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