* (bug 20049) Fixed in PHP notice in search highlighter that occurs in some cases
[mediawiki.git] / includes / OutputPage.php
blobeec5620b936a8b6e57efb96696e2359fd803b5bf
1 <?php
2 if ( ! defined( 'MEDIAWIKI' ) )
3 die( 1 );
5 /**
6 * @todo document
7 */
8 class OutputPage {
9 var $mMetatags = array(), $mKeywords = array(), $mLinktags = array();
10 var $mExtStyles = array();
11 var $mPagetitle = '', $mBodytext = '', $mDebugtext = '';
12 var $mHTMLtitle = '', $mIsarticle = true, $mPrintable = false;
13 var $mSubtitle = '', $mRedirect = '', $mStatusCode;
14 var $mLastModified = '', $mETag = false;
15 var $mCategoryLinks = array(), $mCategories = array(), $mLanguageLinks = array();
17 var $mScripts = '', $mLinkColours, $mPageLinkTitle = '', $mHeadItems = array();
18 var $mInlineMsg = array();
20 var $mTemplateIds = array();
22 var $mAllowUserJs;
23 var $mSuppressQuickbar = false;
24 var $mDoNothing = false;
25 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
26 var $mIsArticleRelated = true;
27 protected $mParserOptions = null; // lazy initialised, use parserOptions()
29 var $mFeedLinks = array();
31 var $mEnableClientCache = true;
32 var $mArticleBodyOnly = false;
34 var $mNewSectionLink = false;
35 var $mHideNewSectionLink = false;
36 var $mNoGallery = false;
37 var $mPageTitleActionText = '';
38 var $mParseWarnings = array();
39 var $mSquidMaxage = 0;
40 var $mRevisionId = null;
41 protected $mTitle = null;
43 /**
44 * An array of stylesheet filenames (relative from skins path), with options
45 * for CSS media, IE conditions, and RTL/LTR direction.
46 * For internal use; add settings in the skin via $this->addStyle()
48 var $styles = array();
50 /**
51 * Whether to load jQuery core.
53 protected $mJQueryDone = false;
55 private $mIndexPolicy = 'index';
56 private $mFollowPolicy = 'follow';
57 private $mVaryHeader = array( 'Accept-Encoding' => array('list-contains=gzip'),
58 'Cookie' => null );
61 /**
62 * Constructor
63 * Initialise private variables
65 function __construct() {
66 global $wgAllowUserJs;
67 $this->mAllowUserJs = $wgAllowUserJs;
70 /**
71 * Redirect to $url rather than displaying the normal page
73 * @param $url String: URL
74 * @param $responsecode String: HTTP status code
76 public function redirect( $url, $responsecode = '302' ) {
77 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
78 $this->mRedirect = str_replace( "\n", '', $url );
79 $this->mRedirectCode = $responsecode;
82 /**
83 * Get the URL to redirect to, or an empty string if not redirect URL set
85 * @return String
87 public function getRedirect() {
88 return $this->mRedirect;
91 /**
92 * Set the HTTP status code to send with the output.
94 * @param $statusCode Integer
95 * @return nothing
97 public function setStatusCode( $statusCode ) {
98 $this->mStatusCode = $statusCode;
103 * Add a new <meta> tag
104 * To add an http-equiv meta tag, precede the name with "http:"
106 * @param $name tag name
107 * @param $val tag value
109 function addMeta( $name, $val ) {
110 array_push( $this->mMetatags, array( $name, $val ) );
114 * Add a keyword or a list of keywords in the page header
116 * @param $text String or array of strings
118 function addKeyword( $text ) {
119 if( is_array( $text ) ) {
120 $this->mKeywords = array_merge( $this->mKeywords, $text );
121 } else {
122 array_push( $this->mKeywords, $text );
127 * Add a new \<link\> tag to the page header
129 * @param $linkarr Array: associative array of attributes.
131 function addLink( $linkarr ) {
132 array_push( $this->mLinktags, $linkarr );
136 * Add a new \<link\> with "rel" attribute set to "meta"
138 * @param $linkarr Array: associative array mapping attribute names to their
139 * values, both keys and values will be escaped, and the
140 * "rel" attribute will be automatically added
142 function addMetadataLink( $linkarr ) {
143 # note: buggy CC software only reads first "meta" link
144 static $haveMeta = false;
145 $linkarr['rel'] = $haveMeta ? 'alternate meta' : 'meta';
146 $this->addLink( $linkarr );
147 $haveMeta = true;
152 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
154 * @param $script String: raw HTML
156 function addScript( $script ) {
157 $this->mScripts .= $script . "\n";
161 * Register and add a stylesheet from an extension directory.
163 * @param $url String path to sheet. Provide either a full url (beginning
164 * with 'http', etc) or a relative path from the document root
165 * (beginning with '/'). Otherwise it behaves identically to
166 * addStyle() and draws from the /skins folder.
168 public function addExtensionStyle( $url ) {
169 array_push( $this->mExtStyles, $url );
173 * Get all links added by extensions
175 * @return Array
177 function getExtStyle() {
178 return $this->mExtStyles;
182 * Add a JavaScript file out of skins/common, or a given relative path.
184 * @param $file String: filename in skins/common or complete on-server path
185 * (/foo/bar.js)
187 public function addScriptFile( $file ) {
188 global $wgStylePath, $wgStyleVersion;
189 if( substr( $file, 0, 1 ) == '/' || preg_match( '#^[a-z]*://#i', $file ) ) {
190 $path = $file;
191 } else {
192 $path = "{$wgStylePath}/common/{$file}";
194 $this->addScript( Html::linkedScript( wfAppendQuery( $path, $wgStyleVersion ) ) );
198 * Add a self-contained script tag with the given contents
200 * @param $script String: JavaScript text, no <script> tags
202 public function addInlineScript( $script ) {
203 $this->mScripts .= Html::inlineScript( "\n$script\n" ) . "\n";
207 * Get all registered JS and CSS tags for the header.
209 * @return String
211 function getScript() {
212 return $this->mScripts . $this->getHeadItems();
216 * Get all header items in a string
218 * @return String
220 function getHeadItems() {
221 $s = '';
222 foreach ( $this->mHeadItems as $item ) {
223 $s .= $item;
225 return $s;
229 * Add or replace an header item to the output
231 * @param $name String: item name
232 * @param $value String: raw HTML
234 public function addHeadItem( $name, $value ) {
235 $this->mHeadItems[$name] = $value;
239 * Check if the header item $name is already set
241 * @param $name String: item name
242 * @return Boolean
244 public function hasHeadItem( $name ) {
245 return isset( $this->mHeadItems[$name] );
249 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
251 * @param $tag String: value of "ETag" header
253 function setETag( $tag ) {
254 $this->mETag = $tag;
258 * Set whether the output should only contain the body of the article,
259 * without any skin, sidebar, etc.
260 * Used e.g. when calling with "action=render".
262 * @param $only Boolean: whether to output only the body of the article
264 public function setArticleBodyOnly( $only ) {
265 $this->mArticleBodyOnly = $only;
269 * Return whether the output will contain only the body of the article
271 * @return Boolean
273 public function getArticleBodyOnly() {
274 return $this->mArticleBodyOnly;
279 * checkLastModified tells the client to use the client-cached page if
280 * possible. If sucessful, the OutputPage is disabled so that
281 * any future call to OutputPage->output() have no effect.
283 * Side effect: sets mLastModified for Last-Modified header
285 * @return Boolean: true iff cache-ok headers was sent.
287 public function checkLastModified( $timestamp ) {
288 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
290 if ( !$timestamp || $timestamp == '19700101000000' ) {
291 wfDebug( __METHOD__ . ": CACHE DISABLED, NO TIMESTAMP\n" );
292 return false;
294 if( !$wgCachePages ) {
295 wfDebug( __METHOD__ . ": CACHE DISABLED\n", false );
296 return false;
298 if( $wgUser->getOption( 'nocache' ) ) {
299 wfDebug( __METHOD__ . ": USER DISABLED CACHE\n", false );
300 return false;
303 $timestamp = wfTimestamp( TS_MW, $timestamp );
304 $modifiedTimes = array(
305 'page' => $timestamp,
306 'user' => $wgUser->getTouched(),
307 'epoch' => $wgCacheEpoch
309 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
311 $maxModified = max( $modifiedTimes );
312 $this->mLastModified = wfTimestamp( TS_RFC2822, $maxModified );
314 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
315 wfDebug( __METHOD__ . ": client did not send If-Modified-Since header\n", false );
316 return false;
319 # Make debug info
320 $info = '';
321 foreach ( $modifiedTimes as $name => $value ) {
322 if ( $info !== '' ) {
323 $info .= ', ';
325 $info .= "$name=" . wfTimestamp( TS_ISO_8601, $value );
328 # IE sends sizes after the date like this:
329 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
330 # this breaks strtotime().
331 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
333 wfSuppressWarnings(); // E_STRICT system time bitching
334 $clientHeaderTime = strtotime( $clientHeader );
335 wfRestoreWarnings();
336 if ( !$clientHeaderTime ) {
337 wfDebug( __METHOD__ . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
338 return false;
340 $clientHeaderTime = wfTimestamp( TS_MW, $clientHeaderTime );
342 wfDebug( __METHOD__ . ": client sent If-Modified-Since: " .
343 wfTimestamp( TS_ISO_8601, $clientHeaderTime ) . "\n", false );
344 wfDebug( __METHOD__ . ": effective Last-Modified: " .
345 wfTimestamp( TS_ISO_8601, $maxModified ) . "\n", false );
346 if( $clientHeaderTime < $maxModified ) {
347 wfDebug( __METHOD__ . ": STALE, $info\n", false );
348 return false;
351 # Not modified
352 # Give a 304 response code and disable body output
353 wfDebug( __METHOD__ . ": NOT MODIFIED, $info\n", false );
354 ini_set('zlib.output_compression', 0);
355 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
356 $this->sendCacheControl();
357 $this->disable();
359 // Don't output a compressed blob when using ob_gzhandler;
360 // it's technically against HTTP spec and seems to confuse
361 // Firefox when the response gets split over two packets.
362 wfClearOutputBuffers();
364 return true;
368 * Override the last modified timestamp
370 * @param $timestamp String: new timestamp, in a format readable by
371 * wfTimestamp()
373 public function setLastModified( $timestamp ) {
374 $this->mLastModified = wfTimestamp( TS_RFC2822, $timestamp );
379 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
381 * @param $policy String: the literal string to output as the contents of
382 * the meta tag. Will be parsed according to the spec and output in
383 * standardized form.
384 * @return null
386 public function setRobotPolicy( $policy ) {
387 $policy = Article::formatRobotPolicy( $policy );
389 if( isset( $policy['index'] ) ){
390 $this->setIndexPolicy( $policy['index'] );
392 if( isset( $policy['follow'] ) ){
393 $this->setFollowPolicy( $policy['follow'] );
398 * Set the index policy for the page, but leave the follow policy un-
399 * touched.
401 * @param $policy string Either 'index' or 'noindex'.
402 * @return null
404 public function setIndexPolicy( $policy ) {
405 $policy = trim( $policy );
406 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
407 $this->mIndexPolicy = $policy;
412 * Set the follow policy for the page, but leave the index policy un-
413 * touched.
415 * @param $policy String: either 'follow' or 'nofollow'.
416 * @return null
418 public function setFollowPolicy( $policy ) {
419 $policy = trim( $policy );
420 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
421 $this->mFollowPolicy = $policy;
427 * Set the new value of the "action text", this will be added to the
428 * "HTML title", separated from it with " - ".
430 * @param $text String: new value of the "action text"
432 public function setPageTitleActionText( $text ) {
433 $this->mPageTitleActionText = $text;
437 * Get the value of the "action text"
439 * @return String
441 public function getPageTitleActionText() {
442 if ( isset( $this->mPageTitleActionText ) ) {
443 return $this->mPageTitleActionText;
448 * "HTML title" means the contents of <title>. It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
450 public function setHTMLTitle( $name ) {
451 $this->mHTMLtitle = $name;
455 * Return the "HTML title", i.e. the content of the <title> tag.
457 * @return String
459 public function getHTMLTitle() {
460 return $this->mHTMLtitle;
464 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
465 * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
466 * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
467 * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
469 public function setPageTitle( $name ) {
470 # change "<script>foo&bar</script>" to "&lt;script&gt;foo&amp;bar&lt;/script&gt;"
471 # but leave "<i>foobar</i>" alone
472 $nameWithTags = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags( $name ) );
473 $this->mPagetitle = $nameWithTags;
475 $taction = $this->getPageTitleActionText();
476 if( !empty( $taction ) ) {
477 $name .= ' - '.$taction;
480 # change "<i>foo&amp;bar</i>" to "foo&bar"
481 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer::stripAllTags( $nameWithTags ) ) );
485 * Return the "page title", i.e. the content of the \<h1\> tag.
487 * @return String
489 public function getPageTitle() {
490 return $this->mPagetitle;
494 * Set the Title object to use
496 * @param $t Title object
498 public function setTitle( $t ) {
499 $this->mTitle = $t;
503 * Get the Title object used in this instance
505 * @return Title
507 public function getTitle() {
508 if ( $this->mTitle instanceof Title ) {
509 return $this->mTitle;
510 } else {
511 wfDebug( __METHOD__ . ' called and $mTitle is null. Return $wgTitle for sanity' );
512 global $wgTitle;
513 return $wgTitle;
518 * Replace the subtile with $str
520 * @param $str String: new value of the subtitle
522 public function setSubtitle( $str ) {
523 $this->mSubtitle = /*$this->parse(*/ $str /*)*/; // @bug 2514
527 * Add $str to the subtitle
529 * @param $str String to add to the subtitle
531 public function appendSubtitle( $str ) {
532 $this->mSubtitle .= /*$this->parse(*/ $str /*)*/; // @bug 2514
536 * Get the subtitle
538 * @return String
540 public function getSubtitle() {
541 return $this->mSubtitle;
546 * Set the page as printable, i.e. it'll be displayed with with all
547 * print styles included
549 public function setPrintable() {
550 $this->mPrintable = true;
554 * Return whether the page is "printable"
556 * @return Boolean
558 public function isPrintable() {
559 return $this->mPrintable;
564 * Disable output completely, i.e. calling output() will have no effect
566 public function disable() {
567 $this->mDoNothing = true;
571 * Return whether the output will be completely disabled
573 * @return Boolean
575 public function isDisabled() {
576 return $this->mDoNothing;
581 * Show an "add new section" link?
583 * @return Boolean
585 public function showNewSectionLink() {
586 return $this->mNewSectionLink;
590 * Forcibly hide the new section link?
592 * @return Boolean
594 public function forceHideNewSectionLink() {
595 return $this->mHideNewSectionLink;
600 * Add or remove feed links in the page header
601 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
602 * for the new version
603 * @see addFeedLink()
605 * @param $show Boolean: true: add default feeds, false: remove all feeds
607 public function setSyndicated( $show = true ) {
608 if ( $show ) {
609 $this->setFeedAppendQuery( false );
610 } else {
611 $this->mFeedLinks = array();
616 * Add default feeds to the page header
617 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
618 * for the new version
619 * @see addFeedLink()
621 * @param $val String: query to append to feed links or false to output
622 * default links
624 public function setFeedAppendQuery( $val ) {
625 global $wgAdvertisedFeedTypes;
627 $this->mFeedLinks = array();
629 foreach ( $wgAdvertisedFeedTypes as $type ) {
630 $query = "feed=$type";
631 if ( is_string( $val ) ) {
632 $query .= '&' . $val;
634 $this->mFeedLinks[$type] = $this->getTitle()->getLocalURL( $query );
639 * Add a feed link to the page header
641 * @param $format String: feed type, should be a key of $wgFeedClasses
642 * @param $href String: URL
644 public function addFeedLink( $format, $href ) {
645 $this->mFeedLinks[$format] = $href;
649 * Should we output feed links for this page?
650 * @return Boolean
652 public function isSyndicated() {
653 return count( $this->mFeedLinks ) > 0;
657 * Return URLs for each supported syndication format for this page.
658 * @return array associating format keys with URLs
660 public function getSyndicationLinks() {
661 return $this->mFeedLinks;
665 * Will currently always return null
667 * @return null
669 public function getFeedAppendQuery() {
670 return $this->mFeedLinksAppendQuery;
674 * Set whether the displayed content is related to the source of the
675 * corresponding article on the wiki
676 * Setting true will cause the change "article related" toggle to true
678 * @param $v Boolean
680 public function setArticleFlag( $v ) {
681 $this->mIsarticle = $v;
682 if ( $v ) {
683 $this->mIsArticleRelated = $v;
688 * Return whether the content displayed page is related to the source of
689 * the corresponding article on the wiki
691 * @return Boolean
693 public function isArticle() {
694 return $this->mIsarticle;
698 * Set whether this page is related an article on the wiki
699 * Setting false will cause the change of "article flag" toggle to false
701 * @param $v Boolean
703 public function setArticleRelated( $v ) {
704 $this->mIsArticleRelated = $v;
705 if ( !$v ) {
706 $this->mIsarticle = false;
711 * Return whether this page is related an article on the wiki
713 * @return Boolean
715 public function isArticleRelated() {
716 return $this->mIsArticleRelated;
721 * Add new language links
723 * @param $newLinkArray Associative array mapping language code to the page
724 * name
726 public function addLanguageLinks( $newLinkArray ) {
727 $this->mLanguageLinks += $newLinkArray;
731 * Reset the language links and add new language links
733 * @param $newLinkArray Associative array mapping language code to the page
734 * name
736 public function setLanguageLinks( $newLinkArray ) {
737 $this->mLanguageLinks = $newLinkArray;
741 * Get the list of language links
743 * @return Associative array mapping language code to the page name
745 public function getLanguageLinks() {
746 return $this->mLanguageLinks;
751 * Add an array of categories, with names in the keys
753 * @param $categories Associative array mapping category name to its sort key
755 public function addCategoryLinks( $categories ) {
756 global $wgUser, $wgContLang;
758 if ( !is_array( $categories ) || count( $categories ) == 0 ) {
759 return;
762 # Add the links to a LinkBatch
763 $arr = array( NS_CATEGORY => $categories );
764 $lb = new LinkBatch;
765 $lb->setArray( $arr );
767 # Fetch existence plus the hiddencat property
768 $dbr = wfGetDB( DB_SLAVE );
769 $pageTable = $dbr->tableName( 'page' );
770 $where = $lb->constructSet( 'page', $dbr );
771 $propsTable = $dbr->tableName( 'page_props' );
772 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, pp_value
773 FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
774 $res = $dbr->query( $sql, __METHOD__ );
776 # Add the results to the link cache
777 $lb->addResultToCache( LinkCache::singleton(), $res );
779 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
780 $categories = array_combine( array_keys( $categories ),
781 array_fill( 0, count( $categories ), 'normal' ) );
783 # Mark hidden categories
784 foreach ( $res as $row ) {
785 if ( isset( $row->pp_value ) ) {
786 $categories[$row->page_title] = 'hidden';
790 # Add the remaining categories to the skin
791 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks ) ) ) {
792 $sk = $wgUser->getSkin();
793 foreach ( $categories as $category => $type ) {
794 $origcategory = $category;
795 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
796 $wgContLang->findVariantLink( $category, $title, true );
797 if ( $category != $origcategory )
798 if ( array_key_exists( $category, $categories ) )
799 continue;
800 $text = $wgContLang->convertHtml( $title->getText() );
801 $this->mCategories[] = $title->getText();
802 $this->mCategoryLinks[$type][] = $sk->link( $title, $text );
808 * Reset the category links (but not the category list) and add $categories
810 * @param $categories Associative array mapping category name to its sort key
812 public function setCategoryLinks( $categories ) {
813 $this->mCategoryLinks = array();
814 $this->addCategoryLinks( $categories );
818 * Get the list of category links, in a 2-D array with the following format:
819 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
820 * hidden categories) and $link a HTML fragment with a link to the category
821 * page
823 * @return Array
825 public function getCategoryLinks() {
826 return $this->mCategoryLinks;
830 * Get the list of category names this page belongs to
832 * @return Array of strings
834 public function getCategories() {
835 return $this->mCategories;
840 * Suppress the quickbar from the output, only for skin supporting
841 * the quickbar
843 public function suppressQuickbar() {
844 $this->mSuppressQuickbar = true;
848 * Return whether the quickbar should be suppressed from the output
850 * @return Boolean
852 public function isQuickbarSuppressed() {
853 return $this->mSuppressQuickbar;
858 * Remove user JavaScript from scripts to load
860 public function disallowUserJs() {
861 $this->mAllowUserJs = false;
865 * Return whether user JavaScript is allowed for this page
867 * @return Boolean
869 public function isUserJsAllowed() {
870 return $this->mAllowUserJs;
875 * Prepend $text to the body HTML
877 * @param $text String: HTML
879 public function prependHTML( $text ) {
880 $this->mBodytext = $text . $this->mBodytext;
884 * Append $text to the body HTML
886 * @param $text String: HTML
888 public function addHTML( $text ) {
889 $this->mBodytext .= $text;
893 * Clear the body HTML
895 public function clearHTML() {
896 $this->mBodytext = '';
900 * Get the body HTML
902 * @return String: HTML
904 public function getHTML() {
905 return $this->mBodytext;
910 * Add $text to the debug output
912 * @param $text String: debug text
914 public function debug( $text ) {
915 $this->mDebugtext .= $text;
920 * @deprecated use parserOptions() instead
922 public function setParserOptions( $options ) {
923 wfDeprecated( __METHOD__ );
924 return $this->parserOptions( $options );
928 * Get/set the ParserOptions object to use for wikitext parsing
930 * @param $options either the ParserOption to use or null to only get the
931 * current ParserOption object
932 * @return current ParserOption object
934 public function parserOptions( $options = null ) {
935 if ( !$this->mParserOptions ) {
936 $this->mParserOptions = new ParserOptions;
938 return wfSetVar( $this->mParserOptions, $options );
942 * Set the revision ID which will be seen by the wiki text parser
943 * for things such as embedded {{REVISIONID}} variable use.
945 * @param $revid Mixed: an positive integer, or null
946 * @return Mixed: previous value
948 public function setRevisionId( $revid ) {
949 $val = is_null( $revid ) ? null : intval( $revid );
950 return wfSetVar( $this->mRevisionId, $val );
954 * Get the current revision ID
956 * @return Integer
958 public function getRevisionId() {
959 return $this->mRevisionId;
963 * Convert wikitext to HTML and add it to the buffer
964 * Default assumes that the current page title will be used.
966 * @param $text String
967 * @param $linestart Boolean: is this the start of a line?
969 public function addWikiText( $text, $linestart = true ) {
970 $title = $this->getTitle(); // Work arround E_STRICT
971 $this->addWikiTextTitle( $text, $title, $linestart );
975 * Add wikitext with a custom Title object
977 * @param $text String: wikitext
978 * @param $title Title object
979 * @param $linestart Boolean: is this the start of a line?
981 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
982 $this->addWikiTextTitle( $text, $title, $linestart );
986 * Add wikitext with a custom Title object and
988 * @param $text String: wikitext
989 * @param $title Title object
990 * @param $linestart Boolean: is this the start of a line?
992 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
993 $this->addWikiTextTitle( $text, $title, $linestart, true );
997 * Add wikitext with tidy enabled
999 * @param $text String: wikitext
1000 * @param $linestart Boolean: is this the start of a line?
1002 public function addWikiTextTidy( $text, $linestart = true ) {
1003 $title = $this->getTitle();
1004 $this->addWikiTextTitleTidy($text, $title, $linestart);
1008 * Add wikitext with a custom Title object
1010 * @param $text String: wikitext
1011 * @param $title Title object
1012 * @param $linestart Boolean: is this the start of a line?
1013 * @param $tidy Boolean: whether to use tidy
1015 public function addWikiTextTitle( $text, &$title, $linestart, $tidy = false ) {
1016 global $wgParser;
1018 wfProfileIn( __METHOD__ );
1020 wfIncrStats( 'pcache_not_possible' );
1022 $popts = $this->parserOptions();
1023 $oldTidy = $popts->setTidy( $tidy );
1025 $parserOutput = $wgParser->parse( $text, $title, $popts,
1026 $linestart, true, $this->mRevisionId );
1028 $popts->setTidy( $oldTidy );
1030 $this->addParserOutput( $parserOutput );
1032 wfProfileOut( __METHOD__ );
1036 * Add wikitext to the buffer, assuming that this is the primary text for a page view
1037 * Saves the text into the parser cache if possible.
1039 * @param $text String: wikitext
1040 * @param $article Article object
1041 * @param $cache Boolean
1042 * @deprecated Use Article::outputWikitext
1044 public function addPrimaryWikiText( $text, $article, $cache = true ) {
1045 global $wgParser;
1047 wfDeprecated( __METHOD__ );
1049 $popts = $this->parserOptions();
1050 $popts->setTidy(true);
1051 $parserOutput = $wgParser->parse( $text, $article->mTitle,
1052 $popts, true, true, $this->mRevisionId );
1053 $popts->setTidy(false);
1054 if ( $cache && $article && $parserOutput->getCacheTime() != -1 ) {
1055 $parserCache = ParserCache::singleton();
1056 $parserCache->save( $parserOutput, $article, $popts);
1059 $this->addParserOutput( $parserOutput );
1063 * @deprecated use addWikiTextTidy()
1065 public function addSecondaryWikiText( $text, $linestart = true ) {
1066 wfDeprecated( __METHOD__ );
1067 $this->addWikiTextTitleTidy($text, $this->getTitle(), $linestart);
1072 * Add a ParserOutput object, but without Html
1074 * @param $parserOutput ParserOutput object
1076 public function addParserOutputNoText( &$parserOutput ) {
1077 global $wgExemptFromUserRobotsControl, $wgContentNamespaces;
1079 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
1080 $this->addCategoryLinks( $parserOutput->getCategories() );
1081 $this->mNewSectionLink = $parserOutput->getNewSection();
1082 $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
1084 $this->mParseWarnings = $parserOutput->getWarnings();
1085 if ( $parserOutput->getCacheTime() == -1 ) {
1086 $this->enableClientCache( false );
1088 $this->mNoGallery = $parserOutput->getNoGallery();
1089 $this->mHeadItems = array_merge( $this->mHeadItems, $parserOutput->getHeadItems() );
1090 // Versioning...
1091 foreach ( (array)$parserOutput->mTemplateIds as $ns => $dbks ) {
1092 if ( isset( $this->mTemplateIds[$ns] ) ) {
1093 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
1094 } else {
1095 $this->mTemplateIds[$ns] = $dbks;
1098 // Page title
1099 $title = $parserOutput->getTitleText();
1100 if ( $title != '' ) {
1101 $this->setPageTitle( $title );
1104 // Hooks registered in the object
1105 global $wgParserOutputHooks;
1106 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1107 list( $hookName, $data ) = $hookInfo;
1108 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1109 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1113 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1117 * Add a ParserOutput object
1119 * @param $parserOutput ParserOutput
1121 function addParserOutput( &$parserOutput ) {
1122 $this->addParserOutputNoText( $parserOutput );
1123 $text = $parserOutput->getText();
1124 wfRunHooks( 'OutputPageBeforeHTML',array( &$this, &$text ) );
1125 $this->addHTML( $text );
1130 * Add the output of a QuickTemplate to the output buffer
1132 * @param $template QuickTemplate
1134 public function addTemplate( &$template ) {
1135 ob_start();
1136 $template->execute();
1137 $this->addHTML( ob_get_contents() );
1138 ob_end_clean();
1142 * Parse wikitext and return the HTML.
1144 * @param $text String
1145 * @param $linestart Boolean: is this the start of a line?
1146 * @param $interface Boolean: use interface language ($wgLang instead of
1147 * $wgContLang) while parsing language sensitive magic
1148 * words like GRAMMAR and PLURAL
1149 * @return String: HTML
1151 public function parse( $text, $linestart = true, $interface = false ) {
1152 global $wgParser;
1153 if( is_null( $this->getTitle() ) ) {
1154 throw new MWException( 'Empty $mTitle in ' . __METHOD__ );
1156 $popts = $this->parserOptions();
1157 if ( $interface) { $popts->setInterfaceMessage(true); }
1158 $parserOutput = $wgParser->parse( $text, $this->getTitle(), $popts,
1159 $linestart, true, $this->mRevisionId );
1160 if ( $interface) { $popts->setInterfaceMessage(false); }
1161 return $parserOutput->getText();
1165 * Parse wikitext, strip paragraphs, and return the HTML.
1167 * @param $text String
1168 * @param $linestart Boolean: is this the start of a line?
1169 * @param $interface Boolean: use interface language ($wgLang instead of
1170 * $wgContLang) while parsing language sensitive magic
1171 * words like GRAMMAR and PLURAL
1172 * @return String: HTML
1174 public function parseInline( $text, $linestart = true, $interface = false ) {
1175 $parsed = $this->parse( $text, $linestart, $interface );
1177 $m = array();
1178 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1179 $parsed = $m[1];
1182 return $parsed;
1186 * @deprecated
1188 * @param $article Article
1189 * @return Boolean: true if successful, else false.
1191 public function tryParserCache( &$article ) {
1192 wfDeprecated( __METHOD__ );
1193 $parserOutput = ParserCache::singleton()->get( $article, $article->getParserOptions() );
1195 if ($parserOutput !== false) {
1196 $this->addParserOutput( $parserOutput );
1197 return true;
1198 } else {
1199 return false;
1204 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1206 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1208 public function setSquidMaxage( $maxage ) {
1209 $this->mSquidMaxage = $maxage;
1213 * Use enableClientCache(false) to force it to send nocache headers
1215 * @param $state ??
1217 public function enableClientCache( $state ) {
1218 return wfSetVar( $this->mEnableClientCache, $state );
1222 * Get the list of cookies that will influence on the cache
1224 * @return Array
1226 function getCacheVaryCookies() {
1227 global $wgCookiePrefix, $wgCacheVaryCookies;
1228 static $cookies;
1229 if ( $cookies === null ) {
1230 $cookies = array_merge(
1231 array(
1232 "{$wgCookiePrefix}Token",
1233 "{$wgCookiePrefix}LoggedOut",
1234 session_name()
1236 $wgCacheVaryCookies
1238 wfRunHooks('GetCacheVaryCookies', array( $this, &$cookies ) );
1240 return $cookies;
1244 * Return whether this page is not cacheable because "useskin" or "uselang"
1245 * url parameters were passed
1247 * @return Boolean
1249 function uncacheableBecauseRequestVars() {
1250 global $wgRequest;
1251 return $wgRequest->getText('useskin', false) === false
1252 && $wgRequest->getText('uselang', false) === false;
1256 * Check if the request has a cache-varying cookie header
1257 * If it does, it's very important that we don't allow public caching
1259 * @return Boolean
1261 function haveCacheVaryCookies() {
1262 global $wgRequest;
1263 $cookieHeader = $wgRequest->getHeader( 'cookie' );
1264 if ( $cookieHeader === false ) {
1265 return false;
1267 $cvCookies = $this->getCacheVaryCookies();
1268 foreach ( $cvCookies as $cookieName ) {
1269 # Check for a simple string match, like the way squid does it
1270 if ( strpos( $cookieHeader, $cookieName ) ) {
1271 wfDebug( __METHOD__.": found $cookieName\n" );
1272 return true;
1275 wfDebug( __METHOD__.": no cache-varying cookies found\n" );
1276 return false;
1280 * Add an HTTP header that will influence on the cache
1282 * @param $header String: header name
1283 * @param $option either an Array or null
1285 public function addVaryHeader( $header, $option = null ) {
1286 if ( !array_key_exists( $header, $this->mVaryHeader ) ) {
1287 $this->mVaryHeader[$header] = $option;
1289 elseif( is_array( $option ) ) {
1290 if( is_array( $this->mVaryHeader[$header] ) ) {
1291 $this->mVaryHeader[$header] = array_merge( $this->mVaryHeader[$header], $option );
1293 else {
1294 $this->mVaryHeader[$header] = $option;
1297 $this->mVaryHeader[$header] = array_unique( $this->mVaryHeader[$header] );
1301 * Get a complete X-Vary-Options header
1303 * @return String
1305 public function getXVO() {
1306 $cvCookies = $this->getCacheVaryCookies();
1308 $cookiesOption = array();
1309 foreach ( $cvCookies as $cookieName ) {
1310 $cookiesOption[] = 'string-contains=' . $cookieName;
1312 $this->addVaryHeader( 'Cookie', $cookiesOption );
1314 $headers = array();
1315 foreach( $this->mVaryHeader as $header => $option ) {
1316 $newheader = $header;
1317 if( is_array( $option ) )
1318 $newheader .= ';' . implode( ';', $option );
1319 $headers[] = $newheader;
1321 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1323 return $xvo;
1327 * bug 21672: Add Accept-Language to Vary and XVO headers
1328 * if there's no 'variant' parameter existed in GET.
1330 * For example:
1331 * /w/index.php?title=Main_page should always be served; but
1332 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1334 function addAcceptLanguage() {
1335 global $wgRequest, $wgContLang;
1336 if( !$wgRequest->getCheck('variant') && $wgContLang->hasVariants() ) {
1337 $variants = $wgContLang->getVariants();
1338 $aloption = array();
1339 foreach ( $variants as $variant ) {
1340 if( $variant === $wgContLang->getCode() )
1341 continue;
1342 else
1343 $aloption[] = "string-contains=$variant";
1345 $this->addVaryHeader( 'Accept-Language', $aloption );
1350 * Send cache control HTTP headers
1352 public function sendCacheControl() {
1353 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest, $wgUseXVO;
1355 $response = $wgRequest->response();
1356 if ($wgUseETag && $this->mETag)
1357 $response->header("ETag: $this->mETag");
1359 $this->addAcceptLanguage();
1361 # don't serve compressed data to clients who can't handle it
1362 # maintain different caches for logged-in users and non-logged in ones
1363 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader ) ) );
1365 if ( $wgUseXVO ) {
1366 # Add an X-Vary-Options header for Squid with Wikimedia patches
1367 $response->header( $this->getXVO() );
1370 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache ) {
1371 if( $wgUseSquid && session_id() == '' &&
1372 ! $this->isPrintable() && $this->mSquidMaxage != 0 && !$this->haveCacheVaryCookies() )
1374 if ( $wgUseESI ) {
1375 # We'll purge the proxy cache explicitly, but require end user agents
1376 # to revalidate against the proxy on each visit.
1377 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1378 wfDebug( __METHOD__ . ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1379 # start with a shorter timeout for initial testing
1380 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1381 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage.', content="ESI/1.0"');
1382 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1383 } else {
1384 # We'll purge the proxy cache for anons explicitly, but require end user agents
1385 # to revalidate against the proxy on each visit.
1386 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1387 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1388 wfDebug( __METHOD__ . ": local proxy caching; {$this->mLastModified} **\n", false );
1389 # start with a shorter timeout for initial testing
1390 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1391 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage.', must-revalidate, max-age=0' );
1393 } else {
1394 # We do want clients to cache if they can, but they *must* check for updates
1395 # on revisiting the page.
1396 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **\n", false );
1397 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1398 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1400 if($this->mLastModified) {
1401 $response->header( "Last-Modified: {$this->mLastModified}" );
1403 } else {
1404 wfDebug( __METHOD__ . ": no caching **\n", false );
1406 # In general, the absence of a last modified header should be enough to prevent
1407 # the client from using its cache. We send a few other things just to make sure.
1408 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1409 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1410 $response->header( 'Pragma: no-cache' );
1415 * Get the message associed with the HTTP response code $code
1417 * @param $code Integer: status code
1418 * @return String or null: message or null if $code is not in the list of
1419 * messages
1421 public static function getStatusMessage( $code ) {
1422 static $statusMessage = array(
1423 100 => 'Continue',
1424 101 => 'Switching Protocols',
1425 102 => 'Processing',
1426 200 => 'OK',
1427 201 => 'Created',
1428 202 => 'Accepted',
1429 203 => 'Non-Authoritative Information',
1430 204 => 'No Content',
1431 205 => 'Reset Content',
1432 206 => 'Partial Content',
1433 207 => 'Multi-Status',
1434 300 => 'Multiple Choices',
1435 301 => 'Moved Permanently',
1436 302 => 'Found',
1437 303 => 'See Other',
1438 304 => 'Not Modified',
1439 305 => 'Use Proxy',
1440 307 => 'Temporary Redirect',
1441 400 => 'Bad Request',
1442 401 => 'Unauthorized',
1443 402 => 'Payment Required',
1444 403 => 'Forbidden',
1445 404 => 'Not Found',
1446 405 => 'Method Not Allowed',
1447 406 => 'Not Acceptable',
1448 407 => 'Proxy Authentication Required',
1449 408 => 'Request Timeout',
1450 409 => 'Conflict',
1451 410 => 'Gone',
1452 411 => 'Length Required',
1453 412 => 'Precondition Failed',
1454 413 => 'Request Entity Too Large',
1455 414 => 'Request-URI Too Large',
1456 415 => 'Unsupported Media Type',
1457 416 => 'Request Range Not Satisfiable',
1458 417 => 'Expectation Failed',
1459 422 => 'Unprocessable Entity',
1460 423 => 'Locked',
1461 424 => 'Failed Dependency',
1462 500 => 'Internal Server Error',
1463 501 => 'Not Implemented',
1464 502 => 'Bad Gateway',
1465 503 => 'Service Unavailable',
1466 504 => 'Gateway Timeout',
1467 505 => 'HTTP Version Not Supported',
1468 507 => 'Insufficient Storage'
1470 return isset( $statusMessage[$code] ) ? $statusMessage[$code] : null;
1474 * Finally, all the text has been munged and accumulated into
1475 * the object, let's actually output it:
1477 public function output() {
1478 global $wgUser, $wgOutputEncoding, $wgRequest;
1479 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
1480 global $wgUseAjax, $wgAjaxWatch;
1481 global $wgEnableMWSuggest, $wgUniversalEditButton;
1482 global $wgArticle;
1484 if( $this->mDoNothing ){
1485 return;
1487 wfProfileIn( __METHOD__ );
1488 if ( $this->mRedirect != '' ) {
1489 # Standards require redirect URLs to be absolute
1490 $this->mRedirect = wfExpandUrl( $this->mRedirect );
1491 if( $this->mRedirectCode == '301' || $this->mRedirectCode == '303' ) {
1492 if( !$wgDebugRedirects ) {
1493 $message = self::getStatusMessage( $this->mRedirectCode );
1494 $wgRequest->response()->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
1496 $this->mLastModified = wfTimestamp( TS_RFC2822 );
1498 $this->sendCacheControl();
1500 $wgRequest->response()->header( "Content-Type: text/html; charset=utf-8" );
1501 if( $wgDebugRedirects ) {
1502 $url = htmlspecialchars( $this->mRedirect );
1503 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1504 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1505 print "</body>\n</html>\n";
1506 } else {
1507 $wgRequest->response()->header( 'Location: ' . $this->mRedirect );
1509 wfProfileOut( __METHOD__ );
1510 return;
1511 } elseif ( $this->mStatusCode ) {
1512 $message = self::getStatusMessage( $this->mStatusCode );
1513 if ( $message )
1514 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode . ' ' . $message );
1517 $sk = $wgUser->getSkin();
1519 if ( $wgUseAjax ) {
1520 $this->addScriptFile( 'ajax.js' );
1522 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1524 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1525 $this->addScriptFile( 'ajaxwatch.js' );
1528 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ){
1529 $this->addScriptFile( 'mwsuggest.js' );
1533 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1534 $this->addScriptFile( 'rightclickedit.js' );
1537 if( $wgUniversalEditButton ) {
1538 if( isset( $wgArticle ) && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1539 && ( $this->getTitle()->exists() || $this->getTitle()->quickUserCan( 'create' ) ) ) {
1540 // Original UniversalEditButton
1541 $msg = wfMsg('edit');
1542 $this->addLink( array(
1543 'rel' => 'alternate',
1544 'type' => 'application/x-wiki',
1545 'title' => $msg,
1546 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1547 ) );
1548 // Alternate edit link
1549 $this->addLink( array(
1550 'rel' => 'edit',
1551 'title' => $msg,
1552 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1553 ) );
1557 # Buffer output; final headers may depend on later processing
1558 ob_start();
1560 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1561 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
1563 if ($this->mArticleBodyOnly) {
1564 $this->out($this->mBodytext);
1565 } else {
1566 // Hook that allows last minute changes to the output page, e.g.
1567 // adding of CSS or Javascript by extensions.
1568 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1570 wfProfileIn( 'Output-skin' );
1571 $sk->outputPage( $this );
1572 wfProfileOut( 'Output-skin' );
1575 $this->sendCacheControl();
1576 ob_end_flush();
1577 wfProfileOut( __METHOD__ );
1581 * Actually output something with print(). Performs an iconv to the
1582 * output encoding, if needed.
1584 * @param $ins String: the string to output
1586 public function out( $ins ) {
1587 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1588 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1589 $outs = $ins;
1590 } else {
1591 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1592 if ( false === $outs ) { $outs = $ins; }
1594 print $outs;
1598 * @todo document
1600 public static function setEncodings() {
1601 global $wgInputEncoding, $wgOutputEncoding;
1602 global $wgContLang;
1604 $wgInputEncoding = strtolower( $wgInputEncoding );
1606 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
1607 $wgOutputEncoding = strtolower( $wgOutputEncoding );
1608 return;
1610 $wgOutputEncoding = $wgInputEncoding;
1614 * @deprecated use wfReportTime() instead.
1616 * @return String
1618 public function reportTime() {
1619 wfDeprecated( __METHOD__ );
1620 $time = wfReportTime();
1621 return $time;
1625 * Produce a "user is blocked" page.
1627 * @param $return Boolean: whether to have a "return to $wgTitle" message or not.
1628 * @return nothing
1630 function blockedPage( $return = true ) {
1631 global $wgUser, $wgContLang, $wgLang;
1633 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1634 $this->setRobotPolicy( 'noindex,nofollow' );
1635 $this->setArticleRelated( false );
1637 $name = User::whoIs( $wgUser->blockedBy() );
1638 $reason = $wgUser->blockedFor();
1639 if( $reason == '' ) {
1640 $reason = wfMsg( 'blockednoreason' );
1642 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW, $wgUser->mBlock->mTimestamp ), true );
1643 $ip = wfGetIP();
1645 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
1647 $blockid = $wgUser->mBlock->mId;
1649 $blockExpiry = $wgUser->mBlock->mExpiry;
1650 if ( $blockExpiry == 'infinity' ) {
1651 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1652 // Search for localization in 'ipboptions'
1653 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1654 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1655 if ( strpos( $option, ":" ) === false )
1656 continue;
1657 list( $show, $value ) = explode( ":", $option );
1658 if ( $value == 'infinite' || $value == 'indefinite' ) {
1659 $blockExpiry = $show;
1660 break;
1663 } else {
1664 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW, $blockExpiry ), true );
1667 if ( $wgUser->mBlock->mAuto ) {
1668 $msg = 'autoblockedtext';
1669 } else {
1670 $msg = 'blockedtext';
1673 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1674 * This could be a username, an ip range, or a single ip. */
1675 $intended = $wgUser->mBlock->mAddress;
1677 $this->addWikiMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
1679 # Don't auto-return to special pages
1680 if( $return ) {
1681 $return = $this->getTitle()->getNamespace() > -1 ? $this->getTitle() : null;
1682 $this->returnToMain( null, $return );
1687 * Output a standard error page
1689 * @param $title String: message key for page title
1690 * @param $msg String: message key for page text
1691 * @param $params Array: message parameters
1693 public function showErrorPage( $title, $msg, $params = array() ) {
1694 if ( $this->getTitle() ) {
1695 $this->mDebugtext .= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1697 $this->setPageTitle( wfMsg( $title ) );
1698 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1699 $this->setRobotPolicy( 'noindex,nofollow' );
1700 $this->setArticleRelated( false );
1701 $this->enableClientCache( false );
1702 $this->mRedirect = '';
1703 $this->mBodytext = '';
1705 array_unshift( $params, 'parse' );
1706 array_unshift( $params, $msg );
1707 $this->addHTML( call_user_func_array( 'wfMsgExt', $params ) );
1709 $this->returnToMain();
1713 * Output a standard permission error page
1715 * @param $errors Array: error message keys
1716 * @param $action String: action that was denied or null if unknown
1718 public function showPermissionsErrorPage( $errors, $action = null ) {
1719 $this->mDebugtext .= 'Original title: ' .
1720 $this->getTitle()->getPrefixedText() . "\n";
1721 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1722 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1723 $this->setRobotPolicy( 'noindex,nofollow' );
1724 $this->setArticleRelated( false );
1725 $this->enableClientCache( false );
1726 $this->mRedirect = '';
1727 $this->mBodytext = '';
1728 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1732 * Display an error page indicating that a given version of MediaWiki is
1733 * required to use it
1735 * @param $version Mixed: the version of MediaWiki needed to use the page
1737 public function versionRequired( $version ) {
1738 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1739 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1740 $this->setRobotPolicy( 'noindex,nofollow' );
1741 $this->setArticleRelated( false );
1742 $this->mBodytext = '';
1744 $this->addWikiMsg( 'versionrequiredtext', $version );
1745 $this->returnToMain();
1749 * Display an error page noting that a given permission bit is required.
1751 * @param $permission String: key required
1753 public function permissionRequired( $permission ) {
1754 global $wgLang;
1756 $this->setPageTitle( wfMsg( 'badaccess' ) );
1757 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1758 $this->setRobotPolicy( 'noindex,nofollow' );
1759 $this->setArticleRelated( false );
1760 $this->mBodytext = '';
1762 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1763 User::getGroupsWithPermission( $permission ) );
1764 if( $groups ) {
1765 $this->addWikiMsg( 'badaccess-groups',
1766 $wgLang->commaList( $groups ),
1767 count( $groups) );
1768 } else {
1769 $this->addWikiMsg( 'badaccess-group0' );
1771 $this->returnToMain();
1775 * @deprecated use permissionRequired()
1777 public function sysopRequired() {
1778 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
1782 * @deprecated use permissionRequired()
1784 public function developerRequired() {
1785 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
1789 * Produce the stock "please login to use the wiki" page
1791 public function loginToUse() {
1792 global $wgUser, $wgContLang;
1794 if( $wgUser->isLoggedIn() ) {
1795 $this->permissionRequired( 'read' );
1796 return;
1799 $skin = $wgUser->getSkin();
1801 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1802 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1803 $this->setRobotPolicy( 'noindex,nofollow' );
1804 $this->setArticleFlag( false );
1806 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
1807 $loginLink = $skin->link(
1808 $loginTitle,
1809 wfMsgHtml( 'loginreqlink' ),
1810 array(),
1811 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
1812 array( 'known', 'noclasses' )
1814 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1815 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . "-->" );
1817 # Don't return to the main page if the user can't read it
1818 # otherwise we'll end up in a pointless loop
1819 $mainPage = Title::newMainPage();
1820 if( $mainPage->userCanRead() )
1821 $this->returnToMain( null, $mainPage );
1825 * Format a list of error messages
1827 * @param $errors An array of arrays returned by Title::getUserPermissionsErrors
1828 * @param $action String: action that was denied or null if unknown
1829 * @return String: the wikitext error-messages, formatted into a list.
1831 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1832 if ($action == null) {
1833 $text = wfMsgNoTrans( 'permissionserrorstext', count($errors)). "\n\n";
1834 } else {
1835 global $wgLang;
1836 $action_desc = wfMsgNoTrans( "action-$action" );
1837 $text = wfMsgNoTrans( 'permissionserrorstext-withaction', count($errors), $action_desc ) . "\n\n";
1840 if (count( $errors ) > 1) {
1841 $text .= '<ul class="permissions-errors">' . "\n";
1843 foreach( $errors as $error )
1845 $text .= '<li>';
1846 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1847 $text .= "</li>\n";
1849 $text .= '</ul>';
1850 } else {
1851 $text .= "<div class=\"permissions-errors\">\n" . call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) . "\n</div>";
1854 return $text;
1858 * Display a page stating that the Wiki is in read-only mode,
1859 * and optionally show the source of the page that the user
1860 * was trying to edit. Should only be called (for this
1861 * purpose) after wfReadOnly() has returned true.
1863 * For historical reasons, this function is _also_ used to
1864 * show the error message when a user tries to edit a page
1865 * they are not allowed to edit. (Unless it's because they're
1866 * blocked, then we show blockedPage() instead.) In this
1867 * case, the second parameter should be set to true and a list
1868 * of reasons supplied as the third parameter.
1870 * @todo Needs to be split into multiple functions.
1872 * @param $source String: source code to show (or null).
1873 * @param $protected Boolean: is this a permissions error?
1874 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
1875 * @param $action String: action that was denied or null if unknown
1877 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1878 global $wgUser;
1879 $skin = $wgUser->getSkin();
1881 $this->setRobotPolicy( 'noindex,nofollow' );
1882 $this->setArticleRelated( false );
1884 // If no reason is given, just supply a default "I can't let you do
1885 // that, Dave" message. Should only occur if called by legacy code.
1886 if ( $protected && empty($reasons) ) {
1887 $reasons[] = array( 'badaccess-group0' );
1890 if ( !empty($reasons) ) {
1891 // Permissions error
1892 if( $source ) {
1893 $this->setPageTitle( wfMsg( 'viewsource' ) );
1894 $this->setSubtitle(
1895 wfMsg(
1896 'viewsourcefor',
1897 $skin->link(
1898 $this->getTitle(),
1899 null,
1900 array(),
1901 array(),
1902 array( 'known', 'noclasses' )
1906 } else {
1907 $this->setPageTitle( wfMsg( 'badaccess' ) );
1909 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1910 } else {
1911 // Wiki is read only
1912 $this->setPageTitle( wfMsg( 'readonly' ) );
1913 $reason = wfReadOnlyReason();
1914 $this->wrapWikiMsg( '<div class="mw-readonly-error">\n$1</div>', array( 'readonlytext', $reason ) );
1917 // Show source, if supplied
1918 if( is_string( $source ) ) {
1919 $this->addWikiMsg( 'viewsourcetext' );
1921 $params = array(
1922 'id' => 'wpTextbox1',
1923 'name' => 'wpTextbox1',
1924 'cols' => $wgUser->getOption( 'cols' ),
1925 'rows' => $wgUser->getOption( 'rows' ),
1926 'readonly' => 'readonly'
1928 $this->addHTML( Html::element( 'textarea', $params, $source ) );
1930 // Show templates used by this article
1931 $skin = $wgUser->getSkin();
1932 $article = new Article( $this->getTitle() );
1933 $this->addHTML( "<div class='templatesUsed'>
1934 {$skin->formatTemplates( $article->getUsedTemplates() )}
1935 </div>
1936 " );
1939 # If the title doesn't exist, it's fairly pointless to print a return
1940 # link to it. After all, you just tried editing it and couldn't, so
1941 # what's there to do there?
1942 if( $this->getTitle()->exists() ) {
1943 $this->returnToMain( null, $this->getTitle() );
1947 /** @deprecated */
1948 public function errorpage( $title, $msg ) {
1949 wfDeprecated( __METHOD__ );
1950 throw new ErrorPageError( $title, $msg );
1953 /** @deprecated */
1954 public function databaseError( $fname, $sql, $error, $errno ) {
1955 throw new MWException( "OutputPage::databaseError is obsolete\n" );
1958 /** @deprecated */
1959 public function fatalError( $message ) {
1960 wfDeprecated( __METHOD__ );
1961 throw new FatalError( $message );
1964 /** @deprecated */
1965 public function unexpectedValueError( $name, $val ) {
1966 wfDeprecated( __METHOD__ );
1967 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1970 /** @deprecated */
1971 public function fileCopyError( $old, $new ) {
1972 wfDeprecated( __METHOD__ );
1973 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1976 /** @deprecated */
1977 public function fileRenameError( $old, $new ) {
1978 wfDeprecated( __METHOD__ );
1979 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1982 /** @deprecated */
1983 public function fileDeleteError( $name ) {
1984 wfDeprecated( __METHOD__ );
1985 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1988 /** @deprecated */
1989 public function fileNotFoundError( $name ) {
1990 wfDeprecated( __METHOD__ );
1991 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1994 public function showFatalError( $message ) {
1995 $this->setPageTitle( wfMsg( "internalerror" ) );
1996 $this->setRobotPolicy( "noindex,nofollow" );
1997 $this->setArticleRelated( false );
1998 $this->enableClientCache( false );
1999 $this->mRedirect = '';
2000 $this->mBodytext = $message;
2003 public function showUnexpectedValueError( $name, $val ) {
2004 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
2007 public function showFileCopyError( $old, $new ) {
2008 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
2011 public function showFileRenameError( $old, $new ) {
2012 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
2015 public function showFileDeleteError( $name ) {
2016 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
2019 public function showFileNotFoundError( $name ) {
2020 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
2024 * Add a "return to" link pointing to a specified title
2026 * @param $title Title to link
2027 * @param $query String: query string
2028 * @param $text String text of the link (input is not escaped)
2030 public function addReturnTo( $title, $query=array(), $text=null ) {
2031 global $wgUser;
2032 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullUrl() ) );
2033 $link = wfMsgHtml(
2034 'returnto',
2035 $wgUser->getSkin()->link( $title, $text, array(), $query )
2037 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2041 * Add a "return to" link pointing to a specified title,
2042 * or the title indicated in the request, or else the main page
2044 * @param $unused No longer used
2045 * @param $returnto Title or String to return to
2046 * @param $returntoquery String: query string for the return to link
2048 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2049 global $wgRequest;
2051 if ( $returnto == null ) {
2052 $returnto = $wgRequest->getText( 'returnto' );
2055 if ( $returntoquery == null ) {
2056 $returntoquery = $wgRequest->getText( 'returntoquery' );
2059 if ( $returnto === '' ) {
2060 $returnto = Title::newMainPage();
2063 if ( is_object( $returnto ) ) {
2064 $titleObj = $returnto;
2065 } else {
2066 $titleObj = Title::newFromText( $returnto );
2068 if ( !is_object( $titleObj ) ) {
2069 $titleObj = Title::newMainPage();
2072 $this->addReturnTo( $titleObj, $returntoquery );
2076 * @param $sk Skin The given Skin
2077 * @param $includeStyle Unused (?)
2078 * @return String: The doctype, opening <html>, and head element.
2080 public function headElement( Skin $sk, $includeStyle = true ) {
2081 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
2082 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces, $wgHtml5Version;
2083 global $wgContLang, $wgUseTrackbacks, $wgStyleVersion, $wgHtml5, $wgWellFormedXml;
2084 global $wgUser, $wgRequest, $wgLang;
2086 if ( $sk->commonPrintStylesheet() ) {
2087 $this->addStyle( 'common/wikiprintable.css', 'print' );
2089 $sk->setupUserCss( $this );
2091 $ret = '';
2093 if( $wgMimeType == 'text/xml' || $wgMimeType == 'application/xhtml+xml' || $wgMimeType == 'application/xml' ) {
2094 $ret .= "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?" . ">\n";
2097 if ( $this->getHTMLTitle() == '' ) {
2098 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ) );
2101 $dir = $wgContLang->getDir();
2103 $htmlAttribs = array( 'lang' => $wgContLanguageCode, 'dir' => $dir );
2104 if ( $wgHtml5 ) {
2105 if ( $wgWellFormedXml ) {
2106 # Unknown elements and attributes are okay in XML, but unknown
2107 # named entities are well-formedness errors and will break XML
2108 # parsers. Thus we need a doctype that gives us appropriate
2109 # entity definitions. The HTML5 spec permits four legacy
2110 # doctypes as obsolete but conforming, so let's pick one of
2111 # those, although it makes our pages look like XHTML1 Strict.
2112 # Isn't compatibility great?
2113 $ret .= "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n";
2114 } else {
2115 # Much saner.
2116 $ret .= "<!doctype html>\n";
2118 if ( $wgHtml5Version ) {
2119 $htmlAttribs['version'] = $wgHtml5Version;
2121 } else {
2122 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\" \"$wgDTD\">\n";
2123 $htmlAttribs['xmlns'] = $wgXhtmlDefaultNamespace;
2124 foreach ( $wgXhtmlNamespaces as $tag => $ns ) {
2125 $htmlAttribs["xmlns:$tag"] = $ns;
2127 $this->addMeta( 'http:Content-Type', "$wgMimeType; charset=$wgOutputEncoding" );
2129 $ret .= Html::openElement( 'html', $htmlAttribs ) . "\n";
2131 $openHead = Html::openElement( 'head' );
2132 if ( $openHead ) {
2133 # Don't bother with the newline if $head == ''
2134 $ret .= "$openHead\n";
2136 $ret .= "<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n";
2138 if ( $wgHtml5 ) {
2139 # More succinct than <meta http-equiv=Content-Type>, has the
2140 # same effect
2141 $ret .= Html::element( 'meta', array( 'charset' => $wgOutputEncoding ) ) . "\n";
2144 $ret .= implode( "\n", array(
2145 $this->getHeadLinks(),
2146 $this->buildCssLinks(),
2147 $this->getHeadScripts( $sk ),
2148 $this->getHeadItems(),
2149 ) );
2150 if ( $sk->usercss ) {
2151 $ret .= Html::inlineStyle( $sk->usercss );
2154 if ( $wgUseTrackbacks && $this->isArticleRelated() ) {
2155 $ret .= $this->getTitle()->trackbackRDF();
2158 $closeHead = Html::closeElement( 'head' );
2159 if ( $closeHead ) {
2160 $ret .= "$closeHead\n";
2163 $bodyAttrs = array();
2165 # Crazy edit-on-double-click stuff
2166 $action = $wgRequest->getVal( 'action', 'view' );
2168 if ( $this->getTitle()->getNamespace() != NS_SPECIAL
2169 && !in_array( $action, array( 'edit', 'submit' ) )
2170 && $wgUser->getOption( 'editondblclick' ) ) {
2171 $bodyAttrs['ondblclick'] = "document.location = '" . Xml::escapeJsString( $this->getTitle()->getEditURL() ) . "'";
2174 # Class bloat
2175 $bodyAttrs['class'] = "mediawiki $dir";
2177 if ( $wgLang->capitalizeAllNouns() ) {
2178 # A <body> class is probably not the best way to do this . . .
2179 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2181 $bodyAttrs['class'] .= ' ns-' . $this->getTitle()->getNamespace();
2182 if ( $this->getTitle()->getNamespace() == NS_SPECIAL ) {
2183 $bodyAttrs['class'] .= ' ns-special';
2184 } elseif ( $this->getTitle()->isTalkPage() ) {
2185 $bodyAttrs['class'] .= ' ns-talk';
2186 } else {
2187 $bodyAttrs['class'] .= ' ns-subject';
2189 $bodyAttrs['class'] .= ' ' . Sanitizer::escapeClass( 'page-' . $this->getTitle()->getPrefixedText() );
2190 $bodyAttrs['class'] .= ' skin-' . Sanitizer::escapeClass( $wgUser->getSkin()->getSkinName() );
2192 $ret .= Html::openElement( 'body', $bodyAttrs ) . "\n";
2194 return $ret;
2198 * Gets the global variables and mScripts; also adds userjs to the end if
2199 * enabled
2201 * @param $sk Skin object to use
2202 * @return String: HTML fragment
2204 function getHeadScripts( Skin $sk ) {
2205 global $wgUser, $wgRequest, $wgJsMimeType, $wgUseSiteJs;
2206 global $wgStylePath, $wgStyleVersion;
2208 $scripts = Skin::makeGlobalVariablesScript( $sk->getSkinName() );
2209 $scripts .= Html::linkedScript( "{$wgStylePath}/common/wikibits.js?$wgStyleVersion" );
2211 //add site JS if enabled:
2212 if( $wgUseSiteJs ) {
2213 $jsCache = $wgUser->isLoggedIn() ? '&smaxage=0' : '';
2214 $this->addScriptFile( Skin::makeUrl( '-',
2215 "action=raw$jsCache&gen=js&useskin=" .
2216 urlencode( $sk->getSkinName() )
2221 //add user js if enabled:
2222 if( $this->isUserJsAllowed() && $wgUser->isLoggedIn() ) {
2223 $action = $wgRequest->getVal( 'action', 'view' );
2224 if( $this->mTitle && $this->mTitle->isJsSubpage() and $sk->userCanPreview( $action ) ) {
2225 # XXX: additional security check/prompt?
2226 $this->addInlineScript( $wgRequest->getText( 'wpTextbox1' ) );
2227 } else {
2228 $userpage = $wgUser->getUserPage();
2229 $names = array( 'common', $sk->getSkinName() );
2230 foreach( $names as $name ) {
2231 $scriptpage = Title::makeTitleSafe(
2232 NS_USER,
2233 $userpage->getDBkey() . '/' . $name . '.js'
2235 if ( $scriptpage && $scriptpage->exists() ) {
2236 $userjs = $scriptpage->getLocalURL( 'action=raw&ctype=' . $wgJsMimeType );
2237 $this->addScriptFile( $userjs );
2243 $scripts .= "\n" . $this->mScripts;
2244 return $scripts;
2248 * Add default \<meta\> tags
2250 protected function addDefaultMeta() {
2251 global $wgVersion, $wgHtml5;
2253 static $called = false;
2254 if ( $called ) {
2255 # Don't run this twice
2256 return;
2258 $called = true;
2260 if ( !$wgHtml5 ) {
2261 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); //bug 15835
2263 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
2265 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
2266 if( $p !== 'index,follow' ) {
2267 // http://www.robotstxt.org/wc/meta-user.html
2268 // Only show if it's different from the default robots policy
2269 $this->addMeta( 'robots', $p );
2272 if ( count( $this->mKeywords ) > 0 ) {
2273 $strip = array(
2274 "/<.*?" . ">/" => '',
2275 "/_/" => ' '
2277 $this->addMeta( 'keywords', preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords ) ) );
2282 * @return string HTML tag links to be put in the header.
2284 public function getHeadLinks() {
2285 global $wgRequest, $wgFeed;
2287 // Ideally this should happen earlier, somewhere. :P
2288 $this->addDefaultMeta();
2290 $tags = array();
2292 foreach ( $this->mMetatags as $tag ) {
2293 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
2294 $a = 'http-equiv';
2295 $tag[0] = substr( $tag[0], 5 );
2296 } else {
2297 $a = 'name';
2299 $tags[] = Html::element( 'meta',
2300 array(
2301 $a => $tag[0],
2302 'content' => $tag[1] ) );
2304 foreach ( $this->mLinktags as $tag ) {
2305 $tags[] = Html::element( 'link', $tag );
2308 if( $wgFeed ) {
2309 foreach( $this->getSyndicationLinks() as $format => $link ) {
2310 # Use the page name for the title (accessed through $wgTitle since
2311 # there's no other way). In principle, this could lead to issues
2312 # with having the same name for different feeds corresponding to
2313 # the same page, but we can't avoid that at this low a level.
2315 $tags[] = $this->feedLink(
2316 $format,
2317 $link,
2318 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
2319 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() ) );
2322 # Recent changes feed should appear on every page (except recentchanges,
2323 # that would be redundant). Put it after the per-page feed to avoid
2324 # changing existing behavior. It's still available, probably via a
2325 # menu in your browser. Some sites might have a different feed they'd
2326 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
2327 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
2328 # If so, use it instead.
2330 global $wgOverrideSiteFeed, $wgSitename, $wgAdvertisedFeedTypes;
2331 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
2333 if ( $wgOverrideSiteFeed ) {
2334 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
2335 $tags[] = $this->feedLink (
2336 $type,
2337 htmlspecialchars( $feedUrl ),
2338 wfMsg( "site-{$type}-feed", $wgSitename ) );
2340 } elseif ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
2341 foreach ( $wgAdvertisedFeedTypes as $format ) {
2342 $tags[] = $this->feedLink(
2343 $format,
2344 $rctitle->getLocalURL( "feed={$format}" ),
2345 wfMsg( "site-{$format}-feed", $wgSitename ) ); # For grep: 'site-rss-feed', 'site-atom-feed'.
2350 return implode( "\n", $tags );
2354 * Generate a <link rel/> for a feed.
2356 * @param $type String: feed type
2357 * @param $url String: URL to the feed
2358 * @param $text String: value of the "title" attribute
2359 * @return String: HTML fragment
2361 private function feedLink( $type, $url, $text ) {
2362 return Html::element( 'link', array(
2363 'rel' => 'alternate',
2364 'type' => "application/$type+xml",
2365 'title' => $text,
2366 'href' => $url ) );
2370 * Add a local or specified stylesheet, with the given media options.
2371 * Meant primarily for internal use...
2373 * @param $style String: URL to the file
2374 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
2375 * @param $condition String: for IE conditional comments, specifying an IE version
2376 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
2378 public function addStyle( $style, $media='', $condition='', $dir='' ) {
2379 $options = array();
2380 // Even though we expect the media type to be lowercase, but here we
2381 // force it to lowercase to be safe.
2382 if( $media )
2383 $options['media'] = $media;
2384 if( $condition )
2385 $options['condition'] = $condition;
2386 if( $dir )
2387 $options['dir'] = $dir;
2388 $this->styles[$style] = $options;
2392 * Adds inline CSS styles
2393 * @param $style_css Mixed: inline CSS
2395 public function addInlineStyle( $style_css ){
2396 $this->mScripts .= Html::inlineStyle( $style_css );
2400 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
2401 * These will be applied to various media & IE conditionals.
2403 public function buildCssLinks() {
2404 $links = array();
2405 foreach( $this->styles as $file => $options ) {
2406 $link = $this->styleLink( $file, $options );
2407 if( $link )
2408 $links[] = $link;
2411 return implode( "\n", $links );
2415 * Generate \<link\> tags for stylesheets
2417 * @param $style String: URL to the file
2418 * @param $options Array: option, can contain 'condition', 'dir', 'media'
2419 * keys
2420 * @return String: HTML fragment
2422 protected function styleLink( $style, $options ) {
2423 global $wgRequest;
2425 if( isset( $options['dir'] ) ) {
2426 global $wgContLang;
2427 $siteDir = $wgContLang->getDir();
2428 if( $siteDir != $options['dir'] )
2429 return '';
2432 if( isset( $options['media'] ) ) {
2433 $media = $this->transformCssMedia( $options['media'] );
2434 if( is_null( $media ) ) {
2435 return '';
2437 } else {
2438 $media = 'all';
2441 if( substr( $style, 0, 1 ) == '/' ||
2442 substr( $style, 0, 5 ) == 'http:' ||
2443 substr( $style, 0, 6 ) == 'https:' ) {
2444 $url = $style;
2445 } else {
2446 global $wgStylePath, $wgStyleVersion;
2447 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
2450 $link = Html::linkedStyle( $url, $media );
2452 if( isset( $options['condition'] ) ) {
2453 $condition = htmlspecialchars( $options['condition'] );
2454 $link = "<!--[if $condition]>$link<![endif]-->";
2456 return $link;
2460 * Transform "media" attribute based on request parameters
2462 * @param $media String: current value of the "media" attribute
2463 * @return String: modified value of the "media" attribute
2465 function transformCssMedia( $media ) {
2466 global $wgRequest, $wgHandheldForIPhone;
2468 // Switch in on-screen display for media testing
2469 $switches = array(
2470 'printable' => 'print',
2471 'handheld' => 'handheld',
2473 foreach( $switches as $switch => $targetMedia ) {
2474 if( $wgRequest->getBool( $switch ) ) {
2475 if( $media == $targetMedia ) {
2476 $media = '';
2477 } elseif( $media == 'screen' ) {
2478 return null;
2483 // Expand longer media queries as iPhone doesn't grok 'handheld'
2484 if( $wgHandheldForIPhone ) {
2485 $mediaAliases = array(
2486 'screen' => 'screen and (min-device-width: 481px)',
2487 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
2490 if( isset( $mediaAliases[$media] ) ) {
2491 $media = $mediaAliases[$media];
2495 return $media;
2499 * Turn off regular page output and return an error reponse
2500 * for when rate limiting has triggered.
2502 public function rateLimited() {
2503 $this->setPageTitle(wfMsg('actionthrottled'));
2504 $this->setRobotPolicy( 'noindex,follow' );
2505 $this->setArticleRelated( false );
2506 $this->enableClientCache( false );
2507 $this->mRedirect = '';
2508 $this->clearHTML();
2509 $this->setStatusCode(503);
2510 $this->addWikiMsg( 'actionthrottledtext' );
2512 $this->returnToMain( null, $this->getTitle() );
2516 * Show a warning about slave lag
2518 * If the lag is higher than $wgSlaveLagCritical seconds,
2519 * then the warning is a bit more obvious. If the lag is
2520 * lower than $wgSlaveLagWarning, then no warning is shown.
2522 * @param $lag Integer: slave lag
2524 public function showLagWarning( $lag ) {
2525 global $wgSlaveLagWarning, $wgSlaveLagCritical, $wgLang;
2526 if( $lag >= $wgSlaveLagWarning ) {
2527 $message = $lag < $wgSlaveLagCritical
2528 ? 'lag-warn-normal'
2529 : 'lag-warn-high';
2530 $wrap = Html::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2531 $this->wrapWikiMsg( "$wrap\n", array( $message, $wgLang->formatNum( $lag ) ) );
2536 * Add a wikitext-formatted message to the output.
2537 * This is equivalent to:
2539 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2541 public function addWikiMsg( /*...*/ ) {
2542 $args = func_get_args();
2543 $name = array_shift( $args );
2544 $this->addWikiMsgArray( $name, $args );
2548 * Add a wikitext-formatted message to the output.
2549 * Like addWikiMsg() except the parameters are taken as an array
2550 * instead of a variable argument list.
2552 * $options is passed through to wfMsgExt(), see that function for details.
2554 public function addWikiMsgArray( $name, $args, $options = array() ) {
2555 $options[] = 'parse';
2556 $text = wfMsgExt( $name, $options, $args );
2557 $this->addHTML( $text );
2561 * This function takes a number of message/argument specifications, wraps them in
2562 * some overall structure, and then parses the result and adds it to the output.
2564 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
2565 * on. The subsequent arguments may either be strings, in which case they are the
2566 * message names, or arrays, in which case the first element is the message name,
2567 * and subsequent elements are the parameters to that message.
2569 * The special named parameter 'options' in a message specification array is passed
2570 * through to the $options parameter of wfMsgExt().
2572 * Don't use this for messages that are not in users interface language.
2574 * For example:
2576 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>", 'some-error' );
2578 * Is equivalent to:
2580 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . "</div>" );
2582 * The newline after opening div is needed in some wikitext. See bug 19226.
2584 public function wrapWikiMsg( $wrap /*, ...*/ ) {
2585 $msgSpecs = func_get_args();
2586 array_shift( $msgSpecs );
2587 $msgSpecs = array_values( $msgSpecs );
2588 $s = $wrap;
2589 foreach ( $msgSpecs as $n => $spec ) {
2590 $options = array();
2591 if ( is_array( $spec ) ) {
2592 $args = $spec;
2593 $name = array_shift( $args );
2594 if ( isset( $args['options'] ) ) {
2595 $options = $args['options'];
2596 unset( $args['options'] );
2598 } else {
2599 $args = array();
2600 $name = $spec;
2602 $s = str_replace( '$' . ( $n + 1 ), wfMsgExt( $name, $options, $args ), $s );
2604 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );
2608 * Include jQuery core. Use this to avoid loading it multiple times
2609 * before we get a usable script loader.
2611 * @param $modules Array: list of jQuery modules which should be loaded
2612 * @return Array: the list of modules which were not loaded.
2613 * @since 1.16
2615 public function includeJQuery( $modules = array() ) {
2616 global $wgStylePath, $wgStyleVersion;
2618 $supportedModules = array( /** TODO: add things here */ );
2619 $unsupported = array_diff( $modules, $supportedModules );
2621 $url = "$wgStylePath/common/jquery.min.js?$wgStyleVersion";
2622 if ( !$this->mJQueryDone ) {
2623 $this->mJQueryDone = true;
2624 $this->mScripts = Html::linkedScript( $url ) . "\n" . $this->mScripts;
2626 return $unsupported;