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