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 ParserOptions 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( 'mediawiki.util' );
1792 global $wgIncludeLegacyJavaScript;
1793 if( $wgIncludeLegacyJavaScript ){
1794 $this->addModules( 'mediawiki.legacy.wikibits' );
1797 // Add various resources if required
1799 $this->addModules( 'mediawiki.legacy.ajax' );
1801 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1803 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1804 $this->addModules( 'mediawiki.action.watch.ajax' );
1807 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ) {
1808 $this->addModules( 'mediawiki.legacy.mwsuggest' );
1812 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1813 $this->addModules( 'mediawiki.action.view.rightClickEdit' );
1816 if( $wgUniversalEditButton ) {
1817 if( $this->isArticleRelated() && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1818 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create' ) ) ) {
1819 // Original UniversalEditButton
1820 $msg = wfMsg( 'edit' );
1821 $this->addLink( array(
1822 'rel' => 'alternate',
1823 'type' => 'application/x-wiki',
1825 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1827 // Alternate edit link
1828 $this->addLink( array(
1831 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1837 # Buffer output; final headers may depend on later processing
1840 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1841 $wgRequest->response()->header( 'Content-language: ' . $wgLanguageCode );
1843 // Prevent framing, if requested
1844 $frameOptions = $this->getFrameOptions();
1845 if ( $frameOptions ) {
1846 $wgRequest->response()->header( "X-Frame-Options: $frameOptions" );
1849 if ( $this->mArticleBodyOnly
) {
1850 $this->out( $this->mBodytext
);
1852 // Hook that allows last minute changes to the output page, e.g.
1853 // adding of CSS or Javascript by extensions.
1854 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1856 wfProfileIn( 'Output-skin' );
1857 $sk->outputPage( $this );
1858 wfProfileOut( 'Output-skin' );
1861 $this->sendCacheControl();
1863 wfProfileOut( __METHOD__
);
1867 * Actually output something with print(). Performs an iconv to the
1868 * output encoding, if needed.
1870 * @param $ins String: the string to output
1872 public function out( $ins ) {
1873 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1874 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1877 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1878 if ( false === $outs ) {
1886 * Produce a "user is blocked" page.
1888 * @param $return Boolean: whether to have a "return to $wgTitle" message or not.
1891 function blockedPage( $return = true ) {
1892 global $wgUser, $wgContLang, $wgLang;
1894 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1895 $this->setRobotPolicy( 'noindex,nofollow' );
1896 $this->setArticleRelated( false );
1898 $name = User
::whoIs( $wgUser->blockedBy() );
1899 $reason = $wgUser->blockedFor();
1900 if( $reason == '' ) {
1901 $reason = wfMsg( 'blockednoreason' );
1903 $blockTimestamp = $wgLang->timeanddate(
1904 wfTimestamp( TS_MW
, $wgUser->mBlock
->mTimestamp
), true
1908 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1910 $blockid = $wgUser->mBlock
->mId
;
1912 $blockExpiry = $wgUser->mBlock
->mExpiry
;
1913 if ( $blockExpiry == 'infinity' ) {
1914 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1915 // Search for localization in 'ipboptions'
1916 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1917 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1918 if ( strpos( $option, ':' ) === false ) {
1921 list( $show, $value ) = explode( ':', $option );
1922 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1923 $blockExpiry = $show;
1928 $blockExpiry = $wgLang->timeanddate(
1929 wfTimestamp( TS_MW
, $blockExpiry ),
1934 if ( $wgUser->mBlock
->mAuto
) {
1935 $msg = 'autoblockedtext';
1937 $msg = 'blockedtext';
1940 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1941 * This could be a username, an IP range, or a single IP. */
1942 $intended = $wgUser->mBlock
->mAddress
;
1945 $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry,
1946 $intended, $blockTimestamp
1949 # Don't auto-return to special pages
1951 $return = $this->getTitle()->getNamespace() > -1 ?
$this->getTitle() : null;
1952 $this->returnToMain( null, $return );
1957 * Output a standard error page
1959 * @param $title String: message key for page title
1960 * @param $msg String: message key for page text
1961 * @param $params Array: message parameters
1963 public function showErrorPage( $title, $msg, $params = array() ) {
1964 if ( $this->getTitle() ) {
1965 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1967 $this->setPageTitle( wfMsg( $title ) );
1968 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1969 $this->setRobotPolicy( 'noindex,nofollow' );
1970 $this->setArticleRelated( false );
1971 $this->enableClientCache( false );
1972 $this->mRedirect
= '';
1973 $this->mBodytext
= '';
1975 $this->addWikiMsgArray( $msg, $params );
1977 $this->returnToMain();
1981 * Output a standard permission error page
1983 * @param $errors Array: error message keys
1984 * @param $action String: action that was denied or null if unknown
1986 public function showPermissionsErrorPage( $errors, $action = null ) {
1987 $this->mDebugtext
.= 'Original title: ' .
1988 $this->getTitle()->getPrefixedText() . "\n";
1989 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1990 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1991 $this->setRobotPolicy( 'noindex,nofollow' );
1992 $this->setArticleRelated( false );
1993 $this->enableClientCache( false );
1994 $this->mRedirect
= '';
1995 $this->mBodytext
= '';
1996 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2000 * Display an error page indicating that a given version of MediaWiki is
2001 * required to use it
2003 * @param $version Mixed: the version of MediaWiki needed to use the page
2005 public function versionRequired( $version ) {
2006 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
2007 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
2008 $this->setRobotPolicy( 'noindex,nofollow' );
2009 $this->setArticleRelated( false );
2010 $this->mBodytext
= '';
2012 $this->addWikiMsg( 'versionrequiredtext', $version );
2013 $this->returnToMain();
2017 * Display an error page noting that a given permission bit is required.
2019 * @param $permission String: key required
2021 public function permissionRequired( $permission ) {
2024 $this->setPageTitle( wfMsg( 'badaccess' ) );
2025 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
2026 $this->setRobotPolicy( 'noindex,nofollow' );
2027 $this->setArticleRelated( false );
2028 $this->mBodytext
= '';
2030 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
2031 User
::getGroupsWithPermission( $permission ) );
2035 $wgLang->commaList( $groups ),
2039 $this->addWikiMsg( 'badaccess-group0' );
2041 $this->returnToMain();
2045 * Produce the stock "please login to use the wiki" page
2047 public function loginToUse() {
2050 if( $wgUser->isLoggedIn() ) {
2051 $this->permissionRequired( 'read' );
2055 $skin = $wgUser->getSkin();
2057 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
2058 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
2059 $this->setRobotPolicy( 'noindex,nofollow' );
2060 $this->setArticleRelated( false );
2062 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
2063 $loginLink = $skin->link(
2065 wfMsgHtml( 'loginreqlink' ),
2067 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
2068 array( 'known', 'noclasses' )
2070 $this->addWikiMsgArray( 'loginreqpagetext', array( $loginLink ), array( 'replaceafter' ) );
2071 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . '-->' );
2073 # Don't return to the main page if the user can't read it
2074 # otherwise we'll end up in a pointless loop
2075 $mainPage = Title
::newMainPage();
2076 if( $mainPage->userCanRead() ) {
2077 $this->returnToMain( null, $mainPage );
2082 * Format a list of error messages
2084 * @param $errors Array of arrays returned by Title::getUserPermissionsErrors
2085 * @param $action String: action that was denied or null if unknown
2086 * @return String: the wikitext error-messages, formatted into a list.
2088 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2089 if ( $action == null ) {
2090 $text = wfMsgNoTrans( 'permissionserrorstext', count( $errors ) ) . "\n\n";
2092 $action_desc = wfMsgNoTrans( "action-$action" );
2093 $text = wfMsgNoTrans(
2094 'permissionserrorstext-withaction',
2100 if ( count( $errors ) > 1 ) {
2101 $text .= '<ul class="permissions-errors">' . "\n";
2103 foreach( $errors as $error ) {
2105 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
2110 $text .= "<div class=\"permissions-errors\">\n" .
2111 call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) .
2119 * Display a page stating that the Wiki is in read-only mode,
2120 * and optionally show the source of the page that the user
2121 * was trying to edit. Should only be called (for this
2122 * purpose) after wfReadOnly() has returned true.
2124 * For historical reasons, this function is _also_ used to
2125 * show the error message when a user tries to edit a page
2126 * they are not allowed to edit. (Unless it's because they're
2127 * blocked, then we show blockedPage() instead.) In this
2128 * case, the second parameter should be set to true and a list
2129 * of reasons supplied as the third parameter.
2131 * @todo Needs to be split into multiple functions.
2133 * @param $source String: source code to show (or null).
2134 * @param $protected Boolean: is this a permissions error?
2135 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
2136 * @param $action String: action that was denied or null if unknown
2138 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
2140 $skin = $wgUser->getSkin();
2142 $this->setRobotPolicy( 'noindex,nofollow' );
2143 $this->setArticleRelated( false );
2145 // If no reason is given, just supply a default "I can't let you do
2146 // that, Dave" message. Should only occur if called by legacy code.
2147 if ( $protected && empty( $reasons ) ) {
2148 $reasons[] = array( 'badaccess-group0' );
2151 if ( !empty( $reasons ) ) {
2152 // Permissions error
2154 $this->setPageTitle( wfMsg( 'viewsource' ) );
2156 wfMsg( 'viewsourcefor', $skin->linkKnown( $this->getTitle() ) )
2159 $this->setPageTitle( wfMsg( 'badaccess' ) );
2161 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2163 // Wiki is read only
2164 $this->setPageTitle( wfMsg( 'readonly' ) );
2165 $reason = wfReadOnlyReason();
2166 $this->wrapWikiMsg( "<div class='mw-readonly-error'>\n$1\n</div>", array( 'readonlytext', $reason ) );
2169 // Show source, if supplied
2170 if( is_string( $source ) ) {
2171 $this->addWikiMsg( 'viewsourcetext' );
2174 'id' => 'wpTextbox1',
2175 'name' => 'wpTextbox1',
2176 'cols' => $wgUser->getOption( 'cols' ),
2177 'rows' => $wgUser->getOption( 'rows' ),
2178 'readonly' => 'readonly'
2180 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
2182 // Show templates used by this article
2183 $skin = $wgUser->getSkin();
2184 $article = new Article( $this->getTitle() );
2185 $this->addHTML( "<div class='templatesUsed'>
2186 {$skin->formatTemplates( $article->getUsedTemplates() )}
2191 # If the title doesn't exist, it's fairly pointless to print a return
2192 # link to it. After all, you just tried editing it and couldn't, so
2193 # what's there to do there?
2194 if( $this->getTitle()->exists() ) {
2195 $this->returnToMain( null, $this->getTitle() );
2200 * Adds JS-based password security checker
2201 * @param $passwordId String ID of input box containing password
2202 * @param $retypeId String ID of input box containing retyped password
2205 public function addPasswordSecurity( $passwordId, $retypeId ) {
2207 'password' => '#' . $passwordId,
2208 'retype' => '#' . $retypeId,
2209 'messages' => array(),
2211 foreach ( array( 'password-strength', 'password-strength-bad', 'password-strength-mediocre',
2212 'password-strength-acceptable', 'password-strength-good', 'password-retype', 'password-retype-mismatch'
2214 $data['messages'][$message] = wfMsg( $message );
2216 $this->addScript( Html
::inlineScript( 'var passwordSecurity=' . FormatJson
::encode( $data ) ) );
2217 $this->addModules( 'mediawiki.legacy.password' );
2220 public function showFatalError( $message ) {
2221 $this->setPageTitle( wfMsg( 'internalerror' ) );
2222 $this->setRobotPolicy( 'noindex,nofollow' );
2223 $this->setArticleRelated( false );
2224 $this->enableClientCache( false );
2225 $this->mRedirect
= '';
2226 $this->mBodytext
= $message;
2229 public function showUnexpectedValueError( $name, $val ) {
2230 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
2233 public function showFileCopyError( $old, $new ) {
2234 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
2237 public function showFileRenameError( $old, $new ) {
2238 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
2241 public function showFileDeleteError( $name ) {
2242 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
2245 public function showFileNotFoundError( $name ) {
2246 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
2250 * Add a "return to" link pointing to a specified title
2252 * @param $title Title to link
2253 * @param $query String: query string
2254 * @param $text String text of the link (input is not escaped)
2256 public function addReturnTo( $title, $query = array(), $text = null ) {
2258 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL() ) );
2261 $wgUser->getSkin()->link( $title, $text, array(), $query )
2263 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2267 * Add a "return to" link pointing to a specified title,
2268 * or the title indicated in the request, or else the main page
2270 * @param $unused No longer used
2271 * @param $returnto Title or String to return to
2272 * @param $returntoquery String: query string for the return to link
2274 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2277 if ( $returnto == null ) {
2278 $returnto = $wgRequest->getText( 'returnto' );
2281 if ( $returntoquery == null ) {
2282 $returntoquery = $wgRequest->getText( 'returntoquery' );
2285 if ( $returnto === '' ) {
2286 $returnto = Title
::newMainPage();
2289 if ( is_object( $returnto ) ) {
2290 $titleObj = $returnto;
2292 $titleObj = Title
::newFromText( $returnto );
2294 if ( !is_object( $titleObj ) ) {
2295 $titleObj = Title
::newMainPage();
2298 $this->addReturnTo( $titleObj, $returntoquery );
2302 * @param $sk Skin The given Skin
2303 * @param $includeStyle Boolean: unused
2304 * @return String: The doctype, opening <html>, and head element.
2306 public function headElement( Skin
$sk, $includeStyle = true ) {
2307 global $wgOutputEncoding, $wgMimeType;
2308 global $wgUseTrackbacks, $wgHtml5;
2309 global $wgUser, $wgRequest, $wgLang;
2311 if ( $sk->commonPrintStylesheet() ) {
2312 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2314 $sk->setupUserCss( $this );
2317 $ret = Html
::htmlHeader( array( 'lang' => $lang->getCode(), 'dir' => $lang->getDir() ) );
2319 if ( $this->getHTMLTitle() == '' ) {
2320 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ) );
2323 $openHead = Html
::openElement( 'head' );
2325 # Don't bother with the newline if $head == ''
2326 $ret .= "$openHead\n";
2330 # More succinct than <meta http-equiv=Content-Type>, has the
2332 $ret .= Html
::element( 'meta', array( 'charset' => $wgOutputEncoding ) ) . "\n";
2334 $this->addMeta( 'http:Content-Type', "$wgMimeType; charset=$wgOutputEncoding" );
2337 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2339 $ret .= implode( "\n", array(
2340 $this->getHeadLinks( $sk ),
2341 $this->buildCssLinks( $sk ),
2342 $this->getHeadItems()
2345 if ( $wgUseTrackbacks && $this->isArticleRelated() ) {
2346 $ret .= $this->getTitle()->trackbackRDF();
2349 $closeHead = Html
::closeElement( 'head' );
2351 $ret .= "$closeHead\n";
2354 $bodyAttrs = array();
2356 # Crazy edit-on-double-click stuff
2357 $action = $wgRequest->getVal( 'action', 'view' );
2360 $this->getTitle()->getNamespace() != NS_SPECIAL
&&
2361 !in_array( $action, array( 'edit', 'submit' ) ) &&
2362 $wgUser->getOption( 'editondblclick' )
2365 $bodyAttrs['ondblclick'] = "document.location = '" . Xml
::escapeJsString( $this->getTitle()->getEditURL() ) . "'";
2369 $dir = wfUILang()->getDir();
2370 $bodyAttrs['class'] = "mediawiki $dir";
2372 if ( $wgLang->capitalizeAllNouns() ) {
2373 # A <body> class is probably not the best way to do this . . .
2374 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2376 $bodyAttrs['class'] .= ' ' . $sk->getPageClasses( $this->getTitle() );
2377 $bodyAttrs['class'] .= ' skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2379 $sk->addToBodyAttributes( $this, $bodyAttrs ); // Allow skins to add body attributes they need
2380 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2382 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2388 * Get a ResourceLoader object associated with this OutputPage
2390 * @return ResourceLoader
2392 public function getResourceLoader() {
2393 if ( is_null( $this->mResourceLoader
) ) {
2394 $this->mResourceLoader
= new ResourceLoader();
2396 return $this->mResourceLoader
;
2402 * @param $modules Array/string with the module name
2403 * @param $only String ResourceLoaderModule TYPE_ class constant
2404 * @param $useESI boolean
2405 * @return string html <script> and <style> tags
2407 protected function makeResourceLoaderLink( Skin
$skin, $modules, $only, $useESI = false ) {
2408 global $wgUser, $wgLang, $wgLoadScript, $wgResourceLoaderUseESI,
2409 $wgResourceLoaderInlinePrivateModules, $wgRequest;
2410 // Lazy-load ResourceLoader
2411 // TODO: Should this be a static function of ResourceLoader instead?
2412 // TODO: Divide off modules starting with "user", and add the user parameter to them
2414 'lang' => $wgLang->getCode(),
2415 'debug' => ResourceLoader
::inDebugMode() ?
'true' : 'false',
2416 'skin' => $skin->getSkinName(),
2419 // Propagate printable and handheld parameters if present
2420 if ( $this->isPrintable() ) {
2421 $baseQuery['printable'] = 1;
2423 if ( $wgRequest->getBool( 'handheld' ) ) {
2424 $baseQuery['handheld'] = 1;
2427 if ( !count( $modules ) ) {
2431 if ( count( $modules ) > 1 ) {
2432 // Remove duplicate module requests
2433 $modules = array_unique( (array) $modules );
2434 // Sort module names so requests are more uniform
2437 if ( ResourceLoader
::inDebugMode() ) {
2438 // Recursively call us for every item
2440 foreach ( $modules as $name ) {
2441 $links .= $this->makeResourceLoaderLink( $skin, $name, $only, $useESI );
2447 // Create keyed-by-group list of module objects from modules list
2449 $resourceLoader = $this->getResourceLoader();
2450 foreach ( (array) $modules as $name ) {
2451 $module = $resourceLoader->getModule( $name );
2452 # Check that we're allowed to include this module on this page
2453 if ( ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2454 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2455 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2456 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2462 $group = $module->getGroup();
2463 if ( !isset( $groups[$group] ) ) {
2464 $groups[$group] = array();
2466 $groups[$group][$name] = $module;
2470 foreach ( $groups as $group => $modules ) {
2471 $query = $baseQuery;
2472 // Special handling for user-specific groups
2473 if ( ( $group === 'user' ||
$group === 'private' ) && $wgUser->isLoggedIn() ) {
2474 $query['user'] = $wgUser->getName();
2477 // Create a fake request based on the one we are about to make so modules return
2478 // correct timestamp and emptiness data
2479 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2480 // Drop modules that know they're empty
2481 foreach ( $modules as $key => $module ) {
2482 if ( $module->isKnownEmpty( $context ) ) {
2483 unset( $modules[$key] );
2486 // If there are no modules left, skip this group
2487 if ( $modules === array() ) {
2491 $query['modules'] = implode( '|', array_keys( $modules ) );
2493 // Support inlining of private modules if configured as such
2494 if ( $group === 'private' && $wgResourceLoaderInlinePrivateModules ) {
2495 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2496 $links .= Html
::inlineStyle(
2497 $resourceLoader->makeModuleResponse( $context, $modules )
2500 $links .= Html
::inlineScript(
2501 ResourceLoader
::makeLoaderConditionalScript(
2502 $resourceLoader->makeModuleResponse( $context, $modules )
2508 // Special handling for user and site groups; because users might change their stuff
2509 // on-wiki like site or user pages, or user preferences; we need to find the highest
2510 // timestamp of these user-changable modules so we can ensure cache misses on change
2511 if ( $group === 'user' ||
$group === 'site' ) {
2512 // Get the maximum timestamp
2514 foreach ( $modules as $module ) {
2515 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2517 // Add a version parameter so cache will break when things change
2518 $query['version'] = wfTimestamp( TS_ISO_8601_BASIC
, $timestamp );
2520 // Make queries uniform in order
2523 $url = wfAppendQuery( $wgLoadScript, $query );
2524 if ( $useESI && $wgResourceLoaderUseESI ) {
2525 $esi = Xml
::element( 'esi:include', array( 'src' => $url ) );
2526 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2527 $links .= Html
::inlineStyle( $esi );
2529 $links .= Html
::inlineScript( $esi );
2532 // Automatically select style/script elements
2533 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2534 $links .= Html
::linkedStyle( wfAppendQuery( $wgLoadScript, $query ) ) . "\n";
2536 $links .= Html
::linkedScript( wfAppendQuery( $wgLoadScript, $query ) ) . "\n";
2544 * Gets the global variables and mScripts; also adds userjs to the end if
2545 * enabled. Despite the name, these scripts are no longer put in the
2546 * <head> but at the bottom of the <body>
2548 * @param $sk Skin object to use
2549 * @return String: HTML fragment
2551 function getHeadScripts( Skin
$sk ) {
2552 global $wgUser, $wgRequest, $wgUseSiteJs, $wgAllowUserJs;
2554 // Startup - this will immediately load jquery and mediawiki modules
2555 $scripts = $this->makeResourceLoaderLink( $sk, 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
, true );
2557 // Script and Messages "only" requests
2558 $scripts .= $this->makeResourceLoaderLink( $sk, $this->getModuleScripts( true ), ResourceLoaderModule
::TYPE_SCRIPTS
);
2559 $scripts .= $this->makeResourceLoaderLink( $sk, $this->getModuleMessages( true ), ResourceLoaderModule
::TYPE_MESSAGES
);
2561 // Modules requests - let the client calculate dependencies and batch requests as it likes
2563 if ( $this->getModules( true ) ) {
2564 $loader = Xml
::encodeJsCall( 'mw.loader.load', array( $this->getModules( true ) ) ) .
2565 Xml
::encodeJsCall( 'mw.loader.go', array() );
2568 $scripts .= Html
::inlineScript(
2569 ResourceLoader
::makeLoaderConditionalScript(
2570 ResourceLoader
::makeConfigSetScript( $this->getJSVars() ) . $loader
2575 $scripts .= "\n" . $this->mScripts
;
2577 $userScripts = array( 'user.options' );
2579 // Add site JS if enabled
2580 if ( $wgUseSiteJs ) {
2581 $scripts .= $this->makeResourceLoaderLink( $sk, 'site', ResourceLoaderModule
::TYPE_SCRIPTS
);
2582 if( $wgUser->isLoggedIn() ){
2583 $userScripts[] = 'user.groups';
2587 // Add user JS if enabled
2588 if ( $wgAllowUserJs && $wgUser->isLoggedIn() ) {
2589 $action = $wgRequest->getVal( 'action', 'view' );
2590 if( $this->mTitle
&& $this->mTitle
->isJsSubpage() && $sk->userCanPreview( $action ) ) {
2591 # XXX: additional security check/prompt?
2592 $scripts .= Html
::inlineScript( "\n" . $wgRequest->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2594 # FIXME: this means that User:Me/Common.js doesn't load when previewing
2595 # User:Me/Vector.js, and vice versa (bug26283)
2596 $userScripts[] = 'user';
2599 $scripts .= $this->makeResourceLoaderLink( $sk, $userScripts, ResourceLoaderModule
::TYPE_SCRIPTS
);
2605 * Get an array containing global JS variables
2607 * Do not add things here which can be evaluated in
2608 * ResourceLoaderStartupScript - in other words, without state.
2609 * You will only be adding bloat to the page and causing page caches to
2610 * have to be purged on configuration changes.
2612 protected function getJSVars() {
2613 global $wgUser, $wgRequest, $wgUseAjax, $wgEnableMWSuggest, $wgContLang;
2615 $title = $this->getTitle();
2616 $ns = $title->getNamespace();
2617 $nsname = MWNamespace
::exists( $ns ) ? MWNamespace
::getCanonicalName( $ns ) : $title->getNsText();
2618 if ( $ns == NS_SPECIAL
) {
2619 $parts = SpecialPage
::resolveAliasWithSubpage( $title->getDBkey() );
2620 $canonicalName = $parts[0];
2622 $canonicalName = false; # bug 21115
2626 'wgCanonicalNamespace' => $nsname,
2627 'wgCanonicalSpecialPageName' => $canonicalName,
2628 'wgNamespaceNumber' => $title->getNamespace(),
2629 'wgPageName' => $title->getPrefixedDBKey(),
2630 'wgTitle' => $title->getText(),
2631 'wgCurRevisionId' => $title->getLatestRevID(),
2632 'wgArticleId' => $title->getArticleId(),
2633 'wgIsArticle' => $this->isArticle(),
2634 'wgAction' => $wgRequest->getText( 'action', 'view' ),
2635 'wgUserName' => $wgUser->isAnon() ?
null : $wgUser->getName(),
2636 'wgUserGroups' => $wgUser->getEffectiveGroups(),
2637 'wgCategories' => $this->getCategories(),
2638 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
2640 if ( $wgContLang->hasVariants() ) {
2641 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
2643 foreach ( $title->getRestrictionTypes() as $type ) {
2644 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
2646 if ( $wgUseAjax && $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ) {
2647 $vars['wgSearchNamespaces'] = SearchEngine
::userNamespaces( $wgUser );
2650 // Allow extensions to add their custom variables to the global JS variables
2651 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars ) );
2657 * Add default \<meta\> tags
2659 protected function addDefaultMeta() {
2660 global $wgVersion, $wgHtml5;
2662 static $called = false;
2664 # Don't run this twice
2670 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); // bug 15835
2672 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
2674 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
2675 if( $p !== 'index,follow' ) {
2676 // http://www.robotstxt.org/wc/meta-user.html
2677 // Only show if it's different from the default robots policy
2678 $this->addMeta( 'robots', $p );
2681 if ( count( $this->mKeywords
) > 0 ) {
2683 "/<.*?" . ">/" => '',
2689 array_keys( $strip ),
2690 array_values( $strip ),
2691 implode( ',', $this->mKeywords
)
2698 * @return string HTML tag links to be put in the header.
2700 public function getHeadLinks( Skin
$sk ) {
2703 // Ideally this should happen earlier, somewhere. :P
2704 $this->addDefaultMeta();
2708 foreach ( $this->mMetatags
as $tag ) {
2709 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
2711 $tag[0] = substr( $tag[0], 5 );
2715 $tags[] = Html
::element( 'meta',
2718 'content' => $tag[1]
2722 foreach ( $this->mLinktags
as $tag ) {
2723 $tags[] = Html
::element( 'link', $tag );
2727 foreach( $this->getSyndicationLinks() as $format => $link ) {
2728 # Use the page name for the title (accessed through $wgTitle since
2729 # there's no other way). In principle, this could lead to issues
2730 # with having the same name for different feeds corresponding to
2731 # the same page, but we can't avoid that at this low a level.
2733 $tags[] = $this->feedLink(
2736 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
2737 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )
2741 # Recent changes feed should appear on every page (except recentchanges,
2742 # that would be redundant). Put it after the per-page feed to avoid
2743 # changing existing behavior. It's still available, probably via a
2744 # menu in your browser. Some sites might have a different feed they'd
2745 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
2746 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
2747 # If so, use it instead.
2749 global $wgOverrideSiteFeed, $wgSitename, $wgAdvertisedFeedTypes;
2750 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
2752 if ( $wgOverrideSiteFeed ) {
2753 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
2754 $tags[] = $this->feedLink(
2756 htmlspecialchars( $feedUrl ),
2757 wfMsg( "site-{$type}-feed", $wgSitename )
2760 } elseif ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
2761 foreach ( $wgAdvertisedFeedTypes as $format ) {
2762 $tags[] = $this->feedLink(
2764 $rctitle->getLocalURL( "feed={$format}" ),
2765 wfMsg( "site-{$format}-feed", $wgSitename ) # For grep: 'site-rss-feed', 'site-atom-feed'.
2770 return implode( "\n", $tags );
2774 * Generate a <link rel/> for a feed.
2776 * @param $type String: feed type
2777 * @param $url String: URL to the feed
2778 * @param $text String: value of the "title" attribute
2779 * @return String: HTML fragment
2781 private function feedLink( $type, $url, $text ) {
2782 return Html
::element( 'link', array(
2783 'rel' => 'alternate',
2784 'type' => "application/$type+xml",
2791 * Add a local or specified stylesheet, with the given media options.
2792 * Meant primarily for internal use...
2794 * @param $style String: URL to the file
2795 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
2796 * @param $condition String: for IE conditional comments, specifying an IE version
2797 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
2799 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
2801 // Even though we expect the media type to be lowercase, but here we
2802 // force it to lowercase to be safe.
2804 $options['media'] = $media;
2807 $options['condition'] = $condition;
2810 $options['dir'] = $dir;
2812 $this->styles
[$style] = $options;
2816 * Adds inline CSS styles
2817 * @param $style_css Mixed: inline CSS
2819 public function addInlineStyle( $style_css ){
2820 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
2824 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
2825 * These will be applied to various media & IE conditionals.
2826 * @param $sk Skin object
2828 public function buildCssLinks( $sk ) {
2830 // Add ResourceLoader styles
2831 // Split the styles into four groups
2832 $styles = array( 'other' => array(), 'user' => array(), 'site' => array(), 'private' => array() );
2833 $resourceLoader = $this->getResourceLoader();
2834 foreach ( $this->getModuleStyles() as $name ) {
2835 $group = $resourceLoader->getModule( $name )->getGroup();
2836 // Modules in groups named "other" or anything different than "user", "site" or "private"
2837 // will be placed in the "other" group
2838 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
2841 // We want site, private and user styles to override dynamically added styles from modules, but we want
2842 // dynamically added styles to override statically added styles from other modules. So the order
2843 // has to be other, dynamic, site, private, user
2844 // Add statically added styles for other modules
2845 $ret .= $this->makeResourceLoaderLink( $sk, $styles['other'], ResourceLoaderModule
::TYPE_STYLES
);
2846 // Add normal styles added through addStyle()/addInlineStyle() here
2847 $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
2848 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
2849 // We use a <meta> tag with a made-up name for this because that's valid HTML
2850 $ret .= Html
::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) );
2852 // Add site, private and user styles
2853 // 'private' at present only contains user.options, so put that before 'user'
2854 // Any future private modules will likely have a similar user-specific character
2855 foreach ( array( 'site', 'private', 'user' ) as $group ) {
2856 $ret .= $this->makeResourceLoaderLink( $sk, $styles[$group],
2857 ResourceLoaderModule
::TYPE_STYLES
2863 public function buildCssLinksArray() {
2865 foreach( $this->styles
as $file => $options ) {
2866 $link = $this->styleLink( $file, $options );
2868 $links[$file] = $link;
2875 * Generate \<link\> tags for stylesheets
2877 * @param $style String: URL to the file
2878 * @param $options Array: option, can contain 'condition', 'dir', 'media'
2880 * @return String: HTML fragment
2882 protected function styleLink( $style, $options ) {
2883 if( isset( $options['dir'] ) ) {
2884 $siteDir = wfUILang()->getDir();
2885 if( $siteDir != $options['dir'] ) {
2890 if( isset( $options['media'] ) ) {
2891 $media = self
::transformCssMedia( $options['media'] );
2892 if( is_null( $media ) ) {
2899 if( substr( $style, 0, 1 ) == '/' ||
2900 substr( $style, 0, 5 ) == 'http:' ||
2901 substr( $style, 0, 6 ) == 'https:' ) {
2904 global $wgStylePath, $wgStyleVersion;
2905 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
2908 $link = Html
::linkedStyle( $url, $media );
2910 if( isset( $options['condition'] ) ) {
2911 $condition = htmlspecialchars( $options['condition'] );
2912 $link = "<!--[if $condition]>$link<![endif]-->";
2918 * Transform "media" attribute based on request parameters
2920 * @param $media String: current value of the "media" attribute
2921 * @return String: modified value of the "media" attribute
2923 public static function transformCssMedia( $media ) {
2924 global $wgRequest, $wgHandheldForIPhone;
2926 // Switch in on-screen display for media testing
2928 'printable' => 'print',
2929 'handheld' => 'handheld',
2931 foreach( $switches as $switch => $targetMedia ) {
2932 if( $wgRequest->getBool( $switch ) ) {
2933 if( $media == $targetMedia ) {
2935 } elseif( $media == 'screen' ) {
2941 // Expand longer media queries as iPhone doesn't grok 'handheld'
2942 if( $wgHandheldForIPhone ) {
2943 $mediaAliases = array(
2944 'screen' => 'screen and (min-device-width: 481px)',
2945 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
2948 if( isset( $mediaAliases[$media] ) ) {
2949 $media = $mediaAliases[$media];
2957 * Turn off regular page output and return an error reponse
2958 * for when rate limiting has triggered.
2960 public function rateLimited() {
2961 $this->setPageTitle( wfMsg( 'actionthrottled' ) );
2962 $this->setRobotPolicy( 'noindex,follow' );
2963 $this->setArticleRelated( false );
2964 $this->enableClientCache( false );
2965 $this->mRedirect
= '';
2967 $this->setStatusCode( 503 );
2968 $this->addWikiMsg( 'actionthrottledtext' );
2970 $this->returnToMain( null, $this->getTitle() );
2974 * Show a warning about slave lag
2976 * If the lag is higher than $wgSlaveLagCritical seconds,
2977 * then the warning is a bit more obvious. If the lag is
2978 * lower than $wgSlaveLagWarning, then no warning is shown.
2980 * @param $lag Integer: slave lag
2982 public function showLagWarning( $lag ) {
2983 global $wgSlaveLagWarning, $wgSlaveLagCritical, $wgLang;
2984 if( $lag >= $wgSlaveLagWarning ) {
2985 $message = $lag < $wgSlaveLagCritical
2988 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2989 $this->wrapWikiMsg( "$wrap\n", array( $message, $wgLang->formatNum( $lag ) ) );
2994 * Add a wikitext-formatted message to the output.
2995 * This is equivalent to:
2997 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2999 public function addWikiMsg( /*...*/ ) {
3000 $args = func_get_args();
3001 $name = array_shift( $args );
3002 $this->addWikiMsgArray( $name, $args );
3006 * Add a wikitext-formatted message to the output.
3007 * Like addWikiMsg() except the parameters are taken as an array
3008 * instead of a variable argument list.
3010 * $options is passed through to wfMsgExt(), see that function for details.
3012 public function addWikiMsgArray( $name, $args, $options = array() ) {
3013 $options[] = 'parse';
3014 $text = wfMsgExt( $name, $options, $args );
3015 $this->addHTML( $text );
3019 * This function takes a number of message/argument specifications, wraps them in
3020 * some overall structure, and then parses the result and adds it to the output.
3022 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3023 * on. The subsequent arguments may either be strings, in which case they are the
3024 * message names, or arrays, in which case the first element is the message name,
3025 * and subsequent elements are the parameters to that message.
3027 * The special named parameter 'options' in a message specification array is passed
3028 * through to the $options parameter of wfMsgExt().
3030 * Don't use this for messages that are not in users interface language.
3034 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3038 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . "\n</div>" );
3040 * The newline after opening div is needed in some wikitext. See bug 19226.
3042 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3043 $msgSpecs = func_get_args();
3044 array_shift( $msgSpecs );
3045 $msgSpecs = array_values( $msgSpecs );
3047 foreach ( $msgSpecs as $n => $spec ) {
3049 if ( is_array( $spec ) ) {
3051 $name = array_shift( $args );
3052 if ( isset( $args['options'] ) ) {
3053 $options = $args['options'];
3054 unset( $args['options'] );
3060 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
3062 $this->addWikiText( $s );
3066 * Include jQuery core. Use this to avoid loading it multiple times
3067 * before we get a usable script loader.
3069 * @param $modules Array: list of jQuery modules which should be loaded
3070 * @return Array: the list of modules which were not loaded.
3072 * @deprecated @since 1.17
3074 public function includeJQuery( $modules = array() ) {