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