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