Merge "OOUIfy CheckMatrix in PHP and JS"
[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 if ( $sk->shouldPreloadLogo() ) {
2369 $this->addLogoPreloadLinkHeaders();
2370 }
2371 }
2372
2373 $linkHeader = $this->getLinkHeader();
2374 if ( $linkHeader ) {
2375 $response->header( $linkHeader );
2376 }
2377
2378 // Prevent framing, if requested
2379 $frameOptions = $this->getFrameOptions();
2380 if ( $frameOptions ) {
2381 $response->header( "X-Frame-Options: $frameOptions" );
2382 }
2383
2384 ContentSecurityPolicy::sendHeaders( $this );
2385
2386 if ( $this->mArticleBodyOnly ) {
2387 echo $this->mBodytext;
2388 } else {
2389 // Enable safe mode if requested (T152169)
2390 if ( $this->getRequest()->getBool( 'safemode' ) ) {
2391 $this->disallowUserJs();
2392 }
2393
2394 $sk = $this->getSkin();
2395 $this->loadSkinModules( $sk );
2396
2397 MWDebug::addModules( $this );
2398
2399 // Avoid PHP 7.1 warning of passing $this by reference
2400 $outputPage = $this;
2401 // Hook that allows last minute changes to the output page, e.g.
2402 // adding of CSS or Javascript by extensions.
2403 Hooks::runWithoutAbort( 'BeforePageDisplay', [ &$outputPage, &$sk ] );
2404
2405 try {
2406 $sk->outputPage();
2407 } catch ( Exception $e ) {
2408 ob_end_clean(); // bug T129657
2409 throw $e;
2410 }
2411 }
2412
2413 try {
2414 // This hook allows last minute changes to final overall output by modifying output buffer
2415 Hooks::runWithoutAbort( 'AfterFinalPageOutput', [ $this ] );
2416 } catch ( Exception $e ) {
2417 ob_end_clean(); // bug T129657
2418 throw $e;
2419 }
2420
2421 $this->sendCacheControl();
2422
2423 if ( $return ) {
2424 return ob_get_clean();
2425 } else {
2426 ob_end_flush();
2427 return null;
2428 }
2429 }
2430
2431 /**
2432 * Prepare this object to display an error page; disable caching and
2433 * indexing, clear the current text and redirect, set the page's title
2434 * and optionally an custom HTML title (content of the "<title>" tag).
2435 *
2436 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2437 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2438 * optional, if not passed the "<title>" attribute will be
2439 * based on $pageTitle
2440 */
2441 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2442 $this->setPageTitle( $pageTitle );
2443 if ( $htmlTitle !== false ) {
2444 $this->setHTMLTitle( $htmlTitle );
2445 }
2446 $this->setRobotPolicy( 'noindex,nofollow' );
2447 $this->setArticleRelated( false );
2448 $this->enableClientCache( false );
2449 $this->mRedirect = '';
2450 $this->clearSubtitle();
2451 $this->clearHTML();
2452 }
2453
2454 /**
2455 * Output a standard error page
2456 *
2457 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2458 * showErrorPage( 'titlemsg', 'pagetextmsg', [ 'param1', 'param2' ] );
2459 * showErrorPage( 'titlemsg', $messageObject );
2460 * showErrorPage( $titleMessageObject, $messageObject );
2461 *
2462 * @param string|Message $title Message key (string) for page title, or a Message object
2463 * @param string|Message $msg Message key (string) for page text, or a Message object
2464 * @param array $params Message parameters; ignored if $msg is a Message object
2465 */
2466 public function showErrorPage( $title, $msg, $params = [] ) {
2467 if ( !$title instanceof Message ) {
2468 $title = $this->msg( $title );
2469 }
2470
2471 $this->prepareErrorPage( $title );
2472
2473 if ( $msg instanceof Message ) {
2474 if ( $params !== [] ) {
2475 trigger_error( 'Argument ignored: $params. The message parameters argument '
2476 . 'is discarded when the $msg argument is a Message object instead of '
2477 . 'a string.', E_USER_NOTICE );
2478 }
2479 $this->addHTML( $msg->parseAsBlock() );
2480 } else {
2481 $this->addWikiMsgArray( $msg, $params );
2482 }
2483
2484 $this->returnToMain();
2485 }
2486
2487 /**
2488 * Output a standard permission error page
2489 *
2490 * @param array $errors Error message keys or [key, param...] arrays
2491 * @param string|null $action Action that was denied or null if unknown
2492 */
2493 public function showPermissionsErrorPage( array $errors, $action = null ) {
2494 foreach ( $errors as $key => $error ) {
2495 $errors[$key] = (array)$error;
2496 }
2497
2498 // For some action (read, edit, create and upload), display a "login to do this action"
2499 // error if all of the following conditions are met:
2500 // 1. the user is not logged in
2501 // 2. the only error is insufficient permissions (i.e. no block or something else)
2502 // 3. the error can be avoided simply by logging in
2503 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2504 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2505 && ( $errors[0][0] == 'badaccess-groups' || $errors[0][0] == 'badaccess-group0' )
2506 && ( User::groupHasPermission( 'user', $action )
2507 || User::groupHasPermission( 'autoconfirmed', $action ) )
2508 ) {
2509 $displayReturnto = null;
2510
2511 # Due to T34276, if a user does not have read permissions,
2512 # $this->getTitle() will just give Special:Badtitle, which is
2513 # not especially useful as a returnto parameter. Use the title
2514 # from the request instead, if there was one.
2515 $request = $this->getRequest();
2516 $returnto = Title::newFromText( $request->getVal( 'title', '' ) );
2517 if ( $action == 'edit' ) {
2518 $msg = 'whitelistedittext';
2519 $displayReturnto = $returnto;
2520 } elseif ( $action == 'createpage' || $action == 'createtalk' ) {
2521 $msg = 'nocreatetext';
2522 } elseif ( $action == 'upload' ) {
2523 $msg = 'uploadnologintext';
2524 } else { # Read
2525 $msg = 'loginreqpagetext';
2526 $displayReturnto = Title::newMainPage();
2527 }
2528
2529 $query = [];
2530
2531 if ( $returnto ) {
2532 $query['returnto'] = $returnto->getPrefixedText();
2533
2534 if ( !$request->wasPosted() ) {
2535 $returntoquery = $request->getValues();
2536 unset( $returntoquery['title'] );
2537 unset( $returntoquery['returnto'] );
2538 unset( $returntoquery['returntoquery'] );
2539 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2540 }
2541 }
2542 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
2543 $loginLink = $linkRenderer->makeKnownLink(
2544 SpecialPage::getTitleFor( 'Userlogin' ),
2545 $this->msg( 'loginreqlink' )->text(),
2546 [],
2547 $query
2548 );
2549
2550 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2551 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2552
2553 # Don't return to a page the user can't read otherwise
2554 # we'll end up in a pointless loop
2555 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2556 $this->returnToMain( null, $displayReturnto );
2557 }
2558 } else {
2559 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2560 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2561 }
2562 }
2563
2564 /**
2565 * Display an error page indicating that a given version of MediaWiki is
2566 * required to use it
2567 *
2568 * @param mixed $version The version of MediaWiki needed to use the page
2569 */
2570 public function versionRequired( $version ) {
2571 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2572
2573 $this->addWikiMsg( 'versionrequiredtext', $version );
2574 $this->returnToMain();
2575 }
2576
2577 /**
2578 * Format a list of error messages
2579 *
2580 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2581 * @param string|null $action Action that was denied or null if unknown
2582 * @return string The wikitext error-messages, formatted into a list.
2583 */
2584 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2585 if ( $action == null ) {
2586 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2587 } else {
2588 $action_desc = $this->msg( "action-$action" )->plain();
2589 $text = $this->msg(
2590 'permissionserrorstext-withaction',
2591 count( $errors ),
2592 $action_desc
2593 )->plain() . "\n\n";
2594 }
2595
2596 if ( count( $errors ) > 1 ) {
2597 $text .= '<ul class="permissions-errors">' . "\n";
2598
2599 foreach ( $errors as $error ) {
2600 $text .= '<li>';
2601 $text .= $this->msg( ...$error )->plain();
2602 $text .= "</li>\n";
2603 }
2604 $text .= '</ul>';
2605 } else {
2606 $text .= "<div class=\"permissions-errors\">\n" .
2607 $this->msg( ...reset( $errors ) )->plain() .
2608 "\n</div>";
2609 }
2610
2611 return $text;
2612 }
2613
2614 /**
2615 * Show a warning about replica DB lag
2616 *
2617 * If the lag is higher than $wgSlaveLagCritical seconds,
2618 * then the warning is a bit more obvious. If the lag is
2619 * lower than $wgSlaveLagWarning, then no warning is shown.
2620 *
2621 * @param int $lag Slave lag
2622 */
2623 public function showLagWarning( $lag ) {
2624 $config = $this->getConfig();
2625 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2626 $lag = floor( $lag ); // floor to avoid nano seconds to display
2627 $message = $lag < $config->get( 'SlaveLagCritical' )
2628 ? 'lag-warn-normal'
2629 : 'lag-warn-high';
2630 $wrap = Html::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2631 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2632 }
2633 }
2634
2635 /**
2636 * Output an error page
2637 *
2638 * @note FatalError exception class provides an alternative.
2639 * @param string $message Error to output. Must be escaped for HTML.
2640 */
2641 public function showFatalError( $message ) {
2642 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2643
2644 $this->addHTML( $message );
2645 }
2646
2647 /**
2648 * @deprecated 1.32 Use OutputPage::showFatalError or throw FatalError instead.
2649 */
2650 public function showUnexpectedValueError( $name, $val ) {
2651 wfDeprecated( __METHOD__, '1.32' );
2652 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->escaped() );
2653 }
2654
2655 /**
2656 * @deprecated 1.32 Use OutputPage::showFatalError or throw FatalError instead.
2657 */
2658 public function showFileCopyError( $old, $new ) {
2659 wfDeprecated( __METHOD__, '1.32' );
2660 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->escaped() );
2661 }
2662
2663 /**
2664 * @deprecated 1.32 Use OutputPage::showFatalError or throw FatalError instead.
2665 */
2666 public function showFileRenameError( $old, $new ) {
2667 wfDeprecated( __METHOD__, '1.32' );
2668 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->escpaed() );
2669 }
2670
2671 /**
2672 * @deprecated 1.32 Use OutputPage::showFatalError or throw FatalError instead.
2673 */
2674 public function showFileDeleteError( $name ) {
2675 wfDeprecated( __METHOD__, '1.32' );
2676 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->escaped() );
2677 }
2678
2679 /**
2680 * @deprecated 1.32 Use OutputPage::showFatalError or throw FatalError instead.
2681 */
2682 public function showFileNotFoundError( $name ) {
2683 wfDeprecated( __METHOD__, '1.32' );
2684 $this->showFatalError( $this->msg( 'filenotfound', $name )->escaped() );
2685 }
2686
2687 /**
2688 * Add a "return to" link pointing to a specified title
2689 *
2690 * @param Title $title Title to link
2691 * @param array $query Query string parameters
2692 * @param string|null $text Text of the link (input is not escaped)
2693 * @param array $options Options array to pass to Linker
2694 */
2695 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
2696 $linkRenderer = MediaWikiServices::getInstance()
2697 ->getLinkRendererFactory()->createFromLegacyOptions( $options );
2698 $link = $this->msg( 'returnto' )->rawParams(
2699 $linkRenderer->makeLink( $title, $text, [], $query ) )->escaped();
2700 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2701 }
2702
2703 /**
2704 * Add a "return to" link pointing to a specified title,
2705 * or the title indicated in the request, or else the main page
2706 *
2707 * @param mixed|null $unused
2708 * @param Title|string|null $returnto Title or String to return to
2709 * @param string|null $returntoquery Query string for the return to link
2710 */
2711 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2712 if ( $returnto == null ) {
2713 $returnto = $this->getRequest()->getText( 'returnto' );
2714 }
2715
2716 if ( $returntoquery == null ) {
2717 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2718 }
2719
2720 if ( $returnto === '' ) {
2721 $returnto = Title::newMainPage();
2722 }
2723
2724 if ( is_object( $returnto ) ) {
2725 $titleObj = $returnto;
2726 } else {
2727 $titleObj = Title::newFromText( $returnto );
2728 }
2729 // We don't want people to return to external interwiki. That
2730 // might potentially be used as part of a phishing scheme
2731 if ( !is_object( $titleObj ) || $titleObj->isExternal() ) {
2732 $titleObj = Title::newMainPage();
2733 }
2734
2735 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2736 }
2737
2738 private function getRlClientContext() {
2739 if ( !$this->rlClientContext ) {
2740 $query = ResourceLoader::makeLoaderQuery(
2741 [], // modules; not relevant
2742 $this->getLanguage()->getCode(),
2743 $this->getSkin()->getSkinName(),
2744 $this->getUser()->isLoggedIn() ? $this->getUser()->getName() : null,
2745 null, // version; not relevant
2746 ResourceLoader::inDebugMode(),
2747 null, // only; not relevant
2748 $this->isPrintable(),
2749 $this->getRequest()->getBool( 'handheld' )
2750 );
2751 $this->rlClientContext = new ResourceLoaderContext(
2752 $this->getResourceLoader(),
2753 new FauxRequest( $query )
2754 );
2755 if ( $this->contentOverrideCallbacks ) {
2756 $this->rlClientContext = new DerivativeResourceLoaderContext( $this->rlClientContext );
2757 $this->rlClientContext->setContentOverrideCallback( function ( Title $title ) {
2758 foreach ( $this->contentOverrideCallbacks as $callback ) {
2759 $content = $callback( $title );
2760 if ( $content !== null ) {
2761 return $content;
2762 }
2763 }
2764 return null;
2765 } );
2766 }
2767 }
2768 return $this->rlClientContext;
2769 }
2770
2771 /**
2772 * Call this to freeze the module queue and JS config and create a formatter.
2773 *
2774 * Depending on the Skin, this may get lazy-initialised in either headElement() or
2775 * getBottomScripts(). See SkinTemplate::prepareQuickTemplate(). Calling this too early may
2776 * cause unexpected side-effects since disallowUserJs() may be called at any time to change
2777 * the module filters retroactively. Skins and extension hooks may also add modules until very
2778 * late in the request lifecycle.
2779 *
2780 * @return ResourceLoaderClientHtml
2781 */
2782 public function getRlClient() {
2783 if ( !$this->rlClient ) {
2784 $context = $this->getRlClientContext();
2785 $rl = $this->getResourceLoader();
2786 $this->addModules( [
2787 'user',
2788 'user.options',
2789 'user.tokens',
2790 ] );
2791 $this->addModuleStyles( [
2792 'site.styles',
2793 'noscript',
2794 'user.styles',
2795 ] );
2796 $this->getSkin()->setupSkinUserCss( $this );
2797
2798 // Prepare exempt modules for buildExemptModules()
2799 $exemptGroups = [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ];
2800 $exemptStates = [];
2801 $moduleStyles = $this->getModuleStyles( /*filter*/ true );
2802
2803 // Preload getTitleInfo for isKnownEmpty calls below and in ResourceLoaderClientHtml
2804 // Separate user-specific batch for improved cache-hit ratio.
2805 $userBatch = [ 'user.styles', 'user' ];
2806 $siteBatch = array_diff( $moduleStyles, $userBatch );
2807 $dbr = wfGetDB( DB_REPLICA );
2808 ResourceLoaderWikiModule::preloadTitleInfo( $context, $dbr, $siteBatch );
2809 ResourceLoaderWikiModule::preloadTitleInfo( $context, $dbr, $userBatch );
2810
2811 // Filter out modules handled by buildExemptModules()
2812 $moduleStyles = array_filter( $moduleStyles,
2813 function ( $name ) use ( $rl, $context, &$exemptGroups, &$exemptStates ) {
2814 $module = $rl->getModule( $name );
2815 if ( $module ) {
2816 $group = $module->getGroup();
2817 if ( isset( $exemptGroups[$group] ) ) {
2818 $exemptStates[$name] = 'ready';
2819 if ( !$module->isKnownEmpty( $context ) ) {
2820 // E.g. Don't output empty <styles>
2821 $exemptGroups[$group][] = $name;
2822 }
2823 return false;
2824 }
2825 }
2826 return true;
2827 }
2828 );
2829 $this->rlExemptStyleModules = $exemptGroups;
2830
2831 $rlClient = new ResourceLoaderClientHtml( $context, [
2832 'target' => $this->getTarget(),
2833 'nonce' => $this->getCSPNonce(),
2834 // When 'safemode', disallowUserJs(), or reduceAllowedModules() is used
2835 // to only restrict modules to ORIGIN_CORE (ie. disallow ORIGIN_USER), the list of
2836 // modules enqueud for loading on this page is filtered to just those.
2837 // However, to make sure we also apply the restriction to dynamic dependencies and
2838 // lazy-loaded modules at run-time on the client-side, pass 'safemode' down to the
2839 // StartupModule so that the client-side registry will not contain any restricted
2840 // modules either. (T152169, T185303)
2841 'safemode' => ( $this->getAllowedModules( ResourceLoaderModule::TYPE_COMBINED )
2842 <= ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL
2843 ) ? '1' : null,
2844 ] );
2845 $rlClient->setConfig( $this->getJSVars() );
2846 $rlClient->setModules( $this->getModules( /*filter*/ true ) );
2847 $rlClient->setModuleStyles( $moduleStyles );
2848 $rlClient->setModuleScripts( $this->getModuleScripts( /*filter*/ true ) );
2849 $rlClient->setExemptStates( $exemptStates );
2850 $this->rlClient = $rlClient;
2851 }
2852 return $this->rlClient;
2853 }
2854
2855 /**
2856 * @param Skin $sk The given Skin
2857 * @param bool $includeStyle Unused
2858 * @return string The doctype, opening "<html>", and head element.
2859 */
2860 public function headElement( Skin $sk, $includeStyle = true ) {
2861 $userdir = $this->getLanguage()->getDir();
2862 $sitedir = MediaWikiServices::getInstance()->getContentLanguage()->getDir();
2863
2864 $pieces = [];
2865 $pieces[] = Html::htmlHeader( Sanitizer::mergeAttributes(
2866 $this->getRlClient()->getDocumentAttributes(),
2867 $sk->getHtmlElementAttributes()
2868 ) );
2869 $pieces[] = Html::openElement( 'head' );
2870
2871 if ( $this->getHTMLTitle() == '' ) {
2872 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2873 }
2874
2875 if ( !Html::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2876 // Add <meta charset="UTF-8">
2877 // This should be before <title> since it defines the charset used by
2878 // text including the text inside <title>.
2879 // The spec recommends defining XHTML5's charset using the XML declaration
2880 // instead of meta.
2881 // Our XML declaration is output by Html::htmlHeader.
2882 // https://html.spec.whatwg.org/multipage/semantics.html#attr-meta-http-equiv-content-type
2883 // https://html.spec.whatwg.org/multipage/semantics.html#charset
2884 $pieces[] = Html::element( 'meta', [ 'charset' => 'UTF-8' ] );
2885 }
2886
2887 $pieces[] = Html::element( 'title', null, $this->getHTMLTitle() );
2888 $pieces[] = $this->getRlClient()->getHeadHtml();
2889 $pieces[] = $this->buildExemptModules();
2890 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
2891 $pieces = array_merge( $pieces, array_values( $this->mHeadItems ) );
2892
2893 // Use an IE conditional comment to serve the script only to old IE
2894 $pieces[] = '<!--[if lt IE 9]>' .
2895 ResourceLoaderClientHtml::makeLoad(
2896 ResourceLoaderContext::newDummyContext(),
2897 [ 'html5shiv' ],
2898 ResourceLoaderModule::TYPE_SCRIPTS,
2899 [ 'sync' => true ],
2900 $this->getCSPNonce()
2901 ) .
2902 '<![endif]-->';
2903
2904 $pieces[] = Html::closeElement( 'head' );
2905
2906 $bodyClasses = $this->mAdditionalBodyClasses;
2907 $bodyClasses[] = 'mediawiki';
2908
2909 # Classes for LTR/RTL directionality support
2910 $bodyClasses[] = $userdir;
2911 $bodyClasses[] = "sitedir-$sitedir";
2912
2913 $underline = $this->getUser()->getOption( 'underline' );
2914 if ( $underline < 2 ) {
2915 // The following classes can be used here:
2916 // * mw-underline-always
2917 // * mw-underline-never
2918 $bodyClasses[] = 'mw-underline-' . ( $underline ? 'always' : 'never' );
2919 }
2920
2921 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2922 # A <body> class is probably not the best way to do this . . .
2923 $bodyClasses[] = 'capitalize-all-nouns';
2924 }
2925
2926 // Parser feature migration class
2927 // The idea is that this will eventually be removed, after the wikitext
2928 // which requires it is cleaned up.
2929 $bodyClasses[] = 'mw-hide-empty-elt';
2930
2931 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2932 $bodyClasses[] = 'skin-' . Sanitizer::escapeClass( $sk->getSkinName() );
2933 $bodyClasses[] =
2934 'action-' . Sanitizer::escapeClass( Action::getActionName( $this->getContext() ) );
2935
2936 $bodyAttrs = [];
2937 // While the implode() is not strictly needed, it's used for backwards compatibility
2938 // (this used to be built as a string and hooks likely still expect that).
2939 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2940
2941 // Allow skins and extensions to add body attributes they need
2942 $sk->addToBodyAttributes( $this, $bodyAttrs );
2943 Hooks::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
2944
2945 $pieces[] = Html::openElement( 'body', $bodyAttrs );
2946
2947 return self::combineWrappedStrings( $pieces );
2948 }
2949
2950 /**
2951 * Get a ResourceLoader object associated with this OutputPage
2952 *
2953 * @return ResourceLoader
2954 */
2955 public function getResourceLoader() {
2956 if ( is_null( $this->mResourceLoader ) ) {
2957 $this->mResourceLoader = new ResourceLoader(
2958 $this->getConfig(),
2959 LoggerFactory::getInstance( 'resourceloader' )
2960 );
2961 }
2962 return $this->mResourceLoader;
2963 }
2964
2965 /**
2966 * Explicily load or embed modules on a page.
2967 *
2968 * @param array|string $modules One or more module names
2969 * @param string $only ResourceLoaderModule TYPE_ class constant
2970 * @param array $extraQuery [optional] Array with extra query parameters for the request
2971 * @return string|WrappedStringList HTML
2972 */
2973 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
2974 // Apply 'target' and 'origin' filters
2975 $modules = $this->filterModules( (array)$modules, null, $only );
2976
2977 return ResourceLoaderClientHtml::makeLoad(
2978 $this->getRlClientContext(),
2979 $modules,
2980 $only,
2981 $extraQuery,
2982 $this->getCSPNonce()
2983 );
2984 }
2985
2986 /**
2987 * Combine WrappedString chunks and filter out empty ones
2988 *
2989 * @param array $chunks
2990 * @return string|WrappedStringList HTML
2991 */
2992 protected static function combineWrappedStrings( array $chunks ) {
2993 // Filter out empty values
2994 $chunks = array_filter( $chunks, 'strlen' );
2995 return WrappedString::join( "\n", $chunks );
2996 }
2997
2998 /**
2999 * JS stuff to put at the bottom of the `<body>`.
3000 * These are legacy scripts ($this->mScripts), and user JS.
3001 *
3002 * @return string|WrappedStringList HTML
3003 */
3004 public function getBottomScripts() {
3005 $chunks = [];
3006 $chunks[] = $this->getRlClient()->getBodyHtml();
3007
3008 // Legacy non-ResourceLoader scripts
3009 $chunks[] = $this->mScripts;
3010
3011 if ( $this->limitReportJSData ) {
3012 $chunks[] = ResourceLoader::makeInlineScript(
3013 ResourceLoader::makeConfigSetScript(
3014 [ 'wgPageParseReport' => $this->limitReportJSData ]
3015 ),
3016 $this->getCSPNonce()
3017 );
3018 }
3019
3020 return self::combineWrappedStrings( $chunks );
3021 }
3022
3023 /**
3024 * Get the javascript config vars to include on this page
3025 *
3026 * @return array Array of javascript config vars
3027 * @since 1.23
3028 */
3029 public function getJsConfigVars() {
3030 return $this->mJsConfigVars;
3031 }
3032
3033 /**
3034 * Add one or more variables to be set in mw.config in JavaScript
3035 *
3036 * @param string|array $keys Key or array of key/value pairs
3037 * @param mixed|null $value [optional] Value of the configuration variable
3038 */
3039 public function addJsConfigVars( $keys, $value = null ) {
3040 if ( is_array( $keys ) ) {
3041 foreach ( $keys as $key => $value ) {
3042 $this->mJsConfigVars[$key] = $value;
3043 }
3044 return;
3045 }
3046
3047 $this->mJsConfigVars[$keys] = $value;
3048 }
3049
3050 /**
3051 * Get an array containing the variables to be set in mw.config in JavaScript.
3052 *
3053 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3054 * - in other words, page-independent/site-wide variables (without state).
3055 * You will only be adding bloat to the html page and causing page caches to
3056 * have to be purged on configuration changes.
3057 * @return array
3058 */
3059 public function getJSVars() {
3060 $curRevisionId = 0;
3061 $articleId = 0;
3062 $canonicalSpecialPageName = false; # T23115
3063 $services = MediaWikiServices::getInstance();
3064
3065 $title = $this->getTitle();
3066 $ns = $title->getNamespace();
3067 $canonicalNamespace = MWNamespace::exists( $ns )
3068 ? MWNamespace::getCanonicalName( $ns )
3069 : $title->getNsText();
3070
3071 $sk = $this->getSkin();
3072 // Get the relevant title so that AJAX features can use the correct page name
3073 // when making API requests from certain special pages (T36972).
3074 $relevantTitle = $sk->getRelevantTitle();
3075 $relevantUser = $sk->getRelevantUser();
3076
3077 if ( $ns == NS_SPECIAL ) {
3078 list( $canonicalSpecialPageName, /*...*/ ) =
3079 $services->getSpecialPageFactory()->
3080 resolveAlias( $title->getDBkey() );
3081 } elseif ( $this->canUseWikiPage() ) {
3082 $wikiPage = $this->getWikiPage();
3083 $curRevisionId = $wikiPage->getLatest();
3084 $articleId = $wikiPage->getId();
3085 }
3086
3087 $lang = $title->getPageViewLanguage();
3088
3089 // Pre-process information
3090 $separatorTransTable = $lang->separatorTransformTable();
3091 $separatorTransTable = $separatorTransTable ?: [];
3092 $compactSeparatorTransTable = [
3093 implode( "\t", array_keys( $separatorTransTable ) ),
3094 implode( "\t", $separatorTransTable ),
3095 ];
3096 $digitTransTable = $lang->digitTransformTable();
3097 $digitTransTable = $digitTransTable ?: [];
3098 $compactDigitTransTable = [
3099 implode( "\t", array_keys( $digitTransTable ) ),
3100 implode( "\t", $digitTransTable ),
3101 ];
3102
3103 $user = $this->getUser();
3104
3105 $vars = [
3106 'wgCanonicalNamespace' => $canonicalNamespace,
3107 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3108 'wgNamespaceNumber' => $title->getNamespace(),
3109 'wgPageName' => $title->getPrefixedDBkey(),
3110 'wgTitle' => $title->getText(),
3111 'wgCurRevisionId' => $curRevisionId,
3112 'wgRevisionId' => (int)$this->getRevisionId(),
3113 'wgArticleId' => $articleId,
3114 'wgIsArticle' => $this->isArticle(),
3115 'wgIsRedirect' => $title->isRedirect(),
3116 'wgAction' => Action::getActionName( $this->getContext() ),
3117 'wgUserName' => $user->isAnon() ? null : $user->getName(),
3118 'wgUserGroups' => $user->getEffectiveGroups(),
3119 'wgCategories' => $this->getCategories(),
3120 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3121 'wgPageContentLanguage' => $lang->getCode(),
3122 'wgPageContentModel' => $title->getContentModel(),
3123 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3124 'wgDigitTransformTable' => $compactDigitTransTable,
3125 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3126 'wgMonthNames' => $lang->getMonthNamesArray(),
3127 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3128 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3129 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3130 'wgRequestId' => WebRequest::getRequestId(),
3131 'wgCSPNonce' => $this->getCSPNonce(),
3132 ];
3133
3134 if ( $user->isLoggedIn() ) {
3135 $vars['wgUserId'] = $user->getId();
3136 $vars['wgUserEditCount'] = $user->getEditCount();
3137 $userReg = $user->getRegistration();
3138 $vars['wgUserRegistration'] = $userReg ? wfTimestamp( TS_UNIX, $userReg ) * 1000 : null;
3139 // Get the revision ID of the oldest new message on the user's talk
3140 // page. This can be used for constructing new message alerts on
3141 // the client side.
3142 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3143 }
3144
3145 $contLang = $services->getContentLanguage();
3146 if ( $contLang->hasVariants() ) {
3147 $vars['wgUserVariant'] = $contLang->getPreferredVariant();
3148 }
3149 // Same test as SkinTemplate
3150 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3151 && ( $title->exists() || $title->quickUserCan( 'create', $user ) );
3152
3153 $vars['wgRelevantPageIsProbablyEditable'] = $relevantTitle
3154 && $relevantTitle->quickUserCan( 'edit', $user )
3155 && ( $relevantTitle->exists() || $relevantTitle->quickUserCan( 'create', $user ) );
3156
3157 foreach ( $title->getRestrictionTypes() as $type ) {
3158 // Following keys are set in $vars:
3159 // wgRestrictionCreate, wgRestrictionEdit, wgRestrictionMove, wgRestrictionUpload
3160 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3161 }
3162
3163 if ( $title->isMainPage() ) {
3164 $vars['wgIsMainPage'] = true;
3165 }
3166
3167 if ( $this->mRedirectedFrom ) {
3168 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom->getPrefixedDBkey();
3169 }
3170
3171 if ( $relevantUser ) {
3172 $vars['wgRelevantUserName'] = $relevantUser->getName();
3173 }
3174
3175 // Allow extensions to add their custom variables to the mw.config map.
3176 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3177 // page-dependant but site-wide (without state).
3178 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3179 Hooks::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3180
3181 // Merge in variables from addJsConfigVars last
3182 return array_merge( $vars, $this->getJsConfigVars() );
3183 }
3184
3185 /**
3186 * To make it harder for someone to slip a user a fake
3187 * JavaScript or CSS preview, a random token
3188 * is associated with the login session. If it's not
3189 * passed back with the preview request, we won't render
3190 * the code.
3191 *
3192 * @return bool
3193 */
3194 public function userCanPreview() {
3195 $request = $this->getRequest();
3196 if (
3197 $request->getVal( 'action' ) !== 'submit' ||
3198 !$request->wasPosted()
3199 ) {
3200 return false;
3201 }
3202
3203 $user = $this->getUser();
3204
3205 if ( !$user->isLoggedIn() ) {
3206 // Anons have predictable edit tokens
3207 return false;
3208 }
3209 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3210 return false;
3211 }
3212
3213 $title = $this->getTitle();
3214 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3215 if ( count( $errors ) !== 0 ) {
3216 return false;
3217 }
3218
3219 return true;
3220 }
3221
3222 /**
3223 * @return array Array in format "link name or number => 'link html'".
3224 */
3225 public function getHeadLinksArray() {
3226 global $wgVersion;
3227
3228 $tags = [];
3229 $config = $this->getConfig();
3230
3231 $canonicalUrl = $this->mCanonicalUrl;
3232
3233 $tags['meta-generator'] = Html::element( 'meta', [
3234 'name' => 'generator',
3235 'content' => "MediaWiki $wgVersion",
3236 ] );
3237
3238 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3239 // Per https://w3c.github.io/webappsec-referrer-policy/#unknown-policy-values
3240 // fallbacks should come before the primary value so we need to reverse the array.
3241 foreach ( array_reverse( (array)$config->get( 'ReferrerPolicy' ) ) as $i => $policy ) {
3242 $tags["meta-referrer-$i"] = Html::element( 'meta', [
3243 'name' => 'referrer',
3244 'content' => $policy,
3245 ] );
3246 }
3247 }
3248
3249 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3250 if ( $p !== 'index,follow' ) {
3251 // http://www.robotstxt.org/wc/meta-user.html
3252 // Only show if it's different from the default robots policy
3253 $tags['meta-robots'] = Html::element( 'meta', [
3254 'name' => 'robots',
3255 'content' => $p,
3256 ] );
3257 }
3258
3259 foreach ( $this->mMetatags as $tag ) {
3260 if ( strncasecmp( $tag[0], 'http:', 5 ) === 0 ) {
3261 $a = 'http-equiv';
3262 $tag[0] = substr( $tag[0], 5 );
3263 } elseif ( strncasecmp( $tag[0], 'og:', 3 ) === 0 ) {
3264 $a = 'property';
3265 } else {
3266 $a = 'name';
3267 }
3268 $tagName = "meta-{$tag[0]}";
3269 if ( isset( $tags[$tagName] ) ) {
3270 $tagName .= $tag[1];
3271 }
3272 $tags[$tagName] = Html::element( 'meta',
3273 [
3274 $a => $tag[0],
3275 'content' => $tag[1]
3276 ]
3277 );
3278 }
3279
3280 foreach ( $this->mLinktags as $tag ) {
3281 $tags[] = Html::element( 'link', $tag );
3282 }
3283
3284 # Universal edit button
3285 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3286 $user = $this->getUser();
3287 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3288 && ( $this->getTitle()->exists() ||
3289 $this->getTitle()->quickUserCan( 'create', $user ) )
3290 ) {
3291 // Original UniversalEditButton
3292 $msg = $this->msg( 'edit' )->text();
3293 $tags['universal-edit-button'] = Html::element( 'link', [
3294 'rel' => 'alternate',
3295 'type' => 'application/x-wiki',
3296 'title' => $msg,
3297 'href' => $this->getTitle()->getEditURL(),
3298 ] );
3299 // Alternate edit link
3300 $tags['alternative-edit'] = Html::element( 'link', [
3301 'rel' => 'edit',
3302 'title' => $msg,
3303 'href' => $this->getTitle()->getEditURL(),
3304 ] );
3305 }
3306 }
3307
3308 # Generally the order of the favicon and apple-touch-icon links
3309 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3310 # uses whichever one appears later in the HTML source. Make sure
3311 # apple-touch-icon is specified first to avoid this.
3312 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3313 $tags['apple-touch-icon'] = Html::element( 'link', [
3314 'rel' => 'apple-touch-icon',
3315 'href' => $config->get( 'AppleTouchIcon' )
3316 ] );
3317 }
3318
3319 if ( $config->get( 'Favicon' ) !== false ) {
3320 $tags['favicon'] = Html::element( 'link', [
3321 'rel' => 'shortcut icon',
3322 'href' => $config->get( 'Favicon' )
3323 ] );
3324 }
3325
3326 # OpenSearch description link
3327 $tags['opensearch'] = Html::element( 'link', [
3328 'rel' => 'search',
3329 'type' => 'application/opensearchdescription+xml',
3330 'href' => wfScript( 'opensearch_desc' ),
3331 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3332 ] );
3333
3334 # Real Simple Discovery link, provides auto-discovery information
3335 # for the MediaWiki API (and potentially additional custom API
3336 # support such as WordPress or Twitter-compatible APIs for a
3337 # blogging extension, etc)
3338 $tags['rsd'] = Html::element( 'link', [
3339 'rel' => 'EditURI',
3340 'type' => 'application/rsd+xml',
3341 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3342 // Whether RSD accepts relative or protocol-relative URLs is completely
3343 // undocumented, though.
3344 'href' => wfExpandUrl( wfAppendQuery(
3345 wfScript( 'api' ),
3346 [ 'action' => 'rsd' ] ),
3347 PROTO_RELATIVE
3348 ),
3349 ] );
3350
3351 # Language variants
3352 if ( !$config->get( 'DisableLangConversion' ) ) {
3353 $lang = $this->getTitle()->getPageLanguage();
3354 if ( $lang->hasVariants() ) {
3355 $variants = $lang->getVariants();
3356 foreach ( $variants as $variant ) {
3357 $tags["variant-$variant"] = Html::element( 'link', [
3358 'rel' => 'alternate',
3359 'hreflang' => LanguageCode::bcp47( $variant ),
3360 'href' => $this->getTitle()->getLocalURL(
3361 [ 'variant' => $variant ] )
3362 ]
3363 );
3364 }
3365 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3366 $tags["variant-x-default"] = Html::element( 'link', [
3367 'rel' => 'alternate',
3368 'hreflang' => 'x-default',
3369 'href' => $this->getTitle()->getLocalURL() ] );
3370 }
3371 }
3372
3373 # Copyright
3374 if ( $this->copyrightUrl !== null ) {
3375 $copyright = $this->copyrightUrl;
3376 } else {
3377 $copyright = '';
3378 if ( $config->get( 'RightsPage' ) ) {
3379 $copy = Title::newFromText( $config->get( 'RightsPage' ) );
3380
3381 if ( $copy ) {
3382 $copyright = $copy->getLocalURL();
3383 }
3384 }
3385
3386 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3387 $copyright = $config->get( 'RightsUrl' );
3388 }
3389 }
3390
3391 if ( $copyright ) {
3392 $tags['copyright'] = Html::element( 'link', [
3393 'rel' => 'license',
3394 'href' => $copyright ]
3395 );
3396 }
3397
3398 # Feeds
3399 if ( $config->get( 'Feed' ) ) {
3400 $feedLinks = [];
3401
3402 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3403 # Use the page name for the title. In principle, this could
3404 # lead to issues with having the same name for different feeds
3405 # corresponding to the same page, but we can't avoid that at
3406 # this low a level.
3407
3408 $feedLinks[] = $this->feedLink(
3409 $format,
3410 $link,
3411 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3412 $this->msg(
3413 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3414 )->text()
3415 );
3416 }
3417
3418 # Recent changes feed should appear on every page (except recentchanges,
3419 # that would be redundant). Put it after the per-page feed to avoid
3420 # changing existing behavior. It's still available, probably via a
3421 # menu in your browser. Some sites might have a different feed they'd
3422 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3423 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3424 # If so, use it instead.
3425 $sitename = $config->get( 'Sitename' );
3426 if ( $config->get( 'OverrideSiteFeed' ) ) {
3427 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3428 // Note, this->feedLink escapes the url.
3429 $feedLinks[] = $this->feedLink(
3430 $type,
3431 $feedUrl,
3432 $this->msg( "site-{$type}-feed", $sitename )->text()
3433 );
3434 }
3435 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3436 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
3437 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3438 $feedLinks[] = $this->feedLink(
3439 $format,
3440 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3441 # For grep: 'site-rss-feed', 'site-atom-feed'
3442 $this->msg( "site-{$format}-feed", $sitename )->text()
3443 );
3444 }
3445 }
3446
3447 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3448 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3449 # use OutputPage::addFeedLink() instead.
3450 Hooks::run( 'AfterBuildFeedLinks', [ &$feedLinks ] );
3451
3452 $tags += $feedLinks;
3453 }
3454
3455 # Canonical URL
3456 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3457 if ( $canonicalUrl !== false ) {
3458 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL );
3459 } else {
3460 if ( $this->isArticleRelated() ) {
3461 // This affects all requests where "setArticleRelated" is true. This is
3462 // typically all requests that show content (query title, curid, oldid, diff),
3463 // and all wikipage actions (edit, delete, purge, info, history etc.).
3464 // It does not apply to File pages and Special pages.
3465 // 'history' and 'info' actions address page metadata rather than the page
3466 // content itself, so they may not be canonicalized to the view page url.
3467 // TODO: this ought to be better encapsulated in the Action class.
3468 $action = Action::getActionName( $this->getContext() );
3469 if ( in_array( $action, [ 'history', 'info' ] ) ) {
3470 $query = "action={$action}";
3471 } else {
3472 $query = '';
3473 }
3474 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3475 } else {
3476 $reqUrl = $this->getRequest()->getRequestURL();
3477 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL );
3478 }
3479 }
3480 }
3481 if ( $canonicalUrl !== false ) {
3482 $tags[] = Html::element( 'link', [
3483 'rel' => 'canonical',
3484 'href' => $canonicalUrl
3485 ] );
3486 }
3487
3488 // Allow extensions to add, remove and/or otherwise manipulate these links
3489 // If you want only to *add* <head> links, please use the addHeadItem()
3490 // (or addHeadItems() for multiple items) method instead.
3491 // This hook is provided as a last resort for extensions to modify these
3492 // links before the output is sent to client.
3493 Hooks::run( 'OutputPageAfterGetHeadLinksArray', [ &$tags, $this ] );
3494
3495 return $tags;
3496 }
3497
3498 /**
3499 * Generate a "<link rel/>" for a feed.
3500 *
3501 * @param string $type Feed type
3502 * @param string $url URL to the feed
3503 * @param string $text Value of the "title" attribute
3504 * @return string HTML fragment
3505 */
3506 private function feedLink( $type, $url, $text ) {
3507 return Html::element( 'link', [
3508 'rel' => 'alternate',
3509 'type' => "application/$type+xml",
3510 'title' => $text,
3511 'href' => $url ]
3512 );
3513 }
3514
3515 /**
3516 * Add a local or specified stylesheet, with the given media options.
3517 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3518 *
3519 * @param string $style URL to the file
3520 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3521 * @param string $condition For IE conditional comments, specifying an IE version
3522 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3523 */
3524 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3525 $options = [];
3526 if ( $media ) {
3527 $options['media'] = $media;
3528 }
3529 if ( $condition ) {
3530 $options['condition'] = $condition;
3531 }
3532 if ( $dir ) {
3533 $options['dir'] = $dir;
3534 }
3535 $this->styles[$style] = $options;
3536 }
3537
3538 /**
3539 * Adds inline CSS styles
3540 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3541 *
3542 * @param mixed $style_css Inline CSS
3543 * @param string $flip Set to 'flip' to flip the CSS if needed
3544 */
3545 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3546 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3547 # If wanted, and the interface is right-to-left, flip the CSS
3548 $style_css = CSSJanus::transform( $style_css, true, false );
3549 }
3550 $this->mInlineStyles .= Html::inlineStyle( $style_css );
3551 }
3552
3553 /**
3554 * Build exempt modules and legacy non-ResourceLoader styles.
3555 *
3556 * @return string|WrappedStringList HTML
3557 */
3558 protected function buildExemptModules() {
3559 $chunks = [];
3560 // Things that go after the ResourceLoaderDynamicStyles marker
3561 $append = [];
3562
3563 // We want site, private and user styles to override dynamically added styles from
3564 // general modules, but we want dynamically added styles to override statically added
3565 // style modules. So the order has to be:
3566 // - page style modules (formatted by ResourceLoaderClientHtml::getHeadHtml())
3567 // - dynamically loaded styles (added by mw.loader before ResourceLoaderDynamicStyles)
3568 // - ResourceLoaderDynamicStyles marker
3569 // - site/private/user styles
3570
3571 // Add legacy styles added through addStyle()/addInlineStyle() here
3572 $chunks[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles;
3573
3574 $chunks[] = Html::element(
3575 'meta',
3576 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
3577 );
3578
3579 $separateReq = [ 'site.styles', 'user.styles' ];
3580 foreach ( $this->rlExemptStyleModules as $group => $moduleNames ) {
3581 // Combinable modules
3582 $chunks[] = $this->makeResourceLoaderLink(
3583 array_diff( $moduleNames, $separateReq ),
3584 ResourceLoaderModule::TYPE_STYLES
3585 );
3586
3587 foreach ( array_intersect( $moduleNames, $separateReq ) as $name ) {
3588 // These require their own dedicated request in order to support "@import"
3589 // syntax, which is incompatible with concatenation. (T147667, T37562)
3590 $chunks[] = $this->makeResourceLoaderLink( $name,
3591 ResourceLoaderModule::TYPE_STYLES
3592 );
3593 }
3594 }
3595
3596 return self::combineWrappedStrings( array_merge( $chunks, $append ) );
3597 }
3598
3599 /**
3600 * @return array
3601 */
3602 public function buildCssLinksArray() {
3603 $links = [];
3604
3605 foreach ( $this->styles as $file => $options ) {
3606 $link = $this->styleLink( $file, $options );
3607 if ( $link ) {
3608 $links[$file] = $link;
3609 }
3610 }
3611 return $links;
3612 }
3613
3614 /**
3615 * Generate \<link\> tags for stylesheets
3616 *
3617 * @param string $style URL to the file
3618 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3619 * @return string HTML fragment
3620 */
3621 protected function styleLink( $style, array $options ) {
3622 if ( isset( $options['dir'] ) ) {
3623 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3624 return '';
3625 }
3626 }
3627
3628 if ( isset( $options['media'] ) ) {
3629 $media = self::transformCssMedia( $options['media'] );
3630 if ( is_null( $media ) ) {
3631 return '';
3632 }
3633 } else {
3634 $media = 'all';
3635 }
3636
3637 if ( substr( $style, 0, 1 ) == '/' ||
3638 substr( $style, 0, 5 ) == 'http:' ||
3639 substr( $style, 0, 6 ) == 'https:' ) {
3640 $url = $style;
3641 } else {
3642 $config = $this->getConfig();
3643 // Append file hash as query parameter
3644 $url = self::transformResourcePath(
3645 $config,
3646 $config->get( 'StylePath' ) . '/' . $style
3647 );
3648 }
3649
3650 $link = Html::linkedStyle( $url, $media );
3651
3652 if ( isset( $options['condition'] ) ) {
3653 $condition = htmlspecialchars( $options['condition'] );
3654 $link = "<!--[if $condition]>$link<![endif]-->";
3655 }
3656 return $link;
3657 }
3658
3659 /**
3660 * Transform path to web-accessible static resource.
3661 *
3662 * This is used to add a validation hash as query string.
3663 * This aids various behaviors:
3664 *
3665 * - Put long Cache-Control max-age headers on responses for improved
3666 * cache performance.
3667 * - Get the correct version of a file as expected by the current page.
3668 * - Instantly get the updated version of a file after deployment.
3669 *
3670 * Avoid using this for urls included in HTML as otherwise clients may get different
3671 * versions of a resource when navigating the site depending on when the page was cached.
3672 * If changes to the url propagate, this is not a problem (e.g. if the url is in
3673 * an external stylesheet).
3674 *
3675 * @since 1.27
3676 * @param Config $config
3677 * @param string $path Path-absolute URL to file (from document root, must start with "/")
3678 * @return string URL
3679 */
3680 public static function transformResourcePath( Config $config, $path ) {
3681 global $IP;
3682
3683 $localDir = $IP;
3684 $remotePathPrefix = $config->get( 'ResourceBasePath' );
3685 if ( $remotePathPrefix === '' ) {
3686 // The configured base path is required to be empty string for
3687 // wikis in the domain root
3688 $remotePath = '/';
3689 } else {
3690 $remotePath = $remotePathPrefix;
3691 }
3692 if ( strpos( $path, $remotePath ) !== 0 || substr( $path, 0, 2 ) === '//' ) {
3693 // - Path is outside wgResourceBasePath, ignore.
3694 // - Path is protocol-relative. Fixes T155310. Not supported by RelPath lib.
3695 return $path;
3696 }
3697 // For files in resources, extensions/ or skins/, ResourceBasePath is preferred here.
3698 // For other misc files in $IP, we'll fallback to that as well. There is, however, a fourth
3699 // supported dir/path pair in the configuration (wgUploadDirectory, wgUploadPath)
3700 // which is not expected to be in wgResourceBasePath on CDNs. (T155146)
3701 $uploadPath = $config->get( 'UploadPath' );
3702 if ( strpos( $path, $uploadPath ) === 0 ) {
3703 $localDir = $config->get( 'UploadDirectory' );
3704 $remotePathPrefix = $remotePath = $uploadPath;
3705 }
3706
3707 $path = RelPath::getRelativePath( $path, $remotePath );
3708 return self::transformFilePath( $remotePathPrefix, $localDir, $path );
3709 }
3710
3711 /**
3712 * Utility method for transformResourceFilePath().
3713 *
3714 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
3715 *
3716 * @since 1.27
3717 * @param string $remotePathPrefix URL path prefix that points to $localPath
3718 * @param string $localPath File directory exposed at $remotePath
3719 * @param string $file Path to target file relative to $localPath
3720 * @return string URL
3721 */
3722 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
3723 $hash = md5_file( "$localPath/$file" );
3724 if ( $hash === false ) {
3725 wfLogWarning( __METHOD__ . ": Failed to hash $localPath/$file" );
3726 $hash = '';
3727 }
3728 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
3729 }
3730
3731 /**
3732 * Transform "media" attribute based on request parameters
3733 *
3734 * @param string $media Current value of the "media" attribute
3735 * @return string Modified value of the "media" attribute, or null to skip
3736 * this stylesheet
3737 */
3738 public static function transformCssMedia( $media ) {
3739 global $wgRequest;
3740
3741 // https://www.w3.org/TR/css3-mediaqueries/#syntax
3742 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3743
3744 // Switch in on-screen display for media testing
3745 $switches = [
3746 'printable' => 'print',
3747 'handheld' => 'handheld',
3748 ];
3749 foreach ( $switches as $switch => $targetMedia ) {
3750 if ( $wgRequest->getBool( $switch ) ) {
3751 if ( $media == $targetMedia ) {
3752 $media = '';
3753 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3754 /* This regex will not attempt to understand a comma-separated media_query_list
3755 *
3756 * Example supported values for $media:
3757 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3758 * Example NOT supported value for $media:
3759 * '3d-glasses, screen, print and resolution > 90dpi'
3760 *
3761 * If it's a print request, we never want any kind of screen stylesheets
3762 * If it's a handheld request (currently the only other choice with a switch),
3763 * we don't want simple 'screen' but we might want screen queries that
3764 * have a max-width or something, so we'll pass all others on and let the
3765 * client do the query.
3766 */
3767 if ( $targetMedia == 'print' || $media == 'screen' ) {
3768 return null;
3769 }
3770 }
3771 }
3772 }
3773
3774 return $media;
3775 }
3776
3777 /**
3778 * Add a wikitext-formatted message to the output.
3779 * This is equivalent to:
3780 *
3781 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3782 */
3783 public function addWikiMsg( /*...*/ ) {
3784 $args = func_get_args();
3785 $name = array_shift( $args );
3786 $this->addWikiMsgArray( $name, $args );
3787 }
3788
3789 /**
3790 * Add a wikitext-formatted message to the output.
3791 * Like addWikiMsg() except the parameters are taken as an array
3792 * instead of a variable argument list.
3793 *
3794 * @param string $name
3795 * @param array $args
3796 */
3797 public function addWikiMsgArray( $name, $args ) {
3798 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3799 }
3800
3801 /**
3802 * This function takes a number of message/argument specifications, wraps them in
3803 * some overall structure, and then parses the result and adds it to the output.
3804 *
3805 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3806 * and so on. The subsequent arguments may be either
3807 * 1) strings, in which case they are message names, or
3808 * 2) arrays, in which case, within each array, the first element is the message
3809 * name, and subsequent elements are the parameters to that message.
3810 *
3811 * Don't use this for messages that are not in the user's interface language.
3812 *
3813 * For example:
3814 *
3815 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3816 *
3817 * Is equivalent to:
3818 *
3819 * $wgOut->addWikiText( "<div class='error'>\n"
3820 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3821 *
3822 * The newline after the opening div is needed in some wikitext. See T21226.
3823 *
3824 * @param string $wrap
3825 */
3826 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3827 $msgSpecs = func_get_args();
3828 array_shift( $msgSpecs );
3829 $msgSpecs = array_values( $msgSpecs );
3830 $s = $wrap;
3831 foreach ( $msgSpecs as $n => $spec ) {
3832 if ( is_array( $spec ) ) {
3833 $args = $spec;
3834 $name = array_shift( $args );
3835 if ( isset( $args['options'] ) ) {
3836 unset( $args['options'] );
3837 wfDeprecated(
3838 'Adding "options" to ' . __METHOD__ . ' is no longer supported',
3839 '1.20'
3840 );
3841 }
3842 } else {
3843 $args = [];
3844 $name = $spec;
3845 }
3846 $s = str_replace( '$' . ( $n + 1 ), $this->msg( $name, $args )->plain(), $s );
3847 }
3848 $this->addWikiText( $s );
3849 }
3850
3851 /**
3852 * Whether the output has a table of contents
3853 * @return bool
3854 * @since 1.22
3855 */
3856 public function isTOCEnabled() {
3857 return $this->mEnableTOC;
3858 }
3859
3860 /**
3861 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3862 * @param bool $flag
3863 * @since 1.23
3864 * @deprecated since 1.31, use $poOptions to addParserOutput() instead.
3865 */
3866 public function enableSectionEditLinks( $flag = true ) {
3867 wfDeprecated( __METHOD__, '1.31' );
3868 }
3869
3870 /**
3871 * @return bool
3872 * @since 1.23
3873 * @deprecated since 1.31, use $poOptions to addParserOutput() instead.
3874 */
3875 public function sectionEditLinksEnabled() {
3876 wfDeprecated( __METHOD__, '1.31' );
3877 return true;
3878 }
3879
3880 /**
3881 * Helper function to setup the PHP implementation of OOUI to use in this request.
3882 *
3883 * @since 1.26
3884 * @param String $skinName The Skin name to determine the correct OOUI theme
3885 * @param String $dir Language direction
3886 */
3887 public static function setupOOUI( $skinName = 'default', $dir = 'ltr' ) {
3888 $themes = ResourceLoaderOOUIModule::getSkinThemeMap();
3889 $theme = $themes[$skinName] ?? $themes['default'];
3890 // For example, 'OOUI\WikimediaUITheme'.
3891 $themeClass = "OOUI\\{$theme}Theme";
3892 OOUI\Theme::setSingleton( new $themeClass() );
3893 OOUI\Element::setDefaultDir( $dir );
3894 }
3895
3896 /**
3897 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
3898 * MediaWiki and this OutputPage instance.
3899 *
3900 * @since 1.25
3901 */
3902 public function enableOOUI() {
3903 self::setupOOUI(
3904 strtolower( $this->getSkin()->getSkinName() ),
3905 $this->getLanguage()->getDir()
3906 );
3907 $this->addModuleStyles( [
3908 'oojs-ui-core.styles',
3909 'oojs-ui.styles.indicators',
3910 'oojs-ui.styles.textures',
3911 'mediawiki.widgets.styles',
3912 'oojs-ui.styles.icons-content',
3913 'oojs-ui.styles.icons-alerts',
3914 'oojs-ui.styles.icons-interactions',
3915 ] );
3916 }
3917
3918 /**
3919 * Add Link headers for preloading the wiki's logo.
3920 *
3921 * @since 1.26
3922 */
3923 protected function addLogoPreloadLinkHeaders() {
3924 $logo = ResourceLoaderSkinModule::getLogo( $this->getConfig() );
3925
3926 $tags = [];
3927 $logosPerDppx = [];
3928 $logos = [];
3929
3930 if ( !is_array( $logo ) ) {
3931 // No media queries required if we only have one variant
3932 $this->addLinkHeader( '<' . $logo . '>;rel=preload;as=image' );
3933 return;
3934 }
3935
3936 if ( isset( $logo['svg'] ) ) {
3937 // No media queries required if we only have a 1x and svg variant
3938 // because all preload-capable browsers support SVGs
3939 $this->addLinkHeader( '<' . $logo['svg'] . '>;rel=preload;as=image' );
3940 return;
3941 }
3942
3943 foreach ( $logo as $dppx => $src ) {
3944 // Keys are in this format: "1.5x"
3945 $dppx = substr( $dppx, 0, -1 );
3946 $logosPerDppx[$dppx] = $src;
3947 }
3948
3949 // Because PHP can't have floats as array keys
3950 uksort( $logosPerDppx, function ( $a , $b ) {
3951 $a = floatval( $a );
3952 $b = floatval( $b );
3953 // Sort from smallest to largest (e.g. 1x, 1.5x, 2x)
3954 return $a <=> $b;
3955 } );
3956
3957 foreach ( $logosPerDppx as $dppx => $src ) {
3958 $logos[] = [ 'dppx' => $dppx, 'src' => $src ];
3959 }
3960
3961 $logosCount = count( $logos );
3962 // Logic must match ResourceLoaderSkinModule:
3963 // - 1x applies to resolution < 1.5dppx
3964 // - 1.5x applies to resolution >= 1.5dppx && < 2dppx
3965 // - 2x applies to resolution >= 2dppx
3966 // Note that min-resolution and max-resolution are both inclusive.
3967 for ( $i = 0; $i < $logosCount; $i++ ) {
3968 if ( $i === 0 ) {
3969 // Smallest dppx
3970 // min-resolution is ">=" (larger than or equal to)
3971 // "not min-resolution" is essentially "<"
3972 $media_query = 'not all and (min-resolution: ' . $logos[ 1 ]['dppx'] . 'dppx)';
3973 } elseif ( $i !== $logosCount - 1 ) {
3974 // In between
3975 // Media query expressions can only apply "not" to the entire expression
3976 // (e.g. can't express ">= 1.5 and not >= 2).
3977 // Workaround: Use <= 1.9999 in place of < 2.
3978 $upper_bound = floatval( $logos[ $i + 1 ]['dppx'] ) - 0.000001;
3979 $media_query = '(min-resolution: ' . $logos[ $i ]['dppx'] .
3980 'dppx) and (max-resolution: ' . $upper_bound . 'dppx)';
3981 } else {
3982 // Largest dppx
3983 $media_query = '(min-resolution: ' . $logos[ $i ]['dppx'] . 'dppx)';
3984 }
3985
3986 $this->addLinkHeader(
3987 '<' . $logos[$i]['src'] . '>;rel=preload;as=image;media=' . $media_query
3988 );
3989 }
3990 }
3991
3992 /**
3993 * Get (and set if not yet set) the CSP nonce.
3994 *
3995 * This value needs to be included in any <script> tags on the
3996 * page.
3997 *
3998 * @return string|bool Nonce or false to mean don't output nonce
3999 * @since 1.32
4000 */
4001 public function getCSPNonce() {
4002 if ( !ContentSecurityPolicy::isNonceRequired( $this->getConfig() ) ) {
4003 return false;
4004 }
4005 if ( $this->CSPNonce === null ) {
4006 // XXX It might be expensive to generate randomness
4007 // on every request, on Windows.
4008 $rand = random_bytes( 15 );
4009 $this->CSPNonce = base64_encode( $rand );
4010 }
4011 return $this->CSPNonce;
4012 }
4013 }