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