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