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