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