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
21 class OutputPage
extends ContextSource
{
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 = false;
53 * Should be private. Has get/set methods properly documented.
54 * Stores "article flag" toggle.
56 var $mIsArticleRelated = true;
59 * Should be private. We have to set isPrintable(). Some pages should
60 * never be printed (ex: redirections).
62 var $mPrintable = false;
65 * Should be private. We have set/get/append methods.
67 * Contains the page subtitle. Special pages usually have some links here.
68 * Don't confuse with site subtitle added by skins.
76 * mLastModified and mEtag are used for sending cache control.
77 * The whole caching system should probably be moved into its own class.
79 var $mLastModified = '';
82 * Should be private. No getter but used in sendCacheControl();
83 * Contains an HTTP Entity Tags (see RFC 2616 section 3.13) which is used
84 * as a unique identifier for the content. It is later used by the client
85 * to compare its cached version with the server version. Client sends
86 * headers If-Match and If-None-Match containing its locally cached ETAG value.
88 * To get more information, you will have to look at HTTP/1.1 protocol which
89 * is properly described in RFC 2616 : http://tools.ietf.org/html/rfc2616
93 var $mCategoryLinks = array();
94 var $mCategories = array();
96 /// Should be private. Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
97 var $mLanguageLinks = array();
100 * Should be private. Used for JavaScript (pre resource loader)
101 * We should split js / css.
102 * mScripts content is inserted as is in <head> by Skin. This might contains
103 * either a link to a stylesheet or inline css.
108 * Inline CSS styles. Use addInlineStyle() sparsingly
110 var $mInlineStyles = '';
116 * Used by skin template.
117 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
119 var $mPageLinkTitle = '';
121 /// Array of elements in <head>. Parser might add its own headers!
122 var $mHeadItems = array();
124 // @todo FIXME: Next variables probably comes from the resource loader
125 var $mModules = array(), $mModuleScripts = array(), $mModuleStyles = array(), $mModuleMessages = array();
126 var $mResourceLoader;
127 var $mJsConfigVars = array();
129 /** @todo FIXME: Is this still used ?*/
130 var $mInlineMsg = array();
132 var $mTemplateIds = array();
133 var $mImageTimeKeys = array();
135 var $mRedirectCode = '';
137 var $mFeedLinksAppendQuery = null;
139 # What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
140 # @see ResourceLoaderModule::$origin
141 # ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
142 protected $mAllowedModules = array(
143 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
147 * @EasterEgg I just love the name for this self documenting variable.
150 var $mDoNothing = false;
153 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
155 /// lazy initialised, use parserOptions()
156 protected $mParserOptions = null;
159 * Handles the atom / rss links.
160 * We probably only support atom in 2011.
161 * Looks like a private variable.
162 * @see $wgAdvertisedFeedTypes
164 var $mFeedLinks = array();
166 // Gwicke work on squid caching? Roughly from 2003.
167 var $mEnableClientCache = true;
170 * Flag if output should only contain the body of the article.
173 var $mArticleBodyOnly = false;
175 var $mNewSectionLink = false;
176 var $mHideNewSectionLink = false;
179 * Comes from the parser. This was probably made to load CSS/JS only
180 * if we had <gallery>. Used directly in CategoryPage.php
181 * Looks like resource loader can replace this.
183 var $mNoGallery = false;
185 // should be private.
186 var $mPageTitleActionText = '';
187 var $mParseWarnings = array();
189 // Cache stuff. Looks like mEnableClientCache
190 var $mSquidMaxage = 0;
193 var $mPreventClickjacking = true;
195 /// should be private. To include the variable {{REVISIONID}}
196 var $mRevisionId = null;
198 var $mFileVersion = null;
201 * An array of stylesheet filenames (relative from skins path), with options
202 * for CSS media, IE conditions, and RTL/LTR direction.
203 * For internal use; add settings in the skin via $this->addStyle()
205 * Style again! This seems like a code duplication since we already have
206 * mStyles. This is what makes OpenSource amazing.
208 var $styles = array();
211 * Whether jQuery is already handled.
213 protected $mJQueryDone = false;
215 private $mIndexPolicy = 'index';
216 private $mFollowPolicy = 'follow';
217 private $mVaryHeader = array(
218 'Accept-Encoding' => array( 'list-contains=gzip' ),
223 * Constructor for OutputPage. This should not be called directly.
224 * Instead a new RequestContext should be created and it will implicitly create
225 * a OutputPage tied to that context.
227 function __construct( IContextSource
$context = null ) {
228 if ( $context === null ) {
229 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
230 wfDeprecated( __METHOD__
);
232 $this->setContext( $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 an array of head items
518 function getHeadItemsArray() {
519 return $this->mHeadItems
;
523 * Get all header items in a string
527 function getHeadItems() {
529 foreach ( $this->mHeadItems
as $item ) {
536 * Add or replace an header item to the output
538 * @param $name String: item name
539 * @param $value String: raw HTML
541 public function addHeadItem( $name, $value ) {
542 $this->mHeadItems
[$name] = $value;
546 * Check if the header item $name is already set
548 * @param $name String: item name
551 public function hasHeadItem( $name ) {
552 return isset( $this->mHeadItems
[$name] );
556 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
558 * @param $tag String: value of "ETag" header
560 function setETag( $tag ) {
565 * Set whether the output should only contain the body of the article,
566 * without any skin, sidebar, etc.
567 * Used e.g. when calling with "action=render".
569 * @param $only Boolean: whether to output only the body of the article
571 public function setArticleBodyOnly( $only ) {
572 $this->mArticleBodyOnly
= $only;
576 * Return whether the output will contain only the body of the article
580 public function getArticleBodyOnly() {
581 return $this->mArticleBodyOnly
;
585 * checkLastModified tells the client to use the client-cached page if
586 * possible. If sucessful, the OutputPage is disabled so that
587 * any future call to OutputPage->output() have no effect.
589 * Side effect: sets mLastModified for Last-Modified header
591 * @param $timestamp string
593 * @return Boolean: true iff cache-ok headers was sent.
595 public function checkLastModified( $timestamp ) {
596 global $wgCachePages, $wgCacheEpoch;
598 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
599 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
602 if( !$wgCachePages ) {
603 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
606 if( $this->getUser()->getOption( 'nocache' ) ) {
607 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
611 $timestamp = wfTimestamp( TS_MW
, $timestamp );
612 $modifiedTimes = array(
613 'page' => $timestamp,
614 'user' => $this->getUser()->getTouched(),
615 'epoch' => $wgCacheEpoch
617 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
619 $maxModified = max( $modifiedTimes );
620 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
622 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
623 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
629 foreach ( $modifiedTimes as $name => $value ) {
630 if ( $info !== '' ) {
633 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
636 # IE sends sizes after the date like this:
637 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
638 # this breaks strtotime().
639 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
641 wfSuppressWarnings(); // E_STRICT system time bitching
642 $clientHeaderTime = strtotime( $clientHeader );
644 if ( !$clientHeaderTime ) {
645 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
648 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
650 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
651 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
652 wfDebug( __METHOD__
. ": effective Last-Modified: " .
653 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
654 if( $clientHeaderTime < $maxModified ) {
655 wfDebug( __METHOD__
. ": STALE, $info\n", false );
660 # Give a 304 response code and disable body output
661 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
662 ini_set( 'zlib.output_compression', 0 );
663 $this->getRequest()->response()->header( "HTTP/1.1 304 Not Modified" );
664 $this->sendCacheControl();
667 // Don't output a compressed blob when using ob_gzhandler;
668 // it's technically against HTTP spec and seems to confuse
669 // Firefox when the response gets split over two packets.
670 wfClearOutputBuffers();
676 * Override the last modified timestamp
678 * @param $timestamp String: new timestamp, in a format readable by
681 public function setLastModified( $timestamp ) {
682 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
686 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
688 * @param $policy String: the literal string to output as the contents of
689 * the meta tag. Will be parsed according to the spec and output in
693 public function setRobotPolicy( $policy ) {
694 $policy = Article
::formatRobotPolicy( $policy );
696 if( isset( $policy['index'] ) ) {
697 $this->setIndexPolicy( $policy['index'] );
699 if( isset( $policy['follow'] ) ) {
700 $this->setFollowPolicy( $policy['follow'] );
705 * Set the index policy for the page, but leave the follow policy un-
708 * @param $policy string Either 'index' or 'noindex'.
711 public function setIndexPolicy( $policy ) {
712 $policy = trim( $policy );
713 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
714 $this->mIndexPolicy
= $policy;
719 * Set the follow policy for the page, but leave the index policy un-
722 * @param $policy String: either 'follow' or 'nofollow'.
725 public function setFollowPolicy( $policy ) {
726 $policy = trim( $policy );
727 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
728 $this->mFollowPolicy
= $policy;
733 * Set the new value of the "action text", this will be added to the
734 * "HTML title", separated from it with " - ".
736 * @param $text String: new value of the "action text"
738 public function setPageTitleActionText( $text ) {
739 $this->mPageTitleActionText
= $text;
743 * Get the value of the "action text"
747 public function getPageTitleActionText() {
748 if ( isset( $this->mPageTitleActionText
) ) {
749 return $this->mPageTitleActionText
;
754 * "HTML title" means the contents of <title>.
755 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
757 * @param $name string
759 public function setHTMLTitle( $name ) {
760 $this->mHTMLtitle
= $name;
764 * Return the "HTML title", i.e. the content of the <title> tag.
768 public function getHTMLTitle() {
769 return $this->mHTMLtitle
;
773 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
774 * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
775 * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
776 * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
778 * @param $name string
780 public function setPageTitle( $name ) {
781 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
782 # but leave "<i>foobar</i>" alone
783 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
784 $this->mPagetitle
= $nameWithTags;
786 # change "<i>foo&bar</i>" to "foo&bar"
787 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer
::stripAllTags( $nameWithTags ) ) );
791 * Return the "page title", i.e. the content of the \<h1\> tag.
795 public function getPageTitle() {
796 return $this->mPagetitle
;
800 * Set the Title object to use
802 * @param $t Title object
804 public function setTitle( Title
$t ) {
805 $this->getContext()->setTitle( $t );
810 * Replace the subtile with $str
812 * @param $str String: new value of the subtitle
814 public function setSubtitle( $str ) {
815 $this->mSubtitle
= /*$this->parse(*/ $str /*)*/; // @bug 2514
819 * Add $str to the subtitle
821 * @param $str String to add to the subtitle
823 public function appendSubtitle( $str ) {
824 $this->mSubtitle
.= /*$this->parse(*/ $str /*)*/; // @bug 2514
832 public function getSubtitle() {
833 return $this->mSubtitle
;
837 * Set the page as printable, i.e. it'll be displayed with with all
838 * print styles included
840 public function setPrintable() {
841 $this->mPrintable
= true;
845 * Return whether the page is "printable"
849 public function isPrintable() {
850 return $this->mPrintable
;
854 * Disable output completely, i.e. calling output() will have no effect
856 public function disable() {
857 $this->mDoNothing
= true;
861 * Return whether the output will be completely disabled
865 public function isDisabled() {
866 return $this->mDoNothing
;
870 * Show an "add new section" link?
874 public function showNewSectionLink() {
875 return $this->mNewSectionLink
;
879 * Forcibly hide the new section link?
883 public function forceHideNewSectionLink() {
884 return $this->mHideNewSectionLink
;
888 * Add or remove feed links in the page header
889 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
890 * for the new version
893 * @param $show Boolean: true: add default feeds, false: remove all feeds
895 public function setSyndicated( $show = true ) {
897 $this->setFeedAppendQuery( false );
899 $this->mFeedLinks
= array();
904 * Add default feeds to the page header
905 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
906 * for the new version
909 * @param $val String: query to append to feed links or false to output
912 public function setFeedAppendQuery( $val ) {
913 global $wgAdvertisedFeedTypes;
915 $this->mFeedLinks
= array();
917 foreach ( $wgAdvertisedFeedTypes as $type ) {
918 $query = "feed=$type";
919 if ( is_string( $val ) ) {
920 $query .= '&' . $val;
922 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
927 * Add a feed link to the page header
929 * @param $format String: feed type, should be a key of $wgFeedClasses
930 * @param $href String: URL
932 public function addFeedLink( $format, $href ) {
933 global $wgAdvertisedFeedTypes;
935 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
936 $this->mFeedLinks
[$format] = $href;
941 * Should we output feed links for this page?
944 public function isSyndicated() {
945 return count( $this->mFeedLinks
) > 0;
949 * Return URLs for each supported syndication format for this page.
950 * @return array associating format keys with URLs
952 public function getSyndicationLinks() {
953 return $this->mFeedLinks
;
957 * Will currently always return null
961 public function getFeedAppendQuery() {
962 return $this->mFeedLinksAppendQuery
;
966 * Set whether the displayed content is related to the source of the
967 * corresponding article on the wiki
968 * Setting true will cause the change "article related" toggle to true
972 public function setArticleFlag( $v ) {
973 $this->mIsarticle
= $v;
975 $this->mIsArticleRelated
= $v;
980 * Return whether the content displayed page is related to the source of
981 * the corresponding article on the wiki
985 public function isArticle() {
986 return $this->mIsarticle
;
990 * Set whether this page is related an article on the wiki
991 * Setting false will cause the change of "article flag" toggle to false
995 public function setArticleRelated( $v ) {
996 $this->mIsArticleRelated
= $v;
998 $this->mIsarticle
= false;
1003 * Return whether this page is related an article on the wiki
1007 public function isArticleRelated() {
1008 return $this->mIsArticleRelated
;
1012 * Add new language links
1014 * @param $newLinkArray Associative array mapping language code to the page
1017 public function addLanguageLinks( $newLinkArray ) {
1018 $this->mLanguageLinks +
= $newLinkArray;
1022 * Reset the language links and add new language links
1024 * @param $newLinkArray Associative array mapping language code to the page
1027 public function setLanguageLinks( $newLinkArray ) {
1028 $this->mLanguageLinks
= $newLinkArray;
1032 * Get the list of language links
1034 * @return Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1036 public function getLanguageLinks() {
1037 return $this->mLanguageLinks
;
1041 * Add an array of categories, with names in the keys
1043 * @param $categories Array mapping category name => sort key
1045 public function addCategoryLinks( $categories ) {
1048 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1052 # Add the links to a LinkBatch
1053 $arr = array( NS_CATEGORY
=> $categories );
1054 $lb = new LinkBatch
;
1055 $lb->setArray( $arr );
1057 # Fetch existence plus the hiddencat property
1058 $dbr = wfGetDB( DB_SLAVE
);
1059 $res = $dbr->select( array( 'page', 'page_props' ),
1060 array( 'page_id', 'page_namespace', 'page_title', 'page_len', 'page_is_redirect', 'page_latest', 'pp_value' ),
1061 $lb->constructSet( 'page', $dbr ),
1064 array( 'page_props' => array( 'LEFT JOIN', array( 'pp_propname' => 'hiddencat', 'pp_page = page_id' ) ) )
1067 # Add the results to the link cache
1068 $lb->addResultToCache( LinkCache
::singleton(), $res );
1070 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
1071 $categories = array_combine(
1072 array_keys( $categories ),
1073 array_fill( 0, count( $categories ), 'normal' )
1076 # Mark hidden categories
1077 foreach ( $res as $row ) {
1078 if ( isset( $row->pp_value
) ) {
1079 $categories[$row->page_title
] = 'hidden';
1083 # Add the remaining categories to the skin
1084 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
1085 foreach ( $categories as $category => $type ) {
1086 $origcategory = $category;
1087 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1088 $wgContLang->findVariantLink( $category, $title, true );
1089 if ( $category != $origcategory ) {
1090 if ( array_key_exists( $category, $categories ) ) {
1094 $text = $wgContLang->convertHtml( $title->getText() );
1095 $this->mCategories
[] = $title->getText();
1096 $this->mCategoryLinks
[$type][] = Linker
::link( $title, $text );
1102 * Reset the category links (but not the category list) and add $categories
1104 * @param $categories Array mapping category name => sort key
1106 public function setCategoryLinks( $categories ) {
1107 $this->mCategoryLinks
= array();
1108 $this->addCategoryLinks( $categories );
1112 * Get the list of category links, in a 2-D array with the following format:
1113 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1114 * hidden categories) and $link a HTML fragment with a link to the category
1119 public function getCategoryLinks() {
1120 return $this->mCategoryLinks
;
1124 * Get the list of category names this page belongs to
1126 * @return Array of strings
1128 public function getCategories() {
1129 return $this->mCategories
;
1133 * Do not allow scripts which can be modified by wiki users to load on this page;
1134 * only allow scripts bundled with, or generated by, the software.
1136 public function disallowUserJs() {
1137 $this->reduceAllowedModules(
1138 ResourceLoaderModule
::TYPE_SCRIPTS
,
1139 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1144 * Return whether user JavaScript is allowed for this page
1145 * @deprecated since 1.18 Load modules with ResourceLoader, and origin and
1146 * trustworthiness is identified and enforced automagically.
1149 public function isUserJsAllowed() {
1150 return $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
) >= ResourceLoaderModule
::ORIGIN_USER_INDIVIDUAL
;
1154 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1155 * @see ResourceLoaderModule::$origin
1156 * @param $type String ResourceLoaderModule TYPE_ constant
1157 * @return Int ResourceLoaderModule ORIGIN_ class constant
1159 public function getAllowedModules( $type ){
1160 if( $type == ResourceLoaderModule
::TYPE_COMBINED
){
1161 return min( array_values( $this->mAllowedModules
) );
1163 return isset( $this->mAllowedModules
[$type] )
1164 ?
$this->mAllowedModules
[$type]
1165 : ResourceLoaderModule
::ORIGIN_ALL
;
1170 * Set the highest level of CSS/JS untrustworthiness allowed
1171 * @param $type String ResourceLoaderModule TYPE_ constant
1172 * @param $level Int ResourceLoaderModule class constant
1174 public function setAllowedModules( $type, $level ){
1175 $this->mAllowedModules
[$type] = $level;
1179 * As for setAllowedModules(), but don't inadvertantly make the page more accessible
1180 * @param $type String
1181 * @param $level Int ResourceLoaderModule class constant
1183 public function reduceAllowedModules( $type, $level ){
1184 $this->mAllowedModules
[$type] = min( $this->getAllowedModules($type), $level );
1188 * Prepend $text to the body HTML
1190 * @param $text String: HTML
1192 public function prependHTML( $text ) {
1193 $this->mBodytext
= $text . $this->mBodytext
;
1197 * Append $text to the body HTML
1199 * @param $text String: HTML
1201 public function addHTML( $text ) {
1202 $this->mBodytext
.= $text;
1206 * Shortcut for adding an Html::element via addHTML.
1210 * @param $element string
1211 * @param $attribs array
1212 * @param $contents string
1214 public function addElement( $element, $attribs = array(), $contents = '' ) {
1215 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1219 * Clear the body HTML
1221 public function clearHTML() {
1222 $this->mBodytext
= '';
1228 * @return String: HTML
1230 public function getHTML() {
1231 return $this->mBodytext
;
1235 * Add $text to the debug output
1237 * @param $text String: debug text
1239 public function debug( $text ) {
1240 $this->mDebugtext
.= $text;
1244 * Get/set the ParserOptions object to use for wikitext parsing
1246 * @param $options either the ParserOption to use or null to only get the
1247 * current ParserOption object
1248 * @return ParserOptions object
1250 public function parserOptions( $options = null ) {
1251 if ( !$this->mParserOptions
) {
1252 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1253 $this->mParserOptions
->setEditSection( false );
1255 return wfSetVar( $this->mParserOptions
, $options );
1259 * Set the revision ID which will be seen by the wiki text parser
1260 * for things such as embedded {{REVISIONID}} variable use.
1262 * @param $revid Mixed: an positive integer, or null
1263 * @return Mixed: previous value
1265 public function setRevisionId( $revid ) {
1266 $val = is_null( $revid ) ?
null : intval( $revid );
1267 return wfSetVar( $this->mRevisionId
, $val );
1271 * Get the displayed revision ID
1275 public function getRevisionId() {
1276 return $this->mRevisionId
;
1280 * Set the displayed file version
1282 * @param $file File|false
1283 * @return Mixed: previous value
1285 public function setFileVersion( $file ) {
1287 if ( $file instanceof File
&& $file->exists() ) {
1288 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1290 return wfSetVar( $this->mFileVersion
, $val, true );
1294 * Get the displayed file version
1296 * @return Array|null ('time' => MW timestamp, 'sha1' => sha1)
1298 public function getFileVersion() {
1299 return $this->mFileVersion
;
1303 * Get the templates used on this page
1305 * @return Array (namespace => dbKey => revId)
1308 public function getTemplateIds() {
1309 return $this->mTemplateIds
;
1313 * Get the files used on this page
1315 * @return Array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1318 public function getFileSearchOptions() {
1319 return $this->mImageTimeKeys
;
1323 * Convert wikitext to HTML and add it to the buffer
1324 * Default assumes that the current page title will be used.
1326 * @param $text String
1327 * @param $linestart Boolean: is this the start of a line?
1328 * @param $interface Boolean: is this text in the user interface language?
1330 public function addWikiText( $text, $linestart = true, $interface = true ) {
1331 $title = $this->getTitle(); // Work arround E_STRICT
1332 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1336 * Add wikitext with a custom Title object
1338 * @param $text String: wikitext
1339 * @param $title Title object
1340 * @param $linestart Boolean: is this the start of a line?
1342 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1343 $this->addWikiTextTitle( $text, $title, $linestart );
1347 * Add wikitext with a custom Title object and tidy enabled.
1349 * @param $text String: wikitext
1350 * @param $title Title object
1351 * @param $linestart Boolean: is this the start of a line?
1353 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1354 $this->addWikiTextTitle( $text, $title, $linestart, true );
1358 * Add wikitext with tidy enabled
1360 * @param $text String: wikitext
1361 * @param $linestart Boolean: is this the start of a line?
1363 public function addWikiTextTidy( $text, $linestart = true ) {
1364 $title = $this->getTitle();
1365 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1369 * Add wikitext with a custom Title object
1371 * @param $text String: wikitext
1372 * @param $title Title object
1373 * @param $linestart Boolean: is this the start of a line?
1374 * @param $tidy Boolean: whether to use tidy
1375 * @param $interface Boolean: whether it is an interface message
1376 * (for example disables conversion)
1378 public function addWikiTextTitle( $text, &$title, $linestart, $tidy = false, $interface = false ) {
1381 wfProfileIn( __METHOD__
);
1383 wfIncrStats( 'pcache_not_possible' );
1385 $popts = $this->parserOptions();
1386 $oldTidy = $popts->setTidy( $tidy );
1387 $popts->setInterfaceMessage( (bool) $interface );
1389 $parserOutput = $wgParser->parse(
1390 $text, $title, $popts,
1391 $linestart, true, $this->mRevisionId
1394 $popts->setTidy( $oldTidy );
1396 $this->addParserOutput( $parserOutput );
1398 wfProfileOut( __METHOD__
);
1402 * Add a ParserOutput object, but without Html
1404 * @param $parserOutput ParserOutput object
1406 public function addParserOutputNoText( &$parserOutput ) {
1407 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1408 $this->addCategoryLinks( $parserOutput->getCategories() );
1409 $this->mNewSectionLink
= $parserOutput->getNewSection();
1410 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1412 $this->mParseWarnings
= $parserOutput->getWarnings();
1413 if ( !$parserOutput->isCacheable() ) {
1414 $this->enableClientCache( false );
1416 $this->mNoGallery
= $parserOutput->getNoGallery();
1417 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1418 $this->addModules( $parserOutput->getModules() );
1419 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1420 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1421 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1423 // Template versioning...
1424 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1425 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1426 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1428 $this->mTemplateIds
[$ns] = $dbks;
1431 // File versioning...
1432 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1433 $this->mImageTimeKeys
[$dbk] = $data;
1436 // Hooks registered in the object
1437 global $wgParserOutputHooks;
1438 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1439 list( $hookName, $data ) = $hookInfo;
1440 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1441 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1445 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1449 * Add a ParserOutput object
1451 * @param $parserOutput ParserOutput
1453 function addParserOutput( &$parserOutput ) {
1454 $this->addParserOutputNoText( $parserOutput );
1455 $text = $parserOutput->getText();
1456 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1457 $this->addHTML( $text );
1462 * Add the output of a QuickTemplate to the output buffer
1464 * @param $template QuickTemplate
1466 public function addTemplate( &$template ) {
1468 $template->execute();
1469 $this->addHTML( ob_get_contents() );
1474 * Parse wikitext and return the HTML.
1476 * @param $text String
1477 * @param $linestart Boolean: is this the start of a line?
1478 * @param $interface Boolean: use interface language ($wgLang instead of
1479 * $wgContLang) while parsing language sensitive magic
1480 * words like GRAMMAR and PLURAL. This also disables
1481 * LanguageConverter.
1482 * @param $language Language object: target language object, will override
1484 * @return String: HTML
1486 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1489 if( is_null( $this->getTitle() ) ) {
1490 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1493 $popts = $this->parserOptions();
1495 $popts->setInterfaceMessage( true );
1497 if ( $language !== null ) {
1498 $oldLang = $popts->setTargetLanguage( $language );
1501 $parserOutput = $wgParser->parse(
1502 $text, $this->getTitle(), $popts,
1503 $linestart, true, $this->mRevisionId
1507 $popts->setInterfaceMessage( false );
1509 if ( $language !== null ) {
1510 $popts->setTargetLanguage( $oldLang );
1513 return $parserOutput->getText();
1517 * Parse wikitext, strip paragraphs, and return the HTML.
1519 * @param $text String
1520 * @param $linestart Boolean: is this the start of a line?
1521 * @param $interface Boolean: use interface language ($wgLang instead of
1522 * $wgContLang) while parsing language sensitive magic
1523 * words like GRAMMAR and PLURAL
1524 * @return String: HTML
1526 public function parseInline( $text, $linestart = true, $interface = false ) {
1527 $parsed = $this->parse( $text, $linestart, $interface );
1530 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1538 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1540 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1542 public function setSquidMaxage( $maxage ) {
1543 $this->mSquidMaxage
= $maxage;
1547 * Use enableClientCache(false) to force it to send nocache headers
1549 * @param $state bool
1553 public function enableClientCache( $state ) {
1554 return wfSetVar( $this->mEnableClientCache
, $state );
1558 * Get the list of cookies that will influence on the cache
1562 function getCacheVaryCookies() {
1563 global $wgCookiePrefix, $wgCacheVaryCookies;
1565 if ( $cookies === null ) {
1566 $cookies = array_merge(
1568 "{$wgCookiePrefix}Token",
1569 "{$wgCookiePrefix}LoggedOut",
1574 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1580 * Return whether this page is not cacheable because "useskin" or "uselang"
1581 * URL parameters were passed.
1585 function uncacheableBecauseRequestVars() {
1586 $request = $this->getRequest();
1587 return $request->getText( 'useskin', false ) === false
1588 && $request->getText( 'uselang', false ) === false;
1592 * Check if the request has a cache-varying cookie header
1593 * If it does, it's very important that we don't allow public caching
1597 function haveCacheVaryCookies() {
1598 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1599 if ( $cookieHeader === false ) {
1602 $cvCookies = $this->getCacheVaryCookies();
1603 foreach ( $cvCookies as $cookieName ) {
1604 # Check for a simple string match, like the way squid does it
1605 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1606 wfDebug( __METHOD__
. ": found $cookieName\n" );
1610 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1615 * Add an HTTP header that will influence on the cache
1617 * @param $header String: header name
1618 * @param $option Array|null
1619 * @todo FIXME: Document the $option parameter; it appears to be for
1620 * X-Vary-Options but what format is acceptable?
1622 public function addVaryHeader( $header, $option = null ) {
1623 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1624 $this->mVaryHeader
[$header] = (array)$option;
1625 } elseif( is_array( $option ) ) {
1626 if( is_array( $this->mVaryHeader
[$header] ) ) {
1627 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
1629 $this->mVaryHeader
[$header] = $option;
1632 $this->mVaryHeader
[$header] = array_unique( $this->mVaryHeader
[$header] );
1636 * Get a complete X-Vary-Options header
1640 public function getXVO() {
1641 $cvCookies = $this->getCacheVaryCookies();
1643 $cookiesOption = array();
1644 foreach ( $cvCookies as $cookieName ) {
1645 $cookiesOption[] = 'string-contains=' . $cookieName;
1647 $this->addVaryHeader( 'Cookie', $cookiesOption );
1650 foreach( $this->mVaryHeader
as $header => $option ) {
1651 $newheader = $header;
1652 if( is_array( $option ) ) {
1653 $newheader .= ';' . implode( ';', $option );
1655 $headers[] = $newheader;
1657 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1663 * bug 21672: Add Accept-Language to Vary and XVO headers
1664 * if there's no 'variant' parameter existed in GET.
1667 * /w/index.php?title=Main_page should always be served; but
1668 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1670 function addAcceptLanguage() {
1671 $lang = $this->getTitle()->getPageLanguage();
1672 if( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
1673 $variants = $lang->getVariants();
1674 $aloption = array();
1675 foreach ( $variants as $variant ) {
1676 if( $variant === $lang->getCode() ) {
1679 $aloption[] = 'string-contains=' . $variant;
1681 // IE and some other browsers use another form of language code
1682 // in their Accept-Language header, like "zh-CN" or "zh-TW".
1683 // We should handle these too.
1684 $ievariant = explode( '-', $variant );
1685 if ( count( $ievariant ) == 2 ) {
1686 $ievariant[1] = strtoupper( $ievariant[1] );
1687 $ievariant = implode( '-', $ievariant );
1688 $aloption[] = 'string-contains=' . $ievariant;
1692 $this->addVaryHeader( 'Accept-Language', $aloption );
1697 * Set a flag which will cause an X-Frame-Options header appropriate for
1698 * edit pages to be sent. The header value is controlled by
1699 * $wgEditPageFrameOptions.
1701 * This is the default for special pages. If you display a CSRF-protected
1702 * form on an ordinary view page, then you need to call this function.
1704 * @param $enable bool
1706 public function preventClickjacking( $enable = true ) {
1707 $this->mPreventClickjacking
= $enable;
1711 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1712 * This can be called from pages which do not contain any CSRF-protected
1715 public function allowClickjacking() {
1716 $this->mPreventClickjacking
= false;
1720 * Get the X-Frame-Options header value (without the name part), or false
1721 * if there isn't one. This is used by Skin to determine whether to enable
1722 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1726 public function getFrameOptions() {
1727 global $wgBreakFrames, $wgEditPageFrameOptions;
1728 if ( $wgBreakFrames ) {
1730 } elseif ( $this->mPreventClickjacking
&& $wgEditPageFrameOptions ) {
1731 return $wgEditPageFrameOptions;
1737 * Send cache control HTTP headers
1739 public function sendCacheControl() {
1740 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgUseXVO;
1742 $response = $this->getRequest()->response();
1743 if ( $wgUseETag && $this->mETag
) {
1744 $response->header( "ETag: $this->mETag" );
1747 $this->addAcceptLanguage();
1749 # don't serve compressed data to clients who can't handle it
1750 # maintain different caches for logged-in users and non-logged in ones
1751 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) ) );
1754 # Add an X-Vary-Options header for Squid with Wikimedia patches
1755 $response->header( $this->getXVO() );
1758 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
1760 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1761 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
1765 # We'll purge the proxy cache explicitly, but require end user agents
1766 # to revalidate against the proxy on each visit.
1767 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1768 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1769 # start with a shorter timeout for initial testing
1770 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1771 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
1772 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1774 # We'll purge the proxy cache for anons explicitly, but require end user agents
1775 # to revalidate against the proxy on each visit.
1776 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1777 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1778 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
1779 # start with a shorter timeout for initial testing
1780 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1781 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
1784 # We do want clients to cache if they can, but they *must* check for updates
1785 # on revisiting the page.
1786 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
1787 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1788 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1790 if($this->mLastModified
) {
1791 $response->header( "Last-Modified: {$this->mLastModified}" );
1794 wfDebug( __METHOD__
. ": no caching **\n", false );
1796 # In general, the absence of a last modified header should be enough to prevent
1797 # the client from using its cache. We send a few other things just to make sure.
1798 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1799 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1800 $response->header( 'Pragma: no-cache' );
1805 * Get the message associed with the HTTP response code $code
1807 * @param $code Integer: status code
1808 * @return String or null: message or null if $code is not in the list of
1811 * @deprecated since 1.18 Use HttpStatus::getMessage() instead.
1813 public static function getStatusMessage( $code ) {
1814 wfDeprecated( __METHOD__
);
1815 return HttpStatus
::getMessage( $code );
1819 * Finally, all the text has been munged and accumulated into
1820 * the object, let's actually output it:
1822 public function output() {
1823 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType, $wgVaryOnXFP;
1825 if( $this->mDoNothing
) {
1829 wfProfileIn( __METHOD__
);
1831 $response = $this->getRequest()->response();
1833 if ( $this->mRedirect
!= '' ) {
1834 # Standards require redirect URLs to be absolute
1835 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
1836 if( $this->mRedirectCode
== '301' ||
$this->mRedirectCode
== '303' ) {
1837 if( !$wgDebugRedirects ) {
1838 $message = HttpStatus
::getMessage( $this->mRedirectCode
);
1839 $response->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
1841 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1843 if ( $wgVaryOnXFP ) {
1844 $this->addVaryHeader( 'X-Forwarded-Proto' );
1846 $this->sendCacheControl();
1848 $response->header( "Content-Type: text/html; charset=utf-8" );
1849 if( $wgDebugRedirects ) {
1850 $url = htmlspecialchars( $this->mRedirect
);
1851 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1852 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1853 print "</body>\n</html>\n";
1855 $response->header( 'Location: ' . $this->mRedirect
);
1857 wfProfileOut( __METHOD__
);
1859 } elseif ( $this->mStatusCode
) {
1860 $message = HttpStatus
::getMessage( $this->mStatusCode
);
1862 $response->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
1866 # Buffer output; final headers may depend on later processing
1869 $response->header( "Content-type: $wgMimeType; charset=UTF-8" );
1870 $response->header( 'Content-language: ' . $wgLanguageCode );
1872 // Prevent framing, if requested
1873 $frameOptions = $this->getFrameOptions();
1874 if ( $frameOptions ) {
1875 $response->header( "X-Frame-Options: $frameOptions" );
1878 if ( $this->mArticleBodyOnly
) {
1879 $this->out( $this->mBodytext
);
1881 $this->addDefaultModules();
1883 $sk = $this->getSkin();
1885 // Hook that allows last minute changes to the output page, e.g.
1886 // adding of CSS or Javascript by extensions.
1887 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1889 wfProfileIn( 'Output-skin' );
1891 wfProfileOut( 'Output-skin' );
1894 $this->sendCacheControl();
1896 wfProfileOut( __METHOD__
);
1900 * Actually output something with print().
1902 * @param $ins String: the string to output
1904 public function out( $ins ) {
1909 * Produce a "user is blocked" page.
1910 * @deprecated since 1.18
1912 function blockedPage() {
1913 throw new UserBlockedError( $this->getUser()->mBlock
);
1917 * Output a standard error page
1919 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
1920 * showErrorPage( 'titlemsg', $messageObject );
1922 * @param $title String: message key for page title
1923 * @param $msg Mixed: message key (string) for page text, or a Message object
1924 * @param $params Array: message parameters; ignored if $msg is a Message object
1926 public function showErrorPage( $title, $msg, $params = array() ) {
1927 if ( $this->getTitle() ) {
1928 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1930 $this->setPageTitle( wfMsg( $title ) );
1931 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1932 $this->setRobotPolicy( 'noindex,nofollow' );
1933 $this->setArticleRelated( false );
1934 $this->enableClientCache( false );
1935 $this->mRedirect
= '';
1936 $this->mBodytext
= '';
1938 if ( $msg instanceof Message
){
1939 $this->addHTML( $msg->parse() );
1941 $this->addWikiMsgArray( $msg, $params );
1944 $this->returnToMain();
1948 * Output a standard permission error page
1950 * @param $errors Array: error message keys
1951 * @param $action String: action that was denied or null if unknown
1953 public function showPermissionsErrorPage( $errors, $action = null ) {
1954 $this->mDebugtext
.= 'Original title: ' .
1955 $this->getTitle()->getPrefixedText() . "\n";
1956 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1957 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1958 $this->setRobotPolicy( 'noindex,nofollow' );
1959 $this->setArticleRelated( false );
1960 $this->enableClientCache( false );
1961 $this->mRedirect
= '';
1962 $this->mBodytext
= '';
1963 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1967 * Display an error page indicating that a given version of MediaWiki is
1968 * required to use it
1970 * @param $version Mixed: the version of MediaWiki needed to use the page
1972 public function versionRequired( $version ) {
1973 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1974 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1975 $this->setRobotPolicy( 'noindex,nofollow' );
1976 $this->setArticleRelated( false );
1977 $this->mBodytext
= '';
1979 $this->addWikiMsg( 'versionrequiredtext', $version );
1980 $this->returnToMain();
1984 * Display an error page noting that a given permission bit is required.
1985 * @deprecated since 1.18, just throw the exception directly
1986 * @param $permission String: key required
1988 public function permissionRequired( $permission ) {
1989 throw new PermissionsError( $permission );
1993 * Produce the stock "please login to use the wiki" page
1995 public function loginToUse() {
1996 if( $this->getUser()->isLoggedIn() ) {
1997 throw new PermissionsError( 'read' );
2000 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
2001 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
2002 $this->setRobotPolicy( 'noindex,nofollow' );
2003 $this->setArticleRelated( false );
2005 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
2006 $loginLink = Linker
::linkKnown(
2008 wfMsgHtml( 'loginreqlink' ),
2010 array( 'returnto' => $this->getTitle()->getPrefixedText() )
2012 $this->addHTML( wfMessage( 'loginreqpagetext' )->rawParams( $loginLink )->parse() .
2013 "\n<!--" . $this->getTitle()->getPrefixedUrl() . '-->' );
2015 # Don't return to the main page if the user can't read it
2016 # otherwise we'll end up in a pointless loop
2017 $mainPage = Title
::newMainPage();
2018 if( $mainPage->userCanRead() ) {
2019 $this->returnToMain( null, $mainPage );
2024 * Format a list of error messages
2026 * @param $errors Array of arrays returned by Title::getUserPermissionsErrors
2027 * @param $action String: action that was denied or null if unknown
2028 * @return String: the wikitext error-messages, formatted into a list.
2030 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2031 if ( $action == null ) {
2032 $text = wfMsgNoTrans( 'permissionserrorstext', count( $errors ) ) . "\n\n";
2034 $action_desc = wfMsgNoTrans( "action-$action" );
2035 $text = wfMsgNoTrans(
2036 'permissionserrorstext-withaction',
2042 if ( count( $errors ) > 1 ) {
2043 $text .= '<ul class="permissions-errors">' . "\n";
2045 foreach( $errors as $error ) {
2047 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
2052 $text .= "<div class=\"permissions-errors\">\n" .
2053 call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) .
2061 * Display a page stating that the Wiki is in read-only mode,
2062 * and optionally show the source of the page that the user
2063 * was trying to edit. Should only be called (for this
2064 * purpose) after wfReadOnly() has returned true.
2066 * For historical reasons, this function is _also_ used to
2067 * show the error message when a user tries to edit a page
2068 * they are not allowed to edit. (Unless it's because they're
2069 * blocked, then we show blockedPage() instead.) In this
2070 * case, the second parameter should be set to true and a list
2071 * of reasons supplied as the third parameter.
2073 * @todo Needs to be split into multiple functions.
2075 * @param $source String: source code to show (or null).
2076 * @param $protected Boolean: is this a permissions error?
2077 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
2078 * @param $action String: action that was denied or null if unknown
2080 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
2081 $this->setRobotPolicy( 'noindex,nofollow' );
2082 $this->setArticleRelated( false );
2084 // If no reason is given, just supply a default "I can't let you do
2085 // that, Dave" message. Should only occur if called by legacy code.
2086 if ( $protected && empty( $reasons ) ) {
2087 $reasons[] = array( 'badaccess-group0' );
2090 if ( !empty( $reasons ) ) {
2091 // Permissions error
2093 $this->setPageTitle( wfMsg( 'viewsource' ) );
2095 wfMsg( 'viewsourcefor', Linker
::linkKnown( $this->getTitle() ) )
2098 $this->setPageTitle( wfMsg( 'badaccess' ) );
2100 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2102 // Wiki is read only
2103 throw new ReadOnlyError
;
2106 // Show source, if supplied
2107 if( is_string( $source ) ) {
2108 $this->addWikiMsg( 'viewsourcetext' );
2110 $pageLang = $this->getTitle()->getPageLanguage();
2112 'id' => 'wpTextbox1',
2113 'name' => 'wpTextbox1',
2114 'cols' => $this->getUser()->getOption( 'cols' ),
2115 'rows' => $this->getUser()->getOption( 'rows' ),
2116 'readonly' => 'readonly',
2117 'lang' => $pageLang->getCode(),
2118 'dir' => $pageLang->getDir(),
2120 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
2122 // Show templates used by this article
2123 $article = new Article( $this->getTitle() );
2124 $templates = Linker
::formatTemplates( $article->getUsedTemplates() );
2125 $this->addHTML( "<div class='templatesUsed'>
2131 # If the title doesn't exist, it's fairly pointless to print a return
2132 # link to it. After all, you just tried editing it and couldn't, so
2133 # what's there to do there?
2134 if( $this->getTitle()->exists() ) {
2135 $this->returnToMain( null, $this->getTitle() );
2140 * Turn off regular page output and return an error reponse
2141 * for when rate limiting has triggered.
2143 public function rateLimited() {
2144 throw new ThrottledError
;
2148 * Show a warning about slave lag
2150 * If the lag is higher than $wgSlaveLagCritical seconds,
2151 * then the warning is a bit more obvious. If the lag is
2152 * lower than $wgSlaveLagWarning, then no warning is shown.
2154 * @param $lag Integer: slave lag
2156 public function showLagWarning( $lag ) {
2157 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2158 if( $lag >= $wgSlaveLagWarning ) {
2159 $message = $lag < $wgSlaveLagCritical
2162 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2163 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getContext()->getLang()->formatNum( $lag ) ) );
2167 public function showFatalError( $message ) {
2168 $this->setPageTitle( wfMsg( 'internalerror' ) );
2169 $this->setRobotPolicy( 'noindex,nofollow' );
2170 $this->setArticleRelated( false );
2171 $this->enableClientCache( false );
2172 $this->mRedirect
= '';
2173 $this->mBodytext
= $message;
2176 public function showUnexpectedValueError( $name, $val ) {
2177 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
2180 public function showFileCopyError( $old, $new ) {
2181 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
2184 public function showFileRenameError( $old, $new ) {
2185 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
2188 public function showFileDeleteError( $name ) {
2189 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
2192 public function showFileNotFoundError( $name ) {
2193 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
2197 * Add a "return to" link pointing to a specified title
2199 * @param $title Title to link
2200 * @param $query String query string
2201 * @param $text String text of the link (input is not escaped)
2203 public function addReturnTo( $title, $query = array(), $text = null ) {
2204 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL() ) );
2207 Linker
::link( $title, $text, array(), $query )
2209 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2213 * Add a "return to" link pointing to a specified title,
2214 * or the title indicated in the request, or else the main page
2216 * @param $unused No longer used
2217 * @param $returnto Title or String to return to
2218 * @param $returntoquery String: query string for the return to link
2220 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2221 if ( $returnto == null ) {
2222 $returnto = $this->getRequest()->getText( 'returnto' );
2225 if ( $returntoquery == null ) {
2226 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2229 if ( $returnto === '' ) {
2230 $returnto = Title
::newMainPage();
2233 if ( is_object( $returnto ) ) {
2234 $titleObj = $returnto;
2236 $titleObj = Title
::newFromText( $returnto );
2238 if ( !is_object( $titleObj ) ) {
2239 $titleObj = Title
::newMainPage();
2242 $this->addReturnTo( $titleObj, $returntoquery );
2246 * @param $sk Skin The given Skin
2247 * @param $includeStyle Boolean: unused
2248 * @return String: The doctype, opening <html>, and head element.
2250 public function headElement( Skin
$sk, $includeStyle = true ) {
2251 global $wgContLang, $wgUseTrackbacks;
2252 $userdir = $this->getLang()->getDir();
2253 $sitedir = $wgContLang->getDir();
2255 if ( $sk->commonPrintStylesheet() ) {
2256 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2259 $ret = Html
::htmlHeader( array( 'lang' => $this->getLang()->getCode(), 'dir' => $userdir, 'class' => 'client-nojs' ) );
2261 if ( $this->getHTMLTitle() == '' ) {
2262 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ) );
2265 $openHead = Html
::openElement( 'head' );
2267 # Don't bother with the newline if $head == ''
2268 $ret .= "$openHead\n";
2271 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2273 $ret .= implode( "\n", array(
2274 $this->getHeadLinks( null, true ),
2275 $this->buildCssLinks(),
2276 $this->getHeadScripts(),
2277 $this->getHeadItems()
2280 if ( $wgUseTrackbacks && $this->isArticleRelated() ) {
2281 $ret .= $this->getTitle()->trackbackRDF();
2284 $closeHead = Html
::closeElement( 'head' );
2286 $ret .= "$closeHead\n";
2289 $bodyAttrs = array();
2291 # Classes for LTR/RTL directionality support
2292 $bodyAttrs['class'] = "mediawiki $userdir sitedir-$sitedir";
2294 if ( $this->getContext()->getLang()->capitalizeAllNouns() ) {
2295 # A <body> class is probably not the best way to do this . . .
2296 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2298 $bodyAttrs['class'] .= ' ' . $sk->getPageClasses( $this->getTitle() );
2299 $bodyAttrs['class'] .= ' skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2301 $sk->addToBodyAttributes( $this, $bodyAttrs ); // Allow skins to add body attributes they need
2302 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2304 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2310 * Add the default ResourceLoader modules to this object
2312 private function addDefaultModules() {
2313 global $wgIncludeLegacyJavaScript, $wgUseAjax, $wgAjaxWatch, $wgEnableMWSuggest;
2315 // Add base resources
2316 $this->addModules( array(
2319 'mediawiki.page.startup',
2320 'mediawiki.page.ready',
2322 if ( $wgIncludeLegacyJavaScript ){
2323 $this->addModules( 'mediawiki.legacy.wikibits' );
2326 // Add various resources if required
2328 $this->addModules( 'mediawiki.legacy.ajax' );
2330 wfRunHooks( 'AjaxAddScript', array( &$this ) );
2332 if( $wgAjaxWatch && $this->getUser()->isLoggedIn() ) {
2333 $this->addModules( 'mediawiki.action.watch.ajax' );
2336 if ( $wgEnableMWSuggest && !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2337 $this->addModules( 'mediawiki.legacy.mwsuggest' );
2341 if ( $this->getUser()->getBoolOption( 'editsectiononrightclick' ) ) {
2342 $this->addModules( 'mediawiki.action.view.rightClickEdit' );
2345 # Crazy edit-on-double-click stuff
2346 if ( $this->isArticle() && $this->getUser()->getOption( 'editondblclick' ) ) {
2347 $this->addModules( 'mediawiki.action.view.dblClickEdit' );
2352 * Get a ResourceLoader object associated with this OutputPage
2354 * @return ResourceLoader
2356 public function getResourceLoader() {
2357 if ( is_null( $this->mResourceLoader
) ) {
2358 $this->mResourceLoader
= new ResourceLoader();
2360 return $this->mResourceLoader
;
2365 * @param $modules Array/string with the module name(s)
2366 * @param $only String ResourceLoaderModule TYPE_ class constant
2367 * @param $useESI boolean
2368 * @param $extraQuery Array with extra query parameters to add to each request. array( param => value )
2369 * @return string html <script> and <style> tags
2371 protected function makeResourceLoaderLink( $modules, $only, $useESI = false, array $extraQuery = array() ) {
2372 global $wgResourceLoaderUseESI, $wgResourceLoaderInlinePrivateModules;
2374 if ( !count( $modules ) ) {
2378 if ( count( $modules ) > 1 ) {
2379 // Remove duplicate module requests
2380 $modules = array_unique( (array) $modules );
2381 // Sort module names so requests are more uniform
2384 if ( ResourceLoader
::inDebugMode() ) {
2385 // Recursively call us for every item
2387 foreach ( $modules as $name ) {
2388 $links .= $this->makeResourceLoaderLink( $name, $only, $useESI );
2394 // Create keyed-by-group list of module objects from modules list
2396 $resourceLoader = $this->getResourceLoader();
2397 foreach ( (array) $modules as $name ) {
2398 $module = $resourceLoader->getModule( $name );
2399 # Check that we're allowed to include this module on this page
2400 if ( ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2401 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2402 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2403 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2409 $group = $module->getGroup();
2410 if ( !isset( $groups[$group] ) ) {
2411 $groups[$group] = array();
2413 $groups[$group][$name] = $module;
2417 foreach ( $groups as $group => $modules ) {
2418 // Special handling for user-specific groups
2420 if ( ( $group === 'user' ||
$group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2421 $user = $this->getUser()->getName();
2424 // Create a fake request based on the one we are about to make so modules return
2425 // correct timestamp and emptiness data
2426 $query = ResourceLoader
::makeLoaderQuery(
2427 array(), // modules; not determined yet
2428 $this->getContext()->getLang()->getCode(),
2429 $this->getSkin()->getSkinName(),
2431 null, // version; not determined yet
2432 ResourceLoader
::inDebugMode(),
2433 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2434 $this->isPrintable(),
2435 $this->getRequest()->getBool( 'handheld' ),
2438 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2439 // Drop modules that know they're empty
2440 foreach ( $modules as $key => $module ) {
2441 if ( $module->isKnownEmpty( $context ) ) {
2442 unset( $modules[$key] );
2445 // If there are no modules left, skip this group
2446 if ( $modules === array() ) {
2450 // Support inlining of private modules if configured as such
2451 if ( $group === 'private' && $wgResourceLoaderInlinePrivateModules ) {
2452 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2453 $links .= Html
::inlineStyle(
2454 $resourceLoader->makeModuleResponse( $context, $modules )
2457 $links .= Html
::inlineScript(
2458 ResourceLoader
::makeLoaderConditionalScript(
2459 $resourceLoader->makeModuleResponse( $context, $modules )
2466 // Special handling for the user group; because users might change their stuff
2467 // on-wiki like user pages, or user preferences; we need to find the highest
2468 // timestamp of these user-changable modules so we can ensure cache misses on change
2469 // This should NOT be done for the site group (bug 27564) because anons get that too
2470 // and we shouldn't be putting timestamps in Squid-cached HTML
2472 if ( $group === 'user' ) {
2473 // Get the maximum timestamp
2475 foreach ( $modules as $module ) {
2476 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2478 // Add a version parameter so cache will break when things change
2479 $version = wfTimestamp( TS_ISO_8601_BASIC
, $timestamp );
2482 $url = ResourceLoader
::makeLoaderURL(
2483 array_keys( $modules ),
2484 $this->getContext()->getLang()->getCode(),
2485 $this->getSkin()->getSkinName(),
2488 ResourceLoader
::inDebugMode(),
2489 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2490 $this->isPrintable(),
2491 $this->getRequest()->getBool( 'handheld' ),
2494 if ( $useESI && $wgResourceLoaderUseESI ) {
2495 $esi = Xml
::element( 'esi:include', array( 'src' => $url ) );
2496 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2497 $link = Html
::inlineStyle( $esi );
2499 $link = Html
::inlineScript( $esi );
2502 // Automatically select style/script elements
2503 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2504 $link = Html
::linkedStyle( $url );
2506 $link = Html
::linkedScript( $url );
2510 if( $group == 'noscript' ){
2511 $links .= Html
::rawElement( 'noscript', array(), $link ) . "\n";
2513 $links .= $link . "\n";
2520 * JS stuff to put in the <head>. This is the startup module, config
2521 * vars and modules marked with position 'top'
2523 * @return String: HTML fragment
2525 function getHeadScripts() {
2526 // Startup - this will immediately load jquery and mediawiki modules
2527 $scripts = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
, true );
2529 // Load config before anything else
2530 $scripts .= Html
::inlineScript(
2531 ResourceLoader
::makeLoaderConditionalScript(
2532 ResourceLoader
::makeConfigSetScript( $this->getJSVars() )
2536 // Script and Messages "only" requests marked for top inclusion
2537 // Messages should go first
2538 $scripts .= $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'top' ), ResourceLoaderModule
::TYPE_MESSAGES
);
2539 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'top' ), ResourceLoaderModule
::TYPE_SCRIPTS
);
2541 // Modules requests - let the client calculate dependencies and batch requests as it likes
2542 // Only load modules that have marked themselves for loading at the top
2543 $modules = $this->getModules( true, 'top' );
2545 $scripts .= Html
::inlineScript(
2546 ResourceLoader
::makeLoaderConditionalScript(
2547 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
2556 * JS stuff to put at the bottom of the <body>: modules marked with position 'bottom',
2557 * legacy scripts ($this->mScripts), user preferences, site JS and user JS
2561 function getBottomScripts() {
2562 global $wgUseSiteJs, $wgAllowUserJs;
2564 // Script and Messages "only" requests marked for bottom inclusion
2565 // Messages should go first
2566 $scripts = $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'bottom' ), ResourceLoaderModule
::TYPE_MESSAGES
);
2567 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ), ResourceLoaderModule
::TYPE_SCRIPTS
);
2569 // Modules requests - let the client calculate dependencies and batch requests as it likes
2570 // Only load modules that have marked themselves for loading at the bottom
2571 $modules = $this->getModules( true, 'bottom' );
2573 $scripts .= Html
::inlineScript(
2574 ResourceLoader
::makeLoaderConditionalScript(
2575 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
2581 $scripts .= "\n" . $this->mScripts
;
2583 $userScripts = array( 'user.options', 'user.tokens' );
2585 // Add site JS if enabled
2586 if ( $wgUseSiteJs ) {
2587 $scripts .= $this->makeResourceLoaderLink( 'site', ResourceLoaderModule
::TYPE_SCRIPTS
);
2588 if( $this->getUser()->isLoggedIn() ){
2589 $userScripts[] = 'user.groups';
2593 // Add user JS if enabled
2594 if ( $wgAllowUserJs && $this->getUser()->isLoggedIn() ) {
2595 if( $this->getTitle() && $this->getTitle()->isJsSubpage() && $this->userCanPreview() ) {
2596 # XXX: additional security check/prompt?
2597 // We're on a preview of a JS subpage
2598 // Exclude this page from the user module in case it's in there (bug 26283)
2599 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
, false,
2600 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
2602 // Load the previewed JS
2603 $scripts .= Html
::inlineScript( "\n" . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2605 // Include the user module normally
2606 // We can't do $userScripts[] = 'user'; because the user module would end up
2607 // being wrapped in a closure, so load it raw like 'site'
2608 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
);
2611 $scripts .= $this->makeResourceLoaderLink( $userScripts, ResourceLoaderModule
::TYPE_COMBINED
);
2617 * Add one or more variables to be set in mw.config in JavaScript.
2619 * @param $key {String|Array} Key or array of key/value pars.
2620 * @param $value {Mixed} Value of the configuration variable.
2622 public function addJsConfigVars( $keys, $value ) {
2623 if ( is_array( $keys ) ) {
2624 foreach ( $keys as $key => $value ) {
2625 $this->mJsConfigVars
[$key] = $value;
2630 $this->mJsConfigVars
[$keys] = $value;
2635 * Get an array containing the variables to be set in mw.config in JavaScript.
2637 * Do not add things here which can be evaluated in ResourceLoaderStartupScript
2638 * - in other words, page-independent/site-wide variables (without state).
2639 * You will only be adding bloat to the html page and causing page caches to
2640 * have to be purged on configuration changes.
2642 protected function getJSVars() {
2643 global $wgUseAjax, $wgEnableMWSuggest;
2645 $title = $this->getTitle();
2646 $ns = $title->getNamespace();
2647 $nsname = MWNamespace
::exists( $ns ) ? MWNamespace
::getCanonicalName( $ns ) : $title->getNsText();
2648 if ( $ns == NS_SPECIAL
) {
2649 list( $canonicalName, /*...*/ ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
2651 $canonicalName = false; # bug 21115
2655 'wgCanonicalNamespace' => $nsname,
2656 'wgCanonicalSpecialPageName' => $canonicalName,
2657 'wgNamespaceNumber' => $title->getNamespace(),
2658 'wgPageName' => $title->getPrefixedDBKey(),
2659 'wgTitle' => $title->getText(),
2660 'wgCurRevisionId' => $title->getLatestRevID(),
2661 'wgArticleId' => $title->getArticleId(),
2662 'wgIsArticle' => $this->isArticle(),
2663 'wgAction' => $this->getRequest()->getText( 'action', 'view' ),
2664 'wgUserName' => $this->getUser()->isAnon() ?
null : $this->getUser()->getName(),
2665 'wgUserGroups' => $this->getUser()->getEffectiveGroups(),
2666 'wgCategories' => $this->getCategories(),
2667 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
2669 $lang = $this->getTitle()->getPageLanguage();
2670 if ( $lang->hasVariants() ) {
2671 $vars['wgUserVariant'] = $lang->getPreferredVariant();
2673 foreach ( $title->getRestrictionTypes() as $type ) {
2674 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
2676 if ( $wgUseAjax && $wgEnableMWSuggest && !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2677 $vars['wgSearchNamespaces'] = SearchEngine
::userNamespaces( $this->getUser() );
2679 if ( $title->isMainPage() ) {
2680 $vars['wgIsMainPage'] = true;
2683 // Allow extensions to add their custom variables to the mw.config map.
2684 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
2685 // page-dependant but site-wide (without state).
2686 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
2687 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars, &$this ) );
2689 // Merge in variables from addJsConfigVars last
2690 return array_merge( $vars, $this->mJsConfigVars
);
2694 * To make it harder for someone to slip a user a fake
2695 * user-JavaScript or user-CSS preview, a random token
2696 * is associated with the login session. If it's not
2697 * passed back with the preview request, we won't render
2702 public function userCanPreview() {
2703 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
2704 ||
!$this->getRequest()->wasPosted()
2705 ||
!$this->getUser()->matchEditToken(
2706 $this->getRequest()->getVal( 'wpEditToken' ) )
2710 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
2714 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
2718 * @param $unused Unused
2719 * @param $addContentType bool
2721 * @return string HTML tag links to be put in the header.
2723 public function getHeadLinks( $unused = null, $addContentType = false ) {
2724 global $wgUniversalEditButton, $wgFavicon, $wgAppleTouchIcon, $wgEnableAPI,
2725 $wgSitename, $wgVersion, $wgHtml5, $wgMimeType,
2726 $wgFeed, $wgOverrideSiteFeed, $wgAdvertisedFeedTypes,
2727 $wgDisableLangConversion, $wgCanonicalLanguageLinks,
2728 $wgRightsPage, $wgRightsUrl;
2732 if ( $addContentType ) {
2734 # More succinct than <meta http-equiv=Content-Type>, has the
2736 $tags[] = Html
::element( 'meta', array( 'charset' => 'UTF-8' ) );
2738 $tags[] = Html
::element( 'meta', array(
2739 'http-equiv' => 'Content-Type',
2740 'content' => "$wgMimeType; charset=UTF-8"
2742 $tags[] = Html
::element( 'meta', array( // bug 15835
2743 'http-equiv' => 'Content-Style-Type',
2744 'content' => 'text/css'
2749 $tags[] = Html
::element( 'meta', array(
2750 'name' => 'generator',
2751 'content' => "MediaWiki $wgVersion",
2754 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
2755 if( $p !== 'index,follow' ) {
2756 // http://www.robotstxt.org/wc/meta-user.html
2757 // Only show if it's different from the default robots policy
2758 $tags[] = Html
::element( 'meta', array(
2764 if ( count( $this->mKeywords
) > 0 ) {
2766 "/<.*?" . ">/" => '',
2769 $tags[] = Html
::element( 'meta', array(
2770 'name' => 'keywords',
2771 'content' => preg_replace(
2772 array_keys( $strip ),
2773 array_values( $strip ),
2774 implode( ',', $this->mKeywords
)
2779 foreach ( $this->mMetatags
as $tag ) {
2780 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
2782 $tag[0] = substr( $tag[0], 5 );
2786 $tags[] = Html
::element( 'meta',
2789 'content' => $tag[1]
2794 foreach ( $this->mLinktags
as $tag ) {
2795 $tags[] = Html
::element( 'link', $tag );
2798 # Universal edit button
2799 if ( $wgUniversalEditButton ) {
2800 if ( $this->isArticleRelated() && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
2801 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create' ) ) ) {
2802 // Original UniversalEditButton
2803 $msg = wfMsg( 'edit' );
2804 $tags[] = Html
::element( 'link', array(
2805 'rel' => 'alternate',
2806 'type' => 'application/x-wiki',
2808 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
2810 // Alternate edit link
2811 $tags[] = Html
::element( 'link', array(
2814 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
2819 # Generally the order of the favicon and apple-touch-icon links
2820 # should not matter, but Konqueror (3.5.9 at least) incorrectly
2821 # uses whichever one appears later in the HTML source. Make sure
2822 # apple-touch-icon is specified first to avoid this.
2823 if ( $wgAppleTouchIcon !== false ) {
2824 $tags[] = Html
::element( 'link', array( 'rel' => 'apple-touch-icon', 'href' => $wgAppleTouchIcon ) );
2827 if ( $wgFavicon !== false ) {
2828 $tags[] = Html
::element( 'link', array( 'rel' => 'shortcut icon', 'href' => $wgFavicon ) );
2831 # OpenSearch description link
2832 $tags[] = Html
::element( 'link', array(
2834 'type' => 'application/opensearchdescription+xml',
2835 'href' => wfScript( 'opensearch_desc' ),
2836 'title' => wfMsgForContent( 'opensearch-desc' ),
2839 if ( $wgEnableAPI ) {
2840 # Real Simple Discovery link, provides auto-discovery information
2841 # for the MediaWiki API (and potentially additional custom API
2842 # support such as WordPress or Twitter-compatible APIs for a
2843 # blogging extension, etc)
2844 $tags[] = Html
::element( 'link', array(
2846 'type' => 'application/rsd+xml',
2847 // Output a protocol-relative URL here if $wgServer is protocol-relative
2848 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
2849 'href' => wfExpandUrl( wfAppendQuery( wfScript( 'api' ), array( 'action' => 'rsd' ) ), PROTO_RELATIVE
),
2853 $lang = $this->getTitle()->getPageLanguage();
2856 if ( !$wgDisableLangConversion && $wgCanonicalLanguageLinks
2857 && $lang->hasVariants() ) {
2859 $urlvar = $lang->getURLVariant();
2862 $variants = $lang->getVariants();
2863 foreach ( $variants as $_v ) {
2864 $tags[] = Html
::element( 'link', array(
2865 'rel' => 'alternate',
2867 'href' => $this->getTitle()->getLocalURL( '', $_v ) )
2871 $tags[] = Html
::element( 'link', array(
2872 'rel' => 'canonical',
2873 'href' => $this->getTitle()->getCanonicalUrl()
2880 if ( $wgRightsPage ) {
2881 $copy = Title
::newFromText( $wgRightsPage );
2884 $copyright = $copy->getLocalURL();
2888 if ( !$copyright && $wgRightsUrl ) {
2889 $copyright = $wgRightsUrl;
2893 $tags[] = Html
::element( 'link', array(
2894 'rel' => 'copyright',
2895 'href' => $copyright )
2901 foreach( $this->getSyndicationLinks() as $format => $link ) {
2902 # Use the page name for the title. In principle, this could
2903 # lead to issues with having the same name for different feeds
2904 # corresponding to the same page, but we can't avoid that at
2907 $tags[] = $this->feedLink(
2910 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
2911 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )
2915 # Recent changes feed should appear on every page (except recentchanges,
2916 # that would be redundant). Put it after the per-page feed to avoid
2917 # changing existing behavior. It's still available, probably via a
2918 # menu in your browser. Some sites might have a different feed they'd
2919 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
2920 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
2921 # If so, use it instead.
2923 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
2925 if ( $wgOverrideSiteFeed ) {
2926 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
2927 // Note, this->feedLink escapes the url.
2928 $tags[] = $this->feedLink(
2931 wfMsg( "site-{$type}-feed", $wgSitename )
2934 } elseif ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
2935 foreach ( $wgAdvertisedFeedTypes as $format ) {
2936 $tags[] = $this->feedLink(
2938 $rctitle->getLocalURL( "feed={$format}" ),
2939 wfMsg( "site-{$format}-feed", $wgSitename ) # For grep: 'site-rss-feed', 'site-atom-feed'.
2944 return implode( "\n", $tags );
2948 * Generate a <link rel/> for a feed.
2950 * @param $type String: feed type
2951 * @param $url String: URL to the feed
2952 * @param $text String: value of the "title" attribute
2953 * @return String: HTML fragment
2955 private function feedLink( $type, $url, $text ) {
2956 return Html
::element( 'link', array(
2957 'rel' => 'alternate',
2958 'type' => "application/$type+xml",
2965 * Add a local or specified stylesheet, with the given media options.
2966 * Meant primarily for internal use...
2968 * @param $style String: URL to the file
2969 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
2970 * @param $condition String: for IE conditional comments, specifying an IE version
2971 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
2973 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
2975 // Even though we expect the media type to be lowercase, but here we
2976 // force it to lowercase to be safe.
2978 $options['media'] = $media;
2981 $options['condition'] = $condition;
2984 $options['dir'] = $dir;
2986 $this->styles
[$style] = $options;
2990 * Adds inline CSS styles
2991 * @param $style_css Mixed: inline CSS
2992 * @param $flip String: Set to 'flip' to flip the CSS if needed
2994 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
2995 if( $flip === 'flip' && $this->getLang()->isRTL() ) {
2996 # If wanted, and the interface is right-to-left, flip the CSS
2997 $style_css = CSSJanus
::transform( $style_css, true, false );
2999 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3003 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
3004 * These will be applied to various media & IE conditionals.
3008 public function buildCssLinks() {
3009 global $wgUseSiteCss, $wgAllowUserCss, $wgAllowUserCssPrefs;
3011 $this->getSkin()->setupSkinUserCss( $this );
3013 // Add ResourceLoader styles
3014 // Split the styles into four groups
3015 $styles = array( 'other' => array(), 'user' => array(), 'site' => array(), 'private' => array(), 'noscript' => array() );
3016 $otherTags = ''; // Tags to append after the normal <link> tags
3017 $resourceLoader = $this->getResourceLoader();
3019 $moduleStyles = $this->getModuleStyles();
3021 // Per-site custom styles
3022 if ( $wgUseSiteCss ) {
3023 $moduleStyles[] = 'site';
3024 $moduleStyles[] = 'noscript';
3025 if( $this->getUser()->isLoggedIn() ){
3026 $moduleStyles[] = 'user.groups';
3030 // Per-user custom styles
3031 if ( $wgAllowUserCss ) {
3032 if ( $this->getTitle()->isCssSubpage() && $this->userCanPreview() ) {
3033 // We're on a preview of a CSS subpage
3034 // Exclude this page from the user module in case it's in there (bug 26283)
3035 $otherTags .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_STYLES
, false,
3036 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3038 // Load the previewed CSS
3039 $otherTags .= Html
::inlineStyle( $this->getRequest()->getText( 'wpTextbox1' ) );
3041 // Load the user styles normally
3042 $moduleStyles[] = 'user';
3046 // Per-user preference styles
3047 if ( $wgAllowUserCssPrefs ) {
3048 $moduleStyles[] = 'user.options';
3051 foreach ( $moduleStyles as $name ) {
3052 $group = $resourceLoader->getModule( $name )->getGroup();
3053 // Modules in groups named "other" or anything different than "user", "site" or "private"
3054 // will be placed in the "other" group
3055 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
3058 // We want site, private and user styles to override dynamically added styles from modules, but we want
3059 // dynamically added styles to override statically added styles from other modules. So the order
3060 // has to be other, dynamic, site, private, user
3061 // Add statically added styles for other modules
3062 $ret = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule
::TYPE_STYLES
);
3063 // Add normal styles added through addStyle()/addInlineStyle() here
3064 $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3065 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3066 // We use a <meta> tag with a made-up name for this because that's valid HTML
3067 $ret .= Html
::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) ) . "\n";
3069 // Add site, private and user styles
3070 // 'private' at present only contains user.options, so put that before 'user'
3071 // Any future private modules will likely have a similar user-specific character
3072 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3073 $ret .= $this->makeResourceLoaderLink( $styles[$group],
3074 ResourceLoaderModule
::TYPE_STYLES
3078 // Add stuff in $otherTags (previewed user CSS if applicable)
3086 public function buildCssLinksArray() {
3089 // Add any extension CSS
3090 foreach ( $this->mExtStyles
as $url ) {
3091 $this->addStyle( $url );
3093 $this->mExtStyles
= array();
3095 foreach( $this->styles
as $file => $options ) {
3096 $link = $this->styleLink( $file, $options );
3098 $links[$file] = $link;
3105 * Generate \<link\> tags for stylesheets
3107 * @param $style String: URL to the file
3108 * @param $options Array: option, can contain 'condition', 'dir', 'media'
3110 * @return String: HTML fragment
3112 protected function styleLink( $style, $options ) {
3113 if( isset( $options['dir'] ) ) {
3114 if( $this->getLang()->getDir() != $options['dir'] ) {
3119 if( isset( $options['media'] ) ) {
3120 $media = self
::transformCssMedia( $options['media'] );
3121 if( is_null( $media ) ) {
3128 if( substr( $style, 0, 1 ) == '/' ||
3129 substr( $style, 0, 5 ) == 'http:' ||
3130 substr( $style, 0, 6 ) == 'https:' ) {
3133 global $wgStylePath, $wgStyleVersion;
3134 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
3137 $link = Html
::linkedStyle( $url, $media );
3139 if( isset( $options['condition'] ) ) {
3140 $condition = htmlspecialchars( $options['condition'] );
3141 $link = "<!--[if $condition]>$link<![endif]-->";
3147 * Transform "media" attribute based on request parameters
3149 * @param $media String: current value of the "media" attribute
3150 * @return String: modified value of the "media" attribute
3152 public static function transformCssMedia( $media ) {
3153 global $wgRequest, $wgHandheldForIPhone;
3155 // Switch in on-screen display for media testing
3157 'printable' => 'print',
3158 'handheld' => 'handheld',
3160 foreach( $switches as $switch => $targetMedia ) {
3161 if( $wgRequest->getBool( $switch ) ) {
3162 if( $media == $targetMedia ) {
3164 } elseif( $media == 'screen' ) {
3170 // Expand longer media queries as iPhone doesn't grok 'handheld'
3171 if( $wgHandheldForIPhone ) {
3172 $mediaAliases = array(
3173 'screen' => 'screen and (min-device-width: 481px)',
3174 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
3177 if( isset( $mediaAliases[$media] ) ) {
3178 $media = $mediaAliases[$media];
3186 * Add a wikitext-formatted message to the output.
3187 * This is equivalent to:
3189 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
3191 public function addWikiMsg( /*...*/ ) {
3192 $args = func_get_args();
3193 $name = array_shift( $args );
3194 $this->addWikiMsgArray( $name, $args );
3198 * Add a wikitext-formatted message to the output.
3199 * Like addWikiMsg() except the parameters are taken as an array
3200 * instead of a variable argument list.
3202 * $options is passed through to wfMsgExt(), see that function for details.
3204 * @param $name string
3205 * @param $args array
3206 * @param $options array
3208 public function addWikiMsgArray( $name, $args, $options = array() ) {
3209 $options[] = 'parse';
3210 $text = wfMsgExt( $name, $options, $args );
3211 $this->addHTML( $text );
3215 * This function takes a number of message/argument specifications, wraps them in
3216 * some overall structure, and then parses the result and adds it to the output.
3218 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3219 * on. The subsequent arguments may either be strings, in which case they are the
3220 * message names, or arrays, in which case the first element is the message name,
3221 * and subsequent elements are the parameters to that message.
3223 * The special named parameter 'options' in a message specification array is passed
3224 * through to the $options parameter of wfMsgExt().
3226 * Don't use this for messages that are not in users interface language.
3230 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3234 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . "\n</div>" );
3236 * The newline after opening div is needed in some wikitext. See bug 19226.
3238 * @param $wrap string
3240 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3241 $msgSpecs = func_get_args();
3242 array_shift( $msgSpecs );
3243 $msgSpecs = array_values( $msgSpecs );
3245 foreach ( $msgSpecs as $n => $spec ) {
3247 if ( is_array( $spec ) ) {
3249 $name = array_shift( $args );
3250 if ( isset( $args['options'] ) ) {
3251 $options = $args['options'];
3252 unset( $args['options'] );
3258 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
3260 $this->addWikiText( $s );
3264 * Include jQuery core. Use this to avoid loading it multiple times
3265 * before we get a usable script loader.
3267 * @param $modules Array: list of jQuery modules which should be loaded
3268 * @return Array: the list of modules which were not loaded.
3270 * @deprecated since 1.17
3272 public function includeJQuery( $modules = array() ) {