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