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