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, and modules
365 * which are no longer registered (eg a page is cached before an extension is disabled)
366 * @param $modules Array
369 protected function filterModules( $modules, $type = ResourceLoaderModule
::TYPE_COMBINED
){
370 $resourceLoader = $this->getResourceLoader();
371 $filteredModules = array();
372 foreach( $modules as $val ){
373 $module = $resourceLoader->getModule( $val );
374 if( $module instanceof ResourceLoaderModule
375 && $module->getOrigin() <= $this->getAllowedModules( $type ) )
377 $filteredModules[] = $val;
380 return $filteredModules;
384 * Get the list of modules to include on this page
386 * @param $filter Bool whether to filter out insufficiently trustworthy modules
387 * @return Array of module names
389 public function getModules( $filter = false, $param = 'mModules' ) {
390 $modules = array_values( array_unique( $this->$param ) );
392 ?
$this->filterModules( $modules )
397 * Add one or more modules recognized by the resource loader. Modules added
398 * through this function will be loaded by the resource loader when the
401 * @param $modules Mixed: module name (string) or array of module names
403 public function addModules( $modules ) {
404 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
408 * Get the list of module JS to include on this page
409 * @return array of module names
411 public function getModuleScripts( $filter = false ) {
412 return $this->getModules( $filter, 'mModuleScripts' );
416 * Add only JS of one or more modules recognized by the resource loader. Module
417 * scripts added through this function will be loaded by the resource loader when
420 * @param $modules Mixed: module name (string) or array of module names
422 public function addModuleScripts( $modules ) {
423 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
427 * Get the list of module CSS to include on this page
429 * @return Array of module names
431 public function getModuleStyles( $filter = false ) {
432 return $this->getModules( $filter, 'mModuleStyles' );
436 * Add only CSS of one or more modules recognized by the resource loader. Module
437 * styles added through this function will be loaded by the resource loader when
440 * @param $modules Mixed: module name (string) or array of module names
442 public function addModuleStyles( $modules ) {
443 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
447 * Get the list of module messages to include on this page
449 * @return Array of module names
451 public function getModuleMessages( $filter = false ) {
452 return $this->getModules( $filter, 'mModuleMessages' );
456 * Add only messages of one or more modules recognized by the resource loader.
457 * Module messages added through this function will be loaded by the resource
458 * loader when the page loads.
460 * @param $modules Mixed: module name (string) or array of module names
462 public function addModuleMessages( $modules ) {
463 $this->mModuleMessages
= array_merge( $this->mModuleMessages
, (array)$modules );
467 * Get all header items in a string
471 function getHeadItems() {
473 foreach ( $this->mHeadItems
as $item ) {
480 * Add or replace an header item to the output
482 * @param $name String: item name
483 * @param $value String: raw HTML
485 public function addHeadItem( $name, $value ) {
486 $this->mHeadItems
[$name] = $value;
490 * Check if the header item $name is already set
492 * @param $name String: item name
495 public function hasHeadItem( $name ) {
496 return isset( $this->mHeadItems
[$name] );
500 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
502 * @param $tag String: value of "ETag" header
504 function setETag( $tag ) {
509 * Set whether the output should only contain the body of the article,
510 * without any skin, sidebar, etc.
511 * Used e.g. when calling with "action=render".
513 * @param $only Boolean: whether to output only the body of the article
515 public function setArticleBodyOnly( $only ) {
516 $this->mArticleBodyOnly
= $only;
520 * Return whether the output will contain only the body of the article
524 public function getArticleBodyOnly() {
525 return $this->mArticleBodyOnly
;
529 * checkLastModified tells the client to use the client-cached page if
530 * possible. If sucessful, the OutputPage is disabled so that
531 * any future call to OutputPage->output() have no effect.
533 * Side effect: sets mLastModified for Last-Modified header
535 * @return Boolean: true iff cache-ok headers was sent.
537 public function checkLastModified( $timestamp ) {
538 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
540 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
541 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
544 if( !$wgCachePages ) {
545 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
548 if( $wgUser->getOption( 'nocache' ) ) {
549 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
553 $timestamp = wfTimestamp( TS_MW
, $timestamp );
554 $modifiedTimes = array(
555 'page' => $timestamp,
556 'user' => $wgUser->getTouched(),
557 'epoch' => $wgCacheEpoch
559 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
561 $maxModified = max( $modifiedTimes );
562 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
564 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
565 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
571 foreach ( $modifiedTimes as $name => $value ) {
572 if ( $info !== '' ) {
575 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
578 # IE sends sizes after the date like this:
579 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
580 # this breaks strtotime().
581 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
583 wfSuppressWarnings(); // E_STRICT system time bitching
584 $clientHeaderTime = strtotime( $clientHeader );
586 if ( !$clientHeaderTime ) {
587 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
590 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
592 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
593 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
594 wfDebug( __METHOD__
. ": effective Last-Modified: " .
595 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
596 if( $clientHeaderTime < $maxModified ) {
597 wfDebug( __METHOD__
. ": STALE, $info\n", false );
602 # Give a 304 response code and disable body output
603 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
604 ini_set( 'zlib.output_compression', 0 );
605 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
606 $this->sendCacheControl();
609 // Don't output a compressed blob when using ob_gzhandler;
610 // it's technically against HTTP spec and seems to confuse
611 // Firefox when the response gets split over two packets.
612 wfClearOutputBuffers();
618 * Override the last modified timestamp
620 * @param $timestamp String: new timestamp, in a format readable by
623 public function setLastModified( $timestamp ) {
624 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
628 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
630 * @param $policy String: the literal string to output as the contents of
631 * the meta tag. Will be parsed according to the spec and output in
635 public function setRobotPolicy( $policy ) {
636 $policy = Article
::formatRobotPolicy( $policy );
638 if( isset( $policy['index'] ) ) {
639 $this->setIndexPolicy( $policy['index'] );
641 if( isset( $policy['follow'] ) ) {
642 $this->setFollowPolicy( $policy['follow'] );
647 * Set the index policy for the page, but leave the follow policy un-
650 * @param $policy string Either 'index' or 'noindex'.
653 public function setIndexPolicy( $policy ) {
654 $policy = trim( $policy );
655 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
656 $this->mIndexPolicy
= $policy;
661 * Set the follow policy for the page, but leave the index policy un-
664 * @param $policy String: either 'follow' or 'nofollow'.
667 public function setFollowPolicy( $policy ) {
668 $policy = trim( $policy );
669 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
670 $this->mFollowPolicy
= $policy;
675 * Set the new value of the "action text", this will be added to the
676 * "HTML title", separated from it with " - ".
678 * @param $text String: new value of the "action text"
680 public function setPageTitleActionText( $text ) {
681 $this->mPageTitleActionText
= $text;
685 * Get the value of the "action text"
689 public function getPageTitleActionText() {
690 if ( isset( $this->mPageTitleActionText
) ) {
691 return $this->mPageTitleActionText
;
696 * "HTML title" means the contents of <title>.
697 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
699 public function setHTMLTitle( $name ) {
700 $this->mHTMLtitle
= $name;
704 * Return the "HTML title", i.e. the content of the <title> tag.
708 public function getHTMLTitle() {
709 return $this->mHTMLtitle
;
713 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
714 * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
715 * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
716 * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
718 public function setPageTitle( $name ) {
719 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
720 # but leave "<i>foobar</i>" alone
721 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
722 $this->mPagetitle
= $nameWithTags;
724 # change "<i>foo&bar</i>" to "foo&bar"
725 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer
::stripAllTags( $nameWithTags ) ) );
729 * Return the "page title", i.e. the content of the \<h1\> tag.
733 public function getPageTitle() {
734 return $this->mPagetitle
;
738 * Set the Title object to use
740 * @param $t Title object
742 public function setTitle( $t ) {
747 * Get the Title object used in this instance
751 public function getTitle() {
752 if ( $this->mTitle
instanceof Title
) {
753 return $this->mTitle
;
755 wfDebug( __METHOD__
. " called and \$mTitle is null. Return \$wgTitle for sanity\n" );
762 * Replace the subtile with $str
764 * @param $str String: new value of the subtitle
766 public function setSubtitle( $str ) {
767 $this->mSubtitle
= /*$this->parse(*/ $str /*)*/; // @bug 2514
771 * Add $str to the subtitle
773 * @param $str String to add to the subtitle
775 public function appendSubtitle( $str ) {
776 $this->mSubtitle
.= /*$this->parse(*/ $str /*)*/; // @bug 2514
784 public function getSubtitle() {
785 return $this->mSubtitle
;
789 * Set the page as printable, i.e. it'll be displayed with with all
790 * print styles included
792 public function setPrintable() {
793 $this->mPrintable
= true;
797 * Return whether the page is "printable"
801 public function isPrintable() {
802 return $this->mPrintable
;
806 * Disable output completely, i.e. calling output() will have no effect
808 public function disable() {
809 $this->mDoNothing
= true;
813 * Return whether the output will be completely disabled
817 public function isDisabled() {
818 return $this->mDoNothing
;
822 * Show an "add new section" link?
826 public function showNewSectionLink() {
827 return $this->mNewSectionLink
;
831 * Forcibly hide the new section link?
835 public function forceHideNewSectionLink() {
836 return $this->mHideNewSectionLink
;
840 * Add or remove feed links in the page header
841 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
842 * for the new version
845 * @param $show Boolean: true: add default feeds, false: remove all feeds
847 public function setSyndicated( $show = true ) {
849 $this->setFeedAppendQuery( false );
851 $this->mFeedLinks
= array();
856 * Add default feeds to the page header
857 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
858 * for the new version
861 * @param $val String: query to append to feed links or false to output
864 public function setFeedAppendQuery( $val ) {
865 global $wgAdvertisedFeedTypes;
867 $this->mFeedLinks
= array();
869 foreach ( $wgAdvertisedFeedTypes as $type ) {
870 $query = "feed=$type";
871 if ( is_string( $val ) ) {
872 $query .= '&' . $val;
874 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
879 * Add a feed link to the page header
881 * @param $format String: feed type, should be a key of $wgFeedClasses
882 * @param $href String: URL
884 public function addFeedLink( $format, $href ) {
885 global $wgAdvertisedFeedTypes;
887 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
888 $this->mFeedLinks
[$format] = $href;
893 * Should we output feed links for this page?
896 public function isSyndicated() {
897 return count( $this->mFeedLinks
) > 0;
901 * Return URLs for each supported syndication format for this page.
902 * @return array associating format keys with URLs
904 public function getSyndicationLinks() {
905 return $this->mFeedLinks
;
909 * Will currently always return null
913 public function getFeedAppendQuery() {
914 return $this->mFeedLinksAppendQuery
;
918 * Set whether the displayed content is related to the source of the
919 * corresponding article on the wiki
920 * Setting true will cause the change "article related" toggle to true
924 public function setArticleFlag( $v ) {
925 $this->mIsarticle
= $v;
927 $this->mIsArticleRelated
= $v;
932 * Return whether the content displayed page is related to the source of
933 * the corresponding article on the wiki
937 public function isArticle() {
938 return $this->mIsarticle
;
942 * Set whether this page is related an article on the wiki
943 * Setting false will cause the change of "article flag" toggle to false
947 public function setArticleRelated( $v ) {
948 $this->mIsArticleRelated
= $v;
950 $this->mIsarticle
= false;
955 * Return whether this page is related an article on the wiki
959 public function isArticleRelated() {
960 return $this->mIsArticleRelated
;
964 * Add new language links
966 * @param $newLinkArray Associative array mapping language code to the page
969 public function addLanguageLinks( $newLinkArray ) {
970 $this->mLanguageLinks +
= $newLinkArray;
974 * Reset the language links and add new language links
976 * @param $newLinkArray Associative array mapping language code to the page
979 public function setLanguageLinks( $newLinkArray ) {
980 $this->mLanguageLinks
= $newLinkArray;
984 * Get the list of language links
986 * @return Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
988 public function getLanguageLinks() {
989 return $this->mLanguageLinks
;
993 * Add an array of categories, with names in the keys
995 * @param $categories Array mapping category name => sort key
997 public function addCategoryLinks( $categories ) {
998 global $wgUser, $wgContLang;
1000 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1004 # Add the links to a LinkBatch
1005 $arr = array( NS_CATEGORY
=> $categories );
1006 $lb = new LinkBatch
;
1007 $lb->setArray( $arr );
1009 # Fetch existence plus the hiddencat property
1010 $dbr = wfGetDB( DB_SLAVE
);
1011 $res = $dbr->select( array( 'page', 'page_props' ),
1012 array( 'page_id', 'page_namespace', 'page_title', 'page_len', 'page_is_redirect', 'page_latest', 'pp_value' ),
1013 $lb->constructSet( 'page', $dbr ),
1016 array( 'page_props' => array( 'LEFT JOIN', array( 'pp_propname' => 'hiddencat', 'pp_page = page_id' ) ) )
1019 # Add the results to the link cache
1020 $lb->addResultToCache( LinkCache
::singleton(), $res );
1022 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
1023 $categories = array_combine(
1024 array_keys( $categories ),
1025 array_fill( 0, count( $categories ), 'normal' )
1028 # Mark hidden categories
1029 foreach ( $res as $row ) {
1030 if ( isset( $row->pp_value
) ) {
1031 $categories[$row->page_title
] = 'hidden';
1035 # Add the remaining categories to the skin
1036 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
1037 $sk = $wgUser->getSkin();
1038 foreach ( $categories as $category => $type ) {
1039 $origcategory = $category;
1040 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1041 $wgContLang->findVariantLink( $category, $title, true );
1042 if ( $category != $origcategory ) {
1043 if ( array_key_exists( $category, $categories ) ) {
1047 $text = $wgContLang->convertHtml( $title->getText() );
1048 $this->mCategories
[] = $title->getText();
1049 $this->mCategoryLinks
[$type][] = $sk->link( $title, $text );
1055 * Reset the category links (but not the category list) and add $categories
1057 * @param $categories Array mapping category name => sort key
1059 public function setCategoryLinks( $categories ) {
1060 $this->mCategoryLinks
= array();
1061 $this->addCategoryLinks( $categories );
1065 * Get the list of category links, in a 2-D array with the following format:
1066 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1067 * hidden categories) and $link a HTML fragment with a link to the category
1072 public function getCategoryLinks() {
1073 return $this->mCategoryLinks
;
1077 * Get the list of category names this page belongs to
1079 * @return Array of strings
1081 public function getCategories() {
1082 return $this->mCategories
;
1086 * Do not allow scripts which can be modified by wiki users to load on this page;
1087 * only allow scripts bundled with, or generated by, the software.
1089 public function disallowUserJs() {
1090 $this->reduceAllowedModules(
1091 ResourceLoaderModule
::TYPE_SCRIPTS
,
1092 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1097 * Return whether user JavaScript is allowed for this page
1098 * @deprecated since 1.18 Load modules with ResourceLoader, and origin and
1099 * trustworthiness is identified and enforced automagically.
1102 public function isUserJsAllowed() {
1103 return $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
) >= ResourceLoaderModule
::ORIGIN_USER_INDIVIDUAL
;
1107 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1108 * @see ResourceLoaderModule::$origin
1109 * @param $type String ResourceLoaderModule TYPE_ constant
1110 * @return Int ResourceLoaderModule ORIGIN_ class constant
1112 public function getAllowedModules( $type ){
1113 if( $type == ResourceLoaderModule
::TYPE_COMBINED
){
1114 return min( array_values( $this->mAllowedModules
) );
1116 return isset( $this->mAllowedModules
[$type] )
1117 ?
$this->mAllowedModules
[$type]
1118 : ResourceLoaderModule
::ORIGIN_ALL
;
1123 * Set the highest level of CSS/JS untrustworthiness allowed
1124 * @param $type String ResourceLoaderModule TYPE_ constant
1125 * @param $level Int ResourceLoaderModule class constant
1127 public function setAllowedModules( $type, $level ){
1128 $this->mAllowedModules
[$type] = $level;
1132 * As for setAllowedModules(), but don't inadvertantly make the page more accessible
1133 * @param $type String
1134 * @param $level Int ResourceLoaderModule class constant
1136 public function reduceAllowedModules( $type, $level ){
1137 $this->mAllowedModules
[$type] = min( $this->getAllowedModules($type), $level );
1141 * Prepend $text to the body HTML
1143 * @param $text String: HTML
1145 public function prependHTML( $text ) {
1146 $this->mBodytext
= $text . $this->mBodytext
;
1150 * Append $text to the body HTML
1152 * @param $text String: HTML
1154 public function addHTML( $text ) {
1155 $this->mBodytext
.= $text;
1159 * Clear the body HTML
1161 public function clearHTML() {
1162 $this->mBodytext
= '';
1168 * @return String: HTML
1170 public function getHTML() {
1171 return $this->mBodytext
;
1175 * Add $text to the debug output
1177 * @param $text String: debug text
1179 public function debug( $text ) {
1180 $this->mDebugtext
.= $text;
1184 * Get/set the ParserOptions object to use for wikitext parsing
1186 * @param $options either the ParserOption to use or null to only get the
1187 * current ParserOption object
1188 * @return ParserOptions object
1190 public function parserOptions( $options = null ) {
1191 if ( !$this->mParserOptions
) {
1192 $this->mParserOptions
= new ParserOptions
;
1194 return wfSetVar( $this->mParserOptions
, $options );
1198 * Set the revision ID which will be seen by the wiki text parser
1199 * for things such as embedded {{REVISIONID}} variable use.
1201 * @param $revid Mixed: an positive integer, or null
1202 * @return Mixed: previous value
1204 public function setRevisionId( $revid ) {
1205 $val = is_null( $revid ) ?
null : intval( $revid );
1206 return wfSetVar( $this->mRevisionId
, $val );
1210 * Get the current revision ID
1214 public function getRevisionId() {
1215 return $this->mRevisionId
;
1219 * Convert wikitext to HTML and add it to the buffer
1220 * Default assumes that the current page title will be used.
1222 * @param $text String
1223 * @param $linestart Boolean: is this the start of a line?
1225 public function addWikiText( $text, $linestart = true ) {
1226 $title = $this->getTitle(); // Work arround E_STRICT
1227 $this->addWikiTextTitle( $text, $title, $linestart );
1231 * Add wikitext with a custom Title object
1233 * @param $text String: wikitext
1234 * @param $title Title object
1235 * @param $linestart Boolean: is this the start of a line?
1237 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1238 $this->addWikiTextTitle( $text, $title, $linestart );
1242 * Add wikitext with a custom Title object and
1244 * @param $text String: wikitext
1245 * @param $title Title object
1246 * @param $linestart Boolean: is this the start of a line?
1248 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1249 $this->addWikiTextTitle( $text, $title, $linestart, true );
1253 * Add wikitext with tidy enabled
1255 * @param $text String: wikitext
1256 * @param $linestart Boolean: is this the start of a line?
1258 public function addWikiTextTidy( $text, $linestart = true ) {
1259 $title = $this->getTitle();
1260 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1264 * Add wikitext with a custom Title object
1266 * @param $text String: wikitext
1267 * @param $title Title object
1268 * @param $linestart Boolean: is this the start of a line?
1269 * @param $tidy Boolean: whether to use tidy
1271 public function addWikiTextTitle( $text, &$title, $linestart, $tidy = false ) {
1274 wfProfileIn( __METHOD__
);
1276 wfIncrStats( 'pcache_not_possible' );
1278 $popts = $this->parserOptions();
1279 $oldTidy = $popts->setTidy( $tidy );
1281 $parserOutput = $wgParser->parse(
1282 $text, $title, $popts,
1283 $linestart, true, $this->mRevisionId
1286 $popts->setTidy( $oldTidy );
1288 $this->addParserOutput( $parserOutput );
1290 wfProfileOut( __METHOD__
);
1294 * Add a ParserOutput object, but without Html
1296 * @param $parserOutput ParserOutput object
1298 public function addParserOutputNoText( &$parserOutput ) {
1299 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1300 $this->addCategoryLinks( $parserOutput->getCategories() );
1301 $this->mNewSectionLink
= $parserOutput->getNewSection();
1302 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1304 $this->mParseWarnings
= $parserOutput->getWarnings();
1305 if ( !$parserOutput->isCacheable() ) {
1306 $this->enableClientCache( false );
1308 $this->mNoGallery
= $parserOutput->getNoGallery();
1309 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1310 $this->addModules( $parserOutput->getModules() );
1312 foreach ( (array)$parserOutput->mTemplateIds
as $ns => $dbks ) {
1313 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1314 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1316 $this->mTemplateIds
[$ns] = $dbks;
1320 // Hooks registered in the object
1321 global $wgParserOutputHooks;
1322 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1323 list( $hookName, $data ) = $hookInfo;
1324 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1325 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1329 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1333 * Add a ParserOutput object
1335 * @param $parserOutput ParserOutput
1337 function addParserOutput( &$parserOutput ) {
1338 $this->addParserOutputNoText( $parserOutput );
1339 $text = $parserOutput->getText();
1340 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1341 $this->addHTML( $text );
1346 * Add the output of a QuickTemplate to the output buffer
1348 * @param $template QuickTemplate
1350 public function addTemplate( &$template ) {
1352 $template->execute();
1353 $this->addHTML( ob_get_contents() );
1358 * Parse wikitext and return the HTML.
1360 * @param $text String
1361 * @param $linestart Boolean: is this the start of a line?
1362 * @param $interface Boolean: use interface language ($wgLang instead of
1363 * $wgContLang) while parsing language sensitive magic
1364 * words like GRAMMAR and PLURAL
1365 * @param $language Language object: target language object, will override
1367 * @return String: HTML
1369 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1370 // Check one for one common cause for parser state resetting
1371 $callers = wfGetAllCallers( 10 );
1372 if ( strpos( $callers, 'Parser::extensionSubstitution' ) !== false ) {
1373 throw new MWException( "wfMsg* function with parsing cannot be used " .
1374 "inside a tag hook. Should use parser->recursiveTagParse() instead" );
1379 if( is_null( $this->getTitle() ) ) {
1380 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1383 $popts = $this->parserOptions();
1385 $popts->setInterfaceMessage( true );
1387 if ( $language !== null ) {
1388 $oldLang = $popts->setTargetLanguage( $language );
1391 $parserOutput = $wgParser->parse(
1392 $text, $this->getTitle(), $popts,
1393 $linestart, true, $this->mRevisionId
1397 $popts->setInterfaceMessage( false );
1399 if ( $language !== null ) {
1400 $popts->setTargetLanguage( $oldLang );
1403 return $parserOutput->getText();
1407 * Parse wikitext, strip paragraphs, and return the HTML.
1409 * @param $text String
1410 * @param $linestart Boolean: is this the start of a line?
1411 * @param $interface Boolean: use interface language ($wgLang instead of
1412 * $wgContLang) while parsing language sensitive magic
1413 * words like GRAMMAR and PLURAL
1414 * @return String: HTML
1416 public function parseInline( $text, $linestart = true, $interface = false ) {
1417 $parsed = $this->parse( $text, $linestart, $interface );
1420 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1428 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1430 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1432 public function setSquidMaxage( $maxage ) {
1433 $this->mSquidMaxage
= $maxage;
1437 * Use enableClientCache(false) to force it to send nocache headers
1441 public function enableClientCache( $state ) {
1442 return wfSetVar( $this->mEnableClientCache
, $state );
1446 * Get the list of cookies that will influence on the cache
1450 function getCacheVaryCookies() {
1451 global $wgCookiePrefix, $wgCacheVaryCookies;
1453 if ( $cookies === null ) {
1454 $cookies = array_merge(
1456 "{$wgCookiePrefix}Token",
1457 "{$wgCookiePrefix}LoggedOut",
1462 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1468 * Return whether this page is not cacheable because "useskin" or "uselang"
1469 * URL parameters were passed.
1473 function uncacheableBecauseRequestVars() {
1475 return $wgRequest->getText( 'useskin', false ) === false
1476 && $wgRequest->getText( 'uselang', false ) === false;
1480 * Check if the request has a cache-varying cookie header
1481 * If it does, it's very important that we don't allow public caching
1485 function haveCacheVaryCookies() {
1487 $cookieHeader = $wgRequest->getHeader( 'cookie' );
1488 if ( $cookieHeader === false ) {
1491 $cvCookies = $this->getCacheVaryCookies();
1492 foreach ( $cvCookies as $cookieName ) {
1493 # Check for a simple string match, like the way squid does it
1494 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1495 wfDebug( __METHOD__
. ": found $cookieName\n" );
1499 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1504 * Add an HTTP header that will influence on the cache
1506 * @param $header String: header name
1507 * @param $option Array|null
1508 * @fixme Document the $option parameter; it appears to be for
1509 * X-Vary-Options but what format is acceptable?
1511 public function addVaryHeader( $header, $option = null ) {
1512 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1513 $this->mVaryHeader
[$header] = (array)$option;
1514 } elseif( is_array( $option ) ) {
1515 if( is_array( $this->mVaryHeader
[$header] ) ) {
1516 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
1518 $this->mVaryHeader
[$header] = $option;
1521 $this->mVaryHeader
[$header] = array_unique( $this->mVaryHeader
[$header] );
1525 * Get a complete X-Vary-Options header
1529 public function getXVO() {
1530 $cvCookies = $this->getCacheVaryCookies();
1532 $cookiesOption = array();
1533 foreach ( $cvCookies as $cookieName ) {
1534 $cookiesOption[] = 'string-contains=' . $cookieName;
1536 $this->addVaryHeader( 'Cookie', $cookiesOption );
1539 foreach( $this->mVaryHeader
as $header => $option ) {
1540 $newheader = $header;
1541 if( is_array( $option ) ) {
1542 $newheader .= ';' . implode( ';', $option );
1544 $headers[] = $newheader;
1546 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1552 * bug 21672: Add Accept-Language to Vary and XVO headers
1553 * if there's no 'variant' parameter existed in GET.
1556 * /w/index.php?title=Main_page should always be served; but
1557 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1559 function addAcceptLanguage() {
1560 global $wgRequest, $wgContLang;
1561 if( !$wgRequest->getCheck( 'variant' ) && $wgContLang->hasVariants() ) {
1562 $variants = $wgContLang->getVariants();
1563 $aloption = array();
1564 foreach ( $variants as $variant ) {
1565 if( $variant === $wgContLang->getCode() ) {
1568 $aloption[] = 'string-contains=' . $variant;
1570 // IE and some other browsers use another form of language code
1571 // in their Accept-Language header, like "zh-CN" or "zh-TW".
1572 // We should handle these too.
1573 $ievariant = explode( '-', $variant );
1574 if ( count( $ievariant ) == 2 ) {
1575 $ievariant[1] = strtoupper( $ievariant[1] );
1576 $ievariant = implode( '-', $ievariant );
1577 $aloption[] = 'string-contains=' . $ievariant;
1581 $this->addVaryHeader( 'Accept-Language', $aloption );
1586 * Set a flag which will cause an X-Frame-Options header appropriate for
1587 * edit pages to be sent. The header value is controlled by
1588 * $wgEditPageFrameOptions.
1590 * This is the default for special pages. If you display a CSRF-protected
1591 * form on an ordinary view page, then you need to call this function.
1593 public function preventClickjacking( $enable = true ) {
1594 $this->mPreventClickjacking
= $enable;
1598 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1599 * This can be called from pages which do not contain any CSRF-protected
1602 public function allowClickjacking() {
1603 $this->mPreventClickjacking
= false;
1607 * Get the X-Frame-Options header value (without the name part), or false
1608 * if there isn't one. This is used by Skin to determine whether to enable
1609 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1611 public function getFrameOptions() {
1612 global $wgBreakFrames, $wgEditPageFrameOptions;
1613 if ( $wgBreakFrames ) {
1615 } elseif ( $this->mPreventClickjacking
&& $wgEditPageFrameOptions ) {
1616 return $wgEditPageFrameOptions;
1621 * Send cache control HTTP headers
1623 public function sendCacheControl() {
1624 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest, $wgUseXVO;
1626 $response = $wgRequest->response();
1627 if ( $wgUseETag && $this->mETag
) {
1628 $response->header( "ETag: $this->mETag" );
1631 $this->addAcceptLanguage();
1633 # don't serve compressed data to clients who can't handle it
1634 # maintain different caches for logged-in users and non-logged in ones
1635 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) ) );
1638 # Add an X-Vary-Options header for Squid with Wikimedia patches
1639 $response->header( $this->getXVO() );
1642 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
1644 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1645 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
1649 # We'll purge the proxy cache explicitly, but require end user agents
1650 # to revalidate against the proxy on each visit.
1651 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1652 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1653 # start with a shorter timeout for initial testing
1654 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1655 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
1656 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1658 # We'll purge the proxy cache for anons explicitly, but require end user agents
1659 # to revalidate against the proxy on each visit.
1660 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1661 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1662 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
1663 # start with a shorter timeout for initial testing
1664 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1665 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
1668 # We do want clients to cache if they can, but they *must* check for updates
1669 # on revisiting the page.
1670 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
1671 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1672 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1674 if($this->mLastModified
) {
1675 $response->header( "Last-Modified: {$this->mLastModified}" );
1678 wfDebug( __METHOD__
. ": no caching **\n", false );
1680 # In general, the absence of a last modified header should be enough to prevent
1681 # the client from using its cache. We send a few other things just to make sure.
1682 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1683 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1684 $response->header( 'Pragma: no-cache' );
1689 * Get the message associed with the HTTP response code $code
1691 * @param $code Integer: status code
1692 * @return String or null: message or null if $code is not in the list of
1695 public static function getStatusMessage( $code ) {
1696 static $statusMessage = array(
1698 101 => 'Switching Protocols',
1699 102 => 'Processing',
1703 203 => 'Non-Authoritative Information',
1704 204 => 'No Content',
1705 205 => 'Reset Content',
1706 206 => 'Partial Content',
1707 207 => 'Multi-Status',
1708 300 => 'Multiple Choices',
1709 301 => 'Moved Permanently',
1712 304 => 'Not Modified',
1714 307 => 'Temporary Redirect',
1715 400 => 'Bad Request',
1716 401 => 'Unauthorized',
1717 402 => 'Payment Required',
1720 405 => 'Method Not Allowed',
1721 406 => 'Not Acceptable',
1722 407 => 'Proxy Authentication Required',
1723 408 => 'Request Timeout',
1726 411 => 'Length Required',
1727 412 => 'Precondition Failed',
1728 413 => 'Request Entity Too Large',
1729 414 => 'Request-URI Too Large',
1730 415 => 'Unsupported Media Type',
1731 416 => 'Request Range Not Satisfiable',
1732 417 => 'Expectation Failed',
1733 422 => 'Unprocessable Entity',
1735 424 => 'Failed Dependency',
1736 500 => 'Internal Server Error',
1737 501 => 'Not Implemented',
1738 502 => 'Bad Gateway',
1739 503 => 'Service Unavailable',
1740 504 => 'Gateway Timeout',
1741 505 => 'HTTP Version Not Supported',
1742 507 => 'Insufficient Storage'
1744 return isset( $statusMessage[$code] ) ?
$statusMessage[$code] : null;
1748 * Finally, all the text has been munged and accumulated into
1749 * the object, let's actually output it:
1751 public function output() {
1752 global $wgUser, $wgOutputEncoding, $wgRequest;
1753 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType;
1754 global $wgUseAjax, $wgAjaxWatch;
1755 global $wgEnableMWSuggest, $wgUniversalEditButton;
1757 if( $this->mDoNothing
) {
1760 wfProfileIn( __METHOD__
);
1761 if ( $this->mRedirect
!= '' ) {
1762 # Standards require redirect URLs to be absolute
1763 $this->mRedirect
= wfExpandUrl( $this->mRedirect
);
1764 if( $this->mRedirectCode
== '301' ||
$this->mRedirectCode
== '303' ) {
1765 if( !$wgDebugRedirects ) {
1766 $message = self
::getStatusMessage( $this->mRedirectCode
);
1767 $wgRequest->response()->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
1769 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1771 $this->sendCacheControl();
1773 $wgRequest->response()->header( "Content-Type: text/html; charset=utf-8" );
1774 if( $wgDebugRedirects ) {
1775 $url = htmlspecialchars( $this->mRedirect
);
1776 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1777 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1778 print "</body>\n</html>\n";
1780 $wgRequest->response()->header( 'Location: ' . $this->mRedirect
);
1782 wfProfileOut( __METHOD__
);
1784 } elseif ( $this->mStatusCode
) {
1785 $message = self
::getStatusMessage( $this->mStatusCode
);
1787 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
1791 // Add base resources
1792 $this->addModules( 'mediawiki.util' );
1793 global $wgIncludeLegacyJavaScript;
1794 if( $wgIncludeLegacyJavaScript ){
1795 $this->addModules( 'mediawiki.legacy.wikibits' );
1798 // Add various resources if required
1800 $this->addModules( 'mediawiki.legacy.ajax' );
1802 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1804 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1805 $this->addModules( 'mediawiki.action.watch.ajax' );
1808 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ) {
1809 $this->addModules( 'mediawiki.legacy.mwsuggest' );
1813 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1814 $this->addModules( 'mediawiki.action.view.rightClickEdit' );
1817 if( $wgUniversalEditButton ) {
1818 if( $this->isArticleRelated() && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1819 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create' ) ) ) {
1820 // Original UniversalEditButton
1821 $msg = wfMsg( 'edit' );
1822 $this->addLink( array(
1823 'rel' => 'alternate',
1824 'type' => 'application/x-wiki',
1826 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1828 // Alternate edit link
1829 $this->addLink( array(
1832 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1838 # Buffer output; final headers may depend on later processing
1841 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1842 $wgRequest->response()->header( 'Content-language: ' . $wgLanguageCode );
1844 // Prevent framing, if requested
1845 $frameOptions = $this->getFrameOptions();
1846 if ( $frameOptions ) {
1847 $wgRequest->response()->header( "X-Frame-Options: $frameOptions" );
1850 if ( $this->mArticleBodyOnly
) {
1851 $this->out( $this->mBodytext
);
1853 $sk = $wgUser->getSkin( $this->getTitle() );
1855 // Hook that allows last minute changes to the output page, e.g.
1856 // adding of CSS or Javascript by extensions.
1857 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1859 wfProfileIn( 'Output-skin' );
1860 $sk->outputPage( $this );
1861 wfProfileOut( 'Output-skin' );
1864 $this->sendCacheControl();
1866 wfProfileOut( __METHOD__
);
1870 * Actually output something with print(). Performs an iconv to the
1871 * output encoding, if needed.
1873 * @param $ins String: the string to output
1875 public function out( $ins ) {
1876 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1877 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1880 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1881 if ( false === $outs ) {
1889 * Produce a "user is blocked" page.
1891 * @param $return Boolean: whether to have a "return to $wgTitle" message or not.
1894 function blockedPage( $return = true ) {
1895 global $wgUser, $wgContLang, $wgLang;
1897 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1898 $this->setRobotPolicy( 'noindex,nofollow' );
1899 $this->setArticleRelated( false );
1901 $name = User
::whoIs( $wgUser->blockedBy() );
1902 $reason = $wgUser->blockedFor();
1903 if( $reason == '' ) {
1904 $reason = wfMsg( 'blockednoreason' );
1906 $blockTimestamp = $wgLang->timeanddate(
1907 wfTimestamp( TS_MW
, $wgUser->mBlock
->mTimestamp
), true
1911 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1913 $blockid = $wgUser->mBlock
->getId();
1915 $blockExpiry = $wgLang->formatExpiry( $wgUser->mBlock
->mExpiry
);
1917 if ( $wgUser->mBlock
->mAuto
) {
1918 $msg = 'autoblockedtext';
1920 $msg = 'blockedtext';
1923 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1924 * This could be a username, an IP range, or a single IP. */
1925 $intended = $wgUser->mBlock
->getTarget();
1928 $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry,
1929 $intended, $blockTimestamp
1932 # Don't auto-return to special pages
1934 $return = $this->getTitle()->getNamespace() > -1 ?
$this->getTitle() : null;
1935 $this->returnToMain( null, $return );
1940 * Output a standard error page
1942 * @param $title String: message key for page title
1943 * @param $msg String: message key for page text
1944 * @param $params Array: message parameters
1946 public function showErrorPage( $title, $msg, $params = array() ) {
1947 if ( $this->getTitle() ) {
1948 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1950 $this->setPageTitle( wfMsg( $title ) );
1951 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1952 $this->setRobotPolicy( 'noindex,nofollow' );
1953 $this->setArticleRelated( false );
1954 $this->enableClientCache( false );
1955 $this->mRedirect
= '';
1956 $this->mBodytext
= '';
1958 $this->addWikiMsgArray( $msg, $params );
1960 $this->returnToMain();
1964 * Output a standard permission error page
1966 * @param $errors Array: error message keys
1967 * @param $action String: action that was denied or null if unknown
1969 public function showPermissionsErrorPage( $errors, $action = null ) {
1970 $this->mDebugtext
.= 'Original title: ' .
1971 $this->getTitle()->getPrefixedText() . "\n";
1972 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1973 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1974 $this->setRobotPolicy( 'noindex,nofollow' );
1975 $this->setArticleRelated( false );
1976 $this->enableClientCache( false );
1977 $this->mRedirect
= '';
1978 $this->mBodytext
= '';
1979 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1983 * Display an error page indicating that a given version of MediaWiki is
1984 * required to use it
1986 * @param $version Mixed: the version of MediaWiki needed to use the page
1988 public function versionRequired( $version ) {
1989 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1990 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1991 $this->setRobotPolicy( 'noindex,nofollow' );
1992 $this->setArticleRelated( false );
1993 $this->mBodytext
= '';
1995 $this->addWikiMsg( 'versionrequiredtext', $version );
1996 $this->returnToMain();
2000 * Display an error page noting that a given permission bit is required.
2002 * @param $permission String: key required
2004 public function permissionRequired( $permission ) {
2007 $this->setPageTitle( wfMsg( 'badaccess' ) );
2008 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
2009 $this->setRobotPolicy( 'noindex,nofollow' );
2010 $this->setArticleRelated( false );
2011 $this->mBodytext
= '';
2013 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
2014 User
::getGroupsWithPermission( $permission ) );
2018 $wgLang->commaList( $groups ),
2022 $this->addWikiMsg( 'badaccess-group0' );
2024 $this->returnToMain();
2028 * Produce the stock "please login to use the wiki" page
2030 public function loginToUse() {
2033 if( $wgUser->isLoggedIn() ) {
2034 $this->permissionRequired( 'read' );
2038 $skin = $wgUser->getSkin();
2040 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
2041 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
2042 $this->setRobotPolicy( 'noindex,nofollow' );
2043 $this->setArticleRelated( false );
2045 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
2046 $loginLink = $skin->link(
2048 wfMsgHtml( 'loginreqlink' ),
2050 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
2051 array( 'known', 'noclasses' )
2053 $this->addWikiMsgArray( 'loginreqpagetext', array( $loginLink ), array( 'replaceafter' ) );
2054 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . '-->' );
2056 # Don't return to the main page if the user can't read it
2057 # otherwise we'll end up in a pointless loop
2058 $mainPage = Title
::newMainPage();
2059 if( $mainPage->userCanRead() ) {
2060 $this->returnToMain( null, $mainPage );
2065 * Format a list of error messages
2067 * @param $errors Array of arrays returned by Title::getUserPermissionsErrors
2068 * @param $action String: action that was denied or null if unknown
2069 * @return String: the wikitext error-messages, formatted into a list.
2071 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2072 if ( $action == null ) {
2073 $text = wfMsgNoTrans( 'permissionserrorstext', count( $errors ) ) . "\n\n";
2075 $action_desc = wfMsgNoTrans( "action-$action" );
2076 $text = wfMsgNoTrans(
2077 'permissionserrorstext-withaction',
2083 if ( count( $errors ) > 1 ) {
2084 $text .= '<ul class="permissions-errors">' . "\n";
2086 foreach( $errors as $error ) {
2088 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
2093 $text .= "<div class=\"permissions-errors\">\n" .
2094 call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) .
2102 * Display a page stating that the Wiki is in read-only mode,
2103 * and optionally show the source of the page that the user
2104 * was trying to edit. Should only be called (for this
2105 * purpose) after wfReadOnly() has returned true.
2107 * For historical reasons, this function is _also_ used to
2108 * show the error message when a user tries to edit a page
2109 * they are not allowed to edit. (Unless it's because they're
2110 * blocked, then we show blockedPage() instead.) In this
2111 * case, the second parameter should be set to true and a list
2112 * of reasons supplied as the third parameter.
2114 * @todo Needs to be split into multiple functions.
2116 * @param $source String: source code to show (or null).
2117 * @param $protected Boolean: is this a permissions error?
2118 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
2119 * @param $action String: action that was denied or null if unknown
2121 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
2123 $skin = $wgUser->getSkin();
2125 $this->setRobotPolicy( 'noindex,nofollow' );
2126 $this->setArticleRelated( false );
2128 // If no reason is given, just supply a default "I can't let you do
2129 // that, Dave" message. Should only occur if called by legacy code.
2130 if ( $protected && empty( $reasons ) ) {
2131 $reasons[] = array( 'badaccess-group0' );
2134 if ( !empty( $reasons ) ) {
2135 // Permissions error
2137 $this->setPageTitle( wfMsg( 'viewsource' ) );
2139 wfMsg( 'viewsourcefor', $skin->linkKnown( $this->getTitle() ) )
2142 $this->setPageTitle( wfMsg( 'badaccess' ) );
2144 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2146 // Wiki is read only
2147 $this->setPageTitle( wfMsg( 'readonly' ) );
2148 $reason = wfReadOnlyReason();
2149 $this->wrapWikiMsg( "<div class='mw-readonly-error'>\n$1\n</div>", array( 'readonlytext', $reason ) );
2152 // Show source, if supplied
2153 if( is_string( $source ) ) {
2154 $this->addWikiMsg( 'viewsourcetext' );
2157 'id' => 'wpTextbox1',
2158 'name' => 'wpTextbox1',
2159 'cols' => $wgUser->getOption( 'cols' ),
2160 'rows' => $wgUser->getOption( 'rows' ),
2161 'readonly' => 'readonly'
2163 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
2165 // Show templates used by this article
2166 $skin = $wgUser->getSkin();
2167 $article = new Article( $this->getTitle() );
2168 $this->addHTML( "<div class='templatesUsed'>
2169 {$skin->formatTemplates( $article->getUsedTemplates() )}
2174 # If the title doesn't exist, it's fairly pointless to print a return
2175 # link to it. After all, you just tried editing it and couldn't, so
2176 # what's there to do there?
2177 if( $this->getTitle()->exists() ) {
2178 $this->returnToMain( null, $this->getTitle() );
2183 * Adds JS-based password security checker
2184 * @param $passwordId String ID of input box containing password
2185 * @param $retypeId String ID of input box containing retyped password
2188 public function addPasswordSecurity( $passwordId, $retypeId ) {
2190 'password' => '#' . $passwordId,
2191 'retype' => '#' . $retypeId,
2192 'messages' => array(),
2194 foreach ( array( 'password-strength', 'password-strength-bad', 'password-strength-mediocre',
2195 'password-strength-acceptable', 'password-strength-good', 'password-retype', 'password-retype-mismatch'
2197 $data['messages'][$message] = wfMsg( $message );
2199 $this->addScript( Html
::inlineScript( 'var passwordSecurity=' . FormatJson
::encode( $data ) ) );
2200 $this->addModules( 'mediawiki.legacy.password' );
2203 public function showFatalError( $message ) {
2204 $this->setPageTitle( wfMsg( 'internalerror' ) );
2205 $this->setRobotPolicy( 'noindex,nofollow' );
2206 $this->setArticleRelated( false );
2207 $this->enableClientCache( false );
2208 $this->mRedirect
= '';
2209 $this->mBodytext
= $message;
2212 public function showUnexpectedValueError( $name, $val ) {
2213 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
2216 public function showFileCopyError( $old, $new ) {
2217 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
2220 public function showFileRenameError( $old, $new ) {
2221 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
2224 public function showFileDeleteError( $name ) {
2225 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
2228 public function showFileNotFoundError( $name ) {
2229 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
2233 * Add a "return to" link pointing to a specified title
2235 * @param $title Title to link
2236 * @param $query String: query string
2237 * @param $text String text of the link (input is not escaped)
2239 public function addReturnTo( $title, $query = array(), $text = null ) {
2241 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL() ) );
2244 $wgUser->getSkin()->link( $title, $text, array(), $query )
2246 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2250 * Add a "return to" link pointing to a specified title,
2251 * or the title indicated in the request, or else the main page
2253 * @param $unused No longer used
2254 * @param $returnto Title or String to return to
2255 * @param $returntoquery String: query string for the return to link
2257 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2260 if ( $returnto == null ) {
2261 $returnto = $wgRequest->getText( 'returnto' );
2264 if ( $returntoquery == null ) {
2265 $returntoquery = $wgRequest->getText( 'returntoquery' );
2268 if ( $returnto === '' ) {
2269 $returnto = Title
::newMainPage();
2272 if ( is_object( $returnto ) ) {
2273 $titleObj = $returnto;
2275 $titleObj = Title
::newFromText( $returnto );
2277 if ( !is_object( $titleObj ) ) {
2278 $titleObj = Title
::newMainPage();
2281 $this->addReturnTo( $titleObj, $returntoquery );
2285 * @param $sk Skin The given Skin
2286 * @param $includeStyle Boolean: unused
2287 * @return String: The doctype, opening <html>, and head element.
2289 public function headElement( Skin
$sk, $includeStyle = true ) {
2290 global $wgOutputEncoding, $wgMimeType;
2291 global $wgUseTrackbacks, $wgHtml5;
2292 global $wgUser, $wgRequest, $wgLang;
2294 if ( $sk->commonPrintStylesheet() ) {
2295 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2297 $sk->setupUserCss( $this );
2300 $ret = Html
::htmlHeader( array( 'lang' => $lang->getCode(), 'dir' => $lang->getDir() ) );
2302 if ( $this->getHTMLTitle() == '' ) {
2303 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ) );
2306 $openHead = Html
::openElement( 'head' );
2308 # Don't bother with the newline if $head == ''
2309 $ret .= "$openHead\n";
2313 # More succinct than <meta http-equiv=Content-Type>, has the
2315 $ret .= Html
::element( 'meta', array( 'charset' => $wgOutputEncoding ) ) . "\n";
2317 $this->addMeta( 'http:Content-Type', "$wgMimeType; charset=$wgOutputEncoding" );
2320 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2322 $ret .= implode( "\n", array(
2323 $this->getHeadLinks( $sk ),
2324 $this->buildCssLinks( $sk ),
2325 $this->getHeadItems()
2328 if ( $wgUseTrackbacks && $this->isArticleRelated() ) {
2329 $ret .= $this->getTitle()->trackbackRDF();
2332 $closeHead = Html
::closeElement( 'head' );
2334 $ret .= "$closeHead\n";
2337 $bodyAttrs = array();
2339 # Crazy edit-on-double-click stuff
2340 $action = $wgRequest->getVal( 'action', 'view' );
2343 $this->getTitle()->getNamespace() != NS_SPECIAL
&&
2344 !in_array( $action, array( 'edit', 'submit' ) ) &&
2345 $wgUser->getOption( 'editondblclick' )
2348 $bodyAttrs['ondblclick'] = "document.location = '" . Xml
::escapeJsString( $this->getTitle()->getEditURL() ) . "'";
2352 $dir = wfUILang()->getDir();
2353 $bodyAttrs['class'] = "mediawiki $dir";
2355 if ( $wgLang->capitalizeAllNouns() ) {
2356 # A <body> class is probably not the best way to do this . . .
2357 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2359 $bodyAttrs['class'] .= ' ' . $sk->getPageClasses( $this->getTitle() );
2360 $bodyAttrs['class'] .= ' skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2362 $sk->addToBodyAttributes( $this, $bodyAttrs ); // Allow skins to add body attributes they need
2363 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2365 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2371 * Get a ResourceLoader object associated with this OutputPage
2373 * @return ResourceLoader
2375 public function getResourceLoader() {
2376 if ( is_null( $this->mResourceLoader
) ) {
2377 $this->mResourceLoader
= new ResourceLoader();
2379 return $this->mResourceLoader
;
2385 * @param $modules Array/string with the module name
2386 * @param $only String ResourceLoaderModule TYPE_ class constant
2387 * @param $useESI boolean
2388 * @return string html <script> and <style> tags
2390 protected function makeResourceLoaderLink( Skin
$skin, $modules, $only, $useESI = false ) {
2391 global $wgUser, $wgLang, $wgLoadScript, $wgResourceLoaderUseESI,
2392 $wgResourceLoaderInlinePrivateModules, $wgRequest;
2393 // Lazy-load ResourceLoader
2394 // TODO: Should this be a static function of ResourceLoader instead?
2395 // TODO: Divide off modules starting with "user", and add the user parameter to them
2397 'lang' => $wgLang->getCode(),
2398 'debug' => ResourceLoader
::inDebugMode() ?
'true' : 'false',
2399 'skin' => $skin->getSkinName(),
2402 // Propagate printable and handheld parameters if present
2403 if ( $this->isPrintable() ) {
2404 $baseQuery['printable'] = 1;
2406 if ( $wgRequest->getBool( 'handheld' ) ) {
2407 $baseQuery['handheld'] = 1;
2410 if ( !count( $modules ) ) {
2414 if ( count( $modules ) > 1 ) {
2415 // Remove duplicate module requests
2416 $modules = array_unique( (array) $modules );
2417 // Sort module names so requests are more uniform
2420 if ( ResourceLoader
::inDebugMode() ) {
2421 // Recursively call us for every item
2423 foreach ( $modules as $name ) {
2424 $links .= $this->makeResourceLoaderLink( $skin, $name, $only, $useESI );
2430 // Create keyed-by-group list of module objects from modules list
2432 $resourceLoader = $this->getResourceLoader();
2433 foreach ( (array) $modules as $name ) {
2434 $module = $resourceLoader->getModule( $name );
2435 # Check that we're allowed to include this module on this page
2436 if ( ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2437 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2438 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2439 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2445 $group = $module->getGroup();
2446 if ( !isset( $groups[$group] ) ) {
2447 $groups[$group] = array();
2449 $groups[$group][$name] = $module;
2453 foreach ( $groups as $group => $modules ) {
2454 $query = $baseQuery;
2455 // Special handling for user-specific groups
2456 if ( ( $group === 'user' ||
$group === 'private' ) && $wgUser->isLoggedIn() ) {
2457 $query['user'] = $wgUser->getName();
2460 // Create a fake request based on the one we are about to make so modules return
2461 // correct timestamp and emptiness data
2462 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2463 // Drop modules that know they're empty
2464 foreach ( $modules as $key => $module ) {
2465 if ( $module->isKnownEmpty( $context ) ) {
2466 unset( $modules[$key] );
2469 // If there are no modules left, skip this group
2470 if ( $modules === array() ) {
2474 $query['modules'] = implode( '|', array_keys( $modules ) );
2476 // Support inlining of private modules if configured as such
2477 if ( $group === 'private' && $wgResourceLoaderInlinePrivateModules ) {
2478 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2479 $links .= Html
::inlineStyle(
2480 $resourceLoader->makeModuleResponse( $context, $modules )
2483 $links .= Html
::inlineScript(
2484 ResourceLoader
::makeLoaderConditionalScript(
2485 $resourceLoader->makeModuleResponse( $context, $modules )
2491 // Special handling for the user group; because users might change their stuff
2492 // on-wiki like user pages, or user preferences; we need to find the highest
2493 // timestamp of these user-changable modules so we can ensure cache misses on change
2494 // This should NOT be done for the site group (bug 27564) because anons get that too
2495 // and we shouldn't be putting timestamps in Squid-cached HTML
2496 if ( $group === 'user' ) {
2497 // Get the maximum timestamp
2499 foreach ( $modules as $module ) {
2500 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2502 // Add a version parameter so cache will break when things change
2503 $query['version'] = wfTimestamp( TS_ISO_8601_BASIC
, $timestamp );
2505 // Make queries uniform in order
2508 $url = wfAppendQuery( $wgLoadScript, $query );
2509 if ( $useESI && $wgResourceLoaderUseESI ) {
2510 $esi = Xml
::element( 'esi:include', array( 'src' => $url ) );
2511 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2512 $link = Html
::inlineStyle( $esi );
2514 $link = Html
::inlineScript( $esi );
2517 // Automatically select style/script elements
2518 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2519 $link = Html
::linkedStyle( wfAppendQuery( $wgLoadScript, $query ) );
2521 $link = Html
::linkedScript( wfAppendQuery( $wgLoadScript, $query ) );
2525 if( $group == 'noscript' ){
2526 $links .= Html
::rawElement( 'noscript', array(), $link ) . "\n";
2528 $links .= $link . "\n";
2535 * Gets the global variables and mScripts; also adds userjs to the end if
2536 * enabled. Despite the name, these scripts are no longer put in the
2537 * <head> but at the bottom of the <body>
2539 * @param $sk Skin object to use
2540 * @return String: HTML fragment
2542 function getHeadScripts( Skin
$sk ) {
2543 global $wgUser, $wgRequest, $wgUseSiteJs, $wgAllowUserJs;
2545 // Startup - this will immediately load jquery and mediawiki modules
2546 $scripts = $this->makeResourceLoaderLink( $sk, 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
, true );
2548 // Script and Messages "only" requests
2549 $scripts .= $this->makeResourceLoaderLink( $sk, $this->getModuleScripts( true ), ResourceLoaderModule
::TYPE_SCRIPTS
);
2550 $scripts .= $this->makeResourceLoaderLink( $sk, $this->getModuleMessages( true ), ResourceLoaderModule
::TYPE_MESSAGES
);
2552 // Modules requests - let the client calculate dependencies and batch requests as it likes
2554 if ( $this->getModules( true ) ) {
2555 $loader = Xml
::encodeJsCall( 'mw.loader.load', array( $this->getModules( true ) ) ) .
2556 Xml
::encodeJsCall( 'mw.loader.go', array() );
2559 $scripts .= Html
::inlineScript(
2560 ResourceLoader
::makeLoaderConditionalScript(
2561 ResourceLoader
::makeConfigSetScript( $this->getJSVars() ) . $loader
2566 $scripts .= "\n" . $this->mScripts
;
2568 $userScripts = array( 'user.options' );
2570 // Add site JS if enabled
2571 if ( $wgUseSiteJs ) {
2572 $scripts .= $this->makeResourceLoaderLink( $sk, 'site', ResourceLoaderModule
::TYPE_SCRIPTS
);
2573 if( $wgUser->isLoggedIn() ){
2574 $userScripts[] = 'user.groups';
2578 // Add user JS if enabled
2579 if ( $wgAllowUserJs && $wgUser->isLoggedIn() ) {
2580 $action = $wgRequest->getVal( 'action', 'view' );
2581 if( $this->mTitle
&& $this->mTitle
->isJsSubpage() && $sk->userCanPreview( $action ) ) {
2582 # XXX: additional security check/prompt?
2583 $scripts .= Html
::inlineScript( "\n" . $wgRequest->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2585 # FIXME: this means that User:Me/Common.js doesn't load when previewing
2586 # User:Me/Vector.js, and vice versa (bug26283)
2587 $userScripts[] = 'user';
2590 $scripts .= $this->makeResourceLoaderLink( $sk, $userScripts, ResourceLoaderModule
::TYPE_SCRIPTS
);
2596 * Get an array containing global JS variables
2598 * Do not add things here which can be evaluated in
2599 * ResourceLoaderStartupScript - in other words, without state.
2600 * You will only be adding bloat to the page and causing page caches to
2601 * have to be purged on configuration changes.
2603 protected function getJSVars() {
2604 global $wgUser, $wgRequest, $wgUseAjax, $wgEnableMWSuggest, $wgContLang;
2606 $title = $this->getTitle();
2607 $ns = $title->getNamespace();
2608 $nsname = MWNamespace
::exists( $ns ) ? MWNamespace
::getCanonicalName( $ns ) : $title->getNsText();
2609 if ( $ns == NS_SPECIAL
) {
2610 $parts = SpecialPage
::resolveAliasWithSubpage( $title->getDBkey() );
2611 $canonicalName = $parts[0];
2613 $canonicalName = false; # bug 21115
2617 'wgCanonicalNamespace' => $nsname,
2618 'wgCanonicalSpecialPageName' => $canonicalName,
2619 'wgNamespaceNumber' => $title->getNamespace(),
2620 'wgPageName' => $title->getPrefixedDBKey(),
2621 'wgTitle' => $title->getText(),
2622 'wgCurRevisionId' => $title->getLatestRevID(),
2623 'wgArticleId' => $title->getArticleId(),
2624 'wgIsArticle' => $this->isArticle(),
2625 'wgAction' => $wgRequest->getText( 'action', 'view' ),
2626 'wgUserName' => $wgUser->isAnon() ?
null : $wgUser->getName(),
2627 'wgUserGroups' => $wgUser->getEffectiveGroups(),
2628 'wgCategories' => $this->getCategories(),
2629 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
2631 if ( $wgContLang->hasVariants() ) {
2632 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
2634 foreach ( $title->getRestrictionTypes() as $type ) {
2635 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
2637 if ( $wgUseAjax && $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ) {
2638 $vars['wgSearchNamespaces'] = SearchEngine
::userNamespaces( $wgUser );
2641 // Allow extensions to add their custom variables to the global JS variables
2642 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars ) );
2648 * Add default \<meta\> tags
2650 protected function addDefaultMeta() {
2651 global $wgVersion, $wgHtml5;
2653 static $called = false;
2655 # Don't run this twice
2661 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); // bug 15835
2663 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
2665 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
2666 if( $p !== 'index,follow' ) {
2667 // http://www.robotstxt.org/wc/meta-user.html
2668 // Only show if it's different from the default robots policy
2669 $this->addMeta( 'robots', $p );
2672 if ( count( $this->mKeywords
) > 0 ) {
2674 "/<.*?" . ">/" => '',
2680 array_keys( $strip ),
2681 array_values( $strip ),
2682 implode( ',', $this->mKeywords
)
2689 * @return string HTML tag links to be put in the header.
2691 public function getHeadLinks( Skin
$sk ) {
2694 // Ideally this should happen earlier, somewhere. :P
2695 $this->addDefaultMeta();
2699 foreach ( $this->mMetatags
as $tag ) {
2700 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
2702 $tag[0] = substr( $tag[0], 5 );
2706 $tags[] = Html
::element( 'meta',
2709 'content' => $tag[1]
2713 foreach ( $this->mLinktags
as $tag ) {
2714 $tags[] = Html
::element( 'link', $tag );
2718 foreach( $this->getSyndicationLinks() as $format => $link ) {
2719 # Use the page name for the title (accessed through $wgTitle since
2720 # there's no other way). In principle, this could lead to issues
2721 # with having the same name for different feeds corresponding to
2722 # the same page, but we can't avoid that at this low a level.
2724 $tags[] = $this->feedLink(
2727 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
2728 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )
2732 # Recent changes feed should appear on every page (except recentchanges,
2733 # that would be redundant). Put it after the per-page feed to avoid
2734 # changing existing behavior. It's still available, probably via a
2735 # menu in your browser. Some sites might have a different feed they'd
2736 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
2737 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
2738 # If so, use it instead.
2740 global $wgOverrideSiteFeed, $wgSitename, $wgAdvertisedFeedTypes;
2741 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
2743 if ( $wgOverrideSiteFeed ) {
2744 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
2745 $tags[] = $this->feedLink(
2747 htmlspecialchars( $feedUrl ),
2748 wfMsg( "site-{$type}-feed", $wgSitename )
2751 } elseif ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
2752 foreach ( $wgAdvertisedFeedTypes as $format ) {
2753 $tags[] = $this->feedLink(
2755 $rctitle->getLocalURL( "feed={$format}" ),
2756 wfMsg( "site-{$format}-feed", $wgSitename ) # For grep: 'site-rss-feed', 'site-atom-feed'.
2761 return implode( "\n", $tags );
2765 * Generate a <link rel/> for a feed.
2767 * @param $type String: feed type
2768 * @param $url String: URL to the feed
2769 * @param $text String: value of the "title" attribute
2770 * @return String: HTML fragment
2772 private function feedLink( $type, $url, $text ) {
2773 return Html
::element( 'link', array(
2774 'rel' => 'alternate',
2775 'type' => "application/$type+xml",
2782 * Add a local or specified stylesheet, with the given media options.
2783 * Meant primarily for internal use...
2785 * @param $style String: URL to the file
2786 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
2787 * @param $condition String: for IE conditional comments, specifying an IE version
2788 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
2790 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
2792 // Even though we expect the media type to be lowercase, but here we
2793 // force it to lowercase to be safe.
2795 $options['media'] = $media;
2798 $options['condition'] = $condition;
2801 $options['dir'] = $dir;
2803 $this->styles
[$style] = $options;
2807 * Adds inline CSS styles
2808 * @param $style_css Mixed: inline CSS
2810 public function addInlineStyle( $style_css ){
2811 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
2815 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
2816 * These will be applied to various media & IE conditionals.
2817 * @param $sk Skin object
2819 public function buildCssLinks( $sk ) {
2821 // Add ResourceLoader styles
2822 // Split the styles into four groups
2823 $styles = array( 'other' => array(), 'user' => array(), 'site' => array(), 'private' => array(), 'noscript' => array() );
2824 $resourceLoader = $this->getResourceLoader();
2825 foreach ( $this->getModuleStyles() as $name ) {
2826 $group = $resourceLoader->getModule( $name )->getGroup();
2827 // Modules in groups named "other" or anything different than "user", "site" or "private"
2828 // will be placed in the "other" group
2829 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
2832 // We want site, private and user styles to override dynamically added styles from modules, but we want
2833 // dynamically added styles to override statically added styles from other modules. So the order
2834 // has to be other, dynamic, site, private, user
2835 // Add statically added styles for other modules
2836 $ret .= $this->makeResourceLoaderLink( $sk, $styles['other'], ResourceLoaderModule
::TYPE_STYLES
);
2837 // Add normal styles added through addStyle()/addInlineStyle() here
2838 $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
2839 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
2840 // We use a <meta> tag with a made-up name for this because that's valid HTML
2841 $ret .= Html
::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) ) . "\n";
2843 // Add site, private and user styles
2844 // 'private' at present only contains user.options, so put that before 'user'
2845 // Any future private modules will likely have a similar user-specific character
2846 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
2847 $ret .= $this->makeResourceLoaderLink( $sk, $styles[$group],
2848 ResourceLoaderModule
::TYPE_STYLES
2854 public function buildCssLinksArray() {
2856 foreach( $this->styles
as $file => $options ) {
2857 $link = $this->styleLink( $file, $options );
2859 $links[$file] = $link;
2866 * Generate \<link\> tags for stylesheets
2868 * @param $style String: URL to the file
2869 * @param $options Array: option, can contain 'condition', 'dir', 'media'
2871 * @return String: HTML fragment
2873 protected function styleLink( $style, $options ) {
2874 if( isset( $options['dir'] ) ) {
2875 $siteDir = wfUILang()->getDir();
2876 if( $siteDir != $options['dir'] ) {
2881 if( isset( $options['media'] ) ) {
2882 $media = self
::transformCssMedia( $options['media'] );
2883 if( is_null( $media ) ) {
2890 if( substr( $style, 0, 1 ) == '/' ||
2891 substr( $style, 0, 5 ) == 'http:' ||
2892 substr( $style, 0, 6 ) == 'https:' ) {
2895 global $wgStylePath, $wgStyleVersion;
2896 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
2899 $link = Html
::linkedStyle( $url, $media );
2901 if( isset( $options['condition'] ) ) {
2902 $condition = htmlspecialchars( $options['condition'] );
2903 $link = "<!--[if $condition]>$link<![endif]-->";
2909 * Transform "media" attribute based on request parameters
2911 * @param $media String: current value of the "media" attribute
2912 * @return String: modified value of the "media" attribute
2914 public static function transformCssMedia( $media ) {
2915 global $wgRequest, $wgHandheldForIPhone;
2917 // Switch in on-screen display for media testing
2919 'printable' => 'print',
2920 'handheld' => 'handheld',
2922 foreach( $switches as $switch => $targetMedia ) {
2923 if( $wgRequest->getBool( $switch ) ) {
2924 if( $media == $targetMedia ) {
2926 } elseif( $media == 'screen' ) {
2932 // Expand longer media queries as iPhone doesn't grok 'handheld'
2933 if( $wgHandheldForIPhone ) {
2934 $mediaAliases = array(
2935 'screen' => 'screen and (min-device-width: 481px)',
2936 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
2939 if( isset( $mediaAliases[$media] ) ) {
2940 $media = $mediaAliases[$media];
2948 * Turn off regular page output and return an error reponse
2949 * for when rate limiting has triggered.
2951 public function rateLimited() {
2952 $this->setPageTitle( wfMsg( 'actionthrottled' ) );
2953 $this->setRobotPolicy( 'noindex,follow' );
2954 $this->setArticleRelated( false );
2955 $this->enableClientCache( false );
2956 $this->mRedirect
= '';
2958 $this->setStatusCode( 503 );
2959 $this->addWikiMsg( 'actionthrottledtext' );
2961 $this->returnToMain( null, $this->getTitle() );
2965 * Show a warning about slave lag
2967 * If the lag is higher than $wgSlaveLagCritical seconds,
2968 * then the warning is a bit more obvious. If the lag is
2969 * lower than $wgSlaveLagWarning, then no warning is shown.
2971 * @param $lag Integer: slave lag
2973 public function showLagWarning( $lag ) {
2974 global $wgSlaveLagWarning, $wgSlaveLagCritical, $wgLang;
2975 if( $lag >= $wgSlaveLagWarning ) {
2976 $message = $lag < $wgSlaveLagCritical
2979 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2980 $this->wrapWikiMsg( "$wrap\n", array( $message, $wgLang->formatNum( $lag ) ) );
2985 * Add a wikitext-formatted message to the output.
2986 * This is equivalent to:
2988 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2990 public function addWikiMsg( /*...*/ ) {
2991 $args = func_get_args();
2992 $name = array_shift( $args );
2993 $this->addWikiMsgArray( $name, $args );
2997 * Add a wikitext-formatted message to the output.
2998 * Like addWikiMsg() except the parameters are taken as an array
2999 * instead of a variable argument list.
3001 * $options is passed through to wfMsgExt(), see that function for details.
3003 public function addWikiMsgArray( $name, $args, $options = array() ) {
3004 $options[] = 'parse';
3005 $text = wfMsgExt( $name, $options, $args );
3006 $this->addHTML( $text );
3010 * This function takes a number of message/argument specifications, wraps them in
3011 * some overall structure, and then parses the result and adds it to the output.
3013 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3014 * on. The subsequent arguments may either be strings, in which case they are the
3015 * message names, or arrays, in which case the first element is the message name,
3016 * and subsequent elements are the parameters to that message.
3018 * The special named parameter 'options' in a message specification array is passed
3019 * through to the $options parameter of wfMsgExt().
3021 * Don't use this for messages that are not in users interface language.
3025 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3029 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . "\n</div>" );
3031 * The newline after opening div is needed in some wikitext. See bug 19226.
3033 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3034 $msgSpecs = func_get_args();
3035 array_shift( $msgSpecs );
3036 $msgSpecs = array_values( $msgSpecs );
3038 foreach ( $msgSpecs as $n => $spec ) {
3040 if ( is_array( $spec ) ) {
3042 $name = array_shift( $args );
3043 if ( isset( $args['options'] ) ) {
3044 $options = $args['options'];
3045 unset( $args['options'] );
3051 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
3053 $this->addWikiText( $s );
3057 * Include jQuery core. Use this to avoid loading it multiple times
3058 * before we get a usable script loader.
3060 * @param $modules Array: list of jQuery modules which should be loaded
3061 * @return Array: the list of modules which were not loaded.
3063 * @deprecated since 1.17
3065 public function includeJQuery( $modules = array() ) {