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