* Made Resources.php return a pure-data array instead of an ugly mix of data and...
[lhc/web/wiklou.git] / includes / resourceloader / ResourceLoader.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 * @author Roan Kattouw
20 * @author Trevor Parscal
21 */
22
23 /**
24 * Dynamic JavaScript and CSS resource loading system.
25 *
26 * Most of the documention is on the MediaWiki documentation wiki starting at:
27 * http://www.mediawiki.org/wiki/ResourceLoader
28 */
29 class ResourceLoader {
30
31 /* Protected Static Members */
32
33 /** Array: List of module name/ResourceLoaderModule object pairs */
34 protected $modules = array();
35 /** Associative array mapping module name to info associative array */
36 protected $moduleInfos = array();
37
38 /* Protected Methods */
39
40 /**
41 * Loads information stored in the database about modules.
42 *
43 * This method grabs modules dependencies from the database and updates modules
44 * objects.
45 *
46 * This is not inside the module code because it is much faster to
47 * request all of the information at once than it is to have each module
48 * requests its own information. This sacrifice of modularity yields a substantial
49 * performance improvement.
50 *
51 * @param $modules Array: List of module names to preload information for
52 * @param $context ResourceLoaderContext: Context to load the information within
53 */
54 protected function preloadModuleInfo( array $modules, ResourceLoaderContext $context ) {
55 if ( !count( $modules ) ) {
56 return; // or else Database*::select() will explode, plus it's cheaper!
57 }
58 $dbr = wfGetDB( DB_SLAVE );
59 $skin = $context->getSkin();
60 $lang = $context->getLanguage();
61
62 // Get file dependency information
63 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
64 'md_module' => $modules,
65 'md_skin' => $context->getSkin()
66 ), __METHOD__
67 );
68
69 // Set modules' dependecies
70 $modulesWithDeps = array();
71 foreach ( $res as $row ) {
72 $this->getModule( $row->md_module )->setFileDependencies( $skin,
73 FormatJson::decode( $row->md_deps, true )
74 );
75 $modulesWithDeps[] = $row->md_module;
76 }
77
78 // Register the absence of a dependency row too
79 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
80 $this->getModule( $name )->setFileDependencies( $skin, array() );
81 }
82
83 // Get message blob mtimes. Only do this for modules with messages
84 $modulesWithMessages = array();
85 $modulesWithoutMessages = array();
86 foreach ( $modules as $name ) {
87 if ( count( $this->getModule( $name )->getMessages() ) ) {
88 $modulesWithMessages[] = $name;
89 } else {
90 $modulesWithoutMessages[] = $name;
91 }
92 }
93 if ( count( $modulesWithMessages ) ) {
94 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
95 'mr_resource' => $modulesWithMessages,
96 'mr_lang' => $lang
97 ), __METHOD__
98 );
99 foreach ( $res as $row ) {
100 $this->getModule( $row->mr_resource )->setMsgBlobMtime( $lang, $row->mr_timestamp );
101 }
102 }
103 foreach ( $modulesWithoutMessages as $name ) {
104 $this->getModule( $name )->setMsgBlobMtime( $lang, 0 );
105 }
106 }
107
108 /**
109 * Runs JavaScript or CSS data through a filter, caching the filtered result for future calls.
110 *
111 * Available filters are:
112 * - minify-js \see JSMin::minify
113 * - minify-css \see CSSMin::minify
114 * - flip-css \see CSSJanus::transform
115 *
116 * If $data is empty, only contains whitespace or the filter was unknown,
117 * $data is returned unmodified.
118 *
119 * @param $filter String: Name of filter to run
120 * @param $data String: Text to filter, such as JavaScript or CSS text
121 * @return String: Filtered data
122 */
123 protected function filter( $filter, $data ) {
124 wfProfileIn( __METHOD__ );
125
126 // For empty/whitespace-only data or for unknown filters, don't perform
127 // any caching or processing
128 if ( trim( $data ) === ''
129 || !in_array( $filter, array( 'minify-js', 'minify-css', 'flip-css' ) ) )
130 {
131 wfProfileOut( __METHOD__ );
132 return $data;
133 }
134
135 // Try for cache hit
136 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
137 $key = wfMemcKey( 'resourceloader', 'filter', $filter, md5( $data ) );
138 $cache = wfGetCache( CACHE_ANYTHING );
139 $cacheEntry = $cache->get( $key );
140 if ( is_string( $cacheEntry ) ) {
141 wfProfileOut( __METHOD__ );
142 return $cacheEntry;
143 }
144
145 // Run the filter - we've already verified one of these will work
146 try {
147 switch ( $filter ) {
148 case 'minify-js':
149 $result = JSMin::minify( $data );
150 break;
151 case 'minify-css':
152 $result = CSSMin::minify( $data );
153 break;
154 case 'flip-css':
155 $result = CSSJanus::transform( $data, true, false );
156 break;
157 }
158 } catch ( Exception $exception ) {
159 throw new MWException( 'ResourceLoader filter error. ' .
160 'Exception was thrown: ' . $exception->getMessage() );
161 }
162
163 // Save filtered text to Memcached
164 $cache->set( $key, $result );
165
166 wfProfileOut( __METHOD__ );
167
168 return $result;
169 }
170
171 /* Methods */
172
173 /**
174 * Registers core modules and runs registration hooks.
175 */
176 public function __construct() {
177 global $IP, $wgResourceModules;
178
179 wfProfileIn( __METHOD__ );
180
181 // Register core modules
182 $this->register( include( "$IP/resources/Resources.php" ) );
183 // Register extension modules
184 wfRunHooks( 'ResourceLoaderRegisterModules', array( &$this ) );
185 $this->register( $wgResourceModules );
186
187 wfProfileOut( __METHOD__ );
188 }
189
190 /**
191 * Registers a module with the ResourceLoader system.
192 *
193 * @param $name Mixed: Name of module as a string or List of name/object pairs as an array
194 * @param $info Module info array. For backwards compatibility with 1.17alpha,
195 * this may also be a ResourceLoaderModule object. Optional when using
196 * multiple-registration calling style.
197 * @throws MWException: If a duplicate module registration is attempted
198 * @throws MWException: If something other than a ResourceLoaderModule is being registered
199 * @return Boolean: False if there were any errors, in which case one or more modules were not
200 * registered
201 */
202 public function register( $name, $info = null ) {
203 wfProfileIn( __METHOD__ );
204
205 // Allow multiple modules to be registered in one call
206 if ( is_array( $name ) ) {
207 foreach ( $name as $key => $value ) {
208 $this->register( $key, $value );
209 }
210 return;
211 }
212
213 // Disallow duplicate registrations
214 if ( isset( $this->moduleInfos[$name] ) ) {
215 // A module has already been registered by this name
216 throw new MWException(
217 'ResourceLoader duplicate registration error. ' .
218 'Another module has already been registered as ' . $name
219 );
220 }
221
222 // Attach module
223 if ( is_object( $info ) ) {
224 // Old calling convention
225 // Validate the input
226 if ( !( $info instanceof ResourceLoaderModule ) ) {
227 throw new MWException( 'ResourceLoader invalid module error. ' .
228 'Instances of ResourceLoaderModule expected.' );
229 }
230
231 $this->moduleInfos[$name] = array( 'object' => $info );
232 $this->modules[$name] = $info;
233 } else {
234 // New calling convention
235 $this->moduleInfos[$name] = $info;
236 }
237
238 wfProfileOut( __METHOD__ );
239 }
240
241 /**
242 * Get a list of module names
243 *
244 * @return Array: List of module names
245 */
246 public function getModuleNames() {
247 return array_keys( $this->moduleInfos );
248 }
249
250 /**
251 * Get the ResourceLoaderModule object for a given module name.
252 *
253 * @param $name String: Module name
254 * @return Mixed: ResourceLoaderModule if module has been registered, null otherwise
255 */
256 public function getModule( $name ) {
257 if ( !isset( $this->modules[$name] ) ) {
258 if ( !isset( $this->moduleInfos[$name] ) ) {
259 // No such module
260 return null;
261 }
262 // Construct the requested object
263 $info = $this->moduleInfos[$name];
264 if ( isset( $info['object'] ) ) {
265 // Object given in info array
266 $object = $info['object'];
267 } else {
268 if ( !isset( $info['class'] ) ) {
269 $class = 'ResourceLoaderFileModule';
270 } else {
271 $class = $info['class'];
272 }
273 $object = new $class( $info );
274 }
275 $object->setName( $name );
276 $this->modules[$name] = $object;
277 }
278
279 return $this->modules[$name];
280 }
281
282 /**
283 * Outputs a response to a resource load-request, including a content-type header.
284 *
285 * @param $context ResourceLoaderContext: Context in which a response should be formed
286 */
287 public function respond( ResourceLoaderContext $context ) {
288 global $wgResourceLoaderMaxage, $wgCacheEpoch;
289
290 wfProfileIn( __METHOD__ );
291
292 // Split requested modules into two groups, modules and missing
293 $modules = array();
294 $missing = array();
295 foreach ( $context->getModules() as $name ) {
296 if ( isset( $this->moduleInfos[$name] ) ) {
297 $modules[$name] = $this->getModule( $name );
298 } else {
299 $missing[] = $name;
300 }
301 }
302
303 // If a version wasn't specified we need a shorter expiry time for updates
304 // to propagate to clients quickly
305 if ( is_null( $context->getVersion() ) ) {
306 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
307 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
308 }
309 // If a version was specified we can use a longer expiry time since changing
310 // version numbers causes cache misses
311 else {
312 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
313 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
314 }
315
316 // Preload information needed to the mtime calculation below
317 $this->preloadModuleInfo( array_keys( $modules ), $context );
318
319 wfProfileIn( __METHOD__.'-getModifiedTime' );
320
321 // To send Last-Modified and support If-Modified-Since, we need to detect
322 // the last modified time
323 $mtime = wfTimestamp( TS_UNIX, $wgCacheEpoch );
324 foreach ( $modules as $module ) {
325 // Bypass squid cache if the request includes any private modules
326 if ( $module->getGroup() === 'private' ) {
327 $smaxage = 0;
328 }
329 // Calculate maximum modified time
330 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
331 }
332
333 wfProfileOut( __METHOD__.'-getModifiedTime' );
334
335 if ( $context->getOnly() === 'styles' ) {
336 header( 'Content-Type: text/css' );
337 } else {
338 header( 'Content-Type: text/javascript' );
339 }
340 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $mtime ) );
341 if ( $context->getDebug() ) {
342 header( 'Cache-Control: must-revalidate' );
343 } else {
344 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
345 header( 'Expires: ' . wfTimestamp( TS_RFC2822, min( $maxage, $smaxage ) + time() ) );
346 }
347
348 // If there's an If-Modified-Since header, respond with a 304 appropriately
349 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
350 if ( $ims !== false && $mtime <= wfTimestamp( TS_UNIX, $ims ) ) {
351 header( 'HTTP/1.0 304 Not Modified' );
352 header( 'Status: 304 Not Modified' );
353 wfProfileOut( __METHOD__ );
354 return;
355 }
356
357 // Generate a response
358 $response = $this->makeModuleResponse( $context, $modules, $missing );
359
360 // Tack on PHP warnings as a comment in debug mode
361 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
362 $response .= "/*\n$warnings\n*/";
363 }
364
365 // Clear any warnings from the buffer
366 ob_clean();
367 echo $response;
368
369 wfProfileOut( __METHOD__ );
370 }
371
372 /**
373 * Generates code for a response
374 *
375 * @param $context ResourceLoaderContext: Context in which to generate a response
376 * @param $modules Array: List of module objects keyed by module name
377 * @param $missing Array: List of unavailable modules (optional)
378 * @return String: Response data
379 */
380 public function makeModuleResponse( ResourceLoaderContext $context,
381 array $modules, $missing = array() )
382 {
383 // Pre-fetch blobs
384 if ( $context->shouldIncludeMessages() ) {
385 $blobs = MessageBlobStore::get( $this, $modules, $context->getLanguage() );
386 } else {
387 $blobs = array();
388 }
389
390 // Generate output
391 $out = '';
392 foreach ( $modules as $name => $module ) {
393
394 wfProfileIn( __METHOD__ . '-' . $name );
395
396 // Scripts
397 $scripts = '';
398 if ( $context->shouldIncludeScripts() ) {
399 $scripts .= $module->getScript( $context ) . "\n";
400 }
401
402 // Styles
403 $styles = array();
404 if ( $context->shouldIncludeStyles() ) {
405 $styles = $module->getStyles( $context );
406 // Flip CSS on a per-module basis
407 if ( $styles && $module->getFlip( $context ) ) {
408 foreach ( $styles as $media => $style ) {
409 $styles[$media] = $this->filter( 'flip-css', $style );
410 }
411 }
412 }
413
414 // Messages
415 $messagesBlob = isset( $blobs[$name] ) ? $blobs[$name] : array();
416
417 // Append output
418 switch ( $context->getOnly() ) {
419 case 'scripts':
420 $out .= $scripts;
421 break;
422 case 'styles':
423 $out .= self::makeCombinedStyles( $styles );
424 break;
425 case 'messages':
426 $out .= self::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
427 break;
428 default:
429 // Minify CSS before embedding in mediaWiki.loader.implement call
430 // (unless in debug mode)
431 if ( !$context->getDebug() ) {
432 foreach ( $styles as $media => $style ) {
433 $styles[$media] = $this->filter( 'minify-css', $style );
434 }
435 }
436 $out .= self::makeLoaderImplementScript( $name, $scripts, $styles,
437 new XmlJsCode( $messagesBlob ) );
438 break;
439 }
440
441 wfProfileOut( __METHOD__ . '-' . $name );
442 }
443
444 // Update module states
445 if ( $context->shouldIncludeScripts() ) {
446 // Set the state of modules loaded as only scripts to ready
447 if ( count( $modules ) && $context->getOnly() === 'scripts'
448 && !isset( $modules['startup'] ) )
449 {
450 $out .= self::makeLoaderStateScript(
451 array_fill_keys( array_keys( $modules ), 'ready' ) );
452 }
453 // Set the state of modules which were requested but unavailable as missing
454 if ( is_array( $missing ) && count( $missing ) ) {
455 $out .= self::makeLoaderStateScript( array_fill_keys( $missing, 'missing' ) );
456 }
457 }
458
459 if ( $context->getDebug() ) {
460 return $out;
461 } else {
462 if ( $context->getOnly() === 'styles' ) {
463 return $this->filter( 'minify-css', $out );
464 } else {
465 return $this->filter( 'minify-js', $out );
466 }
467 }
468 }
469
470 /* Static Methods */
471
472 /**
473 * Returns JS code to call to mediaWiki.loader.implement for a module with
474 * given properties.
475 *
476 * @param $name Module name
477 * @param $scripts Array: List of JavaScript code snippets to be executed after the
478 * module is loaded
479 * @param $styles Array: List of CSS strings keyed by media type
480 * @param $messages Mixed: List of messages associated with this module. May either be an
481 * associative array mapping message key to value, or a JSON-encoded message blob containing
482 * the same data, wrapped in an XmlJsCode object.
483 */
484 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
485 if ( is_array( $scripts ) ) {
486 $scripts = implode( $scripts, "\n" );
487 }
488 return Xml::encodeJsCall(
489 'mediaWiki.loader.implement',
490 array(
491 $name,
492 new XmlJsCode( "function() {{$scripts}}" ),
493 (object)$styles,
494 (object)$messages
495 ) );
496 }
497
498 /**
499 * Returns JS code which, when called, will register a given list of messages.
500 *
501 * @param $messages Mixed: Either an associative array mapping message key to value, or a
502 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
503 */
504 public static function makeMessageSetScript( $messages ) {
505 return Xml::encodeJsCall( 'mediaWiki.messages.set', array( (object)$messages ) );
506 }
507
508 /**
509 * Combines an associative array mapping media type to CSS into a
510 * single stylesheet with @media blocks.
511 *
512 * @param $styles Array: List of CSS strings keyed by media type
513 */
514 public static function makeCombinedStyles( array $styles ) {
515 $out = '';
516 foreach ( $styles as $media => $style ) {
517 $out .= "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "\n}\n";
518 }
519 return $out;
520 }
521
522 /**
523 * Returns a JS call to mediaWiki.loader.state, which sets the state of a
524 * module or modules to a given value. Has two calling conventions:
525 *
526 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
527 * Set the state of a single module called $name to $state
528 *
529 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
530 * Set the state of modules with the given names to the given states
531 */
532 public static function makeLoaderStateScript( $name, $state = null ) {
533 if ( is_array( $name ) ) {
534 return Xml::encodeJsCall( 'mediaWiki.loader.state', array( $name ) );
535 } else {
536 return Xml::encodeJsCall( 'mediaWiki.loader.state', array( $name, $state ) );
537 }
538 }
539
540 /**
541 * Returns JS code which calls the script given by $script. The script will
542 * be called with local variables name, version, dependencies and group,
543 * which will have values corresponding to $name, $version, $dependencies
544 * and $group as supplied.
545 *
546 * @param $name String: Module name
547 * @param $version Integer: Module version number as a timestamp
548 * @param $dependencies Array: List of module names on which this module depends
549 * @param $group String: Group which the module is in.
550 * @param $script String: JavaScript code
551 */
552 public static function makeCustomLoaderScript( $name, $version, $dependencies, $group, $script ) {
553 $script = str_replace( "\n", "\n\t", trim( $script ) );
554 return Xml::encodeJsCall(
555 "( function( name, version, dependencies, group ) {\n\t$script\n} )",
556 array( $name, $version, $dependencies, $group ) );
557 }
558
559 /**
560 * Returns JS code which calls mediaWiki.loader.register with the given
561 * parameters. Has three calling conventions:
562 *
563 * - ResourceLoader::makeLoaderRegisterScript( $name, $version, $dependencies, $group ):
564 * Register a single module.
565 *
566 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
567 * Register modules with the given names.
568 *
569 * - ResourceLoader::makeLoaderRegisterScript( array(
570 * array( $name1, $version1, $dependencies1, $group1 ),
571 * array( $name2, $version2, $dependencies1, $group2 ),
572 * ...
573 * ) ):
574 * Registers modules with the given names and parameters.
575 *
576 * @param $name String: Module name
577 * @param $version Integer: Module version number as a timestamp
578 * @param $dependencies Array: List of module names on which this module depends
579 * @param $group String: group which the module is in.
580 */
581 public static function makeLoaderRegisterScript( $name, $version = null,
582 $dependencies = null, $group = null )
583 {
584 if ( is_array( $name ) ) {
585 return Xml::encodeJsCall( 'mediaWiki.loader.register', array( $name ) );
586 } else {
587 $version = (int) $version > 1 ? (int) $version : 1;
588 return Xml::encodeJsCall( 'mediaWiki.loader.register',
589 array( $name, $version, $dependencies, $group ) );
590 }
591 }
592
593 /**
594 * Returns JS code which runs given JS code if the client-side framework is
595 * present.
596 *
597 * @param $script String: JavaScript code
598 */
599 public static function makeLoaderConditionalScript( $script ) {
600 $script = str_replace( "\n", "\n\t", trim( $script ) );
601 return "if ( window.mediaWiki ) {\n\t$script\n}\n";
602 }
603
604 /**
605 * Returns JS code which will set the MediaWiki configuration array to
606 * the given value.
607 *
608 * @param $configuration Array: List of configuration values keyed by variable name
609 */
610 public static function makeConfigSetScript( array $configuration ) {
611 return Xml::encodeJsCall( 'mediaWiki.config.set', array( $configuration ) );
612 }
613
614 /**
615 * Determine whether debug mode was requested
616 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
617 * @return bool
618 */
619 public static function inDebugMode() {
620 global $wgRequest, $wgResourceLoaderDebug;
621 static $retval = null;
622 if ( !is_null( $retval ) )
623 return $retval;
624 return $retval = $wgRequest->getFuzzyBool( 'debug',
625 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug ) );
626 }
627 }