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 * Register and add a stylesheet from an extension directory.
470 * @deprecated since 1.27 use addModuleStyles() or addStyle() instead
471 * @param string $url Path to sheet. Provide either a full url (beginning
472 * with 'http', etc) or a relative path from the document root
473 * (beginning with '/'). Otherwise it behaves identically to
474 * addStyle() and draws from the /skins folder.
476 public function addExtensionStyle( $url ) {
477 wfDeprecated( __METHOD__
, '1.27' );
478 array_push( $this->mExtStyles
, $url );
482 * Get all styles added by extensions
484 * @deprecated since 1.27
487 function getExtStyle() {
488 wfDeprecated( __METHOD__
, '1.27' );
489 return $this->mExtStyles
;
493 * Add a JavaScript file out of skins/common, or a given relative path.
494 * Internal use only. Use OutputPage::addModules() if possible.
496 * @param string $file Filename in skins/common or complete on-server path
498 * @param string $version Style version of the file. Defaults to $wgStyleVersion
500 public function addScriptFile( $file, $version = null ) {
501 // See if $file parameter is an absolute URL or begins with a slash
502 if ( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
505 $path = $this->getConfig()->get( 'StylePath' ) . "/common/{$file}";
507 if ( is_null( $version ) ) {
508 $version = $this->getConfig()->get( 'StyleVersion' );
510 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
514 * Add a self-contained script tag with the given contents
515 * Internal use only. Use OutputPage::addModules() if possible.
517 * @param string $script JavaScript text, no script tags
519 public function addInlineScript( $script ) {
520 $this->mScripts
.= Html
::inlineScript( $script );
524 * Filter an array of modules to remove insufficiently trustworthy members, and modules
525 * which are no longer registered (eg a page is cached before an extension is disabled)
526 * @param array $modules
527 * @param string|null $position If not null, only return modules with this position
528 * @param string $type
531 protected function filterModules( array $modules, $position = null,
532 $type = ResourceLoaderModule
::TYPE_COMBINED
534 $resourceLoader = $this->getResourceLoader();
535 $filteredModules = [];
536 foreach ( $modules as $val ) {
537 $module = $resourceLoader->getModule( $val );
538 if ( $module instanceof ResourceLoaderModule
539 && $module->getOrigin() <= $this->getAllowedModules( $type )
540 && ( is_null( $position ) ||
$module->getPosition() == $position )
542 if ( $this->mTarget
&& !in_array( $this->mTarget
, $module->getTargets() ) ) {
543 $this->warnModuleTargetFilter( $module->getName() );
546 $filteredModules[] = $val;
549 return $filteredModules;
552 private function warnModuleTargetFilter( $moduleName ) {
553 static $warnings = [];
554 if ( isset( $warnings[$this->mTarget
][$moduleName] ) ) {
557 $warnings[$this->mTarget
][$moduleName] = true;
558 $this->getResourceLoader()->getLogger()->debug(
559 'Module "{module}" not loadable on target "{target}".',
561 'module' => $moduleName,
562 'target' => $this->mTarget
,
568 * Get the list of modules to include on this page
570 * @param bool $filter Whether to filter out insufficiently trustworthy modules
571 * @param string|null $position If not null, only return modules with this position
572 * @param string $param
573 * @param string $type
574 * @return array Array of module names
576 public function getModules( $filter = false, $position = null, $param = 'mModules',
577 $type = ResourceLoaderModule
::TYPE_COMBINED
579 $modules = array_values( array_unique( $this->$param ) );
581 ?
$this->filterModules( $modules, $position, $type )
586 * Add one or more modules recognized by ResourceLoader. Modules added
587 * through this function will be loaded by ResourceLoader when the
590 * @param string|array $modules Module name (string) or array of module names
592 public function addModules( $modules ) {
593 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
597 * Get the list of module JS to include on this page
599 * @param bool $filter
600 * @param string|null $position
601 * @return array Array of module names
603 public function getModuleScripts( $filter = false, $position = null ) {
604 return $this->getModules( $filter, $position, 'mModuleScripts',
605 ResourceLoaderModule
::TYPE_SCRIPTS
610 * Add only JS of one or more modules recognized by ResourceLoader. Module
611 * scripts added through this function will be loaded by ResourceLoader when
614 * @param string|array $modules Module name (string) or array of module names
616 public function addModuleScripts( $modules ) {
617 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
621 * Get the list of module CSS to include on this page
623 * @param bool $filter
624 * @param string|null $position
625 * @return array Array of module names
627 public function getModuleStyles( $filter = false, $position = null ) {
628 return $this->getModules( $filter, $position, 'mModuleStyles',
629 ResourceLoaderModule
::TYPE_STYLES
634 * Add only CSS of one or more modules recognized by ResourceLoader.
636 * Module styles added through this function will be added using standard link CSS
637 * tags, rather than as a combined Javascript and CSS package. Thus, they will
638 * load when JavaScript is disabled (unless CSS also happens to be disabled).
640 * @param string|array $modules Module name (string) or array of module names
642 public function addModuleStyles( $modules ) {
643 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
647 * @return null|string ResourceLoader target
649 public function getTarget() {
650 return $this->mTarget
;
654 * Sets ResourceLoader target for load.php links. If null, will be omitted
656 * @param string|null $target
658 public function setTarget( $target ) {
659 $this->mTarget
= $target;
663 * Get an array of head items
667 function getHeadItemsArray() {
668 return $this->mHeadItems
;
672 * Add or replace a head item to the output
674 * Whenever possible, use more specific options like ResourceLoader modules,
675 * OutputPage::addLink(), OutputPage::addMetaLink() and OutputPage::addFeedLink()
676 * Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
677 * OutputPage::addInlineScript() and OutputPage::addInlineStyle()
678 * This would be your very LAST fallback.
680 * @param string $name Item name
681 * @param string $value Raw HTML
683 public function addHeadItem( $name, $value ) {
684 $this->mHeadItems
[$name] = $value;
688 * Add one or more head items to the output
691 * @param string|string[] $values Raw HTML
693 public function addHeadItems( $values ) {
694 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$values );
698 * Check if the header item $name is already set
700 * @param string $name Item name
703 public function hasHeadItem( $name ) {
704 return isset( $this->mHeadItems
[$name] );
708 * Add a class to the <body> element
711 * @param string|string[] $classes One or more classes to add
713 public function addBodyClasses( $classes ) {
714 $this->mAdditionalBodyClasses
= array_merge( $this->mAdditionalBodyClasses
, (array)$classes );
718 * @deprecated since 1.28 Obsolete - wgUseETag experiment was removed.
721 public function setETag( $tag ) {
725 * Set whether the output should only contain the body of the article,
726 * without any skin, sidebar, etc.
727 * Used e.g. when calling with "action=render".
729 * @param bool $only Whether to output only the body of the article
731 public function setArticleBodyOnly( $only ) {
732 $this->mArticleBodyOnly
= $only;
736 * Return whether the output will contain only the body of the article
740 public function getArticleBodyOnly() {
741 return $this->mArticleBodyOnly
;
745 * Set an additional output property
748 * @param string $name
749 * @param mixed $value
751 public function setProperty( $name, $value ) {
752 $this->mProperties
[$name] = $value;
756 * Get an additional output property
759 * @param string $name
760 * @return mixed Property value or null if not found
762 public function getProperty( $name ) {
763 if ( isset( $this->mProperties
[$name] ) ) {
764 return $this->mProperties
[$name];
771 * checkLastModified tells the client to use the client-cached page if
772 * possible. If successful, the OutputPage is disabled so that
773 * any future call to OutputPage->output() have no effect.
775 * Side effect: sets mLastModified for Last-Modified header
777 * @param string $timestamp
779 * @return bool True if cache-ok headers was sent.
781 public function checkLastModified( $timestamp ) {
782 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
783 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
786 $config = $this->getConfig();
787 if ( !$config->get( 'CachePages' ) ) {
788 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
792 $timestamp = wfTimestamp( TS_MW
, $timestamp );
794 'page' => $timestamp,
795 'user' => $this->getUser()->getTouched(),
796 'epoch' => $config->get( 'CacheEpoch' )
798 if ( $config->get( 'UseSquid' ) ) {
799 // T46570: the core page itself may not change, but resources might
800 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, time() - $config->get( 'SquidMaxage' ) );
802 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this ] );
804 $maxModified = max( $modifiedTimes );
805 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
807 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
808 if ( $clientHeader === false ) {
809 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header", 'private' );
813 # IE sends sizes after the date like this:
814 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
815 # this breaks strtotime().
816 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
818 MediaWiki\
suppressWarnings(); // E_STRICT system time bitching
819 $clientHeaderTime = strtotime( $clientHeader );
820 MediaWiki\restoreWarnings
();
821 if ( !$clientHeaderTime ) {
823 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
826 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
830 foreach ( $modifiedTimes as $name => $value ) {
831 if ( $info !== '' ) {
834 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
837 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
838 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ), 'private' );
839 wfDebug( __METHOD__
. ": effective Last-Modified: " .
840 wfTimestamp( TS_ISO_8601
, $maxModified ), 'private' );
841 if ( $clientHeaderTime < $maxModified ) {
842 wfDebug( __METHOD__
. ": STALE, $info", 'private' );
847 # Give a 304 Not Modified response code and disable body output
848 wfDebug( __METHOD__
. ": NOT MODIFIED, $info", 'private' );
849 ini_set( 'zlib.output_compression', 0 );
850 $this->getRequest()->response()->statusHeader( 304 );
851 $this->sendCacheControl();
854 // Don't output a compressed blob when using ob_gzhandler;
855 // it's technically against HTTP spec and seems to confuse
856 // Firefox when the response gets split over two packets.
857 wfClearOutputBuffers();
863 * Override the last modified timestamp
865 * @param string $timestamp New timestamp, in a format readable by
868 public function setLastModified( $timestamp ) {
869 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
873 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
875 * @param string $policy The literal string to output as the contents of
876 * the meta tag. Will be parsed according to the spec and output in
880 public function setRobotPolicy( $policy ) {
881 $policy = Article
::formatRobotPolicy( $policy );
883 if ( isset( $policy['index'] ) ) {
884 $this->setIndexPolicy( $policy['index'] );
886 if ( isset( $policy['follow'] ) ) {
887 $this->setFollowPolicy( $policy['follow'] );
892 * Set the index policy for the page, but leave the follow policy un-
895 * @param string $policy Either 'index' or 'noindex'.
898 public function setIndexPolicy( $policy ) {
899 $policy = trim( $policy );
900 if ( in_array( $policy, [ 'index', 'noindex' ] ) ) {
901 $this->mIndexPolicy
= $policy;
906 * Set the follow policy for the page, but leave the index policy un-
909 * @param string $policy Either 'follow' or 'nofollow'.
912 public function setFollowPolicy( $policy ) {
913 $policy = trim( $policy );
914 if ( in_array( $policy, [ 'follow', 'nofollow' ] ) ) {
915 $this->mFollowPolicy
= $policy;
920 * Set the new value of the "action text", this will be added to the
921 * "HTML title", separated from it with " - ".
923 * @param string $text New value of the "action text"
925 public function setPageTitleActionText( $text ) {
926 $this->mPageTitleActionText
= $text;
930 * Get the value of the "action text"
934 public function getPageTitleActionText() {
935 return $this->mPageTitleActionText
;
939 * "HTML title" means the contents of "<title>".
940 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
942 * @param string|Message $name
944 public function setHTMLTitle( $name ) {
945 if ( $name instanceof Message
) {
946 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
948 $this->mHTMLtitle
= $name;
953 * Return the "HTML title", i.e. the content of the "<title>" tag.
957 public function getHTMLTitle() {
958 return $this->mHTMLtitle
;
962 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
966 public function setRedirectedFrom( $t ) {
967 $this->mRedirectedFrom
= $t;
971 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
972 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
973 * but not bad tags like \<script\>. This function automatically sets
974 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
975 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
976 * good tags like \<i\> will be dropped entirely.
978 * @param string|Message $name
980 public function setPageTitle( $name ) {
981 if ( $name instanceof Message
) {
982 $name = $name->setContext( $this->getContext() )->text();
985 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
986 # but leave "<i>foobar</i>" alone
987 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
988 $this->mPagetitle
= $nameWithTags;
990 # change "<i>foo&bar</i>" to "foo&bar"
992 $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) )
993 ->inContentLanguage()
998 * Return the "page title", i.e. the content of the \<h1\> tag.
1002 public function getPageTitle() {
1003 return $this->mPagetitle
;
1007 * Set the Title object to use
1011 public function setTitle( Title
$t ) {
1012 $this->getContext()->setTitle( $t );
1016 * Replace the subtitle with $str
1018 * @param string|Message $str New value of the subtitle. String should be safe HTML.
1020 public function setSubtitle( $str ) {
1021 $this->clearSubtitle();
1022 $this->addSubtitle( $str );
1026 * Add $str to the subtitle
1028 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
1030 public function addSubtitle( $str ) {
1031 if ( $str instanceof Message
) {
1032 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
1034 $this->mSubtitle
[] = $str;
1039 * Build message object for a subtitle containing a backlink to a page
1041 * @param Title $title Title to link to
1042 * @param array $query Array of additional parameters to include in the link
1046 public static function buildBacklinkSubtitle( Title
$title, $query = [] ) {
1047 if ( $title->isRedirect() ) {
1048 $query['redirect'] = 'no';
1050 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1051 return wfMessage( 'backlinksubtitle' )
1052 ->rawParams( $linkRenderer->makeLink( $title, null, [], $query ) );
1056 * Add a subtitle containing a backlink to a page
1058 * @param Title $title Title to link to
1059 * @param array $query Array of additional parameters to include in the link
1061 public function addBacklinkSubtitle( Title
$title, $query = [] ) {
1062 $this->addSubtitle( self
::buildBacklinkSubtitle( $title, $query ) );
1066 * Clear the subtitles
1068 public function clearSubtitle() {
1069 $this->mSubtitle
= [];
1077 public function getSubtitle() {
1078 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1082 * Set the page as printable, i.e. it'll be displayed with all
1083 * print styles included
1085 public function setPrintable() {
1086 $this->mPrintable
= true;
1090 * Return whether the page is "printable"
1094 public function isPrintable() {
1095 return $this->mPrintable
;
1099 * Disable output completely, i.e. calling output() will have no effect
1101 public function disable() {
1102 $this->mDoNothing
= true;
1106 * Return whether the output will be completely disabled
1110 public function isDisabled() {
1111 return $this->mDoNothing
;
1115 * Show an "add new section" link?
1119 public function showNewSectionLink() {
1120 return $this->mNewSectionLink
;
1124 * Forcibly hide the new section link?
1128 public function forceHideNewSectionLink() {
1129 return $this->mHideNewSectionLink
;
1133 * Add or remove feed links in the page header
1134 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1135 * for the new version
1136 * @see addFeedLink()
1138 * @param bool $show True: add default feeds, false: remove all feeds
1140 public function setSyndicated( $show = true ) {
1142 $this->setFeedAppendQuery( false );
1144 $this->mFeedLinks
= [];
1149 * Add default feeds to the page header
1150 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1151 * for the new version
1152 * @see addFeedLink()
1154 * @param string $val Query to append to feed links or false to output
1157 public function setFeedAppendQuery( $val ) {
1158 $this->mFeedLinks
= [];
1160 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1161 $query = "feed=$type";
1162 if ( is_string( $val ) ) {
1163 $query .= '&' . $val;
1165 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1170 * Add a feed link to the page header
1172 * @param string $format Feed type, should be a key of $wgFeedClasses
1173 * @param string $href URL
1175 public function addFeedLink( $format, $href ) {
1176 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1177 $this->mFeedLinks
[$format] = $href;
1182 * Should we output feed links for this page?
1185 public function isSyndicated() {
1186 return count( $this->mFeedLinks
) > 0;
1190 * Return URLs for each supported syndication format for this page.
1191 * @return array Associating format keys with URLs
1193 public function getSyndicationLinks() {
1194 return $this->mFeedLinks
;
1198 * Will currently always return null
1202 public function getFeedAppendQuery() {
1203 return $this->mFeedLinksAppendQuery
;
1207 * Set whether the displayed content is related to the source of the
1208 * corresponding article on the wiki
1209 * Setting true will cause the change "article related" toggle to true
1213 public function setArticleFlag( $v ) {
1214 $this->mIsarticle
= $v;
1216 $this->mIsArticleRelated
= $v;
1221 * Return whether the content displayed page is related to the source of
1222 * the corresponding article on the wiki
1226 public function isArticle() {
1227 return $this->mIsarticle
;
1231 * Set whether this page is related an article on the wiki
1232 * Setting false will cause the change of "article flag" toggle to false
1236 public function setArticleRelated( $v ) {
1237 $this->mIsArticleRelated
= $v;
1239 $this->mIsarticle
= false;
1244 * Return whether this page is related an article on the wiki
1248 public function isArticleRelated() {
1249 return $this->mIsArticleRelated
;
1253 * Add new language links
1255 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1256 * (e.g. 'fr:Test page')
1258 public function addLanguageLinks( array $newLinkArray ) {
1259 $this->mLanguageLinks +
= $newLinkArray;
1263 * Reset the language links and add new language links
1265 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1266 * (e.g. 'fr:Test page')
1268 public function setLanguageLinks( array $newLinkArray ) {
1269 $this->mLanguageLinks
= $newLinkArray;
1273 * Get the list of language links
1275 * @return string[] Array of interwiki-prefixed (non DB key) titles (e.g. 'fr:Test page')
1277 public function getLanguageLinks() {
1278 return $this->mLanguageLinks
;
1282 * Add an array of categories, with names in the keys
1284 * @param array $categories Mapping category name => sort key
1286 public function addCategoryLinks( array $categories ) {
1289 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1293 $res = $this->addCategoryLinksToLBAndGetResult( $categories );
1295 # Set all the values to 'normal'.
1296 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1298 # Mark hidden categories
1299 foreach ( $res as $row ) {
1300 if ( isset( $row->pp_value
) ) {
1301 $categories[$row->page_title
] = 'hidden';
1305 // Avoid PHP 7.1 warning of passing $this by reference
1306 $outputPage = $this;
1307 # Add the remaining categories to the skin
1309 'OutputPageMakeCategoryLinks',
1310 [ &$outputPage, $categories, &$this->mCategoryLinks
] )
1312 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1313 foreach ( $categories as $category => $type ) {
1314 // array keys will cast numeric category names to ints, so cast back to string
1315 $category = (string)$category;
1316 $origcategory = $category;
1317 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1321 $wgContLang->findVariantLink( $category, $title, true );
1322 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1325 $text = $wgContLang->convertHtml( $title->getText() );
1326 $this->mCategories
[$type][] = $title->getText();
1327 $this->mCategoryLinks
[$type][] = $linkRenderer->makeLink( $title, new HtmlArmor( $text ) );
1333 * @param array $categories
1334 * @return bool|ResultWrapper
1336 protected function addCategoryLinksToLBAndGetResult( array $categories ) {
1337 # Add the links to a LinkBatch
1338 $arr = [ NS_CATEGORY
=> $categories ];
1339 $lb = new LinkBatch
;
1340 $lb->setArray( $arr );
1342 # Fetch existence plus the hiddencat property
1343 $dbr = wfGetDB( DB_REPLICA
);
1344 $fields = array_merge(
1345 LinkCache
::getSelectFields(),
1346 [ 'page_namespace', 'page_title', 'pp_value' ]
1349 $res = $dbr->select( [ 'page', 'page_props' ],
1351 $lb->constructSet( 'page', $dbr ),
1354 [ 'page_props' => [ 'LEFT JOIN', [
1355 'pp_propname' => 'hiddencat',
1360 # Add the results to the link cache
1361 $lb->addResultToCache( LinkCache
::singleton(), $res );
1367 * Reset the category links (but not the category list) and add $categories
1369 * @param array $categories Mapping category name => sort key
1371 public function setCategoryLinks( array $categories ) {
1372 $this->mCategoryLinks
= [];
1373 $this->addCategoryLinks( $categories );
1377 * Get the list of category links, in a 2-D array with the following format:
1378 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1379 * hidden categories) and $link a HTML fragment with a link to the category
1384 public function getCategoryLinks() {
1385 return $this->mCategoryLinks
;
1389 * Get the list of category names this page belongs to.
1391 * @param string $type The type of categories which should be returned. Possible values:
1392 * * all: all categories of all types
1393 * * hidden: only the hidden categories
1394 * * normal: all categories, except hidden categories
1395 * @return array Array of strings
1397 public function getCategories( $type = 'all' ) {
1398 if ( $type === 'all' ) {
1399 $allCategories = [];
1400 foreach ( $this->mCategories
as $categories ) {
1401 $allCategories = array_merge( $allCategories, $categories );
1403 return $allCategories;
1405 if ( !isset( $this->mCategories
[$type] ) ) {
1406 throw new InvalidArgumentException( 'Invalid category type given: ' . $type );
1408 return $this->mCategories
[$type];
1412 * Add an array of indicators, with their identifiers as array
1413 * keys and HTML contents as values.
1415 * In case of duplicate keys, existing values are overwritten.
1417 * @param array $indicators
1420 public function setIndicators( array $indicators ) {
1421 $this->mIndicators
= $indicators +
$this->mIndicators
;
1422 // Keep ordered by key
1423 ksort( $this->mIndicators
);
1427 * Get the indicators associated with this page.
1429 * The array will be internally ordered by item keys.
1431 * @return array Keys: identifiers, values: HTML contents
1434 public function getIndicators() {
1435 return $this->mIndicators
;
1439 * Adds help link with an icon via page indicators.
1440 * Link target can be overridden by a local message containing a wikilink:
1441 * the message key is: lowercase action or special page name + '-helppage'.
1442 * @param string $to Target MediaWiki.org page title or encoded URL.
1443 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1446 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1447 $this->addModuleStyles( 'mediawiki.helplink' );
1448 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1450 if ( $overrideBaseUrl ) {
1453 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1454 $helpUrl = "//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1457 $link = Html
::rawElement(
1461 'target' => '_blank',
1462 'class' => 'mw-helplink',
1467 $this->setIndicators( [ 'mw-helplink' => $link ] );
1471 * Do not allow scripts which can be modified by wiki users to load on this page;
1472 * only allow scripts bundled with, or generated by, the software.
1473 * Site-wide styles are controlled by a config setting, since they can be
1474 * used to create a custom skin/theme, but not user-specific ones.
1476 * @todo this should be given a more accurate name
1478 public function disallowUserJs() {
1479 $this->reduceAllowedModules(
1480 ResourceLoaderModule
::TYPE_SCRIPTS
,
1481 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1484 // Site-wide styles are controlled by a config setting, see T73621
1485 // for background on why. User styles are never allowed.
1486 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1487 $styleOrigin = ResourceLoaderModule
::ORIGIN_USER_SITEWIDE
;
1489 $styleOrigin = ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
;
1491 $this->reduceAllowedModules(
1492 ResourceLoaderModule
::TYPE_STYLES
,
1498 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1499 * @see ResourceLoaderModule::$origin
1500 * @param string $type ResourceLoaderModule TYPE_ constant
1501 * @return int ResourceLoaderModule ORIGIN_ class constant
1503 public function getAllowedModules( $type ) {
1504 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1505 return min( array_values( $this->mAllowedModules
) );
1507 return isset( $this->mAllowedModules
[$type] )
1508 ?
$this->mAllowedModules
[$type]
1509 : ResourceLoaderModule
::ORIGIN_ALL
;
1514 * Limit the highest level of CSS/JS untrustworthiness allowed.
1516 * If passed the same or a higher level than the current level of untrustworthiness set, the
1517 * level will remain unchanged.
1519 * @param string $type
1520 * @param int $level ResourceLoaderModule class constant
1522 public function reduceAllowedModules( $type, $level ) {
1523 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1527 * Prepend $text to the body HTML
1529 * @param string $text HTML
1531 public function prependHTML( $text ) {
1532 $this->mBodytext
= $text . $this->mBodytext
;
1536 * Append $text to the body HTML
1538 * @param string $text HTML
1540 public function addHTML( $text ) {
1541 $this->mBodytext
.= $text;
1545 * Shortcut for adding an Html::element via addHTML.
1549 * @param string $element
1550 * @param array $attribs
1551 * @param string $contents
1553 public function addElement( $element, array $attribs = [], $contents = '' ) {
1554 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1558 * Clear the body HTML
1560 public function clearHTML() {
1561 $this->mBodytext
= '';
1567 * @return string HTML
1569 public function getHTML() {
1570 return $this->mBodytext
;
1574 * Get/set the ParserOptions object to use for wikitext parsing
1576 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1577 * current ParserOption object. This parameter is deprecated since 1.31.
1578 * @return ParserOptions
1580 public function parserOptions( $options = null ) {
1581 if ( $options !== null ) {
1582 wfDeprecated( __METHOD__
. ' with non-null $options', '1.31' );
1585 if ( $options !== null && !empty( $options->isBogus
) ) {
1586 // Someone is trying to set a bogus pre-$wgUser PO. Check if it has
1587 // been changed somehow, and keep it if so.
1588 $anonPO = ParserOptions
::newFromAnon();
1589 $anonPO->setEditSection( false );
1590 $anonPO->setAllowUnsafeRawHtml( false );
1591 if ( !$options->matches( $anonPO ) ) {
1592 wfLogWarning( __METHOD__
. ': Setting a changed bogus ParserOptions: ' . wfGetAllCallers( 5 ) );
1593 $options->isBogus
= false;
1597 if ( !$this->mParserOptions
) {
1598 if ( !$this->getContext()->getUser()->isSafeToLoad() ) {
1599 // $wgUser isn't unstubbable yet, so don't try to get a
1600 // ParserOptions for it. And don't cache this ParserOptions
1602 $po = ParserOptions
::newFromAnon();
1603 $po->setEditSection( false );
1604 $po->setAllowUnsafeRawHtml( false );
1605 $po->isBogus
= true;
1606 if ( $options !== null ) {
1607 $this->mParserOptions
= empty( $options->isBogus
) ?
$options : null;
1612 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1613 $this->mParserOptions
->setEditSection( false );
1614 $this->mParserOptions
->setAllowUnsafeRawHtml( false );
1617 if ( $options !== null && !empty( $options->isBogus
) ) {
1618 // They're trying to restore the bogus pre-$wgUser PO. Do the right
1620 return wfSetVar( $this->mParserOptions
, null, true );
1622 return wfSetVar( $this->mParserOptions
, $options );
1627 * Set the revision ID which will be seen by the wiki text parser
1628 * for things such as embedded {{REVISIONID}} variable use.
1630 * @param int|null $revid An positive integer, or null
1631 * @return mixed Previous value
1633 public function setRevisionId( $revid ) {
1634 $val = is_null( $revid ) ?
null : intval( $revid );
1635 return wfSetVar( $this->mRevisionId
, $val );
1639 * Get the displayed revision ID
1643 public function getRevisionId() {
1644 return $this->mRevisionId
;
1648 * Set the timestamp of the revision which will be displayed. This is used
1649 * to avoid a extra DB call in Skin::lastModified().
1651 * @param string|null $timestamp
1652 * @return mixed Previous value
1654 public function setRevisionTimestamp( $timestamp ) {
1655 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1659 * Get the timestamp of displayed revision.
1660 * This will be null if not filled by setRevisionTimestamp().
1662 * @return string|null
1664 public function getRevisionTimestamp() {
1665 return $this->mRevisionTimestamp
;
1669 * Set the displayed file version
1671 * @param File|bool $file
1672 * @return mixed Previous value
1674 public function setFileVersion( $file ) {
1676 if ( $file instanceof File
&& $file->exists() ) {
1677 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1679 return wfSetVar( $this->mFileVersion
, $val, true );
1683 * Get the displayed file version
1685 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1687 public function getFileVersion() {
1688 return $this->mFileVersion
;
1692 * Get the templates used on this page
1694 * @return array (namespace => dbKey => revId)
1697 public function getTemplateIds() {
1698 return $this->mTemplateIds
;
1702 * Get the files used on this page
1704 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1707 public function getFileSearchOptions() {
1708 return $this->mImageTimeKeys
;
1712 * Convert wikitext to HTML and add it to the buffer
1713 * Default assumes that the current page title will be used.
1715 * @param string $text
1716 * @param bool $linestart Is this the start of a line?
1717 * @param bool $interface Is this text in the user interface language?
1718 * @throws MWException
1720 public function addWikiText( $text, $linestart = true, $interface = true ) {
1721 $title = $this->getTitle(); // Work around E_STRICT
1723 throw new MWException( 'Title is null' );
1725 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1729 * Add wikitext with a custom Title object
1731 * @param string $text Wikitext
1732 * @param Title &$title
1733 * @param bool $linestart Is this the start of a line?
1735 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1736 $this->addWikiTextTitle( $text, $title, $linestart );
1740 * Add wikitext with a custom Title object and tidy enabled.
1742 * @param string $text Wikitext
1743 * @param Title &$title
1744 * @param bool $linestart Is this the start of a line?
1746 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1747 $this->addWikiTextTitle( $text, $title, $linestart, true );
1751 * Add wikitext with tidy enabled
1753 * @param string $text Wikitext
1754 * @param bool $linestart Is this the start of a line?
1756 public function addWikiTextTidy( $text, $linestart = true ) {
1757 $title = $this->getTitle();
1758 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1762 * Add wikitext with a custom Title object
1764 * @param string $text Wikitext
1765 * @param Title $title
1766 * @param bool $linestart Is this the start of a line?
1767 * @param bool $tidy Whether to use tidy
1768 * @param bool $interface Whether it is an interface message
1769 * (for example disables conversion)
1771 public function addWikiTextTitle( $text, Title
$title, $linestart,
1772 $tidy = false, $interface = false
1776 $popts = $this->parserOptions();
1777 $oldTidy = $popts->setTidy( $tidy );
1778 $popts->setInterfaceMessage( (bool)$interface );
1780 $parserOutput = $wgParser->getFreshParser()->parse(
1781 $text, $title, $popts,
1782 $linestart, true, $this->mRevisionId
1785 $popts->setTidy( $oldTidy );
1787 $this->addParserOutput( $parserOutput, [
1788 'enableSectionEditLinks' => false,
1793 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1794 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1798 * @param ParserOutput $parserOutput
1800 public function addParserOutputMetadata( $parserOutput ) {
1801 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1802 $this->addCategoryLinks( $parserOutput->getCategories() );
1803 $this->setIndicators( $parserOutput->getIndicators() );
1804 $this->mNewSectionLink
= $parserOutput->getNewSection();
1805 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1807 if ( !$parserOutput->isCacheable() ) {
1808 $this->enableClientCache( false );
1810 $this->mNoGallery
= $parserOutput->getNoGallery();
1811 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1812 $this->addModules( $parserOutput->getModules() );
1813 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1814 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1815 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1816 $this->mPreventClickjacking
= $this->mPreventClickjacking
1817 ||
$parserOutput->preventClickjacking();
1819 // Template versioning...
1820 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1821 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1822 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1824 $this->mTemplateIds
[$ns] = $dbks;
1827 // File versioning...
1828 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1829 $this->mImageTimeKeys
[$dbk] = $data;
1832 // Hooks registered in the object
1833 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1834 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1835 list( $hookName, $data ) = $hookInfo;
1836 if ( isset( $parserOutputHooks[$hookName] ) ) {
1837 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1841 // Enable OOUI if requested via ParserOutput
1842 if ( $parserOutput->getEnableOOUI() ) {
1843 $this->enableOOUI();
1846 // Include parser limit report
1847 if ( !$this->limitReportJSData
) {
1848 $this->limitReportJSData
= $parserOutput->getLimitReportJSData();
1851 // Link flags are ignored for now, but may in the future be
1852 // used to mark individual language links.
1854 // Avoid PHP 7.1 warning of passing $this by reference
1855 $outputPage = $this;
1856 Hooks
::run( 'LanguageLinks', [ $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ] );
1857 Hooks
::runWithoutAbort( 'OutputPageParserOutput', [ &$outputPage, $parserOutput ] );
1859 // This check must be after 'OutputPageParserOutput' runs in addParserOutputMetadata
1860 // so that extensions may modify ParserOutput to toggle TOC.
1861 // This cannot be moved to addParserOutputText because that is not
1862 // called by EditPage for Preview.
1863 if ( $parserOutput->getTOCEnabled() && $parserOutput->getTOCHTML() ) {
1864 $this->mEnableTOC
= true;
1869 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1870 * ParserOutput object, without any other metadata.
1873 * @param ParserOutput $parserOutput
1874 * @param array $poOptions Options to ParserOutput::getText()
1876 public function addParserOutputContent( $parserOutput, $poOptions = [] ) {
1877 $this->addParserOutputText( $parserOutput, $poOptions );
1879 $this->addModules( $parserOutput->getModules() );
1880 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1881 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1883 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1887 * Add the HTML associated with a ParserOutput object, without any metadata.
1890 * @param ParserOutput $parserOutput
1891 * @param array $poOptions Options to ParserOutput::getText()
1893 public function addParserOutputText( $parserOutput, $poOptions = [] ) {
1894 $text = $parserOutput->getText( $poOptions );
1895 // Avoid PHP 7.1 warning of passing $this by reference
1896 $outputPage = $this;
1897 Hooks
::runWithoutAbort( 'OutputPageBeforeHTML', [ &$outputPage, &$text ] );
1898 $this->addHTML( $text );
1902 * Add everything from a ParserOutput object.
1904 * @param ParserOutput $parserOutput
1905 * @param array $poOptions Options to ParserOutput::getText()
1907 function addParserOutput( $parserOutput, $poOptions = [] ) {
1908 $this->addParserOutputMetadata( $parserOutput );
1910 // Touch section edit links only if not previously disabled
1911 if ( $parserOutput->getEditSectionTokens() ) {
1912 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks
);
1914 if ( !$this->mEnableSectionEditLinks
1915 && !array_key_exists( 'enableSectionEditLinks', $poOptions )
1917 $poOptions['enableSectionEditLinks'] = false;
1920 $this->addParserOutputText( $parserOutput, $poOptions );
1924 * Add the output of a QuickTemplate to the output buffer
1926 * @param QuickTemplate &$template
1928 public function addTemplate( &$template ) {
1929 $this->addHTML( $template->getHTML() );
1933 * Parse wikitext and return the HTML.
1935 * @param string $text
1936 * @param bool $linestart Is this the start of a line?
1937 * @param bool $interface Use interface language ($wgLang instead of
1938 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1939 * This also disables LanguageConverter.
1940 * @param Language $language Target language object, will override $interface
1941 * @throws MWException
1942 * @return string HTML
1944 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1947 if ( is_null( $this->getTitle() ) ) {
1948 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1951 $popts = $this->parserOptions();
1953 $popts->setInterfaceMessage( true );
1955 if ( $language !== null ) {
1956 $oldLang = $popts->setTargetLanguage( $language );
1959 $parserOutput = $wgParser->getFreshParser()->parse(
1960 $text, $this->getTitle(), $popts,
1961 $linestart, true, $this->mRevisionId
1965 $popts->setInterfaceMessage( false );
1967 if ( $language !== null ) {
1968 $popts->setTargetLanguage( $oldLang );
1971 return $parserOutput->getText( [
1972 'enableSectionEditLinks' => false,
1977 * Parse wikitext, strip paragraphs, and return the HTML.
1979 * @param string $text
1980 * @param bool $linestart Is this the start of a line?
1981 * @param bool $interface Use interface language ($wgLang instead of
1982 * $wgContLang) while parsing language sensitive magic
1983 * words like GRAMMAR and PLURAL
1984 * @return string HTML
1986 public function parseInline( $text, $linestart = true, $interface = false ) {
1987 $parsed = $this->parse( $text, $linestart, $interface );
1988 return Parser
::stripOuterParagraph( $parsed );
1992 * @param int $maxage
1993 * @deprecated since 1.27 Use setCdnMaxage() instead
1995 public function setSquidMaxage( $maxage ) {
1996 wfDeprecated( __METHOD__
, '1.27' );
1997 $this->setCdnMaxage( $maxage );
2001 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
2003 * @param int $maxage Maximum cache time on the CDN, in seconds.
2005 public function setCdnMaxage( $maxage ) {
2006 $this->mCdnMaxage
= min( $maxage, $this->mCdnMaxageLimit
);
2010 * Lower the value of the "s-maxage" part of the "Cache-control" HTTP header
2012 * @param int $maxage Maximum cache time on the CDN, in seconds
2015 public function lowerCdnMaxage( $maxage ) {
2016 $this->mCdnMaxageLimit
= min( $maxage, $this->mCdnMaxageLimit
);
2017 $this->setCdnMaxage( $this->mCdnMaxage
);
2021 * Get TTL in [$minTTL,$maxTTL] in pass it to lowerCdnMaxage()
2023 * This sets and returns $minTTL if $mtime is false or null. Otherwise,
2024 * the TTL is higher the older the $mtime timestamp is. Essentially, the
2025 * TTL is 90% of the age of the object, subject to the min and max.
2027 * @param string|int|float|bool|null $mtime Last-Modified timestamp
2028 * @param int $minTTL Mimimum TTL in seconds [default: 1 minute]
2029 * @param int $maxTTL Maximum TTL in seconds [default: $wgSquidMaxage]
2030 * @return int TTL in seconds
2033 public function adaptCdnTTL( $mtime, $minTTL = 0, $maxTTL = 0 ) {
2034 $minTTL = $minTTL ?
: IExpiringStore
::TTL_MINUTE
;
2035 $maxTTL = $maxTTL ?
: $this->getConfig()->get( 'SquidMaxage' );
2037 if ( $mtime === null ||
$mtime === false ) {
2038 return $minTTL; // entity does not exist
2041 $age = time() - wfTimestamp( TS_UNIX
, $mtime );
2042 $adaptiveTTL = max( 0.9 * $age, $minTTL );
2043 $adaptiveTTL = min( $adaptiveTTL, $maxTTL );
2045 $this->lowerCdnMaxage( (int)$adaptiveTTL );
2047 return $adaptiveTTL;
2051 * Use enableClientCache(false) to force it to send nocache headers
2053 * @param bool $state
2057 public function enableClientCache( $state ) {
2058 return wfSetVar( $this->mEnableClientCache
, $state );
2062 * Get the list of cookies that will influence on the cache
2066 function getCacheVaryCookies() {
2068 if ( $cookies === null ) {
2069 $config = $this->getConfig();
2070 $cookies = array_merge(
2071 SessionManager
::singleton()->getVaryCookies(),
2075 $config->get( 'CacheVaryCookies' )
2077 Hooks
::run( 'GetCacheVaryCookies', [ $this, &$cookies ] );
2083 * Check if the request has a cache-varying cookie header
2084 * If it does, it's very important that we don't allow public caching
2088 function haveCacheVaryCookies() {
2089 $request = $this->getRequest();
2090 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2091 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2092 wfDebug( __METHOD__
. ": found $cookieName\n" );
2096 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
2101 * Add an HTTP header that will influence on the cache
2103 * @param string $header Header name
2104 * @param string[]|null $option Options for the Key header. See
2105 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2106 * for the list of valid options.
2108 public function addVaryHeader( $header, array $option = null ) {
2109 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
2110 $this->mVaryHeader
[$header] = [];
2112 if ( !is_array( $option ) ) {
2115 $this->mVaryHeader
[$header] = array_unique( array_merge( $this->mVaryHeader
[$header], $option ) );
2119 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2120 * such as Accept-Encoding or Cookie
2124 public function getVaryHeader() {
2125 // If we vary on cookies, let's make sure it's always included here too.
2126 if ( $this->getCacheVaryCookies() ) {
2127 $this->addVaryHeader( 'Cookie' );
2130 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2131 $this->addVaryHeader( $header, $options );
2133 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader
) );
2137 * Add an HTTP Link: header
2139 * @param string $header Header value
2141 public function addLinkHeader( $header ) {
2142 $this->mLinkHeader
[] = $header;
2146 * Return a Link: header. Based on the values of $mLinkHeader.
2150 public function getLinkHeader() {
2151 if ( !$this->mLinkHeader
) {
2155 return 'Link: ' . implode( ',', $this->mLinkHeader
);
2159 * Get a complete Key header
2163 public function getKeyHeader() {
2164 $cvCookies = $this->getCacheVaryCookies();
2166 $cookiesOption = [];
2167 foreach ( $cvCookies as $cookieName ) {
2168 $cookiesOption[] = 'param=' . $cookieName;
2170 $this->addVaryHeader( 'Cookie', $cookiesOption );
2172 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2173 $this->addVaryHeader( $header, $options );
2177 foreach ( $this->mVaryHeader
as $header => $option ) {
2178 $newheader = $header;
2179 if ( is_array( $option ) && count( $option ) > 0 ) {
2180 $newheader .= ';' . implode( ';', $option );
2182 $headers[] = $newheader;
2184 $key = 'Key: ' . implode( ',', $headers );
2190 * T23672: Add Accept-Language to Vary and Key headers
2191 * if there's no 'variant' parameter existed in GET.
2194 * /w/index.php?title=Main_page should always be served; but
2195 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
2197 function addAcceptLanguage() {
2198 $title = $this->getTitle();
2199 if ( !$title instanceof Title
) {
2203 $lang = $title->getPageLanguage();
2204 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2205 $variants = $lang->getVariants();
2207 foreach ( $variants as $variant ) {
2208 if ( $variant === $lang->getCode() ) {
2211 $aloption[] = 'substr=' . $variant;
2213 // IE and some other browsers use BCP 47 standards in
2214 // their Accept-Language header, like "zh-CN" or "zh-Hant".
2215 // We should handle these too.
2216 $variantBCP47 = LanguageCode
::bcp47( $variant );
2217 if ( $variantBCP47 !== $variant ) {
2218 $aloption[] = 'substr=' . $variantBCP47;
2222 $this->addVaryHeader( 'Accept-Language', $aloption );
2227 * Set a flag which will cause an X-Frame-Options header appropriate for
2228 * edit pages to be sent. The header value is controlled by
2229 * $wgEditPageFrameOptions.
2231 * This is the default for special pages. If you display a CSRF-protected
2232 * form on an ordinary view page, then you need to call this function.
2234 * @param bool $enable
2236 public function preventClickjacking( $enable = true ) {
2237 $this->mPreventClickjacking
= $enable;
2241 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2242 * This can be called from pages which do not contain any CSRF-protected
2245 public function allowClickjacking() {
2246 $this->mPreventClickjacking
= false;
2250 * Get the prevent-clickjacking flag
2255 public function getPreventClickjacking() {
2256 return $this->mPreventClickjacking
;
2260 * Get the X-Frame-Options header value (without the name part), or false
2261 * if there isn't one. This is used by Skin to determine whether to enable
2262 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2264 * @return string|false
2266 public function getFrameOptions() {
2267 $config = $this->getConfig();
2268 if ( $config->get( 'BreakFrames' ) ) {
2270 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2271 return $config->get( 'EditPageFrameOptions' );
2277 * Send cache control HTTP headers
2279 public function sendCacheControl() {
2280 $response = $this->getRequest()->response();
2281 $config = $this->getConfig();
2283 $this->addVaryHeader( 'Cookie' );
2284 $this->addAcceptLanguage();
2286 # don't serve compressed data to clients who can't handle it
2287 # maintain different caches for logged-in users and non-logged in ones
2288 $response->header( $this->getVaryHeader() );
2290 if ( $config->get( 'UseKeyHeader' ) ) {
2291 $response->header( $this->getKeyHeader() );
2294 if ( $this->mEnableClientCache
) {
2296 $config->get( 'UseSquid' ) &&
2297 !$response->hasCookies() &&
2298 !SessionManager
::getGlobalSession()->isPersistent() &&
2299 !$this->isPrintable() &&
2300 $this->mCdnMaxage
!= 0 &&
2301 !$this->haveCacheVaryCookies()
2303 if ( $config->get( 'UseESI' ) ) {
2304 # We'll purge the proxy cache explicitly, but require end user agents
2305 # to revalidate against the proxy on each visit.
2306 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2307 wfDebug( __METHOD__
.
2308 ": proxy caching with ESI; {$this->mLastModified} **", 'private' );
2309 # start with a shorter timeout for initial testing
2310 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2312 "Surrogate-Control: max-age={$config->get( 'SquidMaxage' )}" .
2313 "+{$this->mCdnMaxage}, content=\"ESI/1.0\""
2315 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2317 # We'll purge the proxy cache for anons explicitly, but require end user agents
2318 # to revalidate against the proxy on each visit.
2319 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2320 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2321 wfDebug( __METHOD__
.
2322 ": local proxy caching; {$this->mLastModified} **", 'private' );
2323 # start with a shorter timeout for initial testing
2324 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2325 $response->header( "Cache-Control: " .
2326 "s-maxage={$this->mCdnMaxage}, must-revalidate, max-age=0" );
2329 # We do want clients to cache if they can, but they *must* check for updates
2330 # on revisiting the page.
2331 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **", 'private' );
2332 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2333 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2335 if ( $this->mLastModified
) {
2336 $response->header( "Last-Modified: {$this->mLastModified}" );
2339 wfDebug( __METHOD__
. ": no caching **", 'private' );
2341 # In general, the absence of a last modified header should be enough to prevent
2342 # the client from using its cache. We send a few other things just to make sure.
2343 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2344 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2345 $response->header( 'Pragma: no-cache' );
2350 * Finally, all the text has been munged and accumulated into
2351 * the object, let's actually output it:
2353 * @param bool $return Set to true to get the result as a string rather than sending it
2354 * @return string|null
2356 * @throws FatalError
2357 * @throws MWException
2359 public function output( $return = false ) {
2362 if ( $this->mDoNothing
) {
2363 return $return ?
'' : null;
2366 $response = $this->getRequest()->response();
2367 $config = $this->getConfig();
2369 if ( $this->mRedirect
!= '' ) {
2370 # Standards require redirect URLs to be absolute
2371 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2373 $redirect = $this->mRedirect
;
2374 $code = $this->mRedirectCode
;
2376 if ( Hooks
::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2377 if ( $code == '301' ||
$code == '303' ) {
2378 if ( !$config->get( 'DebugRedirects' ) ) {
2379 $response->statusHeader( $code );
2381 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2383 if ( $config->get( 'VaryOnXFP' ) ) {
2384 $this->addVaryHeader( 'X-Forwarded-Proto' );
2386 $this->sendCacheControl();
2388 $response->header( "Content-Type: text/html; charset=utf-8" );
2389 if ( $config->get( 'DebugRedirects' ) ) {
2390 $url = htmlspecialchars( $redirect );
2391 print "<!DOCTYPE html>\n<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2392 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2393 print "</body>\n</html>\n";
2395 $response->header( 'Location: ' . $redirect );
2399 return $return ?
'' : null;
2400 } elseif ( $this->mStatusCode
) {
2401 $response->statusHeader( $this->mStatusCode
);
2404 # Buffer output; final headers may depend on later processing
2407 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2408 $response->header( 'Content-language: ' . $wgContLang->getHtmlCode() );
2410 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2411 // jQuery etc. can work correctly.
2412 $response->header( 'X-UA-Compatible: IE=Edge' );
2414 if ( !$this->mArticleBodyOnly
) {
2415 $sk = $this->getSkin();
2417 if ( $sk->shouldPreloadLogo() ) {
2418 $this->addLogoPreloadLinkHeaders();
2422 $linkHeader = $this->getLinkHeader();
2423 if ( $linkHeader ) {
2424 $response->header( $linkHeader );
2427 // Prevent framing, if requested
2428 $frameOptions = $this->getFrameOptions();
2429 if ( $frameOptions ) {
2430 $response->header( "X-Frame-Options: $frameOptions" );
2433 if ( $this->mArticleBodyOnly
) {
2434 echo $this->mBodytext
;
2436 // Enable safe mode if requested
2437 if ( $this->getRequest()->getBool( 'safemode' ) ) {
2438 $this->disallowUserJs();
2441 $sk = $this->getSkin();
2442 foreach ( $sk->getDefaultModules() as $group ) {
2443 $this->addModules( $group );
2446 MWDebug
::addModules( $this );
2448 // Avoid PHP 7.1 warning of passing $this by reference
2449 $outputPage = $this;
2450 // Hook that allows last minute changes to the output page, e.g.
2451 // adding of CSS or Javascript by extensions.
2452 Hooks
::runWithoutAbort( 'BeforePageDisplay', [ &$outputPage, &$sk ] );
2456 } catch ( Exception
$e ) {
2457 ob_end_clean(); // bug T129657
2463 // This hook allows last minute changes to final overall output by modifying output buffer
2464 Hooks
::runWithoutAbort( 'AfterFinalPageOutput', [ $this ] );
2465 } catch ( Exception
$e ) {
2466 ob_end_clean(); // bug T129657
2470 $this->sendCacheControl();
2473 return ob_get_clean();
2481 * Prepare this object to display an error page; disable caching and
2482 * indexing, clear the current text and redirect, set the page's title
2483 * and optionally an custom HTML title (content of the "<title>" tag).
2485 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2486 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2487 * optional, if not passed the "<title>" attribute will be
2488 * based on $pageTitle
2490 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2491 $this->setPageTitle( $pageTitle );
2492 if ( $htmlTitle !== false ) {
2493 $this->setHTMLTitle( $htmlTitle );
2495 $this->setRobotPolicy( 'noindex,nofollow' );
2496 $this->setArticleRelated( false );
2497 $this->enableClientCache( false );
2498 $this->mRedirect
= '';
2499 $this->clearSubtitle();
2504 * Output a standard error page
2506 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2507 * showErrorPage( 'titlemsg', 'pagetextmsg', [ 'param1', 'param2' ] );
2508 * showErrorPage( 'titlemsg', $messageObject );
2509 * showErrorPage( $titleMessageObject, $messageObject );
2511 * @param string|Message $title Message key (string) for page title, or a Message object
2512 * @param string|Message $msg Message key (string) for page text, or a Message object
2513 * @param array $params Message parameters; ignored if $msg is a Message object
2515 public function showErrorPage( $title, $msg, $params = [] ) {
2516 if ( !$title instanceof Message
) {
2517 $title = $this->msg( $title );
2520 $this->prepareErrorPage( $title );
2522 if ( $msg instanceof Message
) {
2523 if ( $params !== [] ) {
2524 trigger_error( 'Argument ignored: $params. The message parameters argument '
2525 . 'is discarded when the $msg argument is a Message object instead of '
2526 . 'a string.', E_USER_NOTICE
);
2528 $this->addHTML( $msg->parseAsBlock() );
2530 $this->addWikiMsgArray( $msg, $params );
2533 $this->returnToMain();
2537 * Output a standard permission error page
2539 * @param array $errors Error message keys or [key, param...] arrays
2540 * @param string $action Action that was denied or null if unknown
2542 public function showPermissionsErrorPage( array $errors, $action = null ) {
2543 foreach ( $errors as $key => $error ) {
2544 $errors[$key] = (array)$error;
2547 // For some action (read, edit, create and upload), display a "login to do this action"
2548 // error if all of the following conditions are met:
2549 // 1. the user is not logged in
2550 // 2. the only error is insufficient permissions (i.e. no block or something else)
2551 // 3. the error can be avoided simply by logging in
2552 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2553 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2554 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2555 && ( User
::groupHasPermission( 'user', $action )
2556 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2558 $displayReturnto = null;
2560 # Due to T34276, if a user does not have read permissions,
2561 # $this->getTitle() will just give Special:Badtitle, which is
2562 # not especially useful as a returnto parameter. Use the title
2563 # from the request instead, if there was one.
2564 $request = $this->getRequest();
2565 $returnto = Title
::newFromText( $request->getVal( 'title', '' ) );
2566 if ( $action == 'edit' ) {
2567 $msg = 'whitelistedittext';
2568 $displayReturnto = $returnto;
2569 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2570 $msg = 'nocreatetext';
2571 } elseif ( $action == 'upload' ) {
2572 $msg = 'uploadnologintext';
2574 $msg = 'loginreqpagetext';
2575 $displayReturnto = Title
::newMainPage();
2581 $query['returnto'] = $returnto->getPrefixedText();
2583 if ( !$request->wasPosted() ) {
2584 $returntoquery = $request->getValues();
2585 unset( $returntoquery['title'] );
2586 unset( $returntoquery['returnto'] );
2587 unset( $returntoquery['returntoquery'] );
2588 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2591 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
2592 $loginLink = $linkRenderer->makeKnownLink(
2593 SpecialPage
::getTitleFor( 'Userlogin' ),
2594 $this->msg( 'loginreqlink' )->text(),
2599 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2600 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2602 # Don't return to a page the user can't read otherwise
2603 # we'll end up in a pointless loop
2604 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2605 $this->returnToMain( null, $displayReturnto );
2608 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2609 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2614 * Display an error page indicating that a given version of MediaWiki is
2615 * required to use it
2617 * @param mixed $version The version of MediaWiki needed to use the page
2619 public function versionRequired( $version ) {
2620 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2622 $this->addWikiMsg( 'versionrequiredtext', $version );
2623 $this->returnToMain();
2627 * Format a list of error messages
2629 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2630 * @param string $action Action that was denied or null if unknown
2631 * @return string The wikitext error-messages, formatted into a list.
2633 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2634 if ( $action == null ) {
2635 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2637 $action_desc = $this->msg( "action-$action" )->plain();
2639 'permissionserrorstext-withaction',
2642 )->plain() . "\n\n";
2645 if ( count( $errors ) > 1 ) {
2646 $text .= '<ul class="permissions-errors">' . "\n";
2648 foreach ( $errors as $error ) {
2650 $text .= call_user_func_array( [ $this, 'msg' ], $error )->plain();
2655 $text .= "<div class=\"permissions-errors\">\n" .
2656 call_user_func_array( [ $this, 'msg' ], reset( $errors ) )->plain() .
2664 * Display a page stating that the Wiki is in read-only mode.
2665 * Should only be called after wfReadOnly() has returned true.
2667 * Historically, this function was used to show the source of the page that the user
2668 * was trying to edit and _also_ permissions error messages. The relevant code was
2669 * moved into EditPage in 1.19 (r102024 / d83c2a431c2a) and removed here in 1.25.
2671 * @deprecated since 1.25; throw the exception directly
2672 * @throws ReadOnlyError
2674 public function readOnlyPage() {
2675 if ( func_num_args() > 0 ) {
2676 throw new MWException( __METHOD__
. ' no longer accepts arguments since 1.25.' );
2679 throw new ReadOnlyError
;
2683 * Turn off regular page output and return an error response
2684 * for when rate limiting has triggered.
2686 * @deprecated since 1.25; throw the exception directly
2688 public function rateLimited() {
2689 wfDeprecated( __METHOD__
, '1.25' );
2690 throw new ThrottledError
;
2694 * Show a warning about replica DB lag
2696 * If the lag is higher than $wgSlaveLagCritical seconds,
2697 * then the warning is a bit more obvious. If the lag is
2698 * lower than $wgSlaveLagWarning, then no warning is shown.
2700 * @param int $lag Slave lag
2702 public function showLagWarning( $lag ) {
2703 $config = $this->getConfig();
2704 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2705 $lag = floor( $lag ); // floor to avoid nano seconds to display
2706 $message = $lag < $config->get( 'SlaveLagCritical' )
2709 $wrap = Html
::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2710 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2714 public function showFatalError( $message ) {
2715 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2717 $this->addHTML( $message );
2720 public function showUnexpectedValueError( $name, $val ) {
2721 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2724 public function showFileCopyError( $old, $new ) {
2725 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2728 public function showFileRenameError( $old, $new ) {
2729 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2732 public function showFileDeleteError( $name ) {
2733 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2736 public function showFileNotFoundError( $name ) {
2737 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2741 * Add a "return to" link pointing to a specified title
2743 * @param Title $title Title to link
2744 * @param array $query Query string parameters
2745 * @param string $text Text of the link (input is not escaped)
2746 * @param array $options Options array to pass to Linker
2748 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
2749 $linkRenderer = MediaWikiServices
::getInstance()
2750 ->getLinkRendererFactory()->createFromLegacyOptions( $options );
2751 $link = $this->msg( 'returnto' )->rawParams(
2752 $linkRenderer->makeLink( $title, $text, [], $query ) )->escaped();
2753 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2757 * Add a "return to" link pointing to a specified title,
2758 * or the title indicated in the request, or else the main page
2760 * @param mixed $unused
2761 * @param Title|string $returnto Title or String to return to
2762 * @param string $returntoquery Query string for the return to link
2764 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2765 if ( $returnto == null ) {
2766 $returnto = $this->getRequest()->getText( 'returnto' );
2769 if ( $returntoquery == null ) {
2770 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2773 if ( $returnto === '' ) {
2774 $returnto = Title
::newMainPage();
2777 if ( is_object( $returnto ) ) {
2778 $titleObj = $returnto;
2780 $titleObj = Title
::newFromText( $returnto );
2782 // We don't want people to return to external interwiki. That
2783 // might potentially be used as part of a phishing scheme
2784 if ( !is_object( $titleObj ) ||
$titleObj->isExternal() ) {
2785 $titleObj = Title
::newMainPage();
2788 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2791 private function getRlClientContext() {
2792 if ( !$this->rlClientContext
) {
2793 $query = ResourceLoader
::makeLoaderQuery(
2794 [], // modules; not relevant
2795 $this->getLanguage()->getCode(),
2796 $this->getSkin()->getSkinName(),
2797 $this->getUser()->isLoggedIn() ?
$this->getUser()->getName() : null,
2798 null, // version; not relevant
2799 ResourceLoader
::inDebugMode(),
2800 null, // only; not relevant
2801 $this->isPrintable(),
2802 $this->getRequest()->getBool( 'handheld' )
2804 $this->rlClientContext
= new ResourceLoaderContext(
2805 $this->getResourceLoader(),
2806 new FauxRequest( $query )
2809 return $this->rlClientContext
;
2813 * Call this to freeze the module queue and JS config and create a formatter.
2815 * Depending on the Skin, this may get lazy-initialised in either headElement() or
2816 * getBottomScripts(). See SkinTemplate::prepareQuickTemplate(). Calling this too early may
2817 * cause unexpected side-effects since disallowUserJs() may be called at any time to change
2818 * the module filters retroactively. Skins and extension hooks may also add modules until very
2819 * late in the request lifecycle.
2821 * @return ResourceLoaderClientHtml
2823 public function getRlClient() {
2824 if ( !$this->rlClient
) {
2825 $context = $this->getRlClientContext();
2826 $rl = $this->getResourceLoader();
2827 $this->addModules( [
2831 $this->addModuleStyles( [
2836 $this->getSkin()->setupSkinUserCss( $this );
2838 // Prepare exempt modules for buildExemptModules()
2839 $exemptGroups = [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ];
2841 $moduleStyles = $this->getModuleStyles( /*filter*/ true );
2843 // Preload getTitleInfo for isKnownEmpty calls below and in ResourceLoaderClientHtml
2844 // Separate user-specific batch for improved cache-hit ratio.
2845 $userBatch = [ 'user.styles', 'user' ];
2846 $siteBatch = array_diff( $moduleStyles, $userBatch );
2847 $dbr = wfGetDB( DB_REPLICA
);
2848 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $siteBatch );
2849 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $userBatch );
2851 // Filter out modules handled by buildExemptModules()
2852 $moduleStyles = array_filter( $moduleStyles,
2853 function ( $name ) use ( $rl, $context, &$exemptGroups, &$exemptStates ) {
2854 $module = $rl->getModule( $name );
2856 if ( $name === 'user.styles' && $this->isUserCssPreview() ) {
2857 $exemptStates[$name] = 'ready';
2858 // Special case in buildExemptModules()
2861 $group = $module->getGroup();
2862 if ( isset( $exemptGroups[$group] ) ) {
2863 $exemptStates[$name] = 'ready';
2864 if ( !$module->isKnownEmpty( $context ) ) {
2865 // E.g. Don't output empty <styles>
2866 $exemptGroups[$group][] = $name;
2874 $this->rlExemptStyleModules
= $exemptGroups;
2876 $isUserModuleFiltered = !$this->filterModules( [ 'user' ] );
2877 // If this page filters out 'user', makeResourceLoaderLink will drop it.
2878 // Avoid indefinite "loading" state or untrue "ready" state (T145368).
2879 if ( !$isUserModuleFiltered ) {
2880 // Manually handled by getBottomScripts()
2881 $userModule = $rl->getModule( 'user' );
2882 $userState = $userModule->isKnownEmpty( $context ) && !$this->isUserJsPreview()
2885 $this->rlUserModuleState
= $exemptStates['user'] = $userState;
2888 $rlClient = new ResourceLoaderClientHtml( $context, $this->getTarget() );
2889 $rlClient->setConfig( $this->getJSVars() );
2890 $rlClient->setModules( $this->getModules( /*filter*/ true ) );
2891 $rlClient->setModuleStyles( $moduleStyles );
2892 $rlClient->setModuleScripts( $this->getModuleScripts( /*filter*/ true ) );
2893 $rlClient->setExemptStates( $exemptStates );
2894 $this->rlClient
= $rlClient;
2896 return $this->rlClient
;
2900 * @param Skin $sk The given Skin
2901 * @param bool $includeStyle Unused
2902 * @return string The doctype, opening "<html>", and head element.
2904 public function headElement( Skin
$sk, $includeStyle = true ) {
2907 $userdir = $this->getLanguage()->getDir();
2908 $sitedir = $wgContLang->getDir();
2911 $pieces[] = Html
::htmlHeader( Sanitizer
::mergeAttributes(
2912 $this->getRlClient()->getDocumentAttributes(),
2913 $sk->getHtmlElementAttributes()
2915 $pieces[] = Html
::openElement( 'head' );
2917 if ( $this->getHTMLTitle() == '' ) {
2918 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2921 if ( !Html
::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2922 // Add <meta charset="UTF-8">
2923 // This should be before <title> since it defines the charset used by
2924 // text including the text inside <title>.
2925 // The spec recommends defining XHTML5's charset using the XML declaration
2927 // Our XML declaration is output by Html::htmlHeader.
2928 // https://html.spec.whatwg.org/multipage/semantics.html#attr-meta-http-equiv-content-type
2929 // https://html.spec.whatwg.org/multipage/semantics.html#charset
2930 $pieces[] = Html
::element( 'meta', [ 'charset' => 'UTF-8' ] );
2933 $pieces[] = Html
::element( 'title', null, $this->getHTMLTitle() );
2934 $pieces[] = $this->getRlClient()->getHeadHtml();
2935 $pieces[] = $this->buildExemptModules();
2936 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
2937 $pieces = array_merge( $pieces, array_values( $this->mHeadItems
) );
2939 // Use an IE conditional comment to serve the script only to old IE
2940 $pieces[] = '<!--[if lt IE 9]>' .
2941 ResourceLoaderClientHtml
::makeLoad(
2942 ResourceLoaderContext
::newDummyContext(),
2944 ResourceLoaderModule
::TYPE_SCRIPTS
,
2949 $pieces[] = Html
::closeElement( 'head' );
2951 $bodyClasses = $this->mAdditionalBodyClasses
;
2952 $bodyClasses[] = 'mediawiki';
2954 # Classes for LTR/RTL directionality support
2955 $bodyClasses[] = $userdir;
2956 $bodyClasses[] = "sitedir-$sitedir";
2958 $underline = $this->getUser()->getOption( 'underline' );
2959 if ( $underline < 2 ) {
2960 // The following classes can be used here:
2961 // * mw-underline-always
2962 // * mw-underline-never
2963 $bodyClasses[] = 'mw-underline-' . ( $underline ?
'always' : 'never' );
2966 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2967 # A <body> class is probably not the best way to do this . . .
2968 $bodyClasses[] = 'capitalize-all-nouns';
2971 // Parser feature migration class
2972 // The idea is that this will eventually be removed, after the wikitext
2973 // which requires it is cleaned up.
2974 $bodyClasses[] = 'mw-hide-empty-elt';
2976 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2977 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2979 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2982 // While the implode() is not strictly needed, it's used for backwards compatibility
2983 // (this used to be built as a string and hooks likely still expect that).
2984 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2986 // Allow skins and extensions to add body attributes they need
2987 $sk->addToBodyAttributes( $this, $bodyAttrs );
2988 Hooks
::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
2990 $pieces[] = Html
::openElement( 'body', $bodyAttrs );
2992 return self
::combineWrappedStrings( $pieces );
2996 * Get a ResourceLoader object associated with this OutputPage
2998 * @return ResourceLoader
3000 public function getResourceLoader() {
3001 if ( is_null( $this->mResourceLoader
) ) {
3002 $this->mResourceLoader
= new ResourceLoader(
3004 LoggerFactory
::getInstance( 'resourceloader' )
3007 return $this->mResourceLoader
;
3011 * Explicily load or embed modules on a page.
3013 * @param array|string $modules One or more module names
3014 * @param string $only ResourceLoaderModule TYPE_ class constant
3015 * @param array $extraQuery [optional] Array with extra query parameters for the request
3016 * @return string|WrappedStringList HTML
3018 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
3019 // Apply 'target' and 'origin' filters
3020 $modules = $this->filterModules( (array)$modules, null, $only );
3022 return ResourceLoaderClientHtml
::makeLoad(
3023 $this->getRlClientContext(),
3031 * Combine WrappedString chunks and filter out empty ones
3033 * @param array $chunks
3034 * @return string|WrappedStringList HTML
3036 protected static function combineWrappedStrings( array $chunks ) {
3037 // Filter out empty values
3038 $chunks = array_filter( $chunks, 'strlen' );
3039 return WrappedString
::join( "\n", $chunks );
3042 private function isUserJsPreview() {
3043 return $this->getConfig()->get( 'AllowUserJs' )
3044 && $this->getTitle()
3045 && $this->getTitle()->isJsSubpage()
3046 && $this->userCanPreview();
3049 protected function isUserCssPreview() {
3050 return $this->getConfig()->get( 'AllowUserCss' )
3051 && $this->getTitle()
3052 && $this->getTitle()->isCssSubpage()
3053 && $this->userCanPreview();
3057 * JS stuff to put at the bottom of the `<body>`. These are modules with position 'bottom',
3058 * legacy scripts ($this->mScripts), and user JS.
3060 * @return string|WrappedStringList HTML
3062 public function getBottomScripts() {
3064 $chunks[] = $this->getRlClient()->getBodyHtml();
3066 // Legacy non-ResourceLoader scripts
3067 $chunks[] = $this->mScripts
;
3069 // Exempt 'user' module
3070 // - May need excludepages for live preview. (T28283)
3071 // - Must use TYPE_COMBINED so its response is handled by mw.loader.implement() which
3072 // ensures execution is scheduled after the "site" module.
3073 // - Don't load if module state is already resolved as "ready".
3074 if ( $this->rlUserModuleState
=== 'loading' ) {
3075 if ( $this->isUserJsPreview() ) {
3076 $chunks[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_COMBINED
,
3077 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
3079 $chunks[] = ResourceLoader
::makeInlineScript(
3080 Xml
::encodeJsCall( 'mw.loader.using', [
3084 . Xml
::encodeJsCall( '$.globalEval', [
3085 $this->getRequest()->getText( 'wpTextbox1' )
3091 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
3092 // asynchronously and may arrive *after* the inline script here. So the previewed code
3093 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js.
3094 // Similarly, when previewing ./common.js and the user module does arrive first,
3095 // it will arrive without common.js and the inline script runs after.
3096 // Thus running common after the excluded subpage.
3099 $chunks[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_COMBINED
);
3103 if ( $this->limitReportJSData
) {
3104 $chunks[] = ResourceLoader
::makeInlineScript(
3105 ResourceLoader
::makeConfigSetScript(
3106 [ 'wgPageParseReport' => $this->limitReportJSData
]
3111 return self
::combineWrappedStrings( $chunks );
3115 * Get the javascript config vars to include on this page
3117 * @return array Array of javascript config vars
3120 public function getJsConfigVars() {
3121 return $this->mJsConfigVars
;
3125 * Add one or more variables to be set in mw.config in JavaScript
3127 * @param string|array $keys Key or array of key/value pairs
3128 * @param mixed $value [optional] Value of the configuration variable
3130 public function addJsConfigVars( $keys, $value = null ) {
3131 if ( is_array( $keys ) ) {
3132 foreach ( $keys as $key => $value ) {
3133 $this->mJsConfigVars
[$key] = $value;
3138 $this->mJsConfigVars
[$keys] = $value;
3142 * Get an array containing the variables to be set in mw.config in JavaScript.
3144 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3145 * - in other words, page-independent/site-wide variables (without state).
3146 * You will only be adding bloat to the html page and causing page caches to
3147 * have to be purged on configuration changes.
3150 public function getJSVars() {
3155 $canonicalSpecialPageName = false; # T23115
3157 $title = $this->getTitle();
3158 $ns = $title->getNamespace();
3159 $canonicalNamespace = MWNamespace
::exists( $ns )
3160 ? MWNamespace
::getCanonicalName( $ns )
3161 : $title->getNsText();
3163 $sk = $this->getSkin();
3164 // Get the relevant title so that AJAX features can use the correct page name
3165 // when making API requests from certain special pages (T36972).
3166 $relevantTitle = $sk->getRelevantTitle();
3167 $relevantUser = $sk->getRelevantUser();
3169 if ( $ns == NS_SPECIAL
) {
3170 list( $canonicalSpecialPageName, /*...*/ ) =
3171 SpecialPageFactory
::resolveAlias( $title->getDBkey() );
3172 } elseif ( $this->canUseWikiPage() ) {
3173 $wikiPage = $this->getWikiPage();
3174 $curRevisionId = $wikiPage->getLatest();
3175 $articleId = $wikiPage->getId();
3178 $lang = $title->getPageViewLanguage();
3180 // Pre-process information
3181 $separatorTransTable = $lang->separatorTransformTable();
3182 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : [];
3183 $compactSeparatorTransTable = [
3184 implode( "\t", array_keys( $separatorTransTable ) ),
3185 implode( "\t", $separatorTransTable ),
3187 $digitTransTable = $lang->digitTransformTable();
3188 $digitTransTable = $digitTransTable ?
$digitTransTable : [];
3189 $compactDigitTransTable = [
3190 implode( "\t", array_keys( $digitTransTable ) ),
3191 implode( "\t", $digitTransTable ),
3194 $user = $this->getUser();
3197 'wgCanonicalNamespace' => $canonicalNamespace,
3198 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3199 'wgNamespaceNumber' => $title->getNamespace(),
3200 'wgPageName' => $title->getPrefixedDBkey(),
3201 'wgTitle' => $title->getText(),
3202 'wgCurRevisionId' => $curRevisionId,
3203 'wgRevisionId' => (int)$this->getRevisionId(),
3204 'wgArticleId' => $articleId,
3205 'wgIsArticle' => $this->isArticle(),
3206 'wgIsRedirect' => $title->isRedirect(),
3207 'wgAction' => Action
::getActionName( $this->getContext() ),
3208 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3209 'wgUserGroups' => $user->getEffectiveGroups(),
3210 'wgCategories' => $this->getCategories(),
3211 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3212 'wgPageContentLanguage' => $lang->getCode(),
3213 'wgPageContentModel' => $title->getContentModel(),
3214 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3215 'wgDigitTransformTable' => $compactDigitTransTable,
3216 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3217 'wgMonthNames' => $lang->getMonthNamesArray(),
3218 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3219 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3220 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3221 'wgRequestId' => WebRequest
::getRequestId(),
3224 if ( $user->isLoggedIn() ) {
3225 $vars['wgUserId'] = $user->getId();
3226 $vars['wgUserEditCount'] = $user->getEditCount();
3227 $userReg = $user->getRegistration();
3228 $vars['wgUserRegistration'] = $userReg ?
wfTimestamp( TS_UNIX
, $userReg ) * 1000 : null;
3229 // Get the revision ID of the oldest new message on the user's talk
3230 // page. This can be used for constructing new message alerts on
3232 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3235 if ( $wgContLang->hasVariants() ) {
3236 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3238 // Same test as SkinTemplate
3239 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3240 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3242 $vars['wgRelevantPageIsProbablyEditable'] = $relevantTitle
3243 && $relevantTitle->quickUserCan( 'edit', $user )
3244 && ( $relevantTitle->exists() ||
$relevantTitle->quickUserCan( 'create', $user ) );
3246 foreach ( $title->getRestrictionTypes() as $type ) {
3247 // Following keys are set in $vars:
3248 // wgRestrictionCreate, wgRestrictionEdit, wgRestrictionMove, wgRestrictionUpload
3249 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3252 if ( $title->isMainPage() ) {
3253 $vars['wgIsMainPage'] = true;
3256 if ( $this->mRedirectedFrom
) {
3257 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3260 if ( $relevantUser ) {
3261 $vars['wgRelevantUserName'] = $relevantUser->getName();
3264 // Allow extensions to add their custom variables to the mw.config map.
3265 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3266 // page-dependant but site-wide (without state).
3267 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3268 Hooks
::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3270 // Merge in variables from addJsConfigVars last
3271 return array_merge( $vars, $this->getJsConfigVars() );
3275 * To make it harder for someone to slip a user a fake
3276 * user-JavaScript or user-CSS preview, a random token
3277 * is associated with the login session. If it's not
3278 * passed back with the preview request, we won't render
3283 public function userCanPreview() {
3284 $request = $this->getRequest();
3286 $request->getVal( 'action' ) !== 'submit' ||
3287 !$request->getCheck( 'wpPreview' ) ||
3288 !$request->wasPosted()
3293 $user = $this->getUser();
3295 if ( !$user->isLoggedIn() ) {
3296 // Anons have predictable edit tokens
3299 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3303 $title = $this->getTitle();
3304 if ( !$title->isJsSubpage() && !$title->isCssSubpage() ) {
3307 if ( !$title->isSubpageOf( $user->getUserPage() ) ) {
3308 // Don't execute another user's CSS or JS on preview (T85855)
3312 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3313 if ( count( $errors ) !== 0 ) {
3321 * @return array Array in format "link name or number => 'link html'".
3323 public function getHeadLinksArray() {
3327 $config = $this->getConfig();
3329 $canonicalUrl = $this->mCanonicalUrl
;
3331 $tags['meta-generator'] = Html
::element( 'meta', [
3332 'name' => 'generator',
3333 'content' => "MediaWiki $wgVersion",
3336 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3337 // Per https://w3c.github.io/webappsec-referrer-policy/#unknown-policy-values
3338 // fallbacks should come before the primary value so we need to reverse the array.
3339 foreach ( array_reverse( (array)$config->get( 'ReferrerPolicy' ) ) as $i => $policy ) {
3340 $tags["meta-referrer-$i"] = Html
::element( 'meta', [
3341 'name' => 'referrer',
3342 'content' => $policy,
3347 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3348 if ( $p !== 'index,follow' ) {
3349 // http://www.robotstxt.org/wc/meta-user.html
3350 // Only show if it's different from the default robots policy
3351 $tags['meta-robots'] = Html
::element( 'meta', [
3357 foreach ( $this->mMetatags
as $tag ) {
3358 if ( strncasecmp( $tag[0], 'http:', 5 ) === 0 ) {
3360 $tag[0] = substr( $tag[0], 5 );
3361 } elseif ( strncasecmp( $tag[0], 'og:', 3 ) === 0 ) {
3366 $tagName = "meta-{$tag[0]}";
3367 if ( isset( $tags[$tagName] ) ) {
3368 $tagName .= $tag[1];
3370 $tags[$tagName] = Html
::element( 'meta',
3373 'content' => $tag[1]
3378 foreach ( $this->mLinktags
as $tag ) {
3379 $tags[] = Html
::element( 'link', $tag );
3382 # Universal edit button
3383 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3384 $user = $this->getUser();
3385 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3386 && ( $this->getTitle()->exists() ||
3387 $this->getTitle()->quickUserCan( 'create', $user ) )
3389 // Original UniversalEditButton
3390 $msg = $this->msg( 'edit' )->text();
3391 $tags['universal-edit-button'] = Html
::element( 'link', [
3392 'rel' => 'alternate',
3393 'type' => 'application/x-wiki',
3395 'href' => $this->getTitle()->getEditURL(),
3397 // Alternate edit link
3398 $tags['alternative-edit'] = Html
::element( 'link', [
3401 'href' => $this->getTitle()->getEditURL(),
3406 # Generally the order of the favicon and apple-touch-icon links
3407 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3408 # uses whichever one appears later in the HTML source. Make sure
3409 # apple-touch-icon is specified first to avoid this.
3410 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3411 $tags['apple-touch-icon'] = Html
::element( 'link', [
3412 'rel' => 'apple-touch-icon',
3413 'href' => $config->get( 'AppleTouchIcon' )
3417 if ( $config->get( 'Favicon' ) !== false ) {
3418 $tags['favicon'] = Html
::element( 'link', [
3419 'rel' => 'shortcut icon',
3420 'href' => $config->get( 'Favicon' )
3424 # OpenSearch description link
3425 $tags['opensearch'] = Html
::element( 'link', [
3427 'type' => 'application/opensearchdescription+xml',
3428 'href' => wfScript( 'opensearch_desc' ),
3429 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3432 if ( $config->get( 'EnableAPI' ) ) {
3433 # Real Simple Discovery link, provides auto-discovery information
3434 # for the MediaWiki API (and potentially additional custom API
3435 # support such as WordPress or Twitter-compatible APIs for a
3436 # blogging extension, etc)
3437 $tags['rsd'] = Html
::element( 'link', [
3439 'type' => 'application/rsd+xml',
3440 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3441 // Whether RSD accepts relative or protocol-relative URLs is completely
3442 // undocumented, though.
3443 'href' => wfExpandUrl( wfAppendQuery(
3445 [ 'action' => 'rsd' ] ),
3452 if ( !$config->get( 'DisableLangConversion' ) ) {
3453 $lang = $this->getTitle()->getPageLanguage();
3454 if ( $lang->hasVariants() ) {
3455 $variants = $lang->getVariants();
3456 foreach ( $variants as $variant ) {
3457 $tags["variant-$variant"] = Html
::element( 'link', [
3458 'rel' => 'alternate',
3459 'hreflang' => LanguageCode
::bcp47( $variant ),
3460 'href' => $this->getTitle()->getLocalURL(
3461 [ 'variant' => $variant ] )
3465 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3466 $tags["variant-x-default"] = Html
::element( 'link', [
3467 'rel' => 'alternate',
3468 'hreflang' => 'x-default',
3469 'href' => $this->getTitle()->getLocalURL() ] );
3474 if ( $this->copyrightUrl
!== null ) {
3475 $copyright = $this->copyrightUrl
;
3478 if ( $config->get( 'RightsPage' ) ) {
3479 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3482 $copyright = $copy->getLocalURL();
3486 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3487 $copyright = $config->get( 'RightsUrl' );
3492 $tags['copyright'] = Html
::element( 'link', [
3494 'href' => $copyright ]
3499 if ( $config->get( 'Feed' ) ) {
3502 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3503 # Use the page name for the title. In principle, this could
3504 # lead to issues with having the same name for different feeds
3505 # corresponding to the same page, but we can't avoid that at
3508 $feedLinks[] = $this->feedLink(
3511 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3513 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3518 # Recent changes feed should appear on every page (except recentchanges,
3519 # that would be redundant). Put it after the per-page feed to avoid
3520 # changing existing behavior. It's still available, probably via a
3521 # menu in your browser. Some sites might have a different feed they'd
3522 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3523 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3524 # If so, use it instead.
3525 $sitename = $config->get( 'Sitename' );
3526 if ( $config->get( 'OverrideSiteFeed' ) ) {
3527 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3528 // Note, this->feedLink escapes the url.
3529 $feedLinks[] = $this->feedLink(
3532 $this->msg( "site-{$type}-feed", $sitename )->text()
3535 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3536 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3537 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3538 $feedLinks[] = $this->feedLink(
3540 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3541 # For grep: 'site-rss-feed', 'site-atom-feed'
3542 $this->msg( "site-{$format}-feed", $sitename )->text()
3547 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3548 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3549 # use OutputPage::addFeedLink() instead.
3550 Hooks
::run( 'AfterBuildFeedLinks', [ &$feedLinks ] );
3552 $tags +
= $feedLinks;
3556 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3557 if ( $canonicalUrl !== false ) {
3558 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3560 if ( $this->isArticleRelated() ) {
3561 // This affects all requests where "setArticleRelated" is true. This is
3562 // typically all requests that show content (query title, curid, oldid, diff),
3563 // and all wikipage actions (edit, delete, purge, info, history etc.).
3564 // It does not apply to File pages and Special pages.
3565 // 'history' and 'info' actions address page metadata rather than the page
3566 // content itself, so they may not be canonicalized to the view page url.
3567 // TODO: this ought to be better encapsulated in the Action class.
3568 $action = Action
::getActionName( $this->getContext() );
3569 if ( in_array( $action, [ 'history', 'info' ] ) ) {
3570 $query = "action={$action}";
3574 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3576 $reqUrl = $this->getRequest()->getRequestURL();
3577 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3581 if ( $canonicalUrl !== false ) {
3582 $tags[] = Html
::element( 'link', [
3583 'rel' => 'canonical',
3584 'href' => $canonicalUrl
3592 * Generate a "<link rel/>" for a feed.
3594 * @param string $type Feed type
3595 * @param string $url URL to the feed
3596 * @param string $text Value of the "title" attribute
3597 * @return string HTML fragment
3599 private function feedLink( $type, $url, $text ) {
3600 return Html
::element( 'link', [
3601 'rel' => 'alternate',
3602 'type' => "application/$type+xml",
3609 * Add a local or specified stylesheet, with the given media options.
3610 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3612 * @param string $style URL to the file
3613 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3614 * @param string $condition For IE conditional comments, specifying an IE version
3615 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3617 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3620 $options['media'] = $media;
3623 $options['condition'] = $condition;
3626 $options['dir'] = $dir;
3628 $this->styles
[$style] = $options;
3632 * Adds inline CSS styles
3633 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3635 * @param mixed $style_css Inline CSS
3636 * @param string $flip Set to 'flip' to flip the CSS if needed
3638 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3639 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3640 # If wanted, and the interface is right-to-left, flip the CSS
3641 $style_css = CSSJanus
::transform( $style_css, true, false );
3643 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3647 * Build exempt modules and legacy non-ResourceLoader styles.
3649 * @return string|WrappedStringList HTML
3651 protected function buildExemptModules() {
3655 // Things that go after the ResourceLoaderDynamicStyles marker
3658 // Exempt 'user' styles module (may need 'excludepages' for live preview)
3659 if ( $this->isUserCssPreview() ) {
3660 $append[] = $this->makeResourceLoaderLink(
3662 ResourceLoaderModule
::TYPE_STYLES
,
3663 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
3666 // Load the previewed CSS. Janus it if needed.
3667 // User-supplied CSS is assumed to in the wiki's content language.
3668 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3669 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3670 $previewedCSS = CSSJanus
::transform( $previewedCSS, true, false );
3672 $append[] = Html
::inlineStyle( $previewedCSS );
3675 // We want site, private and user styles to override dynamically added styles from
3676 // general modules, but we want dynamically added styles to override statically added
3677 // style modules. So the order has to be:
3678 // - page style modules (formatted by ResourceLoaderClientHtml::getHeadHtml())
3679 // - dynamically loaded styles (added by mw.loader before ResourceLoaderDynamicStyles)
3680 // - ResourceLoaderDynamicStyles marker
3681 // - site/private/user styles
3683 // Add legacy styles added through addStyle()/addInlineStyle() here
3684 $chunks[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3686 $chunks[] = Html
::element(
3688 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
3691 $separateReq = [ 'site.styles', 'user.styles' ];
3692 foreach ( $this->rlExemptStyleModules
as $group => $moduleNames ) {
3693 // Combinable modules
3694 $chunks[] = $this->makeResourceLoaderLink(
3695 array_diff( $moduleNames, $separateReq ),
3696 ResourceLoaderModule
::TYPE_STYLES
3699 foreach ( array_intersect( $moduleNames, $separateReq ) as $name ) {
3700 // These require their own dedicated request in order to support "@import"
3701 // syntax, which is incompatible with concatenation. (T147667, T37562)
3702 $chunks[] = $this->makeResourceLoaderLink( $name,
3703 ResourceLoaderModule
::TYPE_STYLES
3708 return self
::combineWrappedStrings( array_merge( $chunks, $append ) );
3714 public function buildCssLinksArray() {
3717 // Add any extension CSS
3718 foreach ( $this->mExtStyles
as $url ) {
3719 $this->addStyle( $url );
3721 $this->mExtStyles
= [];
3723 foreach ( $this->styles
as $file => $options ) {
3724 $link = $this->styleLink( $file, $options );
3726 $links[$file] = $link;
3733 * Generate \<link\> tags for stylesheets
3735 * @param string $style URL to the file
3736 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3737 * @return string HTML fragment
3739 protected function styleLink( $style, array $options ) {
3740 if ( isset( $options['dir'] ) ) {
3741 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3746 if ( isset( $options['media'] ) ) {
3747 $media = self
::transformCssMedia( $options['media'] );
3748 if ( is_null( $media ) ) {
3755 if ( substr( $style, 0, 1 ) == '/' ||
3756 substr( $style, 0, 5 ) == 'http:' ||
3757 substr( $style, 0, 6 ) == 'https:' ) {
3760 $config = $this->getConfig();
3761 $url = $config->get( 'StylePath' ) . '/' . $style . '?' .
3762 $config->get( 'StyleVersion' );
3765 $link = Html
::linkedStyle( $url, $media );
3767 if ( isset( $options['condition'] ) ) {
3768 $condition = htmlspecialchars( $options['condition'] );
3769 $link = "<!--[if $condition]>$link<![endif]-->";
3775 * Transform path to web-accessible static resource.
3777 * This is used to add a validation hash as query string.
3778 * This aids various behaviors:
3780 * - Put long Cache-Control max-age headers on responses for improved
3781 * cache performance.
3782 * - Get the correct version of a file as expected by the current page.
3783 * - Instantly get the updated version of a file after deployment.
3785 * Avoid using this for urls included in HTML as otherwise clients may get different
3786 * versions of a resource when navigating the site depending on when the page was cached.
3787 * If changes to the url propagate, this is not a problem (e.g. if the url is in
3788 * an external stylesheet).
3791 * @param Config $config
3792 * @param string $path Path-absolute URL to file (from document root, must start with "/")
3793 * @return string URL
3795 public static function transformResourcePath( Config
$config, $path ) {
3799 $remotePathPrefix = $config->get( 'ResourceBasePath' );
3800 if ( $remotePathPrefix === '' ) {
3801 // The configured base path is required to be empty string for
3802 // wikis in the domain root
3805 $remotePath = $remotePathPrefix;
3807 if ( strpos( $path, $remotePath ) !== 0 ||
substr( $path, 0, 2 ) === '//' ) {
3808 // - Path is outside wgResourceBasePath, ignore.
3809 // - Path is protocol-relative. Fixes T155310. Not supported by RelPath lib.
3812 // For files in resources, extensions/ or skins/, ResourceBasePath is preferred here.
3813 // For other misc files in $IP, we'll fallback to that as well. There is, however, a fourth
3814 // supported dir/path pair in the configuration (wgUploadDirectory, wgUploadPath)
3815 // which is not expected to be in wgResourceBasePath on CDNs. (T155146)
3816 $uploadPath = $config->get( 'UploadPath' );
3817 if ( strpos( $path, $uploadPath ) === 0 ) {
3818 $localDir = $config->get( 'UploadDirectory' );
3819 $remotePathPrefix = $remotePath = $uploadPath;
3822 $path = RelPath
::getRelativePath( $path, $remotePath );
3823 return self
::transformFilePath( $remotePathPrefix, $localDir, $path );
3827 * Utility method for transformResourceFilePath().
3829 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
3832 * @param string $remotePathPrefix URL path prefix that points to $localPath
3833 * @param string $localPath File directory exposed at $remotePath
3834 * @param string $file Path to target file relative to $localPath
3835 * @return string URL
3837 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
3838 $hash = md5_file( "$localPath/$file" );
3839 if ( $hash === false ) {
3840 wfLogWarning( __METHOD__
. ": Failed to hash $localPath/$file" );
3843 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
3847 * Transform "media" attribute based on request parameters
3849 * @param string $media Current value of the "media" attribute
3850 * @return string Modified value of the "media" attribute, or null to skip
3853 public static function transformCssMedia( $media ) {
3856 // https://www.w3.org/TR/css3-mediaqueries/#syntax
3857 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3859 // Switch in on-screen display for media testing
3861 'printable' => 'print',
3862 'handheld' => 'handheld',
3864 foreach ( $switches as $switch => $targetMedia ) {
3865 if ( $wgRequest->getBool( $switch ) ) {
3866 if ( $media == $targetMedia ) {
3868 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3869 /* This regex will not attempt to understand a comma-separated media_query_list
3871 * Example supported values for $media:
3872 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3873 * Example NOT supported value for $media:
3874 * '3d-glasses, screen, print and resolution > 90dpi'
3876 * If it's a print request, we never want any kind of screen stylesheets
3877 * If it's a handheld request (currently the only other choice with a switch),
3878 * we don't want simple 'screen' but we might want screen queries that
3879 * have a max-width or something, so we'll pass all others on and let the
3880 * client do the query.
3882 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3893 * Add a wikitext-formatted message to the output.
3894 * This is equivalent to:
3896 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3898 public function addWikiMsg( /*...*/ ) {
3899 $args = func_get_args();
3900 $name = array_shift( $args );
3901 $this->addWikiMsgArray( $name, $args );
3905 * Add a wikitext-formatted message to the output.
3906 * Like addWikiMsg() except the parameters are taken as an array
3907 * instead of a variable argument list.
3909 * @param string $name
3910 * @param array $args
3912 public function addWikiMsgArray( $name, $args ) {
3913 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3917 * This function takes a number of message/argument specifications, wraps them in
3918 * some overall structure, and then parses the result and adds it to the output.
3920 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3921 * and so on. The subsequent arguments may be either
3922 * 1) strings, in which case they are message names, or
3923 * 2) arrays, in which case, within each array, the first element is the message
3924 * name, and subsequent elements are the parameters to that message.
3926 * Don't use this for messages that are not in the user's interface language.
3930 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3934 * $wgOut->addWikiText( "<div class='error'>\n"
3935 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3937 * The newline after the opening div is needed in some wikitext. See T21226.
3939 * @param string $wrap
3941 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3942 $msgSpecs = func_get_args();
3943 array_shift( $msgSpecs );
3944 $msgSpecs = array_values( $msgSpecs );
3946 foreach ( $msgSpecs as $n => $spec ) {
3947 if ( is_array( $spec ) ) {
3949 $name = array_shift( $args );
3950 if ( isset( $args['options'] ) ) {
3951 unset( $args['options'] );
3953 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3961 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3963 $this->addWikiText( $s );
3967 * Whether the output has a table of contents
3971 public function isTOCEnabled() {
3972 return $this->mEnableTOC
;
3976 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3979 * @deprecated since 1.31, use $poOptions to addParserOutput() instead.
3981 public function enableSectionEditLinks( $flag = true ) {
3982 $this->mEnableSectionEditLinks
= $flag;
3988 * @deprecated since 1.31, use $poOptions to addParserOutput() instead.
3990 public function sectionEditLinksEnabled() {
3991 return $this->mEnableSectionEditLinks
;
3995 * Helper function to setup the PHP implementation of OOUI to use in this request.
3998 * @param String $skinName The Skin name to determine the correct OOUI theme
3999 * @param String $dir Language direction
4001 public static function setupOOUI( $skinName = 'default', $dir = 'ltr' ) {
4002 $themes = ResourceLoaderOOUIModule
::getSkinThemeMap();
4003 $theme = isset( $themes[$skinName] ) ?
$themes[$skinName] : $themes['default'];
4004 // For example, 'OOUI\WikimediaUITheme'.
4005 $themeClass = "OOUI\\{$theme}Theme";
4006 OOUI\Theme
::setSingleton( new $themeClass() );
4007 OOUI\Element
::setDefaultDir( $dir );
4011 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
4012 * MediaWiki and this OutputPage instance.
4016 public function enableOOUI() {
4018 strtolower( $this->getSkin()->getSkinName() ),
4019 $this->getLanguage()->getDir()
4021 $this->addModuleStyles( [
4022 'oojs-ui-core.styles',
4023 'oojs-ui.styles.indicators',
4024 'oojs-ui.styles.textures',
4025 'mediawiki.widgets.styles',
4026 'oojs-ui.styles.icons-content',
4027 'oojs-ui.styles.icons-alerts',
4028 'oojs-ui.styles.icons-interactions',
4033 * Add Link headers for preloading the wiki's logo.
4037 protected function addLogoPreloadLinkHeaders() {
4038 $logo = ResourceLoaderSkinModule
::getLogo( $this->getConfig() );
4044 if ( !is_array( $logo ) ) {
4045 // No media queries required if we only have one variant
4046 $this->addLinkHeader( '<' . $logo . '>;rel=preload;as=image' );
4050 if ( isset( $logo['svg'] ) ) {
4051 // No media queries required if we only have a 1x and svg variant
4052 // because all preload-capable browsers support SVGs
4053 $this->addLinkHeader( '<' . $logo['svg'] . '>;rel=preload;as=image' );
4057 foreach ( $logo as $dppx => $src ) {
4058 // Keys are in this format: "1.5x"
4059 $dppx = substr( $dppx, 0, -1 );
4060 $logosPerDppx[$dppx] = $src;
4063 // Because PHP can't have floats as array keys
4064 uksort( $logosPerDppx, function ( $a , $b ) {
4065 $a = floatval( $a );
4066 $b = floatval( $b );
4071 // Sort from smallest to largest (e.g. 1x, 1.5x, 2x)
4072 return ( $a < $b ) ?
-1 : 1;
4075 foreach ( $logosPerDppx as $dppx => $src ) {
4076 $logos[] = [ 'dppx' => $dppx, 'src' => $src ];
4079 $logosCount = count( $logos );
4080 // Logic must match ResourceLoaderSkinModule:
4081 // - 1x applies to resolution < 1.5dppx
4082 // - 1.5x applies to resolution >= 1.5dppx && < 2dppx
4083 // - 2x applies to resolution >= 2dppx
4084 // Note that min-resolution and max-resolution are both inclusive.
4085 for ( $i = 0; $i < $logosCount; $i++
) {
4088 // min-resolution is ">=" (larger than or equal to)
4089 // "not min-resolution" is essentially "<"
4090 $media_query = 'not all and (min-resolution: ' . $logos[ 1 ]['dppx'] . 'dppx)';
4091 } elseif ( $i !== $logosCount - 1 ) {
4093 // Media query expressions can only apply "not" to the entire expression
4094 // (e.g. can't express ">= 1.5 and not >= 2).
4095 // Workaround: Use <= 1.9999 in place of < 2.
4096 $upper_bound = floatval( $logos[ $i +
1 ]['dppx'] ) - 0.000001;
4097 $media_query = '(min-resolution: ' . $logos[ $i ]['dppx'] .
4098 'dppx) and (max-resolution: ' . $upper_bound . 'dppx)';
4101 $media_query = '(min-resolution: ' . $logos[ $i ]['dppx'] . 'dppx)';
4104 $this->addLinkHeader(
4105 '<' . $logos[$i]['src'] . '>;rel=preload;as=image;media=' . $media_query