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