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