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