For consistency, removed line break
[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, except pre-registered ones listed in
180 * self::$preRegisteredModules
181 *
182 * @param $context ResourceLoaderContext object
183 * @return String: JavaScript code for registering all modules with the client loader
184 */
185 public static function getModuleRegistrations( ResourceLoaderContext $context ) {
186 wfProfileIn( __METHOD__ );
187 self::initialize();
188
189 $scripts = '';
190 $registrations = array();
191
192 foreach ( self::$modules as $name => $module ) {
193 // Support module loader scripts
194 if ( ( $loader = $module->getLoaderScript() ) !== false ) {
195 $deps = FormatJson::encode( $module->getDependencies() );
196 $version = wfTimestamp( TS_ISO_8601,
197 round( $module->getModifiedTime( $context ), -2 ) );
198 $scripts .= "( function( name, version, dependencies ) { $loader } )\n" .
199 "( '$name', '$version', $deps );\n";
200 }
201 // Automatically register module
202 else {
203 // Modules without dependencies pass two arguments (name, timestamp) to
204 // mediaWiki.loader.register()
205 if ( !count( $module->getDependencies() ) ) {
206 $registrations[] = array( $name, $module->getModifiedTime( $context ) );
207 }
208 // Modules with dependencies pass three arguments (name, timestamp, dependencies)
209 // to mediaWiki.loader.register()
210 else {
211 $registrations[] = array( $name, $module->getModifiedTime( $context ),
212 $module->getDependencies() );
213 }
214 }
215 }
216 $out = $scripts . "mediaWiki.loader.register( " . FormatJson::encode( $registrations ) . " );\n";
217 wfProfileOut( __METHOD__ );
218 return $out;
219 }
220
221 /**
222 * Get the highest modification time of all modules, based on a given
223 * combination of language code, skin name and debug mode flag.
224 *
225 * @param $context ResourceLoaderContext object
226 * @return Integer: UNIX timestamp
227 */
228 public static function getHighestModifiedTime( ResourceLoaderContext $context ) {
229
230 self::initialize();
231
232 $time = 1; // wfTimestamp() treats 0 as 'now', so that's not a suitable choice
233
234 foreach ( self::$modules as $module ) {
235 $time = max( $time, $module->getModifiedTime( $context ) );
236 }
237
238 return $time;
239 }
240
241 /**
242 * Outputs a response to a resource load-request, including a content-type header
243 *
244 * @param $context ResourceLoaderContext object
245 */
246 public static function respond( ResourceLoaderContext $context ) {
247 global $wgResourceLoaderVersionedClientMaxage, $wgResourceLoaderVersionedServerMaxage;
248 global $wgResourceLoaderUnversionedServerMaxage, $wgResourceLoaderUnversionedClientMaxage;
249
250 wfProfileIn( __METHOD__ );
251 self::initialize();
252
253 // Split requested modules into two groups, modules and missing
254 $modules = array();
255 $missing = array();
256
257 foreach ( $context->getModules() as $name ) {
258 if ( isset( self::$modules[$name] ) ) {
259 $modules[] = $name;
260 } else {
261 $missing[] = $name;
262 }
263 }
264
265 // If a version wasn't specified we need a shorter expiry time for updates to
266 // propagate to clients quickly
267 if ( is_null( $context->getVersion() ) ) {
268 $maxage = $wgResourceLoaderUnversionedClientMaxage;
269 $smaxage = $wgResourceLoaderUnversionedServerMaxage;
270 }
271 // If a version was specified we can use a longer expiry time since changing
272 // version numbers causes cache misses
273 else {
274 $maxage = $wgResourceLoaderVersionedClientMaxage;
275 $smaxage = $wgResourceLoaderVersionedServerMaxage;
276 }
277
278 // To send Last-Modified and support If-Modified-Since, we need to detect
279 // the last modified time
280 wfProfileIn( __METHOD__.'-getModifiedTime' );
281 $mtime = 1;
282 foreach ( $modules as $name ) {
283 $mtime = max( $mtime, self::$modules[$name]->getModifiedTime( $context ) );
284 }
285 wfProfileOut( __METHOD__.'-getModifiedTime' );
286
287 header( 'Content-Type: ' . ( $context->getOnly() === 'styles' ? 'text/css' : 'text/javascript' ) );
288 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $mtime ) );
289 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
290 header( 'Expires: ' . wfTimestamp( TS_RFC2822, min( $maxage, $smaxage ) + time() ) );
291
292 // If there's an If-Modified-Since header, respond with a 304 appropriately
293 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
294 if ( $ims !== false && $mtime >= wfTimestamp( TS_UNIX, $ims ) ) {
295 header( 'HTTP/1.0 304 Not Modified' );
296 header( 'Status: 304 Not Modified' );
297 wfProfileOut( __METHOD__ );
298 return;
299 }
300
301 // Use output buffering
302 ob_start();
303
304 // Pre-fetch blobs
305 $blobs = $context->shouldIncludeMessages() ?
306 MessageBlobStore::get( $modules, $context->getLanguage() ) : array();
307
308 // Generate output
309 foreach ( $modules as $name ) {
310 wfProfileIn( __METHOD__ . '-' . $name );
311 // Scripts
312 $scripts = '';
313
314 if ( $context->shouldIncludeScripts() ) {
315 $scripts .= self::$modules[$name]->getScript( $context ) . "\n";
316 }
317
318 // Styles
319 $styles = array();
320
321 if (
322 $context->shouldIncludeStyles()
323 && ( count( $styles = self::$modules[$name]->getStyles( $context ) ) )
324 ) {
325 foreach ( $styles as $media => $style ) {
326 if ( self::$modules[$name]->getFlip( $context ) ) {
327 $styles[$media] = self::filter( 'flip-css', $style );
328 }
329 if ( !$context->getDebug() ) {
330 $styles[$media] = self::filter( 'minify-css', $style );
331 }
332 }
333 }
334
335 // Messages
336 $messages = isset( $blobs[$name] ) ? $blobs[$name] : '{}';
337
338 // Output
339 if ( $context->getOnly() === 'styles' ) {
340 if ( $context->getDebug() ) {
341 echo "/* $name */\n";
342 foreach ( $styles as $media => $style ) {
343 echo "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "\n}\n";
344 }
345 } else {
346 foreach ( $styles as $media => $style ) {
347 if ( strlen( $style ) ) {
348 echo "@media $media{" . $style . "}";
349 }
350 }
351 }
352 } else if ( $context->getOnly() === 'scripts' ) {
353 echo $scripts;
354 } else if ( $context->getOnly() === 'messages' ) {
355 echo "mediaWiki.msg.set( $messages );\n";
356 } else {
357 if ( count( $styles ) ) {
358 $styles = FormatJson::encode( $styles );
359 } else {
360 $styles = 'null';
361 }
362 echo "mediaWiki.loader.implement( '$name', function() {{$scripts}},\n$styles,\n$messages );\n";
363 }
364 wfProfileOut( __METHOD__ . '-' . $name );
365 }
366
367 // Update the status of script-only modules
368 if ( $context->getOnly() === 'scripts' && !in_array( 'startup', $modules ) ) {
369 $statuses = array();
370
371 foreach ( $modules as $name ) {
372 $statuses[$name] = 'ready';
373 }
374
375 $statuses = FormatJson::encode( $statuses );
376 echo "mediaWiki.loader.state( $statuses );\n";
377 }
378
379 // Register missing modules
380 if ( $context->shouldIncludeScripts() ) {
381 foreach ( $missing as $name ) {
382 echo "mediaWiki.loader.register( '$name', null, 'missing' );\n";
383 }
384 }
385
386 // Output the appropriate header
387 if ( $context->getOnly() !== 'styles' ) {
388 if ( $context->getDebug() ) {
389 ob_end_flush();
390 } else {
391 echo self::filter( 'minify-js', ob_get_clean() );
392 }
393 }
394 wfProfileOut( __METHOD__ );
395 }
396 }