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