2 if ( !defined( 'MEDIAWIKI' ) ) {
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 Antoine Musso
21 class OutputPage
extends ContextSource
{
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
36 /// Contains all of the <body> content. Should be private we got set/get accessors and the append() method.
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
49 /// Should be private. Is the displayed content related to the source of the corresponding wiki article.
50 var $mIsarticle = false;
53 * Should be private. Has get/set methods properly documented.
54 * Stores "article flag" toggle.
56 var $mIsArticleRelated = true;
59 * Should be private. We have to set isPrintable(). Some pages should
60 * never be printed (ex: redirections).
62 var $mPrintable = false;
65 * Should be private. We have set/get/append methods.
67 * Contains the page subtitle. Special pages usually have some links here.
68 * Don't confuse with site subtitle added by skins.
70 private $mSubtitle = array();
76 * mLastModified and mEtag are used for sending cache control.
77 * The whole caching system should probably be moved into its own class.
79 var $mLastModified = '';
82 * Should be private. No getter but used in sendCacheControl();
83 * Contains an HTTP Entity Tags (see RFC 2616 section 3.13) which is used
84 * as a unique identifier for the content. It is later used by the client
85 * to compare its cached version with the server version. Client sends
86 * headers If-Match and If-None-Match containing its locally cached ETAG value.
88 * To get more information, you will have to look at HTTP/1.1 protocol which
89 * is properly described in RFC 2616 : http://tools.ietf.org/html/rfc2616
93 var $mCategoryLinks = array();
94 var $mCategories = array();
96 /// Should be private. Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
97 var $mLanguageLinks = array();
100 * Should be private. Used for JavaScript (pre resource loader)
101 * We should split js / css.
102 * mScripts content is inserted as is in <head> by Skin. This might contains
103 * either a link to a stylesheet or inline css.
108 * Inline CSS styles. Use addInlineStyle() sparsingly
110 var $mInlineStyles = '';
116 * Used by skin template.
117 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
119 var $mPageLinkTitle = '';
121 /// Array of elements in <head>. Parser might add its own headers!
122 var $mHeadItems = array();
124 // @todo FIXME: Next variables probably comes from the resource loader
125 var $mModules = array(), $mModuleScripts = array(), $mModuleStyles = array(), $mModuleMessages = array();
126 var $mResourceLoader;
127 var $mJsConfigVars = array();
129 /** @todo FIXME: Is this still used ?*/
130 var $mInlineMsg = array();
132 var $mTemplateIds = array();
133 var $mImageTimeKeys = array();
135 var $mRedirectCode = '';
137 var $mFeedLinksAppendQuery = null;
139 # What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
140 # @see ResourceLoaderModule::$origin
141 # ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
142 protected $mAllowedModules = array(
143 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
147 * @EasterEgg I just love the name for this self documenting variable.
150 var $mDoNothing = false;
153 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
156 * lazy initialised, use parserOptions()
159 protected $mParserOptions = null;
162 * Handles the atom / rss links.
163 * We probably only support atom in 2011.
164 * Looks like a private variable.
165 * @see $wgAdvertisedFeedTypes
167 var $mFeedLinks = array();
169 // Gwicke work on squid caching? Roughly from 2003.
170 var $mEnableClientCache = true;
173 * Flag if output should only contain the body of the article.
176 var $mArticleBodyOnly = false;
178 var $mNewSectionLink = false;
179 var $mHideNewSectionLink = false;
182 * Comes from the parser. This was probably made to load CSS/JS only
183 * if we had <gallery>. Used directly in CategoryPage.php
184 * Looks like resource loader can replace this.
186 var $mNoGallery = false;
188 // should be private.
189 var $mPageTitleActionText = '';
190 var $mParseWarnings = array();
192 // Cache stuff. Looks like mEnableClientCache
193 var $mSquidMaxage = 0;
196 var $mPreventClickjacking = true;
198 /// should be private. To include the variable {{REVISIONID}}
199 var $mRevisionId = null;
201 var $mFileVersion = null;
204 * An array of stylesheet filenames (relative from skins path), with options
205 * for CSS media, IE conditions, and RTL/LTR direction.
206 * For internal use; add settings in the skin via $this->addStyle()
208 * Style again! This seems like a code duplication since we already have
209 * mStyles. This is what makes OpenSource amazing.
211 var $styles = array();
214 * Whether jQuery is already handled.
216 protected $mJQueryDone = false;
218 private $mIndexPolicy = 'index';
219 private $mFollowPolicy = 'follow';
220 private $mVaryHeader = array(
221 'Accept-Encoding' => array( 'list-contains=gzip' ),
226 * Constructor for OutputPage. This should not be called directly.
227 * Instead a new RequestContext should be created and it will implicitly create
228 * a OutputPage tied to that context.
230 function __construct( IContextSource
$context = null ) {
231 if ( $context === null ) {
232 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
233 wfDeprecated( __METHOD__
);
235 $this->setContext( $context );
240 * Redirect to $url rather than displaying the normal page
242 * @param $url String: URL
243 * @param $responsecode String: HTTP status code
245 public function redirect( $url, $responsecode = '302' ) {
246 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
247 $this->mRedirect
= str_replace( "\n", '', $url );
248 $this->mRedirectCode
= $responsecode;
252 * Get the URL to redirect to, or an empty string if not redirect URL set
256 public function getRedirect() {
257 return $this->mRedirect
;
261 * Set the HTTP status code to send with the output.
263 * @param $statusCode Integer
265 public function setStatusCode( $statusCode ) {
266 $this->mStatusCode
= $statusCode;
270 * Add a new <meta> tag
271 * To add an http-equiv meta tag, precede the name with "http:"
273 * @param $name String tag name
274 * @param $val String tag value
276 function addMeta( $name, $val ) {
277 array_push( $this->mMetatags
, array( $name, $val ) );
281 * Add a keyword or a list of keywords in the page header
283 * @param $text String or array of strings
285 function addKeyword( $text ) {
286 if( is_array( $text ) ) {
287 $this->mKeywords
= array_merge( $this->mKeywords
, $text );
289 array_push( $this->mKeywords
, $text );
294 * Add a new \<link\> tag to the page header
296 * @param $linkarr Array: associative array of attributes.
298 function addLink( $linkarr ) {
299 array_push( $this->mLinktags
, $linkarr );
303 * Add a new \<link\> with "rel" attribute set to "meta"
305 * @param $linkarr Array: associative array mapping attribute names to their
306 * values, both keys and values will be escaped, and the
307 * "rel" attribute will be automatically added
309 function addMetadataLink( $linkarr ) {
310 $linkarr['rel'] = $this->getMetadataAttribute();
311 $this->addLink( $linkarr );
315 * Get the value of the "rel" attribute for metadata links
319 public function getMetadataAttribute() {
320 # note: buggy CC software only reads first "meta" link
321 static $haveMeta = false;
323 return 'alternate meta';
331 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
333 * @param $script String: raw HTML
335 function addScript( $script ) {
336 $this->mScripts
.= $script . "\n";
340 * Register and add a stylesheet from an extension directory.
342 * @param $url String path to sheet. Provide either a full url (beginning
343 * with 'http', etc) or a relative path from the document root
344 * (beginning with '/'). Otherwise it behaves identically to
345 * addStyle() and draws from the /skins folder.
347 public function addExtensionStyle( $url ) {
348 array_push( $this->mExtStyles
, $url );
352 * Get all styles added by extensions
356 function getExtStyle() {
357 return $this->mExtStyles
;
361 * Add a JavaScript file out of skins/common, or a given relative path.
363 * @param $file String: filename in skins/common or complete on-server path
365 * @param $version String: style version of the file. Defaults to $wgStyleVersion
367 public function addScriptFile( $file, $version = null ) {
368 global $wgStylePath, $wgStyleVersion;
369 // See if $file parameter is an absolute URL or begins with a slash
370 if( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
373 $path = "{$wgStylePath}/common/{$file}";
375 if ( is_null( $version ) )
376 $version = $wgStyleVersion;
377 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
381 * Add a self-contained script tag with the given contents
383 * @param $script String: JavaScript text, no <script> tags
385 public function addInlineScript( $script ) {
386 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
390 * Get all registered JS and CSS tags for the header.
394 function getScript() {
395 return $this->mScripts
. $this->getHeadItems();
399 * Filter an array of modules to remove insufficiently trustworthy members, and modules
400 * which are no longer registered (eg a page is cached before an extension is disabled)
401 * @param $modules Array
402 * @param $position String if not null, only return modules with this position
403 * @param $type string
406 protected function filterModules( $modules, $position = null, $type = ResourceLoaderModule
::TYPE_COMBINED
){
407 $resourceLoader = $this->getResourceLoader();
408 $filteredModules = array();
409 foreach( $modules as $val ){
410 $module = $resourceLoader->getModule( $val );
411 if( $module instanceof ResourceLoaderModule
412 && $module->getOrigin() <= $this->getAllowedModules( $type )
413 && ( is_null( $position ) ||
$module->getPosition() == $position ) )
415 $filteredModules[] = $val;
418 return $filteredModules;
422 * Get the list of modules to include on this page
424 * @param $filter Bool whether to filter out insufficiently trustworthy modules
425 * @param $position String if not null, only return modules with this position
426 * @param $param string
427 * @return Array of module names
429 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
430 $modules = array_values( array_unique( $this->$param ) );
432 ?
$this->filterModules( $modules, $position )
437 * Add one or more modules recognized by the resource loader. Modules added
438 * through this function will be loaded by the resource loader when the
441 * @param $modules Mixed: module name (string) or array of module names
443 public function addModules( $modules ) {
444 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
448 * Get the list of module JS to include on this page
453 * @return array of module names
455 public function getModuleScripts( $filter = false, $position = null ) {
456 return $this->getModules( $filter, $position, 'mModuleScripts' );
460 * Add only JS of one or more modules recognized by the resource loader. Module
461 * scripts added through this function will be loaded by the resource loader when
464 * @param $modules Mixed: module name (string) or array of module names
466 public function addModuleScripts( $modules ) {
467 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
471 * Get the list of module CSS to include on this page
476 * @return Array of module names
478 public function getModuleStyles( $filter = false, $position = null ) {
479 return $this->getModules( $filter, $position, 'mModuleStyles' );
483 * Add only CSS of one or more modules recognized by the resource loader. Module
484 * styles added through this function will be loaded by the resource loader when
487 * @param $modules Mixed: module name (string) or array of module names
489 public function addModuleStyles( $modules ) {
490 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
494 * Get the list of module messages to include on this page
499 * @return Array of module names
501 public function getModuleMessages( $filter = false, $position = null ) {
502 return $this->getModules( $filter, $position, 'mModuleMessages' );
506 * Add only messages of one or more modules recognized by the resource loader.
507 * Module messages added through this function will be loaded by the resource
508 * loader when the page loads.
510 * @param $modules Mixed: module name (string) or array of module names
512 public function addModuleMessages( $modules ) {
513 $this->mModuleMessages
= array_merge( $this->mModuleMessages
, (array)$modules );
517 * Get an array of head items
521 function getHeadItemsArray() {
522 return $this->mHeadItems
;
526 * Get all header items in a string
530 function getHeadItems() {
532 foreach ( $this->mHeadItems
as $item ) {
539 * Add or replace an header item to the output
541 * @param $name String: item name
542 * @param $value String: raw HTML
544 public function addHeadItem( $name, $value ) {
545 $this->mHeadItems
[$name] = $value;
549 * Check if the header item $name is already set
551 * @param $name String: item name
554 public function hasHeadItem( $name ) {
555 return isset( $this->mHeadItems
[$name] );
559 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
561 * @param $tag String: value of "ETag" header
563 function setETag( $tag ) {
568 * Set whether the output should only contain the body of the article,
569 * without any skin, sidebar, etc.
570 * Used e.g. when calling with "action=render".
572 * @param $only Boolean: whether to output only the body of the article
574 public function setArticleBodyOnly( $only ) {
575 $this->mArticleBodyOnly
= $only;
579 * Return whether the output will contain only the body of the article
583 public function getArticleBodyOnly() {
584 return $this->mArticleBodyOnly
;
588 * checkLastModified tells the client to use the client-cached page if
589 * possible. If sucessful, the OutputPage is disabled so that
590 * any future call to OutputPage->output() have no effect.
592 * Side effect: sets mLastModified for Last-Modified header
594 * @param $timestamp string
596 * @return Boolean: true iff cache-ok headers was sent.
598 public function checkLastModified( $timestamp ) {
599 global $wgCachePages, $wgCacheEpoch;
601 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
602 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
605 if( !$wgCachePages ) {
606 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
609 if( $this->getUser()->getOption( 'nocache' ) ) {
610 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
614 $timestamp = wfTimestamp( TS_MW
, $timestamp );
615 $modifiedTimes = array(
616 'page' => $timestamp,
617 'user' => $this->getUser()->getTouched(),
618 'epoch' => $wgCacheEpoch
620 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
622 $maxModified = max( $modifiedTimes );
623 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
625 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
626 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
632 foreach ( $modifiedTimes as $name => $value ) {
633 if ( $info !== '' ) {
636 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
639 # IE sends sizes after the date like this:
640 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
641 # this breaks strtotime().
642 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
644 wfSuppressWarnings(); // E_STRICT system time bitching
645 $clientHeaderTime = strtotime( $clientHeader );
647 if ( !$clientHeaderTime ) {
648 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
651 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
653 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
654 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
655 wfDebug( __METHOD__
. ": effective Last-Modified: " .
656 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
657 if( $clientHeaderTime < $maxModified ) {
658 wfDebug( __METHOD__
. ": STALE, $info\n", false );
663 # Give a 304 response code and disable body output
664 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
665 ini_set( 'zlib.output_compression', 0 );
666 $this->getRequest()->response()->header( "HTTP/1.1 304 Not Modified" );
667 $this->sendCacheControl();
670 // Don't output a compressed blob when using ob_gzhandler;
671 // it's technically against HTTP spec and seems to confuse
672 // Firefox when the response gets split over two packets.
673 wfClearOutputBuffers();
679 * Override the last modified timestamp
681 * @param $timestamp String: new timestamp, in a format readable by
684 public function setLastModified( $timestamp ) {
685 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
689 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
691 * @param $policy String: the literal string to output as the contents of
692 * the meta tag. Will be parsed according to the spec and output in
696 public function setRobotPolicy( $policy ) {
697 $policy = Article
::formatRobotPolicy( $policy );
699 if( isset( $policy['index'] ) ) {
700 $this->setIndexPolicy( $policy['index'] );
702 if( isset( $policy['follow'] ) ) {
703 $this->setFollowPolicy( $policy['follow'] );
708 * Set the index policy for the page, but leave the follow policy un-
711 * @param $policy string Either 'index' or 'noindex'.
714 public function setIndexPolicy( $policy ) {
715 $policy = trim( $policy );
716 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
717 $this->mIndexPolicy
= $policy;
722 * Set the follow policy for the page, but leave the index policy un-
725 * @param $policy String: either 'follow' or 'nofollow'.
728 public function setFollowPolicy( $policy ) {
729 $policy = trim( $policy );
730 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
731 $this->mFollowPolicy
= $policy;
736 * Set the new value of the "action text", this will be added to the
737 * "HTML title", separated from it with " - ".
739 * @param $text String: new value of the "action text"
741 public function setPageTitleActionText( $text ) {
742 $this->mPageTitleActionText
= $text;
746 * Get the value of the "action text"
750 public function getPageTitleActionText() {
751 if ( isset( $this->mPageTitleActionText
) ) {
752 return $this->mPageTitleActionText
;
757 * "HTML title" means the contents of <title>.
758 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
760 * @param $name string
762 public function setHTMLTitle( $name ) {
763 if ( $name instanceof Message
) {
764 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
766 $this->mHTMLtitle
= $name;
771 * Return the "HTML title", i.e. the content of the <title> tag.
775 public function getHTMLTitle() {
776 return $this->mHTMLtitle
;
780 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
781 * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
782 * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
783 * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
785 * @param $name string|Message
787 public function setPageTitle( $name ) {
788 if ( $name instanceof Message
) {
789 $name = $name->setContext( $this->getContext() )->text();
792 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
793 # but leave "<i>foobar</i>" alone
794 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
795 $this->mPagetitle
= $nameWithTags;
797 # change "<i>foo&bar</i>" to "foo&bar"
798 $this->setHTMLTitle( $this->msg( 'pagetitle', Sanitizer
::stripAllTags( $nameWithTags ) ) );
802 * Return the "page title", i.e. the content of the \<h1\> tag.
806 public function getPageTitle() {
807 return $this->mPagetitle
;
811 * Set the Title object to use
813 * @param $t Title object
815 public function setTitle( Title
$t ) {
816 $this->getContext()->setTitle( $t );
821 * Replace the subtile with $str
823 * @param $str String|Message: new value of the subtitle
825 public function setSubtitle( $str ) {
826 $this->clearSubtitle();
827 $this->addSubtitle( $str );
831 * Add $str to the subtitle
833 * @deprecated in 1.19; use addSubtitle() instead
834 * @param $str String|Message to add to the subtitle
836 public function appendSubtitle( $str ) {
837 $this->addSubtitle( $str );
841 * Add $str to the subtitle
843 * @param $str String|Message to add to the subtitle
845 public function addSubtitle( $str ) {
846 if ( $str instanceof Message
) {
847 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
849 $this->mSubtitle
[] = $str;
854 * Add a subtitle containing a backlink to a page
856 * @param $title Title to link to
858 public function addBacklinkSubtitle( Title
$title ) {
860 if ( $title->isRedirect() ) {
861 $query['redirect'] = 'no';
863 $this->addSubtitle( $this->msg( 'backlinksubtitle' )->rawParams( Linker
::link( $title, null, array(), $query ) ) );
867 * Clear the subtitles
869 public function clearSubtitle() {
870 $this->mSubtitle
= array();
878 public function getSubtitle() {
879 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
883 * Set the page as printable, i.e. it'll be displayed with with all
884 * print styles included
886 public function setPrintable() {
887 $this->mPrintable
= true;
891 * Return whether the page is "printable"
895 public function isPrintable() {
896 return $this->mPrintable
;
900 * Disable output completely, i.e. calling output() will have no effect
902 public function disable() {
903 $this->mDoNothing
= true;
907 * Return whether the output will be completely disabled
911 public function isDisabled() {
912 return $this->mDoNothing
;
916 * Show an "add new section" link?
920 public function showNewSectionLink() {
921 return $this->mNewSectionLink
;
925 * Forcibly hide the new section link?
929 public function forceHideNewSectionLink() {
930 return $this->mHideNewSectionLink
;
934 * Add or remove feed links in the page header
935 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
936 * for the new version
939 * @param $show Boolean: true: add default feeds, false: remove all feeds
941 public function setSyndicated( $show = true ) {
943 $this->setFeedAppendQuery( false );
945 $this->mFeedLinks
= array();
950 * Add default feeds to the page header
951 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
952 * for the new version
955 * @param $val String: query to append to feed links or false to output
958 public function setFeedAppendQuery( $val ) {
959 global $wgAdvertisedFeedTypes;
961 $this->mFeedLinks
= array();
963 foreach ( $wgAdvertisedFeedTypes as $type ) {
964 $query = "feed=$type";
965 if ( is_string( $val ) ) {
966 $query .= '&' . $val;
968 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
973 * Add a feed link to the page header
975 * @param $format String: feed type, should be a key of $wgFeedClasses
976 * @param $href String: URL
978 public function addFeedLink( $format, $href ) {
979 global $wgAdvertisedFeedTypes;
981 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
982 $this->mFeedLinks
[$format] = $href;
987 * Should we output feed links for this page?
990 public function isSyndicated() {
991 return count( $this->mFeedLinks
) > 0;
995 * Return URLs for each supported syndication format for this page.
996 * @return array associating format keys with URLs
998 public function getSyndicationLinks() {
999 return $this->mFeedLinks
;
1003 * Will currently always return null
1007 public function getFeedAppendQuery() {
1008 return $this->mFeedLinksAppendQuery
;
1012 * Set whether the displayed content is related to the source of the
1013 * corresponding article on the wiki
1014 * Setting true will cause the change "article related" toggle to true
1018 public function setArticleFlag( $v ) {
1019 $this->mIsarticle
= $v;
1021 $this->mIsArticleRelated
= $v;
1026 * Return whether the content displayed page is related to the source of
1027 * the corresponding article on the wiki
1031 public function isArticle() {
1032 return $this->mIsarticle
;
1036 * Set whether this page is related an article on the wiki
1037 * Setting false will cause the change of "article flag" toggle to false
1041 public function setArticleRelated( $v ) {
1042 $this->mIsArticleRelated
= $v;
1044 $this->mIsarticle
= false;
1049 * Return whether this page is related an article on the wiki
1053 public function isArticleRelated() {
1054 return $this->mIsArticleRelated
;
1058 * Add new language links
1060 * @param $newLinkArray Associative array mapping language code to the page
1063 public function addLanguageLinks( $newLinkArray ) {
1064 $this->mLanguageLinks +
= $newLinkArray;
1068 * Reset the language links and add new language links
1070 * @param $newLinkArray Associative array mapping language code to the page
1073 public function setLanguageLinks( $newLinkArray ) {
1074 $this->mLanguageLinks
= $newLinkArray;
1078 * Get the list of language links
1080 * @return Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1082 public function getLanguageLinks() {
1083 return $this->mLanguageLinks
;
1087 * Add an array of categories, with names in the keys
1089 * @param $categories Array mapping category name => sort key
1091 public function addCategoryLinks( $categories ) {
1094 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1098 # Add the links to a LinkBatch
1099 $arr = array( NS_CATEGORY
=> $categories );
1100 $lb = new LinkBatch
;
1101 $lb->setArray( $arr );
1103 # Fetch existence plus the hiddencat property
1104 $dbr = wfGetDB( DB_SLAVE
);
1105 $res = $dbr->select( array( 'page', 'page_props' ),
1106 array( 'page_id', 'page_namespace', 'page_title', 'page_len', 'page_is_redirect', 'page_latest', 'pp_value' ),
1107 $lb->constructSet( 'page', $dbr ),
1110 array( 'page_props' => array( 'LEFT JOIN', array( 'pp_propname' => 'hiddencat', 'pp_page = page_id' ) ) )
1113 # Add the results to the link cache
1114 $lb->addResultToCache( LinkCache
::singleton(), $res );
1116 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
1117 $categories = array_combine(
1118 array_keys( $categories ),
1119 array_fill( 0, count( $categories ), 'normal' )
1122 # Mark hidden categories
1123 foreach ( $res as $row ) {
1124 if ( isset( $row->pp_value
) ) {
1125 $categories[$row->page_title
] = 'hidden';
1129 # Add the remaining categories to the skin
1130 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
1131 foreach ( $categories as $category => $type ) {
1132 $origcategory = $category;
1133 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1134 $wgContLang->findVariantLink( $category, $title, true );
1135 if ( $category != $origcategory ) {
1136 if ( array_key_exists( $category, $categories ) ) {
1140 $text = $wgContLang->convertHtml( $title->getText() );
1141 $this->mCategories
[] = $title->getText();
1142 $this->mCategoryLinks
[$type][] = Linker
::link( $title, $text );
1148 * Reset the category links (but not the category list) and add $categories
1150 * @param $categories Array mapping category name => sort key
1152 public function setCategoryLinks( $categories ) {
1153 $this->mCategoryLinks
= array();
1154 $this->addCategoryLinks( $categories );
1158 * Get the list of category links, in a 2-D array with the following format:
1159 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1160 * hidden categories) and $link a HTML fragment with a link to the category
1165 public function getCategoryLinks() {
1166 return $this->mCategoryLinks
;
1170 * Get the list of category names this page belongs to
1172 * @return Array of strings
1174 public function getCategories() {
1175 return $this->mCategories
;
1179 * Do not allow scripts which can be modified by wiki users to load on this page;
1180 * only allow scripts bundled with, or generated by, the software.
1182 public function disallowUserJs() {
1183 $this->reduceAllowedModules(
1184 ResourceLoaderModule
::TYPE_SCRIPTS
,
1185 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1190 * Return whether user JavaScript is allowed for this page
1191 * @deprecated since 1.18 Load modules with ResourceLoader, and origin and
1192 * trustworthiness is identified and enforced automagically.
1195 public function isUserJsAllowed() {
1196 return $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
) >= ResourceLoaderModule
::ORIGIN_USER_INDIVIDUAL
;
1200 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1201 * @see ResourceLoaderModule::$origin
1202 * @param $type String ResourceLoaderModule TYPE_ constant
1203 * @return Int ResourceLoaderModule ORIGIN_ class constant
1205 public function getAllowedModules( $type ){
1206 if( $type == ResourceLoaderModule
::TYPE_COMBINED
){
1207 return min( array_values( $this->mAllowedModules
) );
1209 return isset( $this->mAllowedModules
[$type] )
1210 ?
$this->mAllowedModules
[$type]
1211 : ResourceLoaderModule
::ORIGIN_ALL
;
1216 * Set the highest level of CSS/JS untrustworthiness allowed
1217 * @param $type String ResourceLoaderModule TYPE_ constant
1218 * @param $level Int ResourceLoaderModule class constant
1220 public function setAllowedModules( $type, $level ){
1221 $this->mAllowedModules
[$type] = $level;
1225 * As for setAllowedModules(), but don't inadvertantly make the page more accessible
1226 * @param $type String
1227 * @param $level Int ResourceLoaderModule class constant
1229 public function reduceAllowedModules( $type, $level ){
1230 $this->mAllowedModules
[$type] = min( $this->getAllowedModules($type), $level );
1234 * Prepend $text to the body HTML
1236 * @param $text String: HTML
1238 public function prependHTML( $text ) {
1239 $this->mBodytext
= $text . $this->mBodytext
;
1243 * Append $text to the body HTML
1245 * @param $text String: HTML
1247 public function addHTML( $text ) {
1248 $this->mBodytext
.= $text;
1252 * Shortcut for adding an Html::element via addHTML.
1256 * @param $element string
1257 * @param $attribs array
1258 * @param $contents string
1260 public function addElement( $element, $attribs = array(), $contents = '' ) {
1261 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1265 * Clear the body HTML
1267 public function clearHTML() {
1268 $this->mBodytext
= '';
1274 * @return String: HTML
1276 public function getHTML() {
1277 return $this->mBodytext
;
1281 * Add $text to the debug output
1283 * @param $text String: debug text
1285 public function debug( $text ) {
1286 $this->mDebugtext
.= $text;
1290 * Get/set the ParserOptions object to use for wikitext parsing
1292 * @param $options either the ParserOption to use or null to only get the
1293 * current ParserOption object
1294 * @return ParserOptions object
1296 public function parserOptions( $options = null ) {
1297 if ( !$this->mParserOptions
) {
1298 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1299 $this->mParserOptions
->setEditSection( false );
1301 return wfSetVar( $this->mParserOptions
, $options );
1305 * Set the revision ID which will be seen by the wiki text parser
1306 * for things such as embedded {{REVISIONID}} variable use.
1308 * @param $revid Mixed: an positive integer, or null
1309 * @return Mixed: previous value
1311 public function setRevisionId( $revid ) {
1312 $val = is_null( $revid ) ?
null : intval( $revid );
1313 return wfSetVar( $this->mRevisionId
, $val );
1317 * Get the displayed revision ID
1321 public function getRevisionId() {
1322 return $this->mRevisionId
;
1326 * Set the displayed file version
1328 * @param $file File|false
1329 * @return Mixed: previous value
1331 public function setFileVersion( $file ) {
1333 if ( $file instanceof File
&& $file->exists() ) {
1334 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1336 return wfSetVar( $this->mFileVersion
, $val, true );
1340 * Get the displayed file version
1342 * @return Array|null ('time' => MW timestamp, 'sha1' => sha1)
1344 public function getFileVersion() {
1345 return $this->mFileVersion
;
1349 * Get the templates used on this page
1351 * @return Array (namespace => dbKey => revId)
1354 public function getTemplateIds() {
1355 return $this->mTemplateIds
;
1359 * Get the files used on this page
1361 * @return Array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1364 public function getFileSearchOptions() {
1365 return $this->mImageTimeKeys
;
1369 * Convert wikitext to HTML and add it to the buffer
1370 * Default assumes that the current page title will be used.
1372 * @param $text String
1373 * @param $linestart Boolean: is this the start of a line?
1374 * @param $interface Boolean: is this text in the user interface language?
1376 public function addWikiText( $text, $linestart = true, $interface = true ) {
1377 $title = $this->getTitle(); // Work arround E_STRICT
1378 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1382 * Add wikitext with a custom Title object
1384 * @param $text String: wikitext
1385 * @param $title Title object
1386 * @param $linestart Boolean: is this the start of a line?
1388 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1389 $this->addWikiTextTitle( $text, $title, $linestart );
1393 * Add wikitext with a custom Title object and tidy enabled.
1395 * @param $text String: wikitext
1396 * @param $title Title object
1397 * @param $linestart Boolean: is this the start of a line?
1399 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1400 $this->addWikiTextTitle( $text, $title, $linestart, true );
1404 * Add wikitext with tidy enabled
1406 * @param $text String: wikitext
1407 * @param $linestart Boolean: is this the start of a line?
1409 public function addWikiTextTidy( $text, $linestart = true ) {
1410 $title = $this->getTitle();
1411 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1415 * Add wikitext with a custom Title object
1417 * @param $text String: wikitext
1418 * @param $title Title object
1419 * @param $linestart Boolean: is this the start of a line?
1420 * @param $tidy Boolean: whether to use tidy
1421 * @param $interface Boolean: whether it is an interface message
1422 * (for example disables conversion)
1424 public function addWikiTextTitle( $text, &$title, $linestart, $tidy = false, $interface = false ) {
1427 wfProfileIn( __METHOD__
);
1429 wfIncrStats( 'pcache_not_possible' );
1431 $popts = $this->parserOptions();
1432 $oldTidy = $popts->setTidy( $tidy );
1433 $popts->setInterfaceMessage( (bool) $interface );
1435 $parserOutput = $wgParser->parse(
1436 $text, $title, $popts,
1437 $linestart, true, $this->mRevisionId
1440 $popts->setTidy( $oldTidy );
1442 $this->addParserOutput( $parserOutput );
1444 wfProfileOut( __METHOD__
);
1448 * Add a ParserOutput object, but without Html
1450 * @param $parserOutput ParserOutput object
1452 public function addParserOutputNoText( &$parserOutput ) {
1453 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1454 $this->addCategoryLinks( $parserOutput->getCategories() );
1455 $this->mNewSectionLink
= $parserOutput->getNewSection();
1456 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1458 $this->mParseWarnings
= $parserOutput->getWarnings();
1459 if ( !$parserOutput->isCacheable() ) {
1460 $this->enableClientCache( false );
1462 $this->mNoGallery
= $parserOutput->getNoGallery();
1463 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1464 $this->addModules( $parserOutput->getModules() );
1465 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1466 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1467 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1469 // Template versioning...
1470 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1471 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1472 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1474 $this->mTemplateIds
[$ns] = $dbks;
1477 // File versioning...
1478 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1479 $this->mImageTimeKeys
[$dbk] = $data;
1482 // Hooks registered in the object
1483 global $wgParserOutputHooks;
1484 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1485 list( $hookName, $data ) = $hookInfo;
1486 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1487 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1491 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1495 * Add a ParserOutput object
1497 * @param $parserOutput ParserOutput
1499 function addParserOutput( &$parserOutput ) {
1500 $this->addParserOutputNoText( $parserOutput );
1501 $text = $parserOutput->getText();
1502 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1503 $this->addHTML( $text );
1508 * Add the output of a QuickTemplate to the output buffer
1510 * @param $template QuickTemplate
1512 public function addTemplate( &$template ) {
1514 $template->execute();
1515 $this->addHTML( ob_get_contents() );
1520 * Parse wikitext and return the HTML.
1522 * @param $text String
1523 * @param $linestart Boolean: is this the start of a line?
1524 * @param $interface Boolean: use interface language ($wgLang instead of
1525 * $wgContLang) while parsing language sensitive magic
1526 * words like GRAMMAR and PLURAL. This also disables
1527 * LanguageConverter.
1528 * @param $language Language object: target language object, will override
1530 * @return String: HTML
1532 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1535 if( is_null( $this->getTitle() ) ) {
1536 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1539 $popts = $this->parserOptions();
1541 $popts->setInterfaceMessage( true );
1543 if ( $language !== null ) {
1544 $oldLang = $popts->setTargetLanguage( $language );
1547 $parserOutput = $wgParser->parse(
1548 $text, $this->getTitle(), $popts,
1549 $linestart, true, $this->mRevisionId
1553 $popts->setInterfaceMessage( false );
1555 if ( $language !== null ) {
1556 $popts->setTargetLanguage( $oldLang );
1559 return $parserOutput->getText();
1563 * Parse wikitext, strip paragraphs, and return the HTML.
1565 * @param $text String
1566 * @param $linestart Boolean: is this the start of a line?
1567 * @param $interface Boolean: use interface language ($wgLang instead of
1568 * $wgContLang) while parsing language sensitive magic
1569 * words like GRAMMAR and PLURAL
1570 * @return String: HTML
1572 public function parseInline( $text, $linestart = true, $interface = false ) {
1573 $parsed = $this->parse( $text, $linestart, $interface );
1576 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1584 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1586 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1588 public function setSquidMaxage( $maxage ) {
1589 $this->mSquidMaxage
= $maxage;
1593 * Use enableClientCache(false) to force it to send nocache headers
1595 * @param $state bool
1599 public function enableClientCache( $state ) {
1600 return wfSetVar( $this->mEnableClientCache
, $state );
1604 * Get the list of cookies that will influence on the cache
1608 function getCacheVaryCookies() {
1609 global $wgCookiePrefix, $wgCacheVaryCookies;
1611 if ( $cookies === null ) {
1612 $cookies = array_merge(
1614 "{$wgCookiePrefix}Token",
1615 "{$wgCookiePrefix}LoggedOut",
1620 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1626 * Return whether this page is not cacheable because "useskin" or "uselang"
1627 * URL parameters were passed.
1631 function uncacheableBecauseRequestVars() {
1632 $request = $this->getRequest();
1633 return $request->getText( 'useskin', false ) === false
1634 && $request->getText( 'uselang', false ) === false;
1638 * Check if the request has a cache-varying cookie header
1639 * If it does, it's very important that we don't allow public caching
1643 function haveCacheVaryCookies() {
1644 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1645 if ( $cookieHeader === false ) {
1648 $cvCookies = $this->getCacheVaryCookies();
1649 foreach ( $cvCookies as $cookieName ) {
1650 # Check for a simple string match, like the way squid does it
1651 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1652 wfDebug( __METHOD__
. ": found $cookieName\n" );
1656 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1661 * Add an HTTP header that will influence on the cache
1663 * @param $header String: header name
1664 * @param $option Array|null
1665 * @todo FIXME: Document the $option parameter; it appears to be for
1666 * X-Vary-Options but what format is acceptable?
1668 public function addVaryHeader( $header, $option = null ) {
1669 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1670 $this->mVaryHeader
[$header] = (array)$option;
1671 } elseif( is_array( $option ) ) {
1672 if( is_array( $this->mVaryHeader
[$header] ) ) {
1673 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
1675 $this->mVaryHeader
[$header] = $option;
1678 $this->mVaryHeader
[$header] = array_unique( (array)$this->mVaryHeader
[$header] );
1682 * Get a complete X-Vary-Options header
1686 public function getXVO() {
1687 $cvCookies = $this->getCacheVaryCookies();
1689 $cookiesOption = array();
1690 foreach ( $cvCookies as $cookieName ) {
1691 $cookiesOption[] = 'string-contains=' . $cookieName;
1693 $this->addVaryHeader( 'Cookie', $cookiesOption );
1696 foreach( $this->mVaryHeader
as $header => $option ) {
1697 $newheader = $header;
1698 if( is_array( $option ) ) {
1699 $newheader .= ';' . implode( ';', $option );
1701 $headers[] = $newheader;
1703 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1709 * bug 21672: Add Accept-Language to Vary and XVO headers
1710 * if there's no 'variant' parameter existed in GET.
1713 * /w/index.php?title=Main_page should always be served; but
1714 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1716 function addAcceptLanguage() {
1717 $lang = $this->getTitle()->getPageLanguage();
1718 if( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
1719 $variants = $lang->getVariants();
1720 $aloption = array();
1721 foreach ( $variants as $variant ) {
1722 if( $variant === $lang->getCode() ) {
1725 $aloption[] = 'string-contains=' . $variant;
1727 // IE and some other browsers use another form of language code
1728 // in their Accept-Language header, like "zh-CN" or "zh-TW".
1729 // We should handle these too.
1730 $ievariant = explode( '-', $variant );
1731 if ( count( $ievariant ) == 2 ) {
1732 $ievariant[1] = strtoupper( $ievariant[1] );
1733 $ievariant = implode( '-', $ievariant );
1734 $aloption[] = 'string-contains=' . $ievariant;
1738 $this->addVaryHeader( 'Accept-Language', $aloption );
1743 * Set a flag which will cause an X-Frame-Options header appropriate for
1744 * edit pages to be sent. The header value is controlled by
1745 * $wgEditPageFrameOptions.
1747 * This is the default for special pages. If you display a CSRF-protected
1748 * form on an ordinary view page, then you need to call this function.
1750 * @param $enable bool
1752 public function preventClickjacking( $enable = true ) {
1753 $this->mPreventClickjacking
= $enable;
1757 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1758 * This can be called from pages which do not contain any CSRF-protected
1761 public function allowClickjacking() {
1762 $this->mPreventClickjacking
= false;
1766 * Get the X-Frame-Options header value (without the name part), or false
1767 * if there isn't one. This is used by Skin to determine whether to enable
1768 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1772 public function getFrameOptions() {
1773 global $wgBreakFrames, $wgEditPageFrameOptions;
1774 if ( $wgBreakFrames ) {
1776 } elseif ( $this->mPreventClickjacking
&& $wgEditPageFrameOptions ) {
1777 return $wgEditPageFrameOptions;
1783 * Send cache control HTTP headers
1785 public function sendCacheControl() {
1786 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgUseXVO;
1788 $response = $this->getRequest()->response();
1789 if ( $wgUseETag && $this->mETag
) {
1790 $response->header( "ETag: $this->mETag" );
1793 $this->addAcceptLanguage();
1795 # don't serve compressed data to clients who can't handle it
1796 # maintain different caches for logged-in users and non-logged in ones
1797 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) ) );
1800 # Add an X-Vary-Options header for Squid with Wikimedia patches
1801 $response->header( $this->getXVO() );
1804 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
1806 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1807 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
1811 # We'll purge the proxy cache explicitly, but require end user agents
1812 # to revalidate against the proxy on each visit.
1813 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1814 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1815 # start with a shorter timeout for initial testing
1816 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1817 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
1818 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1820 # We'll purge the proxy cache for anons explicitly, but require end user agents
1821 # to revalidate against the proxy on each visit.
1822 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1823 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1824 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
1825 # start with a shorter timeout for initial testing
1826 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1827 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
1830 # We do want clients to cache if they can, but they *must* check for updates
1831 # on revisiting the page.
1832 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
1833 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1834 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1836 if($this->mLastModified
) {
1837 $response->header( "Last-Modified: {$this->mLastModified}" );
1840 wfDebug( __METHOD__
. ": no caching **\n", false );
1842 # In general, the absence of a last modified header should be enough to prevent
1843 # the client from using its cache. We send a few other things just to make sure.
1844 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1845 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1846 $response->header( 'Pragma: no-cache' );
1851 * Get the message associed with the HTTP response code $code
1853 * @param $code Integer: status code
1854 * @return String or null: message or null if $code is not in the list of
1857 * @deprecated since 1.18 Use HttpStatus::getMessage() instead.
1859 public static function getStatusMessage( $code ) {
1860 wfDeprecated( __METHOD__
);
1861 return HttpStatus
::getMessage( $code );
1865 * Finally, all the text has been munged and accumulated into
1866 * the object, let's actually output it:
1868 public function output() {
1869 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType, $wgVaryOnXFP;
1871 if( $this->mDoNothing
) {
1875 wfProfileIn( __METHOD__
);
1877 $response = $this->getRequest()->response();
1879 if ( $this->mRedirect
!= '' ) {
1880 # Standards require redirect URLs to be absolute
1881 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
1882 if( $this->mRedirectCode
== '301' ||
$this->mRedirectCode
== '303' ) {
1883 if( !$wgDebugRedirects ) {
1884 $message = HttpStatus
::getMessage( $this->mRedirectCode
);
1885 $response->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
1887 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1889 if ( $wgVaryOnXFP ) {
1890 $this->addVaryHeader( 'X-Forwarded-Proto' );
1892 $this->sendCacheControl();
1894 $response->header( "Content-Type: text/html; charset=utf-8" );
1895 if( $wgDebugRedirects ) {
1896 $url = htmlspecialchars( $this->mRedirect
);
1897 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1898 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1899 print "</body>\n</html>\n";
1901 $response->header( 'Location: ' . $this->mRedirect
);
1903 wfProfileOut( __METHOD__
);
1905 } elseif ( $this->mStatusCode
) {
1906 $message = HttpStatus
::getMessage( $this->mStatusCode
);
1908 $response->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
1912 # Buffer output; final headers may depend on later processing
1915 $response->header( "Content-type: $wgMimeType; charset=UTF-8" );
1916 $response->header( 'Content-language: ' . $wgLanguageCode );
1918 // Prevent framing, if requested
1919 $frameOptions = $this->getFrameOptions();
1920 if ( $frameOptions ) {
1921 $response->header( "X-Frame-Options: $frameOptions" );
1924 if ( $this->mArticleBodyOnly
) {
1925 $this->out( $this->mBodytext
);
1927 $this->addDefaultModules();
1929 $sk = $this->getSkin();
1931 // Hook that allows last minute changes to the output page, e.g.
1932 // adding of CSS or Javascript by extensions.
1933 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1935 wfProfileIn( 'Output-skin' );
1937 wfProfileOut( 'Output-skin' );
1940 $this->sendCacheControl();
1942 wfProfileOut( __METHOD__
);
1946 * Actually output something with print().
1948 * @param $ins String: the string to output
1950 public function out( $ins ) {
1955 * Produce a "user is blocked" page.
1956 * @deprecated since 1.18
1958 function blockedPage() {
1959 throw new UserBlockedError( $this->getUser()->mBlock
);
1963 * Prepare this object to display an error page; disable caching and
1964 * indexing, clear the current text and redirect, set the page's title
1965 * and optionally an custom HTML title (content of the <title> tag).
1967 * @param $pageTitle String|Message will be passed directly to setPageTitle()
1968 * @param $htmlTitle String|Message will be passed directly to setHTMLTitle();
1969 * optional, if not passed the <title> attribute will be
1970 * based on $pageTitle
1972 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
1973 if ( $this->getTitle() ) {
1974 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1977 $this->setPageTitle( $pageTitle );
1978 if ( $htmlTitle !== false ) {
1979 $this->setHTMLTitle( $htmlTitle );
1981 $this->setRobotPolicy( 'noindex,nofollow' );
1982 $this->setArticleRelated( false );
1983 $this->enableClientCache( false );
1984 $this->mRedirect
= '';
1985 $this->clearSubtitle();
1990 * Output a standard error page
1992 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
1993 * showErrorPage( 'titlemsg', $messageObject );
1995 * @param $title String: message key for page title
1996 * @param $msg Mixed: message key (string) for page text, or a Message object
1997 * @param $params Array: message parameters; ignored if $msg is a Message object
1999 public function showErrorPage( $title, $msg, $params = array() ) {
2000 $this->prepareErrorPage( $this->msg( $title ), $this->msg( 'errorpagetitle' ) );
2002 if ( $msg instanceof Message
){
2003 $this->addHTML( $msg->parse() );
2005 $this->addWikiMsgArray( $msg, $params );
2008 $this->returnToMain();
2012 * Output a standard permission error page
2014 * @param $errors Array: error message keys
2015 * @param $action String: action that was denied or null if unknown
2017 public function showPermissionsErrorPage( $errors, $action = null ) {
2018 global $wgGroupPermissions;
2020 // For some action (read, edit, create and upload), display a "login to do this action"
2021 // error if all of the following conditions are met:
2022 // 1. the user is not logged in
2023 // 2. the only error is insufficient permissions (i.e. no block or something else)
2024 // 3. the error can be avoided simply by logging in
2025 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2026 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2027 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2028 && ( ( isset( $wgGroupPermissions['user'][$action] ) && $wgGroupPermissions['user'][$action] )
2029 ||
( isset( $wgGroupPermissions['autoconfirmed'][$action] ) && $wgGroupPermissions['autoconfirmed'][$action] ) )
2031 $displayReturnto = null;
2032 $returnto = $this->getTitle();
2033 if ( $action == 'edit' ) {
2034 $msg = 'whitelistedittext';
2035 $displayReturnto = $returnto;
2036 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2037 $msg = 'nocreatetext';
2038 } elseif ( $action == 'upload' ) {
2039 $msg = 'uploadnologintext';
2041 $msg = 'loginreqpagetext';
2042 $displayReturnto = Title
::newMainPage();
2047 $query['returnto'] = $returnto->getPrefixedText();
2048 $request = $this->getRequest();
2049 if ( !$request->wasPosted() ) {
2050 $returntoquery = $request->getValues();
2051 unset( $returntoquery['title'] );
2052 unset( $returntoquery['returnto'] );
2053 unset( $returntoquery['returntoquery'] );
2054 $query['returntoquery'] = wfArrayToCGI( $returntoquery );
2057 $loginLink = Linker
::linkKnown(
2058 SpecialPage
::getTitleFor( 'Userlogin' ),
2059 $this->msg( 'loginreqlink' )->escaped(),
2064 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2065 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2067 # Don't return to a page the user can't read otherwise
2068 # we'll end up in a pointless loop
2069 if ( $displayReturnto && $displayReturnto->userCanRead() ) {
2070 $this->returnToMain( null, $displayReturnto );
2073 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2074 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2079 * Display an error page indicating that a given version of MediaWiki is
2080 * required to use it
2082 * @param $version Mixed: the version of MediaWiki needed to use the page
2084 public function versionRequired( $version ) {
2085 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2087 $this->addWikiMsg( 'versionrequiredtext', $version );
2088 $this->returnToMain();
2092 * Display an error page noting that a given permission bit is required.
2093 * @deprecated since 1.18, just throw the exception directly
2094 * @param $permission String: key required
2096 public function permissionRequired( $permission ) {
2097 throw new PermissionsError( $permission );
2101 * Produce the stock "please login to use the wiki" page
2103 * @deprecated in 1.19; throw the exception directly
2105 public function loginToUse() {
2106 throw new PermissionsError( 'read' );
2110 * Format a list of error messages
2112 * @param $errors Array of arrays returned by Title::getUserPermissionsErrors
2113 * @param $action String: action that was denied or null if unknown
2114 * @return String: the wikitext error-messages, formatted into a list.
2116 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2117 if ( $action == null ) {
2118 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2120 $action_desc = $this->msg( "action-$action" )->plain();
2122 'permissionserrorstext-withaction',
2125 )->plain() . "\n\n";
2128 if ( count( $errors ) > 1 ) {
2129 $text .= '<ul class="permissions-errors">' . "\n";
2131 foreach( $errors as $error ) {
2133 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2138 $text .= "<div class=\"permissions-errors\">\n" .
2139 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2147 * Display a page stating that the Wiki is in read-only mode,
2148 * and optionally show the source of the page that the user
2149 * was trying to edit. Should only be called (for this
2150 * purpose) after wfReadOnly() has returned true.
2152 * For historical reasons, this function is _also_ used to
2153 * show the error message when a user tries to edit a page
2154 * they are not allowed to edit. (Unless it's because they're
2155 * blocked, then we show blockedPage() instead.) In this
2156 * case, the second parameter should be set to true and a list
2157 * of reasons supplied as the third parameter.
2159 * @todo Needs to be split into multiple functions.
2161 * @param $source String: source code to show (or null).
2162 * @param $protected Boolean: is this a permissions error?
2163 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
2164 * @param $action String: action that was denied or null if unknown
2166 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
2167 $this->setRobotPolicy( 'noindex,nofollow' );
2168 $this->setArticleRelated( false );
2170 // If no reason is given, just supply a default "I can't let you do
2171 // that, Dave" message. Should only occur if called by legacy code.
2172 if ( $protected && empty( $reasons ) ) {
2173 $reasons[] = array( 'badaccess-group0' );
2176 if ( !empty( $reasons ) ) {
2177 // Permissions error
2179 $this->setPageTitle( $this->msg( 'viewsource-title', $this->getTitle()->getPrefixedText() ) );
2180 $this->addBacklinkSubtitle( $this->getTitle() );
2182 $this->setPageTitle( $this->msg( 'badaccess' ) );
2184 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2186 // Wiki is read only
2187 throw new ReadOnlyError
;
2190 // Show source, if supplied
2191 if( is_string( $source ) ) {
2192 $this->addWikiMsg( 'viewsourcetext' );
2194 $pageLang = $this->getTitle()->getPageLanguage();
2196 'id' => 'wpTextbox1',
2197 'name' => 'wpTextbox1',
2198 'cols' => $this->getUser()->getOption( 'cols' ),
2199 'rows' => $this->getUser()->getOption( 'rows' ),
2200 'readonly' => 'readonly',
2201 'lang' => $pageLang->getCode(),
2202 'dir' => $pageLang->getDir(),
2204 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
2206 // Show templates used by this article
2207 $article = new Article( $this->getTitle() );
2208 $templates = Linker
::formatTemplates( $article->getUsedTemplates() );
2209 $this->addHTML( "<div class='templatesUsed'>
2215 # If the title doesn't exist, it's fairly pointless to print a return
2216 # link to it. After all, you just tried editing it and couldn't, so
2217 # what's there to do there?
2218 if( $this->getTitle()->exists() ) {
2219 $this->returnToMain( null, $this->getTitle() );
2224 * Turn off regular page output and return an error reponse
2225 * for when rate limiting has triggered.
2227 public function rateLimited() {
2228 throw new ThrottledError
;
2232 * Show a warning about slave lag
2234 * If the lag is higher than $wgSlaveLagCritical seconds,
2235 * then the warning is a bit more obvious. If the lag is
2236 * lower than $wgSlaveLagWarning, then no warning is shown.
2238 * @param $lag Integer: slave lag
2240 public function showLagWarning( $lag ) {
2241 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2242 if( $lag >= $wgSlaveLagWarning ) {
2243 $message = $lag < $wgSlaveLagCritical
2246 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2247 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLang()->formatNum( $lag ) ) );
2251 public function showFatalError( $message ) {
2252 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2254 $this->addHTML( $message );
2257 public function showUnexpectedValueError( $name, $val ) {
2258 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2261 public function showFileCopyError( $old, $new ) {
2262 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2265 public function showFileRenameError( $old, $new ) {
2266 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2269 public function showFileDeleteError( $name ) {
2270 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2273 public function showFileNotFoundError( $name ) {
2274 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2278 * Add a "return to" link pointing to a specified title
2280 * @param $title Title to link
2281 * @param $query String query string
2282 * @param $text String text of the link (input is not escaped)
2284 public function addReturnTo( $title, $query = array(), $text = null ) {
2285 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL() ) );
2286 $link = $this->msg( 'returnto' )->rawParams(
2287 Linker
::link( $title, $text, array(), $query ) )->escaped();
2288 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2292 * Add a "return to" link pointing to a specified title,
2293 * or the title indicated in the request, or else the main page
2295 * @param $unused No longer used
2296 * @param $returnto Title or String to return to
2297 * @param $returntoquery String: query string for the return to link
2299 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2300 if ( $returnto == null ) {
2301 $returnto = $this->getRequest()->getText( 'returnto' );
2304 if ( $returntoquery == null ) {
2305 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2308 if ( $returnto === '' ) {
2309 $returnto = Title
::newMainPage();
2312 if ( is_object( $returnto ) ) {
2313 $titleObj = $returnto;
2315 $titleObj = Title
::newFromText( $returnto );
2317 if ( !is_object( $titleObj ) ) {
2318 $titleObj = Title
::newMainPage();
2321 $this->addReturnTo( $titleObj, $returntoquery );
2325 * @param $sk Skin The given Skin
2326 * @param $includeStyle Boolean: unused
2327 * @return String: The doctype, opening <html>, and head element.
2329 public function headElement( Skin
$sk, $includeStyle = true ) {
2330 global $wgContLang, $wgUseTrackbacks;
2331 $userdir = $this->getLang()->getDir();
2332 $sitedir = $wgContLang->getDir();
2334 if ( $sk->commonPrintStylesheet() ) {
2335 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2338 $ret = Html
::htmlHeader( array( 'lang' => $this->getLang()->getCode(), 'dir' => $userdir, 'class' => 'client-nojs' ) );
2340 if ( $this->getHTMLTitle() == '' ) {
2341 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() ) );
2344 $openHead = Html
::openElement( 'head' );
2346 # Don't bother with the newline if $head == ''
2347 $ret .= "$openHead\n";
2350 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2352 $ret .= implode( "\n", array(
2353 $this->getHeadLinks( null, true ),
2354 $this->buildCssLinks(),
2355 $this->getHeadScripts(),
2356 $this->getHeadItems()
2359 if ( $wgUseTrackbacks && $this->isArticleRelated() ) {
2360 $ret .= $this->getTitle()->trackbackRDF();
2363 $closeHead = Html
::closeElement( 'head' );
2365 $ret .= "$closeHead\n";
2368 $bodyAttrs = array();
2370 # Classes for LTR/RTL directionality support
2371 $bodyAttrs['class'] = "mediawiki $userdir sitedir-$sitedir";
2373 if ( $this->getLang()->capitalizeAllNouns() ) {
2374 # A <body> class is probably not the best way to do this . . .
2375 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2377 $bodyAttrs['class'] .= ' ' . $sk->getPageClasses( $this->getTitle() );
2378 $bodyAttrs['class'] .= ' skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2380 $sk->addToBodyAttributes( $this, $bodyAttrs ); // Allow skins to add body attributes they need
2381 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2383 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2389 * Add the default ResourceLoader modules to this object
2391 private function addDefaultModules() {
2392 global $wgIncludeLegacyJavaScript, $wgUseAjax, $wgAjaxWatch, $wgEnableMWSuggest;
2394 // Add base resources
2395 $this->addModules( array(
2398 'mediawiki.page.startup',
2399 'mediawiki.page.ready',
2401 if ( $wgIncludeLegacyJavaScript ){
2402 $this->addModules( 'mediawiki.legacy.wikibits' );
2405 // Add various resources if required
2407 $this->addModules( 'mediawiki.legacy.ajax' );
2409 wfRunHooks( 'AjaxAddScript', array( &$this ) );
2411 if( $wgAjaxWatch && $this->getUser()->isLoggedIn() ) {
2412 $this->addModules( 'mediawiki.action.watch.ajax' );
2415 if ( $wgEnableMWSuggest && !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2416 $this->addModules( 'mediawiki.legacy.mwsuggest' );
2420 if ( $this->getUser()->getBoolOption( 'editsectiononrightclick' ) ) {
2421 $this->addModules( 'mediawiki.action.view.rightClickEdit' );
2424 # Crazy edit-on-double-click stuff
2425 if ( $this->isArticle() && $this->getUser()->getOption( 'editondblclick' ) ) {
2426 $this->addModules( 'mediawiki.action.view.dblClickEdit' );
2431 * Get a ResourceLoader object associated with this OutputPage
2433 * @return ResourceLoader
2435 public function getResourceLoader() {
2436 if ( is_null( $this->mResourceLoader
) ) {
2437 $this->mResourceLoader
= new ResourceLoader();
2439 return $this->mResourceLoader
;
2444 * @param $modules Array/string with the module name(s)
2445 * @param $only String ResourceLoaderModule TYPE_ class constant
2446 * @param $useESI boolean
2447 * @param $extraQuery Array with extra query parameters to add to each request. array( param => value )
2448 * @return string html <script> and <style> tags
2450 protected function makeResourceLoaderLink( $modules, $only, $useESI = false, array $extraQuery = array() ) {
2451 global $wgResourceLoaderUseESI, $wgResourceLoaderInlinePrivateModules;
2453 if ( !count( $modules ) ) {
2457 if ( count( $modules ) > 1 ) {
2458 // Remove duplicate module requests
2459 $modules = array_unique( (array) $modules );
2460 // Sort module names so requests are more uniform
2463 if ( ResourceLoader
::inDebugMode() ) {
2464 // Recursively call us for every item
2466 foreach ( $modules as $name ) {
2467 $links .= $this->makeResourceLoaderLink( $name, $only, $useESI );
2473 // Create keyed-by-group list of module objects from modules list
2475 $resourceLoader = $this->getResourceLoader();
2476 foreach ( (array) $modules as $name ) {
2477 $module = $resourceLoader->getModule( $name );
2478 # Check that we're allowed to include this module on this page
2479 if ( ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2480 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2481 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2482 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2488 $group = $module->getGroup();
2489 if ( !isset( $groups[$group] ) ) {
2490 $groups[$group] = array();
2492 $groups[$group][$name] = $module;
2496 foreach ( $groups as $group => $modules ) {
2497 // Special handling for user-specific groups
2499 if ( ( $group === 'user' ||
$group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2500 $user = $this->getUser()->getName();
2503 // Create a fake request based on the one we are about to make so modules return
2504 // correct timestamp and emptiness data
2505 $query = ResourceLoader
::makeLoaderQuery(
2506 array(), // modules; not determined yet
2507 $this->getLang()->getCode(),
2508 $this->getSkin()->getSkinName(),
2510 null, // version; not determined yet
2511 ResourceLoader
::inDebugMode(),
2512 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2513 $this->isPrintable(),
2514 $this->getRequest()->getBool( 'handheld' ),
2517 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2518 // Drop modules that know they're empty
2519 foreach ( $modules as $key => $module ) {
2520 if ( $module->isKnownEmpty( $context ) ) {
2521 unset( $modules[$key] );
2524 // If there are no modules left, skip this group
2525 if ( $modules === array() ) {
2529 // Support inlining of private modules if configured as such
2530 if ( $group === 'private' && $wgResourceLoaderInlinePrivateModules ) {
2531 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2532 $links .= Html
::inlineStyle(
2533 $resourceLoader->makeModuleResponse( $context, $modules )
2536 $links .= Html
::inlineScript(
2537 ResourceLoader
::makeLoaderConditionalScript(
2538 $resourceLoader->makeModuleResponse( $context, $modules )
2545 // Special handling for the user group; because users might change their stuff
2546 // on-wiki like user pages, or user preferences; we need to find the highest
2547 // timestamp of these user-changable modules so we can ensure cache misses on change
2548 // This should NOT be done for the site group (bug 27564) because anons get that too
2549 // and we shouldn't be putting timestamps in Squid-cached HTML
2551 if ( $group === 'user' ) {
2552 // Get the maximum timestamp
2554 foreach ( $modules as $module ) {
2555 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2557 // Add a version parameter so cache will break when things change
2558 $version = wfTimestamp( TS_ISO_8601_BASIC
, $timestamp );
2561 $url = ResourceLoader
::makeLoaderURL(
2562 array_keys( $modules ),
2563 $this->getLang()->getCode(),
2564 $this->getSkin()->getSkinName(),
2567 ResourceLoader
::inDebugMode(),
2568 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2569 $this->isPrintable(),
2570 $this->getRequest()->getBool( 'handheld' ),
2573 if ( $useESI && $wgResourceLoaderUseESI ) {
2574 $esi = Xml
::element( 'esi:include', array( 'src' => $url ) );
2575 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2576 $link = Html
::inlineStyle( $esi );
2578 $link = Html
::inlineScript( $esi );
2581 // Automatically select style/script elements
2582 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2583 $link = Html
::linkedStyle( $url );
2585 $link = Html
::linkedScript( $url );
2589 if( $group == 'noscript' ){
2590 $links .= Html
::rawElement( 'noscript', array(), $link ) . "\n";
2592 $links .= $link . "\n";
2599 * JS stuff to put in the <head>. This is the startup module, config
2600 * vars and modules marked with position 'top'
2602 * @return String: HTML fragment
2604 function getHeadScripts() {
2605 // Startup - this will immediately load jquery and mediawiki modules
2606 $scripts = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
, true );
2608 // Load config before anything else
2609 $scripts .= Html
::inlineScript(
2610 ResourceLoader
::makeLoaderConditionalScript(
2611 ResourceLoader
::makeConfigSetScript( $this->getJSVars() )
2615 // Script and Messages "only" requests marked for top inclusion
2616 // Messages should go first
2617 $scripts .= $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'top' ), ResourceLoaderModule
::TYPE_MESSAGES
);
2618 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'top' ), ResourceLoaderModule
::TYPE_SCRIPTS
);
2620 // Modules requests - let the client calculate dependencies and batch requests as it likes
2621 // Only load modules that have marked themselves for loading at the top
2622 $modules = $this->getModules( true, 'top' );
2624 $scripts .= Html
::inlineScript(
2625 ResourceLoader
::makeLoaderConditionalScript(
2626 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
2635 * JS stuff to put at the bottom of the <body>: modules marked with position 'bottom',
2636 * legacy scripts ($this->mScripts), user preferences, site JS and user JS
2640 function getBottomScripts() {
2641 global $wgUseSiteJs, $wgAllowUserJs;
2643 // Script and Messages "only" requests marked for bottom inclusion
2644 // Messages should go first
2645 $scripts = $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'bottom' ), ResourceLoaderModule
::TYPE_MESSAGES
);
2646 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ), ResourceLoaderModule
::TYPE_SCRIPTS
);
2648 // Modules requests - let the client calculate dependencies and batch requests as it likes
2649 // Only load modules that have marked themselves for loading at the bottom
2650 $modules = $this->getModules( true, 'bottom' );
2652 $scripts .= Html
::inlineScript(
2653 ResourceLoader
::makeLoaderConditionalScript(
2654 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
2660 $scripts .= "\n" . $this->mScripts
;
2662 $userScripts = array( 'user.options', 'user.tokens' );
2664 // Add site JS if enabled
2665 if ( $wgUseSiteJs ) {
2666 $scripts .= $this->makeResourceLoaderLink( 'site', ResourceLoaderModule
::TYPE_SCRIPTS
);
2667 if( $this->getUser()->isLoggedIn() ){
2668 $userScripts[] = 'user.groups';
2672 // Add user JS if enabled
2673 if ( $wgAllowUserJs && $this->getUser()->isLoggedIn() ) {
2674 if( $this->getTitle() && $this->getTitle()->isJsSubpage() && $this->userCanPreview() ) {
2675 # XXX: additional security check/prompt?
2676 // We're on a preview of a JS subpage
2677 // Exclude this page from the user module in case it's in there (bug 26283)
2678 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
, false,
2679 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
2681 // Load the previewed JS
2682 $scripts .= Html
::inlineScript( "\n" . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2684 // Include the user module normally
2685 // We can't do $userScripts[] = 'user'; because the user module would end up
2686 // being wrapped in a closure, so load it raw like 'site'
2687 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
);
2690 $scripts .= $this->makeResourceLoaderLink( $userScripts, ResourceLoaderModule
::TYPE_COMBINED
);
2696 * Add one or more variables to be set in mw.config in JavaScript.
2698 * @param $key {String|Array} Key or array of key/value pars.
2699 * @param $value {Mixed} Value of the configuration variable.
2701 public function addJsConfigVars( $keys, $value ) {
2702 if ( is_array( $keys ) ) {
2703 foreach ( $keys as $key => $value ) {
2704 $this->mJsConfigVars
[$key] = $value;
2709 $this->mJsConfigVars
[$keys] = $value;
2714 * Get an array containing the variables to be set in mw.config in JavaScript.
2716 * Do not add things here which can be evaluated in ResourceLoaderStartupScript
2717 * - in other words, page-independent/site-wide variables (without state).
2718 * You will only be adding bloat to the html page and causing page caches to
2719 * have to be purged on configuration changes.
2721 protected function getJSVars() {
2722 global $wgUseAjax, $wgEnableMWSuggest;
2724 $title = $this->getTitle();
2725 $ns = $title->getNamespace();
2726 $nsname = MWNamespace
::exists( $ns ) ? MWNamespace
::getCanonicalName( $ns ) : $title->getNsText();
2727 if ( $ns == NS_SPECIAL
) {
2728 list( $canonicalName, /*...*/ ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
2730 $canonicalName = false; # bug 21115
2734 'wgCanonicalNamespace' => $nsname,
2735 'wgCanonicalSpecialPageName' => $canonicalName,
2736 'wgNamespaceNumber' => $title->getNamespace(),
2737 'wgPageName' => $title->getPrefixedDBKey(),
2738 'wgTitle' => $title->getText(),
2739 'wgCurRevisionId' => $title->getLatestRevID(),
2740 'wgArticleId' => $title->getArticleId(),
2741 'wgIsArticle' => $this->isArticle(),
2742 'wgAction' => $this->getRequest()->getText( 'action', 'view' ),
2743 'wgUserName' => $this->getUser()->isAnon() ?
null : $this->getUser()->getName(),
2744 'wgUserGroups' => $this->getUser()->getEffectiveGroups(),
2745 'wgCategories' => $this->getCategories(),
2746 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
2748 $lang = $this->getTitle()->getPageLanguage();
2749 if ( $lang->hasVariants() ) {
2750 $vars['wgUserVariant'] = $lang->getPreferredVariant();
2752 foreach ( $title->getRestrictionTypes() as $type ) {
2753 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
2755 if ( $wgUseAjax && $wgEnableMWSuggest && !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2756 $vars['wgSearchNamespaces'] = SearchEngine
::userNamespaces( $this->getUser() );
2758 if ( $title->isMainPage() ) {
2759 $vars['wgIsMainPage'] = true;
2762 // Allow extensions to add their custom variables to the mw.config map.
2763 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
2764 // page-dependant but site-wide (without state).
2765 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
2766 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
2768 // Merge in variables from addJsConfigVars last
2769 return array_merge( $vars, $this->mJsConfigVars
);
2773 * To make it harder for someone to slip a user a fake
2774 * user-JavaScript or user-CSS preview, a random token
2775 * is associated with the login session. If it's not
2776 * passed back with the preview request, we won't render
2781 public function userCanPreview() {
2782 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
2783 ||
!$this->getRequest()->wasPosted()
2784 ||
!$this->getUser()->matchEditToken(
2785 $this->getRequest()->getVal( 'wpEditToken' ) )
2789 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
2793 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
2797 * @param $unused Unused
2798 * @param $addContentType bool
2800 * @return string HTML tag links to be put in the header.
2802 public function getHeadLinks( $unused = null, $addContentType = false ) {
2803 global $wgUniversalEditButton, $wgFavicon, $wgAppleTouchIcon, $wgEnableAPI,
2804 $wgSitename, $wgVersion, $wgHtml5, $wgMimeType,
2805 $wgFeed, $wgOverrideSiteFeed, $wgAdvertisedFeedTypes,
2806 $wgDisableLangConversion, $wgCanonicalLanguageLinks,
2807 $wgRightsPage, $wgRightsUrl;
2811 if ( $addContentType ) {
2813 # More succinct than <meta http-equiv=Content-Type>, has the
2815 $tags[] = Html
::element( 'meta', array( 'charset' => 'UTF-8' ) );
2817 $tags[] = Html
::element( 'meta', array(
2818 'http-equiv' => 'Content-Type',
2819 'content' => "$wgMimeType; charset=UTF-8"
2821 $tags[] = Html
::element( 'meta', array( // bug 15835
2822 'http-equiv' => 'Content-Style-Type',
2823 'content' => 'text/css'
2828 $tags[] = Html
::element( 'meta', array(
2829 'name' => 'generator',
2830 'content' => "MediaWiki $wgVersion",
2833 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
2834 if( $p !== 'index,follow' ) {
2835 // http://www.robotstxt.org/wc/meta-user.html
2836 // Only show if it's different from the default robots policy
2837 $tags[] = Html
::element( 'meta', array(
2843 if ( count( $this->mKeywords
) > 0 ) {
2845 "/<.*?" . ">/" => '',
2848 $tags[] = Html
::element( 'meta', array(
2849 'name' => 'keywords',
2850 'content' => preg_replace(
2851 array_keys( $strip ),
2852 array_values( $strip ),
2853 implode( ',', $this->mKeywords
)
2858 foreach ( $this->mMetatags
as $tag ) {
2859 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
2861 $tag[0] = substr( $tag[0], 5 );
2865 $tags[] = Html
::element( 'meta',
2868 'content' => $tag[1]
2873 foreach ( $this->mLinktags
as $tag ) {
2874 $tags[] = Html
::element( 'link', $tag );
2877 # Universal edit button
2878 if ( $wgUniversalEditButton && $this->isArticleRelated() ) {
2879 $user = $this->getUser();
2880 if ( $this->getTitle()->quickUserCan( 'edit', $user )
2881 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create', $user ) ) ) {
2882 // Original UniversalEditButton
2883 $msg = $this->msg( 'edit' )->text();
2884 $tags[] = Html
::element( 'link', array(
2885 'rel' => 'alternate',
2886 'type' => 'application/x-wiki',
2888 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
2890 // Alternate edit link
2891 $tags[] = Html
::element( 'link', array(
2894 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
2899 # Generally the order of the favicon and apple-touch-icon links
2900 # should not matter, but Konqueror (3.5.9 at least) incorrectly
2901 # uses whichever one appears later in the HTML source. Make sure
2902 # apple-touch-icon is specified first to avoid this.
2903 if ( $wgAppleTouchIcon !== false ) {
2904 $tags[] = Html
::element( 'link', array( 'rel' => 'apple-touch-icon', 'href' => $wgAppleTouchIcon ) );
2907 if ( $wgFavicon !== false ) {
2908 $tags[] = Html
::element( 'link', array( 'rel' => 'shortcut icon', 'href' => $wgFavicon ) );
2911 # OpenSearch description link
2912 $tags[] = Html
::element( 'link', array(
2914 'type' => 'application/opensearchdescription+xml',
2915 'href' => wfScript( 'opensearch_desc' ),
2916 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
2919 if ( $wgEnableAPI ) {
2920 # Real Simple Discovery link, provides auto-discovery information
2921 # for the MediaWiki API (and potentially additional custom API
2922 # support such as WordPress or Twitter-compatible APIs for a
2923 # blogging extension, etc)
2924 $tags[] = Html
::element( 'link', array(
2926 'type' => 'application/rsd+xml',
2927 // Output a protocol-relative URL here if $wgServer is protocol-relative
2928 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
2929 'href' => wfExpandUrl( wfAppendQuery( wfScript( 'api' ), array( 'action' => 'rsd' ) ), PROTO_RELATIVE
),
2935 if ( !$wgDisableLangConversion && $wgCanonicalLanguageLinks ) {
2936 $lang = $this->getTitle()->getPageLanguage();
2937 if ( $lang->hasVariants() ) {
2939 $urlvar = $lang->getURLVariant();
2942 $variants = $lang->getVariants();
2943 foreach ( $variants as $_v ) {
2944 $tags[] = Html
::element( 'link', array(
2945 'rel' => 'alternate',
2947 'href' => $this->getTitle()->getLocalURL( '', $_v ) )
2951 $tags[] = Html
::element( 'link', array(
2952 'rel' => 'canonical',
2953 'href' => $this->getTitle()->getCanonicalUrl()
2961 if ( $wgRightsPage ) {
2962 $copy = Title
::newFromText( $wgRightsPage );
2965 $copyright = $copy->getLocalURL();
2969 if ( !$copyright && $wgRightsUrl ) {
2970 $copyright = $wgRightsUrl;
2974 $tags[] = Html
::element( 'link', array(
2975 'rel' => 'copyright',
2976 'href' => $copyright )
2982 foreach( $this->getSyndicationLinks() as $format => $link ) {
2983 # Use the page name for the title. In principle, this could
2984 # lead to issues with having the same name for different feeds
2985 # corresponding to the same page, but we can't avoid that at
2988 $tags[] = $this->feedLink(
2991 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
2992 $this->msg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )->text()
2996 # Recent changes feed should appear on every page (except recentchanges,
2997 # that would be redundant). Put it after the per-page feed to avoid
2998 # changing existing behavior. It's still available, probably via a
2999 # menu in your browser. Some sites might have a different feed they'd
3000 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3001 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3002 # If so, use it instead.
3003 if ( $wgOverrideSiteFeed ) {
3004 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
3005 // Note, this->feedLink escapes the url.
3006 $tags[] = $this->feedLink(
3009 $this->msg( "site-{$type}-feed", $wgSitename )->text()
3012 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3013 foreach ( $wgAdvertisedFeedTypes as $format ) {
3014 $tags[] = $this->feedLink(
3016 $this->getTitle()->getLocalURL( "feed={$format}" ),
3017 $this->msg( "site-{$format}-feed", $wgSitename )->text() # For grep: 'site-rss-feed', 'site-atom-feed'.
3022 return implode( "\n", $tags );
3026 * Generate a <link rel/> for a feed.
3028 * @param $type String: feed type
3029 * @param $url String: URL to the feed
3030 * @param $text String: value of the "title" attribute
3031 * @return String: HTML fragment
3033 private function feedLink( $type, $url, $text ) {
3034 return Html
::element( 'link', array(
3035 'rel' => 'alternate',
3036 'type' => "application/$type+xml",
3043 * Add a local or specified stylesheet, with the given media options.
3044 * Meant primarily for internal use...
3046 * @param $style String: URL to the file
3047 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
3048 * @param $condition String: for IE conditional comments, specifying an IE version
3049 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
3051 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3053 // Even though we expect the media type to be lowercase, but here we
3054 // force it to lowercase to be safe.
3056 $options['media'] = $media;
3059 $options['condition'] = $condition;
3062 $options['dir'] = $dir;
3064 $this->styles
[$style] = $options;
3068 * Adds inline CSS styles
3069 * @param $style_css Mixed: inline CSS
3070 * @param $flip String: Set to 'flip' to flip the CSS if needed
3072 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3073 if( $flip === 'flip' && $this->getLang()->isRTL() ) {
3074 # If wanted, and the interface is right-to-left, flip the CSS
3075 $style_css = CSSJanus
::transform( $style_css, true, false );
3077 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3081 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
3082 * These will be applied to various media & IE conditionals.
3086 public function buildCssLinks() {
3087 global $wgUseSiteCss, $wgAllowUserCss, $wgAllowUserCssPrefs;
3089 $this->getSkin()->setupSkinUserCss( $this );
3091 // Add ResourceLoader styles
3092 // Split the styles into four groups
3093 $styles = array( 'other' => array(), 'user' => array(), 'site' => array(), 'private' => array(), 'noscript' => array() );
3094 $otherTags = ''; // Tags to append after the normal <link> tags
3095 $resourceLoader = $this->getResourceLoader();
3097 $moduleStyles = $this->getModuleStyles();
3099 // Per-site custom styles
3100 if ( $wgUseSiteCss ) {
3101 $moduleStyles[] = 'site';
3102 $moduleStyles[] = 'noscript';
3103 if( $this->getUser()->isLoggedIn() ){
3104 $moduleStyles[] = 'user.groups';
3108 // Per-user custom styles
3109 if ( $wgAllowUserCss ) {
3110 if ( $this->getTitle()->isCssSubpage() && $this->userCanPreview() ) {
3111 // We're on a preview of a CSS subpage
3112 // Exclude this page from the user module in case it's in there (bug 26283)
3113 $otherTags .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_STYLES
, false,
3114 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3116 // Load the previewed CSS
3117 $otherTags .= Html
::inlineStyle( $this->getRequest()->getText( 'wpTextbox1' ) );
3119 // Load the user styles normally
3120 $moduleStyles[] = 'user';
3124 // Per-user preference styles
3125 if ( $wgAllowUserCssPrefs ) {
3126 $moduleStyles[] = 'user.options';
3129 foreach ( $moduleStyles as $name ) {
3130 $group = $resourceLoader->getModule( $name )->getGroup();
3131 // Modules in groups named "other" or anything different than "user", "site" or "private"
3132 // will be placed in the "other" group
3133 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
3136 // We want site, private and user styles to override dynamically added styles from modules, but we want
3137 // dynamically added styles to override statically added styles from other modules. So the order
3138 // has to be other, dynamic, site, private, user
3139 // Add statically added styles for other modules
3140 $ret = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule
::TYPE_STYLES
);
3141 // Add normal styles added through addStyle()/addInlineStyle() here
3142 $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3143 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3144 // We use a <meta> tag with a made-up name for this because that's valid HTML
3145 $ret .= Html
::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) ) . "\n";
3147 // Add site, private and user styles
3148 // 'private' at present only contains user.options, so put that before 'user'
3149 // Any future private modules will likely have a similar user-specific character
3150 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3151 $ret .= $this->makeResourceLoaderLink( $styles[$group],
3152 ResourceLoaderModule
::TYPE_STYLES
3156 // Add stuff in $otherTags (previewed user CSS if applicable)
3164 public function buildCssLinksArray() {
3167 // Add any extension CSS
3168 foreach ( $this->mExtStyles
as $url ) {
3169 $this->addStyle( $url );
3171 $this->mExtStyles
= array();
3173 foreach( $this->styles
as $file => $options ) {
3174 $link = $this->styleLink( $file, $options );
3176 $links[$file] = $link;
3183 * Generate \<link\> tags for stylesheets
3185 * @param $style String: URL to the file
3186 * @param $options Array: option, can contain 'condition', 'dir', 'media'
3188 * @return String: HTML fragment
3190 protected function styleLink( $style, $options ) {
3191 if( isset( $options['dir'] ) ) {
3192 if( $this->getLang()->getDir() != $options['dir'] ) {
3197 if( isset( $options['media'] ) ) {
3198 $media = self
::transformCssMedia( $options['media'] );
3199 if( is_null( $media ) ) {
3206 if( substr( $style, 0, 1 ) == '/' ||
3207 substr( $style, 0, 5 ) == 'http:' ||
3208 substr( $style, 0, 6 ) == 'https:' ) {
3211 global $wgStylePath, $wgStyleVersion;
3212 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
3215 $link = Html
::linkedStyle( $url, $media );
3217 if( isset( $options['condition'] ) ) {
3218 $condition = htmlspecialchars( $options['condition'] );
3219 $link = "<!--[if $condition]>$link<![endif]-->";
3225 * Transform "media" attribute based on request parameters
3227 * @param $media String: current value of the "media" attribute
3228 * @return String: modified value of the "media" attribute
3230 public static function transformCssMedia( $media ) {
3231 global $wgRequest, $wgHandheldForIPhone;
3233 // Switch in on-screen display for media testing
3235 'printable' => 'print',
3236 'handheld' => 'handheld',
3238 foreach( $switches as $switch => $targetMedia ) {
3239 if( $wgRequest->getBool( $switch ) ) {
3240 if( $media == $targetMedia ) {
3242 } elseif( $media == 'screen' ) {
3248 // Expand longer media queries as iPhone doesn't grok 'handheld'
3249 if( $wgHandheldForIPhone ) {
3250 $mediaAliases = array(
3251 'screen' => 'screen and (min-device-width: 481px)',
3252 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
3255 if( isset( $mediaAliases[$media] ) ) {
3256 $media = $mediaAliases[$media];
3264 * Add a wikitext-formatted message to the output.
3265 * This is equivalent to:
3267 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
3269 public function addWikiMsg( /*...*/ ) {
3270 $args = func_get_args();
3271 $name = array_shift( $args );
3272 $this->addWikiMsgArray( $name, $args );
3276 * Add a wikitext-formatted message to the output.
3277 * Like addWikiMsg() except the parameters are taken as an array
3278 * instead of a variable argument list.
3280 * @param $name string
3281 * @param $args array
3283 public function addWikiMsgArray( $name, $args ) {
3284 $this->addWikiText( $this->msg( $name, $args )->plain() );
3288 * This function takes a number of message/argument specifications, wraps them in
3289 * some overall structure, and then parses the result and adds it to the output.
3291 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3292 * on. The subsequent arguments may either be strings, in which case they are the
3293 * message names, or arrays, in which case the first element is the message name,
3294 * and subsequent elements are the parameters to that message.
3296 * The special named parameter 'options' in a message specification array is passed
3297 * through to the $options parameter of wfMsgExt().
3299 * Don't use this for messages that are not in users interface language.
3303 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3307 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . "\n</div>" );
3309 * The newline after opening div is needed in some wikitext. See bug 19226.
3311 * @param $wrap string
3313 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3314 $msgSpecs = func_get_args();
3315 array_shift( $msgSpecs );
3316 $msgSpecs = array_values( $msgSpecs );
3318 foreach ( $msgSpecs as $n => $spec ) {
3320 if ( is_array( $spec ) ) {
3322 $name = array_shift( $args );
3323 if ( isset( $args['options'] ) ) {
3324 $options = $args['options'];
3325 unset( $args['options'] );
3331 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
3333 $this->addWikiText( $s );
3337 * Include jQuery core. Use this to avoid loading it multiple times
3338 * before we get a usable script loader.
3340 * @param $modules Array: list of jQuery modules which should be loaded
3341 * @return Array: the list of modules which were not loaded.
3343 * @deprecated since 1.17
3345 public function includeJQuery( $modules = array() ) {