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