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