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