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