3 * Abstraction for resource loader modules.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @author Trevor Parscal
22 * @author Roan Kattouw
26 * Abstraction for resource loader modules, with name registration and maxage functionality.
28 abstract class ResourceLoaderModule
{
30 const TYPE_SCRIPTS
= 'scripts';
31 const TYPE_STYLES
= 'styles';
32 const TYPE_COMBINED
= 'combined';
34 # sitewide core module like a skin file or jQuery component
35 const ORIGIN_CORE_SITEWIDE
= 1;
37 # per-user module generated by the software
38 const ORIGIN_CORE_INDIVIDUAL
= 2;
40 # sitewide module generated from user-editable files, like MediaWiki:Common.js, or
41 # modules accessible to multiple users, such as those generated by the Gadgets extension.
42 const ORIGIN_USER_SITEWIDE
= 3;
44 # per-user module generated from user-editable files, like User:Me/vector.js
45 const ORIGIN_USER_INDIVIDUAL
= 4;
47 # an access constant; make sure this is kept as the largest number in this group
48 const ORIGIN_ALL
= 10;
50 # script and style modules form a hierarchy of trustworthiness, with core modules like
51 # skins and jQuery as most trustworthy, and user scripts as least trustworthy. We can
52 # limit the types of scripts and styles we allow to load on, say, sensitive special
53 # pages like Special:UserLogin and Special:Preferences
54 protected $origin = self
::ORIGIN_CORE_SITEWIDE
;
56 /* Protected Members */
58 protected $name = null;
59 protected $targets = array( 'desktop' );
61 // In-object cache for file dependencies
62 protected $fileDeps = array();
63 // In-object cache for message blob mtime
64 protected $msgBlobMtime = array();
65 // In-object cache for version hash
66 protected $versionHash = array();
67 // In-object cache for module content
68 protected $contents = array();
70 // Whether the position returned by getPosition() is defined in the module configuration
71 // and not a default value
72 protected $isPositionDefined = false;
82 * Get this module's name. This is set when the module is registered
83 * with ResourceLoader::register()
85 * @return string|null Name (string) or null if no name was set
87 public function getName() {
92 * Set this module's name. This is called by ResourceLoader::register()
93 * when registering the module. Other code should not call this.
95 * @param string $name Name
97 public function setName( $name ) {
102 * Get this module's origin. This is set when the module is registered
103 * with ResourceLoader::register()
105 * @return int ResourceLoaderModule class constant, the subclass default
106 * if not set manually
108 public function getOrigin() {
109 return $this->origin
;
113 * Set this module's origin. This is called by ResourceLoader::register()
114 * when registering the module. Other code should not call this.
116 * @param int $origin Origin
118 public function setOrigin( $origin ) {
119 $this->origin
= $origin;
123 * @param ResourceLoaderContext $context
126 public function getFlip( $context ) {
129 return $wgContLang->getDir() !== $context->getDirection();
133 * Get all JS for this module for a given language and skin.
134 * Includes all relevant JS except loader scripts.
136 * @param ResourceLoaderContext $context
137 * @return string JavaScript code
139 public function getScript( ResourceLoaderContext
$context ) {
140 // Stub, override expected
145 * Takes named templates by the module and returns an array mapping.
147 * @return array of templates mapping template alias to content
149 public function getTemplates() {
150 // Stub, override expected.
158 public function getConfig() {
159 if ( $this->config
=== null ) {
160 // Ugh, fall back to default
161 $this->config
= ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
164 return $this->config
;
168 * @param Config $config
171 public function setConfig( Config
$config ) {
172 $this->config
= $config;
176 * Get the URL or URLs to load for this module's JS in debug mode.
177 * The default behavior is to return a load.php?only=scripts URL for
178 * the module, but file-based modules will want to override this to
179 * load the files directly.
181 * This function is called only when 1) we're in debug mode, 2) there
182 * is no only= parameter and 3) supportsURLLoading() returns true.
183 * #2 is important to prevent an infinite loop, therefore this function
184 * MUST return either an only= URL or a non-load.php URL.
186 * @param ResourceLoaderContext $context
187 * @return array Array of URLs
189 public function getScriptURLsForDebug( ResourceLoaderContext
$context ) {
190 $resourceLoader = $context->getResourceLoader();
191 $derivative = new DerivativeResourceLoaderContext( $context );
192 $derivative->setModules( array( $this->getName() ) );
193 $derivative->setOnly( 'scripts' );
194 $derivative->setDebug( true );
196 $url = $resourceLoader->createLoaderURL(
201 return array( $url );
205 * Whether this module supports URL loading. If this function returns false,
206 * getScript() will be used even in cases (debug mode, no only param) where
207 * getScriptURLsForDebug() would normally be used instead.
210 public function supportsURLLoading() {
215 * Get all CSS for this module for a given skin.
217 * @param ResourceLoaderContext $context
218 * @return array List of CSS strings or array of CSS strings keyed by media type.
219 * like array( 'screen' => '.foo { width: 0 }' );
220 * or array( 'screen' => array( '.foo { width: 0 }' ) );
222 public function getStyles( ResourceLoaderContext
$context ) {
223 // Stub, override expected
228 * Get the URL or URLs to load for this module's CSS in debug mode.
229 * The default behavior is to return a load.php?only=styles URL for
230 * the module, but file-based modules will want to override this to
231 * load the files directly. See also getScriptURLsForDebug()
233 * @param ResourceLoaderContext $context
234 * @return array Array( mediaType => array( URL1, URL2, ... ), ... )
236 public function getStyleURLsForDebug( ResourceLoaderContext
$context ) {
237 $resourceLoader = $context->getResourceLoader();
238 $derivative = new DerivativeResourceLoaderContext( $context );
239 $derivative->setModules( array( $this->getName() ) );
240 $derivative->setOnly( 'styles' );
241 $derivative->setDebug( true );
243 $url = $resourceLoader->createLoaderURL(
248 return array( 'all' => array( $url ) );
252 * Get the messages needed for this module.
254 * To get a JSON blob with messages, use MessageBlobStore::get()
256 * @return array List of message keys. Keys may occur more than once
258 public function getMessages() {
259 // Stub, override expected
264 * Get the group this module is in.
266 * @return string Group name
268 public function getGroup() {
269 // Stub, override expected
274 * Get the origin of this module. Should only be overridden for foreign modules.
276 * @return string Origin name, 'local' for local modules
278 public function getSource() {
279 // Stub, override expected
284 * Where on the HTML page should this module's JS be loaded?
285 * - 'top': in the "<head>"
286 * - 'bottom': at the bottom of the "<body>"
290 public function getPosition() {
295 * Whether the position returned by getPosition() is a default value or comes from the module
296 * definition. This method is meant to be short-lived, and is only useful until classes added
297 * via addModuleStyles with a default value define an explicit position. See getModuleStyles()
298 * in OutputPage for the related migration warning.
303 public function isPositionDefault() {
304 return !$this->isPositionDefined
;
308 * Whether this module's JS expects to work without the client-side ResourceLoader module.
309 * Returning true from this function will prevent mw.loader.state() call from being
310 * appended to the bottom of the script.
314 public function isRaw() {
319 * Get the loader JS for this module, if set.
321 * @return mixed JavaScript loader code as a string or boolean false if no custom loader set
323 public function getLoaderScript() {
324 // Stub, override expected
329 * Get a list of modules this module depends on.
331 * Dependency information is taken into account when loading a module
332 * on the client side.
334 * To add dependencies dynamically on the client side, use a custom
335 * loader script, see getLoaderScript()
337 * Note: It is expected that $context will be made non-optional in the near
340 * @param ResourceLoaderContext $context
341 * @return array List of module names as strings
343 public function getDependencies( ResourceLoaderContext
$context = null ) {
344 // Stub, override expected
349 * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
351 * @return array Array of strings
353 public function getTargets() {
354 return $this->targets
;
358 * Get the skip function.
360 * Modules that provide fallback functionality can provide a "skip function". This
361 * function, if provided, will be passed along to the module registry on the client.
362 * When this module is loaded (either directly or as a dependency of another module),
363 * then this function is executed first. If the function returns true, the module will
364 * instantly be considered "ready" without requesting the associated module resources.
366 * The value returned here must be valid javascript for execution in a private function.
367 * It must not contain the "function () {" and "}" wrapper though.
369 * @return string|null A JavaScript function body returning a boolean value, or null
371 public function getSkipFunction() {
376 * Get the files this module depends on indirectly for a given skin.
377 * Currently these are only image files referenced by the module's CSS.
379 * @param string $skin Skin name
380 * @return array List of files
382 public function getFileDependencies( $skin ) {
383 // Try in-object cache first
384 if ( isset( $this->fileDeps
[$skin] ) ) {
385 return $this->fileDeps
[$skin];
388 $dbr = wfGetDB( DB_SLAVE
);
389 $deps = $dbr->selectField( 'module_deps',
392 'md_module' => $this->getName(),
398 if ( !is_null( $deps ) ) {
399 $this->fileDeps
[$skin] = (array)FormatJson
::decode( $deps, true );
401 $this->fileDeps
[$skin] = array();
404 return $this->fileDeps
[$skin];
408 * Set preloaded file dependency information. Used so we can load this
409 * information for all modules at once.
410 * @param string $skin Skin name
411 * @param array $deps Array of file names
413 public function setFileDependencies( $skin, $deps ) {
414 $this->fileDeps
[$skin] = $deps;
418 * Get the last modification timestamp of the messages in this module for a given language.
419 * @param string $lang Language code
420 * @return int UNIX timestamp
422 public function getMsgBlobMtime( $lang ) {
423 if ( !isset( $this->msgBlobMtime
[$lang] ) ) {
424 if ( !count( $this->getMessages() ) ) {
428 $dbr = wfGetDB( DB_SLAVE
);
429 $msgBlobMtime = $dbr->selectField( 'msg_resource',
432 'mr_resource' => $this->getName(),
437 // If no blob was found, but the module does have messages, that means we need
438 // to regenerate it. Return NOW
439 if ( $msgBlobMtime === false ) {
440 $msgBlobMtime = wfTimestampNow();
442 $this->msgBlobMtime
[$lang] = wfTimestamp( TS_UNIX
, $msgBlobMtime );
444 return $this->msgBlobMtime
[$lang];
448 * Set a preloaded message blob last modification timestamp. Used so we
449 * can load this information for all modules at once.
450 * @param string $lang Language code
451 * @param int $mtime UNIX timestamp
453 public function setMsgBlobMtime( $lang, $mtime ) {
454 $this->msgBlobMtime
[$lang] = $mtime;
458 * Get an array of this module's resources. Ready for serving to the web.
461 * @param ResourceLoaderContext $context
464 public function getModuleContent( ResourceLoaderContext
$context ) {
465 $contextHash = $context->getHash();
466 // Cache this expensive operation. This calls builds the scripts, styles, and messages
467 // content which typically involves filesystem and/or database access.
468 if ( !array_key_exists( $contextHash, $this->contents
) ) {
469 $this->contents
[$contextHash] = $this->buildContent( $context );
471 return $this->contents
[$contextHash];
475 * Bundle all resources attached to this module into an array.
478 * @param ResourceLoaderContext $context
481 final protected function buildContent( ResourceLoaderContext
$context ) {
482 $rl = $context->getResourceLoader();
483 $stats = RequestContext
::getMain()->getStats();
484 $statStart = microtime( true );
486 // Only include properties that are relevant to this context (e.g. only=scripts)
487 // and that are non-empty (e.g. don't include "templates" for modules without
488 // templates). This helps prevent invalidating cache for all modules when new
489 // optional properties are introduced.
493 if ( $context->shouldIncludeScripts() ) {
494 // If we are in debug mode, we'll want to return an array of URLs if possible
495 // However, we can't do this if the module doesn't support it
496 // We also can't do this if there is an only= parameter, because we have to give
497 // the module a way to return a load.php URL without causing an infinite loop
498 if ( $context->getDebug() && !$context->getOnly() && $this->supportsURLLoading() ) {
499 $scripts = $this->getScriptURLsForDebug( $context );
501 $scripts = $this->getScript( $context );
502 // rtrim() because there are usually a few line breaks
503 // after the last ';'. A new line at EOF, a new line
504 // added by ResourceLoaderFileModule::readScriptFiles, etc.
505 if ( is_string( $scripts )
506 && strlen( $scripts )
507 && substr( rtrim( $scripts ), -1 ) !== ';'
509 // Append semicolon to prevent weird bugs caused by files not
510 // terminating their statements right (bug 27054)
514 $content['scripts'] = $scripts;
518 if ( $context->shouldIncludeStyles() ) {
520 // Don't create empty stylesheets like array( '' => '' ) for modules
521 // that don't *have* any stylesheets (bug 38024).
522 $stylePairs = $this->getStyles( $context );
523 if ( count( $stylePairs ) ) {
524 // If we are in debug mode without &only= set, we'll want to return an array of URLs
525 // See comment near shouldIncludeScripts() for more details
526 if ( $context->getDebug() && !$context->getOnly() && $this->supportsURLLoading() ) {
528 'url' => $this->getStyleURLsForDebug( $context )
531 // Minify CSS before embedding in mw.loader.implement call
532 // (unless in debug mode)
533 if ( !$context->getDebug() ) {
534 foreach ( $stylePairs as $media => $style ) {
535 // Can be either a string or an array of strings.
536 if ( is_array( $style ) ) {
537 $stylePairs[$media] = array();
538 foreach ( $style as $cssText ) {
539 if ( is_string( $cssText ) ) {
540 $stylePairs[$media][] =
541 $rl->filter( 'minify-css', $cssText );
544 } elseif ( is_string( $style ) ) {
545 $stylePairs[$media] = $rl->filter( 'minify-css', $style );
549 // Wrap styles into @media groups as needed and flatten into a numerical array
551 'css' => $rl->makeCombinedStyles( $stylePairs )
555 $content['styles'] = $styles;
559 $blobs = $rl->getMessageBlobStore()->get(
561 array( $this->getName() => $this ),
562 $context->getLanguage()
564 if ( isset( $blobs[$this->getName()] ) ) {
565 $content['messagesBlob'] = $blobs[$this->getName()];
568 $templates = $this->getTemplates();
570 $content['templates'] = $templates;
573 $statTiming = microtime( true ) - $statStart;
574 $statName = strtr( $this->getName(), '.', '_' );
575 $stats->timing( "resourceloader_build.all", $statTiming );
576 $stats->timing( "resourceloader_build.$statName", $statTiming );
582 * Get a string identifying the current version of this module in a given context.
584 * Whenever anything happens that changes the module's response (e.g. scripts, styles, and
585 * messages) this value must change. This value is used to store module responses in cache.
586 * (Both client-side and server-side.)
588 * It is not recommended to override this directly. Use getDefinitionSummary() instead.
589 * If overridden, one must call the parent getVersionHash(), append data and re-hash.
591 * This method should be quick because it is frequently run by ResourceLoaderStartUpModule to
592 * propagate changes to the client and effectively invalidate cache.
594 * For backward-compatibility, the following optional data providers are automatically included:
596 * - getModifiedTime()
597 * - getModifiedHash()
600 * @param ResourceLoaderContext $context
601 * @return string Hash (should use ResourceLoader::makeHash)
603 public function getVersionHash( ResourceLoaderContext
$context ) {
604 // The startup module produces a manifest with versions representing the entire module.
605 // Typically, the request for the startup module itself has only=scripts. That must apply
606 // only to the startup module content, and not to the module version computed here.
607 $context = new DerivativeResourceLoaderContext( $context );
608 $context->setModules( array() );
609 // Version hash must cover all resources, regardless of startup request itself.
610 $context->setOnly( null );
611 // Compute version hash based on content, not debug urls.
612 $context->setDebug( false );
614 // Cache this somewhat expensive operation. Especially because some classes
615 // (e.g. startup module) iterate more than once over all modules to get versions.
616 $contextHash = $context->getHash();
617 if ( !array_key_exists( $contextHash, $this->versionHash
) ) {
619 if ( $this->enableModuleContentVersion() ) {
620 // Detect changes directly
621 $str = json_encode( $this->getModuleContent( $context ) );
623 // Infer changes based on definition and other metrics
624 $summary = $this->getDefinitionSummary( $context );
625 if ( !isset( $summary['_cacheEpoch'] ) ) {
626 throw new LogicException( 'getDefinitionSummary must call parent method' );
628 $str = json_encode( $summary );
630 $mtime = $this->getModifiedTime( $context );
631 if ( $mtime !== null ) {
632 // Support: MediaWiki 1.25 and earlier
633 $str .= strval( $mtime );
636 $mhash = $this->getModifiedHash( $context );
637 if ( $mhash !== null ) {
638 // Support: MediaWiki 1.25 and earlier
639 $str .= strval( $mhash );
643 $this->versionHash
[$contextHash] = ResourceLoader
::makeHash( $str );
645 return $this->versionHash
[$contextHash];
649 * Whether to generate version hash based on module content.
651 * If a module requires database or file system access to build the module
652 * content, consider disabling this in favour of manually tracking relevant
653 * aspects in getDefinitionSummary(). See getVersionHash() for how this is used.
657 public function enableModuleContentVersion() {
662 * Get the definition summary for this module.
664 * This is the method subclasses are recommended to use to track values in their
665 * version hash. Call this in getVersionHash() and pass it to e.g. json_encode.
667 * Subclasses must call the parent getDefinitionSummary() and build on that.
668 * It is recommended that each subclass appends its own new array. This prevents
669 * clashes or accidental overwrites of existing keys and gives each subclass
670 * its own scope for simple array keys.
673 * $summary = parent::getDefinitionSummary( $context );
674 * $summary[] = array(
681 * Return an array containing values from all significant properties of this
682 * module's definition.
684 * Be careful not to normalise too much. Especially preserve the order of things
685 * that carry significance in getScript and getStyles (T39812).
687 * Avoid including things that are insiginificant (e.g. order of message keys is
688 * insignificant and should be sorted to avoid unnecessary cache invalidation).
690 * This data structure must exclusively contain arrays and scalars as values (avoid
691 * object instances) to allow simple serialisation using json_encode.
693 * If modules have a hash or timestamp from another source, that may be incuded as-is.
695 * A number of utility methods are available to help you gather data. These are not
696 * called by default and must be included by the subclass' getDefinitionSummary().
698 * - getMsgBlobMtime()
701 * @param ResourceLoaderContext $context
704 public function getDefinitionSummary( ResourceLoaderContext
$context ) {
706 '_class' => get_class( $this ),
707 '_cacheEpoch' => $this->getConfig()->get( 'CacheEpoch' ),
712 * Get this module's last modification timestamp for a given context.
714 * @deprecated since 1.26 Use getDefinitionSummary() instead
715 * @param ResourceLoaderContext $context Context object
716 * @return int|null UNIX timestamp
718 public function getModifiedTime( ResourceLoaderContext
$context ) {
723 * Helper method for providing a version hash to getVersionHash().
725 * @deprecated since 1.26 Use getDefinitionSummary() instead
726 * @param ResourceLoaderContext $context
727 * @return string|null Hash
729 public function getModifiedHash( ResourceLoaderContext
$context ) {
734 * Back-compat dummy for old subclass implementations of getModifiedTime().
736 * This method used to use ObjectCache to track when a hash was first seen. That principle
737 * stems from a time that ResourceLoader could only identify module versions by timestamp.
738 * That is no longer the case. Use getDefinitionSummary() directly.
740 * @deprecated since 1.26 Superseded by getVersionHash()
741 * @param ResourceLoaderContext $context
742 * @return int UNIX timestamp
744 public function getHashMtime( ResourceLoaderContext
$context ) {
745 if ( !is_string( $this->getModifiedHash( $context ) ) ) {
753 * Back-compat dummy for old subclass implementations of getModifiedTime().
756 * @deprecated since 1.26 Superseded by getVersionHash()
757 * @param ResourceLoaderContext $context
758 * @return int UNIX timestamp
760 public function getDefinitionMtime( ResourceLoaderContext
$context ) {
761 if ( $this->getDefinitionSummary( $context ) === null ) {
769 * Check whether this module is known to be empty. If a child class
770 * has an easy and cheap way to determine that this module is
771 * definitely going to be empty, it should override this method to
772 * return true in that case. Callers may optimize the request for this
773 * module away if this function returns true.
774 * @param ResourceLoaderContext $context
777 public function isKnownEmpty( ResourceLoaderContext
$context ) {
781 /** @var JSParser Lazy-initialized; use self::javaScriptParser() */
782 private static $jsParser;
783 private static $parseCacheVersion = 1;
786 * Validate a given script file; if valid returns the original source.
787 * If invalid, returns replacement JS source that throws an exception.
789 * @param string $fileName
790 * @param string $contents
791 * @return string JS with the original, or a replacement error
793 protected function validateScriptFile( $fileName, $contents ) {
794 if ( $this->getConfig()->get( 'ResourceLoaderValidateJS' ) ) {
796 // Use CACHE_ANYTHING since parsing JS is much slower than a DB query
800 self
::$parseCacheVersion,
803 $cache = wfGetCache( CACHE_ANYTHING
);
804 $cacheEntry = $cache->get( $key );
805 if ( is_string( $cacheEntry ) ) {
809 $parser = self
::javaScriptParser();
811 $parser->parse( $contents, $fileName, 1 );
813 } catch ( Exception
$e ) {
814 // We'll save this to cache to avoid having to validate broken JS over and over...
815 $err = $e->getMessage();
816 $result = "mw.log.error(" .
817 Xml
::encodeJsVar( "JavaScript parse error: $err" ) . ");";
820 $cache->set( $key, $result );
830 protected static function javaScriptParser() {
831 if ( !self
::$jsParser ) {
832 self
::$jsParser = new JSParser();
834 return self
::$jsParser;
838 * Safe version of filemtime(), which doesn't throw a PHP warning if the file doesn't exist.
841 * @param string $filePath File path
842 * @return int UNIX timestamp
844 protected static function safeFilemtime( $filePath ) {
845 MediaWiki\
suppressWarnings();
846 $mtime = filemtime( $filePath ) ?
: 1;
847 MediaWiki\restoreWarnings
();
852 * Safe version of sha1_file(), which doesn't throw a PHP warning if the file doesn't exist.
853 * Defaults to empty string.
855 * @param string $filePath File path
856 * @return string Hash
858 protected static function safeFileHash( $filePath ) {
859 MediaWiki\
suppressWarnings();
860 $hash = sha1_file( $filePath ) ?
: '';
861 MediaWiki\restoreWarnings
();