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