7f1639addf3fb3d152b4ebc631abd1e57881adcb
[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(), $mCategories = 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 public function getCategories() {
668 return $this->mCategories;
669 }
670
671 /**
672 * Add an array of categories, with names in the keys
673 */
674 public function addCategoryLinks( $categories ) {
675 global $wgUser, $wgContLang;
676
677 if ( !is_array( $categories ) || count( $categories ) == 0 ) {
678 return;
679 }
680
681 # Add the links to a LinkBatch
682 $arr = array( NS_CATEGORY => $categories );
683 $lb = new LinkBatch;
684 $lb->setArray( $arr );
685
686 # Fetch existence plus the hiddencat property
687 $dbr = wfGetDB( DB_SLAVE );
688 $pageTable = $dbr->tableName( 'page' );
689 $where = $lb->constructSet( 'page', $dbr );
690 $propsTable = $dbr->tableName( 'page_props' );
691 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, pp_value
692 FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
693 $res = $dbr->query( $sql, __METHOD__ );
694
695 # Add the results to the link cache
696 $lb->addResultToCache( LinkCache::singleton(), $res );
697
698 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
699 $categories = array_combine( array_keys( $categories ),
700 array_fill( 0, count( $categories ), 'normal' ) );
701
702 # Mark hidden categories
703 foreach ( $res as $row ) {
704 if ( isset( $row->pp_value ) ) {
705 $categories[$row->page_title] = 'hidden';
706 }
707 }
708
709 # Add the remaining categories to the skin
710 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks ) ) ) {
711 $sk = $wgUser->getSkin();
712 foreach ( $categories as $category => $type ) {
713 $origcategory = $category;
714 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
715 $wgContLang->findVariantLink( $category, $title, true );
716 if ( $category != $origcategory )
717 if ( array_key_exists( $category, $categories ) )
718 continue;
719 $text = $wgContLang->convertHtml( $title->getText() );
720 $this->mCategories[] = $title->getText();
721 $this->mCategoryLinks[$type][] = $sk->link( $title, $text );
722 }
723 }
724 }
725
726 public function setCategoryLinks($categories) {
727 $this->mCategoryLinks = array();
728 $this->addCategoryLinks($categories);
729 }
730
731 public function suppressQuickbar() { $this->mSuppressQuickbar = true; }
732 public function isQuickbarSuppressed() { return $this->mSuppressQuickbar; }
733
734 public function disallowUserJs() { $this->mAllowUserJs = false; }
735 public function isUserJsAllowed() { return $this->mAllowUserJs; }
736
737 public function prependHTML( $text ) { $this->mBodytext = $text . $this->mBodytext; }
738 public function addHTML( $text ) { $this->mBodytext .= $text; }
739 public function clearHTML() { $this->mBodytext = ''; }
740 public function getHTML() { return $this->mBodytext; }
741 public function debug( $text ) { $this->mDebugtext .= $text; }
742
743 /* @deprecated */
744 public function setParserOptions( $options ) {
745 wfDeprecated( __METHOD__ );
746 return $this->parserOptions( $options );
747 }
748
749 public function parserOptions( $options = null ) {
750 if ( !$this->mParserOptions ) {
751 $this->mParserOptions = new ParserOptions;
752 }
753 return wfSetVar( $this->mParserOptions, $options );
754 }
755
756 /**
757 * Set the revision ID which will be seen by the wiki text parser
758 * for things such as embedded {{REVISIONID}} variable use.
759 * @param mixed $revid an integer, or NULL
760 * @return mixed previous value
761 */
762 public function setRevisionId( $revid ) {
763 $val = is_null( $revid ) ? null : intval( $revid );
764 return wfSetVar( $this->mRevisionId, $val );
765 }
766
767 public function getRevisionId() {
768 return $this->mRevisionId;
769 }
770
771 /**
772 * Convert wikitext to HTML and add it to the buffer
773 * Default assumes that the current page title will
774 * be used.
775 *
776 * @param string $text
777 * @param bool $linestart
778 */
779 public function addWikiText( $text, $linestart = true ) {
780 $title = $this->getTitle(); // Work arround E_STRICT
781 $this->addWikiTextTitle( $text, $title, $linestart );
782 }
783
784 public function addWikiTextWithTitle($text, &$title, $linestart = true) {
785 $this->addWikiTextTitle($text, $title, $linestart);
786 }
787
788 function addWikiTextTitleTidy($text, &$title, $linestart = true) {
789 $this->addWikiTextTitle( $text, $title, $linestart, true );
790 }
791
792 public function addWikiTextTitle($text, &$title, $linestart, $tidy = false) {
793 global $wgParser;
794
795 wfProfileIn( __METHOD__ );
796
797 wfIncrStats( 'pcache_not_possible' );
798
799 $popts = $this->parserOptions();
800 $oldTidy = $popts->setTidy( $tidy );
801
802 $parserOutput = $wgParser->parse( $text, $title, $popts,
803 $linestart, true, $this->mRevisionId );
804
805 $popts->setTidy( $oldTidy );
806
807 $this->addParserOutput( $parserOutput );
808
809 wfProfileOut( __METHOD__ );
810 }
811
812 /**
813 * @todo document
814 * @param ParserOutput object &$parserOutput
815 */
816 public function addParserOutputNoText( &$parserOutput ) {
817 global $wgExemptFromUserRobotsControl, $wgContentNamespaces;
818
819 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
820 $this->addCategoryLinks( $parserOutput->getCategories() );
821 $this->mNewSectionLink = $parserOutput->getNewSection();
822 $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
823
824 $this->mParseWarnings = $parserOutput->getWarnings();
825 if ( $parserOutput->getCacheTime() == -1 ) {
826 $this->enableClientCache( false );
827 }
828 $this->mNoGallery = $parserOutput->getNoGallery();
829 $this->mHeadItems = array_merge( $this->mHeadItems, (array)$parserOutput->mHeadItems );
830 // Versioning...
831 foreach ( (array)$parserOutput->mTemplateIds as $ns => $dbks ) {
832 if ( isset( $this->mTemplateIds[$ns] ) ) {
833 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
834 } else {
835 $this->mTemplateIds[$ns] = $dbks;
836 }
837 }
838 // Page title
839 if( ( $dt = $parserOutput->getDisplayTitle() ) !== false )
840 $this->setPageTitle( $dt );
841 else if ( ( $title = $parserOutput->getTitleText() ) != '' )
842 $this->setPageTitle( $title );
843
844 // Hooks registered in the object
845 global $wgParserOutputHooks;
846 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
847 list( $hookName, $data ) = $hookInfo;
848 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
849 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
850 }
851 }
852
853 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
854 }
855
856 /**
857 * @todo document
858 * @param ParserOutput &$parserOutput
859 */
860 function addParserOutput( &$parserOutput ) {
861 $this->addParserOutputNoText( $parserOutput );
862 $text = $parserOutput->getText();
863 wfRunHooks( 'OutputPageBeforeHTML',array( &$this, &$text ) );
864 $this->addHTML( $text );
865 }
866
867 /**
868 * Add wikitext to the buffer, assuming that this is the primary text for a page view
869 * Saves the text into the parser cache if possible.
870 *
871 * @param string $text
872 * @param Article $article
873 * @param bool $cache
874 * @deprecated Use Article::outputWikitext
875 */
876 public function addPrimaryWikiText( $text, $article, $cache = true ) {
877 global $wgParser;
878
879 wfDeprecated( __METHOD__ );
880
881 $popts = $this->parserOptions();
882 $popts->setTidy(true);
883 $parserOutput = $wgParser->parse( $text, $article->mTitle,
884 $popts, true, true, $this->mRevisionId );
885 $popts->setTidy(false);
886 if ( $cache && $article && $parserOutput->getCacheTime() != -1 ) {
887 $parserCache = ParserCache::singleton();
888 $parserCache->save( $parserOutput, $article, $popts);
889 }
890
891 $this->addParserOutput( $parserOutput );
892 }
893
894 /**
895 * @deprecated use addWikiTextTidy()
896 */
897 public function addSecondaryWikiText( $text, $linestart = true ) {
898 wfDeprecated( __METHOD__ );
899 $this->addWikiTextTitleTidy($text, $this->getTitle(), $linestart);
900 }
901
902 /**
903 * Add wikitext with tidy enabled
904 */
905 public function addWikiTextTidy( $text, $linestart = true ) {
906 $title = $this->getTitle();
907 $this->addWikiTextTitleTidy($text, $title, $linestart);
908 }
909
910
911 /**
912 * Add the output of a QuickTemplate to the output buffer
913 *
914 * @param QuickTemplate $template
915 */
916 public function addTemplate( &$template ) {
917 ob_start();
918 $template->execute();
919 $this->addHTML( ob_get_contents() );
920 ob_end_clean();
921 }
922
923 /**
924 * Parse wikitext and return the HTML.
925 *
926 * @param string $text
927 * @param bool $linestart Is this the start of a line?
928 * @param bool $interface ??
929 */
930 public function parse( $text, $linestart = true, $interface = false ) {
931 global $wgParser;
932 if( is_null( $this->getTitle() ) ) {
933 throw new MWException( 'Empty $mTitle in ' . __METHOD__ );
934 }
935 $popts = $this->parserOptions();
936 if ( $interface) { $popts->setInterfaceMessage(true); }
937 $parserOutput = $wgParser->parse( $text, $this->getTitle(), $popts,
938 $linestart, true, $this->mRevisionId );
939 if ( $interface) { $popts->setInterfaceMessage(false); }
940 return $parserOutput->getText();
941 }
942
943 /** Parse wikitext, strip paragraphs, and return the HTML. */
944 public function parseInline( $text, $linestart = true, $interface = false ) {
945 $parsed = $this->parse( $text, $linestart, $interface );
946
947 $m = array();
948 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
949 $parsed = $m[1];
950 }
951
952 return $parsed;
953 }
954
955 /**
956 * @param Article $article
957 * @param User $user
958 *
959 * @deprecated
960 *
961 * @return bool True if successful, else false.
962 */
963 public function tryParserCache( &$article ) {
964 wfDeprecated( __METHOD__ );
965 $parserOutput = ParserCache::singleton()->get( $article, $article->getParserOptions() );
966
967 if ($parserOutput !== false) {
968 $this->addParserOutput( $parserOutput );
969 return true;
970 } else {
971 return false;
972 }
973 }
974
975 /**
976 * @param int $maxage Maximum cache time on the Squid, in seconds.
977 */
978 public function setSquidMaxage( $maxage ) {
979 $this->mSquidMaxage = $maxage;
980 }
981
982 /**
983 * Use enableClientCache(false) to force it to send nocache headers
984 * @param $state ??
985 */
986 public function enableClientCache( $state ) {
987 return wfSetVar( $this->mEnableClientCache, $state );
988 }
989
990 function getCacheVaryCookies() {
991 global $wgCookiePrefix, $wgCacheVaryCookies;
992 static $cookies;
993 if ( $cookies === null ) {
994 $cookies = array_merge(
995 array(
996 "{$wgCookiePrefix}Token",
997 "{$wgCookiePrefix}LoggedOut",
998 session_name()
999 ),
1000 $wgCacheVaryCookies
1001 );
1002 wfRunHooks('GetCacheVaryCookies', array( $this, &$cookies ) );
1003 }
1004 return $cookies;
1005 }
1006
1007 function uncacheableBecauseRequestVars() {
1008 global $wgRequest;
1009 return $wgRequest->getText('useskin', false) === false
1010 && $wgRequest->getText('uselang', false) === false;
1011 }
1012
1013 /**
1014 * Check if the request has a cache-varying cookie header
1015 * If it does, it's very important that we don't allow public caching
1016 */
1017 function haveCacheVaryCookies() {
1018 global $wgRequest;
1019 $cookieHeader = $wgRequest->getHeader( 'cookie' );
1020 if ( $cookieHeader === false ) {
1021 return false;
1022 }
1023 $cvCookies = $this->getCacheVaryCookies();
1024 foreach ( $cvCookies as $cookieName ) {
1025 # Check for a simple string match, like the way squid does it
1026 if ( strpos( $cookieHeader, $cookieName ) ) {
1027 wfDebug( __METHOD__.": found $cookieName\n" );
1028 return true;
1029 }
1030 }
1031 wfDebug( __METHOD__.": no cache-varying cookies found\n" );
1032 return false;
1033 }
1034
1035 /** Get a complete X-Vary-Options header */
1036 public function getXVO() {
1037 $cvCookies = $this->getCacheVaryCookies();
1038 $xvo = 'X-Vary-Options: Accept-Encoding;list-contains=gzip,Cookie;';
1039 $first = true;
1040 foreach ( $cvCookies as $cookieName ) {
1041 if ( $first ) {
1042 $first = false;
1043 } else {
1044 $xvo .= ';';
1045 }
1046 $xvo .= 'string-contains=' . $cookieName;
1047 }
1048 return $xvo;
1049 }
1050
1051 public function sendCacheControl() {
1052 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest, $wgUseXVO;
1053
1054 $response = $wgRequest->response();
1055 if ($wgUseETag && $this->mETag)
1056 $response->header("ETag: $this->mETag");
1057
1058 # don't serve compressed data to clients who can't handle it
1059 # maintain different caches for logged-in users and non-logged in ones
1060 $response->header( 'Vary: Accept-Encoding, Cookie' );
1061
1062 if ( $wgUseXVO ) {
1063 # Add an X-Vary-Options header for Squid with Wikimedia patches
1064 $response->header( $this->getXVO() );
1065 }
1066
1067 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache ) {
1068 if( $wgUseSquid && session_id() == '' &&
1069 ! $this->isPrintable() && $this->mSquidMaxage != 0 && !$this->haveCacheVaryCookies() )
1070 {
1071 if ( $wgUseESI ) {
1072 # We'll purge the proxy cache explicitly, but require end user agents
1073 # to revalidate against the proxy on each visit.
1074 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1075 wfDebug( __METHOD__ . ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1076 # start with a shorter timeout for initial testing
1077 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1078 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage.', content="ESI/1.0"');
1079 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1080 } else {
1081 # We'll purge the proxy cache for anons explicitly, but require end user agents
1082 # to revalidate against the proxy on each visit.
1083 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1084 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1085 wfDebug( __METHOD__ . ": local proxy caching; {$this->mLastModified} **\n", false );
1086 # start with a shorter timeout for initial testing
1087 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1088 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage.', must-revalidate, max-age=0' );
1089 }
1090 } else {
1091 # We do want clients to cache if they can, but they *must* check for updates
1092 # on revisiting the page.
1093 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **\n", false );
1094 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1095 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1096 }
1097 if($this->mLastModified) {
1098 $response->header( "Last-Modified: {$this->mLastModified}" );
1099 }
1100 } else {
1101 wfDebug( __METHOD__ . ": no caching **\n", false );
1102
1103 # In general, the absence of a last modified header should be enough to prevent
1104 # the client from using its cache. We send a few other things just to make sure.
1105 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1106 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1107 $response->header( 'Pragma: no-cache' );
1108 }
1109 wfRunHooks('CacheHeadersAfterSet', array( $this ) );
1110 }
1111
1112 /**
1113 * Finally, all the text has been munged and accumulated into
1114 * the object, let's actually output it:
1115 */
1116 public function output() {
1117 global $wgUser, $wgOutputEncoding, $wgRequest;
1118 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
1119 global $wgUseAjax, $wgAjaxWatch;
1120 global $wgEnableMWSuggest, $wgUniversalEditButton;
1121 global $wgArticle;
1122
1123 if( $this->mDoNothing ){
1124 return;
1125 }
1126 wfProfileIn( __METHOD__ );
1127 if ( '' != $this->mRedirect ) {
1128 # Standards require redirect URLs to be absolute
1129 $this->mRedirect = wfExpandUrl( $this->mRedirect );
1130 if( $this->mRedirectCode == '301') {
1131 if( !$wgDebugRedirects ) {
1132 $wgRequest->response()->header("HTTP/1.1 {$this->mRedirectCode} Moved Permanently");
1133 }
1134 $this->mLastModified = wfTimestamp( TS_RFC2822 );
1135 }
1136 $this->sendCacheControl();
1137
1138 $wgRequest->response()->header("Content-Type: text/html; charset=utf-8");
1139 if( $wgDebugRedirects ) {
1140 $url = htmlspecialchars( $this->mRedirect );
1141 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1142 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1143 print "</body>\n</html>\n";
1144 } else {
1145 $wgRequest->response()->header( 'Location: '.$this->mRedirect );
1146 }
1147 wfProfileOut( __METHOD__ );
1148 return;
1149 }
1150 elseif ( $this->mStatusCode )
1151 {
1152 $statusMessage = array(
1153 100 => 'Continue',
1154 101 => 'Switching Protocols',
1155 102 => 'Processing',
1156 200 => 'OK',
1157 201 => 'Created',
1158 202 => 'Accepted',
1159 203 => 'Non-Authoritative Information',
1160 204 => 'No Content',
1161 205 => 'Reset Content',
1162 206 => 'Partial Content',
1163 207 => 'Multi-Status',
1164 300 => 'Multiple Choices',
1165 301 => 'Moved Permanently',
1166 302 => 'Found',
1167 303 => 'See Other',
1168 304 => 'Not Modified',
1169 305 => 'Use Proxy',
1170 307 => 'Temporary Redirect',
1171 400 => 'Bad Request',
1172 401 => 'Unauthorized',
1173 402 => 'Payment Required',
1174 403 => 'Forbidden',
1175 404 => 'Not Found',
1176 405 => 'Method Not Allowed',
1177 406 => 'Not Acceptable',
1178 407 => 'Proxy Authentication Required',
1179 408 => 'Request Timeout',
1180 409 => 'Conflict',
1181 410 => 'Gone',
1182 411 => 'Length Required',
1183 412 => 'Precondition Failed',
1184 413 => 'Request Entity Too Large',
1185 414 => 'Request-URI Too Large',
1186 415 => 'Unsupported Media Type',
1187 416 => 'Request Range Not Satisfiable',
1188 417 => 'Expectation Failed',
1189 422 => 'Unprocessable Entity',
1190 423 => 'Locked',
1191 424 => 'Failed Dependency',
1192 500 => 'Internal Server Error',
1193 501 => 'Not Implemented',
1194 502 => 'Bad Gateway',
1195 503 => 'Service Unavailable',
1196 504 => 'Gateway Timeout',
1197 505 => 'HTTP Version Not Supported',
1198 507 => 'Insufficient Storage'
1199 );
1200
1201 if ( $statusMessage[$this->mStatusCode] )
1202 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode . ' ' . $statusMessage[$this->mStatusCode] );
1203 }
1204
1205 $sk = $wgUser->getSkin();
1206
1207 // Add our core scripts to output
1208 $this->addCoreScripts2Top();
1209
1210 if ( $wgUseAjax ) {
1211 $this->addScriptFile( 'ajax.js' );
1212
1213 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1214
1215 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1216 $this->addScriptFile( 'ajaxwatch.js' );
1217 }
1218
1219 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ){
1220 $this->addScriptFile( 'mwsuggest.js' );
1221 }
1222 }
1223
1224 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1225 $this->addScriptFile( 'rightclickedit.js' );
1226 }
1227
1228 global $wgUseAJAXCategories, $wgEnableJS2system;
1229 if ($wgUseAJAXCategories && $wgEnableJS2system) {
1230 global $wgAJAXCategoriesNamespaces;
1231
1232 $title = $this->getTitle();
1233
1234 if( empty( $wgAJAXCategoriesNamespaces ) || in_array( $title->getNamespace(), $wgAJAXCategoriesNamespaces ) ) {
1235 $this->addScriptClass( 'ajaxCategories' );
1236 }
1237 }
1238
1239 if( $wgUniversalEditButton ) {
1240 if( isset( $wgArticle ) && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1241 && ( $this->getTitle()->exists() || $this->getTitle()->quickUserCan( 'create' ) ) ) {
1242 // Original UniversalEditButton
1243 $msg = wfMsg('edit');
1244 $this->addLink( array(
1245 'rel' => 'alternate',
1246 'type' => 'application/x-wiki',
1247 'title' => $msg,
1248 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1249 ) );
1250 // Alternate edit link
1251 $this->addLink( array(
1252 'rel' => 'edit',
1253 'title' => $msg,
1254 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1255 ) );
1256 }
1257 }
1258
1259 # Buffer output; final headers may depend on later processing
1260 ob_start();
1261
1262 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1263 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
1264
1265 if ($this->mArticleBodyOnly) {
1266 $this->out($this->mBodytext);
1267 } else {
1268 // Hook that allows last minute changes to the output page, e.g.
1269 // adding of CSS or Javascript by extensions.
1270 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1271
1272 wfProfileIn( 'Output-skin' );
1273 $sk->outputPage( $this );
1274 wfProfileOut( 'Output-skin' );
1275 }
1276
1277 $this->sendCacheControl();
1278 ob_end_flush();
1279 wfProfileOut( __METHOD__ );
1280 }
1281
1282 /**
1283 * Actually output something with print(). Performs an iconv to the
1284 * output encoding, if needed.
1285 * @param string $ins The string to output
1286 */
1287 public function out( $ins ) {
1288 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1289 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1290 $outs = $ins;
1291 } else {
1292 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1293 if ( false === $outs ) { $outs = $ins; }
1294 }
1295 print $outs;
1296 }
1297
1298 /**
1299 * @todo document
1300 */
1301 public static function setEncodings() {
1302 global $wgInputEncoding, $wgOutputEncoding;
1303 global $wgContLang;
1304
1305 $wgInputEncoding = strtolower( $wgInputEncoding );
1306
1307 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
1308 $wgOutputEncoding = strtolower( $wgOutputEncoding );
1309 return;
1310 }
1311 $wgOutputEncoding = $wgInputEncoding;
1312 }
1313
1314 /**
1315 * Deprecated, use wfReportTime() instead.
1316 * @return string
1317 * @deprecated
1318 */
1319 public function reportTime() {
1320 wfDeprecated( __METHOD__ );
1321 $time = wfReportTime();
1322 return $time;
1323 }
1324
1325 /**
1326 * Produce a "user is blocked" page.
1327 *
1328 * @param bool $return Whether to have a "return to $wgTitle" message or not.
1329 * @return nothing
1330 */
1331 function blockedPage( $return = true ) {
1332 global $wgUser, $wgContLang, $wgLang;
1333
1334 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1335 $this->setRobotPolicy( 'noindex,nofollow' );
1336 $this->setArticleRelated( false );
1337
1338 $name = User::whoIs( $wgUser->blockedBy() );
1339 $reason = $wgUser->blockedFor();
1340 if( $reason == '' ) {
1341 $reason = wfMsg( 'blockednoreason' );
1342 }
1343 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW, $wgUser->mBlock->mTimestamp ), true );
1344 $ip = wfGetIP();
1345
1346 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
1347
1348 $blockid = $wgUser->mBlock->mId;
1349
1350 $blockExpiry = $wgUser->mBlock->mExpiry;
1351 if ( $blockExpiry == 'infinity' ) {
1352 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1353 // Search for localization in 'ipboptions'
1354 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1355 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1356 if ( strpos( $option, ":" ) === false )
1357 continue;
1358 list( $show, $value ) = explode( ":", $option );
1359 if ( $value == 'infinite' || $value == 'indefinite' ) {
1360 $blockExpiry = $show;
1361 break;
1362 }
1363 }
1364 } else {
1365 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW, $blockExpiry ), true );
1366 }
1367
1368 if ( $wgUser->mBlock->mAuto ) {
1369 $msg = 'autoblockedtext';
1370 } else {
1371 $msg = 'blockedtext';
1372 }
1373
1374 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1375 * This could be a username, an ip range, or a single ip. */
1376 $intended = $wgUser->mBlock->mAddress;
1377
1378 $this->addWikiMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
1379
1380 # Don't auto-return to special pages
1381 if( $return ) {
1382 $return = $this->getTitle()->getNamespace() > -1 ? $this->getTitle() : null;
1383 $this->returnToMain( null, $return );
1384 }
1385 }
1386
1387 /**
1388 * Output a standard error page
1389 *
1390 * @param string $title Message key for page title
1391 * @param string $msg Message key for page text
1392 * @param array $params Message parameters
1393 */
1394 public function showErrorPage( $title, $msg, $params = array() ) {
1395 if ( $this->getTitle() ) {
1396 $this->mDebugtext .= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1397 }
1398 $this->setPageTitle( wfMsg( $title ) );
1399 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1400 $this->setRobotPolicy( 'noindex,nofollow' );
1401 $this->setArticleRelated( false );
1402 $this->enableClientCache( false );
1403 $this->mRedirect = '';
1404 $this->mBodytext = '';
1405
1406 array_unshift( $params, 'parse' );
1407 array_unshift( $params, $msg );
1408 $this->addHTML( call_user_func_array( 'wfMsgExt', $params ) );
1409
1410 $this->returnToMain();
1411 }
1412
1413 /**
1414 * Output a standard permission error page
1415 *
1416 * @param array $errors Error message keys
1417 */
1418 public function showPermissionsErrorPage( $errors, $action = null )
1419 {
1420 $this->mDebugtext .= 'Original title: ' .
1421 $this->getTitle()->getPrefixedText() . "\n";
1422 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1423 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1424 $this->setRobotPolicy( 'noindex,nofollow' );
1425 $this->setArticleRelated( false );
1426 $this->enableClientCache( false );
1427 $this->mRedirect = '';
1428 $this->mBodytext = '';
1429 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1430 }
1431
1432 /** @deprecated */
1433 public function errorpage( $title, $msg ) {
1434 wfDeprecated( __METHOD__ );
1435 throw new ErrorPageError( $title, $msg );
1436 }
1437
1438 /**
1439 * Display an error page indicating that a given version of MediaWiki is
1440 * required to use it
1441 *
1442 * @param mixed $version The version of MediaWiki needed to use the page
1443 */
1444 public function versionRequired( $version ) {
1445 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1446 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1447 $this->setRobotPolicy( 'noindex,nofollow' );
1448 $this->setArticleRelated( false );
1449 $this->mBodytext = '';
1450
1451 $this->addWikiMsg( 'versionrequiredtext', $version );
1452 $this->returnToMain();
1453 }
1454
1455 /**
1456 * Display an error page noting that a given permission bit is required.
1457 *
1458 * @param string $permission key required
1459 */
1460 public function permissionRequired( $permission ) {
1461 global $wgLang;
1462
1463 $this->setPageTitle( wfMsg( 'badaccess' ) );
1464 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1465 $this->setRobotPolicy( 'noindex,nofollow' );
1466 $this->setArticleRelated( false );
1467 $this->mBodytext = '';
1468
1469 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1470 User::getGroupsWithPermission( $permission ) );
1471 if( $groups ) {
1472 $this->addWikiMsg( 'badaccess-groups',
1473 $wgLang->commaList( $groups ),
1474 count( $groups) );
1475 } else {
1476 $this->addWikiMsg( 'badaccess-group0' );
1477 }
1478 $this->returnToMain();
1479 }
1480
1481 /**
1482 * Use permissionRequired.
1483 * @deprecated
1484 */
1485 public function sysopRequired() {
1486 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
1487 }
1488
1489 /**
1490 * Use permissionRequired.
1491 * @deprecated
1492 */
1493 public function developerRequired() {
1494 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
1495 }
1496
1497 /**
1498 * Produce the stock "please login to use the wiki" page
1499 */
1500 public function loginToUse() {
1501 global $wgUser, $wgContLang;
1502
1503 if( $wgUser->isLoggedIn() ) {
1504 $this->permissionRequired( 'read' );
1505 return;
1506 }
1507
1508 $skin = $wgUser->getSkin();
1509
1510 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1511 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1512 $this->setRobotPolicy( 'noindex,nofollow' );
1513 $this->setArticleFlag( false );
1514
1515 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
1516 $loginLink = $skin->link(
1517 $loginTitle,
1518 wfMsgHtml( 'loginreqlink' ),
1519 array(),
1520 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
1521 array( 'known', 'noclasses' )
1522 );
1523 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1524 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . "-->" );
1525
1526 # Don't return to the main page if the user can't read it
1527 # otherwise we'll end up in a pointless loop
1528 $mainPage = Title::newMainPage();
1529 if( $mainPage->userCanRead() )
1530 $this->returnToMain( null, $mainPage );
1531 }
1532
1533 /** @deprecated */
1534 public function databaseError( $fname, $sql, $error, $errno ) {
1535 throw new MWException( "OutputPage::databaseError is obsolete\n" );
1536 }
1537
1538 /**
1539 * @param array $errors An array of arrays returned by Title::getUserPermissionsErrors
1540 * @return string The wikitext error-messages, formatted into a list.
1541 */
1542 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1543 if ($action == null) {
1544 $text = wfMsgNoTrans( 'permissionserrorstext', count($errors)). "\n\n";
1545 } else {
1546 global $wgLang;
1547 $action_desc = wfMsgNoTrans( "action-$action" );
1548 $text = wfMsgNoTrans( 'permissionserrorstext-withaction', count($errors), $action_desc ) . "\n\n";
1549 }
1550
1551 if (count( $errors ) > 1) {
1552 $text .= '<ul class="permissions-errors">' . "\n";
1553
1554 foreach( $errors as $error )
1555 {
1556 $text .= '<li>';
1557 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1558 $text .= "</li>\n";
1559 }
1560 $text .= '</ul>';
1561 } else {
1562 $text .= "<div class=\"permissions-errors\">\n" . call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) . "\n</div>";
1563 }
1564
1565 return $text;
1566 }
1567
1568 /**
1569 * Display a page stating that the Wiki is in read-only mode,
1570 * and optionally show the source of the page that the user
1571 * was trying to edit. Should only be called (for this
1572 * purpose) after wfReadOnly() has returned true.
1573 *
1574 * For historical reasons, this function is _also_ used to
1575 * show the error message when a user tries to edit a page
1576 * they are not allowed to edit. (Unless it's because they're
1577 * blocked, then we show blockedPage() instead.) In this
1578 * case, the second parameter should be set to true and a list
1579 * of reasons supplied as the third parameter.
1580 *
1581 * @todo Needs to be split into multiple functions.
1582 *
1583 * @param string $source Source code to show (or null).
1584 * @param bool $protected Is this a permissions error?
1585 * @param array $reasons List of reasons for this error, as returned by Title::getUserPermissionsErrors().
1586 */
1587 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1588 global $wgUser;
1589 $skin = $wgUser->getSkin();
1590
1591 $this->setRobotPolicy( 'noindex,nofollow' );
1592 $this->setArticleRelated( false );
1593
1594 // If no reason is given, just supply a default "I can't let you do
1595 // that, Dave" message. Should only occur if called by legacy code.
1596 if ( $protected && empty($reasons) ) {
1597 $reasons[] = array( 'badaccess-group0' );
1598 }
1599
1600 if ( !empty($reasons) ) {
1601 // Permissions error
1602 if( $source ) {
1603 $this->setPageTitle( wfMsg( 'viewsource' ) );
1604 $this->setSubtitle(
1605 wfMsg(
1606 'viewsourcefor',
1607 $skin->link(
1608 $this->getTitle(),
1609 null,
1610 array(),
1611 array(),
1612 array( 'known', 'noclasses' )
1613 )
1614 )
1615 );
1616 } else {
1617 $this->setPageTitle( wfMsg( 'badaccess' ) );
1618 }
1619 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1620 } else {
1621 // Wiki is read only
1622 $this->setPageTitle( wfMsg( 'readonly' ) );
1623 $reason = wfReadOnlyReason();
1624 $this->wrapWikiMsg( '<div class="mw-readonly-error">$1</div>', array( 'readonlytext', $reason ) );
1625 }
1626
1627 // Show source, if supplied
1628 if( is_string( $source ) ) {
1629 $this->addWikiMsg( 'viewsourcetext' );
1630
1631 $params = array(
1632 'id' => 'wpTextbox1',
1633 'name' => 'wpTextbox1',
1634 'cols' => $wgUser->getOption( 'cols' ),
1635 'rows' => $wgUser->getOption( 'rows' ),
1636 'readonly' => 'readonly'
1637 );
1638 $this->addHTML( Html::element( 'textarea', $params, $source ) );
1639
1640 // Show templates used by this article
1641 $skin = $wgUser->getSkin();
1642 $article = new Article( $this->getTitle() );
1643 $this->addHTML( "<div class='templatesUsed'>
1644 {$skin->formatTemplates( $article->getUsedTemplates() )}
1645 </div>
1646 " );
1647 }
1648
1649 # If the title doesn't exist, it's fairly pointless to print a return
1650 # link to it. After all, you just tried editing it and couldn't, so
1651 # what's there to do there?
1652 if( $this->getTitle()->exists() ) {
1653 $this->returnToMain( null, $this->getTitle() );
1654 }
1655 }
1656
1657 /** @deprecated */
1658 public function fatalError( $message ) {
1659 wfDeprecated( __METHOD__ );
1660 throw new FatalError( $message );
1661 }
1662
1663 /** @deprecated */
1664 public function unexpectedValueError( $name, $val ) {
1665 wfDeprecated( __METHOD__ );
1666 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1667 }
1668
1669 /** @deprecated */
1670 public function fileCopyError( $old, $new ) {
1671 wfDeprecated( __METHOD__ );
1672 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1673 }
1674
1675 /** @deprecated */
1676 public function fileRenameError( $old, $new ) {
1677 wfDeprecated( __METHOD__ );
1678 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1679 }
1680
1681 /** @deprecated */
1682 public function fileDeleteError( $name ) {
1683 wfDeprecated( __METHOD__ );
1684 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1685 }
1686
1687 /** @deprecated */
1688 public function fileNotFoundError( $name ) {
1689 wfDeprecated( __METHOD__ );
1690 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1691 }
1692
1693 public function showFatalError( $message ) {
1694 $this->setPageTitle( wfMsg( "internalerror" ) );
1695 $this->setRobotPolicy( "noindex,nofollow" );
1696 $this->setArticleRelated( false );
1697 $this->enableClientCache( false );
1698 $this->mRedirect = '';
1699 $this->mBodytext = $message;
1700 }
1701
1702 public function showUnexpectedValueError( $name, $val ) {
1703 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
1704 }
1705
1706 public function showFileCopyError( $old, $new ) {
1707 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
1708 }
1709
1710 public function showFileRenameError( $old, $new ) {
1711 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
1712 }
1713
1714 public function showFileDeleteError( $name ) {
1715 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
1716 }
1717
1718 public function showFileNotFoundError( $name ) {
1719 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1720 }
1721
1722 /**
1723 * Add a "return to" link pointing to a specified title
1724 *
1725 * @param Title $title Title to link
1726 * @param string $query Query string
1727 */
1728 public function addReturnTo( $title, $query = array() ) {
1729 global $wgUser;
1730 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullUrl() ) );
1731 $link = wfMsgHtml( 'returnto', $wgUser->getSkin()->link(
1732 $title, null, array(), $query ) );
1733 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
1734 }
1735
1736 /**
1737 * Add a "return to" link pointing to a specified title,
1738 * or the title indicated in the request, or else the main page
1739 *
1740 * @param null $unused No longer used
1741 * @param Title $returnto Title to return to
1742 */
1743 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
1744 global $wgRequest;
1745
1746 if ( $returnto == null ) {
1747 $returnto = $wgRequest->getText( 'returnto' );
1748 }
1749
1750 if ( $returntoquery == null ) {
1751 $returntoquery = $wgRequest->getText( 'returntoquery' );
1752 }
1753
1754 if ( '' === $returnto ) {
1755 $returnto = Title::newMainPage();
1756 }
1757
1758 if ( is_object( $returnto ) ) {
1759 $titleObj = $returnto;
1760 } else {
1761 $titleObj = Title::newFromText( $returnto );
1762 }
1763 if ( !is_object( $titleObj ) ) {
1764 $titleObj = Title::newMainPage();
1765 }
1766
1767 $this->addReturnTo( $titleObj, $returntoquery );
1768 }
1769
1770 /**
1771 * @return string The doctype, opening <html>, and head element.
1772 *
1773 * @param $sk Skin The given Skin
1774 */
1775 public function headElement( Skin $sk, $includeStyle = true ) {
1776 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1777 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces, $wgHtml5Version;
1778 global $wgContLang, $wgUseTrackbacks, $wgStyleVersion, $wgEnableScriptLoader, $wgHtml5;
1779
1780 $this->addMeta( "http:Content-Type", "$wgMimeType; charset={$wgOutputEncoding}" );
1781 if ( $sk->commonPrintStylesheet() ) {
1782 $this->addStyle( 'common/wikiprintable.css', 'print' );
1783 }
1784 $sk->setupUserCss( $this );
1785
1786 $ret = '';
1787
1788 if( $wgMimeType == 'text/xml' || $wgMimeType == 'application/xhtml+xml' || $wgMimeType == 'application/xml' ) {
1789 $ret .= "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?" . ">\n";
1790 }
1791
1792 if ( '' == $this->getHTMLTitle() ) {
1793 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1794 }
1795
1796 $dir = $wgContLang->getDir();
1797
1798 if ( $wgHtml5 ) {
1799 $ret .= "<!DOCTYPE html>\n";
1800 $ret .= "<html lang=\"$wgContLanguageCode\" dir=\"$dir\" ";
1801 if ($wgHtml5Version) $ret .= " version=\"$wgHtml5Version\" ";
1802 $ret .= ">\n";
1803 } else {
1804 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\" \"$wgDTD\">\n";
1805 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1806 foreach($wgXhtmlNamespaces as $tag => $ns) {
1807 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1808 }
1809 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" dir=\"$dir\">\n";
1810 }
1811
1812 $ret .= "<head>\n";
1813 $ret .= "<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n";
1814 $ret .= implode( "\n", array(
1815 $this->getHeadLinks(),
1816 $this->buildCssLinks(),
1817 $this->getHeadScripts( $sk ),
1818 $this->getHeadItems(),
1819 ));
1820 if( $sk->usercss ){
1821 $ret .= Html::inlineStyle( $sk->usercss );
1822 }
1823
1824 if( $wgEnableScriptLoader )
1825 $ret .= $this->getScriptLoaderJs();
1826
1827 if ($wgUseTrackbacks && $this->isArticleRelated())
1828 $ret .= $this->getTitle()->trackbackRDF();
1829
1830 $ret .= "</head>\n";
1831 return $ret;
1832 }
1833
1834 /*
1835 * gets the global variables and mScripts
1836 *
1837 * also adds userjs to the end if enabled:
1838 */
1839 function getHeadScripts( Skin $sk ) {
1840 global $wgUser, $wgRequest, $wgJsMimeType, $wgUseSiteJs;
1841
1842 $vars = Skin::makeGlobalVariablesScript( $sk->getSkinName() );
1843
1844 //add site JS if enabled:
1845 if( $wgUseSiteJs ) {
1846 $jsCache = $wgUser->isLoggedIn() ? '&smaxage=0' : '';
1847 $this->addScriptFile( Skin::makeUrl( '-',
1848 "action=raw$jsCache&gen=js&useskin=" .
1849 urlencode( $sk->getSkinName() )
1850 )
1851 );
1852 }
1853
1854 //add user js if enabled:
1855 if( $this->isUserJsAllowed() && $wgUser->isLoggedIn() ) {
1856 $action = $wgRequest->getVal( 'action', 'view' );
1857 if( $this->mTitle && $this->mTitle->isJsSubpage() and $sk->userCanPreview( $action ) ) {
1858 # XXX: additional security check/prompt?
1859 $this->addInlineScript( $wgRequest->getText( 'wpTextbox1' ) );
1860 } else {
1861 $userpage = $wgUser->getUserPage();
1862 $userjs = Skin::makeUrl(
1863 $userpage->getPrefixedText() . '/' . $sk->getSkinName() . '.js',
1864 'action=raw&ctype=' . $wgJsMimeType );
1865 $this->addScriptFile( $userjs );
1866 }
1867 }
1868
1869 return $vars . "\n" . $this->mScripts;
1870 }
1871
1872 protected function addDefaultMeta() {
1873 global $wgVersion, $wgHtml5;
1874
1875 static $called = false;
1876 if ( $called ) {
1877 # Don't run this twice
1878 return;
1879 }
1880 $called = true;
1881
1882 if ( !$wgHtml5 ) {
1883 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); //bug 15835
1884 }
1885 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
1886
1887 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
1888 if( $p !== 'index,follow' ) {
1889 // http://www.robotstxt.org/wc/meta-user.html
1890 // Only show if it's different from the default robots policy
1891 $this->addMeta( 'robots', $p );
1892 }
1893
1894 if ( count( $this->mKeywords ) > 0 ) {
1895 $strip = array(
1896 "/<.*?" . ">/" => '',
1897 "/_/" => ' '
1898 );
1899 $this->addMeta( 'keywords', preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords ) ) );
1900 }
1901 }
1902
1903 /**
1904 * @return string HTML tag links to be put in the header.
1905 */
1906 public function getHeadLinks() {
1907 global $wgRequest, $wgFeed;
1908
1909 // Ideally this should happen earlier, somewhere. :P
1910 $this->addDefaultMeta();
1911
1912 $tags = array();
1913
1914 foreach ( $this->mMetatags as $tag ) {
1915 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
1916 $a = 'http-equiv';
1917 $tag[0] = substr( $tag[0], 5 );
1918 } else {
1919 $a = 'name';
1920 }
1921 $tags[] = Html::element( 'meta',
1922 array(
1923 $a => $tag[0],
1924 'content' => $tag[1] ) );
1925 }
1926 foreach ( $this->mLinktags as $tag ) {
1927 $tags[] = Html::element( 'link', $tag );
1928 }
1929
1930 if( $wgFeed ) {
1931 foreach( $this->getSyndicationLinks() as $format => $link ) {
1932 # Use the page name for the title (accessed through $wgTitle since
1933 # there's no other way). In principle, this could lead to issues
1934 # with having the same name for different feeds corresponding to
1935 # the same page, but we can't avoid that at this low a level.
1936
1937 $tags[] = $this->feedLink(
1938 $format,
1939 $link,
1940 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() ) ); # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
1941 }
1942
1943 # Recent changes feed should appear on every page (except recentchanges,
1944 # that would be redundant). Put it after the per-page feed to avoid
1945 # changing existing behavior. It's still available, probably via a
1946 # menu in your browser. Some sites might have a different feed they'd
1947 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
1948 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
1949 # If so, use it instead.
1950
1951 global $wgOverrideSiteFeed, $wgSitename, $wgFeedClasses;
1952 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
1953
1954 if ( $wgOverrideSiteFeed ) {
1955 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
1956 $tags[] = $this->feedLink (
1957 $type,
1958 htmlspecialchars( $feedUrl ),
1959 wfMsg( "site-{$type}-feed", $wgSitename ) );
1960 }
1961 }
1962 else if ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
1963 foreach( $wgFeedClasses as $format => $class ) {
1964 $tags[] = $this->feedLink(
1965 $format,
1966 $rctitle->getLocalURL( "feed={$format}" ),
1967 wfMsg( "site-{$format}-feed", $wgSitename ) ); # For grep: 'site-rss-feed', 'site-atom-feed'.
1968 }
1969 }
1970 }
1971
1972 return implode( "\n", $tags );
1973 }
1974
1975 /**
1976 * Return URLs for each supported syndication format for this page.
1977 * @return array associating format keys with URLs
1978 */
1979 public function getSyndicationLinks() {
1980 return $this->mFeedLinks;
1981 }
1982
1983 /**
1984 * Generate a <link rel/> for an RSS feed.
1985 */
1986 private function feedLink( $type, $url, $text ) {
1987 return Html::element( 'link', array(
1988 'rel' => 'alternate',
1989 'type' => "application/$type+xml",
1990 'title' => $text,
1991 'href' => $url ) );
1992 }
1993
1994 /**
1995 * Add a local or specified stylesheet, with the given media options.
1996 * Meant primarily for internal use...
1997 *
1998 * @param $media -- to specify a media type, 'screen', 'printable', 'handheld' or any.
1999 * @param $conditional -- for IE conditional comments, specifying an IE version
2000 * @param $dir -- set to 'rtl' or 'ltr' for direction-specific sheets
2001 */
2002 public function addStyle( $style, $media='', $condition='', $dir='' ) {
2003 $options = array();
2004 // Even though we expect the media type to be lowercase, but here we
2005 // force it to lowercase to be safe.
2006 if( $media )
2007 $options['media'] = $media;
2008 if( $condition )
2009 $options['condition'] = $condition;
2010 if( $dir )
2011 $options['dir'] = $dir;
2012 $this->styles[$style] = $options;
2013 }
2014
2015 /**
2016 * Adds inline CSS styles
2017 * @param $style_css Mixed: inline CSS
2018 */
2019 public function addInlineStyle( $style_css ){
2020 $this->mScripts .= Html::inlineStyle( $style_css );
2021 }
2022
2023 /**
2024 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
2025 * These will be applied to various media & IE conditionals.
2026 */
2027 public function buildCssLinks() {
2028 $links = array();
2029 foreach( $this->styles as $file => $options ) {
2030 $link = $this->styleLink( $file, $options );
2031 if( $link )
2032 $links[] = $link;
2033 }
2034
2035 return implode( "\n", $links );
2036 }
2037
2038 protected function styleLink( $style, $options ) {
2039 global $wgRequest;
2040
2041 if( isset( $options['dir'] ) ) {
2042 global $wgContLang;
2043 $siteDir = $wgContLang->getDir();
2044 if( $siteDir != $options['dir'] )
2045 return '';
2046 }
2047
2048 if( isset( $options['media'] ) ) {
2049 $media = $this->transformCssMedia( $options['media'] );
2050 if( is_null( $media ) ) {
2051 return '';
2052 }
2053 } else {
2054 $media = 'all';
2055 }
2056
2057 if( substr( $style, 0, 1 ) == '/' ||
2058 substr( $style, 0, 5 ) == 'http:' ||
2059 substr( $style, 0, 6 ) == 'https:' ) {
2060 $url = $style;
2061 } else {
2062 global $wgStylePath, $wgStyleVersion;
2063 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
2064 }
2065
2066 $link = Html::linkedStyle( $url, $media );
2067
2068 if( isset( $options['condition'] ) ) {
2069 $condition = htmlspecialchars( $options['condition'] );
2070 $link = "<!--[if $condition]>$link<![endif]-->";
2071 }
2072 return $link;
2073 }
2074
2075 function transformCssMedia( $media ) {
2076 global $wgRequest, $wgHandheldForIPhone;
2077
2078 // Switch in on-screen display for media testing
2079 $switches = array(
2080 'printable' => 'print',
2081 'handheld' => 'handheld',
2082 );
2083 foreach( $switches as $switch => $targetMedia ) {
2084 if( $wgRequest->getBool( $switch ) ) {
2085 if( $media == $targetMedia ) {
2086 $media = '';
2087 } elseif( $media == 'screen' ) {
2088 return null;
2089 }
2090 }
2091 }
2092
2093 // Expand longer media queries as iPhone doesn't grok 'handheld'
2094 if( $wgHandheldForIPhone ) {
2095 $mediaAliases = array(
2096 'screen' => 'screen and (min-device-width: 481px)',
2097 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
2098 );
2099
2100 if( isset( $mediaAliases[$media] ) ) {
2101 $media = $mediaAliases[$media];
2102 }
2103 }
2104
2105 return $media;
2106 }
2107
2108 /**
2109 * Turn off regular page output and return an error reponse
2110 * for when rate limiting has triggered.
2111 */
2112 public function rateLimited() {
2113
2114 $this->setPageTitle(wfMsg('actionthrottled'));
2115 $this->setRobotPolicy( 'noindex,follow' );
2116 $this->setArticleRelated( false );
2117 $this->enableClientCache( false );
2118 $this->mRedirect = '';
2119 $this->clearHTML();
2120 $this->setStatusCode(503);
2121 $this->addWikiMsg( 'actionthrottledtext' );
2122
2123 $this->returnToMain( null, $this->getTitle() );
2124 }
2125
2126 /**
2127 * Show an "add new section" link?
2128 *
2129 * @return bool
2130 */
2131 public function showNewSectionLink() {
2132 return $this->mNewSectionLink;
2133 }
2134
2135 /**
2136 * Forcibly hide the new section link?
2137 *
2138 * @return bool
2139 */
2140 public function forceHideNewSectionLink() {
2141 return $this->mHideNewSectionLink;
2142 }
2143
2144 /**
2145 * Show a warning about slave lag
2146 *
2147 * If the lag is higher than $wgSlaveLagCritical seconds,
2148 * then the warning is a bit more obvious. If the lag is
2149 * lower than $wgSlaveLagWarning, then no warning is shown.
2150 *
2151 * @param int $lag Slave lag
2152 */
2153 public function showLagWarning( $lag ) {
2154 global $wgSlaveLagWarning, $wgSlaveLagCritical, $wgLang;
2155 if( $lag >= $wgSlaveLagWarning ) {
2156 $message = $lag < $wgSlaveLagCritical
2157 ? 'lag-warn-normal'
2158 : 'lag-warn-high';
2159 $wrap = Html::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2160 $this->wrapWikiMsg( "$wrap\n", array( $message, $wgLang->formatNum( $lag ) ) );
2161 }
2162 }
2163
2164 /**
2165 * Add a wikitext-formatted message to the output.
2166 * This is equivalent to:
2167 *
2168 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2169 */
2170 public function addWikiMsg( /*...*/ ) {
2171 $args = func_get_args();
2172 $name = array_shift( $args );
2173 $this->addWikiMsgArray( $name, $args );
2174 }
2175
2176 /**
2177 * Add a wikitext-formatted message to the output.
2178 * Like addWikiMsg() except the parameters are taken as an array
2179 * instead of a variable argument list.
2180 *
2181 * $options is passed through to wfMsgExt(), see that function for details.
2182 */
2183 public function addWikiMsgArray( $name, $args, $options = array() ) {
2184 $options[] = 'parse';
2185 $text = wfMsgExt( $name, $options, $args );
2186 $this->addHTML( $text );
2187 }
2188
2189 /**
2190 * This function takes a number of message/argument specifications, wraps them in
2191 * some overall structure, and then parses the result and adds it to the output.
2192 *
2193 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
2194 * on. The subsequent arguments may either be strings, in which case they are the
2195 * message names, or arrays, in which case the first element is the message name,
2196 * and subsequent elements are the parameters to that message.
2197 *
2198 * The special named parameter 'options' in a message specification array is passed
2199 * through to the $options parameter of wfMsgExt().
2200 *
2201 * Don't use this for messages that are not in users interface language.
2202 *
2203 * For example:
2204 *
2205 * $wgOut->wrapWikiMsg( '<div class="error">$1</div>', 'some-error' );
2206 *
2207 * Is equivalent to:
2208 *
2209 * $wgOut->addWikiText( '<div class="error">' . wfMsgNoTrans( 'some-error' ) . '</div>' );
2210 */
2211 public function wrapWikiMsg( $wrap /*, ...*/ ) {
2212 $msgSpecs = func_get_args();
2213 array_shift( $msgSpecs );
2214 $msgSpecs = array_values( $msgSpecs );
2215 $s = $wrap;
2216 foreach ( $msgSpecs as $n => $spec ) {
2217 $options = array();
2218 if ( is_array( $spec ) ) {
2219 $args = $spec;
2220 $name = array_shift( $args );
2221 if ( isset( $args['options'] ) ) {
2222 $options = $args['options'];
2223 unset( $args['options'] );
2224 }
2225 } else {
2226 $args = array();
2227 $name = $spec;
2228 }
2229 $s = str_replace( '$' . ( $n + 1 ), wfMsgExt( $name, $options, $args ), $s );
2230 }
2231 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );
2232 }
2233 }