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