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