2 if ( ! defined( 'MEDIAWIKI' ) )
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();
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;
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();
51 * Whether to load jQuery core.
53 protected $mIncludeJQuery = false;
55 private $mIndexPolicy = 'index';
56 private $mFollowPolicy = 'follow';
57 private $mVaryHeader = array( 'Accept-Encoding' => array('list-contains=gzip'),
62 * Initialise private variables
64 function __construct() {
65 global $wgAllowUserJs;
66 $this->mAllowUserJs
= $wgAllowUserJs;
69 public function redirect( $url, $responsecode = '302' ) {
70 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
71 $this->mRedirect
= str_replace( "\n", '', $url );
72 $this->mRedirectCode
= $responsecode;
75 public function getRedirect() {
76 return $this->mRedirect
;
80 * Set the HTTP status code to send with the output.
82 * @param int $statusCode
85 function setStatusCode( $statusCode ) { $this->mStatusCode
= $statusCode; }
88 * Add a new <meta> tag
89 * To add an http-equiv meta tag, precede the name with "http:"
91 * @param $name tag name
92 * @param $val tag value
94 function addMeta( $name, $val ) {
95 array_push( $this->mMetatags
, array( $name, $val ) );
98 function addKeyword( $text ) {
99 if( is_array( $text )) {
100 $this->mKeywords
= array_merge( $this->mKeywords
, $text );
102 array_push( $this->mKeywords
, $text );
105 function addScript( $script ) {
106 $this->mScripts
.= $script . "\n";
110 * Register and add a stylesheet from an extension directory.
111 * @param $url String path to sheet. Provide either a full url (beginning
112 * with 'http', etc) or a relative path from the document root
113 * (beginning with '/'). Otherwise it behaves identically to
114 * addStyle() and draws from the /skins folder.
116 public function addExtensionStyle( $url ) {
117 array_push( $this->mExtStyles
, $url );
121 * Add a JavaScript file out of skins/common, or a given relative path.
122 * @param string $file filename in skins/common or complete on-server path (/foo/bar.js)
124 function addScriptFile( $file ) {
125 global $wgStylePath, $wgStyleVersion;
126 if( substr( $file, 0, 1 ) == '/' ) {
129 $path = "{$wgStylePath}/common/{$file}";
131 $this->addScript( Html
::linkedScript( "$path?$wgStyleVersion" ) );
135 * Add a self-contained script tag with the given contents
136 * @param string $script JavaScript text, no <script> tags
138 function addInlineScript( $script ) {
139 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
143 * Get all registered JS and CSS tags for the header.
145 function getScript() {
146 return $this->mScripts
. $this->getHeadItems();
149 function getHeadItems() {
151 foreach ( $this->mHeadItems
as $item ) {
157 function addHeadItem( $name, $value ) {
158 $this->mHeadItems
[$name] = $value;
161 function hasHeadItem( $name ) {
162 return isset( $this->mHeadItems
[$name] );
165 function setETag($tag) { $this->mETag
= $tag; }
166 function setArticleBodyOnly($only) { $this->mArticleBodyOnly
= $only; }
167 function getArticleBodyOnly() { return $this->mArticleBodyOnly
; }
169 function addLink( $linkarr ) {
170 # $linkarr should be an associative array of attributes. We'll escape on output.
171 array_push( $this->mLinktags
, $linkarr );
174 # Get all links added by extensions
175 function getExtStyle() {
176 return $this->mExtStyles
;
179 function addMetadataLink( $linkarr ) {
180 # note: buggy CC software only reads first "meta" link
181 static $haveMeta = false;
182 $linkarr['rel'] = ($haveMeta) ?
'alternate meta' : 'meta';
183 $this->addLink( $linkarr );
188 * checkLastModified tells the client to use the client-cached page if
189 * possible. If sucessful, the OutputPage is disabled so that
190 * any future call to OutputPage->output() have no effect.
192 * Side effect: sets mLastModified for Last-Modified header
194 * @return bool True iff cache-ok headers was sent.
196 function checkLastModified( $timestamp ) {
197 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
199 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
200 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
203 if( !$wgCachePages ) {
204 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
207 if( $wgUser->getOption( 'nocache' ) ) {
208 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
212 $timestamp = wfTimestamp( TS_MW
, $timestamp );
213 $modifiedTimes = array(
214 'page' => $timestamp,
215 'user' => $wgUser->getTouched(),
216 'epoch' => $wgCacheEpoch
218 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
220 $maxModified = max( $modifiedTimes );
221 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
223 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
224 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
230 foreach ( $modifiedTimes as $name => $value ) {
231 if ( $info !== '' ) {
234 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
237 # IE sends sizes after the date like this:
238 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
239 # this breaks strtotime().
240 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
242 wfSuppressWarnings(); // E_STRICT system time bitching
243 $clientHeaderTime = strtotime( $clientHeader );
245 if ( !$clientHeaderTime ) {
246 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
249 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
251 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
252 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
253 wfDebug( __METHOD__
. ": effective Last-Modified: " .
254 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
255 if( $clientHeaderTime < $maxModified ) {
256 wfDebug( __METHOD__
. ": STALE, $info\n", false );
261 # Give a 304 response code and disable body output
262 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
263 ini_set('zlib.output_compression', 0);
264 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
265 $this->sendCacheControl();
268 // Don't output a compressed blob when using ob_gzhandler;
269 // it's technically against HTTP spec and seems to confuse
270 // Firefox when the response gets split over two packets.
271 wfClearOutputBuffers();
276 function setPageTitleActionText( $text ) {
277 $this->mPageTitleActionText
= $text;
280 function getPageTitleActionText () {
281 if ( isset( $this->mPageTitleActionText
) ) {
282 return $this->mPageTitleActionText
;
287 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
289 * @param $policy string The literal string to output as the contents of
290 * the meta tag. Will be parsed according to the spec and output in
294 public function setRobotPolicy( $policy ) {
295 $policy = Article
::formatRobotPolicy( $policy );
297 if( isset( $policy['index'] ) ){
298 $this->setIndexPolicy( $policy['index'] );
300 if( isset( $policy['follow'] ) ){
301 $this->setFollowPolicy( $policy['follow'] );
306 * Set the index policy for the page, but leave the follow policy un-
309 * @param $policy string Either 'index' or 'noindex'.
312 public function setIndexPolicy( $policy ) {
313 $policy = trim( $policy );
314 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
315 $this->mIndexPolicy
= $policy;
320 * Set the follow policy for the page, but leave the index policy un-
323 * @param $policy string Either 'follow' or 'nofollow'.
326 public function setFollowPolicy( $policy ) {
327 $policy = trim( $policy );
328 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
329 $this->mFollowPolicy
= $policy;
334 * "HTML title" means the contents of <title>. It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
336 public function setHTMLTitle( $name ) {
337 $this->mHTMLtitle
= $name;
341 * "Page title" means the contents of <h1>. It is stored as a valid HTML fragment.
342 * This function allows good tags like <sup> in the <h1> tag, but not bad tags like <script>.
343 * This function automatically sets <title> to the same content as <h1> but with all tags removed.
344 * Bad tags that were escaped in <h1> will still be escaped in <title>, and good tags like <i> will be dropped entirely.
346 public function setPageTitle( $name ) {
347 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
348 # but leave "<i>foobar</i>" alone
349 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
350 $this->mPagetitle
= $nameWithTags;
352 $taction = $this->getPageTitleActionText();
353 if( !empty( $taction ) ) {
354 $name .= ' - '.$taction;
357 # change "<i>foo&bar</i>" to "foo&bar"
358 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer
::stripAllTags( $nameWithTags ) ) );
361 public function setTitle( $t ) {
365 public function getTitle() {
366 if ( $this->mTitle
instanceof Title
) {
367 return $this->mTitle
;
370 wfDebug( __METHOD__
. ' called and $mTitle is null. Return $wgTitle for sanity' );
376 public function getHTMLTitle() { return $this->mHTMLtitle
; }
377 public function getPageTitle() { return $this->mPagetitle
; }
378 public function setSubtitle( $str ) { $this->mSubtitle
= /*$this->parse(*/$str/*)*/; } // @bug 2514
379 public function appendSubtitle( $str ) { $this->mSubtitle
.= /*$this->parse(*/$str/*)*/; } // @bug 2514
380 public function getSubtitle() { return $this->mSubtitle
; }
381 public function isArticle() { return $this->mIsarticle
; }
382 public function setPrintable() { $this->mPrintable
= true; }
383 public function isPrintable() { return $this->mPrintable
; }
384 public function disable() { $this->mDoNothing
= true; }
385 public function isDisabled() { return $this->mDoNothing
; }
388 * Add or remove feed links in the page header
389 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
390 * for the new version
393 * @param $show Boolean: true: add default feeds, false: remove all feeds
395 public function setSyndicated( $show = true ) {
397 $this->setFeedAppendQuery( false );
399 $this->mFeedLinks
= array();
404 * Add default feeds to the page header
405 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
406 * for the new version
409 * @param $val String: query to append to feed links or false to output
412 public function setFeedAppendQuery( $val ) {
413 global $wgAdvertisedFeedTypes;
415 $this->mFeedLinks
= array();
417 foreach ( $wgAdvertisedFeedTypes as $type ) {
418 $query = "feed=$type";
419 if ( is_string( $val ) ) {
420 $query .= '&' . $val;
422 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
427 * Add a feed link to the page header
429 * @param $format String: feed type, should be a key of $wgFeedClasses
430 * @param $href String: URL
432 public function addFeedLink( $format, $href ) {
433 $this->mFeedLinks
[$format] = $href;
437 * Should we output feed links for this page?
440 public function isSyndicated() { return count($this->mFeedLinks
) > 0; }
442 public function getFeedAppendQuery() { return $this->mFeedLinksAppendQuery
; }
444 public function setArticleRelated( $v ) {
445 $this->mIsArticleRelated
= $v;
447 $this->mIsarticle
= false;
450 public function setArticleFlag( $v ) {
451 $this->mIsarticle
= $v;
453 $this->mIsArticleRelated
= $v;
457 public function isArticleRelated() { return $this->mIsArticleRelated
; }
459 public function getLanguageLinks() { return $this->mLanguageLinks
; }
460 public function addLanguageLinks($newLinkArray) {
461 $this->mLanguageLinks +
= $newLinkArray;
463 public function setLanguageLinks($newLinkArray) {
464 $this->mLanguageLinks
= $newLinkArray;
467 public function getCategoryLinks() {
468 return $this->mCategoryLinks
;
471 public function getCategories() {
472 return $this->mCategories
;
476 * Add an array of categories, with names in the keys
478 public function addCategoryLinks( $categories ) {
479 global $wgUser, $wgContLang;
481 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
485 # Add the links to a LinkBatch
486 $arr = array( NS_CATEGORY
=> $categories );
488 $lb->setArray( $arr );
490 # Fetch existence plus the hiddencat property
491 $dbr = wfGetDB( DB_SLAVE
);
492 $pageTable = $dbr->tableName( 'page' );
493 $where = $lb->constructSet( 'page', $dbr );
494 $propsTable = $dbr->tableName( 'page_props' );
495 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, pp_value
496 FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
497 $res = $dbr->query( $sql, __METHOD__
);
499 # Add the results to the link cache
500 $lb->addResultToCache( LinkCache
::singleton(), $res );
502 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
503 $categories = array_combine( array_keys( $categories ),
504 array_fill( 0, count( $categories ), 'normal' ) );
506 # Mark hidden categories
507 foreach ( $res as $row ) {
508 if ( isset( $row->pp_value
) ) {
509 $categories[$row->page_title
] = 'hidden';
513 # Add the remaining categories to the skin
514 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
515 $sk = $wgUser->getSkin();
516 foreach ( $categories as $category => $type ) {
517 $origcategory = $category;
518 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
519 $wgContLang->findVariantLink( $category, $title, true );
520 if ( $category != $origcategory )
521 if ( array_key_exists( $category, $categories ) )
523 $text = $wgContLang->convertHtml( $title->getText() );
524 $this->mCategories
[] = $title->getText();
525 $this->mCategoryLinks
[$type][] = $sk->link( $title, $text );
530 public function setCategoryLinks($categories) {
531 $this->mCategoryLinks
= array();
532 $this->addCategoryLinks($categories);
535 public function suppressQuickbar() { $this->mSuppressQuickbar
= true; }
536 public function isQuickbarSuppressed() { return $this->mSuppressQuickbar
; }
538 public function disallowUserJs() { $this->mAllowUserJs
= false; }
539 public function isUserJsAllowed() { return $this->mAllowUserJs
; }
541 public function prependHTML( $text ) { $this->mBodytext
= $text . $this->mBodytext
; }
542 public function addHTML( $text ) { $this->mBodytext
.= $text; }
543 public function clearHTML() { $this->mBodytext
= ''; }
544 public function getHTML() { return $this->mBodytext
; }
545 public function debug( $text ) { $this->mDebugtext
.= $text; }
548 public function setParserOptions( $options ) {
549 wfDeprecated( __METHOD__
);
550 return $this->parserOptions( $options );
553 public function parserOptions( $options = null ) {
554 if ( !$this->mParserOptions
) {
555 $this->mParserOptions
= new ParserOptions
;
557 return wfSetVar( $this->mParserOptions
, $options );
561 * Set the revision ID which will be seen by the wiki text parser
562 * for things such as embedded {{REVISIONID}} variable use.
563 * @param mixed $revid an integer, or NULL
564 * @return mixed previous value
566 public function setRevisionId( $revid ) {
567 $val = is_null( $revid ) ?
null : intval( $revid );
568 return wfSetVar( $this->mRevisionId
, $val );
571 public function getRevisionId() {
572 return $this->mRevisionId
;
576 * Convert wikitext to HTML and add it to the buffer
577 * Default assumes that the current page title will
580 * @param string $text
581 * @param bool $linestart
583 public function addWikiText( $text, $linestart = true ) {
584 $title = $this->getTitle(); // Work arround E_STRICT
585 $this->addWikiTextTitle( $text, $title, $linestart );
588 public function addWikiTextWithTitle($text, &$title, $linestart = true) {
589 $this->addWikiTextTitle($text, $title, $linestart);
592 function addWikiTextTitleTidy($text, &$title, $linestart = true) {
593 $this->addWikiTextTitle( $text, $title, $linestart, true );
596 public function addWikiTextTitle($text, &$title, $linestart, $tidy = false) {
599 wfProfileIn( __METHOD__
);
601 wfIncrStats( 'pcache_not_possible' );
603 $popts = $this->parserOptions();
604 $oldTidy = $popts->setTidy( $tidy );
606 $parserOutput = $wgParser->parse( $text, $title, $popts,
607 $linestart, true, $this->mRevisionId
);
609 $popts->setTidy( $oldTidy );
611 $this->addParserOutput( $parserOutput );
613 wfProfileOut( __METHOD__
);
618 * @param ParserOutput object &$parserOutput
620 public function addParserOutputNoText( &$parserOutput ) {
621 global $wgExemptFromUserRobotsControl, $wgContentNamespaces;
623 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
624 $this->addCategoryLinks( $parserOutput->getCategories() );
625 $this->mNewSectionLink
= $parserOutput->getNewSection();
626 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
628 $this->mParseWarnings
= $parserOutput->getWarnings();
629 if ( $parserOutput->getCacheTime() == -1 ) {
630 $this->enableClientCache( false );
632 $this->mNoGallery
= $parserOutput->getNoGallery();
633 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
635 foreach ( (array)$parserOutput->mTemplateIds
as $ns => $dbks ) {
636 if ( isset( $this->mTemplateIds
[$ns] ) ) {
637 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
639 $this->mTemplateIds
[$ns] = $dbks;
643 $title = $parserOutput->getTitleText();
644 if ( $title != '' ) {
645 $this->setPageTitle( $title );
648 // Hooks registered in the object
649 global $wgParserOutputHooks;
650 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
651 list( $hookName, $data ) = $hookInfo;
652 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
653 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
657 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
662 * @param ParserOutput &$parserOutput
664 function addParserOutput( &$parserOutput ) {
665 $this->addParserOutputNoText( $parserOutput );
666 $text = $parserOutput->getText();
667 wfRunHooks( 'OutputPageBeforeHTML',array( &$this, &$text ) );
668 $this->addHTML( $text );
672 * Add wikitext to the buffer, assuming that this is the primary text for a page view
673 * Saves the text into the parser cache if possible.
675 * @param string $text
676 * @param Article $article
678 * @deprecated Use Article::outputWikitext
680 public function addPrimaryWikiText( $text, $article, $cache = true ) {
683 wfDeprecated( __METHOD__
);
685 $popts = $this->parserOptions();
686 $popts->setTidy(true);
687 $parserOutput = $wgParser->parse( $text, $article->mTitle
,
688 $popts, true, true, $this->mRevisionId
);
689 $popts->setTidy(false);
690 if ( $cache && $article && $parserOutput->getCacheTime() != -1 ) {
691 $parserCache = ParserCache
::singleton();
692 $parserCache->save( $parserOutput, $article, $popts);
695 $this->addParserOutput( $parserOutput );
699 * @deprecated use addWikiTextTidy()
701 public function addSecondaryWikiText( $text, $linestart = true ) {
702 wfDeprecated( __METHOD__
);
703 $this->addWikiTextTitleTidy($text, $this->getTitle(), $linestart);
707 * Add wikitext with tidy enabled
709 public function addWikiTextTidy( $text, $linestart = true ) {
710 $title = $this->getTitle();
711 $this->addWikiTextTitleTidy($text, $title, $linestart);
716 * Add the output of a QuickTemplate to the output buffer
718 * @param QuickTemplate $template
720 public function addTemplate( &$template ) {
722 $template->execute();
723 $this->addHTML( ob_get_contents() );
728 * Parse wikitext and return the HTML.
730 * @param string $text
731 * @param bool $linestart Is this the start of a line?
732 * @param bool $interface ??
734 public function parse( $text, $linestart = true, $interface = false ) {
736 if( is_null( $this->getTitle() ) ) {
737 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
739 $popts = $this->parserOptions();
740 if ( $interface) { $popts->setInterfaceMessage(true); }
741 $parserOutput = $wgParser->parse( $text, $this->getTitle(), $popts,
742 $linestart, true, $this->mRevisionId
);
743 if ( $interface) { $popts->setInterfaceMessage(false); }
744 return $parserOutput->getText();
747 /** Parse wikitext, strip paragraphs, and return the HTML. */
748 public function parseInline( $text, $linestart = true, $interface = false ) {
749 $parsed = $this->parse( $text, $linestart, $interface );
752 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
760 * @param Article $article
765 * @return bool True if successful, else false.
767 public function tryParserCache( &$article ) {
768 wfDeprecated( __METHOD__
);
769 $parserOutput = ParserCache
::singleton()->get( $article, $article->getParserOptions() );
771 if ($parserOutput !== false) {
772 $this->addParserOutput( $parserOutput );
780 * @param int $maxage Maximum cache time on the Squid, in seconds.
782 public function setSquidMaxage( $maxage ) {
783 $this->mSquidMaxage
= $maxage;
787 * Use enableClientCache(false) to force it to send nocache headers
790 public function enableClientCache( $state ) {
791 return wfSetVar( $this->mEnableClientCache
, $state );
794 function getCacheVaryCookies() {
795 global $wgCookiePrefix, $wgCacheVaryCookies;
797 if ( $cookies === null ) {
798 $cookies = array_merge(
800 "{$wgCookiePrefix}Token",
801 "{$wgCookiePrefix}LoggedOut",
806 wfRunHooks('GetCacheVaryCookies', array( $this, &$cookies ) );
811 function uncacheableBecauseRequestVars() {
813 return $wgRequest->getText('useskin', false) === false
814 && $wgRequest->getText('uselang', false) === false;
818 * Check if the request has a cache-varying cookie header
819 * If it does, it's very important that we don't allow public caching
821 function haveCacheVaryCookies() {
823 $cookieHeader = $wgRequest->getHeader( 'cookie' );
824 if ( $cookieHeader === false ) {
827 $cvCookies = $this->getCacheVaryCookies();
828 foreach ( $cvCookies as $cookieName ) {
829 # Check for a simple string match, like the way squid does it
830 if ( strpos( $cookieHeader, $cookieName ) ) {
831 wfDebug( __METHOD__
.": found $cookieName\n" );
835 wfDebug( __METHOD__
.": no cache-varying cookies found\n" );
839 public function addVaryHeader( $header, $option = null ) {
840 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
841 $this->mVaryHeader
[$header] = $option;
843 elseif( is_array( $option ) ) {
844 if( is_array( $this->mVaryHeader
[$header] ) ) {
845 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
848 $this->mVaryHeader
[$header] = $option;
851 $this->mVaryHeader
[$header] = array_unique( $this->mVaryHeader
[$header] );
854 /** Get a complete X-Vary-Options header */
855 public function getXVO() {
856 $cvCookies = $this->getCacheVaryCookies();
858 $cookiesOption = array();
859 foreach ( $cvCookies as $cookieName ) {
860 $cookiesOption[] = 'string-contains=' . $cookieName;
862 $this->addVaryHeader( 'Cookie', $cookiesOption );
865 foreach( $this->mVaryHeader
as $header => $option ) {
866 $newheader = $header;
867 if( is_array( $option ) )
868 $newheader .= ';' . implode( ';', $option );
869 $headers[] = $newheader;
871 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
876 /** bug 21672: Add Accept-Language to Vary and XVO headers
877 if there's no 'variant' parameter existed in GET.
880 /w/index.php?title=Main_page should always be served; but
881 /w/index.php?title=Main_page&variant=zh-cn should never be served.
883 patched by Liangent and Philip */
884 function addAcceptLanguage() {
885 global $wgRequest, $wgContLang;
886 if( !$wgRequest->getCheck('variant') && $wgContLang->hasVariants() ) {
887 $variants = $wgContLang->getVariants();
889 foreach ( $variants as $variant ) {
890 if( $variant === $wgContLang->getCode() )
893 $aloption[] = "string-contains=$variant";
895 $this->addVaryHeader( 'Accept-Language', $aloption );
899 public function sendCacheControl() {
900 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest, $wgUseXVO;
902 $response = $wgRequest->response();
903 if ($wgUseETag && $this->mETag
)
904 $response->header("ETag: $this->mETag");
906 $this->addAcceptLanguage();
908 # don't serve compressed data to clients who can't handle it
909 # maintain different caches for logged-in users and non-logged in ones
910 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) ) );
913 # Add an X-Vary-Options header for Squid with Wikimedia patches
914 $response->header( $this->getXVO() );
917 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
918 if( $wgUseSquid && session_id() == '' &&
919 ! $this->isPrintable() && $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies() )
922 # We'll purge the proxy cache explicitly, but require end user agents
923 # to revalidate against the proxy on each visit.
924 # Surrogate-Control controls our Squid, Cache-Control downstream caches
925 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
926 # start with a shorter timeout for initial testing
927 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
928 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
929 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
931 # We'll purge the proxy cache for anons explicitly, but require end user agents
932 # to revalidate against the proxy on each visit.
933 # IMPORTANT! The Squid needs to replace the Cache-Control header with
934 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
935 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
936 # start with a shorter timeout for initial testing
937 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
938 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
941 # We do want clients to cache if they can, but they *must* check for updates
942 # on revisiting the page.
943 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
944 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
945 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
947 if($this->mLastModified
) {
948 $response->header( "Last-Modified: {$this->mLastModified}" );
951 wfDebug( __METHOD__
. ": no caching **\n", false );
953 # In general, the absence of a last modified header should be enough to prevent
954 # the client from using its cache. We send a few other things just to make sure.
955 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
956 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
957 $response->header( 'Pragma: no-cache' );
959 wfRunHooks('CacheHeadersAfterSet', array( $this ) );
963 * Get the message associed with the HTTP response code $code
965 * @param $code Integer: status code
966 * @return String or null: message or null if $code is not in the list of
969 public static function getStatusMessage( $code ) {
970 static $statusMessage = array(
972 101 => 'Switching Protocols',
977 203 => 'Non-Authoritative Information',
979 205 => 'Reset Content',
980 206 => 'Partial Content',
981 207 => 'Multi-Status',
982 300 => 'Multiple Choices',
983 301 => 'Moved Permanently',
986 304 => 'Not Modified',
988 307 => 'Temporary Redirect',
989 400 => 'Bad Request',
990 401 => 'Unauthorized',
991 402 => 'Payment Required',
994 405 => 'Method Not Allowed',
995 406 => 'Not Acceptable',
996 407 => 'Proxy Authentication Required',
997 408 => 'Request Timeout',
1000 411 => 'Length Required',
1001 412 => 'Precondition Failed',
1002 413 => 'Request Entity Too Large',
1003 414 => 'Request-URI Too Large',
1004 415 => 'Unsupported Media Type',
1005 416 => 'Request Range Not Satisfiable',
1006 417 => 'Expectation Failed',
1007 422 => 'Unprocessable Entity',
1009 424 => 'Failed Dependency',
1010 500 => 'Internal Server Error',
1011 501 => 'Not Implemented',
1012 502 => 'Bad Gateway',
1013 503 => 'Service Unavailable',
1014 504 => 'Gateway Timeout',
1015 505 => 'HTTP Version Not Supported',
1016 507 => 'Insufficient Storage'
1018 return isset( $statusMessage[$code] ) ?
$statusMessage[$code] : null;
1022 * Finally, all the text has been munged and accumulated into
1023 * the object, let's actually output it:
1025 public function output() {
1026 global $wgUser, $wgOutputEncoding, $wgRequest;
1027 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
1028 global $wgUseAjax, $wgAjaxWatch;
1029 global $wgEnableMWSuggest, $wgUniversalEditButton;
1032 if( $this->mDoNothing
){
1035 wfProfileIn( __METHOD__
);
1036 if ( $this->mRedirect
!= '' ) {
1037 # Standards require redirect URLs to be absolute
1038 $this->mRedirect
= wfExpandUrl( $this->mRedirect
);
1039 if( $this->mRedirectCode
== '301' ||
$this->mRedirectCode
== '303' ) {
1040 if( !$wgDebugRedirects ) {
1041 $message = self
::getStatusMessage( $this->mRedirectCode
);
1042 $wgRequest->response()->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
1044 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1046 $this->sendCacheControl();
1048 $wgRequest->response()->header( "Content-Type: text/html; charset=utf-8" );
1049 if( $wgDebugRedirects ) {
1050 $url = htmlspecialchars( $this->mRedirect
);
1051 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1052 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1053 print "</body>\n</html>\n";
1055 $wgRequest->response()->header( 'Location: ' . $this->mRedirect
);
1057 wfProfileOut( __METHOD__
);
1059 } elseif ( $this->mStatusCode
) {
1060 $message = self
::getStatusMessage( $this->mStatusCode
);
1062 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
1065 $sk = $wgUser->getSkin();
1068 $this->addScriptFile( 'ajax.js' );
1070 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1072 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1073 $this->addScriptFile( 'ajaxwatch.js' );
1076 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ){
1077 $this->addScriptFile( 'mwsuggest.js' );
1081 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1082 $this->addScriptFile( 'rightclickedit.js' );
1085 if( $wgUniversalEditButton ) {
1086 if( isset( $wgArticle ) && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1087 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create' ) ) ) {
1088 // Original UniversalEditButton
1089 $msg = wfMsg('edit');
1090 $this->addLink( array(
1091 'rel' => 'alternate',
1092 'type' => 'application/x-wiki',
1094 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1096 // Alternate edit link
1097 $this->addLink( array(
1100 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1105 # Buffer output; final headers may depend on later processing
1108 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1109 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
1111 if ($this->mArticleBodyOnly
) {
1112 $this->out($this->mBodytext
);
1114 // Hook that allows last minute changes to the output page, e.g.
1115 // adding of CSS or Javascript by extensions.
1116 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1118 wfProfileIn( 'Output-skin' );
1119 $sk->outputPage( $this );
1120 wfProfileOut( 'Output-skin' );
1123 $this->sendCacheControl();
1125 wfProfileOut( __METHOD__
);
1129 * Actually output something with print(). Performs an iconv to the
1130 * output encoding, if needed.
1131 * @param string $ins The string to output
1133 public function out( $ins ) {
1134 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1135 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1138 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1139 if ( false === $outs ) { $outs = $ins; }
1147 public static function setEncodings() {
1148 global $wgInputEncoding, $wgOutputEncoding;
1151 $wgInputEncoding = strtolower( $wgInputEncoding );
1153 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
1154 $wgOutputEncoding = strtolower( $wgOutputEncoding );
1157 $wgOutputEncoding = $wgInputEncoding;
1161 * Deprecated, use wfReportTime() instead.
1165 public function reportTime() {
1166 wfDeprecated( __METHOD__
);
1167 $time = wfReportTime();
1172 * Produce a "user is blocked" page.
1174 * @param bool $return Whether to have a "return to $wgTitle" message or not.
1177 function blockedPage( $return = true ) {
1178 global $wgUser, $wgContLang, $wgLang;
1180 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1181 $this->setRobotPolicy( 'noindex,nofollow' );
1182 $this->setArticleRelated( false );
1184 $name = User
::whoIs( $wgUser->blockedBy() );
1185 $reason = $wgUser->blockedFor();
1186 if( $reason == '' ) {
1187 $reason = wfMsg( 'blockednoreason' );
1189 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $wgUser->mBlock
->mTimestamp
), true );
1192 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1194 $blockid = $wgUser->mBlock
->mId
;
1196 $blockExpiry = $wgUser->mBlock
->mExpiry
;
1197 if ( $blockExpiry == 'infinity' ) {
1198 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1199 // Search for localization in 'ipboptions'
1200 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1201 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1202 if ( strpos( $option, ":" ) === false )
1204 list( $show, $value ) = explode( ":", $option );
1205 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1206 $blockExpiry = $show;
1211 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1214 if ( $wgUser->mBlock
->mAuto
) {
1215 $msg = 'autoblockedtext';
1217 $msg = 'blockedtext';
1220 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1221 * This could be a username, an ip range, or a single ip. */
1222 $intended = $wgUser->mBlock
->mAddress
;
1224 $this->addWikiMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
1226 # Don't auto-return to special pages
1228 $return = $this->getTitle()->getNamespace() > -1 ?
$this->getTitle() : null;
1229 $this->returnToMain( null, $return );
1234 * Output a standard error page
1236 * @param string $title Message key for page title
1237 * @param string $msg Message key for page text
1238 * @param array $params Message parameters
1240 public function showErrorPage( $title, $msg, $params = array() ) {
1241 if ( $this->getTitle() ) {
1242 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1244 $this->setPageTitle( wfMsg( $title ) );
1245 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1246 $this->setRobotPolicy( 'noindex,nofollow' );
1247 $this->setArticleRelated( false );
1248 $this->enableClientCache( false );
1249 $this->mRedirect
= '';
1250 $this->mBodytext
= '';
1252 array_unshift( $params, 'parse' );
1253 array_unshift( $params, $msg );
1254 $this->addHTML( call_user_func_array( 'wfMsgExt', $params ) );
1256 $this->returnToMain();
1260 * Output a standard permission error page
1262 * @param array $errors Error message keys
1264 public function showPermissionsErrorPage( $errors, $action = null )
1266 $this->mDebugtext
.= 'Original title: ' .
1267 $this->getTitle()->getPrefixedText() . "\n";
1268 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1269 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1270 $this->setRobotPolicy( 'noindex,nofollow' );
1271 $this->setArticleRelated( false );
1272 $this->enableClientCache( false );
1273 $this->mRedirect
= '';
1274 $this->mBodytext
= '';
1275 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1279 public function errorpage( $title, $msg ) {
1280 wfDeprecated( __METHOD__
);
1281 throw new ErrorPageError( $title, $msg );
1285 * Display an error page indicating that a given version of MediaWiki is
1286 * required to use it
1288 * @param mixed $version The version of MediaWiki needed to use the page
1290 public function versionRequired( $version ) {
1291 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1292 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1293 $this->setRobotPolicy( 'noindex,nofollow' );
1294 $this->setArticleRelated( false );
1295 $this->mBodytext
= '';
1297 $this->addWikiMsg( 'versionrequiredtext', $version );
1298 $this->returnToMain();
1302 * Display an error page noting that a given permission bit is required.
1304 * @param string $permission key required
1306 public function permissionRequired( $permission ) {
1309 $this->setPageTitle( wfMsg( 'badaccess' ) );
1310 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1311 $this->setRobotPolicy( 'noindex,nofollow' );
1312 $this->setArticleRelated( false );
1313 $this->mBodytext
= '';
1315 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1316 User
::getGroupsWithPermission( $permission ) );
1318 $this->addWikiMsg( 'badaccess-groups',
1319 $wgLang->commaList( $groups ),
1322 $this->addWikiMsg( 'badaccess-group0' );
1324 $this->returnToMain();
1328 * Use permissionRequired.
1331 public function sysopRequired() {
1332 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
1336 * Use permissionRequired.
1339 public function developerRequired() {
1340 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
1344 * Produce the stock "please login to use the wiki" page
1346 public function loginToUse() {
1347 global $wgUser, $wgContLang;
1349 if( $wgUser->isLoggedIn() ) {
1350 $this->permissionRequired( 'read' );
1354 $skin = $wgUser->getSkin();
1356 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1357 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1358 $this->setRobotPolicy( 'noindex,nofollow' );
1359 $this->setArticleFlag( false );
1361 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1362 $loginLink = $skin->link(
1364 wfMsgHtml( 'loginreqlink' ),
1366 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
1367 array( 'known', 'noclasses' )
1369 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1370 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . "-->" );
1372 # Don't return to the main page if the user can't read it
1373 # otherwise we'll end up in a pointless loop
1374 $mainPage = Title
::newMainPage();
1375 if( $mainPage->userCanRead() )
1376 $this->returnToMain( null, $mainPage );
1380 public function databaseError( $fname, $sql, $error, $errno ) {
1381 throw new MWException( "OutputPage::databaseError is obsolete\n" );
1385 * @param array $errors An array of arrays returned by Title::getUserPermissionsErrors
1386 * @return string The wikitext error-messages, formatted into a list.
1388 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1389 if ($action == null) {
1390 $text = wfMsgNoTrans( 'permissionserrorstext', count($errors)). "\n\n";
1393 $action_desc = wfMsgNoTrans( "action-$action" );
1394 $text = wfMsgNoTrans( 'permissionserrorstext-withaction', count($errors), $action_desc ) . "\n\n";
1397 if (count( $errors ) > 1) {
1398 $text .= '<ul class="permissions-errors">' . "\n";
1400 foreach( $errors as $error )
1403 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1408 $text .= "<div class=\"permissions-errors\">\n" . call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) . "\n</div>";
1415 * Display a page stating that the Wiki is in read-only mode,
1416 * and optionally show the source of the page that the user
1417 * was trying to edit. Should only be called (for this
1418 * purpose) after wfReadOnly() has returned true.
1420 * For historical reasons, this function is _also_ used to
1421 * show the error message when a user tries to edit a page
1422 * they are not allowed to edit. (Unless it's because they're
1423 * blocked, then we show blockedPage() instead.) In this
1424 * case, the second parameter should be set to true and a list
1425 * of reasons supplied as the third parameter.
1427 * @todo Needs to be split into multiple functions.
1429 * @param string $source Source code to show (or null).
1430 * @param bool $protected Is this a permissions error?
1431 * @param array $reasons List of reasons for this error, as returned by Title::getUserPermissionsErrors().
1433 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1435 $skin = $wgUser->getSkin();
1437 $this->setRobotPolicy( 'noindex,nofollow' );
1438 $this->setArticleRelated( false );
1440 // If no reason is given, just supply a default "I can't let you do
1441 // that, Dave" message. Should only occur if called by legacy code.
1442 if ( $protected && empty($reasons) ) {
1443 $reasons[] = array( 'badaccess-group0' );
1446 if ( !empty($reasons) ) {
1447 // Permissions error
1449 $this->setPageTitle( wfMsg( 'viewsource' ) );
1458 array( 'known', 'noclasses' )
1463 $this->setPageTitle( wfMsg( 'badaccess' ) );
1465 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1467 // Wiki is read only
1468 $this->setPageTitle( wfMsg( 'readonly' ) );
1469 $reason = wfReadOnlyReason();
1470 $this->wrapWikiMsg( '<div class="mw-readonly-error">\n$1</div>', array( 'readonlytext', $reason ) );
1473 // Show source, if supplied
1474 if( is_string( $source ) ) {
1475 $this->addWikiMsg( 'viewsourcetext' );
1478 'id' => 'wpTextbox1',
1479 'name' => 'wpTextbox1',
1480 'cols' => $wgUser->getOption( 'cols' ),
1481 'rows' => $wgUser->getOption( 'rows' ),
1482 'readonly' => 'readonly'
1484 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
1486 // Show templates used by this article
1487 $skin = $wgUser->getSkin();
1488 $article = new Article( $this->getTitle() );
1489 $this->addHTML( "<div class='templatesUsed'>
1490 {$skin->formatTemplates( $article->getUsedTemplates() )}
1495 # If the title doesn't exist, it's fairly pointless to print a return
1496 # link to it. After all, you just tried editing it and couldn't, so
1497 # what's there to do there?
1498 if( $this->getTitle()->exists() ) {
1499 $this->returnToMain( null, $this->getTitle() );
1504 public function fatalError( $message ) {
1505 wfDeprecated( __METHOD__
);
1506 throw new FatalError( $message );
1510 public function unexpectedValueError( $name, $val ) {
1511 wfDeprecated( __METHOD__
);
1512 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1516 public function fileCopyError( $old, $new ) {
1517 wfDeprecated( __METHOD__
);
1518 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1522 public function fileRenameError( $old, $new ) {
1523 wfDeprecated( __METHOD__
);
1524 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1528 public function fileDeleteError( $name ) {
1529 wfDeprecated( __METHOD__
);
1530 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1534 public function fileNotFoundError( $name ) {
1535 wfDeprecated( __METHOD__
);
1536 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1539 public function showFatalError( $message ) {
1540 $this->setPageTitle( wfMsg( "internalerror" ) );
1541 $this->setRobotPolicy( "noindex,nofollow" );
1542 $this->setArticleRelated( false );
1543 $this->enableClientCache( false );
1544 $this->mRedirect
= '';
1545 $this->mBodytext
= $message;
1548 public function showUnexpectedValueError( $name, $val ) {
1549 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
1552 public function showFileCopyError( $old, $new ) {
1553 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
1556 public function showFileRenameError( $old, $new ) {
1557 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
1560 public function showFileDeleteError( $name ) {
1561 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
1564 public function showFileNotFoundError( $name ) {
1565 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1569 * Add a "return to" link pointing to a specified title
1571 * @param $title Title to link
1572 * @param $query String: query string
1574 public function addReturnTo( $title, $query = array() ) {
1576 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullUrl() ) );
1577 $link = wfMsgHtml( 'returnto', $wgUser->getSkin()->link(
1578 $title, null, array(), $query ) );
1579 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
1583 * Add a "return to" link pointing to a specified title,
1584 * or the title indicated in the request, or else the main page
1586 * @param $unused No longer used
1587 * @param $returnto Title or String to return to
1588 * @param $returntoquery String: query string for the return to link
1590 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
1593 if ( $returnto == null ) {
1594 $returnto = $wgRequest->getText( 'returnto' );
1597 if ( $returntoquery == null ) {
1598 $returntoquery = $wgRequest->getText( 'returntoquery' );
1601 if ( $returnto === '' ) {
1602 $returnto = Title
::newMainPage();
1605 if ( is_object( $returnto ) ) {
1606 $titleObj = $returnto;
1608 $titleObj = Title
::newFromText( $returnto );
1610 if ( !is_object( $titleObj ) ) {
1611 $titleObj = Title
::newMainPage();
1614 $this->addReturnTo( $titleObj, $returntoquery );
1618 * @return string The doctype, opening <html>, and head element.
1620 * @param $sk Skin The given Skin
1622 public function headElement( Skin
$sk, $includeStyle = true ) {
1623 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1624 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces, $wgHtml5Version;
1625 global $wgContLang, $wgUseTrackbacks, $wgStyleVersion, $wgHtml5, $wgWellFormedXml;
1626 global $wgUser, $wgRequest, $wgLang;
1628 $this->addMeta( "http:Content-Type", "$wgMimeType; charset={$wgOutputEncoding}" );
1629 if ( $sk->commonPrintStylesheet() ) {
1630 $this->addStyle( 'common/wikiprintable.css', 'print' );
1632 $sk->setupUserCss( $this );
1636 if( $wgMimeType == 'text/xml' ||
$wgMimeType == 'application/xhtml+xml' ||
$wgMimeType == 'application/xml' ) {
1637 $ret .= "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?" . ">\n";
1640 if ( $this->getHTMLTitle() == '' ) {
1641 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1644 $dir = $wgContLang->getDir();
1647 if ( $wgWellFormedXml ) {
1648 # Unknown elements and attributes are okay in XML, but unknown
1649 # named entities are well-formedness errors and will break XML
1650 # parsers. Thus we need a doctype that gives us appropriate
1651 # entity definitions. The HTML5 spec permits four legacy
1652 # doctypes as obsolete but conforming, so let's pick one of
1653 # those, although it makes our pages look like XHTML1 Strict.
1654 # Isn't compatibility great?
1655 $ret .= "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n";
1658 $ret .= "<!doctype html>\n";
1660 $ret .= "<html lang=\"$wgContLanguageCode\" dir=\"$dir\" ";
1661 if ( $wgHtml5Version ) $ret .= " version=\"$wgHtml5Version\" ";
1664 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\" \"$wgDTD\">\n";
1665 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1666 foreach($wgXhtmlNamespaces as $tag => $ns) {
1667 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1669 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" dir=\"$dir\">\n";
1673 $ret .= "<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n";
1674 $ret .= implode( "\n", array(
1675 $this->getHeadLinks(),
1676 $this->buildCssLinks(),
1677 $this->getHeadScripts( $sk ),
1678 $this->getHeadItems(),
1681 $ret .= Html
::inlineStyle( $sk->usercss
);
1684 if ($wgUseTrackbacks && $this->isArticleRelated())
1685 $ret .= $this->getTitle()->trackbackRDF();
1687 $ret .= "</head>\n";
1689 $bodyAttrs = array();
1691 # Crazy edit-on-double-click stuff
1692 $action = $wgRequest->getVal( 'action', 'view' );
1694 if ( $this->getTitle()->getNamespace() != NS_SPECIAL
1695 && !in_array( $action, array( 'edit', 'submit' ) )
1696 && $wgUser->getOption( 'editondblclick' ) ) {
1697 $bodyAttrs['ondblclick'] = "document.location = '" . Xml
::escapeJsString( $this->getTitle()->getEditURL() ) . "'";
1701 $bodyAttrs['class'] = "mediawiki $dir";
1703 if ( $wgLang->capitalizeAllNouns() ) {
1704 # A <body> class is probably not the best way to do this . . .
1705 $bodyAttrs['class'] .= ' capitalize-all-nouns';
1707 $bodyAttrs['class'] .= ' ns-' . $this->getTitle()->getNamespace();
1708 if ( $this->getTitle()->getNamespace() == NS_SPECIAL
) {
1709 $bodyAttrs['class'] .= ' ns-special';
1710 } elseif ( $this->getTitle()->isTalkPage() ) {
1711 $bodyAttrs['class'] .= ' ns-talk';
1713 $bodyAttrs['class'] .= ' ns-subject';
1715 $bodyAttrs['class'] .= ' ' . Sanitizer
::escapeClass( 'page-' . $this->getTitle()->getPrefixedText() );
1716 $bodyAttrs['class'] .= ' skin-' . Sanitizer
::escapeClass( $wgUser->getSkin()->getSkinName() );
1718 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
1724 * gets the global variables and mScripts
1726 * also adds userjs to the end if enabled:
1728 function getHeadScripts( Skin
$sk ) {
1729 global $wgUser, $wgRequest, $wgJsMimeType, $wgUseSiteJs;
1730 global $wgStylePath, $wgStyleVersion;
1732 $scripts = Skin
::makeGlobalVariablesScript( $sk->getSkinName() );
1733 $scripts .= Html
::linkedScript( "{$wgStylePath}/common/wikibits.js?$wgStyleVersion" );
1735 //add site JS if enabled:
1736 if( $wgUseSiteJs ) {
1737 $jsCache = $wgUser->isLoggedIn() ?
'&smaxage=0' : '';
1738 $this->addScriptFile( Skin
::makeUrl( '-',
1739 "action=raw$jsCache&gen=js&useskin=" .
1740 urlencode( $sk->getSkinName() )
1745 //add user js if enabled:
1746 if( $this->isUserJsAllowed() && $wgUser->isLoggedIn() ) {
1747 $action = $wgRequest->getVal( 'action', 'view' );
1748 if( $this->mTitle
&& $this->mTitle
->isJsSubpage() and $sk->userCanPreview( $action ) ) {
1749 # XXX: additional security check/prompt?
1750 $this->addInlineScript( $wgRequest->getText( 'wpTextbox1' ) );
1752 $userpage = $wgUser->getUserPage();
1753 $scriptpage = Title
::makeTitleSafe(
1755 $userpage->getDBkey() . '/' . $sk->getSkinName() . '.js'
1757 if ( $scriptpage && $scriptpage->exists() ) {
1758 $userjs = Skin
::makeUrl( $scriptpage->getPrefixedText(), 'action=raw&ctype=' . $wgJsMimeType );
1759 $this->addScriptFile( $userjs );
1764 $scripts .= "\n" . $this->mScripts
;
1768 protected function addDefaultMeta() {
1769 global $wgVersion, $wgHtml5;
1771 static $called = false;
1773 # Don't run this twice
1779 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); //bug 15835
1781 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
1783 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
1784 if( $p !== 'index,follow' ) {
1785 // http://www.robotstxt.org/wc/meta-user.html
1786 // Only show if it's different from the default robots policy
1787 $this->addMeta( 'robots', $p );
1790 if ( count( $this->mKeywords
) > 0 ) {
1792 "/<.*?" . ">/" => '',
1795 $this->addMeta( 'keywords', preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords
) ) );
1800 * @return string HTML tag links to be put in the header.
1802 public function getHeadLinks() {
1803 global $wgRequest, $wgFeed;
1805 // Ideally this should happen earlier, somewhere. :P
1806 $this->addDefaultMeta();
1810 foreach ( $this->mMetatags
as $tag ) {
1811 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
1813 $tag[0] = substr( $tag[0], 5 );
1817 $tags[] = Html
::element( 'meta',
1820 'content' => $tag[1] ) );
1822 foreach ( $this->mLinktags
as $tag ) {
1823 $tags[] = Html
::element( 'link', $tag );
1827 foreach( $this->getSyndicationLinks() as $format => $link ) {
1828 # Use the page name for the title (accessed through $wgTitle since
1829 # there's no other way). In principle, this could lead to issues
1830 # with having the same name for different feeds corresponding to
1831 # the same page, but we can't avoid that at this low a level.
1833 $tags[] = $this->feedLink(
1836 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
1837 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() ) );
1840 # Recent changes feed should appear on every page (except recentchanges,
1841 # that would be redundant). Put it after the per-page feed to avoid
1842 # changing existing behavior. It's still available, probably via a
1843 # menu in your browser. Some sites might have a different feed they'd
1844 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
1845 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
1846 # If so, use it instead.
1848 global $wgOverrideSiteFeed, $wgSitename, $wgAdvertisedFeedTypes;
1849 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
1851 if ( $wgOverrideSiteFeed ) {
1852 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
1853 $tags[] = $this->feedLink (
1855 htmlspecialchars( $feedUrl ),
1856 wfMsg( "site-{$type}-feed", $wgSitename ) );
1858 } elseif ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
1859 foreach ( $wgAdvertisedFeedTypes as $format ) {
1860 $tags[] = $this->feedLink(
1862 $rctitle->getLocalURL( "feed={$format}" ),
1863 wfMsg( "site-{$format}-feed", $wgSitename ) ); # For grep: 'site-rss-feed', 'site-atom-feed'.
1868 return implode( "\n", $tags );
1872 * Return URLs for each supported syndication format for this page.
1873 * @return array associating format keys with URLs
1875 public function getSyndicationLinks() {
1876 return $this->mFeedLinks
;
1880 * Generate a <link rel/> for an RSS feed.
1882 private function feedLink( $type, $url, $text ) {
1883 return Html
::element( 'link', array(
1884 'rel' => 'alternate',
1885 'type' => "application/$type+xml",
1891 * Add a local or specified stylesheet, with the given media options.
1892 * Meant primarily for internal use...
1894 * @param $media -- to specify a media type, 'screen', 'printable', 'handheld' or any.
1895 * @param $conditional -- for IE conditional comments, specifying an IE version
1896 * @param $dir -- set to 'rtl' or 'ltr' for direction-specific sheets
1898 public function addStyle( $style, $media='', $condition='', $dir='' ) {
1900 // Even though we expect the media type to be lowercase, but here we
1901 // force it to lowercase to be safe.
1903 $options['media'] = $media;
1905 $options['condition'] = $condition;
1907 $options['dir'] = $dir;
1908 $this->styles
[$style] = $options;
1912 * Adds inline CSS styles
1913 * @param $style_css Mixed: inline CSS
1915 public function addInlineStyle( $style_css ){
1916 $this->mScripts
.= Html
::inlineStyle( $style_css );
1920 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
1921 * These will be applied to various media & IE conditionals.
1923 public function buildCssLinks() {
1925 foreach( $this->styles
as $file => $options ) {
1926 $link = $this->styleLink( $file, $options );
1931 return implode( "\n", $links );
1934 protected function styleLink( $style, $options ) {
1937 if( isset( $options['dir'] ) ) {
1939 $siteDir = $wgContLang->getDir();
1940 if( $siteDir != $options['dir'] )
1944 if( isset( $options['media'] ) ) {
1945 $media = $this->transformCssMedia( $options['media'] );
1946 if( is_null( $media ) ) {
1953 if( substr( $style, 0, 1 ) == '/' ||
1954 substr( $style, 0, 5 ) == 'http:' ||
1955 substr( $style, 0, 6 ) == 'https:' ) {
1958 global $wgStylePath, $wgStyleVersion;
1959 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
1962 $link = Html
::linkedStyle( $url, $media );
1964 if( isset( $options['condition'] ) ) {
1965 $condition = htmlspecialchars( $options['condition'] );
1966 $link = "<!--[if $condition]>$link<![endif]-->";
1971 function transformCssMedia( $media ) {
1972 global $wgRequest, $wgHandheldForIPhone;
1974 // Switch in on-screen display for media testing
1976 'printable' => 'print',
1977 'handheld' => 'handheld',
1979 foreach( $switches as $switch => $targetMedia ) {
1980 if( $wgRequest->getBool( $switch ) ) {
1981 if( $media == $targetMedia ) {
1983 } elseif( $media == 'screen' ) {
1989 // Expand longer media queries as iPhone doesn't grok 'handheld'
1990 if( $wgHandheldForIPhone ) {
1991 $mediaAliases = array(
1992 'screen' => 'screen and (min-device-width: 481px)',
1993 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
1996 if( isset( $mediaAliases[$media] ) ) {
1997 $media = $mediaAliases[$media];
2005 * Turn off regular page output and return an error reponse
2006 * for when rate limiting has triggered.
2008 public function rateLimited() {
2010 $this->setPageTitle(wfMsg('actionthrottled'));
2011 $this->setRobotPolicy( 'noindex,follow' );
2012 $this->setArticleRelated( false );
2013 $this->enableClientCache( false );
2014 $this->mRedirect
= '';
2016 $this->setStatusCode(503);
2017 $this->addWikiMsg( 'actionthrottledtext' );
2019 $this->returnToMain( null, $this->getTitle() );
2023 * Show an "add new section" link?
2027 public function showNewSectionLink() {
2028 return $this->mNewSectionLink
;
2032 * Forcibly hide the new section link?
2036 public function forceHideNewSectionLink() {
2037 return $this->mHideNewSectionLink
;
2041 * Show a warning about slave lag
2043 * If the lag is higher than $wgSlaveLagCritical seconds,
2044 * then the warning is a bit more obvious. If the lag is
2045 * lower than $wgSlaveLagWarning, then no warning is shown.
2047 * @param int $lag Slave lag
2049 public function showLagWarning( $lag ) {
2050 global $wgSlaveLagWarning, $wgSlaveLagCritical, $wgLang;
2051 if( $lag >= $wgSlaveLagWarning ) {
2052 $message = $lag < $wgSlaveLagCritical
2055 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2056 $this->wrapWikiMsg( "$wrap\n", array( $message, $wgLang->formatNum( $lag ) ) );
2061 * Add a wikitext-formatted message to the output.
2062 * This is equivalent to:
2064 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2066 public function addWikiMsg( /*...*/ ) {
2067 $args = func_get_args();
2068 $name = array_shift( $args );
2069 $this->addWikiMsgArray( $name, $args );
2073 * Add a wikitext-formatted message to the output.
2074 * Like addWikiMsg() except the parameters are taken as an array
2075 * instead of a variable argument list.
2077 * $options is passed through to wfMsgExt(), see that function for details.
2079 public function addWikiMsgArray( $name, $args, $options = array() ) {
2080 $options[] = 'parse';
2081 $text = wfMsgExt( $name, $options, $args );
2082 $this->addHTML( $text );
2086 * This function takes a number of message/argument specifications, wraps them in
2087 * some overall structure, and then parses the result and adds it to the output.
2089 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
2090 * on. The subsequent arguments may either be strings, in which case they are the
2091 * message names, or arrays, in which case the first element is the message name,
2092 * and subsequent elements are the parameters to that message.
2094 * The special named parameter 'options' in a message specification array is passed
2095 * through to the $options parameter of wfMsgExt().
2097 * Don't use this for messages that are not in users interface language.
2101 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>", 'some-error' );
2105 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . '</div>' );
2107 * The newline after opening div is needed in some wikitext. See bug 19226.
2109 public function wrapWikiMsg( $wrap /*, ...*/ ) {
2110 $msgSpecs = func_get_args();
2111 array_shift( $msgSpecs );
2112 $msgSpecs = array_values( $msgSpecs );
2114 foreach ( $msgSpecs as $n => $spec ) {
2116 if ( is_array( $spec ) ) {
2118 $name = array_shift( $args );
2119 if ( isset( $args['options'] ) ) {
2120 $options = $args['options'];
2121 unset( $args['options'] );
2127 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
2129 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );
2133 * Include jQuery core. Use this to avoid loading it multiple times
2134 * before we get usable script loader.
2136 public function includeJQuery() {
2137 if ( $this->mIncludeJQuery
) return;
2138 $this->mIncludeJQuery
= true;
2140 global $wgScriptPath, $wgStyleVersion, $wgJsMimeType;
2143 'type' => $wgJsMimeType,
2144 'src' => "$wgScriptPath/js2/js2stopgap.min.js?$wgStyleVersion",
2146 $this->mScripts
= Html
::element( 'script', $params ) . "\n" . $this->mScripts
;