Implement $wgAllowUserRobotsControl to control whether the new __INDEX__ and __NOINDE...
[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 $wgAllowUserRobotsControl;
476
477 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
478 $this->addCategoryLinks( $parserOutput->getCategories() );
479 $this->mNewSectionLink = $parserOutput->getNewSection();
480 if( $wgAllowUserRobotsControl ) {
481 # FIXME: This probably overrides $wgArticleRobotPolicies, is that wise?
482 $this->setIndexPolicy( $parserOutput->getIndexPolicy() );
483 }
484 $this->addKeywords( $parserOutput );
485 $this->mParseWarnings = $parserOutput->getWarnings();
486 if ( $parserOutput->getCacheTime() == -1 ) {
487 $this->enableClientCache( false );
488 }
489 $this->mNoGallery = $parserOutput->getNoGallery();
490 $this->mHeadItems = array_merge( $this->mHeadItems, (array)$parserOutput->mHeadItems );
491 // Versioning...
492 $this->mTemplateIds = wfArrayMerge( $this->mTemplateIds, (array)$parserOutput->mTemplateIds );
493
494 // Display title
495 if( ( $dt = $parserOutput->getDisplayTitle() ) !== false )
496 $this->setPageTitle( $dt );
497
498 // Hooks registered in the object
499 global $wgParserOutputHooks;
500 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
501 list( $hookName, $data ) = $hookInfo;
502 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
503 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
504 }
505 }
506
507 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
508 }
509
510 /**
511 * @todo document
512 * @param ParserOutput &$parserOutput
513 */
514 function addParserOutput( &$parserOutput ) {
515 $this->addParserOutputNoText( $parserOutput );
516 $text = $parserOutput->getText();
517 wfRunHooks( 'OutputPageBeforeHTML',array( &$this, &$text ) );
518 $this->addHTML( $text );
519 }
520
521 /**
522 * Add wikitext to the buffer, assuming that this is the primary text for a page view
523 * Saves the text into the parser cache if possible.
524 *
525 * @param string $text
526 * @param Article $article
527 * @param bool $cache
528 * @deprecated Use Article::outputWikitext
529 */
530 public function addPrimaryWikiText( $text, $article, $cache = true ) {
531 global $wgParser, $wgUser;
532
533 wfDeprecated( __METHOD__ );
534
535 $popts = $this->parserOptions();
536 $popts->setTidy(true);
537 $parserOutput = $wgParser->parse( $text, $article->mTitle,
538 $popts, true, true, $this->mRevisionId );
539 $popts->setTidy(false);
540 if ( $cache && $article && $parserOutput->getCacheTime() != -1 ) {
541 $parserCache = ParserCache::singleton();
542 $parserCache->save( $parserOutput, $article, $wgUser );
543 }
544
545 $this->addParserOutput( $parserOutput );
546 }
547
548 /**
549 * @deprecated use addWikiTextTidy()
550 */
551 public function addSecondaryWikiText( $text, $linestart = true ) {
552 global $wgTitle;
553 wfDeprecated( __METHOD__ );
554 $this->addWikiTextTitleTidy($text, $wgTitle, $linestart);
555 }
556
557 /**
558 * Add wikitext with tidy enabled
559 */
560 public function addWikiTextTidy( $text, $linestart = true ) {
561 global $wgTitle;
562 $this->addWikiTextTitleTidy($text, $wgTitle, $linestart);
563 }
564
565
566 /**
567 * Add the output of a QuickTemplate to the output buffer
568 *
569 * @param QuickTemplate $template
570 */
571 public function addTemplate( &$template ) {
572 ob_start();
573 $template->execute();
574 $this->addHTML( ob_get_contents() );
575 ob_end_clean();
576 }
577
578 /**
579 * Parse wikitext and return the HTML.
580 *
581 * @param string $text
582 * @param bool $linestart Is this the start of a line?
583 * @param bool $interface ??
584 */
585 public function parse( $text, $linestart = true, $interface = false ) {
586 global $wgParser, $wgTitle;
587 $popts = $this->parserOptions();
588 if ( $interface) { $popts->setInterfaceMessage(true); }
589 $parserOutput = $wgParser->parse( $text, $wgTitle, $popts,
590 $linestart, true, $this->mRevisionId );
591 if ( $interface) { $popts->setInterfaceMessage(false); }
592 return $parserOutput->getText();
593 }
594
595 /**
596 * @param Article $article
597 * @param User $user
598 *
599 * @return bool True if successful, else false.
600 */
601 public function tryParserCache( &$article, $user ) {
602 $parserCache = ParserCache::singleton();
603 $parserOutput = $parserCache->get( $article, $user );
604 if ( $parserOutput !== false ) {
605 $this->addParserOutput( $parserOutput );
606 return true;
607 } else {
608 return false;
609 }
610 }
611
612 /**
613 * @param int $maxage Maximum cache time on the Squid, in seconds.
614 */
615 public function setSquidMaxage( $maxage ) {
616 $this->mSquidMaxage = $maxage;
617 }
618
619 /**
620 * Use enableClientCache(false) to force it to send nocache headers
621 * @param $state ??
622 */
623 public function enableClientCache( $state ) {
624 return wfSetVar( $this->mEnableClientCache, $state );
625 }
626
627 function getCacheVaryCookies() {
628 global $wgCookiePrefix, $wgCacheVaryCookies;
629 static $cookies;
630 if ( $cookies === null ) {
631 $cookies = array_merge(
632 array(
633 "{$wgCookiePrefix}Token",
634 "{$wgCookiePrefix}LoggedOut",
635 session_name()
636 ),
637 $wgCacheVaryCookies
638 );
639 wfRunHooks('GetCacheVaryCookies', array( $this, &$cookies ) );
640 }
641 return $cookies;
642 }
643
644 function uncacheableBecauseRequestVars() {
645 global $wgRequest;
646 return $wgRequest->getText('useskin', false) === false
647 && $wgRequest->getText('uselang', false) === false;
648 }
649
650 /**
651 * Check if the request has a cache-varying cookie header
652 * If it does, it's very important that we don't allow public caching
653 */
654 function haveCacheVaryCookies() {
655 global $wgRequest, $wgCookiePrefix;
656 $cookieHeader = $wgRequest->getHeader( 'cookie' );
657 if ( $cookieHeader === false ) {
658 return false;
659 }
660 $cvCookies = $this->getCacheVaryCookies();
661 foreach ( $cvCookies as $cookieName ) {
662 # Check for a simple string match, like the way squid does it
663 if ( strpos( $cookieHeader, $cookieName ) ) {
664 wfDebug( __METHOD__.": found $cookieName\n" );
665 return true;
666 }
667 }
668 wfDebug( __METHOD__.": no cache-varying cookies found\n" );
669 return false;
670 }
671
672 /** Get a complete X-Vary-Options header */
673 public function getXVO() {
674 global $wgCookiePrefix;
675 $cvCookies = $this->getCacheVaryCookies();
676 $xvo = 'X-Vary-Options: Accept-Encoding;list-contains=gzip,Cookie;';
677 $first = true;
678 foreach ( $cvCookies as $cookieName ) {
679 if ( $first ) {
680 $first = false;
681 } else {
682 $xvo .= ';';
683 }
684 $xvo .= 'string-contains=' . $cookieName;
685 }
686 return $xvo;
687 }
688
689 public function sendCacheControl() {
690 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest;
691
692 $response = $wgRequest->response();
693 if ($wgUseETag && $this->mETag)
694 $response->header("ETag: $this->mETag");
695
696 # don't serve compressed data to clients who can't handle it
697 # maintain different caches for logged-in users and non-logged in ones
698 $response->header( 'Vary: Accept-Encoding, Cookie' );
699
700 # Add an X-Vary-Options header for Squid with Wikimedia patches
701 $response->header( $this->getXVO() );
702
703 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache ) {
704 if( $wgUseSquid && session_id() == '' &&
705 ! $this->isPrintable() && $this->mSquidMaxage != 0 && !$this->haveCacheVaryCookies() )
706 {
707 if ( $wgUseESI ) {
708 # We'll purge the proxy cache explicitly, but require end user agents
709 # to revalidate against the proxy on each visit.
710 # Surrogate-Control controls our Squid, Cache-Control downstream caches
711 wfDebug( __METHOD__ . ": proxy caching with ESI; {$this->mLastModified} **\n", false );
712 # start with a shorter timeout for initial testing
713 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
714 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage.', content="ESI/1.0"');
715 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
716 } else {
717 # We'll purge the proxy cache for anons explicitly, but require end user agents
718 # to revalidate against the proxy on each visit.
719 # IMPORTANT! The Squid needs to replace the Cache-Control header with
720 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
721 wfDebug( __METHOD__ . ": local proxy caching; {$this->mLastModified} **\n", false );
722 # start with a shorter timeout for initial testing
723 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
724 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage.', must-revalidate, max-age=0' );
725 }
726 } else {
727 # We do want clients to cache if they can, but they *must* check for updates
728 # on revisiting the page.
729 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **\n", false );
730 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
731 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
732 }
733 if($this->mLastModified) $response->header( "Last-modified: {$this->mLastModified}" );
734 } else {
735 wfDebug( __METHOD__ . ": no caching **\n", false );
736
737 # In general, the absence of a last modified header should be enough to prevent
738 # the client from using its cache. We send a few other things just to make sure.
739 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
740 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
741 $response->header( 'Pragma: no-cache' );
742 }
743 }
744
745 /**
746 * Finally, all the text has been munged and accumulated into
747 * the object, let's actually output it:
748 */
749 public function output() {
750 global $wgUser, $wgOutputEncoding, $wgRequest;
751 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
752 global $wgJsMimeType, $wgUseAjax, $wgAjaxSearch, $wgAjaxWatch;
753 global $wgServer, $wgEnableMWSuggest;
754
755 if( $this->mDoNothing ){
756 return;
757 }
758
759 wfProfileIn( __METHOD__ );
760
761 if ( '' != $this->mRedirect ) {
762 # Standards require redirect URLs to be absolute
763 $this->mRedirect = wfExpandUrl( $this->mRedirect );
764 if( $this->mRedirectCode == '301') {
765 if( !$wgDebugRedirects ) {
766 $wgRequest->response()->header("HTTP/1.1 {$this->mRedirectCode} Moved Permanently");
767 }
768 $this->mLastModified = wfTimestamp( TS_RFC2822 );
769 }
770
771 $this->sendCacheControl();
772
773 $wgRequest->response()->header("Content-Type: text/html; charset=utf-8");
774 if( $wgDebugRedirects ) {
775 $url = htmlspecialchars( $this->mRedirect );
776 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
777 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
778 print "</body>\n</html>\n";
779 } else {
780 $wgRequest->response()->header( 'Location: '.$this->mRedirect );
781 }
782 wfProfileOut( __METHOD__ );
783 return;
784 }
785 elseif ( $this->mStatusCode )
786 {
787 $statusMessage = array(
788 100 => 'Continue',
789 101 => 'Switching Protocols',
790 102 => 'Processing',
791 200 => 'OK',
792 201 => 'Created',
793 202 => 'Accepted',
794 203 => 'Non-Authoritative Information',
795 204 => 'No Content',
796 205 => 'Reset Content',
797 206 => 'Partial Content',
798 207 => 'Multi-Status',
799 300 => 'Multiple Choices',
800 301 => 'Moved Permanently',
801 302 => 'Found',
802 303 => 'See Other',
803 304 => 'Not Modified',
804 305 => 'Use Proxy',
805 307 => 'Temporary Redirect',
806 400 => 'Bad Request',
807 401 => 'Unauthorized',
808 402 => 'Payment Required',
809 403 => 'Forbidden',
810 404 => 'Not Found',
811 405 => 'Method Not Allowed',
812 406 => 'Not Acceptable',
813 407 => 'Proxy Authentication Required',
814 408 => 'Request Timeout',
815 409 => 'Conflict',
816 410 => 'Gone',
817 411 => 'Length Required',
818 412 => 'Precondition Failed',
819 413 => 'Request Entity Too Large',
820 414 => 'Request-URI Too Large',
821 415 => 'Unsupported Media Type',
822 416 => 'Request Range Not Satisfiable',
823 417 => 'Expectation Failed',
824 422 => 'Unprocessable Entity',
825 423 => 'Locked',
826 424 => 'Failed Dependency',
827 500 => 'Internal Server Error',
828 501 => 'Not Implemented',
829 502 => 'Bad Gateway',
830 503 => 'Service Unavailable',
831 504 => 'Gateway Timeout',
832 505 => 'HTTP Version Not Supported',
833 507 => 'Insufficient Storage'
834 );
835
836 if ( $statusMessage[$this->mStatusCode] )
837 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode . ' ' . $statusMessage[$this->mStatusCode] );
838 }
839
840 $sk = $wgUser->getSkin();
841
842 if ( $wgUseAjax ) {
843 $this->addScriptFile( 'ajax.js' );
844
845 wfRunHooks( 'AjaxAddScript', array( &$this ) );
846
847 if( $wgAjaxSearch && $wgUser->getBoolOption( 'ajaxsearch' ) ) {
848 $this->addScriptFile( 'ajaxsearch.js' );
849 $this->addScript( "<script type=\"{$wgJsMimeType}\">hookEvent(\"load\", sajax_onload);</script>\n" );
850 }
851
852 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
853 $this->addScriptFile( 'ajaxwatch.js' );
854 }
855
856 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ){
857 $this->addScriptFile( 'mwsuggest.js' );
858 }
859 }
860
861 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
862 $this->addScriptFile( 'rightclickedit.js' );
863 }
864
865
866 # Buffer output; final headers may depend on later processing
867 ob_start();
868
869 # Disable temporary placeholders, so that the skin produces HTML
870 $sk->postParseLinkColour( false );
871
872 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
873 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
874
875 if ($this->mArticleBodyOnly) {
876 $this->out($this->mBodytext);
877 } else {
878 // Hook that allows last minute changes to the output page, e.g.
879 // adding of CSS or Javascript by extensions.
880 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
881
882 wfProfileIn( 'Output-skin' );
883 $sk->outputPage( $this );
884 wfProfileOut( 'Output-skin' );
885 }
886
887 $this->sendCacheControl();
888 ob_end_flush();
889 wfProfileOut( __METHOD__ );
890 }
891
892 /**
893 * @todo document
894 * @param string $ins
895 */
896 public function out( $ins ) {
897 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
898 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
899 $outs = $ins;
900 } else {
901 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
902 if ( false === $outs ) { $outs = $ins; }
903 }
904 print $outs;
905 }
906
907 /**
908 * @todo document
909 */
910 public static function setEncodings() {
911 global $wgInputEncoding, $wgOutputEncoding;
912 global $wgUser, $wgContLang;
913
914 $wgInputEncoding = strtolower( $wgInputEncoding );
915
916 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
917 $wgOutputEncoding = strtolower( $wgOutputEncoding );
918 return;
919 }
920 $wgOutputEncoding = $wgInputEncoding;
921 }
922
923 /**
924 * Deprecated, use wfReportTime() instead.
925 * @return string
926 * @deprecated
927 */
928 public function reportTime() {
929 wfDeprecated( __METHOD__ );
930 $time = wfReportTime();
931 return $time;
932 }
933
934 /**
935 * Produce a "user is blocked" page.
936 *
937 * @param bool $return Whether to have a "return to $wgTitle" message or not.
938 * @return nothing
939 */
940 function blockedPage( $return = true ) {
941 global $wgUser, $wgContLang, $wgTitle, $wgLang;
942
943 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
944 $this->setRobotPolicy( 'noindex,nofollow' );
945 $this->setArticleRelated( false );
946
947 $name = User::whoIs( $wgUser->blockedBy() );
948 $reason = $wgUser->blockedFor();
949 if( $reason == '' ) {
950 $reason = wfMsg( 'blockednoreason' );
951 }
952 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW, $wgUser->mBlock->mTimestamp ), true );
953 $ip = wfGetIP();
954
955 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
956
957 $blockid = $wgUser->mBlock->mId;
958
959 $blockExpiry = $wgUser->mBlock->mExpiry;
960 if ( $blockExpiry == 'infinity' ) {
961 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
962 // Search for localization in 'ipboptions'
963 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
964 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
965 if ( strpos( $option, ":" ) === false )
966 continue;
967 list( $show, $value ) = explode( ":", $option );
968 if ( $value == 'infinite' || $value == 'indefinite' ) {
969 $blockExpiry = $show;
970 break;
971 }
972 }
973 } else {
974 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW, $blockExpiry ), true );
975 }
976
977 if ( $wgUser->mBlock->mAuto ) {
978 $msg = 'autoblockedtext';
979 } else {
980 $msg = 'blockedtext';
981 }
982
983 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
984 * This could be a username, an ip range, or a single ip. */
985 $intended = $wgUser->mBlock->mAddress;
986
987 $this->addWikiMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
988
989 # Don't auto-return to special pages
990 if( $return ) {
991 $return = $wgTitle->getNamespace() > -1 ? $wgTitle : NULL;
992 $this->returnToMain( null, $return );
993 }
994 }
995
996 /**
997 * Output a standard error page
998 *
999 * @param string $title Message key for page title
1000 * @param string $msg Message key for page text
1001 * @param array $params Message parameters
1002 */
1003 public function showErrorPage( $title, $msg, $params = array() ) {
1004 global $wgTitle;
1005 if ( isset($wgTitle) ) {
1006 $this->mDebugtext .= 'Original title: ' . $wgTitle->getPrefixedText() . "\n";
1007 }
1008 $this->setPageTitle( wfMsg( $title ) );
1009 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1010 $this->setRobotPolicy( 'noindex,nofollow' );
1011 $this->setArticleRelated( false );
1012 $this->enableClientCache( false );
1013 $this->mRedirect = '';
1014 $this->mBodytext = '';
1015
1016 array_unshift( $params, 'parse' );
1017 array_unshift( $params, $msg );
1018 $this->addHtml( call_user_func_array( 'wfMsgExt', $params ) );
1019
1020 $this->returnToMain();
1021 }
1022
1023 /**
1024 * Output a standard permission error page
1025 *
1026 * @param array $errors Error message keys
1027 */
1028 public function showPermissionsErrorPage( $errors, $action = null )
1029 {
1030 global $wgTitle;
1031
1032 $this->mDebugtext .= 'Original title: ' .
1033 $wgTitle->getPrefixedText() . "\n";
1034 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1035 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1036 $this->setRobotPolicy( 'noindex,nofollow' );
1037 $this->setArticleRelated( false );
1038 $this->enableClientCache( false );
1039 $this->mRedirect = '';
1040 $this->mBodytext = '';
1041 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1042 }
1043
1044 /** @deprecated */
1045 public function errorpage( $title, $msg ) {
1046 wfDeprecated( __METHOD__ );
1047 throw new ErrorPageError( $title, $msg );
1048 }
1049
1050 /**
1051 * Display an error page indicating that a given version of MediaWiki is
1052 * required to use it
1053 *
1054 * @param mixed $version The version of MediaWiki needed to use the page
1055 */
1056 public function versionRequired( $version ) {
1057 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1058 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1059 $this->setRobotPolicy( 'noindex,nofollow' );
1060 $this->setArticleRelated( false );
1061 $this->mBodytext = '';
1062
1063 $this->addWikiMsg( 'versionrequiredtext', $version );
1064 $this->returnToMain();
1065 }
1066
1067 /**
1068 * Display an error page noting that a given permission bit is required.
1069 *
1070 * @param string $permission key required
1071 */
1072 public function permissionRequired( $permission ) {
1073 global $wgGroupPermissions, $wgUser;
1074
1075 $this->setPageTitle( wfMsg( 'badaccess' ) );
1076 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1077 $this->setRobotPolicy( 'noindex,nofollow' );
1078 $this->setArticleRelated( false );
1079 $this->mBodytext = '';
1080
1081 $groups = array();
1082 foreach( $wgGroupPermissions as $key => $value ) {
1083 if( isset( $value[$permission] ) && $value[$permission] == true ) {
1084 $groupName = User::getGroupName( $key );
1085 $groupPage = User::getGroupPage( $key );
1086 if( $groupPage ) {
1087 $skin = $wgUser->getSkin();
1088 $groups[] = $skin->makeLinkObj( $groupPage, $groupName );
1089 } else {
1090 $groups[] = $groupName;
1091 }
1092 }
1093 }
1094 $n = count( $groups );
1095 $groups = implode( ', ', $groups );
1096 switch( $n ) {
1097 case 0:
1098 case 1:
1099 case 2:
1100 $message = wfMsgHtml( "badaccess-group$n", $groups );
1101 break;
1102 default:
1103 $message = wfMsgHtml( 'badaccess-groups', $groups );
1104 }
1105 $this->addHtml( $message );
1106 $this->returnToMain();
1107 }
1108
1109 /**
1110 * Use permissionRequired.
1111 * @deprecated
1112 */
1113 public function sysopRequired() {
1114 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
1115 }
1116
1117 /**
1118 * Use permissionRequired.
1119 * @deprecated
1120 */
1121 public function developerRequired() {
1122 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
1123 }
1124
1125 /**
1126 * Produce the stock "please login to use the wiki" page
1127 */
1128 public function loginToUse() {
1129 global $wgUser, $wgTitle, $wgContLang;
1130
1131 if( $wgUser->isLoggedIn() ) {
1132 $this->permissionRequired( 'read' );
1133 return;
1134 }
1135
1136 $skin = $wgUser->getSkin();
1137
1138 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1139 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1140 $this->setRobotPolicy( 'noindex,nofollow' );
1141 $this->setArticleFlag( false );
1142
1143 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
1144 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $wgTitle->getPrefixedUrl() );
1145 $this->addHtml( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1146 $this->addHtml( "\n<!--" . $wgTitle->getPrefixedUrl() . "-->" );
1147
1148 # Don't return to the main page if the user can't read it
1149 # otherwise we'll end up in a pointless loop
1150 $mainPage = Title::newMainPage();
1151 if( $mainPage->userCanRead() )
1152 $this->returnToMain( null, $mainPage );
1153 }
1154
1155 /** @deprecated */
1156 public function databaseError( $fname, $sql, $error, $errno ) {
1157 throw new MWException( "OutputPage::databaseError is obsolete\n" );
1158 }
1159
1160 /**
1161 * @param array $errors An array of arrays returned by Title::getUserPermissionsErrors
1162 * @return string The wikitext error-messages, formatted into a list.
1163 */
1164 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1165 if ($action == null) {
1166 $text = wfMsgNoTrans( 'permissionserrorstext', count($errors)). "\n\n";
1167 } else {
1168 $action_desc = wfMsg( "right-$action" );
1169 $action_desc[0] = strtolower($action_desc[0]);
1170 $text = wfMsgNoTrans( 'permissionserrorstext-withaction', count($errors), $action_desc ) . "\n\n";
1171 }
1172
1173 if (count( $errors ) > 1) {
1174 $text .= '<ul class="permissions-errors">' . "\n";
1175
1176 foreach( $errors as $error )
1177 {
1178 $text .= '<li>';
1179 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1180 $text .= "</li>\n";
1181 }
1182 $text .= '</ul>';
1183 } else {
1184 $text .= '<div class="permissions-errors">' . call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) . '</div>';
1185 }
1186
1187 return $text;
1188 }
1189
1190 /**
1191 * Display a page stating that the Wiki is in read-only mode,
1192 * and optionally show the source of the page that the user
1193 * was trying to edit. Should only be called (for this
1194 * purpose) after wfReadOnly() has returned true.
1195 *
1196 * For historical reasons, this function is _also_ used to
1197 * show the error message when a user tries to edit a page
1198 * they are not allowed to edit. (Unless it's because they're
1199 * blocked, then we show blockedPage() instead.) In this
1200 * case, the second parameter should be set to true and a list
1201 * of reasons supplied as the third parameter.
1202 *
1203 * @todo Needs to be split into multiple functions.
1204 *
1205 * @param string $source Source code to show (or null).
1206 * @param bool $protected Is this a permissions error?
1207 * @param array $reasons List of reasons for this error, as returned by Title::getUserPermissionsErrors().
1208 */
1209 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1210 global $wgUser, $wgTitle;
1211 $skin = $wgUser->getSkin();
1212
1213 $this->setRobotPolicy( 'noindex,nofollow' );
1214 $this->setArticleRelated( false );
1215
1216 // If no reason is given, just supply a default "I can't let you do
1217 // that, Dave" message. Should only occur if called by legacy code.
1218 if ( $protected && empty($reasons) ) {
1219 $reasons[] = array( 'badaccess-group0' );
1220 }
1221
1222 if ( !empty($reasons) ) {
1223 // Permissions error
1224 if( $source ) {
1225 $this->setPageTitle( wfMsg( 'viewsource' ) );
1226 $this->setSubtitle( wfMsg( 'viewsourcefor', $skin->makeKnownLinkObj( $wgTitle ) ) );
1227 } else {
1228 $this->setPageTitle( wfMsg( 'badaccess' ) );
1229 }
1230 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1231 } else {
1232 // Wiki is read only
1233 $this->setPageTitle( wfMsg( 'readonly' ) );
1234 $reason = wfReadOnlyReason();
1235 $this->addWikiMsg( 'readonlytext', $reason );
1236 }
1237
1238 // Show source, if supplied
1239 if( is_string( $source ) ) {
1240 $this->addWikiMsg( 'viewsourcetext' );
1241 $text = Xml::openElement( 'textarea',
1242 array( 'id' => 'wpTextbox1',
1243 'name' => 'wpTextbox1',
1244 'cols' => $wgUser->getOption( 'cols' ),
1245 'rows' => $wgUser->getOption( 'rows' ),
1246 'readonly' => 'readonly' ) );
1247 $text .= htmlspecialchars( $source );
1248 $text .= Xml::closeElement( 'textarea' );
1249 $this->addHTML( $text );
1250
1251 // Show templates used by this article
1252 $skin = $wgUser->getSkin();
1253 $article = new Article( $wgTitle );
1254 $this->addHTML( $skin->formatTemplates( $article->getUsedTemplates() ) );
1255 }
1256
1257 # If the title doesn't exist, it's fairly pointless to print a return
1258 # link to it. After all, you just tried editing it and couldn't, so
1259 # what's there to do there?
1260 if( $wgTitle->exists() ) {
1261 $this->returnToMain( null, $wgTitle );
1262 }
1263 }
1264
1265 /** @deprecated */
1266 public function fatalError( $message ) {
1267 wfDeprecated( __METHOD__ );
1268 throw new FatalError( $message );
1269 }
1270
1271 /** @deprecated */
1272 public function unexpectedValueError( $name, $val ) {
1273 wfDeprecated( __METHOD__ );
1274 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1275 }
1276
1277 /** @deprecated */
1278 public function fileCopyError( $old, $new ) {
1279 wfDeprecated( __METHOD__ );
1280 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1281 }
1282
1283 /** @deprecated */
1284 public function fileRenameError( $old, $new ) {
1285 wfDeprecated( __METHOD__ );
1286 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1287 }
1288
1289 /** @deprecated */
1290 public function fileDeleteError( $name ) {
1291 wfDeprecated( __METHOD__ );
1292 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1293 }
1294
1295 /** @deprecated */
1296 public function fileNotFoundError( $name ) {
1297 wfDeprecated( __METHOD__ );
1298 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1299 }
1300
1301 public function showFatalError( $message ) {
1302 $this->setPageTitle( wfMsg( "internalerror" ) );
1303 $this->setRobotPolicy( "noindex,nofollow" );
1304 $this->setArticleRelated( false );
1305 $this->enableClientCache( false );
1306 $this->mRedirect = '';
1307 $this->mBodytext = $message;
1308 }
1309
1310 public function showUnexpectedValueError( $name, $val ) {
1311 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
1312 }
1313
1314 public function showFileCopyError( $old, $new ) {
1315 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
1316 }
1317
1318 public function showFileRenameError( $old, $new ) {
1319 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
1320 }
1321
1322 public function showFileDeleteError( $name ) {
1323 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
1324 }
1325
1326 public function showFileNotFoundError( $name ) {
1327 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1328 }
1329
1330 /**
1331 * Add a "return to" link pointing to a specified title
1332 *
1333 * @param Title $title Title to link
1334 */
1335 public function addReturnTo( $title ) {
1336 global $wgUser;
1337 $link = wfMsg( 'returnto', $wgUser->getSkin()->makeLinkObj( $title ) );
1338 $this->addHtml( "<p>{$link}</p>\n" );
1339 }
1340
1341 /**
1342 * Add a "return to" link pointing to a specified title,
1343 * or the title indicated in the request, or else the main page
1344 *
1345 * @param null $unused No longer used
1346 * @param Title $returnto Title to return to
1347 */
1348 public function returnToMain( $unused = null, $returnto = NULL ) {
1349 global $wgRequest;
1350
1351 if ( $returnto == NULL ) {
1352 $returnto = $wgRequest->getText( 'returnto' );
1353 }
1354
1355 if ( '' === $returnto ) {
1356 $returnto = Title::newMainPage();
1357 }
1358
1359 if ( is_object( $returnto ) ) {
1360 $titleObj = $returnto;
1361 } else {
1362 $titleObj = Title::newFromText( $returnto );
1363 }
1364 if ( !is_object( $titleObj ) ) {
1365 $titleObj = Title::newMainPage();
1366 }
1367
1368 $this->addReturnTo( $titleObj );
1369 }
1370
1371 /**
1372 * This function takes the title (first item of mGoodLinks), categories, existing and broken links for the page
1373 * and uses the first 10 of them for META keywords
1374 *
1375 * @param ParserOutput &$parserOutput
1376 */
1377 private function addKeywords( &$parserOutput ) {
1378 global $wgTitle;
1379 $this->addKeyword( $wgTitle->getPrefixedText() );
1380 $count = 1;
1381 $links2d =& $parserOutput->getLinks();
1382 if ( !is_array( $links2d ) ) {
1383 return;
1384 }
1385 foreach ( $links2d as $dbkeys ) {
1386 foreach( $dbkeys as $dbkey => $unused ) {
1387 $this->addKeyword( $dbkey );
1388 if ( ++$count > 10 ) {
1389 break 2;
1390 }
1391 }
1392 }
1393 }
1394
1395 /**
1396 * @return string The doctype, opening <html>, and head element.
1397 */
1398 public function headElement() {
1399 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1400 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces;
1401 global $wgUser, $wgContLang, $wgUseTrackbacks, $wgTitle, $wgStyleVersion;
1402
1403 if( $wgMimeType == 'text/xml' || $wgMimeType == 'application/xhtml+xml' || $wgMimeType == 'application/xml' ) {
1404 $ret = "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?>\n";
1405 } else {
1406 $ret = '';
1407 }
1408
1409 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\"\n \"$wgDTD\">\n";
1410
1411 if ( '' == $this->getHTMLTitle() ) {
1412 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1413 }
1414
1415 $rtl = $wgContLang->isRTL() ? " dir='RTL'" : '';
1416 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1417 foreach($wgXhtmlNamespaces as $tag => $ns) {
1418 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1419 }
1420 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" $rtl>\n";
1421 $ret .= "<head>\n<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n";
1422 $this->addMeta( "http:Content-type", "$wgMimeType; charset={$wgOutputEncoding}" );
1423
1424 $ret .= $this->getHeadLinks();
1425 global $wgStylePath;
1426 if( $this->isPrintable() ) {
1427 $media = '';
1428 } else {
1429 $media = "media='print'";
1430 }
1431 $printsheet = htmlspecialchars( "$wgStylePath/common/wikiprintable.css?$wgStyleVersion" );
1432 $ret .= "<link rel='stylesheet' type='text/css' $media href='$printsheet' />\n";
1433
1434 $sk = $wgUser->getSkin();
1435 $ret .= $sk->getHeadScripts( $this->mAllowUserJs );
1436 $ret .= $this->mScripts;
1437 $ret .= $sk->getUserStyles();
1438 $ret .= $this->getHeadItems();
1439
1440 if ($wgUseTrackbacks && $this->isArticleRelated())
1441 $ret .= $wgTitle->trackbackRDF();
1442
1443 $ret .= "</head>\n";
1444 return $ret;
1445 }
1446
1447 protected function addDefaultMeta() {
1448 global $wgVersion;
1449 $this->addMeta( "generator", "MediaWiki $wgVersion" );
1450
1451 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
1452 if( $p !== 'index,follow' ) {
1453 // http://www.robotstxt.org/wc/meta-user.html
1454 // Only show if it's different from the default robots policy
1455 $this->addMeta( 'robots', $p );
1456 }
1457
1458 if ( count( $this->mKeywords ) > 0 ) {
1459 $strip = array(
1460 "/<.*?>/" => '',
1461 "/_/" => ' '
1462 );
1463 $this->addMeta( 'keywords', preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords ) ) );
1464 }
1465 }
1466
1467 /**
1468 * @return string HTML tag links to be put in the header.
1469 */
1470 public function getHeadLinks() {
1471 global $wgRequest, $wgFeed;
1472
1473 // Ideally this should happen earlier, somewhere. :P
1474 $this->addDefaultMeta();
1475
1476 $tags = array();
1477
1478 foreach ( $this->mMetatags as $tag ) {
1479 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
1480 $a = 'http-equiv';
1481 $tag[0] = substr( $tag[0], 5 );
1482 } else {
1483 $a = 'name';
1484 }
1485 $tags[] = Xml::element( 'meta',
1486 array(
1487 $a => $tag[0],
1488 'content' => $tag[1] ) );
1489 }
1490 foreach ( $this->mLinktags as $tag ) {
1491 $tags[] = Xml::element( 'link', $tag );
1492 }
1493
1494 if( $wgFeed ) {
1495 global $wgTitle;
1496 foreach( $this->getSyndicationLinks() as $format => $link ) {
1497 # Use the page name for the title (accessed through $wgTitle since
1498 # there's no other way). In principle, this could lead to issues
1499 # with having the same name for different feeds corresponding to
1500 # the same page, but we can't avoid that at this low a level.
1501
1502 $tags[] = $this->feedLink(
1503 $format,
1504 $link,
1505 wfMsg( "page-{$format}-feed", $wgTitle->getPrefixedText() ) ); # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
1506 }
1507
1508 # Recent changes feed should appear on every page (except recentchanges,
1509 # that would be redundant). Put it after the per-page feed to avoid
1510 # changing existing behavior. It's still available, probably via a
1511 # menu in your browser.
1512
1513 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
1514 if ( $wgTitle->getPrefixedText() != $rctitle->getPrefixedText() ) {
1515 global $wgSitename;
1516
1517 $tags[] = $this->feedLink(
1518 'rss',
1519 $rctitle->getFullURL( 'feed=rss' ),
1520 wfMsg( 'site-rss-feed', $wgSitename ) );
1521 $tags[] = $this->feedLink(
1522 'atom',
1523 $rctitle->getFullURL( 'feed=atom' ),
1524 wfMsg( 'site-atom-feed', $wgSitename ) );
1525 }
1526 }
1527
1528 return implode( "\n\t\t", $tags ) . "\n";
1529 }
1530
1531 /**
1532 * Return URLs for each supported syndication format for this page.
1533 * @return array associating format keys with URLs
1534 */
1535 public function getSyndicationLinks() {
1536 global $wgTitle, $wgFeedClasses;
1537 $links = array();
1538
1539 if( $this->isSyndicated() ) {
1540 if( is_string( $this->getFeedAppendQuery() ) ) {
1541 $appendQuery = "&" . $this->getFeedAppendQuery();
1542 } else {
1543 $appendQuery = "";
1544 }
1545
1546 foreach( $wgFeedClasses as $format => $class ) {
1547 $links[$format] = $wgTitle->getLocalUrl( "feed=$format{$appendQuery}" );
1548 }
1549 }
1550 return $links;
1551 }
1552
1553 /**
1554 * Generate a <link rel/> for an RSS feed.
1555 */
1556 private function feedLink( $type, $url, $text ) {
1557 return Xml::element( 'link', array(
1558 'rel' => 'alternate',
1559 'type' => "application/$type+xml",
1560 'title' => $text,
1561 'href' => $url ) );
1562 }
1563
1564 /**
1565 * Turn off regular page output and return an error reponse
1566 * for when rate limiting has triggered.
1567 */
1568 public function rateLimited() {
1569 global $wgTitle;
1570
1571 $this->setPageTitle(wfMsg('actionthrottled'));
1572 $this->setRobotPolicy( 'noindex,follow' );
1573 $this->setArticleRelated( false );
1574 $this->enableClientCache( false );
1575 $this->mRedirect = '';
1576 $this->clearHTML();
1577 $this->setStatusCode(503);
1578 $this->addWikiMsg( 'actionthrottledtext' );
1579
1580 $this->returnToMain( null, $wgTitle );
1581 }
1582
1583 /**
1584 * Show an "add new section" link?
1585 *
1586 * @return bool
1587 */
1588 public function showNewSectionLink() {
1589 return $this->mNewSectionLink;
1590 }
1591
1592 /**
1593 * Show a warning about slave lag
1594 *
1595 * If the lag is higher than $wgSlaveLagCritical seconds,
1596 * then the warning is a bit more obvious. If the lag is
1597 * lower than $wgSlaveLagWarning, then no warning is shown.
1598 *
1599 * @param int $lag Slave lag
1600 */
1601 public function showLagWarning( $lag ) {
1602 global $wgSlaveLagWarning, $wgSlaveLagCritical;
1603 if( $lag >= $wgSlaveLagWarning ) {
1604 $message = $lag < $wgSlaveLagCritical
1605 ? 'lag-warn-normal'
1606 : 'lag-warn-high';
1607 $warning = wfMsgExt( $message, 'parse', $lag );
1608 $this->addHtml( "<div class=\"mw-{$message}\">\n{$warning}\n</div>\n" );
1609 }
1610 }
1611
1612 /**
1613 * Add a wikitext-formatted message to the output.
1614 * This is equivalent to:
1615 *
1616 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
1617 */
1618 public function addWikiMsg( /*...*/ ) {
1619 $args = func_get_args();
1620 $name = array_shift( $args );
1621 $this->addWikiMsgArray( $name, $args );
1622 }
1623
1624 /**
1625 * Add a wikitext-formatted message to the output.
1626 * Like addWikiMsg() except the parameters are taken as an array
1627 * instead of a variable argument list.
1628 *
1629 * $options is passed through to wfMsgExt(), see that function for details.
1630 */
1631 public function addWikiMsgArray( $name, $args, $options = array() ) {
1632 $options[] = 'parse';
1633 $text = wfMsgExt( $name, $options, $args );
1634 $this->addHTML( $text );
1635 }
1636
1637 /**
1638 * This function takes a number of message/argument specifications, wraps them in
1639 * some overall structure, and then parses the result and adds it to the output.
1640 *
1641 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
1642 * on. The subsequent arguments may either be strings, in which case they are the
1643 * message names, or an arrays, in which case the first element is the message name,
1644 * and subsequent elements are the parameters to that message.
1645 *
1646 * The special named parameter 'options' in a message specification array is passed
1647 * through to the $options parameter of wfMsgExt().
1648 *
1649 * Don't use this for messages that are not in users interface language.
1650 *
1651 * For example:
1652 *
1653 * $wgOut->wrapWikiMsg( '<div class="error">$1</div>', 'some-error' );
1654 *
1655 * Is equivalent to:
1656 *
1657 * $wgOut->addWikiText( '<div class="error">' . wfMsgNoTrans( 'some-error' ) . '</div>' );
1658 */
1659 public function wrapWikiMsg( $wrap /*, ...*/ ) {
1660 $msgSpecs = func_get_args();
1661 array_shift( $msgSpecs );
1662 $msgSpecs = array_values( $msgSpecs );
1663 $s = $wrap;
1664 foreach ( $msgSpecs as $n => $spec ) {
1665 $options = array();
1666 if ( is_array( $spec ) ) {
1667 $args = $spec;
1668 $name = array_shift( $args );
1669 if ( isset( $args['options'] ) ) {
1670 $options = $args['options'];
1671 unset( $args['options'] );
1672 }
1673 } else {
1674 $args = array();
1675 $name = $spec;
1676 }
1677 $s = str_replace( '$' . ($n+1), wfMsgExt( $name, $options, $args ), $s );
1678 }
1679 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );
1680 }
1681 }