Merge "Clean up spacing of doc comments"
[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 * Set the timestamp of the revision which will be displayed. This is used
1666 * to avoid a extra DB call in Skin::lastModified().
1667 *
1668 * @param string|null $timestamp
1669 * @return mixed Previous value
1670 */
1671 public function setRevisionTimestamp( $timestamp ) {
1672 return wfSetVar( $this->mRevisionTimestamp, $timestamp, true );
1673 }
1674
1675 /**
1676 * Get the timestamp of displayed revision.
1677 * This will be null if not filled by setRevisionTimestamp().
1678 *
1679 * @return string|null
1680 */
1681 public function getRevisionTimestamp() {
1682 return $this->mRevisionTimestamp;
1683 }
1684
1685 /**
1686 * Set the displayed file version
1687 *
1688 * @param File|null $file
1689 * @return mixed Previous value
1690 */
1691 public function setFileVersion( $file ) {
1692 $val = null;
1693 if ( $file instanceof File && $file->exists() ) {
1694 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1695 }
1696 return wfSetVar( $this->mFileVersion, $val, true );
1697 }
1698
1699 /**
1700 * Get the displayed file version
1701 *
1702 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1703 */
1704 public function getFileVersion() {
1705 return $this->mFileVersion;
1706 }
1707
1708 /**
1709 * Get the templates used on this page
1710 *
1711 * @return array (namespace => dbKey => revId)
1712 * @since 1.18
1713 */
1714 public function getTemplateIds() {
1715 return $this->mTemplateIds;
1716 }
1717
1718 /**
1719 * Get the files used on this page
1720 *
1721 * @return array [ dbKey => [ 'time' => MW timestamp or null, 'sha1' => sha1 or '' ] ]
1722 * @since 1.18
1723 */
1724 public function getFileSearchOptions() {
1725 return $this->mImageTimeKeys;
1726 }
1727
1728 /**
1729 * Convert wikitext *in the user interface language* to HTML and
1730 * add it to the buffer. The result will not be
1731 * language-converted, as user interface messages are already
1732 * localized into a specific variant. Assumes that the current
1733 * page title will be used if optional $title is not
1734 * provided. Output will be tidy.
1735 *
1736 * @param string $text Wikitext in the user interface language
1737 * @param bool $linestart Is this the start of a line? (Defaults to true)
1738 * @param Title|null $title Optional title to use; default of `null`
1739 * means use current page title.
1740 * @throws MWException if $title is not provided and OutputPage::getTitle()
1741 * is null
1742 * @since 1.32
1743 */
1744 public function addWikiTextAsInterface(
1745 $text, $linestart = true, Title $title = null
1746 ) {
1747 if ( $title === null ) {
1748 $title = $this->getTitle();
1749 }
1750 if ( !$title ) {
1751 throw new MWException( 'Title is null' );
1752 }
1753 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*interface*/true );
1754 }
1755
1756 /**
1757 * Convert wikitext *in the user interface language* to HTML and
1758 * add it to the buffer with a `<div class="$wrapperClass">`
1759 * wrapper. The result will not be language-converted, as user
1760 * interface messages as already localized into a specific
1761 * variant. The $text will be parsed in start-of-line context.
1762 * Output will be tidy.
1763 *
1764 * @param string $wrapperClass The class attribute value for the <div>
1765 * wrapper in the output HTML
1766 * @param string $text Wikitext in the user interface language
1767 * @since 1.32
1768 */
1769 public function wrapWikiTextAsInterface(
1770 $wrapperClass, $text
1771 ) {
1772 $this->addWikiTextTitleInternal(
1773 $text, $this->getTitle(),
1774 /*linestart*/true, /*interface*/true,
1775 $wrapperClass
1776 );
1777 }
1778
1779 /**
1780 * Convert wikitext *in the page content language* to HTML and add
1781 * it to the buffer. The result with be language-converted to the
1782 * user's preferred variant. Assumes that the current page title
1783 * will be used if optional $title is not provided. Output will be
1784 * tidy.
1785 *
1786 * @param string $text Wikitext in the page content language
1787 * @param bool $linestart Is this the start of a line? (Defaults to true)
1788 * @param Title|null $title Optional title to use; default of `null`
1789 * means use current page title.
1790 * @throws MWException if $title is not provided and OutputPage::getTitle()
1791 * is null
1792 * @since 1.32
1793 */
1794 public function addWikiTextAsContent(
1795 $text, $linestart = true, Title $title = null
1796 ) {
1797 if ( $title === null ) {
1798 $title = $this->getTitle();
1799 }
1800 if ( !$title ) {
1801 throw new MWException( 'Title is null' );
1802 }
1803 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*interface*/false );
1804 }
1805
1806 /**
1807 * Add wikitext with a custom Title object.
1808 * Output is unwrapped.
1809 *
1810 * @param string $text Wikitext
1811 * @param Title $title
1812 * @param bool $linestart Is this the start of a line?
1813 * @param bool $tidy Whether to use tidy.
1814 * Setting this to false (or omitting it) is deprecated
1815 * since 1.32; all wikitext should be tidied.
1816 * @param bool $interface Whether it is an interface message
1817 * (for example disables conversion)
1818 * @param string $wrapperClass if not empty, wraps the output in
1819 * a `<div class="$wrapperClass">`
1820 * @private
1821 */
1822 private function addWikiTextTitleInternal(
1823 $text, Title $title, $linestart, $interface, $wrapperClass = null
1824 ) {
1825 $parserOutput = $this->parseInternal(
1826 $text, $title, $linestart, true, $interface, /*language*/null
1827 );
1828
1829 $this->addParserOutput( $parserOutput, [
1830 'enableSectionEditLinks' => false,
1831 'wrapperDivClass' => $wrapperClass ?? '',
1832 ] );
1833 }
1834
1835 /**
1836 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1837 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1838 * and so on.
1839 *
1840 * @since 1.24
1841 * @param ParserOutput $parserOutput
1842 */
1843 public function addParserOutputMetadata( ParserOutput $parserOutput ) {
1844 $this->mLanguageLinks =
1845 array_merge( $this->mLanguageLinks, $parserOutput->getLanguageLinks() );
1846 $this->addCategoryLinks( $parserOutput->getCategories() );
1847 $this->setIndicators( $parserOutput->getIndicators() );
1848 $this->mNewSectionLink = $parserOutput->getNewSection();
1849 $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
1850
1851 if ( !$parserOutput->isCacheable() ) {
1852 $this->enableClientCache( false );
1853 }
1854 $this->mNoGallery = $parserOutput->getNoGallery();
1855 $this->mHeadItems = array_merge( $this->mHeadItems, $parserOutput->getHeadItems() );
1856 $this->addModules( $parserOutput->getModules() );
1857 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1858 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1859 $this->mPreventClickjacking = $this->mPreventClickjacking
1860 || $parserOutput->preventClickjacking();
1861
1862 // Template versioning...
1863 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1864 if ( isset( $this->mTemplateIds[$ns] ) ) {
1865 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
1866 } else {
1867 $this->mTemplateIds[$ns] = $dbks;
1868 }
1869 }
1870 // File versioning...
1871 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1872 $this->mImageTimeKeys[$dbk] = $data;
1873 }
1874
1875 // Hooks registered in the object
1876 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1877 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1878 list( $hookName, $data ) = $hookInfo;
1879 if ( isset( $parserOutputHooks[$hookName] ) ) {
1880 $parserOutputHooks[$hookName]( $this, $parserOutput, $data );
1881 }
1882 }
1883
1884 // Enable OOUI if requested via ParserOutput
1885 if ( $parserOutput->getEnableOOUI() ) {
1886 $this->enableOOUI();
1887 }
1888
1889 // Include parser limit report
1890 if ( !$this->limitReportJSData ) {
1891 $this->limitReportJSData = $parserOutput->getLimitReportJSData();
1892 }
1893
1894 // Link flags are ignored for now, but may in the future be
1895 // used to mark individual language links.
1896 $linkFlags = [];
1897 // Avoid PHP 7.1 warning of passing $this by reference
1898 $outputPage = $this;
1899 Hooks::run( 'LanguageLinks', [ $this->getTitle(), &$this->mLanguageLinks, &$linkFlags ] );
1900 Hooks::runWithoutAbort( 'OutputPageParserOutput', [ &$outputPage, $parserOutput ] );
1901
1902 // This check must be after 'OutputPageParserOutput' runs in addParserOutputMetadata
1903 // so that extensions may modify ParserOutput to toggle TOC.
1904 // This cannot be moved to addParserOutputText because that is not
1905 // called by EditPage for Preview.
1906 if ( $parserOutput->getTOCHTML() ) {
1907 $this->mEnableTOC = true;
1908 }
1909 }
1910
1911 /**
1912 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1913 * ParserOutput object, without any other metadata.
1914 *
1915 * @since 1.24
1916 * @param ParserOutput $parserOutput
1917 * @param array $poOptions Options to ParserOutput::getText()
1918 */
1919 public function addParserOutputContent( ParserOutput $parserOutput, $poOptions = [] ) {
1920 $this->addParserOutputText( $parserOutput, $poOptions );
1921
1922 $this->addModules( $parserOutput->getModules() );
1923 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1924
1925 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1926 }
1927
1928 /**
1929 * Add the HTML associated with a ParserOutput object, without any metadata.
1930 *
1931 * @since 1.24
1932 * @param ParserOutput $parserOutput
1933 * @param array $poOptions Options to ParserOutput::getText()
1934 */
1935 public function addParserOutputText( ParserOutput $parserOutput, $poOptions = [] ) {
1936 $text = $parserOutput->getText( $poOptions );
1937 // Avoid PHP 7.1 warning of passing $this by reference
1938 $outputPage = $this;
1939 Hooks::runWithoutAbort( 'OutputPageBeforeHTML', [ &$outputPage, &$text ] );
1940 $this->addHTML( $text );
1941 }
1942
1943 /**
1944 * Add everything from a ParserOutput object.
1945 *
1946 * @param ParserOutput $parserOutput
1947 * @param array $poOptions Options to ParserOutput::getText()
1948 */
1949 function addParserOutput( ParserOutput $parserOutput, $poOptions = [] ) {
1950 $this->addParserOutputMetadata( $parserOutput );
1951 $this->addParserOutputText( $parserOutput, $poOptions );
1952 }
1953
1954 /**
1955 * Add the output of a QuickTemplate to the output buffer
1956 *
1957 * @param QuickTemplate &$template
1958 */
1959 public function addTemplate( &$template ) {
1960 $this->addHTML( $template->getHTML() );
1961 }
1962
1963 /**
1964 * Parse wikitext and return the HTML.
1965 *
1966 * @todo The output is wrapped in a <div> iff $interface is false; it's
1967 * probably best to always strip the wrapper.
1968 *
1969 * @param string $text
1970 * @param bool $linestart Is this the start of a line?
1971 * @param bool $interface Use interface language (instead of content language) while parsing
1972 * language sensitive magic words like GRAMMAR and PLURAL. This also disables
1973 * LanguageConverter.
1974 * @param Language|null $language Target language object, will override $interface
1975 * @throws MWException
1976 * @return string HTML
1977 * @deprecated since 1.32, due to untidy output and inconsistent wrapper;
1978 * use parseAsContent() if $interface is default value or false, or else
1979 * parseAsInterface() if $interface is true.
1980 */
1981 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1982 wfDeprecated( __METHOD__, '1.33' );
1983 return $this->parseInternal(
1984 $text, $this->getTitle(), $linestart, /*tidy*/false, $interface, $language
1985 )->getText( [
1986 'enableSectionEditLinks' => false,
1987 ] );
1988 }
1989
1990 /**
1991 * Parse wikitext *in the page content language* and return the HTML.
1992 * The result will be language-converted to the user's preferred variant.
1993 * Output will be tidy.
1994 *
1995 * @param string $text Wikitext in the page content language
1996 * @param bool $linestart Is this the start of a line? (Defaults to true)
1997 * @throws MWException
1998 * @return string HTML
1999 * @since 1.32
2000 */
2001 public function parseAsContent( $text, $linestart = true ) {
2002 return $this->parseInternal(
2003 $text, $this->getTitle(), $linestart, /*tidy*/true, /*interface*/false, /*language*/null
2004 )->getText( [
2005 'enableSectionEditLinks' => false,
2006 'wrapperDivClass' => ''
2007 ] );
2008 }
2009
2010 /**
2011 * Parse wikitext *in the user interface language* and return the HTML.
2012 * The result will not be language-converted, as user interface messages
2013 * are already localized into a specific variant.
2014 * Output will be tidy.
2015 *
2016 * @param string $text Wikitext in the user interface language
2017 * @param bool $linestart Is this the start of a line? (Defaults to true)
2018 * @throws MWException
2019 * @return string HTML
2020 * @since 1.32
2021 */
2022 public function parseAsInterface( $text, $linestart = true ) {
2023 return $this->parseInternal(
2024 $text, $this->getTitle(), $linestart, /*tidy*/true, /*interface*/true, /*language*/null
2025 )->getText( [
2026 'enableSectionEditLinks' => false,
2027 'wrapperDivClass' => ''
2028 ] );
2029 }
2030
2031 /**
2032 * Parse wikitext *in the user interface language*, strip
2033 * paragraph wrapper, and return the HTML.
2034 * The result will not be language-converted, as user interface messages
2035 * are already localized into a specific variant.
2036 * Output will be tidy. Outer paragraph wrapper will only be stripped
2037 * if the result is a single paragraph.
2038 *
2039 * @param string $text Wikitext in the user interface language
2040 * @param bool $linestart Is this the start of a line? (Defaults to true)
2041 * @throws MWException
2042 * @return string HTML
2043 * @since 1.32
2044 */
2045 public function parseInlineAsInterface( $text, $linestart = true ) {
2046 return Parser::stripOuterParagraph(
2047 $this->parseAsInterface( $text, $linestart )
2048 );
2049 }
2050
2051 /**
2052 * Parse wikitext, strip paragraph wrapper, and return the HTML.
2053 *
2054 * @param string $text
2055 * @param bool $linestart Is this the start of a line?
2056 * @param bool $interface Use interface language (instead of content language) while parsing
2057 * language sensitive magic words like GRAMMAR and PLURAL
2058 * @return string HTML
2059 * @deprecated since 1.32, due to untidy output and confusing default
2060 * for $interface. Use parseInlineAsInterface() if $interface is
2061 * the default value or false, or else use
2062 * Parser::stripOuterParagraph($outputPage->parseAsContent(...)).
2063 */
2064 public function parseInline( $text, $linestart = true, $interface = false ) {
2065 wfDeprecated( __METHOD__, '1.33' );
2066 $parsed = $this->parseInternal(
2067 $text, $this->getTitle(), $linestart, /*tidy*/false, $interface, /*language*/null
2068 )->getText( [
2069 'enableSectionEditLinks' => false,
2070 'wrapperDivClass' => '', /* no wrapper div */
2071 ] );
2072 return Parser::stripOuterParagraph( $parsed );
2073 }
2074
2075 /**
2076 * Parse wikitext and return the HTML (internal implementation helper)
2077 *
2078 * @param string $text
2079 * @param Title $title The title to use
2080 * @param bool $linestart Is this the start of a line?
2081 * @param bool $tidy Whether the output should be tidied
2082 * @param bool $interface Use interface language (instead of content language) while parsing
2083 * language sensitive magic words like GRAMMAR and PLURAL. This also disables
2084 * LanguageConverter.
2085 * @param Language|null $language Target language object, will override $interface
2086 * @throws MWException
2087 * @return ParserOutput
2088 */
2089 private function parseInternal( $text, $title, $linestart, $tidy, $interface, $language ) {
2090 if ( is_null( $title ) ) {
2091 throw new MWException( 'Empty $mTitle in ' . __METHOD__ );
2092 }
2093
2094 $popts = $this->parserOptions();
2095 $oldTidy = $popts->setTidy( $tidy );
2096 $oldInterface = $popts->setInterfaceMessage( (bool)$interface );
2097
2098 if ( $language !== null ) {
2099 $oldLang = $popts->setTargetLanguage( $language );
2100 }
2101
2102 $parserOutput = MediaWikiServices::getInstance()->getParser()->getFreshParser()->parse(
2103 $text, $title, $popts,
2104 $linestart, true, $this->mRevisionId
2105 );
2106
2107 $popts->setTidy( $oldTidy );
2108 $popts->setInterfaceMessage( $oldInterface );
2109
2110 if ( $language !== null ) {
2111 $popts->setTargetLanguage( $oldLang );
2112 }
2113
2114 return $parserOutput;
2115 }
2116
2117 /**
2118 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
2119 *
2120 * @param int $maxage Maximum cache time on the CDN, in seconds.
2121 */
2122 public function setCdnMaxage( $maxage ) {
2123 $this->mCdnMaxage = min( $maxage, $this->mCdnMaxageLimit );
2124 }
2125
2126 /**
2127 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header to $maxage if that is
2128 * lower than the current s-maxage. Either way, $maxage is now an upper limit on s-maxage, so
2129 * that future calls to setCdnMaxage() will no longer be able to raise the s-maxage above
2130 * $maxage.
2131 *
2132 * @param int $maxage Maximum cache time on the CDN, in seconds
2133 * @since 1.27
2134 */
2135 public function lowerCdnMaxage( $maxage ) {
2136 $this->mCdnMaxageLimit = min( $maxage, $this->mCdnMaxageLimit );
2137 $this->setCdnMaxage( $this->mCdnMaxage );
2138 }
2139
2140 /**
2141 * Get TTL in [$minTTL,$maxTTL] in pass it to lowerCdnMaxage()
2142 *
2143 * This sets and returns $minTTL if $mtime is false or null. Otherwise,
2144 * the TTL is higher the older the $mtime timestamp is. Essentially, the
2145 * TTL is 90% of the age of the object, subject to the min and max.
2146 *
2147 * @param string|int|float|bool|null $mtime Last-Modified timestamp
2148 * @param int $minTTL Minimum TTL in seconds [default: 1 minute]
2149 * @param int $maxTTL Maximum TTL in seconds [default: $wgCdnMaxAge]
2150 * @since 1.28
2151 */
2152 public function adaptCdnTTL( $mtime, $minTTL = 0, $maxTTL = 0 ) {
2153 $minTTL = $minTTL ?: IExpiringStore::TTL_MINUTE;
2154 $maxTTL = $maxTTL ?: $this->getConfig()->get( 'CdnMaxAge' );
2155
2156 if ( $mtime === null || $mtime === false ) {
2157 return $minTTL; // entity does not exist
2158 }
2159
2160 $age = MWTimestamp::time() - wfTimestamp( TS_UNIX, $mtime );
2161 $adaptiveTTL = max( 0.9 * $age, $minTTL );
2162 $adaptiveTTL = min( $adaptiveTTL, $maxTTL );
2163
2164 $this->lowerCdnMaxage( (int)$adaptiveTTL );
2165 }
2166
2167 /**
2168 * Use enableClientCache(false) to force it to send nocache headers
2169 *
2170 * @param bool|null $state New value, or null to not set the value
2171 *
2172 * @return bool Old value
2173 */
2174 public function enableClientCache( $state ) {
2175 return wfSetVar( $this->mEnableClientCache, $state );
2176 }
2177
2178 /**
2179 * Get the list of cookie names that will influence the cache
2180 *
2181 * @return array
2182 */
2183 function getCacheVaryCookies() {
2184 if ( self::$cacheVaryCookies === null ) {
2185 $config = $this->getConfig();
2186 self::$cacheVaryCookies = array_values( array_unique( array_merge(
2187 SessionManager::singleton()->getVaryCookies(),
2188 [
2189 'forceHTTPS',
2190 ],
2191 $config->get( 'CacheVaryCookies' )
2192 ) ) );
2193 Hooks::run( 'GetCacheVaryCookies', [ $this, &self::$cacheVaryCookies ] );
2194 }
2195 return self::$cacheVaryCookies;
2196 }
2197
2198 /**
2199 * Check if the request has a cache-varying cookie header
2200 * If it does, it's very important that we don't allow public caching
2201 *
2202 * @return bool
2203 */
2204 function haveCacheVaryCookies() {
2205 $request = $this->getRequest();
2206 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2207 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2208 wfDebug( __METHOD__ . ": found $cookieName\n" );
2209 return true;
2210 }
2211 }
2212 wfDebug( __METHOD__ . ": no cache-varying cookies found\n" );
2213 return false;
2214 }
2215
2216 /**
2217 * Add an HTTP header that will influence on the cache
2218 *
2219 * @param string $header Header name
2220 * @param string[]|null $option Deprecated; formerly options for the
2221 * Key header, deprecated in 1.32 and removed in 1.34. See
2222 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2223 * for the list of formerly-valid options.
2224 */
2225 public function addVaryHeader( $header, array $option = null ) {
2226 if ( $option !== null && count( $option ) > 0 ) {
2227 wfDeprecated( 'addVaryHeader $option is ignored', '1.34' );
2228 }
2229 if ( !array_key_exists( $header, $this->mVaryHeader ) ) {
2230 $this->mVaryHeader[$header] = null;
2231 }
2232 }
2233
2234 /**
2235 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2236 * such as Accept-Encoding or Cookie
2237 *
2238 * @return string
2239 */
2240 public function getVaryHeader() {
2241 // If we vary on cookies, let's make sure it's always included here too.
2242 if ( $this->getCacheVaryCookies() ) {
2243 $this->addVaryHeader( 'Cookie' );
2244 }
2245
2246 foreach ( SessionManager::singleton()->getVaryHeaders() as $header => $options ) {
2247 $this->addVaryHeader( $header, $options );
2248 }
2249 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader ) );
2250 }
2251
2252 /**
2253 * Add an HTTP Link: header
2254 *
2255 * @param string $header Header value
2256 */
2257 public function addLinkHeader( $header ) {
2258 $this->mLinkHeader[] = $header;
2259 }
2260
2261 /**
2262 * Return a Link: header. Based on the values of $mLinkHeader.
2263 *
2264 * @return string
2265 */
2266 public function getLinkHeader() {
2267 if ( !$this->mLinkHeader ) {
2268 return false;
2269 }
2270
2271 return 'Link: ' . implode( ',', $this->mLinkHeader );
2272 }
2273
2274 /**
2275 * T23672: Add Accept-Language to Vary header if there's no 'variant' parameter in GET.
2276 *
2277 * For example:
2278 * /w/index.php?title=Main_page will vary based on Accept-Language; but
2279 * /w/index.php?title=Main_page&variant=zh-cn will not.
2280 */
2281 private function addAcceptLanguage() {
2282 $title = $this->getTitle();
2283 if ( !$title instanceof Title ) {
2284 return;
2285 }
2286
2287 $lang = $title->getPageLanguage();
2288 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2289 $this->addVaryHeader( 'Accept-Language' );
2290 }
2291 }
2292
2293 /**
2294 * Set a flag which will cause an X-Frame-Options header appropriate for
2295 * edit pages to be sent. The header value is controlled by
2296 * $wgEditPageFrameOptions.
2297 *
2298 * This is the default for special pages. If you display a CSRF-protected
2299 * form on an ordinary view page, then you need to call this function.
2300 *
2301 * @param bool $enable
2302 */
2303 public function preventClickjacking( $enable = true ) {
2304 $this->mPreventClickjacking = $enable;
2305 }
2306
2307 /**
2308 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2309 * This can be called from pages which do not contain any CSRF-protected
2310 * HTML form.
2311 */
2312 public function allowClickjacking() {
2313 $this->mPreventClickjacking = false;
2314 }
2315
2316 /**
2317 * Get the prevent-clickjacking flag
2318 *
2319 * @since 1.24
2320 * @return bool
2321 */
2322 public function getPreventClickjacking() {
2323 return $this->mPreventClickjacking;
2324 }
2325
2326 /**
2327 * Get the X-Frame-Options header value (without the name part), or false
2328 * if there isn't one. This is used by Skin to determine whether to enable
2329 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2330 *
2331 * @return string|false
2332 */
2333 public function getFrameOptions() {
2334 $config = $this->getConfig();
2335 if ( $config->get( 'BreakFrames' ) ) {
2336 return 'DENY';
2337 } elseif ( $this->mPreventClickjacking && $config->get( 'EditPageFrameOptions' ) ) {
2338 return $config->get( 'EditPageFrameOptions' );
2339 }
2340 return false;
2341 }
2342
2343 /**
2344 * Get the Origin-Trial header values. This is used to enable Chrome Origin
2345 * Trials: https://github.com/GoogleChrome/OriginTrials
2346 *
2347 * @return array
2348 */
2349 private function getOriginTrials() {
2350 $config = $this->getConfig();
2351
2352 return $config->get( 'OriginTrials' );
2353 }
2354
2355 private function getReportTo() {
2356 $config = $this->getConfig();
2357
2358 $expiry = $config->get( 'ReportToExpiry' );
2359
2360 if ( !$expiry ) {
2361 return false;
2362 }
2363
2364 $endpoints = $config->get( 'ReportToEndpoints' );
2365
2366 if ( !$endpoints ) {
2367 return false;
2368 }
2369
2370 $output = [ 'max_age' => $expiry, 'endpoints' => [] ];
2371
2372 foreach ( $endpoints as $endpoint ) {
2373 $output['endpoints'][] = [ 'url' => $endpoint ];
2374 }
2375
2376 return json_encode( $output, JSON_UNESCAPED_SLASHES );
2377 }
2378
2379 private function getFeaturePolicyReportOnly() {
2380 $config = $this->getConfig();
2381
2382 $features = $config->get( 'FeaturePolicyReportOnly' );
2383 return implode( ';', $features );
2384 }
2385
2386 /**
2387 * Send cache control HTTP headers
2388 */
2389 public function sendCacheControl() {
2390 $response = $this->getRequest()->response();
2391 $config = $this->getConfig();
2392
2393 $this->addVaryHeader( 'Cookie' );
2394 $this->addAcceptLanguage();
2395
2396 # don't serve compressed data to clients who can't handle it
2397 # maintain different caches for logged-in users and non-logged in ones
2398 $response->header( $this->getVaryHeader() );
2399
2400 if ( $this->mEnableClientCache ) {
2401 if (
2402 $config->get( 'UseCdn' ) &&
2403 !$response->hasCookies() &&
2404 !SessionManager::getGlobalSession()->isPersistent() &&
2405 !$this->isPrintable() &&
2406 $this->mCdnMaxage != 0 &&
2407 !$this->haveCacheVaryCookies()
2408 ) {
2409 if ( $config->get( 'UseESI' ) ) {
2410 wfDeprecated( '$wgUseESI = true', '1.33' );
2411 # We'll purge the proxy cache explicitly, but require end user agents
2412 # to revalidate against the proxy on each visit.
2413 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2414 wfDebug( __METHOD__ .
2415 ": proxy caching with ESI; {$this->mLastModified} **", 'private' );
2416 # start with a shorter timeout for initial testing
2417 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2418 $response->header(
2419 "Surrogate-Control: max-age={$config->get( 'CdnMaxAge' )}" .
2420 "+{$this->mCdnMaxage}, content=\"ESI/1.0\""
2421 );
2422 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2423 } else {
2424 # We'll purge the proxy cache for anons explicitly, but require end user agents
2425 # to revalidate against the proxy on each visit.
2426 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2427 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2428 wfDebug( __METHOD__ .
2429 ": local proxy caching; {$this->mLastModified} **", 'private' );
2430 # start with a shorter timeout for initial testing
2431 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2432 $response->header( "Cache-Control: " .
2433 "s-maxage={$this->mCdnMaxage}, must-revalidate, max-age=0" );
2434 }
2435 } else {
2436 # We do want clients to cache if they can, but they *must* check for updates
2437 # on revisiting the page.
2438 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **", 'private' );
2439 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2440 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2441 }
2442 if ( $this->mLastModified ) {
2443 $response->header( "Last-Modified: {$this->mLastModified}" );
2444 }
2445 } else {
2446 wfDebug( __METHOD__ . ": no caching **", 'private' );
2447
2448 # In general, the absence of a last modified header should be enough to prevent
2449 # the client from using its cache. We send a few other things just to make sure.
2450 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2451 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2452 $response->header( 'Pragma: no-cache' );
2453 }
2454 }
2455
2456 /**
2457 * Transfer styles and JavaScript modules from skin.
2458 *
2459 * @param Skin $sk to load modules for
2460 */
2461 public function loadSkinModules( $sk ) {
2462 foreach ( $sk->getDefaultModules() as $group => $modules ) {
2463 if ( $group === 'styles' ) {
2464 foreach ( $modules as $key => $moduleMembers ) {
2465 $this->addModuleStyles( $moduleMembers );
2466 }
2467 } else {
2468 $this->addModules( $modules );
2469 }
2470 }
2471 }
2472
2473 /**
2474 * Finally, all the text has been munged and accumulated into
2475 * the object, let's actually output it:
2476 *
2477 * @param bool $return Set to true to get the result as a string rather than sending it
2478 * @return string|null
2479 * @throws Exception
2480 * @throws FatalError
2481 * @throws MWException
2482 */
2483 public function output( $return = false ) {
2484 if ( $this->mDoNothing ) {
2485 return $return ? '' : null;
2486 }
2487
2488 $response = $this->getRequest()->response();
2489 $config = $this->getConfig();
2490
2491 if ( $this->mRedirect != '' ) {
2492 # Standards require redirect URLs to be absolute
2493 $this->mRedirect = wfExpandUrl( $this->mRedirect, PROTO_CURRENT );
2494
2495 $redirect = $this->mRedirect;
2496 $code = $this->mRedirectCode;
2497
2498 if ( Hooks::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2499 if ( $code == '301' || $code == '303' ) {
2500 if ( !$config->get( 'DebugRedirects' ) ) {
2501 $response->statusHeader( $code );
2502 }
2503 $this->mLastModified = wfTimestamp( TS_RFC2822 );
2504 }
2505 if ( $config->get( 'VaryOnXFP' ) ) {
2506 $this->addVaryHeader( 'X-Forwarded-Proto' );
2507 }
2508 $this->sendCacheControl();
2509
2510 $response->header( "Content-Type: text/html; charset=utf-8" );
2511 if ( $config->get( 'DebugRedirects' ) ) {
2512 $url = htmlspecialchars( $redirect );
2513 print "<!DOCTYPE html>\n<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2514 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2515 print "</body>\n</html>\n";
2516 } else {
2517 $response->header( 'Location: ' . $redirect );
2518 }
2519 }
2520
2521 return $return ? '' : null;
2522 } elseif ( $this->mStatusCode ) {
2523 $response->statusHeader( $this->mStatusCode );
2524 }
2525
2526 # Buffer output; final headers may depend on later processing
2527 ob_start();
2528
2529 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2530 $response->header( 'Content-language: ' .
2531 MediaWikiServices::getInstance()->getContentLanguage()->getHtmlCode() );
2532
2533 $linkHeader = $this->getLinkHeader();
2534 if ( $linkHeader ) {
2535 $response->header( $linkHeader );
2536 }
2537
2538 // Prevent framing, if requested
2539 $frameOptions = $this->getFrameOptions();
2540 if ( $frameOptions ) {
2541 $response->header( "X-Frame-Options: $frameOptions" );
2542 }
2543
2544 $originTrials = $this->getOriginTrials();
2545 foreach ( $originTrials as $originTrial ) {
2546 $response->header( "Origin-Trial: $originTrial", false );
2547 }
2548
2549 $reportTo = $this->getReportTo();
2550 if ( $reportTo ) {
2551 $response->header( "Report-To: $reportTo" );
2552 }
2553
2554 $featurePolicyReportOnly = $this->getFeaturePolicyReportOnly();
2555 if ( $featurePolicyReportOnly ) {
2556 $response->header( "Feature-Policy-Report-Only: $featurePolicyReportOnly" );
2557 }
2558
2559 ContentSecurityPolicy::sendHeaders( $this );
2560
2561 if ( $this->mArticleBodyOnly ) {
2562 echo $this->mBodytext;
2563 } else {
2564 // Enable safe mode if requested (T152169)
2565 if ( $this->getRequest()->getBool( 'safemode' ) ) {
2566 $this->disallowUserJs();
2567 }
2568
2569 $sk = $this->getSkin();
2570 $this->loadSkinModules( $sk );
2571
2572 MWDebug::addModules( $this );
2573
2574 // Avoid PHP 7.1 warning of passing $this by reference
2575 $outputPage = $this;
2576 // Hook that allows last minute changes to the output page, e.g.
2577 // adding of CSS or Javascript by extensions.
2578 Hooks::runWithoutAbort( 'BeforePageDisplay', [ &$outputPage, &$sk ] );
2579
2580 try {
2581 $sk->outputPage();
2582 } catch ( Exception $e ) {
2583 ob_end_clean(); // bug T129657
2584 throw $e;
2585 }
2586 }
2587
2588 try {
2589 // This hook allows last minute changes to final overall output by modifying output buffer
2590 Hooks::runWithoutAbort( 'AfterFinalPageOutput', [ $this ] );
2591 } catch ( Exception $e ) {
2592 ob_end_clean(); // bug T129657
2593 throw $e;
2594 }
2595
2596 $this->sendCacheControl();
2597
2598 if ( $return ) {
2599 return ob_get_clean();
2600 } else {
2601 ob_end_flush();
2602 return null;
2603 }
2604 }
2605
2606 /**
2607 * Prepare this object to display an error page; disable caching and
2608 * indexing, clear the current text and redirect, set the page's title
2609 * and optionally an custom HTML title (content of the "<title>" tag).
2610 *
2611 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2612 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2613 * optional, if not passed the "<title>" attribute will be
2614 * based on $pageTitle
2615 */
2616 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2617 $this->setPageTitle( $pageTitle );
2618 if ( $htmlTitle !== false ) {
2619 $this->setHTMLTitle( $htmlTitle );
2620 }
2621 $this->setRobotPolicy( 'noindex,nofollow' );
2622 $this->setArticleRelated( false );
2623 $this->enableClientCache( false );
2624 $this->mRedirect = '';
2625 $this->clearSubtitle();
2626 $this->clearHTML();
2627 }
2628
2629 /**
2630 * Output a standard error page
2631 *
2632 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2633 * showErrorPage( 'titlemsg', 'pagetextmsg', [ 'param1', 'param2' ] );
2634 * showErrorPage( 'titlemsg', $messageObject );
2635 * showErrorPage( $titleMessageObject, $messageObject );
2636 *
2637 * @param string|Message $title Message key (string) for page title, or a Message object
2638 * @param string|Message $msg Message key (string) for page text, or a Message object
2639 * @param array $params Message parameters; ignored if $msg is a Message object
2640 */
2641 public function showErrorPage( $title, $msg, $params = [] ) {
2642 if ( !$title instanceof Message ) {
2643 $title = $this->msg( $title );
2644 }
2645
2646 $this->prepareErrorPage( $title );
2647
2648 if ( $msg instanceof Message ) {
2649 if ( $params !== [] ) {
2650 trigger_error( 'Argument ignored: $params. The message parameters argument '
2651 . 'is discarded when the $msg argument is a Message object instead of '
2652 . 'a string.', E_USER_NOTICE );
2653 }
2654 $this->addHTML( $msg->parseAsBlock() );
2655 } else {
2656 $this->addWikiMsgArray( $msg, $params );
2657 }
2658
2659 $this->returnToMain();
2660 }
2661
2662 /**
2663 * Output a standard permission error page
2664 *
2665 * @param array $errors Error message keys or [key, param...] arrays
2666 * @param string|null $action Action that was denied or null if unknown
2667 */
2668 public function showPermissionsErrorPage( array $errors, $action = null ) {
2669 foreach ( $errors as $key => $error ) {
2670 $errors[$key] = (array)$error;
2671 }
2672
2673 // For some action (read, edit, create and upload), display a "login to do this action"
2674 // error if all of the following conditions are met:
2675 // 1. the user is not logged in
2676 // 2. the only error is insufficient permissions (i.e. no block or something else)
2677 // 3. the error can be avoided simply by logging in
2678 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2679 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2680 && ( $errors[0][0] == 'badaccess-groups' || $errors[0][0] == 'badaccess-group0' )
2681 && ( User::groupHasPermission( 'user', $action )
2682 || User::groupHasPermission( 'autoconfirmed', $action ) )
2683 ) {
2684 $displayReturnto = null;
2685
2686 # Due to T34276, if a user does not have read permissions,
2687 # $this->getTitle() will just give Special:Badtitle, which is
2688 # not especially useful as a returnto parameter. Use the title
2689 # from the request instead, if there was one.
2690 $request = $this->getRequest();
2691 $returnto = Title::newFromText( $request->getVal( 'title', '' ) );
2692 if ( $action == 'edit' ) {
2693 $msg = 'whitelistedittext';
2694 $displayReturnto = $returnto;
2695 } elseif ( $action == 'createpage' || $action == 'createtalk' ) {
2696 $msg = 'nocreatetext';
2697 } elseif ( $action == 'upload' ) {
2698 $msg = 'uploadnologintext';
2699 } else { # Read
2700 $msg = 'loginreqpagetext';
2701 $displayReturnto = Title::newMainPage();
2702 }
2703
2704 $query = [];
2705
2706 if ( $returnto ) {
2707 $query['returnto'] = $returnto->getPrefixedText();
2708
2709 if ( !$request->wasPosted() ) {
2710 $returntoquery = $request->getValues();
2711 unset( $returntoquery['title'] );
2712 unset( $returntoquery['returnto'] );
2713 unset( $returntoquery['returntoquery'] );
2714 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2715 }
2716 }
2717
2718 $services = MediaWikiServices::getInstance();
2719
2720 $title = SpecialPage::getTitleFor( 'Userlogin' );
2721 $linkRenderer = $services->getLinkRenderer();
2722 $loginUrl = $title->getLinkURL( $query, false, PROTO_RELATIVE );
2723 $loginLink = $linkRenderer->makeKnownLink(
2724 $title,
2725 $this->msg( 'loginreqlink' )->text(),
2726 [],
2727 $query
2728 );
2729
2730 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2731 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->params( $loginUrl )->parse() );
2732
2733 $permissionManager = $services->getPermissionManager();
2734
2735 # Don't return to a page the user can't read otherwise
2736 # we'll end up in a pointless loop
2737 if ( $displayReturnto && $permissionManager->userCan(
2738 'read', $this->getUser(), $displayReturnto
2739 ) ) {
2740 $this->returnToMain( null, $displayReturnto );
2741 }
2742 } else {
2743 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2744 $this->addWikiTextAsInterface( $this->formatPermissionsErrorMessage( $errors, $action ) );
2745 }
2746 }
2747
2748 /**
2749 * Display an error page indicating that a given version of MediaWiki is
2750 * required to use it
2751 *
2752 * @param mixed $version The version of MediaWiki needed to use the page
2753 */
2754 public function versionRequired( $version ) {
2755 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2756
2757 $this->addWikiMsg( 'versionrequiredtext', $version );
2758 $this->returnToMain();
2759 }
2760
2761 /**
2762 * Format a list of error messages
2763 *
2764 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2765 * @param string|null $action Action that was denied or null if unknown
2766 * @return string The wikitext error-messages, formatted into a list.
2767 */
2768 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2769 if ( $action == null ) {
2770 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2771 } else {
2772 $action_desc = $this->msg( "action-$action" )->plain();
2773 $text = $this->msg(
2774 'permissionserrorstext-withaction',
2775 count( $errors ),
2776 $action_desc
2777 )->plain() . "\n\n";
2778 }
2779
2780 if ( count( $errors ) > 1 ) {
2781 $text .= '<ul class="permissions-errors">' . "\n";
2782
2783 foreach ( $errors as $error ) {
2784 $text .= '<li>';
2785 $text .= $this->msg( ...$error )->plain();
2786 $text .= "</li>\n";
2787 }
2788 $text .= '</ul>';
2789 } else {
2790 $text .= "<div class=\"permissions-errors\">\n" .
2791 $this->msg( ...reset( $errors ) )->plain() .
2792 "\n</div>";
2793 }
2794
2795 return $text;
2796 }
2797
2798 /**
2799 * Show a warning about replica DB lag
2800 *
2801 * If the lag is higher than $wgSlaveLagCritical seconds,
2802 * then the warning is a bit more obvious. If the lag is
2803 * lower than $wgSlaveLagWarning, then no warning is shown.
2804 *
2805 * @param int $lag Replica lag
2806 */
2807 public function showLagWarning( $lag ) {
2808 $config = $this->getConfig();
2809 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2810 $lag = floor( $lag ); // floor to avoid nano seconds to display
2811 $message = $lag < $config->get( 'SlaveLagCritical' )
2812 ? 'lag-warn-normal'
2813 : 'lag-warn-high';
2814 $wrap = Html::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2815 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2816 }
2817 }
2818
2819 /**
2820 * Output an error page
2821 *
2822 * @note FatalError exception class provides an alternative.
2823 * @param string $message Error to output. Must be escaped for HTML.
2824 */
2825 public function showFatalError( $message ) {
2826 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2827
2828 $this->addHTML( $message );
2829 }
2830
2831 /**
2832 * Add a "return to" link pointing to a specified title
2833 *
2834 * @param Title $title Title to link
2835 * @param array $query Query string parameters
2836 * @param string|null $text Text of the link (input is not escaped)
2837 * @param array $options Options array to pass to Linker
2838 */
2839 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
2840 $linkRenderer = MediaWikiServices::getInstance()
2841 ->getLinkRendererFactory()->createFromLegacyOptions( $options );
2842 $link = $this->msg( 'returnto' )->rawParams(
2843 $linkRenderer->makeLink( $title, $text, [], $query ) )->escaped();
2844 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2845 }
2846
2847 /**
2848 * Add a "return to" link pointing to a specified title,
2849 * or the title indicated in the request, or else the main page
2850 *
2851 * @param mixed|null $unused
2852 * @param Title|string|null $returnto Title or String to return to
2853 * @param string|null $returntoquery Query string for the return to link
2854 */
2855 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2856 if ( $returnto == null ) {
2857 $returnto = $this->getRequest()->getText( 'returnto' );
2858 }
2859
2860 if ( $returntoquery == null ) {
2861 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2862 }
2863
2864 if ( $returnto === '' ) {
2865 $returnto = Title::newMainPage();
2866 }
2867
2868 if ( is_object( $returnto ) ) {
2869 $titleObj = $returnto;
2870 } else {
2871 $titleObj = Title::newFromText( $returnto );
2872 }
2873 // We don't want people to return to external interwiki. That
2874 // might potentially be used as part of a phishing scheme
2875 if ( !is_object( $titleObj ) || $titleObj->isExternal() ) {
2876 $titleObj = Title::newMainPage();
2877 }
2878
2879 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2880 }
2881
2882 private function getRlClientContext() {
2883 if ( !$this->rlClientContext ) {
2884 $query = ResourceLoader::makeLoaderQuery(
2885 [], // modules; not relevant
2886 $this->getLanguage()->getCode(),
2887 $this->getSkin()->getSkinName(),
2888 $this->getUser()->isLoggedIn() ? $this->getUser()->getName() : null,
2889 null, // version; not relevant
2890 ResourceLoader::inDebugMode(),
2891 null, // only; not relevant
2892 $this->isPrintable(),
2893 $this->getRequest()->getBool( 'handheld' )
2894 );
2895 $this->rlClientContext = new ResourceLoaderContext(
2896 $this->getResourceLoader(),
2897 new FauxRequest( $query )
2898 );
2899 if ( $this->contentOverrideCallbacks ) {
2900 $this->rlClientContext = new DerivativeResourceLoaderContext( $this->rlClientContext );
2901 $this->rlClientContext->setContentOverrideCallback( function ( Title $title ) {
2902 foreach ( $this->contentOverrideCallbacks as $callback ) {
2903 $content = $callback( $title );
2904 if ( $content !== null ) {
2905 $text = ContentHandler::getContentText( $content );
2906 if ( strpos( $text, '</script>' ) !== false ) {
2907 // Proactively replace this so that we can display a message
2908 // to the user, instead of letting it go to Html::inlineScript(),
2909 // where it would be considered a server-side issue.
2910 $titleFormatted = $title->getPrefixedText();
2911 $content = new JavaScriptContent(
2912 Xml::encodeJsCall( 'mw.log.error', [
2913 "Cannot preview $titleFormatted due to script-closing tag."
2914 ] )
2915 );
2916 }
2917 return $content;
2918 }
2919 }
2920 return null;
2921 } );
2922 }
2923 }
2924 return $this->rlClientContext;
2925 }
2926
2927 /**
2928 * Call this to freeze the module queue and JS config and create a formatter.
2929 *
2930 * Depending on the Skin, this may get lazy-initialised in either headElement() or
2931 * getBottomScripts(). See SkinTemplate::prepareQuickTemplate(). Calling this too early may
2932 * cause unexpected side-effects since disallowUserJs() may be called at any time to change
2933 * the module filters retroactively. Skins and extension hooks may also add modules until very
2934 * late in the request lifecycle.
2935 *
2936 * @return ResourceLoaderClientHtml
2937 */
2938 public function getRlClient() {
2939 if ( !$this->rlClient ) {
2940 $context = $this->getRlClientContext();
2941 $rl = $this->getResourceLoader();
2942 $this->addModules( [
2943 'user',
2944 'user.options',
2945 'user.tokens',
2946 ] );
2947 $this->addModuleStyles( [
2948 'site.styles',
2949 'noscript',
2950 'user.styles',
2951 ] );
2952 $this->getSkin()->setupSkinUserCss( $this );
2953
2954 // Prepare exempt modules for buildExemptModules()
2955 $exemptGroups = [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ];
2956 $exemptStates = [];
2957 $moduleStyles = $this->getModuleStyles( /*filter*/ true );
2958
2959 // Preload getTitleInfo for isKnownEmpty calls below and in ResourceLoaderClientHtml
2960 // Separate user-specific batch for improved cache-hit ratio.
2961 $userBatch = [ 'user.styles', 'user' ];
2962 $siteBatch = array_diff( $moduleStyles, $userBatch );
2963 $dbr = wfGetDB( DB_REPLICA );
2964 ResourceLoaderWikiModule::preloadTitleInfo( $context, $dbr, $siteBatch );
2965 ResourceLoaderWikiModule::preloadTitleInfo( $context, $dbr, $userBatch );
2966
2967 // Filter out modules handled by buildExemptModules()
2968 $moduleStyles = array_filter( $moduleStyles,
2969 function ( $name ) use ( $rl, $context, &$exemptGroups, &$exemptStates ) {
2970 $module = $rl->getModule( $name );
2971 if ( $module ) {
2972 $group = $module->getGroup();
2973 if ( isset( $exemptGroups[$group] ) ) {
2974 $exemptStates[$name] = 'ready';
2975 if ( !$module->isKnownEmpty( $context ) ) {
2976 // E.g. Don't output empty <styles>
2977 $exemptGroups[$group][] = $name;
2978 }
2979 return false;
2980 }
2981 }
2982 return true;
2983 }
2984 );
2985 $this->rlExemptStyleModules = $exemptGroups;
2986
2987 $rlClient = new ResourceLoaderClientHtml( $context, [
2988 'target' => $this->getTarget(),
2989 'nonce' => $this->getCSPNonce(),
2990 // When 'safemode', disallowUserJs(), or reduceAllowedModules() is used
2991 // to only restrict modules to ORIGIN_CORE (ie. disallow ORIGIN_USER), the list of
2992 // modules enqueud for loading on this page is filtered to just those.
2993 // However, to make sure we also apply the restriction to dynamic dependencies and
2994 // lazy-loaded modules at run-time on the client-side, pass 'safemode' down to the
2995 // StartupModule so that the client-side registry will not contain any restricted
2996 // modules either. (T152169, T185303)
2997 'safemode' => ( $this->getAllowedModules( ResourceLoaderModule::TYPE_COMBINED )
2998 <= ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL
2999 ) ? '1' : null,
3000 ] );
3001 $rlClient->setConfig( $this->getJSVars() );
3002 $rlClient->setModules( $this->getModules( /*filter*/ true ) );
3003 $rlClient->setModuleStyles( $moduleStyles );
3004 $rlClient->setExemptStates( $exemptStates );
3005 $this->rlClient = $rlClient;
3006 }
3007 return $this->rlClient;
3008 }
3009
3010 /**
3011 * @param Skin $sk The given Skin
3012 * @param bool $includeStyle Unused
3013 * @return string The doctype, opening "<html>", and head element.
3014 */
3015 public function headElement( Skin $sk, $includeStyle = true ) {
3016 $config = $this->getConfig();
3017 $userdir = $this->getLanguage()->getDir();
3018 $sitedir = MediaWikiServices::getInstance()->getContentLanguage()->getDir();
3019
3020 $pieces = [];
3021 $pieces[] = Html::htmlHeader( Sanitizer::mergeAttributes(
3022 $this->getRlClient()->getDocumentAttributes(),
3023 $sk->getHtmlElementAttributes()
3024 ) );
3025 $pieces[] = Html::openElement( 'head' );
3026
3027 if ( $this->getHTMLTitle() == '' ) {
3028 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
3029 }
3030
3031 if ( !Html::isXmlMimeType( $config->get( 'MimeType' ) ) ) {
3032 // Add <meta charset="UTF-8">
3033 // This should be before <title> since it defines the charset used by
3034 // text including the text inside <title>.
3035 // The spec recommends defining XHTML5's charset using the XML declaration
3036 // instead of meta.
3037 // Our XML declaration is output by Html::htmlHeader.
3038 // https://html.spec.whatwg.org/multipage/semantics.html#attr-meta-http-equiv-content-type
3039 // https://html.spec.whatwg.org/multipage/semantics.html#charset
3040 $pieces[] = Html::element( 'meta', [ 'charset' => 'UTF-8' ] );
3041 }
3042
3043 $pieces[] = Html::element( 'title', null, $this->getHTMLTitle() );
3044 $pieces[] = $this->getRlClient()->getHeadHtml();
3045 $pieces[] = $this->buildExemptModules();
3046 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
3047 $pieces = array_merge( $pieces, array_values( $this->mHeadItems ) );
3048
3049 // This library is intended to run on older browsers that MediaWiki no longer
3050 // supports as Grade A. For these Grade C browsers, we provide an experience
3051 // using only HTML and CSS. But, where standards-compliant browsers are able to
3052 // style unknown HTML elements without issue, old IE ignores these styles.
3053 // The html5shiv library fixes that.
3054 // Use an IE conditional comment to serve the script only to old IE
3055 $shivUrl = $config->get( 'ResourceBasePath' ) . '/resources/lib/html5shiv/html5shiv.js';
3056 $pieces[] = '<!--[if lt IE 9]>' .
3057 Html::linkedScript( $shivUrl, $this->getCSPNonce() ) .
3058 '<![endif]-->';
3059
3060 $pieces[] = Html::closeElement( 'head' );
3061
3062 $bodyClasses = $this->mAdditionalBodyClasses;
3063 $bodyClasses[] = 'mediawiki';
3064
3065 # Classes for LTR/RTL directionality support
3066 $bodyClasses[] = $userdir;
3067 $bodyClasses[] = "sitedir-$sitedir";
3068
3069 $underline = $this->getUser()->getOption( 'underline' );
3070 if ( $underline < 2 ) {
3071 // The following classes can be used here:
3072 // * mw-underline-always
3073 // * mw-underline-never
3074 $bodyClasses[] = 'mw-underline-' . ( $underline ? 'always' : 'never' );
3075 }
3076
3077 if ( $this->getLanguage()->capitalizeAllNouns() ) {
3078 # A <body> class is probably not the best way to do this . . .
3079 $bodyClasses[] = 'capitalize-all-nouns';
3080 }
3081
3082 // Parser feature migration class
3083 // The idea is that this will eventually be removed, after the wikitext
3084 // which requires it is cleaned up.
3085 $bodyClasses[] = 'mw-hide-empty-elt';
3086
3087 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
3088 $bodyClasses[] = 'skin-' . Sanitizer::escapeClass( $sk->getSkinName() );
3089 $bodyClasses[] =
3090 'action-' . Sanitizer::escapeClass( Action::getActionName( $this->getContext() ) );
3091
3092 $bodyAttrs = [];
3093 // While the implode() is not strictly needed, it's used for backwards compatibility
3094 // (this used to be built as a string and hooks likely still expect that).
3095 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
3096
3097 // Allow skins and extensions to add body attributes they need
3098 $sk->addToBodyAttributes( $this, $bodyAttrs );
3099 Hooks::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
3100
3101 $pieces[] = Html::openElement( 'body', $bodyAttrs );
3102
3103 return self::combineWrappedStrings( $pieces );
3104 }
3105
3106 /**
3107 * Get a ResourceLoader object associated with this OutputPage
3108 *
3109 * @return ResourceLoader
3110 */
3111 public function getResourceLoader() {
3112 if ( is_null( $this->mResourceLoader ) ) {
3113 // Lazy-initialise as needed
3114 $this->mResourceLoader = MediaWikiServices::getInstance()->getResourceLoader();
3115 }
3116 return $this->mResourceLoader;
3117 }
3118
3119 /**
3120 * Explicily load or embed modules on a page.
3121 *
3122 * @param array|string $modules One or more module names
3123 * @param string $only ResourceLoaderModule TYPE_ class constant
3124 * @param array $extraQuery [optional] Array with extra query parameters for the request
3125 * @return string|WrappedStringList HTML
3126 */
3127 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
3128 // Apply 'target' and 'origin' filters
3129 $modules = $this->filterModules( (array)$modules, null, $only );
3130
3131 return ResourceLoaderClientHtml::makeLoad(
3132 $this->getRlClientContext(),
3133 $modules,
3134 $only,
3135 $extraQuery,
3136 $this->getCSPNonce()
3137 );
3138 }
3139
3140 /**
3141 * Combine WrappedString chunks and filter out empty ones
3142 *
3143 * @param array $chunks
3144 * @return string|WrappedStringList HTML
3145 */
3146 protected static function combineWrappedStrings( array $chunks ) {
3147 // Filter out empty values
3148 $chunks = array_filter( $chunks, 'strlen' );
3149 return WrappedString::join( "\n", $chunks );
3150 }
3151
3152 /**
3153 * JS stuff to put at the bottom of the `<body>`.
3154 * These are legacy scripts ($this->mScripts), and user JS.
3155 *
3156 * @return string|WrappedStringList HTML
3157 */
3158 public function getBottomScripts() {
3159 $chunks = [];
3160 $chunks[] = $this->getRlClient()->getBodyHtml();
3161
3162 // Legacy non-ResourceLoader scripts
3163 $chunks[] = $this->mScripts;
3164
3165 if ( $this->limitReportJSData ) {
3166 $chunks[] = ResourceLoader::makeInlineScript(
3167 ResourceLoader::makeConfigSetScript(
3168 [ 'wgPageParseReport' => $this->limitReportJSData ]
3169 ),
3170 $this->getCSPNonce()
3171 );
3172 }
3173
3174 return self::combineWrappedStrings( $chunks );
3175 }
3176
3177 /**
3178 * Get the javascript config vars to include on this page
3179 *
3180 * @return array Array of javascript config vars
3181 * @since 1.23
3182 */
3183 public function getJsConfigVars() {
3184 return $this->mJsConfigVars;
3185 }
3186
3187 /**
3188 * Add one or more variables to be set in mw.config in JavaScript
3189 *
3190 * @param string|array $keys Key or array of key/value pairs
3191 * @param mixed|null $value [optional] Value of the configuration variable
3192 */
3193 public function addJsConfigVars( $keys, $value = null ) {
3194 if ( is_array( $keys ) ) {
3195 foreach ( $keys as $key => $value ) {
3196 $this->mJsConfigVars[$key] = $value;
3197 }
3198 return;
3199 }
3200
3201 $this->mJsConfigVars[$keys] = $value;
3202 }
3203
3204 /**
3205 * Get an array containing the variables to be set in mw.config in JavaScript.
3206 *
3207 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3208 * - in other words, page-independent/site-wide variables (without state).
3209 * You will only be adding bloat to the html page and causing page caches to
3210 * have to be purged on configuration changes.
3211 * @return array
3212 */
3213 public function getJSVars() {
3214 $curRevisionId = 0;
3215 $articleId = 0;
3216 $canonicalSpecialPageName = false; # T23115
3217 $services = MediaWikiServices::getInstance();
3218
3219 $title = $this->getTitle();
3220 $ns = $title->getNamespace();
3221 $nsInfo = MediaWikiServices::getInstance()->getNamespaceInfo();
3222 $canonicalNamespace = $nsInfo->exists( $ns )
3223 ? $nsInfo->getCanonicalName( $ns )
3224 : $title->getNsText();
3225
3226 $sk = $this->getSkin();
3227 // Get the relevant title so that AJAX features can use the correct page name
3228 // when making API requests from certain special pages (T36972).
3229 $relevantTitle = $sk->getRelevantTitle();
3230 $relevantUser = $sk->getRelevantUser();
3231
3232 if ( $ns == NS_SPECIAL ) {
3233 list( $canonicalSpecialPageName, /*...*/ ) =
3234 $services->getSpecialPageFactory()->
3235 resolveAlias( $title->getDBkey() );
3236 } elseif ( $this->canUseWikiPage() ) {
3237 $wikiPage = $this->getWikiPage();
3238 $curRevisionId = $wikiPage->getLatest();
3239 $articleId = $wikiPage->getId();
3240 }
3241
3242 $lang = $title->getPageViewLanguage();
3243
3244 // Pre-process information
3245 $separatorTransTable = $lang->separatorTransformTable();
3246 $separatorTransTable = $separatorTransTable ?: [];
3247 $compactSeparatorTransTable = [
3248 implode( "\t", array_keys( $separatorTransTable ) ),
3249 implode( "\t", $separatorTransTable ),
3250 ];
3251 $digitTransTable = $lang->digitTransformTable();
3252 $digitTransTable = $digitTransTable ?: [];
3253 $compactDigitTransTable = [
3254 implode( "\t", array_keys( $digitTransTable ) ),
3255 implode( "\t", $digitTransTable ),
3256 ];
3257
3258 $user = $this->getUser();
3259
3260 $vars = [
3261 'wgCanonicalNamespace' => $canonicalNamespace,
3262 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3263 'wgNamespaceNumber' => $title->getNamespace(),
3264 'wgPageName' => $title->getPrefixedDBkey(),
3265 'wgTitle' => $title->getText(),
3266 'wgCurRevisionId' => $curRevisionId,
3267 'wgRevisionId' => (int)$this->getRevisionId(),
3268 'wgArticleId' => $articleId,
3269 'wgIsArticle' => $this->isArticle(),
3270 'wgIsRedirect' => $title->isRedirect(),
3271 'wgAction' => Action::getActionName( $this->getContext() ),
3272 'wgUserName' => $user->isAnon() ? null : $user->getName(),
3273 'wgUserGroups' => $user->getEffectiveGroups(),
3274 'wgCategories' => $this->getCategories(),
3275 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3276 'wgPageContentLanguage' => $lang->getCode(),
3277 'wgPageContentModel' => $title->getContentModel(),
3278 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3279 'wgDigitTransformTable' => $compactDigitTransTable,
3280 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3281 'wgMonthNames' => $lang->getMonthNamesArray(),
3282 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3283 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3284 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3285 'wgRequestId' => WebRequest::getRequestId(),
3286 'wgCSPNonce' => $this->getCSPNonce(),
3287 ];
3288
3289 if ( $user->isLoggedIn() ) {
3290 $vars['wgUserId'] = $user->getId();
3291 $vars['wgUserEditCount'] = $user->getEditCount();
3292 $userReg = $user->getRegistration();
3293 $vars['wgUserRegistration'] = $userReg ? wfTimestamp( TS_UNIX, $userReg ) * 1000 : null;
3294 // Get the revision ID of the oldest new message on the user's talk
3295 // page. This can be used for constructing new message alerts on
3296 // the client side.
3297 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3298 }
3299
3300 $contLang = $services->getContentLanguage();
3301 if ( $contLang->hasVariants() ) {
3302 $vars['wgUserVariant'] = $contLang->getPreferredVariant();
3303 }
3304 // Same test as SkinTemplate
3305 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3306 && ( $title->exists() || $title->quickUserCan( 'create', $user ) );
3307
3308 $vars['wgRelevantPageIsProbablyEditable'] = $relevantTitle
3309 && $relevantTitle->quickUserCan( 'edit', $user )
3310 && ( $relevantTitle->exists() || $relevantTitle->quickUserCan( 'create', $user ) );
3311
3312 foreach ( $title->getRestrictionTypes() as $type ) {
3313 // Following keys are set in $vars:
3314 // wgRestrictionCreate, wgRestrictionEdit, wgRestrictionMove, wgRestrictionUpload
3315 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3316 }
3317
3318 if ( $title->isMainPage() ) {
3319 $vars['wgIsMainPage'] = true;
3320 }
3321
3322 if ( $this->mRedirectedFrom ) {
3323 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom->getPrefixedDBkey();
3324 }
3325
3326 if ( $relevantUser ) {
3327 $vars['wgRelevantUserName'] = $relevantUser->getName();
3328 }
3329
3330 // Allow extensions to add their custom variables to the mw.config map.
3331 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3332 // page-dependant but site-wide (without state).
3333 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3334 Hooks::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3335
3336 // Merge in variables from addJsConfigVars last
3337 return array_merge( $vars, $this->getJsConfigVars() );
3338 }
3339
3340 /**
3341 * To make it harder for someone to slip a user a fake
3342 * JavaScript or CSS preview, a random token
3343 * is associated with the login session. If it's not
3344 * passed back with the preview request, we won't render
3345 * the code.
3346 *
3347 * @return bool
3348 */
3349 public function userCanPreview() {
3350 $request = $this->getRequest();
3351 if (
3352 $request->getVal( 'action' ) !== 'submit' ||
3353 !$request->wasPosted()
3354 ) {
3355 return false;
3356 }
3357
3358 $user = $this->getUser();
3359
3360 if ( !$user->isLoggedIn() ) {
3361 // Anons have predictable edit tokens
3362 return false;
3363 }
3364 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3365 return false;
3366 }
3367
3368 $title = $this->getTitle();
3369 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3370 if ( count( $errors ) !== 0 ) {
3371 return false;
3372 }
3373
3374 return true;
3375 }
3376
3377 /**
3378 * @return array Array in format "link name or number => 'link html'".
3379 */
3380 public function getHeadLinksArray() {
3381 global $wgVersion;
3382
3383 $tags = [];
3384 $config = $this->getConfig();
3385
3386 $canonicalUrl = $this->mCanonicalUrl;
3387
3388 $tags['meta-generator'] = Html::element( 'meta', [
3389 'name' => 'generator',
3390 'content' => "MediaWiki $wgVersion",
3391 ] );
3392
3393 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3394 // Per https://w3c.github.io/webappsec-referrer-policy/#unknown-policy-values
3395 // fallbacks should come before the primary value so we need to reverse the array.
3396 foreach ( array_reverse( (array)$config->get( 'ReferrerPolicy' ) ) as $i => $policy ) {
3397 $tags["meta-referrer-$i"] = Html::element( 'meta', [
3398 'name' => 'referrer',
3399 'content' => $policy,
3400 ] );
3401 }
3402 }
3403
3404 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3405 if ( $p !== 'index,follow' ) {
3406 // http://www.robotstxt.org/wc/meta-user.html
3407 // Only show if it's different from the default robots policy
3408 $tags['meta-robots'] = Html::element( 'meta', [
3409 'name' => 'robots',
3410 'content' => $p,
3411 ] );
3412 }
3413
3414 foreach ( $this->mMetatags as $tag ) {
3415 if ( strncasecmp( $tag[0], 'http:', 5 ) === 0 ) {
3416 $a = 'http-equiv';
3417 $tag[0] = substr( $tag[0], 5 );
3418 } elseif ( strncasecmp( $tag[0], 'og:', 3 ) === 0 ) {
3419 $a = 'property';
3420 } else {
3421 $a = 'name';
3422 }
3423 $tagName = "meta-{$tag[0]}";
3424 if ( isset( $tags[$tagName] ) ) {
3425 $tagName .= $tag[1];
3426 }
3427 $tags[$tagName] = Html::element( 'meta',
3428 [
3429 $a => $tag[0],
3430 'content' => $tag[1]
3431 ]
3432 );
3433 }
3434
3435 foreach ( $this->mLinktags as $tag ) {
3436 $tags[] = Html::element( 'link', $tag );
3437 }
3438
3439 # Universal edit button
3440 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3441 $user = $this->getUser();
3442 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3443 && ( $this->getTitle()->exists() ||
3444 $this->getTitle()->quickUserCan( 'create', $user ) )
3445 ) {
3446 // Original UniversalEditButton
3447 $msg = $this->msg( 'edit' )->text();
3448 $tags['universal-edit-button'] = Html::element( 'link', [
3449 'rel' => 'alternate',
3450 'type' => 'application/x-wiki',
3451 'title' => $msg,
3452 'href' => $this->getTitle()->getEditURL(),
3453 ] );
3454 // Alternate edit link
3455 $tags['alternative-edit'] = Html::element( 'link', [
3456 'rel' => 'edit',
3457 'title' => $msg,
3458 'href' => $this->getTitle()->getEditURL(),
3459 ] );
3460 }
3461 }
3462
3463 # Generally the order of the favicon and apple-touch-icon links
3464 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3465 # uses whichever one appears later in the HTML source. Make sure
3466 # apple-touch-icon is specified first to avoid this.
3467 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3468 $tags['apple-touch-icon'] = Html::element( 'link', [
3469 'rel' => 'apple-touch-icon',
3470 'href' => $config->get( 'AppleTouchIcon' )
3471 ] );
3472 }
3473
3474 if ( $config->get( 'Favicon' ) !== false ) {
3475 $tags['favicon'] = Html::element( 'link', [
3476 'rel' => 'shortcut icon',
3477 'href' => $config->get( 'Favicon' )
3478 ] );
3479 }
3480
3481 # OpenSearch description link
3482 $tags['opensearch'] = Html::element( 'link', [
3483 'rel' => 'search',
3484 'type' => 'application/opensearchdescription+xml',
3485 'href' => wfScript( 'opensearch_desc' ),
3486 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3487 ] );
3488
3489 # Real Simple Discovery link, provides auto-discovery information
3490 # for the MediaWiki API (and potentially additional custom API
3491 # support such as WordPress or Twitter-compatible APIs for a
3492 # blogging extension, etc)
3493 $tags['rsd'] = Html::element( 'link', [
3494 'rel' => 'EditURI',
3495 'type' => 'application/rsd+xml',
3496 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3497 // Whether RSD accepts relative or protocol-relative URLs is completely
3498 // undocumented, though.
3499 'href' => wfExpandUrl( wfAppendQuery(
3500 wfScript( 'api' ),
3501 [ 'action' => 'rsd' ] ),
3502 PROTO_RELATIVE
3503 ),
3504 ] );
3505
3506 # Language variants
3507 if ( !$config->get( 'DisableLangConversion' ) ) {
3508 $lang = $this->getTitle()->getPageLanguage();
3509 if ( $lang->hasVariants() ) {
3510 $variants = $lang->getVariants();
3511 foreach ( $variants as $variant ) {
3512 $tags["variant-$variant"] = Html::element( 'link', [
3513 'rel' => 'alternate',
3514 'hreflang' => LanguageCode::bcp47( $variant ),
3515 'href' => $this->getTitle()->getLocalURL(
3516 [ 'variant' => $variant ] )
3517 ]
3518 );
3519 }
3520 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3521 $tags["variant-x-default"] = Html::element( 'link', [
3522 'rel' => 'alternate',
3523 'hreflang' => 'x-default',
3524 'href' => $this->getTitle()->getLocalURL() ] );
3525 }
3526 }
3527
3528 # Copyright
3529 if ( $this->copyrightUrl !== null ) {
3530 $copyright = $this->copyrightUrl;
3531 } else {
3532 $copyright = '';
3533 if ( $config->get( 'RightsPage' ) ) {
3534 $copy = Title::newFromText( $config->get( 'RightsPage' ) );
3535
3536 if ( $copy ) {
3537 $copyright = $copy->getLocalURL();
3538 }
3539 }
3540
3541 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3542 $copyright = $config->get( 'RightsUrl' );
3543 }
3544 }
3545
3546 if ( $copyright ) {
3547 $tags['copyright'] = Html::element( 'link', [
3548 'rel' => 'license',
3549 'href' => $copyright ]
3550 );
3551 }
3552
3553 # Feeds
3554 if ( $config->get( 'Feed' ) ) {
3555 $feedLinks = [];
3556
3557 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3558 # Use the page name for the title. In principle, this could
3559 # lead to issues with having the same name for different feeds
3560 # corresponding to the same page, but we can't avoid that at
3561 # this low a level.
3562
3563 $feedLinks[] = $this->feedLink(
3564 $format,
3565 $link,
3566 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3567 $this->msg(
3568 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3569 )->text()
3570 );
3571 }
3572
3573 # Recent changes feed should appear on every page (except recentchanges,
3574 # that would be redundant). Put it after the per-page feed to avoid
3575 # changing existing behavior. It's still available, probably via a
3576 # menu in your browser. Some sites might have a different feed they'd
3577 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3578 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3579 # If so, use it instead.
3580 $sitename = $config->get( 'Sitename' );
3581 $overrideSiteFeed = $config->get( 'OverrideSiteFeed' );
3582 if ( $overrideSiteFeed ) {
3583 foreach ( $overrideSiteFeed as $type => $feedUrl ) {
3584 // Note, this->feedLink escapes the url.
3585 $feedLinks[] = $this->feedLink(
3586 $type,
3587 $feedUrl,
3588 $this->msg( "site-{$type}-feed", $sitename )->text()
3589 );
3590 }
3591 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3592 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
3593 foreach ( $this->getAdvertisedFeedTypes() as $format ) {
3594 $feedLinks[] = $this->feedLink(
3595 $format,
3596 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3597 # For grep: 'site-rss-feed', 'site-atom-feed'
3598 $this->msg( "site-{$format}-feed", $sitename )->text()
3599 );
3600 }
3601 }
3602
3603 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3604 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3605 # use OutputPage::addFeedLink() instead.
3606 Hooks::run( 'AfterBuildFeedLinks', [ &$feedLinks ] );
3607
3608 $tags += $feedLinks;
3609 }
3610
3611 # Canonical URL
3612 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3613 if ( $canonicalUrl !== false ) {
3614 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL );
3615 } elseif ( $this->isArticleRelated() ) {
3616 // This affects all requests where "setArticleRelated" is true. This is
3617 // typically all requests that show content (query title, curid, oldid, diff),
3618 // and all wikipage actions (edit, delete, purge, info, history etc.).
3619 // It does not apply to File pages and Special pages.
3620 // 'history' and 'info' actions address page metadata rather than the page
3621 // content itself, so they may not be canonicalized to the view page url.
3622 // TODO: this ought to be better encapsulated in the Action class.
3623 $action = Action::getActionName( $this->getContext() );
3624 if ( in_array( $action, [ 'history', 'info' ] ) ) {
3625 $query = "action={$action}";
3626 } else {
3627 $query = '';
3628 }
3629 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3630 } else {
3631 $reqUrl = $this->getRequest()->getRequestURL();
3632 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL );
3633 }
3634 }
3635 if ( $canonicalUrl !== false ) {
3636 $tags[] = Html::element( 'link', [
3637 'rel' => 'canonical',
3638 'href' => $canonicalUrl
3639 ] );
3640 }
3641
3642 // Allow extensions to add, remove and/or otherwise manipulate these links
3643 // If you want only to *add* <head> links, please use the addHeadItem()
3644 // (or addHeadItems() for multiple items) method instead.
3645 // This hook is provided as a last resort for extensions to modify these
3646 // links before the output is sent to client.
3647 Hooks::run( 'OutputPageAfterGetHeadLinksArray', [ &$tags, $this ] );
3648
3649 return $tags;
3650 }
3651
3652 /**
3653 * Generate a "<link rel/>" for a feed.
3654 *
3655 * @param string $type Feed type
3656 * @param string $url URL to the feed
3657 * @param string $text Value of the "title" attribute
3658 * @return string HTML fragment
3659 */
3660 private function feedLink( $type, $url, $text ) {
3661 return Html::element( 'link', [
3662 'rel' => 'alternate',
3663 'type' => "application/$type+xml",
3664 'title' => $text,
3665 'href' => $url ]
3666 );
3667 }
3668
3669 /**
3670 * Add a local or specified stylesheet, with the given media options.
3671 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3672 *
3673 * @param string $style URL to the file
3674 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3675 * @param string $condition For IE conditional comments, specifying an IE version
3676 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3677 */
3678 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3679 $options = [];
3680 if ( $media ) {
3681 $options['media'] = $media;
3682 }
3683 if ( $condition ) {
3684 $options['condition'] = $condition;
3685 }
3686 if ( $dir ) {
3687 $options['dir'] = $dir;
3688 }
3689 $this->styles[$style] = $options;
3690 }
3691
3692 /**
3693 * Adds inline CSS styles
3694 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3695 *
3696 * @param mixed $style_css Inline CSS
3697 * @param string $flip Set to 'flip' to flip the CSS if needed
3698 */
3699 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3700 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3701 # If wanted, and the interface is right-to-left, flip the CSS
3702 $style_css = CSSJanus::transform( $style_css, true, false );
3703 }
3704 $this->mInlineStyles .= Html::inlineStyle( $style_css );
3705 }
3706
3707 /**
3708 * Build exempt modules and legacy non-ResourceLoader styles.
3709 *
3710 * @return string|WrappedStringList HTML
3711 */
3712 protected function buildExemptModules() {
3713 $chunks = [];
3714
3715 // Requirements:
3716 // - Within modules provided by the software (core, skin, extensions),
3717 // styles from skin stylesheets should be overridden by styles
3718 // from modules dynamically loaded with JavaScript.
3719 // - Styles from site-specific, private, and user modules should override
3720 // both of the above.
3721 //
3722 // The effective order for stylesheets must thus be:
3723 // 1. Page style modules, formatted server-side by ResourceLoaderClientHtml.
3724 // 2. Dynamically-loaded styles, inserted client-side by mw.loader.
3725 // 3. Styles that are site-specific, private or from the user, formatted
3726 // server-side by this function.
3727 //
3728 // The 'ResourceLoaderDynamicStyles' marker helps JavaScript know where
3729 // point #2 is.
3730
3731 // Add legacy styles added through addStyle()/addInlineStyle() here
3732 $chunks[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles;
3733
3734 // Things that go after the ResourceLoaderDynamicStyles marker
3735 $append = [];
3736 $separateReq = [ 'site.styles', 'user.styles' ];
3737 foreach ( $this->rlExemptStyleModules as $group => $moduleNames ) {
3738 if ( $moduleNames ) {
3739 $append[] = $this->makeResourceLoaderLink(
3740 array_diff( $moduleNames, $separateReq ),
3741 ResourceLoaderModule::TYPE_STYLES
3742 );
3743
3744 foreach ( array_intersect( $moduleNames, $separateReq ) as $name ) {
3745 // These require their own dedicated request in order to support "@import"
3746 // syntax, which is incompatible with concatenation. (T147667, T37562)
3747 $append[] = $this->makeResourceLoaderLink( $name,
3748 ResourceLoaderModule::TYPE_STYLES
3749 );
3750 }
3751 }
3752 }
3753 if ( $append ) {
3754 $chunks[] = Html::element(
3755 'meta',
3756 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
3757 );
3758 $chunks = array_merge( $chunks, $append );
3759 }
3760
3761 return self::combineWrappedStrings( $chunks );
3762 }
3763
3764 /**
3765 * @return array
3766 */
3767 public function buildCssLinksArray() {
3768 $links = [];
3769
3770 foreach ( $this->styles as $file => $options ) {
3771 $link = $this->styleLink( $file, $options );
3772 if ( $link ) {
3773 $links[$file] = $link;
3774 }
3775 }
3776 return $links;
3777 }
3778
3779 /**
3780 * Generate \<link\> tags for stylesheets
3781 *
3782 * @param string $style URL to the file
3783 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3784 * @return string HTML fragment
3785 */
3786 protected function styleLink( $style, array $options ) {
3787 if ( isset( $options['dir'] ) && $this->getLanguage()->getDir() != $options['dir'] ) {
3788 return '';
3789 }
3790
3791 if ( isset( $options['media'] ) ) {
3792 $media = self::transformCssMedia( $options['media'] );
3793 if ( is_null( $media ) ) {
3794 return '';
3795 }
3796 } else {
3797 $media = 'all';
3798 }
3799
3800 if ( substr( $style, 0, 1 ) == '/' ||
3801 substr( $style, 0, 5 ) == 'http:' ||
3802 substr( $style, 0, 6 ) == 'https:' ) {
3803 $url = $style;
3804 } else {
3805 $config = $this->getConfig();
3806 // Append file hash as query parameter
3807 $url = self::transformResourcePath(
3808 $config,
3809 $config->get( 'StylePath' ) . '/' . $style
3810 );
3811 }
3812
3813 $link = Html::linkedStyle( $url, $media );
3814
3815 if ( isset( $options['condition'] ) ) {
3816 $condition = htmlspecialchars( $options['condition'] );
3817 $link = "<!--[if $condition]>$link<![endif]-->";
3818 }
3819 return $link;
3820 }
3821
3822 /**
3823 * Transform path to web-accessible static resource.
3824 *
3825 * This is used to add a validation hash as query string.
3826 * This aids various behaviors:
3827 *
3828 * - Put long Cache-Control max-age headers on responses for improved
3829 * cache performance.
3830 * - Get the correct version of a file as expected by the current page.
3831 * - Instantly get the updated version of a file after deployment.
3832 *
3833 * Avoid using this for urls included in HTML as otherwise clients may get different
3834 * versions of a resource when navigating the site depending on when the page was cached.
3835 * If changes to the url propagate, this is not a problem (e.g. if the url is in
3836 * an external stylesheet).
3837 *
3838 * @since 1.27
3839 * @param Config $config
3840 * @param string $path Path-absolute URL to file (from document root, must start with "/")
3841 * @return string URL
3842 */
3843 public static function transformResourcePath( Config $config, $path ) {
3844 global $IP;
3845
3846 $localDir = $IP;
3847 $remotePathPrefix = $config->get( 'ResourceBasePath' );
3848 if ( $remotePathPrefix === '' ) {
3849 // The configured base path is required to be empty string for
3850 // wikis in the domain root
3851 $remotePath = '/';
3852 } else {
3853 $remotePath = $remotePathPrefix;
3854 }
3855 if ( strpos( $path, $remotePath ) !== 0 || substr( $path, 0, 2 ) === '//' ) {
3856 // - Path is outside wgResourceBasePath, ignore.
3857 // - Path is protocol-relative. Fixes T155310. Not supported by RelPath lib.
3858 return $path;
3859 }
3860 // For files in resources, extensions/ or skins/, ResourceBasePath is preferred here.
3861 // For other misc files in $IP, we'll fallback to that as well. There is, however, a fourth
3862 // supported dir/path pair in the configuration (wgUploadDirectory, wgUploadPath)
3863 // which is not expected to be in wgResourceBasePath on CDNs. (T155146)
3864 $uploadPath = $config->get( 'UploadPath' );
3865 if ( strpos( $path, $uploadPath ) === 0 ) {
3866 $localDir = $config->get( 'UploadDirectory' );
3867 $remotePathPrefix = $remotePath = $uploadPath;
3868 }
3869
3870 $path = RelPath::getRelativePath( $path, $remotePath );
3871 return self::transformFilePath( $remotePathPrefix, $localDir, $path );
3872 }
3873
3874 /**
3875 * Utility method for transformResourceFilePath().
3876 *
3877 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
3878 *
3879 * @since 1.27
3880 * @param string $remotePathPrefix URL path prefix that points to $localPath
3881 * @param string $localPath File directory exposed at $remotePath
3882 * @param string $file Path to target file relative to $localPath
3883 * @return string URL
3884 */
3885 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
3886 $hash = md5_file( "$localPath/$file" );
3887 if ( $hash === false ) {
3888 wfLogWarning( __METHOD__ . ": Failed to hash $localPath/$file" );
3889 $hash = '';
3890 }
3891 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
3892 }
3893
3894 /**
3895 * Transform "media" attribute based on request parameters
3896 *
3897 * @param string $media Current value of the "media" attribute
3898 * @return string Modified value of the "media" attribute, or null to skip
3899 * this stylesheet
3900 */
3901 public static function transformCssMedia( $media ) {
3902 global $wgRequest;
3903
3904 // https://www.w3.org/TR/css3-mediaqueries/#syntax
3905 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3906
3907 // Switch in on-screen display for media testing
3908 $switches = [
3909 'printable' => 'print',
3910 'handheld' => 'handheld',
3911 ];
3912 foreach ( $switches as $switch => $targetMedia ) {
3913 if ( $wgRequest->getBool( $switch ) ) {
3914 if ( $media == $targetMedia ) {
3915 $media = '';
3916 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3917 /* This regex will not attempt to understand a comma-separated media_query_list
3918 *
3919 * Example supported values for $media:
3920 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3921 * Example NOT supported value for $media:
3922 * '3d-glasses, screen, print and resolution > 90dpi'
3923 *
3924 * If it's a print request, we never want any kind of screen stylesheets
3925 * If it's a handheld request (currently the only other choice with a switch),
3926 * we don't want simple 'screen' but we might want screen queries that
3927 * have a max-width or something, so we'll pass all others on and let the
3928 * client do the query.
3929 */
3930 if ( $targetMedia == 'print' || $media == 'screen' ) {
3931 return null;
3932 }
3933 }
3934 }
3935 }
3936
3937 return $media;
3938 }
3939
3940 /**
3941 * Add a wikitext-formatted message to the output.
3942 * This is equivalent to:
3943 *
3944 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3945 */
3946 public function addWikiMsg( /*...*/ ) {
3947 $args = func_get_args();
3948 $name = array_shift( $args );
3949 $this->addWikiMsgArray( $name, $args );
3950 }
3951
3952 /**
3953 * Add a wikitext-formatted message to the output.
3954 * Like addWikiMsg() except the parameters are taken as an array
3955 * instead of a variable argument list.
3956 *
3957 * @param string $name
3958 * @param array $args
3959 */
3960 public function addWikiMsgArray( $name, $args ) {
3961 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3962 }
3963
3964 /**
3965 * This function takes a number of message/argument specifications, wraps them in
3966 * some overall structure, and then parses the result and adds it to the output.
3967 *
3968 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3969 * and so on. The subsequent arguments may be either
3970 * 1) strings, in which case they are message names, or
3971 * 2) arrays, in which case, within each array, the first element is the message
3972 * name, and subsequent elements are the parameters to that message.
3973 *
3974 * Don't use this for messages that are not in the user's interface language.
3975 *
3976 * For example:
3977 *
3978 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3979 *
3980 * Is equivalent to:
3981 *
3982 * $wgOut->addWikiTextAsInterface( "<div class='error'>\n"
3983 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3984 *
3985 * The newline after the opening div is needed in some wikitext. See T21226.
3986 *
3987 * @param string $wrap
3988 */
3989 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3990 $msgSpecs = func_get_args();
3991 array_shift( $msgSpecs );
3992 $msgSpecs = array_values( $msgSpecs );
3993 $s = $wrap;
3994 foreach ( $msgSpecs as $n => $spec ) {
3995 if ( is_array( $spec ) ) {
3996 $args = $spec;
3997 $name = array_shift( $args );
3998 } else {
3999 $args = [];
4000 $name = $spec;
4001 }
4002 $s = str_replace( '$' . ( $n + 1 ), $this->msg( $name, $args )->plain(), $s );
4003 }
4004 $this->addWikiTextAsInterface( $s );
4005 }
4006
4007 /**
4008 * Whether the output has a table of contents
4009 * @return bool
4010 * @since 1.22
4011 */
4012 public function isTOCEnabled() {
4013 return $this->mEnableTOC;
4014 }
4015
4016 /**
4017 * Helper function to setup the PHP implementation of OOUI to use in this request.
4018 *
4019 * @since 1.26
4020 * @param string $skinName The Skin name to determine the correct OOUI theme
4021 * @param string $dir Language direction
4022 */
4023 public static function setupOOUI( $skinName = 'default', $dir = 'ltr' ) {
4024 $themes = ResourceLoaderOOUIModule::getSkinThemeMap();
4025 $theme = $themes[$skinName] ?? $themes['default'];
4026 // For example, 'OOUI\WikimediaUITheme'.
4027 $themeClass = "OOUI\\{$theme}Theme";
4028 OOUI\Theme::setSingleton( new $themeClass() );
4029 OOUI\Element::setDefaultDir( $dir );
4030 }
4031
4032 /**
4033 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
4034 * MediaWiki and this OutputPage instance.
4035 *
4036 * @since 1.25
4037 */
4038 public function enableOOUI() {
4039 self::setupOOUI(
4040 strtolower( $this->getSkin()->getSkinName() ),
4041 $this->getLanguage()->getDir()
4042 );
4043 $this->addModuleStyles( [
4044 'oojs-ui-core.styles',
4045 'oojs-ui.styles.indicators',
4046 'mediawiki.widgets.styles',
4047 'oojs-ui-core.icons',
4048 ] );
4049 }
4050
4051 /**
4052 * Get (and set if not yet set) the CSP nonce.
4053 *
4054 * This value needs to be included in any <script> tags on the
4055 * page.
4056 *
4057 * @return string|bool Nonce or false to mean don't output nonce
4058 * @since 1.32
4059 */
4060 public function getCSPNonce() {
4061 if ( !ContentSecurityPolicy::isNonceRequired( $this->getConfig() ) ) {
4062 return false;
4063 }
4064 if ( $this->CSPNonce === null ) {
4065 // XXX It might be expensive to generate randomness
4066 // on every request, on Windows.
4067 $rand = random_bytes( 15 );
4068 $this->CSPNonce = base64_encode( $rand );
4069 }
4070 return $this->CSPNonce;
4071 }
4072
4073 }