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_MESSAGES
= 'messages';
33 const TYPE_COMBINED
= 'combined';
35 # sitewide core module like a skin file or jQuery component
36 const ORIGIN_CORE_SITEWIDE
= 1;
38 # per-user module generated by the software
39 const ORIGIN_CORE_INDIVIDUAL
= 2;
41 # sitewide module generated from user-editable files, like MediaWiki:Common.js, or
42 # modules accessible to multiple users, such as those generated by the Gadgets extension.
43 const ORIGIN_USER_SITEWIDE
= 3;
45 # per-user module generated from user-editable files, like User:Me/vector.js
46 const ORIGIN_USER_INDIVIDUAL
= 4;
48 # an access constant; make sure this is kept as the largest number in this group
49 const ORIGIN_ALL
= 10;
51 # script and style modules form a hierarchy of trustworthiness, with core modules like
52 # skins and jQuery as most trustworthy, and user scripts as least trustworthy. We can
53 # limit the types of scripts and styles we allow to load on, say, sensitive special
54 # pages like Special:UserLogin and Special:Preferences
55 protected $origin = self
::ORIGIN_CORE_SITEWIDE
;
57 /* Protected Members */
59 protected $name = null;
60 protected $targets = array( 'desktop' );
62 // In-object cache for file dependencies
63 protected $fileDeps = array();
64 // In-object cache for message blob mtime
65 protected $msgBlobMtime = array();
70 * Get this module's name. This is set when the module is registered
71 * with ResourceLoader::register()
73 * @return string|null Name (string) or null if no name was set
75 public function getName() {
80 * Set this module's name. This is called by ResourceLoader::register()
81 * when registering the module. Other code should not call this.
83 * @param string $name Name
85 public function setName( $name ) {
90 * Get this module's origin. This is set when the module is registered
91 * with ResourceLoader::register()
93 * @return int ResourceLoaderModule class constant, the subclass default
96 public function getOrigin() {
101 * Set this module's origin. This is called by ResourceLoader::register()
102 * when registering the module. Other code should not call this.
104 * @param int $origin Origin
106 public function setOrigin( $origin ) {
107 $this->origin
= $origin;
111 * @param ResourceLoaderContext $context
114 public function getFlip( $context ) {
117 return $wgContLang->getDir() !== $context->getDirection();
121 * Get all JS for this module for a given language and skin.
122 * Includes all relevant JS except loader scripts.
124 * @param ResourceLoaderContext $context
125 * @return string JavaScript code
127 public function getScript( ResourceLoaderContext
$context ) {
128 // Stub, override expected
133 * Get the URL or URLs to load for this module's JS in debug mode.
134 * The default behavior is to return a load.php?only=scripts URL for
135 * the module, but file-based modules will want to override this to
136 * load the files directly.
138 * This function is called only when 1) we're in debug mode, 2) there
139 * is no only= parameter and 3) supportsURLLoading() returns true.
140 * #2 is important to prevent an infinite loop, therefore this function
141 * MUST return either an only= URL or a non-load.php URL.
143 * @param ResourceLoaderContext $context
144 * @return array Array of URLs
146 public function getScriptURLsForDebug( ResourceLoaderContext
$context ) {
147 $resourceLoader = $context->getResourceLoader();
148 $derivative = new DerivativeResourceLoaderContext( $context );
149 $derivative->setModules( array( $this->getName() ) );
150 $derivative->setOnly( 'scripts' );
151 $derivative->setDebug( true );
153 $url = $resourceLoader->createLoaderURL(
158 return array( $url );
162 * Whether this module supports URL loading. If this function returns false,
163 * getScript() will be used even in cases (debug mode, no only param) where
164 * getScriptURLsForDebug() would normally be used instead.
167 public function supportsURLLoading() {
172 * Get all CSS for this module for a given skin.
174 * @param ResourceLoaderContext $context
175 * @return array List of CSS strings or array of CSS strings keyed by media type.
176 * like array( 'screen' => '.foo { width: 0 }' );
177 * or array( 'screen' => array( '.foo { width: 0 }' ) );
179 public function getStyles( ResourceLoaderContext
$context ) {
180 // Stub, override expected
185 * Get the URL or URLs to load for this module's CSS in debug mode.
186 * The default behavior is to return a load.php?only=styles URL for
187 * the module, but file-based modules will want to override this to
188 * load the files directly. See also getScriptURLsForDebug()
190 * @param ResourceLoaderContext $context
191 * @return array Array( mediaType => array( URL1, URL2, ... ), ... )
193 public function getStyleURLsForDebug( ResourceLoaderContext
$context ) {
194 $resourceLoader = $context->getResourceLoader();
195 $derivative = new DerivativeResourceLoaderContext( $context );
196 $derivative->setModules( array( $this->getName() ) );
197 $derivative->setOnly( 'styles' );
198 $derivative->setDebug( true );
200 $url = $resourceLoader->createLoaderURL(
205 return array( 'all' => array( $url ) );
209 * Get the messages needed for this module.
211 * To get a JSON blob with messages, use MessageBlobStore::get()
213 * @return array List of message keys. Keys may occur more than once
215 public function getMessages() {
216 // Stub, override expected
221 * Get the group this module is in.
223 * @return string Group name
225 public function getGroup() {
226 // Stub, override expected
231 * Get the origin of this module. Should only be overridden for foreign modules.
233 * @return string Origin name, 'local' for local modules
235 public function getSource() {
236 // Stub, override expected
241 * Where on the HTML page should this module's JS be loaded?
242 * - 'top': in the "<head>"
243 * - 'bottom': at the bottom of the "<body>"
247 public function getPosition() {
252 * Whether this module's JS expects to work without the client-side ResourceLoader module.
253 * Returning true from this function will prevent mw.loader.state() call from being
254 * appended to the bottom of the script.
258 public function isRaw() {
263 * Get the loader JS for this module, if set.
265 * @return mixed JavaScript loader code as a string or boolean false if no custom loader set
267 public function getLoaderScript() {
268 // Stub, override expected
273 * Get a list of modules this module depends on.
275 * Dependency information is taken into account when loading a module
276 * on the client side.
278 * To add dependencies dynamically on the client side, use a custom
279 * loader script, see getLoaderScript()
280 * @return array List of module names as strings
282 public function getDependencies() {
283 // Stub, override expected
288 * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
290 * @return array Array of strings
292 public function getTargets() {
293 return $this->targets
;
297 * Get the skip function.
299 * Modules that provide fallback functionality can provide a "skip function". This
300 * function, if provided, will be passed along to the module registry on the client.
301 * When this module is loaded (either directly or as a dependency of another module),
302 * then this function is executed first. If the function returns true, the module will
303 * instantly be considered "ready" without requesting the associated module resources.
305 * The value returned here must be valid javascript for execution in a private function.
306 * It must not contain the "function () {" and "}" wrapper though.
308 * @return string|null A JavaScript function body returning a boolean value, or null
310 public function getSkipFunction() {
315 * Get the files this module depends on indirectly for a given skin.
316 * Currently these are only image files referenced by the module's CSS.
318 * @param string $skin Skin name
319 * @return array List of files
321 public function getFileDependencies( $skin ) {
322 // Try in-object cache first
323 if ( isset( $this->fileDeps
[$skin] ) ) {
324 return $this->fileDeps
[$skin];
327 $dbr = wfGetDB( DB_SLAVE
);
328 $deps = $dbr->selectField( 'module_deps', 'md_deps', array(
329 'md_module' => $this->getName(),
333 if ( !is_null( $deps ) ) {
334 $this->fileDeps
[$skin] = (array)FormatJson
::decode( $deps, true );
336 $this->fileDeps
[$skin] = array();
338 return $this->fileDeps
[$skin];
342 * Set preloaded file dependency information. Used so we can load this
343 * information for all modules at once.
344 * @param string $skin Skin name
345 * @param array $deps Array of file names
347 public function setFileDependencies( $skin, $deps ) {
348 $this->fileDeps
[$skin] = $deps;
352 * Get the last modification timestamp of the message blob for this
353 * module in a given language.
354 * @param string $lang Language code
355 * @return int UNIX timestamp, or 0 if the module doesn't have messages
357 public function getMsgBlobMtime( $lang ) {
358 if ( !isset( $this->msgBlobMtime
[$lang] ) ) {
359 if ( !count( $this->getMessages() ) ) {
363 $dbr = wfGetDB( DB_SLAVE
);
364 $msgBlobMtime = $dbr->selectField( 'msg_resource', 'mr_timestamp', array(
365 'mr_resource' => $this->getName(),
369 // If no blob was found, but the module does have messages, that means we need
370 // to regenerate it. Return NOW
371 if ( $msgBlobMtime === false ) {
372 $msgBlobMtime = wfTimestampNow();
374 $this->msgBlobMtime
[$lang] = wfTimestamp( TS_UNIX
, $msgBlobMtime );
376 return $this->msgBlobMtime
[$lang];
380 * Set a preloaded message blob last modification timestamp. Used so we
381 * can load this information for all modules at once.
382 * @param string $lang Language code
383 * @param int $mtime UNIX timestamp or 0 if there is no such blob
385 public function setMsgBlobMtime( $lang, $mtime ) {
386 $this->msgBlobMtime
[$lang] = $mtime;
389 /* Abstract Methods */
392 * Get this module's last modification timestamp for a given
393 * combination of language, skin and debug mode flag. This is typically
394 * the highest of each of the relevant components' modification
395 * timestamps. Whenever anything happens that changes the module's
396 * contents for these parameters, the mtime should increase.
398 * NOTE: The mtime of the module's messages is NOT automatically included.
399 * If you want this to happen, you'll need to call getMsgBlobMtime()
400 * yourself and take its result into consideration.
402 * NOTE: The mtime of the module's hash is NOT automatically included.
403 * If your module provides a getModifiedHash() method, you'll need to call getHashMtime()
404 * yourself and take its result into consideration.
406 * @param ResourceLoaderContext $context Context object
407 * @return int UNIX timestamp
409 public function getModifiedTime( ResourceLoaderContext
$context ) {
415 * Helper method for calculating when the module's hash (if it has one) changed.
417 * @param ResourceLoaderContext $context
418 * @return int UNIX timestamp or 0 if no hash was provided
419 * by getModifiedHash()
421 public function getHashMtime( ResourceLoaderContext
$context ) {
422 $hash = $this->getModifiedHash( $context );
423 if ( !is_string( $hash ) ) {
427 $cache = wfGetCache( CACHE_ANYTHING
);
428 $key = wfMemcKey( 'resourceloader', 'modulemodifiedhash', $this->getName(), $hash );
430 $data = $cache->get( $key );
431 if ( is_array( $data ) && $data['hash'] === $hash ) {
432 // Hash is still the same, re-use the timestamp of when we first saw this hash.
433 return $data['timestamp'];
436 $timestamp = wfTimestamp();
437 $cache->set( $key, array(
439 'timestamp' => $timestamp,
446 * Get the hash for whatever this module may contain.
448 * This is the method subclasses should implement if they want to make
449 * use of getHashMTime() inside getModifiedTime().
451 * @param ResourceLoaderContext $context
452 * @return string|null Hash
454 public function getModifiedHash( ResourceLoaderContext
$context ) {
459 * Helper method for calculating when this module's definition summary was last changed.
463 * @return int UNIX timestamp or 0 if no definition summary was provided
464 * by getDefinitionSummary()
466 public function getDefinitionMtime( ResourceLoaderContext
$context ) {
467 wfProfileIn( __METHOD__
);
468 $summary = $this->getDefinitionSummary( $context );
469 if ( $summary === null ) {
470 wfProfileOut( __METHOD__
);
474 $hash = md5( json_encode( $summary ) );
476 $cache = wfGetCache( CACHE_ANYTHING
);
478 // Embed the hash itself in the cache key. This allows for a few nifty things:
479 // - During deployment, servers with old and new versions of the code communicating
480 // with the same memcached will not override the same key repeatedly increasing
482 // - In case of the definition changing and then changing back in a short period of time
483 // (e.g. in case of a revert or a corrupt server) the old timestamp and client-side cache
484 // url will be re-used.
485 // - If different context-combinations (e.g. same skin, same language or some combination
486 // thereof) result in the same definition, they will use the same hash and timestamp.
487 $key = wfMemcKey( 'resourceloader', 'moduledefinition', $this->getName(), $hash );
489 $data = $cache->get( $key );
490 if ( is_int( $data ) && $data > 0 ) {
491 // We've seen this hash before, re-use the timestamp of when we first saw it.
492 wfProfileOut( __METHOD__
);
496 wfDebugLog( 'resourceloader', __METHOD__
. ": New definition hash for module "
497 . "{$this->getName()} in context {$context->getHash()}: $hash." );
500 $cache->set( $key, $timestamp );
502 wfProfileOut( __METHOD__
);
507 * Get the definition summary for this module.
509 * This is the method subclasses should implement if they want to make
510 * use of getDefinitionMTime() inside getModifiedTime().
512 * Return an array containing values from all significant properties of this
513 * module's definition. Be sure to include things that are explicitly ordered,
514 * in their actaul order (bug 37812).
516 * Avoid including things that are insiginificant (e.g. order of message
517 * keys is insignificant and should be sorted to avoid unnecessary cache
520 * Avoid including things already considered by other methods inside your
521 * getModifiedTime(), such as file mtime timestamps.
523 * Serialisation is done using json_encode, which means object state is not
524 * taken into account when building the hash. This data structure must only
525 * contain arrays and scalars as values (avoid object instances) which means
526 * it requires abstraction.
532 public function getDefinitionSummary( ResourceLoaderContext
$context ) {
534 'class' => get_class( $this ),
539 * Check whether this module is known to be empty. If a child class
540 * has an easy and cheap way to determine that this module is
541 * definitely going to be empty, it should override this method to
542 * return true in that case. Callers may optimize the request for this
543 * module away if this function returns true.
544 * @param ResourceLoaderContext $context
547 public function isKnownEmpty( ResourceLoaderContext
$context ) {
551 /** @var JSParser Lazy-initialized; use self::javaScriptParser() */
552 private static $jsParser;
553 private static $parseCacheVersion = 1;
556 * Validate a given script file; if valid returns the original source.
557 * If invalid, returns replacement JS source that throws an exception.
559 * @param string $fileName
560 * @param string $contents
561 * @return string JS with the original, or a replacement error
563 protected function validateScriptFile( $fileName, $contents ) {
564 global $wgResourceLoaderValidateJS;
565 if ( $wgResourceLoaderValidateJS ) {
567 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
568 $key = wfMemcKey( 'resourceloader', 'jsparse', self
::$parseCacheVersion, md5( $contents ) );
569 $cache = wfGetCache( CACHE_ANYTHING
);
570 $cacheEntry = $cache->get( $key );
571 if ( is_string( $cacheEntry ) ) {
575 $parser = self
::javaScriptParser();
577 $parser->parse( $contents, $fileName, 1 );
579 } catch ( Exception
$e ) {
580 // We'll save this to cache to avoid having to validate broken JS over and over...
581 $err = $e->getMessage();
582 $result = "throw new Error(" . Xml
::encodeJsVar( "JavaScript parse error: $err" ) . ");";
585 $cache->set( $key, $result );
595 protected static function javaScriptParser() {
596 if ( !self
::$jsParser ) {
597 self
::$jsParser = new JSParser();
599 return self
::$jsParser;
603 * Safe version of filemtime(), which doesn't throw a PHP warning if the file doesn't exist
604 * but returns 1 instead.
605 * @param string $filename File name
606 * @return int UNIX timestamp, or 1 if the file doesn't exist
608 protected static function safeFilemtime( $filename ) {
609 if ( file_exists( $filename ) ) {
610 return filemtime( $filename );
612 // We only ever map this function on an array if we're gonna call max() after,
613 // so return our standard minimum timestamps here. This is 1, not 0, because
614 // wfTimestamp(0) == NOW