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