Added versions to statically added ResourceLoader script and style tags.
[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 * @example
27 * // Registers a module with the resource loading system
28 * ResourceLoader::register( 'foo', array(
29 * // Script or list of scripts to include when implementating the module (required)
30 * 'script' => 'resources/foo/foo.js',
31 * // List of scripts or lists of scripts to include based on the current language
32 * 'locales' => array(
33 * 'en-gb' => 'resources/foo/locales/en-gb.js',
34 * ),
35 * // Script or list of scripts to include only when in debug mode
36 * 'debug' => 'resources/foo/debug.js',
37 * // If this module is going to be loaded before the mediawiki module is ready such as jquery or the mediawiki
38 * // module itself, it can be included without special loader wrapping - this will also limit the module to not be
39 * // able to specify needs, custom loaders, styles, themes or messages (any of the options below) - raw scripts
40 * // get registered as 'ready' after the mediawiki module is ready, so they can be named as dependencies
41 * 'raw' => false,
42 * // Modules or list of modules which are needed and should be used when generating loader code
43 * 'needs' => 'resources/foo/foo.js',
44 * // Script or list of scripts which will cause loader code to not be generated - if you are doing something fancy
45 * // with your dependencies this gives you a way to use custom registration code
46 * 'loader' => 'resources/foo/loader.js',
47 * // Style-sheets or list of style-sheets to include
48 * 'style' => 'resources/foo/foo.css',
49 * // List of style-sheets or lists of style-sheets to include based on the skin - if no match is found for current
50 * // skin, 'default' is used - if default doesn't exist nothing is added
51 * 'themes' => array(
52 * 'default' => 'resources/foo/themes/default/foo.css',
53 * 'vector' => 'resources/foo/themes/vector.foo.css',
54 * ),
55 * // List of keys of messages to include
56 * 'messages' => array( 'foo-hello', 'foo-goodbye' ),
57 * // Subclass of ResourceLoaderModule to use for custom modules
58 * 'class' => 'ResourceLoaderSiteJSModule',
59 * ) );
60 * @example
61 * // Responds to a resource loading request
62 * ResourceLoader::respond( $wgRequest, $wgServer . wfScript( 'load' ) );
63 */
64 class ResourceLoader {
65 /* Protected Static Members */
66
67 // @var array list of module name/ResourceLoaderModule object pairs
68 protected static $modules = array();
69
70 /* Protected Static Methods */
71
72 /**
73 * Runs text through a filter, caching the filtered result for future calls
74 *
75 * @param $filter String: name of filter to run
76 * @param $data String: text to filter, such as JavaScript or CSS text
77 * @param $file String: path to file being filtered, (optional: only required for CSS to resolve paths)
78 * @return String: filtered data
79 */
80 protected static function filter( $filter, $data ) {
81 global $wgMemc;
82
83 // For empty or whitespace-only things, don't do any processing
84 if ( trim( $data ) === '' ) {
85 return $data;
86 }
87
88 // Try memcached
89 $key = wfMemcKey( 'resourceloader', 'filter', $filter, md5( $data ) );
90 $cached = $wgMemc->get( $key );
91
92 if ( $cached !== false && $cached !== null ) {
93 return $cached;
94 }
95
96 // Run the filter
97 try {
98 switch ( $filter ) {
99 case 'minify-js':
100 $result = JSMin::minify( $data );
101 break;
102 case 'minify-css':
103 $result = CSSMin::minify( $data );
104 break;
105 case 'flip-css':
106 $result = CSSJanus::transform( $data, true, false );
107 break;
108 default:
109 // Don't cache anything, just pass right through
110 return $data;
111 }
112 } catch ( Exception $exception ) {
113 throw new MWException( 'Filter threw an exception: ' . $exception->getMessage() );
114 }
115
116 // Save to memcached
117 $wgMemc->set( $key, $result );
118
119 return $result;
120 }
121
122 /* Static Methods */
123
124 /**
125 * Registers a module with the ResourceLoader system.
126 *
127 * Note that registering the same object under multiple names is not supported and may silently fail in all
128 * kinds of interesting ways.
129 *
130 * @param $name Mixed: string of name of module or array of name/object pairs
131 * @param $object ResourceLoaderModule: module object (optional when using multiple-registration calling style)
132 * @return Boolean: false if there were any errors, in which case one or more modules were not registered
133 *
134 * @todo We need much more clever error reporting, not just in detailing what happened, but in bringing errors to
135 * the client in a way that they can easily see them if they want to, such as by using FireBug
136 */
137 public static function register( $name, ResourceLoaderModule $object = null ) {
138 // Allow multiple modules to be registered in one call
139 if ( is_array( $name ) && !isset( $object ) ) {
140 foreach ( $name as $key => $value ) {
141 self::register( $key, $value );
142 }
143
144 return;
145 }
146
147 // Disallow duplicate registrations
148 if ( isset( self::$modules[$name] ) ) {
149 // A module has already been registered by this name
150 throw new MWException( 'Another module has already been registered as ' . $name );
151 }
152 // Attach module
153 self::$modules[$name] = $object;
154 $object->setName( $name );
155 }
156
157 /**
158 * Gets a map of all modules and their options
159 *
160 * @return Array: array( modulename => ResourceLoaderModule )
161 */
162 public static function getModules() {
163 return self::$modules;
164 }
165
166 /**
167 * Get the ResourceLoaderModule object for a given module name
168 *
169 * @param $name String: module name
170 * @return mixed ResourceLoaderModule or null if not registered
171 */
172 public static function getModule( $name ) {
173 return isset( self::$modules[$name] ) ? self::$modules[$name] : null;
174 }
175
176 /**
177 * Gets registration code for all modules, except pre-registered ones listed in self::$preRegisteredModules
178 *
179 * @param $context ResourceLoaderContext object
180 * @return String: JavaScript code for registering all modules with the client loader
181 */
182 public static function getModuleRegistrations( ResourceLoaderContext $context ) {
183 $scripts = '';
184 $registrations = array();
185
186 foreach ( self::$modules as $name => $module ) {
187 // Support module loader scripts
188 if ( ( $loader = $module->getLoaderScript() ) !== false ) {
189 $scripts .= $loader;
190 }
191 // Automatically register module
192 else {
193 // Modules without dependencies pass two arguments (name, timestamp) to mediaWiki.loader.register()
194 if ( !count( $module->getDependencies() ) ) {
195 $registrations[] = array( $name, $module->getModifiedTime( $context ) );
196 }
197 // Modules with dependencies pass three arguments (name, timestamp, dependencies) to mediaWiki.loader.register()
198 else {
199 $registrations[] = array( $name, $module->getModifiedTime( $context ), $module->getDependencies() );
200 }
201 }
202 }
203 return $scripts . "mediaWiki.loader.register( " . FormatJson::encode( $registrations ) . " );";
204 }
205
206 /**
207 * Get the highest modification time of all modules, based on a given combination of language code,
208 * skin name and debug mode flag.
209 *
210 * @param $context ResourceLoaderContext object
211 * @return Integer: UNIX timestamp
212 */
213 public static function getHighestModifiedTime( ResourceLoaderContext $context ) {
214 $time = 1; // wfTimestamp() treats 0 as 'now', so that's not a suitable choice
215
216 foreach ( self::$modules as $module ) {
217 $time = max( $time, $module->getModifiedTime( $context ) );
218 }
219
220 return $time;
221 }
222
223 /**
224 * Outputs a response to a resource load-request, including a content-type header
225 *
226 * @param $context ResourceLoaderContext object
227 */
228 public static function respond( ResourceLoaderContext $context ) {
229 // Split requested modules into two groups, modules and missing
230 $modules = array();
231 $missing = array();
232
233 foreach ( $context->getModules() as $name ) {
234 if ( isset( self::$modules[$name] ) ) {
235 $modules[] = $name;
236 } else {
237 $missing[] = $name;
238 }
239 }
240
241 // Calculate the mtime and caching maxages for this request. We need this, 304 or no 304
242 $mtime = 1;
243 $maxage = PHP_INT_MAX;
244 $smaxage = PHP_INT_MAX;
245
246 foreach ( $modules as $name ) {
247 $mtime = max( $mtime, self::$modules[$name]->getModifiedTime( $context ) );
248 $maxage = min( $maxage, self::$modules[$name]->getClientMaxage() );
249 $smaxage = min( $smaxage, self::$modules[$name]->getServerMaxage() );
250 }
251
252 // Output headers
253 if ( $context->getOnly() === 'styles' ) {
254 header( 'Content-Type: text/css' );
255 } else {
256 header( 'Content-Type: text/javascript' );
257 }
258
259 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $mtime ) );
260 $expires = wfTimestamp( TS_RFC2822, min( $maxage, $smaxage ) + time() );
261 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
262 header( "Expires: $expires" );
263
264 // Check if there's an If-Modified-Since header and respond with a 304 Not Modified if possible
265 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
266
267 if ( $ims !== false && wfTimestamp( TS_UNIX, $ims ) == $mtime ) {
268 header( 'HTTP/1.0 304 Not Modified' );
269 header( 'Status: 304 Not Modified' );
270 return;
271 }
272
273 // Use output buffering
274 ob_start();
275
276 // Pre-fetch blobs
277 $blobs = $context->shouldIncludeMessages() ?
278 MessageBlobStore::get( $modules, $context->getLanguage() ) : array();
279
280 // Generate output
281 foreach ( $modules as $name ) {
282 // Scripts
283 $scripts = '';
284
285 if ( $context->shouldIncludeScripts() ) {
286 $scripts .= self::$modules[$name]->getScript( $context );
287 }
288
289 // Styles
290 $styles = array();
291
292 if (
293 $context->shouldIncludeStyles() && ( count( $styles = self::$modules[$name]->getStyles( $context ) ) )
294 ) {
295 foreach ( $styles as $media => $style ) {
296 if ( self::$modules[$name]->getFlip( $context ) ) {
297 $styles[$media] = self::filter( 'flip-css', $style );
298 }
299 if ( !$context->getDebug() ) {
300 $styles[$media] = self::filter( 'minify-css', $style );
301 }
302 }
303 }
304
305 // Messages
306 $messages = isset( $blobs[$name] ) ? $blobs[$name] : '{}';
307
308 // Output
309 if ( $context->getOnly() === 'styles' ) {
310 if ( $context->getDebug() ) {
311 echo "/* $name */\n";
312 foreach ( $styles as $media => $style ) {
313 echo "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "\n}\n";
314 }
315 } else {
316 foreach ( $styles as $media => $style ) {
317 if ( strlen( $style ) ) {
318 echo "@media $media{" . $style . "}";
319 }
320 }
321 }
322 } else if ( $context->getOnly() === 'scripts' ) {
323 echo $scripts;
324 } else if ( $context->getOnly() === 'messages' ) {
325 echo "mediaWiki.msg.set( $messages );\n";
326 } else {
327 $styles = FormatJson::encode( $styles );
328 echo "mediaWiki.loader.implement( '$name', function() {{$scripts}},\n$styles,\n$messages );\n";
329 }
330 }
331
332 // Update the status of script-only modules
333 if ( $context->getOnly() === 'scripts' && !in_array( 'startup', $modules ) ) {
334 $statuses = array();
335
336 foreach ( $modules as $name ) {
337 $statuses[$name] = 'ready';
338 }
339
340 $statuses = FormatJson::encode( $statuses );
341 echo "mediaWiki.loader.state( $statuses );\n";
342 }
343
344 // Register missing modules
345 if ( $context->shouldIncludeScripts() ) {
346 foreach ( $missing as $name ) {
347 echo "mediaWiki.loader.register( '$name', null, 'missing' );\n";
348 }
349 }
350
351 // Output the appropriate header
352 if ( $context->getOnly() !== 'styles' ) {
353 if ( $context->getDebug() ) {
354 ob_end_flush();
355 } else {
356 echo self::filter( 'minify-js', ob_get_clean() );
357 }
358 }
359 }
360 }
361
362 // FIXME: Temp hack
363 require_once "$IP/resources/Resources.php";