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, $wgJsMimeType;
126 if( substr( $file, 0, 1 ) == '/' ) {
129 $path = "{$wgStylePath}/common/{$file}";
132 Xml
::element( 'script',
134 'type' => $wgJsMimeType,
135 'src' => "$path?$wgStyleVersion",
143 * Add a self-contained script tag with the given contents
144 * @param string $script JavaScript text, no <script> tags
146 function addInlineScript( $script ) {
147 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
151 * Get all registered JS and CSS tags for the header.
153 function getScript() {
154 return $this->mScripts
. $this->getHeadItems();
157 function getHeadItems() {
159 foreach ( $this->mHeadItems
as $item ) {
165 function addHeadItem( $name, $value ) {
166 $this->mHeadItems
[$name] = $value;
169 function hasHeadItem( $name ) {
170 return isset( $this->mHeadItems
[$name] );
173 function setETag($tag) { $this->mETag
= $tag; }
174 function setArticleBodyOnly($only) { $this->mArticleBodyOnly
= $only; }
175 function getArticleBodyOnly() { return $this->mArticleBodyOnly
; }
177 function addLink( $linkarr ) {
178 # $linkarr should be an associative array of attributes. We'll escape on output.
179 array_push( $this->mLinktags
, $linkarr );
182 # Get all links added by extensions
183 function getExtStyle() {
184 return $this->mExtStyles
;
187 function addMetadataLink( $linkarr ) {
188 # note: buggy CC software only reads first "meta" link
189 static $haveMeta = false;
190 $linkarr['rel'] = ($haveMeta) ?
'alternate meta' : 'meta';
191 $this->addLink( $linkarr );
196 * checkLastModified tells the client to use the client-cached page if
197 * possible. If sucessful, the OutputPage is disabled so that
198 * any future call to OutputPage->output() have no effect.
200 * Side effect: sets mLastModified for Last-Modified header
202 * @return bool True iff cache-ok headers was sent.
204 function checkLastModified( $timestamp ) {
205 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
207 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
208 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
211 if( !$wgCachePages ) {
212 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
215 if( $wgUser->getOption( 'nocache' ) ) {
216 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
220 $timestamp = wfTimestamp( TS_MW
, $timestamp );
221 $modifiedTimes = array(
222 'page' => $timestamp,
223 'user' => $wgUser->getTouched(),
224 'epoch' => $wgCacheEpoch
226 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
228 $maxModified = max( $modifiedTimes );
229 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
231 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
232 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
238 foreach ( $modifiedTimes as $name => $value ) {
239 if ( $info !== '' ) {
242 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
245 # IE sends sizes after the date like this:
246 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
247 # this breaks strtotime().
248 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
250 wfSuppressWarnings(); // E_STRICT system time bitching
251 $clientHeaderTime = strtotime( $clientHeader );
253 if ( !$clientHeaderTime ) {
254 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
257 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
259 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
260 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
261 wfDebug( __METHOD__
. ": effective Last-Modified: " .
262 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
263 if( $clientHeaderTime < $maxModified ) {
264 wfDebug( __METHOD__
. ": STALE, $info\n", false );
269 # Give a 304 response code and disable body output
270 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
271 ini_set('zlib.output_compression', 0);
272 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
273 $this->sendCacheControl();
276 // Don't output a compressed blob when using ob_gzhandler;
277 // it's technically against HTTP spec and seems to confuse
278 // Firefox when the response gets split over two packets.
279 wfClearOutputBuffers();
284 function setPageTitleActionText( $text ) {
285 $this->mPageTitleActionText
= $text;
288 function getPageTitleActionText () {
289 if ( isset( $this->mPageTitleActionText
) ) {
290 return $this->mPageTitleActionText
;
295 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
297 * @param $policy string The literal string to output as the contents of
298 * the meta tag. Will be parsed according to the spec and output in
302 public function setRobotPolicy( $policy ) {
303 $policy = Article
::formatRobotPolicy( $policy );
305 if( isset( $policy['index'] ) ){
306 $this->setIndexPolicy( $policy['index'] );
308 if( isset( $policy['follow'] ) ){
309 $this->setFollowPolicy( $policy['follow'] );
314 * Set the index policy for the page, but leave the follow policy un-
317 * @param $policy string Either 'index' or 'noindex'.
320 public function setIndexPolicy( $policy ) {
321 $policy = trim( $policy );
322 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
323 $this->mIndexPolicy
= $policy;
328 * Set the follow policy for the page, but leave the index policy un-
331 * @param $policy string Either 'follow' or 'nofollow'.
334 public function setFollowPolicy( $policy ) {
335 $policy = trim( $policy );
336 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
337 $this->mFollowPolicy
= $policy;
342 * "HTML title" means the contents of <title>. It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
344 public function setHTMLTitle( $name ) {
345 $this->mHTMLtitle
= $name;
349 * "Page title" means the contents of <h1>. It is stored as a valid HTML fragment.
350 * This function allows good tags like <sup> in the <h1> tag, but not bad tags like <script>.
351 * This function automatically sets <title> to the same content as <h1> but with all tags removed.
352 * Bad tags that were escaped in <h1> will still be escaped in <title>, and good tags like <i> will be dropped entirely.
354 public function setPageTitle( $name ) {
355 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
356 # but leave "<i>foobar</i>" alone
357 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
358 $this->mPagetitle
= $nameWithTags;
360 $taction = $this->getPageTitleActionText();
361 if( !empty( $taction ) ) {
362 $name .= ' - '.$taction;
365 # change "<i>foo&bar</i>" to "foo&bar"
366 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer
::stripAllTags( $nameWithTags ) ) );
369 public function setTitle( $t ) {
373 public function getTitle() {
374 if ( $this->mTitle
instanceof Title
) {
375 return $this->mTitle
;
378 wfDebug( __METHOD__
. ' called and $mTitle is null. Return $wgTitle for sanity' );
384 public function getHTMLTitle() { return $this->mHTMLtitle
; }
385 public function getPageTitle() { return $this->mPagetitle
; }
386 public function setSubtitle( $str ) { $this->mSubtitle
= /*$this->parse(*/$str/*)*/; } // @bug 2514
387 public function appendSubtitle( $str ) { $this->mSubtitle
.= /*$this->parse(*/$str/*)*/; } // @bug 2514
388 public function getSubtitle() { return $this->mSubtitle
; }
389 public function isArticle() { return $this->mIsarticle
; }
390 public function setPrintable() { $this->mPrintable
= true; }
391 public function isPrintable() { return $this->mPrintable
; }
392 public function getFeedAppendQuery() { return $this->mFeedLinksAppendQuery
; }
393 public function disable() { $this->mDoNothing
= true; }
394 public function isDisabled() { return $this->mDoNothing
; }
396 public function setSyndicated( $show = true ) {
398 $this->setFeedAppendQuery( false );
400 $this->mFeedLinks
= array();
404 public function setFeedAppendQuery( $val ) {
405 global $wgFeedClasses, $wgAdvertisedFeedTypes;
407 $this->mFeedLinks
= array();
409 foreach ( $wgAdvertisedFeedTypes as $type ) {
410 $query = "feed=$type";
411 if ( is_string( $val ) ) {
412 $query .= '&' . $val;
414 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
418 public function addFeedLink( $format, $href ) {
419 $this->mFeedLinks
[$format] = $href;
422 public function isSyndicated() { return count($this->mFeedLinks
); }
424 public function setArticleRelated( $v ) {
425 $this->mIsArticleRelated
= $v;
427 $this->mIsarticle
= false;
430 public function setArticleFlag( $v ) {
431 $this->mIsarticle
= $v;
433 $this->mIsArticleRelated
= $v;
437 public function isArticleRelated() { return $this->mIsArticleRelated
; }
439 public function getLanguageLinks() { return $this->mLanguageLinks
; }
440 public function addLanguageLinks($newLinkArray) {
441 $this->mLanguageLinks +
= $newLinkArray;
443 public function setLanguageLinks($newLinkArray) {
444 $this->mLanguageLinks
= $newLinkArray;
447 public function getCategoryLinks() {
448 return $this->mCategoryLinks
;
451 public function getCategories() {
452 return $this->mCategories
;
456 * Add an array of categories, with names in the keys
458 public function addCategoryLinks( $categories ) {
459 global $wgUser, $wgContLang;
461 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
465 # Add the links to a LinkBatch
466 $arr = array( NS_CATEGORY
=> $categories );
468 $lb->setArray( $arr );
470 # Fetch existence plus the hiddencat property
471 $dbr = wfGetDB( DB_SLAVE
);
472 $pageTable = $dbr->tableName( 'page' );
473 $where = $lb->constructSet( 'page', $dbr );
474 $propsTable = $dbr->tableName( 'page_props' );
475 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, pp_value
476 FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
477 $res = $dbr->query( $sql, __METHOD__
);
479 # Add the results to the link cache
480 $lb->addResultToCache( LinkCache
::singleton(), $res );
482 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
483 $categories = array_combine( array_keys( $categories ),
484 array_fill( 0, count( $categories ), 'normal' ) );
486 # Mark hidden categories
487 foreach ( $res as $row ) {
488 if ( isset( $row->pp_value
) ) {
489 $categories[$row->page_title
] = 'hidden';
493 # Add the remaining categories to the skin
494 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
495 $sk = $wgUser->getSkin();
496 foreach ( $categories as $category => $type ) {
497 $origcategory = $category;
498 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
499 $wgContLang->findVariantLink( $category, $title, true );
500 if ( $category != $origcategory )
501 if ( array_key_exists( $category, $categories ) )
503 $text = $wgContLang->convertHtml( $title->getText() );
504 $this->mCategories
[] = $title->getText();
505 $this->mCategoryLinks
[$type][] = $sk->link( $title, $text );
510 public function setCategoryLinks($categories) {
511 $this->mCategoryLinks
= array();
512 $this->addCategoryLinks($categories);
515 public function suppressQuickbar() { $this->mSuppressQuickbar
= true; }
516 public function isQuickbarSuppressed() { return $this->mSuppressQuickbar
; }
518 public function disallowUserJs() { $this->mAllowUserJs
= false; }
519 public function isUserJsAllowed() { return $this->mAllowUserJs
; }
521 public function prependHTML( $text ) { $this->mBodytext
= $text . $this->mBodytext
; }
522 public function addHTML( $text ) { $this->mBodytext
.= $text; }
523 public function clearHTML() { $this->mBodytext
= ''; }
524 public function getHTML() { return $this->mBodytext
; }
525 public function debug( $text ) { $this->mDebugtext
.= $text; }
528 public function setParserOptions( $options ) {
529 wfDeprecated( __METHOD__
);
530 return $this->parserOptions( $options );
533 public function parserOptions( $options = null ) {
534 if ( !$this->mParserOptions
) {
535 $this->mParserOptions
= new ParserOptions
;
537 return wfSetVar( $this->mParserOptions
, $options );
541 * Set the revision ID which will be seen by the wiki text parser
542 * for things such as embedded {{REVISIONID}} variable use.
543 * @param mixed $revid an integer, or NULL
544 * @return mixed previous value
546 public function setRevisionId( $revid ) {
547 $val = is_null( $revid ) ?
null : intval( $revid );
548 return wfSetVar( $this->mRevisionId
, $val );
551 public function getRevisionId() {
552 return $this->mRevisionId
;
556 * Convert wikitext to HTML and add it to the buffer
557 * Default assumes that the current page title will
560 * @param string $text
561 * @param bool $linestart
563 public function addWikiText( $text, $linestart = true ) {
564 $title = $this->getTitle(); // Work arround E_STRICT
565 $this->addWikiTextTitle( $text, $title, $linestart );
568 public function addWikiTextWithTitle($text, &$title, $linestart = true) {
569 $this->addWikiTextTitle($text, $title, $linestart);
572 function addWikiTextTitleTidy($text, &$title, $linestart = true) {
573 $this->addWikiTextTitle( $text, $title, $linestart, true );
576 public function addWikiTextTitle($text, &$title, $linestart, $tidy = false) {
579 wfProfileIn( __METHOD__
);
581 wfIncrStats( 'pcache_not_possible' );
583 $popts = $this->parserOptions();
584 $oldTidy = $popts->setTidy( $tidy );
586 $parserOutput = $wgParser->parse( $text, $title, $popts,
587 $linestart, true, $this->mRevisionId
);
589 $popts->setTidy( $oldTidy );
591 $this->addParserOutput( $parserOutput );
593 wfProfileOut( __METHOD__
);
598 * @param ParserOutput object &$parserOutput
600 public function addParserOutputNoText( &$parserOutput ) {
601 global $wgExemptFromUserRobotsControl, $wgContentNamespaces;
603 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
604 $this->addCategoryLinks( $parserOutput->getCategories() );
605 $this->mNewSectionLink
= $parserOutput->getNewSection();
606 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
608 $this->mParseWarnings
= $parserOutput->getWarnings();
609 if ( $parserOutput->getCacheTime() == -1 ) {
610 $this->enableClientCache( false );
612 $this->mNoGallery
= $parserOutput->getNoGallery();
613 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
615 foreach ( (array)$parserOutput->mTemplateIds
as $ns => $dbks ) {
616 if ( isset( $this->mTemplateIds
[$ns] ) ) {
617 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
619 $this->mTemplateIds
[$ns] = $dbks;
623 $title = $parserOutput->getTitleText();
624 if ( $title != '' ) {
625 $this->setPageTitle( $title );
628 // Hooks registered in the object
629 global $wgParserOutputHooks;
630 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
631 list( $hookName, $data ) = $hookInfo;
632 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
633 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
637 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
642 * @param ParserOutput &$parserOutput
644 function addParserOutput( &$parserOutput ) {
645 $this->addParserOutputNoText( $parserOutput );
646 $text = $parserOutput->getText();
647 wfRunHooks( 'OutputPageBeforeHTML',array( &$this, &$text ) );
648 $this->addHTML( $text );
652 * Add wikitext to the buffer, assuming that this is the primary text for a page view
653 * Saves the text into the parser cache if possible.
655 * @param string $text
656 * @param Article $article
658 * @deprecated Use Article::outputWikitext
660 public function addPrimaryWikiText( $text, $article, $cache = true ) {
663 wfDeprecated( __METHOD__
);
665 $popts = $this->parserOptions();
666 $popts->setTidy(true);
667 $parserOutput = $wgParser->parse( $text, $article->mTitle
,
668 $popts, true, true, $this->mRevisionId
);
669 $popts->setTidy(false);
670 if ( $cache && $article && $parserOutput->getCacheTime() != -1 ) {
671 $parserCache = ParserCache
::singleton();
672 $parserCache->save( $parserOutput, $article, $popts);
675 $this->addParserOutput( $parserOutput );
679 * @deprecated use addWikiTextTidy()
681 public function addSecondaryWikiText( $text, $linestart = true ) {
682 wfDeprecated( __METHOD__
);
683 $this->addWikiTextTitleTidy($text, $this->getTitle(), $linestart);
687 * Add wikitext with tidy enabled
689 public function addWikiTextTidy( $text, $linestart = true ) {
690 $title = $this->getTitle();
691 $this->addWikiTextTitleTidy($text, $title, $linestart);
696 * Add the output of a QuickTemplate to the output buffer
698 * @param QuickTemplate $template
700 public function addTemplate( &$template ) {
702 $template->execute();
703 $this->addHTML( ob_get_contents() );
708 * Parse wikitext and return the HTML.
710 * @param string $text
711 * @param bool $linestart Is this the start of a line?
712 * @param bool $interface ??
714 public function parse( $text, $linestart = true, $interface = false ) {
716 if( is_null( $this->getTitle() ) ) {
717 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
719 $popts = $this->parserOptions();
720 if ( $interface) { $popts->setInterfaceMessage(true); }
721 $parserOutput = $wgParser->parse( $text, $this->getTitle(), $popts,
722 $linestart, true, $this->mRevisionId
);
723 if ( $interface) { $popts->setInterfaceMessage(false); }
724 return $parserOutput->getText();
727 /** Parse wikitext, strip paragraphs, and return the HTML. */
728 public function parseInline( $text, $linestart = true, $interface = false ) {
729 $parsed = $this->parse( $text, $linestart, $interface );
732 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
740 * @param Article $article
745 * @return bool True if successful, else false.
747 public function tryParserCache( &$article ) {
748 wfDeprecated( __METHOD__
);
749 $parserOutput = ParserCache
::singleton()->get( $article, $article->getParserOptions() );
751 if ($parserOutput !== false) {
752 $this->addParserOutput( $parserOutput );
760 * @param int $maxage Maximum cache time on the Squid, in seconds.
762 public function setSquidMaxage( $maxage ) {
763 $this->mSquidMaxage
= $maxage;
767 * Use enableClientCache(false) to force it to send nocache headers
770 public function enableClientCache( $state ) {
771 return wfSetVar( $this->mEnableClientCache
, $state );
774 function getCacheVaryCookies() {
775 global $wgCookiePrefix, $wgCacheVaryCookies;
777 if ( $cookies === null ) {
778 $cookies = array_merge(
780 "{$wgCookiePrefix}Token",
781 "{$wgCookiePrefix}LoggedOut",
786 wfRunHooks('GetCacheVaryCookies', array( $this, &$cookies ) );
791 function uncacheableBecauseRequestVars() {
793 return $wgRequest->getText('useskin', false) === false
794 && $wgRequest->getText('uselang', false) === false;
798 * Check if the request has a cache-varying cookie header
799 * If it does, it's very important that we don't allow public caching
801 function haveCacheVaryCookies() {
803 $cookieHeader = $wgRequest->getHeader( 'cookie' );
804 if ( $cookieHeader === false ) {
807 $cvCookies = $this->getCacheVaryCookies();
808 foreach ( $cvCookies as $cookieName ) {
809 # Check for a simple string match, like the way squid does it
810 if ( strpos( $cookieHeader, $cookieName ) ) {
811 wfDebug( __METHOD__
.": found $cookieName\n" );
815 wfDebug( __METHOD__
.": no cache-varying cookies found\n" );
819 public function addVaryHeader( $header, $option = null ) {
820 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
821 $this->mVaryHeader
[$header] = $option;
823 elseif( is_array( $option ) ) {
824 if( is_array( $this->mVaryHeader
[$header] ) ) {
825 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
828 $this->mVaryHeader
[$header] = $option;
831 $this->mVaryHeader
[$header] = array_unique( $this->mVaryHeader
[$header] );
834 /** Get a complete X-Vary-Options header */
835 public function getXVO() {
836 $cvCookies = $this->getCacheVaryCookies();
838 $cookiesOption = array();
839 foreach ( $cvCookies as $cookieName ) {
840 $cookiesOption[] = 'string-contains=' . $cookieName;
842 $this->addVaryHeader( 'Cookie', $cookiesOption );
845 foreach( $this->mVaryHeader
as $header => $option ) {
846 $newheader = $header;
847 if( is_array( $option ) )
848 $newheader .= ';' . implode( ';', $option );
849 $headers[] = $newheader;
851 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
856 /** bug 21672: Add Accept-Language to Vary and XVO headers
857 if there's no 'variant' parameter existed in GET.
860 /w/index.php?title=Main_page should always be served; but
861 /w/index.php?title=Main_page&variant=zh-cn should never be served.
863 patched by Liangent and Philip */
864 function addAcceptLanguage() {
865 global $wgRequest, $wgContLang;
866 if( !$wgRequest->getCheck('variant') && $wgContLang->hasVariants() ) {
867 $variants = $wgContLang->getVariants();
869 foreach ( $variants as $variant ) {
870 if( $variant === $wgContLang->getCode() )
873 $aloption[] = "string-contains=$variant";
875 $this->addVaryHeader( 'Accept-Language', $aloption );
879 public function sendCacheControl() {
880 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest, $wgUseXVO;
882 $response = $wgRequest->response();
883 if ($wgUseETag && $this->mETag
)
884 $response->header("ETag: $this->mETag");
886 $this->addAcceptLanguage();
888 # don't serve compressed data to clients who can't handle it
889 # maintain different caches for logged-in users and non-logged in ones
890 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) ) );
893 # Add an X-Vary-Options header for Squid with Wikimedia patches
894 $response->header( $this->getXVO() );
897 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
898 if( $wgUseSquid && session_id() == '' &&
899 ! $this->isPrintable() && $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies() )
902 # We'll purge the proxy cache explicitly, but require end user agents
903 # to revalidate against the proxy on each visit.
904 # Surrogate-Control controls our Squid, Cache-Control downstream caches
905 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
906 # start with a shorter timeout for initial testing
907 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
908 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
909 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
911 # We'll purge the proxy cache for anons explicitly, but require end user agents
912 # to revalidate against the proxy on each visit.
913 # IMPORTANT! The Squid needs to replace the Cache-Control header with
914 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
915 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
916 # start with a shorter timeout for initial testing
917 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
918 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
921 # We do want clients to cache if they can, but they *must* check for updates
922 # on revisiting the page.
923 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
924 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
925 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
927 if($this->mLastModified
) {
928 $response->header( "Last-Modified: {$this->mLastModified}" );
931 wfDebug( __METHOD__
. ": no caching **\n", false );
933 # In general, the absence of a last modified header should be enough to prevent
934 # the client from using its cache. We send a few other things just to make sure.
935 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
936 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
937 $response->header( 'Pragma: no-cache' );
939 wfRunHooks('CacheHeadersAfterSet', array( $this ) );
943 * Get the message associed with the HTTP response code $code
945 * @param $code Integer: status code
946 * @return String or null: message or null if $code is not in the list of
949 public static function getStatusMessage( $code ) {
950 static $statusMessage = array(
952 101 => 'Switching Protocols',
957 203 => 'Non-Authoritative Information',
959 205 => 'Reset Content',
960 206 => 'Partial Content',
961 207 => 'Multi-Status',
962 300 => 'Multiple Choices',
963 301 => 'Moved Permanently',
966 304 => 'Not Modified',
968 307 => 'Temporary Redirect',
969 400 => 'Bad Request',
970 401 => 'Unauthorized',
971 402 => 'Payment Required',
974 405 => 'Method Not Allowed',
975 406 => 'Not Acceptable',
976 407 => 'Proxy Authentication Required',
977 408 => 'Request Timeout',
980 411 => 'Length Required',
981 412 => 'Precondition Failed',
982 413 => 'Request Entity Too Large',
983 414 => 'Request-URI Too Large',
984 415 => 'Unsupported Media Type',
985 416 => 'Request Range Not Satisfiable',
986 417 => 'Expectation Failed',
987 422 => 'Unprocessable Entity',
989 424 => 'Failed Dependency',
990 500 => 'Internal Server Error',
991 501 => 'Not Implemented',
992 502 => 'Bad Gateway',
993 503 => 'Service Unavailable',
994 504 => 'Gateway Timeout',
995 505 => 'HTTP Version Not Supported',
996 507 => 'Insufficient Storage'
998 return isset( $statusMessage[$code] ) ?
$statusMessage[$code] : null;
1002 * Finally, all the text has been munged and accumulated into
1003 * the object, let's actually output it:
1005 public function output() {
1006 global $wgUser, $wgOutputEncoding, $wgRequest;
1007 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
1008 global $wgUseAjax, $wgAjaxWatch;
1009 global $wgEnableMWSuggest, $wgUniversalEditButton;
1012 if( $this->mDoNothing
){
1015 wfProfileIn( __METHOD__
);
1016 if ( $this->mRedirect
!= '' ) {
1017 # Standards require redirect URLs to be absolute
1018 $this->mRedirect
= wfExpandUrl( $this->mRedirect
);
1019 if( $this->mRedirectCode
== '301' ||
$this->mRedirectCode
== '303' ) {
1020 if( !$wgDebugRedirects ) {
1021 $message = self
::getStatusMessage( $this->mRedirectCode
);
1022 $wgRequest->response()->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
1024 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1026 $this->sendCacheControl();
1028 $wgRequest->response()->header( "Content-Type: text/html; charset=utf-8" );
1029 if( $wgDebugRedirects ) {
1030 $url = htmlspecialchars( $this->mRedirect
);
1031 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1032 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1033 print "</body>\n</html>\n";
1035 $wgRequest->response()->header( 'Location: ' . $this->mRedirect
);
1037 wfProfileOut( __METHOD__
);
1039 } elseif ( $this->mStatusCode
) {
1040 $message = self
::getStatusMessage( $this->mStatusCode
);
1042 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
1045 $sk = $wgUser->getSkin();
1048 $this->addScriptFile( 'ajax.js' );
1050 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1052 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1053 $this->addScriptFile( 'ajaxwatch.js' );
1056 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ){
1057 $this->addScriptFile( 'mwsuggest.js' );
1061 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1062 $this->addScriptFile( 'rightclickedit.js' );
1065 if( $wgUniversalEditButton ) {
1066 if( isset( $wgArticle ) && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1067 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create' ) ) ) {
1068 // Original UniversalEditButton
1069 $msg = wfMsg('edit');
1070 $this->addLink( array(
1071 'rel' => 'alternate',
1072 'type' => 'application/x-wiki',
1074 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1076 // Alternate edit link
1077 $this->addLink( array(
1080 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1085 # Buffer output; final headers may depend on later processing
1088 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1089 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
1091 if ($this->mArticleBodyOnly
) {
1092 $this->out($this->mBodytext
);
1094 // Hook that allows last minute changes to the output page, e.g.
1095 // adding of CSS or Javascript by extensions.
1096 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1098 wfProfileIn( 'Output-skin' );
1099 $sk->outputPage( $this );
1100 wfProfileOut( 'Output-skin' );
1103 $this->sendCacheControl();
1105 wfProfileOut( __METHOD__
);
1109 * Actually output something with print(). Performs an iconv to the
1110 * output encoding, if needed.
1111 * @param string $ins The string to output
1113 public function out( $ins ) {
1114 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1115 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1118 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1119 if ( false === $outs ) { $outs = $ins; }
1127 public static function setEncodings() {
1128 global $wgInputEncoding, $wgOutputEncoding;
1131 $wgInputEncoding = strtolower( $wgInputEncoding );
1133 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
1134 $wgOutputEncoding = strtolower( $wgOutputEncoding );
1137 $wgOutputEncoding = $wgInputEncoding;
1141 * Deprecated, use wfReportTime() instead.
1145 public function reportTime() {
1146 wfDeprecated( __METHOD__
);
1147 $time = wfReportTime();
1152 * Produce a "user is blocked" page.
1154 * @param bool $return Whether to have a "return to $wgTitle" message or not.
1157 function blockedPage( $return = true ) {
1158 global $wgUser, $wgContLang, $wgLang;
1160 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1161 $this->setRobotPolicy( 'noindex,nofollow' );
1162 $this->setArticleRelated( false );
1164 $name = User
::whoIs( $wgUser->blockedBy() );
1165 $reason = $wgUser->blockedFor();
1166 if( $reason == '' ) {
1167 $reason = wfMsg( 'blockednoreason' );
1169 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $wgUser->mBlock
->mTimestamp
), true );
1172 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1174 $blockid = $wgUser->mBlock
->mId
;
1176 $blockExpiry = $wgUser->mBlock
->mExpiry
;
1177 if ( $blockExpiry == 'infinity' ) {
1178 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1179 // Search for localization in 'ipboptions'
1180 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1181 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1182 if ( strpos( $option, ":" ) === false )
1184 list( $show, $value ) = explode( ":", $option );
1185 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1186 $blockExpiry = $show;
1191 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1194 if ( $wgUser->mBlock
->mAuto
) {
1195 $msg = 'autoblockedtext';
1197 $msg = 'blockedtext';
1200 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1201 * This could be a username, an ip range, or a single ip. */
1202 $intended = $wgUser->mBlock
->mAddress
;
1204 $this->addWikiMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
1206 # Don't auto-return to special pages
1208 $return = $this->getTitle()->getNamespace() > -1 ?
$this->getTitle() : null;
1209 $this->returnToMain( null, $return );
1214 * Output a standard error page
1216 * @param string $title Message key for page title
1217 * @param string $msg Message key for page text
1218 * @param array $params Message parameters
1220 public function showErrorPage( $title, $msg, $params = array() ) {
1221 if ( $this->getTitle() ) {
1222 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1224 $this->setPageTitle( wfMsg( $title ) );
1225 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1226 $this->setRobotPolicy( 'noindex,nofollow' );
1227 $this->setArticleRelated( false );
1228 $this->enableClientCache( false );
1229 $this->mRedirect
= '';
1230 $this->mBodytext
= '';
1232 array_unshift( $params, 'parse' );
1233 array_unshift( $params, $msg );
1234 $this->addHTML( call_user_func_array( 'wfMsgExt', $params ) );
1236 $this->returnToMain();
1240 * Output a standard permission error page
1242 * @param array $errors Error message keys
1244 public function showPermissionsErrorPage( $errors, $action = null )
1246 $this->mDebugtext
.= 'Original title: ' .
1247 $this->getTitle()->getPrefixedText() . "\n";
1248 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1249 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1250 $this->setRobotPolicy( 'noindex,nofollow' );
1251 $this->setArticleRelated( false );
1252 $this->enableClientCache( false );
1253 $this->mRedirect
= '';
1254 $this->mBodytext
= '';
1255 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1259 public function errorpage( $title, $msg ) {
1260 wfDeprecated( __METHOD__
);
1261 throw new ErrorPageError( $title, $msg );
1265 * Display an error page indicating that a given version of MediaWiki is
1266 * required to use it
1268 * @param mixed $version The version of MediaWiki needed to use the page
1270 public function versionRequired( $version ) {
1271 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1272 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1273 $this->setRobotPolicy( 'noindex,nofollow' );
1274 $this->setArticleRelated( false );
1275 $this->mBodytext
= '';
1277 $this->addWikiMsg( 'versionrequiredtext', $version );
1278 $this->returnToMain();
1282 * Display an error page noting that a given permission bit is required.
1284 * @param string $permission key required
1286 public function permissionRequired( $permission ) {
1289 $this->setPageTitle( wfMsg( 'badaccess' ) );
1290 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1291 $this->setRobotPolicy( 'noindex,nofollow' );
1292 $this->setArticleRelated( false );
1293 $this->mBodytext
= '';
1295 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1296 User
::getGroupsWithPermission( $permission ) );
1298 $this->addWikiMsg( 'badaccess-groups',
1299 $wgLang->commaList( $groups ),
1302 $this->addWikiMsg( 'badaccess-group0' );
1304 $this->returnToMain();
1308 * Use permissionRequired.
1311 public function sysopRequired() {
1312 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
1316 * Use permissionRequired.
1319 public function developerRequired() {
1320 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
1324 * Produce the stock "please login to use the wiki" page
1326 public function loginToUse() {
1327 global $wgUser, $wgContLang;
1329 if( $wgUser->isLoggedIn() ) {
1330 $this->permissionRequired( 'read' );
1334 $skin = $wgUser->getSkin();
1336 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1337 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1338 $this->setRobotPolicy( 'noindex,nofollow' );
1339 $this->setArticleFlag( false );
1341 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1342 $loginLink = $skin->link(
1344 wfMsgHtml( 'loginreqlink' ),
1346 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
1347 array( 'known', 'noclasses' )
1349 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1350 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . "-->" );
1352 # Don't return to the main page if the user can't read it
1353 # otherwise we'll end up in a pointless loop
1354 $mainPage = Title
::newMainPage();
1355 if( $mainPage->userCanRead() )
1356 $this->returnToMain( null, $mainPage );
1360 public function databaseError( $fname, $sql, $error, $errno ) {
1361 throw new MWException( "OutputPage::databaseError is obsolete\n" );
1365 * @param array $errors An array of arrays returned by Title::getUserPermissionsErrors
1366 * @return string The wikitext error-messages, formatted into a list.
1368 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1369 if ($action == null) {
1370 $text = wfMsgNoTrans( 'permissionserrorstext', count($errors)). "\n\n";
1373 $action_desc = wfMsgNoTrans( "action-$action" );
1374 $text = wfMsgNoTrans( 'permissionserrorstext-withaction', count($errors), $action_desc ) . "\n\n";
1377 if (count( $errors ) > 1) {
1378 $text .= '<ul class="permissions-errors">' . "\n";
1380 foreach( $errors as $error )
1383 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1388 $text .= "<div class=\"permissions-errors\">\n" . call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) . "\n</div>";
1395 * Display a page stating that the Wiki is in read-only mode,
1396 * and optionally show the source of the page that the user
1397 * was trying to edit. Should only be called (for this
1398 * purpose) after wfReadOnly() has returned true.
1400 * For historical reasons, this function is _also_ used to
1401 * show the error message when a user tries to edit a page
1402 * they are not allowed to edit. (Unless it's because they're
1403 * blocked, then we show blockedPage() instead.) In this
1404 * case, the second parameter should be set to true and a list
1405 * of reasons supplied as the third parameter.
1407 * @todo Needs to be split into multiple functions.
1409 * @param string $source Source code to show (or null).
1410 * @param bool $protected Is this a permissions error?
1411 * @param array $reasons List of reasons for this error, as returned by Title::getUserPermissionsErrors().
1413 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1415 $skin = $wgUser->getSkin();
1417 $this->setRobotPolicy( 'noindex,nofollow' );
1418 $this->setArticleRelated( false );
1420 // If no reason is given, just supply a default "I can't let you do
1421 // that, Dave" message. Should only occur if called by legacy code.
1422 if ( $protected && empty($reasons) ) {
1423 $reasons[] = array( 'badaccess-group0' );
1426 if ( !empty($reasons) ) {
1427 // Permissions error
1429 $this->setPageTitle( wfMsg( 'viewsource' ) );
1438 array( 'known', 'noclasses' )
1443 $this->setPageTitle( wfMsg( 'badaccess' ) );
1445 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1447 // Wiki is read only
1448 $this->setPageTitle( wfMsg( 'readonly' ) );
1449 $reason = wfReadOnlyReason();
1450 $this->wrapWikiMsg( '<div class="mw-readonly-error">\n$1</div>', array( 'readonlytext', $reason ) );
1453 // Show source, if supplied
1454 if( is_string( $source ) ) {
1455 $this->addWikiMsg( 'viewsourcetext' );
1458 'id' => 'wpTextbox1',
1459 'name' => 'wpTextbox1',
1460 'cols' => $wgUser->getOption( 'cols' ),
1461 'rows' => $wgUser->getOption( 'rows' ),
1462 'readonly' => 'readonly'
1464 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
1466 // Show templates used by this article
1467 $skin = $wgUser->getSkin();
1468 $article = new Article( $this->getTitle() );
1469 $this->addHTML( "<div class='templatesUsed'>
1470 {$skin->formatTemplates( $article->getUsedTemplates() )}
1475 # If the title doesn't exist, it's fairly pointless to print a return
1476 # link to it. After all, you just tried editing it and couldn't, so
1477 # what's there to do there?
1478 if( $this->getTitle()->exists() ) {
1479 $this->returnToMain( null, $this->getTitle() );
1484 public function fatalError( $message ) {
1485 wfDeprecated( __METHOD__
);
1486 throw new FatalError( $message );
1490 public function unexpectedValueError( $name, $val ) {
1491 wfDeprecated( __METHOD__
);
1492 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1496 public function fileCopyError( $old, $new ) {
1497 wfDeprecated( __METHOD__
);
1498 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1502 public function fileRenameError( $old, $new ) {
1503 wfDeprecated( __METHOD__
);
1504 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1508 public function fileDeleteError( $name ) {
1509 wfDeprecated( __METHOD__
);
1510 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1514 public function fileNotFoundError( $name ) {
1515 wfDeprecated( __METHOD__
);
1516 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1519 public function showFatalError( $message ) {
1520 $this->setPageTitle( wfMsg( "internalerror" ) );
1521 $this->setRobotPolicy( "noindex,nofollow" );
1522 $this->setArticleRelated( false );
1523 $this->enableClientCache( false );
1524 $this->mRedirect
= '';
1525 $this->mBodytext
= $message;
1528 public function showUnexpectedValueError( $name, $val ) {
1529 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
1532 public function showFileCopyError( $old, $new ) {
1533 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
1536 public function showFileRenameError( $old, $new ) {
1537 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
1540 public function showFileDeleteError( $name ) {
1541 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
1544 public function showFileNotFoundError( $name ) {
1545 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1549 * Add a "return to" link pointing to a specified title
1551 * @param $title Title to link
1552 * @param $query String: query string
1554 public function addReturnTo( $title, $query = array() ) {
1556 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullUrl() ) );
1557 $link = wfMsgHtml( 'returnto', $wgUser->getSkin()->link(
1558 $title, null, array(), $query ) );
1559 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
1563 * Add a "return to" link pointing to a specified title,
1564 * or the title indicated in the request, or else the main page
1566 * @param $unused No longer used
1567 * @param $returnto Title or String to return to
1568 * @param $returntoquery String: query string for the return to link
1570 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
1573 if ( $returnto == null ) {
1574 $returnto = $wgRequest->getText( 'returnto' );
1577 if ( $returntoquery == null ) {
1578 $returntoquery = $wgRequest->getText( 'returntoquery' );
1581 if ( $returnto === '' ) {
1582 $returnto = Title
::newMainPage();
1585 if ( is_object( $returnto ) ) {
1586 $titleObj = $returnto;
1588 $titleObj = Title
::newFromText( $returnto );
1590 if ( !is_object( $titleObj ) ) {
1591 $titleObj = Title
::newMainPage();
1594 $this->addReturnTo( $titleObj, $returntoquery );
1598 * @return string The doctype, opening <html>, and head element.
1600 * @param $sk Skin The given Skin
1602 public function headElement( Skin
$sk, $includeStyle = true ) {
1603 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1604 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces, $wgHtml5Version;
1605 global $wgContLang, $wgUseTrackbacks, $wgStyleVersion, $wgHtml5, $wgWellFormedXml;
1606 global $wgUser, $wgRequest, $wgLang;
1608 $this->addMeta( "http:Content-Type", "$wgMimeType; charset={$wgOutputEncoding}" );
1609 if ( $sk->commonPrintStylesheet() ) {
1610 $this->addStyle( 'common/wikiprintable.css', 'print' );
1612 $sk->setupUserCss( $this );
1616 if( $wgMimeType == 'text/xml' ||
$wgMimeType == 'application/xhtml+xml' ||
$wgMimeType == 'application/xml' ) {
1617 $ret .= "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?" . ">\n";
1620 if ( $this->getHTMLTitle() == '' ) {
1621 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1624 $dir = $wgContLang->getDir();
1627 if ( $wgWellFormedXml ) {
1628 # Unknown elements and attributes are okay in XML, but unknown
1629 # named entities are well-formedness errors and will break XML
1630 # parsers. Thus we need a doctype that gives us appropriate
1631 # entity definitions. The HTML5 spec permits four legacy
1632 # doctypes as obsolete but conforming, so let's pick one of
1633 # those, although it makes our pages look like XHTML1 Strict.
1634 # Isn't compatibility great?
1635 $ret .= "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n";
1638 $ret .= "<!doctype html>\n";
1640 $ret .= "<html lang=\"$wgContLanguageCode\" dir=\"$dir\" ";
1641 if ( $wgHtml5Version ) $ret .= " version=\"$wgHtml5Version\" ";
1644 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\" \"$wgDTD\">\n";
1645 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1646 foreach($wgXhtmlNamespaces as $tag => $ns) {
1647 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1649 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" dir=\"$dir\">\n";
1653 $ret .= "<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n";
1654 $ret .= implode( "\n", array(
1655 $this->getHeadLinks(),
1656 $this->buildCssLinks(),
1657 $this->getHeadScripts( $sk ),
1658 $this->getHeadItems(),
1661 $ret .= Html
::inlineStyle( $sk->usercss
);
1664 if ($wgUseTrackbacks && $this->isArticleRelated())
1665 $ret .= $this->getTitle()->trackbackRDF();
1667 $ret .= "</head>\n";
1669 $bodyAttrs = array();
1671 # Crazy edit-on-double-click stuff
1672 $action = $wgRequest->getVal( 'action', 'view' );
1674 if ( $this->getTitle()->getNamespace() != NS_SPECIAL
1675 && !in_array( $action, array( 'edit', 'submit' ) )
1676 && $wgUser->getOption( 'editondblclick' ) ) {
1677 $bodyAttrs['ondblclick'] = "document.location = '" . Xml
::escapeJsString( $this->getTitle()->getEditURL() ) . "'";
1681 $bodyAttrs['class'] = "mediawiki $dir";
1683 if ( $wgLang->capitalizeAllNouns() ) {
1684 # A <body> class is probably not the best way to do this . . .
1685 $bodyAttrs['class'] .= ' capitalize-all-nouns';
1687 $bodyAttrs['class'] .= ' ns-' . $this->getTitle()->getNamespace();
1688 if ( $this->getTitle()->getNamespace() == NS_SPECIAL
) {
1689 $bodyAttrs['class'] .= ' ns-special';
1690 } elseif ( $this->getTitle()->isTalkPage() ) {
1691 $bodyAttrs['class'] .= ' ns-talk';
1693 $bodyAttrs['class'] .= ' ns-subject';
1695 $bodyAttrs['class'] .= ' ' . Sanitizer
::escapeClass( 'page-' . $this->getTitle()->getPrefixedText() );
1696 $bodyAttrs['class'] .= ' skin-' . Sanitizer
::escapeClass( $wgUser->getSkin()->getSkinName() );
1698 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
1704 * gets the global variables and mScripts
1706 * also adds userjs to the end if enabled:
1708 function getHeadScripts( Skin
$sk ) {
1709 global $wgUser, $wgRequest, $wgJsMimeType, $wgUseSiteJs;
1710 global $wgStylePath, $wgStyleVersion;
1712 $scripts = Skin
::makeGlobalVariablesScript( $sk->getSkinName() );
1713 $scripts .= Html
::linkedScript( "{$wgStylePath}/common/wikibits.js?$wgStyleVersion" );
1715 //add site JS if enabled:
1716 if( $wgUseSiteJs ) {
1717 $jsCache = $wgUser->isLoggedIn() ?
'&smaxage=0' : '';
1718 $this->addScriptFile( Skin
::makeUrl( '-',
1719 "action=raw$jsCache&gen=js&useskin=" .
1720 urlencode( $sk->getSkinName() )
1725 //add user js if enabled:
1726 if( $this->isUserJsAllowed() && $wgUser->isLoggedIn() ) {
1727 $action = $wgRequest->getVal( 'action', 'view' );
1728 if( $this->mTitle
&& $this->mTitle
->isJsSubpage() and $sk->userCanPreview( $action ) ) {
1729 # XXX: additional security check/prompt?
1730 $this->addInlineScript( $wgRequest->getText( 'wpTextbox1' ) );
1732 $userpage = $wgUser->getUserPage();
1733 $scriptpage = Title
::makeTitleSafe(
1735 $userpage->getDBkey() . '/' . $sk->getSkinName() . '.js'
1737 if ( $scriptpage && $scriptpage->exists() ) {
1738 $userjs = Skin
::makeUrl( $scriptpage->getPrefixedText(), 'action=raw&ctype=' . $wgJsMimeType );
1739 $this->addScriptFile( $userjs );
1744 $scripts .= "\n" . $this->mScripts
;
1748 protected function addDefaultMeta() {
1749 global $wgVersion, $wgHtml5;
1751 static $called = false;
1753 # Don't run this twice
1759 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); //bug 15835
1761 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
1763 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
1764 if( $p !== 'index,follow' ) {
1765 // http://www.robotstxt.org/wc/meta-user.html
1766 // Only show if it's different from the default robots policy
1767 $this->addMeta( 'robots', $p );
1770 if ( count( $this->mKeywords
) > 0 ) {
1772 "/<.*?" . ">/" => '',
1775 $this->addMeta( 'keywords', preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords
) ) );
1780 * @return string HTML tag links to be put in the header.
1782 public function getHeadLinks() {
1783 global $wgRequest, $wgFeed;
1785 // Ideally this should happen earlier, somewhere. :P
1786 $this->addDefaultMeta();
1790 foreach ( $this->mMetatags
as $tag ) {
1791 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
1793 $tag[0] = substr( $tag[0], 5 );
1797 $tags[] = Html
::element( 'meta',
1800 'content' => $tag[1] ) );
1802 foreach ( $this->mLinktags
as $tag ) {
1803 $tags[] = Html
::element( 'link', $tag );
1807 foreach( $this->getSyndicationLinks() as $format => $link ) {
1808 # Use the page name for the title (accessed through $wgTitle since
1809 # there's no other way). In principle, this could lead to issues
1810 # with having the same name for different feeds corresponding to
1811 # the same page, but we can't avoid that at this low a level.
1813 $tags[] = $this->feedLink(
1816 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
1817 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() ) );
1820 # Recent changes feed should appear on every page (except recentchanges,
1821 # that would be redundant). Put it after the per-page feed to avoid
1822 # changing existing behavior. It's still available, probably via a
1823 # menu in your browser. Some sites might have a different feed they'd
1824 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
1825 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
1826 # If so, use it instead.
1828 global $wgOverrideSiteFeed, $wgSitename, $wgFeedClasses, $wgAdvertisedFeedTypes;
1829 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
1831 if ( $wgOverrideSiteFeed ) {
1832 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
1833 $tags[] = $this->feedLink (
1835 htmlspecialchars( $feedUrl ),
1836 wfMsg( "site-{$type}-feed", $wgSitename ) );
1838 } elseif ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
1839 foreach ( $wgAdvertisedFeedTypes as $format ) {
1840 $tags[] = $this->feedLink(
1842 $rctitle->getLocalURL( "feed={$format}" ),
1843 wfMsg( "site-{$format}-feed", $wgSitename ) ); # For grep: 'site-rss-feed', 'site-atom-feed'.
1848 return implode( "\n", $tags );
1852 * Return URLs for each supported syndication format for this page.
1853 * @return array associating format keys with URLs
1855 public function getSyndicationLinks() {
1856 return $this->mFeedLinks
;
1860 * Generate a <link rel/> for an RSS feed.
1862 private function feedLink( $type, $url, $text ) {
1863 return Html
::element( 'link', array(
1864 'rel' => 'alternate',
1865 'type' => "application/$type+xml",
1871 * Add a local or specified stylesheet, with the given media options.
1872 * Meant primarily for internal use...
1874 * @param $media -- to specify a media type, 'screen', 'printable', 'handheld' or any.
1875 * @param $conditional -- for IE conditional comments, specifying an IE version
1876 * @param $dir -- set to 'rtl' or 'ltr' for direction-specific sheets
1878 public function addStyle( $style, $media='', $condition='', $dir='' ) {
1880 // Even though we expect the media type to be lowercase, but here we
1881 // force it to lowercase to be safe.
1883 $options['media'] = $media;
1885 $options['condition'] = $condition;
1887 $options['dir'] = $dir;
1888 $this->styles
[$style] = $options;
1892 * Adds inline CSS styles
1893 * @param $style_css Mixed: inline CSS
1895 public function addInlineStyle( $style_css ){
1896 $this->mScripts
.= Html
::inlineStyle( $style_css );
1900 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
1901 * These will be applied to various media & IE conditionals.
1903 public function buildCssLinks() {
1905 foreach( $this->styles
as $file => $options ) {
1906 $link = $this->styleLink( $file, $options );
1911 return implode( "\n", $links );
1914 protected function styleLink( $style, $options ) {
1917 if( isset( $options['dir'] ) ) {
1919 $siteDir = $wgContLang->getDir();
1920 if( $siteDir != $options['dir'] )
1924 if( isset( $options['media'] ) ) {
1925 $media = $this->transformCssMedia( $options['media'] );
1926 if( is_null( $media ) ) {
1933 if( substr( $style, 0, 1 ) == '/' ||
1934 substr( $style, 0, 5 ) == 'http:' ||
1935 substr( $style, 0, 6 ) == 'https:' ) {
1938 global $wgStylePath, $wgStyleVersion;
1939 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
1942 $link = Html
::linkedStyle( $url, $media );
1944 if( isset( $options['condition'] ) ) {
1945 $condition = htmlspecialchars( $options['condition'] );
1946 $link = "<!--[if $condition]>$link<![endif]-->";
1951 function transformCssMedia( $media ) {
1952 global $wgRequest, $wgHandheldForIPhone;
1954 // Switch in on-screen display for media testing
1956 'printable' => 'print',
1957 'handheld' => 'handheld',
1959 foreach( $switches as $switch => $targetMedia ) {
1960 if( $wgRequest->getBool( $switch ) ) {
1961 if( $media == $targetMedia ) {
1963 } elseif( $media == 'screen' ) {
1969 // Expand longer media queries as iPhone doesn't grok 'handheld'
1970 if( $wgHandheldForIPhone ) {
1971 $mediaAliases = array(
1972 'screen' => 'screen and (min-device-width: 481px)',
1973 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
1976 if( isset( $mediaAliases[$media] ) ) {
1977 $media = $mediaAliases[$media];
1985 * Turn off regular page output and return an error reponse
1986 * for when rate limiting has triggered.
1988 public function rateLimited() {
1990 $this->setPageTitle(wfMsg('actionthrottled'));
1991 $this->setRobotPolicy( 'noindex,follow' );
1992 $this->setArticleRelated( false );
1993 $this->enableClientCache( false );
1994 $this->mRedirect
= '';
1996 $this->setStatusCode(503);
1997 $this->addWikiMsg( 'actionthrottledtext' );
1999 $this->returnToMain( null, $this->getTitle() );
2003 * Show an "add new section" link?
2007 public function showNewSectionLink() {
2008 return $this->mNewSectionLink
;
2012 * Forcibly hide the new section link?
2016 public function forceHideNewSectionLink() {
2017 return $this->mHideNewSectionLink
;
2021 * Show a warning about slave lag
2023 * If the lag is higher than $wgSlaveLagCritical seconds,
2024 * then the warning is a bit more obvious. If the lag is
2025 * lower than $wgSlaveLagWarning, then no warning is shown.
2027 * @param int $lag Slave lag
2029 public function showLagWarning( $lag ) {
2030 global $wgSlaveLagWarning, $wgSlaveLagCritical, $wgLang;
2031 if( $lag >= $wgSlaveLagWarning ) {
2032 $message = $lag < $wgSlaveLagCritical
2035 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2036 $this->wrapWikiMsg( "$wrap\n", array( $message, $wgLang->formatNum( $lag ) ) );
2041 * Add a wikitext-formatted message to the output.
2042 * This is equivalent to:
2044 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2046 public function addWikiMsg( /*...*/ ) {
2047 $args = func_get_args();
2048 $name = array_shift( $args );
2049 $this->addWikiMsgArray( $name, $args );
2053 * Add a wikitext-formatted message to the output.
2054 * Like addWikiMsg() except the parameters are taken as an array
2055 * instead of a variable argument list.
2057 * $options is passed through to wfMsgExt(), see that function for details.
2059 public function addWikiMsgArray( $name, $args, $options = array() ) {
2060 $options[] = 'parse';
2061 $text = wfMsgExt( $name, $options, $args );
2062 $this->addHTML( $text );
2066 * This function takes a number of message/argument specifications, wraps them in
2067 * some overall structure, and then parses the result and adds it to the output.
2069 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
2070 * on. The subsequent arguments may either be strings, in which case they are the
2071 * message names, or arrays, in which case the first element is the message name,
2072 * and subsequent elements are the parameters to that message.
2074 * The special named parameter 'options' in a message specification array is passed
2075 * through to the $options parameter of wfMsgExt().
2077 * Don't use this for messages that are not in users interface language.
2081 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>", 'some-error' );
2085 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . '</div>' );
2087 * The newline after opening div is needed in some wikitext. See bug 19226.
2089 public function wrapWikiMsg( $wrap /*, ...*/ ) {
2090 $msgSpecs = func_get_args();
2091 array_shift( $msgSpecs );
2092 $msgSpecs = array_values( $msgSpecs );
2094 foreach ( $msgSpecs as $n => $spec ) {
2096 if ( is_array( $spec ) ) {
2098 $name = array_shift( $args );
2099 if ( isset( $args['options'] ) ) {
2100 $options = $args['options'];
2101 unset( $args['options'] );
2107 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
2109 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );
2113 * Include jQuery core. Use this to avoid loading it multiple times
2114 * before we get usable script loader.
2116 public function includeJQuery() {
2117 if ( $this->mIncludeJQuery
) return;
2118 $this->mIncludeJQuery
= true;
2120 global $wgScriptPath, $wgStyleVersion, $wgJsMimeType;
2123 'type' => $wgJsMimeType,
2124 'src' => "$wgScriptPath/js2/js2stopgap.min.js?$wgStyleVersion",
2126 $this->mScripts
= Html
::element( 'script', $params ) . "\n" . $this->mScripts
;