Uh, also I shouldn't introduce syntax errors while fixing regressions.
[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 $wgServer, $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
860 # Buffer output; final headers may depend on later processing
861 ob_start();
862
863 # Disable temporary placeholders, so that the skin produces HTML
864 $sk->postParseLinkColour( false );
865
866 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
867 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
868
869 if ($this->mArticleBodyOnly) {
870 $this->out($this->mBodytext);
871 } else {
872 // Hook that allows last minute changes to the output page, e.g.
873 // adding of CSS or Javascript by extensions.
874 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
875
876 wfProfileIn( 'Output-skin' );
877 $sk->outputPage( $this );
878 wfProfileOut( 'Output-skin' );
879 }
880
881 $this->sendCacheControl();
882 ob_end_flush();
883 wfProfileOut( __METHOD__ );
884 }
885
886 /**
887 * @todo document
888 * @param string $ins
889 */
890 public function out( $ins ) {
891 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
892 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
893 $outs = $ins;
894 } else {
895 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
896 if ( false === $outs ) { $outs = $ins; }
897 }
898 print $outs;
899 }
900
901 /**
902 * @todo document
903 */
904 public static function setEncodings() {
905 global $wgInputEncoding, $wgOutputEncoding;
906 global $wgUser, $wgContLang;
907
908 $wgInputEncoding = strtolower( $wgInputEncoding );
909
910 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
911 $wgOutputEncoding = strtolower( $wgOutputEncoding );
912 return;
913 }
914 $wgOutputEncoding = $wgInputEncoding;
915 }
916
917 /**
918 * Deprecated, use wfReportTime() instead.
919 * @return string
920 * @deprecated
921 */
922 public function reportTime() {
923 wfDeprecated( __METHOD__ );
924 $time = wfReportTime();
925 return $time;
926 }
927
928 /**
929 * Produce a "user is blocked" page.
930 *
931 * @param bool $return Whether to have a "return to $wgTitle" message or not.
932 * @return nothing
933 */
934 function blockedPage( $return = true ) {
935 global $wgUser, $wgContLang, $wgTitle, $wgLang;
936
937 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
938 $this->setRobotPolicy( 'noindex,nofollow' );
939 $this->setArticleRelated( false );
940
941 $name = User::whoIs( $wgUser->blockedBy() );
942 $reason = $wgUser->blockedFor();
943 if( $reason == '' ) {
944 $reason = wfMsg( 'blockednoreason' );
945 }
946 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW, $wgUser->mBlock->mTimestamp ), true );
947 $ip = wfGetIP();
948
949 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
950
951 $blockid = $wgUser->mBlock->mId;
952
953 $blockExpiry = $wgUser->mBlock->mExpiry;
954 if ( $blockExpiry == 'infinity' ) {
955 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
956 // Search for localization in 'ipboptions'
957 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
958 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
959 if ( strpos( $option, ":" ) === false )
960 continue;
961 list( $show, $value ) = explode( ":", $option );
962 if ( $value == 'infinite' || $value == 'indefinite' ) {
963 $blockExpiry = $show;
964 break;
965 }
966 }
967 } else {
968 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW, $blockExpiry ), true );
969 }
970
971 if ( $wgUser->mBlock->mAuto ) {
972 $msg = 'autoblockedtext';
973 } else {
974 $msg = 'blockedtext';
975 }
976
977 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
978 * This could be a username, an ip range, or a single ip. */
979 $intended = $wgUser->mBlock->mAddress;
980
981 $this->addWikiMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
982
983 # Don't auto-return to special pages
984 if( $return ) {
985 $return = $wgTitle->getNamespace() > -1 ? $wgTitle : NULL;
986 $this->returnToMain( null, $return );
987 }
988 }
989
990 /**
991 * Output a standard error page
992 *
993 * @param string $title Message key for page title
994 * @param string $msg Message key for page text
995 * @param array $params Message parameters
996 */
997 public function showErrorPage( $title, $msg, $params = array() ) {
998 global $wgTitle;
999 if ( isset($wgTitle) ) {
1000 $this->mDebugtext .= 'Original title: ' . $wgTitle->getPrefixedText() . "\n";
1001 }
1002 $this->setPageTitle( wfMsg( $title ) );
1003 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1004 $this->setRobotPolicy( 'noindex,nofollow' );
1005 $this->setArticleRelated( false );
1006 $this->enableClientCache( false );
1007 $this->mRedirect = '';
1008 $this->mBodytext = '';
1009
1010 array_unshift( $params, 'parse' );
1011 array_unshift( $params, $msg );
1012 $this->addHtml( call_user_func_array( 'wfMsgExt', $params ) );
1013
1014 $this->returnToMain();
1015 }
1016
1017 /**
1018 * Output a standard permission error page
1019 *
1020 * @param array $errors Error message keys
1021 */
1022 public function showPermissionsErrorPage( $errors, $action = null )
1023 {
1024 global $wgTitle;
1025
1026 $this->mDebugtext .= 'Original title: ' .
1027 $wgTitle->getPrefixedText() . "\n";
1028 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1029 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1030 $this->setRobotPolicy( 'noindex,nofollow' );
1031 $this->setArticleRelated( false );
1032 $this->enableClientCache( false );
1033 $this->mRedirect = '';
1034 $this->mBodytext = '';
1035 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1036 }
1037
1038 /** @deprecated */
1039 public function errorpage( $title, $msg ) {
1040 wfDeprecated( __METHOD__ );
1041 throw new ErrorPageError( $title, $msg );
1042 }
1043
1044 /**
1045 * Display an error page indicating that a given version of MediaWiki is
1046 * required to use it
1047 *
1048 * @param mixed $version The version of MediaWiki needed to use the page
1049 */
1050 public function versionRequired( $version ) {
1051 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1052 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1053 $this->setRobotPolicy( 'noindex,nofollow' );
1054 $this->setArticleRelated( false );
1055 $this->mBodytext = '';
1056
1057 $this->addWikiMsg( 'versionrequiredtext', $version );
1058 $this->returnToMain();
1059 }
1060
1061 /**
1062 * Display an error page noting that a given permission bit is required.
1063 *
1064 * @param string $permission key required
1065 */
1066 public function permissionRequired( $permission ) {
1067 global $wgGroupPermissions, $wgUser;
1068
1069 $this->setPageTitle( wfMsg( 'badaccess' ) );
1070 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1071 $this->setRobotPolicy( 'noindex,nofollow' );
1072 $this->setArticleRelated( false );
1073 $this->mBodytext = '';
1074
1075 $groups = array();
1076 foreach( $wgGroupPermissions as $key => $value ) {
1077 if( isset( $value[$permission] ) && $value[$permission] == true ) {
1078 $groupName = User::getGroupName( $key );
1079 $groupPage = User::getGroupPage( $key );
1080 if( $groupPage ) {
1081 $skin = $wgUser->getSkin();
1082 $groups[] = $skin->makeLinkObj( $groupPage, $groupName );
1083 } else {
1084 $groups[] = $groupName;
1085 }
1086 }
1087 }
1088 $n = count( $groups );
1089 $groups = implode( ', ', $groups );
1090 switch( $n ) {
1091 case 0:
1092 case 1:
1093 case 2:
1094 $message = wfMsgHtml( "badaccess-group$n", $groups );
1095 break;
1096 default:
1097 $message = wfMsgHtml( 'badaccess-groups', $groups );
1098 }
1099 $this->addHtml( $message );
1100 $this->returnToMain();
1101 }
1102
1103 /**
1104 * Use permissionRequired.
1105 * @deprecated
1106 */
1107 public function sysopRequired() {
1108 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
1109 }
1110
1111 /**
1112 * Use permissionRequired.
1113 * @deprecated
1114 */
1115 public function developerRequired() {
1116 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
1117 }
1118
1119 /**
1120 * Produce the stock "please login to use the wiki" page
1121 */
1122 public function loginToUse() {
1123 global $wgUser, $wgTitle, $wgContLang;
1124
1125 if( $wgUser->isLoggedIn() ) {
1126 $this->permissionRequired( 'read' );
1127 return;
1128 }
1129
1130 $skin = $wgUser->getSkin();
1131
1132 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1133 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1134 $this->setRobotPolicy( 'noindex,nofollow' );
1135 $this->setArticleFlag( false );
1136
1137 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
1138 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $wgTitle->getPrefixedUrl() );
1139 $this->addHtml( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1140 $this->addHtml( "\n<!--" . $wgTitle->getPrefixedUrl() . "-->" );
1141
1142 # Don't return to the main page if the user can't read it
1143 # otherwise we'll end up in a pointless loop
1144 $mainPage = Title::newMainPage();
1145 if( $mainPage->userCanRead() )
1146 $this->returnToMain( null, $mainPage );
1147 }
1148
1149 /** @deprecated */
1150 public function databaseError( $fname, $sql, $error, $errno ) {
1151 throw new MWException( "OutputPage::databaseError is obsolete\n" );
1152 }
1153
1154 /**
1155 * @param array $errors An array of arrays returned by Title::getUserPermissionsErrors
1156 * @return string The wikitext error-messages, formatted into a list.
1157 */
1158 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1159 if ($action == null) {
1160 $text = wfMsgNoTrans( 'permissionserrorstext', count($errors)). "\n\n";
1161 } else {
1162 $action_desc = wfMsg( "right-$action" );
1163 $action_desc[0] = strtolower($action_desc[0]);
1164 $text = wfMsgNoTrans( 'permissionserrorstext-withaction', count($errors), $action_desc ) . "\n\n";
1165 }
1166
1167 if (count( $errors ) > 1) {
1168 $text .= '<ul class="permissions-errors">' . "\n";
1169
1170 foreach( $errors as $error )
1171 {
1172 $text .= '<li>';
1173 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1174 $text .= "</li>\n";
1175 }
1176 $text .= '</ul>';
1177 } else {
1178 $text .= '<div class="permissions-errors">' . call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) . '</div>';
1179 }
1180
1181 return $text;
1182 }
1183
1184 /**
1185 * Display a page stating that the Wiki is in read-only mode,
1186 * and optionally show the source of the page that the user
1187 * was trying to edit. Should only be called (for this
1188 * purpose) after wfReadOnly() has returned true.
1189 *
1190 * For historical reasons, this function is _also_ used to
1191 * show the error message when a user tries to edit a page
1192 * they are not allowed to edit. (Unless it's because they're
1193 * blocked, then we show blockedPage() instead.) In this
1194 * case, the second parameter should be set to true and a list
1195 * of reasons supplied as the third parameter.
1196 *
1197 * @todo Needs to be split into multiple functions.
1198 *
1199 * @param string $source Source code to show (or null).
1200 * @param bool $protected Is this a permissions error?
1201 * @param array $reasons List of reasons for this error, as returned by Title::getUserPermissionsErrors().
1202 */
1203 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1204 global $wgUser, $wgTitle;
1205 $skin = $wgUser->getSkin();
1206
1207 $this->setRobotPolicy( 'noindex,nofollow' );
1208 $this->setArticleRelated( false );
1209
1210 // If no reason is given, just supply a default "I can't let you do
1211 // that, Dave" message. Should only occur if called by legacy code.
1212 if ( $protected && empty($reasons) ) {
1213 $reasons[] = array( 'badaccess-group0' );
1214 }
1215
1216 if ( !empty($reasons) ) {
1217 // Permissions error
1218 if( $source ) {
1219 $this->setPageTitle( wfMsg( 'viewsource' ) );
1220 $this->setSubtitle( wfMsg( 'viewsourcefor', $skin->makeKnownLinkObj( $wgTitle ) ) );
1221 } else {
1222 $this->setPageTitle( wfMsg( 'badaccess' ) );
1223 }
1224 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1225 } else {
1226 // Wiki is read only
1227 $this->setPageTitle( wfMsg( 'readonly' ) );
1228 $reason = wfReadOnlyReason();
1229 $this->addWikiMsg( 'readonlytext', $reason );
1230 }
1231
1232 // Show source, if supplied
1233 if( is_string( $source ) ) {
1234 $this->addWikiMsg( 'viewsourcetext' );
1235 $text = Xml::openElement( 'textarea',
1236 array( 'id' => 'wpTextbox1',
1237 'name' => 'wpTextbox1',
1238 'cols' => $wgUser->getOption( 'cols' ),
1239 'rows' => $wgUser->getOption( 'rows' ),
1240 'readonly' => 'readonly' ) );
1241 $text .= htmlspecialchars( $source );
1242 $text .= Xml::closeElement( 'textarea' );
1243 $this->addHTML( $text );
1244
1245 // Show templates used by this article
1246 $skin = $wgUser->getSkin();
1247 $article = new Article( $wgTitle );
1248 $this->addHTML( $skin->formatTemplates( $article->getUsedTemplates() ) );
1249 }
1250
1251 # If the title doesn't exist, it's fairly pointless to print a return
1252 # link to it. After all, you just tried editing it and couldn't, so
1253 # what's there to do there?
1254 if( $wgTitle->exists() ) {
1255 $this->returnToMain( null, $wgTitle );
1256 }
1257 }
1258
1259 /** @deprecated */
1260 public function fatalError( $message ) {
1261 wfDeprecated( __METHOD__ );
1262 throw new FatalError( $message );
1263 }
1264
1265 /** @deprecated */
1266 public function unexpectedValueError( $name, $val ) {
1267 wfDeprecated( __METHOD__ );
1268 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1269 }
1270
1271 /** @deprecated */
1272 public function fileCopyError( $old, $new ) {
1273 wfDeprecated( __METHOD__ );
1274 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1275 }
1276
1277 /** @deprecated */
1278 public function fileRenameError( $old, $new ) {
1279 wfDeprecated( __METHOD__ );
1280 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1281 }
1282
1283 /** @deprecated */
1284 public function fileDeleteError( $name ) {
1285 wfDeprecated( __METHOD__ );
1286 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1287 }
1288
1289 /** @deprecated */
1290 public function fileNotFoundError( $name ) {
1291 wfDeprecated( __METHOD__ );
1292 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1293 }
1294
1295 public function showFatalError( $message ) {
1296 $this->setPageTitle( wfMsg( "internalerror" ) );
1297 $this->setRobotPolicy( "noindex,nofollow" );
1298 $this->setArticleRelated( false );
1299 $this->enableClientCache( false );
1300 $this->mRedirect = '';
1301 $this->mBodytext = $message;
1302 }
1303
1304 public function showUnexpectedValueError( $name, $val ) {
1305 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
1306 }
1307
1308 public function showFileCopyError( $old, $new ) {
1309 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
1310 }
1311
1312 public function showFileRenameError( $old, $new ) {
1313 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
1314 }
1315
1316 public function showFileDeleteError( $name ) {
1317 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
1318 }
1319
1320 public function showFileNotFoundError( $name ) {
1321 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1322 }
1323
1324 /**
1325 * Add a "return to" link pointing to a specified title
1326 *
1327 * @param Title $title Title to link
1328 */
1329 public function addReturnTo( $title ) {
1330 global $wgUser;
1331 $link = wfMsg( 'returnto', $wgUser->getSkin()->makeLinkObj( $title ) );
1332 $this->addHtml( "<p>{$link}</p>\n" );
1333 }
1334
1335 /**
1336 * Add a "return to" link pointing to a specified title,
1337 * or the title indicated in the request, or else the main page
1338 *
1339 * @param null $unused No longer used
1340 * @param Title $returnto Title to return to
1341 */
1342 public function returnToMain( $unused = null, $returnto = NULL ) {
1343 global $wgRequest;
1344
1345 if ( $returnto == NULL ) {
1346 $returnto = $wgRequest->getText( 'returnto' );
1347 }
1348
1349 if ( '' === $returnto ) {
1350 $returnto = Title::newMainPage();
1351 }
1352
1353 if ( is_object( $returnto ) ) {
1354 $titleObj = $returnto;
1355 } else {
1356 $titleObj = Title::newFromText( $returnto );
1357 }
1358 if ( !is_object( $titleObj ) ) {
1359 $titleObj = Title::newMainPage();
1360 }
1361
1362 $this->addReturnTo( $titleObj );
1363 }
1364
1365 /**
1366 * This function takes the title (first item of mGoodLinks), categories, existing and broken links for the page
1367 * and uses the first 10 of them for META keywords
1368 *
1369 * @param ParserOutput &$parserOutput
1370 */
1371 private function addKeywords( &$parserOutput ) {
1372 global $wgTitle;
1373 $this->addKeyword( $wgTitle->getPrefixedText() );
1374 $count = 1;
1375 $links2d =& $parserOutput->getLinks();
1376 if ( !is_array( $links2d ) ) {
1377 return;
1378 }
1379 foreach ( $links2d as $dbkeys ) {
1380 foreach( $dbkeys as $dbkey => $unused ) {
1381 $this->addKeyword( $dbkey );
1382 if ( ++$count > 10 ) {
1383 break 2;
1384 }
1385 }
1386 }
1387 }
1388
1389 /**
1390 * @return string The doctype, opening <html>, and head element.
1391 */
1392 public function headElement() {
1393 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1394 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces;
1395 global $wgUser, $wgContLang, $wgUseTrackbacks, $wgTitle, $wgStyleVersion;
1396
1397 if( $wgMimeType == 'text/xml' || $wgMimeType == 'application/xhtml+xml' || $wgMimeType == 'application/xml' ) {
1398 $ret = "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?>\n";
1399 } else {
1400 $ret = '';
1401 }
1402
1403 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\"\n \"$wgDTD\">\n";
1404
1405 if ( '' == $this->getHTMLTitle() ) {
1406 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1407 }
1408
1409 $rtl = $wgContLang->isRTL() ? " dir='RTL'" : '';
1410 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1411 foreach($wgXhtmlNamespaces as $tag => $ns) {
1412 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1413 }
1414 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" $rtl>\n";
1415 $ret .= "<head>\n<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n";
1416 $this->addMeta( "http:Content-type", "$wgMimeType; charset={$wgOutputEncoding}" );
1417
1418 $ret .= $this->getHeadLinks();
1419 global $wgStylePath;
1420 if( $this->isPrintable() ) {
1421 $media = '';
1422 } else {
1423 $media = "media='print'";
1424 }
1425 $printsheet = htmlspecialchars( "$wgStylePath/common/wikiprintable.css?$wgStyleVersion" );
1426 $ret .= "<link rel='stylesheet' type='text/css' $media href='$printsheet' />\n";
1427
1428 $sk = $wgUser->getSkin();
1429 $ret .= $sk->getHeadScripts( $this->mAllowUserJs );
1430 $ret .= $this->mScripts;
1431 $ret .= $sk->getUserStyles();
1432 $ret .= $this->getHeadItems();
1433
1434 if ($wgUseTrackbacks && $this->isArticleRelated())
1435 $ret .= $wgTitle->trackbackRDF();
1436
1437 $ret .= "</head>\n";
1438 return $ret;
1439 }
1440
1441 protected function addDefaultMeta() {
1442 global $wgVersion;
1443 $this->addMeta( "generator", "MediaWiki $wgVersion" );
1444
1445 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
1446 if( $p !== 'index,follow' ) {
1447 // http://www.robotstxt.org/wc/meta-user.html
1448 // Only show if it's different from the default robots policy
1449 $this->addMeta( 'robots', $p );
1450 }
1451
1452 if ( count( $this->mKeywords ) > 0 ) {
1453 $strip = array(
1454 "/<.*?>/" => '',
1455 "/_/" => ' '
1456 );
1457 $this->addMeta( 'keywords', preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords ) ) );
1458 }
1459 }
1460
1461 /**
1462 * @return string HTML tag links to be put in the header.
1463 */
1464 public function getHeadLinks() {
1465 global $wgRequest, $wgFeed;
1466
1467 // Ideally this should happen earlier, somewhere. :P
1468 $this->addDefaultMeta();
1469
1470 $tags = array();
1471
1472 foreach ( $this->mMetatags as $tag ) {
1473 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
1474 $a = 'http-equiv';
1475 $tag[0] = substr( $tag[0], 5 );
1476 } else {
1477 $a = 'name';
1478 }
1479 $tags[] = Xml::element( 'meta',
1480 array(
1481 $a => $tag[0],
1482 'content' => $tag[1] ) );
1483 }
1484 foreach ( $this->mLinktags as $tag ) {
1485 $tags[] = Xml::element( 'link', $tag );
1486 }
1487
1488 if( $wgFeed ) {
1489 global $wgTitle;
1490 foreach( $this->getSyndicationLinks() as $format => $link ) {
1491 # Use the page name for the title (accessed through $wgTitle since
1492 # there's no other way). In principle, this could lead to issues
1493 # with having the same name for different feeds corresponding to
1494 # the same page, but we can't avoid that at this low a level.
1495
1496 $tags[] = $this->feedLink(
1497 $format,
1498 $link,
1499 wfMsg( "page-{$format}-feed", $wgTitle->getPrefixedText() ) ); # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
1500 }
1501
1502 # Recent changes feed should appear on every page (except recentchanges,
1503 # that would be redundant). Put it after the per-page feed to avoid
1504 # changing existing behavior. It's still available, probably via a
1505 # menu in your browser.
1506
1507 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
1508 if ( $wgTitle->getPrefixedText() != $rctitle->getPrefixedText() ) {
1509 global $wgSitename;
1510
1511 $tags[] = $this->feedLink(
1512 'rss',
1513 $rctitle->getFullURL( 'feed=rss' ),
1514 wfMsg( 'site-rss-feed', $wgSitename ) );
1515 $tags[] = $this->feedLink(
1516 'atom',
1517 $rctitle->getFullURL( 'feed=atom' ),
1518 wfMsg( 'site-atom-feed', $wgSitename ) );
1519 }
1520 }
1521
1522 return implode( "\n\t\t", $tags ) . "\n";
1523 }
1524
1525 /**
1526 * Return URLs for each supported syndication format for this page.
1527 * @return array associating format keys with URLs
1528 */
1529 public function getSyndicationLinks() {
1530 global $wgTitle, $wgFeedClasses;
1531 $links = array();
1532
1533 if( $this->isSyndicated() ) {
1534 if( is_string( $this->getFeedAppendQuery() ) ) {
1535 $appendQuery = "&" . $this->getFeedAppendQuery();
1536 } else {
1537 $appendQuery = "";
1538 }
1539
1540 foreach( $wgFeedClasses as $format => $class ) {
1541 $links[$format] = $wgTitle->getLocalUrl( "feed=$format{$appendQuery}" );
1542 }
1543 }
1544 return $links;
1545 }
1546
1547 /**
1548 * Generate a <link rel/> for an RSS feed.
1549 */
1550 private function feedLink( $type, $url, $text ) {
1551 return Xml::element( 'link', array(
1552 'rel' => 'alternate',
1553 'type' => "application/$type+xml",
1554 'title' => $text,
1555 'href' => $url ) );
1556 }
1557
1558 /**
1559 * Turn off regular page output and return an error reponse
1560 * for when rate limiting has triggered.
1561 */
1562 public function rateLimited() {
1563 global $wgTitle;
1564
1565 $this->setPageTitle(wfMsg('actionthrottled'));
1566 $this->setRobotPolicy( 'noindex,follow' );
1567 $this->setArticleRelated( false );
1568 $this->enableClientCache( false );
1569 $this->mRedirect = '';
1570 $this->clearHTML();
1571 $this->setStatusCode(503);
1572 $this->addWikiMsg( 'actionthrottledtext' );
1573
1574 $this->returnToMain( null, $wgTitle );
1575 }
1576
1577 /**
1578 * Show an "add new section" link?
1579 *
1580 * @return bool
1581 */
1582 public function showNewSectionLink() {
1583 return $this->mNewSectionLink;
1584 }
1585
1586 /**
1587 * Show a warning about slave lag
1588 *
1589 * If the lag is higher than $wgSlaveLagCritical seconds,
1590 * then the warning is a bit more obvious. If the lag is
1591 * lower than $wgSlaveLagWarning, then no warning is shown.
1592 *
1593 * @param int $lag Slave lag
1594 */
1595 public function showLagWarning( $lag ) {
1596 global $wgSlaveLagWarning, $wgSlaveLagCritical;
1597 if( $lag >= $wgSlaveLagWarning ) {
1598 $message = $lag < $wgSlaveLagCritical
1599 ? 'lag-warn-normal'
1600 : 'lag-warn-high';
1601 $warning = wfMsgExt( $message, 'parse', $lag );
1602 $this->addHtml( "<div class=\"mw-{$message}\">\n{$warning}\n</div>\n" );
1603 }
1604 }
1605
1606 /**
1607 * Add a wikitext-formatted message to the output.
1608 * This is equivalent to:
1609 *
1610 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
1611 */
1612 public function addWikiMsg( /*...*/ ) {
1613 $args = func_get_args();
1614 $name = array_shift( $args );
1615 $this->addWikiMsgArray( $name, $args );
1616 }
1617
1618 /**
1619 * Add a wikitext-formatted message to the output.
1620 * Like addWikiMsg() except the parameters are taken as an array
1621 * instead of a variable argument list.
1622 *
1623 * $options is passed through to wfMsgExt(), see that function for details.
1624 */
1625 public function addWikiMsgArray( $name, $args, $options = array() ) {
1626 $options[] = 'parse';
1627 $text = wfMsgExt( $name, $options, $args );
1628 $this->addHTML( $text );
1629 }
1630
1631 /**
1632 * This function takes a number of message/argument specifications, wraps them in
1633 * some overall structure, and then parses the result and adds it to the output.
1634 *
1635 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
1636 * on. The subsequent arguments may either be strings, in which case they are the
1637 * message names, or an arrays, in which case the first element is the message name,
1638 * and subsequent elements are the parameters to that message.
1639 *
1640 * The special named parameter 'options' in a message specification array is passed
1641 * through to the $options parameter of wfMsgExt().
1642 *
1643 * Don't use this for messages that are not in users interface language.
1644 *
1645 * For example:
1646 *
1647 * $wgOut->wrapWikiMsg( '<div class="error">$1</div>', 'some-error' );
1648 *
1649 * Is equivalent to:
1650 *
1651 * $wgOut->addWikiText( '<div class="error">' . wfMsgNoTrans( 'some-error' ) . '</div>' );
1652 */
1653 public function wrapWikiMsg( $wrap /*, ...*/ ) {
1654 $msgSpecs = func_get_args();
1655 array_shift( $msgSpecs );
1656 $msgSpecs = array_values( $msgSpecs );
1657 $s = $wrap;
1658 foreach ( $msgSpecs as $n => $spec ) {
1659 $options = array();
1660 if ( is_array( $spec ) ) {
1661 $args = $spec;
1662 $name = array_shift( $args );
1663 if ( isset( $args['options'] ) ) {
1664 $options = $args['options'];
1665 unset( $args['options'] );
1666 }
1667 } else {
1668 $args = array();
1669 $name = $spec;
1670 }
1671 $s = str_replace( '$' . ($n+1), wfMsgExt( $name, $options, $args ), $s );
1672 }
1673 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );
1674 }
1675 }