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