Rewrite ajaxwatch.js to use the API watch action, and JQuery. Allows it to be used...
[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;
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 # Buffer output; final headers may depend on later processing
1555 ob_start();
1556
1557 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1558 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
1559
1560 if ($this->mArticleBodyOnly) {
1561 $this->out($this->mBodytext);
1562 } else {
1563 // Hook that allows last minute changes to the output page, e.g.
1564 // adding of CSS or Javascript by extensions.
1565 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1566
1567 wfProfileIn( 'Output-skin' );
1568 $sk->outputPage( $this );
1569 wfProfileOut( 'Output-skin' );
1570 }
1571
1572 $this->sendCacheControl();
1573 ob_end_flush();
1574 wfProfileOut( __METHOD__ );
1575 }
1576
1577 /**
1578 * Actually output something with print(). Performs an iconv to the
1579 * output encoding, if needed.
1580 *
1581 * @param $ins String: the string to output
1582 */
1583 public function out( $ins ) {
1584 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1585 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1586 $outs = $ins;
1587 } else {
1588 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1589 if ( false === $outs ) { $outs = $ins; }
1590 }
1591 print $outs;
1592 }
1593
1594 /**
1595 * @todo document
1596 */
1597 public static function setEncodings() {
1598 global $wgInputEncoding, $wgOutputEncoding;
1599 global $wgContLang;
1600
1601 $wgInputEncoding = strtolower( $wgInputEncoding );
1602
1603 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
1604 $wgOutputEncoding = strtolower( $wgOutputEncoding );
1605 return;
1606 }
1607 $wgOutputEncoding = $wgInputEncoding;
1608 }
1609
1610 /**
1611 * @deprecated use wfReportTime() instead.
1612 *
1613 * @return String
1614 */
1615 public function reportTime() {
1616 wfDeprecated( __METHOD__ );
1617 $time = wfReportTime();
1618 return $time;
1619 }
1620
1621 /**
1622 * Produce a "user is blocked" page.
1623 *
1624 * @param $return Boolean: whether to have a "return to $wgTitle" message or not.
1625 * @return nothing
1626 */
1627 function blockedPage( $return = true ) {
1628 global $wgUser, $wgContLang, $wgLang;
1629
1630 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1631 $this->setRobotPolicy( 'noindex,nofollow' );
1632 $this->setArticleRelated( false );
1633
1634 $name = User::whoIs( $wgUser->blockedBy() );
1635 $reason = $wgUser->blockedFor();
1636 if( $reason == '' ) {
1637 $reason = wfMsg( 'blockednoreason' );
1638 }
1639 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW, $wgUser->mBlock->mTimestamp ), true );
1640 $ip = wfGetIP();
1641
1642 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
1643
1644 $blockid = $wgUser->mBlock->mId;
1645
1646 $blockExpiry = $wgUser->mBlock->mExpiry;
1647 if ( $blockExpiry == 'infinity' ) {
1648 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1649 // Search for localization in 'ipboptions'
1650 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1651 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1652 if ( strpos( $option, ":" ) === false )
1653 continue;
1654 list( $show, $value ) = explode( ":", $option );
1655 if ( $value == 'infinite' || $value == 'indefinite' ) {
1656 $blockExpiry = $show;
1657 break;
1658 }
1659 }
1660 } else {
1661 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW, $blockExpiry ), true );
1662 }
1663
1664 if ( $wgUser->mBlock->mAuto ) {
1665 $msg = 'autoblockedtext';
1666 } else {
1667 $msg = 'blockedtext';
1668 }
1669
1670 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1671 * This could be a username, an ip range, or a single ip. */
1672 $intended = $wgUser->mBlock->mAddress;
1673
1674 $this->addWikiMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
1675
1676 # Don't auto-return to special pages
1677 if( $return ) {
1678 $return = $this->getTitle()->getNamespace() > -1 ? $this->getTitle() : null;
1679 $this->returnToMain( null, $return );
1680 }
1681 }
1682
1683 /**
1684 * Output a standard error page
1685 *
1686 * @param $title String: message key for page title
1687 * @param $msg String: message key for page text
1688 * @param $params Array: message parameters
1689 */
1690 public function showErrorPage( $title, $msg, $params = array() ) {
1691 if ( $this->getTitle() ) {
1692 $this->mDebugtext .= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1693 }
1694 $this->setPageTitle( wfMsg( $title ) );
1695 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1696 $this->setRobotPolicy( 'noindex,nofollow' );
1697 $this->setArticleRelated( false );
1698 $this->enableClientCache( false );
1699 $this->mRedirect = '';
1700 $this->mBodytext = '';
1701
1702 array_unshift( $params, 'parse' );
1703 array_unshift( $params, $msg );
1704 $this->addHTML( call_user_func_array( 'wfMsgExt', $params ) );
1705
1706 $this->returnToMain();
1707 }
1708
1709 /**
1710 * Output a standard permission error page
1711 *
1712 * @param $errors Array: error message keys
1713 * @param $action String: action that was denied or null if unknown
1714 */
1715 public function showPermissionsErrorPage( $errors, $action = null ) {
1716 $this->mDebugtext .= 'Original title: ' .
1717 $this->getTitle()->getPrefixedText() . "\n";
1718 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1719 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1720 $this->setRobotPolicy( 'noindex,nofollow' );
1721 $this->setArticleRelated( false );
1722 $this->enableClientCache( false );
1723 $this->mRedirect = '';
1724 $this->mBodytext = '';
1725 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1726 }
1727
1728 /**
1729 * Display an error page indicating that a given version of MediaWiki is
1730 * required to use it
1731 *
1732 * @param $version Mixed: the version of MediaWiki needed to use the page
1733 */
1734 public function versionRequired( $version ) {
1735 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1736 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1737 $this->setRobotPolicy( 'noindex,nofollow' );
1738 $this->setArticleRelated( false );
1739 $this->mBodytext = '';
1740
1741 $this->addWikiMsg( 'versionrequiredtext', $version );
1742 $this->returnToMain();
1743 }
1744
1745 /**
1746 * Display an error page noting that a given permission bit is required.
1747 *
1748 * @param $permission String: key required
1749 */
1750 public function permissionRequired( $permission ) {
1751 global $wgLang;
1752
1753 $this->setPageTitle( wfMsg( 'badaccess' ) );
1754 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1755 $this->setRobotPolicy( 'noindex,nofollow' );
1756 $this->setArticleRelated( false );
1757 $this->mBodytext = '';
1758
1759 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1760 User::getGroupsWithPermission( $permission ) );
1761 if( $groups ) {
1762 $this->addWikiMsg( 'badaccess-groups',
1763 $wgLang->commaList( $groups ),
1764 count( $groups) );
1765 } else {
1766 $this->addWikiMsg( 'badaccess-group0' );
1767 }
1768 $this->returnToMain();
1769 }
1770
1771 /**
1772 * @deprecated use permissionRequired()
1773 */
1774 public function sysopRequired() {
1775 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
1776 }
1777
1778 /**
1779 * @deprecated use permissionRequired()
1780 */
1781 public function developerRequired() {
1782 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
1783 }
1784
1785 /**
1786 * Produce the stock "please login to use the wiki" page
1787 */
1788 public function loginToUse() {
1789 global $wgUser, $wgContLang;
1790
1791 if( $wgUser->isLoggedIn() ) {
1792 $this->permissionRequired( 'read' );
1793 return;
1794 }
1795
1796 $skin = $wgUser->getSkin();
1797
1798 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1799 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1800 $this->setRobotPolicy( 'noindex,nofollow' );
1801 $this->setArticleFlag( false );
1802
1803 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
1804 $loginLink = $skin->link(
1805 $loginTitle,
1806 wfMsgHtml( 'loginreqlink' ),
1807 array(),
1808 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
1809 array( 'known', 'noclasses' )
1810 );
1811 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1812 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . "-->" );
1813
1814 # Don't return to the main page if the user can't read it
1815 # otherwise we'll end up in a pointless loop
1816 $mainPage = Title::newMainPage();
1817 if( $mainPage->userCanRead() )
1818 $this->returnToMain( null, $mainPage );
1819 }
1820
1821 /**
1822 * Format a list of error messages
1823 *
1824 * @param $errors An array of arrays returned by Title::getUserPermissionsErrors
1825 * @param $action String: action that was denied or null if unknown
1826 * @return String: the wikitext error-messages, formatted into a list.
1827 */
1828 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1829 if ($action == null) {
1830 $text = wfMsgNoTrans( 'permissionserrorstext', count($errors)). "\n\n";
1831 } else {
1832 global $wgLang;
1833 $action_desc = wfMsgNoTrans( "action-$action" );
1834 $text = wfMsgNoTrans( 'permissionserrorstext-withaction', count($errors), $action_desc ) . "\n\n";
1835 }
1836
1837 if (count( $errors ) > 1) {
1838 $text .= '<ul class="permissions-errors">' . "\n";
1839
1840 foreach( $errors as $error )
1841 {
1842 $text .= '<li>';
1843 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1844 $text .= "</li>\n";
1845 }
1846 $text .= '</ul>';
1847 } else {
1848 $text .= "<div class=\"permissions-errors\">\n" . call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) . "\n</div>";
1849 }
1850
1851 return $text;
1852 }
1853
1854 /**
1855 * Display a page stating that the Wiki is in read-only mode,
1856 * and optionally show the source of the page that the user
1857 * was trying to edit. Should only be called (for this
1858 * purpose) after wfReadOnly() has returned true.
1859 *
1860 * For historical reasons, this function is _also_ used to
1861 * show the error message when a user tries to edit a page
1862 * they are not allowed to edit. (Unless it's because they're
1863 * blocked, then we show blockedPage() instead.) In this
1864 * case, the second parameter should be set to true and a list
1865 * of reasons supplied as the third parameter.
1866 *
1867 * @todo Needs to be split into multiple functions.
1868 *
1869 * @param $source String: source code to show (or null).
1870 * @param $protected Boolean: is this a permissions error?
1871 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
1872 * @param $action String: action that was denied or null if unknown
1873 */
1874 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1875 global $wgUser;
1876 $skin = $wgUser->getSkin();
1877
1878 $this->setRobotPolicy( 'noindex,nofollow' );
1879 $this->setArticleRelated( false );
1880
1881 // If no reason is given, just supply a default "I can't let you do
1882 // that, Dave" message. Should only occur if called by legacy code.
1883 if ( $protected && empty($reasons) ) {
1884 $reasons[] = array( 'badaccess-group0' );
1885 }
1886
1887 if ( !empty($reasons) ) {
1888 // Permissions error
1889 if( $source ) {
1890 $this->setPageTitle( wfMsg( 'viewsource' ) );
1891 $this->setSubtitle(
1892 wfMsg(
1893 'viewsourcefor',
1894 $skin->link(
1895 $this->getTitle(),
1896 null,
1897 array(),
1898 array(),
1899 array( 'known', 'noclasses' )
1900 )
1901 )
1902 );
1903 } else {
1904 $this->setPageTitle( wfMsg( 'badaccess' ) );
1905 }
1906 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1907 } else {
1908 // Wiki is read only
1909 $this->setPageTitle( wfMsg( 'readonly' ) );
1910 $reason = wfReadOnlyReason();
1911 $this->wrapWikiMsg( "<div class='mw-readonly-error'>\n$1</div>", array( 'readonlytext', $reason ) );
1912 }
1913
1914 // Show source, if supplied
1915 if( is_string( $source ) ) {
1916 $this->addWikiMsg( 'viewsourcetext' );
1917
1918 $params = array(
1919 'id' => 'wpTextbox1',
1920 'name' => 'wpTextbox1',
1921 'cols' => $wgUser->getOption( 'cols' ),
1922 'rows' => $wgUser->getOption( 'rows' ),
1923 'readonly' => 'readonly'
1924 );
1925 $this->addHTML( Html::element( 'textarea', $params, $source ) );
1926
1927 // Show templates used by this article
1928 $skin = $wgUser->getSkin();
1929 $article = new Article( $this->getTitle() );
1930 $this->addHTML( "<div class='templatesUsed'>
1931 {$skin->formatTemplates( $article->getUsedTemplates() )}
1932 </div>
1933 " );
1934 }
1935
1936 # If the title doesn't exist, it's fairly pointless to print a return
1937 # link to it. After all, you just tried editing it and couldn't, so
1938 # what's there to do there?
1939 if( $this->getTitle()->exists() ) {
1940 $this->returnToMain( null, $this->getTitle() );
1941 }
1942 }
1943
1944 /** @deprecated */
1945 public function errorpage( $title, $msg ) {
1946 wfDeprecated( __METHOD__ );
1947 throw new ErrorPageError( $title, $msg );
1948 }
1949
1950 /** @deprecated */
1951 public function databaseError( $fname, $sql, $error, $errno ) {
1952 throw new MWException( "OutputPage::databaseError is obsolete\n" );
1953 }
1954
1955 /** @deprecated */
1956 public function fatalError( $message ) {
1957 wfDeprecated( __METHOD__ );
1958 throw new FatalError( $message );
1959 }
1960
1961 /** @deprecated */
1962 public function unexpectedValueError( $name, $val ) {
1963 wfDeprecated( __METHOD__ );
1964 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1965 }
1966
1967 /** @deprecated */
1968 public function fileCopyError( $old, $new ) {
1969 wfDeprecated( __METHOD__ );
1970 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1971 }
1972
1973 /** @deprecated */
1974 public function fileRenameError( $old, $new ) {
1975 wfDeprecated( __METHOD__ );
1976 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1977 }
1978
1979 /** @deprecated */
1980 public function fileDeleteError( $name ) {
1981 wfDeprecated( __METHOD__ );
1982 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1983 }
1984
1985 /** @deprecated */
1986 public function fileNotFoundError( $name ) {
1987 wfDeprecated( __METHOD__ );
1988 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1989 }
1990
1991 public function showFatalError( $message ) {
1992 $this->setPageTitle( wfMsg( "internalerror" ) );
1993 $this->setRobotPolicy( "noindex,nofollow" );
1994 $this->setArticleRelated( false );
1995 $this->enableClientCache( false );
1996 $this->mRedirect = '';
1997 $this->mBodytext = $message;
1998 }
1999
2000 public function showUnexpectedValueError( $name, $val ) {
2001 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
2002 }
2003
2004 public function showFileCopyError( $old, $new ) {
2005 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
2006 }
2007
2008 public function showFileRenameError( $old, $new ) {
2009 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
2010 }
2011
2012 public function showFileDeleteError( $name ) {
2013 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
2014 }
2015
2016 public function showFileNotFoundError( $name ) {
2017 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
2018 }
2019
2020 /**
2021 * Add a "return to" link pointing to a specified title
2022 *
2023 * @param $title Title to link
2024 * @param $query String: query string
2025 * @param $text String text of the link (input is not escaped)
2026 */
2027 public function addReturnTo( $title, $query=array(), $text=null ) {
2028 global $wgUser;
2029 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullUrl() ) );
2030 $link = wfMsgHtml(
2031 'returnto',
2032 $wgUser->getSkin()->link( $title, $text, array(), $query )
2033 );
2034 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2035 }
2036
2037 /**
2038 * Add a "return to" link pointing to a specified title,
2039 * or the title indicated in the request, or else the main page
2040 *
2041 * @param $unused No longer used
2042 * @param $returnto Title or String to return to
2043 * @param $returntoquery String: query string for the return to link
2044 */
2045 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2046 global $wgRequest;
2047
2048 if ( $returnto == null ) {
2049 $returnto = $wgRequest->getText( 'returnto' );
2050 }
2051
2052 if ( $returntoquery == null ) {
2053 $returntoquery = $wgRequest->getText( 'returntoquery' );
2054 }
2055
2056 if ( $returnto === '' ) {
2057 $returnto = Title::newMainPage();
2058 }
2059
2060 if ( is_object( $returnto ) ) {
2061 $titleObj = $returnto;
2062 } else {
2063 $titleObj = Title::newFromText( $returnto );
2064 }
2065 if ( !is_object( $titleObj ) ) {
2066 $titleObj = Title::newMainPage();
2067 }
2068
2069 $this->addReturnTo( $titleObj, $returntoquery );
2070 }
2071
2072 /**
2073 * @param $sk Skin The given Skin
2074 * @param $includeStyle Unused (?)
2075 * @return String: The doctype, opening <html>, and head element.
2076 */
2077 public function headElement( Skin $sk, $includeStyle = true ) {
2078 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
2079 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces, $wgHtml5Version;
2080 global $wgContLang, $wgUseTrackbacks, $wgStyleVersion, $wgHtml5, $wgWellFormedXml;
2081 global $wgUser, $wgRequest, $wgLang;
2082
2083 if ( $sk->commonPrintStylesheet() ) {
2084 $this->addStyle( 'common/wikiprintable.css', 'print' );
2085 }
2086 $sk->setupUserCss( $this );
2087
2088 $ret = '';
2089
2090 if( $wgMimeType == 'text/xml' || $wgMimeType == 'application/xhtml+xml' || $wgMimeType == 'application/xml' ) {
2091 $ret .= "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?" . ">\n";
2092 }
2093
2094 if ( $this->getHTMLTitle() == '' ) {
2095 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ) );
2096 }
2097
2098 $dir = $wgContLang->getDir();
2099
2100 $htmlAttribs = array( 'lang' => $wgContLanguageCode, 'dir' => $dir );
2101 if ( $wgHtml5 ) {
2102 if ( $wgWellFormedXml ) {
2103 # Unknown elements and attributes are okay in XML, but unknown
2104 # named entities are well-formedness errors and will break XML
2105 # parsers. Thus we need a doctype that gives us appropriate
2106 # entity definitions. The HTML5 spec permits four legacy
2107 # doctypes as obsolete but conforming, so let's pick one of
2108 # those, although it makes our pages look like XHTML1 Strict.
2109 # Isn't compatibility great?
2110 $ret .= "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n";
2111 } else {
2112 # Much saner.
2113 $ret .= "<!doctype html>\n";
2114 }
2115 if ( $wgHtml5Version ) {
2116 $htmlAttribs['version'] = $wgHtml5Version;
2117 }
2118 } else {
2119 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\" \"$wgDTD\">\n";
2120 $htmlAttribs['xmlns'] = $wgXhtmlDefaultNamespace;
2121 foreach ( $wgXhtmlNamespaces as $tag => $ns ) {
2122 $htmlAttribs["xmlns:$tag"] = $ns;
2123 }
2124 $this->addMeta( 'http:Content-Type', "$wgMimeType; charset=$wgOutputEncoding" );
2125 }
2126 $ret .= Html::openElement( 'html', $htmlAttribs ) . "\n";
2127
2128 $openHead = Html::openElement( 'head' );
2129 if ( $openHead ) {
2130 # Don't bother with the newline if $head == ''
2131 $ret .= "$openHead\n";
2132 }
2133 $ret .= "<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n";
2134
2135 if ( $wgHtml5 ) {
2136 # More succinct than <meta http-equiv=Content-Type>, has the
2137 # same effect
2138 $ret .= Html::element( 'meta', array( 'charset' => $wgOutputEncoding ) ) . "\n";
2139 }
2140
2141 $ret .= implode( "\n", array(
2142 $this->getHeadLinks(),
2143 $this->buildCssLinks(),
2144 $this->getHeadScripts( $sk ),
2145 $this->getHeadItems(),
2146 ) );
2147 if ( $sk->usercss ) {
2148 $ret .= Html::inlineStyle( $sk->usercss );
2149 }
2150
2151 if ( $wgUseTrackbacks && $this->isArticleRelated() ) {
2152 $ret .= $this->getTitle()->trackbackRDF();
2153 }
2154
2155 $closeHead = Html::closeElement( 'head' );
2156 if ( $closeHead ) {
2157 $ret .= "$closeHead\n";
2158 }
2159
2160 $bodyAttrs = array();
2161
2162 # Crazy edit-on-double-click stuff
2163 $action = $wgRequest->getVal( 'action', 'view' );
2164
2165 if ( $this->getTitle()->getNamespace() != NS_SPECIAL
2166 && !in_array( $action, array( 'edit', 'submit' ) )
2167 && $wgUser->getOption( 'editondblclick' ) ) {
2168 $bodyAttrs['ondblclick'] = "document.location = '" . Xml::escapeJsString( $this->getTitle()->getEditURL() ) . "'";
2169 }
2170
2171 # Class bloat
2172 $bodyAttrs['class'] = "mediawiki $dir";
2173
2174 if ( $wgLang->capitalizeAllNouns() ) {
2175 # A <body> class is probably not the best way to do this . . .
2176 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2177 }
2178 $bodyAttrs['class'] .= ' ns-' . $this->getTitle()->getNamespace();
2179 if ( $this->getTitle()->getNamespace() == NS_SPECIAL ) {
2180 $bodyAttrs['class'] .= ' ns-special';
2181 } elseif ( $this->getTitle()->isTalkPage() ) {
2182 $bodyAttrs['class'] .= ' ns-talk';
2183 } else {
2184 $bodyAttrs['class'] .= ' ns-subject';
2185 }
2186 $bodyAttrs['class'] .= ' ' . Sanitizer::escapeClass( 'page-' . $this->getTitle()->getPrefixedText() );
2187 $bodyAttrs['class'] .= ' skin-' . Sanitizer::escapeClass( $wgUser->getSkin()->getSkinName() );
2188
2189 $ret .= Html::openElement( 'body', $bodyAttrs ) . "\n";
2190
2191 return $ret;
2192 }
2193
2194 /**
2195 * Gets the global variables and mScripts; also adds userjs to the end if
2196 * enabled
2197 *
2198 * @param $sk Skin object to use
2199 * @return String: HTML fragment
2200 */
2201 function getHeadScripts( Skin $sk ) {
2202 global $wgUser, $wgRequest, $wgJsMimeType, $wgUseSiteJs;
2203 global $wgStylePath, $wgStyleVersion;
2204
2205 $scripts = Skin::makeGlobalVariablesScript( $sk->getSkinName() );
2206 $scripts .= Html::linkedScript( "{$wgStylePath}/common/wikibits.js?$wgStyleVersion" );
2207
2208 //add site JS if enabled:
2209 if( $wgUseSiteJs ) {
2210 $jsCache = $wgUser->isLoggedIn() ? '&smaxage=0' : '';
2211 $this->addScriptFile( Skin::makeUrl( '-',
2212 "action=raw$jsCache&gen=js&useskin=" .
2213 urlencode( $sk->getSkinName() )
2214 )
2215 );
2216 }
2217
2218 //add user js if enabled:
2219 if( $this->isUserJsAllowed() && $wgUser->isLoggedIn() ) {
2220 $action = $wgRequest->getVal( 'action', 'view' );
2221 if( $this->mTitle && $this->mTitle->isJsSubpage() and $sk->userCanPreview( $action ) ) {
2222 # XXX: additional security check/prompt?
2223 $this->addInlineScript( $wgRequest->getText( 'wpTextbox1' ) );
2224 } else {
2225 $userpage = $wgUser->getUserPage();
2226 $names = array( 'common', $sk->getSkinName() );
2227 foreach( $names as $name ) {
2228 $scriptpage = Title::makeTitleSafe(
2229 NS_USER,
2230 $userpage->getDBkey() . '/' . $name . '.js'
2231 );
2232 if ( $scriptpage && $scriptpage->exists() ) {
2233 $userjs = $scriptpage->getLocalURL( 'action=raw&ctype=' . $wgJsMimeType );
2234 $this->addScriptFile( $userjs );
2235 }
2236 }
2237 }
2238 }
2239
2240 $scripts .= "\n" . $this->mScripts;
2241 return $scripts;
2242 }
2243
2244 /**
2245 * Add default \<meta\> tags
2246 */
2247 protected function addDefaultMeta() {
2248 global $wgVersion, $wgHtml5;
2249
2250 static $called = false;
2251 if ( $called ) {
2252 # Don't run this twice
2253 return;
2254 }
2255 $called = true;
2256
2257 if ( !$wgHtml5 ) {
2258 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); //bug 15835
2259 }
2260 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
2261
2262 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
2263 if( $p !== 'index,follow' ) {
2264 // http://www.robotstxt.org/wc/meta-user.html
2265 // Only show if it's different from the default robots policy
2266 $this->addMeta( 'robots', $p );
2267 }
2268
2269 if ( count( $this->mKeywords ) > 0 ) {
2270 $strip = array(
2271 "/<.*?" . ">/" => '',
2272 "/_/" => ' '
2273 );
2274 $this->addMeta( 'keywords', preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords ) ) );
2275 }
2276 }
2277
2278 /**
2279 * @return string HTML tag links to be put in the header.
2280 */
2281 public function getHeadLinks() {
2282 global $wgRequest, $wgFeed;
2283
2284 // Ideally this should happen earlier, somewhere. :P
2285 $this->addDefaultMeta();
2286
2287 $tags = array();
2288
2289 foreach ( $this->mMetatags as $tag ) {
2290 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
2291 $a = 'http-equiv';
2292 $tag[0] = substr( $tag[0], 5 );
2293 } else {
2294 $a = 'name';
2295 }
2296 $tags[] = Html::element( 'meta',
2297 array(
2298 $a => $tag[0],
2299 'content' => $tag[1] ) );
2300 }
2301 foreach ( $this->mLinktags as $tag ) {
2302 $tags[] = Html::element( 'link', $tag );
2303 }
2304
2305 if( $wgFeed ) {
2306 foreach( $this->getSyndicationLinks() as $format => $link ) {
2307 # Use the page name for the title (accessed through $wgTitle since
2308 # there's no other way). In principle, this could lead to issues
2309 # with having the same name for different feeds corresponding to
2310 # the same page, but we can't avoid that at this low a level.
2311
2312 $tags[] = $this->feedLink(
2313 $format,
2314 $link,
2315 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
2316 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() ) );
2317 }
2318
2319 # Recent changes feed should appear on every page (except recentchanges,
2320 # that would be redundant). Put it after the per-page feed to avoid
2321 # changing existing behavior. It's still available, probably via a
2322 # menu in your browser. Some sites might have a different feed they'd
2323 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
2324 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
2325 # If so, use it instead.
2326
2327 global $wgOverrideSiteFeed, $wgSitename, $wgAdvertisedFeedTypes;
2328 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
2329
2330 if ( $wgOverrideSiteFeed ) {
2331 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
2332 $tags[] = $this->feedLink (
2333 $type,
2334 htmlspecialchars( $feedUrl ),
2335 wfMsg( "site-{$type}-feed", $wgSitename ) );
2336 }
2337 } elseif ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
2338 foreach ( $wgAdvertisedFeedTypes as $format ) {
2339 $tags[] = $this->feedLink(
2340 $format,
2341 $rctitle->getLocalURL( "feed={$format}" ),
2342 wfMsg( "site-{$format}-feed", $wgSitename ) ); # For grep: 'site-rss-feed', 'site-atom-feed'.
2343 }
2344 }
2345 }
2346
2347 return implode( "\n", $tags );
2348 }
2349
2350 /**
2351 * Generate a <link rel/> for a feed.
2352 *
2353 * @param $type String: feed type
2354 * @param $url String: URL to the feed
2355 * @param $text String: value of the "title" attribute
2356 * @return String: HTML fragment
2357 */
2358 private function feedLink( $type, $url, $text ) {
2359 return Html::element( 'link', array(
2360 'rel' => 'alternate',
2361 'type' => "application/$type+xml",
2362 'title' => $text,
2363 'href' => $url ) );
2364 }
2365
2366 /**
2367 * Add a local or specified stylesheet, with the given media options.
2368 * Meant primarily for internal use...
2369 *
2370 * @param $style String: URL to the file
2371 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
2372 * @param $condition String: for IE conditional comments, specifying an IE version
2373 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
2374 */
2375 public function addStyle( $style, $media='', $condition='', $dir='' ) {
2376 $options = array();
2377 // Even though we expect the media type to be lowercase, but here we
2378 // force it to lowercase to be safe.
2379 if( $media )
2380 $options['media'] = $media;
2381 if( $condition )
2382 $options['condition'] = $condition;
2383 if( $dir )
2384 $options['dir'] = $dir;
2385 $this->styles[$style] = $options;
2386 }
2387
2388 /**
2389 * Adds inline CSS styles
2390 * @param $style_css Mixed: inline CSS
2391 */
2392 public function addInlineStyle( $style_css ){
2393 $this->mScripts .= Html::inlineStyle( $style_css );
2394 }
2395
2396 /**
2397 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
2398 * These will be applied to various media & IE conditionals.
2399 */
2400 public function buildCssLinks() {
2401 $links = array();
2402 foreach( $this->styles as $file => $options ) {
2403 $link = $this->styleLink( $file, $options );
2404 if( $link )
2405 $links[] = $link;
2406 }
2407
2408 return implode( "\n", $links );
2409 }
2410
2411 /**
2412 * Generate \<link\> tags for stylesheets
2413 *
2414 * @param $style String: URL to the file
2415 * @param $options Array: option, can contain 'condition', 'dir', 'media'
2416 * keys
2417 * @return String: HTML fragment
2418 */
2419 protected function styleLink( $style, $options ) {
2420 global $wgRequest;
2421
2422 if( isset( $options['dir'] ) ) {
2423 global $wgContLang;
2424 $siteDir = $wgContLang->getDir();
2425 if( $siteDir != $options['dir'] )
2426 return '';
2427 }
2428
2429 if( isset( $options['media'] ) ) {
2430 $media = $this->transformCssMedia( $options['media'] );
2431 if( is_null( $media ) ) {
2432 return '';
2433 }
2434 } else {
2435 $media = 'all';
2436 }
2437
2438 if( substr( $style, 0, 1 ) == '/' ||
2439 substr( $style, 0, 5 ) == 'http:' ||
2440 substr( $style, 0, 6 ) == 'https:' ) {
2441 $url = $style;
2442 } else {
2443 global $wgStylePath, $wgStyleVersion;
2444 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
2445 }
2446
2447 $link = Html::linkedStyle( $url, $media );
2448
2449 if( isset( $options['condition'] ) ) {
2450 $condition = htmlspecialchars( $options['condition'] );
2451 $link = "<!--[if $condition]>$link<![endif]-->";
2452 }
2453 return $link;
2454 }
2455
2456 /**
2457 * Transform "media" attribute based on request parameters
2458 *
2459 * @param $media String: current value of the "media" attribute
2460 * @return String: modified value of the "media" attribute
2461 */
2462 function transformCssMedia( $media ) {
2463 global $wgRequest, $wgHandheldForIPhone;
2464
2465 // Switch in on-screen display for media testing
2466 $switches = array(
2467 'printable' => 'print',
2468 'handheld' => 'handheld',
2469 );
2470 foreach( $switches as $switch => $targetMedia ) {
2471 if( $wgRequest->getBool( $switch ) ) {
2472 if( $media == $targetMedia ) {
2473 $media = '';
2474 } elseif( $media == 'screen' ) {
2475 return null;
2476 }
2477 }
2478 }
2479
2480 // Expand longer media queries as iPhone doesn't grok 'handheld'
2481 if( $wgHandheldForIPhone ) {
2482 $mediaAliases = array(
2483 'screen' => 'screen and (min-device-width: 481px)',
2484 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
2485 );
2486
2487 if( isset( $mediaAliases[$media] ) ) {
2488 $media = $mediaAliases[$media];
2489 }
2490 }
2491
2492 return $media;
2493 }
2494
2495 /**
2496 * Turn off regular page output and return an error reponse
2497 * for when rate limiting has triggered.
2498 */
2499 public function rateLimited() {
2500 $this->setPageTitle(wfMsg('actionthrottled'));
2501 $this->setRobotPolicy( 'noindex,follow' );
2502 $this->setArticleRelated( false );
2503 $this->enableClientCache( false );
2504 $this->mRedirect = '';
2505 $this->clearHTML();
2506 $this->setStatusCode(503);
2507 $this->addWikiMsg( 'actionthrottledtext' );
2508
2509 $this->returnToMain( null, $this->getTitle() );
2510 }
2511
2512 /**
2513 * Show a warning about slave lag
2514 *
2515 * If the lag is higher than $wgSlaveLagCritical seconds,
2516 * then the warning is a bit more obvious. If the lag is
2517 * lower than $wgSlaveLagWarning, then no warning is shown.
2518 *
2519 * @param $lag Integer: slave lag
2520 */
2521 public function showLagWarning( $lag ) {
2522 global $wgSlaveLagWarning, $wgSlaveLagCritical, $wgLang;
2523 if( $lag >= $wgSlaveLagWarning ) {
2524 $message = $lag < $wgSlaveLagCritical
2525 ? 'lag-warn-normal'
2526 : 'lag-warn-high';
2527 $wrap = Html::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2528 $this->wrapWikiMsg( "$wrap\n", array( $message, $wgLang->formatNum( $lag ) ) );
2529 }
2530 }
2531
2532 /**
2533 * Add a wikitext-formatted message to the output.
2534 * This is equivalent to:
2535 *
2536 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2537 */
2538 public function addWikiMsg( /*...*/ ) {
2539 $args = func_get_args();
2540 $name = array_shift( $args );
2541 $this->addWikiMsgArray( $name, $args );
2542 }
2543
2544 /**
2545 * Add a wikitext-formatted message to the output.
2546 * Like addWikiMsg() except the parameters are taken as an array
2547 * instead of a variable argument list.
2548 *
2549 * $options is passed through to wfMsgExt(), see that function for details.
2550 */
2551 public function addWikiMsgArray( $name, $args, $options = array() ) {
2552 $options[] = 'parse';
2553 $text = wfMsgExt( $name, $options, $args );
2554 $this->addHTML( $text );
2555 }
2556
2557 /**
2558 * This function takes a number of message/argument specifications, wraps them in
2559 * some overall structure, and then parses the result and adds it to the output.
2560 *
2561 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
2562 * on. The subsequent arguments may either be strings, in which case they are the
2563 * message names, or arrays, in which case the first element is the message name,
2564 * and subsequent elements are the parameters to that message.
2565 *
2566 * The special named parameter 'options' in a message specification array is passed
2567 * through to the $options parameter of wfMsgExt().
2568 *
2569 * Don't use this for messages that are not in users interface language.
2570 *
2571 * For example:
2572 *
2573 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>", 'some-error' );
2574 *
2575 * Is equivalent to:
2576 *
2577 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . "</div>" );
2578 *
2579 * The newline after opening div is needed in some wikitext. See bug 19226.
2580 */
2581 public function wrapWikiMsg( $wrap /*, ...*/ ) {
2582 $msgSpecs = func_get_args();
2583 array_shift( $msgSpecs );
2584 $msgSpecs = array_values( $msgSpecs );
2585 $s = $wrap;
2586 foreach ( $msgSpecs as $n => $spec ) {
2587 $options = array();
2588 if ( is_array( $spec ) ) {
2589 $args = $spec;
2590 $name = array_shift( $args );
2591 if ( isset( $args['options'] ) ) {
2592 $options = $args['options'];
2593 unset( $args['options'] );
2594 }
2595 } else {
2596 $args = array();
2597 $name = $spec;
2598 }
2599 $s = str_replace( '$' . ( $n + 1 ), wfMsgExt( $name, $options, $args ), $s );
2600 }
2601 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );
2602 }
2603
2604 /**
2605 * Include jQuery core. Use this to avoid loading it multiple times
2606 * before we get a usable script loader.
2607 *
2608 * @param $modules Array: list of jQuery modules which should be loaded
2609 * @return Array: the list of modules which were not loaded.
2610 * @since 1.16
2611 */
2612 public function includeJQuery( $modules = array() ) {
2613 global $wgStylePath, $wgStyleVersion;
2614
2615 $supportedModules = array( /** TODO: add things here */ );
2616 $unsupported = array_diff( $modules, $supportedModules );
2617
2618 $url = "$wgStylePath/common/jquery.min.js?$wgStyleVersion";
2619 if ( !$this->mJQueryDone ) {
2620 $this->mJQueryDone = true;
2621 $this->mScripts = Html::linkedScript( $url ) . "\n" . $this->mScripts;
2622 }
2623 return $unsupported;
2624 }
2625
2626 }