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