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