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\Session\SessionManager
;
25 use WrappedString\WrappedString
;
26 use WrappedString\WrappedStringList
;
29 * This class should be covered by a general architecture document which does
30 * not exist as of January 2011. This is one of the Core classes and should
31 * be read at least once by any new developers.
33 * This class is used to prepare the final rendering. A skin is then
34 * applied to the output parameters (links, javascript, html, categories ...).
36 * @todo FIXME: Another class handles sending the whole page to the client.
38 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
43 class OutputPage
extends ContextSource
{
44 /** @var array Should be private. Used with addMeta() which adds "<meta>" */
45 protected $mMetatags = [];
48 protected $mLinktags = [];
51 protected $mCanonicalUrl = false;
54 * @var array Additional stylesheets. Looks like this is for extensions.
55 * Might be replaced by ResourceLoader.
57 protected $mExtStyles = [];
60 * @var string Should be private - has getter and setter. Contains
62 public $mPagetitle = '';
65 * @var string Contains all of the "<body>" content. Should be private we
66 * got set/get accessors and the append() method.
68 public $mBodytext = '';
70 /** @var string Stores contents of "<title>" tag */
71 private $mHTMLtitle = '';
74 * @var bool Is the displayed content related to the source of the
75 * corresponding wiki article.
77 private $mIsarticle = false;
79 /** @var bool Stores "article flag" toggle. */
80 private $mIsArticleRelated = true;
83 * @var bool We have to set isPrintable(). Some pages should
84 * never be printed (ex: redirections).
86 private $mPrintable = false;
89 * @var array Contains the page subtitle. Special pages usually have some
90 * links here. Don't confuse with site subtitle added by skins.
92 private $mSubtitle = [];
95 public $mRedirect = '';
98 protected $mStatusCode;
101 * @var string Used for sending cache control.
102 * The whole caching system should probably be moved into its own class.
104 protected $mLastModified = '';
107 protected $mCategoryLinks = [];
110 protected $mCategories = [];
113 protected $mIndicators = [];
115 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
116 private $mLanguageLinks = [];
119 * Used for JavaScript (predates ResourceLoader)
120 * @todo We should split JS / CSS.
121 * mScripts content is inserted as is in "<head>" by Skin. This might
122 * contain either a link to a stylesheet or inline CSS.
124 private $mScripts = '';
126 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
127 protected $mInlineStyles = '';
130 * @var string Used by skin template.
131 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
133 public $mPageLinkTitle = '';
135 /** @var array Array of elements in "<head>". Parser might add its own headers! */
136 protected $mHeadItems = [];
139 protected $mModules = [];
142 protected $mModuleScripts = [];
145 protected $mModuleStyles = [];
147 /** @var ResourceLoader */
148 protected $mResourceLoader;
150 /** @var ResourceLoaderClientHtml */
153 /** @var ResourceLoaderContext */
154 private $rlClientContext;
157 private $rlUserModuleState;
160 private $rlExemptStyleModules;
163 protected $mJsConfigVars = [];
166 protected $mTemplateIds = [];
169 protected $mImageTimeKeys = [];
172 public $mRedirectCode = '';
174 protected $mFeedLinksAppendQuery = null;
177 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
178 * @see ResourceLoaderModule::$origin
179 * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
181 protected $mAllowedModules = [
182 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
185 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
186 protected $mDoNothing = false;
191 protected $mContainsNewMagic = 0;
194 * lazy initialised, use parserOptions()
197 protected $mParserOptions = null;
200 * Handles the Atom / RSS links.
201 * We probably only support Atom in 2011.
202 * @see $wgAdvertisedFeedTypes
204 private $mFeedLinks = [];
206 // Gwicke work on squid caching? Roughly from 2003.
207 protected $mEnableClientCache = true;
209 /** @var bool Flag if output should only contain the body of the article. */
210 private $mArticleBodyOnly = false;
213 protected $mNewSectionLink = false;
216 protected $mHideNewSectionLink = false;
219 * @var bool Comes from the parser. This was probably made to load CSS/JS
220 * only if we had "<gallery>". Used directly in CategoryPage.php.
221 * Looks like ResourceLoader can replace this.
223 public $mNoGallery = false;
226 private $mPageTitleActionText = '';
228 /** @var int Cache stuff. Looks like mEnableClientCache */
229 protected $mCdnMaxage = 0;
230 /** @var int Upper limit on mCdnMaxage */
231 protected $mCdnMaxageLimit = INF
;
234 * @var bool Controls if anti-clickjacking / frame-breaking headers will
235 * be sent. This should be done for pages where edit actions are possible.
236 * Setters: $this->preventClickjacking() and $this->allowClickjacking().
238 protected $mPreventClickjacking = true;
240 /** @var int To include the variable {{REVISIONID}} */
241 private $mRevisionId = null;
244 private $mRevisionTimestamp = null;
247 protected $mFileVersion = null;
250 * @var array An array of stylesheet filenames (relative from skins path),
251 * with options for CSS media, IE conditions, and RTL/LTR direction.
252 * For internal use; add settings in the skin via $this->addStyle()
254 * Style again! This seems like a code duplication since we already have
255 * mStyles. This is what makes Open Source amazing.
257 protected $styles = [];
259 private $mIndexPolicy = 'index';
260 private $mFollowPolicy = 'follow';
261 private $mVaryHeader = [
262 'Accept-Encoding' => [ 'match=gzip' ],
266 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
271 private $mRedirectedFrom = null;
274 * Additional key => value data
276 private $mProperties = [];
279 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
281 private $mTarget = null;
284 * @var bool Whether parser output should contain table of contents
286 private $mEnableTOC = true;
289 * @var bool Whether parser output should contain section edit links
291 private $mEnableSectionEditLinks = true;
294 * @var string|null The URL to send in a <link> element with rel=copyright
296 private $copyrightUrl;
298 /** @var array Profiling data */
299 private $limitReportData = [];
302 * Constructor for OutputPage. This should not be called directly.
303 * Instead a new RequestContext should be created and it will implicitly create
304 * a OutputPage tied to that context.
305 * @param IContextSource|null $context
307 function __construct( IContextSource
$context = null ) {
308 if ( $context === null ) {
309 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
310 wfDeprecated( __METHOD__
, '1.18' );
312 $this->setContext( $context );
317 * Redirect to $url rather than displaying the normal page
319 * @param string $url URL
320 * @param string $responsecode HTTP status code
322 public function redirect( $url, $responsecode = '302' ) {
323 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
324 $this->mRedirect
= str_replace( "\n", '', $url );
325 $this->mRedirectCode
= $responsecode;
329 * Get the URL to redirect to, or an empty string if not redirect URL set
333 public function getRedirect() {
334 return $this->mRedirect
;
338 * Set the copyright URL to send with the output.
339 * Empty string to omit, null to reset.
343 * @param string|null $url
345 public function setCopyrightUrl( $url ) {
346 $this->copyrightUrl
= $url;
350 * Set the HTTP status code to send with the output.
352 * @param int $statusCode
354 public function setStatusCode( $statusCode ) {
355 $this->mStatusCode
= $statusCode;
359 * Add a new "<meta>" tag
360 * To add an http-equiv meta tag, precede the name with "http:"
362 * @param string $name Tag name
363 * @param string $val Tag value
365 function addMeta( $name, $val ) {
366 array_push( $this->mMetatags
, [ $name, $val ] );
370 * Returns the current <meta> tags
375 public function getMetaTags() {
376 return $this->mMetatags
;
380 * Add a new \<link\> tag to the page header.
382 * Note: use setCanonicalUrl() for rel=canonical.
384 * @param array $linkarr Associative array of attributes.
386 function addLink( array $linkarr ) {
387 array_push( $this->mLinktags
, $linkarr );
391 * Returns the current <link> tags
396 public function getLinkTags() {
397 return $this->mLinktags
;
401 * Add a new \<link\> with "rel" attribute set to "meta"
403 * @param array $linkarr Associative array mapping attribute names to their
404 * values, both keys and values will be escaped, and the
405 * "rel" attribute will be automatically added
407 function addMetadataLink( array $linkarr ) {
408 $linkarr['rel'] = $this->getMetadataAttribute();
409 $this->addLink( $linkarr );
413 * Set the URL to be used for the <link rel=canonical>. This should be used
414 * in preference to addLink(), to avoid duplicate link tags.
417 function setCanonicalUrl( $url ) {
418 $this->mCanonicalUrl
= $url;
422 * Returns the URL to be used for the <link rel=canonical> if
426 * @return bool|string
428 public function getCanonicalUrl() {
429 return $this->mCanonicalUrl
;
433 * Get the value of the "rel" attribute for metadata links
437 public function getMetadataAttribute() {
438 # note: buggy CC software only reads first "meta" link
439 static $haveMeta = false;
441 return 'alternate meta';
449 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
450 * Internal use only. Use OutputPage::addModules() or OutputPage::addJsConfigVars()
453 * @param string $script Raw HTML
455 function addScript( $script ) {
456 $this->mScripts
.= $script;
460 * Register and add a stylesheet from an extension directory.
462 * @deprecated since 1.27 use addModuleStyles() or addStyle() instead
463 * @param string $url Path to sheet. Provide either a full url (beginning
464 * with 'http', etc) or a relative path from the document root
465 * (beginning with '/'). Otherwise it behaves identically to
466 * addStyle() and draws from the /skins folder.
468 public function addExtensionStyle( $url ) {
469 wfDeprecated( __METHOD__
, '1.27' );
470 array_push( $this->mExtStyles
, $url );
474 * Get all styles added by extensions
476 * @deprecated since 1.27
479 function getExtStyle() {
480 wfDeprecated( __METHOD__
, '1.27' );
481 return $this->mExtStyles
;
485 * Add a JavaScript file out of skins/common, or a given relative path.
486 * Internal use only. Use OutputPage::addModules() if possible.
488 * @param string $file Filename in skins/common or complete on-server path
490 * @param string $version Style version of the file. Defaults to $wgStyleVersion
492 public function addScriptFile( $file, $version = null ) {
493 // See if $file parameter is an absolute URL or begins with a slash
494 if ( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
497 $path = $this->getConfig()->get( 'StylePath' ) . "/common/{$file}";
499 if ( is_null( $version ) ) {
500 $version = $this->getConfig()->get( 'StyleVersion' );
502 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
506 * Add a self-contained script tag with the given contents
507 * Internal use only. Use OutputPage::addModules() if possible.
509 * @param string $script JavaScript text, no script tags
511 public function addInlineScript( $script ) {
512 $this->mScripts
.= Html
::inlineScript( $script );
516 * Filter an array of modules to remove insufficiently trustworthy members, and modules
517 * which are no longer registered (eg a page is cached before an extension is disabled)
518 * @param array $modules
519 * @param string|null $position If not null, only return modules with this position
520 * @param string $type
523 protected function filterModules( array $modules, $position = null,
524 $type = ResourceLoaderModule
::TYPE_COMBINED
526 $resourceLoader = $this->getResourceLoader();
527 $filteredModules = [];
528 foreach ( $modules as $val ) {
529 $module = $resourceLoader->getModule( $val );
530 if ( $module instanceof ResourceLoaderModule
531 && $module->getOrigin() <= $this->getAllowedModules( $type )
532 && ( is_null( $position ) ||
$module->getPosition() == $position )
533 && ( !$this->mTarget ||
in_array( $this->mTarget
, $module->getTargets() ) )
535 $filteredModules[] = $val;
538 return $filteredModules;
542 * Get the list of modules to include on this page
544 * @param bool $filter Whether to filter out insufficiently trustworthy modules
545 * @param string|null $position If not null, only return modules with this position
546 * @param string $param
547 * @return array Array of module names
549 public function getModules( $filter = false, $position = null, $param = 'mModules',
550 $type = ResourceLoaderModule
::TYPE_COMBINED
552 $modules = array_values( array_unique( $this->$param ) );
554 ?
$this->filterModules( $modules, $position, $type )
559 * Add one or more modules recognized by ResourceLoader. Modules added
560 * through this function will be loaded by ResourceLoader when the
563 * @param string|array $modules Module name (string) or array of module names
565 public function addModules( $modules ) {
566 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
570 * Get the list of module JS to include on this page
572 * @param bool $filter
573 * @param string|null $position
574 * @return array Array of module names
576 public function getModuleScripts( $filter = false, $position = null ) {
577 return $this->getModules( $filter, $position, 'mModuleScripts',
578 ResourceLoaderModule
::TYPE_SCRIPTS
583 * Add only JS of one or more modules recognized by ResourceLoader. Module
584 * scripts added through this function will be loaded by ResourceLoader when
587 * @param string|array $modules Module name (string) or array of module names
589 public function addModuleScripts( $modules ) {
590 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
594 * Get the list of module CSS to include on this page
596 * @param bool $filter
597 * @param string|null $position
598 * @return array Array of module names
600 public function getModuleStyles( $filter = false, $position = null ) {
601 return $this->getModules( $filter, $position, 'mModuleStyles',
602 ResourceLoaderModule
::TYPE_STYLES
607 * Add only CSS of one or more modules recognized by ResourceLoader.
609 * Module styles added through this function will be added using standard link CSS
610 * tags, rather than as a combined Javascript and CSS package. Thus, they will
611 * load when JavaScript is disabled (unless CSS also happens to be disabled).
613 * @param string|array $modules Module name (string) or array of module names
615 public function addModuleStyles( $modules ) {
616 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
620 * @return null|string ResourceLoader target
622 public function getTarget() {
623 return $this->mTarget
;
627 * Sets ResourceLoader target for load.php links. If null, will be omitted
629 * @param string|null $target
631 public function setTarget( $target ) {
632 $this->mTarget
= $target;
636 * Get an array of head items
640 function getHeadItemsArray() {
641 return $this->mHeadItems
;
645 * Add or replace a head item to the output
647 * Whenever possible, use more specific options like ResourceLoader modules,
648 * OutputPage::addLink(), OutputPage::addMetaLink() and OutputPage::addFeedLink()
649 * Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
650 * OutputPage::addInlineScript() and OutputPage::addInlineStyle()
651 * This would be your very LAST fallback.
653 * @param string $name Item name
654 * @param string $value Raw HTML
656 public function addHeadItem( $name, $value ) {
657 $this->mHeadItems
[$name] = $value;
661 * Add one or more head items to the output
664 * @param string|string[] $value Raw HTML
666 public function addHeadItems( $values ) {
667 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$values );
671 * Check if the header item $name is already set
673 * @param string $name Item name
676 public function hasHeadItem( $name ) {
677 return isset( $this->mHeadItems
[$name] );
681 * @deprecated since 1.28 Obsolete - wgUseETag experiment was removed.
684 public function setETag( $tag ) {
688 * Set whether the output should only contain the body of the article,
689 * without any skin, sidebar, etc.
690 * Used e.g. when calling with "action=render".
692 * @param bool $only Whether to output only the body of the article
694 public function setArticleBodyOnly( $only ) {
695 $this->mArticleBodyOnly
= $only;
699 * Return whether the output will contain only the body of the article
703 public function getArticleBodyOnly() {
704 return $this->mArticleBodyOnly
;
708 * Set an additional output property
711 * @param string $name
712 * @param mixed $value
714 public function setProperty( $name, $value ) {
715 $this->mProperties
[$name] = $value;
719 * Get an additional output property
722 * @param string $name
723 * @return mixed Property value or null if not found
725 public function getProperty( $name ) {
726 if ( isset( $this->mProperties
[$name] ) ) {
727 return $this->mProperties
[$name];
734 * checkLastModified tells the client to use the client-cached page if
735 * possible. If successful, the OutputPage is disabled so that
736 * any future call to OutputPage->output() have no effect.
738 * Side effect: sets mLastModified for Last-Modified header
740 * @param string $timestamp
742 * @return bool True if cache-ok headers was sent.
744 public function checkLastModified( $timestamp ) {
745 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
746 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
749 $config = $this->getConfig();
750 if ( !$config->get( 'CachePages' ) ) {
751 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
755 $timestamp = wfTimestamp( TS_MW
, $timestamp );
757 'page' => $timestamp,
758 'user' => $this->getUser()->getTouched(),
759 'epoch' => $config->get( 'CacheEpoch' )
761 if ( $config->get( 'UseSquid' ) ) {
762 // bug 44570: the core page itself may not change, but resources might
763 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, time() - $config->get( 'SquidMaxage' ) );
765 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this ] );
767 $maxModified = max( $modifiedTimes );
768 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
770 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
771 if ( $clientHeader === false ) {
772 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header", 'private' );
776 # IE sends sizes after the date like this:
777 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
778 # this breaks strtotime().
779 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
781 MediaWiki\
suppressWarnings(); // E_STRICT system time bitching
782 $clientHeaderTime = strtotime( $clientHeader );
783 MediaWiki\restoreWarnings
();
784 if ( !$clientHeaderTime ) {
786 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
789 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
793 foreach ( $modifiedTimes as $name => $value ) {
794 if ( $info !== '' ) {
797 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
800 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
801 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ), 'private' );
802 wfDebug( __METHOD__
. ": effective Last-Modified: " .
803 wfTimestamp( TS_ISO_8601
, $maxModified ), 'private' );
804 if ( $clientHeaderTime < $maxModified ) {
805 wfDebug( __METHOD__
. ": STALE, $info", 'private' );
810 # Give a 304 Not Modified response code and disable body output
811 wfDebug( __METHOD__
. ": NOT MODIFIED, $info", 'private' );
812 ini_set( 'zlib.output_compression', 0 );
813 $this->getRequest()->response()->statusHeader( 304 );
814 $this->sendCacheControl();
817 // Don't output a compressed blob when using ob_gzhandler;
818 // it's technically against HTTP spec and seems to confuse
819 // Firefox when the response gets split over two packets.
820 wfClearOutputBuffers();
826 * Override the last modified timestamp
828 * @param string $timestamp New timestamp, in a format readable by
831 public function setLastModified( $timestamp ) {
832 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
836 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
838 * @param string $policy The literal string to output as the contents of
839 * the meta tag. Will be parsed according to the spec and output in
843 public function setRobotPolicy( $policy ) {
844 $policy = Article
::formatRobotPolicy( $policy );
846 if ( isset( $policy['index'] ) ) {
847 $this->setIndexPolicy( $policy['index'] );
849 if ( isset( $policy['follow'] ) ) {
850 $this->setFollowPolicy( $policy['follow'] );
855 * Set the index policy for the page, but leave the follow policy un-
858 * @param string $policy Either 'index' or 'noindex'.
861 public function setIndexPolicy( $policy ) {
862 $policy = trim( $policy );
863 if ( in_array( $policy, [ 'index', 'noindex' ] ) ) {
864 $this->mIndexPolicy
= $policy;
869 * Set the follow policy for the page, but leave the index policy un-
872 * @param string $policy Either 'follow' or 'nofollow'.
875 public function setFollowPolicy( $policy ) {
876 $policy = trim( $policy );
877 if ( in_array( $policy, [ 'follow', 'nofollow' ] ) ) {
878 $this->mFollowPolicy
= $policy;
883 * Set the new value of the "action text", this will be added to the
884 * "HTML title", separated from it with " - ".
886 * @param string $text New value of the "action text"
888 public function setPageTitleActionText( $text ) {
889 $this->mPageTitleActionText
= $text;
893 * Get the value of the "action text"
897 public function getPageTitleActionText() {
898 return $this->mPageTitleActionText
;
902 * "HTML title" means the contents of "<title>".
903 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
905 * @param string|Message $name
907 public function setHTMLTitle( $name ) {
908 if ( $name instanceof Message
) {
909 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
911 $this->mHTMLtitle
= $name;
916 * Return the "HTML title", i.e. the content of the "<title>" tag.
920 public function getHTMLTitle() {
921 return $this->mHTMLtitle
;
925 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
929 public function setRedirectedFrom( $t ) {
930 $this->mRedirectedFrom
= $t;
934 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
935 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
936 * but not bad tags like \<script\>. This function automatically sets
937 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
938 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
939 * good tags like \<i\> will be dropped entirely.
941 * @param string|Message $name
943 public function setPageTitle( $name ) {
944 if ( $name instanceof Message
) {
945 $name = $name->setContext( $this->getContext() )->text();
948 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
949 # but leave "<i>foobar</i>" alone
950 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
951 $this->mPagetitle
= $nameWithTags;
953 # change "<i>foo&bar</i>" to "foo&bar"
955 $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) )
956 ->inContentLanguage()
961 * Return the "page title", i.e. the content of the \<h1\> tag.
965 public function getPageTitle() {
966 return $this->mPagetitle
;
970 * Set the Title object to use
974 public function setTitle( Title
$t ) {
975 $this->getContext()->setTitle( $t );
979 * Replace the subtitle with $str
981 * @param string|Message $str New value of the subtitle. String should be safe HTML.
983 public function setSubtitle( $str ) {
984 $this->clearSubtitle();
985 $this->addSubtitle( $str );
989 * Add $str to the subtitle
991 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
993 public function addSubtitle( $str ) {
994 if ( $str instanceof Message
) {
995 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
997 $this->mSubtitle
[] = $str;
1002 * Build message object for a subtitle containing a backlink to a page
1004 * @param Title $title Title to link to
1005 * @param array $query Array of additional parameters to include in the link
1009 public static function buildBacklinkSubtitle( Title
$title, $query = [] ) {
1010 if ( $title->isRedirect() ) {
1011 $query['redirect'] = 'no';
1013 return wfMessage( 'backlinksubtitle' )
1014 ->rawParams( Linker
::link( $title, null, [], $query ) );
1018 * Add a subtitle containing a backlink to a page
1020 * @param Title $title Title to link to
1021 * @param array $query Array of additional parameters to include in the link
1023 public function addBacklinkSubtitle( Title
$title, $query = [] ) {
1024 $this->addSubtitle( self
::buildBacklinkSubtitle( $title, $query ) );
1028 * Clear the subtitles
1030 public function clearSubtitle() {
1031 $this->mSubtitle
= [];
1039 public function getSubtitle() {
1040 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1044 * Set the page as printable, i.e. it'll be displayed with all
1045 * print styles included
1047 public function setPrintable() {
1048 $this->mPrintable
= true;
1052 * Return whether the page is "printable"
1056 public function isPrintable() {
1057 return $this->mPrintable
;
1061 * Disable output completely, i.e. calling output() will have no effect
1063 public function disable() {
1064 $this->mDoNothing
= true;
1068 * Return whether the output will be completely disabled
1072 public function isDisabled() {
1073 return $this->mDoNothing
;
1077 * Show an "add new section" link?
1081 public function showNewSectionLink() {
1082 return $this->mNewSectionLink
;
1086 * Forcibly hide the new section link?
1090 public function forceHideNewSectionLink() {
1091 return $this->mHideNewSectionLink
;
1095 * Add or remove feed links in the page header
1096 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1097 * for the new version
1098 * @see addFeedLink()
1100 * @param bool $show True: add default feeds, false: remove all feeds
1102 public function setSyndicated( $show = true ) {
1104 $this->setFeedAppendQuery( false );
1106 $this->mFeedLinks
= [];
1111 * Add default feeds to the page header
1112 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1113 * for the new version
1114 * @see addFeedLink()
1116 * @param string $val Query to append to feed links or false to output
1119 public function setFeedAppendQuery( $val ) {
1120 $this->mFeedLinks
= [];
1122 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1123 $query = "feed=$type";
1124 if ( is_string( $val ) ) {
1125 $query .= '&' . $val;
1127 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1132 * Add a feed link to the page header
1134 * @param string $format Feed type, should be a key of $wgFeedClasses
1135 * @param string $href URL
1137 public function addFeedLink( $format, $href ) {
1138 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1139 $this->mFeedLinks
[$format] = $href;
1144 * Should we output feed links for this page?
1147 public function isSyndicated() {
1148 return count( $this->mFeedLinks
) > 0;
1152 * Return URLs for each supported syndication format for this page.
1153 * @return array Associating format keys with URLs
1155 public function getSyndicationLinks() {
1156 return $this->mFeedLinks
;
1160 * Will currently always return null
1164 public function getFeedAppendQuery() {
1165 return $this->mFeedLinksAppendQuery
;
1169 * Set whether the displayed content is related to the source of the
1170 * corresponding article on the wiki
1171 * Setting true will cause the change "article related" toggle to true
1175 public function setArticleFlag( $v ) {
1176 $this->mIsarticle
= $v;
1178 $this->mIsArticleRelated
= $v;
1183 * Return whether the content displayed page is related to the source of
1184 * the corresponding article on the wiki
1188 public function isArticle() {
1189 return $this->mIsarticle
;
1193 * Set whether this page is related an article on the wiki
1194 * Setting false will cause the change of "article flag" toggle to false
1198 public function setArticleRelated( $v ) {
1199 $this->mIsArticleRelated
= $v;
1201 $this->mIsarticle
= false;
1206 * Return whether this page is related an article on the wiki
1210 public function isArticleRelated() {
1211 return $this->mIsArticleRelated
;
1215 * Add new language links
1217 * @param array $newLinkArray Associative array mapping language code to the page
1220 public function addLanguageLinks( array $newLinkArray ) {
1221 $this->mLanguageLinks +
= $newLinkArray;
1225 * Reset the language links and add new language links
1227 * @param array $newLinkArray Associative array mapping language code to the page
1230 public function setLanguageLinks( array $newLinkArray ) {
1231 $this->mLanguageLinks
= $newLinkArray;
1235 * Get the list of language links
1237 * @return array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1239 public function getLanguageLinks() {
1240 return $this->mLanguageLinks
;
1244 * Add an array of categories, with names in the keys
1246 * @param array $categories Mapping category name => sort key
1248 public function addCategoryLinks( array $categories ) {
1251 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1255 # Add the links to a LinkBatch
1256 $arr = [ NS_CATEGORY
=> $categories ];
1257 $lb = new LinkBatch
;
1258 $lb->setArray( $arr );
1260 # Fetch existence plus the hiddencat property
1261 $dbr = wfGetDB( DB_REPLICA
);
1262 $fields = array_merge(
1263 LinkCache
::getSelectFields(),
1264 [ 'page_namespace', 'page_title', 'pp_value' ]
1267 $res = $dbr->select( [ 'page', 'page_props' ],
1269 $lb->constructSet( 'page', $dbr ),
1272 [ 'page_props' => [ 'LEFT JOIN', [
1273 'pp_propname' => 'hiddencat',
1278 # Add the results to the link cache
1279 $lb->addResultToCache( LinkCache
::singleton(), $res );
1281 # Set all the values to 'normal'.
1282 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1284 # Mark hidden categories
1285 foreach ( $res as $row ) {
1286 if ( isset( $row->pp_value
) ) {
1287 $categories[$row->page_title
] = 'hidden';
1291 # Add the remaining categories to the skin
1293 'OutputPageMakeCategoryLinks',
1294 [ &$this, $categories, &$this->mCategoryLinks
] )
1296 foreach ( $categories as $category => $type ) {
1297 // array keys will cast numeric category names to ints, so cast back to string
1298 $category = (string)$category;
1299 $origcategory = $category;
1300 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1304 $wgContLang->findVariantLink( $category, $title, true );
1305 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1308 $text = $wgContLang->convertHtml( $title->getText() );
1309 $this->mCategories
[] = $title->getText();
1310 $this->mCategoryLinks
[$type][] = Linker
::link( $title, $text );
1316 * Reset the category links (but not the category list) and add $categories
1318 * @param array $categories Mapping category name => sort key
1320 public function setCategoryLinks( array $categories ) {
1321 $this->mCategoryLinks
= [];
1322 $this->addCategoryLinks( $categories );
1326 * Get the list of category links, in a 2-D array with the following format:
1327 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1328 * hidden categories) and $link a HTML fragment with a link to the category
1333 public function getCategoryLinks() {
1334 return $this->mCategoryLinks
;
1338 * Get the list of category names this page belongs to
1340 * @return array Array of strings
1342 public function getCategories() {
1343 return $this->mCategories
;
1347 * Add an array of indicators, with their identifiers as array
1348 * keys and HTML contents as values.
1350 * In case of duplicate keys, existing values are overwritten.
1352 * @param array $indicators
1355 public function setIndicators( array $indicators ) {
1356 $this->mIndicators
= $indicators +
$this->mIndicators
;
1357 // Keep ordered by key
1358 ksort( $this->mIndicators
);
1362 * Get the indicators associated with this page.
1364 * The array will be internally ordered by item keys.
1366 * @return array Keys: identifiers, values: HTML contents
1369 public function getIndicators() {
1370 return $this->mIndicators
;
1374 * Adds help link with an icon via page indicators.
1375 * Link target can be overridden by a local message containing a wikilink:
1376 * the message key is: lowercase action or special page name + '-helppage'.
1377 * @param string $to Target MediaWiki.org page title or encoded URL.
1378 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1381 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1382 $this->addModuleStyles( 'mediawiki.helplink' );
1383 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1385 if ( $overrideBaseUrl ) {
1388 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1389 $helpUrl = "//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1392 $link = Html
::rawElement(
1396 'target' => '_blank',
1397 'class' => 'mw-helplink',
1402 $this->setIndicators( [ 'mw-helplink' => $link ] );
1406 * Do not allow scripts which can be modified by wiki users to load on this page;
1407 * only allow scripts bundled with, or generated by, the software.
1408 * Site-wide styles are controlled by a config setting, since they can be
1409 * used to create a custom skin/theme, but not user-specific ones.
1411 * @todo this should be given a more accurate name
1413 public function disallowUserJs() {
1414 $this->reduceAllowedModules(
1415 ResourceLoaderModule
::TYPE_SCRIPTS
,
1416 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1419 // Site-wide styles are controlled by a config setting, see bug 71621
1420 // for background on why. User styles are never allowed.
1421 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1422 $styleOrigin = ResourceLoaderModule
::ORIGIN_USER_SITEWIDE
;
1424 $styleOrigin = ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
;
1426 $this->reduceAllowedModules(
1427 ResourceLoaderModule
::TYPE_STYLES
,
1433 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1434 * @see ResourceLoaderModule::$origin
1435 * @param string $type ResourceLoaderModule TYPE_ constant
1436 * @return int ResourceLoaderModule ORIGIN_ class constant
1438 public function getAllowedModules( $type ) {
1439 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1440 return min( array_values( $this->mAllowedModules
) );
1442 return isset( $this->mAllowedModules
[$type] )
1443 ?
$this->mAllowedModules
[$type]
1444 : ResourceLoaderModule
::ORIGIN_ALL
;
1449 * Limit the highest level of CSS/JS untrustworthiness allowed.
1451 * If passed the same or a higher level than the current level of untrustworthiness set, the
1452 * level will remain unchanged.
1454 * @param string $type
1455 * @param int $level ResourceLoaderModule class constant
1457 public function reduceAllowedModules( $type, $level ) {
1458 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1462 * Prepend $text to the body HTML
1464 * @param string $text HTML
1466 public function prependHTML( $text ) {
1467 $this->mBodytext
= $text . $this->mBodytext
;
1471 * Append $text to the body HTML
1473 * @param string $text HTML
1475 public function addHTML( $text ) {
1476 $this->mBodytext
.= $text;
1480 * Shortcut for adding an Html::element via addHTML.
1484 * @param string $element
1485 * @param array $attribs
1486 * @param string $contents
1488 public function addElement( $element, array $attribs = [], $contents = '' ) {
1489 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1493 * Clear the body HTML
1495 public function clearHTML() {
1496 $this->mBodytext
= '';
1502 * @return string HTML
1504 public function getHTML() {
1505 return $this->mBodytext
;
1509 * Get/set the ParserOptions object to use for wikitext parsing
1511 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1512 * current ParserOption object
1513 * @return ParserOptions
1515 public function parserOptions( $options = null ) {
1516 if ( $options !== null && !empty( $options->isBogus
) ) {
1517 // Someone is trying to set a bogus pre-$wgUser PO. Check if it has
1518 // been changed somehow, and keep it if so.
1519 $anonPO = ParserOptions
::newFromAnon();
1520 $anonPO->setEditSection( false );
1521 if ( !$options->matches( $anonPO ) ) {
1522 wfLogWarning( __METHOD__
. ': Setting a changed bogus ParserOptions: ' . wfGetAllCallers( 5 ) );
1523 $options->isBogus
= false;
1527 if ( !$this->mParserOptions
) {
1528 if ( !$this->getContext()->getUser()->isSafeToLoad() ) {
1529 // $wgUser isn't unstubbable yet, so don't try to get a
1530 // ParserOptions for it. And don't cache this ParserOptions
1532 $po = ParserOptions
::newFromAnon();
1533 $po->setEditSection( false );
1534 $po->isBogus
= true;
1535 if ( $options !== null ) {
1536 $this->mParserOptions
= empty( $options->isBogus
) ?
$options : null;
1541 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1542 $this->mParserOptions
->setEditSection( false );
1545 if ( $options !== null && !empty( $options->isBogus
) ) {
1546 // They're trying to restore the bogus pre-$wgUser PO. Do the right
1548 return wfSetVar( $this->mParserOptions
, null, true );
1550 return wfSetVar( $this->mParserOptions
, $options );
1555 * Set the revision ID which will be seen by the wiki text parser
1556 * for things such as embedded {{REVISIONID}} variable use.
1558 * @param int|null $revid An positive integer, or null
1559 * @return mixed Previous value
1561 public function setRevisionId( $revid ) {
1562 $val = is_null( $revid ) ?
null : intval( $revid );
1563 return wfSetVar( $this->mRevisionId
, $val );
1567 * Get the displayed revision ID
1571 public function getRevisionId() {
1572 return $this->mRevisionId
;
1576 * Set the timestamp of the revision which will be displayed. This is used
1577 * to avoid a extra DB call in Skin::lastModified().
1579 * @param string|null $timestamp
1580 * @return mixed Previous value
1582 public function setRevisionTimestamp( $timestamp ) {
1583 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1587 * Get the timestamp of displayed revision.
1588 * This will be null if not filled by setRevisionTimestamp().
1590 * @return string|null
1592 public function getRevisionTimestamp() {
1593 return $this->mRevisionTimestamp
;
1597 * Set the displayed file version
1599 * @param File|bool $file
1600 * @return mixed Previous value
1602 public function setFileVersion( $file ) {
1604 if ( $file instanceof File
&& $file->exists() ) {
1605 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1607 return wfSetVar( $this->mFileVersion
, $val, true );
1611 * Get the displayed file version
1613 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1615 public function getFileVersion() {
1616 return $this->mFileVersion
;
1620 * Get the templates used on this page
1622 * @return array (namespace => dbKey => revId)
1625 public function getTemplateIds() {
1626 return $this->mTemplateIds
;
1630 * Get the files used on this page
1632 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1635 public function getFileSearchOptions() {
1636 return $this->mImageTimeKeys
;
1640 * Convert wikitext to HTML and add it to the buffer
1641 * Default assumes that the current page title will be used.
1643 * @param string $text
1644 * @param bool $linestart Is this the start of a line?
1645 * @param bool $interface Is this text in the user interface language?
1646 * @throws MWException
1648 public function addWikiText( $text, $linestart = true, $interface = true ) {
1649 $title = $this->getTitle(); // Work around E_STRICT
1651 throw new MWException( 'Title is null' );
1653 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1657 * Add wikitext with a custom Title object
1659 * @param string $text Wikitext
1660 * @param Title $title
1661 * @param bool $linestart Is this the start of a line?
1663 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1664 $this->addWikiTextTitle( $text, $title, $linestart );
1668 * Add wikitext with a custom Title object and tidy enabled.
1670 * @param string $text Wikitext
1671 * @param Title $title
1672 * @param bool $linestart Is this the start of a line?
1674 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1675 $this->addWikiTextTitle( $text, $title, $linestart, true );
1679 * Add wikitext with tidy enabled
1681 * @param string $text Wikitext
1682 * @param bool $linestart Is this the start of a line?
1684 public function addWikiTextTidy( $text, $linestart = true ) {
1685 $title = $this->getTitle();
1686 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1690 * Add wikitext with a custom Title object
1692 * @param string $text Wikitext
1693 * @param Title $title
1694 * @param bool $linestart Is this the start of a line?
1695 * @param bool $tidy Whether to use tidy
1696 * @param bool $interface Whether it is an interface message
1697 * (for example disables conversion)
1699 public function addWikiTextTitle( $text, Title
$title, $linestart,
1700 $tidy = false, $interface = false
1704 $popts = $this->parserOptions();
1705 $oldTidy = $popts->setTidy( $tidy );
1706 $popts->setInterfaceMessage( (bool)$interface );
1708 $parserOutput = $wgParser->getFreshParser()->parse(
1709 $text, $title, $popts,
1710 $linestart, true, $this->mRevisionId
1713 $popts->setTidy( $oldTidy );
1715 $this->addParserOutput( $parserOutput );
1720 * Add a ParserOutput object, but without Html.
1722 * @deprecated since 1.24, use addParserOutputMetadata() instead.
1723 * @param ParserOutput $parserOutput
1725 public function addParserOutputNoText( $parserOutput ) {
1726 wfDeprecated( __METHOD__
, '1.24' );
1727 $this->addParserOutputMetadata( $parserOutput );
1731 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1732 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1736 * @param ParserOutput $parserOutput
1738 public function addParserOutputMetadata( $parserOutput ) {
1739 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1740 $this->addCategoryLinks( $parserOutput->getCategories() );
1741 $this->setIndicators( $parserOutput->getIndicators() );
1742 $this->mNewSectionLink
= $parserOutput->getNewSection();
1743 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1745 if ( !$parserOutput->isCacheable() ) {
1746 $this->enableClientCache( false );
1748 $this->mNoGallery
= $parserOutput->getNoGallery();
1749 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1750 $this->addModules( $parserOutput->getModules() );
1751 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1752 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1753 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1754 $this->mPreventClickjacking
= $this->mPreventClickjacking
1755 ||
$parserOutput->preventClickjacking();
1757 // Template versioning...
1758 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1759 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1760 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1762 $this->mTemplateIds
[$ns] = $dbks;
1765 // File versioning...
1766 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1767 $this->mImageTimeKeys
[$dbk] = $data;
1770 // Hooks registered in the object
1771 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1772 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1773 list( $hookName, $data ) = $hookInfo;
1774 if ( isset( $parserOutputHooks[$hookName] ) ) {
1775 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1779 // Enable OOUI if requested via ParserOutput
1780 if ( $parserOutput->getEnableOOUI() ) {
1781 $this->enableOOUI();
1784 // Include profiling data
1785 if ( !$this->limitReportData
) {
1786 $this->setLimitReportData( $parserOutput->getLimitReportData() );
1789 // Link flags are ignored for now, but may in the future be
1790 // used to mark individual language links.
1792 Hooks
::run( 'LanguageLinks', [ $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ] );
1793 Hooks
::run( 'OutputPageParserOutput', [ &$this, $parserOutput ] );
1797 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1798 * ParserOutput object, without any other metadata.
1801 * @param ParserOutput $parserOutput
1803 public function addParserOutputContent( $parserOutput ) {
1804 $this->addParserOutputText( $parserOutput );
1806 $this->addModules( $parserOutput->getModules() );
1807 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1808 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1810 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1814 * Add the HTML associated with a ParserOutput object, without any metadata.
1817 * @param ParserOutput $parserOutput
1819 public function addParserOutputText( $parserOutput ) {
1820 $text = $parserOutput->getText();
1821 Hooks
::run( 'OutputPageBeforeHTML', [ &$this, &$text ] );
1822 $this->addHTML( $text );
1826 * Add everything from a ParserOutput object.
1828 * @param ParserOutput $parserOutput
1830 function addParserOutput( $parserOutput ) {
1831 $this->addParserOutputMetadata( $parserOutput );
1832 $parserOutput->setTOCEnabled( $this->mEnableTOC
);
1834 // Touch section edit links only if not previously disabled
1835 if ( $parserOutput->getEditSectionTokens() ) {
1836 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks
);
1839 $this->addParserOutputText( $parserOutput );
1843 * Add the output of a QuickTemplate to the output buffer
1845 * @param QuickTemplate $template
1847 public function addTemplate( &$template ) {
1848 $this->addHTML( $template->getHTML() );
1852 * Parse wikitext and return the HTML.
1854 * @param string $text
1855 * @param bool $linestart Is this the start of a line?
1856 * @param bool $interface Use interface language ($wgLang instead of
1857 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1858 * This also disables LanguageConverter.
1859 * @param Language $language Target language object, will override $interface
1860 * @throws MWException
1861 * @return string HTML
1863 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1866 if ( is_null( $this->getTitle() ) ) {
1867 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1870 $popts = $this->parserOptions();
1872 $popts->setInterfaceMessage( true );
1874 if ( $language !== null ) {
1875 $oldLang = $popts->setTargetLanguage( $language );
1878 $parserOutput = $wgParser->getFreshParser()->parse(
1879 $text, $this->getTitle(), $popts,
1880 $linestart, true, $this->mRevisionId
1884 $popts->setInterfaceMessage( false );
1886 if ( $language !== null ) {
1887 $popts->setTargetLanguage( $oldLang );
1890 return $parserOutput->getText();
1894 * Parse wikitext, strip paragraphs, and return the HTML.
1896 * @param string $text
1897 * @param bool $linestart Is this the start of a line?
1898 * @param bool $interface Use interface language ($wgLang instead of
1899 * $wgContLang) while parsing language sensitive magic
1900 * words like GRAMMAR and PLURAL
1901 * @return string HTML
1903 public function parseInline( $text, $linestart = true, $interface = false ) {
1904 $parsed = $this->parse( $text, $linestart, $interface );
1905 return Parser
::stripOuterParagraph( $parsed );
1910 * @deprecated since 1.27 Use setCdnMaxage() instead
1912 public function setSquidMaxage( $maxage ) {
1913 $this->setCdnMaxage( $maxage );
1917 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1919 * @param int $maxage Maximum cache time on the CDN, in seconds.
1921 public function setCdnMaxage( $maxage ) {
1922 $this->mCdnMaxage
= min( $maxage, $this->mCdnMaxageLimit
);
1926 * Lower the value of the "s-maxage" part of the "Cache-control" HTTP header
1928 * @param int $maxage Maximum cache time on the CDN, in seconds
1931 public function lowerCdnMaxage( $maxage ) {
1932 $this->mCdnMaxageLimit
= min( $maxage, $this->mCdnMaxageLimit
);
1933 $this->setCdnMaxage( $this->mCdnMaxage
);
1937 * Get TTL in [$minTTL,$maxTTL] in pass it to lowerCdnMaxage()
1939 * This sets and returns $minTTL if $mtime is false or null. Otherwise,
1940 * the TTL is higher the older the $mtime timestamp is. Essentially, the
1941 * TTL is 90% of the age of the object, subject to the min and max.
1943 * @param string|integer|float|bool|null $mtime Last-Modified timestamp
1944 * @param integer $minTTL Mimimum TTL in seconds [default: 1 minute]
1945 * @param integer $maxTTL Maximum TTL in seconds [default: $wgSquidMaxage]
1946 * @return integer TTL in seconds
1949 public function adaptCdnTTL( $mtime, $minTTL = 0, $maxTTL = 0 ) {
1950 $minTTL = $minTTL ?
: IExpiringStore
::TTL_MINUTE
;
1951 $maxTTL = $maxTTL ?
: $this->getConfig()->get( 'SquidMaxage' );
1953 if ( $mtime === null ||
$mtime === false ) {
1954 return $minTTL; // entity does not exist
1957 $age = time() - wfTimestamp( TS_UNIX
, $mtime );
1958 $adaptiveTTL = max( .9 * $age, $minTTL );
1959 $adaptiveTTL = min( $adaptiveTTL, $maxTTL );
1961 $this->lowerCdnMaxage( (int)$adaptiveTTL );
1963 return $adaptiveTTL;
1967 * Use enableClientCache(false) to force it to send nocache headers
1969 * @param bool $state
1973 public function enableClientCache( $state ) {
1974 return wfSetVar( $this->mEnableClientCache
, $state );
1978 * Get the list of cookies that will influence on the cache
1982 function getCacheVaryCookies() {
1984 if ( $cookies === null ) {
1985 $config = $this->getConfig();
1986 $cookies = array_merge(
1987 SessionManager
::singleton()->getVaryCookies(),
1991 $config->get( 'CacheVaryCookies' )
1993 Hooks
::run( 'GetCacheVaryCookies', [ $this, &$cookies ] );
1999 * Check if the request has a cache-varying cookie header
2000 * If it does, it's very important that we don't allow public caching
2004 function haveCacheVaryCookies() {
2005 $request = $this->getRequest();
2006 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2007 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2008 wfDebug( __METHOD__
. ": found $cookieName\n" );
2012 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
2017 * Add an HTTP header that will influence on the cache
2019 * @param string $header Header name
2020 * @param string[]|null $option Options for the Key header. See
2021 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2022 * for the list of valid options.
2024 public function addVaryHeader( $header, array $option = null ) {
2025 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
2026 $this->mVaryHeader
[$header] = [];
2028 if ( !is_array( $option ) ) {
2031 $this->mVaryHeader
[$header] = array_unique( array_merge( $this->mVaryHeader
[$header], $option ) );
2035 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2036 * such as Accept-Encoding or Cookie
2040 public function getVaryHeader() {
2041 // If we vary on cookies, let's make sure it's always included here too.
2042 if ( $this->getCacheVaryCookies() ) {
2043 $this->addVaryHeader( 'Cookie' );
2046 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2047 $this->addVaryHeader( $header, $options );
2049 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader
) );
2053 * Get a complete Key header
2057 public function getKeyHeader() {
2058 $cvCookies = $this->getCacheVaryCookies();
2060 $cookiesOption = [];
2061 foreach ( $cvCookies as $cookieName ) {
2062 $cookiesOption[] = 'param=' . $cookieName;
2064 $this->addVaryHeader( 'Cookie', $cookiesOption );
2066 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2067 $this->addVaryHeader( $header, $options );
2071 foreach ( $this->mVaryHeader
as $header => $option ) {
2072 $newheader = $header;
2073 if ( is_array( $option ) && count( $option ) > 0 ) {
2074 $newheader .= ';' . implode( ';', $option );
2076 $headers[] = $newheader;
2078 $key = 'Key: ' . implode( ',', $headers );
2084 * T23672: Add Accept-Language to Vary and Key headers
2085 * if there's no 'variant' parameter existed in GET.
2088 * /w/index.php?title=Main_page should always be served; but
2089 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
2091 function addAcceptLanguage() {
2092 $title = $this->getTitle();
2093 if ( !$title instanceof Title
) {
2097 $lang = $title->getPageLanguage();
2098 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2099 $variants = $lang->getVariants();
2101 foreach ( $variants as $variant ) {
2102 if ( $variant === $lang->getCode() ) {
2105 $aloption[] = 'substr=' . $variant;
2107 // IE and some other browsers use BCP 47 standards in
2108 // their Accept-Language header, like "zh-CN" or "zh-Hant".
2109 // We should handle these too.
2110 $variantBCP47 = wfBCP47( $variant );
2111 if ( $variantBCP47 !== $variant ) {
2112 $aloption[] = 'substr=' . $variantBCP47;
2116 $this->addVaryHeader( 'Accept-Language', $aloption );
2121 * Set a flag which will cause an X-Frame-Options header appropriate for
2122 * edit pages to be sent. The header value is controlled by
2123 * $wgEditPageFrameOptions.
2125 * This is the default for special pages. If you display a CSRF-protected
2126 * form on an ordinary view page, then you need to call this function.
2128 * @param bool $enable
2130 public function preventClickjacking( $enable = true ) {
2131 $this->mPreventClickjacking
= $enable;
2135 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2136 * This can be called from pages which do not contain any CSRF-protected
2139 public function allowClickjacking() {
2140 $this->mPreventClickjacking
= false;
2144 * Get the prevent-clickjacking flag
2149 public function getPreventClickjacking() {
2150 return $this->mPreventClickjacking
;
2154 * Get the X-Frame-Options header value (without the name part), or false
2155 * if there isn't one. This is used by Skin to determine whether to enable
2156 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2160 public function getFrameOptions() {
2161 $config = $this->getConfig();
2162 if ( $config->get( 'BreakFrames' ) ) {
2164 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2165 return $config->get( 'EditPageFrameOptions' );
2171 * Send cache control HTTP headers
2173 public function sendCacheControl() {
2174 $response = $this->getRequest()->response();
2175 $config = $this->getConfig();
2177 $this->addVaryHeader( 'Cookie' );
2178 $this->addAcceptLanguage();
2180 # don't serve compressed data to clients who can't handle it
2181 # maintain different caches for logged-in users and non-logged in ones
2182 $response->header( $this->getVaryHeader() );
2184 if ( $config->get( 'UseKeyHeader' ) ) {
2185 $response->header( $this->getKeyHeader() );
2188 if ( $this->mEnableClientCache
) {
2190 $config->get( 'UseSquid' ) &&
2191 !$response->hasCookies() &&
2192 !SessionManager
::getGlobalSession()->isPersistent() &&
2193 !$this->isPrintable() &&
2194 $this->mCdnMaxage
!= 0 &&
2195 !$this->haveCacheVaryCookies()
2197 if ( $config->get( 'UseESI' ) ) {
2198 # We'll purge the proxy cache explicitly, but require end user agents
2199 # to revalidate against the proxy on each visit.
2200 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2201 wfDebug( __METHOD__
.
2202 ": proxy caching with ESI; {$this->mLastModified} **", 'private' );
2203 # start with a shorter timeout for initial testing
2204 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2206 "Surrogate-Control: max-age={$config->get( 'SquidMaxage' )}" .
2207 "+{$this->mCdnMaxage}, content=\"ESI/1.0\""
2209 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2211 # We'll purge the proxy cache for anons explicitly, but require end user agents
2212 # to revalidate against the proxy on each visit.
2213 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2214 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2215 wfDebug( __METHOD__
.
2216 ": local proxy caching; {$this->mLastModified} **", 'private' );
2217 # start with a shorter timeout for initial testing
2218 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2219 $response->header( "Cache-Control: " .
2220 "s-maxage={$this->mCdnMaxage}, must-revalidate, max-age=0" );
2223 # We do want clients to cache if they can, but they *must* check for updates
2224 # on revisiting the page.
2225 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **", 'private' );
2226 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2227 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2229 if ( $this->mLastModified
) {
2230 $response->header( "Last-Modified: {$this->mLastModified}" );
2233 wfDebug( __METHOD__
. ": no caching **", 'private' );
2235 # In general, the absence of a last modified header should be enough to prevent
2236 # the client from using its cache. We send a few other things just to make sure.
2237 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2238 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2239 $response->header( 'Pragma: no-cache' );
2244 * Finally, all the text has been munged and accumulated into
2245 * the object, let's actually output it:
2247 * @param bool $return Set to true to get the result as a string rather than sending it
2248 * @return string|null
2250 * @throws FatalError
2251 * @throws MWException
2253 public function output( $return = false ) {
2256 if ( $this->mDoNothing
) {
2257 return $return ?
'' : null;
2260 $response = $this->getRequest()->response();
2261 $config = $this->getConfig();
2263 if ( $this->mRedirect
!= '' ) {
2264 # Standards require redirect URLs to be absolute
2265 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2267 $redirect = $this->mRedirect
;
2268 $code = $this->mRedirectCode
;
2270 if ( Hooks
::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2271 if ( $code == '301' ||
$code == '303' ) {
2272 if ( !$config->get( 'DebugRedirects' ) ) {
2273 $response->statusHeader( $code );
2275 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2277 if ( $config->get( 'VaryOnXFP' ) ) {
2278 $this->addVaryHeader( 'X-Forwarded-Proto' );
2280 $this->sendCacheControl();
2282 $response->header( "Content-Type: text/html; charset=utf-8" );
2283 if ( $config->get( 'DebugRedirects' ) ) {
2284 $url = htmlspecialchars( $redirect );
2285 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2286 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2287 print "</body>\n</html>\n";
2289 $response->header( 'Location: ' . $redirect );
2293 return $return ?
'' : null;
2294 } elseif ( $this->mStatusCode
) {
2295 $response->statusHeader( $this->mStatusCode
);
2298 # Buffer output; final headers may depend on later processing
2301 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2302 $response->header( 'Content-language: ' . $wgContLang->getHtmlCode() );
2304 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2305 // jQuery etc. can work correctly.
2306 $response->header( 'X-UA-Compatible: IE=Edge' );
2308 // Prevent framing, if requested
2309 $frameOptions = $this->getFrameOptions();
2310 if ( $frameOptions ) {
2311 $response->header( "X-Frame-Options: $frameOptions" );
2314 if ( $this->mArticleBodyOnly
) {
2315 echo $this->mBodytext
;
2317 $sk = $this->getSkin();
2318 // add skin specific modules
2319 $modules = $sk->getDefaultModules();
2321 // Enforce various default modules for all pages and all skins
2323 // Keep this list as small as possible
2325 'mediawiki.page.startup',
2329 // Support for high-density display images if enabled
2330 if ( $config->get( 'ResponsiveImages' ) ) {
2331 $coreModules[] = 'mediawiki.hidpi';
2334 $this->addModules( $coreModules );
2335 foreach ( $modules as $group ) {
2336 $this->addModules( $group );
2338 MWDebug
::addModules( $this );
2340 // Hook that allows last minute changes to the output page, e.g.
2341 // adding of CSS or Javascript by extensions.
2342 Hooks
::run( 'BeforePageDisplay', [ &$this, &$sk ] );
2346 } catch ( Exception
$e ) {
2347 ob_end_clean(); // bug T129657
2353 // This hook allows last minute changes to final overall output by modifying output buffer
2354 Hooks
::run( 'AfterFinalPageOutput', [ $this ] );
2355 } catch ( Exception
$e ) {
2356 ob_end_clean(); // bug T129657
2360 $this->sendCacheControl();
2363 return ob_get_clean();
2371 * Prepare this object to display an error page; disable caching and
2372 * indexing, clear the current text and redirect, set the page's title
2373 * and optionally an custom HTML title (content of the "<title>" tag).
2375 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2376 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2377 * optional, if not passed the "<title>" attribute will be
2378 * based on $pageTitle
2380 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2381 $this->setPageTitle( $pageTitle );
2382 if ( $htmlTitle !== false ) {
2383 $this->setHTMLTitle( $htmlTitle );
2385 $this->setRobotPolicy( 'noindex,nofollow' );
2386 $this->setArticleRelated( false );
2387 $this->enableClientCache( false );
2388 $this->mRedirect
= '';
2389 $this->clearSubtitle();
2394 * Output a standard error page
2396 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2397 * showErrorPage( 'titlemsg', 'pagetextmsg', [ 'param1', 'param2' ] );
2398 * showErrorPage( 'titlemsg', $messageObject );
2399 * showErrorPage( $titleMessageObject, $messageObject );
2401 * @param string|Message $title Message key (string) for page title, or a Message object
2402 * @param string|Message $msg Message key (string) for page text, or a Message object
2403 * @param array $params Message parameters; ignored if $msg is a Message object
2405 public function showErrorPage( $title, $msg, $params = [] ) {
2406 if ( !$title instanceof Message
) {
2407 $title = $this->msg( $title );
2410 $this->prepareErrorPage( $title );
2412 if ( $msg instanceof Message
) {
2413 if ( $params !== [] ) {
2414 trigger_error( 'Argument ignored: $params. The message parameters argument '
2415 . 'is discarded when the $msg argument is a Message object instead of '
2416 . 'a string.', E_USER_NOTICE
);
2418 $this->addHTML( $msg->parseAsBlock() );
2420 $this->addWikiMsgArray( $msg, $params );
2423 $this->returnToMain();
2427 * Output a standard permission error page
2429 * @param array $errors Error message keys or [key, param...] arrays
2430 * @param string $action Action that was denied or null if unknown
2432 public function showPermissionsErrorPage( array $errors, $action = null ) {
2433 foreach ( $errors as $key => $error ) {
2434 $errors[$key] = (array)$error;
2437 // For some action (read, edit, create and upload), display a "login to do this action"
2438 // error if all of the following conditions are met:
2439 // 1. the user is not logged in
2440 // 2. the only error is insufficient permissions (i.e. no block or something else)
2441 // 3. the error can be avoided simply by logging in
2442 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2443 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2444 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2445 && ( User
::groupHasPermission( 'user', $action )
2446 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2448 $displayReturnto = null;
2450 # Due to bug 32276, if a user does not have read permissions,
2451 # $this->getTitle() will just give Special:Badtitle, which is
2452 # not especially useful as a returnto parameter. Use the title
2453 # from the request instead, if there was one.
2454 $request = $this->getRequest();
2455 $returnto = Title
::newFromText( $request->getVal( 'title', '' ) );
2456 if ( $action == 'edit' ) {
2457 $msg = 'whitelistedittext';
2458 $displayReturnto = $returnto;
2459 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2460 $msg = 'nocreatetext';
2461 } elseif ( $action == 'upload' ) {
2462 $msg = 'uploadnologintext';
2464 $msg = 'loginreqpagetext';
2465 $displayReturnto = Title
::newMainPage();
2471 $query['returnto'] = $returnto->getPrefixedText();
2473 if ( !$request->wasPosted() ) {
2474 $returntoquery = $request->getValues();
2475 unset( $returntoquery['title'] );
2476 unset( $returntoquery['returnto'] );
2477 unset( $returntoquery['returntoquery'] );
2478 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2481 $loginLink = Linker
::linkKnown(
2482 SpecialPage
::getTitleFor( 'Userlogin' ),
2483 $this->msg( 'loginreqlink' )->escaped(),
2488 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2489 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2491 # Don't return to a page the user can't read otherwise
2492 # we'll end up in a pointless loop
2493 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2494 $this->returnToMain( null, $displayReturnto );
2497 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2498 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2503 * Display an error page indicating that a given version of MediaWiki is
2504 * required to use it
2506 * @param mixed $version The version of MediaWiki needed to use the page
2508 public function versionRequired( $version ) {
2509 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2511 $this->addWikiMsg( 'versionrequiredtext', $version );
2512 $this->returnToMain();
2516 * Format a list of error messages
2518 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2519 * @param string $action Action that was denied or null if unknown
2520 * @return string The wikitext error-messages, formatted into a list.
2522 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2523 if ( $action == null ) {
2524 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2526 $action_desc = $this->msg( "action-$action" )->plain();
2528 'permissionserrorstext-withaction',
2531 )->plain() . "\n\n";
2534 if ( count( $errors ) > 1 ) {
2535 $text .= '<ul class="permissions-errors">' . "\n";
2537 foreach ( $errors as $error ) {
2539 $text .= call_user_func_array( [ $this, 'msg' ], $error )->plain();
2544 $text .= "<div class=\"permissions-errors\">\n" .
2545 call_user_func_array( [ $this, 'msg' ], reset( $errors ) )->plain() .
2553 * Display a page stating that the Wiki is in read-only mode.
2554 * Should only be called after wfReadOnly() has returned true.
2556 * Historically, this function was used to show the source of the page that the user
2557 * was trying to edit and _also_ permissions error messages. The relevant code was
2558 * moved into EditPage in 1.19 (r102024 / d83c2a431c2a) and removed here in 1.25.
2560 * @deprecated since 1.25; throw the exception directly
2561 * @throws ReadOnlyError
2563 public function readOnlyPage() {
2564 if ( func_num_args() > 0 ) {
2565 throw new MWException( __METHOD__
. ' no longer accepts arguments since 1.25.' );
2568 throw new ReadOnlyError
;
2572 * Turn off regular page output and return an error response
2573 * for when rate limiting has triggered.
2575 * @deprecated since 1.25; throw the exception directly
2577 public function rateLimited() {
2578 wfDeprecated( __METHOD__
, '1.25' );
2579 throw new ThrottledError
;
2583 * Show a warning about replica DB lag
2585 * If the lag is higher than $wgSlaveLagCritical seconds,
2586 * then the warning is a bit more obvious. If the lag is
2587 * lower than $wgSlaveLagWarning, then no warning is shown.
2589 * @param int $lag Slave lag
2591 public function showLagWarning( $lag ) {
2592 $config = $this->getConfig();
2593 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2594 $lag = floor( $lag ); // floor to avoid nano seconds to display
2595 $message = $lag < $config->get( 'SlaveLagCritical' )
2598 $wrap = Html
::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2599 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2603 public function showFatalError( $message ) {
2604 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2606 $this->addHTML( $message );
2609 public function showUnexpectedValueError( $name, $val ) {
2610 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2613 public function showFileCopyError( $old, $new ) {
2614 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2617 public function showFileRenameError( $old, $new ) {
2618 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2621 public function showFileDeleteError( $name ) {
2622 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2625 public function showFileNotFoundError( $name ) {
2626 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2630 * Add a "return to" link pointing to a specified title
2632 * @param Title $title Title to link
2633 * @param array $query Query string parameters
2634 * @param string $text Text of the link (input is not escaped)
2635 * @param array $options Options array to pass to Linker
2637 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
2638 $link = $this->msg( 'returnto' )->rawParams(
2639 Linker
::link( $title, $text, [], $query, $options ) )->escaped();
2640 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2644 * Add a "return to" link pointing to a specified title,
2645 * or the title indicated in the request, or else the main page
2647 * @param mixed $unused
2648 * @param Title|string $returnto Title or String to return to
2649 * @param string $returntoquery Query string for the return to link
2651 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2652 if ( $returnto == null ) {
2653 $returnto = $this->getRequest()->getText( 'returnto' );
2656 if ( $returntoquery == null ) {
2657 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2660 if ( $returnto === '' ) {
2661 $returnto = Title
::newMainPage();
2664 if ( is_object( $returnto ) ) {
2665 $titleObj = $returnto;
2667 $titleObj = Title
::newFromText( $returnto );
2669 if ( !is_object( $titleObj ) ) {
2670 $titleObj = Title
::newMainPage();
2673 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2676 private function getRlClientContext() {
2677 if ( !$this->rlClientContext
) {
2678 $query = ResourceLoader
::makeLoaderQuery(
2679 [], // modules; not relevant
2680 $this->getLanguage()->getCode(),
2681 $this->getSkin()->getSkinName(),
2682 $this->getUser()->isLoggedIn() ?
$this->getUser()->getName() : null,
2683 null, // version; not relevant
2684 ResourceLoader
::inDebugMode(),
2685 null, // only; not relevant
2686 $this->isPrintable(),
2687 $this->getRequest()->getBool( 'handheld' )
2689 $this->rlClientContext
= new ResourceLoaderContext(
2690 $this->getResourceLoader(),
2691 new FauxRequest( $query )
2694 return $this->rlClientContext
;
2698 * Call this to freeze the module queue and JS config and create a formatter.
2700 * Depending on the Skin, this may get lazy-initialised in either headElement() or
2701 * getBottomScripts(). See SkinTemplate::prepareQuickTemplate(). Calling this too early may
2702 * cause unexpected side-effects since disallowUserJs() may be called at any time to change
2703 * the module filters retroactively. Skins and extension hooks may also add modules until very
2704 * late in the request lifecycle.
2706 * @return ResourceLoaderClientHtml
2708 public function getRlClient() {
2709 if ( !$this->rlClient
) {
2710 $context = $this->getRlClientContext();
2711 $rl = $this->getResourceLoader();
2712 $this->addModules( [
2716 $this->addModuleStyles( [
2722 $this->getSkin()->setupSkinUserCss( $this );
2724 // Prepare exempt modules for buildExemptModules()
2725 $exemptGroups = [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ];
2727 $moduleStyles = $this->getModuleStyles( /*filter*/ true );
2729 // Preload getTitleInfo for isKnownEmpty calls below and in ResourceLoaderClientHtml
2730 // Separate user-specific batch for improved cache-hit ratio.
2731 $userBatch = [ 'user.styles', 'user' ];
2732 $siteBatch = array_diff( $moduleStyles, $userBatch );
2733 $dbr = wfGetDB( DB_REPLICA
);
2734 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $siteBatch );
2735 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $userBatch );
2737 // Filter out modules handled by buildExemptModules()
2738 $moduleStyles = array_filter( $moduleStyles,
2739 function ( $name ) use ( $rl, $context, &$exemptGroups, &$exemptStates ) {
2740 $module = $rl->getModule( $name );
2742 if ( $name === 'user.styles' && $this->isUserCssPreview() ) {
2743 $exemptStates[$name] = 'ready';
2744 // Special case in buildExemptModules()
2747 $group = $module->getGroup();
2748 if ( isset( $exemptGroups[$group] ) ) {
2749 $exemptStates[$name] = 'ready';
2750 if ( !$module->isKnownEmpty( $context ) ) {
2751 // E.g. Don't output empty <styles>
2752 $exemptGroups[$group][] = $name;
2760 $this->rlExemptStyleModules
= $exemptGroups;
2762 $isUserModuleFiltered = !$this->filterModules( [ 'user' ] );
2763 // If this page filters out 'user', makeResourceLoaderLink will drop it.
2764 // Avoid indefinite "loading" state or untrue "ready" state (T145368).
2765 if ( !$isUserModuleFiltered ) {
2766 // Manually handled by getBottomScripts()
2767 $userModule = $rl->getModule( 'user' );
2768 $userState = $userModule->isKnownEmpty( $context ) && !$this->isUserJsPreview()
2771 $this->rlUserModuleState
= $exemptStates['user'] = $userState;
2774 $rlClient = new ResourceLoaderClientHtml( $context, $this->getTarget() );
2775 $rlClient->setConfig( $this->getJSVars() );
2776 $rlClient->setModules( $this->getModules( /*filter*/ true ) );
2777 $rlClient->setModuleStyles( $moduleStyles );
2778 $rlClient->setModuleScripts( $this->getModuleScripts( /*filter*/ true ) );
2779 $rlClient->setExemptStates( $exemptStates );
2780 $this->rlClient
= $rlClient;
2782 return $this->rlClient
;
2786 * @param Skin $sk The given Skin
2787 * @param bool $includeStyle Unused
2788 * @return string The doctype, opening "<html>", and head element.
2790 public function headElement( Skin
$sk, $includeStyle = true ) {
2793 $userdir = $this->getLanguage()->getDir();
2794 $sitedir = $wgContLang->getDir();
2797 $pieces[] = Html
::htmlHeader( Sanitizer
::mergeAttributes(
2798 $this->getRlClient()->getDocumentAttributes(),
2799 $sk->getHtmlElementAttributes()
2801 $pieces[] = Html
::openElement( 'head' );
2803 if ( $this->getHTMLTitle() == '' ) {
2804 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2807 if ( !Html
::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2808 // Add <meta charset="UTF-8">
2809 // This should be before <title> since it defines the charset used by
2810 // text including the text inside <title>.
2811 // The spec recommends defining XHTML5's charset using the XML declaration
2813 // Our XML declaration is output by Html::htmlHeader.
2814 // http://www.whatwg.org/html/semantics.html#attr-meta-http-equiv-content-type
2815 // http://www.whatwg.org/html/semantics.html#charset
2816 $pieces[] = Html
::element( 'meta', [ 'charset' => 'UTF-8' ] );
2819 $pieces[] = Html
::element( 'title', null, $this->getHTMLTitle() );
2820 $pieces[] = $this->getRlClient()->getHeadHtml();
2821 $pieces[] = $this->buildExemptModules();
2822 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
2823 $pieces = array_merge( $pieces, array_values( $this->mHeadItems
) );
2824 $pieces[] = Html
::closeElement( 'head' );
2827 $bodyClasses[] = 'mediawiki';
2829 # Classes for LTR/RTL directionality support
2830 $bodyClasses[] = $userdir;
2831 $bodyClasses[] = "sitedir-$sitedir";
2833 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2834 # A <body> class is probably not the best way to do this . . .
2835 $bodyClasses[] = 'capitalize-all-nouns';
2838 // Parser feature migration class
2839 // The idea is that this will eventually be removed, after the wikitext
2840 // which requires it is cleaned up.
2841 $bodyClasses[] = 'mw-hide-empty-elt';
2843 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2844 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2846 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2849 // While the implode() is not strictly needed, it's used for backwards compatibility
2850 // (this used to be built as a string and hooks likely still expect that).
2851 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2853 // Allow skins and extensions to add body attributes they need
2854 $sk->addToBodyAttributes( $this, $bodyAttrs );
2855 Hooks
::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
2857 $pieces[] = Html
::openElement( 'body', $bodyAttrs );
2859 return self
::combineWrappedStrings( $pieces );
2863 * Get a ResourceLoader object associated with this OutputPage
2865 * @return ResourceLoader
2867 public function getResourceLoader() {
2868 if ( is_null( $this->mResourceLoader
) ) {
2869 $this->mResourceLoader
= new ResourceLoader(
2871 LoggerFactory
::getInstance( 'resourceloader' )
2874 return $this->mResourceLoader
;
2878 * Explicily load or embed modules on a page.
2880 * @param array|string $modules One or more module names
2881 * @param string $only ResourceLoaderModule TYPE_ class constant
2882 * @param array $extraQuery [optional] Array with extra query parameters for the request
2883 * @return string|WrappedStringList HTML
2885 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
2886 // Apply 'target' and 'origin' filters
2887 $modules = $this->filterModules( (array)$modules, null, $only );
2889 return ResourceLoaderClientHtml
::makeLoad(
2890 $this->getRlClientContext(),
2898 * Combine WrappedString chunks and filter out empty ones
2900 * @param array $chunks
2901 * @return string|WrappedStringList HTML
2903 protected static function combineWrappedStrings( array $chunks ) {
2904 // Filter out empty values
2905 $chunks = array_filter( $chunks, 'strlen' );
2906 return WrappedString
::join( "\n", $chunks );
2909 private function isUserJsPreview() {
2910 return $this->getConfig()->get( 'AllowUserJs' )
2911 && $this->getTitle()
2912 && $this->getTitle()->isJsSubpage()
2913 && $this->userCanPreview();
2916 private function isUserCssPreview() {
2917 return $this->getConfig()->get( 'AllowUserCss' )
2918 && $this->getTitle()
2919 && $this->getTitle()->isCssSubpage()
2920 && $this->userCanPreview();
2924 * JS stuff to put at the bottom of the `<body>`. These are modules with position 'bottom',
2925 * legacy scripts ($this->mScripts), and user JS.
2927 * @return string|WrappedStringList HTML
2929 public function getBottomScripts() {
2931 $chunks[] = $this->getRlClient()->getBodyHtml();
2933 // Legacy non-ResourceLoader scripts
2934 $chunks[] = $this->mScripts
;
2936 // Exempt 'user' module
2937 // - May need excludepages for live preview. (T28283)
2938 // - Must use TYPE_COMBINED so its response is handled by mw.loader.implement() which
2939 // ensures execution is scheduled after the "site" module.
2940 // - Don't load if module state is already resolved as "ready".
2941 if ( $this->rlUserModuleState
=== 'loading' ) {
2942 if ( $this->isUserJsPreview() ) {
2943 $chunks[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_COMBINED
,
2944 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
2946 $chunks[] = ResourceLoader
::makeInlineScript(
2947 Xml
::encodeJsCall( 'mw.loader.using', [
2951 . Xml
::encodeJsCall( '$.globalEval', [
2952 $this->getRequest()->getText( 'wpTextbox1' )
2958 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
2959 // asynchronously and may arrive *after* the inline script here. So the previewed code
2960 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js.
2961 // Similarly, when previewing ./common.js and the user module does arrive first,
2962 // it will arrive without common.js and the inline script runs after.
2963 // Thus running common after the excluded subpage.
2966 $chunks[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_COMBINED
);
2970 if ( $this->limitReportData
) {
2971 $chunks[] = ResourceLoader
::makeInlineScript(
2972 ResourceLoader
::makeConfigSetScript(
2973 [ 'wgPageParseReport' => $this->limitReportData
],
2979 return self
::combineWrappedStrings( $chunks );
2983 * Get the javascript config vars to include on this page
2985 * @return array Array of javascript config vars
2988 public function getJsConfigVars() {
2989 return $this->mJsConfigVars
;
2993 * Add one or more variables to be set in mw.config in JavaScript
2995 * @param string|array $keys Key or array of key/value pairs
2996 * @param mixed $value [optional] Value of the configuration variable
2998 public function addJsConfigVars( $keys, $value = null ) {
2999 if ( is_array( $keys ) ) {
3000 foreach ( $keys as $key => $value ) {
3001 $this->mJsConfigVars
[$key] = $value;
3006 $this->mJsConfigVars
[$keys] = $value;
3010 * Get an array containing the variables to be set in mw.config in JavaScript.
3012 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3013 * - in other words, page-independent/site-wide variables (without state).
3014 * You will only be adding bloat to the html page and causing page caches to
3015 * have to be purged on configuration changes.
3018 public function getJSVars() {
3023 $canonicalSpecialPageName = false; # bug 21115
3025 $title = $this->getTitle();
3026 $ns = $title->getNamespace();
3027 $canonicalNamespace = MWNamespace
::exists( $ns )
3028 ? MWNamespace
::getCanonicalName( $ns )
3029 : $title->getNsText();
3031 $sk = $this->getSkin();
3032 // Get the relevant title so that AJAX features can use the correct page name
3033 // when making API requests from certain special pages (bug 34972).
3034 $relevantTitle = $sk->getRelevantTitle();
3035 $relevantUser = $sk->getRelevantUser();
3037 if ( $ns == NS_SPECIAL
) {
3038 list( $canonicalSpecialPageName, /*...*/ ) =
3039 SpecialPageFactory
::resolveAlias( $title->getDBkey() );
3040 } elseif ( $this->canUseWikiPage() ) {
3041 $wikiPage = $this->getWikiPage();
3042 $curRevisionId = $wikiPage->getLatest();
3043 $articleId = $wikiPage->getId();
3046 $lang = $title->getPageViewLanguage();
3048 // Pre-process information
3049 $separatorTransTable = $lang->separatorTransformTable();
3050 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : [];
3051 $compactSeparatorTransTable = [
3052 implode( "\t", array_keys( $separatorTransTable ) ),
3053 implode( "\t", $separatorTransTable ),
3055 $digitTransTable = $lang->digitTransformTable();
3056 $digitTransTable = $digitTransTable ?
$digitTransTable : [];
3057 $compactDigitTransTable = [
3058 implode( "\t", array_keys( $digitTransTable ) ),
3059 implode( "\t", $digitTransTable ),
3062 $user = $this->getUser();
3065 'wgCanonicalNamespace' => $canonicalNamespace,
3066 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3067 'wgNamespaceNumber' => $title->getNamespace(),
3068 'wgPageName' => $title->getPrefixedDBkey(),
3069 'wgTitle' => $title->getText(),
3070 'wgCurRevisionId' => $curRevisionId,
3071 'wgRevisionId' => (int)$this->getRevisionId(),
3072 'wgArticleId' => $articleId,
3073 'wgIsArticle' => $this->isArticle(),
3074 'wgIsRedirect' => $title->isRedirect(),
3075 'wgAction' => Action
::getActionName( $this->getContext() ),
3076 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3077 'wgUserGroups' => $user->getEffectiveGroups(),
3078 'wgCategories' => $this->getCategories(),
3079 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3080 'wgPageContentLanguage' => $lang->getCode(),
3081 'wgPageContentModel' => $title->getContentModel(),
3082 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3083 'wgDigitTransformTable' => $compactDigitTransTable,
3084 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3085 'wgMonthNames' => $lang->getMonthNamesArray(),
3086 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3087 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3088 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3089 'wgRequestId' => WebRequest
::getRequestId(),
3092 if ( $user->isLoggedIn() ) {
3093 $vars['wgUserId'] = $user->getId();
3094 $vars['wgUserEditCount'] = $user->getEditCount();
3095 $userReg = $user->getRegistration();
3096 $vars['wgUserRegistration'] = $userReg ?
wfTimestamp( TS_UNIX
, $userReg ) * 1000 : null;
3097 // Get the revision ID of the oldest new message on the user's talk
3098 // page. This can be used for constructing new message alerts on
3100 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3103 if ( $wgContLang->hasVariants() ) {
3104 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3106 // Same test as SkinTemplate
3107 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3108 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3110 foreach ( $title->getRestrictionTypes() as $type ) {
3111 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3114 if ( $title->isMainPage() ) {
3115 $vars['wgIsMainPage'] = true;
3118 if ( $this->mRedirectedFrom
) {
3119 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3122 if ( $relevantUser ) {
3123 $vars['wgRelevantUserName'] = $relevantUser->getName();
3126 // Allow extensions to add their custom variables to the mw.config map.
3127 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3128 // page-dependant but site-wide (without state).
3129 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3130 Hooks
::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3132 // Merge in variables from addJsConfigVars last
3133 return array_merge( $vars, $this->getJsConfigVars() );
3137 * To make it harder for someone to slip a user a fake
3138 * user-JavaScript or user-CSS preview, a random token
3139 * is associated with the login session. If it's not
3140 * passed back with the preview request, we won't render
3145 public function userCanPreview() {
3146 $request = $this->getRequest();
3148 $request->getVal( 'action' ) !== 'submit' ||
3149 !$request->getCheck( 'wpPreview' ) ||
3150 !$request->wasPosted()
3155 $user = $this->getUser();
3157 if ( !$user->isLoggedIn() ) {
3158 // Anons have predictable edit tokens
3161 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3165 $title = $this->getTitle();
3166 if ( !$title->isJsSubpage() && !$title->isCssSubpage() ) {
3169 if ( !$title->isSubpageOf( $user->getUserPage() ) ) {
3170 // Don't execute another user's CSS or JS on preview (T85855)
3174 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3175 if ( count( $errors ) !== 0 ) {
3183 * @return array Array in format "link name or number => 'link html'".
3185 public function getHeadLinksArray() {
3189 $config = $this->getConfig();
3191 $canonicalUrl = $this->mCanonicalUrl
;
3193 $tags['meta-generator'] = Html
::element( 'meta', [
3194 'name' => 'generator',
3195 'content' => "MediaWiki $wgVersion",
3198 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3199 $tags['meta-referrer'] = Html
::element( 'meta', [
3200 'name' => 'referrer',
3201 'content' => $config->get( 'ReferrerPolicy' )
3205 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3206 if ( $p !== 'index,follow' ) {
3207 // http://www.robotstxt.org/wc/meta-user.html
3208 // Only show if it's different from the default robots policy
3209 $tags['meta-robots'] = Html
::element( 'meta', [
3215 foreach ( $this->mMetatags
as $tag ) {
3216 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3218 $tag[0] = substr( $tag[0], 5 );
3222 $tagName = "meta-{$tag[0]}";
3223 if ( isset( $tags[$tagName] ) ) {
3224 $tagName .= $tag[1];
3226 $tags[$tagName] = Html
::element( 'meta',
3229 'content' => $tag[1]
3234 foreach ( $this->mLinktags
as $tag ) {
3235 $tags[] = Html
::element( 'link', $tag );
3238 # Universal edit button
3239 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3240 $user = $this->getUser();
3241 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3242 && ( $this->getTitle()->exists() ||
3243 $this->getTitle()->quickUserCan( 'create', $user ) )
3245 // Original UniversalEditButton
3246 $msg = $this->msg( 'edit' )->text();
3247 $tags['universal-edit-button'] = Html
::element( 'link', [
3248 'rel' => 'alternate',
3249 'type' => 'application/x-wiki',
3251 'href' => $this->getTitle()->getEditURL(),
3253 // Alternate edit link
3254 $tags['alternative-edit'] = Html
::element( 'link', [
3257 'href' => $this->getTitle()->getEditURL(),
3262 # Generally the order of the favicon and apple-touch-icon links
3263 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3264 # uses whichever one appears later in the HTML source. Make sure
3265 # apple-touch-icon is specified first to avoid this.
3266 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3267 $tags['apple-touch-icon'] = Html
::element( 'link', [
3268 'rel' => 'apple-touch-icon',
3269 'href' => $config->get( 'AppleTouchIcon' )
3273 if ( $config->get( 'Favicon' ) !== false ) {
3274 $tags['favicon'] = Html
::element( 'link', [
3275 'rel' => 'shortcut icon',
3276 'href' => $config->get( 'Favicon' )
3280 # OpenSearch description link
3281 $tags['opensearch'] = Html
::element( 'link', [
3283 'type' => 'application/opensearchdescription+xml',
3284 'href' => wfScript( 'opensearch_desc' ),
3285 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3288 if ( $config->get( 'EnableAPI' ) ) {
3289 # Real Simple Discovery link, provides auto-discovery information
3290 # for the MediaWiki API (and potentially additional custom API
3291 # support such as WordPress or Twitter-compatible APIs for a
3292 # blogging extension, etc)
3293 $tags['rsd'] = Html
::element( 'link', [
3295 'type' => 'application/rsd+xml',
3296 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3297 // Whether RSD accepts relative or protocol-relative URLs is completely
3298 // undocumented, though.
3299 'href' => wfExpandUrl( wfAppendQuery(
3301 [ 'action' => 'rsd' ] ),
3308 if ( !$config->get( 'DisableLangConversion' ) ) {
3309 $lang = $this->getTitle()->getPageLanguage();
3310 if ( $lang->hasVariants() ) {
3311 $variants = $lang->getVariants();
3312 foreach ( $variants as $variant ) {
3313 $tags["variant-$variant"] = Html
::element( 'link', [
3314 'rel' => 'alternate',
3315 'hreflang' => wfBCP47( $variant ),
3316 'href' => $this->getTitle()->getLocalURL(
3317 [ 'variant' => $variant ] )
3321 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3322 $tags["variant-x-default"] = Html
::element( 'link', [
3323 'rel' => 'alternate',
3324 'hreflang' => 'x-default',
3325 'href' => $this->getTitle()->getLocalURL() ] );
3330 if ( $this->copyrightUrl
!== null ) {
3331 $copyright = $this->copyrightUrl
;
3334 if ( $config->get( 'RightsPage' ) ) {
3335 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3338 $copyright = $copy->getLocalURL();
3342 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3343 $copyright = $config->get( 'RightsUrl' );
3348 $tags['copyright'] = Html
::element( 'link', [
3349 'rel' => 'copyright',
3350 'href' => $copyright ]
3355 if ( $config->get( 'Feed' ) ) {
3358 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3359 # Use the page name for the title. In principle, this could
3360 # lead to issues with having the same name for different feeds
3361 # corresponding to the same page, but we can't avoid that at
3364 $feedLinks[] = $this->feedLink(
3367 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3369 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3374 # Recent changes feed should appear on every page (except recentchanges,
3375 # that would be redundant). Put it after the per-page feed to avoid
3376 # changing existing behavior. It's still available, probably via a
3377 # menu in your browser. Some sites might have a different feed they'd
3378 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3379 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3380 # If so, use it instead.
3381 $sitename = $config->get( 'Sitename' );
3382 if ( $config->get( 'OverrideSiteFeed' ) ) {
3383 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3384 // Note, this->feedLink escapes the url.
3385 $feedLinks[] = $this->feedLink(
3388 $this->msg( "site-{$type}-feed", $sitename )->text()
3391 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3392 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3393 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3394 $feedLinks[] = $this->feedLink(
3396 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3397 # For grep: 'site-rss-feed', 'site-atom-feed'
3398 $this->msg( "site-{$format}-feed", $sitename )->text()
3403 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3404 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3405 # use OutputPage::addFeedLink() instead.
3406 Hooks
::run( 'AfterBuildFeedLinks', [ &$feedLinks ] );
3408 $tags +
= $feedLinks;
3412 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3413 if ( $canonicalUrl !== false ) {
3414 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3416 if ( $this->isArticleRelated() ) {
3417 // This affects all requests where "setArticleRelated" is true. This is
3418 // typically all requests that show content (query title, curid, oldid, diff),
3419 // and all wikipage actions (edit, delete, purge, info, history etc.).
3420 // It does not apply to File pages and Special pages.
3421 // 'history' and 'info' actions address page metadata rather than the page
3422 // content itself, so they may not be canonicalized to the view page url.
3423 // TODO: this ought to be better encapsulated in the Action class.
3424 $action = Action
::getActionName( $this->getContext() );
3425 if ( in_array( $action, [ 'history', 'info' ] ) ) {
3426 $query = "action={$action}";
3430 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3432 $reqUrl = $this->getRequest()->getRequestURL();
3433 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3437 if ( $canonicalUrl !== false ) {
3438 $tags[] = Html
::element( 'link', [
3439 'rel' => 'canonical',
3440 'href' => $canonicalUrl
3448 * @return string HTML tag links to be put in the header.
3449 * @deprecated since 1.24 Use OutputPage::headElement or if you have to,
3450 * OutputPage::getHeadLinksArray directly.
3452 public function getHeadLinks() {
3453 wfDeprecated( __METHOD__
, '1.24' );
3454 return implode( "\n", $this->getHeadLinksArray() );
3458 * Generate a "<link rel/>" for a feed.
3460 * @param string $type Feed type
3461 * @param string $url URL to the feed
3462 * @param string $text Value of the "title" attribute
3463 * @return string HTML fragment
3465 private function feedLink( $type, $url, $text ) {
3466 return Html
::element( 'link', [
3467 'rel' => 'alternate',
3468 'type' => "application/$type+xml",
3475 * Add a local or specified stylesheet, with the given media options.
3476 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3478 * @param string $style URL to the file
3479 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3480 * @param string $condition For IE conditional comments, specifying an IE version
3481 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3483 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3486 $options['media'] = $media;
3489 $options['condition'] = $condition;
3492 $options['dir'] = $dir;
3494 $this->styles
[$style] = $options;
3498 * Adds inline CSS styles
3499 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3501 * @param mixed $style_css Inline CSS
3502 * @param string $flip Set to 'flip' to flip the CSS if needed
3504 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3505 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3506 # If wanted, and the interface is right-to-left, flip the CSS
3507 $style_css = CSSJanus
::transform( $style_css, true, false );
3509 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3513 * Build exempt modules and legacy non-ResourceLoader styles.
3515 * @return string|WrappedStringList HTML
3517 protected function buildExemptModules() {
3520 $resourceLoader = $this->getResourceLoader();
3522 // Things that go after the ResourceLoaderDynamicStyles marker
3525 // Exempt 'user' styles module (may need 'excludepages' for live preview)
3526 if ( $this->isUserCssPreview() ) {
3527 $append[] = $this->makeResourceLoaderLink(
3529 ResourceLoaderModule
::TYPE_STYLES
,
3530 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
3533 // Load the previewed CSS. Janus it if needed.
3534 // User-supplied CSS is assumed to in the wiki's content language.
3535 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3536 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3537 $previewedCSS = CSSJanus
::transform( $previewedCSS, true, false );
3539 $append[] = Html
::inlineStyle( $previewedCSS );
3542 // We want site, private and user styles to override dynamically added styles from
3543 // general modules, but we want dynamically added styles to override statically added
3544 // style modules. So the order has to be:
3545 // - page style modules (formatted by ResourceLoaderClientHtml::getHeadHtml())
3546 // - dynamically loaded styles (added by mw.loader before ResourceLoaderDynamicStyles)
3547 // - ResourceLoaderDynamicStyles marker
3548 // - site/private/user styles
3550 // Add legacy styles added through addStyle()/addInlineStyle() here
3551 $chunks[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3553 $chunks[] = Html
::element(
3555 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
3558 foreach ( $this->rlExemptStyleModules
as $group => $moduleNames ) {
3559 $chunks[] = $this->makeResourceLoaderLink( $moduleNames,
3560 ResourceLoaderModule
::TYPE_STYLES
3564 return self
::combineWrappedStrings( array_merge( $chunks, $append ) );
3570 public function buildCssLinksArray() {
3573 // Add any extension CSS
3574 foreach ( $this->mExtStyles
as $url ) {
3575 $this->addStyle( $url );
3577 $this->mExtStyles
= [];
3579 foreach ( $this->styles
as $file => $options ) {
3580 $link = $this->styleLink( $file, $options );
3582 $links[$file] = $link;
3589 * Generate \<link\> tags for stylesheets
3591 * @param string $style URL to the file
3592 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3593 * @return string HTML fragment
3595 protected function styleLink( $style, array $options ) {
3596 if ( isset( $options['dir'] ) ) {
3597 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3602 if ( isset( $options['media'] ) ) {
3603 $media = self
::transformCssMedia( $options['media'] );
3604 if ( is_null( $media ) ) {
3611 if ( substr( $style, 0, 1 ) == '/' ||
3612 substr( $style, 0, 5 ) == 'http:' ||
3613 substr( $style, 0, 6 ) == 'https:' ) {
3616 $config = $this->getConfig();
3617 $url = $config->get( 'StylePath' ) . '/' . $style . '?' .
3618 $config->get( 'StyleVersion' );
3621 $link = Html
::linkedStyle( $url, $media );
3623 if ( isset( $options['condition'] ) ) {
3624 $condition = htmlspecialchars( $options['condition'] );
3625 $link = "<!--[if $condition]>$link<![endif]-->";
3631 * Transform path to web-accessible static resource.
3633 * This is used to add a validation hash as query string.
3634 * This aids various behaviors:
3636 * - Put long Cache-Control max-age headers on responses for improved
3637 * cache performance.
3638 * - Get the correct version of a file as expected by the current page.
3639 * - Instantly get the updated version of a file after deployment.
3641 * Avoid using this for urls included in HTML as otherwise clients may get different
3642 * versions of a resource when navigating the site depending on when the page was cached.
3643 * If changes to the url propagate, this is not a problem (e.g. if the url is in
3644 * an external stylesheet).
3647 * @param Config $config
3648 * @param string $path Path-absolute URL to file (from document root, must start with "/")
3649 * @return string URL
3651 public static function transformResourcePath( Config
$config, $path ) {
3653 $remotePathPrefix = $config->get( 'ResourceBasePath' );
3654 if ( $remotePathPrefix === '' ) {
3655 // The configured base path is required to be empty string for
3656 // wikis in the domain root
3659 $remotePath = $remotePathPrefix;
3661 if ( strpos( $path, $remotePath ) !== 0 ) {
3662 // Path is outside wgResourceBasePath, ignore.
3665 $path = RelPath\
getRelativePath( $path, $remotePath );
3666 return self
::transformFilePath( $remotePathPrefix, $IP, $path );
3670 * Utility method for transformResourceFilePath().
3672 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
3675 * @param string $remotePath URL path prefix that points to $localPath
3676 * @param string $localPath File directory exposed at $remotePath
3677 * @param string $file Path to target file relative to $localPath
3678 * @return string URL
3680 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
3681 $hash = md5_file( "$localPath/$file" );
3682 if ( $hash === false ) {
3683 wfLogWarning( __METHOD__
. ": Failed to hash $localPath/$file" );
3686 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
3690 * Transform "media" attribute based on request parameters
3692 * @param string $media Current value of the "media" attribute
3693 * @return string Modified value of the "media" attribute, or null to skip
3696 public static function transformCssMedia( $media ) {
3699 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3700 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3702 // Switch in on-screen display for media testing
3704 'printable' => 'print',
3705 'handheld' => 'handheld',
3707 foreach ( $switches as $switch => $targetMedia ) {
3708 if ( $wgRequest->getBool( $switch ) ) {
3709 if ( $media == $targetMedia ) {
3711 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3712 /* This regex will not attempt to understand a comma-separated media_query_list
3714 * Example supported values for $media:
3715 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3716 * Example NOT supported value for $media:
3717 * '3d-glasses, screen, print and resolution > 90dpi'
3719 * If it's a print request, we never want any kind of screen stylesheets
3720 * If it's a handheld request (currently the only other choice with a switch),
3721 * we don't want simple 'screen' but we might want screen queries that
3722 * have a max-width or something, so we'll pass all others on and let the
3723 * client do the query.
3725 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3736 * Add a wikitext-formatted message to the output.
3737 * This is equivalent to:
3739 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3741 public function addWikiMsg( /*...*/ ) {
3742 $args = func_get_args();
3743 $name = array_shift( $args );
3744 $this->addWikiMsgArray( $name, $args );
3748 * Add a wikitext-formatted message to the output.
3749 * Like addWikiMsg() except the parameters are taken as an array
3750 * instead of a variable argument list.
3752 * @param string $name
3753 * @param array $args
3755 public function addWikiMsgArray( $name, $args ) {
3756 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3760 * This function takes a number of message/argument specifications, wraps them in
3761 * some overall structure, and then parses the result and adds it to the output.
3763 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3764 * and so on. The subsequent arguments may be either
3765 * 1) strings, in which case they are message names, or
3766 * 2) arrays, in which case, within each array, the first element is the message
3767 * name, and subsequent elements are the parameters to that message.
3769 * Don't use this for messages that are not in the user's interface language.
3773 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3777 * $wgOut->addWikiText( "<div class='error'>\n"
3778 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3780 * The newline after the opening div is needed in some wikitext. See bug 19226.
3782 * @param string $wrap
3784 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3785 $msgSpecs = func_get_args();
3786 array_shift( $msgSpecs );
3787 $msgSpecs = array_values( $msgSpecs );
3789 foreach ( $msgSpecs as $n => $spec ) {
3790 if ( is_array( $spec ) ) {
3792 $name = array_shift( $args );
3793 if ( isset( $args['options'] ) ) {
3794 unset( $args['options'] );
3796 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3804 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3806 $this->addWikiText( $s );
3810 * Enables/disables TOC, doesn't override __NOTOC__
3814 public function enableTOC( $flag = true ) {
3815 $this->mEnableTOC
= $flag;
3822 public function isTOCEnabled() {
3823 return $this->mEnableTOC
;
3827 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3831 public function enableSectionEditLinks( $flag = true ) {
3832 $this->mEnableSectionEditLinks
= $flag;
3839 public function sectionEditLinksEnabled() {
3840 return $this->mEnableSectionEditLinks
;
3844 * Helper function to setup the PHP implementation of OOUI to use in this request.
3847 * @param String $skinName The Skin name to determine the correct OOUI theme
3848 * @param String $dir Language direction
3850 public static function setupOOUI( $skinName = '', $dir = 'ltr' ) {
3851 $themes = ExtensionRegistry
::getInstance()->getAttribute( 'SkinOOUIThemes' );
3852 // Make keys (skin names) lowercase for case-insensitive matching.
3853 $themes = array_change_key_case( $themes, CASE_LOWER
);
3854 $theme = isset( $themes[$skinName] ) ?
$themes[$skinName] : 'MediaWiki';
3855 // For example, 'OOUI\MediaWikiTheme'.
3856 $themeClass = "OOUI\\{$theme}Theme";
3857 OOUI\Theme
::setSingleton( new $themeClass() );
3858 OOUI\Element
::setDefaultDir( $dir );
3862 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
3863 * MediaWiki and this OutputPage instance.
3867 public function enableOOUI() {
3869 strtolower( $this->getSkin()->getSkinName() ),
3870 $this->getLanguage()->getDir()
3872 $this->addModuleStyles( [
3873 'oojs-ui-core.styles',
3874 'oojs-ui.styles.icons',
3875 'oojs-ui.styles.indicators',
3876 'oojs-ui.styles.textures',
3877 'mediawiki.widgets.styles',
3882 * @param array $data Data from ParserOutput::getLimitReportData()
3885 public function setLimitReportData( array $data ) {
3886 $this->limitReportData
= $data;