Cleanup setFileDependencies() docs
[lhc/web/wiklou.git] / includes / resourceloader / ResourceLoaderModule.php
1 <?php
2 /**
3 * Abstraction for ResourceLoader 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 use Psr\Log\LoggerAwareInterface;
26 use Psr\Log\LoggerInterface;
27 use Psr\Log\NullLogger;
28
29 /**
30 * Abstraction for ResourceLoader modules, with name registration and maxage functionality.
31 */
32 abstract class ResourceLoaderModule implements LoggerAwareInterface {
33 # Type of resource
34 const TYPE_SCRIPTS = 'scripts';
35 const TYPE_STYLES = 'styles';
36 const TYPE_COMBINED = 'combined';
37
38 # sitewide core module like a skin file or jQuery component
39 const ORIGIN_CORE_SITEWIDE = 1;
40
41 # per-user module generated by the software
42 const ORIGIN_CORE_INDIVIDUAL = 2;
43
44 # sitewide module generated from user-editable files, like MediaWiki:Common.js, or
45 # modules accessible to multiple users, such as those generated by the Gadgets extension.
46 const ORIGIN_USER_SITEWIDE = 3;
47
48 # per-user module generated from user-editable files, like User:Me/vector.js
49 const ORIGIN_USER_INDIVIDUAL = 4;
50
51 # an access constant; make sure this is kept as the largest number in this group
52 const ORIGIN_ALL = 10;
53
54 # script and style modules form a hierarchy of trustworthiness, with core modules like
55 # skins and jQuery as most trustworthy, and user scripts as least trustworthy. We can
56 # limit the types of scripts and styles we allow to load on, say, sensitive special
57 # pages like Special:UserLogin and Special:Preferences
58 protected $origin = self::ORIGIN_CORE_SITEWIDE;
59
60 /* Protected Members */
61
62 protected $name = null;
63 protected $targets = array( 'desktop' );
64
65 // In-object cache for file dependencies
66 protected $fileDeps = array();
67 // In-object cache for message blob (keyed by language)
68 protected $msgBlobs = array();
69 // In-object cache for version hash
70 protected $versionHash = array();
71 // In-object cache for module content
72 protected $contents = array();
73
74 /**
75 * @var Config
76 */
77 protected $config;
78
79 /**
80 * @var LoggerInterface
81 */
82 protected $logger;
83
84 /* Methods */
85
86 /**
87 * Get this module's name. This is set when the module is registered
88 * with ResourceLoader::register()
89 *
90 * @return string|null Name (string) or null if no name was set
91 */
92 public function getName() {
93 return $this->name;
94 }
95
96 /**
97 * Set this module's name. This is called by ResourceLoader::register()
98 * when registering the module. Other code should not call this.
99 *
100 * @param string $name Name
101 */
102 public function setName( $name ) {
103 $this->name = $name;
104 }
105
106 /**
107 * Get this module's origin. This is set when the module is registered
108 * with ResourceLoader::register()
109 *
110 * @return int ResourceLoaderModule class constant, the subclass default
111 * if not set manually
112 */
113 public function getOrigin() {
114 return $this->origin;
115 }
116
117 /**
118 * Set this module's origin. This is called by ResourceLoader::register()
119 * when registering the module. Other code should not call this.
120 *
121 * @param int $origin Origin
122 */
123 public function setOrigin( $origin ) {
124 $this->origin = $origin;
125 }
126
127 /**
128 * @param ResourceLoaderContext $context
129 * @return bool
130 */
131 public function getFlip( $context ) {
132 global $wgContLang;
133
134 return $wgContLang->getDir() !== $context->getDirection();
135 }
136
137 /**
138 * Get all JS for this module for a given language and skin.
139 * Includes all relevant JS except loader scripts.
140 *
141 * @param ResourceLoaderContext $context
142 * @return string JavaScript code
143 */
144 public function getScript( ResourceLoaderContext $context ) {
145 // Stub, override expected
146 return '';
147 }
148
149 /**
150 * Takes named templates by the module and returns an array mapping.
151 *
152 * @return array of templates mapping template alias to content
153 */
154 public function getTemplates() {
155 // Stub, override expected.
156 return array();
157 }
158
159 /**
160 * @return Config
161 * @since 1.24
162 */
163 public function getConfig() {
164 if ( $this->config === null ) {
165 // Ugh, fall back to default
166 $this->config = ConfigFactory::getDefaultInstance()->makeConfig( 'main' );
167 }
168
169 return $this->config;
170 }
171
172 /**
173 * @param Config $config
174 * @since 1.24
175 */
176 public function setConfig( Config $config ) {
177 $this->config = $config;
178 }
179
180 /**
181 * @since 1.27
182 * @param LoggerInterface $logger
183 * @return null
184 */
185 public function setLogger( LoggerInterface $logger ) {
186 $this->logger = $logger;
187 }
188
189 /**
190 * @since 1.27
191 * @return LoggerInterface
192 */
193 protected function getLogger() {
194 if ( !$this->logger ) {
195 $this->logger = new NullLogger();
196 }
197 return $this->logger;
198 }
199
200 /**
201 * Get the URL or URLs to load for this module's JS in debug mode.
202 * The default behavior is to return a load.php?only=scripts URL for
203 * the module, but file-based modules will want to override this to
204 * load the files directly.
205 *
206 * This function is called only when 1) we're in debug mode, 2) there
207 * is no only= parameter and 3) supportsURLLoading() returns true.
208 * #2 is important to prevent an infinite loop, therefore this function
209 * MUST return either an only= URL or a non-load.php URL.
210 *
211 * @param ResourceLoaderContext $context
212 * @return array Array of URLs
213 */
214 public function getScriptURLsForDebug( ResourceLoaderContext $context ) {
215 $resourceLoader = $context->getResourceLoader();
216 $derivative = new DerivativeResourceLoaderContext( $context );
217 $derivative->setModules( array( $this->getName() ) );
218 $derivative->setOnly( 'scripts' );
219 $derivative->setDebug( true );
220
221 $url = $resourceLoader->createLoaderURL(
222 $this->getSource(),
223 $derivative
224 );
225
226 return array( $url );
227 }
228
229 /**
230 * Whether this module supports URL loading. If this function returns false,
231 * getScript() will be used even in cases (debug mode, no only param) where
232 * getScriptURLsForDebug() would normally be used instead.
233 * @return bool
234 */
235 public function supportsURLLoading() {
236 return true;
237 }
238
239 /**
240 * Get all CSS for this module for a given skin.
241 *
242 * @param ResourceLoaderContext $context
243 * @return array List of CSS strings or array of CSS strings keyed by media type.
244 * like array( 'screen' => '.foo { width: 0 }' );
245 * or array( 'screen' => array( '.foo { width: 0 }' ) );
246 */
247 public function getStyles( ResourceLoaderContext $context ) {
248 // Stub, override expected
249 return array();
250 }
251
252 /**
253 * Get the URL or URLs to load for this module's CSS in debug mode.
254 * The default behavior is to return a load.php?only=styles URL for
255 * the module, but file-based modules will want to override this to
256 * load the files directly. See also getScriptURLsForDebug()
257 *
258 * @param ResourceLoaderContext $context
259 * @return array Array( mediaType => array( URL1, URL2, ... ), ... )
260 */
261 public function getStyleURLsForDebug( ResourceLoaderContext $context ) {
262 $resourceLoader = $context->getResourceLoader();
263 $derivative = new DerivativeResourceLoaderContext( $context );
264 $derivative->setModules( array( $this->getName() ) );
265 $derivative->setOnly( 'styles' );
266 $derivative->setDebug( true );
267
268 $url = $resourceLoader->createLoaderURL(
269 $this->getSource(),
270 $derivative
271 );
272
273 return array( 'all' => array( $url ) );
274 }
275
276 /**
277 * Get the messages needed for this module.
278 *
279 * To get a JSON blob with messages, use MessageBlobStore::get()
280 *
281 * @return array List of message keys. Keys may occur more than once
282 */
283 public function getMessages() {
284 // Stub, override expected
285 return array();
286 }
287
288 /**
289 * Get the group this module is in.
290 *
291 * @return string Group name
292 */
293 public function getGroup() {
294 // Stub, override expected
295 return null;
296 }
297
298 /**
299 * Get the origin of this module. Should only be overridden for foreign modules.
300 *
301 * @return string Origin name, 'local' for local modules
302 */
303 public function getSource() {
304 // Stub, override expected
305 return 'local';
306 }
307
308 /**
309 * Where on the HTML page should this module's JS be loaded?
310 * - 'top': in the "<head>"
311 * - 'bottom': at the bottom of the "<body>"
312 *
313 * @return string
314 */
315 public function getPosition() {
316 return 'bottom';
317 }
318
319 /**
320 * Whether this module's JS expects to work without the client-side ResourceLoader module.
321 * Returning true from this function will prevent mw.loader.state() call from being
322 * appended to the bottom of the script.
323 *
324 * @return bool
325 */
326 public function isRaw() {
327 return false;
328 }
329
330 /**
331 * Get a list of modules this module depends on.
332 *
333 * Dependency information is taken into account when loading a module
334 * on the client side.
335 *
336 * Note: It is expected that $context will be made non-optional in the near
337 * future.
338 *
339 * @param ResourceLoaderContext $context
340 * @return array List of module names as strings
341 */
342 public function getDependencies( ResourceLoaderContext $context = null ) {
343 // Stub, override expected
344 return array();
345 }
346
347 /**
348 * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
349 *
350 * @return array Array of strings
351 */
352 public function getTargets() {
353 return $this->targets;
354 }
355
356 /**
357 * Get the skip function.
358 *
359 * Modules that provide fallback functionality can provide a "skip function". This
360 * function, if provided, will be passed along to the module registry on the client.
361 * When this module is loaded (either directly or as a dependency of another module),
362 * then this function is executed first. If the function returns true, the module will
363 * instantly be considered "ready" without requesting the associated module resources.
364 *
365 * The value returned here must be valid javascript for execution in a private function.
366 * It must not contain the "function () {" and "}" wrapper though.
367 *
368 * @return string|null A JavaScript function body returning a boolean value, or null
369 */
370 public function getSkipFunction() {
371 return null;
372 }
373
374 /**
375 * Get the files this module depends on indirectly for a given skin.
376 *
377 * These are only image files referenced by the module's stylesheet.
378 *
379 * @param ResourceLoaderContext $context
380 * @return array List of files
381 */
382 protected function getFileDependencies( ResourceLoaderContext $context ) {
383 $vary = $context->getSkin() . '|' . $context->getLanguage();
384
385 // Try in-object cache first
386 if ( !isset( $this->fileDeps[$vary] ) ) {
387 $dbr = wfGetDB( DB_SLAVE );
388 $deps = $dbr->selectField( 'module_deps',
389 'md_deps',
390 array(
391 'md_module' => $this->getName(),
392 'md_skin' => $vary,
393 ),
394 __METHOD__
395 );
396
397 if ( !is_null( $deps ) ) {
398 $this->fileDeps[$vary] = self::expandRelativePaths(
399 (array)FormatJson::decode( $deps, true )
400 );
401 } else {
402 $this->fileDeps[$vary] = array();
403 }
404 }
405 return $this->fileDeps[$vary];
406 }
407
408 /**
409 * Set in-object cache for file dependencies.
410 *
411 * This is used to retrieve data in batches. See ResourceLoader::preloadModuleInfo().
412 * To save the data, use saveFileDependencies().
413 *
414 * @param ResourceLoaderContext $context
415 * @param string[] $files Array of file names
416 */
417 public function setFileDependencies( ResourceLoaderContext $context, $files ) {
418 $vary = $context->getSkin() . '|' . $context->getLanguage();
419 $this->fileDeps[$vary] = $files;
420 }
421
422 /**
423 * Set the files this module depends on indirectly for a given skin.
424 *
425 * @since 1.27
426 * @param ResourceLoaderContext $context
427 * @param array $localFileRefs List of files
428 */
429 protected function saveFileDependencies( ResourceLoaderContext $context, $localFileRefs ) {
430 // Normalise array
431 $localFileRefs = array_values( array_unique( $localFileRefs ) );
432 sort( $localFileRefs );
433
434 try {
435 // If the list has been modified since last time we cached it, update the cache
436 if ( $localFileRefs !== $this->getFileDependencies( $context ) ) {
437 $vary = $context->getSkin() . '|' . $context->getLanguage();
438 $dbw = wfGetDB( DB_MASTER );
439 $dbw->replace( 'module_deps',
440 array( array( 'md_module', 'md_skin' ) ), array(
441 'md_module' => $this->getName(),
442 'md_skin' => $vary,
443 // Use relative paths to avoid ghost entries when $IP changes (T111481)
444 'md_deps' => FormatJson::encode( self::getRelativePaths( $localFileRefs ) ),
445 )
446 );
447 }
448 } catch ( Exception $e ) {
449 wfDebugLog( 'resourceloader', __METHOD__ . ": failed to update DB: $e" );
450 }
451 }
452
453 /**
454 * Make file paths relative to MediaWiki directory.
455 *
456 * This is used to make file paths safe for storing in a database without the paths
457 * becoming stale or incorrect when MediaWiki is moved or upgraded (T111481).
458 *
459 * @since 1.27
460 * @param array $filePaths
461 * @return array
462 */
463 public static function getRelativePaths( Array $filePaths ) {
464 global $IP;
465 return array_map( function ( $path ) use ( $IP ) {
466 return RelPath\getRelativePath( $path, $IP );
467 }, $filePaths );
468 }
469
470 /**
471 * Expand directories relative to $IP.
472 *
473 * @since 1.27
474 * @param array $filePaths
475 * @return array
476 */
477 public static function expandRelativePaths( Array $filePaths ) {
478 global $IP;
479 return array_map( function ( $path ) use ( $IP ) {
480 return RelPath\joinPath( $IP, $path );
481 }, $filePaths );
482 }
483
484 /**
485 * Get the hash of the message blob.
486 *
487 * @since 1.27
488 * @param ResourceLoaderContext $context
489 * @return string|null JSON blob or null if module has no messages
490 */
491 protected function getMessageBlob( ResourceLoaderContext $context ) {
492 if ( !$this->getMessages() ) {
493 // Don't bother consulting MessageBlobStore
494 return null;
495 }
496 // Message blobs may only vary language, not by context keys
497 $lang = $context->getLanguage();
498 if ( !isset( $this->msgBlobs[$lang] ) ) {
499 $this->getLogger()->warning( 'Message blob for {module} should have been preloaded', array(
500 'module' => $this->getName(),
501 ) );
502 $store = $context->getResourceLoader()->getMessageBlobStore();
503 $this->msgBlobs[$lang] = $store->getBlob( $this, $lang );
504 }
505 return $this->msgBlobs[$lang];
506 }
507
508 /**
509 * Set in-object cache for message blobs.
510 *
511 * Used to allow fetching of message blobs in batches. See ResourceLoader::preloadModuleInfo().
512 *
513 * @since 1.27
514 * @param string|null $blob JSON blob or null
515 * @param string $lang Language code
516 */
517 public function setMessageBlob( $blob, $lang ) {
518 $this->msgBlobs[$lang] = $blob;
519 }
520
521 /**
522 * Get module-specific LESS variables, if any.
523 *
524 * @since 1.27
525 * @param ResourceLoaderContext $context
526 * @return array Module-specific LESS variables.
527 */
528 protected function getLessVars( ResourceLoaderContext $context ) {
529 return array();
530 }
531
532 /**
533 * Get an array of this module's resources. Ready for serving to the web.
534 *
535 * @since 1.26
536 * @param ResourceLoaderContext $context
537 * @return array
538 */
539 public function getModuleContent( ResourceLoaderContext $context ) {
540 $contextHash = $context->getHash();
541 // Cache this expensive operation. This calls builds the scripts, styles, and messages
542 // content which typically involves filesystem and/or database access.
543 if ( !array_key_exists( $contextHash, $this->contents ) ) {
544 $this->contents[$contextHash] = $this->buildContent( $context );
545 }
546 return $this->contents[$contextHash];
547 }
548
549 /**
550 * Bundle all resources attached to this module into an array.
551 *
552 * @since 1.26
553 * @param ResourceLoaderContext $context
554 * @return array
555 */
556 final protected function buildContent( ResourceLoaderContext $context ) {
557 $rl = $context->getResourceLoader();
558 $stats = RequestContext::getMain()->getStats();
559 $statStart = microtime( true );
560
561 // Only include properties that are relevant to this context (e.g. only=scripts)
562 // and that are non-empty (e.g. don't include "templates" for modules without
563 // templates). This helps prevent invalidating cache for all modules when new
564 // optional properties are introduced.
565 $content = array();
566
567 // Scripts
568 if ( $context->shouldIncludeScripts() ) {
569 // If we are in debug mode, we'll want to return an array of URLs if possible
570 // However, we can't do this if the module doesn't support it
571 // We also can't do this if there is an only= parameter, because we have to give
572 // the module a way to return a load.php URL without causing an infinite loop
573 if ( $context->getDebug() && !$context->getOnly() && $this->supportsURLLoading() ) {
574 $scripts = $this->getScriptURLsForDebug( $context );
575 } else {
576 $scripts = $this->getScript( $context );
577 // rtrim() because there are usually a few line breaks
578 // after the last ';'. A new line at EOF, a new line
579 // added by ResourceLoaderFileModule::readScriptFiles, etc.
580 if ( is_string( $scripts )
581 && strlen( $scripts )
582 && substr( rtrim( $scripts ), -1 ) !== ';'
583 ) {
584 // Append semicolon to prevent weird bugs caused by files not
585 // terminating their statements right (bug 27054)
586 $scripts .= ";\n";
587 }
588 }
589 $content['scripts'] = $scripts;
590 }
591
592 // Styles
593 if ( $context->shouldIncludeStyles() ) {
594 $styles = array();
595 // Don't create empty stylesheets like array( '' => '' ) for modules
596 // that don't *have* any stylesheets (bug 38024).
597 $stylePairs = $this->getStyles( $context );
598 if ( count( $stylePairs ) ) {
599 // If we are in debug mode without &only= set, we'll want to return an array of URLs
600 // See comment near shouldIncludeScripts() for more details
601 if ( $context->getDebug() && !$context->getOnly() && $this->supportsURLLoading() ) {
602 $styles = array(
603 'url' => $this->getStyleURLsForDebug( $context )
604 );
605 } else {
606 // Minify CSS before embedding in mw.loader.implement call
607 // (unless in debug mode)
608 if ( !$context->getDebug() ) {
609 foreach ( $stylePairs as $media => $style ) {
610 // Can be either a string or an array of strings.
611 if ( is_array( $style ) ) {
612 $stylePairs[$media] = array();
613 foreach ( $style as $cssText ) {
614 if ( is_string( $cssText ) ) {
615 $stylePairs[$media][] =
616 ResourceLoader::filter( 'minify-css', $cssText );
617 }
618 }
619 } elseif ( is_string( $style ) ) {
620 $stylePairs[$media] = ResourceLoader::filter( 'minify-css', $style );
621 }
622 }
623 }
624 // Wrap styles into @media groups as needed and flatten into a numerical array
625 $styles = array(
626 'css' => $rl->makeCombinedStyles( $stylePairs )
627 );
628 }
629 }
630 $content['styles'] = $styles;
631 }
632
633 // Messages
634 $blob = $this->getMessageBlob( $context );
635 if ( $blob ) {
636 $content['messagesBlob'] = $blob;
637 }
638
639 $templates = $this->getTemplates();
640 if ( $templates ) {
641 $content['templates'] = $templates;
642 }
643
644 $statTiming = microtime( true ) - $statStart;
645 $statName = strtr( $this->getName(), '.', '_' );
646 $stats->timing( "resourceloader_build.all", 1000 * $statTiming );
647 $stats->timing( "resourceloader_build.$statName", 1000 * $statTiming );
648
649 return $content;
650 }
651
652 /**
653 * Get a string identifying the current version of this module in a given context.
654 *
655 * Whenever anything happens that changes the module's response (e.g. scripts, styles, and
656 * messages) this value must change. This value is used to store module responses in cache.
657 * (Both client-side and server-side.)
658 *
659 * It is not recommended to override this directly. Use getDefinitionSummary() instead.
660 * If overridden, one must call the parent getVersionHash(), append data and re-hash.
661 *
662 * This method should be quick because it is frequently run by ResourceLoaderStartUpModule to
663 * propagate changes to the client and effectively invalidate cache.
664 *
665 * For backward-compatibility, the following optional data providers are automatically included:
666 *
667 * - getModifiedTime()
668 * - getModifiedHash()
669 *
670 * @since 1.26
671 * @param ResourceLoaderContext $context
672 * @return string Hash (should use ResourceLoader::makeHash)
673 */
674 public function getVersionHash( ResourceLoaderContext $context ) {
675 // The startup module produces a manifest with versions representing the entire module.
676 // Typically, the request for the startup module itself has only=scripts. That must apply
677 // only to the startup module content, and not to the module version computed here.
678 $context = new DerivativeResourceLoaderContext( $context );
679 $context->setModules( array() );
680 // Version hash must cover all resources, regardless of startup request itself.
681 $context->setOnly( null );
682 // Compute version hash based on content, not debug urls.
683 $context->setDebug( false );
684
685 // Cache this somewhat expensive operation. Especially because some classes
686 // (e.g. startup module) iterate more than once over all modules to get versions.
687 $contextHash = $context->getHash();
688 if ( !array_key_exists( $contextHash, $this->versionHash ) ) {
689
690 if ( $this->enableModuleContentVersion() ) {
691 // Detect changes directly
692 $str = json_encode( $this->getModuleContent( $context ) );
693 } else {
694 // Infer changes based on definition and other metrics
695 $summary = $this->getDefinitionSummary( $context );
696 if ( !isset( $summary['_cacheEpoch'] ) ) {
697 throw new LogicException( 'getDefinitionSummary must call parent method' );
698 }
699 $str = json_encode( $summary );
700
701 $mtime = $this->getModifiedTime( $context );
702 if ( $mtime !== null ) {
703 // Support: MediaWiki 1.25 and earlier
704 $str .= strval( $mtime );
705 }
706
707 $mhash = $this->getModifiedHash( $context );
708 if ( $mhash !== null ) {
709 // Support: MediaWiki 1.25 and earlier
710 $str .= strval( $mhash );
711 }
712 }
713
714 $this->versionHash[$contextHash] = ResourceLoader::makeHash( $str );
715 }
716 return $this->versionHash[$contextHash];
717 }
718
719 /**
720 * Whether to generate version hash based on module content.
721 *
722 * If a module requires database or file system access to build the module
723 * content, consider disabling this in favour of manually tracking relevant
724 * aspects in getDefinitionSummary(). See getVersionHash() for how this is used.
725 *
726 * @return bool
727 */
728 public function enableModuleContentVersion() {
729 return false;
730 }
731
732 /**
733 * Get the definition summary for this module.
734 *
735 * This is the method subclasses are recommended to use to track values in their
736 * version hash. Call this in getVersionHash() and pass it to e.g. json_encode.
737 *
738 * Subclasses must call the parent getDefinitionSummary() and build on that.
739 * It is recommended that each subclass appends its own new array. This prevents
740 * clashes or accidental overwrites of existing keys and gives each subclass
741 * its own scope for simple array keys.
742 *
743 * @code
744 * $summary = parent::getDefinitionSummary( $context );
745 * $summary[] = array(
746 * 'foo' => 123,
747 * 'bar' => 'quux',
748 * );
749 * return $summary;
750 * @endcode
751 *
752 * Return an array containing values from all significant properties of this
753 * module's definition.
754 *
755 * Be careful not to normalise too much. Especially preserve the order of things
756 * that carry significance in getScript and getStyles (T39812).
757 *
758 * Avoid including things that are insiginificant (e.g. order of message keys is
759 * insignificant and should be sorted to avoid unnecessary cache invalidation).
760 *
761 * This data structure must exclusively contain arrays and scalars as values (avoid
762 * object instances) to allow simple serialisation using json_encode.
763 *
764 * If modules have a hash or timestamp from another source, that may be incuded as-is.
765 *
766 * A number of utility methods are available to help you gather data. These are not
767 * called by default and must be included by the subclass' getDefinitionSummary().
768 *
769 * - getMessageBlob()
770 *
771 * @since 1.23
772 * @param ResourceLoaderContext $context
773 * @return array|null
774 */
775 public function getDefinitionSummary( ResourceLoaderContext $context ) {
776 return array(
777 '_class' => get_class( $this ),
778 '_cacheEpoch' => $this->getConfig()->get( 'CacheEpoch' ),
779 );
780 }
781
782 /**
783 * Get this module's last modification timestamp for a given context.
784 *
785 * @deprecated since 1.26 Use getDefinitionSummary() instead
786 * @param ResourceLoaderContext $context Context object
787 * @return int|null UNIX timestamp
788 */
789 public function getModifiedTime( ResourceLoaderContext $context ) {
790 return null;
791 }
792
793 /**
794 * Helper method for providing a version hash to getVersionHash().
795 *
796 * @deprecated since 1.26 Use getDefinitionSummary() instead
797 * @param ResourceLoaderContext $context
798 * @return string|null Hash
799 */
800 public function getModifiedHash( ResourceLoaderContext $context ) {
801 return null;
802 }
803
804 /**
805 * Back-compat dummy for old subclass implementations of getModifiedTime().
806 *
807 * This method used to use ObjectCache to track when a hash was first seen. That principle
808 * stems from a time that ResourceLoader could only identify module versions by timestamp.
809 * That is no longer the case. Use getDefinitionSummary() directly.
810 *
811 * @deprecated since 1.26 Superseded by getVersionHash()
812 * @param ResourceLoaderContext $context
813 * @return int UNIX timestamp
814 */
815 public function getHashMtime( ResourceLoaderContext $context ) {
816 if ( !is_string( $this->getModifiedHash( $context ) ) ) {
817 return 1;
818 }
819 // Dummy that is > 1
820 return 2;
821 }
822
823 /**
824 * Back-compat dummy for old subclass implementations of getModifiedTime().
825 *
826 * @since 1.23
827 * @deprecated since 1.26 Superseded by getVersionHash()
828 * @param ResourceLoaderContext $context
829 * @return int UNIX timestamp
830 */
831 public function getDefinitionMtime( ResourceLoaderContext $context ) {
832 if ( $this->getDefinitionSummary( $context ) === null ) {
833 return 1;
834 }
835 // Dummy that is > 1
836 return 2;
837 }
838
839 /**
840 * Check whether this module is known to be empty. If a child class
841 * has an easy and cheap way to determine that this module is
842 * definitely going to be empty, it should override this method to
843 * return true in that case. Callers may optimize the request for this
844 * module away if this function returns true.
845 * @param ResourceLoaderContext $context
846 * @return bool
847 */
848 public function isKnownEmpty( ResourceLoaderContext $context ) {
849 return false;
850 }
851
852 /** @var JSParser Lazy-initialized; use self::javaScriptParser() */
853 private static $jsParser;
854 private static $parseCacheVersion = 1;
855
856 /**
857 * Validate a given script file; if valid returns the original source.
858 * If invalid, returns replacement JS source that throws an exception.
859 *
860 * @param string $fileName
861 * @param string $contents
862 * @return string JS with the original, or a replacement error
863 */
864 protected function validateScriptFile( $fileName, $contents ) {
865 if ( $this->getConfig()->get( 'ResourceLoaderValidateJS' ) ) {
866 // Try for cache hit
867 $cache = ObjectCache::getMainWANInstance();
868 $key = $cache->makeKey(
869 'resourceloader',
870 'jsparse',
871 self::$parseCacheVersion,
872 md5( $contents )
873 );
874 $cacheEntry = $cache->get( $key );
875 if ( is_string( $cacheEntry ) ) {
876 return $cacheEntry;
877 }
878
879 $parser = self::javaScriptParser();
880 try {
881 $parser->parse( $contents, $fileName, 1 );
882 $result = $contents;
883 } catch ( Exception $e ) {
884 // We'll save this to cache to avoid having to validate broken JS over and over...
885 $err = $e->getMessage();
886 $result = "mw.log.error(" .
887 Xml::encodeJsVar( "JavaScript parse error: $err" ) . ");";
888 }
889
890 $cache->set( $key, $result );
891 return $result;
892 } else {
893 return $contents;
894 }
895 }
896
897 /**
898 * @return JSParser
899 */
900 protected static function javaScriptParser() {
901 if ( !self::$jsParser ) {
902 self::$jsParser = new JSParser();
903 }
904 return self::$jsParser;
905 }
906
907 /**
908 * Safe version of filemtime(), which doesn't throw a PHP warning if the file doesn't exist.
909 * Defaults to 1.
910 *
911 * @param string $filePath File path
912 * @return int UNIX timestamp
913 */
914 protected static function safeFilemtime( $filePath ) {
915 MediaWiki\suppressWarnings();
916 $mtime = filemtime( $filePath ) ?: 1;
917 MediaWiki\restoreWarnings();
918 return $mtime;
919 }
920
921 /**
922 * Compute a non-cryptographic string hash of a file's contents.
923 * If the file does not exist or cannot be read, returns an empty string.
924 *
925 * @since 1.26 Uses MD4 instead of SHA1.
926 * @param string $filePath File path
927 * @return string Hash
928 */
929 protected static function safeFileHash( $filePath ) {
930 return FileContentsHasher::getFileContentsHash( $filePath );
931 }
932 }