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