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