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