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(), $mLanguageLinks = array();
16 var $mScripts = '', $mLinkColours, $mPageLinkTitle = '', $mHeadItems = array();
17 var $mTemplateIds = array();
20 var $mSuppressQuickbar = false;
21 var $mOnloadHandler = '';
22 var $mDoNothing = false;
23 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
24 var $mIsArticleRelated = true;
25 protected $mParserOptions = null; // lazy initialised, use parserOptions()
26 var $mShowFeedLinks = false;
27 var $mFeedLinksAppendQuery = false;
28 var $mEnableClientCache = true;
29 var $mArticleBodyOnly = false;
31 var $mNewSectionLink = false;
32 var $mHideNewSectionLink = false;
33 var $mNoGallery = false;
34 var $mPageTitleActionText = '';
35 var $mParseWarnings = array();
36 var $mSquidMaxage = 0;
37 var $mRevisionId = null;
38 protected $mTitle = null;
41 * An array of stylesheet filenames (relative from skins path), with options
42 * for CSS media, IE conditions, and RTL/LTR direction.
43 * For internal use; add settings in the skin via $this->addStyle()
45 var $styles = array();
47 private $mIndexPolicy = 'index';
48 private $mFollowPolicy = 'follow';
52 * Initialise private variables
54 function __construct() {
55 global $wgAllowUserJs;
56 $this->mAllowUserJs
= $wgAllowUserJs;
59 public function redirect( $url, $responsecode = '302' ) {
60 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
61 $this->mRedirect
= str_replace( "\n", '', $url );
62 $this->mRedirectCode
= $responsecode;
65 public function getRedirect() {
66 return $this->mRedirect
;
70 * Set the HTTP status code to send with the output.
72 * @param int $statusCode
75 function setStatusCode( $statusCode ) { $this->mStatusCode
= $statusCode; }
78 * Add a new <meta> tag
79 * To add an http-equiv meta tag, precede the name with "http:"
81 * @param $name tag name
82 * @param $val tag value
84 function addMeta( $name, $val ) {
85 array_push( $this->mMetatags
, array( $name, $val ) );
88 function addKeyword( $text ) {
89 if( is_array( $text )) {
90 $this->mKeywords
= array_merge( $this->mKeywords
, $text );
93 array_push( $this->mKeywords
, $text );
96 function addScript( $script ) { $this->mScripts
.= "\t\t".$script; }
98 function addExtensionStyle( $url ) {
99 $linkarr = array( 'rel' => 'stylesheet', 'href' => $url, 'type' => 'text/css' );
100 array_push( $this->mExtStyles
, $linkarr );
104 * Add a JavaScript file out of skins/common, or a given relative path.
105 * @param string $file filename in skins/common or complete on-server path (/foo/bar.js)
107 function addScriptFile( $file ) {
108 global $wgStylePath, $wgStyleVersion, $wgJsMimeType;
109 if( substr( $file, 0, 1 ) == '/' ) {
112 $path = "{$wgStylePath}/common/{$file}";
115 Xml
::element( 'script',
117 'type' => $wgJsMimeType,
118 'src' => "$path?$wgStyleVersion",
126 * Add a self-contained script tag with the given contents
127 * @param string $script JavaScript text, no <script> tags
129 function addInlineScript( $script ) {
130 global $wgJsMimeType;
131 $this->mScripts
.= "<script type=\"$wgJsMimeType\">/*<![CDATA[*/\n$script\n/*]]>*/</script>";
134 function getScript() {
135 return $this->mScripts
. $this->getHeadItems();
138 function getHeadItems() {
140 foreach ( $this->mHeadItems
as $item ) {
146 function addHeadItem( $name, $value ) {
147 $this->mHeadItems
[$name] = $value;
150 function hasHeadItem( $name ) {
151 return isset( $this->mHeadItems
[$name] );
154 function setETag($tag) { $this->mETag
= $tag; }
155 function setArticleBodyOnly($only) { $this->mArticleBodyOnly
= $only; }
156 function getArticleBodyOnly($only) { return $this->mArticleBodyOnly
; }
158 function addLink( $linkarr ) {
159 # $linkarr should be an associative array of attributes. We'll escape on output.
160 array_push( $this->mLinktags
, $linkarr );
163 # Get all links added by extensions
164 function getExtStyle() {
165 return $this->mExtStyles
;
168 function addMetadataLink( $linkarr ) {
169 # note: buggy CC software only reads first "meta" link
170 static $haveMeta = false;
171 $linkarr['rel'] = ($haveMeta) ?
'alternate meta' : 'meta';
172 $this->addLink( $linkarr );
177 * checkLastModified tells the client to use the client-cached page if
178 * possible. If sucessful, the OutputPage is disabled so that
179 * any future call to OutputPage->output() have no effect.
181 * Side effect: sets mLastModified for Last-Modified header
183 * @return bool True iff cache-ok headers was sent.
185 function checkLastModified( $timestamp ) {
186 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
188 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
189 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
192 if( !$wgCachePages ) {
193 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
196 if( $wgUser->getOption( 'nocache' ) ) {
197 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
201 $timestamp = wfTimestamp( TS_MW
, $timestamp );
202 $modifiedTimes = array(
203 'page' => $timestamp,
204 'user' => $wgUser->getTouched(),
205 'epoch' => $wgCacheEpoch
207 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
209 $maxModified = max( $modifiedTimes );
210 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
212 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
213 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
219 foreach ( $modifiedTimes as $name => $value ) {
220 if ( $info !== '' ) {
223 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
226 # IE sends sizes after the date like this:
227 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
228 # this breaks strtotime().
229 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
231 wfSuppressWarnings(); // E_STRICT system time bitching
232 $clientHeaderTime = strtotime( $clientHeader );
234 if ( !$clientHeaderTime ) {
235 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
238 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
240 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
241 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
242 wfDebug( __METHOD__
. ": effective Last-Modified: " .
243 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
244 if( $clientHeaderTime < $maxModified ) {
245 wfDebug( __METHOD__
. ": STALE, $info\n", false );
250 # Give a 304 response code and disable body output
251 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
252 ini_set('zlib.output_compression', 0);
253 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
254 $this->sendCacheControl();
257 // Don't output a compressed blob when using ob_gzhandler;
258 // it's technically against HTTP spec and seems to confuse
259 // Firefox when the response gets split over two packets.
260 wfClearOutputBuffers();
265 function setPageTitleActionText( $text ) {
266 $this->mPageTitleActionText
= $text;
269 function getPageTitleActionText () {
270 if ( isset( $this->mPageTitleActionText
) ) {
271 return $this->mPageTitleActionText
;
276 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
278 * @param $policy string The literal string to output as the contents of
279 * the meta tag. Will be parsed according to the spec and output in
283 public function setRobotPolicy( $policy ) {
284 $policy = explode( ',', $policy );
285 $policy = array_map( 'trim', $policy );
287 # The default policy is follow, so if nothing is said explicitly, we
289 if( in_array( 'nofollow', $policy ) ) {
290 $this->mFollowPolicy
= 'nofollow';
292 $this->mFollowPolicy
= 'follow';
295 if( in_array( 'noindex', $policy ) ) {
296 $this->mIndexPolicy
= 'noindex';
298 $this->mIndexPolicy
= 'index';
303 * Set the index policy for the page, but leave the follow policy un-
306 * @param $policy string Either 'index' or 'noindex'.
309 public function setIndexPolicy( $policy ) {
310 $policy = trim( $policy );
311 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
312 $this->mIndexPolicy
= $policy;
317 * Set the follow policy for the page, but leave the index policy un-
320 * @param $policy string Either 'follow' or 'nofollow'.
323 public function setFollowPolicy( $policy ) {
324 $policy = trim( $policy );
325 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
326 $this->mFollowPolicy
= $policy;
331 * "HTML title" means the contents of <title>. It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
333 public function setHTMLTitle( $name ) {
334 $this->mHTMLtitle
= $name;
338 * "Page title" means the contents of <h1>. It is stored as a valid HTML fragment.
339 * This function allows good tags like <sup> in the <h1> tag, but not bad tags like <script>.
340 * This function automatically sets <title> to the same content as <h1> but with all tags removed.
341 * Bad tags that were escaped in <h1> will still be escaped in <title>, and good tags like <i> will be dropped entirely.
343 public function setPageTitle( $name ) {
345 $name = $wgContLang->convert( $name, true );
346 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
347 # but leave "<i>foobar</i>" alone
348 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
349 $this->mPagetitle
= $nameWithTags;
351 $taction = $this->getPageTitleActionText();
352 if( !empty( $taction ) ) {
353 $name .= ' - '.$taction;
356 # change "<i>foo&bar</i>" to "foo&bar"
357 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer
::stripAllTags( $nameWithTags ) ) );
360 public function setTitle( $t ) {
364 public function getTitle() {
365 if ( $this->mTitle
instanceof Title
) {
366 return $this->mTitle
;
369 wfDebug( __METHOD__
. ' called and $mTitle is null. Return $wgTitle for sanity' );
375 public function getHTMLTitle() { return $this->mHTMLtitle
; }
376 public function getPageTitle() { return $this->mPagetitle
; }
377 public function setSubtitle( $str ) { $this->mSubtitle
= /*$this->parse(*/$str/*)*/; } // @bug 2514
378 public function appendSubtitle( $str ) { $this->mSubtitle
.= /*$this->parse(*/$str/*)*/; } // @bug 2514
379 public function getSubtitle() { return $this->mSubtitle
; }
380 public function isArticle() { return $this->mIsarticle
; }
381 public function setPrintable() { $this->mPrintable
= true; }
382 public function isPrintable() { return $this->mPrintable
; }
383 public function setSyndicated( $show = true ) { $this->mShowFeedLinks
= $show; }
384 public function isSyndicated() { return $this->mShowFeedLinks
; }
385 public function setFeedAppendQuery( $val ) { $this->mFeedLinksAppendQuery
= $val; }
386 public function getFeedAppendQuery() { return $this->mFeedLinksAppendQuery
; }
387 public function setOnloadHandler( $js ) { $this->mOnloadHandler
= $js; }
388 public function getOnloadHandler() { return $this->mOnloadHandler
; }
389 public function disable() { $this->mDoNothing
= true; }
390 public function isDisabled() { return $this->mDoNothing
; }
392 public function setArticleRelated( $v ) {
393 $this->mIsArticleRelated
= $v;
395 $this->mIsarticle
= false;
398 public function setArticleFlag( $v ) {
399 $this->mIsarticle
= $v;
401 $this->mIsArticleRelated
= $v;
405 public function isArticleRelated() { return $this->mIsArticleRelated
; }
407 public function getLanguageLinks() { return $this->mLanguageLinks
; }
408 public function addLanguageLinks($newLinkArray) {
409 $this->mLanguageLinks +
= $newLinkArray;
411 public function setLanguageLinks($newLinkArray) {
412 $this->mLanguageLinks
= $newLinkArray;
415 public function getCategoryLinks() {
416 return $this->mCategoryLinks
;
420 * Add an array of categories, with names in the keys
422 public function addCategoryLinks( $categories ) {
423 global $wgUser, $wgContLang;
425 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
429 # Add the links to a LinkBatch
430 $arr = array( NS_CATEGORY
=> $categories );
432 $lb->setArray( $arr );
434 # Fetch existence plus the hiddencat property
435 $dbr = wfGetDB( DB_SLAVE
);
436 $pageTable = $dbr->tableName( 'page' );
437 $where = $lb->constructSet( 'page', $dbr );
438 $propsTable = $dbr->tableName( 'page_props' );
439 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, pp_value
440 FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
441 $res = $dbr->query( $sql, __METHOD__
);
443 # Add the results to the link cache
444 $lb->addResultToCache( LinkCache
::singleton(), $res );
446 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
447 $categories = array_combine( array_keys( $categories ),
448 array_fill( 0, count( $categories ), 'normal' ) );
450 # Mark hidden categories
451 foreach ( $res as $row ) {
452 if ( isset( $row->pp_value
) ) {
453 $categories[$row->page_title
] = 'hidden';
457 # Add the remaining categories to the skin
458 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
459 $sk = $wgUser->getSkin();
460 foreach ( $categories as $category => $type ) {
461 $origcategory = $category;
462 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
463 $wgContLang->findVariantLink( $category, $title, true );
464 if ( $category != $origcategory )
465 if ( array_key_exists( $category, $categories ) )
467 $text = $wgContLang->convertHtml( $title->getText() );
468 $this->mCategoryLinks
[$type][] = $sk->link( $title, $text );
473 public function setCategoryLinks($categories) {
474 $this->mCategoryLinks
= array();
475 $this->addCategoryLinks($categories);
478 public function suppressQuickbar() { $this->mSuppressQuickbar
= true; }
479 public function isQuickbarSuppressed() { return $this->mSuppressQuickbar
; }
481 public function disallowUserJs() { $this->mAllowUserJs
= false; }
482 public function isUserJsAllowed() { return $this->mAllowUserJs
; }
484 public function prependHTML( $text ) { $this->mBodytext
= $text . $this->mBodytext
; }
485 public function addHTML( $text ) { $this->mBodytext
.= $text; }
486 public function clearHTML() { $this->mBodytext
= ''; }
487 public function getHTML() { return $this->mBodytext
; }
488 public function debug( $text ) { $this->mDebugtext
.= $text; }
491 public function setParserOptions( $options ) {
492 wfDeprecated( __METHOD__
);
493 return $this->parserOptions( $options );
496 public function parserOptions( $options = null ) {
497 if ( !$this->mParserOptions
) {
498 $this->mParserOptions
= new ParserOptions
;
500 return wfSetVar( $this->mParserOptions
, $options );
504 * Set the revision ID which will be seen by the wiki text parser
505 * for things such as embedded {{REVISIONID}} variable use.
506 * @param mixed $revid an integer, or NULL
507 * @return mixed previous value
509 public function setRevisionId( $revid ) {
510 $val = is_null( $revid ) ?
null : intval( $revid );
511 return wfSetVar( $this->mRevisionId
, $val );
514 public function getRevisionId() {
515 return $this->mRevisionId
;
519 * Convert wikitext to HTML and add it to the buffer
520 * Default assumes that the current page title will
523 * @param string $text
524 * @param bool $linestart
526 public function addWikiText( $text, $linestart = true ) {
527 $title = $this->getTitle(); // Work arround E_STRICT
528 $this->addWikiTextTitle( $text, $title, $linestart );
531 public function addWikiTextWithTitle($text, &$title, $linestart = true) {
532 $this->addWikiTextTitle($text, $title, $linestart);
535 function addWikiTextTitleTidy($text, &$title, $linestart = true) {
536 $this->addWikiTextTitle( $text, $title, $linestart, true );
539 public function addWikiTextTitle($text, &$title, $linestart, $tidy = false) {
542 wfProfileIn( __METHOD__
);
544 wfIncrStats( 'pcache_not_possible' );
546 $popts = $this->parserOptions();
547 $oldTidy = $popts->setTidy( $tidy );
549 $parserOutput = $wgParser->parse( $text, $title, $popts,
550 $linestart, true, $this->mRevisionId
);
552 $popts->setTidy( $oldTidy );
554 $this->addParserOutput( $parserOutput );
556 wfProfileOut( __METHOD__
);
561 * @param ParserOutput object &$parserOutput
563 public function addParserOutputNoText( &$parserOutput ) {
564 global $wgExemptFromUserRobotsControl, $wgContentNamespaces;
566 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
567 $this->addCategoryLinks( $parserOutput->getCategories() );
568 $this->mNewSectionLink
= $parserOutput->getNewSection();
569 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
571 if( is_null( $wgExemptFromUserRobotsControl ) ) {
572 $bannedNamespaces = $wgContentNamespaces;
574 $bannedNamespaces = $wgExemptFromUserRobotsControl;
576 if( !in_array( $this->getTitle()->getNamespace(), $bannedNamespaces ) ) {
577 # FIXME (bug 14900): This overrides $wgArticleRobotPolicies, and it
579 $this->setIndexPolicy( $parserOutput->getIndexPolicy() );
582 $this->addKeywords( $parserOutput );
583 $this->mParseWarnings
= $parserOutput->getWarnings();
584 if ( $parserOutput->getCacheTime() == -1 ) {
585 $this->enableClientCache( false );
587 $this->mNoGallery
= $parserOutput->getNoGallery();
588 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$parserOutput->mHeadItems
);
590 foreach ( (array)$parserOutput->mTemplateIds
as $ns => $dbks ) {
591 if ( isset( $this->mTemplateIds
[$ns] ) ) {
592 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
594 $this->mTemplateIds
[$ns] = $dbks;
598 if( ( $dt = $parserOutput->getDisplayTitle() ) !== false )
599 $this->setPageTitle( $dt );
600 else if ( ( $title = $parserOutput->getTitleText() ) != '' )
601 $this->setPageTitle( $title );
603 // Hooks registered in the object
604 global $wgParserOutputHooks;
605 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
606 list( $hookName, $data ) = $hookInfo;
607 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
608 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
612 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
617 * @param ParserOutput &$parserOutput
619 function addParserOutput( &$parserOutput ) {
620 $this->addParserOutputNoText( $parserOutput );
621 $text = $parserOutput->getText();
622 wfRunHooks( 'OutputPageBeforeHTML',array( &$this, &$text ) );
623 $this->addHTML( $text );
627 * Add wikitext to the buffer, assuming that this is the primary text for a page view
628 * Saves the text into the parser cache if possible.
630 * @param string $text
631 * @param Article $article
633 * @deprecated Use Article::outputWikitext
635 public function addPrimaryWikiText( $text, $article, $cache = true ) {
638 wfDeprecated( __METHOD__
);
640 $popts = $this->parserOptions();
641 $popts->setTidy(true);
642 $parserOutput = $wgParser->parse( $text, $article->mTitle
,
643 $popts, true, true, $this->mRevisionId
);
644 $popts->setTidy(false);
645 if ( $cache && $article && $parserOutput->getCacheTime() != -1 ) {
646 $parserCache = ParserCache
::singleton();
647 $parserCache->save( $parserOutput, $article, $popts);
650 $this->addParserOutput( $parserOutput );
654 * @deprecated use addWikiTextTidy()
656 public function addSecondaryWikiText( $text, $linestart = true ) {
657 wfDeprecated( __METHOD__
);
658 $this->addWikiTextTitleTidy($text, $this->getTitle(), $linestart);
662 * Add wikitext with tidy enabled
664 public function addWikiTextTidy( $text, $linestart = true ) {
665 $title = $this->getTitle();
666 $this->addWikiTextTitleTidy($text, $title, $linestart);
671 * Add the output of a QuickTemplate to the output buffer
673 * @param QuickTemplate $template
675 public function addTemplate( &$template ) {
677 $template->execute();
678 $this->addHTML( ob_get_contents() );
683 * Parse wikitext and return the HTML.
685 * @param string $text
686 * @param bool $linestart Is this the start of a line?
687 * @param bool $interface ??
689 public function parse( $text, $linestart = true, $interface = false ) {
691 if( is_null( $this->getTitle() ) ) {
692 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
694 $popts = $this->parserOptions();
695 if ( $interface) { $popts->setInterfaceMessage(true); }
696 $parserOutput = $wgParser->parse( $text, $this->getTitle(), $popts,
697 $linestart, true, $this->mRevisionId
);
698 if ( $interface) { $popts->setInterfaceMessage(false); }
699 return $parserOutput->getText();
702 /** Parse wikitext, strip paragraphs, and return the HTML. */
703 public function parseInline( $text, $linestart = true, $interface = false ) {
704 $parsed = $this->parse( $text, $linestart, $interface );
707 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
715 * @param Article $article
718 * @return bool True if successful, else false.
720 public function tryParserCache( &$article ) {
721 $parserCache = ParserCache
::singleton();
722 $parserOutput = $parserCache->get( $article, $this->parserOptions() );
723 if ( $parserOutput !== false ) {
724 $this->addParserOutput( $parserOutput );
732 * @param int $maxage Maximum cache time on the Squid, in seconds.
734 public function setSquidMaxage( $maxage ) {
735 $this->mSquidMaxage
= $maxage;
739 * Use enableClientCache(false) to force it to send nocache headers
742 public function enableClientCache( $state ) {
743 return wfSetVar( $this->mEnableClientCache
, $state );
746 function getCacheVaryCookies() {
747 global $wgCookiePrefix, $wgCacheVaryCookies;
749 if ( $cookies === null ) {
750 $cookies = array_merge(
752 "{$wgCookiePrefix}Token",
753 "{$wgCookiePrefix}LoggedOut",
758 wfRunHooks('GetCacheVaryCookies', array( $this, &$cookies ) );
763 function uncacheableBecauseRequestVars() {
765 return $wgRequest->getText('useskin', false) === false
766 && $wgRequest->getText('uselang', false) === false;
770 * Check if the request has a cache-varying cookie header
771 * If it does, it's very important that we don't allow public caching
773 function haveCacheVaryCookies() {
775 $cookieHeader = $wgRequest->getHeader( 'cookie' );
776 if ( $cookieHeader === false ) {
779 $cvCookies = $this->getCacheVaryCookies();
780 foreach ( $cvCookies as $cookieName ) {
781 # Check for a simple string match, like the way squid does it
782 if ( strpos( $cookieHeader, $cookieName ) ) {
783 wfDebug( __METHOD__
.": found $cookieName\n" );
787 wfDebug( __METHOD__
.": no cache-varying cookies found\n" );
791 /** Get a complete X-Vary-Options header */
792 public function getXVO() {
793 $cvCookies = $this->getCacheVaryCookies();
794 $xvo = 'X-Vary-Options: Accept-Encoding;list-contains=gzip,Cookie;';
796 foreach ( $cvCookies as $cookieName ) {
802 $xvo .= 'string-contains=' . $cookieName;
807 public function sendCacheControl() {
808 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest;
810 $response = $wgRequest->response();
811 if ($wgUseETag && $this->mETag
)
812 $response->header("ETag: $this->mETag");
814 # don't serve compressed data to clients who can't handle it
815 # maintain different caches for logged-in users and non-logged in ones
816 $response->header( 'Vary: Accept-Encoding, Cookie' );
818 # Add an X-Vary-Options header for Squid with Wikimedia patches
819 $response->header( $this->getXVO() );
821 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
822 if( $wgUseSquid && session_id() == '' &&
823 ! $this->isPrintable() && $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies() )
826 # We'll purge the proxy cache explicitly, but require end user agents
827 # to revalidate against the proxy on each visit.
828 # Surrogate-Control controls our Squid, Cache-Control downstream caches
829 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
830 # start with a shorter timeout for initial testing
831 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
832 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
833 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
835 # We'll purge the proxy cache for anons explicitly, but require end user agents
836 # to revalidate against the proxy on each visit.
837 # IMPORTANT! The Squid needs to replace the Cache-Control header with
838 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
839 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
840 # start with a shorter timeout for initial testing
841 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
842 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
845 # We do want clients to cache if they can, but they *must* check for updates
846 # on revisiting the page.
847 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
848 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
849 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
851 if($this->mLastModified
) {
852 $response->header( "Last-Modified: {$this->mLastModified}" );
855 wfDebug( __METHOD__
. ": no caching **\n", false );
857 # In general, the absence of a last modified header should be enough to prevent
858 # the client from using its cache. We send a few other things just to make sure.
859 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
860 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
861 $response->header( 'Pragma: no-cache' );
866 * Finally, all the text has been munged and accumulated into
867 * the object, let's actually output it:
869 public function output() {
870 global $wgUser, $wgOutputEncoding, $wgRequest;
871 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
872 global $wgJsMimeType, $wgUseAjax, $wgAjaxWatch;
873 global $wgEnableMWSuggest, $wgUniversalEditButton;
876 if( $this->mDoNothing
){
880 wfProfileIn( __METHOD__
);
882 if ( '' != $this->mRedirect
) {
883 # Standards require redirect URLs to be absolute
884 $this->mRedirect
= wfExpandUrl( $this->mRedirect
);
885 if( $this->mRedirectCode
== '301') {
886 if( !$wgDebugRedirects ) {
887 $wgRequest->response()->header("HTTP/1.1 {$this->mRedirectCode} Moved Permanently");
889 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
892 $this->sendCacheControl();
894 $wgRequest->response()->header("Content-Type: text/html; charset=utf-8");
895 if( $wgDebugRedirects ) {
896 $url = htmlspecialchars( $this->mRedirect
);
897 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
898 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
899 print "</body>\n</html>\n";
901 $wgRequest->response()->header( 'Location: '.$this->mRedirect
);
903 wfProfileOut( __METHOD__
);
906 elseif ( $this->mStatusCode
)
908 $statusMessage = array(
910 101 => 'Switching Protocols',
915 203 => 'Non-Authoritative Information',
917 205 => 'Reset Content',
918 206 => 'Partial Content',
919 207 => 'Multi-Status',
920 300 => 'Multiple Choices',
921 301 => 'Moved Permanently',
924 304 => 'Not Modified',
926 307 => 'Temporary Redirect',
927 400 => 'Bad Request',
928 401 => 'Unauthorized',
929 402 => 'Payment Required',
932 405 => 'Method Not Allowed',
933 406 => 'Not Acceptable',
934 407 => 'Proxy Authentication Required',
935 408 => 'Request Timeout',
938 411 => 'Length Required',
939 412 => 'Precondition Failed',
940 413 => 'Request Entity Too Large',
941 414 => 'Request-URI Too Large',
942 415 => 'Unsupported Media Type',
943 416 => 'Request Range Not Satisfiable',
944 417 => 'Expectation Failed',
945 422 => 'Unprocessable Entity',
947 424 => 'Failed Dependency',
948 500 => 'Internal Server Error',
949 501 => 'Not Implemented',
950 502 => 'Bad Gateway',
951 503 => 'Service Unavailable',
952 504 => 'Gateway Timeout',
953 505 => 'HTTP Version Not Supported',
954 507 => 'Insufficient Storage'
957 if ( $statusMessage[$this->mStatusCode
] )
958 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $statusMessage[$this->mStatusCode
] );
961 $sk = $wgUser->getSkin();
964 $this->addScriptFile( 'ajax.js' );
966 wfRunHooks( 'AjaxAddScript', array( &$this ) );
968 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
969 $this->addScriptFile( 'ajaxwatch.js' );
972 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ){
973 $this->addScriptFile( 'mwsuggest.js' );
977 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
978 $this->addScriptFile( 'rightclickedit.js' );
981 if( $wgUniversalEditButton ) {
982 if( isset( $wgArticle ) && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
983 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create' ) ) ) {
984 // Original UniversalEditButton
985 $this->addLink( array(
986 'rel' => 'alternate',
987 'type' => 'application/x-wiki',
988 'title' => wfMsg( 'edit' ),
989 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
991 // Alternate edit link
992 $this->addLink( array(
994 'title' => wfMsg( 'edit' ),
995 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1000 # Buffer output; final headers may depend on later processing
1003 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1004 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
1006 if ($this->mArticleBodyOnly
) {
1007 $this->out($this->mBodytext
);
1009 // Hook that allows last minute changes to the output page, e.g.
1010 // adding of CSS or Javascript by extensions.
1011 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1013 wfProfileIn( 'Output-skin' );
1014 $sk->outputPage( $this );
1015 wfProfileOut( 'Output-skin' );
1018 $this->sendCacheControl();
1020 wfProfileOut( __METHOD__
);
1024 * Actually output something with print(). Performs an iconv to the
1025 * output encoding, if needed.
1026 * @param string $ins The string to output
1028 public function out( $ins ) {
1029 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1030 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1033 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1034 if ( false === $outs ) { $outs = $ins; }
1042 public static function setEncodings() {
1043 global $wgInputEncoding, $wgOutputEncoding;
1046 $wgInputEncoding = strtolower( $wgInputEncoding );
1048 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
1049 $wgOutputEncoding = strtolower( $wgOutputEncoding );
1052 $wgOutputEncoding = $wgInputEncoding;
1056 * Deprecated, use wfReportTime() instead.
1060 public function reportTime() {
1061 wfDeprecated( __METHOD__
);
1062 $time = wfReportTime();
1067 * Produce a "user is blocked" page.
1069 * @param bool $return Whether to have a "return to $wgTitle" message or not.
1072 function blockedPage( $return = true ) {
1073 global $wgUser, $wgContLang, $wgLang;
1075 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1076 $this->setRobotPolicy( 'noindex,nofollow' );
1077 $this->setArticleRelated( false );
1079 $name = User
::whoIs( $wgUser->blockedBy() );
1080 $reason = $wgUser->blockedFor();
1081 if( $reason == '' ) {
1082 $reason = wfMsg( 'blockednoreason' );
1084 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $wgUser->mBlock
->mTimestamp
), true );
1087 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1089 $blockid = $wgUser->mBlock
->mId
;
1091 $blockExpiry = $wgUser->mBlock
->mExpiry
;
1092 if ( $blockExpiry == 'infinity' ) {
1093 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1094 // Search for localization in 'ipboptions'
1095 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1096 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1097 if ( strpos( $option, ":" ) === false )
1099 list( $show, $value ) = explode( ":", $option );
1100 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1101 $blockExpiry = $show;
1106 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1109 if ( $wgUser->mBlock
->mAuto
) {
1110 $msg = 'autoblockedtext';
1112 $msg = 'blockedtext';
1115 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1116 * This could be a username, an ip range, or a single ip. */
1117 $intended = $wgUser->mBlock
->mAddress
;
1119 $this->addWikiMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
1121 # Don't auto-return to special pages
1123 $return = $this->getTitle()->getNamespace() > -1 ?
$this->getTitle() : null;
1124 $this->returnToMain( null, $return );
1129 * Output a standard error page
1131 * @param string $title Message key for page title
1132 * @param string $msg Message key for page text
1133 * @param array $params Message parameters
1135 public function showErrorPage( $title, $msg, $params = array() ) {
1136 if ( $this->getTitle() ) {
1137 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1139 $this->setPageTitle( wfMsg( $title ) );
1140 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1141 $this->setRobotPolicy( 'noindex,nofollow' );
1142 $this->setArticleRelated( false );
1143 $this->enableClientCache( false );
1144 $this->mRedirect
= '';
1145 $this->mBodytext
= '';
1147 array_unshift( $params, 'parse' );
1148 array_unshift( $params, $msg );
1149 $this->addHTML( call_user_func_array( 'wfMsgExt', $params ) );
1151 $this->returnToMain();
1155 * Output a standard permission error page
1157 * @param array $errors Error message keys
1159 public function showPermissionsErrorPage( $errors, $action = null )
1161 $this->mDebugtext
.= 'Original title: ' .
1162 $this->getTitle()->getPrefixedText() . "\n";
1163 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1164 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1165 $this->setRobotPolicy( 'noindex,nofollow' );
1166 $this->setArticleRelated( false );
1167 $this->enableClientCache( false );
1168 $this->mRedirect
= '';
1169 $this->mBodytext
= '';
1170 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1174 public function errorpage( $title, $msg ) {
1175 wfDeprecated( __METHOD__
);
1176 throw new ErrorPageError( $title, $msg );
1180 * Display an error page indicating that a given version of MediaWiki is
1181 * required to use it
1183 * @param mixed $version The version of MediaWiki needed to use the page
1185 public function versionRequired( $version ) {
1186 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1187 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1188 $this->setRobotPolicy( 'noindex,nofollow' );
1189 $this->setArticleRelated( false );
1190 $this->mBodytext
= '';
1192 $this->addWikiMsg( 'versionrequiredtext', $version );
1193 $this->returnToMain();
1197 * Display an error page noting that a given permission bit is required.
1199 * @param string $permission key required
1201 public function permissionRequired( $permission ) {
1204 $this->setPageTitle( wfMsg( 'badaccess' ) );
1205 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1206 $this->setRobotPolicy( 'noindex,nofollow' );
1207 $this->setArticleRelated( false );
1208 $this->mBodytext
= '';
1210 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1211 User
::getGroupsWithPermission( $permission ) );
1213 $this->addWikiMsg( 'badaccess-groups',
1214 $wgLang->commaList( $groups ),
1217 $this->addWikiMsg( 'badaccess-group0' );
1219 $this->returnToMain();
1223 * Use permissionRequired.
1226 public function sysopRequired() {
1227 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
1231 * Use permissionRequired.
1234 public function developerRequired() {
1235 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
1239 * Produce the stock "please login to use the wiki" page
1241 public function loginToUse() {
1242 global $wgUser, $wgContLang;
1244 if( $wgUser->isLoggedIn() ) {
1245 $this->permissionRequired( 'read' );
1249 $skin = $wgUser->getSkin();
1251 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1252 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1253 $this->setRobotPolicy( 'noindex,nofollow' );
1254 $this->setArticleFlag( false );
1256 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1257 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $this->getTitle()->getPrefixedUrl() );
1258 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1259 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . "-->" );
1261 # Don't return to the main page if the user can't read it
1262 # otherwise we'll end up in a pointless loop
1263 $mainPage = Title
::newMainPage();
1264 if( $mainPage->userCanRead() )
1265 $this->returnToMain( null, $mainPage );
1269 public function databaseError( $fname, $sql, $error, $errno ) {
1270 throw new MWException( "OutputPage::databaseError is obsolete\n" );
1274 * @param array $errors An array of arrays returned by Title::getUserPermissionsErrors
1275 * @return string The wikitext error-messages, formatted into a list.
1277 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1278 if ($action == null) {
1279 $text = wfMsgNoTrans( 'permissionserrorstext', count($errors)). "\n\n";
1282 $action_desc = wfMsgNoTrans( "action-$action" );
1283 $text = wfMsgNoTrans( 'permissionserrorstext-withaction', count($errors), $action_desc ) . "\n\n";
1286 if (count( $errors ) > 1) {
1287 $text .= '<ul class="permissions-errors">' . "\n";
1289 foreach( $errors as $error )
1292 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1297 $text .= "<div class=\"permissions-errors\">\n" . call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) . "\n</div>";
1304 * Display a page stating that the Wiki is in read-only mode,
1305 * and optionally show the source of the page that the user
1306 * was trying to edit. Should only be called (for this
1307 * purpose) after wfReadOnly() has returned true.
1309 * For historical reasons, this function is _also_ used to
1310 * show the error message when a user tries to edit a page
1311 * they are not allowed to edit. (Unless it's because they're
1312 * blocked, then we show blockedPage() instead.) In this
1313 * case, the second parameter should be set to true and a list
1314 * of reasons supplied as the third parameter.
1316 * @todo Needs to be split into multiple functions.
1318 * @param string $source Source code to show (or null).
1319 * @param bool $protected Is this a permissions error?
1320 * @param array $reasons List of reasons for this error, as returned by Title::getUserPermissionsErrors().
1322 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1324 $skin = $wgUser->getSkin();
1326 $this->setRobotPolicy( 'noindex,nofollow' );
1327 $this->setArticleRelated( false );
1329 // If no reason is given, just supply a default "I can't let you do
1330 // that, Dave" message. Should only occur if called by legacy code.
1331 if ( $protected && empty($reasons) ) {
1332 $reasons[] = array( 'badaccess-group0' );
1335 if ( !empty($reasons) ) {
1336 // Permissions error
1338 $this->setPageTitle( wfMsg( 'viewsource' ) );
1339 $this->setSubtitle( wfMsg( 'viewsourcefor', $skin->makeKnownLinkObj( $this->getTitle() ) ) );
1341 $this->setPageTitle( wfMsg( 'badaccess' ) );
1343 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1345 // Wiki is read only
1346 $this->setPageTitle( wfMsg( 'readonly' ) );
1347 $reason = wfReadOnlyReason();
1348 $this->wrapWikiMsg( '<div class="mw-readonly-error">$1</div>', array( 'readonlytext', $reason ) );
1351 // Show source, if supplied
1352 if( is_string( $source ) ) {
1353 $this->addWikiMsg( 'viewsourcetext' );
1354 $text = Xml
::openElement( 'textarea',
1355 array( 'id' => 'wpTextbox1',
1356 'name' => 'wpTextbox1',
1357 'cols' => $wgUser->getOption( 'cols' ),
1358 'rows' => $wgUser->getOption( 'rows' ),
1359 'readonly' => 'readonly' ) );
1360 $text .= htmlspecialchars( $source );
1361 $text .= Xml
::closeElement( 'textarea' );
1362 $this->addHTML( $text );
1364 // Show templates used by this article
1365 $skin = $wgUser->getSkin();
1366 $article = new Article( $this->getTitle() );
1367 $this->addHTML( "<div class='templatesUsed'>
1368 {$skin->formatTemplates( $article->getUsedTemplates() )}
1373 # If the title doesn't exist, it's fairly pointless to print a return
1374 # link to it. After all, you just tried editing it and couldn't, so
1375 # what's there to do there?
1376 if( $this->getTitle()->exists() ) {
1377 $this->returnToMain( null, $this->getTitle() );
1382 public function fatalError( $message ) {
1383 wfDeprecated( __METHOD__
);
1384 throw new FatalError( $message );
1388 public function unexpectedValueError( $name, $val ) {
1389 wfDeprecated( __METHOD__
);
1390 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1394 public function fileCopyError( $old, $new ) {
1395 wfDeprecated( __METHOD__
);
1396 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1400 public function fileRenameError( $old, $new ) {
1401 wfDeprecated( __METHOD__
);
1402 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1406 public function fileDeleteError( $name ) {
1407 wfDeprecated( __METHOD__
);
1408 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1412 public function fileNotFoundError( $name ) {
1413 wfDeprecated( __METHOD__
);
1414 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1417 public function showFatalError( $message ) {
1418 $this->setPageTitle( wfMsg( "internalerror" ) );
1419 $this->setRobotPolicy( "noindex,nofollow" );
1420 $this->setArticleRelated( false );
1421 $this->enableClientCache( false );
1422 $this->mRedirect
= '';
1423 $this->mBodytext
= $message;
1426 public function showUnexpectedValueError( $name, $val ) {
1427 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
1430 public function showFileCopyError( $old, $new ) {
1431 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
1434 public function showFileRenameError( $old, $new ) {
1435 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
1438 public function showFileDeleteError( $name ) {
1439 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
1442 public function showFileNotFoundError( $name ) {
1443 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1447 * Add a "return to" link pointing to a specified title
1449 * @param Title $title Title to link
1451 public function addReturnTo( $title ) {
1453 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullUrl() ) );
1454 $link = wfMsgHtml( 'returnto', $wgUser->getSkin()->link( $title ) );
1455 $this->addHTML( "<p>{$link}</p>\n" );
1459 * Add a "return to" link pointing to a specified title,
1460 * or the title indicated in the request, or else the main page
1462 * @param null $unused No longer used
1463 * @param Title $returnto Title to return to
1465 public function returnToMain( $unused = null, $returnto = NULL ) {
1468 if ( $returnto == NULL ) {
1469 $returnto = $wgRequest->getText( 'returnto' );
1472 if ( '' === $returnto ) {
1473 $returnto = Title
::newMainPage();
1476 if ( is_object( $returnto ) ) {
1477 $titleObj = $returnto;
1479 $titleObj = Title
::newFromText( $returnto );
1481 if ( !is_object( $titleObj ) ) {
1482 $titleObj = Title
::newMainPage();
1485 $this->addReturnTo( $titleObj );
1489 * This function takes the title (first item of mGoodLinks), categories,
1490 * existing and broken links for the page
1491 * and uses the first 10 of them for META keywords
1493 * @param ParserOutput &$parserOutput
1495 private function addKeywords( &$parserOutput ) {
1497 // Get an array of keywords if there are more than one
1498 // variant of the site language
1499 $text = $wgContLang->autoConvertToAllVariants( $this->getTitle()->getPrefixedText());
1500 // array_values: We needn't to merge variant's code name
1501 // into $this->mKeywords;
1502 // array_unique: We should insert a keyword just for once
1503 $text = array_unique( array_values( $text ));
1504 $this->addKeyword( $text );
1506 $links2d =& $parserOutput->getLinks();
1507 if ( !is_array( $links2d ) ) {
1510 foreach ( $links2d as $dbkeys ) {
1511 foreach( $dbkeys as $dbkey => $unused ) {
1512 $dbkey = $wgContLang->autoConvertToAllVariants( $dbkey );
1513 $dbkey = array_unique( array_values( $dbkey ));
1514 $this->addKeyword( $dbkey );
1515 if ( ++
$count > 10 ) {
1523 * @return string The doctype, opening <html>, and head element.
1525 public function headElement( Skin
$sk ) {
1526 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1527 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces;
1528 global $wgContLang, $wgUseTrackbacks, $wgStyleVersion;
1530 $this->addMeta( "http:Content-type", "$wgMimeType; charset={$wgOutputEncoding}" );
1531 $this->addStyle( 'common/wikiprintable.css', 'print' );
1532 $sk->setupUserCss( $this );
1536 if( $wgMimeType == 'text/xml' ||
$wgMimeType == 'application/xhtml+xml' ||
$wgMimeType == 'application/xml' ) {
1537 $ret .= "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?" . ">\n";
1540 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\"\n \"$wgDTD\">\n";
1542 if ( '' == $this->getHTMLTitle() ) {
1543 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1546 $rtl = $wgContLang->isRTL() ?
" dir='RTL'" : '';
1547 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1548 foreach($wgXhtmlNamespaces as $tag => $ns) {
1549 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1551 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" $rtl>\n";
1552 $ret .= "<head>\n<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n\t\t";
1553 $ret .= implode( "\t\t", array(
1554 $this->getHeadLinks(),
1555 $this->buildCssLinks(),
1556 $sk->getHeadScripts( $this->mAllowUserJs
),
1558 $this->getHeadItems(),
1561 $ret .= "<style type='text/css'>{$sk->usercss}</style>";
1564 if ($wgUseTrackbacks && $this->isArticleRelated())
1565 $ret .= $this->getTitle()->trackbackRDF();
1567 $ret .= "</head>\n";
1571 protected function addDefaultMeta() {
1573 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); //bug 15835
1574 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
1576 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
1577 if( $p !== 'index,follow' ) {
1578 // http://www.robotstxt.org/wc/meta-user.html
1579 // Only show if it's different from the default robots policy
1580 $this->addMeta( 'robots', $p );
1583 if ( count( $this->mKeywords
) > 0 ) {
1585 "/<.*?" . ">/" => '',
1588 $this->addMeta( 'keywords', preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords
) ) );
1593 * @return string HTML tag links to be put in the header.
1595 public function getHeadLinks() {
1596 global $wgRequest, $wgFeed;
1598 // Ideally this should happen earlier, somewhere. :P
1599 $this->addDefaultMeta();
1603 foreach ( $this->mMetatags
as $tag ) {
1604 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
1606 $tag[0] = substr( $tag[0], 5 );
1610 $tags[] = Xml
::element( 'meta',
1613 'content' => $tag[1] ) );
1615 foreach ( $this->mLinktags
as $tag ) {
1616 $tags[] = Xml
::element( 'link', $tag );
1620 foreach( $this->getSyndicationLinks() as $format => $link ) {
1621 # Use the page name for the title (accessed through $wgTitle since
1622 # there's no other way). In principle, this could lead to issues
1623 # with having the same name for different feeds corresponding to
1624 # the same page, but we can't avoid that at this low a level.
1626 $tags[] = $this->feedLink(
1629 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() ) ); # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
1632 # Recent changes feed should appear on every page (except recentchanges,
1633 # that would be redundant). Put it after the per-page feed to avoid
1634 # changing existing behavior. It's still available, probably via a
1635 # menu in your browser. Some sites might have a different feed they'd
1636 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
1637 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
1638 # If so, use it instead.
1640 global $wgOverrideSiteFeed, $wgSitename, $wgFeedClasses;
1641 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
1643 if ( $wgOverrideSiteFeed ) {
1644 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
1645 $tags[] = $this->feedLink (
1647 htmlspecialchars( $feedUrl ),
1648 wfMsg( "site-{$type}-feed", $wgSitename ) );
1651 else if ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
1652 foreach( $wgFeedClasses as $format => $class ) {
1653 $tags[] = $this->feedLink(
1655 $rctitle->getLocalURL( "feed={$format}" ),
1656 wfMsg( "site-{$format}-feed", $wgSitename ) ); # For grep: 'site-rss-feed', 'site-atom-feed'.
1661 return implode( "\n\t\t", $tags ) . "\n";
1665 * Return URLs for each supported syndication format for this page.
1666 * @return array associating format keys with URLs
1668 public function getSyndicationLinks() {
1669 global $wgFeedClasses;
1672 if( $this->isSyndicated() ) {
1673 if( is_string( $this->getFeedAppendQuery() ) ) {
1674 $appendQuery = "&" . $this->getFeedAppendQuery();
1679 foreach( $wgFeedClasses as $format => $class ) {
1680 $links[$format] = $this->getTitle()->getLocalUrl( "feed=$format{$appendQuery}" );
1687 * Generate a <link rel/> for an RSS feed.
1689 private function feedLink( $type, $url, $text ) {
1690 return Xml
::element( 'link', array(
1691 'rel' => 'alternate',
1692 'type' => "application/$type+xml",
1698 * Add a local or specified stylesheet, with the given media options.
1699 * Meant primarily for internal use...
1701 * @param $media -- to specify a media type, 'screen', 'printable', 'handheld' or any.
1702 * @param $conditional -- for IE conditional comments, specifying an IE version
1703 * @param $dir -- set to 'rtl' or 'ltr' for direction-specific sheets
1705 public function addStyle( $style, $media='', $condition='', $dir='' ) {
1708 $options['media'] = $media;
1710 $options['condition'] = $condition;
1712 $options['dir'] = $dir;
1713 $this->styles
[$style] = $options;
1717 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
1718 * These will be applied to various media & IE conditionals.
1720 public function buildCssLinks() {
1722 foreach( $this->styles
as $file => $options ) {
1723 $link = $this->styleLink( $file, $options );
1728 return implode( "\n\t\t", $links );
1731 protected function styleLink( $style, $options ) {
1734 if( isset( $options['dir'] ) ) {
1736 $siteDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
1737 if( $siteDir != $options['dir'] )
1741 if( isset( $options['media'] ) ) {
1742 $media = $this->transformCssMedia( $options['media'] );
1743 if( is_null( $media ) ) {
1750 if( substr( $style, 0, 1 ) == '/' ||
1751 substr( $style, 0, 5 ) == 'http:' ||
1752 substr( $style, 0, 6 ) == 'https:' ) {
1755 global $wgStylePath, $wgStyleVersion;
1756 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
1760 'rel' => 'stylesheet',
1762 'type' => 'text/css' );
1764 $attribs['media'] = $media;
1767 $link = Xml
::element( 'link', $attribs );
1769 if( isset( $options['condition'] ) ) {
1770 $condition = htmlspecialchars( $options['condition'] );
1771 $link = "<!--[if $condition]>$link<![endif]-->";
1776 function transformCssMedia( $media ) {
1777 global $wgRequest, $wgHandheldForIPhone;
1779 // Switch in on-screen display for media testing
1781 'printable' => 'print',
1782 'handheld' => 'handheld',
1784 foreach( $switches as $switch => $targetMedia ) {
1785 if( $wgRequest->getBool( $switch ) ) {
1786 if( $media == $targetMedia ) {
1788 } elseif( $media == 'screen' ) {
1794 // Expand longer media queries as iPhone doesn't grok 'handheld'
1795 if( $wgHandheldForIPhone ) {
1796 $mediaAliases = array(
1797 'screen' => 'screen and (min-device-width: 481px)',
1798 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
1801 if( isset( $mediaAliases[$media] ) ) {
1802 $media = $mediaAliases[$media];
1810 * Turn off regular page output and return an error reponse
1811 * for when rate limiting has triggered.
1813 public function rateLimited() {
1815 $this->setPageTitle(wfMsg('actionthrottled'));
1816 $this->setRobotPolicy( 'noindex,follow' );
1817 $this->setArticleRelated( false );
1818 $this->enableClientCache( false );
1819 $this->mRedirect
= '';
1821 $this->setStatusCode(503);
1822 $this->addWikiMsg( 'actionthrottledtext' );
1824 $this->returnToMain( null, $this->getTitle() );
1828 * Show an "add new section" link?
1832 public function showNewSectionLink() {
1833 return $this->mNewSectionLink
;
1837 * Forcibly hide the new section link?
1841 public function forceHideNewSectionLink() {
1842 return $this->mHideNewSectionLink
;
1846 * Show a warning about slave lag
1848 * If the lag is higher than $wgSlaveLagCritical seconds,
1849 * then the warning is a bit more obvious. If the lag is
1850 * lower than $wgSlaveLagWarning, then no warning is shown.
1852 * @param int $lag Slave lag
1854 public function showLagWarning( $lag ) {
1855 global $wgSlaveLagWarning, $wgSlaveLagCritical;
1856 if( $lag >= $wgSlaveLagWarning ) {
1857 $message = $lag < $wgSlaveLagCritical
1860 $warning = wfMsgExt( $message, 'parse', $lag );
1861 $this->addHTML( "<div class=\"mw-{$message}\">\n{$warning}\n</div>\n" );
1866 * Add a wikitext-formatted message to the output.
1867 * This is equivalent to:
1869 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
1871 public function addWikiMsg( /*...*/ ) {
1872 $args = func_get_args();
1873 $name = array_shift( $args );
1874 $this->addWikiMsgArray( $name, $args );
1878 * Add a wikitext-formatted message to the output.
1879 * Like addWikiMsg() except the parameters are taken as an array
1880 * instead of a variable argument list.
1882 * $options is passed through to wfMsgExt(), see that function for details.
1884 public function addWikiMsgArray( $name, $args, $options = array() ) {
1885 $options[] = 'parse';
1886 $text = wfMsgExt( $name, $options, $args );
1887 $this->addHTML( $text );
1891 * This function takes a number of message/argument specifications, wraps them in
1892 * some overall structure, and then parses the result and adds it to the output.
1894 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
1895 * on. The subsequent arguments may either be strings, in which case they are the
1896 * message names, or arrays, in which case the first element is the message name,
1897 * and subsequent elements are the parameters to that message.
1899 * The special named parameter 'options' in a message specification array is passed
1900 * through to the $options parameter of wfMsgExt().
1902 * Don't use this for messages that are not in users interface language.
1906 * $wgOut->wrapWikiMsg( '<div class="error">$1</div>', 'some-error' );
1910 * $wgOut->addWikiText( '<div class="error">' . wfMsgNoTrans( 'some-error' ) . '</div>' );
1912 public function wrapWikiMsg( $wrap /*, ...*/ ) {
1913 $msgSpecs = func_get_args();
1914 array_shift( $msgSpecs );
1915 $msgSpecs = array_values( $msgSpecs );
1917 foreach ( $msgSpecs as $n => $spec ) {
1919 if ( is_array( $spec ) ) {
1921 $name = array_shift( $args );
1922 if ( isset( $args['options'] ) ) {
1923 $options = $args['options'];
1924 unset( $args['options'] );
1930 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
1932 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );