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