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