Fixed user scripts/styles and site scripts/styles - they were totally broken in r7277...
[mediawiki.git] / includes / OutputPage.php
blobb86cb6ca7a762a25694feb87aad35b6edc1f044a
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 = '', $mLinkColours, $mPageLinkTitle = '', $mHeadItems = array();
27 var $mModules = array(), $mModuleScripts = array(), $mModuleStyles = array(), $mModuleMessages = array();
28 var $mInlineMsg = array();
30 var $mTemplateIds = array();
32 var $mAllowUserJs;
33 var $mSuppressQuickbar = false;
34 var $mDoNothing = false;
35 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
36 var $mIsArticleRelated = true;
37 protected $mParserOptions = null; // lazy initialised, use parserOptions()
39 var $mFeedLinks = array();
41 var $mEnableClientCache = true;
42 var $mArticleBodyOnly = false;
44 var $mNewSectionLink = false;
45 var $mHideNewSectionLink = false;
46 var $mNoGallery = false;
47 var $mPageTitleActionText = '';
48 var $mParseWarnings = array();
49 var $mSquidMaxage = 0;
50 var $mRevisionId = null;
51 protected $mTitle = null;
53 /**
54 * An array of stylesheet filenames (relative from skins path), with options
55 * for CSS media, IE conditions, and RTL/LTR direction.
56 * For internal use; add settings in the skin via $this->addStyle()
58 var $styles = array();
60 /**
61 * Whether to load jQuery core.
63 protected $mJQueryDone = false;
65 private $mIndexPolicy = 'index';
66 private $mFollowPolicy = 'follow';
67 private $mVaryHeader = array(
68 'Accept-Encoding' => array( 'list-contains=gzip' ),
69 'Cookie' => null
72 /**
73 * Constructor
74 * Initialise private variables
76 function __construct() {
77 global $wgAllowUserJs;
78 $this->mAllowUserJs = $wgAllowUserJs;
81 /**
82 * Redirect to $url rather than displaying the normal page
84 * @param $url String: URL
85 * @param $responsecode String: HTTP status code
87 public function redirect( $url, $responsecode = '302' ) {
88 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
89 $this->mRedirect = str_replace( "\n", '', $url );
90 $this->mRedirectCode = $responsecode;
93 /**
94 * Get the URL to redirect to, or an empty string if not redirect URL set
96 * @return String
98 public function getRedirect() {
99 return $this->mRedirect;
103 * Set the HTTP status code to send with the output.
105 * @param $statusCode Integer
106 * @return nothing
108 public function setStatusCode( $statusCode ) {
109 $this->mStatusCode = $statusCode;
113 * Add a new <meta> tag
114 * To add an http-equiv meta tag, precede the name with "http:"
116 * @param $name tag name
117 * @param $val tag value
119 function addMeta( $name, $val ) {
120 array_push( $this->mMetatags, array( $name, $val ) );
124 * Add a keyword or a list of keywords in the page header
126 * @param $text String or array of strings
128 function addKeyword( $text ) {
129 if( is_array( $text ) ) {
130 $this->mKeywords = array_merge( $this->mKeywords, $text );
131 } else {
132 array_push( $this->mKeywords, $text );
137 * Add a new \<link\> tag to the page header
139 * @param $linkarr Array: associative array of attributes.
141 function addLink( $linkarr ) {
142 array_push( $this->mLinktags, $linkarr );
146 * Add a new \<link\> with "rel" attribute set to "meta"
148 * @param $linkarr Array: associative array mapping attribute names to their
149 * values, both keys and values will be escaped, and the
150 * "rel" attribute will be automatically added
152 function addMetadataLink( $linkarr ) {
153 # note: buggy CC software only reads first "meta" link
154 static $haveMeta = false;
155 $linkarr['rel'] = $haveMeta ? 'alternate meta' : 'meta';
156 $this->addLink( $linkarr );
157 $haveMeta = true;
161 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
163 * @param $script String: raw HTML
165 function addScript( $script ) {
166 $this->mScripts .= $script . "\n";
170 * Register and add a stylesheet from an extension directory.
172 * @param $url String path to sheet. Provide either a full url (beginning
173 * with 'http', etc) or a relative path from the document root
174 * (beginning with '/'). Otherwise it behaves identically to
175 * addStyle() and draws from the /skins folder.
177 public function addExtensionStyle( $url ) {
178 array_push( $this->mExtStyles, $url );
182 * Get all links added by extensions
184 * @return Array
186 function getExtStyle() {
187 return $this->mExtStyles;
191 * Add a JavaScript file out of skins/common, or a given relative path.
193 * @param $file String: filename in skins/common or complete on-server path
194 * (/foo/bar.js)
195 * @param $version String: style version of the file. Defaults to $wgStyleVersion
197 public function addScriptFile( $file, $version = null ) {
198 global $wgStylePath, $wgStyleVersion;
199 // See if $file parameter is an absolute URL or begins with a slash
200 if( substr( $file, 0, 1 ) == '/' || preg_match( '#^[a-z]*://#i', $file ) ) {
201 $path = $file;
202 } else {
203 $path = "{$wgStylePath}/common/{$file}";
205 if ( is_null( $version ) )
206 $version = $wgStyleVersion;
207 $this->addScript( Html::linkedScript( wfAppendQuery( $path, $version ) ) );
211 * Add a self-contained script tag with the given contents
213 * @param $script String: JavaScript text, no <script> tags
215 public function addInlineScript( $script ) {
216 $this->mScripts .= Html::inlineScript( "\n$script\n" ) . "\n";
220 * Get all registered JS and CSS tags for the header.
222 * @return String
224 function getScript() {
225 return $this->mScripts . $this->getHeadItems();
229 * Get the list of modules to include on this page
231 * @return Array of module names
233 public function getModules() {
234 return $this->mModules;
238 * Add one or more modules recognized by the resource loader. Modules added
239 * through this function will be loaded by the resource loader when the
240 * page loads.
242 * @param $modules Mixed: module name (string) or array of module names
244 public function addModules( $modules ) {
245 $this->mModules = array_merge( $this->mModules, (array)$modules );
249 * Get the list of module JS to include on this page
250 * @return array of module names
252 public function getModuleScripts() {
253 return $this->mModuleScripts;
257 * Add only JS of one or more modules recognized by the resource loader. Module
258 * scripts added through this function will be loaded by the resource loader when
259 * the page loads.
261 * @param $modules Mixed: module name (string) or array of module names
263 public function addModuleScripts( $modules ) {
264 $this->mModuleScripts = array_merge( $this->mModuleScripts, (array)$modules );
268 * Get the list of module CSS to include on this page
270 * @return Array of module names
272 public function getModuleStyles() {
273 return $this->mModuleStyles;
277 * Add only CSS of one or more modules recognized by the resource loader. Module
278 * styles added through this function will be loaded by the resource loader when
279 * the page loads.
281 * @param $modules Mixed: module name (string) or array of module names
283 public function addModuleStyles( $modules ) {
284 $this->mModuleStyles = array_merge( $this->mModuleStyles, (array)$modules );
288 * Get the list of module messages to include on this page
290 * @return Array of module names
292 public function getModuleMessages() {
293 return $this->mModuleMessages;
297 * Add only messages of one or more modules recognized by the resource loader.
298 * Module messages added through this function will be loaded by the resource
299 * loader when the page loads.
301 * @param $modules Mixed: module name (string) or array of module names
303 public function addModuleMessages( $modules ) {
304 $this->mModuleMessages = array_merge( $this->mModuleMessages, (array)$modules );
308 * Get all header items in a string
310 * @return String
312 function getHeadItems() {
313 $s = '';
314 foreach ( $this->mHeadItems as $item ) {
315 $s .= $item;
317 return $s;
321 * Add or replace an header item to the output
323 * @param $name String: item name
324 * @param $value String: raw HTML
326 public function addHeadItem( $name, $value ) {
327 $this->mHeadItems[$name] = $value;
331 * Check if the header item $name is already set
333 * @param $name String: item name
334 * @return Boolean
336 public function hasHeadItem( $name ) {
337 return isset( $this->mHeadItems[$name] );
341 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
343 * @param $tag String: value of "ETag" header
345 function setETag( $tag ) {
346 $this->mETag = $tag;
350 * Set whether the output should only contain the body of the article,
351 * without any skin, sidebar, etc.
352 * Used e.g. when calling with "action=render".
354 * @param $only Boolean: whether to output only the body of the article
356 public function setArticleBodyOnly( $only ) {
357 $this->mArticleBodyOnly = $only;
361 * Return whether the output will contain only the body of the article
363 * @return Boolean
365 public function getArticleBodyOnly() {
366 return $this->mArticleBodyOnly;
370 * checkLastModified tells the client to use the client-cached page if
371 * possible. If sucessful, the OutputPage is disabled so that
372 * any future call to OutputPage->output() have no effect.
374 * Side effect: sets mLastModified for Last-Modified header
376 * @return Boolean: true iff cache-ok headers was sent.
378 public function checkLastModified( $timestamp ) {
379 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
381 if ( !$timestamp || $timestamp == '19700101000000' ) {
382 wfDebug( __METHOD__ . ": CACHE DISABLED, NO TIMESTAMP\n" );
383 return false;
385 if( !$wgCachePages ) {
386 wfDebug( __METHOD__ . ": CACHE DISABLED\n", false );
387 return false;
389 if( $wgUser->getOption( 'nocache' ) ) {
390 wfDebug( __METHOD__ . ": USER DISABLED CACHE\n", false );
391 return false;
394 $timestamp = wfTimestamp( TS_MW, $timestamp );
395 $modifiedTimes = array(
396 'page' => $timestamp,
397 'user' => $wgUser->getTouched(),
398 'epoch' => $wgCacheEpoch
400 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
402 $maxModified = max( $modifiedTimes );
403 $this->mLastModified = wfTimestamp( TS_RFC2822, $maxModified );
405 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
406 wfDebug( __METHOD__ . ": client did not send If-Modified-Since header\n", false );
407 return false;
410 # Make debug info
411 $info = '';
412 foreach ( $modifiedTimes as $name => $value ) {
413 if ( $info !== '' ) {
414 $info .= ', ';
416 $info .= "$name=" . wfTimestamp( TS_ISO_8601, $value );
419 # IE sends sizes after the date like this:
420 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
421 # this breaks strtotime().
422 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
424 wfSuppressWarnings(); // E_STRICT system time bitching
425 $clientHeaderTime = strtotime( $clientHeader );
426 wfRestoreWarnings();
427 if ( !$clientHeaderTime ) {
428 wfDebug( __METHOD__ . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
429 return false;
431 $clientHeaderTime = wfTimestamp( TS_MW, $clientHeaderTime );
433 wfDebug( __METHOD__ . ": client sent If-Modified-Since: " .
434 wfTimestamp( TS_ISO_8601, $clientHeaderTime ) . "\n", false );
435 wfDebug( __METHOD__ . ": effective Last-Modified: " .
436 wfTimestamp( TS_ISO_8601, $maxModified ) . "\n", false );
437 if( $clientHeaderTime < $maxModified ) {
438 wfDebug( __METHOD__ . ": STALE, $info\n", false );
439 return false;
442 # Not modified
443 # Give a 304 response code and disable body output
444 wfDebug( __METHOD__ . ": NOT MODIFIED, $info\n", false );
445 ini_set( 'zlib.output_compression', 0 );
446 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
447 $this->sendCacheControl();
448 $this->disable();
450 // Don't output a compressed blob when using ob_gzhandler;
451 // it's technically against HTTP spec and seems to confuse
452 // Firefox when the response gets split over two packets.
453 wfClearOutputBuffers();
455 return true;
459 * Override the last modified timestamp
461 * @param $timestamp String: new timestamp, in a format readable by
462 * wfTimestamp()
464 public function setLastModified( $timestamp ) {
465 $this->mLastModified = wfTimestamp( TS_RFC2822, $timestamp );
469 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
471 * @param $policy String: the literal string to output as the contents of
472 * the meta tag. Will be parsed according to the spec and output in
473 * standardized form.
474 * @return null
476 public function setRobotPolicy( $policy ) {
477 $policy = Article::formatRobotPolicy( $policy );
479 if( isset( $policy['index'] ) ) {
480 $this->setIndexPolicy( $policy['index'] );
482 if( isset( $policy['follow'] ) ) {
483 $this->setFollowPolicy( $policy['follow'] );
488 * Set the index policy for the page, but leave the follow policy un-
489 * touched.
491 * @param $policy string Either 'index' or 'noindex'.
492 * @return null
494 public function setIndexPolicy( $policy ) {
495 $policy = trim( $policy );
496 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
497 $this->mIndexPolicy = $policy;
502 * Set the follow policy for the page, but leave the index policy un-
503 * touched.
505 * @param $policy String: either 'follow' or 'nofollow'.
506 * @return null
508 public function setFollowPolicy( $policy ) {
509 $policy = trim( $policy );
510 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
511 $this->mFollowPolicy = $policy;
516 * Set the new value of the "action text", this will be added to the
517 * "HTML title", separated from it with " - ".
519 * @param $text String: new value of the "action text"
521 public function setPageTitleActionText( $text ) {
522 $this->mPageTitleActionText = $text;
526 * Get the value of the "action text"
528 * @return String
530 public function getPageTitleActionText() {
531 if ( isset( $this->mPageTitleActionText ) ) {
532 return $this->mPageTitleActionText;
537 * "HTML title" means the contents of <title>.
538 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
540 public function setHTMLTitle( $name ) {
541 $this->mHTMLtitle = $name;
545 * Return the "HTML title", i.e. the content of the <title> tag.
547 * @return String
549 public function getHTMLTitle() {
550 return $this->mHTMLtitle;
554 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
555 * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
556 * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
557 * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
559 public function setPageTitle( $name ) {
560 # change "<script>foo&bar</script>" to "&lt;script&gt;foo&amp;bar&lt;/script&gt;"
561 # but leave "<i>foobar</i>" alone
562 $nameWithTags = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags( $name ) );
563 $this->mPagetitle = $nameWithTags;
565 $taction = $this->getPageTitleActionText();
566 if( !empty( $taction ) ) {
567 $name .= ' - '.$taction;
570 # change "<i>foo&amp;bar</i>" to "foo&bar"
571 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer::stripAllTags( $nameWithTags ) ) );
575 * Return the "page title", i.e. the content of the \<h1\> tag.
577 * @return String
579 public function getPageTitle() {
580 return $this->mPagetitle;
584 * Set the Title object to use
586 * @param $t Title object
588 public function setTitle( $t ) {
589 $this->mTitle = $t;
593 * Get the Title object used in this instance
595 * @return Title
597 public function getTitle() {
598 if ( $this->mTitle instanceof Title ) {
599 return $this->mTitle;
600 } else {
601 wfDebug( __METHOD__ . " called and \$mTitle is null. Return \$wgTitle for sanity\n" );
602 global $wgTitle;
603 return $wgTitle;
608 * Replace the subtile with $str
610 * @param $str String: new value of the subtitle
612 public function setSubtitle( $str ) {
613 $this->mSubtitle = /*$this->parse(*/ $str /*)*/; // @bug 2514
617 * Add $str to the subtitle
619 * @param $str String to add to the subtitle
621 public function appendSubtitle( $str ) {
622 $this->mSubtitle .= /*$this->parse(*/ $str /*)*/; // @bug 2514
626 * Get the subtitle
628 * @return String
630 public function getSubtitle() {
631 return $this->mSubtitle;
635 * Set the page as printable, i.e. it'll be displayed with with all
636 * print styles included
638 public function setPrintable() {
639 $this->mPrintable = true;
643 * Return whether the page is "printable"
645 * @return Boolean
647 public function isPrintable() {
648 return $this->mPrintable;
652 * Disable output completely, i.e. calling output() will have no effect
654 public function disable() {
655 $this->mDoNothing = true;
659 * Return whether the output will be completely disabled
661 * @return Boolean
663 public function isDisabled() {
664 return $this->mDoNothing;
668 * Show an "add new section" link?
670 * @return Boolean
672 public function showNewSectionLink() {
673 return $this->mNewSectionLink;
677 * Forcibly hide the new section link?
679 * @return Boolean
681 public function forceHideNewSectionLink() {
682 return $this->mHideNewSectionLink;
686 * Add or remove feed links in the page header
687 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
688 * for the new version
689 * @see addFeedLink()
691 * @param $show Boolean: true: add default feeds, false: remove all feeds
693 public function setSyndicated( $show = true ) {
694 if ( $show ) {
695 $this->setFeedAppendQuery( false );
696 } else {
697 $this->mFeedLinks = array();
702 * Add default feeds to the page header
703 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
704 * for the new version
705 * @see addFeedLink()
707 * @param $val String: query to append to feed links or false to output
708 * default links
710 public function setFeedAppendQuery( $val ) {
711 global $wgAdvertisedFeedTypes;
713 $this->mFeedLinks = array();
715 foreach ( $wgAdvertisedFeedTypes as $type ) {
716 $query = "feed=$type";
717 if ( is_string( $val ) ) {
718 $query .= '&' . $val;
720 $this->mFeedLinks[$type] = $this->getTitle()->getLocalURL( $query );
725 * Add a feed link to the page header
727 * @param $format String: feed type, should be a key of $wgFeedClasses
728 * @param $href String: URL
730 public function addFeedLink( $format, $href ) {
731 global $wgAdvertisedFeedTypes;
733 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
734 $this->mFeedLinks[$format] = $href;
739 * Should we output feed links for this page?
740 * @return Boolean
742 public function isSyndicated() {
743 return count( $this->mFeedLinks ) > 0;
747 * Return URLs for each supported syndication format for this page.
748 * @return array associating format keys with URLs
750 public function getSyndicationLinks() {
751 return $this->mFeedLinks;
755 * Will currently always return null
757 * @return null
759 public function getFeedAppendQuery() {
760 return $this->mFeedLinksAppendQuery;
764 * Set whether the displayed content is related to the source of the
765 * corresponding article on the wiki
766 * Setting true will cause the change "article related" toggle to true
768 * @param $v Boolean
770 public function setArticleFlag( $v ) {
771 $this->mIsarticle = $v;
772 if ( $v ) {
773 $this->mIsArticleRelated = $v;
778 * Return whether the content displayed page is related to the source of
779 * the corresponding article on the wiki
781 * @return Boolean
783 public function isArticle() {
784 return $this->mIsarticle;
788 * Set whether this page is related an article on the wiki
789 * Setting false will cause the change of "article flag" toggle to false
791 * @param $v Boolean
793 public function setArticleRelated( $v ) {
794 $this->mIsArticleRelated = $v;
795 if ( !$v ) {
796 $this->mIsarticle = false;
801 * Return whether this page is related an article on the wiki
803 * @return Boolean
805 public function isArticleRelated() {
806 return $this->mIsArticleRelated;
810 * Add new language links
812 * @param $newLinkArray Associative array mapping language code to the page
813 * name
815 public function addLanguageLinks( $newLinkArray ) {
816 $this->mLanguageLinks += $newLinkArray;
820 * Reset the language links and add new language links
822 * @param $newLinkArray Associative array mapping language code to the page
823 * name
825 public function setLanguageLinks( $newLinkArray ) {
826 $this->mLanguageLinks = $newLinkArray;
830 * Get the list of language links
832 * @return Associative array mapping language code to the page name
834 public function getLanguageLinks() {
835 return $this->mLanguageLinks;
839 * Add an array of categories, with names in the keys
841 * @param $categories Associative array mapping category name to its sort key
843 public function addCategoryLinks( $categories ) {
844 global $wgUser, $wgContLang;
846 if ( !is_array( $categories ) || count( $categories ) == 0 ) {
847 return;
850 # Add the links to a LinkBatch
851 $arr = array( NS_CATEGORY => $categories );
852 $lb = new LinkBatch;
853 $lb->setArray( $arr );
855 # Fetch existence plus the hiddencat property
856 $dbr = wfGetDB( DB_SLAVE );
857 $pageTable = $dbr->tableName( 'page' );
858 $where = $lb->constructSet( 'page', $dbr );
859 $propsTable = $dbr->tableName( 'page_props' );
860 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, page_latest, pp_value
861 FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
862 $res = $dbr->query( $sql, __METHOD__ );
864 # Add the results to the link cache
865 $lb->addResultToCache( LinkCache::singleton(), $res );
867 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
868 $categories = array_combine(
869 array_keys( $categories ),
870 array_fill( 0, count( $categories ), 'normal' )
873 # Mark hidden categories
874 foreach ( $res as $row ) {
875 if ( isset( $row->pp_value ) ) {
876 $categories[$row->page_title] = 'hidden';
880 # Add the remaining categories to the skin
881 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks ) ) ) {
882 $sk = $wgUser->getSkin();
883 foreach ( $categories as $category => $type ) {
884 $origcategory = $category;
885 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
886 $wgContLang->findVariantLink( $category, $title, true );
887 if ( $category != $origcategory ) {
888 if ( array_key_exists( $category, $categories ) ) {
889 continue;
892 $text = $wgContLang->convertHtml( $title->getText() );
893 $this->mCategories[] = $title->getText();
894 $this->mCategoryLinks[$type][] = $sk->link( $title, $text );
900 * Reset the category links (but not the category list) and add $categories
902 * @param $categories Associative array mapping category name to its sort key
904 public function setCategoryLinks( $categories ) {
905 $this->mCategoryLinks = array();
906 $this->addCategoryLinks( $categories );
910 * Get the list of category links, in a 2-D array with the following format:
911 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
912 * hidden categories) and $link a HTML fragment with a link to the category
913 * page
915 * @return Array
917 public function getCategoryLinks() {
918 return $this->mCategoryLinks;
922 * Get the list of category names this page belongs to
924 * @return Array of strings
926 public function getCategories() {
927 return $this->mCategories;
931 * Suppress the quickbar from the output, only for skin supporting
932 * the quickbar
934 public function suppressQuickbar() {
935 $this->mSuppressQuickbar = true;
939 * Return whether the quickbar should be suppressed from the output
941 * @return Boolean
943 public function isQuickbarSuppressed() {
944 return $this->mSuppressQuickbar;
948 * Remove user JavaScript from scripts to load
950 public function disallowUserJs() {
951 $this->mAllowUserJs = false;
955 * Return whether user JavaScript is allowed for this page
957 * @return Boolean
959 public function isUserJsAllowed() {
960 return $this->mAllowUserJs;
964 * Prepend $text to the body HTML
966 * @param $text String: HTML
968 public function prependHTML( $text ) {
969 $this->mBodytext = $text . $this->mBodytext;
973 * Append $text to the body HTML
975 * @param $text String: HTML
977 public function addHTML( $text ) {
978 $this->mBodytext .= $text;
982 * Clear the body HTML
984 public function clearHTML() {
985 $this->mBodytext = '';
989 * Get the body HTML
991 * @return String: HTML
993 public function getHTML() {
994 return $this->mBodytext;
998 * Add $text to the debug output
1000 * @param $text String: debug text
1002 public function debug( $text ) {
1003 $this->mDebugtext .= $text;
1007 * @deprecated use parserOptions() instead
1009 public function setParserOptions( $options ) {
1010 wfDeprecated( __METHOD__ );
1011 return $this->parserOptions( $options );
1015 * Get/set the ParserOptions object to use for wikitext parsing
1017 * @param $options either the ParserOption to use or null to only get the
1018 * current ParserOption object
1019 * @return current ParserOption object
1021 public function parserOptions( $options = null ) {
1022 if ( !$this->mParserOptions ) {
1023 $this->mParserOptions = new ParserOptions;
1025 return wfSetVar( $this->mParserOptions, $options );
1029 * Set the revision ID which will be seen by the wiki text parser
1030 * for things such as embedded {{REVISIONID}} variable use.
1032 * @param $revid Mixed: an positive integer, or null
1033 * @return Mixed: previous value
1035 public function setRevisionId( $revid ) {
1036 $val = is_null( $revid ) ? null : intval( $revid );
1037 return wfSetVar( $this->mRevisionId, $val );
1041 * Get the current revision ID
1043 * @return Integer
1045 public function getRevisionId() {
1046 return $this->mRevisionId;
1050 * Convert wikitext to HTML and add it to the buffer
1051 * Default assumes that the current page title will be used.
1053 * @param $text String
1054 * @param $linestart Boolean: is this the start of a line?
1056 public function addWikiText( $text, $linestart = true ) {
1057 $title = $this->getTitle(); // Work arround E_STRICT
1058 $this->addWikiTextTitle( $text, $title, $linestart );
1062 * Add wikitext with a custom Title object
1064 * @param $text String: wikitext
1065 * @param $title Title object
1066 * @param $linestart Boolean: is this the start of a line?
1068 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1069 $this->addWikiTextTitle( $text, $title, $linestart );
1073 * Add wikitext with a custom Title object and
1075 * @param $text String: wikitext
1076 * @param $title Title object
1077 * @param $linestart Boolean: is this the start of a line?
1079 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1080 $this->addWikiTextTitle( $text, $title, $linestart, true );
1084 * Add wikitext with tidy enabled
1086 * @param $text String: wikitext
1087 * @param $linestart Boolean: is this the start of a line?
1089 public function addWikiTextTidy( $text, $linestart = true ) {
1090 $title = $this->getTitle();
1091 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1095 * Add wikitext with a custom Title object
1097 * @param $text String: wikitext
1098 * @param $title Title object
1099 * @param $linestart Boolean: is this the start of a line?
1100 * @param $tidy Boolean: whether to use tidy
1102 public function addWikiTextTitle( $text, &$title, $linestart, $tidy = false ) {
1103 global $wgParser;
1105 wfProfileIn( __METHOD__ );
1107 wfIncrStats( 'pcache_not_possible' );
1109 $popts = $this->parserOptions();
1110 $oldTidy = $popts->setTidy( $tidy );
1112 $parserOutput = $wgParser->parse(
1113 $text, $title, $popts,
1114 $linestart, true, $this->mRevisionId
1117 $popts->setTidy( $oldTidy );
1119 $this->addParserOutput( $parserOutput );
1121 wfProfileOut( __METHOD__ );
1125 * Add wikitext to the buffer, assuming that this is the primary text for a page view
1126 * Saves the text into the parser cache if possible.
1128 * @param $text String: wikitext
1129 * @param $article Article object
1130 * @param $cache Boolean
1131 * @deprecated Use Article::outputWikitext
1133 public function addPrimaryWikiText( $text, $article, $cache = true ) {
1134 global $wgParser;
1136 wfDeprecated( __METHOD__ );
1138 $popts = $this->parserOptions();
1139 $popts->setTidy( true );
1140 $parserOutput = $wgParser->parse(
1141 $text, $article->mTitle,
1142 $popts, true, true, $this->mRevisionId
1144 $popts->setTidy( false );
1145 if ( $cache && $article && $parserOutput->isCacheable() ) {
1146 $parserCache = ParserCache::singleton();
1147 $parserCache->save( $parserOutput, $article, $popts );
1150 $this->addParserOutput( $parserOutput );
1154 * @deprecated use addWikiTextTidy()
1156 public function addSecondaryWikiText( $text, $linestart = true ) {
1157 wfDeprecated( __METHOD__ );
1158 $this->addWikiTextTitleTidy( $text, $this->getTitle(), $linestart );
1162 * Add a ParserOutput object, but without Html
1164 * @param $parserOutput ParserOutput object
1166 public function addParserOutputNoText( &$parserOutput ) {
1167 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
1168 $this->addCategoryLinks( $parserOutput->getCategories() );
1169 $this->mNewSectionLink = $parserOutput->getNewSection();
1170 $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
1172 $this->mParseWarnings = $parserOutput->getWarnings();
1173 if ( !$parserOutput->isCacheable() ) {
1174 $this->enableClientCache( false );
1176 $this->mNoGallery = $parserOutput->getNoGallery();
1177 $this->mHeadItems = array_merge( $this->mHeadItems, $parserOutput->getHeadItems() );
1178 $this->addModules( $parserOutput->getModules() );
1179 // Versioning...
1180 foreach ( (array)$parserOutput->mTemplateIds as $ns => $dbks ) {
1181 if ( isset( $this->mTemplateIds[$ns] ) ) {
1182 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
1183 } else {
1184 $this->mTemplateIds[$ns] = $dbks;
1188 // Hooks registered in the object
1189 global $wgParserOutputHooks;
1190 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1191 list( $hookName, $data ) = $hookInfo;
1192 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1193 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1197 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1201 * Add a ParserOutput object
1203 * @param $parserOutput ParserOutput
1205 function addParserOutput( &$parserOutput ) {
1206 $this->addParserOutputNoText( $parserOutput );
1207 $text = $parserOutput->getText();
1208 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1209 $this->addHTML( $text );
1214 * Add the output of a QuickTemplate to the output buffer
1216 * @param $template QuickTemplate
1218 public function addTemplate( &$template ) {
1219 ob_start();
1220 $template->execute();
1221 $this->addHTML( ob_get_contents() );
1222 ob_end_clean();
1226 * Parse wikitext and return the HTML.
1228 * @param $text String
1229 * @param $linestart Boolean: is this the start of a line?
1230 * @param $interface Boolean: use interface language ($wgLang instead of
1231 * $wgContLang) while parsing language sensitive magic
1232 * words like GRAMMAR and PLURAL
1233 * @return String: HTML
1235 public function parse( $text, $linestart = true, $interface = false ) {
1236 global $wgParser;
1237 if( is_null( $this->getTitle() ) ) {
1238 throw new MWException( 'Empty $mTitle in ' . __METHOD__ );
1240 $popts = $this->parserOptions();
1241 if ( $interface ) {
1242 $popts->setInterfaceMessage( true );
1244 $parserOutput = $wgParser->parse(
1245 $text, $this->getTitle(), $popts,
1246 $linestart, true, $this->mRevisionId
1248 if ( $interface ) {
1249 $popts->setInterfaceMessage( false );
1251 return $parserOutput->getText();
1255 * Parse wikitext, strip paragraphs, and return the HTML.
1257 * @param $text String
1258 * @param $linestart Boolean: is this the start of a line?
1259 * @param $interface Boolean: use interface language ($wgLang instead of
1260 * $wgContLang) while parsing language sensitive magic
1261 * words like GRAMMAR and PLURAL
1262 * @return String: HTML
1264 public function parseInline( $text, $linestart = true, $interface = false ) {
1265 $parsed = $this->parse( $text, $linestart, $interface );
1267 $m = array();
1268 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1269 $parsed = $m[1];
1272 return $parsed;
1276 * @deprecated
1278 * @param $article Article
1279 * @return Boolean: true if successful, else false.
1281 public function tryParserCache( &$article ) {
1282 wfDeprecated( __METHOD__ );
1283 $parserOutput = ParserCache::singleton()->get( $article, $article->getParserOptions() );
1285 if ( $parserOutput !== false ) {
1286 $this->addParserOutput( $parserOutput );
1287 return true;
1288 } else {
1289 return false;
1294 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1296 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1298 public function setSquidMaxage( $maxage ) {
1299 $this->mSquidMaxage = $maxage;
1303 * Use enableClientCache(false) to force it to send nocache headers
1305 * @param $state ??
1307 public function enableClientCache( $state ) {
1308 return wfSetVar( $this->mEnableClientCache, $state );
1312 * Get the list of cookies that will influence on the cache
1314 * @return Array
1316 function getCacheVaryCookies() {
1317 global $wgCookiePrefix, $wgCacheVaryCookies;
1318 static $cookies;
1319 if ( $cookies === null ) {
1320 $cookies = array_merge(
1321 array(
1322 "{$wgCookiePrefix}Token",
1323 "{$wgCookiePrefix}LoggedOut",
1324 session_name()
1326 $wgCacheVaryCookies
1328 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1330 return $cookies;
1334 * Return whether this page is not cacheable because "useskin" or "uselang"
1335 * URL parameters were passed.
1337 * @return Boolean
1339 function uncacheableBecauseRequestVars() {
1340 global $wgRequest;
1341 return $wgRequest->getText( 'useskin', false ) === false
1342 && $wgRequest->getText( 'uselang', false ) === false;
1346 * Check if the request has a cache-varying cookie header
1347 * If it does, it's very important that we don't allow public caching
1349 * @return Boolean
1351 function haveCacheVaryCookies() {
1352 global $wgRequest;
1353 $cookieHeader = $wgRequest->getHeader( 'cookie' );
1354 if ( $cookieHeader === false ) {
1355 return false;
1357 $cvCookies = $this->getCacheVaryCookies();
1358 foreach ( $cvCookies as $cookieName ) {
1359 # Check for a simple string match, like the way squid does it
1360 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1361 wfDebug( __METHOD__ . ": found $cookieName\n" );
1362 return true;
1365 wfDebug( __METHOD__ . ": no cache-varying cookies found\n" );
1366 return false;
1370 * Add an HTTP header that will influence on the cache
1372 * @param $header String: header name
1373 * @param $option either an Array or null
1375 public function addVaryHeader( $header, $option = null ) {
1376 if ( !array_key_exists( $header, $this->mVaryHeader ) ) {
1377 $this->mVaryHeader[$header] = $option;
1378 } elseif( is_array( $option ) ) {
1379 if( is_array( $this->mVaryHeader[$header] ) ) {
1380 $this->mVaryHeader[$header] = array_merge( $this->mVaryHeader[$header], $option );
1381 } else {
1382 $this->mVaryHeader[$header] = $option;
1385 $this->mVaryHeader[$header] = array_unique( $this->mVaryHeader[$header] );
1389 * Get a complete X-Vary-Options header
1391 * @return String
1393 public function getXVO() {
1394 $cvCookies = $this->getCacheVaryCookies();
1396 $cookiesOption = array();
1397 foreach ( $cvCookies as $cookieName ) {
1398 $cookiesOption[] = 'string-contains=' . $cookieName;
1400 $this->addVaryHeader( 'Cookie', $cookiesOption );
1402 $headers = array();
1403 foreach( $this->mVaryHeader as $header => $option ) {
1404 $newheader = $header;
1405 if( is_array( $option ) ) {
1406 $newheader .= ';' . implode( ';', $option );
1408 $headers[] = $newheader;
1410 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1412 return $xvo;
1416 * bug 21672: Add Accept-Language to Vary and XVO headers
1417 * if there's no 'variant' parameter existed in GET.
1419 * For example:
1420 * /w/index.php?title=Main_page should always be served; but
1421 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1423 function addAcceptLanguage() {
1424 global $wgRequest, $wgContLang;
1425 if( !$wgRequest->getCheck( 'variant' ) && $wgContLang->hasVariants() ) {
1426 $variants = $wgContLang->getVariants();
1427 $aloption = array();
1428 foreach ( $variants as $variant ) {
1429 if( $variant === $wgContLang->getCode() ) {
1430 continue;
1431 } else {
1432 $aloption[] = "string-contains=$variant";
1435 $this->addVaryHeader( 'Accept-Language', $aloption );
1440 * Send cache control HTTP headers
1442 public function sendCacheControl() {
1443 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest, $wgUseXVO;
1445 $response = $wgRequest->response();
1446 if ( $wgUseETag && $this->mETag ) {
1447 $response->header( "ETag: $this->mETag" );
1450 $this->addAcceptLanguage();
1452 # don't serve compressed data to clients who can't handle it
1453 # maintain different caches for logged-in users and non-logged in ones
1454 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader ) ) );
1456 if ( $wgUseXVO ) {
1457 # Add an X-Vary-Options header for Squid with Wikimedia patches
1458 $response->header( $this->getXVO() );
1461 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache ) {
1463 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1464 $this->mSquidMaxage != 0 && !$this->haveCacheVaryCookies()
1467 if ( $wgUseESI ) {
1468 # We'll purge the proxy cache explicitly, but require end user agents
1469 # to revalidate against the proxy on each visit.
1470 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1471 wfDebug( __METHOD__ . ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1472 # start with a shorter timeout for initial testing
1473 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1474 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage.', content="ESI/1.0"');
1475 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1476 } else {
1477 # We'll purge the proxy cache for anons explicitly, but require end user agents
1478 # to revalidate against the proxy on each visit.
1479 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1480 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1481 wfDebug( __METHOD__ . ": local proxy caching; {$this->mLastModified} **\n", false );
1482 # start with a shorter timeout for initial testing
1483 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1484 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage.', must-revalidate, max-age=0' );
1486 } else {
1487 # We do want clients to cache if they can, but they *must* check for updates
1488 # on revisiting the page.
1489 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **\n", false );
1490 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1491 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1493 if($this->mLastModified) {
1494 $response->header( "Last-Modified: {$this->mLastModified}" );
1496 } else {
1497 wfDebug( __METHOD__ . ": no caching **\n", false );
1499 # In general, the absence of a last modified header should be enough to prevent
1500 # the client from using its cache. We send a few other things just to make sure.
1501 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1502 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1503 $response->header( 'Pragma: no-cache' );
1508 * Get the message associed with the HTTP response code $code
1510 * @param $code Integer: status code
1511 * @return String or null: message or null if $code is not in the list of
1512 * messages
1514 public static function getStatusMessage( $code ) {
1515 static $statusMessage = array(
1516 100 => 'Continue',
1517 101 => 'Switching Protocols',
1518 102 => 'Processing',
1519 200 => 'OK',
1520 201 => 'Created',
1521 202 => 'Accepted',
1522 203 => 'Non-Authoritative Information',
1523 204 => 'No Content',
1524 205 => 'Reset Content',
1525 206 => 'Partial Content',
1526 207 => 'Multi-Status',
1527 300 => 'Multiple Choices',
1528 301 => 'Moved Permanently',
1529 302 => 'Found',
1530 303 => 'See Other',
1531 304 => 'Not Modified',
1532 305 => 'Use Proxy',
1533 307 => 'Temporary Redirect',
1534 400 => 'Bad Request',
1535 401 => 'Unauthorized',
1536 402 => 'Payment Required',
1537 403 => 'Forbidden',
1538 404 => 'Not Found',
1539 405 => 'Method Not Allowed',
1540 406 => 'Not Acceptable',
1541 407 => 'Proxy Authentication Required',
1542 408 => 'Request Timeout',
1543 409 => 'Conflict',
1544 410 => 'Gone',
1545 411 => 'Length Required',
1546 412 => 'Precondition Failed',
1547 413 => 'Request Entity Too Large',
1548 414 => 'Request-URI Too Large',
1549 415 => 'Unsupported Media Type',
1550 416 => 'Request Range Not Satisfiable',
1551 417 => 'Expectation Failed',
1552 422 => 'Unprocessable Entity',
1553 423 => 'Locked',
1554 424 => 'Failed Dependency',
1555 500 => 'Internal Server Error',
1556 501 => 'Not Implemented',
1557 502 => 'Bad Gateway',
1558 503 => 'Service Unavailable',
1559 504 => 'Gateway Timeout',
1560 505 => 'HTTP Version Not Supported',
1561 507 => 'Insufficient Storage'
1563 return isset( $statusMessage[$code] ) ? $statusMessage[$code] : null;
1567 * Finally, all the text has been munged and accumulated into
1568 * the object, let's actually output it:
1570 public function output() {
1571 global $wgUser, $wgOutputEncoding, $wgRequest;
1572 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType;
1573 global $wgUseAjax, $wgAjaxWatch;
1574 global $wgEnableMWSuggest, $wgUniversalEditButton;
1575 global $wgArticle;
1577 if( $this->mDoNothing ) {
1578 return;
1580 wfProfileIn( __METHOD__ );
1581 if ( $this->mRedirect != '' ) {
1582 # Standards require redirect URLs to be absolute
1583 $this->mRedirect = wfExpandUrl( $this->mRedirect );
1584 if( $this->mRedirectCode == '301' || $this->mRedirectCode == '303' ) {
1585 if( !$wgDebugRedirects ) {
1586 $message = self::getStatusMessage( $this->mRedirectCode );
1587 $wgRequest->response()->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
1589 $this->mLastModified = wfTimestamp( TS_RFC2822 );
1591 $this->sendCacheControl();
1593 $wgRequest->response()->header( "Content-Type: text/html; charset=utf-8" );
1594 if( $wgDebugRedirects ) {
1595 $url = htmlspecialchars( $this->mRedirect );
1596 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1597 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1598 print "</body>\n</html>\n";
1599 } else {
1600 $wgRequest->response()->header( 'Location: ' . $this->mRedirect );
1602 wfProfileOut( __METHOD__ );
1603 return;
1604 } elseif ( $this->mStatusCode ) {
1605 $message = self::getStatusMessage( $this->mStatusCode );
1606 if ( $message ) {
1607 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode . ' ' . $message );
1611 $sk = $wgUser->getSkin();
1613 // Add base resources
1614 $this->addModules( array( 'mediawiki.legacy.wikibits' ) );
1616 // Add various resources if required
1617 if ( $wgUseAjax ) {
1618 $this->addModules( 'mediawiki.legacy.ajax' );
1620 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1622 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1623 $this->addModules( 'mediawiki.legacy.ajaxwatch' );
1626 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ) {
1627 $this->addModules( 'mediawiki.legacy.mwsuggest' );
1631 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1632 $this->addModules( 'mediawiki.legacy.rightclickedit' );
1635 if( $wgUniversalEditButton ) {
1636 if( isset( $wgArticle ) && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1637 && ( $this->getTitle()->exists() || $this->getTitle()->quickUserCan( 'create' ) ) ) {
1638 // Original UniversalEditButton
1639 $msg = wfMsg( 'edit' );
1640 $this->addLink( array(
1641 'rel' => 'alternate',
1642 'type' => 'application/x-wiki',
1643 'title' => $msg,
1644 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1645 ) );
1646 // Alternate edit link
1647 $this->addLink( array(
1648 'rel' => 'edit',
1649 'title' => $msg,
1650 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1651 ) );
1656 # Buffer output; final headers may depend on later processing
1657 ob_start();
1659 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1660 $wgRequest->response()->header( 'Content-language: ' . $wgLanguageCode );
1662 if ( $this->mArticleBodyOnly ) {
1663 $this->out( $this->mBodytext );
1664 } else {
1665 // Hook that allows last minute changes to the output page, e.g.
1666 // adding of CSS or Javascript by extensions.
1667 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1669 wfProfileIn( 'Output-skin' );
1670 $sk->outputPage( $this );
1671 wfProfileOut( 'Output-skin' );
1674 $this->sendCacheControl();
1675 ob_end_flush();
1676 wfProfileOut( __METHOD__ );
1680 * Actually output something with print(). Performs an iconv to the
1681 * output encoding, if needed.
1683 * @param $ins String: the string to output
1685 public function out( $ins ) {
1686 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1687 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1688 $outs = $ins;
1689 } else {
1690 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1691 if ( false === $outs ) {
1692 $outs = $ins;
1695 print $outs;
1699 * @todo document
1701 public static function setEncodings() {
1702 global $wgInputEncoding, $wgOutputEncoding;
1704 $wgInputEncoding = strtolower( $wgInputEncoding );
1706 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
1707 $wgOutputEncoding = strtolower( $wgOutputEncoding );
1708 return;
1710 $wgOutputEncoding = $wgInputEncoding;
1714 * @deprecated use wfReportTime() instead.
1716 * @return String
1718 public function reportTime() {
1719 wfDeprecated( __METHOD__ );
1720 $time = wfReportTime();
1721 return $time;
1725 * Produce a "user is blocked" page.
1727 * @param $return Boolean: whether to have a "return to $wgTitle" message or not.
1728 * @return nothing
1730 function blockedPage( $return = true ) {
1731 global $wgUser, $wgContLang, $wgLang;
1733 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1734 $this->setRobotPolicy( 'noindex,nofollow' );
1735 $this->setArticleRelated( false );
1737 $name = User::whoIs( $wgUser->blockedBy() );
1738 $reason = $wgUser->blockedFor();
1739 if( $reason == '' ) {
1740 $reason = wfMsg( 'blockednoreason' );
1742 $blockTimestamp = $wgLang->timeanddate(
1743 wfTimestamp( TS_MW, $wgUser->mBlock->mTimestamp ), true
1745 $ip = wfGetIP();
1747 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
1749 $blockid = $wgUser->mBlock->mId;
1751 $blockExpiry = $wgUser->mBlock->mExpiry;
1752 if ( $blockExpiry == 'infinity' ) {
1753 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1754 // Search for localization in 'ipboptions'
1755 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1756 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1757 if ( strpos( $option, ':' ) === false ) {
1758 continue;
1760 list( $show, $value ) = explode( ':', $option );
1761 if ( $value == 'infinite' || $value == 'indefinite' ) {
1762 $blockExpiry = $show;
1763 break;
1766 } else {
1767 $blockExpiry = $wgLang->timeanddate(
1768 wfTimestamp( TS_MW, $blockExpiry ),
1769 true
1773 if ( $wgUser->mBlock->mAuto ) {
1774 $msg = 'autoblockedtext';
1775 } else {
1776 $msg = 'blockedtext';
1779 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1780 * This could be a username, an IP range, or a single IP. */
1781 $intended = $wgUser->mBlock->mAddress;
1783 $this->addWikiMsg(
1784 $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry,
1785 $intended, $blockTimestamp
1788 # Don't auto-return to special pages
1789 if( $return ) {
1790 $return = $this->getTitle()->getNamespace() > -1 ? $this->getTitle() : null;
1791 $this->returnToMain( null, $return );
1796 * Output a standard error page
1798 * @param $title String: message key for page title
1799 * @param $msg String: message key for page text
1800 * @param $params Array: message parameters
1802 public function showErrorPage( $title, $msg, $params = array() ) {
1803 if ( $this->getTitle() ) {
1804 $this->mDebugtext .= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1806 $this->setPageTitle( wfMsg( $title ) );
1807 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1808 $this->setRobotPolicy( 'noindex,nofollow' );
1809 $this->setArticleRelated( false );
1810 $this->enableClientCache( false );
1811 $this->mRedirect = '';
1812 $this->mBodytext = '';
1814 array_unshift( $params, 'parse' );
1815 array_unshift( $params, $msg );
1816 $this->addHTML( call_user_func_array( 'wfMsgExt', $params ) );
1818 $this->returnToMain();
1822 * Output a standard permission error page
1824 * @param $errors Array: error message keys
1825 * @param $action String: action that was denied or null if unknown
1827 public function showPermissionsErrorPage( $errors, $action = null ) {
1828 $this->mDebugtext .= 'Original title: ' .
1829 $this->getTitle()->getPrefixedText() . "\n";
1830 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1831 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1832 $this->setRobotPolicy( 'noindex,nofollow' );
1833 $this->setArticleRelated( false );
1834 $this->enableClientCache( false );
1835 $this->mRedirect = '';
1836 $this->mBodytext = '';
1837 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1841 * Display an error page indicating that a given version of MediaWiki is
1842 * required to use it
1844 * @param $version Mixed: the version of MediaWiki needed to use the page
1846 public function versionRequired( $version ) {
1847 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1848 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1849 $this->setRobotPolicy( 'noindex,nofollow' );
1850 $this->setArticleRelated( false );
1851 $this->mBodytext = '';
1853 $this->addWikiMsg( 'versionrequiredtext', $version );
1854 $this->returnToMain();
1858 * Display an error page noting that a given permission bit is required.
1860 * @param $permission String: key required
1862 public function permissionRequired( $permission ) {
1863 global $wgLang;
1865 $this->setPageTitle( wfMsg( 'badaccess' ) );
1866 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1867 $this->setRobotPolicy( 'noindex,nofollow' );
1868 $this->setArticleRelated( false );
1869 $this->mBodytext = '';
1871 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1872 User::getGroupsWithPermission( $permission ) );
1873 if( $groups ) {
1874 $this->addWikiMsg(
1875 'badaccess-groups',
1876 $wgLang->commaList( $groups ),
1877 count( $groups )
1879 } else {
1880 $this->addWikiMsg( 'badaccess-group0' );
1882 $this->returnToMain();
1886 * Produce the stock "please login to use the wiki" page
1888 public function loginToUse() {
1889 global $wgUser;
1891 if( $wgUser->isLoggedIn() ) {
1892 $this->permissionRequired( 'read' );
1893 return;
1896 $skin = $wgUser->getSkin();
1898 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1899 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1900 $this->setRobotPolicy( 'noindex,nofollow' );
1901 $this->setArticleFlag( false );
1903 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
1904 $loginLink = $skin->link(
1905 $loginTitle,
1906 wfMsgHtml( 'loginreqlink' ),
1907 array(),
1908 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
1909 array( 'known', 'noclasses' )
1911 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1912 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . '-->' );
1914 # Don't return to the main page if the user can't read it
1915 # otherwise we'll end up in a pointless loop
1916 $mainPage = Title::newMainPage();
1917 if( $mainPage->userCanRead() ) {
1918 $this->returnToMain( null, $mainPage );
1923 * Format a list of error messages
1925 * @param $errors An array of arrays returned by Title::getUserPermissionsErrors
1926 * @param $action String: action that was denied or null if unknown
1927 * @return String: the wikitext error-messages, formatted into a list.
1929 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1930 if ( $action == null ) {
1931 $text = wfMsgNoTrans( 'permissionserrorstext', count( $errors ) ) . "\n\n";
1932 } else {
1933 $action_desc = wfMsgNoTrans( "action-$action" );
1934 $text = wfMsgNoTrans(
1935 'permissionserrorstext-withaction',
1936 count( $errors ),
1937 $action_desc
1938 ) . "\n\n";
1941 if ( count( $errors ) > 1 ) {
1942 $text .= '<ul class="permissions-errors">' . "\n";
1944 foreach( $errors as $error ) {
1945 $text .= '<li>';
1946 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1947 $text .= "</li>\n";
1949 $text .= '</ul>';
1950 } else {
1951 $text .= "<div class=\"permissions-errors\">\n" .
1952 call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) .
1953 "\n</div>";
1956 return $text;
1960 * Display a page stating that the Wiki is in read-only mode,
1961 * and optionally show the source of the page that the user
1962 * was trying to edit. Should only be called (for this
1963 * purpose) after wfReadOnly() has returned true.
1965 * For historical reasons, this function is _also_ used to
1966 * show the error message when a user tries to edit a page
1967 * they are not allowed to edit. (Unless it's because they're
1968 * blocked, then we show blockedPage() instead.) In this
1969 * case, the second parameter should be set to true and a list
1970 * of reasons supplied as the third parameter.
1972 * @todo Needs to be split into multiple functions.
1974 * @param $source String: source code to show (or null).
1975 * @param $protected Boolean: is this a permissions error?
1976 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
1977 * @param $action String: action that was denied or null if unknown
1979 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1980 global $wgUser;
1981 $skin = $wgUser->getSkin();
1983 $this->setRobotPolicy( 'noindex,nofollow' );
1984 $this->setArticleRelated( false );
1986 // If no reason is given, just supply a default "I can't let you do
1987 // that, Dave" message. Should only occur if called by legacy code.
1988 if ( $protected && empty( $reasons ) ) {
1989 $reasons[] = array( 'badaccess-group0' );
1992 if ( !empty( $reasons ) ) {
1993 // Permissions error
1994 if( $source ) {
1995 $this->setPageTitle( wfMsg( 'viewsource' ) );
1996 $this->setSubtitle(
1997 wfMsg( 'viewsourcefor', $skin->linkKnown( $this->getTitle() ) )
1999 } else {
2000 $this->setPageTitle( wfMsg( 'badaccess' ) );
2002 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2003 } else {
2004 // Wiki is read only
2005 $this->setPageTitle( wfMsg( 'readonly' ) );
2006 $reason = wfReadOnlyReason();
2007 $this->wrapWikiMsg( "<div class='mw-readonly-error'>\n$1\n</div>", array( 'readonlytext', $reason ) );
2010 // Show source, if supplied
2011 if( is_string( $source ) ) {
2012 $this->addWikiMsg( 'viewsourcetext' );
2014 $params = array(
2015 'id' => 'wpTextbox1',
2016 'name' => 'wpTextbox1',
2017 'cols' => $wgUser->getOption( 'cols' ),
2018 'rows' => $wgUser->getOption( 'rows' ),
2019 'readonly' => 'readonly'
2021 $this->addHTML( Html::element( 'textarea', $params, $source ) );
2023 // Show templates used by this article
2024 $skin = $wgUser->getSkin();
2025 $article = new Article( $this->getTitle() );
2026 $this->addHTML( "<div class='templatesUsed'>
2027 {$skin->formatTemplates( $article->getUsedTemplates() )}
2028 </div>
2029 " );
2032 # If the title doesn't exist, it's fairly pointless to print a return
2033 # link to it. After all, you just tried editing it and couldn't, so
2034 # what's there to do there?
2035 if( $this->getTitle()->exists() ) {
2036 $this->returnToMain( null, $this->getTitle() );
2041 * Adds JS-based password security checker
2042 * @param $passwordId String ID of input box containing password
2043 * @param $retypeId String ID of input box containing retyped password
2044 * @return none
2046 public function addPasswordSecurity( $passwordId, $retypeId ) {
2047 $this->includeJQuery();
2048 $data = array(
2049 'password' => '#' . $passwordId,
2050 'retype' => '#' . $retypeId,
2051 'messages' => array(),
2053 foreach ( array( 'password-strength', 'password-strength-bad', 'password-strength-mediocre',
2054 'password-strength-acceptable', 'password-strength-good', 'password-retype', 'password-retype-mismatch'
2055 ) as $message ) {
2056 $data['messages'][$message] = wfMsg( $message );
2058 $this->addScript( Html::inlineScript( 'var passwordSecurity=' . FormatJson::encode( $data ) ) );
2059 $this->addModules( 'mediawiki.legacy.password' );
2062 /** @deprecated */
2063 public function errorpage( $title, $msg ) {
2064 wfDeprecated( __METHOD__ );
2065 throw new ErrorPageError( $title, $msg );
2068 /** @deprecated */
2069 public function databaseError( $fname, $sql, $error, $errno ) {
2070 throw new MWException( "OutputPage::databaseError is obsolete\n" );
2073 /** @deprecated */
2074 public function fatalError( $message ) {
2075 wfDeprecated( __METHOD__ );
2076 throw new FatalError( $message );
2079 /** @deprecated */
2080 public function unexpectedValueError( $name, $val ) {
2081 wfDeprecated( __METHOD__ );
2082 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
2085 /** @deprecated */
2086 public function fileCopyError( $old, $new ) {
2087 wfDeprecated( __METHOD__ );
2088 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
2091 /** @deprecated */
2092 public function fileRenameError( $old, $new ) {
2093 wfDeprecated( __METHOD__ );
2094 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
2097 /** @deprecated */
2098 public function fileDeleteError( $name ) {
2099 wfDeprecated( __METHOD__ );
2100 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
2103 /** @deprecated */
2104 public function fileNotFoundError( $name ) {
2105 wfDeprecated( __METHOD__ );
2106 throw new FatalError( wfMsg( 'filenotfound', $name ) );
2109 public function showFatalError( $message ) {
2110 $this->setPageTitle( wfMsg( 'internalerror' ) );
2111 $this->setRobotPolicy( 'noindex,nofollow' );
2112 $this->setArticleRelated( false );
2113 $this->enableClientCache( false );
2114 $this->mRedirect = '';
2115 $this->mBodytext = $message;
2118 public function showUnexpectedValueError( $name, $val ) {
2119 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
2122 public function showFileCopyError( $old, $new ) {
2123 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
2126 public function showFileRenameError( $old, $new ) {
2127 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
2130 public function showFileDeleteError( $name ) {
2131 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
2134 public function showFileNotFoundError( $name ) {
2135 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
2139 * Add a "return to" link pointing to a specified title
2141 * @param $title Title to link
2142 * @param $query String: query string
2143 * @param $text String text of the link (input is not escaped)
2145 public function addReturnTo( $title, $query = array(), $text = null ) {
2146 global $wgUser;
2147 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL() ) );
2148 $link = wfMsgHtml(
2149 'returnto',
2150 $wgUser->getSkin()->link( $title, $text, array(), $query )
2152 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2156 * Add a "return to" link pointing to a specified title,
2157 * or the title indicated in the request, or else the main page
2159 * @param $unused No longer used
2160 * @param $returnto Title or String to return to
2161 * @param $returntoquery String: query string for the return to link
2163 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2164 global $wgRequest;
2166 if ( $returnto == null ) {
2167 $returnto = $wgRequest->getText( 'returnto' );
2170 if ( $returntoquery == null ) {
2171 $returntoquery = $wgRequest->getText( 'returntoquery' );
2174 if ( $returnto === '' ) {
2175 $returnto = Title::newMainPage();
2178 if ( is_object( $returnto ) ) {
2179 $titleObj = $returnto;
2180 } else {
2181 $titleObj = Title::newFromText( $returnto );
2183 if ( !is_object( $titleObj ) ) {
2184 $titleObj = Title::newMainPage();
2187 $this->addReturnTo( $titleObj, $returntoquery );
2191 * @param $sk Skin The given Skin
2192 * @param $includeStyle Boolean: unused
2193 * @return String: The doctype, opening <html>, and head element.
2195 public function headElement( Skin $sk, $includeStyle = true ) {
2196 global $wgOutputEncoding, $wgMimeType;
2197 global $wgUseTrackbacks, $wgHtml5;
2198 global $wgUser, $wgRequest, $wgLang;
2200 if ( $sk->commonPrintStylesheet() ) {
2201 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2203 $sk->setupUserCss( $this );
2205 $ret = Html::htmlHeader( array( 'lang' => wfUILang()->getCode() ) );
2207 if ( $this->getHTMLTitle() == '' ) {
2208 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ) );
2211 $openHead = Html::openElement( 'head' );
2212 if ( $openHead ) {
2213 # Don't bother with the newline if $head == ''
2214 $ret .= "$openHead\n";
2217 if ( $wgHtml5 ) {
2218 # More succinct than <meta http-equiv=Content-Type>, has the
2219 # same effect
2220 $ret .= Html::element( 'meta', array( 'charset' => $wgOutputEncoding ) ) . "\n";
2221 } else {
2222 $this->addMeta( 'http:Content-Type', "$wgMimeType; charset=$wgOutputEncoding" );
2225 $ret .= Html::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2227 $ret .= implode( "\n", array(
2228 $this->getHeadLinks( $sk ),
2229 $this->buildCssLinks(),
2230 $this->getHeadItems(),
2231 ) );
2232 if ( $sk->usercss ) {
2233 $ret .= Html::inlineStyle( $sk->usercss );
2236 if ( $wgUseTrackbacks && $this->isArticleRelated() ) {
2237 $ret .= $this->getTitle()->trackbackRDF();
2240 $closeHead = Html::closeElement( 'head' );
2241 if ( $closeHead ) {
2242 $ret .= "$closeHead\n";
2245 $bodyAttrs = array();
2247 # Crazy edit-on-double-click stuff
2248 $action = $wgRequest->getVal( 'action', 'view' );
2250 if (
2251 $this->getTitle()->getNamespace() != NS_SPECIAL &&
2252 !in_array( $action, array( 'edit', 'submit' ) ) &&
2253 $wgUser->getOption( 'editondblclick' )
2256 $bodyAttrs['ondblclick'] = "document.location = '" . Xml::escapeJsString( $this->getTitle()->getEditURL() ) . "'";
2259 # Class bloat
2260 $dir = wfUILang()->getDir();
2261 $bodyAttrs['class'] = "mediawiki $dir";
2263 if ( $wgLang->capitalizeAllNouns() ) {
2264 # A <body> class is probably not the best way to do this . . .
2265 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2267 $bodyAttrs['class'] .= ' ns-' . $this->getTitle()->getNamespace();
2268 if ( $this->getTitle()->getNamespace() == NS_SPECIAL ) {
2269 $bodyAttrs['class'] .= ' ns-special';
2270 } elseif ( $this->getTitle()->isTalkPage() ) {
2271 $bodyAttrs['class'] .= ' ns-talk';
2272 } else {
2273 $bodyAttrs['class'] .= ' ns-subject';
2275 $bodyAttrs['class'] .= ' ' . Sanitizer::escapeClass( 'page-' . $this->getTitle()->getPrefixedText() );
2276 $bodyAttrs['class'] .= ' skin-' . Sanitizer::escapeClass( $wgUser->getSkin()->getSkinName() );
2278 $ret .= Html::openElement( 'body', $bodyAttrs ) . "\n";
2280 return $ret;
2283 static function makeResourceLoaderLink( $skin, $modules, $only ) {
2284 global $wgUser, $wgLang, $wgRequest, $wgLoadScript;
2285 // TODO: Should this be a static function of ResourceLoader instead?
2286 // TODO: Divide off modules starting with "user", and add the user parameter to them
2287 $query = array(
2288 'lang' => $wgLang->getCode(),
2289 'debug' => $wgRequest->getBool( 'debug' ) && $wgRequest->getVal( 'debug' ) !== 'false',
2290 'skin' => $wgUser->getSkin()->getSkinName(),
2291 'only' => $only,
2293 $moduleGroups = array( null => array(), 'user' => array() );
2294 foreach ( (array) $modules as $module ) {
2295 $moduleGroups[strpos( $module, 'user' ) === 0 ? 'user' : null][] = $module;
2297 $links = '';
2298 foreach ( $moduleGroups as $group => $modules ) {
2299 if ( count( $modules ) ) {
2300 $query['modules'] = implode( '|', array_unique( (array) $modules ) );
2301 if ( $group === 'user' ) {
2302 $query['user'] = $wgUser->getName();
2304 // Automatically select style/script elements
2305 if ( $only === 'styles' ) {
2306 $links .= Html::linkedStyle( wfAppendQuery( $wgLoadScript, $query ) );
2307 } else {
2308 $links .= Html::linkedScript( wfAppendQuery( $wgLoadScript, $query ) );
2312 return $links;
2316 * Gets the global variables and mScripts; also adds userjs to the end if
2317 * enabled. Despite the name, these scripts are no longer put in the
2318 * <head> but at the bottom of the <body>
2320 * @param $sk Skin object to use
2321 * @return String: HTML fragment
2323 function getHeadScripts( Skin $sk ) {
2324 global $wgUser, $wgRequest, $wgJsMimeType;
2325 global $wgUseSiteJs;
2327 // Statup - this will immediately load jquery and mediawiki modules
2328 $scripts = self::makeResourceLoaderLink( $sk, 'startup', 'scripts' );
2330 // Configuration -- This could be merged together with the load and go, but makeGlobalVariablesScript returns a
2331 // whole script tag -- grumble grumble...
2332 $scripts .= Skin::makeGlobalVariablesScript( $sk->getSkinName() ) . "\n";
2334 // Script and Messages "only"
2335 if ( $wgRequest->getBool( 'debug' ) && $wgRequest->getVal( 'debug' ) !== 'false' ) {
2336 // Scripts
2337 foreach ( $this->getModuleScripts() as $name ) {
2338 $scripts .= self::makeResourceLoaderLink( $sk, $name, 'scripts' );
2340 // Messages
2341 foreach ( $this->getModuleMessages() as $name ) {
2342 $scripts .= self::makeResourceLoaderLink( $sk, $name, 'messages' );
2344 } else {
2345 // Scripts
2346 if ( count( $this->getModuleScripts() ) ) {
2347 $scripts .= self::makeResourceLoaderLink( $sk, $this->getModuleScripts(), 'scripts' );
2349 // Messages
2350 if ( count( $this->getModuleMessages() ) ) {
2351 $scripts .= self::makeResourceLoaderLink( $sk, $this->getModuleMessages(), 'messages' );
2355 // Modules - let the client calculate dependencies and batch requests as it likes
2356 if ( $this->getModules() ) {
2357 $modules = FormatJson::encode( $this->getModules() );
2358 $scripts .= Html::inlineScript(
2359 "if ( mediaWiki !== undefined ) { mediaWiki.loader.load( {$modules} ); mediaWiki.loader.go(); }"
2363 // Add user JS if enabled
2364 if( $this->isUserJsAllowed() && $wgUser->isLoggedIn() ) {
2365 $action = $wgRequest->getVal( 'action', 'view' );
2366 if( $this->mTitle && $this->mTitle->isJsSubpage() && $sk->userCanPreview( $action ) ) {
2367 # XXX: additional security check/prompt?
2368 $this->addInlineScript( $wgRequest->getText( 'wpTextbox1' ) );
2369 } else {
2370 $scripts .= self::makeResourceLoaderLink( $sk, 'user', 'scripts' );
2373 $scripts .= "\n" . $this->mScripts;
2375 // Add site JS if enabled
2376 if ( $wgUseSiteJs ) {
2377 $scripts .= self::makeResourceLoaderLink( $sk, 'site', 'scripts' );
2380 return $scripts;
2384 * Add default \<meta\> tags
2386 protected function addDefaultMeta() {
2387 global $wgVersion, $wgHtml5;
2389 static $called = false;
2390 if ( $called ) {
2391 # Don't run this twice
2392 return;
2394 $called = true;
2396 if ( !$wgHtml5 ) {
2397 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); // bug 15835
2399 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
2401 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
2402 if( $p !== 'index,follow' ) {
2403 // http://www.robotstxt.org/wc/meta-user.html
2404 // Only show if it's different from the default robots policy
2405 $this->addMeta( 'robots', $p );
2408 if ( count( $this->mKeywords ) > 0 ) {
2409 $strip = array(
2410 "/<.*?" . ">/" => '',
2411 "/_/" => ' '
2413 $this->addMeta(
2414 'keywords',
2415 preg_replace(
2416 array_keys( $strip ),
2417 array_values( $strip ),
2418 implode( ',', $this->mKeywords )
2425 * @return string HTML tag links to be put in the header.
2427 public function getHeadLinks( $sk ) {
2428 global $wgFeed, $wgRequest;
2430 // Ideally this should happen earlier, somewhere. :P
2431 $this->addDefaultMeta();
2433 $tags = array();
2435 foreach ( $this->mMetatags as $tag ) {
2436 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
2437 $a = 'http-equiv';
2438 $tag[0] = substr( $tag[0], 5 );
2439 } else {
2440 $a = 'name';
2442 $tags[] = Html::element( 'meta',
2443 array(
2444 $a => $tag[0],
2445 'content' => $tag[1]
2449 foreach ( $this->mLinktags as $tag ) {
2450 $tags[] = Html::element( 'link', $tag );
2453 if( $wgFeed ) {
2454 foreach( $this->getSyndicationLinks() as $format => $link ) {
2455 # Use the page name for the title (accessed through $wgTitle since
2456 # there's no other way). In principle, this could lead to issues
2457 # with having the same name for different feeds corresponding to
2458 # the same page, but we can't avoid that at this low a level.
2460 $tags[] = $this->feedLink(
2461 $format,
2462 $link,
2463 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
2464 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )
2468 # Recent changes feed should appear on every page (except recentchanges,
2469 # that would be redundant). Put it after the per-page feed to avoid
2470 # changing existing behavior. It's still available, probably via a
2471 # menu in your browser. Some sites might have a different feed they'd
2472 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
2473 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
2474 # If so, use it instead.
2476 global $wgOverrideSiteFeed, $wgSitename, $wgAdvertisedFeedTypes;
2477 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
2479 if ( $wgOverrideSiteFeed ) {
2480 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
2481 $tags[] = $this->feedLink(
2482 $type,
2483 htmlspecialchars( $feedUrl ),
2484 wfMsg( "site-{$type}-feed", $wgSitename )
2487 } elseif ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
2488 foreach ( $wgAdvertisedFeedTypes as $format ) {
2489 $tags[] = $this->feedLink(
2490 $format,
2491 $rctitle->getLocalURL( "feed={$format}" ),
2492 wfMsg( "site-{$format}-feed", $wgSitename ) # For grep: 'site-rss-feed', 'site-atom-feed'.
2498 // Support individual script requests in debug mode
2499 if ( $wgRequest->getBool( 'debug' ) && $wgRequest->getVal( 'debug' ) !== 'false' ) {
2500 foreach ( $this->getModuleStyles() as $name ) {
2501 $tags[] = self::makeResourceLoaderLink( $sk, $name, 'styles' );
2503 } else {
2504 if ( count( $this->getModuleStyles() ) ) {
2505 $tags[] = self::makeResourceLoaderLink( $sk, $this->getModuleStyles(), 'styles' );
2509 return implode( "\n", $tags );
2513 * Generate a <link rel/> for a feed.
2515 * @param $type String: feed type
2516 * @param $url String: URL to the feed
2517 * @param $text String: value of the "title" attribute
2518 * @return String: HTML fragment
2520 private function feedLink( $type, $url, $text ) {
2521 return Html::element( 'link', array(
2522 'rel' => 'alternate',
2523 'type' => "application/$type+xml",
2524 'title' => $text,
2525 'href' => $url )
2530 * Add a local or specified stylesheet, with the given media options.
2531 * Meant primarily for internal use...
2533 * @param $style String: URL to the file
2534 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
2535 * @param $condition String: for IE conditional comments, specifying an IE version
2536 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
2538 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
2539 $options = array();
2540 // Even though we expect the media type to be lowercase, but here we
2541 // force it to lowercase to be safe.
2542 if( $media ) {
2543 $options['media'] = $media;
2545 if( $condition ) {
2546 $options['condition'] = $condition;
2548 if( $dir ) {
2549 $options['dir'] = $dir;
2551 $this->styles[$style] = $options;
2555 * Adds inline CSS styles
2556 * @param $style_css Mixed: inline CSS
2558 public function addInlineStyle( $style_css ){
2559 $this->mScripts .= Html::inlineStyle( $style_css );
2563 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
2564 * These will be applied to various media & IE conditionals.
2566 public function buildCssLinks() {
2567 return implode( "\n", $this->buildCssLinksArray() );
2570 public function buildCssLinksArray() {
2571 $links = array();
2572 foreach( $this->styles as $file => $options ) {
2573 $link = $this->styleLink( $file, $options );
2574 if( $link ) {
2575 $links[$file] = $link;
2578 return $links;
2582 * Generate \<link\> tags for stylesheets
2584 * @param $style String: URL to the file
2585 * @param $options Array: option, can contain 'condition', 'dir', 'media'
2586 * keys
2587 * @return String: HTML fragment
2589 protected function styleLink( $style, $options ) {
2590 if( isset( $options['dir'] ) ) {
2591 $siteDir = wfUILang()->getDir();
2592 if( $siteDir != $options['dir'] ) {
2593 return '';
2597 if( isset( $options['media'] ) ) {
2598 $media = $this->transformCssMedia( $options['media'] );
2599 if( is_null( $media ) ) {
2600 return '';
2602 } else {
2603 $media = 'all';
2606 if( substr( $style, 0, 1 ) == '/' ||
2607 substr( $style, 0, 5 ) == 'http:' ||
2608 substr( $style, 0, 6 ) == 'https:' ) {
2609 $url = $style;
2610 } else {
2611 global $wgStylePath, $wgStyleVersion;
2612 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
2615 $link = Html::linkedStyle( $url, $media );
2617 if( isset( $options['condition'] ) ) {
2618 $condition = htmlspecialchars( $options['condition'] );
2619 $link = "<!--[if $condition]>$link<![endif]-->";
2621 return $link;
2625 * Transform "media" attribute based on request parameters
2627 * @param $media String: current value of the "media" attribute
2628 * @return String: modified value of the "media" attribute
2630 function transformCssMedia( $media ) {
2631 global $wgRequest, $wgHandheldForIPhone;
2633 // Switch in on-screen display for media testing
2634 $switches = array(
2635 'printable' => 'print',
2636 'handheld' => 'handheld',
2638 foreach( $switches as $switch => $targetMedia ) {
2639 if( $wgRequest->getBool( $switch ) ) {
2640 if( $media == $targetMedia ) {
2641 $media = '';
2642 } elseif( $media == 'screen' ) {
2643 return null;
2648 // Expand longer media queries as iPhone doesn't grok 'handheld'
2649 if( $wgHandheldForIPhone ) {
2650 $mediaAliases = array(
2651 'screen' => 'screen and (min-device-width: 481px)',
2652 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
2655 if( isset( $mediaAliases[$media] ) ) {
2656 $media = $mediaAliases[$media];
2660 return $media;
2664 * Turn off regular page output and return an error reponse
2665 * for when rate limiting has triggered.
2667 public function rateLimited() {
2668 $this->setPageTitle( wfMsg( 'actionthrottled' ) );
2669 $this->setRobotPolicy( 'noindex,follow' );
2670 $this->setArticleRelated( false );
2671 $this->enableClientCache( false );
2672 $this->mRedirect = '';
2673 $this->clearHTML();
2674 $this->setStatusCode( 503 );
2675 $this->addWikiMsg( 'actionthrottledtext' );
2677 $this->returnToMain( null, $this->getTitle() );
2681 * Show a warning about slave lag
2683 * If the lag is higher than $wgSlaveLagCritical seconds,
2684 * then the warning is a bit more obvious. If the lag is
2685 * lower than $wgSlaveLagWarning, then no warning is shown.
2687 * @param $lag Integer: slave lag
2689 public function showLagWarning( $lag ) {
2690 global $wgSlaveLagWarning, $wgSlaveLagCritical, $wgLang;
2691 if( $lag >= $wgSlaveLagWarning ) {
2692 $message = $lag < $wgSlaveLagCritical
2693 ? 'lag-warn-normal'
2694 : 'lag-warn-high';
2695 $wrap = Html::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2696 $this->wrapWikiMsg( "$wrap\n", array( $message, $wgLang->formatNum( $lag ) ) );
2701 * Add a wikitext-formatted message to the output.
2702 * This is equivalent to:
2704 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2706 public function addWikiMsg( /*...*/ ) {
2707 $args = func_get_args();
2708 $name = array_shift( $args );
2709 $this->addWikiMsgArray( $name, $args );
2713 * Add a wikitext-formatted message to the output.
2714 * Like addWikiMsg() except the parameters are taken as an array
2715 * instead of a variable argument list.
2717 * $options is passed through to wfMsgExt(), see that function for details.
2719 public function addWikiMsgArray( $name, $args, $options = array() ) {
2720 $options[] = 'parse';
2721 $text = wfMsgExt( $name, $options, $args );
2722 $this->addHTML( $text );
2726 * This function takes a number of message/argument specifications, wraps them in
2727 * some overall structure, and then parses the result and adds it to the output.
2729 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
2730 * on. The subsequent arguments may either be strings, in which case they are the
2731 * message names, or arrays, in which case the first element is the message name,
2732 * and subsequent elements are the parameters to that message.
2734 * The special named parameter 'options' in a message specification array is passed
2735 * through to the $options parameter of wfMsgExt().
2737 * Don't use this for messages that are not in users interface language.
2739 * For example:
2741 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
2743 * Is equivalent to:
2745 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . "\n</div>" );
2747 * The newline after opening div is needed in some wikitext. See bug 19226.
2749 public function wrapWikiMsg( $wrap /*, ...*/ ) {
2750 $msgSpecs = func_get_args();
2751 array_shift( $msgSpecs );
2752 $msgSpecs = array_values( $msgSpecs );
2753 $s = $wrap;
2754 foreach ( $msgSpecs as $n => $spec ) {
2755 $options = array();
2756 if ( is_array( $spec ) ) {
2757 $args = $spec;
2758 $name = array_shift( $args );
2759 if ( isset( $args['options'] ) ) {
2760 $options = $args['options'];
2761 unset( $args['options'] );
2763 } else {
2764 $args = array();
2765 $name = $spec;
2767 $s = str_replace( '$' . ( $n + 1 ), wfMsgExt( $name, $options, $args ), $s );
2769 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );
2773 * Include jQuery core. Use this to avoid loading it multiple times
2774 * before we get a usable script loader.
2776 * @param $modules Array: list of jQuery modules which should be loaded
2777 * @return Array: the list of modules which were not loaded.
2778 * @since 1.16
2779 * @deprecated No longer needed as of 1.17
2781 public function includeJQuery( $modules = array() ) {
2782 return array();