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