Merge "Show password policy flags on Special:PasswordPolicies"
[lhc/web/wiklou.git] / includes / OutputPage.php
1 <?php
2 /**
3 * Preparation for the final page rendering.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 use MediaWiki\Linker\LinkTarget;
24 use MediaWiki\MediaWikiServices;
25 use MediaWiki\Session\SessionManager;
26 use Wikimedia\Rdbms\IResultWrapper;
27 use Wikimedia\RelPath;
28 use Wikimedia\WrappedString;
29 use Wikimedia\WrappedStringList;
30
31 /**
32 * This class should be covered by a general architecture document which does
33 * not exist as of January 2011. This is one of the Core classes and should
34 * be read at least once by any new developers.
35 *
36 * This class is used to prepare the final rendering. A skin is then
37 * applied to the output parameters (links, javascript, html, categories ...).
38 *
39 * @todo FIXME: Another class handles sending the whole page to the client.
40 *
41 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
42 * in November 2010.
43 *
44 * @todo document
45 */
46 class OutputPage extends ContextSource {
47 /** @var array Should be private. Used with addMeta() which adds "<meta>" */
48 protected $mMetatags = [];
49
50 /** @var array */
51 protected $mLinktags = [];
52
53 /** @var bool */
54 protected $mCanonicalUrl = false;
55
56 /**
57 * @var string The contents of <h1> */
58 private $mPageTitle = '';
59
60 /**
61 * @var string The displayed title of the page. Different from page title
62 * if overridden by display title magic word or hooks. Can contain safe
63 * HTML. Different from page title which may contain messages such as
64 * "Editing X" which is displayed in h1. This can be used for other places
65 * where the page name is referred on the page.
66 */
67 private $displayTitle;
68
69 /**
70 * @var string Contains all of the "<body>" content. Should be private we
71 * got set/get accessors and the append() method.
72 */
73 public $mBodytext = '';
74
75 /** @var string Stores contents of "<title>" tag */
76 private $mHTMLtitle = '';
77
78 /**
79 * @var bool Is the displayed content related to the source of the
80 * corresponding wiki article.
81 */
82 private $mIsArticle = false;
83
84 /** @var bool Stores "article flag" toggle. */
85 private $mIsArticleRelated = true;
86
87 /** @var bool Is the content subject to copyright */
88 private $mHasCopyright = false;
89
90 /**
91 * @var bool We have to set isPrintable(). Some pages should
92 * never be printed (ex: redirections).
93 */
94 private $mPrintable = false;
95
96 /**
97 * @var array Contains the page subtitle. Special pages usually have some
98 * links here. Don't confuse with site subtitle added by skins.
99 */
100 private $mSubtitle = [];
101
102 /** @var string */
103 public $mRedirect = '';
104
105 /** @var int */
106 protected $mStatusCode;
107
108 /**
109 * @var string Used for sending cache control.
110 * The whole caching system should probably be moved into its own class.
111 */
112 protected $mLastModified = '';
113
114 /** @var array */
115 protected $mCategoryLinks = [];
116
117 /** @var array */
118 protected $mCategories = [
119 'hidden' => [],
120 'normal' => [],
121 ];
122
123 /** @var array */
124 protected $mIndicators = [];
125
126 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
127 private $mLanguageLinks = [];
128
129 /**
130 * Used for JavaScript (predates ResourceLoader)
131 * @todo We should split JS / CSS.
132 * mScripts content is inserted as is in "<head>" by Skin. This might
133 * contain either a link to a stylesheet or inline CSS.
134 */
135 private $mScripts = '';
136
137 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
138 protected $mInlineStyles = '';
139
140 /**
141 * @var string Used by skin template.
142 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
143 */
144 public $mPageLinkTitle = '';
145
146 /** @var array Array of elements in "<head>". Parser might add its own headers! */
147 protected $mHeadItems = [];
148
149 /** @var array Additional <body> classes; there are also <body> classes from other sources */
150 protected $mAdditionalBodyClasses = [];
151
152 /** @var array */
153 protected $mModules = [];
154
155 /** @var array */
156 protected $mModuleScripts = [];
157
158 /** @var array */
159 protected $mModuleStyles = [];
160
161 /** @var ResourceLoader */
162 protected $mResourceLoader;
163
164 /** @var ResourceLoaderClientHtml */
165 private $rlClient;
166
167 /** @var ResourceLoaderContext */
168 private $rlClientContext;
169
170 /** @var array */
171 private $rlExemptStyleModules;
172
173 /** @var array */
174 protected $mJsConfigVars = [];
175
176 /** @var array */
177 protected $mTemplateIds = [];
178
179 /** @var array */
180 protected $mImageTimeKeys = [];
181
182 /** @var string */
183 public $mRedirectCode = '';
184
185 protected $mFeedLinksAppendQuery = null;
186
187 /** @var array
188 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
189 * @see ResourceLoaderModule::$origin
190 * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
191 */
192 protected $mAllowedModules = [
193 ResourceLoaderModule::TYPE_COMBINED => ResourceLoaderModule::ORIGIN_ALL,
194 ];
195
196 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
197 protected $mDoNothing = false;
198
199 // Parser related.
200
201 /** @var int */
202 protected $mContainsNewMagic = 0;
203
204 /**
205 * lazy initialised, use parserOptions()
206 * @var ParserOptions
207 */
208 protected $mParserOptions = null;
209
210 /**
211 * Handles the Atom / RSS links.
212 * We probably only support Atom in 2011.
213 * @see $wgAdvertisedFeedTypes
214 */
215 private $mFeedLinks = [];
216
217 // Gwicke work on squid caching? Roughly from 2003.
218 protected $mEnableClientCache = true;
219
220 /** @var bool Flag if output should only contain the body of the article. */
221 private $mArticleBodyOnly = false;
222
223 /** @var bool */
224 protected $mNewSectionLink = false;
225
226 /** @var bool */
227 protected $mHideNewSectionLink = false;
228
229 /**
230 * @var bool Comes from the parser. This was probably made to load CSS/JS
231 * only if we had "<gallery>". Used directly in CategoryPage.php.
232 * Looks like ResourceLoader can replace this.
233 */
234 public $mNoGallery = false;
235
236 /** @var int Cache stuff. Looks like mEnableClientCache */
237 protected $mCdnMaxage = 0;
238 /** @var int Upper limit on mCdnMaxage */
239 protected $mCdnMaxageLimit = INF;
240
241 /**
242 * @var bool Controls if anti-clickjacking / frame-breaking headers will
243 * be sent. This should be done for pages where edit actions are possible.
244 * Setters: $this->preventClickjacking() and $this->allowClickjacking().
245 */
246 protected $mPreventClickjacking = true;
247
248 /** @var int To include the variable {{REVISIONID}} */
249 private $mRevisionId = null;
250
251 /** @var string */
252 private $mRevisionTimestamp = null;
253
254 /** @var array */
255 protected $mFileVersion = null;
256
257 /**
258 * @var array An array of stylesheet filenames (relative from skins path),
259 * with options for CSS media, IE conditions, and RTL/LTR direction.
260 * For internal use; add settings in the skin via $this->addStyle()
261 *
262 * Style again! This seems like a code duplication since we already have
263 * mStyles. This is what makes Open Source amazing.
264 */
265 protected $styles = [];
266
267 private $mIndexPolicy = 'index';
268 private $mFollowPolicy = 'follow';
269
270 /**
271 * @var array Headers that cause the cache to vary. Key is header name, value is an array of
272 * options for the Key header.
273 */
274 private $mVaryHeader = [
275 'Accept-Encoding' => [ 'match=gzip' ],
276 ];
277
278 /**
279 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
280 * of the redirect.
281 *
282 * @var Title
283 */
284 private $mRedirectedFrom = null;
285
286 /**
287 * Additional key => value data
288 */
289 private $mProperties = [];
290
291 /**
292 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
293 */
294 private $mTarget = null;
295
296 /**
297 * @var bool Whether parser output contains a table of contents
298 */
299 private $mEnableTOC = false;
300
301 /**
302 * @var string|null The URL to send in a <link> element with rel=license
303 */
304 private $copyrightUrl;
305
306 /** @var array Profiling data */
307 private $limitReportJSData = [];
308
309 /** @var array Map Title to Content */
310 private $contentOverrides = [];
311
312 /** @var callable[] */
313 private $contentOverrideCallbacks = [];
314
315 /**
316 * Link: header contents
317 */
318 private $mLinkHeader = [];
319
320 /**
321 * @var string The nonce for Content-Security-Policy
322 */
323 private $CSPNonce;
324
325 /**
326 * @var array A cache of the names of the cookies that will influence the cache
327 */
328 private static $cacheVaryCookies = null;
329
330 /**
331 * Constructor for OutputPage. This should not be called directly.
332 * Instead a new RequestContext should be created and it will implicitly create
333 * a OutputPage tied to that context.
334 * @param IContextSource $context
335 */
336 function __construct( IContextSource $context ) {
337 $this->setContext( $context );
338 }
339
340 /**
341 * Redirect to $url rather than displaying the normal page
342 *
343 * @param string $url
344 * @param string $responsecode HTTP status code
345 */
346 public function redirect( $url, $responsecode = '302' ) {
347 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
348 $this->mRedirect = str_replace( "\n", '', $url );
349 $this->mRedirectCode = $responsecode;
350 }
351
352 /**
353 * Get the URL to redirect to, or an empty string if not redirect URL set
354 *
355 * @return string
356 */
357 public function getRedirect() {
358 return $this->mRedirect;
359 }
360
361 /**
362 * Set the copyright URL to send with the output.
363 * Empty string to omit, null to reset.
364 *
365 * @since 1.26
366 *
367 * @param string|null $url
368 */
369 public function setCopyrightUrl( $url ) {
370 $this->copyrightUrl = $url;
371 }
372
373 /**
374 * Set the HTTP status code to send with the output.
375 *
376 * @param int $statusCode
377 */
378 public function setStatusCode( $statusCode ) {
379 $this->mStatusCode = $statusCode;
380 }
381
382 /**
383 * Add a new "<meta>" tag
384 * To add an http-equiv meta tag, precede the name with "http:"
385 *
386 * @param string $name Name of the meta tag
387 * @param string $val Value of the meta tag
388 */
389 function addMeta( $name, $val ) {
390 array_push( $this->mMetatags, [ $name, $val ] );
391 }
392
393 /**
394 * Returns the current <meta> tags
395 *
396 * @since 1.25
397 * @return array
398 */
399 public function getMetaTags() {
400 return $this->mMetatags;
401 }
402
403 /**
404 * Add a new \<link\> tag to the page header.
405 *
406 * Note: use setCanonicalUrl() for rel=canonical.
407 *
408 * @param array $linkarr Associative array of attributes.
409 */
410 function addLink( array $linkarr ) {
411 array_push( $this->mLinktags, $linkarr );
412 }
413
414 /**
415 * Returns the current <link> tags
416 *
417 * @since 1.25
418 * @return array
419 */
420 public function getLinkTags() {
421 return $this->mLinktags;
422 }
423
424 /**
425 * Set the URL to be used for the <link rel=canonical>. This should be used
426 * in preference to addLink(), to avoid duplicate link tags.
427 * @param string $url
428 */
429 function setCanonicalUrl( $url ) {
430 $this->mCanonicalUrl = $url;
431 }
432
433 /**
434 * Returns the URL to be used for the <link rel=canonical> if
435 * one is set.
436 *
437 * @since 1.25
438 * @return bool|string
439 */
440 public function getCanonicalUrl() {
441 return $this->mCanonicalUrl;
442 }
443
444 /**
445 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
446 * Internal use only. Use OutputPage::addModules() or OutputPage::addJsConfigVars()
447 * if possible.
448 *
449 * @param string $script Raw HTML
450 */
451 function addScript( $script ) {
452 $this->mScripts .= $script;
453 }
454
455 /**
456 * Add a JavaScript file to be loaded as `<script>` on this page.
457 *
458 * Internal use only. Use OutputPage::addModules() if possible.
459 *
460 * @param string $file URL to file (absolute path, protocol-relative, or full url)
461 * @param string|null $unused Previously used to change the cache-busting query parameter
462 */
463 public function addScriptFile( $file, $unused = null ) {
464 if ( substr( $file, 0, 1 ) !== '/' && !preg_match( '#^[a-z]*://#i', $file ) ) {
465 // This is not an absolute path, protocol-relative url, or full scheme url,
466 // presumed to be an old call intended to include a file from /w/skins/common,
467 // which doesn't exist anymore as of MediaWiki 1.24 per T71277. Ignore.
468 wfDeprecated( __METHOD__, '1.24' );
469 return;
470 }
471 $this->addScript( Html::linkedScript( $file, $this->getCSPNonce() ) );
472 }
473
474 /**
475 * Add a self-contained script tag with the given contents
476 * Internal use only. Use OutputPage::addModules() if possible.
477 *
478 * @param string $script JavaScript text, no script tags
479 */
480 public function addInlineScript( $script ) {
481 $this->mScripts .= Html::inlineScript( "\n$script\n", $this->getCSPNonce() ) . "\n";
482 }
483
484 /**
485 * Filter an array of modules to remove insufficiently trustworthy members, and modules
486 * which are no longer registered (eg a page is cached before an extension is disabled)
487 * @param array $modules
488 * @param string|null $position Unused
489 * @param string $type
490 * @return array
491 */
492 protected function filterModules( array $modules, $position = null,
493 $type = ResourceLoaderModule::TYPE_COMBINED
494 ) {
495 $resourceLoader = $this->getResourceLoader();
496 $filteredModules = [];
497 foreach ( $modules as $val ) {
498 $module = $resourceLoader->getModule( $val );
499 if ( $module instanceof ResourceLoaderModule
500 && $module->getOrigin() <= $this->getAllowedModules( $type )
501 ) {
502 if ( $this->mTarget && !in_array( $this->mTarget, $module->getTargets() ) ) {
503 $this->warnModuleTargetFilter( $module->getName() );
504 continue;
505 }
506 $filteredModules[] = $val;
507 }
508 }
509 return $filteredModules;
510 }
511
512 private function warnModuleTargetFilter( $moduleName ) {
513 static $warnings = [];
514 if ( isset( $warnings[$this->mTarget][$moduleName] ) ) {
515 return;
516 }
517 $warnings[$this->mTarget][$moduleName] = true;
518 $this->getResourceLoader()->getLogger()->debug(
519 'Module "{module}" not loadable on target "{target}".',
520 [
521 'module' => $moduleName,
522 'target' => $this->mTarget,
523 ]
524 );
525 }
526
527 /**
528 * Get the list of modules to include on this page
529 *
530 * @param bool $filter Whether to filter out insufficiently trustworthy modules
531 * @param string|null $position Unused
532 * @param string $param
533 * @param string $type
534 * @return array Array of module names
535 */
536 public function getModules( $filter = false, $position = null, $param = 'mModules',
537 $type = ResourceLoaderModule::TYPE_COMBINED
538 ) {
539 $modules = array_values( array_unique( $this->$param ) );
540 return $filter
541 ? $this->filterModules( $modules, null, $type )
542 : $modules;
543 }
544
545 /**
546 * Load one or more ResourceLoader modules on this page.
547 *
548 * @param string|array $modules Module name (string) or array of module names
549 */
550 public function addModules( $modules ) {
551 $this->mModules = array_merge( $this->mModules, (array)$modules );
552 }
553
554 /**
555 * Get the list of script-only modules to load on this page.
556 *
557 * @param bool $filter
558 * @param string|null $position Unused
559 * @return array Array of module names
560 */
561 public function getModuleScripts( $filter = false, $position = null ) {
562 return $this->getModules( $filter, null, 'mModuleScripts',
563 ResourceLoaderModule::TYPE_SCRIPTS
564 );
565 }
566
567 /**
568 * Load the scripts of one or more ResourceLoader modules, on this page.
569 *
570 * This method exists purely to provide the legacy behaviour of loading
571 * a module's scripts in the global scope, and without dependency resolution.
572 * See <https://phabricator.wikimedia.org/T188689>.
573 *
574 * @deprecated since 1.31 Use addModules() instead.
575 * @param string|array $modules Module name (string) or array of module names
576 */
577 public function addModuleScripts( $modules ) {
578 $this->mModuleScripts = array_merge( $this->mModuleScripts, (array)$modules );
579 }
580
581 /**
582 * Get the list of style-only modules to load on this page.
583 *
584 * @param bool $filter
585 * @param string|null $position Unused
586 * @return array Array of module names
587 */
588 public function getModuleStyles( $filter = false, $position = null ) {
589 return $this->getModules( $filter, null, 'mModuleStyles',
590 ResourceLoaderModule::TYPE_STYLES
591 );
592 }
593
594 /**
595 * Load the styles of one or more ResourceLoader modules on this page.
596 *
597 * Module styles added through this function will be loaded as a stylesheet,
598 * using a standard `<link rel=stylesheet>` HTML tag, rather than as a combined
599 * Javascript and CSS package. Thus, they will even load when JavaScript is disabled.
600 *
601 * @param string|array $modules Module name (string) or array of module names
602 */
603 public function addModuleStyles( $modules ) {
604 $this->mModuleStyles = array_merge( $this->mModuleStyles, (array)$modules );
605 }
606
607 /**
608 * @return null|string ResourceLoader target
609 */
610 public function getTarget() {
611 return $this->mTarget;
612 }
613
614 /**
615 * Sets ResourceLoader target for load.php links. If null, will be omitted
616 *
617 * @param string|null $target
618 */
619 public function setTarget( $target ) {
620 $this->mTarget = $target;
621 }
622
623 /**
624 * Add a mapping from a LinkTarget to a Content, for things like page preview.
625 * @see self::addContentOverrideCallback()
626 * @since 1.32
627 * @param LinkTarget $target
628 * @param Content $content
629 */
630 public function addContentOverride( LinkTarget $target, Content $content ) {
631 if ( !$this->contentOverrides ) {
632 // Register a callback for $this->contentOverrides on the first call
633 $this->addContentOverrideCallback( function ( LinkTarget $target ) {
634 $key = $target->getNamespace() . ':' . $target->getDBkey();
635 return $this->contentOverrides[$key] ?? null;
636 } );
637 }
638
639 $key = $target->getNamespace() . ':' . $target->getDBkey();
640 $this->contentOverrides[$key] = $content;
641 }
642
643 /**
644 * Add a callback for mapping from a Title to a Content object, for things
645 * like page preview.
646 * @see ResourceLoaderContext::getContentOverrideCallback()
647 * @since 1.32
648 * @param callable $callback
649 */
650 public function addContentOverrideCallback( callable $callback ) {
651 $this->contentOverrideCallbacks[] = $callback;
652 }
653
654 /**
655 * Get an array of head items
656 *
657 * @return array
658 */
659 function getHeadItemsArray() {
660 return $this->mHeadItems;
661 }
662
663 /**
664 * Add or replace a head item to the output
665 *
666 * Whenever possible, use more specific options like ResourceLoader modules,
667 * OutputPage::addLink(), OutputPage::addMetaLink() and OutputPage::addFeedLink()
668 * Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
669 * OutputPage::addInlineScript() and OutputPage::addInlineStyle()
670 * This would be your very LAST fallback.
671 *
672 * @param string $name Item name
673 * @param string $value Raw HTML
674 */
675 public function addHeadItem( $name, $value ) {
676 $this->mHeadItems[$name] = $value;
677 }
678
679 /**
680 * Add one or more head items to the output
681 *
682 * @since 1.28
683 * @param string|string[] $values Raw HTML
684 */
685 public function addHeadItems( $values ) {
686 $this->mHeadItems = array_merge( $this->mHeadItems, (array)$values );
687 }
688
689 /**
690 * Check if the header item $name is already set
691 *
692 * @param string $name Item name
693 * @return bool
694 */
695 public function hasHeadItem( $name ) {
696 return isset( $this->mHeadItems[$name] );
697 }
698
699 /**
700 * Add a class to the <body> element
701 *
702 * @since 1.30
703 * @param string|string[] $classes One or more classes to add
704 */
705 public function addBodyClasses( $classes ) {
706 $this->mAdditionalBodyClasses = array_merge( $this->mAdditionalBodyClasses, (array)$classes );
707 }
708
709 /**
710 * Set whether the output should only contain the body of the article,
711 * without any skin, sidebar, etc.
712 * Used e.g. when calling with "action=render".
713 *
714 * @param bool $only Whether to output only the body of the article
715 */
716 public function setArticleBodyOnly( $only ) {
717 $this->mArticleBodyOnly = $only;
718 }
719
720 /**
721 * Return whether the output will contain only the body of the article
722 *
723 * @return bool
724 */
725 public function getArticleBodyOnly() {
726 return $this->mArticleBodyOnly;
727 }
728
729 /**
730 * Set an additional output property
731 * @since 1.21
732 *
733 * @param string $name
734 * @param mixed $value
735 */
736 public function setProperty( $name, $value ) {
737 $this->mProperties[$name] = $value;
738 }
739
740 /**
741 * Get an additional output property
742 * @since 1.21
743 *
744 * @param string $name
745 * @return mixed Property value or null if not found
746 */
747 public function getProperty( $name ) {
748 return $this->mProperties[$name] ?? null;
749 }
750
751 /**
752 * checkLastModified tells the client to use the client-cached page if
753 * possible. If successful, the OutputPage is disabled so that
754 * any future call to OutputPage->output() have no effect.
755 *
756 * Side effect: sets mLastModified for Last-Modified header
757 *
758 * @param string $timestamp
759 *
760 * @return bool True if cache-ok headers was sent.
761 */
762 public function checkLastModified( $timestamp ) {
763 if ( !$timestamp || $timestamp == '19700101000000' ) {
764 wfDebug( __METHOD__ . ": CACHE DISABLED, NO TIMESTAMP\n" );
765 return false;
766 }
767 $config = $this->getConfig();
768 if ( !$config->get( 'CachePages' ) ) {
769 wfDebug( __METHOD__ . ": CACHE DISABLED\n" );
770 return false;
771 }
772
773 $timestamp = wfTimestamp( TS_MW, $timestamp );
774 $modifiedTimes = [
775 'page' => $timestamp,
776 'user' => $this->getUser()->getTouched(),
777 'epoch' => $config->get( 'CacheEpoch' )
778 ];
779 if ( $config->get( 'UseSquid' ) ) {
780 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW, $this->getCdnCacheEpoch(
781 time(),
782 $config->get( 'SquidMaxage' )
783 ) );
784 }
785 Hooks::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this ] );
786
787 $maxModified = max( $modifiedTimes );
788 $this->mLastModified = wfTimestamp( TS_RFC2822, $maxModified );
789
790 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
791 if ( $clientHeader === false ) {
792 wfDebug( __METHOD__ . ": client did not send If-Modified-Since header", 'private' );
793 return false;
794 }
795
796 # IE sends sizes after the date like this:
797 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
798 # this breaks strtotime().
799 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
800
801 Wikimedia\suppressWarnings(); // E_STRICT system time warnings
802 $clientHeaderTime = strtotime( $clientHeader );
803 Wikimedia\restoreWarnings();
804 if ( !$clientHeaderTime ) {
805 wfDebug( __METHOD__
806 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
807 return false;
808 }
809 $clientHeaderTime = wfTimestamp( TS_MW, $clientHeaderTime );
810
811 # Make debug info
812 $info = '';
813 foreach ( $modifiedTimes as $name => $value ) {
814 if ( $info !== '' ) {
815 $info .= ', ';
816 }
817 $info .= "$name=" . wfTimestamp( TS_ISO_8601, $value );
818 }
819
820 wfDebug( __METHOD__ . ": client sent If-Modified-Since: " .
821 wfTimestamp( TS_ISO_8601, $clientHeaderTime ), 'private' );
822 wfDebug( __METHOD__ . ": effective Last-Modified: " .
823 wfTimestamp( TS_ISO_8601, $maxModified ), 'private' );
824 if ( $clientHeaderTime < $maxModified ) {
825 wfDebug( __METHOD__ . ": STALE, $info", 'private' );
826 return false;
827 }
828
829 # Not modified
830 # Give a 304 Not Modified response code and disable body output
831 wfDebug( __METHOD__ . ": NOT MODIFIED, $info", 'private' );
832 ini_set( 'zlib.output_compression', 0 );
833 $this->getRequest()->response()->statusHeader( 304 );
834 $this->sendCacheControl();
835 $this->disable();
836
837 // Don't output a compressed blob when using ob_gzhandler;
838 // it's technically against HTTP spec and seems to confuse
839 // Firefox when the response gets split over two packets.
840 wfClearOutputBuffers();
841
842 return true;
843 }
844
845 /**
846 * @param int $reqTime Time of request (eg. now)
847 * @param int $maxAge Cache TTL in seconds
848 * @return int Timestamp
849 */
850 private function getCdnCacheEpoch( $reqTime, $maxAge ) {
851 // Ensure Last-Modified is never more than (wgSquidMaxage) in the past,
852 // because even if the wiki page content hasn't changed since, static
853 // resources may have changed (skin HTML, interface messages, urls, etc.)
854 // and must roll-over in a timely manner (T46570)
855 return $reqTime - $maxAge;
856 }
857
858 /**
859 * Override the last modified timestamp
860 *
861 * @param string $timestamp New timestamp, in a format readable by
862 * wfTimestamp()
863 */
864 public function setLastModified( $timestamp ) {
865 $this->mLastModified = wfTimestamp( TS_RFC2822, $timestamp );
866 }
867
868 /**
869 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
870 *
871 * @param string $policy The literal string to output as the contents of
872 * the meta tag. Will be parsed according to the spec and output in
873 * standardized form.
874 * @return null
875 */
876 public function setRobotPolicy( $policy ) {
877 $policy = Article::formatRobotPolicy( $policy );
878
879 if ( isset( $policy['index'] ) ) {
880 $this->setIndexPolicy( $policy['index'] );
881 }
882 if ( isset( $policy['follow'] ) ) {
883 $this->setFollowPolicy( $policy['follow'] );
884 }
885 }
886
887 /**
888 * Set the index policy for the page, but leave the follow policy un-
889 * touched.
890 *
891 * @param string $policy Either 'index' or 'noindex'.
892 * @return null
893 */
894 public function setIndexPolicy( $policy ) {
895 $policy = trim( $policy );
896 if ( in_array( $policy, [ 'index', 'noindex' ] ) ) {
897 $this->mIndexPolicy = $policy;
898 }
899 }
900
901 /**
902 * Set the follow policy for the page, but leave the index policy un-
903 * touched.
904 *
905 * @param string $policy Either 'follow' or 'nofollow'.
906 * @return null
907 */
908 public function setFollowPolicy( $policy ) {
909 $policy = trim( $policy );
910 if ( in_array( $policy, [ 'follow', 'nofollow' ] ) ) {
911 $this->mFollowPolicy = $policy;
912 }
913 }
914
915 /**
916 * "HTML title" means the contents of "<title>".
917 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
918 *
919 * @param string|Message $name
920 */
921 public function setHTMLTitle( $name ) {
922 if ( $name instanceof Message ) {
923 $this->mHTMLtitle = $name->setContext( $this->getContext() )->text();
924 } else {
925 $this->mHTMLtitle = $name;
926 }
927 }
928
929 /**
930 * Return the "HTML title", i.e. the content of the "<title>" tag.
931 *
932 * @return string
933 */
934 public function getHTMLTitle() {
935 return $this->mHTMLtitle;
936 }
937
938 /**
939 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
940 *
941 * @param Title $t
942 */
943 public function setRedirectedFrom( $t ) {
944 $this->mRedirectedFrom = $t;
945 }
946
947 /**
948 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
949 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
950 * but not bad tags like \<script\>. This function automatically sets
951 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
952 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
953 * good tags like \<i\> will be dropped entirely.
954 *
955 * @param string|Message $name
956 */
957 public function setPageTitle( $name ) {
958 if ( $name instanceof Message ) {
959 $name = $name->setContext( $this->getContext() )->text();
960 }
961
962 # change "<script>foo&bar</script>" to "&lt;script&gt;foo&amp;bar&lt;/script&gt;"
963 # but leave "<i>foobar</i>" alone
964 $nameWithTags = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags( $name ) );
965 $this->mPageTitle = $nameWithTags;
966
967 # change "<i>foo&amp;bar</i>" to "foo&bar"
968 $this->setHTMLTitle(
969 $this->msg( 'pagetitle' )->rawParams( Sanitizer::stripAllTags( $nameWithTags ) )
970 ->inContentLanguage()
971 );
972 }
973
974 /**
975 * Return the "page title", i.e. the content of the \<h1\> tag.
976 *
977 * @return string
978 */
979 public function getPageTitle() {
980 return $this->mPageTitle;
981 }
982
983 /**
984 * Same as page title but only contains name of the page, not any other text.
985 *
986 * @since 1.32
987 * @param string $html Page title text.
988 * @see OutputPage::setPageTitle
989 */
990 public function setDisplayTitle( $html ) {
991 $this->displayTitle = $html;
992 }
993
994 /**
995 * Returns page display title.
996 *
997 * Performs some normalization, but this not as strict the magic word.
998 *
999 * @since 1.32
1000 * @return string HTML
1001 */
1002 public function getDisplayTitle() {
1003 $html = $this->displayTitle;
1004 if ( $html === null ) {
1005 $html = $this->getTitle()->getPrefixedText();
1006 }
1007
1008 return Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags( $html ) );
1009 }
1010
1011 /**
1012 * Returns page display title without namespace prefix if possible.
1013 *
1014 * @since 1.32
1015 * @return string HTML
1016 */
1017 public function getUnprefixedDisplayTitle() {
1018 $text = $this->getDisplayTitle();
1019 $nsPrefix = $this->getTitle()->getNsText() . ':';
1020 $prefix = preg_quote( $nsPrefix, '/' );
1021
1022 return preg_replace( "/^$prefix/i", '', $text );
1023 }
1024
1025 /**
1026 * Set the Title object to use
1027 *
1028 * @param Title $t
1029 */
1030 public function setTitle( Title $t ) {
1031 $this->getContext()->setTitle( $t );
1032 }
1033
1034 /**
1035 * Replace the subtitle with $str
1036 *
1037 * @param string|Message $str New value of the subtitle. String should be safe HTML.
1038 */
1039 public function setSubtitle( $str ) {
1040 $this->clearSubtitle();
1041 $this->addSubtitle( $str );
1042 }
1043
1044 /**
1045 * Add $str to the subtitle
1046 *
1047 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
1048 */
1049 public function addSubtitle( $str ) {
1050 if ( $str instanceof Message ) {
1051 $this->mSubtitle[] = $str->setContext( $this->getContext() )->parse();
1052 } else {
1053 $this->mSubtitle[] = $str;
1054 }
1055 }
1056
1057 /**
1058 * Build message object for a subtitle containing a backlink to a page
1059 *
1060 * @param Title $title Title to link to
1061 * @param array $query Array of additional parameters to include in the link
1062 * @return Message
1063 * @since 1.25
1064 */
1065 public static function buildBacklinkSubtitle( Title $title, $query = [] ) {
1066 if ( $title->isRedirect() ) {
1067 $query['redirect'] = 'no';
1068 }
1069 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
1070 return wfMessage( 'backlinksubtitle' )
1071 ->rawParams( $linkRenderer->makeLink( $title, null, [], $query ) );
1072 }
1073
1074 /**
1075 * Add a subtitle containing a backlink to a page
1076 *
1077 * @param Title $title Title to link to
1078 * @param array $query Array of additional parameters to include in the link
1079 */
1080 public function addBacklinkSubtitle( Title $title, $query = [] ) {
1081 $this->addSubtitle( self::buildBacklinkSubtitle( $title, $query ) );
1082 }
1083
1084 /**
1085 * Clear the subtitles
1086 */
1087 public function clearSubtitle() {
1088 $this->mSubtitle = [];
1089 }
1090
1091 /**
1092 * Get the subtitle
1093 *
1094 * @return string
1095 */
1096 public function getSubtitle() {
1097 return implode( "<br />\n\t\t\t\t", $this->mSubtitle );
1098 }
1099
1100 /**
1101 * Set the page as printable, i.e. it'll be displayed with all
1102 * print styles included
1103 */
1104 public function setPrintable() {
1105 $this->mPrintable = true;
1106 }
1107
1108 /**
1109 * Return whether the page is "printable"
1110 *
1111 * @return bool
1112 */
1113 public function isPrintable() {
1114 return $this->mPrintable;
1115 }
1116
1117 /**
1118 * Disable output completely, i.e. calling output() will have no effect
1119 */
1120 public function disable() {
1121 $this->mDoNothing = true;
1122 }
1123
1124 /**
1125 * Return whether the output will be completely disabled
1126 *
1127 * @return bool
1128 */
1129 public function isDisabled() {
1130 return $this->mDoNothing;
1131 }
1132
1133 /**
1134 * Show an "add new section" link?
1135 *
1136 * @return bool
1137 */
1138 public function showNewSectionLink() {
1139 return $this->mNewSectionLink;
1140 }
1141
1142 /**
1143 * Forcibly hide the new section link?
1144 *
1145 * @return bool
1146 */
1147 public function forceHideNewSectionLink() {
1148 return $this->mHideNewSectionLink;
1149 }
1150
1151 /**
1152 * Add or remove feed links in the page header
1153 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1154 * for the new version
1155 * @see addFeedLink()
1156 *
1157 * @param bool $show True: add default feeds, false: remove all feeds
1158 */
1159 public function setSyndicated( $show = true ) {
1160 if ( $show ) {
1161 $this->setFeedAppendQuery( false );
1162 } else {
1163 $this->mFeedLinks = [];
1164 }
1165 }
1166
1167 /**
1168 * Add default feeds to the page header
1169 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1170 * for the new version
1171 * @see addFeedLink()
1172 *
1173 * @param string $val Query to append to feed links or false to output
1174 * default links
1175 */
1176 public function setFeedAppendQuery( $val ) {
1177 $this->mFeedLinks = [];
1178
1179 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1180 $query = "feed=$type";
1181 if ( is_string( $val ) ) {
1182 $query .= '&' . $val;
1183 }
1184 $this->mFeedLinks[$type] = $this->getTitle()->getLocalURL( $query );
1185 }
1186 }
1187
1188 /**
1189 * Add a feed link to the page header
1190 *
1191 * @param string $format Feed type, should be a key of $wgFeedClasses
1192 * @param string $href URL
1193 */
1194 public function addFeedLink( $format, $href ) {
1195 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1196 $this->mFeedLinks[$format] = $href;
1197 }
1198 }
1199
1200 /**
1201 * Should we output feed links for this page?
1202 * @return bool
1203 */
1204 public function isSyndicated() {
1205 return count( $this->mFeedLinks ) > 0;
1206 }
1207
1208 /**
1209 * Return URLs for each supported syndication format for this page.
1210 * @return array Associating format keys with URLs
1211 */
1212 public function getSyndicationLinks() {
1213 return $this->mFeedLinks;
1214 }
1215
1216 /**
1217 * Will currently always return null
1218 *
1219 * @return null
1220 */
1221 public function getFeedAppendQuery() {
1222 return $this->mFeedLinksAppendQuery;
1223 }
1224
1225 /**
1226 * Set whether the displayed content is related to the source of the
1227 * corresponding article on the wiki
1228 * Setting true will cause the change "article related" toggle to true
1229 *
1230 * @param bool $newVal
1231 */
1232 public function setArticleFlag( $newVal ) {
1233 $this->mIsArticle = $newVal;
1234 if ( $newVal ) {
1235 $this->mIsArticleRelated = $newVal;
1236 }
1237 }
1238
1239 /**
1240 * Return whether the content displayed page is related to the source of
1241 * the corresponding article on the wiki
1242 *
1243 * @return bool
1244 */
1245 public function isArticle() {
1246 return $this->mIsArticle;
1247 }
1248
1249 /**
1250 * Set whether this page is related an article on the wiki
1251 * Setting false will cause the change of "article flag" toggle to false
1252 *
1253 * @param bool $newVal
1254 */
1255 public function setArticleRelated( $newVal ) {
1256 $this->mIsArticleRelated = $newVal;
1257 if ( !$newVal ) {
1258 $this->mIsArticle = false;
1259 }
1260 }
1261
1262 /**
1263 * Return whether this page is related an article on the wiki
1264 *
1265 * @return bool
1266 */
1267 public function isArticleRelated() {
1268 return $this->mIsArticleRelated;
1269 }
1270
1271 /**
1272 * Set whether the standard copyright should be shown for the current page.
1273 *
1274 * @param bool $hasCopyright
1275 */
1276 public function setCopyright( $hasCopyright ) {
1277 $this->mHasCopyright = $hasCopyright;
1278 }
1279
1280 /**
1281 * Return whether the standard copyright should be shown for the current page.
1282 * By default, it is true for all articles but other pages
1283 * can signal it by using setCopyright( true ).
1284 *
1285 * Used by SkinTemplate to decided whether to show the copyright.
1286 *
1287 * @return bool
1288 */
1289 public function showsCopyright() {
1290 return $this->isArticle() || $this->mHasCopyright;
1291 }
1292
1293 /**
1294 * Add new language links
1295 *
1296 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1297 * (e.g. 'fr:Test page')
1298 */
1299 public function addLanguageLinks( array $newLinkArray ) {
1300 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $newLinkArray );
1301 }
1302
1303 /**
1304 * Reset the language links and add new language links
1305 *
1306 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1307 * (e.g. 'fr:Test page')
1308 */
1309 public function setLanguageLinks( array $newLinkArray ) {
1310 $this->mLanguageLinks = $newLinkArray;
1311 }
1312
1313 /**
1314 * Get the list of language links
1315 *
1316 * @return string[] Array of interwiki-prefixed (non DB key) titles (e.g. 'fr:Test page')
1317 */
1318 public function getLanguageLinks() {
1319 return $this->mLanguageLinks;
1320 }
1321
1322 /**
1323 * Add an array of categories, with names in the keys
1324 *
1325 * @param array $categories Mapping category name => sort key
1326 */
1327 public function addCategoryLinks( array $categories ) {
1328 if ( !$categories ) {
1329 return;
1330 }
1331
1332 $res = $this->addCategoryLinksToLBAndGetResult( $categories );
1333
1334 # Set all the values to 'normal'.
1335 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1336
1337 # Mark hidden categories
1338 foreach ( $res as $row ) {
1339 if ( isset( $row->pp_value ) ) {
1340 $categories[$row->page_title] = 'hidden';
1341 }
1342 }
1343
1344 // Avoid PHP 7.1 warning of passing $this by reference
1345 $outputPage = $this;
1346 # Add the remaining categories to the skin
1347 if ( Hooks::run(
1348 'OutputPageMakeCategoryLinks',
1349 [ &$outputPage, $categories, &$this->mCategoryLinks ] )
1350 ) {
1351 $services = MediaWikiServices::getInstance();
1352 $linkRenderer = $services->getLinkRenderer();
1353 foreach ( $categories as $category => $type ) {
1354 // array keys will cast numeric category names to ints, so cast back to string
1355 $category = (string)$category;
1356 $origcategory = $category;
1357 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
1358 if ( !$title ) {
1359 continue;
1360 }
1361 $services->getContentLanguage()->findVariantLink( $category, $title, true );
1362 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1363 continue;
1364 }
1365 $text = $services->getContentLanguage()->convertHtml( $title->getText() );
1366 $this->mCategories[$type][] = $title->getText();
1367 $this->mCategoryLinks[$type][] = $linkRenderer->makeLink( $title, new HtmlArmor( $text ) );
1368 }
1369 }
1370 }
1371
1372 /**
1373 * @param array $categories
1374 * @return bool|IResultWrapper
1375 */
1376 protected function addCategoryLinksToLBAndGetResult( array $categories ) {
1377 # Add the links to a LinkBatch
1378 $arr = [ NS_CATEGORY => $categories ];
1379 $lb = new LinkBatch;
1380 $lb->setArray( $arr );
1381
1382 # Fetch existence plus the hiddencat property
1383 $dbr = wfGetDB( DB_REPLICA );
1384 $fields = array_merge(
1385 LinkCache::getSelectFields(),
1386 [ 'page_namespace', 'page_title', 'pp_value' ]
1387 );
1388
1389 $res = $dbr->select( [ 'page', 'page_props' ],
1390 $fields,
1391 $lb->constructSet( 'page', $dbr ),
1392 __METHOD__,
1393 [],
1394 [ 'page_props' => [ 'LEFT JOIN', [
1395 'pp_propname' => 'hiddencat',
1396 'pp_page = page_id'
1397 ] ] ]
1398 );
1399
1400 # Add the results to the link cache
1401 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
1402 $lb->addResultToCache( $linkCache, $res );
1403
1404 return $res;
1405 }
1406
1407 /**
1408 * Reset the category links (but not the category list) and add $categories
1409 *
1410 * @param array $categories Mapping category name => sort key
1411 */
1412 public function setCategoryLinks( array $categories ) {
1413 $this->mCategoryLinks = [];
1414 $this->addCategoryLinks( $categories );
1415 }
1416
1417 /**
1418 * Get the list of category links, in a 2-D array with the following format:
1419 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1420 * hidden categories) and $link a HTML fragment with a link to the category
1421 * page
1422 *
1423 * @return array
1424 */
1425 public function getCategoryLinks() {
1426 return $this->mCategoryLinks;
1427 }
1428
1429 /**
1430 * Get the list of category names this page belongs to.
1431 *
1432 * @param string $type The type of categories which should be returned. Possible values:
1433 * * all: all categories of all types
1434 * * hidden: only the hidden categories
1435 * * normal: all categories, except hidden categories
1436 * @return array Array of strings
1437 */
1438 public function getCategories( $type = 'all' ) {
1439 if ( $type === 'all' ) {
1440 $allCategories = [];
1441 foreach ( $this->mCategories as $categories ) {
1442 $allCategories = array_merge( $allCategories, $categories );
1443 }
1444 return $allCategories;
1445 }
1446 if ( !isset( $this->mCategories[$type] ) ) {
1447 throw new InvalidArgumentException( 'Invalid category type given: ' . $type );
1448 }
1449 return $this->mCategories[$type];
1450 }
1451
1452 /**
1453 * Add an array of indicators, with their identifiers as array
1454 * keys and HTML contents as values.
1455 *
1456 * In case of duplicate keys, existing values are overwritten.
1457 *
1458 * @param array $indicators
1459 * @since 1.25
1460 */
1461 public function setIndicators( array $indicators ) {
1462 $this->mIndicators = $indicators + $this->mIndicators;
1463 // Keep ordered by key
1464 ksort( $this->mIndicators );
1465 }
1466
1467 /**
1468 * Get the indicators associated with this page.
1469 *
1470 * The array will be internally ordered by item keys.
1471 *
1472 * @return array Keys: identifiers, values: HTML contents
1473 * @since 1.25
1474 */
1475 public function getIndicators() {
1476 return $this->mIndicators;
1477 }
1478
1479 /**
1480 * Adds help link with an icon via page indicators.
1481 * Link target can be overridden by a local message containing a wikilink:
1482 * the message key is: lowercase action or special page name + '-helppage'.
1483 * @param string $to Target MediaWiki.org page title or encoded URL.
1484 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1485 * @since 1.25
1486 */
1487 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1488 $this->addModuleStyles( 'mediawiki.helplink' );
1489 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1490
1491 if ( $overrideBaseUrl ) {
1492 $helpUrl = $to;
1493 } else {
1494 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1495 $helpUrl = "//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1496 }
1497
1498 $link = Html::rawElement(
1499 'a',
1500 [
1501 'href' => $helpUrl,
1502 'target' => '_blank',
1503 'class' => 'mw-helplink',
1504 ],
1505 $text
1506 );
1507
1508 $this->setIndicators( [ 'mw-helplink' => $link ] );
1509 }
1510
1511 /**
1512 * Do not allow scripts which can be modified by wiki users to load on this page;
1513 * only allow scripts bundled with, or generated by, the software.
1514 * Site-wide styles are controlled by a config setting, since they can be
1515 * used to create a custom skin/theme, but not user-specific ones.
1516 *
1517 * @todo this should be given a more accurate name
1518 */
1519 public function disallowUserJs() {
1520 $this->reduceAllowedModules(
1521 ResourceLoaderModule::TYPE_SCRIPTS,
1522 ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL
1523 );
1524
1525 // Site-wide styles are controlled by a config setting, see T73621
1526 // for background on why. User styles are never allowed.
1527 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1528 $styleOrigin = ResourceLoaderModule::ORIGIN_USER_SITEWIDE;
1529 } else {
1530 $styleOrigin = ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL;
1531 }
1532 $this->reduceAllowedModules(
1533 ResourceLoaderModule::TYPE_STYLES,
1534 $styleOrigin
1535 );
1536 }
1537
1538 /**
1539 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1540 * @see ResourceLoaderModule::$origin
1541 * @param string $type ResourceLoaderModule TYPE_ constant
1542 * @return int ResourceLoaderModule ORIGIN_ class constant
1543 */
1544 public function getAllowedModules( $type ) {
1545 if ( $type == ResourceLoaderModule::TYPE_COMBINED ) {
1546 return min( array_values( $this->mAllowedModules ) );
1547 } else {
1548 return $this->mAllowedModules[$type] ?? ResourceLoaderModule::ORIGIN_ALL;
1549 }
1550 }
1551
1552 /**
1553 * Limit the highest level of CSS/JS untrustworthiness allowed.
1554 *
1555 * If passed the same or a higher level than the current level of untrustworthiness set, the
1556 * level will remain unchanged.
1557 *
1558 * @param string $type
1559 * @param int $level ResourceLoaderModule class constant
1560 */
1561 public function reduceAllowedModules( $type, $level ) {
1562 $this->mAllowedModules[$type] = min( $this->getAllowedModules( $type ), $level );
1563 }
1564
1565 /**
1566 * Prepend $text to the body HTML
1567 *
1568 * @param string $text HTML
1569 */
1570 public function prependHTML( $text ) {
1571 $this->mBodytext = $text . $this->mBodytext;
1572 }
1573
1574 /**
1575 * Append $text to the body HTML
1576 *
1577 * @param string $text HTML
1578 */
1579 public function addHTML( $text ) {
1580 $this->mBodytext .= $text;
1581 }
1582
1583 /**
1584 * Shortcut for adding an Html::element via addHTML.
1585 *
1586 * @since 1.19
1587 *
1588 * @param string $element
1589 * @param array $attribs
1590 * @param string $contents
1591 */
1592 public function addElement( $element, array $attribs = [], $contents = '' ) {
1593 $this->addHTML( Html::element( $element, $attribs, $contents ) );
1594 }
1595
1596 /**
1597 * Clear the body HTML
1598 */
1599 public function clearHTML() {
1600 $this->mBodytext = '';
1601 }
1602
1603 /**
1604 * Get the body HTML
1605 *
1606 * @return string HTML
1607 */
1608 public function getHTML() {
1609 return $this->mBodytext;
1610 }
1611
1612 /**
1613 * Get/set the ParserOptions object to use for wikitext parsing
1614 *
1615 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1616 * current ParserOption object. This parameter is deprecated since 1.31.
1617 * @return ParserOptions
1618 */
1619 public function parserOptions( $options = null ) {
1620 if ( $options !== null ) {
1621 wfDeprecated( __METHOD__ . ' with non-null $options', '1.31' );
1622 }
1623
1624 if ( $options !== null && !empty( $options->isBogus ) ) {
1625 // Someone is trying to set a bogus pre-$wgUser PO. Check if it has
1626 // been changed somehow, and keep it if so.
1627 $anonPO = ParserOptions::newFromAnon();
1628 $anonPO->setAllowUnsafeRawHtml( false );
1629 if ( !$options->matches( $anonPO ) ) {
1630 wfLogWarning( __METHOD__ . ': Setting a changed bogus ParserOptions: ' . wfGetAllCallers( 5 ) );
1631 $options->isBogus = false;
1632 }
1633 }
1634
1635 if ( !$this->mParserOptions ) {
1636 if ( !$this->getContext()->getUser()->isSafeToLoad() ) {
1637 // $wgUser isn't unstubbable yet, so don't try to get a
1638 // ParserOptions for it. And don't cache this ParserOptions
1639 // either.
1640 $po = ParserOptions::newFromAnon();
1641 $po->setAllowUnsafeRawHtml( false );
1642 $po->isBogus = true;
1643 if ( $options !== null ) {
1644 $this->mParserOptions = empty( $options->isBogus ) ? $options : null;
1645 }
1646 return $po;
1647 }
1648
1649 $this->mParserOptions = ParserOptions::newFromContext( $this->getContext() );
1650 $this->mParserOptions->setAllowUnsafeRawHtml( false );
1651 }
1652
1653 if ( $options !== null && !empty( $options->isBogus ) ) {
1654 // They're trying to restore the bogus pre-$wgUser PO. Do the right
1655 // thing.
1656 return wfSetVar( $this->mParserOptions, null, true );
1657 } else {
1658 return wfSetVar( $this->mParserOptions, $options );
1659 }
1660 }
1661
1662 /**
1663 * Set the revision ID which will be seen by the wiki text parser
1664 * for things such as embedded {{REVISIONID}} variable use.
1665 *
1666 * @param int|null $revid A positive integer, or null
1667 * @return mixed Previous value
1668 */
1669 public function setRevisionId( $revid ) {
1670 $val = is_null( $revid ) ? null : intval( $revid );
1671 return wfSetVar( $this->mRevisionId, $val, true );
1672 }
1673
1674 /**
1675 * Get the displayed revision ID
1676 *
1677 * @return int
1678 */
1679 public function getRevisionId() {
1680 return $this->mRevisionId;
1681 }
1682
1683 /**
1684 * Set the timestamp of the revision which will be displayed. This is used
1685 * to avoid a extra DB call in Skin::lastModified().
1686 *
1687 * @param string|null $timestamp
1688 * @return mixed Previous value
1689 */
1690 public function setRevisionTimestamp( $timestamp ) {
1691 return wfSetVar( $this->mRevisionTimestamp, $timestamp, true );
1692 }
1693
1694 /**
1695 * Get the timestamp of displayed revision.
1696 * This will be null if not filled by setRevisionTimestamp().
1697 *
1698 * @return string|null
1699 */
1700 public function getRevisionTimestamp() {
1701 return $this->mRevisionTimestamp;
1702 }
1703
1704 /**
1705 * Set the displayed file version
1706 *
1707 * @param File|null $file
1708 * @return mixed Previous value
1709 */
1710 public function setFileVersion( $file ) {
1711 $val = null;
1712 if ( $file instanceof File && $file->exists() ) {
1713 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1714 }
1715 return wfSetVar( $this->mFileVersion, $val, true );
1716 }
1717
1718 /**
1719 * Get the displayed file version
1720 *
1721 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1722 */
1723 public function getFileVersion() {
1724 return $this->mFileVersion;
1725 }
1726
1727 /**
1728 * Get the templates used on this page
1729 *
1730 * @return array (namespace => dbKey => revId)
1731 * @since 1.18
1732 */
1733 public function getTemplateIds() {
1734 return $this->mTemplateIds;
1735 }
1736
1737 /**
1738 * Get the files used on this page
1739 *
1740 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1741 * @since 1.18
1742 */
1743 public function getFileSearchOptions() {
1744 return $this->mImageTimeKeys;
1745 }
1746
1747 /**
1748 * Convert wikitext to HTML and add it to the buffer
1749 * Default assumes that the current page title will be used.
1750 *
1751 * @param string $text
1752 * @param bool $linestart Is this the start of a line?
1753 * @param bool $interface Is this text in the user interface language?
1754 * @throws MWException
1755 * @deprecated since 1.32 due to untidy output; use
1756 * addWikiTextAsInterface() if $interface is default value or true,
1757 * or else addWikiTextAsContent() if $interface is false.
1758 */
1759 public function addWikiText( $text, $linestart = true, $interface = true ) {
1760 wfDeprecated( __METHOD__, '1.32' );
1761 $title = $this->getTitle();
1762 if ( !$title ) {
1763 throw new MWException( 'Title is null' );
1764 }
1765 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*tidy*/false, $interface );
1766 }
1767
1768 /**
1769 * Convert wikitext *in the user interface language* to HTML and
1770 * add it to the buffer. The result will not be
1771 * language-converted, as user interface messages are already
1772 * localized into a specific variant. Assumes that the current
1773 * page title will be used if optional $title is not
1774 * provided. Output will be tidy.
1775 *
1776 * @param string $text Wikitext in the user interface language
1777 * @param bool $linestart Is this the start of a line? (Defaults to true)
1778 * @param Title|null $title Optional title to use; default of `null`
1779 * means use current page title.
1780 * @throws MWException if $title is not provided and OutputPage::getTitle()
1781 * is null
1782 * @since 1.32
1783 */
1784 public function addWikiTextAsInterface(
1785 $text, $linestart = true, Title $title = null
1786 ) {
1787 if ( $title === null ) {
1788 $title = $this->getTitle();
1789 }
1790 if ( !$title ) {
1791 throw new MWException( 'Title is null' );
1792 }
1793 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*tidy*/true, /*interface*/true );
1794 }
1795
1796 /**
1797 * Convert wikitext *in the user interface language* to HTML and
1798 * add it to the buffer with a `<div class="$wrapperClass">`
1799 * wrapper. The result will not be language-converted, as user
1800 * interface messages as already localized into a specific
1801 * variant. The $text will be parsed in start-of-line context.
1802 * Output will be tidy.
1803 *
1804 * @param string $wrapperClass The class attribute value for the <div>
1805 * wrapper in the output HTML
1806 * @param string $text Wikitext in the user interface language
1807 * @since 1.32
1808 */
1809 public function wrapWikiTextAsInterface(
1810 $wrapperClass, $text
1811 ) {
1812 $this->addWikiTextTitleInternal(
1813 $text, $this->getTitle(),
1814 /*linestart*/true, /*tidy*/true, /*interface*/true,
1815 $wrapperClass
1816 );
1817 }
1818
1819 /**
1820 * Convert wikitext *in the page content language* to HTML and add
1821 * it to the buffer. The result with be language-converted to the
1822 * user's preferred variant. Assumes that the current page title
1823 * will be used if optional $title is not provided. Output will be
1824 * tidy.
1825 *
1826 * @param string $text Wikitext in the page content language
1827 * @param bool $linestart Is this the start of a line? (Defaults to true)
1828 * @param Title|null $title Optional title to use; default of `null`
1829 * means use current page title.
1830 * @throws MWException if $title is not provided and OutputPage::getTitle()
1831 * is null
1832 * @since 1.32
1833 */
1834 public function addWikiTextAsContent(
1835 $text, $linestart = true, Title $title = null
1836 ) {
1837 if ( $title === null ) {
1838 $title = $this->getTitle();
1839 }
1840 if ( !$title ) {
1841 throw new MWException( 'Title is null' );
1842 }
1843 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*tidy*/true, /*interface*/false );
1844 }
1845
1846 /**
1847 * Add wikitext with a custom Title object
1848 *
1849 * @param string $text Wikitext
1850 * @param Title $title
1851 * @param bool $linestart Is this the start of a line?
1852 * @deprecated since 1.32 due to untidy output; use
1853 * addWikiTextAsInterface()
1854 */
1855 public function addWikiTextWithTitle( $text, Title $title, $linestart = true ) {
1856 wfDeprecated( __METHOD__, '1.32' );
1857 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*tidy*/false, /*interface*/false );
1858 }
1859
1860 /**
1861 * Add wikitext *in content language* with a custom Title object.
1862 * Output will be tidy.
1863 *
1864 * @param string $text Wikitext in content language
1865 * @param Title $title
1866 * @param bool $linestart Is this the start of a line?
1867 * @deprecated since 1.32 to rename methods consistently; use
1868 * addWikiTextAsContent()
1869 */
1870 function addWikiTextTitleTidy( $text, Title $title, $linestart = true ) {
1871 wfDeprecated( __METHOD__, '1.32' );
1872 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*tidy*/true, /*interface*/false );
1873 }
1874
1875 /**
1876 * Add wikitext *in content language*. Output will be tidy.
1877 *
1878 * @param string $text Wikitext in content language
1879 * @param bool $linestart Is this the start of a line?
1880 * @deprecated since 1.32 to rename methods consistently; use
1881 * addWikiTextAsContent()
1882 */
1883 public function addWikiTextTidy( $text, $linestart = true ) {
1884 wfDeprecated( __METHOD__, '1.32' );
1885 $title = $this->getTitle();
1886 if ( !$title ) {
1887 throw new MWException( 'Title is null' );
1888 }
1889 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*tidy*/true, /*interface*/false );
1890 }
1891
1892 /**
1893 * Add wikitext with a custom Title object.
1894 * Output is unwrapped.
1895 *
1896 * @param string $text Wikitext
1897 * @param Title $title
1898 * @param bool $linestart Is this the start of a line?
1899 * @param bool $tidy Whether to use tidy.
1900 * Setting this to false (or omitting it) is deprecated
1901 * since 1.32; all wikitext should be tidied.
1902 * For backwards-compatibility with prior MW releases,
1903 * you may wish to invoke this method but set $tidy=true;
1904 * this will result in equivalent output to the non-deprecated
1905 * addWikiTextAsContent()/addWikiTextAsInterface() methods.
1906 * @param bool $interface Whether it is an interface message
1907 * (for example disables conversion)
1908 * @deprecated since 1.32, use addWikiTextAsContent() or
1909 * addWikiTextAsInterface() (depending on $interface)
1910 */
1911 public function addWikiTextTitle( $text, Title $title, $linestart,
1912 $tidy = false, $interface = false
1913 ) {
1914 wfDeprecated( __METHOD__, '1.32' );
1915 return $this->addWikiTextTitleInternal( $text, $title, $linestart, $tidy, $interface );
1916 }
1917
1918 /**
1919 * Add wikitext with a custom Title object.
1920 * Output is unwrapped.
1921 *
1922 * @param string $text Wikitext
1923 * @param Title $title
1924 * @param bool $linestart Is this the start of a line?
1925 * @param bool $tidy Whether to use tidy.
1926 * Setting this to false (or omitting it) is deprecated
1927 * since 1.32; all wikitext should be tidied.
1928 * @param bool $interface Whether it is an interface message
1929 * (for example disables conversion)
1930 * @param string $wrapperClass if not empty, wraps the output in
1931 * a `<div class="$wrapperClass">`
1932 * @private
1933 */
1934 private function addWikiTextTitleInternal(
1935 $text, Title $title, $linestart, $tidy, $interface, $wrapperClass = null
1936 ) {
1937 if ( !$tidy ) {
1938 wfDeprecated( 'disabling tidy', '1.32' );
1939 }
1940
1941 $parserOutput = $this->parseInternal(
1942 $text, $title, $linestart, $tidy, $interface, /*language*/null
1943 );
1944
1945 $this->addParserOutput( $parserOutput, [
1946 'enableSectionEditLinks' => false,
1947 'wrapperDivClass' => $wrapperClass ?? '',
1948 ] );
1949 }
1950
1951 /**
1952 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1953 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1954 * and so on.
1955 *
1956 * @since 1.24
1957 * @param ParserOutput $parserOutput
1958 */
1959 public function addParserOutputMetadata( ParserOutput $parserOutput ) {
1960 $this->mLanguageLinks =
1961 array_merge( $this->mLanguageLinks, $parserOutput->getLanguageLinks() );
1962 $this->addCategoryLinks( $parserOutput->getCategories() );
1963 $this->setIndicators( $parserOutput->getIndicators() );
1964 $this->mNewSectionLink = $parserOutput->getNewSection();
1965 $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
1966
1967 if ( !$parserOutput->isCacheable() ) {
1968 $this->enableClientCache( false );
1969 }
1970 $this->mNoGallery = $parserOutput->getNoGallery();
1971 $this->mHeadItems = array_merge( $this->mHeadItems, $parserOutput->getHeadItems() );
1972 $this->addModules( $parserOutput->getModules() );
1973 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1974 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1975 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1976 $this->mPreventClickjacking = $this->mPreventClickjacking
1977 || $parserOutput->preventClickjacking();
1978
1979 // Template versioning...
1980 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1981 if ( isset( $this->mTemplateIds[$ns] ) ) {
1982 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
1983 } else {
1984 $this->mTemplateIds[$ns] = $dbks;
1985 }
1986 }
1987 // File versioning...
1988 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1989 $this->mImageTimeKeys[$dbk] = $data;
1990 }
1991
1992 // Hooks registered in the object
1993 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1994 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1995 list( $hookName, $data ) = $hookInfo;
1996 if ( isset( $parserOutputHooks[$hookName] ) ) {
1997 $parserOutputHooks[$hookName]( $this, $parserOutput, $data );
1998 }
1999 }
2000
2001 // Enable OOUI if requested via ParserOutput
2002 if ( $parserOutput->getEnableOOUI() ) {
2003 $this->enableOOUI();
2004 }
2005
2006 // Include parser limit report
2007 if ( !$this->limitReportJSData ) {
2008 $this->limitReportJSData = $parserOutput->getLimitReportJSData();
2009 }
2010
2011 // Link flags are ignored for now, but may in the future be
2012 // used to mark individual language links.
2013 $linkFlags = [];
2014 // Avoid PHP 7.1 warning of passing $this by reference
2015 $outputPage = $this;
2016 Hooks::run( 'LanguageLinks', [ $this->getTitle(), &$this->mLanguageLinks, &$linkFlags ] );
2017 Hooks::runWithoutAbort( 'OutputPageParserOutput', [ &$outputPage, $parserOutput ] );
2018
2019 // This check must be after 'OutputPageParserOutput' runs in addParserOutputMetadata
2020 // so that extensions may modify ParserOutput to toggle TOC.
2021 // This cannot be moved to addParserOutputText because that is not
2022 // called by EditPage for Preview.
2023 if ( $parserOutput->getTOCHTML() ) {
2024 $this->mEnableTOC = true;
2025 }
2026 }
2027
2028 /**
2029 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
2030 * ParserOutput object, without any other metadata.
2031 *
2032 * @since 1.24
2033 * @param ParserOutput $parserOutput
2034 * @param array $poOptions Options to ParserOutput::getText()
2035 */
2036 public function addParserOutputContent( ParserOutput $parserOutput, $poOptions = [] ) {
2037 $this->addParserOutputText( $parserOutput, $poOptions );
2038
2039 $this->addModules( $parserOutput->getModules() );
2040 $this->addModuleScripts( $parserOutput->getModuleScripts() );
2041 $this->addModuleStyles( $parserOutput->getModuleStyles() );
2042
2043 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
2044 }
2045
2046 /**
2047 * Add the HTML associated with a ParserOutput object, without any metadata.
2048 *
2049 * @since 1.24
2050 * @param ParserOutput $parserOutput
2051 * @param array $poOptions Options to ParserOutput::getText()
2052 */
2053 public function addParserOutputText( ParserOutput $parserOutput, $poOptions = [] ) {
2054 $text = $parserOutput->getText( $poOptions );
2055 // Avoid PHP 7.1 warning of passing $this by reference
2056 $outputPage = $this;
2057 Hooks::runWithoutAbort( 'OutputPageBeforeHTML', [ &$outputPage, &$text ] );
2058 $this->addHTML( $text );
2059 }
2060
2061 /**
2062 * Add everything from a ParserOutput object.
2063 *
2064 * @param ParserOutput $parserOutput
2065 * @param array $poOptions Options to ParserOutput::getText()
2066 */
2067 function addParserOutput( ParserOutput $parserOutput, $poOptions = [] ) {
2068 $this->addParserOutputMetadata( $parserOutput );
2069 $this->addParserOutputText( $parserOutput, $poOptions );
2070 }
2071
2072 /**
2073 * Add the output of a QuickTemplate to the output buffer
2074 *
2075 * @param QuickTemplate &$template
2076 */
2077 public function addTemplate( &$template ) {
2078 $this->addHTML( $template->getHTML() );
2079 }
2080
2081 /**
2082 * Parse wikitext and return the HTML.
2083 *
2084 * @todo The output is wrapped in a <div> iff $interface is false; it's
2085 * probably best to always strip the wrapper.
2086 *
2087 * @param string $text
2088 * @param bool $linestart Is this the start of a line?
2089 * @param bool $interface Use interface language (instead of content language) while parsing
2090 * language sensitive magic words like GRAMMAR and PLURAL. This also disables
2091 * LanguageConverter.
2092 * @param Language|null $language Target language object, will override $interface
2093 * @throws MWException
2094 * @return string HTML
2095 * @deprecated since 1.32, due to untidy output and inconsistent wrapper;
2096 * use parseAsContent() if $interface is default value or false, or else
2097 * parseAsInterface() if $interface is true.
2098 */
2099 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
2100 wfDeprecated( __METHOD__, '1.33' );
2101 return $this->parseInternal(
2102 $text, $this->getTitle(), $linestart, /*tidy*/false, $interface, $language
2103 )->getText( [
2104 'enableSectionEditLinks' => false,
2105 ] );
2106 }
2107
2108 /**
2109 * Parse wikitext *in the page content language* and return the HTML.
2110 * The result will be language-converted to the user's preferred variant.
2111 * Output will be tidy.
2112 *
2113 * @param string $text Wikitext in the page content language
2114 * @param bool $linestart Is this the start of a line? (Defaults to true)
2115 * @throws MWException
2116 * @return string HTML
2117 * @since 1.32
2118 */
2119 public function parseAsContent( $text, $linestart = true ) {
2120 return $this->parseInternal(
2121 $text, $this->getTitle(), $linestart, /*tidy*/true, /*interface*/false, /*language*/null
2122 )->getText( [
2123 'enableSectionEditLinks' => false,
2124 'wrapperDivClass' => ''
2125 ] );
2126 }
2127
2128 /**
2129 * Parse wikitext *in the user interface language* and return the HTML.
2130 * The result will not be language-converted, as user interface messages
2131 * are already localized into a specific variant.
2132 * Output will be tidy.
2133 *
2134 * @param string $text Wikitext in the user interface language
2135 * @param bool $linestart Is this the start of a line? (Defaults to true)
2136 * @throws MWException
2137 * @return string HTML
2138 * @since 1.32
2139 */
2140 public function parseAsInterface( $text, $linestart = true ) {
2141 return $this->parseInternal(
2142 $text, $this->getTitle(), $linestart, /*tidy*/true, /*interface*/true, /*language*/null
2143 )->getText( [
2144 'enableSectionEditLinks' => false,
2145 'wrapperDivClass' => ''
2146 ] );
2147 }
2148
2149 /**
2150 * Parse wikitext *in the user interface language*, strip
2151 * paragraph wrapper, and return the HTML.
2152 * The result will not be language-converted, as user interface messages
2153 * are already localized into a specific variant.
2154 * Output will be tidy. Outer paragraph wrapper will only be stripped
2155 * if the result is a single paragraph.
2156 *
2157 * @param string $text Wikitext in the user interface language
2158 * @param bool $linestart Is this the start of a line? (Defaults to true)
2159 * @throws MWException
2160 * @return string HTML
2161 * @since 1.32
2162 */
2163 public function parseInlineAsInterface( $text, $linestart = true ) {
2164 return Parser::stripOuterParagraph(
2165 $this->parseAsInterface( $text, $linestart )
2166 );
2167 }
2168
2169 /**
2170 * Parse wikitext, strip paragraph wrapper, and return the HTML.
2171 *
2172 * @param string $text
2173 * @param bool $linestart Is this the start of a line?
2174 * @param bool $interface Use interface language (instead of content language) while parsing
2175 * language sensitive magic words like GRAMMAR and PLURAL
2176 * @return string HTML
2177 * @deprecated since 1.32, due to untidy output and confusing default
2178 * for $interface. Use parseInlineAsInterface() if $interface is
2179 * the default value or false, or else use
2180 * Parser::stripOuterParagraph($outputPage->parseAsContent(...)).
2181 */
2182 public function parseInline( $text, $linestart = true, $interface = false ) {
2183 wfDeprecated( __METHOD__, '1.33' );
2184 $parsed = $this->parseInternal(
2185 $text, $this->getTitle(), $linestart, /*tidy*/false, $interface, /*language*/null
2186 )->getText( [
2187 'enableSectionEditLinks' => false,
2188 'wrapperDivClass' => '', /* no wrapper div */
2189 ] );
2190 return Parser::stripOuterParagraph( $parsed );
2191 }
2192
2193 /**
2194 * Parse wikitext and return the HTML (internal implementation helper)
2195 *
2196 * @param string $text
2197 * @param Title The title to use
2198 * @param bool $linestart Is this the start of a line?
2199 * @param bool $tidy Whether the output should be tidied
2200 * @param bool $interface Use interface language (instead of content language) while parsing
2201 * language sensitive magic words like GRAMMAR and PLURAL. This also disables
2202 * LanguageConverter.
2203 * @param Language|null $language Target language object, will override $interface
2204 * @throws MWException
2205 * @return ParserOutput
2206 */
2207 private function parseInternal( $text, $title, $linestart, $tidy, $interface, $language ) {
2208 global $wgParser;
2209
2210 if ( is_null( $title ) ) {
2211 throw new MWException( 'Empty $mTitle in ' . __METHOD__ );
2212 }
2213
2214 $popts = $this->parserOptions();
2215 $oldTidy = $popts->setTidy( $tidy );
2216 $oldInterface = $popts->setInterfaceMessage( (bool)$interface );
2217
2218 if ( $language !== null ) {
2219 $oldLang = $popts->setTargetLanguage( $language );
2220 }
2221
2222 $parserOutput = $wgParser->getFreshParser()->parse(
2223 $text, $title, $popts,
2224 $linestart, true, $this->mRevisionId
2225 );
2226
2227 $popts->setTidy( $oldTidy );
2228 $popts->setInterfaceMessage( $oldInterface );
2229
2230 if ( $language !== null ) {
2231 $popts->setTargetLanguage( $oldLang );
2232 }
2233
2234 return $parserOutput;
2235 }
2236
2237 /**
2238 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
2239 *
2240 * @param int $maxage Maximum cache time on the CDN, in seconds.
2241 */
2242 public function setCdnMaxage( $maxage ) {
2243 $this->mCdnMaxage = min( $maxage, $this->mCdnMaxageLimit );
2244 }
2245
2246 /**
2247 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header to $maxage if that is
2248 * lower than the current s-maxage. Either way, $maxage is now an upper limit on s-maxage, so
2249 * that future calls to setCdnMaxage() will no longer be able to raise the s-maxage above
2250 * $maxage.
2251 *
2252 * @param int $maxage Maximum cache time on the CDN, in seconds
2253 * @since 1.27
2254 */
2255 public function lowerCdnMaxage( $maxage ) {
2256 $this->mCdnMaxageLimit = min( $maxage, $this->mCdnMaxageLimit );
2257 $this->setCdnMaxage( $this->mCdnMaxage );
2258 }
2259
2260 /**
2261 * Get TTL in [$minTTL,$maxTTL] in pass it to lowerCdnMaxage()
2262 *
2263 * This sets and returns $minTTL if $mtime is false or null. Otherwise,
2264 * the TTL is higher the older the $mtime timestamp is. Essentially, the
2265 * TTL is 90% of the age of the object, subject to the min and max.
2266 *
2267 * @param string|int|float|bool|null $mtime Last-Modified timestamp
2268 * @param int $minTTL Minimum TTL in seconds [default: 1 minute]
2269 * @param int $maxTTL Maximum TTL in seconds [default: $wgSquidMaxage]
2270 * @since 1.28
2271 */
2272 public function adaptCdnTTL( $mtime, $minTTL = 0, $maxTTL = 0 ) {
2273 $minTTL = $minTTL ?: IExpiringStore::TTL_MINUTE;
2274 $maxTTL = $maxTTL ?: $this->getConfig()->get( 'SquidMaxage' );
2275
2276 if ( $mtime === null || $mtime === false ) {
2277 return $minTTL; // entity does not exist
2278 }
2279
2280 $age = MWTimestamp::time() - wfTimestamp( TS_UNIX, $mtime );
2281 $adaptiveTTL = max( 0.9 * $age, $minTTL );
2282 $adaptiveTTL = min( $adaptiveTTL, $maxTTL );
2283
2284 $this->lowerCdnMaxage( (int)$adaptiveTTL );
2285 }
2286
2287 /**
2288 * Use enableClientCache(false) to force it to send nocache headers
2289 *
2290 * @param bool|null $state New value, or null to not set the value
2291 *
2292 * @return bool Old value
2293 */
2294 public function enableClientCache( $state ) {
2295 return wfSetVar( $this->mEnableClientCache, $state );
2296 }
2297
2298 /**
2299 * Get the list of cookie names that will influence the cache
2300 *
2301 * @return array
2302 */
2303 function getCacheVaryCookies() {
2304 if ( self::$cacheVaryCookies === null ) {
2305 $config = $this->getConfig();
2306 self::$cacheVaryCookies = array_values( array_unique( array_merge(
2307 SessionManager::singleton()->getVaryCookies(),
2308 [
2309 'forceHTTPS',
2310 ],
2311 $config->get( 'CacheVaryCookies' )
2312 ) ) );
2313 Hooks::run( 'GetCacheVaryCookies', [ $this, &self::$cacheVaryCookies ] );
2314 }
2315 return self::$cacheVaryCookies;
2316 }
2317
2318 /**
2319 * Check if the request has a cache-varying cookie header
2320 * If it does, it's very important that we don't allow public caching
2321 *
2322 * @return bool
2323 */
2324 function haveCacheVaryCookies() {
2325 $request = $this->getRequest();
2326 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2327 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2328 wfDebug( __METHOD__ . ": found $cookieName\n" );
2329 return true;
2330 }
2331 }
2332 wfDebug( __METHOD__ . ": no cache-varying cookies found\n" );
2333 return false;
2334 }
2335
2336 /**
2337 * Add an HTTP header that will influence on the cache
2338 *
2339 * @param string $header Header name
2340 * @param string[]|null $option Options for the Key header. See
2341 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2342 * for the list of valid options.
2343 */
2344 public function addVaryHeader( $header, array $option = null ) {
2345 if ( !array_key_exists( $header, $this->mVaryHeader ) ) {
2346 $this->mVaryHeader[$header] = [];
2347 }
2348 if ( !is_array( $option ) ) {
2349 $option = [];
2350 }
2351 $this->mVaryHeader[$header] =
2352 array_unique( array_merge( $this->mVaryHeader[$header], $option ) );
2353 }
2354
2355 /**
2356 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2357 * such as Accept-Encoding or Cookie
2358 *
2359 * @return string
2360 */
2361 public function getVaryHeader() {
2362 // If we vary on cookies, let's make sure it's always included here too.
2363 if ( $this->getCacheVaryCookies() ) {
2364 $this->addVaryHeader( 'Cookie' );
2365 }
2366
2367 foreach ( SessionManager::singleton()->getVaryHeaders() as $header => $options ) {
2368 $this->addVaryHeader( $header, $options );
2369 }
2370 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader ) );
2371 }
2372
2373 /**
2374 * Add an HTTP Link: header
2375 *
2376 * @param string $header Header value
2377 */
2378 public function addLinkHeader( $header ) {
2379 $this->mLinkHeader[] = $header;
2380 }
2381
2382 /**
2383 * Return a Link: header. Based on the values of $mLinkHeader.
2384 *
2385 * @return string
2386 */
2387 public function getLinkHeader() {
2388 if ( !$this->mLinkHeader ) {
2389 return false;
2390 }
2391
2392 return 'Link: ' . implode( ',', $this->mLinkHeader );
2393 }
2394
2395 /**
2396 * Get a complete Key header
2397 *
2398 * @return string
2399 * @deprecated in 1.32; the IETF spec for this header expired w/o becoming
2400 * a standard.
2401 */
2402 public function getKeyHeader() {
2403 wfDeprecated( '$wgUseKeyHeader', '1.32' );
2404
2405 $cvCookies = $this->getCacheVaryCookies();
2406
2407 $cookiesOption = [];
2408 foreach ( $cvCookies as $cookieName ) {
2409 $cookiesOption[] = 'param=' . $cookieName;
2410 }
2411 $this->addVaryHeader( 'Cookie', $cookiesOption );
2412
2413 foreach ( SessionManager::singleton()->getVaryHeaders() as $header => $options ) {
2414 $this->addVaryHeader( $header, $options );
2415 }
2416
2417 $headers = [];
2418 foreach ( $this->mVaryHeader as $header => $option ) {
2419 $newheader = $header;
2420 if ( is_array( $option ) && count( $option ) > 0 ) {
2421 $newheader .= ';' . implode( ';', $option );
2422 }
2423 $headers[] = $newheader;
2424 }
2425 $key = 'Key: ' . implode( ',', $headers );
2426
2427 return $key;
2428 }
2429
2430 /**
2431 * T23672: Add Accept-Language to Vary and Key headers if there's no 'variant' parameter in GET.
2432 *
2433 * For example:
2434 * /w/index.php?title=Main_page will vary based on Accept-Language; but
2435 * /w/index.php?title=Main_page&variant=zh-cn will not.
2436 */
2437 private function addAcceptLanguage() {
2438 $title = $this->getTitle();
2439 if ( !$title instanceof Title ) {
2440 return;
2441 }
2442
2443 $lang = $title->getPageLanguage();
2444 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2445 $variants = $lang->getVariants();
2446 $aloption = [];
2447 foreach ( $variants as $variant ) {
2448 if ( $variant === $lang->getCode() ) {
2449 continue;
2450 }
2451
2452 // XXX Note that this code is not strictly correct: we
2453 // do a case-insensitive match in
2454 // LanguageConverter::getHeaderVariant() while the
2455 // (abandoned, draft) spec for the `Key` header only
2456 // allows case-sensitive matches. To match the logic
2457 // in LanguageConverter::getHeaderVariant() we should
2458 // also be looking at fallback variants and deprecated
2459 // mediawiki-internal codes, as well as BCP 47
2460 // normalized forms.
2461
2462 $aloption[] = "substr=$variant";
2463
2464 // IE and some other browsers use BCP 47 standards in their Accept-Language header,
2465 // like "zh-CN" or "zh-Hant". We should handle these too.
2466 $variantBCP47 = LanguageCode::bcp47( $variant );
2467 if ( $variantBCP47 !== $variant ) {
2468 $aloption[] = "substr=$variantBCP47";
2469 }
2470 }
2471 $this->addVaryHeader( 'Accept-Language', $aloption );
2472 }
2473 }
2474
2475 /**
2476 * Set a flag which will cause an X-Frame-Options header appropriate for
2477 * edit pages to be sent. The header value is controlled by
2478 * $wgEditPageFrameOptions.
2479 *
2480 * This is the default for special pages. If you display a CSRF-protected
2481 * form on an ordinary view page, then you need to call this function.
2482 *
2483 * @param bool $enable
2484 */
2485 public function preventClickjacking( $enable = true ) {
2486 $this->mPreventClickjacking = $enable;
2487 }
2488
2489 /**
2490 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2491 * This can be called from pages which do not contain any CSRF-protected
2492 * HTML form.
2493 */
2494 public function allowClickjacking() {
2495 $this->mPreventClickjacking = false;
2496 }
2497
2498 /**
2499 * Get the prevent-clickjacking flag
2500 *
2501 * @since 1.24
2502 * @return bool
2503 */
2504 public function getPreventClickjacking() {
2505 return $this->mPreventClickjacking;
2506 }
2507
2508 /**
2509 * Get the X-Frame-Options header value (without the name part), or false
2510 * if there isn't one. This is used by Skin to determine whether to enable
2511 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2512 *
2513 * @return string|false
2514 */
2515 public function getFrameOptions() {
2516 $config = $this->getConfig();
2517 if ( $config->get( 'BreakFrames' ) ) {
2518 return 'DENY';
2519 } elseif ( $this->mPreventClickjacking && $config->get( 'EditPageFrameOptions' ) ) {
2520 return $config->get( 'EditPageFrameOptions' );
2521 }
2522 return false;
2523 }
2524
2525 /**
2526 * Get the Origin-Trial header values. This is used to enable Chrome Origin
2527 * Trials: https://github.com/GoogleChrome/OriginTrials
2528 *
2529 * @return array
2530 */
2531 private function getOriginTrials() {
2532 $config = $this->getConfig();
2533
2534 return $config->get( 'OriginTrials' );
2535 }
2536
2537 /**
2538 * Send cache control HTTP headers
2539 */
2540 public function sendCacheControl() {
2541 $response = $this->getRequest()->response();
2542 $config = $this->getConfig();
2543
2544 $this->addVaryHeader( 'Cookie' );
2545 $this->addAcceptLanguage();
2546
2547 # don't serve compressed data to clients who can't handle it
2548 # maintain different caches for logged-in users and non-logged in ones
2549 $response->header( $this->getVaryHeader() );
2550
2551 if ( $config->get( 'UseKeyHeader' ) ) {
2552 $response->header( $this->getKeyHeader() );
2553 }
2554
2555 if ( $this->mEnableClientCache ) {
2556 if (
2557 $config->get( 'UseSquid' ) &&
2558 !$response->hasCookies() &&
2559 !SessionManager::getGlobalSession()->isPersistent() &&
2560 !$this->isPrintable() &&
2561 $this->mCdnMaxage != 0 &&
2562 !$this->haveCacheVaryCookies()
2563 ) {
2564 if ( $config->get( 'UseESI' ) ) {
2565 wfDeprecated( '$wgUseESI = true', '1.33' );
2566 # We'll purge the proxy cache explicitly, but require end user agents
2567 # to revalidate against the proxy on each visit.
2568 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2569 wfDebug( __METHOD__ .
2570 ": proxy caching with ESI; {$this->mLastModified} **", 'private' );
2571 # start with a shorter timeout for initial testing
2572 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2573 $response->header(
2574 "Surrogate-Control: max-age={$config->get( 'SquidMaxage' )}" .
2575 "+{$this->mCdnMaxage}, content=\"ESI/1.0\""
2576 );
2577 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2578 } else {
2579 # We'll purge the proxy cache for anons explicitly, but require end user agents
2580 # to revalidate against the proxy on each visit.
2581 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2582 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2583 wfDebug( __METHOD__ .
2584 ": local proxy caching; {$this->mLastModified} **", 'private' );
2585 # start with a shorter timeout for initial testing
2586 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2587 $response->header( "Cache-Control: " .
2588 "s-maxage={$this->mCdnMaxage}, must-revalidate, max-age=0" );
2589 }
2590 } else {
2591 # We do want clients to cache if they can, but they *must* check for updates
2592 # on revisiting the page.
2593 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **", 'private' );
2594 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2595 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2596 }
2597 if ( $this->mLastModified ) {
2598 $response->header( "Last-Modified: {$this->mLastModified}" );
2599 }
2600 } else {
2601 wfDebug( __METHOD__ . ": no caching **", 'private' );
2602
2603 # In general, the absence of a last modified header should be enough to prevent
2604 # the client from using its cache. We send a few other things just to make sure.
2605 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2606 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2607 $response->header( 'Pragma: no-cache' );
2608 }
2609 }
2610
2611 /**
2612 * Transfer styles and JavaScript modules from skin.
2613 *
2614 * @param Skin $sk to load modules for
2615 */
2616 public function loadSkinModules( $sk ) {
2617 foreach ( $sk->getDefaultModules() as $group => $modules ) {
2618 if ( $group === 'styles' ) {
2619 foreach ( $modules as $key => $moduleMembers ) {
2620 $this->addModuleStyles( $moduleMembers );
2621 }
2622 } else {
2623 $this->addModules( $modules );
2624 }
2625 }
2626 }
2627
2628 /**
2629 * Finally, all the text has been munged and accumulated into
2630 * the object, let's actually output it:
2631 *
2632 * @param bool $return Set to true to get the result as a string rather than sending it
2633 * @return string|null
2634 * @throws Exception
2635 * @throws FatalError
2636 * @throws MWException
2637 */
2638 public function output( $return = false ) {
2639 if ( $this->mDoNothing ) {
2640 return $return ? '' : null;
2641 }
2642
2643 $response = $this->getRequest()->response();
2644 $config = $this->getConfig();
2645
2646 if ( $this->mRedirect != '' ) {
2647 # Standards require redirect URLs to be absolute
2648 $this->mRedirect = wfExpandUrl( $this->mRedirect, PROTO_CURRENT );
2649
2650 $redirect = $this->mRedirect;
2651 $code = $this->mRedirectCode;
2652
2653 if ( Hooks::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2654 if ( $code == '301' || $code == '303' ) {
2655 if ( !$config->get( 'DebugRedirects' ) ) {
2656 $response->statusHeader( $code );
2657 }
2658 $this->mLastModified = wfTimestamp( TS_RFC2822 );
2659 }
2660 if ( $config->get( 'VaryOnXFP' ) ) {
2661 $this->addVaryHeader( 'X-Forwarded-Proto' );
2662 }
2663 $this->sendCacheControl();
2664
2665 $response->header( "Content-Type: text/html; charset=utf-8" );
2666 if ( $config->get( 'DebugRedirects' ) ) {
2667 $url = htmlspecialchars( $redirect );
2668 print "<!DOCTYPE html>\n<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2669 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2670 print "</body>\n</html>\n";
2671 } else {
2672 $response->header( 'Location: ' . $redirect );
2673 }
2674 }
2675
2676 return $return ? '' : null;
2677 } elseif ( $this->mStatusCode ) {
2678 $response->statusHeader( $this->mStatusCode );
2679 }
2680
2681 # Buffer output; final headers may depend on later processing
2682 ob_start();
2683
2684 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2685 $response->header( 'Content-language: ' .
2686 MediaWikiServices::getInstance()->getContentLanguage()->getHtmlCode() );
2687
2688 if ( !$this->mArticleBodyOnly ) {
2689 $sk = $this->getSkin();
2690 }
2691
2692 $linkHeader = $this->getLinkHeader();
2693 if ( $linkHeader ) {
2694 $response->header( $linkHeader );
2695 }
2696
2697 // Prevent framing, if requested
2698 $frameOptions = $this->getFrameOptions();
2699 if ( $frameOptions ) {
2700 $response->header( "X-Frame-Options: $frameOptions" );
2701 }
2702
2703 $originTrials = $this->getOriginTrials();
2704 foreach ( $originTrials as $originTrial ) {
2705 $response->header( "Origin-Trial: $originTrial", false );
2706 }
2707
2708 ContentSecurityPolicy::sendHeaders( $this );
2709
2710 if ( $this->mArticleBodyOnly ) {
2711 echo $this->mBodytext;
2712 } else {
2713 // Enable safe mode if requested (T152169)
2714 if ( $this->getRequest()->getBool( 'safemode' ) ) {
2715 $this->disallowUserJs();
2716 }
2717
2718 $sk = $this->getSkin();
2719 $this->loadSkinModules( $sk );
2720
2721 MWDebug::addModules( $this );
2722
2723 // Avoid PHP 7.1 warning of passing $this by reference
2724 $outputPage = $this;
2725 // Hook that allows last minute changes to the output page, e.g.
2726 // adding of CSS or Javascript by extensions.
2727 Hooks::runWithoutAbort( 'BeforePageDisplay', [ &$outputPage, &$sk ] );
2728
2729 try {
2730 $sk->outputPage();
2731 } catch ( Exception $e ) {
2732 ob_end_clean(); // bug T129657
2733 throw $e;
2734 }
2735 }
2736
2737 try {
2738 // This hook allows last minute changes to final overall output by modifying output buffer
2739 Hooks::runWithoutAbort( 'AfterFinalPageOutput', [ $this ] );
2740 } catch ( Exception $e ) {
2741 ob_end_clean(); // bug T129657
2742 throw $e;
2743 }
2744
2745 $this->sendCacheControl();
2746
2747 if ( $return ) {
2748 return ob_get_clean();
2749 } else {
2750 ob_end_flush();
2751 return null;
2752 }
2753 }
2754
2755 /**
2756 * Prepare this object to display an error page; disable caching and
2757 * indexing, clear the current text and redirect, set the page's title
2758 * and optionally an custom HTML title (content of the "<title>" tag).
2759 *
2760 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2761 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2762 * optional, if not passed the "<title>" attribute will be
2763 * based on $pageTitle
2764 */
2765 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2766 $this->setPageTitle( $pageTitle );
2767 if ( $htmlTitle !== false ) {
2768 $this->setHTMLTitle( $htmlTitle );
2769 }
2770 $this->setRobotPolicy( 'noindex,nofollow' );
2771 $this->setArticleRelated( false );
2772 $this->enableClientCache( false );
2773 $this->mRedirect = '';
2774 $this->clearSubtitle();
2775 $this->clearHTML();
2776 }
2777
2778 /**
2779 * Output a standard error page
2780 *
2781 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2782 * showErrorPage( 'titlemsg', 'pagetextmsg', [ 'param1', 'param2' ] );
2783 * showErrorPage( 'titlemsg', $messageObject );
2784 * showErrorPage( $titleMessageObject, $messageObject );
2785 *
2786 * @param string|Message $title Message key (string) for page title, or a Message object
2787 * @param string|Message $msg Message key (string) for page text, or a Message object
2788 * @param array $params Message parameters; ignored if $msg is a Message object
2789 */
2790 public function showErrorPage( $title, $msg, $params = [] ) {
2791 if ( !$title instanceof Message ) {
2792 $title = $this->msg( $title );
2793 }
2794
2795 $this->prepareErrorPage( $title );
2796
2797 if ( $msg instanceof Message ) {
2798 if ( $params !== [] ) {
2799 trigger_error( 'Argument ignored: $params. The message parameters argument '
2800 . 'is discarded when the $msg argument is a Message object instead of '
2801 . 'a string.', E_USER_NOTICE );
2802 }
2803 $this->addHTML( $msg->parseAsBlock() );
2804 } else {
2805 $this->addWikiMsgArray( $msg, $params );
2806 }
2807
2808 $this->returnToMain();
2809 }
2810
2811 /**
2812 * Output a standard permission error page
2813 *
2814 * @param array $errors Error message keys or [key, param...] arrays
2815 * @param string|null $action Action that was denied or null if unknown
2816 */
2817 public function showPermissionsErrorPage( array $errors, $action = null ) {
2818 foreach ( $errors as $key => $error ) {
2819 $errors[$key] = (array)$error;
2820 }
2821
2822 // For some action (read, edit, create and upload), display a "login to do this action"
2823 // error if all of the following conditions are met:
2824 // 1. the user is not logged in
2825 // 2. the only error is insufficient permissions (i.e. no block or something else)
2826 // 3. the error can be avoided simply by logging in
2827 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2828 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2829 && ( $errors[0][0] == 'badaccess-groups' || $errors[0][0] == 'badaccess-group0' )
2830 && ( User::groupHasPermission( 'user', $action )
2831 || User::groupHasPermission( 'autoconfirmed', $action ) )
2832 ) {
2833 $displayReturnto = null;
2834
2835 # Due to T34276, if a user does not have read permissions,
2836 # $this->getTitle() will just give Special:Badtitle, which is
2837 # not especially useful as a returnto parameter. Use the title
2838 # from the request instead, if there was one.
2839 $request = $this->getRequest();
2840 $returnto = Title::newFromText( $request->getVal( 'title', '' ) );
2841 if ( $action == 'edit' ) {
2842 $msg = 'whitelistedittext';
2843 $displayReturnto = $returnto;
2844 } elseif ( $action == 'createpage' || $action == 'createtalk' ) {
2845 $msg = 'nocreatetext';
2846 } elseif ( $action == 'upload' ) {
2847 $msg = 'uploadnologintext';
2848 } else { # Read
2849 $msg = 'loginreqpagetext';
2850 $displayReturnto = Title::newMainPage();
2851 }
2852
2853 $query = [];
2854
2855 if ( $returnto ) {
2856 $query['returnto'] = $returnto->getPrefixedText();
2857
2858 if ( !$request->wasPosted() ) {
2859 $returntoquery = $request->getValues();
2860 unset( $returntoquery['title'] );
2861 unset( $returntoquery['returnto'] );
2862 unset( $returntoquery['returntoquery'] );
2863 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2864 }
2865 }
2866 $title = SpecialPage::getTitleFor( 'Userlogin' );
2867 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
2868 $loginUrl = $title->getLinkURL( $query, false, PROTO_RELATIVE );
2869 $loginLink = $linkRenderer->makeKnownLink(
2870 $title,
2871 $this->msg( 'loginreqlink' )->text(),
2872 [],
2873 $query
2874 );
2875
2876 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2877 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->params( $loginUrl )->parse() );
2878
2879 # Don't return to a page the user can't read otherwise
2880 # we'll end up in a pointless loop
2881 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2882 $this->returnToMain( null, $displayReturnto );
2883 }
2884 } else {
2885 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2886 $this->addWikiTextAsInterface( $this->formatPermissionsErrorMessage( $errors, $action ) );
2887 }
2888 }
2889
2890 /**
2891 * Display an error page indicating that a given version of MediaWiki is
2892 * required to use it
2893 *
2894 * @param mixed $version The version of MediaWiki needed to use the page
2895 */
2896 public function versionRequired( $version ) {
2897 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2898
2899 $this->addWikiMsg( 'versionrequiredtext', $version );
2900 $this->returnToMain();
2901 }
2902
2903 /**
2904 * Format a list of error messages
2905 *
2906 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2907 * @param string|null $action Action that was denied or null if unknown
2908 * @return string The wikitext error-messages, formatted into a list.
2909 */
2910 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2911 if ( $action == null ) {
2912 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2913 } else {
2914 $action_desc = $this->msg( "action-$action" )->plain();
2915 $text = $this->msg(
2916 'permissionserrorstext-withaction',
2917 count( $errors ),
2918 $action_desc
2919 )->plain() . "\n\n";
2920 }
2921
2922 if ( count( $errors ) > 1 ) {
2923 $text .= '<ul class="permissions-errors">' . "\n";
2924
2925 foreach ( $errors as $error ) {
2926 $text .= '<li>';
2927 $text .= $this->msg( ...$error )->plain();
2928 $text .= "</li>\n";
2929 }
2930 $text .= '</ul>';
2931 } else {
2932 $text .= "<div class=\"permissions-errors\">\n" .
2933 $this->msg( ...reset( $errors ) )->plain() .
2934 "\n</div>";
2935 }
2936
2937 return $text;
2938 }
2939
2940 /**
2941 * Show a warning about replica DB lag
2942 *
2943 * If the lag is higher than $wgSlaveLagCritical seconds,
2944 * then the warning is a bit more obvious. If the lag is
2945 * lower than $wgSlaveLagWarning, then no warning is shown.
2946 *
2947 * @param int $lag Replica lag
2948 */
2949 public function showLagWarning( $lag ) {
2950 $config = $this->getConfig();
2951 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2952 $lag = floor( $lag ); // floor to avoid nano seconds to display
2953 $message = $lag < $config->get( 'SlaveLagCritical' )
2954 ? 'lag-warn-normal'
2955 : 'lag-warn-high';
2956 $wrap = Html::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2957 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2958 }
2959 }
2960
2961 /**
2962 * Output an error page
2963 *
2964 * @note FatalError exception class provides an alternative.
2965 * @param string $message Error to output. Must be escaped for HTML.
2966 */
2967 public function showFatalError( $message ) {
2968 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2969
2970 $this->addHTML( $message );
2971 }
2972
2973 /**
2974 * @deprecated 1.32 Use OutputPage::showFatalError or throw FatalError instead.
2975 */
2976 public function showUnexpectedValueError( $name, $val ) {
2977 wfDeprecated( __METHOD__, '1.32' );
2978 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->escaped() );
2979 }
2980
2981 /**
2982 * @deprecated 1.32 Use OutputPage::showFatalError or throw FatalError instead.
2983 */
2984 public function showFileCopyError( $old, $new ) {
2985 wfDeprecated( __METHOD__, '1.32' );
2986 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->escaped() );
2987 }
2988
2989 /**
2990 * @deprecated 1.32 Use OutputPage::showFatalError or throw FatalError instead.
2991 */
2992 public function showFileRenameError( $old, $new ) {
2993 wfDeprecated( __METHOD__, '1.32' );
2994 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->escpaed() );
2995 }
2996
2997 /**
2998 * @deprecated 1.32 Use OutputPage::showFatalError or throw FatalError instead.
2999 */
3000 public function showFileDeleteError( $name ) {
3001 wfDeprecated( __METHOD__, '1.32' );
3002 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->escaped() );
3003 }
3004
3005 /**
3006 * @deprecated 1.32 Use OutputPage::showFatalError or throw FatalError instead.
3007 */
3008 public function showFileNotFoundError( $name ) {
3009 wfDeprecated( __METHOD__, '1.32' );
3010 $this->showFatalError( $this->msg( 'filenotfound', $name )->escaped() );
3011 }
3012
3013 /**
3014 * Add a "return to" link pointing to a specified title
3015 *
3016 * @param Title $title Title to link
3017 * @param array $query Query string parameters
3018 * @param string|null $text Text of the link (input is not escaped)
3019 * @param array $options Options array to pass to Linker
3020 */
3021 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
3022 $linkRenderer = MediaWikiServices::getInstance()
3023 ->getLinkRendererFactory()->createFromLegacyOptions( $options );
3024 $link = $this->msg( 'returnto' )->rawParams(
3025 $linkRenderer->makeLink( $title, $text, [], $query ) )->escaped();
3026 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
3027 }
3028
3029 /**
3030 * Add a "return to" link pointing to a specified title,
3031 * or the title indicated in the request, or else the main page
3032 *
3033 * @param mixed|null $unused
3034 * @param Title|string|null $returnto Title or String to return to
3035 * @param string|null $returntoquery Query string for the return to link
3036 */
3037 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
3038 if ( $returnto == null ) {
3039 $returnto = $this->getRequest()->getText( 'returnto' );
3040 }
3041
3042 if ( $returntoquery == null ) {
3043 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
3044 }
3045
3046 if ( $returnto === '' ) {
3047 $returnto = Title::newMainPage();
3048 }
3049
3050 if ( is_object( $returnto ) ) {
3051 $titleObj = $returnto;
3052 } else {
3053 $titleObj = Title::newFromText( $returnto );
3054 }
3055 // We don't want people to return to external interwiki. That
3056 // might potentially be used as part of a phishing scheme
3057 if ( !is_object( $titleObj ) || $titleObj->isExternal() ) {
3058 $titleObj = Title::newMainPage();
3059 }
3060
3061 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
3062 }
3063
3064 private function getRlClientContext() {
3065 if ( !$this->rlClientContext ) {
3066 $query = ResourceLoader::makeLoaderQuery(
3067 [], // modules; not relevant
3068 $this->getLanguage()->getCode(),
3069 $this->getSkin()->getSkinName(),
3070 $this->getUser()->isLoggedIn() ? $this->getUser()->getName() : null,
3071 null, // version; not relevant
3072 ResourceLoader::inDebugMode(),
3073 null, // only; not relevant
3074 $this->isPrintable(),
3075 $this->getRequest()->getBool( 'handheld' )
3076 );
3077 $this->rlClientContext = new ResourceLoaderContext(
3078 $this->getResourceLoader(),
3079 new FauxRequest( $query )
3080 );
3081 if ( $this->contentOverrideCallbacks ) {
3082 $this->rlClientContext = new DerivativeResourceLoaderContext( $this->rlClientContext );
3083 $this->rlClientContext->setContentOverrideCallback( function ( Title $title ) {
3084 foreach ( $this->contentOverrideCallbacks as $callback ) {
3085 $content = $callback( $title );
3086 if ( $content !== null ) {
3087 $text = ContentHandler::getContentText( $content );
3088 if ( strpos( $text, '</script>' ) !== false ) {
3089 // Proactively replace this so that we can display a message
3090 // to the user, instead of letting it go to Html::inlineScript(),
3091 // where it would be considered a server-side issue.
3092 $titleFormatted = $title->getPrefixedText();
3093 $content = new JavaScriptContent(
3094 Xml::encodeJsCall( 'mw.log.error', [
3095 "Cannot preview $titleFormatted due to script-closing tag."
3096 ] )
3097 );
3098 }
3099 return $content;
3100 }
3101 }
3102 return null;
3103 } );
3104 }
3105 }
3106 return $this->rlClientContext;
3107 }
3108
3109 /**
3110 * Call this to freeze the module queue and JS config and create a formatter.
3111 *
3112 * Depending on the Skin, this may get lazy-initialised in either headElement() or
3113 * getBottomScripts(). See SkinTemplate::prepareQuickTemplate(). Calling this too early may
3114 * cause unexpected side-effects since disallowUserJs() may be called at any time to change
3115 * the module filters retroactively. Skins and extension hooks may also add modules until very
3116 * late in the request lifecycle.
3117 *
3118 * @return ResourceLoaderClientHtml
3119 */
3120 public function getRlClient() {
3121 if ( !$this->rlClient ) {
3122 $context = $this->getRlClientContext();
3123 $rl = $this->getResourceLoader();
3124 $this->addModules( [
3125 'user',
3126 'user.options',
3127 'user.tokens',
3128 ] );
3129 $this->addModuleStyles( [
3130 'site.styles',
3131 'noscript',
3132 'user.styles',
3133 ] );
3134 $this->getSkin()->setupSkinUserCss( $this );
3135
3136 // Prepare exempt modules for buildExemptModules()
3137 $exemptGroups = [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ];
3138 $exemptStates = [];
3139 $moduleStyles = $this->getModuleStyles( /*filter*/ true );
3140
3141 // Preload getTitleInfo for isKnownEmpty calls below and in ResourceLoaderClientHtml
3142 // Separate user-specific batch for improved cache-hit ratio.
3143 $userBatch = [ 'user.styles', 'user' ];
3144 $siteBatch = array_diff( $moduleStyles, $userBatch );
3145 $dbr = wfGetDB( DB_REPLICA );
3146 ResourceLoaderWikiModule::preloadTitleInfo( $context, $dbr, $siteBatch );
3147 ResourceLoaderWikiModule::preloadTitleInfo( $context, $dbr, $userBatch );
3148
3149 // Filter out modules handled by buildExemptModules()
3150 $moduleStyles = array_filter( $moduleStyles,
3151 function ( $name ) use ( $rl, $context, &$exemptGroups, &$exemptStates ) {
3152 $module = $rl->getModule( $name );
3153 if ( $module ) {
3154 $group = $module->getGroup();
3155 if ( isset( $exemptGroups[$group] ) ) {
3156 $exemptStates[$name] = 'ready';
3157 if ( !$module->isKnownEmpty( $context ) ) {
3158 // E.g. Don't output empty <styles>
3159 $exemptGroups[$group][] = $name;
3160 }
3161 return false;
3162 }
3163 }
3164 return true;
3165 }
3166 );
3167 $this->rlExemptStyleModules = $exemptGroups;
3168
3169 $rlClient = new ResourceLoaderClientHtml( $context, [
3170 'target' => $this->getTarget(),
3171 'nonce' => $this->getCSPNonce(),
3172 // When 'safemode', disallowUserJs(), or reduceAllowedModules() is used
3173 // to only restrict modules to ORIGIN_CORE (ie. disallow ORIGIN_USER), the list of
3174 // modules enqueud for loading on this page is filtered to just those.
3175 // However, to make sure we also apply the restriction to dynamic dependencies and
3176 // lazy-loaded modules at run-time on the client-side, pass 'safemode' down to the
3177 // StartupModule so that the client-side registry will not contain any restricted
3178 // modules either. (T152169, T185303)
3179 'safemode' => ( $this->getAllowedModules( ResourceLoaderModule::TYPE_COMBINED )
3180 <= ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL
3181 ) ? '1' : null,
3182 ] );
3183 $rlClient->setConfig( $this->getJSVars() );
3184 $rlClient->setModules( $this->getModules( /*filter*/ true ) );
3185 $rlClient->setModuleStyles( $moduleStyles );
3186 $rlClient->setModuleScripts( $this->getModuleScripts( /*filter*/ true ) );
3187 $rlClient->setExemptStates( $exemptStates );
3188 $this->rlClient = $rlClient;
3189 }
3190 return $this->rlClient;
3191 }
3192
3193 /**
3194 * @param Skin $sk The given Skin
3195 * @param bool $includeStyle Unused
3196 * @return string The doctype, opening "<html>", and head element.
3197 */
3198 public function headElement( Skin $sk, $includeStyle = true ) {
3199 $userdir = $this->getLanguage()->getDir();
3200 $sitedir = MediaWikiServices::getInstance()->getContentLanguage()->getDir();
3201
3202 $pieces = [];
3203 $pieces[] = Html::htmlHeader( Sanitizer::mergeAttributes(
3204 $this->getRlClient()->getDocumentAttributes(),
3205 $sk->getHtmlElementAttributes()
3206 ) );
3207 $pieces[] = Html::openElement( 'head' );
3208
3209 if ( $this->getHTMLTitle() == '' ) {
3210 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
3211 }
3212
3213 if ( !Html::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
3214 // Add <meta charset="UTF-8">
3215 // This should be before <title> since it defines the charset used by
3216 // text including the text inside <title>.
3217 // The spec recommends defining XHTML5's charset using the XML declaration
3218 // instead of meta.
3219 // Our XML declaration is output by Html::htmlHeader.
3220 // https://html.spec.whatwg.org/multipage/semantics.html#attr-meta-http-equiv-content-type
3221 // https://html.spec.whatwg.org/multipage/semantics.html#charset
3222 $pieces[] = Html::element( 'meta', [ 'charset' => 'UTF-8' ] );
3223 }
3224
3225 $pieces[] = Html::element( 'title', null, $this->getHTMLTitle() );
3226 $pieces[] = $this->getRlClient()->getHeadHtml();
3227 $pieces[] = $this->buildExemptModules();
3228 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
3229 $pieces = array_merge( $pieces, array_values( $this->mHeadItems ) );
3230
3231 // Use an IE conditional comment to serve the script only to old IE
3232 $pieces[] = '<!--[if lt IE 9]>' .
3233 ResourceLoaderClientHtml::makeLoad(
3234 ResourceLoaderContext::newDummyContext(),
3235 [ 'html5shiv' ],
3236 ResourceLoaderModule::TYPE_SCRIPTS,
3237 [ 'sync' => true ],
3238 $this->getCSPNonce()
3239 ) .
3240 '<![endif]-->';
3241
3242 $pieces[] = Html::closeElement( 'head' );
3243
3244 $bodyClasses = $this->mAdditionalBodyClasses;
3245 $bodyClasses[] = 'mediawiki';
3246
3247 # Classes for LTR/RTL directionality support
3248 $bodyClasses[] = $userdir;
3249 $bodyClasses[] = "sitedir-$sitedir";
3250
3251 $underline = $this->getUser()->getOption( 'underline' );
3252 if ( $underline < 2 ) {
3253 // The following classes can be used here:
3254 // * mw-underline-always
3255 // * mw-underline-never
3256 $bodyClasses[] = 'mw-underline-' . ( $underline ? 'always' : 'never' );
3257 }
3258
3259 if ( $this->getLanguage()->capitalizeAllNouns() ) {
3260 # A <body> class is probably not the best way to do this . . .
3261 $bodyClasses[] = 'capitalize-all-nouns';
3262 }
3263
3264 // Parser feature migration class
3265 // The idea is that this will eventually be removed, after the wikitext
3266 // which requires it is cleaned up.
3267 $bodyClasses[] = 'mw-hide-empty-elt';
3268
3269 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
3270 $bodyClasses[] = 'skin-' . Sanitizer::escapeClass( $sk->getSkinName() );
3271 $bodyClasses[] =
3272 'action-' . Sanitizer::escapeClass( Action::getActionName( $this->getContext() ) );
3273
3274 $bodyAttrs = [];
3275 // While the implode() is not strictly needed, it's used for backwards compatibility
3276 // (this used to be built as a string and hooks likely still expect that).
3277 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
3278
3279 // Allow skins and extensions to add body attributes they need
3280 $sk->addToBodyAttributes( $this, $bodyAttrs );
3281 Hooks::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
3282
3283 $pieces[] = Html::openElement( 'body', $bodyAttrs );
3284
3285 return self::combineWrappedStrings( $pieces );
3286 }
3287
3288 /**
3289 * Get a ResourceLoader object associated with this OutputPage
3290 *
3291 * @return ResourceLoader
3292 */
3293 public function getResourceLoader() {
3294 if ( is_null( $this->mResourceLoader ) ) {
3295 // Lazy-initialise as needed
3296 $this->mResourceLoader = MediaWikiServices::getInstance()->getResourceLoader();
3297 }
3298 return $this->mResourceLoader;
3299 }
3300
3301 /**
3302 * Explicily load or embed modules on a page.
3303 *
3304 * @param array|string $modules One or more module names
3305 * @param string $only ResourceLoaderModule TYPE_ class constant
3306 * @param array $extraQuery [optional] Array with extra query parameters for the request
3307 * @return string|WrappedStringList HTML
3308 */
3309 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
3310 // Apply 'target' and 'origin' filters
3311 $modules = $this->filterModules( (array)$modules, null, $only );
3312
3313 return ResourceLoaderClientHtml::makeLoad(
3314 $this->getRlClientContext(),
3315 $modules,
3316 $only,
3317 $extraQuery,
3318 $this->getCSPNonce()
3319 );
3320 }
3321
3322 /**
3323 * Combine WrappedString chunks and filter out empty ones
3324 *
3325 * @param array $chunks
3326 * @return string|WrappedStringList HTML
3327 */
3328 protected static function combineWrappedStrings( array $chunks ) {
3329 // Filter out empty values
3330 $chunks = array_filter( $chunks, 'strlen' );
3331 return WrappedString::join( "\n", $chunks );
3332 }
3333
3334 /**
3335 * JS stuff to put at the bottom of the `<body>`.
3336 * These are legacy scripts ($this->mScripts), and user JS.
3337 *
3338 * @return string|WrappedStringList HTML
3339 */
3340 public function getBottomScripts() {
3341 $chunks = [];
3342 $chunks[] = $this->getRlClient()->getBodyHtml();
3343
3344 // Legacy non-ResourceLoader scripts
3345 $chunks[] = $this->mScripts;
3346
3347 if ( $this->limitReportJSData ) {
3348 $chunks[] = ResourceLoader::makeInlineScript(
3349 ResourceLoader::makeConfigSetScript(
3350 [ 'wgPageParseReport' => $this->limitReportJSData ]
3351 ),
3352 $this->getCSPNonce()
3353 );
3354 }
3355
3356 return self::combineWrappedStrings( $chunks );
3357 }
3358
3359 /**
3360 * Get the javascript config vars to include on this page
3361 *
3362 * @return array Array of javascript config vars
3363 * @since 1.23
3364 */
3365 public function getJsConfigVars() {
3366 return $this->mJsConfigVars;
3367 }
3368
3369 /**
3370 * Add one or more variables to be set in mw.config in JavaScript
3371 *
3372 * @param string|array $keys Key or array of key/value pairs
3373 * @param mixed|null $value [optional] Value of the configuration variable
3374 */
3375 public function addJsConfigVars( $keys, $value = null ) {
3376 if ( is_array( $keys ) ) {
3377 foreach ( $keys as $key => $value ) {
3378 $this->mJsConfigVars[$key] = $value;
3379 }
3380 return;
3381 }
3382
3383 $this->mJsConfigVars[$keys] = $value;
3384 }
3385
3386 /**
3387 * Get an array containing the variables to be set in mw.config in JavaScript.
3388 *
3389 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3390 * - in other words, page-independent/site-wide variables (without state).
3391 * You will only be adding bloat to the html page and causing page caches to
3392 * have to be purged on configuration changes.
3393 * @return array
3394 */
3395 public function getJSVars() {
3396 $curRevisionId = 0;
3397 $articleId = 0;
3398 $canonicalSpecialPageName = false; # T23115
3399 $services = MediaWikiServices::getInstance();
3400
3401 $title = $this->getTitle();
3402 $ns = $title->getNamespace();
3403 $canonicalNamespace = MWNamespace::exists( $ns )
3404 ? MWNamespace::getCanonicalName( $ns )
3405 : $title->getNsText();
3406
3407 $sk = $this->getSkin();
3408 // Get the relevant title so that AJAX features can use the correct page name
3409 // when making API requests from certain special pages (T36972).
3410 $relevantTitle = $sk->getRelevantTitle();
3411 $relevantUser = $sk->getRelevantUser();
3412
3413 if ( $ns == NS_SPECIAL ) {
3414 list( $canonicalSpecialPageName, /*...*/ ) =
3415 $services->getSpecialPageFactory()->
3416 resolveAlias( $title->getDBkey() );
3417 } elseif ( $this->canUseWikiPage() ) {
3418 $wikiPage = $this->getWikiPage();
3419 $curRevisionId = $wikiPage->getLatest();
3420 $articleId = $wikiPage->getId();
3421 }
3422
3423 $lang = $title->getPageViewLanguage();
3424
3425 // Pre-process information
3426 $separatorTransTable = $lang->separatorTransformTable();
3427 $separatorTransTable = $separatorTransTable ?: [];
3428 $compactSeparatorTransTable = [
3429 implode( "\t", array_keys( $separatorTransTable ) ),
3430 implode( "\t", $separatorTransTable ),
3431 ];
3432 $digitTransTable = $lang->digitTransformTable();
3433 $digitTransTable = $digitTransTable ?: [];
3434 $compactDigitTransTable = [
3435 implode( "\t", array_keys( $digitTransTable ) ),
3436 implode( "\t", $digitTransTable ),
3437 ];
3438
3439 $user = $this->getUser();
3440
3441 $vars = [
3442 'wgCanonicalNamespace' => $canonicalNamespace,
3443 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3444 'wgNamespaceNumber' => $title->getNamespace(),
3445 'wgPageName' => $title->getPrefixedDBkey(),
3446 'wgTitle' => $title->getText(),
3447 'wgCurRevisionId' => $curRevisionId,
3448 'wgRevisionId' => (int)$this->getRevisionId(),
3449 'wgArticleId' => $articleId,
3450 'wgIsArticle' => $this->isArticle(),
3451 'wgIsRedirect' => $title->isRedirect(),
3452 'wgAction' => Action::getActionName( $this->getContext() ),
3453 'wgUserName' => $user->isAnon() ? null : $user->getName(),
3454 'wgUserGroups' => $user->getEffectiveGroups(),
3455 'wgCategories' => $this->getCategories(),
3456 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3457 'wgPageContentLanguage' => $lang->getCode(),
3458 'wgPageContentModel' => $title->getContentModel(),
3459 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3460 'wgDigitTransformTable' => $compactDigitTransTable,
3461 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3462 'wgMonthNames' => $lang->getMonthNamesArray(),
3463 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3464 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3465 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3466 'wgRequestId' => WebRequest::getRequestId(),
3467 'wgCSPNonce' => $this->getCSPNonce(),
3468 ];
3469
3470 if ( $user->isLoggedIn() ) {
3471 $vars['wgUserId'] = $user->getId();
3472 $vars['wgUserEditCount'] = $user->getEditCount();
3473 $userReg = $user->getRegistration();
3474 $vars['wgUserRegistration'] = $userReg ? wfTimestamp( TS_UNIX, $userReg ) * 1000 : null;
3475 // Get the revision ID of the oldest new message on the user's talk
3476 // page. This can be used for constructing new message alerts on
3477 // the client side.
3478 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3479 }
3480
3481 $contLang = $services->getContentLanguage();
3482 if ( $contLang->hasVariants() ) {
3483 $vars['wgUserVariant'] = $contLang->getPreferredVariant();
3484 }
3485 // Same test as SkinTemplate
3486 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3487 && ( $title->exists() || $title->quickUserCan( 'create', $user ) );
3488
3489 $vars['wgRelevantPageIsProbablyEditable'] = $relevantTitle
3490 && $relevantTitle->quickUserCan( 'edit', $user )
3491 && ( $relevantTitle->exists() || $relevantTitle->quickUserCan( 'create', $user ) );
3492
3493 foreach ( $title->getRestrictionTypes() as $type ) {
3494 // Following keys are set in $vars:
3495 // wgRestrictionCreate, wgRestrictionEdit, wgRestrictionMove, wgRestrictionUpload
3496 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3497 }
3498
3499 if ( $title->isMainPage() ) {
3500 $vars['wgIsMainPage'] = true;
3501 }
3502
3503 if ( $this->mRedirectedFrom ) {
3504 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom->getPrefixedDBkey();
3505 }
3506
3507 if ( $relevantUser ) {
3508 $vars['wgRelevantUserName'] = $relevantUser->getName();
3509 }
3510
3511 // Allow extensions to add their custom variables to the mw.config map.
3512 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3513 // page-dependant but site-wide (without state).
3514 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3515 Hooks::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3516
3517 // Merge in variables from addJsConfigVars last
3518 return array_merge( $vars, $this->getJsConfigVars() );
3519 }
3520
3521 /**
3522 * To make it harder for someone to slip a user a fake
3523 * JavaScript or CSS preview, a random token
3524 * is associated with the login session. If it's not
3525 * passed back with the preview request, we won't render
3526 * the code.
3527 *
3528 * @return bool
3529 */
3530 public function userCanPreview() {
3531 $request = $this->getRequest();
3532 if (
3533 $request->getVal( 'action' ) !== 'submit' ||
3534 !$request->wasPosted()
3535 ) {
3536 return false;
3537 }
3538
3539 $user = $this->getUser();
3540
3541 if ( !$user->isLoggedIn() ) {
3542 // Anons have predictable edit tokens
3543 return false;
3544 }
3545 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3546 return false;
3547 }
3548
3549 $title = $this->getTitle();
3550 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3551 if ( count( $errors ) !== 0 ) {
3552 return false;
3553 }
3554
3555 return true;
3556 }
3557
3558 /**
3559 * @return array Array in format "link name or number => 'link html'".
3560 */
3561 public function getHeadLinksArray() {
3562 global $wgVersion;
3563
3564 $tags = [];
3565 $config = $this->getConfig();
3566
3567 $canonicalUrl = $this->mCanonicalUrl;
3568
3569 $tags['meta-generator'] = Html::element( 'meta', [
3570 'name' => 'generator',
3571 'content' => "MediaWiki $wgVersion",
3572 ] );
3573
3574 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3575 // Per https://w3c.github.io/webappsec-referrer-policy/#unknown-policy-values
3576 // fallbacks should come before the primary value so we need to reverse the array.
3577 foreach ( array_reverse( (array)$config->get( 'ReferrerPolicy' ) ) as $i => $policy ) {
3578 $tags["meta-referrer-$i"] = Html::element( 'meta', [
3579 'name' => 'referrer',
3580 'content' => $policy,
3581 ] );
3582 }
3583 }
3584
3585 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3586 if ( $p !== 'index,follow' ) {
3587 // http://www.robotstxt.org/wc/meta-user.html
3588 // Only show if it's different from the default robots policy
3589 $tags['meta-robots'] = Html::element( 'meta', [
3590 'name' => 'robots',
3591 'content' => $p,
3592 ] );
3593 }
3594
3595 foreach ( $this->mMetatags as $tag ) {
3596 if ( strncasecmp( $tag[0], 'http:', 5 ) === 0 ) {
3597 $a = 'http-equiv';
3598 $tag[0] = substr( $tag[0], 5 );
3599 } elseif ( strncasecmp( $tag[0], 'og:', 3 ) === 0 ) {
3600 $a = 'property';
3601 } else {
3602 $a = 'name';
3603 }
3604 $tagName = "meta-{$tag[0]}";
3605 if ( isset( $tags[$tagName] ) ) {
3606 $tagName .= $tag[1];
3607 }
3608 $tags[$tagName] = Html::element( 'meta',
3609 [
3610 $a => $tag[0],
3611 'content' => $tag[1]
3612 ]
3613 );
3614 }
3615
3616 foreach ( $this->mLinktags as $tag ) {
3617 $tags[] = Html::element( 'link', $tag );
3618 }
3619
3620 # Universal edit button
3621 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3622 $user = $this->getUser();
3623 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3624 && ( $this->getTitle()->exists() ||
3625 $this->getTitle()->quickUserCan( 'create', $user ) )
3626 ) {
3627 // Original UniversalEditButton
3628 $msg = $this->msg( 'edit' )->text();
3629 $tags['universal-edit-button'] = Html::element( 'link', [
3630 'rel' => 'alternate',
3631 'type' => 'application/x-wiki',
3632 'title' => $msg,
3633 'href' => $this->getTitle()->getEditURL(),
3634 ] );
3635 // Alternate edit link
3636 $tags['alternative-edit'] = Html::element( 'link', [
3637 'rel' => 'edit',
3638 'title' => $msg,
3639 'href' => $this->getTitle()->getEditURL(),
3640 ] );
3641 }
3642 }
3643
3644 # Generally the order of the favicon and apple-touch-icon links
3645 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3646 # uses whichever one appears later in the HTML source. Make sure
3647 # apple-touch-icon is specified first to avoid this.
3648 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3649 $tags['apple-touch-icon'] = Html::element( 'link', [
3650 'rel' => 'apple-touch-icon',
3651 'href' => $config->get( 'AppleTouchIcon' )
3652 ] );
3653 }
3654
3655 if ( $config->get( 'Favicon' ) !== false ) {
3656 $tags['favicon'] = Html::element( 'link', [
3657 'rel' => 'shortcut icon',
3658 'href' => $config->get( 'Favicon' )
3659 ] );
3660 }
3661
3662 # OpenSearch description link
3663 $tags['opensearch'] = Html::element( 'link', [
3664 'rel' => 'search',
3665 'type' => 'application/opensearchdescription+xml',
3666 'href' => wfScript( 'opensearch_desc' ),
3667 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3668 ] );
3669
3670 # Real Simple Discovery link, provides auto-discovery information
3671 # for the MediaWiki API (and potentially additional custom API
3672 # support such as WordPress or Twitter-compatible APIs for a
3673 # blogging extension, etc)
3674 $tags['rsd'] = Html::element( 'link', [
3675 'rel' => 'EditURI',
3676 'type' => 'application/rsd+xml',
3677 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3678 // Whether RSD accepts relative or protocol-relative URLs is completely
3679 // undocumented, though.
3680 'href' => wfExpandUrl( wfAppendQuery(
3681 wfScript( 'api' ),
3682 [ 'action' => 'rsd' ] ),
3683 PROTO_RELATIVE
3684 ),
3685 ] );
3686
3687 # Language variants
3688 if ( !$config->get( 'DisableLangConversion' ) ) {
3689 $lang = $this->getTitle()->getPageLanguage();
3690 if ( $lang->hasVariants() ) {
3691 $variants = $lang->getVariants();
3692 foreach ( $variants as $variant ) {
3693 $tags["variant-$variant"] = Html::element( 'link', [
3694 'rel' => 'alternate',
3695 'hreflang' => LanguageCode::bcp47( $variant ),
3696 'href' => $this->getTitle()->getLocalURL(
3697 [ 'variant' => $variant ] )
3698 ]
3699 );
3700 }
3701 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3702 $tags["variant-x-default"] = Html::element( 'link', [
3703 'rel' => 'alternate',
3704 'hreflang' => 'x-default',
3705 'href' => $this->getTitle()->getLocalURL() ] );
3706 }
3707 }
3708
3709 # Copyright
3710 if ( $this->copyrightUrl !== null ) {
3711 $copyright = $this->copyrightUrl;
3712 } else {
3713 $copyright = '';
3714 if ( $config->get( 'RightsPage' ) ) {
3715 $copy = Title::newFromText( $config->get( 'RightsPage' ) );
3716
3717 if ( $copy ) {
3718 $copyright = $copy->getLocalURL();
3719 }
3720 }
3721
3722 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3723 $copyright = $config->get( 'RightsUrl' );
3724 }
3725 }
3726
3727 if ( $copyright ) {
3728 $tags['copyright'] = Html::element( 'link', [
3729 'rel' => 'license',
3730 'href' => $copyright ]
3731 );
3732 }
3733
3734 # Feeds
3735 if ( $config->get( 'Feed' ) ) {
3736 $feedLinks = [];
3737
3738 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3739 # Use the page name for the title. In principle, this could
3740 # lead to issues with having the same name for different feeds
3741 # corresponding to the same page, but we can't avoid that at
3742 # this low a level.
3743
3744 $feedLinks[] = $this->feedLink(
3745 $format,
3746 $link,
3747 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3748 $this->msg(
3749 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3750 )->text()
3751 );
3752 }
3753
3754 # Recent changes feed should appear on every page (except recentchanges,
3755 # that would be redundant). Put it after the per-page feed to avoid
3756 # changing existing behavior. It's still available, probably via a
3757 # menu in your browser. Some sites might have a different feed they'd
3758 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3759 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3760 # If so, use it instead.
3761 $sitename = $config->get( 'Sitename' );
3762 if ( $config->get( 'OverrideSiteFeed' ) ) {
3763 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3764 // Note, this->feedLink escapes the url.
3765 $feedLinks[] = $this->feedLink(
3766 $type,
3767 $feedUrl,
3768 $this->msg( "site-{$type}-feed", $sitename )->text()
3769 );
3770 }
3771 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3772 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
3773 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3774 $feedLinks[] = $this->feedLink(
3775 $format,
3776 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3777 # For grep: 'site-rss-feed', 'site-atom-feed'
3778 $this->msg( "site-{$format}-feed", $sitename )->text()
3779 );
3780 }
3781 }
3782
3783 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3784 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3785 # use OutputPage::addFeedLink() instead.
3786 Hooks::run( 'AfterBuildFeedLinks', [ &$feedLinks ] );
3787
3788 $tags += $feedLinks;
3789 }
3790
3791 # Canonical URL
3792 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3793 if ( $canonicalUrl !== false ) {
3794 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL );
3795 } else {
3796 if ( $this->isArticleRelated() ) {
3797 // This affects all requests where "setArticleRelated" is true. This is
3798 // typically all requests that show content (query title, curid, oldid, diff),
3799 // and all wikipage actions (edit, delete, purge, info, history etc.).
3800 // It does not apply to File pages and Special pages.
3801 // 'history' and 'info' actions address page metadata rather than the page
3802 // content itself, so they may not be canonicalized to the view page url.
3803 // TODO: this ought to be better encapsulated in the Action class.
3804 $action = Action::getActionName( $this->getContext() );
3805 if ( in_array( $action, [ 'history', 'info' ] ) ) {
3806 $query = "action={$action}";
3807 } else {
3808 $query = '';
3809 }
3810 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3811 } else {
3812 $reqUrl = $this->getRequest()->getRequestURL();
3813 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL );
3814 }
3815 }
3816 }
3817 if ( $canonicalUrl !== false ) {
3818 $tags[] = Html::element( 'link', [
3819 'rel' => 'canonical',
3820 'href' => $canonicalUrl
3821 ] );
3822 }
3823
3824 // Allow extensions to add, remove and/or otherwise manipulate these links
3825 // If you want only to *add* <head> links, please use the addHeadItem()
3826 // (or addHeadItems() for multiple items) method instead.
3827 // This hook is provided as a last resort for extensions to modify these
3828 // links before the output is sent to client.
3829 Hooks::run( 'OutputPageAfterGetHeadLinksArray', [ &$tags, $this ] );
3830
3831 return $tags;
3832 }
3833
3834 /**
3835 * Generate a "<link rel/>" for a feed.
3836 *
3837 * @param string $type Feed type
3838 * @param string $url URL to the feed
3839 * @param string $text Value of the "title" attribute
3840 * @return string HTML fragment
3841 */
3842 private function feedLink( $type, $url, $text ) {
3843 return Html::element( 'link', [
3844 'rel' => 'alternate',
3845 'type' => "application/$type+xml",
3846 'title' => $text,
3847 'href' => $url ]
3848 );
3849 }
3850
3851 /**
3852 * Add a local or specified stylesheet, with the given media options.
3853 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3854 *
3855 * @param string $style URL to the file
3856 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3857 * @param string $condition For IE conditional comments, specifying an IE version
3858 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3859 */
3860 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3861 $options = [];
3862 if ( $media ) {
3863 $options['media'] = $media;
3864 }
3865 if ( $condition ) {
3866 $options['condition'] = $condition;
3867 }
3868 if ( $dir ) {
3869 $options['dir'] = $dir;
3870 }
3871 $this->styles[$style] = $options;
3872 }
3873
3874 /**
3875 * Adds inline CSS styles
3876 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3877 *
3878 * @param mixed $style_css Inline CSS
3879 * @param string $flip Set to 'flip' to flip the CSS if needed
3880 */
3881 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3882 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3883 # If wanted, and the interface is right-to-left, flip the CSS
3884 $style_css = CSSJanus::transform( $style_css, true, false );
3885 }
3886 $this->mInlineStyles .= Html::inlineStyle( $style_css );
3887 }
3888
3889 /**
3890 * Build exempt modules and legacy non-ResourceLoader styles.
3891 *
3892 * @return string|WrappedStringList HTML
3893 */
3894 protected function buildExemptModules() {
3895 $chunks = [];
3896 // Things that go after the ResourceLoaderDynamicStyles marker
3897 $append = [];
3898
3899 // We want site, private and user styles to override dynamically added styles from
3900 // general modules, but we want dynamically added styles to override statically added
3901 // style modules. So the order has to be:
3902 // - page style modules (formatted by ResourceLoaderClientHtml::getHeadHtml())
3903 // - dynamically loaded styles (added by mw.loader before ResourceLoaderDynamicStyles)
3904 // - ResourceLoaderDynamicStyles marker
3905 // - site/private/user styles
3906
3907 // Add legacy styles added through addStyle()/addInlineStyle() here
3908 $chunks[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles;
3909
3910 $chunks[] = Html::element(
3911 'meta',
3912 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
3913 );
3914
3915 $separateReq = [ 'site.styles', 'user.styles' ];
3916 foreach ( $this->rlExemptStyleModules as $group => $moduleNames ) {
3917 // Combinable modules
3918 $chunks[] = $this->makeResourceLoaderLink(
3919 array_diff( $moduleNames, $separateReq ),
3920 ResourceLoaderModule::TYPE_STYLES
3921 );
3922
3923 foreach ( array_intersect( $moduleNames, $separateReq ) as $name ) {
3924 // These require their own dedicated request in order to support "@import"
3925 // syntax, which is incompatible with concatenation. (T147667, T37562)
3926 $chunks[] = $this->makeResourceLoaderLink( $name,
3927 ResourceLoaderModule::TYPE_STYLES
3928 );
3929 }
3930 }
3931
3932 return self::combineWrappedStrings( array_merge( $chunks, $append ) );
3933 }
3934
3935 /**
3936 * @return array
3937 */
3938 public function buildCssLinksArray() {
3939 $links = [];
3940
3941 foreach ( $this->styles as $file => $options ) {
3942 $link = $this->styleLink( $file, $options );
3943 if ( $link ) {
3944 $links[$file] = $link;
3945 }
3946 }
3947 return $links;
3948 }
3949
3950 /**
3951 * Generate \<link\> tags for stylesheets
3952 *
3953 * @param string $style URL to the file
3954 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3955 * @return string HTML fragment
3956 */
3957 protected function styleLink( $style, array $options ) {
3958 if ( isset( $options['dir'] ) ) {
3959 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3960 return '';
3961 }
3962 }
3963
3964 if ( isset( $options['media'] ) ) {
3965 $media = self::transformCssMedia( $options['media'] );
3966 if ( is_null( $media ) ) {
3967 return '';
3968 }
3969 } else {
3970 $media = 'all';
3971 }
3972
3973 if ( substr( $style, 0, 1 ) == '/' ||
3974 substr( $style, 0, 5 ) == 'http:' ||
3975 substr( $style, 0, 6 ) == 'https:' ) {
3976 $url = $style;
3977 } else {
3978 $config = $this->getConfig();
3979 // Append file hash as query parameter
3980 $url = self::transformResourcePath(
3981 $config,
3982 $config->get( 'StylePath' ) . '/' . $style
3983 );
3984 }
3985
3986 $link = Html::linkedStyle( $url, $media );
3987
3988 if ( isset( $options['condition'] ) ) {
3989 $condition = htmlspecialchars( $options['condition'] );
3990 $link = "<!--[if $condition]>$link<![endif]-->";
3991 }
3992 return $link;
3993 }
3994
3995 /**
3996 * Transform path to web-accessible static resource.
3997 *
3998 * This is used to add a validation hash as query string.
3999 * This aids various behaviors:
4000 *
4001 * - Put long Cache-Control max-age headers on responses for improved
4002 * cache performance.
4003 * - Get the correct version of a file as expected by the current page.
4004 * - Instantly get the updated version of a file after deployment.
4005 *
4006 * Avoid using this for urls included in HTML as otherwise clients may get different
4007 * versions of a resource when navigating the site depending on when the page was cached.
4008 * If changes to the url propagate, this is not a problem (e.g. if the url is in
4009 * an external stylesheet).
4010 *
4011 * @since 1.27
4012 * @param Config $config
4013 * @param string $path Path-absolute URL to file (from document root, must start with "/")
4014 * @return string URL
4015 */
4016 public static function transformResourcePath( Config $config, $path ) {
4017 global $IP;
4018
4019 $localDir = $IP;
4020 $remotePathPrefix = $config->get( 'ResourceBasePath' );
4021 if ( $remotePathPrefix === '' ) {
4022 // The configured base path is required to be empty string for
4023 // wikis in the domain root
4024 $remotePath = '/';
4025 } else {
4026 $remotePath = $remotePathPrefix;
4027 }
4028 if ( strpos( $path, $remotePath ) !== 0 || substr( $path, 0, 2 ) === '//' ) {
4029 // - Path is outside wgResourceBasePath, ignore.
4030 // - Path is protocol-relative. Fixes T155310. Not supported by RelPath lib.
4031 return $path;
4032 }
4033 // For files in resources, extensions/ or skins/, ResourceBasePath is preferred here.
4034 // For other misc files in $IP, we'll fallback to that as well. There is, however, a fourth
4035 // supported dir/path pair in the configuration (wgUploadDirectory, wgUploadPath)
4036 // which is not expected to be in wgResourceBasePath on CDNs. (T155146)
4037 $uploadPath = $config->get( 'UploadPath' );
4038 if ( strpos( $path, $uploadPath ) === 0 ) {
4039 $localDir = $config->get( 'UploadDirectory' );
4040 $remotePathPrefix = $remotePath = $uploadPath;
4041 }
4042
4043 $path = RelPath::getRelativePath( $path, $remotePath );
4044 return self::transformFilePath( $remotePathPrefix, $localDir, $path );
4045 }
4046
4047 /**
4048 * Utility method for transformResourceFilePath().
4049 *
4050 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
4051 *
4052 * @since 1.27
4053 * @param string $remotePathPrefix URL path prefix that points to $localPath
4054 * @param string $localPath File directory exposed at $remotePath
4055 * @param string $file Path to target file relative to $localPath
4056 * @return string URL
4057 */
4058 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
4059 $hash = md5_file( "$localPath/$file" );
4060 if ( $hash === false ) {
4061 wfLogWarning( __METHOD__ . ": Failed to hash $localPath/$file" );
4062 $hash = '';
4063 }
4064 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
4065 }
4066
4067 /**
4068 * Transform "media" attribute based on request parameters
4069 *
4070 * @param string $media Current value of the "media" attribute
4071 * @return string Modified value of the "media" attribute, or null to skip
4072 * this stylesheet
4073 */
4074 public static function transformCssMedia( $media ) {
4075 global $wgRequest;
4076
4077 // https://www.w3.org/TR/css3-mediaqueries/#syntax
4078 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
4079
4080 // Switch in on-screen display for media testing
4081 $switches = [
4082 'printable' => 'print',
4083 'handheld' => 'handheld',
4084 ];
4085 foreach ( $switches as $switch => $targetMedia ) {
4086 if ( $wgRequest->getBool( $switch ) ) {
4087 if ( $media == $targetMedia ) {
4088 $media = '';
4089 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
4090 /* This regex will not attempt to understand a comma-separated media_query_list
4091 *
4092 * Example supported values for $media:
4093 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
4094 * Example NOT supported value for $media:
4095 * '3d-glasses, screen, print and resolution > 90dpi'
4096 *
4097 * If it's a print request, we never want any kind of screen stylesheets
4098 * If it's a handheld request (currently the only other choice with a switch),
4099 * we don't want simple 'screen' but we might want screen queries that
4100 * have a max-width or something, so we'll pass all others on and let the
4101 * client do the query.
4102 */
4103 if ( $targetMedia == 'print' || $media == 'screen' ) {
4104 return null;
4105 }
4106 }
4107 }
4108 }
4109
4110 return $media;
4111 }
4112
4113 /**
4114 * Add a wikitext-formatted message to the output.
4115 * This is equivalent to:
4116 *
4117 * $wgOut->addWikiText( wfMessage( ... )->plain() )
4118 */
4119 public function addWikiMsg( /*...*/ ) {
4120 $args = func_get_args();
4121 $name = array_shift( $args );
4122 $this->addWikiMsgArray( $name, $args );
4123 }
4124
4125 /**
4126 * Add a wikitext-formatted message to the output.
4127 * Like addWikiMsg() except the parameters are taken as an array
4128 * instead of a variable argument list.
4129 *
4130 * @param string $name
4131 * @param array $args
4132 */
4133 public function addWikiMsgArray( $name, $args ) {
4134 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
4135 }
4136
4137 /**
4138 * This function takes a number of message/argument specifications, wraps them in
4139 * some overall structure, and then parses the result and adds it to the output.
4140 *
4141 * In the $wrap, $1 is replaced with the first message, $2 with the second,
4142 * and so on. The subsequent arguments may be either
4143 * 1) strings, in which case they are message names, or
4144 * 2) arrays, in which case, within each array, the first element is the message
4145 * name, and subsequent elements are the parameters to that message.
4146 *
4147 * Don't use this for messages that are not in the user's interface language.
4148 *
4149 * For example:
4150 *
4151 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
4152 *
4153 * Is equivalent to:
4154 *
4155 * $wgOut->addWikiTextAsInterface( "<div class='error'>\n"
4156 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
4157 *
4158 * The newline after the opening div is needed in some wikitext. See T21226.
4159 *
4160 * @param string $wrap
4161 */
4162 public function wrapWikiMsg( $wrap /*, ...*/ ) {
4163 $msgSpecs = func_get_args();
4164 array_shift( $msgSpecs );
4165 $msgSpecs = array_values( $msgSpecs );
4166 $s = $wrap;
4167 foreach ( $msgSpecs as $n => $spec ) {
4168 if ( is_array( $spec ) ) {
4169 $args = $spec;
4170 $name = array_shift( $args );
4171 if ( isset( $args['options'] ) ) {
4172 unset( $args['options'] );
4173 wfDeprecated(
4174 'Adding "options" to ' . __METHOD__ . ' is no longer supported',
4175 '1.20'
4176 );
4177 }
4178 } else {
4179 $args = [];
4180 $name = $spec;
4181 }
4182 $s = str_replace( '$' . ( $n + 1 ), $this->msg( $name, $args )->plain(), $s );
4183 }
4184 $this->addWikiTextAsInterface( $s );
4185 }
4186
4187 /**
4188 * Whether the output has a table of contents
4189 * @return bool
4190 * @since 1.22
4191 */
4192 public function isTOCEnabled() {
4193 return $this->mEnableTOC;
4194 }
4195
4196 /**
4197 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
4198 * @param bool $flag
4199 * @since 1.23
4200 * @deprecated since 1.31, use $poOptions to addParserOutput() instead.
4201 */
4202 public function enableSectionEditLinks( $flag = true ) {
4203 wfDeprecated( __METHOD__, '1.31' );
4204 }
4205
4206 /**
4207 * @return bool
4208 * @since 1.23
4209 * @deprecated since 1.31, use $poOptions to addParserOutput() instead.
4210 */
4211 public function sectionEditLinksEnabled() {
4212 wfDeprecated( __METHOD__, '1.31' );
4213 return true;
4214 }
4215
4216 /**
4217 * Helper function to setup the PHP implementation of OOUI to use in this request.
4218 *
4219 * @since 1.26
4220 * @param string $skinName The Skin name to determine the correct OOUI theme
4221 * @param string $dir Language direction
4222 */
4223 public static function setupOOUI( $skinName = 'default', $dir = 'ltr' ) {
4224 $themes = ResourceLoaderOOUIModule::getSkinThemeMap();
4225 $theme = $themes[$skinName] ?? $themes['default'];
4226 // For example, 'OOUI\WikimediaUITheme'.
4227 $themeClass = "OOUI\\{$theme}Theme";
4228 OOUI\Theme::setSingleton( new $themeClass() );
4229 OOUI\Element::setDefaultDir( $dir );
4230 }
4231
4232 /**
4233 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
4234 * MediaWiki and this OutputPage instance.
4235 *
4236 * @since 1.25
4237 */
4238 public function enableOOUI() {
4239 self::setupOOUI(
4240 strtolower( $this->getSkin()->getSkinName() ),
4241 $this->getLanguage()->getDir()
4242 );
4243 $this->addModuleStyles( [
4244 'oojs-ui-core.styles',
4245 'oojs-ui.styles.indicators',
4246 'oojs-ui.styles.textures',
4247 'mediawiki.widgets.styles',
4248 'oojs-ui.styles.icons-content',
4249 'oojs-ui.styles.icons-alerts',
4250 'oojs-ui.styles.icons-interactions',
4251 ] );
4252 }
4253
4254 /**
4255 * Get (and set if not yet set) the CSP nonce.
4256 *
4257 * This value needs to be included in any <script> tags on the
4258 * page.
4259 *
4260 * @return string|bool Nonce or false to mean don't output nonce
4261 * @since 1.32
4262 */
4263 public function getCSPNonce() {
4264 if ( !ContentSecurityPolicy::isNonceRequired( $this->getConfig() ) ) {
4265 return false;
4266 }
4267 if ( $this->CSPNonce === null ) {
4268 // XXX It might be expensive to generate randomness
4269 // on every request, on Windows.
4270 $rand = random_bytes( 15 );
4271 $this->CSPNonce = base64_encode( $rand );
4272 }
4273 return $this->CSPNonce;
4274 }
4275
4276 }