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