Revert r90232.
[lhc/web/wiklou.git] / includes / resourceloader / ResourceLoader.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 * @author Roan Kattouw
20 * @author Trevor Parscal
21 */
22
23 /**
24 * Dynamic JavaScript and CSS resource loading system.
25 *
26 * Most of the documention is on the MediaWiki documentation wiki starting at:
27 * http://www.mediawiki.org/wiki/ResourceLoader
28 */
29 class ResourceLoader {
30
31 /* Protected Static Members */
32 protected static $filterCacheVersion = 4;
33
34 /** Array: List of module name/ResourceLoaderModule object pairs */
35 protected $modules = array();
36 /** Associative array mapping module name to info associative array */
37 protected $moduleInfos = array();
38
39 /* Protected Methods */
40
41 /**
42 * Loads information stored in the database about modules.
43 *
44 * This method grabs modules dependencies from the database and updates modules
45 * objects.
46 *
47 * This is not inside the module code because it is much faster to
48 * request all of the information at once than it is to have each module
49 * requests its own information. This sacrifice of modularity yields a substantial
50 * performance improvement.
51 *
52 * @param $modules Array: List of module names to preload information for
53 * @param $context ResourceLoaderContext: Context to load the information within
54 */
55 public function preloadModuleInfo( array $modules, ResourceLoaderContext $context ) {
56 if ( !count( $modules ) ) {
57 return; // or else Database*::select() will explode, plus it's cheaper!
58 }
59 $dbr = wfGetDB( DB_SLAVE );
60 $skin = $context->getSkin();
61 $lang = $context->getLanguage();
62
63 // Get file dependency information
64 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
65 'md_module' => $modules,
66 'md_skin' => $skin
67 ), __METHOD__
68 );
69
70 // Set modules' dependencies
71 $modulesWithDeps = array();
72 foreach ( $res as $row ) {
73 $this->getModule( $row->md_module )->setFileDependencies( $skin,
74 FormatJson::decode( $row->md_deps, true )
75 );
76 $modulesWithDeps[] = $row->md_module;
77 }
78
79 // Register the absence of a dependency row too
80 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
81 $this->getModule( $name )->setFileDependencies( $skin, array() );
82 }
83
84 // Get message blob mtimes. Only do this for modules with messages
85 $modulesWithMessages = array();
86 foreach ( $modules as $name ) {
87 if ( count( $this->getModule( $name )->getMessages() ) ) {
88 $modulesWithMessages[] = $name;
89 }
90 }
91 $modulesWithoutMessages = array_flip( $modules ); // Will be trimmed down by the loop below
92 if ( count( $modulesWithMessages ) ) {
93 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
94 'mr_resource' => $modulesWithMessages,
95 'mr_lang' => $lang
96 ), __METHOD__
97 );
98 foreach ( $res as $row ) {
99 $this->getModule( $row->mr_resource )->setMsgBlobMtime( $lang,
100 wfTimestamp( TS_UNIX, $row->mr_timestamp ) );
101 unset( $modulesWithoutMessages[$row->mr_resource] );
102 }
103 }
104 foreach ( array_keys( $modulesWithoutMessages ) as $name ) {
105 $this->getModule( $name )->setMsgBlobMtime( $lang, 0 );
106 }
107 }
108
109 /**
110 * Runs JavaScript or CSS data through a filter, caching the filtered result for future calls.
111 *
112 * Available filters are:
113 * - minify-js \see JavaScriptMinifier::minify
114 * - minify-css \see CSSMin::minify
115 *
116 * If $data is empty, only contains whitespace or the filter was unknown,
117 * $data is returned unmodified.
118 *
119 * @param $filter String: Name of filter to run
120 * @param $data String: Text to filter, such as JavaScript or CSS text
121 * @return String: Filtered data, or a comment containing an error message
122 */
123 protected function filter( $filter, $data ) {
124 global $wgResourceLoaderMinifierStatementsOnOwnLine, $wgResourceLoaderMinifierMaxLineLength;
125 wfProfileIn( __METHOD__ );
126
127 // For empty/whitespace-only data or for unknown filters, don't perform
128 // any caching or processing
129 if ( trim( $data ) === ''
130 || !in_array( $filter, array( 'minify-js', 'minify-css' ) ) )
131 {
132 wfProfileOut( __METHOD__ );
133 return $data;
134 }
135
136 // Try for cache hit
137 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
138 $key = wfMemcKey( 'resourceloader', 'filter', $filter, self::$filterCacheVersion, md5( $data ) );
139 $cache = wfGetCache( CACHE_ANYTHING );
140 $cacheEntry = $cache->get( $key );
141 if ( is_string( $cacheEntry ) ) {
142 wfProfileOut( __METHOD__ );
143 return $cacheEntry;
144 }
145
146 $result = '';
147 // Run the filter - we've already verified one of these will work
148 try {
149 switch ( $filter ) {
150 case 'minify-js':
151 $result = JavaScriptMinifier::minify( $data,
152 $wgResourceLoaderMinifierStatementsOnOwnLine,
153 $wgResourceLoaderMinifierMaxLineLength
154 );
155 $result .= "\n\n/* cache key: $key */\n";
156 break;
157 case 'minify-css':
158 $result = CSSMin::minify( $data );
159 $result .= "\n\n/* cache key: $key */\n";
160 break;
161 }
162
163 // Save filtered text to Memcached
164 $cache->set( $key, $result );
165 } catch ( Exception $exception ) {
166 // Return exception as a comment
167 $result = "/*\n{$exception->__toString()}\n*/\n";
168 }
169
170 wfProfileOut( __METHOD__ );
171
172 return $result;
173 }
174
175 /* Methods */
176
177 /**
178 * Registers core modules and runs registration hooks.
179 */
180 public function __construct() {
181 global $IP, $wgResourceModules;
182
183 wfProfileIn( __METHOD__ );
184
185 // Register core modules
186 $this->register( include( "$IP/resources/Resources.php" ) );
187 // Register extension modules
188 wfRunHooks( 'ResourceLoaderRegisterModules', array( &$this ) );
189 $this->register( $wgResourceModules );
190
191 wfProfileOut( __METHOD__ );
192 }
193
194 /**
195 * Registers a module with the ResourceLoader system.
196 *
197 * @param $name Mixed: Name of module as a string or List of name/object pairs as an array
198 * @param $info Module info array. For backwards compatibility with 1.17alpha,
199 * this may also be a ResourceLoaderModule object. Optional when using
200 * multiple-registration calling style.
201 * @throws MWException: If a duplicate module registration is attempted
202 * @throws MWException: If a module name contains illegal characters (pipes or commas)
203 * @throws MWException: If something other than a ResourceLoaderModule is being registered
204 * @return Boolean: False if there were any errors, in which case one or more modules were not
205 * registered
206 */
207 public function register( $name, $info = null ) {
208 wfProfileIn( __METHOD__ );
209
210 // Allow multiple modules to be registered in one call
211 if ( is_array( $name ) ) {
212 foreach ( $name as $key => $value ) {
213 $this->register( $key, $value );
214 }
215 wfProfileOut( __METHOD__ );
216 return;
217 }
218
219 // Disallow duplicate registrations
220 if ( isset( $this->moduleInfos[$name] ) ) {
221 // A module has already been registered by this name
222 throw new MWException(
223 'ResourceLoader duplicate registration error. ' .
224 'Another module has already been registered as ' . $name
225 );
226 }
227
228 // Check $name for illegal characters
229 if ( preg_match( '/[|,!]/', $name ) ) {
230 throw new MWException( "ResourceLoader module name '$name' is invalid. Names may not contain pipes (|), commas (,) or exclamation marks (!)" );
231 }
232
233 // Attach module
234 if ( is_object( $info ) ) {
235 // Old calling convention
236 // Validate the input
237 if ( !( $info instanceof ResourceLoaderModule ) ) {
238 throw new MWException( 'ResourceLoader invalid module error. ' .
239 'Instances of ResourceLoaderModule expected.' );
240 }
241
242 $this->moduleInfos[$name] = array( 'object' => $info );
243 $info->setName( $name );
244 $this->modules[$name] = $info;
245 } else {
246 // New calling convention
247 $this->moduleInfos[$name] = $info;
248 }
249
250 wfProfileOut( __METHOD__ );
251 }
252
253 /**
254 * Get a list of module names
255 *
256 * @return Array: List of module names
257 */
258 public function getModuleNames() {
259 return array_keys( $this->moduleInfos );
260 }
261
262 /**
263 * Get the ResourceLoaderModule object for a given module name.
264 *
265 * @param $name String: Module name
266 * @return ResourceLoaderModule if module has been registered, null otherwise
267 */
268 public function getModule( $name ) {
269 if ( !isset( $this->modules[$name] ) ) {
270 if ( !isset( $this->moduleInfos[$name] ) ) {
271 // No such module
272 return null;
273 }
274 // Construct the requested object
275 $info = $this->moduleInfos[$name];
276 if ( isset( $info['object'] ) ) {
277 // Object given in info array
278 $object = $info['object'];
279 } else {
280 if ( !isset( $info['class'] ) ) {
281 $class = 'ResourceLoaderFileModule';
282 } else {
283 $class = $info['class'];
284 }
285 $object = new $class( $info );
286 }
287 $object->setName( $name );
288 $this->modules[$name] = $object;
289 }
290
291 return $this->modules[$name];
292 }
293
294 /**
295 * Outputs a response to a resource load-request, including a content-type header.
296 *
297 * @param $context ResourceLoaderContext: Context in which a response should be formed
298 */
299 public function respond( ResourceLoaderContext $context ) {
300 global $wgResourceLoaderMaxage, $wgCacheEpoch;
301
302 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
303 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
304 // is used: ob_clean() will clear the GZIP header in that case and it won't come
305 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
306 // the whole thing in our own output buffer to be sure the active buffer
307 // doesn't use ob_gzhandler.
308 // See http://bugs.php.net/bug.php?id=36514
309 ob_start();
310
311 wfProfileIn( __METHOD__ );
312 $exceptions = '';
313
314 // Split requested modules into two groups, modules and missing
315 $modules = array();
316 $missing = array();
317 foreach ( $context->getModules() as $name ) {
318 if ( isset( $this->moduleInfos[$name] ) ) {
319 $modules[$name] = $this->getModule( $name );
320 } else {
321 $missing[] = $name;
322 }
323 }
324
325 // If a version wasn't specified we need a shorter expiry time for updates
326 // to propagate to clients quickly
327 if ( is_null( $context->getVersion() ) ) {
328 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
329 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
330 }
331 // If a version was specified we can use a longer expiry time since changing
332 // version numbers causes cache misses
333 else {
334 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
335 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
336 }
337
338 // Preload information needed to the mtime calculation below
339 try {
340 $this->preloadModuleInfo( array_keys( $modules ), $context );
341 } catch( Exception $e ) {
342 // Add exception to the output as a comment
343 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
344 }
345
346 wfProfileIn( __METHOD__.'-getModifiedTime' );
347
348 $private = false;
349 // To send Last-Modified and support If-Modified-Since, we need to detect
350 // the last modified time
351 $mtime = wfTimestamp( TS_UNIX, $wgCacheEpoch );
352 foreach ( $modules as $module ) {
353 try {
354 // Bypass Squid and other shared caches if the request includes any private modules
355 if ( $module->getGroup() === 'private' ) {
356 $private = true;
357 }
358 // Calculate maximum modified time
359 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
360 } catch ( Exception $e ) {
361 // Add exception to the output as a comment
362 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
363 }
364 }
365
366 wfProfileOut( __METHOD__.'-getModifiedTime' );
367
368 if ( $context->getOnly() === 'styles' ) {
369 header( 'Content-Type: text/css; charset=utf-8' );
370 } else {
371 header( 'Content-Type: text/javascript; charset=utf-8' );
372 }
373 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $mtime ) );
374 if ( $context->getDebug() ) {
375 // Do not cache debug responses
376 header( 'Cache-Control: private, no-cache, must-revalidate' );
377 header( 'Pragma: no-cache' );
378 } else {
379 if ( $private ) {
380 header( "Cache-Control: private, max-age=$maxage" );
381 $exp = $maxage;
382 } else {
383 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
384 $exp = min( $maxage, $smaxage );
385 }
386 header( 'Expires: ' . wfTimestamp( TS_RFC2822, $exp + time() ) );
387 }
388
389 // If there's an If-Modified-Since header, respond with a 304 appropriately
390 // Some clients send "timestamp;length=123". Strip the part after the first ';'
391 // so we get a valid timestamp.
392 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
393 // Never send 304s in debug mode
394 if ( $ims !== false && !$context->getDebug() ) {
395 $imsTS = strtok( $ims, ';' );
396 if ( $mtime <= wfTimestamp( TS_UNIX, $imsTS ) ) {
397 // There's another bug in ob_gzhandler (see also the comment at
398 // the top of this function) that causes it to gzip even empty
399 // responses, meaning it's impossible to produce a truly empty
400 // response (because the gzip header is always there). This is
401 // a problem because 304 responses have to be completely empty
402 // per the HTTP spec, and Firefox behaves buggily when they're not.
403 // See also http://bugs.php.net/bug.php?id=51579
404 // To work around this, we tear down all output buffering before
405 // sending the 304.
406 // On some setups, ob_get_level() doesn't seem to go down to zero
407 // no matter how often we call ob_get_clean(), so instead of doing
408 // the more intuitive while ( ob_get_level() > 0 ) ob_get_clean();
409 // we have to be safe here and avoid an infinite loop.
410 for ( $i = 0; $i < ob_get_level(); $i++ ) {
411 ob_end_clean();
412 }
413
414 header( 'HTTP/1.0 304 Not Modified' );
415 header( 'Status: 304 Not Modified' );
416 wfProfileOut( __METHOD__ );
417 return;
418 }
419 }
420
421 // Generate a response
422 $response = $this->makeModuleResponse( $context, $modules, $missing );
423
424 // Prepend comments indicating exceptions
425 $response = $exceptions . $response;
426
427 // Capture any PHP warnings from the output buffer and append them to the
428 // response in a comment if we're in debug mode.
429 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
430 $response = "/*\n$warnings\n*/\n" . $response;
431 }
432
433 // Remove the output buffer and output the response
434 ob_end_clean();
435 echo $response;
436
437 wfProfileOut( __METHOD__ );
438 }
439
440 /**
441 * Generates code for a response
442 *
443 * @param $context ResourceLoaderContext: Context in which to generate a response
444 * @param $modules Array: List of module objects keyed by module name
445 * @param $missing Array: List of unavailable modules (optional)
446 * @return String: Response data
447 */
448 public function makeModuleResponse( ResourceLoaderContext $context,
449 array $modules, $missing = array() )
450 {
451 $out = '';
452 $exceptions = '';
453 if ( $modules === array() && $missing === array() ) {
454 return '/* No modules requested. Max made me put this here */';
455 }
456
457 wfProfileIn( __METHOD__ );
458 // Pre-fetch blobs
459 if ( $context->shouldIncludeMessages() ) {
460 try {
461 $blobs = MessageBlobStore::get( $this, $modules, $context->getLanguage() );
462 } catch ( Exception $e ) {
463 // Add exception to the output as a comment
464 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
465 }
466 } else {
467 $blobs = array();
468 }
469
470 // Generate output
471 foreach ( $modules as $name => $module ) {
472 wfProfileIn( __METHOD__ . '-' . $name );
473 try {
474 $scripts = '';
475 if ( $context->shouldIncludeScripts() ) {
476 $scripts = $module->getScript( $context );
477 if ( is_string( $scripts ) ) {
478 // bug 27054: Append semicolon to prevent weird bugs
479 // caused by files not terminating their statements right
480 $scripts .= ";\n";
481 }
482 }
483 // Styles
484 $styles = array();
485 if ( $context->shouldIncludeStyles() ) {
486 $styles = $module->getStyles( $context );
487 }
488
489 // Messages
490 $messagesBlob = isset( $blobs[$name] ) ? $blobs[$name] : '{}';
491
492 // Append output
493 switch ( $context->getOnly() ) {
494 case 'scripts':
495 if ( is_string( $scripts ) ) {
496 $out .= $scripts;
497 } else if ( is_array( $scripts ) ) {
498 $out .= self::makeLoaderImplementScript( $name, $scripts, array(), array() );
499 }
500 break;
501 case 'styles':
502 $out .= self::makeCombinedStyles( $styles );
503 break;
504 case 'messages':
505 $out .= self::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
506 break;
507 default:
508 // Minify CSS before embedding in mw.loader.implement call
509 // (unless in debug mode)
510 if ( !$context->getDebug() ) {
511 foreach ( $styles as $media => $style ) {
512 if ( is_string( $style ) ) {
513 $styles[$media] = $this->filter( 'minify-css', $style );
514 }
515 }
516 }
517 $out .= self::makeLoaderImplementScript( $name, $scripts, $styles,
518 new XmlJsCode( $messagesBlob ) );
519 break;
520 }
521 } catch ( Exception $e ) {
522 // Add exception to the output as a comment
523 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
524
525 // Register module as missing
526 $missing[] = $name;
527 unset( $modules[$name] );
528 }
529 wfProfileOut( __METHOD__ . '-' . $name );
530 }
531
532 // Update module states
533 if ( $context->shouldIncludeScripts() ) {
534 // Set the state of modules loaded as only scripts to ready
535 if ( count( $modules ) && $context->getOnly() === 'scripts'
536 && !isset( $modules['startup'] ) )
537 {
538 $out .= self::makeLoaderStateScript(
539 array_fill_keys( array_keys( $modules ), 'ready' ) );
540 }
541 // Set the state of modules which were requested but unavailable as missing
542 if ( is_array( $missing ) && count( $missing ) ) {
543 $out .= self::makeLoaderStateScript( array_fill_keys( $missing, 'missing' ) );
544 }
545 }
546
547 if ( !$context->getDebug() ) {
548 if ( $context->getOnly() === 'styles' ) {
549 $out = $this->filter( 'minify-css', $out );
550 } else {
551 $out = $this->filter( 'minify-js', $out );
552 }
553 }
554
555 wfProfileOut( __METHOD__ );
556 return $exceptions . $out;
557 }
558
559 /* Static Methods */
560
561 /**
562 * Returns JS code to call to mw.loader.implement for a module with
563 * given properties.
564 *
565 * @param $name Module name
566 * @param $scripts Mixed: List of URLs to JavaScript files or String of JavaScript code
567 * @param $styles Mixed: List of CSS strings keyed by media type, or list of lists of URLs to
568 * CSS files keyed by media type
569 * @param $messages Mixed: List of messages associated with this module. May either be an
570 * associative array mapping message key to value, or a JSON-encoded message blob containing
571 * the same data, wrapped in an XmlJsCode object.
572 *
573 * @return string
574 */
575 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
576 if ( is_string( $scripts ) ) {
577 $scripts = new XmlJsCode( "function( $ ) {{$scripts}}" );
578 } else if ( !is_array( $scripts ) ) {
579 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
580 }
581 return Xml::encodeJsCall(
582 'mw.loader.implement',
583 array(
584 $name,
585 $scripts,
586 (object)$styles,
587 (object)$messages
588 ) );
589 }
590
591 /**
592 * Returns JS code which, when called, will register a given list of messages.
593 *
594 * @param $messages Mixed: Either an associative array mapping message key to value, or a
595 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
596 *
597 * @return string
598 */
599 public static function makeMessageSetScript( $messages ) {
600 return Xml::encodeJsCall( 'mw.messages.set', array( (object)$messages ) );
601 }
602
603 /**
604 * Combines an associative array mapping media type to CSS into a
605 * single stylesheet with @media blocks.
606 *
607 * @param $styles Array: List of CSS strings keyed by media type
608 *
609 * @return string
610 */
611 public static function makeCombinedStyles( array $styles ) {
612 $out = '';
613 foreach ( $styles as $media => $style ) {
614 // Transform the media type based on request params and config
615 // The way that this relies on $wgRequest to propagate request params is slightly evil
616 $media = OutputPage::transformCssMedia( $media );
617
618 if ( $media === null ) {
619 // Skip
620 } else if ( $media === '' || $media == 'all' ) {
621 // Don't output invalid or frivolous @media statements
622 $out .= "$style\n";
623 } else {
624 $out .= "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "\n}\n";
625 }
626 }
627 return $out;
628 }
629
630 /**
631 * Returns a JS call to mw.loader.state, which sets the state of a
632 * module or modules to a given value. Has two calling conventions:
633 *
634 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
635 * Set the state of a single module called $name to $state
636 *
637 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
638 * Set the state of modules with the given names to the given states
639 *
640 * @param $name string
641 * @param $state
642 *
643 * @return string
644 */
645 public static function makeLoaderStateScript( $name, $state = null ) {
646 if ( is_array( $name ) ) {
647 return Xml::encodeJsCall( 'mw.loader.state', array( $name ) );
648 } else {
649 return Xml::encodeJsCall( 'mw.loader.state', array( $name, $state ) );
650 }
651 }
652
653 /**
654 * Returns JS code which calls the script given by $script. The script will
655 * be called with local variables name, version, dependencies and group,
656 * which will have values corresponding to $name, $version, $dependencies
657 * and $group as supplied.
658 *
659 * @param $name String: Module name
660 * @param $version Integer: Module version number as a timestamp
661 * @param $dependencies Array: List of module names on which this module depends
662 * @param $group String: Group which the module is in.
663 * @param $script String: JavaScript code
664 *
665 * @return string
666 */
667 public static function makeCustomLoaderScript( $name, $version, $dependencies, $group, $script ) {
668 $script = str_replace( "\n", "\n\t", trim( $script ) );
669 return Xml::encodeJsCall(
670 "( function( name, version, dependencies, group ) {\n\t$script\n} )",
671 array( $name, $version, $dependencies, $group ) );
672 }
673
674 /**
675 * Returns JS code which calls mw.loader.register with the given
676 * parameters. Has three calling conventions:
677 *
678 * - ResourceLoader::makeLoaderRegisterScript( $name, $version, $dependencies, $group ):
679 * Register a single module.
680 *
681 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
682 * Register modules with the given names.
683 *
684 * - ResourceLoader::makeLoaderRegisterScript( array(
685 * array( $name1, $version1, $dependencies1, $group1 ),
686 * array( $name2, $version2, $dependencies1, $group2 ),
687 * ...
688 * ) ):
689 * Registers modules with the given names and parameters.
690 *
691 * @param $name String: Module name
692 * @param $version Integer: Module version number as a timestamp
693 * @param $dependencies Array: List of module names on which this module depends
694 * @param $group String: group which the module is in.
695 *
696 * @return string
697 */
698 public static function makeLoaderRegisterScript( $name, $version = null,
699 $dependencies = null, $group = null )
700 {
701 if ( is_array( $name ) ) {
702 return Xml::encodeJsCall( 'mw.loader.register', array( $name ) );
703 } else {
704 $version = (int) $version > 1 ? (int) $version : 1;
705 return Xml::encodeJsCall( 'mw.loader.register',
706 array( $name, $version, $dependencies, $group ) );
707 }
708 }
709
710 /**
711 * Returns JS code which runs given JS code if the client-side framework is
712 * present.
713 *
714 * @param $script String: JavaScript code
715 *
716 * @return string
717 */
718 public static function makeLoaderConditionalScript( $script ) {
719 $script = str_replace( "\n", "\n\t", trim( $script ) );
720 return "if ( window.mediaWiki ) {\n\t$script\n}\n";
721 }
722
723 /**
724 * Returns JS code which will set the MediaWiki configuration array to
725 * the given value.
726 *
727 * @param $configuration Array: List of configuration values keyed by variable name
728 *
729 * @return string
730 */
731 public static function makeConfigSetScript( array $configuration ) {
732 return Xml::encodeJsCall( 'mw.config.set', array( $configuration ) );
733 }
734
735 /**
736 * Convert an array of module names to a packed query string.
737 *
738 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
739 * becomes 'foo.bar,baz|bar.baz,quux'
740 * @param $modules array of module names (strings)
741 * @return string Packed query string
742 */
743 public static function makePackedModulesString( $modules ) {
744 $groups = array(); // array( prefix => array( suffixes ) )
745 foreach ( $modules as $module ) {
746 $pos = strrpos( $module, '.' );
747 $prefix = $pos === false ? '' : substr( $module, 0, $pos );
748 $suffix = $pos === false ? $module : substr( $module, $pos + 1 );
749 $groups[$prefix][] = $suffix;
750 }
751
752 $arr = array();
753 foreach ( $groups as $prefix => $suffixes ) {
754 $p = $prefix === '' ? '' : $prefix . '.';
755 $arr[] = $p . implode( ',', $suffixes );
756 }
757 $str = implode( '|', $arr );
758 return $str;
759 }
760
761 /**
762 * Determine whether debug mode was requested
763 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
764 * @return bool
765 */
766 public static function inDebugMode() {
767 global $wgRequest, $wgResourceLoaderDebug;
768 static $retval = null;
769 if ( !is_null( $retval ) ) {
770 return $retval;
771 }
772 return $retval = $wgRequest->getFuzzyBool( 'debug',
773 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug ) );
774 }
775 }