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;
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 $this->getRequest()->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 RequestContext used in this instance
757 * @param RequestContext $context
759 public function setContext( RequestContext
$context ) {
760 $this->mContext
= $context;
764 * Get the RequestContext used in this instance
766 * @return RequestContext
768 public function getContext() {
769 if ( !isset($this->mContext
) ) {
770 wfDebug( __METHOD__
. " called and \$mContext is null. Using RequestContext::getMain(); for sanity\n" );
771 $this->mContext
= RequestContext
::getMain();
773 return $this->mContext
;
777 * Get the WebRequest being used for this instance
782 public function getRequest() {
783 return $this->getContext()->getRequest();
787 * Set the Title object to use
789 * @param $t Title object
791 public function setTitle( $t ) {
792 $this->getContext()->setTitle($t);
796 * Get the Title object used in this instance
800 public function getTitle() {
801 return $this->getContext()->getTitle();
805 * Get the User object used in this instance
810 public function getUser() {
811 return $this->getContext()->getUser();
815 * Get the Skin object used to render this instance
820 public function getSkin() {
821 return $this->getContext()->getSkin();
825 * Replace the subtile with $str
827 * @param $str String: new value of the subtitle
829 public function setSubtitle( $str ) {
830 $this->mSubtitle
= /*$this->parse(*/ $str /*)*/; // @bug 2514
834 * Add $str to the subtitle
836 * @param $str String to add to the subtitle
838 public function appendSubtitle( $str ) {
839 $this->mSubtitle
.= /*$this->parse(*/ $str /*)*/; // @bug 2514
847 public function getSubtitle() {
848 return $this->mSubtitle
;
852 * Set the page as printable, i.e. it'll be displayed with with all
853 * print styles included
855 public function setPrintable() {
856 $this->mPrintable
= true;
860 * Return whether the page is "printable"
864 public function isPrintable() {
865 return $this->mPrintable
;
869 * Disable output completely, i.e. calling output() will have no effect
871 public function disable() {
872 $this->mDoNothing
= true;
876 * Return whether the output will be completely disabled
880 public function isDisabled() {
881 return $this->mDoNothing
;
885 * Show an "add new section" link?
889 public function showNewSectionLink() {
890 return $this->mNewSectionLink
;
894 * Forcibly hide the new section link?
898 public function forceHideNewSectionLink() {
899 return $this->mHideNewSectionLink
;
903 * Add or remove feed links in the page header
904 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
905 * for the new version
908 * @param $show Boolean: true: add default feeds, false: remove all feeds
910 public function setSyndicated( $show = true ) {
912 $this->setFeedAppendQuery( false );
914 $this->mFeedLinks
= array();
919 * Add default feeds to the page header
920 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
921 * for the new version
924 * @param $val String: query to append to feed links or false to output
927 public function setFeedAppendQuery( $val ) {
928 global $wgAdvertisedFeedTypes;
930 $this->mFeedLinks
= array();
932 foreach ( $wgAdvertisedFeedTypes as $type ) {
933 $query = "feed=$type";
934 if ( is_string( $val ) ) {
935 $query .= '&' . $val;
937 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
942 * Add a feed link to the page header
944 * @param $format String: feed type, should be a key of $wgFeedClasses
945 * @param $href String: URL
947 public function addFeedLink( $format, $href ) {
948 global $wgAdvertisedFeedTypes;
950 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
951 $this->mFeedLinks
[$format] = $href;
956 * Should we output feed links for this page?
959 public function isSyndicated() {
960 return count( $this->mFeedLinks
) > 0;
964 * Return URLs for each supported syndication format for this page.
965 * @return array associating format keys with URLs
967 public function getSyndicationLinks() {
968 return $this->mFeedLinks
;
972 * Will currently always return null
976 public function getFeedAppendQuery() {
977 return $this->mFeedLinksAppendQuery
;
981 * Set whether the displayed content is related to the source of the
982 * corresponding article on the wiki
983 * Setting true will cause the change "article related" toggle to true
987 public function setArticleFlag( $v ) {
988 $this->mIsarticle
= $v;
990 $this->mIsArticleRelated
= $v;
995 * Return whether the content displayed page is related to the source of
996 * the corresponding article on the wiki
1000 public function isArticle() {
1001 return $this->mIsarticle
;
1005 * Set whether this page is related an article on the wiki
1006 * Setting false will cause the change of "article flag" toggle to false
1010 public function setArticleRelated( $v ) {
1011 $this->mIsArticleRelated
= $v;
1013 $this->mIsarticle
= false;
1018 * Return whether this page is related an article on the wiki
1022 public function isArticleRelated() {
1023 return $this->mIsArticleRelated
;
1027 * Add new language links
1029 * @param $newLinkArray Associative array mapping language code to the page
1032 public function addLanguageLinks( $newLinkArray ) {
1033 $this->mLanguageLinks +
= $newLinkArray;
1037 * Reset the language links and add new language links
1039 * @param $newLinkArray Associative array mapping language code to the page
1042 public function setLanguageLinks( $newLinkArray ) {
1043 $this->mLanguageLinks
= $newLinkArray;
1047 * Get the list of language links
1049 * @return Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1051 public function getLanguageLinks() {
1052 return $this->mLanguageLinks
;
1056 * Add an array of categories, with names in the keys
1058 * @param $categories Array mapping category name => sort key
1060 public function addCategoryLinks( $categories ) {
1063 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1067 # Add the links to a LinkBatch
1068 $arr = array( NS_CATEGORY
=> $categories );
1069 $lb = new LinkBatch
;
1070 $lb->setArray( $arr );
1072 # Fetch existence plus the hiddencat property
1073 $dbr = wfGetDB( DB_SLAVE
);
1074 $res = $dbr->select( array( 'page', 'page_props' ),
1075 array( 'page_id', 'page_namespace', 'page_title', 'page_len', 'page_is_redirect', 'page_latest', 'pp_value' ),
1076 $lb->constructSet( 'page', $dbr ),
1079 array( 'page_props' => array( 'LEFT JOIN', array( 'pp_propname' => 'hiddencat', 'pp_page = page_id' ) ) )
1082 # Add the results to the link cache
1083 $lb->addResultToCache( LinkCache
::singleton(), $res );
1085 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
1086 $categories = array_combine(
1087 array_keys( $categories ),
1088 array_fill( 0, count( $categories ), 'normal' )
1091 # Mark hidden categories
1092 foreach ( $res as $row ) {
1093 if ( isset( $row->pp_value
) ) {
1094 $categories[$row->page_title
] = 'hidden';
1098 # Add the remaining categories to the skin
1099 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
1100 foreach ( $categories as $category => $type ) {
1101 $origcategory = $category;
1102 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1103 $wgContLang->findVariantLink( $category, $title, true );
1104 if ( $category != $origcategory ) {
1105 if ( array_key_exists( $category, $categories ) ) {
1109 $text = $wgContLang->convertHtml( $title->getText() );
1110 $this->mCategories
[] = $title->getText();
1111 $this->mCategoryLinks
[$type][] = $this->getSkin()->link( $title, $text );
1117 * Reset the category links (but not the category list) and add $categories
1119 * @param $categories Array mapping category name => sort key
1121 public function setCategoryLinks( $categories ) {
1122 $this->mCategoryLinks
= array();
1123 $this->addCategoryLinks( $categories );
1127 * Get the list of category links, in a 2-D array with the following format:
1128 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1129 * hidden categories) and $link a HTML fragment with a link to the category
1134 public function getCategoryLinks() {
1135 return $this->mCategoryLinks
;
1139 * Get the list of category names this page belongs to
1141 * @return Array of strings
1143 public function getCategories() {
1144 return $this->mCategories
;
1148 * Do not allow scripts which can be modified by wiki users to load on this page;
1149 * only allow scripts bundled with, or generated by, the software.
1151 public function disallowUserJs() {
1152 $this->reduceAllowedModules(
1153 ResourceLoaderModule
::TYPE_SCRIPTS
,
1154 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1159 * Return whether user JavaScript is allowed for this page
1160 * @deprecated since 1.18 Load modules with ResourceLoader, and origin and
1161 * trustworthiness is identified and enforced automagically.
1164 public function isUserJsAllowed() {
1165 return $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
) >= ResourceLoaderModule
::ORIGIN_USER_INDIVIDUAL
;
1169 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1170 * @see ResourceLoaderModule::$origin
1171 * @param $type String ResourceLoaderModule TYPE_ constant
1172 * @return Int ResourceLoaderModule ORIGIN_ class constant
1174 public function getAllowedModules( $type ){
1175 if( $type == ResourceLoaderModule
::TYPE_COMBINED
){
1176 return min( array_values( $this->mAllowedModules
) );
1178 return isset( $this->mAllowedModules
[$type] )
1179 ?
$this->mAllowedModules
[$type]
1180 : ResourceLoaderModule
::ORIGIN_ALL
;
1185 * Set the highest level of CSS/JS untrustworthiness allowed
1186 * @param $type String ResourceLoaderModule TYPE_ constant
1187 * @param $level Int ResourceLoaderModule class constant
1189 public function setAllowedModules( $type, $level ){
1190 $this->mAllowedModules
[$type] = $level;
1194 * As for setAllowedModules(), but don't inadvertantly make the page more accessible
1195 * @param $type String
1196 * @param $level Int ResourceLoaderModule class constant
1198 public function reduceAllowedModules( $type, $level ){
1199 $this->mAllowedModules
[$type] = min( $this->getAllowedModules($type), $level );
1203 * Prepend $text to the body HTML
1205 * @param $text String: HTML
1207 public function prependHTML( $text ) {
1208 $this->mBodytext
= $text . $this->mBodytext
;
1212 * Append $text to the body HTML
1214 * @param $text String: HTML
1216 public function addHTML( $text ) {
1217 $this->mBodytext
.= $text;
1221 * Clear the body HTML
1223 public function clearHTML() {
1224 $this->mBodytext
= '';
1230 * @return String: HTML
1232 public function getHTML() {
1233 return $this->mBodytext
;
1237 * Add $text to the debug output
1239 * @param $text String: debug text
1241 public function debug( $text ) {
1242 $this->mDebugtext
.= $text;
1246 * Get/set the ParserOptions object to use for wikitext parsing
1248 * @param $options either the ParserOption to use or null to only get the
1249 * current ParserOption object
1250 * @return ParserOptions object
1252 public function parserOptions( $options = null ) {
1253 if ( !$this->mParserOptions
) {
1254 $this->mParserOptions
= new ParserOptions
;
1256 return wfSetVar( $this->mParserOptions
, $options );
1260 * Set the revision ID which will be seen by the wiki text parser
1261 * for things such as embedded {{REVISIONID}} variable use.
1263 * @param $revid Mixed: an positive integer, or null
1264 * @return Mixed: previous value
1266 public function setRevisionId( $revid ) {
1267 $val = is_null( $revid ) ?
null : intval( $revid );
1268 return wfSetVar( $this->mRevisionId
, $val );
1272 * Get the current revision ID
1276 public function getRevisionId() {
1277 return $this->mRevisionId
;
1281 * Get the templates used on this page
1283 * @return Array (namespace => dbKey => revId)
1285 public function getTemplateIds() {
1286 return $this->mTemplateIds
;
1290 * Get the files used on this page
1292 * @return Array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1294 public function getImageTimeKeys() {
1295 return $this->mImageTimeKeys
;
1299 * Convert wikitext to HTML and add it to the buffer
1300 * Default assumes that the current page title will be used.
1302 * @param $text String
1303 * @param $linestart Boolean: is this the start of a line?
1305 public function addWikiText( $text, $linestart = true ) {
1306 $title = $this->getTitle(); // Work arround E_STRICT
1307 $this->addWikiTextTitle( $text, $title, $linestart );
1311 * Add wikitext with a custom Title object
1313 * @param $text String: wikitext
1314 * @param $title Title object
1315 * @param $linestart Boolean: is this the start of a line?
1317 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1318 $this->addWikiTextTitle( $text, $title, $linestart );
1322 * Add wikitext with a custom Title object and
1324 * @param $text String: wikitext
1325 * @param $title Title object
1326 * @param $linestart Boolean: is this the start of a line?
1328 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1329 $this->addWikiTextTitle( $text, $title, $linestart, true );
1333 * Add wikitext with tidy enabled
1335 * @param $text String: wikitext
1336 * @param $linestart Boolean: is this the start of a line?
1338 public function addWikiTextTidy( $text, $linestart = true ) {
1339 $title = $this->getTitle();
1340 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1344 * Add wikitext with a custom Title object
1346 * @param $text String: wikitext
1347 * @param $title Title object
1348 * @param $linestart Boolean: is this the start of a line?
1349 * @param $tidy Boolean: whether to use tidy
1351 public function addWikiTextTitle( $text, &$title, $linestart, $tidy = false ) {
1354 wfProfileIn( __METHOD__
);
1356 wfIncrStats( 'pcache_not_possible' );
1358 $popts = $this->parserOptions();
1359 $oldTidy = $popts->setTidy( $tidy );
1361 $parserOutput = $wgParser->parse(
1362 $text, $title, $popts,
1363 $linestart, true, $this->mRevisionId
1366 $popts->setTidy( $oldTidy );
1368 $this->addParserOutput( $parserOutput );
1370 wfProfileOut( __METHOD__
);
1374 * Add a ParserOutput object, but without Html
1376 * @param $parserOutput ParserOutput object
1378 public function addParserOutputNoText( &$parserOutput ) {
1379 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1380 $this->addCategoryLinks( $parserOutput->getCategories() );
1381 $this->mNewSectionLink
= $parserOutput->getNewSection();
1382 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1384 $this->mParseWarnings
= $parserOutput->getWarnings();
1385 if ( !$parserOutput->isCacheable() ) {
1386 $this->enableClientCache( false );
1388 $this->mNoGallery
= $parserOutput->getNoGallery();
1389 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1390 $this->addModules( $parserOutput->getModules() );
1392 // Template versioning...
1393 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1394 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1395 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1397 $this->mTemplateIds
[$ns] = $dbks;
1400 // File versioning...
1401 foreach ( (array)$parserOutput->getImageTimeKeys() as $dbk => $data ) {
1402 $this->mImageTimeKeys
[$dbk] = $data;
1405 // Hooks registered in the object
1406 global $wgParserOutputHooks;
1407 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1408 list( $hookName, $data ) = $hookInfo;
1409 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1410 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1414 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1418 * Add a ParserOutput object
1420 * @param $parserOutput ParserOutput
1422 function addParserOutput( &$parserOutput ) {
1423 $this->addParserOutputNoText( $parserOutput );
1424 $text = $parserOutput->getText();
1425 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1426 $this->addHTML( $text );
1431 * Add the output of a QuickTemplate to the output buffer
1433 * @param $template QuickTemplate
1435 public function addTemplate( &$template ) {
1437 $template->execute();
1438 $this->addHTML( ob_get_contents() );
1443 * Parse wikitext and return the HTML.
1445 * @param $text String
1446 * @param $linestart Boolean: is this the start of a line?
1447 * @param $interface Boolean: use interface language ($wgLang instead of
1448 * $wgContLang) while parsing language sensitive magic
1449 * words like GRAMMAR and PLURAL
1450 * @param $language Language object: target language object, will override
1452 * @return String: HTML
1454 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1455 // Check one for one common cause for parser state resetting
1456 $callers = wfGetAllCallers( 10 );
1457 if ( strpos( $callers, 'Parser::extensionSubstitution' ) !== false ) {
1458 throw new MWException( "wfMsg* function with parsing cannot be used " .
1459 "inside a tag hook. Should use parser->recursiveTagParse() instead" );
1464 if( is_null( $this->getTitle() ) ) {
1465 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1468 $popts = $this->parserOptions();
1470 $popts->setInterfaceMessage( true );
1472 if ( $language !== null ) {
1473 $oldLang = $popts->setTargetLanguage( $language );
1476 $parserOutput = $wgParser->parse(
1477 $text, $this->getTitle(), $popts,
1478 $linestart, true, $this->mRevisionId
1482 $popts->setInterfaceMessage( false );
1484 if ( $language !== null ) {
1485 $popts->setTargetLanguage( $oldLang );
1488 return $parserOutput->getText();
1492 * Parse wikitext, strip paragraphs, and return the HTML.
1494 * @param $text String
1495 * @param $linestart Boolean: is this the start of a line?
1496 * @param $interface Boolean: use interface language ($wgLang instead of
1497 * $wgContLang) while parsing language sensitive magic
1498 * words like GRAMMAR and PLURAL
1499 * @return String: HTML
1501 public function parseInline( $text, $linestart = true, $interface = false ) {
1502 $parsed = $this->parse( $text, $linestart, $interface );
1505 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1513 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1515 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1517 public function setSquidMaxage( $maxage ) {
1518 $this->mSquidMaxage
= $maxage;
1522 * Use enableClientCache(false) to force it to send nocache headers
1526 public function enableClientCache( $state ) {
1527 return wfSetVar( $this->mEnableClientCache
, $state );
1531 * Get the list of cookies that will influence on the cache
1535 function getCacheVaryCookies() {
1536 global $wgCookiePrefix, $wgCacheVaryCookies;
1538 if ( $cookies === null ) {
1539 $cookies = array_merge(
1541 "{$wgCookiePrefix}Token",
1542 "{$wgCookiePrefix}LoggedOut",
1547 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1553 * Return whether this page is not cacheable because "useskin" or "uselang"
1554 * URL parameters were passed.
1558 function uncacheableBecauseRequestVars() {
1559 $request = $this->getRequest();
1560 return $request->getText( 'useskin', false ) === false
1561 && $request->getText( 'uselang', false ) === false;
1565 * Check if the request has a cache-varying cookie header
1566 * If it does, it's very important that we don't allow public caching
1570 function haveCacheVaryCookies() {
1571 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1572 if ( $cookieHeader === false ) {
1575 $cvCookies = $this->getCacheVaryCookies();
1576 foreach ( $cvCookies as $cookieName ) {
1577 # Check for a simple string match, like the way squid does it
1578 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1579 wfDebug( __METHOD__
. ": found $cookieName\n" );
1583 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1588 * Add an HTTP header that will influence on the cache
1590 * @param $header String: header name
1591 * @param $option Array|null
1592 * @fixme Document the $option parameter; it appears to be for
1593 * X-Vary-Options but what format is acceptable?
1595 public function addVaryHeader( $header, $option = null ) {
1596 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1597 $this->mVaryHeader
[$header] = (array)$option;
1598 } elseif( is_array( $option ) ) {
1599 if( is_array( $this->mVaryHeader
[$header] ) ) {
1600 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
1602 $this->mVaryHeader
[$header] = $option;
1605 $this->mVaryHeader
[$header] = array_unique( $this->mVaryHeader
[$header] );
1609 * Get a complete X-Vary-Options header
1613 public function getXVO() {
1614 $cvCookies = $this->getCacheVaryCookies();
1616 $cookiesOption = array();
1617 foreach ( $cvCookies as $cookieName ) {
1618 $cookiesOption[] = 'string-contains=' . $cookieName;
1620 $this->addVaryHeader( 'Cookie', $cookiesOption );
1623 foreach( $this->mVaryHeader
as $header => $option ) {
1624 $newheader = $header;
1625 if( is_array( $option ) ) {
1626 $newheader .= ';' . implode( ';', $option );
1628 $headers[] = $newheader;
1630 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1636 * bug 21672: Add Accept-Language to Vary and XVO headers
1637 * if there's no 'variant' parameter existed in GET.
1640 * /w/index.php?title=Main_page should always be served; but
1641 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1643 function addAcceptLanguage() {
1645 if( !$this->getRequest()->getCheck( 'variant' ) && $wgContLang->hasVariants() ) {
1646 $variants = $wgContLang->getVariants();
1647 $aloption = array();
1648 foreach ( $variants as $variant ) {
1649 if( $variant === $wgContLang->getCode() ) {
1652 $aloption[] = 'string-contains=' . $variant;
1654 // IE and some other browsers use another form of language code
1655 // in their Accept-Language header, like "zh-CN" or "zh-TW".
1656 // We should handle these too.
1657 $ievariant = explode( '-', $variant );
1658 if ( count( $ievariant ) == 2 ) {
1659 $ievariant[1] = strtoupper( $ievariant[1] );
1660 $ievariant = implode( '-', $ievariant );
1661 $aloption[] = 'string-contains=' . $ievariant;
1665 $this->addVaryHeader( 'Accept-Language', $aloption );
1670 * Set a flag which will cause an X-Frame-Options header appropriate for
1671 * edit pages to be sent. The header value is controlled by
1672 * $wgEditPageFrameOptions.
1674 * This is the default for special pages. If you display a CSRF-protected
1675 * form on an ordinary view page, then you need to call this function.
1677 public function preventClickjacking( $enable = true ) {
1678 $this->mPreventClickjacking
= $enable;
1682 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1683 * This can be called from pages which do not contain any CSRF-protected
1686 public function allowClickjacking() {
1687 $this->mPreventClickjacking
= false;
1691 * Get the X-Frame-Options header value (without the name part), or false
1692 * if there isn't one. This is used by Skin to determine whether to enable
1693 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1695 public function getFrameOptions() {
1696 global $wgBreakFrames, $wgEditPageFrameOptions;
1697 if ( $wgBreakFrames ) {
1699 } elseif ( $this->mPreventClickjacking
&& $wgEditPageFrameOptions ) {
1700 return $wgEditPageFrameOptions;
1705 * Send cache control HTTP headers
1707 public function sendCacheControl() {
1708 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgUseXVO;
1710 $response = $this->getRequest()->response();
1711 if ( $wgUseETag && $this->mETag
) {
1712 $response->header( "ETag: $this->mETag" );
1715 $this->addAcceptLanguage();
1717 # don't serve compressed data to clients who can't handle it
1718 # maintain different caches for logged-in users and non-logged in ones
1719 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) ) );
1722 # Add an X-Vary-Options header for Squid with Wikimedia patches
1723 $response->header( $this->getXVO() );
1726 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
1728 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1729 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
1733 # We'll purge the proxy cache explicitly, but require end user agents
1734 # to revalidate against the proxy on each visit.
1735 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1736 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1737 # start with a shorter timeout for initial testing
1738 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1739 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
1740 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1742 # We'll purge the proxy cache for anons explicitly, but require end user agents
1743 # to revalidate against the proxy on each visit.
1744 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1745 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1746 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
1747 # start with a shorter timeout for initial testing
1748 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1749 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
1752 # We do want clients to cache if they can, but they *must* check for updates
1753 # on revisiting the page.
1754 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
1755 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1756 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1758 if($this->mLastModified
) {
1759 $response->header( "Last-Modified: {$this->mLastModified}" );
1762 wfDebug( __METHOD__
. ": no caching **\n", false );
1764 # In general, the absence of a last modified header should be enough to prevent
1765 # the client from using its cache. We send a few other things just to make sure.
1766 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1767 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1768 $response->header( 'Pragma: no-cache' );
1773 * Get the message associed with the HTTP response code $code
1775 * @param $code Integer: status code
1776 * @return String or null: message or null if $code is not in the list of
1779 public static function getStatusMessage( $code ) {
1780 static $statusMessage = array(
1782 101 => 'Switching Protocols',
1783 102 => 'Processing',
1787 203 => 'Non-Authoritative Information',
1788 204 => 'No Content',
1789 205 => 'Reset Content',
1790 206 => 'Partial Content',
1791 207 => 'Multi-Status',
1792 300 => 'Multiple Choices',
1793 301 => 'Moved Permanently',
1796 304 => 'Not Modified',
1798 307 => 'Temporary Redirect',
1799 400 => 'Bad Request',
1800 401 => 'Unauthorized',
1801 402 => 'Payment Required',
1804 405 => 'Method Not Allowed',
1805 406 => 'Not Acceptable',
1806 407 => 'Proxy Authentication Required',
1807 408 => 'Request Timeout',
1810 411 => 'Length Required',
1811 412 => 'Precondition Failed',
1812 413 => 'Request Entity Too Large',
1813 414 => 'Request-URI Too Large',
1814 415 => 'Unsupported Media Type',
1815 416 => 'Request Range Not Satisfiable',
1816 417 => 'Expectation Failed',
1817 422 => 'Unprocessable Entity',
1819 424 => 'Failed Dependency',
1820 500 => 'Internal Server Error',
1821 501 => 'Not Implemented',
1822 502 => 'Bad Gateway',
1823 503 => 'Service Unavailable',
1824 504 => 'Gateway Timeout',
1825 505 => 'HTTP Version Not Supported',
1826 507 => 'Insufficient Storage'
1828 return isset( $statusMessage[$code] ) ?
$statusMessage[$code] : null;
1832 * Finally, all the text has been munged and accumulated into
1833 * the object, let's actually output it:
1835 public function output() {
1836 global $wgOutputEncoding;
1837 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType;
1839 if( $this->mDoNothing
) {
1843 wfProfileIn( __METHOD__
);
1845 $response = $this->getRequest()->response();
1847 if ( $this->mRedirect
!= '' ) {
1848 # Standards require redirect URLs to be absolute
1849 $this->mRedirect
= wfExpandUrl( $this->mRedirect
);
1850 if( $this->mRedirectCode
== '301' ||
$this->mRedirectCode
== '303' ) {
1851 if( !$wgDebugRedirects ) {
1852 $message = self
::getStatusMessage( $this->mRedirectCode
);
1853 $response->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
1855 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1857 $this->sendCacheControl();
1859 $response->header( "Content-Type: text/html; charset=utf-8" );
1860 if( $wgDebugRedirects ) {
1861 $url = htmlspecialchars( $this->mRedirect
);
1862 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1863 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1864 print "</body>\n</html>\n";
1866 $response->header( 'Location: ' . $this->mRedirect
);
1868 wfProfileOut( __METHOD__
);
1870 } elseif ( $this->mStatusCode
) {
1871 $message = self
::getStatusMessage( $this->mStatusCode
);
1873 $response->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
1877 # Buffer output; final headers may depend on later processing
1880 $response->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1881 $response->header( 'Content-language: ' . $wgLanguageCode );
1883 // Prevent framing, if requested
1884 $frameOptions = $this->getFrameOptions();
1885 if ( $frameOptions ) {
1886 $response->header( "X-Frame-Options: $frameOptions" );
1889 if ( $this->mArticleBodyOnly
) {
1890 $this->out( $this->mBodytext
);
1892 $this->addDefaultModules();
1894 $sk = $this->getSkin( $this->getTitle() );
1896 // Hook that allows last minute changes to the output page, e.g.
1897 // adding of CSS or Javascript by extensions.
1898 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1900 wfProfileIn( 'Output-skin' );
1901 $sk->outputPage( $this );
1902 wfProfileOut( 'Output-skin' );
1905 $this->sendCacheControl();
1907 wfProfileOut( __METHOD__
);
1911 * Actually output something with print(). Performs an iconv to the
1912 * output encoding, if needed.
1914 * @param $ins String: the string to output
1916 public function out( $ins ) {
1917 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1918 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1921 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1922 if ( false === $outs ) {
1930 * Produce a "user is blocked" page.
1932 * @param $return Boolean: whether to have a "return to $wgTitle" message or not.
1935 function blockedPage( $return = true ) {
1938 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1939 $this->setRobotPolicy( 'noindex,nofollow' );
1940 $this->setArticleRelated( false );
1942 $name = $this->getUser()->blockedBy();
1943 $reason = $this->getUser()->blockedFor();
1944 if( $reason == '' ) {
1945 $reason = wfMsg( 'blockednoreason' );
1947 $blockTimestamp = $this->getContext()->getLang()->timeanddate(
1948 wfTimestamp( TS_MW
, $this->getUser()->mBlock
->mTimestamp
), true
1952 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1954 $blockid = $this->getUser()->mBlock
->getId();
1956 $blockExpiry = $this->getContext()->getLang()->formatExpiry( $this->getUser()->mBlock
->mExpiry
);
1958 if ( $this->getUser()->mBlock
->mAuto
) {
1959 $msg = 'autoblockedtext';
1961 $msg = 'blockedtext';
1964 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1965 * This could be a username, an IP range, or a single IP. */
1966 $intended = $this->getUser()->mBlock
->getTarget();
1969 $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry,
1970 $intended, $blockTimestamp
1973 # Don't auto-return to special pages
1975 $return = $this->getTitle()->getNamespace() > -1 ?
$this->getTitle() : null;
1976 $this->returnToMain( null, $return );
1981 * Output a standard error page
1983 * @param $title String: message key for page title
1984 * @param $msg String: message key for page text
1985 * @param $params Array: message parameters
1987 public function showErrorPage( $title, $msg, $params = array() ) {
1988 if ( $this->getTitle() ) {
1989 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1991 $this->setPageTitle( wfMsg( $title ) );
1992 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1993 $this->setRobotPolicy( 'noindex,nofollow' );
1994 $this->setArticleRelated( false );
1995 $this->enableClientCache( false );
1996 $this->mRedirect
= '';
1997 $this->mBodytext
= '';
1999 $this->addWikiMsgArray( $msg, $params );
2001 $this->returnToMain();
2005 * Output a standard permission error page
2007 * @param $errors Array: error message keys
2008 * @param $action String: action that was denied or null if unknown
2010 public function showPermissionsErrorPage( $errors, $action = null ) {
2011 $this->mDebugtext
.= 'Original title: ' .
2012 $this->getTitle()->getPrefixedText() . "\n";
2013 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
2014 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
2015 $this->setRobotPolicy( 'noindex,nofollow' );
2016 $this->setArticleRelated( false );
2017 $this->enableClientCache( false );
2018 $this->mRedirect
= '';
2019 $this->mBodytext
= '';
2020 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2024 * Display an error page indicating that a given version of MediaWiki is
2025 * required to use it
2027 * @param $version Mixed: the version of MediaWiki needed to use the page
2029 public function versionRequired( $version ) {
2030 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
2031 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
2032 $this->setRobotPolicy( 'noindex,nofollow' );
2033 $this->setArticleRelated( false );
2034 $this->mBodytext
= '';
2036 $this->addWikiMsg( 'versionrequiredtext', $version );
2037 $this->returnToMain();
2041 * Display an error page noting that a given permission bit is required.
2043 * @param $permission String: key required
2045 public function permissionRequired( $permission ) {
2046 $this->setPageTitle( wfMsg( 'badaccess' ) );
2047 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
2048 $this->setRobotPolicy( 'noindex,nofollow' );
2049 $this->setArticleRelated( false );
2050 $this->mBodytext
= '';
2052 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
2053 User
::getGroupsWithPermission( $permission ) );
2057 $this->getContext()->getLang()->commaList( $groups ),
2061 $this->addWikiMsg( 'badaccess-group0' );
2063 $this->returnToMain();
2067 * Produce the stock "please login to use the wiki" page
2069 public function loginToUse() {
2070 if( $this->getUser()->isLoggedIn() ) {
2071 $this->permissionRequired( 'read' );
2075 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
2076 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
2077 $this->setRobotPolicy( 'noindex,nofollow' );
2078 $this->setArticleRelated( false );
2080 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
2081 $loginLink = $this->getSkin()->link(
2083 wfMsgHtml( 'loginreqlink' ),
2085 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
2086 array( 'known', 'noclasses' )
2088 $this->addWikiMsgArray( 'loginreqpagetext', array( $loginLink ), array( 'replaceafter' ) );
2089 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . '-->' );
2091 # Don't return to the main page if the user can't read it
2092 # otherwise we'll end up in a pointless loop
2093 $mainPage = Title
::newMainPage();
2094 if( $mainPage->userCanRead() ) {
2095 $this->returnToMain( null, $mainPage );
2100 * Format a list of error messages
2102 * @param $errors Array of arrays returned by Title::getUserPermissionsErrors
2103 * @param $action String: action that was denied or null if unknown
2104 * @return String: the wikitext error-messages, formatted into a list.
2106 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2107 if ( $action == null ) {
2108 $text = wfMsgNoTrans( 'permissionserrorstext', count( $errors ) ) . "\n\n";
2110 $action_desc = wfMsgNoTrans( "action-$action" );
2111 $text = wfMsgNoTrans(
2112 'permissionserrorstext-withaction',
2118 if ( count( $errors ) > 1 ) {
2119 $text .= '<ul class="permissions-errors">' . "\n";
2121 foreach( $errors as $error ) {
2123 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
2128 $text .= "<div class=\"permissions-errors\">\n" .
2129 call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) .
2137 * Display a page stating that the Wiki is in read-only mode,
2138 * and optionally show the source of the page that the user
2139 * was trying to edit. Should only be called (for this
2140 * purpose) after wfReadOnly() has returned true.
2142 * For historical reasons, this function is _also_ used to
2143 * show the error message when a user tries to edit a page
2144 * they are not allowed to edit. (Unless it's because they're
2145 * blocked, then we show blockedPage() instead.) In this
2146 * case, the second parameter should be set to true and a list
2147 * of reasons supplied as the third parameter.
2149 * @todo Needs to be split into multiple functions.
2151 * @param $source String: source code to show (or null).
2152 * @param $protected Boolean: is this a permissions error?
2153 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
2154 * @param $action String: action that was denied or null if unknown
2156 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
2157 $this->setRobotPolicy( 'noindex,nofollow' );
2158 $this->setArticleRelated( false );
2160 // If no reason is given, just supply a default "I can't let you do
2161 // that, Dave" message. Should only occur if called by legacy code.
2162 if ( $protected && empty( $reasons ) ) {
2163 $reasons[] = array( 'badaccess-group0' );
2166 if ( !empty( $reasons ) ) {
2167 // Permissions error
2169 $this->setPageTitle( wfMsg( 'viewsource' ) );
2171 wfMsg( 'viewsourcefor', $this->getSkin()->linkKnown( $this->getTitle() ) )
2174 $this->setPageTitle( wfMsg( 'badaccess' ) );
2176 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2178 // Wiki is read only
2179 $this->setPageTitle( wfMsg( 'readonly' ) );
2180 $reason = wfReadOnlyReason();
2181 $this->wrapWikiMsg( "<div class='mw-readonly-error'>\n$1\n</div>", array( 'readonlytext', $reason ) );
2184 // Show source, if supplied
2185 if( is_string( $source ) ) {
2186 $this->addWikiMsg( 'viewsourcetext' );
2189 'id' => 'wpTextbox1',
2190 'name' => 'wpTextbox1',
2191 'cols' => $this->getUser()->getOption( 'cols' ),
2192 'rows' => $this->getUser()->getOption( 'rows' ),
2193 'readonly' => 'readonly'
2195 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
2197 // Show templates used by this article
2198 $skin = $this->getSkin();
2199 $article = new Article( $this->getTitle() );
2200 $this->addHTML( "<div class='templatesUsed'>
2201 {$skin->formatTemplates( $article->getUsedTemplates() )}
2206 # If the title doesn't exist, it's fairly pointless to print a return
2207 # link to it. After all, you just tried editing it and couldn't, so
2208 # what's there to do there?
2209 if( $this->getTitle()->exists() ) {
2210 $this->returnToMain( null, $this->getTitle() );
2215 * Adds JS-based password security checker
2216 * @param $passwordId String ID of input box containing password
2217 * @param $retypeId String ID of input box containing retyped password
2220 public function addPasswordSecurity( $passwordId, $retypeId ) {
2222 'password' => '#' . $passwordId,
2223 'retype' => '#' . $retypeId,
2224 'messages' => array(),
2226 foreach ( array( 'password-strength', 'password-strength-bad', 'password-strength-mediocre',
2227 'password-strength-acceptable', 'password-strength-good', 'password-retype', 'password-retype-mismatch'
2229 $data['messages'][$message] = wfMsg( $message );
2231 $this->addScript( Html
::inlineScript( 'var passwordSecurity=' . FormatJson
::encode( $data ) ) );
2232 $this->addModules( 'mediawiki.legacy.password' );
2235 public function showFatalError( $message ) {
2236 $this->setPageTitle( wfMsg( 'internalerror' ) );
2237 $this->setRobotPolicy( 'noindex,nofollow' );
2238 $this->setArticleRelated( false );
2239 $this->enableClientCache( false );
2240 $this->mRedirect
= '';
2241 $this->mBodytext
= $message;
2244 public function showUnexpectedValueError( $name, $val ) {
2245 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
2248 public function showFileCopyError( $old, $new ) {
2249 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
2252 public function showFileRenameError( $old, $new ) {
2253 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
2256 public function showFileDeleteError( $name ) {
2257 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
2260 public function showFileNotFoundError( $name ) {
2261 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
2265 * Add a "return to" link pointing to a specified title
2267 * @param $title Title to link
2268 * @param $query String: query string
2269 * @param $text String text of the link (input is not escaped)
2271 public function addReturnTo( $title, $query = array(), $text = null ) {
2272 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL() ) );
2275 $this->getSkin()->link( $title, $text, array(), $query )
2277 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2281 * Add a "return to" link pointing to a specified title,
2282 * or the title indicated in the request, or else the main page
2284 * @param $unused No longer used
2285 * @param $returnto Title or String to return to
2286 * @param $returntoquery String: query string for the return to link
2288 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2289 if ( $returnto == null ) {
2290 $returnto = $this->getRequest()->getText( 'returnto' );
2293 if ( $returntoquery == null ) {
2294 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2297 if ( $returnto === '' ) {
2298 $returnto = Title
::newMainPage();
2301 if ( is_object( $returnto ) ) {
2302 $titleObj = $returnto;
2304 $titleObj = Title
::newFromText( $returnto );
2306 if ( !is_object( $titleObj ) ) {
2307 $titleObj = Title
::newMainPage();
2310 $this->addReturnTo( $titleObj, $returntoquery );
2314 * @param $sk Skin The given Skin
2315 * @param $includeStyle Boolean: unused
2316 * @return String: The doctype, opening <html>, and head element.
2318 public function headElement( Skin
$sk, $includeStyle = true ) {
2319 global $wgOutputEncoding, $wgMimeType;
2320 global $wgUseTrackbacks, $wgHtml5;
2322 if ( $sk->commonPrintStylesheet() ) {
2323 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2325 $sk->setupUserCss( $this );
2328 $ret = Html
::htmlHeader( array( 'lang' => $lang->getCode(), 'dir' => $lang->getDir() ) );
2330 if ( $this->getHTMLTitle() == '' ) {
2331 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ) );
2334 $openHead = Html
::openElement( 'head' );
2336 # Don't bother with the newline if $head == ''
2337 $ret .= "$openHead\n";
2340 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2342 $ret .= implode( "\n", array(
2343 $this->getHeadLinks( $sk, true ),
2344 $this->buildCssLinks( $sk ),
2345 $this->getHeadItems()
2348 if ( $wgUseTrackbacks && $this->isArticleRelated() ) {
2349 $ret .= $this->getTitle()->trackbackRDF();
2352 $closeHead = Html
::closeElement( 'head' );
2354 $ret .= "$closeHead\n";
2357 $bodyAttrs = array();
2359 # Crazy edit-on-double-click stuff
2360 $action = $this->getRequest()->getVal( 'action', 'view' );
2363 $this->getTitle()->getNamespace() != NS_SPECIAL
&&
2364 in_array( $action, array( 'view', 'purge' ) ) &&
2365 $this->getUser()->getOption( 'editondblclick' )
2368 $bodyAttrs['ondblclick'] = "document.location = '" . Xml
::escapeJsString( $this->getTitle()->getEditURL() ) . "'";
2372 $dir = wfUILang()->getDir();
2373 $bodyAttrs['class'] = "mediawiki $dir";
2375 if ( $this->getContext()->getLang()->capitalizeAllNouns() ) {
2376 # A <body> class is probably not the best way to do this . . .
2377 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2379 $bodyAttrs['class'] .= ' ' . $sk->getPageClasses( $this->getTitle() );
2380 $bodyAttrs['class'] .= ' skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2382 $sk->addToBodyAttributes( $this, $bodyAttrs ); // Allow skins to add body attributes they need
2383 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2385 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2391 * Add the default ResourceLoader modules to this object
2393 private function addDefaultModules() {
2394 global $wgIncludeLegacyJavaScript,
2395 $wgUseAjax, $wgAjaxWatch, $wgEnableMWSuggest;
2397 // Add base resources
2398 $this->addModules( 'mediawiki.util' );
2399 if( $wgIncludeLegacyJavaScript ){
2400 $this->addModules( 'mediawiki.legacy.wikibits' );
2403 // Add various resources if required
2405 $this->addModules( 'mediawiki.legacy.ajax' );
2407 wfRunHooks( 'AjaxAddScript', array( &$this ) );
2409 if( $wgAjaxWatch && $this->getUser()->isLoggedIn() ) {
2410 $this->addModules( 'mediawiki.action.watch.ajax' );
2413 if ( $wgEnableMWSuggest && !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2414 $this->addModules( 'mediawiki.legacy.mwsuggest' );
2418 if( $this->getUser()->getBoolOption( 'editsectiononrightclick' ) ) {
2419 $this->addModules( 'mediawiki.action.view.rightClickEdit' );
2424 * Get a ResourceLoader object associated with this OutputPage
2426 * @return ResourceLoader
2428 public function getResourceLoader() {
2429 if ( is_null( $this->mResourceLoader
) ) {
2430 $this->mResourceLoader
= new ResourceLoader();
2432 return $this->mResourceLoader
;
2438 * @param $modules Array/string with the module name
2439 * @param $only String ResourceLoaderModule TYPE_ class constant
2440 * @param $useESI boolean
2441 * @return string html <script> and <style> tags
2443 protected function makeResourceLoaderLink( Skin
$skin, $modules, $only, $useESI = false ) {
2444 global $wgLoadScript, $wgResourceLoaderUseESI,
2445 $wgResourceLoaderInlinePrivateModules;
2446 // Lazy-load ResourceLoader
2447 // TODO: Should this be a static function of ResourceLoader instead?
2448 // TODO: Divide off modules starting with "user", and add the user parameter to them
2450 'lang' => $this->getContext()->getLang()->getCode(),
2451 'debug' => ResourceLoader
::inDebugMode() ?
'true' : 'false',
2452 'skin' => $skin->getSkinName(),
2455 // Propagate printable and handheld parameters if present
2456 if ( $this->isPrintable() ) {
2457 $baseQuery['printable'] = 1;
2459 if ( $this->getRequest()->getBool( 'handheld' ) ) {
2460 $baseQuery['handheld'] = 1;
2463 if ( !count( $modules ) ) {
2467 if ( count( $modules ) > 1 ) {
2468 // Remove duplicate module requests
2469 $modules = array_unique( (array) $modules );
2470 // Sort module names so requests are more uniform
2473 if ( ResourceLoader
::inDebugMode() ) {
2474 // Recursively call us for every item
2476 foreach ( $modules as $name ) {
2477 $links .= $this->makeResourceLoaderLink( $skin, $name, $only, $useESI );
2483 // Create keyed-by-group list of module objects from modules list
2485 $resourceLoader = $this->getResourceLoader();
2486 foreach ( (array) $modules as $name ) {
2487 $module = $resourceLoader->getModule( $name );
2488 # Check that we're allowed to include this module on this page
2489 if ( ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2490 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2491 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2492 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2498 $group = $module->getGroup();
2499 if ( !isset( $groups[$group] ) ) {
2500 $groups[$group] = array();
2502 $groups[$group][$name] = $module;
2506 foreach ( $groups as $group => $modules ) {
2507 $query = $baseQuery;
2508 // Special handling for user-specific groups
2509 if ( ( $group === 'user' ||
$group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2510 $query['user'] = $this->getUser()->getName();
2513 // Create a fake request based on the one we are about to make so modules return
2514 // correct timestamp and emptiness data
2515 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2516 // Drop modules that know they're empty
2517 foreach ( $modules as $key => $module ) {
2518 if ( $module->isKnownEmpty( $context ) ) {
2519 unset( $modules[$key] );
2522 // If there are no modules left, skip this group
2523 if ( $modules === array() ) {
2527 $query['modules'] = implode( '|', array_keys( $modules ) );
2529 // Support inlining of private modules if configured as such
2530 if ( $group === 'private' && $wgResourceLoaderInlinePrivateModules ) {
2531 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2532 $links .= Html
::inlineStyle(
2533 $resourceLoader->makeModuleResponse( $context, $modules )
2536 $links .= Html
::inlineScript(
2537 ResourceLoader
::makeLoaderConditionalScript(
2538 $resourceLoader->makeModuleResponse( $context, $modules )
2544 // Special handling for the user group; because users might change their stuff
2545 // on-wiki like user pages, or user preferences; we need to find the highest
2546 // timestamp of these user-changable modules so we can ensure cache misses on change
2547 // This should NOT be done for the site group (bug 27564) because anons get that too
2548 // and we shouldn't be putting timestamps in Squid-cached HTML
2549 if ( $group === 'user' ) {
2550 // Get the maximum timestamp
2552 foreach ( $modules as $module ) {
2553 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2555 // Add a version parameter so cache will break when things change
2556 $query['version'] = wfTimestamp( TS_ISO_8601_BASIC
, $timestamp );
2558 // Make queries uniform in order
2561 $url = wfAppendQuery( $wgLoadScript, $query );
2562 if ( $useESI && $wgResourceLoaderUseESI ) {
2563 $esi = Xml
::element( 'esi:include', array( 'src' => $url ) );
2564 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2565 $link = Html
::inlineStyle( $esi );
2567 $link = Html
::inlineScript( $esi );
2570 // Automatically select style/script elements
2571 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2572 $link = Html
::linkedStyle( wfAppendQuery( $wgLoadScript, $query ) );
2574 $link = Html
::linkedScript( wfAppendQuery( $wgLoadScript, $query ) );
2578 if( $group == 'noscript' ){
2579 $links .= Html
::rawElement( 'noscript', array(), $link ) . "\n";
2581 $links .= $link . "\n";
2588 * Gets the global variables and mScripts; also adds userjs to the end if
2589 * enabled. Despite the name, these scripts are no longer put in the
2590 * <head> but at the bottom of the <body>
2592 * @param $sk Skin object to use
2593 * @return String: HTML fragment
2595 function getHeadScripts( Skin
$sk ) {
2596 global $wgUseSiteJs, $wgAllowUserJs;
2598 // Startup - this will immediately load jquery and mediawiki modules
2599 $scripts = $this->makeResourceLoaderLink( $sk, 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
, true );
2601 // Script and Messages "only" requests
2602 $scripts .= $this->makeResourceLoaderLink( $sk, $this->getModuleScripts( true ), ResourceLoaderModule
::TYPE_SCRIPTS
);
2603 $scripts .= $this->makeResourceLoaderLink( $sk, $this->getModuleMessages( true ), ResourceLoaderModule
::TYPE_MESSAGES
);
2605 // Modules requests - let the client calculate dependencies and batch requests as it likes
2607 if ( $this->getModules( true ) ) {
2608 $loader = Xml
::encodeJsCall( 'mw.loader.load', array( $this->getModules( true ) ) ) .
2609 Xml
::encodeJsCall( 'mw.loader.go', array() );
2612 $scripts .= Html
::inlineScript(
2613 ResourceLoader
::makeLoaderConditionalScript(
2614 ResourceLoader
::makeConfigSetScript( $this->getJSVars() ) . $loader
2619 $scripts .= "\n" . $this->mScripts
;
2621 $userScripts = array( 'user.options' );
2623 // Add site JS if enabled
2624 if ( $wgUseSiteJs ) {
2625 $scripts .= $this->makeResourceLoaderLink( $sk, 'site', ResourceLoaderModule
::TYPE_SCRIPTS
);
2626 if( $this->getUser()->isLoggedIn() ){
2627 $userScripts[] = 'user.groups';
2631 // Add user JS if enabled
2632 if ( $wgAllowUserJs && $this->getUser()->isLoggedIn() ) {
2633 $action = $this->getRequest()->getVal( 'action', 'view' );
2634 if( $this->getTitle() && $this->getTitle()->isJsSubpage() && $sk->userCanPreview( $action ) ) {
2635 # XXX: additional security check/prompt?
2636 $scripts .= Html
::inlineScript( "\n" . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2638 # FIXME: this means that User:Me/Common.js doesn't load when previewing
2639 # User:Me/Vector.js, and vice versa (bug26283)
2640 $userScripts[] = 'user';
2643 $scripts .= $this->makeResourceLoaderLink( $sk, $userScripts, ResourceLoaderModule
::TYPE_SCRIPTS
);
2649 * Get an array containing global JS variables
2651 * Do not add things here which can be evaluated in
2652 * ResourceLoaderStartupScript - in other words, without state.
2653 * You will only be adding bloat to the page and causing page caches to
2654 * have to be purged on configuration changes.
2656 protected function getJSVars() {
2657 global $wgUseAjax, $wgEnableMWSuggest, $wgContLang;
2659 $title = $this->getTitle();
2660 $ns = $title->getNamespace();
2661 $nsname = MWNamespace
::exists( $ns ) ? MWNamespace
::getCanonicalName( $ns ) : $title->getNsText();
2662 if ( $ns == NS_SPECIAL
) {
2663 $parts = SpecialPage
::resolveAliasWithSubpage( $title->getDBkey() );
2664 $canonicalName = $parts[0];
2666 $canonicalName = false; # bug 21115
2670 'wgCanonicalNamespace' => $nsname,
2671 'wgCanonicalSpecialPageName' => $canonicalName,
2672 'wgNamespaceNumber' => $title->getNamespace(),
2673 'wgPageName' => $title->getPrefixedDBKey(),
2674 'wgTitle' => $title->getText(),
2675 'wgCurRevisionId' => $title->getLatestRevID(),
2676 'wgArticleId' => $title->getArticleId(),
2677 'wgIsArticle' => $this->isArticle(),
2678 'wgAction' => $this->getRequest()->getText( 'action', 'view' ),
2679 'wgUserName' => $this->getUser()->isAnon() ?
null : $this->getUser()->getName(),
2680 'wgUserGroups' => $this->getUser()->getEffectiveGroups(),
2681 'wgCategories' => $this->getCategories(),
2682 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
2684 if ( $wgContLang->hasVariants() ) {
2685 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
2687 foreach ( $title->getRestrictionTypes() as $type ) {
2688 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
2690 if ( $wgUseAjax && $wgEnableMWSuggest && !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2691 $vars['wgSearchNamespaces'] = SearchEngine
::userNamespaces( $this->getUser() );
2694 // Allow extensions to add their custom variables to the global JS variables
2695 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars ) );
2701 * @return string HTML tag links to be put in the header.
2703 public function getHeadLinks( Skin
$sk, $addContentType = false ) {
2704 global $wgUniversalEditButton, $wgFavicon, $wgAppleTouchIcon, $wgEnableAPI,
2705 $wgSitename, $wgVersion, $wgHtml5, $wgMimeType, $wgOutputEncoding,
2706 $wgFeed, $wgOverrideSiteFeed, $wgAdvertisedFeedTypes,
2707 $wgEnableDublinCoreRdf, $wgEnableCreativeCommonsRdf,
2708 $wgDisableLangConversion, $wgCanonicalLanguageLinks, $wgContLang,
2709 $wgRightsPage, $wgRightsUrl;
2713 if ( $addContentType ) {
2715 # More succinct than <meta http-equiv=Content-Type>, has the
2717 $tags[] = Html
::element( 'meta', array( 'charset' => $wgOutputEncoding ) );
2719 $tags[] = Html
::element( 'meta', array(
2720 'http-equiv' => 'Content-Type',
2721 'content' => "$wgMimeType; charset=$wgOutputEncoding"
2723 $tags[] = Html
::element( 'meta', array( // bug 15835
2724 'http-equiv' => 'Content-Style-Type',
2725 'content' => 'text/css'
2730 $tags[] = Html
::element( 'meta', array(
2731 'name' => 'generator',
2732 'content' => "MediaWiki $wgVersion",
2735 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
2736 if( $p !== 'index,follow' ) {
2737 // http://www.robotstxt.org/wc/meta-user.html
2738 // Only show if it's different from the default robots policy
2739 $tags[] = Html
::element( 'meta', array(
2745 if ( count( $this->mKeywords
) > 0 ) {
2747 "/<.*?" . ">/" => '',
2750 $tags[] = Html
::element( 'meta', array(
2751 'name' => 'keywords',
2752 'content' => preg_replace(
2753 array_keys( $strip ),
2754 array_values( $strip ),
2755 implode( ',', $this->mKeywords
)
2760 foreach ( $this->mMetatags
as $tag ) {
2761 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
2763 $tag[0] = substr( $tag[0], 5 );
2767 $tags[] = Html
::element( 'meta',
2770 'content' => $tag[1]
2775 foreach ( $this->mLinktags
as $tag ) {
2776 $tags[] = Html
::element( 'link', $tag );
2779 # Universal edit button
2780 if ( $wgUniversalEditButton ) {
2781 if ( $this->isArticleRelated() && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
2782 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create' ) ) ) {
2783 // Original UniversalEditButton
2784 $msg = wfMsg( 'edit' );
2785 $tags[] = Html
::element( 'link', array(
2786 'rel' => 'alternate',
2787 'type' => 'application/x-wiki',
2789 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
2791 // Alternate edit link
2792 $tags[] = Html
::element( 'link', array(
2795 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
2800 # Generally the order of the favicon and apple-touch-icon links
2801 # should not matter, but Konqueror (3.5.9 at least) incorrectly
2802 # uses whichever one appears later in the HTML source. Make sure
2803 # apple-touch-icon is specified first to avoid this.
2804 if ( $wgAppleTouchIcon !== false ) {
2805 $tags[] = Html
::element( 'link', array( 'rel' => 'apple-touch-icon', 'href' => $wgAppleTouchIcon ) );
2808 if ( $wgFavicon !== false ) {
2809 $tags[] = Html
::element( 'link', array( 'rel' => 'shortcut icon', 'href' => $wgFavicon ) );
2812 # OpenSearch description link
2813 $tags[] = Html
::element( 'link', array(
2815 'type' => 'application/opensearchdescription+xml',
2816 'href' => wfScript( 'opensearch_desc' ),
2817 'title' => wfMsgForContent( 'opensearch-desc' ),
2820 if ( $wgEnableAPI ) {
2821 # Real Simple Discovery link, provides auto-discovery information
2822 # for the MediaWiki API (and potentially additional custom API
2823 # support such as WordPress or Twitter-compatible APIs for a
2824 # blogging extension, etc)
2825 $tags[] = Html
::element( 'link', array(
2827 'type' => 'application/rsd+xml',
2828 'href' => wfExpandUrl( wfAppendQuery( wfScript( 'api' ), array( 'action' => 'rsd' ) ) ),
2833 # - Creative Commons
2834 # See http://wiki.creativecommons.org/Extend_Metadata.
2836 # Use hreflang to specify canonical and alternate links
2837 # See http://www.google.com/support/webmasters/bin/answer.py?answer=189077
2838 if ( $this->isArticleRelated() ) {
2839 # note: buggy CC software only reads first "meta" link
2840 if ( $wgEnableCreativeCommonsRdf ) {
2841 $tags[] = Html
::element( 'link', array(
2842 'rel' => $this->getMetadataAttribute(),
2843 'title' => 'Creative Commons',
2844 'type' => 'application/rdf+xml',
2845 'href' => $this->getTitle()->getLocalURL( 'action=creativecommons' ) )
2849 if ( $wgEnableDublinCoreRdf ) {
2850 $tags[] = Html
::element( 'link', array(
2851 'rel' => $this->getMetadataAttribute(),
2852 'title' => 'Dublin Core',
2853 'type' => 'application/rdf+xml',
2854 'href' => $this->getTitle()->getLocalURL( 'action=dublincore' ) )
2860 if ( !$wgDisableLangConversion && $wgCanonicalLanguageLinks
2861 && $wgContLang->hasVariants() ) {
2863 $urlvar = $wgContLang->getURLVariant();
2866 $variants = $wgContLang->getVariants();
2867 foreach ( $variants as $_v ) {
2868 $tags[] = Html
::element( 'link', array(
2869 'rel' => 'alternate',
2871 'href' => $this->getTitle()->getLocalURL( '', $_v ) )
2875 $tags[] = Html
::element( 'link', array(
2876 'rel' => 'canonical',
2877 'href' => $this->getTitle()->getFullURL() )
2884 if ( $wgRightsPage ) {
2885 $copy = Title
::newFromText( $wgRightsPage );
2888 $copyright = $copy->getLocalURL();
2892 if ( !$copyright && $wgRightsUrl ) {
2893 $copyright = $wgRightsUrl;
2897 $tags[] = Html
::element( 'link', array(
2898 'rel' => 'copyright',
2899 'href' => $copyright )
2905 foreach( $this->getSyndicationLinks() as $format => $link ) {
2906 # Use the page name for the title (accessed through $wgTitle since
2907 # there's no other way). In principle, this could lead to issues
2908 # with having the same name for different feeds corresponding to
2909 # the same page, but we can't avoid that at this low a level.
2911 $tags[] = $this->feedLink(
2914 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
2915 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )
2919 # Recent changes feed should appear on every page (except recentchanges,
2920 # that would be redundant). Put it after the per-page feed to avoid
2921 # changing existing behavior. It's still available, probably via a
2922 # menu in your browser. Some sites might have a different feed they'd
2923 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
2924 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
2925 # If so, use it instead.
2927 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
2929 if ( $wgOverrideSiteFeed ) {
2930 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
2931 $tags[] = $this->feedLink(
2933 htmlspecialchars( $feedUrl ),
2934 wfMsg( "site-{$type}-feed", $wgSitename )
2937 } elseif ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
2938 foreach ( $wgAdvertisedFeedTypes as $format ) {
2939 $tags[] = $this->feedLink(
2941 $rctitle->getLocalURL( "feed={$format}" ),
2942 wfMsg( "site-{$format}-feed", $wgSitename ) # For grep: 'site-rss-feed', 'site-atom-feed'.
2947 return implode( "\n", $tags );
2951 * Generate a <link rel/> for a feed.
2953 * @param $type String: feed type
2954 * @param $url String: URL to the feed
2955 * @param $text String: value of the "title" attribute
2956 * @return String: HTML fragment
2958 private function feedLink( $type, $url, $text ) {
2959 return Html
::element( 'link', array(
2960 'rel' => 'alternate',
2961 'type' => "application/$type+xml",
2968 * Add a local or specified stylesheet, with the given media options.
2969 * Meant primarily for internal use...
2971 * @param $style String: URL to the file
2972 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
2973 * @param $condition String: for IE conditional comments, specifying an IE version
2974 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
2976 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
2978 // Even though we expect the media type to be lowercase, but here we
2979 // force it to lowercase to be safe.
2981 $options['media'] = $media;
2984 $options['condition'] = $condition;
2987 $options['dir'] = $dir;
2989 $this->styles
[$style] = $options;
2993 * Adds inline CSS styles
2994 * @param $style_css Mixed: inline CSS
2996 public function addInlineStyle( $style_css ){
2997 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3001 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
3002 * These will be applied to various media & IE conditionals.
3003 * @param $sk Skin object
3005 public function buildCssLinks( $sk ) {
3007 // Add ResourceLoader styles
3008 // Split the styles into four groups
3009 $styles = array( 'other' => array(), 'user' => array(), 'site' => array(), 'private' => array(), 'noscript' => array() );
3010 $resourceLoader = $this->getResourceLoader();
3011 foreach ( $this->getModuleStyles() as $name ) {
3012 $group = $resourceLoader->getModule( $name )->getGroup();
3013 // Modules in groups named "other" or anything different than "user", "site" or "private"
3014 // will be placed in the "other" group
3015 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
3018 // We want site, private and user styles to override dynamically added styles from modules, but we want
3019 // dynamically added styles to override statically added styles from other modules. So the order
3020 // has to be other, dynamic, site, private, user
3021 // Add statically added styles for other modules
3022 $ret .= $this->makeResourceLoaderLink( $sk, $styles['other'], ResourceLoaderModule
::TYPE_STYLES
);
3023 // Add normal styles added through addStyle()/addInlineStyle() here
3024 $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3025 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3026 // We use a <meta> tag with a made-up name for this because that's valid HTML
3027 $ret .= Html
::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) ) . "\n";
3029 // Add site, private and user styles
3030 // 'private' at present only contains user.options, so put that before 'user'
3031 // Any future private modules will likely have a similar user-specific character
3032 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3033 $ret .= $this->makeResourceLoaderLink( $sk, $styles[$group],
3034 ResourceLoaderModule
::TYPE_STYLES
3040 public function buildCssLinksArray() {
3042 foreach( $this->styles
as $file => $options ) {
3043 $link = $this->styleLink( $file, $options );
3045 $links[$file] = $link;
3052 * Generate \<link\> tags for stylesheets
3054 * @param $style String: URL to the file
3055 * @param $options Array: option, can contain 'condition', 'dir', 'media'
3057 * @return String: HTML fragment
3059 protected function styleLink( $style, $options ) {
3060 if( isset( $options['dir'] ) ) {
3061 $siteDir = wfUILang()->getDir();
3062 if( $siteDir != $options['dir'] ) {
3067 if( isset( $options['media'] ) ) {
3068 $media = self
::transformCssMedia( $options['media'] );
3069 if( is_null( $media ) ) {
3076 if( substr( $style, 0, 1 ) == '/' ||
3077 substr( $style, 0, 5 ) == 'http:' ||
3078 substr( $style, 0, 6 ) == 'https:' ) {
3081 global $wgStylePath, $wgStyleVersion;
3082 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
3085 $link = Html
::linkedStyle( $url, $media );
3087 if( isset( $options['condition'] ) ) {
3088 $condition = htmlspecialchars( $options['condition'] );
3089 $link = "<!--[if $condition]>$link<![endif]-->";
3095 * Transform "media" attribute based on request parameters
3097 * @param $media String: current value of the "media" attribute
3098 * @return String: modified value of the "media" attribute
3100 public static function transformCssMedia( $media ) {
3101 global $wgRequest, $wgHandheldForIPhone;
3103 // Switch in on-screen display for media testing
3105 'printable' => 'print',
3106 'handheld' => 'handheld',
3108 foreach( $switches as $switch => $targetMedia ) {
3109 if( $wgRequest->getBool( $switch ) ) {
3110 if( $media == $targetMedia ) {
3112 } elseif( $media == 'screen' ) {
3118 // Expand longer media queries as iPhone doesn't grok 'handheld'
3119 if( $wgHandheldForIPhone ) {
3120 $mediaAliases = array(
3121 'screen' => 'screen and (min-device-width: 481px)',
3122 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
3125 if( isset( $mediaAliases[$media] ) ) {
3126 $media = $mediaAliases[$media];
3134 * Turn off regular page output and return an error reponse
3135 * for when rate limiting has triggered.
3137 public function rateLimited() {
3138 $this->setPageTitle( wfMsg( 'actionthrottled' ) );
3139 $this->setRobotPolicy( 'noindex,follow' );
3140 $this->setArticleRelated( false );
3141 $this->enableClientCache( false );
3142 $this->mRedirect
= '';
3144 $this->setStatusCode( 503 );
3145 $this->addWikiMsg( 'actionthrottledtext' );
3147 $this->returnToMain( null, $this->getTitle() );
3151 * Show a warning about slave lag
3153 * If the lag is higher than $wgSlaveLagCritical seconds,
3154 * then the warning is a bit more obvious. If the lag is
3155 * lower than $wgSlaveLagWarning, then no warning is shown.
3157 * @param $lag Integer: slave lag
3159 public function showLagWarning( $lag ) {
3160 global $wgSlaveLagWarning, $wgSlaveLagCritical;
3161 if( $lag >= $wgSlaveLagWarning ) {
3162 $message = $lag < $wgSlaveLagCritical
3165 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
3166 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getContext()->getLang()->formatNum( $lag ) ) );
3171 * Add a wikitext-formatted message to the output.
3172 * This is equivalent to:
3174 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
3176 public function addWikiMsg( /*...*/ ) {
3177 $args = func_get_args();
3178 $name = array_shift( $args );
3179 $this->addWikiMsgArray( $name, $args );
3183 * Add a wikitext-formatted message to the output.
3184 * Like addWikiMsg() except the parameters are taken as an array
3185 * instead of a variable argument list.
3187 * $options is passed through to wfMsgExt(), see that function for details.
3189 public function addWikiMsgArray( $name, $args, $options = array() ) {
3190 $options[] = 'parse';
3191 $text = wfMsgExt( $name, $options, $args );
3192 $this->addHTML( $text );
3196 * This function takes a number of message/argument specifications, wraps them in
3197 * some overall structure, and then parses the result and adds it to the output.
3199 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3200 * on. The subsequent arguments may either be strings, in which case they are the
3201 * message names, or arrays, in which case the first element is the message name,
3202 * and subsequent elements are the parameters to that message.
3204 * The special named parameter 'options' in a message specification array is passed
3205 * through to the $options parameter of wfMsgExt().
3207 * Don't use this for messages that are not in users interface language.
3211 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3215 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . "\n</div>" );
3217 * The newline after opening div is needed in some wikitext. See bug 19226.
3219 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3220 $msgSpecs = func_get_args();
3221 array_shift( $msgSpecs );
3222 $msgSpecs = array_values( $msgSpecs );
3224 foreach ( $msgSpecs as $n => $spec ) {
3226 if ( is_array( $spec ) ) {
3228 $name = array_shift( $args );
3229 if ( isset( $args['options'] ) ) {
3230 $options = $args['options'];
3231 unset( $args['options'] );
3237 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
3239 $this->addWikiText( $s );
3243 * Include jQuery core. Use this to avoid loading it multiple times
3244 * before we get a usable script loader.
3246 * @param $modules Array: list of jQuery modules which should be loaded
3247 * @return Array: the list of modules which were not loaded.
3249 * @deprecated since 1.17
3251 public function includeJQuery( $modules = array() ) {