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