Remove "related" searches
[mediawiki.git] / includes / OutputPage.php
blobaf90ca6da43fec68a45dc8c7f09b9294dd4130b0
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 /**
24 * This class should be covered by a general architecture document which does
25 * not exist as of January 2011. This is one of the Core classes and should
26 * be read at least once by any new developers.
28 * This class is used to prepare the final rendering. A skin is then
29 * applied to the output parameters (links, javascript, html, categories ...).
31 * @todo FIXME: Another class handles sending the whole page to the client.
33 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
34 * in November 2010.
36 * @todo document
38 class OutputPage extends ContextSource {
39 /** @var array Should be private. Used with addMeta() which adds "<meta>" */
40 protected $mMetatags = array();
42 /** @var array */
43 protected $mLinktags = array();
45 /** @var bool */
46 protected $mCanonicalUrl = false;
48 /**
49 * @var array Additional stylesheets. Looks like this is for extensions.
50 * Might be replaced by resource loader.
52 protected $mExtStyles = array();
54 /**
55 * @var string Should be private - has getter and setter. Contains
56 * the HTML title */
57 public $mPagetitle = '';
59 /**
60 * @var string Contains all of the "<body>" content. Should be private we
61 * got set/get accessors and the append() method.
63 public $mBodytext = '';
65 /**
66 * Holds the debug lines that will be output as comments in page source if
67 * $wgDebugComments is enabled. See also $wgShowDebug.
68 * @deprecated since 1.20; use MWDebug class instead.
70 public $mDebugtext = '';
72 /** @var string Stores contents of "<title>" tag */
73 private $mHTMLtitle = '';
75 /**
76 * @var bool Is the displayed content related to the source of the
77 * corresponding wiki article.
79 private $mIsarticle = false;
81 /** @var bool Stores "article flag" toggle. */
82 private $mIsArticleRelated = true;
84 /**
85 * @var bool We have to set isPrintable(). Some pages should
86 * never be printed (ex: redirections).
88 private $mPrintable = false;
90 /**
91 * @var array Contains the page subtitle. Special pages usually have some
92 * links here. Don't confuse with site subtitle added by skins.
94 private $mSubtitle = array();
96 /** @var string */
97 public $mRedirect = '';
99 /** @var int */
100 protected $mStatusCode;
103 * @var string Variable mLastModified and mEtag are used for sending cache control.
104 * The whole caching system should probably be moved into its own class.
106 protected $mLastModified = '';
109 * Contains an HTTP Entity Tags (see RFC 2616 section 3.13) which is used
110 * as a unique identifier for the content. It is later used by the client
111 * to compare its cached version with the server version. Client sends
112 * headers If-Match and If-None-Match containing its locally cached ETAG value.
114 * To get more information, you will have to look at HTTP/1.1 protocol which
115 * is properly described in RFC 2616 : http://tools.ietf.org/html/rfc2616
117 private $mETag = false;
119 /** @var array */
120 protected $mCategoryLinks = array();
122 /** @var array */
123 protected $mCategories = array();
125 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
126 private $mLanguageLinks = array();
129 * Used for JavaScript (pre resource loader)
130 * @todo We should split JS / CSS.
131 * mScripts content is inserted as is in "<head>" by Skin. This might
132 * contain either a link to a stylesheet or inline CSS.
134 private $mScripts = '';
136 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
137 protected $mInlineStyles = '';
139 /** @todo Unused? */
140 private $mLinkColours;
143 * @var string Used by skin template.
144 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
146 public $mPageLinkTitle = '';
148 /** @var array Array of elements in "<head>". Parser might add its own headers! */
149 protected $mHeadItems = array();
151 // @todo FIXME: Next 5 variables probably come from the resource loader
153 /** @var array */
154 protected $mModules = array();
156 /** @var array */
157 protected $mModuleScripts = array();
159 /** @var array */
160 protected $mModuleStyles = array();
162 /** @var array */
163 protected $mModuleMessages = array();
165 /** @var ResourceLoader */
166 protected $mResourceLoader;
168 /** @var array */
169 protected $mJsConfigVars = array();
171 /** @var array */
172 protected $mTemplateIds = array();
174 /** @var array */
175 protected $mImageTimeKeys = array();
177 /** @var string */
178 public $mRedirectCode = '';
180 protected $mFeedLinksAppendQuery = null;
182 /** @var array
183 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
184 * @see ResourceLoaderModule::$origin
185 * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
187 protected $mAllowedModules = array(
188 ResourceLoaderModule::TYPE_COMBINED => ResourceLoaderModule::ORIGIN_ALL,
191 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
192 protected $mDoNothing = false;
194 // Parser related.
197 * @var int
198 * @todo Unused?
200 private $mContainsOldMagic = 0;
202 /** @var int */
203 protected $mContainsNewMagic = 0;
206 * lazy initialised, use parserOptions()
207 * @var ParserOptions
209 protected $mParserOptions = null;
212 * Handles the Atom / RSS links.
213 * We probably only support Atom in 2011.
214 * @see $wgAdvertisedFeedTypes
216 private $mFeedLinks = array();
218 // Gwicke work on squid caching? Roughly from 2003.
219 protected $mEnableClientCache = true;
221 /** @var bool Flag if output should only contain the body of the article. */
222 private $mArticleBodyOnly = false;
224 /** @var bool */
225 protected $mNewSectionLink = false;
227 /** @var bool */
228 protected $mHideNewSectionLink = false;
231 * @var bool Comes from the parser. This was probably made to load CSS/JS
232 * only if we had "<gallery>". Used directly in CategoryPage.php.
233 * Looks like resource loader can replace this.
235 public $mNoGallery = false;
237 /** @var string */
238 private $mPageTitleActionText = '';
240 /** @var array */
241 private $mParseWarnings = array();
243 /** @var int Cache stuff. Looks like mEnableClientCache */
244 protected $mSquidMaxage = 0;
247 * @var bool
248 * @todo Document
250 protected $mPreventClickjacking = true;
252 /** @var int To include the variable {{REVISIONID}} */
253 private $mRevisionId = null;
255 /** @var string */
256 private $mRevisionTimestamp = null;
258 /** @var array */
259 protected $mFileVersion = null;
262 * @var array An array of stylesheet filenames (relative from skins path),
263 * with options for CSS media, IE conditions, and RTL/LTR direction.
264 * For internal use; add settings in the skin via $this->addStyle()
266 * Style again! This seems like a code duplication since we already have
267 * mStyles. This is what makes Open Source amazing.
269 protected $styles = array();
272 * Whether jQuery is already handled.
274 protected $mJQueryDone = false;
276 private $mIndexPolicy = 'index';
277 private $mFollowPolicy = 'follow';
278 private $mVaryHeader = array(
279 'Accept-Encoding' => array( 'list-contains=gzip' ),
283 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
284 * of the redirect.
286 * @var Title
288 private $mRedirectedFrom = null;
291 * Additional key => value data
293 private $mProperties = array();
296 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
298 private $mTarget = null;
301 * @var bool Whether parser output should contain table of contents
303 private $mEnableTOC = true;
306 * @var bool Whether parser output should contain section edit links
308 private $mEnableSectionEditLinks = true;
311 * Constructor for OutputPage. This should not be called directly.
312 * Instead a new RequestContext should be created and it will implicitly create
313 * a OutputPage tied to that context.
314 * @param IContextSource|null $context
316 function __construct( IContextSource $context = null ) {
317 if ( $context === null ) {
318 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
319 wfDeprecated( __METHOD__, '1.18' );
320 } else {
321 $this->setContext( $context );
326 * Redirect to $url rather than displaying the normal page
328 * @param string $url URL
329 * @param string $responsecode HTTP status code
331 public function redirect( $url, $responsecode = '302' ) {
332 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
333 $this->mRedirect = str_replace( "\n", '', $url );
334 $this->mRedirectCode = $responsecode;
338 * Get the URL to redirect to, or an empty string if not redirect URL set
340 * @return string
342 public function getRedirect() {
343 return $this->mRedirect;
347 * Set the HTTP status code to send with the output.
349 * @param int $statusCode
351 public function setStatusCode( $statusCode ) {
352 $this->mStatusCode = $statusCode;
356 * Add a new "<meta>" tag
357 * To add an http-equiv meta tag, precede the name with "http:"
359 * @param string $name Tag name
360 * @param string $val Tag value
362 function addMeta( $name, $val ) {
363 array_push( $this->mMetatags, array( $name, $val ) );
367 * Add a new \<link\> tag to the page header.
369 * Note: use setCanonicalUrl() for rel=canonical.
371 * @param array $linkarr Associative array of attributes.
373 function addLink( array $linkarr ) {
374 array_push( $this->mLinktags, $linkarr );
378 * Add a new \<link\> with "rel" attribute set to "meta"
380 * @param array $linkarr Associative array mapping attribute names to their
381 * values, both keys and values will be escaped, and the
382 * "rel" attribute will be automatically added
384 function addMetadataLink( array $linkarr ) {
385 $linkarr['rel'] = $this->getMetadataAttribute();
386 $this->addLink( $linkarr );
390 * Set the URL to be used for the <link rel=canonical>. This should be used
391 * in preference to addLink(), to avoid duplicate link tags.
392 * @param string $url
394 function setCanonicalUrl( $url ) {
395 $this->mCanonicalUrl = $url;
399 * Get the value of the "rel" attribute for metadata links
401 * @return string
403 public function getMetadataAttribute() {
404 # note: buggy CC software only reads first "meta" link
405 static $haveMeta = false;
406 if ( $haveMeta ) {
407 return 'alternate meta';
408 } else {
409 $haveMeta = true;
410 return 'meta';
415 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
417 * @param string $script Raw HTML
419 function addScript( $script ) {
420 $this->mScripts .= $script . "\n";
424 * Register and add a stylesheet from an extension directory.
426 * @param string $url Path to sheet. Provide either a full url (beginning
427 * with 'http', etc) or a relative path from the document root
428 * (beginning with '/'). Otherwise it behaves identically to
429 * addStyle() and draws from the /skins folder.
431 public function addExtensionStyle( $url ) {
432 array_push( $this->mExtStyles, $url );
436 * Get all styles added by extensions
438 * @return array
440 function getExtStyle() {
441 return $this->mExtStyles;
445 * Add a JavaScript file out of skins/common, or a given relative path.
447 * @param string $file Filename in skins/common or complete on-server path
448 * (/foo/bar.js)
449 * @param string $version Style version of the file. Defaults to $wgStyleVersion
451 public function addScriptFile( $file, $version = null ) {
452 // See if $file parameter is an absolute URL or begins with a slash
453 if ( substr( $file, 0, 1 ) == '/' || preg_match( '#^[a-z]*://#i', $file ) ) {
454 $path = $file;
455 } else {
456 $path = $this->getConfig()->get( 'StylePath' ) . "/common/{$file}";
458 if ( is_null( $version ) ) {
459 $version = $this->getConfig()->get( 'StyleVersion' );
461 $this->addScript( Html::linkedScript( wfAppendQuery( $path, $version ) ) );
465 * Add a self-contained script tag with the given contents
467 * @param string $script JavaScript text, no "<script>" tags
469 public function addInlineScript( $script ) {
470 $this->mScripts .= Html::inlineScript( "\n$script\n" ) . "\n";
474 * Get all registered JS and CSS tags for the header.
476 * @return string
477 * @deprecated since 1.24 Use OutputPage::headElement to build the full header.
479 function getScript() {
480 wfDeprecated( __METHOD__, '1.24' );
481 return $this->mScripts . $this->getHeadItems();
485 * Filter an array of modules to remove insufficiently trustworthy members, and modules
486 * which are no longer registered (eg a page is cached before an extension is disabled)
487 * @param array $modules
488 * @param string|null $position If not null, only return modules with this position
489 * @param string $type
490 * @return array
492 protected function filterModules( array $modules, $position = null,
493 $type = ResourceLoaderModule::TYPE_COMBINED
495 $resourceLoader = $this->getResourceLoader();
496 $filteredModules = array();
497 foreach ( $modules as $val ) {
498 $module = $resourceLoader->getModule( $val );
499 if ( $module instanceof ResourceLoaderModule
500 && $module->getOrigin() <= $this->getAllowedModules( $type )
501 && ( is_null( $position ) || $module->getPosition() == $position )
502 && ( !$this->mTarget || in_array( $this->mTarget, $module->getTargets() ) )
504 $filteredModules[] = $val;
507 return $filteredModules;
511 * Get the list of modules to include on this page
513 * @param bool $filter Whether to filter out insufficiently trustworthy modules
514 * @param string|null $position If not null, only return modules with this position
515 * @param string $param
516 * @return array Array of module names
518 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
519 $modules = array_values( array_unique( $this->$param ) );
520 return $filter
521 ? $this->filterModules( $modules, $position )
522 : $modules;
526 * Add one or more modules recognized by the resource loader. Modules added
527 * through this function will be loaded by the resource loader when the
528 * page loads.
530 * @param string|array $modules Module name (string) or array of module names
532 public function addModules( $modules ) {
533 $this->mModules = array_merge( $this->mModules, (array)$modules );
537 * Get the list of module JS to include on this page
539 * @param bool $filter
540 * @param string|null $position
542 * @return array Array of module names
544 public function getModuleScripts( $filter = false, $position = null ) {
545 return $this->getModules( $filter, $position, 'mModuleScripts' );
549 * Add only JS of one or more modules recognized by the resource loader. Module
550 * scripts added through this function will be loaded by the resource loader when
551 * the page loads.
553 * @param string|array $modules Module name (string) or array of module names
555 public function addModuleScripts( $modules ) {
556 $this->mModuleScripts = array_merge( $this->mModuleScripts, (array)$modules );
560 * Get the list of module CSS to include on this page
562 * @param bool $filter
563 * @param string|null $position
565 * @return array Array of module names
567 public function getModuleStyles( $filter = false, $position = null ) {
568 return $this->getModules( $filter, $position, 'mModuleStyles' );
572 * Add only CSS of one or more modules recognized by the resource loader.
574 * Module styles added through this function will be added using standard link CSS
575 * tags, rather than as a combined Javascript and CSS package. Thus, they will
576 * load when JavaScript is disabled (unless CSS also happens to be disabled).
578 * @param string|array $modules Module name (string) or array of module names
580 public function addModuleStyles( $modules ) {
581 $this->mModuleStyles = array_merge( $this->mModuleStyles, (array)$modules );
585 * Get the list of module messages to include on this page
587 * @param bool $filter
588 * @param string|null $position
590 * @return array Array of module names
592 public function getModuleMessages( $filter = false, $position = null ) {
593 return $this->getModules( $filter, $position, 'mModuleMessages' );
597 * Add only messages of one or more modules recognized by the resource loader.
598 * Module messages added through this function will be loaded by the resource
599 * loader when the page loads.
601 * @param string|array $modules Module name (string) or array of module names
603 public function addModuleMessages( $modules ) {
604 $this->mModuleMessages = array_merge( $this->mModuleMessages, (array)$modules );
608 * @return null|string ResourceLoader target
610 public function getTarget() {
611 return $this->mTarget;
615 * Sets ResourceLoader target for load.php links. If null, will be omitted
617 * @param string|null $target
619 public function setTarget( $target ) {
620 $this->mTarget = $target;
624 * Get an array of head items
626 * @return array
628 function getHeadItemsArray() {
629 return $this->mHeadItems;
633 * Get all header items in a string
635 * @return string
636 * @deprecated since 1.24 Use OutputPage::headElement or
637 * if absolutely necessary use OutputPage::getHeadItemsArray
639 function getHeadItems() {
640 wfDeprecated( __METHOD__, '1.24' );
641 $s = '';
642 foreach ( $this->mHeadItems as $item ) {
643 $s .= $item;
645 return $s;
649 * Add or replace an header item to the output
651 * @param string $name Item name
652 * @param string $value Raw HTML
654 public function addHeadItem( $name, $value ) {
655 $this->mHeadItems[$name] = $value;
659 * Check if the header item $name is already set
661 * @param string $name Item name
662 * @return bool
664 public function hasHeadItem( $name ) {
665 return isset( $this->mHeadItems[$name] );
669 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
671 * @param string $tag Value of "ETag" header
673 function setETag( $tag ) {
674 $this->mETag = $tag;
678 * Set whether the output should only contain the body of the article,
679 * without any skin, sidebar, etc.
680 * Used e.g. when calling with "action=render".
682 * @param bool $only Whether to output only the body of the article
684 public function setArticleBodyOnly( $only ) {
685 $this->mArticleBodyOnly = $only;
689 * Return whether the output will contain only the body of the article
691 * @return bool
693 public function getArticleBodyOnly() {
694 return $this->mArticleBodyOnly;
698 * Set an additional output property
699 * @since 1.21
701 * @param string $name
702 * @param mixed $value
704 public function setProperty( $name, $value ) {
705 $this->mProperties[$name] = $value;
709 * Get an additional output property
710 * @since 1.21
712 * @param string $name
713 * @return mixed Property value or null if not found
715 public function getProperty( $name ) {
716 if ( isset( $this->mProperties[$name] ) ) {
717 return $this->mProperties[$name];
718 } else {
719 return null;
724 * checkLastModified tells the client to use the client-cached page if
725 * possible. If successful, the OutputPage is disabled so that
726 * any future call to OutputPage->output() have no effect.
728 * Side effect: sets mLastModified for Last-Modified header
730 * @param string $timestamp
732 * @return bool True if cache-ok headers was sent.
734 public function checkLastModified( $timestamp ) {
735 if ( !$timestamp || $timestamp == '19700101000000' ) {
736 wfDebug( __METHOD__ . ": CACHE DISABLED, NO TIMESTAMP\n" );
737 return false;
739 $config = $this->getConfig();
740 if ( !$config->get( 'CachePages' ) ) {
741 wfDebug( __METHOD__ . ": CACHE DISABLED\n" );
742 return false;
745 $timestamp = wfTimestamp( TS_MW, $timestamp );
746 $modifiedTimes = array(
747 'page' => $timestamp,
748 'user' => $this->getUser()->getTouched(),
749 'epoch' => $config->get( 'CacheEpoch' )
751 if ( $config->get( 'UseSquid' ) ) {
752 // bug 44570: the core page itself may not change, but resources might
753 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW, time() - $config->get( 'SquidMaxage' ) );
755 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
757 $maxModified = max( $modifiedTimes );
758 $this->mLastModified = wfTimestamp( TS_RFC2822, $maxModified );
760 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
761 if ( $clientHeader === false ) {
762 wfDebug( __METHOD__ . ": client did not send If-Modified-Since header\n", 'log' );
763 return false;
766 # IE sends sizes after the date like this:
767 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
768 # this breaks strtotime().
769 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
771 wfSuppressWarnings(); // E_STRICT system time bitching
772 $clientHeaderTime = strtotime( $clientHeader );
773 wfRestoreWarnings();
774 if ( !$clientHeaderTime ) {
775 wfDebug( __METHOD__
776 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
777 return false;
779 $clientHeaderTime = wfTimestamp( TS_MW, $clientHeaderTime );
781 # Make debug info
782 $info = '';
783 foreach ( $modifiedTimes as $name => $value ) {
784 if ( $info !== '' ) {
785 $info .= ', ';
787 $info .= "$name=" . wfTimestamp( TS_ISO_8601, $value );
790 wfDebug( __METHOD__ . ": client sent If-Modified-Since: " .
791 wfTimestamp( TS_ISO_8601, $clientHeaderTime ) . "\n", 'log' );
792 wfDebug( __METHOD__ . ": effective Last-Modified: " .
793 wfTimestamp( TS_ISO_8601, $maxModified ) . "\n", 'log' );
794 if ( $clientHeaderTime < $maxModified ) {
795 wfDebug( __METHOD__ . ": STALE, $info\n", 'log' );
796 return false;
799 # Not modified
800 # Give a 304 response code and disable body output
801 wfDebug( __METHOD__ . ": NOT MODIFIED, $info\n", 'log' );
802 ini_set( 'zlib.output_compression', 0 );
803 $this->getRequest()->response()->header( "HTTP/1.1 304 Not Modified" );
804 $this->sendCacheControl();
805 $this->disable();
807 // Don't output a compressed blob when using ob_gzhandler;
808 // it's technically against HTTP spec and seems to confuse
809 // Firefox when the response gets split over two packets.
810 wfClearOutputBuffers();
812 return true;
816 * Override the last modified timestamp
818 * @param string $timestamp New timestamp, in a format readable by
819 * wfTimestamp()
821 public function setLastModified( $timestamp ) {
822 $this->mLastModified = wfTimestamp( TS_RFC2822, $timestamp );
826 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
828 * @param string $policy The literal string to output as the contents of
829 * the meta tag. Will be parsed according to the spec and output in
830 * standardized form.
831 * @return null
833 public function setRobotPolicy( $policy ) {
834 $policy = Article::formatRobotPolicy( $policy );
836 if ( isset( $policy['index'] ) ) {
837 $this->setIndexPolicy( $policy['index'] );
839 if ( isset( $policy['follow'] ) ) {
840 $this->setFollowPolicy( $policy['follow'] );
845 * Set the index policy for the page, but leave the follow policy un-
846 * touched.
848 * @param string $policy Either 'index' or 'noindex'.
849 * @return null
851 public function setIndexPolicy( $policy ) {
852 $policy = trim( $policy );
853 if ( in_array( $policy, array( 'index', 'noindex' ) ) ) {
854 $this->mIndexPolicy = $policy;
859 * Set the follow policy for the page, but leave the index policy un-
860 * touched.
862 * @param string $policy Either 'follow' or 'nofollow'.
863 * @return null
865 public function setFollowPolicy( $policy ) {
866 $policy = trim( $policy );
867 if ( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
868 $this->mFollowPolicy = $policy;
873 * Set the new value of the "action text", this will be added to the
874 * "HTML title", separated from it with " - ".
876 * @param string $text New value of the "action text"
878 public function setPageTitleActionText( $text ) {
879 $this->mPageTitleActionText = $text;
883 * Get the value of the "action text"
885 * @return string
887 public function getPageTitleActionText() {
888 return $this->mPageTitleActionText;
892 * "HTML title" means the contents of "<title>".
893 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
895 * @param string|Message $name
897 public function setHTMLTitle( $name ) {
898 if ( $name instanceof Message ) {
899 $this->mHTMLtitle = $name->setContext( $this->getContext() )->text();
900 } else {
901 $this->mHTMLtitle = $name;
906 * Return the "HTML title", i.e. the content of the "<title>" tag.
908 * @return string
910 public function getHTMLTitle() {
911 return $this->mHTMLtitle;
915 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
917 * @param Title $t
919 public function setRedirectedFrom( $t ) {
920 $this->mRedirectedFrom = $t;
924 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
925 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
926 * but not bad tags like \<script\>. This function automatically sets
927 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
928 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
929 * good tags like \<i\> will be dropped entirely.
931 * @param string|Message $name
933 public function setPageTitle( $name ) {
934 if ( $name instanceof Message ) {
935 $name = $name->setContext( $this->getContext() )->text();
938 # change "<script>foo&bar</script>" to "&lt;script&gt;foo&amp;bar&lt;/script&gt;"
939 # but leave "<i>foobar</i>" alone
940 $nameWithTags = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags( $name ) );
941 $this->mPagetitle = $nameWithTags;
943 # change "<i>foo&amp;bar</i>" to "foo&bar"
944 $this->setHTMLTitle(
945 $this->msg( 'pagetitle' )->rawParams( Sanitizer::stripAllTags( $nameWithTags ) )
946 ->inContentLanguage()
951 * Return the "page title", i.e. the content of the \<h1\> tag.
953 * @return string
955 public function getPageTitle() {
956 return $this->mPagetitle;
960 * Set the Title object to use
962 * @param Title $t
964 public function setTitle( Title $t ) {
965 $this->getContext()->setTitle( $t );
969 * Replace the subtitle with $str
971 * @param string|Message $str New value of the subtitle. String should be safe HTML.
973 public function setSubtitle( $str ) {
974 $this->clearSubtitle();
975 $this->addSubtitle( $str );
979 * Add $str to the subtitle
981 * @deprecated since 1.19; use addSubtitle() instead
982 * @param string|Message $str String or Message to add to the subtitle
984 public function appendSubtitle( $str ) {
985 $this->addSubtitle( $str );
989 * Add $str to the subtitle
991 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
993 public function addSubtitle( $str ) {
994 if ( $str instanceof Message ) {
995 $this->mSubtitle[] = $str->setContext( $this->getContext() )->parse();
996 } else {
997 $this->mSubtitle[] = $str;
1002 * Add a subtitle containing a backlink to a page
1004 * @param Title $title Title to link to
1005 * @param array $query Array of additional parameters to include in the link
1007 public function addBacklinkSubtitle( Title $title, $query = array() ) {
1008 if ( $title->isRedirect() ) {
1009 $query['redirect'] = 'no';
1011 $this->addSubtitle( $this->msg( 'backlinksubtitle' )
1012 ->rawParams( Linker::link( $title, null, array(), $query ) ) );
1016 * Clear the subtitles
1018 public function clearSubtitle() {
1019 $this->mSubtitle = array();
1023 * Get the subtitle
1025 * @return string
1027 public function getSubtitle() {
1028 return implode( "<br />\n\t\t\t\t", $this->mSubtitle );
1032 * Set the page as printable, i.e. it'll be displayed with with all
1033 * print styles included
1035 public function setPrintable() {
1036 $this->mPrintable = true;
1040 * Return whether the page is "printable"
1042 * @return bool
1044 public function isPrintable() {
1045 return $this->mPrintable;
1049 * Disable output completely, i.e. calling output() will have no effect
1051 public function disable() {
1052 $this->mDoNothing = true;
1056 * Return whether the output will be completely disabled
1058 * @return bool
1060 public function isDisabled() {
1061 return $this->mDoNothing;
1065 * Show an "add new section" link?
1067 * @return bool
1069 public function showNewSectionLink() {
1070 return $this->mNewSectionLink;
1074 * Forcibly hide the new section link?
1076 * @return bool
1078 public function forceHideNewSectionLink() {
1079 return $this->mHideNewSectionLink;
1083 * Add or remove feed links in the page header
1084 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1085 * for the new version
1086 * @see addFeedLink()
1088 * @param bool $show True: add default feeds, false: remove all feeds
1090 public function setSyndicated( $show = true ) {
1091 if ( $show ) {
1092 $this->setFeedAppendQuery( false );
1093 } else {
1094 $this->mFeedLinks = array();
1099 * Add default feeds to the page header
1100 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1101 * for the new version
1102 * @see addFeedLink()
1104 * @param string $val Query to append to feed links or false to output
1105 * default links
1107 public function setFeedAppendQuery( $val ) {
1108 $this->mFeedLinks = array();
1110 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1111 $query = "feed=$type";
1112 if ( is_string( $val ) ) {
1113 $query .= '&' . $val;
1115 $this->mFeedLinks[$type] = $this->getTitle()->getLocalURL( $query );
1120 * Add a feed link to the page header
1122 * @param string $format Feed type, should be a key of $wgFeedClasses
1123 * @param string $href URL
1125 public function addFeedLink( $format, $href ) {
1126 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1127 $this->mFeedLinks[$format] = $href;
1132 * Should we output feed links for this page?
1133 * @return bool
1135 public function isSyndicated() {
1136 return count( $this->mFeedLinks ) > 0;
1140 * Return URLs for each supported syndication format for this page.
1141 * @return array Associating format keys with URLs
1143 public function getSyndicationLinks() {
1144 return $this->mFeedLinks;
1148 * Will currently always return null
1150 * @return null
1152 public function getFeedAppendQuery() {
1153 return $this->mFeedLinksAppendQuery;
1157 * Set whether the displayed content is related to the source of the
1158 * corresponding article on the wiki
1159 * Setting true will cause the change "article related" toggle to true
1161 * @param bool $v
1163 public function setArticleFlag( $v ) {
1164 $this->mIsarticle = $v;
1165 if ( $v ) {
1166 $this->mIsArticleRelated = $v;
1171 * Return whether the content displayed page is related to the source of
1172 * the corresponding article on the wiki
1174 * @return bool
1176 public function isArticle() {
1177 return $this->mIsarticle;
1181 * Set whether this page is related an article on the wiki
1182 * Setting false will cause the change of "article flag" toggle to false
1184 * @param bool $v
1186 public function setArticleRelated( $v ) {
1187 $this->mIsArticleRelated = $v;
1188 if ( !$v ) {
1189 $this->mIsarticle = false;
1194 * Return whether this page is related an article on the wiki
1196 * @return bool
1198 public function isArticleRelated() {
1199 return $this->mIsArticleRelated;
1203 * Add new language links
1205 * @param array $newLinkArray Associative array mapping language code to the page
1206 * name
1208 public function addLanguageLinks( array $newLinkArray ) {
1209 $this->mLanguageLinks += $newLinkArray;
1213 * Reset the language links and add new language links
1215 * @param array $newLinkArray Associative array mapping language code to the page
1216 * name
1218 public function setLanguageLinks( array $newLinkArray ) {
1219 $this->mLanguageLinks = $newLinkArray;
1223 * Get the list of language links
1225 * @return array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1227 public function getLanguageLinks() {
1228 return $this->mLanguageLinks;
1232 * Add an array of categories, with names in the keys
1234 * @param array $categories Mapping category name => sort key
1236 public function addCategoryLinks( array $categories ) {
1237 global $wgContLang;
1239 if ( !is_array( $categories ) || count( $categories ) == 0 ) {
1240 return;
1243 # Add the links to a LinkBatch
1244 $arr = array( NS_CATEGORY => $categories );
1245 $lb = new LinkBatch;
1246 $lb->setArray( $arr );
1248 # Fetch existence plus the hiddencat property
1249 $dbr = wfGetDB( DB_SLAVE );
1250 $fields = array( 'page_id', 'page_namespace', 'page_title', 'page_len',
1251 'page_is_redirect', 'page_latest', 'pp_value' );
1253 if ( $this->getConfig()->get( 'ContentHandlerUseDB' ) ) {
1254 $fields[] = 'page_content_model';
1257 $res = $dbr->select( array( 'page', 'page_props' ),
1258 $fields,
1259 $lb->constructSet( 'page', $dbr ),
1260 __METHOD__,
1261 array(),
1262 array( 'page_props' => array( 'LEFT JOIN', array(
1263 'pp_propname' => 'hiddencat',
1264 'pp_page = page_id'
1265 ) ) )
1268 # Add the results to the link cache
1269 $lb->addResultToCache( LinkCache::singleton(), $res );
1271 # Set all the values to 'normal'.
1272 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1274 # Mark hidden categories
1275 foreach ( $res as $row ) {
1276 if ( isset( $row->pp_value ) ) {
1277 $categories[$row->page_title] = 'hidden';
1281 # Add the remaining categories to the skin
1282 if ( wfRunHooks(
1283 'OutputPageMakeCategoryLinks',
1284 array( &$this, $categories, &$this->mCategoryLinks ) )
1286 foreach ( $categories as $category => $type ) {
1287 $origcategory = $category;
1288 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
1289 if ( !$title ) {
1290 continue;
1292 $wgContLang->findVariantLink( $category, $title, true );
1293 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1294 continue;
1296 $text = $wgContLang->convertHtml( $title->getText() );
1297 $this->mCategories[] = $title->getText();
1298 $this->mCategoryLinks[$type][] = Linker::link( $title, $text );
1304 * Reset the category links (but not the category list) and add $categories
1306 * @param array $categories Mapping category name => sort key
1308 public function setCategoryLinks( array $categories ) {
1309 $this->mCategoryLinks = array();
1310 $this->addCategoryLinks( $categories );
1314 * Get the list of category links, in a 2-D array with the following format:
1315 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1316 * hidden categories) and $link a HTML fragment with a link to the category
1317 * page
1319 * @return array
1321 public function getCategoryLinks() {
1322 return $this->mCategoryLinks;
1326 * Get the list of category names this page belongs to
1328 * @return array Array of strings
1330 public function getCategories() {
1331 return $this->mCategories;
1335 * Do not allow scripts which can be modified by wiki users to load on this page;
1336 * only allow scripts bundled with, or generated by, the software.
1338 public function disallowUserJs() {
1339 $this->reduceAllowedModules(
1340 ResourceLoaderModule::TYPE_SCRIPTS,
1341 ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL
1346 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1347 * @see ResourceLoaderModule::$origin
1348 * @param string $type ResourceLoaderModule TYPE_ constant
1349 * @return int ResourceLoaderModule ORIGIN_ class constant
1351 public function getAllowedModules( $type ) {
1352 if ( $type == ResourceLoaderModule::TYPE_COMBINED ) {
1353 return min( array_values( $this->mAllowedModules ) );
1354 } else {
1355 return isset( $this->mAllowedModules[$type] )
1356 ? $this->mAllowedModules[$type]
1357 : ResourceLoaderModule::ORIGIN_ALL;
1362 * Set the highest level of CSS/JS untrustworthiness allowed
1363 * @param string $type ResourceLoaderModule TYPE_ constant
1364 * @param int $level ResourceLoaderModule class constant
1366 public function setAllowedModules( $type, $level ) {
1367 $this->mAllowedModules[$type] = $level;
1371 * As for setAllowedModules(), but don't inadvertently make the page more accessible
1372 * @param string $type
1373 * @param int $level ResourceLoaderModule class constant
1375 public function reduceAllowedModules( $type, $level ) {
1376 $this->mAllowedModules[$type] = min( $this->getAllowedModules( $type ), $level );
1380 * Prepend $text to the body HTML
1382 * @param string $text HTML
1384 public function prependHTML( $text ) {
1385 $this->mBodytext = $text . $this->mBodytext;
1389 * Append $text to the body HTML
1391 * @param string $text HTML
1393 public function addHTML( $text ) {
1394 $this->mBodytext .= $text;
1398 * Shortcut for adding an Html::element via addHTML.
1400 * @since 1.19
1402 * @param string $element
1403 * @param array $attribs
1404 * @param string $contents
1406 public function addElement( $element, array $attribs = array(), $contents = '' ) {
1407 $this->addHTML( Html::element( $element, $attribs, $contents ) );
1411 * Clear the body HTML
1413 public function clearHTML() {
1414 $this->mBodytext = '';
1418 * Get the body HTML
1420 * @return string HTML
1422 public function getHTML() {
1423 return $this->mBodytext;
1427 * Get/set the ParserOptions object to use for wikitext parsing
1429 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1430 * current ParserOption object
1431 * @return ParserOptions
1433 public function parserOptions( $options = null ) {
1434 if ( !$this->mParserOptions ) {
1435 $this->mParserOptions = ParserOptions::newFromContext( $this->getContext() );
1436 $this->mParserOptions->setEditSection( false );
1438 return wfSetVar( $this->mParserOptions, $options );
1442 * Set the revision ID which will be seen by the wiki text parser
1443 * for things such as embedded {{REVISIONID}} variable use.
1445 * @param int|null $revid An positive integer, or null
1446 * @return mixed Previous value
1448 public function setRevisionId( $revid ) {
1449 $val = is_null( $revid ) ? null : intval( $revid );
1450 return wfSetVar( $this->mRevisionId, $val );
1454 * Get the displayed revision ID
1456 * @return int
1458 public function getRevisionId() {
1459 return $this->mRevisionId;
1463 * Set the timestamp of the revision which will be displayed. This is used
1464 * to avoid a extra DB call in Skin::lastModified().
1466 * @param string|null $timestamp
1467 * @return mixed Previous value
1469 public function setRevisionTimestamp( $timestamp ) {
1470 return wfSetVar( $this->mRevisionTimestamp, $timestamp );
1474 * Get the timestamp of displayed revision.
1475 * This will be null if not filled by setRevisionTimestamp().
1477 * @return string|null
1479 public function getRevisionTimestamp() {
1480 return $this->mRevisionTimestamp;
1484 * Set the displayed file version
1486 * @param File|bool $file
1487 * @return mixed Previous value
1489 public function setFileVersion( $file ) {
1490 $val = null;
1491 if ( $file instanceof File && $file->exists() ) {
1492 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1494 return wfSetVar( $this->mFileVersion, $val, true );
1498 * Get the displayed file version
1500 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1502 public function getFileVersion() {
1503 return $this->mFileVersion;
1507 * Get the templates used on this page
1509 * @return array (namespace => dbKey => revId)
1510 * @since 1.18
1512 public function getTemplateIds() {
1513 return $this->mTemplateIds;
1517 * Get the files used on this page
1519 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1520 * @since 1.18
1522 public function getFileSearchOptions() {
1523 return $this->mImageTimeKeys;
1527 * Convert wikitext to HTML and add it to the buffer
1528 * Default assumes that the current page title will be used.
1530 * @param string $text
1531 * @param bool $linestart Is this the start of a line?
1532 * @param bool $interface Is this text in the user interface language?
1534 public function addWikiText( $text, $linestart = true, $interface = true ) {
1535 $title = $this->getTitle(); // Work around E_STRICT
1536 if ( !$title ) {
1537 throw new MWException( 'Title is null' );
1539 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1543 * Add wikitext with a custom Title object
1545 * @param string $text Wikitext
1546 * @param Title $title
1547 * @param bool $linestart Is this the start of a line?
1549 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1550 $this->addWikiTextTitle( $text, $title, $linestart );
1554 * Add wikitext with a custom Title object and tidy enabled.
1556 * @param string $text Wikitext
1557 * @param Title $title
1558 * @param bool $linestart Is this the start of a line?
1560 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1561 $this->addWikiTextTitle( $text, $title, $linestart, true );
1565 * Add wikitext with tidy enabled
1567 * @param string $text Wikitext
1568 * @param bool $linestart Is this the start of a line?
1570 public function addWikiTextTidy( $text, $linestart = true ) {
1571 $title = $this->getTitle();
1572 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1576 * Add wikitext with a custom Title object
1578 * @param string $text Wikitext
1579 * @param Title $title
1580 * @param bool $linestart Is this the start of a line?
1581 * @param bool $tidy Whether to use tidy
1582 * @param bool $interface Whether it is an interface message
1583 * (for example disables conversion)
1585 public function addWikiTextTitle( $text, Title $title, $linestart,
1586 $tidy = false, $interface = false
1588 global $wgParser;
1590 wfProfileIn( __METHOD__ );
1592 $popts = $this->parserOptions();
1593 $oldTidy = $popts->setTidy( $tidy );
1594 $popts->setInterfaceMessage( (bool)$interface );
1596 $parserOutput = $wgParser->getFreshParser()->parse(
1597 $text, $title, $popts,
1598 $linestart, true, $this->mRevisionId
1601 $popts->setTidy( $oldTidy );
1603 $this->addParserOutput( $parserOutput );
1605 wfProfileOut( __METHOD__ );
1609 * Add a ParserOutput object, but without Html.
1611 * @deprecated since 1.24, use addParserOutputMetadata() instead.
1612 * @param ParserOutput $parserOutput
1614 public function addParserOutputNoText( $parserOutput ) {
1615 $this->addParserOutputMetadata( $parserOutput );
1619 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1620 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1621 * and so on.
1623 * @since 1.24
1624 * @param ParserOutput $parserOutput
1626 public function addParserOutputMetadata( $parserOutput ) {
1627 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
1628 $this->addCategoryLinks( $parserOutput->getCategories() );
1629 $this->mNewSectionLink = $parserOutput->getNewSection();
1630 $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
1632 $this->mParseWarnings = $parserOutput->getWarnings();
1633 if ( !$parserOutput->isCacheable() ) {
1634 $this->enableClientCache( false );
1636 $this->mNoGallery = $parserOutput->getNoGallery();
1637 $this->mHeadItems = array_merge( $this->mHeadItems, $parserOutput->getHeadItems() );
1638 $this->addModules( $parserOutput->getModules() );
1639 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1640 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1641 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1642 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1643 $this->mPreventClickjacking = $this->mPreventClickjacking
1644 || $parserOutput->preventClickjacking();
1646 // Template versioning...
1647 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1648 if ( isset( $this->mTemplateIds[$ns] ) ) {
1649 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
1650 } else {
1651 $this->mTemplateIds[$ns] = $dbks;
1654 // File versioning...
1655 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1656 $this->mImageTimeKeys[$dbk] = $data;
1659 // Hooks registered in the object
1660 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1661 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1662 list( $hookName, $data ) = $hookInfo;
1663 if ( isset( $parserOutputHooks[$hookName] ) ) {
1664 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1668 // Link flags are ignored for now, but may in the future be
1669 // used to mark individual language links.
1670 $linkFlags = array();
1671 wfRunHooks( 'LanguageLinks', array( $this->getTitle(), &$this->mLanguageLinks, &$linkFlags ) );
1672 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1676 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1677 * ParserOutput object, without any other metadata.
1679 * @since 1.24
1680 * @param ParserOutput $parserOutput
1682 public function addParserOutputContent( $parserOutput ) {
1683 $this->addParserOutputText( $parserOutput );
1685 $this->addModules( $parserOutput->getModules() );
1686 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1687 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1688 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1690 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1694 * Add the HTML associated with a ParserOutput object, without any metadata.
1696 * @since 1.24
1697 * @param ParserOutput $parserOutput
1699 public function addParserOutputText( $parserOutput ) {
1700 $text = $parserOutput->getText();
1701 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1702 $this->addHTML( $text );
1706 * Add everything from a ParserOutput object.
1708 * @param ParserOutput $parserOutput
1710 function addParserOutput( $parserOutput ) {
1711 $this->addParserOutputMetadata( $parserOutput );
1712 $parserOutput->setTOCEnabled( $this->mEnableTOC );
1714 // Touch section edit links only if not previously disabled
1715 if ( $parserOutput->getEditSectionTokens() ) {
1716 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks );
1719 $this->addParserOutputText( $parserOutput );
1723 * Add the output of a QuickTemplate to the output buffer
1725 * @param QuickTemplate $template
1727 public function addTemplate( &$template ) {
1728 $this->addHTML( $template->getHTML() );
1732 * Parse wikitext and return the HTML.
1734 * @param string $text
1735 * @param bool $linestart Is this the start of a line?
1736 * @param bool $interface Use interface language ($wgLang instead of
1737 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1738 * This also disables LanguageConverter.
1739 * @param Language $language Target language object, will override $interface
1740 * @throws MWException
1741 * @return string HTML
1743 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1744 global $wgParser;
1746 if ( is_null( $this->getTitle() ) ) {
1747 throw new MWException( 'Empty $mTitle in ' . __METHOD__ );
1750 $popts = $this->parserOptions();
1751 if ( $interface ) {
1752 $popts->setInterfaceMessage( true );
1754 if ( $language !== null ) {
1755 $oldLang = $popts->setTargetLanguage( $language );
1758 $parserOutput = $wgParser->getFreshParser()->parse(
1759 $text, $this->getTitle(), $popts,
1760 $linestart, true, $this->mRevisionId
1763 if ( $interface ) {
1764 $popts->setInterfaceMessage( false );
1766 if ( $language !== null ) {
1767 $popts->setTargetLanguage( $oldLang );
1770 return $parserOutput->getText();
1774 * Parse wikitext, strip paragraphs, and return the HTML.
1776 * @param string $text
1777 * @param bool $linestart Is this the start of a line?
1778 * @param bool $interface Use interface language ($wgLang instead of
1779 * $wgContLang) while parsing language sensitive magic
1780 * words like GRAMMAR and PLURAL
1781 * @return string HTML
1783 public function parseInline( $text, $linestart = true, $interface = false ) {
1784 $parsed = $this->parse( $text, $linestart, $interface );
1785 return Parser::stripOuterParagraph( $parsed );
1789 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1791 * @param int $maxage Maximum cache time on the Squid, in seconds.
1793 public function setSquidMaxage( $maxage ) {
1794 $this->mSquidMaxage = $maxage;
1798 * Use enableClientCache(false) to force it to send nocache headers
1800 * @param bool $state
1802 * @return bool
1804 public function enableClientCache( $state ) {
1805 return wfSetVar( $this->mEnableClientCache, $state );
1809 * Get the list of cookies that will influence on the cache
1811 * @return array
1813 function getCacheVaryCookies() {
1814 static $cookies;
1815 if ( $cookies === null ) {
1816 $config = $this->getConfig();
1817 $cookies = array_merge(
1818 array(
1819 $config->get( 'CookiePrefix' ) . 'Token',
1820 $config->get( 'CookiePrefix' ) . 'LoggedOut',
1821 "forceHTTPS",
1822 session_name()
1824 $config->get( 'CacheVaryCookies' )
1826 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1828 return $cookies;
1832 * Check if the request has a cache-varying cookie header
1833 * If it does, it's very important that we don't allow public caching
1835 * @return bool
1837 function haveCacheVaryCookies() {
1838 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1839 if ( $cookieHeader === false ) {
1840 return false;
1842 $cvCookies = $this->getCacheVaryCookies();
1843 foreach ( $cvCookies as $cookieName ) {
1844 # Check for a simple string match, like the way squid does it
1845 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1846 wfDebug( __METHOD__ . ": found $cookieName\n" );
1847 return true;
1850 wfDebug( __METHOD__ . ": no cache-varying cookies found\n" );
1851 return false;
1855 * Add an HTTP header that will influence on the cache
1857 * @param string $header Header name
1858 * @param array|null $option
1859 * @todo FIXME: Document the $option parameter; it appears to be for
1860 * X-Vary-Options but what format is acceptable?
1862 public function addVaryHeader( $header, $option = null ) {
1863 if ( !array_key_exists( $header, $this->mVaryHeader ) ) {
1864 $this->mVaryHeader[$header] = (array)$option;
1865 } elseif ( is_array( $option ) ) {
1866 if ( is_array( $this->mVaryHeader[$header] ) ) {
1867 $this->mVaryHeader[$header] = array_merge( $this->mVaryHeader[$header], $option );
1868 } else {
1869 $this->mVaryHeader[$header] = $option;
1872 $this->mVaryHeader[$header] = array_unique( (array)$this->mVaryHeader[$header] );
1876 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
1877 * such as Accept-Encoding or Cookie
1879 * @return string
1881 public function getVaryHeader() {
1882 return 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader ) );
1886 * Get a complete X-Vary-Options header
1888 * @return string
1890 public function getXVO() {
1891 $cvCookies = $this->getCacheVaryCookies();
1893 $cookiesOption = array();
1894 foreach ( $cvCookies as $cookieName ) {
1895 $cookiesOption[] = 'string-contains=' . $cookieName;
1897 $this->addVaryHeader( 'Cookie', $cookiesOption );
1899 $headers = array();
1900 foreach ( $this->mVaryHeader as $header => $option ) {
1901 $newheader = $header;
1902 if ( is_array( $option ) && count( $option ) > 0 ) {
1903 $newheader .= ';' . implode( ';', $option );
1905 $headers[] = $newheader;
1907 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1909 return $xvo;
1913 * bug 21672: Add Accept-Language to Vary and XVO headers
1914 * if there's no 'variant' parameter existed in GET.
1916 * For example:
1917 * /w/index.php?title=Main_page should always be served; but
1918 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1920 function addAcceptLanguage() {
1921 $title = $this->getTitle();
1922 if ( !$title instanceof Title ) {
1923 return;
1926 $lang = $title->getPageLanguage();
1927 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
1928 $variants = $lang->getVariants();
1929 $aloption = array();
1930 foreach ( $variants as $variant ) {
1931 if ( $variant === $lang->getCode() ) {
1932 continue;
1933 } else {
1934 $aloption[] = 'string-contains=' . $variant;
1936 // IE and some other browsers use BCP 47 standards in
1937 // their Accept-Language header, like "zh-CN" or "zh-Hant".
1938 // We should handle these too.
1939 $variantBCP47 = wfBCP47( $variant );
1940 if ( $variantBCP47 !== $variant ) {
1941 $aloption[] = 'string-contains=' . $variantBCP47;
1945 $this->addVaryHeader( 'Accept-Language', $aloption );
1950 * Set a flag which will cause an X-Frame-Options header appropriate for
1951 * edit pages to be sent. The header value is controlled by
1952 * $wgEditPageFrameOptions.
1954 * This is the default for special pages. If you display a CSRF-protected
1955 * form on an ordinary view page, then you need to call this function.
1957 * @param bool $enable
1959 public function preventClickjacking( $enable = true ) {
1960 $this->mPreventClickjacking = $enable;
1964 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1965 * This can be called from pages which do not contain any CSRF-protected
1966 * HTML form.
1968 public function allowClickjacking() {
1969 $this->mPreventClickjacking = false;
1973 * Get the prevent-clickjacking flag
1975 * @since 1.24
1976 * @return bool
1978 public function getPreventClickjacking() {
1979 return $this->mPreventClickjacking;
1983 * Get the X-Frame-Options header value (without the name part), or false
1984 * if there isn't one. This is used by Skin to determine whether to enable
1985 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1987 * @return string
1989 public function getFrameOptions() {
1990 $config = $this->getConfig();
1991 if ( $config->get( 'BreakFrames' ) ) {
1992 return 'DENY';
1993 } elseif ( $this->mPreventClickjacking && $config->get( 'EditPageFrameOptions' ) ) {
1994 return $config->get( 'EditPageFrameOptions' );
1996 return false;
2000 * Send cache control HTTP headers
2002 public function sendCacheControl() {
2003 $response = $this->getRequest()->response();
2004 $config = $this->getConfig();
2005 if ( $config->get( 'UseETag' ) && $this->mETag ) {
2006 $response->header( "ETag: $this->mETag" );
2009 $this->addVaryHeader( 'Cookie' );
2010 $this->addAcceptLanguage();
2012 # don't serve compressed data to clients who can't handle it
2013 # maintain different caches for logged-in users and non-logged in ones
2014 $response->header( $this->getVaryHeader() );
2016 if ( $config->get( 'UseXVO' ) ) {
2017 # Add an X-Vary-Options header for Squid with Wikimedia patches
2018 $response->header( $this->getXVO() );
2021 if ( $this->mEnableClientCache ) {
2022 if (
2023 $config->get( 'UseSquid' ) && session_id() == '' && !$this->isPrintable() &&
2024 $this->mSquidMaxage != 0 && !$this->haveCacheVaryCookies()
2026 if ( $config->get( 'UseESI' ) ) {
2027 # We'll purge the proxy cache explicitly, but require end user agents
2028 # to revalidate against the proxy on each visit.
2029 # Surrogate-Control controls our Squid, Cache-Control downstream caches
2030 wfDebug( __METHOD__ . ": proxy caching with ESI; {$this->mLastModified} **\n", 'log' );
2031 # start with a shorter timeout for initial testing
2032 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2033 $response->header( 'Surrogate-Control: max-age=' . $config->get( 'SquidMaxage' )
2034 . '+' . $this->mSquidMaxage . ', content="ESI/1.0"' );
2035 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2036 } else {
2037 # We'll purge the proxy cache for anons explicitly, but require end user agents
2038 # to revalidate against the proxy on each visit.
2039 # IMPORTANT! The Squid needs to replace the Cache-Control header with
2040 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2041 wfDebug( __METHOD__ . ": local proxy caching; {$this->mLastModified} **\n", 'log' );
2042 # start with a shorter timeout for initial testing
2043 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2044 $response->header( 'Cache-Control: s-maxage=' . $this->mSquidMaxage
2045 . ', must-revalidate, max-age=0' );
2047 } else {
2048 # We do want clients to cache if they can, but they *must* check for updates
2049 # on revisiting the page.
2050 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **\n", 'log' );
2051 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2052 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2054 if ( $this->mLastModified ) {
2055 $response->header( "Last-Modified: {$this->mLastModified}" );
2057 } else {
2058 wfDebug( __METHOD__ . ": no caching **\n", 'log' );
2060 # In general, the absence of a last modified header should be enough to prevent
2061 # the client from using its cache. We send a few other things just to make sure.
2062 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2063 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2064 $response->header( 'Pragma: no-cache' );
2069 * Finally, all the text has been munged and accumulated into
2070 * the object, let's actually output it:
2072 public function output() {
2073 global $wgLanguageCode;
2075 if ( $this->mDoNothing ) {
2076 return;
2079 wfProfileIn( __METHOD__ );
2081 $response = $this->getRequest()->response();
2082 $config = $this->getConfig();
2084 if ( $this->mRedirect != '' ) {
2085 # Standards require redirect URLs to be absolute
2086 $this->mRedirect = wfExpandUrl( $this->mRedirect, PROTO_CURRENT );
2088 $redirect = $this->mRedirect;
2089 $code = $this->mRedirectCode;
2091 if ( wfRunHooks( "BeforePageRedirect", array( $this, &$redirect, &$code ) ) ) {
2092 if ( $code == '301' || $code == '303' ) {
2093 if ( !$config->get( 'DebugRedirects' ) ) {
2094 $message = HttpStatus::getMessage( $code );
2095 $response->header( "HTTP/1.1 $code $message" );
2097 $this->mLastModified = wfTimestamp( TS_RFC2822 );
2099 if ( $config->get( 'VaryOnXFP' ) ) {
2100 $this->addVaryHeader( 'X-Forwarded-Proto' );
2102 $this->sendCacheControl();
2104 $response->header( "Content-Type: text/html; charset=utf-8" );
2105 if ( $config->get( 'DebugRedirects' ) ) {
2106 $url = htmlspecialchars( $redirect );
2107 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2108 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2109 print "</body>\n</html>\n";
2110 } else {
2111 $response->header( 'Location: ' . $redirect );
2115 wfProfileOut( __METHOD__ );
2116 return;
2117 } elseif ( $this->mStatusCode ) {
2118 $message = HttpStatus::getMessage( $this->mStatusCode );
2119 if ( $message ) {
2120 $response->header( 'HTTP/1.1 ' . $this->mStatusCode . ' ' . $message );
2124 # Buffer output; final headers may depend on later processing
2125 ob_start();
2127 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2128 $response->header( 'Content-language: ' . $wgLanguageCode );
2130 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2131 // jQuery etc. can work correctly.
2132 $response->header( 'X-UA-Compatible: IE=Edge' );
2134 // Prevent framing, if requested
2135 $frameOptions = $this->getFrameOptions();
2136 if ( $frameOptions ) {
2137 $response->header( "X-Frame-Options: $frameOptions" );
2140 if ( $this->mArticleBodyOnly ) {
2141 echo $this->mBodytext;
2142 } else {
2144 $sk = $this->getSkin();
2145 // add skin specific modules
2146 $modules = $sk->getDefaultModules();
2148 // enforce various default modules for all skins
2149 $coreModules = array(
2150 // keep this list as small as possible
2151 'mediawiki.page.startup',
2152 'mediawiki.user',
2155 // Support for high-density display images if enabled
2156 if ( $config->get( 'ResponsiveImages' ) ) {
2157 $coreModules[] = 'mediawiki.hidpi';
2160 $this->addModules( $coreModules );
2161 foreach ( $modules as $group ) {
2162 $this->addModules( $group );
2164 MWDebug::addModules( $this );
2166 // Hook that allows last minute changes to the output page, e.g.
2167 // adding of CSS or Javascript by extensions.
2168 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
2170 wfProfileIn( 'Output-skin' );
2171 $sk->outputPage();
2172 wfProfileOut( 'Output-skin' );
2175 // This hook allows last minute changes to final overall output by modifying output buffer
2176 wfRunHooks( 'AfterFinalPageOutput', array( $this ) );
2178 $this->sendCacheControl();
2180 ob_end_flush();
2182 wfProfileOut( __METHOD__ );
2186 * Actually output something with print.
2188 * @param string $ins The string to output
2189 * @deprecated since 1.22 Use echo yourself.
2191 public function out( $ins ) {
2192 wfDeprecated( __METHOD__, '1.22' );
2193 print $ins;
2197 * Produce a "user is blocked" page.
2198 * @deprecated since 1.18
2200 function blockedPage() {
2201 throw new UserBlockedError( $this->getUser()->mBlock );
2205 * Prepare this object to display an error page; disable caching and
2206 * indexing, clear the current text and redirect, set the page's title
2207 * and optionally an custom HTML title (content of the "<title>" tag).
2209 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2210 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2211 * optional, if not passed the "<title>" attribute will be
2212 * based on $pageTitle
2214 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2215 $this->setPageTitle( $pageTitle );
2216 if ( $htmlTitle !== false ) {
2217 $this->setHTMLTitle( $htmlTitle );
2219 $this->setRobotPolicy( 'noindex,nofollow' );
2220 $this->setArticleRelated( false );
2221 $this->enableClientCache( false );
2222 $this->mRedirect = '';
2223 $this->clearSubtitle();
2224 $this->clearHTML();
2228 * Output a standard error page
2230 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2231 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2232 * showErrorPage( 'titlemsg', $messageObject );
2233 * showErrorPage( $titleMessageObject, $messageObject );
2235 * @param string|Message $title Message key (string) for page title, or a Message object
2236 * @param string|Message $msg Message key (string) for page text, or a Message object
2237 * @param array $params Message parameters; ignored if $msg is a Message object
2239 public function showErrorPage( $title, $msg, $params = array() ) {
2240 if ( !$title instanceof Message ) {
2241 $title = $this->msg( $title );
2244 $this->prepareErrorPage( $title );
2246 if ( $msg instanceof Message ) {
2247 if ( $params !== array() ) {
2248 trigger_error( 'Argument ignored: $params. The message parameters argument '
2249 . 'is discarded when the $msg argument is a Message object instead of '
2250 . 'a string.', E_USER_NOTICE );
2252 $this->addHTML( $msg->parseAsBlock() );
2253 } else {
2254 $this->addWikiMsgArray( $msg, $params );
2257 $this->returnToMain();
2261 * Output a standard permission error page
2263 * @param array $errors Error message keys
2264 * @param string $action Action that was denied or null if unknown
2266 public function showPermissionsErrorPage( array $errors, $action = null ) {
2267 // For some action (read, edit, create and upload), display a "login to do this action"
2268 // error if all of the following conditions are met:
2269 // 1. the user is not logged in
2270 // 2. the only error is insufficient permissions (i.e. no block or something else)
2271 // 3. the error can be avoided simply by logging in
2272 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2273 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2274 && ( $errors[0][0] == 'badaccess-groups' || $errors[0][0] == 'badaccess-group0' )
2275 && ( User::groupHasPermission( 'user', $action )
2276 || User::groupHasPermission( 'autoconfirmed', $action ) )
2278 $displayReturnto = null;
2280 # Due to bug 32276, if a user does not have read permissions,
2281 # $this->getTitle() will just give Special:Badtitle, which is
2282 # not especially useful as a returnto parameter. Use the title
2283 # from the request instead, if there was one.
2284 $request = $this->getRequest();
2285 $returnto = Title::newFromURL( $request->getVal( 'title', '' ) );
2286 if ( $action == 'edit' ) {
2287 $msg = 'whitelistedittext';
2288 $displayReturnto = $returnto;
2289 } elseif ( $action == 'createpage' || $action == 'createtalk' ) {
2290 $msg = 'nocreatetext';
2291 } elseif ( $action == 'upload' ) {
2292 $msg = 'uploadnologintext';
2293 } else { # Read
2294 $msg = 'loginreqpagetext';
2295 $displayReturnto = Title::newMainPage();
2298 $query = array();
2300 if ( $returnto ) {
2301 $query['returnto'] = $returnto->getPrefixedText();
2303 if ( !$request->wasPosted() ) {
2304 $returntoquery = $request->getValues();
2305 unset( $returntoquery['title'] );
2306 unset( $returntoquery['returnto'] );
2307 unset( $returntoquery['returntoquery'] );
2308 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2311 $loginLink = Linker::linkKnown(
2312 SpecialPage::getTitleFor( 'Userlogin' ),
2313 $this->msg( 'loginreqlink' )->escaped(),
2314 array(),
2315 $query
2318 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2319 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2321 # Don't return to a page the user can't read otherwise
2322 # we'll end up in a pointless loop
2323 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2324 $this->returnToMain( null, $displayReturnto );
2326 } else {
2327 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2328 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2333 * Display an error page indicating that a given version of MediaWiki is
2334 * required to use it
2336 * @param mixed $version The version of MediaWiki needed to use the page
2338 public function versionRequired( $version ) {
2339 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2341 $this->addWikiMsg( 'versionrequiredtext', $version );
2342 $this->returnToMain();
2346 * Display an error page noting that a given permission bit is required.
2347 * @deprecated since 1.18, just throw the exception directly
2348 * @param string $permission Key required
2349 * @throws PermissionsError
2351 public function permissionRequired( $permission ) {
2352 throw new PermissionsError( $permission );
2356 * Produce the stock "please login to use the wiki" page
2358 * @deprecated since 1.19; throw the exception directly
2360 public function loginToUse() {
2361 throw new PermissionsError( 'read' );
2365 * Format a list of error messages
2367 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2368 * @param string $action Action that was denied or null if unknown
2369 * @return string The wikitext error-messages, formatted into a list.
2371 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2372 if ( $action == null ) {
2373 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2374 } else {
2375 $action_desc = $this->msg( "action-$action" )->plain();
2376 $text = $this->msg(
2377 'permissionserrorstext-withaction',
2378 count( $errors ),
2379 $action_desc
2380 )->plain() . "\n\n";
2383 if ( count( $errors ) > 1 ) {
2384 $text .= '<ul class="permissions-errors">' . "\n";
2386 foreach ( $errors as $error ) {
2387 $text .= '<li>';
2388 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2389 $text .= "</li>\n";
2391 $text .= '</ul>';
2392 } else {
2393 $text .= "<div class=\"permissions-errors\">\n" .
2394 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2395 "\n</div>";
2398 return $text;
2402 * Display a page stating that the Wiki is in read-only mode,
2403 * and optionally show the source of the page that the user
2404 * was trying to edit. Should only be called (for this
2405 * purpose) after wfReadOnly() has returned true.
2407 * For historical reasons, this function is _also_ used to
2408 * show the error message when a user tries to edit a page
2409 * they are not allowed to edit. (Unless it's because they're
2410 * blocked, then we show blockedPage() instead.) In this
2411 * case, the second parameter should be set to true and a list
2412 * of reasons supplied as the third parameter.
2414 * @todo Needs to be split into multiple functions.
2416 * @param string $source Source code to show (or null).
2417 * @param bool $protected Is this a permissions error?
2418 * @param array $reasons List of reasons for this error, as returned by
2419 * Title::getUserPermissionsErrors().
2420 * @param string $action Action that was denied or null if unknown
2421 * @throws ReadOnlyError
2423 public function readOnlyPage( $source = null, $protected = false,
2424 array $reasons = array(), $action = null
2426 $this->setRobotPolicy( 'noindex,nofollow' );
2427 $this->setArticleRelated( false );
2429 // If no reason is given, just supply a default "I can't let you do
2430 // that, Dave" message. Should only occur if called by legacy code.
2431 if ( $protected && empty( $reasons ) ) {
2432 $reasons[] = array( 'badaccess-group0' );
2435 if ( !empty( $reasons ) ) {
2436 // Permissions error
2437 if ( $source ) {
2438 $this->setPageTitle( $this->msg( 'viewsource-title', $this->getTitle()->getPrefixedText() ) );
2439 $this->addBacklinkSubtitle( $this->getTitle() );
2440 } else {
2441 $this->setPageTitle( $this->msg( 'badaccess' ) );
2443 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2444 } else {
2445 // Wiki is read only
2446 throw new ReadOnlyError;
2449 // Show source, if supplied
2450 if ( is_string( $source ) ) {
2451 $this->addWikiMsg( 'viewsourcetext' );
2453 $pageLang = $this->getTitle()->getPageLanguage();
2454 $params = array(
2455 'id' => 'wpTextbox1',
2456 'name' => 'wpTextbox1',
2457 'cols' => $this->getUser()->getOption( 'cols' ),
2458 'rows' => $this->getUser()->getOption( 'rows' ),
2459 'readonly' => 'readonly',
2460 'lang' => $pageLang->getHtmlCode(),
2461 'dir' => $pageLang->getDir(),
2463 $this->addHTML( Html::element( 'textarea', $params, $source ) );
2465 // Show templates used by this article
2466 $templates = Linker::formatTemplates( $this->getTitle()->getTemplateLinksFrom() );
2467 $this->addHTML( "<div class='templatesUsed'>
2468 $templates
2469 </div>
2470 " );
2473 # If the title doesn't exist, it's fairly pointless to print a return
2474 # link to it. After all, you just tried editing it and couldn't, so
2475 # what's there to do there?
2476 if ( $this->getTitle()->exists() ) {
2477 $this->returnToMain( null, $this->getTitle() );
2482 * Turn off regular page output and return an error response
2483 * for when rate limiting has triggered.
2485 public function rateLimited() {
2486 throw new ThrottledError;
2490 * Show a warning about slave lag
2492 * If the lag is higher than $wgSlaveLagCritical seconds,
2493 * then the warning is a bit more obvious. If the lag is
2494 * lower than $wgSlaveLagWarning, then no warning is shown.
2496 * @param int $lag Slave lag
2498 public function showLagWarning( $lag ) {
2499 $config = $this->getConfig();
2500 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2501 $message = $lag < $config->get( 'SlaveLagCritical' )
2502 ? 'lag-warn-normal'
2503 : 'lag-warn-high';
2504 $wrap = Html::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2505 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2509 public function showFatalError( $message ) {
2510 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2512 $this->addHTML( $message );
2515 public function showUnexpectedValueError( $name, $val ) {
2516 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2519 public function showFileCopyError( $old, $new ) {
2520 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2523 public function showFileRenameError( $old, $new ) {
2524 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2527 public function showFileDeleteError( $name ) {
2528 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2531 public function showFileNotFoundError( $name ) {
2532 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2536 * Add a "return to" link pointing to a specified title
2538 * @param Title $title Title to link
2539 * @param array $query Query string parameters
2540 * @param string $text Text of the link (input is not escaped)
2541 * @param array $options Options array to pass to Linker
2543 public function addReturnTo( $title, array $query = array(), $text = null, $options = array() ) {
2544 $link = $this->msg( 'returnto' )->rawParams(
2545 Linker::link( $title, $text, array(), $query, $options ) )->escaped();
2546 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2550 * Add a "return to" link pointing to a specified title,
2551 * or the title indicated in the request, or else the main page
2553 * @param mixed $unused
2554 * @param Title|string $returnto Title or String to return to
2555 * @param string $returntoquery Query string for the return to link
2557 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2558 if ( $returnto == null ) {
2559 $returnto = $this->getRequest()->getText( 'returnto' );
2562 if ( $returntoquery == null ) {
2563 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2566 if ( $returnto === '' ) {
2567 $returnto = Title::newMainPage();
2570 if ( is_object( $returnto ) ) {
2571 $titleObj = $returnto;
2572 } else {
2573 $titleObj = Title::newFromText( $returnto );
2575 if ( !is_object( $titleObj ) ) {
2576 $titleObj = Title::newMainPage();
2579 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2583 * @param Skin $sk The given Skin
2584 * @param bool $includeStyle Unused
2585 * @return string The doctype, opening "<html>", and head element.
2587 public function headElement( Skin $sk, $includeStyle = true ) {
2588 global $wgContLang;
2590 $userdir = $this->getLanguage()->getDir();
2591 $sitedir = $wgContLang->getDir();
2593 $ret = Html::htmlHeader( $sk->getHtmlElementAttributes() );
2595 if ( $this->getHTMLTitle() == '' ) {
2596 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2599 $openHead = Html::openElement( 'head' );
2600 if ( $openHead ) {
2601 # Don't bother with the newline if $head == ''
2602 $ret .= "$openHead\n";
2605 if ( !Html::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2606 // Add <meta charset="UTF-8">
2607 // This should be before <title> since it defines the charset used by
2608 // text including the text inside <title>.
2609 // The spec recommends defining XHTML5's charset using the XML declaration
2610 // instead of meta.
2611 // Our XML declaration is output by Html::htmlHeader.
2612 // http://www.whatwg.org/html/semantics.html#attr-meta-http-equiv-content-type
2613 // http://www.whatwg.org/html/semantics.html#charset
2614 $ret .= Html::element( 'meta', array( 'charset' => 'UTF-8' ) ) . "\n";
2617 $ret .= Html::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2619 foreach ( $this->getHeadLinksArray() as $item ) {
2620 $ret .= $item . "\n";
2623 // No newline after buildCssLinks since makeResourceLoaderLink did that already
2624 $ret .= $this->buildCssLinks();
2626 $ret .= $this->getHeadScripts() . "\n";
2628 foreach ( $this->mHeadItems as $item ) {
2629 $ret .= $item . "\n";
2632 $closeHead = Html::closeElement( 'head' );
2633 if ( $closeHead ) {
2634 $ret .= "$closeHead\n";
2637 $bodyClasses = array();
2638 $bodyClasses[] = 'mediawiki';
2640 # Classes for LTR/RTL directionality support
2641 $bodyClasses[] = $userdir;
2642 $bodyClasses[] = "sitedir-$sitedir";
2644 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2645 # A <body> class is probably not the best way to do this . . .
2646 $bodyClasses[] = 'capitalize-all-nouns';
2649 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2650 $bodyClasses[] = 'skin-' . Sanitizer::escapeClass( $sk->getSkinName() );
2651 $bodyClasses[] =
2652 'action-' . Sanitizer::escapeClass( Action::getActionName( $this->getContext() ) );
2654 $bodyAttrs = array();
2655 // While the implode() is not strictly needed, it's used for backwards compatibility
2656 // (this used to be built as a string and hooks likely still expect that).
2657 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2659 // Allow skins and extensions to add body attributes they need
2660 $sk->addToBodyAttributes( $this, $bodyAttrs );
2661 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2663 $ret .= Html::openElement( 'body', $bodyAttrs ) . "\n";
2665 return $ret;
2669 * Get a ResourceLoader object associated with this OutputPage
2671 * @return ResourceLoader
2673 public function getResourceLoader() {
2674 if ( is_null( $this->mResourceLoader ) ) {
2675 $this->mResourceLoader = new ResourceLoader( $this->getConfig() );
2677 return $this->mResourceLoader;
2681 * @todo Document
2682 * @param array|string $modules One or more module names
2683 * @param string $only ResourceLoaderModule TYPE_ class constant
2684 * @param bool $useESI
2685 * @param array $extraQuery Array with extra query parameters to add to each
2686 * request. array( param => value ).
2687 * @param bool $loadCall If true, output an (asynchronous) mw.loader.load()
2688 * call rather than a "<script src='...'>" tag.
2689 * @return string The html "<script>", "<link>" and "<style>" tags
2691 protected function makeResourceLoaderLink( $modules, $only, $useESI = false,
2692 array $extraQuery = array(), $loadCall = false
2694 $modules = (array)$modules;
2696 $links = array(
2697 'html' => '',
2698 'states' => array(),
2701 if ( !count( $modules ) ) {
2702 return $links;
2705 if ( count( $modules ) > 1 ) {
2706 // Remove duplicate module requests
2707 $modules = array_unique( $modules );
2708 // Sort module names so requests are more uniform
2709 sort( $modules );
2711 if ( ResourceLoader::inDebugMode() ) {
2712 // Recursively call us for every item
2713 foreach ( $modules as $name ) {
2714 $link = $this->makeResourceLoaderLink( $name, $only, $useESI );
2715 $links['html'] .= $link['html'];
2716 $links['states'] += $link['states'];
2718 return $links;
2722 if ( !is_null( $this->mTarget ) ) {
2723 $extraQuery['target'] = $this->mTarget;
2726 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
2727 $sortedModules = array();
2728 $resourceLoader = $this->getResourceLoader();
2729 $resourceLoaderUseESI = $this->getConfig()->get( 'ResourceLoaderUseESI' );
2730 foreach ( $modules as $name ) {
2731 $module = $resourceLoader->getModule( $name );
2732 # Check that we're allowed to include this module on this page
2733 if ( !$module
2734 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_SCRIPTS )
2735 && $only == ResourceLoaderModule::TYPE_SCRIPTS )
2736 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_STYLES )
2737 && $only == ResourceLoaderModule::TYPE_STYLES )
2738 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_COMBINED )
2739 && $only == ResourceLoaderModule::TYPE_COMBINED )
2740 || ( $this->mTarget && !in_array( $this->mTarget, $module->getTargets() ) )
2742 continue;
2745 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
2748 foreach ( $sortedModules as $source => $groups ) {
2749 foreach ( $groups as $group => $grpModules ) {
2750 // Special handling for user-specific groups
2751 $user = null;
2752 if ( ( $group === 'user' || $group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2753 $user = $this->getUser()->getName();
2756 // Create a fake request based on the one we are about to make so modules return
2757 // correct timestamp and emptiness data
2758 $query = ResourceLoader::makeLoaderQuery(
2759 array(), // modules; not determined yet
2760 $this->getLanguage()->getCode(),
2761 $this->getSkin()->getSkinName(),
2762 $user,
2763 null, // version; not determined yet
2764 ResourceLoader::inDebugMode(),
2765 $only === ResourceLoaderModule::TYPE_COMBINED ? null : $only,
2766 $this->isPrintable(),
2767 $this->getRequest()->getBool( 'handheld' ),
2768 $extraQuery
2770 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2772 // Extract modules that know they're empty
2773 foreach ( $grpModules as $key => $module ) {
2774 // Inline empty modules: since they're empty, just mark them as 'ready' (bug 46857)
2775 // If we're only getting the styles, we don't need to do anything for empty modules.
2776 if ( $module->isKnownEmpty( $context ) ) {
2777 unset( $grpModules[$key] );
2778 if ( $only !== ResourceLoaderModule::TYPE_STYLES ) {
2779 $links['states'][$key] = 'ready';
2784 // If there are no non-empty modules, skip this group
2785 if ( count( $grpModules ) === 0 ) {
2786 continue;
2789 // Inline private modules. These can't be loaded through load.php for security
2790 // reasons, see bug 34907. Note that these modules should be loaded from
2791 // getHeadScripts() before the first loader call. Otherwise other modules can't
2792 // properly use them as dependencies (bug 30914)
2793 if ( $group === 'private' ) {
2794 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
2795 $links['html'] .= Html::inlineStyle(
2796 $resourceLoader->makeModuleResponse( $context, $grpModules )
2798 } else {
2799 $links['html'] .= Html::inlineScript(
2800 ResourceLoader::makeLoaderConditionalScript(
2801 $resourceLoader->makeModuleResponse( $context, $grpModules )
2805 $links['html'] .= "\n";
2806 continue;
2809 // Special handling for the user group; because users might change their stuff
2810 // on-wiki like user pages, or user preferences; we need to find the highest
2811 // timestamp of these user-changeable modules so we can ensure cache misses on change
2812 // This should NOT be done for the site group (bug 27564) because anons get that too
2813 // and we shouldn't be putting timestamps in Squid-cached HTML
2814 $version = null;
2815 if ( $group === 'user' ) {
2816 // Get the maximum timestamp
2817 $timestamp = 1;
2818 foreach ( $grpModules as $module ) {
2819 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2821 // Add a version parameter so cache will break when things change
2822 $query['version'] = wfTimestamp( TS_ISO_8601_BASIC, $timestamp );
2825 $query['modules'] = ResourceLoader::makePackedModulesString( array_keys( $grpModules ) );
2826 $moduleContext = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2827 $url = $resourceLoader->createLoaderURL( $source, $moduleContext, $extraQuery );
2829 if ( $useESI && $resourceLoaderUseESI ) {
2830 $esi = Xml::element( 'esi:include', array( 'src' => $url ) );
2831 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
2832 $link = Html::inlineStyle( $esi );
2833 } else {
2834 $link = Html::inlineScript( $esi );
2836 } else {
2837 // Automatically select style/script elements
2838 if ( $only === ResourceLoaderModule::TYPE_STYLES ) {
2839 $link = Html::linkedStyle( $url );
2840 } elseif ( $loadCall ) {
2841 $link = Html::inlineScript(
2842 ResourceLoader::makeLoaderConditionalScript(
2843 Xml::encodeJsCall( 'mw.loader.load', array( $url, 'text/javascript', true ) )
2846 } else {
2847 $link = Html::linkedScript( $url );
2849 // For modules requested directly in the html via <link> or <script>,
2850 // tell mw.loader they are being loading to prevent duplicate requests.
2851 foreach ( $grpModules as $key => $module ) {
2852 // Don't output state=loading for the startup module..
2853 if ( $key !== 'startup' ) {
2854 $links['states'][$key] = 'loading';
2860 if ( $group == 'noscript' ) {
2861 $links['html'] .= Html::rawElement( 'noscript', array(), $link ) . "\n";
2862 } else {
2863 $links['html'] .= $link . "\n";
2868 return $links;
2872 * Build html output from an array of links from makeResourceLoaderLink.
2873 * @param array $links
2874 * @return string HTML
2876 protected static function getHtmlFromLoaderLinks( array $links ) {
2877 $html = '';
2878 $states = array();
2879 foreach ( $links as $link ) {
2880 if ( !is_array( $link ) ) {
2881 $html .= $link;
2882 } else {
2883 $html .= $link['html'];
2884 $states += $link['states'];
2888 if ( count( $states ) ) {
2889 $html = Html::inlineScript(
2890 ResourceLoader::makeLoaderConditionalScript(
2891 ResourceLoader::makeLoaderStateScript( $states )
2893 ) . "\n" . $html;
2896 return $html;
2900 * JS stuff to put in the "<head>". This is the startup module, config
2901 * vars and modules marked with position 'top'
2903 * @return string HTML fragment
2905 function getHeadScripts() {
2906 // Startup - this will immediately load jquery and mediawiki modules
2907 $links = array();
2908 $links[] = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule::TYPE_SCRIPTS, true );
2910 // Load config before anything else
2911 $links[] = Html::inlineScript(
2912 ResourceLoader::makeLoaderConditionalScript(
2913 ResourceLoader::makeConfigSetScript( $this->getJSVars() )
2917 // Load embeddable private modules before any loader links
2918 // This needs to be TYPE_COMBINED so these modules are properly wrapped
2919 // in mw.loader.implement() calls and deferred until mw.user is available
2920 $embedScripts = array( 'user.options', 'user.tokens' );
2921 $links[] = $this->makeResourceLoaderLink( $embedScripts, ResourceLoaderModule::TYPE_COMBINED );
2923 // Scripts and messages "only" requests marked for top inclusion
2924 // Messages should go first
2925 $links[] = $this->makeResourceLoaderLink(
2926 $this->getModuleMessages( true, 'top' ),
2927 ResourceLoaderModule::TYPE_MESSAGES
2929 $links[] = $this->makeResourceLoaderLink(
2930 $this->getModuleScripts( true, 'top' ),
2931 ResourceLoaderModule::TYPE_SCRIPTS
2934 // Modules requests - let the client calculate dependencies and batch requests as it likes
2935 // Only load modules that have marked themselves for loading at the top
2936 $modules = $this->getModules( true, 'top' );
2937 if ( $modules ) {
2938 $links[] = Html::inlineScript(
2939 ResourceLoader::makeLoaderConditionalScript(
2940 Xml::encodeJsCall( 'mw.loader.load', array( $modules ) )
2945 if ( $this->getConfig()->get( 'ResourceLoaderExperimentalAsyncLoading' ) ) {
2946 $links[] = $this->getScriptsForBottomQueue( true );
2949 return self::getHtmlFromLoaderLinks( $links );
2953 * JS stuff to put at the 'bottom', which can either be the bottom of the
2954 * "<body>" or the bottom of the "<head>" depending on
2955 * $wgResourceLoaderExperimentalAsyncLoading: modules marked with position
2956 * 'bottom', legacy scripts ($this->mScripts), user preferences, site JS
2957 * and user JS.
2959 * @param bool $inHead If true, this HTML goes into the "<head>",
2960 * if false it goes into the "<body>".
2961 * @return string
2963 function getScriptsForBottomQueue( $inHead ) {
2964 // Scripts and messages "only" requests marked for bottom inclusion
2965 // If we're in the <head>, use load() calls rather than <script src="..."> tags
2966 // Messages should go first
2967 $links = array();
2968 $links[] = $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'bottom' ),
2969 ResourceLoaderModule::TYPE_MESSAGES, /* $useESI = */ false, /* $extraQuery = */ array(),
2970 /* $loadCall = */ $inHead
2972 $links[] = $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
2973 ResourceLoaderModule::TYPE_SCRIPTS, /* $useESI = */ false, /* $extraQuery = */ array(),
2974 /* $loadCall = */ $inHead
2977 // Modules requests - let the client calculate dependencies and batch requests as it likes
2978 // Only load modules that have marked themselves for loading at the bottom
2979 $modules = $this->getModules( true, 'bottom' );
2980 if ( $modules ) {
2981 $links[] = Html::inlineScript(
2982 ResourceLoader::makeLoaderConditionalScript(
2983 Xml::encodeJsCall( 'mw.loader.load', array( $modules, null, true ) )
2988 // Legacy Scripts
2989 $links[] = "\n" . $this->mScripts;
2991 // Add site JS if enabled
2992 $links[] = $this->makeResourceLoaderLink( 'site', ResourceLoaderModule::TYPE_SCRIPTS,
2993 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2996 // Add user JS if enabled
2997 if ( $this->getConfig()->get( 'AllowUserJs' )
2998 && $this->getUser()->isLoggedIn()
2999 && $this->getTitle()
3000 && $this->getTitle()->isJsSubpage()
3001 && $this->userCanPreview()
3003 # XXX: additional security check/prompt?
3004 // We're on a preview of a JS subpage
3005 // Exclude this page from the user module in case it's in there (bug 26283)
3006 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_SCRIPTS, false,
3007 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() ), $inHead
3009 // Load the previewed JS
3010 $links[] = Html::inlineScript( "\n"
3011 . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
3013 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
3014 // asynchronously and may arrive *after* the inline script here. So the previewed code
3015 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js...
3016 } else {
3017 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
3018 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_SCRIPTS,
3019 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3023 // Group JS is only enabled if site JS is enabled.
3024 $links[] = $this->makeResourceLoaderLink( 'user.groups', ResourceLoaderModule::TYPE_COMBINED,
3025 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3028 return self::getHtmlFromLoaderLinks( $links );
3032 * JS stuff to put at the bottom of the "<body>"
3033 * @return string
3035 function getBottomScripts() {
3036 // Optimise jQuery ready event cross-browser.
3037 // This also enforces $.isReady to be true at </body> which fixes the
3038 // mw.loader bug in Firefox with using document.write between </body>
3039 // and the DOMContentReady event (bug 47457).
3040 $html = Html::inlineScript( 'window.jQuery && jQuery.ready();' );
3042 if ( !$this->getConfig()->get( 'ResourceLoaderExperimentalAsyncLoading' ) ) {
3043 $html .= $this->getScriptsForBottomQueue( false );
3046 return $html;
3050 * Get the javascript config vars to include on this page
3052 * @return array Array of javascript config vars
3053 * @since 1.23
3055 public function getJsConfigVars() {
3056 return $this->mJsConfigVars;
3060 * Add one or more variables to be set in mw.config in JavaScript
3062 * @param string|array $keys Key or array of key/value pairs
3063 * @param mixed $value [optional] Value of the configuration variable
3065 public function addJsConfigVars( $keys, $value = null ) {
3066 if ( is_array( $keys ) ) {
3067 foreach ( $keys as $key => $value ) {
3068 $this->mJsConfigVars[$key] = $value;
3070 return;
3073 $this->mJsConfigVars[$keys] = $value;
3077 * Get an array containing the variables to be set in mw.config in JavaScript.
3079 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3080 * - in other words, page-independent/site-wide variables (without state).
3081 * You will only be adding bloat to the html page and causing page caches to
3082 * have to be purged on configuration changes.
3083 * @return array
3085 private function getJSVars() {
3086 global $wgContLang;
3088 $curRevisionId = 0;
3089 $articleId = 0;
3090 $canonicalSpecialPageName = false; # bug 21115
3092 $title = $this->getTitle();
3093 $ns = $title->getNamespace();
3094 $canonicalNamespace = MWNamespace::exists( $ns )
3095 ? MWNamespace::getCanonicalName( $ns )
3096 : $title->getNsText();
3098 $sk = $this->getSkin();
3099 // Get the relevant title so that AJAX features can use the correct page name
3100 // when making API requests from certain special pages (bug 34972).
3101 $relevantTitle = $sk->getRelevantTitle();
3102 $relevantUser = $sk->getRelevantUser();
3104 if ( $ns == NS_SPECIAL ) {
3105 list( $canonicalSpecialPageName, /*...*/ ) =
3106 SpecialPageFactory::resolveAlias( $title->getDBkey() );
3107 } elseif ( $this->canUseWikiPage() ) {
3108 $wikiPage = $this->getWikiPage();
3109 $curRevisionId = $wikiPage->getLatest();
3110 $articleId = $wikiPage->getId();
3113 $lang = $title->getPageLanguage();
3115 // Pre-process information
3116 $separatorTransTable = $lang->separatorTransformTable();
3117 $separatorTransTable = $separatorTransTable ? $separatorTransTable : array();
3118 $compactSeparatorTransTable = array(
3119 implode( "\t", array_keys( $separatorTransTable ) ),
3120 implode( "\t", $separatorTransTable ),
3122 $digitTransTable = $lang->digitTransformTable();
3123 $digitTransTable = $digitTransTable ? $digitTransTable : array();
3124 $compactDigitTransTable = array(
3125 implode( "\t", array_keys( $digitTransTable ) ),
3126 implode( "\t", $digitTransTable ),
3129 $user = $this->getUser();
3131 $vars = array(
3132 'wgCanonicalNamespace' => $canonicalNamespace,
3133 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3134 'wgNamespaceNumber' => $title->getNamespace(),
3135 'wgPageName' => $title->getPrefixedDBkey(),
3136 'wgTitle' => $title->getText(),
3137 'wgCurRevisionId' => $curRevisionId,
3138 'wgRevisionId' => (int)$this->getRevisionId(),
3139 'wgArticleId' => $articleId,
3140 'wgIsArticle' => $this->isArticle(),
3141 'wgIsRedirect' => $title->isRedirect(),
3142 'wgAction' => Action::getActionName( $this->getContext() ),
3143 'wgUserName' => $user->isAnon() ? null : $user->getName(),
3144 'wgUserGroups' => $user->getEffectiveGroups(),
3145 'wgCategories' => $this->getCategories(),
3146 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3147 'wgPageContentLanguage' => $lang->getCode(),
3148 'wgPageContentModel' => $title->getContentModel(),
3149 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3150 'wgDigitTransformTable' => $compactDigitTransTable,
3151 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3152 'wgMonthNames' => $lang->getMonthNamesArray(),
3153 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3154 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3157 if ( $user->isLoggedIn() ) {
3158 $vars['wgUserId'] = $user->getId();
3159 $vars['wgUserEditCount'] = $user->getEditCount();
3160 $userReg = wfTimestampOrNull( TS_UNIX, $user->getRegistration() );
3161 $vars['wgUserRegistration'] = $userReg !== null ? ( $userReg * 1000 ) : null;
3162 // Get the revision ID of the oldest new message on the user's talk
3163 // page. This can be used for constructing new message alerts on
3164 // the client side.
3165 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3168 if ( $wgContLang->hasVariants() ) {
3169 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3171 // Same test as SkinTemplate
3172 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3173 && ( $title->exists() || $title->quickUserCan( 'create', $user ) );
3175 foreach ( $title->getRestrictionTypes() as $type ) {
3176 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3179 if ( $title->isMainPage() ) {
3180 $vars['wgIsMainPage'] = true;
3183 if ( $this->mRedirectedFrom ) {
3184 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom->getPrefixedDBkey();
3187 if ( $relevantUser ) {
3188 $vars['wgRelevantUserName'] = $relevantUser->getName();
3191 // Allow extensions to add their custom variables to the mw.config map.
3192 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3193 // page-dependant but site-wide (without state).
3194 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3195 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
3197 // Merge in variables from addJsConfigVars last
3198 return array_merge( $vars, $this->getJsConfigVars() );
3202 * To make it harder for someone to slip a user a fake
3203 * user-JavaScript or user-CSS preview, a random token
3204 * is associated with the login session. If it's not
3205 * passed back with the preview request, we won't render
3206 * the code.
3208 * @return bool
3210 public function userCanPreview() {
3211 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
3212 || !$this->getRequest()->wasPosted()
3213 || !$this->getUser()->matchEditToken(
3214 $this->getRequest()->getVal( 'wpEditToken' ) )
3216 return false;
3218 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
3219 return false;
3222 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
3226 * @return array Array in format "link name or number => 'link html'".
3228 public function getHeadLinksArray() {
3229 global $wgVersion;
3231 $tags = array();
3232 $config = $this->getConfig();
3234 $canonicalUrl = $this->mCanonicalUrl;
3236 $tags['meta-generator'] = Html::element( 'meta', array(
3237 'name' => 'generator',
3238 'content' => "MediaWiki $wgVersion",
3239 ) );
3241 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3242 if ( $p !== 'index,follow' ) {
3243 // http://www.robotstxt.org/wc/meta-user.html
3244 // Only show if it's different from the default robots policy
3245 $tags['meta-robots'] = Html::element( 'meta', array(
3246 'name' => 'robots',
3247 'content' => $p,
3248 ) );
3251 foreach ( $this->mMetatags as $tag ) {
3252 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3253 $a = 'http-equiv';
3254 $tag[0] = substr( $tag[0], 5 );
3255 } else {
3256 $a = 'name';
3258 $tagName = "meta-{$tag[0]}";
3259 if ( isset( $tags[$tagName] ) ) {
3260 $tagName .= $tag[1];
3262 $tags[$tagName] = Html::element( 'meta',
3263 array(
3264 $a => $tag[0],
3265 'content' => $tag[1]
3270 foreach ( $this->mLinktags as $tag ) {
3271 $tags[] = Html::element( 'link', $tag );
3274 # Universal edit button
3275 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3276 $user = $this->getUser();
3277 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3278 && ( $this->getTitle()->exists() || $this->getTitle()->quickUserCan( 'create', $user ) ) ) {
3279 // Original UniversalEditButton
3280 $msg = $this->msg( 'edit' )->text();
3281 $tags['universal-edit-button'] = Html::element( 'link', array(
3282 'rel' => 'alternate',
3283 'type' => 'application/x-wiki',
3284 'title' => $msg,
3285 'href' => $this->getTitle()->getEditURL(),
3286 ) );
3287 // Alternate edit link
3288 $tags['alternative-edit'] = Html::element( 'link', array(
3289 'rel' => 'edit',
3290 'title' => $msg,
3291 'href' => $this->getTitle()->getEditURL(),
3292 ) );
3296 # Generally the order of the favicon and apple-touch-icon links
3297 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3298 # uses whichever one appears later in the HTML source. Make sure
3299 # apple-touch-icon is specified first to avoid this.
3300 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3301 $tags['apple-touch-icon'] = Html::element( 'link', array(
3302 'rel' => 'apple-touch-icon',
3303 'href' => $config->get( 'AppleTouchIcon' )
3304 ) );
3307 if ( $config->get( 'Favicon' ) !== false ) {
3308 $tags['favicon'] = Html::element( 'link', array(
3309 'rel' => 'shortcut icon',
3310 'href' => $config->get( 'Favicon' )
3311 ) );
3314 # OpenSearch description link
3315 $tags['opensearch'] = Html::element( 'link', array(
3316 'rel' => 'search',
3317 'type' => 'application/opensearchdescription+xml',
3318 'href' => wfScript( 'opensearch_desc' ),
3319 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3320 ) );
3322 if ( $config->get( 'EnableAPI' ) ) {
3323 # Real Simple Discovery link, provides auto-discovery information
3324 # for the MediaWiki API (and potentially additional custom API
3325 # support such as WordPress or Twitter-compatible APIs for a
3326 # blogging extension, etc)
3327 $tags['rsd'] = Html::element( 'link', array(
3328 'rel' => 'EditURI',
3329 'type' => 'application/rsd+xml',
3330 // Output a protocol-relative URL here if $wgServer is protocol-relative
3331 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
3332 'href' => wfExpandUrl( wfAppendQuery(
3333 wfScript( 'api' ),
3334 array( 'action' => 'rsd' ) ),
3335 PROTO_RELATIVE
3337 ) );
3340 # Language variants
3341 if ( !$config->get( 'DisableLangConversion' ) ) {
3342 $lang = $this->getTitle()->getPageLanguage();
3343 if ( $lang->hasVariants() ) {
3344 $variants = $lang->getVariants();
3345 foreach ( $variants as $_v ) {
3346 $tags["variant-$_v"] = Html::element( 'link', array(
3347 'rel' => 'alternate',
3348 'hreflang' => wfBCP47( $_v ),
3349 'href' => $this->getTitle()->getLocalURL( array( 'variant' => $_v ) ) )
3353 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3354 $tags["variant-x-default"] = Html::element( 'link', array(
3355 'rel' => 'alternate',
3356 'hreflang' => 'x-default',
3357 'href' => $this->getTitle()->getLocalURL() ) );
3360 # Copyright
3361 $copyright = '';
3362 if ( $config->get( 'RightsPage' ) ) {
3363 $copy = Title::newFromText( $config->get( 'RightsPage' ) );
3365 if ( $copy ) {
3366 $copyright = $copy->getLocalURL();
3370 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3371 $copyright = $config->get( 'RightsUrl' );
3374 if ( $copyright ) {
3375 $tags['copyright'] = Html::element( 'link', array(
3376 'rel' => 'copyright',
3377 'href' => $copyright )
3381 # Feeds
3382 if ( $config->get( 'Feed' ) ) {
3383 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3384 # Use the page name for the title. In principle, this could
3385 # lead to issues with having the same name for different feeds
3386 # corresponding to the same page, but we can't avoid that at
3387 # this low a level.
3389 $tags[] = $this->feedLink(
3390 $format,
3391 $link,
3392 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3393 $this->msg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )->text()
3397 # Recent changes feed should appear on every page (except recentchanges,
3398 # that would be redundant). Put it after the per-page feed to avoid
3399 # changing existing behavior. It's still available, probably via a
3400 # menu in your browser. Some sites might have a different feed they'd
3401 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3402 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3403 # If so, use it instead.
3404 $sitename = $config->get( 'Sitename' );
3405 if ( $config->get( 'OverrideSiteFeed' ) ) {
3406 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3407 // Note, this->feedLink escapes the url.
3408 $tags[] = $this->feedLink(
3409 $type,
3410 $feedUrl,
3411 $this->msg( "site-{$type}-feed", $sitename )->text()
3414 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3415 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
3416 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3417 $tags[] = $this->feedLink(
3418 $format,
3419 $rctitle->getLocalURL( array( 'feed' => $format ) ),
3420 # For grep: 'site-rss-feed', 'site-atom-feed'
3421 $this->msg( "site-{$format}-feed", $sitename )->text()
3427 # Canonical URL
3428 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3429 if ( $canonicalUrl !== false ) {
3430 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL );
3431 } else {
3432 $reqUrl = $this->getRequest()->getRequestURL();
3433 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL );
3436 if ( $canonicalUrl !== false ) {
3437 $tags[] = Html::element( 'link', array(
3438 'rel' => 'canonical',
3439 'href' => $canonicalUrl
3440 ) );
3443 return $tags;
3447 * @return string HTML tag links to be put in the header.
3448 * @deprecated since 1.24 Use OutputPage::headElement or if you have to,
3449 * OutputPage::getHeadLinksArray directly.
3451 public function getHeadLinks() {
3452 wfDeprecated( __METHOD__, '1.24' );
3453 return implode( "\n", $this->getHeadLinksArray() );
3457 * Generate a "<link rel/>" for a feed.
3459 * @param string $type Feed type
3460 * @param string $url URL to the feed
3461 * @param string $text Value of the "title" attribute
3462 * @return string HTML fragment
3464 private function feedLink( $type, $url, $text ) {
3465 return Html::element( 'link', array(
3466 'rel' => 'alternate',
3467 'type' => "application/$type+xml",
3468 'title' => $text,
3469 'href' => $url )
3474 * Add a local or specified stylesheet, with the given media options.
3475 * Meant primarily for internal use...
3477 * @param string $style URL to the file
3478 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3479 * @param string $condition For IE conditional comments, specifying an IE version
3480 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3482 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3483 $options = array();
3484 // Even though we expect the media type to be lowercase, but here we
3485 // force it to lowercase to be safe.
3486 if ( $media ) {
3487 $options['media'] = $media;
3489 if ( $condition ) {
3490 $options['condition'] = $condition;
3492 if ( $dir ) {
3493 $options['dir'] = $dir;
3495 $this->styles[$style] = $options;
3499 * Adds inline CSS styles
3500 * @param mixed $style_css Inline CSS
3501 * @param string $flip Set to 'flip' to flip the CSS if needed
3503 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3504 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3505 # If wanted, and the interface is right-to-left, flip the CSS
3506 $style_css = CSSJanus::transform( $style_css, true, false );
3507 } else {
3508 $style_css = CSSJanus::nullTransform( $style_css );
3510 $this->mInlineStyles .= Html::inlineStyle( $style_css ) . "\n";
3514 * Build a set of "<link>" elements for the stylesheets specified in the $this->styles array.
3515 * These will be applied to various media & IE conditionals.
3517 * @return string
3519 public function buildCssLinks() {
3520 global $wgContLang;
3522 $this->getSkin()->setupSkinUserCss( $this );
3524 // Add ResourceLoader styles
3525 // Split the styles into these groups
3526 $styles = array(
3527 'other' => array(),
3528 'user' => array(),
3529 'site' => array(),
3530 'private' => array(),
3531 'noscript' => array()
3533 $links = array();
3534 $otherTags = ''; // Tags to append after the normal <link> tags
3535 $resourceLoader = $this->getResourceLoader();
3537 $moduleStyles = $this->getModuleStyles();
3539 // Per-site custom styles
3540 $moduleStyles[] = 'site';
3541 $moduleStyles[] = 'noscript';
3542 $moduleStyles[] = 'user.groups';
3544 // Per-user custom styles
3545 if ( $this->getConfig()->get( 'AllowUserCss' ) && $this->getTitle()->isCssSubpage() && $this->userCanPreview() ) {
3546 // We're on a preview of a CSS subpage
3547 // Exclude this page from the user module in case it's in there (bug 26283)
3548 $link = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_STYLES, false,
3549 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3551 $otherTags .= $link['html'];
3553 // Load the previewed CSS
3554 // If needed, Janus it first. This is user-supplied CSS, so it's
3555 // assumed to be right for the content language directionality.
3556 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3557 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3558 $previewedCSS = CSSJanus::transform( $previewedCSS, true, false );
3559 } else {
3560 $previewedCSS = CSSJanus::nullTransform( $previewedCSS );
3562 $otherTags .= Html::inlineStyle( $previewedCSS ) . "\n";
3563 } else {
3564 // Load the user styles normally
3565 $moduleStyles[] = 'user';
3568 // Per-user preference styles
3569 $moduleStyles[] = 'user.cssprefs';
3571 foreach ( $moduleStyles as $name ) {
3572 $module = $resourceLoader->getModule( $name );
3573 if ( !$module ) {
3574 continue;
3576 $group = $module->getGroup();
3577 // Modules in groups different than the ones listed on top (see $styles assignment)
3578 // will be placed in the "other" group
3579 $styles[isset( $styles[$group] ) ? $group : 'other'][] = $name;
3582 // We want site, private and user styles to override dynamically added
3583 // styles from modules, but we want dynamically added styles to override
3584 // statically added styles from other modules. So the order has to be
3585 // other, dynamic, site, private, user. Add statically added styles for
3586 // other modules
3587 $links[] = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule::TYPE_STYLES );
3588 // Add normal styles added through addStyle()/addInlineStyle() here
3589 $links[] = implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles;
3590 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3591 // We use a <meta> tag with a made-up name for this because that's valid HTML
3592 $links[] = Html::element(
3593 'meta',
3594 array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' )
3595 ) . "\n";
3597 // Add site, private and user styles
3598 // 'private' at present only contains user.options, so put that before 'user'
3599 // Any future private modules will likely have a similar user-specific character
3600 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3601 $links[] = $this->makeResourceLoaderLink( $styles[$group],
3602 ResourceLoaderModule::TYPE_STYLES
3606 // Add stuff in $otherTags (previewed user CSS if applicable)
3607 return self::getHtmlFromLoaderLinks( $links ) . $otherTags;
3611 * @return array
3613 public function buildCssLinksArray() {
3614 $links = array();
3616 // Add any extension CSS
3617 foreach ( $this->mExtStyles as $url ) {
3618 $this->addStyle( $url );
3620 $this->mExtStyles = array();
3622 foreach ( $this->styles as $file => $options ) {
3623 $link = $this->styleLink( $file, $options );
3624 if ( $link ) {
3625 $links[$file] = $link;
3628 return $links;
3632 * Generate \<link\> tags for stylesheets
3634 * @param string $style URL to the file
3635 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3636 * @return string HTML fragment
3638 protected function styleLink( $style, array $options ) {
3639 if ( isset( $options['dir'] ) ) {
3640 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3641 return '';
3645 if ( isset( $options['media'] ) ) {
3646 $media = self::transformCssMedia( $options['media'] );
3647 if ( is_null( $media ) ) {
3648 return '';
3650 } else {
3651 $media = 'all';
3654 if ( substr( $style, 0, 1 ) == '/' ||
3655 substr( $style, 0, 5 ) == 'http:' ||
3656 substr( $style, 0, 6 ) == 'https:' ) {
3657 $url = $style;
3658 } else {
3659 $config = $this->getConfig();
3660 $url = $config->get( 'StylePath' ) . '/' . $style . '?' . $config->get( 'StyleVersion' );
3663 $link = Html::linkedStyle( $url, $media );
3665 if ( isset( $options['condition'] ) ) {
3666 $condition = htmlspecialchars( $options['condition'] );
3667 $link = "<!--[if $condition]>$link<![endif]-->";
3669 return $link;
3673 * Transform "media" attribute based on request parameters
3675 * @param string $media Current value of the "media" attribute
3676 * @return string Modified value of the "media" attribute, or null to skip
3677 * this stylesheet
3679 public static function transformCssMedia( $media ) {
3680 global $wgRequest;
3682 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3683 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3685 // Switch in on-screen display for media testing
3686 $switches = array(
3687 'printable' => 'print',
3688 'handheld' => 'handheld',
3690 foreach ( $switches as $switch => $targetMedia ) {
3691 if ( $wgRequest->getBool( $switch ) ) {
3692 if ( $media == $targetMedia ) {
3693 $media = '';
3694 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3695 // This regex will not attempt to understand a comma-separated media_query_list
3697 // Example supported values for $media:
3698 // 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3699 // Example NOT supported value for $media:
3700 // '3d-glasses, screen, print and resolution > 90dpi'
3702 // If it's a print request, we never want any kind of screen stylesheets
3703 // If it's a handheld request (currently the only other choice with a switch),
3704 // we don't want simple 'screen' but we might want screen queries that
3705 // have a max-width or something, so we'll pass all others on and let the
3706 // client do the query.
3707 if ( $targetMedia == 'print' || $media == 'screen' ) {
3708 return null;
3714 return $media;
3718 * Add a wikitext-formatted message to the output.
3719 * This is equivalent to:
3721 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3723 public function addWikiMsg( /*...*/ ) {
3724 $args = func_get_args();
3725 $name = array_shift( $args );
3726 $this->addWikiMsgArray( $name, $args );
3730 * Add a wikitext-formatted message to the output.
3731 * Like addWikiMsg() except the parameters are taken as an array
3732 * instead of a variable argument list.
3734 * @param string $name
3735 * @param array $args
3737 public function addWikiMsgArray( $name, $args ) {
3738 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3742 * This function takes a number of message/argument specifications, wraps them in
3743 * some overall structure, and then parses the result and adds it to the output.
3745 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3746 * on. The subsequent arguments may either be strings, in which case they are the
3747 * message names, or arrays, in which case the first element is the message name,
3748 * and subsequent elements are the parameters to that message.
3750 * Don't use this for messages that are not in users interface language.
3752 * For example:
3754 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3756 * Is equivalent to:
3758 * $wgOut->addWikiText( "<div class='error'>\n"
3759 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3761 * The newline after opening div is needed in some wikitext. See bug 19226.
3763 * @param string $wrap
3765 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3766 $msgSpecs = func_get_args();
3767 array_shift( $msgSpecs );
3768 $msgSpecs = array_values( $msgSpecs );
3769 $s = $wrap;
3770 foreach ( $msgSpecs as $n => $spec ) {
3771 if ( is_array( $spec ) ) {
3772 $args = $spec;
3773 $name = array_shift( $args );
3774 if ( isset( $args['options'] ) ) {
3775 unset( $args['options'] );
3776 wfDeprecated(
3777 'Adding "options" to ' . __METHOD__ . ' is no longer supported',
3778 '1.20'
3781 } else {
3782 $args = array();
3783 $name = $spec;
3785 $s = str_replace( '$' . ( $n + 1 ), $this->msg( $name, $args )->plain(), $s );
3787 $this->addWikiText( $s );
3791 * Include jQuery core. Use this to avoid loading it multiple times
3792 * before we get a usable script loader.
3794 * @param array $modules List of jQuery modules which should be loaded
3795 * @return array The list of modules which were not loaded.
3796 * @since 1.16
3797 * @deprecated since 1.17
3799 public function includeJQuery( array $modules = array() ) {
3800 return array();
3804 * Enables/disables TOC, doesn't override __NOTOC__
3805 * @param bool $flag
3806 * @since 1.22
3808 public function enableTOC( $flag = true ) {
3809 $this->mEnableTOC = $flag;
3813 * @return bool
3814 * @since 1.22
3816 public function isTOCEnabled() {
3817 return $this->mEnableTOC;
3821 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3822 * @param bool $flag
3823 * @since 1.23
3825 public function enableSectionEditLinks( $flag = true ) {
3826 $this->mEnableSectionEditLinks = $flag;
3830 * @return bool
3831 * @since 1.23
3833 public function sectionEditLinksEnabled() {
3834 return $this->mEnableSectionEditLinks;