(bug 14687) OutputPage::addStyle() now adds type="text/css" like it should.
[lhc/web/wiklou.git] / includes / OutputPage.php
1 <?php
2 if ( ! defined( 'MEDIAWIKI' ) )
3 die( 1 );
4
5 /**
6 * @todo document
7 */
8 class OutputPage {
9 var $mMetatags, $mKeywords;
10 var $mLinktags, $mPagetitle, $mBodytext, $mDebugtext;
11 var $mHTMLtitle, $mRobotpolicy, $mIsarticle, $mPrintable;
12 var $mSubtitle, $mRedirect, $mStatusCode;
13 var $mLastModified, $mETag, $mCategoryLinks;
14 var $mScripts, $mLinkColours, $mPageLinkTitle;
15
16 var $mAllowUserJs;
17 var $mSuppressQuickbar;
18 var $mOnloadHandler;
19 var $mDoNothing;
20 var $mContainsOldMagic, $mContainsNewMagic;
21 var $mIsArticleRelated;
22 protected $mParserOptions; // lazy initialised, use parserOptions()
23 var $mShowFeedLinks = false;
24 var $mFeedLinksAppendQuery = false;
25 var $mEnableClientCache = true;
26 var $mArticleBodyOnly = false;
27
28 var $mNewSectionLink = false;
29 var $mNoGallery = false;
30 var $mPageTitleActionText = '';
31 var $mParseWarnings = array();
32
33 /**
34 * Constructor
35 * Initialise private variables
36 */
37 function __construct() {
38 global $wgAllowUserJs;
39 $this->mAllowUserJs = $wgAllowUserJs;
40 $this->mMetatags = $this->mKeywords = $this->mLinktags = array();
41 $this->mHTMLtitle = $this->mPagetitle = $this->mBodytext =
42 $this->mRedirect = $this->mLastModified =
43 $this->mSubtitle = $this->mDebugtext = $this->mRobotpolicy =
44 $this->mOnloadHandler = $this->mPageLinkTitle = '';
45 $this->mIsArticleRelated = $this->mIsarticle = $this->mPrintable = true;
46 $this->mSuppressQuickbar = $this->mPrintable = false;
47 $this->mLanguageLinks = array();
48 $this->mCategoryLinks = array();
49 $this->mDoNothing = false;
50 $this->mContainsOldMagic = $this->mContainsNewMagic = 0;
51 $this->mParserOptions = null;
52 $this->mSquidMaxage = 0;
53 $this->mScripts = '';
54 $this->mHeadItems = array();
55 $this->mETag = false;
56 $this->mRevisionId = null;
57 $this->mNewSectionLink = false;
58 $this->mTemplateIds = array();
59 }
60
61 public function redirect( $url, $responsecode = '302' ) {
62 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
63 $this->mRedirect = str_replace( "\n", '', $url );
64 $this->mRedirectCode = $responsecode;
65 }
66
67 public function getRedirect() {
68 return $this->mRedirect;
69 }
70
71 /**
72 * Set the HTTP status code to send with the output.
73 *
74 * @param int $statusCode
75 * @return nothing
76 */
77 function setStatusCode( $statusCode ) { $this->mStatusCode = $statusCode; }
78
79 # To add an http-equiv meta tag, precede the name with "http:"
80 function addMeta( $name, $val ) { array_push( $this->mMetatags, array( $name, $val ) ); }
81 function addKeyword( $text ) { array_push( $this->mKeywords, $text ); }
82 function addScript( $script ) { $this->mScripts .= "\t\t".$script; }
83 function addStyle( $style ) {
84 global $wgStylePath, $wgStyleVersion;
85 $this->addLink(
86 array(
87 'rel' => 'stylesheet',
88 'href' => $wgStylePath . '/' . $style . '?' . $wgStyleVersion,
89 'type' => 'text/css' ) );
90 }
91
92 /**
93 * Add a JavaScript file out of skins/common, or a given relative path.
94 * @param string $file filename in skins/common or complete on-server path (/foo/bar.js)
95 */
96 function addScriptFile( $file ) {
97 global $wgStylePath, $wgStyleVersion, $wgJsMimeType;
98 if( substr( $file, 0, 1 ) == '/' ) {
99 $path = $file;
100 } else {
101 $path = "{$wgStylePath}/common/{$file}";
102 }
103 $encPath = htmlspecialchars( $path );
104 $this->addScript( "<script type=\"{$wgJsMimeType}\" src=\"$path?$wgStyleVersion\"></script>\n" );
105 }
106
107 /**
108 * Add a self-contained script tag with the given contents
109 * @param string $script JavaScript text, no <script> tags
110 */
111 function addInlineScript( $script ) {
112 global $wgJsMimeType;
113 $this->mScripts .= "<script type=\"$wgJsMimeType\">/*<![CDATA[*/\n$script\n/*]]>*/</script>";
114 }
115
116 function getScript() {
117 return $this->mScripts . $this->getHeadItems();
118 }
119
120 function getHeadItems() {
121 $s = '';
122 foreach ( $this->mHeadItems as $item ) {
123 $s .= $item;
124 }
125 return $s;
126 }
127
128 function addHeadItem( $name, $value ) {
129 $this->mHeadItems[$name] = $value;
130 }
131
132 function hasHeadItem( $name ) {
133 return isset( $this->mHeadItems[$name] );
134 }
135
136 function setETag($tag) { $this->mETag = $tag; }
137 function setArticleBodyOnly($only) { $this->mArticleBodyOnly = $only; }
138 function getArticleBodyOnly($only) { return $this->mArticleBodyOnly; }
139
140 function addLink( $linkarr ) {
141 # $linkarr should be an associative array of attributes. We'll escape on output.
142 array_push( $this->mLinktags, $linkarr );
143 }
144
145 function addMetadataLink( $linkarr ) {
146 # note: buggy CC software only reads first "meta" link
147 static $haveMeta = false;
148 $linkarr['rel'] = ($haveMeta) ? 'alternate meta' : 'meta';
149 $this->addLink( $linkarr );
150 $haveMeta = true;
151 }
152
153 /**
154 * checkLastModified tells the client to use the client-cached page if
155 * possible. If sucessful, the OutputPage is disabled so that
156 * any future call to OutputPage->output() have no effect.
157 *
158 * @return bool True iff cache-ok headers was sent.
159 */
160 function checkLastModified ( $timestamp ) {
161 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
162
163 if ( !$timestamp || $timestamp == '19700101000000' ) {
164 wfDebug( __METHOD__ . ": CACHE DISABLED, NO TIMESTAMP\n" );
165 return;
166 }
167 if( !$wgCachePages ) {
168 wfDebug( __METHOD__ . ": CACHE DISABLED\n", false );
169 return;
170 }
171 if( $wgUser->getOption( 'nocache' ) ) {
172 wfDebug( __METHOD__ . ": USER DISABLED CACHE\n", false );
173 return;
174 }
175
176 $timestamp=wfTimestamp(TS_MW,$timestamp);
177 $lastmod = wfTimestamp( TS_RFC2822, max( $timestamp, $wgUser->mTouched, $wgCacheEpoch ) );
178
179 if( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
180 # IE sends sizes after the date like this:
181 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
182 # this breaks strtotime().
183 $modsince = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
184
185 wfSuppressWarnings(); // E_STRICT system time bitching
186 $modsinceTime = strtotime( $modsince );
187 wfRestoreWarnings();
188
189 $ismodsince = wfTimestamp( TS_MW, $modsinceTime ? $modsinceTime : 1 );
190 wfDebug( __METHOD__ . ": -- client send If-Modified-Since: " . $modsince . "\n", false );
191 wfDebug( __METHOD__ . ": -- we might send Last-Modified : $lastmod\n", false );
192 if( ($ismodsince >= $timestamp ) && $wgUser->validateCache( $ismodsince ) && $ismodsince >= $wgCacheEpoch ) {
193 # Make sure you're in a place you can leave when you call us!
194 $wgRequest->response()->header( "HTTP/1.0 304 Not Modified" );
195 $this->mLastModified = $lastmod;
196 $this->sendCacheControl();
197 wfDebug( __METHOD__ . ": CACHED client: $ismodsince ; user: $wgUser->mTouched ; page: $timestamp ; site $wgCacheEpoch\n", false );
198 $this->disable();
199
200 // Don't output a compressed blob when using ob_gzhandler;
201 // it's technically against HTTP spec and seems to confuse
202 // Firefox when the response gets split over two packets.
203 wfClearOutputBuffers();
204
205 return true;
206 } else {
207 wfDebug( __METHOD__ . ": READY client: $ismodsince ; user: $wgUser->mTouched ; page: $timestamp ; site $wgCacheEpoch\n", false );
208 $this->mLastModified = $lastmod;
209 }
210 } else {
211 wfDebug( __METHOD__ . ": client did not send If-Modified-Since header\n", false );
212 $this->mLastModified = $lastmod;
213 }
214 }
215
216 function setPageTitleActionText( $text ) {
217 $this->mPageTitleActionText = $text;
218 }
219
220 function getPageTitleActionText () {
221 if ( isset( $this->mPageTitleActionText ) ) {
222 return $this->mPageTitleActionText;
223 }
224 }
225
226 public function setRobotpolicy( $str ) { $this->mRobotpolicy = $str; }
227 public function setHTMLTitle( $name ) {$this->mHTMLtitle = $name; }
228 public function setPageTitle( $name ) {
229 global $action, $wgContLang;
230 $name = $wgContLang->convert($name, true);
231 $this->mPagetitle = $name;
232 if(!empty($action)) {
233 $taction = $this->getPageTitleActionText();
234 if( !empty( $taction ) ) {
235 $name .= ' - '.$taction;
236 }
237 }
238
239 $this->setHTMLTitle( wfMsg( 'pagetitle', $name ) );
240 }
241 public function getHTMLTitle() { return $this->mHTMLtitle; }
242 public function getPageTitle() { return $this->mPagetitle; }
243 public function setSubtitle( $str ) { $this->mSubtitle = /*$this->parse(*/$str/*)*/; } // @bug 2514
244 public function appendSubtitle( $str ) { $this->mSubtitle .= /*$this->parse(*/$str/*)*/; } // @bug 2514
245 public function getSubtitle() { return $this->mSubtitle; }
246 public function isArticle() { return $this->mIsarticle; }
247 public function setPrintable() { $this->mPrintable = true; }
248 public function isPrintable() { return $this->mPrintable; }
249 public function setSyndicated( $show = true ) { $this->mShowFeedLinks = $show; }
250 public function isSyndicated() { return $this->mShowFeedLinks; }
251 public function setFeedAppendQuery( $val ) { $this->mFeedLinksAppendQuery = $val; }
252 public function getFeedAppendQuery() { return $this->mFeedLinksAppendQuery; }
253 public function setOnloadHandler( $js ) { $this->mOnloadHandler = $js; }
254 public function getOnloadHandler() { return $this->mOnloadHandler; }
255 public function disable() { $this->mDoNothing = true; }
256
257 public function setArticleRelated( $v ) {
258 $this->mIsArticleRelated = $v;
259 if ( !$v ) {
260 $this->mIsarticle = false;
261 }
262 }
263 public function setArticleFlag( $v ) {
264 $this->mIsarticle = $v;
265 if ( $v ) {
266 $this->mIsArticleRelated = $v;
267 }
268 }
269
270 public function isArticleRelated() { return $this->mIsArticleRelated; }
271
272 public function getLanguageLinks() { return $this->mLanguageLinks; }
273 public function addLanguageLinks($newLinkArray) {
274 $this->mLanguageLinks += $newLinkArray;
275 }
276 public function setLanguageLinks($newLinkArray) {
277 $this->mLanguageLinks = $newLinkArray;
278 }
279
280 public function getCategoryLinks() {
281 return $this->mCategoryLinks;
282 }
283
284 /**
285 * Add an array of categories, with names in the keys
286 */
287 public function addCategoryLinks( $categories ) {
288 global $wgUser, $wgContLang;
289
290 if ( !is_array( $categories ) || count( $categories ) == 0 ) {
291 return;
292 }
293
294 # Add the links to a LinkBatch
295 $arr = array( NS_CATEGORY => $categories );
296 $lb = new LinkBatch;
297 $lb->setArray( $arr );
298
299 # Fetch existence plus the hiddencat property
300 $dbr = wfGetDB( DB_SLAVE );
301 $pageTable = $dbr->tableName( 'page' );
302 $where = $lb->constructSet( 'page', $dbr );
303 $propsTable = $dbr->tableName( 'page_props' );
304 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, pp_value
305 FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
306 $res = $dbr->query( $sql, __METHOD__ );
307
308 # Add the results to the link cache
309 $lb->addResultToCache( LinkCache::singleton(), $res );
310
311 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
312 $categories = array_combine( array_keys( $categories ),
313 array_fill( 0, count( $categories ), 'normal' ) );
314
315 # Mark hidden categories
316 foreach ( $res as $row ) {
317 if ( isset( $row->pp_value ) ) {
318 $categories[$row->page_title] = 'hidden';
319 }
320 }
321
322 # Add the remaining categories to the skin
323 $sk = $wgUser->getSkin();
324 foreach ( $categories as $category => $type ) {
325 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
326 $text = $wgContLang->convertHtml( $title->getText() );
327 $this->mCategoryLinks[$type][] = $sk->makeLinkObj( $title, $text );
328 }
329 }
330
331 public function setCategoryLinks($categories) {
332 $this->mCategoryLinks = array();
333 $this->addCategoryLinks($categories);
334 }
335
336 public function suppressQuickbar() { $this->mSuppressQuickbar = true; }
337 public function isQuickbarSuppressed() { return $this->mSuppressQuickbar; }
338
339 public function disallowUserJs() { $this->mAllowUserJs = false; }
340 public function isUserJsAllowed() { return $this->mAllowUserJs; }
341
342 public function addHTML( $text ) { $this->mBodytext .= $text; }
343 public function clearHTML() { $this->mBodytext = ''; }
344 public function getHTML() { return $this->mBodytext; }
345 public function debug( $text ) { $this->mDebugtext .= $text; }
346
347 /* @deprecated */
348 public function setParserOptions( $options ) {
349 wfDeprecated( __METHOD__ );
350 return $this->parserOptions( $options );
351 }
352
353 public function parserOptions( $options = null ) {
354 if ( !$this->mParserOptions ) {
355 $this->mParserOptions = new ParserOptions;
356 }
357 return wfSetVar( $this->mParserOptions, $options );
358 }
359
360 /**
361 * Set the revision ID which will be seen by the wiki text parser
362 * for things such as embedded {{REVISIONID}} variable use.
363 * @param mixed $revid an integer, or NULL
364 * @return mixed previous value
365 */
366 public function setRevisionId( $revid ) {
367 $val = is_null( $revid ) ? null : intval( $revid );
368 return wfSetVar( $this->mRevisionId, $val );
369 }
370
371 /**
372 * Convert wikitext to HTML and add it to the buffer
373 * Default assumes that the current page title will
374 * be used.
375 *
376 * @param string $text
377 * @param bool $linestart
378 */
379 public function addWikiText( $text, $linestart = true ) {
380 global $wgTitle;
381 $this->addWikiTextTitle($text, $wgTitle, $linestart);
382 }
383
384 public function addWikiTextWithTitle($text, &$title, $linestart = true) {
385 $this->addWikiTextTitle($text, $title, $linestart);
386 }
387
388 function addWikiTextTitleTidy($text, &$title, $linestart = true) {
389 $this->addWikiTextTitle( $text, $title, $linestart, true );
390 }
391
392 public function addWikiTextTitle($text, &$title, $linestart, $tidy = false) {
393 global $wgParser;
394
395 wfProfileIn( __METHOD__ );
396
397 wfIncrStats( 'pcache_not_possible' );
398
399 $popts = $this->parserOptions();
400 $oldTidy = $popts->setTidy( $tidy );
401
402 $parserOutput = $wgParser->parse( $text, $title, $popts,
403 $linestart, true, $this->mRevisionId );
404
405 $popts->setTidy( $oldTidy );
406
407 $this->addParserOutput( $parserOutput );
408
409 wfProfileOut( __METHOD__ );
410 }
411
412 /**
413 * @todo document
414 * @param ParserOutput object &$parserOutput
415 */
416 public function addParserOutputNoText( &$parserOutput ) {
417 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
418 $this->addCategoryLinks( $parserOutput->getCategories() );
419 $this->mNewSectionLink = $parserOutput->getNewSection();
420 $this->addKeywords( $parserOutput );
421 $this->mParseWarnings = $parserOutput->getWarnings();
422 if ( $parserOutput->getCacheTime() == -1 ) {
423 $this->enableClientCache( false );
424 }
425 $this->mNoGallery = $parserOutput->getNoGallery();
426 $this->mHeadItems = array_merge( $this->mHeadItems, (array)$parserOutput->mHeadItems );
427 // Versioning...
428 $this->mTemplateIds = wfArrayMerge( $this->mTemplateIds, (array)$parserOutput->mTemplateIds );
429
430 // Display title
431 if( ( $dt = $parserOutput->getDisplayTitle() ) !== false )
432 $this->setPageTitle( $dt );
433
434 // Hooks registered in the object
435 global $wgParserOutputHooks;
436 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
437 list( $hookName, $data ) = $hookInfo;
438 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
439 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
440 }
441 }
442
443 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
444 }
445
446 /**
447 * @todo document
448 * @param ParserOutput &$parserOutput
449 */
450 function addParserOutput( &$parserOutput ) {
451 $this->addParserOutputNoText( $parserOutput );
452 $text = $parserOutput->getText();
453 wfRunHooks( 'OutputPageBeforeHTML',array( &$this, &$text ) );
454 $this->addHTML( $text );
455 }
456
457 /**
458 * Add wikitext to the buffer, assuming that this is the primary text for a page view
459 * Saves the text into the parser cache if possible.
460 *
461 * @param string $text
462 * @param Article $article
463 * @param bool $cache
464 * @deprecated Use Article::outputWikitext
465 */
466 public function addPrimaryWikiText( $text, $article, $cache = true ) {
467 global $wgParser, $wgUser;
468
469 wfDeprecated( __METHOD__ );
470
471 $popts = $this->parserOptions();
472 $popts->setTidy(true);
473 $parserOutput = $wgParser->parse( $text, $article->mTitle,
474 $popts, true, true, $this->mRevisionId );
475 $popts->setTidy(false);
476 if ( $cache && $article && $parserOutput->getCacheTime() != -1 ) {
477 $parserCache = ParserCache::singleton();
478 $parserCache->save( $parserOutput, $article, $wgUser );
479 }
480
481 $this->addParserOutput( $parserOutput );
482 }
483
484 /**
485 * @deprecated use addWikiTextTidy()
486 */
487 public function addSecondaryWikiText( $text, $linestart = true ) {
488 global $wgTitle;
489 wfDeprecated( __METHOD__ );
490 $this->addWikiTextTitleTidy($text, $wgTitle, $linestart);
491 }
492
493 /**
494 * Add wikitext with tidy enabled
495 */
496 public function addWikiTextTidy( $text, $linestart = true ) {
497 global $wgTitle;
498 $this->addWikiTextTitleTidy($text, $wgTitle, $linestart);
499 }
500
501
502 /**
503 * Add the output of a QuickTemplate to the output buffer
504 *
505 * @param QuickTemplate $template
506 */
507 public function addTemplate( &$template ) {
508 ob_start();
509 $template->execute();
510 $this->addHTML( ob_get_contents() );
511 ob_end_clean();
512 }
513
514 /**
515 * Parse wikitext and return the HTML.
516 *
517 * @param string $text
518 * @param bool $linestart Is this the start of a line?
519 * @param bool $interface ??
520 */
521 public function parse( $text, $linestart = true, $interface = false ) {
522 global $wgParser, $wgTitle;
523 $popts = $this->parserOptions();
524 if ( $interface) { $popts->setInterfaceMessage(true); }
525 $parserOutput = $wgParser->parse( $text, $wgTitle, $popts,
526 $linestart, true, $this->mRevisionId );
527 if ( $interface) { $popts->setInterfaceMessage(false); }
528 return $parserOutput->getText();
529 }
530
531 /**
532 * @param Article $article
533 * @param User $user
534 *
535 * @return bool True if successful, else false.
536 */
537 public function tryParserCache( &$article, $user ) {
538 $parserCache = ParserCache::singleton();
539 $parserOutput = $parserCache->get( $article, $user );
540 if ( $parserOutput !== false ) {
541 $this->addParserOutput( $parserOutput );
542 return true;
543 } else {
544 return false;
545 }
546 }
547
548 /**
549 * @param int $maxage Maximum cache time on the Squid, in seconds.
550 */
551 public function setSquidMaxage( $maxage ) {
552 $this->mSquidMaxage = $maxage;
553 }
554
555 /**
556 * Use enableClientCache(false) to force it to send nocache headers
557 * @param $state ??
558 */
559 public function enableClientCache( $state ) {
560 return wfSetVar( $this->mEnableClientCache, $state );
561 }
562
563 function getCacheVaryCookies() {
564 global $wgCookiePrefix, $wgCacheVaryCookies;
565 static $cookies;
566 if ( $cookies === null ) {
567 $cookies = array_merge(
568 array(
569 "{$wgCookiePrefix}Token",
570 "{$wgCookiePrefix}LoggedOut",
571 session_name()
572 ),
573 $wgCacheVaryCookies
574 );
575 wfRunHooks('GetCacheVaryCookies', array( $this, &$cookies ) );
576 }
577 return $cookies;
578 }
579
580 function uncacheableBecauseRequestVars() {
581 global $wgRequest;
582 return $wgRequest->getText('useskin', false) === false
583 && $wgRequest->getText('uselang', false) === false;
584 }
585
586 /**
587 * Check if the request has a cache-varying cookie header
588 * If it does, it's very important that we don't allow public caching
589 */
590 function haveCacheVaryCookies() {
591 global $wgRequest, $wgCookiePrefix;
592 $cookieHeader = $wgRequest->getHeader( 'cookie' );
593 if ( $cookieHeader === false ) {
594 return false;
595 }
596 $cvCookies = $this->getCacheVaryCookies();
597 foreach ( $cvCookies as $cookieName ) {
598 # Check for a simple string match, like the way squid does it
599 if ( strpos( $cookieHeader, $cookieName ) ) {
600 wfDebug( __METHOD__.": found $cookieName\n" );
601 return true;
602 }
603 }
604 wfDebug( __METHOD__.": no cache-varying cookies found\n" );
605 return false;
606 }
607
608 /** Get a complete X-Vary-Options header */
609 public function getXVO() {
610 global $wgCookiePrefix;
611 $cvCookies = $this->getCacheVaryCookies();
612 $xvo = 'X-Vary-Options: Accept-Encoding;list-contains=gzip,Cookie;';
613 $first = true;
614 foreach ( $cvCookies as $cookieName ) {
615 if ( $first ) {
616 $first = false;
617 } else {
618 $xvo .= ';';
619 }
620 $xvo .= 'string-contains=' . $cookieName;
621 }
622 return $xvo;
623 }
624
625 public function sendCacheControl() {
626 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest;
627
628 $response = $wgRequest->response();
629 if ($wgUseETag && $this->mETag)
630 $response->header("ETag: $this->mETag");
631
632 # don't serve compressed data to clients who can't handle it
633 # maintain different caches for logged-in users and non-logged in ones
634 $response->header( 'Vary: Accept-Encoding, Cookie' );
635
636 # Add an X-Vary-Options header for Squid with Wikimedia patches
637 $response->header( $this->getXVO() );
638
639 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache ) {
640 if( $wgUseSquid && session_id() == '' &&
641 ! $this->isPrintable() && $this->mSquidMaxage != 0 && !$this->haveCacheVaryCookies() )
642 {
643 if ( $wgUseESI ) {
644 # We'll purge the proxy cache explicitly, but require end user agents
645 # to revalidate against the proxy on each visit.
646 # Surrogate-Control controls our Squid, Cache-Control downstream caches
647 wfDebug( __METHOD__ . ": proxy caching with ESI; {$this->mLastModified} **\n", false );
648 # start with a shorter timeout for initial testing
649 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
650 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage.', content="ESI/1.0"');
651 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
652 } else {
653 # We'll purge the proxy cache for anons explicitly, but require end user agents
654 # to revalidate against the proxy on each visit.
655 # IMPORTANT! The Squid needs to replace the Cache-Control header with
656 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
657 wfDebug( __METHOD__ . ": local proxy caching; {$this->mLastModified} **\n", false );
658 # start with a shorter timeout for initial testing
659 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
660 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage.', must-revalidate, max-age=0' );
661 }
662 } else {
663 # We do want clients to cache if they can, but they *must* check for updates
664 # on revisiting the page.
665 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **\n", false );
666 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
667 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
668 }
669 if($this->mLastModified) $response->header( "Last-modified: {$this->mLastModified}" );
670 } else {
671 wfDebug( __METHOD__ . ": no caching **\n", false );
672
673 # In general, the absence of a last modified header should be enough to prevent
674 # the client from using its cache. We send a few other things just to make sure.
675 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
676 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
677 $response->header( 'Pragma: no-cache' );
678 }
679 }
680
681 /**
682 * Finally, all the text has been munged and accumulated into
683 * the object, let's actually output it:
684 */
685 public function output() {
686 global $wgUser, $wgOutputEncoding, $wgRequest;
687 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
688 global $wgJsMimeType, $wgUseAjax, $wgAjaxSearch, $wgAjaxWatch;
689 global $wgServer, $wgEnableMWSuggest;
690
691 if( $this->mDoNothing ){
692 return;
693 }
694
695 wfProfileIn( __METHOD__ );
696
697 if ( '' != $this->mRedirect ) {
698 # Standards require redirect URLs to be absolute
699 $this->mRedirect = wfExpandUrl( $this->mRedirect );
700 if( $this->mRedirectCode == '301') {
701 if( !$wgDebugRedirects ) {
702 $wgRequest->response()->header("HTTP/1.1 {$this->mRedirectCode} Moved Permanently");
703 }
704 $this->mLastModified = wfTimestamp( TS_RFC2822 );
705 }
706
707 $this->sendCacheControl();
708
709 $wgRequest->response()->header("Content-Type: text/html; charset=utf-8");
710 if( $wgDebugRedirects ) {
711 $url = htmlspecialchars( $this->mRedirect );
712 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
713 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
714 print "</body>\n</html>\n";
715 } else {
716 $wgRequest->response()->header( 'Location: '.$this->mRedirect );
717 }
718 wfProfileOut( __METHOD__ );
719 return;
720 }
721 elseif ( $this->mStatusCode )
722 {
723 $statusMessage = array(
724 100 => 'Continue',
725 101 => 'Switching Protocols',
726 102 => 'Processing',
727 200 => 'OK',
728 201 => 'Created',
729 202 => 'Accepted',
730 203 => 'Non-Authoritative Information',
731 204 => 'No Content',
732 205 => 'Reset Content',
733 206 => 'Partial Content',
734 207 => 'Multi-Status',
735 300 => 'Multiple Choices',
736 301 => 'Moved Permanently',
737 302 => 'Found',
738 303 => 'See Other',
739 304 => 'Not Modified',
740 305 => 'Use Proxy',
741 307 => 'Temporary Redirect',
742 400 => 'Bad Request',
743 401 => 'Unauthorized',
744 402 => 'Payment Required',
745 403 => 'Forbidden',
746 404 => 'Not Found',
747 405 => 'Method Not Allowed',
748 406 => 'Not Acceptable',
749 407 => 'Proxy Authentication Required',
750 408 => 'Request Timeout',
751 409 => 'Conflict',
752 410 => 'Gone',
753 411 => 'Length Required',
754 412 => 'Precondition Failed',
755 413 => 'Request Entity Too Large',
756 414 => 'Request-URI Too Large',
757 415 => 'Unsupported Media Type',
758 416 => 'Request Range Not Satisfiable',
759 417 => 'Expectation Failed',
760 422 => 'Unprocessable Entity',
761 423 => 'Locked',
762 424 => 'Failed Dependency',
763 500 => 'Internal Server Error',
764 501 => 'Not Implemented',
765 502 => 'Bad Gateway',
766 503 => 'Service Unavailable',
767 504 => 'Gateway Timeout',
768 505 => 'HTTP Version Not Supported',
769 507 => 'Insufficient Storage'
770 );
771
772 if ( $statusMessage[$this->mStatusCode] )
773 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode . ' ' . $statusMessage[$this->mStatusCode] );
774 }
775
776 $sk = $wgUser->getSkin();
777
778 if ( $wgUseAjax ) {
779 $this->addScriptFile( 'ajax.js' );
780
781 wfRunHooks( 'AjaxAddScript', array( &$this ) );
782
783 if( $wgAjaxSearch && $wgUser->getBoolOption( 'ajaxsearch' ) ) {
784 $this->addScriptFile( 'ajaxsearch.js' );
785 $this->addScript( "<script type=\"{$wgJsMimeType}\">hookEvent(\"load\", sajax_onload);</script>\n" );
786 }
787
788 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
789 $this->addScriptFile( 'ajaxwatch.js' );
790 }
791
792 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ){
793 $this->addScriptFile( 'mwsuggest.js' );
794 }
795 }
796
797 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
798 $this->addScriptFile( 'rightclickedit.js' );
799 }
800
801
802 # Buffer output; final headers may depend on later processing
803 ob_start();
804
805 # Disable temporary placeholders, so that the skin produces HTML
806 $sk->postParseLinkColour( false );
807
808 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
809 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
810
811 if ($this->mArticleBodyOnly) {
812 $this->out($this->mBodytext);
813 } else {
814 // Hook that allows last minute changes to the output page, e.g.
815 // adding of CSS or Javascript by extensions.
816 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
817
818 wfProfileIn( 'Output-skin' );
819 $sk->outputPage( $this );
820 wfProfileOut( 'Output-skin' );
821 }
822
823 $this->sendCacheControl();
824 ob_end_flush();
825 wfProfileOut( __METHOD__ );
826 }
827
828 /**
829 * @todo document
830 * @param string $ins
831 */
832 public function out( $ins ) {
833 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
834 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
835 $outs = $ins;
836 } else {
837 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
838 if ( false === $outs ) { $outs = $ins; }
839 }
840 print $outs;
841 }
842
843 /**
844 * @todo document
845 */
846 public static function setEncodings() {
847 global $wgInputEncoding, $wgOutputEncoding;
848 global $wgUser, $wgContLang;
849
850 $wgInputEncoding = strtolower( $wgInputEncoding );
851
852 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
853 $wgOutputEncoding = strtolower( $wgOutputEncoding );
854 return;
855 }
856 $wgOutputEncoding = $wgInputEncoding;
857 }
858
859 /**
860 * Deprecated, use wfReportTime() instead.
861 * @return string
862 * @deprecated
863 */
864 public function reportTime() {
865 wfDeprecated( __METHOD__ );
866 $time = wfReportTime();
867 return $time;
868 }
869
870 /**
871 * Produce a "user is blocked" page.
872 *
873 * @param bool $return Whether to have a "return to $wgTitle" message or not.
874 * @return nothing
875 */
876 function blockedPage( $return = true ) {
877 global $wgUser, $wgContLang, $wgTitle, $wgLang;
878
879 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
880 $this->setRobotpolicy( 'noindex,nofollow' );
881 $this->setArticleRelated( false );
882
883 $name = User::whoIs( $wgUser->blockedBy() );
884 $reason = $wgUser->blockedFor();
885 if( $reason == '' ) {
886 $reason = wfMsg( 'blockednoreason' );
887 }
888 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW, $wgUser->mBlock->mTimestamp ), true );
889 $ip = wfGetIP();
890
891 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
892
893 $blockid = $wgUser->mBlock->mId;
894
895 $blockExpiry = $wgUser->mBlock->mExpiry;
896 if ( $blockExpiry == 'infinity' ) {
897 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
898 // Search for localization in 'ipboptions'
899 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
900 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
901 if ( strpos( $option, ":" ) === false )
902 continue;
903 list( $show, $value ) = explode( ":", $option );
904 if ( $value == 'infinite' || $value == 'indefinite' ) {
905 $blockExpiry = $show;
906 break;
907 }
908 }
909 } else {
910 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW, $blockExpiry ), true );
911 }
912
913 if ( $wgUser->mBlock->mAuto ) {
914 $msg = 'autoblockedtext';
915 } else {
916 $msg = 'blockedtext';
917 }
918
919 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
920 * This could be a username, an ip range, or a single ip. */
921 $intended = $wgUser->mBlock->mAddress;
922
923 $this->addWikiMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
924
925 # Don't auto-return to special pages
926 if( $return ) {
927 $return = $wgTitle->getNamespace() > -1 ? $wgTitle : NULL;
928 $this->returnToMain( null, $return );
929 }
930 }
931
932 /**
933 * Output a standard error page
934 *
935 * @param string $title Message key for page title
936 * @param string $msg Message key for page text
937 * @param array $params Message parameters
938 */
939 public function showErrorPage( $title, $msg, $params = array() ) {
940 global $wgTitle;
941 if ( isset($wgTitle) ) {
942 $this->mDebugtext .= 'Original title: ' . $wgTitle->getPrefixedText() . "\n";
943 }
944 $this->setPageTitle( wfMsg( $title ) );
945 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
946 $this->setRobotpolicy( 'noindex,nofollow' );
947 $this->setArticleRelated( false );
948 $this->enableClientCache( false );
949 $this->mRedirect = '';
950 $this->mBodytext = '';
951
952 array_unshift( $params, 'parse' );
953 array_unshift( $params, $msg );
954 $this->addHtml( call_user_func_array( 'wfMsgExt', $params ) );
955
956 $this->returnToMain();
957 }
958
959 /**
960 * Output a standard permission error page
961 *
962 * @param array $errors Error message keys
963 */
964 public function showPermissionsErrorPage( $errors, $action = null )
965 {
966 global $wgTitle;
967
968 $this->mDebugtext .= 'Original title: ' .
969 $wgTitle->getPrefixedText() . "\n";
970 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
971 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
972 $this->setRobotpolicy( 'noindex,nofollow' );
973 $this->setArticleRelated( false );
974 $this->enableClientCache( false );
975 $this->mRedirect = '';
976 $this->mBodytext = '';
977 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
978 }
979
980 /** @deprecated */
981 public function errorpage( $title, $msg ) {
982 wfDeprecated( __METHOD__ );
983 throw new ErrorPageError( $title, $msg );
984 }
985
986 /**
987 * Display an error page indicating that a given version of MediaWiki is
988 * required to use it
989 *
990 * @param mixed $version The version of MediaWiki needed to use the page
991 */
992 public function versionRequired( $version ) {
993 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
994 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
995 $this->setRobotpolicy( 'noindex,nofollow' );
996 $this->setArticleRelated( false );
997 $this->mBodytext = '';
998
999 $this->addWikiMsg( 'versionrequiredtext', $version );
1000 $this->returnToMain();
1001 }
1002
1003 /**
1004 * Display an error page noting that a given permission bit is required.
1005 *
1006 * @param string $permission key required
1007 */
1008 public function permissionRequired( $permission ) {
1009 global $wgGroupPermissions, $wgUser;
1010
1011 $this->setPageTitle( wfMsg( 'badaccess' ) );
1012 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1013 $this->setRobotpolicy( 'noindex,nofollow' );
1014 $this->setArticleRelated( false );
1015 $this->mBodytext = '';
1016
1017 $groups = array();
1018 foreach( $wgGroupPermissions as $key => $value ) {
1019 if( isset( $value[$permission] ) && $value[$permission] == true ) {
1020 $groupName = User::getGroupName( $key );
1021 $groupPage = User::getGroupPage( $key );
1022 if( $groupPage ) {
1023 $skin = $wgUser->getSkin();
1024 $groups[] = $skin->makeLinkObj( $groupPage, $groupName );
1025 } else {
1026 $groups[] = $groupName;
1027 }
1028 }
1029 }
1030 $n = count( $groups );
1031 $groups = implode( ', ', $groups );
1032 switch( $n ) {
1033 case 0:
1034 case 1:
1035 case 2:
1036 $message = wfMsgHtml( "badaccess-group$n", $groups );
1037 break;
1038 default:
1039 $message = wfMsgHtml( 'badaccess-groups', $groups );
1040 }
1041 $this->addHtml( $message );
1042 $this->returnToMain();
1043 }
1044
1045 /**
1046 * Use permissionRequired.
1047 * @deprecated
1048 */
1049 public function sysopRequired() {
1050 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
1051 }
1052
1053 /**
1054 * Use permissionRequired.
1055 * @deprecated
1056 */
1057 public function developerRequired() {
1058 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
1059 }
1060
1061 /**
1062 * Produce the stock "please login to use the wiki" page
1063 */
1064 public function loginToUse() {
1065 global $wgUser, $wgTitle, $wgContLang;
1066
1067 if( $wgUser->isLoggedIn() ) {
1068 $this->permissionRequired( 'read' );
1069 return;
1070 }
1071
1072 $skin = $wgUser->getSkin();
1073
1074 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1075 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1076 $this->setRobotPolicy( 'noindex,nofollow' );
1077 $this->setArticleFlag( false );
1078
1079 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
1080 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $wgTitle->getPrefixedUrl() );
1081 $this->addHtml( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1082 $this->addHtml( "\n<!--" . $wgTitle->getPrefixedUrl() . "-->" );
1083
1084 # Don't return to the main page if the user can't read it
1085 # otherwise we'll end up in a pointless loop
1086 $mainPage = Title::newMainPage();
1087 if( $mainPage->userCanRead() )
1088 $this->returnToMain( null, $mainPage );
1089 }
1090
1091 /** @deprecated */
1092 public function databaseError( $fname, $sql, $error, $errno ) {
1093 throw new MWException( "OutputPage::databaseError is obsolete\n" );
1094 }
1095
1096 /**
1097 * @param array $errors An array of arrays returned by Title::getUserPermissionsErrors
1098 * @return string The wikitext error-messages, formatted into a list.
1099 */
1100 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1101 if ($action == null) {
1102 $text = wfMsgNoTrans( 'permissionserrorstext', count($errors)). "\n\n";
1103 } else {
1104 $action_desc = wfMsg( "right-$action" );
1105 $action_desc[0] = strtolower($action_desc[0]);
1106 $text = wfMsgNoTrans( 'permissionserrorstext-withaction', count($errors), $action_desc ) . "\n\n";
1107 }
1108
1109 if (count( $errors ) > 1) {
1110 $text .= '<ul class="permissions-errors">' . "\n";
1111
1112 foreach( $errors as $error )
1113 {
1114 $text .= '<li>';
1115 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1116 $text .= "</li>\n";
1117 }
1118 $text .= '</ul>';
1119 } else {
1120 $text .= '<div class="permissions-errors">' . call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) . '</div>';
1121 }
1122
1123 return $text;
1124 }
1125
1126 /**
1127 * Display a page stating that the Wiki is in read-only mode,
1128 * and optionally show the source of the page that the user
1129 * was trying to edit. Should only be called (for this
1130 * purpose) after wfReadOnly() has returned true.
1131 *
1132 * For historical reasons, this function is _also_ used to
1133 * show the error message when a user tries to edit a page
1134 * they are not allowed to edit. (Unless it's because they're
1135 * blocked, then we show blockedPage() instead.) In this
1136 * case, the second parameter should be set to true and a list
1137 * of reasons supplied as the third parameter.
1138 *
1139 * @todo Needs to be split into multiple functions.
1140 *
1141 * @param string $source Source code to show (or null).
1142 * @param bool $protected Is this a permissions error?
1143 * @param array $reasons List of reasons for this error, as returned by Title::getUserPermissionsErrors().
1144 */
1145 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1146 global $wgUser, $wgTitle;
1147 $skin = $wgUser->getSkin();
1148
1149 $this->setRobotpolicy( 'noindex,nofollow' );
1150 $this->setArticleRelated( false );
1151
1152 // If no reason is given, just supply a default "I can't let you do
1153 // that, Dave" message. Should only occur if called by legacy code.
1154 if ( $protected && empty($reasons) ) {
1155 $reasons[] = array( 'badaccess-group0' );
1156 }
1157
1158 if ( !empty($reasons) ) {
1159 // Permissions error
1160 if( $source ) {
1161 $this->setPageTitle( wfMsg( 'viewsource' ) );
1162 $this->setSubtitle( wfMsg( 'viewsourcefor', $skin->makeKnownLinkObj( $wgTitle ) ) );
1163 } else {
1164 $this->setPageTitle( wfMsg( 'badaccess' ) );
1165 }
1166 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1167 } else {
1168 // Wiki is read only
1169 $this->setPageTitle( wfMsg( 'readonly' ) );
1170 $reason = wfReadOnlyReason();
1171 $this->addWikiMsg( 'readonlytext', $reason );
1172 }
1173
1174 // Show source, if supplied
1175 if( is_string( $source ) ) {
1176 $this->addWikiMsg( 'viewsourcetext' );
1177 $text = Xml::openElement( 'textarea',
1178 array( 'id' => 'wpTextbox1',
1179 'name' => 'wpTextbox1',
1180 'cols' => $wgUser->getOption( 'cols' ),
1181 'rows' => $wgUser->getOption( 'rows' ),
1182 'readonly' => 'readonly' ) );
1183 $text .= htmlspecialchars( $source );
1184 $text .= Xml::closeElement( 'textarea' );
1185 $this->addHTML( $text );
1186
1187 // Show templates used by this article
1188 $skin = $wgUser->getSkin();
1189 $article = new Article( $wgTitle );
1190 $this->addHTML( $skin->formatTemplates( $article->getUsedTemplates() ) );
1191 }
1192
1193 # If the title doesn't exist, it's fairly pointless to print a return
1194 # link to it. After all, you just tried editing it and couldn't, so
1195 # what's there to do there?
1196 if( $wgTitle->exists() ) {
1197 $this->returnToMain( null, $wgTitle );
1198 }
1199 }
1200
1201 /** @deprecated */
1202 public function fatalError( $message ) {
1203 wfDeprecated( __METHOD__ );
1204 throw new FatalError( $message );
1205 }
1206
1207 /** @deprecated */
1208 public function unexpectedValueError( $name, $val ) {
1209 wfDeprecated( __METHOD__ );
1210 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1211 }
1212
1213 /** @deprecated */
1214 public function fileCopyError( $old, $new ) {
1215 wfDeprecated( __METHOD__ );
1216 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1217 }
1218
1219 /** @deprecated */
1220 public function fileRenameError( $old, $new ) {
1221 wfDeprecated( __METHOD__ );
1222 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1223 }
1224
1225 /** @deprecated */
1226 public function fileDeleteError( $name ) {
1227 wfDeprecated( __METHOD__ );
1228 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1229 }
1230
1231 /** @deprecated */
1232 public function fileNotFoundError( $name ) {
1233 wfDeprecated( __METHOD__ );
1234 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1235 }
1236
1237 public function showFatalError( $message ) {
1238 $this->setPageTitle( wfMsg( "internalerror" ) );
1239 $this->setRobotpolicy( "noindex,nofollow" );
1240 $this->setArticleRelated( false );
1241 $this->enableClientCache( false );
1242 $this->mRedirect = '';
1243 $this->mBodytext = $message;
1244 }
1245
1246 public function showUnexpectedValueError( $name, $val ) {
1247 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
1248 }
1249
1250 public function showFileCopyError( $old, $new ) {
1251 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
1252 }
1253
1254 public function showFileRenameError( $old, $new ) {
1255 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
1256 }
1257
1258 public function showFileDeleteError( $name ) {
1259 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
1260 }
1261
1262 public function showFileNotFoundError( $name ) {
1263 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1264 }
1265
1266 /**
1267 * Add a "return to" link pointing to a specified title
1268 *
1269 * @param Title $title Title to link
1270 */
1271 public function addReturnTo( $title ) {
1272 global $wgUser;
1273 $link = wfMsg( 'returnto', $wgUser->getSkin()->makeLinkObj( $title ) );
1274 $this->addHtml( "<p>{$link}</p>\n" );
1275 }
1276
1277 /**
1278 * Add a "return to" link pointing to a specified title,
1279 * or the title indicated in the request, or else the main page
1280 *
1281 * @param null $unused No longer used
1282 * @param Title $returnto Title to return to
1283 */
1284 public function returnToMain( $unused = null, $returnto = NULL ) {
1285 global $wgRequest;
1286
1287 if ( $returnto == NULL ) {
1288 $returnto = $wgRequest->getText( 'returnto' );
1289 }
1290
1291 if ( '' === $returnto ) {
1292 $returnto = Title::newMainPage();
1293 }
1294
1295 if ( is_object( $returnto ) ) {
1296 $titleObj = $returnto;
1297 } else {
1298 $titleObj = Title::newFromText( $returnto );
1299 }
1300 if ( !is_object( $titleObj ) ) {
1301 $titleObj = Title::newMainPage();
1302 }
1303
1304 $this->addReturnTo( $titleObj );
1305 }
1306
1307 /**
1308 * This function takes the title (first item of mGoodLinks), categories, existing and broken links for the page
1309 * and uses the first 10 of them for META keywords
1310 *
1311 * @param ParserOutput &$parserOutput
1312 */
1313 private function addKeywords( &$parserOutput ) {
1314 global $wgTitle;
1315 $this->addKeyword( $wgTitle->getPrefixedText() );
1316 $count = 1;
1317 $links2d =& $parserOutput->getLinks();
1318 if ( !is_array( $links2d ) ) {
1319 return;
1320 }
1321 foreach ( $links2d as $dbkeys ) {
1322 foreach( $dbkeys as $dbkey => $unused ) {
1323 $this->addKeyword( $dbkey );
1324 if ( ++$count > 10 ) {
1325 break 2;
1326 }
1327 }
1328 }
1329 }
1330
1331 /**
1332 * @return string The doctype, opening <html>, and head element.
1333 */
1334 public function headElement() {
1335 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1336 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces;
1337 global $wgUser, $wgContLang, $wgUseTrackbacks, $wgTitle, $wgStyleVersion;
1338
1339 if( $wgMimeType == 'text/xml' || $wgMimeType == 'application/xhtml+xml' || $wgMimeType == 'application/xml' ) {
1340 $ret = "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?>\n";
1341 } else {
1342 $ret = '';
1343 }
1344
1345 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\"\n \"$wgDTD\">\n";
1346
1347 if ( '' == $this->getHTMLTitle() ) {
1348 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1349 }
1350
1351 $rtl = $wgContLang->isRTL() ? " dir='RTL'" : '';
1352 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1353 foreach($wgXhtmlNamespaces as $tag => $ns) {
1354 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1355 }
1356 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" $rtl>\n";
1357 $ret .= "<head>\n<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n";
1358 array_push( $this->mMetatags, array( "http:Content-type", "$wgMimeType; charset={$wgOutputEncoding}" ) );
1359
1360 $ret .= $this->getHeadLinks();
1361 global $wgStylePath;
1362 if( $this->isPrintable() ) {
1363 $media = '';
1364 } else {
1365 $media = "media='print'";
1366 }
1367 $printsheet = htmlspecialchars( "$wgStylePath/common/wikiprintable.css?$wgStyleVersion" );
1368 $ret .= "<link rel='stylesheet' type='text/css' $media href='$printsheet' />\n";
1369
1370 $sk = $wgUser->getSkin();
1371 $ret .= $sk->getHeadScripts( $this->mAllowUserJs );
1372 $ret .= $this->mScripts;
1373 $ret .= $sk->getUserStyles();
1374 $ret .= $this->getHeadItems();
1375
1376 if ($wgUseTrackbacks && $this->isArticleRelated())
1377 $ret .= $wgTitle->trackbackRDF();
1378
1379 $ret .= "</head>\n";
1380 return $ret;
1381 }
1382
1383 /**
1384 * @return string HTML tag links to be put in the header.
1385 */
1386 public function getHeadLinks() {
1387 global $wgRequest, $wgFeed, $wgVersion;
1388 $ret = "<meta name=\"generator\" content=\"MediaWiki " . $wgVersion . "\" />\n";
1389 foreach ( $this->mMetatags as $tag ) {
1390 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
1391 $a = 'http-equiv';
1392 $tag[0] = substr( $tag[0], 5 );
1393 } else {
1394 $a = 'name';
1395 }
1396 $ret .= "<meta $a=\"{$tag[0]}\" content=\"{$tag[1]}\" />\n";
1397 }
1398
1399 $p = $this->mRobotpolicy;
1400 if( $p !== '' && $p != 'index,follow' ) {
1401 // http://www.robotstxt.org/wc/meta-user.html
1402 // Only show if it's different from the default robots policy
1403 $ret .= "<meta name=\"robots\" content=\"$p\" />\n";
1404 }
1405
1406 if ( count( $this->mKeywords ) > 0 ) {
1407 $strip = array(
1408 "/<.*?>/" => '',
1409 "/_/" => ' '
1410 );
1411 $ret .= "\t\t<meta name=\"keywords\" content=\"" .
1412 htmlspecialchars(preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords ))) . "\" />\n";
1413 }
1414 foreach ( $this->mLinktags as $tag ) {
1415 $ret .= "\t\t<link";
1416 foreach( $tag as $attr => $val ) {
1417 $ret .= " $attr=\"" . htmlspecialchars( $val ) . "\"";
1418 }
1419 $ret .= " />\n";
1420 }
1421
1422 if( $wgFeed ) {
1423 global $wgTitle;
1424 foreach( $this->getSyndicationLinks() as $format => $link ) {
1425 # Use the page name for the title (accessed through $wgTitle since
1426 # there's no other way). In principle, this could lead to issues
1427 # with having the same name for different feeds corresponding to
1428 # the same page, but we can't avoid that at this low a level.
1429
1430 $ret .= $this->feedLink(
1431 $format,
1432 $link,
1433 wfMsg( "page-{$format}-feed", $wgTitle->getPrefixedText() ) ); # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
1434 }
1435
1436 # Recent changes feed should appear on every page (except recentchanges,
1437 # that would be redundant). Put it after the per-page feed to avoid
1438 # changing existing behavior. It's still available, probably via a
1439 # menu in your browser.
1440
1441 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
1442 if ( $wgTitle->getPrefixedText() != $rctitle->getPrefixedText() ) {
1443 global $wgSitename;
1444
1445 $ret .= $this->feedLink(
1446 'rss',
1447 $rctitle->getFullURL( 'feed=rss' ),
1448 wfMsg( 'site-rss-feed', $wgSitename ) );
1449 $ret .= $this->feedLink(
1450 'atom',
1451 $rctitle->getFullURL( 'feed=atom' ),
1452 wfMsg( 'site-atom-feed', $wgSitename ) );
1453 }
1454 }
1455
1456 return $ret;
1457 }
1458
1459 /**
1460 * Return URLs for each supported syndication format for this page.
1461 * @return array associating format keys with URLs
1462 */
1463 public function getSyndicationLinks() {
1464 global $wgTitle, $wgFeedClasses;
1465 $links = array();
1466
1467 if( $this->isSyndicated() ) {
1468 if( is_string( $this->getFeedAppendQuery() ) ) {
1469 $appendQuery = "&" . $this->getFeedAppendQuery();
1470 } else {
1471 $appendQuery = "";
1472 }
1473
1474 foreach( $wgFeedClasses as $format => $class ) {
1475 $links[$format] = $wgTitle->getLocalUrl( "feed=$format{$appendQuery}" );
1476 }
1477 }
1478 return $links;
1479 }
1480
1481 /**
1482 * Generate a <link rel/> for an RSS feed.
1483 */
1484 private function feedLink( $type, $url, $text ) {
1485 return Xml::element( 'link', array(
1486 'rel' => 'alternate',
1487 'type' => "application/$type+xml",
1488 'title' => $text,
1489 'href' => $url ) ) . "\n";
1490 }
1491
1492 /**
1493 * Turn off regular page output and return an error reponse
1494 * for when rate limiting has triggered.
1495 */
1496 public function rateLimited() {
1497 global $wgTitle;
1498
1499 $this->setPageTitle(wfMsg('actionthrottled'));
1500 $this->setRobotPolicy( 'noindex,follow' );
1501 $this->setArticleRelated( false );
1502 $this->enableClientCache( false );
1503 $this->mRedirect = '';
1504 $this->clearHTML();
1505 $this->setStatusCode(503);
1506 $this->addWikiMsg( 'actionthrottledtext' );
1507
1508 $this->returnToMain( null, $wgTitle );
1509 }
1510
1511 /**
1512 * Show an "add new section" link?
1513 *
1514 * @return bool
1515 */
1516 public function showNewSectionLink() {
1517 return $this->mNewSectionLink;
1518 }
1519
1520 /**
1521 * Show a warning about slave lag
1522 *
1523 * If the lag is higher than $wgSlaveLagCritical seconds,
1524 * then the warning is a bit more obvious. If the lag is
1525 * lower than $wgSlaveLagWarning, then no warning is shown.
1526 *
1527 * @param int $lag Slave lag
1528 */
1529 public function showLagWarning( $lag ) {
1530 global $wgSlaveLagWarning, $wgSlaveLagCritical;
1531 if( $lag >= $wgSlaveLagWarning ) {
1532 $message = $lag < $wgSlaveLagCritical
1533 ? 'lag-warn-normal'
1534 : 'lag-warn-high';
1535 $warning = wfMsgExt( $message, 'parse', $lag );
1536 $this->addHtml( "<div class=\"mw-{$message}\">\n{$warning}\n</div>\n" );
1537 }
1538 }
1539
1540 /**
1541 * Add a wikitext-formatted message to the output.
1542 * This is equivalent to:
1543 *
1544 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
1545 */
1546 public function addWikiMsg( /*...*/ ) {
1547 $args = func_get_args();
1548 $name = array_shift( $args );
1549 $this->addWikiMsgArray( $name, $args );
1550 }
1551
1552 /**
1553 * Add a wikitext-formatted message to the output.
1554 * Like addWikiMsg() except the parameters are taken as an array
1555 * instead of a variable argument list.
1556 *
1557 * $options is passed through to wfMsgExt(), see that function for details.
1558 */
1559 public function addWikiMsgArray( $name, $args, $options = array() ) {
1560 $options[] = 'parse';
1561 $text = wfMsgExt( $name, $options, $args );
1562 $this->addHTML( $text );
1563 }
1564
1565 /**
1566 * This function takes a number of message/argument specifications, wraps them in
1567 * some overall structure, and then parses the result and adds it to the output.
1568 *
1569 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
1570 * on. The subsequent arguments may either be strings, in which case they are the
1571 * message names, or an arrays, in which case the first element is the message name,
1572 * and subsequent elements are the parameters to that message.
1573 *
1574 * The special named parameter 'options' in a message specification array is passed
1575 * through to the $options parameter of wfMsgExt().
1576 *
1577 * Don't use this for messages that are not in users interface language.
1578 *
1579 * For example:
1580 *
1581 * $wgOut->wrapWikiMsg( '<div class="error">$1</div>', 'some-error' );
1582 *
1583 * Is equivalent to:
1584 *
1585 * $wgOut->addWikiText( '<div class="error">' . wfMsgNoTrans( 'some-error' ) . '</div>' );
1586 */
1587 public function wrapWikiMsg( $wrap /*, ...*/ ) {
1588 $msgSpecs = func_get_args();
1589 array_shift( $msgSpecs );
1590 $msgSpecs = array_values( $msgSpecs );
1591 $s = $wrap;
1592 foreach ( $msgSpecs as $n => $spec ) {
1593 $options = array();
1594 if ( is_array( $spec ) ) {
1595 $args = $spec;
1596 $name = array_shift( $args );
1597 if ( isset( $args['options'] ) ) {
1598 $options = $args['options'];
1599 unset( $args['options'] );
1600 }
1601 } else {
1602 $args = array();
1603 $name = $spec;
1604 }
1605 $s = str_replace( '$' . ($n+1), wfMsgExt( $name, $options, $args ), $s );
1606 }
1607 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );
1608 }
1609 }