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