Fix bug 26570 (user CSS preview broken) and bug 26555 (styles added with $out->addSty...
[mediawiki.git] / includes / OutputPage.php
blob4127210ce0cfe278fbd2f0fe280850b9c692e706
1 <?php
2 if ( !defined( 'MEDIAWIKI' ) ) {
3 die( 1 );
6 /**
7 * @todo document
8 */
9 class OutputPage {
10 var $mMetatags = array(), $mKeywords = array(), $mLinktags = array();
11 var $mExtStyles = array();
12 var $mPagetitle = '', $mBodytext = '';
14 /**
15 * Holds the debug lines that will be outputted as comments in page source if
16 * $wgDebugComments is enabled. See also $wgShowDebug.
17 * TODO: make a getter method for this
19 public $mDebugtext = '';
21 var $mHTMLtitle = '', $mIsarticle = true, $mPrintable = false;
22 var $mSubtitle = '', $mRedirect = '', $mStatusCode;
23 var $mLastModified = '', $mETag = false;
24 var $mCategoryLinks = array(), $mCategories = array(), $mLanguageLinks = array();
26 var $mScripts = '', $mInlineStyles = '', $mLinkColours, $mPageLinkTitle = '', $mHeadItems = array();
27 var $mModules = array(), $mModuleScripts = array(), $mModuleStyles = array(), $mModuleMessages = array();
28 var $mResourceLoader;
29 var $mInlineMsg = array();
31 var $mTemplateIds = array();
33 var $mAllowUserJs;
34 var $mSuppressQuickbar = false;
35 var $mDoNothing = false;
36 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
37 var $mIsArticleRelated = true;
38 protected $mParserOptions = null; // lazy initialised, use parserOptions()
40 var $mFeedLinks = array();
42 var $mEnableClientCache = true;
43 var $mArticleBodyOnly = false;
45 var $mNewSectionLink = false;
46 var $mHideNewSectionLink = false;
47 var $mNoGallery = false;
48 var $mPageTitleActionText = '';
49 var $mParseWarnings = array();
50 var $mSquidMaxage = 0;
51 var $mPreventClickjacking = true;
52 var $mRevisionId = null;
53 protected $mTitle = null;
55 /**
56 * An array of stylesheet filenames (relative from skins path), with options
57 * for CSS media, IE conditions, and RTL/LTR direction.
58 * For internal use; add settings in the skin via $this->addStyle()
60 var $styles = array();
62 /**
63 * Whether to load jQuery core.
65 protected $mJQueryDone = false;
67 private $mIndexPolicy = 'index';
68 private $mFollowPolicy = 'follow';
69 private $mVaryHeader = array(
70 'Accept-Encoding' => array( 'list-contains=gzip' ),
71 'Cookie' => null
74 /**
75 * Constructor
76 * Initialise private variables
78 function __construct() {
79 global $wgAllowUserJs;
80 $this->mAllowUserJs = $wgAllowUserJs;
83 /**
84 * Redirect to $url rather than displaying the normal page
86 * @param $url String: URL
87 * @param $responsecode String: HTTP status code
89 public function redirect( $url, $responsecode = '302' ) {
90 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
91 $this->mRedirect = str_replace( "\n", '', $url );
92 $this->mRedirectCode = $responsecode;
95 /**
96 * Get the URL to redirect to, or an empty string if not redirect URL set
98 * @return String
100 public function getRedirect() {
101 return $this->mRedirect;
105 * Set the HTTP status code to send with the output.
107 * @param $statusCode Integer
108 * @return nothing
110 public function setStatusCode( $statusCode ) {
111 $this->mStatusCode = $statusCode;
115 * Add a new <meta> tag
116 * To add an http-equiv meta tag, precede the name with "http:"
118 * @param $name tag name
119 * @param $val tag value
121 function addMeta( $name, $val ) {
122 array_push( $this->mMetatags, array( $name, $val ) );
126 * Add a keyword or a list of keywords in the page header
128 * @param $text String or array of strings
130 function addKeyword( $text ) {
131 if( is_array( $text ) ) {
132 $this->mKeywords = array_merge( $this->mKeywords, $text );
133 } else {
134 array_push( $this->mKeywords, $text );
139 * Add a new \<link\> tag to the page header
141 * @param $linkarr Array: associative array of attributes.
143 function addLink( $linkarr ) {
144 array_push( $this->mLinktags, $linkarr );
148 * Add a new \<link\> with "rel" attribute set to "meta"
150 * @param $linkarr Array: associative array mapping attribute names to their
151 * values, both keys and values will be escaped, and the
152 * "rel" attribute will be automatically added
154 function addMetadataLink( $linkarr ) {
155 # note: buggy CC software only reads first "meta" link
156 static $haveMeta = false;
157 $linkarr['rel'] = $haveMeta ? 'alternate meta' : 'meta';
158 $this->addLink( $linkarr );
159 $haveMeta = true;
163 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
165 * @param $script String: raw HTML
167 function addScript( $script ) {
168 $this->mScripts .= $script . "\n";
172 * Register and add a stylesheet from an extension directory.
174 * @param $url String path to sheet. Provide either a full url (beginning
175 * with 'http', etc) or a relative path from the document root
176 * (beginning with '/'). Otherwise it behaves identically to
177 * addStyle() and draws from the /skins folder.
179 public function addExtensionStyle( $url ) {
180 array_push( $this->mExtStyles, $url );
184 * Get all links added by extensions
186 * @return Array
188 function getExtStyle() {
189 return $this->mExtStyles;
193 * Add a JavaScript file out of skins/common, or a given relative path.
195 * @param $file String: filename in skins/common or complete on-server path
196 * (/foo/bar.js)
197 * @param $version String: style version of the file. Defaults to $wgStyleVersion
199 public function addScriptFile( $file, $version = null ) {
200 global $wgStylePath, $wgStyleVersion;
201 // See if $file parameter is an absolute URL or begins with a slash
202 if( substr( $file, 0, 1 ) == '/' || preg_match( '#^[a-z]*://#i', $file ) ) {
203 $path = $file;
204 } else {
205 $path = "{$wgStylePath}/common/{$file}";
207 if ( is_null( $version ) )
208 $version = $wgStyleVersion;
209 $this->addScript( Html::linkedScript( wfAppendQuery( $path, $version ) ) );
213 * Add a self-contained script tag with the given contents
215 * @param $script String: JavaScript text, no <script> tags
217 public function addInlineScript( $script ) {
218 $this->mScripts .= Html::inlineScript( "\n$script\n" ) . "\n";
222 * Get all registered JS and CSS tags for the header.
224 * @return String
226 function getScript() {
227 return $this->mScripts . $this->getHeadItems();
231 * Get the list of modules to include on this page
233 * @return Array of module names
235 public function getModules() {
236 return $this->mModules;
240 * Add one or more modules recognized by the resource loader. Modules added
241 * through this function will be loaded by the resource loader when the
242 * page loads.
244 * @param $modules Mixed: module name (string) or array of module names
246 public function addModules( $modules ) {
247 $this->mModules = array_merge( $this->mModules, (array)$modules );
251 * Get the list of module JS to include on this page
252 * @return array of module names
254 public function getModuleScripts() {
255 return $this->mModuleScripts;
259 * Add only JS of one or more modules recognized by the resource loader. Module
260 * scripts added through this function will be loaded by the resource loader when
261 * the page loads.
263 * @param $modules Mixed: module name (string) or array of module names
265 public function addModuleScripts( $modules ) {
266 $this->mModuleScripts = array_merge( $this->mModuleScripts, (array)$modules );
270 * Get the list of module CSS to include on this page
272 * @return Array of module names
274 public function getModuleStyles() {
275 return $this->mModuleStyles;
279 * Add only CSS of one or more modules recognized by the resource loader. Module
280 * styles added through this function will be loaded by the resource loader when
281 * the page loads.
283 * @param $modules Mixed: module name (string) or array of module names
285 public function addModuleStyles( $modules ) {
286 $this->mModuleStyles = array_merge( $this->mModuleStyles, (array)$modules );
290 * Get the list of module messages to include on this page
292 * @return Array of module names
294 public function getModuleMessages() {
295 return $this->mModuleMessages;
299 * Add only messages of one or more modules recognized by the resource loader.
300 * Module messages added through this function will be loaded by the resource
301 * loader when the page loads.
303 * @param $modules Mixed: module name (string) or array of module names
305 public function addModuleMessages( $modules ) {
306 $this->mModuleMessages = array_merge( $this->mModuleMessages, (array)$modules );
310 * Get all header items in a string
312 * @return String
314 function getHeadItems() {
315 $s = '';
316 foreach ( $this->mHeadItems as $item ) {
317 $s .= $item;
319 return $s;
323 * Add or replace an header item to the output
325 * @param $name String: item name
326 * @param $value String: raw HTML
328 public function addHeadItem( $name, $value ) {
329 $this->mHeadItems[$name] = $value;
333 * Check if the header item $name is already set
335 * @param $name String: item name
336 * @return Boolean
338 public function hasHeadItem( $name ) {
339 return isset( $this->mHeadItems[$name] );
343 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
345 * @param $tag String: value of "ETag" header
347 function setETag( $tag ) {
348 $this->mETag = $tag;
352 * Set whether the output should only contain the body of the article,
353 * without any skin, sidebar, etc.
354 * Used e.g. when calling with "action=render".
356 * @param $only Boolean: whether to output only the body of the article
358 public function setArticleBodyOnly( $only ) {
359 $this->mArticleBodyOnly = $only;
363 * Return whether the output will contain only the body of the article
365 * @return Boolean
367 public function getArticleBodyOnly() {
368 return $this->mArticleBodyOnly;
372 * checkLastModified tells the client to use the client-cached page if
373 * possible. If sucessful, the OutputPage is disabled so that
374 * any future call to OutputPage->output() have no effect.
376 * Side effect: sets mLastModified for Last-Modified header
378 * @return Boolean: true iff cache-ok headers was sent.
380 public function checkLastModified( $timestamp ) {
381 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
383 if ( !$timestamp || $timestamp == '19700101000000' ) {
384 wfDebug( __METHOD__ . ": CACHE DISABLED, NO TIMESTAMP\n" );
385 return false;
387 if( !$wgCachePages ) {
388 wfDebug( __METHOD__ . ": CACHE DISABLED\n", false );
389 return false;
391 if( $wgUser->getOption( 'nocache' ) ) {
392 wfDebug( __METHOD__ . ": USER DISABLED CACHE\n", false );
393 return false;
396 $timestamp = wfTimestamp( TS_MW, $timestamp );
397 $modifiedTimes = array(
398 'page' => $timestamp,
399 'user' => $wgUser->getTouched(),
400 'epoch' => $wgCacheEpoch
402 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
404 $maxModified = max( $modifiedTimes );
405 $this->mLastModified = wfTimestamp( TS_RFC2822, $maxModified );
407 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
408 wfDebug( __METHOD__ . ": client did not send If-Modified-Since header\n", false );
409 return false;
412 # Make debug info
413 $info = '';
414 foreach ( $modifiedTimes as $name => $value ) {
415 if ( $info !== '' ) {
416 $info .= ', ';
418 $info .= "$name=" . wfTimestamp( TS_ISO_8601, $value );
421 # IE sends sizes after the date like this:
422 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
423 # this breaks strtotime().
424 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
426 wfSuppressWarnings(); // E_STRICT system time bitching
427 $clientHeaderTime = strtotime( $clientHeader );
428 wfRestoreWarnings();
429 if ( !$clientHeaderTime ) {
430 wfDebug( __METHOD__ . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
431 return false;
433 $clientHeaderTime = wfTimestamp( TS_MW, $clientHeaderTime );
435 wfDebug( __METHOD__ . ": client sent If-Modified-Since: " .
436 wfTimestamp( TS_ISO_8601, $clientHeaderTime ) . "\n", false );
437 wfDebug( __METHOD__ . ": effective Last-Modified: " .
438 wfTimestamp( TS_ISO_8601, $maxModified ) . "\n", false );
439 if( $clientHeaderTime < $maxModified ) {
440 wfDebug( __METHOD__ . ": STALE, $info\n", false );
441 return false;
444 # Not modified
445 # Give a 304 response code and disable body output
446 wfDebug( __METHOD__ . ": NOT MODIFIED, $info\n", false );
447 ini_set( 'zlib.output_compression', 0 );
448 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
449 $this->sendCacheControl();
450 $this->disable();
452 // Don't output a compressed blob when using ob_gzhandler;
453 // it's technically against HTTP spec and seems to confuse
454 // Firefox when the response gets split over two packets.
455 wfClearOutputBuffers();
457 return true;
461 * Override the last modified timestamp
463 * @param $timestamp String: new timestamp, in a format readable by
464 * wfTimestamp()
466 public function setLastModified( $timestamp ) {
467 $this->mLastModified = wfTimestamp( TS_RFC2822, $timestamp );
471 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
473 * @param $policy String: the literal string to output as the contents of
474 * the meta tag. Will be parsed according to the spec and output in
475 * standardized form.
476 * @return null
478 public function setRobotPolicy( $policy ) {
479 $policy = Article::formatRobotPolicy( $policy );
481 if( isset( $policy['index'] ) ) {
482 $this->setIndexPolicy( $policy['index'] );
484 if( isset( $policy['follow'] ) ) {
485 $this->setFollowPolicy( $policy['follow'] );
490 * Set the index policy for the page, but leave the follow policy un-
491 * touched.
493 * @param $policy string Either 'index' or 'noindex'.
494 * @return null
496 public function setIndexPolicy( $policy ) {
497 $policy = trim( $policy );
498 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
499 $this->mIndexPolicy = $policy;
504 * Set the follow policy for the page, but leave the index policy un-
505 * touched.
507 * @param $policy String: either 'follow' or 'nofollow'.
508 * @return null
510 public function setFollowPolicy( $policy ) {
511 $policy = trim( $policy );
512 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
513 $this->mFollowPolicy = $policy;
518 * Set the new value of the "action text", this will be added to the
519 * "HTML title", separated from it with " - ".
521 * @param $text String: new value of the "action text"
523 public function setPageTitleActionText( $text ) {
524 $this->mPageTitleActionText = $text;
528 * Get the value of the "action text"
530 * @return String
532 public function getPageTitleActionText() {
533 if ( isset( $this->mPageTitleActionText ) ) {
534 return $this->mPageTitleActionText;
539 * "HTML title" means the contents of <title>.
540 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
542 public function setHTMLTitle( $name ) {
543 $this->mHTMLtitle = $name;
547 * Return the "HTML title", i.e. the content of the <title> tag.
549 * @return String
551 public function getHTMLTitle() {
552 return $this->mHTMLtitle;
556 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
557 * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
558 * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
559 * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
561 public function setPageTitle( $name ) {
562 # change "<script>foo&bar</script>" to "&lt;script&gt;foo&amp;bar&lt;/script&gt;"
563 # but leave "<i>foobar</i>" alone
564 $nameWithTags = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags( $name ) );
565 $this->mPagetitle = $nameWithTags;
567 # change "<i>foo&amp;bar</i>" to "foo&bar"
568 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer::stripAllTags( $nameWithTags ) ) );
572 * Return the "page title", i.e. the content of the \<h1\> tag.
574 * @return String
576 public function getPageTitle() {
577 return $this->mPagetitle;
581 * Set the Title object to use
583 * @param $t Title object
585 public function setTitle( $t ) {
586 $this->mTitle = $t;
590 * Get the Title object used in this instance
592 * @return Title
594 public function getTitle() {
595 if ( $this->mTitle instanceof Title ) {
596 return $this->mTitle;
597 } else {
598 wfDebug( __METHOD__ . " called and \$mTitle is null. Return \$wgTitle for sanity\n" );
599 global $wgTitle;
600 return $wgTitle;
605 * Replace the subtile with $str
607 * @param $str String: new value of the subtitle
609 public function setSubtitle( $str ) {
610 $this->mSubtitle = /*$this->parse(*/ $str /*)*/; // @bug 2514
614 * Add $str to the subtitle
616 * @param $str String to add to the subtitle
618 public function appendSubtitle( $str ) {
619 $this->mSubtitle .= /*$this->parse(*/ $str /*)*/; // @bug 2514
623 * Get the subtitle
625 * @return String
627 public function getSubtitle() {
628 return $this->mSubtitle;
632 * Set the page as printable, i.e. it'll be displayed with with all
633 * print styles included
635 public function setPrintable() {
636 $this->mPrintable = true;
640 * Return whether the page is "printable"
642 * @return Boolean
644 public function isPrintable() {
645 return $this->mPrintable;
649 * Disable output completely, i.e. calling output() will have no effect
651 public function disable() {
652 $this->mDoNothing = true;
656 * Return whether the output will be completely disabled
658 * @return Boolean
660 public function isDisabled() {
661 return $this->mDoNothing;
665 * Show an "add new section" link?
667 * @return Boolean
669 public function showNewSectionLink() {
670 return $this->mNewSectionLink;
674 * Forcibly hide the new section link?
676 * @return Boolean
678 public function forceHideNewSectionLink() {
679 return $this->mHideNewSectionLink;
683 * Add or remove feed links in the page header
684 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
685 * for the new version
686 * @see addFeedLink()
688 * @param $show Boolean: true: add default feeds, false: remove all feeds
690 public function setSyndicated( $show = true ) {
691 if ( $show ) {
692 $this->setFeedAppendQuery( false );
693 } else {
694 $this->mFeedLinks = array();
699 * Add default feeds to the page header
700 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
701 * for the new version
702 * @see addFeedLink()
704 * @param $val String: query to append to feed links or false to output
705 * default links
707 public function setFeedAppendQuery( $val ) {
708 global $wgAdvertisedFeedTypes;
710 $this->mFeedLinks = array();
712 foreach ( $wgAdvertisedFeedTypes as $type ) {
713 $query = "feed=$type";
714 if ( is_string( $val ) ) {
715 $query .= '&' . $val;
717 $this->mFeedLinks[$type] = $this->getTitle()->getLocalURL( $query );
722 * Add a feed link to the page header
724 * @param $format String: feed type, should be a key of $wgFeedClasses
725 * @param $href String: URL
727 public function addFeedLink( $format, $href ) {
728 global $wgAdvertisedFeedTypes;
730 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
731 $this->mFeedLinks[$format] = $href;
736 * Should we output feed links for this page?
737 * @return Boolean
739 public function isSyndicated() {
740 return count( $this->mFeedLinks ) > 0;
744 * Return URLs for each supported syndication format for this page.
745 * @return array associating format keys with URLs
747 public function getSyndicationLinks() {
748 return $this->mFeedLinks;
752 * Will currently always return null
754 * @return null
756 public function getFeedAppendQuery() {
757 return $this->mFeedLinksAppendQuery;
761 * Set whether the displayed content is related to the source of the
762 * corresponding article on the wiki
763 * Setting true will cause the change "article related" toggle to true
765 * @param $v Boolean
767 public function setArticleFlag( $v ) {
768 $this->mIsarticle = $v;
769 if ( $v ) {
770 $this->mIsArticleRelated = $v;
775 * Return whether the content displayed page is related to the source of
776 * the corresponding article on the wiki
778 * @return Boolean
780 public function isArticle() {
781 return $this->mIsarticle;
785 * Set whether this page is related an article on the wiki
786 * Setting false will cause the change of "article flag" toggle to false
788 * @param $v Boolean
790 public function setArticleRelated( $v ) {
791 $this->mIsArticleRelated = $v;
792 if ( !$v ) {
793 $this->mIsarticle = false;
798 * Return whether this page is related an article on the wiki
800 * @return Boolean
802 public function isArticleRelated() {
803 return $this->mIsArticleRelated;
807 * Add new language links
809 * @param $newLinkArray Associative array mapping language code to the page
810 * name
812 public function addLanguageLinks( $newLinkArray ) {
813 $this->mLanguageLinks += $newLinkArray;
817 * Reset the language links and add new language links
819 * @param $newLinkArray Associative array mapping language code to the page
820 * name
822 public function setLanguageLinks( $newLinkArray ) {
823 $this->mLanguageLinks = $newLinkArray;
827 * Get the list of language links
829 * @return Associative array mapping language code to the page name
831 public function getLanguageLinks() {
832 return $this->mLanguageLinks;
836 * Add an array of categories, with names in the keys
838 * @param $categories Associative array mapping category name to its sort key
840 public function addCategoryLinks( $categories ) {
841 global $wgUser, $wgContLang;
843 if ( !is_array( $categories ) || count( $categories ) == 0 ) {
844 return;
847 # Add the links to a LinkBatch
848 $arr = array( NS_CATEGORY => $categories );
849 $lb = new LinkBatch;
850 $lb->setArray( $arr );
852 # Fetch existence plus the hiddencat property
853 $dbr = wfGetDB( DB_SLAVE );
854 $pageTable = $dbr->tableName( 'page' );
855 $where = $lb->constructSet( 'page', $dbr );
856 $propsTable = $dbr->tableName( 'page_props' );
857 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, page_latest, pp_value
858 FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
859 $res = $dbr->query( $sql, __METHOD__ );
861 # Add the results to the link cache
862 $lb->addResultToCache( LinkCache::singleton(), $res );
864 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
865 $categories = array_combine(
866 array_keys( $categories ),
867 array_fill( 0, count( $categories ), 'normal' )
870 # Mark hidden categories
871 foreach ( $res as $row ) {
872 if ( isset( $row->pp_value ) ) {
873 $categories[$row->page_title] = 'hidden';
877 # Add the remaining categories to the skin
878 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks ) ) ) {
879 $sk = $wgUser->getSkin();
880 foreach ( $categories as $category => $type ) {
881 $origcategory = $category;
882 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
883 $wgContLang->findVariantLink( $category, $title, true );
884 if ( $category != $origcategory ) {
885 if ( array_key_exists( $category, $categories ) ) {
886 continue;
889 $text = $wgContLang->convertHtml( $title->getText() );
890 $this->mCategories[] = $title->getText();
891 $this->mCategoryLinks[$type][] = $sk->link( $title, $text );
897 * Reset the category links (but not the category list) and add $categories
899 * @param $categories Associative array mapping category name to its sort key
901 public function setCategoryLinks( $categories ) {
902 $this->mCategoryLinks = array();
903 $this->addCategoryLinks( $categories );
907 * Get the list of category links, in a 2-D array with the following format:
908 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
909 * hidden categories) and $link a HTML fragment with a link to the category
910 * page
912 * @return Array
914 public function getCategoryLinks() {
915 return $this->mCategoryLinks;
919 * Get the list of category names this page belongs to
921 * @return Array of strings
923 public function getCategories() {
924 return $this->mCategories;
928 * Suppress the quickbar from the output, only for skin supporting
929 * the quickbar
931 public function suppressQuickbar() {
932 $this->mSuppressQuickbar = true;
936 * Return whether the quickbar should be suppressed from the output
938 * @return Boolean
940 public function isQuickbarSuppressed() {
941 return $this->mSuppressQuickbar;
945 * Remove user JavaScript from scripts to load
947 public function disallowUserJs() {
948 $this->mAllowUserJs = false;
952 * Return whether user JavaScript is allowed for this page
954 * @return Boolean
956 public function isUserJsAllowed() {
957 return $this->mAllowUserJs;
961 * Prepend $text to the body HTML
963 * @param $text String: HTML
965 public function prependHTML( $text ) {
966 $this->mBodytext = $text . $this->mBodytext;
970 * Append $text to the body HTML
972 * @param $text String: HTML
974 public function addHTML( $text ) {
975 $this->mBodytext .= $text;
979 * Clear the body HTML
981 public function clearHTML() {
982 $this->mBodytext = '';
986 * Get the body HTML
988 * @return String: HTML
990 public function getHTML() {
991 return $this->mBodytext;
995 * Add $text to the debug output
997 * @param $text String: debug text
999 public function debug( $text ) {
1000 $this->mDebugtext .= $text;
1004 * @deprecated use parserOptions() instead
1006 public function setParserOptions( $options ) {
1007 wfDeprecated( __METHOD__ );
1008 return $this->parserOptions( $options );
1012 * Get/set the ParserOptions object to use for wikitext parsing
1014 * @param $options either the ParserOption to use or null to only get the
1015 * current ParserOption object
1016 * @return current ParserOption object
1018 public function parserOptions( $options = null ) {
1019 if ( !$this->mParserOptions ) {
1020 $this->mParserOptions = new ParserOptions;
1022 return wfSetVar( $this->mParserOptions, $options );
1026 * Set the revision ID which will be seen by the wiki text parser
1027 * for things such as embedded {{REVISIONID}} variable use.
1029 * @param $revid Mixed: an positive integer, or null
1030 * @return Mixed: previous value
1032 public function setRevisionId( $revid ) {
1033 $val = is_null( $revid ) ? null : intval( $revid );
1034 return wfSetVar( $this->mRevisionId, $val );
1038 * Get the current revision ID
1040 * @return Integer
1042 public function getRevisionId() {
1043 return $this->mRevisionId;
1047 * Convert wikitext to HTML and add it to the buffer
1048 * Default assumes that the current page title will be used.
1050 * @param $text String
1051 * @param $linestart Boolean: is this the start of a line?
1053 public function addWikiText( $text, $linestart = true ) {
1054 $title = $this->getTitle(); // Work arround E_STRICT
1055 $this->addWikiTextTitle( $text, $title, $linestart );
1059 * Add wikitext with a custom Title object
1061 * @param $text String: wikitext
1062 * @param $title Title object
1063 * @param $linestart Boolean: is this the start of a line?
1065 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1066 $this->addWikiTextTitle( $text, $title, $linestart );
1070 * Add wikitext with a custom Title object and
1072 * @param $text String: wikitext
1073 * @param $title Title object
1074 * @param $linestart Boolean: is this the start of a line?
1076 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1077 $this->addWikiTextTitle( $text, $title, $linestart, true );
1081 * Add wikitext with tidy enabled
1083 * @param $text String: wikitext
1084 * @param $linestart Boolean: is this the start of a line?
1086 public function addWikiTextTidy( $text, $linestart = true ) {
1087 $title = $this->getTitle();
1088 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1092 * Add wikitext with a custom Title object
1094 * @param $text String: wikitext
1095 * @param $title Title object
1096 * @param $linestart Boolean: is this the start of a line?
1097 * @param $tidy Boolean: whether to use tidy
1099 public function addWikiTextTitle( $text, &$title, $linestart, $tidy = false ) {
1100 global $wgParser;
1102 wfProfileIn( __METHOD__ );
1104 wfIncrStats( 'pcache_not_possible' );
1106 $popts = $this->parserOptions();
1107 $oldTidy = $popts->setTidy( $tidy );
1109 $parserOutput = $wgParser->parse(
1110 $text, $title, $popts,
1111 $linestart, true, $this->mRevisionId
1114 $popts->setTidy( $oldTidy );
1116 $this->addParserOutput( $parserOutput );
1118 wfProfileOut( __METHOD__ );
1122 * Add wikitext to the buffer, assuming that this is the primary text for a page view
1123 * Saves the text into the parser cache if possible.
1125 * @param $text String: wikitext
1126 * @param $article Article object
1127 * @param $cache Boolean
1128 * @deprecated Use Article::outputWikitext
1130 public function addPrimaryWikiText( $text, $article, $cache = true ) {
1131 global $wgParser;
1133 wfDeprecated( __METHOD__ );
1135 $popts = $this->parserOptions();
1136 $popts->setTidy( true );
1137 $parserOutput = $wgParser->parse(
1138 $text, $article->mTitle,
1139 $popts, true, true, $this->mRevisionId
1141 $popts->setTidy( false );
1142 if ( $cache && $article && $parserOutput->isCacheable() ) {
1143 $parserCache = ParserCache::singleton();
1144 $parserCache->save( $parserOutput, $article, $popts );
1147 $this->addParserOutput( $parserOutput );
1151 * @deprecated use addWikiTextTidy()
1153 public function addSecondaryWikiText( $text, $linestart = true ) {
1154 wfDeprecated( __METHOD__ );
1155 $this->addWikiTextTitleTidy( $text, $this->getTitle(), $linestart );
1159 * Add a ParserOutput object, but without Html
1161 * @param $parserOutput ParserOutput object
1163 public function addParserOutputNoText( &$parserOutput ) {
1164 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
1165 $this->addCategoryLinks( $parserOutput->getCategories() );
1166 $this->mNewSectionLink = $parserOutput->getNewSection();
1167 $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
1169 $this->mParseWarnings = $parserOutput->getWarnings();
1170 if ( !$parserOutput->isCacheable() ) {
1171 $this->enableClientCache( false );
1173 $this->mNoGallery = $parserOutput->getNoGallery();
1174 $this->mHeadItems = array_merge( $this->mHeadItems, $parserOutput->getHeadItems() );
1175 $this->addModules( $parserOutput->getModules() );
1176 // Versioning...
1177 foreach ( (array)$parserOutput->mTemplateIds as $ns => $dbks ) {
1178 if ( isset( $this->mTemplateIds[$ns] ) ) {
1179 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
1180 } else {
1181 $this->mTemplateIds[$ns] = $dbks;
1185 // Hooks registered in the object
1186 global $wgParserOutputHooks;
1187 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1188 list( $hookName, $data ) = $hookInfo;
1189 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1190 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1194 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1198 * Add a ParserOutput object
1200 * @param $parserOutput ParserOutput
1202 function addParserOutput( &$parserOutput ) {
1203 $this->addParserOutputNoText( $parserOutput );
1204 $text = $parserOutput->getText();
1205 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1206 $this->addHTML( $text );
1211 * Add the output of a QuickTemplate to the output buffer
1213 * @param $template QuickTemplate
1215 public function addTemplate( &$template ) {
1216 ob_start();
1217 $template->execute();
1218 $this->addHTML( ob_get_contents() );
1219 ob_end_clean();
1223 * Parse wikitext and return the HTML.
1225 * @param $text String
1226 * @param $linestart Boolean: is this the start of a line?
1227 * @param $interface Boolean: use interface language ($wgLang instead of
1228 * $wgContLang) while parsing language sensitive magic
1229 * words like GRAMMAR and PLURAL
1230 * @param $language Language object: target language object, will override
1231 * $interface
1232 * @return String: HTML
1234 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1235 global $wgParser;
1237 if( is_null( $this->getTitle() ) ) {
1238 throw new MWException( 'Empty $mTitle in ' . __METHOD__ );
1241 $popts = $this->parserOptions();
1242 if ( $interface ) {
1243 $popts->setInterfaceMessage( true );
1245 if ( $language !== null ) {
1246 $oldLang = $popts->setTargetLanguage( $language );
1249 $parserOutput = $wgParser->parse(
1250 $text, $this->getTitle(), $popts,
1251 $linestart, true, $this->mRevisionId
1254 if ( $interface ) {
1255 $popts->setInterfaceMessage( false );
1257 if ( $language !== null ) {
1258 $popts->setTargetLanguage( $oldLang );
1261 return $parserOutput->getText();
1265 * Parse wikitext, strip paragraphs, and return the HTML.
1267 * @param $text String
1268 * @param $linestart Boolean: is this the start of a line?
1269 * @param $interface Boolean: use interface language ($wgLang instead of
1270 * $wgContLang) while parsing language sensitive magic
1271 * words like GRAMMAR and PLURAL
1272 * @return String: HTML
1274 public function parseInline( $text, $linestart = true, $interface = false ) {
1275 $parsed = $this->parse( $text, $linestart, $interface );
1277 $m = array();
1278 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1279 $parsed = $m[1];
1282 return $parsed;
1286 * @deprecated
1288 * @param $article Article
1289 * @return Boolean: true if successful, else false.
1291 public function tryParserCache( &$article ) {
1292 wfDeprecated( __METHOD__ );
1293 $parserOutput = ParserCache::singleton()->get( $article, $article->getParserOptions() );
1295 if ( $parserOutput !== false ) {
1296 $this->addParserOutput( $parserOutput );
1297 return true;
1298 } else {
1299 return false;
1304 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1306 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1308 public function setSquidMaxage( $maxage ) {
1309 $this->mSquidMaxage = $maxage;
1313 * Use enableClientCache(false) to force it to send nocache headers
1315 * @param $state ??
1317 public function enableClientCache( $state ) {
1318 return wfSetVar( $this->mEnableClientCache, $state );
1322 * Get the list of cookies that will influence on the cache
1324 * @return Array
1326 function getCacheVaryCookies() {
1327 global $wgCookiePrefix, $wgCacheVaryCookies;
1328 static $cookies;
1329 if ( $cookies === null ) {
1330 $cookies = array_merge(
1331 array(
1332 "{$wgCookiePrefix}Token",
1333 "{$wgCookiePrefix}LoggedOut",
1334 session_name()
1336 $wgCacheVaryCookies
1338 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1340 return $cookies;
1344 * Return whether this page is not cacheable because "useskin" or "uselang"
1345 * URL parameters were passed.
1347 * @return Boolean
1349 function uncacheableBecauseRequestVars() {
1350 global $wgRequest;
1351 return $wgRequest->getText( 'useskin', false ) === false
1352 && $wgRequest->getText( 'uselang', false ) === false;
1356 * Check if the request has a cache-varying cookie header
1357 * If it does, it's very important that we don't allow public caching
1359 * @return Boolean
1361 function haveCacheVaryCookies() {
1362 global $wgRequest;
1363 $cookieHeader = $wgRequest->getHeader( 'cookie' );
1364 if ( $cookieHeader === false ) {
1365 return false;
1367 $cvCookies = $this->getCacheVaryCookies();
1368 foreach ( $cvCookies as $cookieName ) {
1369 # Check for a simple string match, like the way squid does it
1370 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1371 wfDebug( __METHOD__ . ": found $cookieName\n" );
1372 return true;
1375 wfDebug( __METHOD__ . ": no cache-varying cookies found\n" );
1376 return false;
1380 * Add an HTTP header that will influence on the cache
1382 * @param $header String: header name
1383 * @param $option either an Array or null
1385 public function addVaryHeader( $header, $option = null ) {
1386 if ( !array_key_exists( $header, $this->mVaryHeader ) ) {
1387 $this->mVaryHeader[$header] = $option;
1388 } elseif( is_array( $option ) ) {
1389 if( is_array( $this->mVaryHeader[$header] ) ) {
1390 $this->mVaryHeader[$header] = array_merge( $this->mVaryHeader[$header], $option );
1391 } else {
1392 $this->mVaryHeader[$header] = $option;
1395 $this->mVaryHeader[$header] = array_unique( $this->mVaryHeader[$header] );
1399 * Get a complete X-Vary-Options header
1401 * @return String
1403 public function getXVO() {
1404 $cvCookies = $this->getCacheVaryCookies();
1406 $cookiesOption = array();
1407 foreach ( $cvCookies as $cookieName ) {
1408 $cookiesOption[] = 'string-contains=' . $cookieName;
1410 $this->addVaryHeader( 'Cookie', $cookiesOption );
1412 $headers = array();
1413 foreach( $this->mVaryHeader as $header => $option ) {
1414 $newheader = $header;
1415 if( is_array( $option ) ) {
1416 $newheader .= ';' . implode( ';', $option );
1418 $headers[] = $newheader;
1420 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1422 return $xvo;
1426 * bug 21672: Add Accept-Language to Vary and XVO headers
1427 * if there's no 'variant' parameter existed in GET.
1429 * For example:
1430 * /w/index.php?title=Main_page should always be served; but
1431 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1433 function addAcceptLanguage() {
1434 global $wgRequest, $wgContLang;
1435 if( !$wgRequest->getCheck( 'variant' ) && $wgContLang->hasVariants() ) {
1436 $variants = $wgContLang->getVariants();
1437 $aloption = array();
1438 foreach ( $variants as $variant ) {
1439 if( $variant === $wgContLang->getCode() ) {
1440 continue;
1441 } else {
1442 $aloption[] = 'string-contains=' . $variant;
1444 // IE and some other browsers use another form of language code
1445 // in their Accept-Language header, like "zh-CN" or "zh-TW".
1446 // We should handle these too.
1447 $ievariant = explode( '-', $variant );
1448 if ( count( $ievariant ) == 2 ) {
1449 $ievariant[1] = strtoupper( $ievariant[1] );
1450 $ievariant = implode( '-', $ievariant );
1451 $aloption[] = 'string-contains=' . $ievariant;
1455 $this->addVaryHeader( 'Accept-Language', $aloption );
1460 * Set a flag which will cause an X-Frame-Options header appropriate for
1461 * edit pages to be sent. The header value is controlled by
1462 * $wgEditPageFrameOptions.
1464 * This is the default for special pages. If you display a CSRF-protected
1465 * form on an ordinary view page, then you need to call this function.
1467 public function preventClickjacking( $enable = true ) {
1468 $this->mPreventClickjacking = $enable;
1472 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1473 * This can be called from pages which do not contain any CSRF-protected
1474 * HTML form.
1476 public function allowClickjacking() {
1477 $this->mPreventClickjacking = false;
1481 * Get the X-Frame-Options header value (without the name part), or false
1482 * if there isn't one. This is used by Skin to determine whether to enable
1483 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1485 public function getFrameOptions() {
1486 global $wgBreakFrames, $wgEditPageFrameOptions;
1487 if ( $wgBreakFrames ) {
1488 return 'DENY';
1489 } elseif ( $this->mPreventClickjacking && $wgEditPageFrameOptions ) {
1490 return $wgEditPageFrameOptions;
1495 * Send cache control HTTP headers
1497 public function sendCacheControl() {
1498 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest, $wgUseXVO;
1500 $response = $wgRequest->response();
1501 if ( $wgUseETag && $this->mETag ) {
1502 $response->header( "ETag: $this->mETag" );
1505 $this->addAcceptLanguage();
1507 # don't serve compressed data to clients who can't handle it
1508 # maintain different caches for logged-in users and non-logged in ones
1509 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader ) ) );
1511 if ( $wgUseXVO ) {
1512 # Add an X-Vary-Options header for Squid with Wikimedia patches
1513 $response->header( $this->getXVO() );
1516 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache ) {
1518 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1519 $this->mSquidMaxage != 0 && !$this->haveCacheVaryCookies()
1522 if ( $wgUseESI ) {
1523 # We'll purge the proxy cache explicitly, but require end user agents
1524 # to revalidate against the proxy on each visit.
1525 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1526 wfDebug( __METHOD__ . ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1527 # start with a shorter timeout for initial testing
1528 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1529 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage.', content="ESI/1.0"');
1530 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1531 } else {
1532 # We'll purge the proxy cache for anons explicitly, but require end user agents
1533 # to revalidate against the proxy on each visit.
1534 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1535 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1536 wfDebug( __METHOD__ . ": local proxy caching; {$this->mLastModified} **\n", false );
1537 # start with a shorter timeout for initial testing
1538 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1539 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage.', must-revalidate, max-age=0' );
1541 } else {
1542 # We do want clients to cache if they can, but they *must* check for updates
1543 # on revisiting the page.
1544 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **\n", false );
1545 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1546 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1548 if($this->mLastModified) {
1549 $response->header( "Last-Modified: {$this->mLastModified}" );
1551 } else {
1552 wfDebug( __METHOD__ . ": no caching **\n", false );
1554 # In general, the absence of a last modified header should be enough to prevent
1555 # the client from using its cache. We send a few other things just to make sure.
1556 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1557 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1558 $response->header( 'Pragma: no-cache' );
1563 * Get the message associed with the HTTP response code $code
1565 * @param $code Integer: status code
1566 * @return String or null: message or null if $code is not in the list of
1567 * messages
1569 public static function getStatusMessage( $code ) {
1570 static $statusMessage = array(
1571 100 => 'Continue',
1572 101 => 'Switching Protocols',
1573 102 => 'Processing',
1574 200 => 'OK',
1575 201 => 'Created',
1576 202 => 'Accepted',
1577 203 => 'Non-Authoritative Information',
1578 204 => 'No Content',
1579 205 => 'Reset Content',
1580 206 => 'Partial Content',
1581 207 => 'Multi-Status',
1582 300 => 'Multiple Choices',
1583 301 => 'Moved Permanently',
1584 302 => 'Found',
1585 303 => 'See Other',
1586 304 => 'Not Modified',
1587 305 => 'Use Proxy',
1588 307 => 'Temporary Redirect',
1589 400 => 'Bad Request',
1590 401 => 'Unauthorized',
1591 402 => 'Payment Required',
1592 403 => 'Forbidden',
1593 404 => 'Not Found',
1594 405 => 'Method Not Allowed',
1595 406 => 'Not Acceptable',
1596 407 => 'Proxy Authentication Required',
1597 408 => 'Request Timeout',
1598 409 => 'Conflict',
1599 410 => 'Gone',
1600 411 => 'Length Required',
1601 412 => 'Precondition Failed',
1602 413 => 'Request Entity Too Large',
1603 414 => 'Request-URI Too Large',
1604 415 => 'Unsupported Media Type',
1605 416 => 'Request Range Not Satisfiable',
1606 417 => 'Expectation Failed',
1607 422 => 'Unprocessable Entity',
1608 423 => 'Locked',
1609 424 => 'Failed Dependency',
1610 500 => 'Internal Server Error',
1611 501 => 'Not Implemented',
1612 502 => 'Bad Gateway',
1613 503 => 'Service Unavailable',
1614 504 => 'Gateway Timeout',
1615 505 => 'HTTP Version Not Supported',
1616 507 => 'Insufficient Storage'
1618 return isset( $statusMessage[$code] ) ? $statusMessage[$code] : null;
1622 * Finally, all the text has been munged and accumulated into
1623 * the object, let's actually output it:
1625 public function output() {
1626 global $wgUser, $wgOutputEncoding, $wgRequest;
1627 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType;
1628 global $wgUseAjax, $wgAjaxWatch;
1629 global $wgEnableMWSuggest, $wgUniversalEditButton;
1631 if( $this->mDoNothing ) {
1632 return;
1634 wfProfileIn( __METHOD__ );
1635 if ( $this->mRedirect != '' ) {
1636 # Standards require redirect URLs to be absolute
1637 $this->mRedirect = wfExpandUrl( $this->mRedirect );
1638 if( $this->mRedirectCode == '301' || $this->mRedirectCode == '303' ) {
1639 if( !$wgDebugRedirects ) {
1640 $message = self::getStatusMessage( $this->mRedirectCode );
1641 $wgRequest->response()->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
1643 $this->mLastModified = wfTimestamp( TS_RFC2822 );
1645 $this->sendCacheControl();
1647 $wgRequest->response()->header( "Content-Type: text/html; charset=utf-8" );
1648 if( $wgDebugRedirects ) {
1649 $url = htmlspecialchars( $this->mRedirect );
1650 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1651 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1652 print "</body>\n</html>\n";
1653 } else {
1654 $wgRequest->response()->header( 'Location: ' . $this->mRedirect );
1656 wfProfileOut( __METHOD__ );
1657 return;
1658 } elseif ( $this->mStatusCode ) {
1659 $message = self::getStatusMessage( $this->mStatusCode );
1660 if ( $message ) {
1661 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode . ' ' . $message );
1665 $sk = $wgUser->getSkin();
1667 // Add base resources
1668 $this->addModules( array( 'mediawiki.legacy.wikibits', 'mediawiki.util' ) );
1670 // Add various resources if required
1671 if ( $wgUseAjax ) {
1672 $this->addModules( 'mediawiki.legacy.ajax' );
1674 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1676 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1677 $this->addModules( 'mediawiki.action.watch.ajax' );
1680 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ) {
1681 $this->addModules( 'mediawiki.legacy.mwsuggest' );
1685 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1686 $this->addModules( 'mediawiki.action.view.rightClickEdit' );
1689 if( $wgUniversalEditButton ) {
1690 if( $this->isArticleRelated() && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1691 && ( $this->getTitle()->exists() || $this->getTitle()->quickUserCan( 'create' ) ) ) {
1692 // Original UniversalEditButton
1693 $msg = wfMsg( 'edit' );
1694 $this->addLink( array(
1695 'rel' => 'alternate',
1696 'type' => 'application/x-wiki',
1697 'title' => $msg,
1698 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1699 ) );
1700 // Alternate edit link
1701 $this->addLink( array(
1702 'rel' => 'edit',
1703 'title' => $msg,
1704 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1705 ) );
1710 # Buffer output; final headers may depend on later processing
1711 ob_start();
1713 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1714 $wgRequest->response()->header( 'Content-language: ' . $wgLanguageCode );
1716 // Prevent framing, if requested
1717 $frameOptions = $this->getFrameOptions();
1718 if ( $frameOptions ) {
1719 $wgRequest->response()->header( "X-Frame-Options: $frameOptions" );
1722 if ( $this->mArticleBodyOnly ) {
1723 $this->out( $this->mBodytext );
1724 } else {
1725 // Hook that allows last minute changes to the output page, e.g.
1726 // adding of CSS or Javascript by extensions.
1727 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1729 wfProfileIn( 'Output-skin' );
1730 $sk->outputPage( $this );
1731 wfProfileOut( 'Output-skin' );
1734 $this->sendCacheControl();
1735 ob_end_flush();
1736 wfProfileOut( __METHOD__ );
1740 * Actually output something with print(). Performs an iconv to the
1741 * output encoding, if needed.
1743 * @param $ins String: the string to output
1745 public function out( $ins ) {
1746 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1747 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1748 $outs = $ins;
1749 } else {
1750 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1751 if ( false === $outs ) {
1752 $outs = $ins;
1755 print $outs;
1759 * @deprecated use wfReportTime() instead.
1761 * @return String
1763 public function reportTime() {
1764 wfDeprecated( __METHOD__ );
1765 $time = wfReportTime();
1766 return $time;
1770 * Produce a "user is blocked" page.
1772 * @param $return Boolean: whether to have a "return to $wgTitle" message or not.
1773 * @return nothing
1775 function blockedPage( $return = true ) {
1776 global $wgUser, $wgContLang, $wgLang;
1778 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1779 $this->setRobotPolicy( 'noindex,nofollow' );
1780 $this->setArticleRelated( false );
1782 $name = User::whoIs( $wgUser->blockedBy() );
1783 $reason = $wgUser->blockedFor();
1784 if( $reason == '' ) {
1785 $reason = wfMsg( 'blockednoreason' );
1787 $blockTimestamp = $wgLang->timeanddate(
1788 wfTimestamp( TS_MW, $wgUser->mBlock->mTimestamp ), true
1790 $ip = wfGetIP();
1792 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
1794 $blockid = $wgUser->mBlock->mId;
1796 $blockExpiry = $wgUser->mBlock->mExpiry;
1797 if ( $blockExpiry == 'infinity' ) {
1798 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1799 // Search for localization in 'ipboptions'
1800 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1801 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1802 if ( strpos( $option, ':' ) === false ) {
1803 continue;
1805 list( $show, $value ) = explode( ':', $option );
1806 if ( $value == 'infinite' || $value == 'indefinite' ) {
1807 $blockExpiry = $show;
1808 break;
1811 } else {
1812 $blockExpiry = $wgLang->timeanddate(
1813 wfTimestamp( TS_MW, $blockExpiry ),
1814 true
1818 if ( $wgUser->mBlock->mAuto ) {
1819 $msg = 'autoblockedtext';
1820 } else {
1821 $msg = 'blockedtext';
1824 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1825 * This could be a username, an IP range, or a single IP. */
1826 $intended = $wgUser->mBlock->mAddress;
1828 $this->addWikiMsg(
1829 $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry,
1830 $intended, $blockTimestamp
1833 # Don't auto-return to special pages
1834 if( $return ) {
1835 $return = $this->getTitle()->getNamespace() > -1 ? $this->getTitle() : null;
1836 $this->returnToMain( null, $return );
1841 * Output a standard error page
1843 * @param $title String: message key for page title
1844 * @param $msg String: message key for page text
1845 * @param $params Array: message parameters
1847 public function showErrorPage( $title, $msg, $params = array() ) {
1848 if ( $this->getTitle() ) {
1849 $this->mDebugtext .= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1851 $this->setPageTitle( wfMsg( $title ) );
1852 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1853 $this->setRobotPolicy( 'noindex,nofollow' );
1854 $this->setArticleRelated( false );
1855 $this->enableClientCache( false );
1856 $this->mRedirect = '';
1857 $this->mBodytext = '';
1859 $this->addWikiMsgArray( $msg, $params );
1861 $this->returnToMain();
1865 * Output a standard permission error page
1867 * @param $errors Array: error message keys
1868 * @param $action String: action that was denied or null if unknown
1870 public function showPermissionsErrorPage( $errors, $action = null ) {
1871 $this->mDebugtext .= 'Original title: ' .
1872 $this->getTitle()->getPrefixedText() . "\n";
1873 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1874 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1875 $this->setRobotPolicy( 'noindex,nofollow' );
1876 $this->setArticleRelated( false );
1877 $this->enableClientCache( false );
1878 $this->mRedirect = '';
1879 $this->mBodytext = '';
1880 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1884 * Display an error page indicating that a given version of MediaWiki is
1885 * required to use it
1887 * @param $version Mixed: the version of MediaWiki needed to use the page
1889 public function versionRequired( $version ) {
1890 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1891 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1892 $this->setRobotPolicy( 'noindex,nofollow' );
1893 $this->setArticleRelated( false );
1894 $this->mBodytext = '';
1896 $this->addWikiMsg( 'versionrequiredtext', $version );
1897 $this->returnToMain();
1901 * Display an error page noting that a given permission bit is required.
1903 * @param $permission String: key required
1905 public function permissionRequired( $permission ) {
1906 global $wgLang;
1908 $this->setPageTitle( wfMsg( 'badaccess' ) );
1909 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1910 $this->setRobotPolicy( 'noindex,nofollow' );
1911 $this->setArticleRelated( false );
1912 $this->mBodytext = '';
1914 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1915 User::getGroupsWithPermission( $permission ) );
1916 if( $groups ) {
1917 $this->addWikiMsg(
1918 'badaccess-groups',
1919 $wgLang->commaList( $groups ),
1920 count( $groups )
1922 } else {
1923 $this->addWikiMsg( 'badaccess-group0' );
1925 $this->returnToMain();
1929 * Produce the stock "please login to use the wiki" page
1931 public function loginToUse() {
1932 global $wgUser;
1934 if( $wgUser->isLoggedIn() ) {
1935 $this->permissionRequired( 'read' );
1936 return;
1939 $skin = $wgUser->getSkin();
1941 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1942 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1943 $this->setRobotPolicy( 'noindex,nofollow' );
1944 $this->setArticleRelated( false );
1946 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
1947 $loginLink = $skin->link(
1948 $loginTitle,
1949 wfMsgHtml( 'loginreqlink' ),
1950 array(),
1951 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
1952 array( 'known', 'noclasses' )
1954 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1955 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . '-->' );
1957 # Don't return to the main page if the user can't read it
1958 # otherwise we'll end up in a pointless loop
1959 $mainPage = Title::newMainPage();
1960 if( $mainPage->userCanRead() ) {
1961 $this->returnToMain( null, $mainPage );
1966 * Format a list of error messages
1968 * @param $errors An array of arrays returned by Title::getUserPermissionsErrors
1969 * @param $action String: action that was denied or null if unknown
1970 * @return String: the wikitext error-messages, formatted into a list.
1972 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1973 if ( $action == null ) {
1974 $text = wfMsgNoTrans( 'permissionserrorstext', count( $errors ) ) . "\n\n";
1975 } else {
1976 $action_desc = wfMsgNoTrans( "action-$action" );
1977 $text = wfMsgNoTrans(
1978 'permissionserrorstext-withaction',
1979 count( $errors ),
1980 $action_desc
1981 ) . "\n\n";
1984 if ( count( $errors ) > 1 ) {
1985 $text .= '<ul class="permissions-errors">' . "\n";
1987 foreach( $errors as $error ) {
1988 $text .= '<li>';
1989 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1990 $text .= "</li>\n";
1992 $text .= '</ul>';
1993 } else {
1994 $text .= "<div class=\"permissions-errors\">\n" .
1995 call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) .
1996 "\n</div>";
1999 return $text;
2003 * Display a page stating that the Wiki is in read-only mode,
2004 * and optionally show the source of the page that the user
2005 * was trying to edit. Should only be called (for this
2006 * purpose) after wfReadOnly() has returned true.
2008 * For historical reasons, this function is _also_ used to
2009 * show the error message when a user tries to edit a page
2010 * they are not allowed to edit. (Unless it's because they're
2011 * blocked, then we show blockedPage() instead.) In this
2012 * case, the second parameter should be set to true and a list
2013 * of reasons supplied as the third parameter.
2015 * @todo Needs to be split into multiple functions.
2017 * @param $source String: source code to show (or null).
2018 * @param $protected Boolean: is this a permissions error?
2019 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
2020 * @param $action String: action that was denied or null if unknown
2022 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
2023 global $wgUser;
2024 $skin = $wgUser->getSkin();
2026 $this->setRobotPolicy( 'noindex,nofollow' );
2027 $this->setArticleRelated( false );
2029 // If no reason is given, just supply a default "I can't let you do
2030 // that, Dave" message. Should only occur if called by legacy code.
2031 if ( $protected && empty( $reasons ) ) {
2032 $reasons[] = array( 'badaccess-group0' );
2035 if ( !empty( $reasons ) ) {
2036 // Permissions error
2037 if( $source ) {
2038 $this->setPageTitle( wfMsg( 'viewsource' ) );
2039 $this->setSubtitle(
2040 wfMsg( 'viewsourcefor', $skin->linkKnown( $this->getTitle() ) )
2042 } else {
2043 $this->setPageTitle( wfMsg( 'badaccess' ) );
2045 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2046 } else {
2047 // Wiki is read only
2048 $this->setPageTitle( wfMsg( 'readonly' ) );
2049 $reason = wfReadOnlyReason();
2050 $this->wrapWikiMsg( "<div class='mw-readonly-error'>\n$1\n</div>", array( 'readonlytext', $reason ) );
2053 // Show source, if supplied
2054 if( is_string( $source ) ) {
2055 $this->addWikiMsg( 'viewsourcetext' );
2057 $params = array(
2058 'id' => 'wpTextbox1',
2059 'name' => 'wpTextbox1',
2060 'cols' => $wgUser->getOption( 'cols' ),
2061 'rows' => $wgUser->getOption( 'rows' ),
2062 'readonly' => 'readonly'
2064 $this->addHTML( Html::element( 'textarea', $params, $source ) );
2066 // Show templates used by this article
2067 $skin = $wgUser->getSkin();
2068 $article = new Article( $this->getTitle() );
2069 $this->addHTML( "<div class='templatesUsed'>
2070 {$skin->formatTemplates( $article->getUsedTemplates() )}
2071 </div>
2072 " );
2075 # If the title doesn't exist, it's fairly pointless to print a return
2076 # link to it. After all, you just tried editing it and couldn't, so
2077 # what's there to do there?
2078 if( $this->getTitle()->exists() ) {
2079 $this->returnToMain( null, $this->getTitle() );
2084 * Adds JS-based password security checker
2085 * @param $passwordId String ID of input box containing password
2086 * @param $retypeId String ID of input box containing retyped password
2087 * @return none
2089 public function addPasswordSecurity( $passwordId, $retypeId ) {
2090 $data = array(
2091 'password' => '#' . $passwordId,
2092 'retype' => '#' . $retypeId,
2093 'messages' => array(),
2095 foreach ( array( 'password-strength', 'password-strength-bad', 'password-strength-mediocre',
2096 'password-strength-acceptable', 'password-strength-good', 'password-retype', 'password-retype-mismatch'
2097 ) as $message ) {
2098 $data['messages'][$message] = wfMsg( $message );
2100 $this->addScript( Html::inlineScript( 'var passwordSecurity=' . FormatJson::encode( $data ) ) );
2101 $this->addModules( 'mediawiki.legacy.password' );
2104 /** @deprecated */
2105 public function errorpage( $title, $msg ) {
2106 wfDeprecated( __METHOD__ );
2107 throw new ErrorPageError( $title, $msg );
2110 /** @deprecated */
2111 public function databaseError( $fname, $sql, $error, $errno ) {
2112 throw new MWException( "OutputPage::databaseError is obsolete\n" );
2115 /** @deprecated */
2116 public function fatalError( $message ) {
2117 wfDeprecated( __METHOD__ );
2118 throw new FatalError( $message );
2121 /** @deprecated */
2122 public function unexpectedValueError( $name, $val ) {
2123 wfDeprecated( __METHOD__ );
2124 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
2127 /** @deprecated */
2128 public function fileCopyError( $old, $new ) {
2129 wfDeprecated( __METHOD__ );
2130 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
2133 /** @deprecated */
2134 public function fileRenameError( $old, $new ) {
2135 wfDeprecated( __METHOD__ );
2136 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
2139 /** @deprecated */
2140 public function fileDeleteError( $name ) {
2141 wfDeprecated( __METHOD__ );
2142 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
2145 /** @deprecated */
2146 public function fileNotFoundError( $name ) {
2147 wfDeprecated( __METHOD__ );
2148 throw new FatalError( wfMsg( 'filenotfound', $name ) );
2151 public function showFatalError( $message ) {
2152 $this->setPageTitle( wfMsg( 'internalerror' ) );
2153 $this->setRobotPolicy( 'noindex,nofollow' );
2154 $this->setArticleRelated( false );
2155 $this->enableClientCache( false );
2156 $this->mRedirect = '';
2157 $this->mBodytext = $message;
2160 public function showUnexpectedValueError( $name, $val ) {
2161 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
2164 public function showFileCopyError( $old, $new ) {
2165 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
2168 public function showFileRenameError( $old, $new ) {
2169 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
2172 public function showFileDeleteError( $name ) {
2173 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
2176 public function showFileNotFoundError( $name ) {
2177 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
2181 * Add a "return to" link pointing to a specified title
2183 * @param $title Title to link
2184 * @param $query String: query string
2185 * @param $text String text of the link (input is not escaped)
2187 public function addReturnTo( $title, $query = array(), $text = null ) {
2188 global $wgUser;
2189 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL() ) );
2190 $link = wfMsgHtml(
2191 'returnto',
2192 $wgUser->getSkin()->link( $title, $text, array(), $query )
2194 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2198 * Add a "return to" link pointing to a specified title,
2199 * or the title indicated in the request, or else the main page
2201 * @param $unused No longer used
2202 * @param $returnto Title or String to return to
2203 * @param $returntoquery String: query string for the return to link
2205 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2206 global $wgRequest;
2208 if ( $returnto == null ) {
2209 $returnto = $wgRequest->getText( 'returnto' );
2212 if ( $returntoquery == null ) {
2213 $returntoquery = $wgRequest->getText( 'returntoquery' );
2216 if ( $returnto === '' ) {
2217 $returnto = Title::newMainPage();
2220 if ( is_object( $returnto ) ) {
2221 $titleObj = $returnto;
2222 } else {
2223 $titleObj = Title::newFromText( $returnto );
2225 if ( !is_object( $titleObj ) ) {
2226 $titleObj = Title::newMainPage();
2229 $this->addReturnTo( $titleObj, $returntoquery );
2233 * @param $sk Skin The given Skin
2234 * @param $includeStyle Boolean: unused
2235 * @return String: The doctype, opening <html>, and head element.
2237 public function headElement( Skin $sk, $includeStyle = true ) {
2238 global $wgOutputEncoding, $wgMimeType;
2239 global $wgUseTrackbacks, $wgHtml5;
2240 global $wgUser, $wgRequest, $wgLang;
2242 if ( $sk->commonPrintStylesheet() ) {
2243 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2245 $sk->setupUserCss( $this );
2247 $ret = Html::htmlHeader( array( 'lang' => wfUILang()->getCode() ) );
2249 if ( $this->getHTMLTitle() == '' ) {
2250 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ) );
2253 $openHead = Html::openElement( 'head' );
2254 if ( $openHead ) {
2255 # Don't bother with the newline if $head == ''
2256 $ret .= "$openHead\n";
2259 if ( $wgHtml5 ) {
2260 # More succinct than <meta http-equiv=Content-Type>, has the
2261 # same effect
2262 $ret .= Html::element( 'meta', array( 'charset' => $wgOutputEncoding ) ) . "\n";
2263 } else {
2264 $this->addMeta( 'http:Content-Type', "$wgMimeType; charset=$wgOutputEncoding" );
2267 $ret .= Html::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2269 $ret .= implode( "\n", array(
2270 $this->getHeadLinks( $sk ),
2271 $this->buildCssLinks( $sk ),
2272 $this->getHeadItems()
2273 ) );
2275 if ( $wgUseTrackbacks && $this->isArticleRelated() ) {
2276 $ret .= $this->getTitle()->trackbackRDF();
2279 $closeHead = Html::closeElement( 'head' );
2280 if ( $closeHead ) {
2281 $ret .= "$closeHead\n";
2284 $bodyAttrs = array();
2286 # Crazy edit-on-double-click stuff
2287 $action = $wgRequest->getVal( 'action', 'view' );
2289 if (
2290 $this->getTitle()->getNamespace() != NS_SPECIAL &&
2291 !in_array( $action, array( 'edit', 'submit' ) ) &&
2292 $wgUser->getOption( 'editondblclick' )
2295 $bodyAttrs['ondblclick'] = "document.location = '" . Xml::escapeJsString( $this->getTitle()->getEditURL() ) . "'";
2298 # Class bloat
2299 $dir = wfUILang()->getDir();
2300 $bodyAttrs['class'] = "mediawiki $dir";
2302 if ( $wgLang->capitalizeAllNouns() ) {
2303 # A <body> class is probably not the best way to do this . . .
2304 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2306 $bodyAttrs['class'] .= ' ns-' . $this->getTitle()->getNamespace();
2307 if ( $this->getTitle()->getNamespace() == NS_SPECIAL ) {
2308 $bodyAttrs['class'] .= ' ns-special';
2309 } elseif ( $this->getTitle()->isTalkPage() ) {
2310 $bodyAttrs['class'] .= ' ns-talk';
2311 } else {
2312 $bodyAttrs['class'] .= ' ns-subject';
2314 $bodyAttrs['class'] .= ' ' . Sanitizer::escapeClass( 'page-' . $this->getTitle()->getPrefixedText() );
2315 $bodyAttrs['class'] .= ' skin-' . Sanitizer::escapeClass( $wgUser->getSkin()->getSkinName() );
2317 $sk->addToBodyAttributes( $this, $bodyAttrs ); // Allow skins to add body attributes they need
2318 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2320 $ret .= Html::openElement( 'body', $bodyAttrs ) . "\n";
2322 return $ret;
2326 * Get a ResourceLoader object associated with this OutputPage
2328 public function getResourceLoader() {
2329 if ( is_null( $this->mResourceLoader ) ) {
2330 $this->mResourceLoader = new ResourceLoader();
2332 return $this->mResourceLoader;
2336 * TODO: Document
2337 * @param $skin Skin
2338 * @param $modules Array/string with the module name
2339 * @param $only string May be styles, messages or scripts
2340 * @param $useESI boolean
2341 * @return string html <script> and <style> tags
2343 protected function makeResourceLoaderLink( Skin $skin, $modules, $only, $useESI = false ) {
2344 global $wgUser, $wgLang, $wgLoadScript, $wgResourceLoaderUseESI,
2345 $wgResourceLoaderInlinePrivateModules;
2346 // Lazy-load ResourceLoader
2347 // TODO: Should this be a static function of ResourceLoader instead?
2348 // TODO: Divide off modules starting with "user", and add the user parameter to them
2349 $query = array(
2350 'lang' => $wgLang->getCode(),
2351 'debug' => ResourceLoader::inDebugMode() ? 'true' : 'false',
2352 'skin' => $skin->getSkinName(),
2353 'only' => $only,
2356 if ( !count( $modules ) ) {
2357 return '';
2360 if ( count( $modules ) > 1 ) {
2361 // Remove duplicate module requests
2362 $modules = array_unique( (array) $modules );
2363 // Sort module names so requests are more uniform
2364 sort( $modules );
2366 if ( ResourceLoader::inDebugMode() ) {
2367 // Recursively call us for every item
2368 $links = '';
2369 foreach ( $modules as $name ) {
2370 $links .= $this->makeResourceLoaderLink( $skin, $name, $only, $useESI );
2372 return $links;
2376 // Create keyed-by-group list of module objects from modules list
2377 $groups = array();
2378 $resourceLoader = $this->getResourceLoader();
2379 foreach ( (array) $modules as $name ) {
2380 $module = $resourceLoader->getModule( $name );
2381 $group = $module->getGroup();
2382 if ( !isset( $groups[$group] ) ) {
2383 $groups[$group] = array();
2385 $groups[$group][$name] = $module;
2387 $links = '';
2388 foreach ( $groups as $group => $modules ) {
2389 $query['modules'] = implode( '|', array_keys( $modules ) );
2390 // Special handling for user-specific groups
2391 if ( ( $group === 'user' || $group === 'private' ) && $wgUser->isLoggedIn() ) {
2392 $query['user'] = $wgUser->getName();
2394 // Support inlining of private modules if configured as such
2395 if ( $group === 'private' && $wgResourceLoaderInlinePrivateModules ) {
2396 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2397 if ( $only == 'styles' ) {
2398 $links .= Html::inlineStyle(
2399 $resourceLoader->makeModuleResponse( $context, $modules )
2401 } else {
2402 $links .= Html::inlineScript(
2403 ResourceLoader::makeLoaderConditionalScript(
2404 $resourceLoader->makeModuleResponse( $context, $modules )
2408 continue;
2410 // Special handling for user and site groups; because users might change their stuff
2411 // on-wiki like site or user pages, or user preferences; we need to find the highest
2412 // timestamp of these user-changable modules so we can ensure cache misses on change
2413 if ( $group === 'user' || $group === 'site' ) {
2414 // Create a fake request based on the one we are about to make so modules return
2415 // correct times
2416 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2417 // Get the maximum timestamp
2418 $timestamp = 1;
2419 foreach ( $modules as $module ) {
2420 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2422 // Add a version parameter so cache will break when things change
2423 $query['version'] = wfTimestamp( TS_ISO_8601_BASIC, round( $timestamp, -2 ) );
2425 // Make queries uniform in order
2426 ksort( $query );
2428 $url = wfAppendQuery( $wgLoadScript, $query );
2429 if ( $useESI && $wgResourceLoaderUseESI ) {
2430 $esi = Xml::element( 'esi:include', array( 'src' => $url ) );
2431 if ( $only == 'styles' ) {
2432 $links .= Html::inlineStyle( $esi );
2433 } else {
2434 $links .= Html::inlineScript( $esi );
2436 } else {
2437 // Automatically select style/script elements
2438 if ( $only === 'styles' ) {
2439 $links .= Html::linkedStyle( wfAppendQuery( $wgLoadScript, $query ) ) . "\n";
2440 } else {
2441 $links .= Html::linkedScript( wfAppendQuery( $wgLoadScript, $query ) ) . "\n";
2445 return $links;
2449 * Gets the global variables and mScripts; also adds userjs to the end if
2450 * enabled. Despite the name, these scripts are no longer put in the
2451 * <head> but at the bottom of the <body>
2453 * @param $sk Skin object to use
2454 * @return String: HTML fragment
2456 function getHeadScripts( Skin $sk ) {
2457 global $wgUser, $wgRequest, $wgUseSiteJs;
2459 // Startup - this will immediately load jquery and mediawiki modules
2460 $scripts = $this->makeResourceLoaderLink( $sk, 'startup', 'scripts', true );
2462 // Configuration -- This could be merged together with the load and go, but
2463 // makeGlobalVariablesScript returns a whole script tag -- grumble grumble...
2464 $scripts .= Skin::makeGlobalVariablesScript( $sk->getSkinName() ) . "\n";
2466 // Script and Messages "only" requests
2467 $scripts .= $this->makeResourceLoaderLink( $sk, $this->getModuleScripts(), 'scripts' );
2468 $scripts .= $this->makeResourceLoaderLink( $sk, $this->getModuleMessages(), 'messages' );
2470 // Modules requests - let the client calculate dependencies and batch requests as it likes
2471 if ( $this->getModules() ) {
2472 $scripts .= Html::inlineScript(
2473 ResourceLoader::makeLoaderConditionalScript(
2474 Xml::encodeJsCall( 'mediaWiki.loader.load', array( $this->getModules() ) ) .
2475 Xml::encodeJsCall( 'mediaWiki.loader.go', array() )
2477 ) . "\n";
2480 // Legacy Scripts
2481 $scripts .= "\n" . $this->mScripts;
2483 // Add site JS if enabled
2484 if ( $wgUseSiteJs ) {
2485 $scripts .= $this->makeResourceLoaderLink( $sk, 'site', 'scripts' );
2488 // Add user JS if enabled - trying to load user.options as a bundle if possible
2489 $userOptionsAdded = false;
2490 if ( $this->isUserJsAllowed() && $wgUser->isLoggedIn() ) {
2491 $action = $wgRequest->getVal( 'action', 'view' );
2492 if( $this->mTitle && $this->mTitle->isJsSubpage() && $sk->userCanPreview( $action ) ) {
2493 # XXX: additional security check/prompt?
2494 $scripts .= Html::inlineScript( "\n" . $wgRequest->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2495 } else {
2496 $scripts .= $this->makeResourceLoaderLink(
2497 $sk, array( 'user', 'user.options' ), 'scripts'
2499 $userOptionsAdded = true;
2502 if ( !$userOptionsAdded ) {
2503 $scripts .= $this->makeResourceLoaderLink( $sk, 'user.options', 'scripts' );
2506 return $scripts;
2510 * Add default \<meta\> tags
2512 protected function addDefaultMeta() {
2513 global $wgVersion, $wgHtml5;
2515 static $called = false;
2516 if ( $called ) {
2517 # Don't run this twice
2518 return;
2520 $called = true;
2522 if ( !$wgHtml5 ) {
2523 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); // bug 15835
2525 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
2527 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
2528 if( $p !== 'index,follow' ) {
2529 // http://www.robotstxt.org/wc/meta-user.html
2530 // Only show if it's different from the default robots policy
2531 $this->addMeta( 'robots', $p );
2534 if ( count( $this->mKeywords ) > 0 ) {
2535 $strip = array(
2536 "/<.*?" . ">/" => '',
2537 "/_/" => ' '
2539 $this->addMeta(
2540 'keywords',
2541 preg_replace(
2542 array_keys( $strip ),
2543 array_values( $strip ),
2544 implode( ',', $this->mKeywords )
2551 * @return string HTML tag links to be put in the header.
2553 public function getHeadLinks( Skin $sk ) {
2554 global $wgFeed;
2556 // Ideally this should happen earlier, somewhere. :P
2557 $this->addDefaultMeta();
2559 $tags = array();
2561 foreach ( $this->mMetatags as $tag ) {
2562 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
2563 $a = 'http-equiv';
2564 $tag[0] = substr( $tag[0], 5 );
2565 } else {
2566 $a = 'name';
2568 $tags[] = Html::element( 'meta',
2569 array(
2570 $a => $tag[0],
2571 'content' => $tag[1]
2575 foreach ( $this->mLinktags as $tag ) {
2576 $tags[] = Html::element( 'link', $tag );
2579 if( $wgFeed ) {
2580 foreach( $this->getSyndicationLinks() as $format => $link ) {
2581 # Use the page name for the title (accessed through $wgTitle since
2582 # there's no other way). In principle, this could lead to issues
2583 # with having the same name for different feeds corresponding to
2584 # the same page, but we can't avoid that at this low a level.
2586 $tags[] = $this->feedLink(
2587 $format,
2588 $link,
2589 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
2590 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )
2594 # Recent changes feed should appear on every page (except recentchanges,
2595 # that would be redundant). Put it after the per-page feed to avoid
2596 # changing existing behavior. It's still available, probably via a
2597 # menu in your browser. Some sites might have a different feed they'd
2598 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
2599 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
2600 # If so, use it instead.
2602 global $wgOverrideSiteFeed, $wgSitename, $wgAdvertisedFeedTypes;
2603 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
2605 if ( $wgOverrideSiteFeed ) {
2606 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
2607 $tags[] = $this->feedLink(
2608 $type,
2609 htmlspecialchars( $feedUrl ),
2610 wfMsg( "site-{$type}-feed", $wgSitename )
2613 } elseif ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
2614 foreach ( $wgAdvertisedFeedTypes as $format ) {
2615 $tags[] = $this->feedLink(
2616 $format,
2617 $rctitle->getLocalURL( "feed={$format}" ),
2618 wfMsg( "site-{$format}-feed", $wgSitename ) # For grep: 'site-rss-feed', 'site-atom-feed'.
2623 return implode( "\n", $tags );
2627 * Generate a <link rel/> for a feed.
2629 * @param $type String: feed type
2630 * @param $url String: URL to the feed
2631 * @param $text String: value of the "title" attribute
2632 * @return String: HTML fragment
2634 private function feedLink( $type, $url, $text ) {
2635 return Html::element( 'link', array(
2636 'rel' => 'alternate',
2637 'type' => "application/$type+xml",
2638 'title' => $text,
2639 'href' => $url )
2644 * Add a local or specified stylesheet, with the given media options.
2645 * Meant primarily for internal use...
2647 * @param $style String: URL to the file
2648 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
2649 * @param $condition String: for IE conditional comments, specifying an IE version
2650 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
2652 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
2653 $options = array();
2654 // Even though we expect the media type to be lowercase, but here we
2655 // force it to lowercase to be safe.
2656 if( $media ) {
2657 $options['media'] = $media;
2659 if( $condition ) {
2660 $options['condition'] = $condition;
2662 if( $dir ) {
2663 $options['dir'] = $dir;
2665 $this->styles[$style] = $options;
2669 * Adds inline CSS styles
2670 * @param $style_css Mixed: inline CSS
2672 public function addInlineStyle( $style_css ){
2673 $this->mInlineStyles .= Html::inlineStyle( $style_css );
2677 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
2678 * These will be applied to various media & IE conditionals.
2679 * @param $sk Skin object
2681 public function buildCssLinks( $sk ) {
2682 $ret = '';
2683 // Add ResourceLoader styles
2684 // Split the styles into three groups
2685 $styles = array( 'other' => array(), 'user' => array(), 'site' => array() );
2686 $resourceLoader = $this->getResourceLoader();
2687 foreach ( $this->getModuleStyles() as $name ) {
2688 $group = $resourceLoader->getModule( $name )->getGroup();
2689 // Modules in groups named "other" or anything different than "user" or "site" will
2690 // be placed in the "other" group
2691 $styles[isset( $styles[$group] ) ? $group : 'other'][] = $name;
2694 // We want site and user styles to override dynamically added styles from modules, but we want
2695 // dynamically added styles to override statically added styles from other modules. So the order
2696 // has to be other, dynamic, site, user
2697 // Add statically added styles for other modules
2698 $ret .= $this->makeResourceLoaderLink( $sk, $styles['other'], 'styles' );
2699 // Add normal styles added through addStyle()/addInlineStyle() here
2700 $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles;
2701 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
2702 // We use a <meta> tag with a made-up name for this because that's valid HTML
2703 $ret .= Html::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) );
2704 // Add site and user styles
2705 $ret .= $this->makeResourceLoaderLink(
2706 $sk, array_merge( $styles['site'], $styles['user'] ), 'styles'
2708 return $ret;
2711 public function buildCssLinksArray() {
2712 $links = array();
2713 foreach( $this->styles as $file => $options ) {
2714 $link = $this->styleLink( $file, $options );
2715 if( $link ) {
2716 $links[$file] = $link;
2719 return $links;
2723 * Generate \<link\> tags for stylesheets
2725 * @param $style String: URL to the file
2726 * @param $options Array: option, can contain 'condition', 'dir', 'media'
2727 * keys
2728 * @return String: HTML fragment
2730 protected function styleLink( $style, $options ) {
2731 if( isset( $options['dir'] ) ) {
2732 $siteDir = wfUILang()->getDir();
2733 if( $siteDir != $options['dir'] ) {
2734 return '';
2738 if( isset( $options['media'] ) ) {
2739 $media = $this->transformCssMedia( $options['media'] );
2740 if( is_null( $media ) ) {
2741 return '';
2743 } else {
2744 $media = 'all';
2747 if( substr( $style, 0, 1 ) == '/' ||
2748 substr( $style, 0, 5 ) == 'http:' ||
2749 substr( $style, 0, 6 ) == 'https:' ) {
2750 $url = $style;
2751 } else {
2752 global $wgStylePath, $wgStyleVersion;
2753 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
2756 $link = Html::linkedStyle( $url, $media );
2758 if( isset( $options['condition'] ) ) {
2759 $condition = htmlspecialchars( $options['condition'] );
2760 $link = "<!--[if $condition]>$link<![endif]-->";
2762 return $link;
2766 * Transform "media" attribute based on request parameters
2768 * @param $media String: current value of the "media" attribute
2769 * @return String: modified value of the "media" attribute
2771 function transformCssMedia( $media ) {
2772 global $wgRequest, $wgHandheldForIPhone;
2774 // Switch in on-screen display for media testing
2775 $switches = array(
2776 'printable' => 'print',
2777 'handheld' => 'handheld',
2779 foreach( $switches as $switch => $targetMedia ) {
2780 if( $wgRequest->getBool( $switch ) ) {
2781 if( $media == $targetMedia ) {
2782 $media = '';
2783 } elseif( $media == 'screen' ) {
2784 return null;
2789 // Expand longer media queries as iPhone doesn't grok 'handheld'
2790 if( $wgHandheldForIPhone ) {
2791 $mediaAliases = array(
2792 'screen' => 'screen and (min-device-width: 481px)',
2793 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
2796 if( isset( $mediaAliases[$media] ) ) {
2797 $media = $mediaAliases[$media];
2801 return $media;
2805 * Turn off regular page output and return an error reponse
2806 * for when rate limiting has triggered.
2808 public function rateLimited() {
2809 $this->setPageTitle( wfMsg( 'actionthrottled' ) );
2810 $this->setRobotPolicy( 'noindex,follow' );
2811 $this->setArticleRelated( false );
2812 $this->enableClientCache( false );
2813 $this->mRedirect = '';
2814 $this->clearHTML();
2815 $this->setStatusCode( 503 );
2816 $this->addWikiMsg( 'actionthrottledtext' );
2818 $this->returnToMain( null, $this->getTitle() );
2822 * Show a warning about slave lag
2824 * If the lag is higher than $wgSlaveLagCritical seconds,
2825 * then the warning is a bit more obvious. If the lag is
2826 * lower than $wgSlaveLagWarning, then no warning is shown.
2828 * @param $lag Integer: slave lag
2830 public function showLagWarning( $lag ) {
2831 global $wgSlaveLagWarning, $wgSlaveLagCritical, $wgLang;
2832 if( $lag >= $wgSlaveLagWarning ) {
2833 $message = $lag < $wgSlaveLagCritical
2834 ? 'lag-warn-normal'
2835 : 'lag-warn-high';
2836 $wrap = Html::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2837 $this->wrapWikiMsg( "$wrap\n", array( $message, $wgLang->formatNum( $lag ) ) );
2842 * Add a wikitext-formatted message to the output.
2843 * This is equivalent to:
2845 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2847 public function addWikiMsg( /*...*/ ) {
2848 $args = func_get_args();
2849 $name = array_shift( $args );
2850 $this->addWikiMsgArray( $name, $args );
2854 * Add a wikitext-formatted message to the output.
2855 * Like addWikiMsg() except the parameters are taken as an array
2856 * instead of a variable argument list.
2858 * $options is passed through to wfMsgExt(), see that function for details.
2860 public function addWikiMsgArray( $name, $args, $options = array() ) {
2861 $options[] = 'parse';
2862 $text = wfMsgExt( $name, $options, $args );
2863 $this->addHTML( $text );
2867 * This function takes a number of message/argument specifications, wraps them in
2868 * some overall structure, and then parses the result and adds it to the output.
2870 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
2871 * on. The subsequent arguments may either be strings, in which case they are the
2872 * message names, or arrays, in which case the first element is the message name,
2873 * and subsequent elements are the parameters to that message.
2875 * The special named parameter 'options' in a message specification array is passed
2876 * through to the $options parameter of wfMsgExt().
2878 * Don't use this for messages that are not in users interface language.
2880 * For example:
2882 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
2884 * Is equivalent to:
2886 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . "\n</div>" );
2888 * The newline after opening div is needed in some wikitext. See bug 19226.
2890 public function wrapWikiMsg( $wrap /*, ...*/ ) {
2891 $msgSpecs = func_get_args();
2892 array_shift( $msgSpecs );
2893 $msgSpecs = array_values( $msgSpecs );
2894 $s = $wrap;
2895 foreach ( $msgSpecs as $n => $spec ) {
2896 $options = array();
2897 if ( is_array( $spec ) ) {
2898 $args = $spec;
2899 $name = array_shift( $args );
2900 if ( isset( $args['options'] ) ) {
2901 $options = $args['options'];
2902 unset( $args['options'] );
2904 } else {
2905 $args = array();
2906 $name = $spec;
2908 $s = str_replace( '$' . ( $n + 1 ), wfMsgExt( $name, $options, $args ), $s );
2910 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );
2914 * Include jQuery core. Use this to avoid loading it multiple times
2915 * before we get a usable script loader.
2917 * @param $modules Array: list of jQuery modules which should be loaded
2918 * @return Array: the list of modules which were not loaded.
2919 * @since 1.16
2920 * @deprecated No longer needed as of 1.17
2922 public function includeJQuery( $modules = array() ) {
2923 return array();