2 if ( !defined( 'MEDIAWIKI' ) ) {
10 var $mMetatags = array(), $mKeywords = array(), $mLinktags = array();
11 var $mExtStyles = array();
12 var $mPagetitle = '', $mBodytext = '';
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();
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;
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();
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' ),
74 * Initialise private variables
76 function __construct() {
77 global $wgAllowUserJs;
78 $this->mAllowUserJs
= $wgAllowUserJs;
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;
94 * Get the URL to redirect to, or an empty string if not redirect URL set
98 public function getRedirect() {
99 return $this->mRedirect
;
103 * Set the HTTP status code to send with the output.
105 * @param $statusCode Integer
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 );
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 );
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
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
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 ) ) {
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.
224 function getScript() {
225 return $this->mScripts
. $this->getHeadItems();
229 * Get the list of modules to include on this page
230 * @return array of module names
232 public function getModules() {
233 return $this->mModules
;
237 * Add one or more modules recognized by the resource loader. Modules added
238 * through this function will be loaded by the resource loader when the
240 * @param $module mixed Module name (string) or array of module names
242 public function addModules( $modules ) {
243 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
247 * Get the list of module JS to include on this page
248 * @return array of module names
250 public function getModuleScripts() {
251 return $this->mModuleScripts
;
255 * Add only JS of one or more modules recognized by the resource loader. Module
256 * scripts added through this function will be loaded by the resource loader when
258 * @param $module mixed Module name (string) or array of module names
260 public function addModuleScripts( $modules ) {
261 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
265 * Get the list of module CSS to include on this page
266 * @return array of module names
268 public function getModuleStyles() {
269 return $this->mModuleStyles
;
273 * Add only CSS of one or more modules recognized by the resource loader. Module
274 * styles added through this function will be loaded by the resource loader when
276 * @param $module mixed Module name (string) or array of module names
278 public function addModuleStyles( $modules ) {
279 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
283 * Get the list of module messages to include on this page
284 * @return array of module names
286 public function getModuleMessages() {
287 return $this->mModuleMessages
;
291 * Add only messages of one or more modules recognized by the resource loader.
292 * Module messages added through this function will be loaded by the resource
293 * loader when the page loads.
294 * @param $module mixed Module name (string) or array of module names
296 public function addModuleMessages( $modules ) {
297 $this->mModuleMessages
= array_merge( $this->mModuleMessages
, (array)$modules );
301 * Get all header items in a string
305 function getHeadItems() {
307 foreach ( $this->mHeadItems
as $item ) {
314 * Add or replace an header item to the output
316 * @param $name String: item name
317 * @param $value String: raw HTML
319 public function addHeadItem( $name, $value ) {
320 $this->mHeadItems
[$name] = $value;
324 * Check if the header item $name is already set
326 * @param $name String: item name
329 public function hasHeadItem( $name ) {
330 return isset( $this->mHeadItems
[$name] );
334 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
336 * @param $tag String: value of "ETag" header
338 function setETag( $tag ) {
343 * Set whether the output should only contain the body of the article,
344 * without any skin, sidebar, etc.
345 * Used e.g. when calling with "action=render".
347 * @param $only Boolean: whether to output only the body of the article
349 public function setArticleBodyOnly( $only ) {
350 $this->mArticleBodyOnly
= $only;
354 * Return whether the output will contain only the body of the article
358 public function getArticleBodyOnly() {
359 return $this->mArticleBodyOnly
;
363 * checkLastModified tells the client to use the client-cached page if
364 * possible. If sucessful, the OutputPage is disabled so that
365 * any future call to OutputPage->output() have no effect.
367 * Side effect: sets mLastModified for Last-Modified header
369 * @return Boolean: true iff cache-ok headers was sent.
371 public function checkLastModified( $timestamp ) {
372 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
374 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
375 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
378 if( !$wgCachePages ) {
379 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
382 if( $wgUser->getOption( 'nocache' ) ) {
383 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
387 $timestamp = wfTimestamp( TS_MW
, $timestamp );
388 $modifiedTimes = array(
389 'page' => $timestamp,
390 'user' => $wgUser->getTouched(),
391 'epoch' => $wgCacheEpoch
393 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
395 $maxModified = max( $modifiedTimes );
396 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
398 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
399 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
405 foreach ( $modifiedTimes as $name => $value ) {
406 if ( $info !== '' ) {
409 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
412 # IE sends sizes after the date like this:
413 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
414 # this breaks strtotime().
415 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
417 wfSuppressWarnings(); // E_STRICT system time bitching
418 $clientHeaderTime = strtotime( $clientHeader );
420 if ( !$clientHeaderTime ) {
421 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
424 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
426 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
427 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
428 wfDebug( __METHOD__
. ": effective Last-Modified: " .
429 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
430 if( $clientHeaderTime < $maxModified ) {
431 wfDebug( __METHOD__
. ": STALE, $info\n", false );
436 # Give a 304 response code and disable body output
437 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
438 ini_set( 'zlib.output_compression', 0 );
439 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
440 $this->sendCacheControl();
443 // Don't output a compressed blob when using ob_gzhandler;
444 // it's technically against HTTP spec and seems to confuse
445 // Firefox when the response gets split over two packets.
446 wfClearOutputBuffers();
452 * Override the last modified timestamp
454 * @param $timestamp String: new timestamp, in a format readable by
457 public function setLastModified( $timestamp ) {
458 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
462 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
464 * @param $policy String: the literal string to output as the contents of
465 * the meta tag. Will be parsed according to the spec and output in
469 public function setRobotPolicy( $policy ) {
470 $policy = Article
::formatRobotPolicy( $policy );
472 if( isset( $policy['index'] ) ) {
473 $this->setIndexPolicy( $policy['index'] );
475 if( isset( $policy['follow'] ) ) {
476 $this->setFollowPolicy( $policy['follow'] );
481 * Set the index policy for the page, but leave the follow policy un-
484 * @param $policy string Either 'index' or 'noindex'.
487 public function setIndexPolicy( $policy ) {
488 $policy = trim( $policy );
489 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
490 $this->mIndexPolicy
= $policy;
495 * Set the follow policy for the page, but leave the index policy un-
498 * @param $policy String: either 'follow' or 'nofollow'.
501 public function setFollowPolicy( $policy ) {
502 $policy = trim( $policy );
503 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
504 $this->mFollowPolicy
= $policy;
509 * Set the new value of the "action text", this will be added to the
510 * "HTML title", separated from it with " - ".
512 * @param $text String: new value of the "action text"
514 public function setPageTitleActionText( $text ) {
515 $this->mPageTitleActionText
= $text;
519 * Get the value of the "action text"
523 public function getPageTitleActionText() {
524 if ( isset( $this->mPageTitleActionText
) ) {
525 return $this->mPageTitleActionText
;
530 * "HTML title" means the contents of <title>.
531 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
533 public function setHTMLTitle( $name ) {
534 $this->mHTMLtitle
= $name;
538 * Return the "HTML title", i.e. the content of the <title> tag.
542 public function getHTMLTitle() {
543 return $this->mHTMLtitle
;
547 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
548 * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
549 * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
550 * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
552 public function setPageTitle( $name ) {
553 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
554 # but leave "<i>foobar</i>" alone
555 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
556 $this->mPagetitle
= $nameWithTags;
558 $taction = $this->getPageTitleActionText();
559 if( !empty( $taction ) ) {
560 $name .= ' - '.$taction;
563 # change "<i>foo&bar</i>" to "foo&bar"
564 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer
::stripAllTags( $nameWithTags ) ) );
568 * Return the "page title", i.e. the content of the \<h1\> tag.
572 public function getPageTitle() {
573 return $this->mPagetitle
;
577 * Set the Title object to use
579 * @param $t Title object
581 public function setTitle( $t ) {
586 * Get the Title object used in this instance
590 public function getTitle() {
591 if ( $this->mTitle
instanceof Title
) {
592 return $this->mTitle
;
594 wfDebug( __METHOD__
. " called and \$mTitle is null. Return \$wgTitle for sanity\n" );
601 * Replace the subtile with $str
603 * @param $str String: new value of the subtitle
605 public function setSubtitle( $str ) {
606 $this->mSubtitle
= /*$this->parse(*/ $str /*)*/; // @bug 2514
610 * Add $str to the subtitle
612 * @param $str String to add to the subtitle
614 public function appendSubtitle( $str ) {
615 $this->mSubtitle
.= /*$this->parse(*/ $str /*)*/; // @bug 2514
623 public function getSubtitle() {
624 return $this->mSubtitle
;
628 * Set the page as printable, i.e. it'll be displayed with with all
629 * print styles included
631 public function setPrintable() {
632 $this->mPrintable
= true;
636 * Return whether the page is "printable"
640 public function isPrintable() {
641 return $this->mPrintable
;
645 * Disable output completely, i.e. calling output() will have no effect
647 public function disable() {
648 $this->mDoNothing
= true;
652 * Return whether the output will be completely disabled
656 public function isDisabled() {
657 return $this->mDoNothing
;
661 * Show an "add new section" link?
665 public function showNewSectionLink() {
666 return $this->mNewSectionLink
;
670 * Forcibly hide the new section link?
674 public function forceHideNewSectionLink() {
675 return $this->mHideNewSectionLink
;
679 * Add or remove feed links in the page header
680 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
681 * for the new version
684 * @param $show Boolean: true: add default feeds, false: remove all feeds
686 public function setSyndicated( $show = true ) {
688 $this->setFeedAppendQuery( false );
690 $this->mFeedLinks
= array();
695 * Add default feeds to the page header
696 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
697 * for the new version
700 * @param $val String: query to append to feed links or false to output
703 public function setFeedAppendQuery( $val ) {
704 global $wgAdvertisedFeedTypes;
706 $this->mFeedLinks
= array();
708 foreach ( $wgAdvertisedFeedTypes as $type ) {
709 $query = "feed=$type";
710 if ( is_string( $val ) ) {
711 $query .= '&' . $val;
713 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
718 * Add a feed link to the page header
720 * @param $format String: feed type, should be a key of $wgFeedClasses
721 * @param $href String: URL
723 public function addFeedLink( $format, $href ) {
724 global $wgAdvertisedFeedTypes;
726 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
727 $this->mFeedLinks
[$format] = $href;
732 * Should we output feed links for this page?
735 public function isSyndicated() {
736 return count( $this->mFeedLinks
) > 0;
740 * Return URLs for each supported syndication format for this page.
741 * @return array associating format keys with URLs
743 public function getSyndicationLinks() {
744 return $this->mFeedLinks
;
748 * Will currently always return null
752 public function getFeedAppendQuery() {
753 return $this->mFeedLinksAppendQuery
;
757 * Set whether the displayed content is related to the source of the
758 * corresponding article on the wiki
759 * Setting true will cause the change "article related" toggle to true
763 public function setArticleFlag( $v ) {
764 $this->mIsarticle
= $v;
766 $this->mIsArticleRelated
= $v;
771 * Return whether the content displayed page is related to the source of
772 * the corresponding article on the wiki
776 public function isArticle() {
777 return $this->mIsarticle
;
781 * Set whether this page is related an article on the wiki
782 * Setting false will cause the change of "article flag" toggle to false
786 public function setArticleRelated( $v ) {
787 $this->mIsArticleRelated
= $v;
789 $this->mIsarticle
= false;
794 * Return whether this page is related an article on the wiki
798 public function isArticleRelated() {
799 return $this->mIsArticleRelated
;
803 * Add new language links
805 * @param $newLinkArray Associative array mapping language code to the page
808 public function addLanguageLinks( $newLinkArray ) {
809 $this->mLanguageLinks +
= $newLinkArray;
813 * Reset the language links and add new language links
815 * @param $newLinkArray Associative array mapping language code to the page
818 public function setLanguageLinks( $newLinkArray ) {
819 $this->mLanguageLinks
= $newLinkArray;
823 * Get the list of language links
825 * @return Associative array mapping language code to the page name
827 public function getLanguageLinks() {
828 return $this->mLanguageLinks
;
832 * Add an array of categories, with names in the keys
834 * @param $categories Associative array mapping category name to its sort key
836 public function addCategoryLinks( $categories ) {
837 global $wgUser, $wgContLang;
839 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
843 # Add the links to a LinkBatch
844 $arr = array( NS_CATEGORY
=> $categories );
846 $lb->setArray( $arr );
848 # Fetch existence plus the hiddencat property
849 $dbr = wfGetDB( DB_SLAVE
);
850 $pageTable = $dbr->tableName( 'page' );
851 $where = $lb->constructSet( 'page', $dbr );
852 $propsTable = $dbr->tableName( 'page_props' );
853 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, page_latest, pp_value
854 FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
855 $res = $dbr->query( $sql, __METHOD__
);
857 # Add the results to the link cache
858 $lb->addResultToCache( LinkCache
::singleton(), $res );
860 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
861 $categories = array_combine(
862 array_keys( $categories ),
863 array_fill( 0, count( $categories ), 'normal' )
866 # Mark hidden categories
867 foreach ( $res as $row ) {
868 if ( isset( $row->pp_value
) ) {
869 $categories[$row->page_title
] = 'hidden';
873 # Add the remaining categories to the skin
874 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
875 $sk = $wgUser->getSkin();
876 foreach ( $categories as $category => $type ) {
877 $origcategory = $category;
878 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
879 $wgContLang->findVariantLink( $category, $title, true );
880 if ( $category != $origcategory ) {
881 if ( array_key_exists( $category, $categories ) ) {
885 $text = $wgContLang->convertHtml( $title->getText() );
886 $this->mCategories
[] = $title->getText();
887 $this->mCategoryLinks
[$type][] = $sk->link( $title, $text );
893 * Reset the category links (but not the category list) and add $categories
895 * @param $categories Associative array mapping category name to its sort key
897 public function setCategoryLinks( $categories ) {
898 $this->mCategoryLinks
= array();
899 $this->addCategoryLinks( $categories );
903 * Get the list of category links, in a 2-D array with the following format:
904 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
905 * hidden categories) and $link a HTML fragment with a link to the category
910 public function getCategoryLinks() {
911 return $this->mCategoryLinks
;
915 * Get the list of category names this page belongs to
917 * @return Array of strings
919 public function getCategories() {
920 return $this->mCategories
;
924 * Suppress the quickbar from the output, only for skin supporting
927 public function suppressQuickbar() {
928 $this->mSuppressQuickbar
= true;
932 * Return whether the quickbar should be suppressed from the output
936 public function isQuickbarSuppressed() {
937 return $this->mSuppressQuickbar
;
941 * Remove user JavaScript from scripts to load
943 public function disallowUserJs() {
944 $this->mAllowUserJs
= false;
948 * Return whether user JavaScript is allowed for this page
952 public function isUserJsAllowed() {
953 return $this->mAllowUserJs
;
957 * Prepend $text to the body HTML
959 * @param $text String: HTML
961 public function prependHTML( $text ) {
962 $this->mBodytext
= $text . $this->mBodytext
;
966 * Append $text to the body HTML
968 * @param $text String: HTML
970 public function addHTML( $text ) {
971 $this->mBodytext
.= $text;
975 * Clear the body HTML
977 public function clearHTML() {
978 $this->mBodytext
= '';
984 * @return String: HTML
986 public function getHTML() {
987 return $this->mBodytext
;
991 * Add $text to the debug output
993 * @param $text String: debug text
995 public function debug( $text ) {
996 $this->mDebugtext
.= $text;
1000 * @deprecated use parserOptions() instead
1002 public function setParserOptions( $options ) {
1003 wfDeprecated( __METHOD__
);
1004 return $this->parserOptions( $options );
1008 * Get/set the ParserOptions object to use for wikitext parsing
1010 * @param $options either the ParserOption to use or null to only get the
1011 * current ParserOption object
1012 * @return current ParserOption object
1014 public function parserOptions( $options = null ) {
1015 if ( !$this->mParserOptions
) {
1016 $this->mParserOptions
= new ParserOptions
;
1018 return wfSetVar( $this->mParserOptions
, $options );
1022 * Set the revision ID which will be seen by the wiki text parser
1023 * for things such as embedded {{REVISIONID}} variable use.
1025 * @param $revid Mixed: an positive integer, or null
1026 * @return Mixed: previous value
1028 public function setRevisionId( $revid ) {
1029 $val = is_null( $revid ) ?
null : intval( $revid );
1030 return wfSetVar( $this->mRevisionId
, $val );
1034 * Get the current revision ID
1038 public function getRevisionId() {
1039 return $this->mRevisionId
;
1043 * Convert wikitext to HTML and add it to the buffer
1044 * Default assumes that the current page title will be used.
1046 * @param $text String
1047 * @param $linestart Boolean: is this the start of a line?
1049 public function addWikiText( $text, $linestart = true ) {
1050 $title = $this->getTitle(); // Work arround E_STRICT
1051 $this->addWikiTextTitle( $text, $title, $linestart );
1055 * Add wikitext with a custom Title object
1057 * @param $text String: wikitext
1058 * @param $title Title object
1059 * @param $linestart Boolean: is this the start of a line?
1061 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1062 $this->addWikiTextTitle( $text, $title, $linestart );
1066 * Add wikitext with a custom Title object and
1068 * @param $text String: wikitext
1069 * @param $title Title object
1070 * @param $linestart Boolean: is this the start of a line?
1072 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1073 $this->addWikiTextTitle( $text, $title, $linestart, true );
1077 * Add wikitext with tidy enabled
1079 * @param $text String: wikitext
1080 * @param $linestart Boolean: is this the start of a line?
1082 public function addWikiTextTidy( $text, $linestart = true ) {
1083 $title = $this->getTitle();
1084 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1088 * Add wikitext with a custom Title object
1090 * @param $text String: wikitext
1091 * @param $title Title object
1092 * @param $linestart Boolean: is this the start of a line?
1093 * @param $tidy Boolean: whether to use tidy
1095 public function addWikiTextTitle( $text, &$title, $linestart, $tidy = false ) {
1098 wfProfileIn( __METHOD__
);
1100 wfIncrStats( 'pcache_not_possible' );
1102 $popts = $this->parserOptions();
1103 $oldTidy = $popts->setTidy( $tidy );
1105 $parserOutput = $wgParser->parse(
1106 $text, $title, $popts,
1107 $linestart, true, $this->mRevisionId
1110 $popts->setTidy( $oldTidy );
1112 $this->addParserOutput( $parserOutput );
1114 wfProfileOut( __METHOD__
);
1118 * Add wikitext to the buffer, assuming that this is the primary text for a page view
1119 * Saves the text into the parser cache if possible.
1121 * @param $text String: wikitext
1122 * @param $article Article object
1123 * @param $cache Boolean
1124 * @deprecated Use Article::outputWikitext
1126 public function addPrimaryWikiText( $text, $article, $cache = true ) {
1129 wfDeprecated( __METHOD__
);
1131 $popts = $this->parserOptions();
1132 $popts->setTidy( true );
1133 $parserOutput = $wgParser->parse(
1134 $text, $article->mTitle
,
1135 $popts, true, true, $this->mRevisionId
1137 $popts->setTidy( false );
1138 if ( $cache && $article && $parserOutput->isCacheable() ) {
1139 $parserCache = ParserCache
::singleton();
1140 $parserCache->save( $parserOutput, $article, $popts );
1143 $this->addParserOutput( $parserOutput );
1147 * @deprecated use addWikiTextTidy()
1149 public function addSecondaryWikiText( $text, $linestart = true ) {
1150 wfDeprecated( __METHOD__
);
1151 $this->addWikiTextTitleTidy( $text, $this->getTitle(), $linestart );
1155 * Add a ParserOutput object, but without Html
1157 * @param $parserOutput ParserOutput object
1159 public function addParserOutputNoText( &$parserOutput ) {
1160 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1161 $this->addCategoryLinks( $parserOutput->getCategories() );
1162 $this->mNewSectionLink
= $parserOutput->getNewSection();
1163 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1165 $this->mParseWarnings
= $parserOutput->getWarnings();
1166 if ( !$parserOutput->isCacheable() ) {
1167 $this->enableClientCache( false );
1169 $this->mNoGallery
= $parserOutput->getNoGallery();
1170 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1171 $this->addModules( $parserOutput->getModules() );
1173 foreach ( (array)$parserOutput->mTemplateIds
as $ns => $dbks ) {
1174 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1175 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1177 $this->mTemplateIds
[$ns] = $dbks;
1181 // Hooks registered in the object
1182 global $wgParserOutputHooks;
1183 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1184 list( $hookName, $data ) = $hookInfo;
1185 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1186 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1190 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1194 * Add a ParserOutput object
1196 * @param $parserOutput ParserOutput
1198 function addParserOutput( &$parserOutput ) {
1199 $this->addParserOutputNoText( $parserOutput );
1200 $text = $parserOutput->getText();
1201 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1202 $this->addHTML( $text );
1207 * Add the output of a QuickTemplate to the output buffer
1209 * @param $template QuickTemplate
1211 public function addTemplate( &$template ) {
1213 $template->execute();
1214 $this->addHTML( ob_get_contents() );
1219 * Parse wikitext and return the HTML.
1221 * @param $text String
1222 * @param $linestart Boolean: is this the start of a line?
1223 * @param $interface Boolean: use interface language ($wgLang instead of
1224 * $wgContLang) while parsing language sensitive magic
1225 * words like GRAMMAR and PLURAL
1226 * @return String: HTML
1228 public function parse( $text, $linestart = true, $interface = false ) {
1230 if( is_null( $this->getTitle() ) ) {
1231 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1233 $popts = $this->parserOptions();
1235 $popts->setInterfaceMessage( true );
1237 $parserOutput = $wgParser->parse(
1238 $text, $this->getTitle(), $popts,
1239 $linestart, true, $this->mRevisionId
1242 $popts->setInterfaceMessage( false );
1244 return $parserOutput->getText();
1248 * Parse wikitext, strip paragraphs, and return the HTML.
1250 * @param $text String
1251 * @param $linestart Boolean: is this the start of a line?
1252 * @param $interface Boolean: use interface language ($wgLang instead of
1253 * $wgContLang) while parsing language sensitive magic
1254 * words like GRAMMAR and PLURAL
1255 * @return String: HTML
1257 public function parseInline( $text, $linestart = true, $interface = false ) {
1258 $parsed = $this->parse( $text, $linestart, $interface );
1261 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1271 * @param $article Article
1272 * @return Boolean: true if successful, else false.
1274 public function tryParserCache( &$article ) {
1275 wfDeprecated( __METHOD__
);
1276 $parserOutput = ParserCache
::singleton()->get( $article, $article->getParserOptions() );
1278 if ( $parserOutput !== false ) {
1279 $this->addParserOutput( $parserOutput );
1287 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1289 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1291 public function setSquidMaxage( $maxage ) {
1292 $this->mSquidMaxage
= $maxage;
1296 * Use enableClientCache(false) to force it to send nocache headers
1300 public function enableClientCache( $state ) {
1301 return wfSetVar( $this->mEnableClientCache
, $state );
1305 * Get the list of cookies that will influence on the cache
1309 function getCacheVaryCookies() {
1310 global $wgCookiePrefix, $wgCacheVaryCookies;
1312 if ( $cookies === null ) {
1313 $cookies = array_merge(
1315 "{$wgCookiePrefix}Token",
1316 "{$wgCookiePrefix}LoggedOut",
1321 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1327 * Return whether this page is not cacheable because "useskin" or "uselang"
1328 * URL parameters were passed.
1332 function uncacheableBecauseRequestVars() {
1334 return $wgRequest->getText( 'useskin', false ) === false
1335 && $wgRequest->getText( 'uselang', false ) === false;
1339 * Check if the request has a cache-varying cookie header
1340 * If it does, it's very important that we don't allow public caching
1344 function haveCacheVaryCookies() {
1346 $cookieHeader = $wgRequest->getHeader( 'cookie' );
1347 if ( $cookieHeader === false ) {
1350 $cvCookies = $this->getCacheVaryCookies();
1351 foreach ( $cvCookies as $cookieName ) {
1352 # Check for a simple string match, like the way squid does it
1353 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1354 wfDebug( __METHOD__
. ": found $cookieName\n" );
1358 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1363 * Add an HTTP header that will influence on the cache
1365 * @param $header String: header name
1366 * @param $option either an Array or null
1368 public function addVaryHeader( $header, $option = null ) {
1369 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1370 $this->mVaryHeader
[$header] = $option;
1371 } elseif( is_array( $option ) ) {
1372 if( is_array( $this->mVaryHeader
[$header] ) ) {
1373 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
1375 $this->mVaryHeader
[$header] = $option;
1378 $this->mVaryHeader
[$header] = array_unique( $this->mVaryHeader
[$header] );
1382 * Get a complete X-Vary-Options header
1386 public function getXVO() {
1387 $cvCookies = $this->getCacheVaryCookies();
1389 $cookiesOption = array();
1390 foreach ( $cvCookies as $cookieName ) {
1391 $cookiesOption[] = 'string-contains=' . $cookieName;
1393 $this->addVaryHeader( 'Cookie', $cookiesOption );
1396 foreach( $this->mVaryHeader
as $header => $option ) {
1397 $newheader = $header;
1398 if( is_array( $option ) ) {
1399 $newheader .= ';' . implode( ';', $option );
1401 $headers[] = $newheader;
1403 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1409 * bug 21672: Add Accept-Language to Vary and XVO headers
1410 * if there's no 'variant' parameter existed in GET.
1413 * /w/index.php?title=Main_page should always be served; but
1414 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1416 function addAcceptLanguage() {
1417 global $wgRequest, $wgContLang;
1418 if( !$wgRequest->getCheck( 'variant' ) && $wgContLang->hasVariants() ) {
1419 $variants = $wgContLang->getVariants();
1420 $aloption = array();
1421 foreach ( $variants as $variant ) {
1422 if( $variant === $wgContLang->getCode() ) {
1425 $aloption[] = "string-contains=$variant";
1428 $this->addVaryHeader( 'Accept-Language', $aloption );
1433 * Send cache control HTTP headers
1435 public function sendCacheControl() {
1436 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest, $wgUseXVO;
1438 $response = $wgRequest->response();
1439 if ( $wgUseETag && $this->mETag
) {
1440 $response->header( "ETag: $this->mETag" );
1443 $this->addAcceptLanguage();
1445 # don't serve compressed data to clients who can't handle it
1446 # maintain different caches for logged-in users and non-logged in ones
1447 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) ) );
1450 # Add an X-Vary-Options header for Squid with Wikimedia patches
1451 $response->header( $this->getXVO() );
1454 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
1456 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1457 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
1461 # We'll purge the proxy cache explicitly, but require end user agents
1462 # to revalidate against the proxy on each visit.
1463 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1464 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1465 # start with a shorter timeout for initial testing
1466 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1467 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
1468 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1470 # We'll purge the proxy cache for anons explicitly, but require end user agents
1471 # to revalidate against the proxy on each visit.
1472 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1473 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1474 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
1475 # start with a shorter timeout for initial testing
1476 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1477 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
1480 # We do want clients to cache if they can, but they *must* check for updates
1481 # on revisiting the page.
1482 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
1483 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1484 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1486 if($this->mLastModified
) {
1487 $response->header( "Last-Modified: {$this->mLastModified}" );
1490 wfDebug( __METHOD__
. ": no caching **\n", false );
1492 # In general, the absence of a last modified header should be enough to prevent
1493 # the client from using its cache. We send a few other things just to make sure.
1494 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1495 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1496 $response->header( 'Pragma: no-cache' );
1501 * Get the message associed with the HTTP response code $code
1503 * @param $code Integer: status code
1504 * @return String or null: message or null if $code is not in the list of
1507 public static function getStatusMessage( $code ) {
1508 static $statusMessage = array(
1510 101 => 'Switching Protocols',
1511 102 => 'Processing',
1515 203 => 'Non-Authoritative Information',
1516 204 => 'No Content',
1517 205 => 'Reset Content',
1518 206 => 'Partial Content',
1519 207 => 'Multi-Status',
1520 300 => 'Multiple Choices',
1521 301 => 'Moved Permanently',
1524 304 => 'Not Modified',
1526 307 => 'Temporary Redirect',
1527 400 => 'Bad Request',
1528 401 => 'Unauthorized',
1529 402 => 'Payment Required',
1532 405 => 'Method Not Allowed',
1533 406 => 'Not Acceptable',
1534 407 => 'Proxy Authentication Required',
1535 408 => 'Request Timeout',
1538 411 => 'Length Required',
1539 412 => 'Precondition Failed',
1540 413 => 'Request Entity Too Large',
1541 414 => 'Request-URI Too Large',
1542 415 => 'Unsupported Media Type',
1543 416 => 'Request Range Not Satisfiable',
1544 417 => 'Expectation Failed',
1545 422 => 'Unprocessable Entity',
1547 424 => 'Failed Dependency',
1548 500 => 'Internal Server Error',
1549 501 => 'Not Implemented',
1550 502 => 'Bad Gateway',
1551 503 => 'Service Unavailable',
1552 504 => 'Gateway Timeout',
1553 505 => 'HTTP Version Not Supported',
1554 507 => 'Insufficient Storage'
1556 return isset( $statusMessage[$code] ) ?
$statusMessage[$code] : null;
1560 * Finally, all the text has been munged and accumulated into
1561 * the object, let's actually output it:
1563 public function output() {
1564 global $wgUser, $wgOutputEncoding, $wgRequest;
1565 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
1566 global $wgUseAjax, $wgAjaxWatch;
1567 global $wgEnableMWSuggest, $wgUniversalEditButton;
1568 global $wgArticle, $wgJQueryOnEveryPage;
1570 if( $this->mDoNothing
) {
1573 wfProfileIn( __METHOD__
);
1574 if ( $this->mRedirect
!= '' ) {
1575 # Standards require redirect URLs to be absolute
1576 $this->mRedirect
= wfExpandUrl( $this->mRedirect
);
1577 if( $this->mRedirectCode
== '301' ||
$this->mRedirectCode
== '303' ) {
1578 if( !$wgDebugRedirects ) {
1579 $message = self
::getStatusMessage( $this->mRedirectCode
);
1580 $wgRequest->response()->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
1582 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1584 $this->sendCacheControl();
1586 $wgRequest->response()->header( "Content-Type: text/html; charset=utf-8" );
1587 if( $wgDebugRedirects ) {
1588 $url = htmlspecialchars( $this->mRedirect
);
1589 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1590 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1591 print "</body>\n</html>\n";
1593 $wgRequest->response()->header( 'Location: ' . $this->mRedirect
);
1595 wfProfileOut( __METHOD__
);
1597 } elseif ( $this->mStatusCode
) {
1598 $message = self
::getStatusMessage( $this->mStatusCode
);
1600 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
1604 $sk = $wgUser->getSkin();
1606 // Add base resources
1607 $this->addModules( array( 'mediawiki.legacy.wikibits' ) );
1609 // Add various resources if required
1611 $this->addModules( 'mediawiki.legacy.ajax' );
1613 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1615 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1616 $this->addModules( 'mediawiki.legacy.ajaxwatch' );
1619 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ) {
1620 $this->addModules( 'mediawiki.legacy.mwsuggest' );
1624 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1625 $this->addModules( 'mediawiki.legacy.rightclickedit' );
1628 if( $wgUniversalEditButton ) {
1629 if( isset( $wgArticle ) && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1630 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create' ) ) ) {
1631 // Original UniversalEditButton
1632 $msg = wfMsg( 'edit' );
1633 $this->addLink( array(
1634 'rel' => 'alternate',
1635 'type' => 'application/x-wiki',
1637 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1639 // Alternate edit link
1640 $this->addLink( array(
1643 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1649 # Buffer output; final headers may depend on later processing
1652 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1653 $wgRequest->response()->header( 'Content-language: ' . $wgContLanguageCode );
1655 if ( $this->mArticleBodyOnly
) {
1656 $this->out( $this->mBodytext
);
1658 // Hook that allows last minute changes to the output page, e.g.
1659 // adding of CSS or Javascript by extensions.
1660 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1662 wfProfileIn( 'Output-skin' );
1663 $sk->outputPage( $this );
1664 wfProfileOut( 'Output-skin' );
1667 $this->sendCacheControl();
1669 wfProfileOut( __METHOD__
);
1673 * Actually output something with print(). Performs an iconv to the
1674 * output encoding, if needed.
1676 * @param $ins String: the string to output
1678 public function out( $ins ) {
1679 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1680 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1683 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1684 if ( false === $outs ) {
1694 public static function setEncodings() {
1695 global $wgInputEncoding, $wgOutputEncoding;
1697 $wgInputEncoding = strtolower( $wgInputEncoding );
1699 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
1700 $wgOutputEncoding = strtolower( $wgOutputEncoding );
1703 $wgOutputEncoding = $wgInputEncoding;
1707 * @deprecated use wfReportTime() instead.
1711 public function reportTime() {
1712 wfDeprecated( __METHOD__
);
1713 $time = wfReportTime();
1718 * Produce a "user is blocked" page.
1720 * @param $return Boolean: whether to have a "return to $wgTitle" message or not.
1723 function blockedPage( $return = true ) {
1724 global $wgUser, $wgContLang, $wgLang;
1726 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1727 $this->setRobotPolicy( 'noindex,nofollow' );
1728 $this->setArticleRelated( false );
1730 $name = User
::whoIs( $wgUser->blockedBy() );
1731 $reason = $wgUser->blockedFor();
1732 if( $reason == '' ) {
1733 $reason = wfMsg( 'blockednoreason' );
1735 $blockTimestamp = $wgLang->timeanddate(
1736 wfTimestamp( TS_MW
, $wgUser->mBlock
->mTimestamp
), true
1740 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1742 $blockid = $wgUser->mBlock
->mId
;
1744 $blockExpiry = $wgUser->mBlock
->mExpiry
;
1745 if ( $blockExpiry == 'infinity' ) {
1746 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1747 // Search for localization in 'ipboptions'
1748 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1749 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1750 if ( strpos( $option, ':' ) === false ) {
1753 list( $show, $value ) = explode( ':', $option );
1754 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1755 $blockExpiry = $show;
1760 $blockExpiry = $wgLang->timeanddate(
1761 wfTimestamp( TS_MW
, $blockExpiry ),
1766 if ( $wgUser->mBlock
->mAuto
) {
1767 $msg = 'autoblockedtext';
1769 $msg = 'blockedtext';
1772 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1773 * This could be a username, an IP range, or a single IP. */
1774 $intended = $wgUser->mBlock
->mAddress
;
1777 $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry,
1778 $intended, $blockTimestamp
1781 # Don't auto-return to special pages
1783 $return = $this->getTitle()->getNamespace() > -1 ?
$this->getTitle() : null;
1784 $this->returnToMain( null, $return );
1789 * Output a standard error page
1791 * @param $title String: message key for page title
1792 * @param $msg String: message key for page text
1793 * @param $params Array: message parameters
1795 public function showErrorPage( $title, $msg, $params = array() ) {
1796 if ( $this->getTitle() ) {
1797 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1799 $this->setPageTitle( wfMsg( $title ) );
1800 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1801 $this->setRobotPolicy( 'noindex,nofollow' );
1802 $this->setArticleRelated( false );
1803 $this->enableClientCache( false );
1804 $this->mRedirect
= '';
1805 $this->mBodytext
= '';
1807 array_unshift( $params, 'parse' );
1808 array_unshift( $params, $msg );
1809 $this->addHTML( call_user_func_array( 'wfMsgExt', $params ) );
1811 $this->returnToMain();
1815 * Output a standard permission error page
1817 * @param $errors Array: error message keys
1818 * @param $action String: action that was denied or null if unknown
1820 public function showPermissionsErrorPage( $errors, $action = null ) {
1821 $this->mDebugtext
.= 'Original title: ' .
1822 $this->getTitle()->getPrefixedText() . "\n";
1823 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1824 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1825 $this->setRobotPolicy( 'noindex,nofollow' );
1826 $this->setArticleRelated( false );
1827 $this->enableClientCache( false );
1828 $this->mRedirect
= '';
1829 $this->mBodytext
= '';
1830 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1834 * Display an error page indicating that a given version of MediaWiki is
1835 * required to use it
1837 * @param $version Mixed: the version of MediaWiki needed to use the page
1839 public function versionRequired( $version ) {
1840 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1841 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1842 $this->setRobotPolicy( 'noindex,nofollow' );
1843 $this->setArticleRelated( false );
1844 $this->mBodytext
= '';
1846 $this->addWikiMsg( 'versionrequiredtext', $version );
1847 $this->returnToMain();
1851 * Display an error page noting that a given permission bit is required.
1853 * @param $permission String: key required
1855 public function permissionRequired( $permission ) {
1858 $this->setPageTitle( wfMsg( 'badaccess' ) );
1859 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1860 $this->setRobotPolicy( 'noindex,nofollow' );
1861 $this->setArticleRelated( false );
1862 $this->mBodytext
= '';
1864 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1865 User
::getGroupsWithPermission( $permission ) );
1869 $wgLang->commaList( $groups ),
1873 $this->addWikiMsg( 'badaccess-group0' );
1875 $this->returnToMain();
1879 * Produce the stock "please login to use the wiki" page
1881 public function loginToUse() {
1884 if( $wgUser->isLoggedIn() ) {
1885 $this->permissionRequired( 'read' );
1889 $skin = $wgUser->getSkin();
1891 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1892 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1893 $this->setRobotPolicy( 'noindex,nofollow' );
1894 $this->setArticleFlag( false );
1896 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1897 $loginLink = $skin->link(
1899 wfMsgHtml( 'loginreqlink' ),
1901 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
1902 array( 'known', 'noclasses' )
1904 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1905 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . '-->' );
1907 # Don't return to the main page if the user can't read it
1908 # otherwise we'll end up in a pointless loop
1909 $mainPage = Title
::newMainPage();
1910 if( $mainPage->userCanRead() ) {
1911 $this->returnToMain( null, $mainPage );
1916 * Format a list of error messages
1918 * @param $errors An array of arrays returned by Title::getUserPermissionsErrors
1919 * @param $action String: action that was denied or null if unknown
1920 * @return String: the wikitext error-messages, formatted into a list.
1922 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1923 if ( $action == null ) {
1924 $text = wfMsgNoTrans( 'permissionserrorstext', count( $errors ) ) . "\n\n";
1926 $action_desc = wfMsgNoTrans( "action-$action" );
1927 $text = wfMsgNoTrans(
1928 'permissionserrorstext-withaction',
1934 if ( count( $errors ) > 1 ) {
1935 $text .= '<ul class="permissions-errors">' . "\n";
1937 foreach( $errors as $error ) {
1939 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1944 $text .= "<div class=\"permissions-errors\">\n" .
1945 call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) .
1953 * Display a page stating that the Wiki is in read-only mode,
1954 * and optionally show the source of the page that the user
1955 * was trying to edit. Should only be called (for this
1956 * purpose) after wfReadOnly() has returned true.
1958 * For historical reasons, this function is _also_ used to
1959 * show the error message when a user tries to edit a page
1960 * they are not allowed to edit. (Unless it's because they're
1961 * blocked, then we show blockedPage() instead.) In this
1962 * case, the second parameter should be set to true and a list
1963 * of reasons supplied as the third parameter.
1965 * @todo Needs to be split into multiple functions.
1967 * @param $source String: source code to show (or null).
1968 * @param $protected Boolean: is this a permissions error?
1969 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
1970 * @param $action String: action that was denied or null if unknown
1972 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1974 $skin = $wgUser->getSkin();
1976 $this->setRobotPolicy( 'noindex,nofollow' );
1977 $this->setArticleRelated( false );
1979 // If no reason is given, just supply a default "I can't let you do
1980 // that, Dave" message. Should only occur if called by legacy code.
1981 if ( $protected && empty( $reasons ) ) {
1982 $reasons[] = array( 'badaccess-group0' );
1985 if ( !empty( $reasons ) ) {
1986 // Permissions error
1988 $this->setPageTitle( wfMsg( 'viewsource' ) );
1990 wfMsg( 'viewsourcefor', $skin->linkKnown( $this->getTitle() ) )
1993 $this->setPageTitle( wfMsg( 'badaccess' ) );
1995 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1997 // Wiki is read only
1998 $this->setPageTitle( wfMsg( 'readonly' ) );
1999 $reason = wfReadOnlyReason();
2000 $this->wrapWikiMsg( "<div class='mw-readonly-error'>\n$1\n</div>", array( 'readonlytext', $reason ) );
2003 // Show source, if supplied
2004 if( is_string( $source ) ) {
2005 $this->addWikiMsg( 'viewsourcetext' );
2008 'id' => 'wpTextbox1',
2009 'name' => 'wpTextbox1',
2010 'cols' => $wgUser->getOption( 'cols' ),
2011 'rows' => $wgUser->getOption( 'rows' ),
2012 'readonly' => 'readonly'
2014 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
2016 // Show templates used by this article
2017 $skin = $wgUser->getSkin();
2018 $article = new Article( $this->getTitle() );
2019 $this->addHTML( "<div class='templatesUsed'>
2020 {$skin->formatTemplates( $article->getUsedTemplates() )}
2025 # If the title doesn't exist, it's fairly pointless to print a return
2026 # link to it. After all, you just tried editing it and couldn't, so
2027 # what's there to do there?
2028 if( $this->getTitle()->exists() ) {
2029 $this->returnToMain( null, $this->getTitle() );
2034 * Adds JS-based password security checker
2035 * @param $passwordId String ID of input box containing password
2036 * @param $retypeId String ID of input box containing retyped password
2039 public function addPasswordSecurity( $passwordId, $retypeId ) {
2040 $this->includeJQuery();
2042 'password' => '#' . $passwordId,
2043 'retype' => '#' . $retypeId,
2044 'messages' => array(),
2046 foreach ( array( 'password-strength', 'password-strength-bad', 'password-strength-mediocre',
2047 'password-strength-acceptable', 'password-strength-good', 'password-retype', 'password-retype-mismatch'
2049 $data['messages'][$message] = wfMsg( $message );
2051 $this->addScript( Html
::inlineScript( 'var passwordSecurity=' . FormatJson
::encode( $data ) ) );
2052 $this->addModules( 'mediawiki.legacy.password' );
2056 public function errorpage( $title, $msg ) {
2057 wfDeprecated( __METHOD__
);
2058 throw new ErrorPageError( $title, $msg );
2062 public function databaseError( $fname, $sql, $error, $errno ) {
2063 throw new MWException( "OutputPage::databaseError is obsolete\n" );
2067 public function fatalError( $message ) {
2068 wfDeprecated( __METHOD__
);
2069 throw new FatalError( $message );
2073 public function unexpectedValueError( $name, $val ) {
2074 wfDeprecated( __METHOD__
);
2075 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
2079 public function fileCopyError( $old, $new ) {
2080 wfDeprecated( __METHOD__
);
2081 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
2085 public function fileRenameError( $old, $new ) {
2086 wfDeprecated( __METHOD__
);
2087 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
2091 public function fileDeleteError( $name ) {
2092 wfDeprecated( __METHOD__
);
2093 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
2097 public function fileNotFoundError( $name ) {
2098 wfDeprecated( __METHOD__
);
2099 throw new FatalError( wfMsg( 'filenotfound', $name ) );
2102 public function showFatalError( $message ) {
2103 $this->setPageTitle( wfMsg( 'internalerror' ) );
2104 $this->setRobotPolicy( 'noindex,nofollow' );
2105 $this->setArticleRelated( false );
2106 $this->enableClientCache( false );
2107 $this->mRedirect
= '';
2108 $this->mBodytext
= $message;
2111 public function showUnexpectedValueError( $name, $val ) {
2112 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
2115 public function showFileCopyError( $old, $new ) {
2116 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
2119 public function showFileRenameError( $old, $new ) {
2120 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
2123 public function showFileDeleteError( $name ) {
2124 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
2127 public function showFileNotFoundError( $name ) {
2128 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
2132 * Add a "return to" link pointing to a specified title
2134 * @param $title Title to link
2135 * @param $query String: query string
2136 * @param $text String text of the link (input is not escaped)
2138 public function addReturnTo( $title, $query = array(), $text = null ) {
2140 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL() ) );
2143 $wgUser->getSkin()->link( $title, $text, array(), $query )
2145 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2149 * Add a "return to" link pointing to a specified title,
2150 * or the title indicated in the request, or else the main page
2152 * @param $unused No longer used
2153 * @param $returnto Title or String to return to
2154 * @param $returntoquery String: query string for the return to link
2156 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2159 if ( $returnto == null ) {
2160 $returnto = $wgRequest->getText( 'returnto' );
2163 if ( $returntoquery == null ) {
2164 $returntoquery = $wgRequest->getText( 'returntoquery' );
2167 if ( $returnto === '' ) {
2168 $returnto = Title
::newMainPage();
2171 if ( is_object( $returnto ) ) {
2172 $titleObj = $returnto;
2174 $titleObj = Title
::newFromText( $returnto );
2176 if ( !is_object( $titleObj ) ) {
2177 $titleObj = Title
::newMainPage();
2180 $this->addReturnTo( $titleObj, $returntoquery );
2184 * @param $sk Skin The given Skin
2185 * @param $includeStyle Boolean: unused
2186 * @return String: The doctype, opening <html>, and head element.
2188 public function headElement( Skin
$sk, $includeStyle = true ) {
2189 global $wgOutputEncoding, $wgMimeType;
2190 global $wgUseTrackbacks, $wgHtml5;
2191 global $wgUser, $wgRequest, $wgLang;
2193 if ( $sk->commonPrintStylesheet() ) {
2194 $this->addStyle( 'common/wikiprintable.css', 'print' );
2196 $sk->setupUserCss( $this );
2198 $ret = Html
::htmlHeader( array( 'lang' => wfUILang()->getCode() ) );
2200 if ( $this->getHTMLTitle() == '' ) {
2201 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ) );
2204 $openHead = Html
::openElement( 'head' );
2206 # Don't bother with the newline if $head == ''
2207 $ret .= "$openHead\n";
2211 # More succinct than <meta http-equiv=Content-Type>, has the
2213 $ret .= Html
::element( 'meta', array( 'charset' => $wgOutputEncoding ) ) . "\n";
2215 $this->addMeta( 'http:Content-Type', "$wgMimeType; charset=$wgOutputEncoding" );
2218 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2220 $ret .= implode( "\n", array(
2221 $this->getHeadLinks( $sk ),
2222 $this->buildCssLinks(),
2223 $this->getHeadItems(),
2225 if ( $sk->usercss
) {
2226 $ret .= Html
::inlineStyle( $sk->usercss
);
2229 if ( $wgUseTrackbacks && $this->isArticleRelated() ) {
2230 $ret .= $this->getTitle()->trackbackRDF();
2233 $closeHead = Html
::closeElement( 'head' );
2235 $ret .= "$closeHead\n";
2238 $bodyAttrs = array();
2240 # Crazy edit-on-double-click stuff
2241 $action = $wgRequest->getVal( 'action', 'view' );
2244 $this->getTitle()->getNamespace() != NS_SPECIAL
&&
2245 !in_array( $action, array( 'edit', 'submit' ) ) &&
2246 $wgUser->getOption( 'editondblclick' )
2249 $bodyAttrs['ondblclick'] = "document.location = '" . Xml
::escapeJsString( $this->getTitle()->getEditURL() ) . "'";
2253 $dir = wfUILang()->getDir();
2254 $bodyAttrs['class'] = "mediawiki $dir";
2256 if ( $wgLang->capitalizeAllNouns() ) {
2257 # A <body> class is probably not the best way to do this . . .
2258 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2260 $bodyAttrs['class'] .= ' ns-' . $this->getTitle()->getNamespace();
2261 if ( $this->getTitle()->getNamespace() == NS_SPECIAL
) {
2262 $bodyAttrs['class'] .= ' ns-special';
2263 } elseif ( $this->getTitle()->isTalkPage() ) {
2264 $bodyAttrs['class'] .= ' ns-talk';
2266 $bodyAttrs['class'] .= ' ns-subject';
2268 $bodyAttrs['class'] .= ' ' . Sanitizer
::escapeClass( 'page-' . $this->getTitle()->getPrefixedText() );
2269 $bodyAttrs['class'] .= ' skin-' . Sanitizer
::escapeClass( $wgUser->getSkin()->getSkinName() );
2271 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2276 static function makeResourceLoaderLink( $skin, $modules, $only ) {
2277 global $wgUser, $wgLang, $wgRequest, $wgScriptPath;
2278 // TODO: Should this be a static function of ResourceLoader instead?
2280 'modules' => implode( '|', array_unique( (array) $modules ) ),
2281 'lang' => $wgLang->getCode(),
2282 'debug' => $wgRequest->getBool( 'debug' ) && $wgRequest->getVal( 'debug' ) !== 'false',
2283 'skin' => $wgUser->getSkin()->getSkinName(),
2286 // Automatically select style/script elements
2287 if ( $only === 'styles' ) {
2288 return Html
::linkedStyle( wfAppendQuery( $wgScriptPath . '/load.php', $query ) );
2290 return Html
::linkedScript( wfAppendQuery( $wgScriptPath . '/load.php', $query ) );
2295 * Gets the global variables and mScripts; also adds userjs to the end if
2296 * enabled. Despite the name, these scripts are no longer put in the
2297 * <head> but at the bottom of the <body>
2299 * @param $sk Skin object to use
2300 * @return String: HTML fragment
2302 function getHeadScripts( Skin
$sk ) {
2303 global $wgUser, $wgRequest, $wgJsMimeType;
2304 global $wgStylePath, $wgStyleVersion, $wgUseSiteJs;
2306 // Statup - this will immediately load jquery and mediawiki modules
2307 $scripts = self
::makeResourceLoaderLink( $sk, 'startup', 'scripts' );
2309 $scripts .= Skin
::makeGlobalVariablesScript( $sk->getSkinName() ) . "\n";
2310 // Support individual script requests in debug mode
2311 if ( $wgRequest->getBool( 'debug' ) && $wgRequest->getVal( 'debug' ) !== 'false' ) {
2313 foreach ( $this->getModuleScripts() as $name ) {
2314 $scripts .= self
::makeResourceLoaderLink( $sk, $name, 'scripts' );
2317 foreach ( $this->getModuleMessages() as $name ) {
2318 $scripts .= self
::makeResourceLoaderLink( $sk, $name, 'messages' );
2322 if ( count( $this->getModuleScripts() ) ) {
2323 $scripts .= self
::makeResourceLoaderLink( $sk, $this->getModuleScripts(), 'scripts' );
2326 if ( count( $this->getModuleMessages() ) ) {
2327 $scripts .= self
::makeResourceLoaderLink( $sk, $this->getModuleMessages(), 'messages' );
2330 if ( $this->getModules() ) {
2331 // Modules - let the client calculate dependencies and batch requests as it likes
2332 $modules = FormatJson
::encode( $this->getModules() );
2333 $scripts .= Html
::inlineScript(
2334 "if ( mediaWiki !== undefined ) { mediaWiki.loader.load( {$modules} ); }"
2337 // TODO: User Scripts should be included using the resource loader
2338 // Add user JS if enabled
2339 if( $this->isUserJsAllowed() && $wgUser->isLoggedIn() ) {
2340 $action = $wgRequest->getVal( 'action', 'view' );
2341 if( $this->mTitle
&& $this->mTitle
->isJsSubpage() && $sk->userCanPreview( $action ) ) {
2342 # XXX: additional security check/prompt?
2343 $this->addInlineScript( $wgRequest->getText( 'wpTextbox1' ) );
2345 $userpage = $wgUser->getUserPage();
2346 foreach( array( 'common', $sk->getSkinName() ) as $name ) {
2347 $scriptpage = Title
::makeTitleSafe( NS_USER
, $userpage->getDBkey() . '/' . $name . '.js' );
2348 if ( $scriptpage && $scriptpage->exists() && ( $scriptpage->getLength() > 0 ) ) {
2349 $userjs = $scriptpage->getLocalURL( 'action=raw&ctype=' . $wgJsMimeType );
2350 $this->addScriptFile( $userjs, $scriptpage->getLatestRevID() );
2355 $scripts .= "\n" . $this->mScripts
;
2356 // This should be at the bottom of the body - below ALL other scripts
2357 $scripts .= Html
::inlineScript( "if ( mediaWiki !== undefined ) { mediaWiki.loader.go(); }" );
2358 // Add site JS if enabled
2359 if ( $wgUseSiteJs ) {
2360 $scripts .= self
::makeResourceLoaderLink( $sk, 'sitejs', 'scripts' );
2367 * Add default \<meta\> tags
2369 protected function addDefaultMeta() {
2370 global $wgVersion, $wgHtml5;
2372 static $called = false;
2374 # Don't run this twice
2380 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); // bug 15835
2382 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
2384 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
2385 if( $p !== 'index,follow' ) {
2386 // http://www.robotstxt.org/wc/meta-user.html
2387 // Only show if it's different from the default robots policy
2388 $this->addMeta( 'robots', $p );
2391 if ( count( $this->mKeywords
) > 0 ) {
2393 "/<.*?" . ">/" => '',
2399 array_keys( $strip ),
2400 array_values( $strip ),
2401 implode( ',', $this->mKeywords
)
2408 * @return string HTML tag links to be put in the header.
2410 public function getHeadLinks( $sk ) {
2411 global $wgFeed, $wgRequest;
2413 // Ideally this should happen earlier, somewhere. :P
2414 $this->addDefaultMeta();
2418 foreach ( $this->mMetatags
as $tag ) {
2419 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
2421 $tag[0] = substr( $tag[0], 5 );
2425 $tags[] = Html
::element( 'meta',
2428 'content' => $tag[1]
2432 foreach ( $this->mLinktags
as $tag ) {
2433 $tags[] = Html
::element( 'link', $tag );
2437 foreach( $this->getSyndicationLinks() as $format => $link ) {
2438 # Use the page name for the title (accessed through $wgTitle since
2439 # there's no other way). In principle, this could lead to issues
2440 # with having the same name for different feeds corresponding to
2441 # the same page, but we can't avoid that at this low a level.
2443 $tags[] = $this->feedLink(
2446 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
2447 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )
2451 # Recent changes feed should appear on every page (except recentchanges,
2452 # that would be redundant). Put it after the per-page feed to avoid
2453 # changing existing behavior. It's still available, probably via a
2454 # menu in your browser. Some sites might have a different feed they'd
2455 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
2456 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
2457 # If so, use it instead.
2459 global $wgOverrideSiteFeed, $wgSitename, $wgAdvertisedFeedTypes;
2460 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
2462 if ( $wgOverrideSiteFeed ) {
2463 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
2464 $tags[] = $this->feedLink(
2466 htmlspecialchars( $feedUrl ),
2467 wfMsg( "site-{$type}-feed", $wgSitename )
2470 } elseif ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
2471 foreach ( $wgAdvertisedFeedTypes as $format ) {
2472 $tags[] = $this->feedLink(
2474 $rctitle->getLocalURL( "feed={$format}" ),
2475 wfMsg( "site-{$format}-feed", $wgSitename ) # For grep: 'site-rss-feed', 'site-atom-feed'.
2481 // Support individual script requests in debug mode
2482 if ( $wgRequest->getBool( 'debug' ) && $wgRequest->getVal( 'debug' ) !== 'false' ) {
2483 foreach ( $this->getModuleStyles() as $name ) {
2484 $tags[] = self
::makeResourceLoaderLink( $sk, $name, 'styles' );
2487 if ( count( $this->getModuleStyles() ) ) {
2488 $tags[] = self
::makeResourceLoaderLink( $sk, $this->getModuleStyles(), 'styles' );
2492 return implode( "\n", $tags );
2496 * Generate a <link rel/> for a feed.
2498 * @param $type String: feed type
2499 * @param $url String: URL to the feed
2500 * @param $text String: value of the "title" attribute
2501 * @return String: HTML fragment
2503 private function feedLink( $type, $url, $text ) {
2504 return Html
::element( 'link', array(
2505 'rel' => 'alternate',
2506 'type' => "application/$type+xml",
2513 * Add a local or specified stylesheet, with the given media options.
2514 * Meant primarily for internal use...
2516 * @param $style String: URL to the file
2517 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
2518 * @param $condition String: for IE conditional comments, specifying an IE version
2519 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
2521 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
2523 // Even though we expect the media type to be lowercase, but here we
2524 // force it to lowercase to be safe.
2526 $options['media'] = $media;
2529 $options['condition'] = $condition;
2532 $options['dir'] = $dir;
2534 $this->styles
[$style] = $options;
2538 * Adds inline CSS styles
2539 * @param $style_css Mixed: inline CSS
2541 public function addInlineStyle( $style_css ){
2542 $this->mScripts
.= Html
::inlineStyle( $style_css );
2546 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
2547 * These will be applied to various media & IE conditionals.
2549 public function buildCssLinks() {
2550 return implode( "\n", $this->buildCssLinksArray() );
2553 public function buildCssLinksArray() {
2555 foreach( $this->styles
as $file => $options ) {
2556 $link = $this->styleLink( $file, $options );
2558 $links[$file] = $link;
2565 * Generate \<link\> tags for stylesheets
2567 * @param $style String: URL to the file
2568 * @param $options Array: option, can contain 'condition', 'dir', 'media'
2570 * @return String: HTML fragment
2572 protected function styleLink( $style, $options ) {
2573 if( isset( $options['dir'] ) ) {
2574 $siteDir = wfUILang()->getDir();
2575 if( $siteDir != $options['dir'] ) {
2580 if( isset( $options['media'] ) ) {
2581 $media = $this->transformCssMedia( $options['media'] );
2582 if( is_null( $media ) ) {
2589 if( substr( $style, 0, 1 ) == '/' ||
2590 substr( $style, 0, 5 ) == 'http:' ||
2591 substr( $style, 0, 6 ) == 'https:' ) {
2594 global $wgStylePath, $wgStyleVersion;
2595 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
2598 $link = Html
::linkedStyle( $url, $media );
2600 if( isset( $options['condition'] ) ) {
2601 $condition = htmlspecialchars( $options['condition'] );
2602 $link = "<!--[if $condition]>$link<![endif]-->";
2608 * Transform "media" attribute based on request parameters
2610 * @param $media String: current value of the "media" attribute
2611 * @return String: modified value of the "media" attribute
2613 function transformCssMedia( $media ) {
2614 global $wgRequest, $wgHandheldForIPhone;
2616 // Switch in on-screen display for media testing
2618 'printable' => 'print',
2619 'handheld' => 'handheld',
2621 foreach( $switches as $switch => $targetMedia ) {
2622 if( $wgRequest->getBool( $switch ) ) {
2623 if( $media == $targetMedia ) {
2625 } elseif( $media == 'screen' ) {
2631 // Expand longer media queries as iPhone doesn't grok 'handheld'
2632 if( $wgHandheldForIPhone ) {
2633 $mediaAliases = array(
2634 'screen' => 'screen and (min-device-width: 481px)',
2635 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
2638 if( isset( $mediaAliases[$media] ) ) {
2639 $media = $mediaAliases[$media];
2647 * Turn off regular page output and return an error reponse
2648 * for when rate limiting has triggered.
2650 public function rateLimited() {
2651 $this->setPageTitle( wfMsg( 'actionthrottled' ) );
2652 $this->setRobotPolicy( 'noindex,follow' );
2653 $this->setArticleRelated( false );
2654 $this->enableClientCache( false );
2655 $this->mRedirect
= '';
2657 $this->setStatusCode( 503 );
2658 $this->addWikiMsg( 'actionthrottledtext' );
2660 $this->returnToMain( null, $this->getTitle() );
2664 * Show a warning about slave lag
2666 * If the lag is higher than $wgSlaveLagCritical seconds,
2667 * then the warning is a bit more obvious. If the lag is
2668 * lower than $wgSlaveLagWarning, then no warning is shown.
2670 * @param $lag Integer: slave lag
2672 public function showLagWarning( $lag ) {
2673 global $wgSlaveLagWarning, $wgSlaveLagCritical, $wgLang;
2674 if( $lag >= $wgSlaveLagWarning ) {
2675 $message = $lag < $wgSlaveLagCritical
2678 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2679 $this->wrapWikiMsg( "$wrap\n", array( $message, $wgLang->formatNum( $lag ) ) );
2684 * Add a wikitext-formatted message to the output.
2685 * This is equivalent to:
2687 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2689 public function addWikiMsg( /*...*/ ) {
2690 $args = func_get_args();
2691 $name = array_shift( $args );
2692 $this->addWikiMsgArray( $name, $args );
2696 * Add a wikitext-formatted message to the output.
2697 * Like addWikiMsg() except the parameters are taken as an array
2698 * instead of a variable argument list.
2700 * $options is passed through to wfMsgExt(), see that function for details.
2702 public function addWikiMsgArray( $name, $args, $options = array() ) {
2703 $options[] = 'parse';
2704 $text = wfMsgExt( $name, $options, $args );
2705 $this->addHTML( $text );
2709 * This function takes a number of message/argument specifications, wraps them in
2710 * some overall structure, and then parses the result and adds it to the output.
2712 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
2713 * on. The subsequent arguments may either be strings, in which case they are the
2714 * message names, or arrays, in which case the first element is the message name,
2715 * and subsequent elements are the parameters to that message.
2717 * The special named parameter 'options' in a message specification array is passed
2718 * through to the $options parameter of wfMsgExt().
2720 * Don't use this for messages that are not in users interface language.
2724 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
2728 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . "\n</div>" );
2730 * The newline after opening div is needed in some wikitext. See bug 19226.
2732 public function wrapWikiMsg( $wrap /*, ...*/ ) {
2733 $msgSpecs = func_get_args();
2734 array_shift( $msgSpecs );
2735 $msgSpecs = array_values( $msgSpecs );
2737 foreach ( $msgSpecs as $n => $spec ) {
2739 if ( is_array( $spec ) ) {
2741 $name = array_shift( $args );
2742 if ( isset( $args['options'] ) ) {
2743 $options = $args['options'];
2744 unset( $args['options'] );
2750 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
2752 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );
2756 * Include jQuery core. Use this to avoid loading it multiple times
2757 * before we get a usable script loader.
2759 * @param $modules Array: list of jQuery modules which should be loaded
2760 * @return Array: the list of modules which were not loaded.
2762 * @deprecated No longer needed as of 1.17
2764 public function includeJQuery( $modules = array() ) {