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