thumb_handler.php doesn't seem to extract path_info correctly
[mediawiki.git] / includes / resourceloader / ResourceLoader.php
blob543bd1d30061fd8013634ad15bf720675d84bc69
1 <?php
2 /**
3 * Base class for resource loading system.
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.
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.
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
20 * @file
21 * @author Roan Kattouw
22 * @author Trevor Parscal
25 /**
26 * Dynamic JavaScript and CSS resource loading system.
28 * Most of the documention is on the MediaWiki documentation wiki starting at:
29 * http://www.mediawiki.org/wiki/ResourceLoader
31 class ResourceLoader {
33 /* Protected Static Members */
34 protected static $filterCacheVersion = 7;
35 protected static $requiredSourceProperties = array( 'loadScript' );
37 /** Array: List of module name/ResourceLoaderModule object pairs */
38 protected $modules = array();
40 /** Associative array mapping module name to info associative array */
41 protected $moduleInfos = array();
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();
47 /** array( 'source-id' => array( 'loadScript' => 'http://.../load.php' ) ) **/
48 protected $sources = array();
50 /* Protected Methods */
52 /**
53 * Loads information stored in the database about modules.
55 * This method grabs modules dependencies from the database and updates modules
56 * objects.
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.
63 * @param array $modules List of module names to preload information for
64 * @param $context ResourceLoaderContext: Context to load the information within
66 public function preloadModuleInfo( array $modules, ResourceLoaderContext $context ) {
67 if ( !count( $modules ) ) {
68 return; // or else Database*::select() will explode, plus it's cheaper!
70 $dbr = wfGetDB( DB_SLAVE );
71 $skin = $context->getSkin();
72 $lang = $context->getLanguage();
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__
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 )
87 $modulesWithDeps[] = $row->md_module;
90 // Register the absence of a dependency row too
91 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
92 $this->getModule( $name )->setFileDependencies( $skin, array() );
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;
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__
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] );
115 foreach ( array_keys( $modulesWithoutMessages ) as $name ) {
116 $this->getModule( $name )->setMsgBlobMtime( $lang, 0 );
121 * Runs JavaScript or CSS data through a filter, caching the filtered result for future calls.
123 * Available filters are:
124 * - minify-js \see JavaScriptMinifier::minify
125 * - minify-css \see CSSMin::minify
127 * If $data is empty, only contains whitespace or the filter was unknown,
128 * $data is returned unmodified.
130 * @param string $filter Name of filter to run
131 * @param string $data Text to filter, such as JavaScript or CSS text
132 * @return String: Filtered data, or a comment containing an error message
134 protected function filter( $filter, $data ) {
135 global $wgResourceLoaderMinifierStatementsOnOwnLine, $wgResourceLoaderMinifierMaxLineLength;
136 wfProfileIn( __METHOD__ );
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' ) ) )
143 wfProfileOut( __METHOD__ );
144 return $data;
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;
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
166 $result .= "\n/* cache key: $key */";
167 break;
168 case 'minify-css':
169 $result = CSSMin::minify( $data );
170 $result .= "\n/* cache key: $key */";
171 break;
174 // Save filtered text to Memcached
175 $cache->set( $key, $result );
176 } catch ( Exception $exception ) {
177 wfDebugLog( 'resourceloader', __METHOD__ . ": minification failed: $e" );
178 $this->hasErrors = true;
179 // Return exception as a comment
180 $result = $this->makeComment( $exception->__toString() );
183 wfProfileOut( __METHOD__ );
185 return $result;
188 /* Methods */
191 * Registers core modules and runs registration hooks.
193 public function __construct() {
194 global $IP, $wgResourceModules, $wgResourceLoaderSources, $wgLoadScript, $wgEnableJavaScriptTest;
196 wfProfileIn( __METHOD__ );
198 // Add 'local' source first
199 $this->addSource( 'local', array( 'loadScript' => $wgLoadScript, 'apiScript' => wfScript( 'api' ) ) );
201 // Add other sources
202 $this->addSource( $wgResourceLoaderSources );
204 // Register core modules
205 $this->register( include "$IP/resources/Resources.php" );
206 // Register extension modules
207 wfRunHooks( 'ResourceLoaderRegisterModules', array( &$this ) );
208 $this->register( $wgResourceModules );
210 if ( $wgEnableJavaScriptTest === true ) {
211 $this->registerTestModules();
214 wfProfileOut( __METHOD__ );
218 * Registers a module with the ResourceLoader system.
220 * @param $name Mixed: Name of module as a string or List of name/object pairs as an array
221 * @param array $info Module info array. For backwards compatibility with 1.17alpha,
222 * this may also be a ResourceLoaderModule object. Optional when using
223 * multiple-registration calling style.
224 * @throws MWException: If a duplicate module registration is attempted
225 * @throws MWException: If a module name contains illegal characters (pipes or commas)
226 * @throws MWException: If something other than a ResourceLoaderModule is being registered
227 * @return Boolean: False if there were any errors, in which case one or more modules were not
228 * registered
230 public function register( $name, $info = null ) {
231 wfProfileIn( __METHOD__ );
233 // Allow multiple modules to be registered in one call
234 $registrations = is_array( $name ) ? $name : array( $name => $info );
235 foreach ( $registrations as $name => $info ) {
236 // Disallow duplicate registrations
237 if ( isset( $this->moduleInfos[$name] ) ) {
238 wfProfileOut( __METHOD__ );
239 // A module has already been registered by this name
240 throw new MWException(
241 'ResourceLoader duplicate registration error. ' .
242 'Another module has already been registered as ' . $name
246 // Check $name for validity
247 if ( !self::isValidModuleName( $name ) ) {
248 wfProfileOut( __METHOD__ );
249 throw new MWException( "ResourceLoader module name '$name' is invalid, see ResourceLoader::isValidModuleName()" );
252 // Attach module
253 if ( is_object( $info ) ) {
254 // Old calling convention
255 // Validate the input
256 if ( !( $info instanceof ResourceLoaderModule ) ) {
257 wfProfileOut( __METHOD__ );
258 throw new MWException( 'ResourceLoader invalid module error. ' .
259 'Instances of ResourceLoaderModule expected.' );
262 $this->moduleInfos[$name] = array( 'object' => $info );
263 $info->setName( $name );
264 $this->modules[$name] = $info;
265 } else {
266 // New calling convention
267 $this->moduleInfos[$name] = $info;
271 wfProfileOut( __METHOD__ );
276 public function registerTestModules() {
277 global $IP, $wgEnableJavaScriptTest;
279 if ( $wgEnableJavaScriptTest !== true ) {
280 throw new MWException( 'Attempt to register JavaScript test modules but <tt>$wgEnableJavaScriptTest</tt> is false. Edit your <tt>LocalSettings.php</tt> to enable it.' );
283 wfProfileIn( __METHOD__ );
285 // Get core test suites
286 $testModules = array();
287 $testModules['qunit'] = include "$IP/tests/qunit/QUnitTestResources.php";
288 // Get other test suites (e.g. from extensions)
289 wfRunHooks( 'ResourceLoaderTestModules', array( &$testModules, &$this ) );
291 // Add the testrunner (which configures QUnit) to the dependencies.
292 // Since it must be ready before any of the test suites are executed.
293 foreach ( $testModules['qunit'] as &$module ) {
294 // Make sure all test modules are top-loading so that when QUnit starts
295 // on document-ready, it will run once and finish. If some tests arrive
296 // later (possibly after QUnit has already finished) they will be ignored.
297 $module['position'] = 'top';
298 $module['dependencies'][] = 'mediawiki.tests.qunit.testrunner';
301 foreach ( $testModules as $id => $names ) {
302 // Register test modules
303 $this->register( $testModules[$id] );
305 // Keep track of their names so that they can be loaded together
306 $this->testModuleNames[$id] = array_keys( $testModules[$id] );
309 wfProfileOut( __METHOD__ );
313 * Add a foreign source of modules.
315 * Source properties:
316 * 'loadScript': URL (either fully-qualified or protocol-relative) of load.php for this source
318 * @param $id Mixed: source ID (string), or array( id1 => props1, id2 => props2, ... )
319 * @param array $properties source properties
320 * @throws MWException
322 public function addSource( $id, $properties = null ) {
323 // Allow multiple sources to be registered in one call
324 if ( is_array( $id ) ) {
325 foreach ( $id as $key => $value ) {
326 $this->addSource( $key, $value );
328 return;
331 // Disallow duplicates
332 if ( isset( $this->sources[$id] ) ) {
333 throw new MWException(
334 'ResourceLoader duplicate source addition error. ' .
335 'Another source has already been registered as ' . $id
339 // Validate properties
340 foreach ( self::$requiredSourceProperties as $prop ) {
341 if ( !isset( $properties[$prop] ) ) {
342 throw new MWException( "Required property $prop missing from source ID $id" );
346 $this->sources[$id] = $properties;
350 * Get a list of module names
352 * @return Array: List of module names
354 public function getModuleNames() {
355 return array_keys( $this->moduleInfos );
359 * Get a list of test module names for one (or all) frameworks.
360 * If the given framework id is unknkown, or if the in-object variable is not an array,
361 * then it will return an empty array.
363 * @param string $framework Optional. Get only the test module names for one
364 * particular framework.
365 * @return Array
367 public function getTestModuleNames( $framework = 'all' ) {
368 /// @todo api siteinfo prop testmodulenames modulenames
369 if ( $framework == 'all' ) {
370 return $this->testModuleNames;
371 } elseif ( isset( $this->testModuleNames[$framework] ) && is_array( $this->testModuleNames[$framework] ) ) {
372 return $this->testModuleNames[$framework];
373 } else {
374 return array();
379 * Get the ResourceLoaderModule object for a given module name.
381 * @param string $name Module name
382 * @return ResourceLoaderModule if module has been registered, null otherwise
384 public function getModule( $name ) {
385 if ( !isset( $this->modules[$name] ) ) {
386 if ( !isset( $this->moduleInfos[$name] ) ) {
387 // No such module
388 return null;
390 // Construct the requested object
391 $info = $this->moduleInfos[$name];
392 if ( isset( $info['object'] ) ) {
393 // Object given in info array
394 $object = $info['object'];
395 } else {
396 if ( !isset( $info['class'] ) ) {
397 $class = 'ResourceLoaderFileModule';
398 } else {
399 $class = $info['class'];
401 $object = new $class( $info );
403 $object->setName( $name );
404 $this->modules[$name] = $object;
407 return $this->modules[$name];
411 * Get the list of sources
413 * @return Array: array( id => array of properties, .. )
415 public function getSources() {
416 return $this->sources;
420 * Outputs a response to a resource load-request, including a content-type header.
422 * @param $context ResourceLoaderContext: Context in which a response should be formed
424 public function respond( ResourceLoaderContext $context ) {
425 global $wgCacheEpoch, $wgUseFileCache;
427 // Use file cache if enabled and available...
428 if ( $wgUseFileCache ) {
429 $fileCache = ResourceFileCache::newFromContext( $context );
430 if ( $this->tryRespondFromFileCache( $fileCache, $context ) ) {
431 return; // output handled
435 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
436 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
437 // is used: ob_clean() will clear the GZIP header in that case and it won't come
438 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
439 // the whole thing in our own output buffer to be sure the active buffer
440 // doesn't use ob_gzhandler.
441 // See http://bugs.php.net/bug.php?id=36514
442 ob_start();
444 wfProfileIn( __METHOD__ );
445 $errors = '';
446 $this->hasErrors = false;
448 // Split requested modules into two groups, modules and missing
449 $modules = array();
450 $missing = array();
451 foreach ( $context->getModules() as $name ) {
452 if ( isset( $this->moduleInfos[$name] ) ) {
453 $module = $this->getModule( $name );
454 // Do not allow private modules to be loaded from the web.
455 // This is a security issue, see bug 34907.
456 if ( $module->getGroup() === 'private' ) {
457 wfDebugLog( 'resourceloader', __METHOD__ . ": request for private module denied: $e" );
458 $this->hasErrors = true;
459 // Add exception to the output as a comment
460 $errors .= $this->makeComment( "Cannot show private module \"$name\"" );
462 continue;
464 $modules[$name] = $module;
465 } else {
466 $missing[] = $name;
470 // Preload information needed to the mtime calculation below
471 try {
472 $this->preloadModuleInfo( array_keys( $modules ), $context );
473 } catch ( Exception $e ) {
474 wfDebugLog( 'resourceloader', __METHOD__ . ": preloading module info failed: $e" );
475 $this->hasErrors = true;
476 // Add exception to the output as a comment
477 $errors .= $this->makeComment( $e->__toString() );
480 wfProfileIn( __METHOD__ . '-getModifiedTime' );
482 // To send Last-Modified and support If-Modified-Since, we need to detect
483 // the last modified time
484 $mtime = wfTimestamp( TS_UNIX, $wgCacheEpoch );
485 foreach ( $modules as $module ) {
487 * @var $module ResourceLoaderModule
489 try {
490 // Calculate maximum modified time
491 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
492 } catch ( Exception $e ) {
493 wfDebugLog( 'resourceloader', __METHOD__ . ": calculating maximum modified time failed: $e" );
494 $this->hasErrors = true;
495 // Add exception to the output as a comment
496 $errors .= $this->makeComment( $e->__toString() );
500 wfProfileOut( __METHOD__ . '-getModifiedTime' );
502 // If there's an If-Modified-Since header, respond with a 304 appropriately
503 if ( $this->tryRespondLastModified( $context, $mtime ) ) {
504 wfProfileOut( __METHOD__ );
505 return; // output handled (buffers cleared)
508 // Generate a response
509 $response = $this->makeModuleResponse( $context, $modules, $missing );
511 // Prepend comments indicating exceptions
512 $response = $errors . $response;
514 // Capture any PHP warnings from the output buffer and append them to the
515 // response in a comment if we're in debug mode.
516 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
517 $response = $this->makeComment( $warnings ) . $response;
518 $this->hasErrors = true;
521 // Save response to file cache unless there are errors
522 if ( isset( $fileCache ) && !$errors && !$missing ) {
523 // Cache single modules...and other requests if there are enough hits
524 if ( ResourceFileCache::useFileCache( $context ) ) {
525 if ( $fileCache->isCacheWorthy() ) {
526 $fileCache->saveText( $response );
527 } else {
528 $fileCache->incrMissesRecent( $context->getRequest() );
533 // Send content type and cache related headers
534 $this->sendResponseHeaders( $context, $mtime, $this->hasErrors );
536 // Remove the output buffer and output the response
537 ob_end_clean();
538 echo $response;
540 wfProfileOut( __METHOD__ );
544 * Send content type and last modified headers to the client.
545 * @param $context ResourceLoaderContext
546 * @param string $mtime TS_MW timestamp to use for last-modified
547 * @param bool $error Whether there are commented-out errors in the response
548 * @return void
550 protected function sendResponseHeaders( ResourceLoaderContext $context, $mtime, $errors ) {
551 global $wgResourceLoaderMaxage;
552 // If a version wasn't specified we need a shorter expiry time for updates
553 // to propagate to clients quickly
554 // If there were errors, we also need a shorter expiry time so we can recover quickly
555 if ( is_null( $context->getVersion() ) || $errors ) {
556 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
557 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
558 // If a version was specified we can use a longer expiry time since changing
559 // version numbers causes cache misses
560 } else {
561 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
562 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
564 if ( $context->getOnly() === 'styles' ) {
565 header( 'Content-Type: text/css; charset=utf-8' );
566 } else {
567 header( 'Content-Type: text/javascript; charset=utf-8' );
569 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $mtime ) );
570 if ( $context->getDebug() ) {
571 // Do not cache debug responses
572 header( 'Cache-Control: private, no-cache, must-revalidate' );
573 header( 'Pragma: no-cache' );
574 } else {
575 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
576 $exp = min( $maxage, $smaxage );
577 header( 'Expires: ' . wfTimestamp( TS_RFC2822, $exp + time() ) );
582 * If there's an If-Modified-Since header, respond with a 304 appropriately
583 * and clear out the output buffer. If the client cache is too old then do nothing.
584 * @param $context ResourceLoaderContext
585 * @param string $mtime The TS_MW timestamp to check the header against
586 * @return bool True iff 304 header sent and output handled
588 protected function tryRespondLastModified( ResourceLoaderContext $context, $mtime ) {
589 // If there's an If-Modified-Since header, respond with a 304 appropriately
590 // Some clients send "timestamp;length=123". Strip the part after the first ';'
591 // so we get a valid timestamp.
592 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
593 // Never send 304s in debug mode
594 if ( $ims !== false && !$context->getDebug() ) {
595 $imsTS = strtok( $ims, ';' );
596 if ( $mtime <= wfTimestamp( TS_UNIX, $imsTS ) ) {
597 // There's another bug in ob_gzhandler (see also the comment at
598 // the top of this function) that causes it to gzip even empty
599 // responses, meaning it's impossible to produce a truly empty
600 // response (because the gzip header is always there). This is
601 // a problem because 304 responses have to be completely empty
602 // per the HTTP spec, and Firefox behaves buggily when they're not.
603 // See also http://bugs.php.net/bug.php?id=51579
604 // To work around this, we tear down all output buffering before
605 // sending the 304.
606 // On some setups, ob_get_level() doesn't seem to go down to zero
607 // no matter how often we call ob_get_clean(), so instead of doing
608 // the more intuitive while ( ob_get_level() > 0 ) ob_get_clean();
609 // we have to be safe here and avoid an infinite loop.
610 // Caching the level is not an option, need to allow it to
611 // shorten the loop on-the-fly (bug 46836)
612 for ( $i = 0; $i < ob_get_level(); $i++ ) {
613 ob_end_clean();
616 header( 'HTTP/1.0 304 Not Modified' );
617 header( 'Status: 304 Not Modified' );
618 return true;
621 return false;
625 * Send out code for a response from file cache if possible
627 * @param $fileCache ResourceFileCache: Cache object for this request URL
628 * @param $context ResourceLoaderContext: Context in which to generate a response
629 * @return bool If this found a cache file and handled the response
631 protected function tryRespondFromFileCache(
632 ResourceFileCache $fileCache, ResourceLoaderContext $context
634 global $wgResourceLoaderMaxage;
635 // Buffer output to catch warnings.
636 ob_start();
637 // Get the maximum age the cache can be
638 $maxage = is_null( $context->getVersion() )
639 ? $wgResourceLoaderMaxage['unversioned']['server']
640 : $wgResourceLoaderMaxage['versioned']['server'];
641 // Minimum timestamp the cache file must have
642 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW, time() - $maxage ) );
643 if ( !$good ) {
644 try { // RL always hits the DB on file cache miss...
645 wfGetDB( DB_SLAVE );
646 } catch ( DBConnectionError $e ) { // ...check if we need to fallback to cache
647 $good = $fileCache->isCacheGood(); // cache existence check
650 if ( $good ) {
651 $ts = $fileCache->cacheTimestamp();
652 // Send content type and cache headers
653 $this->sendResponseHeaders( $context, $ts, false );
654 // If there's an If-Modified-Since header, respond with a 304 appropriately
655 if ( $this->tryRespondLastModified( $context, $ts ) ) {
656 return false; // output handled (buffers cleared)
658 $response = $fileCache->fetchText();
659 // Capture any PHP warnings from the output buffer and append them to the
660 // response in a comment if we're in debug mode.
661 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
662 $response = "/*\n$warnings\n*/\n" . $response;
664 // Remove the output buffer and output the response
665 ob_end_clean();
666 echo $response . "\n/* Cached {$ts} */";
667 return true; // cache hit
669 // Clear buffer
670 ob_end_clean();
672 return false; // cache miss
675 protected function makeComment( $text ) {
676 $encText = str_replace( '*/', '* /', $text );
677 return "/*\n$encText\n*/\n";
681 * Generates code for a response
683 * @param $context ResourceLoaderContext: Context in which to generate a response
684 * @param array $modules List of module objects keyed by module name
685 * @param array $missing List of unavailable modules (optional)
686 * @return String: Response data
688 public function makeModuleResponse( ResourceLoaderContext $context,
689 array $modules, $missing = array()
691 $out = '';
692 $exceptions = '';
693 if ( $modules === array() && $missing === array() ) {
694 return '/* No modules requested. Max made me put this here */';
697 wfProfileIn( __METHOD__ );
698 // Pre-fetch blobs
699 if ( $context->shouldIncludeMessages() ) {
700 try {
701 $blobs = MessageBlobStore::get( $this, $modules, $context->getLanguage() );
702 } catch ( Exception $e ) {
703 wfDebugLog( 'resourceloader', __METHOD__ . ": pre-fetching blobs from MessageBlobStore failed: $e" );
704 $this->hasErrors = true;
705 // Add exception to the output as a comment
706 $exceptions .= $this->makeComment( $e->__toString() );
708 } else {
709 $blobs = array();
712 // Generate output
713 $isRaw = false;
714 foreach ( $modules as $name => $module ) {
716 * @var $module ResourceLoaderModule
719 wfProfileIn( __METHOD__ . '-' . $name );
720 try {
721 $scripts = '';
722 if ( $context->shouldIncludeScripts() ) {
723 // If we are in debug mode, we'll want to return an array of URLs if possible
724 // However, we can't do this if the module doesn't support it
725 // We also can't do this if there is an only= parameter, because we have to give
726 // the module a way to return a load.php URL without causing an infinite loop
727 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
728 $scripts = $module->getScriptURLsForDebug( $context );
729 } else {
730 $scripts = $module->getScript( $context );
731 if ( is_string( $scripts ) && strlen( $scripts ) && substr( $scripts, -1 ) !== ';' ) {
732 // bug 27054: Append semicolon to prevent weird bugs
733 // caused by files not terminating their statements right
734 $scripts .= ";\n";
738 // Styles
739 $styles = array();
740 if ( $context->shouldIncludeStyles() ) {
741 // Don't create empty stylesheets like array( '' => '' ) for modules
742 // that don't *have* any stylesheets (bug 38024).
743 $stylePairs = $module->getStyles( $context );
744 if ( count ( $stylePairs ) ) {
745 // If we are in debug mode without &only= set, we'll want to return an array of URLs
746 // See comment near shouldIncludeScripts() for more details
747 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
748 $styles = array(
749 'url' => $module->getStyleURLsForDebug( $context )
751 } else {
752 // Minify CSS before embedding in mw.loader.implement call
753 // (unless in debug mode)
754 if ( !$context->getDebug() ) {
755 foreach ( $stylePairs as $media => $style ) {
756 // Can be either a string or an array of strings.
757 if ( is_array( $style ) ) {
758 $stylePairs[$media] = array();
759 foreach ( $style as $cssText ) {
760 if ( is_string( $cssText ) ) {
761 $stylePairs[$media][] = $this->filter( 'minify-css', $cssText );
764 } elseif ( is_string( $style ) ) {
765 $stylePairs[$media] = $this->filter( 'minify-css', $style );
769 // Wrap styles into @media groups as needed and flatten into a numerical array
770 $styles = array(
771 'css' => self::makeCombinedStyles( $stylePairs )
777 // Messages
778 $messagesBlob = isset( $blobs[$name] ) ? $blobs[$name] : '{}';
780 // Append output
781 switch ( $context->getOnly() ) {
782 case 'scripts':
783 if ( is_string( $scripts ) ) {
784 // Load scripts raw...
785 $out .= $scripts;
786 } elseif ( is_array( $scripts ) ) {
787 // ...except when $scripts is an array of URLs
788 $out .= self::makeLoaderImplementScript( $name, $scripts, array(), array() );
790 break;
791 case 'styles':
792 // We no longer seperate into media, they are all combined now with
793 // custom media type groups into @media .. {} sections as part of the css string.
794 // Module returns either an empty array or a numerical array with css strings.
795 $out .= isset( $styles['css'] ) ? implode( '', $styles['css'] ) : '';
796 break;
797 case 'messages':
798 $out .= self::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
799 break;
800 default:
801 $out .= self::makeLoaderImplementScript(
802 $name,
803 $scripts,
804 $styles,
805 new XmlJsCode( $messagesBlob )
807 break;
809 } catch ( Exception $e ) {
810 wfDebugLog( 'resourceloader', __METHOD__ . ": generating module package failed: $e" );
811 $this->hasErrors = true;
812 // Add exception to the output as a comment
813 $exceptions .= $this->makeComment( $e->__toString() );
815 // Register module as missing
816 $missing[] = $name;
817 unset( $modules[$name] );
819 $isRaw |= $module->isRaw();
820 wfProfileOut( __METHOD__ . '-' . $name );
823 // Update module states
824 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
825 // Set the state of modules loaded as only scripts to ready
826 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
827 $out .= self::makeLoaderStateScript(
828 array_fill_keys( array_keys( $modules ), 'ready' ) );
830 // Set the state of modules which were requested but unavailable as missing
831 if ( is_array( $missing ) && count( $missing ) ) {
832 $out .= self::makeLoaderStateScript( array_fill_keys( $missing, 'missing' ) );
836 if ( !$context->getDebug() ) {
837 if ( $context->getOnly() === 'styles' ) {
838 $out = $this->filter( 'minify-css', $out );
839 } else {
840 $out = $this->filter( 'minify-js', $out );
844 wfProfileOut( __METHOD__ );
845 return $exceptions . $out;
848 /* Static Methods */
851 * Returns JS code to call to mw.loader.implement for a module with
852 * given properties.
854 * @param string $name Module name
855 * @param $scripts Mixed: List of URLs to JavaScript files or String of JavaScript code
856 * @param $styles Mixed: Array of CSS strings keyed by media type, or an array of lists of URLs to
857 * CSS files keyed by media type
858 * @param $messages Mixed: List of messages associated with this module. May either be an
859 * associative array mapping message key to value, or a JSON-encoded message blob containing
860 * the same data, wrapped in an XmlJsCode object.
862 * @throws MWException
863 * @return string
865 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
866 if ( is_string( $scripts ) ) {
867 $scripts = new XmlJsCode( "function () {\n{$scripts}\n}" );
868 } elseif ( !is_array( $scripts ) ) {
869 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
871 return Xml::encodeJsCall(
872 'mw.loader.implement',
873 array(
874 $name,
875 $scripts,
876 // Force objects. mw.loader.implement requires them to be javascript objects.
877 // Although these variables are associative arrays, which become javascript
878 // objects through json_encode. In many cases they will be empty arrays, and
879 // PHP/json_encode() consider empty arrays to be numerical arrays and
880 // output javascript "[]" instead of "{}". This fixes that.
881 (object)$styles,
882 (object)$messages
884 ResourceLoader::inDebugMode()
889 * Returns JS code which, when called, will register a given list of messages.
891 * @param $messages Mixed: Either an associative array mapping message key to value, or a
892 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
894 * @return string
896 public static function makeMessageSetScript( $messages ) {
897 return Xml::encodeJsCall( 'mw.messages.set', array( (object)$messages ) );
901 * Combines an associative array mapping media type to CSS into a
902 * single stylesheet with "@media" blocks.
904 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings.
906 * @return Array
908 private static function makeCombinedStyles( array $stylePairs ) {
909 $out = array();
910 foreach ( $stylePairs as $media => $styles ) {
911 // ResourceLoaderFileModule::getStyle can return the styles
912 // as a string or an array of strings. This is to allow separation in
913 // the front-end.
914 $styles = (array)$styles;
915 foreach ( $styles as $style ) {
916 $style = trim( $style );
917 // Don't output an empty "@media print { }" block (bug 40498)
918 if ( $style !== '' ) {
919 // Transform the media type based on request params and config
920 // The way that this relies on $wgRequest to propagate request params is slightly evil
921 $media = OutputPage::transformCssMedia( $media );
923 if ( $media === '' || $media == 'all' ) {
924 $out[] = $style;
925 } elseif ( is_string( $media ) ) {
926 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
928 // else: skip
932 return $out;
936 * Returns a JS call to mw.loader.state, which sets the state of a
937 * module or modules to a given value. Has two calling conventions:
939 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
940 * Set the state of a single module called $name to $state
942 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
943 * Set the state of modules with the given names to the given states
945 * @param $name string
946 * @param $state
948 * @return string
950 public static function makeLoaderStateScript( $name, $state = null ) {
951 if ( is_array( $name ) ) {
952 return Xml::encodeJsCall( 'mw.loader.state', array( $name ) );
953 } else {
954 return Xml::encodeJsCall( 'mw.loader.state', array( $name, $state ) );
959 * Returns JS code which calls the script given by $script. The script will
960 * be called with local variables name, version, dependencies and group,
961 * which will have values corresponding to $name, $version, $dependencies
962 * and $group as supplied.
964 * @param string $name Module name
965 * @param $version Integer: Module version number as a timestamp
966 * @param array $dependencies List of module names on which this module depends
967 * @param string $group Group which the module is in.
968 * @param string $source Source of the module, or 'local' if not foreign.
969 * @param string $script JavaScript code
971 * @return string
973 public static function makeCustomLoaderScript( $name, $version, $dependencies, $group, $source, $script ) {
974 $script = str_replace( "\n", "\n\t", trim( $script ) );
975 return Xml::encodeJsCall(
976 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
977 array( $name, $version, $dependencies, $group, $source ) );
981 * Returns JS code which calls mw.loader.register with the given
982 * parameters. Has three calling conventions:
984 * - ResourceLoader::makeLoaderRegisterScript( $name, $version, $dependencies, $group, $source ):
985 * Register a single module.
987 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
988 * Register modules with the given names.
990 * - ResourceLoader::makeLoaderRegisterScript( array(
991 * array( $name1, $version1, $dependencies1, $group1, $source1 ),
992 * array( $name2, $version2, $dependencies1, $group2, $source2 ),
993 * ...
994 * ) ):
995 * Registers modules with the given names and parameters.
997 * @param string $name Module name
998 * @param $version Integer: Module version number as a timestamp
999 * @param array $dependencies List of module names on which this module depends
1000 * @param string $group group which the module is in.
1001 * @param string $source source of the module, or 'local' if not foreign
1003 * @return string
1005 public static function makeLoaderRegisterScript( $name, $version = null,
1006 $dependencies = null, $group = null, $source = null
1008 if ( is_array( $name ) ) {
1009 return Xml::encodeJsCall( 'mw.loader.register', array( $name ) );
1010 } else {
1011 $version = (int)$version > 1 ? (int)$version : 1;
1012 return Xml::encodeJsCall( 'mw.loader.register',
1013 array( $name, $version, $dependencies, $group, $source ) );
1018 * Returns JS code which calls mw.loader.addSource() with the given
1019 * parameters. Has two calling conventions:
1021 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1022 * Register a single source
1024 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $props1, $id2 => $props2, ... ) );
1025 * Register sources with the given IDs and properties.
1027 * @param string $id source ID
1028 * @param array $properties source properties (see addSource())
1030 * @return string
1032 public static function makeLoaderSourcesScript( $id, $properties = null ) {
1033 if ( is_array( $id ) ) {
1034 return Xml::encodeJsCall( 'mw.loader.addSource', array( $id ) );
1035 } else {
1036 return Xml::encodeJsCall( 'mw.loader.addSource', array( $id, $properties ) );
1041 * Returns JS code which runs given JS code if the client-side framework is
1042 * present.
1044 * @param string $script JavaScript code
1046 * @return string
1048 public static function makeLoaderConditionalScript( $script ) {
1049 return "if(window.mw){\n" . trim( $script ) . "\n}";
1053 * Returns JS code which will set the MediaWiki configuration array to
1054 * the given value.
1056 * @param array $configuration List of configuration values keyed by variable name
1058 * @return string
1060 public static function makeConfigSetScript( array $configuration ) {
1061 return Xml::encodeJsCall( 'mw.config.set', array( $configuration ), ResourceLoader::inDebugMode() );
1065 * Convert an array of module names to a packed query string.
1067 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
1068 * becomes 'foo.bar,baz|bar.baz,quux'
1069 * @param array $modules of module names (strings)
1070 * @return string Packed query string
1072 public static function makePackedModulesString( $modules ) {
1073 $groups = array(); // array( prefix => array( suffixes ) )
1074 foreach ( $modules as $module ) {
1075 $pos = strrpos( $module, '.' );
1076 $prefix = $pos === false ? '' : substr( $module, 0, $pos );
1077 $suffix = $pos === false ? $module : substr( $module, $pos + 1 );
1078 $groups[$prefix][] = $suffix;
1081 $arr = array();
1082 foreach ( $groups as $prefix => $suffixes ) {
1083 $p = $prefix === '' ? '' : $prefix . '.';
1084 $arr[] = $p . implode( ',', $suffixes );
1086 $str = implode( '|', $arr );
1087 return $str;
1091 * Determine whether debug mode was requested
1092 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1093 * @return bool
1095 public static function inDebugMode() {
1096 global $wgRequest, $wgResourceLoaderDebug;
1097 static $retval = null;
1098 if ( !is_null( $retval ) ) {
1099 return $retval;
1101 return $retval = $wgRequest->getFuzzyBool( 'debug',
1102 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug ) );
1106 * Build a load.php URL
1107 * @param array $modules of module names (strings)
1108 * @param string $lang Language code
1109 * @param string $skin Skin name
1110 * @param string|null $user User name. If null, the &user= parameter is omitted
1111 * @param string|null $version Versioning timestamp
1112 * @param bool $debug Whether the request should be in debug mode
1113 * @param string|null $only &only= parameter
1114 * @param bool $printable Printable mode
1115 * @param bool $handheld Handheld mode
1116 * @param array $extraQuery Extra query parameters to add
1117 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1119 public static function makeLoaderURL( $modules, $lang, $skin, $user = null, $version = null, $debug = false, $only = null,
1120 $printable = false, $handheld = false, $extraQuery = array() ) {
1121 global $wgLoadScript;
1122 $query = self::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
1123 $only, $printable, $handheld, $extraQuery
1126 // Prevent the IE6 extension check from being triggered (bug 28840)
1127 // by appending a character that's invalid in Windows extensions ('*')
1128 return wfExpandUrl( wfAppendQuery( $wgLoadScript, $query ) . '&*', PROTO_RELATIVE );
1132 * Build a query array (array representation of query string) for load.php. Helper
1133 * function for makeLoaderURL().
1134 * @return array
1136 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null, $version = null, $debug = false, $only = null,
1137 $printable = false, $handheld = false, $extraQuery = array() ) {
1138 $query = array(
1139 'modules' => self::makePackedModulesString( $modules ),
1140 'lang' => $lang,
1141 'skin' => $skin,
1142 'debug' => $debug ? 'true' : 'false',
1144 if ( $user !== null ) {
1145 $query['user'] = $user;
1147 if ( $version !== null ) {
1148 $query['version'] = $version;
1150 if ( $only !== null ) {
1151 $query['only'] = $only;
1153 if ( $printable ) {
1154 $query['printable'] = 1;
1156 if ( $handheld ) {
1157 $query['handheld'] = 1;
1159 $query += $extraQuery;
1161 // Make queries uniform in order
1162 ksort( $query );
1163 return $query;
1167 * Check a module name for validity.
1169 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1170 * at most 255 bytes.
1172 * @param string $moduleName Module name to check
1173 * @return bool Whether $moduleName is a valid module name
1175 public static function isValidModuleName( $moduleName ) {
1176 return !preg_match( '/[|,!]/', $moduleName ) && strlen( $moduleName ) <= 255;