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