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