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