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