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 * @todo FIXME: Another class 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 HTTP/1.1 protocol 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 // @todo FIXME: Next variables probably comes from the resource loader
119 var $mModules = array(), $mModuleScripts = array(), $mModuleStyles = array(), $mModuleMessages = array();
120 var $mResourceLoader;
122 /** @todo FIXME: Is this still used ?*/
123 var $mInlineMsg = array();
125 var $mTemplateIds = array();
126 var $mImageTimeKeys = array();
128 var $mRedirectCode = '';
130 var $mFeedLinksAppendQuery = null;
132 # What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
133 # @see ResourceLoaderModule::$origin
134 # ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
135 protected $mAllowedModules = array(
136 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
140 * @EasterEgg I just love the name for this self documenting variable.
143 var $mDoNothing = false;
146 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
149 * Should be private. Has get/set methods properly documented.
150 * Stores "article flag" toggle.
152 var $mIsArticleRelated = true;
154 /// lazy initialised, use parserOptions()
155 protected $mParserOptions = null;
158 * Handles the atom / rss links.
159 * We probably only support atom in 2011.
160 * Looks like a private variable.
161 * @see $wgAdvertisedFeedTypes
163 var $mFeedLinks = array();
165 // Gwicke work on squid caching? Roughly from 2003.
166 var $mEnableClientCache = true;
169 * Flag if output should only contain the body of the article.
172 var $mArticleBodyOnly = false;
174 var $mNewSectionLink = false;
175 var $mHideNewSectionLink = false;
178 * Comes from the parser. This was probably made to load CSS/JS only
179 * if we had <gallery>. Used directly in CategoryPage.php
180 * Looks like resource loader can replace this.
182 var $mNoGallery = false;
184 // should be private.
185 var $mPageTitleActionText = '';
186 var $mParseWarnings = array();
188 // Cache stuff. Looks like mEnableClientCache
189 var $mSquidMaxage = 0;
192 var $mPreventClickjacking = true;
194 /// should be private. To include the variable {{REVISIONID}}
195 var $mRevisionId = null;
197 var $mFileVersion = null;
202 * An array of stylesheet filenames (relative from skins path), with options
203 * for CSS media, IE conditions, and RTL/LTR direction.
204 * For internal use; add settings in the skin via $this->addStyle()
206 * Style again! This seems like a code duplication since we already have
207 * mStyles. This is what makes OpenSource amazing.
209 var $styles = array();
212 * Whether jQuery is already handled.
214 protected $mJQueryDone = false;
216 private $mIndexPolicy = 'index';
217 private $mFollowPolicy = 'follow';
218 private $mVaryHeader = array(
219 'Accept-Encoding' => array( 'list-contains=gzip' ),
224 * Constructor for OutputPage. This should not be called directly.
225 * Instead a new RequestContext should be created and it will implicitly create
226 * a OutputPage tied to that context.
228 function __construct( RequestContext
$context = null ) {
229 if ( !isset($context) ) {
230 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
231 wfDeprecated( __METHOD__
);
233 $this->mContext
= $context;
237 * Redirect to $url rather than displaying the normal page
239 * @param $url String: URL
240 * @param $responsecode String: HTTP status code
242 public function redirect( $url, $responsecode = '302' ) {
243 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
244 $this->mRedirect
= str_replace( "\n", '', $url );
245 $this->mRedirectCode
= $responsecode;
249 * Get the URL to redirect to, or an empty string if not redirect URL set
253 public function getRedirect() {
254 return $this->mRedirect
;
258 * Set the HTTP status code to send with the output.
260 * @param $statusCode Integer
262 public function setStatusCode( $statusCode ) {
263 $this->mStatusCode
= $statusCode;
267 * Add a new <meta> tag
268 * To add an http-equiv meta tag, precede the name with "http:"
270 * @param $name String tag name
271 * @param $val String tag value
273 function addMeta( $name, $val ) {
274 array_push( $this->mMetatags
, array( $name, $val ) );
278 * Add a keyword or a list of keywords in the page header
280 * @param $text String or array of strings
282 function addKeyword( $text ) {
283 if( is_array( $text ) ) {
284 $this->mKeywords
= array_merge( $this->mKeywords
, $text );
286 array_push( $this->mKeywords
, $text );
291 * Add a new \<link\> tag to the page header
293 * @param $linkarr Array: associative array of attributes.
295 function addLink( $linkarr ) {
296 array_push( $this->mLinktags
, $linkarr );
300 * Add a new \<link\> with "rel" attribute set to "meta"
302 * @param $linkarr Array: associative array mapping attribute names to their
303 * values, both keys and values will be escaped, and the
304 * "rel" attribute will be automatically added
306 function addMetadataLink( $linkarr ) {
307 $linkarr['rel'] = $this->getMetadataAttribute();
308 $this->addLink( $linkarr );
312 * Get the value of the "rel" attribute for metadata links
316 public function getMetadataAttribute() {
317 # note: buggy CC software only reads first "meta" link
318 static $haveMeta = false;
320 return 'alternate meta';
328 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
330 * @param $script String: raw HTML
332 function addScript( $script ) {
333 $this->mScripts
.= $script . "\n";
337 * Register and add a stylesheet from an extension directory.
339 * @param $url String path to sheet. Provide either a full url (beginning
340 * with 'http', etc) or a relative path from the document root
341 * (beginning with '/'). Otherwise it behaves identically to
342 * addStyle() and draws from the /skins folder.
344 public function addExtensionStyle( $url ) {
345 array_push( $this->mExtStyles
, $url );
349 * Get all styles added by extensions
353 function getExtStyle() {
354 return $this->mExtStyles
;
358 * Add a JavaScript file out of skins/common, or a given relative path.
360 * @param $file String: filename in skins/common or complete on-server path
362 * @param $version String: style version of the file. Defaults to $wgStyleVersion
364 public function addScriptFile( $file, $version = null ) {
365 global $wgStylePath, $wgStyleVersion;
366 // See if $file parameter is an absolute URL or begins with a slash
367 if( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
370 $path = "{$wgStylePath}/common/{$file}";
372 if ( is_null( $version ) )
373 $version = $wgStyleVersion;
374 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
378 * Add a self-contained script tag with the given contents
380 * @param $script String: JavaScript text, no <script> tags
382 public function addInlineScript( $script ) {
383 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
387 * Get all registered JS and CSS tags for the header.
391 function getScript() {
392 return $this->mScripts
. $this->getHeadItems();
396 * Filter an array of modules to remove insufficiently trustworthy members, and modules
397 * which are no longer registered (eg a page is cached before an extension is disabled)
398 * @param $modules Array
399 * @param $position String if not null, only return modules with this position
400 * @param $type string
403 protected function filterModules( $modules, $position = null, $type = ResourceLoaderModule
::TYPE_COMBINED
){
404 $resourceLoader = $this->getResourceLoader();
405 $filteredModules = array();
406 foreach( $modules as $val ){
407 $module = $resourceLoader->getModule( $val );
408 if( $module instanceof ResourceLoaderModule
409 && $module->getOrigin() <= $this->getAllowedModules( $type )
410 && ( is_null( $position ) ||
$module->getPosition() == $position ) )
412 $filteredModules[] = $val;
415 return $filteredModules;
419 * Get the list of modules to include on this page
421 * @param $filter Bool whether to filter out insufficiently trustworthy modules
422 * @param $position String if not null, only return modules with this position
423 * @param $param string
424 * @return Array of module names
426 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
427 $modules = array_values( array_unique( $this->$param ) );
429 ?
$this->filterModules( $modules, $position )
434 * Add one or more modules recognized by the resource loader. Modules added
435 * through this function will be loaded by the resource loader when the
438 * @param $modules Mixed: module name (string) or array of module names
440 public function addModules( $modules ) {
441 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
445 * Get the list of module JS to include on this page
450 * @return array of module names
452 public function getModuleScripts( $filter = false, $position = null ) {
453 return $this->getModules( $filter, $position, 'mModuleScripts' );
457 * Add only JS of one or more modules recognized by the resource loader. Module
458 * scripts added through this function will be loaded by the resource loader when
461 * @param $modules Mixed: module name (string) or array of module names
463 public function addModuleScripts( $modules ) {
464 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
468 * Get the list of module CSS to include on this page
473 * @return Array of module names
475 public function getModuleStyles( $filter = false, $position = null ) {
476 return $this->getModules( $filter, $position, 'mModuleStyles' );
480 * Add only CSS of one or more modules recognized by the resource loader. Module
481 * styles added through this function will be loaded by the resource loader when
484 * @param $modules Mixed: module name (string) or array of module names
486 public function addModuleStyles( $modules ) {
487 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
491 * Get the list of module messages to include on this page
496 * @return Array of module names
498 public function getModuleMessages( $filter = false, $position = null ) {
499 return $this->getModules( $filter, $position, 'mModuleMessages' );
503 * Add only messages of one or more modules recognized by the resource loader.
504 * Module messages added through this function will be loaded by the resource
505 * loader when the page loads.
507 * @param $modules Mixed: module name (string) or array of module names
509 public function addModuleMessages( $modules ) {
510 $this->mModuleMessages
= array_merge( $this->mModuleMessages
, (array)$modules );
514 * Get all header items in a string
518 function getHeadItems() {
520 foreach ( $this->mHeadItems
as $item ) {
527 * Add or replace an header item to the output
529 * @param $name String: item name
530 * @param $value String: raw HTML
532 public function addHeadItem( $name, $value ) {
533 $this->mHeadItems
[$name] = $value;
537 * Check if the header item $name is already set
539 * @param $name String: item name
542 public function hasHeadItem( $name ) {
543 return isset( $this->mHeadItems
[$name] );
547 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
549 * @param $tag String: value of "ETag" header
551 function setETag( $tag ) {
556 * Set whether the output should only contain the body of the article,
557 * without any skin, sidebar, etc.
558 * Used e.g. when calling with "action=render".
560 * @param $only Boolean: whether to output only the body of the article
562 public function setArticleBodyOnly( $only ) {
563 $this->mArticleBodyOnly
= $only;
567 * Return whether the output will contain only the body of the article
571 public function getArticleBodyOnly() {
572 return $this->mArticleBodyOnly
;
576 * checkLastModified tells the client to use the client-cached page if
577 * possible. If sucessful, the OutputPage is disabled so that
578 * any future call to OutputPage->output() have no effect.
580 * Side effect: sets mLastModified for Last-Modified header
582 * @param $timestamp string
584 * @return Boolean: true iff cache-ok headers was sent.
586 public function checkLastModified( $timestamp ) {
587 global $wgCachePages, $wgCacheEpoch;
589 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
590 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
593 if( !$wgCachePages ) {
594 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
597 if( $this->getUser()->getOption( 'nocache' ) ) {
598 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
602 $timestamp = wfTimestamp( TS_MW
, $timestamp );
603 $modifiedTimes = array(
604 'page' => $timestamp,
605 'user' => $this->getUser()->getTouched(),
606 'epoch' => $wgCacheEpoch
608 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
610 $maxModified = max( $modifiedTimes );
611 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
613 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
614 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
620 foreach ( $modifiedTimes as $name => $value ) {
621 if ( $info !== '' ) {
624 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
627 # IE sends sizes after the date like this:
628 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
629 # this breaks strtotime().
630 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
632 wfSuppressWarnings(); // E_STRICT system time bitching
633 $clientHeaderTime = strtotime( $clientHeader );
635 if ( !$clientHeaderTime ) {
636 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
639 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
641 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
642 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
643 wfDebug( __METHOD__
. ": effective Last-Modified: " .
644 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
645 if( $clientHeaderTime < $maxModified ) {
646 wfDebug( __METHOD__
. ": STALE, $info\n", false );
651 # Give a 304 response code and disable body output
652 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
653 ini_set( 'zlib.output_compression', 0 );
654 $this->getRequest()->response()->header( "HTTP/1.1 304 Not Modified" );
655 $this->sendCacheControl();
658 // Don't output a compressed blob when using ob_gzhandler;
659 // it's technically against HTTP spec and seems to confuse
660 // Firefox when the response gets split over two packets.
661 wfClearOutputBuffers();
667 * Override the last modified timestamp
669 * @param $timestamp String: new timestamp, in a format readable by
672 public function setLastModified( $timestamp ) {
673 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
677 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
679 * @param $policy String: the literal string to output as the contents of
680 * the meta tag. Will be parsed according to the spec and output in
684 public function setRobotPolicy( $policy ) {
685 $policy = Article
::formatRobotPolicy( $policy );
687 if( isset( $policy['index'] ) ) {
688 $this->setIndexPolicy( $policy['index'] );
690 if( isset( $policy['follow'] ) ) {
691 $this->setFollowPolicy( $policy['follow'] );
696 * Set the index policy for the page, but leave the follow policy un-
699 * @param $policy string Either 'index' or 'noindex'.
702 public function setIndexPolicy( $policy ) {
703 $policy = trim( $policy );
704 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
705 $this->mIndexPolicy
= $policy;
710 * Set the follow policy for the page, but leave the index policy un-
713 * @param $policy String: either 'follow' or 'nofollow'.
716 public function setFollowPolicy( $policy ) {
717 $policy = trim( $policy );
718 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
719 $this->mFollowPolicy
= $policy;
724 * Set the new value of the "action text", this will be added to the
725 * "HTML title", separated from it with " - ".
727 * @param $text String: new value of the "action text"
729 public function setPageTitleActionText( $text ) {
730 $this->mPageTitleActionText
= $text;
734 * Get the value of the "action text"
738 public function getPageTitleActionText() {
739 if ( isset( $this->mPageTitleActionText
) ) {
740 return $this->mPageTitleActionText
;
745 * "HTML title" means the contents of <title>.
746 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
748 * @param $name string
750 public function setHTMLTitle( $name ) {
751 $this->mHTMLtitle
= $name;
755 * Return the "HTML title", i.e. the content of the <title> tag.
759 public function getHTMLTitle() {
760 return $this->mHTMLtitle
;
764 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
765 * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
766 * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
767 * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
769 * @param $name string
771 public function setPageTitle( $name ) {
772 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
773 # but leave "<i>foobar</i>" alone
774 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
775 $this->mPagetitle
= $nameWithTags;
777 # change "<i>foo&bar</i>" to "foo&bar"
778 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer
::stripAllTags( $nameWithTags ) ) );
782 * Return the "page title", i.e. the content of the \<h1\> tag.
786 public function getPageTitle() {
787 return $this->mPagetitle
;
791 * Get the RequestContext used in this instance
793 * @return RequestContext
795 private function getContext() {
796 if ( !isset($this->mContext
) ) {
797 wfDebug( __METHOD__
. " called and \$mContext is null. Using RequestContext::getMain(); for sanity\n" );
798 $this->mContext
= RequestContext
::getMain();
800 return $this->mContext
;
804 * Get the WebRequest being used for this instance
809 public function getRequest() {
810 return $this->getContext()->getRequest();
814 * Set the Title object to use
816 * @param $t Title object
818 public function setTitle( $t ) {
819 $this->getContext()->setTitle( $t );
823 * Get the Title object used in this instance
827 public function getTitle() {
828 return $this->getContext()->getTitle();
832 * Get the User object used in this instance
837 public function getUser() {
838 return $this->getContext()->getUser();
842 * Get the Skin object used to render this instance
847 public function getSkin() {
848 return $this->getContext()->getSkin();
852 * Replace the subtile with $str
854 * @param $str String: new value of the subtitle
856 public function setSubtitle( $str ) {
857 $this->mSubtitle
= /*$this->parse(*/ $str /*)*/; // @bug 2514
861 * Add $str to the subtitle
863 * @param $str String to add to the subtitle
865 public function appendSubtitle( $str ) {
866 $this->mSubtitle
.= /*$this->parse(*/ $str /*)*/; // @bug 2514
874 public function getSubtitle() {
875 return $this->mSubtitle
;
879 * Set the page as printable, i.e. it'll be displayed with with all
880 * print styles included
882 public function setPrintable() {
883 $this->mPrintable
= true;
887 * Return whether the page is "printable"
891 public function isPrintable() {
892 return $this->mPrintable
;
896 * Disable output completely, i.e. calling output() will have no effect
898 public function disable() {
899 $this->mDoNothing
= true;
903 * Return whether the output will be completely disabled
907 public function isDisabled() {
908 return $this->mDoNothing
;
912 * Show an "add new section" link?
916 public function showNewSectionLink() {
917 return $this->mNewSectionLink
;
921 * Forcibly hide the new section link?
925 public function forceHideNewSectionLink() {
926 return $this->mHideNewSectionLink
;
930 * Add or remove feed links in the page header
931 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
932 * for the new version
935 * @param $show Boolean: true: add default feeds, false: remove all feeds
937 public function setSyndicated( $show = true ) {
939 $this->setFeedAppendQuery( false );
941 $this->mFeedLinks
= array();
946 * Add default feeds to the page header
947 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
948 * for the new version
951 * @param $val String: query to append to feed links or false to output
954 public function setFeedAppendQuery( $val ) {
955 global $wgAdvertisedFeedTypes;
957 $this->mFeedLinks
= array();
959 foreach ( $wgAdvertisedFeedTypes as $type ) {
960 $query = "feed=$type";
961 if ( is_string( $val ) ) {
962 $query .= '&' . $val;
964 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
969 * Add a feed link to the page header
971 * @param $format String: feed type, should be a key of $wgFeedClasses
972 * @param $href String: URL
974 public function addFeedLink( $format, $href ) {
975 global $wgAdvertisedFeedTypes;
977 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
978 $this->mFeedLinks
[$format] = $href;
983 * Should we output feed links for this page?
986 public function isSyndicated() {
987 return count( $this->mFeedLinks
) > 0;
991 * Return URLs for each supported syndication format for this page.
992 * @return array associating format keys with URLs
994 public function getSyndicationLinks() {
995 return $this->mFeedLinks
;
999 * Will currently always return null
1003 public function getFeedAppendQuery() {
1004 return $this->mFeedLinksAppendQuery
;
1008 * Set whether the displayed content is related to the source of the
1009 * corresponding article on the wiki
1010 * Setting true will cause the change "article related" toggle to true
1014 public function setArticleFlag( $v ) {
1015 $this->mIsarticle
= $v;
1017 $this->mIsArticleRelated
= $v;
1022 * Return whether the content displayed page is related to the source of
1023 * the corresponding article on the wiki
1027 public function isArticle() {
1028 return $this->mIsarticle
;
1032 * Set whether this page is related an article on the wiki
1033 * Setting false will cause the change of "article flag" toggle to false
1037 public function setArticleRelated( $v ) {
1038 $this->mIsArticleRelated
= $v;
1040 $this->mIsarticle
= false;
1045 * Return whether this page is related an article on the wiki
1049 public function isArticleRelated() {
1050 return $this->mIsArticleRelated
;
1054 * Add new language links
1056 * @param $newLinkArray Associative array mapping language code to the page
1059 public function addLanguageLinks( $newLinkArray ) {
1060 $this->mLanguageLinks +
= $newLinkArray;
1064 * Reset the language links and add new language links
1066 * @param $newLinkArray Associative array mapping language code to the page
1069 public function setLanguageLinks( $newLinkArray ) {
1070 $this->mLanguageLinks
= $newLinkArray;
1074 * Get the list of language links
1076 * @return Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1078 public function getLanguageLinks() {
1079 return $this->mLanguageLinks
;
1083 * Add an array of categories, with names in the keys
1085 * @param $categories Array mapping category name => sort key
1087 public function addCategoryLinks( $categories ) {
1090 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1094 # Add the links to a LinkBatch
1095 $arr = array( NS_CATEGORY
=> $categories );
1096 $lb = new LinkBatch
;
1097 $lb->setArray( $arr );
1099 # Fetch existence plus the hiddencat property
1100 $dbr = wfGetDB( DB_SLAVE
);
1101 $res = $dbr->select( array( 'page', 'page_props' ),
1102 array( 'page_id', 'page_namespace', 'page_title', 'page_len', 'page_is_redirect', 'page_latest', 'pp_value' ),
1103 $lb->constructSet( 'page', $dbr ),
1106 array( 'page_props' => array( 'LEFT JOIN', array( 'pp_propname' => 'hiddencat', 'pp_page = page_id' ) ) )
1109 # Add the results to the link cache
1110 $lb->addResultToCache( LinkCache
::singleton(), $res );
1112 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
1113 $categories = array_combine(
1114 array_keys( $categories ),
1115 array_fill( 0, count( $categories ), 'normal' )
1118 # Mark hidden categories
1119 foreach ( $res as $row ) {
1120 if ( isset( $row->pp_value
) ) {
1121 $categories[$row->page_title
] = 'hidden';
1125 # Add the remaining categories to the skin
1126 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
1127 foreach ( $categories as $category => $type ) {
1128 $origcategory = $category;
1129 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1130 $wgContLang->findVariantLink( $category, $title, true );
1131 if ( $category != $origcategory ) {
1132 if ( array_key_exists( $category, $categories ) ) {
1136 $text = $wgContLang->convertHtml( $title->getText() );
1137 $this->mCategories
[] = $title->getText();
1138 $this->mCategoryLinks
[$type][] = Linker
::link( $title, $text );
1144 * Reset the category links (but not the category list) and add $categories
1146 * @param $categories Array mapping category name => sort key
1148 public function setCategoryLinks( $categories ) {
1149 $this->mCategoryLinks
= array();
1150 $this->addCategoryLinks( $categories );
1154 * Get the list of category links, in a 2-D array with the following format:
1155 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1156 * hidden categories) and $link a HTML fragment with a link to the category
1161 public function getCategoryLinks() {
1162 return $this->mCategoryLinks
;
1166 * Get the list of category names this page belongs to
1168 * @return Array of strings
1170 public function getCategories() {
1171 return $this->mCategories
;
1175 * Do not allow scripts which can be modified by wiki users to load on this page;
1176 * only allow scripts bundled with, or generated by, the software.
1178 public function disallowUserJs() {
1179 $this->reduceAllowedModules(
1180 ResourceLoaderModule
::TYPE_SCRIPTS
,
1181 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1186 * Return whether user JavaScript is allowed for this page
1187 * @deprecated since 1.18 Load modules with ResourceLoader, and origin and
1188 * trustworthiness is identified and enforced automagically.
1191 public function isUserJsAllowed() {
1192 return $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
) >= ResourceLoaderModule
::ORIGIN_USER_INDIVIDUAL
;
1196 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1197 * @see ResourceLoaderModule::$origin
1198 * @param $type String ResourceLoaderModule TYPE_ constant
1199 * @return Int ResourceLoaderModule ORIGIN_ class constant
1201 public function getAllowedModules( $type ){
1202 if( $type == ResourceLoaderModule
::TYPE_COMBINED
){
1203 return min( array_values( $this->mAllowedModules
) );
1205 return isset( $this->mAllowedModules
[$type] )
1206 ?
$this->mAllowedModules
[$type]
1207 : ResourceLoaderModule
::ORIGIN_ALL
;
1212 * Set the highest level of CSS/JS untrustworthiness allowed
1213 * @param $type String ResourceLoaderModule TYPE_ constant
1214 * @param $level Int ResourceLoaderModule class constant
1216 public function setAllowedModules( $type, $level ){
1217 $this->mAllowedModules
[$type] = $level;
1221 * As for setAllowedModules(), but don't inadvertantly make the page more accessible
1222 * @param $type String
1223 * @param $level Int ResourceLoaderModule class constant
1225 public function reduceAllowedModules( $type, $level ){
1226 $this->mAllowedModules
[$type] = min( $this->getAllowedModules($type), $level );
1230 * Prepend $text to the body HTML
1232 * @param $text String: HTML
1234 public function prependHTML( $text ) {
1235 $this->mBodytext
= $text . $this->mBodytext
;
1239 * Append $text to the body HTML
1241 * @param $text String: HTML
1243 public function addHTML( $text ) {
1244 $this->mBodytext
.= $text;
1248 * Clear the body HTML
1250 public function clearHTML() {
1251 $this->mBodytext
= '';
1257 * @return String: HTML
1259 public function getHTML() {
1260 return $this->mBodytext
;
1264 * Add $text to the debug output
1266 * @param $text String: debug text
1268 public function debug( $text ) {
1269 $this->mDebugtext
.= $text;
1273 * Get/set the ParserOptions object to use for wikitext parsing
1275 * @param $options either the ParserOption to use or null to only get the
1276 * current ParserOption object
1277 * @return ParserOptions object
1279 public function parserOptions( $options = null ) {
1280 if ( !$this->mParserOptions
) {
1281 $this->mParserOptions
= new ParserOptions
;
1282 $this->mParserOptions
->setEditSection( false );
1284 return wfSetVar( $this->mParserOptions
, $options );
1288 * Set the revision ID which will be seen by the wiki text parser
1289 * for things such as embedded {{REVISIONID}} variable use.
1291 * @param $revid Mixed: an positive integer, or null
1292 * @return Mixed: previous value
1294 public function setRevisionId( $revid ) {
1295 $val = is_null( $revid ) ?
null : intval( $revid );
1296 return wfSetVar( $this->mRevisionId
, $val );
1300 * Get the displayed revision ID
1304 public function getRevisionId() {
1305 return $this->mRevisionId
;
1309 * Set the displayed file version
1311 * @param $file File|false
1312 * @return Mixed: previous value
1314 public function setFileVersion( $file ) {
1316 if ( $file instanceof File
&& $file->exists() ) {
1317 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1319 return wfSetVar( $this->mFileVersion
, $val, true );
1323 * Get the displayed file version
1325 * @return Array|null ('time' => MW timestamp, 'sha1' => sha1)
1327 public function getFileVersion() {
1328 return $this->mFileVersion
;
1332 * Get the templates used on this page
1334 * @return Array (namespace => dbKey => revId)
1337 public function getTemplateIds() {
1338 return $this->mTemplateIds
;
1342 * Get the files used on this page
1344 * @return Array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1347 public function getImageTimeKeys() {
1348 return $this->mImageTimeKeys
;
1352 * Convert wikitext to HTML and add it to the buffer
1353 * Default assumes that the current page title will be used.
1355 * @param $text String
1356 * @param $linestart Boolean: is this the start of a line?
1358 public function addWikiText( $text, $linestart = true ) {
1359 $title = $this->getTitle(); // Work arround E_STRICT
1360 $this->addWikiTextTitle( $text, $title, $linestart );
1364 * Add wikitext with a custom Title object
1366 * @param $text String: wikitext
1367 * @param $title Title object
1368 * @param $linestart Boolean: is this the start of a line?
1370 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1371 $this->addWikiTextTitle( $text, $title, $linestart );
1375 * Add wikitext with a custom Title object and
1377 * @param $text String: wikitext
1378 * @param $title Title object
1379 * @param $linestart Boolean: is this the start of a line?
1381 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1382 $this->addWikiTextTitle( $text, $title, $linestart, true );
1386 * Add wikitext with tidy enabled
1388 * @param $text String: wikitext
1389 * @param $linestart Boolean: is this the start of a line?
1391 public function addWikiTextTidy( $text, $linestart = true ) {
1392 $title = $this->getTitle();
1393 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1397 * Add wikitext with a custom Title object
1399 * @param $text String: wikitext
1400 * @param $title Title object
1401 * @param $linestart Boolean: is this the start of a line?
1402 * @param $tidy Boolean: whether to use tidy
1404 public function addWikiTextTitle( $text, &$title, $linestart, $tidy = false ) {
1407 wfProfileIn( __METHOD__
);
1409 wfIncrStats( 'pcache_not_possible' );
1411 $popts = $this->parserOptions();
1412 $oldTidy = $popts->setTidy( $tidy );
1414 $parserOutput = $wgParser->parse(
1415 $text, $title, $popts,
1416 $linestart, true, $this->mRevisionId
1419 $popts->setTidy( $oldTidy );
1421 $this->addParserOutput( $parserOutput );
1423 wfProfileOut( __METHOD__
);
1427 * Add a ParserOutput object, but without Html
1429 * @param $parserOutput ParserOutput object
1431 public function addParserOutputNoText( &$parserOutput ) {
1432 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1433 $this->addCategoryLinks( $parserOutput->getCategories() );
1434 $this->mNewSectionLink
= $parserOutput->getNewSection();
1435 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1437 $this->mParseWarnings
= $parserOutput->getWarnings();
1438 if ( !$parserOutput->isCacheable() ) {
1439 $this->enableClientCache( false );
1441 $this->mNoGallery
= $parserOutput->getNoGallery();
1442 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1443 $this->addModules( $parserOutput->getModules() );
1445 // Template versioning...
1446 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1447 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1448 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1450 $this->mTemplateIds
[$ns] = $dbks;
1453 // File versioning...
1454 foreach ( (array)$parserOutput->getImageTimeKeys() as $dbk => $data ) {
1455 $this->mImageTimeKeys
[$dbk] = $data;
1458 // Hooks registered in the object
1459 global $wgParserOutputHooks;
1460 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1461 list( $hookName, $data ) = $hookInfo;
1462 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1463 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1467 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1471 * Add a ParserOutput object
1473 * @param $parserOutput ParserOutput
1475 function addParserOutput( &$parserOutput ) {
1476 $this->addParserOutputNoText( $parserOutput );
1477 $text = $parserOutput->getText();
1478 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1479 $this->addHTML( $text );
1484 * Add the output of a QuickTemplate to the output buffer
1486 * @param $template QuickTemplate
1488 public function addTemplate( &$template ) {
1490 $template->execute();
1491 $this->addHTML( ob_get_contents() );
1496 * Parse wikitext and return the HTML.
1498 * @param $text String
1499 * @param $linestart Boolean: is this the start of a line?
1500 * @param $interface Boolean: use interface language ($wgLang instead of
1501 * $wgContLang) while parsing language sensitive magic
1502 * words like GRAMMAR and PLURAL
1503 * @param $language Language object: target language object, will override
1505 * @return String: HTML
1507 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1508 // Check one for one common cause for parser state resetting
1509 $callers = wfGetAllCallers( 10 );
1510 if ( strpos( $callers, 'Parser::extensionSubstitution' ) !== false ) {
1511 throw new MWException( "wfMsg* function with parsing cannot be used " .
1512 "inside a tag hook. Should use parser->recursiveTagParse() instead" );
1517 if( is_null( $this->getTitle() ) ) {
1518 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1521 $popts = $this->parserOptions();
1523 $popts->setInterfaceMessage( true );
1525 if ( $language !== null ) {
1526 $oldLang = $popts->setTargetLanguage( $language );
1529 $parserOutput = $wgParser->parse(
1530 $text, $this->getTitle(), $popts,
1531 $linestart, true, $this->mRevisionId
1535 $popts->setInterfaceMessage( false );
1537 if ( $language !== null ) {
1538 $popts->setTargetLanguage( $oldLang );
1541 return $parserOutput->getText();
1545 * Parse wikitext, strip paragraphs, and return the HTML.
1547 * @param $text String
1548 * @param $linestart Boolean: is this the start of a line?
1549 * @param $interface Boolean: use interface language ($wgLang instead of
1550 * $wgContLang) while parsing language sensitive magic
1551 * words like GRAMMAR and PLURAL
1552 * @return String: HTML
1554 public function parseInline( $text, $linestart = true, $interface = false ) {
1555 $parsed = $this->parse( $text, $linestart, $interface );
1558 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1566 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1568 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1570 public function setSquidMaxage( $maxage ) {
1571 $this->mSquidMaxage
= $maxage;
1575 * Use enableClientCache(false) to force it to send nocache headers
1577 * @param $state bool
1581 public function enableClientCache( $state ) {
1582 return wfSetVar( $this->mEnableClientCache
, $state );
1586 * Get the list of cookies that will influence on the cache
1590 function getCacheVaryCookies() {
1591 global $wgCookiePrefix, $wgCacheVaryCookies;
1593 if ( $cookies === null ) {
1594 $cookies = array_merge(
1596 "{$wgCookiePrefix}Token",
1597 "{$wgCookiePrefix}LoggedOut",
1602 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1608 * Return whether this page is not cacheable because "useskin" or "uselang"
1609 * URL parameters were passed.
1613 function uncacheableBecauseRequestVars() {
1614 $request = $this->getRequest();
1615 return $request->getText( 'useskin', false ) === false
1616 && $request->getText( 'uselang', false ) === false;
1620 * Check if the request has a cache-varying cookie header
1621 * If it does, it's very important that we don't allow public caching
1625 function haveCacheVaryCookies() {
1626 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1627 if ( $cookieHeader === false ) {
1630 $cvCookies = $this->getCacheVaryCookies();
1631 foreach ( $cvCookies as $cookieName ) {
1632 # Check for a simple string match, like the way squid does it
1633 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1634 wfDebug( __METHOD__
. ": found $cookieName\n" );
1638 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1643 * Add an HTTP header that will influence on the cache
1645 * @param $header String: header name
1646 * @param $option Array|null
1647 * @todo FIXME: Document the $option parameter; it appears to be for
1648 * X-Vary-Options but what format is acceptable?
1650 public function addVaryHeader( $header, $option = null ) {
1651 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1652 $this->mVaryHeader
[$header] = (array)$option;
1653 } elseif( is_array( $option ) ) {
1654 if( is_array( $this->mVaryHeader
[$header] ) ) {
1655 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
1657 $this->mVaryHeader
[$header] = $option;
1660 $this->mVaryHeader
[$header] = array_unique( $this->mVaryHeader
[$header] );
1664 * Get a complete X-Vary-Options header
1668 public function getXVO() {
1669 $cvCookies = $this->getCacheVaryCookies();
1671 $cookiesOption = array();
1672 foreach ( $cvCookies as $cookieName ) {
1673 $cookiesOption[] = 'string-contains=' . $cookieName;
1675 $this->addVaryHeader( 'Cookie', $cookiesOption );
1678 foreach( $this->mVaryHeader
as $header => $option ) {
1679 $newheader = $header;
1680 if( is_array( $option ) ) {
1681 $newheader .= ';' . implode( ';', $option );
1683 $headers[] = $newheader;
1685 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1691 * bug 21672: Add Accept-Language to Vary and XVO headers
1692 * if there's no 'variant' parameter existed in GET.
1695 * /w/index.php?title=Main_page should always be served; but
1696 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1698 function addAcceptLanguage() {
1700 if( !$this->getRequest()->getCheck( 'variant' ) && $wgContLang->hasVariants() ) {
1701 $variants = $wgContLang->getVariants();
1702 $aloption = array();
1703 foreach ( $variants as $variant ) {
1704 if( $variant === $wgContLang->getCode() ) {
1707 $aloption[] = 'string-contains=' . $variant;
1709 // IE and some other browsers use another form of language code
1710 // in their Accept-Language header, like "zh-CN" or "zh-TW".
1711 // We should handle these too.
1712 $ievariant = explode( '-', $variant );
1713 if ( count( $ievariant ) == 2 ) {
1714 $ievariant[1] = strtoupper( $ievariant[1] );
1715 $ievariant = implode( '-', $ievariant );
1716 $aloption[] = 'string-contains=' . $ievariant;
1720 $this->addVaryHeader( 'Accept-Language', $aloption );
1725 * Set a flag which will cause an X-Frame-Options header appropriate for
1726 * edit pages to be sent. The header value is controlled by
1727 * $wgEditPageFrameOptions.
1729 * This is the default for special pages. If you display a CSRF-protected
1730 * form on an ordinary view page, then you need to call this function.
1732 * @param $enable bool
1734 public function preventClickjacking( $enable = true ) {
1735 $this->mPreventClickjacking
= $enable;
1739 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1740 * This can be called from pages which do not contain any CSRF-protected
1743 public function allowClickjacking() {
1744 $this->mPreventClickjacking
= false;
1748 * Get the X-Frame-Options header value (without the name part), or false
1749 * if there isn't one. This is used by Skin to determine whether to enable
1750 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1754 public function getFrameOptions() {
1755 global $wgBreakFrames, $wgEditPageFrameOptions;
1756 if ( $wgBreakFrames ) {
1758 } elseif ( $this->mPreventClickjacking
&& $wgEditPageFrameOptions ) {
1759 return $wgEditPageFrameOptions;
1764 * Send cache control HTTP headers
1766 public function sendCacheControl() {
1767 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgUseXVO;
1769 $response = $this->getRequest()->response();
1770 if ( $wgUseETag && $this->mETag
) {
1771 $response->header( "ETag: $this->mETag" );
1774 $this->addAcceptLanguage();
1776 # don't serve compressed data to clients who can't handle it
1777 # maintain different caches for logged-in users and non-logged in ones
1778 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) ) );
1781 # Add an X-Vary-Options header for Squid with Wikimedia patches
1782 $response->header( $this->getXVO() );
1785 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
1787 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1788 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
1792 # We'll purge the proxy cache explicitly, but require end user agents
1793 # to revalidate against the proxy on each visit.
1794 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1795 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1796 # start with a shorter timeout for initial testing
1797 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1798 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
1799 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1801 # We'll purge the proxy cache for anons explicitly, but require end user agents
1802 # to revalidate against the proxy on each visit.
1803 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1804 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1805 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
1806 # start with a shorter timeout for initial testing
1807 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1808 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
1811 # We do want clients to cache if they can, but they *must* check for updates
1812 # on revisiting the page.
1813 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
1814 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1815 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1817 if($this->mLastModified
) {
1818 $response->header( "Last-Modified: {$this->mLastModified}" );
1821 wfDebug( __METHOD__
. ": no caching **\n", false );
1823 # In general, the absence of a last modified header should be enough to prevent
1824 # the client from using its cache. We send a few other things just to make sure.
1825 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1826 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1827 $response->header( 'Pragma: no-cache' );
1832 * Get the message associed with the HTTP response code $code
1834 * @param $code Integer: status code
1835 * @return String or null: message or null if $code is not in the list of
1838 * @deprecated since 1.18 Use HttpStatus::getMessage() instead.
1840 public static function getStatusMessage( $code ) {
1841 wfDeprecated( __METHOD__
);
1842 return HttpStatus
::getMessage( $code );
1846 * Finally, all the text has been munged and accumulated into
1847 * the object, let's actually output it:
1849 public function output() {
1850 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType;
1852 if( $this->mDoNothing
) {
1856 wfProfileIn( __METHOD__
);
1858 $response = $this->getRequest()->response();
1860 if ( $this->mRedirect
!= '' ) {
1861 # Standards require redirect URLs to be absolute
1862 $this->mRedirect
= wfExpandUrl( $this->mRedirect
);
1863 if( $this->mRedirectCode
== '301' ||
$this->mRedirectCode
== '303' ) {
1864 if( !$wgDebugRedirects ) {
1865 $message = HttpStatus
::getMessage( $this->mRedirectCode
);
1866 $response->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
1868 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1870 $this->sendCacheControl();
1872 $response->header( "Content-Type: text/html; charset=utf-8" );
1873 if( $wgDebugRedirects ) {
1874 $url = htmlspecialchars( $this->mRedirect
);
1875 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1876 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1877 print "</body>\n</html>\n";
1879 $response->header( 'Location: ' . $this->mRedirect
);
1881 wfProfileOut( __METHOD__
);
1883 } elseif ( $this->mStatusCode
) {
1884 $message = HttpStatus
::getMessage( $this->mStatusCode
);
1886 $response->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
1890 # Buffer output; final headers may depend on later processing
1893 $response->header( "Content-type: $wgMimeType; charset=UTF-8" );
1894 $response->header( 'Content-language: ' . $wgLanguageCode );
1896 // Prevent framing, if requested
1897 $frameOptions = $this->getFrameOptions();
1898 if ( $frameOptions ) {
1899 $response->header( "X-Frame-Options: $frameOptions" );
1902 if ( $this->mArticleBodyOnly
) {
1903 $this->out( $this->mBodytext
);
1905 $this->addDefaultModules();
1907 $sk = $this->getSkin();
1909 // Hook that allows last minute changes to the output page, e.g.
1910 // adding of CSS or Javascript by extensions.
1911 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1913 wfProfileIn( 'Output-skin' );
1914 $sk->outputPage( $this );
1915 wfProfileOut( 'Output-skin' );
1918 $this->sendCacheControl();
1920 wfProfileOut( __METHOD__
);
1924 * Actually output something with print().
1926 * @param $ins String: the string to output
1928 public function out( $ins ) {
1933 * Produce a "user is blocked" page.
1934 * @deprecated since 1.18
1936 function blockedPage() {
1937 throw new UserBlockedError( $this->getUser()->mBlock
);
1941 * Output a standard error page
1943 * @param $title String: message key for page title
1944 * @param $msg String: message key for page text
1945 * @param $params Array: message parameters
1947 public function showErrorPage( $title, $msg, $params = array() ) {
1948 if ( $this->getTitle() ) {
1949 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1951 $this->setPageTitle( wfMsg( $title ) );
1952 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1953 $this->setRobotPolicy( 'noindex,nofollow' );
1954 $this->setArticleRelated( false );
1955 $this->enableClientCache( false );
1956 $this->mRedirect
= '';
1957 $this->mBodytext
= '';
1959 $this->addWikiMsgArray( $msg, $params );
1961 $this->returnToMain();
1965 * Output a standard permission error page
1967 * @param $errors Array: error message keys
1968 * @param $action String: action that was denied or null if unknown
1970 public function showPermissionsErrorPage( $errors, $action = null ) {
1971 $this->mDebugtext
.= 'Original title: ' .
1972 $this->getTitle()->getPrefixedText() . "\n";
1973 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1974 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1975 $this->setRobotPolicy( 'noindex,nofollow' );
1976 $this->setArticleRelated( false );
1977 $this->enableClientCache( false );
1978 $this->mRedirect
= '';
1979 $this->mBodytext
= '';
1980 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1984 * Display an error page indicating that a given version of MediaWiki is
1985 * required to use it
1987 * @param $version Mixed: the version of MediaWiki needed to use the page
1989 public function versionRequired( $version ) {
1990 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1991 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1992 $this->setRobotPolicy( 'noindex,nofollow' );
1993 $this->setArticleRelated( false );
1994 $this->mBodytext
= '';
1996 $this->addWikiMsg( 'versionrequiredtext', $version );
1997 $this->returnToMain();
2001 * Display an error page noting that a given permission bit is required.
2002 * @deprecated since 1.18, just throw the exception directly
2003 * @param $permission String: key required
2005 public function permissionRequired( $permission ) {
2006 throw new PermissionsError( $permission );
2010 * Produce the stock "please login to use the wiki" page
2012 public function loginToUse() {
2013 if( $this->getUser()->isLoggedIn() ) {
2014 throw new PermissionsError( 'read' );
2017 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
2018 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
2019 $this->setRobotPolicy( 'noindex,nofollow' );
2020 $this->setArticleRelated( false );
2022 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
2023 $loginLink = Linker
::linkKnown(
2025 wfMsgHtml( 'loginreqlink' ),
2027 array( 'returnto' => $this->getTitle()->getPrefixedText() )
2029 $this->addHTML( wfMessage( 'loginreqpagetext' )->rawParams( $loginLink )->parse() .
2030 "\n<!--" . $this->getTitle()->getPrefixedUrl() . '-->' );
2032 # Don't return to the main page if the user can't read it
2033 # otherwise we'll end up in a pointless loop
2034 $mainPage = Title
::newMainPage();
2035 if( $mainPage->userCanRead() ) {
2036 $this->returnToMain( null, $mainPage );
2041 * Format a list of error messages
2043 * @param $errors Array of arrays returned by Title::getUserPermissionsErrors
2044 * @param $action String: action that was denied or null if unknown
2045 * @return String: the wikitext error-messages, formatted into a list.
2047 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2048 if ( $action == null ) {
2049 $text = wfMsgNoTrans( 'permissionserrorstext', count( $errors ) ) . "\n\n";
2051 $action_desc = wfMsgNoTrans( "action-$action" );
2052 $text = wfMsgNoTrans(
2053 'permissionserrorstext-withaction',
2059 if ( count( $errors ) > 1 ) {
2060 $text .= '<ul class="permissions-errors">' . "\n";
2062 foreach( $errors as $error ) {
2064 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
2069 $text .= "<div class=\"permissions-errors\">\n" .
2070 call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) .
2078 * Display a page stating that the Wiki is in read-only mode,
2079 * and optionally show the source of the page that the user
2080 * was trying to edit. Should only be called (for this
2081 * purpose) after wfReadOnly() has returned true.
2083 * For historical reasons, this function is _also_ used to
2084 * show the error message when a user tries to edit a page
2085 * they are not allowed to edit. (Unless it's because they're
2086 * blocked, then we show blockedPage() instead.) In this
2087 * case, the second parameter should be set to true and a list
2088 * of reasons supplied as the third parameter.
2090 * @todo Needs to be split into multiple functions.
2092 * @param $source String: source code to show (or null).
2093 * @param $protected Boolean: is this a permissions error?
2094 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
2095 * @param $action String: action that was denied or null if unknown
2097 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
2098 $this->setRobotPolicy( 'noindex,nofollow' );
2099 $this->setArticleRelated( false );
2101 // If no reason is given, just supply a default "I can't let you do
2102 // that, Dave" message. Should only occur if called by legacy code.
2103 if ( $protected && empty( $reasons ) ) {
2104 $reasons[] = array( 'badaccess-group0' );
2107 if ( !empty( $reasons ) ) {
2108 // Permissions error
2110 $this->setPageTitle( wfMsg( 'viewsource' ) );
2112 wfMsg( 'viewsourcefor', Linker
::linkKnown( $this->getTitle() ) )
2115 $this->setPageTitle( wfMsg( 'badaccess' ) );
2117 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2119 // Wiki is read only
2120 throw new ReadOnlyError
;
2123 // Show source, if supplied
2124 if( is_string( $source ) ) {
2125 $this->addWikiMsg( 'viewsourcetext' );
2128 'id' => 'wpTextbox1',
2129 'name' => 'wpTextbox1',
2130 'cols' => $this->getUser()->getOption( 'cols' ),
2131 'rows' => $this->getUser()->getOption( 'rows' ),
2132 'readonly' => 'readonly'
2134 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
2136 // Show templates used by this article
2137 $article = new Article( $this->getTitle() );
2138 $templates = Linker
::formatTemplates( $article->getUsedTemplates() );
2139 $this->addHTML( "<div class='templatesUsed'>
2145 # If the title doesn't exist, it's fairly pointless to print a return
2146 # link to it. After all, you just tried editing it and couldn't, so
2147 # what's there to do there?
2148 if( $this->getTitle()->exists() ) {
2149 $this->returnToMain( null, $this->getTitle() );
2154 * Turn off regular page output and return an error reponse
2155 * for when rate limiting has triggered.
2157 public function rateLimited() {
2158 throw new ThrottledError
;
2162 * Show a warning about slave lag
2164 * If the lag is higher than $wgSlaveLagCritical seconds,
2165 * then the warning is a bit more obvious. If the lag is
2166 * lower than $wgSlaveLagWarning, then no warning is shown.
2168 * @param $lag Integer: slave lag
2170 public function showLagWarning( $lag ) {
2171 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2172 if( $lag >= $wgSlaveLagWarning ) {
2173 $message = $lag < $wgSlaveLagCritical
2176 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2177 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getContext()->getLang()->formatNum( $lag ) ) );
2181 public function showFatalError( $message ) {
2182 $this->setPageTitle( wfMsg( 'internalerror' ) );
2183 $this->setRobotPolicy( 'noindex,nofollow' );
2184 $this->setArticleRelated( false );
2185 $this->enableClientCache( false );
2186 $this->mRedirect
= '';
2187 $this->mBodytext
= $message;
2190 public function showUnexpectedValueError( $name, $val ) {
2191 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
2194 public function showFileCopyError( $old, $new ) {
2195 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
2198 public function showFileRenameError( $old, $new ) {
2199 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
2202 public function showFileDeleteError( $name ) {
2203 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
2206 public function showFileNotFoundError( $name ) {
2207 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
2211 * Add a "return to" link pointing to a specified title
2213 * @param $title Title to link
2214 * @param $query String query string
2215 * @param $text String text of the link (input is not escaped)
2217 public function addReturnTo( $title, $query = array(), $text = null ) {
2218 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL() ) );
2221 Linker
::link( $title, $text, array(), $query )
2223 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2227 * Add a "return to" link pointing to a specified title,
2228 * or the title indicated in the request, or else the main page
2230 * @param $unused No longer used
2231 * @param $returnto Title or String to return to
2232 * @param $returntoquery String: query string for the return to link
2234 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2235 if ( $returnto == null ) {
2236 $returnto = $this->getRequest()->getText( 'returnto' );
2239 if ( $returntoquery == null ) {
2240 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2243 if ( $returnto === '' ) {
2244 $returnto = Title
::newMainPage();
2247 if ( is_object( $returnto ) ) {
2248 $titleObj = $returnto;
2250 $titleObj = Title
::newFromText( $returnto );
2252 if ( !is_object( $titleObj ) ) {
2253 $titleObj = Title
::newMainPage();
2256 $this->addReturnTo( $titleObj, $returntoquery );
2260 * @param $sk Skin The given Skin
2261 * @param $includeStyle Boolean: unused
2262 * @return String: The doctype, opening <html>, and head element.
2264 public function headElement( Skin
$sk, $includeStyle = true ) {
2265 global $wgLang, $wgContLang, $wgUseTrackbacks;
2266 $userdir = $wgLang->getDir();
2267 $sitedir = $wgContLang->getDir();
2269 if ( $sk->commonPrintStylesheet() ) {
2270 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2272 $sk->setupUserCss( $this );
2274 $ret = Html
::htmlHeader( array( 'lang' => $wgLang->getCode(), 'dir' => $userdir ) );
2276 if ( $this->getHTMLTitle() == '' ) {
2277 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ) );
2280 $openHead = Html
::openElement( 'head' );
2282 # Don't bother with the newline if $head == ''
2283 $ret .= "$openHead\n";
2286 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2288 $ret .= implode( "\n", array(
2289 $this->getHeadLinks( $sk, true ),
2290 $this->buildCssLinks( $sk ),
2291 $this->getHeadScripts( $sk ),
2292 $this->getHeadItems()
2295 if ( $wgUseTrackbacks && $this->isArticleRelated() ) {
2296 $ret .= $this->getTitle()->trackbackRDF();
2299 $closeHead = Html
::closeElement( 'head' );
2301 $ret .= "$closeHead\n";
2304 $bodyAttrs = array();
2306 # Crazy edit-on-double-click stuff
2307 $action = $this->getRequest()->getVal( 'action', 'view' );
2310 $this->getTitle()->getNamespace() != NS_SPECIAL
&&
2311 in_array( $action, array( 'view', 'purge' ) ) &&
2312 $this->getUser()->getOption( 'editondblclick' )
2315 $editUrl = $this->getTitle()->getLocalUrl( $sk->editUrlOptions() );
2316 $bodyAttrs['ondblclick'] = "document.location = '" .
2317 Xml
::escapeJsString( $editUrl ) . "'";
2320 # Classes for LTR/RTL directionality support
2321 $bodyAttrs['class'] = "mediawiki $userdir sitedir-$sitedir";
2323 if ( $this->getContext()->getLang()->capitalizeAllNouns() ) {
2324 # A <body> class is probably not the best way to do this . . .
2325 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2327 $bodyAttrs['class'] .= ' ' . $sk->getPageClasses( $this->getTitle() );
2328 $bodyAttrs['class'] .= ' skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2330 $sk->addToBodyAttributes( $this, $bodyAttrs ); // Allow skins to add body attributes they need
2331 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2333 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2339 * Add the default ResourceLoader modules to this object
2341 private function addDefaultModules() {
2342 global $wgIncludeLegacyJavaScript, $wgUseAjax,
2343 $wgAjaxWatch, $wgEnableMWSuggest, $wgUseAJAXCategories;
2345 // Add base resources
2346 $this->addModules( array(
2349 'mediawiki.page.startup',
2350 'mediawiki.page.ready',
2352 if ( $wgIncludeLegacyJavaScript ){
2353 $this->addModules( 'mediawiki.legacy.wikibits' );
2356 // Add various resources if required
2358 $this->addModules( 'mediawiki.legacy.ajax' );
2360 wfRunHooks( 'AjaxAddScript', array( &$this ) );
2362 if( $wgAjaxWatch && $this->getUser()->isLoggedIn() ) {
2363 $this->addModules( 'mediawiki.action.watch.ajax' );
2366 if ( $wgEnableMWSuggest && !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2367 $this->addModules( 'mediawiki.page.mwsuggest' );
2371 if ( $this->getUser()->getBoolOption( 'editsectiononrightclick' ) ) {
2372 $this->addModules( 'mediawiki.action.view.rightClickEdit' );
2375 if ( $wgUseAJAXCategories ) {
2376 global $wgAJAXCategoriesNamespaces;
2378 $title = $this->getTitle();
2380 if( empty( $wgAJAXCategoriesNamespaces ) ||
in_array( $title->getNamespace(), $wgAJAXCategoriesNamespaces ) ) {
2381 $this->addModules( 'mediawiki.page.ajaxCategories.init' );
2387 * Get a ResourceLoader object associated with this OutputPage
2389 * @return ResourceLoader
2391 public function getResourceLoader() {
2392 if ( is_null( $this->mResourceLoader
) ) {
2393 $this->mResourceLoader
= new ResourceLoader();
2395 return $this->mResourceLoader
;
2401 * @param $modules Array/string with the module name
2402 * @param $only String ResourceLoaderModule TYPE_ class constant
2403 * @param $useESI boolean
2404 * @return string html <script> and <style> tags
2406 protected function makeResourceLoaderLink( Skin
$skin, $modules, $only, $useESI = false ) {
2407 global $wgLoadScript, $wgResourceLoaderUseESI,
2408 $wgResourceLoaderInlinePrivateModules;
2409 // Lazy-load ResourceLoader
2410 // TODO: Should this be a static function of ResourceLoader instead?
2412 'lang' => $this->getContext()->getLang()->getCode(),
2413 'debug' => ResourceLoader
::inDebugMode() ?
'true' : 'false',
2414 'skin' => $skin->getSkinName(),
2417 // Propagate printable and handheld parameters if present
2418 if ( $this->isPrintable() ) {
2419 $baseQuery['printable'] = 1;
2421 if ( $this->getRequest()->getBool( 'handheld' ) ) {
2422 $baseQuery['handheld'] = 1;
2425 if ( !count( $modules ) ) {
2429 if ( count( $modules ) > 1 ) {
2430 // Remove duplicate module requests
2431 $modules = array_unique( (array) $modules );
2432 // Sort module names so requests are more uniform
2435 if ( ResourceLoader
::inDebugMode() ) {
2436 // Recursively call us for every item
2438 foreach ( $modules as $name ) {
2439 $links .= $this->makeResourceLoaderLink( $skin, $name, $only, $useESI );
2445 // Create keyed-by-group list of module objects from modules list
2447 $resourceLoader = $this->getResourceLoader();
2448 foreach ( (array) $modules as $name ) {
2449 $module = $resourceLoader->getModule( $name );
2450 # Check that we're allowed to include this module on this page
2451 if ( ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2452 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2453 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2454 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2460 $group = $module->getGroup();
2461 if ( !isset( $groups[$group] ) ) {
2462 $groups[$group] = array();
2464 $groups[$group][$name] = $module;
2468 foreach ( $groups as $group => $modules ) {
2469 $query = $baseQuery;
2470 // Special handling for user-specific groups
2471 if ( ( $group === 'user' ||
$group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2472 $query['user'] = $this->getUser()->getName();
2475 // Create a fake request based on the one we are about to make so modules return
2476 // correct timestamp and emptiness data
2477 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2478 // Drop modules that know they're empty
2479 foreach ( $modules as $key => $module ) {
2480 if ( $module->isKnownEmpty( $context ) ) {
2481 unset( $modules[$key] );
2484 // If there are no modules left, skip this group
2485 if ( $modules === array() ) {
2489 $query['modules'] = ResourceLoader
::makePackedModulesString( array_keys( $modules ) );
2491 // Support inlining of private modules if configured as such
2492 if ( $group === 'private' && $wgResourceLoaderInlinePrivateModules ) {
2493 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2494 $links .= Html
::inlineStyle(
2495 $resourceLoader->makeModuleResponse( $context, $modules )
2498 $links .= Html
::inlineScript(
2499 ResourceLoader
::makeLoaderConditionalScript(
2500 $resourceLoader->makeModuleResponse( $context, $modules )
2506 // Special handling for the user group; because users might change their stuff
2507 // on-wiki like user pages, or user preferences; we need to find the highest
2508 // timestamp of these user-changable modules so we can ensure cache misses on change
2509 // This should NOT be done for the site group (bug 27564) because anons get that too
2510 // and we shouldn't be putting timestamps in Squid-cached HTML
2511 if ( $group === 'user' ) {
2512 // Get the maximum timestamp
2514 foreach ( $modules as $module ) {
2515 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2517 // Add a version parameter so cache will break when things change
2518 $query['version'] = wfTimestamp( TS_ISO_8601_BASIC
, $timestamp );
2520 // Make queries uniform in order
2523 $url = wfAppendQuery( $wgLoadScript, $query );
2524 // Prevent the IE6 extension check from being triggered (bug 28840)
2525 // by appending a character that's invalid in Windows extensions ('*')
2527 if ( $useESI && $wgResourceLoaderUseESI ) {
2528 $esi = Xml
::element( 'esi:include', array( 'src' => $url ) );
2529 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2530 $link = Html
::inlineStyle( $esi );
2532 $link = Html
::inlineScript( $esi );
2535 // Automatically select style/script elements
2536 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2537 $link = Html
::linkedStyle( $url );
2539 $link = Html
::linkedScript( $url );
2543 if( $group == 'noscript' ){
2544 $links .= Html
::rawElement( 'noscript', array(), $link ) . "\n";
2546 $links .= $link . "\n";
2553 * JS stuff to put in the <head>. This is the startup module, config
2554 * vars and modules marked with position 'top'
2556 * @param $sk Skin object to use
2557 * @return String: HTML fragment
2559 function getHeadScripts( Skin
$sk ) {
2560 // Startup - this will immediately load jquery and mediawiki modules
2561 $scripts = $this->makeResourceLoaderLink( $sk, 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
, true );
2563 // Load config before anything else
2564 $scripts .= Html
::inlineScript(
2565 ResourceLoader
::makeLoaderConditionalScript(
2566 ResourceLoader
::makeConfigSetScript( $this->getJSVars() )
2570 // Script and Messages "only" requests marked for top inclusion
2571 // Messages should go first
2572 $scripts .= $this->makeResourceLoaderLink( $sk, $this->getModuleMessages( true, 'top' ), ResourceLoaderModule
::TYPE_MESSAGES
);
2573 $scripts .= $this->makeResourceLoaderLink( $sk, $this->getModuleScripts( true, 'top' ), ResourceLoaderModule
::TYPE_SCRIPTS
);
2575 // Modules requests - let the client calculate dependencies and batch requests as it likes
2576 // Only load modules that have marked themselves for loading at the top
2577 $modules = $this->getModules( true, 'top' );
2579 $scripts .= Html
::inlineScript(
2580 ResourceLoader
::makeLoaderConditionalScript(
2581 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
2590 * JS stuff to put at the bottom of the <body>: modules marked with position 'bottom',
2591 * legacy scripts ($this->mScripts), user preferences, site JS and user JS
2597 function getBottomScripts( Skin
$sk ) {
2598 global $wgUseSiteJs, $wgAllowUserJs;
2600 // Script and Messages "only" requests marked for bottom inclusion
2601 // Messages should go first
2602 $scripts = $this->makeResourceLoaderLink( $sk, $this->getModuleMessages( true, 'bottom' ), ResourceLoaderModule
::TYPE_MESSAGES
);
2603 $scripts .= $this->makeResourceLoaderLink( $sk, $this->getModuleScripts( true, 'bottom' ), ResourceLoaderModule
::TYPE_SCRIPTS
);
2605 // Modules requests - let the client calculate dependencies and batch requests as it likes
2606 // Only load modules that have marked themselves for loading at the bottom
2607 $modules = $this->getModules( true, 'bottom' );
2609 $scripts .= Html
::inlineScript(
2610 ResourceLoader
::makeLoaderConditionalScript(
2611 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
2617 $scripts .= "\n" . $this->mScripts
;
2619 $userScripts = array( 'user.options', 'user.tokens' );
2621 // Add site JS if enabled
2622 if ( $wgUseSiteJs ) {
2623 $scripts .= $this->makeResourceLoaderLink( $sk, 'site', ResourceLoaderModule
::TYPE_SCRIPTS
);
2624 if( $this->getUser()->isLoggedIn() ){
2625 $userScripts[] = 'user.groups';
2629 // Add user JS if enabled
2630 if ( $wgAllowUserJs && $this->getUser()->isLoggedIn() ) {
2631 if( $this->getTitle() && $this->getTitle()->isJsSubpage() && $sk->userCanPreview() ) {
2632 # XXX: additional security check/prompt?
2633 $scripts .= Html
::inlineScript( "\n" . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2635 # @todo FIXME: This means that User:Me/Common.js doesn't load when previewing
2636 # User:Me/Vector.js, and vice versa (bug26283)
2637 $userScripts[] = 'user';
2640 $scripts .= $this->makeResourceLoaderLink( $sk, $userScripts, ResourceLoaderModule
::TYPE_SCRIPTS
);
2646 * Get an array containing global JS variables
2648 * Do not add things here which can be evaluated in
2649 * ResourceLoaderStartupScript - in other words, without state.
2650 * You will only be adding bloat to the page and causing page caches to
2651 * have to be purged on configuration changes.
2653 protected function getJSVars() {
2654 global $wgUseAjax, $wgEnableMWSuggest, $wgContLang;
2656 $title = $this->getTitle();
2657 $ns = $title->getNamespace();
2658 $nsname = MWNamespace
::exists( $ns ) ? MWNamespace
::getCanonicalName( $ns ) : $title->getNsText();
2659 if ( $ns == NS_SPECIAL
) {
2660 list( $canonicalName, /*...*/ ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
2662 $canonicalName = false; # bug 21115
2666 'wgCanonicalNamespace' => $nsname,
2667 'wgCanonicalSpecialPageName' => $canonicalName,
2668 'wgNamespaceNumber' => $title->getNamespace(),
2669 'wgPageName' => $title->getPrefixedDBKey(),
2670 'wgTitle' => $title->getText(),
2671 'wgCurRevisionId' => $title->getLatestRevID(),
2672 'wgArticleId' => $title->getArticleId(),
2673 'wgIsArticle' => $this->isArticle(),
2674 'wgAction' => $this->getRequest()->getText( 'action', 'view' ),
2675 'wgUserName' => $this->getUser()->isAnon() ?
null : $this->getUser()->getName(),
2676 'wgUserGroups' => $this->getUser()->getEffectiveGroups(),
2677 'wgCategories' => $this->getCategories(),
2678 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
2680 if ( $wgContLang->hasVariants() ) {
2681 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
2683 foreach ( $title->getRestrictionTypes() as $type ) {
2684 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
2686 if ( $wgUseAjax && $wgEnableMWSuggest && !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2687 $vars['wgSearchNamespaces'] = SearchEngine
::userNamespaces( $this->getUser() );
2689 if ( $title->isMainPage() ) {
2690 $vars['wgIsMainPage'] = true;
2693 // Allow extensions to add their custom variables to the global JS variables
2694 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars ) );
2701 * @param $addContentType bool
2703 * @return string HTML tag links to be put in the header.
2705 public function getHeadLinks( Skin
$sk, $addContentType = false ) {
2706 global $wgUniversalEditButton, $wgFavicon, $wgAppleTouchIcon, $wgEnableAPI,
2707 $wgSitename, $wgVersion, $wgHtml5, $wgMimeType,
2708 $wgFeed, $wgOverrideSiteFeed, $wgAdvertisedFeedTypes,
2709 $wgDisableLangConversion, $wgCanonicalLanguageLinks, $wgContLang,
2710 $wgRightsPage, $wgRightsUrl;
2714 if ( $addContentType ) {
2716 # More succinct than <meta http-equiv=Content-Type>, has the
2718 $tags[] = Html
::element( 'meta', array( 'charset' => 'UTF-8' ) );
2720 $tags[] = Html
::element( 'meta', array(
2721 'http-equiv' => 'Content-Type',
2722 'content' => "$wgMimeType; charset=UTF-8"
2724 $tags[] = Html
::element( 'meta', array( // bug 15835
2725 'http-equiv' => 'Content-Style-Type',
2726 'content' => 'text/css'
2731 $tags[] = Html
::element( 'meta', array(
2732 'name' => 'generator',
2733 'content' => "MediaWiki $wgVersion",
2736 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
2737 if( $p !== 'index,follow' ) {
2738 // http://www.robotstxt.org/wc/meta-user.html
2739 // Only show if it's different from the default robots policy
2740 $tags[] = Html
::element( 'meta', array(
2746 if ( count( $this->mKeywords
) > 0 ) {
2748 "/<.*?" . ">/" => '',
2751 $tags[] = Html
::element( 'meta', array(
2752 'name' => 'keywords',
2753 'content' => preg_replace(
2754 array_keys( $strip ),
2755 array_values( $strip ),
2756 implode( ',', $this->mKeywords
)
2761 foreach ( $this->mMetatags
as $tag ) {
2762 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
2764 $tag[0] = substr( $tag[0], 5 );
2768 $tags[] = Html
::element( 'meta',
2771 'content' => $tag[1]
2776 foreach ( $this->mLinktags
as $tag ) {
2777 $tags[] = Html
::element( 'link', $tag );
2780 # Universal edit button
2781 if ( $wgUniversalEditButton ) {
2782 if ( $this->isArticleRelated() && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
2783 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create' ) ) ) {
2784 // Original UniversalEditButton
2785 $msg = wfMsg( 'edit' );
2786 $tags[] = Html
::element( 'link', array(
2787 'rel' => 'alternate',
2788 'type' => 'application/x-wiki',
2790 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
2792 // Alternate edit link
2793 $tags[] = Html
::element( 'link', array(
2796 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
2801 # Generally the order of the favicon and apple-touch-icon links
2802 # should not matter, but Konqueror (3.5.9 at least) incorrectly
2803 # uses whichever one appears later in the HTML source. Make sure
2804 # apple-touch-icon is specified first to avoid this.
2805 if ( $wgAppleTouchIcon !== false ) {
2806 $tags[] = Html
::element( 'link', array( 'rel' => 'apple-touch-icon', 'href' => $wgAppleTouchIcon ) );
2809 if ( $wgFavicon !== false ) {
2810 $tags[] = Html
::element( 'link', array( 'rel' => 'shortcut icon', 'href' => $wgFavicon ) );
2813 # OpenSearch description link
2814 $tags[] = Html
::element( 'link', array(
2816 'type' => 'application/opensearchdescription+xml',
2817 'href' => wfScript( 'opensearch_desc' ),
2818 'title' => wfMsgForContent( 'opensearch-desc' ),
2821 if ( $wgEnableAPI ) {
2822 # Real Simple Discovery link, provides auto-discovery information
2823 # for the MediaWiki API (and potentially additional custom API
2824 # support such as WordPress or Twitter-compatible APIs for a
2825 # blogging extension, etc)
2826 $tags[] = Html
::element( 'link', array(
2828 'type' => 'application/rsd+xml',
2829 'href' => wfExpandUrl( wfAppendQuery( wfScript( 'api' ), array( 'action' => 'rsd' ) ) ),
2834 if ( !$wgDisableLangConversion && $wgCanonicalLanguageLinks
2835 && $wgContLang->hasVariants() ) {
2837 $urlvar = $wgContLang->getURLVariant();
2840 $variants = $wgContLang->getVariants();
2841 foreach ( $variants as $_v ) {
2842 $tags[] = Html
::element( 'link', array(
2843 'rel' => 'alternate',
2845 'href' => $this->getTitle()->getLocalURL( '', $_v ) )
2849 $tags[] = Html
::element( 'link', array(
2850 'rel' => 'canonical',
2851 'href' => $this->getTitle()->getFullURL() )
2858 if ( $wgRightsPage ) {
2859 $copy = Title
::newFromText( $wgRightsPage );
2862 $copyright = $copy->getLocalURL();
2866 if ( !$copyright && $wgRightsUrl ) {
2867 $copyright = $wgRightsUrl;
2871 $tags[] = Html
::element( 'link', array(
2872 'rel' => 'copyright',
2873 'href' => $copyright )
2879 foreach( $this->getSyndicationLinks() as $format => $link ) {
2880 # Use the page name for the title. In principle, this could
2881 # lead to issues with having the same name for different feeds
2882 # corresponding to the same page, but we can't avoid that at
2885 $tags[] = $this->feedLink(
2888 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
2889 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )
2893 # Recent changes feed should appear on every page (except recentchanges,
2894 # that would be redundant). Put it after the per-page feed to avoid
2895 # changing existing behavior. It's still available, probably via a
2896 # menu in your browser. Some sites might have a different feed they'd
2897 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
2898 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
2899 # If so, use it instead.
2901 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
2903 if ( $wgOverrideSiteFeed ) {
2904 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
2905 $tags[] = $this->feedLink(
2907 htmlspecialchars( $feedUrl ),
2908 wfMsg( "site-{$type}-feed", $wgSitename )
2911 } elseif ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
2912 foreach ( $wgAdvertisedFeedTypes as $format ) {
2913 $tags[] = $this->feedLink(
2915 $rctitle->getLocalURL( "feed={$format}" ),
2916 wfMsg( "site-{$format}-feed", $wgSitename ) # For grep: 'site-rss-feed', 'site-atom-feed'.
2921 return implode( "\n", $tags );
2925 * Generate a <link rel/> for a feed.
2927 * @param $type String: feed type
2928 * @param $url String: URL to the feed
2929 * @param $text String: value of the "title" attribute
2930 * @return String: HTML fragment
2932 private function feedLink( $type, $url, $text ) {
2933 return Html
::element( 'link', array(
2934 'rel' => 'alternate',
2935 'type' => "application/$type+xml",
2942 * Add a local or specified stylesheet, with the given media options.
2943 * Meant primarily for internal use...
2945 * @param $style String: URL to the file
2946 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
2947 * @param $condition String: for IE conditional comments, specifying an IE version
2948 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
2950 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
2952 // Even though we expect the media type to be lowercase, but here we
2953 // force it to lowercase to be safe.
2955 $options['media'] = $media;
2958 $options['condition'] = $condition;
2961 $options['dir'] = $dir;
2963 $this->styles
[$style] = $options;
2967 * Adds inline CSS styles
2968 * @param $style_css Mixed: inline CSS
2970 public function addInlineStyle( $style_css ){
2971 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
2975 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
2976 * These will be applied to various media & IE conditionals.
2977 * @param $sk Skin object
2981 public function buildCssLinks( $sk ) {
2983 // Add ResourceLoader styles
2984 // Split the styles into four groups
2985 $styles = array( 'other' => array(), 'user' => array(), 'site' => array(), 'private' => array(), 'noscript' => array() );
2986 $resourceLoader = $this->getResourceLoader();
2987 foreach ( $this->getModuleStyles() as $name ) {
2988 $group = $resourceLoader->getModule( $name )->getGroup();
2989 // Modules in groups named "other" or anything different than "user", "site" or "private"
2990 // will be placed in the "other" group
2991 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
2994 // We want site, private and user styles to override dynamically added styles from modules, but we want
2995 // dynamically added styles to override statically added styles from other modules. So the order
2996 // has to be other, dynamic, site, private, user
2997 // Add statically added styles for other modules
2998 $ret .= $this->makeResourceLoaderLink( $sk, $styles['other'], ResourceLoaderModule
::TYPE_STYLES
);
2999 // Add normal styles added through addStyle()/addInlineStyle() here
3000 $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3001 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3002 // We use a <meta> tag with a made-up name for this because that's valid HTML
3003 $ret .= Html
::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) ) . "\n";
3005 // Add site, private and user styles
3006 // 'private' at present only contains user.options, so put that before 'user'
3007 // Any future private modules will likely have a similar user-specific character
3008 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3009 $ret .= $this->makeResourceLoaderLink( $sk, $styles[$group],
3010 ResourceLoaderModule
::TYPE_STYLES
3016 public function buildCssLinksArray() {
3018 foreach( $this->styles
as $file => $options ) {
3019 $link = $this->styleLink( $file, $options );
3021 $links[$file] = $link;
3028 * Generate \<link\> tags for stylesheets
3030 * @param $style String: URL to the file
3031 * @param $options Array: option, can contain 'condition', 'dir', 'media'
3033 * @return String: HTML fragment
3035 protected function styleLink( $style, $options ) {
3036 if( isset( $options['dir'] ) ) {
3038 if( $wgLang->getDir() != $options['dir'] ) {
3043 if( isset( $options['media'] ) ) {
3044 $media = self
::transformCssMedia( $options['media'] );
3045 if( is_null( $media ) ) {
3052 if( substr( $style, 0, 1 ) == '/' ||
3053 substr( $style, 0, 5 ) == 'http:' ||
3054 substr( $style, 0, 6 ) == 'https:' ) {
3057 global $wgStylePath, $wgStyleVersion;
3058 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
3061 $link = Html
::linkedStyle( $url, $media );
3063 if( isset( $options['condition'] ) ) {
3064 $condition = htmlspecialchars( $options['condition'] );
3065 $link = "<!--[if $condition]>$link<![endif]-->";
3071 * Transform "media" attribute based on request parameters
3073 * @param $media String: current value of the "media" attribute
3074 * @return String: modified value of the "media" attribute
3076 public static function transformCssMedia( $media ) {
3077 global $wgRequest, $wgHandheldForIPhone;
3079 // Switch in on-screen display for media testing
3081 'printable' => 'print',
3082 'handheld' => 'handheld',
3084 foreach( $switches as $switch => $targetMedia ) {
3085 if( $wgRequest->getBool( $switch ) ) {
3086 if( $media == $targetMedia ) {
3088 } elseif( $media == 'screen' ) {
3094 // Expand longer media queries as iPhone doesn't grok 'handheld'
3095 if( $wgHandheldForIPhone ) {
3096 $mediaAliases = array(
3097 'screen' => 'screen and (min-device-width: 481px)',
3098 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
3101 if( isset( $mediaAliases[$media] ) ) {
3102 $media = $mediaAliases[$media];
3110 * Add a wikitext-formatted message to the output.
3111 * This is equivalent to:
3113 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
3115 public function addWikiMsg( /*...*/ ) {
3116 $args = func_get_args();
3117 $name = array_shift( $args );
3118 $this->addWikiMsgArray( $name, $args );
3122 * Add a wikitext-formatted message to the output.
3123 * Like addWikiMsg() except the parameters are taken as an array
3124 * instead of a variable argument list.
3126 * $options is passed through to wfMsgExt(), see that function for details.
3128 * @param $name string
3129 * @param $args array
3130 * @param $options array
3132 public function addWikiMsgArray( $name, $args, $options = array() ) {
3133 $options[] = 'parse';
3134 $text = wfMsgExt( $name, $options, $args );
3135 $this->addHTML( $text );
3139 * This function takes a number of message/argument specifications, wraps them in
3140 * some overall structure, and then parses the result and adds it to the output.
3142 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3143 * on. The subsequent arguments may either be strings, in which case they are the
3144 * message names, or arrays, in which case the first element is the message name,
3145 * and subsequent elements are the parameters to that message.
3147 * The special named parameter 'options' in a message specification array is passed
3148 * through to the $options parameter of wfMsgExt().
3150 * Don't use this for messages that are not in users interface language.
3154 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3158 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . "\n</div>" );
3160 * The newline after opening div is needed in some wikitext. See bug 19226.
3162 * @param $wrap string
3164 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3165 $msgSpecs = func_get_args();
3166 array_shift( $msgSpecs );
3167 $msgSpecs = array_values( $msgSpecs );
3169 foreach ( $msgSpecs as $n => $spec ) {
3171 if ( is_array( $spec ) ) {
3173 $name = array_shift( $args );
3174 if ( isset( $args['options'] ) ) {
3175 $options = $args['options'];
3176 unset( $args['options'] );
3182 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
3184 $this->addWikiText( $s );
3188 * Include jQuery core. Use this to avoid loading it multiple times
3189 * before we get a usable script loader.
3191 * @param $modules Array: list of jQuery modules which should be loaded
3192 * @return Array: the list of modules which were not loaded.
3194 * @deprecated since 1.17
3196 public function includeJQuery( $modules = array() ) {