484329b8c8e22bc05c940b7c9eeebd5d972930b1
[lhc/web/wiklou.git] / includes / 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 defined( 'MEDIAWIKI' ) || die( 1 );
24
25 /**
26 * Dynamic JavaScript and CSS resource loading system
27 */
28 class ResourceLoader {
29
30 /* Protected Static Members */
31
32 // @var array list of module name/ResourceLoaderModule object pairs
33 protected static $modules = array();
34 protected static $initialized = false;
35
36 /* Protected Static Methods */
37
38 /**
39 * Registers core modules and runs registration hooks
40 */
41 protected static function initialize() {
42 global $IP;
43
44 // Safety check - this should never be called more than once
45 if ( !self::$initialized ) {
46 wfProfileIn( __METHOD__ );
47 // This needs to be first, because hooks might call ResourceLoader
48 // public interfaces which will call this
49 self::$initialized = true;
50 self::register( include( "$IP/resources/Resources.php" ) );
51 wfRunHooks( 'ResourceLoaderRegisterModules' );
52 wfProfileOut( __METHOD__ );
53 }
54 }
55
56 /*
57 * Loads information stored in the database about modules
58 *
59 * This is not inside the module code because it's so much more performant to request all of the information at once
60 * than it is to have each module requests it's own information.
61 *
62 * @param $modules array list of module names to preload information for
63 * @param $context ResourceLoaderContext context to load the information within
64 */
65 protected static function preloadModuleInfo( array $modules, ResourceLoaderContext $context ) {
66 $dbr = wfGetDb( DB_SLAVE );
67 $skin = $context->getSkin();
68 $lang = $context->getLanguage();
69
70 // Get file dependency information
71 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
72 'md_module' => $modules,
73 'md_skin' => $context->getSkin()
74 ), __METHOD__
75 );
76
77 $modulesWithDeps = array();
78 foreach ( $res as $row ) {
79 self::$modules[$row->md_module]->setFileDependencies( $skin,
80 FormatJson::decode( $row->md_deps, true )
81 );
82 $modulesWithDeps[] = $row->md_module;
83 }
84 // Register the absence of a dependencies row too
85 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
86 self::$modules[$name]->setFileDependencies( $skin, array() );
87 }
88
89 // Get message blob mtimes. Only do this for modules with messages
90 $modulesWithMessages = array();
91 $modulesWithoutMessages = array();
92 foreach ( $modules as $name ) {
93 if ( count( self::$modules[$name]->getMessages() ) ) {
94 $modulesWithMessages[] = $name;
95 } else {
96 $modulesWithoutMessages[] = $name;
97 }
98 }
99 if ( count( $modulesWithMessages ) ) {
100 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
101 'mr_resource' => $modulesWithMessages,
102 'mr_lang' => $lang
103 ), __METHOD__
104 );
105 foreach ( $res as $row ) {
106 self::$modules[$row->mr_resource]->setMsgBlobMtime( $lang, $row->mr_timestamp );
107 }
108 }
109 foreach ( $modulesWithoutMessages as $name ) {
110 self::$modules[$name]->setMsgBlobMtime( $lang, 0 );
111 }
112 }
113
114 /**
115 * Runs text through a filter, caching the filtered result for future calls
116 *
117 * @param $filter String: name of filter to run
118 * @param $data String: text to filter, such as JavaScript or CSS text
119 * @param $file String: path to file being filtered, (optional: only required for CSS to resolve paths)
120 * @return String: filtered data
121 */
122 protected static function filter( $filter, $data ) {
123 global $wgMemc;
124 wfProfileIn( __METHOD__ );
125
126 // For empty or whitespace-only things, don't do any processing
127 if ( trim( $data ) === '' ) {
128 wfProfileOut( __METHOD__ );
129 return $data;
130 }
131
132 // Try memcached
133 $key = wfMemcKey( 'resourceloader', 'filter', $filter, md5( $data ) );
134 $cached = $wgMemc->get( $key );
135
136 if ( $cached !== false && $cached !== null ) {
137 wfProfileOut( __METHOD__ );
138 return $cached;
139 }
140
141 // Run the filter
142 try {
143 switch ( $filter ) {
144 case 'minify-js':
145 $result = JSMin::minify( $data );
146 break;
147 case 'minify-css':
148 $result = CSSMin::minify( $data );
149 break;
150 case 'flip-css':
151 $result = CSSJanus::transform( $data, true, false );
152 break;
153 default:
154 // Don't cache anything, just pass right through
155 wfProfileOut( __METHOD__ );
156 return $data;
157 }
158 } catch ( Exception $exception ) {
159 throw new MWException( 'Filter threw an exception: ' . $exception->getMessage() );
160 }
161
162 // Save to memcached
163 $wgMemc->set( $key, $result );
164
165 wfProfileOut( __METHOD__ );
166 return $result;
167 }
168
169 /* Static Methods */
170
171 /**
172 * Registers a module with the ResourceLoader system.
173 *
174 * Note that registering the same object under multiple names is not supported
175 * and may silently fail in all kinds of interesting ways.
176 *
177 * @param $name Mixed: string of name of module or array of name/object pairs
178 * @param $object ResourceLoaderModule: module object (optional when using
179 * multiple-registration calling style)
180 * @return Boolean: false if there were any errors, in which case one or more
181 * modules were not registered
182 *
183 * @todo We need much more clever error reporting, not just in detailing what
184 * happened, but in bringing errors to the client in a way that they can
185 * easily see them if they want to, such as by using FireBug
186 */
187 public static function register( $name, ResourceLoaderModule $object = null ) {
188 wfProfileIn( __METHOD__ );
189 self::initialize();
190
191 // Allow multiple modules to be registered in one call
192 if ( is_array( $name ) && !isset( $object ) ) {
193 foreach ( $name as $key => $value ) {
194 self::register( $key, $value );
195 }
196
197 wfProfileOut( __METHOD__ );
198 return;
199 }
200
201 // Disallow duplicate registrations
202 if ( isset( self::$modules[$name] ) ) {
203 // A module has already been registered by this name
204 throw new MWException( 'Another module has already been registered as ' . $name );
205 }
206 // Attach module
207 self::$modules[$name] = $object;
208 $object->setName( $name );
209 wfProfileOut( __METHOD__ );
210 }
211
212 /**
213 * Gets a map of all modules and their options
214 *
215 * @return Array: array( modulename => ResourceLoaderModule )
216 */
217 public static function getModules() {
218
219 self::initialize();
220
221 return self::$modules;
222 }
223
224 /**
225 * Get the ResourceLoaderModule object for a given module name
226 *
227 * @param $name String: module name
228 * @return mixed ResourceLoaderModule or null if not registered
229 */
230 public static function getModule( $name ) {
231
232 self::initialize();
233
234 return isset( self::$modules[$name] ) ? self::$modules[$name] : null;
235 }
236
237 /**
238 * Get the highest modification time of all modules, based on a given
239 * combination of language code, skin name and debug mode flag.
240 *
241 * @param $context ResourceLoaderContext object
242 * @return Integer: UNIX timestamp
243 */
244 public static function getHighestModifiedTime( ResourceLoaderContext $context ) {
245
246 self::initialize();
247
248 $time = 1; // wfTimestamp() treats 0 as 'now', so that's not a suitable choice
249
250 foreach ( self::$modules as $module ) {
251 $time = max( $time, $module->getModifiedTime( $context ) );
252 }
253
254 return $time;
255 }
256
257 /**
258 * Outputs a response to a resource load-request, including a content-type header
259 *
260 * @param $context ResourceLoaderContext object
261 */
262 public static function respond( ResourceLoaderContext $context ) {
263 global $wgResourceLoaderMaxage;
264
265 wfProfileIn( __METHOD__ );
266 self::initialize();
267
268 // Split requested modules into two groups, modules and missing
269 $modules = array();
270 $missing = array();
271
272 foreach ( $context->getModules() as $name ) {
273 if ( isset( self::$modules[$name] ) ) {
274 $modules[$name] = self::$modules[$name];
275 } else {
276 $missing[] = $name;
277 }
278 }
279
280 // If a version wasn't specified we need a shorter expiry time for updates to
281 // propagate to clients quickly
282 if ( is_null( $context->getVersion() ) ) {
283 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
284 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
285 }
286 // If a version was specified we can use a longer expiry time since changing
287 // version numbers causes cache misses
288 else {
289 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
290 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
291 }
292
293 // Preload information needed to the mtime calculation below
294 self::preloadModuleInfo( array_keys( $modules ), $context );
295
296 // To send Last-Modified and support If-Modified-Since, we need to detect
297 // the last modified time
298 wfProfileIn( __METHOD__.'-getModifiedTime' );
299 $mtime = 1;
300 foreach ( $modules as $module ) {
301 // Bypass squid cache if the request includes any private modules
302 if ( $module->getGroup() === 'private' ) {
303 $smaxage = 0;
304 }
305 // Calculate maximum modified time
306 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
307 }
308 wfProfileOut( __METHOD__.'-getModifiedTime' );
309
310 header( 'Content-Type: ' . ( $context->getOnly() === 'styles' ? 'text/css' : 'text/javascript' ) );
311 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $mtime ) );
312 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
313 header( 'Expires: ' . wfTimestamp( TS_RFC2822, min( $maxage, $smaxage ) + time() ) );
314
315 // If there's an If-Modified-Since header, respond with a 304 appropriately
316 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
317 if ( $ims !== false && $mtime >= wfTimestamp( TS_UNIX, $ims ) ) {
318 header( 'HTTP/1.0 304 Not Modified' );
319 header( 'Status: 304 Not Modified' );
320 wfProfileOut( __METHOD__ );
321 return;
322 }
323
324 echo self::makeModuleResponse( $context, $modules, $missing );
325
326 wfProfileOut( __METHOD__ );
327 }
328
329 public static function makeModuleResponse( ResourceLoaderContext $context, array $modules, $missing = null ) {
330 global $wgUser;
331
332 // Pre-fetch blobs
333 $blobs = $context->shouldIncludeMessages() ?
334 MessageBlobStore::get( array_keys( $modules ), $context->getLanguage() ) : array();
335
336 // Generate output
337 $out = '';
338 foreach ( $modules as $name => $module ) {
339 wfProfileIn( __METHOD__ . '-' . $name );
340
341 // Scripts
342 $scripts = '';
343 if ( $context->shouldIncludeScripts() ) {
344 $scripts .= $module->getScript( $context ) . "\n";
345 }
346
347 // Styles
348 $styles = array();
349 if (
350 $context->shouldIncludeStyles() &&
351 ( count( $styles = $module->getStyles( $context ) ) )
352 ) {
353 // Flip CSS on a per-module basis
354 if ( self::$modules[$name]->getFlip( $context ) ) {
355 foreach ( $styles as $media => $style ) {
356 $styles[$media] = self::filter( 'flip-css', $style );
357 }
358 }
359 }
360
361 // Messages
362 $messages = isset( $blobs[$name] ) ? $blobs[$name] : '{}';
363
364 // Append output
365 switch ( $context->getOnly() ) {
366 case 'scripts':
367 $out .= $scripts;
368 break;
369 case 'styles':
370 $out .= self::makeCombinedStyles( $styles );
371 break;
372 case 'messages':
373 $out .= self::makeMessageSetScript( $messages );
374 break;
375 default:
376 // Minify CSS before embedding in mediaWiki.loader.implement call (unless in debug mode)
377 if ( !$context->getDebug() ) {
378 foreach ( $styles as $media => $style ) {
379 $styles[$media] = self::filter( 'minify-css', $style );
380 }
381 }
382 $out .= self::makeLoaderImplementScript( $name, $scripts, $styles, $messages );
383 break;
384 }
385
386 wfProfileOut( __METHOD__ . '-' . $name );
387 }
388
389 // Update module states
390 if ( $context->shouldIncludeScripts() ) {
391 // Set the state of modules loaded as only scripts to ready
392 if ( count( $modules ) && $context->getOnly() === 'scripts' && !isset( $modules['startup'] ) ) {
393 $out .= self::makeLoaderStateScript( array_fill_keys( array_keys( $modules ), 'ready' ) );
394 }
395 // Set the state of modules which were requested but unavailable as missing
396 if ( is_array( $missing ) && count( $missing ) ) {
397 $out .= self::makeLoaderStateScript( array_fill_keys( $missing, 'missing' ) );
398 }
399 }
400
401 if ( $context->getDebug() ) {
402 return $out;
403 } else {
404 if ( $context->getOnly() === 'styles' ) {
405 return self::filter( 'minify-css', $out );
406 } else {
407 return self::filter( 'minify-js', $out );
408 }
409 }
410 }
411
412 // Client code generation methods
413
414 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
415 if ( is_array( $scripts ) ) {
416 $scripts = implode( $scripts, "\n" );
417 }
418 if ( is_array( $styles ) ) {
419 $styles = count( $styles ) ? FormatJson::encode( $styles ) : 'null';
420 }
421 if ( is_array( $messages ) ) {
422 $messages = count( $messages ) ? FormatJson::encode( $messages ) : 'null';
423 }
424 return "mediaWiki.loader.implement( '$name', function() {{$scripts}},\n$styles,\n$messages );\n";
425 }
426
427 public static function makeMessageSetScript( $messages ) {
428 if ( is_array( $messages ) ) {
429 $messages = count( $messages ) ? FormatJson::encode( $messages ) : 'null';
430 }
431 return "mediaWiki.msg.set( $messages );\n";
432 }
433
434 public static function makeCombinedStyles( array $styles ) {
435 $out = '';
436 foreach ( $styles as $media => $style ) {
437 $out .= "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "\n}\n";
438 }
439 return $out;
440 }
441
442 public static function makeLoaderStateScript( $name, $state = null ) {
443 if ( is_array( $name ) ) {
444 $statuses = FormatJson::encode( $name );
445 return "mediaWiki.loader.state( $statuses );\n";
446 } else {
447 $name = Xml::escapeJsString( $name );
448 $name = Xml::escapeJsString( $state );
449 return "mediaWiki.loader.state( '$name', '$state' );\n";
450 }
451 }
452
453 public static function makeCustomLoaderScript( $name, $version, $dependencies, $group, $script ) {
454 $name = Xml::escapeJsString( $name );
455 $version = (int) $version > 1 ? (int) $version : 1;
456 if ( is_array( $dependencies ) ) {
457 $dependencies = FormatJson::encode( $dependencies );
458 } else if ( is_string( $dependencies ) ) {
459 $dependencies = "'" . Xml::escapeJsString( $dependencies ) . "'";
460 } else {
461 $dependencies = 'null';
462 }
463 if ( is_string( $group ) ) {
464 $group = "'" . Xml::escapeJsString( $group ) . "'";
465 } else {
466 $group = 'null';
467 }
468 $script = str_replace( "\n", "\n\t", trim( $script ) );
469 return "( function( name, version, dependencies ) {\n\t$script\n} )" .
470 "( '$name', $version, $dependencies, $group );\n";
471 }
472
473 public static function makeLoaderRegisterScript( $name, $version = null, $dependencies = null, $group = null ) {
474 if ( is_array( $name ) ) {
475 $registrations = FormatJson::encode( $name );
476 return "mediaWiki.loader.register( $registrations );\n";
477 } else {
478 $name = Xml::escapeJsString( $name );
479 $version = (int) $version > 1 ? (int) $version : 1;
480 if ( is_array( $dependencies ) ) {
481 $dependencies = FormatJson::encode( $dependencies );
482 } else if ( is_string( $dependencies ) ) {
483 $dependencies = "'" . Xml::escapeJsString( $dependencies ) . "'";
484 } else {
485 $dependencies = 'null';
486 }
487 if ( is_string( $group ) ) {
488 $group = "'" . Xml::escapeJsString( $group ) . "'";
489 } else {
490 $group = 'null';
491 }
492 return "mediaWiki.loader.register( '$name', $version, $dependencies, $group );\n";
493 }
494 }
495
496 public static function makeLoaderConditionalScript( $script ) {
497 $script = str_replace( "\n", "\n\t", trim( $script ) );
498 return "if ( window.mediaWiki ) {\n\t$script\n}\n";
499 }
500
501 public static function makeConfigSetScript( array $configuration ) {
502 $configuration = FormatJson::encode( $configuration );
503 return "mediaWiki.config.set( $configuration );\n";
504 }
505 }