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