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