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