2 if ( !defined( 'MEDIAWIKI' ) ) {
7 * This class should be covered by a general architecture document which does
8 * not exist as of january 2011. This is one of the Core class and should
9 * be read at least once by any new developers.
11 * This class is used to prepare the final rendering. A skin is then
12 * applied to the output parameters (links, javascript, html, categories ...).
14 * Another class (fixme) handle sending the whole page to the client.
16 * Some comments comes from a pairing session between Zak Greant and Ashar Voultoiz
22 /// Should be private. Used with addMeta() which adds <meta>
23 var $mMetatags = array();
25 /// <meta keyworkds="stuff"> most of the time the first 10 links to an article
26 var $mKeywords = array();
28 var $mLinktags = array();
30 /// Additional stylesheets. Looks like this is for extensions. Might be replaced by resource loader.
31 var $mExtStyles = array();
33 /// Should be private - has getter and setter. Contains the HTML title
36 /// Contains all of the <body> content. Should be private we got set/get accessors and the append() method.
40 * Holds the debug lines that will be outputted as comments in page source if
41 * $wgDebugComments is enabled. See also $wgShowDebug.
42 * TODO: make a getter method for this
44 public $mDebugtext = ''; // TODO: we might want to replace it by wfDebug() wfDebugLog()
46 /// Should be private. Stores contents of <title> tag
49 /// Should be private. Is the displayed content related to the source of the corresponding wiki article.
50 var $mIsarticle = true;
53 * Should be private. We have to set isPrintable(). Some pages should
54 * never be printed (ex: redirections).
56 var $mPrintable = false;
59 * Should be private. We have set/get/append methods.
61 * Contains the page subtitle. Special pages usually have some links here.
62 * Don't confuse with site subtitle added by skins.
70 * mLastModified and mEtag are used for sending cache control.
71 * The whole caching system should probably be moved in its own class.
73 var $mLastModified = '';
76 * Should be private. No getter but used in sendCacheControl();
77 * Contains an HTTP Entity Tags (see RFC 2616 section 3.13) which is used
78 * as a unique identifier for the content. It is later used by the client
79 * to compare its cache version with the server version. Client sends
80 * headers If-Match and If-None-Match containing its local cache ETAG value.
82 * To get more information, you will have to look at HTTP1/1 protocols which
83 * is properly described in RFC 2616 : http://tools.ietf.org/html/rfc2616
87 var $mCategoryLinks = array();
88 var $mCategories = array();
90 /// Should be private. Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
91 var $mLanguageLinks = array();
94 * Should be private. Used for JavaScript (pre resource loader)
95 * We should split js / css.
96 * mScripts content is inserted as is in <head> by Skin. This might contains
97 * either a link to a stylesheet or inline css.
102 * Inline CSS styles. Use addInlineStyle() sparsingly
104 var $mInlineStyles = '';
110 * Used by skin template.
111 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
113 var $mPageLinkTitle = '';
115 /// Array of elements in <head>. Parser might add its own headers!
116 var $mHeadItems = array();
118 // Next variables probably comes from the resource loader @todo FIXME
119 var $mModules = array(), $mModuleScripts = array(), $mModuleStyles = array(), $mModuleMessages = array();
120 var $mResourceLoader;
122 /** @fixme is this still used ?*/
123 var $mInlineMsg = array();
125 var $mTemplateIds = array();
127 # What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
128 # @see ResourceLoaderModule::$origin
129 # ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
130 protected $mAllowedModules = array(
131 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
135 * @EasterEgg I just love the name for this self documenting variable.
138 var $mDoNothing = false;
141 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
144 * Should be private. Has get/set methods properly documented.
145 * Stores "article flag" toggle.
147 var $mIsArticleRelated = true;
149 /// lazy initialised, use parserOptions()
150 protected $mParserOptions = null;
153 * Handles the atom / rss links.
154 * We probably only support atom in 2011.
155 * Looks like a private variable.
156 * @see $wgAdvertisedFeedTypes
158 var $mFeedLinks = array();
160 // Gwicke work on squid caching? Roughly from 2003.
161 var $mEnableClientCache = true;
164 * Flag if output should only contain the body of the article.
167 var $mArticleBodyOnly = false;
169 var $mNewSectionLink = false;
170 var $mHideNewSectionLink = false;
173 * Comes from the parser. This was probably made to load CSS/JS only
174 * if we had <gallery>. Used directly in CategoryPage.php
175 * Looks like resource loader can replace this.
177 var $mNoGallery = false;
179 // should be private.
180 var $mPageTitleActionText = '';
181 var $mParseWarnings = array();
183 // Cache stuff. Looks like mEnableClientCache
184 var $mSquidMaxage = 0;
187 var $mPreventClickjacking = true;
189 /// should be private. To include the variable {{REVISIONID}}
190 var $mRevisionId = null;
192 /// Stores a Title object (of the current page).
193 protected $mTitle = null;
196 * An array of stylesheet filenames (relative from skins path), with options
197 * for CSS media, IE conditions, and RTL/LTR direction.
198 * For internal use; add settings in the skin via $this->addStyle()
200 * Style again! This seems like a code duplication since we already have
201 * mStyles. This is what makes OpenSource amazing.
203 var $styles = array();
206 * Whether jQuery is already handled.
208 protected $mJQueryDone = false;
210 private $mIndexPolicy = 'index';
211 private $mFollowPolicy = 'follow';
212 private $mVaryHeader = array(
213 'Accept-Encoding' => array( 'list-contains=gzip' ),
218 * Redirect to $url rather than displaying the normal page
220 * @param $url String: URL
221 * @param $responsecode String: HTTP status code
223 public function redirect( $url, $responsecode = '302' ) {
224 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
225 $this->mRedirect
= str_replace( "\n", '', $url );
226 $this->mRedirectCode
= $responsecode;
230 * Get the URL to redirect to, or an empty string if not redirect URL set
234 public function getRedirect() {
235 return $this->mRedirect
;
239 * Set the HTTP status code to send with the output.
241 * @param $statusCode Integer
243 public function setStatusCode( $statusCode ) {
244 $this->mStatusCode
= $statusCode;
248 * Add a new <meta> tag
249 * To add an http-equiv meta tag, precede the name with "http:"
251 * @param $name String tag name
252 * @param $val String tag value
254 function addMeta( $name, $val ) {
255 array_push( $this->mMetatags
, array( $name, $val ) );
259 * Add a keyword or a list of keywords in the page header
261 * @param $text String or array of strings
263 function addKeyword( $text ) {
264 if( is_array( $text ) ) {
265 $this->mKeywords
= array_merge( $this->mKeywords
, $text );
267 array_push( $this->mKeywords
, $text );
272 * Add a new \<link\> tag to the page header
274 * @param $linkarr Array: associative array of attributes.
276 function addLink( $linkarr ) {
277 array_push( $this->mLinktags
, $linkarr );
281 * Add a new \<link\> with "rel" attribute set to "meta"
283 * @param $linkarr Array: associative array mapping attribute names to their
284 * values, both keys and values will be escaped, and the
285 * "rel" attribute will be automatically added
287 function addMetadataLink( $linkarr ) {
288 # note: buggy CC software only reads first "meta" link
289 static $haveMeta = false;
290 $linkarr['rel'] = $haveMeta ?
'alternate meta' : 'meta';
291 $this->addLink( $linkarr );
296 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
298 * @param $script String: raw HTML
300 function addScript( $script ) {
301 $this->mScripts
.= $script . "\n";
305 * Register and add a stylesheet from an extension directory.
307 * @param $url String path to sheet. Provide either a full url (beginning
308 * with 'http', etc) or a relative path from the document root
309 * (beginning with '/'). Otherwise it behaves identically to
310 * addStyle() and draws from the /skins folder.
312 public function addExtensionStyle( $url ) {
313 array_push( $this->mExtStyles
, $url );
317 * Get all styles added by extensions
321 function getExtStyle() {
322 return $this->mExtStyles
;
326 * Add a JavaScript file out of skins/common, or a given relative path.
328 * @param $file String: filename in skins/common or complete on-server path
330 * @param $version String: style version of the file. Defaults to $wgStyleVersion
332 public function addScriptFile( $file, $version = null ) {
333 global $wgStylePath, $wgStyleVersion;
334 // See if $file parameter is an absolute URL or begins with a slash
335 if( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
338 $path = "{$wgStylePath}/common/{$file}";
340 if ( is_null( $version ) )
341 $version = $wgStyleVersion;
342 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
346 * Add a self-contained script tag with the given contents
348 * @param $script String: JavaScript text, no <script> tags
350 public function addInlineScript( $script ) {
351 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
355 * Get all registered JS and CSS tags for the header.
359 function getScript() {
360 return $this->mScripts
. $this->getHeadItems();
364 * Filter an array of modules to remove insufficiently trustworthy members
365 * @param $modules Array
368 protected function filterModules( $modules, $type = ResourceLoaderModule
::TYPE_COMBINED
){
369 $resourceLoader = $this->getResourceLoader();
370 $filteredModules = array();
371 foreach( $modules as $val ){
372 $module = $resourceLoader->getModule( $val );
373 if( $module->getOrigin() <= $this->getAllowedModules( $type ) ) {
374 $filteredModules[] = $val;
377 return $filteredModules;
381 * Get the list of modules to include on this page
383 * @param $filter Bool whether to filter out insufficiently trustworthy modules
384 * @return Array of module names
386 public function getModules( $filter = false, $param = 'mModules' ) {
387 $modules = array_values( array_unique( $this->$param ) );
389 ?
$this->filterModules( $modules )
394 * Add one or more modules recognized by the resource loader. Modules added
395 * through this function will be loaded by the resource loader when the
398 * @param $modules Mixed: module name (string) or array of module names
400 public function addModules( $modules ) {
401 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
405 * Get the list of module JS to include on this page
406 * @return array of module names
408 public function getModuleScripts( $filter = false ) {
409 return $this->getModules( $filter, 'mModuleScripts' );
413 * Add only JS of one or more modules recognized by the resource loader. Module
414 * scripts added through this function will be loaded by the resource loader when
417 * @param $modules Mixed: module name (string) or array of module names
419 public function addModuleScripts( $modules ) {
420 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
424 * Get the list of module CSS to include on this page
426 * @return Array of module names
428 public function getModuleStyles( $filter = false ) {
429 return $this->getModules( $filter, 'mModuleStyles' );
433 * Add only CSS of one or more modules recognized by the resource loader. Module
434 * styles added through this function will be loaded by the resource loader when
437 * @param $modules Mixed: module name (string) or array of module names
439 public function addModuleStyles( $modules ) {
440 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
444 * Get the list of module messages to include on this page
446 * @return Array of module names
448 public function getModuleMessages( $filter = false ) {
449 return $this->getModules( $filter, 'mModuleMessages' );
453 * Add only messages of one or more modules recognized by the resource loader.
454 * Module messages added through this function will be loaded by the resource
455 * loader when the page loads.
457 * @param $modules Mixed: module name (string) or array of module names
459 public function addModuleMessages( $modules ) {
460 $this->mModuleMessages
= array_merge( $this->mModuleMessages
, (array)$modules );
464 * Get all header items in a string
468 function getHeadItems() {
470 foreach ( $this->mHeadItems
as $item ) {
477 * Add or replace an header item to the output
479 * @param $name String: item name
480 * @param $value String: raw HTML
482 public function addHeadItem( $name, $value ) {
483 $this->mHeadItems
[$name] = $value;
487 * Check if the header item $name is already set
489 * @param $name String: item name
492 public function hasHeadItem( $name ) {
493 return isset( $this->mHeadItems
[$name] );
497 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
499 * @param $tag String: value of "ETag" header
501 function setETag( $tag ) {
506 * Set whether the output should only contain the body of the article,
507 * without any skin, sidebar, etc.
508 * Used e.g. when calling with "action=render".
510 * @param $only Boolean: whether to output only the body of the article
512 public function setArticleBodyOnly( $only ) {
513 $this->mArticleBodyOnly
= $only;
517 * Return whether the output will contain only the body of the article
521 public function getArticleBodyOnly() {
522 return $this->mArticleBodyOnly
;
526 * checkLastModified tells the client to use the client-cached page if
527 * possible. If sucessful, the OutputPage is disabled so that
528 * any future call to OutputPage->output() have no effect.
530 * Side effect: sets mLastModified for Last-Modified header
532 * @return Boolean: true iff cache-ok headers was sent.
534 public function checkLastModified( $timestamp ) {
535 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
537 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
538 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
541 if( !$wgCachePages ) {
542 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
545 if( $wgUser->getOption( 'nocache' ) ) {
546 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
550 $timestamp = wfTimestamp( TS_MW
, $timestamp );
551 $modifiedTimes = array(
552 'page' => $timestamp,
553 'user' => $wgUser->getTouched(),
554 'epoch' => $wgCacheEpoch
556 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
558 $maxModified = max( $modifiedTimes );
559 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
561 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
562 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
568 foreach ( $modifiedTimes as $name => $value ) {
569 if ( $info !== '' ) {
572 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
575 # IE sends sizes after the date like this:
576 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
577 # this breaks strtotime().
578 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
580 wfSuppressWarnings(); // E_STRICT system time bitching
581 $clientHeaderTime = strtotime( $clientHeader );
583 if ( !$clientHeaderTime ) {
584 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
587 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
589 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
590 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
591 wfDebug( __METHOD__
. ": effective Last-Modified: " .
592 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
593 if( $clientHeaderTime < $maxModified ) {
594 wfDebug( __METHOD__
. ": STALE, $info\n", false );
599 # Give a 304 response code and disable body output
600 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
601 ini_set( 'zlib.output_compression', 0 );
602 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
603 $this->sendCacheControl();
606 // Don't output a compressed blob when using ob_gzhandler;
607 // it's technically against HTTP spec and seems to confuse
608 // Firefox when the response gets split over two packets.
609 wfClearOutputBuffers();
615 * Override the last modified timestamp
617 * @param $timestamp String: new timestamp, in a format readable by
620 public function setLastModified( $timestamp ) {
621 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
625 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
627 * @param $policy String: the literal string to output as the contents of
628 * the meta tag. Will be parsed according to the spec and output in
632 public function setRobotPolicy( $policy ) {
633 $policy = Article
::formatRobotPolicy( $policy );
635 if( isset( $policy['index'] ) ) {
636 $this->setIndexPolicy( $policy['index'] );
638 if( isset( $policy['follow'] ) ) {
639 $this->setFollowPolicy( $policy['follow'] );
644 * Set the index policy for the page, but leave the follow policy un-
647 * @param $policy string Either 'index' or 'noindex'.
650 public function setIndexPolicy( $policy ) {
651 $policy = trim( $policy );
652 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
653 $this->mIndexPolicy
= $policy;
658 * Set the follow policy for the page, but leave the index policy un-
661 * @param $policy String: either 'follow' or 'nofollow'.
664 public function setFollowPolicy( $policy ) {
665 $policy = trim( $policy );
666 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
667 $this->mFollowPolicy
= $policy;
672 * Set the new value of the "action text", this will be added to the
673 * "HTML title", separated from it with " - ".
675 * @param $text String: new value of the "action text"
677 public function setPageTitleActionText( $text ) {
678 $this->mPageTitleActionText
= $text;
682 * Get the value of the "action text"
686 public function getPageTitleActionText() {
687 if ( isset( $this->mPageTitleActionText
) ) {
688 return $this->mPageTitleActionText
;
693 * "HTML title" means the contents of <title>.
694 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
696 public function setHTMLTitle( $name ) {
697 $this->mHTMLtitle
= $name;
701 * Return the "HTML title", i.e. the content of the <title> tag.
705 public function getHTMLTitle() {
706 return $this->mHTMLtitle
;
710 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
711 * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
712 * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
713 * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
715 public function setPageTitle( $name ) {
716 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
717 # but leave "<i>foobar</i>" alone
718 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
719 $this->mPagetitle
= $nameWithTags;
721 # change "<i>foo&bar</i>" to "foo&bar"
722 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer
::stripAllTags( $nameWithTags ) ) );
726 * Return the "page title", i.e. the content of the \<h1\> tag.
730 public function getPageTitle() {
731 return $this->mPagetitle
;
735 * Set the Title object to use
737 * @param $t Title object
739 public function setTitle( $t ) {
744 * Get the Title object used in this instance
748 public function getTitle() {
749 if ( $this->mTitle
instanceof Title
) {
750 return $this->mTitle
;
752 wfDebug( __METHOD__
. " called and \$mTitle is null. Return \$wgTitle for sanity\n" );
759 * Replace the subtile with $str
761 * @param $str String: new value of the subtitle
763 public function setSubtitle( $str ) {
764 $this->mSubtitle
= /*$this->parse(*/ $str /*)*/; // @bug 2514
768 * Add $str to the subtitle
770 * @param $str String to add to the subtitle
772 public function appendSubtitle( $str ) {
773 $this->mSubtitle
.= /*$this->parse(*/ $str /*)*/; // @bug 2514
781 public function getSubtitle() {
782 return $this->mSubtitle
;
786 * Set the page as printable, i.e. it'll be displayed with with all
787 * print styles included
789 public function setPrintable() {
790 $this->mPrintable
= true;
794 * Return whether the page is "printable"
798 public function isPrintable() {
799 return $this->mPrintable
;
803 * Disable output completely, i.e. calling output() will have no effect
805 public function disable() {
806 $this->mDoNothing
= true;
810 * Return whether the output will be completely disabled
814 public function isDisabled() {
815 return $this->mDoNothing
;
819 * Show an "add new section" link?
823 public function showNewSectionLink() {
824 return $this->mNewSectionLink
;
828 * Forcibly hide the new section link?
832 public function forceHideNewSectionLink() {
833 return $this->mHideNewSectionLink
;
837 * Add or remove feed links in the page header
838 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
839 * for the new version
842 * @param $show Boolean: true: add default feeds, false: remove all feeds
844 public function setSyndicated( $show = true ) {
846 $this->setFeedAppendQuery( false );
848 $this->mFeedLinks
= array();
853 * Add default feeds to the page header
854 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
855 * for the new version
858 * @param $val String: query to append to feed links or false to output
861 public function setFeedAppendQuery( $val ) {
862 global $wgAdvertisedFeedTypes;
864 $this->mFeedLinks
= array();
866 foreach ( $wgAdvertisedFeedTypes as $type ) {
867 $query = "feed=$type";
868 if ( is_string( $val ) ) {
869 $query .= '&' . $val;
871 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
876 * Add a feed link to the page header
878 * @param $format String: feed type, should be a key of $wgFeedClasses
879 * @param $href String: URL
881 public function addFeedLink( $format, $href ) {
882 global $wgAdvertisedFeedTypes;
884 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
885 $this->mFeedLinks
[$format] = $href;
890 * Should we output feed links for this page?
893 public function isSyndicated() {
894 return count( $this->mFeedLinks
) > 0;
898 * Return URLs for each supported syndication format for this page.
899 * @return array associating format keys with URLs
901 public function getSyndicationLinks() {
902 return $this->mFeedLinks
;
906 * Will currently always return null
910 public function getFeedAppendQuery() {
911 return $this->mFeedLinksAppendQuery
;
915 * Set whether the displayed content is related to the source of the
916 * corresponding article on the wiki
917 * Setting true will cause the change "article related" toggle to true
921 public function setArticleFlag( $v ) {
922 $this->mIsarticle
= $v;
924 $this->mIsArticleRelated
= $v;
929 * Return whether the content displayed page is related to the source of
930 * the corresponding article on the wiki
934 public function isArticle() {
935 return $this->mIsarticle
;
939 * Set whether this page is related an article on the wiki
940 * Setting false will cause the change of "article flag" toggle to false
944 public function setArticleRelated( $v ) {
945 $this->mIsArticleRelated
= $v;
947 $this->mIsarticle
= false;
952 * Return whether this page is related an article on the wiki
956 public function isArticleRelated() {
957 return $this->mIsArticleRelated
;
961 * Add new language links
963 * @param $newLinkArray Associative array mapping language code to the page
966 public function addLanguageLinks( $newLinkArray ) {
967 $this->mLanguageLinks +
= $newLinkArray;
971 * Reset the language links and add new language links
973 * @param $newLinkArray Associative array mapping language code to the page
976 public function setLanguageLinks( $newLinkArray ) {
977 $this->mLanguageLinks
= $newLinkArray;
981 * Get the list of language links
983 * @return Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
985 public function getLanguageLinks() {
986 return $this->mLanguageLinks
;
990 * Add an array of categories, with names in the keys
992 * @param $categories Array mapping category name => sort key
994 public function addCategoryLinks( $categories ) {
995 global $wgUser, $wgContLang;
997 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1001 # Add the links to a LinkBatch
1002 $arr = array( NS_CATEGORY
=> $categories );
1003 $lb = new LinkBatch
;
1004 $lb->setArray( $arr );
1006 # Fetch existence plus the hiddencat property
1007 $dbr = wfGetDB( DB_SLAVE
);
1008 $res = $dbr->select( array( 'page', 'page_props' ),
1009 array( 'page_id', 'page_namespace', 'page_title', 'page_len', 'page_is_redirect', 'page_latest', 'pp_value' ),
1010 $lb->constructSet( 'page', $dbr ),
1013 array( 'page_props' => array( 'LEFT JOIN', array( 'pp_propname' => 'hiddencat', 'pp_page = page_id' ) ) )
1016 # Add the results to the link cache
1017 $lb->addResultToCache( LinkCache
::singleton(), $res );
1019 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
1020 $categories = array_combine(
1021 array_keys( $categories ),
1022 array_fill( 0, count( $categories ), 'normal' )
1025 # Mark hidden categories
1026 foreach ( $res as $row ) {
1027 if ( isset( $row->pp_value
) ) {
1028 $categories[$row->page_title
] = 'hidden';
1032 # Add the remaining categories to the skin
1033 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
1034 $sk = $wgUser->getSkin();
1035 foreach ( $categories as $category => $type ) {
1036 $origcategory = $category;
1037 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1038 $wgContLang->findVariantLink( $category, $title, true );
1039 if ( $category != $origcategory ) {
1040 if ( array_key_exists( $category, $categories ) ) {
1044 $text = $wgContLang->convertHtml( $title->getText() );
1045 $this->mCategories
[] = $title->getText();
1046 $this->mCategoryLinks
[$type][] = $sk->link( $title, $text );
1052 * Reset the category links (but not the category list) and add $categories
1054 * @param $categories Array mapping category name => sort key
1056 public function setCategoryLinks( $categories ) {
1057 $this->mCategoryLinks
= array();
1058 $this->addCategoryLinks( $categories );
1062 * Get the list of category links, in a 2-D array with the following format:
1063 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1064 * hidden categories) and $link a HTML fragment with a link to the category
1069 public function getCategoryLinks() {
1070 return $this->mCategoryLinks
;
1074 * Get the list of category names this page belongs to
1076 * @return Array of strings
1078 public function getCategories() {
1079 return $this->mCategories
;
1083 * Do not allow scripts which can be modified by wiki users to load on this page;
1084 * only allow scripts bundled with, or generated by, the software.
1086 public function disallowUserJs() {
1087 $this->reduceAllowedModules(
1088 ResourceLoaderModule
::TYPE_SCRIPTS
,
1089 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1094 * Return whether user JavaScript is allowed for this page
1095 * @deprecated @since 1.18 Load modules with ResourceLoader, and origin and
1096 * trustworthiness is identified and enforced automagically.
1099 public function isUserJsAllowed() {
1100 return $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
) >= ResourceLoaderModule
::ORIGIN_USER_INDIVIDUAL
;
1104 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1105 * @see ResourceLoaderModule::$origin
1106 * @param $type String ResourceLoaderModule TYPE_ constant
1107 * @return Int ResourceLoaderModule ORIGIN_ class constant
1109 public function getAllowedModules( $type ){
1110 if( $type == ResourceLoaderModule
::TYPE_COMBINED
){
1111 return min( array_values( $this->mAllowedModules
) );
1113 return isset( $this->mAllowedModules
[$type] )
1114 ?
$this->mAllowedModules
[$type]
1115 : ResourceLoaderModule
::ORIGIN_ALL
;
1120 * Set the highest level of CSS/JS untrustworthiness allowed
1121 * @param $type String ResourceLoaderModule TYPE_ constant
1122 * @param $level Int ResourceLoaderModule class constant
1124 public function setAllowedModules( $type, $level ){
1125 $this->mAllowedModules
[$type] = $level;
1129 * As for setAllowedModules(), but don't inadvertantly make the page more accessible
1130 * @param $type String
1131 * @param $level Int ResourceLoaderModule class constant
1133 public function reduceAllowedModules( $type, $level ){
1134 $this->mAllowedModules
[$type] = min( $this->getAllowedModules($type), $level );
1138 * Prepend $text to the body HTML
1140 * @param $text String: HTML
1142 public function prependHTML( $text ) {
1143 $this->mBodytext
= $text . $this->mBodytext
;
1147 * Append $text to the body HTML
1149 * @param $text String: HTML
1151 public function addHTML( $text ) {
1152 $this->mBodytext
.= $text;
1156 * Clear the body HTML
1158 public function clearHTML() {
1159 $this->mBodytext
= '';
1165 * @return String: HTML
1167 public function getHTML() {
1168 return $this->mBodytext
;
1172 * Add $text to the debug output
1174 * @param $text String: debug text
1176 public function debug( $text ) {
1177 $this->mDebugtext
.= $text;
1181 * Get/set the ParserOptions object to use for wikitext parsing
1183 * @param $options either the ParserOption to use or null to only get the
1184 * current ParserOption object
1185 * @return current ParserOption object
1187 public function parserOptions( $options = null ) {
1188 if ( !$this->mParserOptions
) {
1189 $this->mParserOptions
= new ParserOptions
;
1191 return wfSetVar( $this->mParserOptions
, $options );
1195 * Set the revision ID which will be seen by the wiki text parser
1196 * for things such as embedded {{REVISIONID}} variable use.
1198 * @param $revid Mixed: an positive integer, or null
1199 * @return Mixed: previous value
1201 public function setRevisionId( $revid ) {
1202 $val = is_null( $revid ) ?
null : intval( $revid );
1203 return wfSetVar( $this->mRevisionId
, $val );
1207 * Get the current revision ID
1211 public function getRevisionId() {
1212 return $this->mRevisionId
;
1216 * Convert wikitext to HTML and add it to the buffer
1217 * Default assumes that the current page title will be used.
1219 * @param $text String
1220 * @param $linestart Boolean: is this the start of a line?
1222 public function addWikiText( $text, $linestart = true ) {
1223 $title = $this->getTitle(); // Work arround E_STRICT
1224 $this->addWikiTextTitle( $text, $title, $linestart );
1228 * Add wikitext with a custom Title object
1230 * @param $text String: wikitext
1231 * @param $title Title object
1232 * @param $linestart Boolean: is this the start of a line?
1234 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1235 $this->addWikiTextTitle( $text, $title, $linestart );
1239 * Add wikitext with a custom Title object and
1241 * @param $text String: wikitext
1242 * @param $title Title object
1243 * @param $linestart Boolean: is this the start of a line?
1245 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1246 $this->addWikiTextTitle( $text, $title, $linestart, true );
1250 * Add wikitext with tidy enabled
1252 * @param $text String: wikitext
1253 * @param $linestart Boolean: is this the start of a line?
1255 public function addWikiTextTidy( $text, $linestart = true ) {
1256 $title = $this->getTitle();
1257 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1261 * Add wikitext with a custom Title object
1263 * @param $text String: wikitext
1264 * @param $title Title object
1265 * @param $linestart Boolean: is this the start of a line?
1266 * @param $tidy Boolean: whether to use tidy
1268 public function addWikiTextTitle( $text, &$title, $linestart, $tidy = false ) {
1271 wfProfileIn( __METHOD__
);
1273 wfIncrStats( 'pcache_not_possible' );
1275 $popts = $this->parserOptions();
1276 $oldTidy = $popts->setTidy( $tidy );
1278 $parserOutput = $wgParser->parse(
1279 $text, $title, $popts,
1280 $linestart, true, $this->mRevisionId
1283 $popts->setTidy( $oldTidy );
1285 $this->addParserOutput( $parserOutput );
1287 wfProfileOut( __METHOD__
);
1291 * Add a ParserOutput object, but without Html
1293 * @param $parserOutput ParserOutput object
1295 public function addParserOutputNoText( &$parserOutput ) {
1296 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1297 $this->addCategoryLinks( $parserOutput->getCategories() );
1298 $this->mNewSectionLink
= $parserOutput->getNewSection();
1299 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1301 $this->mParseWarnings
= $parserOutput->getWarnings();
1302 if ( !$parserOutput->isCacheable() ) {
1303 $this->enableClientCache( false );
1305 $this->mNoGallery
= $parserOutput->getNoGallery();
1306 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1307 $this->addModules( $parserOutput->getModules() );
1309 foreach ( (array)$parserOutput->mTemplateIds
as $ns => $dbks ) {
1310 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1311 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1313 $this->mTemplateIds
[$ns] = $dbks;
1317 // Hooks registered in the object
1318 global $wgParserOutputHooks;
1319 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1320 list( $hookName, $data ) = $hookInfo;
1321 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1322 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1326 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1330 * Add a ParserOutput object
1332 * @param $parserOutput ParserOutput
1334 function addParserOutput( &$parserOutput ) {
1335 $this->addParserOutputNoText( $parserOutput );
1336 $text = $parserOutput->getText();
1337 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1338 $this->addHTML( $text );
1343 * Add the output of a QuickTemplate to the output buffer
1345 * @param $template QuickTemplate
1347 public function addTemplate( &$template ) {
1349 $template->execute();
1350 $this->addHTML( ob_get_contents() );
1355 * Parse wikitext and return the HTML.
1357 * @param $text String
1358 * @param $linestart Boolean: is this the start of a line?
1359 * @param $interface Boolean: use interface language ($wgLang instead of
1360 * $wgContLang) while parsing language sensitive magic
1361 * words like GRAMMAR and PLURAL
1362 * @param $language Language object: target language object, will override
1364 * @return String: HTML
1366 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1367 // Check one for one common cause for parser state resetting
1368 $callers = wfGetAllCallers( 10 );
1369 if ( strpos( $callers, 'Parser::extensionSubstitution' ) !== false ) {
1370 throw new MWException( "wfMsg* function with parsing cannot be used " .
1371 "inside a tag hook. Should use parser->recursiveTagParse() instead" );
1376 if( is_null( $this->getTitle() ) ) {
1377 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1380 $popts = $this->parserOptions();
1382 $popts->setInterfaceMessage( true );
1384 if ( $language !== null ) {
1385 $oldLang = $popts->setTargetLanguage( $language );
1388 $parserOutput = $wgParser->parse(
1389 $text, $this->getTitle(), $popts,
1390 $linestart, true, $this->mRevisionId
1394 $popts->setInterfaceMessage( false );
1396 if ( $language !== null ) {
1397 $popts->setTargetLanguage( $oldLang );
1400 return $parserOutput->getText();
1404 * Parse wikitext, strip paragraphs, and return the HTML.
1406 * @param $text String
1407 * @param $linestart Boolean: is this the start of a line?
1408 * @param $interface Boolean: use interface language ($wgLang instead of
1409 * $wgContLang) while parsing language sensitive magic
1410 * words like GRAMMAR and PLURAL
1411 * @return String: HTML
1413 public function parseInline( $text, $linestart = true, $interface = false ) {
1414 $parsed = $this->parse( $text, $linestart, $interface );
1417 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1425 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1427 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1429 public function setSquidMaxage( $maxage ) {
1430 $this->mSquidMaxage
= $maxage;
1434 * Use enableClientCache(false) to force it to send nocache headers
1438 public function enableClientCache( $state ) {
1439 return wfSetVar( $this->mEnableClientCache
, $state );
1443 * Get the list of cookies that will influence on the cache
1447 function getCacheVaryCookies() {
1448 global $wgCookiePrefix, $wgCacheVaryCookies;
1450 if ( $cookies === null ) {
1451 $cookies = array_merge(
1453 "{$wgCookiePrefix}Token",
1454 "{$wgCookiePrefix}LoggedOut",
1459 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1465 * Return whether this page is not cacheable because "useskin" or "uselang"
1466 * URL parameters were passed.
1470 function uncacheableBecauseRequestVars() {
1472 return $wgRequest->getText( 'useskin', false ) === false
1473 && $wgRequest->getText( 'uselang', false ) === false;
1477 * Check if the request has a cache-varying cookie header
1478 * If it does, it's very important that we don't allow public caching
1482 function haveCacheVaryCookies() {
1484 $cookieHeader = $wgRequest->getHeader( 'cookie' );
1485 if ( $cookieHeader === false ) {
1488 $cvCookies = $this->getCacheVaryCookies();
1489 foreach ( $cvCookies as $cookieName ) {
1490 # Check for a simple string match, like the way squid does it
1491 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1492 wfDebug( __METHOD__
. ": found $cookieName\n" );
1496 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1501 * Add an HTTP header that will influence on the cache
1503 * @param $header String: header name
1504 * @param $option Array|null
1505 * @fixme Document the $option parameter; it appears to be for
1506 * X-Vary-Options but what format is acceptable?
1508 public function addVaryHeader( $header, $option = null ) {
1509 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1510 $this->mVaryHeader
[$header] = (array)$option;
1511 } elseif( is_array( $option ) ) {
1512 if( is_array( $this->mVaryHeader
[$header] ) ) {
1513 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
1515 $this->mVaryHeader
[$header] = $option;
1518 $this->mVaryHeader
[$header] = array_unique( $this->mVaryHeader
[$header] );
1522 * Get a complete X-Vary-Options header
1526 public function getXVO() {
1527 $cvCookies = $this->getCacheVaryCookies();
1529 $cookiesOption = array();
1530 foreach ( $cvCookies as $cookieName ) {
1531 $cookiesOption[] = 'string-contains=' . $cookieName;
1533 $this->addVaryHeader( 'Cookie', $cookiesOption );
1536 foreach( $this->mVaryHeader
as $header => $option ) {
1537 $newheader = $header;
1538 if( is_array( $option ) ) {
1539 $newheader .= ';' . implode( ';', $option );
1541 $headers[] = $newheader;
1543 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1549 * bug 21672: Add Accept-Language to Vary and XVO headers
1550 * if there's no 'variant' parameter existed in GET.
1553 * /w/index.php?title=Main_page should always be served; but
1554 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1556 function addAcceptLanguage() {
1557 global $wgRequest, $wgContLang;
1558 if( !$wgRequest->getCheck( 'variant' ) && $wgContLang->hasVariants() ) {
1559 $variants = $wgContLang->getVariants();
1560 $aloption = array();
1561 foreach ( $variants as $variant ) {
1562 if( $variant === $wgContLang->getCode() ) {
1565 $aloption[] = 'string-contains=' . $variant;
1567 // IE and some other browsers use another form of language code
1568 // in their Accept-Language header, like "zh-CN" or "zh-TW".
1569 // We should handle these too.
1570 $ievariant = explode( '-', $variant );
1571 if ( count( $ievariant ) == 2 ) {
1572 $ievariant[1] = strtoupper( $ievariant[1] );
1573 $ievariant = implode( '-', $ievariant );
1574 $aloption[] = 'string-contains=' . $ievariant;
1578 $this->addVaryHeader( 'Accept-Language', $aloption );
1583 * Set a flag which will cause an X-Frame-Options header appropriate for
1584 * edit pages to be sent. The header value is controlled by
1585 * $wgEditPageFrameOptions.
1587 * This is the default for special pages. If you display a CSRF-protected
1588 * form on an ordinary view page, then you need to call this function.
1590 public function preventClickjacking( $enable = true ) {
1591 $this->mPreventClickjacking
= $enable;
1595 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1596 * This can be called from pages which do not contain any CSRF-protected
1599 public function allowClickjacking() {
1600 $this->mPreventClickjacking
= false;
1604 * Get the X-Frame-Options header value (without the name part), or false
1605 * if there isn't one. This is used by Skin to determine whether to enable
1606 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1608 public function getFrameOptions() {
1609 global $wgBreakFrames, $wgEditPageFrameOptions;
1610 if ( $wgBreakFrames ) {
1612 } elseif ( $this->mPreventClickjacking
&& $wgEditPageFrameOptions ) {
1613 return $wgEditPageFrameOptions;
1618 * Send cache control HTTP headers
1620 public function sendCacheControl() {
1621 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest, $wgUseXVO;
1623 $response = $wgRequest->response();
1624 if ( $wgUseETag && $this->mETag
) {
1625 $response->header( "ETag: $this->mETag" );
1628 $this->addAcceptLanguage();
1630 # don't serve compressed data to clients who can't handle it
1631 # maintain different caches for logged-in users and non-logged in ones
1632 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) ) );
1635 # Add an X-Vary-Options header for Squid with Wikimedia patches
1636 $response->header( $this->getXVO() );
1639 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
1641 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1642 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
1646 # We'll purge the proxy cache explicitly, but require end user agents
1647 # to revalidate against the proxy on each visit.
1648 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1649 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1650 # start with a shorter timeout for initial testing
1651 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1652 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
1653 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1655 # We'll purge the proxy cache for anons explicitly, but require end user agents
1656 # to revalidate against the proxy on each visit.
1657 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1658 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1659 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
1660 # start with a shorter timeout for initial testing
1661 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1662 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
1665 # We do want clients to cache if they can, but they *must* check for updates
1666 # on revisiting the page.
1667 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
1668 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1669 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1671 if($this->mLastModified
) {
1672 $response->header( "Last-Modified: {$this->mLastModified}" );
1675 wfDebug( __METHOD__
. ": no caching **\n", false );
1677 # In general, the absence of a last modified header should be enough to prevent
1678 # the client from using its cache. We send a few other things just to make sure.
1679 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1680 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1681 $response->header( 'Pragma: no-cache' );
1686 * Get the message associed with the HTTP response code $code
1688 * @param $code Integer: status code
1689 * @return String or null: message or null if $code is not in the list of
1692 public static function getStatusMessage( $code ) {
1693 static $statusMessage = array(
1695 101 => 'Switching Protocols',
1696 102 => 'Processing',
1700 203 => 'Non-Authoritative Information',
1701 204 => 'No Content',
1702 205 => 'Reset Content',
1703 206 => 'Partial Content',
1704 207 => 'Multi-Status',
1705 300 => 'Multiple Choices',
1706 301 => 'Moved Permanently',
1709 304 => 'Not Modified',
1711 307 => 'Temporary Redirect',
1712 400 => 'Bad Request',
1713 401 => 'Unauthorized',
1714 402 => 'Payment Required',
1717 405 => 'Method Not Allowed',
1718 406 => 'Not Acceptable',
1719 407 => 'Proxy Authentication Required',
1720 408 => 'Request Timeout',
1723 411 => 'Length Required',
1724 412 => 'Precondition Failed',
1725 413 => 'Request Entity Too Large',
1726 414 => 'Request-URI Too Large',
1727 415 => 'Unsupported Media Type',
1728 416 => 'Request Range Not Satisfiable',
1729 417 => 'Expectation Failed',
1730 422 => 'Unprocessable Entity',
1732 424 => 'Failed Dependency',
1733 500 => 'Internal Server Error',
1734 501 => 'Not Implemented',
1735 502 => 'Bad Gateway',
1736 503 => 'Service Unavailable',
1737 504 => 'Gateway Timeout',
1738 505 => 'HTTP Version Not Supported',
1739 507 => 'Insufficient Storage'
1741 return isset( $statusMessage[$code] ) ?
$statusMessage[$code] : null;
1745 * Finally, all the text has been munged and accumulated into
1746 * the object, let's actually output it:
1748 public function output() {
1749 global $wgUser, $wgOutputEncoding, $wgRequest;
1750 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType;
1751 global $wgUseAjax, $wgAjaxWatch;
1752 global $wgEnableMWSuggest, $wgUniversalEditButton;
1754 if( $this->mDoNothing
) {
1757 wfProfileIn( __METHOD__
);
1758 if ( $this->mRedirect
!= '' ) {
1759 # Standards require redirect URLs to be absolute
1760 $this->mRedirect
= wfExpandUrl( $this->mRedirect
);
1761 if( $this->mRedirectCode
== '301' ||
$this->mRedirectCode
== '303' ) {
1762 if( !$wgDebugRedirects ) {
1763 $message = self
::getStatusMessage( $this->mRedirectCode
);
1764 $wgRequest->response()->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
1766 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1768 $this->sendCacheControl();
1770 $wgRequest->response()->header( "Content-Type: text/html; charset=utf-8" );
1771 if( $wgDebugRedirects ) {
1772 $url = htmlspecialchars( $this->mRedirect
);
1773 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1774 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1775 print "</body>\n</html>\n";
1777 $wgRequest->response()->header( 'Location: ' . $this->mRedirect
);
1779 wfProfileOut( __METHOD__
);
1781 } elseif ( $this->mStatusCode
) {
1782 $message = self
::getStatusMessage( $this->mStatusCode
);
1784 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
1788 $sk = $wgUser->getSkin();
1790 // Add base resources
1791 $this->addModules( array( 'mediawiki.legacy.wikibits', 'mediawiki.util' ) );
1793 // Add various resources if required
1795 $this->addModules( 'mediawiki.legacy.ajax' );
1797 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1799 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1800 $this->addModules( 'mediawiki.action.watch.ajax' );
1803 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ) {
1804 $this->addModules( 'mediawiki.legacy.mwsuggest' );
1808 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1809 $this->addModules( 'mediawiki.action.view.rightClickEdit' );
1812 if( $wgUniversalEditButton ) {
1813 if( $this->isArticleRelated() && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1814 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create' ) ) ) {
1815 // Original UniversalEditButton
1816 $msg = wfMsg( 'edit' );
1817 $this->addLink( array(
1818 'rel' => 'alternate',
1819 'type' => 'application/x-wiki',
1821 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1823 // Alternate edit link
1824 $this->addLink( array(
1827 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1833 # Buffer output; final headers may depend on later processing
1836 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1837 $wgRequest->response()->header( 'Content-language: ' . $wgLanguageCode );
1839 // Prevent framing, if requested
1840 $frameOptions = $this->getFrameOptions();
1841 if ( $frameOptions ) {
1842 $wgRequest->response()->header( "X-Frame-Options: $frameOptions" );
1845 if ( $this->mArticleBodyOnly
) {
1846 $this->out( $this->mBodytext
);
1848 // Hook that allows last minute changes to the output page, e.g.
1849 // adding of CSS or Javascript by extensions.
1850 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1852 wfProfileIn( 'Output-skin' );
1853 $sk->outputPage( $this );
1854 wfProfileOut( 'Output-skin' );
1857 $this->sendCacheControl();
1859 wfProfileOut( __METHOD__
);
1863 * Actually output something with print(). Performs an iconv to the
1864 * output encoding, if needed.
1866 * @param $ins String: the string to output
1868 public function out( $ins ) {
1869 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1870 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1873 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1874 if ( false === $outs ) {
1882 * Produce a "user is blocked" page.
1884 * @param $return Boolean: whether to have a "return to $wgTitle" message or not.
1887 function blockedPage( $return = true ) {
1888 global $wgUser, $wgContLang, $wgLang;
1890 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1891 $this->setRobotPolicy( 'noindex,nofollow' );
1892 $this->setArticleRelated( false );
1894 $name = User
::whoIs( $wgUser->blockedBy() );
1895 $reason = $wgUser->blockedFor();
1896 if( $reason == '' ) {
1897 $reason = wfMsg( 'blockednoreason' );
1899 $blockTimestamp = $wgLang->timeanddate(
1900 wfTimestamp( TS_MW
, $wgUser->mBlock
->mTimestamp
), true
1904 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1906 $blockid = $wgUser->mBlock
->mId
;
1908 $blockExpiry = $wgUser->mBlock
->mExpiry
;
1909 if ( $blockExpiry == 'infinity' ) {
1910 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1911 // Search for localization in 'ipboptions'
1912 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1913 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1914 if ( strpos( $option, ':' ) === false ) {
1917 list( $show, $value ) = explode( ':', $option );
1918 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1919 $blockExpiry = $show;
1924 $blockExpiry = $wgLang->timeanddate(
1925 wfTimestamp( TS_MW
, $blockExpiry ),
1930 if ( $wgUser->mBlock
->mAuto
) {
1931 $msg = 'autoblockedtext';
1933 $msg = 'blockedtext';
1936 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1937 * This could be a username, an IP range, or a single IP. */
1938 $intended = $wgUser->mBlock
->mAddress
;
1941 $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry,
1942 $intended, $blockTimestamp
1945 # Don't auto-return to special pages
1947 $return = $this->getTitle()->getNamespace() > -1 ?
$this->getTitle() : null;
1948 $this->returnToMain( null, $return );
1953 * Output a standard error page
1955 * @param $title String: message key for page title
1956 * @param $msg String: message key for page text
1957 * @param $params Array: message parameters
1959 public function showErrorPage( $title, $msg, $params = array() ) {
1960 if ( $this->getTitle() ) {
1961 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1963 $this->setPageTitle( wfMsg( $title ) );
1964 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1965 $this->setRobotPolicy( 'noindex,nofollow' );
1966 $this->setArticleRelated( false );
1967 $this->enableClientCache( false );
1968 $this->mRedirect
= '';
1969 $this->mBodytext
= '';
1971 $this->addWikiMsgArray( $msg, $params );
1973 $this->returnToMain();
1977 * Output a standard permission error page
1979 * @param $errors Array: error message keys
1980 * @param $action String: action that was denied or null if unknown
1982 public function showPermissionsErrorPage( $errors, $action = null ) {
1983 $this->mDebugtext
.= 'Original title: ' .
1984 $this->getTitle()->getPrefixedText() . "\n";
1985 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1986 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1987 $this->setRobotPolicy( 'noindex,nofollow' );
1988 $this->setArticleRelated( false );
1989 $this->enableClientCache( false );
1990 $this->mRedirect
= '';
1991 $this->mBodytext
= '';
1992 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1996 * Display an error page indicating that a given version of MediaWiki is
1997 * required to use it
1999 * @param $version Mixed: the version of MediaWiki needed to use the page
2001 public function versionRequired( $version ) {
2002 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
2003 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
2004 $this->setRobotPolicy( 'noindex,nofollow' );
2005 $this->setArticleRelated( false );
2006 $this->mBodytext
= '';
2008 $this->addWikiMsg( 'versionrequiredtext', $version );
2009 $this->returnToMain();
2013 * Display an error page noting that a given permission bit is required.
2015 * @param $permission String: key required
2017 public function permissionRequired( $permission ) {
2020 $this->setPageTitle( wfMsg( 'badaccess' ) );
2021 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
2022 $this->setRobotPolicy( 'noindex,nofollow' );
2023 $this->setArticleRelated( false );
2024 $this->mBodytext
= '';
2026 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
2027 User
::getGroupsWithPermission( $permission ) );
2031 $wgLang->commaList( $groups ),
2035 $this->addWikiMsg( 'badaccess-group0' );
2037 $this->returnToMain();
2041 * Produce the stock "please login to use the wiki" page
2043 public function loginToUse() {
2046 if( $wgUser->isLoggedIn() ) {
2047 $this->permissionRequired( 'read' );
2051 $skin = $wgUser->getSkin();
2053 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
2054 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
2055 $this->setRobotPolicy( 'noindex,nofollow' );
2056 $this->setArticleRelated( false );
2058 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
2059 $loginLink = $skin->link(
2061 wfMsgHtml( 'loginreqlink' ),
2063 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
2064 array( 'known', 'noclasses' )
2066 $this->addWikiMsgArray( 'loginreqpagetext', array( $loginLink ), array( 'replaceafter' ) );
2067 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . '-->' );
2069 # Don't return to the main page if the user can't read it
2070 # otherwise we'll end up in a pointless loop
2071 $mainPage = Title
::newMainPage();
2072 if( $mainPage->userCanRead() ) {
2073 $this->returnToMain( null, $mainPage );
2078 * Format a list of error messages
2080 * @param $errors Array of arrays returned by Title::getUserPermissionsErrors
2081 * @param $action String: action that was denied or null if unknown
2082 * @return String: the wikitext error-messages, formatted into a list.
2084 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2085 if ( $action == null ) {
2086 $text = wfMsgNoTrans( 'permissionserrorstext', count( $errors ) ) . "\n\n";
2088 $action_desc = wfMsgNoTrans( "action-$action" );
2089 $text = wfMsgNoTrans(
2090 'permissionserrorstext-withaction',
2096 if ( count( $errors ) > 1 ) {
2097 $text .= '<ul class="permissions-errors">' . "\n";
2099 foreach( $errors as $error ) {
2101 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
2106 $text .= "<div class=\"permissions-errors\">\n" .
2107 call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) .
2115 * Display a page stating that the Wiki is in read-only mode,
2116 * and optionally show the source of the page that the user
2117 * was trying to edit. Should only be called (for this
2118 * purpose) after wfReadOnly() has returned true.
2120 * For historical reasons, this function is _also_ used to
2121 * show the error message when a user tries to edit a page
2122 * they are not allowed to edit. (Unless it's because they're
2123 * blocked, then we show blockedPage() instead.) In this
2124 * case, the second parameter should be set to true and a list
2125 * of reasons supplied as the third parameter.
2127 * @todo Needs to be split into multiple functions.
2129 * @param $source String: source code to show (or null).
2130 * @param $protected Boolean: is this a permissions error?
2131 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
2132 * @param $action String: action that was denied or null if unknown
2134 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
2136 $skin = $wgUser->getSkin();
2138 $this->setRobotPolicy( 'noindex,nofollow' );
2139 $this->setArticleRelated( false );
2141 // If no reason is given, just supply a default "I can't let you do
2142 // that, Dave" message. Should only occur if called by legacy code.
2143 if ( $protected && empty( $reasons ) ) {
2144 $reasons[] = array( 'badaccess-group0' );
2147 if ( !empty( $reasons ) ) {
2148 // Permissions error
2150 $this->setPageTitle( wfMsg( 'viewsource' ) );
2152 wfMsg( 'viewsourcefor', $skin->linkKnown( $this->getTitle() ) )
2155 $this->setPageTitle( wfMsg( 'badaccess' ) );
2157 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2159 // Wiki is read only
2160 $this->setPageTitle( wfMsg( 'readonly' ) );
2161 $reason = wfReadOnlyReason();
2162 $this->wrapWikiMsg( "<div class='mw-readonly-error'>\n$1\n</div>", array( 'readonlytext', $reason ) );
2165 // Show source, if supplied
2166 if( is_string( $source ) ) {
2167 $this->addWikiMsg( 'viewsourcetext' );
2170 'id' => 'wpTextbox1',
2171 'name' => 'wpTextbox1',
2172 'cols' => $wgUser->getOption( 'cols' ),
2173 'rows' => $wgUser->getOption( 'rows' ),
2174 'readonly' => 'readonly'
2176 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
2178 // Show templates used by this article
2179 $skin = $wgUser->getSkin();
2180 $article = new Article( $this->getTitle() );
2181 $this->addHTML( "<div class='templatesUsed'>
2182 {$skin->formatTemplates( $article->getUsedTemplates() )}
2187 # If the title doesn't exist, it's fairly pointless to print a return
2188 # link to it. After all, you just tried editing it and couldn't, so
2189 # what's there to do there?
2190 if( $this->getTitle()->exists() ) {
2191 $this->returnToMain( null, $this->getTitle() );
2196 * Adds JS-based password security checker
2197 * @param $passwordId String ID of input box containing password
2198 * @param $retypeId String ID of input box containing retyped password
2201 public function addPasswordSecurity( $passwordId, $retypeId ) {
2203 'password' => '#' . $passwordId,
2204 'retype' => '#' . $retypeId,
2205 'messages' => array(),
2207 foreach ( array( 'password-strength', 'password-strength-bad', 'password-strength-mediocre',
2208 'password-strength-acceptable', 'password-strength-good', 'password-retype', 'password-retype-mismatch'
2210 $data['messages'][$message] = wfMsg( $message );
2212 $this->addScript( Html
::inlineScript( 'var passwordSecurity=' . FormatJson
::encode( $data ) ) );
2213 $this->addModules( 'mediawiki.legacy.password' );
2216 public function showFatalError( $message ) {
2217 $this->setPageTitle( wfMsg( 'internalerror' ) );
2218 $this->setRobotPolicy( 'noindex,nofollow' );
2219 $this->setArticleRelated( false );
2220 $this->enableClientCache( false );
2221 $this->mRedirect
= '';
2222 $this->mBodytext
= $message;
2225 public function showUnexpectedValueError( $name, $val ) {
2226 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
2229 public function showFileCopyError( $old, $new ) {
2230 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
2233 public function showFileRenameError( $old, $new ) {
2234 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
2237 public function showFileDeleteError( $name ) {
2238 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
2241 public function showFileNotFoundError( $name ) {
2242 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
2246 * Add a "return to" link pointing to a specified title
2248 * @param $title Title to link
2249 * @param $query String: query string
2250 * @param $text String text of the link (input is not escaped)
2252 public function addReturnTo( $title, $query = array(), $text = null ) {
2254 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL() ) );
2257 $wgUser->getSkin()->link( $title, $text, array(), $query )
2259 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2263 * Add a "return to" link pointing to a specified title,
2264 * or the title indicated in the request, or else the main page
2266 * @param $unused No longer used
2267 * @param $returnto Title or String to return to
2268 * @param $returntoquery String: query string for the return to link
2270 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2273 if ( $returnto == null ) {
2274 $returnto = $wgRequest->getText( 'returnto' );
2277 if ( $returntoquery == null ) {
2278 $returntoquery = $wgRequest->getText( 'returntoquery' );
2281 if ( $returnto === '' ) {
2282 $returnto = Title
::newMainPage();
2285 if ( is_object( $returnto ) ) {
2286 $titleObj = $returnto;
2288 $titleObj = Title
::newFromText( $returnto );
2290 if ( !is_object( $titleObj ) ) {
2291 $titleObj = Title
::newMainPage();
2294 $this->addReturnTo( $titleObj, $returntoquery );
2298 * @param $sk Skin The given Skin
2299 * @param $includeStyle Boolean: unused
2300 * @return String: The doctype, opening <html>, and head element.
2302 public function headElement( Skin
$sk, $includeStyle = true ) {
2303 global $wgOutputEncoding, $wgMimeType;
2304 global $wgUseTrackbacks, $wgHtml5;
2305 global $wgUser, $wgRequest, $wgLang;
2307 if ( $sk->commonPrintStylesheet() ) {
2308 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2310 $sk->setupUserCss( $this );
2313 $ret = Html
::htmlHeader( array( 'lang' => $lang->getCode(), 'dir' => $lang->getDir() ) );
2315 if ( $this->getHTMLTitle() == '' ) {
2316 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ) );
2319 $openHead = Html
::openElement( 'head' );
2321 # Don't bother with the newline if $head == ''
2322 $ret .= "$openHead\n";
2326 # More succinct than <meta http-equiv=Content-Type>, has the
2328 $ret .= Html
::element( 'meta', array( 'charset' => $wgOutputEncoding ) ) . "\n";
2330 $this->addMeta( 'http:Content-Type', "$wgMimeType; charset=$wgOutputEncoding" );
2333 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2335 $ret .= implode( "\n", array(
2336 $this->getHeadLinks( $sk ),
2337 $this->buildCssLinks( $sk ),
2338 $this->getHeadItems()
2341 if ( $wgUseTrackbacks && $this->isArticleRelated() ) {
2342 $ret .= $this->getTitle()->trackbackRDF();
2345 $closeHead = Html
::closeElement( 'head' );
2347 $ret .= "$closeHead\n";
2350 $bodyAttrs = array();
2352 # Crazy edit-on-double-click stuff
2353 $action = $wgRequest->getVal( 'action', 'view' );
2356 $this->getTitle()->getNamespace() != NS_SPECIAL
&&
2357 !in_array( $action, array( 'edit', 'submit' ) ) &&
2358 $wgUser->getOption( 'editondblclick' )
2361 $bodyAttrs['ondblclick'] = "document.location = '" . Xml
::escapeJsString( $this->getTitle()->getEditURL() ) . "'";
2365 $dir = wfUILang()->getDir();
2366 $bodyAttrs['class'] = "mediawiki $dir";
2368 if ( $wgLang->capitalizeAllNouns() ) {
2369 # A <body> class is probably not the best way to do this . . .
2370 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2372 $bodyAttrs['class'] .= ' ' . $sk->getPageClasses( $this->getTitle() );
2373 $bodyAttrs['class'] .= ' skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2375 $sk->addToBodyAttributes( $this, $bodyAttrs ); // Allow skins to add body attributes they need
2376 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2378 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2384 * Get a ResourceLoader object associated with this OutputPage
2386 public function getResourceLoader() {
2387 if ( is_null( $this->mResourceLoader
) ) {
2388 $this->mResourceLoader
= new ResourceLoader();
2390 return $this->mResourceLoader
;
2396 * @param $modules Array/string with the module name
2397 * @param $only String ResourceLoaderModule TYPE_ class constant
2398 * @param $useESI boolean
2399 * @return string html <script> and <style> tags
2401 protected function makeResourceLoaderLink( Skin
$skin, $modules, $only, $useESI = false ) {
2402 global $wgUser, $wgLang, $wgLoadScript, $wgResourceLoaderUseESI,
2403 $wgResourceLoaderInlinePrivateModules, $wgRequest;
2404 // Lazy-load ResourceLoader
2405 // TODO: Should this be a static function of ResourceLoader instead?
2406 // TODO: Divide off modules starting with "user", and add the user parameter to them
2408 'lang' => $wgLang->getCode(),
2409 'debug' => ResourceLoader
::inDebugMode() ?
'true' : 'false',
2410 'skin' => $skin->getSkinName(),
2413 // Propagate printable and handheld parameters if present
2414 if ( $wgRequest->getBool( 'printable' ) ) {
2415 $query['printable'] = 1;
2417 if ( $wgRequest->getBool( 'handheld' ) ) {
2418 $query['handheld'] = 1;
2421 if ( !count( $modules ) ) {
2425 if ( count( $modules ) > 1 ) {
2426 // Remove duplicate module requests
2427 $modules = array_unique( (array) $modules );
2428 // Sort module names so requests are more uniform
2431 if ( ResourceLoader
::inDebugMode() ) {
2432 // Recursively call us for every item
2434 foreach ( $modules as $name ) {
2435 $links .= $this->makeResourceLoaderLink( $skin, $name, $only, $useESI );
2441 // Create keyed-by-group list of module objects from modules list
2443 $resourceLoader = $this->getResourceLoader();
2444 foreach ( (array) $modules as $name ) {
2445 $module = $resourceLoader->getModule( $name );
2446 # Check that we're allowed to include this module on this page
2447 if( ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2448 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2449 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2450 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2456 $group = $module->getGroup();
2457 if ( !isset( $groups[$group] ) ) {
2458 $groups[$group] = array();
2460 $groups[$group][$name] = $module;
2464 foreach ( $groups as $group => $modules ) {
2465 $query['modules'] = implode( '|', array_keys( $modules ) );
2466 // Special handling for user-specific groups
2467 if ( ( $group === 'user' ||
$group === 'private' ) && $wgUser->isLoggedIn() ) {
2468 $query['user'] = $wgUser->getName();
2470 // Support inlining of private modules if configured as such
2471 if ( $group === 'private' && $wgResourceLoaderInlinePrivateModules ) {
2472 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2473 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2474 $links .= Html
::inlineStyle(
2475 $resourceLoader->makeModuleResponse( $context, $modules )
2478 $links .= Html
::inlineScript(
2479 ResourceLoader
::makeLoaderConditionalScript(
2480 $resourceLoader->makeModuleResponse( $context, $modules )
2486 // Special handling for user and site groups; because users might change their stuff
2487 // on-wiki like site or user pages, or user preferences; we need to find the highest
2488 // timestamp of these user-changable modules so we can ensure cache misses on change
2489 if ( $group === 'user' ||
$group === 'site' ) {
2490 // Create a fake request based on the one we are about to make so modules return
2492 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2493 // Get the maximum timestamp
2495 foreach ( $modules as $module ) {
2496 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2498 // Add a version parameter so cache will break when things change
2499 $query['version'] = wfTimestamp( TS_ISO_8601_BASIC
, $timestamp );
2501 // Make queries uniform in order
2504 $url = wfAppendQuery( $wgLoadScript, $query );
2505 if ( $useESI && $wgResourceLoaderUseESI ) {
2506 $esi = Xml
::element( 'esi:include', array( 'src' => $url ) );
2507 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2508 $links .= Html
::inlineStyle( $esi );
2510 $links .= Html
::inlineScript( $esi );
2513 // Automatically select style/script elements
2514 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2515 $links .= Html
::linkedStyle( wfAppendQuery( $wgLoadScript, $query ) ) . "\n";
2517 $links .= Html
::linkedScript( wfAppendQuery( $wgLoadScript, $query ) ) . "\n";
2525 * Gets the global variables and mScripts; also adds userjs to the end if
2526 * enabled. Despite the name, these scripts are no longer put in the
2527 * <head> but at the bottom of the <body>
2529 * @param $sk Skin object to use
2530 * @return String: HTML fragment
2532 function getHeadScripts( Skin
$sk ) {
2533 global $wgUser, $wgRequest, $wgUseSiteJs, $wgAllowUserJs;
2535 // Startup - this will immediately load jquery and mediawiki modules
2536 $scripts = $this->makeResourceLoaderLink( $sk, 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
, true );
2538 // Script and Messages "only" requests
2539 $scripts .= $this->makeResourceLoaderLink( $sk, $this->getModuleScripts( true ), ResourceLoaderModule
::TYPE_SCRIPTS
);
2540 $scripts .= $this->makeResourceLoaderLink( $sk, $this->getModuleMessages( true ), ResourceLoaderModule
::TYPE_MESSAGES
);
2542 // Modules requests - let the client calculate dependencies and batch requests as it likes
2544 if ( $this->getModules( true ) ) {
2545 $loader = Xml
::encodeJsCall( 'mediaWiki.loader.load', array( $this->getModules( true ) ) ) .
2546 Xml
::encodeJsCall( 'mediaWiki.loader.go', array() );
2549 $scripts .= Html
::inlineScript(
2550 ResourceLoader
::makeLoaderConditionalScript(
2551 ResourceLoader
::makeConfigSetScript( $this->getJSVars() ) . $loader
2556 $scripts .= "\n" . $this->mScripts
;
2558 $userScripts = array( 'user.options' );
2560 // Add site JS if enabled
2561 if ( $wgUseSiteJs ) {
2562 $scripts .= $this->makeResourceLoaderLink( $sk, 'site', ResourceLoaderModule
::TYPE_SCRIPTS
);
2563 if( $wgUser->isLoggedIn() ){
2564 $userScripts[] = 'user.groups';
2568 // Add user JS if enabled
2569 if ( $wgAllowUserJs && $wgUser->isLoggedIn() ) {
2570 $action = $wgRequest->getVal( 'action', 'view' );
2571 if( $this->mTitle
&& $this->mTitle
->isJsSubpage() && $sk->userCanPreview( $action ) ) {
2572 # XXX: additional security check/prompt?
2573 $scripts .= Html
::inlineScript( "\n" . $wgRequest->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2575 # FIXME: this means that User:Me/Common.js doesn't load when previewing
2576 # User:Me/Vector.js, and vice versa (bug26283)
2577 $userScripts[] = 'user';
2580 $scripts .= $this->makeResourceLoaderLink( $sk, $userScripts, ResourceLoaderModule
::TYPE_SCRIPTS
);
2586 * Get an array containing global JS variables
2588 * Do not add things here which can be evaluated in
2589 * ResourceLoaderStartupScript - in other words, without state.
2590 * You will only be adding bloat to the page and causing page caches to
2591 * have to be purged on configuration changes.
2593 protected function getJSVars() {
2594 global $wgUser, $wgRequest, $wgUseAjax, $wgEnableMWSuggest, $wgContLang;
2596 $title = $this->getTitle();
2597 $ns = $title->getNamespace();
2598 $nsname = MWNamespace
::exists( $ns ) ? MWNamespace
::getCanonicalName( $ns ) : $title->getNsText();
2601 'wgCanonicalNamespace' => $nsname,
2602 'wgCanonicalSpecialPageName' => $ns == NS_SPECIAL ?
2603 SpecialPage
::resolveAlias( $title->getDBkey() ) : false, # bug 21115
2604 'wgNamespaceNumber' => $title->getNamespace(),
2605 'wgPageName' => $title->getPrefixedDBKey(),
2606 'wgTitle' => $title->getText(),
2607 'wgCurRevisionId' => $title->getLatestRevID(),
2608 'wgArticleId' => $title->getArticleId(),
2609 'wgIsArticle' => $this->isArticle(),
2610 'wgAction' => $wgRequest->getText( 'action', 'view' ),
2611 'wgUserName' => $wgUser->isAnon() ?
null : $wgUser->getName(),
2612 'wgUserGroups' => $wgUser->getEffectiveGroups(),
2613 'wgCategories' => $this->getCategories(),
2614 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
2616 if ( $wgContLang->hasVariants() ) {
2617 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
2619 foreach ( $title->getRestrictionTypes() as $type ) {
2620 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
2622 if ( $wgUseAjax && $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ) {
2623 $vars['wgSearchNamespaces'] = SearchEngine
::userNamespaces( $wgUser );
2626 // Allow extensions to add their custom variables to the global JS variables
2627 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars ) );
2633 * Add default \<meta\> tags
2635 protected function addDefaultMeta() {
2636 global $wgVersion, $wgHtml5;
2638 static $called = false;
2640 # Don't run this twice
2646 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); // bug 15835
2648 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
2650 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
2651 if( $p !== 'index,follow' ) {
2652 // http://www.robotstxt.org/wc/meta-user.html
2653 // Only show if it's different from the default robots policy
2654 $this->addMeta( 'robots', $p );
2657 if ( count( $this->mKeywords
) > 0 ) {
2659 "/<.*?" . ">/" => '',
2665 array_keys( $strip ),
2666 array_values( $strip ),
2667 implode( ',', $this->mKeywords
)
2674 * @return string HTML tag links to be put in the header.
2676 public function getHeadLinks( Skin
$sk ) {
2679 // Ideally this should happen earlier, somewhere. :P
2680 $this->addDefaultMeta();
2684 foreach ( $this->mMetatags
as $tag ) {
2685 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
2687 $tag[0] = substr( $tag[0], 5 );
2691 $tags[] = Html
::element( 'meta',
2694 'content' => $tag[1]
2698 foreach ( $this->mLinktags
as $tag ) {
2699 $tags[] = Html
::element( 'link', $tag );
2703 foreach( $this->getSyndicationLinks() as $format => $link ) {
2704 # Use the page name for the title (accessed through $wgTitle since
2705 # there's no other way). In principle, this could lead to issues
2706 # with having the same name for different feeds corresponding to
2707 # the same page, but we can't avoid that at this low a level.
2709 $tags[] = $this->feedLink(
2712 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
2713 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )
2717 # Recent changes feed should appear on every page (except recentchanges,
2718 # that would be redundant). Put it after the per-page feed to avoid
2719 # changing existing behavior. It's still available, probably via a
2720 # menu in your browser. Some sites might have a different feed they'd
2721 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
2722 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
2723 # If so, use it instead.
2725 global $wgOverrideSiteFeed, $wgSitename, $wgAdvertisedFeedTypes;
2726 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
2728 if ( $wgOverrideSiteFeed ) {
2729 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
2730 $tags[] = $this->feedLink(
2732 htmlspecialchars( $feedUrl ),
2733 wfMsg( "site-{$type}-feed", $wgSitename )
2736 } elseif ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
2737 foreach ( $wgAdvertisedFeedTypes as $format ) {
2738 $tags[] = $this->feedLink(
2740 $rctitle->getLocalURL( "feed={$format}" ),
2741 wfMsg( "site-{$format}-feed", $wgSitename ) # For grep: 'site-rss-feed', 'site-atom-feed'.
2746 return implode( "\n", $tags );
2750 * Generate a <link rel/> for a feed.
2752 * @param $type String: feed type
2753 * @param $url String: URL to the feed
2754 * @param $text String: value of the "title" attribute
2755 * @return String: HTML fragment
2757 private function feedLink( $type, $url, $text ) {
2758 return Html
::element( 'link', array(
2759 'rel' => 'alternate',
2760 'type' => "application/$type+xml",
2767 * Add a local or specified stylesheet, with the given media options.
2768 * Meant primarily for internal use...
2770 * @param $style String: URL to the file
2771 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
2772 * @param $condition String: for IE conditional comments, specifying an IE version
2773 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
2775 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
2777 // Even though we expect the media type to be lowercase, but here we
2778 // force it to lowercase to be safe.
2780 $options['media'] = $media;
2783 $options['condition'] = $condition;
2786 $options['dir'] = $dir;
2788 $this->styles
[$style] = $options;
2792 * Adds inline CSS styles
2793 * @param $style_css Mixed: inline CSS
2795 public function addInlineStyle( $style_css ){
2796 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
2800 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
2801 * These will be applied to various media & IE conditionals.
2802 * @param $sk Skin object
2804 public function buildCssLinks( $sk ) {
2806 // Add ResourceLoader styles
2807 // Split the styles into three groups
2808 $styles = array( 'other' => array(), 'user' => array(), 'site' => array() );
2809 $resourceLoader = $this->getResourceLoader();
2810 foreach ( $this->getModuleStyles() as $name ) {
2811 $group = $resourceLoader->getModule( $name )->getGroup();
2812 // Modules in groups named "other" or anything different than "user" or "site" will
2813 // be placed in the "other" group
2814 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
2817 // We want site and user styles to override dynamically added styles from modules, but we want
2818 // dynamically added styles to override statically added styles from other modules. So the order
2819 // has to be other, dynamic, site, user
2820 // Add statically added styles for other modules
2821 $ret .= $this->makeResourceLoaderLink( $sk, $styles['other'], ResourceLoaderModule
::TYPE_STYLES
);
2822 // Add normal styles added through addStyle()/addInlineStyle() here
2823 $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
2824 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
2825 // We use a <meta> tag with a made-up name for this because that's valid HTML
2826 $ret .= Html
::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) );
2827 // Add site and user styles
2828 $ret .= $this->makeResourceLoaderLink(
2829 $sk, array_merge( $styles['site'], $styles['user'] ), ResourceLoaderModule
::TYPE_STYLES
2834 public function buildCssLinksArray() {
2836 foreach( $this->styles
as $file => $options ) {
2837 $link = $this->styleLink( $file, $options );
2839 $links[$file] = $link;
2846 * Generate \<link\> tags for stylesheets
2848 * @param $style String: URL to the file
2849 * @param $options Array: option, can contain 'condition', 'dir', 'media'
2851 * @return String: HTML fragment
2853 protected function styleLink( $style, $options ) {
2854 if( isset( $options['dir'] ) ) {
2855 $siteDir = wfUILang()->getDir();
2856 if( $siteDir != $options['dir'] ) {
2861 if( isset( $options['media'] ) ) {
2862 $media = self
::transformCssMedia( $options['media'] );
2863 if( is_null( $media ) ) {
2870 if( substr( $style, 0, 1 ) == '/' ||
2871 substr( $style, 0, 5 ) == 'http:' ||
2872 substr( $style, 0, 6 ) == 'https:' ) {
2875 global $wgStylePath, $wgStyleVersion;
2876 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
2879 $link = Html
::linkedStyle( $url, $media );
2881 if( isset( $options['condition'] ) ) {
2882 $condition = htmlspecialchars( $options['condition'] );
2883 $link = "<!--[if $condition]>$link<![endif]-->";
2889 * Transform "media" attribute based on request parameters
2891 * @param $media String: current value of the "media" attribute
2892 * @return String: modified value of the "media" attribute
2894 public static function transformCssMedia( $media ) {
2895 global $wgRequest, $wgHandheldForIPhone;
2897 // Switch in on-screen display for media testing
2899 'printable' => 'print',
2900 'handheld' => 'handheld',
2902 foreach( $switches as $switch => $targetMedia ) {
2903 if( $wgRequest->getBool( $switch ) ) {
2904 if( $media == $targetMedia ) {
2906 } elseif( $media == 'screen' ) {
2912 // Expand longer media queries as iPhone doesn't grok 'handheld'
2913 if( $wgHandheldForIPhone ) {
2914 $mediaAliases = array(
2915 'screen' => 'screen and (min-device-width: 481px)',
2916 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
2919 if( isset( $mediaAliases[$media] ) ) {
2920 $media = $mediaAliases[$media];
2928 * Turn off regular page output and return an error reponse
2929 * for when rate limiting has triggered.
2931 public function rateLimited() {
2932 $this->setPageTitle( wfMsg( 'actionthrottled' ) );
2933 $this->setRobotPolicy( 'noindex,follow' );
2934 $this->setArticleRelated( false );
2935 $this->enableClientCache( false );
2936 $this->mRedirect
= '';
2938 $this->setStatusCode( 503 );
2939 $this->addWikiMsg( 'actionthrottledtext' );
2941 $this->returnToMain( null, $this->getTitle() );
2945 * Show a warning about slave lag
2947 * If the lag is higher than $wgSlaveLagCritical seconds,
2948 * then the warning is a bit more obvious. If the lag is
2949 * lower than $wgSlaveLagWarning, then no warning is shown.
2951 * @param $lag Integer: slave lag
2953 public function showLagWarning( $lag ) {
2954 global $wgSlaveLagWarning, $wgSlaveLagCritical, $wgLang;
2955 if( $lag >= $wgSlaveLagWarning ) {
2956 $message = $lag < $wgSlaveLagCritical
2959 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2960 $this->wrapWikiMsg( "$wrap\n", array( $message, $wgLang->formatNum( $lag ) ) );
2965 * Add a wikitext-formatted message to the output.
2966 * This is equivalent to:
2968 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2970 public function addWikiMsg( /*...*/ ) {
2971 $args = func_get_args();
2972 $name = array_shift( $args );
2973 $this->addWikiMsgArray( $name, $args );
2977 * Add a wikitext-formatted message to the output.
2978 * Like addWikiMsg() except the parameters are taken as an array
2979 * instead of a variable argument list.
2981 * $options is passed through to wfMsgExt(), see that function for details.
2983 public function addWikiMsgArray( $name, $args, $options = array() ) {
2984 $options[] = 'parse';
2985 $text = wfMsgExt( $name, $options, $args );
2986 $this->addHTML( $text );
2990 * This function takes a number of message/argument specifications, wraps them in
2991 * some overall structure, and then parses the result and adds it to the output.
2993 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
2994 * on. The subsequent arguments may either be strings, in which case they are the
2995 * message names, or arrays, in which case the first element is the message name,
2996 * and subsequent elements are the parameters to that message.
2998 * The special named parameter 'options' in a message specification array is passed
2999 * through to the $options parameter of wfMsgExt().
3001 * Don't use this for messages that are not in users interface language.
3005 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3009 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . "\n</div>" );
3011 * The newline after opening div is needed in some wikitext. See bug 19226.
3013 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3014 $msgSpecs = func_get_args();
3015 array_shift( $msgSpecs );
3016 $msgSpecs = array_values( $msgSpecs );
3018 foreach ( $msgSpecs as $n => $spec ) {
3020 if ( is_array( $spec ) ) {
3022 $name = array_shift( $args );
3023 if ( isset( $args['options'] ) ) {
3024 $options = $args['options'];
3025 unset( $args['options'] );
3031 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
3033 $this->addWikiText( $s );
3037 * Include jQuery core. Use this to avoid loading it multiple times
3038 * before we get a usable script loader.
3040 * @param $modules Array: list of jQuery modules which should be loaded
3041 * @return Array: the list of modules which were not loaded.
3043 * @deprecated @since 1.17
3045 public function includeJQuery( $modules = array() ) {