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