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