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