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