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