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