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