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