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