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