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