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