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