3 * Preparation for the final page rendering.
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.
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.
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
23 use MediaWiki\Logger\LoggerFactory
;
24 use MediaWiki\MediaWikiServices
;
25 use MediaWiki\Session\SessionManager
;
26 use Wikimedia\RelPath
;
27 use Wikimedia\WrappedString
;
28 use Wikimedia\WrappedStringList
;
31 * This class should be covered by a general architecture document which does
32 * not exist as of January 2011. This is one of the Core classes and should
33 * be read at least once by any new developers.
35 * This class is used to prepare the final rendering. A skin is then
36 * applied to the output parameters (links, javascript, html, categories ...).
38 * @todo FIXME: Another class handles sending the whole page to the client.
40 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
45 class OutputPage
extends ContextSource
{
46 /** @var array Should be private. Used with addMeta() which adds "<meta>" */
47 protected $mMetatags = [];
50 protected $mLinktags = [];
53 protected $mCanonicalUrl = false;
56 * @var array Additional stylesheets. Looks like this is for extensions.
57 * Might be replaced by ResourceLoader.
59 protected $mExtStyles = [];
62 * @var string Should be private - has getter and setter. Contains
64 public $mPagetitle = '';
67 * @var string Contains all of the "<body>" content. Should be private we
68 * got set/get accessors and the append() method.
70 public $mBodytext = '';
72 /** @var string Stores contents of "<title>" tag */
73 private $mHTMLtitle = '';
76 * @var bool Is the displayed content related to the source of the
77 * corresponding wiki article.
79 private $mIsarticle = false;
81 /** @var bool Stores "article flag" toggle. */
82 private $mIsArticleRelated = true;
85 * @var bool We have to set isPrintable(). Some pages should
86 * never be printed (ex: redirections).
88 private $mPrintable = false;
91 * @var array Contains the page subtitle. Special pages usually have some
92 * links here. Don't confuse with site subtitle added by skins.
94 private $mSubtitle = [];
97 public $mRedirect = '';
100 protected $mStatusCode;
103 * @var string Used for sending cache control.
104 * The whole caching system should probably be moved into its own class.
106 protected $mLastModified = '';
109 protected $mCategoryLinks = [];
112 protected $mCategories = [
118 protected $mIndicators = [];
120 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
121 private $mLanguageLinks = [];
124 * Used for JavaScript (predates ResourceLoader)
125 * @todo We should split JS / CSS.
126 * mScripts content is inserted as is in "<head>" by Skin. This might
127 * contain either a link to a stylesheet or inline CSS.
129 private $mScripts = '';
131 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
132 protected $mInlineStyles = '';
135 * @var string Used by skin template.
136 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
138 public $mPageLinkTitle = '';
140 /** @var array Array of elements in "<head>". Parser might add its own headers! */
141 protected $mHeadItems = [];
143 /** @var array Additional <body> classes; there are also <body> classes from other sources */
144 protected $mAdditionalBodyClasses = [];
147 protected $mModules = [];
150 protected $mModuleScripts = [];
153 protected $mModuleStyles = [];
155 /** @var ResourceLoader */
156 protected $mResourceLoader;
158 /** @var ResourceLoaderClientHtml */
161 /** @var ResourceLoaderContext */
162 private $rlClientContext;
165 private $rlUserModuleState;
168 private $rlExemptStyleModules;
171 protected $mJsConfigVars = [];
174 protected $mTemplateIds = [];
177 protected $mImageTimeKeys = [];
180 public $mRedirectCode = '';
182 protected $mFeedLinksAppendQuery = null;
185 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
186 * @see ResourceLoaderModule::$origin
187 * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
189 protected $mAllowedModules = [
190 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
193 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
194 protected $mDoNothing = false;
199 protected $mContainsNewMagic = 0;
202 * lazy initialised, use parserOptions()
205 protected $mParserOptions = null;
208 * Handles the Atom / RSS links.
209 * We probably only support Atom in 2011.
210 * @see $wgAdvertisedFeedTypes
212 private $mFeedLinks = [];
214 // Gwicke work on squid caching? Roughly from 2003.
215 protected $mEnableClientCache = true;
217 /** @var bool Flag if output should only contain the body of the article. */
218 private $mArticleBodyOnly = false;
221 protected $mNewSectionLink = false;
224 protected $mHideNewSectionLink = false;
227 * @var bool Comes from the parser. This was probably made to load CSS/JS
228 * only if we had "<gallery>". Used directly in CategoryPage.php.
229 * Looks like ResourceLoader can replace this.
231 public $mNoGallery = false;
234 private $mPageTitleActionText = '';
236 /** @var int Cache stuff. Looks like mEnableClientCache */
237 protected $mCdnMaxage = 0;
238 /** @var int Upper limit on mCdnMaxage */
239 protected $mCdnMaxageLimit = INF
;
242 * @var bool Controls if anti-clickjacking / frame-breaking headers will
243 * be sent. This should be done for pages where edit actions are possible.
244 * Setters: $this->preventClickjacking() and $this->allowClickjacking().
246 protected $mPreventClickjacking = true;
248 /** @var int To include the variable {{REVISIONID}} */
249 private $mRevisionId = null;
252 private $mRevisionTimestamp = null;
255 protected $mFileVersion = null;
258 * @var array An array of stylesheet filenames (relative from skins path),
259 * with options for CSS media, IE conditions, and RTL/LTR direction.
260 * For internal use; add settings in the skin via $this->addStyle()
262 * Style again! This seems like a code duplication since we already have
263 * mStyles. This is what makes Open Source amazing.
265 protected $styles = [];
267 private $mIndexPolicy = 'index';
268 private $mFollowPolicy = 'follow';
269 private $mVaryHeader = [
270 'Accept-Encoding' => [ 'match=gzip' ],
274 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
279 private $mRedirectedFrom = null;
282 * Additional key => value data
284 private $mProperties = [];
287 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
289 private $mTarget = null;
292 * @var bool Whether parser output contains a table of contents
294 private $mEnableTOC = false;
297 * @var bool Whether parser output should contain section edit links
299 private $mEnableSectionEditLinks = true;
302 * @var string|null The URL to send in a <link> element with rel=license
304 private $copyrightUrl;
306 /** @var array Profiling data */
307 private $limitReportJSData = [];
310 * Link: header contents
312 private $mLinkHeader = [];
315 * Constructor for OutputPage. This should not be called directly.
316 * Instead a new RequestContext should be created and it will implicitly create
317 * a OutputPage tied to that context.
318 * @param IContextSource $context
320 function __construct( IContextSource
$context ) {
321 $this->setContext( $context );
325 * Redirect to $url rather than displaying the normal page
328 * @param string $responsecode HTTP status code
330 public function redirect( $url, $responsecode = '302' ) {
331 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
332 $this->mRedirect
= str_replace( "\n", '', $url );
333 $this->mRedirectCode
= $responsecode;
337 * Get the URL to redirect to, or an empty string if not redirect URL set
341 public function getRedirect() {
342 return $this->mRedirect
;
346 * Set the copyright URL to send with the output.
347 * Empty string to omit, null to reset.
351 * @param string|null $url
353 public function setCopyrightUrl( $url ) {
354 $this->copyrightUrl
= $url;
358 * Set the HTTP status code to send with the output.
360 * @param int $statusCode
362 public function setStatusCode( $statusCode ) {
363 $this->mStatusCode
= $statusCode;
367 * Add a new "<meta>" tag
368 * To add an http-equiv meta tag, precede the name with "http:"
370 * @param string $name Name of the meta tag
371 * @param string $val Value of the meta tag
373 function addMeta( $name, $val ) {
374 array_push( $this->mMetatags
, [ $name, $val ] );
378 * Returns the current <meta> tags
383 public function getMetaTags() {
384 return $this->mMetatags
;
388 * Add a new \<link\> tag to the page header.
390 * Note: use setCanonicalUrl() for rel=canonical.
392 * @param array $linkarr Associative array of attributes.
394 function addLink( array $linkarr ) {
395 array_push( $this->mLinktags
, $linkarr );
399 * Returns the current <link> tags
404 public function getLinkTags() {
405 return $this->mLinktags
;
409 * Add a new \<link\> with "rel" attribute set to "meta"
411 * @param array $linkarr Associative array mapping attribute names to their
412 * values, both keys and values will be escaped, and the
413 * "rel" attribute will be automatically added
415 function addMetadataLink( array $linkarr ) {
416 $linkarr['rel'] = $this->getMetadataAttribute();
417 $this->addLink( $linkarr );
421 * Set the URL to be used for the <link rel=canonical>. This should be used
422 * in preference to addLink(), to avoid duplicate link tags.
425 function setCanonicalUrl( $url ) {
426 $this->mCanonicalUrl
= $url;
430 * Returns the URL to be used for the <link rel=canonical> if
434 * @return bool|string
436 public function getCanonicalUrl() {
437 return $this->mCanonicalUrl
;
441 * Get the value of the "rel" attribute for metadata links
445 public function getMetadataAttribute() {
446 # note: buggy CC software only reads first "meta" link
447 static $haveMeta = false;
449 return 'alternate meta';
457 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
458 * Internal use only. Use OutputPage::addModules() or OutputPage::addJsConfigVars()
461 * @param string $script Raw HTML
463 function addScript( $script ) {
464 $this->mScripts
.= $script;
468 * Add a JavaScript file out of skins/common, or a given relative path.
469 * Internal use only. Use OutputPage::addModules() if possible.
471 * @param string $file Filename in skins/common or complete on-server path
473 * @param string $version Style version of the file. Defaults to $wgStyleVersion
475 public function addScriptFile( $file, $version = null ) {
476 // See if $file parameter is an absolute URL or begins with a slash
477 if ( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
480 $path = $this->getConfig()->get( 'StylePath' ) . "/common/{$file}";
482 if ( is_null( $version ) ) {
483 $version = $this->getConfig()->get( 'StyleVersion' );
485 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
489 * Add a self-contained script tag with the given contents
490 * Internal use only. Use OutputPage::addModules() if possible.
492 * @param string $script JavaScript text, no script tags
494 public function addInlineScript( $script ) {
495 $this->mScripts
.= Html
::inlineScript( $script );
499 * Filter an array of modules to remove insufficiently trustworthy members, and modules
500 * which are no longer registered (eg a page is cached before an extension is disabled)
501 * @param array $modules
502 * @param string|null $position If not null, only return modules with this position
503 * @param string $type
506 protected function filterModules( array $modules, $position = null,
507 $type = ResourceLoaderModule
::TYPE_COMBINED
509 $resourceLoader = $this->getResourceLoader();
510 $filteredModules = [];
511 foreach ( $modules as $val ) {
512 $module = $resourceLoader->getModule( $val );
513 if ( $module instanceof ResourceLoaderModule
514 && $module->getOrigin() <= $this->getAllowedModules( $type )
515 && ( is_null( $position ) ||
$module->getPosition() == $position )
517 if ( $this->mTarget
&& !in_array( $this->mTarget
, $module->getTargets() ) ) {
518 $this->warnModuleTargetFilter( $module->getName() );
521 $filteredModules[] = $val;
524 return $filteredModules;
527 private function warnModuleTargetFilter( $moduleName ) {
528 static $warnings = [];
529 if ( isset( $warnings[$this->mTarget
][$moduleName] ) ) {
532 $warnings[$this->mTarget
][$moduleName] = true;
533 $this->getResourceLoader()->getLogger()->debug(
534 'Module "{module}" not loadable on target "{target}".',
536 'module' => $moduleName,
537 'target' => $this->mTarget
,
543 * Get the list of modules to include on this page
545 * @param bool $filter Whether to filter out insufficiently trustworthy modules
546 * @param string|null $position If not null, only return modules with this position
547 * @param string $param
548 * @param string $type
549 * @return array Array of module names
551 public function getModules( $filter = false, $position = null, $param = 'mModules',
552 $type = ResourceLoaderModule
::TYPE_COMBINED
554 $modules = array_values( array_unique( $this->$param ) );
556 ?
$this->filterModules( $modules, $position, $type )
561 * Add one or more modules recognized by ResourceLoader. Modules added
562 * through this function will be loaded by ResourceLoader when the
565 * @param string|array $modules Module name (string) or array of module names
567 public function addModules( $modules ) {
568 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
572 * Get the list of module JS to include on this page
574 * @param bool $filter
575 * @param string|null $position
576 * @return array Array of module names
578 public function getModuleScripts( $filter = false, $position = null ) {
579 return $this->getModules( $filter, $position, 'mModuleScripts',
580 ResourceLoaderModule
::TYPE_SCRIPTS
585 * Add only JS of one or more modules recognized by ResourceLoader. Module
586 * scripts added through this function will be loaded by ResourceLoader when
589 * @param string|array $modules Module name (string) or array of module names
591 public function addModuleScripts( $modules ) {
592 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
596 * Get the list of module CSS to include on this page
598 * @param bool $filter
599 * @param string|null $position
600 * @return array Array of module names
602 public function getModuleStyles( $filter = false, $position = null ) {
603 return $this->getModules( $filter, $position, 'mModuleStyles',
604 ResourceLoaderModule
::TYPE_STYLES
609 * Add only CSS of one or more modules recognized by ResourceLoader.
611 * Module styles added through this function will be added using standard link CSS
612 * tags, rather than as a combined Javascript and CSS package. Thus, they will
613 * load when JavaScript is disabled (unless CSS also happens to be disabled).
615 * @param string|array $modules Module name (string) or array of module names
617 public function addModuleStyles( $modules ) {
618 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
622 * @return null|string ResourceLoader target
624 public function getTarget() {
625 return $this->mTarget
;
629 * Sets ResourceLoader target for load.php links. If null, will be omitted
631 * @param string|null $target
633 public function setTarget( $target ) {
634 $this->mTarget
= $target;
638 * Get an array of head items
642 function getHeadItemsArray() {
643 return $this->mHeadItems
;
647 * Add or replace a head item to the output
649 * Whenever possible, use more specific options like ResourceLoader modules,
650 * OutputPage::addLink(), OutputPage::addMetaLink() and OutputPage::addFeedLink()
651 * Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
652 * OutputPage::addInlineScript() and OutputPage::addInlineStyle()
653 * This would be your very LAST fallback.
655 * @param string $name Item name
656 * @param string $value Raw HTML
658 public function addHeadItem( $name, $value ) {
659 $this->mHeadItems
[$name] = $value;
663 * Add one or more head items to the output
666 * @param string|string[] $values Raw HTML
668 public function addHeadItems( $values ) {
669 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$values );
673 * Check if the header item $name is already set
675 * @param string $name Item name
678 public function hasHeadItem( $name ) {
679 return isset( $this->mHeadItems
[$name] );
683 * Add a class to the <body> element
686 * @param string|string[] $classes One or more classes to add
688 public function addBodyClasses( $classes ) {
689 $this->mAdditionalBodyClasses
= array_merge( $this->mAdditionalBodyClasses
, (array)$classes );
693 * Set whether the output should only contain the body of the article,
694 * without any skin, sidebar, etc.
695 * Used e.g. when calling with "action=render".
697 * @param bool $only Whether to output only the body of the article
699 public function setArticleBodyOnly( $only ) {
700 $this->mArticleBodyOnly
= $only;
704 * Return whether the output will contain only the body of the article
708 public function getArticleBodyOnly() {
709 return $this->mArticleBodyOnly
;
713 * Set an additional output property
716 * @param string $name
717 * @param mixed $value
719 public function setProperty( $name, $value ) {
720 $this->mProperties
[$name] = $value;
724 * Get an additional output property
727 * @param string $name
728 * @return mixed Property value or null if not found
730 public function getProperty( $name ) {
731 if ( isset( $this->mProperties
[$name] ) ) {
732 return $this->mProperties
[$name];
739 * checkLastModified tells the client to use the client-cached page if
740 * possible. If successful, the OutputPage is disabled so that
741 * any future call to OutputPage->output() have no effect.
743 * Side effect: sets mLastModified for Last-Modified header
745 * @param string $timestamp
747 * @return bool True if cache-ok headers was sent.
749 public function checkLastModified( $timestamp ) {
750 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
751 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
754 $config = $this->getConfig();
755 if ( !$config->get( 'CachePages' ) ) {
756 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
760 $timestamp = wfTimestamp( TS_MW
, $timestamp );
762 'page' => $timestamp,
763 'user' => $this->getUser()->getTouched(),
764 'epoch' => $config->get( 'CacheEpoch' )
766 if ( $config->get( 'UseSquid' ) ) {
767 // T46570: the core page itself may not change, but resources might
768 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, time() - $config->get( 'SquidMaxage' ) );
770 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this ] );
772 $maxModified = max( $modifiedTimes );
773 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
775 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
776 if ( $clientHeader === false ) {
777 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header", 'private' );
781 # IE sends sizes after the date like this:
782 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
783 # this breaks strtotime().
784 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
786 MediaWiki\
suppressWarnings(); // E_STRICT system time bitching
787 $clientHeaderTime = strtotime( $clientHeader );
788 MediaWiki\restoreWarnings
();
789 if ( !$clientHeaderTime ) {
791 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
794 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
798 foreach ( $modifiedTimes as $name => $value ) {
799 if ( $info !== '' ) {
802 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
805 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
806 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ), 'private' );
807 wfDebug( __METHOD__
. ": effective Last-Modified: " .
808 wfTimestamp( TS_ISO_8601
, $maxModified ), 'private' );
809 if ( $clientHeaderTime < $maxModified ) {
810 wfDebug( __METHOD__
. ": STALE, $info", 'private' );
815 # Give a 304 Not Modified response code and disable body output
816 wfDebug( __METHOD__
. ": NOT MODIFIED, $info", 'private' );
817 ini_set( 'zlib.output_compression', 0 );
818 $this->getRequest()->response()->statusHeader( 304 );
819 $this->sendCacheControl();
822 // Don't output a compressed blob when using ob_gzhandler;
823 // it's technically against HTTP spec and seems to confuse
824 // Firefox when the response gets split over two packets.
825 wfClearOutputBuffers();
831 * Override the last modified timestamp
833 * @param string $timestamp New timestamp, in a format readable by
836 public function setLastModified( $timestamp ) {
837 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
841 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
843 * @param string $policy The literal string to output as the contents of
844 * the meta tag. Will be parsed according to the spec and output in
848 public function setRobotPolicy( $policy ) {
849 $policy = Article
::formatRobotPolicy( $policy );
851 if ( isset( $policy['index'] ) ) {
852 $this->setIndexPolicy( $policy['index'] );
854 if ( isset( $policy['follow'] ) ) {
855 $this->setFollowPolicy( $policy['follow'] );
860 * Set the index policy for the page, but leave the follow policy un-
863 * @param string $policy Either 'index' or 'noindex'.
866 public function setIndexPolicy( $policy ) {
867 $policy = trim( $policy );
868 if ( in_array( $policy, [ 'index', 'noindex' ] ) ) {
869 $this->mIndexPolicy
= $policy;
874 * Set the follow policy for the page, but leave the index policy un-
877 * @param string $policy Either 'follow' or 'nofollow'.
880 public function setFollowPolicy( $policy ) {
881 $policy = trim( $policy );
882 if ( in_array( $policy, [ 'follow', 'nofollow' ] ) ) {
883 $this->mFollowPolicy
= $policy;
888 * Set the new value of the "action text", this will be added to the
889 * "HTML title", separated from it with " - ".
891 * @param string $text New value of the "action text"
893 public function setPageTitleActionText( $text ) {
894 $this->mPageTitleActionText
= $text;
898 * Get the value of the "action text"
902 public function getPageTitleActionText() {
903 return $this->mPageTitleActionText
;
907 * "HTML title" means the contents of "<title>".
908 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
910 * @param string|Message $name
912 public function setHTMLTitle( $name ) {
913 if ( $name instanceof Message
) {
914 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
916 $this->mHTMLtitle
= $name;
921 * Return the "HTML title", i.e. the content of the "<title>" tag.
925 public function getHTMLTitle() {
926 return $this->mHTMLtitle
;
930 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
934 public function setRedirectedFrom( $t ) {
935 $this->mRedirectedFrom
= $t;
939 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
940 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
941 * but not bad tags like \<script\>. This function automatically sets
942 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
943 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
944 * good tags like \<i\> will be dropped entirely.
946 * @param string|Message $name
948 public function setPageTitle( $name ) {
949 if ( $name instanceof Message
) {
950 $name = $name->setContext( $this->getContext() )->text();
953 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
954 # but leave "<i>foobar</i>" alone
955 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
956 $this->mPagetitle
= $nameWithTags;
958 # change "<i>foo&bar</i>" to "foo&bar"
960 $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) )
961 ->inContentLanguage()
966 * Return the "page title", i.e. the content of the \<h1\> tag.
970 public function getPageTitle() {
971 return $this->mPagetitle
;
975 * Set the Title object to use
979 public function setTitle( Title
$t ) {
980 $this->getContext()->setTitle( $t );
984 * Replace the subtitle with $str
986 * @param string|Message $str New value of the subtitle. String should be safe HTML.
988 public function setSubtitle( $str ) {
989 $this->clearSubtitle();
990 $this->addSubtitle( $str );
994 * Add $str to the subtitle
996 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
998 public function addSubtitle( $str ) {
999 if ( $str instanceof Message
) {
1000 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
1002 $this->mSubtitle
[] = $str;
1007 * Build message object for a subtitle containing a backlink to a page
1009 * @param Title $title Title to link to
1010 * @param array $query Array of additional parameters to include in the link
1014 public static function buildBacklinkSubtitle( Title
$title, $query = [] ) {
1015 if ( $title->isRedirect() ) {
1016 $query['redirect'] = 'no';
1018 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1019 return wfMessage( 'backlinksubtitle' )
1020 ->rawParams( $linkRenderer->makeLink( $title, null, [], $query ) );
1024 * Add a subtitle containing a backlink to a page
1026 * @param Title $title Title to link to
1027 * @param array $query Array of additional parameters to include in the link
1029 public function addBacklinkSubtitle( Title
$title, $query = [] ) {
1030 $this->addSubtitle( self
::buildBacklinkSubtitle( $title, $query ) );
1034 * Clear the subtitles
1036 public function clearSubtitle() {
1037 $this->mSubtitle
= [];
1045 public function getSubtitle() {
1046 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1050 * Set the page as printable, i.e. it'll be displayed with all
1051 * print styles included
1053 public function setPrintable() {
1054 $this->mPrintable
= true;
1058 * Return whether the page is "printable"
1062 public function isPrintable() {
1063 return $this->mPrintable
;
1067 * Disable output completely, i.e. calling output() will have no effect
1069 public function disable() {
1070 $this->mDoNothing
= true;
1074 * Return whether the output will be completely disabled
1078 public function isDisabled() {
1079 return $this->mDoNothing
;
1083 * Show an "add new section" link?
1087 public function showNewSectionLink() {
1088 return $this->mNewSectionLink
;
1092 * Forcibly hide the new section link?
1096 public function forceHideNewSectionLink() {
1097 return $this->mHideNewSectionLink
;
1101 * Add or remove feed links in the page header
1102 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1103 * for the new version
1104 * @see addFeedLink()
1106 * @param bool $show True: add default feeds, false: remove all feeds
1108 public function setSyndicated( $show = true ) {
1110 $this->setFeedAppendQuery( false );
1112 $this->mFeedLinks
= [];
1117 * Add default feeds to the page header
1118 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1119 * for the new version
1120 * @see addFeedLink()
1122 * @param string $val Query to append to feed links or false to output
1125 public function setFeedAppendQuery( $val ) {
1126 $this->mFeedLinks
= [];
1128 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1129 $query = "feed=$type";
1130 if ( is_string( $val ) ) {
1131 $query .= '&' . $val;
1133 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1138 * Add a feed link to the page header
1140 * @param string $format Feed type, should be a key of $wgFeedClasses
1141 * @param string $href URL
1143 public function addFeedLink( $format, $href ) {
1144 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1145 $this->mFeedLinks
[$format] = $href;
1150 * Should we output feed links for this page?
1153 public function isSyndicated() {
1154 return count( $this->mFeedLinks
) > 0;
1158 * Return URLs for each supported syndication format for this page.
1159 * @return array Associating format keys with URLs
1161 public function getSyndicationLinks() {
1162 return $this->mFeedLinks
;
1166 * Will currently always return null
1170 public function getFeedAppendQuery() {
1171 return $this->mFeedLinksAppendQuery
;
1175 * Set whether the displayed content is related to the source of the
1176 * corresponding article on the wiki
1177 * Setting true will cause the change "article related" toggle to true
1181 public function setArticleFlag( $v ) {
1182 $this->mIsarticle
= $v;
1184 $this->mIsArticleRelated
= $v;
1189 * Return whether the content displayed page is related to the source of
1190 * the corresponding article on the wiki
1194 public function isArticle() {
1195 return $this->mIsarticle
;
1199 * Set whether this page is related an article on the wiki
1200 * Setting false will cause the change of "article flag" toggle to false
1204 public function setArticleRelated( $v ) {
1205 $this->mIsArticleRelated
= $v;
1207 $this->mIsarticle
= false;
1212 * Return whether this page is related an article on the wiki
1216 public function isArticleRelated() {
1217 return $this->mIsArticleRelated
;
1221 * Add new language links
1223 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1224 * (e.g. 'fr:Test page')
1226 public function addLanguageLinks( array $newLinkArray ) {
1227 $this->mLanguageLinks +
= $newLinkArray;
1231 * Reset the language links and add new language links
1233 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1234 * (e.g. 'fr:Test page')
1236 public function setLanguageLinks( array $newLinkArray ) {
1237 $this->mLanguageLinks
= $newLinkArray;
1241 * Get the list of language links
1243 * @return string[] Array of interwiki-prefixed (non DB key) titles (e.g. 'fr:Test page')
1245 public function getLanguageLinks() {
1246 return $this->mLanguageLinks
;
1250 * Add an array of categories, with names in the keys
1252 * @param array $categories Mapping category name => sort key
1254 public function addCategoryLinks( array $categories ) {
1257 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1261 $res = $this->addCategoryLinksToLBAndGetResult( $categories );
1263 # Set all the values to 'normal'.
1264 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1266 # Mark hidden categories
1267 foreach ( $res as $row ) {
1268 if ( isset( $row->pp_value
) ) {
1269 $categories[$row->page_title
] = 'hidden';
1273 // Avoid PHP 7.1 warning of passing $this by reference
1274 $outputPage = $this;
1275 # Add the remaining categories to the skin
1277 'OutputPageMakeCategoryLinks',
1278 [ &$outputPage, $categories, &$this->mCategoryLinks
] )
1280 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1281 foreach ( $categories as $category => $type ) {
1282 // array keys will cast numeric category names to ints, so cast back to string
1283 $category = (string)$category;
1284 $origcategory = $category;
1285 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1289 $wgContLang->findVariantLink( $category, $title, true );
1290 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1293 $text = $wgContLang->convertHtml( $title->getText() );
1294 $this->mCategories
[$type][] = $title->getText();
1295 $this->mCategoryLinks
[$type][] = $linkRenderer->makeLink( $title, new HtmlArmor( $text ) );
1301 * @param array $categories
1302 * @return bool|ResultWrapper
1304 protected function addCategoryLinksToLBAndGetResult( array $categories ) {
1305 # Add the links to a LinkBatch
1306 $arr = [ NS_CATEGORY
=> $categories ];
1307 $lb = new LinkBatch
;
1308 $lb->setArray( $arr );
1310 # Fetch existence plus the hiddencat property
1311 $dbr = wfGetDB( DB_REPLICA
);
1312 $fields = array_merge(
1313 LinkCache
::getSelectFields(),
1314 [ 'page_namespace', 'page_title', 'pp_value' ]
1317 $res = $dbr->select( [ 'page', 'page_props' ],
1319 $lb->constructSet( 'page', $dbr ),
1322 [ 'page_props' => [ 'LEFT JOIN', [
1323 'pp_propname' => 'hiddencat',
1328 # Add the results to the link cache
1329 $lb->addResultToCache( LinkCache
::singleton(), $res );
1335 * Reset the category links (but not the category list) and add $categories
1337 * @param array $categories Mapping category name => sort key
1339 public function setCategoryLinks( array $categories ) {
1340 $this->mCategoryLinks
= [];
1341 $this->addCategoryLinks( $categories );
1345 * Get the list of category links, in a 2-D array with the following format:
1346 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1347 * hidden categories) and $link a HTML fragment with a link to the category
1352 public function getCategoryLinks() {
1353 return $this->mCategoryLinks
;
1357 * Get the list of category names this page belongs to.
1359 * @param string $type The type of categories which should be returned. Possible values:
1360 * * all: all categories of all types
1361 * * hidden: only the hidden categories
1362 * * normal: all categories, except hidden categories
1363 * @return array Array of strings
1365 public function getCategories( $type = 'all' ) {
1366 if ( $type === 'all' ) {
1367 $allCategories = [];
1368 foreach ( $this->mCategories
as $categories ) {
1369 $allCategories = array_merge( $allCategories, $categories );
1371 return $allCategories;
1373 if ( !isset( $this->mCategories
[$type] ) ) {
1374 throw new InvalidArgumentException( 'Invalid category type given: ' . $type );
1376 return $this->mCategories
[$type];
1380 * Add an array of indicators, with their identifiers as array
1381 * keys and HTML contents as values.
1383 * In case of duplicate keys, existing values are overwritten.
1385 * @param array $indicators
1388 public function setIndicators( array $indicators ) {
1389 $this->mIndicators
= $indicators +
$this->mIndicators
;
1390 // Keep ordered by key
1391 ksort( $this->mIndicators
);
1395 * Get the indicators associated with this page.
1397 * The array will be internally ordered by item keys.
1399 * @return array Keys: identifiers, values: HTML contents
1402 public function getIndicators() {
1403 return $this->mIndicators
;
1407 * Adds help link with an icon via page indicators.
1408 * Link target can be overridden by a local message containing a wikilink:
1409 * the message key is: lowercase action or special page name + '-helppage'.
1410 * @param string $to Target MediaWiki.org page title or encoded URL.
1411 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1414 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1415 $this->addModuleStyles( 'mediawiki.helplink' );
1416 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1418 if ( $overrideBaseUrl ) {
1421 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1422 $helpUrl = "//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1425 $link = Html
::rawElement(
1429 'target' => '_blank',
1430 'class' => 'mw-helplink',
1435 $this->setIndicators( [ 'mw-helplink' => $link ] );
1439 * Do not allow scripts which can be modified by wiki users to load on this page;
1440 * only allow scripts bundled with, or generated by, the software.
1441 * Site-wide styles are controlled by a config setting, since they can be
1442 * used to create a custom skin/theme, but not user-specific ones.
1444 * @todo this should be given a more accurate name
1446 public function disallowUserJs() {
1447 $this->reduceAllowedModules(
1448 ResourceLoaderModule
::TYPE_SCRIPTS
,
1449 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1452 // Site-wide styles are controlled by a config setting, see T73621
1453 // for background on why. User styles are never allowed.
1454 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1455 $styleOrigin = ResourceLoaderModule
::ORIGIN_USER_SITEWIDE
;
1457 $styleOrigin = ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
;
1459 $this->reduceAllowedModules(
1460 ResourceLoaderModule
::TYPE_STYLES
,
1466 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1467 * @see ResourceLoaderModule::$origin
1468 * @param string $type ResourceLoaderModule TYPE_ constant
1469 * @return int ResourceLoaderModule ORIGIN_ class constant
1471 public function getAllowedModules( $type ) {
1472 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1473 return min( array_values( $this->mAllowedModules
) );
1475 return isset( $this->mAllowedModules
[$type] )
1476 ?
$this->mAllowedModules
[$type]
1477 : ResourceLoaderModule
::ORIGIN_ALL
;
1482 * Limit the highest level of CSS/JS untrustworthiness allowed.
1484 * If passed the same or a higher level than the current level of untrustworthiness set, the
1485 * level will remain unchanged.
1487 * @param string $type
1488 * @param int $level ResourceLoaderModule class constant
1490 public function reduceAllowedModules( $type, $level ) {
1491 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1495 * Prepend $text to the body HTML
1497 * @param string $text HTML
1499 public function prependHTML( $text ) {
1500 $this->mBodytext
= $text . $this->mBodytext
;
1504 * Append $text to the body HTML
1506 * @param string $text HTML
1508 public function addHTML( $text ) {
1509 $this->mBodytext
.= $text;
1513 * Shortcut for adding an Html::element via addHTML.
1517 * @param string $element
1518 * @param array $attribs
1519 * @param string $contents
1521 public function addElement( $element, array $attribs = [], $contents = '' ) {
1522 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1526 * Clear the body HTML
1528 public function clearHTML() {
1529 $this->mBodytext
= '';
1535 * @return string HTML
1537 public function getHTML() {
1538 return $this->mBodytext
;
1542 * Get/set the ParserOptions object to use for wikitext parsing
1544 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1545 * current ParserOption object. This parameter is deprecated since 1.31.
1546 * @return ParserOptions
1548 public function parserOptions( $options = null ) {
1549 if ( $options !== null ) {
1550 wfDeprecated( __METHOD__
. ' with non-null $options', '1.31' );
1553 if ( $options !== null && !empty( $options->isBogus
) ) {
1554 // Someone is trying to set a bogus pre-$wgUser PO. Check if it has
1555 // been changed somehow, and keep it if so.
1556 $anonPO = ParserOptions
::newFromAnon();
1557 $anonPO->setEditSection( false );
1558 $anonPO->setAllowUnsafeRawHtml( false );
1559 if ( !$options->matches( $anonPO ) ) {
1560 wfLogWarning( __METHOD__
. ': Setting a changed bogus ParserOptions: ' . wfGetAllCallers( 5 ) );
1561 $options->isBogus
= false;
1565 if ( !$this->mParserOptions
) {
1566 if ( !$this->getContext()->getUser()->isSafeToLoad() ) {
1567 // $wgUser isn't unstubbable yet, so don't try to get a
1568 // ParserOptions for it. And don't cache this ParserOptions
1570 $po = ParserOptions
::newFromAnon();
1571 $po->setEditSection( false );
1572 $po->setAllowUnsafeRawHtml( false );
1573 $po->isBogus
= true;
1574 if ( $options !== null ) {
1575 $this->mParserOptions
= empty( $options->isBogus
) ?
$options : null;
1580 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1581 $this->mParserOptions
->setEditSection( false );
1582 $this->mParserOptions
->setAllowUnsafeRawHtml( false );
1585 if ( $options !== null && !empty( $options->isBogus
) ) {
1586 // They're trying to restore the bogus pre-$wgUser PO. Do the right
1588 return wfSetVar( $this->mParserOptions
, null, true );
1590 return wfSetVar( $this->mParserOptions
, $options );
1595 * Set the revision ID which will be seen by the wiki text parser
1596 * for things such as embedded {{REVISIONID}} variable use.
1598 * @param int|null $revid An positive integer, or null
1599 * @return mixed Previous value
1601 public function setRevisionId( $revid ) {
1602 $val = is_null( $revid ) ?
null : intval( $revid );
1603 return wfSetVar( $this->mRevisionId
, $val );
1607 * Get the displayed revision ID
1611 public function getRevisionId() {
1612 return $this->mRevisionId
;
1616 * Set the timestamp of the revision which will be displayed. This is used
1617 * to avoid a extra DB call in Skin::lastModified().
1619 * @param string|null $timestamp
1620 * @return mixed Previous value
1622 public function setRevisionTimestamp( $timestamp ) {
1623 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1627 * Get the timestamp of displayed revision.
1628 * This will be null if not filled by setRevisionTimestamp().
1630 * @return string|null
1632 public function getRevisionTimestamp() {
1633 return $this->mRevisionTimestamp
;
1637 * Set the displayed file version
1639 * @param File|bool $file
1640 * @return mixed Previous value
1642 public function setFileVersion( $file ) {
1644 if ( $file instanceof File
&& $file->exists() ) {
1645 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1647 return wfSetVar( $this->mFileVersion
, $val, true );
1651 * Get the displayed file version
1653 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1655 public function getFileVersion() {
1656 return $this->mFileVersion
;
1660 * Get the templates used on this page
1662 * @return array (namespace => dbKey => revId)
1665 public function getTemplateIds() {
1666 return $this->mTemplateIds
;
1670 * Get the files used on this page
1672 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1675 public function getFileSearchOptions() {
1676 return $this->mImageTimeKeys
;
1680 * Convert wikitext to HTML and add it to the buffer
1681 * Default assumes that the current page title will be used.
1683 * @param string $text
1684 * @param bool $linestart Is this the start of a line?
1685 * @param bool $interface Is this text in the user interface language?
1686 * @throws MWException
1688 public function addWikiText( $text, $linestart = true, $interface = true ) {
1689 $title = $this->getTitle(); // Work around E_STRICT
1691 throw new MWException( 'Title is null' );
1693 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1697 * Add wikitext with a custom Title object
1699 * @param string $text Wikitext
1700 * @param Title &$title
1701 * @param bool $linestart Is this the start of a line?
1703 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1704 $this->addWikiTextTitle( $text, $title, $linestart );
1708 * Add wikitext with a custom Title object and tidy enabled.
1710 * @param string $text Wikitext
1711 * @param Title &$title
1712 * @param bool $linestart Is this the start of a line?
1714 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1715 $this->addWikiTextTitle( $text, $title, $linestart, true );
1719 * Add wikitext with tidy enabled
1721 * @param string $text Wikitext
1722 * @param bool $linestart Is this the start of a line?
1724 public function addWikiTextTidy( $text, $linestart = true ) {
1725 $title = $this->getTitle();
1726 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1730 * Add wikitext with a custom Title object
1732 * @param string $text Wikitext
1733 * @param Title $title
1734 * @param bool $linestart Is this the start of a line?
1735 * @param bool $tidy Whether to use tidy
1736 * @param bool $interface Whether it is an interface message
1737 * (for example disables conversion)
1739 public function addWikiTextTitle( $text, Title
$title, $linestart,
1740 $tidy = false, $interface = false
1744 $popts = $this->parserOptions();
1745 $oldTidy = $popts->setTidy( $tidy );
1746 $popts->setInterfaceMessage( (bool)$interface );
1748 $parserOutput = $wgParser->getFreshParser()->parse(
1749 $text, $title, $popts,
1750 $linestart, true, $this->mRevisionId
1753 $popts->setTidy( $oldTidy );
1755 $this->addParserOutput( $parserOutput, [
1756 'enableSectionEditLinks' => false,
1761 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1762 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1766 * @param ParserOutput $parserOutput
1768 public function addParserOutputMetadata( $parserOutput ) {
1769 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1770 $this->addCategoryLinks( $parserOutput->getCategories() );
1771 $this->setIndicators( $parserOutput->getIndicators() );
1772 $this->mNewSectionLink
= $parserOutput->getNewSection();
1773 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1775 if ( !$parserOutput->isCacheable() ) {
1776 $this->enableClientCache( false );
1778 $this->mNoGallery
= $parserOutput->getNoGallery();
1779 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1780 $this->addModules( $parserOutput->getModules() );
1781 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1782 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1783 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1784 $this->mPreventClickjacking
= $this->mPreventClickjacking
1785 ||
$parserOutput->preventClickjacking();
1787 // Template versioning...
1788 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1789 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1790 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1792 $this->mTemplateIds
[$ns] = $dbks;
1795 // File versioning...
1796 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1797 $this->mImageTimeKeys
[$dbk] = $data;
1800 // Hooks registered in the object
1801 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1802 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1803 list( $hookName, $data ) = $hookInfo;
1804 if ( isset( $parserOutputHooks[$hookName] ) ) {
1805 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1809 // Enable OOUI if requested via ParserOutput
1810 if ( $parserOutput->getEnableOOUI() ) {
1811 $this->enableOOUI();
1814 // Include parser limit report
1815 if ( !$this->limitReportJSData
) {
1816 $this->limitReportJSData
= $parserOutput->getLimitReportJSData();
1819 // Link flags are ignored for now, but may in the future be
1820 // used to mark individual language links.
1822 // Avoid PHP 7.1 warning of passing $this by reference
1823 $outputPage = $this;
1824 Hooks
::run( 'LanguageLinks', [ $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ] );
1825 Hooks
::runWithoutAbort( 'OutputPageParserOutput', [ &$outputPage, $parserOutput ] );
1827 // This check must be after 'OutputPageParserOutput' runs in addParserOutputMetadata
1828 // so that extensions may modify ParserOutput to toggle TOC.
1829 // This cannot be moved to addParserOutputText because that is not
1830 // called by EditPage for Preview.
1831 if ( $parserOutput->getTOCEnabled() && $parserOutput->getTOCHTML() ) {
1832 $this->mEnableTOC
= true;
1837 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1838 * ParserOutput object, without any other metadata.
1841 * @param ParserOutput $parserOutput
1842 * @param array $poOptions Options to ParserOutput::getText()
1844 public function addParserOutputContent( $parserOutput, $poOptions = [] ) {
1845 $this->addParserOutputText( $parserOutput, $poOptions );
1847 $this->addModules( $parserOutput->getModules() );
1848 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1849 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1851 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1855 * Add the HTML associated with a ParserOutput object, without any metadata.
1858 * @param ParserOutput $parserOutput
1859 * @param array $poOptions Options to ParserOutput::getText()
1861 public function addParserOutputText( $parserOutput, $poOptions = [] ) {
1862 $text = $parserOutput->getText( $poOptions );
1863 // Avoid PHP 7.1 warning of passing $this by reference
1864 $outputPage = $this;
1865 Hooks
::runWithoutAbort( 'OutputPageBeforeHTML', [ &$outputPage, &$text ] );
1866 $this->addHTML( $text );
1870 * Add everything from a ParserOutput object.
1872 * @param ParserOutput $parserOutput
1873 * @param array $poOptions Options to ParserOutput::getText()
1875 function addParserOutput( $parserOutput, $poOptions = [] ) {
1876 $this->addParserOutputMetadata( $parserOutput );
1878 // Touch section edit links only if not previously disabled
1879 if ( $parserOutput->getEditSectionTokens() ) {
1880 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks
);
1882 if ( !$this->mEnableSectionEditLinks
1883 && !array_key_exists( 'enableSectionEditLinks', $poOptions )
1885 $poOptions['enableSectionEditLinks'] = false;
1888 $this->addParserOutputText( $parserOutput, $poOptions );
1892 * Add the output of a QuickTemplate to the output buffer
1894 * @param QuickTemplate &$template
1896 public function addTemplate( &$template ) {
1897 $this->addHTML( $template->getHTML() );
1901 * Parse wikitext and return the HTML.
1903 * @param string $text
1904 * @param bool $linestart Is this the start of a line?
1905 * @param bool $interface Use interface language ($wgLang instead of
1906 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1907 * This also disables LanguageConverter.
1908 * @param Language $language Target language object, will override $interface
1909 * @throws MWException
1910 * @return string HTML
1912 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1915 if ( is_null( $this->getTitle() ) ) {
1916 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1919 $popts = $this->parserOptions();
1921 $popts->setInterfaceMessage( true );
1923 if ( $language !== null ) {
1924 $oldLang = $popts->setTargetLanguage( $language );
1927 $parserOutput = $wgParser->getFreshParser()->parse(
1928 $text, $this->getTitle(), $popts,
1929 $linestart, true, $this->mRevisionId
1933 $popts->setInterfaceMessage( false );
1935 if ( $language !== null ) {
1936 $popts->setTargetLanguage( $oldLang );
1939 return $parserOutput->getText( [
1940 'enableSectionEditLinks' => false,
1945 * Parse wikitext, strip paragraphs, and return the HTML.
1947 * @param string $text
1948 * @param bool $linestart Is this the start of a line?
1949 * @param bool $interface Use interface language ($wgLang instead of
1950 * $wgContLang) while parsing language sensitive magic
1951 * words like GRAMMAR and PLURAL
1952 * @return string HTML
1954 public function parseInline( $text, $linestart = true, $interface = false ) {
1955 $parsed = $this->parse( $text, $linestart, $interface );
1956 return Parser
::stripOuterParagraph( $parsed );
1960 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1962 * @param int $maxage Maximum cache time on the CDN, in seconds.
1964 public function setCdnMaxage( $maxage ) {
1965 $this->mCdnMaxage
= min( $maxage, $this->mCdnMaxageLimit
);
1969 * Lower the value of the "s-maxage" part of the "Cache-control" HTTP header
1971 * @param int $maxage Maximum cache time on the CDN, in seconds
1974 public function lowerCdnMaxage( $maxage ) {
1975 $this->mCdnMaxageLimit
= min( $maxage, $this->mCdnMaxageLimit
);
1976 $this->setCdnMaxage( $this->mCdnMaxage
);
1980 * Get TTL in [$minTTL,$maxTTL] in pass it to lowerCdnMaxage()
1982 * This sets and returns $minTTL if $mtime is false or null. Otherwise,
1983 * the TTL is higher the older the $mtime timestamp is. Essentially, the
1984 * TTL is 90% of the age of the object, subject to the min and max.
1986 * @param string|int|float|bool|null $mtime Last-Modified timestamp
1987 * @param int $minTTL Mimimum TTL in seconds [default: 1 minute]
1988 * @param int $maxTTL Maximum TTL in seconds [default: $wgSquidMaxage]
1989 * @return int TTL in seconds
1992 public function adaptCdnTTL( $mtime, $minTTL = 0, $maxTTL = 0 ) {
1993 $minTTL = $minTTL ?
: IExpiringStore
::TTL_MINUTE
;
1994 $maxTTL = $maxTTL ?
: $this->getConfig()->get( 'SquidMaxage' );
1996 if ( $mtime === null ||
$mtime === false ) {
1997 return $minTTL; // entity does not exist
2000 $age = time() - wfTimestamp( TS_UNIX
, $mtime );
2001 $adaptiveTTL = max( 0.9 * $age, $minTTL );
2002 $adaptiveTTL = min( $adaptiveTTL, $maxTTL );
2004 $this->lowerCdnMaxage( (int)$adaptiveTTL );
2006 return $adaptiveTTL;
2010 * Use enableClientCache(false) to force it to send nocache headers
2012 * @param bool $state
2016 public function enableClientCache( $state ) {
2017 return wfSetVar( $this->mEnableClientCache
, $state );
2021 * Get the list of cookies that will influence on the cache
2025 function getCacheVaryCookies() {
2027 if ( $cookies === null ) {
2028 $config = $this->getConfig();
2029 $cookies = array_merge(
2030 SessionManager
::singleton()->getVaryCookies(),
2034 $config->get( 'CacheVaryCookies' )
2036 Hooks
::run( 'GetCacheVaryCookies', [ $this, &$cookies ] );
2042 * Check if the request has a cache-varying cookie header
2043 * If it does, it's very important that we don't allow public caching
2047 function haveCacheVaryCookies() {
2048 $request = $this->getRequest();
2049 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2050 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2051 wfDebug( __METHOD__
. ": found $cookieName\n" );
2055 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
2060 * Add an HTTP header that will influence on the cache
2062 * @param string $header Header name
2063 * @param string[]|null $option Options for the Key header. See
2064 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2065 * for the list of valid options.
2067 public function addVaryHeader( $header, array $option = null ) {
2068 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
2069 $this->mVaryHeader
[$header] = [];
2071 if ( !is_array( $option ) ) {
2074 $this->mVaryHeader
[$header] = array_unique( array_merge( $this->mVaryHeader
[$header], $option ) );
2078 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2079 * such as Accept-Encoding or Cookie
2083 public function getVaryHeader() {
2084 // If we vary on cookies, let's make sure it's always included here too.
2085 if ( $this->getCacheVaryCookies() ) {
2086 $this->addVaryHeader( 'Cookie' );
2089 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2090 $this->addVaryHeader( $header, $options );
2092 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader
) );
2096 * Add an HTTP Link: header
2098 * @param string $header Header value
2100 public function addLinkHeader( $header ) {
2101 $this->mLinkHeader
[] = $header;
2105 * Return a Link: header. Based on the values of $mLinkHeader.
2109 public function getLinkHeader() {
2110 if ( !$this->mLinkHeader
) {
2114 return 'Link: ' . implode( ',', $this->mLinkHeader
);
2118 * Get a complete Key header
2122 public function getKeyHeader() {
2123 $cvCookies = $this->getCacheVaryCookies();
2125 $cookiesOption = [];
2126 foreach ( $cvCookies as $cookieName ) {
2127 $cookiesOption[] = 'param=' . $cookieName;
2129 $this->addVaryHeader( 'Cookie', $cookiesOption );
2131 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2132 $this->addVaryHeader( $header, $options );
2136 foreach ( $this->mVaryHeader
as $header => $option ) {
2137 $newheader = $header;
2138 if ( is_array( $option ) && count( $option ) > 0 ) {
2139 $newheader .= ';' . implode( ';', $option );
2141 $headers[] = $newheader;
2143 $key = 'Key: ' . implode( ',', $headers );
2149 * T23672: Add Accept-Language to Vary and Key headers
2150 * if there's no 'variant' parameter existed in GET.
2153 * /w/index.php?title=Main_page should always be served; but
2154 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
2156 function addAcceptLanguage() {
2157 $title = $this->getTitle();
2158 if ( !$title instanceof Title
) {
2162 $lang = $title->getPageLanguage();
2163 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2164 $variants = $lang->getVariants();
2166 foreach ( $variants as $variant ) {
2167 if ( $variant === $lang->getCode() ) {
2170 $aloption[] = 'substr=' . $variant;
2172 // IE and some other browsers use BCP 47 standards in
2173 // their Accept-Language header, like "zh-CN" or "zh-Hant".
2174 // We should handle these too.
2175 $variantBCP47 = LanguageCode
::bcp47( $variant );
2176 if ( $variantBCP47 !== $variant ) {
2177 $aloption[] = 'substr=' . $variantBCP47;
2181 $this->addVaryHeader( 'Accept-Language', $aloption );
2186 * Set a flag which will cause an X-Frame-Options header appropriate for
2187 * edit pages to be sent. The header value is controlled by
2188 * $wgEditPageFrameOptions.
2190 * This is the default for special pages. If you display a CSRF-protected
2191 * form on an ordinary view page, then you need to call this function.
2193 * @param bool $enable
2195 public function preventClickjacking( $enable = true ) {
2196 $this->mPreventClickjacking
= $enable;
2200 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2201 * This can be called from pages which do not contain any CSRF-protected
2204 public function allowClickjacking() {
2205 $this->mPreventClickjacking
= false;
2209 * Get the prevent-clickjacking flag
2214 public function getPreventClickjacking() {
2215 return $this->mPreventClickjacking
;
2219 * Get the X-Frame-Options header value (without the name part), or false
2220 * if there isn't one. This is used by Skin to determine whether to enable
2221 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2223 * @return string|false
2225 public function getFrameOptions() {
2226 $config = $this->getConfig();
2227 if ( $config->get( 'BreakFrames' ) ) {
2229 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2230 return $config->get( 'EditPageFrameOptions' );
2236 * Send cache control HTTP headers
2238 public function sendCacheControl() {
2239 $response = $this->getRequest()->response();
2240 $config = $this->getConfig();
2242 $this->addVaryHeader( 'Cookie' );
2243 $this->addAcceptLanguage();
2245 # don't serve compressed data to clients who can't handle it
2246 # maintain different caches for logged-in users and non-logged in ones
2247 $response->header( $this->getVaryHeader() );
2249 if ( $config->get( 'UseKeyHeader' ) ) {
2250 $response->header( $this->getKeyHeader() );
2253 if ( $this->mEnableClientCache
) {
2255 $config->get( 'UseSquid' ) &&
2256 !$response->hasCookies() &&
2257 !SessionManager
::getGlobalSession()->isPersistent() &&
2258 !$this->isPrintable() &&
2259 $this->mCdnMaxage
!= 0 &&
2260 !$this->haveCacheVaryCookies()
2262 if ( $config->get( 'UseESI' ) ) {
2263 # We'll purge the proxy cache explicitly, but require end user agents
2264 # to revalidate against the proxy on each visit.
2265 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2266 wfDebug( __METHOD__
.
2267 ": proxy caching with ESI; {$this->mLastModified} **", 'private' );
2268 # start with a shorter timeout for initial testing
2269 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2271 "Surrogate-Control: max-age={$config->get( 'SquidMaxage' )}" .
2272 "+{$this->mCdnMaxage}, content=\"ESI/1.0\""
2274 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2276 # We'll purge the proxy cache for anons explicitly, but require end user agents
2277 # to revalidate against the proxy on each visit.
2278 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2279 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2280 wfDebug( __METHOD__
.
2281 ": local proxy caching; {$this->mLastModified} **", 'private' );
2282 # start with a shorter timeout for initial testing
2283 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2284 $response->header( "Cache-Control: " .
2285 "s-maxage={$this->mCdnMaxage}, must-revalidate, max-age=0" );
2288 # We do want clients to cache if they can, but they *must* check for updates
2289 # on revisiting the page.
2290 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **", 'private' );
2291 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2292 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2294 if ( $this->mLastModified
) {
2295 $response->header( "Last-Modified: {$this->mLastModified}" );
2298 wfDebug( __METHOD__
. ": no caching **", 'private' );
2300 # In general, the absence of a last modified header should be enough to prevent
2301 # the client from using its cache. We send a few other things just to make sure.
2302 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2303 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2304 $response->header( 'Pragma: no-cache' );
2309 * Finally, all the text has been munged and accumulated into
2310 * the object, let's actually output it:
2312 * @param bool $return Set to true to get the result as a string rather than sending it
2313 * @return string|null
2315 * @throws FatalError
2316 * @throws MWException
2318 public function output( $return = false ) {
2321 if ( $this->mDoNothing
) {
2322 return $return ?
'' : null;
2325 $response = $this->getRequest()->response();
2326 $config = $this->getConfig();
2328 if ( $this->mRedirect
!= '' ) {
2329 # Standards require redirect URLs to be absolute
2330 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2332 $redirect = $this->mRedirect
;
2333 $code = $this->mRedirectCode
;
2335 if ( Hooks
::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2336 if ( $code == '301' ||
$code == '303' ) {
2337 if ( !$config->get( 'DebugRedirects' ) ) {
2338 $response->statusHeader( $code );
2340 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2342 if ( $config->get( 'VaryOnXFP' ) ) {
2343 $this->addVaryHeader( 'X-Forwarded-Proto' );
2345 $this->sendCacheControl();
2347 $response->header( "Content-Type: text/html; charset=utf-8" );
2348 if ( $config->get( 'DebugRedirects' ) ) {
2349 $url = htmlspecialchars( $redirect );
2350 print "<!DOCTYPE html>\n<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2351 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2352 print "</body>\n</html>\n";
2354 $response->header( 'Location: ' . $redirect );
2358 return $return ?
'' : null;
2359 } elseif ( $this->mStatusCode
) {
2360 $response->statusHeader( $this->mStatusCode
);
2363 # Buffer output; final headers may depend on later processing
2366 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2367 $response->header( 'Content-language: ' . $wgContLang->getHtmlCode() );
2369 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2370 // jQuery etc. can work correctly.
2371 $response->header( 'X-UA-Compatible: IE=Edge' );
2373 if ( !$this->mArticleBodyOnly
) {
2374 $sk = $this->getSkin();
2376 if ( $sk->shouldPreloadLogo() ) {
2377 $this->addLogoPreloadLinkHeaders();
2381 $linkHeader = $this->getLinkHeader();
2382 if ( $linkHeader ) {
2383 $response->header( $linkHeader );
2386 // Prevent framing, if requested
2387 $frameOptions = $this->getFrameOptions();
2388 if ( $frameOptions ) {
2389 $response->header( "X-Frame-Options: $frameOptions" );
2392 if ( $this->mArticleBodyOnly
) {
2393 echo $this->mBodytext
;
2395 // Enable safe mode if requested
2396 if ( $this->getRequest()->getBool( 'safemode' ) ) {
2397 $this->disallowUserJs();
2400 $sk = $this->getSkin();
2401 foreach ( $sk->getDefaultModules() as $group ) {
2402 $this->addModules( $group );
2405 MWDebug
::addModules( $this );
2407 // Avoid PHP 7.1 warning of passing $this by reference
2408 $outputPage = $this;
2409 // Hook that allows last minute changes to the output page, e.g.
2410 // adding of CSS or Javascript by extensions.
2411 Hooks
::runWithoutAbort( 'BeforePageDisplay', [ &$outputPage, &$sk ] );
2415 } catch ( Exception
$e ) {
2416 ob_end_clean(); // bug T129657
2422 // This hook allows last minute changes to final overall output by modifying output buffer
2423 Hooks
::runWithoutAbort( 'AfterFinalPageOutput', [ $this ] );
2424 } catch ( Exception
$e ) {
2425 ob_end_clean(); // bug T129657
2429 $this->sendCacheControl();
2432 return ob_get_clean();
2440 * Prepare this object to display an error page; disable caching and
2441 * indexing, clear the current text and redirect, set the page's title
2442 * and optionally an custom HTML title (content of the "<title>" tag).
2444 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2445 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2446 * optional, if not passed the "<title>" attribute will be
2447 * based on $pageTitle
2449 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2450 $this->setPageTitle( $pageTitle );
2451 if ( $htmlTitle !== false ) {
2452 $this->setHTMLTitle( $htmlTitle );
2454 $this->setRobotPolicy( 'noindex,nofollow' );
2455 $this->setArticleRelated( false );
2456 $this->enableClientCache( false );
2457 $this->mRedirect
= '';
2458 $this->clearSubtitle();
2463 * Output a standard error page
2465 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2466 * showErrorPage( 'titlemsg', 'pagetextmsg', [ 'param1', 'param2' ] );
2467 * showErrorPage( 'titlemsg', $messageObject );
2468 * showErrorPage( $titleMessageObject, $messageObject );
2470 * @param string|Message $title Message key (string) for page title, or a Message object
2471 * @param string|Message $msg Message key (string) for page text, or a Message object
2472 * @param array $params Message parameters; ignored if $msg is a Message object
2474 public function showErrorPage( $title, $msg, $params = [] ) {
2475 if ( !$title instanceof Message
) {
2476 $title = $this->msg( $title );
2479 $this->prepareErrorPage( $title );
2481 if ( $msg instanceof Message
) {
2482 if ( $params !== [] ) {
2483 trigger_error( 'Argument ignored: $params. The message parameters argument '
2484 . 'is discarded when the $msg argument is a Message object instead of '
2485 . 'a string.', E_USER_NOTICE
);
2487 $this->addHTML( $msg->parseAsBlock() );
2489 $this->addWikiMsgArray( $msg, $params );
2492 $this->returnToMain();
2496 * Output a standard permission error page
2498 * @param array $errors Error message keys or [key, param...] arrays
2499 * @param string $action Action that was denied or null if unknown
2501 public function showPermissionsErrorPage( array $errors, $action = null ) {
2502 foreach ( $errors as $key => $error ) {
2503 $errors[$key] = (array)$error;
2506 // For some action (read, edit, create and upload), display a "login to do this action"
2507 // error if all of the following conditions are met:
2508 // 1. the user is not logged in
2509 // 2. the only error is insufficient permissions (i.e. no block or something else)
2510 // 3. the error can be avoided simply by logging in
2511 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2512 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2513 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2514 && ( User
::groupHasPermission( 'user', $action )
2515 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2517 $displayReturnto = null;
2519 # Due to T34276, if a user does not have read permissions,
2520 # $this->getTitle() will just give Special:Badtitle, which is
2521 # not especially useful as a returnto parameter. Use the title
2522 # from the request instead, if there was one.
2523 $request = $this->getRequest();
2524 $returnto = Title
::newFromText( $request->getVal( 'title', '' ) );
2525 if ( $action == 'edit' ) {
2526 $msg = 'whitelistedittext';
2527 $displayReturnto = $returnto;
2528 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2529 $msg = 'nocreatetext';
2530 } elseif ( $action == 'upload' ) {
2531 $msg = 'uploadnologintext';
2533 $msg = 'loginreqpagetext';
2534 $displayReturnto = Title
::newMainPage();
2540 $query['returnto'] = $returnto->getPrefixedText();
2542 if ( !$request->wasPosted() ) {
2543 $returntoquery = $request->getValues();
2544 unset( $returntoquery['title'] );
2545 unset( $returntoquery['returnto'] );
2546 unset( $returntoquery['returntoquery'] );
2547 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2550 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
2551 $loginLink = $linkRenderer->makeKnownLink(
2552 SpecialPage
::getTitleFor( 'Userlogin' ),
2553 $this->msg( 'loginreqlink' )->text(),
2558 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2559 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2561 # Don't return to a page the user can't read otherwise
2562 # we'll end up in a pointless loop
2563 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2564 $this->returnToMain( null, $displayReturnto );
2567 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2568 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2573 * Display an error page indicating that a given version of MediaWiki is
2574 * required to use it
2576 * @param mixed $version The version of MediaWiki needed to use the page
2578 public function versionRequired( $version ) {
2579 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2581 $this->addWikiMsg( 'versionrequiredtext', $version );
2582 $this->returnToMain();
2586 * Format a list of error messages
2588 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2589 * @param string $action Action that was denied or null if unknown
2590 * @return string The wikitext error-messages, formatted into a list.
2592 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2593 if ( $action == null ) {
2594 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2596 $action_desc = $this->msg( "action-$action" )->plain();
2598 'permissionserrorstext-withaction',
2601 )->plain() . "\n\n";
2604 if ( count( $errors ) > 1 ) {
2605 $text .= '<ul class="permissions-errors">' . "\n";
2607 foreach ( $errors as $error ) {
2609 $text .= call_user_func_array( [ $this, 'msg' ], $error )->plain();
2614 $text .= "<div class=\"permissions-errors\">\n" .
2615 call_user_func_array( [ $this, 'msg' ], reset( $errors ) )->plain() .
2623 * Show a warning about replica DB lag
2625 * If the lag is higher than $wgSlaveLagCritical seconds,
2626 * then the warning is a bit more obvious. If the lag is
2627 * lower than $wgSlaveLagWarning, then no warning is shown.
2629 * @param int $lag Slave lag
2631 public function showLagWarning( $lag ) {
2632 $config = $this->getConfig();
2633 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2634 $lag = floor( $lag ); // floor to avoid nano seconds to display
2635 $message = $lag < $config->get( 'SlaveLagCritical' )
2638 $wrap = Html
::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2639 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2643 public function showFatalError( $message ) {
2644 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2646 $this->addHTML( $message );
2649 public function showUnexpectedValueError( $name, $val ) {
2650 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2653 public function showFileCopyError( $old, $new ) {
2654 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2657 public function showFileRenameError( $old, $new ) {
2658 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2661 public function showFileDeleteError( $name ) {
2662 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2665 public function showFileNotFoundError( $name ) {
2666 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2670 * Add a "return to" link pointing to a specified title
2672 * @param Title $title Title to link
2673 * @param array $query Query string parameters
2674 * @param string $text Text of the link (input is not escaped)
2675 * @param array $options Options array to pass to Linker
2677 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
2678 $linkRenderer = MediaWikiServices
::getInstance()
2679 ->getLinkRendererFactory()->createFromLegacyOptions( $options );
2680 $link = $this->msg( 'returnto' )->rawParams(
2681 $linkRenderer->makeLink( $title, $text, [], $query ) )->escaped();
2682 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2686 * Add a "return to" link pointing to a specified title,
2687 * or the title indicated in the request, or else the main page
2689 * @param mixed $unused
2690 * @param Title|string $returnto Title or String to return to
2691 * @param string $returntoquery Query string for the return to link
2693 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2694 if ( $returnto == null ) {
2695 $returnto = $this->getRequest()->getText( 'returnto' );
2698 if ( $returntoquery == null ) {
2699 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2702 if ( $returnto === '' ) {
2703 $returnto = Title
::newMainPage();
2706 if ( is_object( $returnto ) ) {
2707 $titleObj = $returnto;
2709 $titleObj = Title
::newFromText( $returnto );
2711 // We don't want people to return to external interwiki. That
2712 // might potentially be used as part of a phishing scheme
2713 if ( !is_object( $titleObj ) ||
$titleObj->isExternal() ) {
2714 $titleObj = Title
::newMainPage();
2717 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2720 private function getRlClientContext() {
2721 if ( !$this->rlClientContext
) {
2722 $query = ResourceLoader
::makeLoaderQuery(
2723 [], // modules; not relevant
2724 $this->getLanguage()->getCode(),
2725 $this->getSkin()->getSkinName(),
2726 $this->getUser()->isLoggedIn() ?
$this->getUser()->getName() : null,
2727 null, // version; not relevant
2728 ResourceLoader
::inDebugMode(),
2729 null, // only; not relevant
2730 $this->isPrintable(),
2731 $this->getRequest()->getBool( 'handheld' )
2733 $this->rlClientContext
= new ResourceLoaderContext(
2734 $this->getResourceLoader(),
2735 new FauxRequest( $query )
2738 return $this->rlClientContext
;
2742 * Call this to freeze the module queue and JS config and create a formatter.
2744 * Depending on the Skin, this may get lazy-initialised in either headElement() or
2745 * getBottomScripts(). See SkinTemplate::prepareQuickTemplate(). Calling this too early may
2746 * cause unexpected side-effects since disallowUserJs() may be called at any time to change
2747 * the module filters retroactively. Skins and extension hooks may also add modules until very
2748 * late in the request lifecycle.
2750 * @return ResourceLoaderClientHtml
2752 public function getRlClient() {
2753 if ( !$this->rlClient
) {
2754 $context = $this->getRlClientContext();
2755 $rl = $this->getResourceLoader();
2756 $this->addModules( [
2760 $this->addModuleStyles( [
2765 $this->getSkin()->setupSkinUserCss( $this );
2767 // Prepare exempt modules for buildExemptModules()
2768 $exemptGroups = [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ];
2770 $moduleStyles = $this->getModuleStyles( /*filter*/ true );
2772 // Preload getTitleInfo for isKnownEmpty calls below and in ResourceLoaderClientHtml
2773 // Separate user-specific batch for improved cache-hit ratio.
2774 $userBatch = [ 'user.styles', 'user' ];
2775 $siteBatch = array_diff( $moduleStyles, $userBatch );
2776 $dbr = wfGetDB( DB_REPLICA
);
2777 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $siteBatch );
2778 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $userBatch );
2780 // Filter out modules handled by buildExemptModules()
2781 $moduleStyles = array_filter( $moduleStyles,
2782 function ( $name ) use ( $rl, $context, &$exemptGroups, &$exemptStates ) {
2783 $module = $rl->getModule( $name );
2785 if ( $name === 'user.styles' && $this->isUserCssPreview() ) {
2786 $exemptStates[$name] = 'ready';
2787 // Special case in buildExemptModules()
2790 $group = $module->getGroup();
2791 if ( isset( $exemptGroups[$group] ) ) {
2792 $exemptStates[$name] = 'ready';
2793 if ( !$module->isKnownEmpty( $context ) ) {
2794 // E.g. Don't output empty <styles>
2795 $exemptGroups[$group][] = $name;
2803 $this->rlExemptStyleModules
= $exemptGroups;
2805 $isUserModuleFiltered = !$this->filterModules( [ 'user' ] );
2806 // If this page filters out 'user', makeResourceLoaderLink will drop it.
2807 // Avoid indefinite "loading" state or untrue "ready" state (T145368).
2808 if ( !$isUserModuleFiltered ) {
2809 // Manually handled by getBottomScripts()
2810 $userModule = $rl->getModule( 'user' );
2811 $userState = $userModule->isKnownEmpty( $context ) && !$this->isUserJsPreview()
2814 $this->rlUserModuleState
= $exemptStates['user'] = $userState;
2817 $rlClient = new ResourceLoaderClientHtml( $context, $this->getTarget() );
2818 $rlClient->setConfig( $this->getJSVars() );
2819 $rlClient->setModules( $this->getModules( /*filter*/ true ) );
2820 $rlClient->setModuleStyles( $moduleStyles );
2821 $rlClient->setModuleScripts( $this->getModuleScripts( /*filter*/ true ) );
2822 $rlClient->setExemptStates( $exemptStates );
2823 $this->rlClient
= $rlClient;
2825 return $this->rlClient
;
2829 * @param Skin $sk The given Skin
2830 * @param bool $includeStyle Unused
2831 * @return string The doctype, opening "<html>", and head element.
2833 public function headElement( Skin
$sk, $includeStyle = true ) {
2836 $userdir = $this->getLanguage()->getDir();
2837 $sitedir = $wgContLang->getDir();
2840 $pieces[] = Html
::htmlHeader( Sanitizer
::mergeAttributes(
2841 $this->getRlClient()->getDocumentAttributes(),
2842 $sk->getHtmlElementAttributes()
2844 $pieces[] = Html
::openElement( 'head' );
2846 if ( $this->getHTMLTitle() == '' ) {
2847 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2850 if ( !Html
::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2851 // Add <meta charset="UTF-8">
2852 // This should be before <title> since it defines the charset used by
2853 // text including the text inside <title>.
2854 // The spec recommends defining XHTML5's charset using the XML declaration
2856 // Our XML declaration is output by Html::htmlHeader.
2857 // https://html.spec.whatwg.org/multipage/semantics.html#attr-meta-http-equiv-content-type
2858 // https://html.spec.whatwg.org/multipage/semantics.html#charset
2859 $pieces[] = Html
::element( 'meta', [ 'charset' => 'UTF-8' ] );
2862 $pieces[] = Html
::element( 'title', null, $this->getHTMLTitle() );
2863 $pieces[] = $this->getRlClient()->getHeadHtml();
2864 $pieces[] = $this->buildExemptModules();
2865 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
2866 $pieces = array_merge( $pieces, array_values( $this->mHeadItems
) );
2868 // Use an IE conditional comment to serve the script only to old IE
2869 $pieces[] = '<!--[if lt IE 9]>' .
2870 ResourceLoaderClientHtml
::makeLoad(
2871 ResourceLoaderContext
::newDummyContext(),
2873 ResourceLoaderModule
::TYPE_SCRIPTS
,
2878 $pieces[] = Html
::closeElement( 'head' );
2880 $bodyClasses = $this->mAdditionalBodyClasses
;
2881 $bodyClasses[] = 'mediawiki';
2883 # Classes for LTR/RTL directionality support
2884 $bodyClasses[] = $userdir;
2885 $bodyClasses[] = "sitedir-$sitedir";
2887 $underline = $this->getUser()->getOption( 'underline' );
2888 if ( $underline < 2 ) {
2889 // The following classes can be used here:
2890 // * mw-underline-always
2891 // * mw-underline-never
2892 $bodyClasses[] = 'mw-underline-' . ( $underline ?
'always' : 'never' );
2895 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2896 # A <body> class is probably not the best way to do this . . .
2897 $bodyClasses[] = 'capitalize-all-nouns';
2900 // Parser feature migration class
2901 // The idea is that this will eventually be removed, after the wikitext
2902 // which requires it is cleaned up.
2903 $bodyClasses[] = 'mw-hide-empty-elt';
2905 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2906 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2908 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2911 // While the implode() is not strictly needed, it's used for backwards compatibility
2912 // (this used to be built as a string and hooks likely still expect that).
2913 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2915 // Allow skins and extensions to add body attributes they need
2916 $sk->addToBodyAttributes( $this, $bodyAttrs );
2917 Hooks
::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
2919 $pieces[] = Html
::openElement( 'body', $bodyAttrs );
2921 return self
::combineWrappedStrings( $pieces );
2925 * Get a ResourceLoader object associated with this OutputPage
2927 * @return ResourceLoader
2929 public function getResourceLoader() {
2930 if ( is_null( $this->mResourceLoader
) ) {
2931 $this->mResourceLoader
= new ResourceLoader(
2933 LoggerFactory
::getInstance( 'resourceloader' )
2936 return $this->mResourceLoader
;
2940 * Explicily load or embed modules on a page.
2942 * @param array|string $modules One or more module names
2943 * @param string $only ResourceLoaderModule TYPE_ class constant
2944 * @param array $extraQuery [optional] Array with extra query parameters for the request
2945 * @return string|WrappedStringList HTML
2947 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
2948 // Apply 'target' and 'origin' filters
2949 $modules = $this->filterModules( (array)$modules, null, $only );
2951 return ResourceLoaderClientHtml
::makeLoad(
2952 $this->getRlClientContext(),
2960 * Combine WrappedString chunks and filter out empty ones
2962 * @param array $chunks
2963 * @return string|WrappedStringList HTML
2965 protected static function combineWrappedStrings( array $chunks ) {
2966 // Filter out empty values
2967 $chunks = array_filter( $chunks, 'strlen' );
2968 return WrappedString
::join( "\n", $chunks );
2971 private function isUserJsPreview() {
2972 return $this->getConfig()->get( 'AllowUserJs' )
2973 && $this->getTitle()
2974 && $this->getTitle()->isJsSubpage()
2975 && $this->userCanPreview();
2978 protected function isUserCssPreview() {
2979 return $this->getConfig()->get( 'AllowUserCss' )
2980 && $this->getTitle()
2981 && $this->getTitle()->isCssSubpage()
2982 && $this->userCanPreview();
2986 * JS stuff to put at the bottom of the `<body>`. These are modules with position 'bottom',
2987 * legacy scripts ($this->mScripts), and user JS.
2989 * @return string|WrappedStringList HTML
2991 public function getBottomScripts() {
2993 $chunks[] = $this->getRlClient()->getBodyHtml();
2995 // Legacy non-ResourceLoader scripts
2996 $chunks[] = $this->mScripts
;
2998 // Exempt 'user' module
2999 // - May need excludepages for live preview. (T28283)
3000 // - Must use TYPE_COMBINED so its response is handled by mw.loader.implement() which
3001 // ensures execution is scheduled after the "site" module.
3002 // - Don't load if module state is already resolved as "ready".
3003 if ( $this->rlUserModuleState
=== 'loading' ) {
3004 if ( $this->isUserJsPreview() ) {
3005 $chunks[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_COMBINED
,
3006 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
3008 $chunks[] = ResourceLoader
::makeInlineScript(
3009 Xml
::encodeJsCall( 'mw.loader.using', [
3013 . Xml
::encodeJsCall( '$.globalEval', [
3014 $this->getRequest()->getText( 'wpTextbox1' )
3020 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
3021 // asynchronously and may arrive *after* the inline script here. So the previewed code
3022 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js.
3023 // Similarly, when previewing ./common.js and the user module does arrive first,
3024 // it will arrive without common.js and the inline script runs after.
3025 // Thus running common after the excluded subpage.
3028 $chunks[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_COMBINED
);
3032 if ( $this->limitReportJSData
) {
3033 $chunks[] = ResourceLoader
::makeInlineScript(
3034 ResourceLoader
::makeConfigSetScript(
3035 [ 'wgPageParseReport' => $this->limitReportJSData
]
3040 return self
::combineWrappedStrings( $chunks );
3044 * Get the javascript config vars to include on this page
3046 * @return array Array of javascript config vars
3049 public function getJsConfigVars() {
3050 return $this->mJsConfigVars
;
3054 * Add one or more variables to be set in mw.config in JavaScript
3056 * @param string|array $keys Key or array of key/value pairs
3057 * @param mixed $value [optional] Value of the configuration variable
3059 public function addJsConfigVars( $keys, $value = null ) {
3060 if ( is_array( $keys ) ) {
3061 foreach ( $keys as $key => $value ) {
3062 $this->mJsConfigVars
[$key] = $value;
3067 $this->mJsConfigVars
[$keys] = $value;
3071 * Get an array containing the variables to be set in mw.config in JavaScript.
3073 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3074 * - in other words, page-independent/site-wide variables (without state).
3075 * You will only be adding bloat to the html page and causing page caches to
3076 * have to be purged on configuration changes.
3079 public function getJSVars() {
3084 $canonicalSpecialPageName = false; # T23115
3086 $title = $this->getTitle();
3087 $ns = $title->getNamespace();
3088 $canonicalNamespace = MWNamespace
::exists( $ns )
3089 ? MWNamespace
::getCanonicalName( $ns )
3090 : $title->getNsText();
3092 $sk = $this->getSkin();
3093 // Get the relevant title so that AJAX features can use the correct page name
3094 // when making API requests from certain special pages (T36972).
3095 $relevantTitle = $sk->getRelevantTitle();
3096 $relevantUser = $sk->getRelevantUser();
3098 if ( $ns == NS_SPECIAL
) {
3099 list( $canonicalSpecialPageName, /*...*/ ) =
3100 SpecialPageFactory
::resolveAlias( $title->getDBkey() );
3101 } elseif ( $this->canUseWikiPage() ) {
3102 $wikiPage = $this->getWikiPage();
3103 $curRevisionId = $wikiPage->getLatest();
3104 $articleId = $wikiPage->getId();
3107 $lang = $title->getPageViewLanguage();
3109 // Pre-process information
3110 $separatorTransTable = $lang->separatorTransformTable();
3111 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : [];
3112 $compactSeparatorTransTable = [
3113 implode( "\t", array_keys( $separatorTransTable ) ),
3114 implode( "\t", $separatorTransTable ),
3116 $digitTransTable = $lang->digitTransformTable();
3117 $digitTransTable = $digitTransTable ?
$digitTransTable : [];
3118 $compactDigitTransTable = [
3119 implode( "\t", array_keys( $digitTransTable ) ),
3120 implode( "\t", $digitTransTable ),
3123 $user = $this->getUser();
3126 'wgCanonicalNamespace' => $canonicalNamespace,
3127 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3128 'wgNamespaceNumber' => $title->getNamespace(),
3129 'wgPageName' => $title->getPrefixedDBkey(),
3130 'wgTitle' => $title->getText(),
3131 'wgCurRevisionId' => $curRevisionId,
3132 'wgRevisionId' => (int)$this->getRevisionId(),
3133 'wgArticleId' => $articleId,
3134 'wgIsArticle' => $this->isArticle(),
3135 'wgIsRedirect' => $title->isRedirect(),
3136 'wgAction' => Action
::getActionName( $this->getContext() ),
3137 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3138 'wgUserGroups' => $user->getEffectiveGroups(),
3139 'wgCategories' => $this->getCategories(),
3140 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3141 'wgPageContentLanguage' => $lang->getCode(),
3142 'wgPageContentModel' => $title->getContentModel(),
3143 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3144 'wgDigitTransformTable' => $compactDigitTransTable,
3145 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3146 'wgMonthNames' => $lang->getMonthNamesArray(),
3147 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3148 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3149 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3150 'wgRequestId' => WebRequest
::getRequestId(),
3153 if ( $user->isLoggedIn() ) {
3154 $vars['wgUserId'] = $user->getId();
3155 $vars['wgUserEditCount'] = $user->getEditCount();
3156 $userReg = $user->getRegistration();
3157 $vars['wgUserRegistration'] = $userReg ?
wfTimestamp( TS_UNIX
, $userReg ) * 1000 : null;
3158 // Get the revision ID of the oldest new message on the user's talk
3159 // page. This can be used for constructing new message alerts on
3161 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3164 if ( $wgContLang->hasVariants() ) {
3165 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3167 // Same test as SkinTemplate
3168 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3169 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3171 $vars['wgRelevantPageIsProbablyEditable'] = $relevantTitle
3172 && $relevantTitle->quickUserCan( 'edit', $user )
3173 && ( $relevantTitle->exists() ||
$relevantTitle->quickUserCan( 'create', $user ) );
3175 foreach ( $title->getRestrictionTypes() as $type ) {
3176 // Following keys are set in $vars:
3177 // wgRestrictionCreate, wgRestrictionEdit, wgRestrictionMove, wgRestrictionUpload
3178 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3181 if ( $title->isMainPage() ) {
3182 $vars['wgIsMainPage'] = true;
3185 if ( $this->mRedirectedFrom
) {
3186 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3189 if ( $relevantUser ) {
3190 $vars['wgRelevantUserName'] = $relevantUser->getName();
3193 // Allow extensions to add their custom variables to the mw.config map.
3194 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3195 // page-dependant but site-wide (without state).
3196 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3197 Hooks
::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3199 // Merge in variables from addJsConfigVars last
3200 return array_merge( $vars, $this->getJsConfigVars() );
3204 * To make it harder for someone to slip a user a fake
3205 * user-JavaScript or user-CSS preview, a random token
3206 * is associated with the login session. If it's not
3207 * passed back with the preview request, we won't render
3212 public function userCanPreview() {
3213 $request = $this->getRequest();
3215 $request->getVal( 'action' ) !== 'submit' ||
3216 !$request->getCheck( 'wpPreview' ) ||
3217 !$request->wasPosted()
3222 $user = $this->getUser();
3224 if ( !$user->isLoggedIn() ) {
3225 // Anons have predictable edit tokens
3228 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3232 $title = $this->getTitle();
3233 if ( !$title->isJsSubpage() && !$title->isCssSubpage() ) {
3236 if ( !$title->isSubpageOf( $user->getUserPage() ) ) {
3237 // Don't execute another user's CSS or JS on preview (T85855)
3241 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3242 if ( count( $errors ) !== 0 ) {
3250 * @return array Array in format "link name or number => 'link html'".
3252 public function getHeadLinksArray() {
3256 $config = $this->getConfig();
3258 $canonicalUrl = $this->mCanonicalUrl
;
3260 $tags['meta-generator'] = Html
::element( 'meta', [
3261 'name' => 'generator',
3262 'content' => "MediaWiki $wgVersion",
3265 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3266 // Per https://w3c.github.io/webappsec-referrer-policy/#unknown-policy-values
3267 // fallbacks should come before the primary value so we need to reverse the array.
3268 foreach ( array_reverse( (array)$config->get( 'ReferrerPolicy' ) ) as $i => $policy ) {
3269 $tags["meta-referrer-$i"] = Html
::element( 'meta', [
3270 'name' => 'referrer',
3271 'content' => $policy,
3276 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3277 if ( $p !== 'index,follow' ) {
3278 // http://www.robotstxt.org/wc/meta-user.html
3279 // Only show if it's different from the default robots policy
3280 $tags['meta-robots'] = Html
::element( 'meta', [
3286 foreach ( $this->mMetatags
as $tag ) {
3287 if ( strncasecmp( $tag[0], 'http:', 5 ) === 0 ) {
3289 $tag[0] = substr( $tag[0], 5 );
3290 } elseif ( strncasecmp( $tag[0], 'og:', 3 ) === 0 ) {
3295 $tagName = "meta-{$tag[0]}";
3296 if ( isset( $tags[$tagName] ) ) {
3297 $tagName .= $tag[1];
3299 $tags[$tagName] = Html
::element( 'meta',
3302 'content' => $tag[1]
3307 foreach ( $this->mLinktags
as $tag ) {
3308 $tags[] = Html
::element( 'link', $tag );
3311 # Universal edit button
3312 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3313 $user = $this->getUser();
3314 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3315 && ( $this->getTitle()->exists() ||
3316 $this->getTitle()->quickUserCan( 'create', $user ) )
3318 // Original UniversalEditButton
3319 $msg = $this->msg( 'edit' )->text();
3320 $tags['universal-edit-button'] = Html
::element( 'link', [
3321 'rel' => 'alternate',
3322 'type' => 'application/x-wiki',
3324 'href' => $this->getTitle()->getEditURL(),
3326 // Alternate edit link
3327 $tags['alternative-edit'] = Html
::element( 'link', [
3330 'href' => $this->getTitle()->getEditURL(),
3335 # Generally the order of the favicon and apple-touch-icon links
3336 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3337 # uses whichever one appears later in the HTML source. Make sure
3338 # apple-touch-icon is specified first to avoid this.
3339 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3340 $tags['apple-touch-icon'] = Html
::element( 'link', [
3341 'rel' => 'apple-touch-icon',
3342 'href' => $config->get( 'AppleTouchIcon' )
3346 if ( $config->get( 'Favicon' ) !== false ) {
3347 $tags['favicon'] = Html
::element( 'link', [
3348 'rel' => 'shortcut icon',
3349 'href' => $config->get( 'Favicon' )
3353 # OpenSearch description link
3354 $tags['opensearch'] = Html
::element( 'link', [
3356 'type' => 'application/opensearchdescription+xml',
3357 'href' => wfScript( 'opensearch_desc' ),
3358 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3361 if ( $config->get( 'EnableAPI' ) ) {
3362 # Real Simple Discovery link, provides auto-discovery information
3363 # for the MediaWiki API (and potentially additional custom API
3364 # support such as WordPress or Twitter-compatible APIs for a
3365 # blogging extension, etc)
3366 $tags['rsd'] = Html
::element( 'link', [
3368 'type' => 'application/rsd+xml',
3369 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3370 // Whether RSD accepts relative or protocol-relative URLs is completely
3371 // undocumented, though.
3372 'href' => wfExpandUrl( wfAppendQuery(
3374 [ 'action' => 'rsd' ] ),
3381 if ( !$config->get( 'DisableLangConversion' ) ) {
3382 $lang = $this->getTitle()->getPageLanguage();
3383 if ( $lang->hasVariants() ) {
3384 $variants = $lang->getVariants();
3385 foreach ( $variants as $variant ) {
3386 $tags["variant-$variant"] = Html
::element( 'link', [
3387 'rel' => 'alternate',
3388 'hreflang' => LanguageCode
::bcp47( $variant ),
3389 'href' => $this->getTitle()->getLocalURL(
3390 [ 'variant' => $variant ] )
3394 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3395 $tags["variant-x-default"] = Html
::element( 'link', [
3396 'rel' => 'alternate',
3397 'hreflang' => 'x-default',
3398 'href' => $this->getTitle()->getLocalURL() ] );
3403 if ( $this->copyrightUrl
!== null ) {
3404 $copyright = $this->copyrightUrl
;
3407 if ( $config->get( 'RightsPage' ) ) {
3408 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3411 $copyright = $copy->getLocalURL();
3415 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3416 $copyright = $config->get( 'RightsUrl' );
3421 $tags['copyright'] = Html
::element( 'link', [
3423 'href' => $copyright ]
3428 if ( $config->get( 'Feed' ) ) {
3431 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3432 # Use the page name for the title. In principle, this could
3433 # lead to issues with having the same name for different feeds
3434 # corresponding to the same page, but we can't avoid that at
3437 $feedLinks[] = $this->feedLink(
3440 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3442 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3447 # Recent changes feed should appear on every page (except recentchanges,
3448 # that would be redundant). Put it after the per-page feed to avoid
3449 # changing existing behavior. It's still available, probably via a
3450 # menu in your browser. Some sites might have a different feed they'd
3451 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3452 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3453 # If so, use it instead.
3454 $sitename = $config->get( 'Sitename' );
3455 if ( $config->get( 'OverrideSiteFeed' ) ) {
3456 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3457 // Note, this->feedLink escapes the url.
3458 $feedLinks[] = $this->feedLink(
3461 $this->msg( "site-{$type}-feed", $sitename )->text()
3464 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3465 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3466 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3467 $feedLinks[] = $this->feedLink(
3469 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3470 # For grep: 'site-rss-feed', 'site-atom-feed'
3471 $this->msg( "site-{$format}-feed", $sitename )->text()
3476 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3477 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3478 # use OutputPage::addFeedLink() instead.
3479 Hooks
::run( 'AfterBuildFeedLinks', [ &$feedLinks ] );
3481 $tags +
= $feedLinks;
3485 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3486 if ( $canonicalUrl !== false ) {
3487 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3489 if ( $this->isArticleRelated() ) {
3490 // This affects all requests where "setArticleRelated" is true. This is
3491 // typically all requests that show content (query title, curid, oldid, diff),
3492 // and all wikipage actions (edit, delete, purge, info, history etc.).
3493 // It does not apply to File pages and Special pages.
3494 // 'history' and 'info' actions address page metadata rather than the page
3495 // content itself, so they may not be canonicalized to the view page url.
3496 // TODO: this ought to be better encapsulated in the Action class.
3497 $action = Action
::getActionName( $this->getContext() );
3498 if ( in_array( $action, [ 'history', 'info' ] ) ) {
3499 $query = "action={$action}";
3503 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3505 $reqUrl = $this->getRequest()->getRequestURL();
3506 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3510 if ( $canonicalUrl !== false ) {
3511 $tags[] = Html
::element( 'link', [
3512 'rel' => 'canonical',
3513 'href' => $canonicalUrl
3521 * Generate a "<link rel/>" for a feed.
3523 * @param string $type Feed type
3524 * @param string $url URL to the feed
3525 * @param string $text Value of the "title" attribute
3526 * @return string HTML fragment
3528 private function feedLink( $type, $url, $text ) {
3529 return Html
::element( 'link', [
3530 'rel' => 'alternate',
3531 'type' => "application/$type+xml",
3538 * Add a local or specified stylesheet, with the given media options.
3539 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3541 * @param string $style URL to the file
3542 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3543 * @param string $condition For IE conditional comments, specifying an IE version
3544 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3546 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3549 $options['media'] = $media;
3552 $options['condition'] = $condition;
3555 $options['dir'] = $dir;
3557 $this->styles
[$style] = $options;
3561 * Adds inline CSS styles
3562 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3564 * @param mixed $style_css Inline CSS
3565 * @param string $flip Set to 'flip' to flip the CSS if needed
3567 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3568 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3569 # If wanted, and the interface is right-to-left, flip the CSS
3570 $style_css = CSSJanus
::transform( $style_css, true, false );
3572 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3576 * Build exempt modules and legacy non-ResourceLoader styles.
3578 * @return string|WrappedStringList HTML
3580 protected function buildExemptModules() {
3584 // Things that go after the ResourceLoaderDynamicStyles marker
3587 // Exempt 'user' styles module (may need 'excludepages' for live preview)
3588 if ( $this->isUserCssPreview() ) {
3589 $append[] = $this->makeResourceLoaderLink(
3591 ResourceLoaderModule
::TYPE_STYLES
,
3592 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
3595 // Load the previewed CSS. Janus it if needed.
3596 // User-supplied CSS is assumed to in the wiki's content language.
3597 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3598 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3599 $previewedCSS = CSSJanus
::transform( $previewedCSS, true, false );
3601 $append[] = Html
::inlineStyle( $previewedCSS );
3604 // We want site, private and user styles to override dynamically added styles from
3605 // general modules, but we want dynamically added styles to override statically added
3606 // style modules. So the order has to be:
3607 // - page style modules (formatted by ResourceLoaderClientHtml::getHeadHtml())
3608 // - dynamically loaded styles (added by mw.loader before ResourceLoaderDynamicStyles)
3609 // - ResourceLoaderDynamicStyles marker
3610 // - site/private/user styles
3612 // Add legacy styles added through addStyle()/addInlineStyle() here
3613 $chunks[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3615 $chunks[] = Html
::element(
3617 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
3620 $separateReq = [ 'site.styles', 'user.styles' ];
3621 foreach ( $this->rlExemptStyleModules
as $group => $moduleNames ) {
3622 // Combinable modules
3623 $chunks[] = $this->makeResourceLoaderLink(
3624 array_diff( $moduleNames, $separateReq ),
3625 ResourceLoaderModule
::TYPE_STYLES
3628 foreach ( array_intersect( $moduleNames, $separateReq ) as $name ) {
3629 // These require their own dedicated request in order to support "@import"
3630 // syntax, which is incompatible with concatenation. (T147667, T37562)
3631 $chunks[] = $this->makeResourceLoaderLink( $name,
3632 ResourceLoaderModule
::TYPE_STYLES
3637 return self
::combineWrappedStrings( array_merge( $chunks, $append ) );
3643 public function buildCssLinksArray() {
3646 // Add any extension CSS
3647 foreach ( $this->mExtStyles
as $url ) {
3648 $this->addStyle( $url );
3650 $this->mExtStyles
= [];
3652 foreach ( $this->styles
as $file => $options ) {
3653 $link = $this->styleLink( $file, $options );
3655 $links[$file] = $link;
3662 * Generate \<link\> tags for stylesheets
3664 * @param string $style URL to the file
3665 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3666 * @return string HTML fragment
3668 protected function styleLink( $style, array $options ) {
3669 if ( isset( $options['dir'] ) ) {
3670 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3675 if ( isset( $options['media'] ) ) {
3676 $media = self
::transformCssMedia( $options['media'] );
3677 if ( is_null( $media ) ) {
3684 if ( substr( $style, 0, 1 ) == '/' ||
3685 substr( $style, 0, 5 ) == 'http:' ||
3686 substr( $style, 0, 6 ) == 'https:' ) {
3689 $config = $this->getConfig();
3690 $url = $config->get( 'StylePath' ) . '/' . $style . '?' .
3691 $config->get( 'StyleVersion' );
3694 $link = Html
::linkedStyle( $url, $media );
3696 if ( isset( $options['condition'] ) ) {
3697 $condition = htmlspecialchars( $options['condition'] );
3698 $link = "<!--[if $condition]>$link<![endif]-->";
3704 * Transform path to web-accessible static resource.
3706 * This is used to add a validation hash as query string.
3707 * This aids various behaviors:
3709 * - Put long Cache-Control max-age headers on responses for improved
3710 * cache performance.
3711 * - Get the correct version of a file as expected by the current page.
3712 * - Instantly get the updated version of a file after deployment.
3714 * Avoid using this for urls included in HTML as otherwise clients may get different
3715 * versions of a resource when navigating the site depending on when the page was cached.
3716 * If changes to the url propagate, this is not a problem (e.g. if the url is in
3717 * an external stylesheet).
3720 * @param Config $config
3721 * @param string $path Path-absolute URL to file (from document root, must start with "/")
3722 * @return string URL
3724 public static function transformResourcePath( Config
$config, $path ) {
3728 $remotePathPrefix = $config->get( 'ResourceBasePath' );
3729 if ( $remotePathPrefix === '' ) {
3730 // The configured base path is required to be empty string for
3731 // wikis in the domain root
3734 $remotePath = $remotePathPrefix;
3736 if ( strpos( $path, $remotePath ) !== 0 ||
substr( $path, 0, 2 ) === '//' ) {
3737 // - Path is outside wgResourceBasePath, ignore.
3738 // - Path is protocol-relative. Fixes T155310. Not supported by RelPath lib.
3741 // For files in resources, extensions/ or skins/, ResourceBasePath is preferred here.
3742 // For other misc files in $IP, we'll fallback to that as well. There is, however, a fourth
3743 // supported dir/path pair in the configuration (wgUploadDirectory, wgUploadPath)
3744 // which is not expected to be in wgResourceBasePath on CDNs. (T155146)
3745 $uploadPath = $config->get( 'UploadPath' );
3746 if ( strpos( $path, $uploadPath ) === 0 ) {
3747 $localDir = $config->get( 'UploadDirectory' );
3748 $remotePathPrefix = $remotePath = $uploadPath;
3751 $path = RelPath
::getRelativePath( $path, $remotePath );
3752 return self
::transformFilePath( $remotePathPrefix, $localDir, $path );
3756 * Utility method for transformResourceFilePath().
3758 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
3761 * @param string $remotePathPrefix URL path prefix that points to $localPath
3762 * @param string $localPath File directory exposed at $remotePath
3763 * @param string $file Path to target file relative to $localPath
3764 * @return string URL
3766 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
3767 $hash = md5_file( "$localPath/$file" );
3768 if ( $hash === false ) {
3769 wfLogWarning( __METHOD__
. ": Failed to hash $localPath/$file" );
3772 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
3776 * Transform "media" attribute based on request parameters
3778 * @param string $media Current value of the "media" attribute
3779 * @return string Modified value of the "media" attribute, or null to skip
3782 public static function transformCssMedia( $media ) {
3785 // https://www.w3.org/TR/css3-mediaqueries/#syntax
3786 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3788 // Switch in on-screen display for media testing
3790 'printable' => 'print',
3791 'handheld' => 'handheld',
3793 foreach ( $switches as $switch => $targetMedia ) {
3794 if ( $wgRequest->getBool( $switch ) ) {
3795 if ( $media == $targetMedia ) {
3797 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3798 /* This regex will not attempt to understand a comma-separated media_query_list
3800 * Example supported values for $media:
3801 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3802 * Example NOT supported value for $media:
3803 * '3d-glasses, screen, print and resolution > 90dpi'
3805 * If it's a print request, we never want any kind of screen stylesheets
3806 * If it's a handheld request (currently the only other choice with a switch),
3807 * we don't want simple 'screen' but we might want screen queries that
3808 * have a max-width or something, so we'll pass all others on and let the
3809 * client do the query.
3811 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3822 * Add a wikitext-formatted message to the output.
3823 * This is equivalent to:
3825 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3827 public function addWikiMsg( /*...*/ ) {
3828 $args = func_get_args();
3829 $name = array_shift( $args );
3830 $this->addWikiMsgArray( $name, $args );
3834 * Add a wikitext-formatted message to the output.
3835 * Like addWikiMsg() except the parameters are taken as an array
3836 * instead of a variable argument list.
3838 * @param string $name
3839 * @param array $args
3841 public function addWikiMsgArray( $name, $args ) {
3842 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3846 * This function takes a number of message/argument specifications, wraps them in
3847 * some overall structure, and then parses the result and adds it to the output.
3849 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3850 * and so on. The subsequent arguments may be either
3851 * 1) strings, in which case they are message names, or
3852 * 2) arrays, in which case, within each array, the first element is the message
3853 * name, and subsequent elements are the parameters to that message.
3855 * Don't use this for messages that are not in the user's interface language.
3859 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3863 * $wgOut->addWikiText( "<div class='error'>\n"
3864 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3866 * The newline after the opening div is needed in some wikitext. See T21226.
3868 * @param string $wrap
3870 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3871 $msgSpecs = func_get_args();
3872 array_shift( $msgSpecs );
3873 $msgSpecs = array_values( $msgSpecs );
3875 foreach ( $msgSpecs as $n => $spec ) {
3876 if ( is_array( $spec ) ) {
3878 $name = array_shift( $args );
3879 if ( isset( $args['options'] ) ) {
3880 unset( $args['options'] );
3882 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3890 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3892 $this->addWikiText( $s );
3896 * Whether the output has a table of contents
3900 public function isTOCEnabled() {
3901 return $this->mEnableTOC
;
3905 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3908 * @deprecated since 1.31, use $poOptions to addParserOutput() instead.
3910 public function enableSectionEditLinks( $flag = true ) {
3911 $this->mEnableSectionEditLinks
= $flag;
3917 * @deprecated since 1.31, use $poOptions to addParserOutput() instead.
3919 public function sectionEditLinksEnabled() {
3920 return $this->mEnableSectionEditLinks
;
3924 * Helper function to setup the PHP implementation of OOUI to use in this request.
3927 * @param String $skinName The Skin name to determine the correct OOUI theme
3928 * @param String $dir Language direction
3930 public static function setupOOUI( $skinName = 'default', $dir = 'ltr' ) {
3931 $themes = ResourceLoaderOOUIModule
::getSkinThemeMap();
3932 $theme = isset( $themes[$skinName] ) ?
$themes[$skinName] : $themes['default'];
3933 // For example, 'OOUI\WikimediaUITheme'.
3934 $themeClass = "OOUI\\{$theme}Theme";
3935 OOUI\Theme
::setSingleton( new $themeClass() );
3936 OOUI\Element
::setDefaultDir( $dir );
3940 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
3941 * MediaWiki and this OutputPage instance.
3945 public function enableOOUI() {
3947 strtolower( $this->getSkin()->getSkinName() ),
3948 $this->getLanguage()->getDir()
3950 $this->addModuleStyles( [
3951 'oojs-ui-core.styles',
3952 'oojs-ui.styles.indicators',
3953 'oojs-ui.styles.textures',
3954 'mediawiki.widgets.styles',
3955 'oojs-ui.styles.icons-content',
3956 'oojs-ui.styles.icons-alerts',
3957 'oojs-ui.styles.icons-interactions',
3962 * Add Link headers for preloading the wiki's logo.
3966 protected function addLogoPreloadLinkHeaders() {
3967 $logo = ResourceLoaderSkinModule
::getLogo( $this->getConfig() );
3973 if ( !is_array( $logo ) ) {
3974 // No media queries required if we only have one variant
3975 $this->addLinkHeader( '<' . $logo . '>;rel=preload;as=image' );
3979 if ( isset( $logo['svg'] ) ) {
3980 // No media queries required if we only have a 1x and svg variant
3981 // because all preload-capable browsers support SVGs
3982 $this->addLinkHeader( '<' . $logo['svg'] . '>;rel=preload;as=image' );
3986 foreach ( $logo as $dppx => $src ) {
3987 // Keys are in this format: "1.5x"
3988 $dppx = substr( $dppx, 0, -1 );
3989 $logosPerDppx[$dppx] = $src;
3992 // Because PHP can't have floats as array keys
3993 uksort( $logosPerDppx, function ( $a , $b ) {
3994 $a = floatval( $a );
3995 $b = floatval( $b );
4000 // Sort from smallest to largest (e.g. 1x, 1.5x, 2x)
4001 return ( $a < $b ) ?
-1 : 1;
4004 foreach ( $logosPerDppx as $dppx => $src ) {
4005 $logos[] = [ 'dppx' => $dppx, 'src' => $src ];
4008 $logosCount = count( $logos );
4009 // Logic must match ResourceLoaderSkinModule:
4010 // - 1x applies to resolution < 1.5dppx
4011 // - 1.5x applies to resolution >= 1.5dppx && < 2dppx
4012 // - 2x applies to resolution >= 2dppx
4013 // Note that min-resolution and max-resolution are both inclusive.
4014 for ( $i = 0; $i < $logosCount; $i++
) {
4017 // min-resolution is ">=" (larger than or equal to)
4018 // "not min-resolution" is essentially "<"
4019 $media_query = 'not all and (min-resolution: ' . $logos[ 1 ]['dppx'] . 'dppx)';
4020 } elseif ( $i !== $logosCount - 1 ) {
4022 // Media query expressions can only apply "not" to the entire expression
4023 // (e.g. can't express ">= 1.5 and not >= 2).
4024 // Workaround: Use <= 1.9999 in place of < 2.
4025 $upper_bound = floatval( $logos[ $i +
1 ]['dppx'] ) - 0.000001;
4026 $media_query = '(min-resolution: ' . $logos[ $i ]['dppx'] .
4027 'dppx) and (max-resolution: ' . $upper_bound . 'dppx)';
4030 $media_query = '(min-resolution: ' . $logos[ $i ]['dppx'] . 'dppx)';
4033 $this->addLinkHeader(
4034 '<' . $logos[$i]['src'] . '>;rel=preload;as=image;media=' . $media_query