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