Moved CSS flipping to occur inside a module - this resolves a bug which occurs when...
[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 /** Array: List of module name/ResourceLoaderModule object pairs */
34 protected $modules = array();
35 /** Associative array mapping module name to info associative array */
36 protected $moduleInfos = array();
37
38 /* Protected Methods */
39
40 /**
41 * Loads information stored in the database about modules.
42 *
43 * This method grabs modules dependencies from the database and updates modules
44 * objects.
45 *
46 * This is not inside the module code because it is much faster to
47 * request all of the information at once than it is to have each module
48 * requests its own information. This sacrifice of modularity yields a substantial
49 * performance improvement.
50 *
51 * @param $modules Array: List of module names to preload information for
52 * @param $context ResourceLoaderContext: Context to load the information within
53 */
54 protected function preloadModuleInfo( array $modules, ResourceLoaderContext $context ) {
55 if ( !count( $modules ) ) {
56 return; // or else Database*::select() will explode, plus it's cheaper!
57 }
58 $dbr = wfGetDB( DB_SLAVE );
59 $skin = $context->getSkin();
60 $lang = $context->getLanguage();
61
62 // Get file dependency information
63 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
64 'md_module' => $modules,
65 'md_skin' => $context->getSkin()
66 ), __METHOD__
67 );
68
69 // Set modules' dependecies
70 $modulesWithDeps = array();
71 foreach ( $res as $row ) {
72 $this->getModule( $row->md_module )->setFileDependencies( $skin,
73 FormatJson::decode( $row->md_deps, true )
74 );
75 $modulesWithDeps[] = $row->md_module;
76 }
77
78 // Register the absence of a dependency row too
79 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
80 $this->getModule( $name )->setFileDependencies( $skin, array() );
81 }
82
83 // Get message blob mtimes. Only do this for modules with messages
84 $modulesWithMessages = array();
85 $modulesWithoutMessages = array();
86 foreach ( $modules as $name ) {
87 if ( count( $this->getModule( $name )->getMessages() ) ) {
88 $modulesWithMessages[] = $name;
89 } else {
90 $modulesWithoutMessages[] = $name;
91 }
92 }
93 if ( count( $modulesWithMessages ) ) {
94 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
95 'mr_resource' => $modulesWithMessages,
96 'mr_lang' => $lang
97 ), __METHOD__
98 );
99 foreach ( $res as $row ) {
100 $this->getModule( $row->mr_resource )->setMsgBlobMtime( $lang, $row->mr_timestamp );
101 }
102 }
103 foreach ( $modulesWithoutMessages as $name ) {
104 $this->getModule( $name )->setMsgBlobMtime( $lang, 0 );
105 }
106 }
107
108 /**
109 * Runs JavaScript or CSS data through a filter, caching the filtered result for future calls.
110 *
111 * Available filters are:
112 * - minify-js \see JSMin::minify
113 * - minify-css \see CSSMin::minify
114 *
115 * If $data is empty, only contains whitespace or the filter was unknown,
116 * $data is returned unmodified.
117 *
118 * @param $filter String: Name of filter to run
119 * @param $data String: Text to filter, such as JavaScript or CSS text
120 * @return String: Filtered data
121 */
122 protected function filter( $filter, $data ) {
123 wfProfileIn( __METHOD__ );
124
125 // For empty/whitespace-only data or for unknown filters, don't perform
126 // any caching or processing
127 if ( trim( $data ) === ''
128 || !in_array( $filter, array( 'minify-js', 'minify-css' ) ) )
129 {
130 wfProfileOut( __METHOD__ );
131 return $data;
132 }
133
134 // Try for cache hit
135 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
136 $key = wfMemcKey( 'resourceloader', 'filter', $filter, md5( $data ) );
137 $cache = wfGetCache( CACHE_ANYTHING );
138 $cacheEntry = $cache->get( $key );
139 if ( is_string( $cacheEntry ) ) {
140 wfProfileOut( __METHOD__ );
141 return $cacheEntry;
142 }
143
144 // Run the filter - we've already verified one of these will work
145 try {
146 switch ( $filter ) {
147 case 'minify-js':
148 $result = JSMin::minify( $data );
149 break;
150 case 'minify-css':
151 $result = CSSMin::minify( $data );
152 break;
153 }
154 } catch ( Exception $exception ) {
155 throw new MWException( 'ResourceLoader filter error. ' .
156 'Exception was thrown: ' . $exception->getMessage() );
157 }
158
159 // Save filtered text to Memcached
160 $cache->set( $key, $result );
161
162 wfProfileOut( __METHOD__ );
163
164 return $result;
165 }
166
167 /* Methods */
168
169 /**
170 * Registers core modules and runs registration hooks.
171 */
172 public function __construct() {
173 global $IP, $wgResourceModules;
174
175 wfProfileIn( __METHOD__ );
176
177 // Register core modules
178 $this->register( include( "$IP/resources/Resources.php" ) );
179 // Register extension modules
180 wfRunHooks( 'ResourceLoaderRegisterModules', array( &$this ) );
181 $this->register( $wgResourceModules );
182
183 wfProfileOut( __METHOD__ );
184 }
185
186 /**
187 * Registers a module with the ResourceLoader system.
188 *
189 * @param $name Mixed: Name of module as a string or List of name/object pairs as an array
190 * @param $info Module info array. For backwards compatibility with 1.17alpha,
191 * this may also be a ResourceLoaderModule 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 registered
195 * @return Boolean: False if there were any errors, in which case one or more modules were not
196 * registered
197 */
198 public function register( $name, $info = null ) {
199 wfProfileIn( __METHOD__ );
200
201 // Allow multiple modules to be registered in one call
202 if ( is_array( $name ) ) {
203 foreach ( $name as $key => $value ) {
204 $this->register( $key, $value );
205 }
206 return;
207 }
208
209 // Disallow duplicate registrations
210 if ( isset( $this->moduleInfos[$name] ) ) {
211 // A module has already been registered by this name
212 throw new MWException(
213 'ResourceLoader duplicate registration error. ' .
214 'Another module has already been registered as ' . $name
215 );
216 }
217
218 // Attach module
219 if ( is_object( $info ) ) {
220 // Old calling convention
221 // Validate the input
222 if ( !( $info instanceof ResourceLoaderModule ) ) {
223 throw new MWException( 'ResourceLoader invalid module error. ' .
224 'Instances of ResourceLoaderModule expected.' );
225 }
226
227 $this->moduleInfos[$name] = array( 'object' => $info );
228 $info->setName( $name );
229 $this->modules[$name] = $info;
230 } else {
231 // New calling convention
232 $this->moduleInfos[$name] = $info;
233 }
234
235 wfProfileOut( __METHOD__ );
236 }
237
238 /**
239 * Get a list of module names
240 *
241 * @return Array: List of module names
242 */
243 public function getModuleNames() {
244 return array_keys( $this->moduleInfos );
245 }
246
247 /**
248 * Get the ResourceLoaderModule object for a given module name.
249 *
250 * @param $name String: Module name
251 * @return Mixed: ResourceLoaderModule if module has been registered, null otherwise
252 */
253 public function getModule( $name ) {
254 if ( !isset( $this->modules[$name] ) ) {
255 if ( !isset( $this->moduleInfos[$name] ) ) {
256 // No such module
257 return null;
258 }
259 // Construct the requested object
260 $info = $this->moduleInfos[$name];
261 if ( isset( $info['object'] ) ) {
262 // Object given in info array
263 $object = $info['object'];
264 } else {
265 if ( !isset( $info['class'] ) ) {
266 $class = 'ResourceLoaderFileModule';
267 } else {
268 $class = $info['class'];
269 }
270 $object = new $class( $info );
271 }
272 $object->setName( $name );
273 $this->modules[$name] = $object;
274 }
275
276 return $this->modules[$name];
277 }
278
279 /**
280 * Outputs a response to a resource load-request, including a content-type header.
281 *
282 * @param $context ResourceLoaderContext: Context in which a response should be formed
283 */
284 public function respond( ResourceLoaderContext $context ) {
285 global $wgResourceLoaderMaxage, $wgCacheEpoch;
286
287 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
288 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
289 // is used: ob_clean() will clear the GZIP header in that case and it won't come
290 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
291 // the whole thing in our own output buffer to be sure the active buffer
292 // doesn't use ob_gzhandler.
293 // See http://bugs.php.net/bug.php?id=36514
294 ob_start();
295
296 wfProfileIn( __METHOD__ );
297
298 // Split requested modules into two groups, modules and missing
299 $modules = array();
300 $missing = array();
301 foreach ( $context->getModules() as $name ) {
302 if ( isset( $this->moduleInfos[$name] ) ) {
303 $modules[$name] = $this->getModule( $name );
304 } else {
305 $missing[] = $name;
306 }
307 }
308
309 // If a version wasn't specified we need a shorter expiry time for updates
310 // to propagate to clients quickly
311 if ( is_null( $context->getVersion() ) ) {
312 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
313 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
314 }
315 // If a version was specified we can use a longer expiry time since changing
316 // version numbers causes cache misses
317 else {
318 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
319 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
320 }
321
322 // Preload information needed to the mtime calculation below
323 $this->preloadModuleInfo( array_keys( $modules ), $context );
324
325 wfProfileIn( __METHOD__.'-getModifiedTime' );
326
327 // To send Last-Modified and support If-Modified-Since, we need to detect
328 // the last modified time
329 $mtime = wfTimestamp( TS_UNIX, $wgCacheEpoch );
330 foreach ( $modules as $module ) {
331 // Bypass squid cache if the request includes any private modules
332 if ( $module->getGroup() === 'private' ) {
333 $smaxage = 0;
334 }
335 // Calculate maximum modified time
336 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
337 }
338
339 wfProfileOut( __METHOD__.'-getModifiedTime' );
340
341 if ( $context->getOnly() === 'styles' ) {
342 header( 'Content-Type: text/css' );
343 } else {
344 header( 'Content-Type: text/javascript' );
345 }
346 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $mtime ) );
347 if ( $context->getDebug() ) {
348 header( 'Cache-Control: must-revalidate' );
349 } else {
350 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
351 header( 'Expires: ' . wfTimestamp( TS_RFC2822, min( $maxage, $smaxage ) + time() ) );
352 }
353
354 // If there's an If-Modified-Since header, respond with a 304 appropriately
355 // Some clients send "timestamp;length=123". Strip the part after the first ';'
356 // so we get a valid timestamp.
357 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
358 if ( $ims !== false ) {
359 $imsTS = strtok( $ims, ';' );
360 if ( $mtime <= wfTimestamp( TS_UNIX, $imsTS ) ) {
361 // There's another bug in ob_gzhandler (see also the comment at
362 // the top of this function) that causes it to gzip even empty
363 // responses, meaning it's impossible to produce a truly empty
364 // response (because the gzip header is always there). This is
365 // a problem because 304 responses have to be completely empty
366 // per the HTTP spec, and Firefox behaves buggily when they're not.
367 // See also http://bugs.php.net/bug.php?id=51579
368 // To work around this, we tear down all output buffering before
369 // sending the 304.
370 while ( ob_get_level() > 0 ) {
371 ob_end_clean();
372 }
373
374 header( 'HTTP/1.0 304 Not Modified' );
375 header( 'Status: 304 Not Modified' );
376 wfProfileOut( __METHOD__ );
377 return;
378 }
379 }
380
381 // Generate a response
382 $response = $this->makeModuleResponse( $context, $modules, $missing );
383
384 // Capture any PHP warnings from the output buffer and append them to the
385 // response in a comment if we're in debug mode.
386 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
387 $response .= "/*\n$warnings\n*/";
388 }
389
390 // Remove the output buffer and output the response
391 ob_end_clean();
392 echo $response;
393
394 wfProfileOut( __METHOD__ );
395 }
396
397 /**
398 * Generates code for a response
399 *
400 * @param $context ResourceLoaderContext: Context in which to generate a response
401 * @param $modules Array: List of module objects keyed by module name
402 * @param $missing Array: List of unavailable modules (optional)
403 * @return String: Response data
404 */
405 public function makeModuleResponse( ResourceLoaderContext $context,
406 array $modules, $missing = array() )
407 {
408 if ( $modules === array() && $missing === array() ) {
409 return '/* No modules requested. Max made me put this here */';
410 }
411
412 // Pre-fetch blobs
413 if ( $context->shouldIncludeMessages() ) {
414 $blobs = MessageBlobStore::get( $this, $modules, $context->getLanguage() );
415 } else {
416 $blobs = array();
417 }
418
419 // Generate output
420 $out = '';
421 foreach ( $modules as $name => $module ) {
422
423 wfProfileIn( __METHOD__ . '-' . $name );
424
425 // Scripts
426 $scripts = '';
427 if ( $context->shouldIncludeScripts() ) {
428 $scripts .= $module->getScript( $context ) . "\n";
429 }
430
431 // Styles
432 $styles = array();
433 if ( $context->shouldIncludeStyles() ) {
434 $styles = $module->getStyles( $context );
435 }
436
437 // Messages
438 $messagesBlob = isset( $blobs[$name] ) ? $blobs[$name] : '{}';
439
440 // Append output
441 switch ( $context->getOnly() ) {
442 case 'scripts':
443 $out .= $scripts;
444 break;
445 case 'styles':
446 $out .= self::makeCombinedStyles( $styles );
447 break;
448 case 'messages':
449 $out .= self::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
450 break;
451 default:
452 // Minify CSS before embedding in mediaWiki.loader.implement call
453 // (unless in debug mode)
454 if ( !$context->getDebug() ) {
455 foreach ( $styles as $media => $style ) {
456 $styles[$media] = $this->filter( 'minify-css', $style );
457 }
458 }
459 $out .= self::makeLoaderImplementScript( $name, $scripts, $styles,
460 new XmlJsCode( $messagesBlob ) );
461 break;
462 }
463
464 wfProfileOut( __METHOD__ . '-' . $name );
465 }
466
467 // Update module states
468 if ( $context->shouldIncludeScripts() ) {
469 // Set the state of modules loaded as only scripts to ready
470 if ( count( $modules ) && $context->getOnly() === 'scripts'
471 && !isset( $modules['startup'] ) )
472 {
473 $out .= self::makeLoaderStateScript(
474 array_fill_keys( array_keys( $modules ), 'ready' ) );
475 }
476 // Set the state of modules which were requested but unavailable as missing
477 if ( is_array( $missing ) && count( $missing ) ) {
478 $out .= self::makeLoaderStateScript( array_fill_keys( $missing, 'missing' ) );
479 }
480 }
481
482 if ( $context->getDebug() ) {
483 return $out;
484 } else {
485 if ( $context->getOnly() === 'styles' ) {
486 return $this->filter( 'minify-css', $out );
487 } else {
488 return $this->filter( 'minify-js', $out );
489 }
490 }
491 }
492
493 /* Static Methods */
494
495 /**
496 * Returns JS code to call to mediaWiki.loader.implement for a module with
497 * given properties.
498 *
499 * @param $name Module name
500 * @param $scripts Array: List of JavaScript code snippets to be executed after the
501 * module is loaded
502 * @param $styles Array: List of CSS strings keyed by media type
503 * @param $messages Mixed: List of messages associated with this module. May either be an
504 * associative array mapping message key to value, or a JSON-encoded message blob containing
505 * the same data, wrapped in an XmlJsCode object.
506 */
507 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
508 if ( is_array( $scripts ) ) {
509 $scripts = implode( $scripts, "\n" );
510 }
511 return Xml::encodeJsCall(
512 'mediaWiki.loader.implement',
513 array(
514 $name,
515 new XmlJsCode( "function() {{$scripts}}" ),
516 (object)$styles,
517 (object)$messages
518 ) );
519 }
520
521 /**
522 * Returns JS code which, when called, will register a given list of messages.
523 *
524 * @param $messages Mixed: Either an associative array mapping message key to value, or a
525 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
526 */
527 public static function makeMessageSetScript( $messages ) {
528 return Xml::encodeJsCall( 'mediaWiki.messages.set', array( (object)$messages ) );
529 }
530
531 /**
532 * Combines an associative array mapping media type to CSS into a
533 * single stylesheet with @media blocks.
534 *
535 * @param $styles Array: List of CSS strings keyed by media type
536 */
537 public static function makeCombinedStyles( array $styles ) {
538 $out = '';
539 foreach ( $styles as $media => $style ) {
540 $out .= "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "\n}\n";
541 }
542 return $out;
543 }
544
545 /**
546 * Returns a JS call to mediaWiki.loader.state, which sets the state of a
547 * module or modules to a given value. Has two calling conventions:
548 *
549 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
550 * Set the state of a single module called $name to $state
551 *
552 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
553 * Set the state of modules with the given names to the given states
554 */
555 public static function makeLoaderStateScript( $name, $state = null ) {
556 if ( is_array( $name ) ) {
557 return Xml::encodeJsCall( 'mediaWiki.loader.state', array( $name ) );
558 } else {
559 return Xml::encodeJsCall( 'mediaWiki.loader.state', array( $name, $state ) );
560 }
561 }
562
563 /**
564 * Returns JS code which calls the script given by $script. The script will
565 * be called with local variables name, version, dependencies and group,
566 * which will have values corresponding to $name, $version, $dependencies
567 * and $group as supplied.
568 *
569 * @param $name String: Module name
570 * @param $version Integer: Module version number as a timestamp
571 * @param $dependencies Array: List of module names on which this module depends
572 * @param $group String: Group which the module is in.
573 * @param $script String: JavaScript code
574 */
575 public static function makeCustomLoaderScript( $name, $version, $dependencies, $group, $script ) {
576 $script = str_replace( "\n", "\n\t", trim( $script ) );
577 return Xml::encodeJsCall(
578 "( function( name, version, dependencies, group ) {\n\t$script\n} )",
579 array( $name, $version, $dependencies, $group ) );
580 }
581
582 /**
583 * Returns JS code which calls mediaWiki.loader.register with the given
584 * parameters. Has three calling conventions:
585 *
586 * - ResourceLoader::makeLoaderRegisterScript( $name, $version, $dependencies, $group ):
587 * Register a single module.
588 *
589 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
590 * Register modules with the given names.
591 *
592 * - ResourceLoader::makeLoaderRegisterScript( array(
593 * array( $name1, $version1, $dependencies1, $group1 ),
594 * array( $name2, $version2, $dependencies1, $group2 ),
595 * ...
596 * ) ):
597 * Registers modules with the given names and parameters.
598 *
599 * @param $name String: Module name
600 * @param $version Integer: Module version number as a timestamp
601 * @param $dependencies Array: List of module names on which this module depends
602 * @param $group String: group which the module is in.
603 */
604 public static function makeLoaderRegisterScript( $name, $version = null,
605 $dependencies = null, $group = null )
606 {
607 if ( is_array( $name ) ) {
608 return Xml::encodeJsCall( 'mediaWiki.loader.register', array( $name ) );
609 } else {
610 $version = (int) $version > 1 ? (int) $version : 1;
611 return Xml::encodeJsCall( 'mediaWiki.loader.register',
612 array( $name, $version, $dependencies, $group ) );
613 }
614 }
615
616 /**
617 * Returns JS code which runs given JS code if the client-side framework is
618 * present.
619 *
620 * @param $script String: JavaScript code
621 */
622 public static function makeLoaderConditionalScript( $script ) {
623 $script = str_replace( "\n", "\n\t", trim( $script ) );
624 return "if ( window.mediaWiki ) {\n\t$script\n}\n";
625 }
626
627 /**
628 * Returns JS code which will set the MediaWiki configuration array to
629 * the given value.
630 *
631 * @param $configuration Array: List of configuration values keyed by variable name
632 */
633 public static function makeConfigSetScript( array $configuration ) {
634 return Xml::encodeJsCall( 'mediaWiki.config.set', array( $configuration ) );
635 }
636
637 /**
638 * Determine whether debug mode was requested
639 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
640 * @return bool
641 */
642 public static function inDebugMode() {
643 global $wgRequest, $wgResourceLoaderDebug;
644 static $retval = null;
645 if ( !is_null( $retval ) )
646 return $retval;
647 return $retval = $wgRequest->getFuzzyBool( 'debug',
648 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug ) );
649 }
650 }