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