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