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