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