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