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