Folowup r77763, add documentation for $wgFooterIcons.
[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 wfProfileIn( __METHOD__ );
292
293 // Split requested modules into two groups, modules and missing
294 $modules = array();
295 $missing = array();
296 foreach ( $context->getModules() as $name ) {
297 if ( isset( $this->moduleInfos[$name] ) ) {
298 $modules[$name] = $this->getModule( $name );
299 } else {
300 $missing[] = $name;
301 }
302 }
303
304 // If a version wasn't specified we need a shorter expiry time for updates
305 // to propagate to clients quickly
306 if ( is_null( $context->getVersion() ) ) {
307 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
308 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
309 }
310 // If a version was specified we can use a longer expiry time since changing
311 // version numbers causes cache misses
312 else {
313 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
314 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
315 }
316
317 // Preload information needed to the mtime calculation below
318 $this->preloadModuleInfo( array_keys( $modules ), $context );
319
320 wfProfileIn( __METHOD__.'-getModifiedTime' );
321
322 // To send Last-Modified and support If-Modified-Since, we need to detect
323 // the last modified time
324 $mtime = wfTimestamp( TS_UNIX, $wgCacheEpoch );
325 foreach ( $modules as $module ) {
326 // Bypass squid cache if the request includes any private modules
327 if ( $module->getGroup() === 'private' ) {
328 $smaxage = 0;
329 }
330 // Calculate maximum modified time
331 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
332 }
333
334 wfProfileOut( __METHOD__.'-getModifiedTime' );
335
336 if ( $context->getOnly() === 'styles' ) {
337 header( 'Content-Type: text/css' );
338 } else {
339 header( 'Content-Type: text/javascript' );
340 }
341 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $mtime ) );
342 if ( $context->getDebug() ) {
343 header( 'Cache-Control: must-revalidate' );
344 } else {
345 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
346 header( 'Expires: ' . wfTimestamp( TS_RFC2822, min( $maxage, $smaxage ) + time() ) );
347 }
348
349 // If there's an If-Modified-Since header, respond with a 304 appropriately
350 // Some clients send "timestamp;length=123". Strip the part after the first ';'
351 // so we get a valid timestamp.
352 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
353 if ( $ims !== false ) {
354 $imsTS = strtok( $ims, ';' );
355 if ( $mtime <= wfTimestamp( TS_UNIX, $imsTS ) ) {
356 header( 'HTTP/1.0 304 Not Modified' );
357 header( 'Status: 304 Not Modified' );
358 wfProfileOut( __METHOD__ );
359 return;
360 }
361 }
362
363 // Generate a response
364 $response = $this->makeModuleResponse( $context, $modules, $missing );
365
366 // Tack on PHP warnings as a comment in debug mode
367 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
368 $response .= "/*\n$warnings\n*/";
369 }
370
371 // Clear any warnings from the buffer
372 ob_clean();
373 echo $response;
374
375 wfProfileOut( __METHOD__ );
376 }
377
378 /**
379 * Generates code for a response
380 *
381 * @param $context ResourceLoaderContext: Context in which to generate a response
382 * @param $modules Array: List of module objects keyed by module name
383 * @param $missing Array: List of unavailable modules (optional)
384 * @return String: Response data
385 */
386 public function makeModuleResponse( ResourceLoaderContext $context,
387 array $modules, $missing = array() )
388 {
389 // Pre-fetch blobs
390 if ( $context->shouldIncludeMessages() ) {
391 $blobs = MessageBlobStore::get( $this, $modules, $context->getLanguage() );
392 } else {
393 $blobs = array();
394 }
395
396 // Generate output
397 $out = '';
398 foreach ( $modules as $name => $module ) {
399
400 wfProfileIn( __METHOD__ . '-' . $name );
401
402 // Scripts
403 $scripts = '';
404 if ( $context->shouldIncludeScripts() ) {
405 $scripts .= $module->getScript( $context ) . "\n";
406 }
407
408 // Styles
409 $styles = array();
410 if ( $context->shouldIncludeStyles() ) {
411 $styles = $module->getStyles( $context );
412 // Flip CSS on a per-module basis
413 if ( $styles && $module->getFlip( $context ) ) {
414 foreach ( $styles as $media => $style ) {
415 $styles[$media] = $this->filter( 'flip-css', $style );
416 }
417 }
418 }
419
420 // Messages
421 $messagesBlob = isset( $blobs[$name] ) ? $blobs[$name] : '{}';
422
423 // Append output
424 switch ( $context->getOnly() ) {
425 case 'scripts':
426 $out .= $scripts;
427 break;
428 case 'styles':
429 $out .= self::makeCombinedStyles( $styles );
430 break;
431 case 'messages':
432 $out .= self::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
433 break;
434 default:
435 // Minify CSS before embedding in mediaWiki.loader.implement call
436 // (unless in debug mode)
437 if ( !$context->getDebug() ) {
438 foreach ( $styles as $media => $style ) {
439 $styles[$media] = $this->filter( 'minify-css', $style );
440 }
441 }
442 $out .= self::makeLoaderImplementScript( $name, $scripts, $styles,
443 new XmlJsCode( $messagesBlob ) );
444 break;
445 }
446
447 wfProfileOut( __METHOD__ . '-' . $name );
448 }
449
450 // Update module states
451 if ( $context->shouldIncludeScripts() ) {
452 // Set the state of modules loaded as only scripts to ready
453 if ( count( $modules ) && $context->getOnly() === 'scripts'
454 && !isset( $modules['startup'] ) )
455 {
456 $out .= self::makeLoaderStateScript(
457 array_fill_keys( array_keys( $modules ), 'ready' ) );
458 }
459 // Set the state of modules which were requested but unavailable as missing
460 if ( is_array( $missing ) && count( $missing ) ) {
461 $out .= self::makeLoaderStateScript( array_fill_keys( $missing, 'missing' ) );
462 }
463 }
464
465 if ( $context->getDebug() ) {
466 return $out;
467 } else {
468 if ( $context->getOnly() === 'styles' ) {
469 return $this->filter( 'minify-css', $out );
470 } else {
471 return $this->filter( 'minify-js', $out );
472 }
473 }
474 }
475
476 /* Static Methods */
477
478 /**
479 * Returns JS code to call to mediaWiki.loader.implement for a module with
480 * given properties.
481 *
482 * @param $name Module name
483 * @param $scripts Array: List of JavaScript code snippets to be executed after the
484 * module is loaded
485 * @param $styles Array: List of CSS strings keyed by media type
486 * @param $messages Mixed: List of messages associated with this module. May either be an
487 * associative array mapping message key to value, or a JSON-encoded message blob containing
488 * the same data, wrapped in an XmlJsCode object.
489 */
490 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
491 if ( is_array( $scripts ) ) {
492 $scripts = implode( $scripts, "\n" );
493 }
494 return Xml::encodeJsCall(
495 'mediaWiki.loader.implement',
496 array(
497 $name,
498 new XmlJsCode( "function() {{$scripts}}" ),
499 (object)$styles,
500 (object)$messages
501 ) );
502 }
503
504 /**
505 * Returns JS code which, when called, will register a given list of messages.
506 *
507 * @param $messages Mixed: Either an associative array mapping message key to value, or a
508 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
509 */
510 public static function makeMessageSetScript( $messages ) {
511 return Xml::encodeJsCall( 'mediaWiki.messages.set', array( (object)$messages ) );
512 }
513
514 /**
515 * Combines an associative array mapping media type to CSS into a
516 * single stylesheet with @media blocks.
517 *
518 * @param $styles Array: List of CSS strings keyed by media type
519 */
520 public static function makeCombinedStyles( array $styles ) {
521 $out = '';
522 foreach ( $styles as $media => $style ) {
523 $out .= "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "\n}\n";
524 }
525 return $out;
526 }
527
528 /**
529 * Returns a JS call to mediaWiki.loader.state, which sets the state of a
530 * module or modules to a given value. Has two calling conventions:
531 *
532 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
533 * Set the state of a single module called $name to $state
534 *
535 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
536 * Set the state of modules with the given names to the given states
537 */
538 public static function makeLoaderStateScript( $name, $state = null ) {
539 if ( is_array( $name ) ) {
540 return Xml::encodeJsCall( 'mediaWiki.loader.state', array( $name ) );
541 } else {
542 return Xml::encodeJsCall( 'mediaWiki.loader.state', array( $name, $state ) );
543 }
544 }
545
546 /**
547 * Returns JS code which calls the script given by $script. The script will
548 * be called with local variables name, version, dependencies and group,
549 * which will have values corresponding to $name, $version, $dependencies
550 * and $group as supplied.
551 *
552 * @param $name String: Module name
553 * @param $version Integer: Module version number as a timestamp
554 * @param $dependencies Array: List of module names on which this module depends
555 * @param $group String: Group which the module is in.
556 * @param $script String: JavaScript code
557 */
558 public static function makeCustomLoaderScript( $name, $version, $dependencies, $group, $script ) {
559 $script = str_replace( "\n", "\n\t", trim( $script ) );
560 return Xml::encodeJsCall(
561 "( function( name, version, dependencies, group ) {\n\t$script\n} )",
562 array( $name, $version, $dependencies, $group ) );
563 }
564
565 /**
566 * Returns JS code which calls mediaWiki.loader.register with the given
567 * parameters. Has three calling conventions:
568 *
569 * - ResourceLoader::makeLoaderRegisterScript( $name, $version, $dependencies, $group ):
570 * Register a single module.
571 *
572 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
573 * Register modules with the given names.
574 *
575 * - ResourceLoader::makeLoaderRegisterScript( array(
576 * array( $name1, $version1, $dependencies1, $group1 ),
577 * array( $name2, $version2, $dependencies1, $group2 ),
578 * ...
579 * ) ):
580 * Registers modules with the given names and parameters.
581 *
582 * @param $name String: Module name
583 * @param $version Integer: Module version number as a timestamp
584 * @param $dependencies Array: List of module names on which this module depends
585 * @param $group String: group which the module is in.
586 */
587 public static function makeLoaderRegisterScript( $name, $version = null,
588 $dependencies = null, $group = null )
589 {
590 if ( is_array( $name ) ) {
591 return Xml::encodeJsCall( 'mediaWiki.loader.register', array( $name ) );
592 } else {
593 $version = (int) $version > 1 ? (int) $version : 1;
594 return Xml::encodeJsCall( 'mediaWiki.loader.register',
595 array( $name, $version, $dependencies, $group ) );
596 }
597 }
598
599 /**
600 * Returns JS code which runs given JS code if the client-side framework is
601 * present.
602 *
603 * @param $script String: JavaScript code
604 */
605 public static function makeLoaderConditionalScript( $script ) {
606 $script = str_replace( "\n", "\n\t", trim( $script ) );
607 return "if ( window.mediaWiki ) {\n\t$script\n}\n";
608 }
609
610 /**
611 * Returns JS code which will set the MediaWiki configuration array to
612 * the given value.
613 *
614 * @param $configuration Array: List of configuration values keyed by variable name
615 */
616 public static function makeConfigSetScript( array $configuration ) {
617 return Xml::encodeJsCall( 'mediaWiki.config.set', array( $configuration ) );
618 }
619
620 /**
621 * Determine whether debug mode was requested
622 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
623 * @return bool
624 */
625 public static function inDebugMode() {
626 global $wgRequest, $wgResourceLoaderDebug;
627 static $retval = null;
628 if ( !is_null( $retval ) )
629 return $retval;
630 return $retval = $wgRequest->getFuzzyBool( 'debug',
631 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug ) );
632 }
633 }