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