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