Revert r91426 and followups r91427, r91430: Breaks Gallery-related parser tests
[mediawiki.git] / includes / OutputPage.php
blob1de0b653b66cfb8f42c1ed4cd264bd5d0ada2cfd
1 <?php
2 if ( !defined( 'MEDIAWIKI' ) ) {
3 die( 1 );
6 /**
7 * This class should be covered by a general architecture document which does
8 * not exist as of January 2011. This is one of the Core classes and should
9 * be read at least once by any new developers.
11 * This class is used to prepare the final rendering. A skin is then
12 * applied to the output parameters (links, javascript, html, categories ...).
14 * @todo FIXME: Another class handles sending the whole page to the client.
16 * Some comments comes from a pairing session between Zak Greant and Ashar Voultoiz
17 * in November 2010.
19 * @todo document
21 class OutputPage {
22 /// Should be private. Used with addMeta() which adds <meta>
23 var $mMetatags = array();
25 /// <meta keyworkds="stuff"> most of the time the first 10 links to an article
26 var $mKeywords = array();
28 var $mLinktags = array();
30 /// Additional stylesheets. Looks like this is for extensions. Might be replaced by resource loader.
31 var $mExtStyles = array();
33 /// Should be private - has getter and setter. Contains the HTML title
34 var $mPagetitle = '';
36 /// Contains all of the <body> content. Should be private we got set/get accessors and the append() method.
37 var $mBodytext = '';
39 /**
40 * Holds the debug lines that will be output as comments in page source if
41 * $wgDebugComments is enabled. See also $wgShowDebug.
42 * TODO: make a getter method for this
44 public $mDebugtext = ''; // TODO: we might want to replace it by wfDebug() wfDebugLog()
46 /// Should be private. Stores contents of <title> tag
47 var $mHTMLtitle = '';
49 /// Should be private. Is the displayed content related to the source of the corresponding wiki article.
50 var $mIsarticle = true;
52 /**
53 * Should be private. We have to set isPrintable(). Some pages should
54 * never be printed (ex: redirections).
56 var $mPrintable = false;
58 /**
59 * Should be private. We have set/get/append methods.
61 * Contains the page subtitle. Special pages usually have some links here.
62 * Don't confuse with site subtitle added by skins.
64 var $mSubtitle = '';
66 var $mRedirect = '';
67 var $mStatusCode;
69 /**
70 * mLastModified and mEtag are used for sending cache control.
71 * The whole caching system should probably be moved into its own class.
73 var $mLastModified = '';
75 /**
76 * Should be private. No getter but used in sendCacheControl();
77 * Contains an HTTP Entity Tags (see RFC 2616 section 3.13) which is used
78 * as a unique identifier for the content. It is later used by the client
79 * to compare its cached version with the server version. Client sends
80 * headers If-Match and If-None-Match containing its locally cached ETAG value.
82 * To get more information, you will have to look at HTTP/1.1 protocol which
83 * is properly described in RFC 2616 : http://tools.ietf.org/html/rfc2616
85 var $mETag = false;
87 var $mCategoryLinks = array();
88 var $mCategories = array();
90 /// Should be private. Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
91 var $mLanguageLinks = array();
93 /**
94 * Should be private. Used for JavaScript (pre resource loader)
95 * We should split js / css.
96 * mScripts content is inserted as is in <head> by Skin. This might contains
97 * either a link to a stylesheet or inline css.
99 var $mScripts = '';
102 * Inline CSS styles. Use addInlineStyle() sparsingly
104 var $mInlineStyles = '';
107 var $mLinkColours;
110 * Used by skin template.
111 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
113 var $mPageLinkTitle = '';
115 /// Array of elements in <head>. Parser might add its own headers!
116 var $mHeadItems = array();
118 // @todo FIXME: Next variables probably comes from the resource loader
119 var $mModules = array(), $mModuleScripts = array(), $mModuleStyles = array(), $mModuleMessages = array();
120 var $mResourceLoader;
122 /** @todo FIXME: Is this still used ?*/
123 var $mInlineMsg = array();
125 var $mTemplateIds = array();
126 var $mImageTimeKeys = array();
128 # What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
129 # @see ResourceLoaderModule::$origin
130 # ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
131 protected $mAllowedModules = array(
132 ResourceLoaderModule::TYPE_COMBINED => ResourceLoaderModule::ORIGIN_ALL,
136 * @EasterEgg I just love the name for this self documenting variable.
137 * @todo document
139 var $mDoNothing = false;
141 // Parser related.
142 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
145 * Should be private. Has get/set methods properly documented.
146 * Stores "article flag" toggle.
148 var $mIsArticleRelated = true;
150 /// lazy initialised, use parserOptions()
151 protected $mParserOptions = null;
154 * Handles the atom / rss links.
155 * We probably only support atom in 2011.
156 * Looks like a private variable.
157 * @see $wgAdvertisedFeedTypes
159 var $mFeedLinks = array();
161 // Gwicke work on squid caching? Roughly from 2003.
162 var $mEnableClientCache = true;
165 * Flag if output should only contain the body of the article.
166 * Should be private.
168 var $mArticleBodyOnly = false;
170 var $mNewSectionLink = false;
171 var $mHideNewSectionLink = false;
174 * Comes from the parser. This was probably made to load CSS/JS only
175 * if we had <gallery>. Used directly in CategoryPage.php
176 * Looks like resource loader can replace this.
178 var $mNoGallery = false;
180 // should be private.
181 var $mPageTitleActionText = '';
182 var $mParseWarnings = array();
184 // Cache stuff. Looks like mEnableClientCache
185 var $mSquidMaxage = 0;
187 // @todo document
188 var $mPreventClickjacking = true;
190 /// should be private. To include the variable {{REVISIONID}}
191 var $mRevisionId = null;
193 var $mFileVersion = null;
195 private $mContext;
198 * An array of stylesheet filenames (relative from skins path), with options
199 * for CSS media, IE conditions, and RTL/LTR direction.
200 * For internal use; add settings in the skin via $this->addStyle()
202 * Style again! This seems like a code duplication since we already have
203 * mStyles. This is what makes OpenSource amazing.
205 var $styles = array();
208 * Whether jQuery is already handled.
210 protected $mJQueryDone = false;
212 private $mIndexPolicy = 'index';
213 private $mFollowPolicy = 'follow';
214 private $mVaryHeader = array(
215 'Accept-Encoding' => array( 'list-contains=gzip' ),
216 'Cookie' => null
220 * Constructor for OutputPage. This should not be called directly.
221 * Instead a new RequestContext should be created and it will implicitly create
222 * a OutputPage tied to that context.
224 function __construct( RequestContext $context = null ) {
225 if ( !isset($context) ) {
226 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
227 wfDeprecated( __METHOD__ );
229 $this->mContext = $context;
233 * Redirect to $url rather than displaying the normal page
235 * @param $url String: URL
236 * @param $responsecode String: HTTP status code
238 public function redirect( $url, $responsecode = '302' ) {
239 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
240 $this->mRedirect = str_replace( "\n", '', $url );
241 $this->mRedirectCode = $responsecode;
245 * Get the URL to redirect to, or an empty string if not redirect URL set
247 * @return String
249 public function getRedirect() {
250 return $this->mRedirect;
254 * Set the HTTP status code to send with the output.
256 * @param $statusCode Integer
258 public function setStatusCode( $statusCode ) {
259 $this->mStatusCode = $statusCode;
263 * Add a new <meta> tag
264 * To add an http-equiv meta tag, precede the name with "http:"
266 * @param $name String tag name
267 * @param $val String tag value
269 function addMeta( $name, $val ) {
270 array_push( $this->mMetatags, array( $name, $val ) );
274 * Add a keyword or a list of keywords in the page header
276 * @param $text String or array of strings
278 function addKeyword( $text ) {
279 if( is_array( $text ) ) {
280 $this->mKeywords = array_merge( $this->mKeywords, $text );
281 } else {
282 array_push( $this->mKeywords, $text );
287 * Add a new \<link\> tag to the page header
289 * @param $linkarr Array: associative array of attributes.
291 function addLink( $linkarr ) {
292 array_push( $this->mLinktags, $linkarr );
296 * Add a new \<link\> with "rel" attribute set to "meta"
298 * @param $linkarr Array: associative array mapping attribute names to their
299 * values, both keys and values will be escaped, and the
300 * "rel" attribute will be automatically added
302 function addMetadataLink( $linkarr ) {
303 $linkarr['rel'] = $this->getMetadataAttribute();
304 $this->addLink( $linkarr );
308 * Get the value of the "rel" attribute for metadata links
310 * @return String
312 public function getMetadataAttribute() {
313 # note: buggy CC software only reads first "meta" link
314 static $haveMeta = false;
315 if ( $haveMeta ) {
316 return 'alternate meta';
317 } else {
318 $haveMeta = true;
319 return 'meta';
324 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
326 * @param $script String: raw HTML
328 function addScript( $script ) {
329 $this->mScripts .= $script . "\n";
333 * Register and add a stylesheet from an extension directory.
335 * @param $url String path to sheet. Provide either a full url (beginning
336 * with 'http', etc) or a relative path from the document root
337 * (beginning with '/'). Otherwise it behaves identically to
338 * addStyle() and draws from the /skins folder.
340 public function addExtensionStyle( $url ) {
341 array_push( $this->mExtStyles, $url );
345 * Get all styles added by extensions
347 * @return Array
349 function getExtStyle() {
350 return $this->mExtStyles;
354 * Add a JavaScript file out of skins/common, or a given relative path.
356 * @param $file String: filename in skins/common or complete on-server path
357 * (/foo/bar.js)
358 * @param $version String: style version of the file. Defaults to $wgStyleVersion
360 public function addScriptFile( $file, $version = null ) {
361 global $wgStylePath, $wgStyleVersion;
362 // See if $file parameter is an absolute URL or begins with a slash
363 if( substr( $file, 0, 1 ) == '/' || preg_match( '#^[a-z]*://#i', $file ) ) {
364 $path = $file;
365 } else {
366 $path = "{$wgStylePath}/common/{$file}";
368 if ( is_null( $version ) )
369 $version = $wgStyleVersion;
370 $this->addScript( Html::linkedScript( wfAppendQuery( $path, $version ) ) );
374 * Add a self-contained script tag with the given contents
376 * @param $script String: JavaScript text, no <script> tags
378 public function addInlineScript( $script ) {
379 $this->mScripts .= Html::inlineScript( "\n$script\n" ) . "\n";
383 * Get all registered JS and CSS tags for the header.
385 * @return String
387 function getScript() {
388 return $this->mScripts . $this->getHeadItems();
392 * Filter an array of modules to remove insufficiently trustworthy members, and modules
393 * which are no longer registered (eg a page is cached before an extension is disabled)
394 * @param $modules Array
395 * @param $position String if not null, only return modules with this position
396 * @param $type string
397 * @return Array
399 protected function filterModules( $modules, $position = null, $type = ResourceLoaderModule::TYPE_COMBINED ){
400 $resourceLoader = $this->getResourceLoader();
401 $filteredModules = array();
402 foreach( $modules as $val ){
403 $module = $resourceLoader->getModule( $val );
404 if( $module instanceof ResourceLoaderModule
405 && $module->getOrigin() <= $this->getAllowedModules( $type )
406 && ( is_null( $position ) || $module->getPosition() == $position ) )
408 $filteredModules[] = $val;
411 return $filteredModules;
415 * Get the list of modules to include on this page
417 * @param $filter Bool whether to filter out insufficiently trustworthy modules
418 * @param $position String if not null, only return modules with this position
419 * @param $param string
420 * @return Array of module names
422 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
423 $modules = array_values( array_unique( $this->$param ) );
424 return $filter
425 ? $this->filterModules( $modules, $position )
426 : $modules;
430 * Add one or more modules recognized by the resource loader. Modules added
431 * through this function will be loaded by the resource loader when the
432 * page loads.
434 * @param $modules Mixed: module name (string) or array of module names
436 public function addModules( $modules ) {
437 $this->mModules = array_merge( $this->mModules, (array)$modules );
441 * Get the list of module JS to include on this page
443 * @param $filter
444 * @param $position
446 * @return array of module names
448 public function getModuleScripts( $filter = false, $position = null ) {
449 return $this->getModules( $filter, $position, 'mModuleScripts' );
453 * Add only JS of one or more modules recognized by the resource loader. Module
454 * scripts added through this function will be loaded by the resource loader when
455 * the page loads.
457 * @param $modules Mixed: module name (string) or array of module names
459 public function addModuleScripts( $modules ) {
460 $this->mModuleScripts = array_merge( $this->mModuleScripts, (array)$modules );
464 * Get the list of module CSS to include on this page
466 * @param $filter
467 * @param $position
469 * @return Array of module names
471 public function getModuleStyles( $filter = false, $position = null ) {
472 return $this->getModules( $filter, $position, 'mModuleStyles' );
476 * Add only CSS of one or more modules recognized by the resource loader. Module
477 * styles added through this function will be loaded by the resource loader when
478 * the page loads.
480 * @param $modules Mixed: module name (string) or array of module names
482 public function addModuleStyles( $modules ) {
483 $this->mModuleStyles = array_merge( $this->mModuleStyles, (array)$modules );
487 * Get the list of module messages to include on this page
489 * @param $filter
490 * @param $position
492 * @return Array of module names
494 public function getModuleMessages( $filter = false, $position = null ) {
495 return $this->getModules( $filter, $position, 'mModuleMessages' );
499 * Add only messages of one or more modules recognized by the resource loader.
500 * Module messages added through this function will be loaded by the resource
501 * loader when the page loads.
503 * @param $modules Mixed: module name (string) or array of module names
505 public function addModuleMessages( $modules ) {
506 $this->mModuleMessages = array_merge( $this->mModuleMessages, (array)$modules );
510 * Get all header items in a string
512 * @return String
514 function getHeadItems() {
515 $s = '';
516 foreach ( $this->mHeadItems as $item ) {
517 $s .= $item;
519 return $s;
523 * Add or replace an header item to the output
525 * @param $name String: item name
526 * @param $value String: raw HTML
528 public function addHeadItem( $name, $value ) {
529 $this->mHeadItems[$name] = $value;
533 * Check if the header item $name is already set
535 * @param $name String: item name
536 * @return Boolean
538 public function hasHeadItem( $name ) {
539 return isset( $this->mHeadItems[$name] );
543 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
545 * @param $tag String: value of "ETag" header
547 function setETag( $tag ) {
548 $this->mETag = $tag;
552 * Set whether the output should only contain the body of the article,
553 * without any skin, sidebar, etc.
554 * Used e.g. when calling with "action=render".
556 * @param $only Boolean: whether to output only the body of the article
558 public function setArticleBodyOnly( $only ) {
559 $this->mArticleBodyOnly = $only;
563 * Return whether the output will contain only the body of the article
565 * @return Boolean
567 public function getArticleBodyOnly() {
568 return $this->mArticleBodyOnly;
572 * checkLastModified tells the client to use the client-cached page if
573 * possible. If sucessful, the OutputPage is disabled so that
574 * any future call to OutputPage->output() have no effect.
576 * Side effect: sets mLastModified for Last-Modified header
578 * @param $timestamp string
580 * @return Boolean: true iff cache-ok headers was sent.
582 public function checkLastModified( $timestamp ) {
583 global $wgCachePages, $wgCacheEpoch;
585 if ( !$timestamp || $timestamp == '19700101000000' ) {
586 wfDebug( __METHOD__ . ": CACHE DISABLED, NO TIMESTAMP\n" );
587 return false;
589 if( !$wgCachePages ) {
590 wfDebug( __METHOD__ . ": CACHE DISABLED\n", false );
591 return false;
593 if( $this->getUser()->getOption( 'nocache' ) ) {
594 wfDebug( __METHOD__ . ": USER DISABLED CACHE\n", false );
595 return false;
598 $timestamp = wfTimestamp( TS_MW, $timestamp );
599 $modifiedTimes = array(
600 'page' => $timestamp,
601 'user' => $this->getUser()->getTouched(),
602 'epoch' => $wgCacheEpoch
604 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
606 $maxModified = max( $modifiedTimes );
607 $this->mLastModified = wfTimestamp( TS_RFC2822, $maxModified );
609 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
610 wfDebug( __METHOD__ . ": client did not send If-Modified-Since header\n", false );
611 return false;
614 # Make debug info
615 $info = '';
616 foreach ( $modifiedTimes as $name => $value ) {
617 if ( $info !== '' ) {
618 $info .= ', ';
620 $info .= "$name=" . wfTimestamp( TS_ISO_8601, $value );
623 # IE sends sizes after the date like this:
624 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
625 # this breaks strtotime().
626 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
628 wfSuppressWarnings(); // E_STRICT system time bitching
629 $clientHeaderTime = strtotime( $clientHeader );
630 wfRestoreWarnings();
631 if ( !$clientHeaderTime ) {
632 wfDebug( __METHOD__ . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
633 return false;
635 $clientHeaderTime = wfTimestamp( TS_MW, $clientHeaderTime );
637 wfDebug( __METHOD__ . ": client sent If-Modified-Since: " .
638 wfTimestamp( TS_ISO_8601, $clientHeaderTime ) . "\n", false );
639 wfDebug( __METHOD__ . ": effective Last-Modified: " .
640 wfTimestamp( TS_ISO_8601, $maxModified ) . "\n", false );
641 if( $clientHeaderTime < $maxModified ) {
642 wfDebug( __METHOD__ . ": STALE, $info\n", false );
643 return false;
646 # Not modified
647 # Give a 304 response code and disable body output
648 wfDebug( __METHOD__ . ": NOT MODIFIED, $info\n", false );
649 ini_set( 'zlib.output_compression', 0 );
650 $this->getRequest()->response()->header( "HTTP/1.1 304 Not Modified" );
651 $this->sendCacheControl();
652 $this->disable();
654 // Don't output a compressed blob when using ob_gzhandler;
655 // it's technically against HTTP spec and seems to confuse
656 // Firefox when the response gets split over two packets.
657 wfClearOutputBuffers();
659 return true;
663 * Override the last modified timestamp
665 * @param $timestamp String: new timestamp, in a format readable by
666 * wfTimestamp()
668 public function setLastModified( $timestamp ) {
669 $this->mLastModified = wfTimestamp( TS_RFC2822, $timestamp );
673 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
675 * @param $policy String: the literal string to output as the contents of
676 * the meta tag. Will be parsed according to the spec and output in
677 * standardized form.
678 * @return null
680 public function setRobotPolicy( $policy ) {
681 $policy = Article::formatRobotPolicy( $policy );
683 if( isset( $policy['index'] ) ) {
684 $this->setIndexPolicy( $policy['index'] );
686 if( isset( $policy['follow'] ) ) {
687 $this->setFollowPolicy( $policy['follow'] );
692 * Set the index policy for the page, but leave the follow policy un-
693 * touched.
695 * @param $policy string Either 'index' or 'noindex'.
696 * @return null
698 public function setIndexPolicy( $policy ) {
699 $policy = trim( $policy );
700 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
701 $this->mIndexPolicy = $policy;
706 * Set the follow policy for the page, but leave the index policy un-
707 * touched.
709 * @param $policy String: either 'follow' or 'nofollow'.
710 * @return null
712 public function setFollowPolicy( $policy ) {
713 $policy = trim( $policy );
714 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
715 $this->mFollowPolicy = $policy;
720 * Set the new value of the "action text", this will be added to the
721 * "HTML title", separated from it with " - ".
723 * @param $text String: new value of the "action text"
725 public function setPageTitleActionText( $text ) {
726 $this->mPageTitleActionText = $text;
730 * Get the value of the "action text"
732 * @return String
734 public function getPageTitleActionText() {
735 if ( isset( $this->mPageTitleActionText ) ) {
736 return $this->mPageTitleActionText;
741 * "HTML title" means the contents of <title>.
742 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
744 * @param $name string
746 public function setHTMLTitle( $name ) {
747 $this->mHTMLtitle = $name;
751 * Return the "HTML title", i.e. the content of the <title> tag.
753 * @return String
755 public function getHTMLTitle() {
756 return $this->mHTMLtitle;
760 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
761 * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
762 * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
763 * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
765 * @param $name string
767 public function setPageTitle( $name ) {
768 # change "<script>foo&bar</script>" to "&lt;script&gt;foo&amp;bar&lt;/script&gt;"
769 # but leave "<i>foobar</i>" alone
770 $nameWithTags = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags( $name ) );
771 $this->mPagetitle = $nameWithTags;
773 # change "<i>foo&amp;bar</i>" to "foo&bar"
774 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer::stripAllTags( $nameWithTags ) ) );
778 * Return the "page title", i.e. the content of the \<h1\> tag.
780 * @return String
782 public function getPageTitle() {
783 return $this->mPagetitle;
787 * Get the RequestContext used in this instance
789 * @return RequestContext
791 private function getContext() {
792 if ( !isset($this->mContext) ) {
793 wfDebug( __METHOD__ . " called and \$mContext is null. Using RequestContext::getMain(); for sanity\n" );
794 $this->mContext = RequestContext::getMain();
796 return $this->mContext;
800 * Get the WebRequest being used for this instance
802 * @return WebRequest
803 * @since 1.18
805 public function getRequest() {
806 return $this->getContext()->getRequest();
810 * Set the Title object to use
812 * @param $t Title object
814 public function setTitle( $t ) {
815 $this->getContext()->setTitle( $t );
819 * Get the Title object used in this instance
821 * @return Title
823 public function getTitle() {
824 return $this->getContext()->getTitle();
828 * Get the User object used in this instance
830 * @return User
831 * @since 1.18
833 public function getUser() {
834 return $this->getContext()->getUser();
838 * Get the Skin object used to render this instance
840 * @return Skin
841 * @since 1.18
843 public function getSkin() {
844 return $this->getContext()->getSkin();
848 * Replace the subtile with $str
850 * @param $str String: new value of the subtitle
852 public function setSubtitle( $str ) {
853 $this->mSubtitle = /*$this->parse(*/ $str /*)*/; // @bug 2514
857 * Add $str to the subtitle
859 * @param $str String to add to the subtitle
861 public function appendSubtitle( $str ) {
862 $this->mSubtitle .= /*$this->parse(*/ $str /*)*/; // @bug 2514
866 * Get the subtitle
868 * @return String
870 public function getSubtitle() {
871 return $this->mSubtitle;
875 * Set the page as printable, i.e. it'll be displayed with with all
876 * print styles included
878 public function setPrintable() {
879 $this->mPrintable = true;
883 * Return whether the page is "printable"
885 * @return Boolean
887 public function isPrintable() {
888 return $this->mPrintable;
892 * Disable output completely, i.e. calling output() will have no effect
894 public function disable() {
895 $this->mDoNothing = true;
899 * Return whether the output will be completely disabled
901 * @return Boolean
903 public function isDisabled() {
904 return $this->mDoNothing;
908 * Show an "add new section" link?
910 * @return Boolean
912 public function showNewSectionLink() {
913 return $this->mNewSectionLink;
917 * Forcibly hide the new section link?
919 * @return Boolean
921 public function forceHideNewSectionLink() {
922 return $this->mHideNewSectionLink;
926 * Add or remove feed links in the page header
927 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
928 * for the new version
929 * @see addFeedLink()
931 * @param $show Boolean: true: add default feeds, false: remove all feeds
933 public function setSyndicated( $show = true ) {
934 if ( $show ) {
935 $this->setFeedAppendQuery( false );
936 } else {
937 $this->mFeedLinks = array();
942 * Add default feeds to the page header
943 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
944 * for the new version
945 * @see addFeedLink()
947 * @param $val String: query to append to feed links or false to output
948 * default links
950 public function setFeedAppendQuery( $val ) {
951 global $wgAdvertisedFeedTypes;
953 $this->mFeedLinks = array();
955 foreach ( $wgAdvertisedFeedTypes as $type ) {
956 $query = "feed=$type";
957 if ( is_string( $val ) ) {
958 $query .= '&' . $val;
960 $this->mFeedLinks[$type] = $this->getTitle()->getLocalURL( $query );
965 * Add a feed link to the page header
967 * @param $format String: feed type, should be a key of $wgFeedClasses
968 * @param $href String: URL
970 public function addFeedLink( $format, $href ) {
971 global $wgAdvertisedFeedTypes;
973 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
974 $this->mFeedLinks[$format] = $href;
979 * Should we output feed links for this page?
980 * @return Boolean
982 public function isSyndicated() {
983 return count( $this->mFeedLinks ) > 0;
987 * Return URLs for each supported syndication format for this page.
988 * @return array associating format keys with URLs
990 public function getSyndicationLinks() {
991 return $this->mFeedLinks;
995 * Will currently always return null
997 * @return null
999 public function getFeedAppendQuery() {
1000 return $this->mFeedLinksAppendQuery;
1004 * Set whether the displayed content is related to the source of the
1005 * corresponding article on the wiki
1006 * Setting true will cause the change "article related" toggle to true
1008 * @param $v Boolean
1010 public function setArticleFlag( $v ) {
1011 $this->mIsarticle = $v;
1012 if ( $v ) {
1013 $this->mIsArticleRelated = $v;
1018 * Return whether the content displayed page is related to the source of
1019 * the corresponding article on the wiki
1021 * @return Boolean
1023 public function isArticle() {
1024 return $this->mIsarticle;
1028 * Set whether this page is related an article on the wiki
1029 * Setting false will cause the change of "article flag" toggle to false
1031 * @param $v Boolean
1033 public function setArticleRelated( $v ) {
1034 $this->mIsArticleRelated = $v;
1035 if ( !$v ) {
1036 $this->mIsarticle = false;
1041 * Return whether this page is related an article on the wiki
1043 * @return Boolean
1045 public function isArticleRelated() {
1046 return $this->mIsArticleRelated;
1050 * Add new language links
1052 * @param $newLinkArray Associative array mapping language code to the page
1053 * name
1055 public function addLanguageLinks( $newLinkArray ) {
1056 $this->mLanguageLinks += $newLinkArray;
1060 * Reset the language links and add new language links
1062 * @param $newLinkArray Associative array mapping language code to the page
1063 * name
1065 public function setLanguageLinks( $newLinkArray ) {
1066 $this->mLanguageLinks = $newLinkArray;
1070 * Get the list of language links
1072 * @return Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1074 public function getLanguageLinks() {
1075 return $this->mLanguageLinks;
1079 * Add an array of categories, with names in the keys
1081 * @param $categories Array mapping category name => sort key
1083 public function addCategoryLinks( $categories ) {
1084 global $wgContLang;
1086 if ( !is_array( $categories ) || count( $categories ) == 0 ) {
1087 return;
1090 # Add the links to a LinkBatch
1091 $arr = array( NS_CATEGORY => $categories );
1092 $lb = new LinkBatch;
1093 $lb->setArray( $arr );
1095 # Fetch existence plus the hiddencat property
1096 $dbr = wfGetDB( DB_SLAVE );
1097 $res = $dbr->select( array( 'page', 'page_props' ),
1098 array( 'page_id', 'page_namespace', 'page_title', 'page_len', 'page_is_redirect', 'page_latest', 'pp_value' ),
1099 $lb->constructSet( 'page', $dbr ),
1100 __METHOD__,
1101 array(),
1102 array( 'page_props' => array( 'LEFT JOIN', array( 'pp_propname' => 'hiddencat', 'pp_page = page_id' ) ) )
1105 # Add the results to the link cache
1106 $lb->addResultToCache( LinkCache::singleton(), $res );
1108 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
1109 $categories = array_combine(
1110 array_keys( $categories ),
1111 array_fill( 0, count( $categories ), 'normal' )
1114 # Mark hidden categories
1115 foreach ( $res as $row ) {
1116 if ( isset( $row->pp_value ) ) {
1117 $categories[$row->page_title] = 'hidden';
1121 # Add the remaining categories to the skin
1122 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks ) ) ) {
1123 foreach ( $categories as $category => $type ) {
1124 $origcategory = $category;
1125 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
1126 $wgContLang->findVariantLink( $category, $title, true );
1127 if ( $category != $origcategory ) {
1128 if ( array_key_exists( $category, $categories ) ) {
1129 continue;
1132 $text = $wgContLang->convertHtml( $title->getText() );
1133 $this->mCategories[] = $title->getText();
1134 $this->mCategoryLinks[$type][] = Linker::link( $title, $text );
1140 * Reset the category links (but not the category list) and add $categories
1142 * @param $categories Array mapping category name => sort key
1144 public function setCategoryLinks( $categories ) {
1145 $this->mCategoryLinks = array();
1146 $this->addCategoryLinks( $categories );
1150 * Get the list of category links, in a 2-D array with the following format:
1151 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1152 * hidden categories) and $link a HTML fragment with a link to the category
1153 * page
1155 * @return Array
1157 public function getCategoryLinks() {
1158 return $this->mCategoryLinks;
1162 * Get the list of category names this page belongs to
1164 * @return Array of strings
1166 public function getCategories() {
1167 return $this->mCategories;
1171 * Do not allow scripts which can be modified by wiki users to load on this page;
1172 * only allow scripts bundled with, or generated by, the software.
1174 public function disallowUserJs() {
1175 $this->reduceAllowedModules(
1176 ResourceLoaderModule::TYPE_SCRIPTS,
1177 ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL
1182 * Return whether user JavaScript is allowed for this page
1183 * @deprecated since 1.18 Load modules with ResourceLoader, and origin and
1184 * trustworthiness is identified and enforced automagically.
1185 * @return Boolean
1187 public function isUserJsAllowed() {
1188 return $this->getAllowedModules( ResourceLoaderModule::TYPE_SCRIPTS ) >= ResourceLoaderModule::ORIGIN_USER_INDIVIDUAL;
1192 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1193 * @see ResourceLoaderModule::$origin
1194 * @param $type String ResourceLoaderModule TYPE_ constant
1195 * @return Int ResourceLoaderModule ORIGIN_ class constant
1197 public function getAllowedModules( $type ){
1198 if( $type == ResourceLoaderModule::TYPE_COMBINED ){
1199 return min( array_values( $this->mAllowedModules ) );
1200 } else {
1201 return isset( $this->mAllowedModules[$type] )
1202 ? $this->mAllowedModules[$type]
1203 : ResourceLoaderModule::ORIGIN_ALL;
1208 * Set the highest level of CSS/JS untrustworthiness allowed
1209 * @param $type String ResourceLoaderModule TYPE_ constant
1210 * @param $level Int ResourceLoaderModule class constant
1212 public function setAllowedModules( $type, $level ){
1213 $this->mAllowedModules[$type] = $level;
1217 * As for setAllowedModules(), but don't inadvertantly make the page more accessible
1218 * @param $type String
1219 * @param $level Int ResourceLoaderModule class constant
1221 public function reduceAllowedModules( $type, $level ){
1222 $this->mAllowedModules[$type] = min( $this->getAllowedModules($type), $level );
1226 * Prepend $text to the body HTML
1228 * @param $text String: HTML
1230 public function prependHTML( $text ) {
1231 $this->mBodytext = $text . $this->mBodytext;
1235 * Append $text to the body HTML
1237 * @param $text String: HTML
1239 public function addHTML( $text ) {
1240 $this->mBodytext .= $text;
1244 * Clear the body HTML
1246 public function clearHTML() {
1247 $this->mBodytext = '';
1251 * Get the body HTML
1253 * @return String: HTML
1255 public function getHTML() {
1256 return $this->mBodytext;
1260 * Add $text to the debug output
1262 * @param $text String: debug text
1264 public function debug( $text ) {
1265 $this->mDebugtext .= $text;
1269 * Get/set the ParserOptions object to use for wikitext parsing
1271 * @param $options either the ParserOption to use or null to only get the
1272 * current ParserOption object
1273 * @return ParserOptions object
1275 public function parserOptions( $options = null ) {
1276 if ( !$this->mParserOptions ) {
1277 $this->mParserOptions = new ParserOptions;
1279 return wfSetVar( $this->mParserOptions, $options );
1283 * Set the revision ID which will be seen by the wiki text parser
1284 * for things such as embedded {{REVISIONID}} variable use.
1286 * @param $revid Mixed: an positive integer, or null
1287 * @return Mixed: previous value
1289 public function setRevisionId( $revid ) {
1290 $val = is_null( $revid ) ? null : intval( $revid );
1291 return wfSetVar( $this->mRevisionId, $val );
1295 * Get the displayed revision ID
1297 * @return Integer
1299 public function getRevisionId() {
1300 return $this->mRevisionId;
1304 * Set the displayed file version
1306 * @param $file File|false
1307 * @return Mixed: previous value
1309 public function setFileVersion( $file ) {
1310 if ( $file instanceof File && $file->exists() ) {
1311 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1313 return wfSetVar( $this->mFileVersion, $val );
1317 * Get the displayed file version
1319 * @return Array|null ('time' => MW timestamp, 'sha1' => sha1)
1321 public function getFileVersion() {
1322 return $this->mFileVersion;
1326 * Get the templates used on this page
1328 * @return Array (namespace => dbKey => revId)
1329 * @since 1.18
1331 public function getTemplateIds() {
1332 return $this->mTemplateIds;
1336 * Get the files used on this page
1338 * @return Array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1339 * @since 1.18
1341 public function getImageTimeKeys() {
1342 return $this->mImageTimeKeys;
1346 * Convert wikitext to HTML and add it to the buffer
1347 * Default assumes that the current page title will be used.
1349 * @param $text String
1350 * @param $linestart Boolean: is this the start of a line?
1352 public function addWikiText( $text, $linestart = true ) {
1353 $title = $this->getTitle(); // Work arround E_STRICT
1354 $this->addWikiTextTitle( $text, $title, $linestart );
1358 * Add wikitext with a custom Title object
1360 * @param $text String: wikitext
1361 * @param $title Title object
1362 * @param $linestart Boolean: is this the start of a line?
1364 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1365 $this->addWikiTextTitle( $text, $title, $linestart );
1369 * Add wikitext with a custom Title object and
1371 * @param $text String: wikitext
1372 * @param $title Title object
1373 * @param $linestart Boolean: is this the start of a line?
1375 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1376 $this->addWikiTextTitle( $text, $title, $linestart, true );
1380 * Add wikitext with tidy enabled
1382 * @param $text String: wikitext
1383 * @param $linestart Boolean: is this the start of a line?
1385 public function addWikiTextTidy( $text, $linestart = true ) {
1386 $title = $this->getTitle();
1387 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1391 * Add wikitext with a custom Title object
1393 * @param $text String: wikitext
1394 * @param $title Title object
1395 * @param $linestart Boolean: is this the start of a line?
1396 * @param $tidy Boolean: whether to use tidy
1398 public function addWikiTextTitle( $text, &$title, $linestart, $tidy = false ) {
1399 global $wgParser;
1401 wfProfileIn( __METHOD__ );
1403 wfIncrStats( 'pcache_not_possible' );
1405 $popts = $this->parserOptions();
1406 $oldTidy = $popts->setTidy( $tidy );
1408 $parserOutput = $wgParser->parse(
1409 $text, $title, $popts,
1410 $linestart, true, $this->mRevisionId
1413 $popts->setTidy( $oldTidy );
1415 $this->addParserOutput( $parserOutput );
1417 wfProfileOut( __METHOD__ );
1421 * Add a ParserOutput object, but without Html
1423 * @param $parserOutput ParserOutput object
1425 public function addParserOutputNoText( &$parserOutput ) {
1426 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
1427 $this->addCategoryLinks( $parserOutput->getCategories() );
1428 $this->mNewSectionLink = $parserOutput->getNewSection();
1429 $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
1431 $this->mParseWarnings = $parserOutput->getWarnings();
1432 if ( !$parserOutput->isCacheable() ) {
1433 $this->enableClientCache( false );
1435 $this->mNoGallery = $parserOutput->getNoGallery();
1436 $this->mHeadItems = array_merge( $this->mHeadItems, $parserOutput->getHeadItems() );
1437 $this->addModules( $parserOutput->getModules() );
1439 // Template versioning...
1440 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1441 if ( isset( $this->mTemplateIds[$ns] ) ) {
1442 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
1443 } else {
1444 $this->mTemplateIds[$ns] = $dbks;
1447 // File versioning...
1448 foreach ( (array)$parserOutput->getImageTimeKeys() as $dbk => $data ) {
1449 $this->mImageTimeKeys[$dbk] = $data;
1452 // Hooks registered in the object
1453 global $wgParserOutputHooks;
1454 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1455 list( $hookName, $data ) = $hookInfo;
1456 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1457 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1461 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1465 * Add a ParserOutput object
1467 * @param $parserOutput ParserOutput
1469 function addParserOutput( &$parserOutput ) {
1470 $this->addParserOutputNoText( $parserOutput );
1471 $text = $parserOutput->getText();
1472 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1473 $this->addHTML( $text );
1478 * Add the output of a QuickTemplate to the output buffer
1480 * @param $template QuickTemplate
1482 public function addTemplate( &$template ) {
1483 ob_start();
1484 $template->execute();
1485 $this->addHTML( ob_get_contents() );
1486 ob_end_clean();
1490 * Parse wikitext and return the HTML.
1492 * @param $text String
1493 * @param $linestart Boolean: is this the start of a line?
1494 * @param $interface Boolean: use interface language ($wgLang instead of
1495 * $wgContLang) while parsing language sensitive magic
1496 * words like GRAMMAR and PLURAL
1497 * @param $language Language object: target language object, will override
1498 * $interface
1499 * @return String: HTML
1501 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1502 // Check one for one common cause for parser state resetting
1503 $callers = wfGetAllCallers( 10 );
1504 if ( strpos( $callers, 'Parser::extensionSubstitution' ) !== false ) {
1505 throw new MWException( "wfMsg* function with parsing cannot be used " .
1506 "inside a tag hook. Should use parser->recursiveTagParse() instead" );
1509 global $wgParser;
1511 if( is_null( $this->getTitle() ) ) {
1512 throw new MWException( 'Empty $mTitle in ' . __METHOD__ );
1515 $popts = $this->parserOptions();
1516 if ( $interface ) {
1517 $popts->setInterfaceMessage( true );
1519 if ( $language !== null ) {
1520 $oldLang = $popts->setTargetLanguage( $language );
1523 $parserOutput = $wgParser->parse(
1524 $text, $this->getTitle(), $popts,
1525 $linestart, true, $this->mRevisionId
1528 if ( $interface ) {
1529 $popts->setInterfaceMessage( false );
1531 if ( $language !== null ) {
1532 $popts->setTargetLanguage( $oldLang );
1535 return $parserOutput->getText();
1539 * Parse wikitext, strip paragraphs, and return the HTML.
1541 * @param $text String
1542 * @param $linestart Boolean: is this the start of a line?
1543 * @param $interface Boolean: use interface language ($wgLang instead of
1544 * $wgContLang) while parsing language sensitive magic
1545 * words like GRAMMAR and PLURAL
1546 * @return String: HTML
1548 public function parseInline( $text, $linestart = true, $interface = false ) {
1549 $parsed = $this->parse( $text, $linestart, $interface );
1551 $m = array();
1552 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1553 $parsed = $m[1];
1556 return $parsed;
1560 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1562 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1564 public function setSquidMaxage( $maxage ) {
1565 $this->mSquidMaxage = $maxage;
1569 * Use enableClientCache(false) to force it to send nocache headers
1571 * @param $state bool
1573 * @return bool
1575 public function enableClientCache( $state ) {
1576 return wfSetVar( $this->mEnableClientCache, $state );
1580 * Get the list of cookies that will influence on the cache
1582 * @return Array
1584 function getCacheVaryCookies() {
1585 global $wgCookiePrefix, $wgCacheVaryCookies;
1586 static $cookies;
1587 if ( $cookies === null ) {
1588 $cookies = array_merge(
1589 array(
1590 "{$wgCookiePrefix}Token",
1591 "{$wgCookiePrefix}LoggedOut",
1592 session_name()
1594 $wgCacheVaryCookies
1596 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1598 return $cookies;
1602 * Return whether this page is not cacheable because "useskin" or "uselang"
1603 * URL parameters were passed.
1605 * @return Boolean
1607 function uncacheableBecauseRequestVars() {
1608 $request = $this->getRequest();
1609 return $request->getText( 'useskin', false ) === false
1610 && $request->getText( 'uselang', false ) === false;
1614 * Check if the request has a cache-varying cookie header
1615 * If it does, it's very important that we don't allow public caching
1617 * @return Boolean
1619 function haveCacheVaryCookies() {
1620 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1621 if ( $cookieHeader === false ) {
1622 return false;
1624 $cvCookies = $this->getCacheVaryCookies();
1625 foreach ( $cvCookies as $cookieName ) {
1626 # Check for a simple string match, like the way squid does it
1627 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1628 wfDebug( __METHOD__ . ": found $cookieName\n" );
1629 return true;
1632 wfDebug( __METHOD__ . ": no cache-varying cookies found\n" );
1633 return false;
1637 * Add an HTTP header that will influence on the cache
1639 * @param $header String: header name
1640 * @param $option Array|null
1641 * @todo FIXME: Document the $option parameter; it appears to be for
1642 * X-Vary-Options but what format is acceptable?
1644 public function addVaryHeader( $header, $option = null ) {
1645 if ( !array_key_exists( $header, $this->mVaryHeader ) ) {
1646 $this->mVaryHeader[$header] = (array)$option;
1647 } elseif( is_array( $option ) ) {
1648 if( is_array( $this->mVaryHeader[$header] ) ) {
1649 $this->mVaryHeader[$header] = array_merge( $this->mVaryHeader[$header], $option );
1650 } else {
1651 $this->mVaryHeader[$header] = $option;
1654 $this->mVaryHeader[$header] = array_unique( $this->mVaryHeader[$header] );
1658 * Get a complete X-Vary-Options header
1660 * @return String
1662 public function getXVO() {
1663 $cvCookies = $this->getCacheVaryCookies();
1665 $cookiesOption = array();
1666 foreach ( $cvCookies as $cookieName ) {
1667 $cookiesOption[] = 'string-contains=' . $cookieName;
1669 $this->addVaryHeader( 'Cookie', $cookiesOption );
1671 $headers = array();
1672 foreach( $this->mVaryHeader as $header => $option ) {
1673 $newheader = $header;
1674 if( is_array( $option ) ) {
1675 $newheader .= ';' . implode( ';', $option );
1677 $headers[] = $newheader;
1679 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1681 return $xvo;
1685 * bug 21672: Add Accept-Language to Vary and XVO headers
1686 * if there's no 'variant' parameter existed in GET.
1688 * For example:
1689 * /w/index.php?title=Main_page should always be served; but
1690 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1692 function addAcceptLanguage() {
1693 global $wgContLang;
1694 if( !$this->getRequest()->getCheck( 'variant' ) && $wgContLang->hasVariants() ) {
1695 $variants = $wgContLang->getVariants();
1696 $aloption = array();
1697 foreach ( $variants as $variant ) {
1698 if( $variant === $wgContLang->getCode() ) {
1699 continue;
1700 } else {
1701 $aloption[] = 'string-contains=' . $variant;
1703 // IE and some other browsers use another form of language code
1704 // in their Accept-Language header, like "zh-CN" or "zh-TW".
1705 // We should handle these too.
1706 $ievariant = explode( '-', $variant );
1707 if ( count( $ievariant ) == 2 ) {
1708 $ievariant[1] = strtoupper( $ievariant[1] );
1709 $ievariant = implode( '-', $ievariant );
1710 $aloption[] = 'string-contains=' . $ievariant;
1714 $this->addVaryHeader( 'Accept-Language', $aloption );
1719 * Set a flag which will cause an X-Frame-Options header appropriate for
1720 * edit pages to be sent. The header value is controlled by
1721 * $wgEditPageFrameOptions.
1723 * This is the default for special pages. If you display a CSRF-protected
1724 * form on an ordinary view page, then you need to call this function.
1726 * @param $enable bool
1728 public function preventClickjacking( $enable = true ) {
1729 $this->mPreventClickjacking = $enable;
1733 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1734 * This can be called from pages which do not contain any CSRF-protected
1735 * HTML form.
1737 public function allowClickjacking() {
1738 $this->mPreventClickjacking = false;
1742 * Get the X-Frame-Options header value (without the name part), or false
1743 * if there isn't one. This is used by Skin to determine whether to enable
1744 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1746 * @return string
1748 public function getFrameOptions() {
1749 global $wgBreakFrames, $wgEditPageFrameOptions;
1750 if ( $wgBreakFrames ) {
1751 return 'DENY';
1752 } elseif ( $this->mPreventClickjacking && $wgEditPageFrameOptions ) {
1753 return $wgEditPageFrameOptions;
1758 * Send cache control HTTP headers
1760 public function sendCacheControl() {
1761 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgUseXVO;
1763 $response = $this->getRequest()->response();
1764 if ( $wgUseETag && $this->mETag ) {
1765 $response->header( "ETag: $this->mETag" );
1768 $this->addAcceptLanguage();
1770 # don't serve compressed data to clients who can't handle it
1771 # maintain different caches for logged-in users and non-logged in ones
1772 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader ) ) );
1774 if ( $wgUseXVO ) {
1775 # Add an X-Vary-Options header for Squid with Wikimedia patches
1776 $response->header( $this->getXVO() );
1779 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache ) {
1781 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1782 $this->mSquidMaxage != 0 && !$this->haveCacheVaryCookies()
1785 if ( $wgUseESI ) {
1786 # We'll purge the proxy cache explicitly, but require end user agents
1787 # to revalidate against the proxy on each visit.
1788 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1789 wfDebug( __METHOD__ . ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1790 # start with a shorter timeout for initial testing
1791 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1792 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage.', content="ESI/1.0"');
1793 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1794 } else {
1795 # We'll purge the proxy cache for anons explicitly, but require end user agents
1796 # to revalidate against the proxy on each visit.
1797 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1798 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1799 wfDebug( __METHOD__ . ": local proxy caching; {$this->mLastModified} **\n", false );
1800 # start with a shorter timeout for initial testing
1801 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1802 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage.', must-revalidate, max-age=0' );
1804 } else {
1805 # We do want clients to cache if they can, but they *must* check for updates
1806 # on revisiting the page.
1807 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **\n", false );
1808 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1809 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1811 if($this->mLastModified) {
1812 $response->header( "Last-Modified: {$this->mLastModified}" );
1814 } else {
1815 wfDebug( __METHOD__ . ": no caching **\n", false );
1817 # In general, the absence of a last modified header should be enough to prevent
1818 # the client from using its cache. We send a few other things just to make sure.
1819 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1820 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1821 $response->header( 'Pragma: no-cache' );
1826 * Get the message associed with the HTTP response code $code
1828 * @param $code Integer: status code
1829 * @return String or null: message or null if $code is not in the list of
1830 * messages
1832 * @deprecated since 1.19 Use HttpStatus::getMessage() instead.
1834 public static function getStatusMessage( $code ) {
1835 wfDeprecated( __METHOD__ );
1836 return HttpStatus::getMessage( $code );
1840 * Finally, all the text has been munged and accumulated into
1841 * the object, let's actually output it:
1843 public function output() {
1844 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType;
1846 if( $this->mDoNothing ) {
1847 return;
1850 wfProfileIn( __METHOD__ );
1852 $response = $this->getRequest()->response();
1854 if ( $this->mRedirect != '' ) {
1855 # Standards require redirect URLs to be absolute
1856 $this->mRedirect = wfExpandUrl( $this->mRedirect );
1857 if( $this->mRedirectCode == '301' || $this->mRedirectCode == '303' ) {
1858 if( !$wgDebugRedirects ) {
1859 $message = HttpStatus::getMessage( $this->mRedirectCode );
1860 $response->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
1862 $this->mLastModified = wfTimestamp( TS_RFC2822 );
1864 $this->sendCacheControl();
1866 $response->header( "Content-Type: text/html; charset=utf-8" );
1867 if( $wgDebugRedirects ) {
1868 $url = htmlspecialchars( $this->mRedirect );
1869 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1870 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1871 print "</body>\n</html>\n";
1872 } else {
1873 $response->header( 'Location: ' . $this->mRedirect );
1875 wfProfileOut( __METHOD__ );
1876 return;
1877 } elseif ( $this->mStatusCode ) {
1878 $message = HttpStatus::getMessage( $this->mStatusCode );
1879 if ( $message ) {
1880 $response->header( 'HTTP/1.1 ' . $this->mStatusCode . ' ' . $message );
1884 # Buffer output; final headers may depend on later processing
1885 ob_start();
1887 $response->header( "Content-type: $wgMimeType; charset=UTF-8" );
1888 $response->header( 'Content-language: ' . $wgLanguageCode );
1890 // Prevent framing, if requested
1891 $frameOptions = $this->getFrameOptions();
1892 if ( $frameOptions ) {
1893 $response->header( "X-Frame-Options: $frameOptions" );
1896 if ( $this->mArticleBodyOnly ) {
1897 $this->out( $this->mBodytext );
1898 } else {
1899 $this->addDefaultModules();
1901 $sk = $this->getSkin();
1903 // Hook that allows last minute changes to the output page, e.g.
1904 // adding of CSS or Javascript by extensions.
1905 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1907 wfProfileIn( 'Output-skin' );
1908 $sk->outputPage( $this );
1909 wfProfileOut( 'Output-skin' );
1912 $this->sendCacheControl();
1913 ob_end_flush();
1914 wfProfileOut( __METHOD__ );
1918 * Actually output something with print().
1920 * @param $ins String: the string to output
1922 public function out( $ins ) {
1923 print $ins;
1927 * Produce a "user is blocked" page.
1928 * @deprecated since 1.18
1930 function blockedPage() {
1931 throw new UserBlockedError( $this->getUser()->mBlock );
1935 * Output a standard error page
1937 * @param $title String: message key for page title
1938 * @param $msg String: message key for page text
1939 * @param $params Array: message parameters
1941 public function showErrorPage( $title, $msg, $params = array() ) {
1942 if ( $this->getTitle() ) {
1943 $this->mDebugtext .= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1945 $this->setPageTitle( wfMsg( $title ) );
1946 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1947 $this->setRobotPolicy( 'noindex,nofollow' );
1948 $this->setArticleRelated( false );
1949 $this->enableClientCache( false );
1950 $this->mRedirect = '';
1951 $this->mBodytext = '';
1953 $this->addWikiMsgArray( $msg, $params );
1955 $this->returnToMain();
1959 * Output a standard permission error page
1961 * @param $errors Array: error message keys
1962 * @param $action String: action that was denied or null if unknown
1964 public function showPermissionsErrorPage( $errors, $action = null ) {
1965 $this->mDebugtext .= 'Original title: ' .
1966 $this->getTitle()->getPrefixedText() . "\n";
1967 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1968 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1969 $this->setRobotPolicy( 'noindex,nofollow' );
1970 $this->setArticleRelated( false );
1971 $this->enableClientCache( false );
1972 $this->mRedirect = '';
1973 $this->mBodytext = '';
1974 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1978 * Display an error page indicating that a given version of MediaWiki is
1979 * required to use it
1981 * @param $version Mixed: the version of MediaWiki needed to use the page
1983 public function versionRequired( $version ) {
1984 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1985 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1986 $this->setRobotPolicy( 'noindex,nofollow' );
1987 $this->setArticleRelated( false );
1988 $this->mBodytext = '';
1990 $this->addWikiMsg( 'versionrequiredtext', $version );
1991 $this->returnToMain();
1995 * Display an error page noting that a given permission bit is required.
1996 * @deprecated since 1.18, just throw the exception directly
1997 * @param $permission String: key required
1999 public function permissionRequired( $permission ) {
2000 throw new PermissionsError( $permission );
2004 * Produce the stock "please login to use the wiki" page
2006 public function loginToUse() {
2007 if( $this->getUser()->isLoggedIn() ) {
2008 throw new PermissionsError( 'read' );
2011 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
2012 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
2013 $this->setRobotPolicy( 'noindex,nofollow' );
2014 $this->setArticleRelated( false );
2016 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
2017 $loginLink = Linker::link(
2018 $loginTitle,
2019 wfMsgHtml( 'loginreqlink' ),
2020 array(),
2021 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
2022 array( 'known', 'noclasses' )
2024 $this->addWikiMsgArray( 'loginreqpagetext', array( $loginLink ), array( 'replaceafter' ) );
2025 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . '-->' );
2027 # Don't return to the main page if the user can't read it
2028 # otherwise we'll end up in a pointless loop
2029 $mainPage = Title::newMainPage();
2030 if( $mainPage->userCanRead() ) {
2031 $this->returnToMain( null, $mainPage );
2036 * Format a list of error messages
2038 * @param $errors Array of arrays returned by Title::getUserPermissionsErrors
2039 * @param $action String: action that was denied or null if unknown
2040 * @return String: the wikitext error-messages, formatted into a list.
2042 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2043 if ( $action == null ) {
2044 $text = wfMsgNoTrans( 'permissionserrorstext', count( $errors ) ) . "\n\n";
2045 } else {
2046 $action_desc = wfMsgNoTrans( "action-$action" );
2047 $text = wfMsgNoTrans(
2048 'permissionserrorstext-withaction',
2049 count( $errors ),
2050 $action_desc
2051 ) . "\n\n";
2054 if ( count( $errors ) > 1 ) {
2055 $text .= '<ul class="permissions-errors">' . "\n";
2057 foreach( $errors as $error ) {
2058 $text .= '<li>';
2059 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
2060 $text .= "</li>\n";
2062 $text .= '</ul>';
2063 } else {
2064 $text .= "<div class=\"permissions-errors\">\n" .
2065 call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) .
2066 "\n</div>";
2069 return $text;
2073 * Display a page stating that the Wiki is in read-only mode,
2074 * and optionally show the source of the page that the user
2075 * was trying to edit. Should only be called (for this
2076 * purpose) after wfReadOnly() has returned true.
2078 * For historical reasons, this function is _also_ used to
2079 * show the error message when a user tries to edit a page
2080 * they are not allowed to edit. (Unless it's because they're
2081 * blocked, then we show blockedPage() instead.) In this
2082 * case, the second parameter should be set to true and a list
2083 * of reasons supplied as the third parameter.
2085 * @todo Needs to be split into multiple functions.
2087 * @param $source String: source code to show (or null).
2088 * @param $protected Boolean: is this a permissions error?
2089 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
2090 * @param $action String: action that was denied or null if unknown
2092 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
2093 $this->setRobotPolicy( 'noindex,nofollow' );
2094 $this->setArticleRelated( false );
2096 // If no reason is given, just supply a default "I can't let you do
2097 // that, Dave" message. Should only occur if called by legacy code.
2098 if ( $protected && empty( $reasons ) ) {
2099 $reasons[] = array( 'badaccess-group0' );
2102 if ( !empty( $reasons ) ) {
2103 // Permissions error
2104 if( $source ) {
2105 $this->setPageTitle( wfMsg( 'viewsource' ) );
2106 $this->setSubtitle(
2107 wfMsg( 'viewsourcefor', Linker::linkKnown( $this->getTitle() ) )
2109 } else {
2110 $this->setPageTitle( wfMsg( 'badaccess' ) );
2112 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2113 } else {
2114 // Wiki is read only
2115 throw new ReadOnlyError;
2118 // Show source, if supplied
2119 if( is_string( $source ) ) {
2120 $this->addWikiMsg( 'viewsourcetext' );
2122 $params = array(
2123 'id' => 'wpTextbox1',
2124 'name' => 'wpTextbox1',
2125 'cols' => $this->getUser()->getOption( 'cols' ),
2126 'rows' => $this->getUser()->getOption( 'rows' ),
2127 'readonly' => 'readonly'
2129 $this->addHTML( Html::element( 'textarea', $params, $source ) );
2131 // Show templates used by this article
2132 $article = new Article( $this->getTitle() );
2133 $templates = Linker::formatTemplates( $article->getUsedTemplates() );
2134 $this->addHTML( "<div class='templatesUsed'>
2135 $templates
2136 </div>
2137 " );
2140 # If the title doesn't exist, it's fairly pointless to print a return
2141 # link to it. After all, you just tried editing it and couldn't, so
2142 # what's there to do there?
2143 if( $this->getTitle()->exists() ) {
2144 $this->returnToMain( null, $this->getTitle() );
2149 * Turn off regular page output and return an error reponse
2150 * for when rate limiting has triggered.
2152 public function rateLimited() {
2153 throw new ThrottledError;
2157 * Show a warning about slave lag
2159 * If the lag is higher than $wgSlaveLagCritical seconds,
2160 * then the warning is a bit more obvious. If the lag is
2161 * lower than $wgSlaveLagWarning, then no warning is shown.
2163 * @param $lag Integer: slave lag
2165 public function showLagWarning( $lag ) {
2166 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2167 if( $lag >= $wgSlaveLagWarning ) {
2168 $message = $lag < $wgSlaveLagCritical
2169 ? 'lag-warn-normal'
2170 : 'lag-warn-high';
2171 $wrap = Html::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2172 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getContext()->getLang()->formatNum( $lag ) ) );
2176 public function showFatalError( $message ) {
2177 $this->setPageTitle( wfMsg( 'internalerror' ) );
2178 $this->setRobotPolicy( 'noindex,nofollow' );
2179 $this->setArticleRelated( false );
2180 $this->enableClientCache( false );
2181 $this->mRedirect = '';
2182 $this->mBodytext = $message;
2185 public function showUnexpectedValueError( $name, $val ) {
2186 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
2189 public function showFileCopyError( $old, $new ) {
2190 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
2193 public function showFileRenameError( $old, $new ) {
2194 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
2197 public function showFileDeleteError( $name ) {
2198 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
2201 public function showFileNotFoundError( $name ) {
2202 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
2206 * Add a "return to" link pointing to a specified title
2208 * @param $title Title to link
2209 * @param $query String query string
2210 * @param $text String text of the link (input is not escaped)
2212 public function addReturnTo( $title, $query = array(), $text = null ) {
2213 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL() ) );
2214 $link = wfMsgHtml(
2215 'returnto',
2216 Linker::link( $title, $text, array(), $query )
2218 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2222 * Add a "return to" link pointing to a specified title,
2223 * or the title indicated in the request, or else the main page
2225 * @param $unused No longer used
2226 * @param $returnto Title or String to return to
2227 * @param $returntoquery String: query string for the return to link
2229 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2230 if ( $returnto == null ) {
2231 $returnto = $this->getRequest()->getText( 'returnto' );
2234 if ( $returntoquery == null ) {
2235 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2238 if ( $returnto === '' ) {
2239 $returnto = Title::newMainPage();
2242 if ( is_object( $returnto ) ) {
2243 $titleObj = $returnto;
2244 } else {
2245 $titleObj = Title::newFromText( $returnto );
2247 if ( !is_object( $titleObj ) ) {
2248 $titleObj = Title::newMainPage();
2251 $this->addReturnTo( $titleObj, $returntoquery );
2255 * @param $sk Skin The given Skin
2256 * @param $includeStyle Boolean: unused
2257 * @return String: The doctype, opening <html>, and head element.
2259 public function headElement( Skin $sk, $includeStyle = true ) {
2260 global $wgUseTrackbacks, $wgLang;
2262 if ( $sk->commonPrintStylesheet() ) {
2263 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2265 $sk->setupUserCss( $this );
2267 $ret = Html::htmlHeader( array( 'lang' => $wgLang->getCode(), 'dir' => $wgLang->getDir() ) );
2269 if ( $this->getHTMLTitle() == '' ) {
2270 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ) );
2273 $openHead = Html::openElement( 'head' );
2274 if ( $openHead ) {
2275 # Don't bother with the newline if $head == ''
2276 $ret .= "$openHead\n";
2279 $ret .= Html::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2281 $ret .= implode( "\n", array(
2282 $this->getHeadLinks( $sk, true ),
2283 $this->buildCssLinks( $sk ),
2284 $this->getHeadScripts( $sk ),
2285 $this->getHeadItems()
2286 ) );
2288 if ( $wgUseTrackbacks && $this->isArticleRelated() ) {
2289 $ret .= $this->getTitle()->trackbackRDF();
2292 $closeHead = Html::closeElement( 'head' );
2293 if ( $closeHead ) {
2294 $ret .= "$closeHead\n";
2297 $bodyAttrs = array();
2299 # Crazy edit-on-double-click stuff
2300 $action = $this->getRequest()->getVal( 'action', 'view' );
2302 if (
2303 $this->getTitle()->getNamespace() != NS_SPECIAL &&
2304 in_array( $action, array( 'view', 'purge' ) ) &&
2305 $this->getUser()->getOption( 'editondblclick' )
2308 $editUrl = $this->getTitle()->getLocalUrl( $sk->editUrlOptions() );
2309 $bodyAttrs['ondblclick'] = "document.location = '" .
2310 Xml::escapeJsString( $editUrl ) . "'";
2313 # Classes for LTR/RTL directionality support
2314 global $wgLang, $wgContLang;
2315 $userdir = $wgLang->getDir();
2316 $sitedir = $wgContLang->getDir();
2317 $bodyAttrs['class'] = "mediawiki $userdir sitedir-$sitedir";
2319 if ( $this->getContext()->getLang()->capitalizeAllNouns() ) {
2320 # A <body> class is probably not the best way to do this . . .
2321 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2323 $bodyAttrs['class'] .= ' ' . $sk->getPageClasses( $this->getTitle() );
2324 $bodyAttrs['class'] .= ' skin-' . Sanitizer::escapeClass( $sk->getSkinName() );
2326 $sk->addToBodyAttributes( $this, $bodyAttrs ); // Allow skins to add body attributes they need
2327 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2329 $ret .= Html::openElement( 'body', $bodyAttrs ) . "\n";
2331 return $ret;
2335 * Add the default ResourceLoader modules to this object
2337 private function addDefaultModules() {
2338 global $wgIncludeLegacyJavaScript,
2339 $wgUseAjax, $wgAjaxWatch, $wgEnableMWSuggest;
2341 // Add base resources
2342 $this->addModules( array(
2343 'mediawiki.user',
2344 'mediawiki.util',
2345 'mediawiki.page.startup',
2346 'mediawiki.page.ready',
2347 ) );
2348 if ( $wgIncludeLegacyJavaScript ){
2349 $this->addModules( 'mediawiki.legacy.wikibits' );
2352 // Add various resources if required
2353 if ( $wgUseAjax ) {
2354 $this->addModules( 'mediawiki.legacy.ajax' );
2356 wfRunHooks( 'AjaxAddScript', array( &$this ) );
2358 if( $wgAjaxWatch && $this->getUser()->isLoggedIn() ) {
2359 $this->addModules( 'mediawiki.action.watch.ajax' );
2362 if ( $wgEnableMWSuggest && !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2363 $this->addModules( 'mediawiki.legacy.mwsuggest' );
2367 if( $this->getUser()->getBoolOption( 'editsectiononrightclick' ) ) {
2368 $this->addModules( 'mediawiki.action.view.rightClickEdit' );
2373 * Get a ResourceLoader object associated with this OutputPage
2375 * @return ResourceLoader
2377 public function getResourceLoader() {
2378 if ( is_null( $this->mResourceLoader ) ) {
2379 $this->mResourceLoader = new ResourceLoader();
2381 return $this->mResourceLoader;
2385 * TODO: Document
2386 * @param $skin Skin
2387 * @param $modules Array/string with the module name
2388 * @param $only String ResourceLoaderModule TYPE_ class constant
2389 * @param $useESI boolean
2390 * @return string html <script> and <style> tags
2392 protected function makeResourceLoaderLink( Skin $skin, $modules, $only, $useESI = false ) {
2393 global $wgLoadScript, $wgResourceLoaderUseESI,
2394 $wgResourceLoaderInlinePrivateModules;
2395 // Lazy-load ResourceLoader
2396 // TODO: Should this be a static function of ResourceLoader instead?
2397 $baseQuery = array(
2398 'lang' => $this->getContext()->getLang()->getCode(),
2399 'debug' => ResourceLoader::inDebugMode() ? 'true' : 'false',
2400 'skin' => $skin->getSkinName(),
2401 'only' => $only,
2403 // Propagate printable and handheld parameters if present
2404 if ( $this->isPrintable() ) {
2405 $baseQuery['printable'] = 1;
2407 if ( $this->getRequest()->getBool( 'handheld' ) ) {
2408 $baseQuery['handheld'] = 1;
2411 if ( !count( $modules ) ) {
2412 return '';
2415 if ( count( $modules ) > 1 ) {
2416 // Remove duplicate module requests
2417 $modules = array_unique( (array) $modules );
2418 // Sort module names so requests are more uniform
2419 sort( $modules );
2421 if ( ResourceLoader::inDebugMode() ) {
2422 // Recursively call us for every item
2423 $links = '';
2424 foreach ( $modules as $name ) {
2425 $links .= $this->makeResourceLoaderLink( $skin, $name, $only, $useESI );
2427 return $links;
2431 // Create keyed-by-group list of module objects from modules list
2432 $groups = array();
2433 $resourceLoader = $this->getResourceLoader();
2434 foreach ( (array) $modules as $name ) {
2435 $module = $resourceLoader->getModule( $name );
2436 # Check that we're allowed to include this module on this page
2437 if ( ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_SCRIPTS )
2438 && $only == ResourceLoaderModule::TYPE_SCRIPTS )
2439 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_STYLES )
2440 && $only == ResourceLoaderModule::TYPE_STYLES )
2443 continue;
2446 $group = $module->getGroup();
2447 if ( !isset( $groups[$group] ) ) {
2448 $groups[$group] = array();
2450 $groups[$group][$name] = $module;
2453 $links = '';
2454 foreach ( $groups as $group => $modules ) {
2455 $query = $baseQuery;
2456 // Special handling for user-specific groups
2457 if ( ( $group === 'user' || $group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2458 $query['user'] = $this->getUser()->getName();
2461 // Create a fake request based on the one we are about to make so modules return
2462 // correct timestamp and emptiness data
2463 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2464 // Drop modules that know they're empty
2465 foreach ( $modules as $key => $module ) {
2466 if ( $module->isKnownEmpty( $context ) ) {
2467 unset( $modules[$key] );
2470 // If there are no modules left, skip this group
2471 if ( $modules === array() ) {
2472 continue;
2475 $query['modules'] = ResourceLoader::makePackedModulesString( array_keys( $modules ) );
2477 // Support inlining of private modules if configured as such
2478 if ( $group === 'private' && $wgResourceLoaderInlinePrivateModules ) {
2479 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
2480 $links .= Html::inlineStyle(
2481 $resourceLoader->makeModuleResponse( $context, $modules )
2483 } else {
2484 $links .= Html::inlineScript(
2485 ResourceLoader::makeLoaderConditionalScript(
2486 $resourceLoader->makeModuleResponse( $context, $modules )
2490 continue;
2492 // Special handling for the user group; because users might change their stuff
2493 // on-wiki like user pages, or user preferences; we need to find the highest
2494 // timestamp of these user-changable modules so we can ensure cache misses on change
2495 // This should NOT be done for the site group (bug 27564) because anons get that too
2496 // and we shouldn't be putting timestamps in Squid-cached HTML
2497 if ( $group === 'user' ) {
2498 // Get the maximum timestamp
2499 $timestamp = 1;
2500 foreach ( $modules as $module ) {
2501 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2503 // Add a version parameter so cache will break when things change
2504 $query['version'] = wfTimestamp( TS_ISO_8601_BASIC, $timestamp );
2506 // Make queries uniform in order
2507 ksort( $query );
2509 $url = wfAppendQuery( $wgLoadScript, $query );
2510 // Prevent the IE6 extension check from being triggered (bug 28840)
2511 // by appending a character that's invalid in Windows extensions ('*')
2512 $url .= '&*';
2513 if ( $useESI && $wgResourceLoaderUseESI ) {
2514 $esi = Xml::element( 'esi:include', array( 'src' => $url ) );
2515 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
2516 $link = Html::inlineStyle( $esi );
2517 } else {
2518 $link = Html::inlineScript( $esi );
2520 } else {
2521 // Automatically select style/script elements
2522 if ( $only === ResourceLoaderModule::TYPE_STYLES ) {
2523 $link = Html::linkedStyle( $url );
2524 } else {
2525 $link = Html::linkedScript( $url );
2529 if( $group == 'noscript' ){
2530 $links .= Html::rawElement( 'noscript', array(), $link ) . "\n";
2531 } else {
2532 $links .= $link . "\n";
2535 return $links;
2539 * JS stuff to put in the <head>. This is the startup module, config
2540 * vars and modules marked with position 'top'
2542 * @param $sk Skin object to use
2543 * @return String: HTML fragment
2545 function getHeadScripts( Skin $sk ) {
2546 // Startup - this will immediately load jquery and mediawiki modules
2547 $scripts = $this->makeResourceLoaderLink( $sk, 'startup', ResourceLoaderModule::TYPE_SCRIPTS, true );
2549 // Load config before anything else
2550 $scripts .= Html::inlineScript(
2551 ResourceLoader::makeLoaderConditionalScript(
2552 ResourceLoader::makeConfigSetScript( $this->getJSVars() )
2556 // Script and Messages "only" requests marked for top inclusion
2557 // Messages should go first
2558 $scripts .= $this->makeResourceLoaderLink( $sk, $this->getModuleMessages( true, 'top' ), ResourceLoaderModule::TYPE_MESSAGES );
2559 $scripts .= $this->makeResourceLoaderLink( $sk, $this->getModuleScripts( true, 'top' ), ResourceLoaderModule::TYPE_SCRIPTS );
2561 // Modules requests - let the client calculate dependencies and batch requests as it likes
2562 // Only load modules that have marked themselves for loading at the top
2563 $modules = $this->getModules( true, 'top' );
2564 if ( $modules ) {
2565 $scripts .= Html::inlineScript(
2566 ResourceLoader::makeLoaderConditionalScript(
2567 Xml::encodeJsCall( 'mw.loader.load', array( $modules ) )
2572 return $scripts;
2576 * JS stuff to put at the bottom of the <body>: modules marked with position 'bottom',
2577 * legacy scripts ($this->mScripts), user preferences, site JS and user JS
2579 * @param $sk Skin
2581 * @return string
2583 function getBottomScripts( Skin $sk ) {
2584 global $wgUseSiteJs, $wgAllowUserJs;
2586 // Script and Messages "only" requests marked for bottom inclusion
2587 // Messages should go first
2588 $scripts = $this->makeResourceLoaderLink( $sk, $this->getModuleMessages( true, 'bottom' ), ResourceLoaderModule::TYPE_MESSAGES );
2589 $scripts .= $this->makeResourceLoaderLink( $sk, $this->getModuleScripts( true, 'bottom' ), ResourceLoaderModule::TYPE_SCRIPTS );
2591 // Modules requests - let the client calculate dependencies and batch requests as it likes
2592 // Only load modules that have marked themselves for loading at the bottom
2593 $modules = $this->getModules( true, 'bottom' );
2594 if ( $modules ) {
2595 $scripts .= Html::inlineScript(
2596 ResourceLoader::makeLoaderConditionalScript(
2597 Xml::encodeJsCall( 'mw.loader.load', array( $modules ) )
2602 // Legacy Scripts
2603 $scripts .= "\n" . $this->mScripts;
2605 $userScripts = array( 'user.options', 'user.tokens' );
2607 // Add site JS if enabled
2608 if ( $wgUseSiteJs ) {
2609 $scripts .= $this->makeResourceLoaderLink( $sk, 'site', ResourceLoaderModule::TYPE_SCRIPTS );
2610 if( $this->getUser()->isLoggedIn() ){
2611 $userScripts[] = 'user.groups';
2615 // Add user JS if enabled
2616 if ( $wgAllowUserJs && $this->getUser()->isLoggedIn() ) {
2617 $action = $this->getRequest()->getVal( 'action', 'view' );
2618 if( $this->getTitle() && $this->getTitle()->isJsSubpage() && $sk->userCanPreview( $action ) ) {
2619 # XXX: additional security check/prompt?
2620 $scripts .= Html::inlineScript( "\n" . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2621 } else {
2622 # @todo FIXME: This means that User:Me/Common.js doesn't load when previewing
2623 # User:Me/Vector.js, and vice versa (bug26283)
2624 $userScripts[] = 'user';
2627 $scripts .= $this->makeResourceLoaderLink( $sk, $userScripts, ResourceLoaderModule::TYPE_SCRIPTS );
2629 return $scripts;
2633 * Get an array containing global JS variables
2635 * Do not add things here which can be evaluated in
2636 * ResourceLoaderStartupScript - in other words, without state.
2637 * You will only be adding bloat to the page and causing page caches to
2638 * have to be purged on configuration changes.
2640 protected function getJSVars() {
2641 global $wgUseAjax, $wgEnableMWSuggest, $wgContLang;
2643 $title = $this->getTitle();
2644 $ns = $title->getNamespace();
2645 $nsname = MWNamespace::exists( $ns ) ? MWNamespace::getCanonicalName( $ns ) : $title->getNsText();
2646 if ( $ns == NS_SPECIAL ) {
2647 list( $canonicalName, /*...*/ ) = SpecialPageFactory::resolveAlias( $title->getDBkey() );
2648 } else {
2649 $canonicalName = false; # bug 21115
2652 $vars = array(
2653 'wgCanonicalNamespace' => $nsname,
2654 'wgCanonicalSpecialPageName' => $canonicalName,
2655 'wgNamespaceNumber' => $title->getNamespace(),
2656 'wgPageName' => $title->getPrefixedDBKey(),
2657 'wgTitle' => $title->getText(),
2658 'wgCurRevisionId' => $title->getLatestRevID(),
2659 'wgArticleId' => $title->getArticleId(),
2660 'wgIsArticle' => $this->isArticle(),
2661 'wgAction' => $this->getRequest()->getText( 'action', 'view' ),
2662 'wgUserName' => $this->getUser()->isAnon() ? null : $this->getUser()->getName(),
2663 'wgUserGroups' => $this->getUser()->getEffectiveGroups(),
2664 'wgCategories' => $this->getCategories(),
2665 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
2667 if ( $wgContLang->hasVariants() ) {
2668 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
2670 foreach ( $title->getRestrictionTypes() as $type ) {
2671 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
2673 if ( $wgUseAjax && $wgEnableMWSuggest && !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2674 $vars['wgSearchNamespaces'] = SearchEngine::userNamespaces( $this->getUser() );
2676 if ( $title->isMainPage() ) {
2677 $vars['wgIsMainPage'] = true;
2680 // Allow extensions to add their custom variables to the global JS variables
2681 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars ) );
2683 return $vars;
2687 * @param $sk Skin
2688 * @param $addContentType bool
2690 * @return string HTML tag links to be put in the header.
2692 public function getHeadLinks( Skin $sk, $addContentType = false ) {
2693 global $wgUniversalEditButton, $wgFavicon, $wgAppleTouchIcon, $wgEnableAPI,
2694 $wgSitename, $wgVersion, $wgHtml5, $wgMimeType,
2695 $wgFeed, $wgOverrideSiteFeed, $wgAdvertisedFeedTypes,
2696 $wgDisableLangConversion, $wgCanonicalLanguageLinks, $wgContLang,
2697 $wgRightsPage, $wgRightsUrl;
2699 $tags = array();
2701 if ( $addContentType ) {
2702 if ( $wgHtml5 ) {
2703 # More succinct than <meta http-equiv=Content-Type>, has the
2704 # same effect
2705 $tags[] = Html::element( 'meta', array( 'charset' => 'UTF-8' ) );
2706 } else {
2707 $tags[] = Html::element( 'meta', array(
2708 'http-equiv' => 'Content-Type',
2709 'content' => "$wgMimeType; charset=UTF-8"
2710 ) );
2711 $tags[] = Html::element( 'meta', array( // bug 15835
2712 'http-equiv' => 'Content-Style-Type',
2713 'content' => 'text/css'
2714 ) );
2718 $tags[] = Html::element( 'meta', array(
2719 'name' => 'generator',
2720 'content' => "MediaWiki $wgVersion",
2721 ) );
2723 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
2724 if( $p !== 'index,follow' ) {
2725 // http://www.robotstxt.org/wc/meta-user.html
2726 // Only show if it's different from the default robots policy
2727 $tags[] = Html::element( 'meta', array(
2728 'name' => 'robots',
2729 'content' => $p,
2730 ) );
2733 if ( count( $this->mKeywords ) > 0 ) {
2734 $strip = array(
2735 "/<.*?" . ">/" => '',
2736 "/_/" => ' '
2738 $tags[] = Html::element( 'meta', array(
2739 'name' => 'keywords',
2740 'content' => preg_replace(
2741 array_keys( $strip ),
2742 array_values( $strip ),
2743 implode( ',', $this->mKeywords )
2745 ) );
2748 foreach ( $this->mMetatags as $tag ) {
2749 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
2750 $a = 'http-equiv';
2751 $tag[0] = substr( $tag[0], 5 );
2752 } else {
2753 $a = 'name';
2755 $tags[] = Html::element( 'meta',
2756 array(
2757 $a => $tag[0],
2758 'content' => $tag[1]
2763 foreach ( $this->mLinktags as $tag ) {
2764 $tags[] = Html::element( 'link', $tag );
2767 # Universal edit button
2768 if ( $wgUniversalEditButton ) {
2769 if ( $this->isArticleRelated() && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
2770 && ( $this->getTitle()->exists() || $this->getTitle()->quickUserCan( 'create' ) ) ) {
2771 // Original UniversalEditButton
2772 $msg = wfMsg( 'edit' );
2773 $tags[] = Html::element( 'link', array(
2774 'rel' => 'alternate',
2775 'type' => 'application/x-wiki',
2776 'title' => $msg,
2777 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
2778 ) );
2779 // Alternate edit link
2780 $tags[] = Html::element( 'link', array(
2781 'rel' => 'edit',
2782 'title' => $msg,
2783 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
2784 ) );
2788 # Generally the order of the favicon and apple-touch-icon links
2789 # should not matter, but Konqueror (3.5.9 at least) incorrectly
2790 # uses whichever one appears later in the HTML source. Make sure
2791 # apple-touch-icon is specified first to avoid this.
2792 if ( $wgAppleTouchIcon !== false ) {
2793 $tags[] = Html::element( 'link', array( 'rel' => 'apple-touch-icon', 'href' => $wgAppleTouchIcon ) );
2796 if ( $wgFavicon !== false ) {
2797 $tags[] = Html::element( 'link', array( 'rel' => 'shortcut icon', 'href' => $wgFavicon ) );
2800 # OpenSearch description link
2801 $tags[] = Html::element( 'link', array(
2802 'rel' => 'search',
2803 'type' => 'application/opensearchdescription+xml',
2804 'href' => wfScript( 'opensearch_desc' ),
2805 'title' => wfMsgForContent( 'opensearch-desc' ),
2806 ) );
2808 if ( $wgEnableAPI ) {
2809 # Real Simple Discovery link, provides auto-discovery information
2810 # for the MediaWiki API (and potentially additional custom API
2811 # support such as WordPress or Twitter-compatible APIs for a
2812 # blogging extension, etc)
2813 $tags[] = Html::element( 'link', array(
2814 'rel' => 'EditURI',
2815 'type' => 'application/rsd+xml',
2816 'href' => wfExpandUrl( wfAppendQuery( wfScript( 'api' ), array( 'action' => 'rsd' ) ) ),
2817 ) );
2820 # Language variants
2821 if ( !$wgDisableLangConversion && $wgCanonicalLanguageLinks
2822 && $wgContLang->hasVariants() ) {
2824 $urlvar = $wgContLang->getURLVariant();
2826 if ( !$urlvar ) {
2827 $variants = $wgContLang->getVariants();
2828 foreach ( $variants as $_v ) {
2829 $tags[] = Html::element( 'link', array(
2830 'rel' => 'alternate',
2831 'hreflang' => $_v,
2832 'href' => $this->getTitle()->getLocalURL( '', $_v ) )
2835 } else {
2836 $tags[] = Html::element( 'link', array(
2837 'rel' => 'canonical',
2838 'href' => $this->getTitle()->getFullURL() )
2843 # Copyright
2844 $copyright = '';
2845 if ( $wgRightsPage ) {
2846 $copy = Title::newFromText( $wgRightsPage );
2848 if ( $copy ) {
2849 $copyright = $copy->getLocalURL();
2853 if ( !$copyright && $wgRightsUrl ) {
2854 $copyright = $wgRightsUrl;
2857 if ( $copyright ) {
2858 $tags[] = Html::element( 'link', array(
2859 'rel' => 'copyright',
2860 'href' => $copyright )
2864 # Feeds
2865 if ( $wgFeed ) {
2866 foreach( $this->getSyndicationLinks() as $format => $link ) {
2867 # Use the page name for the title. In principle, this could
2868 # lead to issues with having the same name for different feeds
2869 # corresponding to the same page, but we can't avoid that at
2870 # this low a level.
2872 $tags[] = $this->feedLink(
2873 $format,
2874 $link,
2875 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
2876 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )
2880 # Recent changes feed should appear on every page (except recentchanges,
2881 # that would be redundant). Put it after the per-page feed to avoid
2882 # changing existing behavior. It's still available, probably via a
2883 # menu in your browser. Some sites might have a different feed they'd
2884 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
2885 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
2886 # If so, use it instead.
2888 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
2890 if ( $wgOverrideSiteFeed ) {
2891 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
2892 $tags[] = $this->feedLink(
2893 $type,
2894 htmlspecialchars( $feedUrl ),
2895 wfMsg( "site-{$type}-feed", $wgSitename )
2898 } elseif ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
2899 foreach ( $wgAdvertisedFeedTypes as $format ) {
2900 $tags[] = $this->feedLink(
2901 $format,
2902 $rctitle->getLocalURL( "feed={$format}" ),
2903 wfMsg( "site-{$format}-feed", $wgSitename ) # For grep: 'site-rss-feed', 'site-atom-feed'.
2908 return implode( "\n", $tags );
2912 * Generate a <link rel/> for a feed.
2914 * @param $type String: feed type
2915 * @param $url String: URL to the feed
2916 * @param $text String: value of the "title" attribute
2917 * @return String: HTML fragment
2919 private function feedLink( $type, $url, $text ) {
2920 return Html::element( 'link', array(
2921 'rel' => 'alternate',
2922 'type' => "application/$type+xml",
2923 'title' => $text,
2924 'href' => $url )
2929 * Add a local or specified stylesheet, with the given media options.
2930 * Meant primarily for internal use...
2932 * @param $style String: URL to the file
2933 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
2934 * @param $condition String: for IE conditional comments, specifying an IE version
2935 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
2937 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
2938 $options = array();
2939 // Even though we expect the media type to be lowercase, but here we
2940 // force it to lowercase to be safe.
2941 if( $media ) {
2942 $options['media'] = $media;
2944 if( $condition ) {
2945 $options['condition'] = $condition;
2947 if( $dir ) {
2948 $options['dir'] = $dir;
2950 $this->styles[$style] = $options;
2954 * Adds inline CSS styles
2955 * @param $style_css Mixed: inline CSS
2957 public function addInlineStyle( $style_css ){
2958 $this->mInlineStyles .= Html::inlineStyle( $style_css );
2962 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
2963 * These will be applied to various media & IE conditionals.
2964 * @param $sk Skin object
2966 * @return string
2968 public function buildCssLinks( $sk ) {
2969 $ret = '';
2970 // Add ResourceLoader styles
2971 // Split the styles into four groups
2972 $styles = array( 'other' => array(), 'user' => array(), 'site' => array(), 'private' => array(), 'noscript' => array() );
2973 $resourceLoader = $this->getResourceLoader();
2974 foreach ( $this->getModuleStyles() as $name ) {
2975 $group = $resourceLoader->getModule( $name )->getGroup();
2976 // Modules in groups named "other" or anything different than "user", "site" or "private"
2977 // will be placed in the "other" group
2978 $styles[isset( $styles[$group] ) ? $group : 'other'][] = $name;
2981 // We want site, private and user styles to override dynamically added styles from modules, but we want
2982 // dynamically added styles to override statically added styles from other modules. So the order
2983 // has to be other, dynamic, site, private, user
2984 // Add statically added styles for other modules
2985 $ret .= $this->makeResourceLoaderLink( $sk, $styles['other'], ResourceLoaderModule::TYPE_STYLES );
2986 // Add normal styles added through addStyle()/addInlineStyle() here
2987 $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles;
2988 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
2989 // We use a <meta> tag with a made-up name for this because that's valid HTML
2990 $ret .= Html::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) ) . "\n";
2992 // Add site, private and user styles
2993 // 'private' at present only contains user.options, so put that before 'user'
2994 // Any future private modules will likely have a similar user-specific character
2995 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
2996 $ret .= $this->makeResourceLoaderLink( $sk, $styles[$group],
2997 ResourceLoaderModule::TYPE_STYLES
3000 return $ret;
3003 public function buildCssLinksArray() {
3004 $links = array();
3005 foreach( $this->styles as $file => $options ) {
3006 $link = $this->styleLink( $file, $options );
3007 if( $link ) {
3008 $links[$file] = $link;
3011 return $links;
3015 * Generate \<link\> tags for stylesheets
3017 * @param $style String: URL to the file
3018 * @param $options Array: option, can contain 'condition', 'dir', 'media'
3019 * keys
3020 * @return String: HTML fragment
3022 protected function styleLink( $style, $options ) {
3023 if( isset( $options['dir'] ) ) {
3024 global $wgLang;
3025 if( $wgLang->getDir() != $options['dir'] ) {
3026 return '';
3030 if( isset( $options['media'] ) ) {
3031 $media = self::transformCssMedia( $options['media'] );
3032 if( is_null( $media ) ) {
3033 return '';
3035 } else {
3036 $media = 'all';
3039 if( substr( $style, 0, 1 ) == '/' ||
3040 substr( $style, 0, 5 ) == 'http:' ||
3041 substr( $style, 0, 6 ) == 'https:' ) {
3042 $url = $style;
3043 } else {
3044 global $wgStylePath, $wgStyleVersion;
3045 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
3048 $link = Html::linkedStyle( $url, $media );
3050 if( isset( $options['condition'] ) ) {
3051 $condition = htmlspecialchars( $options['condition'] );
3052 $link = "<!--[if $condition]>$link<![endif]-->";
3054 return $link;
3058 * Transform "media" attribute based on request parameters
3060 * @param $media String: current value of the "media" attribute
3061 * @return String: modified value of the "media" attribute
3063 public static function transformCssMedia( $media ) {
3064 global $wgRequest, $wgHandheldForIPhone;
3066 // Switch in on-screen display for media testing
3067 $switches = array(
3068 'printable' => 'print',
3069 'handheld' => 'handheld',
3071 foreach( $switches as $switch => $targetMedia ) {
3072 if( $wgRequest->getBool( $switch ) ) {
3073 if( $media == $targetMedia ) {
3074 $media = '';
3075 } elseif( $media == 'screen' ) {
3076 return null;
3081 // Expand longer media queries as iPhone doesn't grok 'handheld'
3082 if( $wgHandheldForIPhone ) {
3083 $mediaAliases = array(
3084 'screen' => 'screen and (min-device-width: 481px)',
3085 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
3088 if( isset( $mediaAliases[$media] ) ) {
3089 $media = $mediaAliases[$media];
3093 return $media;
3097 * Add a wikitext-formatted message to the output.
3098 * This is equivalent to:
3100 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
3102 public function addWikiMsg( /*...*/ ) {
3103 $args = func_get_args();
3104 $name = array_shift( $args );
3105 $this->addWikiMsgArray( $name, $args );
3109 * Add a wikitext-formatted message to the output.
3110 * Like addWikiMsg() except the parameters are taken as an array
3111 * instead of a variable argument list.
3113 * $options is passed through to wfMsgExt(), see that function for details.
3115 * @param $name string
3116 * @param $args array
3117 * @param $options array
3119 public function addWikiMsgArray( $name, $args, $options = array() ) {
3120 $options[] = 'parse';
3121 $text = wfMsgExt( $name, $options, $args );
3122 $this->addHTML( $text );
3126 * This function takes a number of message/argument specifications, wraps them in
3127 * some overall structure, and then parses the result and adds it to the output.
3129 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3130 * on. The subsequent arguments may either be strings, in which case they are the
3131 * message names, or arrays, in which case the first element is the message name,
3132 * and subsequent elements are the parameters to that message.
3134 * The special named parameter 'options' in a message specification array is passed
3135 * through to the $options parameter of wfMsgExt().
3137 * Don't use this for messages that are not in users interface language.
3139 * For example:
3141 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3143 * Is equivalent to:
3145 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . "\n</div>" );
3147 * The newline after opening div is needed in some wikitext. See bug 19226.
3149 * @param $wrap string
3151 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3152 $msgSpecs = func_get_args();
3153 array_shift( $msgSpecs );
3154 $msgSpecs = array_values( $msgSpecs );
3155 $s = $wrap;
3156 foreach ( $msgSpecs as $n => $spec ) {
3157 $options = array();
3158 if ( is_array( $spec ) ) {
3159 $args = $spec;
3160 $name = array_shift( $args );
3161 if ( isset( $args['options'] ) ) {
3162 $options = $args['options'];
3163 unset( $args['options'] );
3165 } else {
3166 $args = array();
3167 $name = $spec;
3169 $s = str_replace( '$' . ( $n + 1 ), wfMsgExt( $name, $options, $args ), $s );
3171 $this->addWikiText( $s );
3175 * Include jQuery core. Use this to avoid loading it multiple times
3176 * before we get a usable script loader.
3178 * @param $modules Array: list of jQuery modules which should be loaded
3179 * @return Array: the list of modules which were not loaded.
3180 * @since 1.16
3181 * @deprecated since 1.17
3183 public function includeJQuery( $modules = array() ) {
3184 return array();