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