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