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 * Return the number of feed links that will be added to the page header
441 public function isSyndicated() { return count($this->mFeedLinks
); }
443 public function getFeedAppendQuery() { return $this->mFeedLinksAppendQuery
; }
445 public function setArticleRelated( $v ) {
446 $this->mIsArticleRelated
= $v;
448 $this->mIsarticle
= false;
451 public function setArticleFlag( $v ) {
452 $this->mIsarticle
= $v;
454 $this->mIsArticleRelated
= $v;
458 public function isArticleRelated() { return $this->mIsArticleRelated
; }
460 public function getLanguageLinks() { return $this->mLanguageLinks
; }
461 public function addLanguageLinks($newLinkArray) {
462 $this->mLanguageLinks +
= $newLinkArray;
464 public function setLanguageLinks($newLinkArray) {
465 $this->mLanguageLinks
= $newLinkArray;
468 public function getCategoryLinks() {
469 return $this->mCategoryLinks
;
472 public function getCategories() {
473 return $this->mCategories
;
477 * Add an array of categories, with names in the keys
479 public function addCategoryLinks( $categories ) {
480 global $wgUser, $wgContLang;
482 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
486 # Add the links to a LinkBatch
487 $arr = array( NS_CATEGORY
=> $categories );
489 $lb->setArray( $arr );
491 # Fetch existence plus the hiddencat property
492 $dbr = wfGetDB( DB_SLAVE
);
493 $pageTable = $dbr->tableName( 'page' );
494 $where = $lb->constructSet( 'page', $dbr );
495 $propsTable = $dbr->tableName( 'page_props' );
496 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, pp_value
497 FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
498 $res = $dbr->query( $sql, __METHOD__
);
500 # Add the results to the link cache
501 $lb->addResultToCache( LinkCache
::singleton(), $res );
503 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
504 $categories = array_combine( array_keys( $categories ),
505 array_fill( 0, count( $categories ), 'normal' ) );
507 # Mark hidden categories
508 foreach ( $res as $row ) {
509 if ( isset( $row->pp_value
) ) {
510 $categories[$row->page_title
] = 'hidden';
514 # Add the remaining categories to the skin
515 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
516 $sk = $wgUser->getSkin();
517 foreach ( $categories as $category => $type ) {
518 $origcategory = $category;
519 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
520 $wgContLang->findVariantLink( $category, $title, true );
521 if ( $category != $origcategory )
522 if ( array_key_exists( $category, $categories ) )
524 $text = $wgContLang->convertHtml( $title->getText() );
525 $this->mCategories
[] = $title->getText();
526 $this->mCategoryLinks
[$type][] = $sk->link( $title, $text );
531 public function setCategoryLinks($categories) {
532 $this->mCategoryLinks
= array();
533 $this->addCategoryLinks($categories);
536 public function suppressQuickbar() { $this->mSuppressQuickbar
= true; }
537 public function isQuickbarSuppressed() { return $this->mSuppressQuickbar
; }
539 public function disallowUserJs() { $this->mAllowUserJs
= false; }
540 public function isUserJsAllowed() { return $this->mAllowUserJs
; }
542 public function prependHTML( $text ) { $this->mBodytext
= $text . $this->mBodytext
; }
543 public function addHTML( $text ) { $this->mBodytext
.= $text; }
544 public function clearHTML() { $this->mBodytext
= ''; }
545 public function getHTML() { return $this->mBodytext
; }
546 public function debug( $text ) { $this->mDebugtext
.= $text; }
549 public function setParserOptions( $options ) {
550 wfDeprecated( __METHOD__
);
551 return $this->parserOptions( $options );
554 public function parserOptions( $options = null ) {
555 if ( !$this->mParserOptions
) {
556 $this->mParserOptions
= new ParserOptions
;
558 return wfSetVar( $this->mParserOptions
, $options );
562 * Set the revision ID which will be seen by the wiki text parser
563 * for things such as embedded {{REVISIONID}} variable use.
564 * @param mixed $revid an integer, or NULL
565 * @return mixed previous value
567 public function setRevisionId( $revid ) {
568 $val = is_null( $revid ) ?
null : intval( $revid );
569 return wfSetVar( $this->mRevisionId
, $val );
572 public function getRevisionId() {
573 return $this->mRevisionId
;
577 * Convert wikitext to HTML and add it to the buffer
578 * Default assumes that the current page title will
581 * @param string $text
582 * @param bool $linestart
584 public function addWikiText( $text, $linestart = true ) {
585 $title = $this->getTitle(); // Work arround E_STRICT
586 $this->addWikiTextTitle( $text, $title, $linestart );
589 public function addWikiTextWithTitle($text, &$title, $linestart = true) {
590 $this->addWikiTextTitle($text, $title, $linestart);
593 function addWikiTextTitleTidy($text, &$title, $linestart = true) {
594 $this->addWikiTextTitle( $text, $title, $linestart, true );
597 public function addWikiTextTitle($text, &$title, $linestart, $tidy = false) {
600 wfProfileIn( __METHOD__
);
602 wfIncrStats( 'pcache_not_possible' );
604 $popts = $this->parserOptions();
605 $oldTidy = $popts->setTidy( $tidy );
607 $parserOutput = $wgParser->parse( $text, $title, $popts,
608 $linestart, true, $this->mRevisionId
);
610 $popts->setTidy( $oldTidy );
612 $this->addParserOutput( $parserOutput );
614 wfProfileOut( __METHOD__
);
619 * @param ParserOutput object &$parserOutput
621 public function addParserOutputNoText( &$parserOutput ) {
622 global $wgExemptFromUserRobotsControl, $wgContentNamespaces;
624 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
625 $this->addCategoryLinks( $parserOutput->getCategories() );
626 $this->mNewSectionLink
= $parserOutput->getNewSection();
627 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
629 $this->mParseWarnings
= $parserOutput->getWarnings();
630 if ( $parserOutput->getCacheTime() == -1 ) {
631 $this->enableClientCache( false );
633 $this->mNoGallery
= $parserOutput->getNoGallery();
634 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
636 foreach ( (array)$parserOutput->mTemplateIds
as $ns => $dbks ) {
637 if ( isset( $this->mTemplateIds
[$ns] ) ) {
638 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
640 $this->mTemplateIds
[$ns] = $dbks;
644 $title = $parserOutput->getTitleText();
645 if ( $title != '' ) {
646 $this->setPageTitle( $title );
649 // Hooks registered in the object
650 global $wgParserOutputHooks;
651 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
652 list( $hookName, $data ) = $hookInfo;
653 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
654 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
658 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
663 * @param ParserOutput &$parserOutput
665 function addParserOutput( &$parserOutput ) {
666 $this->addParserOutputNoText( $parserOutput );
667 $text = $parserOutput->getText();
668 wfRunHooks( 'OutputPageBeforeHTML',array( &$this, &$text ) );
669 $this->addHTML( $text );
673 * Add wikitext to the buffer, assuming that this is the primary text for a page view
674 * Saves the text into the parser cache if possible.
676 * @param string $text
677 * @param Article $article
679 * @deprecated Use Article::outputWikitext
681 public function addPrimaryWikiText( $text, $article, $cache = true ) {
684 wfDeprecated( __METHOD__
);
686 $popts = $this->parserOptions();
687 $popts->setTidy(true);
688 $parserOutput = $wgParser->parse( $text, $article->mTitle
,
689 $popts, true, true, $this->mRevisionId
);
690 $popts->setTidy(false);
691 if ( $cache && $article && $parserOutput->getCacheTime() != -1 ) {
692 $parserCache = ParserCache
::singleton();
693 $parserCache->save( $parserOutput, $article, $popts);
696 $this->addParserOutput( $parserOutput );
700 * @deprecated use addWikiTextTidy()
702 public function addSecondaryWikiText( $text, $linestart = true ) {
703 wfDeprecated( __METHOD__
);
704 $this->addWikiTextTitleTidy($text, $this->getTitle(), $linestart);
708 * Add wikitext with tidy enabled
710 public function addWikiTextTidy( $text, $linestart = true ) {
711 $title = $this->getTitle();
712 $this->addWikiTextTitleTidy($text, $title, $linestart);
717 * Add the output of a QuickTemplate to the output buffer
719 * @param QuickTemplate $template
721 public function addTemplate( &$template ) {
723 $template->execute();
724 $this->addHTML( ob_get_contents() );
729 * Parse wikitext and return the HTML.
731 * @param string $text
732 * @param bool $linestart Is this the start of a line?
733 * @param bool $interface ??
735 public function parse( $text, $linestart = true, $interface = false ) {
737 if( is_null( $this->getTitle() ) ) {
738 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
740 $popts = $this->parserOptions();
741 if ( $interface) { $popts->setInterfaceMessage(true); }
742 $parserOutput = $wgParser->parse( $text, $this->getTitle(), $popts,
743 $linestart, true, $this->mRevisionId
);
744 if ( $interface) { $popts->setInterfaceMessage(false); }
745 return $parserOutput->getText();
748 /** Parse wikitext, strip paragraphs, and return the HTML. */
749 public function parseInline( $text, $linestart = true, $interface = false ) {
750 $parsed = $this->parse( $text, $linestart, $interface );
753 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
761 * @param Article $article
766 * @return bool True if successful, else false.
768 public function tryParserCache( &$article ) {
769 wfDeprecated( __METHOD__
);
770 $parserOutput = ParserCache
::singleton()->get( $article, $article->getParserOptions() );
772 if ($parserOutput !== false) {
773 $this->addParserOutput( $parserOutput );
781 * @param int $maxage Maximum cache time on the Squid, in seconds.
783 public function setSquidMaxage( $maxage ) {
784 $this->mSquidMaxage
= $maxage;
788 * Use enableClientCache(false) to force it to send nocache headers
791 public function enableClientCache( $state ) {
792 return wfSetVar( $this->mEnableClientCache
, $state );
795 function getCacheVaryCookies() {
796 global $wgCookiePrefix, $wgCacheVaryCookies;
798 if ( $cookies === null ) {
799 $cookies = array_merge(
801 "{$wgCookiePrefix}Token",
802 "{$wgCookiePrefix}LoggedOut",
807 wfRunHooks('GetCacheVaryCookies', array( $this, &$cookies ) );
812 function uncacheableBecauseRequestVars() {
814 return $wgRequest->getText('useskin', false) === false
815 && $wgRequest->getText('uselang', false) === false;
819 * Check if the request has a cache-varying cookie header
820 * If it does, it's very important that we don't allow public caching
822 function haveCacheVaryCookies() {
824 $cookieHeader = $wgRequest->getHeader( 'cookie' );
825 if ( $cookieHeader === false ) {
828 $cvCookies = $this->getCacheVaryCookies();
829 foreach ( $cvCookies as $cookieName ) {
830 # Check for a simple string match, like the way squid does it
831 if ( strpos( $cookieHeader, $cookieName ) ) {
832 wfDebug( __METHOD__
.": found $cookieName\n" );
836 wfDebug( __METHOD__
.": no cache-varying cookies found\n" );
840 public function addVaryHeader( $header, $option = null ) {
841 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
842 $this->mVaryHeader
[$header] = $option;
844 elseif( is_array( $option ) ) {
845 if( is_array( $this->mVaryHeader
[$header] ) ) {
846 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
849 $this->mVaryHeader
[$header] = $option;
852 $this->mVaryHeader
[$header] = array_unique( $this->mVaryHeader
[$header] );
855 /** Get a complete X-Vary-Options header */
856 public function getXVO() {
857 $cvCookies = $this->getCacheVaryCookies();
859 $cookiesOption = array();
860 foreach ( $cvCookies as $cookieName ) {
861 $cookiesOption[] = 'string-contains=' . $cookieName;
863 $this->addVaryHeader( 'Cookie', $cookiesOption );
866 foreach( $this->mVaryHeader
as $header => $option ) {
867 $newheader = $header;
868 if( is_array( $option ) )
869 $newheader .= ';' . implode( ';', $option );
870 $headers[] = $newheader;
872 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
877 /** bug 21672: Add Accept-Language to Vary and XVO headers
878 if there's no 'variant' parameter existed in GET.
881 /w/index.php?title=Main_page should always be served; but
882 /w/index.php?title=Main_page&variant=zh-cn should never be served.
884 patched by Liangent and Philip */
885 function addAcceptLanguage() {
886 global $wgRequest, $wgContLang;
887 if( !$wgRequest->getCheck('variant') && $wgContLang->hasVariants() ) {
888 $variants = $wgContLang->getVariants();
890 foreach ( $variants as $variant ) {
891 if( $variant === $wgContLang->getCode() )
894 $aloption[] = "string-contains=$variant";
896 $this->addVaryHeader( 'Accept-Language', $aloption );
900 public function sendCacheControl() {
901 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest, $wgUseXVO;
903 $response = $wgRequest->response();
904 if ($wgUseETag && $this->mETag
)
905 $response->header("ETag: $this->mETag");
907 $this->addAcceptLanguage();
909 # don't serve compressed data to clients who can't handle it
910 # maintain different caches for logged-in users and non-logged in ones
911 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) ) );
914 # Add an X-Vary-Options header for Squid with Wikimedia patches
915 $response->header( $this->getXVO() );
918 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
919 if( $wgUseSquid && session_id() == '' &&
920 ! $this->isPrintable() && $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies() )
923 # We'll purge the proxy cache explicitly, but require end user agents
924 # to revalidate against the proxy on each visit.
925 # Surrogate-Control controls our Squid, Cache-Control downstream caches
926 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
927 # start with a shorter timeout for initial testing
928 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
929 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
930 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
932 # We'll purge the proxy cache for anons explicitly, but require end user agents
933 # to revalidate against the proxy on each visit.
934 # IMPORTANT! The Squid needs to replace the Cache-Control header with
935 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
936 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
937 # start with a shorter timeout for initial testing
938 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
939 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
942 # We do want clients to cache if they can, but they *must* check for updates
943 # on revisiting the page.
944 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
945 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
946 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
948 if($this->mLastModified
) {
949 $response->header( "Last-Modified: {$this->mLastModified}" );
952 wfDebug( __METHOD__
. ": no caching **\n", false );
954 # In general, the absence of a last modified header should be enough to prevent
955 # the client from using its cache. We send a few other things just to make sure.
956 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
957 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
958 $response->header( 'Pragma: no-cache' );
960 wfRunHooks('CacheHeadersAfterSet', array( $this ) );
964 * Get the message associed with the HTTP response code $code
966 * @param $code Integer: status code
967 * @return String or null: message or null if $code is not in the list of
970 public static function getStatusMessage( $code ) {
971 static $statusMessage = array(
973 101 => 'Switching Protocols',
978 203 => 'Non-Authoritative Information',
980 205 => 'Reset Content',
981 206 => 'Partial Content',
982 207 => 'Multi-Status',
983 300 => 'Multiple Choices',
984 301 => 'Moved Permanently',
987 304 => 'Not Modified',
989 307 => 'Temporary Redirect',
990 400 => 'Bad Request',
991 401 => 'Unauthorized',
992 402 => 'Payment Required',
995 405 => 'Method Not Allowed',
996 406 => 'Not Acceptable',
997 407 => 'Proxy Authentication Required',
998 408 => 'Request Timeout',
1001 411 => 'Length Required',
1002 412 => 'Precondition Failed',
1003 413 => 'Request Entity Too Large',
1004 414 => 'Request-URI Too Large',
1005 415 => 'Unsupported Media Type',
1006 416 => 'Request Range Not Satisfiable',
1007 417 => 'Expectation Failed',
1008 422 => 'Unprocessable Entity',
1010 424 => 'Failed Dependency',
1011 500 => 'Internal Server Error',
1012 501 => 'Not Implemented',
1013 502 => 'Bad Gateway',
1014 503 => 'Service Unavailable',
1015 504 => 'Gateway Timeout',
1016 505 => 'HTTP Version Not Supported',
1017 507 => 'Insufficient Storage'
1019 return isset( $statusMessage[$code] ) ?
$statusMessage[$code] : null;
1023 * Finally, all the text has been munged and accumulated into
1024 * the object, let's actually output it:
1026 public function output() {
1027 global $wgUser, $wgOutputEncoding, $wgRequest;
1028 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
1029 global $wgUseAjax, $wgAjaxWatch;
1030 global $wgEnableMWSuggest, $wgUniversalEditButton;
1033 if( $this->mDoNothing
){
1036 wfProfileIn( __METHOD__
);
1037 if ( $this->mRedirect
!= '' ) {
1038 # Standards require redirect URLs to be absolute
1039 $this->mRedirect
= wfExpandUrl( $this->mRedirect
);
1040 if( $this->mRedirectCode
== '301' ||
$this->mRedirectCode
== '303' ) {
1041 if( !$wgDebugRedirects ) {
1042 $message = self
::getStatusMessage( $this->mRedirectCode
);
1043 $wgRequest->response()->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
1045 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1047 $this->sendCacheControl();
1049 $wgRequest->response()->header( "Content-Type: text/html; charset=utf-8" );
1050 if( $wgDebugRedirects ) {
1051 $url = htmlspecialchars( $this->mRedirect
);
1052 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1053 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1054 print "</body>\n</html>\n";
1056 $wgRequest->response()->header( 'Location: ' . $this->mRedirect
);
1058 wfProfileOut( __METHOD__
);
1060 } elseif ( $this->mStatusCode
) {
1061 $message = self
::getStatusMessage( $this->mStatusCode
);
1063 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
1066 $sk = $wgUser->getSkin();
1069 $this->addScriptFile( 'ajax.js' );
1071 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1073 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1074 $this->addScriptFile( 'ajaxwatch.js' );
1077 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ){
1078 $this->addScriptFile( 'mwsuggest.js' );
1082 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1083 $this->addScriptFile( 'rightclickedit.js' );
1086 if( $wgUniversalEditButton ) {
1087 if( isset( $wgArticle ) && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1088 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create' ) ) ) {
1089 // Original UniversalEditButton
1090 $msg = wfMsg('edit');
1091 $this->addLink( array(
1092 'rel' => 'alternate',
1093 'type' => 'application/x-wiki',
1095 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1097 // Alternate edit link
1098 $this->addLink( array(
1101 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1106 # Buffer output; final headers may depend on later processing
1109 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1110 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
1112 if ($this->mArticleBodyOnly
) {
1113 $this->out($this->mBodytext
);
1115 // Hook that allows last minute changes to the output page, e.g.
1116 // adding of CSS or Javascript by extensions.
1117 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1119 wfProfileIn( 'Output-skin' );
1120 $sk->outputPage( $this );
1121 wfProfileOut( 'Output-skin' );
1124 $this->sendCacheControl();
1126 wfProfileOut( __METHOD__
);
1130 * Actually output something with print(). Performs an iconv to the
1131 * output encoding, if needed.
1132 * @param string $ins The string to output
1134 public function out( $ins ) {
1135 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1136 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1139 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1140 if ( false === $outs ) { $outs = $ins; }
1148 public static function setEncodings() {
1149 global $wgInputEncoding, $wgOutputEncoding;
1152 $wgInputEncoding = strtolower( $wgInputEncoding );
1154 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
1155 $wgOutputEncoding = strtolower( $wgOutputEncoding );
1158 $wgOutputEncoding = $wgInputEncoding;
1162 * Deprecated, use wfReportTime() instead.
1166 public function reportTime() {
1167 wfDeprecated( __METHOD__
);
1168 $time = wfReportTime();
1173 * Produce a "user is blocked" page.
1175 * @param bool $return Whether to have a "return to $wgTitle" message or not.
1178 function blockedPage( $return = true ) {
1179 global $wgUser, $wgContLang, $wgLang;
1181 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1182 $this->setRobotPolicy( 'noindex,nofollow' );
1183 $this->setArticleRelated( false );
1185 $name = User
::whoIs( $wgUser->blockedBy() );
1186 $reason = $wgUser->blockedFor();
1187 if( $reason == '' ) {
1188 $reason = wfMsg( 'blockednoreason' );
1190 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $wgUser->mBlock
->mTimestamp
), true );
1193 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1195 $blockid = $wgUser->mBlock
->mId
;
1197 $blockExpiry = $wgUser->mBlock
->mExpiry
;
1198 if ( $blockExpiry == 'infinity' ) {
1199 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1200 // Search for localization in 'ipboptions'
1201 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1202 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1203 if ( strpos( $option, ":" ) === false )
1205 list( $show, $value ) = explode( ":", $option );
1206 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1207 $blockExpiry = $show;
1212 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1215 if ( $wgUser->mBlock
->mAuto
) {
1216 $msg = 'autoblockedtext';
1218 $msg = 'blockedtext';
1221 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1222 * This could be a username, an ip range, or a single ip. */
1223 $intended = $wgUser->mBlock
->mAddress
;
1225 $this->addWikiMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
1227 # Don't auto-return to special pages
1229 $return = $this->getTitle()->getNamespace() > -1 ?
$this->getTitle() : null;
1230 $this->returnToMain( null, $return );
1235 * Output a standard error page
1237 * @param string $title Message key for page title
1238 * @param string $msg Message key for page text
1239 * @param array $params Message parameters
1241 public function showErrorPage( $title, $msg, $params = array() ) {
1242 if ( $this->getTitle() ) {
1243 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1245 $this->setPageTitle( wfMsg( $title ) );
1246 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1247 $this->setRobotPolicy( 'noindex,nofollow' );
1248 $this->setArticleRelated( false );
1249 $this->enableClientCache( false );
1250 $this->mRedirect
= '';
1251 $this->mBodytext
= '';
1253 array_unshift( $params, 'parse' );
1254 array_unshift( $params, $msg );
1255 $this->addHTML( call_user_func_array( 'wfMsgExt', $params ) );
1257 $this->returnToMain();
1261 * Output a standard permission error page
1263 * @param array $errors Error message keys
1265 public function showPermissionsErrorPage( $errors, $action = null )
1267 $this->mDebugtext
.= 'Original title: ' .
1268 $this->getTitle()->getPrefixedText() . "\n";
1269 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1270 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1271 $this->setRobotPolicy( 'noindex,nofollow' );
1272 $this->setArticleRelated( false );
1273 $this->enableClientCache( false );
1274 $this->mRedirect
= '';
1275 $this->mBodytext
= '';
1276 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1280 public function errorpage( $title, $msg ) {
1281 wfDeprecated( __METHOD__
);
1282 throw new ErrorPageError( $title, $msg );
1286 * Display an error page indicating that a given version of MediaWiki is
1287 * required to use it
1289 * @param mixed $version The version of MediaWiki needed to use the page
1291 public function versionRequired( $version ) {
1292 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1293 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1294 $this->setRobotPolicy( 'noindex,nofollow' );
1295 $this->setArticleRelated( false );
1296 $this->mBodytext
= '';
1298 $this->addWikiMsg( 'versionrequiredtext', $version );
1299 $this->returnToMain();
1303 * Display an error page noting that a given permission bit is required.
1305 * @param string $permission key required
1307 public function permissionRequired( $permission ) {
1310 $this->setPageTitle( wfMsg( 'badaccess' ) );
1311 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1312 $this->setRobotPolicy( 'noindex,nofollow' );
1313 $this->setArticleRelated( false );
1314 $this->mBodytext
= '';
1316 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1317 User
::getGroupsWithPermission( $permission ) );
1319 $this->addWikiMsg( 'badaccess-groups',
1320 $wgLang->commaList( $groups ),
1323 $this->addWikiMsg( 'badaccess-group0' );
1325 $this->returnToMain();
1329 * Use permissionRequired.
1332 public function sysopRequired() {
1333 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
1337 * Use permissionRequired.
1340 public function developerRequired() {
1341 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
1345 * Produce the stock "please login to use the wiki" page
1347 public function loginToUse() {
1348 global $wgUser, $wgContLang;
1350 if( $wgUser->isLoggedIn() ) {
1351 $this->permissionRequired( 'read' );
1355 $skin = $wgUser->getSkin();
1357 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1358 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1359 $this->setRobotPolicy( 'noindex,nofollow' );
1360 $this->setArticleFlag( false );
1362 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1363 $loginLink = $skin->link(
1365 wfMsgHtml( 'loginreqlink' ),
1367 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
1368 array( 'known', 'noclasses' )
1370 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1371 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . "-->" );
1373 # Don't return to the main page if the user can't read it
1374 # otherwise we'll end up in a pointless loop
1375 $mainPage = Title
::newMainPage();
1376 if( $mainPage->userCanRead() )
1377 $this->returnToMain( null, $mainPage );
1381 public function databaseError( $fname, $sql, $error, $errno ) {
1382 throw new MWException( "OutputPage::databaseError is obsolete\n" );
1386 * @param array $errors An array of arrays returned by Title::getUserPermissionsErrors
1387 * @return string The wikitext error-messages, formatted into a list.
1389 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1390 if ($action == null) {
1391 $text = wfMsgNoTrans( 'permissionserrorstext', count($errors)). "\n\n";
1394 $action_desc = wfMsgNoTrans( "action-$action" );
1395 $text = wfMsgNoTrans( 'permissionserrorstext-withaction', count($errors), $action_desc ) . "\n\n";
1398 if (count( $errors ) > 1) {
1399 $text .= '<ul class="permissions-errors">' . "\n";
1401 foreach( $errors as $error )
1404 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1409 $text .= "<div class=\"permissions-errors\">\n" . call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) . "\n</div>";
1416 * Display a page stating that the Wiki is in read-only mode,
1417 * and optionally show the source of the page that the user
1418 * was trying to edit. Should only be called (for this
1419 * purpose) after wfReadOnly() has returned true.
1421 * For historical reasons, this function is _also_ used to
1422 * show the error message when a user tries to edit a page
1423 * they are not allowed to edit. (Unless it's because they're
1424 * blocked, then we show blockedPage() instead.) In this
1425 * case, the second parameter should be set to true and a list
1426 * of reasons supplied as the third parameter.
1428 * @todo Needs to be split into multiple functions.
1430 * @param string $source Source code to show (or null).
1431 * @param bool $protected Is this a permissions error?
1432 * @param array $reasons List of reasons for this error, as returned by Title::getUserPermissionsErrors().
1434 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1436 $skin = $wgUser->getSkin();
1438 $this->setRobotPolicy( 'noindex,nofollow' );
1439 $this->setArticleRelated( false );
1441 // If no reason is given, just supply a default "I can't let you do
1442 // that, Dave" message. Should only occur if called by legacy code.
1443 if ( $protected && empty($reasons) ) {
1444 $reasons[] = array( 'badaccess-group0' );
1447 if ( !empty($reasons) ) {
1448 // Permissions error
1450 $this->setPageTitle( wfMsg( 'viewsource' ) );
1459 array( 'known', 'noclasses' )
1464 $this->setPageTitle( wfMsg( 'badaccess' ) );
1466 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1468 // Wiki is read only
1469 $this->setPageTitle( wfMsg( 'readonly' ) );
1470 $reason = wfReadOnlyReason();
1471 $this->wrapWikiMsg( '<div class="mw-readonly-error">\n$1</div>', array( 'readonlytext', $reason ) );
1474 // Show source, if supplied
1475 if( is_string( $source ) ) {
1476 $this->addWikiMsg( 'viewsourcetext' );
1479 'id' => 'wpTextbox1',
1480 'name' => 'wpTextbox1',
1481 'cols' => $wgUser->getOption( 'cols' ),
1482 'rows' => $wgUser->getOption( 'rows' ),
1483 'readonly' => 'readonly'
1485 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
1487 // Show templates used by this article
1488 $skin = $wgUser->getSkin();
1489 $article = new Article( $this->getTitle() );
1490 $this->addHTML( "<div class='templatesUsed'>
1491 {$skin->formatTemplates( $article->getUsedTemplates() )}
1496 # If the title doesn't exist, it's fairly pointless to print a return
1497 # link to it. After all, you just tried editing it and couldn't, so
1498 # what's there to do there?
1499 if( $this->getTitle()->exists() ) {
1500 $this->returnToMain( null, $this->getTitle() );
1505 public function fatalError( $message ) {
1506 wfDeprecated( __METHOD__
);
1507 throw new FatalError( $message );
1511 public function unexpectedValueError( $name, $val ) {
1512 wfDeprecated( __METHOD__
);
1513 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1517 public function fileCopyError( $old, $new ) {
1518 wfDeprecated( __METHOD__
);
1519 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1523 public function fileRenameError( $old, $new ) {
1524 wfDeprecated( __METHOD__
);
1525 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1529 public function fileDeleteError( $name ) {
1530 wfDeprecated( __METHOD__
);
1531 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1535 public function fileNotFoundError( $name ) {
1536 wfDeprecated( __METHOD__
);
1537 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1540 public function showFatalError( $message ) {
1541 $this->setPageTitle( wfMsg( "internalerror" ) );
1542 $this->setRobotPolicy( "noindex,nofollow" );
1543 $this->setArticleRelated( false );
1544 $this->enableClientCache( false );
1545 $this->mRedirect
= '';
1546 $this->mBodytext
= $message;
1549 public function showUnexpectedValueError( $name, $val ) {
1550 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
1553 public function showFileCopyError( $old, $new ) {
1554 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
1557 public function showFileRenameError( $old, $new ) {
1558 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
1561 public function showFileDeleteError( $name ) {
1562 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
1565 public function showFileNotFoundError( $name ) {
1566 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1570 * Add a "return to" link pointing to a specified title
1572 * @param $title Title to link
1573 * @param $query String: query string
1575 public function addReturnTo( $title, $query = array() ) {
1577 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullUrl() ) );
1578 $link = wfMsgHtml( 'returnto', $wgUser->getSkin()->link(
1579 $title, null, array(), $query ) );
1580 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
1584 * Add a "return to" link pointing to a specified title,
1585 * or the title indicated in the request, or else the main page
1587 * @param $unused No longer used
1588 * @param $returnto Title or String to return to
1589 * @param $returntoquery String: query string for the return to link
1591 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
1594 if ( $returnto == null ) {
1595 $returnto = $wgRequest->getText( 'returnto' );
1598 if ( $returntoquery == null ) {
1599 $returntoquery = $wgRequest->getText( 'returntoquery' );
1602 if ( $returnto === '' ) {
1603 $returnto = Title
::newMainPage();
1606 if ( is_object( $returnto ) ) {
1607 $titleObj = $returnto;
1609 $titleObj = Title
::newFromText( $returnto );
1611 if ( !is_object( $titleObj ) ) {
1612 $titleObj = Title
::newMainPage();
1615 $this->addReturnTo( $titleObj, $returntoquery );
1619 * @return string The doctype, opening <html>, and head element.
1621 * @param $sk Skin The given Skin
1623 public function headElement( Skin
$sk, $includeStyle = true ) {
1624 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1625 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces, $wgHtml5Version;
1626 global $wgContLang, $wgUseTrackbacks, $wgStyleVersion, $wgHtml5, $wgWellFormedXml;
1627 global $wgUser, $wgRequest, $wgLang;
1629 $this->addMeta( "http:Content-Type", "$wgMimeType; charset={$wgOutputEncoding}" );
1630 if ( $sk->commonPrintStylesheet() ) {
1631 $this->addStyle( 'common/wikiprintable.css', 'print' );
1633 $sk->setupUserCss( $this );
1637 if( $wgMimeType == 'text/xml' ||
$wgMimeType == 'application/xhtml+xml' ||
$wgMimeType == 'application/xml' ) {
1638 $ret .= "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?" . ">\n";
1641 if ( $this->getHTMLTitle() == '' ) {
1642 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1645 $dir = $wgContLang->getDir();
1648 if ( $wgWellFormedXml ) {
1649 # Unknown elements and attributes are okay in XML, but unknown
1650 # named entities are well-formedness errors and will break XML
1651 # parsers. Thus we need a doctype that gives us appropriate
1652 # entity definitions. The HTML5 spec permits four legacy
1653 # doctypes as obsolete but conforming, so let's pick one of
1654 # those, although it makes our pages look like XHTML1 Strict.
1655 # Isn't compatibility great?
1656 $ret .= "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n";
1659 $ret .= "<!doctype html>\n";
1661 $ret .= "<html lang=\"$wgContLanguageCode\" dir=\"$dir\" ";
1662 if ( $wgHtml5Version ) $ret .= " version=\"$wgHtml5Version\" ";
1665 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\" \"$wgDTD\">\n";
1666 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1667 foreach($wgXhtmlNamespaces as $tag => $ns) {
1668 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1670 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" dir=\"$dir\">\n";
1674 $ret .= "<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n";
1675 $ret .= implode( "\n", array(
1676 $this->getHeadLinks(),
1677 $this->buildCssLinks(),
1678 $this->getHeadScripts( $sk ),
1679 $this->getHeadItems(),
1682 $ret .= Html
::inlineStyle( $sk->usercss
);
1685 if ($wgUseTrackbacks && $this->isArticleRelated())
1686 $ret .= $this->getTitle()->trackbackRDF();
1688 $ret .= "</head>\n";
1690 $bodyAttrs = array();
1692 # Crazy edit-on-double-click stuff
1693 $action = $wgRequest->getVal( 'action', 'view' );
1695 if ( $this->getTitle()->getNamespace() != NS_SPECIAL
1696 && !in_array( $action, array( 'edit', 'submit' ) )
1697 && $wgUser->getOption( 'editondblclick' ) ) {
1698 $bodyAttrs['ondblclick'] = "document.location = '" . Xml
::escapeJsString( $this->getTitle()->getEditURL() ) . "'";
1702 $bodyAttrs['class'] = "mediawiki $dir";
1704 if ( $wgLang->capitalizeAllNouns() ) {
1705 # A <body> class is probably not the best way to do this . . .
1706 $bodyAttrs['class'] .= ' capitalize-all-nouns';
1708 $bodyAttrs['class'] .= ' ns-' . $this->getTitle()->getNamespace();
1709 if ( $this->getTitle()->getNamespace() == NS_SPECIAL
) {
1710 $bodyAttrs['class'] .= ' ns-special';
1711 } elseif ( $this->getTitle()->isTalkPage() ) {
1712 $bodyAttrs['class'] .= ' ns-talk';
1714 $bodyAttrs['class'] .= ' ns-subject';
1716 $bodyAttrs['class'] .= ' ' . Sanitizer
::escapeClass( 'page-' . $this->getTitle()->getPrefixedText() );
1717 $bodyAttrs['class'] .= ' skin-' . Sanitizer
::escapeClass( $wgUser->getSkin()->getSkinName() );
1719 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
1725 * gets the global variables and mScripts
1727 * also adds userjs to the end if enabled:
1729 function getHeadScripts( Skin
$sk ) {
1730 global $wgUser, $wgRequest, $wgJsMimeType, $wgUseSiteJs;
1731 global $wgStylePath, $wgStyleVersion;
1733 $scripts = Skin
::makeGlobalVariablesScript( $sk->getSkinName() );
1734 $scripts .= Html
::linkedScript( "{$wgStylePath}/common/wikibits.js?$wgStyleVersion" );
1736 //add site JS if enabled:
1737 if( $wgUseSiteJs ) {
1738 $jsCache = $wgUser->isLoggedIn() ?
'&smaxage=0' : '';
1739 $this->addScriptFile( Skin
::makeUrl( '-',
1740 "action=raw$jsCache&gen=js&useskin=" .
1741 urlencode( $sk->getSkinName() )
1746 //add user js if enabled:
1747 if( $this->isUserJsAllowed() && $wgUser->isLoggedIn() ) {
1748 $action = $wgRequest->getVal( 'action', 'view' );
1749 if( $this->mTitle
&& $this->mTitle
->isJsSubpage() and $sk->userCanPreview( $action ) ) {
1750 # XXX: additional security check/prompt?
1751 $this->addInlineScript( $wgRequest->getText( 'wpTextbox1' ) );
1753 $userpage = $wgUser->getUserPage();
1754 $scriptpage = Title
::makeTitleSafe(
1756 $userpage->getDBkey() . '/' . $sk->getSkinName() . '.js'
1758 if ( $scriptpage && $scriptpage->exists() ) {
1759 $userjs = Skin
::makeUrl( $scriptpage->getPrefixedText(), 'action=raw&ctype=' . $wgJsMimeType );
1760 $this->addScriptFile( $userjs );
1765 $scripts .= "\n" . $this->mScripts
;
1769 protected function addDefaultMeta() {
1770 global $wgVersion, $wgHtml5;
1772 static $called = false;
1774 # Don't run this twice
1780 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); //bug 15835
1782 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
1784 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
1785 if( $p !== 'index,follow' ) {
1786 // http://www.robotstxt.org/wc/meta-user.html
1787 // Only show if it's different from the default robots policy
1788 $this->addMeta( 'robots', $p );
1791 if ( count( $this->mKeywords
) > 0 ) {
1793 "/<.*?" . ">/" => '',
1796 $this->addMeta( 'keywords', preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords
) ) );
1801 * @return string HTML tag links to be put in the header.
1803 public function getHeadLinks() {
1804 global $wgRequest, $wgFeed;
1806 // Ideally this should happen earlier, somewhere. :P
1807 $this->addDefaultMeta();
1811 foreach ( $this->mMetatags
as $tag ) {
1812 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
1814 $tag[0] = substr( $tag[0], 5 );
1818 $tags[] = Html
::element( 'meta',
1821 'content' => $tag[1] ) );
1823 foreach ( $this->mLinktags
as $tag ) {
1824 $tags[] = Html
::element( 'link', $tag );
1828 foreach( $this->getSyndicationLinks() as $format => $link ) {
1829 # Use the page name for the title (accessed through $wgTitle since
1830 # there's no other way). In principle, this could lead to issues
1831 # with having the same name for different feeds corresponding to
1832 # the same page, but we can't avoid that at this low a level.
1834 $tags[] = $this->feedLink(
1837 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
1838 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() ) );
1841 # Recent changes feed should appear on every page (except recentchanges,
1842 # that would be redundant). Put it after the per-page feed to avoid
1843 # changing existing behavior. It's still available, probably via a
1844 # menu in your browser. Some sites might have a different feed they'd
1845 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
1846 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
1847 # If so, use it instead.
1849 global $wgOverrideSiteFeed, $wgSitename, $wgAdvertisedFeedTypes;
1850 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
1852 if ( $wgOverrideSiteFeed ) {
1853 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
1854 $tags[] = $this->feedLink (
1856 htmlspecialchars( $feedUrl ),
1857 wfMsg( "site-{$type}-feed", $wgSitename ) );
1859 } elseif ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
1860 foreach ( $wgAdvertisedFeedTypes as $format ) {
1861 $tags[] = $this->feedLink(
1863 $rctitle->getLocalURL( "feed={$format}" ),
1864 wfMsg( "site-{$format}-feed", $wgSitename ) ); # For grep: 'site-rss-feed', 'site-atom-feed'.
1869 return implode( "\n", $tags );
1873 * Return URLs for each supported syndication format for this page.
1874 * @return array associating format keys with URLs
1876 public function getSyndicationLinks() {
1877 return $this->mFeedLinks
;
1881 * Generate a <link rel/> for an RSS feed.
1883 private function feedLink( $type, $url, $text ) {
1884 return Html
::element( 'link', array(
1885 'rel' => 'alternate',
1886 'type' => "application/$type+xml",
1892 * Add a local or specified stylesheet, with the given media options.
1893 * Meant primarily for internal use...
1895 * @param $media -- to specify a media type, 'screen', 'printable', 'handheld' or any.
1896 * @param $conditional -- for IE conditional comments, specifying an IE version
1897 * @param $dir -- set to 'rtl' or 'ltr' for direction-specific sheets
1899 public function addStyle( $style, $media='', $condition='', $dir='' ) {
1901 // Even though we expect the media type to be lowercase, but here we
1902 // force it to lowercase to be safe.
1904 $options['media'] = $media;
1906 $options['condition'] = $condition;
1908 $options['dir'] = $dir;
1909 $this->styles
[$style] = $options;
1913 * Adds inline CSS styles
1914 * @param $style_css Mixed: inline CSS
1916 public function addInlineStyle( $style_css ){
1917 $this->mScripts
.= Html
::inlineStyle( $style_css );
1921 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
1922 * These will be applied to various media & IE conditionals.
1924 public function buildCssLinks() {
1926 foreach( $this->styles
as $file => $options ) {
1927 $link = $this->styleLink( $file, $options );
1932 return implode( "\n", $links );
1935 protected function styleLink( $style, $options ) {
1938 if( isset( $options['dir'] ) ) {
1940 $siteDir = $wgContLang->getDir();
1941 if( $siteDir != $options['dir'] )
1945 if( isset( $options['media'] ) ) {
1946 $media = $this->transformCssMedia( $options['media'] );
1947 if( is_null( $media ) ) {
1954 if( substr( $style, 0, 1 ) == '/' ||
1955 substr( $style, 0, 5 ) == 'http:' ||
1956 substr( $style, 0, 6 ) == 'https:' ) {
1959 global $wgStylePath, $wgStyleVersion;
1960 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
1963 $link = Html
::linkedStyle( $url, $media );
1965 if( isset( $options['condition'] ) ) {
1966 $condition = htmlspecialchars( $options['condition'] );
1967 $link = "<!--[if $condition]>$link<![endif]-->";
1972 function transformCssMedia( $media ) {
1973 global $wgRequest, $wgHandheldForIPhone;
1975 // Switch in on-screen display for media testing
1977 'printable' => 'print',
1978 'handheld' => 'handheld',
1980 foreach( $switches as $switch => $targetMedia ) {
1981 if( $wgRequest->getBool( $switch ) ) {
1982 if( $media == $targetMedia ) {
1984 } elseif( $media == 'screen' ) {
1990 // Expand longer media queries as iPhone doesn't grok 'handheld'
1991 if( $wgHandheldForIPhone ) {
1992 $mediaAliases = array(
1993 'screen' => 'screen and (min-device-width: 481px)',
1994 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
1997 if( isset( $mediaAliases[$media] ) ) {
1998 $media = $mediaAliases[$media];
2006 * Turn off regular page output and return an error reponse
2007 * for when rate limiting has triggered.
2009 public function rateLimited() {
2011 $this->setPageTitle(wfMsg('actionthrottled'));
2012 $this->setRobotPolicy( 'noindex,follow' );
2013 $this->setArticleRelated( false );
2014 $this->enableClientCache( false );
2015 $this->mRedirect
= '';
2017 $this->setStatusCode(503);
2018 $this->addWikiMsg( 'actionthrottledtext' );
2020 $this->returnToMain( null, $this->getTitle() );
2024 * Show an "add new section" link?
2028 public function showNewSectionLink() {
2029 return $this->mNewSectionLink
;
2033 * Forcibly hide the new section link?
2037 public function forceHideNewSectionLink() {
2038 return $this->mHideNewSectionLink
;
2042 * Show a warning about slave lag
2044 * If the lag is higher than $wgSlaveLagCritical seconds,
2045 * then the warning is a bit more obvious. If the lag is
2046 * lower than $wgSlaveLagWarning, then no warning is shown.
2048 * @param int $lag Slave lag
2050 public function showLagWarning( $lag ) {
2051 global $wgSlaveLagWarning, $wgSlaveLagCritical, $wgLang;
2052 if( $lag >= $wgSlaveLagWarning ) {
2053 $message = $lag < $wgSlaveLagCritical
2056 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2057 $this->wrapWikiMsg( "$wrap\n", array( $message, $wgLang->formatNum( $lag ) ) );
2062 * Add a wikitext-formatted message to the output.
2063 * This is equivalent to:
2065 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2067 public function addWikiMsg( /*...*/ ) {
2068 $args = func_get_args();
2069 $name = array_shift( $args );
2070 $this->addWikiMsgArray( $name, $args );
2074 * Add a wikitext-formatted message to the output.
2075 * Like addWikiMsg() except the parameters are taken as an array
2076 * instead of a variable argument list.
2078 * $options is passed through to wfMsgExt(), see that function for details.
2080 public function addWikiMsgArray( $name, $args, $options = array() ) {
2081 $options[] = 'parse';
2082 $text = wfMsgExt( $name, $options, $args );
2083 $this->addHTML( $text );
2087 * This function takes a number of message/argument specifications, wraps them in
2088 * some overall structure, and then parses the result and adds it to the output.
2090 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
2091 * on. The subsequent arguments may either be strings, in which case they are the
2092 * message names, or arrays, in which case the first element is the message name,
2093 * and subsequent elements are the parameters to that message.
2095 * The special named parameter 'options' in a message specification array is passed
2096 * through to the $options parameter of wfMsgExt().
2098 * Don't use this for messages that are not in users interface language.
2102 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>", 'some-error' );
2106 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . '</div>' );
2108 * The newline after opening div is needed in some wikitext. See bug 19226.
2110 public function wrapWikiMsg( $wrap /*, ...*/ ) {
2111 $msgSpecs = func_get_args();
2112 array_shift( $msgSpecs );
2113 $msgSpecs = array_values( $msgSpecs );
2115 foreach ( $msgSpecs as $n => $spec ) {
2117 if ( is_array( $spec ) ) {
2119 $name = array_shift( $args );
2120 if ( isset( $args['options'] ) ) {
2121 $options = $args['options'];
2122 unset( $args['options'] );
2128 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
2130 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );
2134 * Include jQuery core. Use this to avoid loading it multiple times
2135 * before we get usable script loader.
2137 public function includeJQuery() {
2138 if ( $this->mIncludeJQuery
) return;
2139 $this->mIncludeJQuery
= true;
2141 global $wgScriptPath, $wgStyleVersion, $wgJsMimeType;
2144 'type' => $wgJsMimeType,
2145 'src' => "$wgScriptPath/js2/js2stopgap.min.js?$wgStyleVersion",
2147 $this->mScripts
= Html
::element( 'script', $params ) . "\n" . $this->mScripts
;