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