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