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