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