* (bug 20631) Preview of personal JavaScript and CSS pages now works again
[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 $wgUseSiteJs, $wgUser, $wgJsMimeType;
176 // @todo We should deprecate wikibits in favor of mv_embed 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
199 $sk = $wgUser->getSkin();
200 //add site js:
201 if( $wgUseSiteJs ) {
202 $jsCache = $wgUser->isLoggedIn() ? '&smaxage=0' : '';
203 $this->addScriptFile( Skin::makeUrl( '-',
204 "action=raw$jsCache&gen=js&useskin=" .
205 urlencode( $sk->getSkinName() )
206 )
207 );
208 }
209 //now re-append any scripts that got added prior to the addCoreScripts2Top call
210 $this->mScripts = $this->mScripts . $postScripts;
211 }
212
213 /**
214 * @param string $js_class Name of the JavaScript class
215 * @return boolean False if the class wasn't found, true on success
216 */
217 function addScriptClass( $js_class ){
218 global $wgDebugJavaScript, $wgJSAutoloadLocalClasses, $wgJSAutoloadClasses,
219 $wgEnableScriptLoader, $wgStyleVersion, $wgScriptPath, $wgEnableJS2system;
220
221 $path = jsScriptLoader::getJsPathFromClass( $js_class );
222 if( $path !== false ){
223 if( $wgEnableScriptLoader ) {
224 // Register it with the script loader
225 if( !in_array( $js_class, $this->mScriptLoaderClassList ) ) {
226 $this->mScriptLoaderClassList[] = $js_class;
227 }
228 } else {
229 // Source the script directly
230 $path = $wgScriptPath . '/' . $path;
231 $urlAppend = ( $wgDebugJavaScript ) ? time() : $this->getURIDparam( $js_class );
232 $this->addScript( Html::linkedScript( "$path?$urlAppend" ) );
233
234 //merge in language text (if js2 is on and we have loadGM function)
235 if( $wgEnableJS2system ){
236 $inlineMsg = jsScriptLoader::getLocalizedMsgsFromClass( $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) );
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, $wgScriptModifiedCheck;
274 if( $wgDebugJavaScript ) {
275 return 'urid=' . time();
276 } else {
277 //support single class_name attr
278 if( gettype( $classAry) == 'string' ){
279 $classAry = array( $classAry );
280 }
281 $ftime = $frev = 0;
282 foreach( $classAry as $class ) {
283 if( $wgScriptModifiedCheck ) {
284 $js_path = jsScriptLoader::getJsPathFromClass( $class );
285 if( $js_path ) {
286 $cur_ftime = filemtime ( $IP ."/". $js_path );
287 if( $cur_ftime > $ftime )
288 $ftime = $cur_ftime;
289 }
290 }
291 // Add the latest revision ID if the class set includes a WT (wiki title)
292 if( substr($class, 0, 3) == 'WT:'){
293 $title_str = substr($class, 3);
294 $t = Title::newFromText( $title_str );
295 if( $t && $t->exists() ) {
296 if( $t->getLatestRevID() > $frev )
297 $frev = $t->getLatestRevID();
298 }
299 }
300 }
301 //build the actual unique request id:
302 $urid = "urid={$wgStyleVersion}";
303
304 // Add the file modification time if set
305 if( $ftime != 0 )
306 $urid .= "_" . $ftime;
307
308 //add the wiki rev id if set
309 if( $frev != 0 )
310 $urid.= "_" . $frev;
311
312 return $urid;
313 }
314 }
315
316 /**
317 * Given a script path, get the JS class name, or false if no such path is registered.
318 * @param $path string
319 */
320 function getJsClassFromPath( $path ) {
321 global $wgJSAutoloadClasses, $wgJSAutoloadLocalClasses, $wgScriptPath;
322
323 $scriptLoaderPaths = array_merge( $wgJSAutoloadClasses, $wgJSAutoloadLocalClasses );
324 foreach( $scriptLoaderPaths as $js_class => $js_path ) {
325 $js_path = "{$wgScriptPath}/{$js_path}";
326 if( $path == $js_path )
327 return $js_class;
328 }
329 return false;
330 }
331
332 /**
333 * Add a self-contained script tag with the given contents
334 * @param string $script JavaScript text, no <script> tags
335 */
336 function addInlineScript( $script ) {
337 $this->mScripts .= Html::inlineScript( "\n$script\n" ) . "\n";
338 }
339
340 /**
341 * Get all registered JS and CSS tags for the header.
342 */
343 function getScript() {
344 global $wgEnableScriptLoader;
345 if( $wgEnableScriptLoader ){
346 return $this->mScripts . "\n" . $this->getScriptLoaderJs() . $this->getHeadItems();
347 } else {
348 return $this->mScripts . $this->getHeadItems();
349 }
350 }
351
352 function getHeadItems() {
353 $s = '';
354 foreach ( $this->mHeadItems as $item ) {
355 $s .= $item;
356 }
357 return $s;
358 }
359
360 function addHeadItem( $name, $value ) {
361 $this->mHeadItems[$name] = $value;
362 }
363
364 function hasHeadItem( $name ) {
365 return isset( $this->mHeadItems[$name] );
366 }
367
368 function setETag($tag) { $this->mETag = $tag; }
369 function setArticleBodyOnly($only) { $this->mArticleBodyOnly = $only; }
370 function getArticleBodyOnly() { return $this->mArticleBodyOnly; }
371
372 function addLink( $linkarr ) {
373 # $linkarr should be an associative array of attributes. We'll escape on output.
374 array_push( $this->mLinktags, $linkarr );
375 }
376
377 # Get all links added by extensions
378 function getExtStyle() {
379 return $this->mExtStyles;
380 }
381
382 function addMetadataLink( $linkarr ) {
383 # note: buggy CC software only reads first "meta" link
384 static $haveMeta = false;
385 $linkarr['rel'] = ($haveMeta) ? 'alternate meta' : 'meta';
386 $this->addLink( $linkarr );
387 $haveMeta = true;
388 }
389
390 /**
391 * checkLastModified tells the client to use the client-cached page if
392 * possible. If sucessful, the OutputPage is disabled so that
393 * any future call to OutputPage->output() have no effect.
394 *
395 * Side effect: sets mLastModified for Last-Modified header
396 *
397 * @return bool True iff cache-ok headers was sent.
398 */
399 function checkLastModified( $timestamp ) {
400 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
401
402 if ( !$timestamp || $timestamp == '19700101000000' ) {
403 wfDebug( __METHOD__ . ": CACHE DISABLED, NO TIMESTAMP\n" );
404 return false;
405 }
406 if( !$wgCachePages ) {
407 wfDebug( __METHOD__ . ": CACHE DISABLED\n", false );
408 return false;
409 }
410 if( $wgUser->getOption( 'nocache' ) ) {
411 wfDebug( __METHOD__ . ": USER DISABLED CACHE\n", false );
412 return false;
413 }
414
415 $timestamp = wfTimestamp( TS_MW, $timestamp );
416 $modifiedTimes = array(
417 'page' => $timestamp,
418 'user' => $wgUser->getTouched(),
419 'epoch' => $wgCacheEpoch
420 );
421 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
422
423 $maxModified = max( $modifiedTimes );
424 $this->mLastModified = wfTimestamp( TS_RFC2822, $maxModified );
425
426 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
427 wfDebug( __METHOD__ . ": client did not send If-Modified-Since header\n", false );
428 return false;
429 }
430
431 # Make debug info
432 $info = '';
433 foreach ( $modifiedTimes as $name => $value ) {
434 if ( $info !== '' ) {
435 $info .= ', ';
436 }
437 $info .= "$name=" . wfTimestamp( TS_ISO_8601, $value );
438 }
439
440 # IE sends sizes after the date like this:
441 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
442 # this breaks strtotime().
443 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
444
445 wfSuppressWarnings(); // E_STRICT system time bitching
446 $clientHeaderTime = strtotime( $clientHeader );
447 wfRestoreWarnings();
448 if ( !$clientHeaderTime ) {
449 wfDebug( __METHOD__ . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
450 return false;
451 }
452 $clientHeaderTime = wfTimestamp( TS_MW, $clientHeaderTime );
453
454 wfDebug( __METHOD__ . ": client sent If-Modified-Since: " .
455 wfTimestamp( TS_ISO_8601, $clientHeaderTime ) . "\n", false );
456 wfDebug( __METHOD__ . ": effective Last-Modified: " .
457 wfTimestamp( TS_ISO_8601, $maxModified ) . "\n", false );
458 if( $clientHeaderTime < $maxModified ) {
459 wfDebug( __METHOD__ . ": STALE, $info\n", false );
460 return false;
461 }
462
463 # Not modified
464 # Give a 304 response code and disable body output
465 wfDebug( __METHOD__ . ": NOT MODIFIED, $info\n", false );
466 ini_set('zlib.output_compression', 0);
467 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
468 $this->sendCacheControl();
469 $this->disable();
470
471 // Don't output a compressed blob when using ob_gzhandler;
472 // it's technically against HTTP spec and seems to confuse
473 // Firefox when the response gets split over two packets.
474 wfClearOutputBuffers();
475
476 return true;
477 }
478
479 function setPageTitleActionText( $text ) {
480 $this->mPageTitleActionText = $text;
481 }
482
483 function getPageTitleActionText () {
484 if ( isset( $this->mPageTitleActionText ) ) {
485 return $this->mPageTitleActionText;
486 }
487 }
488
489 /**
490 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
491 *
492 * @param $policy string The literal string to output as the contents of
493 * the meta tag. Will be parsed according to the spec and output in
494 * standardized form.
495 * @return null
496 */
497 public function setRobotPolicy( $policy ) {
498 $policy = Article::formatRobotPolicy( $policy );
499
500 if( isset( $policy['index'] ) ){
501 $this->setIndexPolicy( $policy['index'] );
502 }
503 if( isset( $policy['follow'] ) ){
504 $this->setFollowPolicy( $policy['follow'] );
505 }
506 }
507
508 /**
509 * Set the index policy for the page, but leave the follow policy un-
510 * touched.
511 *
512 * @param $policy string Either 'index' or 'noindex'.
513 * @return null
514 */
515 public function setIndexPolicy( $policy ) {
516 $policy = trim( $policy );
517 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
518 $this->mIndexPolicy = $policy;
519 }
520 }
521
522 /**
523 * Set the follow policy for the page, but leave the index policy un-
524 * touched.
525 *
526 * @param $policy string Either 'follow' or 'nofollow'.
527 * @return null
528 */
529 public function setFollowPolicy( $policy ) {
530 $policy = trim( $policy );
531 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
532 $this->mFollowPolicy = $policy;
533 }
534 }
535
536 /**
537 * "HTML title" means the contents of <title>. It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
538 */
539 public function setHTMLTitle( $name ) {
540 $this->mHTMLtitle = $name;
541 }
542
543 /**
544 * "Page title" means the contents of <h1>. It is stored as a valid HTML fragment.
545 * This function allows good tags like <sup> in the <h1> tag, but not bad tags like <script>.
546 * This function automatically sets <title> to the same content as <h1> but with all tags removed.
547 * Bad tags that were escaped in <h1> will still be escaped in <title>, and good tags like <i> will be dropped entirely.
548 */
549 public function setPageTitle( $name ) {
550 global $wgContLang;
551 $name = $wgContLang->convert( $name, true );
552 # change "<script>foo&bar</script>" to "&lt;script&gt;foo&amp;bar&lt;/script&gt;"
553 # but leave "<i>foobar</i>" alone
554 $nameWithTags = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags( $name ) );
555 $this->mPagetitle = $nameWithTags;
556
557 $taction = $this->getPageTitleActionText();
558 if( !empty( $taction ) ) {
559 $name .= ' - '.$taction;
560 }
561
562 # change "<i>foo&amp;bar</i>" to "foo&bar"
563 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer::stripAllTags( $nameWithTags ) ) );
564 }
565
566 public function setTitle( $t ) {
567 $this->mTitle = $t;
568 }
569
570 public function getTitle() {
571 if ( $this->mTitle instanceof Title ) {
572 return $this->mTitle;
573 }
574 else {
575 wfDebug( __METHOD__ . ' called and $mTitle is null. Return $wgTitle for sanity' );
576 global $wgTitle;
577 return $wgTitle;
578 }
579 }
580
581 public function getHTMLTitle() { return $this->mHTMLtitle; }
582 public function getPageTitle() { return $this->mPagetitle; }
583 public function setSubtitle( $str ) { $this->mSubtitle = /*$this->parse(*/$str/*)*/; } // @bug 2514
584 public function appendSubtitle( $str ) { $this->mSubtitle .= /*$this->parse(*/$str/*)*/; } // @bug 2514
585 public function getSubtitle() { return $this->mSubtitle; }
586 public function isArticle() { return $this->mIsarticle; }
587 public function setPrintable() { $this->mPrintable = true; }
588 public function isPrintable() { return $this->mPrintable; }
589 public function setSyndicated( $show = true ) { $this->mShowFeedLinks = $show; }
590 public function isSyndicated() { return $this->mShowFeedLinks; }
591 public function setFeedAppendQuery( $val ) { $this->mFeedLinksAppendQuery = $val; }
592 public function getFeedAppendQuery() { return $this->mFeedLinksAppendQuery; }
593 public function setOnloadHandler( $js ) { $this->mOnloadHandler = $js; }
594 public function getOnloadHandler() { return $this->mOnloadHandler; }
595 public function disable() { $this->mDoNothing = true; }
596 public function isDisabled() { return $this->mDoNothing; }
597
598 public function setArticleRelated( $v ) {
599 $this->mIsArticleRelated = $v;
600 if ( !$v ) {
601 $this->mIsarticle = false;
602 }
603 }
604 public function setArticleFlag( $v ) {
605 $this->mIsarticle = $v;
606 if ( $v ) {
607 $this->mIsArticleRelated = $v;
608 }
609 }
610
611 public function isArticleRelated() { return $this->mIsArticleRelated; }
612
613 public function getLanguageLinks() { return $this->mLanguageLinks; }
614 public function addLanguageLinks($newLinkArray) {
615 $this->mLanguageLinks += $newLinkArray;
616 }
617 public function setLanguageLinks($newLinkArray) {
618 $this->mLanguageLinks = $newLinkArray;
619 }
620
621 public function getCategoryLinks() {
622 return $this->mCategoryLinks;
623 }
624
625 /**
626 * Add an array of categories, with names in the keys
627 */
628 public function addCategoryLinks( $categories ) {
629 global $wgUser, $wgContLang;
630
631 if ( !is_array( $categories ) || count( $categories ) == 0 ) {
632 return;
633 }
634
635 # Add the links to a LinkBatch
636 $arr = array( NS_CATEGORY => $categories );
637 $lb = new LinkBatch;
638 $lb->setArray( $arr );
639
640 # Fetch existence plus the hiddencat property
641 $dbr = wfGetDB( DB_SLAVE );
642 $pageTable = $dbr->tableName( 'page' );
643 $where = $lb->constructSet( 'page', $dbr );
644 $propsTable = $dbr->tableName( 'page_props' );
645 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, pp_value
646 FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
647 $res = $dbr->query( $sql, __METHOD__ );
648
649 # Add the results to the link cache
650 $lb->addResultToCache( LinkCache::singleton(), $res );
651
652 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
653 $categories = array_combine( array_keys( $categories ),
654 array_fill( 0, count( $categories ), 'normal' ) );
655
656 # Mark hidden categories
657 foreach ( $res as $row ) {
658 if ( isset( $row->pp_value ) ) {
659 $categories[$row->page_title] = 'hidden';
660 }
661 }
662
663 # Add the remaining categories to the skin
664 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks ) ) ) {
665 $sk = $wgUser->getSkin();
666 foreach ( $categories as $category => $type ) {
667 $origcategory = $category;
668 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
669 $wgContLang->findVariantLink( $category, $title, true );
670 if ( $category != $origcategory )
671 if ( array_key_exists( $category, $categories ) )
672 continue;
673 $text = $wgContLang->convertHtml( $title->getText() );
674 $this->mCategoryLinks[$type][] = $sk->link( $title, $text );
675 }
676 }
677 }
678
679 public function setCategoryLinks($categories) {
680 $this->mCategoryLinks = array();
681 $this->addCategoryLinks($categories);
682 }
683
684 public function suppressQuickbar() { $this->mSuppressQuickbar = true; }
685 public function isQuickbarSuppressed() { return $this->mSuppressQuickbar; }
686
687 public function disallowUserJs() { $this->mAllowUserJs = false; }
688 public function isUserJsAllowed() { return $this->mAllowUserJs; }
689
690 public function prependHTML( $text ) { $this->mBodytext = $text . $this->mBodytext; }
691 public function addHTML( $text ) { $this->mBodytext .= $text; }
692 public function clearHTML() { $this->mBodytext = ''; }
693 public function getHTML() { return $this->mBodytext; }
694 public function debug( $text ) { $this->mDebugtext .= $text; }
695
696 /* @deprecated */
697 public function setParserOptions( $options ) {
698 wfDeprecated( __METHOD__ );
699 return $this->parserOptions( $options );
700 }
701
702 public function parserOptions( $options = null ) {
703 if ( !$this->mParserOptions ) {
704 $this->mParserOptions = new ParserOptions;
705 }
706 return wfSetVar( $this->mParserOptions, $options );
707 }
708
709 /**
710 * Set the revision ID which will be seen by the wiki text parser
711 * for things such as embedded {{REVISIONID}} variable use.
712 * @param mixed $revid an integer, or NULL
713 * @return mixed previous value
714 */
715 public function setRevisionId( $revid ) {
716 $val = is_null( $revid ) ? null : intval( $revid );
717 return wfSetVar( $this->mRevisionId, $val );
718 }
719
720 public function getRevisionId() {
721 return $this->mRevisionId;
722 }
723
724 /**
725 * Convert wikitext to HTML and add it to the buffer
726 * Default assumes that the current page title will
727 * be used.
728 *
729 * @param string $text
730 * @param bool $linestart
731 */
732 public function addWikiText( $text, $linestart = true ) {
733 $title = $this->getTitle(); // Work arround E_STRICT
734 $this->addWikiTextTitle( $text, $title, $linestart );
735 }
736
737 public function addWikiTextWithTitle($text, &$title, $linestart = true) {
738 $this->addWikiTextTitle($text, $title, $linestart);
739 }
740
741 function addWikiTextTitleTidy($text, &$title, $linestart = true) {
742 $this->addWikiTextTitle( $text, $title, $linestart, true );
743 }
744
745 public function addWikiTextTitle($text, &$title, $linestart, $tidy = false) {
746 global $wgParser;
747
748 wfProfileIn( __METHOD__ );
749
750 wfIncrStats( 'pcache_not_possible' );
751
752 $popts = $this->parserOptions();
753 $oldTidy = $popts->setTidy( $tidy );
754
755 $parserOutput = $wgParser->parse( $text, $title, $popts,
756 $linestart, true, $this->mRevisionId );
757
758 $popts->setTidy( $oldTidy );
759
760 $this->addParserOutput( $parserOutput );
761
762 wfProfileOut( __METHOD__ );
763 }
764
765 /**
766 * @todo document
767 * @param ParserOutput object &$parserOutput
768 */
769 public function addParserOutputNoText( &$parserOutput ) {
770 global $wgExemptFromUserRobotsControl, $wgContentNamespaces;
771
772 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
773 $this->addCategoryLinks( $parserOutput->getCategories() );
774 $this->mNewSectionLink = $parserOutput->getNewSection();
775 $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
776
777 $this->mParseWarnings = $parserOutput->getWarnings();
778 if ( $parserOutput->getCacheTime() == -1 ) {
779 $this->enableClientCache( false );
780 }
781 $this->mNoGallery = $parserOutput->getNoGallery();
782 $this->mHeadItems = array_merge( $this->mHeadItems, (array)$parserOutput->mHeadItems );
783 // Versioning...
784 foreach ( (array)$parserOutput->mTemplateIds as $ns => $dbks ) {
785 if ( isset( $this->mTemplateIds[$ns] ) ) {
786 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
787 } else {
788 $this->mTemplateIds[$ns] = $dbks;
789 }
790 }
791 // Page title
792 if( ( $dt = $parserOutput->getDisplayTitle() ) !== false )
793 $this->setPageTitle( $dt );
794 else if ( ( $title = $parserOutput->getTitleText() ) != '' )
795 $this->setPageTitle( $title );
796
797 // Hooks registered in the object
798 global $wgParserOutputHooks;
799 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
800 list( $hookName, $data ) = $hookInfo;
801 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
802 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
803 }
804 }
805
806 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
807 }
808
809 /**
810 * @todo document
811 * @param ParserOutput &$parserOutput
812 */
813 function addParserOutput( &$parserOutput ) {
814 $this->addParserOutputNoText( $parserOutput );
815 $text = $parserOutput->getText();
816 wfRunHooks( 'OutputPageBeforeHTML',array( &$this, &$text ) );
817 $this->addHTML( $text );
818 }
819
820 /**
821 * Add wikitext to the buffer, assuming that this is the primary text for a page view
822 * Saves the text into the parser cache if possible.
823 *
824 * @param string $text
825 * @param Article $article
826 * @param bool $cache
827 * @deprecated Use Article::outputWikitext
828 */
829 public function addPrimaryWikiText( $text, $article, $cache = true ) {
830 global $wgParser;
831
832 wfDeprecated( __METHOD__ );
833
834 $popts = $this->parserOptions();
835 $popts->setTidy(true);
836 $parserOutput = $wgParser->parse( $text, $article->mTitle,
837 $popts, true, true, $this->mRevisionId );
838 $popts->setTidy(false);
839 if ( $cache && $article && $parserOutput->getCacheTime() != -1 ) {
840 $parserCache = ParserCache::singleton();
841 $parserCache->save( $parserOutput, $article, $popts);
842 }
843
844 $this->addParserOutput( $parserOutput );
845 }
846
847 /**
848 * @deprecated use addWikiTextTidy()
849 */
850 public function addSecondaryWikiText( $text, $linestart = true ) {
851 wfDeprecated( __METHOD__ );
852 $this->addWikiTextTitleTidy($text, $this->getTitle(), $linestart);
853 }
854
855 /**
856 * Add wikitext with tidy enabled
857 */
858 public function addWikiTextTidy( $text, $linestart = true ) {
859 $title = $this->getTitle();
860 $this->addWikiTextTitleTidy($text, $title, $linestart);
861 }
862
863
864 /**
865 * Add the output of a QuickTemplate to the output buffer
866 *
867 * @param QuickTemplate $template
868 */
869 public function addTemplate( &$template ) {
870 ob_start();
871 $template->execute();
872 $this->addHTML( ob_get_contents() );
873 ob_end_clean();
874 }
875
876 /**
877 * Parse wikitext and return the HTML.
878 *
879 * @param string $text
880 * @param bool $linestart Is this the start of a line?
881 * @param bool $interface ??
882 */
883 public function parse( $text, $linestart = true, $interface = false ) {
884 global $wgParser;
885 if( is_null( $this->getTitle() ) ) {
886 throw new MWException( 'Empty $mTitle in ' . __METHOD__ );
887 }
888 $popts = $this->parserOptions();
889 if ( $interface) { $popts->setInterfaceMessage(true); }
890 $parserOutput = $wgParser->parse( $text, $this->getTitle(), $popts,
891 $linestart, true, $this->mRevisionId );
892 if ( $interface) { $popts->setInterfaceMessage(false); }
893 return $parserOutput->getText();
894 }
895
896 /** Parse wikitext, strip paragraphs, and return the HTML. */
897 public function parseInline( $text, $linestart = true, $interface = false ) {
898 $parsed = $this->parse( $text, $linestart, $interface );
899
900 $m = array();
901 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
902 $parsed = $m[1];
903 }
904
905 return $parsed;
906 }
907
908 /**
909 * @param Article $article
910 * @param User $user
911 *
912 * @deprecated
913 *
914 * @return bool True if successful, else false.
915 */
916 public function tryParserCache( &$article ) {
917 wfDeprecated( __METHOD__ );
918 $parserOutput = ParserCache::singleton()->get( $article, $article->getParserOptions() );
919
920 if ($parserOutput !== false) {
921 $this->addParserOutput( $parserOutput );
922 return true;
923 } else {
924 return false;
925 }
926 }
927
928 /**
929 * @param int $maxage Maximum cache time on the Squid, in seconds.
930 */
931 public function setSquidMaxage( $maxage ) {
932 $this->mSquidMaxage = $maxage;
933 }
934
935 /**
936 * Use enableClientCache(false) to force it to send nocache headers
937 * @param $state ??
938 */
939 public function enableClientCache( $state ) {
940 return wfSetVar( $this->mEnableClientCache, $state );
941 }
942
943 function getCacheVaryCookies() {
944 global $wgCookiePrefix, $wgCacheVaryCookies;
945 static $cookies;
946 if ( $cookies === null ) {
947 $cookies = array_merge(
948 array(
949 "{$wgCookiePrefix}Token",
950 "{$wgCookiePrefix}LoggedOut",
951 session_name()
952 ),
953 $wgCacheVaryCookies
954 );
955 wfRunHooks('GetCacheVaryCookies', array( $this, &$cookies ) );
956 }
957 return $cookies;
958 }
959
960 function uncacheableBecauseRequestVars() {
961 global $wgRequest;
962 return $wgRequest->getText('useskin', false) === false
963 && $wgRequest->getText('uselang', false) === false;
964 }
965
966 /**
967 * Check if the request has a cache-varying cookie header
968 * If it does, it's very important that we don't allow public caching
969 */
970 function haveCacheVaryCookies() {
971 global $wgRequest;
972 $cookieHeader = $wgRequest->getHeader( 'cookie' );
973 if ( $cookieHeader === false ) {
974 return false;
975 }
976 $cvCookies = $this->getCacheVaryCookies();
977 foreach ( $cvCookies as $cookieName ) {
978 # Check for a simple string match, like the way squid does it
979 if ( strpos( $cookieHeader, $cookieName ) ) {
980 wfDebug( __METHOD__.": found $cookieName\n" );
981 return true;
982 }
983 }
984 wfDebug( __METHOD__.": no cache-varying cookies found\n" );
985 return false;
986 }
987
988 /** Get a complete X-Vary-Options header */
989 public function getXVO() {
990 $cvCookies = $this->getCacheVaryCookies();
991 $xvo = 'X-Vary-Options: Accept-Encoding;list-contains=gzip,Cookie;';
992 $first = true;
993 foreach ( $cvCookies as $cookieName ) {
994 if ( $first ) {
995 $first = false;
996 } else {
997 $xvo .= ';';
998 }
999 $xvo .= 'string-contains=' . $cookieName;
1000 }
1001 return $xvo;
1002 }
1003
1004 public function sendCacheControl() {
1005 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest, $wgUseXVO;
1006
1007 $response = $wgRequest->response();
1008 if ($wgUseETag && $this->mETag)
1009 $response->header("ETag: $this->mETag");
1010
1011 # don't serve compressed data to clients who can't handle it
1012 # maintain different caches for logged-in users and non-logged in ones
1013 $response->header( 'Vary: Accept-Encoding, Cookie' );
1014
1015 if ( $wgUseXVO ) {
1016 # Add an X-Vary-Options header for Squid with Wikimedia patches
1017 $response->header( $this->getXVO() );
1018 }
1019
1020 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache ) {
1021 if( $wgUseSquid && session_id() == '' &&
1022 ! $this->isPrintable() && $this->mSquidMaxage != 0 && !$this->haveCacheVaryCookies() )
1023 {
1024 if ( $wgUseESI ) {
1025 # We'll purge the proxy cache explicitly, but require end user agents
1026 # to revalidate against the proxy on each visit.
1027 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1028 wfDebug( __METHOD__ . ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1029 # start with a shorter timeout for initial testing
1030 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1031 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage.', content="ESI/1.0"');
1032 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1033 } else {
1034 # We'll purge the proxy cache for anons explicitly, but require end user agents
1035 # to revalidate against the proxy on each visit.
1036 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1037 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1038 wfDebug( __METHOD__ . ": local proxy caching; {$this->mLastModified} **\n", false );
1039 # start with a shorter timeout for initial testing
1040 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1041 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage.', must-revalidate, max-age=0' );
1042 }
1043 } else {
1044 # We do want clients to cache if they can, but they *must* check for updates
1045 # on revisiting the page.
1046 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **\n", false );
1047 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1048 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1049 }
1050 if($this->mLastModified) {
1051 $response->header( "Last-Modified: {$this->mLastModified}" );
1052 }
1053 } else {
1054 wfDebug( __METHOD__ . ": no caching **\n", false );
1055
1056 # In general, the absence of a last modified header should be enough to prevent
1057 # the client from using its cache. We send a few other things just to make sure.
1058 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1059 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1060 $response->header( 'Pragma: no-cache' );
1061 }
1062 }
1063
1064 /**
1065 * Finally, all the text has been munged and accumulated into
1066 * the object, let's actually output it:
1067 */
1068 public function output() {
1069 global $wgUser, $wgOutputEncoding, $wgRequest;
1070 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
1071 global $wgUseAjax, $wgAjaxWatch;
1072 global $wgEnableMWSuggest, $wgUniversalEditButton;
1073 global $wgArticle;
1074
1075 if( $this->mDoNothing ){
1076 return;
1077 }
1078 wfProfileIn( __METHOD__ );
1079 if ( '' != $this->mRedirect ) {
1080 # Standards require redirect URLs to be absolute
1081 $this->mRedirect = wfExpandUrl( $this->mRedirect );
1082 if( $this->mRedirectCode == '301') {
1083 if( !$wgDebugRedirects ) {
1084 $wgRequest->response()->header("HTTP/1.1 {$this->mRedirectCode} Moved Permanently");
1085 }
1086 $this->mLastModified = wfTimestamp( TS_RFC2822 );
1087 }
1088 $this->sendCacheControl();
1089
1090 $wgRequest->response()->header("Content-Type: text/html; charset=utf-8");
1091 if( $wgDebugRedirects ) {
1092 $url = htmlspecialchars( $this->mRedirect );
1093 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1094 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1095 print "</body>\n</html>\n";
1096 } else {
1097 $wgRequest->response()->header( 'Location: '.$this->mRedirect );
1098 }
1099 wfProfileOut( __METHOD__ );
1100 return;
1101 }
1102 elseif ( $this->mStatusCode )
1103 {
1104 $statusMessage = array(
1105 100 => 'Continue',
1106 101 => 'Switching Protocols',
1107 102 => 'Processing',
1108 200 => 'OK',
1109 201 => 'Created',
1110 202 => 'Accepted',
1111 203 => 'Non-Authoritative Information',
1112 204 => 'No Content',
1113 205 => 'Reset Content',
1114 206 => 'Partial Content',
1115 207 => 'Multi-Status',
1116 300 => 'Multiple Choices',
1117 301 => 'Moved Permanently',
1118 302 => 'Found',
1119 303 => 'See Other',
1120 304 => 'Not Modified',
1121 305 => 'Use Proxy',
1122 307 => 'Temporary Redirect',
1123 400 => 'Bad Request',
1124 401 => 'Unauthorized',
1125 402 => 'Payment Required',
1126 403 => 'Forbidden',
1127 404 => 'Not Found',
1128 405 => 'Method Not Allowed',
1129 406 => 'Not Acceptable',
1130 407 => 'Proxy Authentication Required',
1131 408 => 'Request Timeout',
1132 409 => 'Conflict',
1133 410 => 'Gone',
1134 411 => 'Length Required',
1135 412 => 'Precondition Failed',
1136 413 => 'Request Entity Too Large',
1137 414 => 'Request-URI Too Large',
1138 415 => 'Unsupported Media Type',
1139 416 => 'Request Range Not Satisfiable',
1140 417 => 'Expectation Failed',
1141 422 => 'Unprocessable Entity',
1142 423 => 'Locked',
1143 424 => 'Failed Dependency',
1144 500 => 'Internal Server Error',
1145 501 => 'Not Implemented',
1146 502 => 'Bad Gateway',
1147 503 => 'Service Unavailable',
1148 504 => 'Gateway Timeout',
1149 505 => 'HTTP Version Not Supported',
1150 507 => 'Insufficient Storage'
1151 );
1152
1153 if ( $statusMessage[$this->mStatusCode] )
1154 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode . ' ' . $statusMessage[$this->mStatusCode] );
1155 }
1156
1157 $sk = $wgUser->getSkin();
1158
1159 // Add our core scripts to output
1160 $this->addCoreScripts2Top();
1161
1162 if ( $wgUseAjax ) {
1163 $this->addScriptFile( 'ajax.js' );
1164
1165 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1166
1167 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1168 $this->addScriptFile( 'ajaxwatch.js' );
1169 }
1170
1171 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ){
1172 $this->addScriptFile( 'mwsuggest.js' );
1173 }
1174 }
1175
1176 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1177 $this->addScriptFile( 'rightclickedit.js' );
1178 }
1179
1180 global $wgUseAJAXCategories, $wgEnableJS2system;
1181 if ($wgUseAJAXCategories && $wgEnableJS2system) {
1182 global $wgAJAXCategoriesNamespaces;
1183
1184 $title = $this->getTitle();
1185
1186 if( empty( $wgAJAXCategoriesNamespaces ) || in_array( $title->getNamespace(), $wgAJAXCategoriesNamespaces ) ) {
1187 $this->addScriptClass( 'ajaxCategories' );
1188 }
1189 }
1190
1191 if( $wgUniversalEditButton ) {
1192 if( isset( $wgArticle ) && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1193 && ( $this->getTitle()->exists() || $this->getTitle()->quickUserCan( 'create' ) ) ) {
1194 // Original UniversalEditButton
1195 $msg = wfMsg('edit');
1196 $this->addLink( array(
1197 'rel' => 'alternate',
1198 'type' => 'application/x-wiki',
1199 'title' => $msg,
1200 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1201 ) );
1202 // Alternate edit link
1203 $this->addLink( array(
1204 'rel' => 'edit',
1205 'title' => $msg,
1206 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1207 ) );
1208 }
1209 }
1210
1211 # Buffer output; final headers may depend on later processing
1212 ob_start();
1213
1214 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1215 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
1216
1217 if ($this->mArticleBodyOnly) {
1218 $this->out($this->mBodytext);
1219 } else {
1220 // Hook that allows last minute changes to the output page, e.g.
1221 // adding of CSS or Javascript by extensions.
1222 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1223
1224 wfProfileIn( 'Output-skin' );
1225 $sk->outputPage( $this );
1226 wfProfileOut( 'Output-skin' );
1227 }
1228
1229 $this->sendCacheControl();
1230 ob_end_flush();
1231 wfProfileOut( __METHOD__ );
1232 }
1233
1234 /**
1235 * Actually output something with print(). Performs an iconv to the
1236 * output encoding, if needed.
1237 * @param string $ins The string to output
1238 */
1239 public function out( $ins ) {
1240 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1241 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1242 $outs = $ins;
1243 } else {
1244 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1245 if ( false === $outs ) { $outs = $ins; }
1246 }
1247 print $outs;
1248 }
1249
1250 /**
1251 * @todo document
1252 */
1253 public static function setEncodings() {
1254 global $wgInputEncoding, $wgOutputEncoding;
1255 global $wgContLang;
1256
1257 $wgInputEncoding = strtolower( $wgInputEncoding );
1258
1259 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
1260 $wgOutputEncoding = strtolower( $wgOutputEncoding );
1261 return;
1262 }
1263 $wgOutputEncoding = $wgInputEncoding;
1264 }
1265
1266 /**
1267 * Deprecated, use wfReportTime() instead.
1268 * @return string
1269 * @deprecated
1270 */
1271 public function reportTime() {
1272 wfDeprecated( __METHOD__ );
1273 $time = wfReportTime();
1274 return $time;
1275 }
1276
1277 /**
1278 * Produce a "user is blocked" page.
1279 *
1280 * @param bool $return Whether to have a "return to $wgTitle" message or not.
1281 * @return nothing
1282 */
1283 function blockedPage( $return = true ) {
1284 global $wgUser, $wgContLang, $wgLang;
1285
1286 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1287 $this->setRobotPolicy( 'noindex,nofollow' );
1288 $this->setArticleRelated( false );
1289
1290 $name = User::whoIs( $wgUser->blockedBy() );
1291 $reason = $wgUser->blockedFor();
1292 if( $reason == '' ) {
1293 $reason = wfMsg( 'blockednoreason' );
1294 }
1295 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW, $wgUser->mBlock->mTimestamp ), true );
1296 $ip = wfGetIP();
1297
1298 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
1299
1300 $blockid = $wgUser->mBlock->mId;
1301
1302 $blockExpiry = $wgUser->mBlock->mExpiry;
1303 if ( $blockExpiry == 'infinity' ) {
1304 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1305 // Search for localization in 'ipboptions'
1306 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1307 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1308 if ( strpos( $option, ":" ) === false )
1309 continue;
1310 list( $show, $value ) = explode( ":", $option );
1311 if ( $value == 'infinite' || $value == 'indefinite' ) {
1312 $blockExpiry = $show;
1313 break;
1314 }
1315 }
1316 } else {
1317 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW, $blockExpiry ), true );
1318 }
1319
1320 if ( $wgUser->mBlock->mAuto ) {
1321 $msg = 'autoblockedtext';
1322 } else {
1323 $msg = 'blockedtext';
1324 }
1325
1326 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1327 * This could be a username, an ip range, or a single ip. */
1328 $intended = $wgUser->mBlock->mAddress;
1329
1330 $this->addWikiMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
1331
1332 # Don't auto-return to special pages
1333 if( $return ) {
1334 $return = $this->getTitle()->getNamespace() > -1 ? $this->getTitle() : null;
1335 $this->returnToMain( null, $return );
1336 }
1337 }
1338
1339 /**
1340 * Output a standard error page
1341 *
1342 * @param string $title Message key for page title
1343 * @param string $msg Message key for page text
1344 * @param array $params Message parameters
1345 */
1346 public function showErrorPage( $title, $msg, $params = array() ) {
1347 if ( $this->getTitle() ) {
1348 $this->mDebugtext .= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1349 }
1350 $this->setPageTitle( wfMsg( $title ) );
1351 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1352 $this->setRobotPolicy( 'noindex,nofollow' );
1353 $this->setArticleRelated( false );
1354 $this->enableClientCache( false );
1355 $this->mRedirect = '';
1356 $this->mBodytext = '';
1357
1358 array_unshift( $params, 'parse' );
1359 array_unshift( $params, $msg );
1360 $this->addHTML( call_user_func_array( 'wfMsgExt', $params ) );
1361
1362 $this->returnToMain();
1363 }
1364
1365 /**
1366 * Output a standard permission error page
1367 *
1368 * @param array $errors Error message keys
1369 */
1370 public function showPermissionsErrorPage( $errors, $action = null )
1371 {
1372 $this->mDebugtext .= 'Original title: ' .
1373 $this->getTitle()->getPrefixedText() . "\n";
1374 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1375 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1376 $this->setRobotPolicy( 'noindex,nofollow' );
1377 $this->setArticleRelated( false );
1378 $this->enableClientCache( false );
1379 $this->mRedirect = '';
1380 $this->mBodytext = '';
1381 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1382 }
1383
1384 /** @deprecated */
1385 public function errorpage( $title, $msg ) {
1386 wfDeprecated( __METHOD__ );
1387 throw new ErrorPageError( $title, $msg );
1388 }
1389
1390 /**
1391 * Display an error page indicating that a given version of MediaWiki is
1392 * required to use it
1393 *
1394 * @param mixed $version The version of MediaWiki needed to use the page
1395 */
1396 public function versionRequired( $version ) {
1397 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1398 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1399 $this->setRobotPolicy( 'noindex,nofollow' );
1400 $this->setArticleRelated( false );
1401 $this->mBodytext = '';
1402
1403 $this->addWikiMsg( 'versionrequiredtext', $version );
1404 $this->returnToMain();
1405 }
1406
1407 /**
1408 * Display an error page noting that a given permission bit is required.
1409 *
1410 * @param string $permission key required
1411 */
1412 public function permissionRequired( $permission ) {
1413 global $wgLang;
1414
1415 $this->setPageTitle( wfMsg( 'badaccess' ) );
1416 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1417 $this->setRobotPolicy( 'noindex,nofollow' );
1418 $this->setArticleRelated( false );
1419 $this->mBodytext = '';
1420
1421 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1422 User::getGroupsWithPermission( $permission ) );
1423 if( $groups ) {
1424 $this->addWikiMsg( 'badaccess-groups',
1425 $wgLang->commaList( $groups ),
1426 count( $groups) );
1427 } else {
1428 $this->addWikiMsg( 'badaccess-group0' );
1429 }
1430 $this->returnToMain();
1431 }
1432
1433 /**
1434 * Use permissionRequired.
1435 * @deprecated
1436 */
1437 public function sysopRequired() {
1438 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
1439 }
1440
1441 /**
1442 * Use permissionRequired.
1443 * @deprecated
1444 */
1445 public function developerRequired() {
1446 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
1447 }
1448
1449 /**
1450 * Produce the stock "please login to use the wiki" page
1451 */
1452 public function loginToUse() {
1453 global $wgUser, $wgContLang;
1454
1455 if( $wgUser->isLoggedIn() ) {
1456 $this->permissionRequired( 'read' );
1457 return;
1458 }
1459
1460 $skin = $wgUser->getSkin();
1461
1462 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1463 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1464 $this->setRobotPolicy( 'noindex,nofollow' );
1465 $this->setArticleFlag( false );
1466
1467 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
1468 $loginLink = $skin->link(
1469 $loginTitle,
1470 wfMsgHtml( 'loginreqlink' ),
1471 array(),
1472 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
1473 array( 'known', 'noclasses' )
1474 );
1475 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1476 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . "-->" );
1477
1478 # Don't return to the main page if the user can't read it
1479 # otherwise we'll end up in a pointless loop
1480 $mainPage = Title::newMainPage();
1481 if( $mainPage->userCanRead() )
1482 $this->returnToMain( null, $mainPage );
1483 }
1484
1485 /** @deprecated */
1486 public function databaseError( $fname, $sql, $error, $errno ) {
1487 throw new MWException( "OutputPage::databaseError is obsolete\n" );
1488 }
1489
1490 /**
1491 * @param array $errors An array of arrays returned by Title::getUserPermissionsErrors
1492 * @return string The wikitext error-messages, formatted into a list.
1493 */
1494 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1495 if ($action == null) {
1496 $text = wfMsgNoTrans( 'permissionserrorstext', count($errors)). "\n\n";
1497 } else {
1498 global $wgLang;
1499 $action_desc = wfMsgNoTrans( "action-$action" );
1500 $text = wfMsgNoTrans( 'permissionserrorstext-withaction', count($errors), $action_desc ) . "\n\n";
1501 }
1502
1503 if (count( $errors ) > 1) {
1504 $text .= '<ul class="permissions-errors">' . "\n";
1505
1506 foreach( $errors as $error )
1507 {
1508 $text .= '<li>';
1509 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1510 $text .= "</li>\n";
1511 }
1512 $text .= '</ul>';
1513 } else {
1514 $text .= "<div class=\"permissions-errors\">\n" . call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) . "\n</div>";
1515 }
1516
1517 return $text;
1518 }
1519
1520 /**
1521 * Display a page stating that the Wiki is in read-only mode,
1522 * and optionally show the source of the page that the user
1523 * was trying to edit. Should only be called (for this
1524 * purpose) after wfReadOnly() has returned true.
1525 *
1526 * For historical reasons, this function is _also_ used to
1527 * show the error message when a user tries to edit a page
1528 * they are not allowed to edit. (Unless it's because they're
1529 * blocked, then we show blockedPage() instead.) In this
1530 * case, the second parameter should be set to true and a list
1531 * of reasons supplied as the third parameter.
1532 *
1533 * @todo Needs to be split into multiple functions.
1534 *
1535 * @param string $source Source code to show (or null).
1536 * @param bool $protected Is this a permissions error?
1537 * @param array $reasons List of reasons for this error, as returned by Title::getUserPermissionsErrors().
1538 */
1539 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1540 global $wgUser;
1541 $skin = $wgUser->getSkin();
1542
1543 $this->setRobotPolicy( 'noindex,nofollow' );
1544 $this->setArticleRelated( false );
1545
1546 // If no reason is given, just supply a default "I can't let you do
1547 // that, Dave" message. Should only occur if called by legacy code.
1548 if ( $protected && empty($reasons) ) {
1549 $reasons[] = array( 'badaccess-group0' );
1550 }
1551
1552 if ( !empty($reasons) ) {
1553 // Permissions error
1554 if( $source ) {
1555 $this->setPageTitle( wfMsg( 'viewsource' ) );
1556 $this->setSubtitle(
1557 wfMsg(
1558 'viewsourcefor',
1559 $skin->link(
1560 $this->getTitle(),
1561 null,
1562 array(),
1563 array(),
1564 array( 'known', 'noclasses' )
1565 )
1566 )
1567 );
1568 } else {
1569 $this->setPageTitle( wfMsg( 'badaccess' ) );
1570 }
1571 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1572 } else {
1573 // Wiki is read only
1574 $this->setPageTitle( wfMsg( 'readonly' ) );
1575 $reason = wfReadOnlyReason();
1576 $this->wrapWikiMsg( '<div class="mw-readonly-error">$1</div>', array( 'readonlytext', $reason ) );
1577 }
1578
1579 // Show source, if supplied
1580 if( is_string( $source ) ) {
1581 $this->addWikiMsg( 'viewsourcetext' );
1582
1583 $params = array(
1584 'id' => 'wpTextbox1',
1585 'name' => 'wpTextbox1',
1586 'cols' => $wgUser->getOption( 'cols' ),
1587 'rows' => $wgUser->getOption( 'rows' ),
1588 'readonly' => 'readonly'
1589 );
1590 $this->addHTML( Html::element( 'textarea', $params, $source ) );
1591
1592 // Show templates used by this article
1593 $skin = $wgUser->getSkin();
1594 $article = new Article( $this->getTitle() );
1595 $this->addHTML( "<div class='templatesUsed'>
1596 {$skin->formatTemplates( $article->getUsedTemplates() )}
1597 </div>
1598 " );
1599 }
1600
1601 # If the title doesn't exist, it's fairly pointless to print a return
1602 # link to it. After all, you just tried editing it and couldn't, so
1603 # what's there to do there?
1604 if( $this->getTitle()->exists() ) {
1605 $this->returnToMain( null, $this->getTitle() );
1606 }
1607 }
1608
1609 /** @deprecated */
1610 public function fatalError( $message ) {
1611 wfDeprecated( __METHOD__ );
1612 throw new FatalError( $message );
1613 }
1614
1615 /** @deprecated */
1616 public function unexpectedValueError( $name, $val ) {
1617 wfDeprecated( __METHOD__ );
1618 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1619 }
1620
1621 /** @deprecated */
1622 public function fileCopyError( $old, $new ) {
1623 wfDeprecated( __METHOD__ );
1624 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1625 }
1626
1627 /** @deprecated */
1628 public function fileRenameError( $old, $new ) {
1629 wfDeprecated( __METHOD__ );
1630 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1631 }
1632
1633 /** @deprecated */
1634 public function fileDeleteError( $name ) {
1635 wfDeprecated( __METHOD__ );
1636 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1637 }
1638
1639 /** @deprecated */
1640 public function fileNotFoundError( $name ) {
1641 wfDeprecated( __METHOD__ );
1642 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1643 }
1644
1645 public function showFatalError( $message ) {
1646 $this->setPageTitle( wfMsg( "internalerror" ) );
1647 $this->setRobotPolicy( "noindex,nofollow" );
1648 $this->setArticleRelated( false );
1649 $this->enableClientCache( false );
1650 $this->mRedirect = '';
1651 $this->mBodytext = $message;
1652 }
1653
1654 public function showUnexpectedValueError( $name, $val ) {
1655 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
1656 }
1657
1658 public function showFileCopyError( $old, $new ) {
1659 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
1660 }
1661
1662 public function showFileRenameError( $old, $new ) {
1663 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
1664 }
1665
1666 public function showFileDeleteError( $name ) {
1667 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
1668 }
1669
1670 public function showFileNotFoundError( $name ) {
1671 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1672 }
1673
1674 /**
1675 * Add a "return to" link pointing to a specified title
1676 *
1677 * @param Title $title Title to link
1678 * @param string $query Query string
1679 */
1680 public function addReturnTo( $title, $query = array() ) {
1681 global $wgUser;
1682 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullUrl() ) );
1683 $link = wfMsgHtml( 'returnto', $wgUser->getSkin()->link(
1684 $title, null, array(), $query ) );
1685 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
1686 }
1687
1688 /**
1689 * Add a "return to" link pointing to a specified title,
1690 * or the title indicated in the request, or else the main page
1691 *
1692 * @param null $unused No longer used
1693 * @param Title $returnto Title to return to
1694 */
1695 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
1696 global $wgRequest;
1697
1698 if ( $returnto == null ) {
1699 $returnto = $wgRequest->getText( 'returnto' );
1700 }
1701
1702 if ( $returntoquery == null ) {
1703 $returntoquery = $wgRequest->getText( 'returntoquery' );
1704 }
1705
1706 if ( '' === $returnto ) {
1707 $returnto = Title::newMainPage();
1708 }
1709
1710 if ( is_object( $returnto ) ) {
1711 $titleObj = $returnto;
1712 } else {
1713 $titleObj = Title::newFromText( $returnto );
1714 }
1715 if ( !is_object( $titleObj ) ) {
1716 $titleObj = Title::newMainPage();
1717 }
1718
1719 $this->addReturnTo( $titleObj, $returntoquery );
1720 }
1721
1722 /**
1723 * @return string The doctype, opening <html>, and head element.
1724 *
1725 * @param $sk Skin The given Skin
1726 */
1727 public function headElement( Skin $sk, $includeStyle = true ) {
1728 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1729 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces;
1730 global $wgContLang, $wgUseTrackbacks, $wgStyleVersion, $wgEnableScriptLoader, $wgHtml5;
1731
1732 $this->addMeta( "http:Content-Type", "$wgMimeType; charset={$wgOutputEncoding}" );
1733 if ( $sk->commonPrintStylesheet() ) {
1734 $this->addStyle( 'common/wikiprintable.css', 'print' );
1735 }
1736 $sk->setupUserCss( $this );
1737
1738 $ret = '';
1739
1740 if( $wgMimeType == 'text/xml' || $wgMimeType == 'application/xhtml+xml' || $wgMimeType == 'application/xml' ) {
1741 $ret .= "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?" . ">\n";
1742 }
1743
1744 if ( '' == $this->getHTMLTitle() ) {
1745 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1746 }
1747
1748 $dir = $wgContLang->getDir();
1749
1750 if ( $wgHtml5 ) {
1751 $ret .= "<!doctype html>\n";
1752 $ret .= "<html lang=\"$wgContLanguageCode\" dir=\"$dir\">\n";
1753 } else {
1754 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\" \"$wgDTD\">\n";
1755 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1756 foreach($wgXhtmlNamespaces as $tag => $ns) {
1757 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1758 }
1759 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" dir=\"$dir\">\n";
1760 }
1761
1762 $ret .= "<head>\n";
1763 $ret .= "<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n";
1764 $ret .= implode( "\n", array(
1765 $this->getHeadLinks(),
1766 $this->buildCssLinks(),
1767 $this->getHeadScripts( $sk ),
1768 $this->getHeadItems(),
1769 ));
1770 if( $sk->usercss ){
1771 $ret .= Html::inlineStyle( $sk->usercss );
1772 }
1773
1774 if( $wgEnableScriptLoader )
1775 $ret .= $this->getScriptLoaderJs();
1776
1777 if ($wgUseTrackbacks && $this->isArticleRelated())
1778 $ret .= $this->getTitle()->trackbackRDF();
1779
1780 $ret .= "</head>\n";
1781 return $ret;
1782 }
1783
1784 /*
1785 * gets the global variables and mScripts
1786 *
1787 * also adds userjs to the end if enabled:
1788 */
1789 function getHeadScripts( Skin $sk ) {
1790 global $wgUser, $wgRequest, $wgJsMimeType;
1791
1792 $vars = Skin::makeGlobalVariablesScript( $sk->getSkinName() );
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 }