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