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