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