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