UniversalEditButton microoptimization :)
[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 $msg = wfMsg('edit');
1124 $this->addLink( array(
1125 'rel' => 'alternate',
1126 'type' => 'application/x-wiki',
1127 'title' => $msg,
1128 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1129 ) );
1130 // Alternate edit link
1131 $this->addLink( array(
1132 'rel' => 'edit',
1133 'title' => $msg,
1134 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1135 ) );
1136 }
1137 }
1138
1139 # Buffer output; final headers may depend on later processing
1140 ob_start();
1141
1142 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1143 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
1144
1145 if ($this->mArticleBodyOnly) {
1146 $this->out($this->mBodytext);
1147 } else {
1148 // Hook that allows last minute changes to the output page, e.g.
1149 // adding of CSS or Javascript by extensions.
1150 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1151
1152 wfProfileIn( 'Output-skin' );
1153 $sk->outputPage( $this );
1154 wfProfileOut( 'Output-skin' );
1155 }
1156
1157 $this->sendCacheControl();
1158 ob_end_flush();
1159 wfProfileOut( __METHOD__ );
1160 }
1161
1162 /**
1163 * Actually output something with print(). Performs an iconv to the
1164 * output encoding, if needed.
1165 * @param string $ins The string to output
1166 */
1167 public function out( $ins ) {
1168 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1169 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1170 $outs = $ins;
1171 } else {
1172 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1173 if ( false === $outs ) { $outs = $ins; }
1174 }
1175 print $outs;
1176 }
1177
1178 /**
1179 * @todo document
1180 */
1181 public static function setEncodings() {
1182 global $wgInputEncoding, $wgOutputEncoding;
1183 global $wgContLang;
1184
1185 $wgInputEncoding = strtolower( $wgInputEncoding );
1186
1187 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
1188 $wgOutputEncoding = strtolower( $wgOutputEncoding );
1189 return;
1190 }
1191 $wgOutputEncoding = $wgInputEncoding;
1192 }
1193
1194 /**
1195 * Deprecated, use wfReportTime() instead.
1196 * @return string
1197 * @deprecated
1198 */
1199 public function reportTime() {
1200 wfDeprecated( __METHOD__ );
1201 $time = wfReportTime();
1202 return $time;
1203 }
1204
1205 /**
1206 * Produce a "user is blocked" page.
1207 *
1208 * @param bool $return Whether to have a "return to $wgTitle" message or not.
1209 * @return nothing
1210 */
1211 function blockedPage( $return = true ) {
1212 global $wgUser, $wgContLang, $wgLang;
1213
1214 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1215 $this->setRobotPolicy( 'noindex,nofollow' );
1216 $this->setArticleRelated( false );
1217
1218 $name = User::whoIs( $wgUser->blockedBy() );
1219 $reason = $wgUser->blockedFor();
1220 if( $reason == '' ) {
1221 $reason = wfMsg( 'blockednoreason' );
1222 }
1223 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW, $wgUser->mBlock->mTimestamp ), true );
1224 $ip = wfGetIP();
1225
1226 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
1227
1228 $blockid = $wgUser->mBlock->mId;
1229
1230 $blockExpiry = $wgUser->mBlock->mExpiry;
1231 if ( $blockExpiry == 'infinity' ) {
1232 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1233 // Search for localization in 'ipboptions'
1234 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1235 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1236 if ( strpos( $option, ":" ) === false )
1237 continue;
1238 list( $show, $value ) = explode( ":", $option );
1239 if ( $value == 'infinite' || $value == 'indefinite' ) {
1240 $blockExpiry = $show;
1241 break;
1242 }
1243 }
1244 } else {
1245 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW, $blockExpiry ), true );
1246 }
1247
1248 if ( $wgUser->mBlock->mAuto ) {
1249 $msg = 'autoblockedtext';
1250 } else {
1251 $msg = 'blockedtext';
1252 }
1253
1254 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1255 * This could be a username, an ip range, or a single ip. */
1256 $intended = $wgUser->mBlock->mAddress;
1257
1258 $this->addWikiMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
1259
1260 # Don't auto-return to special pages
1261 if( $return ) {
1262 $return = $this->getTitle()->getNamespace() > -1 ? $this->getTitle() : null;
1263 $this->returnToMain( null, $return );
1264 }
1265 }
1266
1267 /**
1268 * Output a standard error page
1269 *
1270 * @param string $title Message key for page title
1271 * @param string $msg Message key for page text
1272 * @param array $params Message parameters
1273 */
1274 public function showErrorPage( $title, $msg, $params = array() ) {
1275 if ( $this->getTitle() ) {
1276 $this->mDebugtext .= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1277 }
1278 $this->setPageTitle( wfMsg( $title ) );
1279 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1280 $this->setRobotPolicy( 'noindex,nofollow' );
1281 $this->setArticleRelated( false );
1282 $this->enableClientCache( false );
1283 $this->mRedirect = '';
1284 $this->mBodytext = '';
1285
1286 array_unshift( $params, 'parse' );
1287 array_unshift( $params, $msg );
1288 $this->addHTML( call_user_func_array( 'wfMsgExt', $params ) );
1289
1290 $this->returnToMain();
1291 }
1292
1293 /**
1294 * Output a standard permission error page
1295 *
1296 * @param array $errors Error message keys
1297 */
1298 public function showPermissionsErrorPage( $errors, $action = null )
1299 {
1300 $this->mDebugtext .= 'Original title: ' .
1301 $this->getTitle()->getPrefixedText() . "\n";
1302 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1303 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1304 $this->setRobotPolicy( 'noindex,nofollow' );
1305 $this->setArticleRelated( false );
1306 $this->enableClientCache( false );
1307 $this->mRedirect = '';
1308 $this->mBodytext = '';
1309 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1310 }
1311
1312 /** @deprecated */
1313 public function errorpage( $title, $msg ) {
1314 wfDeprecated( __METHOD__ );
1315 throw new ErrorPageError( $title, $msg );
1316 }
1317
1318 /**
1319 * Display an error page indicating that a given version of MediaWiki is
1320 * required to use it
1321 *
1322 * @param mixed $version The version of MediaWiki needed to use the page
1323 */
1324 public function versionRequired( $version ) {
1325 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1326 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1327 $this->setRobotPolicy( 'noindex,nofollow' );
1328 $this->setArticleRelated( false );
1329 $this->mBodytext = '';
1330
1331 $this->addWikiMsg( 'versionrequiredtext', $version );
1332 $this->returnToMain();
1333 }
1334
1335 /**
1336 * Display an error page noting that a given permission bit is required.
1337 *
1338 * @param string $permission key required
1339 */
1340 public function permissionRequired( $permission ) {
1341 global $wgLang;
1342
1343 $this->setPageTitle( wfMsg( 'badaccess' ) );
1344 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1345 $this->setRobotPolicy( 'noindex,nofollow' );
1346 $this->setArticleRelated( false );
1347 $this->mBodytext = '';
1348
1349 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1350 User::getGroupsWithPermission( $permission ) );
1351 if( $groups ) {
1352 $this->addWikiMsg( 'badaccess-groups',
1353 $wgLang->commaList( $groups ),
1354 count( $groups) );
1355 } else {
1356 $this->addWikiMsg( 'badaccess-group0' );
1357 }
1358 $this->returnToMain();
1359 }
1360
1361 /**
1362 * Use permissionRequired.
1363 * @deprecated
1364 */
1365 public function sysopRequired() {
1366 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
1367 }
1368
1369 /**
1370 * Use permissionRequired.
1371 * @deprecated
1372 */
1373 public function developerRequired() {
1374 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
1375 }
1376
1377 /**
1378 * Produce the stock "please login to use the wiki" page
1379 */
1380 public function loginToUse() {
1381 global $wgUser, $wgContLang;
1382
1383 if( $wgUser->isLoggedIn() ) {
1384 $this->permissionRequired( 'read' );
1385 return;
1386 }
1387
1388 $skin = $wgUser->getSkin();
1389
1390 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1391 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1392 $this->setRobotPolicy( 'noindex,nofollow' );
1393 $this->setArticleFlag( false );
1394
1395 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
1396 $loginLink = $skin->link(
1397 $loginTitle,
1398 wfMsgHtml( 'loginreqlink' ),
1399 array(),
1400 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
1401 array( 'known', 'noclasses' )
1402 );
1403 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1404 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . "-->" );
1405
1406 # Don't return to the main page if the user can't read it
1407 # otherwise we'll end up in a pointless loop
1408 $mainPage = Title::newMainPage();
1409 if( $mainPage->userCanRead() )
1410 $this->returnToMain( null, $mainPage );
1411 }
1412
1413 /** @deprecated */
1414 public function databaseError( $fname, $sql, $error, $errno ) {
1415 throw new MWException( "OutputPage::databaseError is obsolete\n" );
1416 }
1417
1418 /**
1419 * @param array $errors An array of arrays returned by Title::getUserPermissionsErrors
1420 * @return string The wikitext error-messages, formatted into a list.
1421 */
1422 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1423 if ($action == null) {
1424 $text = wfMsgNoTrans( 'permissionserrorstext', count($errors)). "\n\n";
1425 } else {
1426 global $wgLang;
1427 $action_desc = wfMsgNoTrans( "action-$action" );
1428 $text = wfMsgNoTrans( 'permissionserrorstext-withaction', count($errors), $action_desc ) . "\n\n";
1429 }
1430
1431 if (count( $errors ) > 1) {
1432 $text .= '<ul class="permissions-errors">' . "\n";
1433
1434 foreach( $errors as $error )
1435 {
1436 $text .= '<li>';
1437 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1438 $text .= "</li>\n";
1439 }
1440 $text .= '</ul>';
1441 } else {
1442 $text .= "<div class=\"permissions-errors\">\n" . call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) . "\n</div>";
1443 }
1444
1445 return $text;
1446 }
1447
1448 /**
1449 * Display a page stating that the Wiki is in read-only mode,
1450 * and optionally show the source of the page that the user
1451 * was trying to edit. Should only be called (for this
1452 * purpose) after wfReadOnly() has returned true.
1453 *
1454 * For historical reasons, this function is _also_ used to
1455 * show the error message when a user tries to edit a page
1456 * they are not allowed to edit. (Unless it's because they're
1457 * blocked, then we show blockedPage() instead.) In this
1458 * case, the second parameter should be set to true and a list
1459 * of reasons supplied as the third parameter.
1460 *
1461 * @todo Needs to be split into multiple functions.
1462 *
1463 * @param string $source Source code to show (or null).
1464 * @param bool $protected Is this a permissions error?
1465 * @param array $reasons List of reasons for this error, as returned by Title::getUserPermissionsErrors().
1466 */
1467 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1468 global $wgUser;
1469 $skin = $wgUser->getSkin();
1470
1471 $this->setRobotPolicy( 'noindex,nofollow' );
1472 $this->setArticleRelated( false );
1473
1474 // If no reason is given, just supply a default "I can't let you do
1475 // that, Dave" message. Should only occur if called by legacy code.
1476 if ( $protected && empty($reasons) ) {
1477 $reasons[] = array( 'badaccess-group0' );
1478 }
1479
1480 if ( !empty($reasons) ) {
1481 // Permissions error
1482 if( $source ) {
1483 $this->setPageTitle( wfMsg( 'viewsource' ) );
1484 $this->setSubtitle(
1485 wfMsg(
1486 'viewsourcefor',
1487 $skin->link(
1488 $this->getTitle(),
1489 null,
1490 array(),
1491 array(),
1492 array( 'known', 'noclasses' )
1493 )
1494 )
1495 );
1496 } else {
1497 $this->setPageTitle( wfMsg( 'badaccess' ) );
1498 }
1499 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1500 } else {
1501 // Wiki is read only
1502 $this->setPageTitle( wfMsg( 'readonly' ) );
1503 $reason = wfReadOnlyReason();
1504 $this->wrapWikiMsg( '<div class="mw-readonly-error">$1</div>', array( 'readonlytext', $reason ) );
1505 }
1506
1507 // Show source, if supplied
1508 if( is_string( $source ) ) {
1509 $this->addWikiMsg( 'viewsourcetext' );
1510 $text = Xml::openElement( 'textarea',
1511 array( 'id' => 'wpTextbox1',
1512 'name' => 'wpTextbox1',
1513 'cols' => $wgUser->getOption( 'cols' ),
1514 'rows' => $wgUser->getOption( 'rows' ),
1515 'readonly' => 'readonly' ) );
1516 $text .= htmlspecialchars( $source );
1517 $text .= Xml::closeElement( 'textarea' );
1518 $this->addHTML( $text );
1519
1520 // Show templates used by this article
1521 $skin = $wgUser->getSkin();
1522 $article = new Article( $this->getTitle() );
1523 $this->addHTML( "<div class='templatesUsed'>
1524 {$skin->formatTemplates( $article->getUsedTemplates() )}
1525 </div>
1526 " );
1527 }
1528
1529 # If the title doesn't exist, it's fairly pointless to print a return
1530 # link to it. After all, you just tried editing it and couldn't, so
1531 # what's there to do there?
1532 if( $this->getTitle()->exists() ) {
1533 $this->returnToMain( null, $this->getTitle() );
1534 }
1535 }
1536
1537 /** @deprecated */
1538 public function fatalError( $message ) {
1539 wfDeprecated( __METHOD__ );
1540 throw new FatalError( $message );
1541 }
1542
1543 /** @deprecated */
1544 public function unexpectedValueError( $name, $val ) {
1545 wfDeprecated( __METHOD__ );
1546 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1547 }
1548
1549 /** @deprecated */
1550 public function fileCopyError( $old, $new ) {
1551 wfDeprecated( __METHOD__ );
1552 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1553 }
1554
1555 /** @deprecated */
1556 public function fileRenameError( $old, $new ) {
1557 wfDeprecated( __METHOD__ );
1558 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1559 }
1560
1561 /** @deprecated */
1562 public function fileDeleteError( $name ) {
1563 wfDeprecated( __METHOD__ );
1564 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1565 }
1566
1567 /** @deprecated */
1568 public function fileNotFoundError( $name ) {
1569 wfDeprecated( __METHOD__ );
1570 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1571 }
1572
1573 public function showFatalError( $message ) {
1574 $this->setPageTitle( wfMsg( "internalerror" ) );
1575 $this->setRobotPolicy( "noindex,nofollow" );
1576 $this->setArticleRelated( false );
1577 $this->enableClientCache( false );
1578 $this->mRedirect = '';
1579 $this->mBodytext = $message;
1580 }
1581
1582 public function showUnexpectedValueError( $name, $val ) {
1583 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
1584 }
1585
1586 public function showFileCopyError( $old, $new ) {
1587 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
1588 }
1589
1590 public function showFileRenameError( $old, $new ) {
1591 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
1592 }
1593
1594 public function showFileDeleteError( $name ) {
1595 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
1596 }
1597
1598 public function showFileNotFoundError( $name ) {
1599 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1600 }
1601
1602 /**
1603 * Add a "return to" link pointing to a specified title
1604 *
1605 * @param Title $title Title to link
1606 * @param string $query Query string
1607 */
1608 public function addReturnTo( $title, $query = array() ) {
1609 global $wgUser;
1610 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullUrl() ) );
1611 $link = wfMsgHtml( 'returnto', $wgUser->getSkin()->link(
1612 $title, null, array(), $query ) );
1613 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
1614 }
1615
1616 /**
1617 * Add a "return to" link pointing to a specified title,
1618 * or the title indicated in the request, or else the main page
1619 *
1620 * @param null $unused No longer used
1621 * @param Title $returnto Title to return to
1622 */
1623 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
1624 global $wgRequest;
1625
1626 if ( $returnto == null ) {
1627 $returnto = $wgRequest->getText( 'returnto' );
1628 }
1629
1630 if ( $returntoquery == null ) {
1631 $returntoquery = $wgRequest->getText( 'returntoquery' );
1632 }
1633
1634 if ( '' === $returnto ) {
1635 $returnto = Title::newMainPage();
1636 }
1637
1638 if ( is_object( $returnto ) ) {
1639 $titleObj = $returnto;
1640 } else {
1641 $titleObj = Title::newFromText( $returnto );
1642 }
1643 if ( !is_object( $titleObj ) ) {
1644 $titleObj = Title::newMainPage();
1645 }
1646
1647 $this->addReturnTo( $titleObj, $returntoquery );
1648 }
1649
1650 /**
1651 * @return string The doctype, opening <html>, and head element.
1652 */
1653 public function headElement( Skin $sk ) {
1654 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1655 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces;
1656 global $wgContLang, $wgUseTrackbacks, $wgStyleVersion, $wgEnableScriptLoader, $wgHtml5;
1657
1658 $this->addMeta( "http:Content-Type", "$wgMimeType; charset={$wgOutputEncoding}" );
1659 if ( $sk->commonPrintStylesheet() ) {
1660 $this->addStyle( 'common/wikiprintable.css', 'print' );
1661 }
1662 $sk->setupUserCss( $this );
1663
1664 $ret = '';
1665
1666 if( $wgMimeType == 'text/xml' || $wgMimeType == 'application/xhtml+xml' || $wgMimeType == 'application/xml' ) {
1667 $ret .= "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?" . ">\n";
1668 }
1669
1670 if ( '' == $this->getHTMLTitle() ) {
1671 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1672 }
1673
1674 $dir = $wgContLang->getDir();
1675
1676 if ( $wgHtml5 ) {
1677 $ret .= "<!doctype html>\n";
1678 $ret .= "<html lang=\"$wgContLanguageCode\" dir=\"$dir\">\n";
1679 } else {
1680 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\" \"$wgDTD\">\n";
1681 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1682 foreach($wgXhtmlNamespaces as $tag => $ns) {
1683 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1684 }
1685 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" dir=\"$dir\">\n";
1686 }
1687
1688 $ret .= "<head>\n";
1689 $ret .= "<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n";
1690 $ret .= implode( "\n", array(
1691 $this->getHeadLinks(),
1692 $this->buildCssLinks(),
1693 $sk->getHeadScripts( $this ),
1694 $this->getHeadItems(),
1695 ));
1696 if( $sk->usercss ){
1697 $ret .= Html::inlineStyle( $sk->usercss );
1698 }
1699
1700 if( $wgEnableScriptLoader )
1701 $ret .= $this->getScriptLoaderJs();
1702
1703 if ($wgUseTrackbacks && $this->isArticleRelated())
1704 $ret .= $this->getTitle()->trackbackRDF();
1705
1706 $ret .= "</head>\n";
1707 return $ret;
1708 }
1709
1710 protected function addDefaultMeta() {
1711 global $wgVersion, $wgHtml5;
1712
1713 static $called = false;
1714 if ( $called ) {
1715 # Don't run this twice
1716 return;
1717 }
1718 $called = true;
1719
1720 if ( !$wgHtml5 ) {
1721 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); //bug 15835
1722 }
1723 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
1724
1725 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
1726 if( $p !== 'index,follow' ) {
1727 // http://www.robotstxt.org/wc/meta-user.html
1728 // Only show if it's different from the default robots policy
1729 $this->addMeta( 'robots', $p );
1730 }
1731
1732 if ( count( $this->mKeywords ) > 0 ) {
1733 $strip = array(
1734 "/<.*?" . ">/" => '',
1735 "/_/" => ' '
1736 );
1737 $this->addMeta( 'keywords', preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords ) ) );
1738 }
1739 }
1740
1741 /**
1742 * @return string HTML tag links to be put in the header.
1743 */
1744 public function getHeadLinks() {
1745 global $wgRequest, $wgFeed;
1746
1747 // Ideally this should happen earlier, somewhere. :P
1748 $this->addDefaultMeta();
1749
1750 $tags = array();
1751
1752 foreach ( $this->mMetatags as $tag ) {
1753 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
1754 $a = 'http-equiv';
1755 $tag[0] = substr( $tag[0], 5 );
1756 } else {
1757 $a = 'name';
1758 }
1759 $tags[] = Xml::element( 'meta',
1760 array(
1761 $a => $tag[0],
1762 'content' => $tag[1] ) );
1763 }
1764 foreach ( $this->mLinktags as $tag ) {
1765 $tags[] = Xml::element( 'link', $tag );
1766 }
1767
1768 if( $wgFeed ) {
1769 foreach( $this->getSyndicationLinks() as $format => $link ) {
1770 # Use the page name for the title (accessed through $wgTitle since
1771 # there's no other way). In principle, this could lead to issues
1772 # with having the same name for different feeds corresponding to
1773 # the same page, but we can't avoid that at this low a level.
1774
1775 $tags[] = $this->feedLink(
1776 $format,
1777 $link,
1778 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() ) ); # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
1779 }
1780
1781 # Recent changes feed should appear on every page (except recentchanges,
1782 # that would be redundant). Put it after the per-page feed to avoid
1783 # changing existing behavior. It's still available, probably via a
1784 # menu in your browser. Some sites might have a different feed they'd
1785 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
1786 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
1787 # If so, use it instead.
1788
1789 global $wgOverrideSiteFeed, $wgSitename, $wgFeedClasses;
1790 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
1791
1792 if ( $wgOverrideSiteFeed ) {
1793 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
1794 $tags[] = $this->feedLink (
1795 $type,
1796 htmlspecialchars( $feedUrl ),
1797 wfMsg( "site-{$type}-feed", $wgSitename ) );
1798 }
1799 }
1800 else if ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
1801 foreach( $wgFeedClasses as $format => $class ) {
1802 $tags[] = $this->feedLink(
1803 $format,
1804 $rctitle->getLocalURL( "feed={$format}" ),
1805 wfMsg( "site-{$format}-feed", $wgSitename ) ); # For grep: 'site-rss-feed', 'site-atom-feed'.
1806 }
1807 }
1808 }
1809
1810 return implode( "\n", $tags ) . "\n";
1811 }
1812
1813 /**
1814 * Return URLs for each supported syndication format for this page.
1815 * @return array associating format keys with URLs
1816 */
1817 public function getSyndicationLinks() {
1818 global $wgFeedClasses;
1819 $links = array();
1820
1821 if( $this->isSyndicated() ) {
1822 if( is_string( $this->getFeedAppendQuery() ) ) {
1823 $appendQuery = "&" . $this->getFeedAppendQuery();
1824 } else {
1825 $appendQuery = "";
1826 }
1827
1828 foreach( $wgFeedClasses as $format => $class ) {
1829 $links[$format] = $this->getTitle()->getLocalUrl( "feed=$format{$appendQuery}" );
1830 }
1831 }
1832 return $links;
1833 }
1834
1835 /**
1836 * Generate a <link rel/> for an RSS feed.
1837 */
1838 private function feedLink( $type, $url, $text ) {
1839 return Xml::element( 'link', array(
1840 'rel' => 'alternate',
1841 'type' => "application/$type+xml",
1842 'title' => $text,
1843 'href' => $url ) );
1844 }
1845
1846 /**
1847 * Add a local or specified stylesheet, with the given media options.
1848 * Meant primarily for internal use...
1849 *
1850 * @param $media -- to specify a media type, 'screen', 'printable', 'handheld' or any.
1851 * @param $conditional -- for IE conditional comments, specifying an IE version
1852 * @param $dir -- set to 'rtl' or 'ltr' for direction-specific sheets
1853 */
1854 public function addStyle( $style, $media='', $condition='', $dir='' ) {
1855 $options = array();
1856 // Even though we expect the media type to be lowercase, but here we
1857 // force it to lowercase to be safe.
1858 if( $media )
1859 $options['media'] = $media;
1860 if( $condition )
1861 $options['condition'] = $condition;
1862 if( $dir )
1863 $options['dir'] = $dir;
1864 $this->styles[$style] = $options;
1865 }
1866
1867 /**
1868 * Adds inline CSS styles
1869 * @param $style_css Mixed: inline CSS
1870 */
1871 public function addInlineStyle( $style_css ){
1872 $this->mScripts .= Html::inlineStyle( $style_css );
1873 }
1874
1875 /**
1876 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
1877 * These will be applied to various media & IE conditionals.
1878 */
1879 public function buildCssLinks() {
1880 $links = array();
1881 foreach( $this->styles as $file => $options ) {
1882 $link = $this->styleLink( $file, $options );
1883 if( $link )
1884 $links[] = $link;
1885 }
1886
1887 return implode( "\n", $links );
1888 }
1889
1890 protected function styleLink( $style, $options ) {
1891 global $wgRequest;
1892
1893 if( isset( $options['dir'] ) ) {
1894 global $wgContLang;
1895 $siteDir = $wgContLang->getDir();
1896 if( $siteDir != $options['dir'] )
1897 return '';
1898 }
1899
1900 if( isset( $options['media'] ) ) {
1901 $media = $this->transformCssMedia( $options['media'] );
1902 if( is_null( $media ) ) {
1903 return '';
1904 }
1905 } else {
1906 $media = 'all';
1907 }
1908
1909 if( substr( $style, 0, 1 ) == '/' ||
1910 substr( $style, 0, 5 ) == 'http:' ||
1911 substr( $style, 0, 6 ) == 'https:' ) {
1912 $url = $style;
1913 } else {
1914 global $wgStylePath, $wgStyleVersion;
1915 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
1916 }
1917
1918 $link = Html::linkedStyle( $url, $media );
1919
1920 if( isset( $options['condition'] ) ) {
1921 $condition = htmlspecialchars( $options['condition'] );
1922 $link = "<!--[if $condition]>$link<![endif]-->";
1923 }
1924 return $link;
1925 }
1926
1927 function transformCssMedia( $media ) {
1928 global $wgRequest, $wgHandheldForIPhone;
1929
1930 // Switch in on-screen display for media testing
1931 $switches = array(
1932 'printable' => 'print',
1933 'handheld' => 'handheld',
1934 );
1935 foreach( $switches as $switch => $targetMedia ) {
1936 if( $wgRequest->getBool( $switch ) ) {
1937 if( $media == $targetMedia ) {
1938 $media = '';
1939 } elseif( $media == 'screen' ) {
1940 return null;
1941 }
1942 }
1943 }
1944
1945 // Expand longer media queries as iPhone doesn't grok 'handheld'
1946 if( $wgHandheldForIPhone ) {
1947 $mediaAliases = array(
1948 'screen' => 'screen and (min-device-width: 481px)',
1949 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
1950 );
1951
1952 if( isset( $mediaAliases[$media] ) ) {
1953 $media = $mediaAliases[$media];
1954 }
1955 }
1956
1957 return $media;
1958 }
1959
1960 /**
1961 * Turn off regular page output and return an error reponse
1962 * for when rate limiting has triggered.
1963 */
1964 public function rateLimited() {
1965
1966 $this->setPageTitle(wfMsg('actionthrottled'));
1967 $this->setRobotPolicy( 'noindex,follow' );
1968 $this->setArticleRelated( false );
1969 $this->enableClientCache( false );
1970 $this->mRedirect = '';
1971 $this->clearHTML();
1972 $this->setStatusCode(503);
1973 $this->addWikiMsg( 'actionthrottledtext' );
1974
1975 $this->returnToMain( null, $this->getTitle() );
1976 }
1977
1978 /**
1979 * Show an "add new section" link?
1980 *
1981 * @return bool
1982 */
1983 public function showNewSectionLink() {
1984 return $this->mNewSectionLink;
1985 }
1986
1987 /**
1988 * Forcibly hide the new section link?
1989 *
1990 * @return bool
1991 */
1992 public function forceHideNewSectionLink() {
1993 return $this->mHideNewSectionLink;
1994 }
1995
1996 /**
1997 * Show a warning about slave lag
1998 *
1999 * If the lag is higher than $wgSlaveLagCritical seconds,
2000 * then the warning is a bit more obvious. If the lag is
2001 * lower than $wgSlaveLagWarning, then no warning is shown.
2002 *
2003 * @param int $lag Slave lag
2004 */
2005 public function showLagWarning( $lag ) {
2006 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2007 if( $lag >= $wgSlaveLagWarning ) {
2008 $message = $lag < $wgSlaveLagCritical
2009 ? 'lag-warn-normal'
2010 : 'lag-warn-high';
2011 $warning = wfMsgExt( $message, 'parse', $lag );
2012 $this->addHTML( "<div class=\"mw-{$message}\">\n{$warning}\n</div>\n" );
2013 }
2014 }
2015
2016 /**
2017 * Add a wikitext-formatted message to the output.
2018 * This is equivalent to:
2019 *
2020 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2021 */
2022 public function addWikiMsg( /*...*/ ) {
2023 $args = func_get_args();
2024 $name = array_shift( $args );
2025 $this->addWikiMsgArray( $name, $args );
2026 }
2027
2028 /**
2029 * Add a wikitext-formatted message to the output.
2030 * Like addWikiMsg() except the parameters are taken as an array
2031 * instead of a variable argument list.
2032 *
2033 * $options is passed through to wfMsgExt(), see that function for details.
2034 */
2035 public function addWikiMsgArray( $name, $args, $options = array() ) {
2036 $options[] = 'parse';
2037 $text = wfMsgExt( $name, $options, $args );
2038 $this->addHTML( $text );
2039 }
2040
2041 /**
2042 * This function takes a number of message/argument specifications, wraps them in
2043 * some overall structure, and then parses the result and adds it to the output.
2044 *
2045 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
2046 * on. The subsequent arguments may either be strings, in which case they are the
2047 * message names, or arrays, in which case the first element is the message name,
2048 * and subsequent elements are the parameters to that message.
2049 *
2050 * The special named parameter 'options' in a message specification array is passed
2051 * through to the $options parameter of wfMsgExt().
2052 *
2053 * Don't use this for messages that are not in users interface language.
2054 *
2055 * For example:
2056 *
2057 * $wgOut->wrapWikiMsg( '<div class="error">$1</div>', 'some-error' );
2058 *
2059 * Is equivalent to:
2060 *
2061 * $wgOut->addWikiText( '<div class="error">' . wfMsgNoTrans( 'some-error' ) . '</div>' );
2062 */
2063 public function wrapWikiMsg( $wrap /*, ...*/ ) {
2064 $msgSpecs = func_get_args();
2065 array_shift( $msgSpecs );
2066 $msgSpecs = array_values( $msgSpecs );
2067 $s = $wrap;
2068 foreach ( $msgSpecs as $n => $spec ) {
2069 $options = array();
2070 if ( is_array( $spec ) ) {
2071 $args = $spec;
2072 $name = array_shift( $args );
2073 if ( isset( $args['options'] ) ) {
2074 $options = $args['options'];
2075 unset( $args['options'] );
2076 }
2077 } else {
2078 $args = array();
2079 $name = $spec;
2080 }
2081 $s = str_replace( '$' . ( $n + 1 ), wfMsgExt( $name, $options, $args ), $s );
2082 }
2083 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );
2084 }
2085 }