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