Remove AjaxAddScript hook
[mediawiki.git] / includes / OutputPage.php
blob6163a8def5625612d8a55b9e176f7606f67abdad
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 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.
315 function __construct( IContextSource $context = null ) {
316 if ( $context === null ) {
317 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
318 wfDeprecated( __METHOD__, '1.18' );
319 } else {
320 $this->setContext( $context );
325 * Redirect to $url rather than displaying the normal page
327 * @param string $url URL
328 * @param string $responsecode HTTP status code
330 public function redirect( $url, $responsecode = '302' ) {
331 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
332 $this->mRedirect = str_replace( "\n", '', $url );
333 $this->mRedirectCode = $responsecode;
337 * Get the URL to redirect to, or an empty string if not redirect URL set
339 * @return string
341 public function getRedirect() {
342 return $this->mRedirect;
346 * Set the HTTP status code to send with the output.
348 * @param int $statusCode
350 public function setStatusCode( $statusCode ) {
351 $this->mStatusCode = $statusCode;
355 * Add a new "<meta>" tag
356 * To add an http-equiv meta tag, precede the name with "http:"
358 * @param string $name tag name
359 * @param string $val tag value
361 function addMeta( $name, $val ) {
362 array_push( $this->mMetatags, array( $name, $val ) );
366 * Add a new \<link\> tag to the page header.
368 * Note: use setCanonicalUrl() for rel=canonical.
370 * @param array $linkarr associative array of attributes.
372 function addLink( $linkarr ) {
373 array_push( $this->mLinktags, $linkarr );
377 * Add a new \<link\> with "rel" attribute set to "meta"
379 * @param array $linkarr associative array mapping attribute names to their
380 * values, both keys and values will be escaped, and the
381 * "rel" attribute will be automatically added
383 function addMetadataLink( $linkarr ) {
384 $linkarr['rel'] = $this->getMetadataAttribute();
385 $this->addLink( $linkarr );
389 * Set the URL to be used for the <link rel=canonical>. This should be used
390 * in preference to addLink(), to avoid duplicate link tags.
392 function setCanonicalUrl( $url ) {
393 $this->mCanonicalUrl = $url;
397 * Get the value of the "rel" attribute for metadata links
399 * @return string
401 public function getMetadataAttribute() {
402 # note: buggy CC software only reads first "meta" link
403 static $haveMeta = false;
404 if ( $haveMeta ) {
405 return 'alternate meta';
406 } else {
407 $haveMeta = true;
408 return 'meta';
413 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
415 * @param string $script raw HTML
417 function addScript( $script ) {
418 $this->mScripts .= $script . "\n";
422 * Register and add a stylesheet from an extension directory.
424 * @param string $url path to sheet. Provide either a full url (beginning
425 * with 'http', etc) or a relative path from the document root
426 * (beginning with '/'). Otherwise it behaves identically to
427 * addStyle() and draws from the /skins folder.
429 public function addExtensionStyle( $url ) {
430 array_push( $this->mExtStyles, $url );
434 * Get all styles added by extensions
436 * @return array
438 function getExtStyle() {
439 return $this->mExtStyles;
443 * Add a JavaScript file out of skins/common, or a given relative path.
445 * @param string $file filename in skins/common or complete on-server path
446 * (/foo/bar.js)
447 * @param string $version style version of the file. Defaults to $wgStyleVersion
449 public function addScriptFile( $file, $version = null ) {
450 global $wgStylePath, $wgStyleVersion;
451 // See if $file parameter is an absolute URL or begins with a slash
452 if ( substr( $file, 0, 1 ) == '/' || preg_match( '#^[a-z]*://#i', $file ) ) {
453 $path = $file;
454 } else {
455 $path = "{$wgStylePath}/common/{$file}";
457 if ( is_null( $version ) ) {
458 $version = $wgStyleVersion;
460 $this->addScript( Html::linkedScript( wfAppendQuery( $path, $version ) ) );
464 * Add a self-contained script tag with the given contents
466 * @param string $script JavaScript text, no "<script>" tags
468 public function addInlineScript( $script ) {
469 $this->mScripts .= Html::inlineScript( "\n$script\n" ) . "\n";
473 * Get all registered JS and CSS tags for the header.
475 * @return string
476 * @deprecated since 1.24 Use OutputPage::headElement to build the full header.
478 function getScript() {
479 wfDeprecated( __METHOD__, '1.24' );
480 return $this->mScripts . $this->getHeadItems();
484 * Filter an array of modules to remove insufficiently trustworthy members, and modules
485 * which are no longer registered (eg a page is cached before an extension is disabled)
486 * @param array $modules
487 * @param string|null $position if not null, only return modules with this position
488 * @param string $type
489 * @return array
491 protected function filterModules( $modules, $position = null,
492 $type = ResourceLoaderModule::TYPE_COMBINED
494 $resourceLoader = $this->getResourceLoader();
495 $filteredModules = array();
496 foreach ( $modules as $val ) {
497 $module = $resourceLoader->getModule( $val );
498 if ( $module instanceof ResourceLoaderModule
499 && $module->getOrigin() <= $this->getAllowedModules( $type )
500 && ( is_null( $position ) || $module->getPosition() == $position )
501 && ( !$this->mTarget || in_array( $this->mTarget, $module->getTargets() ) )
503 $filteredModules[] = $val;
506 return $filteredModules;
510 * Get the list of modules to include on this page
512 * @param bool $filter Whether to filter out insufficiently trustworthy modules
513 * @param string|null $position If not null, only return modules with this position
514 * @param string $param
515 * @return array Array of module names
517 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
518 $modules = array_values( array_unique( $this->$param ) );
519 return $filter
520 ? $this->filterModules( $modules, $position )
521 : $modules;
525 * Add one or more modules recognized by the resource loader. Modules added
526 * through this function will be loaded by the resource loader when the
527 * page loads.
529 * @param string|array $modules Module name (string) or array of module names
531 public function addModules( $modules ) {
532 $this->mModules = array_merge( $this->mModules, (array)$modules );
536 * Get the list of module JS to include on this page
538 * @param bool $filter
539 * @param string|null $position
541 * @return array Array of module names
543 public function getModuleScripts( $filter = false, $position = null ) {
544 return $this->getModules( $filter, $position, 'mModuleScripts' );
548 * Add only JS of one or more modules recognized by the resource loader. Module
549 * scripts added through this function will be loaded by the resource loader when
550 * the page loads.
552 * @param string|array $modules Module name (string) or array of module names
554 public function addModuleScripts( $modules ) {
555 $this->mModuleScripts = array_merge( $this->mModuleScripts, (array)$modules );
559 * Get the list of module CSS to include on this page
561 * @param bool $filter
562 * @param string|null $position
564 * @return array Array of module names
566 public function getModuleStyles( $filter = false, $position = null ) {
567 return $this->getModules( $filter, $position, 'mModuleStyles' );
571 * Add only CSS of one or more modules recognized by the resource loader.
573 * Module styles added through this function will be added using standard link CSS
574 * tags, rather than as a combined Javascript and CSS package. Thus, they will
575 * load when JavaScript is disabled (unless CSS also happens to be disabled).
577 * @param string|array $modules Module name (string) or array of module names
579 public function addModuleStyles( $modules ) {
580 $this->mModuleStyles = array_merge( $this->mModuleStyles, (array)$modules );
584 * Get the list of module messages to include on this page
586 * @param bool $filter
587 * @param string|null $position
589 * @return array Array of module names
591 public function getModuleMessages( $filter = false, $position = null ) {
592 return $this->getModules( $filter, $position, 'mModuleMessages' );
596 * Add only messages of one or more modules recognized by the resource loader.
597 * Module messages added through this function will be loaded by the resource
598 * loader when the page loads.
600 * @param string|array $modules Module name (string) or array of module names
602 public function addModuleMessages( $modules ) {
603 $this->mModuleMessages = array_merge( $this->mModuleMessages, (array)$modules );
607 * @return null|string ResourceLoader target
609 public function getTarget() {
610 return $this->mTarget;
614 * Sets ResourceLoader target for load.php links. If null, will be omitted
616 * @param string|null $target
618 public function setTarget( $target ) {
619 $this->mTarget = $target;
623 * Get an array of head items
625 * @return array
627 function getHeadItemsArray() {
628 return $this->mHeadItems;
632 * Get all header items in a string
634 * @return string
635 * @deprecated since 1.24 Use OutputPage::headElement or
636 * if absolutely necessary use OutputPage::getHeadItemsArray
638 function getHeadItems() {
639 wfDeprecated( __METHOD__, '1.24' );
640 $s = '';
641 foreach ( $this->mHeadItems as $item ) {
642 $s .= $item;
644 return $s;
648 * Add or replace an header item to the output
650 * @param string $name item name
651 * @param string $value raw HTML
653 public function addHeadItem( $name, $value ) {
654 $this->mHeadItems[$name] = $value;
658 * Check if the header item $name is already set
660 * @param string $name Item name
661 * @return bool
663 public function hasHeadItem( $name ) {
664 return isset( $this->mHeadItems[$name] );
668 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
670 * @param string $tag value of "ETag" header
672 function setETag( $tag ) {
673 $this->mETag = $tag;
677 * Set whether the output should only contain the body of the article,
678 * without any skin, sidebar, etc.
679 * Used e.g. when calling with "action=render".
681 * @param bool $only Whether to output only the body of the article
683 public function setArticleBodyOnly( $only ) {
684 $this->mArticleBodyOnly = $only;
688 * Return whether the output will contain only the body of the article
690 * @return bool
692 public function getArticleBodyOnly() {
693 return $this->mArticleBodyOnly;
697 * Set an additional output property
698 * @since 1.21
700 * @param string $name
701 * @param mixed $value
703 public function setProperty( $name, $value ) {
704 $this->mProperties[$name] = $value;
708 * Get an additional output property
709 * @since 1.21
711 * @param string $name
712 * @return mixed Property value or null if not found
714 public function getProperty( $name ) {
715 if ( isset( $this->mProperties[$name] ) ) {
716 return $this->mProperties[$name];
717 } else {
718 return null;
723 * checkLastModified tells the client to use the client-cached page if
724 * possible. If successful, the OutputPage is disabled so that
725 * any future call to OutputPage->output() have no effect.
727 * Side effect: sets mLastModified for Last-Modified header
729 * @param string $timestamp
731 * @return bool True if cache-ok headers was sent.
733 public function checkLastModified( $timestamp ) {
734 global $wgCachePages, $wgCacheEpoch, $wgUseSquid, $wgSquidMaxage;
736 if ( !$timestamp || $timestamp == '19700101000000' ) {
737 wfDebug( __METHOD__ . ": CACHE DISABLED, NO TIMESTAMP\n" );
738 return false;
740 if ( !$wgCachePages ) {
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' => $wgCacheEpoch
751 if ( $wgUseSquid ) {
752 // bug 44570: the core page itself may not change, but resources might
753 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW, time() - $wgSquidMaxage );
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 $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 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 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
1006 public function addBacklinkSubtitle( Title $title ) {
1007 $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 global $wgAdvertisedFeedTypes;
1110 $this->mFeedLinks = array();
1112 foreach ( $wgAdvertisedFeedTypes as $type ) {
1113 $query = "feed=$type";
1114 if ( is_string( $val ) ) {
1115 $query .= '&' . $val;
1117 $this->mFeedLinks[$type] = $this->getTitle()->getLocalURL( $query );
1122 * Add a feed link to the page header
1124 * @param string $format feed type, should be a key of $wgFeedClasses
1125 * @param string $href URL
1127 public function addFeedLink( $format, $href ) {
1128 global $wgAdvertisedFeedTypes;
1130 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
1131 $this->mFeedLinks[$format] = $href;
1136 * Should we output feed links for this page?
1137 * @return bool
1139 public function isSyndicated() {
1140 return count( $this->mFeedLinks ) > 0;
1144 * Return URLs for each supported syndication format for this page.
1145 * @return array associating format keys with URLs
1147 public function getSyndicationLinks() {
1148 return $this->mFeedLinks;
1152 * Will currently always return null
1154 * @return null
1156 public function getFeedAppendQuery() {
1157 return $this->mFeedLinksAppendQuery;
1161 * Set whether the displayed content is related to the source of the
1162 * corresponding article on the wiki
1163 * Setting true will cause the change "article related" toggle to true
1165 * @param bool $v
1167 public function setArticleFlag( $v ) {
1168 $this->mIsarticle = $v;
1169 if ( $v ) {
1170 $this->mIsArticleRelated = $v;
1175 * Return whether the content displayed page is related to the source of
1176 * the corresponding article on the wiki
1178 * @return bool
1180 public function isArticle() {
1181 return $this->mIsarticle;
1185 * Set whether this page is related an article on the wiki
1186 * Setting false will cause the change of "article flag" toggle to false
1188 * @param bool $v
1190 public function setArticleRelated( $v ) {
1191 $this->mIsArticleRelated = $v;
1192 if ( !$v ) {
1193 $this->mIsarticle = false;
1198 * Return whether this page is related an article on the wiki
1200 * @return bool
1202 public function isArticleRelated() {
1203 return $this->mIsArticleRelated;
1207 * Add new language links
1209 * @param array $newLinkArray Associative array mapping language code to the page
1210 * name
1212 public function addLanguageLinks( $newLinkArray ) {
1213 $this->mLanguageLinks += $newLinkArray;
1217 * Reset the language links and add new language links
1219 * @param array $newLinkArray Associative array mapping language code to the page
1220 * name
1222 public function setLanguageLinks( $newLinkArray ) {
1223 $this->mLanguageLinks = $newLinkArray;
1227 * Get the list of language links
1229 * @return array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1231 public function getLanguageLinks() {
1232 return $this->mLanguageLinks;
1236 * Add an array of categories, with names in the keys
1238 * @param array $categories mapping category name => sort key
1240 public function addCategoryLinks( $categories ) {
1241 global $wgContLang;
1243 if ( !is_array( $categories ) || count( $categories ) == 0 ) {
1244 return;
1247 # Add the links to a LinkBatch
1248 $arr = array( NS_CATEGORY => $categories );
1249 $lb = new LinkBatch;
1250 $lb->setArray( $arr );
1252 # Fetch existence plus the hiddencat property
1253 $dbr = wfGetDB( DB_SLAVE );
1254 $res = $dbr->select( array( 'page', 'page_props' ),
1255 array( 'page_id', 'page_namespace', 'page_title', 'page_len',
1256 'page_is_redirect', 'page_latest', 'pp_value' ),
1257 $lb->constructSet( 'page', $dbr ),
1258 __METHOD__,
1259 array(),
1260 array( 'page_props' => array( 'LEFT JOIN', array(
1261 'pp_propname' => 'hiddencat',
1262 'pp_page = page_id'
1263 ) ) )
1266 # Add the results to the link cache
1267 $lb->addResultToCache( LinkCache::singleton(), $res );
1269 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
1270 $categories = array_combine(
1271 array_keys( $categories ),
1272 array_fill( 0, count( $categories ), 'normal' )
1275 # Mark hidden categories
1276 foreach ( $res as $row ) {
1277 if ( isset( $row->pp_value ) ) {
1278 $categories[$row->page_title] = 'hidden';
1282 # Add the remaining categories to the skin
1283 if ( wfRunHooks(
1284 'OutputPageMakeCategoryLinks',
1285 array( &$this, $categories, &$this->mCategoryLinks ) )
1287 foreach ( $categories as $category => $type ) {
1288 $origcategory = $category;
1289 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
1290 $wgContLang->findVariantLink( $category, $title, true );
1291 if ( $category != $origcategory ) {
1292 if ( array_key_exists( $category, $categories ) ) {
1293 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( $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, $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() );
1644 // Template versioning...
1645 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1646 if ( isset( $this->mTemplateIds[$ns] ) ) {
1647 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
1648 } else {
1649 $this->mTemplateIds[$ns] = $dbks;
1652 // File versioning...
1653 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1654 $this->mImageTimeKeys[$dbk] = $data;
1657 // Hooks registered in the object
1658 global $wgParserOutputHooks;
1659 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1660 list( $hookName, $data ) = $hookInfo;
1661 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1662 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1666 // Link flags are ignored for now, but may in the future be
1667 // used to mark individual language links.
1668 $linkFlags = array();
1669 wfRunHooks( 'LanguageLinks', array( $this->getTitle(), &$this->mLanguageLinks, &$linkFlags ) );
1670 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1674 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1675 * ParserOutput object, without any other metadata.
1677 * @since 1.24
1678 * @param ParserOutput $parserOutput
1680 public function addParserOutputContent( &$parserOutput ) {
1681 $this->addParserOutputText( $parserOutput );
1683 $this->addModules( $parserOutput->getModules() );
1684 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1685 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1686 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1688 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1692 * Add the HTML associated with a ParserOutput object, without any metadata.
1694 * @since 1.24
1695 * @param ParserOutput $parserOutput
1697 public function addParserOutputText( &$parserOutput ) {
1698 $text = $parserOutput->getText();
1699 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1700 $this->addHTML( $text );
1704 * Add everything from a ParserOutput object.
1706 * @param ParserOutput $parserOutput
1708 function addParserOutput( &$parserOutput ) {
1709 $this->addParserOutputMetadata( $parserOutput );
1710 $parserOutput->setTOCEnabled( $this->mEnableTOC );
1712 // Touch section edit links only if not previously disabled
1713 if ( $parserOutput->getEditSectionTokens() ) {
1714 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks );
1717 $this->addParserOutputText( $parserOutput );
1721 * Add the output of a QuickTemplate to the output buffer
1723 * @param QuickTemplate $template
1725 public function addTemplate( &$template ) {
1726 $this->addHTML( $template->getHTML() );
1730 * Parse wikitext and return the HTML.
1732 * @param string $text
1733 * @param bool $linestart Is this the start of a line?
1734 * @param bool $interface Use interface language ($wgLang instead of
1735 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1736 * This also disables LanguageConverter.
1737 * @param Language $language Target language object, will override $interface
1738 * @throws MWException
1739 * @return string HTML
1741 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1742 global $wgParser;
1744 if ( is_null( $this->getTitle() ) ) {
1745 throw new MWException( 'Empty $mTitle in ' . __METHOD__ );
1748 $popts = $this->parserOptions();
1749 if ( $interface ) {
1750 $popts->setInterfaceMessage( true );
1752 if ( $language !== null ) {
1753 $oldLang = $popts->setTargetLanguage( $language );
1756 $parserOutput = $wgParser->getFreshParser()->parse(
1757 $text, $this->getTitle(), $popts,
1758 $linestart, true, $this->mRevisionId
1761 if ( $interface ) {
1762 $popts->setInterfaceMessage( false );
1764 if ( $language !== null ) {
1765 $popts->setTargetLanguage( $oldLang );
1768 return $parserOutput->getText();
1772 * Parse wikitext, strip paragraphs, and return the HTML.
1774 * @param string $text
1775 * @param bool $linestart Is this the start of a line?
1776 * @param bool $interface Use interface language ($wgLang instead of
1777 * $wgContLang) while parsing language sensitive magic
1778 * words like GRAMMAR and PLURAL
1779 * @return string HTML
1781 public function parseInline( $text, $linestart = true, $interface = false ) {
1782 $parsed = $this->parse( $text, $linestart, $interface );
1783 return Parser::stripOuterParagraph( $parsed );
1787 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1789 * @param int $maxage Maximum cache time on the Squid, in seconds.
1791 public function setSquidMaxage( $maxage ) {
1792 $this->mSquidMaxage = $maxage;
1796 * Use enableClientCache(false) to force it to send nocache headers
1798 * @param bool $state
1800 * @return bool
1802 public function enableClientCache( $state ) {
1803 return wfSetVar( $this->mEnableClientCache, $state );
1807 * Get the list of cookies that will influence on the cache
1809 * @return array
1811 function getCacheVaryCookies() {
1812 global $wgCookiePrefix, $wgCacheVaryCookies;
1813 static $cookies;
1814 if ( $cookies === null ) {
1815 $cookies = array_merge(
1816 array(
1817 "{$wgCookiePrefix}Token",
1818 "{$wgCookiePrefix}LoggedOut",
1819 "forceHTTPS",
1820 session_name()
1822 $wgCacheVaryCookies
1824 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1826 return $cookies;
1830 * Check if the request has a cache-varying cookie header
1831 * If it does, it's very important that we don't allow public caching
1833 * @return bool
1835 function haveCacheVaryCookies() {
1836 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1837 if ( $cookieHeader === false ) {
1838 return false;
1840 $cvCookies = $this->getCacheVaryCookies();
1841 foreach ( $cvCookies as $cookieName ) {
1842 # Check for a simple string match, like the way squid does it
1843 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1844 wfDebug( __METHOD__ . ": found $cookieName\n" );
1845 return true;
1848 wfDebug( __METHOD__ . ": no cache-varying cookies found\n" );
1849 return false;
1853 * Add an HTTP header that will influence on the cache
1855 * @param string $header header name
1856 * @param array|null $option
1857 * @todo FIXME: Document the $option parameter; it appears to be for
1858 * X-Vary-Options but what format is acceptable?
1860 public function addVaryHeader( $header, $option = null ) {
1861 if ( !array_key_exists( $header, $this->mVaryHeader ) ) {
1862 $this->mVaryHeader[$header] = (array)$option;
1863 } elseif ( is_array( $option ) ) {
1864 if ( is_array( $this->mVaryHeader[$header] ) ) {
1865 $this->mVaryHeader[$header] = array_merge( $this->mVaryHeader[$header], $option );
1866 } else {
1867 $this->mVaryHeader[$header] = $option;
1870 $this->mVaryHeader[$header] = array_unique( (array)$this->mVaryHeader[$header] );
1874 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
1875 * such as Accept-Encoding or Cookie
1877 * @return string
1879 public function getVaryHeader() {
1880 return 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader ) );
1884 * Get a complete X-Vary-Options header
1886 * @return string
1888 public function getXVO() {
1889 $cvCookies = $this->getCacheVaryCookies();
1891 $cookiesOption = array();
1892 foreach ( $cvCookies as $cookieName ) {
1893 $cookiesOption[] = 'string-contains=' . $cookieName;
1895 $this->addVaryHeader( 'Cookie', $cookiesOption );
1897 $headers = array();
1898 foreach ( $this->mVaryHeader as $header => $option ) {
1899 $newheader = $header;
1900 if ( is_array( $option ) && count( $option ) > 0 ) {
1901 $newheader .= ';' . implode( ';', $option );
1903 $headers[] = $newheader;
1905 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1907 return $xvo;
1911 * bug 21672: Add Accept-Language to Vary and XVO headers
1912 * if there's no 'variant' parameter existed in GET.
1914 * For example:
1915 * /w/index.php?title=Main_page should always be served; but
1916 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1918 function addAcceptLanguage() {
1919 $title = $this->getTitle();
1920 if ( !$title instanceof Title ) {
1921 return;
1924 $lang = $title->getPageLanguage();
1925 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
1926 $variants = $lang->getVariants();
1927 $aloption = array();
1928 foreach ( $variants as $variant ) {
1929 if ( $variant === $lang->getCode() ) {
1930 continue;
1931 } else {
1932 $aloption[] = 'string-contains=' . $variant;
1934 // IE and some other browsers use BCP 47 standards in
1935 // their Accept-Language header, like "zh-CN" or "zh-Hant".
1936 // We should handle these too.
1937 $variantBCP47 = wfBCP47( $variant );
1938 if ( $variantBCP47 !== $variant ) {
1939 $aloption[] = 'string-contains=' . $variantBCP47;
1943 $this->addVaryHeader( 'Accept-Language', $aloption );
1948 * Set a flag which will cause an X-Frame-Options header appropriate for
1949 * edit pages to be sent. The header value is controlled by
1950 * $wgEditPageFrameOptions.
1952 * This is the default for special pages. If you display a CSRF-protected
1953 * form on an ordinary view page, then you need to call this function.
1955 * @param bool $enable
1957 public function preventClickjacking( $enable = true ) {
1958 $this->mPreventClickjacking = $enable;
1962 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1963 * This can be called from pages which do not contain any CSRF-protected
1964 * HTML form.
1966 public function allowClickjacking() {
1967 $this->mPreventClickjacking = false;
1971 * Get the X-Frame-Options header value (without the name part), or false
1972 * if there isn't one. This is used by Skin to determine whether to enable
1973 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1975 * @return string
1977 public function getFrameOptions() {
1978 global $wgBreakFrames, $wgEditPageFrameOptions;
1979 if ( $wgBreakFrames ) {
1980 return 'DENY';
1981 } elseif ( $this->mPreventClickjacking && $wgEditPageFrameOptions ) {
1982 return $wgEditPageFrameOptions;
1984 return false;
1988 * Send cache control HTTP headers
1990 public function sendCacheControl() {
1991 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgUseXVO;
1993 $response = $this->getRequest()->response();
1994 if ( $wgUseETag && $this->mETag ) {
1995 $response->header( "ETag: $this->mETag" );
1998 $this->addVaryHeader( 'Cookie' );
1999 $this->addAcceptLanguage();
2001 # don't serve compressed data to clients who can't handle it
2002 # maintain different caches for logged-in users and non-logged in ones
2003 $response->header( $this->getVaryHeader() );
2005 if ( $wgUseXVO ) {
2006 # Add an X-Vary-Options header for Squid with Wikimedia patches
2007 $response->header( $this->getXVO() );
2010 if ( $this->mEnableClientCache ) {
2011 if (
2012 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
2013 $this->mSquidMaxage != 0 && !$this->haveCacheVaryCookies()
2015 if ( $wgUseESI ) {
2016 # We'll purge the proxy cache explicitly, but require end user agents
2017 # to revalidate against the proxy on each visit.
2018 # Surrogate-Control controls our Squid, Cache-Control downstream caches
2019 wfDebug( __METHOD__ . ": proxy caching with ESI; {$this->mLastModified} **\n", 'log' );
2020 # start with a shorter timeout for initial testing
2021 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2022 $response->header( 'Surrogate-Control: max-age=' . $wgSquidMaxage
2023 . '+' . $this->mSquidMaxage . ', content="ESI/1.0"' );
2024 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2025 } else {
2026 # We'll purge the proxy cache for anons explicitly, but require end user agents
2027 # to revalidate against the proxy on each visit.
2028 # IMPORTANT! The Squid needs to replace the Cache-Control header with
2029 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2030 wfDebug( __METHOD__ . ": local proxy caching; {$this->mLastModified} **\n", 'log' );
2031 # start with a shorter timeout for initial testing
2032 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2033 $response->header( 'Cache-Control: s-maxage=' . $this->mSquidMaxage
2034 . ', must-revalidate, max-age=0' );
2036 } else {
2037 # We do want clients to cache if they can, but they *must* check for updates
2038 # on revisiting the page.
2039 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **\n", 'log' );
2040 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2041 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2043 if ( $this->mLastModified ) {
2044 $response->header( "Last-Modified: {$this->mLastModified}" );
2046 } else {
2047 wfDebug( __METHOD__ . ": no caching **\n", 'log' );
2049 # In general, the absence of a last modified header should be enough to prevent
2050 # the client from using its cache. We send a few other things just to make sure.
2051 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2052 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2053 $response->header( 'Pragma: no-cache' );
2058 * Finally, all the text has been munged and accumulated into
2059 * the object, let's actually output it:
2061 public function output() {
2062 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType, $wgVaryOnXFP,
2063 $wgResponsiveImages;
2065 if ( $this->mDoNothing ) {
2066 return;
2069 wfProfileIn( __METHOD__ );
2071 $response = $this->getRequest()->response();
2073 if ( $this->mRedirect != '' ) {
2074 # Standards require redirect URLs to be absolute
2075 $this->mRedirect = wfExpandUrl( $this->mRedirect, PROTO_CURRENT );
2077 $redirect = $this->mRedirect;
2078 $code = $this->mRedirectCode;
2080 if ( wfRunHooks( "BeforePageRedirect", array( $this, &$redirect, &$code ) ) ) {
2081 if ( $code == '301' || $code == '303' ) {
2082 if ( !$wgDebugRedirects ) {
2083 $message = HttpStatus::getMessage( $code );
2084 $response->header( "HTTP/1.1 $code $message" );
2086 $this->mLastModified = wfTimestamp( TS_RFC2822 );
2088 if ( $wgVaryOnXFP ) {
2089 $this->addVaryHeader( 'X-Forwarded-Proto' );
2091 $this->sendCacheControl();
2093 $response->header( "Content-Type: text/html; charset=utf-8" );
2094 if ( $wgDebugRedirects ) {
2095 $url = htmlspecialchars( $redirect );
2096 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2097 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2098 print "</body>\n</html>\n";
2099 } else {
2100 $response->header( 'Location: ' . $redirect );
2104 wfProfileOut( __METHOD__ );
2105 return;
2106 } elseif ( $this->mStatusCode ) {
2107 $message = HttpStatus::getMessage( $this->mStatusCode );
2108 if ( $message ) {
2109 $response->header( 'HTTP/1.1 ' . $this->mStatusCode . ' ' . $message );
2113 # Buffer output; final headers may depend on later processing
2114 ob_start();
2116 $response->header( "Content-type: $wgMimeType; charset=UTF-8" );
2117 $response->header( 'Content-language: ' . $wgLanguageCode );
2119 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2120 // jQuery etc. can work correctly.
2121 $response->header( 'X-UA-Compatible: IE=Edge' );
2123 // Prevent framing, if requested
2124 $frameOptions = $this->getFrameOptions();
2125 if ( $frameOptions ) {
2126 $response->header( "X-Frame-Options: $frameOptions" );
2129 if ( $this->mArticleBodyOnly ) {
2130 echo $this->mBodytext;
2131 } else {
2133 $sk = $this->getSkin();
2134 // add skin specific modules
2135 $modules = $sk->getDefaultModules();
2137 // enforce various default modules for all skins
2138 $coreModules = array(
2139 // keep this list as small as possible
2140 'mediawiki.page.startup',
2141 'mediawiki.user',
2144 // Support for high-density display images if enabled
2145 if ( $wgResponsiveImages ) {
2146 $coreModules[] = 'mediawiki.hidpi';
2149 $this->addModules( $coreModules );
2150 foreach ( $modules as $group ) {
2151 $this->addModules( $group );
2153 MWDebug::addModules( $this );
2155 // Hook that allows last minute changes to the output page, e.g.
2156 // adding of CSS or Javascript by extensions.
2157 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
2159 wfProfileIn( 'Output-skin' );
2160 $sk->outputPage();
2161 wfProfileOut( 'Output-skin' );
2164 // This hook allows last minute changes to final overall output by modifying output buffer
2165 wfRunHooks( 'AfterFinalPageOutput', array( $this ) );
2167 $this->sendCacheControl();
2169 ob_end_flush();
2171 wfProfileOut( __METHOD__ );
2175 * Actually output something with print.
2177 * @param string $ins the string to output
2178 * @deprecated since 1.22 Use echo yourself.
2180 public function out( $ins ) {
2181 wfDeprecated( __METHOD__, '1.22' );
2182 print $ins;
2186 * Produce a "user is blocked" page.
2187 * @deprecated since 1.18
2189 function blockedPage() {
2190 throw new UserBlockedError( $this->getUser()->mBlock );
2194 * Prepare this object to display an error page; disable caching and
2195 * indexing, clear the current text and redirect, set the page's title
2196 * and optionally an custom HTML title (content of the "<title>" tag).
2198 * @param string|Message $pageTitle will be passed directly to setPageTitle()
2199 * @param string|Message $htmlTitle will be passed directly to setHTMLTitle();
2200 * optional, if not passed the "<title>" attribute will be
2201 * based on $pageTitle
2203 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2204 $this->setPageTitle( $pageTitle );
2205 if ( $htmlTitle !== false ) {
2206 $this->setHTMLTitle( $htmlTitle );
2208 $this->setRobotPolicy( 'noindex,nofollow' );
2209 $this->setArticleRelated( false );
2210 $this->enableClientCache( false );
2211 $this->mRedirect = '';
2212 $this->clearSubtitle();
2213 $this->clearHTML();
2217 * Output a standard error page
2219 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2220 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2221 * showErrorPage( 'titlemsg', $messageObject );
2222 * showErrorPage( $titleMessageObject, $messageObject );
2224 * @param string|Message $title Message key (string) for page title, or a Message object
2225 * @param string|Message $msg Message key (string) for page text, or a Message object
2226 * @param array $params Message parameters; ignored if $msg is a Message object
2228 public function showErrorPage( $title, $msg, $params = array() ) {
2229 if ( !$title instanceof Message ) {
2230 $title = $this->msg( $title );
2233 $this->prepareErrorPage( $title );
2235 if ( $msg instanceof Message ) {
2236 if ( $params !== array() ) {
2237 trigger_error( 'Argument ignored: $params. The message parameters argument '
2238 . 'is discarded when the $msg argument is a Message object instead of '
2239 . 'a string.', E_USER_NOTICE );
2241 $this->addHTML( $msg->parseAsBlock() );
2242 } else {
2243 $this->addWikiMsgArray( $msg, $params );
2246 $this->returnToMain();
2250 * Output a standard permission error page
2252 * @param array $errors error message keys
2253 * @param string $action action that was denied or null if unknown
2255 public function showPermissionsErrorPage( $errors, $action = null ) {
2256 // For some action (read, edit, create and upload), display a "login to do this action"
2257 // error if all of the following conditions are met:
2258 // 1. the user is not logged in
2259 // 2. the only error is insufficient permissions (i.e. no block or something else)
2260 // 3. the error can be avoided simply by logging in
2261 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2262 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2263 && ( $errors[0][0] == 'badaccess-groups' || $errors[0][0] == 'badaccess-group0' )
2264 && ( User::groupHasPermission( 'user', $action )
2265 || User::groupHasPermission( 'autoconfirmed', $action ) )
2267 $displayReturnto = null;
2269 # Due to bug 32276, if a user does not have read permissions,
2270 # $this->getTitle() will just give Special:Badtitle, which is
2271 # not especially useful as a returnto parameter. Use the title
2272 # from the request instead, if there was one.
2273 $request = $this->getRequest();
2274 $returnto = Title::newFromURL( $request->getVal( 'title', '' ) );
2275 if ( $action == 'edit' ) {
2276 $msg = 'whitelistedittext';
2277 $displayReturnto = $returnto;
2278 } elseif ( $action == 'createpage' || $action == 'createtalk' ) {
2279 $msg = 'nocreatetext';
2280 } elseif ( $action == 'upload' ) {
2281 $msg = 'uploadnologintext';
2282 } else { # Read
2283 $msg = 'loginreqpagetext';
2284 $displayReturnto = Title::newMainPage();
2287 $query = array();
2289 if ( $returnto ) {
2290 $query['returnto'] = $returnto->getPrefixedText();
2292 if ( !$request->wasPosted() ) {
2293 $returntoquery = $request->getValues();
2294 unset( $returntoquery['title'] );
2295 unset( $returntoquery['returnto'] );
2296 unset( $returntoquery['returntoquery'] );
2297 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2300 $loginLink = Linker::linkKnown(
2301 SpecialPage::getTitleFor( 'Userlogin' ),
2302 $this->msg( 'loginreqlink' )->escaped(),
2303 array(),
2304 $query
2307 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2308 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2310 # Don't return to a page the user can't read otherwise
2311 # we'll end up in a pointless loop
2312 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2313 $this->returnToMain( null, $displayReturnto );
2315 } else {
2316 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2317 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2322 * Display an error page indicating that a given version of MediaWiki is
2323 * required to use it
2325 * @param mixed $version The version of MediaWiki needed to use the page
2327 public function versionRequired( $version ) {
2328 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2330 $this->addWikiMsg( 'versionrequiredtext', $version );
2331 $this->returnToMain();
2335 * Display an error page noting that a given permission bit is required.
2336 * @deprecated since 1.18, just throw the exception directly
2337 * @param string $permission key required
2338 * @throws PermissionsError
2340 public function permissionRequired( $permission ) {
2341 throw new PermissionsError( $permission );
2345 * Produce the stock "please login to use the wiki" page
2347 * @deprecated since 1.19; throw the exception directly
2349 public function loginToUse() {
2350 throw new PermissionsError( 'read' );
2354 * Format a list of error messages
2356 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2357 * @param string $action Action that was denied or null if unknown
2358 * @return string The wikitext error-messages, formatted into a list.
2360 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2361 if ( $action == null ) {
2362 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2363 } else {
2364 $action_desc = $this->msg( "action-$action" )->plain();
2365 $text = $this->msg(
2366 'permissionserrorstext-withaction',
2367 count( $errors ),
2368 $action_desc
2369 )->plain() . "\n\n";
2372 if ( count( $errors ) > 1 ) {
2373 $text .= '<ul class="permissions-errors">' . "\n";
2375 foreach ( $errors as $error ) {
2376 $text .= '<li>';
2377 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2378 $text .= "</li>\n";
2380 $text .= '</ul>';
2381 } else {
2382 $text .= "<div class=\"permissions-errors\">\n" .
2383 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2384 "\n</div>";
2387 return $text;
2391 * Display a page stating that the Wiki is in read-only mode,
2392 * and optionally show the source of the page that the user
2393 * was trying to edit. Should only be called (for this
2394 * purpose) after wfReadOnly() has returned true.
2396 * For historical reasons, this function is _also_ used to
2397 * show the error message when a user tries to edit a page
2398 * they are not allowed to edit. (Unless it's because they're
2399 * blocked, then we show blockedPage() instead.) In this
2400 * case, the second parameter should be set to true and a list
2401 * of reasons supplied as the third parameter.
2403 * @todo Needs to be split into multiple functions.
2405 * @param string $source Source code to show (or null).
2406 * @param bool $protected Is this a permissions error?
2407 * @param array $reasons List of reasons for this error, as returned by
2408 * Title::getUserPermissionsErrors().
2409 * @param string $action Action that was denied or null if unknown
2410 * @throws ReadOnlyError
2412 public function readOnlyPage( $source = null, $protected = false,
2413 $reasons = array(), $action = null
2415 $this->setRobotPolicy( 'noindex,nofollow' );
2416 $this->setArticleRelated( false );
2418 // If no reason is given, just supply a default "I can't let you do
2419 // that, Dave" message. Should only occur if called by legacy code.
2420 if ( $protected && empty( $reasons ) ) {
2421 $reasons[] = array( 'badaccess-group0' );
2424 if ( !empty( $reasons ) ) {
2425 // Permissions error
2426 if ( $source ) {
2427 $this->setPageTitle( $this->msg( 'viewsource-title', $this->getTitle()->getPrefixedText() ) );
2428 $this->addBacklinkSubtitle( $this->getTitle() );
2429 } else {
2430 $this->setPageTitle( $this->msg( 'badaccess' ) );
2432 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2433 } else {
2434 // Wiki is read only
2435 throw new ReadOnlyError;
2438 // Show source, if supplied
2439 if ( is_string( $source ) ) {
2440 $this->addWikiMsg( 'viewsourcetext' );
2442 $pageLang = $this->getTitle()->getPageLanguage();
2443 $params = array(
2444 'id' => 'wpTextbox1',
2445 'name' => 'wpTextbox1',
2446 'cols' => $this->getUser()->getOption( 'cols' ),
2447 'rows' => $this->getUser()->getOption( 'rows' ),
2448 'readonly' => 'readonly',
2449 'lang' => $pageLang->getHtmlCode(),
2450 'dir' => $pageLang->getDir(),
2452 $this->addHTML( Html::element( 'textarea', $params, $source ) );
2454 // Show templates used by this article
2455 $templates = Linker::formatTemplates( $this->getTitle()->getTemplateLinksFrom() );
2456 $this->addHTML( "<div class='templatesUsed'>
2457 $templates
2458 </div>
2459 " );
2462 # If the title doesn't exist, it's fairly pointless to print a return
2463 # link to it. After all, you just tried editing it and couldn't, so
2464 # what's there to do there?
2465 if ( $this->getTitle()->exists() ) {
2466 $this->returnToMain( null, $this->getTitle() );
2471 * Turn off regular page output and return an error response
2472 * for when rate limiting has triggered.
2474 public function rateLimited() {
2475 throw new ThrottledError;
2479 * Show a warning about slave lag
2481 * If the lag is higher than $wgSlaveLagCritical seconds,
2482 * then the warning is a bit more obvious. If the lag is
2483 * lower than $wgSlaveLagWarning, then no warning is shown.
2485 * @param int $lag Slave lag
2487 public function showLagWarning( $lag ) {
2488 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2489 if ( $lag >= $wgSlaveLagWarning ) {
2490 $message = $lag < $wgSlaveLagCritical
2491 ? 'lag-warn-normal'
2492 : 'lag-warn-high';
2493 $wrap = Html::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2494 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2498 public function showFatalError( $message ) {
2499 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2501 $this->addHTML( $message );
2504 public function showUnexpectedValueError( $name, $val ) {
2505 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2508 public function showFileCopyError( $old, $new ) {
2509 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2512 public function showFileRenameError( $old, $new ) {
2513 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2516 public function showFileDeleteError( $name ) {
2517 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2520 public function showFileNotFoundError( $name ) {
2521 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2525 * Add a "return to" link pointing to a specified title
2527 * @param Title $title Title to link
2528 * @param array $query Query string parameters
2529 * @param string $text Text of the link (input is not escaped)
2530 * @param array $options Options array to pass to Linker
2532 public function addReturnTo( $title, $query = array(), $text = null, $options = array() ) {
2533 $link = $this->msg( 'returnto' )->rawParams(
2534 Linker::link( $title, $text, array(), $query, $options ) )->escaped();
2535 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2539 * Add a "return to" link pointing to a specified title,
2540 * or the title indicated in the request, or else the main page
2542 * @param mixed $unused
2543 * @param Title|string $returnto Title or String to return to
2544 * @param string $returntoquery Query string for the return to link
2546 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2547 if ( $returnto == null ) {
2548 $returnto = $this->getRequest()->getText( 'returnto' );
2551 if ( $returntoquery == null ) {
2552 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2555 if ( $returnto === '' ) {
2556 $returnto = Title::newMainPage();
2559 if ( is_object( $returnto ) ) {
2560 $titleObj = $returnto;
2561 } else {
2562 $titleObj = Title::newFromText( $returnto );
2564 if ( !is_object( $titleObj ) ) {
2565 $titleObj = Title::newMainPage();
2568 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2572 * @param Skin $sk The given Skin
2573 * @param bool $includeStyle Unused
2574 * @return string The doctype, opening "<html>", and head element.
2576 public function headElement( Skin $sk, $includeStyle = true ) {
2577 global $wgContLang, $wgMimeType;
2579 $userdir = $this->getLanguage()->getDir();
2580 $sitedir = $wgContLang->getDir();
2582 $ret = Html::htmlHeader( $sk->getHtmlElementAttributes() );
2584 if ( $this->getHTMLTitle() == '' ) {
2585 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2588 $openHead = Html::openElement( 'head' );
2589 if ( $openHead ) {
2590 # Don't bother with the newline if $head == ''
2591 $ret .= "$openHead\n";
2594 if ( !Html::isXmlMimeType( $wgMimeType ) ) {
2595 // Add <meta charset="UTF-8">
2596 // This should be before <title> since it defines the charset used by
2597 // text including the text inside <title>.
2598 // The spec recommends defining XHTML5's charset using the XML declaration
2599 // instead of meta.
2600 // Our XML declaration is output by Html::htmlHeader.
2601 // http://www.whatwg.org/html/semantics.html#attr-meta-http-equiv-content-type
2602 // http://www.whatwg.org/html/semantics.html#charset
2603 $ret .= Html::element( 'meta', array( 'charset' => 'UTF-8' ) ) . "\n";
2606 $ret .= Html::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2608 foreach ( $this->getHeadLinksArray() as $item ) {
2609 $ret .= $item . "\n";
2612 // No newline after buildCssLinks since makeResourceLoaderLink did that already
2613 $ret .= $this->buildCssLinks();
2615 $ret .= $this->getHeadScripts() . "\n";
2617 foreach ( $this->mHeadItems as $item ) {
2618 $ret .= $item . "\n";
2621 $closeHead = Html::closeElement( 'head' );
2622 if ( $closeHead ) {
2623 $ret .= "$closeHead\n";
2626 $bodyClasses = array();
2627 $bodyClasses[] = 'mediawiki';
2629 # Classes for LTR/RTL directionality support
2630 $bodyClasses[] = $userdir;
2631 $bodyClasses[] = "sitedir-$sitedir";
2633 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2634 # A <body> class is probably not the best way to do this . . .
2635 $bodyClasses[] = 'capitalize-all-nouns';
2638 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2639 $bodyClasses[] = 'skin-' . Sanitizer::escapeClass( $sk->getSkinName() );
2640 $bodyClasses[] =
2641 'action-' . Sanitizer::escapeClass( Action::getActionName( $this->getContext() ) );
2643 $bodyAttrs = array();
2644 // While the implode() is not strictly needed, it's used for backwards compatibility
2645 // (this used to be built as a string and hooks likely still expect that).
2646 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2648 // Allow skins and extensions to add body attributes they need
2649 $sk->addToBodyAttributes( $this, $bodyAttrs );
2650 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2652 $ret .= Html::openElement( 'body', $bodyAttrs ) . "\n";
2654 return $ret;
2658 * Get a ResourceLoader object associated with this OutputPage
2660 * @return ResourceLoader
2662 public function getResourceLoader() {
2663 if ( is_null( $this->mResourceLoader ) ) {
2664 $this->mResourceLoader = new ResourceLoader();
2666 return $this->mResourceLoader;
2670 * @todo Document
2671 * @param array|string $modules One or more module names
2672 * @param string $only ResourceLoaderModule TYPE_ class constant
2673 * @param bool $useESI
2674 * @param array $extraQuery Array with extra query parameters to add to each
2675 * request. array( param => value ).
2676 * @param bool $loadCall If true, output an (asynchronous) mw.loader.load()
2677 * call rather than a "<script src='...'>" tag.
2678 * @return string The html "<script>", "<link>" and "<style>" tags
2680 protected function makeResourceLoaderLink( $modules, $only, $useESI = false,
2681 array $extraQuery = array(), $loadCall = false
2683 global $wgResourceLoaderUseESI;
2685 $modules = (array)$modules;
2687 $links = array(
2688 'html' => '',
2689 'states' => array(),
2692 if ( !count( $modules ) ) {
2693 return $links;
2696 if ( count( $modules ) > 1 ) {
2697 // Remove duplicate module requests
2698 $modules = array_unique( $modules );
2699 // Sort module names so requests are more uniform
2700 sort( $modules );
2702 if ( ResourceLoader::inDebugMode() ) {
2703 // Recursively call us for every item
2704 foreach ( $modules as $name ) {
2705 $link = $this->makeResourceLoaderLink( $name, $only, $useESI );
2706 $links['html'] .= $link['html'];
2707 $links['states'] += $link['states'];
2709 return $links;
2713 if ( !is_null( $this->mTarget ) ) {
2714 $extraQuery['target'] = $this->mTarget;
2717 // Create keyed-by-group list of module objects from modules list
2718 $groups = array();
2719 $resourceLoader = $this->getResourceLoader();
2720 foreach ( $modules as $name ) {
2721 $module = $resourceLoader->getModule( $name );
2722 # Check that we're allowed to include this module on this page
2723 if ( !$module
2724 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_SCRIPTS )
2725 && $only == ResourceLoaderModule::TYPE_SCRIPTS )
2726 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_STYLES )
2727 && $only == ResourceLoaderModule::TYPE_STYLES )
2728 || ( $this->mTarget && !in_array( $this->mTarget, $module->getTargets() ) )
2730 continue;
2733 $group = $module->getGroup();
2734 if ( !isset( $groups[$group] ) ) {
2735 $groups[$group] = array();
2737 $groups[$group][$name] = $module;
2740 foreach ( $groups as $group => $grpModules ) {
2741 // Special handling for user-specific groups
2742 $user = null;
2743 if ( ( $group === 'user' || $group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2744 $user = $this->getUser()->getName();
2747 // Create a fake request based on the one we are about to make so modules return
2748 // correct timestamp and emptiness data
2749 $query = ResourceLoader::makeLoaderQuery(
2750 array(), // modules; not determined yet
2751 $this->getLanguage()->getCode(),
2752 $this->getSkin()->getSkinName(),
2753 $user,
2754 null, // version; not determined yet
2755 ResourceLoader::inDebugMode(),
2756 $only === ResourceLoaderModule::TYPE_COMBINED ? null : $only,
2757 $this->isPrintable(),
2758 $this->getRequest()->getBool( 'handheld' ),
2759 $extraQuery
2761 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2763 // Extract modules that know they're empty
2764 foreach ( $grpModules as $key => $module ) {
2765 // Inline empty modules: since they're empty, just mark them as 'ready' (bug 46857)
2766 // If we're only getting the styles, we don't need to do anything for empty modules.
2767 if ( $module->isKnownEmpty( $context ) ) {
2768 unset( $grpModules[$key] );
2769 if ( $only !== ResourceLoaderModule::TYPE_STYLES ) {
2770 $links['states'][$key] = 'ready';
2775 // If there are no non-empty modules, skip this group
2776 if ( count( $grpModules ) === 0 ) {
2777 continue;
2780 // Inline private modules. These can't be loaded through load.php for security
2781 // reasons, see bug 34907. Note that these modules should be loaded from
2782 // getHeadScripts() before the first loader call. Otherwise other modules can't
2783 // properly use them as dependencies (bug 30914)
2784 if ( $group === 'private' ) {
2785 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
2786 $links['html'] .= Html::inlineStyle(
2787 $resourceLoader->makeModuleResponse( $context, $grpModules )
2789 } else {
2790 $links['html'] .= Html::inlineScript(
2791 ResourceLoader::makeLoaderConditionalScript(
2792 $resourceLoader->makeModuleResponse( $context, $grpModules )
2796 $links['html'] .= "\n";
2797 continue;
2800 // Special handling for the user group; because users might change their stuff
2801 // on-wiki like user pages, or user preferences; we need to find the highest
2802 // timestamp of these user-changeable modules so we can ensure cache misses on change
2803 // This should NOT be done for the site group (bug 27564) because anons get that too
2804 // and we shouldn't be putting timestamps in Squid-cached HTML
2805 $version = null;
2806 if ( $group === 'user' ) {
2807 // Get the maximum timestamp
2808 $timestamp = 1;
2809 foreach ( $grpModules as $module ) {
2810 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2812 // Add a version parameter so cache will break when things change
2813 $version = wfTimestamp( TS_ISO_8601_BASIC, $timestamp );
2816 $url = ResourceLoader::makeLoaderURL(
2817 array_keys( $grpModules ),
2818 $this->getLanguage()->getCode(),
2819 $this->getSkin()->getSkinName(),
2820 $user,
2821 $version,
2822 ResourceLoader::inDebugMode(),
2823 $only === ResourceLoaderModule::TYPE_COMBINED ? null : $only,
2824 $this->isPrintable(),
2825 $this->getRequest()->getBool( 'handheld' ),
2826 $extraQuery
2828 if ( $useESI && $wgResourceLoaderUseESI ) {
2829 $esi = Xml::element( 'esi:include', array( 'src' => $url ) );
2830 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
2831 $link = Html::inlineStyle( $esi );
2832 } else {
2833 $link = Html::inlineScript( $esi );
2835 } else {
2836 // Automatically select style/script elements
2837 if ( $only === ResourceLoaderModule::TYPE_STYLES ) {
2838 $link = Html::linkedStyle( $url );
2839 } elseif ( $loadCall ) {
2840 $link = Html::inlineScript(
2841 ResourceLoader::makeLoaderConditionalScript(
2842 Xml::encodeJsCall( 'mw.loader.load', array( $url, 'text/javascript', true ) )
2845 } else {
2846 $link = Html::linkedScript( $url );
2848 // For modules requested directly in the html via <link> or <script>,
2849 // tell mw.loader they are being loading to prevent duplicate requests.
2850 foreach ( $grpModules as $key => $module ) {
2851 // Don't output state=loading for the startup module..
2852 if ( $key !== 'startup' ) {
2853 $links['states'][$key] = 'loading';
2859 if ( $group == 'noscript' ) {
2860 $links['html'] .= Html::rawElement( 'noscript', array(), $link ) . "\n";
2861 } else {
2862 $links['html'] .= $link . "\n";
2866 return $links;
2870 * Build html output from an array of links from makeResourceLoaderLink.
2871 * @param array $links
2872 * @return string HTML
2874 protected static function getHtmlFromLoaderLinks( Array $links ) {
2875 $html = '';
2876 $states = array();
2877 foreach ( $links as $link ) {
2878 if ( !is_array( $link ) ) {
2879 $html .= $link;
2880 } else {
2881 $html .= $link['html'];
2882 $states += $link['states'];
2886 if ( count( $states ) ) {
2887 $html = Html::inlineScript(
2888 ResourceLoader::makeLoaderConditionalScript(
2889 ResourceLoader::makeLoaderStateScript( $states )
2891 ) . "\n" . $html;
2894 return $html;
2898 * JS stuff to put in the "<head>". This is the startup module, config
2899 * vars and modules marked with position 'top'
2901 * @return string HTML fragment
2903 function getHeadScripts() {
2904 global $wgResourceLoaderExperimentalAsyncLoading;
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 ( $wgResourceLoaderExperimentalAsyncLoading ) {
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 global $wgUseSiteJs, $wgAllowUserJs;
2966 // Scripts and messages "only" requests marked for bottom inclusion
2967 // If we're in the <head>, use load() calls rather than <script src="..."> tags
2968 // Messages should go first
2969 $links = array();
2970 $links[] = $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'bottom' ),
2971 ResourceLoaderModule::TYPE_MESSAGES, /* $useESI = */ false, /* $extraQuery = */ array(),
2972 /* $loadCall = */ $inHead
2974 $links[] = $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
2975 ResourceLoaderModule::TYPE_SCRIPTS, /* $useESI = */ false, /* $extraQuery = */ array(),
2976 /* $loadCall = */ $inHead
2979 // Modules requests - let the client calculate dependencies and batch requests as it likes
2980 // Only load modules that have marked themselves for loading at the bottom
2981 $modules = $this->getModules( true, 'bottom' );
2982 if ( $modules ) {
2983 $links[] = Html::inlineScript(
2984 ResourceLoader::makeLoaderConditionalScript(
2985 Xml::encodeJsCall( 'mw.loader.load', array( $modules, null, true ) )
2990 // Legacy Scripts
2991 $links[] = "\n" . $this->mScripts;
2993 // Add site JS if enabled
2994 $links[] = $this->makeResourceLoaderLink( 'site', ResourceLoaderModule::TYPE_SCRIPTS,
2995 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2998 // Add user JS if enabled
2999 if ( $wgAllowUserJs
3000 && $this->getUser()->isLoggedIn()
3001 && $this->getTitle()
3002 && $this->getTitle()->isJsSubpage()
3003 && $this->userCanPreview()
3005 # XXX: additional security check/prompt?
3006 // We're on a preview of a JS subpage
3007 // Exclude this page from the user module in case it's in there (bug 26283)
3008 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_SCRIPTS, false,
3009 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() ), $inHead
3011 // Load the previewed JS
3012 $links[] = Html::inlineScript( "\n"
3013 . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
3015 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
3016 // asynchronously and may arrive *after* the inline script here. So the previewed code
3017 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js...
3018 } else {
3019 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
3020 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_SCRIPTS,
3021 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3025 // Group JS is only enabled if site JS is enabled.
3026 $links[] = $this->makeResourceLoaderLink( 'user.groups', ResourceLoaderModule::TYPE_COMBINED,
3027 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3030 return self::getHtmlFromLoaderLinks( $links );
3034 * JS stuff to put at the bottom of the "<body>"
3035 * @return string
3037 function getBottomScripts() {
3038 global $wgResourceLoaderExperimentalAsyncLoading;
3040 // Optimise jQuery ready event cross-browser.
3041 // This also enforces $.isReady to be true at </body> which fixes the
3042 // mw.loader bug in Firefox with using document.write between </body>
3043 // and the DOMContentReady event (bug 47457).
3044 $html = Html::inlineScript( 'window.jQuery && jQuery.ready();' );
3046 if ( !$wgResourceLoaderExperimentalAsyncLoading ) {
3047 $html .= $this->getScriptsForBottomQueue( false );
3050 return $html;
3054 * Get the javascript config vars to include on this page
3056 * @return array Array of javascript config vars
3057 * @since 1.23
3059 public function getJsConfigVars() {
3060 return $this->mJsConfigVars;
3064 * Add one or more variables to be set in mw.config in JavaScript
3066 * @param string|array $keys Key or array of key/value pairs
3067 * @param mixed $value [optional] Value of the configuration variable
3069 public function addJsConfigVars( $keys, $value = null ) {
3070 if ( is_array( $keys ) ) {
3071 foreach ( $keys as $key => $value ) {
3072 $this->mJsConfigVars[$key] = $value;
3074 return;
3077 $this->mJsConfigVars[$keys] = $value;
3081 * Get an array containing the variables to be set in mw.config in JavaScript.
3083 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3084 * - in other words, page-independent/site-wide variables (without state).
3085 * You will only be adding bloat to the html page and causing page caches to
3086 * have to be purged on configuration changes.
3087 * @return array
3089 private function getJSVars() {
3090 global $wgContLang;
3092 $curRevisionId = 0;
3093 $articleId = 0;
3094 $canonicalSpecialPageName = false; # bug 21115
3096 $title = $this->getTitle();
3097 $ns = $title->getNamespace();
3098 $canonicalNamespace = MWNamespace::exists( $ns )
3099 ? MWNamespace::getCanonicalName( $ns )
3100 : $title->getNsText();
3102 $sk = $this->getSkin();
3103 // Get the relevant title so that AJAX features can use the correct page name
3104 // when making API requests from certain special pages (bug 34972).
3105 $relevantTitle = $sk->getRelevantTitle();
3106 $relevantUser = $sk->getRelevantUser();
3108 if ( $ns == NS_SPECIAL ) {
3109 list( $canonicalSpecialPageName, /*...*/ ) =
3110 SpecialPageFactory::resolveAlias( $title->getDBkey() );
3111 } elseif ( $this->canUseWikiPage() ) {
3112 $wikiPage = $this->getWikiPage();
3113 $curRevisionId = $wikiPage->getLatest();
3114 $articleId = $wikiPage->getId();
3117 $lang = $title->getPageLanguage();
3119 // Pre-process information
3120 $separatorTransTable = $lang->separatorTransformTable();
3121 $separatorTransTable = $separatorTransTable ? $separatorTransTable : array();
3122 $compactSeparatorTransTable = array(
3123 implode( "\t", array_keys( $separatorTransTable ) ),
3124 implode( "\t", $separatorTransTable ),
3126 $digitTransTable = $lang->digitTransformTable();
3127 $digitTransTable = $digitTransTable ? $digitTransTable : array();
3128 $compactDigitTransTable = array(
3129 implode( "\t", array_keys( $digitTransTable ) ),
3130 implode( "\t", $digitTransTable ),
3133 $user = $this->getUser();
3135 $vars = array(
3136 'wgCanonicalNamespace' => $canonicalNamespace,
3137 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3138 'wgNamespaceNumber' => $title->getNamespace(),
3139 'wgPageName' => $title->getPrefixedDBkey(),
3140 'wgTitle' => $title->getText(),
3141 'wgCurRevisionId' => $curRevisionId,
3142 'wgRevisionId' => (int)$this->getRevisionId(),
3143 'wgArticleId' => $articleId,
3144 'wgIsArticle' => $this->isArticle(),
3145 'wgIsRedirect' => $title->isRedirect(),
3146 'wgAction' => Action::getActionName( $this->getContext() ),
3147 'wgUserName' => $user->isAnon() ? null : $user->getName(),
3148 'wgUserGroups' => $user->getEffectiveGroups(),
3149 'wgCategories' => $this->getCategories(),
3150 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3151 'wgPageContentLanguage' => $lang->getCode(),
3152 'wgPageContentModel' => $title->getContentModel(),
3153 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3154 'wgDigitTransformTable' => $compactDigitTransTable,
3155 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3156 'wgMonthNames' => $lang->getMonthNamesArray(),
3157 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3158 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3161 if ( $user->isLoggedIn() ) {
3162 $vars['wgUserId'] = $user->getId();
3163 $vars['wgUserEditCount'] = $user->getEditCount();
3164 $userReg = wfTimestampOrNull( TS_UNIX, $user->getRegistration() );
3165 $vars['wgUserRegistration'] = $userReg !== null ? ( $userReg * 1000 ) : null;
3166 // Get the revision ID of the oldest new message on the user's talk
3167 // page. This can be used for constructing new message alerts on
3168 // the client side.
3169 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3172 if ( $wgContLang->hasVariants() ) {
3173 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3175 // Same test as SkinTemplate
3176 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3177 && ( $title->exists() || $title->quickUserCan( 'create', $user ) );
3179 foreach ( $title->getRestrictionTypes() as $type ) {
3180 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3183 if ( $title->isMainPage() ) {
3184 $vars['wgIsMainPage'] = true;
3187 if ( $this->mRedirectedFrom ) {
3188 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom->getPrefixedDBkey();
3191 if ( $relevantUser ) {
3192 $vars['wgRelevantUserName'] = $relevantUser->getName();
3195 // Allow extensions to add their custom variables to the mw.config map.
3196 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3197 // page-dependant but site-wide (without state).
3198 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3199 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
3201 // Merge in variables from addJsConfigVars last
3202 return array_merge( $vars, $this->getJsConfigVars() );
3206 * To make it harder for someone to slip a user a fake
3207 * user-JavaScript or user-CSS preview, a random token
3208 * is associated with the login session. If it's not
3209 * passed back with the preview request, we won't render
3210 * the code.
3212 * @return bool
3214 public function userCanPreview() {
3215 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
3216 || !$this->getRequest()->wasPosted()
3217 || !$this->getUser()->matchEditToken(
3218 $this->getRequest()->getVal( 'wpEditToken' ) )
3220 return false;
3222 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
3223 return false;
3226 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
3230 * @return array in format "link name or number => 'link html'".
3232 public function getHeadLinksArray() {
3233 global $wgUniversalEditButton, $wgFavicon, $wgAppleTouchIcon, $wgEnableAPI,
3234 $wgSitename, $wgVersion,
3235 $wgFeed, $wgOverrideSiteFeed, $wgAdvertisedFeedTypes,
3236 $wgDisableLangConversion, $wgCanonicalLanguageLinks,
3237 $wgRightsPage, $wgRightsUrl;
3239 $tags = array();
3241 $canonicalUrl = $this->mCanonicalUrl;
3243 $tags['meta-generator'] = Html::element( 'meta', array(
3244 'name' => 'generator',
3245 'content' => "MediaWiki $wgVersion",
3246 ) );
3248 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3249 if ( $p !== 'index,follow' ) {
3250 // http://www.robotstxt.org/wc/meta-user.html
3251 // Only show if it's different from the default robots policy
3252 $tags['meta-robots'] = Html::element( 'meta', array(
3253 'name' => 'robots',
3254 'content' => $p,
3255 ) );
3258 foreach ( $this->mMetatags as $tag ) {
3259 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3260 $a = 'http-equiv';
3261 $tag[0] = substr( $tag[0], 5 );
3262 } else {
3263 $a = 'name';
3265 $tagName = "meta-{$tag[0]}";
3266 if ( isset( $tags[$tagName] ) ) {
3267 $tagName .= $tag[1];
3269 $tags[$tagName] = Html::element( 'meta',
3270 array(
3271 $a => $tag[0],
3272 'content' => $tag[1]
3277 foreach ( $this->mLinktags as $tag ) {
3278 $tags[] = Html::element( 'link', $tag );
3281 # Universal edit button
3282 if ( $wgUniversalEditButton && $this->isArticleRelated() ) {
3283 $user = $this->getUser();
3284 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3285 && ( $this->getTitle()->exists() || $this->getTitle()->quickUserCan( 'create', $user ) ) ) {
3286 // Original UniversalEditButton
3287 $msg = $this->msg( 'edit' )->text();
3288 $tags['universal-edit-button'] = Html::element( 'link', array(
3289 'rel' => 'alternate',
3290 'type' => 'application/x-wiki',
3291 'title' => $msg,
3292 'href' => $this->getTitle()->getEditURL(),
3293 ) );
3294 // Alternate edit link
3295 $tags['alternative-edit'] = Html::element( 'link', array(
3296 'rel' => 'edit',
3297 'title' => $msg,
3298 'href' => $this->getTitle()->getEditURL(),
3299 ) );
3303 # Generally the order of the favicon and apple-touch-icon links
3304 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3305 # uses whichever one appears later in the HTML source. Make sure
3306 # apple-touch-icon is specified first to avoid this.
3307 if ( $wgAppleTouchIcon !== false ) {
3308 $tags['apple-touch-icon'] = Html::element( 'link', array(
3309 'rel' => 'apple-touch-icon',
3310 'href' => $wgAppleTouchIcon
3311 ) );
3314 if ( $wgFavicon !== false ) {
3315 $tags['favicon'] = Html::element( 'link', array(
3316 'rel' => 'shortcut icon',
3317 'href' => $wgFavicon
3318 ) );
3321 # OpenSearch description link
3322 $tags['opensearch'] = Html::element( 'link', array(
3323 'rel' => 'search',
3324 'type' => 'application/opensearchdescription+xml',
3325 'href' => wfScript( 'opensearch_desc' ),
3326 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3327 ) );
3329 if ( $wgEnableAPI ) {
3330 # Real Simple Discovery link, provides auto-discovery information
3331 # for the MediaWiki API (and potentially additional custom API
3332 # support such as WordPress or Twitter-compatible APIs for a
3333 # blogging extension, etc)
3334 $tags['rsd'] = Html::element( 'link', array(
3335 'rel' => 'EditURI',
3336 'type' => 'application/rsd+xml',
3337 // Output a protocol-relative URL here if $wgServer is protocol-relative
3338 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
3339 'href' => wfExpandUrl( wfAppendQuery(
3340 wfScript( 'api' ),
3341 array( 'action' => 'rsd' ) ),
3342 PROTO_RELATIVE
3344 ) );
3347 # Language variants
3348 if ( !$wgDisableLangConversion && $wgCanonicalLanguageLinks ) {
3349 $lang = $this->getTitle()->getPageLanguage();
3350 if ( $lang->hasVariants() ) {
3352 $urlvar = $lang->getURLVariant();
3354 if ( !$urlvar ) {
3355 $variants = $lang->getVariants();
3356 foreach ( $variants as $_v ) {
3357 $tags["variant-$_v"] = Html::element( 'link', array(
3358 'rel' => 'alternate',
3359 'hreflang' => wfBCP47( $_v ),
3360 'href' => $this->getTitle()->getLocalURL( array( 'variant' => $_v ) ) )
3363 } else {
3364 $canonicalUrl = $this->getTitle()->getLocalURL();
3369 # Copyright
3370 $copyright = '';
3371 if ( $wgRightsPage ) {
3372 $copy = Title::newFromText( $wgRightsPage );
3374 if ( $copy ) {
3375 $copyright = $copy->getLocalURL();
3379 if ( !$copyright && $wgRightsUrl ) {
3380 $copyright = $wgRightsUrl;
3383 if ( $copyright ) {
3384 $tags['copyright'] = Html::element( 'link', array(
3385 'rel' => 'copyright',
3386 'href' => $copyright )
3390 # Feeds
3391 if ( $wgFeed ) {
3392 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3393 # Use the page name for the title. In principle, this could
3394 # lead to issues with having the same name for different feeds
3395 # corresponding to the same page, but we can't avoid that at
3396 # this low a level.
3398 $tags[] = $this->feedLink(
3399 $format,
3400 $link,
3401 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3402 $this->msg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )->text()
3406 # Recent changes feed should appear on every page (except recentchanges,
3407 # that would be redundant). Put it after the per-page feed to avoid
3408 # changing existing behavior. It's still available, probably via a
3409 # menu in your browser. Some sites might have a different feed they'd
3410 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3411 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3412 # If so, use it instead.
3413 if ( $wgOverrideSiteFeed ) {
3414 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
3415 // Note, this->feedLink escapes the url.
3416 $tags[] = $this->feedLink(
3417 $type,
3418 $feedUrl,
3419 $this->msg( "site-{$type}-feed", $wgSitename )->text()
3422 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3423 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
3424 foreach ( $wgAdvertisedFeedTypes as $format ) {
3425 $tags[] = $this->feedLink(
3426 $format,
3427 $rctitle->getLocalURL( array( 'feed' => $format ) ),
3428 # For grep: 'site-rss-feed', 'site-atom-feed'
3429 $this->msg( "site-{$format}-feed", $wgSitename )->text()
3435 # Canonical URL
3436 global $wgEnableCanonicalServerLink;
3437 if ( $wgEnableCanonicalServerLink ) {
3438 if ( $canonicalUrl !== false ) {
3439 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL );
3440 } else {
3441 $reqUrl = $this->getRequest()->getRequestURL();
3442 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL );
3445 if ( $canonicalUrl !== false ) {
3446 $tags[] = Html::element( 'link', array(
3447 'rel' => 'canonical',
3448 'href' => $canonicalUrl
3449 ) );
3452 return $tags;
3456 * @return string HTML tag links to be put in the header.
3457 * @deprecated since 1.24 Use OutputPage::headElement or if you have to,
3458 * OutputPage::getHeadLinksArray directly.
3460 public function getHeadLinks() {
3461 wfDeprecated( __METHOD__, '1.24' );
3462 return implode( "\n", $this->getHeadLinksArray() );
3466 * Generate a "<link rel/>" for a feed.
3468 * @param string $type Feed type
3469 * @param string $url URL to the feed
3470 * @param string $text Value of the "title" attribute
3471 * @return string HTML fragment
3473 private function feedLink( $type, $url, $text ) {
3474 return Html::element( 'link', array(
3475 'rel' => 'alternate',
3476 'type' => "application/$type+xml",
3477 'title' => $text,
3478 'href' => $url )
3483 * Add a local or specified stylesheet, with the given media options.
3484 * Meant primarily for internal use...
3486 * @param string $style URL to the file
3487 * @param string $media to specify a media type, 'screen', 'printable', 'handheld' or any.
3488 * @param string $condition for IE conditional comments, specifying an IE version
3489 * @param string $dir set to 'rtl' or 'ltr' for direction-specific sheets
3491 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3492 $options = array();
3493 // Even though we expect the media type to be lowercase, but here we
3494 // force it to lowercase to be safe.
3495 if ( $media ) {
3496 $options['media'] = $media;
3498 if ( $condition ) {
3499 $options['condition'] = $condition;
3501 if ( $dir ) {
3502 $options['dir'] = $dir;
3504 $this->styles[$style] = $options;
3508 * Adds inline CSS styles
3509 * @param mixed $style_css Inline CSS
3510 * @param string $flip Set to 'flip' to flip the CSS if needed
3512 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3513 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3514 # If wanted, and the interface is right-to-left, flip the CSS
3515 $style_css = CSSJanus::transform( $style_css, true, false );
3517 $this->mInlineStyles .= Html::inlineStyle( $style_css ) . "\n";
3521 * Build a set of "<link>" elements for the stylesheets specified in the $this->styles array.
3522 * These will be applied to various media & IE conditionals.
3524 * @return string
3526 public function buildCssLinks() {
3527 global $wgUseSiteCss, $wgAllowUserCss, $wgAllowUserCssPrefs, $wgContLang;
3529 $this->getSkin()->setupSkinUserCss( $this );
3531 // Add ResourceLoader styles
3532 // Split the styles into these groups
3533 $styles = array(
3534 'other' => array(),
3535 'user' => array(),
3536 'site' => array(),
3537 'private' => array(),
3538 'noscript' => array()
3540 $links = array();
3541 $otherTags = ''; // Tags to append after the normal <link> tags
3542 $resourceLoader = $this->getResourceLoader();
3544 $moduleStyles = $this->getModuleStyles();
3546 // Per-site custom styles
3547 $moduleStyles[] = 'site';
3548 $moduleStyles[] = 'noscript';
3549 $moduleStyles[] = 'user.groups';
3551 // Per-user custom styles
3552 if ( $wgAllowUserCss && $this->getTitle()->isCssSubpage() && $this->userCanPreview() ) {
3553 // We're on a preview of a CSS subpage
3554 // Exclude this page from the user module in case it's in there (bug 26283)
3555 $link = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_STYLES, false,
3556 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3558 $otherTags .= $link['html'];
3560 // Load the previewed CSS
3561 // If needed, Janus it first. This is user-supplied CSS, so it's
3562 // assumed to be right for the content language directionality.
3563 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3564 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3565 $previewedCSS = CSSJanus::transform( $previewedCSS, true, false );
3567 $otherTags .= Html::inlineStyle( $previewedCSS ) . "\n";
3568 } else {
3569 // Load the user styles normally
3570 $moduleStyles[] = 'user';
3573 // Per-user preference styles
3574 $moduleStyles[] = 'user.cssprefs';
3576 foreach ( $moduleStyles as $name ) {
3577 $module = $resourceLoader->getModule( $name );
3578 if ( !$module ) {
3579 continue;
3581 $group = $module->getGroup();
3582 // Modules in groups different than the ones listed on top (see $styles assignment)
3583 // will be placed in the "other" group
3584 $styles[ isset( $styles[$group] ) ? $group : 'other' ][] = $name;
3587 // We want site, private and user styles to override dynamically added
3588 // styles from modules, but we want dynamically added styles to override
3589 // statically added styles from other modules. So the order has to be
3590 // other, dynamic, site, private, user. Add statically added styles for
3591 // other modules
3592 $links[] = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule::TYPE_STYLES );
3593 // Add normal styles added through addStyle()/addInlineStyle() here
3594 $links[] = implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles;
3595 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3596 // We use a <meta> tag with a made-up name for this because that's valid HTML
3597 $links[] = Html::element(
3598 'meta',
3599 array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' )
3600 ) . "\n";
3602 // Add site, private and user styles
3603 // 'private' at present only contains user.options, so put that before 'user'
3604 // Any future private modules will likely have a similar user-specific character
3605 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3606 $links[] = $this->makeResourceLoaderLink( $styles[$group],
3607 ResourceLoaderModule::TYPE_STYLES
3611 // Add stuff in $otherTags (previewed user CSS if applicable)
3612 return self::getHtmlFromLoaderLinks( $links ) . $otherTags;
3616 * @return array
3618 public function buildCssLinksArray() {
3619 $links = array();
3621 // Add any extension CSS
3622 foreach ( $this->mExtStyles as $url ) {
3623 $this->addStyle( $url );
3625 $this->mExtStyles = array();
3627 foreach ( $this->styles as $file => $options ) {
3628 $link = $this->styleLink( $file, $options );
3629 if ( $link ) {
3630 $links[$file] = $link;
3633 return $links;
3637 * Generate \<link\> tags for stylesheets
3639 * @param string $style URL to the file
3640 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3641 * @return string HTML fragment
3643 protected function styleLink( $style, $options ) {
3644 if ( isset( $options['dir'] ) ) {
3645 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3646 return '';
3650 if ( isset( $options['media'] ) ) {
3651 $media = self::transformCssMedia( $options['media'] );
3652 if ( is_null( $media ) ) {
3653 return '';
3655 } else {
3656 $media = 'all';
3659 if ( substr( $style, 0, 1 ) == '/' ||
3660 substr( $style, 0, 5 ) == 'http:' ||
3661 substr( $style, 0, 6 ) == 'https:' ) {
3662 $url = $style;
3663 } else {
3664 global $wgStylePath, $wgStyleVersion;
3665 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
3668 $link = Html::linkedStyle( $url, $media );
3670 if ( isset( $options['condition'] ) ) {
3671 $condition = htmlspecialchars( $options['condition'] );
3672 $link = "<!--[if $condition]>$link<![endif]-->";
3674 return $link;
3678 * Transform "media" attribute based on request parameters
3680 * @param string $media Current value of the "media" attribute
3681 * @return string Modified value of the "media" attribute, or null to skip
3682 * this stylesheet
3684 public static function transformCssMedia( $media ) {
3685 global $wgRequest;
3687 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3688 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3690 // Switch in on-screen display for media testing
3691 $switches = array(
3692 'printable' => 'print',
3693 'handheld' => 'handheld',
3695 foreach ( $switches as $switch => $targetMedia ) {
3696 if ( $wgRequest->getBool( $switch ) ) {
3697 if ( $media == $targetMedia ) {
3698 $media = '';
3699 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3700 // This regex will not attempt to understand a comma-separated media_query_list
3702 // Example supported values for $media:
3703 // 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3704 // Example NOT supported value for $media:
3705 // '3d-glasses, screen, print and resolution > 90dpi'
3707 // If it's a print request, we never want any kind of screen stylesheets
3708 // If it's a handheld request (currently the only other choice with a switch),
3709 // we don't want simple 'screen' but we might want screen queries that
3710 // have a max-width or something, so we'll pass all others on and let the
3711 // client do the query.
3712 if ( $targetMedia == 'print' || $media == 'screen' ) {
3713 return null;
3719 return $media;
3723 * Add a wikitext-formatted message to the output.
3724 * This is equivalent to:
3726 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3728 public function addWikiMsg( /*...*/ ) {
3729 $args = func_get_args();
3730 $name = array_shift( $args );
3731 $this->addWikiMsgArray( $name, $args );
3735 * Add a wikitext-formatted message to the output.
3736 * Like addWikiMsg() except the parameters are taken as an array
3737 * instead of a variable argument list.
3739 * @param string $name
3740 * @param array $args
3742 public function addWikiMsgArray( $name, $args ) {
3743 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3747 * This function takes a number of message/argument specifications, wraps them in
3748 * some overall structure, and then parses the result and adds it to the output.
3750 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3751 * on. The subsequent arguments may either be strings, in which case they are the
3752 * message names, or arrays, in which case the first element is the message name,
3753 * and subsequent elements are the parameters to that message.
3755 * Don't use this for messages that are not in users interface language.
3757 * For example:
3759 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3761 * Is equivalent to:
3763 * $wgOut->addWikiText( "<div class='error'>\n"
3764 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3766 * The newline after opening div is needed in some wikitext. See bug 19226.
3768 * @param string $wrap
3770 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3771 $msgSpecs = func_get_args();
3772 array_shift( $msgSpecs );
3773 $msgSpecs = array_values( $msgSpecs );
3774 $s = $wrap;
3775 foreach ( $msgSpecs as $n => $spec ) {
3776 if ( is_array( $spec ) ) {
3777 $args = $spec;
3778 $name = array_shift( $args );
3779 if ( isset( $args['options'] ) ) {
3780 unset( $args['options'] );
3781 wfDeprecated(
3782 'Adding "options" to ' . __METHOD__ . ' is no longer supported',
3783 '1.20'
3786 } else {
3787 $args = array();
3788 $name = $spec;
3790 $s = str_replace( '$' . ( $n + 1 ), $this->msg( $name, $args )->plain(), $s );
3792 $this->addWikiText( $s );
3796 * Include jQuery core. Use this to avoid loading it multiple times
3797 * before we get a usable script loader.
3799 * @param array $modules List of jQuery modules which should be loaded
3800 * @return array The list of modules which were not loaded.
3801 * @since 1.16
3802 * @deprecated since 1.17
3804 public function includeJQuery( $modules = array() ) {
3805 return array();
3809 * Enables/disables TOC, doesn't override __NOTOC__
3810 * @param bool $flag
3811 * @since 1.22
3813 public function enableTOC( $flag = true ) {
3814 $this->mEnableTOC = $flag;
3818 * @return bool
3819 * @since 1.22
3821 public function isTOCEnabled() {
3822 return $this->mEnableTOC;
3826 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3827 * @param bool $flag
3828 * @since 1.23
3830 public function enableSectionEditLinks( $flag = true ) {
3831 $this->mEnableSectionEditLinks = $flag;
3835 * @return bool
3836 * @since 1.23
3838 public function sectionEditLinksEnabled() {
3839 return $this->mEnableSectionEditLinks;