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