Merge "DatabaseMssql: Don't duplicate body of makeList()"
[mediawiki.git] / includes / resourceloader / ResourceLoaderModule.php
blob4c2c2b244056a0f89d32be23f47682c98ee83097
1 <?php
2 /**
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
20 * @file
21 * @author Trevor Parscal
22 * @author Roan Kattouw
25 /**
26 * Abstraction for resource loader modules, with name registration and maxage functionality.
28 abstract class ResourceLoaderModule {
29 # Type of resource
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();
67 /**
68 * @var Config
70 protected $config;
72 /* Methods */
74 /**
75 * Get this module's name. This is set when the module is registered
76 * with ResourceLoader::register()
78 * @return string|null Name (string) or null if no name was set
80 public function getName() {
81 return $this->name;
84 /**
85 * Set this module's name. This is called by ResourceLoader::register()
86 * when registering the module. Other code should not call this.
88 * @param string $name Name
90 public function setName( $name ) {
91 $this->name = $name;
94 /**
95 * Get this module's origin. This is set when the module is registered
96 * with ResourceLoader::register()
98 * @return int ResourceLoaderModule class constant, the subclass default
99 * if not set manually
101 public function getOrigin() {
102 return $this->origin;
106 * Set this module's origin. This is called by ResourceLoader::register()
107 * when registering the module. Other code should not call this.
109 * @param int $origin Origin
111 public function setOrigin( $origin ) {
112 $this->origin = $origin;
116 * @param ResourceLoaderContext $context
117 * @return bool
119 public function getFlip( $context ) {
120 global $wgContLang;
122 return $wgContLang->getDir() !== $context->getDirection();
126 * Get all JS for this module for a given language and skin.
127 * Includes all relevant JS except loader scripts.
129 * @param ResourceLoaderContext $context
130 * @return string JavaScript code
132 public function getScript( ResourceLoaderContext $context ) {
133 // Stub, override expected
134 return '';
138 * Takes named templates by the module and returns an array mapping.
140 * @return array of templates mapping template alias to content
142 public function getTemplates() {
143 // Stub, override expected.
144 return array();
148 * @return Config
149 * @since 1.24
151 public function getConfig() {
152 if ( $this->config === null ) {
153 // Ugh, fall back to default
154 $this->config = ConfigFactory::getDefaultInstance()->makeConfig( 'main' );
157 return $this->config;
161 * @param Config $config
162 * @since 1.24
164 public function setConfig( Config $config ) {
165 $this->config = $config;
169 * Get the URL or URLs to load for this module's JS in debug mode.
170 * The default behavior is to return a load.php?only=scripts URL for
171 * the module, but file-based modules will want to override this to
172 * load the files directly.
174 * This function is called only when 1) we're in debug mode, 2) there
175 * is no only= parameter and 3) supportsURLLoading() returns true.
176 * #2 is important to prevent an infinite loop, therefore this function
177 * MUST return either an only= URL or a non-load.php URL.
179 * @param ResourceLoaderContext $context
180 * @return array Array of URLs
182 public function getScriptURLsForDebug( ResourceLoaderContext $context ) {
183 $resourceLoader = $context->getResourceLoader();
184 $derivative = new DerivativeResourceLoaderContext( $context );
185 $derivative->setModules( array( $this->getName() ) );
186 $derivative->setOnly( 'scripts' );
187 $derivative->setDebug( true );
189 $url = $resourceLoader->createLoaderURL(
190 $this->getSource(),
191 $derivative
194 return array( $url );
198 * Whether this module supports URL loading. If this function returns false,
199 * getScript() will be used even in cases (debug mode, no only param) where
200 * getScriptURLsForDebug() would normally be used instead.
201 * @return bool
203 public function supportsURLLoading() {
204 return true;
208 * Get all CSS for this module for a given skin.
210 * @param ResourceLoaderContext $context
211 * @return array List of CSS strings or array of CSS strings keyed by media type.
212 * like array( 'screen' => '.foo { width: 0 }' );
213 * or array( 'screen' => array( '.foo { width: 0 }' ) );
215 public function getStyles( ResourceLoaderContext $context ) {
216 // Stub, override expected
217 return array();
221 * Get the URL or URLs to load for this module's CSS in debug mode.
222 * The default behavior is to return a load.php?only=styles URL for
223 * the module, but file-based modules will want to override this to
224 * load the files directly. See also getScriptURLsForDebug()
226 * @param ResourceLoaderContext $context
227 * @return array Array( mediaType => array( URL1, URL2, ... ), ... )
229 public function getStyleURLsForDebug( ResourceLoaderContext $context ) {
230 $resourceLoader = $context->getResourceLoader();
231 $derivative = new DerivativeResourceLoaderContext( $context );
232 $derivative->setModules( array( $this->getName() ) );
233 $derivative->setOnly( 'styles' );
234 $derivative->setDebug( true );
236 $url = $resourceLoader->createLoaderURL(
237 $this->getSource(),
238 $derivative
241 return array( 'all' => array( $url ) );
245 * Get the messages needed for this module.
247 * To get a JSON blob with messages, use MessageBlobStore::get()
249 * @return array List of message keys. Keys may occur more than once
251 public function getMessages() {
252 // Stub, override expected
253 return array();
257 * Get the group this module is in.
259 * @return string Group name
261 public function getGroup() {
262 // Stub, override expected
263 return null;
267 * Get the origin of this module. Should only be overridden for foreign modules.
269 * @return string Origin name, 'local' for local modules
271 public function getSource() {
272 // Stub, override expected
273 return 'local';
277 * Where on the HTML page should this module's JS be loaded?
278 * - 'top': in the "<head>"
279 * - 'bottom': at the bottom of the "<body>"
281 * @return string
283 public function getPosition() {
284 return 'bottom';
288 * Whether this module's JS expects to work without the client-side ResourceLoader module.
289 * Returning true from this function will prevent mw.loader.state() call from being
290 * appended to the bottom of the script.
292 * @return bool
294 public function isRaw() {
295 return false;
299 * Get the loader JS for this module, if set.
301 * @return mixed JavaScript loader code as a string or boolean false if no custom loader set
303 public function getLoaderScript() {
304 // Stub, override expected
305 return false;
309 * Get a list of modules this module depends on.
311 * Dependency information is taken into account when loading a module
312 * on the client side.
314 * To add dependencies dynamically on the client side, use a custom
315 * loader script, see getLoaderScript()
316 * @return array List of module names as strings
318 public function getDependencies() {
319 // Stub, override expected
320 return array();
324 * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
326 * @return array Array of strings
328 public function getTargets() {
329 return $this->targets;
333 * Get the skip function.
335 * Modules that provide fallback functionality can provide a "skip function". This
336 * function, if provided, will be passed along to the module registry on the client.
337 * When this module is loaded (either directly or as a dependency of another module),
338 * then this function is executed first. If the function returns true, the module will
339 * instantly be considered "ready" without requesting the associated module resources.
341 * The value returned here must be valid javascript for execution in a private function.
342 * It must not contain the "function () {" and "}" wrapper though.
344 * @return string|null A JavaScript function body returning a boolean value, or null
346 public function getSkipFunction() {
347 return null;
351 * Get the files this module depends on indirectly for a given skin.
352 * Currently these are only image files referenced by the module's CSS.
354 * @param string $skin Skin name
355 * @return array List of files
357 public function getFileDependencies( $skin ) {
358 // Try in-object cache first
359 if ( isset( $this->fileDeps[$skin] ) ) {
360 return $this->fileDeps[$skin];
363 $dbr = wfGetDB( DB_SLAVE );
364 $deps = $dbr->selectField( 'module_deps', 'md_deps', array(
365 'md_module' => $this->getName(),
366 'md_skin' => $skin,
367 ), __METHOD__
369 if ( !is_null( $deps ) ) {
370 $this->fileDeps[$skin] = (array)FormatJson::decode( $deps, true );
371 } else {
372 $this->fileDeps[$skin] = array();
374 return $this->fileDeps[$skin];
378 * Set preloaded file dependency information. Used so we can load this
379 * information for all modules at once.
380 * @param string $skin Skin name
381 * @param array $deps Array of file names
383 public function setFileDependencies( $skin, $deps ) {
384 $this->fileDeps[$skin] = $deps;
388 * Get the last modification timestamp of the message blob for this
389 * module in a given language.
390 * @param string $lang Language code
391 * @return int UNIX timestamp
393 public function getMsgBlobMtime( $lang ) {
394 if ( !isset( $this->msgBlobMtime[$lang] ) ) {
395 if ( !count( $this->getMessages() ) ) {
396 return 1;
399 $dbr = wfGetDB( DB_SLAVE );
400 $msgBlobMtime = $dbr->selectField( 'msg_resource', 'mr_timestamp', array(
401 'mr_resource' => $this->getName(),
402 'mr_lang' => $lang
403 ), __METHOD__
405 // If no blob was found, but the module does have messages, that means we need
406 // to regenerate it. Return NOW
407 if ( $msgBlobMtime === false ) {
408 $msgBlobMtime = wfTimestampNow();
410 $this->msgBlobMtime[$lang] = wfTimestamp( TS_UNIX, $msgBlobMtime );
412 return $this->msgBlobMtime[$lang];
416 * Set a preloaded message blob last modification timestamp. Used so we
417 * can load this information for all modules at once.
418 * @param string $lang Language code
419 * @param int $mtime UNIX timestamp
421 public function setMsgBlobMtime( $lang, $mtime ) {
422 $this->msgBlobMtime[$lang] = $mtime;
425 /* Abstract Methods */
428 * Get this module's last modification timestamp for a given
429 * combination of language, skin and debug mode flag. This is typically
430 * the highest of each of the relevant components' modification
431 * timestamps. Whenever anything happens that changes the module's
432 * contents for these parameters, the mtime should increase.
434 * NOTE: The mtime of the module's messages is NOT automatically included.
435 * If you want this to happen, you'll need to call getMsgBlobMtime()
436 * yourself and take its result into consideration.
438 * NOTE: The mtime of the module's hash is NOT automatically included.
439 * If your module provides a getModifiedHash() method, you'll need to call getHashMtime()
440 * yourself and take its result into consideration.
442 * @param ResourceLoaderContext $context Context object
443 * @return int UNIX timestamp
445 public function getModifiedTime( ResourceLoaderContext $context ) {
446 return 1;
450 * Helper method for calculating when the module's hash (if it has one) changed.
452 * @param ResourceLoaderContext $context
453 * @return int UNIX timestamp
455 public function getHashMtime( ResourceLoaderContext $context ) {
456 $hash = $this->getModifiedHash( $context );
457 if ( !is_string( $hash ) ) {
458 return 1;
461 $cache = wfGetCache( CACHE_ANYTHING );
462 $key = wfMemcKey( 'resourceloader', 'modulemodifiedhash', $this->getName(), $hash );
464 $data = $cache->get( $key );
465 if ( is_array( $data ) && $data['hash'] === $hash ) {
466 // Hash is still the same, re-use the timestamp of when we first saw this hash.
467 return $data['timestamp'];
470 $timestamp = time();
471 $cache->set( $key, array(
472 'hash' => $hash,
473 'timestamp' => $timestamp,
474 ) );
476 return $timestamp;
480 * Get the hash for whatever this module may contain.
482 * This is the method subclasses should implement if they want to make
483 * use of getHashMTime() inside getModifiedTime().
485 * @param ResourceLoaderContext $context
486 * @return string|null Hash
488 public function getModifiedHash( ResourceLoaderContext $context ) {
489 return null;
493 * Helper method for calculating when this module's definition summary was last changed.
495 * @since 1.23
497 * @param ResourceLoaderContext $context
498 * @return int UNIX timestamp
500 public function getDefinitionMtime( ResourceLoaderContext $context ) {
501 $summary = $this->getDefinitionSummary( $context );
502 if ( $summary === null ) {
503 return 1;
506 $hash = md5( json_encode( $summary ) );
508 $cache = wfGetCache( CACHE_ANYTHING );
510 // Embed the hash itself in the cache key. This allows for a few nifty things:
511 // - During deployment, servers with old and new versions of the code communicating
512 // with the same memcached will not override the same key repeatedly increasing
513 // the timestamp.
514 // - In case of the definition changing and then changing back in a short period of time
515 // (e.g. in case of a revert or a corrupt server) the old timestamp and client-side cache
516 // url will be re-used.
517 // - If different context-combinations (e.g. same skin, same language or some combination
518 // thereof) result in the same definition, they will use the same hash and timestamp.
519 $key = wfMemcKey( 'resourceloader', 'moduledefinition', $this->getName(), $hash );
521 $data = $cache->get( $key );
522 if ( is_int( $data ) && $data > 0 ) {
523 // We've seen this hash before, re-use the timestamp of when we first saw it.
524 return $data;
527 wfDebugLog( 'resourceloader', __METHOD__ . ": New definition hash for module "
528 . "{$this->getName()} in context {$context->getHash()}: $hash." );
530 $timestamp = time();
531 $cache->set( $key, $timestamp );
533 return $timestamp;
537 * Get the definition summary for this module.
539 * This is the method subclasses should implement if they want to make
540 * use of getDefinitionMTime() inside getModifiedTime().
542 * Return an array containing values from all significant properties of this
543 * module's definition. Be sure to include things that are explicitly ordered,
544 * in their actaul order (bug 37812).
546 * Avoid including things that are insiginificant (e.g. order of message
547 * keys is insignificant and should be sorted to avoid unnecessary cache
548 * invalidation).
550 * Avoid including things already considered by other methods inside your
551 * getModifiedTime(), such as file mtime timestamps.
553 * Serialisation is done using json_encode, which means object state is not
554 * taken into account when building the hash. This data structure must only
555 * contain arrays and scalars as values (avoid object instances) which means
556 * it requires abstraction.
558 * @since 1.23
560 * @param ResourceLoaderContext $context
561 * @return array|null
563 public function getDefinitionSummary( ResourceLoaderContext $context ) {
564 return array(
565 'class' => get_class( $this ),
570 * Check whether this module is known to be empty. If a child class
571 * has an easy and cheap way to determine that this module is
572 * definitely going to be empty, it should override this method to
573 * return true in that case. Callers may optimize the request for this
574 * module away if this function returns true.
575 * @param ResourceLoaderContext $context
576 * @return bool
578 public function isKnownEmpty( ResourceLoaderContext $context ) {
579 return false;
582 /** @var JSParser Lazy-initialized; use self::javaScriptParser() */
583 private static $jsParser;
584 private static $parseCacheVersion = 1;
587 * Validate a given script file; if valid returns the original source.
588 * If invalid, returns replacement JS source that throws an exception.
590 * @param string $fileName
591 * @param string $contents
592 * @return string JS with the original, or a replacement error
594 protected function validateScriptFile( $fileName, $contents ) {
595 if ( $this->getConfig()->get( 'ResourceLoaderValidateJS' ) ) {
596 // Try for cache hit
597 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
598 $key = wfMemcKey( 'resourceloader', 'jsparse', self::$parseCacheVersion, md5( $contents ) );
599 $cache = wfGetCache( CACHE_ANYTHING );
600 $cacheEntry = $cache->get( $key );
601 if ( is_string( $cacheEntry ) ) {
602 return $cacheEntry;
605 $parser = self::javaScriptParser();
606 try {
607 $parser->parse( $contents, $fileName, 1 );
608 $result = $contents;
609 } catch ( Exception $e ) {
610 // We'll save this to cache to avoid having to validate broken JS over and over...
611 $err = $e->getMessage();
612 $result = "throw new Error(" . Xml::encodeJsVar( "JavaScript parse error: $err" ) . ");";
615 $cache->set( $key, $result );
616 return $result;
617 } else {
618 return $contents;
623 * @return JSParser
625 protected static function javaScriptParser() {
626 if ( !self::$jsParser ) {
627 self::$jsParser = new JSParser();
629 return self::$jsParser;
633 * Safe version of filemtime(), which doesn't throw a PHP warning if the file doesn't exist
634 * but returns 1 instead.
635 * @param string $filename File name
636 * @return int UNIX timestamp
638 protected static function safeFilemtime( $filename ) {
639 if ( !file_exists( $filename ) ) {
640 return 1;
642 return filemtime( $filename );