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 string Should be private - has getter and setter. Contains
58 public $mPagetitle = '';
61 * @var string Contains all of the "<body>" content. Should be private we
62 * got set/get accessors and the append() method.
64 public $mBodytext = '';
66 /** @var string Stores contents of "<title>" tag */
67 private $mHTMLtitle = '';
70 * @var bool Is the displayed content related to the source of the
71 * corresponding wiki article.
73 private $mIsarticle = false;
75 /** @var bool Stores "article flag" toggle. */
76 private $mIsArticleRelated = true;
79 * @var bool We have to set isPrintable(). Some pages should
80 * never be printed (ex: redirections).
82 private $mPrintable = false;
85 * @var array Contains the page subtitle. Special pages usually have some
86 * links here. Don't confuse with site subtitle added by skins.
88 private $mSubtitle = [];
91 public $mRedirect = '';
94 protected $mStatusCode;
97 * @var string Used for sending cache control.
98 * The whole caching system should probably be moved into its own class.
100 protected $mLastModified = '';
103 protected $mCategoryLinks = [];
106 protected $mCategories = [
112 protected $mIndicators = [];
114 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
115 private $mLanguageLinks = [];
118 * Used for JavaScript (predates ResourceLoader)
119 * @todo We should split JS / CSS.
120 * mScripts content is inserted as is in "<head>" by Skin. This might
121 * contain either a link to a stylesheet or inline CSS.
123 private $mScripts = '';
125 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
126 protected $mInlineStyles = '';
129 * @var string Used by skin template.
130 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
132 public $mPageLinkTitle = '';
134 /** @var array Array of elements in "<head>". Parser might add its own headers! */
135 protected $mHeadItems = [];
137 /** @var array Additional <body> classes; there are also <body> classes from other sources */
138 protected $mAdditionalBodyClasses = [];
141 protected $mModules = [];
144 protected $mModuleScripts = [];
147 protected $mModuleStyles = [];
149 /** @var ResourceLoader */
150 protected $mResourceLoader;
152 /** @var ResourceLoaderClientHtml */
155 /** @var ResourceLoaderContext */
156 private $rlClientContext;
159 private $rlUserModuleState;
162 private $rlExemptStyleModules;
165 protected $mJsConfigVars = [];
168 protected $mTemplateIds = [];
171 protected $mImageTimeKeys = [];
174 public $mRedirectCode = '';
176 protected $mFeedLinksAppendQuery = null;
179 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
180 * @see ResourceLoaderModule::$origin
181 * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
183 protected $mAllowedModules = [
184 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
187 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
188 protected $mDoNothing = false;
193 protected $mContainsNewMagic = 0;
196 * lazy initialised, use parserOptions()
199 protected $mParserOptions = null;
202 * Handles the Atom / RSS links.
203 * We probably only support Atom in 2011.
204 * @see $wgAdvertisedFeedTypes
206 private $mFeedLinks = [];
208 // Gwicke work on squid caching? Roughly from 2003.
209 protected $mEnableClientCache = true;
211 /** @var bool Flag if output should only contain the body of the article. */
212 private $mArticleBodyOnly = false;
215 protected $mNewSectionLink = false;
218 protected $mHideNewSectionLink = false;
221 * @var bool Comes from the parser. This was probably made to load CSS/JS
222 * only if we had "<gallery>". Used directly in CategoryPage.php.
223 * Looks like ResourceLoader can replace this.
225 public $mNoGallery = false;
228 private $mPageTitleActionText = '';
230 /** @var int Cache stuff. Looks like mEnableClientCache */
231 protected $mCdnMaxage = 0;
232 /** @var int Upper limit on mCdnMaxage */
233 protected $mCdnMaxageLimit = INF
;
236 * @var bool Controls if anti-clickjacking / frame-breaking headers will
237 * be sent. This should be done for pages where edit actions are possible.
238 * Setters: $this->preventClickjacking() and $this->allowClickjacking().
240 protected $mPreventClickjacking = true;
242 /** @var int To include the variable {{REVISIONID}} */
243 private $mRevisionId = null;
246 private $mRevisionTimestamp = null;
249 protected $mFileVersion = null;
252 * @var array An array of stylesheet filenames (relative from skins path),
253 * with options for CSS media, IE conditions, and RTL/LTR direction.
254 * For internal use; add settings in the skin via $this->addStyle()
256 * Style again! This seems like a code duplication since we already have
257 * mStyles. This is what makes Open Source amazing.
259 protected $styles = [];
261 private $mIndexPolicy = 'index';
262 private $mFollowPolicy = 'follow';
263 private $mVaryHeader = [
264 'Accept-Encoding' => [ 'match=gzip' ],
268 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
273 private $mRedirectedFrom = null;
276 * Additional key => value data
278 private $mProperties = [];
281 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
283 private $mTarget = null;
286 * @var bool Whether parser output contains a table of contents
288 private $mEnableTOC = false;
291 * @var string|null The URL to send in a <link> element with rel=license
293 private $copyrightUrl;
295 /** @var array Profiling data */
296 private $limitReportJSData = [];
299 * Link: header contents
301 private $mLinkHeader = [];
304 * Constructor for OutputPage. This should not be called directly.
305 * Instead a new RequestContext should be created and it will implicitly create
306 * a OutputPage tied to that context.
307 * @param IContextSource $context
309 function __construct( IContextSource
$context ) {
310 $this->setContext( $context );
314 * Redirect to $url rather than displaying the normal page
317 * @param string $responsecode HTTP status code
319 public function redirect( $url, $responsecode = '302' ) {
320 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
321 $this->mRedirect
= str_replace( "\n", '', $url );
322 $this->mRedirectCode
= $responsecode;
326 * Get the URL to redirect to, or an empty string if not redirect URL set
330 public function getRedirect() {
331 return $this->mRedirect
;
335 * Set the copyright URL to send with the output.
336 * Empty string to omit, null to reset.
340 * @param string|null $url
342 public function setCopyrightUrl( $url ) {
343 $this->copyrightUrl
= $url;
347 * Set the HTTP status code to send with the output.
349 * @param int $statusCode
351 public function setStatusCode( $statusCode ) {
352 $this->mStatusCode
= $statusCode;
356 * Add a new "<meta>" tag
357 * To add an http-equiv meta tag, precede the name with "http:"
359 * @param string $name Name of the meta tag
360 * @param string $val Value of the meta tag
362 function addMeta( $name, $val ) {
363 array_push( $this->mMetatags
, [ $name, $val ] );
367 * Returns the current <meta> tags
372 public function getMetaTags() {
373 return $this->mMetatags
;
377 * Add a new \<link\> tag to the page header.
379 * Note: use setCanonicalUrl() for rel=canonical.
381 * @param array $linkarr Associative array of attributes.
383 function addLink( array $linkarr ) {
384 array_push( $this->mLinktags
, $linkarr );
388 * Returns the current <link> tags
393 public function getLinkTags() {
394 return $this->mLinktags
;
398 * Add a new \<link\> with "rel" attribute set to "meta"
400 * @param array $linkarr Associative array mapping attribute names to their
401 * values, both keys and values will be escaped, and the
402 * "rel" attribute will be automatically added
404 function addMetadataLink( array $linkarr ) {
405 $linkarr['rel'] = $this->getMetadataAttribute();
406 $this->addLink( $linkarr );
410 * Set the URL to be used for the <link rel=canonical>. This should be used
411 * in preference to addLink(), to avoid duplicate link tags.
414 function setCanonicalUrl( $url ) {
415 $this->mCanonicalUrl
= $url;
419 * Returns the URL to be used for the <link rel=canonical> if
423 * @return bool|string
425 public function getCanonicalUrl() {
426 return $this->mCanonicalUrl
;
430 * Get the value of the "rel" attribute for metadata links
434 public function getMetadataAttribute() {
435 # note: buggy CC software only reads first "meta" link
436 static $haveMeta = false;
438 return 'alternate meta';
446 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
447 * Internal use only. Use OutputPage::addModules() or OutputPage::addJsConfigVars()
450 * @param string $script Raw HTML
452 function addScript( $script ) {
453 $this->mScripts
.= $script;
457 * Add a JavaScript file out of skins/common, or a given relative path.
458 * Internal use only. Use OutputPage::addModules() if possible.
460 * @param string $file Filename in skins/common or complete on-server path
462 * @param string $version Style version of the file. Defaults to $wgStyleVersion
464 public function addScriptFile( $file, $version = null ) {
465 // See if $file parameter is an absolute URL or begins with a slash
466 if ( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
469 $path = $this->getConfig()->get( 'StylePath' ) . "/common/{$file}";
471 if ( is_null( $version ) ) {
472 $version = $this->getConfig()->get( 'StyleVersion' );
474 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
478 * Add a self-contained script tag with the given contents
479 * Internal use only. Use OutputPage::addModules() if possible.
481 * @param string $script JavaScript text, no script tags
483 public function addInlineScript( $script ) {
484 $this->mScripts
.= Html
::inlineScript( $script );
488 * Filter an array of modules to remove insufficiently trustworthy members, and modules
489 * which are no longer registered (eg a page is cached before an extension is disabled)
490 * @param array $modules
491 * @param string|null $position If not null, only return modules with this position
492 * @param string $type
495 protected function filterModules( array $modules, $position = null,
496 $type = ResourceLoaderModule
::TYPE_COMBINED
498 $resourceLoader = $this->getResourceLoader();
499 $filteredModules = [];
500 foreach ( $modules as $val ) {
501 $module = $resourceLoader->getModule( $val );
502 if ( $module instanceof ResourceLoaderModule
503 && $module->getOrigin() <= $this->getAllowedModules( $type )
504 && ( is_null( $position ) ||
$module->getPosition() == $position )
506 if ( $this->mTarget
&& !in_array( $this->mTarget
, $module->getTargets() ) ) {
507 $this->warnModuleTargetFilter( $module->getName() );
510 $filteredModules[] = $val;
513 return $filteredModules;
516 private function warnModuleTargetFilter( $moduleName ) {
517 static $warnings = [];
518 if ( isset( $warnings[$this->mTarget
][$moduleName] ) ) {
521 $warnings[$this->mTarget
][$moduleName] = true;
522 $this->getResourceLoader()->getLogger()->debug(
523 'Module "{module}" not loadable on target "{target}".',
525 'module' => $moduleName,
526 'target' => $this->mTarget
,
532 * Get the list of modules to include on this page
534 * @param bool $filter Whether to filter out insufficiently trustworthy modules
535 * @param string|null $position If not null, only return modules with this position
536 * @param string $param
537 * @param string $type
538 * @return array Array of module names
540 public function getModules( $filter = false, $position = null, $param = 'mModules',
541 $type = ResourceLoaderModule
::TYPE_COMBINED
543 $modules = array_values( array_unique( $this->$param ) );
545 ?
$this->filterModules( $modules, $position, $type )
550 * Add one or more modules recognized by ResourceLoader. Modules added
551 * through this function will be loaded by ResourceLoader when the
554 * @param string|array $modules Module name (string) or array of module names
556 public function addModules( $modules ) {
557 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
561 * Get the list of module JS to include on this page
563 * @param bool $filter
564 * @param string|null $position
565 * @return array Array of module names
567 public function getModuleScripts( $filter = false, $position = null ) {
568 return $this->getModules( $filter, $position, 'mModuleScripts',
569 ResourceLoaderModule
::TYPE_SCRIPTS
574 * Add only JS of one or more modules recognized by ResourceLoader. Module
575 * scripts added through this function will be loaded by ResourceLoader when
578 * @param string|array $modules Module name (string) or array of module names
580 public function addModuleScripts( $modules ) {
581 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
585 * Get the list of module CSS to include on this page
587 * @param bool $filter
588 * @param string|null $position
589 * @return array Array of module names
591 public function getModuleStyles( $filter = false, $position = null ) {
592 return $this->getModules( $filter, $position, 'mModuleStyles',
593 ResourceLoaderModule
::TYPE_STYLES
598 * Add only CSS of one or more modules recognized by ResourceLoader.
600 * Module styles added through this function will be added using standard link CSS
601 * tags, rather than as a combined Javascript and CSS package. Thus, they will
602 * load when JavaScript is disabled (unless CSS also happens to be disabled).
604 * @param string|array $modules Module name (string) or array of module names
606 public function addModuleStyles( $modules ) {
607 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
611 * @return null|string ResourceLoader target
613 public function getTarget() {
614 return $this->mTarget
;
618 * Sets ResourceLoader target for load.php links. If null, will be omitted
620 * @param string|null $target
622 public function setTarget( $target ) {
623 $this->mTarget
= $target;
627 * Get an array of head items
631 function getHeadItemsArray() {
632 return $this->mHeadItems
;
636 * Add or replace a head item to the output
638 * Whenever possible, use more specific options like ResourceLoader modules,
639 * OutputPage::addLink(), OutputPage::addMetaLink() and OutputPage::addFeedLink()
640 * Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
641 * OutputPage::addInlineScript() and OutputPage::addInlineStyle()
642 * This would be your very LAST fallback.
644 * @param string $name Item name
645 * @param string $value Raw HTML
647 public function addHeadItem( $name, $value ) {
648 $this->mHeadItems
[$name] = $value;
652 * Add one or more head items to the output
655 * @param string|string[] $values Raw HTML
657 public function addHeadItems( $values ) {
658 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$values );
662 * Check if the header item $name is already set
664 * @param string $name Item name
667 public function hasHeadItem( $name ) {
668 return isset( $this->mHeadItems
[$name] );
672 * Add a class to the <body> element
675 * @param string|string[] $classes One or more classes to add
677 public function addBodyClasses( $classes ) {
678 $this->mAdditionalBodyClasses
= array_merge( $this->mAdditionalBodyClasses
, (array)$classes );
682 * Set whether the output should only contain the body of the article,
683 * without any skin, sidebar, etc.
684 * Used e.g. when calling with "action=render".
686 * @param bool $only Whether to output only the body of the article
688 public function setArticleBodyOnly( $only ) {
689 $this->mArticleBodyOnly
= $only;
693 * Return whether the output will contain only the body of the article
697 public function getArticleBodyOnly() {
698 return $this->mArticleBodyOnly
;
702 * Set an additional output property
705 * @param string $name
706 * @param mixed $value
708 public function setProperty( $name, $value ) {
709 $this->mProperties
[$name] = $value;
713 * Get an additional output property
716 * @param string $name
717 * @return mixed Property value or null if not found
719 public function getProperty( $name ) {
720 if ( isset( $this->mProperties
[$name] ) ) {
721 return $this->mProperties
[$name];
728 * checkLastModified tells the client to use the client-cached page if
729 * possible. If successful, the OutputPage is disabled so that
730 * any future call to OutputPage->output() have no effect.
732 * Side effect: sets mLastModified for Last-Modified header
734 * @param string $timestamp
736 * @return bool True if cache-ok headers was sent.
738 public function checkLastModified( $timestamp ) {
739 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
740 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
743 $config = $this->getConfig();
744 if ( !$config->get( 'CachePages' ) ) {
745 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
749 $timestamp = wfTimestamp( TS_MW
, $timestamp );
751 'page' => $timestamp,
752 'user' => $this->getUser()->getTouched(),
753 'epoch' => $config->get( 'CacheEpoch' )
755 if ( $config->get( 'UseSquid' ) ) {
756 // T46570: the core page itself may not change, but resources might
757 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, time() - $config->get( 'SquidMaxage' ) );
759 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this ] );
761 $maxModified = max( $modifiedTimes );
762 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
764 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
765 if ( $clientHeader === false ) {
766 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header", 'private' );
770 # IE sends sizes after the date like this:
771 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
772 # this breaks strtotime().
773 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
775 Wikimedia\
suppressWarnings(); // E_STRICT system time bitching
776 $clientHeaderTime = strtotime( $clientHeader );
777 Wikimedia\restoreWarnings
();
778 if ( !$clientHeaderTime ) {
780 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
783 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
787 foreach ( $modifiedTimes as $name => $value ) {
788 if ( $info !== '' ) {
791 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
794 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
795 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ), 'private' );
796 wfDebug( __METHOD__
. ": effective Last-Modified: " .
797 wfTimestamp( TS_ISO_8601
, $maxModified ), 'private' );
798 if ( $clientHeaderTime < $maxModified ) {
799 wfDebug( __METHOD__
. ": STALE, $info", 'private' );
804 # Give a 304 Not Modified response code and disable body output
805 wfDebug( __METHOD__
. ": NOT MODIFIED, $info", 'private' );
806 ini_set( 'zlib.output_compression', 0 );
807 $this->getRequest()->response()->statusHeader( 304 );
808 $this->sendCacheControl();
811 // Don't output a compressed blob when using ob_gzhandler;
812 // it's technically against HTTP spec and seems to confuse
813 // Firefox when the response gets split over two packets.
814 wfClearOutputBuffers();
820 * Override the last modified timestamp
822 * @param string $timestamp New timestamp, in a format readable by
825 public function setLastModified( $timestamp ) {
826 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
830 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
832 * @param string $policy The literal string to output as the contents of
833 * the meta tag. Will be parsed according to the spec and output in
837 public function setRobotPolicy( $policy ) {
838 $policy = Article
::formatRobotPolicy( $policy );
840 if ( isset( $policy['index'] ) ) {
841 $this->setIndexPolicy( $policy['index'] );
843 if ( isset( $policy['follow'] ) ) {
844 $this->setFollowPolicy( $policy['follow'] );
849 * Set the index policy for the page, but leave the follow policy un-
852 * @param string $policy Either 'index' or 'noindex'.
855 public function setIndexPolicy( $policy ) {
856 $policy = trim( $policy );
857 if ( in_array( $policy, [ 'index', 'noindex' ] ) ) {
858 $this->mIndexPolicy
= $policy;
863 * Set the follow policy for the page, but leave the index policy un-
866 * @param string $policy Either 'follow' or 'nofollow'.
869 public function setFollowPolicy( $policy ) {
870 $policy = trim( $policy );
871 if ( in_array( $policy, [ 'follow', 'nofollow' ] ) ) {
872 $this->mFollowPolicy
= $policy;
877 * Set the new value of the "action text", this will be added to the
878 * "HTML title", separated from it with " - ".
880 * @param string $text New value of the "action text"
882 public function setPageTitleActionText( $text ) {
883 $this->mPageTitleActionText
= $text;
887 * Get the value of the "action text"
891 public function getPageTitleActionText() {
892 return $this->mPageTitleActionText
;
896 * "HTML title" means the contents of "<title>".
897 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
899 * @param string|Message $name
901 public function setHTMLTitle( $name ) {
902 if ( $name instanceof Message
) {
903 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
905 $this->mHTMLtitle
= $name;
910 * Return the "HTML title", i.e. the content of the "<title>" tag.
914 public function getHTMLTitle() {
915 return $this->mHTMLtitle
;
919 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
923 public function setRedirectedFrom( $t ) {
924 $this->mRedirectedFrom
= $t;
928 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
929 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
930 * but not bad tags like \<script\>. This function automatically sets
931 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
932 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
933 * good tags like \<i\> will be dropped entirely.
935 * @param string|Message $name
937 public function setPageTitle( $name ) {
938 if ( $name instanceof Message
) {
939 $name = $name->setContext( $this->getContext() )->text();
942 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
943 # but leave "<i>foobar</i>" alone
944 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
945 $this->mPagetitle
= $nameWithTags;
947 # change "<i>foo&bar</i>" to "foo&bar"
949 $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) )
950 ->inContentLanguage()
955 * Return the "page title", i.e. the content of the \<h1\> tag.
959 public function getPageTitle() {
960 return $this->mPagetitle
;
964 * Set the Title object to use
968 public function setTitle( Title
$t ) {
969 $this->getContext()->setTitle( $t );
973 * Replace the subtitle with $str
975 * @param string|Message $str New value of the subtitle. String should be safe HTML.
977 public function setSubtitle( $str ) {
978 $this->clearSubtitle();
979 $this->addSubtitle( $str );
983 * Add $str to the subtitle
985 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
987 public function addSubtitle( $str ) {
988 if ( $str instanceof Message
) {
989 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
991 $this->mSubtitle
[] = $str;
996 * Build message object for a subtitle containing a backlink to a page
998 * @param Title $title Title to link to
999 * @param array $query Array of additional parameters to include in the link
1003 public static function buildBacklinkSubtitle( Title
$title, $query = [] ) {
1004 if ( $title->isRedirect() ) {
1005 $query['redirect'] = 'no';
1007 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1008 return wfMessage( 'backlinksubtitle' )
1009 ->rawParams( $linkRenderer->makeLink( $title, null, [], $query ) );
1013 * Add a subtitle containing a backlink to a page
1015 * @param Title $title Title to link to
1016 * @param array $query Array of additional parameters to include in the link
1018 public function addBacklinkSubtitle( Title
$title, $query = [] ) {
1019 $this->addSubtitle( self
::buildBacklinkSubtitle( $title, $query ) );
1023 * Clear the subtitles
1025 public function clearSubtitle() {
1026 $this->mSubtitle
= [];
1034 public function getSubtitle() {
1035 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1039 * Set the page as printable, i.e. it'll be displayed with all
1040 * print styles included
1042 public function setPrintable() {
1043 $this->mPrintable
= true;
1047 * Return whether the page is "printable"
1051 public function isPrintable() {
1052 return $this->mPrintable
;
1056 * Disable output completely, i.e. calling output() will have no effect
1058 public function disable() {
1059 $this->mDoNothing
= true;
1063 * Return whether the output will be completely disabled
1067 public function isDisabled() {
1068 return $this->mDoNothing
;
1072 * Show an "add new section" link?
1076 public function showNewSectionLink() {
1077 return $this->mNewSectionLink
;
1081 * Forcibly hide the new section link?
1085 public function forceHideNewSectionLink() {
1086 return $this->mHideNewSectionLink
;
1090 * Add or remove feed links in the page header
1091 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1092 * for the new version
1093 * @see addFeedLink()
1095 * @param bool $show True: add default feeds, false: remove all feeds
1097 public function setSyndicated( $show = true ) {
1099 $this->setFeedAppendQuery( false );
1101 $this->mFeedLinks
= [];
1106 * Add default feeds to the page header
1107 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1108 * for the new version
1109 * @see addFeedLink()
1111 * @param string $val Query to append to feed links or false to output
1114 public function setFeedAppendQuery( $val ) {
1115 $this->mFeedLinks
= [];
1117 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1118 $query = "feed=$type";
1119 if ( is_string( $val ) ) {
1120 $query .= '&' . $val;
1122 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1127 * Add a feed link to the page header
1129 * @param string $format Feed type, should be a key of $wgFeedClasses
1130 * @param string $href URL
1132 public function addFeedLink( $format, $href ) {
1133 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1134 $this->mFeedLinks
[$format] = $href;
1139 * Should we output feed links for this page?
1142 public function isSyndicated() {
1143 return count( $this->mFeedLinks
) > 0;
1147 * Return URLs for each supported syndication format for this page.
1148 * @return array Associating format keys with URLs
1150 public function getSyndicationLinks() {
1151 return $this->mFeedLinks
;
1155 * Will currently always return null
1159 public function getFeedAppendQuery() {
1160 return $this->mFeedLinksAppendQuery
;
1164 * Set whether the displayed content is related to the source of the
1165 * corresponding article on the wiki
1166 * Setting true will cause the change "article related" toggle to true
1170 public function setArticleFlag( $v ) {
1171 $this->mIsarticle
= $v;
1173 $this->mIsArticleRelated
= $v;
1178 * Return whether the content displayed page is related to the source of
1179 * the corresponding article on the wiki
1183 public function isArticle() {
1184 return $this->mIsarticle
;
1188 * Set whether this page is related an article on the wiki
1189 * Setting false will cause the change of "article flag" toggle to false
1193 public function setArticleRelated( $v ) {
1194 $this->mIsArticleRelated
= $v;
1196 $this->mIsarticle
= false;
1201 * Return whether this page is related an article on the wiki
1205 public function isArticleRelated() {
1206 return $this->mIsArticleRelated
;
1210 * Add new language links
1212 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1213 * (e.g. 'fr:Test page')
1215 public function addLanguageLinks( array $newLinkArray ) {
1216 $this->mLanguageLinks +
= $newLinkArray;
1220 * Reset the language links and add new language links
1222 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1223 * (e.g. 'fr:Test page')
1225 public function setLanguageLinks( array $newLinkArray ) {
1226 $this->mLanguageLinks
= $newLinkArray;
1230 * Get the list of language links
1232 * @return string[] Array of interwiki-prefixed (non DB key) titles (e.g. 'fr:Test page')
1234 public function getLanguageLinks() {
1235 return $this->mLanguageLinks
;
1239 * Add an array of categories, with names in the keys
1241 * @param array $categories Mapping category name => sort key
1243 public function addCategoryLinks( array $categories ) {
1246 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1250 $res = $this->addCategoryLinksToLBAndGetResult( $categories );
1252 # Set all the values to 'normal'.
1253 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1255 # Mark hidden categories
1256 foreach ( $res as $row ) {
1257 if ( isset( $row->pp_value
) ) {
1258 $categories[$row->page_title
] = 'hidden';
1262 // Avoid PHP 7.1 warning of passing $this by reference
1263 $outputPage = $this;
1264 # Add the remaining categories to the skin
1266 'OutputPageMakeCategoryLinks',
1267 [ &$outputPage, $categories, &$this->mCategoryLinks
] )
1269 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1270 foreach ( $categories as $category => $type ) {
1271 // array keys will cast numeric category names to ints, so cast back to string
1272 $category = (string)$category;
1273 $origcategory = $category;
1274 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1278 $wgContLang->findVariantLink( $category, $title, true );
1279 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1282 $text = $wgContLang->convertHtml( $title->getText() );
1283 $this->mCategories
[$type][] = $title->getText();
1284 $this->mCategoryLinks
[$type][] = $linkRenderer->makeLink( $title, new HtmlArmor( $text ) );
1290 * @param array $categories
1291 * @return bool|ResultWrapper
1293 protected function addCategoryLinksToLBAndGetResult( array $categories ) {
1294 # Add the links to a LinkBatch
1295 $arr = [ NS_CATEGORY
=> $categories ];
1296 $lb = new LinkBatch
;
1297 $lb->setArray( $arr );
1299 # Fetch existence plus the hiddencat property
1300 $dbr = wfGetDB( DB_REPLICA
);
1301 $fields = array_merge(
1302 LinkCache
::getSelectFields(),
1303 [ 'page_namespace', 'page_title', 'pp_value' ]
1306 $res = $dbr->select( [ 'page', 'page_props' ],
1308 $lb->constructSet( 'page', $dbr ),
1311 [ 'page_props' => [ 'LEFT JOIN', [
1312 'pp_propname' => 'hiddencat',
1317 # Add the results to the link cache
1318 $lb->addResultToCache( LinkCache
::singleton(), $res );
1324 * Reset the category links (but not the category list) and add $categories
1326 * @param array $categories Mapping category name => sort key
1328 public function setCategoryLinks( array $categories ) {
1329 $this->mCategoryLinks
= [];
1330 $this->addCategoryLinks( $categories );
1334 * Get the list of category links, in a 2-D array with the following format:
1335 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1336 * hidden categories) and $link a HTML fragment with a link to the category
1341 public function getCategoryLinks() {
1342 return $this->mCategoryLinks
;
1346 * Get the list of category names this page belongs to.
1348 * @param string $type The type of categories which should be returned. Possible values:
1349 * * all: all categories of all types
1350 * * hidden: only the hidden categories
1351 * * normal: all categories, except hidden categories
1352 * @return array Array of strings
1354 public function getCategories( $type = 'all' ) {
1355 if ( $type === 'all' ) {
1356 $allCategories = [];
1357 foreach ( $this->mCategories
as $categories ) {
1358 $allCategories = array_merge( $allCategories, $categories );
1360 return $allCategories;
1362 if ( !isset( $this->mCategories
[$type] ) ) {
1363 throw new InvalidArgumentException( 'Invalid category type given: ' . $type );
1365 return $this->mCategories
[$type];
1369 * Add an array of indicators, with their identifiers as array
1370 * keys and HTML contents as values.
1372 * In case of duplicate keys, existing values are overwritten.
1374 * @param array $indicators
1377 public function setIndicators( array $indicators ) {
1378 $this->mIndicators
= $indicators +
$this->mIndicators
;
1379 // Keep ordered by key
1380 ksort( $this->mIndicators
);
1384 * Get the indicators associated with this page.
1386 * The array will be internally ordered by item keys.
1388 * @return array Keys: identifiers, values: HTML contents
1391 public function getIndicators() {
1392 return $this->mIndicators
;
1396 * Adds help link with an icon via page indicators.
1397 * Link target can be overridden by a local message containing a wikilink:
1398 * the message key is: lowercase action or special page name + '-helppage'.
1399 * @param string $to Target MediaWiki.org page title or encoded URL.
1400 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1403 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1404 $this->addModuleStyles( 'mediawiki.helplink' );
1405 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1407 if ( $overrideBaseUrl ) {
1410 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1411 $helpUrl = "//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1414 $link = Html
::rawElement(
1418 'target' => '_blank',
1419 'class' => 'mw-helplink',
1424 $this->setIndicators( [ 'mw-helplink' => $link ] );
1428 * Do not allow scripts which can be modified by wiki users to load on this page;
1429 * only allow scripts bundled with, or generated by, the software.
1430 * Site-wide styles are controlled by a config setting, since they can be
1431 * used to create a custom skin/theme, but not user-specific ones.
1433 * @todo this should be given a more accurate name
1435 public function disallowUserJs() {
1436 $this->reduceAllowedModules(
1437 ResourceLoaderModule
::TYPE_SCRIPTS
,
1438 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1441 // Site-wide styles are controlled by a config setting, see T73621
1442 // for background on why. User styles are never allowed.
1443 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1444 $styleOrigin = ResourceLoaderModule
::ORIGIN_USER_SITEWIDE
;
1446 $styleOrigin = ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
;
1448 $this->reduceAllowedModules(
1449 ResourceLoaderModule
::TYPE_STYLES
,
1455 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1456 * @see ResourceLoaderModule::$origin
1457 * @param string $type ResourceLoaderModule TYPE_ constant
1458 * @return int ResourceLoaderModule ORIGIN_ class constant
1460 public function getAllowedModules( $type ) {
1461 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1462 return min( array_values( $this->mAllowedModules
) );
1464 return isset( $this->mAllowedModules
[$type] )
1465 ?
$this->mAllowedModules
[$type]
1466 : ResourceLoaderModule
::ORIGIN_ALL
;
1471 * Limit the highest level of CSS/JS untrustworthiness allowed.
1473 * If passed the same or a higher level than the current level of untrustworthiness set, the
1474 * level will remain unchanged.
1476 * @param string $type
1477 * @param int $level ResourceLoaderModule class constant
1479 public function reduceAllowedModules( $type, $level ) {
1480 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1484 * Prepend $text to the body HTML
1486 * @param string $text HTML
1488 public function prependHTML( $text ) {
1489 $this->mBodytext
= $text . $this->mBodytext
;
1493 * Append $text to the body HTML
1495 * @param string $text HTML
1497 public function addHTML( $text ) {
1498 $this->mBodytext
.= $text;
1502 * Shortcut for adding an Html::element via addHTML.
1506 * @param string $element
1507 * @param array $attribs
1508 * @param string $contents
1510 public function addElement( $element, array $attribs = [], $contents = '' ) {
1511 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1515 * Clear the body HTML
1517 public function clearHTML() {
1518 $this->mBodytext
= '';
1524 * @return string HTML
1526 public function getHTML() {
1527 return $this->mBodytext
;
1531 * Get/set the ParserOptions object to use for wikitext parsing
1533 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1534 * current ParserOption object. This parameter is deprecated since 1.31.
1535 * @return ParserOptions
1537 public function parserOptions( $options = null ) {
1538 if ( $options !== null ) {
1539 wfDeprecated( __METHOD__
. ' with non-null $options', '1.31' );
1542 if ( $options !== null && !empty( $options->isBogus
) ) {
1543 // Someone is trying to set a bogus pre-$wgUser PO. Check if it has
1544 // been changed somehow, and keep it if so.
1545 $anonPO = ParserOptions
::newFromAnon();
1546 $anonPO->setAllowUnsafeRawHtml( false );
1547 if ( !$options->matches( $anonPO ) ) {
1548 wfLogWarning( __METHOD__
. ': Setting a changed bogus ParserOptions: ' . wfGetAllCallers( 5 ) );
1549 $options->isBogus
= false;
1553 if ( !$this->mParserOptions
) {
1554 if ( !$this->getContext()->getUser()->isSafeToLoad() ) {
1555 // $wgUser isn't unstubbable yet, so don't try to get a
1556 // ParserOptions for it. And don't cache this ParserOptions
1558 $po = ParserOptions
::newFromAnon();
1559 $po->setAllowUnsafeRawHtml( false );
1560 $po->isBogus
= true;
1561 if ( $options !== null ) {
1562 $this->mParserOptions
= empty( $options->isBogus
) ?
$options : null;
1567 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1568 $this->mParserOptions
->setAllowUnsafeRawHtml( false );
1571 if ( $options !== null && !empty( $options->isBogus
) ) {
1572 // They're trying to restore the bogus pre-$wgUser PO. Do the right
1574 return wfSetVar( $this->mParserOptions
, null, true );
1576 return wfSetVar( $this->mParserOptions
, $options );
1581 * Set the revision ID which will be seen by the wiki text parser
1582 * for things such as embedded {{REVISIONID}} variable use.
1584 * @param int|null $revid An positive integer, or null
1585 * @return mixed Previous value
1587 public function setRevisionId( $revid ) {
1588 $val = is_null( $revid ) ?
null : intval( $revid );
1589 return wfSetVar( $this->mRevisionId
, $val );
1593 * Get the displayed revision ID
1597 public function getRevisionId() {
1598 return $this->mRevisionId
;
1602 * Set the timestamp of the revision which will be displayed. This is used
1603 * to avoid a extra DB call in Skin::lastModified().
1605 * @param string|null $timestamp
1606 * @return mixed Previous value
1608 public function setRevisionTimestamp( $timestamp ) {
1609 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1613 * Get the timestamp of displayed revision.
1614 * This will be null if not filled by setRevisionTimestamp().
1616 * @return string|null
1618 public function getRevisionTimestamp() {
1619 return $this->mRevisionTimestamp
;
1623 * Set the displayed file version
1625 * @param File|bool $file
1626 * @return mixed Previous value
1628 public function setFileVersion( $file ) {
1630 if ( $file instanceof File
&& $file->exists() ) {
1631 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1633 return wfSetVar( $this->mFileVersion
, $val, true );
1637 * Get the displayed file version
1639 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1641 public function getFileVersion() {
1642 return $this->mFileVersion
;
1646 * Get the templates used on this page
1648 * @return array (namespace => dbKey => revId)
1651 public function getTemplateIds() {
1652 return $this->mTemplateIds
;
1656 * Get the files used on this page
1658 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1661 public function getFileSearchOptions() {
1662 return $this->mImageTimeKeys
;
1666 * Convert wikitext to HTML and add it to the buffer
1667 * Default assumes that the current page title will be used.
1669 * @param string $text
1670 * @param bool $linestart Is this the start of a line?
1671 * @param bool $interface Is this text in the user interface language?
1672 * @throws MWException
1674 public function addWikiText( $text, $linestart = true, $interface = true ) {
1675 $title = $this->getTitle(); // Work around E_STRICT
1677 throw new MWException( 'Title is null' );
1679 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1683 * Add wikitext with a custom Title object
1685 * @param string $text Wikitext
1686 * @param Title &$title
1687 * @param bool $linestart Is this the start of a line?
1689 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1690 $this->addWikiTextTitle( $text, $title, $linestart );
1694 * Add wikitext with a custom Title object and tidy enabled.
1696 * @param string $text Wikitext
1697 * @param Title &$title
1698 * @param bool $linestart Is this the start of a line?
1700 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1701 $this->addWikiTextTitle( $text, $title, $linestart, true );
1705 * Add wikitext with tidy enabled
1707 * @param string $text Wikitext
1708 * @param bool $linestart Is this the start of a line?
1710 public function addWikiTextTidy( $text, $linestart = true ) {
1711 $title = $this->getTitle();
1712 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1716 * Add wikitext with a custom Title object
1718 * @param string $text Wikitext
1719 * @param Title $title
1720 * @param bool $linestart Is this the start of a line?
1721 * @param bool $tidy Whether to use tidy
1722 * @param bool $interface Whether it is an interface message
1723 * (for example disables conversion)
1725 public function addWikiTextTitle( $text, Title
$title, $linestart,
1726 $tidy = false, $interface = false
1730 $popts = $this->parserOptions();
1731 $oldTidy = $popts->setTidy( $tidy );
1732 $popts->setInterfaceMessage( (bool)$interface );
1734 $parserOutput = $wgParser->getFreshParser()->parse(
1735 $text, $title, $popts,
1736 $linestart, true, $this->mRevisionId
1739 $popts->setTidy( $oldTidy );
1741 $this->addParserOutput( $parserOutput, [
1742 'enableSectionEditLinks' => false,
1747 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1748 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1752 * @param ParserOutput $parserOutput
1754 public function addParserOutputMetadata( $parserOutput ) {
1755 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1756 $this->addCategoryLinks( $parserOutput->getCategories() );
1757 $this->setIndicators( $parserOutput->getIndicators() );
1758 $this->mNewSectionLink
= $parserOutput->getNewSection();
1759 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1761 if ( !$parserOutput->isCacheable() ) {
1762 $this->enableClientCache( false );
1764 $this->mNoGallery
= $parserOutput->getNoGallery();
1765 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1766 $this->addModules( $parserOutput->getModules() );
1767 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1768 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1769 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1770 $this->mPreventClickjacking
= $this->mPreventClickjacking
1771 ||
$parserOutput->preventClickjacking();
1773 // Template versioning...
1774 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1775 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1776 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1778 $this->mTemplateIds
[$ns] = $dbks;
1781 // File versioning...
1782 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1783 $this->mImageTimeKeys
[$dbk] = $data;
1786 // Hooks registered in the object
1787 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1788 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1789 list( $hookName, $data ) = $hookInfo;
1790 if ( isset( $parserOutputHooks[$hookName] ) ) {
1791 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1795 // Enable OOUI if requested via ParserOutput
1796 if ( $parserOutput->getEnableOOUI() ) {
1797 $this->enableOOUI();
1800 // Include parser limit report
1801 if ( !$this->limitReportJSData
) {
1802 $this->limitReportJSData
= $parserOutput->getLimitReportJSData();
1805 // Link flags are ignored for now, but may in the future be
1806 // used to mark individual language links.
1808 // Avoid PHP 7.1 warning of passing $this by reference
1809 $outputPage = $this;
1810 Hooks
::run( 'LanguageLinks', [ $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ] );
1811 Hooks
::runWithoutAbort( 'OutputPageParserOutput', [ &$outputPage, $parserOutput ] );
1813 // This check must be after 'OutputPageParserOutput' runs in addParserOutputMetadata
1814 // so that extensions may modify ParserOutput to toggle TOC.
1815 // This cannot be moved to addParserOutputText because that is not
1816 // called by EditPage for Preview.
1817 if ( $parserOutput->getTOCHTML() ) {
1818 $this->mEnableTOC
= true;
1823 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1824 * ParserOutput object, without any other metadata.
1827 * @param ParserOutput $parserOutput
1828 * @param array $poOptions Options to ParserOutput::getText()
1830 public function addParserOutputContent( $parserOutput, $poOptions = [] ) {
1831 $this->addParserOutputText( $parserOutput, $poOptions );
1833 $this->addModules( $parserOutput->getModules() );
1834 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1835 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1837 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1841 * Add the HTML associated with a ParserOutput object, without any metadata.
1844 * @param ParserOutput $parserOutput
1845 * @param array $poOptions Options to ParserOutput::getText()
1847 public function addParserOutputText( $parserOutput, $poOptions = [] ) {
1848 $text = $parserOutput->getText( $poOptions );
1849 // Avoid PHP 7.1 warning of passing $this by reference
1850 $outputPage = $this;
1851 Hooks
::runWithoutAbort( 'OutputPageBeforeHTML', [ &$outputPage, &$text ] );
1852 $this->addHTML( $text );
1856 * Add everything from a ParserOutput object.
1858 * @param ParserOutput $parserOutput
1859 * @param array $poOptions Options to ParserOutput::getText()
1861 function addParserOutput( $parserOutput, $poOptions = [] ) {
1862 $this->addParserOutputMetadata( $parserOutput );
1863 $this->addParserOutputText( $parserOutput, $poOptions );
1867 * Add the output of a QuickTemplate to the output buffer
1869 * @param QuickTemplate &$template
1871 public function addTemplate( &$template ) {
1872 $this->addHTML( $template->getHTML() );
1876 * Parse wikitext and return the HTML.
1878 * @param string $text
1879 * @param bool $linestart Is this the start of a line?
1880 * @param bool $interface Use interface language ($wgLang instead of
1881 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1882 * This also disables LanguageConverter.
1883 * @param Language $language Target language object, will override $interface
1884 * @throws MWException
1885 * @return string HTML
1887 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1890 if ( is_null( $this->getTitle() ) ) {
1891 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1894 $popts = $this->parserOptions();
1896 $popts->setInterfaceMessage( true );
1898 if ( $language !== null ) {
1899 $oldLang = $popts->setTargetLanguage( $language );
1902 $parserOutput = $wgParser->getFreshParser()->parse(
1903 $text, $this->getTitle(), $popts,
1904 $linestart, true, $this->mRevisionId
1908 $popts->setInterfaceMessage( false );
1910 if ( $language !== null ) {
1911 $popts->setTargetLanguage( $oldLang );
1914 return $parserOutput->getText( [
1915 'enableSectionEditLinks' => false,
1920 * Parse wikitext, strip paragraphs, and return the HTML.
1922 * @param string $text
1923 * @param bool $linestart Is this the start of a line?
1924 * @param bool $interface Use interface language ($wgLang instead of
1925 * $wgContLang) while parsing language sensitive magic
1926 * words like GRAMMAR and PLURAL
1927 * @return string HTML
1929 public function parseInline( $text, $linestart = true, $interface = false ) {
1930 $parsed = $this->parse( $text, $linestart, $interface );
1931 return Parser
::stripOuterParagraph( $parsed );
1935 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1937 * @param int $maxage Maximum cache time on the CDN, in seconds.
1939 public function setCdnMaxage( $maxage ) {
1940 $this->mCdnMaxage
= min( $maxage, $this->mCdnMaxageLimit
);
1944 * Lower the value of the "s-maxage" part of the "Cache-control" HTTP header
1946 * @param int $maxage Maximum cache time on the CDN, in seconds
1949 public function lowerCdnMaxage( $maxage ) {
1950 $this->mCdnMaxageLimit
= min( $maxage, $this->mCdnMaxageLimit
);
1951 $this->setCdnMaxage( $this->mCdnMaxage
);
1955 * Get TTL in [$minTTL,$maxTTL] in pass it to lowerCdnMaxage()
1957 * This sets and returns $minTTL if $mtime is false or null. Otherwise,
1958 * the TTL is higher the older the $mtime timestamp is. Essentially, the
1959 * TTL is 90% of the age of the object, subject to the min and max.
1961 * @param string|int|float|bool|null $mtime Last-Modified timestamp
1962 * @param int $minTTL Mimimum TTL in seconds [default: 1 minute]
1963 * @param int $maxTTL Maximum TTL in seconds [default: $wgSquidMaxage]
1964 * @return int TTL in seconds
1967 public function adaptCdnTTL( $mtime, $minTTL = 0, $maxTTL = 0 ) {
1968 $minTTL = $minTTL ?
: IExpiringStore
::TTL_MINUTE
;
1969 $maxTTL = $maxTTL ?
: $this->getConfig()->get( 'SquidMaxage' );
1971 if ( $mtime === null ||
$mtime === false ) {
1972 return $minTTL; // entity does not exist
1975 $age = time() - wfTimestamp( TS_UNIX
, $mtime );
1976 $adaptiveTTL = max( 0.9 * $age, $minTTL );
1977 $adaptiveTTL = min( $adaptiveTTL, $maxTTL );
1979 $this->lowerCdnMaxage( (int)$adaptiveTTL );
1981 return $adaptiveTTL;
1985 * Use enableClientCache(false) to force it to send nocache headers
1987 * @param bool $state
1991 public function enableClientCache( $state ) {
1992 return wfSetVar( $this->mEnableClientCache
, $state );
1996 * Get the list of cookies that will influence on the cache
2000 function getCacheVaryCookies() {
2002 if ( $cookies === null ) {
2003 $config = $this->getConfig();
2004 $cookies = array_merge(
2005 SessionManager
::singleton()->getVaryCookies(),
2009 $config->get( 'CacheVaryCookies' )
2011 Hooks
::run( 'GetCacheVaryCookies', [ $this, &$cookies ] );
2017 * Check if the request has a cache-varying cookie header
2018 * If it does, it's very important that we don't allow public caching
2022 function haveCacheVaryCookies() {
2023 $request = $this->getRequest();
2024 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2025 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2026 wfDebug( __METHOD__
. ": found $cookieName\n" );
2030 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
2035 * Add an HTTP header that will influence on the cache
2037 * @param string $header Header name
2038 * @param string[]|null $option Options for the Key header. See
2039 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2040 * for the list of valid options.
2042 public function addVaryHeader( $header, array $option = null ) {
2043 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
2044 $this->mVaryHeader
[$header] = [];
2046 if ( !is_array( $option ) ) {
2049 $this->mVaryHeader
[$header] = array_unique( array_merge( $this->mVaryHeader
[$header], $option ) );
2053 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2054 * such as Accept-Encoding or Cookie
2058 public function getVaryHeader() {
2059 // If we vary on cookies, let's make sure it's always included here too.
2060 if ( $this->getCacheVaryCookies() ) {
2061 $this->addVaryHeader( 'Cookie' );
2064 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2065 $this->addVaryHeader( $header, $options );
2067 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader
) );
2071 * Add an HTTP Link: header
2073 * @param string $header Header value
2075 public function addLinkHeader( $header ) {
2076 $this->mLinkHeader
[] = $header;
2080 * Return a Link: header. Based on the values of $mLinkHeader.
2084 public function getLinkHeader() {
2085 if ( !$this->mLinkHeader
) {
2089 return 'Link: ' . implode( ',', $this->mLinkHeader
);
2093 * Get a complete Key header
2097 public function getKeyHeader() {
2098 $cvCookies = $this->getCacheVaryCookies();
2100 $cookiesOption = [];
2101 foreach ( $cvCookies as $cookieName ) {
2102 $cookiesOption[] = 'param=' . $cookieName;
2104 $this->addVaryHeader( 'Cookie', $cookiesOption );
2106 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2107 $this->addVaryHeader( $header, $options );
2111 foreach ( $this->mVaryHeader
as $header => $option ) {
2112 $newheader = $header;
2113 if ( is_array( $option ) && count( $option ) > 0 ) {
2114 $newheader .= ';' . implode( ';', $option );
2116 $headers[] = $newheader;
2118 $key = 'Key: ' . implode( ',', $headers );
2124 * T23672: Add Accept-Language to Vary and Key headers
2125 * if there's no 'variant' parameter existed in GET.
2128 * /w/index.php?title=Main_page should always be served; but
2129 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
2131 function addAcceptLanguage() {
2132 $title = $this->getTitle();
2133 if ( !$title instanceof Title
) {
2137 $lang = $title->getPageLanguage();
2138 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2139 $variants = $lang->getVariants();
2141 foreach ( $variants as $variant ) {
2142 if ( $variant === $lang->getCode() ) {
2145 $aloption[] = 'substr=' . $variant;
2147 // IE and some other browsers use BCP 47 standards in
2148 // their Accept-Language header, like "zh-CN" or "zh-Hant".
2149 // We should handle these too.
2150 $variantBCP47 = LanguageCode
::bcp47( $variant );
2151 if ( $variantBCP47 !== $variant ) {
2152 $aloption[] = 'substr=' . $variantBCP47;
2156 $this->addVaryHeader( 'Accept-Language', $aloption );
2161 * Set a flag which will cause an X-Frame-Options header appropriate for
2162 * edit pages to be sent. The header value is controlled by
2163 * $wgEditPageFrameOptions.
2165 * This is the default for special pages. If you display a CSRF-protected
2166 * form on an ordinary view page, then you need to call this function.
2168 * @param bool $enable
2170 public function preventClickjacking( $enable = true ) {
2171 $this->mPreventClickjacking
= $enable;
2175 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2176 * This can be called from pages which do not contain any CSRF-protected
2179 public function allowClickjacking() {
2180 $this->mPreventClickjacking
= false;
2184 * Get the prevent-clickjacking flag
2189 public function getPreventClickjacking() {
2190 return $this->mPreventClickjacking
;
2194 * Get the X-Frame-Options header value (without the name part), or false
2195 * if there isn't one. This is used by Skin to determine whether to enable
2196 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2198 * @return string|false
2200 public function getFrameOptions() {
2201 $config = $this->getConfig();
2202 if ( $config->get( 'BreakFrames' ) ) {
2204 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2205 return $config->get( 'EditPageFrameOptions' );
2211 * Send cache control HTTP headers
2213 public function sendCacheControl() {
2214 $response = $this->getRequest()->response();
2215 $config = $this->getConfig();
2217 $this->addVaryHeader( 'Cookie' );
2218 $this->addAcceptLanguage();
2220 # don't serve compressed data to clients who can't handle it
2221 # maintain different caches for logged-in users and non-logged in ones
2222 $response->header( $this->getVaryHeader() );
2224 if ( $config->get( 'UseKeyHeader' ) ) {
2225 $response->header( $this->getKeyHeader() );
2228 if ( $this->mEnableClientCache
) {
2230 $config->get( 'UseSquid' ) &&
2231 !$response->hasCookies() &&
2232 !SessionManager
::getGlobalSession()->isPersistent() &&
2233 !$this->isPrintable() &&
2234 $this->mCdnMaxage
!= 0 &&
2235 !$this->haveCacheVaryCookies()
2237 if ( $config->get( 'UseESI' ) ) {
2238 # We'll purge the proxy cache explicitly, but require end user agents
2239 # to revalidate against the proxy on each visit.
2240 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2241 wfDebug( __METHOD__
.
2242 ": proxy caching with ESI; {$this->mLastModified} **", 'private' );
2243 # start with a shorter timeout for initial testing
2244 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2246 "Surrogate-Control: max-age={$config->get( 'SquidMaxage' )}" .
2247 "+{$this->mCdnMaxage}, content=\"ESI/1.0\""
2249 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2251 # We'll purge the proxy cache for anons explicitly, but require end user agents
2252 # to revalidate against the proxy on each visit.
2253 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2254 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2255 wfDebug( __METHOD__
.
2256 ": local proxy caching; {$this->mLastModified} **", 'private' );
2257 # start with a shorter timeout for initial testing
2258 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2259 $response->header( "Cache-Control: " .
2260 "s-maxage={$this->mCdnMaxage}, must-revalidate, max-age=0" );
2263 # We do want clients to cache if they can, but they *must* check for updates
2264 # on revisiting the page.
2265 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **", 'private' );
2266 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2267 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2269 if ( $this->mLastModified
) {
2270 $response->header( "Last-Modified: {$this->mLastModified}" );
2273 wfDebug( __METHOD__
. ": no caching **", 'private' );
2275 # In general, the absence of a last modified header should be enough to prevent
2276 # the client from using its cache. We send a few other things just to make sure.
2277 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2278 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2279 $response->header( 'Pragma: no-cache' );
2284 * Finally, all the text has been munged and accumulated into
2285 * the object, let's actually output it:
2287 * @param bool $return Set to true to get the result as a string rather than sending it
2288 * @return string|null
2290 * @throws FatalError
2291 * @throws MWException
2293 public function output( $return = false ) {
2296 if ( $this->mDoNothing
) {
2297 return $return ?
'' : null;
2300 $response = $this->getRequest()->response();
2301 $config = $this->getConfig();
2303 if ( $this->mRedirect
!= '' ) {
2304 # Standards require redirect URLs to be absolute
2305 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2307 $redirect = $this->mRedirect
;
2308 $code = $this->mRedirectCode
;
2310 if ( Hooks
::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2311 if ( $code == '301' ||
$code == '303' ) {
2312 if ( !$config->get( 'DebugRedirects' ) ) {
2313 $response->statusHeader( $code );
2315 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2317 if ( $config->get( 'VaryOnXFP' ) ) {
2318 $this->addVaryHeader( 'X-Forwarded-Proto' );
2320 $this->sendCacheControl();
2322 $response->header( "Content-Type: text/html; charset=utf-8" );
2323 if ( $config->get( 'DebugRedirects' ) ) {
2324 $url = htmlspecialchars( $redirect );
2325 print "<!DOCTYPE html>\n<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2326 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2327 print "</body>\n</html>\n";
2329 $response->header( 'Location: ' . $redirect );
2333 return $return ?
'' : null;
2334 } elseif ( $this->mStatusCode
) {
2335 $response->statusHeader( $this->mStatusCode
);
2338 # Buffer output; final headers may depend on later processing
2341 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2342 $response->header( 'Content-language: ' . $wgContLang->getHtmlCode() );
2344 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2345 // jQuery etc. can work correctly.
2346 $response->header( 'X-UA-Compatible: IE=Edge' );
2348 if ( !$this->mArticleBodyOnly
) {
2349 $sk = $this->getSkin();
2351 if ( $sk->shouldPreloadLogo() ) {
2352 $this->addLogoPreloadLinkHeaders();
2356 $linkHeader = $this->getLinkHeader();
2357 if ( $linkHeader ) {
2358 $response->header( $linkHeader );
2361 // Prevent framing, if requested
2362 $frameOptions = $this->getFrameOptions();
2363 if ( $frameOptions ) {
2364 $response->header( "X-Frame-Options: $frameOptions" );
2367 if ( $this->mArticleBodyOnly
) {
2368 echo $this->mBodytext
;
2370 // Enable safe mode if requested
2371 if ( $this->getRequest()->getBool( 'safemode' ) ) {
2372 $this->disallowUserJs();
2375 $sk = $this->getSkin();
2376 foreach ( $sk->getDefaultModules() as $group ) {
2377 $this->addModules( $group );
2380 MWDebug
::addModules( $this );
2382 // Avoid PHP 7.1 warning of passing $this by reference
2383 $outputPage = $this;
2384 // Hook that allows last minute changes to the output page, e.g.
2385 // adding of CSS or Javascript by extensions.
2386 Hooks
::runWithoutAbort( 'BeforePageDisplay', [ &$outputPage, &$sk ] );
2390 } catch ( Exception
$e ) {
2391 ob_end_clean(); // bug T129657
2397 // This hook allows last minute changes to final overall output by modifying output buffer
2398 Hooks
::runWithoutAbort( 'AfterFinalPageOutput', [ $this ] );
2399 } catch ( Exception
$e ) {
2400 ob_end_clean(); // bug T129657
2404 $this->sendCacheControl();
2407 return ob_get_clean();
2415 * Prepare this object to display an error page; disable caching and
2416 * indexing, clear the current text and redirect, set the page's title
2417 * and optionally an custom HTML title (content of the "<title>" tag).
2419 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2420 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2421 * optional, if not passed the "<title>" attribute will be
2422 * based on $pageTitle
2424 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2425 $this->setPageTitle( $pageTitle );
2426 if ( $htmlTitle !== false ) {
2427 $this->setHTMLTitle( $htmlTitle );
2429 $this->setRobotPolicy( 'noindex,nofollow' );
2430 $this->setArticleRelated( false );
2431 $this->enableClientCache( false );
2432 $this->mRedirect
= '';
2433 $this->clearSubtitle();
2438 * Output a standard error page
2440 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2441 * showErrorPage( 'titlemsg', 'pagetextmsg', [ 'param1', 'param2' ] );
2442 * showErrorPage( 'titlemsg', $messageObject );
2443 * showErrorPage( $titleMessageObject, $messageObject );
2445 * @param string|Message $title Message key (string) for page title, or a Message object
2446 * @param string|Message $msg Message key (string) for page text, or a Message object
2447 * @param array $params Message parameters; ignored if $msg is a Message object
2449 public function showErrorPage( $title, $msg, $params = [] ) {
2450 if ( !$title instanceof Message
) {
2451 $title = $this->msg( $title );
2454 $this->prepareErrorPage( $title );
2456 if ( $msg instanceof Message
) {
2457 if ( $params !== [] ) {
2458 trigger_error( 'Argument ignored: $params. The message parameters argument '
2459 . 'is discarded when the $msg argument is a Message object instead of '
2460 . 'a string.', E_USER_NOTICE
);
2462 $this->addHTML( $msg->parseAsBlock() );
2464 $this->addWikiMsgArray( $msg, $params );
2467 $this->returnToMain();
2471 * Output a standard permission error page
2473 * @param array $errors Error message keys or [key, param...] arrays
2474 * @param string $action Action that was denied or null if unknown
2476 public function showPermissionsErrorPage( array $errors, $action = null ) {
2477 foreach ( $errors as $key => $error ) {
2478 $errors[$key] = (array)$error;
2481 // For some action (read, edit, create and upload), display a "login to do this action"
2482 // error if all of the following conditions are met:
2483 // 1. the user is not logged in
2484 // 2. the only error is insufficient permissions (i.e. no block or something else)
2485 // 3. the error can be avoided simply by logging in
2486 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2487 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2488 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2489 && ( User
::groupHasPermission( 'user', $action )
2490 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2492 $displayReturnto = null;
2494 # Due to T34276, if a user does not have read permissions,
2495 # $this->getTitle() will just give Special:Badtitle, which is
2496 # not especially useful as a returnto parameter. Use the title
2497 # from the request instead, if there was one.
2498 $request = $this->getRequest();
2499 $returnto = Title
::newFromText( $request->getVal( 'title', '' ) );
2500 if ( $action == 'edit' ) {
2501 $msg = 'whitelistedittext';
2502 $displayReturnto = $returnto;
2503 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2504 $msg = 'nocreatetext';
2505 } elseif ( $action == 'upload' ) {
2506 $msg = 'uploadnologintext';
2508 $msg = 'loginreqpagetext';
2509 $displayReturnto = Title
::newMainPage();
2515 $query['returnto'] = $returnto->getPrefixedText();
2517 if ( !$request->wasPosted() ) {
2518 $returntoquery = $request->getValues();
2519 unset( $returntoquery['title'] );
2520 unset( $returntoquery['returnto'] );
2521 unset( $returntoquery['returntoquery'] );
2522 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2525 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
2526 $loginLink = $linkRenderer->makeKnownLink(
2527 SpecialPage
::getTitleFor( 'Userlogin' ),
2528 $this->msg( 'loginreqlink' )->text(),
2533 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2534 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2536 # Don't return to a page the user can't read otherwise
2537 # we'll end up in a pointless loop
2538 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2539 $this->returnToMain( null, $displayReturnto );
2542 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2543 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2548 * Display an error page indicating that a given version of MediaWiki is
2549 * required to use it
2551 * @param mixed $version The version of MediaWiki needed to use the page
2553 public function versionRequired( $version ) {
2554 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2556 $this->addWikiMsg( 'versionrequiredtext', $version );
2557 $this->returnToMain();
2561 * Format a list of error messages
2563 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2564 * @param string $action Action that was denied or null if unknown
2565 * @return string The wikitext error-messages, formatted into a list.
2567 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2568 if ( $action == null ) {
2569 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2571 $action_desc = $this->msg( "action-$action" )->plain();
2573 'permissionserrorstext-withaction',
2576 )->plain() . "\n\n";
2579 if ( count( $errors ) > 1 ) {
2580 $text .= '<ul class="permissions-errors">' . "\n";
2582 foreach ( $errors as $error ) {
2584 $text .= call_user_func_array( [ $this, 'msg' ], $error )->plain();
2589 $text .= "<div class=\"permissions-errors\">\n" .
2590 call_user_func_array( [ $this, 'msg' ], reset( $errors ) )->plain() .
2598 * Show a warning about replica DB lag
2600 * If the lag is higher than $wgSlaveLagCritical seconds,
2601 * then the warning is a bit more obvious. If the lag is
2602 * lower than $wgSlaveLagWarning, then no warning is shown.
2604 * @param int $lag Slave lag
2606 public function showLagWarning( $lag ) {
2607 $config = $this->getConfig();
2608 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2609 $lag = floor( $lag ); // floor to avoid nano seconds to display
2610 $message = $lag < $config->get( 'SlaveLagCritical' )
2613 $wrap = Html
::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2614 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2618 public function showFatalError( $message ) {
2619 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2621 $this->addHTML( $message );
2624 public function showUnexpectedValueError( $name, $val ) {
2625 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2628 public function showFileCopyError( $old, $new ) {
2629 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2632 public function showFileRenameError( $old, $new ) {
2633 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2636 public function showFileDeleteError( $name ) {
2637 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2640 public function showFileNotFoundError( $name ) {
2641 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2645 * Add a "return to" link pointing to a specified title
2647 * @param Title $title Title to link
2648 * @param array $query Query string parameters
2649 * @param string $text Text of the link (input is not escaped)
2650 * @param array $options Options array to pass to Linker
2652 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
2653 $linkRenderer = MediaWikiServices
::getInstance()
2654 ->getLinkRendererFactory()->createFromLegacyOptions( $options );
2655 $link = $this->msg( 'returnto' )->rawParams(
2656 $linkRenderer->makeLink( $title, $text, [], $query ) )->escaped();
2657 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2661 * Add a "return to" link pointing to a specified title,
2662 * or the title indicated in the request, or else the main page
2664 * @param mixed $unused
2665 * @param Title|string $returnto Title or String to return to
2666 * @param string $returntoquery Query string for the return to link
2668 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2669 if ( $returnto == null ) {
2670 $returnto = $this->getRequest()->getText( 'returnto' );
2673 if ( $returntoquery == null ) {
2674 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2677 if ( $returnto === '' ) {
2678 $returnto = Title
::newMainPage();
2681 if ( is_object( $returnto ) ) {
2682 $titleObj = $returnto;
2684 $titleObj = Title
::newFromText( $returnto );
2686 // We don't want people to return to external interwiki. That
2687 // might potentially be used as part of a phishing scheme
2688 if ( !is_object( $titleObj ) ||
$titleObj->isExternal() ) {
2689 $titleObj = Title
::newMainPage();
2692 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2695 private function getRlClientContext() {
2696 if ( !$this->rlClientContext
) {
2697 $query = ResourceLoader
::makeLoaderQuery(
2698 [], // modules; not relevant
2699 $this->getLanguage()->getCode(),
2700 $this->getSkin()->getSkinName(),
2701 $this->getUser()->isLoggedIn() ?
$this->getUser()->getName() : null,
2702 null, // version; not relevant
2703 ResourceLoader
::inDebugMode(),
2704 null, // only; not relevant
2705 $this->isPrintable(),
2706 $this->getRequest()->getBool( 'handheld' )
2708 $this->rlClientContext
= new ResourceLoaderContext(
2709 $this->getResourceLoader(),
2710 new FauxRequest( $query )
2713 return $this->rlClientContext
;
2717 * Call this to freeze the module queue and JS config and create a formatter.
2719 * Depending on the Skin, this may get lazy-initialised in either headElement() or
2720 * getBottomScripts(). See SkinTemplate::prepareQuickTemplate(). Calling this too early may
2721 * cause unexpected side-effects since disallowUserJs() may be called at any time to change
2722 * the module filters retroactively. Skins and extension hooks may also add modules until very
2723 * late in the request lifecycle.
2725 * @return ResourceLoaderClientHtml
2727 public function getRlClient() {
2728 if ( !$this->rlClient
) {
2729 $context = $this->getRlClientContext();
2730 $rl = $this->getResourceLoader();
2731 $this->addModules( [
2735 $this->addModuleStyles( [
2740 $this->getSkin()->setupSkinUserCss( $this );
2742 // Prepare exempt modules for buildExemptModules()
2743 $exemptGroups = [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ];
2745 $moduleStyles = $this->getModuleStyles( /*filter*/ true );
2747 // Preload getTitleInfo for isKnownEmpty calls below and in ResourceLoaderClientHtml
2748 // Separate user-specific batch for improved cache-hit ratio.
2749 $userBatch = [ 'user.styles', 'user' ];
2750 $siteBatch = array_diff( $moduleStyles, $userBatch );
2751 $dbr = wfGetDB( DB_REPLICA
);
2752 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $siteBatch );
2753 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $userBatch );
2755 // Filter out modules handled by buildExemptModules()
2756 $moduleStyles = array_filter( $moduleStyles,
2757 function ( $name ) use ( $rl, $context, &$exemptGroups, &$exemptStates ) {
2758 $module = $rl->getModule( $name );
2760 if ( $name === 'user.styles' && $this->isUserCssPreview() ) {
2761 $exemptStates[$name] = 'ready';
2762 // Special case in buildExemptModules()
2765 $group = $module->getGroup();
2766 if ( isset( $exemptGroups[$group] ) ) {
2767 $exemptStates[$name] = 'ready';
2768 if ( !$module->isKnownEmpty( $context ) ) {
2769 // E.g. Don't output empty <styles>
2770 $exemptGroups[$group][] = $name;
2778 $this->rlExemptStyleModules
= $exemptGroups;
2780 $isUserModuleFiltered = !$this->filterModules( [ 'user' ] );
2781 // If this page filters out 'user', makeResourceLoaderLink will drop it.
2782 // Avoid indefinite "loading" state or untrue "ready" state (T145368).
2783 if ( !$isUserModuleFiltered ) {
2784 // Manually handled by getBottomScripts()
2785 $userModule = $rl->getModule( 'user' );
2786 $userState = $userModule->isKnownEmpty( $context ) && !$this->isUserJsPreview()
2789 $this->rlUserModuleState
= $exemptStates['user'] = $userState;
2792 $rlClient = new ResourceLoaderClientHtml( $context, $this->getTarget() );
2793 $rlClient->setConfig( $this->getJSVars() );
2794 $rlClient->setModules( $this->getModules( /*filter*/ true ) );
2795 $rlClient->setModuleStyles( $moduleStyles );
2796 $rlClient->setModuleScripts( $this->getModuleScripts( /*filter*/ true ) );
2797 $rlClient->setExemptStates( $exemptStates );
2798 $this->rlClient
= $rlClient;
2800 return $this->rlClient
;
2804 * @param Skin $sk The given Skin
2805 * @param bool $includeStyle Unused
2806 * @return string The doctype, opening "<html>", and head element.
2808 public function headElement( Skin
$sk, $includeStyle = true ) {
2811 $userdir = $this->getLanguage()->getDir();
2812 $sitedir = $wgContLang->getDir();
2815 $pieces[] = Html
::htmlHeader( Sanitizer
::mergeAttributes(
2816 $this->getRlClient()->getDocumentAttributes(),
2817 $sk->getHtmlElementAttributes()
2819 $pieces[] = Html
::openElement( 'head' );
2821 if ( $this->getHTMLTitle() == '' ) {
2822 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2825 if ( !Html
::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2826 // Add <meta charset="UTF-8">
2827 // This should be before <title> since it defines the charset used by
2828 // text including the text inside <title>.
2829 // The spec recommends defining XHTML5's charset using the XML declaration
2831 // Our XML declaration is output by Html::htmlHeader.
2832 // https://html.spec.whatwg.org/multipage/semantics.html#attr-meta-http-equiv-content-type
2833 // https://html.spec.whatwg.org/multipage/semantics.html#charset
2834 $pieces[] = Html
::element( 'meta', [ 'charset' => 'UTF-8' ] );
2837 $pieces[] = Html
::element( 'title', null, $this->getHTMLTitle() );
2838 $pieces[] = $this->getRlClient()->getHeadHtml();
2839 $pieces[] = $this->buildExemptModules();
2840 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
2841 $pieces = array_merge( $pieces, array_values( $this->mHeadItems
) );
2843 // Use an IE conditional comment to serve the script only to old IE
2844 $pieces[] = '<!--[if lt IE 9]>' .
2845 ResourceLoaderClientHtml
::makeLoad(
2846 ResourceLoaderContext
::newDummyContext(),
2848 ResourceLoaderModule
::TYPE_SCRIPTS
,
2853 $pieces[] = Html
::closeElement( 'head' );
2855 $bodyClasses = $this->mAdditionalBodyClasses
;
2856 $bodyClasses[] = 'mediawiki';
2858 # Classes for LTR/RTL directionality support
2859 $bodyClasses[] = $userdir;
2860 $bodyClasses[] = "sitedir-$sitedir";
2862 $underline = $this->getUser()->getOption( 'underline' );
2863 if ( $underline < 2 ) {
2864 // The following classes can be used here:
2865 // * mw-underline-always
2866 // * mw-underline-never
2867 $bodyClasses[] = 'mw-underline-' . ( $underline ?
'always' : 'never' );
2870 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2871 # A <body> class is probably not the best way to do this . . .
2872 $bodyClasses[] = 'capitalize-all-nouns';
2875 // Parser feature migration class
2876 // The idea is that this will eventually be removed, after the wikitext
2877 // which requires it is cleaned up.
2878 $bodyClasses[] = 'mw-hide-empty-elt';
2880 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2881 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2883 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2886 // While the implode() is not strictly needed, it's used for backwards compatibility
2887 // (this used to be built as a string and hooks likely still expect that).
2888 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2890 // Allow skins and extensions to add body attributes they need
2891 $sk->addToBodyAttributes( $this, $bodyAttrs );
2892 Hooks
::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
2894 $pieces[] = Html
::openElement( 'body', $bodyAttrs );
2896 return self
::combineWrappedStrings( $pieces );
2900 * Get a ResourceLoader object associated with this OutputPage
2902 * @return ResourceLoader
2904 public function getResourceLoader() {
2905 if ( is_null( $this->mResourceLoader
) ) {
2906 $this->mResourceLoader
= new ResourceLoader(
2908 LoggerFactory
::getInstance( 'resourceloader' )
2911 return $this->mResourceLoader
;
2915 * Explicily load or embed modules on a page.
2917 * @param array|string $modules One or more module names
2918 * @param string $only ResourceLoaderModule TYPE_ class constant
2919 * @param array $extraQuery [optional] Array with extra query parameters for the request
2920 * @return string|WrappedStringList HTML
2922 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
2923 // Apply 'target' and 'origin' filters
2924 $modules = $this->filterModules( (array)$modules, null, $only );
2926 return ResourceLoaderClientHtml
::makeLoad(
2927 $this->getRlClientContext(),
2935 * Combine WrappedString chunks and filter out empty ones
2937 * @param array $chunks
2938 * @return string|WrappedStringList HTML
2940 protected static function combineWrappedStrings( array $chunks ) {
2941 // Filter out empty values
2942 $chunks = array_filter( $chunks, 'strlen' );
2943 return WrappedString
::join( "\n", $chunks );
2946 private function isUserJsPreview() {
2947 return $this->getConfig()->get( 'AllowUserJs' )
2948 && $this->getTitle()
2949 && $this->getTitle()->isJsSubpage()
2950 && $this->userCanPreview();
2953 protected function isUserCssPreview() {
2954 return $this->getConfig()->get( 'AllowUserCss' )
2955 && $this->getTitle()
2956 && $this->getTitle()->isCssSubpage()
2957 && $this->userCanPreview();
2961 * JS stuff to put at the bottom of the `<body>`. These are modules with position 'bottom',
2962 * legacy scripts ($this->mScripts), and user JS.
2964 * @return string|WrappedStringList HTML
2966 public function getBottomScripts() {
2968 $chunks[] = $this->getRlClient()->getBodyHtml();
2970 // Legacy non-ResourceLoader scripts
2971 $chunks[] = $this->mScripts
;
2973 // Exempt 'user' module
2974 // - May need excludepages for live preview. (T28283)
2975 // - Must use TYPE_COMBINED so its response is handled by mw.loader.implement() which
2976 // ensures execution is scheduled after the "site" module.
2977 // - Don't load if module state is already resolved as "ready".
2978 if ( $this->rlUserModuleState
=== 'loading' ) {
2979 if ( $this->isUserJsPreview() ) {
2980 $chunks[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_COMBINED
,
2981 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
2983 $chunks[] = ResourceLoader
::makeInlineScript(
2984 Xml
::encodeJsCall( 'mw.loader.using', [
2988 . Xml
::encodeJsCall( '$.globalEval', [
2989 $this->getRequest()->getText( 'wpTextbox1' )
2995 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
2996 // asynchronously and may arrive *after* the inline script here. So the previewed code
2997 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js.
2998 // Similarly, when previewing ./common.js and the user module does arrive first,
2999 // it will arrive without common.js and the inline script runs after.
3000 // Thus running common after the excluded subpage.
3003 $chunks[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_COMBINED
);
3007 if ( $this->limitReportJSData
) {
3008 $chunks[] = ResourceLoader
::makeInlineScript(
3009 ResourceLoader
::makeConfigSetScript(
3010 [ 'wgPageParseReport' => $this->limitReportJSData
]
3015 return self
::combineWrappedStrings( $chunks );
3019 * Get the javascript config vars to include on this page
3021 * @return array Array of javascript config vars
3024 public function getJsConfigVars() {
3025 return $this->mJsConfigVars
;
3029 * Add one or more variables to be set in mw.config in JavaScript
3031 * @param string|array $keys Key or array of key/value pairs
3032 * @param mixed $value [optional] Value of the configuration variable
3034 public function addJsConfigVars( $keys, $value = null ) {
3035 if ( is_array( $keys ) ) {
3036 foreach ( $keys as $key => $value ) {
3037 $this->mJsConfigVars
[$key] = $value;
3042 $this->mJsConfigVars
[$keys] = $value;
3046 * Get an array containing the variables to be set in mw.config in JavaScript.
3048 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3049 * - in other words, page-independent/site-wide variables (without state).
3050 * You will only be adding bloat to the html page and causing page caches to
3051 * have to be purged on configuration changes.
3054 public function getJSVars() {
3059 $canonicalSpecialPageName = false; # T23115
3061 $title = $this->getTitle();
3062 $ns = $title->getNamespace();
3063 $canonicalNamespace = MWNamespace
::exists( $ns )
3064 ? MWNamespace
::getCanonicalName( $ns )
3065 : $title->getNsText();
3067 $sk = $this->getSkin();
3068 // Get the relevant title so that AJAX features can use the correct page name
3069 // when making API requests from certain special pages (T36972).
3070 $relevantTitle = $sk->getRelevantTitle();
3071 $relevantUser = $sk->getRelevantUser();
3073 if ( $ns == NS_SPECIAL
) {
3074 list( $canonicalSpecialPageName, /*...*/ ) =
3075 SpecialPageFactory
::resolveAlias( $title->getDBkey() );
3076 } elseif ( $this->canUseWikiPage() ) {
3077 $wikiPage = $this->getWikiPage();
3078 $curRevisionId = $wikiPage->getLatest();
3079 $articleId = $wikiPage->getId();
3082 $lang = $title->getPageViewLanguage();
3084 // Pre-process information
3085 $separatorTransTable = $lang->separatorTransformTable();
3086 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : [];
3087 $compactSeparatorTransTable = [
3088 implode( "\t", array_keys( $separatorTransTable ) ),
3089 implode( "\t", $separatorTransTable ),
3091 $digitTransTable = $lang->digitTransformTable();
3092 $digitTransTable = $digitTransTable ?
$digitTransTable : [];
3093 $compactDigitTransTable = [
3094 implode( "\t", array_keys( $digitTransTable ) ),
3095 implode( "\t", $digitTransTable ),
3098 $user = $this->getUser();
3101 'wgCanonicalNamespace' => $canonicalNamespace,
3102 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3103 'wgNamespaceNumber' => $title->getNamespace(),
3104 'wgPageName' => $title->getPrefixedDBkey(),
3105 'wgTitle' => $title->getText(),
3106 'wgCurRevisionId' => $curRevisionId,
3107 'wgRevisionId' => (int)$this->getRevisionId(),
3108 'wgArticleId' => $articleId,
3109 'wgIsArticle' => $this->isArticle(),
3110 'wgIsRedirect' => $title->isRedirect(),
3111 'wgAction' => Action
::getActionName( $this->getContext() ),
3112 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3113 'wgUserGroups' => $user->getEffectiveGroups(),
3114 'wgCategories' => $this->getCategories(),
3115 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3116 'wgPageContentLanguage' => $lang->getCode(),
3117 'wgPageContentModel' => $title->getContentModel(),
3118 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3119 'wgDigitTransformTable' => $compactDigitTransTable,
3120 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3121 'wgMonthNames' => $lang->getMonthNamesArray(),
3122 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3123 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3124 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3125 'wgRequestId' => WebRequest
::getRequestId(),
3128 if ( $user->isLoggedIn() ) {
3129 $vars['wgUserId'] = $user->getId();
3130 $vars['wgUserEditCount'] = $user->getEditCount();
3131 $userReg = $user->getRegistration();
3132 $vars['wgUserRegistration'] = $userReg ?
wfTimestamp( TS_UNIX
, $userReg ) * 1000 : null;
3133 // Get the revision ID of the oldest new message on the user's talk
3134 // page. This can be used for constructing new message alerts on
3136 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3139 if ( $wgContLang->hasVariants() ) {
3140 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3142 // Same test as SkinTemplate
3143 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3144 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3146 $vars['wgRelevantPageIsProbablyEditable'] = $relevantTitle
3147 && $relevantTitle->quickUserCan( 'edit', $user )
3148 && ( $relevantTitle->exists() ||
$relevantTitle->quickUserCan( 'create', $user ) );
3150 foreach ( $title->getRestrictionTypes() as $type ) {
3151 // Following keys are set in $vars:
3152 // wgRestrictionCreate, wgRestrictionEdit, wgRestrictionMove, wgRestrictionUpload
3153 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3156 if ( $title->isMainPage() ) {
3157 $vars['wgIsMainPage'] = true;
3160 if ( $this->mRedirectedFrom
) {
3161 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3164 if ( $relevantUser ) {
3165 $vars['wgRelevantUserName'] = $relevantUser->getName();
3168 // Allow extensions to add their custom variables to the mw.config map.
3169 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3170 // page-dependant but site-wide (without state).
3171 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3172 Hooks
::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3174 // Merge in variables from addJsConfigVars last
3175 return array_merge( $vars, $this->getJsConfigVars() );
3179 * To make it harder for someone to slip a user a fake
3180 * user-JavaScript or user-CSS preview, a random token
3181 * is associated with the login session. If it's not
3182 * passed back with the preview request, we won't render
3187 public function userCanPreview() {
3188 $request = $this->getRequest();
3190 $request->getVal( 'action' ) !== 'submit' ||
3191 !$request->getCheck( 'wpPreview' ) ||
3192 !$request->wasPosted()
3197 $user = $this->getUser();
3199 if ( !$user->isLoggedIn() ) {
3200 // Anons have predictable edit tokens
3203 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3207 $title = $this->getTitle();
3208 if ( !$title->isJsSubpage() && !$title->isCssSubpage() ) {
3211 if ( !$title->isSubpageOf( $user->getUserPage() ) ) {
3212 // Don't execute another user's CSS or JS on preview (T85855)
3216 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3217 if ( count( $errors ) !== 0 ) {
3225 * @return array Array in format "link name or number => 'link html'".
3227 public function getHeadLinksArray() {
3231 $config = $this->getConfig();
3233 $canonicalUrl = $this->mCanonicalUrl
;
3235 $tags['meta-generator'] = Html
::element( 'meta', [
3236 'name' => 'generator',
3237 'content' => "MediaWiki $wgVersion",
3240 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3241 // Per https://w3c.github.io/webappsec-referrer-policy/#unknown-policy-values
3242 // fallbacks should come before the primary value so we need to reverse the array.
3243 foreach ( array_reverse( (array)$config->get( 'ReferrerPolicy' ) ) as $i => $policy ) {
3244 $tags["meta-referrer-$i"] = Html
::element( 'meta', [
3245 'name' => 'referrer',
3246 'content' => $policy,
3251 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3252 if ( $p !== 'index,follow' ) {
3253 // http://www.robotstxt.org/wc/meta-user.html
3254 // Only show if it's different from the default robots policy
3255 $tags['meta-robots'] = Html
::element( 'meta', [
3261 foreach ( $this->mMetatags
as $tag ) {
3262 if ( strncasecmp( $tag[0], 'http:', 5 ) === 0 ) {
3264 $tag[0] = substr( $tag[0], 5 );
3265 } elseif ( strncasecmp( $tag[0], 'og:', 3 ) === 0 ) {
3270 $tagName = "meta-{$tag[0]}";
3271 if ( isset( $tags[$tagName] ) ) {
3272 $tagName .= $tag[1];
3274 $tags[$tagName] = Html
::element( 'meta',
3277 'content' => $tag[1]
3282 foreach ( $this->mLinktags
as $tag ) {
3283 $tags[] = Html
::element( 'link', $tag );
3286 # Universal edit button
3287 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3288 $user = $this->getUser();
3289 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3290 && ( $this->getTitle()->exists() ||
3291 $this->getTitle()->quickUserCan( 'create', $user ) )
3293 // Original UniversalEditButton
3294 $msg = $this->msg( 'edit' )->text();
3295 $tags['universal-edit-button'] = Html
::element( 'link', [
3296 'rel' => 'alternate',
3297 'type' => 'application/x-wiki',
3299 'href' => $this->getTitle()->getEditURL(),
3301 // Alternate edit link
3302 $tags['alternative-edit'] = Html
::element( 'link', [
3305 'href' => $this->getTitle()->getEditURL(),
3310 # Generally the order of the favicon and apple-touch-icon links
3311 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3312 # uses whichever one appears later in the HTML source. Make sure
3313 # apple-touch-icon is specified first to avoid this.
3314 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3315 $tags['apple-touch-icon'] = Html
::element( 'link', [
3316 'rel' => 'apple-touch-icon',
3317 'href' => $config->get( 'AppleTouchIcon' )
3321 if ( $config->get( 'Favicon' ) !== false ) {
3322 $tags['favicon'] = Html
::element( 'link', [
3323 'rel' => 'shortcut icon',
3324 'href' => $config->get( 'Favicon' )
3328 # OpenSearch description link
3329 $tags['opensearch'] = Html
::element( 'link', [
3331 'type' => 'application/opensearchdescription+xml',
3332 'href' => wfScript( 'opensearch_desc' ),
3333 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3336 if ( $config->get( 'EnableAPI' ) ) {
3337 # Real Simple Discovery link, provides auto-discovery information
3338 # for the MediaWiki API (and potentially additional custom API
3339 # support such as WordPress or Twitter-compatible APIs for a
3340 # blogging extension, etc)
3341 $tags['rsd'] = Html
::element( 'link', [
3343 'type' => 'application/rsd+xml',
3344 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3345 // Whether RSD accepts relative or protocol-relative URLs is completely
3346 // undocumented, though.
3347 'href' => wfExpandUrl( wfAppendQuery(
3349 [ 'action' => 'rsd' ] ),
3356 if ( !$config->get( 'DisableLangConversion' ) ) {
3357 $lang = $this->getTitle()->getPageLanguage();
3358 if ( $lang->hasVariants() ) {
3359 $variants = $lang->getVariants();
3360 foreach ( $variants as $variant ) {
3361 $tags["variant-$variant"] = Html
::element( 'link', [
3362 'rel' => 'alternate',
3363 'hreflang' => LanguageCode
::bcp47( $variant ),
3364 'href' => $this->getTitle()->getLocalURL(
3365 [ 'variant' => $variant ] )
3369 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3370 $tags["variant-x-default"] = Html
::element( 'link', [
3371 'rel' => 'alternate',
3372 'hreflang' => 'x-default',
3373 'href' => $this->getTitle()->getLocalURL() ] );
3378 if ( $this->copyrightUrl
!== null ) {
3379 $copyright = $this->copyrightUrl
;
3382 if ( $config->get( 'RightsPage' ) ) {
3383 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3386 $copyright = $copy->getLocalURL();
3390 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3391 $copyright = $config->get( 'RightsUrl' );
3396 $tags['copyright'] = Html
::element( 'link', [
3398 'href' => $copyright ]
3403 if ( $config->get( 'Feed' ) ) {
3406 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3407 # Use the page name for the title. In principle, this could
3408 # lead to issues with having the same name for different feeds
3409 # corresponding to the same page, but we can't avoid that at
3412 $feedLinks[] = $this->feedLink(
3415 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3417 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3422 # Recent changes feed should appear on every page (except recentchanges,
3423 # that would be redundant). Put it after the per-page feed to avoid
3424 # changing existing behavior. It's still available, probably via a
3425 # menu in your browser. Some sites might have a different feed they'd
3426 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3427 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3428 # If so, use it instead.
3429 $sitename = $config->get( 'Sitename' );
3430 if ( $config->get( 'OverrideSiteFeed' ) ) {
3431 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3432 // Note, this->feedLink escapes the url.
3433 $feedLinks[] = $this->feedLink(
3436 $this->msg( "site-{$type}-feed", $sitename )->text()
3439 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3440 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3441 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3442 $feedLinks[] = $this->feedLink(
3444 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3445 # For grep: 'site-rss-feed', 'site-atom-feed'
3446 $this->msg( "site-{$format}-feed", $sitename )->text()
3451 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3452 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3453 # use OutputPage::addFeedLink() instead.
3454 Hooks
::run( 'AfterBuildFeedLinks', [ &$feedLinks ] );
3456 $tags +
= $feedLinks;
3460 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3461 if ( $canonicalUrl !== false ) {
3462 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3464 if ( $this->isArticleRelated() ) {
3465 // This affects all requests where "setArticleRelated" is true. This is
3466 // typically all requests that show content (query title, curid, oldid, diff),
3467 // and all wikipage actions (edit, delete, purge, info, history etc.).
3468 // It does not apply to File pages and Special pages.
3469 // 'history' and 'info' actions address page metadata rather than the page
3470 // content itself, so they may not be canonicalized to the view page url.
3471 // TODO: this ought to be better encapsulated in the Action class.
3472 $action = Action
::getActionName( $this->getContext() );
3473 if ( in_array( $action, [ 'history', 'info' ] ) ) {
3474 $query = "action={$action}";
3478 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3480 $reqUrl = $this->getRequest()->getRequestURL();
3481 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3485 if ( $canonicalUrl !== false ) {
3486 $tags[] = Html
::element( 'link', [
3487 'rel' => 'canonical',
3488 'href' => $canonicalUrl
3496 * Generate a "<link rel/>" for a feed.
3498 * @param string $type Feed type
3499 * @param string $url URL to the feed
3500 * @param string $text Value of the "title" attribute
3501 * @return string HTML fragment
3503 private function feedLink( $type, $url, $text ) {
3504 return Html
::element( 'link', [
3505 'rel' => 'alternate',
3506 'type' => "application/$type+xml",
3513 * Add a local or specified stylesheet, with the given media options.
3514 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3516 * @param string $style URL to the file
3517 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3518 * @param string $condition For IE conditional comments, specifying an IE version
3519 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3521 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3524 $options['media'] = $media;
3527 $options['condition'] = $condition;
3530 $options['dir'] = $dir;
3532 $this->styles
[$style] = $options;
3536 * Adds inline CSS styles
3537 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3539 * @param mixed $style_css Inline CSS
3540 * @param string $flip Set to 'flip' to flip the CSS if needed
3542 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3543 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3544 # If wanted, and the interface is right-to-left, flip the CSS
3545 $style_css = CSSJanus
::transform( $style_css, true, false );
3547 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3551 * Build exempt modules and legacy non-ResourceLoader styles.
3553 * @return string|WrappedStringList HTML
3555 protected function buildExemptModules() {
3559 // Things that go after the ResourceLoaderDynamicStyles marker
3562 // Exempt 'user' styles module (may need 'excludepages' for live preview)
3563 if ( $this->isUserCssPreview() ) {
3564 $append[] = $this->makeResourceLoaderLink(
3566 ResourceLoaderModule
::TYPE_STYLES
,
3567 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
3570 // Load the previewed CSS. Janus it if needed.
3571 // User-supplied CSS is assumed to in the wiki's content language.
3572 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3573 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3574 $previewedCSS = CSSJanus
::transform( $previewedCSS, true, false );
3576 $append[] = Html
::inlineStyle( $previewedCSS );
3579 // We want site, private and user styles to override dynamically added styles from
3580 // general modules, but we want dynamically added styles to override statically added
3581 // style modules. So the order has to be:
3582 // - page style modules (formatted by ResourceLoaderClientHtml::getHeadHtml())
3583 // - dynamically loaded styles (added by mw.loader before ResourceLoaderDynamicStyles)
3584 // - ResourceLoaderDynamicStyles marker
3585 // - site/private/user styles
3587 // Add legacy styles added through addStyle()/addInlineStyle() here
3588 $chunks[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3590 $chunks[] = Html
::element(
3592 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
3595 $separateReq = [ 'site.styles', 'user.styles' ];
3596 foreach ( $this->rlExemptStyleModules
as $group => $moduleNames ) {
3597 // Combinable modules
3598 $chunks[] = $this->makeResourceLoaderLink(
3599 array_diff( $moduleNames, $separateReq ),
3600 ResourceLoaderModule
::TYPE_STYLES
3603 foreach ( array_intersect( $moduleNames, $separateReq ) as $name ) {
3604 // These require their own dedicated request in order to support "@import"
3605 // syntax, which is incompatible with concatenation. (T147667, T37562)
3606 $chunks[] = $this->makeResourceLoaderLink( $name,
3607 ResourceLoaderModule
::TYPE_STYLES
3612 return self
::combineWrappedStrings( array_merge( $chunks, $append ) );
3618 public function buildCssLinksArray() {
3621 foreach ( $this->styles
as $file => $options ) {
3622 $link = $this->styleLink( $file, $options );
3624 $links[$file] = $link;
3631 * Generate \<link\> tags for stylesheets
3633 * @param string $style URL to the file
3634 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3635 * @return string HTML fragment
3637 protected function styleLink( $style, array $options ) {
3638 if ( isset( $options['dir'] ) ) {
3639 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3644 if ( isset( $options['media'] ) ) {
3645 $media = self
::transformCssMedia( $options['media'] );
3646 if ( is_null( $media ) ) {
3653 if ( substr( $style, 0, 1 ) == '/' ||
3654 substr( $style, 0, 5 ) == 'http:' ||
3655 substr( $style, 0, 6 ) == 'https:' ) {
3658 $config = $this->getConfig();
3659 $url = $config->get( 'StylePath' ) . '/' . $style . '?' .
3660 $config->get( 'StyleVersion' );
3663 $link = Html
::linkedStyle( $url, $media );
3665 if ( isset( $options['condition'] ) ) {
3666 $condition = htmlspecialchars( $options['condition'] );
3667 $link = "<!--[if $condition]>$link<![endif]-->";
3673 * Transform path to web-accessible static resource.
3675 * This is used to add a validation hash as query string.
3676 * This aids various behaviors:
3678 * - Put long Cache-Control max-age headers on responses for improved
3679 * cache performance.
3680 * - Get the correct version of a file as expected by the current page.
3681 * - Instantly get the updated version of a file after deployment.
3683 * Avoid using this for urls included in HTML as otherwise clients may get different
3684 * versions of a resource when navigating the site depending on when the page was cached.
3685 * If changes to the url propagate, this is not a problem (e.g. if the url is in
3686 * an external stylesheet).
3689 * @param Config $config
3690 * @param string $path Path-absolute URL to file (from document root, must start with "/")
3691 * @return string URL
3693 public static function transformResourcePath( Config
$config, $path ) {
3697 $remotePathPrefix = $config->get( 'ResourceBasePath' );
3698 if ( $remotePathPrefix === '' ) {
3699 // The configured base path is required to be empty string for
3700 // wikis in the domain root
3703 $remotePath = $remotePathPrefix;
3705 if ( strpos( $path, $remotePath ) !== 0 ||
substr( $path, 0, 2 ) === '//' ) {
3706 // - Path is outside wgResourceBasePath, ignore.
3707 // - Path is protocol-relative. Fixes T155310. Not supported by RelPath lib.
3710 // For files in resources, extensions/ or skins/, ResourceBasePath is preferred here.
3711 // For other misc files in $IP, we'll fallback to that as well. There is, however, a fourth
3712 // supported dir/path pair in the configuration (wgUploadDirectory, wgUploadPath)
3713 // which is not expected to be in wgResourceBasePath on CDNs. (T155146)
3714 $uploadPath = $config->get( 'UploadPath' );
3715 if ( strpos( $path, $uploadPath ) === 0 ) {
3716 $localDir = $config->get( 'UploadDirectory' );
3717 $remotePathPrefix = $remotePath = $uploadPath;
3720 $path = RelPath
::getRelativePath( $path, $remotePath );
3721 return self
::transformFilePath( $remotePathPrefix, $localDir, $path );
3725 * Utility method for transformResourceFilePath().
3727 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
3730 * @param string $remotePathPrefix URL path prefix that points to $localPath
3731 * @param string $localPath File directory exposed at $remotePath
3732 * @param string $file Path to target file relative to $localPath
3733 * @return string URL
3735 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
3736 $hash = md5_file( "$localPath/$file" );
3737 if ( $hash === false ) {
3738 wfLogWarning( __METHOD__
. ": Failed to hash $localPath/$file" );
3741 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
3745 * Transform "media" attribute based on request parameters
3747 * @param string $media Current value of the "media" attribute
3748 * @return string Modified value of the "media" attribute, or null to skip
3751 public static function transformCssMedia( $media ) {
3754 // https://www.w3.org/TR/css3-mediaqueries/#syntax
3755 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3757 // Switch in on-screen display for media testing
3759 'printable' => 'print',
3760 'handheld' => 'handheld',
3762 foreach ( $switches as $switch => $targetMedia ) {
3763 if ( $wgRequest->getBool( $switch ) ) {
3764 if ( $media == $targetMedia ) {
3766 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3767 /* This regex will not attempt to understand a comma-separated media_query_list
3769 * Example supported values for $media:
3770 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3771 * Example NOT supported value for $media:
3772 * '3d-glasses, screen, print and resolution > 90dpi'
3774 * If it's a print request, we never want any kind of screen stylesheets
3775 * If it's a handheld request (currently the only other choice with a switch),
3776 * we don't want simple 'screen' but we might want screen queries that
3777 * have a max-width or something, so we'll pass all others on and let the
3778 * client do the query.
3780 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3791 * Add a wikitext-formatted message to the output.
3792 * This is equivalent to:
3794 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3796 public function addWikiMsg( /*...*/ ) {
3797 $args = func_get_args();
3798 $name = array_shift( $args );
3799 $this->addWikiMsgArray( $name, $args );
3803 * Add a wikitext-formatted message to the output.
3804 * Like addWikiMsg() except the parameters are taken as an array
3805 * instead of a variable argument list.
3807 * @param string $name
3808 * @param array $args
3810 public function addWikiMsgArray( $name, $args ) {
3811 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3815 * This function takes a number of message/argument specifications, wraps them in
3816 * some overall structure, and then parses the result and adds it to the output.
3818 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3819 * and so on. The subsequent arguments may be either
3820 * 1) strings, in which case they are message names, or
3821 * 2) arrays, in which case, within each array, the first element is the message
3822 * name, and subsequent elements are the parameters to that message.
3824 * Don't use this for messages that are not in the user's interface language.
3828 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3832 * $wgOut->addWikiText( "<div class='error'>\n"
3833 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3835 * The newline after the opening div is needed in some wikitext. See T21226.
3837 * @param string $wrap
3839 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3840 $msgSpecs = func_get_args();
3841 array_shift( $msgSpecs );
3842 $msgSpecs = array_values( $msgSpecs );
3844 foreach ( $msgSpecs as $n => $spec ) {
3845 if ( is_array( $spec ) ) {
3847 $name = array_shift( $args );
3848 if ( isset( $args['options'] ) ) {
3849 unset( $args['options'] );
3851 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3859 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3861 $this->addWikiText( $s );
3865 * Whether the output has a table of contents
3869 public function isTOCEnabled() {
3870 return $this->mEnableTOC
;
3874 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3877 * @deprecated since 1.31, use $poOptions to addParserOutput() instead.
3879 public function enableSectionEditLinks( $flag = true ) {
3880 wfDeprecated( __METHOD__
, '1.31' );
3886 * @deprecated since 1.31, use $poOptions to addParserOutput() instead.
3888 public function sectionEditLinksEnabled() {
3889 wfDeprecated( __METHOD__
, '1.31' );
3894 * Helper function to setup the PHP implementation of OOUI to use in this request.
3897 * @param String $skinName The Skin name to determine the correct OOUI theme
3898 * @param String $dir Language direction
3900 public static function setupOOUI( $skinName = 'default', $dir = 'ltr' ) {
3901 $themes = ResourceLoaderOOUIModule
::getSkinThemeMap();
3902 $theme = isset( $themes[$skinName] ) ?
$themes[$skinName] : $themes['default'];
3903 // For example, 'OOUI\WikimediaUITheme'.
3904 $themeClass = "OOUI\\{$theme}Theme";
3905 OOUI\Theme
::setSingleton( new $themeClass() );
3906 OOUI\Element
::setDefaultDir( $dir );
3910 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
3911 * MediaWiki and this OutputPage instance.
3915 public function enableOOUI() {
3917 strtolower( $this->getSkin()->getSkinName() ),
3918 $this->getLanguage()->getDir()
3920 $this->addModuleStyles( [
3921 'oojs-ui-core.styles',
3922 'oojs-ui.styles.indicators',
3923 'oojs-ui.styles.textures',
3924 'mediawiki.widgets.styles',
3925 'oojs-ui.styles.icons-content',
3926 'oojs-ui.styles.icons-alerts',
3927 'oojs-ui.styles.icons-interactions',
3932 * Add Link headers for preloading the wiki's logo.
3936 protected function addLogoPreloadLinkHeaders() {
3937 $logo = ResourceLoaderSkinModule
::getLogo( $this->getConfig() );
3943 if ( !is_array( $logo ) ) {
3944 // No media queries required if we only have one variant
3945 $this->addLinkHeader( '<' . $logo . '>;rel=preload;as=image' );
3949 if ( isset( $logo['svg'] ) ) {
3950 // No media queries required if we only have a 1x and svg variant
3951 // because all preload-capable browsers support SVGs
3952 $this->addLinkHeader( '<' . $logo['svg'] . '>;rel=preload;as=image' );
3956 foreach ( $logo as $dppx => $src ) {
3957 // Keys are in this format: "1.5x"
3958 $dppx = substr( $dppx, 0, -1 );
3959 $logosPerDppx[$dppx] = $src;
3962 // Because PHP can't have floats as array keys
3963 uksort( $logosPerDppx, function ( $a , $b ) {
3964 $a = floatval( $a );
3965 $b = floatval( $b );
3970 // Sort from smallest to largest (e.g. 1x, 1.5x, 2x)
3971 return ( $a < $b ) ?
-1 : 1;
3974 foreach ( $logosPerDppx as $dppx => $src ) {
3975 $logos[] = [ 'dppx' => $dppx, 'src' => $src ];
3978 $logosCount = count( $logos );
3979 // Logic must match ResourceLoaderSkinModule:
3980 // - 1x applies to resolution < 1.5dppx
3981 // - 1.5x applies to resolution >= 1.5dppx && < 2dppx
3982 // - 2x applies to resolution >= 2dppx
3983 // Note that min-resolution and max-resolution are both inclusive.
3984 for ( $i = 0; $i < $logosCount; $i++
) {
3987 // min-resolution is ">=" (larger than or equal to)
3988 // "not min-resolution" is essentially "<"
3989 $media_query = 'not all and (min-resolution: ' . $logos[ 1 ]['dppx'] . 'dppx)';
3990 } elseif ( $i !== $logosCount - 1 ) {
3992 // Media query expressions can only apply "not" to the entire expression
3993 // (e.g. can't express ">= 1.5 and not >= 2).
3994 // Workaround: Use <= 1.9999 in place of < 2.
3995 $upper_bound = floatval( $logos[ $i +
1 ]['dppx'] ) - 0.000001;
3996 $media_query = '(min-resolution: ' . $logos[ $i ]['dppx'] .
3997 'dppx) and (max-resolution: ' . $upper_bound . 'dppx)';
4000 $media_query = '(min-resolution: ' . $logos[ $i ]['dppx'] . 'dppx)';
4003 $this->addLinkHeader(
4004 '<' . $logos[$i]['src'] . '>;rel=preload;as=image;media=' . $media_query