* Added $wgResourceLoaderDebug, a default fallback for debug mode which can be overri...
[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 /**
24 * Dynamic JavaScript and CSS resource loading system
25 */
26 class ResourceLoader {
27
28 /* Protected Static Members */
29
30 // @var array list of module name/ResourceLoaderModule object pairs
31 protected static $modules = array();
32 protected static $initialized = false;
33
34 /* Protected Static Methods */
35
36 /*
37 * Registers core modules and runs registration hooks
38 */
39 protected static function initialize() {
40 global $IP;
41
42 // Safety check - this should never be called more than once
43 if ( !self::$initialized ) {
44 wfProfileIn( __METHOD__ );
45 // This needs to be first, because hooks might call ResourceLoader
46 // public interfaces which will call this
47 self::$initialized = true;
48 self::register( include( "$IP/resources/Resources.php" ) );
49 wfRunHooks( 'ResourceLoaderRegisterModules' );
50 wfProfileOut( __METHOD__ );
51 }
52 }
53
54 /**
55 * Runs text through a filter, caching the filtered result for future calls
56 *
57 * @param $filter String: name of filter to run
58 * @param $data String: text to filter, such as JavaScript or CSS text
59 * @param $file String: path to file being filtered, (optional: only required
60 * for CSS to resolve paths)
61 * @return String: filtered data
62 */
63 protected static function filter( $filter, $data ) {
64 global $wgMemc;
65 wfProfileIn( __METHOD__ );
66
67 // For empty or whitespace-only things, don't do any processing
68 if ( trim( $data ) === '' ) {
69 wfProfileOut( __METHOD__ );
70 return $data;
71 }
72
73 // Try memcached
74 $key = wfMemcKey( 'resourceloader', 'filter', $filter, md5( $data ) );
75 $cached = $wgMemc->get( $key );
76
77 if ( $cached !== false && $cached !== null ) {
78 wfProfileOut( __METHOD__ );
79 return $cached;
80 }
81
82 // Run the filter
83 try {
84 switch ( $filter ) {
85 case 'minify-js':
86 $result = JSMin::minify( $data );
87 break;
88 case 'minify-css':
89 $result = CSSMin::minify( $data );
90 break;
91 case 'flip-css':
92 $result = CSSJanus::transform( $data, true, false );
93 break;
94 default:
95 // Don't cache anything, just pass right through
96 wfProfileOut( __METHOD__ );
97 return $data;
98 }
99 } catch ( Exception $exception ) {
100 throw new MWException( 'Filter threw an exception: ' . $exception->getMessage() );
101 }
102
103 // Save to memcached
104 $wgMemc->set( $key, $result );
105
106 wfProfileOut( __METHOD__ );
107 return $result;
108 }
109
110 /* Static Methods */
111
112 /**
113 * Registers a module with the ResourceLoader system.
114 *
115 * Note that registering the same object under multiple names is not supported
116 * and may silently fail in all kinds of interesting ways.
117 *
118 * @param $name Mixed: string of name of module or array of name/object pairs
119 * @param $object ResourceLoaderModule: module object (optional when using
120 * multiple-registration calling style)
121 * @return Boolean: false if there were any errors, in which case one or more
122 * modules were not registered
123 *
124 * @todo We need much more clever error reporting, not just in detailing what
125 * happened, but in bringing errors to the client in a way that they can
126 * easily see them if they want to, such as by using FireBug
127 */
128 public static function register( $name, ResourceLoaderModule $object = null ) {
129 wfProfileIn( __METHOD__ );
130 self::initialize();
131
132 // Allow multiple modules to be registered in one call
133 if ( is_array( $name ) && !isset( $object ) ) {
134 foreach ( $name as $key => $value ) {
135 self::register( $key, $value );
136 }
137
138 wfProfileOut( __METHOD__ );
139 return;
140 }
141
142 // Disallow duplicate registrations
143 if ( isset( self::$modules[$name] ) ) {
144 // A module has already been registered by this name
145 throw new MWException( 'Another module has already been registered as ' . $name );
146 }
147 // Attach module
148 self::$modules[$name] = $object;
149 $object->setName( $name );
150 wfProfileOut( __METHOD__ );
151 }
152
153 /**
154 * Gets a map of all modules and their options
155 *
156 * @return Array: array( modulename => ResourceLoaderModule )
157 */
158 public static function getModules() {
159
160 self::initialize();
161
162 return self::$modules;
163 }
164
165 /**
166 * Get the ResourceLoaderModule object for a given module name
167 *
168 * @param $name String: module name
169 * @return mixed ResourceLoaderModule or null if not registered
170 */
171 public static function getModule( $name ) {
172
173 self::initialize();
174
175 return isset( self::$modules[$name] ) ? self::$modules[$name] : null;
176 }
177
178 /**
179 * Gets registration code for all modules
180 *
181 * @param $context ResourceLoaderContext object
182 * @return String: JavaScript code for registering all modules with the client loader
183 */
184 public static function getModuleRegistrations( ResourceLoaderContext $context ) {
185 wfProfileIn( __METHOD__ );
186 self::initialize();
187
188 $scripts = '';
189 $registrations = array();
190
191 foreach ( self::$modules as $name => $module ) {
192 // Support module loader scripts
193 if ( ( $loader = $module->getLoaderScript() ) !== false ) {
194 $deps = FormatJson::encode( $module->getDependencies() );
195 $group = FormatJson::encode( $module->getGroup() );
196 $version = wfTimestamp( TS_ISO_8601, round( $module->getModifiedTime( $context ), -2 ) );
197 $scripts .= "( function( name, version, dependencies ) { $loader } )\n" .
198 "( '$name', '$version', $deps, $group );\n";
199 }
200 // Automatically register module
201 else {
202 // Modules without dependencies or a group pass two arguments (name, timestamp) to
203 // mediaWiki.loader.register()
204 if ( !count( $module->getDependencies() && $module->getGroup() === null ) ) {
205 $registrations[] = array( $name, $module->getModifiedTime( $context ) );
206 }
207 // Modules with dependencies but no group pass three arguments (name, timestamp, dependencies)
208 // to mediaWiki.loader.register()
209 else if ( $module->getGroup() === null ) {
210 $registrations[] = array(
211 $name, $module->getModifiedTime( $context ), $module->getDependencies() );
212 }
213 // Modules with dependencies pass four arguments (name, timestamp, dependencies, group)
214 // to mediaWiki.loader.register()
215 else {
216 $registrations[] = array(
217 $name, $module->getModifiedTime( $context ), $module->getDependencies(), $module->getGroup() );
218 }
219 }
220 }
221 $out = $scripts . "mediaWiki.loader.register( " . FormatJson::encode( $registrations ) . " );\n";
222 wfProfileOut( __METHOD__ );
223 return $out;
224 }
225
226 /**
227 * Get the highest modification time of all modules, based on a given
228 * combination of language code, skin name and debug mode flag.
229 *
230 * @param $context ResourceLoaderContext object
231 * @return Integer: UNIX timestamp
232 */
233 public static function getHighestModifiedTime( ResourceLoaderContext $context ) {
234
235 self::initialize();
236
237 $time = 1; // wfTimestamp() treats 0 as 'now', so that's not a suitable choice
238
239 foreach ( self::$modules as $module ) {
240 $time = max( $time, $module->getModifiedTime( $context ) );
241 }
242
243 return $time;
244 }
245
246 /**
247 * Outputs a response to a resource load-request, including a content-type header
248 *
249 * @param $context ResourceLoaderContext object
250 */
251 public static function respond( ResourceLoaderContext $context ) {
252 global $wgResourceLoaderMaxage;
253
254 wfProfileIn( __METHOD__ );
255 self::initialize();
256
257 // Split requested modules into two groups, modules and missing
258 $modules = array();
259 $missing = array();
260
261 foreach ( $context->getModules() as $name ) {
262 if ( isset( self::$modules[$name] ) ) {
263 $modules[] = $name;
264 } else {
265 $missing[] = $name;
266 }
267 }
268
269 // If a version wasn't specified we need a shorter expiry time for updates to
270 // propagate to clients quickly
271 if ( is_null( $context->getVersion() ) ) {
272 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
273 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
274 }
275 // If a version was specified we can use a longer expiry time since changing
276 // version numbers causes cache misses
277 else {
278 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
279 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
280 }
281
282 // To send Last-Modified and support If-Modified-Since, we need to detect
283 // the last modified time
284 wfProfileIn( __METHOD__.'-getModifiedTime' );
285 $mtime = 1;
286 foreach ( $modules as $name ) {
287 $mtime = max( $mtime, self::$modules[$name]->getModifiedTime( $context ) );
288 }
289 wfProfileOut( __METHOD__.'-getModifiedTime' );
290
291 header( 'Content-Type: ' . ( $context->getOnly() === 'styles' ? 'text/css' : 'text/javascript' ) );
292 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $mtime ) );
293 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
294 header( 'Expires: ' . wfTimestamp( TS_RFC2822, min( $maxage, $smaxage ) + time() ) );
295
296 // If there's an If-Modified-Since header, respond with a 304 appropriately
297 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
298 if ( $ims !== false && $mtime >= wfTimestamp( TS_UNIX, $ims ) ) {
299 header( 'HTTP/1.0 304 Not Modified' );
300 header( 'Status: 304 Not Modified' );
301 wfProfileOut( __METHOD__ );
302 return;
303 }
304
305 // Use output buffering
306 ob_start();
307
308 // Pre-fetch blobs
309 $blobs = $context->shouldIncludeMessages() ?
310 MessageBlobStore::get( $modules, $context->getLanguage() ) : array();
311
312 // Generate output
313 foreach ( $modules as $name ) {
314 wfProfileIn( __METHOD__ . '-' . $name );
315 // Scripts
316 $scripts = '';
317
318 if ( $context->shouldIncludeScripts() ) {
319 $scripts .= self::$modules[$name]->getScript( $context ) . "\n";
320 }
321
322 // Styles
323 $styles = array();
324
325 if (
326 $context->shouldIncludeStyles()
327 && ( count( $styles = self::$modules[$name]->getStyles( $context ) ) )
328 ) {
329 foreach ( $styles as $media => $style ) {
330 if ( self::$modules[$name]->getFlip( $context ) ) {
331 $styles[$media] = self::filter( 'flip-css', $style );
332 }
333 if ( !$context->getDebug() ) {
334 $styles[$media] = self::filter( 'minify-css', $style );
335 }
336 }
337 }
338
339 // Messages
340 $messages = isset( $blobs[$name] ) ? $blobs[$name] : '{}';
341
342 // Output
343 if ( $context->getOnly() === 'styles' ) {
344 if ( $context->getDebug() ) {
345 echo "/* $name */\n";
346 foreach ( $styles as $media => $style ) {
347 echo "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "\n}\n";
348 }
349 } else {
350 foreach ( $styles as $media => $style ) {
351 if ( strlen( $style ) ) {
352 echo "@media $media{" . $style . "}";
353 }
354 }
355 }
356 } else if ( $context->getOnly() === 'scripts' ) {
357 echo $scripts;
358 } else if ( $context->getOnly() === 'messages' ) {
359 echo "mediaWiki.msg.set( $messages );\n";
360 } else {
361 if ( count( $styles ) ) {
362 $styles = FormatJson::encode( $styles );
363 } else {
364 $styles = 'null';
365 }
366 echo "mediaWiki.loader.implement( '$name', function() {{$scripts}},\n$styles,\n$messages );\n";
367 }
368 wfProfileOut( __METHOD__ . '-' . $name );
369 }
370
371 // Update the status of script-only modules
372 if ( $context->getOnly() === 'scripts' && !in_array( 'startup', $modules ) ) {
373 $statuses = array();
374
375 foreach ( $modules as $name ) {
376 $statuses[$name] = 'ready';
377 }
378
379 $statuses = FormatJson::encode( $statuses );
380 echo "mediaWiki.loader.state( $statuses );\n";
381 }
382
383 // Register missing modules
384 if ( $context->shouldIncludeScripts() ) {
385 foreach ( $missing as $name ) {
386 echo "mediaWiki.loader.register( '$name', null, 'missing' );\n";
387 }
388 }
389
390 // Output the appropriate header
391 if ( $context->getOnly() !== 'styles' ) {
392 if ( $context->getDebug() ) {
393 ob_end_flush();
394 } else {
395 echo self::filter( 'minify-js', ob_get_clean() );
396 }
397 }
398 wfProfileOut( __METHOD__ );
399 }
400 }