When serializing Message, don't try to unstub StubUserLang
[mediawiki.git] / includes / OutputPage.php
blob93ba702238f4f50d56dcfa865e637d5d4fc85ce8
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 = array();
46 /** @var array */
47 protected $mLinktags = array();
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 = array();
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 = array();
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 = array();
126 /** @var array */
127 protected $mCategories = array();
129 /** @var array */
130 protected $mIndicators = array();
132 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
133 private $mLanguageLinks = array();
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 = array();
155 /** @var array */
156 protected $mModules = array();
158 /** @var array */
159 protected $mModuleScripts = array();
161 /** @var array */
162 protected $mModuleStyles = array();
164 /** @var ResourceLoader */
165 protected $mResourceLoader;
167 /** @var array */
168 protected $mJsConfigVars = array();
170 /** @var array */
171 protected $mTemplateIds = array();
173 /** @var array */
174 protected $mImageTimeKeys = array();
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 = array(
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 = array();
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 = array();
265 * Whether jQuery is already handled.
267 protected $mJQueryDone = false;
269 private $mIndexPolicy = 'index';
270 private $mFollowPolicy = 'follow';
271 private $mVaryHeader = array(
272 'Accept-Encoding' => array( '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 = array();
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, array( $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 = array();
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 array();
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 = array(
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', array( &$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, array( '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, array( '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 = array() ) {
1055 if ( $title->isRedirect() ) {
1056 $query['redirect'] = 'no';
1058 return wfMessage( 'backlinksubtitle' )
1059 ->rawParams( Linker::link( $title, null, array(), $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 = array() ) {
1069 $this->addSubtitle( self::buildBacklinkSubtitle( $title, $query ) );
1073 * Clear the subtitles
1075 public function clearSubtitle() {
1076 $this->mSubtitle = array();
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 = array();
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 = array();
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 = array( 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 = array( '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';
1314 $res = $dbr->select( array( 'page', 'page_props' ),
1315 $fields,
1316 $lb->constructSet( 'page', $dbr ),
1317 __METHOD__,
1318 array(),
1319 array( 'page_props' => array( 'LEFT JOIN', array(
1320 'pp_propname' => 'hiddencat',
1321 'pp_page = page_id'
1322 ) ) )
1325 # Add the results to the link cache
1326 $lb->addResultToCache( LinkCache::singleton(), $res );
1328 # Set all the values to 'normal'.
1329 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1331 # Mark hidden categories
1332 foreach ( $res as $row ) {
1333 if ( isset( $row->pp_value ) ) {
1334 $categories[$row->page_title] = 'hidden';
1338 # Add the remaining categories to the skin
1339 if ( Hooks::run(
1340 'OutputPageMakeCategoryLinks',
1341 array( &$this, $categories, &$this->mCategoryLinks ) )
1343 foreach ( $categories as $category => $type ) {
1344 // array keys will cast numeric category names to ints, so cast back to string
1345 $category = (string)$category;
1346 $origcategory = $category;
1347 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
1348 if ( !$title ) {
1349 continue;
1351 $wgContLang->findVariantLink( $category, $title, true );
1352 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1353 continue;
1355 $text = $wgContLang->convertHtml( $title->getText() );
1356 $this->mCategories[] = $title->getText();
1357 $this->mCategoryLinks[$type][] = Linker::link( $title, $text );
1363 * Reset the category links (but not the category list) and add $categories
1365 * @param array $categories Mapping category name => sort key
1367 public function setCategoryLinks( array $categories ) {
1368 $this->mCategoryLinks = array();
1369 $this->addCategoryLinks( $categories );
1373 * Get the list of category links, in a 2-D array with the following format:
1374 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1375 * hidden categories) and $link a HTML fragment with a link to the category
1376 * page
1378 * @return array
1380 public function getCategoryLinks() {
1381 return $this->mCategoryLinks;
1385 * Get the list of category names this page belongs to
1387 * @return array Array of strings
1389 public function getCategories() {
1390 return $this->mCategories;
1394 * Add an array of indicators, with their identifiers as array
1395 * keys and HTML contents as values.
1397 * In case of duplicate keys, existing values are overwritten.
1399 * @param array $indicators
1400 * @since 1.25
1402 public function setIndicators( array $indicators ) {
1403 $this->mIndicators = $indicators + $this->mIndicators;
1404 // Keep ordered by key
1405 ksort( $this->mIndicators );
1409 * Get the indicators associated with this page.
1411 * The array will be internally ordered by item keys.
1413 * @return array Keys: identifiers, values: HTML contents
1414 * @since 1.25
1416 public function getIndicators() {
1417 return $this->mIndicators;
1421 * Adds help link with an icon via page indicators.
1422 * Link target can be overridden by a local message containing a wikilink:
1423 * the message key is: lowercase action or special page name + '-helppage'.
1424 * @param string $to Target MediaWiki.org page title or encoded URL.
1425 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1426 * @since 1.25
1428 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1429 $this->addModuleStyles( 'mediawiki.helplink' );
1430 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1432 if ( $overrideBaseUrl ) {
1433 $helpUrl = $to;
1434 } else {
1435 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1436 $helpUrl = "//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1439 $link = Html::rawElement(
1440 'a',
1441 array(
1442 'href' => $helpUrl,
1443 'target' => '_blank',
1444 'class' => 'mw-helplink',
1446 $text
1449 $this->setIndicators( array( 'mw-helplink' => $link ) );
1453 * Do not allow scripts which can be modified by wiki users to load on this page;
1454 * only allow scripts bundled with, or generated by, the software.
1455 * Site-wide styles are controlled by a config setting, since they can be
1456 * used to create a custom skin/theme, but not user-specific ones.
1458 * @todo this should be given a more accurate name
1460 public function disallowUserJs() {
1461 $this->reduceAllowedModules(
1462 ResourceLoaderModule::TYPE_SCRIPTS,
1463 ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL
1466 // Site-wide styles are controlled by a config setting, see bug 71621
1467 // for background on why. User styles are never allowed.
1468 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1469 $styleOrigin = ResourceLoaderModule::ORIGIN_USER_SITEWIDE;
1470 } else {
1471 $styleOrigin = ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL;
1473 $this->reduceAllowedModules(
1474 ResourceLoaderModule::TYPE_STYLES,
1475 $styleOrigin
1480 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1481 * @see ResourceLoaderModule::$origin
1482 * @param string $type ResourceLoaderModule TYPE_ constant
1483 * @return int ResourceLoaderModule ORIGIN_ class constant
1485 public function getAllowedModules( $type ) {
1486 if ( $type == ResourceLoaderModule::TYPE_COMBINED ) {
1487 return min( array_values( $this->mAllowedModules ) );
1488 } else {
1489 return isset( $this->mAllowedModules[$type] )
1490 ? $this->mAllowedModules[$type]
1491 : ResourceLoaderModule::ORIGIN_ALL;
1496 * Set the highest level of CSS/JS untrustworthiness allowed
1498 * @deprecated since 1.24 Raising level of allowed untrusted content is no longer supported.
1499 * Use reduceAllowedModules() instead
1500 * @param string $type ResourceLoaderModule TYPE_ constant
1501 * @param int $level ResourceLoaderModule class constant
1503 public function setAllowedModules( $type, $level ) {
1504 wfDeprecated( __METHOD__, '1.24' );
1505 $this->reduceAllowedModules( $type, $level );
1509 * Limit the highest level of CSS/JS untrustworthiness allowed.
1511 * If passed the same or a higher level than the current level of untrustworthiness set, the
1512 * level will remain unchanged.
1514 * @param string $type
1515 * @param int $level ResourceLoaderModule class constant
1517 public function reduceAllowedModules( $type, $level ) {
1518 $this->mAllowedModules[$type] = min( $this->getAllowedModules( $type ), $level );
1522 * Prepend $text to the body HTML
1524 * @param string $text HTML
1526 public function prependHTML( $text ) {
1527 $this->mBodytext = $text . $this->mBodytext;
1531 * Append $text to the body HTML
1533 * @param string $text HTML
1535 public function addHTML( $text ) {
1536 $this->mBodytext .= $text;
1540 * Shortcut for adding an Html::element via addHTML.
1542 * @since 1.19
1544 * @param string $element
1545 * @param array $attribs
1546 * @param string $contents
1548 public function addElement( $element, array $attribs = array(), $contents = '' ) {
1549 $this->addHTML( Html::element( $element, $attribs, $contents ) );
1553 * Clear the body HTML
1555 public function clearHTML() {
1556 $this->mBodytext = '';
1560 * Get the body HTML
1562 * @return string HTML
1564 public function getHTML() {
1565 return $this->mBodytext;
1569 * Get/set the ParserOptions object to use for wikitext parsing
1571 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1572 * current ParserOption object
1573 * @return ParserOptions
1575 public function parserOptions( $options = null ) {
1576 if ( !$this->mParserOptions ) {
1577 $this->mParserOptions = ParserOptions::newFromContext( $this->getContext() );
1578 $this->mParserOptions->setEditSection( false );
1580 return wfSetVar( $this->mParserOptions, $options );
1584 * Set the revision ID which will be seen by the wiki text parser
1585 * for things such as embedded {{REVISIONID}} variable use.
1587 * @param int|null $revid An positive integer, or null
1588 * @return mixed Previous value
1590 public function setRevisionId( $revid ) {
1591 $val = is_null( $revid ) ? null : intval( $revid );
1592 return wfSetVar( $this->mRevisionId, $val );
1596 * Get the displayed revision ID
1598 * @return int
1600 public function getRevisionId() {
1601 return $this->mRevisionId;
1605 * Set the timestamp of the revision which will be displayed. This is used
1606 * to avoid a extra DB call in Skin::lastModified().
1608 * @param string|null $timestamp
1609 * @return mixed Previous value
1611 public function setRevisionTimestamp( $timestamp ) {
1612 return wfSetVar( $this->mRevisionTimestamp, $timestamp );
1616 * Get the timestamp of displayed revision.
1617 * This will be null if not filled by setRevisionTimestamp().
1619 * @return string|null
1621 public function getRevisionTimestamp() {
1622 return $this->mRevisionTimestamp;
1626 * Set the displayed file version
1628 * @param File|bool $file
1629 * @return mixed Previous value
1631 public function setFileVersion( $file ) {
1632 $val = null;
1633 if ( $file instanceof File && $file->exists() ) {
1634 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1636 return wfSetVar( $this->mFileVersion, $val, true );
1640 * Get the displayed file version
1642 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1644 public function getFileVersion() {
1645 return $this->mFileVersion;
1649 * Get the templates used on this page
1651 * @return array (namespace => dbKey => revId)
1652 * @since 1.18
1654 public function getTemplateIds() {
1655 return $this->mTemplateIds;
1659 * Get the files used on this page
1661 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1662 * @since 1.18
1664 public function getFileSearchOptions() {
1665 return $this->mImageTimeKeys;
1669 * Convert wikitext to HTML and add it to the buffer
1670 * Default assumes that the current page title will be used.
1672 * @param string $text
1673 * @param bool $linestart Is this the start of a line?
1674 * @param bool $interface Is this text in the user interface language?
1675 * @throws MWException
1677 public function addWikiText( $text, $linestart = true, $interface = true ) {
1678 $title = $this->getTitle(); // Work around E_STRICT
1679 if ( !$title ) {
1680 throw new MWException( 'Title is null' );
1682 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1686 * Add wikitext with a custom Title object
1688 * @param string $text Wikitext
1689 * @param Title $title
1690 * @param bool $linestart Is this the start of a line?
1692 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1693 $this->addWikiTextTitle( $text, $title, $linestart );
1697 * Add wikitext with a custom Title object and tidy enabled.
1699 * @param string $text Wikitext
1700 * @param Title $title
1701 * @param bool $linestart Is this the start of a line?
1703 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1704 $this->addWikiTextTitle( $text, $title, $linestart, true );
1708 * Add wikitext with tidy enabled
1710 * @param string $text Wikitext
1711 * @param bool $linestart Is this the start of a line?
1713 public function addWikiTextTidy( $text, $linestart = true ) {
1714 $title = $this->getTitle();
1715 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1719 * Add wikitext with a custom Title object
1721 * @param string $text Wikitext
1722 * @param Title $title
1723 * @param bool $linestart Is this the start of a line?
1724 * @param bool $tidy Whether to use tidy
1725 * @param bool $interface Whether it is an interface message
1726 * (for example disables conversion)
1728 public function addWikiTextTitle( $text, Title $title, $linestart,
1729 $tidy = false, $interface = false
1731 global $wgParser;
1733 $popts = $this->parserOptions();
1734 $oldTidy = $popts->setTidy( $tidy );
1735 $popts->setInterfaceMessage( (bool)$interface );
1737 $parserOutput = $wgParser->getFreshParser()->parse(
1738 $text, $title, $popts,
1739 $linestart, true, $this->mRevisionId
1742 $popts->setTidy( $oldTidy );
1744 $this->addParserOutput( $parserOutput );
1749 * Add a ParserOutput object, but without Html.
1751 * @deprecated since 1.24, use addParserOutputMetadata() instead.
1752 * @param ParserOutput $parserOutput
1754 public function addParserOutputNoText( $parserOutput ) {
1755 wfDeprecated( __METHOD__, '1.24' );
1756 $this->addParserOutputMetadata( $parserOutput );
1760 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1761 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1762 * and so on.
1764 * @since 1.24
1765 * @param ParserOutput $parserOutput
1767 public function addParserOutputMetadata( $parserOutput ) {
1768 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
1769 $this->addCategoryLinks( $parserOutput->getCategories() );
1770 $this->setIndicators( $parserOutput->getIndicators() );
1771 $this->mNewSectionLink = $parserOutput->getNewSection();
1772 $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
1774 if ( !$parserOutput->isCacheable() ) {
1775 $this->enableClientCache( false );
1777 $this->mNoGallery = $parserOutput->getNoGallery();
1778 $this->mHeadItems = array_merge( $this->mHeadItems, $parserOutput->getHeadItems() );
1779 $this->addModules( $parserOutput->getModules() );
1780 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1781 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1782 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1783 $this->mPreventClickjacking = $this->mPreventClickjacking
1784 || $parserOutput->preventClickjacking();
1786 // Template versioning...
1787 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1788 if ( isset( $this->mTemplateIds[$ns] ) ) {
1789 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
1790 } else {
1791 $this->mTemplateIds[$ns] = $dbks;
1794 // File versioning...
1795 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1796 $this->mImageTimeKeys[$dbk] = $data;
1799 // Hooks registered in the object
1800 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1801 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1802 list( $hookName, $data ) = $hookInfo;
1803 if ( isset( $parserOutputHooks[$hookName] ) ) {
1804 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1808 // enable OOUI if requested via ParserOutput
1809 if ( $parserOutput->getEnableOOUI() ) {
1810 $this->enableOOUI();
1813 // Link flags are ignored for now, but may in the future be
1814 // used to mark individual language links.
1815 $linkFlags = array();
1816 Hooks::run( 'LanguageLinks', array( $this->getTitle(), &$this->mLanguageLinks, &$linkFlags ) );
1817 Hooks::run( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1821 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1822 * ParserOutput object, without any other metadata.
1824 * @since 1.24
1825 * @param ParserOutput $parserOutput
1827 public function addParserOutputContent( $parserOutput ) {
1828 $this->addParserOutputText( $parserOutput );
1830 $this->addModules( $parserOutput->getModules() );
1831 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1832 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1834 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1838 * Add the HTML associated with a ParserOutput object, without any metadata.
1840 * @since 1.24
1841 * @param ParserOutput $parserOutput
1843 public function addParserOutputText( $parserOutput ) {
1844 $text = $parserOutput->getText();
1845 Hooks::run( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1846 $this->addHTML( $text );
1850 * Add everything from a ParserOutput object.
1852 * @param ParserOutput $parserOutput
1854 function addParserOutput( $parserOutput ) {
1855 $this->addParserOutputMetadata( $parserOutput );
1856 $parserOutput->setTOCEnabled( $this->mEnableTOC );
1858 // Touch section edit links only if not previously disabled
1859 if ( $parserOutput->getEditSectionTokens() ) {
1860 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks );
1863 $this->addParserOutputText( $parserOutput );
1867 * Add the output of a QuickTemplate to the output buffer
1869 * @param QuickTemplate $template
1871 public function addTemplate( &$template ) {
1872 $this->addHTML( $template->getHTML() );
1876 * Parse wikitext and return the HTML.
1878 * @param string $text
1879 * @param bool $linestart Is this the start of a line?
1880 * @param bool $interface Use interface language ($wgLang instead of
1881 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1882 * This also disables LanguageConverter.
1883 * @param Language $language Target language object, will override $interface
1884 * @throws MWException
1885 * @return string HTML
1887 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1888 global $wgParser;
1890 if ( is_null( $this->getTitle() ) ) {
1891 throw new MWException( 'Empty $mTitle in ' . __METHOD__ );
1894 $popts = $this->parserOptions();
1895 if ( $interface ) {
1896 $popts->setInterfaceMessage( true );
1898 if ( $language !== null ) {
1899 $oldLang = $popts->setTargetLanguage( $language );
1902 $parserOutput = $wgParser->getFreshParser()->parse(
1903 $text, $this->getTitle(), $popts,
1904 $linestart, true, $this->mRevisionId
1907 if ( $interface ) {
1908 $popts->setInterfaceMessage( false );
1910 if ( $language !== null ) {
1911 $popts->setTargetLanguage( $oldLang );
1914 return $parserOutput->getText();
1918 * Parse wikitext, strip paragraphs, and return the HTML.
1920 * @param string $text
1921 * @param bool $linestart Is this the start of a line?
1922 * @param bool $interface Use interface language ($wgLang instead of
1923 * $wgContLang) while parsing language sensitive magic
1924 * words like GRAMMAR and PLURAL
1925 * @return string HTML
1927 public function parseInline( $text, $linestart = true, $interface = false ) {
1928 $parsed = $this->parse( $text, $linestart, $interface );
1929 return Parser::stripOuterParagraph( $parsed );
1933 * @param $maxage
1934 * @deprecated since 1.27 Use setCdnMaxage() instead
1936 public function setSquidMaxage( $maxage ) {
1937 $this->setCdnMaxage( $maxage );
1941 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1943 * @param int $maxage Maximum cache time on the CDN, in seconds.
1945 public function setCdnMaxage( $maxage ) {
1946 $this->mCdnMaxage = min( $maxage, $this->mCdnMaxageLimit );
1950 * Lower the value of the "s-maxage" part of the "Cache-control" HTTP header
1952 * @param int $maxage Maximum cache time on the CDN, in seconds
1953 * @since 1.27
1955 public function lowerCdnMaxage( $maxage ) {
1956 $this->mCdnMaxageLimit = min( $maxage, $this->mCdnMaxageLimit );
1957 $this->setCdnMaxage( $this->mCdnMaxage );
1961 * Use enableClientCache(false) to force it to send nocache headers
1963 * @param bool $state
1965 * @return bool
1967 public function enableClientCache( $state ) {
1968 return wfSetVar( $this->mEnableClientCache, $state );
1972 * Get the list of cookies that will influence on the cache
1974 * @return array
1976 function getCacheVaryCookies() {
1977 static $cookies;
1978 if ( $cookies === null ) {
1979 $config = $this->getConfig();
1980 $cookies = array_merge(
1981 SessionManager::singleton()->getVaryCookies(),
1982 array(
1983 'forceHTTPS',
1985 $config->get( 'CacheVaryCookies' )
1987 Hooks::run( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1989 return $cookies;
1993 * Check if the request has a cache-varying cookie header
1994 * If it does, it's very important that we don't allow public caching
1996 * @return bool
1998 function haveCacheVaryCookies() {
1999 $request = $this->getRequest();
2000 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2001 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2002 wfDebug( __METHOD__ . ": found $cookieName\n" );
2003 return true;
2006 wfDebug( __METHOD__ . ": no cache-varying cookies found\n" );
2007 return false;
2011 * Add an HTTP header that will influence on the cache
2013 * @param string $header Header name
2014 * @param string[]|null $option Options for the Key header. See
2015 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2016 * for the list of valid options.
2018 public function addVaryHeader( $header, array $option = null ) {
2019 if ( !array_key_exists( $header, $this->mVaryHeader ) ) {
2020 $this->mVaryHeader[$header] = array();
2022 if ( !is_array( $option ) ) {
2023 $option = array();
2025 $this->mVaryHeader[$header] = array_unique( array_merge( $this->mVaryHeader[$header], $option ) );
2029 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2030 * such as Accept-Encoding or Cookie
2032 * @return string
2034 public function getVaryHeader() {
2035 foreach ( SessionManager::singleton()->getVaryHeaders() as $header => $options ) {
2036 $this->addVaryHeader( $header, $options );
2038 return 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader ) );
2042 * Get a complete Key header
2044 * @return string
2046 public function getKeyHeader() {
2047 $cvCookies = $this->getCacheVaryCookies();
2049 $cookiesOption = array();
2050 foreach ( $cvCookies as $cookieName ) {
2051 $cookiesOption[] = 'param=' . $cookieName;
2053 $this->addVaryHeader( 'Cookie', $cookiesOption );
2055 foreach ( SessionManager::singleton()->getVaryHeaders() as $header => $options ) {
2056 $this->addVaryHeader( $header, $options );
2059 $headers = array();
2060 foreach ( $this->mVaryHeader as $header => $option ) {
2061 $newheader = $header;
2062 if ( is_array( $option ) && count( $option ) > 0 ) {
2063 $newheader .= ';' . implode( ';', $option );
2065 $headers[] = $newheader;
2067 $key = 'Key: ' . implode( ',', $headers );
2069 return $key;
2073 * T23672: Add Accept-Language to Vary and Key headers
2074 * if there's no 'variant' parameter existed in GET.
2076 * For example:
2077 * /w/index.php?title=Main_page should always be served; but
2078 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
2080 function addAcceptLanguage() {
2081 $title = $this->getTitle();
2082 if ( !$title instanceof Title ) {
2083 return;
2086 $lang = $title->getPageLanguage();
2087 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2088 $variants = $lang->getVariants();
2089 $aloption = array();
2090 foreach ( $variants as $variant ) {
2091 if ( $variant === $lang->getCode() ) {
2092 continue;
2093 } else {
2094 $aloption[] = 'substr=' . $variant;
2096 // IE and some other browsers use BCP 47 standards in
2097 // their Accept-Language header, like "zh-CN" or "zh-Hant".
2098 // We should handle these too.
2099 $variantBCP47 = wfBCP47( $variant );
2100 if ( $variantBCP47 !== $variant ) {
2101 $aloption[] = 'substr=' . $variantBCP47;
2105 $this->addVaryHeader( 'Accept-Language', $aloption );
2110 * Set a flag which will cause an X-Frame-Options header appropriate for
2111 * edit pages to be sent. The header value is controlled by
2112 * $wgEditPageFrameOptions.
2114 * This is the default for special pages. If you display a CSRF-protected
2115 * form on an ordinary view page, then you need to call this function.
2117 * @param bool $enable
2119 public function preventClickjacking( $enable = true ) {
2120 $this->mPreventClickjacking = $enable;
2124 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2125 * This can be called from pages which do not contain any CSRF-protected
2126 * HTML form.
2128 public function allowClickjacking() {
2129 $this->mPreventClickjacking = false;
2133 * Get the prevent-clickjacking flag
2135 * @since 1.24
2136 * @return bool
2138 public function getPreventClickjacking() {
2139 return $this->mPreventClickjacking;
2143 * Get the X-Frame-Options header value (without the name part), or false
2144 * if there isn't one. This is used by Skin to determine whether to enable
2145 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2147 * @return string
2149 public function getFrameOptions() {
2150 $config = $this->getConfig();
2151 if ( $config->get( 'BreakFrames' ) ) {
2152 return 'DENY';
2153 } elseif ( $this->mPreventClickjacking && $config->get( 'EditPageFrameOptions' ) ) {
2154 return $config->get( 'EditPageFrameOptions' );
2156 return false;
2160 * Send cache control HTTP headers
2162 public function sendCacheControl() {
2163 $response = $this->getRequest()->response();
2164 $config = $this->getConfig();
2165 if ( $config->get( 'UseETag' ) && $this->mETag ) {
2166 $response->header( "ETag: $this->mETag" );
2169 $this->addVaryHeader( 'Cookie' );
2170 $this->addAcceptLanguage();
2172 # don't serve compressed data to clients who can't handle it
2173 # maintain different caches for logged-in users and non-logged in ones
2174 $response->header( $this->getVaryHeader() );
2176 if ( $config->get( 'UseKeyHeader' ) ) {
2177 $response->header( $this->getKeyHeader() );
2180 if ( $this->mEnableClientCache ) {
2181 if (
2182 $config->get( 'UseSquid' ) && !SessionManager::getGlobalSession()->isPersistent() &&
2183 !$this->isPrintable() && $this->mCdnMaxage != 0 && !$this->haveCacheVaryCookies()
2185 if ( $config->get( 'UseESI' ) ) {
2186 # We'll purge the proxy cache explicitly, but require end user agents
2187 # to revalidate against the proxy on each visit.
2188 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2189 wfDebug( __METHOD__ . ": proxy caching with ESI; {$this->mLastModified} **", 'private' );
2190 # start with a shorter timeout for initial testing
2191 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2192 $response->header( 'Surrogate-Control: max-age=' . $config->get( 'SquidMaxage' )
2193 . '+' . $this->mCdnMaxage . ', content="ESI/1.0"' );
2194 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2195 } else {
2196 # We'll purge the proxy cache for anons explicitly, but require end user agents
2197 # to revalidate against the proxy on each visit.
2198 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2199 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2200 wfDebug( __METHOD__ . ": local proxy caching; {$this->mLastModified} **", 'private' );
2201 # start with a shorter timeout for initial testing
2202 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2203 $response->header( 'Cache-Control: s-maxage=' . $this->mCdnMaxage
2204 . ', must-revalidate, max-age=0' );
2206 } else {
2207 # We do want clients to cache if they can, but they *must* check for updates
2208 # on revisiting the page.
2209 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **", 'private' );
2210 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2211 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2213 if ( $this->mLastModified ) {
2214 $response->header( "Last-Modified: {$this->mLastModified}" );
2216 } else {
2217 wfDebug( __METHOD__ . ": no caching **", 'private' );
2219 # In general, the absence of a last modified header should be enough to prevent
2220 # the client from using its cache. We send a few other things just to make sure.
2221 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2222 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2223 $response->header( 'Pragma: no-cache' );
2228 * Finally, all the text has been munged and accumulated into
2229 * the object, let's actually output it:
2231 public function output() {
2232 if ( $this->mDoNothing ) {
2233 return;
2236 $response = $this->getRequest()->response();
2237 $config = $this->getConfig();
2239 if ( $this->mRedirect != '' ) {
2240 # Standards require redirect URLs to be absolute
2241 $this->mRedirect = wfExpandUrl( $this->mRedirect, PROTO_CURRENT );
2243 $redirect = $this->mRedirect;
2244 $code = $this->mRedirectCode;
2246 if ( Hooks::run( "BeforePageRedirect", array( $this, &$redirect, &$code ) ) ) {
2247 if ( $code == '301' || $code == '303' ) {
2248 if ( !$config->get( 'DebugRedirects' ) ) {
2249 $response->statusHeader( $code );
2251 $this->mLastModified = wfTimestamp( TS_RFC2822 );
2253 if ( $config->get( 'VaryOnXFP' ) ) {
2254 $this->addVaryHeader( 'X-Forwarded-Proto' );
2256 $this->sendCacheControl();
2258 $response->header( "Content-Type: text/html; charset=utf-8" );
2259 if ( $config->get( 'DebugRedirects' ) ) {
2260 $url = htmlspecialchars( $redirect );
2261 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2262 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2263 print "</body>\n</html>\n";
2264 } else {
2265 $response->header( 'Location: ' . $redirect );
2269 return;
2270 } elseif ( $this->mStatusCode ) {
2271 $response->statusHeader( $this->mStatusCode );
2274 # Buffer output; final headers may depend on later processing
2275 ob_start();
2277 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2278 $response->header( 'Content-language: ' . $config->get( 'LanguageCode' ) );
2280 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2281 // jQuery etc. can work correctly.
2282 $response->header( 'X-UA-Compatible: IE=Edge' );
2284 // Prevent framing, if requested
2285 $frameOptions = $this->getFrameOptions();
2286 if ( $frameOptions ) {
2287 $response->header( "X-Frame-Options: $frameOptions" );
2290 if ( $this->mArticleBodyOnly ) {
2291 echo $this->mBodytext;
2292 } else {
2293 $sk = $this->getSkin();
2294 // add skin specific modules
2295 $modules = $sk->getDefaultModules();
2297 // Enforce various default modules for all skins
2298 $coreModules = array(
2299 // Keep this list as small as possible
2300 'site',
2301 'mediawiki.page.startup',
2302 'mediawiki.user',
2305 // Support for high-density display images if enabled
2306 if ( $config->get( 'ResponsiveImages' ) ) {
2307 $coreModules[] = 'mediawiki.hidpi';
2310 $this->addModules( $coreModules );
2311 foreach ( $modules as $group ) {
2312 $this->addModules( $group );
2314 MWDebug::addModules( $this );
2316 // Hook that allows last minute changes to the output page, e.g.
2317 // adding of CSS or Javascript by extensions.
2318 Hooks::run( 'BeforePageDisplay', array( &$this, &$sk ) );
2320 $sk->outputPage();
2323 // This hook allows last minute changes to final overall output by modifying output buffer
2324 Hooks::run( 'AfterFinalPageOutput', array( $this ) );
2326 $this->sendCacheControl();
2328 ob_end_flush();
2333 * Actually output something with print.
2335 * @param string $ins The string to output
2336 * @deprecated since 1.22 Use echo yourself.
2338 public function out( $ins ) {
2339 wfDeprecated( __METHOD__, '1.22' );
2340 print $ins;
2344 * Prepare this object to display an error page; disable caching and
2345 * indexing, clear the current text and redirect, set the page's title
2346 * and optionally an custom HTML title (content of the "<title>" tag).
2348 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2349 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2350 * optional, if not passed the "<title>" attribute will be
2351 * based on $pageTitle
2353 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2354 $this->setPageTitle( $pageTitle );
2355 if ( $htmlTitle !== false ) {
2356 $this->setHTMLTitle( $htmlTitle );
2358 $this->setRobotPolicy( 'noindex,nofollow' );
2359 $this->setArticleRelated( false );
2360 $this->enableClientCache( false );
2361 $this->mRedirect = '';
2362 $this->clearSubtitle();
2363 $this->clearHTML();
2367 * Output a standard error page
2369 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2370 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2371 * showErrorPage( 'titlemsg', $messageObject );
2372 * showErrorPage( $titleMessageObject, $messageObject );
2374 * @param string|Message $title Message key (string) for page title, or a Message object
2375 * @param string|Message $msg Message key (string) for page text, or a Message object
2376 * @param array $params Message parameters; ignored if $msg is a Message object
2378 public function showErrorPage( $title, $msg, $params = array() ) {
2379 if ( !$title instanceof Message ) {
2380 $title = $this->msg( $title );
2383 $this->prepareErrorPage( $title );
2385 if ( $msg instanceof Message ) {
2386 if ( $params !== array() ) {
2387 trigger_error( 'Argument ignored: $params. The message parameters argument '
2388 . 'is discarded when the $msg argument is a Message object instead of '
2389 . 'a string.', E_USER_NOTICE );
2391 $this->addHTML( $msg->parseAsBlock() );
2392 } else {
2393 $this->addWikiMsgArray( $msg, $params );
2396 $this->returnToMain();
2400 * Output a standard permission error page
2402 * @param array $errors Error message keys
2403 * @param string $action Action that was denied or null if unknown
2405 public function showPermissionsErrorPage( array $errors, $action = null ) {
2406 // For some action (read, edit, create and upload), display a "login to do this action"
2407 // error if all of the following conditions are met:
2408 // 1. the user is not logged in
2409 // 2. the only error is insufficient permissions (i.e. no block or something else)
2410 // 3. the error can be avoided simply by logging in
2411 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2412 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2413 && ( $errors[0][0] == 'badaccess-groups' || $errors[0][0] == 'badaccess-group0' )
2414 && ( User::groupHasPermission( 'user', $action )
2415 || User::groupHasPermission( 'autoconfirmed', $action ) )
2417 $displayReturnto = null;
2419 # Due to bug 32276, if a user does not have read permissions,
2420 # $this->getTitle() will just give Special:Badtitle, which is
2421 # not especially useful as a returnto parameter. Use the title
2422 # from the request instead, if there was one.
2423 $request = $this->getRequest();
2424 $returnto = Title::newFromText( $request->getVal( 'title', '' ) );
2425 if ( $action == 'edit' ) {
2426 $msg = 'whitelistedittext';
2427 $displayReturnto = $returnto;
2428 } elseif ( $action == 'createpage' || $action == 'createtalk' ) {
2429 $msg = 'nocreatetext';
2430 } elseif ( $action == 'upload' ) {
2431 $msg = 'uploadnologintext';
2432 } else { # Read
2433 $msg = 'loginreqpagetext';
2434 $displayReturnto = Title::newMainPage();
2437 $query = array();
2439 if ( $returnto ) {
2440 $query['returnto'] = $returnto->getPrefixedText();
2442 if ( !$request->wasPosted() ) {
2443 $returntoquery = $request->getValues();
2444 unset( $returntoquery['title'] );
2445 unset( $returntoquery['returnto'] );
2446 unset( $returntoquery['returntoquery'] );
2447 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2450 $loginLink = Linker::linkKnown(
2451 SpecialPage::getTitleFor( 'Userlogin' ),
2452 $this->msg( 'loginreqlink' )->escaped(),
2453 array(),
2454 $query
2457 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2458 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2460 # Don't return to a page the user can't read otherwise
2461 # we'll end up in a pointless loop
2462 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2463 $this->returnToMain( null, $displayReturnto );
2465 } else {
2466 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2467 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2472 * Display an error page indicating that a given version of MediaWiki is
2473 * required to use it
2475 * @param mixed $version The version of MediaWiki needed to use the page
2477 public function versionRequired( $version ) {
2478 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2480 $this->addWikiMsg( 'versionrequiredtext', $version );
2481 $this->returnToMain();
2485 * Format a list of error messages
2487 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2488 * @param string $action Action that was denied or null if unknown
2489 * @return string The wikitext error-messages, formatted into a list.
2491 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2492 if ( $action == null ) {
2493 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2494 } else {
2495 $action_desc = $this->msg( "action-$action" )->plain();
2496 $text = $this->msg(
2497 'permissionserrorstext-withaction',
2498 count( $errors ),
2499 $action_desc
2500 )->plain() . "\n\n";
2503 if ( count( $errors ) > 1 ) {
2504 $text .= '<ul class="permissions-errors">' . "\n";
2506 foreach ( $errors as $error ) {
2507 $text .= '<li>';
2508 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2509 $text .= "</li>\n";
2511 $text .= '</ul>';
2512 } else {
2513 $text .= "<div class=\"permissions-errors\">\n" .
2514 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2515 "\n</div>";
2518 return $text;
2522 * Display a page stating that the Wiki is in read-only mode.
2523 * Should only be called after wfReadOnly() has returned true.
2525 * Historically, this function was used to show the source of the page that the user
2526 * was trying to edit and _also_ permissions error messages. The relevant code was
2527 * moved into EditPage in 1.19 (r102024 / d83c2a431c2a) and removed here in 1.25.
2529 * @deprecated since 1.25; throw the exception directly
2530 * @throws ReadOnlyError
2532 public function readOnlyPage() {
2533 if ( func_num_args() > 0 ) {
2534 throw new MWException( __METHOD__ . ' no longer accepts arguments since 1.25.' );
2537 throw new ReadOnlyError;
2541 * Turn off regular page output and return an error response
2542 * for when rate limiting has triggered.
2544 * @deprecated since 1.25; throw the exception directly
2546 public function rateLimited() {
2547 wfDeprecated( __METHOD__, '1.25' );
2548 throw new ThrottledError;
2552 * Show a warning about slave lag
2554 * If the lag is higher than $wgSlaveLagCritical seconds,
2555 * then the warning is a bit more obvious. If the lag is
2556 * lower than $wgSlaveLagWarning, then no warning is shown.
2558 * @param int $lag Slave lag
2560 public function showLagWarning( $lag ) {
2561 $config = $this->getConfig();
2562 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2563 $message = $lag < $config->get( 'SlaveLagCritical' )
2564 ? 'lag-warn-normal'
2565 : 'lag-warn-high';
2566 $wrap = Html::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2567 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2571 public function showFatalError( $message ) {
2572 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2574 $this->addHTML( $message );
2577 public function showUnexpectedValueError( $name, $val ) {
2578 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2581 public function showFileCopyError( $old, $new ) {
2582 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2585 public function showFileRenameError( $old, $new ) {
2586 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2589 public function showFileDeleteError( $name ) {
2590 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2593 public function showFileNotFoundError( $name ) {
2594 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2598 * Add a "return to" link pointing to a specified title
2600 * @param Title $title Title to link
2601 * @param array $query Query string parameters
2602 * @param string $text Text of the link (input is not escaped)
2603 * @param array $options Options array to pass to Linker
2605 public function addReturnTo( $title, array $query = array(), $text = null, $options = array() ) {
2606 $link = $this->msg( 'returnto' )->rawParams(
2607 Linker::link( $title, $text, array(), $query, $options ) )->escaped();
2608 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2612 * Add a "return to" link pointing to a specified title,
2613 * or the title indicated in the request, or else the main page
2615 * @param mixed $unused
2616 * @param Title|string $returnto Title or String to return to
2617 * @param string $returntoquery Query string for the return to link
2619 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2620 if ( $returnto == null ) {
2621 $returnto = $this->getRequest()->getText( 'returnto' );
2624 if ( $returntoquery == null ) {
2625 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2628 if ( $returnto === '' ) {
2629 $returnto = Title::newMainPage();
2632 if ( is_object( $returnto ) ) {
2633 $titleObj = $returnto;
2634 } else {
2635 $titleObj = Title::newFromText( $returnto );
2637 if ( !is_object( $titleObj ) ) {
2638 $titleObj = Title::newMainPage();
2641 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2645 * @param Skin $sk The given Skin
2646 * @param bool $includeStyle Unused
2647 * @return string The doctype, opening "<html>", and head element.
2649 public function headElement( Skin $sk, $includeStyle = true ) {
2650 global $wgContLang;
2652 $userdir = $this->getLanguage()->getDir();
2653 $sitedir = $wgContLang->getDir();
2655 $ret = Html::htmlHeader( $sk->getHtmlElementAttributes() );
2657 if ( $this->getHTMLTitle() == '' ) {
2658 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2661 $openHead = Html::openElement( 'head' );
2662 if ( $openHead ) {
2663 # Don't bother with the newline if $head == ''
2664 $ret .= "$openHead\n";
2667 if ( !Html::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2668 // Add <meta charset="UTF-8">
2669 // This should be before <title> since it defines the charset used by
2670 // text including the text inside <title>.
2671 // The spec recommends defining XHTML5's charset using the XML declaration
2672 // instead of meta.
2673 // Our XML declaration is output by Html::htmlHeader.
2674 // http://www.whatwg.org/html/semantics.html#attr-meta-http-equiv-content-type
2675 // http://www.whatwg.org/html/semantics.html#charset
2676 $ret .= Html::element( 'meta', array( 'charset' => 'UTF-8' ) ) . "\n";
2679 $ret .= Html::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2680 $ret .= $this->getInlineHeadScripts() . "\n";
2681 $ret .= $this->buildCssLinks() . "\n";
2682 $ret .= $this->getExternalHeadScripts() . "\n";
2684 foreach ( $this->getHeadLinksArray() as $item ) {
2685 $ret .= $item . "\n";
2688 foreach ( $this->mHeadItems as $item ) {
2689 $ret .= $item . "\n";
2692 $closeHead = Html::closeElement( 'head' );
2693 if ( $closeHead ) {
2694 $ret .= "$closeHead\n";
2697 $bodyClasses = array();
2698 $bodyClasses[] = 'mediawiki';
2700 # Classes for LTR/RTL directionality support
2701 $bodyClasses[] = $userdir;
2702 $bodyClasses[] = "sitedir-$sitedir";
2704 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2705 # A <body> class is probably not the best way to do this . . .
2706 $bodyClasses[] = 'capitalize-all-nouns';
2709 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2710 $bodyClasses[] = 'skin-' . Sanitizer::escapeClass( $sk->getSkinName() );
2711 $bodyClasses[] =
2712 'action-' . Sanitizer::escapeClass( Action::getActionName( $this->getContext() ) );
2714 $bodyAttrs = array();
2715 // While the implode() is not strictly needed, it's used for backwards compatibility
2716 // (this used to be built as a string and hooks likely still expect that).
2717 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2719 // Allow skins and extensions to add body attributes they need
2720 $sk->addToBodyAttributes( $this, $bodyAttrs );
2721 Hooks::run( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2723 $ret .= Html::openElement( 'body', $bodyAttrs ) . "\n";
2725 return $ret;
2729 * Get a ResourceLoader object associated with this OutputPage
2731 * @return ResourceLoader
2733 public function getResourceLoader() {
2734 if ( is_null( $this->mResourceLoader ) ) {
2735 $this->mResourceLoader = new ResourceLoader(
2736 $this->getConfig(),
2737 LoggerFactory::getInstance( 'resourceloader' )
2740 return $this->mResourceLoader;
2744 * Construct neccecary html and loader preset states to load modules on a page.
2746 * Use getHtmlFromLoaderLinks() to convert this array to HTML.
2748 * @param array|string $modules One or more module names
2749 * @param string $only ResourceLoaderModule TYPE_ class constant
2750 * @param array $extraQuery [optional] Array with extra query parameters for the request
2751 * @return array A list of HTML strings and array of client loader preset states
2753 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = array() ) {
2754 $modules = (array)$modules;
2756 $links = array(
2757 // List of html strings
2758 'html' => array(),
2759 // Associative array of module names and their states
2760 'states' => array(),
2763 if ( !count( $modules ) ) {
2764 return $links;
2767 if ( count( $modules ) > 1 ) {
2768 // Remove duplicate module requests
2769 $modules = array_unique( $modules );
2770 // Sort module names so requests are more uniform
2771 sort( $modules );
2773 if ( ResourceLoader::inDebugMode() ) {
2774 // Recursively call us for every item
2775 foreach ( $modules as $name ) {
2776 $link = $this->makeResourceLoaderLink( $name, $only, $extraQuery );
2777 $links['html'] = array_merge( $links['html'], $link['html'] );
2778 $links['states'] += $link['states'];
2780 return $links;
2784 if ( !is_null( $this->mTarget ) ) {
2785 $extraQuery['target'] = $this->mTarget;
2788 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
2789 $sortedModules = array();
2790 $resourceLoader = $this->getResourceLoader();
2791 foreach ( $modules as $name ) {
2792 $module = $resourceLoader->getModule( $name );
2793 # Check that we're allowed to include this module on this page
2794 if ( !$module
2795 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_SCRIPTS )
2796 && $only == ResourceLoaderModule::TYPE_SCRIPTS )
2797 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_STYLES )
2798 && $only == ResourceLoaderModule::TYPE_STYLES )
2799 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_COMBINED )
2800 && $only == ResourceLoaderModule::TYPE_COMBINED )
2801 || ( $this->mTarget && !in_array( $this->mTarget, $module->getTargets() ) )
2803 continue;
2806 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
2809 foreach ( $sortedModules as $source => $groups ) {
2810 foreach ( $groups as $group => $grpModules ) {
2811 // Special handling for user-specific groups
2812 $user = null;
2813 if ( ( $group === 'user' || $group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2814 $user = $this->getUser()->getName();
2817 // Create a fake request based on the one we are about to make so modules return
2818 // correct timestamp and emptiness data
2819 $query = ResourceLoader::makeLoaderQuery(
2820 array(), // modules; not determined yet
2821 $this->getLanguage()->getCode(),
2822 $this->getSkin()->getSkinName(),
2823 $user,
2824 null, // version; not determined yet
2825 ResourceLoader::inDebugMode(),
2826 $only === ResourceLoaderModule::TYPE_COMBINED ? null : $only,
2827 $this->isPrintable(),
2828 $this->getRequest()->getBool( 'handheld' ),
2829 $extraQuery
2831 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2833 // Extract modules that know they're empty and see if we have one or more
2834 // raw modules
2835 $isRaw = false;
2836 foreach ( $grpModules as $key => $module ) {
2837 // Inline empty modules: since they're empty, just mark them as 'ready' (bug 46857)
2838 // If we're only getting the styles, we don't need to do anything for empty modules.
2839 if ( $module->isKnownEmpty( $context ) ) {
2840 unset( $grpModules[$key] );
2841 if ( $only !== ResourceLoaderModule::TYPE_STYLES ) {
2842 $links['states'][$key] = 'ready';
2846 $isRaw |= $module->isRaw();
2849 // If there are no non-empty modules, skip this group
2850 if ( count( $grpModules ) === 0 ) {
2851 continue;
2854 // Inline private modules. These can't be loaded through load.php for security
2855 // reasons, see bug 34907. Note that these modules should be loaded from
2856 // getExternalHeadScripts() before the first loader call. Otherwise other modules can't
2857 // properly use them as dependencies (bug 30914)
2858 if ( $group === 'private' ) {
2859 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
2860 $links['html'][] = Html::inlineStyle(
2861 $resourceLoader->makeModuleResponse( $context, $grpModules )
2863 } else {
2864 $links['html'][] = ResourceLoader::makeInlineScript(
2865 $resourceLoader->makeModuleResponse( $context, $grpModules )
2868 continue;
2871 // Special handling for the user group; because users might change their stuff
2872 // on-wiki like user pages, or user preferences; we need to find the highest
2873 // timestamp of these user-changeable modules so we can ensure cache misses on change
2874 // This should NOT be done for the site group (bug 27564) because anons get that too
2875 // and we shouldn't be putting timestamps in CDN-cached HTML
2876 $version = null;
2877 if ( $group === 'user' ) {
2878 $query['version'] = $resourceLoader->getCombinedVersion( $context, array_keys( $grpModules ) );
2881 $query['modules'] = ResourceLoader::makePackedModulesString( array_keys( $grpModules ) );
2882 $moduleContext = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2883 $url = $resourceLoader->createLoaderURL( $source, $moduleContext, $extraQuery );
2885 // Automatically select style/script elements
2886 if ( $only === ResourceLoaderModule::TYPE_STYLES ) {
2887 $link = Html::linkedStyle( $url );
2888 } else {
2889 if ( $context->getRaw() || $isRaw ) {
2890 // Startup module can't load itself, needs to use <script> instead of mw.loader.load
2891 $link = Html::element( 'script', array(
2892 // In SpecialJavaScriptTest, QUnit must load synchronous
2893 'async' => !isset( $extraQuery['sync'] ),
2894 'src' => $url
2895 ) );
2896 } else {
2897 $link = ResourceLoader::makeInlineScript(
2898 Xml::encodeJsCall( 'mw.loader.load', array( $url ) )
2902 // For modules requested directly in the html via <script> or mw.loader.load
2903 // tell mw.loader they are being loading to prevent duplicate requests.
2904 foreach ( $grpModules as $key => $module ) {
2905 // Don't output state=loading for the startup module.
2906 if ( $key !== 'startup' ) {
2907 $links['states'][$key] = 'loading';
2912 if ( $group == 'noscript' ) {
2913 $links['html'][] = Html::rawElement( 'noscript', array(), $link );
2914 } else {
2915 $links['html'][] = $link;
2920 return $links;
2924 * Build html output from an array of links from makeResourceLoaderLink.
2925 * @param array $links
2926 * @return string HTML
2928 protected static function getHtmlFromLoaderLinks( array $links ) {
2929 $html = array();
2930 $states = array();
2931 foreach ( $links as $link ) {
2932 if ( !is_array( $link ) ) {
2933 $html[] = $link;
2934 } else {
2935 $html = array_merge( $html, $link['html'] );
2936 $states += $link['states'];
2939 // Filter out empty values
2940 $html = array_filter( $html, 'strlen' );
2942 if ( count( $states ) ) {
2943 array_unshift( $html, ResourceLoader::makeInlineScript(
2944 ResourceLoader::makeLoaderStateScript( $states )
2945 ) );
2948 return WrappedString::join( "\n", $html );
2952 * JS stuff to put in the "<head>". This is the startup module, config
2953 * vars and modules marked with position 'top'
2955 * @return string HTML fragment
2957 function getHeadScripts() {
2958 return $this->getInlineHeadScripts() . "\n" . $this->getExternalHeadScripts();
2962 * <script src="..."> tags for "<head>". This is the startup module
2963 * and other modules marked with position 'top'.
2965 * @return string HTML fragment
2967 function getExternalHeadScripts() {
2968 $links = array();
2970 // Startup - this provides the client with the module
2971 // manifest and loads jquery and mediawiki base modules
2972 $links[] = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule::TYPE_SCRIPTS );
2974 return self::getHtmlFromLoaderLinks( $links );
2978 * <script>...</script> tags to put in "<head>".
2980 * @return string HTML fragment
2982 function getInlineHeadScripts() {
2983 $links = array();
2985 // Client profile classes for <html>. Allows for easy hiding/showing of UI components.
2986 // Must be done synchronously on every page to avoid flashes of wrong content.
2987 // Note: This class distinguishes MediaWiki-supported JavaScript from the rest.
2988 // The "rest" includes browsers that support JavaScript but not supported by our runtime.
2989 // For the performance benefit of the majority, this is added unconditionally here and is
2990 // then fixed up by the startup module for unsupported browsers.
2991 $links[] = Html::inlineScript(
2992 'document.documentElement.className = document.documentElement.className'
2993 . '.replace( /(^|\s)client-nojs(\s|$)/, "$1client-js$2" );'
2996 // Load config before anything else
2997 $links[] = ResourceLoader::makeInlineScript(
2998 ResourceLoader::makeConfigSetScript( $this->getJSVars() )
3001 // Load embeddable private modules before any loader links
3002 // This needs to be TYPE_COMBINED so these modules are properly wrapped
3003 // in mw.loader.implement() calls and deferred until mw.user is available
3004 $embedScripts = array( 'user.options' );
3005 $links[] = $this->makeResourceLoaderLink(
3006 $embedScripts,
3007 ResourceLoaderModule::TYPE_COMBINED
3009 // Separate user.tokens as otherwise caching will be allowed (T84960)
3010 $links[] = $this->makeResourceLoaderLink(
3011 'user.tokens',
3012 ResourceLoaderModule::TYPE_COMBINED
3015 // Modules requests - let the client calculate dependencies and batch requests as it likes
3016 // Only load modules that have marked themselves for loading at the top
3017 $modules = $this->getModules( true, 'top' );
3018 if ( $modules ) {
3019 $links[] = ResourceLoader::makeInlineScript(
3020 Xml::encodeJsCall( 'mw.loader.load', array( $modules ) )
3024 // "Scripts only" modules marked for top inclusion
3025 $links[] = $this->makeResourceLoaderLink(
3026 $this->getModuleScripts( true, 'top' ),
3027 ResourceLoaderModule::TYPE_SCRIPTS
3030 return self::getHtmlFromLoaderLinks( $links );
3034 * JS stuff to put at the 'bottom', which goes at the bottom of the `<body>`.
3035 * These are modules marked with position 'bottom', legacy scripts ($this->mScripts),
3036 * site JS, and user JS.
3038 * @param bool $unused Previously used to let this method change its output based
3039 * on whether it was called by getExternalHeadScripts() or getBottomScripts().
3040 * @return string
3042 function getScriptsForBottomQueue( $unused = null ) {
3043 // Scripts "only" requests marked for bottom inclusion
3044 // If we're in the <head>, use load() calls rather than <script src="..."> tags
3045 $links = array();
3047 $links[] = $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
3048 ResourceLoaderModule::TYPE_SCRIPTS
3051 // Modules requests - let the client calculate dependencies and batch requests as it likes
3052 // Only load modules that have marked themselves for loading at the bottom
3053 $modules = $this->getModules( true, 'bottom' );
3054 if ( $modules ) {
3055 $links[] = ResourceLoader::makeInlineScript(
3056 Xml::encodeJsCall( 'mw.loader.load', array( $modules ) )
3060 // Legacy Scripts
3061 $links[] = $this->mScripts;
3063 // Add user JS if enabled
3064 // This must use TYPE_COMBINED instead of only=scripts so that its request is handled by
3065 // mw.loader.implement() which ensures that execution is scheduled after the "site" module.
3066 if ( $this->getConfig()->get( 'AllowUserJs' )
3067 && $this->getUser()->isLoggedIn()
3068 && $this->getTitle()
3069 && $this->getTitle()->isJsSubpage()
3070 && $this->userCanPreview()
3072 // We're on a preview of a JS subpage. Exclude this page from the user module (T28283)
3073 // and include the draft contents as a raw script instead.
3074 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_COMBINED,
3075 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3077 // Load the previewed JS
3078 $links[] = ResourceLoader::makeInlineScript(
3079 Xml::encodeJsCall( 'mw.loader.using', array(
3080 array( 'user', 'site' ),
3081 new XmlJsCode(
3082 'function () {'
3083 . Xml::encodeJsCall( '$.globalEval', array(
3084 $this->getRequest()->getText( 'wpTextbox1' )
3086 . '}'
3091 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
3092 // asynchronously and may arrive *after* the inline script here. So the previewed code
3093 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js.
3094 // Similarly, when previewing ./common.js and the user module does arrive first,
3095 // it will arrive without common.js and the inline script runs after.
3096 // Thus running common after the excluded subpage.
3097 } else {
3098 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
3099 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_COMBINED );
3102 // Group JS is only enabled if site JS is enabled.
3103 $links[] = $this->makeResourceLoaderLink(
3104 'user.groups',
3105 ResourceLoaderModule::TYPE_COMBINED
3108 return self::getHtmlFromLoaderLinks( $links );
3112 * JS stuff to put at the bottom of the "<body>"
3113 * @return string
3115 function getBottomScripts() {
3116 return $this->getScriptsForBottomQueue();
3120 * Get the javascript config vars to include on this page
3122 * @return array Array of javascript config vars
3123 * @since 1.23
3125 public function getJsConfigVars() {
3126 return $this->mJsConfigVars;
3130 * Add one or more variables to be set in mw.config in JavaScript
3132 * @param string|array $keys Key or array of key/value pairs
3133 * @param mixed $value [optional] Value of the configuration variable
3135 public function addJsConfigVars( $keys, $value = null ) {
3136 if ( is_array( $keys ) ) {
3137 foreach ( $keys as $key => $value ) {
3138 $this->mJsConfigVars[$key] = $value;
3140 return;
3143 $this->mJsConfigVars[$keys] = $value;
3147 * Get an array containing the variables to be set in mw.config in JavaScript.
3149 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3150 * - in other words, page-independent/site-wide variables (without state).
3151 * You will only be adding bloat to the html page and causing page caches to
3152 * have to be purged on configuration changes.
3153 * @return array
3155 public function getJSVars() {
3156 global $wgContLang;
3158 $curRevisionId = 0;
3159 $articleId = 0;
3160 $canonicalSpecialPageName = false; # bug 21115
3162 $title = $this->getTitle();
3163 $ns = $title->getNamespace();
3164 $canonicalNamespace = MWNamespace::exists( $ns )
3165 ? MWNamespace::getCanonicalName( $ns )
3166 : $title->getNsText();
3168 $sk = $this->getSkin();
3169 // Get the relevant title so that AJAX features can use the correct page name
3170 // when making API requests from certain special pages (bug 34972).
3171 $relevantTitle = $sk->getRelevantTitle();
3172 $relevantUser = $sk->getRelevantUser();
3174 if ( $ns == NS_SPECIAL ) {
3175 list( $canonicalSpecialPageName, /*...*/ ) =
3176 SpecialPageFactory::resolveAlias( $title->getDBkey() );
3177 } elseif ( $this->canUseWikiPage() ) {
3178 $wikiPage = $this->getWikiPage();
3179 $curRevisionId = $wikiPage->getLatest();
3180 $articleId = $wikiPage->getId();
3183 $lang = $title->getPageLanguage();
3185 // Pre-process information
3186 $separatorTransTable = $lang->separatorTransformTable();
3187 $separatorTransTable = $separatorTransTable ? $separatorTransTable : array();
3188 $compactSeparatorTransTable = array(
3189 implode( "\t", array_keys( $separatorTransTable ) ),
3190 implode( "\t", $separatorTransTable ),
3192 $digitTransTable = $lang->digitTransformTable();
3193 $digitTransTable = $digitTransTable ? $digitTransTable : array();
3194 $compactDigitTransTable = array(
3195 implode( "\t", array_keys( $digitTransTable ) ),
3196 implode( "\t", $digitTransTable ),
3199 $user = $this->getUser();
3201 $vars = array(
3202 'wgCanonicalNamespace' => $canonicalNamespace,
3203 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3204 'wgNamespaceNumber' => $title->getNamespace(),
3205 'wgPageName' => $title->getPrefixedDBkey(),
3206 'wgTitle' => $title->getText(),
3207 'wgCurRevisionId' => $curRevisionId,
3208 'wgRevisionId' => (int)$this->getRevisionId(),
3209 'wgArticleId' => $articleId,
3210 'wgIsArticle' => $this->isArticle(),
3211 'wgIsRedirect' => $title->isRedirect(),
3212 'wgAction' => Action::getActionName( $this->getContext() ),
3213 'wgUserName' => $user->isAnon() ? null : $user->getName(),
3214 'wgUserGroups' => $user->getEffectiveGroups(),
3215 'wgCategories' => $this->getCategories(),
3216 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3217 'wgPageContentLanguage' => $lang->getCode(),
3218 'wgPageContentModel' => $title->getContentModel(),
3219 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3220 'wgDigitTransformTable' => $compactDigitTransTable,
3221 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3222 'wgMonthNames' => $lang->getMonthNamesArray(),
3223 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3224 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3225 'wgRelevantArticleId' => $relevantTitle->getArticleId(),
3228 if ( $user->isLoggedIn() ) {
3229 $vars['wgUserId'] = $user->getId();
3230 $vars['wgUserEditCount'] = $user->getEditCount();
3231 $userReg = wfTimestampOrNull( TS_UNIX, $user->getRegistration() );
3232 $vars['wgUserRegistration'] = $userReg !== null ? ( $userReg * 1000 ) : null;
3233 // Get the revision ID of the oldest new message on the user's talk
3234 // page. This can be used for constructing new message alerts on
3235 // the client side.
3236 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3239 if ( $wgContLang->hasVariants() ) {
3240 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3242 // Same test as SkinTemplate
3243 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3244 && ( $title->exists() || $title->quickUserCan( 'create', $user ) );
3246 foreach ( $title->getRestrictionTypes() as $type ) {
3247 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3250 if ( $title->isMainPage() ) {
3251 $vars['wgIsMainPage'] = true;
3254 if ( $this->mRedirectedFrom ) {
3255 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom->getPrefixedDBkey();
3258 if ( $relevantUser ) {
3259 $vars['wgRelevantUserName'] = $relevantUser->getName();
3262 // Allow extensions to add their custom variables to the mw.config map.
3263 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3264 // page-dependant but site-wide (without state).
3265 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3266 Hooks::run( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
3268 // Merge in variables from addJsConfigVars last
3269 return array_merge( $vars, $this->getJsConfigVars() );
3273 * To make it harder for someone to slip a user a fake
3274 * user-JavaScript or user-CSS preview, a random token
3275 * is associated with the login session. If it's not
3276 * passed back with the preview request, we won't render
3277 * the code.
3279 * @return bool
3281 public function userCanPreview() {
3282 $request = $this->getRequest();
3283 if (
3284 $request->getVal( 'action' ) !== 'submit' ||
3285 !$request->getCheck( 'wpPreview' ) ||
3286 !$request->wasPosted()
3288 return false;
3291 $user = $this->getUser();
3292 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3293 return false;
3296 $title = $this->getTitle();
3297 if ( !$title->isJsSubpage() && !$title->isCssSubpage() ) {
3298 return false;
3300 if ( !$title->isSubpageOf( $user->getUserPage() ) ) {
3301 // Don't execute another user's CSS or JS on preview (T85855)
3302 return false;
3305 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3306 if ( count( $errors ) !== 0 ) {
3307 return false;
3310 return true;
3314 * @return array Array in format "link name or number => 'link html'".
3316 public function getHeadLinksArray() {
3317 global $wgVersion;
3319 $tags = array();
3320 $config = $this->getConfig();
3322 $canonicalUrl = $this->mCanonicalUrl;
3324 $tags['meta-generator'] = Html::element( 'meta', array(
3325 'name' => 'generator',
3326 'content' => "MediaWiki $wgVersion",
3327 ) );
3329 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3330 $tags['meta-referrer'] = Html::element( 'meta', array(
3331 'name' => 'referrer',
3332 'content' => $config->get( 'ReferrerPolicy' )
3333 ) );
3336 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3337 if ( $p !== 'index,follow' ) {
3338 // http://www.robotstxt.org/wc/meta-user.html
3339 // Only show if it's different from the default robots policy
3340 $tags['meta-robots'] = Html::element( 'meta', array(
3341 'name' => 'robots',
3342 'content' => $p,
3343 ) );
3346 foreach ( $this->mMetatags as $tag ) {
3347 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3348 $a = 'http-equiv';
3349 $tag[0] = substr( $tag[0], 5 );
3350 } else {
3351 $a = 'name';
3353 $tagName = "meta-{$tag[0]}";
3354 if ( isset( $tags[$tagName] ) ) {
3355 $tagName .= $tag[1];
3357 $tags[$tagName] = Html::element( 'meta',
3358 array(
3359 $a => $tag[0],
3360 'content' => $tag[1]
3365 foreach ( $this->mLinktags as $tag ) {
3366 $tags[] = Html::element( 'link', $tag );
3369 # Universal edit button
3370 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3371 $user = $this->getUser();
3372 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3373 && ( $this->getTitle()->exists() ||
3374 $this->getTitle()->quickUserCan( 'create', $user ) )
3376 // Original UniversalEditButton
3377 $msg = $this->msg( 'edit' )->text();
3378 $tags['universal-edit-button'] = Html::element( 'link', array(
3379 'rel' => 'alternate',
3380 'type' => 'application/x-wiki',
3381 'title' => $msg,
3382 'href' => $this->getTitle()->getEditURL(),
3383 ) );
3384 // Alternate edit link
3385 $tags['alternative-edit'] = Html::element( 'link', array(
3386 'rel' => 'edit',
3387 'title' => $msg,
3388 'href' => $this->getTitle()->getEditURL(),
3389 ) );
3393 # Generally the order of the favicon and apple-touch-icon links
3394 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3395 # uses whichever one appears later in the HTML source. Make sure
3396 # apple-touch-icon is specified first to avoid this.
3397 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3398 $tags['apple-touch-icon'] = Html::element( 'link', array(
3399 'rel' => 'apple-touch-icon',
3400 'href' => $config->get( 'AppleTouchIcon' )
3401 ) );
3404 if ( $config->get( 'Favicon' ) !== false ) {
3405 $tags['favicon'] = Html::element( 'link', array(
3406 'rel' => 'shortcut icon',
3407 'href' => $config->get( 'Favicon' )
3408 ) );
3411 # OpenSearch description link
3412 $tags['opensearch'] = Html::element( 'link', array(
3413 'rel' => 'search',
3414 'type' => 'application/opensearchdescription+xml',
3415 'href' => wfScript( 'opensearch_desc' ),
3416 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3417 ) );
3419 if ( $config->get( 'EnableAPI' ) ) {
3420 # Real Simple Discovery link, provides auto-discovery information
3421 # for the MediaWiki API (and potentially additional custom API
3422 # support such as WordPress or Twitter-compatible APIs for a
3423 # blogging extension, etc)
3424 $tags['rsd'] = Html::element( 'link', array(
3425 'rel' => 'EditURI',
3426 'type' => 'application/rsd+xml',
3427 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3428 // Whether RSD accepts relative or protocol-relative URLs is completely
3429 // undocumented, though.
3430 'href' => wfExpandUrl( wfAppendQuery(
3431 wfScript( 'api' ),
3432 array( 'action' => 'rsd' ) ),
3433 PROTO_RELATIVE
3435 ) );
3438 # Language variants
3439 if ( !$config->get( 'DisableLangConversion' ) ) {
3440 $lang = $this->getTitle()->getPageLanguage();
3441 if ( $lang->hasVariants() ) {
3442 $variants = $lang->getVariants();
3443 foreach ( $variants as $variant ) {
3444 $tags["variant-$variant"] = Html::element( 'link', array(
3445 'rel' => 'alternate',
3446 'hreflang' => wfBCP47( $variant ),
3447 'href' => $this->getTitle()->getLocalURL(
3448 array( 'variant' => $variant ) )
3452 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3453 $tags["variant-x-default"] = Html::element( 'link', array(
3454 'rel' => 'alternate',
3455 'hreflang' => 'x-default',
3456 'href' => $this->getTitle()->getLocalURL() ) );
3460 # Copyright
3461 if ( $this->copyrightUrl !== null ) {
3462 $copyright = $this->copyrightUrl;
3463 } else {
3464 $copyright = '';
3465 if ( $config->get( 'RightsPage' ) ) {
3466 $copy = Title::newFromText( $config->get( 'RightsPage' ) );
3468 if ( $copy ) {
3469 $copyright = $copy->getLocalURL();
3473 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3474 $copyright = $config->get( 'RightsUrl' );
3478 if ( $copyright ) {
3479 $tags['copyright'] = Html::element( 'link', array(
3480 'rel' => 'copyright',
3481 'href' => $copyright )
3485 # Feeds
3486 if ( $config->get( 'Feed' ) ) {
3487 $feedLinks = array();
3489 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3490 # Use the page name for the title. In principle, this could
3491 # lead to issues with having the same name for different feeds
3492 # corresponding to the same page, but we can't avoid that at
3493 # this low a level.
3495 $feedLinks[] = $this->feedLink(
3496 $format,
3497 $link,
3498 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3499 $this->msg(
3500 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3501 )->text()
3505 # Recent changes feed should appear on every page (except recentchanges,
3506 # that would be redundant). Put it after the per-page feed to avoid
3507 # changing existing behavior. It's still available, probably via a
3508 # menu in your browser. Some sites might have a different feed they'd
3509 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3510 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3511 # If so, use it instead.
3512 $sitename = $config->get( 'Sitename' );
3513 if ( $config->get( 'OverrideSiteFeed' ) ) {
3514 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3515 // Note, this->feedLink escapes the url.
3516 $feedLinks[] = $this->feedLink(
3517 $type,
3518 $feedUrl,
3519 $this->msg( "site-{$type}-feed", $sitename )->text()
3522 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3523 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
3524 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3525 $feedLinks[] = $this->feedLink(
3526 $format,
3527 $rctitle->getLocalURL( array( 'feed' => $format ) ),
3528 # For grep: 'site-rss-feed', 'site-atom-feed'
3529 $this->msg( "site-{$format}-feed", $sitename )->text()
3534 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3535 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3536 # use OutputPage::addFeedLink() instead.
3537 Hooks::run( 'AfterBuildFeedLinks', array( &$feedLinks ) );
3539 $tags += $feedLinks;
3542 # Canonical URL
3543 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3544 if ( $canonicalUrl !== false ) {
3545 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL );
3546 } else {
3547 if ( $this->isArticleRelated() ) {
3548 // This affects all requests where "setArticleRelated" is true. This is
3549 // typically all requests that show content (query title, curid, oldid, diff),
3550 // and all wikipage actions (edit, delete, purge, info, history etc.).
3551 // It does not apply to File pages and Special pages.
3552 // 'history' and 'info' actions address page metadata rather than the page
3553 // content itself, so they may not be canonicalized to the view page url.
3554 // TODO: this ought to be better encapsulated in the Action class.
3555 $action = Action::getActionName( $this->getContext() );
3556 if ( in_array( $action, array( 'history', 'info' ) ) ) {
3557 $query = "action={$action}";
3558 } else {
3559 $query = '';
3561 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3562 } else {
3563 $reqUrl = $this->getRequest()->getRequestURL();
3564 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL );
3568 if ( $canonicalUrl !== false ) {
3569 $tags[] = Html::element( 'link', array(
3570 'rel' => 'canonical',
3571 'href' => $canonicalUrl
3572 ) );
3575 return $tags;
3579 * @return string HTML tag links to be put in the header.
3580 * @deprecated since 1.24 Use OutputPage::headElement or if you have to,
3581 * OutputPage::getHeadLinksArray directly.
3583 public function getHeadLinks() {
3584 wfDeprecated( __METHOD__, '1.24' );
3585 return implode( "\n", $this->getHeadLinksArray() );
3589 * Generate a "<link rel/>" for a feed.
3591 * @param string $type Feed type
3592 * @param string $url URL to the feed
3593 * @param string $text Value of the "title" attribute
3594 * @return string HTML fragment
3596 private function feedLink( $type, $url, $text ) {
3597 return Html::element( 'link', array(
3598 'rel' => 'alternate',
3599 'type' => "application/$type+xml",
3600 'title' => $text,
3601 'href' => $url )
3606 * Add a local or specified stylesheet, with the given media options.
3607 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3609 * @param string $style URL to the file
3610 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3611 * @param string $condition For IE conditional comments, specifying an IE version
3612 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3614 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3615 $options = array();
3616 // Even though we expect the media type to be lowercase, but here we
3617 // force it to lowercase to be safe.
3618 if ( $media ) {
3619 $options['media'] = $media;
3621 if ( $condition ) {
3622 $options['condition'] = $condition;
3624 if ( $dir ) {
3625 $options['dir'] = $dir;
3627 $this->styles[$style] = $options;
3631 * Adds inline CSS styles
3632 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3634 * @param mixed $style_css Inline CSS
3635 * @param string $flip Set to 'flip' to flip the CSS if needed
3637 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3638 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3639 # If wanted, and the interface is right-to-left, flip the CSS
3640 $style_css = CSSJanus::transform( $style_css, true, false );
3642 $this->mInlineStyles .= Html::inlineStyle( $style_css ) . "\n";
3646 * Build a set of "<link>" elements for the stylesheets specified in the $this->styles array.
3647 * These will be applied to various media & IE conditionals.
3649 * @return string
3651 public function buildCssLinks() {
3652 global $wgContLang;
3654 $this->getSkin()->setupSkinUserCss( $this );
3656 // Add ResourceLoader styles
3657 // Split the styles into these groups
3658 $styles = array(
3659 'other' => array(),
3660 'user' => array(),
3661 'site' => array(),
3662 'private' => array(),
3663 'noscript' => array()
3665 $links = array();
3666 $otherTags = array(); // Tags to append after the normal <link> tags
3667 $resourceLoader = $this->getResourceLoader();
3669 $moduleStyles = $this->getModuleStyles();
3671 // Per-site custom styles
3672 $moduleStyles[] = 'site';
3673 $moduleStyles[] = 'noscript';
3674 $moduleStyles[] = 'user.groups';
3676 // Per-user custom styles
3677 if ( $this->getConfig()->get( 'AllowUserCss' ) && $this->getTitle()->isCssSubpage()
3678 && $this->userCanPreview()
3680 // We're on a preview of a CSS subpage
3681 // Exclude this page from the user module in case it's in there (bug 26283)
3682 $link = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_STYLES,
3683 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3685 $otherTags = array_merge( $otherTags, $link['html'] );
3687 // Load the previewed CSS
3688 // If needed, Janus it first. This is user-supplied CSS, so it's
3689 // assumed to be right for the content language directionality.
3690 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3691 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3692 $previewedCSS = CSSJanus::transform( $previewedCSS, true, false );
3694 $otherTags[] = Html::inlineStyle( $previewedCSS ) . "\n";
3695 } else {
3696 // Load the user styles normally
3697 $moduleStyles[] = 'user';
3700 // Per-user preference styles
3701 $moduleStyles[] = 'user.cssprefs';
3703 foreach ( $moduleStyles as $name ) {
3704 $module = $resourceLoader->getModule( $name );
3705 if ( !$module ) {
3706 continue;
3708 if ( $name === 'site' ) {
3709 // HACK: The site module shouldn't be fragmented with a cache group and
3710 // http request. But in order to ensure its styles are separated and after the
3711 // ResourceLoaderDynamicStyles marker, pretend it is in a group called 'site'.
3712 // The scripts remain ungrouped and rides the bottom queue.
3713 $styles['site'][] = $name;
3714 continue;
3716 $group = $module->getGroup();
3717 // Modules in groups other than the ones needing special treatment
3718 // (see $styles assignment)
3719 // will be placed in the "other" style category.
3720 $styles[isset( $styles[$group] ) ? $group : 'other'][] = $name;
3723 // We want site, private and user styles to override dynamically added
3724 // styles from modules, but we want dynamically added styles to override
3725 // statically added styles from other modules. So the order has to be
3726 // other, dynamic, site, private, user. Add statically added styles for
3727 // other modules
3728 $links[] = $this->makeResourceLoaderLink(
3729 $styles['other'],
3730 ResourceLoaderModule::TYPE_STYLES
3732 // Add normal styles added through addStyle()/addInlineStyle() here
3733 $links[] = implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles;
3734 // Add marker tag to mark the place where the client-side
3735 // loader should inject dynamic styles
3736 // We use a <meta> tag with a made-up name for this because that's valid HTML
3737 $links[] = Html::element(
3738 'meta',
3739 array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' )
3742 // Add site-specific and user-specific styles
3743 // 'private' at present only contains user.options, so put that before 'user'
3744 // Any future private modules will likely have a similar user-specific character
3745 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3746 $links[] = $this->makeResourceLoaderLink( $styles[$group],
3747 ResourceLoaderModule::TYPE_STYLES
3751 // Add stuff in $otherTags (previewed user CSS if applicable)
3752 return self::getHtmlFromLoaderLinks( $links ) . implode( '', $otherTags );
3756 * @return array
3758 public function buildCssLinksArray() {
3759 $links = array();
3761 // Add any extension CSS
3762 foreach ( $this->mExtStyles as $url ) {
3763 $this->addStyle( $url );
3765 $this->mExtStyles = array();
3767 foreach ( $this->styles as $file => $options ) {
3768 $link = $this->styleLink( $file, $options );
3769 if ( $link ) {
3770 $links[$file] = $link;
3773 return $links;
3777 * Generate \<link\> tags for stylesheets
3779 * @param string $style URL to the file
3780 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3781 * @return string HTML fragment
3783 protected function styleLink( $style, array $options ) {
3784 if ( isset( $options['dir'] ) ) {
3785 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3786 return '';
3790 if ( isset( $options['media'] ) ) {
3791 $media = self::transformCssMedia( $options['media'] );
3792 if ( is_null( $media ) ) {
3793 return '';
3795 } else {
3796 $media = 'all';
3799 if ( substr( $style, 0, 1 ) == '/' ||
3800 substr( $style, 0, 5 ) == 'http:' ||
3801 substr( $style, 0, 6 ) == 'https:' ) {
3802 $url = $style;
3803 } else {
3804 $config = $this->getConfig();
3805 $url = $config->get( 'StylePath' ) . '/' . $style . '?' .
3806 $config->get( 'StyleVersion' );
3809 $link = Html::linkedStyle( $url, $media );
3811 if ( isset( $options['condition'] ) ) {
3812 $condition = htmlspecialchars( $options['condition'] );
3813 $link = "<!--[if $condition]>$link<![endif]-->";
3815 return $link;
3819 * Transform "media" attribute based on request parameters
3821 * @param string $media Current value of the "media" attribute
3822 * @return string Modified value of the "media" attribute, or null to skip
3823 * this stylesheet
3825 public static function transformCssMedia( $media ) {
3826 global $wgRequest;
3828 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3829 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3831 // Switch in on-screen display for media testing
3832 $switches = array(
3833 'printable' => 'print',
3834 'handheld' => 'handheld',
3836 foreach ( $switches as $switch => $targetMedia ) {
3837 if ( $wgRequest->getBool( $switch ) ) {
3838 if ( $media == $targetMedia ) {
3839 $media = '';
3840 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3841 /* This regex will not attempt to understand a comma-separated media_query_list
3843 * Example supported values for $media:
3844 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3845 * Example NOT supported value for $media:
3846 * '3d-glasses, screen, print and resolution > 90dpi'
3848 * If it's a print request, we never want any kind of screen stylesheets
3849 * If it's a handheld request (currently the only other choice with a switch),
3850 * we don't want simple 'screen' but we might want screen queries that
3851 * have a max-width or something, so we'll pass all others on and let the
3852 * client do the query.
3854 if ( $targetMedia == 'print' || $media == 'screen' ) {
3855 return null;
3861 return $media;
3865 * Add a wikitext-formatted message to the output.
3866 * This is equivalent to:
3868 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3870 public function addWikiMsg( /*...*/ ) {
3871 $args = func_get_args();
3872 $name = array_shift( $args );
3873 $this->addWikiMsgArray( $name, $args );
3877 * Add a wikitext-formatted message to the output.
3878 * Like addWikiMsg() except the parameters are taken as an array
3879 * instead of a variable argument list.
3881 * @param string $name
3882 * @param array $args
3884 public function addWikiMsgArray( $name, $args ) {
3885 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3889 * This function takes a number of message/argument specifications, wraps them in
3890 * some overall structure, and then parses the result and adds it to the output.
3892 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3893 * and so on. The subsequent arguments may be either
3894 * 1) strings, in which case they are message names, or
3895 * 2) arrays, in which case, within each array, the first element is the message
3896 * name, and subsequent elements are the parameters to that message.
3898 * Don't use this for messages that are not in the user's interface language.
3900 * For example:
3902 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3904 * Is equivalent to:
3906 * $wgOut->addWikiText( "<div class='error'>\n"
3907 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3909 * The newline after the opening div is needed in some wikitext. See bug 19226.
3911 * @param string $wrap
3913 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3914 $msgSpecs = func_get_args();
3915 array_shift( $msgSpecs );
3916 $msgSpecs = array_values( $msgSpecs );
3917 $s = $wrap;
3918 foreach ( $msgSpecs as $n => $spec ) {
3919 if ( is_array( $spec ) ) {
3920 $args = $spec;
3921 $name = array_shift( $args );
3922 if ( isset( $args['options'] ) ) {
3923 unset( $args['options'] );
3924 wfDeprecated(
3925 'Adding "options" to ' . __METHOD__ . ' is no longer supported',
3926 '1.20'
3929 } else {
3930 $args = array();
3931 $name = $spec;
3933 $s = str_replace( '$' . ( $n + 1 ), $this->msg( $name, $args )->plain(), $s );
3935 $this->addWikiText( $s );
3939 * Enables/disables TOC, doesn't override __NOTOC__
3940 * @param bool $flag
3941 * @since 1.22
3943 public function enableTOC( $flag = true ) {
3944 $this->mEnableTOC = $flag;
3948 * @return bool
3949 * @since 1.22
3951 public function isTOCEnabled() {
3952 return $this->mEnableTOC;
3956 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3957 * @param bool $flag
3958 * @since 1.23
3960 public function enableSectionEditLinks( $flag = true ) {
3961 $this->mEnableSectionEditLinks = $flag;
3965 * @return bool
3966 * @since 1.23
3968 public function sectionEditLinksEnabled() {
3969 return $this->mEnableSectionEditLinks;
3973 * Helper function to setup the PHP implementation of OOUI to use in this request.
3975 * @since 1.26
3976 * @param String $skinName The Skin name to determine the correct OOUI theme
3977 * @param String $dir Language direction
3979 public static function setupOOUI( $skinName = '', $dir = 'ltr' ) {
3980 $themes = ExtensionRegistry::getInstance()->getAttribute( 'SkinOOUIThemes' );
3981 // Make keys (skin names) lowercase for case-insensitive matching.
3982 $themes = array_change_key_case( $themes, CASE_LOWER );
3983 $theme = isset( $themes[$skinName] ) ? $themes[$skinName] : 'MediaWiki';
3984 // For example, 'OOUI\MediaWikiTheme'.
3985 $themeClass = "OOUI\\{$theme}Theme";
3986 OOUI\Theme::setSingleton( new $themeClass() );
3987 OOUI\Element::setDefaultDir( $dir );
3991 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
3992 * MediaWiki and this OutputPage instance.
3994 * @since 1.25
3996 public function enableOOUI() {
3997 self::setupOOUI(
3998 strtolower( $this->getSkin()->getSkinName() ),
3999 $this->getLanguage()->getDir()
4001 $this->addModuleStyles( array(
4002 'oojs-ui.styles',
4003 'oojs-ui.styles.icons',
4004 'oojs-ui.styles.indicators',
4005 'oojs-ui.styles.textures',
4006 'mediawiki.widgets.styles',
4007 ) );