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