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 classes 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) handles 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 output 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 into 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 cached version with the server version. Client sends
80 * headers If-Match and If-None-Match containing its locally cached 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();
126 var $mImageTimeKeys = array();
128 # What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
129 # @see ResourceLoaderModule::$origin
130 # ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
131 protected $mAllowedModules = array(
132 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
136 * @EasterEgg I just love the name for this self documenting variable.
139 var $mDoNothing = false;
142 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
145 * Should be private. Has get/set methods properly documented.
146 * Stores "article flag" toggle.
148 var $mIsArticleRelated = true;
150 /// lazy initialised, use parserOptions()
151 protected $mParserOptions = null;
154 * Handles the atom / rss links.
155 * We probably only support atom in 2011.
156 * Looks like a private variable.
157 * @see $wgAdvertisedFeedTypes
159 var $mFeedLinks = array();
161 // Gwicke work on squid caching? Roughly from 2003.
162 var $mEnableClientCache = true;
165 * Flag if output should only contain the body of the article.
168 var $mArticleBodyOnly = false;
170 var $mNewSectionLink = false;
171 var $mHideNewSectionLink = false;
174 * Comes from the parser. This was probably made to load CSS/JS only
175 * if we had <gallery>. Used directly in CategoryPage.php
176 * Looks like resource loader can replace this.
178 var $mNoGallery = false;
180 // should be private.
181 var $mPageTitleActionText = '';
182 var $mParseWarnings = array();
184 // Cache stuff. Looks like mEnableClientCache
185 var $mSquidMaxage = 0;
188 var $mPreventClickjacking = true;
190 /// should be private. To include the variable {{REVISIONID}}
191 var $mRevisionId = null;
193 /// Stores a Title object (of the current page).
194 protected $mTitle = null;
196 /// Stores a User object (the one the page is being rendered for)
197 protected $mUser = null;
200 * An array of stylesheet filenames (relative from skins path), with options
201 * for CSS media, IE conditions, and RTL/LTR direction.
202 * For internal use; add settings in the skin via $this->addStyle()
204 * Style again! This seems like a code duplication since we already have
205 * mStyles. This is what makes OpenSource amazing.
207 var $styles = array();
210 * Whether jQuery is already handled.
212 protected $mJQueryDone = false;
214 private $mIndexPolicy = 'index';
215 private $mFollowPolicy = 'follow';
216 private $mVaryHeader = array(
217 'Accept-Encoding' => array( 'list-contains=gzip' ),
222 * Redirect to $url rather than displaying the normal page
224 * @param $url String: URL
225 * @param $responsecode String: HTTP status code
227 public function redirect( $url, $responsecode = '302' ) {
228 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
229 $this->mRedirect
= str_replace( "\n", '', $url );
230 $this->mRedirectCode
= $responsecode;
234 * Get the URL to redirect to, or an empty string if not redirect URL set
238 public function getRedirect() {
239 return $this->mRedirect
;
243 * Set the HTTP status code to send with the output.
245 * @param $statusCode Integer
247 public function setStatusCode( $statusCode ) {
248 $this->mStatusCode
= $statusCode;
252 * Add a new <meta> tag
253 * To add an http-equiv meta tag, precede the name with "http:"
255 * @param $name String tag name
256 * @param $val String tag value
258 function addMeta( $name, $val ) {
259 array_push( $this->mMetatags
, array( $name, $val ) );
263 * Add a keyword or a list of keywords in the page header
265 * @param $text String or array of strings
267 function addKeyword( $text ) {
268 if( is_array( $text ) ) {
269 $this->mKeywords
= array_merge( $this->mKeywords
, $text );
271 array_push( $this->mKeywords
, $text );
276 * Add a new \<link\> tag to the page header
278 * @param $linkarr Array: associative array of attributes.
280 function addLink( $linkarr ) {
281 array_push( $this->mLinktags
, $linkarr );
285 * Add a new \<link\> with "rel" attribute set to "meta"
287 * @param $linkarr Array: associative array mapping attribute names to their
288 * values, both keys and values will be escaped, and the
289 * "rel" attribute will be automatically added
291 function addMetadataLink( $linkarr ) {
292 $linkarr['rel'] = $this->getMetadataAttribute();
293 $this->addLink( $linkarr );
297 * Get the value of the "rel" attribute for metadata links
301 private function getMetadataAttribute() {
302 # note: buggy CC software only reads first "meta" link
303 static $haveMeta = false;
305 return 'alternate meta';
313 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
315 * @param $script String: raw HTML
317 function addScript( $script ) {
318 $this->mScripts
.= $script . "\n";
322 * Register and add a stylesheet from an extension directory.
324 * @param $url String path to sheet. Provide either a full url (beginning
325 * with 'http', etc) or a relative path from the document root
326 * (beginning with '/'). Otherwise it behaves identically to
327 * addStyle() and draws from the /skins folder.
329 public function addExtensionStyle( $url ) {
330 array_push( $this->mExtStyles
, $url );
334 * Get all styles added by extensions
338 function getExtStyle() {
339 return $this->mExtStyles
;
343 * Add a JavaScript file out of skins/common, or a given relative path.
345 * @param $file String: filename in skins/common or complete on-server path
347 * @param $version String: style version of the file. Defaults to $wgStyleVersion
349 public function addScriptFile( $file, $version = null ) {
350 global $wgStylePath, $wgStyleVersion;
351 // See if $file parameter is an absolute URL or begins with a slash
352 if( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
355 $path = "{$wgStylePath}/common/{$file}";
357 if ( is_null( $version ) )
358 $version = $wgStyleVersion;
359 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
363 * Add a self-contained script tag with the given contents
365 * @param $script String: JavaScript text, no <script> tags
367 public function addInlineScript( $script ) {
368 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
372 * Get all registered JS and CSS tags for the header.
376 function getScript() {
377 return $this->mScripts
. $this->getHeadItems();
381 * Filter an array of modules to remove insufficiently trustworthy members, and modules
382 * which are no longer registered (eg a page is cached before an extension is disabled)
383 * @param $modules Array
386 protected function filterModules( $modules, $type = ResourceLoaderModule
::TYPE_COMBINED
){
387 $resourceLoader = $this->getResourceLoader();
388 $filteredModules = array();
389 foreach( $modules as $val ){
390 $module = $resourceLoader->getModule( $val );
391 if( $module instanceof ResourceLoaderModule
392 && $module->getOrigin() <= $this->getAllowedModules( $type ) )
394 $filteredModules[] = $val;
397 return $filteredModules;
401 * Get the list of modules to include on this page
403 * @param $filter Bool whether to filter out insufficiently trustworthy modules
404 * @return Array of module names
406 public function getModules( $filter = false, $param = 'mModules' ) {
407 $modules = array_values( array_unique( $this->$param ) );
409 ?
$this->filterModules( $modules )
414 * Add one or more modules recognized by the resource loader. Modules added
415 * through this function will be loaded by the resource loader when the
418 * @param $modules Mixed: module name (string) or array of module names
420 public function addModules( $modules ) {
421 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
425 * Get the list of module JS to include on this page
426 * @return array of module names
428 public function getModuleScripts( $filter = false ) {
429 return $this->getModules( $filter, 'mModuleScripts' );
433 * Add only JS of one or more modules recognized by the resource loader. Module
434 * scripts 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 addModuleScripts( $modules ) {
440 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
444 * Get the list of module CSS to include on this page
446 * @return Array of module names
448 public function getModuleStyles( $filter = false ) {
449 return $this->getModules( $filter, 'mModuleStyles' );
453 * Add only CSS of one or more modules recognized by the resource loader. Module
454 * styles added through this function will be loaded by the resource loader when
457 * @param $modules Mixed: module name (string) or array of module names
459 public function addModuleStyles( $modules ) {
460 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
464 * Get the list of module messages to include on this page
466 * @return Array of module names
468 public function getModuleMessages( $filter = false ) {
469 return $this->getModules( $filter, 'mModuleMessages' );
473 * Add only messages of one or more modules recognized by the resource loader.
474 * Module messages added through this function will be loaded by the resource
475 * loader when the page loads.
477 * @param $modules Mixed: module name (string) or array of module names
479 public function addModuleMessages( $modules ) {
480 $this->mModuleMessages
= array_merge( $this->mModuleMessages
, (array)$modules );
484 * Get all header items in a string
488 function getHeadItems() {
490 foreach ( $this->mHeadItems
as $item ) {
497 * Add or replace an header item to the output
499 * @param $name String: item name
500 * @param $value String: raw HTML
502 public function addHeadItem( $name, $value ) {
503 $this->mHeadItems
[$name] = $value;
507 * Check if the header item $name is already set
509 * @param $name String: item name
512 public function hasHeadItem( $name ) {
513 return isset( $this->mHeadItems
[$name] );
517 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
519 * @param $tag String: value of "ETag" header
521 function setETag( $tag ) {
526 * Set whether the output should only contain the body of the article,
527 * without any skin, sidebar, etc.
528 * Used e.g. when calling with "action=render".
530 * @param $only Boolean: whether to output only the body of the article
532 public function setArticleBodyOnly( $only ) {
533 $this->mArticleBodyOnly
= $only;
537 * Return whether the output will contain only the body of the article
541 public function getArticleBodyOnly() {
542 return $this->mArticleBodyOnly
;
546 * checkLastModified tells the client to use the client-cached page if
547 * possible. If sucessful, the OutputPage is disabled so that
548 * any future call to OutputPage->output() have no effect.
550 * Side effect: sets mLastModified for Last-Modified header
552 * @return Boolean: true iff cache-ok headers was sent.
554 public function checkLastModified( $timestamp ) {
555 global $wgCachePages, $wgCacheEpoch, $wgRequest;
557 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
558 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
561 if( !$wgCachePages ) {
562 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
565 if( $this->getUser()->getOption( 'nocache' ) ) {
566 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
570 $timestamp = wfTimestamp( TS_MW
, $timestamp );
571 $modifiedTimes = array(
572 'page' => $timestamp,
573 'user' => $this->getUser()->getTouched(),
574 'epoch' => $wgCacheEpoch
576 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
578 $maxModified = max( $modifiedTimes );
579 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
581 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
582 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
588 foreach ( $modifiedTimes as $name => $value ) {
589 if ( $info !== '' ) {
592 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
595 # IE sends sizes after the date like this:
596 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
597 # this breaks strtotime().
598 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
600 wfSuppressWarnings(); // E_STRICT system time bitching
601 $clientHeaderTime = strtotime( $clientHeader );
603 if ( !$clientHeaderTime ) {
604 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
607 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
609 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
610 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
611 wfDebug( __METHOD__
. ": effective Last-Modified: " .
612 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
613 if( $clientHeaderTime < $maxModified ) {
614 wfDebug( __METHOD__
. ": STALE, $info\n", false );
619 # Give a 304 response code and disable body output
620 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
621 ini_set( 'zlib.output_compression', 0 );
622 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
623 $this->sendCacheControl();
626 // Don't output a compressed blob when using ob_gzhandler;
627 // it's technically against HTTP spec and seems to confuse
628 // Firefox when the response gets split over two packets.
629 wfClearOutputBuffers();
635 * Override the last modified timestamp
637 * @param $timestamp String: new timestamp, in a format readable by
640 public function setLastModified( $timestamp ) {
641 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
645 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
647 * @param $policy String: the literal string to output as the contents of
648 * the meta tag. Will be parsed according to the spec and output in
652 public function setRobotPolicy( $policy ) {
653 $policy = Article
::formatRobotPolicy( $policy );
655 if( isset( $policy['index'] ) ) {
656 $this->setIndexPolicy( $policy['index'] );
658 if( isset( $policy['follow'] ) ) {
659 $this->setFollowPolicy( $policy['follow'] );
664 * Set the index policy for the page, but leave the follow policy un-
667 * @param $policy string Either 'index' or 'noindex'.
670 public function setIndexPolicy( $policy ) {
671 $policy = trim( $policy );
672 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
673 $this->mIndexPolicy
= $policy;
678 * Set the follow policy for the page, but leave the index policy un-
681 * @param $policy String: either 'follow' or 'nofollow'.
684 public function setFollowPolicy( $policy ) {
685 $policy = trim( $policy );
686 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
687 $this->mFollowPolicy
= $policy;
692 * Set the new value of the "action text", this will be added to the
693 * "HTML title", separated from it with " - ".
695 * @param $text String: new value of the "action text"
697 public function setPageTitleActionText( $text ) {
698 $this->mPageTitleActionText
= $text;
702 * Get the value of the "action text"
706 public function getPageTitleActionText() {
707 if ( isset( $this->mPageTitleActionText
) ) {
708 return $this->mPageTitleActionText
;
713 * "HTML title" means the contents of <title>.
714 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
716 public function setHTMLTitle( $name ) {
717 $this->mHTMLtitle
= $name;
721 * Return the "HTML title", i.e. the content of the <title> tag.
725 public function getHTMLTitle() {
726 return $this->mHTMLtitle
;
730 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
731 * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
732 * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
733 * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
735 public function setPageTitle( $name ) {
736 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
737 # but leave "<i>foobar</i>" alone
738 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
739 $this->mPagetitle
= $nameWithTags;
741 # change "<i>foo&bar</i>" to "foo&bar"
742 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer
::stripAllTags( $nameWithTags ) ) );
746 * Return the "page title", i.e. the content of the \<h1\> tag.
750 public function getPageTitle() {
751 return $this->mPagetitle
;
755 * Set the Title object to use
757 * @param $t Title object
759 public function setTitle( $t ) {
764 * Get the Title object used in this instance
768 public function getTitle() {
769 if ( $this->mTitle
instanceof Title
) {
770 return $this->mTitle
;
772 wfDebug( __METHOD__
. " called and \$mTitle is null. Return \$wgTitle for sanity\n" );
779 * Set the User object to use
781 * @param $u User object
783 public function setUser( $u ) {
788 * Get the User object used in this instance
792 public function getUser() {
793 if ( !isset($this->mUser
) ) {
794 wfDebug( __METHOD__
. " called and \$mUser is null. Return \$wgUser for sanity\n" );
802 * Get the Skin object used to render this instance
806 public function getSkin() {
807 // For now we'll just proxy to the user. In the future a saner location for
808 // organizing what skin to use may be chosen
809 return $this->getUser()->getSkin();
813 * Replace the subtile with $str
815 * @param $str String: new value of the subtitle
817 public function setSubtitle( $str ) {
818 $this->mSubtitle
= /*$this->parse(*/ $str /*)*/; // @bug 2514
822 * Add $str to the subtitle
824 * @param $str String to add to the subtitle
826 public function appendSubtitle( $str ) {
827 $this->mSubtitle
.= /*$this->parse(*/ $str /*)*/; // @bug 2514
835 public function getSubtitle() {
836 return $this->mSubtitle
;
840 * Set the page as printable, i.e. it'll be displayed with with all
841 * print styles included
843 public function setPrintable() {
844 $this->mPrintable
= true;
848 * Return whether the page is "printable"
852 public function isPrintable() {
853 return $this->mPrintable
;
857 * Disable output completely, i.e. calling output() will have no effect
859 public function disable() {
860 $this->mDoNothing
= true;
864 * Return whether the output will be completely disabled
868 public function isDisabled() {
869 return $this->mDoNothing
;
873 * Show an "add new section" link?
877 public function showNewSectionLink() {
878 return $this->mNewSectionLink
;
882 * Forcibly hide the new section link?
886 public function forceHideNewSectionLink() {
887 return $this->mHideNewSectionLink
;
891 * Add or remove feed links in the page header
892 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
893 * for the new version
896 * @param $show Boolean: true: add default feeds, false: remove all feeds
898 public function setSyndicated( $show = true ) {
900 $this->setFeedAppendQuery( false );
902 $this->mFeedLinks
= array();
907 * Add default feeds to the page header
908 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
909 * for the new version
912 * @param $val String: query to append to feed links or false to output
915 public function setFeedAppendQuery( $val ) {
916 global $wgAdvertisedFeedTypes;
918 $this->mFeedLinks
= array();
920 foreach ( $wgAdvertisedFeedTypes as $type ) {
921 $query = "feed=$type";
922 if ( is_string( $val ) ) {
923 $query .= '&' . $val;
925 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
930 * Add a feed link to the page header
932 * @param $format String: feed type, should be a key of $wgFeedClasses
933 * @param $href String: URL
935 public function addFeedLink( $format, $href ) {
936 global $wgAdvertisedFeedTypes;
938 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
939 $this->mFeedLinks
[$format] = $href;
944 * Should we output feed links for this page?
947 public function isSyndicated() {
948 return count( $this->mFeedLinks
) > 0;
952 * Return URLs for each supported syndication format for this page.
953 * @return array associating format keys with URLs
955 public function getSyndicationLinks() {
956 return $this->mFeedLinks
;
960 * Will currently always return null
964 public function getFeedAppendQuery() {
965 return $this->mFeedLinksAppendQuery
;
969 * Set whether the displayed content is related to the source of the
970 * corresponding article on the wiki
971 * Setting true will cause the change "article related" toggle to true
975 public function setArticleFlag( $v ) {
976 $this->mIsarticle
= $v;
978 $this->mIsArticleRelated
= $v;
983 * Return whether the content displayed page is related to the source of
984 * the corresponding article on the wiki
988 public function isArticle() {
989 return $this->mIsarticle
;
993 * Set whether this page is related an article on the wiki
994 * Setting false will cause the change of "article flag" toggle to false
998 public function setArticleRelated( $v ) {
999 $this->mIsArticleRelated
= $v;
1001 $this->mIsarticle
= false;
1006 * Return whether this page is related an article on the wiki
1010 public function isArticleRelated() {
1011 return $this->mIsArticleRelated
;
1015 * Add new language links
1017 * @param $newLinkArray Associative array mapping language code to the page
1020 public function addLanguageLinks( $newLinkArray ) {
1021 $this->mLanguageLinks +
= $newLinkArray;
1025 * Reset the language links and add new language links
1027 * @param $newLinkArray Associative array mapping language code to the page
1030 public function setLanguageLinks( $newLinkArray ) {
1031 $this->mLanguageLinks
= $newLinkArray;
1035 * Get the list of language links
1037 * @return Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1039 public function getLanguageLinks() {
1040 return $this->mLanguageLinks
;
1044 * Add an array of categories, with names in the keys
1046 * @param $categories Array mapping category name => sort key
1048 public function addCategoryLinks( $categories ) {
1051 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1055 # Add the links to a LinkBatch
1056 $arr = array( NS_CATEGORY
=> $categories );
1057 $lb = new LinkBatch
;
1058 $lb->setArray( $arr );
1060 # Fetch existence plus the hiddencat property
1061 $dbr = wfGetDB( DB_SLAVE
);
1062 $res = $dbr->select( array( 'page', 'page_props' ),
1063 array( 'page_id', 'page_namespace', 'page_title', 'page_len', 'page_is_redirect', 'page_latest', 'pp_value' ),
1064 $lb->constructSet( 'page', $dbr ),
1067 array( 'page_props' => array( 'LEFT JOIN', array( 'pp_propname' => 'hiddencat', 'pp_page = page_id' ) ) )
1070 # Add the results to the link cache
1071 $lb->addResultToCache( LinkCache
::singleton(), $res );
1073 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
1074 $categories = array_combine(
1075 array_keys( $categories ),
1076 array_fill( 0, count( $categories ), 'normal' )
1079 # Mark hidden categories
1080 foreach ( $res as $row ) {
1081 if ( isset( $row->pp_value
) ) {
1082 $categories[$row->page_title
] = 'hidden';
1086 # Add the remaining categories to the skin
1087 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
1088 foreach ( $categories as $category => $type ) {
1089 $origcategory = $category;
1090 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1091 $wgContLang->findVariantLink( $category, $title, true );
1092 if ( $category != $origcategory ) {
1093 if ( array_key_exists( $category, $categories ) ) {
1097 $text = $wgContLang->convertHtml( $title->getText() );
1098 $this->mCategories
[] = $title->getText();
1099 $this->mCategoryLinks
[$type][] = $this->getSkin()->link( $title, $text );
1105 * Reset the category links (but not the category list) and add $categories
1107 * @param $categories Array mapping category name => sort key
1109 public function setCategoryLinks( $categories ) {
1110 $this->mCategoryLinks
= array();
1111 $this->addCategoryLinks( $categories );
1115 * Get the list of category links, in a 2-D array with the following format:
1116 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1117 * hidden categories) and $link a HTML fragment with a link to the category
1122 public function getCategoryLinks() {
1123 return $this->mCategoryLinks
;
1127 * Get the list of category names this page belongs to
1129 * @return Array of strings
1131 public function getCategories() {
1132 return $this->mCategories
;
1136 * Do not allow scripts which can be modified by wiki users to load on this page;
1137 * only allow scripts bundled with, or generated by, the software.
1139 public function disallowUserJs() {
1140 $this->reduceAllowedModules(
1141 ResourceLoaderModule
::TYPE_SCRIPTS
,
1142 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1147 * Return whether user JavaScript is allowed for this page
1148 * @deprecated since 1.18 Load modules with ResourceLoader, and origin and
1149 * trustworthiness is identified and enforced automagically.
1152 public function isUserJsAllowed() {
1153 return $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
) >= ResourceLoaderModule
::ORIGIN_USER_INDIVIDUAL
;
1157 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1158 * @see ResourceLoaderModule::$origin
1159 * @param $type String ResourceLoaderModule TYPE_ constant
1160 * @return Int ResourceLoaderModule ORIGIN_ class constant
1162 public function getAllowedModules( $type ){
1163 if( $type == ResourceLoaderModule
::TYPE_COMBINED
){
1164 return min( array_values( $this->mAllowedModules
) );
1166 return isset( $this->mAllowedModules
[$type] )
1167 ?
$this->mAllowedModules
[$type]
1168 : ResourceLoaderModule
::ORIGIN_ALL
;
1173 * Set the highest level of CSS/JS untrustworthiness allowed
1174 * @param $type String ResourceLoaderModule TYPE_ constant
1175 * @param $level Int ResourceLoaderModule class constant
1177 public function setAllowedModules( $type, $level ){
1178 $this->mAllowedModules
[$type] = $level;
1182 * As for setAllowedModules(), but don't inadvertantly make the page more accessible
1183 * @param $type String
1184 * @param $level Int ResourceLoaderModule class constant
1186 public function reduceAllowedModules( $type, $level ){
1187 $this->mAllowedModules
[$type] = min( $this->getAllowedModules($type), $level );
1191 * Prepend $text to the body HTML
1193 * @param $text String: HTML
1195 public function prependHTML( $text ) {
1196 $this->mBodytext
= $text . $this->mBodytext
;
1200 * Append $text to the body HTML
1202 * @param $text String: HTML
1204 public function addHTML( $text ) {
1205 $this->mBodytext
.= $text;
1209 * Clear the body HTML
1211 public function clearHTML() {
1212 $this->mBodytext
= '';
1218 * @return String: HTML
1220 public function getHTML() {
1221 return $this->mBodytext
;
1225 * Add $text to the debug output
1227 * @param $text String: debug text
1229 public function debug( $text ) {
1230 $this->mDebugtext
.= $text;
1234 * Get/set the ParserOptions object to use for wikitext parsing
1236 * @param $options either the ParserOption to use or null to only get the
1237 * current ParserOption object
1238 * @return ParserOptions object
1240 public function parserOptions( $options = null ) {
1241 if ( !$this->mParserOptions
) {
1242 $this->mParserOptions
= new ParserOptions
;
1244 return wfSetVar( $this->mParserOptions
, $options );
1248 * Set the revision ID which will be seen by the wiki text parser
1249 * for things such as embedded {{REVISIONID}} variable use.
1251 * @param $revid Mixed: an positive integer, or null
1252 * @return Mixed: previous value
1254 public function setRevisionId( $revid ) {
1255 $val = is_null( $revid ) ?
null : intval( $revid );
1256 return wfSetVar( $this->mRevisionId
, $val );
1260 * Get the current revision ID
1264 public function getRevisionId() {
1265 return $this->mRevisionId
;
1269 * Get the templates used on this page
1271 * @return Array (namespace => dbKey => revId)
1273 public function getTemplateIds() {
1274 return $this->mTemplateIds
;
1278 * Get the files used on this page
1280 * @return Array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1282 public function getImageTimeKeys() {
1283 return $this->mImageTimeKeys
;
1287 * Convert wikitext to HTML and add it to the buffer
1288 * Default assumes that the current page title will be used.
1290 * @param $text String
1291 * @param $linestart Boolean: is this the start of a line?
1293 public function addWikiText( $text, $linestart = true ) {
1294 $title = $this->getTitle(); // Work arround E_STRICT
1295 $this->addWikiTextTitle( $text, $title, $linestart );
1299 * Add wikitext with a custom Title object
1301 * @param $text String: wikitext
1302 * @param $title Title object
1303 * @param $linestart Boolean: is this the start of a line?
1305 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1306 $this->addWikiTextTitle( $text, $title, $linestart );
1310 * Add wikitext with a custom Title object and
1312 * @param $text String: wikitext
1313 * @param $title Title object
1314 * @param $linestart Boolean: is this the start of a line?
1316 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1317 $this->addWikiTextTitle( $text, $title, $linestart, true );
1321 * Add wikitext with tidy enabled
1323 * @param $text String: wikitext
1324 * @param $linestart Boolean: is this the start of a line?
1326 public function addWikiTextTidy( $text, $linestart = true ) {
1327 $title = $this->getTitle();
1328 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1332 * Add wikitext with a custom Title object
1334 * @param $text String: wikitext
1335 * @param $title Title object
1336 * @param $linestart Boolean: is this the start of a line?
1337 * @param $tidy Boolean: whether to use tidy
1339 public function addWikiTextTitle( $text, &$title, $linestart, $tidy = false ) {
1342 wfProfileIn( __METHOD__
);
1344 wfIncrStats( 'pcache_not_possible' );
1346 $popts = $this->parserOptions();
1347 $oldTidy = $popts->setTidy( $tidy );
1349 $parserOutput = $wgParser->parse(
1350 $text, $title, $popts,
1351 $linestart, true, $this->mRevisionId
1354 $popts->setTidy( $oldTidy );
1356 $this->addParserOutput( $parserOutput );
1358 wfProfileOut( __METHOD__
);
1362 * Add a ParserOutput object, but without Html
1364 * @param $parserOutput ParserOutput object
1366 public function addParserOutputNoText( &$parserOutput ) {
1367 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1368 $this->addCategoryLinks( $parserOutput->getCategories() );
1369 $this->mNewSectionLink
= $parserOutput->getNewSection();
1370 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1372 $this->mParseWarnings
= $parserOutput->getWarnings();
1373 if ( !$parserOutput->isCacheable() ) {
1374 $this->enableClientCache( false );
1376 $this->mNoGallery
= $parserOutput->getNoGallery();
1377 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1378 $this->addModules( $parserOutput->getModules() );
1380 // Template versioning...
1381 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1382 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1383 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1385 $this->mTemplateIds
[$ns] = $dbks;
1388 // File versioning...
1389 foreach ( (array)$parserOutput->getImageTimeKeys() as $dbk => $data ) {
1390 $this->mImageTimeKeys
[$dbk] = $data;
1393 // Hooks registered in the object
1394 global $wgParserOutputHooks;
1395 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1396 list( $hookName, $data ) = $hookInfo;
1397 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1398 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1402 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1406 * Add a ParserOutput object
1408 * @param $parserOutput ParserOutput
1410 function addParserOutput( &$parserOutput ) {
1411 $this->addParserOutputNoText( $parserOutput );
1412 $text = $parserOutput->getText();
1413 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1414 $this->addHTML( $text );
1419 * Add the output of a QuickTemplate to the output buffer
1421 * @param $template QuickTemplate
1423 public function addTemplate( &$template ) {
1425 $template->execute();
1426 $this->addHTML( ob_get_contents() );
1431 * Parse wikitext and return the HTML.
1433 * @param $text String
1434 * @param $linestart Boolean: is this the start of a line?
1435 * @param $interface Boolean: use interface language ($wgLang instead of
1436 * $wgContLang) while parsing language sensitive magic
1437 * words like GRAMMAR and PLURAL
1438 * @param $language Language object: target language object, will override
1440 * @return String: HTML
1442 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1443 // Check one for one common cause for parser state resetting
1444 $callers = wfGetAllCallers( 10 );
1445 if ( strpos( $callers, 'Parser::extensionSubstitution' ) !== false ) {
1446 throw new MWException( "wfMsg* function with parsing cannot be used " .
1447 "inside a tag hook. Should use parser->recursiveTagParse() instead" );
1452 if( is_null( $this->getTitle() ) ) {
1453 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1456 $popts = $this->parserOptions();
1458 $popts->setInterfaceMessage( true );
1460 if ( $language !== null ) {
1461 $oldLang = $popts->setTargetLanguage( $language );
1464 $parserOutput = $wgParser->parse(
1465 $text, $this->getTitle(), $popts,
1466 $linestart, true, $this->mRevisionId
1470 $popts->setInterfaceMessage( false );
1472 if ( $language !== null ) {
1473 $popts->setTargetLanguage( $oldLang );
1476 return $parserOutput->getText();
1480 * Parse wikitext, strip paragraphs, and return the HTML.
1482 * @param $text String
1483 * @param $linestart Boolean: is this the start of a line?
1484 * @param $interface Boolean: use interface language ($wgLang instead of
1485 * $wgContLang) while parsing language sensitive magic
1486 * words like GRAMMAR and PLURAL
1487 * @return String: HTML
1489 public function parseInline( $text, $linestart = true, $interface = false ) {
1490 $parsed = $this->parse( $text, $linestart, $interface );
1493 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1501 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1503 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1505 public function setSquidMaxage( $maxage ) {
1506 $this->mSquidMaxage
= $maxage;
1510 * Use enableClientCache(false) to force it to send nocache headers
1514 public function enableClientCache( $state ) {
1515 return wfSetVar( $this->mEnableClientCache
, $state );
1519 * Get the list of cookies that will influence on the cache
1523 function getCacheVaryCookies() {
1524 global $wgCookiePrefix, $wgCacheVaryCookies;
1526 if ( $cookies === null ) {
1527 $cookies = array_merge(
1529 "{$wgCookiePrefix}Token",
1530 "{$wgCookiePrefix}LoggedOut",
1535 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1541 * Return whether this page is not cacheable because "useskin" or "uselang"
1542 * URL parameters were passed.
1546 function uncacheableBecauseRequestVars() {
1548 return $wgRequest->getText( 'useskin', false ) === false
1549 && $wgRequest->getText( 'uselang', false ) === false;
1553 * Check if the request has a cache-varying cookie header
1554 * If it does, it's very important that we don't allow public caching
1558 function haveCacheVaryCookies() {
1560 $cookieHeader = $wgRequest->getHeader( 'cookie' );
1561 if ( $cookieHeader === false ) {
1564 $cvCookies = $this->getCacheVaryCookies();
1565 foreach ( $cvCookies as $cookieName ) {
1566 # Check for a simple string match, like the way squid does it
1567 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1568 wfDebug( __METHOD__
. ": found $cookieName\n" );
1572 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1577 * Add an HTTP header that will influence on the cache
1579 * @param $header String: header name
1580 * @param $option Array|null
1581 * @fixme Document the $option parameter; it appears to be for
1582 * X-Vary-Options but what format is acceptable?
1584 public function addVaryHeader( $header, $option = null ) {
1585 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1586 $this->mVaryHeader
[$header] = (array)$option;
1587 } elseif( is_array( $option ) ) {
1588 if( is_array( $this->mVaryHeader
[$header] ) ) {
1589 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
1591 $this->mVaryHeader
[$header] = $option;
1594 $this->mVaryHeader
[$header] = array_unique( $this->mVaryHeader
[$header] );
1598 * Get a complete X-Vary-Options header
1602 public function getXVO() {
1603 $cvCookies = $this->getCacheVaryCookies();
1605 $cookiesOption = array();
1606 foreach ( $cvCookies as $cookieName ) {
1607 $cookiesOption[] = 'string-contains=' . $cookieName;
1609 $this->addVaryHeader( 'Cookie', $cookiesOption );
1612 foreach( $this->mVaryHeader
as $header => $option ) {
1613 $newheader = $header;
1614 if( is_array( $option ) ) {
1615 $newheader .= ';' . implode( ';', $option );
1617 $headers[] = $newheader;
1619 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1625 * bug 21672: Add Accept-Language to Vary and XVO headers
1626 * if there's no 'variant' parameter existed in GET.
1629 * /w/index.php?title=Main_page should always be served; but
1630 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1632 function addAcceptLanguage() {
1633 global $wgRequest, $wgContLang;
1634 if( !$wgRequest->getCheck( 'variant' ) && $wgContLang->hasVariants() ) {
1635 $variants = $wgContLang->getVariants();
1636 $aloption = array();
1637 foreach ( $variants as $variant ) {
1638 if( $variant === $wgContLang->getCode() ) {
1641 $aloption[] = 'string-contains=' . $variant;
1643 // IE and some other browsers use another form of language code
1644 // in their Accept-Language header, like "zh-CN" or "zh-TW".
1645 // We should handle these too.
1646 $ievariant = explode( '-', $variant );
1647 if ( count( $ievariant ) == 2 ) {
1648 $ievariant[1] = strtoupper( $ievariant[1] );
1649 $ievariant = implode( '-', $ievariant );
1650 $aloption[] = 'string-contains=' . $ievariant;
1654 $this->addVaryHeader( 'Accept-Language', $aloption );
1659 * Set a flag which will cause an X-Frame-Options header appropriate for
1660 * edit pages to be sent. The header value is controlled by
1661 * $wgEditPageFrameOptions.
1663 * This is the default for special pages. If you display a CSRF-protected
1664 * form on an ordinary view page, then you need to call this function.
1666 public function preventClickjacking( $enable = true ) {
1667 $this->mPreventClickjacking
= $enable;
1671 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1672 * This can be called from pages which do not contain any CSRF-protected
1675 public function allowClickjacking() {
1676 $this->mPreventClickjacking
= false;
1680 * Get the X-Frame-Options header value (without the name part), or false
1681 * if there isn't one. This is used by Skin to determine whether to enable
1682 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1684 public function getFrameOptions() {
1685 global $wgBreakFrames, $wgEditPageFrameOptions;
1686 if ( $wgBreakFrames ) {
1688 } elseif ( $this->mPreventClickjacking
&& $wgEditPageFrameOptions ) {
1689 return $wgEditPageFrameOptions;
1694 * Send cache control HTTP headers
1696 public function sendCacheControl() {
1697 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest, $wgUseXVO;
1699 $response = $wgRequest->response();
1700 if ( $wgUseETag && $this->mETag
) {
1701 $response->header( "ETag: $this->mETag" );
1704 $this->addAcceptLanguage();
1706 # don't serve compressed data to clients who can't handle it
1707 # maintain different caches for logged-in users and non-logged in ones
1708 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) ) );
1711 # Add an X-Vary-Options header for Squid with Wikimedia patches
1712 $response->header( $this->getXVO() );
1715 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
1717 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1718 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
1722 # We'll purge the proxy cache explicitly, but require end user agents
1723 # to revalidate against the proxy on each visit.
1724 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1725 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1726 # start with a shorter timeout for initial testing
1727 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1728 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
1729 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1731 # We'll purge the proxy cache for anons explicitly, but require end user agents
1732 # to revalidate against the proxy on each visit.
1733 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1734 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1735 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
1736 # start with a shorter timeout for initial testing
1737 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1738 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
1741 # We do want clients to cache if they can, but they *must* check for updates
1742 # on revisiting the page.
1743 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
1744 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1745 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1747 if($this->mLastModified
) {
1748 $response->header( "Last-Modified: {$this->mLastModified}" );
1751 wfDebug( __METHOD__
. ": no caching **\n", false );
1753 # In general, the absence of a last modified header should be enough to prevent
1754 # the client from using its cache. We send a few other things just to make sure.
1755 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1756 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1757 $response->header( 'Pragma: no-cache' );
1762 * Get the message associed with the HTTP response code $code
1764 * @param $code Integer: status code
1765 * @return String or null: message or null if $code is not in the list of
1768 public static function getStatusMessage( $code ) {
1769 static $statusMessage = array(
1771 101 => 'Switching Protocols',
1772 102 => 'Processing',
1776 203 => 'Non-Authoritative Information',
1777 204 => 'No Content',
1778 205 => 'Reset Content',
1779 206 => 'Partial Content',
1780 207 => 'Multi-Status',
1781 300 => 'Multiple Choices',
1782 301 => 'Moved Permanently',
1785 304 => 'Not Modified',
1787 307 => 'Temporary Redirect',
1788 400 => 'Bad Request',
1789 401 => 'Unauthorized',
1790 402 => 'Payment Required',
1793 405 => 'Method Not Allowed',
1794 406 => 'Not Acceptable',
1795 407 => 'Proxy Authentication Required',
1796 408 => 'Request Timeout',
1799 411 => 'Length Required',
1800 412 => 'Precondition Failed',
1801 413 => 'Request Entity Too Large',
1802 414 => 'Request-URI Too Large',
1803 415 => 'Unsupported Media Type',
1804 416 => 'Request Range Not Satisfiable',
1805 417 => 'Expectation Failed',
1806 422 => 'Unprocessable Entity',
1808 424 => 'Failed Dependency',
1809 500 => 'Internal Server Error',
1810 501 => 'Not Implemented',
1811 502 => 'Bad Gateway',
1812 503 => 'Service Unavailable',
1813 504 => 'Gateway Timeout',
1814 505 => 'HTTP Version Not Supported',
1815 507 => 'Insufficient Storage'
1817 return isset( $statusMessage[$code] ) ?
$statusMessage[$code] : null;
1821 * Finally, all the text has been munged and accumulated into
1822 * the object, let's actually output it:
1824 public function output() {
1825 global $wgOutputEncoding, $wgRequest;
1826 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType;
1828 if( $this->mDoNothing
) {
1832 wfProfileIn( __METHOD__
);
1834 $response = $wgRequest->response();
1836 if ( $this->mRedirect
!= '' ) {
1837 # Standards require redirect URLs to be absolute
1838 $this->mRedirect
= wfExpandUrl( $this->mRedirect
);
1839 if( $this->mRedirectCode
== '301' ||
$this->mRedirectCode
== '303' ) {
1840 if( !$wgDebugRedirects ) {
1841 $message = self
::getStatusMessage( $this->mRedirectCode
);
1842 $response->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
1844 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1846 $this->sendCacheControl();
1848 $response->header( "Content-Type: text/html; charset=utf-8" );
1849 if( $wgDebugRedirects ) {
1850 $url = htmlspecialchars( $this->mRedirect
);
1851 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1852 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1853 print "</body>\n</html>\n";
1855 $response->header( 'Location: ' . $this->mRedirect
);
1857 wfProfileOut( __METHOD__
);
1859 } elseif ( $this->mStatusCode
) {
1860 $message = self
::getStatusMessage( $this->mStatusCode
);
1862 $response->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
1866 # Buffer output; final headers may depend on later processing
1869 $response->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1870 $response->header( 'Content-language: ' . $wgLanguageCode );
1872 // Prevent framing, if requested
1873 $frameOptions = $this->getFrameOptions();
1874 if ( $frameOptions ) {
1875 $response->header( "X-Frame-Options: $frameOptions" );
1878 if ( $this->mArticleBodyOnly
) {
1879 $this->out( $this->mBodytext
);
1881 $this->addDefaultModules();
1883 $sk = $this->getSkin( $this->getTitle() );
1885 // Hook that allows last minute changes to the output page, e.g.
1886 // adding of CSS or Javascript by extensions.
1887 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1889 wfProfileIn( 'Output-skin' );
1890 $sk->outputPage( $this );
1891 wfProfileOut( 'Output-skin' );
1894 $this->sendCacheControl();
1896 wfProfileOut( __METHOD__
);
1900 * Actually output something with print(). Performs an iconv to the
1901 * output encoding, if needed.
1903 * @param $ins String: the string to output
1905 public function out( $ins ) {
1906 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1907 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1910 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1911 if ( false === $outs ) {
1919 * Produce a "user is blocked" page.
1921 * @param $return Boolean: whether to have a "return to $wgTitle" message or not.
1924 function blockedPage( $return = true ) {
1925 global $wgContLang, $wgLang;
1927 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1928 $this->setRobotPolicy( 'noindex,nofollow' );
1929 $this->setArticleRelated( false );
1931 $name = $this->getUser()->blockedBy();
1932 $reason = $this->getUser()->blockedFor();
1933 if( $reason == '' ) {
1934 $reason = wfMsg( 'blockednoreason' );
1936 $blockTimestamp = $wgLang->timeanddate(
1937 wfTimestamp( TS_MW
, $this->getUser()->mBlock
->mTimestamp
), true
1941 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1943 $blockid = $this->getUser()->mBlock
->getId();
1945 $blockExpiry = $wgLang->formatExpiry( $this->getUser()->mBlock
->mExpiry
);
1947 if ( $this->getUser()->mBlock
->mAuto
) {
1948 $msg = 'autoblockedtext';
1950 $msg = 'blockedtext';
1953 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1954 * This could be a username, an IP range, or a single IP. */
1955 $intended = $this->getUser()->mBlock
->getTarget();
1958 $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry,
1959 $intended, $blockTimestamp
1962 # Don't auto-return to special pages
1964 $return = $this->getTitle()->getNamespace() > -1 ?
$this->getTitle() : null;
1965 $this->returnToMain( null, $return );
1970 * Output a standard error page
1972 * @param $title String: message key for page title
1973 * @param $msg String: message key for page text
1974 * @param $params Array: message parameters
1976 public function showErrorPage( $title, $msg, $params = array() ) {
1977 if ( $this->getTitle() ) {
1978 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1980 $this->setPageTitle( wfMsg( $title ) );
1981 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1982 $this->setRobotPolicy( 'noindex,nofollow' );
1983 $this->setArticleRelated( false );
1984 $this->enableClientCache( false );
1985 $this->mRedirect
= '';
1986 $this->mBodytext
= '';
1988 $this->addWikiMsgArray( $msg, $params );
1990 $this->returnToMain();
1994 * Output a standard permission error page
1996 * @param $errors Array: error message keys
1997 * @param $action String: action that was denied or null if unknown
1999 public function showPermissionsErrorPage( $errors, $action = null ) {
2000 $this->mDebugtext
.= 'Original title: ' .
2001 $this->getTitle()->getPrefixedText() . "\n";
2002 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
2003 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
2004 $this->setRobotPolicy( 'noindex,nofollow' );
2005 $this->setArticleRelated( false );
2006 $this->enableClientCache( false );
2007 $this->mRedirect
= '';
2008 $this->mBodytext
= '';
2009 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2013 * Display an error page indicating that a given version of MediaWiki is
2014 * required to use it
2016 * @param $version Mixed: the version of MediaWiki needed to use the page
2018 public function versionRequired( $version ) {
2019 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
2020 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
2021 $this->setRobotPolicy( 'noindex,nofollow' );
2022 $this->setArticleRelated( false );
2023 $this->mBodytext
= '';
2025 $this->addWikiMsg( 'versionrequiredtext', $version );
2026 $this->returnToMain();
2030 * Display an error page noting that a given permission bit is required.
2032 * @param $permission String: key required
2034 public function permissionRequired( $permission ) {
2037 $this->setPageTitle( wfMsg( 'badaccess' ) );
2038 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
2039 $this->setRobotPolicy( 'noindex,nofollow' );
2040 $this->setArticleRelated( false );
2041 $this->mBodytext
= '';
2043 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
2044 User
::getGroupsWithPermission( $permission ) );
2048 $wgLang->commaList( $groups ),
2052 $this->addWikiMsg( 'badaccess-group0' );
2054 $this->returnToMain();
2058 * Produce the stock "please login to use the wiki" page
2060 public function loginToUse() {
2061 if( $this->getUser()->isLoggedIn() ) {
2062 $this->permissionRequired( 'read' );
2066 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
2067 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
2068 $this->setRobotPolicy( 'noindex,nofollow' );
2069 $this->setArticleRelated( false );
2071 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
2072 $loginLink = $this->getSkin()->link(
2074 wfMsgHtml( 'loginreqlink' ),
2076 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
2077 array( 'known', 'noclasses' )
2079 $this->addWikiMsgArray( 'loginreqpagetext', array( $loginLink ), array( 'replaceafter' ) );
2080 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . '-->' );
2082 # Don't return to the main page if the user can't read it
2083 # otherwise we'll end up in a pointless loop
2084 $mainPage = Title
::newMainPage();
2085 if( $mainPage->userCanRead() ) {
2086 $this->returnToMain( null, $mainPage );
2091 * Format a list of error messages
2093 * @param $errors Array of arrays returned by Title::getUserPermissionsErrors
2094 * @param $action String: action that was denied or null if unknown
2095 * @return String: the wikitext error-messages, formatted into a list.
2097 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2098 if ( $action == null ) {
2099 $text = wfMsgNoTrans( 'permissionserrorstext', count( $errors ) ) . "\n\n";
2101 $action_desc = wfMsgNoTrans( "action-$action" );
2102 $text = wfMsgNoTrans(
2103 'permissionserrorstext-withaction',
2109 if ( count( $errors ) > 1 ) {
2110 $text .= '<ul class="permissions-errors">' . "\n";
2112 foreach( $errors as $error ) {
2114 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
2119 $text .= "<div class=\"permissions-errors\">\n" .
2120 call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) .
2128 * Display a page stating that the Wiki is in read-only mode,
2129 * and optionally show the source of the page that the user
2130 * was trying to edit. Should only be called (for this
2131 * purpose) after wfReadOnly() has returned true.
2133 * For historical reasons, this function is _also_ used to
2134 * show the error message when a user tries to edit a page
2135 * they are not allowed to edit. (Unless it's because they're
2136 * blocked, then we show blockedPage() instead.) In this
2137 * case, the second parameter should be set to true and a list
2138 * of reasons supplied as the third parameter.
2140 * @todo Needs to be split into multiple functions.
2142 * @param $source String: source code to show (or null).
2143 * @param $protected Boolean: is this a permissions error?
2144 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
2145 * @param $action String: action that was denied or null if unknown
2147 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
2148 $this->setRobotPolicy( 'noindex,nofollow' );
2149 $this->setArticleRelated( false );
2151 // If no reason is given, just supply a default "I can't let you do
2152 // that, Dave" message. Should only occur if called by legacy code.
2153 if ( $protected && empty( $reasons ) ) {
2154 $reasons[] = array( 'badaccess-group0' );
2157 if ( !empty( $reasons ) ) {
2158 // Permissions error
2160 $this->setPageTitle( wfMsg( 'viewsource' ) );
2162 wfMsg( 'viewsourcefor', $this->getSkin()->linkKnown( $this->getTitle() ) )
2165 $this->setPageTitle( wfMsg( 'badaccess' ) );
2167 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2169 // Wiki is read only
2170 $this->setPageTitle( wfMsg( 'readonly' ) );
2171 $reason = wfReadOnlyReason();
2172 $this->wrapWikiMsg( "<div class='mw-readonly-error'>\n$1\n</div>", array( 'readonlytext', $reason ) );
2175 // Show source, if supplied
2176 if( is_string( $source ) ) {
2177 $this->addWikiMsg( 'viewsourcetext' );
2180 'id' => 'wpTextbox1',
2181 'name' => 'wpTextbox1',
2182 'cols' => $this->getUser()->getOption( 'cols' ),
2183 'rows' => $this->getUser()->getOption( 'rows' ),
2184 'readonly' => 'readonly'
2186 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
2188 // Show templates used by this article
2189 $skin = $this->getSkin();
2190 $article = new Article( $this->getTitle() );
2191 $this->addHTML( "<div class='templatesUsed'>
2192 {$skin->formatTemplates( $article->getUsedTemplates() )}
2197 # If the title doesn't exist, it's fairly pointless to print a return
2198 # link to it. After all, you just tried editing it and couldn't, so
2199 # what's there to do there?
2200 if( $this->getTitle()->exists() ) {
2201 $this->returnToMain( null, $this->getTitle() );
2206 * Adds JS-based password security checker
2207 * @param $passwordId String ID of input box containing password
2208 * @param $retypeId String ID of input box containing retyped password
2211 public function addPasswordSecurity( $passwordId, $retypeId ) {
2213 'password' => '#' . $passwordId,
2214 'retype' => '#' . $retypeId,
2215 'messages' => array(),
2217 foreach ( array( 'password-strength', 'password-strength-bad', 'password-strength-mediocre',
2218 'password-strength-acceptable', 'password-strength-good', 'password-retype', 'password-retype-mismatch'
2220 $data['messages'][$message] = wfMsg( $message );
2222 $this->addScript( Html
::inlineScript( 'var passwordSecurity=' . FormatJson
::encode( $data ) ) );
2223 $this->addModules( 'mediawiki.legacy.password' );
2226 public function showFatalError( $message ) {
2227 $this->setPageTitle( wfMsg( 'internalerror' ) );
2228 $this->setRobotPolicy( 'noindex,nofollow' );
2229 $this->setArticleRelated( false );
2230 $this->enableClientCache( false );
2231 $this->mRedirect
= '';
2232 $this->mBodytext
= $message;
2235 public function showUnexpectedValueError( $name, $val ) {
2236 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
2239 public function showFileCopyError( $old, $new ) {
2240 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
2243 public function showFileRenameError( $old, $new ) {
2244 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
2247 public function showFileDeleteError( $name ) {
2248 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
2251 public function showFileNotFoundError( $name ) {
2252 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
2256 * Add a "return to" link pointing to a specified title
2258 * @param $title Title to link
2259 * @param $query String: query string
2260 * @param $text String text of the link (input is not escaped)
2262 public function addReturnTo( $title, $query = array(), $text = null ) {
2263 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL() ) );
2266 $this->getSkin()->link( $title, $text, array(), $query )
2268 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2272 * Add a "return to" link pointing to a specified title,
2273 * or the title indicated in the request, or else the main page
2275 * @param $unused No longer used
2276 * @param $returnto Title or String to return to
2277 * @param $returntoquery String: query string for the return to link
2279 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2282 if ( $returnto == null ) {
2283 $returnto = $wgRequest->getText( 'returnto' );
2286 if ( $returntoquery == null ) {
2287 $returntoquery = $wgRequest->getText( 'returntoquery' );
2290 if ( $returnto === '' ) {
2291 $returnto = Title
::newMainPage();
2294 if ( is_object( $returnto ) ) {
2295 $titleObj = $returnto;
2297 $titleObj = Title
::newFromText( $returnto );
2299 if ( !is_object( $titleObj ) ) {
2300 $titleObj = Title
::newMainPage();
2303 $this->addReturnTo( $titleObj, $returntoquery );
2307 * @param $sk Skin The given Skin
2308 * @param $includeStyle Boolean: unused
2309 * @return String: The doctype, opening <html>, and head element.
2311 public function headElement( Skin
$sk, $includeStyle = true ) {
2312 global $wgOutputEncoding, $wgMimeType;
2313 global $wgUseTrackbacks, $wgHtml5;
2314 global $wgRequest, $wgLang;
2316 if ( $sk->commonPrintStylesheet() ) {
2317 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2319 $sk->setupUserCss( $this );
2322 $ret = Html
::htmlHeader( array( 'lang' => $lang->getCode(), 'dir' => $lang->getDir() ) );
2324 if ( $this->getHTMLTitle() == '' ) {
2325 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ) );
2328 $openHead = Html
::openElement( 'head' );
2330 # Don't bother with the newline if $head == ''
2331 $ret .= "$openHead\n";
2334 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2336 $ret .= implode( "\n", array(
2337 $this->getHeadLinks( $sk, true ),
2338 $this->buildCssLinks( $sk ),
2339 $this->getHeadItems()
2342 if ( $wgUseTrackbacks && $this->isArticleRelated() ) {
2343 $ret .= $this->getTitle()->trackbackRDF();
2346 $closeHead = Html
::closeElement( 'head' );
2348 $ret .= "$closeHead\n";
2351 $bodyAttrs = array();
2353 # Crazy edit-on-double-click stuff
2354 $action = $wgRequest->getVal( 'action', 'view' );
2357 $this->getTitle()->getNamespace() != NS_SPECIAL
&&
2358 in_array( $action, array( 'view', 'purge' ) ) &&
2359 $this->getUser()->getOption( 'editondblclick' )
2362 $bodyAttrs['ondblclick'] = "document.location = '" . Xml
::escapeJsString( $this->getTitle()->getEditURL() ) . "'";
2366 $dir = wfUILang()->getDir();
2367 $bodyAttrs['class'] = "mediawiki $dir";
2369 if ( $wgLang->capitalizeAllNouns() ) {
2370 # A <body> class is probably not the best way to do this . . .
2371 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2373 $bodyAttrs['class'] .= ' ' . $sk->getPageClasses( $this->getTitle() );
2374 $bodyAttrs['class'] .= ' skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2376 $sk->addToBodyAttributes( $this, $bodyAttrs ); // Allow skins to add body attributes they need
2377 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2379 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2385 * Add the default ResourceLoader modules to this object
2387 private function addDefaultModules() {
2388 global $wgIncludeLegacyJavaScript,
2389 $wgUseAjax, $wgAjaxWatch, $wgEnableMWSuggest;
2391 // Add base resources
2392 $this->addModules( 'mediawiki.util' );
2393 if( $wgIncludeLegacyJavaScript ){
2394 $this->addModules( 'mediawiki.legacy.wikibits' );
2397 // Add various resources if required
2399 $this->addModules( 'mediawiki.legacy.ajax' );
2401 wfRunHooks( 'AjaxAddScript', array( &$this ) );
2403 if( $wgAjaxWatch && $this->getUser()->isLoggedIn() ) {
2404 $this->addModules( 'mediawiki.action.watch.ajax' );
2407 if ( $wgEnableMWSuggest && !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2408 $this->addModules( 'mediawiki.legacy.mwsuggest' );
2412 if( $this->getUser()->getBoolOption( 'editsectiononrightclick' ) ) {
2413 $this->addModules( 'mediawiki.action.view.rightClickEdit' );
2418 * Get a ResourceLoader object associated with this OutputPage
2420 * @return ResourceLoader
2422 public function getResourceLoader() {
2423 if ( is_null( $this->mResourceLoader
) ) {
2424 $this->mResourceLoader
= new ResourceLoader();
2426 return $this->mResourceLoader
;
2432 * @param $modules Array/string with the module name
2433 * @param $only String ResourceLoaderModule TYPE_ class constant
2434 * @param $useESI boolean
2435 * @return string html <script> and <style> tags
2437 protected function makeResourceLoaderLink( Skin
$skin, $modules, $only, $useESI = false ) {
2438 global $wgLang, $wgLoadScript, $wgResourceLoaderUseESI,
2439 $wgResourceLoaderInlinePrivateModules, $wgRequest;
2440 // Lazy-load ResourceLoader
2441 // TODO: Should this be a static function of ResourceLoader instead?
2442 // TODO: Divide off modules starting with "user", and add the user parameter to them
2444 'lang' => $wgLang->getCode(),
2445 'debug' => ResourceLoader
::inDebugMode() ?
'true' : 'false',
2446 'skin' => $skin->getSkinName(),
2449 // Propagate printable and handheld parameters if present
2450 if ( $this->isPrintable() ) {
2451 $baseQuery['printable'] = 1;
2453 if ( $wgRequest->getBool( 'handheld' ) ) {
2454 $baseQuery['handheld'] = 1;
2457 if ( !count( $modules ) ) {
2461 if ( count( $modules ) > 1 ) {
2462 // Remove duplicate module requests
2463 $modules = array_unique( (array) $modules );
2464 // Sort module names so requests are more uniform
2467 if ( ResourceLoader
::inDebugMode() ) {
2468 // Recursively call us for every item
2470 foreach ( $modules as $name ) {
2471 $links .= $this->makeResourceLoaderLink( $skin, $name, $only, $useESI );
2477 // Create keyed-by-group list of module objects from modules list
2479 $resourceLoader = $this->getResourceLoader();
2480 foreach ( (array) $modules as $name ) {
2481 $module = $resourceLoader->getModule( $name );
2482 # Check that we're allowed to include this module on this page
2483 if ( ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2484 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2485 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2486 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2492 $group = $module->getGroup();
2493 if ( !isset( $groups[$group] ) ) {
2494 $groups[$group] = array();
2496 $groups[$group][$name] = $module;
2500 foreach ( $groups as $group => $modules ) {
2501 $query = $baseQuery;
2502 // Special handling for user-specific groups
2503 if ( ( $group === 'user' ||
$group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2504 $query['user'] = $this->getUser()->getName();
2507 // Create a fake request based on the one we are about to make so modules return
2508 // correct timestamp and emptiness data
2509 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2510 // Drop modules that know they're empty
2511 foreach ( $modules as $key => $module ) {
2512 if ( $module->isKnownEmpty( $context ) ) {
2513 unset( $modules[$key] );
2516 // If there are no modules left, skip this group
2517 if ( $modules === array() ) {
2521 $query['modules'] = implode( '|', array_keys( $modules ) );
2523 // Support inlining of private modules if configured as such
2524 if ( $group === 'private' && $wgResourceLoaderInlinePrivateModules ) {
2525 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2526 $links .= Html
::inlineStyle(
2527 $resourceLoader->makeModuleResponse( $context, $modules )
2530 $links .= Html
::inlineScript(
2531 ResourceLoader
::makeLoaderConditionalScript(
2532 $resourceLoader->makeModuleResponse( $context, $modules )
2538 // Special handling for the user group; because users might change their stuff
2539 // on-wiki like user pages, or user preferences; we need to find the highest
2540 // timestamp of these user-changable modules so we can ensure cache misses on change
2541 // This should NOT be done for the site group (bug 27564) because anons get that too
2542 // and we shouldn't be putting timestamps in Squid-cached HTML
2543 if ( $group === 'user' ) {
2544 // Get the maximum timestamp
2546 foreach ( $modules as $module ) {
2547 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2549 // Add a version parameter so cache will break when things change
2550 $query['version'] = wfTimestamp( TS_ISO_8601_BASIC
, $timestamp );
2552 // Make queries uniform in order
2555 $url = wfAppendQuery( $wgLoadScript, $query );
2556 if ( $useESI && $wgResourceLoaderUseESI ) {
2557 $esi = Xml
::element( 'esi:include', array( 'src' => $url ) );
2558 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2559 $link = Html
::inlineStyle( $esi );
2561 $link = Html
::inlineScript( $esi );
2564 // Automatically select style/script elements
2565 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2566 $link = Html
::linkedStyle( wfAppendQuery( $wgLoadScript, $query ) );
2568 $link = Html
::linkedScript( wfAppendQuery( $wgLoadScript, $query ) );
2572 if( $group == 'noscript' ){
2573 $links .= Html
::rawElement( 'noscript', array(), $link ) . "\n";
2575 $links .= $link . "\n";
2582 * Gets the global variables and mScripts; also adds userjs to the end if
2583 * enabled. Despite the name, these scripts are no longer put in the
2584 * <head> but at the bottom of the <body>
2586 * @param $sk Skin object to use
2587 * @return String: HTML fragment
2589 function getHeadScripts( Skin
$sk ) {
2590 global $wgRequest, $wgUseSiteJs, $wgAllowUserJs;
2592 // Startup - this will immediately load jquery and mediawiki modules
2593 $scripts = $this->makeResourceLoaderLink( $sk, 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
, true );
2595 // Script and Messages "only" requests
2596 $scripts .= $this->makeResourceLoaderLink( $sk, $this->getModuleScripts( true ), ResourceLoaderModule
::TYPE_SCRIPTS
);
2597 $scripts .= $this->makeResourceLoaderLink( $sk, $this->getModuleMessages( true ), ResourceLoaderModule
::TYPE_MESSAGES
);
2599 // Modules requests - let the client calculate dependencies and batch requests as it likes
2601 if ( $this->getModules( true ) ) {
2602 $loader = Xml
::encodeJsCall( 'mw.loader.load', array( $this->getModules( true ) ) ) .
2603 Xml
::encodeJsCall( 'mw.loader.go', array() );
2606 $scripts .= Html
::inlineScript(
2607 ResourceLoader
::makeLoaderConditionalScript(
2608 ResourceLoader
::makeConfigSetScript( $this->getJSVars() ) . $loader
2613 $scripts .= "\n" . $this->mScripts
;
2615 $userScripts = array( 'user.options' );
2617 // Add site JS if enabled
2618 if ( $wgUseSiteJs ) {
2619 $scripts .= $this->makeResourceLoaderLink( $sk, 'site', ResourceLoaderModule
::TYPE_SCRIPTS
);
2620 if( $this->getUser()->isLoggedIn() ){
2621 $userScripts[] = 'user.groups';
2625 // Add user JS if enabled
2626 if ( $wgAllowUserJs && $this->getUser()->isLoggedIn() ) {
2627 $action = $wgRequest->getVal( 'action', 'view' );
2628 if( $this->mTitle
&& $this->mTitle
->isJsSubpage() && $sk->userCanPreview( $action ) ) {
2629 # XXX: additional security check/prompt?
2630 $scripts .= Html
::inlineScript( "\n" . $wgRequest->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2632 # FIXME: this means that User:Me/Common.js doesn't load when previewing
2633 # User:Me/Vector.js, and vice versa (bug26283)
2634 $userScripts[] = 'user';
2637 $scripts .= $this->makeResourceLoaderLink( $sk, $userScripts, ResourceLoaderModule
::TYPE_SCRIPTS
);
2643 * Get an array containing global JS variables
2645 * Do not add things here which can be evaluated in
2646 * ResourceLoaderStartupScript - in other words, without state.
2647 * You will only be adding bloat to the page and causing page caches to
2648 * have to be purged on configuration changes.
2650 protected function getJSVars() {
2651 global $wgRequest, $wgUseAjax, $wgEnableMWSuggest, $wgContLang;
2653 $title = $this->getTitle();
2654 $ns = $title->getNamespace();
2655 $nsname = MWNamespace
::exists( $ns ) ? MWNamespace
::getCanonicalName( $ns ) : $title->getNsText();
2656 if ( $ns == NS_SPECIAL
) {
2657 $parts = SpecialPage
::resolveAliasWithSubpage( $title->getDBkey() );
2658 $canonicalName = $parts[0];
2660 $canonicalName = false; # bug 21115
2664 'wgCanonicalNamespace' => $nsname,
2665 'wgCanonicalSpecialPageName' => $canonicalName,
2666 'wgNamespaceNumber' => $title->getNamespace(),
2667 'wgPageName' => $title->getPrefixedDBKey(),
2668 'wgTitle' => $title->getText(),
2669 'wgCurRevisionId' => $title->getLatestRevID(),
2670 'wgArticleId' => $title->getArticleId(),
2671 'wgIsArticle' => $this->isArticle(),
2672 'wgAction' => $wgRequest->getText( 'action', 'view' ),
2673 'wgUserName' => $this->getUser()->isAnon() ?
null : $this->getUser()->getName(),
2674 'wgUserGroups' => $this->getUser()->getEffectiveGroups(),
2675 'wgCategories' => $this->getCategories(),
2676 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
2678 if ( $wgContLang->hasVariants() ) {
2679 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
2681 foreach ( $title->getRestrictionTypes() as $type ) {
2682 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
2684 if ( $wgUseAjax && $wgEnableMWSuggest && !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2685 $vars['wgSearchNamespaces'] = SearchEngine
::userNamespaces( $this->getUser() );
2688 // Allow extensions to add their custom variables to the global JS variables
2689 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars ) );
2695 * @return string HTML tag links to be put in the header.
2697 public function getHeadLinks( Skin
$sk, $addContentType = false ) {
2698 global $wgUniversalEditButton, $wgFavicon, $wgAppleTouchIcon, $wgEnableAPI,
2699 $wgSitename, $wgVersion, $wgHtml5, $wgMimeType, $wgOutputEncoding,
2700 $wgFeed, $wgOverrideSiteFeed, $wgAdvertisedFeedTypes,
2701 $wgEnableDublinCoreRdf, $wgEnableCreativeCommonsRdf,
2702 $wgDisableLangConversion, $wgCanonicalLanguageLinks, $wgContLang,
2703 $wgRightsPage, $wgRightsUrl;
2707 if ( $addContentType ) {
2709 # More succinct than <meta http-equiv=Content-Type>, has the
2711 $tags[] = Html
::element( 'meta', array( 'charset' => $wgOutputEncoding ) );
2713 $tags[] = Html
::element( 'meta', array(
2714 'http-equiv' => 'Content-Type',
2715 'content' => "$wgMimeType; charset=$wgOutputEncoding"
2717 $tags[] = Html
::element( 'meta', array( // bug 15835
2718 'http-equiv' => 'Content-Style-Type',
2719 'content' => 'text/css'
2724 $tags[] = Html
::element( 'meta', array(
2725 'name' => 'generator',
2726 'content' => "MediaWiki $wgVersion",
2729 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
2730 if( $p !== 'index,follow' ) {
2731 // http://www.robotstxt.org/wc/meta-user.html
2732 // Only show if it's different from the default robots policy
2733 $tags[] = Html
::element( 'meta', array(
2739 if ( count( $this->mKeywords
) > 0 ) {
2741 "/<.*?" . ">/" => '',
2744 $tags[] = Html
::element( 'meta', array(
2745 'name' => 'keywords',
2746 'content' => preg_replace(
2747 array_keys( $strip ),
2748 array_values( $strip ),
2749 implode( ',', $this->mKeywords
)
2754 foreach ( $this->mMetatags
as $tag ) {
2755 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
2757 $tag[0] = substr( $tag[0], 5 );
2761 $tags[] = Html
::element( 'meta',
2764 'content' => $tag[1]
2769 foreach ( $this->mLinktags
as $tag ) {
2770 $tags[] = Html
::element( 'link', $tag );
2773 # Universal edit button
2774 if ( $wgUniversalEditButton ) {
2775 if ( $this->isArticleRelated() && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
2776 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create' ) ) ) {
2777 // Original UniversalEditButton
2778 $msg = wfMsg( 'edit' );
2779 $tags[] = Html
::element( 'link', array(
2780 'rel' => 'alternate',
2781 'type' => 'application/x-wiki',
2783 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
2785 // Alternate edit link
2786 $tags[] = Html
::element( 'link', array(
2789 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
2794 # Generally the order of the favicon and apple-touch-icon links
2795 # should not matter, but Konqueror (3.5.9 at least) incorrectly
2796 # uses whichever one appears later in the HTML source. Make sure
2797 # apple-touch-icon is specified first to avoid this.
2798 if ( $wgAppleTouchIcon !== false ) {
2799 $tags[] = Html
::element( 'link', array( 'rel' => 'apple-touch-icon', 'href' => $wgAppleTouchIcon ) );
2802 if ( $wgFavicon !== false ) {
2803 $tags[] = Html
::element( 'link', array( 'rel' => 'shortcut icon', 'href' => $wgFavicon ) );
2806 # OpenSearch description link
2807 $tags[] = Html
::element( 'link', array(
2809 'type' => 'application/opensearchdescription+xml',
2810 'href' => wfScript( 'opensearch_desc' ),
2811 'title' => wfMsgForContent( 'opensearch-desc' ),
2814 if ( $wgEnableAPI ) {
2815 # Real Simple Discovery link, provides auto-discovery information
2816 # for the MediaWiki API (and potentially additional custom API
2817 # support such as WordPress or Twitter-compatible APIs for a
2818 # blogging extension, etc)
2819 $tags[] = Html
::element( 'link', array(
2821 'type' => 'application/rsd+xml',
2822 'href' => wfExpandUrl( wfAppendQuery( wfScript( 'api' ), array( 'action' => 'rsd' ) ) ),
2827 # - Creative Commons
2828 # See http://wiki.creativecommons.org/Extend_Metadata.
2830 # Use hreflang to specify canonical and alternate links
2831 # See http://www.google.com/support/webmasters/bin/answer.py?answer=189077
2832 if ( $this->isArticleRelated() ) {
2833 # note: buggy CC software only reads first "meta" link
2834 if ( $wgEnableCreativeCommonsRdf ) {
2835 $tags[] = Html
::element( 'link', array(
2836 'rel' => $this->getMetadataAttribute(),
2837 'title' => 'Creative Commons',
2838 'type' => 'application/rdf+xml',
2839 'href' => $this->getTitle()->getLocalURL( 'action=creativecommons' ) )
2843 if ( $wgEnableDublinCoreRdf ) {
2844 $tags[] = Html
::element( 'link', array(
2845 'rel' => $this->getMetadataAttribute(),
2846 'title' => 'Dublin Core',
2847 'type' => 'application/rdf+xml',
2848 'href' => $this->getTitle()->getLocalURL( 'action=dublincore' ) )
2854 if ( !$wgDisableLangConversion && $wgCanonicalLanguageLinks
2855 && $wgContLang->hasVariants() ) {
2857 $urlvar = $wgContLang->getURLVariant();
2860 $variants = $wgContLang->getVariants();
2861 foreach ( $variants as $_v ) {
2862 $tags[] = Html
::element( 'link', array(
2863 'rel' => 'alternate',
2865 'href' => $this->getTitle()->getLocalURL( '', $_v ) )
2869 $tags[] = Html
::element( 'link', array(
2870 'rel' => 'canonical',
2871 'href' => $this->getTitle()->getFullURL() )
2878 if ( $wgRightsPage ) {
2879 $copy = Title
::newFromText( $wgRightsPage );
2882 $copyright = $copy->getLocalURL();
2886 if ( !$copyright && $wgRightsUrl ) {
2887 $copyright = $wgRightsUrl;
2891 $tags[] = Html
::element( 'link', array(
2892 'rel' => 'copyright',
2893 'href' => $copyright )
2899 foreach( $this->getSyndicationLinks() as $format => $link ) {
2900 # Use the page name for the title (accessed through $wgTitle since
2901 # there's no other way). In principle, this could lead to issues
2902 # with having the same name for different feeds corresponding to
2903 # the same page, but we can't avoid that at this low a level.
2905 $tags[] = $this->feedLink(
2908 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
2909 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )
2913 # Recent changes feed should appear on every page (except recentchanges,
2914 # that would be redundant). Put it after the per-page feed to avoid
2915 # changing existing behavior. It's still available, probably via a
2916 # menu in your browser. Some sites might have a different feed they'd
2917 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
2918 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
2919 # If so, use it instead.
2921 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
2923 if ( $wgOverrideSiteFeed ) {
2924 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
2925 $tags[] = $this->feedLink(
2927 htmlspecialchars( $feedUrl ),
2928 wfMsg( "site-{$type}-feed", $wgSitename )
2931 } elseif ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
2932 foreach ( $wgAdvertisedFeedTypes as $format ) {
2933 $tags[] = $this->feedLink(
2935 $rctitle->getLocalURL( "feed={$format}" ),
2936 wfMsg( "site-{$format}-feed", $wgSitename ) # For grep: 'site-rss-feed', 'site-atom-feed'.
2941 return implode( "\n", $tags );
2945 * Generate a <link rel/> for a feed.
2947 * @param $type String: feed type
2948 * @param $url String: URL to the feed
2949 * @param $text String: value of the "title" attribute
2950 * @return String: HTML fragment
2952 private function feedLink( $type, $url, $text ) {
2953 return Html
::element( 'link', array(
2954 'rel' => 'alternate',
2955 'type' => "application/$type+xml",
2962 * Add a local or specified stylesheet, with the given media options.
2963 * Meant primarily for internal use...
2965 * @param $style String: URL to the file
2966 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
2967 * @param $condition String: for IE conditional comments, specifying an IE version
2968 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
2970 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
2972 // Even though we expect the media type to be lowercase, but here we
2973 // force it to lowercase to be safe.
2975 $options['media'] = $media;
2978 $options['condition'] = $condition;
2981 $options['dir'] = $dir;
2983 $this->styles
[$style] = $options;
2987 * Adds inline CSS styles
2988 * @param $style_css Mixed: inline CSS
2990 public function addInlineStyle( $style_css ){
2991 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
2995 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
2996 * These will be applied to various media & IE conditionals.
2997 * @param $sk Skin object
2999 public function buildCssLinks( $sk ) {
3001 // Add ResourceLoader styles
3002 // Split the styles into four groups
3003 $styles = array( 'other' => array(), 'user' => array(), 'site' => array(), 'private' => array(), 'noscript' => array() );
3004 $resourceLoader = $this->getResourceLoader();
3005 foreach ( $this->getModuleStyles() as $name ) {
3006 $group = $resourceLoader->getModule( $name )->getGroup();
3007 // Modules in groups named "other" or anything different than "user", "site" or "private"
3008 // will be placed in the "other" group
3009 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
3012 // We want site, private and user styles to override dynamically added styles from modules, but we want
3013 // dynamically added styles to override statically added styles from other modules. So the order
3014 // has to be other, dynamic, site, private, user
3015 // Add statically added styles for other modules
3016 $ret .= $this->makeResourceLoaderLink( $sk, $styles['other'], ResourceLoaderModule
::TYPE_STYLES
);
3017 // Add normal styles added through addStyle()/addInlineStyle() here
3018 $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3019 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3020 // We use a <meta> tag with a made-up name for this because that's valid HTML
3021 $ret .= Html
::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) ) . "\n";
3023 // Add site, private and user styles
3024 // 'private' at present only contains user.options, so put that before 'user'
3025 // Any future private modules will likely have a similar user-specific character
3026 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3027 $ret .= $this->makeResourceLoaderLink( $sk, $styles[$group],
3028 ResourceLoaderModule
::TYPE_STYLES
3034 public function buildCssLinksArray() {
3036 foreach( $this->styles
as $file => $options ) {
3037 $link = $this->styleLink( $file, $options );
3039 $links[$file] = $link;
3046 * Generate \<link\> tags for stylesheets
3048 * @param $style String: URL to the file
3049 * @param $options Array: option, can contain 'condition', 'dir', 'media'
3051 * @return String: HTML fragment
3053 protected function styleLink( $style, $options ) {
3054 if( isset( $options['dir'] ) ) {
3055 $siteDir = wfUILang()->getDir();
3056 if( $siteDir != $options['dir'] ) {
3061 if( isset( $options['media'] ) ) {
3062 $media = self
::transformCssMedia( $options['media'] );
3063 if( is_null( $media ) ) {
3070 if( substr( $style, 0, 1 ) == '/' ||
3071 substr( $style, 0, 5 ) == 'http:' ||
3072 substr( $style, 0, 6 ) == 'https:' ) {
3075 global $wgStylePath, $wgStyleVersion;
3076 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
3079 $link = Html
::linkedStyle( $url, $media );
3081 if( isset( $options['condition'] ) ) {
3082 $condition = htmlspecialchars( $options['condition'] );
3083 $link = "<!--[if $condition]>$link<![endif]-->";
3089 * Transform "media" attribute based on request parameters
3091 * @param $media String: current value of the "media" attribute
3092 * @return String: modified value of the "media" attribute
3094 public static function transformCssMedia( $media ) {
3095 global $wgRequest, $wgHandheldForIPhone;
3097 // Switch in on-screen display for media testing
3099 'printable' => 'print',
3100 'handheld' => 'handheld',
3102 foreach( $switches as $switch => $targetMedia ) {
3103 if( $wgRequest->getBool( $switch ) ) {
3104 if( $media == $targetMedia ) {
3106 } elseif( $media == 'screen' ) {
3112 // Expand longer media queries as iPhone doesn't grok 'handheld'
3113 if( $wgHandheldForIPhone ) {
3114 $mediaAliases = array(
3115 'screen' => 'screen and (min-device-width: 481px)',
3116 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
3119 if( isset( $mediaAliases[$media] ) ) {
3120 $media = $mediaAliases[$media];
3128 * Turn off regular page output and return an error reponse
3129 * for when rate limiting has triggered.
3131 public function rateLimited() {
3132 $this->setPageTitle( wfMsg( 'actionthrottled' ) );
3133 $this->setRobotPolicy( 'noindex,follow' );
3134 $this->setArticleRelated( false );
3135 $this->enableClientCache( false );
3136 $this->mRedirect
= '';
3138 $this->setStatusCode( 503 );
3139 $this->addWikiMsg( 'actionthrottledtext' );
3141 $this->returnToMain( null, $this->getTitle() );
3145 * Show a warning about slave lag
3147 * If the lag is higher than $wgSlaveLagCritical seconds,
3148 * then the warning is a bit more obvious. If the lag is
3149 * lower than $wgSlaveLagWarning, then no warning is shown.
3151 * @param $lag Integer: slave lag
3153 public function showLagWarning( $lag ) {
3154 global $wgSlaveLagWarning, $wgSlaveLagCritical, $wgLang;
3155 if( $lag >= $wgSlaveLagWarning ) {
3156 $message = $lag < $wgSlaveLagCritical
3159 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
3160 $this->wrapWikiMsg( "$wrap\n", array( $message, $wgLang->formatNum( $lag ) ) );
3165 * Add a wikitext-formatted message to the output.
3166 * This is equivalent to:
3168 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
3170 public function addWikiMsg( /*...*/ ) {
3171 $args = func_get_args();
3172 $name = array_shift( $args );
3173 $this->addWikiMsgArray( $name, $args );
3177 * Add a wikitext-formatted message to the output.
3178 * Like addWikiMsg() except the parameters are taken as an array
3179 * instead of a variable argument list.
3181 * $options is passed through to wfMsgExt(), see that function for details.
3183 public function addWikiMsgArray( $name, $args, $options = array() ) {
3184 $options[] = 'parse';
3185 $text = wfMsgExt( $name, $options, $args );
3186 $this->addHTML( $text );
3190 * This function takes a number of message/argument specifications, wraps them in
3191 * some overall structure, and then parses the result and adds it to the output.
3193 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3194 * on. The subsequent arguments may either be strings, in which case they are the
3195 * message names, or arrays, in which case the first element is the message name,
3196 * and subsequent elements are the parameters to that message.
3198 * The special named parameter 'options' in a message specification array is passed
3199 * through to the $options parameter of wfMsgExt().
3201 * Don't use this for messages that are not in users interface language.
3205 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3209 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . "\n</div>" );
3211 * The newline after opening div is needed in some wikitext. See bug 19226.
3213 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3214 $msgSpecs = func_get_args();
3215 array_shift( $msgSpecs );
3216 $msgSpecs = array_values( $msgSpecs );
3218 foreach ( $msgSpecs as $n => $spec ) {
3220 if ( is_array( $spec ) ) {
3222 $name = array_shift( $args );
3223 if ( isset( $args['options'] ) ) {
3224 $options = $args['options'];
3225 unset( $args['options'] );
3231 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
3233 $this->addWikiText( $s );
3237 * Include jQuery core. Use this to avoid loading it multiple times
3238 * before we get a usable script loader.
3240 * @param $modules Array: list of jQuery modules which should be loaded
3241 * @return Array: the list of modules which were not loaded.
3243 * @deprecated since 1.17
3245 public function includeJQuery( $modules = array() ) {