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