cleanup to mwsuggest.js & fix some things suggested by JSLint
[lhc/web/wiklou.git] / includes / OutputPage.php
1 <?php
2 if ( ! defined( 'MEDIAWIKI' ) )
3 die( 1 );
4
5 /**
6 * @todo document
7 */
8 class OutputPage {
9 var $mMetatags = array(), $mKeywords = array(), $mLinktags = array();
10 var $mExtStyles = array();
11 var $mPagetitle = '', $mBodytext = '', $mDebugtext = '';
12 var $mHTMLtitle = '', $mIsarticle = true, $mPrintable = false;
13 var $mSubtitle = '', $mRedirect = '', $mStatusCode;
14 var $mLastModified = '', $mETag = false;
15 var $mCategoryLinks = array(), $mCategories = array(), $mLanguageLinks = array();
16
17 var $mScripts = '', $mLinkColours, $mPageLinkTitle = '', $mHeadItems = array();
18 var $mInlineMsg = array();
19
20 var $mTemplateIds = array();
21
22 var $mAllowUserJs;
23 var $mSuppressQuickbar = false;
24 var $mDoNothing = false;
25 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
26 var $mIsArticleRelated = true;
27 protected $mParserOptions = null; // lazy initialised, use parserOptions()
28
29 var $mFeedLinks = array();
30
31 var $mEnableClientCache = true;
32 var $mArticleBodyOnly = false;
33
34 var $mNewSectionLink = false;
35 var $mHideNewSectionLink = false;
36 var $mNoGallery = false;
37 var $mPageTitleActionText = '';
38 var $mParseWarnings = array();
39 var $mSquidMaxage = 0;
40 var $mRevisionId = null;
41 protected $mTitle = null;
42
43 /**
44 * An array of stylesheet filenames (relative from skins path), with options
45 * for CSS media, IE conditions, and RTL/LTR direction.
46 * For internal use; add settings in the skin via $this->addStyle()
47 */
48 var $styles = array();
49
50 private $mIndexPolicy = 'index';
51 private $mFollowPolicy = 'follow';
52 private $mVaryHeader = array( 'Accept-Encoding' => array('list-contains=gzip'),
53 'Cookie' => null );
54
55 /**
56 * Constructor
57 * Initialise private variables
58 */
59 function __construct() {
60 global $wgAllowUserJs;
61 $this->mAllowUserJs = $wgAllowUserJs;
62 }
63
64 public function redirect( $url, $responsecode = '302' ) {
65 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
66 $this->mRedirect = str_replace( "\n", '', $url );
67 $this->mRedirectCode = $responsecode;
68 }
69
70 public function getRedirect() {
71 return $this->mRedirect;
72 }
73
74 /**
75 * Set the HTTP status code to send with the output.
76 *
77 * @param int $statusCode
78 * @return nothing
79 */
80 function setStatusCode( $statusCode ) { $this->mStatusCode = $statusCode; }
81
82 /**
83 * Add a new <meta> tag
84 * To add an http-equiv meta tag, precede the name with "http:"
85 *
86 * @param $name tag name
87 * @param $val tag value
88 */
89 function addMeta( $name, $val ) {
90 array_push( $this->mMetatags, array( $name, $val ) );
91 }
92
93 function addKeyword( $text ) {
94 if( is_array( $text )) {
95 $this->mKeywords = array_merge( $this->mKeywords, $text );
96 } else {
97 array_push( $this->mKeywords, $text );
98 }
99 }
100 function addScript( $script ) {
101 $this->mScripts .= $script . "\n";
102 }
103
104 /**
105 * Register and add a stylesheet from an extension directory.
106 * @param $url String path to sheet. Provide either a full url (beginning
107 * with 'http', etc) or a relative path from the document root
108 * (beginning with '/'). Otherwise it behaves identically to
109 * addStyle() and draws from the /skins folder.
110 */
111 public function addExtensionStyle( $url ) {
112 array_push( $this->mExtStyles, $url );
113 }
114
115 /**
116 * Add a JavaScript file out of skins/common, or a given relative path.
117 * @param string $file filename in skins/common or complete on-server path (/foo/bar.js)
118 */
119 function addScriptFile( $file ) {
120 global $wgStylePath, $wgStyleVersion, $wgJsMimeType;
121 if( substr( $file, 0, 1 ) == '/' ) {
122 $path = $file;
123 } else {
124 $path = "{$wgStylePath}/common/{$file}";
125 }
126 $this->addScript(
127 Xml::element( 'script',
128 array(
129 'type' => $wgJsMimeType,
130 'src' => "$path?$wgStyleVersion",
131 ),
132 '', false
133 )
134 );
135 }
136
137 /**
138 * Add a self-contained script tag with the given contents
139 * @param string $script JavaScript text, no <script> tags
140 */
141 function addInlineScript( $script ) {
142 $this->mScripts .= Html::inlineScript( "\n$script\n" ) . "\n";
143 }
144
145 /**
146 * Get all registered JS and CSS tags for the header.
147 */
148 function getScript() {
149 return $this->mScripts . $this->getHeadItems();
150 }
151
152 function getHeadItems() {
153 $s = '';
154 foreach ( $this->mHeadItems as $item ) {
155 $s .= $item;
156 }
157 return $s;
158 }
159
160 function addHeadItem( $name, $value ) {
161 $this->mHeadItems[$name] = $value;
162 }
163
164 function hasHeadItem( $name ) {
165 return isset( $this->mHeadItems[$name] );
166 }
167
168 function setETag($tag) { $this->mETag = $tag; }
169 function setArticleBodyOnly($only) { $this->mArticleBodyOnly = $only; }
170 function getArticleBodyOnly() { return $this->mArticleBodyOnly; }
171
172 function addLink( $linkarr ) {
173 # $linkarr should be an associative array of attributes. We'll escape on output.
174 array_push( $this->mLinktags, $linkarr );
175 }
176
177 # Get all links added by extensions
178 function getExtStyle() {
179 return $this->mExtStyles;
180 }
181
182 function addMetadataLink( $linkarr ) {
183 # note: buggy CC software only reads first "meta" link
184 static $haveMeta = false;
185 $linkarr['rel'] = ($haveMeta) ? 'alternate meta' : 'meta';
186 $this->addLink( $linkarr );
187 $haveMeta = true;
188 }
189
190 /**
191 * checkLastModified tells the client to use the client-cached page if
192 * possible. If sucessful, the OutputPage is disabled so that
193 * any future call to OutputPage->output() have no effect.
194 *
195 * Side effect: sets mLastModified for Last-Modified header
196 *
197 * @return bool True iff cache-ok headers was sent.
198 */
199 function checkLastModified( $timestamp ) {
200 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
201
202 if ( !$timestamp || $timestamp == '19700101000000' ) {
203 wfDebug( __METHOD__ . ": CACHE DISABLED, NO TIMESTAMP\n" );
204 return false;
205 }
206 if( !$wgCachePages ) {
207 wfDebug( __METHOD__ . ": CACHE DISABLED\n", false );
208 return false;
209 }
210 if( $wgUser->getOption( 'nocache' ) ) {
211 wfDebug( __METHOD__ . ": USER DISABLED CACHE\n", false );
212 return false;
213 }
214
215 $timestamp = wfTimestamp( TS_MW, $timestamp );
216 $modifiedTimes = array(
217 'page' => $timestamp,
218 'user' => $wgUser->getTouched(),
219 'epoch' => $wgCacheEpoch
220 );
221 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
222
223 $maxModified = max( $modifiedTimes );
224 $this->mLastModified = wfTimestamp( TS_RFC2822, $maxModified );
225
226 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
227 wfDebug( __METHOD__ . ": client did not send If-Modified-Since header\n", false );
228 return false;
229 }
230
231 # Make debug info
232 $info = '';
233 foreach ( $modifiedTimes as $name => $value ) {
234 if ( $info !== '' ) {
235 $info .= ', ';
236 }
237 $info .= "$name=" . wfTimestamp( TS_ISO_8601, $value );
238 }
239
240 # IE sends sizes after the date like this:
241 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
242 # this breaks strtotime().
243 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
244
245 wfSuppressWarnings(); // E_STRICT system time bitching
246 $clientHeaderTime = strtotime( $clientHeader );
247 wfRestoreWarnings();
248 if ( !$clientHeaderTime ) {
249 wfDebug( __METHOD__ . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
250 return false;
251 }
252 $clientHeaderTime = wfTimestamp( TS_MW, $clientHeaderTime );
253
254 wfDebug( __METHOD__ . ": client sent If-Modified-Since: " .
255 wfTimestamp( TS_ISO_8601, $clientHeaderTime ) . "\n", false );
256 wfDebug( __METHOD__ . ": effective Last-Modified: " .
257 wfTimestamp( TS_ISO_8601, $maxModified ) . "\n", false );
258 if( $clientHeaderTime < $maxModified ) {
259 wfDebug( __METHOD__ . ": STALE, $info\n", false );
260 return false;
261 }
262
263 # Not modified
264 # Give a 304 response code and disable body output
265 wfDebug( __METHOD__ . ": NOT MODIFIED, $info\n", false );
266 ini_set('zlib.output_compression', 0);
267 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
268 $this->sendCacheControl();
269 $this->disable();
270
271 // Don't output a compressed blob when using ob_gzhandler;
272 // it's technically against HTTP spec and seems to confuse
273 // Firefox when the response gets split over two packets.
274 wfClearOutputBuffers();
275
276 return true;
277 }
278
279 function setPageTitleActionText( $text ) {
280 $this->mPageTitleActionText = $text;
281 }
282
283 function getPageTitleActionText () {
284 if ( isset( $this->mPageTitleActionText ) ) {
285 return $this->mPageTitleActionText;
286 }
287 }
288
289 /**
290 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
291 *
292 * @param $policy string The literal string to output as the contents of
293 * the meta tag. Will be parsed according to the spec and output in
294 * standardized form.
295 * @return null
296 */
297 public function setRobotPolicy( $policy ) {
298 $policy = Article::formatRobotPolicy( $policy );
299
300 if( isset( $policy['index'] ) ){
301 $this->setIndexPolicy( $policy['index'] );
302 }
303 if( isset( $policy['follow'] ) ){
304 $this->setFollowPolicy( $policy['follow'] );
305 }
306 }
307
308 /**
309 * Set the index policy for the page, but leave the follow policy un-
310 * touched.
311 *
312 * @param $policy string Either 'index' or 'noindex'.
313 * @return null
314 */
315 public function setIndexPolicy( $policy ) {
316 $policy = trim( $policy );
317 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
318 $this->mIndexPolicy = $policy;
319 }
320 }
321
322 /**
323 * Set the follow policy for the page, but leave the index policy un-
324 * touched.
325 *
326 * @param $policy string Either 'follow' or 'nofollow'.
327 * @return null
328 */
329 public function setFollowPolicy( $policy ) {
330 $policy = trim( $policy );
331 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
332 $this->mFollowPolicy = $policy;
333 }
334 }
335
336 /**
337 * "HTML title" means the contents of <title>. It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
338 */
339 public function setHTMLTitle( $name ) {
340 $this->mHTMLtitle = $name;
341 }
342
343 /**
344 * "Page title" means the contents of <h1>. It is stored as a valid HTML fragment.
345 * This function allows good tags like <sup> in the <h1> tag, but not bad tags like <script>.
346 * This function automatically sets <title> to the same content as <h1> but with all tags removed.
347 * Bad tags that were escaped in <h1> will still be escaped in <title>, and good tags like <i> will be dropped entirely.
348 */
349 public function setPageTitle( $name ) {
350 # change "<script>foo&bar</script>" to "&lt;script&gt;foo&amp;bar&lt;/script&gt;"
351 # but leave "<i>foobar</i>" alone
352 $nameWithTags = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags( $name ) );
353 $this->mPagetitle = $nameWithTags;
354
355 $taction = $this->getPageTitleActionText();
356 if( !empty( $taction ) ) {
357 $name .= ' - '.$taction;
358 }
359
360 # change "<i>foo&amp;bar</i>" to "foo&bar"
361 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer::stripAllTags( $nameWithTags ) ) );
362 }
363
364 public function setTitle( $t ) {
365 $this->mTitle = $t;
366 }
367
368 public function getTitle() {
369 if ( $this->mTitle instanceof Title ) {
370 return $this->mTitle;
371 }
372 else {
373 wfDebug( __METHOD__ . ' called and $mTitle is null. Return $wgTitle for sanity' );
374 global $wgTitle;
375 return $wgTitle;
376 }
377 }
378
379 public function getHTMLTitle() { return $this->mHTMLtitle; }
380 public function getPageTitle() { return $this->mPagetitle; }
381 public function setSubtitle( $str ) { $this->mSubtitle = /*$this->parse(*/$str/*)*/; } // @bug 2514
382 public function appendSubtitle( $str ) { $this->mSubtitle .= /*$this->parse(*/$str/*)*/; } // @bug 2514
383 public function getSubtitle() { return $this->mSubtitle; }
384 public function isArticle() { return $this->mIsarticle; }
385 public function setPrintable() { $this->mPrintable = true; }
386 public function isPrintable() { return $this->mPrintable; }
387 public function getFeedAppendQuery() { return $this->mFeedLinksAppendQuery; }
388 public function disable() { $this->mDoNothing = true; }
389 public function isDisabled() { return $this->mDoNothing; }
390
391 public function setSyndicated( $show = true ) {
392 if ( $show ) {
393 $this->setFeedAppendQuery( false );
394 } else {
395 $this->mFeedLinks = array();
396 }
397 }
398
399 public function setFeedAppendQuery( $val ) {
400 global $wgFeedClasses, $wgAdvertisedFeedTypes;
401
402 $this->mFeedLinks = array();
403
404 foreach ( $wgAdvertisedFeedTypes as $type ) {
405 $query = "feed=$type";
406 if ( is_string( $val ) ) {
407 $query .= '&' . $val;
408 }
409 $this->mFeedLinks[$type] = $this->getTitle()->getLocalURL( $query );
410 }
411 }
412
413 public function addFeedLink( $format, $href ) {
414 $this->mFeedLinks[$format] = $href;
415 }
416
417 public function isSyndicated() { return count($this->mFeedLinks); }
418
419 public function setArticleRelated( $v ) {
420 $this->mIsArticleRelated = $v;
421 if ( !$v ) {
422 $this->mIsarticle = false;
423 }
424 }
425 public function setArticleFlag( $v ) {
426 $this->mIsarticle = $v;
427 if ( $v ) {
428 $this->mIsArticleRelated = $v;
429 }
430 }
431
432 public function isArticleRelated() { return $this->mIsArticleRelated; }
433
434 public function getLanguageLinks() { return $this->mLanguageLinks; }
435 public function addLanguageLinks($newLinkArray) {
436 $this->mLanguageLinks += $newLinkArray;
437 }
438 public function setLanguageLinks($newLinkArray) {
439 $this->mLanguageLinks = $newLinkArray;
440 }
441
442 public function getCategoryLinks() {
443 return $this->mCategoryLinks;
444 }
445
446 public function getCategories() {
447 return $this->mCategories;
448 }
449
450 /**
451 * Add an array of categories, with names in the keys
452 */
453 public function addCategoryLinks( $categories ) {
454 global $wgUser, $wgContLang;
455
456 if ( !is_array( $categories ) || count( $categories ) == 0 ) {
457 return;
458 }
459
460 # Add the links to a LinkBatch
461 $arr = array( NS_CATEGORY => $categories );
462 $lb = new LinkBatch;
463 $lb->setArray( $arr );
464
465 # Fetch existence plus the hiddencat property
466 $dbr = wfGetDB( DB_SLAVE );
467 $pageTable = $dbr->tableName( 'page' );
468 $where = $lb->constructSet( 'page', $dbr );
469 $propsTable = $dbr->tableName( 'page_props' );
470 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, pp_value
471 FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
472 $res = $dbr->query( $sql, __METHOD__ );
473
474 # Add the results to the link cache
475 $lb->addResultToCache( LinkCache::singleton(), $res );
476
477 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
478 $categories = array_combine( array_keys( $categories ),
479 array_fill( 0, count( $categories ), 'normal' ) );
480
481 # Mark hidden categories
482 foreach ( $res as $row ) {
483 if ( isset( $row->pp_value ) ) {
484 $categories[$row->page_title] = 'hidden';
485 }
486 }
487
488 # Add the remaining categories to the skin
489 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks ) ) ) {
490 $sk = $wgUser->getSkin();
491 foreach ( $categories as $category => $type ) {
492 $origcategory = $category;
493 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
494 $wgContLang->findVariantLink( $category, $title, true );
495 if ( $category != $origcategory )
496 if ( array_key_exists( $category, $categories ) )
497 continue;
498 $text = $wgContLang->convertHtml( $title->getText() );
499 $this->mCategories[] = $title->getText();
500 $this->mCategoryLinks[$type][] = $sk->link( $title, $text );
501 }
502 }
503 }
504
505 public function setCategoryLinks($categories) {
506 $this->mCategoryLinks = array();
507 $this->addCategoryLinks($categories);
508 }
509
510 public function suppressQuickbar() { $this->mSuppressQuickbar = true; }
511 public function isQuickbarSuppressed() { return $this->mSuppressQuickbar; }
512
513 public function disallowUserJs() { $this->mAllowUserJs = false; }
514 public function isUserJsAllowed() { return $this->mAllowUserJs; }
515
516 public function prependHTML( $text ) { $this->mBodytext = $text . $this->mBodytext; }
517 public function addHTML( $text ) { $this->mBodytext .= $text; }
518 public function clearHTML() { $this->mBodytext = ''; }
519 public function getHTML() { return $this->mBodytext; }
520 public function debug( $text ) { $this->mDebugtext .= $text; }
521
522 /* @deprecated */
523 public function setParserOptions( $options ) {
524 wfDeprecated( __METHOD__ );
525 return $this->parserOptions( $options );
526 }
527
528 public function parserOptions( $options = null ) {
529 if ( !$this->mParserOptions ) {
530 $this->mParserOptions = new ParserOptions;
531 }
532 return wfSetVar( $this->mParserOptions, $options );
533 }
534
535 /**
536 * Set the revision ID which will be seen by the wiki text parser
537 * for things such as embedded {{REVISIONID}} variable use.
538 * @param mixed $revid an integer, or NULL
539 * @return mixed previous value
540 */
541 public function setRevisionId( $revid ) {
542 $val = is_null( $revid ) ? null : intval( $revid );
543 return wfSetVar( $this->mRevisionId, $val );
544 }
545
546 public function getRevisionId() {
547 return $this->mRevisionId;
548 }
549
550 /**
551 * Convert wikitext to HTML and add it to the buffer
552 * Default assumes that the current page title will
553 * be used.
554 *
555 * @param string $text
556 * @param bool $linestart
557 */
558 public function addWikiText( $text, $linestart = true ) {
559 $title = $this->getTitle(); // Work arround E_STRICT
560 $this->addWikiTextTitle( $text, $title, $linestart );
561 }
562
563 public function addWikiTextWithTitle($text, &$title, $linestart = true) {
564 $this->addWikiTextTitle($text, $title, $linestart);
565 }
566
567 function addWikiTextTitleTidy($text, &$title, $linestart = true) {
568 $this->addWikiTextTitle( $text, $title, $linestart, true );
569 }
570
571 public function addWikiTextTitle($text, &$title, $linestart, $tidy = false) {
572 global $wgParser;
573
574 wfProfileIn( __METHOD__ );
575
576 wfIncrStats( 'pcache_not_possible' );
577
578 $popts = $this->parserOptions();
579 $oldTidy = $popts->setTidy( $tidy );
580
581 $parserOutput = $wgParser->parse( $text, $title, $popts,
582 $linestart, true, $this->mRevisionId );
583
584 $popts->setTidy( $oldTidy );
585
586 $this->addParserOutput( $parserOutput );
587
588 wfProfileOut( __METHOD__ );
589 }
590
591 /**
592 * @todo document
593 * @param ParserOutput object &$parserOutput
594 */
595 public function addParserOutputNoText( &$parserOutput ) {
596 global $wgExemptFromUserRobotsControl, $wgContentNamespaces;
597
598 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
599 $this->addCategoryLinks( $parserOutput->getCategories() );
600 $this->mNewSectionLink = $parserOutput->getNewSection();
601 $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
602
603 $this->mParseWarnings = $parserOutput->getWarnings();
604 if ( $parserOutput->getCacheTime() == -1 ) {
605 $this->enableClientCache( false );
606 }
607 $this->mNoGallery = $parserOutput->getNoGallery();
608 $this->mHeadItems = array_merge( $this->mHeadItems, $parserOutput->getHeadItems() );
609 // Versioning...
610 foreach ( (array)$parserOutput->mTemplateIds as $ns => $dbks ) {
611 if ( isset( $this->mTemplateIds[$ns] ) ) {
612 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
613 } else {
614 $this->mTemplateIds[$ns] = $dbks;
615 }
616 }
617 // Page title
618 $title = $parserOutput->getTitleText();
619 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">\n$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 global $wgUser, $wgRequest, $wgLang;
1602
1603 $this->addMeta( "http:Content-Type", "$wgMimeType; charset={$wgOutputEncoding}" );
1604 if ( $sk->commonPrintStylesheet() ) {
1605 $this->addStyle( 'common/wikiprintable.css', 'print' );
1606 }
1607 $sk->setupUserCss( $this );
1608
1609 $ret = '';
1610
1611 if( $wgMimeType == 'text/xml' || $wgMimeType == 'application/xhtml+xml' || $wgMimeType == 'application/xml' ) {
1612 $ret .= "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?" . ">\n";
1613 }
1614
1615 if ( $this->getHTMLTitle() == '' ) {
1616 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1617 }
1618
1619 $dir = $wgContLang->getDir();
1620
1621 if ( $wgHtml5 ) {
1622 if ( $wgWellFormedXml ) {
1623 # Unknown elements and attributes are okay in XML, but unknown
1624 # named entities are well-formedness errors and will break XML
1625 # parsers. Thus we need a doctype that gives us appropriate
1626 # entity definitions. The HTML5 spec permits four legacy
1627 # doctypes as obsolete but conforming, so let's pick one of
1628 # those, although it makes our pages look like XHTML1 Strict.
1629 # Isn't compatibility great?
1630 $ret .= "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n";
1631 } else {
1632 # Much saner.
1633 $ret .= "<!doctype html>\n";
1634 }
1635 $ret .= "<html lang=\"$wgContLanguageCode\" dir=\"$dir\" ";
1636 if ( $wgHtml5Version ) $ret .= " version=\"$wgHtml5Version\" ";
1637 $ret .= ">\n";
1638 } else {
1639 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\" \"$wgDTD\">\n";
1640 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1641 foreach($wgXhtmlNamespaces as $tag => $ns) {
1642 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1643 }
1644 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" dir=\"$dir\">\n";
1645 }
1646
1647 $ret .= "<head>\n";
1648 $ret .= "<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n";
1649 $ret .= implode( "\n", array(
1650 $this->getHeadLinks(),
1651 $this->buildCssLinks(),
1652 $this->getHeadScripts( $sk ),
1653 $this->getHeadItems(),
1654 ));
1655 if( $sk->usercss ){
1656 $ret .= Html::inlineStyle( $sk->usercss );
1657 }
1658
1659 if ($wgUseTrackbacks && $this->isArticleRelated())
1660 $ret .= $this->getTitle()->trackbackRDF();
1661
1662 $ret .= "</head>\n";
1663
1664 $bodyAttrs = array();
1665
1666 # Crazy edit-on-double-click stuff
1667 $action = $wgRequest->getVal( 'action', 'view' );
1668
1669 if ( $this->getTitle()->getNamespace() != NS_SPECIAL
1670 && !in_array( $action, array( 'edit', 'submit' ) )
1671 && $wgUser->getOption( 'editondblclick' ) ) {
1672 $bodyAttrs['ondblclick'] = "document.location = '" . Xml::escapeJsString( $this->getTitle()->getEditURL() ) . "'";
1673 }
1674
1675 # Class bloat
1676 $bodyAttrs['class'] = "mediawiki $dir";
1677
1678 if ( $wgLang->capitalizeAllNouns() ) {
1679 # A <body> class is probably not the best way to do this . . .
1680 $bodyAttrs['class'] .= ' capitalize-all-nouns';
1681 }
1682 $bodyAttrs['class'] .= ' ns-' . $this->getTitle()->getNamespace();
1683 if ( $this->getTitle()->getNamespace() == NS_SPECIAL ) {
1684 $bodyAttrs['class'] .= ' ns-special';
1685 } elseif ( $this->getTitle()->isTalkPage() ) {
1686 $bodyAttrs['class'] .= ' ns-talk';
1687 } else {
1688 $bodyAttrs['class'] .= ' ns-subject';
1689 }
1690 $bodyAttrs['class'] .= ' ' . Sanitizer::escapeClass( 'page-' . $this->getTitle()->getPrefixedText() );
1691 $bodyAttrs['class'] .= ' skin-' . Sanitizer::escapeClass( $wgUser->getSkin()->getSkinName() );
1692
1693 $ret .= Html::openElement( 'body', $bodyAttrs ) . "\n";
1694
1695 return $ret;
1696 }
1697
1698 /*
1699 * gets the global variables and mScripts
1700 *
1701 * also adds userjs to the end if enabled:
1702 */
1703 function getHeadScripts( Skin $sk ) {
1704 global $wgUser, $wgRequest, $wgJsMimeType, $wgUseSiteJs;
1705 global $wgStylePath, $wgStyleVersion;
1706
1707 $scripts = Skin::makeGlobalVariablesScript( $sk->getSkinName() );
1708 $scripts .= Html::linkedScript( "{$wgStylePath}/common/wikibits.js?$wgStyleVersion" );
1709
1710 //add site JS if enabled:
1711 if( $wgUseSiteJs ) {
1712 $jsCache = $wgUser->isLoggedIn() ? '&smaxage=0' : '';
1713 $this->addScriptFile( Skin::makeUrl( '-',
1714 "action=raw$jsCache&gen=js&useskin=" .
1715 urlencode( $sk->getSkinName() )
1716 )
1717 );
1718 }
1719
1720 //add user js if enabled:
1721 if( $this->isUserJsAllowed() && $wgUser->isLoggedIn() ) {
1722 $action = $wgRequest->getVal( 'action', 'view' );
1723 if( $this->mTitle && $this->mTitle->isJsSubpage() and $sk->userCanPreview( $action ) ) {
1724 # XXX: additional security check/prompt?
1725 $this->addInlineScript( $wgRequest->getText( 'wpTextbox1' ) );
1726 } else {
1727 $userpage = $wgUser->getUserPage();
1728 $userjs = Skin::makeUrl(
1729 $userpage->getPrefixedText() . '/' . $sk->getSkinName() . '.js',
1730 'action=raw&ctype=' . $wgJsMimeType );
1731 $this->addScriptFile( $userjs );
1732 }
1733 }
1734
1735 $scripts .= "\n" . $this->mScripts;
1736 return $scripts;
1737 }
1738
1739 protected function addDefaultMeta() {
1740 global $wgVersion, $wgHtml5;
1741
1742 static $called = false;
1743 if ( $called ) {
1744 # Don't run this twice
1745 return;
1746 }
1747 $called = true;
1748
1749 if ( !$wgHtml5 ) {
1750 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); //bug 15835
1751 }
1752 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
1753
1754 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
1755 if( $p !== 'index,follow' ) {
1756 // http://www.robotstxt.org/wc/meta-user.html
1757 // Only show if it's different from the default robots policy
1758 $this->addMeta( 'robots', $p );
1759 }
1760
1761 if ( count( $this->mKeywords ) > 0 ) {
1762 $strip = array(
1763 "/<.*?" . ">/" => '',
1764 "/_/" => ' '
1765 );
1766 $this->addMeta( 'keywords', preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords ) ) );
1767 }
1768 }
1769
1770 /**
1771 * @return string HTML tag links to be put in the header.
1772 */
1773 public function getHeadLinks() {
1774 global $wgRequest, $wgFeed;
1775
1776 // Ideally this should happen earlier, somewhere. :P
1777 $this->addDefaultMeta();
1778
1779 $tags = array();
1780
1781 foreach ( $this->mMetatags as $tag ) {
1782 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
1783 $a = 'http-equiv';
1784 $tag[0] = substr( $tag[0], 5 );
1785 } else {
1786 $a = 'name';
1787 }
1788 $tags[] = Html::element( 'meta',
1789 array(
1790 $a => $tag[0],
1791 'content' => $tag[1] ) );
1792 }
1793 foreach ( $this->mLinktags as $tag ) {
1794 $tags[] = Html::element( 'link', $tag );
1795 }
1796
1797 if( $wgFeed ) {
1798 foreach( $this->getSyndicationLinks() as $format => $link ) {
1799 # Use the page name for the title (accessed through $wgTitle since
1800 # there's no other way). In principle, this could lead to issues
1801 # with having the same name for different feeds corresponding to
1802 # the same page, but we can't avoid that at this low a level.
1803
1804 $tags[] = $this->feedLink(
1805 $format,
1806 $link,
1807 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
1808 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() ) );
1809 }
1810
1811 # Recent changes feed should appear on every page (except recentchanges,
1812 # that would be redundant). Put it after the per-page feed to avoid
1813 # changing existing behavior. It's still available, probably via a
1814 # menu in your browser. Some sites might have a different feed they'd
1815 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
1816 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
1817 # If so, use it instead.
1818
1819 global $wgOverrideSiteFeed, $wgSitename, $wgFeedClasses, $wgAdvertisedFeedTypes;
1820 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
1821
1822 if ( $wgOverrideSiteFeed ) {
1823 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
1824 $tags[] = $this->feedLink (
1825 $type,
1826 htmlspecialchars( $feedUrl ),
1827 wfMsg( "site-{$type}-feed", $wgSitename ) );
1828 }
1829 } elseif ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
1830 foreach ( $wgAdvertisedFeedTypes as $format ) {
1831 $tags[] = $this->feedLink(
1832 $format,
1833 $rctitle->getLocalURL( "feed={$format}" ),
1834 wfMsg( "site-{$format}-feed", $wgSitename ) ); # For grep: 'site-rss-feed', 'site-atom-feed'.
1835 }
1836 }
1837 }
1838
1839 return implode( "\n", $tags );
1840 }
1841
1842 /**
1843 * Return URLs for each supported syndication format for this page.
1844 * @return array associating format keys with URLs
1845 */
1846 public function getSyndicationLinks() {
1847 return $this->mFeedLinks;
1848 }
1849
1850 /**
1851 * Generate a <link rel/> for an RSS feed.
1852 */
1853 private function feedLink( $type, $url, $text ) {
1854 return Html::element( 'link', array(
1855 'rel' => 'alternate',
1856 'type' => "application/$type+xml",
1857 'title' => $text,
1858 'href' => $url ) );
1859 }
1860
1861 /**
1862 * Add a local or specified stylesheet, with the given media options.
1863 * Meant primarily for internal use...
1864 *
1865 * @param $media -- to specify a media type, 'screen', 'printable', 'handheld' or any.
1866 * @param $conditional -- for IE conditional comments, specifying an IE version
1867 * @param $dir -- set to 'rtl' or 'ltr' for direction-specific sheets
1868 */
1869 public function addStyle( $style, $media='', $condition='', $dir='' ) {
1870 $options = array();
1871 // Even though we expect the media type to be lowercase, but here we
1872 // force it to lowercase to be safe.
1873 if( $media )
1874 $options['media'] = $media;
1875 if( $condition )
1876 $options['condition'] = $condition;
1877 if( $dir )
1878 $options['dir'] = $dir;
1879 $this->styles[$style] = $options;
1880 }
1881
1882 /**
1883 * Adds inline CSS styles
1884 * @param $style_css Mixed: inline CSS
1885 */
1886 public function addInlineStyle( $style_css ){
1887 $this->mScripts .= Html::inlineStyle( $style_css );
1888 }
1889
1890 /**
1891 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
1892 * These will be applied to various media & IE conditionals.
1893 */
1894 public function buildCssLinks() {
1895 $links = array();
1896 foreach( $this->styles as $file => $options ) {
1897 $link = $this->styleLink( $file, $options );
1898 if( $link )
1899 $links[] = $link;
1900 }
1901
1902 return implode( "\n", $links );
1903 }
1904
1905 protected function styleLink( $style, $options ) {
1906 global $wgRequest;
1907
1908 if( isset( $options['dir'] ) ) {
1909 global $wgContLang;
1910 $siteDir = $wgContLang->getDir();
1911 if( $siteDir != $options['dir'] )
1912 return '';
1913 }
1914
1915 if( isset( $options['media'] ) ) {
1916 $media = $this->transformCssMedia( $options['media'] );
1917 if( is_null( $media ) ) {
1918 return '';
1919 }
1920 } else {
1921 $media = 'all';
1922 }
1923
1924 if( substr( $style, 0, 1 ) == '/' ||
1925 substr( $style, 0, 5 ) == 'http:' ||
1926 substr( $style, 0, 6 ) == 'https:' ) {
1927 $url = $style;
1928 } else {
1929 global $wgStylePath, $wgStyleVersion;
1930 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
1931 }
1932
1933 $link = Html::linkedStyle( $url, $media );
1934
1935 if( isset( $options['condition'] ) ) {
1936 $condition = htmlspecialchars( $options['condition'] );
1937 $link = "<!--[if $condition]>$link<![endif]-->";
1938 }
1939 return $link;
1940 }
1941
1942 function transformCssMedia( $media ) {
1943 global $wgRequest, $wgHandheldForIPhone;
1944
1945 // Switch in on-screen display for media testing
1946 $switches = array(
1947 'printable' => 'print',
1948 'handheld' => 'handheld',
1949 );
1950 foreach( $switches as $switch => $targetMedia ) {
1951 if( $wgRequest->getBool( $switch ) ) {
1952 if( $media == $targetMedia ) {
1953 $media = '';
1954 } elseif( $media == 'screen' ) {
1955 return null;
1956 }
1957 }
1958 }
1959
1960 // Expand longer media queries as iPhone doesn't grok 'handheld'
1961 if( $wgHandheldForIPhone ) {
1962 $mediaAliases = array(
1963 'screen' => 'screen and (min-device-width: 481px)',
1964 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
1965 );
1966
1967 if( isset( $mediaAliases[$media] ) ) {
1968 $media = $mediaAliases[$media];
1969 }
1970 }
1971
1972 return $media;
1973 }
1974
1975 /**
1976 * Turn off regular page output and return an error reponse
1977 * for when rate limiting has triggered.
1978 */
1979 public function rateLimited() {
1980
1981 $this->setPageTitle(wfMsg('actionthrottled'));
1982 $this->setRobotPolicy( 'noindex,follow' );
1983 $this->setArticleRelated( false );
1984 $this->enableClientCache( false );
1985 $this->mRedirect = '';
1986 $this->clearHTML();
1987 $this->setStatusCode(503);
1988 $this->addWikiMsg( 'actionthrottledtext' );
1989
1990 $this->returnToMain( null, $this->getTitle() );
1991 }
1992
1993 /**
1994 * Show an "add new section" link?
1995 *
1996 * @return bool
1997 */
1998 public function showNewSectionLink() {
1999 return $this->mNewSectionLink;
2000 }
2001
2002 /**
2003 * Forcibly hide the new section link?
2004 *
2005 * @return bool
2006 */
2007 public function forceHideNewSectionLink() {
2008 return $this->mHideNewSectionLink;
2009 }
2010
2011 /**
2012 * Show a warning about slave lag
2013 *
2014 * If the lag is higher than $wgSlaveLagCritical seconds,
2015 * then the warning is a bit more obvious. If the lag is
2016 * lower than $wgSlaveLagWarning, then no warning is shown.
2017 *
2018 * @param int $lag Slave lag
2019 */
2020 public function showLagWarning( $lag ) {
2021 global $wgSlaveLagWarning, $wgSlaveLagCritical, $wgLang;
2022 if( $lag >= $wgSlaveLagWarning ) {
2023 $message = $lag < $wgSlaveLagCritical
2024 ? 'lag-warn-normal'
2025 : 'lag-warn-high';
2026 $wrap = Html::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2027 $this->wrapWikiMsg( "$wrap\n", array( $message, $wgLang->formatNum( $lag ) ) );
2028 }
2029 }
2030
2031 /**
2032 * Add a wikitext-formatted message to the output.
2033 * This is equivalent to:
2034 *
2035 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2036 */
2037 public function addWikiMsg( /*...*/ ) {
2038 $args = func_get_args();
2039 $name = array_shift( $args );
2040 $this->addWikiMsgArray( $name, $args );
2041 }
2042
2043 /**
2044 * Add a wikitext-formatted message to the output.
2045 * Like addWikiMsg() except the parameters are taken as an array
2046 * instead of a variable argument list.
2047 *
2048 * $options is passed through to wfMsgExt(), see that function for details.
2049 */
2050 public function addWikiMsgArray( $name, $args, $options = array() ) {
2051 $options[] = 'parse';
2052 $text = wfMsgExt( $name, $options, $args );
2053 $this->addHTML( $text );
2054 }
2055
2056 /**
2057 * This function takes a number of message/argument specifications, wraps them in
2058 * some overall structure, and then parses the result and adds it to the output.
2059 *
2060 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
2061 * on. The subsequent arguments may either be strings, in which case they are the
2062 * message names, or arrays, in which case the first element is the message name,
2063 * and subsequent elements are the parameters to that message.
2064 *
2065 * The special named parameter 'options' in a message specification array is passed
2066 * through to the $options parameter of wfMsgExt().
2067 *
2068 * Don't use this for messages that are not in users interface language.
2069 *
2070 * For example:
2071 *
2072 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>", 'some-error' );
2073 *
2074 * Is equivalent to:
2075 *
2076 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . '</div>' );
2077 *
2078 * The newline after opening div is needed in some wikitext. See bug 19226.
2079 */
2080 public function wrapWikiMsg( $wrap /*, ...*/ ) {
2081 $msgSpecs = func_get_args();
2082 array_shift( $msgSpecs );
2083 $msgSpecs = array_values( $msgSpecs );
2084 $s = $wrap;
2085 foreach ( $msgSpecs as $n => $spec ) {
2086 $options = array();
2087 if ( is_array( $spec ) ) {
2088 $args = $spec;
2089 $name = array_shift( $args );
2090 if ( isset( $args['options'] ) ) {
2091 $options = $args['options'];
2092 unset( $args['options'] );
2093 }
2094 } else {
2095 $args = array();
2096 $name = $spec;
2097 }
2098 $s = str_replace( '$' . ( $n + 1 ), wfMsgExt( $name, $options, $args ), $s );
2099 }
2100 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );
2101 }
2102 }