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