Remove $wgMemc->set() call left over from r73645
[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 defined( 'MEDIAWIKI' ) || die( 1 );
24
25 /**
26 * Dynamic JavaScript and CSS resource loading system
27 */
28 class ResourceLoader {
29
30 /* Protected Static Members */
31
32 // @var array list of module name/ResourceLoaderModule object pairs
33 protected $modules = array();
34
35 /* Protected Methods */
36
37 /**
38 * Loads information stored in the database about modules
39 *
40 * This is not inside the module code because it's so much more performant to request all of the information at once
41 * than it is to have each module requests it's own information.
42 *
43 * @param $modules array list of module names to preload information for
44 * @param $context ResourceLoaderContext context to load the information within
45 */
46 protected function preloadModuleInfo( array $modules, ResourceLoaderContext $context ) {
47 if ( !count( $modules ) ) {
48 return; # or Database*::select() will explode
49 }
50 $dbr = wfGetDb( DB_SLAVE );
51 $skin = $context->getSkin();
52 $lang = $context->getLanguage();
53
54 // Get file dependency information
55 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
56 'md_module' => $modules,
57 'md_skin' => $context->getSkin()
58 ), __METHOD__
59 );
60
61 $modulesWithDeps = array();
62 foreach ( $res as $row ) {
63 $this->modules[$row->md_module]->setFileDependencies( $skin,
64 FormatJson::decode( $row->md_deps, true )
65 );
66 $modulesWithDeps[] = $row->md_module;
67 }
68 // Register the absence of a dependencies row too
69 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
70 $this->modules[$name]->setFileDependencies( $skin, array() );
71 }
72
73 // Get message blob mtimes. Only do this for modules with messages
74 $modulesWithMessages = array();
75 $modulesWithoutMessages = array();
76 foreach ( $modules as $name ) {
77 if ( count( $this->modules[$name]->getMessages() ) ) {
78 $modulesWithMessages[] = $name;
79 } else {
80 $modulesWithoutMessages[] = $name;
81 }
82 }
83 if ( count( $modulesWithMessages ) ) {
84 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
85 'mr_resource' => $modulesWithMessages,
86 'mr_lang' => $lang
87 ), __METHOD__
88 );
89 foreach ( $res as $row ) {
90 $this->modules[$row->mr_resource]->setMsgBlobMtime( $lang, $row->mr_timestamp );
91 }
92 }
93 foreach ( $modulesWithoutMessages as $name ) {
94 $this->modules[$name]->setMsgBlobMtime( $lang, 0 );
95 }
96 }
97
98 /**
99 * Runs text through a filter, caching the filtered result for future calls
100 *
101 * @param $filter String: name of filter to run
102 * @param $data String: text to filter, such as JavaScript or CSS text
103 * @param $file String: path to file being filtered, (optional: only required for CSS to resolve paths)
104 * @return String: filtered data
105 */
106 protected function filter( $filter, $data ) {
107 global $wgMemc;
108 wfProfileIn( __METHOD__ );
109
110 // For empty or whitespace-only things, don't do any processing
111 if ( trim( $data ) === '' ) {
112 wfProfileOut( __METHOD__ );
113 return $data;
114 }
115
116 // Try memcached
117 $key = wfMemcKey( 'resourceloader', 'filter', $filter, md5( $data ) );
118 $cached = $wgMemc->get( $key );
119
120 if ( $cached !== false && $cached !== null ) {
121 wfProfileOut( __METHOD__ );
122 return $cached;
123 }
124
125 // Run the filter
126 try {
127 switch ( $filter ) {
128 case 'minify-js':
129 $result = JSMin::minify( $data );
130 break;
131 case 'minify-css':
132 $result = CSSMin::minify( $data );
133 break;
134 case 'flip-css':
135 $result = CSSJanus::transform( $data, true, false );
136 break;
137 default:
138 // Don't cache anything, just pass right through
139 wfProfileOut( __METHOD__ );
140 return $data;
141 }
142 } catch ( Exception $exception ) {
143 throw new MWException( 'Filter threw an exception: ' . $exception->getMessage() );
144 }
145
146 // Save to memcached
147 $wgMemc->set( $key, $result );
148
149 wfProfileOut( __METHOD__ );
150 return $result;
151 }
152
153 /* Methods */
154
155 /**
156 * Registers core modules and runs registration hooks
157 */
158 public function __construct() {
159 global $IP;
160
161 wfProfileIn( __METHOD__ );
162
163 // Register core modules
164 $this->register( include( "$IP/resources/Resources.php" ) );
165 // Register extension modules
166 wfRunHooks( 'ResourceLoaderRegisterModules', array( &$this ) );
167
168 wfProfileOut( __METHOD__ );
169 }
170
171 /**
172 * Registers a module with the ResourceLoader system.
173 *
174 * Note that registering the same object under multiple names is not supported
175 * and may silently fail in all kinds of interesting ways.
176 *
177 * @param $name Mixed: string of name of module or array of name/object pairs
178 * @param $object ResourceLoaderModule: module object (optional when using
179 * multiple-registration calling style)
180 * @return Boolean: false if there were any errors, in which case one or more
181 * modules were not registered
182 *
183 * @todo We need much more clever error reporting, not just in detailing what
184 * happened, but in bringing errors to the client in a way that they can
185 * easily see them if they want to, such as by using FireBug
186 */
187 public function register( $name, ResourceLoaderModule $object = null ) {
188 wfProfileIn( __METHOD__ );
189
190 // Allow multiple modules to be registered in one call
191 if ( is_array( $name ) && !isset( $object ) ) {
192 foreach ( $name as $key => $value ) {
193 $this->register( $key, $value );
194 }
195
196 wfProfileOut( __METHOD__ );
197 return;
198 }
199
200 // Disallow duplicate registrations
201 if ( isset( $this->modules[$name] ) ) {
202 // A module has already been registered by this name
203 throw new MWException( 'Another module has already been registered as ' . $name );
204 }
205
206 // Validate the input (type hinting lets null through)
207 if ( !( $object instanceof ResourceLoaderModule ) ) {
208 throw new MWException( 'Invalid ResourceLoader module error. Instances of ResourceLoaderModule expected.' );
209 }
210
211 // Attach module
212 $this->modules[$name] = $object;
213 $object->setName( $name );
214
215 wfProfileOut( __METHOD__ );
216 }
217
218 /**
219 * Gets a map of all modules and their options
220 *
221 * @return Array: array( modulename => ResourceLoaderModule )
222 */
223 public function getModules() {
224 return $this->modules;
225 }
226
227 /**
228 * Get the ResourceLoaderModule object for a given module name
229 *
230 * @param $name String: module name
231 * @return mixed ResourceLoaderModule or null if not registered
232 */
233 public function getModule( $name ) {
234 return isset( $this->modules[$name] ) ? $this->modules[$name] : null;
235 }
236
237 /**
238 * Outputs a response to a resource load-request, including a content-type header
239 *
240 * @param $context ResourceLoaderContext object
241 */
242 public function respond( ResourceLoaderContext $context ) {
243 global $wgResourceLoaderMaxage, $wgCacheEpoch;
244
245 wfProfileIn( __METHOD__ );
246
247 // Split requested modules into two groups, modules and missing
248 $modules = array();
249 $missing = array();
250
251 foreach ( $context->getModules() as $name ) {
252 if ( isset( $this->modules[$name] ) ) {
253 $modules[$name] = $this->modules[$name];
254 } else {
255 $missing[] = $name;
256 }
257 }
258
259 // If a version wasn't specified we need a shorter expiry time for updates to
260 // propagate to clients quickly
261 if ( is_null( $context->getVersion() ) ) {
262 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
263 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
264 }
265 // If a version was specified we can use a longer expiry time since changing
266 // version numbers causes cache misses
267 else {
268 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
269 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
270 }
271
272 // Preload information needed to the mtime calculation below
273 $this->preloadModuleInfo( array_keys( $modules ), $context );
274
275 // To send Last-Modified and support If-Modified-Since, we need to detect
276 // the last modified time
277 wfProfileIn( __METHOD__.'-getModifiedTime' );
278 $mtime = $wgCacheEpoch;
279 foreach ( $modules as $module ) {
280 // Bypass squid cache if the request includes any private modules
281 if ( $module->getGroup() === 'private' ) {
282 $smaxage = 0;
283 }
284 // Calculate maximum modified time
285 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
286 }
287 wfProfileOut( __METHOD__.'-getModifiedTime' );
288
289 header( 'Content-Type: ' . ( $context->getOnly() === 'styles' ? 'text/css' : 'text/javascript' ) );
290 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $mtime ) );
291 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
292 header( 'Expires: ' . wfTimestamp( TS_RFC2822, min( $maxage, $smaxage ) + time() ) );
293
294 // If there's an If-Modified-Since header, respond with a 304 appropriately
295 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
296 if ( $ims !== false && $mtime <= wfTimestamp( TS_UNIX, $ims ) ) {
297 header( 'HTTP/1.0 304 Not Modified' );
298 header( 'Status: 304 Not Modified' );
299 wfProfileOut( __METHOD__ );
300 return;
301 }
302
303 echo $this->makeModuleResponse( $context, $modules, $missing );
304
305 wfProfileOut( __METHOD__ );
306 }
307
308 public function makeModuleResponse( ResourceLoaderContext $context, array $modules, $missing = null ) {
309 // Pre-fetch blobs
310 $blobs = $context->shouldIncludeMessages() ?
311 MessageBlobStore::get( $this, $modules, $context->getLanguage() ) : array();
312
313 // Generate output
314 $out = '';
315 foreach ( $modules as $name => $module ) {
316 wfProfileIn( __METHOD__ . '-' . $name );
317
318 // Scripts
319 $scripts = '';
320 if ( $context->shouldIncludeScripts() ) {
321 $scripts .= $module->getScript( $context ) . "\n";
322 }
323
324 // Styles
325 $styles = array();
326 if (
327 $context->shouldIncludeStyles() &&
328 ( count( $styles = $module->getStyles( $context ) ) )
329 ) {
330 // Flip CSS on a per-module basis
331 if ( $this->modules[$name]->getFlip( $context ) ) {
332 foreach ( $styles as $media => $style ) {
333 $styles[$media] = $this->filter( 'flip-css', $style );
334 }
335 }
336 }
337
338 // Messages
339 $messages = isset( $blobs[$name] ) ? $blobs[$name] : '{}';
340
341 // Append output
342 switch ( $context->getOnly() ) {
343 case 'scripts':
344 $out .= $scripts;
345 break;
346 case 'styles':
347 $out .= self::makeCombinedStyles( $styles );
348 break;
349 case 'messages':
350 $out .= self::makeMessageSetScript( $messages );
351 break;
352 default:
353 // Minify CSS before embedding in mediaWiki.loader.implement call (unless in debug mode)
354 if ( !$context->getDebug() ) {
355 foreach ( $styles as $media => $style ) {
356 $styles[$media] = $this->filter( 'minify-css', $style );
357 }
358 }
359 $out .= self::makeLoaderImplementScript( $name, $scripts, $styles, $messages );
360 break;
361 }
362
363 wfProfileOut( __METHOD__ . '-' . $name );
364 }
365
366 // Update module states
367 if ( $context->shouldIncludeScripts() ) {
368 // Set the state of modules loaded as only scripts to ready
369 if ( count( $modules ) && $context->getOnly() === 'scripts' && !isset( $modules['startup'] ) ) {
370 $out .= self::makeLoaderStateScript( array_fill_keys( array_keys( $modules ), 'ready' ) );
371 }
372 // Set the state of modules which were requested but unavailable as missing
373 if ( is_array( $missing ) && count( $missing ) ) {
374 $out .= self::makeLoaderStateScript( array_fill_keys( $missing, 'missing' ) );
375 }
376 }
377
378 if ( $context->getDebug() ) {
379 return $out;
380 } else {
381 if ( $context->getOnly() === 'styles' ) {
382 return $this->filter( 'minify-css', $out );
383 } else {
384 return $this->filter( 'minify-js', $out );
385 }
386 }
387 }
388
389 /* Static Methods */
390
391 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
392 if ( is_array( $scripts ) ) {
393 $scripts = implode( $scripts, "\n" );
394 }
395 if ( is_array( $styles ) ) {
396 $styles = count( $styles ) ? FormatJson::encode( $styles ) : 'null';
397 }
398 if ( is_array( $messages ) ) {
399 $messages = count( $messages ) ? FormatJson::encode( $messages ) : 'null';
400 }
401 return "mediaWiki.loader.implement( '$name', function() {{$scripts}},\n$styles,\n$messages );\n";
402 }
403
404 public static function makeMessageSetScript( $messages ) {
405 if ( is_array( $messages ) ) {
406 $messages = count( $messages ) ? FormatJson::encode( $messages ) : 'null';
407 }
408 return "mediaWiki.msg.set( $messages );\n";
409 }
410
411 public static function makeCombinedStyles( array $styles ) {
412 $out = '';
413 foreach ( $styles as $media => $style ) {
414 $out .= "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "\n}\n";
415 }
416 return $out;
417 }
418
419 public static function makeLoaderStateScript( $name, $state = null ) {
420 if ( is_array( $name ) ) {
421 $statuses = FormatJson::encode( $name );
422 return "mediaWiki.loader.state( $statuses );\n";
423 } else {
424 $name = Xml::escapeJsString( $name );
425 $state = Xml::escapeJsString( $state );
426 return "mediaWiki.loader.state( '$name', '$state' );\n";
427 }
428 }
429
430 public static function makeCustomLoaderScript( $name, $version, $dependencies, $group, $script ) {
431 $name = Xml::escapeJsString( $name );
432 $version = (int) $version > 1 ? (int) $version : 1;
433 if ( is_array( $dependencies ) ) {
434 $dependencies = FormatJson::encode( $dependencies );
435 } else if ( is_string( $dependencies ) ) {
436 $dependencies = "'" . Xml::escapeJsString( $dependencies ) . "'";
437 } else {
438 $dependencies = 'null';
439 }
440 if ( is_string( $group ) ) {
441 $group = "'" . Xml::escapeJsString( $group ) . "'";
442 } else {
443 $group = 'null';
444 }
445 $script = str_replace( "\n", "\n\t", trim( $script ) );
446 return "( function( name, version, dependencies, group ) {\n\t$script\n} )" .
447 "( '$name', $version, $dependencies, $group );\n";
448 }
449
450 public static function makeLoaderRegisterScript( $name, $version = null, $dependencies = null, $group = null ) {
451 if ( is_array( $name ) ) {
452 $registrations = FormatJson::encode( $name );
453 return "mediaWiki.loader.register( $registrations );\n";
454 } else {
455 $name = Xml::escapeJsString( $name );
456 $version = (int) $version > 1 ? (int) $version : 1;
457 if ( is_array( $dependencies ) ) {
458 $dependencies = FormatJson::encode( $dependencies );
459 } else if ( is_string( $dependencies ) ) {
460 $dependencies = "'" . Xml::escapeJsString( $dependencies ) . "'";
461 } else {
462 $dependencies = 'null';
463 }
464 if ( is_string( $group ) ) {
465 $group = "'" . Xml::escapeJsString( $group ) . "'";
466 } else {
467 $group = 'null';
468 }
469 return "mediaWiki.loader.register( '$name', $version, $dependencies, $group );\n";
470 }
471 }
472
473 public static function makeLoaderConditionalScript( $script ) {
474 $script = str_replace( "\n", "\n\t", trim( $script ) );
475 return "if ( window.mediaWiki ) {\n\t$script\n}\n";
476 }
477
478 public static function makeConfigSetScript( array $configuration ) {
479 $configuration = FormatJson::encode( $configuration );
480 return "mediaWiki.config.set( $configuration );\n";
481 }
482 }