Refactored out new sendResponseHeaders() and tryRespondLastModified() functions out...
[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 = 5;
33 protected static $requiredSourceProperties = array( 'loadScript' );
34
35 /** Array: List of module name/ResourceLoaderModule object pairs */
36 protected $modules = array();
37
38 /** Associative array mapping module name to info associative array */
39 protected $moduleInfos = array();
40
41 /** array( 'source-id' => array( 'loadScript' => 'http://.../load.php' ) ) **/
42 protected $sources = array();
43
44 /* Protected Methods */
45
46 /**
47 * Loads information stored in the database about modules.
48 *
49 * This method grabs modules dependencies from the database and updates modules
50 * objects.
51 *
52 * This is not inside the module code because it is much faster to
53 * request all of the information at once than it is to have each module
54 * requests its own information. This sacrifice of modularity yields a substantial
55 * performance improvement.
56 *
57 * @param $modules Array: List of module names to preload information for
58 * @param $context ResourceLoaderContext: Context to load the information within
59 */
60 public function preloadModuleInfo( array $modules, ResourceLoaderContext $context ) {
61 if ( !count( $modules ) ) {
62 return; // or else Database*::select() will explode, plus it's cheaper!
63 }
64 $dbr = wfGetDB( DB_SLAVE );
65 $skin = $context->getSkin();
66 $lang = $context->getLanguage();
67
68 // Get file dependency information
69 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
70 'md_module' => $modules,
71 'md_skin' => $skin
72 ), __METHOD__
73 );
74
75 // Set modules' dependencies
76 $modulesWithDeps = array();
77 foreach ( $res as $row ) {
78 $this->getModule( $row->md_module )->setFileDependencies( $skin,
79 FormatJson::decode( $row->md_deps, true )
80 );
81 $modulesWithDeps[] = $row->md_module;
82 }
83
84 // Register the absence of a dependency row too
85 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
86 $this->getModule( $name )->setFileDependencies( $skin, array() );
87 }
88
89 // Get message blob mtimes. Only do this for modules with messages
90 $modulesWithMessages = array();
91 foreach ( $modules as $name ) {
92 if ( count( $this->getModule( $name )->getMessages() ) ) {
93 $modulesWithMessages[] = $name;
94 }
95 }
96 $modulesWithoutMessages = array_flip( $modules ); // Will be trimmed down by the loop below
97 if ( count( $modulesWithMessages ) ) {
98 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
99 'mr_resource' => $modulesWithMessages,
100 'mr_lang' => $lang
101 ), __METHOD__
102 );
103 foreach ( $res as $row ) {
104 $this->getModule( $row->mr_resource )->setMsgBlobMtime( $lang,
105 wfTimestamp( TS_UNIX, $row->mr_timestamp ) );
106 unset( $modulesWithoutMessages[$row->mr_resource] );
107 }
108 }
109 foreach ( array_keys( $modulesWithoutMessages ) as $name ) {
110 $this->getModule( $name )->setMsgBlobMtime( $lang, 0 );
111 }
112 }
113
114 /**
115 * Runs JavaScript or CSS data through a filter, caching the filtered result for future calls.
116 *
117 * Available filters are:
118 * - minify-js \see JavaScriptMinifier::minify
119 * - minify-css \see CSSMin::minify
120 *
121 * If $data is empty, only contains whitespace or the filter was unknown,
122 * $data is returned unmodified.
123 *
124 * @param $filter String: Name of filter to run
125 * @param $data String: Text to filter, such as JavaScript or CSS text
126 * @return String: Filtered data, or a comment containing an error message
127 */
128 protected function filter( $filter, $data ) {
129 global $wgResourceLoaderMinifierStatementsOnOwnLine, $wgResourceLoaderMinifierMaxLineLength;
130 wfProfileIn( __METHOD__ );
131
132 // For empty/whitespace-only data or for unknown filters, don't perform
133 // any caching or processing
134 if ( trim( $data ) === ''
135 || !in_array( $filter, array( 'minify-js', 'minify-css' ) ) )
136 {
137 wfProfileOut( __METHOD__ );
138 return $data;
139 }
140
141 // Try for cache hit
142 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
143 $key = wfMemcKey( 'resourceloader', 'filter', $filter, self::$filterCacheVersion, md5( $data ) );
144 $cache = wfGetCache( CACHE_ANYTHING );
145 $cacheEntry = $cache->get( $key );
146 if ( is_string( $cacheEntry ) ) {
147 wfProfileOut( __METHOD__ );
148 return $cacheEntry;
149 }
150
151 $result = '';
152 // Run the filter - we've already verified one of these will work
153 try {
154 switch ( $filter ) {
155 case 'minify-js':
156 $result = JavaScriptMinifier::minify( $data,
157 $wgResourceLoaderMinifierStatementsOnOwnLine,
158 $wgResourceLoaderMinifierMaxLineLength
159 );
160 $result .= "\n\n/* cache key: $key */\n";
161 break;
162 case 'minify-css':
163 $result = CSSMin::minify( $data );
164 $result .= "\n\n/* cache key: $key */\n";
165 break;
166 }
167
168 // Save filtered text to Memcached
169 $cache->set( $key, $result );
170 } catch ( Exception $exception ) {
171 // Return exception as a comment
172 $result = "/*\n{$exception->__toString()}\n*/\n";
173 }
174
175 wfProfileOut( __METHOD__ );
176
177 return $result;
178 }
179
180 /* Methods */
181
182 /**
183 * Registers core modules and runs registration hooks.
184 */
185 public function __construct() {
186 global $IP, $wgResourceModules, $wgResourceLoaderSources, $wgLoadScript;
187
188 wfProfileIn( __METHOD__ );
189
190 // Add 'local' source first
191 $this->addSource( 'local', array( 'loadScript' => $wgLoadScript, 'apiScript' => wfScript( 'api' ) ) );
192
193 // Add other sources
194 $this->addSource( $wgResourceLoaderSources );
195
196 // Register core modules
197 $this->register( include( "$IP/resources/Resources.php" ) );
198 // Register extension modules
199 wfRunHooks( 'ResourceLoaderRegisterModules', array( &$this ) );
200 $this->register( $wgResourceModules );
201
202 wfProfileOut( __METHOD__ );
203 }
204
205 /**
206 * Registers a module with the ResourceLoader system.
207 *
208 * @param $name Mixed: Name of module as a string or List of name/object pairs as an array
209 * @param $info Module info array. For backwards compatibility with 1.17alpha,
210 * this may also be a ResourceLoaderModule object. Optional when using
211 * multiple-registration calling style.
212 * @throws MWException: If a duplicate module registration is attempted
213 * @throws MWException: If a module name contains illegal characters (pipes or commas)
214 * @throws MWException: If something other than a ResourceLoaderModule is being registered
215 * @return Boolean: False if there were any errors, in which case one or more modules were not
216 * registered
217 */
218 public function register( $name, $info = null ) {
219 wfProfileIn( __METHOD__ );
220
221 // Allow multiple modules to be registered in one call
222 if ( is_array( $name ) ) {
223 foreach ( $name as $key => $value ) {
224 $this->register( $key, $value );
225 }
226 wfProfileOut( __METHOD__ );
227 return;
228 }
229
230 // Disallow duplicate registrations
231 if ( isset( $this->moduleInfos[$name] ) ) {
232 // A module has already been registered by this name
233 throw new MWException(
234 'ResourceLoader duplicate registration error. ' .
235 'Another module has already been registered as ' . $name
236 );
237 }
238
239 // Check $name for illegal characters
240 if ( preg_match( '/[|,!]/', $name ) ) {
241 throw new MWException( "ResourceLoader module name '$name' is invalid. Names may not contain pipes (|), commas (,) or exclamation marks (!)" );
242 }
243
244 // Attach module
245 if ( is_object( $info ) ) {
246 // Old calling convention
247 // Validate the input
248 if ( !( $info instanceof ResourceLoaderModule ) ) {
249 throw new MWException( 'ResourceLoader invalid module error. ' .
250 'Instances of ResourceLoaderModule expected.' );
251 }
252
253 $this->moduleInfos[$name] = array( 'object' => $info );
254 $info->setName( $name );
255 $this->modules[$name] = $info;
256 } else {
257 // New calling convention
258 $this->moduleInfos[$name] = $info;
259 }
260
261 wfProfileOut( __METHOD__ );
262 }
263
264 /**
265 * Add a foreign source of modules.
266 *
267 * Source properties:
268 * 'loadScript': URL (either fully-qualified or protocol-relative) of load.php for this source
269 *
270 * @param $id Mixed: source ID (string), or array( id1 => props1, id2 => props2, ... )
271 * @param $properties Array: source properties
272 */
273 public function addSource( $id, $properties = null) {
274 // Allow multiple sources to be registered in one call
275 if ( is_array( $id ) ) {
276 foreach ( $id as $key => $value ) {
277 $this->addSource( $key, $value );
278 }
279 return;
280 }
281
282 // Disallow duplicates
283 if ( isset( $this->sources[$id] ) ) {
284 throw new MWException(
285 'ResourceLoader duplicate source addition error. ' .
286 'Another source has already been registered as ' . $id
287 );
288 }
289
290 // Validate properties
291 foreach ( self::$requiredSourceProperties as $prop ) {
292 if ( !isset( $properties[$prop] ) ) {
293 throw new MWException( "Required property $prop missing from source ID $id" );
294 }
295 }
296
297 $this->sources[$id] = $properties;
298 }
299
300 /**
301 * Get a list of module names
302 *
303 * @return Array: List of module names
304 */
305 public function getModuleNames() {
306 return array_keys( $this->moduleInfos );
307 }
308
309 /**
310 * Get the ResourceLoaderModule object for a given module name.
311 *
312 * @param $name String: Module name
313 * @return ResourceLoaderModule if module has been registered, null otherwise
314 */
315 public function getModule( $name ) {
316 if ( !isset( $this->modules[$name] ) ) {
317 if ( !isset( $this->moduleInfos[$name] ) ) {
318 // No such module
319 return null;
320 }
321 // Construct the requested object
322 $info = $this->moduleInfos[$name];
323 if ( isset( $info['object'] ) ) {
324 // Object given in info array
325 $object = $info['object'];
326 } else {
327 if ( !isset( $info['class'] ) ) {
328 $class = 'ResourceLoaderFileModule';
329 } else {
330 $class = $info['class'];
331 }
332 $object = new $class( $info );
333 }
334 $object->setName( $name );
335 $this->modules[$name] = $object;
336 }
337
338 return $this->modules[$name];
339 }
340
341 /**
342 * Get the list of sources
343 *
344 * @return Array: array( id => array of properties, .. )
345 */
346 public function getSources() {
347 return $this->sources;
348 }
349
350 /**
351 * Outputs a response to a resource load-request, including a content-type header.
352 *
353 * @param $context ResourceLoaderContext: Context in which a response should be formed
354 */
355 public function respond( ResourceLoaderContext $context ) {
356 global $wgCacheEpoch;
357
358 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
359 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
360 // is used: ob_clean() will clear the GZIP header in that case and it won't come
361 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
362 // the whole thing in our own output buffer to be sure the active buffer
363 // doesn't use ob_gzhandler.
364 // See http://bugs.php.net/bug.php?id=36514
365 ob_start();
366
367 wfProfileIn( __METHOD__ );
368 $exceptions = '';
369
370 // Split requested modules into two groups, modules and missing
371 $modules = array();
372 $missing = array();
373 foreach ( $context->getModules() as $name ) {
374 if ( isset( $this->moduleInfos[$name] ) ) {
375 $modules[$name] = $this->getModule( $name );
376 } else {
377 $missing[] = $name;
378 }
379 }
380
381 // Preload information needed to the mtime calculation below
382 try {
383 $this->preloadModuleInfo( array_keys( $modules ), $context );
384 } catch( Exception $e ) {
385 // Add exception to the output as a comment
386 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
387 }
388
389 wfProfileIn( __METHOD__.'-getModifiedTime' );
390
391 $private = false;
392 // To send Last-Modified and support If-Modified-Since, we need to detect
393 // the last modified time
394 $mtime = wfTimestamp( TS_UNIX, $wgCacheEpoch );
395 foreach ( $modules as $module ) {
396 try {
397 // Bypass Squid and other shared caches if the request includes any private modules
398 if ( $module->getGroup() === 'private' ) {
399 $private = true;
400 }
401 // Calculate maximum modified time
402 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
403 } catch ( Exception $e ) {
404 // Add exception to the output as a comment
405 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
406 }
407 }
408
409 wfProfileOut( __METHOD__.'-getModifiedTime' );
410
411 // Send content type and cache related headers
412 $this->sendResponseHeaders( $context, $mtime, $private );
413
414 // If there's an If-Modified-Since header, respond with a 304 appropriately
415 if ( $this->tryRespondLastModified( $context, $mtime ) ) {
416 return; // output handled (buffers cleared)
417 }
418
419 // Generate a response
420 $response = $this->makeModuleResponse( $context, $modules, $missing );
421
422 // Prepend comments indicating exceptions
423 $response = $exceptions . $response;
424
425 // Capture any PHP warnings from the output buffer and append them to the
426 // response in a comment if we're in debug mode.
427 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
428 $response = "/*\n$warnings\n*/\n" . $response;
429 }
430
431 // Remove the output buffer and output the response
432 ob_end_clean();
433 echo $response;
434
435 wfProfileOut( __METHOD__ );
436 }
437
438 /**
439 * Send content type and last modified headers to the client.
440 * @param $context ResourceLoaderContext
441 * @param $mtime string TS_MW timestamp to use for last-modified
442 * @param $private bool True iff response contains any private modules
443 * @return void
444 */
445 protected function sendResponseHeaders( ResourceLoaderContext $context, $mtime, $private ) {
446 global $wgResourceLoaderMaxage;
447 // If a version wasn't specified we need a shorter expiry time for updates
448 // to propagate to clients quickly
449 if ( is_null( $context->getVersion() ) ) {
450 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
451 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
452 // If a version was specified we can use a longer expiry time since changing
453 // version numbers causes cache misses
454 } else {
455 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
456 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
457 }
458 if ( $context->getOnly() === 'styles' ) {
459 header( 'Content-Type: text/css; charset=utf-8' );
460 } else {
461 header( 'Content-Type: text/javascript; charset=utf-8' );
462 }
463 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $mtime ) );
464 if ( $context->getDebug() ) {
465 // Do not cache debug responses
466 header( 'Cache-Control: private, no-cache, must-revalidate' );
467 header( 'Pragma: no-cache' );
468 } else {
469 if ( $private ) {
470 header( "Cache-Control: private, max-age=$maxage" );
471 $exp = $maxage;
472 } else {
473 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
474 $exp = min( $maxage, $smaxage );
475 }
476 header( 'Expires: ' . wfTimestamp( TS_RFC2822, $exp + time() ) );
477 }
478 }
479
480 /**
481 * If there's an If-Modified-Since header, respond with a 304 appropriately
482 * and clear out the output buffer. If the client cache is too old then do nothing.
483 * @param $context ResourceLoaderContext
484 * @param $mtime string The TS_MW timestamp to check the header against
485 * @return bool True iff 304 header sent and output handled
486 */
487 protected function tryRespondLastModified( ResourceLoaderContext $context, $mtime ) {
488 // If there's an If-Modified-Since header, respond with a 304 appropriately
489 // Some clients send "timestamp;length=123". Strip the part after the first ';'
490 // so we get a valid timestamp.
491 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
492 // Never send 304s in debug mode
493 if ( $ims !== false && !$context->getDebug() ) {
494 $imsTS = strtok( $ims, ';' );
495 if ( $mtime <= wfTimestamp( TS_UNIX, $imsTS ) ) {
496 // There's another bug in ob_gzhandler (see also the comment at
497 // the top of this function) that causes it to gzip even empty
498 // responses, meaning it's impossible to produce a truly empty
499 // response (because the gzip header is always there). This is
500 // a problem because 304 responses have to be completely empty
501 // per the HTTP spec, and Firefox behaves buggily when they're not.
502 // See also http://bugs.php.net/bug.php?id=51579
503 // To work around this, we tear down all output buffering before
504 // sending the 304.
505 // On some setups, ob_get_level() doesn't seem to go down to zero
506 // no matter how often we call ob_get_clean(), so instead of doing
507 // the more intuitive while ( ob_get_level() > 0 ) ob_get_clean();
508 // we have to be safe here and avoid an infinite loop.
509 for ( $i = 0; $i < ob_get_level(); $i++ ) {
510 ob_end_clean();
511 }
512
513 header( 'HTTP/1.0 304 Not Modified' );
514 header( 'Status: 304 Not Modified' );
515 wfProfileOut( __METHOD__ );
516 return true;
517 }
518 }
519 return false;
520 }
521
522 /**
523 * Generates code for a response
524 *
525 * @param $context ResourceLoaderContext: Context in which to generate a response
526 * @param $modules Array: List of module objects keyed by module name
527 * @param $missing Array: List of unavailable modules (optional)
528 * @return String: Response data
529 */
530 public function makeModuleResponse( ResourceLoaderContext $context,
531 array $modules, $missing = array() )
532 {
533 $out = '';
534 $exceptions = '';
535 if ( $modules === array() && $missing === array() ) {
536 return '/* No modules requested. Max made me put this here */';
537 }
538
539 wfProfileIn( __METHOD__ );
540 // Pre-fetch blobs
541 if ( $context->shouldIncludeMessages() ) {
542 try {
543 $blobs = MessageBlobStore::get( $this, $modules, $context->getLanguage() );
544 } catch ( Exception $e ) {
545 // Add exception to the output as a comment
546 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
547 }
548 } else {
549 $blobs = array();
550 }
551
552 // Generate output
553 foreach ( $modules as $name => $module ) {
554 wfProfileIn( __METHOD__ . '-' . $name );
555 try {
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() && $module->supportsURLLoading() ) {
563 $scripts = $module->getScriptURLsForDebug( $context );
564 } else {
565 $scripts = $module->getScript( $context );
566 if ( is_string( $scripts ) ) {
567 // bug 27054: Append semicolon to prevent weird bugs
568 // caused by files not terminating their statements right
569 $scripts .= ";\n";
570 }
571 }
572 }
573 // Styles
574 $styles = array();
575 if ( $context->shouldIncludeStyles() ) {
576 // If we are in debug mode, we'll want to return an array of URLs
577 // See comment near shouldIncludeScripts() for more details
578 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
579 $styles = $module->getStyleURLsForDebug( $context );
580 } else {
581 $styles = $module->getStyles( $context );
582 }
583 }
584
585 // Messages
586 $messagesBlob = isset( $blobs[$name] ) ? $blobs[$name] : '{}';
587
588 // Append output
589 switch ( $context->getOnly() ) {
590 case 'scripts':
591 if ( is_string( $scripts ) ) {
592 // Load scripts raw...
593 $out .= $scripts;
594 } elseif ( is_array( $scripts ) ) {
595 // ...except when $scripts is an array of URLs
596 $out .= self::makeLoaderImplementScript( $name, $scripts, array(), array() );
597 }
598 break;
599 case 'styles':
600 $out .= self::makeCombinedStyles( $styles );
601 break;
602 case 'messages':
603 $out .= self::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
604 break;
605 default:
606 // Minify CSS before embedding in mw.loader.implement call
607 // (unless in debug mode)
608 if ( !$context->getDebug() ) {
609 foreach ( $styles as $media => $style ) {
610 if ( is_string( $style ) ) {
611 $styles[$media] = $this->filter( 'minify-css', $style );
612 }
613 }
614 }
615 $out .= self::makeLoaderImplementScript( $name, $scripts, $styles,
616 new XmlJsCode( $messagesBlob ) );
617 break;
618 }
619 } catch ( Exception $e ) {
620 // Add exception to the output as a comment
621 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
622
623 // Register module as missing
624 $missing[] = $name;
625 unset( $modules[$name] );
626 }
627 wfProfileOut( __METHOD__ . '-' . $name );
628 }
629
630 // Update module states
631 if ( $context->shouldIncludeScripts() ) {
632 // Set the state of modules loaded as only scripts to ready
633 if ( count( $modules ) && $context->getOnly() === 'scripts'
634 && !isset( $modules['startup'] ) )
635 {
636 $out .= self::makeLoaderStateScript(
637 array_fill_keys( array_keys( $modules ), 'ready' ) );
638 }
639 // Set the state of modules which were requested but unavailable as missing
640 if ( is_array( $missing ) && count( $missing ) ) {
641 $out .= self::makeLoaderStateScript( array_fill_keys( $missing, 'missing' ) );
642 }
643 }
644
645 if ( !$context->getDebug() ) {
646 if ( $context->getOnly() === 'styles' ) {
647 $out = $this->filter( 'minify-css', $out );
648 } else {
649 $out = $this->filter( 'minify-js', $out );
650 }
651 }
652
653 wfProfileOut( __METHOD__ );
654 return $exceptions . $out;
655 }
656
657 /* Static Methods */
658
659 /**
660 * Returns JS code to call to mw.loader.implement for a module with
661 * given properties.
662 *
663 * @param $name Module name
664 * @param $scripts Mixed: List of URLs to JavaScript files or String of JavaScript code
665 * @param $styles Mixed: List of CSS strings keyed by media type, or list of lists of URLs to
666 * CSS files keyed by media type
667 * @param $messages Mixed: List of messages associated with this module. May either be an
668 * associative array mapping message key to value, or a JSON-encoded message blob containing
669 * the same data, wrapped in an XmlJsCode object.
670 *
671 * @return string
672 */
673 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
674 if ( is_string( $scripts ) ) {
675 $scripts = new XmlJsCode( "function( $ ) {{$scripts}}" );
676 } elseif ( !is_array( $scripts ) ) {
677 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
678 }
679 return Xml::encodeJsCall(
680 'mw.loader.implement',
681 array(
682 $name,
683 $scripts,
684 (object)$styles,
685 (object)$messages
686 ) );
687 }
688
689 /**
690 * Returns JS code which, when called, will register a given list of messages.
691 *
692 * @param $messages Mixed: Either an associative array mapping message key to value, or a
693 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
694 *
695 * @return string
696 */
697 public static function makeMessageSetScript( $messages ) {
698 return Xml::encodeJsCall( 'mw.messages.set', array( (object)$messages ) );
699 }
700
701 /**
702 * Combines an associative array mapping media type to CSS into a
703 * single stylesheet with @media blocks.
704 *
705 * @param $styles Array: List of CSS strings keyed by media type
706 *
707 * @return string
708 */
709 public static function makeCombinedStyles( array $styles ) {
710 $out = '';
711 foreach ( $styles as $media => $style ) {
712 // Transform the media type based on request params and config
713 // The way that this relies on $wgRequest to propagate request params is slightly evil
714 $media = OutputPage::transformCssMedia( $media );
715
716 if ( $media === null ) {
717 // Skip
718 } elseif ( $media === '' || $media == 'all' ) {
719 // Don't output invalid or frivolous @media statements
720 $out .= "$style\n";
721 } else {
722 $out .= "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "\n}\n";
723 }
724 }
725 return $out;
726 }
727
728 /**
729 * Returns a JS call to mw.loader.state, which sets the state of a
730 * module or modules to a given value. Has two calling conventions:
731 *
732 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
733 * Set the state of a single module called $name to $state
734 *
735 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
736 * Set the state of modules with the given names to the given states
737 *
738 * @param $name string
739 * @param $state
740 *
741 * @return string
742 */
743 public static function makeLoaderStateScript( $name, $state = null ) {
744 if ( is_array( $name ) ) {
745 return Xml::encodeJsCall( 'mw.loader.state', array( $name ) );
746 } else {
747 return Xml::encodeJsCall( 'mw.loader.state', array( $name, $state ) );
748 }
749 }
750
751 /**
752 * Returns JS code which calls the script given by $script. The script will
753 * be called with local variables name, version, dependencies and group,
754 * which will have values corresponding to $name, $version, $dependencies
755 * and $group as supplied.
756 *
757 * @param $name String: Module name
758 * @param $version Integer: Module version number as a timestamp
759 * @param $dependencies Array: List of module names on which this module depends
760 * @param $group String: Group which the module is in.
761 * @param $source String: Source of the module, or 'local' if not foreign.
762 * @param $script String: JavaScript code
763 *
764 * @return string
765 */
766 public static function makeCustomLoaderScript( $name, $version, $dependencies, $group, $source, $script ) {
767 $script = str_replace( "\n", "\n\t", trim( $script ) );
768 return Xml::encodeJsCall(
769 "( function( name, version, dependencies, group, source ) {\n\t$script\n} )",
770 array( $name, $version, $dependencies, $group, $source ) );
771 }
772
773 /**
774 * Returns JS code which calls mw.loader.register with the given
775 * parameters. Has three calling conventions:
776 *
777 * - ResourceLoader::makeLoaderRegisterScript( $name, $version, $dependencies, $group, $source ):
778 * Register a single module.
779 *
780 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
781 * Register modules with the given names.
782 *
783 * - ResourceLoader::makeLoaderRegisterScript( array(
784 * array( $name1, $version1, $dependencies1, $group1, $source1 ),
785 * array( $name2, $version2, $dependencies1, $group2, $source2 ),
786 * ...
787 * ) ):
788 * Registers modules with the given names and parameters.
789 *
790 * @param $name String: Module name
791 * @param $version Integer: Module version number as a timestamp
792 * @param $dependencies Array: List of module names on which this module depends
793 * @param $group String: group which the module is in.
794 * @param $source String: source of the module, or 'local' if not foreign
795 *
796 * @return string
797 */
798 public static function makeLoaderRegisterScript( $name, $version = null,
799 $dependencies = null, $group = null, $source = null )
800 {
801 if ( is_array( $name ) ) {
802 return Xml::encodeJsCall( 'mw.loader.register', array( $name ) );
803 } else {
804 $version = (int) $version > 1 ? (int) $version : 1;
805 return Xml::encodeJsCall( 'mw.loader.register',
806 array( $name, $version, $dependencies, $group, $source ) );
807 }
808 }
809
810 /**
811 * Returns JS code which calls mw.loader.addSource() with the given
812 * parameters. Has two calling conventions:
813 *
814 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
815 * Register a single source
816 *
817 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $props1, $id2 => $props2, ... ) );
818 * Register sources with the given IDs and properties.
819 *
820 * @param $id String: source ID
821 * @param $properties Array: source properties (see addSource())
822 *
823 * @return string
824 */
825 public static function makeLoaderSourcesScript( $id, $properties = null ) {
826 if ( is_array( $id ) ) {
827 return Xml::encodeJsCall( 'mw.loader.addSource', array( $id ) );
828 } else {
829 return Xml::encodeJsCall( 'mw.loader.addSource', array( $id, $properties ) );
830 }
831 }
832
833 /**
834 * Returns JS code which runs given JS code if the client-side framework is
835 * present.
836 *
837 * @param $script String: JavaScript code
838 *
839 * @return string
840 */
841 public static function makeLoaderConditionalScript( $script ) {
842 $script = str_replace( "\n", "\n\t", trim( $script ) );
843 return "if(window.mw){\n\t$script\n}\n";
844 }
845
846 /**
847 * Returns JS code which will set the MediaWiki configuration array to
848 * the given value.
849 *
850 * @param $configuration Array: List of configuration values keyed by variable name
851 *
852 * @return string
853 */
854 public static function makeConfigSetScript( array $configuration ) {
855 return Xml::encodeJsCall( 'mw.config.set', array( $configuration ) );
856 }
857
858 /**
859 * Convert an array of module names to a packed query string.
860 *
861 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
862 * becomes 'foo.bar,baz|bar.baz,quux'
863 * @param $modules array of module names (strings)
864 * @return string Packed query string
865 */
866 public static function makePackedModulesString( $modules ) {
867 $groups = array(); // array( prefix => array( suffixes ) )
868 foreach ( $modules as $module ) {
869 $pos = strrpos( $module, '.' );
870 $prefix = $pos === false ? '' : substr( $module, 0, $pos );
871 $suffix = $pos === false ? $module : substr( $module, $pos + 1 );
872 $groups[$prefix][] = $suffix;
873 }
874
875 $arr = array();
876 foreach ( $groups as $prefix => $suffixes ) {
877 $p = $prefix === '' ? '' : $prefix . '.';
878 $arr[] = $p . implode( ',', $suffixes );
879 }
880 $str = implode( '|', $arr );
881 return $str;
882 }
883
884 /**
885 * Determine whether debug mode was requested
886 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
887 * @return bool
888 */
889 public static function inDebugMode() {
890 global $wgRequest, $wgResourceLoaderDebug;
891 static $retval = null;
892 if ( !is_null( $retval ) ) {
893 return $retval;
894 }
895 return $retval = $wgRequest->getFuzzyBool( 'debug',
896 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug ) );
897 }
898
899 /**
900 * Build a load.php URL
901 * @param $modules array of module names (strings)
902 * @param $lang string Language code
903 * @param $skin string Skin name
904 * @param $user string|null User name. If null, the &user= parameter is omitted
905 * @param $version string|null Versioning timestamp
906 * @param $debug bool Whether the request should be in debug mode
907 * @param $only string|null &only= parameter
908 * @param $printable bool Printable mode
909 * @param $handheld bool Handheld mode
910 * @param $extraQuery array Extra query parameters to add
911 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
912 */
913 public static function makeLoaderURL( $modules, $lang, $skin, $user = null, $version = null, $debug = false, $only = null,
914 $printable = false, $handheld = false, $extraQuery = array() ) {
915 global $wgLoadScript;
916 $query = self::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
917 $only, $printable, $handheld, $extraQuery
918 );
919
920 // Prevent the IE6 extension check from being triggered (bug 28840)
921 // by appending a character that's invalid in Windows extensions ('*')
922 return wfExpandUrl( wfAppendQuery( $wgLoadScript, $query ) . '&*', PROTO_RELATIVE );
923 }
924
925 /**
926 * Build a query array (array representation of query string) for load.php. Helper
927 * function for makeLoaderURL().
928 * @return array
929 */
930 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null, $version = null, $debug = false, $only = null,
931 $printable = false, $handheld = false, $extraQuery = array() ) {
932 $query = array(
933 'modules' => self::makePackedModulesString( $modules ),
934 'lang' => $lang,
935 'skin' => $skin,
936 'debug' => $debug ? 'true' : 'false',
937 );
938 if ( $user !== null ) {
939 $query['user'] = $user;
940 }
941 if ( $version !== null ) {
942 $query['version'] = $version;
943 }
944 if ( $only !== null ) {
945 $query['only'] = $only;
946 }
947 if ( $printable ) {
948 $query['printable'] = 1;
949 }
950 if ( $handheld ) {
951 $query['handheld'] = 1;
952 }
953 $query += $extraQuery;
954
955 // Make queries uniform in order
956 ksort( $query );
957 return $query;
958 }
959 }