Better solution for r72367, this allows file modules to always be written in ltr...
[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 . $wgScriptPath . '/load.php' );
62 */
63 class ResourceLoader {
64
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 {string} $filter name of filter to run
76 * @param {string} $data text to filter, such as JavaScript or CSS text
77 * @param {string} $file 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 // 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 if ( $cached !== false && $cached !== null ) {
91 return $cached;
92 }
93
94 // Run the filter
95 try {
96 switch ( $filter ) {
97 case 'minify-js':
98 $result = JSMin::minify( $data );
99 break;
100 case 'minify-css':
101 $result = CSSMin::minify( $data );
102 break;
103 case 'flip-css':
104 $result = CSSJanus::transform( $data, true, false );
105 break;
106 default:
107 // Don't cache anything, just pass right through
108 return $data;
109 }
110 } catch ( Exception $exception ) {
111 throw new MWException( 'Filter threw an exception: ' . $exception->getMessage() );
112 }
113
114 // Save to memcached
115 $wgMemc->set( $key, $result );
116 return $result;
117 }
118
119 /* Static Methods */
120
121 /**
122 * Registers a module with the ResourceLoader system.
123 *
124 * Note that registering the same object under multiple names is not supported and may silently fail in all
125 * kinds of interesting ways.
126 *
127 * @param {mixed} $name string of name of module or array of name/object pairs
128 * @param {ResourceLoaderModule} $object module object (optional when using multiple-registration calling style)
129 * @return {boolean} false if there were any errors, in which case one or more modules were not registered
130 *
131 * @todo We need much more clever error reporting, not just in detailing what happened, but in bringing errors to
132 * the client in a way that they can easily see them if they want to, such as by using FireBug
133 */
134 public static function register( $name, ResourceLoaderModule $object = null ) {
135 // Allow multiple modules to be registered in one call
136 if ( is_array( $name ) && !isset( $object ) ) {
137 foreach ( $name as $key => $value ) {
138 self::register( $key, $value );
139 }
140 return;
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 }
151
152 /**
153 * Gets a map of all modules and their options
154 *
155 * @return {array} array( modulename => ResourceLoaderModule )
156 */
157 public static function getModules() {
158 return self::$modules;
159 }
160
161 /**
162 * Get the ResourceLoaderModule object for a given module name
163 * @param $name string Module name
164 * @return mixed ResourceLoaderModule or null if not registered
165 */
166 public static function getModule( $name ) {
167 return isset( self::$modules[$name] ) ? self::$modules[$name] : null;
168 }
169
170 /**
171 * Gets registration code for all modules, except pre-registered ones listed in self::$preRegisteredModules
172 *
173 * The $lang, $skin and $debug parameters are used to calculate the last modified timestamps for each
174 * module.
175 * @param $lang string Language code
176 * @param $skin string Skin name
177 * @param $debug bool Debug mode flag
178 * @return {string} JavaScript code for registering all modules with the client loader
179 */
180 public static function getModuleRegistrations( ResourceLoaderContext $context ) {
181 $scripts = '';
182 $registrations = array();
183 foreach ( self::$modules as $name => $module ) {
184 // Support module loader scripts
185 if ( ( $loader = $module->getLoaderScript() ) !== false ) {
186 $scripts .= $loader;
187 }
188 // Automatically register module
189 else {
190 // Modules without dependencies pass two arguments (name, timestamp) to mediaWiki.loader.register()
191 if ( !count( $module->getDependencies() ) ) {
192 $registrations[] = array( $name, $module->getModifiedTime( $context ) );
193 }
194 // Modules with dependencies pass three arguments (name, timestamp, dependencies) to mediaWiki.loader.register()
195 else {
196 $registrations[] = array( $name, $module->getModifiedTime( $context ), $module->getDependencies() );
197 }
198 }
199 }
200 return $scripts . "mediaWiki.loader.register( " . FormatJson::encode( $registrations ) . " );";
201 }
202
203 /**
204 * Get the highest modification time of all modules, based on a given combination of language code,
205 * skin name and debug mode flag.
206 * @param $lang string Language code
207 * @param $skin string Skin name
208 * @param $debug bool Debug mode flag
209 * @return int UNIX timestamp
210 */
211 public static function getHighestModifiedTime( ResourceLoaderContext $context ) {
212 $time = 1; // wfTimestamp() treats 0 as 'now', so that's not a suitable choice
213 foreach ( self::$modules as $module ) {
214 $time = max( $time, $module->getModifiedTime( $context ) );
215 }
216 return $time;
217 }
218
219 /* Methods */
220
221 /*
222 * Outputs a response to a resource load-request, including a content-type header
223 *
224 * @param {WebRequest} $request web request object to respond to
225 * @param {string} $server web-accessible path to script server
226 *
227 * $options format:
228 * array(
229 * 'lang' => [string: language code, optional, code of default language by default],
230 * 'skin' => [string: name of skin, optional, name of default skin by default],
231 * 'dir' => [string: 'ltr' or 'rtl', optional, direction of lang by default],
232 * 'debug' => [boolean: true to include debug-only scripts, optional, false by default],
233 * 'only' => [string: 'scripts', 'styles' or 'messages', optional, if set only get part of the requested module]
234 * )
235 */
236 public static function respond( ResourceLoaderContext $context ) {
237 // Split requested modules into two groups, modules and missing
238 $modules = array();
239 $missing = array();
240 foreach ( $context->getModules() as $name ) {
241 if ( isset( self::$modules[$name] ) ) {
242 $modules[] = $name;
243 } else {
244 $missing[] = $name;
245 }
246 }
247
248 // Calculate the mtime and caching maxages for this request. We need this, 304 or no 304
249 $mtime = 1;
250 $maxage = PHP_INT_MAX;
251 $smaxage = PHP_INT_MAX;
252 foreach ( $modules as $name ) {
253 $mtime = max( $mtime, self::$modules[$name]->getModifiedTime( $context ) );
254 $maxage = min( $maxage, self::$modules[$name]->getClientMaxage() );
255 $smaxage = min( $smaxage, self::$modules[$name]->getServerMaxage() );
256 }
257
258 // Output headers
259 if ( $context->getOnly() === 'styles' ) {
260 header( 'Content-Type: text/css' );
261 } else {
262 header( 'Content-Type: text/javascript' );
263 }
264 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $mtime ) );
265 $expires = wfTimestamp( TS_RFC2822, min( $maxage, $smaxage ) + time() );
266 header( "Cache-Control: public, maxage=$maxage, s-maxage=$smaxage" );
267 header( "Expires: $expires" );
268
269 // Check if there's an If-Modified-Since header and respond with a 304 Not Modified if possible
270 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
271 if ( $ims !== false && wfTimestamp( TS_UNIX, $ims ) == $mtime ) {
272 header( 'HTTP/1.0 304 Not Modified' );
273 header( 'Status: 304 Not Modified' );
274 return;
275 }
276
277 // Use output buffering
278 ob_start();
279
280 // Pre-fetch blobs
281 $blobs = $context->shouldIncludeMessages() ?
282 MessageBlobStore::get( $modules, $context->getLanguage() ) : array();
283
284 // Generate output
285 foreach ( $modules as $name ) {
286 // Scripts
287 $scripts = '';
288 if ( $context->shouldIncludeScripts() ) {
289 $scripts .= self::$modules[$name]->getScript( $context );
290 }
291 // Styles
292 $styles = '';
293 if (
294 $context->shouldIncludeStyles() &&
295 ( $styles .= self::$modules[$name]->getStyle( $context ) ) !== ''
296 ) {
297 if ( self::$modules[$name]->getFlip( $context ) ) {
298 $styles = self::filter( 'flip-css', $styles );
299 }
300 $styles = $context->getDebug() ? $styles : self::filter( 'minify-css', $styles );
301 }
302 // Messages
303 $messages = isset( $blobs[$name] ) ? $blobs[$name] : '{}';
304 // Output
305 if ( $context->getOnly() === 'styles' ) {
306 echo $styles;
307 } else if ( $context->getOnly() === 'scripts' ) {
308 echo $scripts;
309 } else if ( $context->getOnly() === 'messages' ) {
310 echo "mediaWiki.msg.set( $messages );\n";
311 } else {
312 $styles = Xml::escapeJsString( $styles );
313 echo "mediaWiki.loader.implement( '$name', function() {{$scripts}},\n'$styles',\n$messages );\n";
314 }
315 }
316 // Update the status of script-only modules
317 if ( $context->getOnly() === 'scripts' && !in_array( 'startup', $modules ) ) {
318 $statuses = array();
319 foreach ( $modules as $name ) {
320 $statuses[$name] = 'ready';
321 }
322 $statuses = FormatJson::encode( $statuses );
323 echo "mediaWiki.loader.state( $statuses );";
324 }
325 // Register missing modules
326 if ( $context->shouldIncludeScripts() ) {
327 foreach ( $missing as $name ) {
328 echo "mediaWiki.loader.register( '$name', null, 'missing' );\n";
329 }
330 }
331 // Output the appropriate header
332 if ( $context->getOnly() !== 'styles' ) {
333 if ( $context->getDebug() ) {
334 ob_end_flush();
335 } else {
336 echo self::filter( 'minify-js', ob_get_clean() );
337 }
338 }
339 }
340 }
341
342 // FIXME: Temp hack
343 require_once "$IP/resources/Resources.php";