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