5d17ec1417a41f080060a695ffd71330c4b407e3
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;
200 private $mRevisionTimestamp = null;
202 var $mFileVersion = null;
205 * An array of stylesheet filenames (relative from skins path), with options
206 * for CSS media, IE conditions, and RTL/LTR direction.
207 * For internal use; add settings in the skin via $this->addStyle()
209 * Style again! This seems like a code duplication since we already have
210 * mStyles. This is what makes OpenSource amazing.
212 var $styles = array();
215 * Whether jQuery is already handled.
217 protected $mJQueryDone = false;
219 private $mIndexPolicy = 'index';
220 private $mFollowPolicy = 'follow';
221 private $mVaryHeader = array(
222 'Accept-Encoding' => array( 'list-contains=gzip' ),
227 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
232 private $mRedirectedFrom = null;
235 * Constructor for OutputPage. This should not be called directly.
236 * Instead a new RequestContext should be created and it will implicitly create
237 * a OutputPage tied to that context.
239 function __construct( IContextSource
$context = null ) {
240 if ( $context === null ) {
241 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
242 wfDeprecated( __METHOD__
);
244 $this->setContext( $context );
249 * Redirect to $url rather than displaying the normal page
251 * @param $url String: URL
252 * @param $responsecode String: HTTP status code
254 public function redirect( $url, $responsecode = '302' ) {
255 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
256 $this->mRedirect
= str_replace( "\n", '', $url );
257 $this->mRedirectCode
= $responsecode;
261 * Get the URL to redirect to, or an empty string if not redirect URL set
265 public function getRedirect() {
266 return $this->mRedirect
;
270 * Set the HTTP status code to send with the output.
272 * @param $statusCode Integer
274 public function setStatusCode( $statusCode ) {
275 $this->mStatusCode
= $statusCode;
279 * Add a new <meta> tag
280 * To add an http-equiv meta tag, precede the name with "http:"
282 * @param $name String tag name
283 * @param $val String tag value
285 function addMeta( $name, $val ) {
286 array_push( $this->mMetatags
, array( $name, $val ) );
290 * Add a keyword or a list of keywords in the page header
292 * @param $text String or array of strings
294 function addKeyword( $text ) {
295 if( is_array( $text ) ) {
296 $this->mKeywords
= array_merge( $this->mKeywords
, $text );
298 array_push( $this->mKeywords
, $text );
303 * Add a new \<link\> tag to the page header
305 * @param $linkarr Array: associative array of attributes.
307 function addLink( $linkarr ) {
308 array_push( $this->mLinktags
, $linkarr );
312 * Add a new \<link\> with "rel" attribute set to "meta"
314 * @param $linkarr Array: associative array mapping attribute names to their
315 * values, both keys and values will be escaped, and the
316 * "rel" attribute will be automatically added
318 function addMetadataLink( $linkarr ) {
319 $linkarr['rel'] = $this->getMetadataAttribute();
320 $this->addLink( $linkarr );
324 * Get the value of the "rel" attribute for metadata links
328 public function getMetadataAttribute() {
329 # note: buggy CC software only reads first "meta" link
330 static $haveMeta = false;
332 return 'alternate meta';
340 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
342 * @param $script String: raw HTML
344 function addScript( $script ) {
345 $this->mScripts
.= $script . "\n";
349 * Register and add a stylesheet from an extension directory.
351 * @param $url String path to sheet. Provide either a full url (beginning
352 * with 'http', etc) or a relative path from the document root
353 * (beginning with '/'). Otherwise it behaves identically to
354 * addStyle() and draws from the /skins folder.
356 public function addExtensionStyle( $url ) {
357 array_push( $this->mExtStyles
, $url );
361 * Get all styles added by extensions
365 function getExtStyle() {
366 return $this->mExtStyles
;
370 * Add a JavaScript file out of skins/common, or a given relative path.
372 * @param $file String: filename in skins/common or complete on-server path
374 * @param $version String: style version of the file. Defaults to $wgStyleVersion
376 public function addScriptFile( $file, $version = null ) {
377 global $wgStylePath, $wgStyleVersion;
378 // See if $file parameter is an absolute URL or begins with a slash
379 if( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
382 $path = "{$wgStylePath}/common/{$file}";
384 if ( is_null( $version ) )
385 $version = $wgStyleVersion;
386 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
390 * Add a self-contained script tag with the given contents
392 * @param $script String: JavaScript text, no <script> tags
394 public function addInlineScript( $script ) {
395 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
399 * Get all registered JS and CSS tags for the header.
403 function getScript() {
404 return $this->mScripts
. $this->getHeadItems();
408 * Filter an array of modules to remove insufficiently trustworthy members, and modules
409 * which are no longer registered (eg a page is cached before an extension is disabled)
410 * @param $modules Array
411 * @param $position String if not null, only return modules with this position
412 * @param $type string
415 protected function filterModules( $modules, $position = null, $type = ResourceLoaderModule
::TYPE_COMBINED
){
416 $resourceLoader = $this->getResourceLoader();
417 $filteredModules = array();
418 foreach( $modules as $val ){
419 $module = $resourceLoader->getModule( $val );
420 if( $module instanceof ResourceLoaderModule
421 && $module->getOrigin() <= $this->getAllowedModules( $type )
422 && ( is_null( $position ) ||
$module->getPosition() == $position ) )
424 $filteredModules[] = $val;
427 return $filteredModules;
431 * Get the list of modules to include on this page
433 * @param $filter Bool whether to filter out insufficiently trustworthy modules
434 * @param $position String if not null, only return modules with this position
435 * @param $param string
436 * @return Array of module names
438 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
439 $modules = array_values( array_unique( $this->$param ) );
441 ?
$this->filterModules( $modules, $position )
446 * Add one or more modules recognized by the resource loader. Modules added
447 * through this function will be loaded by the resource loader when the
450 * @param $modules Mixed: module name (string) or array of module names
452 public function addModules( $modules ) {
453 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
457 * Get the list of module JS to include on this page
462 * @return array of module names
464 public function getModuleScripts( $filter = false, $position = null ) {
465 return $this->getModules( $filter, $position, 'mModuleScripts' );
469 * Add only JS of one or more modules recognized by the resource loader. Module
470 * scripts added through this function will be loaded by the resource loader when
473 * @param $modules Mixed: module name (string) or array of module names
475 public function addModuleScripts( $modules ) {
476 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
480 * Get the list of module CSS to include on this page
485 * @return Array of module names
487 public function getModuleStyles( $filter = false, $position = null ) {
488 return $this->getModules( $filter, $position, 'mModuleStyles' );
492 * Add only CSS of one or more modules recognized by the resource loader. Module
493 * styles added through this function will be loaded by the resource loader when
496 * @param $modules Mixed: module name (string) or array of module names
498 public function addModuleStyles( $modules ) {
499 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
503 * Get the list of module messages to include on this page
508 * @return Array of module names
510 public function getModuleMessages( $filter = false, $position = null ) {
511 return $this->getModules( $filter, $position, 'mModuleMessages' );
515 * Add only messages of one or more modules recognized by the resource loader.
516 * Module messages added through this function will be loaded by the resource
517 * loader when the page loads.
519 * @param $modules Mixed: module name (string) or array of module names
521 public function addModuleMessages( $modules ) {
522 $this->mModuleMessages
= array_merge( $this->mModuleMessages
, (array)$modules );
526 * Get an array of head items
530 function getHeadItemsArray() {
531 return $this->mHeadItems
;
535 * Get all header items in a string
539 function getHeadItems() {
541 foreach ( $this->mHeadItems
as $item ) {
548 * Add or replace an header item to the output
550 * @param $name String: item name
551 * @param $value String: raw HTML
553 public function addHeadItem( $name, $value ) {
554 $this->mHeadItems
[$name] = $value;
558 * Check if the header item $name is already set
560 * @param $name String: item name
563 public function hasHeadItem( $name ) {
564 return isset( $this->mHeadItems
[$name] );
568 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
570 * @param $tag String: value of "ETag" header
572 function setETag( $tag ) {
577 * Set whether the output should only contain the body of the article,
578 * without any skin, sidebar, etc.
579 * Used e.g. when calling with "action=render".
581 * @param $only Boolean: whether to output only the body of the article
583 public function setArticleBodyOnly( $only ) {
584 $this->mArticleBodyOnly
= $only;
588 * Return whether the output will contain only the body of the article
592 public function getArticleBodyOnly() {
593 return $this->mArticleBodyOnly
;
597 * checkLastModified tells the client to use the client-cached page if
598 * possible. If sucessful, the OutputPage is disabled so that
599 * any future call to OutputPage->output() have no effect.
601 * Side effect: sets mLastModified for Last-Modified header
603 * @param $timestamp string
605 * @return Boolean: true iff cache-ok headers was sent.
607 public function checkLastModified( $timestamp ) {
608 global $wgCachePages, $wgCacheEpoch;
610 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
611 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
614 if( !$wgCachePages ) {
615 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
618 if( $this->getUser()->getOption( 'nocache' ) ) {
619 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
623 $timestamp = wfTimestamp( TS_MW
, $timestamp );
624 $modifiedTimes = array(
625 'page' => $timestamp,
626 'user' => $this->getUser()->getTouched(),
627 'epoch' => $wgCacheEpoch
629 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
631 $maxModified = max( $modifiedTimes );
632 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
634 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
635 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
641 foreach ( $modifiedTimes as $name => $value ) {
642 if ( $info !== '' ) {
645 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
648 # IE sends sizes after the date like this:
649 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
650 # this breaks strtotime().
651 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
653 wfSuppressWarnings(); // E_STRICT system time bitching
654 $clientHeaderTime = strtotime( $clientHeader );
656 if ( !$clientHeaderTime ) {
657 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
660 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
662 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
663 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
664 wfDebug( __METHOD__
. ": effective Last-Modified: " .
665 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
666 if( $clientHeaderTime < $maxModified ) {
667 wfDebug( __METHOD__
. ": STALE, $info\n", false );
672 # Give a 304 response code and disable body output
673 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
674 ini_set( 'zlib.output_compression', 0 );
675 $this->getRequest()->response()->header( "HTTP/1.1 304 Not Modified" );
676 $this->sendCacheControl();
679 // Don't output a compressed blob when using ob_gzhandler;
680 // it's technically against HTTP spec and seems to confuse
681 // Firefox when the response gets split over two packets.
682 wfClearOutputBuffers();
688 * Override the last modified timestamp
690 * @param $timestamp String: new timestamp, in a format readable by
693 public function setLastModified( $timestamp ) {
694 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
698 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
700 * @param $policy String: the literal string to output as the contents of
701 * the meta tag. Will be parsed according to the spec and output in
705 public function setRobotPolicy( $policy ) {
706 $policy = Article
::formatRobotPolicy( $policy );
708 if( isset( $policy['index'] ) ) {
709 $this->setIndexPolicy( $policy['index'] );
711 if( isset( $policy['follow'] ) ) {
712 $this->setFollowPolicy( $policy['follow'] );
717 * Set the index policy for the page, but leave the follow policy un-
720 * @param $policy string Either 'index' or 'noindex'.
723 public function setIndexPolicy( $policy ) {
724 $policy = trim( $policy );
725 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
726 $this->mIndexPolicy
= $policy;
731 * Set the follow policy for the page, but leave the index policy un-
734 * @param $policy String: either 'follow' or 'nofollow'.
737 public function setFollowPolicy( $policy ) {
738 $policy = trim( $policy );
739 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
740 $this->mFollowPolicy
= $policy;
745 * Set the new value of the "action text", this will be added to the
746 * "HTML title", separated from it with " - ".
748 * @param $text String: new value of the "action text"
750 public function setPageTitleActionText( $text ) {
751 $this->mPageTitleActionText
= $text;
755 * Get the value of the "action text"
759 public function getPageTitleActionText() {
760 if ( isset( $this->mPageTitleActionText
) ) {
761 return $this->mPageTitleActionText
;
766 * "HTML title" means the contents of <title>.
767 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
769 * @param $name string
771 public function setHTMLTitle( $name ) {
772 if ( $name instanceof Message
) {
773 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
775 $this->mHTMLtitle
= $name;
780 * Return the "HTML title", i.e. the content of the <title> tag.
784 public function getHTMLTitle() {
785 return $this->mHTMLtitle
;
789 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
793 public function setRedirectedFrom( $t ) {
794 $this->mRedirectedFrom
= $t;
798 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
799 * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
800 * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
801 * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
803 * @param $name string|Message
805 public function setPageTitle( $name ) {
806 if ( $name instanceof Message
) {
807 $name = $name->setContext( $this->getContext() )->text();
810 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
811 # but leave "<i>foobar</i>" alone
812 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
813 $this->mPagetitle
= $nameWithTags;
815 # change "<i>foo&bar</i>" to "foo&bar"
816 $this->setHTMLTitle( $this->msg( 'pagetitle', Sanitizer
::stripAllTags( $nameWithTags ) ) );
820 * Return the "page title", i.e. the content of the \<h1\> tag.
824 public function getPageTitle() {
825 return $this->mPagetitle
;
829 * Set the Title object to use
831 * @param $t Title object
833 public function setTitle( Title
$t ) {
834 $this->getContext()->setTitle( $t );
839 * Replace the subtile with $str
841 * @param $str String|Message: new value of the subtitle
843 public function setSubtitle( $str ) {
844 $this->clearSubtitle();
845 $this->addSubtitle( $str );
849 * Add $str to the subtitle
851 * @deprecated in 1.19; use addSubtitle() instead
852 * @param $str String|Message to add to the subtitle
854 public function appendSubtitle( $str ) {
855 $this->addSubtitle( $str );
859 * Add $str to the subtitle
861 * @param $str String|Message to add to the subtitle
863 public function addSubtitle( $str ) {
864 if ( $str instanceof Message
) {
865 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
867 $this->mSubtitle
[] = $str;
872 * Add a subtitle containing a backlink to a page
874 * @param $title Title to link to
876 public function addBacklinkSubtitle( Title
$title ) {
878 if ( $title->isRedirect() ) {
879 $query['redirect'] = 'no';
881 $this->addSubtitle( $this->msg( 'backlinksubtitle' )->rawParams( Linker
::link( $title, null, array(), $query ) ) );
885 * Clear the subtitles
887 public function clearSubtitle() {
888 $this->mSubtitle
= array();
896 public function getSubtitle() {
897 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
901 * Set the page as printable, i.e. it'll be displayed with with all
902 * print styles included
904 public function setPrintable() {
905 $this->mPrintable
= true;
909 * Return whether the page is "printable"
913 public function isPrintable() {
914 return $this->mPrintable
;
918 * Disable output completely, i.e. calling output() will have no effect
920 public function disable() {
921 $this->mDoNothing
= true;
925 * Return whether the output will be completely disabled
929 public function isDisabled() {
930 return $this->mDoNothing
;
934 * Show an "add new section" link?
938 public function showNewSectionLink() {
939 return $this->mNewSectionLink
;
943 * Forcibly hide the new section link?
947 public function forceHideNewSectionLink() {
948 return $this->mHideNewSectionLink
;
952 * Add or remove feed links in the page header
953 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
954 * for the new version
957 * @param $show Boolean: true: add default feeds, false: remove all feeds
959 public function setSyndicated( $show = true ) {
961 $this->setFeedAppendQuery( false );
963 $this->mFeedLinks
= array();
968 * Add default feeds to the page header
969 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
970 * for the new version
973 * @param $val String: query to append to feed links or false to output
976 public function setFeedAppendQuery( $val ) {
977 global $wgAdvertisedFeedTypes;
979 $this->mFeedLinks
= array();
981 foreach ( $wgAdvertisedFeedTypes as $type ) {
982 $query = "feed=$type";
983 if ( is_string( $val ) ) {
984 $query .= '&' . $val;
986 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
991 * Add a feed link to the page header
993 * @param $format String: feed type, should be a key of $wgFeedClasses
994 * @param $href String: URL
996 public function addFeedLink( $format, $href ) {
997 global $wgAdvertisedFeedTypes;
999 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
1000 $this->mFeedLinks
[$format] = $href;
1005 * Should we output feed links for this page?
1008 public function isSyndicated() {
1009 return count( $this->mFeedLinks
) > 0;
1013 * Return URLs for each supported syndication format for this page.
1014 * @return array associating format keys with URLs
1016 public function getSyndicationLinks() {
1017 return $this->mFeedLinks
;
1021 * Will currently always return null
1025 public function getFeedAppendQuery() {
1026 return $this->mFeedLinksAppendQuery
;
1030 * Set whether the displayed content is related to the source of the
1031 * corresponding article on the wiki
1032 * Setting true will cause the change "article related" toggle to true
1036 public function setArticleFlag( $v ) {
1037 $this->mIsarticle
= $v;
1039 $this->mIsArticleRelated
= $v;
1044 * Return whether the content displayed page is related to the source of
1045 * the corresponding article on the wiki
1049 public function isArticle() {
1050 return $this->mIsarticle
;
1054 * Set whether this page is related an article on the wiki
1055 * Setting false will cause the change of "article flag" toggle to false
1059 public function setArticleRelated( $v ) {
1060 $this->mIsArticleRelated
= $v;
1062 $this->mIsarticle
= false;
1067 * Return whether this page is related an article on the wiki
1071 public function isArticleRelated() {
1072 return $this->mIsArticleRelated
;
1076 * Add new language links
1078 * @param $newLinkArray Associative array mapping language code to the page
1081 public function addLanguageLinks( $newLinkArray ) {
1082 $this->mLanguageLinks +
= $newLinkArray;
1086 * Reset the language links and add new language links
1088 * @param $newLinkArray Associative array mapping language code to the page
1091 public function setLanguageLinks( $newLinkArray ) {
1092 $this->mLanguageLinks
= $newLinkArray;
1096 * Get the list of language links
1098 * @return Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1100 public function getLanguageLinks() {
1101 return $this->mLanguageLinks
;
1105 * Add an array of categories, with names in the keys
1107 * @param $categories Array mapping category name => sort key
1109 public function addCategoryLinks( $categories ) {
1112 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1116 # Add the links to a LinkBatch
1117 $arr = array( NS_CATEGORY
=> $categories );
1118 $lb = new LinkBatch
;
1119 $lb->setArray( $arr );
1121 # Fetch existence plus the hiddencat property
1122 $dbr = wfGetDB( DB_SLAVE
);
1123 $res = $dbr->select( array( 'page', 'page_props' ),
1124 array( 'page_id', 'page_namespace', 'page_title', 'page_len', 'page_is_redirect', 'page_latest', 'pp_value' ),
1125 $lb->constructSet( 'page', $dbr ),
1128 array( 'page_props' => array( 'LEFT JOIN', array( 'pp_propname' => 'hiddencat', 'pp_page = page_id' ) ) )
1131 # Add the results to the link cache
1132 $lb->addResultToCache( LinkCache
::singleton(), $res );
1134 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
1135 $categories = array_combine(
1136 array_keys( $categories ),
1137 array_fill( 0, count( $categories ), 'normal' )
1140 # Mark hidden categories
1141 foreach ( $res as $row ) {
1142 if ( isset( $row->pp_value
) ) {
1143 $categories[$row->page_title
] = 'hidden';
1147 # Add the remaining categories to the skin
1148 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
1149 foreach ( $categories as $category => $type ) {
1150 $origcategory = $category;
1151 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1152 $wgContLang->findVariantLink( $category, $title, true );
1153 if ( $category != $origcategory ) {
1154 if ( array_key_exists( $category, $categories ) ) {
1158 $text = $wgContLang->convertHtml( $title->getText() );
1159 $this->mCategories
[] = $title->getText();
1160 $this->mCategoryLinks
[$type][] = Linker
::link( $title, $text );
1166 * Reset the category links (but not the category list) and add $categories
1168 * @param $categories Array mapping category name => sort key
1170 public function setCategoryLinks( $categories ) {
1171 $this->mCategoryLinks
= array();
1172 $this->addCategoryLinks( $categories );
1176 * Get the list of category links, in a 2-D array with the following format:
1177 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1178 * hidden categories) and $link a HTML fragment with a link to the category
1183 public function getCategoryLinks() {
1184 return $this->mCategoryLinks
;
1188 * Get the list of category names this page belongs to
1190 * @return Array of strings
1192 public function getCategories() {
1193 return $this->mCategories
;
1197 * Do not allow scripts which can be modified by wiki users to load on this page;
1198 * only allow scripts bundled with, or generated by, the software.
1200 public function disallowUserJs() {
1201 $this->reduceAllowedModules(
1202 ResourceLoaderModule
::TYPE_SCRIPTS
,
1203 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1208 * Return whether user JavaScript is allowed for this page
1209 * @deprecated since 1.18 Load modules with ResourceLoader, and origin and
1210 * trustworthiness is identified and enforced automagically.
1213 public function isUserJsAllowed() {
1214 return $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
) >= ResourceLoaderModule
::ORIGIN_USER_INDIVIDUAL
;
1218 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1219 * @see ResourceLoaderModule::$origin
1220 * @param $type String ResourceLoaderModule TYPE_ constant
1221 * @return Int ResourceLoaderModule ORIGIN_ class constant
1223 public function getAllowedModules( $type ){
1224 if( $type == ResourceLoaderModule
::TYPE_COMBINED
){
1225 return min( array_values( $this->mAllowedModules
) );
1227 return isset( $this->mAllowedModules
[$type] )
1228 ?
$this->mAllowedModules
[$type]
1229 : ResourceLoaderModule
::ORIGIN_ALL
;
1234 * Set the highest level of CSS/JS untrustworthiness allowed
1235 * @param $type String ResourceLoaderModule TYPE_ constant
1236 * @param $level Int ResourceLoaderModule class constant
1238 public function setAllowedModules( $type, $level ){
1239 $this->mAllowedModules
[$type] = $level;
1243 * As for setAllowedModules(), but don't inadvertantly make the page more accessible
1244 * @param $type String
1245 * @param $level Int ResourceLoaderModule class constant
1247 public function reduceAllowedModules( $type, $level ){
1248 $this->mAllowedModules
[$type] = min( $this->getAllowedModules($type), $level );
1252 * Prepend $text to the body HTML
1254 * @param $text String: HTML
1256 public function prependHTML( $text ) {
1257 $this->mBodytext
= $text . $this->mBodytext
;
1261 * Append $text to the body HTML
1263 * @param $text String: HTML
1265 public function addHTML( $text ) {
1266 $this->mBodytext
.= $text;
1270 * Shortcut for adding an Html::element via addHTML.
1274 * @param $element string
1275 * @param $attribs array
1276 * @param $contents string
1278 public function addElement( $element, $attribs = array(), $contents = '' ) {
1279 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1283 * Clear the body HTML
1285 public function clearHTML() {
1286 $this->mBodytext
= '';
1292 * @return String: HTML
1294 public function getHTML() {
1295 return $this->mBodytext
;
1299 * Add $text to the debug output
1301 * @param $text String: debug text
1303 public function debug( $text ) {
1304 $this->mDebugtext
.= $text;
1308 * Get/set the ParserOptions object to use for wikitext parsing
1310 * @param $options either the ParserOption to use or null to only get the
1311 * current ParserOption object
1312 * @return ParserOptions object
1314 public function parserOptions( $options = null ) {
1315 if ( !$this->mParserOptions
) {
1316 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1317 $this->mParserOptions
->setEditSection( false );
1319 return wfSetVar( $this->mParserOptions
, $options );
1323 * Set the revision ID which will be seen by the wiki text parser
1324 * for things such as embedded {{REVISIONID}} variable use.
1326 * @param $revid Mixed: an positive integer, or null
1327 * @return Mixed: previous value
1329 public function setRevisionId( $revid ) {
1330 $val = is_null( $revid ) ?
null : intval( $revid );
1331 return wfSetVar( $this->mRevisionId
, $val );
1335 * Get the displayed revision ID
1339 public function getRevisionId() {
1340 return $this->mRevisionId
;
1344 * Set the timestamp of the revision which will be displayed. This is used
1345 * to avoid a extra DB call in Skin::lastModified().
1347 * @param $revid Mixed: string, or null
1348 * @return Mixed: previous value
1350 public function setRevisionTimestamp( $timestmap ) {
1351 return wfSetVar( $this->mRevisionTimestamp
, $timestmap );
1355 * Get the timestamp of displayed revision.
1356 * This will be null if not filled by setRevisionTimestamp().
1358 * @return String or null
1360 public function getRevisionTimestamp() {
1361 return $this->mRevisionTimestamp
;
1365 * Set the displayed file version
1367 * @param $file File|false
1368 * @return Mixed: previous value
1370 public function setFileVersion( $file ) {
1372 if ( $file instanceof File
&& $file->exists() ) {
1373 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1375 return wfSetVar( $this->mFileVersion
, $val, true );
1379 * Get the displayed file version
1381 * @return Array|null ('time' => MW timestamp, 'sha1' => sha1)
1383 public function getFileVersion() {
1384 return $this->mFileVersion
;
1388 * Get the templates used on this page
1390 * @return Array (namespace => dbKey => revId)
1393 public function getTemplateIds() {
1394 return $this->mTemplateIds
;
1398 * Get the files used on this page
1400 * @return Array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1403 public function getFileSearchOptions() {
1404 return $this->mImageTimeKeys
;
1408 * Convert wikitext to HTML and add it to the buffer
1409 * Default assumes that the current page title will be used.
1411 * @param $text String
1412 * @param $linestart Boolean: is this the start of a line?
1413 * @param $interface Boolean: is this text in the user interface language?
1415 public function addWikiText( $text, $linestart = true, $interface = true ) {
1416 $title = $this->getTitle(); // Work arround E_STRICT
1417 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1421 * Add wikitext with a custom Title object
1423 * @param $text String: wikitext
1424 * @param $title Title object
1425 * @param $linestart Boolean: is this the start of a line?
1427 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1428 $this->addWikiTextTitle( $text, $title, $linestart );
1432 * Add wikitext with a custom Title object and tidy enabled.
1434 * @param $text String: wikitext
1435 * @param $title Title object
1436 * @param $linestart Boolean: is this the start of a line?
1438 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1439 $this->addWikiTextTitle( $text, $title, $linestart, true );
1443 * Add wikitext with tidy enabled
1445 * @param $text String: wikitext
1446 * @param $linestart Boolean: is this the start of a line?
1448 public function addWikiTextTidy( $text, $linestart = true ) {
1449 $title = $this->getTitle();
1450 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1454 * Add wikitext with a custom Title object
1456 * @param $text String: wikitext
1457 * @param $title Title object
1458 * @param $linestart Boolean: is this the start of a line?
1459 * @param $tidy Boolean: whether to use tidy
1460 * @param $interface Boolean: whether it is an interface message
1461 * (for example disables conversion)
1463 public function addWikiTextTitle( $text, &$title, $linestart, $tidy = false, $interface = false ) {
1466 wfProfileIn( __METHOD__
);
1468 wfIncrStats( 'pcache_not_possible' );
1470 $popts = $this->parserOptions();
1471 $oldTidy = $popts->setTidy( $tidy );
1472 $popts->setInterfaceMessage( (bool) $interface );
1474 $parserOutput = $wgParser->parse(
1475 $text, $title, $popts,
1476 $linestart, true, $this->mRevisionId
1479 $popts->setTidy( $oldTidy );
1481 $this->addParserOutput( $parserOutput );
1483 wfProfileOut( __METHOD__
);
1487 * Add a ParserOutput object, but without Html
1489 * @param $parserOutput ParserOutput object
1491 public function addParserOutputNoText( &$parserOutput ) {
1492 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1493 $this->addCategoryLinks( $parserOutput->getCategories() );
1494 $this->mNewSectionLink
= $parserOutput->getNewSection();
1495 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1497 $this->mParseWarnings
= $parserOutput->getWarnings();
1498 if ( !$parserOutput->isCacheable() ) {
1499 $this->enableClientCache( false );
1501 $this->mNoGallery
= $parserOutput->getNoGallery();
1502 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1503 $this->addModules( $parserOutput->getModules() );
1504 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1505 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1506 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1508 // Template versioning...
1509 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1510 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1511 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1513 $this->mTemplateIds
[$ns] = $dbks;
1516 // File versioning...
1517 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1518 $this->mImageTimeKeys
[$dbk] = $data;
1521 // Hooks registered in the object
1522 global $wgParserOutputHooks;
1523 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1524 list( $hookName, $data ) = $hookInfo;
1525 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1526 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1530 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1534 * Add a ParserOutput object
1536 * @param $parserOutput ParserOutput
1538 function addParserOutput( &$parserOutput ) {
1539 $this->addParserOutputNoText( $parserOutput );
1540 $text = $parserOutput->getText();
1541 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1542 $this->addHTML( $text );
1547 * Add the output of a QuickTemplate to the output buffer
1549 * @param $template QuickTemplate
1551 public function addTemplate( &$template ) {
1553 $template->execute();
1554 $this->addHTML( ob_get_contents() );
1559 * Parse wikitext and return the HTML.
1561 * @param $text String
1562 * @param $linestart Boolean: is this the start of a line?
1563 * @param $interface Boolean: use interface language ($wgLang instead of
1564 * $wgContLang) while parsing language sensitive magic
1565 * words like GRAMMAR and PLURAL. This also disables
1566 * LanguageConverter.
1567 * @param $language Language object: target language object, will override
1569 * @return String: HTML
1571 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1574 if( is_null( $this->getTitle() ) ) {
1575 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1578 $popts = $this->parserOptions();
1580 $popts->setInterfaceMessage( true );
1582 if ( $language !== null ) {
1583 $oldLang = $popts->setTargetLanguage( $language );
1586 $parserOutput = $wgParser->parse(
1587 $text, $this->getTitle(), $popts,
1588 $linestart, true, $this->mRevisionId
1592 $popts->setInterfaceMessage( false );
1594 if ( $language !== null ) {
1595 $popts->setTargetLanguage( $oldLang );
1598 return $parserOutput->getText();
1602 * Parse wikitext, strip paragraphs, and return the HTML.
1604 * @param $text String
1605 * @param $linestart Boolean: is this the start of a line?
1606 * @param $interface Boolean: use interface language ($wgLang instead of
1607 * $wgContLang) while parsing language sensitive magic
1608 * words like GRAMMAR and PLURAL
1609 * @return String: HTML
1611 public function parseInline( $text, $linestart = true, $interface = false ) {
1612 $parsed = $this->parse( $text, $linestart, $interface );
1615 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1623 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1625 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1627 public function setSquidMaxage( $maxage ) {
1628 $this->mSquidMaxage
= $maxage;
1632 * Use enableClientCache(false) to force it to send nocache headers
1634 * @param $state bool
1638 public function enableClientCache( $state ) {
1639 return wfSetVar( $this->mEnableClientCache
, $state );
1643 * Get the list of cookies that will influence on the cache
1647 function getCacheVaryCookies() {
1648 global $wgCookiePrefix, $wgCacheVaryCookies;
1650 if ( $cookies === null ) {
1651 $cookies = array_merge(
1653 "{$wgCookiePrefix}Token",
1654 "{$wgCookiePrefix}LoggedOut",
1659 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1665 * Return whether this page is not cacheable because "useskin" or "uselang"
1666 * URL parameters were passed.
1670 function uncacheableBecauseRequestVars() {
1671 $request = $this->getRequest();
1672 return $request->getText( 'useskin', false ) === false
1673 && $request->getText( 'uselang', false ) === false;
1677 * Check if the request has a cache-varying cookie header
1678 * If it does, it's very important that we don't allow public caching
1682 function haveCacheVaryCookies() {
1683 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1684 if ( $cookieHeader === false ) {
1687 $cvCookies = $this->getCacheVaryCookies();
1688 foreach ( $cvCookies as $cookieName ) {
1689 # Check for a simple string match, like the way squid does it
1690 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1691 wfDebug( __METHOD__
. ": found $cookieName\n" );
1695 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1700 * Add an HTTP header that will influence on the cache
1702 * @param $header String: header name
1703 * @param $option Array|null
1704 * @todo FIXME: Document the $option parameter; it appears to be for
1705 * X-Vary-Options but what format is acceptable?
1707 public function addVaryHeader( $header, $option = null ) {
1708 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1709 $this->mVaryHeader
[$header] = (array)$option;
1710 } elseif( is_array( $option ) ) {
1711 if( is_array( $this->mVaryHeader
[$header] ) ) {
1712 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
1714 $this->mVaryHeader
[$header] = $option;
1717 $this->mVaryHeader
[$header] = array_unique( (array)$this->mVaryHeader
[$header] );
1721 * Get a complete X-Vary-Options header
1725 public function getXVO() {
1726 $cvCookies = $this->getCacheVaryCookies();
1728 $cookiesOption = array();
1729 foreach ( $cvCookies as $cookieName ) {
1730 $cookiesOption[] = 'string-contains=' . $cookieName;
1732 $this->addVaryHeader( 'Cookie', $cookiesOption );
1735 foreach( $this->mVaryHeader
as $header => $option ) {
1736 $newheader = $header;
1737 if( is_array( $option ) ) {
1738 $newheader .= ';' . implode( ';', $option );
1740 $headers[] = $newheader;
1742 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1748 * bug 21672: Add Accept-Language to Vary and XVO headers
1749 * if there's no 'variant' parameter existed in GET.
1752 * /w/index.php?title=Main_page should always be served; but
1753 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1755 function addAcceptLanguage() {
1756 $lang = $this->getTitle()->getPageLanguage();
1757 if( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
1758 $variants = $lang->getVariants();
1759 $aloption = array();
1760 foreach ( $variants as $variant ) {
1761 if( $variant === $lang->getCode() ) {
1764 $aloption[] = 'string-contains=' . $variant;
1766 // IE and some other browsers use another form of language code
1767 // in their Accept-Language header, like "zh-CN" or "zh-TW".
1768 // We should handle these too.
1769 $ievariant = explode( '-', $variant );
1770 if ( count( $ievariant ) == 2 ) {
1771 $ievariant[1] = strtoupper( $ievariant[1] );
1772 $ievariant = implode( '-', $ievariant );
1773 $aloption[] = 'string-contains=' . $ievariant;
1777 $this->addVaryHeader( 'Accept-Language', $aloption );
1782 * Set a flag which will cause an X-Frame-Options header appropriate for
1783 * edit pages to be sent. The header value is controlled by
1784 * $wgEditPageFrameOptions.
1786 * This is the default for special pages. If you display a CSRF-protected
1787 * form on an ordinary view page, then you need to call this function.
1789 * @param $enable bool
1791 public function preventClickjacking( $enable = true ) {
1792 $this->mPreventClickjacking
= $enable;
1796 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1797 * This can be called from pages which do not contain any CSRF-protected
1800 public function allowClickjacking() {
1801 $this->mPreventClickjacking
= false;
1805 * Get the X-Frame-Options header value (without the name part), or false
1806 * if there isn't one. This is used by Skin to determine whether to enable
1807 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1811 public function getFrameOptions() {
1812 global $wgBreakFrames, $wgEditPageFrameOptions;
1813 if ( $wgBreakFrames ) {
1815 } elseif ( $this->mPreventClickjacking
&& $wgEditPageFrameOptions ) {
1816 return $wgEditPageFrameOptions;
1822 * Send cache control HTTP headers
1824 public function sendCacheControl() {
1825 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgUseXVO;
1827 $response = $this->getRequest()->response();
1828 if ( $wgUseETag && $this->mETag
) {
1829 $response->header( "ETag: $this->mETag" );
1832 $this->addAcceptLanguage();
1834 # don't serve compressed data to clients who can't handle it
1835 # maintain different caches for logged-in users and non-logged in ones
1836 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) ) );
1839 # Add an X-Vary-Options header for Squid with Wikimedia patches
1840 $response->header( $this->getXVO() );
1843 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
1845 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1846 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
1850 # We'll purge the proxy cache explicitly, but require end user agents
1851 # to revalidate against the proxy on each visit.
1852 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1853 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1854 # start with a shorter timeout for initial testing
1855 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1856 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
1857 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1859 # We'll purge the proxy cache for anons explicitly, but require end user agents
1860 # to revalidate against the proxy on each visit.
1861 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1862 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1863 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
1864 # start with a shorter timeout for initial testing
1865 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1866 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
1869 # We do want clients to cache if they can, but they *must* check for updates
1870 # on revisiting the page.
1871 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
1872 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1873 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1875 if($this->mLastModified
) {
1876 $response->header( "Last-Modified: {$this->mLastModified}" );
1879 wfDebug( __METHOD__
. ": no caching **\n", false );
1881 # In general, the absence of a last modified header should be enough to prevent
1882 # the client from using its cache. We send a few other things just to make sure.
1883 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1884 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1885 $response->header( 'Pragma: no-cache' );
1890 * Get the message associed with the HTTP response code $code
1892 * @param $code Integer: status code
1893 * @return String or null: message or null if $code is not in the list of
1896 * @deprecated since 1.18 Use HttpStatus::getMessage() instead.
1898 public static function getStatusMessage( $code ) {
1899 wfDeprecated( __METHOD__
);
1900 return HttpStatus
::getMessage( $code );
1904 * Finally, all the text has been munged and accumulated into
1905 * the object, let's actually output it:
1907 public function output() {
1908 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType, $wgVaryOnXFP;
1910 if( $this->mDoNothing
) {
1914 wfProfileIn( __METHOD__
);
1916 $response = $this->getRequest()->response();
1918 if ( $this->mRedirect
!= '' ) {
1919 # Standards require redirect URLs to be absolute
1920 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
1921 if( $this->mRedirectCode
== '301' ||
$this->mRedirectCode
== '303' ) {
1922 if( !$wgDebugRedirects ) {
1923 $message = HttpStatus
::getMessage( $this->mRedirectCode
);
1924 $response->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
1926 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1928 if ( $wgVaryOnXFP ) {
1929 $this->addVaryHeader( 'X-Forwarded-Proto' );
1931 $this->sendCacheControl();
1933 $response->header( "Content-Type: text/html; charset=utf-8" );
1934 if( $wgDebugRedirects ) {
1935 $url = htmlspecialchars( $this->mRedirect
);
1936 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1937 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1938 print "</body>\n</html>\n";
1940 $response->header( 'Location: ' . $this->mRedirect
);
1942 wfProfileOut( __METHOD__
);
1944 } elseif ( $this->mStatusCode
) {
1945 $message = HttpStatus
::getMessage( $this->mStatusCode
);
1947 $response->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
1951 # Buffer output; final headers may depend on later processing
1954 $response->header( "Content-type: $wgMimeType; charset=UTF-8" );
1955 $response->header( 'Content-language: ' . $wgLanguageCode );
1957 // Prevent framing, if requested
1958 $frameOptions = $this->getFrameOptions();
1959 if ( $frameOptions ) {
1960 $response->header( "X-Frame-Options: $frameOptions" );
1963 if ( $this->mArticleBodyOnly
) {
1964 $this->out( $this->mBodytext
);
1966 $this->addDefaultModules();
1968 $sk = $this->getSkin();
1970 // Hook that allows last minute changes to the output page, e.g.
1971 // adding of CSS or Javascript by extensions.
1972 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1974 wfProfileIn( 'Output-skin' );
1976 wfProfileOut( 'Output-skin' );
1979 $this->sendCacheControl();
1981 wfProfileOut( __METHOD__
);
1985 * Actually output something with print().
1987 * @param $ins String: the string to output
1989 public function out( $ins ) {
1994 * Produce a "user is blocked" page.
1995 * @deprecated since 1.18
1997 function blockedPage() {
1998 throw new UserBlockedError( $this->getUser()->mBlock
);
2002 * Prepare this object to display an error page; disable caching and
2003 * indexing, clear the current text and redirect, set the page's title
2004 * and optionally an custom HTML title (content of the <title> tag).
2006 * @param $pageTitle String|Message will be passed directly to setPageTitle()
2007 * @param $htmlTitle String|Message will be passed directly to setHTMLTitle();
2008 * optional, if not passed the <title> attribute will be
2009 * based on $pageTitle
2011 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2012 if ( $this->getTitle() ) {
2013 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
2016 $this->setPageTitle( $pageTitle );
2017 if ( $htmlTitle !== false ) {
2018 $this->setHTMLTitle( $htmlTitle );
2020 $this->setRobotPolicy( 'noindex,nofollow' );
2021 $this->setArticleRelated( false );
2022 $this->enableClientCache( false );
2023 $this->mRedirect
= '';
2024 $this->clearSubtitle();
2029 * Output a standard error page
2031 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2032 * showErrorPage( 'titlemsg', $messageObject );
2034 * @param $title String: message key for page title
2035 * @param $msg Mixed: message key (string) for page text, or a Message object
2036 * @param $params Array: message parameters; ignored if $msg is a Message object
2038 public function showErrorPage( $title, $msg, $params = array() ) {
2039 $this->prepareErrorPage( $this->msg( $title ), $this->msg( 'errorpagetitle' ) );
2041 if ( $msg instanceof Message
){
2042 $this->addHTML( $msg->parse() );
2044 $this->addWikiMsgArray( $msg, $params );
2047 $this->returnToMain();
2051 * Output a standard permission error page
2053 * @param $errors Array: error message keys
2054 * @param $action String: action that was denied or null if unknown
2056 public function showPermissionsErrorPage( $errors, $action = null ) {
2057 global $wgGroupPermissions;
2059 // For some action (read, edit, create and upload), display a "login to do this action"
2060 // error if all of the following conditions are met:
2061 // 1. the user is not logged in
2062 // 2. the only error is insufficient permissions (i.e. no block or something else)
2063 // 3. the error can be avoided simply by logging in
2064 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2065 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2066 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2067 && ( ( isset( $wgGroupPermissions['user'][$action] ) && $wgGroupPermissions['user'][$action] )
2068 ||
( isset( $wgGroupPermissions['autoconfirmed'][$action] ) && $wgGroupPermissions['autoconfirmed'][$action] ) )
2070 $displayReturnto = null;
2072 # Due to bug 32276, if a user does not have read permissions,
2073 # $this->getTitle() will just give Special:Badtitle, which is
2074 # not especially useful as a returnto parameter. Use the title
2075 # from the request instead, if there was one.
2076 $request = $this->getRequest();
2077 $returnto = Title
::newFromURL( $request->getVal( 'title', '' ) );
2078 if ( $action == 'edit' ) {
2079 $msg = 'whitelistedittext';
2080 $displayReturnto = $returnto;
2081 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2082 $msg = 'nocreatetext';
2083 } elseif ( $action == 'upload' ) {
2084 $msg = 'uploadnologintext';
2086 $msg = 'loginreqpagetext';
2087 $displayReturnto = Title
::newMainPage();
2093 $query['returnto'] = $returnto->getPrefixedText();
2095 if ( !$request->wasPosted() ) {
2096 $returntoquery = $request->getValues();
2097 unset( $returntoquery['title'] );
2098 unset( $returntoquery['returnto'] );
2099 unset( $returntoquery['returntoquery'] );
2100 $query['returntoquery'] = wfArrayToCGI( $returntoquery );
2103 $loginLink = Linker
::linkKnown(
2104 SpecialPage
::getTitleFor( 'Userlogin' ),
2105 $this->msg( 'loginreqlink' )->escaped(),
2110 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2111 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2113 # Don't return to a page the user can't read otherwise
2114 # we'll end up in a pointless loop
2115 if ( $displayReturnto && $displayReturnto->userCanRead() ) {
2116 $this->returnToMain( null, $displayReturnto );
2119 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2120 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2125 * Display an error page indicating that a given version of MediaWiki is
2126 * required to use it
2128 * @param $version Mixed: the version of MediaWiki needed to use the page
2130 public function versionRequired( $version ) {
2131 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2133 $this->addWikiMsg( 'versionrequiredtext', $version );
2134 $this->returnToMain();
2138 * Display an error page noting that a given permission bit is required.
2139 * @deprecated since 1.18, just throw the exception directly
2140 * @param $permission String: key required
2142 public function permissionRequired( $permission ) {
2143 throw new PermissionsError( $permission );
2147 * Produce the stock "please login to use the wiki" page
2149 * @deprecated in 1.19; throw the exception directly
2151 public function loginToUse() {
2152 throw new PermissionsError( 'read' );
2156 * Format a list of error messages
2158 * @param $errors Array of arrays returned by Title::getUserPermissionsErrors
2159 * @param $action String: action that was denied or null if unknown
2160 * @return String: the wikitext error-messages, formatted into a list.
2162 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2163 if ( $action == null ) {
2164 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2166 $action_desc = $this->msg( "action-$action" )->plain();
2168 'permissionserrorstext-withaction',
2171 )->plain() . "\n\n";
2174 if ( count( $errors ) > 1 ) {
2175 $text .= '<ul class="permissions-errors">' . "\n";
2177 foreach( $errors as $error ) {
2179 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2184 $text .= "<div class=\"permissions-errors\">\n" .
2185 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2193 * Display a page stating that the Wiki is in read-only mode,
2194 * and optionally show the source of the page that the user
2195 * was trying to edit. Should only be called (for this
2196 * purpose) after wfReadOnly() has returned true.
2198 * For historical reasons, this function is _also_ used to
2199 * show the error message when a user tries to edit a page
2200 * they are not allowed to edit. (Unless it's because they're
2201 * blocked, then we show blockedPage() instead.) In this
2202 * case, the second parameter should be set to true and a list
2203 * of reasons supplied as the third parameter.
2205 * @todo Needs to be split into multiple functions.
2207 * @param $source String: source code to show (or null).
2208 * @param $protected Boolean: is this a permissions error?
2209 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
2210 * @param $action String: action that was denied or null if unknown
2212 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
2213 $this->setRobotPolicy( 'noindex,nofollow' );
2214 $this->setArticleRelated( false );
2216 // If no reason is given, just supply a default "I can't let you do
2217 // that, Dave" message. Should only occur if called by legacy code.
2218 if ( $protected && empty( $reasons ) ) {
2219 $reasons[] = array( 'badaccess-group0' );
2222 if ( !empty( $reasons ) ) {
2223 // Permissions error
2225 $this->setPageTitle( $this->msg( 'viewsource-title', $this->getTitle()->getPrefixedText() ) );
2226 $this->addBacklinkSubtitle( $this->getTitle() );
2228 $this->setPageTitle( $this->msg( 'badaccess' ) );
2230 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2232 // Wiki is read only
2233 throw new ReadOnlyError
;
2236 // Show source, if supplied
2237 if( is_string( $source ) ) {
2238 $this->addWikiMsg( 'viewsourcetext' );
2240 $pageLang = $this->getTitle()->getPageLanguage();
2242 'id' => 'wpTextbox1',
2243 'name' => 'wpTextbox1',
2244 'cols' => $this->getUser()->getOption( 'cols' ),
2245 'rows' => $this->getUser()->getOption( 'rows' ),
2246 'readonly' => 'readonly',
2247 'lang' => $pageLang->getHtmlCode(),
2248 'dir' => $pageLang->getDir(),
2250 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
2252 // Show templates used by this article
2253 $page = WikiPage
::factory( $this->getTitle() );
2254 $templates = Linker
::formatTemplates( $page->getUsedTemplates() );
2255 $this->addHTML( "<div class='templatesUsed'>
2261 # If the title doesn't exist, it's fairly pointless to print a return
2262 # link to it. After all, you just tried editing it and couldn't, so
2263 # what's there to do there?
2264 if( $this->getTitle()->exists() ) {
2265 $this->returnToMain( null, $this->getTitle() );
2270 * Turn off regular page output and return an error reponse
2271 * for when rate limiting has triggered.
2273 public function rateLimited() {
2274 throw new ThrottledError
;
2278 * Show a warning about slave lag
2280 * If the lag is higher than $wgSlaveLagCritical seconds,
2281 * then the warning is a bit more obvious. If the lag is
2282 * lower than $wgSlaveLagWarning, then no warning is shown.
2284 * @param $lag Integer: slave lag
2286 public function showLagWarning( $lag ) {
2287 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2288 if( $lag >= $wgSlaveLagWarning ) {
2289 $message = $lag < $wgSlaveLagCritical
2292 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2293 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2297 public function showFatalError( $message ) {
2298 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2300 $this->addHTML( $message );
2303 public function showUnexpectedValueError( $name, $val ) {
2304 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2307 public function showFileCopyError( $old, $new ) {
2308 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2311 public function showFileRenameError( $old, $new ) {
2312 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2315 public function showFileDeleteError( $name ) {
2316 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2319 public function showFileNotFoundError( $name ) {
2320 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2324 * Add a "return to" link pointing to a specified title
2326 * @param $title Title to link
2327 * @param $query String query string
2328 * @param $text String text of the link (input is not escaped)
2330 public function addReturnTo( $title, $query = array(), $text = null ) {
2331 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL() ) );
2332 $link = $this->msg( 'returnto' )->rawParams(
2333 Linker
::link( $title, $text, array(), $query ) )->escaped();
2334 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2338 * Add a "return to" link pointing to a specified title,
2339 * or the title indicated in the request, or else the main page
2341 * @param $unused No longer used
2342 * @param $returnto Title or String to return to
2343 * @param $returntoquery String: query string for the return to link
2345 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2346 if ( $returnto == null ) {
2347 $returnto = $this->getRequest()->getText( 'returnto' );
2350 if ( $returntoquery == null ) {
2351 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2354 if ( $returnto === '' ) {
2355 $returnto = Title
::newMainPage();
2358 if ( is_object( $returnto ) ) {
2359 $titleObj = $returnto;
2361 $titleObj = Title
::newFromText( $returnto );
2363 if ( !is_object( $titleObj ) ) {
2364 $titleObj = Title
::newMainPage();
2367 $this->addReturnTo( $titleObj, $returntoquery );
2371 * @param $sk Skin The given Skin
2372 * @param $includeStyle Boolean: unused
2373 * @return String: The doctype, opening <html>, and head element.
2375 public function headElement( Skin
$sk, $includeStyle = true ) {
2377 $userdir = $this->getLanguage()->getDir();
2378 $sitedir = $wgContLang->getDir();
2380 if ( $sk->commonPrintStylesheet() ) {
2381 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2384 $ret = Html
::htmlHeader( array( 'lang' => $this->getLanguage()->getHtmlCode(), 'dir' => $userdir, 'class' => 'client-nojs' ) );
2386 if ( $this->getHTMLTitle() == '' ) {
2387 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() ) );
2390 $openHead = Html
::openElement( 'head' );
2392 # Don't bother with the newline if $head == ''
2393 $ret .= "$openHead\n";
2396 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2398 $ret .= implode( "\n", array(
2399 $this->getHeadLinks( null, true ),
2400 $this->buildCssLinks(),
2401 $this->getHeadScripts(),
2402 $this->getHeadItems()
2405 $closeHead = Html
::closeElement( 'head' );
2407 $ret .= "$closeHead\n";
2410 $bodyAttrs = array();
2412 # Classes for LTR/RTL directionality support
2413 $bodyAttrs['class'] = "mediawiki $userdir sitedir-$sitedir";
2415 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2416 # A <body> class is probably not the best way to do this . . .
2417 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2419 $bodyAttrs['class'] .= ' ' . $sk->getPageClasses( $this->getTitle() );
2420 $bodyAttrs['class'] .= ' skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2422 $sk->addToBodyAttributes( $this, $bodyAttrs ); // Allow skins to add body attributes they need
2423 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2425 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2431 * Add the default ResourceLoader modules to this object
2433 private function addDefaultModules() {
2434 global $wgIncludeLegacyJavaScript, $wgUseAjax, $wgAjaxWatch, $wgEnableMWSuggest;
2436 // Add base resources
2437 $this->addModules( array(
2440 'mediawiki.page.startup',
2441 'mediawiki.page.ready',
2443 if ( $wgIncludeLegacyJavaScript ){
2444 $this->addModules( 'mediawiki.legacy.wikibits' );
2447 // Add various resources if required
2449 $this->addModules( 'mediawiki.legacy.ajax' );
2451 wfRunHooks( 'AjaxAddScript', array( &$this ) );
2453 if( $wgAjaxWatch && $this->getUser()->isLoggedIn() ) {
2454 $this->addModules( 'mediawiki.action.watch.ajax' );
2457 if ( $wgEnableMWSuggest && !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2458 $this->addModules( 'mediawiki.legacy.mwsuggest' );
2462 if ( $this->getUser()->getBoolOption( 'editsectiononrightclick' ) ) {
2463 $this->addModules( 'mediawiki.action.view.rightClickEdit' );
2466 # Crazy edit-on-double-click stuff
2467 if ( $this->isArticle() && $this->getUser()->getOption( 'editondblclick' ) ) {
2468 $this->addModules( 'mediawiki.action.view.dblClickEdit' );
2473 * Get a ResourceLoader object associated with this OutputPage
2475 * @return ResourceLoader
2477 public function getResourceLoader() {
2478 if ( is_null( $this->mResourceLoader
) ) {
2479 $this->mResourceLoader
= new ResourceLoader();
2481 return $this->mResourceLoader
;
2486 * @param $modules Array/string with the module name(s)
2487 * @param $only String ResourceLoaderModule TYPE_ class constant
2488 * @param $useESI boolean
2489 * @param $extraQuery Array with extra query parameters to add to each request. array( param => value )
2490 * @return string html <script> and <style> tags
2492 protected function makeResourceLoaderLink( $modules, $only, $useESI = false, array $extraQuery = array() ) {
2493 global $wgResourceLoaderUseESI, $wgResourceLoaderInlinePrivateModules;
2495 if ( !count( $modules ) ) {
2499 if ( count( $modules ) > 1 ) {
2500 // Remove duplicate module requests
2501 $modules = array_unique( (array) $modules );
2502 // Sort module names so requests are more uniform
2505 if ( ResourceLoader
::inDebugMode() ) {
2506 // Recursively call us for every item
2508 foreach ( $modules as $name ) {
2509 $links .= $this->makeResourceLoaderLink( $name, $only, $useESI );
2515 // Create keyed-by-group list of module objects from modules list
2517 $resourceLoader = $this->getResourceLoader();
2518 foreach ( (array) $modules as $name ) {
2519 $module = $resourceLoader->getModule( $name );
2520 # Check that we're allowed to include this module on this page
2522 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2523 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2524 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2525 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2531 $group = $module->getGroup();
2532 if ( !isset( $groups[$group] ) ) {
2533 $groups[$group] = array();
2535 $groups[$group][$name] = $module;
2539 foreach ( $groups as $group => $modules ) {
2540 // Special handling for user-specific groups
2542 if ( ( $group === 'user' ||
$group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2543 $user = $this->getUser()->getName();
2546 // Create a fake request based on the one we are about to make so modules return
2547 // correct timestamp and emptiness data
2548 $query = ResourceLoader
::makeLoaderQuery(
2549 array(), // modules; not determined yet
2550 $this->getLanguage()->getCode(),
2551 $this->getSkin()->getSkinName(),
2553 null, // version; not determined yet
2554 ResourceLoader
::inDebugMode(),
2555 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2556 $this->isPrintable(),
2557 $this->getRequest()->getBool( 'handheld' ),
2560 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2561 // Drop modules that know they're empty
2562 foreach ( $modules as $key => $module ) {
2563 if ( $module->isKnownEmpty( $context ) ) {
2564 unset( $modules[$key] );
2567 // If there are no modules left, skip this group
2568 if ( $modules === array() ) {
2572 // Support inlining of private modules if configured as such
2573 if ( $group === 'private' && $wgResourceLoaderInlinePrivateModules ) {
2574 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2575 $links .= Html
::inlineStyle(
2576 $resourceLoader->makeModuleResponse( $context, $modules )
2579 $links .= Html
::inlineScript(
2580 ResourceLoader
::makeLoaderConditionalScript(
2581 $resourceLoader->makeModuleResponse( $context, $modules )
2588 // Special handling for the user group; because users might change their stuff
2589 // on-wiki like user pages, or user preferences; we need to find the highest
2590 // timestamp of these user-changable modules so we can ensure cache misses on change
2591 // This should NOT be done for the site group (bug 27564) because anons get that too
2592 // and we shouldn't be putting timestamps in Squid-cached HTML
2594 if ( $group === 'user' ) {
2595 // Get the maximum timestamp
2597 foreach ( $modules as $module ) {
2598 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2600 // Add a version parameter so cache will break when things change
2601 $version = wfTimestamp( TS_ISO_8601_BASIC
, $timestamp );
2604 $url = ResourceLoader
::makeLoaderURL(
2605 array_keys( $modules ),
2606 $this->getLanguage()->getCode(),
2607 $this->getSkin()->getSkinName(),
2610 ResourceLoader
::inDebugMode(),
2611 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2612 $this->isPrintable(),
2613 $this->getRequest()->getBool( 'handheld' ),
2616 if ( $useESI && $wgResourceLoaderUseESI ) {
2617 $esi = Xml
::element( 'esi:include', array( 'src' => $url ) );
2618 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2619 $link = Html
::inlineStyle( $esi );
2621 $link = Html
::inlineScript( $esi );
2624 // Automatically select style/script elements
2625 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2626 $link = Html
::linkedStyle( $url );
2628 $link = Html
::linkedScript( $url );
2632 if( $group == 'noscript' ){
2633 $links .= Html
::rawElement( 'noscript', array(), $link ) . "\n";
2635 $links .= $link . "\n";
2642 * JS stuff to put in the <head>. This is the startup module, config
2643 * vars and modules marked with position 'top'
2645 * @return String: HTML fragment
2647 function getHeadScripts() {
2648 // Startup - this will immediately load jquery and mediawiki modules
2649 $scripts = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
, true );
2651 // Load config before anything else
2652 $scripts .= Html
::inlineScript(
2653 ResourceLoader
::makeLoaderConditionalScript(
2654 ResourceLoader
::makeConfigSetScript( $this->getJSVars() )
2658 // Script and Messages "only" requests marked for top inclusion
2659 // Messages should go first
2660 $scripts .= $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'top' ), ResourceLoaderModule
::TYPE_MESSAGES
);
2661 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'top' ), ResourceLoaderModule
::TYPE_SCRIPTS
);
2663 // Modules requests - let the client calculate dependencies and batch requests as it likes
2664 // Only load modules that have marked themselves for loading at the top
2665 $modules = $this->getModules( true, 'top' );
2667 $scripts .= Html
::inlineScript(
2668 ResourceLoader
::makeLoaderConditionalScript(
2669 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
2678 * JS stuff to put at the bottom of the <body>: modules marked with position 'bottom',
2679 * legacy scripts ($this->mScripts), user preferences, site JS and user JS
2683 function getBottomScripts() {
2684 global $wgUseSiteJs, $wgAllowUserJs;
2686 // Script and Messages "only" requests marked for bottom inclusion
2687 // Messages should go first
2688 $scripts = $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'bottom' ), ResourceLoaderModule
::TYPE_MESSAGES
);
2689 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ), ResourceLoaderModule
::TYPE_SCRIPTS
);
2691 // Modules requests - let the client calculate dependencies and batch requests as it likes
2692 // Only load modules that have marked themselves for loading at the bottom
2693 $modules = $this->getModules( true, 'bottom' );
2695 $scripts .= Html
::inlineScript(
2696 ResourceLoader
::makeLoaderConditionalScript(
2697 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
2703 $scripts .= "\n" . $this->mScripts
;
2705 $userScripts = array( 'user.options', 'user.tokens' );
2707 // Add site JS if enabled
2708 if ( $wgUseSiteJs ) {
2709 $scripts .= $this->makeResourceLoaderLink( 'site', ResourceLoaderModule
::TYPE_SCRIPTS
);
2710 if( $this->getUser()->isLoggedIn() ){
2711 $userScripts[] = 'user.groups';
2715 // Add user JS if enabled
2716 if ( $wgAllowUserJs && $this->getUser()->isLoggedIn() ) {
2717 if( $this->getTitle() && $this->getTitle()->isJsSubpage() && $this->userCanPreview() ) {
2718 # XXX: additional security check/prompt?
2719 // We're on a preview of a JS subpage
2720 // Exclude this page from the user module in case it's in there (bug 26283)
2721 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
, false,
2722 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
2724 // Load the previewed JS
2725 $scripts .= Html
::inlineScript( "\n" . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2727 // Include the user module normally
2728 // We can't do $userScripts[] = 'user'; because the user module would end up
2729 // being wrapped in a closure, so load it raw like 'site'
2730 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
);
2733 $scripts .= $this->makeResourceLoaderLink( $userScripts, ResourceLoaderModule
::TYPE_COMBINED
);
2739 * Add one or more variables to be set in mw.config in JavaScript.
2741 * @param $key {String|Array} Key or array of key/value pars.
2742 * @param $value {Mixed} Value of the configuration variable.
2744 public function addJsConfigVars( $keys, $value ) {
2745 if ( is_array( $keys ) ) {
2746 foreach ( $keys as $key => $value ) {
2747 $this->mJsConfigVars
[$key] = $value;
2752 $this->mJsConfigVars
[$keys] = $value;
2757 * Get an array containing the variables to be set in mw.config in JavaScript.
2759 * Do not add things here which can be evaluated in ResourceLoaderStartupScript
2760 * - in other words, page-independent/site-wide variables (without state).
2761 * You will only be adding bloat to the html page and causing page caches to
2762 * have to be purged on configuration changes.
2765 protected function getJSVars() {
2766 global $wgUseAjax, $wgEnableMWSuggest;
2768 $title = $this->getTitle();
2769 $ns = $title->getNamespace();
2770 $nsname = MWNamespace
::exists( $ns ) ? MWNamespace
::getCanonicalName( $ns ) : $title->getNsText();
2771 if ( $ns == NS_SPECIAL
) {
2772 list( $canonicalName, /*...*/ ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
2774 $canonicalName = false; # bug 21115
2777 $lang = $title->getPageLanguage();
2779 // Pre-process information
2780 $separatorTransTable = $lang->separatorTransformTable();
2781 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : array();
2782 $compactSeparatorTransTable = array(
2783 implode( "\t", array_keys( $separatorTransTable ) ),
2784 implode( "\t", $separatorTransTable ),
2786 $digitTransTable = $lang->digitTransformTable();
2787 $digitTransTable = $digitTransTable ?
$digitTransTable : array();
2788 $compactDigitTransTable = array(
2789 implode( "\t", array_keys( $digitTransTable ) ),
2790 implode( "\t", $digitTransTable ),
2794 'wgCanonicalNamespace' => $nsname,
2795 'wgCanonicalSpecialPageName' => $canonicalName,
2796 'wgNamespaceNumber' => $title->getNamespace(),
2797 'wgPageName' => $title->getPrefixedDBKey(),
2798 'wgTitle' => $title->getText(),
2799 'wgCurRevisionId' => $title->getLatestRevID(),
2800 'wgArticleId' => $title->getArticleId(),
2801 'wgIsArticle' => $this->isArticle(),
2802 'wgAction' => $this->getRequest()->getText( 'action', 'view' ),
2803 'wgUserName' => $this->getUser()->isAnon() ?
null : $this->getUser()->getName(),
2804 'wgUserGroups' => $this->getUser()->getEffectiveGroups(),
2805 'wgCategories' => $this->getCategories(),
2806 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
2807 'wgPageContentLanguage' => $lang->getCode(),
2808 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
2809 'wgDigitTransformTable' => $compactDigitTransTable,
2811 if ( $lang->hasVariants() ) {
2812 $vars['wgUserVariant'] = $lang->getPreferredVariant();
2814 foreach ( $title->getRestrictionTypes() as $type ) {
2815 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
2817 if ( $wgUseAjax && $wgEnableMWSuggest && !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2818 $vars['wgSearchNamespaces'] = SearchEngine
::userNamespaces( $this->getUser() );
2820 if ( $title->isMainPage() ) {
2821 $vars['wgIsMainPage'] = true;
2823 if ( $this->mRedirectedFrom
) {
2824 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBKey();
2827 // Allow extensions to add their custom variables to the mw.config map.
2828 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
2829 // page-dependant but site-wide (without state).
2830 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
2831 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
2833 // Merge in variables from addJsConfigVars last
2834 return array_merge( $vars, $this->mJsConfigVars
);
2838 * To make it harder for someone to slip a user a fake
2839 * user-JavaScript or user-CSS preview, a random token
2840 * is associated with the login session. If it's not
2841 * passed back with the preview request, we won't render
2846 public function userCanPreview() {
2847 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
2848 ||
!$this->getRequest()->wasPosted()
2849 ||
!$this->getUser()->matchEditToken(
2850 $this->getRequest()->getVal( 'wpEditToken' ) )
2854 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
2858 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
2862 * @param $unused Unused
2863 * @param $addContentType bool
2865 * @return string HTML tag links to be put in the header.
2867 public function getHeadLinks( $unused = null, $addContentType = false ) {
2868 global $wgUniversalEditButton, $wgFavicon, $wgAppleTouchIcon, $wgEnableAPI,
2869 $wgSitename, $wgVersion, $wgHtml5, $wgMimeType,
2870 $wgFeed, $wgOverrideSiteFeed, $wgAdvertisedFeedTypes,
2871 $wgDisableLangConversion, $wgCanonicalLanguageLinks,
2872 $wgRightsPage, $wgRightsUrl;
2876 if ( $addContentType ) {
2878 # More succinct than <meta http-equiv=Content-Type>, has the
2880 $tags[] = Html
::element( 'meta', array( 'charset' => 'UTF-8' ) );
2882 $tags[] = Html
::element( 'meta', array(
2883 'http-equiv' => 'Content-Type',
2884 'content' => "$wgMimeType; charset=UTF-8"
2886 $tags[] = Html
::element( 'meta', array( // bug 15835
2887 'http-equiv' => 'Content-Style-Type',
2888 'content' => 'text/css'
2893 $tags[] = Html
::element( 'meta', array(
2894 'name' => 'generator',
2895 'content' => "MediaWiki $wgVersion",
2898 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
2899 if( $p !== 'index,follow' ) {
2900 // http://www.robotstxt.org/wc/meta-user.html
2901 // Only show if it's different from the default robots policy
2902 $tags[] = Html
::element( 'meta', array(
2908 if ( count( $this->mKeywords
) > 0 ) {
2910 "/<.*?" . ">/" => '',
2913 $tags[] = Html
::element( 'meta', array(
2914 'name' => 'keywords',
2915 'content' => preg_replace(
2916 array_keys( $strip ),
2917 array_values( $strip ),
2918 implode( ',', $this->mKeywords
)
2923 foreach ( $this->mMetatags
as $tag ) {
2924 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
2926 $tag[0] = substr( $tag[0], 5 );
2930 $tags[] = Html
::element( 'meta',
2933 'content' => $tag[1]
2938 foreach ( $this->mLinktags
as $tag ) {
2939 $tags[] = Html
::element( 'link', $tag );
2942 # Universal edit button
2943 if ( $wgUniversalEditButton && $this->isArticleRelated() ) {
2944 $user = $this->getUser();
2945 if ( $this->getTitle()->quickUserCan( 'edit', $user )
2946 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create', $user ) ) ) {
2947 // Original UniversalEditButton
2948 $msg = $this->msg( 'edit' )->text();
2949 $tags[] = Html
::element( 'link', array(
2950 'rel' => 'alternate',
2951 'type' => 'application/x-wiki',
2953 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
2955 // Alternate edit link
2956 $tags[] = Html
::element( 'link', array(
2959 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
2964 # Generally the order of the favicon and apple-touch-icon links
2965 # should not matter, but Konqueror (3.5.9 at least) incorrectly
2966 # uses whichever one appears later in the HTML source. Make sure
2967 # apple-touch-icon is specified first to avoid this.
2968 if ( $wgAppleTouchIcon !== false ) {
2969 $tags[] = Html
::element( 'link', array( 'rel' => 'apple-touch-icon', 'href' => $wgAppleTouchIcon ) );
2972 if ( $wgFavicon !== false ) {
2973 $tags[] = Html
::element( 'link', array( 'rel' => 'shortcut icon', 'href' => $wgFavicon ) );
2976 # OpenSearch description link
2977 $tags[] = Html
::element( 'link', array(
2979 'type' => 'application/opensearchdescription+xml',
2980 'href' => wfScript( 'opensearch_desc' ),
2981 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
2984 if ( $wgEnableAPI ) {
2985 # Real Simple Discovery link, provides auto-discovery information
2986 # for the MediaWiki API (and potentially additional custom API
2987 # support such as WordPress or Twitter-compatible APIs for a
2988 # blogging extension, etc)
2989 $tags[] = Html
::element( 'link', array(
2991 'type' => 'application/rsd+xml',
2992 // Output a protocol-relative URL here if $wgServer is protocol-relative
2993 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
2994 'href' => wfExpandUrl( wfAppendQuery( wfScript( 'api' ), array( 'action' => 'rsd' ) ), PROTO_RELATIVE
),
3000 if ( !$wgDisableLangConversion && $wgCanonicalLanguageLinks ) {
3001 $lang = $this->getTitle()->getPageLanguage();
3002 if ( $lang->hasVariants() ) {
3004 $urlvar = $lang->getURLVariant();
3007 $variants = $lang->getVariants();
3008 foreach ( $variants as $_v ) {
3009 $tags[] = Html
::element( 'link', array(
3010 'rel' => 'alternate',
3012 'href' => $this->getTitle()->getLocalURL( array( 'variant' => $_v ) ) )
3016 $tags[] = Html
::element( 'link', array(
3017 'rel' => 'canonical',
3018 'href' => $this->getTitle()->getCanonicalUrl()
3026 if ( $wgRightsPage ) {
3027 $copy = Title
::newFromText( $wgRightsPage );
3030 $copyright = $copy->getLocalURL();
3034 if ( !$copyright && $wgRightsUrl ) {
3035 $copyright = $wgRightsUrl;
3039 $tags[] = Html
::element( 'link', array(
3040 'rel' => 'copyright',
3041 'href' => $copyright )
3047 foreach( $this->getSyndicationLinks() as $format => $link ) {
3048 # Use the page name for the title. In principle, this could
3049 # lead to issues with having the same name for different feeds
3050 # corresponding to the same page, but we can't avoid that at
3053 $tags[] = $this->feedLink(
3056 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3057 $this->msg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )->text()
3061 # Recent changes feed should appear on every page (except recentchanges,
3062 # that would be redundant). Put it after the per-page feed to avoid
3063 # changing existing behavior. It's still available, probably via a
3064 # menu in your browser. Some sites might have a different feed they'd
3065 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3066 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3067 # If so, use it instead.
3068 if ( $wgOverrideSiteFeed ) {
3069 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
3070 // Note, this->feedLink escapes the url.
3071 $tags[] = $this->feedLink(
3074 $this->msg( "site-{$type}-feed", $wgSitename )->text()
3077 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3078 foreach ( $wgAdvertisedFeedTypes as $format ) {
3079 $tags[] = $this->feedLink(
3081 $this->getTitle()->getLocalURL( "feed={$format}" ),
3082 $this->msg( "site-{$format}-feed", $wgSitename )->text() # For grep: 'site-rss-feed', 'site-atom-feed'.
3087 return implode( "\n", $tags );
3091 * Generate a <link rel/> for a feed.
3093 * @param $type String: feed type
3094 * @param $url String: URL to the feed
3095 * @param $text String: value of the "title" attribute
3096 * @return String: HTML fragment
3098 private function feedLink( $type, $url, $text ) {
3099 return Html
::element( 'link', array(
3100 'rel' => 'alternate',
3101 'type' => "application/$type+xml",
3108 * Add a local or specified stylesheet, with the given media options.
3109 * Meant primarily for internal use...
3111 * @param $style String: URL to the file
3112 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
3113 * @param $condition String: for IE conditional comments, specifying an IE version
3114 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
3116 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3118 // Even though we expect the media type to be lowercase, but here we
3119 // force it to lowercase to be safe.
3121 $options['media'] = $media;
3124 $options['condition'] = $condition;
3127 $options['dir'] = $dir;
3129 $this->styles
[$style] = $options;
3133 * Adds inline CSS styles
3134 * @param $style_css Mixed: inline CSS
3135 * @param $flip String: Set to 'flip' to flip the CSS if needed
3137 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3138 if( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3139 # If wanted, and the interface is right-to-left, flip the CSS
3140 $style_css = CSSJanus
::transform( $style_css, true, false );
3142 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3146 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
3147 * These will be applied to various media & IE conditionals.
3151 public function buildCssLinks() {
3152 global $wgUseSiteCss, $wgAllowUserCss, $wgAllowUserCssPrefs;
3154 $this->getSkin()->setupSkinUserCss( $this );
3156 // Add ResourceLoader styles
3157 // Split the styles into four groups
3158 $styles = array( 'other' => array(), 'user' => array(), 'site' => array(), 'private' => array(), 'noscript' => array() );
3159 $otherTags = ''; // Tags to append after the normal <link> tags
3160 $resourceLoader = $this->getResourceLoader();
3162 $moduleStyles = $this->getModuleStyles();
3164 // Per-site custom styles
3165 if ( $wgUseSiteCss ) {
3166 $moduleStyles[] = 'site';
3167 $moduleStyles[] = 'noscript';
3168 if( $this->getUser()->isLoggedIn() ){
3169 $moduleStyles[] = 'user.groups';
3173 // Per-user custom styles
3174 if ( $wgAllowUserCss ) {
3175 if ( $this->getTitle()->isCssSubpage() && $this->userCanPreview() ) {
3176 // We're on a preview of a CSS subpage
3177 // Exclude this page from the user module in case it's in there (bug 26283)
3178 $otherTags .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_STYLES
, false,
3179 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3181 // Load the previewed CSS
3182 $otherTags .= Html
::inlineStyle( $this->getRequest()->getText( 'wpTextbox1' ) );
3184 // Load the user styles normally
3185 $moduleStyles[] = 'user';
3189 // Per-user preference styles
3190 if ( $wgAllowUserCssPrefs ) {
3191 $moduleStyles[] = 'user.options';
3194 foreach ( $moduleStyles as $name ) {
3195 $module = $resourceLoader->getModule( $name );
3199 $group = $module->getGroup();
3200 // Modules in groups named "other" or anything different than "user", "site" or "private"
3201 // will be placed in the "other" group
3202 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
3205 // We want site, private and user styles to override dynamically added styles from modules, but we want
3206 // dynamically added styles to override statically added styles from other modules. So the order
3207 // has to be other, dynamic, site, private, user
3208 // Add statically added styles for other modules
3209 $ret = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule
::TYPE_STYLES
);
3210 // Add normal styles added through addStyle()/addInlineStyle() here
3211 $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3212 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3213 // We use a <meta> tag with a made-up name for this because that's valid HTML
3214 $ret .= Html
::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) ) . "\n";
3216 // Add site, private and user styles
3217 // 'private' at present only contains user.options, so put that before 'user'
3218 // Any future private modules will likely have a similar user-specific character
3219 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3220 $ret .= $this->makeResourceLoaderLink( $styles[$group],
3221 ResourceLoaderModule
::TYPE_STYLES
3225 // Add stuff in $otherTags (previewed user CSS if applicable)
3233 public function buildCssLinksArray() {
3236 // Add any extension CSS
3237 foreach ( $this->mExtStyles
as $url ) {
3238 $this->addStyle( $url );
3240 $this->mExtStyles
= array();
3242 foreach( $this->styles
as $file => $options ) {
3243 $link = $this->styleLink( $file, $options );
3245 $links[$file] = $link;
3252 * Generate \<link\> tags for stylesheets
3254 * @param $style String: URL to the file
3255 * @param $options Array: option, can contain 'condition', 'dir', 'media'
3257 * @return String: HTML fragment
3259 protected function styleLink( $style, $options ) {
3260 if( isset( $options['dir'] ) ) {
3261 if( $this->getLanguage()->getDir() != $options['dir'] ) {
3266 if( isset( $options['media'] ) ) {
3267 $media = self
::transformCssMedia( $options['media'] );
3268 if( is_null( $media ) ) {
3275 if( substr( $style, 0, 1 ) == '/' ||
3276 substr( $style, 0, 5 ) == 'http:' ||
3277 substr( $style, 0, 6 ) == 'https:' ) {
3280 global $wgStylePath, $wgStyleVersion;
3281 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
3284 $link = Html
::linkedStyle( $url, $media );
3286 if( isset( $options['condition'] ) ) {
3287 $condition = htmlspecialchars( $options['condition'] );
3288 $link = "<!--[if $condition]>$link<![endif]-->";
3294 * Transform "media" attribute based on request parameters
3296 * @param $media String: current value of the "media" attribute
3297 * @return String: modified value of the "media" attribute
3299 public static function transformCssMedia( $media ) {
3300 global $wgRequest, $wgHandheldForIPhone;
3302 // Switch in on-screen display for media testing
3304 'printable' => 'print',
3305 'handheld' => 'handheld',
3307 foreach( $switches as $switch => $targetMedia ) {
3308 if( $wgRequest->getBool( $switch ) ) {
3309 if( $media == $targetMedia ) {
3311 } elseif( $media == 'screen' ) {
3317 // Expand longer media queries as iPhone doesn't grok 'handheld'
3318 if( $wgHandheldForIPhone ) {
3319 $mediaAliases = array(
3320 'screen' => 'screen and (min-device-width: 481px)',
3321 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
3324 if( isset( $mediaAliases[$media] ) ) {
3325 $media = $mediaAliases[$media];
3333 * Add a wikitext-formatted message to the output.
3334 * This is equivalent to:
3336 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
3338 public function addWikiMsg( /*...*/ ) {
3339 $args = func_get_args();
3340 $name = array_shift( $args );
3341 $this->addWikiMsgArray( $name, $args );
3345 * Add a wikitext-formatted message to the output.
3346 * Like addWikiMsg() except the parameters are taken as an array
3347 * instead of a variable argument list.
3349 * @param $name string
3350 * @param $args array
3352 public function addWikiMsgArray( $name, $args ) {
3353 $this->addWikiText( $this->msg( $name, $args )->plain() );
3357 * This function takes a number of message/argument specifications, wraps them in
3358 * some overall structure, and then parses the result and adds it to the output.
3360 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3361 * on. The subsequent arguments may either be strings, in which case they are the
3362 * message names, or arrays, in which case the first element is the message name,
3363 * and subsequent elements are the parameters to that message.
3365 * The special named parameter 'options' in a message specification array is passed
3366 * through to the $options parameter of wfMsgExt().
3368 * Don't use this for messages that are not in users interface language.
3372 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3376 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . "\n</div>" );
3378 * The newline after opening div is needed in some wikitext. See bug 19226.
3380 * @param $wrap string
3382 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3383 $msgSpecs = func_get_args();
3384 array_shift( $msgSpecs );
3385 $msgSpecs = array_values( $msgSpecs );
3387 foreach ( $msgSpecs as $n => $spec ) {
3389 if ( is_array( $spec ) ) {
3391 $name = array_shift( $args );
3392 if ( isset( $args['options'] ) ) {
3393 $options = $args['options'];
3394 unset( $args['options'] );
3400 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
3402 $this->addWikiText( $s );
3406 * Include jQuery core. Use this to avoid loading it multiple times
3407 * before we get a usable script loader.
3409 * @param $modules Array: list of jQuery modules which should be loaded
3410 * @return Array: the list of modules which were not loaded.
3412 * @deprecated since 1.17
3414 public function includeJQuery( $modules = array() ) {