Use wfGetCache( CACHE_ANYTHING ) instead of $wgMemc to store the result of ResourceLo...
[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
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 wfProfileIn( __METHOD__ );
123
124 // For empty/whitespace-only data or for unknown filters, don't perform
125 // any caching or processing
126 if ( trim( $data ) === ''
127 || !in_array( $filter, array( 'minify-js', 'minify-css', 'flip-css' ) ) )
128 {
129 wfProfileOut( __METHOD__ );
130 return $data;
131 }
132
133 // Try for cache hit
134 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
135 $key = wfMemcKey( 'resourceloader', 'filter', $filter, md5( $data ) );
136 $cache = wfGetCache( CACHE_ANYTHING );
137 $cacheEntry = $cache->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 $cache->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: Name of module as a string or List of name/object pairs as an array
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 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, ResourceLoaderModule $object = null ) {
199
200 wfProfileIn( __METHOD__ );
201
202 // Allow multiple modules to be registered in one call
203 if ( is_array( $name ) && !isset( $object ) ) {
204 foreach ( $name as $key => $value ) {
205 $this->register( $key, $value );
206 }
207
208 wfProfileOut( __METHOD__ );
209
210 return;
211 }
212
213 // Disallow duplicate registrations
214 if ( isset( $this->modules[$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 // Validate the input (type hinting lets null through)
223 if ( !( $object instanceof ResourceLoaderModule ) ) {
224 throw new MWException( 'ResourceLoader invalid module error. ' .
225 'Instances of ResourceLoaderModule expected.' );
226 }
227
228 // Attach module
229 $this->modules[$name] = $object;
230 $object->setName( $name );
231
232 wfProfileOut( __METHOD__ );
233 }
234
235 /**
236 * Gets a map of all modules and their options
237 *
238 * @return Array: List of modules keyed by module name
239 */
240 public function getModules() {
241 return $this->modules;
242 }
243
244 /**
245 * Get the ResourceLoaderModule object for a given module name.
246 *
247 * @param $name String: Module name
248 * @return Mixed: ResourceLoaderModule if module has been registered, null otherwise
249 */
250 public function getModule( $name ) {
251 return isset( $this->modules[$name] ) ? $this->modules[$name] : null;
252 }
253
254 /**
255 * Outputs a response to a resource load-request, including a content-type header.
256 *
257 * @param $context ResourceLoaderContext: Context in which a response should be formed
258 */
259 public function respond( ResourceLoaderContext $context ) {
260 global $wgResourceLoaderMaxage, $wgCacheEpoch;
261
262 wfProfileIn( __METHOD__ );
263
264 // Split requested modules into two groups, modules and missing
265 $modules = array();
266 $missing = array();
267 foreach ( $context->getModules() as $name ) {
268 if ( isset( $this->modules[$name] ) ) {
269 $modules[$name] = $this->modules[$name];
270 } else {
271 $missing[] = $name;
272 }
273 }
274
275 // If a version wasn't specified we need a shorter expiry time for updates
276 // to propagate to clients quickly
277 if ( is_null( $context->getVersion() ) ) {
278 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
279 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
280 }
281 // If a version was specified we can use a longer expiry time since changing
282 // version numbers causes cache misses
283 else {
284 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
285 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
286 }
287
288 // Preload information needed to the mtime calculation below
289 $this->preloadModuleInfo( array_keys( $modules ), $context );
290
291 wfProfileIn( __METHOD__.'-getModifiedTime' );
292
293 // To send Last-Modified and support If-Modified-Since, we need to detect
294 // the last modified time
295 $mtime = wfTimestamp( TS_UNIX, $wgCacheEpoch );
296 foreach ( $modules as $module ) {
297 // Bypass squid cache if the request includes any private modules
298 if ( $module->getGroup() === 'private' ) {
299 $smaxage = 0;
300 }
301 // Calculate maximum modified time
302 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
303 }
304
305 wfProfileOut( __METHOD__.'-getModifiedTime' );
306
307 if ( $context->getOnly() === 'styles' ) {
308 header( 'Content-Type: text/css' );
309 } else {
310 header( 'Content-Type: text/javascript' );
311 }
312 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $mtime ) );
313 if ( $context->getDebug() ) {
314 header( 'Cache-Control: must-revalidate' );
315 } else {
316 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
317 header( 'Expires: ' . wfTimestamp( TS_RFC2822, min( $maxage, $smaxage ) + time() ) );
318 }
319
320 // If there's an If-Modified-Since header, respond with a 304 appropriately
321 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
322 if ( $ims !== false && $mtime <= wfTimestamp( TS_UNIX, $ims ) ) {
323 header( 'HTTP/1.0 304 Not Modified' );
324 header( 'Status: 304 Not Modified' );
325 wfProfileOut( __METHOD__ );
326 return;
327 }
328
329 // Generate a response
330 $response = $this->makeModuleResponse( $context, $modules, $missing );
331
332 // Tack on PHP warnings as a comment in debug mode
333 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
334 $response .= "/*\n$warnings\n*/";
335 }
336
337 // Clear any warnings from the buffer
338 ob_clean();
339 echo $response;
340
341 wfProfileOut( __METHOD__ );
342 }
343
344 /**
345 * Generates code for a response
346 *
347 * @param $context ResourceLoaderContext: Context in which to generate a response
348 * @param $modules Array: List of module objects keyed by module name
349 * @param $missing Array: List of unavailable modules (optional)
350 * @return String: Response data
351 */
352 public function makeModuleResponse( ResourceLoaderContext $context,
353 array $modules, $missing = array() )
354 {
355 // Pre-fetch blobs
356 if ( $context->shouldIncludeMessages() ) {
357 $blobs = MessageBlobStore::get( $this, $modules, $context->getLanguage() );
358 } else {
359 $blobs = array();
360 }
361
362 // Generate output
363 $out = '';
364 foreach ( $modules as $name => $module ) {
365
366 wfProfileIn( __METHOD__ . '-' . $name );
367
368 // Scripts
369 $scripts = '';
370 if ( $context->shouldIncludeScripts() ) {
371 $scripts .= $module->getScript( $context ) . "\n";
372 }
373
374 // Styles
375 $styles = array();
376 if ( $context->shouldIncludeStyles() ) {
377 $styles = $module->getStyles( $context );
378 // Flip CSS on a per-module basis
379 if ( $styles && $this->modules[$name]->getFlip( $context ) ) {
380 foreach ( $styles as $media => $style ) {
381 $styles[$media] = $this->filter( 'flip-css', $style );
382 }
383 }
384 }
385
386 // Messages
387 $messagesBlob = isset( $blobs[$name] ) ? $blobs[$name] : array();
388
389 // Append output
390 switch ( $context->getOnly() ) {
391 case 'scripts':
392 $out .= $scripts;
393 break;
394 case 'styles':
395 $out .= self::makeCombinedStyles( $styles );
396 break;
397 case 'messages':
398 $out .= self::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
399 break;
400 default:
401 // Minify CSS before embedding in mediaWiki.loader.implement call
402 // (unless in debug mode)
403 if ( !$context->getDebug() ) {
404 foreach ( $styles as $media => $style ) {
405 $styles[$media] = $this->filter( 'minify-css', $style );
406 }
407 }
408 $out .= self::makeLoaderImplementScript( $name, $scripts, $styles,
409 new XmlJsCode( $messagesBlob ) );
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 /**
445 * Returns JS code to call to mediaWiki.loader.implement for a module with
446 * given properties.
447 *
448 * @param $name Module name
449 * @param $scripts Array: List of JavaScript code snippets to be executed after the
450 * module is loaded
451 * @param $styles Array: List of CSS strings keyed by media type
452 * @param $messages Mixed: List of messages associated with this module. May either be an
453 * associative array mapping message key to value, or a JSON-encoded message blob containing
454 * the same data, wrapped in an XmlJsCode object.
455 */
456 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
457 if ( is_array( $scripts ) ) {
458 $scripts = implode( $scripts, "\n" );
459 }
460 return Xml::encodeJsCall(
461 'mediaWiki.loader.implement',
462 array(
463 $name,
464 new XmlJsCode( "function() {{$scripts}}" ),
465 (object)$styles,
466 (object)$messages
467 ) );
468 }
469
470 /**
471 * Returns JS code which, when called, will register a given list of messages.
472 *
473 * @param $messages Mixed: Either an associative array mapping message key to value, or a
474 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
475 */
476 public static function makeMessageSetScript( $messages ) {
477 return Xml::encodeJsCall( 'mediaWiki.messages.set', array( (object)$messages ) );
478 }
479
480 /**
481 * Combines an associative array mapping media type to CSS into a
482 * single stylesheet with @media blocks.
483 *
484 * @param $styles Array: List of CSS strings keyed by media type
485 */
486 public static function makeCombinedStyles( array $styles ) {
487 $out = '';
488 foreach ( $styles as $media => $style ) {
489 $out .= "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "\n}\n";
490 }
491 return $out;
492 }
493
494 /**
495 * Returns a JS call to mediaWiki.loader.state, which sets the state of a
496 * module or modules to a given value. Has two calling conventions:
497 *
498 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
499 * Set the state of a single module called $name to $state
500 *
501 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
502 * Set the state of modules with the given names to the given states
503 */
504 public static function makeLoaderStateScript( $name, $state = null ) {
505 if ( is_array( $name ) ) {
506 return Xml::encodeJsCall( 'mediaWiki.loader.state', array( $name ) );
507 } else {
508 return Xml::encodeJsCall( 'mediaWiki.loader.state', array( $name, $state ) );
509 }
510 }
511
512 /**
513 * Returns JS code which calls the script given by $script. The script will
514 * be called with local variables name, version, dependencies and group,
515 * which will have values corresponding to $name, $version, $dependencies
516 * and $group as supplied.
517 *
518 * @param $name String: Module name
519 * @param $version Integer: Module version number as a timestamp
520 * @param $dependencies Array: List of module names on which this module depends
521 * @param $group String: Group which the module is in.
522 * @param $script String: JavaScript code
523 */
524 public static function makeCustomLoaderScript( $name, $version, $dependencies, $group, $script ) {
525 $script = str_replace( "\n", "\n\t", trim( $script ) );
526 return Xml::encodeJsCall(
527 "( function( name, version, dependencies, group ) {\n\t$script\n} )",
528 array( $name, $version, $dependencies, $group ) );
529 }
530
531 /**
532 * Returns JS code which calls mediaWiki.loader.register with the given
533 * parameters. Has three calling conventions:
534 *
535 * - ResourceLoader::makeLoaderRegisterScript( $name, $version, $dependencies, $group ):
536 * Register a single module.
537 *
538 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
539 * Register modules with the given names.
540 *
541 * - ResourceLoader::makeLoaderRegisterScript( array(
542 * array( $name1, $version1, $dependencies1, $group1 ),
543 * array( $name2, $version2, $dependencies1, $group2 ),
544 * ...
545 * ) ):
546 * Registers modules with the given names and parameters.
547 *
548 * @param $name String: Module name
549 * @param $version Integer: Module version number as a timestamp
550 * @param $dependencies Array: List of module names on which this module depends
551 * @param $group String: group which the module is in.
552 */
553 public static function makeLoaderRegisterScript( $name, $version = null,
554 $dependencies = null, $group = null )
555 {
556 if ( is_array( $name ) ) {
557 return Xml::encodeJsCall( 'mediaWiki.loader.register', array( $name ) );
558 } else {
559 $version = (int) $version > 1 ? (int) $version : 1;
560 return Xml::encodeJsCall( 'mediaWiki.loader.register',
561 array( $name, $version, $dependencies, $group ) );
562 }
563 }
564
565 /**
566 * Returns JS code which runs given JS code if the client-side framework is
567 * present.
568 *
569 * @param $script String: JavaScript code
570 */
571 public static function makeLoaderConditionalScript( $script ) {
572 $script = str_replace( "\n", "\n\t", trim( $script ) );
573 return "if ( window.mediaWiki ) {\n\t$script\n}\n";
574 }
575
576 /**
577 * Returns JS code which will set the MediaWiki configuration array to
578 * the given value.
579 *
580 * @param $configuration Array: List of configuration values keyed by variable name
581 */
582 public static function makeConfigSetScript( array $configuration ) {
583 return Xml::encodeJsCall( 'mediaWiki.config.set', array( $configuration ) );
584 }
585
586 /**
587 * Determine whether debug mode was requested
588 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
589 * @return bool
590 */
591 public static function inDebugMode() {
592 global $wgRequest, $wgResourceLoaderDebug;
593 static $retval = null;
594 if ( !is_null( $retval ) )
595 return $retval;
596 return $retval = $wgRequest->getFuzzyBool( 'debug',
597 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug ) );
598 }
599 }