Also treat [[#section]] links as expected with the 'local' param for diff view vs...
[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 // the most recent id of any script that is grouped in the script request
19 var $mLatestScriptRevID = 0;
20
21 var $mScripts = '', $mLinkColours, $mPageLinkTitle = '', $mHeadItems = array();
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 ) { $this->mScripts .= "\t\t" . $script . "\n"; }
101
102 function addExtensionStyle( $url ) {
103 $linkarr = array( 'rel' => 'stylesheet', 'href' => $url, 'type' => 'text/css' );
104 array_push( $this->mExtStyles, $linkarr );
105 }
106
107 /**
108 * Add a JavaScript file out of skins/common, or a given relative path.
109 * @param string $file filename in skins/common or complete on-server path (/foo/bar.js)
110 */
111 function addScriptFile( $file ) {
112 global $wgStylePath, $wgStyleVersion, $wgJsMimeType, $wgScript, $wgUser;
113 global $wgJSAutoloadClasses, $wgJSAutoloadLocalClasses, $wgEnableScriptLoader, $wgScriptPath;
114
115 if( substr( $file, 0, 1 ) == '/' ) {
116 $path = $file;
117 } else {
118 $path = "{$wgStylePath}/common/{$file}";
119 }
120
121 if( $wgEnableScriptLoader ){
122 if( strpos( $path, $wgScript ) !== false ){
123 $reqPath = str_replace( $wgScript . '?', '', $path );
124 $reqArgs = explode( '&', $reqPath );
125 $reqSet = array();
126
127 foreach( $reqArgs as $arg ){
128 list( $key, $var ) = explode( '=', $arg );
129 $reqSet[$key] = $var;
130 }
131
132 if( isset( $reqSet['title'] ) && $reqSet != '' ) {
133 // extract any extra param (for now just skin)
134 $ext_param = ( isset( $reqSet['useskin'] ) && $reqSet['useskin'] != '' ) ? '|useskin=' . ucfirst( $reqSet['useskin'] ) : '';
135 $this->mScriptLoaderClassList[] = 'WT:' . $reqSet['title'] . $ext_param ;
136 // add the title revision to the key
137 $t = Title::newFromText( $reqSet['title'] );
138 // if there is no title (don't worry we just use the $wgStyleVersion var (which should be updated on relevant commits)
139 if( $t->exists() ){
140 if( $t->getLatestRevID() > $this->mLatestScriptRevID )
141 $this->mLatestScriptRevID = $t->getLatestRevID();
142 }
143 return true;
144 }
145 }
146
147 // check for class from path:
148 $js_class = $this->getJsClassFromPath( $path );
149 if( $js_class ){
150 // add to the class list:
151 $this->mScriptLoaderClassList[] = $js_class;
152 return true;
153 }
154 }
155
156 // if the script loader did not find a way to add the script than add using addScript
157 $this->addScript(
158 Xml::element( 'script',
159 array(
160 'type' => $wgJsMimeType,
161 'src' => wfAppendQuery( $path, $this->getURIDparam() ),
162 ),
163 '', false
164 )
165 );
166 }
167
168 /**
169 * This is the core script that is included on every page
170 * (they are requested separately to improve caching across
171 * different page load types (edit, upload, view, etc)
172 */
173 function addCoreScripts2Top(){
174 global $wgEnableScriptLoader, $wgStyleVersion, $wgJSAutoloadLocalClasses, $wgJsMimeType, $wgScriptPath, $wgEnableJS2system;
175 //@@todo we should deprecate wikibits in favor of mv_embed and native jQuery functions
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.= Xml::element( 'script', array(
190 'type' => $wgJsMimeType,
191 'src' => "{$wgScriptPath}/{$wgJSAutoloadLocalClasses[$s]}?" . $this->getURIDparam()
192 ),
193 '', false
194 );
195 }
196 }
197 $this->mScripts = $so . $this->mScripts;
198 }
199 }
200
201 /**
202 * @param $js_class String: name of JavaScript class
203 * @return Boolean: false if class wasn't found, true on success
204 */
205 function addScriptClass( $js_class ){
206 global $wgJSAutoloadClasses, $wgJSAutoloadLocalClasses, $wgJsMimeType,
207 $wgEnableScriptLoader, $wgStyleVersion, $wgScriptPath;
208
209 if( isset( $wgJSAutoloadClasses[$js_class] ) || isset( $wgJSAutoloadLocalClasses[$js_class] ) ){
210 if( $wgEnableScriptLoader ){
211 if( !in_array( $js_class, $this->mScriptLoaderClassList ) ){
212 $this->mScriptLoaderClassList[] = $js_class;
213 }
214 } else {
215 // do a normal load of without the script-loader:
216 $path = $wgScriptPath . '/';
217 $path.= isset( $wgJSAutoloadClasses[$js_class] ) ? $wgJSAutoloadClasses[$js_class]:
218 $wgJSAutoloadLocalClasses[$js_class];
219 $this->addScript(
220 Xml::element( 'script',
221 array(
222 'type' => $wgJsMimeType,
223 'src' => "$path?$wgStyleVersion",
224 ),
225 '', false
226 )
227 );
228 }
229 return true;
230 }
231 wfDebug( __METHOD__ . ' could not find js_class: ' . $js_class );
232 return false; // could not find the class
233 }
234
235 /**
236 * gets the scriptLoader javascript include
237 * @param $forcClassAry Boolean: false by default
238 */
239 function getScriptLoaderJs( $forceClassAry = false ){
240 global $wgScriptPath, $wgJsMimeType, $wgStyleVersion, $wgRequest, $wgDebugJavaScript;
241
242 if( !$forceClassAry ){
243 $class_list = implode( ',', $this->mScriptLoaderClassList );
244 } else {
245 $class_list = implode( ',', $forceClassAry );
246 }
247
248 $debug_param = ( $wgDebugJavaScript ||
249 $wgRequest->getVal( 'debug' ) == 'true' ||
250 $wgRequest->getVal( 'debug' ) == '1' )
251 ? '&debug=true' : '';
252
253 //@@todo intelligent unique id generation based on svn version of file (rather than just grabbing the $wgStyleVersion var)
254 //@@todo we should check the packaged message text in this javascript file for updates and update the $mScriptLoaderURID id (in getJsClassFromPath)
255
256 //generate the unique request param (combine with the most recent revision id of any wiki page with the $wgStyleVersion var)
257
258
259 return Xml::element( 'script',
260 array(
261 'type' => $wgJsMimeType,
262 'src' => "$wgScriptPath/mwScriptLoader.php?class={$class_list}{$debug_param}&".$this->getURIDparam(),
263 ),
264 '', false
265 );
266 }
267
268 function getURIDparam(){
269 global $wgDebugJavaScript, $wgStyleVersion;
270 if( $wgDebugJavaScript ){
271 return 'urid=' . time();
272 } else {
273 return "urid={$wgStyleVersion}_{$this->mLatestScriptRevID}";
274 }
275 }
276
277 function getJsClassFromPath( $path ){
278 global $wgJSAutoloadClasses, $wgJSAutoloadLocalClasses, $wgScriptPath;
279
280 $scriptLoaderPaths = array_merge( $wgJSAutoloadClasses, $wgJSAutoloadLocalClasses );
281 foreach( $scriptLoaderPaths as $js_class => $js_path ){
282 $js_path = "{$wgScriptPath}/{$js_path}";
283 if( $path == $js_path )
284 return $js_class;
285 }
286 return false;
287 }
288
289 /**
290 * Add a self-contained script tag with the given contents
291 * @param string $script JavaScript text, no <script> tags
292 */
293 function addInlineScript( $script ) {
294 global $wgJsMimeType;
295 $this->mScripts .= "\t\t<script type=\"$wgJsMimeType\">/*<![CDATA[*/\n\t\t$script\n\t\t/*]]>*/</script>\n";
296 }
297
298 function getScript() {
299 global $wgEnableScriptLoader;
300 if( $wgEnableScriptLoader ){
301 //include $this->mScripts (for anything that we could not package into the scriptloader
302 return $this->mScripts . "\n" . $this->getScriptLoaderJs() . $this->getHeadItems();
303 } else {
304 return $this->mScripts . $this->getHeadItems();
305 }
306 }
307
308 function getHeadItems() {
309 $s = '';
310 foreach ( $this->mHeadItems as $item ) {
311 $s .= $item;
312 }
313 return $s;
314 }
315
316 function addHeadItem( $name, $value ) {
317 $this->mHeadItems[$name] = $value;
318 }
319
320 function hasHeadItem( $name ) {
321 return isset( $this->mHeadItems[$name] );
322 }
323
324 function setETag($tag) { $this->mETag = $tag; }
325 function setArticleBodyOnly($only) { $this->mArticleBodyOnly = $only; }
326 function getArticleBodyOnly($only) { return $this->mArticleBodyOnly; }
327
328 function addLink( $linkarr ) {
329 # $linkarr should be an associative array of attributes. We'll escape on output.
330 array_push( $this->mLinktags, $linkarr );
331 }
332
333 # Get all links added by extensions
334 function getExtStyle() {
335 return $this->mExtStyles;
336 }
337
338 function addMetadataLink( $linkarr ) {
339 # note: buggy CC software only reads first "meta" link
340 static $haveMeta = false;
341 $linkarr['rel'] = ($haveMeta) ? 'alternate meta' : 'meta';
342 $this->addLink( $linkarr );
343 $haveMeta = true;
344 }
345
346 /**
347 * checkLastModified tells the client to use the client-cached page if
348 * possible. If sucessful, the OutputPage is disabled so that
349 * any future call to OutputPage->output() have no effect.
350 *
351 * Side effect: sets mLastModified for Last-Modified header
352 *
353 * @return bool True iff cache-ok headers was sent.
354 */
355 function checkLastModified( $timestamp ) {
356 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
357
358 if ( !$timestamp || $timestamp == '19700101000000' ) {
359 wfDebug( __METHOD__ . ": CACHE DISABLED, NO TIMESTAMP\n" );
360 return false;
361 }
362 if( !$wgCachePages ) {
363 wfDebug( __METHOD__ . ": CACHE DISABLED\n", false );
364 return false;
365 }
366 if( $wgUser->getOption( 'nocache' ) ) {
367 wfDebug( __METHOD__ . ": USER DISABLED CACHE\n", false );
368 return false;
369 }
370
371 $timestamp = wfTimestamp( TS_MW, $timestamp );
372 $modifiedTimes = array(
373 'page' => $timestamp,
374 'user' => $wgUser->getTouched(),
375 'epoch' => $wgCacheEpoch
376 );
377 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
378
379 $maxModified = max( $modifiedTimes );
380 $this->mLastModified = wfTimestamp( TS_RFC2822, $maxModified );
381
382 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
383 wfDebug( __METHOD__ . ": client did not send If-Modified-Since header\n", false );
384 return false;
385 }
386
387 # Make debug info
388 $info = '';
389 foreach ( $modifiedTimes as $name => $value ) {
390 if ( $info !== '' ) {
391 $info .= ', ';
392 }
393 $info .= "$name=" . wfTimestamp( TS_ISO_8601, $value );
394 }
395
396 # IE sends sizes after the date like this:
397 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
398 # this breaks strtotime().
399 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
400
401 wfSuppressWarnings(); // E_STRICT system time bitching
402 $clientHeaderTime = strtotime( $clientHeader );
403 wfRestoreWarnings();
404 if ( !$clientHeaderTime ) {
405 wfDebug( __METHOD__ . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
406 return false;
407 }
408 $clientHeaderTime = wfTimestamp( TS_MW, $clientHeaderTime );
409
410 wfDebug( __METHOD__ . ": client sent If-Modified-Since: " .
411 wfTimestamp( TS_ISO_8601, $clientHeaderTime ) . "\n", false );
412 wfDebug( __METHOD__ . ": effective Last-Modified: " .
413 wfTimestamp( TS_ISO_8601, $maxModified ) . "\n", false );
414 if( $clientHeaderTime < $maxModified ) {
415 wfDebug( __METHOD__ . ": STALE, $info\n", false );
416 return false;
417 }
418
419 # Not modified
420 # Give a 304 response code and disable body output
421 wfDebug( __METHOD__ . ": NOT MODIFIED, $info\n", false );
422 ini_set('zlib.output_compression', 0);
423 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
424 $this->sendCacheControl();
425 $this->disable();
426
427 // Don't output a compressed blob when using ob_gzhandler;
428 // it's technically against HTTP spec and seems to confuse
429 // Firefox when the response gets split over two packets.
430 wfClearOutputBuffers();
431
432 return true;
433 }
434
435 function setPageTitleActionText( $text ) {
436 $this->mPageTitleActionText = $text;
437 }
438
439 function getPageTitleActionText () {
440 if ( isset( $this->mPageTitleActionText ) ) {
441 return $this->mPageTitleActionText;
442 }
443 }
444
445 /**
446 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
447 *
448 * @param $policy string The literal string to output as the contents of
449 * the meta tag. Will be parsed according to the spec and output in
450 * standardized form.
451 * @return null
452 */
453 public function setRobotPolicy( $policy ) {
454 $policy = explode( ',', $policy );
455 $policy = array_map( 'trim', $policy );
456
457 # The default policy is follow, so if nothing is said explicitly, we
458 # do that.
459 if( in_array( 'nofollow', $policy ) ) {
460 $this->mFollowPolicy = 'nofollow';
461 } else {
462 $this->mFollowPolicy = 'follow';
463 }
464
465 if( in_array( 'noindex', $policy ) ) {
466 $this->mIndexPolicy = 'noindex';
467 } else {
468 $this->mIndexPolicy = 'index';
469 }
470 }
471
472 /**
473 * Set the index policy for the page, but leave the follow policy un-
474 * touched.
475 *
476 * @param $policy string Either 'index' or 'noindex'.
477 * @return null
478 */
479 public function setIndexPolicy( $policy ) {
480 $policy = trim( $policy );
481 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
482 $this->mIndexPolicy = $policy;
483 }
484 }
485
486 /**
487 * Set the follow policy for the page, but leave the index policy un-
488 * touched.
489 *
490 * @param $policy string Either 'follow' or 'nofollow'.
491 * @return null
492 */
493 public function setFollowPolicy( $policy ) {
494 $policy = trim( $policy );
495 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
496 $this->mFollowPolicy = $policy;
497 }
498 }
499
500 /**
501 * "HTML title" means the contents of <title>. It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
502 */
503 public function setHTMLTitle( $name ) {
504 $this->mHTMLtitle = $name;
505 }
506
507 /**
508 * "Page title" means the contents of <h1>. It is stored as a valid HTML fragment.
509 * This function allows good tags like <sup> in the <h1> tag, but not bad tags like <script>.
510 * This function automatically sets <title> to the same content as <h1> but with all tags removed.
511 * Bad tags that were escaped in <h1> will still be escaped in <title>, and good tags like <i> will be dropped entirely.
512 */
513 public function setPageTitle( $name ) {
514 global $wgContLang;
515 $name = $wgContLang->convert( $name, true );
516 # change "<script>foo&bar</script>" to "&lt;script&gt;foo&amp;bar&lt;/script&gt;"
517 # but leave "<i>foobar</i>" alone
518 $nameWithTags = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags( $name ) );
519 $this->mPagetitle = $nameWithTags;
520
521 $taction = $this->getPageTitleActionText();
522 if( !empty( $taction ) ) {
523 $name .= ' - '.$taction;
524 }
525
526 # change "<i>foo&amp;bar</i>" to "foo&bar"
527 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer::stripAllTags( $nameWithTags ) ) );
528 }
529
530 public function setTitle( $t ) {
531 $this->mTitle = $t;
532 }
533
534 public function getTitle() {
535 if ( $this->mTitle instanceof Title ) {
536 return $this->mTitle;
537 }
538 else {
539 wfDebug( __METHOD__ . ' called and $mTitle is null. Return $wgTitle for sanity' );
540 global $wgTitle;
541 return $wgTitle;
542 }
543 }
544
545 public function getHTMLTitle() { return $this->mHTMLtitle; }
546 public function getPageTitle() { return $this->mPagetitle; }
547 public function setSubtitle( $str ) { $this->mSubtitle = /*$this->parse(*/$str/*)*/; } // @bug 2514
548 public function appendSubtitle( $str ) { $this->mSubtitle .= /*$this->parse(*/$str/*)*/; } // @bug 2514
549 public function getSubtitle() { return $this->mSubtitle; }
550 public function isArticle() { return $this->mIsarticle; }
551 public function setPrintable() { $this->mPrintable = true; }
552 public function isPrintable() { return $this->mPrintable; }
553 public function setSyndicated( $show = true ) { $this->mShowFeedLinks = $show; }
554 public function isSyndicated() { return $this->mShowFeedLinks; }
555 public function setFeedAppendQuery( $val ) { $this->mFeedLinksAppendQuery = $val; }
556 public function getFeedAppendQuery() { return $this->mFeedLinksAppendQuery; }
557 public function setOnloadHandler( $js ) { $this->mOnloadHandler = $js; }
558 public function getOnloadHandler() { return $this->mOnloadHandler; }
559 public function disable() { $this->mDoNothing = true; }
560 public function isDisabled() { return $this->mDoNothing; }
561
562 public function setArticleRelated( $v ) {
563 $this->mIsArticleRelated = $v;
564 if ( !$v ) {
565 $this->mIsarticle = false;
566 }
567 }
568 public function setArticleFlag( $v ) {
569 $this->mIsarticle = $v;
570 if ( $v ) {
571 $this->mIsArticleRelated = $v;
572 }
573 }
574
575 public function isArticleRelated() { return $this->mIsArticleRelated; }
576
577 public function getLanguageLinks() { return $this->mLanguageLinks; }
578 public function addLanguageLinks($newLinkArray) {
579 $this->mLanguageLinks += $newLinkArray;
580 }
581 public function setLanguageLinks($newLinkArray) {
582 $this->mLanguageLinks = $newLinkArray;
583 }
584
585 public function getCategoryLinks() {
586 return $this->mCategoryLinks;
587 }
588
589 /**
590 * Add an array of categories, with names in the keys
591 */
592 public function addCategoryLinks( $categories ) {
593 global $wgUser, $wgContLang;
594
595 if ( !is_array( $categories ) || count( $categories ) == 0 ) {
596 return;
597 }
598
599 # Add the links to a LinkBatch
600 $arr = array( NS_CATEGORY => $categories );
601 $lb = new LinkBatch;
602 $lb->setArray( $arr );
603
604 # Fetch existence plus the hiddencat property
605 $dbr = wfGetDB( DB_SLAVE );
606 $pageTable = $dbr->tableName( 'page' );
607 $where = $lb->constructSet( 'page', $dbr );
608 $propsTable = $dbr->tableName( 'page_props' );
609 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, pp_value
610 FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
611 $res = $dbr->query( $sql, __METHOD__ );
612
613 # Add the results to the link cache
614 $lb->addResultToCache( LinkCache::singleton(), $res );
615
616 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
617 $categories = array_combine( array_keys( $categories ),
618 array_fill( 0, count( $categories ), 'normal' ) );
619
620 # Mark hidden categories
621 foreach ( $res as $row ) {
622 if ( isset( $row->pp_value ) ) {
623 $categories[$row->page_title] = 'hidden';
624 }
625 }
626
627 # Add the remaining categories to the skin
628 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks ) ) ) {
629 $sk = $wgUser->getSkin();
630 foreach ( $categories as $category => $type ) {
631 $origcategory = $category;
632 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
633 $wgContLang->findVariantLink( $category, $title, true );
634 if ( $category != $origcategory )
635 if ( array_key_exists( $category, $categories ) )
636 continue;
637 $text = $wgContLang->convertHtml( $title->getText() );
638 $this->mCategoryLinks[$type][] = $sk->link( $title, $text );
639 }
640 }
641 }
642
643 public function setCategoryLinks($categories) {
644 $this->mCategoryLinks = array();
645 $this->addCategoryLinks($categories);
646 }
647
648 public function suppressQuickbar() { $this->mSuppressQuickbar = true; }
649 public function isQuickbarSuppressed() { return $this->mSuppressQuickbar; }
650
651 public function disallowUserJs() { $this->mAllowUserJs = false; }
652 public function isUserJsAllowed() { return $this->mAllowUserJs; }
653
654 public function prependHTML( $text ) { $this->mBodytext = $text . $this->mBodytext; }
655 public function addHTML( $text ) { $this->mBodytext .= $text; }
656 public function clearHTML() { $this->mBodytext = ''; }
657 public function getHTML() { return $this->mBodytext; }
658 public function debug( $text ) { $this->mDebugtext .= $text; }
659
660 /* @deprecated */
661 public function setParserOptions( $options ) {
662 wfDeprecated( __METHOD__ );
663 return $this->parserOptions( $options );
664 }
665
666 public function parserOptions( $options = null ) {
667 if ( !$this->mParserOptions ) {
668 $this->mParserOptions = new ParserOptions;
669 }
670 return wfSetVar( $this->mParserOptions, $options );
671 }
672
673 /**
674 * Set the revision ID which will be seen by the wiki text parser
675 * for things such as embedded {{REVISIONID}} variable use.
676 * @param mixed $revid an integer, or NULL
677 * @return mixed previous value
678 */
679 public function setRevisionId( $revid ) {
680 $val = is_null( $revid ) ? null : intval( $revid );
681 return wfSetVar( $this->mRevisionId, $val );
682 }
683
684 public function getRevisionId() {
685 return $this->mRevisionId;
686 }
687
688 /**
689 * Convert wikitext to HTML and add it to the buffer
690 * Default assumes that the current page title will
691 * be used.
692 *
693 * @param string $text
694 * @param bool $linestart
695 */
696 public function addWikiText( $text, $linestart = true ) {
697 $title = $this->getTitle(); // Work arround E_STRICT
698 $this->addWikiTextTitle( $text, $title, $linestart );
699 }
700
701 public function addWikiTextWithTitle($text, &$title, $linestart = true) {
702 $this->addWikiTextTitle($text, $title, $linestart);
703 }
704
705 function addWikiTextTitleTidy($text, &$title, $linestart = true) {
706 $this->addWikiTextTitle( $text, $title, $linestart, true );
707 }
708
709 public function addWikiTextTitle($text, &$title, $linestart, $tidy = false) {
710 global $wgParser;
711
712 wfProfileIn( __METHOD__ );
713
714 wfIncrStats( 'pcache_not_possible' );
715
716 $popts = $this->parserOptions();
717 $oldTidy = $popts->setTidy( $tidy );
718
719 $parserOutput = $wgParser->parse( $text, $title, $popts,
720 $linestart, true, $this->mRevisionId );
721
722 $popts->setTidy( $oldTidy );
723
724 $this->addParserOutput( $parserOutput );
725
726 wfProfileOut( __METHOD__ );
727 }
728
729 /**
730 * @todo document
731 * @param ParserOutput object &$parserOutput
732 */
733 public function addParserOutputNoText( &$parserOutput ) {
734 global $wgExemptFromUserRobotsControl, $wgContentNamespaces;
735
736 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
737 $this->addCategoryLinks( $parserOutput->getCategories() );
738 $this->mNewSectionLink = $parserOutput->getNewSection();
739 $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
740
741 if( is_null( $wgExemptFromUserRobotsControl ) ) {
742 $bannedNamespaces = $wgContentNamespaces;
743 } else {
744 $bannedNamespaces = $wgExemptFromUserRobotsControl;
745 }
746 if( !in_array( $this->getTitle()->getNamespace(), $bannedNamespaces ) ) {
747 # FIXME (bug 14900): This overrides $wgArticleRobotPolicies, and it
748 # shouldn't
749 $this->setIndexPolicy( $parserOutput->getIndexPolicy() );
750 }
751
752 $this->mParseWarnings = $parserOutput->getWarnings();
753 if ( $parserOutput->getCacheTime() == -1 ) {
754 $this->enableClientCache( false );
755 }
756 $this->mNoGallery = $parserOutput->getNoGallery();
757 $this->mHeadItems = array_merge( $this->mHeadItems, (array)$parserOutput->mHeadItems );
758 // Versioning...
759 foreach ( (array)$parserOutput->mTemplateIds as $ns => $dbks ) {
760 if ( isset( $this->mTemplateIds[$ns] ) ) {
761 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
762 } else {
763 $this->mTemplateIds[$ns] = $dbks;
764 }
765 }
766 // Page title
767 if( ( $dt = $parserOutput->getDisplayTitle() ) !== false )
768 $this->setPageTitle( $dt );
769 else if ( ( $title = $parserOutput->getTitleText() ) != '' )
770 $this->setPageTitle( $title );
771
772 // Hooks registered in the object
773 global $wgParserOutputHooks;
774 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
775 list( $hookName, $data ) = $hookInfo;
776 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
777 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
778 }
779 }
780
781 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
782 }
783
784 /**
785 * @todo document
786 * @param ParserOutput &$parserOutput
787 */
788 function addParserOutput( &$parserOutput ) {
789 $this->addParserOutputNoText( $parserOutput );
790 $text = $parserOutput->getText();
791 wfRunHooks( 'OutputPageBeforeHTML',array( &$this, &$text ) );
792 $this->addHTML( $text );
793 }
794
795 /**
796 * Add wikitext to the buffer, assuming that this is the primary text for a page view
797 * Saves the text into the parser cache if possible.
798 *
799 * @param string $text
800 * @param Article $article
801 * @param bool $cache
802 * @deprecated Use Article::outputWikitext
803 */
804 public function addPrimaryWikiText( $text, $article, $cache = true ) {
805 global $wgParser;
806
807 wfDeprecated( __METHOD__ );
808
809 $popts = $this->parserOptions();
810 $popts->setTidy(true);
811 $parserOutput = $wgParser->parse( $text, $article->mTitle,
812 $popts, true, true, $this->mRevisionId );
813 $popts->setTidy(false);
814 if ( $cache && $article && $parserOutput->getCacheTime() != -1 ) {
815 $parserCache = ParserCache::singleton();
816 $parserCache->save( $parserOutput, $article, $popts);
817 }
818
819 $this->addParserOutput( $parserOutput );
820 }
821
822 /**
823 * @deprecated use addWikiTextTidy()
824 */
825 public function addSecondaryWikiText( $text, $linestart = true ) {
826 wfDeprecated( __METHOD__ );
827 $this->addWikiTextTitleTidy($text, $this->getTitle(), $linestart);
828 }
829
830 /**
831 * Add wikitext with tidy enabled
832 */
833 public function addWikiTextTidy( $text, $linestart = true ) {
834 $title = $this->getTitle();
835 $this->addWikiTextTitleTidy($text, $title, $linestart);
836 }
837
838
839 /**
840 * Add the output of a QuickTemplate to the output buffer
841 *
842 * @param QuickTemplate $template
843 */
844 public function addTemplate( &$template ) {
845 ob_start();
846 $template->execute();
847 $this->addHTML( ob_get_contents() );
848 ob_end_clean();
849 }
850
851 /**
852 * Parse wikitext and return the HTML.
853 *
854 * @param string $text
855 * @param bool $linestart Is this the start of a line?
856 * @param bool $interface ??
857 */
858 public function parse( $text, $linestart = true, $interface = false ) {
859 global $wgParser;
860 if( is_null( $this->getTitle() ) ) {
861 throw new MWException( 'Empty $mTitle in ' . __METHOD__ );
862 }
863 $popts = $this->parserOptions();
864 if ( $interface) { $popts->setInterfaceMessage(true); }
865 $parserOutput = $wgParser->parse( $text, $this->getTitle(), $popts,
866 $linestart, true, $this->mRevisionId );
867 if ( $interface) { $popts->setInterfaceMessage(false); }
868 return $parserOutput->getText();
869 }
870
871 /** Parse wikitext, strip paragraphs, and return the HTML. */
872 public function parseInline( $text, $linestart = true, $interface = false ) {
873 $parsed = $this->parse( $text, $linestart, $interface );
874
875 $m = array();
876 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
877 $parsed = $m[1];
878 }
879
880 return $parsed;
881 }
882
883 /**
884 * @param Article $article
885 * @param User $user
886 *
887 * @deprecated
888 *
889 * @return bool True if successful, else false.
890 */
891 public function tryParserCache( &$article ) {
892 wfDeprecated( __METHOD__ );
893 $parserOutput = ParserCache::singleton()->get( $article, $article->getParserOptions() );
894
895 if ($parserOutput !== false) {
896 $this->addParserOutput( $parserOutput );
897 return true;
898 } else {
899 return false;
900 }
901 }
902
903 /**
904 * @param int $maxage Maximum cache time on the Squid, in seconds.
905 */
906 public function setSquidMaxage( $maxage ) {
907 $this->mSquidMaxage = $maxage;
908 }
909
910 /**
911 * Use enableClientCache(false) to force it to send nocache headers
912 * @param $state ??
913 */
914 public function enableClientCache( $state ) {
915 return wfSetVar( $this->mEnableClientCache, $state );
916 }
917
918 function getCacheVaryCookies() {
919 global $wgCookiePrefix, $wgCacheVaryCookies;
920 static $cookies;
921 if ( $cookies === null ) {
922 $cookies = array_merge(
923 array(
924 "{$wgCookiePrefix}Token",
925 "{$wgCookiePrefix}LoggedOut",
926 session_name()
927 ),
928 $wgCacheVaryCookies
929 );
930 wfRunHooks('GetCacheVaryCookies', array( $this, &$cookies ) );
931 }
932 return $cookies;
933 }
934
935 function uncacheableBecauseRequestVars() {
936 global $wgRequest;
937 return $wgRequest->getText('useskin', false) === false
938 && $wgRequest->getText('uselang', false) === false;
939 }
940
941 /**
942 * Check if the request has a cache-varying cookie header
943 * If it does, it's very important that we don't allow public caching
944 */
945 function haveCacheVaryCookies() {
946 global $wgRequest;
947 $cookieHeader = $wgRequest->getHeader( 'cookie' );
948 if ( $cookieHeader === false ) {
949 return false;
950 }
951 $cvCookies = $this->getCacheVaryCookies();
952 foreach ( $cvCookies as $cookieName ) {
953 # Check for a simple string match, like the way squid does it
954 if ( strpos( $cookieHeader, $cookieName ) ) {
955 wfDebug( __METHOD__.": found $cookieName\n" );
956 return true;
957 }
958 }
959 wfDebug( __METHOD__.": no cache-varying cookies found\n" );
960 return false;
961 }
962
963 /** Get a complete X-Vary-Options header */
964 public function getXVO() {
965 $cvCookies = $this->getCacheVaryCookies();
966 $xvo = 'X-Vary-Options: Accept-Encoding;list-contains=gzip,Cookie;';
967 $first = true;
968 foreach ( $cvCookies as $cookieName ) {
969 if ( $first ) {
970 $first = false;
971 } else {
972 $xvo .= ';';
973 }
974 $xvo .= 'string-contains=' . $cookieName;
975 }
976 return $xvo;
977 }
978
979 public function sendCacheControl() {
980 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest;
981
982 $response = $wgRequest->response();
983 if ($wgUseETag && $this->mETag)
984 $response->header("ETag: $this->mETag");
985
986 # don't serve compressed data to clients who can't handle it
987 # maintain different caches for logged-in users and non-logged in ones
988 $response->header( 'Vary: Accept-Encoding, Cookie' );
989
990 # Add an X-Vary-Options header for Squid with Wikimedia patches
991 $response->header( $this->getXVO() );
992
993 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache ) {
994 if( $wgUseSquid && session_id() == '' &&
995 ! $this->isPrintable() && $this->mSquidMaxage != 0 && !$this->haveCacheVaryCookies() )
996 {
997 if ( $wgUseESI ) {
998 # We'll purge the proxy cache explicitly, but require end user agents
999 # to revalidate against the proxy on each visit.
1000 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1001 wfDebug( __METHOD__ . ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1002 # start with a shorter timeout for initial testing
1003 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1004 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage.', content="ESI/1.0"');
1005 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1006 } else {
1007 # We'll purge the proxy cache for anons explicitly, but require end user agents
1008 # to revalidate against the proxy on each visit.
1009 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1010 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1011 wfDebug( __METHOD__ . ": local proxy caching; {$this->mLastModified} **\n", false );
1012 # start with a shorter timeout for initial testing
1013 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1014 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage.', must-revalidate, max-age=0' );
1015 }
1016 } else {
1017 # We do want clients to cache if they can, but they *must* check for updates
1018 # on revisiting the page.
1019 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **\n", false );
1020 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1021 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1022 }
1023 if($this->mLastModified) {
1024 $response->header( "Last-Modified: {$this->mLastModified}" );
1025 }
1026 } else {
1027 wfDebug( __METHOD__ . ": no caching **\n", false );
1028
1029 # In general, the absence of a last modified header should be enough to prevent
1030 # the client from using its cache. We send a few other things just to make sure.
1031 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1032 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1033 $response->header( 'Pragma: no-cache' );
1034 }
1035 }
1036
1037 /**
1038 * Finally, all the text has been munged and accumulated into
1039 * the object, let's actually output it:
1040 */
1041 public function output() {
1042 global $wgUser, $wgOutputEncoding, $wgRequest;
1043 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
1044 global $wgJsMimeType, $wgUseAjax, $wgAjaxWatch;
1045 global $wgEnableMWSuggest, $wgUniversalEditButton;
1046 global $wgArticle;
1047
1048 if( $this->mDoNothing ){
1049 return;
1050 }
1051 wfProfileIn( __METHOD__ );
1052 if ( '' != $this->mRedirect ) {
1053 # Standards require redirect URLs to be absolute
1054 $this->mRedirect = wfExpandUrl( $this->mRedirect );
1055 if( $this->mRedirectCode == '301') {
1056 if( !$wgDebugRedirects ) {
1057 $wgRequest->response()->header("HTTP/1.1 {$this->mRedirectCode} Moved Permanently");
1058 }
1059 $this->mLastModified = wfTimestamp( TS_RFC2822 );
1060 }
1061 $this->sendCacheControl();
1062
1063 $wgRequest->response()->header("Content-Type: text/html; charset=utf-8");
1064 if( $wgDebugRedirects ) {
1065 $url = htmlspecialchars( $this->mRedirect );
1066 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1067 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1068 print "</body>\n</html>\n";
1069 } else {
1070 $wgRequest->response()->header( 'Location: '.$this->mRedirect );
1071 }
1072 wfProfileOut( __METHOD__ );
1073 return;
1074 }
1075 elseif ( $this->mStatusCode )
1076 {
1077 $statusMessage = array(
1078 100 => 'Continue',
1079 101 => 'Switching Protocols',
1080 102 => 'Processing',
1081 200 => 'OK',
1082 201 => 'Created',
1083 202 => 'Accepted',
1084 203 => 'Non-Authoritative Information',
1085 204 => 'No Content',
1086 205 => 'Reset Content',
1087 206 => 'Partial Content',
1088 207 => 'Multi-Status',
1089 300 => 'Multiple Choices',
1090 301 => 'Moved Permanently',
1091 302 => 'Found',
1092 303 => 'See Other',
1093 304 => 'Not Modified',
1094 305 => 'Use Proxy',
1095 307 => 'Temporary Redirect',
1096 400 => 'Bad Request',
1097 401 => 'Unauthorized',
1098 402 => 'Payment Required',
1099 403 => 'Forbidden',
1100 404 => 'Not Found',
1101 405 => 'Method Not Allowed',
1102 406 => 'Not Acceptable',
1103 407 => 'Proxy Authentication Required',
1104 408 => 'Request Timeout',
1105 409 => 'Conflict',
1106 410 => 'Gone',
1107 411 => 'Length Required',
1108 412 => 'Precondition Failed',
1109 413 => 'Request Entity Too Large',
1110 414 => 'Request-URI Too Large',
1111 415 => 'Unsupported Media Type',
1112 416 => 'Request Range Not Satisfiable',
1113 417 => 'Expectation Failed',
1114 422 => 'Unprocessable Entity',
1115 423 => 'Locked',
1116 424 => 'Failed Dependency',
1117 500 => 'Internal Server Error',
1118 501 => 'Not Implemented',
1119 502 => 'Bad Gateway',
1120 503 => 'Service Unavailable',
1121 504 => 'Gateway Timeout',
1122 505 => 'HTTP Version Not Supported',
1123 507 => 'Insufficient Storage'
1124 );
1125
1126 if ( $statusMessage[$this->mStatusCode] )
1127 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode . ' ' . $statusMessage[$this->mStatusCode] );
1128 }
1129
1130 $sk = $wgUser->getSkin();
1131
1132 // add our core scripts to output
1133 $this->addCoreScripts2Top();
1134
1135 if ( $wgUseAjax ) {
1136 $this->addScriptFile( 'ajax.js' );
1137
1138 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1139
1140 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1141 $this->addScriptFile( 'ajaxwatch.js' );
1142 }
1143
1144 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ){
1145 $this->addScriptFile( 'mwsuggest.js' );
1146 }
1147 }
1148
1149 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1150 $this->addScriptFile( 'rightclickedit.js' );
1151 }
1152
1153 if( $wgUniversalEditButton ) {
1154 if( isset( $wgArticle ) && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1155 && ( $this->getTitle()->exists() || $this->getTitle()->quickUserCan( 'create' ) ) ) {
1156 // Original UniversalEditButton
1157 $this->addLink( array(
1158 'rel' => 'alternate',
1159 'type' => 'application/x-wiki',
1160 'title' => wfMsg( 'edit' ),
1161 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1162 ) );
1163 // Alternate edit link
1164 $this->addLink( array(
1165 'rel' => 'edit',
1166 'title' => wfMsg( 'edit' ),
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->isRTL() ? 'rtl' : 'ltr';
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\t<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n\t";
1722 $ret .= implode( "\n", array(
1723 $this->getHeadLinks(),
1724 $this->buildCssLinks(),
1725 $sk->getHeadScripts( $this ),
1726 $this->getHeadItems(),
1727 ));
1728 if( $sk->usercss ){
1729 $ret .= "<style type='text/css'>{$sk->usercss}</style>";
1730 }
1731
1732 if( $wgEnableScriptLoader )
1733 $ret .= $this->getScriptLoaderJs();
1734
1735 if ($wgUseTrackbacks && $this->isArticleRelated())
1736 $ret .= $this->getTitle()->trackbackRDF();
1737
1738 $ret .= "</head>\n";
1739 return $ret;
1740 }
1741
1742 protected function addDefaultMeta() {
1743 global $wgVersion, $wgHtml5;
1744
1745 static $called = false;
1746 if ( $called ) {
1747 # Don't run this twice
1748 return;
1749 }
1750 $called = true;
1751
1752 if ( !$wgHtml5 ) {
1753 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); //bug 15835
1754 }
1755 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
1756
1757 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
1758 if( $p !== 'index,follow' ) {
1759 // http://www.robotstxt.org/wc/meta-user.html
1760 // Only show if it's different from the default robots policy
1761 $this->addMeta( 'robots', $p );
1762 }
1763
1764 if ( count( $this->mKeywords ) > 0 ) {
1765 $strip = array(
1766 "/<.*?" . ">/" => '',
1767 "/_/" => ' '
1768 );
1769 $this->addMeta( 'keywords', preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords ) ) );
1770 }
1771 }
1772
1773 /**
1774 * @return string HTML tag links to be put in the header.
1775 */
1776 public function getHeadLinks() {
1777 global $wgRequest, $wgFeed;
1778
1779 // Ideally this should happen earlier, somewhere. :P
1780 $this->addDefaultMeta();
1781
1782 $tags = array();
1783
1784 foreach ( $this->mMetatags as $tag ) {
1785 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
1786 $a = 'http-equiv';
1787 $tag[0] = substr( $tag[0], 5 );
1788 } else {
1789 $a = 'name';
1790 }
1791 $tags[] = Xml::element( 'meta',
1792 array(
1793 $a => $tag[0],
1794 'content' => $tag[1] ) );
1795 }
1796 foreach ( $this->mLinktags as $tag ) {
1797 $tags[] = Xml::element( 'link', $tag );
1798 }
1799
1800 if( $wgFeed ) {
1801 foreach( $this->getSyndicationLinks() as $format => $link ) {
1802 # Use the page name for the title (accessed through $wgTitle since
1803 # there's no other way). In principle, this could lead to issues
1804 # with having the same name for different feeds corresponding to
1805 # the same page, but we can't avoid that at this low a level.
1806
1807 $tags[] = $this->feedLink(
1808 $format,
1809 $link,
1810 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() ) ); # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
1811 }
1812
1813 # Recent changes feed should appear on every page (except recentchanges,
1814 # that would be redundant). Put it after the per-page feed to avoid
1815 # changing existing behavior. It's still available, probably via a
1816 # menu in your browser. Some sites might have a different feed they'd
1817 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
1818 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
1819 # If so, use it instead.
1820
1821 global $wgOverrideSiteFeed, $wgSitename, $wgFeedClasses;
1822 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
1823
1824 if ( $wgOverrideSiteFeed ) {
1825 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
1826 $tags[] = $this->feedLink (
1827 $type,
1828 htmlspecialchars( $feedUrl ),
1829 wfMsg( "site-{$type}-feed", $wgSitename ) );
1830 }
1831 }
1832 else if ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
1833 foreach( $wgFeedClasses as $format => $class ) {
1834 $tags[] = $this->feedLink(
1835 $format,
1836 $rctitle->getLocalURL( "feed={$format}" ),
1837 wfMsg( "site-{$format}-feed", $wgSitename ) ); # For grep: 'site-rss-feed', 'site-atom-feed'.
1838 }
1839 }
1840 }
1841
1842 return implode( "\n\t", $tags ) . "\n";
1843 }
1844
1845 /**
1846 * Return URLs for each supported syndication format for this page.
1847 * @return array associating format keys with URLs
1848 */
1849 public function getSyndicationLinks() {
1850 global $wgFeedClasses;
1851 $links = array();
1852
1853 if( $this->isSyndicated() ) {
1854 if( is_string( $this->getFeedAppendQuery() ) ) {
1855 $appendQuery = "&" . $this->getFeedAppendQuery();
1856 } else {
1857 $appendQuery = "";
1858 }
1859
1860 foreach( $wgFeedClasses as $format => $class ) {
1861 $links[$format] = $this->getTitle()->getLocalUrl( "feed=$format{$appendQuery}" );
1862 }
1863 }
1864 return $links;
1865 }
1866
1867 /**
1868 * Generate a <link rel/> for an RSS feed.
1869 */
1870 private function feedLink( $type, $url, $text ) {
1871 return Xml::element( 'link', array(
1872 'rel' => 'alternate',
1873 'type' => "application/$type+xml",
1874 'title' => $text,
1875 'href' => $url ) );
1876 }
1877
1878 /**
1879 * Add a local or specified stylesheet, with the given media options.
1880 * Meant primarily for internal use...
1881 *
1882 * @param $media -- to specify a media type, 'screen', 'printable', 'handheld' or any.
1883 * @param $conditional -- for IE conditional comments, specifying an IE version
1884 * @param $dir -- set to 'rtl' or 'ltr' for direction-specific sheets
1885 */
1886 public function addStyle( $style, $media='', $condition='', $dir='' ) {
1887 $options = array();
1888 if( $media )
1889 $options['media'] = $media;
1890 if( $condition )
1891 $options['condition'] = $condition;
1892 if( $dir )
1893 $options['dir'] = $dir;
1894 $this->styles[$style] = $options;
1895 }
1896
1897 /**
1898 * Adds inline CSS styles
1899 * @param $style_css Mixed: inline CSS
1900 */
1901 public function addInlineStyle( $style_css ){
1902 $this->mScripts .= "<style type=\"text/css\">$style_css</style>";
1903 }
1904
1905 /**
1906 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
1907 * These will be applied to various media & IE conditionals.
1908 */
1909 public function buildCssLinks() {
1910 $links = array();
1911 foreach( $this->styles as $file => $options ) {
1912 $link = $this->styleLink( $file, $options );
1913 if( $link )
1914 $links[] = $link;
1915 }
1916
1917 return "\t" . implode( "\n\t", $links );
1918 }
1919
1920 protected function styleLink( $style, $options ) {
1921 global $wgRequest;
1922
1923 if( isset( $options['dir'] ) ) {
1924 global $wgContLang;
1925 $siteDir = $wgContLang->isRTL() ? 'rtl' : 'ltr';
1926 if( $siteDir != $options['dir'] )
1927 return '';
1928 }
1929
1930 if( isset( $options['media'] ) ) {
1931 $media = $this->transformCssMedia( $options['media'] );
1932 if( is_null( $media ) ) {
1933 return '';
1934 }
1935 } else {
1936 $media = '';
1937 }
1938
1939 if( substr( $style, 0, 1 ) == '/' ||
1940 substr( $style, 0, 5 ) == 'http:' ||
1941 substr( $style, 0, 6 ) == 'https:' ) {
1942 $url = $style;
1943 } else {
1944 global $wgStylePath, $wgStyleVersion;
1945 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
1946 }
1947
1948 $attribs = array(
1949 'rel' => 'stylesheet',
1950 'href' => $url,
1951 'type' => 'text/css' );
1952 if( $media ) {
1953 $attribs['media'] = $media;
1954 }
1955
1956 $link = Xml::element( 'link', $attribs );
1957
1958 if( isset( $options['condition'] ) ) {
1959 $condition = htmlspecialchars( $options['condition'] );
1960 $link = "<!--[if $condition]>$link<![endif]-->";
1961 }
1962 return $link;
1963 }
1964
1965 function transformCssMedia( $media ) {
1966 global $wgRequest, $wgHandheldForIPhone;
1967
1968 // Switch in on-screen display for media testing
1969 $switches = array(
1970 'printable' => 'print',
1971 'handheld' => 'handheld',
1972 );
1973 foreach( $switches as $switch => $targetMedia ) {
1974 if( $wgRequest->getBool( $switch ) ) {
1975 if( $media == $targetMedia ) {
1976 $media = '';
1977 } elseif( $media == 'screen' ) {
1978 return null;
1979 }
1980 }
1981 }
1982
1983 // Expand longer media queries as iPhone doesn't grok 'handheld'
1984 if( $wgHandheldForIPhone ) {
1985 $mediaAliases = array(
1986 'screen' => 'screen and (min-device-width: 481px)',
1987 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
1988 );
1989
1990 if( isset( $mediaAliases[$media] ) ) {
1991 $media = $mediaAliases[$media];
1992 }
1993 }
1994
1995 return $media;
1996 }
1997
1998 /**
1999 * Turn off regular page output and return an error reponse
2000 * for when rate limiting has triggered.
2001 */
2002 public function rateLimited() {
2003
2004 $this->setPageTitle(wfMsg('actionthrottled'));
2005 $this->setRobotPolicy( 'noindex,follow' );
2006 $this->setArticleRelated( false );
2007 $this->enableClientCache( false );
2008 $this->mRedirect = '';
2009 $this->clearHTML();
2010 $this->setStatusCode(503);
2011 $this->addWikiMsg( 'actionthrottledtext' );
2012
2013 $this->returnToMain( null, $this->getTitle() );
2014 }
2015
2016 /**
2017 * Show an "add new section" link?
2018 *
2019 * @return bool
2020 */
2021 public function showNewSectionLink() {
2022 return $this->mNewSectionLink;
2023 }
2024
2025 /**
2026 * Forcibly hide the new section link?
2027 *
2028 * @return bool
2029 */
2030 public function forceHideNewSectionLink() {
2031 return $this->mHideNewSectionLink;
2032 }
2033
2034 /**
2035 * Show a warning about slave lag
2036 *
2037 * If the lag is higher than $wgSlaveLagCritical seconds,
2038 * then the warning is a bit more obvious. If the lag is
2039 * lower than $wgSlaveLagWarning, then no warning is shown.
2040 *
2041 * @param int $lag Slave lag
2042 */
2043 public function showLagWarning( $lag ) {
2044 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2045 if( $lag >= $wgSlaveLagWarning ) {
2046 $message = $lag < $wgSlaveLagCritical
2047 ? 'lag-warn-normal'
2048 : 'lag-warn-high';
2049 $warning = wfMsgExt( $message, 'parse', $lag );
2050 $this->addHTML( "<div class=\"mw-{$message}\">\n{$warning}\n</div>\n" );
2051 }
2052 }
2053
2054 /**
2055 * Add a wikitext-formatted message to the output.
2056 * This is equivalent to:
2057 *
2058 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2059 */
2060 public function addWikiMsg( /*...*/ ) {
2061 $args = func_get_args();
2062 $name = array_shift( $args );
2063 $this->addWikiMsgArray( $name, $args );
2064 }
2065
2066 /**
2067 * Add a wikitext-formatted message to the output.
2068 * Like addWikiMsg() except the parameters are taken as an array
2069 * instead of a variable argument list.
2070 *
2071 * $options is passed through to wfMsgExt(), see that function for details.
2072 */
2073 public function addWikiMsgArray( $name, $args, $options = array() ) {
2074 $options[] = 'parse';
2075 $text = wfMsgExt( $name, $options, $args );
2076 $this->addHTML( $text );
2077 }
2078
2079 /**
2080 * This function takes a number of message/argument specifications, wraps them in
2081 * some overall structure, and then parses the result and adds it to the output.
2082 *
2083 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
2084 * on. The subsequent arguments may either be strings, in which case they are the
2085 * message names, or arrays, in which case the first element is the message name,
2086 * and subsequent elements are the parameters to that message.
2087 *
2088 * The special named parameter 'options' in a message specification array is passed
2089 * through to the $options parameter of wfMsgExt().
2090 *
2091 * Don't use this for messages that are not in users interface language.
2092 *
2093 * For example:
2094 *
2095 * $wgOut->wrapWikiMsg( '<div class="error">$1</div>', 'some-error' );
2096 *
2097 * Is equivalent to:
2098 *
2099 * $wgOut->addWikiText( '<div class="error">' . wfMsgNoTrans( 'some-error' ) . '</div>' );
2100 */
2101 public function wrapWikiMsg( $wrap /*, ...*/ ) {
2102 $msgSpecs = func_get_args();
2103 array_shift( $msgSpecs );
2104 $msgSpecs = array_values( $msgSpecs );
2105 $s = $wrap;
2106 foreach ( $msgSpecs as $n => $spec ) {
2107 $options = array();
2108 if ( is_array( $spec ) ) {
2109 $args = $spec;
2110 $name = array_shift( $args );
2111 if ( isset( $args['options'] ) ) {
2112 $options = $args['options'];
2113 unset( $args['options'] );
2114 }
2115 } else {
2116 $args = array();
2117 $name = $spec;
2118 }
2119 $s = str_replace( '$' . ( $n + 1 ), wfMsgExt( $name, $options, $args ), $s );
2120 }
2121 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );
2122 }
2123 }