Merge "Remove unused 'XMPGetInfo' and 'XMPGetResults' hooks"
[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
68 /**
69 * @var Config
70 */
71 protected $config;
72
73 /* Methods */
74
75 /**
76 * Get this module's name. This is set when the module is registered
77 * with ResourceLoader::register()
78 *
79 * @return string|null Name (string) or null if no name was set
80 */
81 public function getName() {
82 return $this->name;
83 }
84
85 /**
86 * Set this module's name. This is called by ResourceLoader::register()
87 * when registering the module. Other code should not call this.
88 *
89 * @param string $name Name
90 */
91 public function setName( $name ) {
92 $this->name = $name;
93 }
94
95 /**
96 * Get this module's origin. This is set when the module is registered
97 * with ResourceLoader::register()
98 *
99 * @return int ResourceLoaderModule class constant, the subclass default
100 * if not set manually
101 */
102 public function getOrigin() {
103 return $this->origin;
104 }
105
106 /**
107 * Set this module's origin. This is called by ResourceLoader::register()
108 * when registering the module. Other code should not call this.
109 *
110 * @param int $origin Origin
111 */
112 public function setOrigin( $origin ) {
113 $this->origin = $origin;
114 }
115
116 /**
117 * @param ResourceLoaderContext $context
118 * @return bool
119 */
120 public function getFlip( $context ) {
121 global $wgContLang;
122
123 return $wgContLang->getDir() !== $context->getDirection();
124 }
125
126 /**
127 * Get all JS for this module for a given language and skin.
128 * Includes all relevant JS except loader scripts.
129 *
130 * @param ResourceLoaderContext $context
131 * @return string JavaScript code
132 */
133 public function getScript( ResourceLoaderContext $context ) {
134 // Stub, override expected
135 return '';
136 }
137
138 /**
139 * Takes named templates by the module and returns an array mapping.
140 *
141 * @return array of templates mapping template alias to content
142 */
143 public function getTemplates() {
144 // Stub, override expected.
145 return array();
146 }
147
148 /**
149 * @return Config
150 * @since 1.24
151 */
152 public function getConfig() {
153 if ( $this->config === null ) {
154 // Ugh, fall back to default
155 $this->config = ConfigFactory::getDefaultInstance()->makeConfig( 'main' );
156 }
157
158 return $this->config;
159 }
160
161 /**
162 * @param Config $config
163 * @since 1.24
164 */
165 public function setConfig( Config $config ) {
166 $this->config = $config;
167 }
168
169 /**
170 * Get the URL or URLs to load for this module's JS in debug mode.
171 * The default behavior is to return a load.php?only=scripts URL for
172 * the module, but file-based modules will want to override this to
173 * load the files directly.
174 *
175 * This function is called only when 1) we're in debug mode, 2) there
176 * is no only= parameter and 3) supportsURLLoading() returns true.
177 * #2 is important to prevent an infinite loop, therefore this function
178 * MUST return either an only= URL or a non-load.php URL.
179 *
180 * @param ResourceLoaderContext $context
181 * @return array Array of URLs
182 */
183 public function getScriptURLsForDebug( ResourceLoaderContext $context ) {
184 $resourceLoader = $context->getResourceLoader();
185 $derivative = new DerivativeResourceLoaderContext( $context );
186 $derivative->setModules( array( $this->getName() ) );
187 $derivative->setOnly( 'scripts' );
188 $derivative->setDebug( true );
189
190 $url = $resourceLoader->createLoaderURL(
191 $this->getSource(),
192 $derivative
193 );
194
195 return array( $url );
196 }
197
198 /**
199 * Whether this module supports URL loading. If this function returns false,
200 * getScript() will be used even in cases (debug mode, no only param) where
201 * getScriptURLsForDebug() would normally be used instead.
202 * @return bool
203 */
204 public function supportsURLLoading() {
205 return true;
206 }
207
208 /**
209 * Get all CSS for this module for a given skin.
210 *
211 * @param ResourceLoaderContext $context
212 * @return array List of CSS strings or array of CSS strings keyed by media type.
213 * like array( 'screen' => '.foo { width: 0 }' );
214 * or array( 'screen' => array( '.foo { width: 0 }' ) );
215 */
216 public function getStyles( ResourceLoaderContext $context ) {
217 // Stub, override expected
218 return array();
219 }
220
221 /**
222 * Get the URL or URLs to load for this module's CSS in debug mode.
223 * The default behavior is to return a load.php?only=styles URL for
224 * the module, but file-based modules will want to override this to
225 * load the files directly. See also getScriptURLsForDebug()
226 *
227 * @param ResourceLoaderContext $context
228 * @return array Array( mediaType => array( URL1, URL2, ... ), ... )
229 */
230 public function getStyleURLsForDebug( ResourceLoaderContext $context ) {
231 $resourceLoader = $context->getResourceLoader();
232 $derivative = new DerivativeResourceLoaderContext( $context );
233 $derivative->setModules( array( $this->getName() ) );
234 $derivative->setOnly( 'styles' );
235 $derivative->setDebug( true );
236
237 $url = $resourceLoader->createLoaderURL(
238 $this->getSource(),
239 $derivative
240 );
241
242 return array( 'all' => array( $url ) );
243 }
244
245 /**
246 * Get the messages needed for this module.
247 *
248 * To get a JSON blob with messages, use MessageBlobStore::get()
249 *
250 * @return array List of message keys. Keys may occur more than once
251 */
252 public function getMessages() {
253 // Stub, override expected
254 return array();
255 }
256
257 /**
258 * Get the group this module is in.
259 *
260 * @return string Group name
261 */
262 public function getGroup() {
263 // Stub, override expected
264 return null;
265 }
266
267 /**
268 * Get the origin of this module. Should only be overridden for foreign modules.
269 *
270 * @return string Origin name, 'local' for local modules
271 */
272 public function getSource() {
273 // Stub, override expected
274 return 'local';
275 }
276
277 /**
278 * Where on the HTML page should this module's JS be loaded?
279 * - 'top': in the "<head>"
280 * - 'bottom': at the bottom of the "<body>"
281 *
282 * @return string
283 */
284 public function getPosition() {
285 return 'bottom';
286 }
287
288 /**
289 * Whether this module's JS expects to work without the client-side ResourceLoader module.
290 * Returning true from this function will prevent mw.loader.state() call from being
291 * appended to the bottom of the script.
292 *
293 * @return bool
294 */
295 public function isRaw() {
296 return false;
297 }
298
299 /**
300 * Get the loader JS for this module, if set.
301 *
302 * @return mixed JavaScript loader code as a string or boolean false if no custom loader set
303 */
304 public function getLoaderScript() {
305 // Stub, override expected
306 return false;
307 }
308
309 /**
310 * Get a list of modules this module depends on.
311 *
312 * Dependency information is taken into account when loading a module
313 * on the client side.
314 *
315 * To add dependencies dynamically on the client side, use a custom
316 * loader script, see getLoaderScript()
317 * @return array List of module names as strings
318 */
319 public function getDependencies() {
320 // Stub, override expected
321 return array();
322 }
323
324 /**
325 * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
326 *
327 * @return array Array of strings
328 */
329 public function getTargets() {
330 return $this->targets;
331 }
332
333 /**
334 * Get the skip function.
335 *
336 * Modules that provide fallback functionality can provide a "skip function". This
337 * function, if provided, will be passed along to the module registry on the client.
338 * When this module is loaded (either directly or as a dependency of another module),
339 * then this function is executed first. If the function returns true, the module will
340 * instantly be considered "ready" without requesting the associated module resources.
341 *
342 * The value returned here must be valid javascript for execution in a private function.
343 * It must not contain the "function () {" and "}" wrapper though.
344 *
345 * @return string|null A JavaScript function body returning a boolean value, or null
346 */
347 public function getSkipFunction() {
348 return null;
349 }
350
351 /**
352 * Get the files this module depends on indirectly for a given skin.
353 * Currently these are only image files referenced by the module's CSS.
354 *
355 * @param string $skin Skin name
356 * @return array List of files
357 */
358 public function getFileDependencies( $skin ) {
359 // Try in-object cache first
360 if ( isset( $this->fileDeps[$skin] ) ) {
361 return $this->fileDeps[$skin];
362 }
363
364 $dbr = wfGetDB( DB_SLAVE );
365 $deps = $dbr->selectField( 'module_deps', 'md_deps', array(
366 'md_module' => $this->getName(),
367 'md_skin' => $skin,
368 ), __METHOD__
369 );
370 if ( !is_null( $deps ) ) {
371 $this->fileDeps[$skin] = (array)FormatJson::decode( $deps, true );
372 } else {
373 $this->fileDeps[$skin] = array();
374 }
375 return $this->fileDeps[$skin];
376 }
377
378 /**
379 * Set preloaded file dependency information. Used so we can load this
380 * information for all modules at once.
381 * @param string $skin Skin name
382 * @param array $deps Array of file names
383 */
384 public function setFileDependencies( $skin, $deps ) {
385 $this->fileDeps[$skin] = $deps;
386 }
387
388 /**
389 * Get the last modification timestamp of the messages in this module for a given language.
390 * @param string $lang Language code
391 * @return int UNIX timestamp
392 */
393 public function getMsgBlobMtime( $lang ) {
394 if ( !isset( $this->msgBlobMtime[$lang] ) ) {
395 if ( !count( $this->getMessages() ) ) {
396 return 1;
397 }
398
399 $dbr = wfGetDB( DB_SLAVE );
400 $msgBlobMtime = $dbr->selectField( 'msg_resource', 'mr_timestamp', array(
401 'mr_resource' => $this->getName(),
402 'mr_lang' => $lang
403 ), __METHOD__
404 );
405 // If no blob was found, but the module does have messages, that means we need
406 // to regenerate it. Return NOW
407 if ( $msgBlobMtime === false ) {
408 $msgBlobMtime = wfTimestampNow();
409 }
410 $this->msgBlobMtime[$lang] = wfTimestamp( TS_UNIX, $msgBlobMtime );
411 }
412 return $this->msgBlobMtime[$lang];
413 }
414
415 /**
416 * Set a preloaded message blob last modification timestamp. Used so we
417 * can load this information for all modules at once.
418 * @param string $lang Language code
419 * @param int $mtime UNIX timestamp
420 */
421 public function setMsgBlobMtime( $lang, $mtime ) {
422 $this->msgBlobMtime[$lang] = $mtime;
423 }
424
425 /**
426 * Get a string identifying the current version of this module in a given context.
427 *
428 * Whenever anything happens that changes the module's response (e.g. scripts, styles, and
429 * messages) this value must change. This value is used to store module responses in cache.
430 * (Both client-side and server-side.)
431 *
432 * It is not recommended to override this directly. Use getDefinitionSummary() instead.
433 * If overridden, one must call the parent getVersionHash(), append data and re-hash.
434 *
435 * This method should be quick because it is frequently run by ResourceLoaderStartUpModule to
436 * propagate changes to the client and effectively invalidate cache.
437 *
438 * For backward-compatibility, the following optional data providers are automatically included:
439 *
440 * - getModifiedTime()
441 * - getModifiedHash()
442 *
443 * @since 1.26
444 * @param ResourceLoaderContext $context
445 * @return string Hash (should use ResourceLoader::makeHash)
446 */
447 public function getVersionHash( ResourceLoaderContext $context ) {
448 // Cache this somewhat expensive operation. Especially because some classes
449 // (e.g. startup module) iterate more than once over all modules to get versions.
450 $contextHash = $context->getHash();
451 if ( !array_key_exists( $contextHash, $this->versionHash ) ) {
452
453 $summary = $this->getDefinitionSummary( $context );
454 if ( !isset( $summary['_cacheEpoch'] ) ) {
455 throw new Exception( 'getDefinitionSummary must call parent method' );
456 }
457 $str = json_encode( $summary );
458
459 $mtime = $this->getModifiedTime( $context );
460 if ( $mtime !== null ) {
461 // Support: MediaWiki 1.25 and earlier
462 $str .= strval( $mtime );
463 }
464
465 $mhash = $this->getModifiedHash( $context );
466 if ( $mhash !== null ) {
467 // Support: MediaWiki 1.25 and earlier
468 $str .= strval( $mhash );
469 }
470
471 $this->versionHash[ $contextHash ] = ResourceLoader::makeHash( $str );
472 }
473 return $this->versionHash[ $contextHash ];
474 }
475
476 /**
477 * Get the definition summary for this module.
478 *
479 * This is the method subclasses are recommended to use to track values in their
480 * version hash. Call this in getVersionHash() and pass it to e.g. json_encode.
481 *
482 * Subclasses must call the parent getDefinitionSummary() and build on that.
483 * It is recommended that each subclass appends its own new array. This prevents
484 * clashes or accidental overwrites of existing keys and gives each subclass
485 * its own scope for simple array keys.
486 *
487 * @code
488 * $summary = parent::getDefinitionSummary( $context );
489 * $summary[] = array(
490 * 'foo' => 123,
491 * 'bar' => 'quux',
492 * );
493 * return $summary;
494 * @endcode
495 *
496 * Return an array containing values from all significant properties of this
497 * module's definition.
498 *
499 * Be careful not to normalise too much. Especially preserve the order of things
500 * that carry significance in getScript and getStyles (T39812).
501 *
502 * Avoid including things that are insiginificant (e.g. order of message keys is
503 * insignificant and should be sorted to avoid unnecessary cache invalidation).
504 *
505 * This data structure must exclusively contain arrays and scalars as values (avoid
506 * object instances) to allow simple serialisation using json_encode.
507 *
508 * If modules have a hash or timestamp from another source, that may be incuded as-is.
509 *
510 * A number of utility methods are available to help you gather data. These are not
511 * called by default and must be included by the subclass' getDefinitionSummary().
512 *
513 * - getMsgBlobMtime()
514 *
515 * @since 1.23
516 * @param ResourceLoaderContext $context
517 * @return array|null
518 */
519 public function getDefinitionSummary( ResourceLoaderContext $context ) {
520 return array(
521 '_class' => get_class( $this ),
522 '_cacheEpoch' => $this->getConfig()->get( 'CacheEpoch' ),
523 );
524 }
525
526 /**
527 * Get this module's last modification timestamp for a given context.
528 *
529 * @deprecated since 1.26 Use getDefinitionSummary() instead
530 * @param ResourceLoaderContext $context Context object
531 * @return int|null UNIX timestamp
532 */
533 public function getModifiedTime( ResourceLoaderContext $context ) {
534 return null;
535 }
536
537 /**
538 * Helper method for providing a version hash to getVersionHash().
539 *
540 * @deprecated since 1.26 Use getDefinitionSummary() instead
541 * @param ResourceLoaderContext $context
542 * @return string|null Hash
543 */
544 public function getModifiedHash( ResourceLoaderContext $context ) {
545 return null;
546 }
547
548 /**
549 * Back-compat dummy for old subclass implementations of getModifiedTime().
550 *
551 * This method used to use ObjectCache to track when a hash was first seen. That principle
552 * stems from a time that ResourceLoader could only identify module versions by timestamp.
553 * That is no longer the case. Use getDefinitionSummary() directly.
554 *
555 * @deprecated since 1.26 Superseded by getVersionHash()
556 * @param ResourceLoaderContext $context
557 * @return int UNIX timestamp
558 */
559 public function getHashMtime( ResourceLoaderContext $context ) {
560 if ( !is_string( $this->getModifiedHash( $context ) ) ) {
561 return 1;
562 }
563 // Dummy that is > 1
564 return 2;
565 }
566
567 /**
568 * Back-compat dummy for old subclass implementations of getModifiedTime().
569 *
570 * @since 1.23
571 * @deprecated since 1.26 Superseded by getVersionHash()
572 * @param ResourceLoaderContext $context
573 * @return int UNIX timestamp
574 */
575 public function getDefinitionMtime( ResourceLoaderContext $context ) {
576 if ( $this->getDefinitionSummary( $context ) === null ) {
577 return 1;
578 }
579 // Dummy that is > 1
580 return 2;
581 }
582
583 /**
584 * Check whether this module is known to be empty. If a child class
585 * has an easy and cheap way to determine that this module is
586 * definitely going to be empty, it should override this method to
587 * return true in that case. Callers may optimize the request for this
588 * module away if this function returns true.
589 * @param ResourceLoaderContext $context
590 * @return bool
591 */
592 public function isKnownEmpty( ResourceLoaderContext $context ) {
593 return false;
594 }
595
596 /** @var JSParser Lazy-initialized; use self::javaScriptParser() */
597 private static $jsParser;
598 private static $parseCacheVersion = 1;
599
600 /**
601 * Validate a given script file; if valid returns the original source.
602 * If invalid, returns replacement JS source that throws an exception.
603 *
604 * @param string $fileName
605 * @param string $contents
606 * @return string JS with the original, or a replacement error
607 */
608 protected function validateScriptFile( $fileName, $contents ) {
609 if ( $this->getConfig()->get( 'ResourceLoaderValidateJS' ) ) {
610 // Try for cache hit
611 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
612 $key = wfMemcKey( 'resourceloader', 'jsparse', self::$parseCacheVersion, md5( $contents ) );
613 $cache = wfGetCache( CACHE_ANYTHING );
614 $cacheEntry = $cache->get( $key );
615 if ( is_string( $cacheEntry ) ) {
616 return $cacheEntry;
617 }
618
619 $parser = self::javaScriptParser();
620 try {
621 $parser->parse( $contents, $fileName, 1 );
622 $result = $contents;
623 } catch ( Exception $e ) {
624 // We'll save this to cache to avoid having to validate broken JS over and over...
625 $err = $e->getMessage();
626 $result = "throw new Error(" . Xml::encodeJsVar( "JavaScript parse error: $err" ) . ");";
627 }
628
629 $cache->set( $key, $result );
630 return $result;
631 } else {
632 return $contents;
633 }
634 }
635
636 /**
637 * @return JSParser
638 */
639 protected static function javaScriptParser() {
640 if ( !self::$jsParser ) {
641 self::$jsParser = new JSParser();
642 }
643 return self::$jsParser;
644 }
645
646 /**
647 * Safe version of filemtime(), which doesn't throw a PHP warning if the file doesn't exist
648 * but returns 1 instead.
649 * @param string $filename File name
650 * @return int UNIX timestamp
651 */
652 protected static function safeFilemtime( $filename ) {
653 wfSuppressWarnings();
654 $mtime = filemtime( $filename ) ?: 1;
655 wfRestoreWarnings();
656
657 return $mtime;
658 }
659 }