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