resourceloader: Add context param to ResourceLoaderModule::getDependencies
[lhc/web/wiklou.git] / includes / resourceloader / ResourceLoaderModule.php
1 <?php
2 /**
3 * Abstraction for resource loader modules.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @author Trevor Parscal
22 * @author Roan Kattouw
23 */
24
25 /**
26 * Abstraction for resource loader modules, with name registration and maxage functionality.
27 */
28 abstract class ResourceLoaderModule {
29 # Type of resource
30 const TYPE_SCRIPTS = 'scripts';
31 const TYPE_STYLES = 'styles';
32 const TYPE_COMBINED = 'combined';
33
34 # sitewide core module like a skin file or jQuery component
35 const ORIGIN_CORE_SITEWIDE = 1;
36
37 # per-user module generated by the software
38 const ORIGIN_CORE_INDIVIDUAL = 2;
39
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;
43
44 # per-user module generated from user-editable files, like User:Me/vector.js
45 const ORIGIN_USER_INDIVIDUAL = 4;
46
47 # an access constant; make sure this is kept as the largest number in this group
48 const ORIGIN_ALL = 10;
49
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;
55
56 /* Protected Members */
57
58 protected $name = null;
59 protected $targets = array( 'desktop' );
60
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
68 // Whether the position returned by getPosition() is defined in the module configuration
69 // and not a default value
70 protected $isPositionDefined = false;
71
72 /**
73 * @var Config
74 */
75 protected $config;
76
77 /* Methods */
78
79 /**
80 * Get this module's name. This is set when the module is registered
81 * with ResourceLoader::register()
82 *
83 * @return string|null Name (string) or null if no name was set
84 */
85 public function getName() {
86 return $this->name;
87 }
88
89 /**
90 * Set this module's name. This is called by ResourceLoader::register()
91 * when registering the module. Other code should not call this.
92 *
93 * @param string $name Name
94 */
95 public function setName( $name ) {
96 $this->name = $name;
97 }
98
99 /**
100 * Get this module's origin. This is set when the module is registered
101 * with ResourceLoader::register()
102 *
103 * @return int ResourceLoaderModule class constant, the subclass default
104 * if not set manually
105 */
106 public function getOrigin() {
107 return $this->origin;
108 }
109
110 /**
111 * Set this module's origin. This is called by ResourceLoader::register()
112 * when registering the module. Other code should not call this.
113 *
114 * @param int $origin Origin
115 */
116 public function setOrigin( $origin ) {
117 $this->origin = $origin;
118 }
119
120 /**
121 * @param ResourceLoaderContext $context
122 * @return bool
123 */
124 public function getFlip( $context ) {
125 global $wgContLang;
126
127 return $wgContLang->getDir() !== $context->getDirection();
128 }
129
130 /**
131 * Get all JS for this module for a given language and skin.
132 * Includes all relevant JS except loader scripts.
133 *
134 * @param ResourceLoaderContext $context
135 * @return string JavaScript code
136 */
137 public function getScript( ResourceLoaderContext $context ) {
138 // Stub, override expected
139 return '';
140 }
141
142 /**
143 * Takes named templates by the module and returns an array mapping.
144 *
145 * @return array of templates mapping template alias to content
146 */
147 public function getTemplates() {
148 // Stub, override expected.
149 return array();
150 }
151
152 /**
153 * @return Config
154 * @since 1.24
155 */
156 public function getConfig() {
157 if ( $this->config === null ) {
158 // Ugh, fall back to default
159 $this->config = ConfigFactory::getDefaultInstance()->makeConfig( 'main' );
160 }
161
162 return $this->config;
163 }
164
165 /**
166 * @param Config $config
167 * @since 1.24
168 */
169 public function setConfig( Config $config ) {
170 $this->config = $config;
171 }
172
173 /**
174 * Get the URL or URLs to load for this module's JS in debug mode.
175 * The default behavior is to return a load.php?only=scripts URL for
176 * the module, but file-based modules will want to override this to
177 * load the files directly.
178 *
179 * This function is called only when 1) we're in debug mode, 2) there
180 * is no only= parameter and 3) supportsURLLoading() returns true.
181 * #2 is important to prevent an infinite loop, therefore this function
182 * MUST return either an only= URL or a non-load.php URL.
183 *
184 * @param ResourceLoaderContext $context
185 * @return array Array of URLs
186 */
187 public function getScriptURLsForDebug( ResourceLoaderContext $context ) {
188 $resourceLoader = $context->getResourceLoader();
189 $derivative = new DerivativeResourceLoaderContext( $context );
190 $derivative->setModules( array( $this->getName() ) );
191 $derivative->setOnly( 'scripts' );
192 $derivative->setDebug( true );
193
194 $url = $resourceLoader->createLoaderURL(
195 $this->getSource(),
196 $derivative
197 );
198
199 return array( $url );
200 }
201
202 /**
203 * Whether this module supports URL loading. If this function returns false,
204 * getScript() will be used even in cases (debug mode, no only param) where
205 * getScriptURLsForDebug() would normally be used instead.
206 * @return bool
207 */
208 public function supportsURLLoading() {
209 return true;
210 }
211
212 /**
213 * Get all CSS for this module for a given skin.
214 *
215 * @param ResourceLoaderContext $context
216 * @return array List of CSS strings or array of CSS strings keyed by media type.
217 * like array( 'screen' => '.foo { width: 0 }' );
218 * or array( 'screen' => array( '.foo { width: 0 }' ) );
219 */
220 public function getStyles( ResourceLoaderContext $context ) {
221 // Stub, override expected
222 return array();
223 }
224
225 /**
226 * Get the URL or URLs to load for this module's CSS in debug mode.
227 * The default behavior is to return a load.php?only=styles URL for
228 * the module, but file-based modules will want to override this to
229 * load the files directly. See also getScriptURLsForDebug()
230 *
231 * @param ResourceLoaderContext $context
232 * @return array Array( mediaType => array( URL1, URL2, ... ), ... )
233 */
234 public function getStyleURLsForDebug( ResourceLoaderContext $context ) {
235 $resourceLoader = $context->getResourceLoader();
236 $derivative = new DerivativeResourceLoaderContext( $context );
237 $derivative->setModules( array( $this->getName() ) );
238 $derivative->setOnly( 'styles' );
239 $derivative->setDebug( true );
240
241 $url = $resourceLoader->createLoaderURL(
242 $this->getSource(),
243 $derivative
244 );
245
246 return array( 'all' => array( $url ) );
247 }
248
249 /**
250 * Get the messages needed for this module.
251 *
252 * To get a JSON blob with messages, use MessageBlobStore::get()
253 *
254 * @return array List of message keys. Keys may occur more than once
255 */
256 public function getMessages() {
257 // Stub, override expected
258 return array();
259 }
260
261 /**
262 * Get the group this module is in.
263 *
264 * @return string Group name
265 */
266 public function getGroup() {
267 // Stub, override expected
268 return null;
269 }
270
271 /**
272 * Get the origin of this module. Should only be overridden for foreign modules.
273 *
274 * @return string Origin name, 'local' for local modules
275 */
276 public function getSource() {
277 // Stub, override expected
278 return 'local';
279 }
280
281 /**
282 * Where on the HTML page should this module's JS be loaded?
283 * - 'top': in the "<head>"
284 * - 'bottom': at the bottom of the "<body>"
285 *
286 * @return string
287 */
288 public function getPosition() {
289 return 'bottom';
290 }
291
292 /**
293 * Whether the position returned by getPosition() is a default value or comes from the module
294 * definition. This method is meant to be short-lived, and is only useful until classes added via
295 * addModuleStyles with a default value define an explicit position. See getModuleStyles() in
296 * OutputPage for the related migration warning.
297 *
298 * @return bool
299 * @since 1.26
300 */
301 public function isPositionDefault() {
302 return !$this->isPositionDefined;
303 }
304
305 /**
306 * Whether this module's JS expects to work without the client-side ResourceLoader module.
307 * Returning true from this function will prevent mw.loader.state() call from being
308 * appended to the bottom of the script.
309 *
310 * @return bool
311 */
312 public function isRaw() {
313 return false;
314 }
315
316 /**
317 * Get the loader JS for this module, if set.
318 *
319 * @return mixed JavaScript loader code as a string or boolean false if no custom loader set
320 */
321 public function getLoaderScript() {
322 // Stub, override expected
323 return false;
324 }
325
326 /**
327 * Get a list of modules this module depends on.
328 *
329 * Dependency information is taken into account when loading a module
330 * on the client side.
331 *
332 * To add dependencies dynamically on the client side, use a custom
333 * loader script, see getLoaderScript()
334 *
335 * Note: It is expected that $context will be made non-optional in the near
336 * future.
337 *
338 * @param ResourceLoaderContext $context
339 * @return array List of module names as strings
340 */
341 public function getDependencies( ResourceLoaderContext $context = null ) {
342 // Stub, override expected
343 return array();
344 }
345
346 /**
347 * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
348 *
349 * @return array Array of strings
350 */
351 public function getTargets() {
352 return $this->targets;
353 }
354
355 /**
356 * Get the skip function.
357 *
358 * Modules that provide fallback functionality can provide a "skip function". This
359 * function, if provided, will be passed along to the module registry on the client.
360 * When this module is loaded (either directly or as a dependency of another module),
361 * then this function is executed first. If the function returns true, the module will
362 * instantly be considered "ready" without requesting the associated module resources.
363 *
364 * The value returned here must be valid javascript for execution in a private function.
365 * It must not contain the "function () {" and "}" wrapper though.
366 *
367 * @return string|null A JavaScript function body returning a boolean value, or null
368 */
369 public function getSkipFunction() {
370 return null;
371 }
372
373 /**
374 * Get the files this module depends on indirectly for a given skin.
375 * Currently these are only image files referenced by the module's CSS.
376 *
377 * @param string $skin Skin name
378 * @return array List of files
379 */
380 public function getFileDependencies( $skin ) {
381 // Try in-object cache first
382 if ( isset( $this->fileDeps[$skin] ) ) {
383 return $this->fileDeps[$skin];
384 }
385
386 $dbr = wfGetDB( DB_SLAVE );
387 $deps = $dbr->selectField( 'module_deps', 'md_deps', array(
388 'md_module' => $this->getName(),
389 'md_skin' => $skin,
390 ), __METHOD__
391 );
392 if ( !is_null( $deps ) ) {
393 $this->fileDeps[$skin] = (array)FormatJson::decode( $deps, true );
394 } else {
395 $this->fileDeps[$skin] = array();
396 }
397 return $this->fileDeps[$skin];
398 }
399
400 /**
401 * Set preloaded file dependency information. Used so we can load this
402 * information for all modules at once.
403 * @param string $skin Skin name
404 * @param array $deps Array of file names
405 */
406 public function setFileDependencies( $skin, $deps ) {
407 $this->fileDeps[$skin] = $deps;
408 }
409
410 /**
411 * Get the last modification timestamp of the messages in this module for a given language.
412 * @param string $lang Language code
413 * @return int UNIX timestamp
414 */
415 public function getMsgBlobMtime( $lang ) {
416 if ( !isset( $this->msgBlobMtime[$lang] ) ) {
417 if ( !count( $this->getMessages() ) ) {
418 return 1;
419 }
420
421 $dbr = wfGetDB( DB_SLAVE );
422 $msgBlobMtime = $dbr->selectField( 'msg_resource', 'mr_timestamp', array(
423 'mr_resource' => $this->getName(),
424 'mr_lang' => $lang
425 ), __METHOD__
426 );
427 // If no blob was found, but the module does have messages, that means we need
428 // to regenerate it. Return NOW
429 if ( $msgBlobMtime === false ) {
430 $msgBlobMtime = wfTimestampNow();
431 }
432 $this->msgBlobMtime[$lang] = wfTimestamp( TS_UNIX, $msgBlobMtime );
433 }
434 return $this->msgBlobMtime[$lang];
435 }
436
437 /**
438 * Set a preloaded message blob last modification timestamp. Used so we
439 * can load this information for all modules at once.
440 * @param string $lang Language code
441 * @param int $mtime UNIX timestamp
442 */
443 public function setMsgBlobMtime( $lang, $mtime ) {
444 $this->msgBlobMtime[$lang] = $mtime;
445 }
446
447 /**
448 * Get a string identifying the current version of this module in a given context.
449 *
450 * Whenever anything happens that changes the module's response (e.g. scripts, styles, and
451 * messages) this value must change. This value is used to store module responses in cache.
452 * (Both client-side and server-side.)
453 *
454 * It is not recommended to override this directly. Use getDefinitionSummary() instead.
455 * If overridden, one must call the parent getVersionHash(), append data and re-hash.
456 *
457 * This method should be quick because it is frequently run by ResourceLoaderStartUpModule to
458 * propagate changes to the client and effectively invalidate cache.
459 *
460 * For backward-compatibility, the following optional data providers are automatically included:
461 *
462 * - getModifiedTime()
463 * - getModifiedHash()
464 *
465 * @since 1.26
466 * @param ResourceLoaderContext $context
467 * @return string Hash (should use ResourceLoader::makeHash)
468 */
469 public function getVersionHash( ResourceLoaderContext $context ) {
470 // Cache this somewhat expensive operation. Especially because some classes
471 // (e.g. startup module) iterate more than once over all modules to get versions.
472 $contextHash = $context->getHash();
473 if ( !array_key_exists( $contextHash, $this->versionHash ) ) {
474
475 $summary = $this->getDefinitionSummary( $context );
476 if ( !isset( $summary['_cacheEpoch'] ) ) {
477 throw new Exception( 'getDefinitionSummary must call parent method' );
478 }
479 $str = json_encode( $summary );
480
481 $mtime = $this->getModifiedTime( $context );
482 if ( $mtime !== null ) {
483 // Support: MediaWiki 1.25 and earlier
484 $str .= strval( $mtime );
485 }
486
487 $mhash = $this->getModifiedHash( $context );
488 if ( $mhash !== null ) {
489 // Support: MediaWiki 1.25 and earlier
490 $str .= strval( $mhash );
491 }
492
493 $this->versionHash[ $contextHash ] = ResourceLoader::makeHash( $str );
494 }
495 return $this->versionHash[ $contextHash ];
496 }
497
498 /**
499 * Get the definition summary for this module.
500 *
501 * This is the method subclasses are recommended to use to track values in their
502 * version hash. Call this in getVersionHash() and pass it to e.g. json_encode.
503 *
504 * Subclasses must call the parent getDefinitionSummary() and build on that.
505 * It is recommended that each subclass appends its own new array. This prevents
506 * clashes or accidental overwrites of existing keys and gives each subclass
507 * its own scope for simple array keys.
508 *
509 * @code
510 * $summary = parent::getDefinitionSummary( $context );
511 * $summary[] = array(
512 * 'foo' => 123,
513 * 'bar' => 'quux',
514 * );
515 * return $summary;
516 * @endcode
517 *
518 * Return an array containing values from all significant properties of this
519 * module's definition.
520 *
521 * Be careful not to normalise too much. Especially preserve the order of things
522 * that carry significance in getScript and getStyles (T39812).
523 *
524 * Avoid including things that are insiginificant (e.g. order of message keys is
525 * insignificant and should be sorted to avoid unnecessary cache invalidation).
526 *
527 * This data structure must exclusively contain arrays and scalars as values (avoid
528 * object instances) to allow simple serialisation using json_encode.
529 *
530 * If modules have a hash or timestamp from another source, that may be incuded as-is.
531 *
532 * A number of utility methods are available to help you gather data. These are not
533 * called by default and must be included by the subclass' getDefinitionSummary().
534 *
535 * - getMsgBlobMtime()
536 *
537 * @since 1.23
538 * @param ResourceLoaderContext $context
539 * @return array|null
540 */
541 public function getDefinitionSummary( ResourceLoaderContext $context ) {
542 return array(
543 '_class' => get_class( $this ),
544 '_cacheEpoch' => $this->getConfig()->get( 'CacheEpoch' ),
545 );
546 }
547
548 /**
549 * Get this module's last modification timestamp for a given context.
550 *
551 * @deprecated since 1.26 Use getDefinitionSummary() instead
552 * @param ResourceLoaderContext $context Context object
553 * @return int|null UNIX timestamp
554 */
555 public function getModifiedTime( ResourceLoaderContext $context ) {
556 return null;
557 }
558
559 /**
560 * Helper method for providing a version hash to getVersionHash().
561 *
562 * @deprecated since 1.26 Use getDefinitionSummary() instead
563 * @param ResourceLoaderContext $context
564 * @return string|null Hash
565 */
566 public function getModifiedHash( ResourceLoaderContext $context ) {
567 return null;
568 }
569
570 /**
571 * Back-compat dummy for old subclass implementations of getModifiedTime().
572 *
573 * This method used to use ObjectCache to track when a hash was first seen. That principle
574 * stems from a time that ResourceLoader could only identify module versions by timestamp.
575 * That is no longer the case. Use getDefinitionSummary() directly.
576 *
577 * @deprecated since 1.26 Superseded by getVersionHash()
578 * @param ResourceLoaderContext $context
579 * @return int UNIX timestamp
580 */
581 public function getHashMtime( ResourceLoaderContext $context ) {
582 if ( !is_string( $this->getModifiedHash( $context ) ) ) {
583 return 1;
584 }
585 // Dummy that is > 1
586 return 2;
587 }
588
589 /**
590 * Back-compat dummy for old subclass implementations of getModifiedTime().
591 *
592 * @since 1.23
593 * @deprecated since 1.26 Superseded by getVersionHash()
594 * @param ResourceLoaderContext $context
595 * @return int UNIX timestamp
596 */
597 public function getDefinitionMtime( ResourceLoaderContext $context ) {
598 if ( $this->getDefinitionSummary( $context ) === null ) {
599 return 1;
600 }
601 // Dummy that is > 1
602 return 2;
603 }
604
605 /**
606 * Check whether this module is known to be empty. If a child class
607 * has an easy and cheap way to determine that this module is
608 * definitely going to be empty, it should override this method to
609 * return true in that case. Callers may optimize the request for this
610 * module away if this function returns true.
611 * @param ResourceLoaderContext $context
612 * @return bool
613 */
614 public function isKnownEmpty( ResourceLoaderContext $context ) {
615 return false;
616 }
617
618 /** @var JSParser Lazy-initialized; use self::javaScriptParser() */
619 private static $jsParser;
620 private static $parseCacheVersion = 1;
621
622 /**
623 * Validate a given script file; if valid returns the original source.
624 * If invalid, returns replacement JS source that throws an exception.
625 *
626 * @param string $fileName
627 * @param string $contents
628 * @return string JS with the original, or a replacement error
629 */
630 protected function validateScriptFile( $fileName, $contents ) {
631 if ( $this->getConfig()->get( 'ResourceLoaderValidateJS' ) ) {
632 // Try for cache hit
633 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
634 $key = wfMemcKey( 'resourceloader', 'jsparse', self::$parseCacheVersion, md5( $contents ) );
635 $cache = wfGetCache( CACHE_ANYTHING );
636 $cacheEntry = $cache->get( $key );
637 if ( is_string( $cacheEntry ) ) {
638 return $cacheEntry;
639 }
640
641 $parser = self::javaScriptParser();
642 try {
643 $parser->parse( $contents, $fileName, 1 );
644 $result = $contents;
645 } catch ( Exception $e ) {
646 // We'll save this to cache to avoid having to validate broken JS over and over...
647 $err = $e->getMessage();
648 $result = "mw.log.error(" . Xml::encodeJsVar( "JavaScript parse error: $err" ) . ");";
649 }
650
651 $cache->set( $key, $result );
652 return $result;
653 } else {
654 return $contents;
655 }
656 }
657
658 /**
659 * @return JSParser
660 */
661 protected static function javaScriptParser() {
662 if ( !self::$jsParser ) {
663 self::$jsParser = new JSParser();
664 }
665 return self::$jsParser;
666 }
667
668 /**
669 * Safe version of filemtime(), which doesn't throw a PHP warning if the file doesn't exist
670 * but returns 1 instead.
671 * @param string $filename File name
672 * @return int UNIX timestamp
673 */
674 protected static function safeFilemtime( $filename ) {
675 wfSuppressWarnings();
676 $mtime = filemtime( $filename ) ?: 1;
677 wfRestoreWarnings();
678
679 return $mtime;
680 }
681 }