Fix use of RawMessage in Status::getMessage()
[mediawiki.git] / includes / OutputPage.php
blob5d1d5d0cdf78cbde557ca8dc893204d68e661b7c
1 <?php
2 /**
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
20 * @file
23 use MediaWiki\Logger\LoggerFactory;
24 use MediaWiki\Session\SessionManager;
25 use WrappedString\WrappedString;
27 /**
28 * This class should be covered by a general architecture document which does
29 * not exist as of January 2011. This is one of the Core classes and should
30 * be read at least once by any new developers.
32 * This class is used to prepare the final rendering. A skin is then
33 * applied to the output parameters (links, javascript, html, categories ...).
35 * @todo FIXME: Another class handles sending the whole page to the client.
37 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
38 * in November 2010.
40 * @todo document
42 class OutputPage extends ContextSource {
43 /** @var array Should be private. Used with addMeta() which adds "<meta>" */
44 protected $mMetatags = [];
46 /** @var array */
47 protected $mLinktags = [];
49 /** @var bool */
50 protected $mCanonicalUrl = false;
52 /**
53 * @var array Additional stylesheets. Looks like this is for extensions.
54 * Might be replaced by ResourceLoader.
56 protected $mExtStyles = [];
58 /**
59 * @var string Should be private - has getter and setter. Contains
60 * the HTML title */
61 public $mPagetitle = '';
63 /**
64 * @var string Contains all of the "<body>" content. Should be private we
65 * got set/get accessors and the append() method.
67 public $mBodytext = '';
69 /**
70 * Holds the debug lines that will be output as comments in page source if
71 * $wgDebugComments is enabled. See also $wgShowDebug.
72 * @deprecated since 1.20; use MWDebug class instead.
74 public $mDebugtext = '';
76 /** @var string Stores contents of "<title>" tag */
77 private $mHTMLtitle = '';
79 /**
80 * @var bool Is the displayed content related to the source of the
81 * corresponding wiki article.
83 private $mIsarticle = false;
85 /** @var bool Stores "article flag" toggle. */
86 private $mIsArticleRelated = true;
88 /**
89 * @var bool We have to set isPrintable(). Some pages should
90 * never be printed (ex: redirections).
92 private $mPrintable = false;
94 /**
95 * @var array Contains the page subtitle. Special pages usually have some
96 * links here. Don't confuse with site subtitle added by skins.
98 private $mSubtitle = [];
100 /** @var string */
101 public $mRedirect = '';
103 /** @var int */
104 protected $mStatusCode;
107 * @var string Variable mLastModified and mEtag are used for sending cache control.
108 * The whole caching system should probably be moved into its own class.
110 protected $mLastModified = '';
113 * Contains an HTTP Entity Tags (see RFC 2616 section 3.13) which is used
114 * as a unique identifier for the content. It is later used by the client
115 * to compare its cached version with the server version. Client sends
116 * headers If-Match and If-None-Match containing its locally cached ETAG value.
118 * To get more information, you will have to look at HTTP/1.1 protocol which
119 * is properly described in RFC 2616 : http://tools.ietf.org/html/rfc2616
121 private $mETag = false;
123 /** @var array */
124 protected $mCategoryLinks = [];
126 /** @var array */
127 protected $mCategories = [];
129 /** @var array */
130 protected $mIndicators = [];
132 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
133 private $mLanguageLinks = [];
136 * Used for JavaScript (predates ResourceLoader)
137 * @todo We should split JS / CSS.
138 * mScripts content is inserted as is in "<head>" by Skin. This might
139 * contain either a link to a stylesheet or inline CSS.
141 private $mScripts = '';
143 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
144 protected $mInlineStyles = '';
147 * @var string Used by skin template.
148 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
150 public $mPageLinkTitle = '';
152 /** @var array Array of elements in "<head>". Parser might add its own headers! */
153 protected $mHeadItems = [];
155 /** @var array */
156 protected $mModules = [];
158 /** @var array */
159 protected $mModuleScripts = [];
161 /** @var array */
162 protected $mModuleStyles = [];
164 /** @var ResourceLoader */
165 protected $mResourceLoader;
167 /** @var array */
168 protected $mJsConfigVars = [];
170 /** @var array */
171 protected $mTemplateIds = [];
173 /** @var array */
174 protected $mImageTimeKeys = [];
176 /** @var string */
177 public $mRedirectCode = '';
179 protected $mFeedLinksAppendQuery = null;
181 /** @var array
182 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
183 * @see ResourceLoaderModule::$origin
184 * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
186 protected $mAllowedModules = [
187 ResourceLoaderModule::TYPE_COMBINED => ResourceLoaderModule::ORIGIN_ALL,
190 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
191 protected $mDoNothing = false;
193 // Parser related.
195 /** @var int */
196 protected $mContainsNewMagic = 0;
199 * lazy initialised, use parserOptions()
200 * @var ParserOptions
202 protected $mParserOptions = null;
205 * Handles the Atom / RSS links.
206 * We probably only support Atom in 2011.
207 * @see $wgAdvertisedFeedTypes
209 private $mFeedLinks = [];
211 // Gwicke work on squid caching? Roughly from 2003.
212 protected $mEnableClientCache = true;
214 /** @var bool Flag if output should only contain the body of the article. */
215 private $mArticleBodyOnly = false;
217 /** @var bool */
218 protected $mNewSectionLink = false;
220 /** @var bool */
221 protected $mHideNewSectionLink = false;
224 * @var bool Comes from the parser. This was probably made to load CSS/JS
225 * only if we had "<gallery>". Used directly in CategoryPage.php.
226 * Looks like ResourceLoader can replace this.
228 public $mNoGallery = false;
230 /** @var string */
231 private $mPageTitleActionText = '';
233 /** @var int Cache stuff. Looks like mEnableClientCache */
234 protected $mCdnMaxage = 0;
235 /** @var int Upper limit on mCdnMaxage */
236 protected $mCdnMaxageLimit = INF;
239 * @var bool Controls if anti-clickjacking / frame-breaking headers will
240 * be sent. This should be done for pages where edit actions are possible.
241 * Setters: $this->preventClickjacking() and $this->allowClickjacking().
243 protected $mPreventClickjacking = true;
245 /** @var int To include the variable {{REVISIONID}} */
246 private $mRevisionId = null;
248 /** @var string */
249 private $mRevisionTimestamp = null;
251 /** @var array */
252 protected $mFileVersion = null;
255 * @var array An array of stylesheet filenames (relative from skins path),
256 * with options for CSS media, IE conditions, and RTL/LTR direction.
257 * For internal use; add settings in the skin via $this->addStyle()
259 * Style again! This seems like a code duplication since we already have
260 * mStyles. This is what makes Open Source amazing.
262 protected $styles = [];
265 * Whether jQuery is already handled.
267 protected $mJQueryDone = false;
269 private $mIndexPolicy = 'index';
270 private $mFollowPolicy = 'follow';
271 private $mVaryHeader = [
272 'Accept-Encoding' => [ 'match=gzip' ],
276 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
277 * of the redirect.
279 * @var Title
281 private $mRedirectedFrom = null;
284 * Additional key => value data
286 private $mProperties = [];
289 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
291 private $mTarget = null;
294 * @var bool Whether parser output should contain table of contents
296 private $mEnableTOC = true;
299 * @var bool Whether parser output should contain section edit links
301 private $mEnableSectionEditLinks = true;
304 * @var string|null The URL to send in a <link> element with rel=copyright
306 private $copyrightUrl;
309 * Constructor for OutputPage. This should not be called directly.
310 * Instead a new RequestContext should be created and it will implicitly create
311 * a OutputPage tied to that context.
312 * @param IContextSource|null $context
314 function __construct( IContextSource $context = null ) {
315 if ( $context === null ) {
316 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
317 wfDeprecated( __METHOD__, '1.18' );
318 } else {
319 $this->setContext( $context );
324 * Redirect to $url rather than displaying the normal page
326 * @param string $url URL
327 * @param string $responsecode HTTP status code
329 public function redirect( $url, $responsecode = '302' ) {
330 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
331 $this->mRedirect = str_replace( "\n", '', $url );
332 $this->mRedirectCode = $responsecode;
336 * Get the URL to redirect to, or an empty string if not redirect URL set
338 * @return string
340 public function getRedirect() {
341 return $this->mRedirect;
345 * Set the copyright URL to send with the output.
346 * Empty string to omit, null to reset.
348 * @since 1.26
350 * @param string|null $url
352 public function setCopyrightUrl( $url ) {
353 $this->copyrightUrl = $url;
357 * Set the HTTP status code to send with the output.
359 * @param int $statusCode
361 public function setStatusCode( $statusCode ) {
362 $this->mStatusCode = $statusCode;
366 * Add a new "<meta>" tag
367 * To add an http-equiv meta tag, precede the name with "http:"
369 * @param string $name Tag name
370 * @param string $val Tag value
372 function addMeta( $name, $val ) {
373 array_push( $this->mMetatags, [ $name, $val ] );
377 * Returns the current <meta> tags
379 * @since 1.25
380 * @return array
382 public function getMetaTags() {
383 return $this->mMetatags;
387 * Add a new \<link\> tag to the page header.
389 * Note: use setCanonicalUrl() for rel=canonical.
391 * @param array $linkarr Associative array of attributes.
393 function addLink( array $linkarr ) {
394 array_push( $this->mLinktags, $linkarr );
398 * Returns the current <link> tags
400 * @since 1.25
401 * @return array
403 public function getLinkTags() {
404 return $this->mLinktags;
408 * Add a new \<link\> with "rel" attribute set to "meta"
410 * @param array $linkarr Associative array mapping attribute names to their
411 * values, both keys and values will be escaped, and the
412 * "rel" attribute will be automatically added
414 function addMetadataLink( array $linkarr ) {
415 $linkarr['rel'] = $this->getMetadataAttribute();
416 $this->addLink( $linkarr );
420 * Set the URL to be used for the <link rel=canonical>. This should be used
421 * in preference to addLink(), to avoid duplicate link tags.
422 * @param string $url
424 function setCanonicalUrl( $url ) {
425 $this->mCanonicalUrl = $url;
429 * Returns the URL to be used for the <link rel=canonical> if
430 * one is set.
432 * @since 1.25
433 * @return bool|string
435 public function getCanonicalUrl() {
436 return $this->mCanonicalUrl;
440 * Get the value of the "rel" attribute for metadata links
442 * @return string
444 public function getMetadataAttribute() {
445 # note: buggy CC software only reads first "meta" link
446 static $haveMeta = false;
447 if ( $haveMeta ) {
448 return 'alternate meta';
449 } else {
450 $haveMeta = true;
451 return 'meta';
456 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
457 * Internal use only. Use OutputPage::addModules() or OutputPage::addJsConfigVars()
458 * if possible.
460 * @param string $script Raw HTML
462 function addScript( $script ) {
463 $this->mScripts .= $script . "\n";
467 * Register and add a stylesheet from an extension directory.
469 * @deprecated since 1.27 use addModuleStyles() or addStyle() instead
470 * @param string $url Path to sheet. Provide either a full url (beginning
471 * with 'http', etc) or a relative path from the document root
472 * (beginning with '/'). Otherwise it behaves identically to
473 * addStyle() and draws from the /skins folder.
475 public function addExtensionStyle( $url ) {
476 wfDeprecated( __METHOD__, '1.27' );
477 array_push( $this->mExtStyles, $url );
481 * Get all styles added by extensions
483 * @deprecated since 1.27
484 * @return array
486 function getExtStyle() {
487 wfDeprecated( __METHOD__, '1.27' );
488 return $this->mExtStyles;
492 * Add a JavaScript file out of skins/common, or a given relative path.
493 * Internal use only. Use OutputPage::addModules() if possible.
495 * @param string $file Filename in skins/common or complete on-server path
496 * (/foo/bar.js)
497 * @param string $version Style version of the file. Defaults to $wgStyleVersion
499 public function addScriptFile( $file, $version = null ) {
500 // See if $file parameter is an absolute URL or begins with a slash
501 if ( substr( $file, 0, 1 ) == '/' || preg_match( '#^[a-z]*://#i', $file ) ) {
502 $path = $file;
503 } else {
504 $path = $this->getConfig()->get( 'StylePath' ) . "/common/{$file}";
506 if ( is_null( $version ) ) {
507 $version = $this->getConfig()->get( 'StyleVersion' );
509 $this->addScript( Html::linkedScript( wfAppendQuery( $path, $version ) ) );
513 * Add a self-contained script tag with the given contents
514 * Internal use only. Use OutputPage::addModules() if possible.
516 * @param string $script JavaScript text, no "<script>" tags
518 public function addInlineScript( $script ) {
519 $this->mScripts .= Html::inlineScript( "\n$script\n" ) . "\n";
523 * Get all registered JS and CSS tags for the header.
525 * @return string
526 * @deprecated since 1.24 Use OutputPage::headElement to build the full header.
528 function getScript() {
529 wfDeprecated( __METHOD__, '1.24' );
530 return $this->mScripts . $this->getHeadItems();
534 * Filter an array of modules to remove insufficiently trustworthy members, and modules
535 * which are no longer registered (eg a page is cached before an extension is disabled)
536 * @param array $modules
537 * @param string|null $position If not null, only return modules with this position
538 * @param string $type
539 * @return array
541 protected function filterModules( array $modules, $position = null,
542 $type = ResourceLoaderModule::TYPE_COMBINED
544 $resourceLoader = $this->getResourceLoader();
545 $filteredModules = [];
546 foreach ( $modules as $val ) {
547 $module = $resourceLoader->getModule( $val );
548 if ( $module instanceof ResourceLoaderModule
549 && $module->getOrigin() <= $this->getAllowedModules( $type )
550 && ( is_null( $position ) || $module->getPosition() == $position )
551 && ( !$this->mTarget || in_array( $this->mTarget, $module->getTargets() ) )
553 $filteredModules[] = $val;
556 return $filteredModules;
560 * Get the list of modules to include on this page
562 * @param bool $filter Whether to filter out insufficiently trustworthy modules
563 * @param string|null $position If not null, only return modules with this position
564 * @param string $param
565 * @return array Array of module names
567 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
568 $modules = array_values( array_unique( $this->$param ) );
569 return $filter
570 ? $this->filterModules( $modules, $position )
571 : $modules;
575 * Add one or more modules recognized by ResourceLoader. Modules added
576 * through this function will be loaded by ResourceLoader when the
577 * page loads.
579 * @param string|array $modules Module name (string) or array of module names
581 public function addModules( $modules ) {
582 $this->mModules = array_merge( $this->mModules, (array)$modules );
586 * Get the list of module JS to include on this page
588 * @param bool $filter
589 * @param string|null $position
591 * @return array Array of module names
593 public function getModuleScripts( $filter = false, $position = null ) {
594 return $this->getModules( $filter, $position, 'mModuleScripts' );
598 * Add only JS of one or more modules recognized by ResourceLoader. Module
599 * scripts added through this function will be loaded by ResourceLoader when
600 * the page loads.
602 * @param string|array $modules Module name (string) or array of module names
604 public function addModuleScripts( $modules ) {
605 $this->mModuleScripts = array_merge( $this->mModuleScripts, (array)$modules );
609 * Get the list of module CSS to include on this page
611 * @param bool $filter
612 * @param string|null $position
614 * @return array Array of module names
616 public function getModuleStyles( $filter = false, $position = null ) {
617 return $this->getModules( $filter, $position, 'mModuleStyles' );
621 * Add only CSS of one or more modules recognized by ResourceLoader.
623 * Module styles added through this function will be added using standard link CSS
624 * tags, rather than as a combined Javascript and CSS package. Thus, they will
625 * load when JavaScript is disabled (unless CSS also happens to be disabled).
627 * @param string|array $modules Module name (string) or array of module names
629 public function addModuleStyles( $modules ) {
630 $this->mModuleStyles = array_merge( $this->mModuleStyles, (array)$modules );
634 * Get the list of module messages to include on this page
636 * @deprecated since 1.26 Obsolete
637 * @param bool $filter
638 * @param string|null $position
639 * @return array Array of module names
641 public function getModuleMessages( $filter = false, $position = null ) {
642 wfDeprecated( __METHOD__, '1.26' );
643 return [];
647 * Load messages of one or more ResourceLoader modules.
649 * @deprecated since 1.26 Use addModules() instead
650 * @param string|array $modules Module name (string) or array of module names
652 public function addModuleMessages( $modules ) {
653 wfDeprecated( __METHOD__, '1.26' );
657 * @return null|string ResourceLoader target
659 public function getTarget() {
660 return $this->mTarget;
664 * Sets ResourceLoader target for load.php links. If null, will be omitted
666 * @param string|null $target
668 public function setTarget( $target ) {
669 $this->mTarget = $target;
673 * Get an array of head items
675 * @return array
677 function getHeadItemsArray() {
678 return $this->mHeadItems;
682 * Get all header items in a string
684 * @return string
685 * @deprecated since 1.24 Use OutputPage::headElement or
686 * if absolutely necessary use OutputPage::getHeadItemsArray
688 function getHeadItems() {
689 wfDeprecated( __METHOD__, '1.24' );
690 $s = '';
691 foreach ( $this->mHeadItems as $item ) {
692 $s .= $item;
694 return $s;
698 * Add or replace an header item to the output
700 * Whenever possible, use more specific options like ResourceLoader modules,
701 * OutputPage::addLink(), OutputPage::addMetaLink() and OutputPage::addFeedLink()
702 * Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
703 * OutputPage::addInlineScript() and OutputPage::addInlineStyle()
704 * This would be your very LAST fallback.
706 * @param string $name Item name
707 * @param string $value Raw HTML
709 public function addHeadItem( $name, $value ) {
710 $this->mHeadItems[$name] = $value;
714 * Check if the header item $name is already set
716 * @param string $name Item name
717 * @return bool
719 public function hasHeadItem( $name ) {
720 return isset( $this->mHeadItems[$name] );
724 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
726 * @param string $tag Value of "ETag" header
728 function setETag( $tag ) {
729 $this->mETag = $tag;
733 * Set whether the output should only contain the body of the article,
734 * without any skin, sidebar, etc.
735 * Used e.g. when calling with "action=render".
737 * @param bool $only Whether to output only the body of the article
739 public function setArticleBodyOnly( $only ) {
740 $this->mArticleBodyOnly = $only;
744 * Return whether the output will contain only the body of the article
746 * @return bool
748 public function getArticleBodyOnly() {
749 return $this->mArticleBodyOnly;
753 * Set an additional output property
754 * @since 1.21
756 * @param string $name
757 * @param mixed $value
759 public function setProperty( $name, $value ) {
760 $this->mProperties[$name] = $value;
764 * Get an additional output property
765 * @since 1.21
767 * @param string $name
768 * @return mixed Property value or null if not found
770 public function getProperty( $name ) {
771 if ( isset( $this->mProperties[$name] ) ) {
772 return $this->mProperties[$name];
773 } else {
774 return null;
779 * checkLastModified tells the client to use the client-cached page if
780 * possible. If successful, the OutputPage is disabled so that
781 * any future call to OutputPage->output() have no effect.
783 * Side effect: sets mLastModified for Last-Modified header
785 * @param string $timestamp
787 * @return bool True if cache-ok headers was sent.
789 public function checkLastModified( $timestamp ) {
790 if ( !$timestamp || $timestamp == '19700101000000' ) {
791 wfDebug( __METHOD__ . ": CACHE DISABLED, NO TIMESTAMP\n" );
792 return false;
794 $config = $this->getConfig();
795 if ( !$config->get( 'CachePages' ) ) {
796 wfDebug( __METHOD__ . ": CACHE DISABLED\n" );
797 return false;
800 $timestamp = wfTimestamp( TS_MW, $timestamp );
801 $modifiedTimes = [
802 'page' => $timestamp,
803 'user' => $this->getUser()->getTouched(),
804 'epoch' => $config->get( 'CacheEpoch' )
806 if ( $config->get( 'UseSquid' ) ) {
807 // bug 44570: the core page itself may not change, but resources might
808 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW, time() - $config->get( 'SquidMaxage' ) );
810 Hooks::run( 'OutputPageCheckLastModified', [ &$modifiedTimes ] );
812 $maxModified = max( $modifiedTimes );
813 $this->mLastModified = wfTimestamp( TS_RFC2822, $maxModified );
815 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
816 if ( $clientHeader === false ) {
817 wfDebug( __METHOD__ . ": client did not send If-Modified-Since header", 'private' );
818 return false;
821 # IE sends sizes after the date like this:
822 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
823 # this breaks strtotime().
824 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
826 MediaWiki\suppressWarnings(); // E_STRICT system time bitching
827 $clientHeaderTime = strtotime( $clientHeader );
828 MediaWiki\restoreWarnings();
829 if ( !$clientHeaderTime ) {
830 wfDebug( __METHOD__
831 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
832 return false;
834 $clientHeaderTime = wfTimestamp( TS_MW, $clientHeaderTime );
836 # Make debug info
837 $info = '';
838 foreach ( $modifiedTimes as $name => $value ) {
839 if ( $info !== '' ) {
840 $info .= ', ';
842 $info .= "$name=" . wfTimestamp( TS_ISO_8601, $value );
845 wfDebug( __METHOD__ . ": client sent If-Modified-Since: " .
846 wfTimestamp( TS_ISO_8601, $clientHeaderTime ), 'private' );
847 wfDebug( __METHOD__ . ": effective Last-Modified: " .
848 wfTimestamp( TS_ISO_8601, $maxModified ), 'private' );
849 if ( $clientHeaderTime < $maxModified ) {
850 wfDebug( __METHOD__ . ": STALE, $info", 'private' );
851 return false;
854 # Not modified
855 # Give a 304 Not Modified response code and disable body output
856 wfDebug( __METHOD__ . ": NOT MODIFIED, $info", 'private' );
857 ini_set( 'zlib.output_compression', 0 );
858 $this->getRequest()->response()->statusHeader( 304 );
859 $this->sendCacheControl();
860 $this->disable();
862 // Don't output a compressed blob when using ob_gzhandler;
863 // it's technically against HTTP spec and seems to confuse
864 // Firefox when the response gets split over two packets.
865 wfClearOutputBuffers();
867 return true;
871 * Override the last modified timestamp
873 * @param string $timestamp New timestamp, in a format readable by
874 * wfTimestamp()
876 public function setLastModified( $timestamp ) {
877 $this->mLastModified = wfTimestamp( TS_RFC2822, $timestamp );
881 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
883 * @param string $policy The literal string to output as the contents of
884 * the meta tag. Will be parsed according to the spec and output in
885 * standardized form.
886 * @return null
888 public function setRobotPolicy( $policy ) {
889 $policy = Article::formatRobotPolicy( $policy );
891 if ( isset( $policy['index'] ) ) {
892 $this->setIndexPolicy( $policy['index'] );
894 if ( isset( $policy['follow'] ) ) {
895 $this->setFollowPolicy( $policy['follow'] );
900 * Set the index policy for the page, but leave the follow policy un-
901 * touched.
903 * @param string $policy Either 'index' or 'noindex'.
904 * @return null
906 public function setIndexPolicy( $policy ) {
907 $policy = trim( $policy );
908 if ( in_array( $policy, [ 'index', 'noindex' ] ) ) {
909 $this->mIndexPolicy = $policy;
914 * Set the follow policy for the page, but leave the index policy un-
915 * touched.
917 * @param string $policy Either 'follow' or 'nofollow'.
918 * @return null
920 public function setFollowPolicy( $policy ) {
921 $policy = trim( $policy );
922 if ( in_array( $policy, [ 'follow', 'nofollow' ] ) ) {
923 $this->mFollowPolicy = $policy;
928 * Set the new value of the "action text", this will be added to the
929 * "HTML title", separated from it with " - ".
931 * @param string $text New value of the "action text"
933 public function setPageTitleActionText( $text ) {
934 $this->mPageTitleActionText = $text;
938 * Get the value of the "action text"
940 * @return string
942 public function getPageTitleActionText() {
943 return $this->mPageTitleActionText;
947 * "HTML title" means the contents of "<title>".
948 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
950 * @param string|Message $name
952 public function setHTMLTitle( $name ) {
953 if ( $name instanceof Message ) {
954 $this->mHTMLtitle = $name->setContext( $this->getContext() )->text();
955 } else {
956 $this->mHTMLtitle = $name;
961 * Return the "HTML title", i.e. the content of the "<title>" tag.
963 * @return string
965 public function getHTMLTitle() {
966 return $this->mHTMLtitle;
970 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
972 * @param Title $t
974 public function setRedirectedFrom( $t ) {
975 $this->mRedirectedFrom = $t;
979 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
980 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
981 * but not bad tags like \<script\>. This function automatically sets
982 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
983 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
984 * good tags like \<i\> will be dropped entirely.
986 * @param string|Message $name
988 public function setPageTitle( $name ) {
989 if ( $name instanceof Message ) {
990 $name = $name->setContext( $this->getContext() )->text();
993 # change "<script>foo&bar</script>" to "&lt;script&gt;foo&amp;bar&lt;/script&gt;"
994 # but leave "<i>foobar</i>" alone
995 $nameWithTags = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags( $name ) );
996 $this->mPagetitle = $nameWithTags;
998 # change "<i>foo&amp;bar</i>" to "foo&bar"
999 $this->setHTMLTitle(
1000 $this->msg( 'pagetitle' )->rawParams( Sanitizer::stripAllTags( $nameWithTags ) )
1001 ->inContentLanguage()
1006 * Return the "page title", i.e. the content of the \<h1\> tag.
1008 * @return string
1010 public function getPageTitle() {
1011 return $this->mPagetitle;
1015 * Set the Title object to use
1017 * @param Title $t
1019 public function setTitle( Title $t ) {
1020 $this->getContext()->setTitle( $t );
1024 * Replace the subtitle with $str
1026 * @param string|Message $str New value of the subtitle. String should be safe HTML.
1028 public function setSubtitle( $str ) {
1029 $this->clearSubtitle();
1030 $this->addSubtitle( $str );
1034 * Add $str to the subtitle
1036 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
1038 public function addSubtitle( $str ) {
1039 if ( $str instanceof Message ) {
1040 $this->mSubtitle[] = $str->setContext( $this->getContext() )->parse();
1041 } else {
1042 $this->mSubtitle[] = $str;
1047 * Build message object for a subtitle containing a backlink to a page
1049 * @param Title $title Title to link to
1050 * @param array $query Array of additional parameters to include in the link
1051 * @return Message
1052 * @since 1.25
1054 public static function buildBacklinkSubtitle( Title $title, $query = [] ) {
1055 if ( $title->isRedirect() ) {
1056 $query['redirect'] = 'no';
1058 return wfMessage( 'backlinksubtitle' )
1059 ->rawParams( Linker::link( $title, null, [], $query ) );
1063 * Add a subtitle containing a backlink to a page
1065 * @param Title $title Title to link to
1066 * @param array $query Array of additional parameters to include in the link
1068 public function addBacklinkSubtitle( Title $title, $query = [] ) {
1069 $this->addSubtitle( self::buildBacklinkSubtitle( $title, $query ) );
1073 * Clear the subtitles
1075 public function clearSubtitle() {
1076 $this->mSubtitle = [];
1080 * Get the subtitle
1082 * @return string
1084 public function getSubtitle() {
1085 return implode( "<br />\n\t\t\t\t", $this->mSubtitle );
1089 * Set the page as printable, i.e. it'll be displayed with all
1090 * print styles included
1092 public function setPrintable() {
1093 $this->mPrintable = true;
1097 * Return whether the page is "printable"
1099 * @return bool
1101 public function isPrintable() {
1102 return $this->mPrintable;
1106 * Disable output completely, i.e. calling output() will have no effect
1108 public function disable() {
1109 $this->mDoNothing = true;
1113 * Return whether the output will be completely disabled
1115 * @return bool
1117 public function isDisabled() {
1118 return $this->mDoNothing;
1122 * Show an "add new section" link?
1124 * @return bool
1126 public function showNewSectionLink() {
1127 return $this->mNewSectionLink;
1131 * Forcibly hide the new section link?
1133 * @return bool
1135 public function forceHideNewSectionLink() {
1136 return $this->mHideNewSectionLink;
1140 * Add or remove feed links in the page header
1141 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1142 * for the new version
1143 * @see addFeedLink()
1145 * @param bool $show True: add default feeds, false: remove all feeds
1147 public function setSyndicated( $show = true ) {
1148 if ( $show ) {
1149 $this->setFeedAppendQuery( false );
1150 } else {
1151 $this->mFeedLinks = [];
1156 * Add default feeds to the page header
1157 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1158 * for the new version
1159 * @see addFeedLink()
1161 * @param string $val Query to append to feed links or false to output
1162 * default links
1164 public function setFeedAppendQuery( $val ) {
1165 $this->mFeedLinks = [];
1167 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1168 $query = "feed=$type";
1169 if ( is_string( $val ) ) {
1170 $query .= '&' . $val;
1172 $this->mFeedLinks[$type] = $this->getTitle()->getLocalURL( $query );
1177 * Add a feed link to the page header
1179 * @param string $format Feed type, should be a key of $wgFeedClasses
1180 * @param string $href URL
1182 public function addFeedLink( $format, $href ) {
1183 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1184 $this->mFeedLinks[$format] = $href;
1189 * Should we output feed links for this page?
1190 * @return bool
1192 public function isSyndicated() {
1193 return count( $this->mFeedLinks ) > 0;
1197 * Return URLs for each supported syndication format for this page.
1198 * @return array Associating format keys with URLs
1200 public function getSyndicationLinks() {
1201 return $this->mFeedLinks;
1205 * Will currently always return null
1207 * @return null
1209 public function getFeedAppendQuery() {
1210 return $this->mFeedLinksAppendQuery;
1214 * Set whether the displayed content is related to the source of the
1215 * corresponding article on the wiki
1216 * Setting true will cause the change "article related" toggle to true
1218 * @param bool $v
1220 public function setArticleFlag( $v ) {
1221 $this->mIsarticle = $v;
1222 if ( $v ) {
1223 $this->mIsArticleRelated = $v;
1228 * Return whether the content displayed page is related to the source of
1229 * the corresponding article on the wiki
1231 * @return bool
1233 public function isArticle() {
1234 return $this->mIsarticle;
1238 * Set whether this page is related an article on the wiki
1239 * Setting false will cause the change of "article flag" toggle to false
1241 * @param bool $v
1243 public function setArticleRelated( $v ) {
1244 $this->mIsArticleRelated = $v;
1245 if ( !$v ) {
1246 $this->mIsarticle = false;
1251 * Return whether this page is related an article on the wiki
1253 * @return bool
1255 public function isArticleRelated() {
1256 return $this->mIsArticleRelated;
1260 * Add new language links
1262 * @param array $newLinkArray Associative array mapping language code to the page
1263 * name
1265 public function addLanguageLinks( array $newLinkArray ) {
1266 $this->mLanguageLinks += $newLinkArray;
1270 * Reset the language links and add new language links
1272 * @param array $newLinkArray Associative array mapping language code to the page
1273 * name
1275 public function setLanguageLinks( array $newLinkArray ) {
1276 $this->mLanguageLinks = $newLinkArray;
1280 * Get the list of language links
1282 * @return array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1284 public function getLanguageLinks() {
1285 return $this->mLanguageLinks;
1289 * Add an array of categories, with names in the keys
1291 * @param array $categories Mapping category name => sort key
1293 public function addCategoryLinks( array $categories ) {
1294 global $wgContLang;
1296 if ( !is_array( $categories ) || count( $categories ) == 0 ) {
1297 return;
1300 # Add the links to a LinkBatch
1301 $arr = [ NS_CATEGORY => $categories ];
1302 $lb = new LinkBatch;
1303 $lb->setArray( $arr );
1305 # Fetch existence plus the hiddencat property
1306 $dbr = wfGetDB( DB_SLAVE );
1307 $fields = [ 'page_id', 'page_namespace', 'page_title', 'page_len',
1308 'page_is_redirect', 'page_latest', 'pp_value' ];
1310 if ( $this->getConfig()->get( 'ContentHandlerUseDB' ) ) {
1311 $fields[] = 'page_content_model';
1313 if ( $this->getConfig()->get( 'PageLanguageUseDB' ) ) {
1314 $fields[] = 'page_lang';
1317 $res = $dbr->select( [ 'page', 'page_props' ],
1318 $fields,
1319 $lb->constructSet( 'page', $dbr ),
1320 __METHOD__,
1322 [ 'page_props' => [ 'LEFT JOIN', [
1323 'pp_propname' => 'hiddencat',
1324 'pp_page = page_id'
1325 ] ] ]
1328 # Add the results to the link cache
1329 $lb->addResultToCache( LinkCache::singleton(), $res );
1331 # Set all the values to 'normal'.
1332 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1334 # Mark hidden categories
1335 foreach ( $res as $row ) {
1336 if ( isset( $row->pp_value ) ) {
1337 $categories[$row->page_title] = 'hidden';
1341 # Add the remaining categories to the skin
1342 if ( Hooks::run(
1343 'OutputPageMakeCategoryLinks',
1344 [ &$this, $categories, &$this->mCategoryLinks ] )
1346 foreach ( $categories as $category => $type ) {
1347 // array keys will cast numeric category names to ints, so cast back to string
1348 $category = (string)$category;
1349 $origcategory = $category;
1350 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
1351 if ( !$title ) {
1352 continue;
1354 $wgContLang->findVariantLink( $category, $title, true );
1355 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1356 continue;
1358 $text = $wgContLang->convertHtml( $title->getText() );
1359 $this->mCategories[] = $title->getText();
1360 $this->mCategoryLinks[$type][] = Linker::link( $title, $text );
1366 * Reset the category links (but not the category list) and add $categories
1368 * @param array $categories Mapping category name => sort key
1370 public function setCategoryLinks( array $categories ) {
1371 $this->mCategoryLinks = [];
1372 $this->addCategoryLinks( $categories );
1376 * Get the list of category links, in a 2-D array with the following format:
1377 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1378 * hidden categories) and $link a HTML fragment with a link to the category
1379 * page
1381 * @return array
1383 public function getCategoryLinks() {
1384 return $this->mCategoryLinks;
1388 * Get the list of category names this page belongs to
1390 * @return array Array of strings
1392 public function getCategories() {
1393 return $this->mCategories;
1397 * Add an array of indicators, with their identifiers as array
1398 * keys and HTML contents as values.
1400 * In case of duplicate keys, existing values are overwritten.
1402 * @param array $indicators
1403 * @since 1.25
1405 public function setIndicators( array $indicators ) {
1406 $this->mIndicators = $indicators + $this->mIndicators;
1407 // Keep ordered by key
1408 ksort( $this->mIndicators );
1412 * Get the indicators associated with this page.
1414 * The array will be internally ordered by item keys.
1416 * @return array Keys: identifiers, values: HTML contents
1417 * @since 1.25
1419 public function getIndicators() {
1420 return $this->mIndicators;
1424 * Adds help link with an icon via page indicators.
1425 * Link target can be overridden by a local message containing a wikilink:
1426 * the message key is: lowercase action or special page name + '-helppage'.
1427 * @param string $to Target MediaWiki.org page title or encoded URL.
1428 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1429 * @since 1.25
1431 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1432 $this->addModuleStyles( 'mediawiki.helplink' );
1433 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1435 if ( $overrideBaseUrl ) {
1436 $helpUrl = $to;
1437 } else {
1438 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1439 $helpUrl = "//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1442 $link = Html::rawElement(
1443 'a',
1445 'href' => $helpUrl,
1446 'target' => '_blank',
1447 'class' => 'mw-helplink',
1449 $text
1452 $this->setIndicators( [ 'mw-helplink' => $link ] );
1456 * Do not allow scripts which can be modified by wiki users to load on this page;
1457 * only allow scripts bundled with, or generated by, the software.
1458 * Site-wide styles are controlled by a config setting, since they can be
1459 * used to create a custom skin/theme, but not user-specific ones.
1461 * @todo this should be given a more accurate name
1463 public function disallowUserJs() {
1464 $this->reduceAllowedModules(
1465 ResourceLoaderModule::TYPE_SCRIPTS,
1466 ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL
1469 // Site-wide styles are controlled by a config setting, see bug 71621
1470 // for background on why. User styles are never allowed.
1471 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1472 $styleOrigin = ResourceLoaderModule::ORIGIN_USER_SITEWIDE;
1473 } else {
1474 $styleOrigin = ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL;
1476 $this->reduceAllowedModules(
1477 ResourceLoaderModule::TYPE_STYLES,
1478 $styleOrigin
1483 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1484 * @see ResourceLoaderModule::$origin
1485 * @param string $type ResourceLoaderModule TYPE_ constant
1486 * @return int ResourceLoaderModule ORIGIN_ class constant
1488 public function getAllowedModules( $type ) {
1489 if ( $type == ResourceLoaderModule::TYPE_COMBINED ) {
1490 return min( array_values( $this->mAllowedModules ) );
1491 } else {
1492 return isset( $this->mAllowedModules[$type] )
1493 ? $this->mAllowedModules[$type]
1494 : ResourceLoaderModule::ORIGIN_ALL;
1499 * Set the highest level of CSS/JS untrustworthiness allowed
1501 * @deprecated since 1.24 Raising level of allowed untrusted content is no longer supported.
1502 * Use reduceAllowedModules() instead
1503 * @param string $type ResourceLoaderModule TYPE_ constant
1504 * @param int $level ResourceLoaderModule class constant
1506 public function setAllowedModules( $type, $level ) {
1507 wfDeprecated( __METHOD__, '1.24' );
1508 $this->reduceAllowedModules( $type, $level );
1512 * Limit the highest level of CSS/JS untrustworthiness allowed.
1514 * If passed the same or a higher level than the current level of untrustworthiness set, the
1515 * level will remain unchanged.
1517 * @param string $type
1518 * @param int $level ResourceLoaderModule class constant
1520 public function reduceAllowedModules( $type, $level ) {
1521 $this->mAllowedModules[$type] = min( $this->getAllowedModules( $type ), $level );
1525 * Prepend $text to the body HTML
1527 * @param string $text HTML
1529 public function prependHTML( $text ) {
1530 $this->mBodytext = $text . $this->mBodytext;
1534 * Append $text to the body HTML
1536 * @param string $text HTML
1538 public function addHTML( $text ) {
1539 $this->mBodytext .= $text;
1543 * Shortcut for adding an Html::element via addHTML.
1545 * @since 1.19
1547 * @param string $element
1548 * @param array $attribs
1549 * @param string $contents
1551 public function addElement( $element, array $attribs = [], $contents = '' ) {
1552 $this->addHTML( Html::element( $element, $attribs, $contents ) );
1556 * Clear the body HTML
1558 public function clearHTML() {
1559 $this->mBodytext = '';
1563 * Get the body HTML
1565 * @return string HTML
1567 public function getHTML() {
1568 return $this->mBodytext;
1572 * Get/set the ParserOptions object to use for wikitext parsing
1574 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1575 * current ParserOption object
1576 * @return ParserOptions
1578 public function parserOptions( $options = null ) {
1579 if ( $options !== null && !empty( $options->isBogus ) ) {
1580 // Someone is trying to set a bogus pre-$wgUser PO. Check if it has
1581 // been changed somehow, and keep it if so.
1582 $anonPO = ParserOptions::newFromAnon();
1583 $anonPO->setEditSection( false );
1584 if ( !$options->matches( $anonPO ) ) {
1585 wfLogWarning( __METHOD__ . ': Setting a changed bogus ParserOptions: ' . wfGetAllCallers( 5 ) );
1586 $options->isBogus = false;
1590 if ( !$this->mParserOptions ) {
1591 if ( !$this->getContext()->getUser()->isSafeToLoad() ) {
1592 // $wgUser isn't unstubbable yet, so don't try to get a
1593 // ParserOptions for it. And don't cache this ParserOptions
1594 // either.
1595 $po = ParserOptions::newFromAnon();
1596 $po->setEditSection( false );
1597 $po->isBogus = true;
1598 if ( $options !== null ) {
1599 $this->mParserOptions = empty( $options->isBogus ) ? $options : null;
1601 return $po;
1604 $this->mParserOptions = ParserOptions::newFromContext( $this->getContext() );
1605 $this->mParserOptions->setEditSection( false );
1608 if ( $options !== null && !empty( $options->isBogus ) ) {
1609 // They're trying to restore the bogus pre-$wgUser PO. Do the right
1610 // thing.
1611 return wfSetVar( $this->mParserOptions, null, true );
1612 } else {
1613 return wfSetVar( $this->mParserOptions, $options );
1618 * Set the revision ID which will be seen by the wiki text parser
1619 * for things such as embedded {{REVISIONID}} variable use.
1621 * @param int|null $revid An positive integer, or null
1622 * @return mixed Previous value
1624 public function setRevisionId( $revid ) {
1625 $val = is_null( $revid ) ? null : intval( $revid );
1626 return wfSetVar( $this->mRevisionId, $val );
1630 * Get the displayed revision ID
1632 * @return int
1634 public function getRevisionId() {
1635 return $this->mRevisionId;
1639 * Set the timestamp of the revision which will be displayed. This is used
1640 * to avoid a extra DB call in Skin::lastModified().
1642 * @param string|null $timestamp
1643 * @return mixed Previous value
1645 public function setRevisionTimestamp( $timestamp ) {
1646 return wfSetVar( $this->mRevisionTimestamp, $timestamp );
1650 * Get the timestamp of displayed revision.
1651 * This will be null if not filled by setRevisionTimestamp().
1653 * @return string|null
1655 public function getRevisionTimestamp() {
1656 return $this->mRevisionTimestamp;
1660 * Set the displayed file version
1662 * @param File|bool $file
1663 * @return mixed Previous value
1665 public function setFileVersion( $file ) {
1666 $val = null;
1667 if ( $file instanceof File && $file->exists() ) {
1668 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1670 return wfSetVar( $this->mFileVersion, $val, true );
1674 * Get the displayed file version
1676 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1678 public function getFileVersion() {
1679 return $this->mFileVersion;
1683 * Get the templates used on this page
1685 * @return array (namespace => dbKey => revId)
1686 * @since 1.18
1688 public function getTemplateIds() {
1689 return $this->mTemplateIds;
1693 * Get the files used on this page
1695 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1696 * @since 1.18
1698 public function getFileSearchOptions() {
1699 return $this->mImageTimeKeys;
1703 * Convert wikitext to HTML and add it to the buffer
1704 * Default assumes that the current page title will be used.
1706 * @param string $text
1707 * @param bool $linestart Is this the start of a line?
1708 * @param bool $interface Is this text in the user interface language?
1709 * @throws MWException
1711 public function addWikiText( $text, $linestart = true, $interface = true ) {
1712 $title = $this->getTitle(); // Work around E_STRICT
1713 if ( !$title ) {
1714 throw new MWException( 'Title is null' );
1716 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1720 * Add wikitext with a custom Title object
1722 * @param string $text Wikitext
1723 * @param Title $title
1724 * @param bool $linestart Is this the start of a line?
1726 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1727 $this->addWikiTextTitle( $text, $title, $linestart );
1731 * Add wikitext with a custom Title object and tidy enabled.
1733 * @param string $text Wikitext
1734 * @param Title $title
1735 * @param bool $linestart Is this the start of a line?
1737 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1738 $this->addWikiTextTitle( $text, $title, $linestart, true );
1742 * Add wikitext with tidy enabled
1744 * @param string $text Wikitext
1745 * @param bool $linestart Is this the start of a line?
1747 public function addWikiTextTidy( $text, $linestart = true ) {
1748 $title = $this->getTitle();
1749 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1753 * Add wikitext with a custom Title object
1755 * @param string $text Wikitext
1756 * @param Title $title
1757 * @param bool $linestart Is this the start of a line?
1758 * @param bool $tidy Whether to use tidy
1759 * @param bool $interface Whether it is an interface message
1760 * (for example disables conversion)
1762 public function addWikiTextTitle( $text, Title $title, $linestart,
1763 $tidy = false, $interface = false
1765 global $wgParser;
1767 $popts = $this->parserOptions();
1768 $oldTidy = $popts->setTidy( $tidy );
1769 $popts->setInterfaceMessage( (bool)$interface );
1771 $parserOutput = $wgParser->getFreshParser()->parse(
1772 $text, $title, $popts,
1773 $linestart, true, $this->mRevisionId
1776 $popts->setTidy( $oldTidy );
1778 $this->addParserOutput( $parserOutput );
1783 * Add a ParserOutput object, but without Html.
1785 * @deprecated since 1.24, use addParserOutputMetadata() instead.
1786 * @param ParserOutput $parserOutput
1788 public function addParserOutputNoText( $parserOutput ) {
1789 wfDeprecated( __METHOD__, '1.24' );
1790 $this->addParserOutputMetadata( $parserOutput );
1794 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1795 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1796 * and so on.
1798 * @since 1.24
1799 * @param ParserOutput $parserOutput
1801 public function addParserOutputMetadata( $parserOutput ) {
1802 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
1803 $this->addCategoryLinks( $parserOutput->getCategories() );
1804 $this->setIndicators( $parserOutput->getIndicators() );
1805 $this->mNewSectionLink = $parserOutput->getNewSection();
1806 $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
1808 if ( !$parserOutput->isCacheable() ) {
1809 $this->enableClientCache( false );
1811 $this->mNoGallery = $parserOutput->getNoGallery();
1812 $this->mHeadItems = array_merge( $this->mHeadItems, $parserOutput->getHeadItems() );
1813 $this->addModules( $parserOutput->getModules() );
1814 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1815 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1816 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1817 $this->mPreventClickjacking = $this->mPreventClickjacking
1818 || $parserOutput->preventClickjacking();
1820 // Template versioning...
1821 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1822 if ( isset( $this->mTemplateIds[$ns] ) ) {
1823 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
1824 } else {
1825 $this->mTemplateIds[$ns] = $dbks;
1828 // File versioning...
1829 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1830 $this->mImageTimeKeys[$dbk] = $data;
1833 // Hooks registered in the object
1834 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1835 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1836 list( $hookName, $data ) = $hookInfo;
1837 if ( isset( $parserOutputHooks[$hookName] ) ) {
1838 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1842 // enable OOUI if requested via ParserOutput
1843 if ( $parserOutput->getEnableOOUI() ) {
1844 $this->enableOOUI();
1847 // Link flags are ignored for now, but may in the future be
1848 // used to mark individual language links.
1849 $linkFlags = [];
1850 Hooks::run( 'LanguageLinks', [ $this->getTitle(), &$this->mLanguageLinks, &$linkFlags ] );
1851 Hooks::run( 'OutputPageParserOutput', [ &$this, $parserOutput ] );
1855 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1856 * ParserOutput object, without any other metadata.
1858 * @since 1.24
1859 * @param ParserOutput $parserOutput
1861 public function addParserOutputContent( $parserOutput ) {
1862 $this->addParserOutputText( $parserOutput );
1864 $this->addModules( $parserOutput->getModules() );
1865 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1866 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1868 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1872 * Add the HTML associated with a ParserOutput object, without any metadata.
1874 * @since 1.24
1875 * @param ParserOutput $parserOutput
1877 public function addParserOutputText( $parserOutput ) {
1878 $text = $parserOutput->getText();
1879 Hooks::run( 'OutputPageBeforeHTML', [ &$this, &$text ] );
1880 $this->addHTML( $text );
1884 * Add everything from a ParserOutput object.
1886 * @param ParserOutput $parserOutput
1888 function addParserOutput( $parserOutput ) {
1889 $this->addParserOutputMetadata( $parserOutput );
1890 $parserOutput->setTOCEnabled( $this->mEnableTOC );
1892 // Touch section edit links only if not previously disabled
1893 if ( $parserOutput->getEditSectionTokens() ) {
1894 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks );
1897 $this->addParserOutputText( $parserOutput );
1901 * Add the output of a QuickTemplate to the output buffer
1903 * @param QuickTemplate $template
1905 public function addTemplate( &$template ) {
1906 $this->addHTML( $template->getHTML() );
1910 * Parse wikitext and return the HTML.
1912 * @param string $text
1913 * @param bool $linestart Is this the start of a line?
1914 * @param bool $interface Use interface language ($wgLang instead of
1915 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1916 * This also disables LanguageConverter.
1917 * @param Language $language Target language object, will override $interface
1918 * @throws MWException
1919 * @return string HTML
1921 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1922 global $wgParser;
1924 if ( is_null( $this->getTitle() ) ) {
1925 throw new MWException( 'Empty $mTitle in ' . __METHOD__ );
1928 $popts = $this->parserOptions();
1929 if ( $interface ) {
1930 $popts->setInterfaceMessage( true );
1932 if ( $language !== null ) {
1933 $oldLang = $popts->setTargetLanguage( $language );
1936 $parserOutput = $wgParser->getFreshParser()->parse(
1937 $text, $this->getTitle(), $popts,
1938 $linestart, true, $this->mRevisionId
1941 if ( $interface ) {
1942 $popts->setInterfaceMessage( false );
1944 if ( $language !== null ) {
1945 $popts->setTargetLanguage( $oldLang );
1948 return $parserOutput->getText();
1952 * Parse wikitext, strip paragraphs, and return the HTML.
1954 * @param string $text
1955 * @param bool $linestart Is this the start of a line?
1956 * @param bool $interface Use interface language ($wgLang instead of
1957 * $wgContLang) while parsing language sensitive magic
1958 * words like GRAMMAR and PLURAL
1959 * @return string HTML
1961 public function parseInline( $text, $linestart = true, $interface = false ) {
1962 $parsed = $this->parse( $text, $linestart, $interface );
1963 return Parser::stripOuterParagraph( $parsed );
1967 * @param $maxage
1968 * @deprecated since 1.27 Use setCdnMaxage() instead
1970 public function setSquidMaxage( $maxage ) {
1971 $this->setCdnMaxage( $maxage );
1975 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1977 * @param int $maxage Maximum cache time on the CDN, in seconds.
1979 public function setCdnMaxage( $maxage ) {
1980 $this->mCdnMaxage = min( $maxage, $this->mCdnMaxageLimit );
1984 * Lower the value of the "s-maxage" part of the "Cache-control" HTTP header
1986 * @param int $maxage Maximum cache time on the CDN, in seconds
1987 * @since 1.27
1989 public function lowerCdnMaxage( $maxage ) {
1990 $this->mCdnMaxageLimit = min( $maxage, $this->mCdnMaxageLimit );
1991 $this->setCdnMaxage( $this->mCdnMaxage );
1995 * Use enableClientCache(false) to force it to send nocache headers
1997 * @param bool $state
1999 * @return bool
2001 public function enableClientCache( $state ) {
2002 return wfSetVar( $this->mEnableClientCache, $state );
2006 * Get the list of cookies that will influence on the cache
2008 * @return array
2010 function getCacheVaryCookies() {
2011 static $cookies;
2012 if ( $cookies === null ) {
2013 $config = $this->getConfig();
2014 $cookies = array_merge(
2015 SessionManager::singleton()->getVaryCookies(),
2017 'forceHTTPS',
2019 $config->get( 'CacheVaryCookies' )
2021 Hooks::run( 'GetCacheVaryCookies', [ $this, &$cookies ] );
2023 return $cookies;
2027 * Check if the request has a cache-varying cookie header
2028 * If it does, it's very important that we don't allow public caching
2030 * @return bool
2032 function haveCacheVaryCookies() {
2033 $request = $this->getRequest();
2034 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2035 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2036 wfDebug( __METHOD__ . ": found $cookieName\n" );
2037 return true;
2040 wfDebug( __METHOD__ . ": no cache-varying cookies found\n" );
2041 return false;
2045 * Add an HTTP header that will influence on the cache
2047 * @param string $header Header name
2048 * @param string[]|null $option Options for the Key header. See
2049 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2050 * for the list of valid options.
2052 public function addVaryHeader( $header, array $option = null ) {
2053 if ( !array_key_exists( $header, $this->mVaryHeader ) ) {
2054 $this->mVaryHeader[$header] = [];
2056 if ( !is_array( $option ) ) {
2057 $option = [];
2059 $this->mVaryHeader[$header] = array_unique( array_merge( $this->mVaryHeader[$header], $option ) );
2063 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2064 * such as Accept-Encoding or Cookie
2066 * @return string
2068 public function getVaryHeader() {
2069 foreach ( SessionManager::singleton()->getVaryHeaders() as $header => $options ) {
2070 $this->addVaryHeader( $header, $options );
2072 return 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader ) );
2076 * Get a complete Key header
2078 * @return string
2080 public function getKeyHeader() {
2081 $cvCookies = $this->getCacheVaryCookies();
2083 $cookiesOption = [];
2084 foreach ( $cvCookies as $cookieName ) {
2085 $cookiesOption[] = 'param=' . $cookieName;
2087 $this->addVaryHeader( 'Cookie', $cookiesOption );
2089 foreach ( SessionManager::singleton()->getVaryHeaders() as $header => $options ) {
2090 $this->addVaryHeader( $header, $options );
2093 $headers = [];
2094 foreach ( $this->mVaryHeader as $header => $option ) {
2095 $newheader = $header;
2096 if ( is_array( $option ) && count( $option ) > 0 ) {
2097 $newheader .= ';' . implode( ';', $option );
2099 $headers[] = $newheader;
2101 $key = 'Key: ' . implode( ',', $headers );
2103 return $key;
2107 * T23672: Add Accept-Language to Vary and Key headers
2108 * if there's no 'variant' parameter existed in GET.
2110 * For example:
2111 * /w/index.php?title=Main_page should always be served; but
2112 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
2114 function addAcceptLanguage() {
2115 $title = $this->getTitle();
2116 if ( !$title instanceof Title ) {
2117 return;
2120 $lang = $title->getPageLanguage();
2121 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2122 $variants = $lang->getVariants();
2123 $aloption = [];
2124 foreach ( $variants as $variant ) {
2125 if ( $variant === $lang->getCode() ) {
2126 continue;
2127 } else {
2128 $aloption[] = 'substr=' . $variant;
2130 // IE and some other browsers use BCP 47 standards in
2131 // their Accept-Language header, like "zh-CN" or "zh-Hant".
2132 // We should handle these too.
2133 $variantBCP47 = wfBCP47( $variant );
2134 if ( $variantBCP47 !== $variant ) {
2135 $aloption[] = 'substr=' . $variantBCP47;
2139 $this->addVaryHeader( 'Accept-Language', $aloption );
2144 * Set a flag which will cause an X-Frame-Options header appropriate for
2145 * edit pages to be sent. The header value is controlled by
2146 * $wgEditPageFrameOptions.
2148 * This is the default for special pages. If you display a CSRF-protected
2149 * form on an ordinary view page, then you need to call this function.
2151 * @param bool $enable
2153 public function preventClickjacking( $enable = true ) {
2154 $this->mPreventClickjacking = $enable;
2158 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2159 * This can be called from pages which do not contain any CSRF-protected
2160 * HTML form.
2162 public function allowClickjacking() {
2163 $this->mPreventClickjacking = false;
2167 * Get the prevent-clickjacking flag
2169 * @since 1.24
2170 * @return bool
2172 public function getPreventClickjacking() {
2173 return $this->mPreventClickjacking;
2177 * Get the X-Frame-Options header value (without the name part), or false
2178 * if there isn't one. This is used by Skin to determine whether to enable
2179 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2181 * @return string
2183 public function getFrameOptions() {
2184 $config = $this->getConfig();
2185 if ( $config->get( 'BreakFrames' ) ) {
2186 return 'DENY';
2187 } elseif ( $this->mPreventClickjacking && $config->get( 'EditPageFrameOptions' ) ) {
2188 return $config->get( 'EditPageFrameOptions' );
2190 return false;
2194 * Send cache control HTTP headers
2196 public function sendCacheControl() {
2197 $response = $this->getRequest()->response();
2198 $config = $this->getConfig();
2199 if ( $config->get( 'UseETag' ) && $this->mETag ) {
2200 $response->header( "ETag: $this->mETag" );
2203 $this->addVaryHeader( 'Cookie' );
2204 $this->addAcceptLanguage();
2206 # don't serve compressed data to clients who can't handle it
2207 # maintain different caches for logged-in users and non-logged in ones
2208 $response->header( $this->getVaryHeader() );
2210 if ( $config->get( 'UseKeyHeader' ) ) {
2211 $response->header( $this->getKeyHeader() );
2214 if ( $this->mEnableClientCache ) {
2215 if (
2216 $config->get( 'UseSquid' ) && !SessionManager::getGlobalSession()->isPersistent() &&
2217 !$this->isPrintable() && $this->mCdnMaxage != 0 && !$this->haveCacheVaryCookies()
2219 if ( $config->get( 'UseESI' ) ) {
2220 # We'll purge the proxy cache explicitly, but require end user agents
2221 # to revalidate against the proxy on each visit.
2222 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2223 wfDebug( __METHOD__ . ": proxy caching with ESI; {$this->mLastModified} **", 'private' );
2224 # start with a shorter timeout for initial testing
2225 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2226 $response->header( 'Surrogate-Control: max-age=' . $config->get( 'SquidMaxage' )
2227 . '+' . $this->mCdnMaxage . ', content="ESI/1.0"' );
2228 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2229 } else {
2230 # We'll purge the proxy cache for anons explicitly, but require end user agents
2231 # to revalidate against the proxy on each visit.
2232 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2233 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2234 wfDebug( __METHOD__ . ": local proxy caching; {$this->mLastModified} **", 'private' );
2235 # start with a shorter timeout for initial testing
2236 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2237 $response->header( 'Cache-Control: s-maxage=' . $this->mCdnMaxage
2238 . ', must-revalidate, max-age=0' );
2240 } else {
2241 # We do want clients to cache if they can, but they *must* check for updates
2242 # on revisiting the page.
2243 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **", 'private' );
2244 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2245 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2247 if ( $this->mLastModified ) {
2248 $response->header( "Last-Modified: {$this->mLastModified}" );
2250 } else {
2251 wfDebug( __METHOD__ . ": no caching **", 'private' );
2253 # In general, the absence of a last modified header should be enough to prevent
2254 # the client from using its cache. We send a few other things just to make sure.
2255 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2256 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2257 $response->header( 'Pragma: no-cache' );
2262 * Finally, all the text has been munged and accumulated into
2263 * the object, let's actually output it:
2265 public function output() {
2266 if ( $this->mDoNothing ) {
2267 return;
2270 $response = $this->getRequest()->response();
2271 $config = $this->getConfig();
2273 if ( $this->mRedirect != '' ) {
2274 # Standards require redirect URLs to be absolute
2275 $this->mRedirect = wfExpandUrl( $this->mRedirect, PROTO_CURRENT );
2277 $redirect = $this->mRedirect;
2278 $code = $this->mRedirectCode;
2280 if ( Hooks::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2281 if ( $code == '301' || $code == '303' ) {
2282 if ( !$config->get( 'DebugRedirects' ) ) {
2283 $response->statusHeader( $code );
2285 $this->mLastModified = wfTimestamp( TS_RFC2822 );
2287 if ( $config->get( 'VaryOnXFP' ) ) {
2288 $this->addVaryHeader( 'X-Forwarded-Proto' );
2290 $this->sendCacheControl();
2292 $response->header( "Content-Type: text/html; charset=utf-8" );
2293 if ( $config->get( 'DebugRedirects' ) ) {
2294 $url = htmlspecialchars( $redirect );
2295 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2296 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2297 print "</body>\n</html>\n";
2298 } else {
2299 $response->header( 'Location: ' . $redirect );
2303 return;
2304 } elseif ( $this->mStatusCode ) {
2305 $response->statusHeader( $this->mStatusCode );
2308 # Buffer output; final headers may depend on later processing
2309 ob_start();
2311 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2312 $response->header( 'Content-language: ' . $config->get( 'LanguageCode' ) );
2314 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2315 // jQuery etc. can work correctly.
2316 $response->header( 'X-UA-Compatible: IE=Edge' );
2318 // Prevent framing, if requested
2319 $frameOptions = $this->getFrameOptions();
2320 if ( $frameOptions ) {
2321 $response->header( "X-Frame-Options: $frameOptions" );
2324 if ( $this->mArticleBodyOnly ) {
2325 echo $this->mBodytext;
2326 } else {
2327 $sk = $this->getSkin();
2328 // add skin specific modules
2329 $modules = $sk->getDefaultModules();
2331 // Enforce various default modules for all skins
2332 $coreModules = [
2333 // Keep this list as small as possible
2334 'site',
2335 'mediawiki.page.startup',
2336 'mediawiki.user',
2339 // Support for high-density display images if enabled
2340 if ( $config->get( 'ResponsiveImages' ) ) {
2341 $coreModules[] = 'mediawiki.hidpi';
2344 $this->addModules( $coreModules );
2345 foreach ( $modules as $group ) {
2346 $this->addModules( $group );
2348 MWDebug::addModules( $this );
2350 // Hook that allows last minute changes to the output page, e.g.
2351 // adding of CSS or Javascript by extensions.
2352 Hooks::run( 'BeforePageDisplay', [ &$this, &$sk ] );
2354 $sk->outputPage();
2357 // This hook allows last minute changes to final overall output by modifying output buffer
2358 Hooks::run( 'AfterFinalPageOutput', [ $this ] );
2360 $this->sendCacheControl();
2362 ob_end_flush();
2367 * Actually output something with print.
2369 * @param string $ins The string to output
2370 * @deprecated since 1.22 Use echo yourself.
2372 public function out( $ins ) {
2373 wfDeprecated( __METHOD__, '1.22' );
2374 print $ins;
2378 * Prepare this object to display an error page; disable caching and
2379 * indexing, clear the current text and redirect, set the page's title
2380 * and optionally an custom HTML title (content of the "<title>" tag).
2382 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2383 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2384 * optional, if not passed the "<title>" attribute will be
2385 * based on $pageTitle
2387 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2388 $this->setPageTitle( $pageTitle );
2389 if ( $htmlTitle !== false ) {
2390 $this->setHTMLTitle( $htmlTitle );
2392 $this->setRobotPolicy( 'noindex,nofollow' );
2393 $this->setArticleRelated( false );
2394 $this->enableClientCache( false );
2395 $this->mRedirect = '';
2396 $this->clearSubtitle();
2397 $this->clearHTML();
2401 * Output a standard error page
2403 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2404 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2405 * showErrorPage( 'titlemsg', $messageObject );
2406 * showErrorPage( $titleMessageObject, $messageObject );
2408 * @param string|Message $title Message key (string) for page title, or a Message object
2409 * @param string|Message $msg Message key (string) for page text, or a Message object
2410 * @param array $params Message parameters; ignored if $msg is a Message object
2412 public function showErrorPage( $title, $msg, $params = [] ) {
2413 if ( !$title instanceof Message ) {
2414 $title = $this->msg( $title );
2417 $this->prepareErrorPage( $title );
2419 if ( $msg instanceof Message ) {
2420 if ( $params !== [] ) {
2421 trigger_error( 'Argument ignored: $params. The message parameters argument '
2422 . 'is discarded when the $msg argument is a Message object instead of '
2423 . 'a string.', E_USER_NOTICE );
2425 $this->addHTML( $msg->parseAsBlock() );
2426 } else {
2427 $this->addWikiMsgArray( $msg, $params );
2430 $this->returnToMain();
2434 * Output a standard permission error page
2436 * @param array $errors Error message keys
2437 * @param string $action Action that was denied or null if unknown
2439 public function showPermissionsErrorPage( array $errors, $action = null ) {
2440 // For some action (read, edit, create and upload), display a "login to do this action"
2441 // error if all of the following conditions are met:
2442 // 1. the user is not logged in
2443 // 2. the only error is insufficient permissions (i.e. no block or something else)
2444 // 3. the error can be avoided simply by logging in
2445 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2446 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2447 && ( $errors[0][0] == 'badaccess-groups' || $errors[0][0] == 'badaccess-group0' )
2448 && ( User::groupHasPermission( 'user', $action )
2449 || User::groupHasPermission( 'autoconfirmed', $action ) )
2451 $displayReturnto = null;
2453 # Due to bug 32276, if a user does not have read permissions,
2454 # $this->getTitle() will just give Special:Badtitle, which is
2455 # not especially useful as a returnto parameter. Use the title
2456 # from the request instead, if there was one.
2457 $request = $this->getRequest();
2458 $returnto = Title::newFromText( $request->getVal( 'title', '' ) );
2459 if ( $action == 'edit' ) {
2460 $msg = 'whitelistedittext';
2461 $displayReturnto = $returnto;
2462 } elseif ( $action == 'createpage' || $action == 'createtalk' ) {
2463 $msg = 'nocreatetext';
2464 } elseif ( $action == 'upload' ) {
2465 $msg = 'uploadnologintext';
2466 } else { # Read
2467 $msg = 'loginreqpagetext';
2468 $displayReturnto = Title::newMainPage();
2471 $query = [];
2473 if ( $returnto ) {
2474 $query['returnto'] = $returnto->getPrefixedText();
2476 if ( !$request->wasPosted() ) {
2477 $returntoquery = $request->getValues();
2478 unset( $returntoquery['title'] );
2479 unset( $returntoquery['returnto'] );
2480 unset( $returntoquery['returntoquery'] );
2481 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2484 $loginLink = Linker::linkKnown(
2485 SpecialPage::getTitleFor( 'Userlogin' ),
2486 $this->msg( 'loginreqlink' )->escaped(),
2488 $query
2491 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2492 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2494 # Don't return to a page the user can't read otherwise
2495 # we'll end up in a pointless loop
2496 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2497 $this->returnToMain( null, $displayReturnto );
2499 } else {
2500 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2501 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2506 * Display an error page indicating that a given version of MediaWiki is
2507 * required to use it
2509 * @param mixed $version The version of MediaWiki needed to use the page
2511 public function versionRequired( $version ) {
2512 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2514 $this->addWikiMsg( 'versionrequiredtext', $version );
2515 $this->returnToMain();
2519 * Format a list of error messages
2521 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2522 * @param string $action Action that was denied or null if unknown
2523 * @return string The wikitext error-messages, formatted into a list.
2525 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2526 if ( $action == null ) {
2527 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2528 } else {
2529 $action_desc = $this->msg( "action-$action" )->plain();
2530 $text = $this->msg(
2531 'permissionserrorstext-withaction',
2532 count( $errors ),
2533 $action_desc
2534 )->plain() . "\n\n";
2537 if ( count( $errors ) > 1 ) {
2538 $text .= '<ul class="permissions-errors">' . "\n";
2540 foreach ( $errors as $error ) {
2541 $text .= '<li>';
2542 $text .= call_user_func_array( [ $this, 'msg' ], $error )->plain();
2543 $text .= "</li>\n";
2545 $text .= '</ul>';
2546 } else {
2547 $text .= "<div class=\"permissions-errors\">\n" .
2548 call_user_func_array( [ $this, 'msg' ], reset( $errors ) )->plain() .
2549 "\n</div>";
2552 return $text;
2556 * Display a page stating that the Wiki is in read-only mode.
2557 * Should only be called after wfReadOnly() has returned true.
2559 * Historically, this function was used to show the source of the page that the user
2560 * was trying to edit and _also_ permissions error messages. The relevant code was
2561 * moved into EditPage in 1.19 (r102024 / d83c2a431c2a) and removed here in 1.25.
2563 * @deprecated since 1.25; throw the exception directly
2564 * @throws ReadOnlyError
2566 public function readOnlyPage() {
2567 if ( func_num_args() > 0 ) {
2568 throw new MWException( __METHOD__ . ' no longer accepts arguments since 1.25.' );
2571 throw new ReadOnlyError;
2575 * Turn off regular page output and return an error response
2576 * for when rate limiting has triggered.
2578 * @deprecated since 1.25; throw the exception directly
2580 public function rateLimited() {
2581 wfDeprecated( __METHOD__, '1.25' );
2582 throw new ThrottledError;
2586 * Show a warning about slave lag
2588 * If the lag is higher than $wgSlaveLagCritical seconds,
2589 * then the warning is a bit more obvious. If the lag is
2590 * lower than $wgSlaveLagWarning, then no warning is shown.
2592 * @param int $lag Slave lag
2594 public function showLagWarning( $lag ) {
2595 $config = $this->getConfig();
2596 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2597 $message = $lag < $config->get( 'SlaveLagCritical' )
2598 ? 'lag-warn-normal'
2599 : 'lag-warn-high';
2600 $wrap = Html::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2601 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2605 public function showFatalError( $message ) {
2606 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2608 $this->addHTML( $message );
2611 public function showUnexpectedValueError( $name, $val ) {
2612 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2615 public function showFileCopyError( $old, $new ) {
2616 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2619 public function showFileRenameError( $old, $new ) {
2620 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2623 public function showFileDeleteError( $name ) {
2624 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2627 public function showFileNotFoundError( $name ) {
2628 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2632 * Add a "return to" link pointing to a specified title
2634 * @param Title $title Title to link
2635 * @param array $query Query string parameters
2636 * @param string $text Text of the link (input is not escaped)
2637 * @param array $options Options array to pass to Linker
2639 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
2640 $link = $this->msg( 'returnto' )->rawParams(
2641 Linker::link( $title, $text, [], $query, $options ) )->escaped();
2642 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2646 * Add a "return to" link pointing to a specified title,
2647 * or the title indicated in the request, or else the main page
2649 * @param mixed $unused
2650 * @param Title|string $returnto Title or String to return to
2651 * @param string $returntoquery Query string for the return to link
2653 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2654 if ( $returnto == null ) {
2655 $returnto = $this->getRequest()->getText( 'returnto' );
2658 if ( $returntoquery == null ) {
2659 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2662 if ( $returnto === '' ) {
2663 $returnto = Title::newMainPage();
2666 if ( is_object( $returnto ) ) {
2667 $titleObj = $returnto;
2668 } else {
2669 $titleObj = Title::newFromText( $returnto );
2671 if ( !is_object( $titleObj ) ) {
2672 $titleObj = Title::newMainPage();
2675 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2679 * @param Skin $sk The given Skin
2680 * @param bool $includeStyle Unused
2681 * @return string The doctype, opening "<html>", and head element.
2683 public function headElement( Skin $sk, $includeStyle = true ) {
2684 global $wgContLang;
2686 $userdir = $this->getLanguage()->getDir();
2687 $sitedir = $wgContLang->getDir();
2689 $ret = Html::htmlHeader( $sk->getHtmlElementAttributes() );
2691 if ( $this->getHTMLTitle() == '' ) {
2692 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2695 $openHead = Html::openElement( 'head' );
2696 if ( $openHead ) {
2697 # Don't bother with the newline if $head == ''
2698 $ret .= "$openHead\n";
2701 if ( !Html::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2702 // Add <meta charset="UTF-8">
2703 // This should be before <title> since it defines the charset used by
2704 // text including the text inside <title>.
2705 // The spec recommends defining XHTML5's charset using the XML declaration
2706 // instead of meta.
2707 // Our XML declaration is output by Html::htmlHeader.
2708 // http://www.whatwg.org/html/semantics.html#attr-meta-http-equiv-content-type
2709 // http://www.whatwg.org/html/semantics.html#charset
2710 $ret .= Html::element( 'meta', [ 'charset' => 'UTF-8' ] ) . "\n";
2713 $ret .= Html::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2714 $ret .= $this->getInlineHeadScripts() . "\n";
2715 $ret .= $this->buildCssLinks() . "\n";
2716 $ret .= $this->getExternalHeadScripts() . "\n";
2718 foreach ( $this->getHeadLinksArray() as $item ) {
2719 $ret .= $item . "\n";
2722 foreach ( $this->mHeadItems as $item ) {
2723 $ret .= $item . "\n";
2726 $closeHead = Html::closeElement( 'head' );
2727 if ( $closeHead ) {
2728 $ret .= "$closeHead\n";
2731 $bodyClasses = [];
2732 $bodyClasses[] = 'mediawiki';
2734 # Classes for LTR/RTL directionality support
2735 $bodyClasses[] = $userdir;
2736 $bodyClasses[] = "sitedir-$sitedir";
2738 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2739 # A <body> class is probably not the best way to do this . . .
2740 $bodyClasses[] = 'capitalize-all-nouns';
2743 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2744 $bodyClasses[] = 'skin-' . Sanitizer::escapeClass( $sk->getSkinName() );
2745 $bodyClasses[] =
2746 'action-' . Sanitizer::escapeClass( Action::getActionName( $this->getContext() ) );
2748 $bodyAttrs = [];
2749 // While the implode() is not strictly needed, it's used for backwards compatibility
2750 // (this used to be built as a string and hooks likely still expect that).
2751 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2753 // Allow skins and extensions to add body attributes they need
2754 $sk->addToBodyAttributes( $this, $bodyAttrs );
2755 Hooks::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
2757 $ret .= Html::openElement( 'body', $bodyAttrs ) . "\n";
2759 return $ret;
2763 * Get a ResourceLoader object associated with this OutputPage
2765 * @return ResourceLoader
2767 public function getResourceLoader() {
2768 if ( is_null( $this->mResourceLoader ) ) {
2769 $this->mResourceLoader = new ResourceLoader(
2770 $this->getConfig(),
2771 LoggerFactory::getInstance( 'resourceloader' )
2774 return $this->mResourceLoader;
2778 * Construct neccecary html and loader preset states to load modules on a page.
2780 * Use getHtmlFromLoaderLinks() to convert this array to HTML.
2782 * @param array|string $modules One or more module names
2783 * @param string $only ResourceLoaderModule TYPE_ class constant
2784 * @param array $extraQuery [optional] Array with extra query parameters for the request
2785 * @return array A list of HTML strings and array of client loader preset states
2787 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
2788 $modules = (array)$modules;
2790 $links = [
2791 // List of html strings
2792 'html' => [],
2793 // Associative array of module names and their states
2794 'states' => [],
2797 if ( !count( $modules ) ) {
2798 return $links;
2801 if ( count( $modules ) > 1 ) {
2802 // Remove duplicate module requests
2803 $modules = array_unique( $modules );
2804 // Sort module names so requests are more uniform
2805 sort( $modules );
2807 if ( ResourceLoader::inDebugMode() ) {
2808 // Recursively call us for every item
2809 foreach ( $modules as $name ) {
2810 $link = $this->makeResourceLoaderLink( $name, $only, $extraQuery );
2811 $links['html'] = array_merge( $links['html'], $link['html'] );
2812 $links['states'] += $link['states'];
2814 return $links;
2818 if ( !is_null( $this->mTarget ) ) {
2819 $extraQuery['target'] = $this->mTarget;
2822 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
2823 $sortedModules = [];
2824 $resourceLoader = $this->getResourceLoader();
2825 foreach ( $modules as $name ) {
2826 $module = $resourceLoader->getModule( $name );
2827 # Check that we're allowed to include this module on this page
2828 if ( !$module
2829 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_SCRIPTS )
2830 && $only == ResourceLoaderModule::TYPE_SCRIPTS )
2831 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_STYLES )
2832 && $only == ResourceLoaderModule::TYPE_STYLES )
2833 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_COMBINED )
2834 && $only == ResourceLoaderModule::TYPE_COMBINED )
2835 || ( $this->mTarget && !in_array( $this->mTarget, $module->getTargets() ) )
2837 continue;
2840 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
2843 foreach ( $sortedModules as $source => $groups ) {
2844 foreach ( $groups as $group => $grpModules ) {
2845 // Special handling for user-specific groups
2846 $user = null;
2847 if ( ( $group === 'user' || $group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2848 $user = $this->getUser()->getName();
2851 // Create a fake request based on the one we are about to make so modules return
2852 // correct timestamp and emptiness data
2853 $query = ResourceLoader::makeLoaderQuery(
2854 [], // modules; not determined yet
2855 $this->getLanguage()->getCode(),
2856 $this->getSkin()->getSkinName(),
2857 $user,
2858 null, // version; not determined yet
2859 ResourceLoader::inDebugMode(),
2860 $only === ResourceLoaderModule::TYPE_COMBINED ? null : $only,
2861 $this->isPrintable(),
2862 $this->getRequest()->getBool( 'handheld' ),
2863 $extraQuery
2865 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2867 // Extract modules that know they're empty and see if we have one or more
2868 // raw modules
2869 $isRaw = false;
2870 foreach ( $grpModules as $key => $module ) {
2871 // Inline empty modules: since they're empty, just mark them as 'ready' (bug 46857)
2872 // If we're only getting the styles, we don't need to do anything for empty modules.
2873 if ( $module->isKnownEmpty( $context ) ) {
2874 unset( $grpModules[$key] );
2875 if ( $only !== ResourceLoaderModule::TYPE_STYLES ) {
2876 $links['states'][$key] = 'ready';
2880 $isRaw |= $module->isRaw();
2883 // If there are no non-empty modules, skip this group
2884 if ( count( $grpModules ) === 0 ) {
2885 continue;
2888 // Inline private modules. These can't be loaded through load.php for security
2889 // reasons, see bug 34907. Note that these modules should be loaded from
2890 // getExternalHeadScripts() before the first loader call. Otherwise other modules can't
2891 // properly use them as dependencies (bug 30914)
2892 if ( $group === 'private' ) {
2893 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
2894 $links['html'][] = Html::inlineStyle(
2895 $resourceLoader->makeModuleResponse( $context, $grpModules )
2897 } else {
2898 $links['html'][] = ResourceLoader::makeInlineScript(
2899 $resourceLoader->makeModuleResponse( $context, $grpModules )
2902 continue;
2905 // Special handling for the user group; because users might change their stuff
2906 // on-wiki like user pages, or user preferences; we need to find the highest
2907 // timestamp of these user-changeable modules so we can ensure cache misses on change
2908 // This should NOT be done for the site group (bug 27564) because anons get that too
2909 // and we shouldn't be putting timestamps in CDN-cached HTML
2910 $version = null;
2911 if ( $group === 'user' ) {
2912 $query['version'] = $resourceLoader->getCombinedVersion( $context, array_keys( $grpModules ) );
2915 $query['modules'] = ResourceLoader::makePackedModulesString( array_keys( $grpModules ) );
2916 $moduleContext = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2917 $url = $resourceLoader->createLoaderURL( $source, $moduleContext, $extraQuery );
2919 // Automatically select style/script elements
2920 if ( $only === ResourceLoaderModule::TYPE_STYLES ) {
2921 $link = Html::linkedStyle( $url );
2922 } else {
2923 if ( $context->getRaw() || $isRaw ) {
2924 // Startup module can't load itself, needs to use <script> instead of mw.loader.load
2925 $link = Html::element( 'script', [
2926 // In SpecialJavaScriptTest, QUnit must load synchronous
2927 'async' => !isset( $extraQuery['sync'] ),
2928 'src' => $url
2929 ] );
2930 } else {
2931 $link = ResourceLoader::makeInlineScript(
2932 Xml::encodeJsCall( 'mw.loader.load', [ $url ] )
2936 // For modules requested directly in the html via <script> or mw.loader.load
2937 // tell mw.loader they are being loading to prevent duplicate requests.
2938 foreach ( $grpModules as $key => $module ) {
2939 // Don't output state=loading for the startup module.
2940 if ( $key !== 'startup' ) {
2941 $links['states'][$key] = 'loading';
2946 if ( $group == 'noscript' ) {
2947 $links['html'][] = Html::rawElement( 'noscript', [], $link );
2948 } else {
2949 $links['html'][] = $link;
2954 return $links;
2958 * Build html output from an array of links from makeResourceLoaderLink.
2959 * @param array $links
2960 * @return string HTML
2962 protected static function getHtmlFromLoaderLinks( array $links ) {
2963 $html = [];
2964 $states = [];
2965 foreach ( $links as $link ) {
2966 if ( !is_array( $link ) ) {
2967 $html[] = $link;
2968 } else {
2969 $html = array_merge( $html, $link['html'] );
2970 $states += $link['states'];
2973 // Filter out empty values
2974 $html = array_filter( $html, 'strlen' );
2976 if ( count( $states ) ) {
2977 array_unshift( $html, ResourceLoader::makeInlineScript(
2978 ResourceLoader::makeLoaderStateScript( $states )
2979 ) );
2982 return WrappedString::join( "\n", $html );
2986 * JS stuff to put in the "<head>". This is the startup module, config
2987 * vars and modules marked with position 'top'
2989 * @return string HTML fragment
2991 function getHeadScripts() {
2992 return $this->getInlineHeadScripts() . "\n" . $this->getExternalHeadScripts();
2996 * <script src="..."> tags for "<head>". This is the startup module
2997 * and other modules marked with position 'top'.
2999 * @return string HTML fragment
3001 function getExternalHeadScripts() {
3002 $links = [];
3004 // Startup - this provides the client with the module
3005 // manifest and loads jquery and mediawiki base modules
3006 $links[] = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule::TYPE_SCRIPTS );
3008 return self::getHtmlFromLoaderLinks( $links );
3012 * <script>...</script> tags to put in "<head>".
3014 * @return string HTML fragment
3016 function getInlineHeadScripts() {
3017 $links = [];
3019 // Client profile classes for <html>. Allows for easy hiding/showing of UI components.
3020 // Must be done synchronously on every page to avoid flashes of wrong content.
3021 // Note: This class distinguishes MediaWiki-supported JavaScript from the rest.
3022 // The "rest" includes browsers that support JavaScript but not supported by our runtime.
3023 // For the performance benefit of the majority, this is added unconditionally here and is
3024 // then fixed up by the startup module for unsupported browsers.
3025 $links[] = Html::inlineScript(
3026 'document.documentElement.className = document.documentElement.className'
3027 . '.replace( /(^|\s)client-nojs(\s|$)/, "$1client-js$2" );'
3030 // Load config before anything else
3031 $links[] = ResourceLoader::makeInlineScript(
3032 ResourceLoader::makeConfigSetScript( $this->getJSVars() )
3035 // Load embeddable private modules before any loader links
3036 // This needs to be TYPE_COMBINED so these modules are properly wrapped
3037 // in mw.loader.implement() calls and deferred until mw.user is available
3038 $embedScripts = [ 'user.options' ];
3039 $links[] = $this->makeResourceLoaderLink(
3040 $embedScripts,
3041 ResourceLoaderModule::TYPE_COMBINED
3043 // Separate user.tokens as otherwise caching will be allowed (T84960)
3044 $links[] = $this->makeResourceLoaderLink(
3045 'user.tokens',
3046 ResourceLoaderModule::TYPE_COMBINED
3049 // Modules requests - let the client calculate dependencies and batch requests as it likes
3050 // Only load modules that have marked themselves for loading at the top
3051 $modules = $this->getModules( true, 'top' );
3052 if ( $modules ) {
3053 $links[] = ResourceLoader::makeInlineScript(
3054 Xml::encodeJsCall( 'mw.loader.load', [ $modules ] )
3058 // "Scripts only" modules marked for top inclusion
3059 $links[] = $this->makeResourceLoaderLink(
3060 $this->getModuleScripts( true, 'top' ),
3061 ResourceLoaderModule::TYPE_SCRIPTS
3064 return self::getHtmlFromLoaderLinks( $links );
3068 * JS stuff to put at the 'bottom', which goes at the bottom of the `<body>`.
3069 * These are modules marked with position 'bottom', legacy scripts ($this->mScripts),
3070 * site JS, and user JS.
3072 * @param bool $unused Previously used to let this method change its output based
3073 * on whether it was called by getExternalHeadScripts() or getBottomScripts().
3074 * @return string
3076 function getScriptsForBottomQueue( $unused = null ) {
3077 // Scripts "only" requests marked for bottom inclusion
3078 // If we're in the <head>, use load() calls rather than <script src="..."> tags
3079 $links = [];
3081 $links[] = $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
3082 ResourceLoaderModule::TYPE_SCRIPTS
3085 // Modules requests - let the client calculate dependencies and batch requests as it likes
3086 // Only load modules that have marked themselves for loading at the bottom
3087 $modules = $this->getModules( true, 'bottom' );
3088 if ( $modules ) {
3089 $links[] = ResourceLoader::makeInlineScript(
3090 Xml::encodeJsCall( 'mw.loader.load', [ $modules ] )
3094 // Legacy Scripts
3095 $links[] = $this->mScripts;
3097 // Add user JS if enabled
3098 // This must use TYPE_COMBINED instead of only=scripts so that its request is handled by
3099 // mw.loader.implement() which ensures that execution is scheduled after the "site" module.
3100 if ( $this->getConfig()->get( 'AllowUserJs' )
3101 && $this->getUser()->isLoggedIn()
3102 && $this->getTitle()
3103 && $this->getTitle()->isJsSubpage()
3104 && $this->userCanPreview()
3106 // We're on a preview of a JS subpage. Exclude this page from the user module (T28283)
3107 // and include the draft contents as a raw script instead.
3108 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_COMBINED,
3109 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
3111 // Load the previewed JS
3112 $links[] = ResourceLoader::makeInlineScript(
3113 Xml::encodeJsCall( 'mw.loader.using', [
3114 [ 'user', 'site' ],
3115 new XmlJsCode(
3116 'function () {'
3117 . Xml::encodeJsCall( '$.globalEval', [
3118 $this->getRequest()->getText( 'wpTextbox1' )
3120 . '}'
3125 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
3126 // asynchronously and may arrive *after* the inline script here. So the previewed code
3127 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js.
3128 // Similarly, when previewing ./common.js and the user module does arrive first,
3129 // it will arrive without common.js and the inline script runs after.
3130 // Thus running common after the excluded subpage.
3131 } else {
3132 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
3133 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_COMBINED );
3136 // Group JS is only enabled if site JS is enabled.
3137 $links[] = $this->makeResourceLoaderLink(
3138 'user.groups',
3139 ResourceLoaderModule::TYPE_COMBINED
3142 return self::getHtmlFromLoaderLinks( $links );
3146 * JS stuff to put at the bottom of the "<body>"
3147 * @return string
3149 function getBottomScripts() {
3150 return $this->getScriptsForBottomQueue();
3154 * Get the javascript config vars to include on this page
3156 * @return array Array of javascript config vars
3157 * @since 1.23
3159 public function getJsConfigVars() {
3160 return $this->mJsConfigVars;
3164 * Add one or more variables to be set in mw.config in JavaScript
3166 * @param string|array $keys Key or array of key/value pairs
3167 * @param mixed $value [optional] Value of the configuration variable
3169 public function addJsConfigVars( $keys, $value = null ) {
3170 if ( is_array( $keys ) ) {
3171 foreach ( $keys as $key => $value ) {
3172 $this->mJsConfigVars[$key] = $value;
3174 return;
3177 $this->mJsConfigVars[$keys] = $value;
3181 * Get an array containing the variables to be set in mw.config in JavaScript.
3183 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3184 * - in other words, page-independent/site-wide variables (without state).
3185 * You will only be adding bloat to the html page and causing page caches to
3186 * have to be purged on configuration changes.
3187 * @return array
3189 public function getJSVars() {
3190 global $wgContLang;
3192 $curRevisionId = 0;
3193 $articleId = 0;
3194 $canonicalSpecialPageName = false; # bug 21115
3196 $title = $this->getTitle();
3197 $ns = $title->getNamespace();
3198 $canonicalNamespace = MWNamespace::exists( $ns )
3199 ? MWNamespace::getCanonicalName( $ns )
3200 : $title->getNsText();
3202 $sk = $this->getSkin();
3203 // Get the relevant title so that AJAX features can use the correct page name
3204 // when making API requests from certain special pages (bug 34972).
3205 $relevantTitle = $sk->getRelevantTitle();
3206 $relevantUser = $sk->getRelevantUser();
3208 if ( $ns == NS_SPECIAL ) {
3209 list( $canonicalSpecialPageName, /*...*/ ) =
3210 SpecialPageFactory::resolveAlias( $title->getDBkey() );
3211 } elseif ( $this->canUseWikiPage() ) {
3212 $wikiPage = $this->getWikiPage();
3213 $curRevisionId = $wikiPage->getLatest();
3214 $articleId = $wikiPage->getId();
3217 $lang = $title->getPageLanguage();
3219 // Pre-process information
3220 $separatorTransTable = $lang->separatorTransformTable();
3221 $separatorTransTable = $separatorTransTable ? $separatorTransTable : [];
3222 $compactSeparatorTransTable = [
3223 implode( "\t", array_keys( $separatorTransTable ) ),
3224 implode( "\t", $separatorTransTable ),
3226 $digitTransTable = $lang->digitTransformTable();
3227 $digitTransTable = $digitTransTable ? $digitTransTable : [];
3228 $compactDigitTransTable = [
3229 implode( "\t", array_keys( $digitTransTable ) ),
3230 implode( "\t", $digitTransTable ),
3233 $user = $this->getUser();
3235 $vars = [
3236 'wgCanonicalNamespace' => $canonicalNamespace,
3237 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3238 'wgNamespaceNumber' => $title->getNamespace(),
3239 'wgPageName' => $title->getPrefixedDBkey(),
3240 'wgTitle' => $title->getText(),
3241 'wgCurRevisionId' => $curRevisionId,
3242 'wgRevisionId' => (int)$this->getRevisionId(),
3243 'wgArticleId' => $articleId,
3244 'wgIsArticle' => $this->isArticle(),
3245 'wgIsRedirect' => $title->isRedirect(),
3246 'wgAction' => Action::getActionName( $this->getContext() ),
3247 'wgUserName' => $user->isAnon() ? null : $user->getName(),
3248 'wgUserGroups' => $user->getEffectiveGroups(),
3249 'wgCategories' => $this->getCategories(),
3250 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3251 'wgPageContentLanguage' => $lang->getCode(),
3252 'wgPageContentModel' => $title->getContentModel(),
3253 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3254 'wgDigitTransformTable' => $compactDigitTransTable,
3255 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3256 'wgMonthNames' => $lang->getMonthNamesArray(),
3257 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3258 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3259 'wgRelevantArticleId' => $relevantTitle->getArticleId(),
3262 if ( $user->isLoggedIn() ) {
3263 $vars['wgUserId'] = $user->getId();
3264 $vars['wgUserEditCount'] = $user->getEditCount();
3265 $userReg = wfTimestampOrNull( TS_UNIX, $user->getRegistration() );
3266 $vars['wgUserRegistration'] = $userReg !== null ? ( $userReg * 1000 ) : null;
3267 // Get the revision ID of the oldest new message on the user's talk
3268 // page. This can be used for constructing new message alerts on
3269 // the client side.
3270 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3273 if ( $wgContLang->hasVariants() ) {
3274 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3276 // Same test as SkinTemplate
3277 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3278 && ( $title->exists() || $title->quickUserCan( 'create', $user ) );
3280 foreach ( $title->getRestrictionTypes() as $type ) {
3281 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3284 if ( $title->isMainPage() ) {
3285 $vars['wgIsMainPage'] = true;
3288 if ( $this->mRedirectedFrom ) {
3289 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom->getPrefixedDBkey();
3292 if ( $relevantUser ) {
3293 $vars['wgRelevantUserName'] = $relevantUser->getName();
3296 // Allow extensions to add their custom variables to the mw.config map.
3297 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3298 // page-dependant but site-wide (without state).
3299 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3300 Hooks::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3302 // Merge in variables from addJsConfigVars last
3303 return array_merge( $vars, $this->getJsConfigVars() );
3307 * To make it harder for someone to slip a user a fake
3308 * user-JavaScript or user-CSS preview, a random token
3309 * is associated with the login session. If it's not
3310 * passed back with the preview request, we won't render
3311 * the code.
3313 * @return bool
3315 public function userCanPreview() {
3316 $request = $this->getRequest();
3317 if (
3318 $request->getVal( 'action' ) !== 'submit' ||
3319 !$request->getCheck( 'wpPreview' ) ||
3320 !$request->wasPosted()
3322 return false;
3325 $user = $this->getUser();
3326 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3327 return false;
3330 $title = $this->getTitle();
3331 if ( !$title->isJsSubpage() && !$title->isCssSubpage() ) {
3332 return false;
3334 if ( !$title->isSubpageOf( $user->getUserPage() ) ) {
3335 // Don't execute another user's CSS or JS on preview (T85855)
3336 return false;
3339 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3340 if ( count( $errors ) !== 0 ) {
3341 return false;
3344 return true;
3348 * @return array Array in format "link name or number => 'link html'".
3350 public function getHeadLinksArray() {
3351 global $wgVersion;
3353 $tags = [];
3354 $config = $this->getConfig();
3356 $canonicalUrl = $this->mCanonicalUrl;
3358 $tags['meta-generator'] = Html::element( 'meta', [
3359 'name' => 'generator',
3360 'content' => "MediaWiki $wgVersion",
3361 ] );
3363 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3364 $tags['meta-referrer'] = Html::element( 'meta', [
3365 'name' => 'referrer',
3366 'content' => $config->get( 'ReferrerPolicy' )
3367 ] );
3370 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3371 if ( $p !== 'index,follow' ) {
3372 // http://www.robotstxt.org/wc/meta-user.html
3373 // Only show if it's different from the default robots policy
3374 $tags['meta-robots'] = Html::element( 'meta', [
3375 'name' => 'robots',
3376 'content' => $p,
3377 ] );
3380 foreach ( $this->mMetatags as $tag ) {
3381 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3382 $a = 'http-equiv';
3383 $tag[0] = substr( $tag[0], 5 );
3384 } else {
3385 $a = 'name';
3387 $tagName = "meta-{$tag[0]}";
3388 if ( isset( $tags[$tagName] ) ) {
3389 $tagName .= $tag[1];
3391 $tags[$tagName] = Html::element( 'meta',
3393 $a => $tag[0],
3394 'content' => $tag[1]
3399 foreach ( $this->mLinktags as $tag ) {
3400 $tags[] = Html::element( 'link', $tag );
3403 # Universal edit button
3404 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3405 $user = $this->getUser();
3406 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3407 && ( $this->getTitle()->exists() ||
3408 $this->getTitle()->quickUserCan( 'create', $user ) )
3410 // Original UniversalEditButton
3411 $msg = $this->msg( 'edit' )->text();
3412 $tags['universal-edit-button'] = Html::element( 'link', [
3413 'rel' => 'alternate',
3414 'type' => 'application/x-wiki',
3415 'title' => $msg,
3416 'href' => $this->getTitle()->getEditURL(),
3417 ] );
3418 // Alternate edit link
3419 $tags['alternative-edit'] = Html::element( 'link', [
3420 'rel' => 'edit',
3421 'title' => $msg,
3422 'href' => $this->getTitle()->getEditURL(),
3423 ] );
3427 # Generally the order of the favicon and apple-touch-icon links
3428 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3429 # uses whichever one appears later in the HTML source. Make sure
3430 # apple-touch-icon is specified first to avoid this.
3431 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3432 $tags['apple-touch-icon'] = Html::element( 'link', [
3433 'rel' => 'apple-touch-icon',
3434 'href' => $config->get( 'AppleTouchIcon' )
3435 ] );
3438 if ( $config->get( 'Favicon' ) !== false ) {
3439 $tags['favicon'] = Html::element( 'link', [
3440 'rel' => 'shortcut icon',
3441 'href' => $config->get( 'Favicon' )
3442 ] );
3445 # OpenSearch description link
3446 $tags['opensearch'] = Html::element( 'link', [
3447 'rel' => 'search',
3448 'type' => 'application/opensearchdescription+xml',
3449 'href' => wfScript( 'opensearch_desc' ),
3450 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3451 ] );
3453 if ( $config->get( 'EnableAPI' ) ) {
3454 # Real Simple Discovery link, provides auto-discovery information
3455 # for the MediaWiki API (and potentially additional custom API
3456 # support such as WordPress or Twitter-compatible APIs for a
3457 # blogging extension, etc)
3458 $tags['rsd'] = Html::element( 'link', [
3459 'rel' => 'EditURI',
3460 'type' => 'application/rsd+xml',
3461 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3462 // Whether RSD accepts relative or protocol-relative URLs is completely
3463 // undocumented, though.
3464 'href' => wfExpandUrl( wfAppendQuery(
3465 wfScript( 'api' ),
3466 [ 'action' => 'rsd' ] ),
3467 PROTO_RELATIVE
3469 ] );
3472 # Language variants
3473 if ( !$config->get( 'DisableLangConversion' ) ) {
3474 $lang = $this->getTitle()->getPageLanguage();
3475 if ( $lang->hasVariants() ) {
3476 $variants = $lang->getVariants();
3477 foreach ( $variants as $variant ) {
3478 $tags["variant-$variant"] = Html::element( 'link', [
3479 'rel' => 'alternate',
3480 'hreflang' => wfBCP47( $variant ),
3481 'href' => $this->getTitle()->getLocalURL(
3482 [ 'variant' => $variant ] )
3486 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3487 $tags["variant-x-default"] = Html::element( 'link', [
3488 'rel' => 'alternate',
3489 'hreflang' => 'x-default',
3490 'href' => $this->getTitle()->getLocalURL() ] );
3494 # Copyright
3495 if ( $this->copyrightUrl !== null ) {
3496 $copyright = $this->copyrightUrl;
3497 } else {
3498 $copyright = '';
3499 if ( $config->get( 'RightsPage' ) ) {
3500 $copy = Title::newFromText( $config->get( 'RightsPage' ) );
3502 if ( $copy ) {
3503 $copyright = $copy->getLocalURL();
3507 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3508 $copyright = $config->get( 'RightsUrl' );
3512 if ( $copyright ) {
3513 $tags['copyright'] = Html::element( 'link', [
3514 'rel' => 'copyright',
3515 'href' => $copyright ]
3519 # Feeds
3520 if ( $config->get( 'Feed' ) ) {
3521 $feedLinks = [];
3523 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3524 # Use the page name for the title. In principle, this could
3525 # lead to issues with having the same name for different feeds
3526 # corresponding to the same page, but we can't avoid that at
3527 # this low a level.
3529 $feedLinks[] = $this->feedLink(
3530 $format,
3531 $link,
3532 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3533 $this->msg(
3534 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3535 )->text()
3539 # Recent changes feed should appear on every page (except recentchanges,
3540 # that would be redundant). Put it after the per-page feed to avoid
3541 # changing existing behavior. It's still available, probably via a
3542 # menu in your browser. Some sites might have a different feed they'd
3543 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3544 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3545 # If so, use it instead.
3546 $sitename = $config->get( 'Sitename' );
3547 if ( $config->get( 'OverrideSiteFeed' ) ) {
3548 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3549 // Note, this->feedLink escapes the url.
3550 $feedLinks[] = $this->feedLink(
3551 $type,
3552 $feedUrl,
3553 $this->msg( "site-{$type}-feed", $sitename )->text()
3556 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3557 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
3558 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3559 $feedLinks[] = $this->feedLink(
3560 $format,
3561 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3562 # For grep: 'site-rss-feed', 'site-atom-feed'
3563 $this->msg( "site-{$format}-feed", $sitename )->text()
3568 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3569 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3570 # use OutputPage::addFeedLink() instead.
3571 Hooks::run( 'AfterBuildFeedLinks', [ &$feedLinks ] );
3573 $tags += $feedLinks;
3576 # Canonical URL
3577 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3578 if ( $canonicalUrl !== false ) {
3579 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL );
3580 } else {
3581 if ( $this->isArticleRelated() ) {
3582 // This affects all requests where "setArticleRelated" is true. This is
3583 // typically all requests that show content (query title, curid, oldid, diff),
3584 // and all wikipage actions (edit, delete, purge, info, history etc.).
3585 // It does not apply to File pages and Special pages.
3586 // 'history' and 'info' actions address page metadata rather than the page
3587 // content itself, so they may not be canonicalized to the view page url.
3588 // TODO: this ought to be better encapsulated in the Action class.
3589 $action = Action::getActionName( $this->getContext() );
3590 if ( in_array( $action, [ 'history', 'info' ] ) ) {
3591 $query = "action={$action}";
3592 } else {
3593 $query = '';
3595 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3596 } else {
3597 $reqUrl = $this->getRequest()->getRequestURL();
3598 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL );
3602 if ( $canonicalUrl !== false ) {
3603 $tags[] = Html::element( 'link', [
3604 'rel' => 'canonical',
3605 'href' => $canonicalUrl
3606 ] );
3609 return $tags;
3613 * @return string HTML tag links to be put in the header.
3614 * @deprecated since 1.24 Use OutputPage::headElement or if you have to,
3615 * OutputPage::getHeadLinksArray directly.
3617 public function getHeadLinks() {
3618 wfDeprecated( __METHOD__, '1.24' );
3619 return implode( "\n", $this->getHeadLinksArray() );
3623 * Generate a "<link rel/>" for a feed.
3625 * @param string $type Feed type
3626 * @param string $url URL to the feed
3627 * @param string $text Value of the "title" attribute
3628 * @return string HTML fragment
3630 private function feedLink( $type, $url, $text ) {
3631 return Html::element( 'link', [
3632 'rel' => 'alternate',
3633 'type' => "application/$type+xml",
3634 'title' => $text,
3635 'href' => $url ]
3640 * Add a local or specified stylesheet, with the given media options.
3641 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3643 * @param string $style URL to the file
3644 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3645 * @param string $condition For IE conditional comments, specifying an IE version
3646 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3648 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3649 $options = [];
3650 if ( $media ) {
3651 $options['media'] = $media;
3653 if ( $condition ) {
3654 $options['condition'] = $condition;
3656 if ( $dir ) {
3657 $options['dir'] = $dir;
3659 $this->styles[$style] = $options;
3663 * Adds inline CSS styles
3664 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3666 * @param mixed $style_css Inline CSS
3667 * @param string $flip Set to 'flip' to flip the CSS if needed
3669 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3670 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3671 # If wanted, and the interface is right-to-left, flip the CSS
3672 $style_css = CSSJanus::transform( $style_css, true, false );
3674 $this->mInlineStyles .= Html::inlineStyle( $style_css ) . "\n";
3678 * Build a set of "<link>" elements for the stylesheets specified in the $this->styles array.
3679 * These will be applied to various media & IE conditionals.
3681 * @return string
3683 public function buildCssLinks() {
3684 global $wgContLang;
3686 $this->getSkin()->setupSkinUserCss( $this );
3688 // Add ResourceLoader styles
3689 // Split the styles into these groups
3690 $styles = [
3691 'other' => [],
3692 'user' => [],
3693 'site' => [],
3694 'private' => [],
3695 'noscript' => []
3697 $links = [];
3698 $otherTags = []; // Tags to append after the normal <link> tags
3699 $resourceLoader = $this->getResourceLoader();
3701 $moduleStyles = $this->getModuleStyles();
3703 // Per-site custom styles
3704 $moduleStyles[] = 'site';
3705 $moduleStyles[] = 'noscript';
3706 $moduleStyles[] = 'user.groups';
3708 // Per-user custom styles
3709 if ( $this->getConfig()->get( 'AllowUserCss' ) && $this->getTitle()->isCssSubpage()
3710 && $this->userCanPreview()
3712 // We're on a preview of a CSS subpage
3713 // Exclude this page from the user module in case it's in there (bug 26283)
3714 $link = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_STYLES,
3715 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
3717 $otherTags = array_merge( $otherTags, $link['html'] );
3719 // Load the previewed CSS
3720 // If needed, Janus it first. This is user-supplied CSS, so it's
3721 // assumed to be right for the content language directionality.
3722 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3723 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3724 $previewedCSS = CSSJanus::transform( $previewedCSS, true, false );
3726 $otherTags[] = Html::inlineStyle( $previewedCSS ) . "\n";
3727 } else {
3728 // Load the user styles normally
3729 $moduleStyles[] = 'user';
3732 // Per-user preference styles
3733 $moduleStyles[] = 'user.cssprefs';
3735 foreach ( $moduleStyles as $name ) {
3736 $module = $resourceLoader->getModule( $name );
3737 if ( !$module ) {
3738 continue;
3740 if ( $name === 'site' ) {
3741 // HACK: The site module shouldn't be fragmented with a cache group and
3742 // http request. But in order to ensure its styles are separated and after the
3743 // ResourceLoaderDynamicStyles marker, pretend it is in a group called 'site'.
3744 // The scripts remain ungrouped and rides the bottom queue.
3745 $styles['site'][] = $name;
3746 continue;
3748 $group = $module->getGroup();
3749 // Modules in groups other than the ones needing special treatment
3750 // (see $styles assignment)
3751 // will be placed in the "other" style category.
3752 $styles[isset( $styles[$group] ) ? $group : 'other'][] = $name;
3755 // We want site, private and user styles to override dynamically added
3756 // styles from modules, but we want dynamically added styles to override
3757 // statically added styles from other modules. So the order has to be
3758 // other, dynamic, site, private, user. Add statically added styles for
3759 // other modules
3760 $links[] = $this->makeResourceLoaderLink(
3761 $styles['other'],
3762 ResourceLoaderModule::TYPE_STYLES
3764 // Add normal styles added through addStyle()/addInlineStyle() here
3765 $links[] = implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles;
3766 // Add marker tag to mark the place where the client-side
3767 // loader should inject dynamic styles
3768 // We use a <meta> tag with a made-up name for this because that's valid HTML
3769 $links[] = Html::element(
3770 'meta',
3771 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
3774 // Add site-specific and user-specific styles
3775 // 'private' at present only contains user.options, so put that before 'user'
3776 // Any future private modules will likely have a similar user-specific character
3777 foreach ( [ 'site', 'noscript', 'private', 'user' ] as $group ) {
3778 $links[] = $this->makeResourceLoaderLink( $styles[$group],
3779 ResourceLoaderModule::TYPE_STYLES
3783 // Add stuff in $otherTags (previewed user CSS if applicable)
3784 return self::getHtmlFromLoaderLinks( $links ) . implode( '', $otherTags );
3788 * @return array
3790 public function buildCssLinksArray() {
3791 $links = [];
3793 // Add any extension CSS
3794 foreach ( $this->mExtStyles as $url ) {
3795 $this->addStyle( $url );
3797 $this->mExtStyles = [];
3799 foreach ( $this->styles as $file => $options ) {
3800 $link = $this->styleLink( $file, $options );
3801 if ( $link ) {
3802 $links[$file] = $link;
3805 return $links;
3809 * Generate \<link\> tags for stylesheets
3811 * @param string $style URL to the file
3812 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3813 * @return string HTML fragment
3815 protected function styleLink( $style, array $options ) {
3816 if ( isset( $options['dir'] ) ) {
3817 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3818 return '';
3822 if ( isset( $options['media'] ) ) {
3823 $media = self::transformCssMedia( $options['media'] );
3824 if ( is_null( $media ) ) {
3825 return '';
3827 } else {
3828 $media = 'all';
3831 if ( substr( $style, 0, 1 ) == '/' ||
3832 substr( $style, 0, 5 ) == 'http:' ||
3833 substr( $style, 0, 6 ) == 'https:' ) {
3834 $url = $style;
3835 } else {
3836 $config = $this->getConfig();
3837 $url = $config->get( 'StylePath' ) . '/' . $style . '?' .
3838 $config->get( 'StyleVersion' );
3841 $link = Html::linkedStyle( $url, $media );
3843 if ( isset( $options['condition'] ) ) {
3844 $condition = htmlspecialchars( $options['condition'] );
3845 $link = "<!--[if $condition]>$link<![endif]-->";
3847 return $link;
3851 * Transform path to web-accessible static resource.
3853 * This is used to add a validation hash as query string.
3854 * This aids various behaviors:
3856 * - Put long Cache-Control max-age headers on responses for improved
3857 * cache performance.
3858 * - Get the correct version of a file as expected by the current page.
3859 * - Instantly get the updated version of a file after deployment.
3861 * Avoid using this for urls included in HTML as otherwise clients may get different
3862 * versions of a resource when navigating the site depending on when the page was cached.
3863 * If changes to the url propagate, this is not a problem (e.g. if the url is in
3864 * an external stylesheet).
3866 * @since 1.27
3867 * @param Config $config
3868 * @param string $path Path-absolute URL to file (from document root, must start with "/")
3869 * @return string URL
3871 public static function transformResourcePath( Config $config, $path ) {
3872 global $IP;
3873 $remotePathPrefix = $config->get( 'ResourceBasePath' );
3874 if ( $remotePathPrefix === '' ) {
3875 // The configured base path is required to be empty string for
3876 // wikis in the domain root
3877 $remotePath = '/';
3878 } else {
3879 $remotePath = $remotePathPrefix;
3881 if ( strpos( $path, $remotePath ) !== 0 ) {
3882 // Path is outside wgResourceBasePath, ignore.
3883 return $path;
3885 $path = RelPath\getRelativePath( $path, $remotePath );
3886 return self::transformFilePath( $remotePathPrefix, $IP, $path );
3890 * Utility method for transformResourceFilePath().
3892 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
3894 * @since 1.27
3895 * @param string $remotePath URL path prefix that points to $localPath
3896 * @param string $localPath File directory exposed at $remotePath
3897 * @param string $file Path to target file relative to $localPath
3898 * @return string URL
3900 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
3901 $hash = md5_file( "$localPath/$file" );
3902 if ( $hash === false ) {
3903 wfLogWarning( __METHOD__ . ": Failed to hash $localPath/$file" );
3904 $hash = '';
3906 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
3910 * Transform "media" attribute based on request parameters
3912 * @param string $media Current value of the "media" attribute
3913 * @return string Modified value of the "media" attribute, or null to skip
3914 * this stylesheet
3916 public static function transformCssMedia( $media ) {
3917 global $wgRequest;
3919 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3920 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3922 // Switch in on-screen display for media testing
3923 $switches = [
3924 'printable' => 'print',
3925 'handheld' => 'handheld',
3927 foreach ( $switches as $switch => $targetMedia ) {
3928 if ( $wgRequest->getBool( $switch ) ) {
3929 if ( $media == $targetMedia ) {
3930 $media = '';
3931 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3932 /* This regex will not attempt to understand a comma-separated media_query_list
3934 * Example supported values for $media:
3935 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3936 * Example NOT supported value for $media:
3937 * '3d-glasses, screen, print and resolution > 90dpi'
3939 * If it's a print request, we never want any kind of screen stylesheets
3940 * If it's a handheld request (currently the only other choice with a switch),
3941 * we don't want simple 'screen' but we might want screen queries that
3942 * have a max-width or something, so we'll pass all others on and let the
3943 * client do the query.
3945 if ( $targetMedia == 'print' || $media == 'screen' ) {
3946 return null;
3952 return $media;
3956 * Add a wikitext-formatted message to the output.
3957 * This is equivalent to:
3959 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3961 public function addWikiMsg( /*...*/ ) {
3962 $args = func_get_args();
3963 $name = array_shift( $args );
3964 $this->addWikiMsgArray( $name, $args );
3968 * Add a wikitext-formatted message to the output.
3969 * Like addWikiMsg() except the parameters are taken as an array
3970 * instead of a variable argument list.
3972 * @param string $name
3973 * @param array $args
3975 public function addWikiMsgArray( $name, $args ) {
3976 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3980 * This function takes a number of message/argument specifications, wraps them in
3981 * some overall structure, and then parses the result and adds it to the output.
3983 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3984 * and so on. The subsequent arguments may be either
3985 * 1) strings, in which case they are message names, or
3986 * 2) arrays, in which case, within each array, the first element is the message
3987 * name, and subsequent elements are the parameters to that message.
3989 * Don't use this for messages that are not in the user's interface language.
3991 * For example:
3993 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3995 * Is equivalent to:
3997 * $wgOut->addWikiText( "<div class='error'>\n"
3998 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
4000 * The newline after the opening div is needed in some wikitext. See bug 19226.
4002 * @param string $wrap
4004 public function wrapWikiMsg( $wrap /*, ...*/ ) {
4005 $msgSpecs = func_get_args();
4006 array_shift( $msgSpecs );
4007 $msgSpecs = array_values( $msgSpecs );
4008 $s = $wrap;
4009 foreach ( $msgSpecs as $n => $spec ) {
4010 if ( is_array( $spec ) ) {
4011 $args = $spec;
4012 $name = array_shift( $args );
4013 if ( isset( $args['options'] ) ) {
4014 unset( $args['options'] );
4015 wfDeprecated(
4016 'Adding "options" to ' . __METHOD__ . ' is no longer supported',
4017 '1.20'
4020 } else {
4021 $args = [];
4022 $name = $spec;
4024 $s = str_replace( '$' . ( $n + 1 ), $this->msg( $name, $args )->plain(), $s );
4026 $this->addWikiText( $s );
4030 * Enables/disables TOC, doesn't override __NOTOC__
4031 * @param bool $flag
4032 * @since 1.22
4034 public function enableTOC( $flag = true ) {
4035 $this->mEnableTOC = $flag;
4039 * @return bool
4040 * @since 1.22
4042 public function isTOCEnabled() {
4043 return $this->mEnableTOC;
4047 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
4048 * @param bool $flag
4049 * @since 1.23
4051 public function enableSectionEditLinks( $flag = true ) {
4052 $this->mEnableSectionEditLinks = $flag;
4056 * @return bool
4057 * @since 1.23
4059 public function sectionEditLinksEnabled() {
4060 return $this->mEnableSectionEditLinks;
4064 * Helper function to setup the PHP implementation of OOUI to use in this request.
4066 * @since 1.26
4067 * @param String $skinName The Skin name to determine the correct OOUI theme
4068 * @param String $dir Language direction
4070 public static function setupOOUI( $skinName = '', $dir = 'ltr' ) {
4071 $themes = ExtensionRegistry::getInstance()->getAttribute( 'SkinOOUIThemes' );
4072 // Make keys (skin names) lowercase for case-insensitive matching.
4073 $themes = array_change_key_case( $themes, CASE_LOWER );
4074 $theme = isset( $themes[$skinName] ) ? $themes[$skinName] : 'MediaWiki';
4075 // For example, 'OOUI\MediaWikiTheme'.
4076 $themeClass = "OOUI\\{$theme}Theme";
4077 OOUI\Theme::setSingleton( new $themeClass() );
4078 OOUI\Element::setDefaultDir( $dir );
4082 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
4083 * MediaWiki and this OutputPage instance.
4085 * @since 1.25
4087 public function enableOOUI() {
4088 self::setupOOUI(
4089 strtolower( $this->getSkin()->getSkinName() ),
4090 $this->getLanguage()->getDir()
4092 $this->addModuleStyles( [
4093 'oojs-ui-core.styles',
4094 'oojs-ui.styles.icons',
4095 'oojs-ui.styles.indicators',
4096 'oojs-ui.styles.textures',
4097 'mediawiki.widgets.styles',
4098 ] );
4099 // Used by 'skipFunction' of the four 'oojs-ui.styles.*' modules. Please don't treat this as a
4100 // public API or you'll be severely disappointed when T87871 is fixed and it disappears.
4101 $this->addMeta( 'X-OOUI-PHP', '1' );