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