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 . "\n"; }
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
.= "\t\t<script type=\"$wgJsMimeType\">/*<![CDATA[*/\n\t\t$script\n\t\t/*]]>*/</script>\n";
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 * Now a wrapper around Article::tryParserCache()
720 * @return bool True if successful, else false.
722 public function tryParserCache( &$article ) {
723 $parserOutput = $article->tryParserCache( $this->parserOptions() );
725 if ($parserOutput !== false) {
726 $this->addParserOutput( $parserOutput );
734 * @param int $maxage Maximum cache time on the Squid, in seconds.
736 public function setSquidMaxage( $maxage ) {
737 $this->mSquidMaxage
= $maxage;
741 * Use enableClientCache(false) to force it to send nocache headers
744 public function enableClientCache( $state ) {
745 return wfSetVar( $this->mEnableClientCache
, $state );
748 function getCacheVaryCookies() {
749 global $wgCookiePrefix, $wgCacheVaryCookies;
751 if ( $cookies === null ) {
752 $cookies = array_merge(
754 "{$wgCookiePrefix}Token",
755 "{$wgCookiePrefix}LoggedOut",
760 wfRunHooks('GetCacheVaryCookies', array( $this, &$cookies ) );
765 function uncacheableBecauseRequestVars() {
767 return $wgRequest->getText('useskin', false) === false
768 && $wgRequest->getText('uselang', false) === false;
772 * Check if the request has a cache-varying cookie header
773 * If it does, it's very important that we don't allow public caching
775 function haveCacheVaryCookies() {
777 $cookieHeader = $wgRequest->getHeader( 'cookie' );
778 if ( $cookieHeader === false ) {
781 $cvCookies = $this->getCacheVaryCookies();
782 foreach ( $cvCookies as $cookieName ) {
783 # Check for a simple string match, like the way squid does it
784 if ( strpos( $cookieHeader, $cookieName ) ) {
785 wfDebug( __METHOD__
.": found $cookieName\n" );
789 wfDebug( __METHOD__
.": no cache-varying cookies found\n" );
793 /** Get a complete X-Vary-Options header */
794 public function getXVO() {
795 $cvCookies = $this->getCacheVaryCookies();
796 $xvo = 'X-Vary-Options: Accept-Encoding;list-contains=gzip,Cookie;';
798 foreach ( $cvCookies as $cookieName ) {
804 $xvo .= 'string-contains=' . $cookieName;
809 public function sendCacheControl() {
810 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest;
812 $response = $wgRequest->response();
813 if ($wgUseETag && $this->mETag
)
814 $response->header("ETag: $this->mETag");
816 # don't serve compressed data to clients who can't handle it
817 # maintain different caches for logged-in users and non-logged in ones
818 $response->header( 'Vary: Accept-Encoding, Cookie' );
820 # Add an X-Vary-Options header for Squid with Wikimedia patches
821 $response->header( $this->getXVO() );
823 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
824 if( $wgUseSquid && session_id() == '' &&
825 ! $this->isPrintable() && $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies() )
828 # We'll purge the proxy cache explicitly, but require end user agents
829 # to revalidate against the proxy on each visit.
830 # Surrogate-Control controls our Squid, Cache-Control downstream caches
831 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
832 # start with a shorter timeout for initial testing
833 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
834 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
835 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
837 # We'll purge the proxy cache for anons explicitly, but require end user agents
838 # to revalidate against the proxy on each visit.
839 # IMPORTANT! The Squid needs to replace the Cache-Control header with
840 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
841 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
842 # start with a shorter timeout for initial testing
843 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
844 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
847 # We do want clients to cache if they can, but they *must* check for updates
848 # on revisiting the page.
849 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
850 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
851 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
853 if($this->mLastModified
) {
854 $response->header( "Last-Modified: {$this->mLastModified}" );
857 wfDebug( __METHOD__
. ": no caching **\n", false );
859 # In general, the absence of a last modified header should be enough to prevent
860 # the client from using its cache. We send a few other things just to make sure.
861 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
862 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
863 $response->header( 'Pragma: no-cache' );
868 * Finally, all the text has been munged and accumulated into
869 * the object, let's actually output it:
871 public function output() {
872 global $wgUser, $wgOutputEncoding, $wgRequest;
873 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
874 global $wgJsMimeType, $wgUseAjax, $wgAjaxWatch;
875 global $wgEnableMWSuggest, $wgUniversalEditButton;
878 if( $this->mDoNothing
){
882 wfProfileIn( __METHOD__
);
884 if ( '' != $this->mRedirect
) {
885 # Standards require redirect URLs to be absolute
886 $this->mRedirect
= wfExpandUrl( $this->mRedirect
);
887 if( $this->mRedirectCode
== '301') {
888 if( !$wgDebugRedirects ) {
889 $wgRequest->response()->header("HTTP/1.1 {$this->mRedirectCode} Moved Permanently");
891 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
894 $this->sendCacheControl();
896 $wgRequest->response()->header("Content-Type: text/html; charset=utf-8");
897 if( $wgDebugRedirects ) {
898 $url = htmlspecialchars( $this->mRedirect
);
899 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
900 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
901 print "</body>\n</html>\n";
903 $wgRequest->response()->header( 'Location: '.$this->mRedirect
);
905 wfProfileOut( __METHOD__
);
908 elseif ( $this->mStatusCode
)
910 $statusMessage = array(
912 101 => 'Switching Protocols',
917 203 => 'Non-Authoritative Information',
919 205 => 'Reset Content',
920 206 => 'Partial Content',
921 207 => 'Multi-Status',
922 300 => 'Multiple Choices',
923 301 => 'Moved Permanently',
926 304 => 'Not Modified',
928 307 => 'Temporary Redirect',
929 400 => 'Bad Request',
930 401 => 'Unauthorized',
931 402 => 'Payment Required',
934 405 => 'Method Not Allowed',
935 406 => 'Not Acceptable',
936 407 => 'Proxy Authentication Required',
937 408 => 'Request Timeout',
940 411 => 'Length Required',
941 412 => 'Precondition Failed',
942 413 => 'Request Entity Too Large',
943 414 => 'Request-URI Too Large',
944 415 => 'Unsupported Media Type',
945 416 => 'Request Range Not Satisfiable',
946 417 => 'Expectation Failed',
947 422 => 'Unprocessable Entity',
949 424 => 'Failed Dependency',
950 500 => 'Internal Server Error',
951 501 => 'Not Implemented',
952 502 => 'Bad Gateway',
953 503 => 'Service Unavailable',
954 504 => 'Gateway Timeout',
955 505 => 'HTTP Version Not Supported',
956 507 => 'Insufficient Storage'
959 if ( $statusMessage[$this->mStatusCode
] )
960 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $statusMessage[$this->mStatusCode
] );
963 $sk = $wgUser->getSkin();
966 $this->addScriptFile( 'ajax.js' );
968 wfRunHooks( 'AjaxAddScript', array( &$this ) );
970 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
971 $this->addScriptFile( 'ajaxwatch.js' );
974 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ){
975 $this->addScriptFile( 'mwsuggest.js' );
979 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
980 $this->addScriptFile( 'rightclickedit.js' );
983 if( $wgUniversalEditButton ) {
984 if( isset( $wgArticle ) && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
985 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create' ) ) ) {
986 // Original UniversalEditButton
987 $this->addLink( array(
988 'rel' => 'alternate',
989 'type' => 'application/x-wiki',
990 'title' => wfMsg( 'edit' ),
991 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
993 // Alternate edit link
994 $this->addLink( array(
996 'title' => wfMsg( 'edit' ),
997 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1002 # Buffer output; final headers may depend on later processing
1005 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1006 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
1008 if ($this->mArticleBodyOnly
) {
1009 $this->out($this->mBodytext
);
1011 // Hook that allows last minute changes to the output page, e.g.
1012 // adding of CSS or Javascript by extensions.
1013 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1015 wfProfileIn( 'Output-skin' );
1016 $sk->outputPage( $this );
1017 wfProfileOut( 'Output-skin' );
1020 $this->sendCacheControl();
1022 wfProfileOut( __METHOD__
);
1026 * Actually output something with print(). Performs an iconv to the
1027 * output encoding, if needed.
1028 * @param string $ins The string to output
1030 public function out( $ins ) {
1031 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1032 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1035 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1036 if ( false === $outs ) { $outs = $ins; }
1044 public static function setEncodings() {
1045 global $wgInputEncoding, $wgOutputEncoding;
1048 $wgInputEncoding = strtolower( $wgInputEncoding );
1050 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
1051 $wgOutputEncoding = strtolower( $wgOutputEncoding );
1054 $wgOutputEncoding = $wgInputEncoding;
1058 * Deprecated, use wfReportTime() instead.
1062 public function reportTime() {
1063 wfDeprecated( __METHOD__
);
1064 $time = wfReportTime();
1069 * Produce a "user is blocked" page.
1071 * @param bool $return Whether to have a "return to $wgTitle" message or not.
1074 function blockedPage( $return = true ) {
1075 global $wgUser, $wgContLang, $wgLang;
1077 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1078 $this->setRobotPolicy( 'noindex,nofollow' );
1079 $this->setArticleRelated( false );
1081 $name = User
::whoIs( $wgUser->blockedBy() );
1082 $reason = $wgUser->blockedFor();
1083 if( $reason == '' ) {
1084 $reason = wfMsg( 'blockednoreason' );
1086 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $wgUser->mBlock
->mTimestamp
), true );
1089 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1091 $blockid = $wgUser->mBlock
->mId
;
1093 $blockExpiry = $wgUser->mBlock
->mExpiry
;
1094 if ( $blockExpiry == 'infinity' ) {
1095 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1096 // Search for localization in 'ipboptions'
1097 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1098 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1099 if ( strpos( $option, ":" ) === false )
1101 list( $show, $value ) = explode( ":", $option );
1102 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1103 $blockExpiry = $show;
1108 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1111 if ( $wgUser->mBlock
->mAuto
) {
1112 $msg = 'autoblockedtext';
1114 $msg = 'blockedtext';
1117 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1118 * This could be a username, an ip range, or a single ip. */
1119 $intended = $wgUser->mBlock
->mAddress
;
1121 $this->addWikiMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
1123 # Don't auto-return to special pages
1125 $return = $this->getTitle()->getNamespace() > -1 ?
$this->getTitle() : null;
1126 $this->returnToMain( null, $return );
1131 * Output a standard error page
1133 * @param string $title Message key for page title
1134 * @param string $msg Message key for page text
1135 * @param array $params Message parameters
1137 public function showErrorPage( $title, $msg, $params = array() ) {
1138 if ( $this->getTitle() ) {
1139 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1141 $this->setPageTitle( wfMsg( $title ) );
1142 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1143 $this->setRobotPolicy( 'noindex,nofollow' );
1144 $this->setArticleRelated( false );
1145 $this->enableClientCache( false );
1146 $this->mRedirect
= '';
1147 $this->mBodytext
= '';
1149 array_unshift( $params, 'parse' );
1150 array_unshift( $params, $msg );
1151 $this->addHTML( call_user_func_array( 'wfMsgExt', $params ) );
1153 $this->returnToMain();
1157 * Output a standard permission error page
1159 * @param array $errors Error message keys
1161 public function showPermissionsErrorPage( $errors, $action = null )
1163 $this->mDebugtext
.= 'Original title: ' .
1164 $this->getTitle()->getPrefixedText() . "\n";
1165 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1166 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1167 $this->setRobotPolicy( 'noindex,nofollow' );
1168 $this->setArticleRelated( false );
1169 $this->enableClientCache( false );
1170 $this->mRedirect
= '';
1171 $this->mBodytext
= '';
1172 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1176 public function errorpage( $title, $msg ) {
1177 wfDeprecated( __METHOD__
);
1178 throw new ErrorPageError( $title, $msg );
1182 * Display an error page indicating that a given version of MediaWiki is
1183 * required to use it
1185 * @param mixed $version The version of MediaWiki needed to use the page
1187 public function versionRequired( $version ) {
1188 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1189 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1190 $this->setRobotPolicy( 'noindex,nofollow' );
1191 $this->setArticleRelated( false );
1192 $this->mBodytext
= '';
1194 $this->addWikiMsg( 'versionrequiredtext', $version );
1195 $this->returnToMain();
1199 * Display an error page noting that a given permission bit is required.
1201 * @param string $permission key required
1203 public function permissionRequired( $permission ) {
1206 $this->setPageTitle( wfMsg( 'badaccess' ) );
1207 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1208 $this->setRobotPolicy( 'noindex,nofollow' );
1209 $this->setArticleRelated( false );
1210 $this->mBodytext
= '';
1212 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1213 User
::getGroupsWithPermission( $permission ) );
1215 $this->addWikiMsg( 'badaccess-groups',
1216 $wgLang->commaList( $groups ),
1219 $this->addWikiMsg( 'badaccess-group0' );
1221 $this->returnToMain();
1225 * Use permissionRequired.
1228 public function sysopRequired() {
1229 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
1233 * Use permissionRequired.
1236 public function developerRequired() {
1237 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
1241 * Produce the stock "please login to use the wiki" page
1243 public function loginToUse() {
1244 global $wgUser, $wgContLang;
1246 if( $wgUser->isLoggedIn() ) {
1247 $this->permissionRequired( 'read' );
1251 $skin = $wgUser->getSkin();
1253 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1254 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1255 $this->setRobotPolicy( 'noindex,nofollow' );
1256 $this->setArticleFlag( false );
1258 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1259 $loginLink = $skin->link(
1261 wfMsgHtml( 'loginreqlink' ),
1263 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
1264 array( 'known', 'noclasses' )
1266 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1267 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . "-->" );
1269 # Don't return to the main page if the user can't read it
1270 # otherwise we'll end up in a pointless loop
1271 $mainPage = Title
::newMainPage();
1272 if( $mainPage->userCanRead() )
1273 $this->returnToMain( null, $mainPage );
1277 public function databaseError( $fname, $sql, $error, $errno ) {
1278 throw new MWException( "OutputPage::databaseError is obsolete\n" );
1282 * @param array $errors An array of arrays returned by Title::getUserPermissionsErrors
1283 * @return string The wikitext error-messages, formatted into a list.
1285 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1286 if ($action == null) {
1287 $text = wfMsgNoTrans( 'permissionserrorstext', count($errors)). "\n\n";
1290 $action_desc = wfMsgNoTrans( "action-$action" );
1291 $text = wfMsgNoTrans( 'permissionserrorstext-withaction', count($errors), $action_desc ) . "\n\n";
1294 if (count( $errors ) > 1) {
1295 $text .= '<ul class="permissions-errors">' . "\n";
1297 foreach( $errors as $error )
1300 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1305 $text .= "<div class=\"permissions-errors\">\n" . call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) . "\n</div>";
1312 * Display a page stating that the Wiki is in read-only mode,
1313 * and optionally show the source of the page that the user
1314 * was trying to edit. Should only be called (for this
1315 * purpose) after wfReadOnly() has returned true.
1317 * For historical reasons, this function is _also_ used to
1318 * show the error message when a user tries to edit a page
1319 * they are not allowed to edit. (Unless it's because they're
1320 * blocked, then we show blockedPage() instead.) In this
1321 * case, the second parameter should be set to true and a list
1322 * of reasons supplied as the third parameter.
1324 * @todo Needs to be split into multiple functions.
1326 * @param string $source Source code to show (or null).
1327 * @param bool $protected Is this a permissions error?
1328 * @param array $reasons List of reasons for this error, as returned by Title::getUserPermissionsErrors().
1330 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1332 $skin = $wgUser->getSkin();
1334 $this->setRobotPolicy( 'noindex,nofollow' );
1335 $this->setArticleRelated( false );
1337 // If no reason is given, just supply a default "I can't let you do
1338 // that, Dave" message. Should only occur if called by legacy code.
1339 if ( $protected && empty($reasons) ) {
1340 $reasons[] = array( 'badaccess-group0' );
1343 if ( !empty($reasons) ) {
1344 // Permissions error
1346 $this->setPageTitle( wfMsg( 'viewsource' ) );
1355 array( 'known', 'noclasses' )
1360 $this->setPageTitle( wfMsg( 'badaccess' ) );
1362 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1364 // Wiki is read only
1365 $this->setPageTitle( wfMsg( 'readonly' ) );
1366 $reason = wfReadOnlyReason();
1367 $this->wrapWikiMsg( '<div class="mw-readonly-error">$1</div>', array( 'readonlytext', $reason ) );
1370 // Show source, if supplied
1371 if( is_string( $source ) ) {
1372 $this->addWikiMsg( 'viewsourcetext' );
1373 $text = Xml
::openElement( 'textarea',
1374 array( 'id' => 'wpTextbox1',
1375 'name' => 'wpTextbox1',
1376 'cols' => $wgUser->getOption( 'cols' ),
1377 'rows' => $wgUser->getOption( 'rows' ),
1378 'readonly' => 'readonly' ) );
1379 $text .= htmlspecialchars( $source );
1380 $text .= Xml
::closeElement( 'textarea' );
1381 $this->addHTML( $text );
1383 // Show templates used by this article
1384 $skin = $wgUser->getSkin();
1385 $article = new Article( $this->getTitle() );
1386 $this->addHTML( "<div class='templatesUsed'>
1387 {$skin->formatTemplates( $article->getUsedTemplates() )}
1392 # If the title doesn't exist, it's fairly pointless to print a return
1393 # link to it. After all, you just tried editing it and couldn't, so
1394 # what's there to do there?
1395 if( $this->getTitle()->exists() ) {
1396 $this->returnToMain( null, $this->getTitle() );
1401 public function fatalError( $message ) {
1402 wfDeprecated( __METHOD__
);
1403 throw new FatalError( $message );
1407 public function unexpectedValueError( $name, $val ) {
1408 wfDeprecated( __METHOD__
);
1409 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1413 public function fileCopyError( $old, $new ) {
1414 wfDeprecated( __METHOD__
);
1415 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1419 public function fileRenameError( $old, $new ) {
1420 wfDeprecated( __METHOD__
);
1421 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1425 public function fileDeleteError( $name ) {
1426 wfDeprecated( __METHOD__
);
1427 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1431 public function fileNotFoundError( $name ) {
1432 wfDeprecated( __METHOD__
);
1433 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1436 public function showFatalError( $message ) {
1437 $this->setPageTitle( wfMsg( "internalerror" ) );
1438 $this->setRobotPolicy( "noindex,nofollow" );
1439 $this->setArticleRelated( false );
1440 $this->enableClientCache( false );
1441 $this->mRedirect
= '';
1442 $this->mBodytext
= $message;
1445 public function showUnexpectedValueError( $name, $val ) {
1446 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
1449 public function showFileCopyError( $old, $new ) {
1450 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
1453 public function showFileRenameError( $old, $new ) {
1454 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
1457 public function showFileDeleteError( $name ) {
1458 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
1461 public function showFileNotFoundError( $name ) {
1462 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1466 * Add a "return to" link pointing to a specified title
1468 * @param Title $title Title to link
1470 public function addReturnTo( $title ) {
1472 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullUrl() ) );
1473 $link = wfMsgHtml( 'returnto', $wgUser->getSkin()->link( $title ) );
1474 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
1478 * Add a "return to" link pointing to a specified title,
1479 * or the title indicated in the request, or else the main page
1481 * @param null $unused No longer used
1482 * @param Title $returnto Title to return to
1484 public function returnToMain( $unused = null, $returnto = NULL ) {
1487 if ( $returnto == NULL ) {
1488 $returnto = $wgRequest->getText( 'returnto' );
1491 if ( '' === $returnto ) {
1492 $returnto = Title
::newMainPage();
1495 if ( is_object( $returnto ) ) {
1496 $titleObj = $returnto;
1498 $titleObj = Title
::newFromText( $returnto );
1500 if ( !is_object( $titleObj ) ) {
1501 $titleObj = Title
::newMainPage();
1504 $this->addReturnTo( $titleObj );
1508 * This function takes the title (first item of mGoodLinks), categories,
1509 * existing and broken links for the page
1510 * and uses the first 10 of them for META keywords
1512 * @param ParserOutput &$parserOutput
1514 private function addKeywords( &$parserOutput ) {
1516 // Get an array of keywords if there are more than one
1517 // variant of the site language
1518 $text = $wgContLang->autoConvertToAllVariants( $this->getTitle()->getPrefixedText());
1519 // array_values: We needn't to merge variant's code name
1520 // into $this->mKeywords;
1521 // array_unique: We should insert a keyword just for once
1522 if( is_array( $text ))
1523 $text = array_unique( array_values( $text ));
1524 $this->addKeyword( $text );
1526 $links2d =& $parserOutput->getLinks();
1527 if ( !is_array( $links2d ) ) {
1530 foreach ( $links2d as $dbkeys ) {
1531 foreach( $dbkeys as $dbkey => $unused ) {
1532 $dbkey = $wgContLang->autoConvertToAllVariants( $dbkey );
1533 if( is_array( $dbkey ))
1534 $dbkey = array_unique( array_values( $dbkey ));
1535 $this->addKeyword( $dbkey );
1536 if ( ++
$count > 10 ) {
1544 * @return string The doctype, opening <html>, and head element.
1546 public function headElement( Skin
$sk ) {
1547 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1548 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces;
1549 global $wgContLang, $wgUseTrackbacks, $wgStyleVersion;
1551 $this->addMeta( "http:Content-type", "$wgMimeType; charset={$wgOutputEncoding}" );
1552 $this->addStyle( 'common/wikiprintable.css', 'print' );
1553 $sk->setupUserCss( $this );
1557 if( $wgMimeType == 'text/xml' ||
$wgMimeType == 'application/xhtml+xml' ||
$wgMimeType == 'application/xml' ) {
1558 $ret .= "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?" . ">\n";
1561 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\"\n \"$wgDTD\">\n";
1563 if ( '' == $this->getHTMLTitle() ) {
1564 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1567 $rtl = $wgContLang->isRTL() ?
" dir='RTL'" : '';
1568 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1569 foreach($wgXhtmlNamespaces as $tag => $ns) {
1570 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1572 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" $rtl>\n";
1573 $ret .= "<head>\n<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n\t\t";
1574 $ret .= implode( "\t\t", array(
1575 $this->getHeadLinks(),
1576 $this->buildCssLinks(),
1577 $sk->getHeadScripts( $this->mAllowUserJs
),
1579 $this->getHeadItems(),
1582 $ret .= "<style type='text/css'>{$sk->usercss}</style>";
1585 if ($wgUseTrackbacks && $this->isArticleRelated())
1586 $ret .= $this->getTitle()->trackbackRDF();
1588 $ret .= "</head>\n";
1592 protected function addDefaultMeta() {
1594 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); //bug 15835
1595 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
1597 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
1598 if( $p !== 'index,follow' ) {
1599 // http://www.robotstxt.org/wc/meta-user.html
1600 // Only show if it's different from the default robots policy
1601 $this->addMeta( 'robots', $p );
1604 if ( count( $this->mKeywords
) > 0 ) {
1606 "/<.*?" . ">/" => '',
1609 $this->addMeta( 'keywords', preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords
) ) );
1614 * @return string HTML tag links to be put in the header.
1616 public function getHeadLinks() {
1617 global $wgRequest, $wgFeed;
1619 // Ideally this should happen earlier, somewhere. :P
1620 $this->addDefaultMeta();
1624 foreach ( $this->mMetatags
as $tag ) {
1625 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
1627 $tag[0] = substr( $tag[0], 5 );
1631 $tags[] = Xml
::element( 'meta',
1634 'content' => $tag[1] ) );
1636 foreach ( $this->mLinktags
as $tag ) {
1637 $tags[] = Xml
::element( 'link', $tag );
1641 foreach( $this->getSyndicationLinks() as $format => $link ) {
1642 # Use the page name for the title (accessed through $wgTitle since
1643 # there's no other way). In principle, this could lead to issues
1644 # with having the same name for different feeds corresponding to
1645 # the same page, but we can't avoid that at this low a level.
1647 $tags[] = $this->feedLink(
1650 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() ) ); # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
1653 # Recent changes feed should appear on every page (except recentchanges,
1654 # that would be redundant). Put it after the per-page feed to avoid
1655 # changing existing behavior. It's still available, probably via a
1656 # menu in your browser. Some sites might have a different feed they'd
1657 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
1658 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
1659 # If so, use it instead.
1661 global $wgOverrideSiteFeed, $wgSitename, $wgFeedClasses;
1662 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
1664 if ( $wgOverrideSiteFeed ) {
1665 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
1666 $tags[] = $this->feedLink (
1668 htmlspecialchars( $feedUrl ),
1669 wfMsg( "site-{$type}-feed", $wgSitename ) );
1672 else if ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
1673 foreach( $wgFeedClasses as $format => $class ) {
1674 $tags[] = $this->feedLink(
1676 $rctitle->getLocalURL( "feed={$format}" ),
1677 wfMsg( "site-{$format}-feed", $wgSitename ) ); # For grep: 'site-rss-feed', 'site-atom-feed'.
1682 return implode( "\n\t\t", $tags ) . "\n";
1686 * Return URLs for each supported syndication format for this page.
1687 * @return array associating format keys with URLs
1689 public function getSyndicationLinks() {
1690 global $wgFeedClasses;
1693 if( $this->isSyndicated() ) {
1694 if( is_string( $this->getFeedAppendQuery() ) ) {
1695 $appendQuery = "&" . $this->getFeedAppendQuery();
1700 foreach( $wgFeedClasses as $format => $class ) {
1701 $links[$format] = $this->getTitle()->getLocalUrl( "feed=$format{$appendQuery}" );
1708 * Generate a <link rel/> for an RSS feed.
1710 private function feedLink( $type, $url, $text ) {
1711 return Xml
::element( 'link', array(
1712 'rel' => 'alternate',
1713 'type' => "application/$type+xml",
1719 * Add a local or specified stylesheet, with the given media options.
1720 * Meant primarily for internal use...
1722 * @param $media -- to specify a media type, 'screen', 'printable', 'handheld' or any.
1723 * @param $conditional -- for IE conditional comments, specifying an IE version
1724 * @param $dir -- set to 'rtl' or 'ltr' for direction-specific sheets
1726 public function addStyle( $style, $media='', $condition='', $dir='' ) {
1729 $options['media'] = $media;
1731 $options['condition'] = $condition;
1733 $options['dir'] = $dir;
1734 $this->styles
[$style] = $options;
1738 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
1739 * These will be applied to various media & IE conditionals.
1741 public function buildCssLinks() {
1743 foreach( $this->styles
as $file => $options ) {
1744 $link = $this->styleLink( $file, $options );
1749 return implode( "\n\t\t", $links );
1752 protected function styleLink( $style, $options ) {
1755 if( isset( $options['dir'] ) ) {
1757 $siteDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
1758 if( $siteDir != $options['dir'] )
1762 if( isset( $options['media'] ) ) {
1763 $media = $this->transformCssMedia( $options['media'] );
1764 if( is_null( $media ) ) {
1771 if( substr( $style, 0, 1 ) == '/' ||
1772 substr( $style, 0, 5 ) == 'http:' ||
1773 substr( $style, 0, 6 ) == 'https:' ) {
1776 global $wgStylePath, $wgStyleVersion;
1777 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
1781 'rel' => 'stylesheet',
1783 'type' => 'text/css' );
1785 $attribs['media'] = $media;
1788 $link = Xml
::element( 'link', $attribs );
1790 if( isset( $options['condition'] ) ) {
1791 $condition = htmlspecialchars( $options['condition'] );
1792 $link = "<!--[if $condition]>$link<![endif]-->";
1797 function transformCssMedia( $media ) {
1798 global $wgRequest, $wgHandheldForIPhone;
1800 // Switch in on-screen display for media testing
1802 'printable' => 'print',
1803 'handheld' => 'handheld',
1805 foreach( $switches as $switch => $targetMedia ) {
1806 if( $wgRequest->getBool( $switch ) ) {
1807 if( $media == $targetMedia ) {
1809 } elseif( $media == 'screen' ) {
1815 // Expand longer media queries as iPhone doesn't grok 'handheld'
1816 if( $wgHandheldForIPhone ) {
1817 $mediaAliases = array(
1818 'screen' => 'screen and (min-device-width: 481px)',
1819 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
1822 if( isset( $mediaAliases[$media] ) ) {
1823 $media = $mediaAliases[$media];
1831 * Turn off regular page output and return an error reponse
1832 * for when rate limiting has triggered.
1834 public function rateLimited() {
1836 $this->setPageTitle(wfMsg('actionthrottled'));
1837 $this->setRobotPolicy( 'noindex,follow' );
1838 $this->setArticleRelated( false );
1839 $this->enableClientCache( false );
1840 $this->mRedirect
= '';
1842 $this->setStatusCode(503);
1843 $this->addWikiMsg( 'actionthrottledtext' );
1845 $this->returnToMain( null, $this->getTitle() );
1849 * Show an "add new section" link?
1853 public function showNewSectionLink() {
1854 return $this->mNewSectionLink
;
1858 * Forcibly hide the new section link?
1862 public function forceHideNewSectionLink() {
1863 return $this->mHideNewSectionLink
;
1867 * Show a warning about slave lag
1869 * If the lag is higher than $wgSlaveLagCritical seconds,
1870 * then the warning is a bit more obvious. If the lag is
1871 * lower than $wgSlaveLagWarning, then no warning is shown.
1873 * @param int $lag Slave lag
1875 public function showLagWarning( $lag ) {
1876 global $wgSlaveLagWarning, $wgSlaveLagCritical;
1877 if( $lag >= $wgSlaveLagWarning ) {
1878 $message = $lag < $wgSlaveLagCritical
1881 $warning = wfMsgExt( $message, 'parse', $lag );
1882 $this->addHTML( "<div class=\"mw-{$message}\">\n{$warning}\n</div>\n" );
1887 * Add a wikitext-formatted message to the output.
1888 * This is equivalent to:
1890 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
1892 public function addWikiMsg( /*...*/ ) {
1893 $args = func_get_args();
1894 $name = array_shift( $args );
1895 $this->addWikiMsgArray( $name, $args );
1899 * Add a wikitext-formatted message to the output.
1900 * Like addWikiMsg() except the parameters are taken as an array
1901 * instead of a variable argument list.
1903 * $options is passed through to wfMsgExt(), see that function for details.
1905 public function addWikiMsgArray( $name, $args, $options = array() ) {
1906 $options[] = 'parse';
1907 $text = wfMsgExt( $name, $options, $args );
1908 $this->addHTML( $text );
1912 * This function takes a number of message/argument specifications, wraps them in
1913 * some overall structure, and then parses the result and adds it to the output.
1915 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
1916 * on. The subsequent arguments may either be strings, in which case they are the
1917 * message names, or arrays, in which case the first element is the message name,
1918 * and subsequent elements are the parameters to that message.
1920 * The special named parameter 'options' in a message specification array is passed
1921 * through to the $options parameter of wfMsgExt().
1923 * Don't use this for messages that are not in users interface language.
1927 * $wgOut->wrapWikiMsg( '<div class="error">$1</div>', 'some-error' );
1931 * $wgOut->addWikiText( '<div class="error">' . wfMsgNoTrans( 'some-error' ) . '</div>' );
1933 public function wrapWikiMsg( $wrap /*, ...*/ ) {
1934 $msgSpecs = func_get_args();
1935 array_shift( $msgSpecs );
1936 $msgSpecs = array_values( $msgSpecs );
1938 foreach ( $msgSpecs as $n => $spec ) {
1940 if ( is_array( $spec ) ) {
1942 $name = array_shift( $args );
1943 if ( isset( $args['options'] ) ) {
1944 $options = $args['options'];
1945 unset( $args['options'] );
1951 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
1953 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );