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();
50 private $mIndexPolicy = 'index';
51 private $mFollowPolicy = 'follow';
52 private $mVaryHeader = array( 'Accept-Encoding' => array('list-contains=gzip'),
57 * Initialise private variables
59 function __construct() {
60 global $wgAllowUserJs;
61 $this->mAllowUserJs
= $wgAllowUserJs;
64 public function redirect( $url, $responsecode = '302' ) {
65 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
66 $this->mRedirect
= str_replace( "\n", '', $url );
67 $this->mRedirectCode
= $responsecode;
70 public function getRedirect() {
71 return $this->mRedirect
;
75 * Set the HTTP status code to send with the output.
77 * @param int $statusCode
80 function setStatusCode( $statusCode ) { $this->mStatusCode
= $statusCode; }
83 * Add a new <meta> tag
84 * To add an http-equiv meta tag, precede the name with "http:"
86 * @param $name tag name
87 * @param $val tag value
89 function addMeta( $name, $val ) {
90 array_push( $this->mMetatags
, array( $name, $val ) );
93 function addKeyword( $text ) {
94 if( is_array( $text )) {
95 $this->mKeywords
= array_merge( $this->mKeywords
, $text );
97 array_push( $this->mKeywords
, $text );
100 function addScript( $script ) {
101 $this->mScripts
.= $script . "\n";
105 * Register and add a stylesheet from an extension directory.
106 * @param $url String path to sheet. Provide either a full url (beginning
107 * with 'http', etc) or a relative path from the document root
108 * (beginning with '/'). Otherwise it behaves identically to
109 * addStyle() and draws from the /skins folder.
111 public function addExtensionStyle( $url ) {
112 array_push( $this->mExtStyles
, $url );
116 * Add a JavaScript file out of skins/common, or a given relative path.
117 * @param string $file filename in skins/common or complete on-server path (/foo/bar.js)
119 function addScriptFile( $file ) {
120 global $wgStylePath, $wgStyleVersion, $wgJsMimeType;
121 if( substr( $file, 0, 1 ) == '/' ) {
124 $path = "{$wgStylePath}/common/{$file}";
127 Xml
::element( 'script',
129 'type' => $wgJsMimeType,
130 'src' => "$path?$wgStyleVersion",
138 * Add a self-contained script tag with the given contents
139 * @param string $script JavaScript text, no <script> tags
141 function addInlineScript( $script ) {
142 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
146 * Get all registered JS and CSS tags for the header.
148 function getScript() {
149 return $this->mScripts
. $this->getHeadItems();
152 function getHeadItems() {
154 foreach ( $this->mHeadItems
as $item ) {
160 function addHeadItem( $name, $value ) {
161 $this->mHeadItems
[$name] = $value;
164 function hasHeadItem( $name ) {
165 return isset( $this->mHeadItems
[$name] );
168 function setETag($tag) { $this->mETag
= $tag; }
169 function setArticleBodyOnly($only) { $this->mArticleBodyOnly
= $only; }
170 function getArticleBodyOnly() { return $this->mArticleBodyOnly
; }
172 function addLink( $linkarr ) {
173 # $linkarr should be an associative array of attributes. We'll escape on output.
174 array_push( $this->mLinktags
, $linkarr );
177 # Get all links added by extensions
178 function getExtStyle() {
179 return $this->mExtStyles
;
182 function addMetadataLink( $linkarr ) {
183 # note: buggy CC software only reads first "meta" link
184 static $haveMeta = false;
185 $linkarr['rel'] = ($haveMeta) ?
'alternate meta' : 'meta';
186 $this->addLink( $linkarr );
191 * checkLastModified tells the client to use the client-cached page if
192 * possible. If sucessful, the OutputPage is disabled so that
193 * any future call to OutputPage->output() have no effect.
195 * Side effect: sets mLastModified for Last-Modified header
197 * @return bool True iff cache-ok headers was sent.
199 function checkLastModified( $timestamp ) {
200 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
202 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
203 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
206 if( !$wgCachePages ) {
207 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
210 if( $wgUser->getOption( 'nocache' ) ) {
211 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
215 $timestamp = wfTimestamp( TS_MW
, $timestamp );
216 $modifiedTimes = array(
217 'page' => $timestamp,
218 'user' => $wgUser->getTouched(),
219 'epoch' => $wgCacheEpoch
221 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
223 $maxModified = max( $modifiedTimes );
224 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
226 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
227 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
233 foreach ( $modifiedTimes as $name => $value ) {
234 if ( $info !== '' ) {
237 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
240 # IE sends sizes after the date like this:
241 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
242 # this breaks strtotime().
243 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
245 wfSuppressWarnings(); // E_STRICT system time bitching
246 $clientHeaderTime = strtotime( $clientHeader );
248 if ( !$clientHeaderTime ) {
249 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
252 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
254 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
255 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
256 wfDebug( __METHOD__
. ": effective Last-Modified: " .
257 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
258 if( $clientHeaderTime < $maxModified ) {
259 wfDebug( __METHOD__
. ": STALE, $info\n", false );
264 # Give a 304 response code and disable body output
265 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
266 ini_set('zlib.output_compression', 0);
267 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
268 $this->sendCacheControl();
271 // Don't output a compressed blob when using ob_gzhandler;
272 // it's technically against HTTP spec and seems to confuse
273 // Firefox when the response gets split over two packets.
274 wfClearOutputBuffers();
279 function setPageTitleActionText( $text ) {
280 $this->mPageTitleActionText
= $text;
283 function getPageTitleActionText () {
284 if ( isset( $this->mPageTitleActionText
) ) {
285 return $this->mPageTitleActionText
;
290 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
292 * @param $policy string The literal string to output as the contents of
293 * the meta tag. Will be parsed according to the spec and output in
297 public function setRobotPolicy( $policy ) {
298 $policy = Article
::formatRobotPolicy( $policy );
300 if( isset( $policy['index'] ) ){
301 $this->setIndexPolicy( $policy['index'] );
303 if( isset( $policy['follow'] ) ){
304 $this->setFollowPolicy( $policy['follow'] );
309 * Set the index policy for the page, but leave the follow policy un-
312 * @param $policy string Either 'index' or 'noindex'.
315 public function setIndexPolicy( $policy ) {
316 $policy = trim( $policy );
317 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
318 $this->mIndexPolicy
= $policy;
323 * Set the follow policy for the page, but leave the index policy un-
326 * @param $policy string Either 'follow' or 'nofollow'.
329 public function setFollowPolicy( $policy ) {
330 $policy = trim( $policy );
331 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
332 $this->mFollowPolicy
= $policy;
337 * "HTML title" means the contents of <title>. It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
339 public function setHTMLTitle( $name ) {
340 $this->mHTMLtitle
= $name;
344 * "Page title" means the contents of <h1>. It is stored as a valid HTML fragment.
345 * This function allows good tags like <sup> in the <h1> tag, but not bad tags like <script>.
346 * This function automatically sets <title> to the same content as <h1> but with all tags removed.
347 * Bad tags that were escaped in <h1> will still be escaped in <title>, and good tags like <i> will be dropped entirely.
349 public function setPageTitle( $name ) {
350 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
351 # but leave "<i>foobar</i>" alone
352 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
353 $this->mPagetitle
= $nameWithTags;
355 $taction = $this->getPageTitleActionText();
356 if( !empty( $taction ) ) {
357 $name .= ' - '.$taction;
360 # change "<i>foo&bar</i>" to "foo&bar"
361 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer
::stripAllTags( $nameWithTags ) ) );
364 public function setTitle( $t ) {
368 public function getTitle() {
369 if ( $this->mTitle
instanceof Title
) {
370 return $this->mTitle
;
373 wfDebug( __METHOD__
. ' called and $mTitle is null. Return $wgTitle for sanity' );
379 public function getHTMLTitle() { return $this->mHTMLtitle
; }
380 public function getPageTitle() { return $this->mPagetitle
; }
381 public function setSubtitle( $str ) { $this->mSubtitle
= /*$this->parse(*/$str/*)*/; } // @bug 2514
382 public function appendSubtitle( $str ) { $this->mSubtitle
.= /*$this->parse(*/$str/*)*/; } // @bug 2514
383 public function getSubtitle() { return $this->mSubtitle
; }
384 public function isArticle() { return $this->mIsarticle
; }
385 public function setPrintable() { $this->mPrintable
= true; }
386 public function isPrintable() { return $this->mPrintable
; }
387 public function getFeedAppendQuery() { return $this->mFeedLinksAppendQuery
; }
388 public function disable() { $this->mDoNothing
= true; }
389 public function isDisabled() { return $this->mDoNothing
; }
391 public function setSyndicated( $show = true ) {
393 $this->setFeedAppendQuery( false );
395 $this->mFeedLinks
= array();
399 public function setFeedAppendQuery( $val ) {
400 global $wgFeedClasses, $wgAdvertisedFeedTypes;
402 $this->mFeedLinks
= array();
404 foreach ( $wgAdvertisedFeedTypes as $type ) {
405 $query = "feed=$type";
406 if ( is_string( $val ) ) {
407 $query .= '&' . $val;
409 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
413 public function addFeedLink( $format, $href ) {
414 $this->mFeedLinks
[$format] = $href;
417 public function isSyndicated() { return count($this->mFeedLinks
); }
419 public function setArticleRelated( $v ) {
420 $this->mIsArticleRelated
= $v;
422 $this->mIsarticle
= false;
425 public function setArticleFlag( $v ) {
426 $this->mIsarticle
= $v;
428 $this->mIsArticleRelated
= $v;
432 public function isArticleRelated() { return $this->mIsArticleRelated
; }
434 public function getLanguageLinks() { return $this->mLanguageLinks
; }
435 public function addLanguageLinks($newLinkArray) {
436 $this->mLanguageLinks +
= $newLinkArray;
438 public function setLanguageLinks($newLinkArray) {
439 $this->mLanguageLinks
= $newLinkArray;
442 public function getCategoryLinks() {
443 return $this->mCategoryLinks
;
446 public function getCategories() {
447 return $this->mCategories
;
451 * Add an array of categories, with names in the keys
453 public function addCategoryLinks( $categories ) {
454 global $wgUser, $wgContLang;
456 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
460 # Add the links to a LinkBatch
461 $arr = array( NS_CATEGORY
=> $categories );
463 $lb->setArray( $arr );
465 # Fetch existence plus the hiddencat property
466 $dbr = wfGetDB( DB_SLAVE
);
467 $pageTable = $dbr->tableName( 'page' );
468 $where = $lb->constructSet( 'page', $dbr );
469 $propsTable = $dbr->tableName( 'page_props' );
470 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, pp_value
471 FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
472 $res = $dbr->query( $sql, __METHOD__
);
474 # Add the results to the link cache
475 $lb->addResultToCache( LinkCache
::singleton(), $res );
477 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
478 $categories = array_combine( array_keys( $categories ),
479 array_fill( 0, count( $categories ), 'normal' ) );
481 # Mark hidden categories
482 foreach ( $res as $row ) {
483 if ( isset( $row->pp_value
) ) {
484 $categories[$row->page_title
] = 'hidden';
488 # Add the remaining categories to the skin
489 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
490 $sk = $wgUser->getSkin();
491 foreach ( $categories as $category => $type ) {
492 $origcategory = $category;
493 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
494 $wgContLang->findVariantLink( $category, $title, true );
495 if ( $category != $origcategory )
496 if ( array_key_exists( $category, $categories ) )
498 $text = $wgContLang->convertHtml( $title->getText() );
499 $this->mCategories
[] = $title->getText();
500 $this->mCategoryLinks
[$type][] = $sk->link( $title, $text );
505 public function setCategoryLinks($categories) {
506 $this->mCategoryLinks
= array();
507 $this->addCategoryLinks($categories);
510 public function suppressQuickbar() { $this->mSuppressQuickbar
= true; }
511 public function isQuickbarSuppressed() { return $this->mSuppressQuickbar
; }
513 public function disallowUserJs() { $this->mAllowUserJs
= false; }
514 public function isUserJsAllowed() { return $this->mAllowUserJs
; }
516 public function prependHTML( $text ) { $this->mBodytext
= $text . $this->mBodytext
; }
517 public function addHTML( $text ) { $this->mBodytext
.= $text; }
518 public function clearHTML() { $this->mBodytext
= ''; }
519 public function getHTML() { return $this->mBodytext
; }
520 public function debug( $text ) { $this->mDebugtext
.= $text; }
523 public function setParserOptions( $options ) {
524 wfDeprecated( __METHOD__
);
525 return $this->parserOptions( $options );
528 public function parserOptions( $options = null ) {
529 if ( !$this->mParserOptions
) {
530 $this->mParserOptions
= new ParserOptions
;
532 return wfSetVar( $this->mParserOptions
, $options );
536 * Set the revision ID which will be seen by the wiki text parser
537 * for things such as embedded {{REVISIONID}} variable use.
538 * @param mixed $revid an integer, or NULL
539 * @return mixed previous value
541 public function setRevisionId( $revid ) {
542 $val = is_null( $revid ) ?
null : intval( $revid );
543 return wfSetVar( $this->mRevisionId
, $val );
546 public function getRevisionId() {
547 return $this->mRevisionId
;
551 * Convert wikitext to HTML and add it to the buffer
552 * Default assumes that the current page title will
555 * @param string $text
556 * @param bool $linestart
558 public function addWikiText( $text, $linestart = true ) {
559 $title = $this->getTitle(); // Work arround E_STRICT
560 $this->addWikiTextTitle( $text, $title, $linestart );
563 public function addWikiTextWithTitle($text, &$title, $linestart = true) {
564 $this->addWikiTextTitle($text, $title, $linestart);
567 function addWikiTextTitleTidy($text, &$title, $linestart = true) {
568 $this->addWikiTextTitle( $text, $title, $linestart, true );
571 public function addWikiTextTitle($text, &$title, $linestart, $tidy = false) {
574 wfProfileIn( __METHOD__
);
576 wfIncrStats( 'pcache_not_possible' );
578 $popts = $this->parserOptions();
579 $oldTidy = $popts->setTidy( $tidy );
581 $parserOutput = $wgParser->parse( $text, $title, $popts,
582 $linestart, true, $this->mRevisionId
);
584 $popts->setTidy( $oldTidy );
586 $this->addParserOutput( $parserOutput );
588 wfProfileOut( __METHOD__
);
593 * @param ParserOutput object &$parserOutput
595 public function addParserOutputNoText( &$parserOutput ) {
596 global $wgExemptFromUserRobotsControl, $wgContentNamespaces;
598 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
599 $this->addCategoryLinks( $parserOutput->getCategories() );
600 $this->mNewSectionLink
= $parserOutput->getNewSection();
601 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
603 $this->mParseWarnings
= $parserOutput->getWarnings();
604 if ( $parserOutput->getCacheTime() == -1 ) {
605 $this->enableClientCache( false );
607 $this->mNoGallery
= $parserOutput->getNoGallery();
608 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$parserOutput->mHeadItems
);
610 foreach ( (array)$parserOutput->mTemplateIds
as $ns => $dbks ) {
611 if ( isset( $this->mTemplateIds
[$ns] ) ) {
612 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
614 $this->mTemplateIds
[$ns] = $dbks;
618 $title = $parserOutput->getTitleText();
619 if ( $title != '' ) {
620 $this->setPageTitle( $title );
623 // Hooks registered in the object
624 global $wgParserOutputHooks;
625 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
626 list( $hookName, $data ) = $hookInfo;
627 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
628 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
632 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
637 * @param ParserOutput &$parserOutput
639 function addParserOutput( &$parserOutput ) {
640 $this->addParserOutputNoText( $parserOutput );
641 $text = $parserOutput->getText();
642 wfRunHooks( 'OutputPageBeforeHTML',array( &$this, &$text ) );
643 $this->addHTML( $text );
647 * Add wikitext to the buffer, assuming that this is the primary text for a page view
648 * Saves the text into the parser cache if possible.
650 * @param string $text
651 * @param Article $article
653 * @deprecated Use Article::outputWikitext
655 public function addPrimaryWikiText( $text, $article, $cache = true ) {
658 wfDeprecated( __METHOD__
);
660 $popts = $this->parserOptions();
661 $popts->setTidy(true);
662 $parserOutput = $wgParser->parse( $text, $article->mTitle
,
663 $popts, true, true, $this->mRevisionId
);
664 $popts->setTidy(false);
665 if ( $cache && $article && $parserOutput->getCacheTime() != -1 ) {
666 $parserCache = ParserCache
::singleton();
667 $parserCache->save( $parserOutput, $article, $popts);
670 $this->addParserOutput( $parserOutput );
674 * @deprecated use addWikiTextTidy()
676 public function addSecondaryWikiText( $text, $linestart = true ) {
677 wfDeprecated( __METHOD__
);
678 $this->addWikiTextTitleTidy($text, $this->getTitle(), $linestart);
682 * Add wikitext with tidy enabled
684 public function addWikiTextTidy( $text, $linestart = true ) {
685 $title = $this->getTitle();
686 $this->addWikiTextTitleTidy($text, $title, $linestart);
691 * Add the output of a QuickTemplate to the output buffer
693 * @param QuickTemplate $template
695 public function addTemplate( &$template ) {
697 $template->execute();
698 $this->addHTML( ob_get_contents() );
703 * Parse wikitext and return the HTML.
705 * @param string $text
706 * @param bool $linestart Is this the start of a line?
707 * @param bool $interface ??
709 public function parse( $text, $linestart = true, $interface = false ) {
711 if( is_null( $this->getTitle() ) ) {
712 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
714 $popts = $this->parserOptions();
715 if ( $interface) { $popts->setInterfaceMessage(true); }
716 $parserOutput = $wgParser->parse( $text, $this->getTitle(), $popts,
717 $linestart, true, $this->mRevisionId
);
718 if ( $interface) { $popts->setInterfaceMessage(false); }
719 return $parserOutput->getText();
722 /** Parse wikitext, strip paragraphs, and return the HTML. */
723 public function parseInline( $text, $linestart = true, $interface = false ) {
724 $parsed = $this->parse( $text, $linestart, $interface );
727 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
735 * @param Article $article
740 * @return bool True if successful, else false.
742 public function tryParserCache( &$article ) {
743 wfDeprecated( __METHOD__
);
744 $parserOutput = ParserCache
::singleton()->get( $article, $article->getParserOptions() );
746 if ($parserOutput !== false) {
747 $this->addParserOutput( $parserOutput );
755 * @param int $maxage Maximum cache time on the Squid, in seconds.
757 public function setSquidMaxage( $maxage ) {
758 $this->mSquidMaxage
= $maxage;
762 * Use enableClientCache(false) to force it to send nocache headers
765 public function enableClientCache( $state ) {
766 return wfSetVar( $this->mEnableClientCache
, $state );
769 function getCacheVaryCookies() {
770 global $wgCookiePrefix, $wgCacheVaryCookies;
772 if ( $cookies === null ) {
773 $cookies = array_merge(
775 "{$wgCookiePrefix}Token",
776 "{$wgCookiePrefix}LoggedOut",
781 wfRunHooks('GetCacheVaryCookies', array( $this, &$cookies ) );
786 function uncacheableBecauseRequestVars() {
788 return $wgRequest->getText('useskin', false) === false
789 && $wgRequest->getText('uselang', false) === false;
793 * Check if the request has a cache-varying cookie header
794 * If it does, it's very important that we don't allow public caching
796 function haveCacheVaryCookies() {
798 $cookieHeader = $wgRequest->getHeader( 'cookie' );
799 if ( $cookieHeader === false ) {
802 $cvCookies = $this->getCacheVaryCookies();
803 foreach ( $cvCookies as $cookieName ) {
804 # Check for a simple string match, like the way squid does it
805 if ( strpos( $cookieHeader, $cookieName ) ) {
806 wfDebug( __METHOD__
.": found $cookieName\n" );
810 wfDebug( __METHOD__
.": no cache-varying cookies found\n" );
814 public function addVaryHeader( $header, $option = null ) {
815 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
816 $this->mVaryHeader
[$header] = $option;
818 elseif( is_array( $option ) ) {
819 if( is_array( $this->mVaryHeader
[$header] ) ) {
820 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
823 $this->mVaryHeader
[$header] = $option;
826 $this->mVaryHeader
[$header] = array_unique( $this->mVaryHeader
[$header] );
829 /** Get a complete X-Vary-Options header */
830 public function getXVO() {
831 $cvCookies = $this->getCacheVaryCookies();
833 $cookiesOption = array();
834 foreach ( $cvCookies as $cookieName ) {
835 $cookiesOption[] = 'string-contains=' . $cookieName;
837 $this->addVaryHeader( 'Cookie', $cookiesOption );
840 foreach( $this->mVaryHeader
as $header => $option ) {
841 $newheader = $header;
842 if( is_array( $option ) )
843 $newheader .= ';' . implode( ';', $option );
844 $headers[] = $newheader;
846 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
851 /** bug 21672: Add Accept-Language to Vary and XVO headers
852 if there's no 'variant' parameter existed in GET.
855 /w/index.php?title=Main_page should always be served; but
856 /w/index.php?title=Main_page&variant=zh-cn should never be served.
858 patched by Liangent and Philip */
859 function addAcceptLanguage() {
860 global $wgRequest, $wgContLang;
861 if( !$wgRequest->getCheck('variant') && $wgContLang->hasVariants() ) {
862 $variants = $wgContLang->getVariants();
864 foreach ( $variants as $variant ) {
865 if( $variant === $wgContLang->getCode() )
868 $aloption[] = "string-contains=$variant";
870 $this->addVaryHeader( 'Accept-Language', $aloption );
874 public function sendCacheControl() {
875 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest, $wgUseXVO;
877 $response = $wgRequest->response();
878 if ($wgUseETag && $this->mETag
)
879 $response->header("ETag: $this->mETag");
881 $this->addAcceptLanguage();
883 # don't serve compressed data to clients who can't handle it
884 # maintain different caches for logged-in users and non-logged in ones
885 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) ) );
888 # Add an X-Vary-Options header for Squid with Wikimedia patches
889 $response->header( $this->getXVO() );
892 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
893 if( $wgUseSquid && session_id() == '' &&
894 ! $this->isPrintable() && $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies() )
897 # We'll purge the proxy cache explicitly, but require end user agents
898 # to revalidate against the proxy on each visit.
899 # Surrogate-Control controls our Squid, Cache-Control downstream caches
900 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
901 # start with a shorter timeout for initial testing
902 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
903 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
904 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
906 # We'll purge the proxy cache for anons explicitly, but require end user agents
907 # to revalidate against the proxy on each visit.
908 # IMPORTANT! The Squid needs to replace the Cache-Control header with
909 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
910 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
911 # start with a shorter timeout for initial testing
912 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
913 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
916 # We do want clients to cache if they can, but they *must* check for updates
917 # on revisiting the page.
918 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
919 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
920 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
922 if($this->mLastModified
) {
923 $response->header( "Last-Modified: {$this->mLastModified}" );
926 wfDebug( __METHOD__
. ": no caching **\n", false );
928 # In general, the absence of a last modified header should be enough to prevent
929 # the client from using its cache. We send a few other things just to make sure.
930 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
931 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
932 $response->header( 'Pragma: no-cache' );
934 wfRunHooks('CacheHeadersAfterSet', array( $this ) );
938 * Get the message associed with the HTTP response code $code
940 * @param $code Integer: status code
941 * @return String or null: message or null if $code is not in the list of
944 public static function getStatusMessage( $code ) {
945 static $statusMessage = array(
947 101 => 'Switching Protocols',
952 203 => 'Non-Authoritative Information',
954 205 => 'Reset Content',
955 206 => 'Partial Content',
956 207 => 'Multi-Status',
957 300 => 'Multiple Choices',
958 301 => 'Moved Permanently',
961 304 => 'Not Modified',
963 307 => 'Temporary Redirect',
964 400 => 'Bad Request',
965 401 => 'Unauthorized',
966 402 => 'Payment Required',
969 405 => 'Method Not Allowed',
970 406 => 'Not Acceptable',
971 407 => 'Proxy Authentication Required',
972 408 => 'Request Timeout',
975 411 => 'Length Required',
976 412 => 'Precondition Failed',
977 413 => 'Request Entity Too Large',
978 414 => 'Request-URI Too Large',
979 415 => 'Unsupported Media Type',
980 416 => 'Request Range Not Satisfiable',
981 417 => 'Expectation Failed',
982 422 => 'Unprocessable Entity',
984 424 => 'Failed Dependency',
985 500 => 'Internal Server Error',
986 501 => 'Not Implemented',
987 502 => 'Bad Gateway',
988 503 => 'Service Unavailable',
989 504 => 'Gateway Timeout',
990 505 => 'HTTP Version Not Supported',
991 507 => 'Insufficient Storage'
993 return isset( $statusMessage[$code] ) ?
$statusMessage[$code] : null;
997 * Finally, all the text has been munged and accumulated into
998 * the object, let's actually output it:
1000 public function output() {
1001 global $wgUser, $wgOutputEncoding, $wgRequest;
1002 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
1003 global $wgUseAjax, $wgAjaxWatch;
1004 global $wgEnableMWSuggest, $wgUniversalEditButton;
1007 if( $this->mDoNothing
){
1010 wfProfileIn( __METHOD__
);
1011 if ( $this->mRedirect
!= '' ) {
1012 # Standards require redirect URLs to be absolute
1013 $this->mRedirect
= wfExpandUrl( $this->mRedirect
);
1014 if( $this->mRedirectCode
== '301' ||
$this->mRedirectCode
== '303' ) {
1015 if( !$wgDebugRedirects ) {
1016 $message = self
::getStatusMessage( $this->mRedirectCode
);
1017 $wgRequest->response()->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
1019 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1021 $this->sendCacheControl();
1023 $wgRequest->response()->header( "Content-Type: text/html; charset=utf-8" );
1024 if( $wgDebugRedirects ) {
1025 $url = htmlspecialchars( $this->mRedirect
);
1026 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1027 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1028 print "</body>\n</html>\n";
1030 $wgRequest->response()->header( 'Location: ' . $this->mRedirect
);
1032 wfProfileOut( __METHOD__
);
1034 } elseif ( $this->mStatusCode
) {
1035 $message = self
::getStatusMessage( $this->mStatusCode
);
1037 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
1040 $sk = $wgUser->getSkin();
1043 $this->addScriptFile( 'ajax.js' );
1045 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1047 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1048 $this->addScriptFile( 'ajaxwatch.js' );
1051 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ){
1052 $this->addScriptFile( 'mwsuggest.js' );
1056 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1057 $this->addScriptFile( 'rightclickedit.js' );
1060 if( $wgUniversalEditButton ) {
1061 if( isset( $wgArticle ) && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1062 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create' ) ) ) {
1063 // Original UniversalEditButton
1064 $msg = wfMsg('edit');
1065 $this->addLink( array(
1066 'rel' => 'alternate',
1067 'type' => 'application/x-wiki',
1069 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1071 // Alternate edit link
1072 $this->addLink( array(
1075 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1080 # Buffer output; final headers may depend on later processing
1083 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1084 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
1086 if ($this->mArticleBodyOnly
) {
1087 $this->out($this->mBodytext
);
1089 // Hook that allows last minute changes to the output page, e.g.
1090 // adding of CSS or Javascript by extensions.
1091 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1093 wfProfileIn( 'Output-skin' );
1094 $sk->outputPage( $this );
1095 wfProfileOut( 'Output-skin' );
1098 $this->sendCacheControl();
1100 wfProfileOut( __METHOD__
);
1104 * Actually output something with print(). Performs an iconv to the
1105 * output encoding, if needed.
1106 * @param string $ins The string to output
1108 public function out( $ins ) {
1109 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1110 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1113 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1114 if ( false === $outs ) { $outs = $ins; }
1122 public static function setEncodings() {
1123 global $wgInputEncoding, $wgOutputEncoding;
1126 $wgInputEncoding = strtolower( $wgInputEncoding );
1128 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
1129 $wgOutputEncoding = strtolower( $wgOutputEncoding );
1132 $wgOutputEncoding = $wgInputEncoding;
1136 * Deprecated, use wfReportTime() instead.
1140 public function reportTime() {
1141 wfDeprecated( __METHOD__
);
1142 $time = wfReportTime();
1147 * Produce a "user is blocked" page.
1149 * @param bool $return Whether to have a "return to $wgTitle" message or not.
1152 function blockedPage( $return = true ) {
1153 global $wgUser, $wgContLang, $wgLang;
1155 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1156 $this->setRobotPolicy( 'noindex,nofollow' );
1157 $this->setArticleRelated( false );
1159 $name = User
::whoIs( $wgUser->blockedBy() );
1160 $reason = $wgUser->blockedFor();
1161 if( $reason == '' ) {
1162 $reason = wfMsg( 'blockednoreason' );
1164 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $wgUser->mBlock
->mTimestamp
), true );
1167 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1169 $blockid = $wgUser->mBlock
->mId
;
1171 $blockExpiry = $wgUser->mBlock
->mExpiry
;
1172 if ( $blockExpiry == 'infinity' ) {
1173 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1174 // Search for localization in 'ipboptions'
1175 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1176 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1177 if ( strpos( $option, ":" ) === false )
1179 list( $show, $value ) = explode( ":", $option );
1180 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1181 $blockExpiry = $show;
1186 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1189 if ( $wgUser->mBlock
->mAuto
) {
1190 $msg = 'autoblockedtext';
1192 $msg = 'blockedtext';
1195 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1196 * This could be a username, an ip range, or a single ip. */
1197 $intended = $wgUser->mBlock
->mAddress
;
1199 $this->addWikiMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
1201 # Don't auto-return to special pages
1203 $return = $this->getTitle()->getNamespace() > -1 ?
$this->getTitle() : null;
1204 $this->returnToMain( null, $return );
1209 * Output a standard error page
1211 * @param string $title Message key for page title
1212 * @param string $msg Message key for page text
1213 * @param array $params Message parameters
1215 public function showErrorPage( $title, $msg, $params = array() ) {
1216 if ( $this->getTitle() ) {
1217 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1219 $this->setPageTitle( wfMsg( $title ) );
1220 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1221 $this->setRobotPolicy( 'noindex,nofollow' );
1222 $this->setArticleRelated( false );
1223 $this->enableClientCache( false );
1224 $this->mRedirect
= '';
1225 $this->mBodytext
= '';
1227 array_unshift( $params, 'parse' );
1228 array_unshift( $params, $msg );
1229 $this->addHTML( call_user_func_array( 'wfMsgExt', $params ) );
1231 $this->returnToMain();
1235 * Output a standard permission error page
1237 * @param array $errors Error message keys
1239 public function showPermissionsErrorPage( $errors, $action = null )
1241 $this->mDebugtext
.= 'Original title: ' .
1242 $this->getTitle()->getPrefixedText() . "\n";
1243 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1244 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1245 $this->setRobotPolicy( 'noindex,nofollow' );
1246 $this->setArticleRelated( false );
1247 $this->enableClientCache( false );
1248 $this->mRedirect
= '';
1249 $this->mBodytext
= '';
1250 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1254 public function errorpage( $title, $msg ) {
1255 wfDeprecated( __METHOD__
);
1256 throw new ErrorPageError( $title, $msg );
1260 * Display an error page indicating that a given version of MediaWiki is
1261 * required to use it
1263 * @param mixed $version The version of MediaWiki needed to use the page
1265 public function versionRequired( $version ) {
1266 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1267 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1268 $this->setRobotPolicy( 'noindex,nofollow' );
1269 $this->setArticleRelated( false );
1270 $this->mBodytext
= '';
1272 $this->addWikiMsg( 'versionrequiredtext', $version );
1273 $this->returnToMain();
1277 * Display an error page noting that a given permission bit is required.
1279 * @param string $permission key required
1281 public function permissionRequired( $permission ) {
1284 $this->setPageTitle( wfMsg( 'badaccess' ) );
1285 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1286 $this->setRobotPolicy( 'noindex,nofollow' );
1287 $this->setArticleRelated( false );
1288 $this->mBodytext
= '';
1290 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1291 User
::getGroupsWithPermission( $permission ) );
1293 $this->addWikiMsg( 'badaccess-groups',
1294 $wgLang->commaList( $groups ),
1297 $this->addWikiMsg( 'badaccess-group0' );
1299 $this->returnToMain();
1303 * Use permissionRequired.
1306 public function sysopRequired() {
1307 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
1311 * Use permissionRequired.
1314 public function developerRequired() {
1315 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
1319 * Produce the stock "please login to use the wiki" page
1321 public function loginToUse() {
1322 global $wgUser, $wgContLang;
1324 if( $wgUser->isLoggedIn() ) {
1325 $this->permissionRequired( 'read' );
1329 $skin = $wgUser->getSkin();
1331 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1332 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1333 $this->setRobotPolicy( 'noindex,nofollow' );
1334 $this->setArticleFlag( false );
1336 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1337 $loginLink = $skin->link(
1339 wfMsgHtml( 'loginreqlink' ),
1341 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
1342 array( 'known', 'noclasses' )
1344 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1345 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . "-->" );
1347 # Don't return to the main page if the user can't read it
1348 # otherwise we'll end up in a pointless loop
1349 $mainPage = Title
::newMainPage();
1350 if( $mainPage->userCanRead() )
1351 $this->returnToMain( null, $mainPage );
1355 public function databaseError( $fname, $sql, $error, $errno ) {
1356 throw new MWException( "OutputPage::databaseError is obsolete\n" );
1360 * @param array $errors An array of arrays returned by Title::getUserPermissionsErrors
1361 * @return string The wikitext error-messages, formatted into a list.
1363 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1364 if ($action == null) {
1365 $text = wfMsgNoTrans( 'permissionserrorstext', count($errors)). "\n\n";
1368 $action_desc = wfMsgNoTrans( "action-$action" );
1369 $text = wfMsgNoTrans( 'permissionserrorstext-withaction', count($errors), $action_desc ) . "\n\n";
1372 if (count( $errors ) > 1) {
1373 $text .= '<ul class="permissions-errors">' . "\n";
1375 foreach( $errors as $error )
1378 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1383 $text .= "<div class=\"permissions-errors\">\n" . call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) . "\n</div>";
1390 * Display a page stating that the Wiki is in read-only mode,
1391 * and optionally show the source of the page that the user
1392 * was trying to edit. Should only be called (for this
1393 * purpose) after wfReadOnly() has returned true.
1395 * For historical reasons, this function is _also_ used to
1396 * show the error message when a user tries to edit a page
1397 * they are not allowed to edit. (Unless it's because they're
1398 * blocked, then we show blockedPage() instead.) In this
1399 * case, the second parameter should be set to true and a list
1400 * of reasons supplied as the third parameter.
1402 * @todo Needs to be split into multiple functions.
1404 * @param string $source Source code to show (or null).
1405 * @param bool $protected Is this a permissions error?
1406 * @param array $reasons List of reasons for this error, as returned by Title::getUserPermissionsErrors().
1408 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1410 $skin = $wgUser->getSkin();
1412 $this->setRobotPolicy( 'noindex,nofollow' );
1413 $this->setArticleRelated( false );
1415 // If no reason is given, just supply a default "I can't let you do
1416 // that, Dave" message. Should only occur if called by legacy code.
1417 if ( $protected && empty($reasons) ) {
1418 $reasons[] = array( 'badaccess-group0' );
1421 if ( !empty($reasons) ) {
1422 // Permissions error
1424 $this->setPageTitle( wfMsg( 'viewsource' ) );
1433 array( 'known', 'noclasses' )
1438 $this->setPageTitle( wfMsg( 'badaccess' ) );
1440 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1442 // Wiki is read only
1443 $this->setPageTitle( wfMsg( 'readonly' ) );
1444 $reason = wfReadOnlyReason();
1445 $this->wrapWikiMsg( '<div class="mw-readonly-error">\n$1</div>', array( 'readonlytext', $reason ) );
1448 // Show source, if supplied
1449 if( is_string( $source ) ) {
1450 $this->addWikiMsg( 'viewsourcetext' );
1453 'id' => 'wpTextbox1',
1454 'name' => 'wpTextbox1',
1455 'cols' => $wgUser->getOption( 'cols' ),
1456 'rows' => $wgUser->getOption( 'rows' ),
1457 'readonly' => 'readonly'
1459 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
1461 // Show templates used by this article
1462 $skin = $wgUser->getSkin();
1463 $article = new Article( $this->getTitle() );
1464 $this->addHTML( "<div class='templatesUsed'>
1465 {$skin->formatTemplates( $article->getUsedTemplates() )}
1470 # If the title doesn't exist, it's fairly pointless to print a return
1471 # link to it. After all, you just tried editing it and couldn't, so
1472 # what's there to do there?
1473 if( $this->getTitle()->exists() ) {
1474 $this->returnToMain( null, $this->getTitle() );
1479 public function fatalError( $message ) {
1480 wfDeprecated( __METHOD__
);
1481 throw new FatalError( $message );
1485 public function unexpectedValueError( $name, $val ) {
1486 wfDeprecated( __METHOD__
);
1487 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1491 public function fileCopyError( $old, $new ) {
1492 wfDeprecated( __METHOD__
);
1493 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1497 public function fileRenameError( $old, $new ) {
1498 wfDeprecated( __METHOD__
);
1499 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1503 public function fileDeleteError( $name ) {
1504 wfDeprecated( __METHOD__
);
1505 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1509 public function fileNotFoundError( $name ) {
1510 wfDeprecated( __METHOD__
);
1511 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1514 public function showFatalError( $message ) {
1515 $this->setPageTitle( wfMsg( "internalerror" ) );
1516 $this->setRobotPolicy( "noindex,nofollow" );
1517 $this->setArticleRelated( false );
1518 $this->enableClientCache( false );
1519 $this->mRedirect
= '';
1520 $this->mBodytext
= $message;
1523 public function showUnexpectedValueError( $name, $val ) {
1524 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
1527 public function showFileCopyError( $old, $new ) {
1528 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
1531 public function showFileRenameError( $old, $new ) {
1532 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
1535 public function showFileDeleteError( $name ) {
1536 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
1539 public function showFileNotFoundError( $name ) {
1540 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1544 * Add a "return to" link pointing to a specified title
1546 * @param $title Title to link
1547 * @param $query String: query string
1549 public function addReturnTo( $title, $query = array() ) {
1551 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullUrl() ) );
1552 $link = wfMsgHtml( 'returnto', $wgUser->getSkin()->link(
1553 $title, null, array(), $query ) );
1554 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
1558 * Add a "return to" link pointing to a specified title,
1559 * or the title indicated in the request, or else the main page
1561 * @param $unused No longer used
1562 * @param $returnto Title or String to return to
1563 * @param $returntoquery String: query string for the return to link
1565 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
1568 if ( $returnto == null ) {
1569 $returnto = $wgRequest->getText( 'returnto' );
1572 if ( $returntoquery == null ) {
1573 $returntoquery = $wgRequest->getText( 'returntoquery' );
1576 if ( $returnto === '' ) {
1577 $returnto = Title
::newMainPage();
1580 if ( is_object( $returnto ) ) {
1581 $titleObj = $returnto;
1583 $titleObj = Title
::newFromText( $returnto );
1585 if ( !is_object( $titleObj ) ) {
1586 $titleObj = Title
::newMainPage();
1589 $this->addReturnTo( $titleObj, $returntoquery );
1593 * @return string The doctype, opening <html>, and head element.
1595 * @param $sk Skin The given Skin
1597 public function headElement( Skin
$sk, $includeStyle = true ) {
1598 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1599 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces, $wgHtml5Version;
1600 global $wgContLang, $wgUseTrackbacks, $wgStyleVersion, $wgHtml5, $wgWellFormedXml;
1601 global $wgUser, $wgRequest, $wgLang;
1603 $this->addMeta( "http:Content-Type", "$wgMimeType; charset={$wgOutputEncoding}" );
1604 if ( $sk->commonPrintStylesheet() ) {
1605 $this->addStyle( 'common/wikiprintable.css', 'print' );
1607 $sk->setupUserCss( $this );
1611 if( $wgMimeType == 'text/xml' ||
$wgMimeType == 'application/xhtml+xml' ||
$wgMimeType == 'application/xml' ) {
1612 $ret .= "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?" . ">\n";
1615 if ( $this->getHTMLTitle() == '' ) {
1616 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1619 $dir = $wgContLang->getDir();
1622 if ( $wgWellFormedXml ) {
1623 # Unknown elements and attributes are okay in XML, but unknown
1624 # named entities are well-formedness errors and will break XML
1625 # parsers. Thus we need a doctype that gives us appropriate
1626 # entity definitions. The HTML5 spec permits four legacy
1627 # doctypes as obsolete but conforming, so let's pick one of
1628 # those, although it makes our pages look like XHTML1 Strict.
1629 # Isn't compatibility great?
1630 $ret .= "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n";
1633 $ret .= "<!doctype html>\n";
1635 $ret .= "<html lang=\"$wgContLanguageCode\" dir=\"$dir\" ";
1636 if ( $wgHtml5Version ) $ret .= " version=\"$wgHtml5Version\" ";
1639 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\" \"$wgDTD\">\n";
1640 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1641 foreach($wgXhtmlNamespaces as $tag => $ns) {
1642 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1644 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" dir=\"$dir\">\n";
1648 $ret .= "<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n";
1649 $ret .= implode( "\n", array(
1650 $this->getHeadLinks(),
1651 $this->buildCssLinks(),
1652 $this->getHeadScripts( $sk ),
1653 $this->getHeadItems(),
1656 $ret .= Html
::inlineStyle( $sk->usercss
);
1659 if ($wgUseTrackbacks && $this->isArticleRelated())
1660 $ret .= $this->getTitle()->trackbackRDF();
1662 $ret .= "</head>\n";
1664 $bodyAttrs = array();
1666 # Crazy edit-on-double-click stuff
1667 $action = $wgRequest->getVal( 'action', 'view' );
1669 if ( $this->mTitle
->getNamespace() != NS_SPECIAL
1670 && !in_array( $action, array( 'edit', 'submit' ) )
1671 && $wgUser->getOption( 'editondblclick' ) ) {
1672 $bodyAttrs['ondblclick'] = "document.location = '" . Xml
::escapeJsString( $this->mTitle
->getEditURL() ) . "'";
1676 $bodyAttrs['class'] = "mediawiki $dir";
1678 if ( $wgLang->capitalizeAllNouns() ) {
1679 # A <body> class is probably not the best way to do this . . .
1680 $bodyAttrs['class'] .= ' capitalize-all-nouns';
1682 $bodyAttrs['class'] .= ' ns-' . $this->mTitle
->getNamespace();
1683 if ( $this->mTitle
->getNamespace() == NS_SPECIAL
) {
1684 $bodyAttrs['class'] .= ' ns-special';
1685 } elseif ( $this->mTitle
->isTalkPage() ) {
1686 $bodyAttrs['class'] .= ' ns-talk';
1688 $bodyAttrs['class'] .= ' ns-subject';
1690 $bodyAttrs['class'] .= ' ' . Sanitizer
::escapeClass( 'page-' . $this->mTitle
->getPrefixedText() );
1691 $bodyAttrs['class'] .= ' skin-' . Sanitizer
::escapeClass( $wgUser->getSkin()->getSkinName() );
1693 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
1699 * gets the global variables and mScripts
1701 * also adds userjs to the end if enabled:
1703 function getHeadScripts( Skin
$sk ) {
1704 global $wgUser, $wgRequest, $wgJsMimeType, $wgUseSiteJs;
1705 global $wgStylePath, $wgStyleVersion;
1707 $scripts = Skin
::makeGlobalVariablesScript( $sk->getSkinName() );
1708 $scripts .= Html
::linkedScript( "{$wgStylePath}/common/wikibits.js?$wgStyleVersion" );
1710 //add site JS if enabled:
1711 if( $wgUseSiteJs ) {
1712 $jsCache = $wgUser->isLoggedIn() ?
'&smaxage=0' : '';
1713 $this->addScriptFile( Skin
::makeUrl( '-',
1714 "action=raw$jsCache&gen=js&useskin=" .
1715 urlencode( $sk->getSkinName() )
1720 //add user js if enabled:
1721 if( $this->isUserJsAllowed() && $wgUser->isLoggedIn() ) {
1722 $action = $wgRequest->getVal( 'action', 'view' );
1723 if( $this->mTitle
&& $this->mTitle
->isJsSubpage() and $sk->userCanPreview( $action ) ) {
1724 # XXX: additional security check/prompt?
1725 $this->addInlineScript( $wgRequest->getText( 'wpTextbox1' ) );
1727 $userpage = $wgUser->getUserPage();
1728 $userjs = Skin
::makeUrl(
1729 $userpage->getPrefixedText() . '/' . $sk->getSkinName() . '.js',
1730 'action=raw&ctype=' . $wgJsMimeType );
1731 $this->addScriptFile( $userjs );
1735 $scripts .= "\n" . $this->mScripts
;
1739 protected function addDefaultMeta() {
1740 global $wgVersion, $wgHtml5;
1742 static $called = false;
1744 # Don't run this twice
1750 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); //bug 15835
1752 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
1754 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
1755 if( $p !== 'index,follow' ) {
1756 // http://www.robotstxt.org/wc/meta-user.html
1757 // Only show if it's different from the default robots policy
1758 $this->addMeta( 'robots', $p );
1761 if ( count( $this->mKeywords
) > 0 ) {
1763 "/<.*?" . ">/" => '',
1766 $this->addMeta( 'keywords', preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords
) ) );
1771 * @return string HTML tag links to be put in the header.
1773 public function getHeadLinks() {
1774 global $wgRequest, $wgFeed;
1776 // Ideally this should happen earlier, somewhere. :P
1777 $this->addDefaultMeta();
1781 foreach ( $this->mMetatags
as $tag ) {
1782 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
1784 $tag[0] = substr( $tag[0], 5 );
1788 $tags[] = Html
::element( 'meta',
1791 'content' => $tag[1] ) );
1793 foreach ( $this->mLinktags
as $tag ) {
1794 $tags[] = Html
::element( 'link', $tag );
1798 foreach( $this->getSyndicationLinks() as $format => $link ) {
1799 # Use the page name for the title (accessed through $wgTitle since
1800 # there's no other way). In principle, this could lead to issues
1801 # with having the same name for different feeds corresponding to
1802 # the same page, but we can't avoid that at this low a level.
1804 $tags[] = $this->feedLink(
1807 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
1808 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() ) );
1811 # Recent changes feed should appear on every page (except recentchanges,
1812 # that would be redundant). Put it after the per-page feed to avoid
1813 # changing existing behavior. It's still available, probably via a
1814 # menu in your browser. Some sites might have a different feed they'd
1815 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
1816 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
1817 # If so, use it instead.
1819 global $wgOverrideSiteFeed, $wgSitename, $wgFeedClasses, $wgAdvertisedFeedTypes;
1820 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
1822 if ( $wgOverrideSiteFeed ) {
1823 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
1824 $tags[] = $this->feedLink (
1826 htmlspecialchars( $feedUrl ),
1827 wfMsg( "site-{$type}-feed", $wgSitename ) );
1829 } elseif ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
1830 foreach ( $wgAdvertisedFeedTypes as $format ) {
1831 $tags[] = $this->feedLink(
1833 $rctitle->getLocalURL( "feed={$format}" ),
1834 wfMsg( "site-{$format}-feed", $wgSitename ) ); # For grep: 'site-rss-feed', 'site-atom-feed'.
1839 return implode( "\n", $tags );
1843 * Return URLs for each supported syndication format for this page.
1844 * @return array associating format keys with URLs
1846 public function getSyndicationLinks() {
1847 return $this->mFeedLinks
;
1851 * Generate a <link rel/> for an RSS feed.
1853 private function feedLink( $type, $url, $text ) {
1854 return Html
::element( 'link', array(
1855 'rel' => 'alternate',
1856 'type' => "application/$type+xml",
1862 * Add a local or specified stylesheet, with the given media options.
1863 * Meant primarily for internal use...
1865 * @param $media -- to specify a media type, 'screen', 'printable', 'handheld' or any.
1866 * @param $conditional -- for IE conditional comments, specifying an IE version
1867 * @param $dir -- set to 'rtl' or 'ltr' for direction-specific sheets
1869 public function addStyle( $style, $media='', $condition='', $dir='' ) {
1871 // Even though we expect the media type to be lowercase, but here we
1872 // force it to lowercase to be safe.
1874 $options['media'] = $media;
1876 $options['condition'] = $condition;
1878 $options['dir'] = $dir;
1879 $this->styles
[$style] = $options;
1883 * Adds inline CSS styles
1884 * @param $style_css Mixed: inline CSS
1886 public function addInlineStyle( $style_css ){
1887 $this->mScripts
.= Html
::inlineStyle( $style_css );
1891 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
1892 * These will be applied to various media & IE conditionals.
1894 public function buildCssLinks() {
1896 foreach( $this->styles
as $file => $options ) {
1897 $link = $this->styleLink( $file, $options );
1902 return implode( "\n", $links );
1905 protected function styleLink( $style, $options ) {
1908 if( isset( $options['dir'] ) ) {
1910 $siteDir = $wgContLang->getDir();
1911 if( $siteDir != $options['dir'] )
1915 if( isset( $options['media'] ) ) {
1916 $media = $this->transformCssMedia( $options['media'] );
1917 if( is_null( $media ) ) {
1924 if( substr( $style, 0, 1 ) == '/' ||
1925 substr( $style, 0, 5 ) == 'http:' ||
1926 substr( $style, 0, 6 ) == 'https:' ) {
1929 global $wgStylePath, $wgStyleVersion;
1930 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
1933 $link = Html
::linkedStyle( $url, $media );
1935 if( isset( $options['condition'] ) ) {
1936 $condition = htmlspecialchars( $options['condition'] );
1937 $link = "<!--[if $condition]>$link<![endif]-->";
1942 function transformCssMedia( $media ) {
1943 global $wgRequest, $wgHandheldForIPhone;
1945 // Switch in on-screen display for media testing
1947 'printable' => 'print',
1948 'handheld' => 'handheld',
1950 foreach( $switches as $switch => $targetMedia ) {
1951 if( $wgRequest->getBool( $switch ) ) {
1952 if( $media == $targetMedia ) {
1954 } elseif( $media == 'screen' ) {
1960 // Expand longer media queries as iPhone doesn't grok 'handheld'
1961 if( $wgHandheldForIPhone ) {
1962 $mediaAliases = array(
1963 'screen' => 'screen and (min-device-width: 481px)',
1964 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
1967 if( isset( $mediaAliases[$media] ) ) {
1968 $media = $mediaAliases[$media];
1976 * Turn off regular page output and return an error reponse
1977 * for when rate limiting has triggered.
1979 public function rateLimited() {
1981 $this->setPageTitle(wfMsg('actionthrottled'));
1982 $this->setRobotPolicy( 'noindex,follow' );
1983 $this->setArticleRelated( false );
1984 $this->enableClientCache( false );
1985 $this->mRedirect
= '';
1987 $this->setStatusCode(503);
1988 $this->addWikiMsg( 'actionthrottledtext' );
1990 $this->returnToMain( null, $this->getTitle() );
1994 * Show an "add new section" link?
1998 public function showNewSectionLink() {
1999 return $this->mNewSectionLink
;
2003 * Forcibly hide the new section link?
2007 public function forceHideNewSectionLink() {
2008 return $this->mHideNewSectionLink
;
2012 * Show a warning about slave lag
2014 * If the lag is higher than $wgSlaveLagCritical seconds,
2015 * then the warning is a bit more obvious. If the lag is
2016 * lower than $wgSlaveLagWarning, then no warning is shown.
2018 * @param int $lag Slave lag
2020 public function showLagWarning( $lag ) {
2021 global $wgSlaveLagWarning, $wgSlaveLagCritical, $wgLang;
2022 if( $lag >= $wgSlaveLagWarning ) {
2023 $message = $lag < $wgSlaveLagCritical
2026 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2027 $this->wrapWikiMsg( "$wrap\n", array( $message, $wgLang->formatNum( $lag ) ) );
2032 * Add a wikitext-formatted message to the output.
2033 * This is equivalent to:
2035 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2037 public function addWikiMsg( /*...*/ ) {
2038 $args = func_get_args();
2039 $name = array_shift( $args );
2040 $this->addWikiMsgArray( $name, $args );
2044 * Add a wikitext-formatted message to the output.
2045 * Like addWikiMsg() except the parameters are taken as an array
2046 * instead of a variable argument list.
2048 * $options is passed through to wfMsgExt(), see that function for details.
2050 public function addWikiMsgArray( $name, $args, $options = array() ) {
2051 $options[] = 'parse';
2052 $text = wfMsgExt( $name, $options, $args );
2053 $this->addHTML( $text );
2057 * This function takes a number of message/argument specifications, wraps them in
2058 * some overall structure, and then parses the result and adds it to the output.
2060 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
2061 * on. The subsequent arguments may either be strings, in which case they are the
2062 * message names, or arrays, in which case the first element is the message name,
2063 * and subsequent elements are the parameters to that message.
2065 * The special named parameter 'options' in a message specification array is passed
2066 * through to the $options parameter of wfMsgExt().
2068 * Don't use this for messages that are not in users interface language.
2072 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>", 'some-error' );
2076 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . '</div>' );
2078 * The newline after opening div is needed in some wikitext. See bug 19226.
2080 public function wrapWikiMsg( $wrap /*, ...*/ ) {
2081 $msgSpecs = func_get_args();
2082 array_shift( $msgSpecs );
2083 $msgSpecs = array_values( $msgSpecs );
2085 foreach ( $msgSpecs as $n => $spec ) {
2087 if ( is_array( $spec ) ) {
2089 $name = array_shift( $args );
2090 if ( isset( $args['options'] ) ) {
2091 $options = $args['options'];
2092 unset( $args['options'] );
2098 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
2100 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );