9973cbc807ba7f46016e8e2b7ecb89807dc88a34
[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, $wgUseFileCache;
357
358 // Use file cache if enabled and available...
359 if ( $wgUseFileCache ) {
360 $fileCache = ResourceFileCache::newFromContext( $context );
361 if ( $this->tryRespondFromFileCache( $fileCache, $context ) ) {
362 return; // output handled
363 }
364 }
365
366 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
367 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
368 // is used: ob_clean() will clear the GZIP header in that case and it won't come
369 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
370 // the whole thing in our own output buffer to be sure the active buffer
371 // doesn't use ob_gzhandler.
372 // See http://bugs.php.net/bug.php?id=36514
373 ob_start();
374
375 wfProfileIn( __METHOD__ );
376 $exceptions = '';
377
378 // Split requested modules into two groups, modules and missing
379 $modules = array();
380 $missing = array();
381 foreach ( $context->getModules() as $name ) {
382 if ( isset( $this->moduleInfos[$name] ) ) {
383 $modules[$name] = $this->getModule( $name );
384 } else {
385 $missing[] = $name;
386 }
387 }
388
389 // Preload information needed to the mtime calculation below
390 try {
391 $this->preloadModuleInfo( array_keys( $modules ), $context );
392 } catch( Exception $e ) {
393 // Add exception to the output as a comment
394 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
395 }
396
397 wfProfileIn( __METHOD__.'-getModifiedTime' );
398
399 $private = false;
400 // To send Last-Modified and support If-Modified-Since, we need to detect
401 // the last modified time
402 $mtime = wfTimestamp( TS_UNIX, $wgCacheEpoch );
403 foreach ( $modules as $module ) {
404 /**
405 * @var $module ResourceLoaderModule
406 */
407 try {
408 // Bypass Squid and other shared caches if the request includes any private modules
409 if ( $module->getGroup() === 'private' ) {
410 $private = true;
411 }
412 // Calculate maximum modified time
413 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
414 } catch ( Exception $e ) {
415 // Add exception to the output as a comment
416 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
417 }
418 }
419
420 wfProfileOut( __METHOD__.'-getModifiedTime' );
421
422 // Send content type and cache related headers
423 $this->sendResponseHeaders( $context, $mtime, $private );
424
425 // If there's an If-Modified-Since header, respond with a 304 appropriately
426 if ( $this->tryRespondLastModified( $context, $mtime ) ) {
427 wfProfileOut( __METHOD__ );
428 return; // output handled (buffers cleared)
429 }
430
431 // Generate a response
432 $response = $this->makeModuleResponse( $context, $modules, $missing );
433
434 // Prepend comments indicating exceptions
435 $response = $exceptions . $response;
436
437 // Capture any PHP warnings from the output buffer and append them to the
438 // response in a comment if we're in debug mode.
439 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
440 $response = "/*\n$warnings\n*/\n" . $response;
441 }
442
443 // Remove the output buffer and output the response
444 ob_end_clean();
445 echo $response;
446
447 // Save response to file cache unless there are private modules or errors
448 if ( isset( $fileCache ) && !$private && !$exceptions && !$missing ) {
449 // Cache single modules...and other requests if there are enough hits
450 if ( ResourceFileCache::useFileCache( $context ) ) {
451 if ( $fileCache->isCacheWorthy() ) {
452 $fileCache->saveText( $response );
453 } else {
454 $fileCache->incrMissesRecent( $context->getRequest() );
455 }
456 }
457 }
458
459 wfProfileOut( __METHOD__ );
460 }
461
462 /**
463 * Send content type and last modified headers to the client.
464 * @param $context ResourceLoaderContext
465 * @param $mtime string TS_MW timestamp to use for last-modified
466 * @param $private bool True iff response contains any private modules
467 * @return void
468 */
469 protected function sendResponseHeaders( ResourceLoaderContext $context, $mtime, $private ) {
470 global $wgResourceLoaderMaxage;
471 // If a version wasn't specified we need a shorter expiry time for updates
472 // to propagate to clients quickly
473 if ( is_null( $context->getVersion() ) ) {
474 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
475 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
476 // If a version was specified we can use a longer expiry time since changing
477 // version numbers causes cache misses
478 } else {
479 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
480 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
481 }
482 if ( $context->getOnly() === 'styles' ) {
483 header( 'Content-Type: text/css; charset=utf-8' );
484 } else {
485 header( 'Content-Type: text/javascript; charset=utf-8' );
486 }
487 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $mtime ) );
488 if ( $context->getDebug() ) {
489 // Do not cache debug responses
490 header( 'Cache-Control: private, no-cache, must-revalidate' );
491 header( 'Pragma: no-cache' );
492 } else {
493 if ( $private ) {
494 header( "Cache-Control: private, max-age=$maxage" );
495 $exp = $maxage;
496 } else {
497 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
498 $exp = min( $maxage, $smaxage );
499 }
500 header( 'Expires: ' . wfTimestamp( TS_RFC2822, $exp + time() ) );
501 }
502 }
503
504 /**
505 * If there's an If-Modified-Since header, respond with a 304 appropriately
506 * and clear out the output buffer. If the client cache is too old then do nothing.
507 * @param $context ResourceLoaderContext
508 * @param $mtime string The TS_MW timestamp to check the header against
509 * @return bool True iff 304 header sent and output handled
510 */
511 protected function tryRespondLastModified( ResourceLoaderContext $context, $mtime ) {
512 // If there's an If-Modified-Since header, respond with a 304 appropriately
513 // Some clients send "timestamp;length=123". Strip the part after the first ';'
514 // so we get a valid timestamp.
515 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
516 // Never send 304s in debug mode
517 if ( $ims !== false && !$context->getDebug() ) {
518 $imsTS = strtok( $ims, ';' );
519 if ( $mtime <= wfTimestamp( TS_UNIX, $imsTS ) ) {
520 // There's another bug in ob_gzhandler (see also the comment at
521 // the top of this function) that causes it to gzip even empty
522 // responses, meaning it's impossible to produce a truly empty
523 // response (because the gzip header is always there). This is
524 // a problem because 304 responses have to be completely empty
525 // per the HTTP spec, and Firefox behaves buggily when they're not.
526 // See also http://bugs.php.net/bug.php?id=51579
527 // To work around this, we tear down all output buffering before
528 // sending the 304.
529 // On some setups, ob_get_level() doesn't seem to go down to zero
530 // no matter how often we call ob_get_clean(), so instead of doing
531 // the more intuitive while ( ob_get_level() > 0 ) ob_get_clean();
532 // we have to be safe here and avoid an infinite loop.
533 for ( $i = 0; $i < ob_get_level(); $i++ ) {
534 ob_end_clean();
535 }
536
537 header( 'HTTP/1.0 304 Not Modified' );
538 header( 'Status: 304 Not Modified' );
539 wfProfileOut( __METHOD__ );
540 return true;
541 }
542 }
543 return false;
544 }
545
546 /**
547 * Send out code for a response from file cache if possible
548 *
549 * @param $fileCache ObjectFileCache: Cache object for this request URL
550 * @param $context ResourceLoaderContext: Context in which to generate a response
551 * @return bool If this found a cache file and handled the response
552 */
553 protected function tryRespondFromFileCache(
554 ResourceFileCache $fileCache, ResourceLoaderContext $context
555 ) {
556 global $wgResourceLoaderMaxage;
557 // Buffer output to catch warnings.
558 ob_start();
559 // Get the maximum age the cache can be
560 $maxage = is_null( $context->getVersion() )
561 ? $wgResourceLoaderMaxage['unversioned']['server']
562 : $wgResourceLoaderMaxage['versioned']['server'];
563 // Minimum timestamp the cache file must have
564 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW, time() - $maxage ) );
565 if ( !$good ) {
566 try { // RL always hits the DB on file cache miss...
567 wfGetDB( DB_SLAVE );
568 } catch( DBConnectionError $e ) { // ...check if we need to fallback to cache
569 $good = $fileCache->isCacheGood(); // cache existence check
570 }
571 }
572 if ( $good ) {
573 $ts = $fileCache->cacheTimestamp();
574 // Send content type and cache headers
575 $this->sendResponseHeaders( $context, $ts, false );
576 // If there's an If-Modified-Since header, respond with a 304 appropriately
577 if ( $this->tryRespondLastModified( $context, $ts ) ) {
578 return false; // output handled (buffers cleared)
579 }
580 $response = $fileCache->fetchText();
581 // Remove the output buffer and output the response
582 ob_end_clean();
583 echo $response . "\n/* Cached {$ts} */";
584 return true; // cache hit
585 }
586 // Clear buffer
587 ob_end_clean();
588
589 return false; // cache miss
590 }
591
592 /**
593 * Generates code for a response
594 *
595 * @param $context ResourceLoaderContext: Context in which to generate a response
596 * @param $modules Array: List of module objects keyed by module name
597 * @param $missing Array: List of unavailable modules (optional)
598 * @return String: Response data
599 */
600 public function makeModuleResponse( ResourceLoaderContext $context,
601 array $modules, $missing = array() )
602 {
603 $out = '';
604 $exceptions = '';
605 if ( $modules === array() && $missing === array() ) {
606 return '/* No modules requested. Max made me put this here */';
607 }
608
609 wfProfileIn( __METHOD__ );
610 // Pre-fetch blobs
611 if ( $context->shouldIncludeMessages() ) {
612 try {
613 $blobs = MessageBlobStore::get( $this, $modules, $context->getLanguage() );
614 } catch ( Exception $e ) {
615 // Add exception to the output as a comment
616 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
617 }
618 } else {
619 $blobs = array();
620 }
621
622 // Generate output
623 foreach ( $modules as $name => $module ) {
624 /**
625 * @var $module ResourceLoaderModule
626 */
627
628 wfProfileIn( __METHOD__ . '-' . $name );
629 try {
630 $scripts = '';
631 if ( $context->shouldIncludeScripts() ) {
632 // If we are in debug mode, we'll want to return an array of URLs if possible
633 // However, we can't do this if the module doesn't support it
634 // We also can't do this if there is an only= parameter, because we have to give
635 // the module a way to return a load.php URL without causing an infinite loop
636 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
637 $scripts = $module->getScriptURLsForDebug( $context );
638 } else {
639 $scripts = $module->getScript( $context );
640 if ( is_string( $scripts ) ) {
641 // bug 27054: Append semicolon to prevent weird bugs
642 // caused by files not terminating their statements right
643 $scripts .= ";\n";
644 }
645 }
646 }
647 // Styles
648 $styles = array();
649 if ( $context->shouldIncludeStyles() ) {
650 // If we are in debug mode, we'll want to return an array of URLs
651 // See comment near shouldIncludeScripts() for more details
652 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
653 $styles = $module->getStyleURLsForDebug( $context );
654 } else {
655 $styles = $module->getStyles( $context );
656 }
657 }
658
659 // Messages
660 $messagesBlob = isset( $blobs[$name] ) ? $blobs[$name] : '{}';
661
662 // Append output
663 switch ( $context->getOnly() ) {
664 case 'scripts':
665 if ( is_string( $scripts ) ) {
666 // Load scripts raw...
667 $out .= $scripts;
668 } elseif ( is_array( $scripts ) ) {
669 // ...except when $scripts is an array of URLs
670 $out .= self::makeLoaderImplementScript( $name, $scripts, array(), array() );
671 }
672 break;
673 case 'styles':
674 $out .= self::makeCombinedStyles( $styles );
675 break;
676 case 'messages':
677 $out .= self::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
678 break;
679 default:
680 // Minify CSS before embedding in mw.loader.implement call
681 // (unless in debug mode)
682 if ( !$context->getDebug() ) {
683 foreach ( $styles as $media => $style ) {
684 if ( is_string( $style ) ) {
685 $styles[$media] = $this->filter( 'minify-css', $style );
686 }
687 }
688 }
689 $out .= self::makeLoaderImplementScript( $name, $scripts, $styles,
690 new XmlJsCode( $messagesBlob ) );
691 break;
692 }
693 } catch ( Exception $e ) {
694 // Add exception to the output as a comment
695 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
696
697 // Register module as missing
698 $missing[] = $name;
699 unset( $modules[$name] );
700 }
701 wfProfileOut( __METHOD__ . '-' . $name );
702 }
703
704 // Update module states
705 if ( $context->shouldIncludeScripts() ) {
706 // Set the state of modules loaded as only scripts to ready
707 if ( count( $modules ) && $context->getOnly() === 'scripts'
708 && !isset( $modules['startup'] ) )
709 {
710 $out .= self::makeLoaderStateScript(
711 array_fill_keys( array_keys( $modules ), 'ready' ) );
712 }
713 // Set the state of modules which were requested but unavailable as missing
714 if ( is_array( $missing ) && count( $missing ) ) {
715 $out .= self::makeLoaderStateScript( array_fill_keys( $missing, 'missing' ) );
716 }
717 }
718
719 if ( !$context->getDebug() ) {
720 if ( $context->getOnly() === 'styles' ) {
721 $out = $this->filter( 'minify-css', $out );
722 } else {
723 $out = $this->filter( 'minify-js', $out );
724 }
725 }
726
727 wfProfileOut( __METHOD__ );
728 return $exceptions . $out;
729 }
730
731 /* Static Methods */
732
733 /**
734 * Returns JS code to call to mw.loader.implement for a module with
735 * given properties.
736 *
737 * @param $name Module name
738 * @param $scripts Mixed: List of URLs to JavaScript files or String of JavaScript code
739 * @param $styles Mixed: List of CSS strings keyed by media type, or list of lists of URLs to
740 * CSS files keyed by media type
741 * @param $messages Mixed: List of messages associated with this module. May either be an
742 * associative array mapping message key to value, or a JSON-encoded message blob containing
743 * the same data, wrapped in an XmlJsCode object.
744 *
745 * @return string
746 */
747 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
748 if ( is_string( $scripts ) ) {
749 $scripts = new XmlJsCode( "function( $ ) {{$scripts}}" );
750 } elseif ( !is_array( $scripts ) ) {
751 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
752 }
753 return Xml::encodeJsCall(
754 'mw.loader.implement',
755 array(
756 $name,
757 $scripts,
758 (object)$styles,
759 (object)$messages
760 ) );
761 }
762
763 /**
764 * Returns JS code which, when called, will register a given list of messages.
765 *
766 * @param $messages Mixed: Either an associative array mapping message key to value, or a
767 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
768 *
769 * @return string
770 */
771 public static function makeMessageSetScript( $messages ) {
772 return Xml::encodeJsCall( 'mw.messages.set', array( (object)$messages ) );
773 }
774
775 /**
776 * Combines an associative array mapping media type to CSS into a
777 * single stylesheet with @media blocks.
778 *
779 * @param $styles Array: List of CSS strings keyed by media type
780 *
781 * @return string
782 */
783 public static function makeCombinedStyles( array $styles ) {
784 $out = '';
785 foreach ( $styles as $media => $style ) {
786 // Transform the media type based on request params and config
787 // The way that this relies on $wgRequest to propagate request params is slightly evil
788 $media = OutputPage::transformCssMedia( $media );
789
790 if ( $media === null ) {
791 // Skip
792 } elseif ( $media === '' || $media == 'all' ) {
793 // Don't output invalid or frivolous @media statements
794 $out .= "$style\n";
795 } else {
796 $out .= "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "\n}\n";
797 }
798 }
799 return $out;
800 }
801
802 /**
803 * Returns a JS call to mw.loader.state, which sets the state of a
804 * module or modules to a given value. Has two calling conventions:
805 *
806 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
807 * Set the state of a single module called $name to $state
808 *
809 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
810 * Set the state of modules with the given names to the given states
811 *
812 * @param $name string
813 * @param $state
814 *
815 * @return string
816 */
817 public static function makeLoaderStateScript( $name, $state = null ) {
818 if ( is_array( $name ) ) {
819 return Xml::encodeJsCall( 'mw.loader.state', array( $name ) );
820 } else {
821 return Xml::encodeJsCall( 'mw.loader.state', array( $name, $state ) );
822 }
823 }
824
825 /**
826 * Returns JS code which calls the script given by $script. The script will
827 * be called with local variables name, version, dependencies and group,
828 * which will have values corresponding to $name, $version, $dependencies
829 * and $group as supplied.
830 *
831 * @param $name String: Module name
832 * @param $version Integer: Module version number as a timestamp
833 * @param $dependencies Array: List of module names on which this module depends
834 * @param $group String: Group which the module is in.
835 * @param $source String: Source of the module, or 'local' if not foreign.
836 * @param $script String: JavaScript code
837 *
838 * @return string
839 */
840 public static function makeCustomLoaderScript( $name, $version, $dependencies, $group, $source, $script ) {
841 $script = str_replace( "\n", "\n\t", trim( $script ) );
842 return Xml::encodeJsCall(
843 "( function( name, version, dependencies, group, source ) {\n\t$script\n} )",
844 array( $name, $version, $dependencies, $group, $source ) );
845 }
846
847 /**
848 * Returns JS code which calls mw.loader.register with the given
849 * parameters. Has three calling conventions:
850 *
851 * - ResourceLoader::makeLoaderRegisterScript( $name, $version, $dependencies, $group, $source ):
852 * Register a single module.
853 *
854 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
855 * Register modules with the given names.
856 *
857 * - ResourceLoader::makeLoaderRegisterScript( array(
858 * array( $name1, $version1, $dependencies1, $group1, $source1 ),
859 * array( $name2, $version2, $dependencies1, $group2, $source2 ),
860 * ...
861 * ) ):
862 * Registers modules with the given names and parameters.
863 *
864 * @param $name String: Module name
865 * @param $version Integer: Module version number as a timestamp
866 * @param $dependencies Array: List of module names on which this module depends
867 * @param $group String: group which the module is in.
868 * @param $source String: source of the module, or 'local' if not foreign
869 *
870 * @return string
871 */
872 public static function makeLoaderRegisterScript( $name, $version = null,
873 $dependencies = null, $group = null, $source = null )
874 {
875 if ( is_array( $name ) ) {
876 return Xml::encodeJsCall( 'mw.loader.register', array( $name ) );
877 } else {
878 $version = (int) $version > 1 ? (int) $version : 1;
879 return Xml::encodeJsCall( 'mw.loader.register',
880 array( $name, $version, $dependencies, $group, $source ) );
881 }
882 }
883
884 /**
885 * Returns JS code which calls mw.loader.addSource() with the given
886 * parameters. Has two calling conventions:
887 *
888 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
889 * Register a single source
890 *
891 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $props1, $id2 => $props2, ... ) );
892 * Register sources with the given IDs and properties.
893 *
894 * @param $id String: source ID
895 * @param $properties Array: source properties (see addSource())
896 *
897 * @return string
898 */
899 public static function makeLoaderSourcesScript( $id, $properties = null ) {
900 if ( is_array( $id ) ) {
901 return Xml::encodeJsCall( 'mw.loader.addSource', array( $id ) );
902 } else {
903 return Xml::encodeJsCall( 'mw.loader.addSource', array( $id, $properties ) );
904 }
905 }
906
907 /**
908 * Returns JS code which runs given JS code if the client-side framework is
909 * present.
910 *
911 * @param $script String: JavaScript code
912 *
913 * @return string
914 */
915 public static function makeLoaderConditionalScript( $script ) {
916 $script = str_replace( "\n", "\n\t", trim( $script ) );
917 return "if(window.mw){\n\t$script\n}\n";
918 }
919
920 /**
921 * Returns JS code which will set the MediaWiki configuration array to
922 * the given value.
923 *
924 * @param $configuration Array: List of configuration values keyed by variable name
925 *
926 * @return string
927 */
928 public static function makeConfigSetScript( array $configuration ) {
929 return Xml::encodeJsCall( 'mw.config.set', array( $configuration ) );
930 }
931
932 /**
933 * Convert an array of module names to a packed query string.
934 *
935 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
936 * becomes 'foo.bar,baz|bar.baz,quux'
937 * @param $modules array of module names (strings)
938 * @return string Packed query string
939 */
940 public static function makePackedModulesString( $modules ) {
941 $groups = array(); // array( prefix => array( suffixes ) )
942 foreach ( $modules as $module ) {
943 $pos = strrpos( $module, '.' );
944 $prefix = $pos === false ? '' : substr( $module, 0, $pos );
945 $suffix = $pos === false ? $module : substr( $module, $pos + 1 );
946 $groups[$prefix][] = $suffix;
947 }
948
949 $arr = array();
950 foreach ( $groups as $prefix => $suffixes ) {
951 $p = $prefix === '' ? '' : $prefix . '.';
952 $arr[] = $p . implode( ',', $suffixes );
953 }
954 $str = implode( '|', $arr );
955 return $str;
956 }
957
958 /**
959 * Determine whether debug mode was requested
960 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
961 * @return bool
962 */
963 public static function inDebugMode() {
964 global $wgRequest, $wgResourceLoaderDebug;
965 static $retval = null;
966 if ( !is_null( $retval ) ) {
967 return $retval;
968 }
969 return $retval = $wgRequest->getFuzzyBool( 'debug',
970 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug ) );
971 }
972
973 /**
974 * Build a load.php URL
975 * @param $modules array of module names (strings)
976 * @param $lang string Language code
977 * @param $skin string Skin name
978 * @param $user string|null User name. If null, the &user= parameter is omitted
979 * @param $version string|null Versioning timestamp
980 * @param $debug bool Whether the request should be in debug mode
981 * @param $only string|null &only= parameter
982 * @param $printable bool Printable mode
983 * @param $handheld bool Handheld mode
984 * @param $extraQuery array Extra query parameters to add
985 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
986 */
987 public static function makeLoaderURL( $modules, $lang, $skin, $user = null, $version = null, $debug = false, $only = null,
988 $printable = false, $handheld = false, $extraQuery = array() ) {
989 global $wgLoadScript;
990 $query = self::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
991 $only, $printable, $handheld, $extraQuery
992 );
993
994 // Prevent the IE6 extension check from being triggered (bug 28840)
995 // by appending a character that's invalid in Windows extensions ('*')
996 return wfExpandUrl( wfAppendQuery( $wgLoadScript, $query ) . '&*', PROTO_RELATIVE );
997 }
998
999 /**
1000 * Build a query array (array representation of query string) for load.php. Helper
1001 * function for makeLoaderURL().
1002 * @return array
1003 */
1004 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null, $version = null, $debug = false, $only = null,
1005 $printable = false, $handheld = false, $extraQuery = array() ) {
1006 $query = array(
1007 'modules' => self::makePackedModulesString( $modules ),
1008 'lang' => $lang,
1009 'skin' => $skin,
1010 'debug' => $debug ? 'true' : 'false',
1011 );
1012 if ( $user !== null ) {
1013 $query['user'] = $user;
1014 }
1015 if ( $version !== null ) {
1016 $query['version'] = $version;
1017 }
1018 if ( $only !== null ) {
1019 $query['only'] = $only;
1020 }
1021 if ( $printable ) {
1022 $query['printable'] = 1;
1023 }
1024 if ( $handheld ) {
1025 $query['handheld'] = 1;
1026 }
1027 $query += $extraQuery;
1028
1029 // Make queries uniform in order
1030 ksort( $query );
1031 return $query;
1032 }
1033 }