]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - includes/OutputPage.php
MediaWiki 1.16.5-scripts
[autoinstalls/mediawiki.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 = '', $mHTMLtitleFromPagetitle = true, $mIsarticle = true, $mPrintable = false;
13         var $mSubtitle = '', $mRedirect = '', $mStatusCode;
14         var $mLastModified = '', $mETag = false;
15         var $mCategoryLinks = array(), $mCategories = array(), $mLanguageLinks = array();
16
17         var $mScripts = '', $mLinkColours, $mPageLinkTitle = '', $mHeadItems = array();
18         var $mInlineMsg = array();
19
20         var $mTemplateIds = array();
21
22         var $mAllowUserJs;
23         var $mSuppressQuickbar = false;
24         var $mDoNothing = false;
25         var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
26         var $mIsArticleRelated = true;
27         protected $mParserOptions = null; // lazy initialised, use parserOptions()
28
29         var $mFeedLinks = array();
30
31         var $mEnableClientCache = true;
32         var $mArticleBodyOnly = false;
33
34         var $mNewSectionLink = false;
35         var $mHideNewSectionLink = false;
36         var $mNoGallery = false;
37         var $mPageTitleActionText = '';
38         var $mParseWarnings = array();
39         var $mSquidMaxage = 0;
40         var $mPreventClickjacking = true;
41         var $mRevisionId = null;
42         protected $mTitle = null;
43
44         /**
45          * An array of stylesheet filenames (relative from skins path), with options
46          * for CSS media, IE conditions, and RTL/LTR direction.
47          * For internal use; add settings in the skin via $this->addStyle()
48          */
49         var $styles = array();
50
51         /**
52          * Whether to load jQuery core.
53          */
54         protected $mJQueryDone = false;
55
56         private $mIndexPolicy = 'index';
57         private $mFollowPolicy = 'follow';
58         private $mVaryHeader = array( 'Accept-Encoding' => array('list-contains=gzip'),
59                                                                   'Cookie' => null );
60
61
62         /**
63          * Constructor
64          * Initialise private variables
65          */
66         function __construct() {
67                 global $wgAllowUserJs;
68                 $this->mAllowUserJs = $wgAllowUserJs;
69         }
70
71         /**
72          * Redirect to $url rather than displaying the normal page
73          *
74          * @param $url String: URL
75          * @param $responsecode String: HTTP status code
76          */
77         public function redirect( $url, $responsecode = '302' ) {
78                 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
79                 $this->mRedirect = str_replace( "\n", '', $url );
80                 $this->mRedirectCode = $responsecode;
81         }
82
83         /**
84          * Get the URL to redirect to, or an empty string if not redirect URL set
85          *
86          * @return String
87          */
88         public function getRedirect() {
89                 return $this->mRedirect;
90         }
91
92         /**
93          * Set the HTTP status code to send with the output.
94          *
95          * @param $statusCode Integer
96          * @return nothing
97          */
98         public function setStatusCode( $statusCode ) {
99                 $this->mStatusCode = $statusCode;
100         }
101
102
103         /**
104          * Add a new <meta> tag
105          * To add an http-equiv meta tag, precede the name with "http:"
106          *
107          * @param $name tag name
108          * @param $val tag value
109          */
110         function addMeta( $name, $val ) {
111                 array_push( $this->mMetatags, array( $name, $val ) );
112         }
113
114         /**
115          * Add a keyword or a list of keywords in the page header
116          *
117          * @param $text String or array of strings
118          */
119         function addKeyword( $text ) {
120                 if( is_array( $text ) ) {
121                         $this->mKeywords = array_merge( $this->mKeywords, $text );
122                 } else {
123                         array_push( $this->mKeywords, $text );
124                 }
125         }
126
127         /**
128          * Add a new \<link\> tag to the page header
129          *
130          * @param $linkarr Array: associative array of attributes.
131          */
132         function addLink( $linkarr ) {
133                 array_push( $this->mLinktags, $linkarr );
134         }
135
136         /**
137          * Add a new \<link\> with "rel" attribute set to "meta"
138          *
139          * @param $linkarr Array: associative array mapping attribute names to their
140          *                 values, both keys and values will be escaped, and the
141          *                 "rel" attribute will be automatically added
142          */
143         function addMetadataLink( $linkarr ) {
144                 # note: buggy CC software only reads first "meta" link
145                 static $haveMeta = false;
146                 $linkarr['rel'] = $haveMeta ? 'alternate meta' : 'meta';
147                 $this->addLink( $linkarr );
148                 $haveMeta = true;
149         }
150
151
152         /**
153          * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
154          *
155          * @param $script String: raw HTML
156          */
157         function addScript( $script ) {
158                 $this->mScripts .= $script . "\n";
159         }
160
161         /**
162          * Register and add a stylesheet from an extension directory.
163          *
164          * @param $url String path to sheet.  Provide either a full url (beginning
165          *             with 'http', etc) or a relative path from the document root
166          *             (beginning with '/').  Otherwise it behaves identically to
167          *             addStyle() and draws from the /skins folder.
168          */
169         public function addExtensionStyle( $url ) {
170                 array_push( $this->mExtStyles, $url );
171         }
172
173         /**
174          * Get all links added by extensions
175          *
176          * @return Array
177          */
178         function getExtStyle() {
179                 return $this->mExtStyles;
180         }
181
182         /**
183          * Add a JavaScript file out of skins/common, or a given relative path.
184          *
185          * @param $file String: filename in skins/common or complete on-server path
186          *              (/foo/bar.js)
187          */
188         public function addScriptFile( $file ) {
189                 global $wgStylePath, $wgStyleVersion;
190                 if( substr( $file, 0, 1 ) == '/' || substr( $file, 0, 7 ) == 'http://' ) {
191                         $path = $file;
192                 } else {
193                         $path =  "{$wgStylePath}/common/{$file}";
194                 }
195                 $this->addScript( Html::linkedScript( wfAppendQuery( $path, $wgStyleVersion ) ) );
196         }
197
198         /**
199          * Add a self-contained script tag with the given contents
200          *
201          * @param $script String: JavaScript text, no <script> tags
202          */
203         public function addInlineScript( $script ) {
204                 $this->mScripts .= Html::inlineScript( "\n$script\n" ) . "\n";
205         }
206
207         /**
208          * Get all registered JS and CSS tags for the header.
209          *
210          * @return String
211          */
212         function getScript() {
213                 return $this->mScripts . $this->getHeadItems();
214         }
215
216         /**
217          * Get all header items in a string
218          *
219          * @return String
220          */
221         function getHeadItems() {
222                 $s = '';
223                 foreach ( $this->mHeadItems as $item ) {
224                         $s .= $item;
225                 }
226                 return $s;
227         }
228
229         /**
230          * Add or replace an header item to the output
231          *
232          * @param $name String: item name
233          * @param $value String: raw HTML
234          */
235         public function addHeadItem( $name, $value ) {
236                 $this->mHeadItems[$name] = $value;
237         }
238
239         /**
240          * Check if the header item $name is already set
241          *
242          * @param $name String: item name
243          * @return Boolean
244          */
245         public function hasHeadItem( $name ) {
246                 return isset( $this->mHeadItems[$name] );
247         }
248
249         /**
250          * Set the value of the ETag HTTP header, only used if $wgUseETag is true
251          *
252          * @param $tag String: value of "ETag" header
253          */
254         function setETag( $tag ) {
255                 $this->mETag = $tag;
256         }
257
258         /**
259          * Set whether the output should only contain the body of the article,
260          * without any skin, sidebar, etc.
261          * Used e.g. when calling with "action=render".
262          *
263          * @param $only Boolean: whether to output only the body of the article
264          */
265         public function setArticleBodyOnly( $only ) {
266                 $this->mArticleBodyOnly = $only;
267         }
268
269         /**
270          * Return whether the output will contain only the body of the article
271          *
272          * @return Boolean
273          */
274         public function getArticleBodyOnly() {
275                 return $this->mArticleBodyOnly;
276         }
277
278
279         /**
280          * checkLastModified tells the client to use the client-cached page if
281          * possible. If sucessful, the OutputPage is disabled so that
282          * any future call to OutputPage->output() have no effect.
283          *
284          * Side effect: sets mLastModified for Last-Modified header
285          *
286          * @return Boolean: true iff cache-ok headers was sent.
287          */
288         public function checkLastModified( $timestamp ) {
289                 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
290
291                 if ( !$timestamp || $timestamp == '19700101000000' ) {
292                         wfDebug( __METHOD__ . ": CACHE DISABLED, NO TIMESTAMP\n" );
293                         return false;
294                 }
295                 if( !$wgCachePages ) {
296                         wfDebug( __METHOD__ . ": CACHE DISABLED\n", false );
297                         return false;
298                 }
299                 if( $wgUser->getOption( 'nocache' ) ) {
300                         wfDebug( __METHOD__ . ": USER DISABLED CACHE\n", false );
301                         return false;
302                 }
303
304                 $timestamp = wfTimestamp( TS_MW, $timestamp );
305                 $modifiedTimes = array(
306                         'page' => $timestamp,
307                         'user' => $wgUser->getTouched(),
308                         'epoch' => $wgCacheEpoch
309                 );
310                 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
311
312                 $maxModified = max( $modifiedTimes );
313                 $this->mLastModified = wfTimestamp( TS_RFC2822, $maxModified );
314
315                 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
316                         wfDebug( __METHOD__ . ": client did not send If-Modified-Since header\n", false );
317                         return false;
318                 }
319
320                 # Make debug info
321                 $info = '';
322                 foreach ( $modifiedTimes as $name => $value ) {
323                         if ( $info !== '' ) {
324                                 $info .= ', ';
325                         }
326                         $info .= "$name=" . wfTimestamp( TS_ISO_8601, $value );
327                 }
328
329                 # IE sends sizes after the date like this:
330                 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
331                 # this breaks strtotime().
332                 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
333
334                 wfSuppressWarnings(); // E_STRICT system time bitching
335                 $clientHeaderTime = strtotime( $clientHeader );
336                 wfRestoreWarnings();
337                 if ( !$clientHeaderTime ) {
338                         wfDebug( __METHOD__ . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
339                         return false;
340                 }
341                 $clientHeaderTime = wfTimestamp( TS_MW, $clientHeaderTime );
342
343                 wfDebug( __METHOD__ . ": client sent If-Modified-Since: " .
344                         wfTimestamp( TS_ISO_8601, $clientHeaderTime ) . "\n", false );
345                 wfDebug( __METHOD__ . ": effective Last-Modified: " .
346                         wfTimestamp( TS_ISO_8601, $maxModified ) . "\n", false );
347                 if( $clientHeaderTime < $maxModified ) {
348                         wfDebug( __METHOD__ . ": STALE, $info\n", false );
349                         return false;
350                 }
351
352                 # Not modified
353                 # Give a 304 response code and disable body output
354                 wfDebug( __METHOD__ . ": NOT MODIFIED, $info\n", false );
355                 ini_set('zlib.output_compression', 0);
356                 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
357                 $this->sendCacheControl();
358                 $this->disable();
359
360                 // Don't output a compressed blob when using ob_gzhandler;
361                 // it's technically against HTTP spec and seems to confuse
362                 // Firefox when the response gets split over two packets.
363                 wfClearOutputBuffers();
364
365                 return true;
366         }
367
368
369         /**
370          * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
371          *
372          * @param $policy String: the literal string to output as the contents of
373          *   the meta tag.  Will be parsed according to the spec and output in
374          *   standardized form.
375          * @return null
376          */
377         public function setRobotPolicy( $policy ) {
378                 $policy = Article::formatRobotPolicy( $policy );
379
380                 if( isset( $policy['index'] ) ){
381                         $this->setIndexPolicy( $policy['index'] );
382                 }
383                 if( isset( $policy['follow'] ) ){
384                         $this->setFollowPolicy( $policy['follow'] );
385                 }
386         }
387
388         /**
389          * Set the index policy for the page, but leave the follow policy un-
390          * touched.
391          *
392          * @param $policy string Either 'index' or 'noindex'.
393          * @return null
394          */
395         public function setIndexPolicy( $policy ) {
396                 $policy = trim( $policy );
397                 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
398                         $this->mIndexPolicy = $policy;
399                 }
400         }
401
402         /**
403          * Set the follow policy for the page, but leave the index policy un-
404          * touched.
405          *
406          * @param $policy String: either 'follow' or 'nofollow'.
407          * @return null
408          */
409         public function setFollowPolicy( $policy ) {
410                 $policy = trim( $policy );
411                 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
412                         $this->mFollowPolicy = $policy;
413                 }
414         }
415
416
417         /**
418          * Set the new value of the "action text", this will be added to the
419          * "HTML title", separated from it with " - ".
420          *
421          * @param $text String: new value of the "action text"
422          */
423         public function setPageTitleActionText( $text ) {
424                 $this->mPageTitleActionText = $text;
425         }
426
427         /**
428          * Get the value of the "action text"
429          *
430          * @return String
431          */
432         public function getPageTitleActionText() {
433                 if ( isset( $this->mPageTitleActionText ) ) {
434                         return $this->mPageTitleActionText;
435                 }
436         }
437
438         /**
439          * "HTML title" means the contents of <title>.
440          * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
441          * If $name is from page title, it can only override names which are also from page title,
442          * but if it is not from page title, it can override all other names.
443          */
444         public function setHTMLTitle( $name, $frompagetitle = false ) {
445                 if ( $frompagetitle && $this->mHTMLtitleFromPagetitle ) {
446                         $this->mHTMLtitle = $name;
447                 }
448                 elseif ( $this->mHTMLtitleFromPagetitle ) {
449                         $this->mHTMLtitle = $name;
450                         $this->mHTMLtitleFromPagetitle = false;
451                 }
452         }
453
454         /**
455          * Return the "HTML title", i.e. the content of the <title> tag.
456          *
457          * @return String
458          */
459         public function getHTMLTitle() {
460                 return $this->mHTMLtitle;
461         }
462
463         /**
464          * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
465          * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
466          * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
467          * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
468          */
469         public function setPageTitle( $name ) {
470                 # change "<script>foo&bar</script>" to "&lt;script&gt;foo&amp;bar&lt;/script&gt;"
471                 # but leave "<i>foobar</i>" alone
472                 $nameWithTags = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags( $name ) );
473                 $this->mPagetitle = $nameWithTags;
474
475                 $taction =  $this->getPageTitleActionText();
476                 if( !empty( $taction ) ) {
477                         $name .= ' - '.$taction;
478                 }
479
480                 # change "<i>foo&amp;bar</i>" to "foo&bar"
481                 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer::stripAllTags( $nameWithTags ) ) );
482         }
483
484         /**
485          * Return the "page title", i.e. the content of the \<h1\> tag.
486          *
487          * @return String
488          */
489         public function getPageTitle() {
490                 return $this->mPagetitle;
491         }
492
493         /**
494          * Set the Title object to use
495          *
496          * @param $t Title object
497          */
498         public function setTitle( $t ) {
499                 $this->mTitle = $t;
500         }
501
502         /**
503          * Get the Title object used in this instance
504          *
505          * @return Title
506          */
507         public function getTitle() {
508                 if ( $this->mTitle instanceof Title ) {
509                         return $this->mTitle;
510                 } else {
511                         wfDebug( __METHOD__ . ' called and $mTitle is null. Return $wgTitle for sanity' );
512                         global $wgTitle;
513                         return $wgTitle;
514                 }
515         }
516
517         /**
518          * Replace the subtile with $str
519          *
520          * @param $str String: new value of the subtitle
521          */
522         public function setSubtitle( $str ) {
523                 $this->mSubtitle = /*$this->parse(*/ $str /*)*/; // @bug 2514
524         }
525
526         /**
527          * Add $str to the subtitle
528          *
529          * @param $str String to add to the subtitle
530          */
531         public function appendSubtitle( $str ) {
532                 $this->mSubtitle .= /*$this->parse(*/ $str /*)*/; // @bug 2514
533         }
534
535         /**
536          * Get the subtitle
537          *
538          * @return String
539          */
540         public function getSubtitle() {
541                 return $this->mSubtitle;
542         }
543
544
545         /**
546          * Set the page as printable, i.e. it'll be displayed with with all
547          * print styles included
548          */
549         public function setPrintable() {
550                 $this->mPrintable = true;
551         }
552
553         /**
554          * Return whether the page is "printable"
555          *
556          * @return Boolean
557          */
558         public function isPrintable() {
559                 return $this->mPrintable;
560         }
561
562
563         /**
564          * Disable output completely, i.e. calling output() will have no effect
565          */
566         public function disable() {
567                 $this->mDoNothing = true;
568         }
569
570         /**
571          * Return whether the output will be completely disabled
572          *
573          * @return Boolean
574          */
575         public function isDisabled() {
576                 return $this->mDoNothing;
577         }
578
579
580         /**
581          * Show an "add new section" link?
582          *
583          * @return Boolean
584          */
585         public function showNewSectionLink() {
586                 return $this->mNewSectionLink;
587         }
588
589         /**
590          * Forcibly hide the new section link?
591          *
592          * @return Boolean
593          */
594         public function forceHideNewSectionLink() {
595                 return $this->mHideNewSectionLink;
596         }
597
598
599         /**
600          * Add or remove feed links in the page header
601          * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
602          * for the new version
603          * @see addFeedLink()
604          *
605          * @param $show Boolean: true: add default feeds, false: remove all feeds
606          */
607         public function setSyndicated( $show = true ) {
608                 if ( $show ) {
609                         $this->setFeedAppendQuery( false );
610                 } else {
611                         $this->mFeedLinks = array();
612                 }
613         }
614
615         /**
616          * Add default feeds to the page header
617          * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
618          * for the new version
619          * @see addFeedLink()
620          *
621          * @param $val String: query to append to feed links or false to output
622          *        default links
623          */
624         public function setFeedAppendQuery( $val ) {
625                 global $wgAdvertisedFeedTypes;
626
627                 $this->mFeedLinks = array();
628
629                 foreach ( $wgAdvertisedFeedTypes as $type ) {
630                         $query = "feed=$type";
631                         if ( is_string( $val ) ) {
632                                 $query .= '&' . $val;
633                         }
634                         $this->mFeedLinks[$type] = $this->getTitle()->getLocalURL( $query );
635                 }
636         }
637
638         /**
639          * Add a feed link to the page header
640          *
641          * @param $format String: feed type, should be a key of $wgFeedClasses
642          * @param $href String: URL
643          */
644         public function addFeedLink( $format, $href ) {
645                 $this->mFeedLinks[$format] = $href;
646         }
647
648         /**
649          * Should we output feed links for this page?
650          * @return Boolean
651          */
652         public function isSyndicated() {
653                 return count( $this->mFeedLinks ) > 0;
654         }
655
656         /**
657          * Return URLs for each supported syndication format for this page.
658          * @return array associating format keys with URLs
659          */
660         public function getSyndicationLinks() {
661                 return $this->mFeedLinks;
662         }
663
664         /**
665          * Will currently always return null
666          *
667          * @return null
668          */
669         public function getFeedAppendQuery() {
670                 return $this->mFeedLinksAppendQuery;
671         }
672
673         /**
674          * Set whether the displayed content is related to the source of the
675          * corresponding article on the wiki
676          * Setting true will cause the change "article related" toggle to true
677          *
678          * @param $v Boolean
679          */
680         public function setArticleFlag( $v ) {
681                 $this->mIsarticle = $v;
682                 if ( $v ) {
683                         $this->mIsArticleRelated = $v;
684                 }
685         }
686
687         /**
688          * Return whether the content displayed page is related to the source of
689          * the corresponding article on the wiki
690          *
691          * @return Boolean
692          */
693         public function isArticle() {
694                 return $this->mIsarticle;
695         }
696
697         /**
698          * Set whether this page is related an article on the wiki
699          * Setting false will cause the change of "article flag" toggle to false
700          *
701          * @param $v Boolean
702          */
703         public function setArticleRelated( $v ) {
704                 $this->mIsArticleRelated = $v;
705                 if ( !$v ) {
706                         $this->mIsarticle = false;
707                 }
708         }
709
710         /**
711          * Return whether this page is related an article on the wiki
712          *
713          * @return Boolean
714          */
715         public function isArticleRelated() {
716                 return $this->mIsArticleRelated;
717         }
718
719
720         /**
721          * Add new language links
722          *
723          * @param $newLinkArray Associative array mapping language code to the page
724          *                      name
725          */
726         public function addLanguageLinks( $newLinkArray ) {
727                 $this->mLanguageLinks += $newLinkArray;
728         }
729
730         /**
731          * Reset the language links and add new language links
732          *
733          * @param $newLinkArray Associative array mapping language code to the page
734          *                      name
735          */
736         public function setLanguageLinks( $newLinkArray ) {
737                 $this->mLanguageLinks = $newLinkArray;
738         }
739
740         /**
741          * Get the list of language links
742          *
743          * @return Associative array mapping language code to the page name
744          */
745         public function getLanguageLinks() {
746                 return $this->mLanguageLinks;
747         }
748
749
750         /**
751          * Add an array of categories, with names in the keys
752          *
753          * @param $categories Associative array mapping category name to its sort key
754          */
755         public function addCategoryLinks( $categories ) {
756                 global $wgUser, $wgContLang;
757
758                 if ( !is_array( $categories ) || count( $categories ) == 0 ) {
759                         return;
760                 }
761
762                 # Add the links to a LinkBatch
763                 $arr = array( NS_CATEGORY => $categories );
764                 $lb = new LinkBatch;
765                 $lb->setArray( $arr );
766
767                 # Fetch existence plus the hiddencat property
768                 $dbr = wfGetDB( DB_SLAVE );
769                 $pageTable = $dbr->tableName( 'page' );
770                 $where = $lb->constructSet( 'page', $dbr );
771                 $propsTable = $dbr->tableName( 'page_props' );
772                 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, pp_value
773                         FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
774                 $res = $dbr->query( $sql, __METHOD__ );
775
776                 # Add the results to the link cache
777                 $lb->addResultToCache( LinkCache::singleton(), $res );
778
779                 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
780                 $categories = array_combine( array_keys( $categories ),
781                         array_fill( 0, count( $categories ), 'normal' ) );
782
783                 # Mark hidden categories
784                 foreach ( $res as $row ) {
785                         if ( isset( $row->pp_value ) ) {
786                                 $categories[$row->page_title] = 'hidden';
787                         }
788                 }
789
790                 # Add the remaining categories to the skin
791                 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks ) ) ) {
792                         $sk = $wgUser->getSkin();
793                         foreach ( $categories as $category => $type ) {
794                                 $origcategory = $category;
795                                 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
796                                 $wgContLang->findVariantLink( $category, $title, true );
797                                 if ( $category != $origcategory )
798                                         if ( array_key_exists( $category, $categories ) )
799                                                 continue;
800                                 $text = $wgContLang->convertHtml( $title->getText() );
801                                 $this->mCategories[] = $title->getText();
802                                 $this->mCategoryLinks[$type][] = $sk->link( $title, $text );
803                         }
804                 }
805         }
806
807         /**
808          * Reset the category links (but not the category list) and add $categories
809          *
810          * @param $categories Associative array mapping category name to its sort key
811          */
812         public function setCategoryLinks( $categories ) {
813                 $this->mCategoryLinks = array();
814                 $this->addCategoryLinks( $categories );
815         }
816
817         /**
818          * Get the list of category links, in a 2-D array with the following format:
819          * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
820          * hidden categories) and $link a HTML fragment with a link to the category
821          * page
822          *
823          * @return Array
824          */
825         public function getCategoryLinks() {
826                 return $this->mCategoryLinks;
827         }
828
829         /**
830          * Get the list of category names this page belongs to
831          *
832          * @return Array of strings
833          */
834         public function getCategories() {
835                 return $this->mCategories;
836         }
837
838
839         /**
840          * Suppress the quickbar from the output, only for skin supporting
841          * the quickbar
842          */
843         public function suppressQuickbar() {
844                 $this->mSuppressQuickbar = true;
845         }
846
847         /**
848          * Return whether the quickbar should be suppressed from the output
849          *
850          * @return Boolean
851          */
852         public function isQuickbarSuppressed() {
853                 return $this->mSuppressQuickbar;
854         }
855
856
857         /**
858          * Remove user JavaScript from scripts to load
859          */
860         public function disallowUserJs() {
861                 $this->mAllowUserJs = false;
862         }
863
864         /**
865          * Return whether user JavaScript is allowed for this page
866          *
867          * @return Boolean
868          */
869         public function isUserJsAllowed() {
870                 return $this->mAllowUserJs;
871         }
872
873
874         /**
875          * Prepend $text to the body HTML
876          *
877          * @param $text String: HTML
878          */
879         public function prependHTML( $text ) {
880                 $this->mBodytext = $text . $this->mBodytext;
881         }
882
883         /**
884          * Append $text to the body HTML
885          *
886          * @param $text String: HTML
887          */
888         public function addHTML( $text ) {
889                 $this->mBodytext .= $text;
890         }
891
892         /**
893          * Clear the body HTML
894          */
895         public function clearHTML() {
896                 $this->mBodytext = '';
897         }
898
899         /**
900          * Get the body HTML
901          *
902          * @return String: HTML
903          */
904         public function getHTML() {
905                 return $this->mBodytext;
906         }
907
908
909         /**
910          * Add $text to the debug output
911          *
912          * @param $text String: debug text
913          */
914         public function debug( $text ) {
915                 $this->mDebugtext .= $text;
916         }
917
918
919         /**
920          * @deprecated use parserOptions() instead
921          */
922         public function setParserOptions( $options ) {
923                 wfDeprecated( __METHOD__ );
924                 return $this->parserOptions( $options );
925         }
926
927         /**
928          * Get/set the ParserOptions object to use for wikitext parsing
929          *
930          * @param $options either the ParserOption to use or null to only get the
931          *                 current ParserOption object
932          * @return current ParserOption object
933          */
934         public function parserOptions( $options = null ) {
935                 if ( !$this->mParserOptions ) {
936                         $this->mParserOptions = new ParserOptions;
937                 }
938                 return wfSetVar( $this->mParserOptions, $options );
939         }
940
941         /**
942          * Set the revision ID which will be seen by the wiki text parser
943          * for things such as embedded {{REVISIONID}} variable use.
944          *
945          * @param $revid Mixed: an positive integer, or null
946          * @return Mixed: previous value
947          */
948         public function setRevisionId( $revid ) {
949                 $val = is_null( $revid ) ? null : intval( $revid );
950                 return wfSetVar( $this->mRevisionId, $val );
951         }
952
953         /**
954          * Get the current revision ID
955          *
956          * @return Integer
957          */
958         public function getRevisionId() {
959                 return $this->mRevisionId;
960         }
961
962         /**
963          * Convert wikitext to HTML and add it to the buffer
964          * Default assumes that the current page title will be used.
965          *
966          * @param $text String
967          * @param $linestart Boolean: is this the start of a line?
968          */
969         public function addWikiText( $text, $linestart = true ) {
970                 $title = $this->getTitle(); // Work arround E_STRICT
971                 $this->addWikiTextTitle( $text, $title, $linestart );
972         }
973
974         /**
975          * Add wikitext with a custom Title object
976          *
977          * @param $text String: wikitext
978          * @param $title Title object
979          * @param $linestart Boolean: is this the start of a line?
980          */
981         public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
982                 $this->addWikiTextTitle( $text, $title, $linestart );
983         }
984
985         /**
986          * Add wikitext with a custom Title object and 
987          *
988          * @param $text String: wikitext
989          * @param $title Title object
990          * @param $linestart Boolean: is this the start of a line?
991          */
992         function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
993                 $this->addWikiTextTitle( $text, $title, $linestart, true );
994         }
995
996         /**
997          * Add wikitext with tidy enabled
998          *
999          * @param $text String: wikitext
1000          * @param $linestart Boolean: is this the start of a line?
1001          */
1002         public function addWikiTextTidy( $text, $linestart = true ) {
1003                 $title = $this->getTitle();
1004                 $this->addWikiTextTitleTidy($text, $title, $linestart);
1005         }
1006
1007         /**
1008          * Add wikitext with a custom Title object
1009          *
1010          * @param $text String: wikitext
1011          * @param $title Title object
1012          * @param $linestart Boolean: is this the start of a line?
1013          * @param $tidy Boolean: whether to use tidy
1014          */
1015         public function addWikiTextTitle( $text, &$title, $linestart, $tidy = false ) {
1016                 global $wgParser;
1017
1018                 wfProfileIn( __METHOD__ );
1019
1020                 wfIncrStats( 'pcache_not_possible' );
1021
1022                 $popts = $this->parserOptions();
1023                 $oldTidy = $popts->setTidy( $tidy );
1024
1025                 $parserOutput = $wgParser->parse( $text, $title, $popts,
1026                         $linestart, true, $this->mRevisionId );
1027
1028                 $popts->setTidy( $oldTidy );
1029
1030                 $this->addParserOutput( $parserOutput );
1031
1032                 wfProfileOut( __METHOD__ );
1033         }
1034
1035         /**
1036          * Add wikitext to the buffer, assuming that this is the primary text for a page view
1037          * Saves the text into the parser cache if possible.
1038          *
1039          * @param $text String: wikitext
1040          * @param $article Article object
1041          * @param $cache Boolean
1042          * @deprecated Use Article::outputWikitext
1043          */
1044         public function addPrimaryWikiText( $text, $article, $cache = true ) {
1045                 global $wgParser;
1046
1047                 wfDeprecated( __METHOD__ );
1048
1049                 $popts = $this->parserOptions();
1050                 $popts->setTidy(true);
1051                 $parserOutput = $wgParser->parse( $text, $article->mTitle,
1052                         $popts, true, true, $this->mRevisionId );
1053                 $popts->setTidy(false);
1054                 if ( $cache && $article && $parserOutput->getCacheTime() != -1 ) {
1055                         $parserCache = ParserCache::singleton();
1056                         $parserCache->save( $parserOutput, $article, $popts);
1057                 }
1058
1059                 $this->addParserOutput( $parserOutput );
1060         }
1061
1062         /**
1063          * @deprecated use addWikiTextTidy()
1064          */
1065         public function addSecondaryWikiText( $text, $linestart = true ) {
1066                 wfDeprecated( __METHOD__ );
1067                 $this->addWikiTextTitleTidy($text, $this->getTitle(), $linestart);
1068         }
1069
1070
1071         /**
1072          * Add a ParserOutput object, but without Html
1073          *
1074          * @param $parserOutput ParserOutput object
1075          */
1076         public function addParserOutputNoText( &$parserOutput ) {
1077                 global $wgExemptFromUserRobotsControl, $wgContentNamespaces;
1078
1079                 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
1080                 $this->addCategoryLinks( $parserOutput->getCategories() );
1081                 $this->mNewSectionLink = $parserOutput->getNewSection();
1082                 $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
1083
1084                 $this->mParseWarnings = $parserOutput->getWarnings();
1085                 if ( $parserOutput->getCacheTime() == -1 ) {
1086                         $this->enableClientCache( false );
1087                 }
1088                 $this->mNoGallery = $parserOutput->getNoGallery();
1089                 $this->mHeadItems = array_merge( $this->mHeadItems, $parserOutput->getHeadItems() );
1090                 // Versioning...
1091                 foreach ( (array)$parserOutput->mTemplateIds as $ns => $dbks ) {
1092                         if ( isset( $this->mTemplateIds[$ns] ) ) {
1093                                 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
1094                         } else {
1095                                 $this->mTemplateIds[$ns] = $dbks;
1096                         }
1097                 }
1098                 // Page title
1099                 $title = $parserOutput->getTitleText();
1100                 if ( $title != '' ) {
1101                         $this->setPageTitle( $title );
1102                 }
1103
1104                 // Hooks registered in the object
1105                 global $wgParserOutputHooks;
1106                 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1107                         list( $hookName, $data ) = $hookInfo;
1108                         if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1109                                 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1110                         }
1111                 }
1112
1113                 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1114         }
1115
1116         /**
1117          * Add a ParserOutput object
1118          *
1119          * @param $parserOutput ParserOutput
1120          */
1121         function addParserOutput( &$parserOutput ) {
1122                 $this->addParserOutputNoText( $parserOutput );
1123                 $text = $parserOutput->getText();
1124                 wfRunHooks( 'OutputPageBeforeHTML',array( &$this, &$text ) );
1125                 $this->addHTML( $text );
1126         }
1127
1128
1129         /**
1130          * Add the output of a QuickTemplate to the output buffer
1131          *
1132          * @param $template QuickTemplate
1133          */
1134         public function addTemplate( &$template ) {
1135                 ob_start();
1136                 $template->execute();
1137                 $this->addHTML( ob_get_contents() );
1138                 ob_end_clean();
1139         }
1140
1141         /**
1142          * Parse wikitext and return the HTML.
1143          *
1144          * @param $text String
1145          * @param $linestart Boolean: is this the start of a line?
1146          * @param $interface Boolean: use interface language ($wgLang instead of
1147          *                   $wgContLang) while parsing language sensitive magic
1148          *                   words like GRAMMAR and PLURAL
1149          * @return String: HTML
1150          */
1151         public function parse( $text, $linestart = true, $interface = false ) {
1152                 global $wgParser;
1153                 if( is_null( $this->getTitle() ) ) {
1154                         throw new MWException( 'Empty $mTitle in ' . __METHOD__ );
1155                 }
1156                 $popts = $this->parserOptions();
1157                 if ( $interface) { $popts->setInterfaceMessage(true); }
1158                 $parserOutput = $wgParser->parse( $text, $this->getTitle(), $popts,
1159                         $linestart, true, $this->mRevisionId );
1160                 if ( $interface) { $popts->setInterfaceMessage(false); }
1161                 return $parserOutput->getText();
1162         }
1163
1164         /**
1165          * Parse wikitext, strip paragraphs, and return the HTML.
1166          *
1167          * @param $text String
1168          * @param $linestart Boolean: is this the start of a line?
1169          * @param $interface Boolean: use interface language ($wgLang instead of
1170          *                   $wgContLang) while parsing language sensitive magic
1171          *                   words like GRAMMAR and PLURAL
1172          * @return String: HTML
1173          */
1174         public function parseInline( $text, $linestart = true, $interface = false ) {
1175                 $parsed = $this->parse( $text, $linestart, $interface );
1176
1177                 $m = array();
1178                 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1179                         $parsed = $m[1];
1180                 }
1181
1182                 return $parsed;
1183         }
1184
1185         /**
1186          * @deprecated
1187          *
1188          * @param $article Article
1189          * @return Boolean: true if successful, else false.
1190          */
1191         public function tryParserCache( &$article ) {
1192                 wfDeprecated( __METHOD__ );
1193                 $parserOutput = ParserCache::singleton()->get( $article, $article->getParserOptions() );
1194
1195                 if ($parserOutput !== false) {
1196                         $this->addParserOutput( $parserOutput );
1197                         return true;
1198                 } else {
1199                         return false;
1200                 }
1201         }
1202
1203         /**
1204          * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1205          *
1206          * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1207          */
1208         public function setSquidMaxage( $maxage ) {
1209                 $this->mSquidMaxage = $maxage;
1210         }
1211
1212         /**
1213          * Use enableClientCache(false) to force it to send nocache headers
1214          *
1215          * @param $state ??
1216          */
1217         public function enableClientCache( $state ) {
1218                 return wfSetVar( $this->mEnableClientCache, $state );
1219         }
1220
1221         /**
1222          * Get the list of cookies that will influence on the cache
1223          *
1224          * @return Array
1225          */
1226         function getCacheVaryCookies() {
1227                 global $wgCookiePrefix, $wgCacheVaryCookies;
1228                 static $cookies;
1229                 if ( $cookies === null ) {
1230                         $cookies = array_merge(
1231                                 array(
1232                                         "{$wgCookiePrefix}Token",
1233                                         "{$wgCookiePrefix}LoggedOut",
1234                                         session_name()
1235                                 ),
1236                                 $wgCacheVaryCookies
1237                         );
1238                         wfRunHooks('GetCacheVaryCookies', array( $this, &$cookies ) );
1239                 }
1240                 return $cookies;
1241         }
1242
1243         /**
1244          * Return whether this page is not cacheable because "useskin" or "uselang"
1245          * url parameters were passed
1246          *
1247          * @return Boolean
1248          */
1249         function uncacheableBecauseRequestVars() {
1250                 global $wgRequest;
1251                 return $wgRequest->getText('useskin', false) === false
1252                         && $wgRequest->getText('uselang', false) === false;
1253         }
1254
1255         /**
1256          * Check if the request has a cache-varying cookie header
1257          * If it does, it's very important that we don't allow public caching
1258          *
1259          * @return Boolean
1260          */
1261         function haveCacheVaryCookies() {
1262                 global $wgRequest;
1263                 $cookieHeader = $wgRequest->getHeader( 'cookie' );
1264                 if ( $cookieHeader === false ) {
1265                         return false;
1266                 }
1267                 $cvCookies = $this->getCacheVaryCookies();
1268                 foreach ( $cvCookies as $cookieName ) {
1269                         # Check for a simple string match, like the way squid does it
1270                         if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1271                                 wfDebug( __METHOD__.": found $cookieName\n" );
1272                                 return true;
1273                         }
1274                 }
1275                 wfDebug( __METHOD__.": no cache-varying cookies found\n" );
1276                 return false;
1277         }
1278
1279         /**
1280          * Add an HTTP header that will influence on the cache
1281          *
1282          * @param $header String: header name
1283          * @param $option either an Array or null
1284          */
1285         public function addVaryHeader( $header, $option = null ) {
1286                 if ( !array_key_exists( $header, $this->mVaryHeader ) ) {
1287                         $this->mVaryHeader[$header] = $option;
1288                 }
1289                 elseif( is_array( $option ) ) {
1290                         if( is_array( $this->mVaryHeader[$header] ) ) {
1291                                 $this->mVaryHeader[$header] = array_merge( $this->mVaryHeader[$header], $option );
1292                         }
1293                         else {
1294                                 $this->mVaryHeader[$header] = $option;
1295                         }
1296                 }
1297                 $this->mVaryHeader[$header] = array_unique( $this->mVaryHeader[$header] );
1298         }
1299
1300         /**
1301          * Get a complete X-Vary-Options header
1302          *
1303          * @return String
1304          */
1305         public function getXVO() {
1306                 $cvCookies = $this->getCacheVaryCookies();
1307                 
1308                 $cookiesOption = array();
1309                 foreach ( $cvCookies as $cookieName ) {
1310                         $cookiesOption[] = 'string-contains=' . $cookieName;
1311                 }
1312                 $this->addVaryHeader( 'Cookie', $cookiesOption );
1313                 
1314                 $headers = array();
1315                 foreach( $this->mVaryHeader as $header => $option ) {
1316                         $newheader = $header;
1317                         if( is_array( $option ) )
1318                                 $newheader .= ';' . implode( ';', $option );
1319                         $headers[] = $newheader;
1320                 }
1321                 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1322                 
1323                 return $xvo;
1324         }
1325
1326         /**
1327          * bug 21672: Add Accept-Language to Vary and XVO headers
1328          * if there's no 'variant' parameter existed in GET.
1329          *
1330          * For example:
1331          *   /w/index.php?title=Main_page should always be served; but
1332          *   /w/index.php?title=Main_page&variant=zh-cn should never be served.
1333          *
1334          * patched by Liangent and Philip
1335          */
1336         function addAcceptLanguage() {
1337                 global $wgRequest, $wgContLang;
1338                 if( !$wgRequest->getCheck('variant') && $wgContLang->hasVariants() ) {
1339                         $variants = $wgContLang->getVariants();
1340                         $aloption = array();
1341                         foreach ( $variants as $variant ) {
1342                                 if( $variant === $wgContLang->getCode() )
1343                                         continue;
1344                                 else
1345                                         $aloption[] = "string-contains=$variant";
1346                         }
1347                         $this->addVaryHeader( 'Accept-Language', $aloption );
1348                 }
1349         }
1350
1351         /**
1352          * Set a flag which will cause an X-Frame-Options header appropriate for 
1353          * edit pages to be sent. The header value is controlled by 
1354          * $wgEditPageFrameOptions.
1355          *
1356          * This is the default for special pages. If you display a CSRF-protected 
1357          * form on an ordinary view page, then you need to call this function.
1358          */
1359         public function preventClickjacking( $enable = true ) {
1360                 $this->mPreventClickjacking = $enable;
1361         }
1362
1363         /**
1364          * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1365          * This can be called from pages which do not contain any CSRF-protected
1366          * HTML form.
1367          */
1368         public function allowClickjacking() {
1369                 $this->mPreventClickjacking = false;
1370         }
1371
1372         /**
1373          * Get the X-Frame-Options header value (without the name part), or false 
1374          * if there isn't one. This is used by Skin to determine whether to enable 
1375          * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1376          */
1377         public function getFrameOptions() {
1378                 global $wgBreakFrames, $wgEditPageFrameOptions;
1379                 if ( $wgBreakFrames ) {
1380                         return 'DENY';
1381                 } elseif ( $this->mPreventClickjacking && $wgEditPageFrameOptions ) {
1382                         return $wgEditPageFrameOptions;
1383                 }
1384         }
1385
1386         /**
1387          * Send cache control HTTP headers
1388          */
1389         public function sendCacheControl() {
1390                 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest, $wgUseXVO;
1391
1392                 $response = $wgRequest->response();
1393                 if ($wgUseETag && $this->mETag)
1394                         $response->header("ETag: $this->mETag");
1395
1396                 $this->addAcceptLanguage();
1397
1398                 # don't serve compressed data to clients who can't handle it
1399                 # maintain different caches for logged-in users and non-logged in ones
1400                 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader ) ) );
1401
1402                 if ( $wgUseXVO ) {
1403                         # Add an X-Vary-Options header for Squid with Wikimedia patches
1404                         $response->header( $this->getXVO() );
1405                 }
1406
1407                 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache ) {
1408                         if( $wgUseSquid && session_id() == '' &&
1409                           ! $this->isPrintable() && $this->mSquidMaxage != 0 && !$this->haveCacheVaryCookies() )
1410                         {
1411                                 if ( $wgUseESI ) {
1412                                         # We'll purge the proxy cache explicitly, but require end user agents
1413                                         # to revalidate against the proxy on each visit.
1414                                         # Surrogate-Control controls our Squid, Cache-Control downstream caches
1415                                         wfDebug( __METHOD__ . ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1416                                         # start with a shorter timeout for initial testing
1417                                         # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1418                                         $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage.', content="ESI/1.0"');
1419                                         $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1420                                 } else {
1421                                         # We'll purge the proxy cache for anons explicitly, but require end user agents
1422                                         # to revalidate against the proxy on each visit.
1423                                         # IMPORTANT! The Squid needs to replace the Cache-Control header with
1424                                         # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1425                                         wfDebug( __METHOD__ . ": local proxy caching; {$this->mLastModified} **\n", false );
1426                                         # start with a shorter timeout for initial testing
1427                                         # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1428                                         $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage.', must-revalidate, max-age=0' );
1429                                 }
1430                         } else {
1431                                 # We do want clients to cache if they can, but they *must* check for updates
1432                                 # on revisiting the page.
1433                                 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **\n", false );
1434                                 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1435                                 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1436                         }
1437                         if($this->mLastModified) {
1438                                 $response->header( "Last-Modified: {$this->mLastModified}" );
1439                         }
1440                 } else {
1441                         wfDebug( __METHOD__ . ": no caching **\n", false );
1442
1443                         # In general, the absence of a last modified header should be enough to prevent
1444                         # the client from using its cache. We send a few other things just to make sure.
1445                         $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1446                         $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1447                         $response->header( 'Pragma: no-cache' );
1448                 }
1449         }
1450
1451         /**
1452          * Get the message associed with the HTTP response code $code
1453          *
1454          * @param $code Integer: status code
1455          * @return String or null: message or null if $code is not in the list of
1456          *         messages
1457          */
1458         public static function getStatusMessage( $code ) {
1459                 static $statusMessage = array(
1460                         100 => 'Continue',
1461                         101 => 'Switching Protocols',
1462                         102 => 'Processing',
1463                         200 => 'OK',
1464                         201 => 'Created',
1465                         202 => 'Accepted',
1466                         203 => 'Non-Authoritative Information',
1467                         204 => 'No Content',
1468                         205 => 'Reset Content',
1469                         206 => 'Partial Content',
1470                         207 => 'Multi-Status',
1471                         300 => 'Multiple Choices',
1472                         301 => 'Moved Permanently',
1473                         302 => 'Found',
1474                         303 => 'See Other',
1475                         304 => 'Not Modified',
1476                         305 => 'Use Proxy',
1477                         307 => 'Temporary Redirect',
1478                         400 => 'Bad Request',
1479                         401 => 'Unauthorized',
1480                         402 => 'Payment Required',
1481                         403 => 'Forbidden',
1482                         404 => 'Not Found',
1483                         405 => 'Method Not Allowed',
1484                         406 => 'Not Acceptable',
1485                         407 => 'Proxy Authentication Required',
1486                         408 => 'Request Timeout',
1487                         409 => 'Conflict',
1488                         410 => 'Gone',
1489                         411 => 'Length Required',
1490                         412 => 'Precondition Failed',
1491                         413 => 'Request Entity Too Large',
1492                         414 => 'Request-URI Too Large',
1493                         415 => 'Unsupported Media Type',
1494                         416 => 'Request Range Not Satisfiable',
1495                         417 => 'Expectation Failed',
1496                         422 => 'Unprocessable Entity',
1497                         423 => 'Locked',
1498                         424 => 'Failed Dependency',
1499                         500 => 'Internal Server Error',
1500                         501 => 'Not Implemented',
1501                         502 => 'Bad Gateway',
1502                         503 => 'Service Unavailable',
1503                         504 => 'Gateway Timeout',
1504                         505 => 'HTTP Version Not Supported',
1505                         507 => 'Insufficient Storage'
1506                 );
1507                 return isset( $statusMessage[$code] ) ? $statusMessage[$code] : null;
1508         }
1509
1510         /**
1511          * Finally, all the text has been munged and accumulated into
1512          * the object, let's actually output it:
1513          */
1514         public function output() {
1515                 global $wgUser, $wgOutputEncoding, $wgRequest;
1516                 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
1517                 global $wgUseAjax, $wgAjaxWatch;
1518                 global $wgEnableMWSuggest, $wgUniversalEditButton;
1519                 global $wgArticle;
1520
1521                 if( $this->mDoNothing ){
1522                         return;
1523                 }
1524                 wfProfileIn( __METHOD__ );
1525                 if ( $this->mRedirect != '' ) {
1526                         # Standards require redirect URLs to be absolute
1527                         $this->mRedirect = wfExpandUrl( $this->mRedirect );
1528                         if( $this->mRedirectCode == '301' || $this->mRedirectCode == '303' ) {
1529                                 if( !$wgDebugRedirects ) {
1530                                         $message = self::getStatusMessage( $this->mRedirectCode );
1531                                         $wgRequest->response()->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
1532                                 }
1533                                 $this->mLastModified = wfTimestamp( TS_RFC2822 );
1534                         }
1535                         $this->sendCacheControl();
1536
1537                         $wgRequest->response()->header( "Content-Type: text/html; charset=utf-8" );
1538                         if( $wgDebugRedirects ) {
1539                                 $url = htmlspecialchars( $this->mRedirect );
1540                                 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1541                                 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1542                                 print "</body>\n</html>\n";
1543                         } else {
1544                                 $wgRequest->response()->header( 'Location: ' . $this->mRedirect );
1545                         }
1546                         wfProfileOut( __METHOD__ );
1547                         return;
1548                 } elseif ( $this->mStatusCode ) {
1549                         $message = self::getStatusMessage( $this->mStatusCode );
1550                         if ( $message )
1551                                 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode . ' ' . $message );
1552                 }
1553
1554                 $sk = $wgUser->getSkin();
1555
1556                 if ( $wgUseAjax ) {
1557                         $this->addScriptFile( 'ajax.js' );
1558
1559                         wfRunHooks( 'AjaxAddScript', array( &$this ) );
1560
1561                         if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1562                                 $this->addScriptFile( 'ajaxwatch.js' );
1563                         }
1564
1565                         if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ){
1566                                 $this->addScriptFile( 'mwsuggest.js' );
1567                         }
1568                 }
1569
1570                 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1571                         $this->addScriptFile( 'rightclickedit.js' );
1572                 }
1573
1574                 if( $wgUniversalEditButton ) {
1575                         if( isset( $wgArticle ) && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1576                                 && ( $this->getTitle()->exists() || $this->getTitle()->quickUserCan( 'create' ) ) ) {
1577                                 // Original UniversalEditButton
1578                                 $msg = wfMsg('edit');
1579                                 $this->addLink( array(
1580                                         'rel' => 'alternate',
1581                                         'type' => 'application/x-wiki',
1582                                         'title' => $msg,
1583                                         'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1584                                 ) );
1585                                 // Alternate edit link
1586                                 $this->addLink( array(
1587                                         'rel' => 'edit',
1588                                         'title' => $msg,
1589                                         'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1590                                 ) );
1591                         }
1592                 }
1593
1594                 # Buffer output; final headers may depend on later processing
1595                 ob_start();
1596
1597                 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1598                 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
1599
1600                 // Prevent framing, if requested
1601                 $frameOptions = $this->getFrameOptions();
1602                 if ( $frameOptions ) {
1603                         $wgRequest->response()->header( "X-Frame-Options: $frameOptions" );
1604                 }
1605
1606
1607                 if ($this->mArticleBodyOnly) {
1608                         $this->out($this->mBodytext);
1609                 } else {
1610                         // Hook that allows last minute changes to the output page, e.g.
1611                         // adding of CSS or Javascript by extensions.
1612                         wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1613
1614                         wfProfileIn( 'Output-skin' );
1615                         $sk->outputPage( $this );
1616                         wfProfileOut( 'Output-skin' );
1617                 }
1618
1619                 $this->sendCacheControl();
1620                 ob_end_flush();
1621                 wfProfileOut( __METHOD__ );
1622         }
1623
1624         /**
1625          * Actually output something with print(). Performs an iconv to the
1626          * output encoding, if needed.
1627          *
1628          * @param $ins String: the string to output
1629          */
1630         public function out( $ins ) {
1631                 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1632                 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1633                         $outs = $ins;
1634                 } else {
1635                         $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1636                         if ( false === $outs ) { $outs = $ins; }
1637                 }
1638                 print $outs;
1639         }
1640
1641         /**
1642          * @todo document
1643          */
1644         public static function setEncodings() {
1645                 global $wgInputEncoding, $wgOutputEncoding;
1646                 global $wgContLang;
1647
1648                 $wgInputEncoding = strtolower( $wgInputEncoding );
1649
1650                 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
1651                         $wgOutputEncoding = strtolower( $wgOutputEncoding );
1652                         return;
1653                 }
1654                 $wgOutputEncoding = $wgInputEncoding;
1655         }
1656
1657         /**
1658          * @deprecated use wfReportTime() instead.
1659          *
1660          * @return String
1661          */
1662         public function reportTime() {
1663                 wfDeprecated( __METHOD__ );
1664                 $time = wfReportTime();
1665                 return $time;
1666         }
1667
1668         /**
1669          * Produce a "user is blocked" page.
1670          *
1671          * @param $return Boolean: whether to have a "return to $wgTitle" message or not.
1672          * @return nothing
1673          */
1674         function blockedPage( $return = true ) {
1675                 global $wgUser, $wgContLang, $wgLang;
1676
1677                 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1678                 $this->setRobotPolicy( 'noindex,nofollow' );
1679                 $this->setArticleRelated( false );
1680
1681                 $name = User::whoIs( $wgUser->blockedBy() );
1682                 $reason = $wgUser->blockedFor();
1683                 if( $reason == '' ) {
1684                         $reason = wfMsg( 'blockednoreason' );
1685                 }
1686                 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW, $wgUser->mBlock->mTimestamp ), true );
1687                 $ip = wfGetIP();
1688
1689                 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
1690
1691                 $blockid = $wgUser->mBlock->mId;
1692
1693                 $blockExpiry = $wgUser->mBlock->mExpiry;
1694                 if ( $blockExpiry == 'infinity' ) {
1695                         // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1696                         // Search for localization in 'ipboptions'
1697                         $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1698                         foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1699                                 if ( strpos( $option, ":" ) === false )
1700                                         continue;
1701                                 list( $show, $value ) = explode( ":", $option );
1702                                 if ( $value == 'infinite' || $value == 'indefinite' ) {
1703                                         $blockExpiry = $show;
1704                                         break;
1705                                 }
1706                         }
1707                 } else {
1708                         $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW, $blockExpiry ), true );
1709                 }
1710
1711                 if ( $wgUser->mBlock->mAuto ) {
1712                         $msg = 'autoblockedtext';
1713                 } else {
1714                         $msg = 'blockedtext';
1715                 }
1716
1717                 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1718                  * This could be a username, an ip range, or a single ip. */
1719                 $intended = $wgUser->mBlock->mAddress;
1720
1721                 $this->addWikiMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
1722
1723                 # Don't auto-return to special pages
1724                 if( $return ) {
1725                         $return = $this->getTitle()->getNamespace() > -1 ? $this->getTitle() : null;
1726                         $this->returnToMain( null, $return );
1727                 }
1728         }
1729
1730         /**
1731          * Output a standard error page
1732          *
1733          * @param $title String: message key for page title
1734          * @param $msg String: message key for page text
1735          * @param $params Array: message parameters
1736          */
1737         public function showErrorPage( $title, $msg, $params = array() ) {
1738                 if ( $this->getTitle() ) {
1739                         $this->mDebugtext .= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1740                 }
1741                 $this->setPageTitle( wfMsg( $title ) );
1742                 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1743                 $this->setRobotPolicy( 'noindex,nofollow' );
1744                 $this->setArticleRelated( false );
1745                 $this->enableClientCache( false );
1746                 $this->mRedirect = '';
1747                 $this->mBodytext = '';
1748
1749                 array_unshift( $params, 'parse' );
1750                 array_unshift( $params, $msg );
1751                 $this->addHTML( call_user_func_array( 'wfMsgExt', $params ) );
1752
1753                 $this->returnToMain();
1754         }
1755
1756         /**
1757          * Output a standard permission error page
1758          *
1759          * @param $errors Array: error message keys
1760          * @param $action String: action that was denied or null if unknown
1761          */
1762         public function showPermissionsErrorPage( $errors, $action = null ) {
1763                 $this->mDebugtext .= 'Original title: ' .
1764                 $this->getTitle()->getPrefixedText() . "\n";
1765                 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1766                 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1767                 $this->setRobotPolicy( 'noindex,nofollow' );
1768                 $this->setArticleRelated( false );
1769                 $this->enableClientCache( false );
1770                 $this->mRedirect = '';
1771                 $this->mBodytext = '';
1772                 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1773         }
1774
1775         /**
1776          * Display an error page indicating that a given version of MediaWiki is
1777          * required to use it
1778          *
1779          * @param $version Mixed: the version of MediaWiki needed to use the page
1780          */
1781         public function versionRequired( $version ) {
1782                 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1783                 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1784                 $this->setRobotPolicy( 'noindex,nofollow' );
1785                 $this->setArticleRelated( false );
1786                 $this->mBodytext = '';
1787
1788                 $this->addWikiMsg( 'versionrequiredtext', $version );
1789                 $this->returnToMain();
1790         }
1791
1792         /**
1793          * Display an error page noting that a given permission bit is required.
1794          *
1795          * @param $permission String: key required
1796          */
1797         public function permissionRequired( $permission ) {
1798                 global $wgLang;
1799
1800                 $this->setPageTitle( wfMsg( 'badaccess' ) );
1801                 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1802                 $this->setRobotPolicy( 'noindex,nofollow' );
1803                 $this->setArticleRelated( false );
1804                 $this->mBodytext = '';
1805
1806                 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1807                         User::getGroupsWithPermission( $permission ) );
1808                 if( $groups ) {
1809                         $this->addWikiMsg( 'badaccess-groups',
1810                                 $wgLang->commaList( $groups ),
1811                                 count( $groups) );
1812                 } else {
1813                         $this->addWikiMsg( 'badaccess-group0' );
1814                 }
1815                 $this->returnToMain();
1816         }
1817
1818         /**
1819          * @deprecated use permissionRequired()
1820          */
1821         public function sysopRequired() {
1822                 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
1823         }
1824
1825         /**
1826          * @deprecated use permissionRequired()
1827          */
1828         public function developerRequired() {
1829                 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
1830         }
1831
1832         /**
1833          * Produce the stock "please login to use the wiki" page
1834          */
1835         public function loginToUse() {
1836                 global $wgUser, $wgContLang;
1837
1838                 if( $wgUser->isLoggedIn() ) {
1839                         $this->permissionRequired( 'read' );
1840                         return;
1841                 }
1842
1843                 $skin = $wgUser->getSkin();
1844
1845                 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1846                 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1847                 $this->setRobotPolicy( 'noindex,nofollow' );
1848                 $this->setArticleFlag( false );
1849
1850                 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
1851                 $loginLink = $skin->link(
1852                         $loginTitle,
1853                         wfMsgHtml( 'loginreqlink' ),
1854                         array(),
1855                         array( 'returnto' => $this->getTitle()->getPrefixedText() ),
1856                         array( 'known', 'noclasses' )
1857                 );
1858                 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1859                 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . "-->" );
1860
1861                 # Don't return to the main page if the user can't read it
1862                 # otherwise we'll end up in a pointless loop
1863                 $mainPage = Title::newMainPage();
1864                 if( $mainPage->userCanRead() )
1865                         $this->returnToMain( null, $mainPage );
1866         }
1867
1868         /**
1869          * Format a list of error messages
1870          *
1871          * @param $errors An array of arrays returned by Title::getUserPermissionsErrors
1872          * @param $action String: action that was denied or null if unknown
1873          * @return String: the wikitext error-messages, formatted into a list.
1874          */
1875         public function formatPermissionsErrorMessage( $errors, $action = null ) {
1876                 if ($action == null) {
1877                         $text = wfMsgNoTrans( 'permissionserrorstext', count($errors)). "\n\n";
1878                 } else {
1879                         global $wgLang;
1880                         $action_desc = wfMsgNoTrans( "action-$action" );
1881                         $text = wfMsgNoTrans( 'permissionserrorstext-withaction', count($errors), $action_desc ) . "\n\n";
1882                 }
1883
1884                 if (count( $errors ) > 1) {
1885                         $text .= '<ul class="permissions-errors">' . "\n";
1886
1887                         foreach( $errors as $error )
1888                         {
1889                                 $text .= '<li>';
1890                                 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1891                                 $text .= "</li>\n";
1892                         }
1893                         $text .= '</ul>';
1894                 } else {
1895                         $text .= "<div class=\"permissions-errors\">\n" . call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) . "\n</div>";
1896                 }
1897
1898                 return $text;
1899         }
1900
1901         /**
1902          * Display a page stating that the Wiki is in read-only mode,
1903          * and optionally show the source of the page that the user
1904          * was trying to edit.  Should only be called (for this
1905          * purpose) after wfReadOnly() has returned true.
1906          *
1907          * For historical reasons, this function is _also_ used to
1908          * show the error message when a user tries to edit a page
1909          * they are not allowed to edit.  (Unless it's because they're
1910          * blocked, then we show blockedPage() instead.)  In this
1911          * case, the second parameter should be set to true and a list
1912          * of reasons supplied as the third parameter.
1913          *
1914          * @todo Needs to be split into multiple functions.
1915          *
1916          * @param $source    String: source code to show (or null).
1917          * @param $protected Boolean: is this a permissions error?
1918          * @param $reasons   Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
1919          * @param $action    String: action that was denied or null if unknown
1920          */
1921         public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1922                 global $wgUser;
1923                 $skin = $wgUser->getSkin();
1924
1925                 $this->setRobotPolicy( 'noindex,nofollow' );
1926                 $this->setArticleRelated( false );
1927
1928                 // If no reason is given, just supply a default "I can't let you do
1929                 // that, Dave" message.  Should only occur if called by legacy code.
1930                 if ( $protected && empty($reasons) ) {
1931                         $reasons[] = array( 'badaccess-group0' );
1932                 }
1933
1934                 if ( !empty($reasons) ) {
1935                         // Permissions error
1936                         if( $source ) {
1937                                 $this->setPageTitle( wfMsg( 'viewsource' ) );
1938                                 $this->setSubtitle(
1939                                         wfMsg(
1940                                                 'viewsourcefor',
1941                                                 $skin->link(
1942                                                         $this->getTitle(),
1943                                                         null,
1944                                                         array(),
1945                                                         array(),
1946                                                         array( 'known', 'noclasses' )
1947                                                 )
1948                                         )
1949                                 );
1950                         } else {
1951                                 $this->setPageTitle( wfMsg( 'badaccess' ) );
1952                         }
1953                         $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1954                 } else {
1955                         // Wiki is read only
1956                         $this->setPageTitle( wfMsg( 'readonly' ) );
1957                         $reason = wfReadOnlyReason();
1958                         $this->wrapWikiMsg( '<div class="mw-readonly-error">\n$1</div>', array( 'readonlytext', $reason ) );
1959                 }
1960
1961                 // Show source, if supplied
1962                 if( is_string( $source ) ) {
1963                         $this->addWikiMsg( 'viewsourcetext' );
1964
1965                         $params = array(
1966                                 'id'   => 'wpTextbox1',
1967                                 'name' => 'wpTextbox1',
1968                                 'cols' => $wgUser->getOption( 'cols' ),
1969                                 'rows' => $wgUser->getOption( 'rows' ),
1970                                 'readonly' => 'readonly'
1971                         );
1972                         $this->addHTML( Html::element( 'textarea', $params, $source ) );
1973
1974                         // Show templates used by this article
1975                         $skin = $wgUser->getSkin();
1976                         $article = new Article( $this->getTitle() );
1977                         $this->addHTML( "<div class='templatesUsed'>
1978 {$skin->formatTemplates( $article->getUsedTemplates() )}
1979 </div>
1980 " );
1981                 }
1982
1983                 # If the title doesn't exist, it's fairly pointless to print a return
1984                 # link to it.  After all, you just tried editing it and couldn't, so
1985                 # what's there to do there?
1986                 if( $this->getTitle()->exists() ) {
1987                         $this->returnToMain( null, $this->getTitle() );
1988                 }
1989         }
1990
1991         /** @deprecated */
1992         public function errorpage( $title, $msg ) {
1993                 wfDeprecated( __METHOD__ );
1994                 throw new ErrorPageError( $title, $msg );
1995         }
1996
1997         /** @deprecated */
1998         public function databaseError( $fname, $sql, $error, $errno ) {
1999                 throw new MWException( "OutputPage::databaseError is obsolete\n" );
2000         }
2001
2002         /** @deprecated */
2003         public function fatalError( $message ) {
2004                 wfDeprecated( __METHOD__ );
2005                 throw new FatalError( $message );
2006         }
2007
2008         /** @deprecated */
2009         public function unexpectedValueError( $name, $val ) {
2010                 wfDeprecated( __METHOD__ );
2011                 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
2012         }
2013
2014         /** @deprecated */
2015         public function fileCopyError( $old, $new ) {
2016                 wfDeprecated( __METHOD__ );
2017                 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
2018         }
2019
2020         /** @deprecated */
2021         public function fileRenameError( $old, $new ) {
2022                 wfDeprecated( __METHOD__ );
2023                 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
2024         }
2025
2026         /** @deprecated */
2027         public function fileDeleteError( $name ) {
2028                 wfDeprecated( __METHOD__ );
2029                 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
2030         }
2031
2032         /** @deprecated */
2033         public function fileNotFoundError( $name ) {
2034                 wfDeprecated( __METHOD__ );
2035                 throw new FatalError( wfMsg( 'filenotfound', $name ) );
2036         }
2037
2038         public function showFatalError( $message ) {
2039                 $this->setPageTitle( wfMsg( "internalerror" ) );
2040                 $this->setRobotPolicy( "noindex,nofollow" );
2041                 $this->setArticleRelated( false );
2042                 $this->enableClientCache( false );
2043                 $this->mRedirect = '';
2044                 $this->mBodytext = $message;
2045         }
2046
2047         public function showUnexpectedValueError( $name, $val ) {
2048                 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
2049         }
2050
2051         public function showFileCopyError( $old, $new ) {
2052                 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
2053         }
2054
2055         public function showFileRenameError( $old, $new ) {
2056                 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
2057         }
2058
2059         public function showFileDeleteError( $name ) {
2060                 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
2061         }
2062
2063         public function showFileNotFoundError( $name ) {
2064                 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
2065         }
2066
2067         /**
2068          * Add a "return to" link pointing to a specified title
2069          *
2070          * @param $title Title to link
2071          * @param $query String: query string
2072          */
2073         public function addReturnTo( $title, $query = array() ) {
2074                 global $wgUser;
2075                 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullUrl() ) );
2076                 $link = wfMsgHtml( 'returnto', $wgUser->getSkin()->link(
2077                         $title, null, array(), $query ) );
2078                 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2079         }
2080
2081         /**
2082          * Add a "return to" link pointing to a specified title,
2083          * or the title indicated in the request, or else the main page
2084          *
2085          * @param $unused No longer used
2086          * @param $returnto Title or String to return to
2087          * @param $returntoquery String: query string for the return to link
2088          */
2089         public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2090                 global $wgRequest;
2091
2092                 if ( $returnto == null ) {
2093                         $returnto = $wgRequest->getText( 'returnto' );
2094                 }
2095
2096                 if ( $returntoquery == null ) {
2097                         $returntoquery = $wgRequest->getText( 'returntoquery' );
2098                 }
2099
2100                 if ( $returnto === '' ) {
2101                         $returnto = Title::newMainPage();
2102                 }
2103
2104                 if ( is_object( $returnto ) ) {
2105                         $titleObj = $returnto;
2106                 } else {
2107                         $titleObj = Title::newFromText( $returnto );
2108                 }
2109                 if ( !is_object( $titleObj ) ) {
2110                         $titleObj = Title::newMainPage();
2111                 }
2112
2113                 $this->addReturnTo( $titleObj, $returntoquery );
2114         }
2115
2116         /**
2117          * @param $sk Skin The given Skin
2118          * @param $includeStyle Unused (?)
2119          * @return String: The doctype, opening <html>, and head element.
2120          */
2121         public function headElement( Skin $sk, $includeStyle = true ) {
2122                 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
2123                 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces, $wgHtml5Version;
2124                 global $wgContLang, $wgUseTrackbacks, $wgStyleVersion, $wgHtml5, $wgWellFormedXml;
2125                 global $wgUser, $wgRequest, $wgLang;
2126
2127                 $this->addMeta( "http:Content-Type", "$wgMimeType; charset={$wgOutputEncoding}" );
2128                 if ( $sk->commonPrintStylesheet() ) {
2129                         $this->addStyle( 'common/wikiprintable.css', 'print' );
2130                 }
2131                 $sk->setupUserCss( $this );
2132
2133                 $ret = '';
2134
2135                 if( $wgMimeType == 'text/xml' || $wgMimeType == 'application/xhtml+xml' || $wgMimeType == 'application/xml' ) {
2136                         $ret .= "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?" . ">\n";
2137                 }
2138
2139                 if ( $this->getHTMLTitle() == '' ) {
2140                         $this->setHTMLTitle(  wfMsg( 'pagetitle', $this->getPageTitle() ));
2141                 }
2142
2143                 $dir = $wgContLang->getDir();
2144
2145                 if ( $wgHtml5 ) {
2146                         if ( $wgWellFormedXml ) {
2147                                 # Unknown elements and attributes are okay in XML, but unknown
2148                                 # named entities are well-formedness errors and will break XML
2149                                 # parsers.  Thus we need a doctype that gives us appropriate
2150                                 # entity definitions.  The HTML5 spec permits four legacy
2151                                 # doctypes as obsolete but conforming, so let's pick one of
2152                                 # those, although it makes our pages look like XHTML1 Strict.
2153                                 # Isn't compatibility great?
2154                                 $ret .= "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n";
2155                         } else {
2156                                 # Much saner.
2157                                 $ret .= "<!doctype html>\n";
2158                         }
2159                         $ret .= "<html lang=\"$wgContLanguageCode\" dir=\"$dir\"";
2160                         if ( $wgHtml5Version ) $ret .= " version=\"$wgHtml5Version\"";
2161                         $ret .= ">\n";
2162                 } else {
2163                         $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\" \"$wgDTD\">\n";
2164                         $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
2165                         foreach($wgXhtmlNamespaces as $tag => $ns) {
2166                                 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
2167                         }
2168                         $ret .= "lang=\"$wgContLanguageCode\" dir=\"$dir\">\n";
2169                 }
2170
2171                 $ret .= "<head>\n";
2172                 $ret .= "<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n";
2173                 $ret .= implode( "\n", array(
2174                         $this->getHeadLinks(),
2175                         $this->buildCssLinks(),
2176                         $this->getHeadScripts( $sk ),
2177                         $this->getHeadItems(),
2178                 ));
2179                 if( $sk->usercss ){
2180                         $ret .= Html::inlineStyle( $sk->usercss );
2181                 }
2182
2183                 if ($wgUseTrackbacks && $this->isArticleRelated())
2184                         $ret .= $this->getTitle()->trackbackRDF();
2185
2186                 $ret .= "</head>\n";
2187
2188                 $bodyAttrs = array();
2189
2190                 # Crazy edit-on-double-click stuff
2191                 $action = $wgRequest->getVal( 'action', 'view' );
2192
2193                 if ( $this->getTitle()->getNamespace() != NS_SPECIAL
2194                 && !in_array( $action, array( 'edit', 'submit' ) )
2195                 && $wgUser->getOption( 'editondblclick' ) ) {
2196                         $bodyAttrs['ondblclick'] = "document.location = '" . Xml::escapeJsString( $this->getTitle()->getEditURL() ) . "'";
2197                 }
2198
2199                 # Class bloat
2200                 $bodyAttrs['class'] = "mediawiki $dir";
2201
2202                 if ( $wgLang->capitalizeAllNouns() ) {
2203                         # A <body> class is probably not the best way to do this . . .
2204                         $bodyAttrs['class'] .= ' capitalize-all-nouns';
2205                 }
2206                 $bodyAttrs['class'] .= ' ns-' . $this->getTitle()->getNamespace();
2207                 if ( $this->getTitle()->getNamespace() == NS_SPECIAL ) {
2208                         $bodyAttrs['class'] .= ' ns-special';
2209                 } elseif ( $this->getTitle()->isTalkPage() ) {
2210                         $bodyAttrs['class'] .= ' ns-talk';
2211                 } else {
2212                         $bodyAttrs['class'] .= ' ns-subject';
2213                 }
2214                 $bodyAttrs['class'] .= ' ' . Sanitizer::escapeClass( 'page-' . $this->getTitle()->getPrefixedText() );
2215                 $bodyAttrs['class'] .= ' skin-' . Sanitizer::escapeClass( $wgUser->getSkin()->getSkinName() );
2216
2217                 $ret .= Html::openElement( 'body', $bodyAttrs ) . "\n";
2218
2219                 return $ret;
2220         }
2221
2222         /**
2223          * Gets the global variables and mScripts; also adds userjs to the end if
2224          * enabled
2225          *
2226          * @param $sk Skin object to use
2227          * @return String: HTML fragment
2228          */
2229         function getHeadScripts( Skin $sk ) {
2230                 global $wgUser, $wgRequest, $wgJsMimeType, $wgUseSiteJs;
2231                 global $wgStylePath, $wgStyleVersion;
2232
2233                 $scripts = Skin::makeGlobalVariablesScript( $sk->getSkinName() );
2234                 $scripts .= Html::linkedScript( "{$wgStylePath}/common/wikibits.js?$wgStyleVersion" );
2235
2236                 //add site JS if enabled:
2237                 if( $wgUseSiteJs ) {
2238                         $jsCache = $wgUser->isLoggedIn() ? '&smaxage=0' : '';
2239                         $this->addScriptFile(  Skin::makeUrl( '-',
2240                                         "action=raw$jsCache&gen=js&useskin=" .
2241                                         urlencode( $sk->getSkinName() )
2242                                         )
2243                                 );
2244                 }
2245
2246                 //add user js if enabled:
2247                 if( $this->isUserJsAllowed() && $wgUser->isLoggedIn() ) {
2248                         $action = $wgRequest->getVal( 'action', 'view' );
2249                         if( $this->mTitle && $this->mTitle->isJsSubpage() and $sk->userCanPreview( $action ) ) {
2250                                 # XXX: additional security check/prompt?
2251                                 $this->addInlineScript( $wgRequest->getText( 'wpTextbox1' ) );
2252                         } else {
2253                                 $userpage = $wgUser->getUserPage();
2254                                 $scriptpage = Title::makeTitleSafe(
2255                                         NS_USER,
2256                                         $userpage->getDBkey() . '/' . $sk->getSkinName() . '.js'
2257                                 );
2258                                 if ( $scriptpage && $scriptpage->exists() ) {
2259                                         $userjs = Skin::makeUrl( $scriptpage->getPrefixedText(), 'action=raw&ctype=' . $wgJsMimeType );
2260                                         $this->addScriptFile( $userjs );
2261                                 }
2262                         }
2263                 }
2264
2265                 $scripts .= "\n" . $this->mScripts;
2266                 return $scripts;
2267         }
2268
2269         /**
2270          * Add default \<meta\> tags
2271          */
2272         protected function addDefaultMeta() {
2273                 global $wgVersion, $wgHtml5;
2274
2275                 static $called = false;
2276                 if ( $called ) {
2277                         # Don't run this twice
2278                         return;
2279                 }
2280                 $called = true;
2281
2282                 if ( !$wgHtml5 ) {
2283                         $this->addMeta( 'http:Content-Style-Type', 'text/css' ); //bug 15835
2284                 }
2285                 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
2286
2287                 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
2288                 if( $p !== 'index,follow' ) {
2289                         // http://www.robotstxt.org/wc/meta-user.html
2290                         // Only show if it's different from the default robots policy
2291                         $this->addMeta( 'robots', $p );
2292                 }
2293
2294                 if ( count( $this->mKeywords ) > 0 ) {
2295                         $strip = array(
2296                                 "/<.*?" . ">/" => '',
2297                                 "/_/" => ' '
2298                         );
2299                         $this->addMeta( 'keywords', preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords ) ) );
2300                 }
2301         }
2302
2303         /**
2304          * @return string HTML tag links to be put in the header.
2305          */
2306         public function getHeadLinks() {
2307                 global $wgRequest, $wgFeed;
2308
2309                 // Ideally this should happen earlier, somewhere. :P
2310                 $this->addDefaultMeta();
2311
2312                 $tags = array();
2313
2314                 foreach ( $this->mMetatags as $tag ) {
2315                         if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
2316                                 $a = 'http-equiv';
2317                                 $tag[0] = substr( $tag[0], 5 );
2318                         } else {
2319                                 $a = 'name';
2320                         }
2321                         $tags[] = Html::element( 'meta',
2322                                 array(
2323                                         $a => $tag[0],
2324                                         'content' => $tag[1] ) );
2325                 }
2326                 foreach ( $this->mLinktags as $tag ) {
2327                         $tags[] = Html::element( 'link', $tag );
2328                 }
2329
2330                 if( $wgFeed ) {
2331                         foreach( $this->getSyndicationLinks() as $format => $link ) {
2332                                 # Use the page name for the title (accessed through $wgTitle since
2333                                 # there's no other way).  In principle, this could lead to issues
2334                                 # with having the same name for different feeds corresponding to
2335                                 # the same page, but we can't avoid that at this low a level.
2336
2337                                 $tags[] = $this->feedLink(
2338                                         $format,
2339                                         $link,
2340                                         # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
2341                                         wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() ) );
2342                         }
2343
2344                         # Recent changes feed should appear on every page (except recentchanges,
2345                         # that would be redundant). Put it after the per-page feed to avoid
2346                         # changing existing behavior. It's still available, probably via a
2347                         # menu in your browser. Some sites might have a different feed they'd
2348                         # like to promote instead of the RC feed (maybe like a "Recent New Articles"
2349                         # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
2350                         # If so, use it instead.
2351
2352                         global $wgOverrideSiteFeed, $wgSitename, $wgAdvertisedFeedTypes;
2353                         $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
2354
2355                         if ( $wgOverrideSiteFeed ) {
2356                                 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
2357                                         $tags[] = $this->feedLink (
2358                                                 $type,
2359                                                 htmlspecialchars( $feedUrl ),
2360                                                 wfMsg( "site-{$type}-feed", $wgSitename ) );
2361                                 }
2362                         } elseif ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
2363                                 foreach ( $wgAdvertisedFeedTypes as $format ) {
2364                                         $tags[] = $this->feedLink(
2365                                                 $format,
2366                                                 $rctitle->getLocalURL( "feed={$format}" ),
2367                                                 wfMsg( "site-{$format}-feed", $wgSitename ) ); # For grep: 'site-rss-feed', 'site-atom-feed'.
2368                                 }
2369                         }
2370                 }
2371
2372                 return implode( "\n", $tags );
2373         }
2374
2375         /**
2376          * Generate a <link rel/> for a feed.
2377          *
2378          * @param $type String: feed type
2379          * @param $url String: URL to the feed
2380          * @param $text String: value of the "title" attribute
2381          * @return String: HTML fragment
2382          */
2383         private function feedLink( $type, $url, $text ) {
2384                 return Html::element( 'link', array(
2385                         'rel' => 'alternate',
2386                         'type' => "application/$type+xml",
2387                         'title' => $text,
2388                         'href' => $url ) );
2389         }
2390
2391         /**
2392          * Add a local or specified stylesheet, with the given media options.
2393          * Meant primarily for internal use...
2394          *
2395          * @param $style String: URL to the file
2396          * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
2397          * @param $condition String: for IE conditional comments, specifying an IE version
2398          * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
2399          */
2400         public function addStyle( $style, $media='', $condition='', $dir='' ) {
2401                 $options = array();
2402                 // Even though we expect the media type to be lowercase, but here we
2403                 // force it to lowercase to be safe.
2404                 if( $media )
2405                         $options['media'] = $media;
2406                 if( $condition )
2407                         $options['condition'] = $condition;
2408                 if( $dir )
2409                         $options['dir'] = $dir;
2410                 $this->styles[$style] = $options;
2411         }
2412
2413         /**
2414          * Adds inline CSS styles
2415          * @param $style_css Mixed: inline CSS
2416          */
2417         public function addInlineStyle( $style_css ){
2418                 $this->mScripts .= Html::inlineStyle( $style_css );
2419         }
2420
2421         /**
2422          * Build a set of <link>s for the stylesheets specified in the $this->styles array.
2423          * These will be applied to various media & IE conditionals.
2424          */
2425         public function buildCssLinks() {
2426                 $links = array();
2427                 foreach( $this->styles as $file => $options ) {
2428                         $link = $this->styleLink( $file, $options );
2429                         if( $link )
2430                                 $links[] = $link;
2431                 }
2432
2433                 return implode( "\n", $links );
2434         }
2435
2436         /**
2437          * Generate \<link\> tags for stylesheets
2438          *
2439          * @param $style String: URL to the file
2440          * @param $options Array: option, can contain 'condition', 'dir', 'media'
2441          *                 keys
2442          * @return String: HTML fragment
2443          */
2444         protected function styleLink( $style, $options ) {
2445                 global $wgRequest;
2446
2447                 if( isset( $options['dir'] ) ) {
2448                         global $wgContLang;
2449                         $siteDir = $wgContLang->getDir();
2450                         if( $siteDir != $options['dir'] )
2451                                 return '';
2452                 }
2453
2454                 if( isset( $options['media'] ) ) {
2455                         $media = $this->transformCssMedia( $options['media'] );
2456                         if( is_null( $media ) ) {
2457                                 return '';
2458                         }
2459                 } else {
2460                         $media = 'all';
2461                 }
2462
2463                 if( substr( $style, 0, 1 ) == '/' ||
2464                         substr( $style, 0, 5 ) == 'http:' ||
2465                         substr( $style, 0, 6 ) == 'https:' ) {
2466                         $url = $style;
2467                 } else {
2468                         global $wgStylePath, $wgStyleVersion;
2469                         $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
2470                 }
2471
2472                 $link = Html::linkedStyle( $url, $media );
2473
2474                 if( isset( $options['condition'] ) ) {
2475                         $condition = htmlspecialchars( $options['condition'] );
2476                         $link = "<!--[if $condition]>$link<![endif]-->";
2477                 }
2478                 return $link;
2479         }
2480
2481         /**
2482          * Transform "media" attribute based on request parameters
2483          *
2484          * @param $media String: current value of the "media" attribute
2485          * @return String: modified value of the "media" attribute
2486          */
2487         function transformCssMedia( $media ) {
2488                 global $wgRequest, $wgHandheldForIPhone;
2489
2490                 // Switch in on-screen display for media testing
2491                 $switches = array(
2492                         'printable' => 'print',
2493                         'handheld' => 'handheld',
2494                 );
2495                 foreach( $switches as $switch => $targetMedia ) {
2496                         if( $wgRequest->getBool( $switch ) ) {
2497                                 if( $media == $targetMedia ) {
2498                                         $media = '';
2499                                 } elseif( $media == 'screen' ) {
2500                                         return null;
2501                                 }
2502                         }
2503                 }
2504
2505                 // Expand longer media queries as iPhone doesn't grok 'handheld'
2506                 if( $wgHandheldForIPhone ) {
2507                         $mediaAliases = array(
2508                                 'screen' => 'screen and (min-device-width: 481px)',
2509                                 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
2510                         );
2511
2512                         if( isset( $mediaAliases[$media] ) ) {
2513                                 $media = $mediaAliases[$media];
2514                         }
2515                 }
2516
2517                 return $media;
2518         }
2519
2520         /**
2521          * Turn off regular page output and return an error reponse
2522          * for when rate limiting has triggered.
2523          */
2524         public function rateLimited() {
2525                 $this->setPageTitle(wfMsg('actionthrottled'));
2526                 $this->setRobotPolicy( 'noindex,follow' );
2527                 $this->setArticleRelated( false );
2528                 $this->enableClientCache( false );
2529                 $this->mRedirect = '';
2530                 $this->clearHTML();
2531                 $this->setStatusCode(503);
2532                 $this->addWikiMsg( 'actionthrottledtext' );
2533
2534                 $this->returnToMain( null, $this->getTitle() );
2535         }
2536
2537         /**
2538          * Show a warning about slave lag
2539          *
2540          * If the lag is higher than $wgSlaveLagCritical seconds,
2541          * then the warning is a bit more obvious. If the lag is
2542          * lower than $wgSlaveLagWarning, then no warning is shown.
2543          *
2544          * @param $lag Integer: slave lag
2545          */
2546         public function showLagWarning( $lag ) {
2547                 global $wgSlaveLagWarning, $wgSlaveLagCritical, $wgLang;
2548                 if( $lag >= $wgSlaveLagWarning ) {
2549                         $message = $lag < $wgSlaveLagCritical
2550                                 ? 'lag-warn-normal'
2551                                 : 'lag-warn-high';
2552                         $wrap = Html::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2553                         $this->wrapWikiMsg( "$wrap\n", array( $message, $wgLang->formatNum( $lag ) ) );
2554                 }
2555         }
2556
2557         /**
2558          * Add a wikitext-formatted message to the output.
2559          * This is equivalent to:
2560          *
2561          *    $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2562          */
2563         public function addWikiMsg( /*...*/ ) {
2564                 $args = func_get_args();
2565                 $name = array_shift( $args );
2566                 $this->addWikiMsgArray( $name, $args );
2567         }
2568
2569         /**
2570          * Add a wikitext-formatted message to the output.
2571          * Like addWikiMsg() except the parameters are taken as an array
2572          * instead of a variable argument list.
2573          *
2574          * $options is passed through to wfMsgExt(), see that function for details.
2575          */
2576         public function addWikiMsgArray( $name, $args, $options = array() ) {
2577                 $options[] = 'parse';
2578                 $text = wfMsgExt( $name, $options, $args );
2579                 $this->addHTML( $text );
2580         }
2581
2582         /**
2583          * This function takes a number of message/argument specifications, wraps them in
2584          * some overall structure, and then parses the result and adds it to the output.
2585          *
2586          * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
2587          * on. The subsequent arguments may either be strings, in which case they are the
2588          * message names, or arrays, in which case the first element is the message name,
2589          * and subsequent elements are the parameters to that message.
2590          *
2591          * The special named parameter 'options' in a message specification array is passed
2592          * through to the $options parameter of wfMsgExt().
2593          *
2594          * Don't use this for messages that are not in users interface language.
2595          *
2596          * For example:
2597          *
2598          *    $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>", 'some-error' );
2599          *
2600          * Is equivalent to:
2601          *
2602          *    $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . "</div>" );
2603          *
2604          * The newline after opening div is needed in some wikitext. See bug 19226.
2605          */
2606         public function wrapWikiMsg( $wrap /*, ...*/ ) {
2607                 $msgSpecs = func_get_args();
2608                 array_shift( $msgSpecs );
2609                 $msgSpecs = array_values( $msgSpecs );
2610                 $s = $wrap;
2611                 foreach ( $msgSpecs as $n => $spec ) {
2612                         $options = array();
2613                         if ( is_array( $spec ) ) {
2614                                 $args = $spec;
2615                                 $name = array_shift( $args );
2616                                 if ( isset( $args['options'] ) ) {
2617                                         $options = $args['options'];
2618                                         unset( $args['options'] );
2619                                 }
2620                         }  else {
2621                                 $args = array();
2622                                 $name = $spec;
2623                         }
2624                         $s = str_replace( '$' . ( $n + 1 ), wfMsgExt( $name, $options, $args ), $s );
2625                 }
2626                 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );
2627         }
2628
2629         /**
2630          * Include jQuery core. Use this to avoid loading it multiple times
2631          * before we get a usable script loader. 
2632          *
2633          * @param $modules Array: list of jQuery modules which should be loaded
2634          * @return Array: the list of modules which were not loaded.
2635          */
2636         public function includeJQuery( $modules = array() ) {
2637                 global $wgStylePath, $wgStyleVersion, $wgJsMimeType;
2638
2639                 $supportedModules = array( /** TODO: add things here */ );
2640                 $unsupported = array_diff( $modules, $supportedModules );
2641
2642                 $params = array(
2643                         'type' => $wgJsMimeType,
2644                         'src' => "$wgStylePath/common/jquery.min.js?$wgStyleVersion",
2645                 );
2646                 if ( !$this->mJQueryDone ) {
2647                         $this->mJQueryDone = true;
2648                         $this->mScripts = Html::element( 'script', $params ) . "\n" . $this->mScripts;
2649                 }
2650                 return $unsupported;
2651         }
2652
2653 }