2 if ( ! defined( 'MEDIAWIKI' ) )
9 var $mMetatags = array(), $mKeywords = array(), $mLinktags = array();
10 var $mExtStyles = array();
11 var $mPagetitle = '', $mBodytext = '', $mDebugtext = '';
12 var $mHTMLtitle = '', $mIsarticle = true, $mPrintable = false;
13 var $mSubtitle = '', $mRedirect = '', $mStatusCode;
14 var $mLastModified = '', $mETag = false;
15 var $mCategoryLinks = array(), $mCategories = array(), $mLanguageLinks = array();
17 var $mScripts = '', $mLinkColours, $mPageLinkTitle = '', $mHeadItems = array();
18 var $mInlineMsg = array();
20 var $mTemplateIds = array();
23 var $mSuppressQuickbar = false;
24 var $mDoNothing = false;
25 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
26 var $mIsArticleRelated = true;
27 protected $mParserOptions = null; // lazy initialised, use parserOptions()
29 var $mFeedLinks = array();
31 var $mEnableClientCache = true;
32 var $mArticleBodyOnly = false;
34 var $mNewSectionLink = false;
35 var $mHideNewSectionLink = false;
36 var $mNoGallery = false;
37 var $mPageTitleActionText = '';
38 var $mParseWarnings = array();
39 var $mSquidMaxage = 0;
40 var $mRevisionId = null;
41 protected $mTitle = null;
44 * An array of stylesheet filenames (relative from skins path), with options
45 * for CSS media, IE conditions, and RTL/LTR direction.
46 * For internal use; add settings in the skin via $this->addStyle()
48 var $styles = array();
51 * Whether to load jQuery core.
53 protected $mIncludeJQuery = false;
55 private $mIndexPolicy = 'index';
56 private $mFollowPolicy = 'follow';
57 private $mVaryHeader = array( 'Accept-Encoding' => array('list-contains=gzip'),
62 * Initialise private variables
64 function __construct() {
65 global $wgAllowUserJs;
66 $this->mAllowUserJs
= $wgAllowUserJs;
69 public function redirect( $url, $responsecode = '302' ) {
70 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
71 $this->mRedirect
= str_replace( "\n", '', $url );
72 $this->mRedirectCode
= $responsecode;
75 public function getRedirect() {
76 return $this->mRedirect
;
80 * Set the HTTP status code to send with the output.
82 * @param int $statusCode
85 function setStatusCode( $statusCode ) { $this->mStatusCode
= $statusCode; }
88 * Add a new <meta> tag
89 * To add an http-equiv meta tag, precede the name with "http:"
91 * @param $name tag name
92 * @param $val tag value
94 function addMeta( $name, $val ) {
95 array_push( $this->mMetatags
, array( $name, $val ) );
98 function addKeyword( $text ) {
99 if( is_array( $text )) {
100 $this->mKeywords
= array_merge( $this->mKeywords
, $text );
102 array_push( $this->mKeywords
, $text );
105 function addScript( $script ) {
106 $this->mScripts
.= $script . "\n";
110 * Register and add a stylesheet from an extension directory.
111 * @param $url String path to sheet. Provide either a full url (beginning
112 * with 'http', etc) or a relative path from the document root
113 * (beginning with '/'). Otherwise it behaves identically to
114 * addStyle() and draws from the /skins folder.
116 public function addExtensionStyle( $url ) {
117 array_push( $this->mExtStyles
, $url );
121 * Add a JavaScript file out of skins/common, or a given relative path.
122 * @param string $file filename in skins/common or complete on-server path (/foo/bar.js)
124 function addScriptFile( $file ) {
125 global $wgStylePath, $wgStyleVersion;
126 if( substr( $file, 0, 1 ) == '/' ) {
129 $path = "{$wgStylePath}/common/{$file}";
131 $this->addScript( Html
::linkedScript( "$path?$wgStyleVersion" ) );
135 * Add a self-contained script tag with the given contents
136 * @param string $script JavaScript text, no <script> tags
138 function addInlineScript( $script ) {
139 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
143 * Get all registered JS and CSS tags for the header.
145 function getScript() {
146 return $this->mScripts
. $this->getHeadItems();
149 function getHeadItems() {
151 foreach ( $this->mHeadItems
as $item ) {
157 function addHeadItem( $name, $value ) {
158 $this->mHeadItems
[$name] = $value;
161 function hasHeadItem( $name ) {
162 return isset( $this->mHeadItems
[$name] );
165 function setETag($tag) { $this->mETag
= $tag; }
166 function setArticleBodyOnly($only) { $this->mArticleBodyOnly
= $only; }
167 function getArticleBodyOnly() { return $this->mArticleBodyOnly
; }
169 function addLink( $linkarr ) {
170 # $linkarr should be an associative array of attributes. We'll escape on output.
171 array_push( $this->mLinktags
, $linkarr );
174 # Get all links added by extensions
175 function getExtStyle() {
176 return $this->mExtStyles
;
179 function addMetadataLink( $linkarr ) {
180 # note: buggy CC software only reads first "meta" link
181 static $haveMeta = false;
182 $linkarr['rel'] = ($haveMeta) ?
'alternate meta' : 'meta';
183 $this->addLink( $linkarr );
188 * checkLastModified tells the client to use the client-cached page if
189 * possible. If sucessful, the OutputPage is disabled so that
190 * any future call to OutputPage->output() have no effect.
192 * Side effect: sets mLastModified for Last-Modified header
194 * @return bool True iff cache-ok headers was sent.
196 function checkLastModified( $timestamp ) {
197 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
199 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
200 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
203 if( !$wgCachePages ) {
204 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
207 if( $wgUser->getOption( 'nocache' ) ) {
208 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
212 $timestamp = wfTimestamp( TS_MW
, $timestamp );
213 $modifiedTimes = array(
214 'page' => $timestamp,
215 'user' => $wgUser->getTouched(),
216 'epoch' => $wgCacheEpoch
218 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
220 $maxModified = max( $modifiedTimes );
221 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
223 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
224 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
230 foreach ( $modifiedTimes as $name => $value ) {
231 if ( $info !== '' ) {
234 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
237 # IE sends sizes after the date like this:
238 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
239 # this breaks strtotime().
240 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
242 wfSuppressWarnings(); // E_STRICT system time bitching
243 $clientHeaderTime = strtotime( $clientHeader );
245 if ( !$clientHeaderTime ) {
246 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
249 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
251 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
252 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
253 wfDebug( __METHOD__
. ": effective Last-Modified: " .
254 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
255 if( $clientHeaderTime < $maxModified ) {
256 wfDebug( __METHOD__
. ": STALE, $info\n", false );
261 # Give a 304 response code and disable body output
262 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
263 ini_set('zlib.output_compression', 0);
264 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
265 $this->sendCacheControl();
268 // Don't output a compressed blob when using ob_gzhandler;
269 // it's technically against HTTP spec and seems to confuse
270 // Firefox when the response gets split over two packets.
271 wfClearOutputBuffers();
276 function setPageTitleActionText( $text ) {
277 $this->mPageTitleActionText
= $text;
280 function getPageTitleActionText () {
281 if ( isset( $this->mPageTitleActionText
) ) {
282 return $this->mPageTitleActionText
;
287 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
289 * @param $policy string The literal string to output as the contents of
290 * the meta tag. Will be parsed according to the spec and output in
294 public function setRobotPolicy( $policy ) {
295 $policy = Article
::formatRobotPolicy( $policy );
297 if( isset( $policy['index'] ) ){
298 $this->setIndexPolicy( $policy['index'] );
300 if( isset( $policy['follow'] ) ){
301 $this->setFollowPolicy( $policy['follow'] );
306 * Set the index policy for the page, but leave the follow policy un-
309 * @param $policy string Either 'index' or 'noindex'.
312 public function setIndexPolicy( $policy ) {
313 $policy = trim( $policy );
314 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
315 $this->mIndexPolicy
= $policy;
320 * Set the follow policy for the page, but leave the index policy un-
323 * @param $policy string Either 'follow' or 'nofollow'.
326 public function setFollowPolicy( $policy ) {
327 $policy = trim( $policy );
328 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
329 $this->mFollowPolicy
= $policy;
334 * "HTML title" means the contents of <title>. It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
336 public function setHTMLTitle( $name ) {
337 $this->mHTMLtitle
= $name;
341 * "Page title" means the contents of <h1>. It is stored as a valid HTML fragment.
342 * This function allows good tags like <sup> in the <h1> tag, but not bad tags like <script>.
343 * This function automatically sets <title> to the same content as <h1> but with all tags removed.
344 * Bad tags that were escaped in <h1> will still be escaped in <title>, and good tags like <i> will be dropped entirely.
346 public function setPageTitle( $name ) {
347 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
348 # but leave "<i>foobar</i>" alone
349 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
350 $this->mPagetitle
= $nameWithTags;
352 $taction = $this->getPageTitleActionText();
353 if( !empty( $taction ) ) {
354 $name .= ' - '.$taction;
357 # change "<i>foo&bar</i>" to "foo&bar"
358 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer
::stripAllTags( $nameWithTags ) ) );
361 public function setTitle( $t ) {
365 public function getTitle() {
366 if ( $this->mTitle
instanceof Title
) {
367 return $this->mTitle
;
370 wfDebug( __METHOD__
. ' called and $mTitle is null. Return $wgTitle for sanity' );
376 public function getHTMLTitle() { return $this->mHTMLtitle
; }
377 public function getPageTitle() { return $this->mPagetitle
; }
378 public function setSubtitle( $str ) { $this->mSubtitle
= /*$this->parse(*/$str/*)*/; } // @bug 2514
379 public function appendSubtitle( $str ) { $this->mSubtitle
.= /*$this->parse(*/$str/*)*/; } // @bug 2514
380 public function getSubtitle() { return $this->mSubtitle
; }
381 public function isArticle() { return $this->mIsarticle
; }
382 public function setPrintable() { $this->mPrintable
= true; }
383 public function isPrintable() { return $this->mPrintable
; }
384 public function getFeedAppendQuery() { return $this->mFeedLinksAppendQuery
; }
385 public function disable() { $this->mDoNothing
= true; }
386 public function isDisabled() { return $this->mDoNothing
; }
388 public function setSyndicated( $show = true ) {
390 $this->setFeedAppendQuery( false );
392 $this->mFeedLinks
= array();
396 public function setFeedAppendQuery( $val ) {
397 global $wgFeedClasses, $wgAdvertisedFeedTypes;
399 $this->mFeedLinks
= array();
401 foreach ( $wgAdvertisedFeedTypes as $type ) {
402 $query = "feed=$type";
403 if ( is_string( $val ) ) {
404 $query .= '&' . $val;
406 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
410 public function addFeedLink( $format, $href ) {
411 $this->mFeedLinks
[$format] = $href;
414 public function isSyndicated() { return count($this->mFeedLinks
); }
416 public function setArticleRelated( $v ) {
417 $this->mIsArticleRelated
= $v;
419 $this->mIsarticle
= false;
422 public function setArticleFlag( $v ) {
423 $this->mIsarticle
= $v;
425 $this->mIsArticleRelated
= $v;
429 public function isArticleRelated() { return $this->mIsArticleRelated
; }
431 public function getLanguageLinks() { return $this->mLanguageLinks
; }
432 public function addLanguageLinks($newLinkArray) {
433 $this->mLanguageLinks +
= $newLinkArray;
435 public function setLanguageLinks($newLinkArray) {
436 $this->mLanguageLinks
= $newLinkArray;
439 public function getCategoryLinks() {
440 return $this->mCategoryLinks
;
443 public function getCategories() {
444 return $this->mCategories
;
448 * Add an array of categories, with names in the keys
450 public function addCategoryLinks( $categories ) {
451 global $wgUser, $wgContLang;
453 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
457 # Add the links to a LinkBatch
458 $arr = array( NS_CATEGORY
=> $categories );
460 $lb->setArray( $arr );
462 # Fetch existence plus the hiddencat property
463 $dbr = wfGetDB( DB_SLAVE
);
464 $pageTable = $dbr->tableName( 'page' );
465 $where = $lb->constructSet( 'page', $dbr );
466 $propsTable = $dbr->tableName( 'page_props' );
467 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, pp_value
468 FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
469 $res = $dbr->query( $sql, __METHOD__
);
471 # Add the results to the link cache
472 $lb->addResultToCache( LinkCache
::singleton(), $res );
474 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
475 $categories = array_combine( array_keys( $categories ),
476 array_fill( 0, count( $categories ), 'normal' ) );
478 # Mark hidden categories
479 foreach ( $res as $row ) {
480 if ( isset( $row->pp_value
) ) {
481 $categories[$row->page_title
] = 'hidden';
485 # Add the remaining categories to the skin
486 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
487 $sk = $wgUser->getSkin();
488 foreach ( $categories as $category => $type ) {
489 $origcategory = $category;
490 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
491 $wgContLang->findVariantLink( $category, $title, true );
492 if ( $category != $origcategory )
493 if ( array_key_exists( $category, $categories ) )
495 $text = $wgContLang->convertHtml( $title->getText() );
496 $this->mCategories
[] = $title->getText();
497 $this->mCategoryLinks
[$type][] = $sk->link( $title, $text );
502 public function setCategoryLinks($categories) {
503 $this->mCategoryLinks
= array();
504 $this->addCategoryLinks($categories);
507 public function suppressQuickbar() { $this->mSuppressQuickbar
= true; }
508 public function isQuickbarSuppressed() { return $this->mSuppressQuickbar
; }
510 public function disallowUserJs() { $this->mAllowUserJs
= false; }
511 public function isUserJsAllowed() { return $this->mAllowUserJs
; }
513 public function prependHTML( $text ) { $this->mBodytext
= $text . $this->mBodytext
; }
514 public function addHTML( $text ) { $this->mBodytext
.= $text; }
515 public function clearHTML() { $this->mBodytext
= ''; }
516 public function getHTML() { return $this->mBodytext
; }
517 public function debug( $text ) { $this->mDebugtext
.= $text; }
520 public function setParserOptions( $options ) {
521 wfDeprecated( __METHOD__
);
522 return $this->parserOptions( $options );
525 public function parserOptions( $options = null ) {
526 if ( !$this->mParserOptions
) {
527 $this->mParserOptions
= new ParserOptions
;
529 return wfSetVar( $this->mParserOptions
, $options );
533 * Set the revision ID which will be seen by the wiki text parser
534 * for things such as embedded {{REVISIONID}} variable use.
535 * @param mixed $revid an integer, or NULL
536 * @return mixed previous value
538 public function setRevisionId( $revid ) {
539 $val = is_null( $revid ) ?
null : intval( $revid );
540 return wfSetVar( $this->mRevisionId
, $val );
543 public function getRevisionId() {
544 return $this->mRevisionId
;
548 * Convert wikitext to HTML and add it to the buffer
549 * Default assumes that the current page title will
552 * @param string $text
553 * @param bool $linestart
555 public function addWikiText( $text, $linestart = true ) {
556 $title = $this->getTitle(); // Work arround E_STRICT
557 $this->addWikiTextTitle( $text, $title, $linestart );
560 public function addWikiTextWithTitle($text, &$title, $linestart = true) {
561 $this->addWikiTextTitle($text, $title, $linestart);
564 function addWikiTextTitleTidy($text, &$title, $linestart = true) {
565 $this->addWikiTextTitle( $text, $title, $linestart, true );
568 public function addWikiTextTitle($text, &$title, $linestart, $tidy = false) {
571 wfProfileIn( __METHOD__
);
573 wfIncrStats( 'pcache_not_possible' );
575 $popts = $this->parserOptions();
576 $oldTidy = $popts->setTidy( $tidy );
578 $parserOutput = $wgParser->parse( $text, $title, $popts,
579 $linestart, true, $this->mRevisionId
);
581 $popts->setTidy( $oldTidy );
583 $this->addParserOutput( $parserOutput );
585 wfProfileOut( __METHOD__
);
590 * @param ParserOutput object &$parserOutput
592 public function addParserOutputNoText( &$parserOutput ) {
593 global $wgExemptFromUserRobotsControl, $wgContentNamespaces;
595 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
596 $this->addCategoryLinks( $parserOutput->getCategories() );
597 $this->mNewSectionLink
= $parserOutput->getNewSection();
598 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
600 $this->mParseWarnings
= $parserOutput->getWarnings();
601 if ( $parserOutput->getCacheTime() == -1 ) {
602 $this->enableClientCache( false );
604 $this->mNoGallery
= $parserOutput->getNoGallery();
605 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
607 foreach ( (array)$parserOutput->mTemplateIds
as $ns => $dbks ) {
608 if ( isset( $this->mTemplateIds
[$ns] ) ) {
609 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
611 $this->mTemplateIds
[$ns] = $dbks;
615 $title = $parserOutput->getTitleText();
616 if ( $title != '' ) {
617 $this->setPageTitle( $title );
620 // Hooks registered in the object
621 global $wgParserOutputHooks;
622 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
623 list( $hookName, $data ) = $hookInfo;
624 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
625 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
629 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
634 * @param ParserOutput &$parserOutput
636 function addParserOutput( &$parserOutput ) {
637 $this->addParserOutputNoText( $parserOutput );
638 $text = $parserOutput->getText();
639 wfRunHooks( 'OutputPageBeforeHTML',array( &$this, &$text ) );
640 $this->addHTML( $text );
644 * Add wikitext to the buffer, assuming that this is the primary text for a page view
645 * Saves the text into the parser cache if possible.
647 * @param string $text
648 * @param Article $article
650 * @deprecated Use Article::outputWikitext
652 public function addPrimaryWikiText( $text, $article, $cache = true ) {
655 wfDeprecated( __METHOD__
);
657 $popts = $this->parserOptions();
658 $popts->setTidy(true);
659 $parserOutput = $wgParser->parse( $text, $article->mTitle
,
660 $popts, true, true, $this->mRevisionId
);
661 $popts->setTidy(false);
662 if ( $cache && $article && $parserOutput->getCacheTime() != -1 ) {
663 $parserCache = ParserCache
::singleton();
664 $parserCache->save( $parserOutput, $article, $popts);
667 $this->addParserOutput( $parserOutput );
671 * @deprecated use addWikiTextTidy()
673 public function addSecondaryWikiText( $text, $linestart = true ) {
674 wfDeprecated( __METHOD__
);
675 $this->addWikiTextTitleTidy($text, $this->getTitle(), $linestart);
679 * Add wikitext with tidy enabled
681 public function addWikiTextTidy( $text, $linestart = true ) {
682 $title = $this->getTitle();
683 $this->addWikiTextTitleTidy($text, $title, $linestart);
688 * Add the output of a QuickTemplate to the output buffer
690 * @param QuickTemplate $template
692 public function addTemplate( &$template ) {
694 $template->execute();
695 $this->addHTML( ob_get_contents() );
700 * Parse wikitext and return the HTML.
702 * @param string $text
703 * @param bool $linestart Is this the start of a line?
704 * @param bool $interface ??
706 public function parse( $text, $linestart = true, $interface = false ) {
708 if( is_null( $this->getTitle() ) ) {
709 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
711 $popts = $this->parserOptions();
712 if ( $interface) { $popts->setInterfaceMessage(true); }
713 $parserOutput = $wgParser->parse( $text, $this->getTitle(), $popts,
714 $linestart, true, $this->mRevisionId
);
715 if ( $interface) { $popts->setInterfaceMessage(false); }
716 return $parserOutput->getText();
719 /** Parse wikitext, strip paragraphs, and return the HTML. */
720 public function parseInline( $text, $linestart = true, $interface = false ) {
721 $parsed = $this->parse( $text, $linestart, $interface );
724 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
732 * @param Article $article
737 * @return bool True if successful, else false.
739 public function tryParserCache( &$article ) {
740 wfDeprecated( __METHOD__
);
741 $parserOutput = ParserCache
::singleton()->get( $article, $article->getParserOptions() );
743 if ($parserOutput !== false) {
744 $this->addParserOutput( $parserOutput );
752 * @param int $maxage Maximum cache time on the Squid, in seconds.
754 public function setSquidMaxage( $maxage ) {
755 $this->mSquidMaxage
= $maxage;
759 * Use enableClientCache(false) to force it to send nocache headers
762 public function enableClientCache( $state ) {
763 return wfSetVar( $this->mEnableClientCache
, $state );
766 function getCacheVaryCookies() {
767 global $wgCookiePrefix, $wgCacheVaryCookies;
769 if ( $cookies === null ) {
770 $cookies = array_merge(
772 "{$wgCookiePrefix}Token",
773 "{$wgCookiePrefix}LoggedOut",
778 wfRunHooks('GetCacheVaryCookies', array( $this, &$cookies ) );
783 function uncacheableBecauseRequestVars() {
785 return $wgRequest->getText('useskin', false) === false
786 && $wgRequest->getText('uselang', false) === false;
790 * Check if the request has a cache-varying cookie header
791 * If it does, it's very important that we don't allow public caching
793 function haveCacheVaryCookies() {
795 $cookieHeader = $wgRequest->getHeader( 'cookie' );
796 if ( $cookieHeader === false ) {
799 $cvCookies = $this->getCacheVaryCookies();
800 foreach ( $cvCookies as $cookieName ) {
801 # Check for a simple string match, like the way squid does it
802 if ( strpos( $cookieHeader, $cookieName ) ) {
803 wfDebug( __METHOD__
.": found $cookieName\n" );
807 wfDebug( __METHOD__
.": no cache-varying cookies found\n" );
811 public function addVaryHeader( $header, $option = null ) {
812 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
813 $this->mVaryHeader
[$header] = $option;
815 elseif( is_array( $option ) ) {
816 if( is_array( $this->mVaryHeader
[$header] ) ) {
817 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
820 $this->mVaryHeader
[$header] = $option;
823 $this->mVaryHeader
[$header] = array_unique( $this->mVaryHeader
[$header] );
826 /** Get a complete X-Vary-Options header */
827 public function getXVO() {
828 $cvCookies = $this->getCacheVaryCookies();
830 $cookiesOption = array();
831 foreach ( $cvCookies as $cookieName ) {
832 $cookiesOption[] = 'string-contains=' . $cookieName;
834 $this->addVaryHeader( 'Cookie', $cookiesOption );
837 foreach( $this->mVaryHeader
as $header => $option ) {
838 $newheader = $header;
839 if( is_array( $option ) )
840 $newheader .= ';' . implode( ';', $option );
841 $headers[] = $newheader;
843 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
848 /** bug 21672: Add Accept-Language to Vary and XVO headers
849 if there's no 'variant' parameter existed in GET.
852 /w/index.php?title=Main_page should always be served; but
853 /w/index.php?title=Main_page&variant=zh-cn should never be served.
855 patched by Liangent and Philip */
856 function addAcceptLanguage() {
857 global $wgRequest, $wgContLang;
858 if( !$wgRequest->getCheck('variant') && $wgContLang->hasVariants() ) {
859 $variants = $wgContLang->getVariants();
861 foreach ( $variants as $variant ) {
862 if( $variant === $wgContLang->getCode() )
865 $aloption[] = "string-contains=$variant";
867 $this->addVaryHeader( 'Accept-Language', $aloption );
871 public function sendCacheControl() {
872 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest, $wgUseXVO;
874 $response = $wgRequest->response();
875 if ($wgUseETag && $this->mETag
)
876 $response->header("ETag: $this->mETag");
878 $this->addAcceptLanguage();
880 # don't serve compressed data to clients who can't handle it
881 # maintain different caches for logged-in users and non-logged in ones
882 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) ) );
885 # Add an X-Vary-Options header for Squid with Wikimedia patches
886 $response->header( $this->getXVO() );
889 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
890 if( $wgUseSquid && session_id() == '' &&
891 ! $this->isPrintable() && $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies() )
894 # We'll purge the proxy cache explicitly, but require end user agents
895 # to revalidate against the proxy on each visit.
896 # Surrogate-Control controls our Squid, Cache-Control downstream caches
897 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
898 # start with a shorter timeout for initial testing
899 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
900 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
901 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
903 # We'll purge the proxy cache for anons explicitly, but require end user agents
904 # to revalidate against the proxy on each visit.
905 # IMPORTANT! The Squid needs to replace the Cache-Control header with
906 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
907 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
908 # start with a shorter timeout for initial testing
909 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
910 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
913 # We do want clients to cache if they can, but they *must* check for updates
914 # on revisiting the page.
915 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
916 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
917 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
919 if($this->mLastModified
) {
920 $response->header( "Last-Modified: {$this->mLastModified}" );
923 wfDebug( __METHOD__
. ": no caching **\n", false );
925 # In general, the absence of a last modified header should be enough to prevent
926 # the client from using its cache. We send a few other things just to make sure.
927 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
928 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
929 $response->header( 'Pragma: no-cache' );
931 wfRunHooks('CacheHeadersAfterSet', array( $this ) );
935 * Get the message associed with the HTTP response code $code
937 * @param $code Integer: status code
938 * @return String or null: message or null if $code is not in the list of
941 public static function getStatusMessage( $code ) {
942 static $statusMessage = array(
944 101 => 'Switching Protocols',
949 203 => 'Non-Authoritative Information',
951 205 => 'Reset Content',
952 206 => 'Partial Content',
953 207 => 'Multi-Status',
954 300 => 'Multiple Choices',
955 301 => 'Moved Permanently',
958 304 => 'Not Modified',
960 307 => 'Temporary Redirect',
961 400 => 'Bad Request',
962 401 => 'Unauthorized',
963 402 => 'Payment Required',
966 405 => 'Method Not Allowed',
967 406 => 'Not Acceptable',
968 407 => 'Proxy Authentication Required',
969 408 => 'Request Timeout',
972 411 => 'Length Required',
973 412 => 'Precondition Failed',
974 413 => 'Request Entity Too Large',
975 414 => 'Request-URI Too Large',
976 415 => 'Unsupported Media Type',
977 416 => 'Request Range Not Satisfiable',
978 417 => 'Expectation Failed',
979 422 => 'Unprocessable Entity',
981 424 => 'Failed Dependency',
982 500 => 'Internal Server Error',
983 501 => 'Not Implemented',
984 502 => 'Bad Gateway',
985 503 => 'Service Unavailable',
986 504 => 'Gateway Timeout',
987 505 => 'HTTP Version Not Supported',
988 507 => 'Insufficient Storage'
990 return isset( $statusMessage[$code] ) ?
$statusMessage[$code] : null;
994 * Finally, all the text has been munged and accumulated into
995 * the object, let's actually output it:
997 public function output() {
998 global $wgUser, $wgOutputEncoding, $wgRequest;
999 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
1000 global $wgUseAjax, $wgAjaxWatch;
1001 global $wgEnableMWSuggest, $wgUniversalEditButton;
1004 if( $this->mDoNothing
){
1007 wfProfileIn( __METHOD__
);
1008 if ( $this->mRedirect
!= '' ) {
1009 # Standards require redirect URLs to be absolute
1010 $this->mRedirect
= wfExpandUrl( $this->mRedirect
);
1011 if( $this->mRedirectCode
== '301' ||
$this->mRedirectCode
== '303' ) {
1012 if( !$wgDebugRedirects ) {
1013 $message = self
::getStatusMessage( $this->mRedirectCode
);
1014 $wgRequest->response()->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
1016 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1018 $this->sendCacheControl();
1020 $wgRequest->response()->header( "Content-Type: text/html; charset=utf-8" );
1021 if( $wgDebugRedirects ) {
1022 $url = htmlspecialchars( $this->mRedirect
);
1023 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1024 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1025 print "</body>\n</html>\n";
1027 $wgRequest->response()->header( 'Location: ' . $this->mRedirect
);
1029 wfProfileOut( __METHOD__
);
1031 } elseif ( $this->mStatusCode
) {
1032 $message = self
::getStatusMessage( $this->mStatusCode
);
1034 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
1037 $sk = $wgUser->getSkin();
1040 $this->addScriptFile( 'ajax.js' );
1042 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1044 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1045 $this->addScriptFile( 'ajaxwatch.js' );
1048 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ){
1049 $this->addScriptFile( 'mwsuggest.js' );
1053 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1054 $this->addScriptFile( 'rightclickedit.js' );
1057 if( $wgUniversalEditButton ) {
1058 if( isset( $wgArticle ) && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1059 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create' ) ) ) {
1060 // Original UniversalEditButton
1061 $msg = wfMsg('edit');
1062 $this->addLink( array(
1063 'rel' => 'alternate',
1064 'type' => 'application/x-wiki',
1066 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1068 // Alternate edit link
1069 $this->addLink( array(
1072 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1077 # Buffer output; final headers may depend on later processing
1080 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1081 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
1083 if ($this->mArticleBodyOnly
) {
1084 $this->out($this->mBodytext
);
1086 // Hook that allows last minute changes to the output page, e.g.
1087 // adding of CSS or Javascript by extensions.
1088 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1090 wfProfileIn( 'Output-skin' );
1091 $sk->outputPage( $this );
1092 wfProfileOut( 'Output-skin' );
1095 $this->sendCacheControl();
1097 wfProfileOut( __METHOD__
);
1101 * Actually output something with print(). Performs an iconv to the
1102 * output encoding, if needed.
1103 * @param string $ins The string to output
1105 public function out( $ins ) {
1106 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1107 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1110 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1111 if ( false === $outs ) { $outs = $ins; }
1119 public static function setEncodings() {
1120 global $wgInputEncoding, $wgOutputEncoding;
1123 $wgInputEncoding = strtolower( $wgInputEncoding );
1125 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
1126 $wgOutputEncoding = strtolower( $wgOutputEncoding );
1129 $wgOutputEncoding = $wgInputEncoding;
1133 * Deprecated, use wfReportTime() instead.
1137 public function reportTime() {
1138 wfDeprecated( __METHOD__
);
1139 $time = wfReportTime();
1144 * Produce a "user is blocked" page.
1146 * @param bool $return Whether to have a "return to $wgTitle" message or not.
1149 function blockedPage( $return = true ) {
1150 global $wgUser, $wgContLang, $wgLang;
1152 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1153 $this->setRobotPolicy( 'noindex,nofollow' );
1154 $this->setArticleRelated( false );
1156 $name = User
::whoIs( $wgUser->blockedBy() );
1157 $reason = $wgUser->blockedFor();
1158 if( $reason == '' ) {
1159 $reason = wfMsg( 'blockednoreason' );
1161 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $wgUser->mBlock
->mTimestamp
), true );
1164 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1166 $blockid = $wgUser->mBlock
->mId
;
1168 $blockExpiry = $wgUser->mBlock
->mExpiry
;
1169 if ( $blockExpiry == 'infinity' ) {
1170 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1171 // Search for localization in 'ipboptions'
1172 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1173 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1174 if ( strpos( $option, ":" ) === false )
1176 list( $show, $value ) = explode( ":", $option );
1177 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1178 $blockExpiry = $show;
1183 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1186 if ( $wgUser->mBlock
->mAuto
) {
1187 $msg = 'autoblockedtext';
1189 $msg = 'blockedtext';
1192 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1193 * This could be a username, an ip range, or a single ip. */
1194 $intended = $wgUser->mBlock
->mAddress
;
1196 $this->addWikiMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
1198 # Don't auto-return to special pages
1200 $return = $this->getTitle()->getNamespace() > -1 ?
$this->getTitle() : null;
1201 $this->returnToMain( null, $return );
1206 * Output a standard error page
1208 * @param string $title Message key for page title
1209 * @param string $msg Message key for page text
1210 * @param array $params Message parameters
1212 public function showErrorPage( $title, $msg, $params = array() ) {
1213 if ( $this->getTitle() ) {
1214 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1216 $this->setPageTitle( wfMsg( $title ) );
1217 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1218 $this->setRobotPolicy( 'noindex,nofollow' );
1219 $this->setArticleRelated( false );
1220 $this->enableClientCache( false );
1221 $this->mRedirect
= '';
1222 $this->mBodytext
= '';
1224 array_unshift( $params, 'parse' );
1225 array_unshift( $params, $msg );
1226 $this->addHTML( call_user_func_array( 'wfMsgExt', $params ) );
1228 $this->returnToMain();
1232 * Output a standard permission error page
1234 * @param array $errors Error message keys
1236 public function showPermissionsErrorPage( $errors, $action = null )
1238 $this->mDebugtext
.= 'Original title: ' .
1239 $this->getTitle()->getPrefixedText() . "\n";
1240 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1241 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1242 $this->setRobotPolicy( 'noindex,nofollow' );
1243 $this->setArticleRelated( false );
1244 $this->enableClientCache( false );
1245 $this->mRedirect
= '';
1246 $this->mBodytext
= '';
1247 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1251 public function errorpage( $title, $msg ) {
1252 wfDeprecated( __METHOD__
);
1253 throw new ErrorPageError( $title, $msg );
1257 * Display an error page indicating that a given version of MediaWiki is
1258 * required to use it
1260 * @param mixed $version The version of MediaWiki needed to use the page
1262 public function versionRequired( $version ) {
1263 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1264 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1265 $this->setRobotPolicy( 'noindex,nofollow' );
1266 $this->setArticleRelated( false );
1267 $this->mBodytext
= '';
1269 $this->addWikiMsg( 'versionrequiredtext', $version );
1270 $this->returnToMain();
1274 * Display an error page noting that a given permission bit is required.
1276 * @param string $permission key required
1278 public function permissionRequired( $permission ) {
1281 $this->setPageTitle( wfMsg( 'badaccess' ) );
1282 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1283 $this->setRobotPolicy( 'noindex,nofollow' );
1284 $this->setArticleRelated( false );
1285 $this->mBodytext
= '';
1287 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1288 User
::getGroupsWithPermission( $permission ) );
1290 $this->addWikiMsg( 'badaccess-groups',
1291 $wgLang->commaList( $groups ),
1294 $this->addWikiMsg( 'badaccess-group0' );
1296 $this->returnToMain();
1300 * Use permissionRequired.
1303 public function sysopRequired() {
1304 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
1308 * Use permissionRequired.
1311 public function developerRequired() {
1312 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
1316 * Produce the stock "please login to use the wiki" page
1318 public function loginToUse() {
1319 global $wgUser, $wgContLang;
1321 if( $wgUser->isLoggedIn() ) {
1322 $this->permissionRequired( 'read' );
1326 $skin = $wgUser->getSkin();
1328 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1329 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1330 $this->setRobotPolicy( 'noindex,nofollow' );
1331 $this->setArticleFlag( false );
1333 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1334 $loginLink = $skin->link(
1336 wfMsgHtml( 'loginreqlink' ),
1338 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
1339 array( 'known', 'noclasses' )
1341 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1342 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . "-->" );
1344 # Don't return to the main page if the user can't read it
1345 # otherwise we'll end up in a pointless loop
1346 $mainPage = Title
::newMainPage();
1347 if( $mainPage->userCanRead() )
1348 $this->returnToMain( null, $mainPage );
1352 public function databaseError( $fname, $sql, $error, $errno ) {
1353 throw new MWException( "OutputPage::databaseError is obsolete\n" );
1357 * @param array $errors An array of arrays returned by Title::getUserPermissionsErrors
1358 * @return string The wikitext error-messages, formatted into a list.
1360 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1361 if ($action == null) {
1362 $text = wfMsgNoTrans( 'permissionserrorstext', count($errors)). "\n\n";
1365 $action_desc = wfMsgNoTrans( "action-$action" );
1366 $text = wfMsgNoTrans( 'permissionserrorstext-withaction', count($errors), $action_desc ) . "\n\n";
1369 if (count( $errors ) > 1) {
1370 $text .= '<ul class="permissions-errors">' . "\n";
1372 foreach( $errors as $error )
1375 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1380 $text .= "<div class=\"permissions-errors\">\n" . call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) . "\n</div>";
1387 * Display a page stating that the Wiki is in read-only mode,
1388 * and optionally show the source of the page that the user
1389 * was trying to edit. Should only be called (for this
1390 * purpose) after wfReadOnly() has returned true.
1392 * For historical reasons, this function is _also_ used to
1393 * show the error message when a user tries to edit a page
1394 * they are not allowed to edit. (Unless it's because they're
1395 * blocked, then we show blockedPage() instead.) In this
1396 * case, the second parameter should be set to true and a list
1397 * of reasons supplied as the third parameter.
1399 * @todo Needs to be split into multiple functions.
1401 * @param string $source Source code to show (or null).
1402 * @param bool $protected Is this a permissions error?
1403 * @param array $reasons List of reasons for this error, as returned by Title::getUserPermissionsErrors().
1405 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1407 $skin = $wgUser->getSkin();
1409 $this->setRobotPolicy( 'noindex,nofollow' );
1410 $this->setArticleRelated( false );
1412 // If no reason is given, just supply a default "I can't let you do
1413 // that, Dave" message. Should only occur if called by legacy code.
1414 if ( $protected && empty($reasons) ) {
1415 $reasons[] = array( 'badaccess-group0' );
1418 if ( !empty($reasons) ) {
1419 // Permissions error
1421 $this->setPageTitle( wfMsg( 'viewsource' ) );
1430 array( 'known', 'noclasses' )
1435 $this->setPageTitle( wfMsg( 'badaccess' ) );
1437 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1439 // Wiki is read only
1440 $this->setPageTitle( wfMsg( 'readonly' ) );
1441 $reason = wfReadOnlyReason();
1442 $this->wrapWikiMsg( '<div class="mw-readonly-error">\n$1</div>', array( 'readonlytext', $reason ) );
1445 // Show source, if supplied
1446 if( is_string( $source ) ) {
1447 $this->addWikiMsg( 'viewsourcetext' );
1450 'id' => 'wpTextbox1',
1451 'name' => 'wpTextbox1',
1452 'cols' => $wgUser->getOption( 'cols' ),
1453 'rows' => $wgUser->getOption( 'rows' ),
1454 'readonly' => 'readonly'
1456 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
1458 // Show templates used by this article
1459 $skin = $wgUser->getSkin();
1460 $article = new Article( $this->getTitle() );
1461 $this->addHTML( "<div class='templatesUsed'>
1462 {$skin->formatTemplates( $article->getUsedTemplates() )}
1467 # If the title doesn't exist, it's fairly pointless to print a return
1468 # link to it. After all, you just tried editing it and couldn't, so
1469 # what's there to do there?
1470 if( $this->getTitle()->exists() ) {
1471 $this->returnToMain( null, $this->getTitle() );
1476 public function fatalError( $message ) {
1477 wfDeprecated( __METHOD__
);
1478 throw new FatalError( $message );
1482 public function unexpectedValueError( $name, $val ) {
1483 wfDeprecated( __METHOD__
);
1484 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1488 public function fileCopyError( $old, $new ) {
1489 wfDeprecated( __METHOD__
);
1490 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1494 public function fileRenameError( $old, $new ) {
1495 wfDeprecated( __METHOD__
);
1496 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1500 public function fileDeleteError( $name ) {
1501 wfDeprecated( __METHOD__
);
1502 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1506 public function fileNotFoundError( $name ) {
1507 wfDeprecated( __METHOD__
);
1508 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1511 public function showFatalError( $message ) {
1512 $this->setPageTitle( wfMsg( "internalerror" ) );
1513 $this->setRobotPolicy( "noindex,nofollow" );
1514 $this->setArticleRelated( false );
1515 $this->enableClientCache( false );
1516 $this->mRedirect
= '';
1517 $this->mBodytext
= $message;
1520 public function showUnexpectedValueError( $name, $val ) {
1521 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
1524 public function showFileCopyError( $old, $new ) {
1525 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
1528 public function showFileRenameError( $old, $new ) {
1529 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
1532 public function showFileDeleteError( $name ) {
1533 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
1536 public function showFileNotFoundError( $name ) {
1537 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1541 * Add a "return to" link pointing to a specified title
1543 * @param $title Title to link
1544 * @param $query String: query string
1546 public function addReturnTo( $title, $query = array() ) {
1548 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullUrl() ) );
1549 $link = wfMsgHtml( 'returnto', $wgUser->getSkin()->link(
1550 $title, null, array(), $query ) );
1551 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
1555 * Add a "return to" link pointing to a specified title,
1556 * or the title indicated in the request, or else the main page
1558 * @param $unused No longer used
1559 * @param $returnto Title or String to return to
1560 * @param $returntoquery String: query string for the return to link
1562 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
1565 if ( $returnto == null ) {
1566 $returnto = $wgRequest->getText( 'returnto' );
1569 if ( $returntoquery == null ) {
1570 $returntoquery = $wgRequest->getText( 'returntoquery' );
1573 if ( $returnto === '' ) {
1574 $returnto = Title
::newMainPage();
1577 if ( is_object( $returnto ) ) {
1578 $titleObj = $returnto;
1580 $titleObj = Title
::newFromText( $returnto );
1582 if ( !is_object( $titleObj ) ) {
1583 $titleObj = Title
::newMainPage();
1586 $this->addReturnTo( $titleObj, $returntoquery );
1590 * @return string The doctype, opening <html>, and head element.
1592 * @param $sk Skin The given Skin
1594 public function headElement( Skin
$sk, $includeStyle = true ) {
1595 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1596 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces, $wgHtml5Version;
1597 global $wgContLang, $wgUseTrackbacks, $wgStyleVersion, $wgHtml5, $wgWellFormedXml;
1598 global $wgUser, $wgRequest, $wgLang;
1600 $this->addMeta( "http:Content-Type", "$wgMimeType; charset={$wgOutputEncoding}" );
1601 if ( $sk->commonPrintStylesheet() ) {
1602 $this->addStyle( 'common/wikiprintable.css', 'print' );
1604 $sk->setupUserCss( $this );
1608 if( $wgMimeType == 'text/xml' ||
$wgMimeType == 'application/xhtml+xml' ||
$wgMimeType == 'application/xml' ) {
1609 $ret .= "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?" . ">\n";
1612 if ( $this->getHTMLTitle() == '' ) {
1613 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1616 $dir = $wgContLang->getDir();
1619 if ( $wgWellFormedXml ) {
1620 # Unknown elements and attributes are okay in XML, but unknown
1621 # named entities are well-formedness errors and will break XML
1622 # parsers. Thus we need a doctype that gives us appropriate
1623 # entity definitions. The HTML5 spec permits four legacy
1624 # doctypes as obsolete but conforming, so let's pick one of
1625 # those, although it makes our pages look like XHTML1 Strict.
1626 # Isn't compatibility great?
1627 $ret .= "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n";
1630 $ret .= "<!doctype html>\n";
1632 $ret .= "<html lang=\"$wgContLanguageCode\" dir=\"$dir\" ";
1633 if ( $wgHtml5Version ) $ret .= " version=\"$wgHtml5Version\" ";
1636 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\" \"$wgDTD\">\n";
1637 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1638 foreach($wgXhtmlNamespaces as $tag => $ns) {
1639 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1641 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" dir=\"$dir\">\n";
1645 $ret .= "<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n";
1646 $ret .= implode( "\n", array(
1647 $this->getHeadLinks(),
1648 $this->buildCssLinks(),
1649 $this->getHeadScripts( $sk ),
1650 $this->getHeadItems(),
1653 $ret .= Html
::inlineStyle( $sk->usercss
);
1656 if ($wgUseTrackbacks && $this->isArticleRelated())
1657 $ret .= $this->getTitle()->trackbackRDF();
1659 $ret .= "</head>\n";
1661 $bodyAttrs = array();
1663 # Crazy edit-on-double-click stuff
1664 $action = $wgRequest->getVal( 'action', 'view' );
1666 if ( $this->getTitle()->getNamespace() != NS_SPECIAL
1667 && !in_array( $action, array( 'edit', 'submit' ) )
1668 && $wgUser->getOption( 'editondblclick' ) ) {
1669 $bodyAttrs['ondblclick'] = "document.location = '" . Xml
::escapeJsString( $this->getTitle()->getEditURL() ) . "'";
1673 $bodyAttrs['class'] = "mediawiki $dir";
1675 if ( $wgLang->capitalizeAllNouns() ) {
1676 # A <body> class is probably not the best way to do this . . .
1677 $bodyAttrs['class'] .= ' capitalize-all-nouns';
1679 $bodyAttrs['class'] .= ' ns-' . $this->getTitle()->getNamespace();
1680 if ( $this->getTitle()->getNamespace() == NS_SPECIAL
) {
1681 $bodyAttrs['class'] .= ' ns-special';
1682 } elseif ( $this->getTitle()->isTalkPage() ) {
1683 $bodyAttrs['class'] .= ' ns-talk';
1685 $bodyAttrs['class'] .= ' ns-subject';
1687 $bodyAttrs['class'] .= ' ' . Sanitizer
::escapeClass( 'page-' . $this->getTitle()->getPrefixedText() );
1688 $bodyAttrs['class'] .= ' skin-' . Sanitizer
::escapeClass( $wgUser->getSkin()->getSkinName() );
1690 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
1696 * gets the global variables and mScripts
1698 * also adds userjs to the end if enabled:
1700 function getHeadScripts( Skin
$sk ) {
1701 global $wgUser, $wgRequest, $wgJsMimeType, $wgUseSiteJs;
1702 global $wgStylePath, $wgStyleVersion;
1704 $scripts = Skin
::makeGlobalVariablesScript( $sk->getSkinName() );
1705 $scripts .= Html
::linkedScript( "{$wgStylePath}/common/wikibits.js?$wgStyleVersion" );
1707 //add site JS if enabled:
1708 if( $wgUseSiteJs ) {
1709 $jsCache = $wgUser->isLoggedIn() ?
'&smaxage=0' : '';
1710 $this->addScriptFile( Skin
::makeUrl( '-',
1711 "action=raw$jsCache&gen=js&useskin=" .
1712 urlencode( $sk->getSkinName() )
1717 //add user js if enabled:
1718 if( $this->isUserJsAllowed() && $wgUser->isLoggedIn() ) {
1719 $action = $wgRequest->getVal( 'action', 'view' );
1720 if( $this->mTitle
&& $this->mTitle
->isJsSubpage() and $sk->userCanPreview( $action ) ) {
1721 # XXX: additional security check/prompt?
1722 $this->addInlineScript( $wgRequest->getText( 'wpTextbox1' ) );
1724 $userpage = $wgUser->getUserPage();
1725 $scriptpage = Title
::makeTitleSafe(
1727 $userpage->getDBkey() . '/' . $sk->getSkinName() . '.js'
1729 if ( $scriptpage && $scriptpage->exists() ) {
1730 $userjs = Skin
::makeUrl( $scriptpage->getPrefixedText(), 'action=raw&ctype=' . $wgJsMimeType );
1731 $this->addScriptFile( $userjs );
1736 $scripts .= "\n" . $this->mScripts
;
1740 protected function addDefaultMeta() {
1741 global $wgVersion, $wgHtml5;
1743 static $called = false;
1745 # Don't run this twice
1751 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); //bug 15835
1753 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
1755 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
1756 if( $p !== 'index,follow' ) {
1757 // http://www.robotstxt.org/wc/meta-user.html
1758 // Only show if it's different from the default robots policy
1759 $this->addMeta( 'robots', $p );
1762 if ( count( $this->mKeywords
) > 0 ) {
1764 "/<.*?" . ">/" => '',
1767 $this->addMeta( 'keywords', preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords
) ) );
1772 * @return string HTML tag links to be put in the header.
1774 public function getHeadLinks() {
1775 global $wgRequest, $wgFeed;
1777 // Ideally this should happen earlier, somewhere. :P
1778 $this->addDefaultMeta();
1782 foreach ( $this->mMetatags
as $tag ) {
1783 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
1785 $tag[0] = substr( $tag[0], 5 );
1789 $tags[] = Html
::element( 'meta',
1792 'content' => $tag[1] ) );
1794 foreach ( $this->mLinktags
as $tag ) {
1795 $tags[] = Html
::element( 'link', $tag );
1799 foreach( $this->getSyndicationLinks() as $format => $link ) {
1800 # Use the page name for the title (accessed through $wgTitle since
1801 # there's no other way). In principle, this could lead to issues
1802 # with having the same name for different feeds corresponding to
1803 # the same page, but we can't avoid that at this low a level.
1805 $tags[] = $this->feedLink(
1808 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
1809 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() ) );
1812 # Recent changes feed should appear on every page (except recentchanges,
1813 # that would be redundant). Put it after the per-page feed to avoid
1814 # changing existing behavior. It's still available, probably via a
1815 # menu in your browser. Some sites might have a different feed they'd
1816 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
1817 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
1818 # If so, use it instead.
1820 global $wgOverrideSiteFeed, $wgSitename, $wgFeedClasses, $wgAdvertisedFeedTypes;
1821 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
1823 if ( $wgOverrideSiteFeed ) {
1824 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
1825 $tags[] = $this->feedLink (
1827 htmlspecialchars( $feedUrl ),
1828 wfMsg( "site-{$type}-feed", $wgSitename ) );
1830 } elseif ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
1831 foreach ( $wgAdvertisedFeedTypes as $format ) {
1832 $tags[] = $this->feedLink(
1834 $rctitle->getLocalURL( "feed={$format}" ),
1835 wfMsg( "site-{$format}-feed", $wgSitename ) ); # For grep: 'site-rss-feed', 'site-atom-feed'.
1840 return implode( "\n", $tags );
1844 * Return URLs for each supported syndication format for this page.
1845 * @return array associating format keys with URLs
1847 public function getSyndicationLinks() {
1848 return $this->mFeedLinks
;
1852 * Generate a <link rel/> for an RSS feed.
1854 private function feedLink( $type, $url, $text ) {
1855 return Html
::element( 'link', array(
1856 'rel' => 'alternate',
1857 'type' => "application/$type+xml",
1863 * Add a local or specified stylesheet, with the given media options.
1864 * Meant primarily for internal use...
1866 * @param $media -- to specify a media type, 'screen', 'printable', 'handheld' or any.
1867 * @param $conditional -- for IE conditional comments, specifying an IE version
1868 * @param $dir -- set to 'rtl' or 'ltr' for direction-specific sheets
1870 public function addStyle( $style, $media='', $condition='', $dir='' ) {
1872 // Even though we expect the media type to be lowercase, but here we
1873 // force it to lowercase to be safe.
1875 $options['media'] = $media;
1877 $options['condition'] = $condition;
1879 $options['dir'] = $dir;
1880 $this->styles
[$style] = $options;
1884 * Adds inline CSS styles
1885 * @param $style_css Mixed: inline CSS
1887 public function addInlineStyle( $style_css ){
1888 $this->mScripts
.= Html
::inlineStyle( $style_css );
1892 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
1893 * These will be applied to various media & IE conditionals.
1895 public function buildCssLinks() {
1897 foreach( $this->styles
as $file => $options ) {
1898 $link = $this->styleLink( $file, $options );
1903 return implode( "\n", $links );
1906 protected function styleLink( $style, $options ) {
1909 if( isset( $options['dir'] ) ) {
1911 $siteDir = $wgContLang->getDir();
1912 if( $siteDir != $options['dir'] )
1916 if( isset( $options['media'] ) ) {
1917 $media = $this->transformCssMedia( $options['media'] );
1918 if( is_null( $media ) ) {
1925 if( substr( $style, 0, 1 ) == '/' ||
1926 substr( $style, 0, 5 ) == 'http:' ||
1927 substr( $style, 0, 6 ) == 'https:' ) {
1930 global $wgStylePath, $wgStyleVersion;
1931 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
1934 $link = Html
::linkedStyle( $url, $media );
1936 if( isset( $options['condition'] ) ) {
1937 $condition = htmlspecialchars( $options['condition'] );
1938 $link = "<!--[if $condition]>$link<![endif]-->";
1943 function transformCssMedia( $media ) {
1944 global $wgRequest, $wgHandheldForIPhone;
1946 // Switch in on-screen display for media testing
1948 'printable' => 'print',
1949 'handheld' => 'handheld',
1951 foreach( $switches as $switch => $targetMedia ) {
1952 if( $wgRequest->getBool( $switch ) ) {
1953 if( $media == $targetMedia ) {
1955 } elseif( $media == 'screen' ) {
1961 // Expand longer media queries as iPhone doesn't grok 'handheld'
1962 if( $wgHandheldForIPhone ) {
1963 $mediaAliases = array(
1964 'screen' => 'screen and (min-device-width: 481px)',
1965 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
1968 if( isset( $mediaAliases[$media] ) ) {
1969 $media = $mediaAliases[$media];
1977 * Turn off regular page output and return an error reponse
1978 * for when rate limiting has triggered.
1980 public function rateLimited() {
1982 $this->setPageTitle(wfMsg('actionthrottled'));
1983 $this->setRobotPolicy( 'noindex,follow' );
1984 $this->setArticleRelated( false );
1985 $this->enableClientCache( false );
1986 $this->mRedirect
= '';
1988 $this->setStatusCode(503);
1989 $this->addWikiMsg( 'actionthrottledtext' );
1991 $this->returnToMain( null, $this->getTitle() );
1995 * Show an "add new section" link?
1999 public function showNewSectionLink() {
2000 return $this->mNewSectionLink
;
2004 * Forcibly hide the new section link?
2008 public function forceHideNewSectionLink() {
2009 return $this->mHideNewSectionLink
;
2013 * Show a warning about slave lag
2015 * If the lag is higher than $wgSlaveLagCritical seconds,
2016 * then the warning is a bit more obvious. If the lag is
2017 * lower than $wgSlaveLagWarning, then no warning is shown.
2019 * @param int $lag Slave lag
2021 public function showLagWarning( $lag ) {
2022 global $wgSlaveLagWarning, $wgSlaveLagCritical, $wgLang;
2023 if( $lag >= $wgSlaveLagWarning ) {
2024 $message = $lag < $wgSlaveLagCritical
2027 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2028 $this->wrapWikiMsg( "$wrap\n", array( $message, $wgLang->formatNum( $lag ) ) );
2033 * Add a wikitext-formatted message to the output.
2034 * This is equivalent to:
2036 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2038 public function addWikiMsg( /*...*/ ) {
2039 $args = func_get_args();
2040 $name = array_shift( $args );
2041 $this->addWikiMsgArray( $name, $args );
2045 * Add a wikitext-formatted message to the output.
2046 * Like addWikiMsg() except the parameters are taken as an array
2047 * instead of a variable argument list.
2049 * $options is passed through to wfMsgExt(), see that function for details.
2051 public function addWikiMsgArray( $name, $args, $options = array() ) {
2052 $options[] = 'parse';
2053 $text = wfMsgExt( $name, $options, $args );
2054 $this->addHTML( $text );
2058 * This function takes a number of message/argument specifications, wraps them in
2059 * some overall structure, and then parses the result and adds it to the output.
2061 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
2062 * on. The subsequent arguments may either be strings, in which case they are the
2063 * message names, or arrays, in which case the first element is the message name,
2064 * and subsequent elements are the parameters to that message.
2066 * The special named parameter 'options' in a message specification array is passed
2067 * through to the $options parameter of wfMsgExt().
2069 * Don't use this for messages that are not in users interface language.
2073 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>", 'some-error' );
2077 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . '</div>' );
2079 * The newline after opening div is needed in some wikitext. See bug 19226.
2081 public function wrapWikiMsg( $wrap /*, ...*/ ) {
2082 $msgSpecs = func_get_args();
2083 array_shift( $msgSpecs );
2084 $msgSpecs = array_values( $msgSpecs );
2086 foreach ( $msgSpecs as $n => $spec ) {
2088 if ( is_array( $spec ) ) {
2090 $name = array_shift( $args );
2091 if ( isset( $args['options'] ) ) {
2092 $options = $args['options'];
2093 unset( $args['options'] );
2099 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
2101 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );
2105 * Include jQuery core. Use this to avoid loading it multiple times
2106 * before we get usable script loader.
2108 public function includeJQuery() {
2109 if ( $this->mIncludeJQuery
) return;
2110 $this->mIncludeJQuery
= true;
2112 global $wgScriptPath, $wgStyleVersion, $wgJsMimeType;
2115 'type' => $wgJsMimeType,
2116 'src' => "$wgScriptPath/js2/js2stopgap.min.js?$wgStyleVersion",
2118 $this->mScripts
= Html
::element( 'script', $params ) . "\n" . $this->mScripts
;