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