Tweaks for SiteConfiguration:
[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 $action_desc = wfMsg( "right-$action" );
1161 $action_desc[0] = strtolower($action_desc[0]);
1162 $text = wfMsgNoTrans( 'permissionserrorstext-withaction', count($errors), $action_desc ) . "\n\n";
1163 }
1164
1165 if (count( $errors ) > 1) {
1166 $text .= '<ul class="permissions-errors">' . "\n";
1167
1168 foreach( $errors as $error )
1169 {
1170 $text .= '<li>';
1171 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1172 $text .= "</li>\n";
1173 }
1174 $text .= '</ul>';
1175 } else {
1176 $text .= '<div class="permissions-errors">' . call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) . '</div>';
1177 }
1178
1179 return $text;
1180 }
1181
1182 /**
1183 * Display a page stating that the Wiki is in read-only mode,
1184 * and optionally show the source of the page that the user
1185 * was trying to edit. Should only be called (for this
1186 * purpose) after wfReadOnly() has returned true.
1187 *
1188 * For historical reasons, this function is _also_ used to
1189 * show the error message when a user tries to edit a page
1190 * they are not allowed to edit. (Unless it's because they're
1191 * blocked, then we show blockedPage() instead.) In this
1192 * case, the second parameter should be set to true and a list
1193 * of reasons supplied as the third parameter.
1194 *
1195 * @todo Needs to be split into multiple functions.
1196 *
1197 * @param string $source Source code to show (or null).
1198 * @param bool $protected Is this a permissions error?
1199 * @param array $reasons List of reasons for this error, as returned by Title::getUserPermissionsErrors().
1200 */
1201 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1202 global $wgUser, $wgTitle;
1203 $skin = $wgUser->getSkin();
1204
1205 $this->setRobotPolicy( 'noindex,nofollow' );
1206 $this->setArticleRelated( false );
1207
1208 // If no reason is given, just supply a default "I can't let you do
1209 // that, Dave" message. Should only occur if called by legacy code.
1210 if ( $protected && empty($reasons) ) {
1211 $reasons[] = array( 'badaccess-group0' );
1212 }
1213
1214 if ( !empty($reasons) ) {
1215 // Permissions error
1216 if( $source ) {
1217 $this->setPageTitle( wfMsg( 'viewsource' ) );
1218 $this->setSubtitle( wfMsg( 'viewsourcefor', $skin->makeKnownLinkObj( $wgTitle ) ) );
1219 } else {
1220 $this->setPageTitle( wfMsg( 'badaccess' ) );
1221 }
1222 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1223 } else {
1224 // Wiki is read only
1225 $this->setPageTitle( wfMsg( 'readonly' ) );
1226 $reason = wfReadOnlyReason();
1227 $this->addWikiMsg( 'readonlytext', $reason );
1228 }
1229
1230 // Show source, if supplied
1231 if( is_string( $source ) ) {
1232 $this->addWikiMsg( 'viewsourcetext' );
1233 $text = Xml::openElement( 'textarea',
1234 array( 'id' => 'wpTextbox1',
1235 'name' => 'wpTextbox1',
1236 'cols' => $wgUser->getOption( 'cols' ),
1237 'rows' => $wgUser->getOption( 'rows' ),
1238 'readonly' => 'readonly' ) );
1239 $text .= htmlspecialchars( $source );
1240 $text .= Xml::closeElement( 'textarea' );
1241 $this->addHTML( $text );
1242
1243 // Show templates used by this article
1244 $skin = $wgUser->getSkin();
1245 $article = new Article( $wgTitle );
1246 $this->addHTML( "<div class='templatesUsed'>
1247 {$skin->formatTemplates( $article->getUsedTemplates() )}
1248 </div>
1249 " );
1250 }
1251
1252 # If the title doesn't exist, it's fairly pointless to print a return
1253 # link to it. After all, you just tried editing it and couldn't, so
1254 # what's there to do there?
1255 if( $wgTitle->exists() ) {
1256 $this->returnToMain( null, $wgTitle );
1257 }
1258 }
1259
1260 /** @deprecated */
1261 public function fatalError( $message ) {
1262 wfDeprecated( __METHOD__ );
1263 throw new FatalError( $message );
1264 }
1265
1266 /** @deprecated */
1267 public function unexpectedValueError( $name, $val ) {
1268 wfDeprecated( __METHOD__ );
1269 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1270 }
1271
1272 /** @deprecated */
1273 public function fileCopyError( $old, $new ) {
1274 wfDeprecated( __METHOD__ );
1275 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1276 }
1277
1278 /** @deprecated */
1279 public function fileRenameError( $old, $new ) {
1280 wfDeprecated( __METHOD__ );
1281 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1282 }
1283
1284 /** @deprecated */
1285 public function fileDeleteError( $name ) {
1286 wfDeprecated( __METHOD__ );
1287 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1288 }
1289
1290 /** @deprecated */
1291 public function fileNotFoundError( $name ) {
1292 wfDeprecated( __METHOD__ );
1293 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1294 }
1295
1296 public function showFatalError( $message ) {
1297 $this->setPageTitle( wfMsg( "internalerror" ) );
1298 $this->setRobotPolicy( "noindex,nofollow" );
1299 $this->setArticleRelated( false );
1300 $this->enableClientCache( false );
1301 $this->mRedirect = '';
1302 $this->mBodytext = $message;
1303 }
1304
1305 public function showUnexpectedValueError( $name, $val ) {
1306 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
1307 }
1308
1309 public function showFileCopyError( $old, $new ) {
1310 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
1311 }
1312
1313 public function showFileRenameError( $old, $new ) {
1314 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
1315 }
1316
1317 public function showFileDeleteError( $name ) {
1318 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
1319 }
1320
1321 public function showFileNotFoundError( $name ) {
1322 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1323 }
1324
1325 /**
1326 * Add a "return to" link pointing to a specified title
1327 *
1328 * @param Title $title Title to link
1329 */
1330 public function addReturnTo( $title ) {
1331 global $wgUser;
1332 $link = wfMsg( 'returnto', $wgUser->getSkin()->makeLinkObj( $title ) );
1333 $this->addHtml( "<p>{$link}</p>\n" );
1334 }
1335
1336 /**
1337 * Add a "return to" link pointing to a specified title,
1338 * or the title indicated in the request, or else the main page
1339 *
1340 * @param null $unused No longer used
1341 * @param Title $returnto Title to return to
1342 */
1343 public function returnToMain( $unused = null, $returnto = NULL ) {
1344 global $wgRequest;
1345
1346 if ( $returnto == NULL ) {
1347 $returnto = $wgRequest->getText( 'returnto' );
1348 }
1349
1350 if ( '' === $returnto ) {
1351 $returnto = Title::newMainPage();
1352 }
1353
1354 if ( is_object( $returnto ) ) {
1355 $titleObj = $returnto;
1356 } else {
1357 $titleObj = Title::newFromText( $returnto );
1358 }
1359 if ( !is_object( $titleObj ) ) {
1360 $titleObj = Title::newMainPage();
1361 }
1362
1363 $this->addReturnTo( $titleObj );
1364 }
1365
1366 /**
1367 * This function takes the title (first item of mGoodLinks), categories, existing and broken links for the page
1368 * and uses the first 10 of them for META keywords
1369 *
1370 * @param ParserOutput &$parserOutput
1371 */
1372 private function addKeywords( &$parserOutput ) {
1373 global $wgTitle;
1374 $this->addKeyword( $wgTitle->getPrefixedText() );
1375 $count = 1;
1376 $links2d =& $parserOutput->getLinks();
1377 if ( !is_array( $links2d ) ) {
1378 return;
1379 }
1380 foreach ( $links2d as $dbkeys ) {
1381 foreach( $dbkeys as $dbkey => $unused ) {
1382 $this->addKeyword( $dbkey );
1383 if ( ++$count > 10 ) {
1384 break 2;
1385 }
1386 }
1387 }
1388 }
1389
1390 /**
1391 * @return string The doctype, opening <html>, and head element.
1392 */
1393 public function headElement( Skin $sk ) {
1394 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1395 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces;
1396 global $wgUser, $wgContLang, $wgUseTrackbacks, $wgTitle, $wgStyleVersion;
1397
1398 $this->addMeta( "http:Content-type", "$wgMimeType; charset={$wgOutputEncoding}" );
1399 $this->addStyle( 'common/wikiprintable.css', 'print' );
1400 $sk->setupUserCss( $this );
1401
1402 $ret = '';
1403
1404 if( $wgMimeType == 'text/xml' || $wgMimeType == 'application/xhtml+xml' || $wgMimeType == 'application/xml' ) {
1405 $ret .= "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?>\n";
1406 }
1407
1408 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\"\n \"$wgDTD\">\n";
1409
1410 if ( '' == $this->getHTMLTitle() ) {
1411 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1412 }
1413
1414 $rtl = $wgContLang->isRTL() ? " dir='RTL'" : '';
1415 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1416 foreach($wgXhtmlNamespaces as $tag => $ns) {
1417 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1418 }
1419 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" $rtl>\n";
1420 $ret .= "<head>\n<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n\t\t";
1421 $ret .= implode( "\t\t", array(
1422 $this->getHeadLinks(),
1423 $this->buildCssLinks(),
1424 $sk->getHeadScripts( $this->mAllowUserJs ),
1425 $this->mScripts,
1426 $this->getHeadItems(),
1427 ));
1428 if( $sk->usercss ){
1429 $ret .= "<style type='text/css'>{$sk->usercss}</style>";
1430 }
1431
1432 if ($wgUseTrackbacks && $this->isArticleRelated())
1433 $ret .= $wgTitle->trackbackRDF();
1434
1435 $ret .= "</head>\n";
1436 return $ret;
1437 }
1438
1439 protected function addDefaultMeta() {
1440 global $wgVersion;
1441 $this->addMeta( "generator", "MediaWiki $wgVersion" );
1442
1443 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
1444 if( $p !== 'index,follow' ) {
1445 // http://www.robotstxt.org/wc/meta-user.html
1446 // Only show if it's different from the default robots policy
1447 $this->addMeta( 'robots', $p );
1448 }
1449
1450 if ( count( $this->mKeywords ) > 0 ) {
1451 $strip = array(
1452 "/<.*?>/" => '',
1453 "/_/" => ' '
1454 );
1455 $this->addMeta( 'keywords', preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords ) ) );
1456 }
1457 }
1458
1459 /**
1460 * @return string HTML tag links to be put in the header.
1461 */
1462 public function getHeadLinks() {
1463 global $wgRequest, $wgFeed;
1464
1465 // Ideally this should happen earlier, somewhere. :P
1466 $this->addDefaultMeta();
1467
1468 $tags = array();
1469
1470 foreach ( $this->mMetatags as $tag ) {
1471 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
1472 $a = 'http-equiv';
1473 $tag[0] = substr( $tag[0], 5 );
1474 } else {
1475 $a = 'name';
1476 }
1477 $tags[] = Xml::element( 'meta',
1478 array(
1479 $a => $tag[0],
1480 'content' => $tag[1] ) );
1481 }
1482 foreach ( $this->mLinktags as $tag ) {
1483 $tags[] = Xml::element( 'link', $tag );
1484 }
1485
1486 if( $wgFeed ) {
1487 global $wgTitle;
1488 foreach( $this->getSyndicationLinks() as $format => $link ) {
1489 # Use the page name for the title (accessed through $wgTitle since
1490 # there's no other way). In principle, this could lead to issues
1491 # with having the same name for different feeds corresponding to
1492 # the same page, but we can't avoid that at this low a level.
1493
1494 $tags[] = $this->feedLink(
1495 $format,
1496 $link,
1497 wfMsg( "page-{$format}-feed", $wgTitle->getPrefixedText() ) ); # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
1498 }
1499
1500 # Recent changes feed should appear on every page (except recentchanges,
1501 # that would be redundant). Put it after the per-page feed to avoid
1502 # changing existing behavior. It's still available, probably via a
1503 # menu in your browser. Some sites might have a different feed they'd
1504 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
1505 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
1506 # If so, use it instead.
1507
1508 global $wgOverrideSiteFeed, $wgSitename;
1509 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
1510
1511 if ( $wgOverrideSiteFeed ) {
1512 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
1513 $tags[] = $this->feedLink (
1514 $type,
1515 htmlspecialchars( $feedUrl ),
1516 wfMsg( "site-{$type}-feed", $wgSitename ) );
1517 }
1518 }
1519 else if ( $wgTitle->getPrefixedText() != $rctitle->getPrefixedText() ) {
1520 $tags[] = $this->feedLink(
1521 'rss',
1522 $rctitle->getFullURL( 'feed=rss' ),
1523 wfMsg( 'site-rss-feed', $wgSitename ) );
1524 $tags[] = $this->feedLink(
1525 'atom',
1526 $rctitle->getFullURL( 'feed=atom' ),
1527 wfMsg( 'site-atom-feed', $wgSitename ) );
1528 }
1529 }
1530
1531 return implode( "\n\t\t", $tags ) . "\n";
1532 }
1533
1534 /**
1535 * Return URLs for each supported syndication format for this page.
1536 * @return array associating format keys with URLs
1537 */
1538 public function getSyndicationLinks() {
1539 global $wgTitle, $wgFeedClasses;
1540 $links = array();
1541
1542 if( $this->isSyndicated() ) {
1543 if( is_string( $this->getFeedAppendQuery() ) ) {
1544 $appendQuery = "&" . $this->getFeedAppendQuery();
1545 } else {
1546 $appendQuery = "";
1547 }
1548
1549 foreach( $wgFeedClasses as $format => $class ) {
1550 $links[$format] = $wgTitle->getLocalUrl( "feed=$format{$appendQuery}" );
1551 }
1552 }
1553 return $links;
1554 }
1555
1556 /**
1557 * Generate a <link rel/> for an RSS feed.
1558 */
1559 private function feedLink( $type, $url, $text ) {
1560 return Xml::element( 'link', array(
1561 'rel' => 'alternate',
1562 'type' => "application/$type+xml",
1563 'title' => $text,
1564 'href' => $url ) );
1565 }
1566
1567 /**
1568 * Add a local or specified stylesheet, with the given media options.
1569 * Meant primarily for internal use...
1570 *
1571 * @param $media -- to specify a media type, 'screen', 'printable', 'handheld' or any.
1572 * @param $conditional -- for IE conditional comments, specifying an IE version
1573 * @param $dir -- set to 'rtl' or 'ltr' for direction-specific sheets
1574 */
1575 public function addStyle( $style, $media='', $condition='', $dir='' ) {
1576 $options = array();
1577 if( $media )
1578 $options['media'] = $media;
1579 if( $condition )
1580 $options['condition'] = $condition;
1581 if( $dir )
1582 $options['dir'] = $dir;
1583 $this->styles[$style] = $options;
1584 }
1585
1586 /**
1587 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
1588 * These will be applied to various media & IE conditionals.
1589 */
1590 public function buildCssLinks() {
1591 $links = array();
1592 foreach( $this->styles as $file => $options ) {
1593 $link = $this->styleLink( $file, $options );
1594 if( $link )
1595 $links[] = $link;
1596 }
1597
1598 return implode( "\n\t\t", $links );
1599 }
1600
1601 protected function styleLink( $style, $options ) {
1602 global $wgRequest;
1603
1604 if( isset( $options['dir'] ) ) {
1605 global $wgContLang;
1606 $siteDir = $wgContLang->isRTL() ? 'rtl' : 'ltr';
1607 if( $siteDir != $options['dir'] )
1608 return '';
1609 }
1610
1611 if( isset( $options['media'] ) ) {
1612 $media = $this->transformCssMedia( $options['media'] );
1613 if( is_null( $media ) ) {
1614 return '';
1615 }
1616 } else {
1617 $media = '';
1618 }
1619
1620 if( substr( $style, 0, 1 ) == '/' ||
1621 substr( $style, 0, 5 ) == 'http:' ||
1622 substr( $style, 0, 6 ) == 'https:' ) {
1623 $url = $style;
1624 } else {
1625 global $wgStylePath, $wgStyleVersion;
1626 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
1627 }
1628
1629 $attribs = array(
1630 'rel' => 'stylesheet',
1631 'href' => $url,
1632 'type' => 'text/css' );
1633 if( $media ) {
1634 $attribs['media'] = $media;
1635 }
1636
1637 $link = Xml::element( 'link', $attribs );
1638
1639 if( isset( $options['condition'] ) ) {
1640 $condition = htmlspecialchars( $options['condition'] );
1641 $link = "<!--[if $condition]>$link<![endif]-->";
1642 }
1643 return $link;
1644 }
1645
1646 function transformCssMedia( $media ) {
1647 global $wgRequest, $wgHandheldForIPhone;
1648
1649 // Switch in on-screen display for media testing
1650 $switches = array(
1651 'printable' => 'print',
1652 'handheld' => 'handheld',
1653 );
1654 foreach( $switches as $switch => $targetMedia ) {
1655 if( $wgRequest->getBool( $switch ) ) {
1656 if( $media == $targetMedia ) {
1657 $media = '';
1658 } elseif( $media == 'screen' ) {
1659 return null;
1660 }
1661 }
1662 }
1663
1664 // Expand longer media queries as iPhone doesn't grok 'handheld'
1665 if( $wgHandheldForIPhone ) {
1666 $mediaAliases = array(
1667 'screen' => 'screen and (min-device-width: 481px)',
1668 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
1669 );
1670
1671 if( isset( $mediaAliases[$media] ) ) {
1672 $media = $mediaAliases[$media];
1673 }
1674 }
1675
1676 return $media;
1677 }
1678
1679 /**
1680 * Turn off regular page output and return an error reponse
1681 * for when rate limiting has triggered.
1682 */
1683 public function rateLimited() {
1684 global $wgTitle;
1685
1686 $this->setPageTitle(wfMsg('actionthrottled'));
1687 $this->setRobotPolicy( 'noindex,follow' );
1688 $this->setArticleRelated( false );
1689 $this->enableClientCache( false );
1690 $this->mRedirect = '';
1691 $this->clearHTML();
1692 $this->setStatusCode(503);
1693 $this->addWikiMsg( 'actionthrottledtext' );
1694
1695 $this->returnToMain( null, $wgTitle );
1696 }
1697
1698 /**
1699 * Show an "add new section" link?
1700 *
1701 * @return bool
1702 */
1703 public function showNewSectionLink() {
1704 return $this->mNewSectionLink;
1705 }
1706
1707 /**
1708 * Show a warning about slave lag
1709 *
1710 * If the lag is higher than $wgSlaveLagCritical seconds,
1711 * then the warning is a bit more obvious. If the lag is
1712 * lower than $wgSlaveLagWarning, then no warning is shown.
1713 *
1714 * @param int $lag Slave lag
1715 */
1716 public function showLagWarning( $lag ) {
1717 global $wgSlaveLagWarning, $wgSlaveLagCritical;
1718 if( $lag >= $wgSlaveLagWarning ) {
1719 $message = $lag < $wgSlaveLagCritical
1720 ? 'lag-warn-normal'
1721 : 'lag-warn-high';
1722 $warning = wfMsgExt( $message, 'parse', $lag );
1723 $this->addHtml( "<div class=\"mw-{$message}\">\n{$warning}\n</div>\n" );
1724 }
1725 }
1726
1727 /**
1728 * Add a wikitext-formatted message to the output.
1729 * This is equivalent to:
1730 *
1731 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
1732 */
1733 public function addWikiMsg( /*...*/ ) {
1734 $args = func_get_args();
1735 $name = array_shift( $args );
1736 $this->addWikiMsgArray( $name, $args );
1737 }
1738
1739 /**
1740 * Add a wikitext-formatted message to the output.
1741 * Like addWikiMsg() except the parameters are taken as an array
1742 * instead of a variable argument list.
1743 *
1744 * $options is passed through to wfMsgExt(), see that function for details.
1745 */
1746 public function addWikiMsgArray( $name, $args, $options = array() ) {
1747 $options[] = 'parse';
1748 $text = wfMsgExt( $name, $options, $args );
1749 $this->addHTML( $text );
1750 }
1751
1752 /**
1753 * This function takes a number of message/argument specifications, wraps them in
1754 * some overall structure, and then parses the result and adds it to the output.
1755 *
1756 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
1757 * on. The subsequent arguments may either be strings, in which case they are the
1758 * message names, or an arrays, in which case the first element is the message name,
1759 * and subsequent elements are the parameters to that message.
1760 *
1761 * The special named parameter 'options' in a message specification array is passed
1762 * through to the $options parameter of wfMsgExt().
1763 *
1764 * Don't use this for messages that are not in users interface language.
1765 *
1766 * For example:
1767 *
1768 * $wgOut->wrapWikiMsg( '<div class="error">$1</div>', 'some-error' );
1769 *
1770 * Is equivalent to:
1771 *
1772 * $wgOut->addWikiText( '<div class="error">' . wfMsgNoTrans( 'some-error' ) . '</div>' );
1773 */
1774 public function wrapWikiMsg( $wrap /*, ...*/ ) {
1775 $msgSpecs = func_get_args();
1776 array_shift( $msgSpecs );
1777 $msgSpecs = array_values( $msgSpecs );
1778 $s = $wrap;
1779 foreach ( $msgSpecs as $n => $spec ) {
1780 $options = array();
1781 if ( is_array( $spec ) ) {
1782 $args = $spec;
1783 $name = array_shift( $args );
1784 if ( isset( $args['options'] ) ) {
1785 $options = $args['options'];
1786 unset( $args['options'] );
1787 }
1788 } else {
1789 $args = array();
1790 $name = $spec;
1791 }
1792 $s = str_replace( '$' . ($n+1), wfMsgExt( $name, $options, $args ), $s );
1793 }
1794 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );
1795 }
1796 }