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