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