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 = '';
71 * Holds the debug lines that will be output as comments in page source if
72 * $wgDebugComments is enabled. See also $wgShowDebug.
73 * @deprecated since 1.20; use MWDebug class instead.
75 public $mDebugtext = '';
77 /** @var string Stores contents of "<title>" tag */
78 private $mHTMLtitle = '';
81 * @var bool Is the displayed content related to the source of the
82 * corresponding wiki article.
84 private $mIsarticle = false;
86 /** @var bool Stores "article flag" toggle. */
87 private $mIsArticleRelated = true;
90 * @var bool We have to set isPrintable(). Some pages should
91 * never be printed (ex: redirections).
93 private $mPrintable = false;
96 * @var array Contains the page subtitle. Special pages usually have some
97 * links here. Don't confuse with site subtitle added by skins.
99 private $mSubtitle = [];
102 public $mRedirect = '';
105 protected $mStatusCode;
108 * @var string Used for sending cache control.
109 * The whole caching system should probably be moved into its own class.
111 protected $mLastModified = '';
114 protected $mCategoryLinks = [];
117 protected $mCategories = [];
120 protected $mIndicators = [];
122 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
123 private $mLanguageLinks = [];
126 * Used for JavaScript (predates ResourceLoader)
127 * @todo We should split JS / CSS.
128 * mScripts content is inserted as is in "<head>" by Skin. This might
129 * contain either a link to a stylesheet or inline CSS.
131 private $mScripts = '';
133 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
134 protected $mInlineStyles = '';
137 * @var string Used by skin template.
138 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
140 public $mPageLinkTitle = '';
142 /** @var array Array of elements in "<head>". Parser might add its own headers! */
143 protected $mHeadItems = [];
146 protected $mModules = [];
149 protected $mModuleScripts = [];
152 protected $mModuleStyles = [];
154 /** @var ResourceLoader */
155 protected $mResourceLoader;
157 /** @var ResourceLoaderClientHtml */
160 /** @var ResourceLoaderContext */
161 private $rlClientContext;
164 private $rlUserModuleState;
167 protected $mJsConfigVars = [];
170 protected $mTemplateIds = [];
173 protected $mImageTimeKeys = [];
176 public $mRedirectCode = '';
178 protected $mFeedLinksAppendQuery = null;
181 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
182 * @see ResourceLoaderModule::$origin
183 * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
185 protected $mAllowedModules = [
186 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
189 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
190 protected $mDoNothing = false;
195 protected $mContainsNewMagic = 0;
198 * lazy initialised, use parserOptions()
201 protected $mParserOptions = null;
204 * Handles the Atom / RSS links.
205 * We probably only support Atom in 2011.
206 * @see $wgAdvertisedFeedTypes
208 private $mFeedLinks = [];
210 // Gwicke work on squid caching? Roughly from 2003.
211 protected $mEnableClientCache = true;
213 /** @var bool Flag if output should only contain the body of the article. */
214 private $mArticleBodyOnly = false;
217 protected $mNewSectionLink = false;
220 protected $mHideNewSectionLink = false;
223 * @var bool Comes from the parser. This was probably made to load CSS/JS
224 * only if we had "<gallery>". Used directly in CategoryPage.php.
225 * Looks like ResourceLoader can replace this.
227 public $mNoGallery = false;
230 private $mPageTitleActionText = '';
232 /** @var int Cache stuff. Looks like mEnableClientCache */
233 protected $mCdnMaxage = 0;
234 /** @var int Upper limit on mCdnMaxage */
235 protected $mCdnMaxageLimit = INF
;
238 * @var bool Controls if anti-clickjacking / frame-breaking headers will
239 * be sent. This should be done for pages where edit actions are possible.
240 * Setters: $this->preventClickjacking() and $this->allowClickjacking().
242 protected $mPreventClickjacking = true;
244 /** @var int To include the variable {{REVISIONID}} */
245 private $mRevisionId = null;
248 private $mRevisionTimestamp = null;
251 protected $mFileVersion = null;
254 * @var array An array of stylesheet filenames (relative from skins path),
255 * with options for CSS media, IE conditions, and RTL/LTR direction.
256 * For internal use; add settings in the skin via $this->addStyle()
258 * Style again! This seems like a code duplication since we already have
259 * mStyles. This is what makes Open Source amazing.
261 protected $styles = [];
263 private $mIndexPolicy = 'index';
264 private $mFollowPolicy = 'follow';
265 private $mVaryHeader = [
266 'Accept-Encoding' => [ 'match=gzip' ],
270 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
275 private $mRedirectedFrom = null;
278 * Additional key => value data
280 private $mProperties = [];
283 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
285 private $mTarget = null;
288 * @var bool Whether parser output should contain table of contents
290 private $mEnableTOC = true;
293 * @var bool Whether parser output should contain section edit links
295 private $mEnableSectionEditLinks = true;
298 * @var string|null The URL to send in a <link> element with rel=copyright
300 private $copyrightUrl;
302 /** @var array Profiling data */
303 private $limitReportData = [];
306 * Constructor for OutputPage. This should not be called directly.
307 * Instead a new RequestContext should be created and it will implicitly create
308 * a OutputPage tied to that context.
309 * @param IContextSource|null $context
311 function __construct( IContextSource
$context = null ) {
312 if ( $context === null ) {
313 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
314 wfDeprecated( __METHOD__
, '1.18' );
316 $this->setContext( $context );
321 * Redirect to $url rather than displaying the normal page
323 * @param string $url URL
324 * @param string $responsecode HTTP status code
326 public function redirect( $url, $responsecode = '302' ) {
327 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
328 $this->mRedirect
= str_replace( "\n", '', $url );
329 $this->mRedirectCode
= $responsecode;
333 * Get the URL to redirect to, or an empty string if not redirect URL set
337 public function getRedirect() {
338 return $this->mRedirect
;
342 * Set the copyright URL to send with the output.
343 * Empty string to omit, null to reset.
347 * @param string|null $url
349 public function setCopyrightUrl( $url ) {
350 $this->copyrightUrl
= $url;
354 * Set the HTTP status code to send with the output.
356 * @param int $statusCode
358 public function setStatusCode( $statusCode ) {
359 $this->mStatusCode
= $statusCode;
363 * Add a new "<meta>" tag
364 * To add an http-equiv meta tag, precede the name with "http:"
366 * @param string $name Tag name
367 * @param string $val Tag value
369 function addMeta( $name, $val ) {
370 array_push( $this->mMetatags
, [ $name, $val ] );
374 * Returns the current <meta> tags
379 public function getMetaTags() {
380 return $this->mMetatags
;
384 * Add a new \<link\> tag to the page header.
386 * Note: use setCanonicalUrl() for rel=canonical.
388 * @param array $linkarr Associative array of attributes.
390 function addLink( array $linkarr ) {
391 array_push( $this->mLinktags
, $linkarr );
395 * Returns the current <link> tags
400 public function getLinkTags() {
401 return $this->mLinktags
;
405 * Add a new \<link\> with "rel" attribute set to "meta"
407 * @param array $linkarr Associative array mapping attribute names to their
408 * values, both keys and values will be escaped, and the
409 * "rel" attribute will be automatically added
411 function addMetadataLink( array $linkarr ) {
412 $linkarr['rel'] = $this->getMetadataAttribute();
413 $this->addLink( $linkarr );
417 * Set the URL to be used for the <link rel=canonical>. This should be used
418 * in preference to addLink(), to avoid duplicate link tags.
421 function setCanonicalUrl( $url ) {
422 $this->mCanonicalUrl
= $url;
426 * Returns the URL to be used for the <link rel=canonical> if
430 * @return bool|string
432 public function getCanonicalUrl() {
433 return $this->mCanonicalUrl
;
437 * Get the value of the "rel" attribute for metadata links
441 public function getMetadataAttribute() {
442 # note: buggy CC software only reads first "meta" link
443 static $haveMeta = false;
445 return 'alternate meta';
453 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
454 * Internal use only. Use OutputPage::addModules() or OutputPage::addJsConfigVars()
457 * @param string $script Raw HTML
459 function addScript( $script ) {
460 $this->mScripts
.= $script;
464 * Register and add a stylesheet from an extension directory.
466 * @deprecated since 1.27 use addModuleStyles() or addStyle() instead
467 * @param string $url Path to sheet. Provide either a full url (beginning
468 * with 'http', etc) or a relative path from the document root
469 * (beginning with '/'). Otherwise it behaves identically to
470 * addStyle() and draws from the /skins folder.
472 public function addExtensionStyle( $url ) {
473 wfDeprecated( __METHOD__
, '1.27' );
474 array_push( $this->mExtStyles
, $url );
478 * Get all styles added by extensions
480 * @deprecated since 1.27
483 function getExtStyle() {
484 wfDeprecated( __METHOD__
, '1.27' );
485 return $this->mExtStyles
;
489 * Add a JavaScript file out of skins/common, or a given relative path.
490 * Internal use only. Use OutputPage::addModules() if possible.
492 * @param string $file Filename in skins/common or complete on-server path
494 * @param string $version Style version of the file. Defaults to $wgStyleVersion
496 public function addScriptFile( $file, $version = null ) {
497 // See if $file parameter is an absolute URL or begins with a slash
498 if ( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
501 $path = $this->getConfig()->get( 'StylePath' ) . "/common/{$file}";
503 if ( is_null( $version ) ) {
504 $version = $this->getConfig()->get( 'StyleVersion' );
506 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
510 * Add a self-contained script tag with the given contents
511 * Internal use only. Use OutputPage::addModules() if possible.
513 * @param string $script JavaScript text, no script tags
515 public function addInlineScript( $script ) {
516 $this->mScripts
.= Html
::inlineScript( $script );
520 * Filter an array of modules to remove insufficiently trustworthy members, and modules
521 * which are no longer registered (eg a page is cached before an extension is disabled)
522 * @param array $modules
523 * @param string|null $position If not null, only return modules with this position
524 * @param string $type
527 protected function filterModules( array $modules, $position = null,
528 $type = ResourceLoaderModule
::TYPE_COMBINED
530 $resourceLoader = $this->getResourceLoader();
531 $filteredModules = [];
532 foreach ( $modules as $val ) {
533 $module = $resourceLoader->getModule( $val );
534 if ( $module instanceof ResourceLoaderModule
535 && $module->getOrigin() <= $this->getAllowedModules( $type )
536 && ( is_null( $position ) ||
$module->getPosition() == $position )
537 && ( !$this->mTarget ||
in_array( $this->mTarget
, $module->getTargets() ) )
539 $filteredModules[] = $val;
542 return $filteredModules;
546 * Get the list of modules to include on this page
548 * @param bool $filter Whether to filter out insufficiently trustworthy modules
549 * @param string|null $position If not null, only return modules with this position
550 * @param string $param
551 * @return array Array of module names
553 public function getModules( $filter = false, $position = null, $param = 'mModules',
554 $type = ResourceLoaderModule
::TYPE_COMBINED
556 $modules = array_values( array_unique( $this->$param ) );
558 ?
$this->filterModules( $modules, $position, $type )
563 * Add one or more modules recognized by ResourceLoader. Modules added
564 * through this function will be loaded by ResourceLoader when the
567 * @param string|array $modules Module name (string) or array of module names
569 public function addModules( $modules ) {
570 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
574 * Get the list of module JS to include on this page
576 * @param bool $filter
577 * @param string|null $position
578 * @return array Array of module names
580 public function getModuleScripts( $filter = false, $position = null ) {
581 return $this->getModules( $filter, $position, 'mModuleScripts',
582 ResourceLoaderModule
::TYPE_SCRIPTS
587 * Add only JS of one or more modules recognized by ResourceLoader. Module
588 * scripts added through this function will be loaded by ResourceLoader when
591 * @param string|array $modules Module name (string) or array of module names
593 public function addModuleScripts( $modules ) {
594 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
598 * Get the list of module CSS to include on this page
600 * @param bool $filter
601 * @param string|null $position
602 * @return array Array of module names
604 public function getModuleStyles( $filter = false, $position = null ) {
605 return $this->getModules( $filter, $position, 'mModuleStyles',
606 ResourceLoaderModule
::TYPE_STYLES
611 * Add only CSS of one or more modules recognized by ResourceLoader.
613 * Module styles added through this function will be added using standard link CSS
614 * tags, rather than as a combined Javascript and CSS package. Thus, they will
615 * load when JavaScript is disabled (unless CSS also happens to be disabled).
617 * @param string|array $modules Module name (string) or array of module names
619 public function addModuleStyles( $modules ) {
620 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
624 * @return null|string ResourceLoader target
626 public function getTarget() {
627 return $this->mTarget
;
631 * Sets ResourceLoader target for load.php links. If null, will be omitted
633 * @param string|null $target
635 public function setTarget( $target ) {
636 $this->mTarget
= $target;
640 * Get an array of head items
644 function getHeadItemsArray() {
645 return $this->mHeadItems
;
649 * Add or replace an header item to the output
651 * Whenever possible, use more specific options like ResourceLoader modules,
652 * OutputPage::addLink(), OutputPage::addMetaLink() and OutputPage::addFeedLink()
653 * Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
654 * OutputPage::addInlineScript() and OutputPage::addInlineStyle()
655 * This would be your very LAST fallback.
657 * @param string $name Item name
658 * @param string $value Raw HTML
660 public function addHeadItem( $name, $value ) {
661 $this->mHeadItems
[$name] = $value;
665 * Check if the header item $name is already set
667 * @param string $name Item name
670 public function hasHeadItem( $name ) {
671 return isset( $this->mHeadItems
[$name] );
675 * @deprecated since 1.28 Obsolete - wgUseETag experiment was removed.
678 public function setETag( $tag ) {
682 * Set whether the output should only contain the body of the article,
683 * without any skin, sidebar, etc.
684 * Used e.g. when calling with "action=render".
686 * @param bool $only Whether to output only the body of the article
688 public function setArticleBodyOnly( $only ) {
689 $this->mArticleBodyOnly
= $only;
693 * Return whether the output will contain only the body of the article
697 public function getArticleBodyOnly() {
698 return $this->mArticleBodyOnly
;
702 * Set an additional output property
705 * @param string $name
706 * @param mixed $value
708 public function setProperty( $name, $value ) {
709 $this->mProperties
[$name] = $value;
713 * Get an additional output property
716 * @param string $name
717 * @return mixed Property value or null if not found
719 public function getProperty( $name ) {
720 if ( isset( $this->mProperties
[$name] ) ) {
721 return $this->mProperties
[$name];
728 * checkLastModified tells the client to use the client-cached page if
729 * possible. If successful, the OutputPage is disabled so that
730 * any future call to OutputPage->output() have no effect.
732 * Side effect: sets mLastModified for Last-Modified header
734 * @param string $timestamp
736 * @return bool True if cache-ok headers was sent.
738 public function checkLastModified( $timestamp ) {
739 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
740 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
743 $config = $this->getConfig();
744 if ( !$config->get( 'CachePages' ) ) {
745 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
749 $timestamp = wfTimestamp( TS_MW
, $timestamp );
751 'page' => $timestamp,
752 'user' => $this->getUser()->getTouched(),
753 'epoch' => $config->get( 'CacheEpoch' )
755 if ( $config->get( 'UseSquid' ) ) {
756 // bug 44570: the core page itself may not change, but resources might
757 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, time() - $config->get( 'SquidMaxage' ) );
759 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this ] );
761 $maxModified = max( $modifiedTimes );
762 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
764 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
765 if ( $clientHeader === false ) {
766 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header", 'private' );
770 # IE sends sizes after the date like this:
771 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
772 # this breaks strtotime().
773 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
775 MediaWiki\
suppressWarnings(); // E_STRICT system time bitching
776 $clientHeaderTime = strtotime( $clientHeader );
777 MediaWiki\restoreWarnings
();
778 if ( !$clientHeaderTime ) {
780 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
783 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
787 foreach ( $modifiedTimes as $name => $value ) {
788 if ( $info !== '' ) {
791 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
794 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
795 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ), 'private' );
796 wfDebug( __METHOD__
. ": effective Last-Modified: " .
797 wfTimestamp( TS_ISO_8601
, $maxModified ), 'private' );
798 if ( $clientHeaderTime < $maxModified ) {
799 wfDebug( __METHOD__
. ": STALE, $info", 'private' );
804 # Give a 304 Not Modified response code and disable body output
805 wfDebug( __METHOD__
. ": NOT MODIFIED, $info", 'private' );
806 ini_set( 'zlib.output_compression', 0 );
807 $this->getRequest()->response()->statusHeader( 304 );
808 $this->sendCacheControl();
811 // Don't output a compressed blob when using ob_gzhandler;
812 // it's technically against HTTP spec and seems to confuse
813 // Firefox when the response gets split over two packets.
814 wfClearOutputBuffers();
820 * Override the last modified timestamp
822 * @param string $timestamp New timestamp, in a format readable by
825 public function setLastModified( $timestamp ) {
826 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
830 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
832 * @param string $policy The literal string to output as the contents of
833 * the meta tag. Will be parsed according to the spec and output in
837 public function setRobotPolicy( $policy ) {
838 $policy = Article
::formatRobotPolicy( $policy );
840 if ( isset( $policy['index'] ) ) {
841 $this->setIndexPolicy( $policy['index'] );
843 if ( isset( $policy['follow'] ) ) {
844 $this->setFollowPolicy( $policy['follow'] );
849 * Set the index policy for the page, but leave the follow policy un-
852 * @param string $policy Either 'index' or 'noindex'.
855 public function setIndexPolicy( $policy ) {
856 $policy = trim( $policy );
857 if ( in_array( $policy, [ 'index', 'noindex' ] ) ) {
858 $this->mIndexPolicy
= $policy;
863 * Set the follow policy for the page, but leave the index policy un-
866 * @param string $policy Either 'follow' or 'nofollow'.
869 public function setFollowPolicy( $policy ) {
870 $policy = trim( $policy );
871 if ( in_array( $policy, [ 'follow', 'nofollow' ] ) ) {
872 $this->mFollowPolicy
= $policy;
877 * Set the new value of the "action text", this will be added to the
878 * "HTML title", separated from it with " - ".
880 * @param string $text New value of the "action text"
882 public function setPageTitleActionText( $text ) {
883 $this->mPageTitleActionText
= $text;
887 * Get the value of the "action text"
891 public function getPageTitleActionText() {
892 return $this->mPageTitleActionText
;
896 * "HTML title" means the contents of "<title>".
897 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
899 * @param string|Message $name
901 public function setHTMLTitle( $name ) {
902 if ( $name instanceof Message
) {
903 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
905 $this->mHTMLtitle
= $name;
910 * Return the "HTML title", i.e. the content of the "<title>" tag.
914 public function getHTMLTitle() {
915 return $this->mHTMLtitle
;
919 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
923 public function setRedirectedFrom( $t ) {
924 $this->mRedirectedFrom
= $t;
928 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
929 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
930 * but not bad tags like \<script\>. This function automatically sets
931 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
932 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
933 * good tags like \<i\> will be dropped entirely.
935 * @param string|Message $name
937 public function setPageTitle( $name ) {
938 if ( $name instanceof Message
) {
939 $name = $name->setContext( $this->getContext() )->text();
942 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
943 # but leave "<i>foobar</i>" alone
944 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
945 $this->mPagetitle
= $nameWithTags;
947 # change "<i>foo&bar</i>" to "foo&bar"
949 $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) )
950 ->inContentLanguage()
955 * Return the "page title", i.e. the content of the \<h1\> tag.
959 public function getPageTitle() {
960 return $this->mPagetitle
;
964 * Set the Title object to use
968 public function setTitle( Title
$t ) {
969 $this->getContext()->setTitle( $t );
973 * Replace the subtitle with $str
975 * @param string|Message $str New value of the subtitle. String should be safe HTML.
977 public function setSubtitle( $str ) {
978 $this->clearSubtitle();
979 $this->addSubtitle( $str );
983 * Add $str to the subtitle
985 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
987 public function addSubtitle( $str ) {
988 if ( $str instanceof Message
) {
989 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
991 $this->mSubtitle
[] = $str;
996 * Build message object for a subtitle containing a backlink to a page
998 * @param Title $title Title to link to
999 * @param array $query Array of additional parameters to include in the link
1003 public static function buildBacklinkSubtitle( Title
$title, $query = [] ) {
1004 if ( $title->isRedirect() ) {
1005 $query['redirect'] = 'no';
1007 return wfMessage( 'backlinksubtitle' )
1008 ->rawParams( Linker
::link( $title, null, [], $query ) );
1012 * Add a subtitle containing a backlink to a page
1014 * @param Title $title Title to link to
1015 * @param array $query Array of additional parameters to include in the link
1017 public function addBacklinkSubtitle( Title
$title, $query = [] ) {
1018 $this->addSubtitle( self
::buildBacklinkSubtitle( $title, $query ) );
1022 * Clear the subtitles
1024 public function clearSubtitle() {
1025 $this->mSubtitle
= [];
1033 public function getSubtitle() {
1034 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1038 * Set the page as printable, i.e. it'll be displayed with all
1039 * print styles included
1041 public function setPrintable() {
1042 $this->mPrintable
= true;
1046 * Return whether the page is "printable"
1050 public function isPrintable() {
1051 return $this->mPrintable
;
1055 * Disable output completely, i.e. calling output() will have no effect
1057 public function disable() {
1058 $this->mDoNothing
= true;
1062 * Return whether the output will be completely disabled
1066 public function isDisabled() {
1067 return $this->mDoNothing
;
1071 * Show an "add new section" link?
1075 public function showNewSectionLink() {
1076 return $this->mNewSectionLink
;
1080 * Forcibly hide the new section link?
1084 public function forceHideNewSectionLink() {
1085 return $this->mHideNewSectionLink
;
1089 * Add or remove feed links in the page header
1090 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1091 * for the new version
1092 * @see addFeedLink()
1094 * @param bool $show True: add default feeds, false: remove all feeds
1096 public function setSyndicated( $show = true ) {
1098 $this->setFeedAppendQuery( false );
1100 $this->mFeedLinks
= [];
1105 * Add default feeds to the page header
1106 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1107 * for the new version
1108 * @see addFeedLink()
1110 * @param string $val Query to append to feed links or false to output
1113 public function setFeedAppendQuery( $val ) {
1114 $this->mFeedLinks
= [];
1116 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1117 $query = "feed=$type";
1118 if ( is_string( $val ) ) {
1119 $query .= '&' . $val;
1121 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1126 * Add a feed link to the page header
1128 * @param string $format Feed type, should be a key of $wgFeedClasses
1129 * @param string $href URL
1131 public function addFeedLink( $format, $href ) {
1132 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1133 $this->mFeedLinks
[$format] = $href;
1138 * Should we output feed links for this page?
1141 public function isSyndicated() {
1142 return count( $this->mFeedLinks
) > 0;
1146 * Return URLs for each supported syndication format for this page.
1147 * @return array Associating format keys with URLs
1149 public function getSyndicationLinks() {
1150 return $this->mFeedLinks
;
1154 * Will currently always return null
1158 public function getFeedAppendQuery() {
1159 return $this->mFeedLinksAppendQuery
;
1163 * Set whether the displayed content is related to the source of the
1164 * corresponding article on the wiki
1165 * Setting true will cause the change "article related" toggle to true
1169 public function setArticleFlag( $v ) {
1170 $this->mIsarticle
= $v;
1172 $this->mIsArticleRelated
= $v;
1177 * Return whether the content displayed page is related to the source of
1178 * the corresponding article on the wiki
1182 public function isArticle() {
1183 return $this->mIsarticle
;
1187 * Set whether this page is related an article on the wiki
1188 * Setting false will cause the change of "article flag" toggle to false
1192 public function setArticleRelated( $v ) {
1193 $this->mIsArticleRelated
= $v;
1195 $this->mIsarticle
= false;
1200 * Return whether this page is related an article on the wiki
1204 public function isArticleRelated() {
1205 return $this->mIsArticleRelated
;
1209 * Add new language links
1211 * @param array $newLinkArray Associative array mapping language code to the page
1214 public function addLanguageLinks( array $newLinkArray ) {
1215 $this->mLanguageLinks +
= $newLinkArray;
1219 * Reset the language links and add new language links
1221 * @param array $newLinkArray Associative array mapping language code to the page
1224 public function setLanguageLinks( array $newLinkArray ) {
1225 $this->mLanguageLinks
= $newLinkArray;
1229 * Get the list of language links
1231 * @return array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1233 public function getLanguageLinks() {
1234 return $this->mLanguageLinks
;
1238 * Add an array of categories, with names in the keys
1240 * @param array $categories Mapping category name => sort key
1242 public function addCategoryLinks( array $categories ) {
1245 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1249 # Add the links to a LinkBatch
1250 $arr = [ NS_CATEGORY
=> $categories ];
1251 $lb = new LinkBatch
;
1252 $lb->setArray( $arr );
1254 # Fetch existence plus the hiddencat property
1255 $dbr = wfGetDB( DB_SLAVE
);
1256 $fields = array_merge(
1257 LinkCache
::getSelectFields(),
1258 [ 'page_namespace', 'page_title', 'pp_value' ]
1261 $res = $dbr->select( [ 'page', 'page_props' ],
1263 $lb->constructSet( 'page', $dbr ),
1266 [ 'page_props' => [ 'LEFT JOIN', [
1267 'pp_propname' => 'hiddencat',
1272 # Add the results to the link cache
1273 $lb->addResultToCache( LinkCache
::singleton(), $res );
1275 # Set all the values to 'normal'.
1276 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1278 # Mark hidden categories
1279 foreach ( $res as $row ) {
1280 if ( isset( $row->pp_value
) ) {
1281 $categories[$row->page_title
] = 'hidden';
1285 # Add the remaining categories to the skin
1287 'OutputPageMakeCategoryLinks',
1288 [ &$this, $categories, &$this->mCategoryLinks
] )
1290 foreach ( $categories as $category => $type ) {
1291 // array keys will cast numeric category names to ints, so cast back to string
1292 $category = (string)$category;
1293 $origcategory = $category;
1294 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1298 $wgContLang->findVariantLink( $category, $title, true );
1299 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1302 $text = $wgContLang->convertHtml( $title->getText() );
1303 $this->mCategories
[] = $title->getText();
1304 $this->mCategoryLinks
[$type][] = Linker
::link( $title, $text );
1310 * Reset the category links (but not the category list) and add $categories
1312 * @param array $categories Mapping category name => sort key
1314 public function setCategoryLinks( array $categories ) {
1315 $this->mCategoryLinks
= [];
1316 $this->addCategoryLinks( $categories );
1320 * Get the list of category links, in a 2-D array with the following format:
1321 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1322 * hidden categories) and $link a HTML fragment with a link to the category
1327 public function getCategoryLinks() {
1328 return $this->mCategoryLinks
;
1332 * Get the list of category names this page belongs to
1334 * @return array Array of strings
1336 public function getCategories() {
1337 return $this->mCategories
;
1341 * Add an array of indicators, with their identifiers as array
1342 * keys and HTML contents as values.
1344 * In case of duplicate keys, existing values are overwritten.
1346 * @param array $indicators
1349 public function setIndicators( array $indicators ) {
1350 $this->mIndicators
= $indicators +
$this->mIndicators
;
1351 // Keep ordered by key
1352 ksort( $this->mIndicators
);
1356 * Get the indicators associated with this page.
1358 * The array will be internally ordered by item keys.
1360 * @return array Keys: identifiers, values: HTML contents
1363 public function getIndicators() {
1364 return $this->mIndicators
;
1368 * Adds help link with an icon via page indicators.
1369 * Link target can be overridden by a local message containing a wikilink:
1370 * the message key is: lowercase action or special page name + '-helppage'.
1371 * @param string $to Target MediaWiki.org page title or encoded URL.
1372 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1375 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1376 $this->addModuleStyles( 'mediawiki.helplink' );
1377 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1379 if ( $overrideBaseUrl ) {
1382 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1383 $helpUrl = "//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1386 $link = Html
::rawElement(
1390 'target' => '_blank',
1391 'class' => 'mw-helplink',
1396 $this->setIndicators( [ 'mw-helplink' => $link ] );
1400 * Do not allow scripts which can be modified by wiki users to load on this page;
1401 * only allow scripts bundled with, or generated by, the software.
1402 * Site-wide styles are controlled by a config setting, since they can be
1403 * used to create a custom skin/theme, but not user-specific ones.
1405 * @todo this should be given a more accurate name
1407 public function disallowUserJs() {
1408 $this->reduceAllowedModules(
1409 ResourceLoaderModule
::TYPE_SCRIPTS
,
1410 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1413 // Site-wide styles are controlled by a config setting, see bug 71621
1414 // for background on why. User styles are never allowed.
1415 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1416 $styleOrigin = ResourceLoaderModule
::ORIGIN_USER_SITEWIDE
;
1418 $styleOrigin = ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
;
1420 $this->reduceAllowedModules(
1421 ResourceLoaderModule
::TYPE_STYLES
,
1427 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1428 * @see ResourceLoaderModule::$origin
1429 * @param string $type ResourceLoaderModule TYPE_ constant
1430 * @return int ResourceLoaderModule ORIGIN_ class constant
1432 public function getAllowedModules( $type ) {
1433 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1434 return min( array_values( $this->mAllowedModules
) );
1436 return isset( $this->mAllowedModules
[$type] )
1437 ?
$this->mAllowedModules
[$type]
1438 : ResourceLoaderModule
::ORIGIN_ALL
;
1443 * Limit the highest level of CSS/JS untrustworthiness allowed.
1445 * If passed the same or a higher level than the current level of untrustworthiness set, the
1446 * level will remain unchanged.
1448 * @param string $type
1449 * @param int $level ResourceLoaderModule class constant
1451 public function reduceAllowedModules( $type, $level ) {
1452 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1456 * Prepend $text to the body HTML
1458 * @param string $text HTML
1460 public function prependHTML( $text ) {
1461 $this->mBodytext
= $text . $this->mBodytext
;
1465 * Append $text to the body HTML
1467 * @param string $text HTML
1469 public function addHTML( $text ) {
1470 $this->mBodytext
.= $text;
1474 * Shortcut for adding an Html::element via addHTML.
1478 * @param string $element
1479 * @param array $attribs
1480 * @param string $contents
1482 public function addElement( $element, array $attribs = [], $contents = '' ) {
1483 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1487 * Clear the body HTML
1489 public function clearHTML() {
1490 $this->mBodytext
= '';
1496 * @return string HTML
1498 public function getHTML() {
1499 return $this->mBodytext
;
1503 * Get/set the ParserOptions object to use for wikitext parsing
1505 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1506 * current ParserOption object
1507 * @return ParserOptions
1509 public function parserOptions( $options = null ) {
1510 if ( $options !== null && !empty( $options->isBogus
) ) {
1511 // Someone is trying to set a bogus pre-$wgUser PO. Check if it has
1512 // been changed somehow, and keep it if so.
1513 $anonPO = ParserOptions
::newFromAnon();
1514 $anonPO->setEditSection( false );
1515 if ( !$options->matches( $anonPO ) ) {
1516 wfLogWarning( __METHOD__
. ': Setting a changed bogus ParserOptions: ' . wfGetAllCallers( 5 ) );
1517 $options->isBogus
= false;
1521 if ( !$this->mParserOptions
) {
1522 if ( !$this->getContext()->getUser()->isSafeToLoad() ) {
1523 // $wgUser isn't unstubbable yet, so don't try to get a
1524 // ParserOptions for it. And don't cache this ParserOptions
1526 $po = ParserOptions
::newFromAnon();
1527 $po->setEditSection( false );
1528 $po->isBogus
= true;
1529 if ( $options !== null ) {
1530 $this->mParserOptions
= empty( $options->isBogus
) ?
$options : null;
1535 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1536 $this->mParserOptions
->setEditSection( false );
1539 if ( $options !== null && !empty( $options->isBogus
) ) {
1540 // They're trying to restore the bogus pre-$wgUser PO. Do the right
1542 return wfSetVar( $this->mParserOptions
, null, true );
1544 return wfSetVar( $this->mParserOptions
, $options );
1549 * Set the revision ID which will be seen by the wiki text parser
1550 * for things such as embedded {{REVISIONID}} variable use.
1552 * @param int|null $revid An positive integer, or null
1553 * @return mixed Previous value
1555 public function setRevisionId( $revid ) {
1556 $val = is_null( $revid ) ?
null : intval( $revid );
1557 return wfSetVar( $this->mRevisionId
, $val );
1561 * Get the displayed revision ID
1565 public function getRevisionId() {
1566 return $this->mRevisionId
;
1570 * Set the timestamp of the revision which will be displayed. This is used
1571 * to avoid a extra DB call in Skin::lastModified().
1573 * @param string|null $timestamp
1574 * @return mixed Previous value
1576 public function setRevisionTimestamp( $timestamp ) {
1577 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1581 * Get the timestamp of displayed revision.
1582 * This will be null if not filled by setRevisionTimestamp().
1584 * @return string|null
1586 public function getRevisionTimestamp() {
1587 return $this->mRevisionTimestamp
;
1591 * Set the displayed file version
1593 * @param File|bool $file
1594 * @return mixed Previous value
1596 public function setFileVersion( $file ) {
1598 if ( $file instanceof File
&& $file->exists() ) {
1599 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1601 return wfSetVar( $this->mFileVersion
, $val, true );
1605 * Get the displayed file version
1607 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1609 public function getFileVersion() {
1610 return $this->mFileVersion
;
1614 * Get the templates used on this page
1616 * @return array (namespace => dbKey => revId)
1619 public function getTemplateIds() {
1620 return $this->mTemplateIds
;
1624 * Get the files used on this page
1626 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1629 public function getFileSearchOptions() {
1630 return $this->mImageTimeKeys
;
1634 * Convert wikitext to HTML and add it to the buffer
1635 * Default assumes that the current page title will be used.
1637 * @param string $text
1638 * @param bool $linestart Is this the start of a line?
1639 * @param bool $interface Is this text in the user interface language?
1640 * @throws MWException
1642 public function addWikiText( $text, $linestart = true, $interface = true ) {
1643 $title = $this->getTitle(); // Work around E_STRICT
1645 throw new MWException( 'Title is null' );
1647 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1651 * Add wikitext with a custom Title object
1653 * @param string $text Wikitext
1654 * @param Title $title
1655 * @param bool $linestart Is this the start of a line?
1657 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1658 $this->addWikiTextTitle( $text, $title, $linestart );
1662 * Add wikitext with a custom Title object and tidy enabled.
1664 * @param string $text Wikitext
1665 * @param Title $title
1666 * @param bool $linestart Is this the start of a line?
1668 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1669 $this->addWikiTextTitle( $text, $title, $linestart, true );
1673 * Add wikitext with tidy enabled
1675 * @param string $text Wikitext
1676 * @param bool $linestart Is this the start of a line?
1678 public function addWikiTextTidy( $text, $linestart = true ) {
1679 $title = $this->getTitle();
1680 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1684 * Add wikitext with a custom Title object
1686 * @param string $text Wikitext
1687 * @param Title $title
1688 * @param bool $linestart Is this the start of a line?
1689 * @param bool $tidy Whether to use tidy
1690 * @param bool $interface Whether it is an interface message
1691 * (for example disables conversion)
1693 public function addWikiTextTitle( $text, Title
$title, $linestart,
1694 $tidy = false, $interface = false
1698 $popts = $this->parserOptions();
1699 $oldTidy = $popts->setTidy( $tidy );
1700 $popts->setInterfaceMessage( (bool)$interface );
1702 $parserOutput = $wgParser->getFreshParser()->parse(
1703 $text, $title, $popts,
1704 $linestart, true, $this->mRevisionId
1707 $popts->setTidy( $oldTidy );
1709 $this->addParserOutput( $parserOutput );
1714 * Add a ParserOutput object, but without Html.
1716 * @deprecated since 1.24, use addParserOutputMetadata() instead.
1717 * @param ParserOutput $parserOutput
1719 public function addParserOutputNoText( $parserOutput ) {
1720 wfDeprecated( __METHOD__
, '1.24' );
1721 $this->addParserOutputMetadata( $parserOutput );
1725 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1726 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1730 * @param ParserOutput $parserOutput
1732 public function addParserOutputMetadata( $parserOutput ) {
1733 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1734 $this->addCategoryLinks( $parserOutput->getCategories() );
1735 $this->setIndicators( $parserOutput->getIndicators() );
1736 $this->mNewSectionLink
= $parserOutput->getNewSection();
1737 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1739 if ( !$parserOutput->isCacheable() ) {
1740 $this->enableClientCache( false );
1742 $this->mNoGallery
= $parserOutput->getNoGallery();
1743 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1744 $this->addModules( $parserOutput->getModules() );
1745 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1746 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1747 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1748 $this->mPreventClickjacking
= $this->mPreventClickjacking
1749 ||
$parserOutput->preventClickjacking();
1751 // Template versioning...
1752 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1753 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1754 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1756 $this->mTemplateIds
[$ns] = $dbks;
1759 // File versioning...
1760 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1761 $this->mImageTimeKeys
[$dbk] = $data;
1764 // Hooks registered in the object
1765 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1766 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1767 list( $hookName, $data ) = $hookInfo;
1768 if ( isset( $parserOutputHooks[$hookName] ) ) {
1769 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1773 // Enable OOUI if requested via ParserOutput
1774 if ( $parserOutput->getEnableOOUI() ) {
1775 $this->enableOOUI();
1778 // Include profiling data
1779 $this->limitReportData
= $parserOutput->getLimitReportData();
1781 // Link flags are ignored for now, but may in the future be
1782 // used to mark individual language links.
1784 Hooks
::run( 'LanguageLinks', [ $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ] );
1785 Hooks
::run( 'OutputPageParserOutput', [ &$this, $parserOutput ] );
1789 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1790 * ParserOutput object, without any other metadata.
1793 * @param ParserOutput $parserOutput
1795 public function addParserOutputContent( $parserOutput ) {
1796 $this->addParserOutputText( $parserOutput );
1798 $this->addModules( $parserOutput->getModules() );
1799 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1800 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1802 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1806 * Add the HTML associated with a ParserOutput object, without any metadata.
1809 * @param ParserOutput $parserOutput
1811 public function addParserOutputText( $parserOutput ) {
1812 $text = $parserOutput->getText();
1813 Hooks
::run( 'OutputPageBeforeHTML', [ &$this, &$text ] );
1814 $this->addHTML( $text );
1818 * Add everything from a ParserOutput object.
1820 * @param ParserOutput $parserOutput
1822 function addParserOutput( $parserOutput ) {
1823 $this->addParserOutputMetadata( $parserOutput );
1824 $parserOutput->setTOCEnabled( $this->mEnableTOC
);
1826 // Touch section edit links only if not previously disabled
1827 if ( $parserOutput->getEditSectionTokens() ) {
1828 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks
);
1831 $this->addParserOutputText( $parserOutput );
1835 * Add the output of a QuickTemplate to the output buffer
1837 * @param QuickTemplate $template
1839 public function addTemplate( &$template ) {
1840 $this->addHTML( $template->getHTML() );
1844 * Parse wikitext and return the HTML.
1846 * @param string $text
1847 * @param bool $linestart Is this the start of a line?
1848 * @param bool $interface Use interface language ($wgLang instead of
1849 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1850 * This also disables LanguageConverter.
1851 * @param Language $language Target language object, will override $interface
1852 * @throws MWException
1853 * @return string HTML
1855 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1858 if ( is_null( $this->getTitle() ) ) {
1859 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1862 $popts = $this->parserOptions();
1864 $popts->setInterfaceMessage( true );
1866 if ( $language !== null ) {
1867 $oldLang = $popts->setTargetLanguage( $language );
1870 $parserOutput = $wgParser->getFreshParser()->parse(
1871 $text, $this->getTitle(), $popts,
1872 $linestart, true, $this->mRevisionId
1876 $popts->setInterfaceMessage( false );
1878 if ( $language !== null ) {
1879 $popts->setTargetLanguage( $oldLang );
1882 return $parserOutput->getText();
1886 * Parse wikitext, strip paragraphs, and return the HTML.
1888 * @param string $text
1889 * @param bool $linestart Is this the start of a line?
1890 * @param bool $interface Use interface language ($wgLang instead of
1891 * $wgContLang) while parsing language sensitive magic
1892 * words like GRAMMAR and PLURAL
1893 * @return string HTML
1895 public function parseInline( $text, $linestart = true, $interface = false ) {
1896 $parsed = $this->parse( $text, $linestart, $interface );
1897 return Parser
::stripOuterParagraph( $parsed );
1902 * @deprecated since 1.27 Use setCdnMaxage() instead
1904 public function setSquidMaxage( $maxage ) {
1905 $this->setCdnMaxage( $maxage );
1909 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1911 * @param int $maxage Maximum cache time on the CDN, in seconds.
1913 public function setCdnMaxage( $maxage ) {
1914 $this->mCdnMaxage
= min( $maxage, $this->mCdnMaxageLimit
);
1918 * Lower the value of the "s-maxage" part of the "Cache-control" HTTP header
1920 * @param int $maxage Maximum cache time on the CDN, in seconds
1923 public function lowerCdnMaxage( $maxage ) {
1924 $this->mCdnMaxageLimit
= min( $maxage, $this->mCdnMaxageLimit
);
1925 $this->setCdnMaxage( $this->mCdnMaxage
);
1929 * Use enableClientCache(false) to force it to send nocache headers
1931 * @param bool $state
1935 public function enableClientCache( $state ) {
1936 return wfSetVar( $this->mEnableClientCache
, $state );
1940 * Get the list of cookies that will influence on the cache
1944 function getCacheVaryCookies() {
1946 if ( $cookies === null ) {
1947 $config = $this->getConfig();
1948 $cookies = array_merge(
1949 SessionManager
::singleton()->getVaryCookies(),
1953 $config->get( 'CacheVaryCookies' )
1955 Hooks
::run( 'GetCacheVaryCookies', [ $this, &$cookies ] );
1961 * Check if the request has a cache-varying cookie header
1962 * If it does, it's very important that we don't allow public caching
1966 function haveCacheVaryCookies() {
1967 $request = $this->getRequest();
1968 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
1969 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
1970 wfDebug( __METHOD__
. ": found $cookieName\n" );
1974 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1979 * Add an HTTP header that will influence on the cache
1981 * @param string $header Header name
1982 * @param string[]|null $option Options for the Key header. See
1983 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
1984 * for the list of valid options.
1986 public function addVaryHeader( $header, array $option = null ) {
1987 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1988 $this->mVaryHeader
[$header] = [];
1990 if ( !is_array( $option ) ) {
1993 $this->mVaryHeader
[$header] = array_unique( array_merge( $this->mVaryHeader
[$header], $option ) );
1997 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
1998 * such as Accept-Encoding or Cookie
2002 public function getVaryHeader() {
2003 // If we vary on cookies, let's make sure it's always included here too.
2004 if ( $this->getCacheVaryCookies() ) {
2005 $this->addVaryHeader( 'Cookie' );
2008 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2009 $this->addVaryHeader( $header, $options );
2011 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader
) );
2015 * Get a complete Key header
2019 public function getKeyHeader() {
2020 $cvCookies = $this->getCacheVaryCookies();
2022 $cookiesOption = [];
2023 foreach ( $cvCookies as $cookieName ) {
2024 $cookiesOption[] = 'param=' . $cookieName;
2026 $this->addVaryHeader( 'Cookie', $cookiesOption );
2028 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2029 $this->addVaryHeader( $header, $options );
2033 foreach ( $this->mVaryHeader
as $header => $option ) {
2034 $newheader = $header;
2035 if ( is_array( $option ) && count( $option ) > 0 ) {
2036 $newheader .= ';' . implode( ';', $option );
2038 $headers[] = $newheader;
2040 $key = 'Key: ' . implode( ',', $headers );
2046 * T23672: Add Accept-Language to Vary and Key headers
2047 * if there's no 'variant' parameter existed in GET.
2050 * /w/index.php?title=Main_page should always be served; but
2051 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
2053 function addAcceptLanguage() {
2054 $title = $this->getTitle();
2055 if ( !$title instanceof Title
) {
2059 $lang = $title->getPageLanguage();
2060 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2061 $variants = $lang->getVariants();
2063 foreach ( $variants as $variant ) {
2064 if ( $variant === $lang->getCode() ) {
2067 $aloption[] = 'substr=' . $variant;
2069 // IE and some other browsers use BCP 47 standards in
2070 // their Accept-Language header, like "zh-CN" or "zh-Hant".
2071 // We should handle these too.
2072 $variantBCP47 = wfBCP47( $variant );
2073 if ( $variantBCP47 !== $variant ) {
2074 $aloption[] = 'substr=' . $variantBCP47;
2078 $this->addVaryHeader( 'Accept-Language', $aloption );
2083 * Set a flag which will cause an X-Frame-Options header appropriate for
2084 * edit pages to be sent. The header value is controlled by
2085 * $wgEditPageFrameOptions.
2087 * This is the default for special pages. If you display a CSRF-protected
2088 * form on an ordinary view page, then you need to call this function.
2090 * @param bool $enable
2092 public function preventClickjacking( $enable = true ) {
2093 $this->mPreventClickjacking
= $enable;
2097 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2098 * This can be called from pages which do not contain any CSRF-protected
2101 public function allowClickjacking() {
2102 $this->mPreventClickjacking
= false;
2106 * Get the prevent-clickjacking flag
2111 public function getPreventClickjacking() {
2112 return $this->mPreventClickjacking
;
2116 * Get the X-Frame-Options header value (without the name part), or false
2117 * if there isn't one. This is used by Skin to determine whether to enable
2118 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2122 public function getFrameOptions() {
2123 $config = $this->getConfig();
2124 if ( $config->get( 'BreakFrames' ) ) {
2126 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2127 return $config->get( 'EditPageFrameOptions' );
2133 * Send cache control HTTP headers
2135 public function sendCacheControl() {
2136 $response = $this->getRequest()->response();
2137 $config = $this->getConfig();
2139 $this->addVaryHeader( 'Cookie' );
2140 $this->addAcceptLanguage();
2142 # don't serve compressed data to clients who can't handle it
2143 # maintain different caches for logged-in users and non-logged in ones
2144 $response->header( $this->getVaryHeader() );
2146 if ( $config->get( 'UseKeyHeader' ) ) {
2147 $response->header( $this->getKeyHeader() );
2150 if ( $this->mEnableClientCache
) {
2152 $config->get( 'UseSquid' ) &&
2153 !$response->hasCookies() &&
2154 !SessionManager
::getGlobalSession()->isPersistent() &&
2155 !$this->isPrintable() &&
2156 $this->mCdnMaxage
!= 0 &&
2157 !$this->haveCacheVaryCookies()
2159 if ( $config->get( 'UseESI' ) ) {
2160 # We'll purge the proxy cache explicitly, but require end user agents
2161 # to revalidate against the proxy on each visit.
2162 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2163 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **", 'private' );
2164 # start with a shorter timeout for initial testing
2165 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2166 $response->header( 'Surrogate-Control: max-age=' . $config->get( 'SquidMaxage' )
2167 . '+' . $this->mCdnMaxage
. ', content="ESI/1.0"' );
2168 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2170 # We'll purge the proxy cache for anons explicitly, but require end user agents
2171 # to revalidate against the proxy on each visit.
2172 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2173 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2174 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **", 'private' );
2175 # start with a shorter timeout for initial testing
2176 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2177 $response->header( 'Cache-Control: s-maxage=' . $this->mCdnMaxage
2178 . ', must-revalidate, max-age=0' );
2181 # We do want clients to cache if they can, but they *must* check for updates
2182 # on revisiting the page.
2183 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **", 'private' );
2184 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2185 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2187 if ( $this->mLastModified
) {
2188 $response->header( "Last-Modified: {$this->mLastModified}" );
2191 wfDebug( __METHOD__
. ": no caching **", 'private' );
2193 # In general, the absence of a last modified header should be enough to prevent
2194 # the client from using its cache. We send a few other things just to make sure.
2195 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2196 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2197 $response->header( 'Pragma: no-cache' );
2202 * Finally, all the text has been munged and accumulated into
2203 * the object, let's actually output it:
2205 public function output() {
2206 if ( $this->mDoNothing
) {
2210 $response = $this->getRequest()->response();
2211 $config = $this->getConfig();
2213 if ( $this->mRedirect
!= '' ) {
2214 # Standards require redirect URLs to be absolute
2215 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2217 $redirect = $this->mRedirect
;
2218 $code = $this->mRedirectCode
;
2220 if ( Hooks
::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2221 if ( $code == '301' ||
$code == '303' ) {
2222 if ( !$config->get( 'DebugRedirects' ) ) {
2223 $response->statusHeader( $code );
2225 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2227 if ( $config->get( 'VaryOnXFP' ) ) {
2228 $this->addVaryHeader( 'X-Forwarded-Proto' );
2230 $this->sendCacheControl();
2232 $response->header( "Content-Type: text/html; charset=utf-8" );
2233 if ( $config->get( 'DebugRedirects' ) ) {
2234 $url = htmlspecialchars( $redirect );
2235 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2236 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2237 print "</body>\n</html>\n";
2239 $response->header( 'Location: ' . $redirect );
2244 } elseif ( $this->mStatusCode
) {
2245 $response->statusHeader( $this->mStatusCode
);
2248 # Buffer output; final headers may depend on later processing
2251 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2252 $response->header( 'Content-language: ' . $config->get( 'LanguageCode' ) );
2254 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2255 // jQuery etc. can work correctly.
2256 $response->header( 'X-UA-Compatible: IE=Edge' );
2258 // Prevent framing, if requested
2259 $frameOptions = $this->getFrameOptions();
2260 if ( $frameOptions ) {
2261 $response->header( "X-Frame-Options: $frameOptions" );
2264 if ( $this->mArticleBodyOnly
) {
2265 echo $this->mBodytext
;
2267 $sk = $this->getSkin();
2268 // add skin specific modules
2269 $modules = $sk->getDefaultModules();
2271 // Enforce various default modules for all pages and all skins
2273 // Keep this list as small as possible
2275 'mediawiki.page.startup',
2279 // Support for high-density display images if enabled
2280 if ( $config->get( 'ResponsiveImages' ) ) {
2281 $coreModules[] = 'mediawiki.hidpi';
2284 $this->addModules( $coreModules );
2285 foreach ( $modules as $group ) {
2286 $this->addModules( $group );
2288 MWDebug
::addModules( $this );
2290 // Hook that allows last minute changes to the output page, e.g.
2291 // adding of CSS or Javascript by extensions.
2292 Hooks
::run( 'BeforePageDisplay', [ &$this, &$sk ] );
2293 $this->getSkin()->setupSkinUserCss( $this );
2297 } catch ( Exception
$e ) {
2298 ob_end_clean(); // bug T129657
2304 // This hook allows last minute changes to final overall output by modifying output buffer
2305 Hooks
::run( 'AfterFinalPageOutput', [ $this ] );
2306 } catch ( Exception
$e ) {
2307 ob_end_clean(); // bug T129657
2311 $this->sendCacheControl();
2318 * Prepare this object to display an error page; disable caching and
2319 * indexing, clear the current text and redirect, set the page's title
2320 * and optionally an custom HTML title (content of the "<title>" tag).
2322 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2323 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2324 * optional, if not passed the "<title>" attribute will be
2325 * based on $pageTitle
2327 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2328 $this->setPageTitle( $pageTitle );
2329 if ( $htmlTitle !== false ) {
2330 $this->setHTMLTitle( $htmlTitle );
2332 $this->setRobotPolicy( 'noindex,nofollow' );
2333 $this->setArticleRelated( false );
2334 $this->enableClientCache( false );
2335 $this->mRedirect
= '';
2336 $this->clearSubtitle();
2341 * Output a standard error page
2343 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2344 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2345 * showErrorPage( 'titlemsg', $messageObject );
2346 * showErrorPage( $titleMessageObject, $messageObject );
2348 * @param string|Message $title Message key (string) for page title, or a Message object
2349 * @param string|Message $msg Message key (string) for page text, or a Message object
2350 * @param array $params Message parameters; ignored if $msg is a Message object
2352 public function showErrorPage( $title, $msg, $params = [] ) {
2353 if ( !$title instanceof Message
) {
2354 $title = $this->msg( $title );
2357 $this->prepareErrorPage( $title );
2359 if ( $msg instanceof Message
) {
2360 if ( $params !== [] ) {
2361 trigger_error( 'Argument ignored: $params. The message parameters argument '
2362 . 'is discarded when the $msg argument is a Message object instead of '
2363 . 'a string.', E_USER_NOTICE
);
2365 $this->addHTML( $msg->parseAsBlock() );
2367 $this->addWikiMsgArray( $msg, $params );
2370 $this->returnToMain();
2374 * Output a standard permission error page
2376 * @param array $errors Error message keys
2377 * @param string $action Action that was denied or null if unknown
2379 public function showPermissionsErrorPage( array $errors, $action = null ) {
2380 // For some action (read, edit, create and upload), display a "login to do this action"
2381 // error if all of the following conditions are met:
2382 // 1. the user is not logged in
2383 // 2. the only error is insufficient permissions (i.e. no block or something else)
2384 // 3. the error can be avoided simply by logging in
2385 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2386 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2387 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2388 && ( User
::groupHasPermission( 'user', $action )
2389 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2391 $displayReturnto = null;
2393 # Due to bug 32276, if a user does not have read permissions,
2394 # $this->getTitle() will just give Special:Badtitle, which is
2395 # not especially useful as a returnto parameter. Use the title
2396 # from the request instead, if there was one.
2397 $request = $this->getRequest();
2398 $returnto = Title
::newFromText( $request->getVal( 'title', '' ) );
2399 if ( $action == 'edit' ) {
2400 $msg = 'whitelistedittext';
2401 $displayReturnto = $returnto;
2402 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2403 $msg = 'nocreatetext';
2404 } elseif ( $action == 'upload' ) {
2405 $msg = 'uploadnologintext';
2407 $msg = 'loginreqpagetext';
2408 $displayReturnto = Title
::newMainPage();
2414 $query['returnto'] = $returnto->getPrefixedText();
2416 if ( !$request->wasPosted() ) {
2417 $returntoquery = $request->getValues();
2418 unset( $returntoquery['title'] );
2419 unset( $returntoquery['returnto'] );
2420 unset( $returntoquery['returntoquery'] );
2421 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2424 $loginLink = Linker
::linkKnown(
2425 SpecialPage
::getTitleFor( 'Userlogin' ),
2426 $this->msg( 'loginreqlink' )->escaped(),
2431 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2432 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2434 # Don't return to a page the user can't read otherwise
2435 # we'll end up in a pointless loop
2436 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2437 $this->returnToMain( null, $displayReturnto );
2440 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2441 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2446 * Display an error page indicating that a given version of MediaWiki is
2447 * required to use it
2449 * @param mixed $version The version of MediaWiki needed to use the page
2451 public function versionRequired( $version ) {
2452 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2454 $this->addWikiMsg( 'versionrequiredtext', $version );
2455 $this->returnToMain();
2459 * Format a list of error messages
2461 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2462 * @param string $action Action that was denied or null if unknown
2463 * @return string The wikitext error-messages, formatted into a list.
2465 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2466 if ( $action == null ) {
2467 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2469 $action_desc = $this->msg( "action-$action" )->plain();
2471 'permissionserrorstext-withaction',
2474 )->plain() . "\n\n";
2477 if ( count( $errors ) > 1 ) {
2478 $text .= '<ul class="permissions-errors">' . "\n";
2480 foreach ( $errors as $error ) {
2482 $text .= call_user_func_array( [ $this, 'msg' ], $error )->plain();
2487 $text .= "<div class=\"permissions-errors\">\n" .
2488 call_user_func_array( [ $this, 'msg' ], reset( $errors ) )->plain() .
2496 * Display a page stating that the Wiki is in read-only mode.
2497 * Should only be called after wfReadOnly() has returned true.
2499 * Historically, this function was used to show the source of the page that the user
2500 * was trying to edit and _also_ permissions error messages. The relevant code was
2501 * moved into EditPage in 1.19 (r102024 / d83c2a431c2a) and removed here in 1.25.
2503 * @deprecated since 1.25; throw the exception directly
2504 * @throws ReadOnlyError
2506 public function readOnlyPage() {
2507 if ( func_num_args() > 0 ) {
2508 throw new MWException( __METHOD__
. ' no longer accepts arguments since 1.25.' );
2511 throw new ReadOnlyError
;
2515 * Turn off regular page output and return an error response
2516 * for when rate limiting has triggered.
2518 * @deprecated since 1.25; throw the exception directly
2520 public function rateLimited() {
2521 wfDeprecated( __METHOD__
, '1.25' );
2522 throw new ThrottledError
;
2526 * Show a warning about slave lag
2528 * If the lag is higher than $wgSlaveLagCritical seconds,
2529 * then the warning is a bit more obvious. If the lag is
2530 * lower than $wgSlaveLagWarning, then no warning is shown.
2532 * @param int $lag Slave lag
2534 public function showLagWarning( $lag ) {
2535 $config = $this->getConfig();
2536 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2537 $message = $lag < $config->get( 'SlaveLagCritical' )
2540 $wrap = Html
::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2541 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2545 public function showFatalError( $message ) {
2546 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2548 $this->addHTML( $message );
2551 public function showUnexpectedValueError( $name, $val ) {
2552 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2555 public function showFileCopyError( $old, $new ) {
2556 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2559 public function showFileRenameError( $old, $new ) {
2560 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2563 public function showFileDeleteError( $name ) {
2564 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2567 public function showFileNotFoundError( $name ) {
2568 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2572 * Add a "return to" link pointing to a specified title
2574 * @param Title $title Title to link
2575 * @param array $query Query string parameters
2576 * @param string $text Text of the link (input is not escaped)
2577 * @param array $options Options array to pass to Linker
2579 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
2580 $link = $this->msg( 'returnto' )->rawParams(
2581 Linker
::link( $title, $text, [], $query, $options ) )->escaped();
2582 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2586 * Add a "return to" link pointing to a specified title,
2587 * or the title indicated in the request, or else the main page
2589 * @param mixed $unused
2590 * @param Title|string $returnto Title or String to return to
2591 * @param string $returntoquery Query string for the return to link
2593 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2594 if ( $returnto == null ) {
2595 $returnto = $this->getRequest()->getText( 'returnto' );
2598 if ( $returntoquery == null ) {
2599 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2602 if ( $returnto === '' ) {
2603 $returnto = Title
::newMainPage();
2606 if ( is_object( $returnto ) ) {
2607 $titleObj = $returnto;
2609 $titleObj = Title
::newFromText( $returnto );
2611 if ( !is_object( $titleObj ) ) {
2612 $titleObj = Title
::newMainPage();
2615 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2618 private function getRlClientContext() {
2619 if ( !$this->rlClientContext
) {
2620 $query = ResourceLoader
::makeLoaderQuery(
2621 [], // modules; not relevant
2622 $this->getLanguage()->getCode(),
2623 $this->getSkin()->getSkinName(),
2624 $this->getUser()->isLoggedIn() ?
$this->getUser()->getName() : null,
2625 null, // version; not relevant
2626 ResourceLoader
::inDebugMode(),
2627 null, // only; not relevant
2628 $this->isPrintable(),
2629 $this->getRequest()->getBool( 'handheld' )
2631 $this->rlClientContext
= new ResourceLoaderContext(
2632 $this->getResourceLoader(),
2633 new FauxRequest( $query )
2636 return $this->rlClientContext
;
2640 * Call this to freeze the module queue and JS config and create a formatter.
2642 * Depending on the Skin, this may get lazy-initialised in either headElement() or
2643 * getBottomScripts(). See SkinTemplate::prepareQuickTemplate(). Calling this too early may
2644 * cause unexpected side-effects since disallowUserJs() may be called at any time to change
2645 * the module filters retroactively. Skins and extension hooks may also add modules until very
2646 * late in the request lifecycle.
2648 * @return ResourceLoaderClientHtml
2650 public function getRlClient() {
2651 if ( !$this->rlClient
) {
2652 $context = $this->getRlClientContext();
2653 $userModule = $this->getResourceLoader()->getModule( 'user' );
2654 // Manually handled by getBottomScripts()
2655 $userState = $userModule->isKnownEmpty( $context ) && !$this->isUserModulePreview()
2658 $this->rlUserModuleState
= $userState;
2660 $this->addModules( [
2664 $rlClient = new ResourceLoaderClientHtml( $context );
2665 $rlClient->setConfig( $this->getJSVars() );
2666 $rlClient->setModules( $this->getModules( /*filter*/ true ) );
2667 $rlClient->setModuleStyles( $this->getModuleStyles( /*filter*/ true ) );
2668 $rlClient->setModuleScripts( $this->getModuleScripts( /*filter*/ true ) );
2669 $rlClient->setExemptStates( [
2670 'user' => $userState,
2671 // Manually handled by buildExemptModules() and getBottomScripts()
2672 'site.styles' => 'ready',
2673 'noscript' => 'ready',
2674 'user.cssprefs' => 'ready',
2675 'user.styles' => 'ready',
2677 $this->rlClient
= $rlClient;
2679 return $this->rlClient
;
2683 * @param Skin $sk The given Skin
2684 * @param bool $includeStyle Unused
2685 * @return string The doctype, opening "<html>", and head element.
2687 public function headElement( Skin
$sk, $includeStyle = true ) {
2690 $userdir = $this->getLanguage()->getDir();
2691 $sitedir = $wgContLang->getDir();
2694 $pieces[] = Html
::htmlHeader( Sanitizer
::mergeAttributes(
2695 $this->getRlClient()->getDocumentAttributes(),
2696 $sk->getHtmlElementAttributes()
2698 $pieces[] = Html
::openElement( 'head' );
2700 if ( $this->getHTMLTitle() == '' ) {
2701 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2704 if ( !Html
::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2705 // Add <meta charset="UTF-8">
2706 // This should be before <title> since it defines the charset used by
2707 // text including the text inside <title>.
2708 // The spec recommends defining XHTML5's charset using the XML declaration
2710 // Our XML declaration is output by Html::htmlHeader.
2711 // http://www.whatwg.org/html/semantics.html#attr-meta-http-equiv-content-type
2712 // http://www.whatwg.org/html/semantics.html#charset
2713 $pieces[] = Html
::element( 'meta', [ 'charset' => 'UTF-8' ] );
2716 $pieces[] = Html
::element( 'title', null, $this->getHTMLTitle() );
2717 $pieces[] = $this->getRlClient()->getHeadHtml();
2718 $pieces[] = $this->buildExemptModules();
2719 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
2720 $pieces = array_merge( $pieces, array_values( $this->mHeadItems
) );
2721 $pieces[] = Html
::closeElement( 'head' );
2724 $bodyClasses[] = 'mediawiki';
2726 # Classes for LTR/RTL directionality support
2727 $bodyClasses[] = $userdir;
2728 $bodyClasses[] = "sitedir-$sitedir";
2730 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2731 # A <body> class is probably not the best way to do this . . .
2732 $bodyClasses[] = 'capitalize-all-nouns';
2735 // Parser feature migration class
2736 // The idea is that this will eventually be removed, after the wikitext
2737 // which requires it is cleaned up.
2738 $bodyClasses[] = 'mw-hide-empty-elt';
2740 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2741 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2743 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2746 // While the implode() is not strictly needed, it's used for backwards compatibility
2747 // (this used to be built as a string and hooks likely still expect that).
2748 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2750 // Allow skins and extensions to add body attributes they need
2751 $sk->addToBodyAttributes( $this, $bodyAttrs );
2752 Hooks
::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
2754 $pieces[] = Html
::openElement( 'body', $bodyAttrs );
2756 return self
::combineWrappedStrings( $pieces );
2760 * Get a ResourceLoader object associated with this OutputPage
2762 * @return ResourceLoader
2764 public function getResourceLoader() {
2765 if ( is_null( $this->mResourceLoader
) ) {
2766 $this->mResourceLoader
= new ResourceLoader(
2768 LoggerFactory
::getInstance( 'resourceloader' )
2771 return $this->mResourceLoader
;
2775 * Explicily load or embed modules on a page.
2777 * @param array|string $modules One or more module names
2778 * @param string $only ResourceLoaderModule TYPE_ class constant
2779 * @param array $extraQuery [optional] Array with extra query parameters for the request
2780 * @return string|WrappedStringList HTML
2782 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
2783 return ResourceLoaderClientHtml
::makeLoad(
2784 $this->getRlClientContext(),
2792 * Combine WrappedString chunks and filter out empty ones
2794 * @param array $chunks
2795 * @return string|WrappedStringList HTML
2797 protected static function combineWrappedStrings( array $chunks ) {
2798 // Filter out empty values
2799 $chunks = array_filter( $chunks, 'strlen' );
2800 return WrappedString
::join( "\n", $chunks );
2804 private function isUserModulePreview() {
2805 return $this->getConfig()->get( 'AllowUserJs' )
2806 && $this->getUser()->isLoggedIn()
2807 && $this->getTitle()
2808 && $this->getTitle()->isJsSubpage()
2809 && $this->userCanPreview();
2813 * JS stuff to put at the bottom of the `<body>`. These are modules with position 'bottom',
2814 * legacy scripts ($this->mScripts), and user JS.
2816 * @return string|WrappedStringList HTML
2818 public function getBottomScripts() {
2820 $chunks[] = $this->getRlClient()->getBodyHtml();
2822 // Legacy non-ResourceLoader scripts
2823 $chunks[] = $this->mScripts
;
2825 // Exempt 'user' module
2826 // - May need excludepages for live preview. (T28283)
2827 // - Must use TYPE_COMBINED so its response is handled by mw.loader.implement() which
2828 // ensures execution is scheduled after the "site" module.
2829 // - Don't load if module state is already resolved as "ready".
2830 if ( $this->rlUserModuleState
=== 'loading' ) {
2831 if ( $this->isUserModulePreview() ) {
2832 $chunks[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_COMBINED
,
2833 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
2835 $chunks[] = ResourceLoader
::makeInlineScript(
2836 Xml
::encodeJsCall( 'mw.loader.using', [
2840 . Xml
::encodeJsCall( '$.globalEval', [
2841 $this->getRequest()->getText( 'wpTextbox1' )
2847 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
2848 // asynchronously and may arrive *after* the inline script here. So the previewed code
2849 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js.
2850 // Similarly, when previewing ./common.js and the user module does arrive first,
2851 // it will arrive without common.js and the inline script runs after.
2852 // Thus running common after the excluded subpage.
2855 $chunks[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_COMBINED
);
2859 $chunks[] = ResourceLoader
::makeInlineScript(
2860 ResourceLoader
::makeConfigSetScript(
2861 [ 'wgPageParseReport' => $this->limitReportData
],
2866 return self
::combineWrappedStrings( $chunks );
2870 * Get the javascript config vars to include on this page
2872 * @return array Array of javascript config vars
2875 public function getJsConfigVars() {
2876 return $this->mJsConfigVars
;
2880 * Add one or more variables to be set in mw.config in JavaScript
2882 * @param string|array $keys Key or array of key/value pairs
2883 * @param mixed $value [optional] Value of the configuration variable
2885 public function addJsConfigVars( $keys, $value = null ) {
2886 if ( is_array( $keys ) ) {
2887 foreach ( $keys as $key => $value ) {
2888 $this->mJsConfigVars
[$key] = $value;
2893 $this->mJsConfigVars
[$keys] = $value;
2897 * Get an array containing the variables to be set in mw.config in JavaScript.
2899 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
2900 * - in other words, page-independent/site-wide variables (without state).
2901 * You will only be adding bloat to the html page and causing page caches to
2902 * have to be purged on configuration changes.
2905 public function getJSVars() {
2910 $canonicalSpecialPageName = false; # bug 21115
2912 $title = $this->getTitle();
2913 $ns = $title->getNamespace();
2914 $canonicalNamespace = MWNamespace
::exists( $ns )
2915 ? MWNamespace
::getCanonicalName( $ns )
2916 : $title->getNsText();
2918 $sk = $this->getSkin();
2919 // Get the relevant title so that AJAX features can use the correct page name
2920 // when making API requests from certain special pages (bug 34972).
2921 $relevantTitle = $sk->getRelevantTitle();
2922 $relevantUser = $sk->getRelevantUser();
2924 if ( $ns == NS_SPECIAL
) {
2925 list( $canonicalSpecialPageName, /*...*/ ) =
2926 SpecialPageFactory
::resolveAlias( $title->getDBkey() );
2927 } elseif ( $this->canUseWikiPage() ) {
2928 $wikiPage = $this->getWikiPage();
2929 $curRevisionId = $wikiPage->getLatest();
2930 $articleId = $wikiPage->getId();
2933 $lang = $title->getPageViewLanguage();
2935 // Pre-process information
2936 $separatorTransTable = $lang->separatorTransformTable();
2937 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : [];
2938 $compactSeparatorTransTable = [
2939 implode( "\t", array_keys( $separatorTransTable ) ),
2940 implode( "\t", $separatorTransTable ),
2942 $digitTransTable = $lang->digitTransformTable();
2943 $digitTransTable = $digitTransTable ?
$digitTransTable : [];
2944 $compactDigitTransTable = [
2945 implode( "\t", array_keys( $digitTransTable ) ),
2946 implode( "\t", $digitTransTable ),
2949 $user = $this->getUser();
2952 'wgCanonicalNamespace' => $canonicalNamespace,
2953 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
2954 'wgNamespaceNumber' => $title->getNamespace(),
2955 'wgPageName' => $title->getPrefixedDBkey(),
2956 'wgTitle' => $title->getText(),
2957 'wgCurRevisionId' => $curRevisionId,
2958 'wgRevisionId' => (int)$this->getRevisionId(),
2959 'wgArticleId' => $articleId,
2960 'wgIsArticle' => $this->isArticle(),
2961 'wgIsRedirect' => $title->isRedirect(),
2962 'wgAction' => Action
::getActionName( $this->getContext() ),
2963 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
2964 'wgUserGroups' => $user->getEffectiveGroups(),
2965 'wgCategories' => $this->getCategories(),
2966 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
2967 'wgPageContentLanguage' => $lang->getCode(),
2968 'wgPageContentModel' => $title->getContentModel(),
2969 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
2970 'wgDigitTransformTable' => $compactDigitTransTable,
2971 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
2972 'wgMonthNames' => $lang->getMonthNamesArray(),
2973 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
2974 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
2975 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
2976 'wgRequestId' => WebRequest
::getRequestId(),
2979 if ( $user->isLoggedIn() ) {
2980 $vars['wgUserId'] = $user->getId();
2981 $vars['wgUserEditCount'] = $user->getEditCount();
2982 $userReg = wfTimestampOrNull( TS_UNIX
, $user->getRegistration() );
2983 $vars['wgUserRegistration'] = $userReg !== null ?
( $userReg * 1000 ) : null;
2984 // Get the revision ID of the oldest new message on the user's talk
2985 // page. This can be used for constructing new message alerts on
2987 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
2990 if ( $wgContLang->hasVariants() ) {
2991 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
2993 // Same test as SkinTemplate
2994 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
2995 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
2997 foreach ( $title->getRestrictionTypes() as $type ) {
2998 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3001 if ( $title->isMainPage() ) {
3002 $vars['wgIsMainPage'] = true;
3005 if ( $this->mRedirectedFrom
) {
3006 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3009 if ( $relevantUser ) {
3010 $vars['wgRelevantUserName'] = $relevantUser->getName();
3013 // Allow extensions to add their custom variables to the mw.config map.
3014 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3015 // page-dependant but site-wide (without state).
3016 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3017 Hooks
::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3019 // Merge in variables from addJsConfigVars last
3020 return array_merge( $vars, $this->getJsConfigVars() );
3024 * To make it harder for someone to slip a user a fake
3025 * user-JavaScript or user-CSS preview, a random token
3026 * is associated with the login session. If it's not
3027 * passed back with the preview request, we won't render
3032 public function userCanPreview() {
3033 $request = $this->getRequest();
3035 $request->getVal( 'action' ) !== 'submit' ||
3036 !$request->getCheck( 'wpPreview' ) ||
3037 !$request->wasPosted()
3042 $user = $this->getUser();
3043 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3047 $title = $this->getTitle();
3048 if ( !$title->isJsSubpage() && !$title->isCssSubpage() ) {
3051 if ( !$title->isSubpageOf( $user->getUserPage() ) ) {
3052 // Don't execute another user's CSS or JS on preview (T85855)
3056 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3057 if ( count( $errors ) !== 0 ) {
3065 * @return array Array in format "link name or number => 'link html'".
3067 public function getHeadLinksArray() {
3071 $config = $this->getConfig();
3073 $canonicalUrl = $this->mCanonicalUrl
;
3075 $tags['meta-generator'] = Html
::element( 'meta', [
3076 'name' => 'generator',
3077 'content' => "MediaWiki $wgVersion",
3080 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3081 $tags['meta-referrer'] = Html
::element( 'meta', [
3082 'name' => 'referrer',
3083 'content' => $config->get( 'ReferrerPolicy' )
3087 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3088 if ( $p !== 'index,follow' ) {
3089 // http://www.robotstxt.org/wc/meta-user.html
3090 // Only show if it's different from the default robots policy
3091 $tags['meta-robots'] = Html
::element( 'meta', [
3097 foreach ( $this->mMetatags
as $tag ) {
3098 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3100 $tag[0] = substr( $tag[0], 5 );
3104 $tagName = "meta-{$tag[0]}";
3105 if ( isset( $tags[$tagName] ) ) {
3106 $tagName .= $tag[1];
3108 $tags[$tagName] = Html
::element( 'meta',
3111 'content' => $tag[1]
3116 foreach ( $this->mLinktags
as $tag ) {
3117 $tags[] = Html
::element( 'link', $tag );
3120 # Universal edit button
3121 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3122 $user = $this->getUser();
3123 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3124 && ( $this->getTitle()->exists() ||
3125 $this->getTitle()->quickUserCan( 'create', $user ) )
3127 // Original UniversalEditButton
3128 $msg = $this->msg( 'edit' )->text();
3129 $tags['universal-edit-button'] = Html
::element( 'link', [
3130 'rel' => 'alternate',
3131 'type' => 'application/x-wiki',
3133 'href' => $this->getTitle()->getEditURL(),
3135 // Alternate edit link
3136 $tags['alternative-edit'] = Html
::element( 'link', [
3139 'href' => $this->getTitle()->getEditURL(),
3144 # Generally the order of the favicon and apple-touch-icon links
3145 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3146 # uses whichever one appears later in the HTML source. Make sure
3147 # apple-touch-icon is specified first to avoid this.
3148 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3149 $tags['apple-touch-icon'] = Html
::element( 'link', [
3150 'rel' => 'apple-touch-icon',
3151 'href' => $config->get( 'AppleTouchIcon' )
3155 if ( $config->get( 'Favicon' ) !== false ) {
3156 $tags['favicon'] = Html
::element( 'link', [
3157 'rel' => 'shortcut icon',
3158 'href' => $config->get( 'Favicon' )
3162 # OpenSearch description link
3163 $tags['opensearch'] = Html
::element( 'link', [
3165 'type' => 'application/opensearchdescription+xml',
3166 'href' => wfScript( 'opensearch_desc' ),
3167 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3170 if ( $config->get( 'EnableAPI' ) ) {
3171 # Real Simple Discovery link, provides auto-discovery information
3172 # for the MediaWiki API (and potentially additional custom API
3173 # support such as WordPress or Twitter-compatible APIs for a
3174 # blogging extension, etc)
3175 $tags['rsd'] = Html
::element( 'link', [
3177 'type' => 'application/rsd+xml',
3178 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3179 // Whether RSD accepts relative or protocol-relative URLs is completely
3180 // undocumented, though.
3181 'href' => wfExpandUrl( wfAppendQuery(
3183 [ 'action' => 'rsd' ] ),
3190 if ( !$config->get( 'DisableLangConversion' ) ) {
3191 $lang = $this->getTitle()->getPageLanguage();
3192 if ( $lang->hasVariants() ) {
3193 $variants = $lang->getVariants();
3194 foreach ( $variants as $variant ) {
3195 $tags["variant-$variant"] = Html
::element( 'link', [
3196 'rel' => 'alternate',
3197 'hreflang' => wfBCP47( $variant ),
3198 'href' => $this->getTitle()->getLocalURL(
3199 [ 'variant' => $variant ] )
3203 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3204 $tags["variant-x-default"] = Html
::element( 'link', [
3205 'rel' => 'alternate',
3206 'hreflang' => 'x-default',
3207 'href' => $this->getTitle()->getLocalURL() ] );
3212 if ( $this->copyrightUrl
!== null ) {
3213 $copyright = $this->copyrightUrl
;
3216 if ( $config->get( 'RightsPage' ) ) {
3217 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3220 $copyright = $copy->getLocalURL();
3224 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3225 $copyright = $config->get( 'RightsUrl' );
3230 $tags['copyright'] = Html
::element( 'link', [
3231 'rel' => 'copyright',
3232 'href' => $copyright ]
3237 if ( $config->get( 'Feed' ) ) {
3240 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3241 # Use the page name for the title. In principle, this could
3242 # lead to issues with having the same name for different feeds
3243 # corresponding to the same page, but we can't avoid that at
3246 $feedLinks[] = $this->feedLink(
3249 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3251 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3256 # Recent changes feed should appear on every page (except recentchanges,
3257 # that would be redundant). Put it after the per-page feed to avoid
3258 # changing existing behavior. It's still available, probably via a
3259 # menu in your browser. Some sites might have a different feed they'd
3260 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3261 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3262 # If so, use it instead.
3263 $sitename = $config->get( 'Sitename' );
3264 if ( $config->get( 'OverrideSiteFeed' ) ) {
3265 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3266 // Note, this->feedLink escapes the url.
3267 $feedLinks[] = $this->feedLink(
3270 $this->msg( "site-{$type}-feed", $sitename )->text()
3273 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3274 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3275 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3276 $feedLinks[] = $this->feedLink(
3278 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3279 # For grep: 'site-rss-feed', 'site-atom-feed'
3280 $this->msg( "site-{$format}-feed", $sitename )->text()
3285 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3286 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3287 # use OutputPage::addFeedLink() instead.
3288 Hooks
::run( 'AfterBuildFeedLinks', [ &$feedLinks ] );
3290 $tags +
= $feedLinks;
3294 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3295 if ( $canonicalUrl !== false ) {
3296 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3298 if ( $this->isArticleRelated() ) {
3299 // This affects all requests where "setArticleRelated" is true. This is
3300 // typically all requests that show content (query title, curid, oldid, diff),
3301 // and all wikipage actions (edit, delete, purge, info, history etc.).
3302 // It does not apply to File pages and Special pages.
3303 // 'history' and 'info' actions address page metadata rather than the page
3304 // content itself, so they may not be canonicalized to the view page url.
3305 // TODO: this ought to be better encapsulated in the Action class.
3306 $action = Action
::getActionName( $this->getContext() );
3307 if ( in_array( $action, [ 'history', 'info' ] ) ) {
3308 $query = "action={$action}";
3312 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3314 $reqUrl = $this->getRequest()->getRequestURL();
3315 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3319 if ( $canonicalUrl !== false ) {
3320 $tags[] = Html
::element( 'link', [
3321 'rel' => 'canonical',
3322 'href' => $canonicalUrl
3330 * @return string HTML tag links to be put in the header.
3331 * @deprecated since 1.24 Use OutputPage::headElement or if you have to,
3332 * OutputPage::getHeadLinksArray directly.
3334 public function getHeadLinks() {
3335 wfDeprecated( __METHOD__
, '1.24' );
3336 return implode( "\n", $this->getHeadLinksArray() );
3340 * Generate a "<link rel/>" for a feed.
3342 * @param string $type Feed type
3343 * @param string $url URL to the feed
3344 * @param string $text Value of the "title" attribute
3345 * @return string HTML fragment
3347 private function feedLink( $type, $url, $text ) {
3348 return Html
::element( 'link', [
3349 'rel' => 'alternate',
3350 'type' => "application/$type+xml",
3357 * Add a local or specified stylesheet, with the given media options.
3358 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3360 * @param string $style URL to the file
3361 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3362 * @param string $condition For IE conditional comments, specifying an IE version
3363 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3365 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3368 $options['media'] = $media;
3371 $options['condition'] = $condition;
3374 $options['dir'] = $dir;
3376 $this->styles
[$style] = $options;
3380 * Adds inline CSS styles
3381 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3383 * @param mixed $style_css Inline CSS
3384 * @param string $flip Set to 'flip' to flip the CSS if needed
3386 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3387 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3388 # If wanted, and the interface is right-to-left, flip the CSS
3389 $style_css = CSSJanus
::transform( $style_css, true, false );
3391 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3395 * Build exempt modules and legacy non-ResourceLoader styles.
3397 * @return string|WrappedStringList HTML
3399 protected function buildExemptModules() {
3402 $resourceLoader = $this->getResourceLoader();
3404 // Things that should be appended after the other link and style chunks
3411 // Exempt 'user' styles module.
3412 // - May need excludepages for live preview.
3413 // - Position after ResourceLoaderDynamicStyles marker
3414 if ( $this->getConfig()->get( 'AllowUserCss' ) && $this->getTitle()->isCssSubpage()
3415 && $this->userCanPreview()
3417 $append[] = $this->makeResourceLoaderLink(
3419 ResourceLoaderModule
::TYPE_STYLES
,
3420 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
3423 // Load the previewed CSS. Janus it if needed.
3424 // User-supplied CSS is assumed to in the wiki's content language.
3425 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3426 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3427 $previewedCSS = CSSJanus
::transform( $previewedCSS, true, false );
3429 $append[] = Html
::inlineStyle( $previewedCSS );
3431 $module = $this->getResourceLoader()->getModule( 'user.styles' );
3432 if ( !$module->isKnownEmpty( $this->getRlClientContext() ) ) {
3433 // Load styles normally
3434 $moduleStyles[] = 'user.styles';
3438 // Exempt 'user.cssprefs' module
3439 // - Position after ResourceLoaderDynamicStyles marker
3440 $moduleStyles[] = 'user.cssprefs';
3449 foreach ( $moduleStyles as $name ) {
3450 $module = $resourceLoader->getModule( $name );
3451 if ( !$module ||
$module->isKnownEmpty( $this->getRlClientContext() ) ) {
3452 // E.g. Don't output empty <styles> for user.cssprefs
3455 if ( $name === 'site.styles' ) {
3456 // HACK: Technically, the 'site.styles' module isn't in a separate request group.
3457 // But, in order to ensure its styles are in the right position after the marker,
3458 // pretend it's in a group called 'site'.
3459 $groups['site'][] = $name;
3462 $group = $module->getGroup();
3463 // Use "other" in case. All exempt modules are in one of the known groups though.
3464 $groups[isset( $groups[$group] ) ?
$group : 'other'][] = $name;
3467 // We want site, private and user styles to override dynamically added
3468 // styles from modules, but we want dynamically added styles to override
3469 // statically added styles from other modules. So the order has to be
3470 // other, dynamic, site, private, user. Add statically added styles for
3473 // Add legacy styles added through addStyle()/addInlineStyle() here
3474 $chunks[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3476 // Client-side mw.loader will inject dynamic styles before this marker.
3477 $chunks[] = Html
::element(
3479 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
3482 foreach ( [ 'other', 'site', 'noscript', 'private', 'user' ] as $group ) {
3483 $chunks[] = $this->makeResourceLoaderLink( $groups[$group],
3484 ResourceLoaderModule
::TYPE_STYLES
3488 return self
::combineWrappedStrings( array_merge( $chunks, $append ) );
3494 public function buildCssLinksArray() {
3497 // Add any extension CSS
3498 foreach ( $this->mExtStyles
as $url ) {
3499 $this->addStyle( $url );
3501 $this->mExtStyles
= [];
3503 foreach ( $this->styles
as $file => $options ) {
3504 $link = $this->styleLink( $file, $options );
3506 $links[$file] = $link;
3513 * Generate \<link\> tags for stylesheets
3515 * @param string $style URL to the file
3516 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3517 * @return string HTML fragment
3519 protected function styleLink( $style, array $options ) {
3520 if ( isset( $options['dir'] ) ) {
3521 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3526 if ( isset( $options['media'] ) ) {
3527 $media = self
::transformCssMedia( $options['media'] );
3528 if ( is_null( $media ) ) {
3535 if ( substr( $style, 0, 1 ) == '/' ||
3536 substr( $style, 0, 5 ) == 'http:' ||
3537 substr( $style, 0, 6 ) == 'https:' ) {
3540 $config = $this->getConfig();
3541 $url = $config->get( 'StylePath' ) . '/' . $style . '?' .
3542 $config->get( 'StyleVersion' );
3545 $link = Html
::linkedStyle( $url, $media );
3547 if ( isset( $options['condition'] ) ) {
3548 $condition = htmlspecialchars( $options['condition'] );
3549 $link = "<!--[if $condition]>$link<![endif]-->";
3555 * Transform path to web-accessible static resource.
3557 * This is used to add a validation hash as query string.
3558 * This aids various behaviors:
3560 * - Put long Cache-Control max-age headers on responses for improved
3561 * cache performance.
3562 * - Get the correct version of a file as expected by the current page.
3563 * - Instantly get the updated version of a file after deployment.
3565 * Avoid using this for urls included in HTML as otherwise clients may get different
3566 * versions of a resource when navigating the site depending on when the page was cached.
3567 * If changes to the url propagate, this is not a problem (e.g. if the url is in
3568 * an external stylesheet).
3571 * @param Config $config
3572 * @param string $path Path-absolute URL to file (from document root, must start with "/")
3573 * @return string URL
3575 public static function transformResourcePath( Config
$config, $path ) {
3577 $remotePathPrefix = $config->get( 'ResourceBasePath' );
3578 if ( $remotePathPrefix === '' ) {
3579 // The configured base path is required to be empty string for
3580 // wikis in the domain root
3583 $remotePath = $remotePathPrefix;
3585 if ( strpos( $path, $remotePath ) !== 0 ) {
3586 // Path is outside wgResourceBasePath, ignore.
3589 $path = RelPath\
getRelativePath( $path, $remotePath );
3590 return self
::transformFilePath( $remotePathPrefix, $IP, $path );
3594 * Utility method for transformResourceFilePath().
3596 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
3599 * @param string $remotePath URL path prefix that points to $localPath
3600 * @param string $localPath File directory exposed at $remotePath
3601 * @param string $file Path to target file relative to $localPath
3602 * @return string URL
3604 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
3605 $hash = md5_file( "$localPath/$file" );
3606 if ( $hash === false ) {
3607 wfLogWarning( __METHOD__
. ": Failed to hash $localPath/$file" );
3610 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
3614 * Transform "media" attribute based on request parameters
3616 * @param string $media Current value of the "media" attribute
3617 * @return string Modified value of the "media" attribute, or null to skip
3620 public static function transformCssMedia( $media ) {
3623 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3624 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3626 // Switch in on-screen display for media testing
3628 'printable' => 'print',
3629 'handheld' => 'handheld',
3631 foreach ( $switches as $switch => $targetMedia ) {
3632 if ( $wgRequest->getBool( $switch ) ) {
3633 if ( $media == $targetMedia ) {
3635 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3636 /* This regex will not attempt to understand a comma-separated media_query_list
3638 * Example supported values for $media:
3639 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3640 * Example NOT supported value for $media:
3641 * '3d-glasses, screen, print and resolution > 90dpi'
3643 * If it's a print request, we never want any kind of screen stylesheets
3644 * If it's a handheld request (currently the only other choice with a switch),
3645 * we don't want simple 'screen' but we might want screen queries that
3646 * have a max-width or something, so we'll pass all others on and let the
3647 * client do the query.
3649 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3660 * Add a wikitext-formatted message to the output.
3661 * This is equivalent to:
3663 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3665 public function addWikiMsg( /*...*/ ) {
3666 $args = func_get_args();
3667 $name = array_shift( $args );
3668 $this->addWikiMsgArray( $name, $args );
3672 * Add a wikitext-formatted message to the output.
3673 * Like addWikiMsg() except the parameters are taken as an array
3674 * instead of a variable argument list.
3676 * @param string $name
3677 * @param array $args
3679 public function addWikiMsgArray( $name, $args ) {
3680 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3684 * This function takes a number of message/argument specifications, wraps them in
3685 * some overall structure, and then parses the result and adds it to the output.
3687 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3688 * and so on. The subsequent arguments may be either
3689 * 1) strings, in which case they are message names, or
3690 * 2) arrays, in which case, within each array, the first element is the message
3691 * name, and subsequent elements are the parameters to that message.
3693 * Don't use this for messages that are not in the user's interface language.
3697 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3701 * $wgOut->addWikiText( "<div class='error'>\n"
3702 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3704 * The newline after the opening div is needed in some wikitext. See bug 19226.
3706 * @param string $wrap
3708 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3709 $msgSpecs = func_get_args();
3710 array_shift( $msgSpecs );
3711 $msgSpecs = array_values( $msgSpecs );
3713 foreach ( $msgSpecs as $n => $spec ) {
3714 if ( is_array( $spec ) ) {
3716 $name = array_shift( $args );
3717 if ( isset( $args['options'] ) ) {
3718 unset( $args['options'] );
3720 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3728 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3730 $this->addWikiText( $s );
3734 * Enables/disables TOC, doesn't override __NOTOC__
3738 public function enableTOC( $flag = true ) {
3739 $this->mEnableTOC
= $flag;
3746 public function isTOCEnabled() {
3747 return $this->mEnableTOC
;
3751 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3755 public function enableSectionEditLinks( $flag = true ) {
3756 $this->mEnableSectionEditLinks
= $flag;
3763 public function sectionEditLinksEnabled() {
3764 return $this->mEnableSectionEditLinks
;
3768 * Helper function to setup the PHP implementation of OOUI to use in this request.
3771 * @param String $skinName The Skin name to determine the correct OOUI theme
3772 * @param String $dir Language direction
3774 public static function setupOOUI( $skinName = '', $dir = 'ltr' ) {
3775 $themes = ExtensionRegistry
::getInstance()->getAttribute( 'SkinOOUIThemes' );
3776 // Make keys (skin names) lowercase for case-insensitive matching.
3777 $themes = array_change_key_case( $themes, CASE_LOWER
);
3778 $theme = isset( $themes[$skinName] ) ?
$themes[$skinName] : 'MediaWiki';
3779 // For example, 'OOUI\MediaWikiTheme'.
3780 $themeClass = "OOUI\\{$theme}Theme";
3781 OOUI\Theme
::setSingleton( new $themeClass() );
3782 OOUI\Element
::setDefaultDir( $dir );
3786 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
3787 * MediaWiki and this OutputPage instance.
3791 public function enableOOUI() {
3793 strtolower( $this->getSkin()->getSkinName() ),
3794 $this->getLanguage()->getDir()
3796 $this->addModuleStyles( [
3797 'oojs-ui-core.styles',
3798 'oojs-ui.styles.icons',
3799 'oojs-ui.styles.indicators',
3800 'oojs-ui.styles.textures',
3801 'mediawiki.widgets.styles',
3803 // Used by 'skipFunction' of the four 'oojs-ui.styles.*' modules. Please don't treat this as a
3804 // public API or you'll be severely disappointed when T87871 is fixed and it disappears.
3805 $this->addMeta( 'X-OOUI-PHP', '1' );