Include $IP in path passed to remap() so filesystem access will work properly
[mediawiki.git] / includes / resourceloader / ResourceLoader.php
blob2c815fe27ec3500941cb5501236b23e83fcb5c8f
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.
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.
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
18 * @file
19 * @author Roan Kattouw
20 * @author Trevor Parscal
23 defined( 'MEDIAWIKI' ) || die( 1 );
25 /**
26 * Dynamic JavaScript and CSS resource loading system.
28 * Most of the documention is on the MediaWiki documentation wiki starting at:
29 * http://www.mediawiki.org/wiki/ResourceLoader
31 class ResourceLoader {
33 /* Protected Static Members */
35 /** @var {array} List of module name/ResourceLoaderModule object pairs */
36 protected $modules = array();
38 /* Protected Methods */
40 /**
41 * Loads information stored in the database about modules.
43 * This method grabs modules dependencies from the database and updates modules objects.
45 * This is not inside the module code because it's so much more performant to request all of the information at once
46 * than it is to have each module requests its own information. This sacrifice of modularity yields a profound
47 * performance improvement.
49 * @param {array} $modules List of module names to preload information for
50 * @param {ResourceLoaderContext} $context Context to load the information within
52 protected function preloadModuleInfo( array $modules, ResourceLoaderContext $context ) {
53 if ( !count( $modules ) ) {
54 return; // or else Database*::select() will explode, plus it's cheaper!
56 $dbr = wfGetDb( DB_SLAVE );
57 $skin = $context->getSkin();
58 $lang = $context->getLanguage();
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__
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 )
73 $modulesWithDeps[] = $row->md_module;
76 // Register the absence of a dependency row too
77 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
78 $this->modules[$name]->setFileDependencies( $skin, array() );
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;
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__
97 foreach ( $res as $row ) {
98 $this->modules[$row->mr_resource]->setMsgBlobMtime( $lang, $row->mr_timestamp );
101 foreach ( $modulesWithoutMessages as $name ) {
102 $this->modules[$name]->setMsgBlobMtime( $lang, 0 );
107 * Runs JavaScript or CSS data through a filter, caching the filtered result for future calls.
109 * Available filters are:
110 * - minify-js \see JSMin::minify
111 * - minify-css \see CSSMin::minify
112 * - flip-css \see CSSJanus::transform
114 * If $data is empty, only contains whitespace or the filter was unknown, $data is returned unmodified.
116 * @param {string} $filter Name of filter to run
117 * @param {string} $data Text to filter, such as JavaScript or CSS text
118 * @return {string} Filtered data
120 protected function filter( $filter, $data ) {
121 global $wgMemc;
123 wfProfileIn( __METHOD__ );
125 // For empty/whitespace-only data or for unknown filters, don't perform any caching or processing
126 if ( trim( $data ) === '' || !in_array( $filter, array( 'minify-js', 'minify-css', 'flip-css' ) ) ) {
127 wfProfileOut( __METHOD__ );
128 return $data;
131 // Try for Memcached hit
132 $key = wfMemcKey( 'resourceloader', 'filter', $filter, md5( $data ) );
133 if ( is_string( $cache = $wgMemc->get( $key ) ) ) {
134 wfProfileOut( __METHOD__ );
135 return $cache;
138 // Run the filter - we've already verified one of these will work
139 try {
140 switch ( $filter ) {
141 case 'minify-js':
142 $result = JSMin::minify( $data );
143 break;
144 case 'minify-css':
145 $result = CSSMin::minify( $data );
146 break;
147 case 'flip-css':
148 $result = CSSJanus::transform( $data, true, false );
149 break;
151 } catch ( Exception $exception ) {
152 throw new MWException( 'ResourceLoader filter error. Exception was thrown: ' . $exception->getMessage() );
155 // Save filtered text to Memcached
156 $wgMemc->set( $key, $result );
158 wfProfileOut( __METHOD__ );
160 return $result;
163 /* Methods */
166 * Registers core modules and runs registration hooks.
168 public function __construct() {
169 global $IP;
171 wfProfileIn( __METHOD__ );
173 // Register core modules
174 $this->register( include( "$IP/resources/Resources.php" ) );
175 // Register extension modules
176 wfRunHooks( 'ResourceLoaderRegisterModules', array( &$this ) );
178 wfProfileOut( __METHOD__ );
182 * Registers a module with the ResourceLoader system.
184 * @param {mixed} $name string of name of module or array of name/object pairs
185 * @param {ResourceLoaderModule} $object module object (optional when using multiple-registration calling style)
186 * @throws {MWException} If a duplicate module registration is attempted
187 * @throws {MWException} If something other than a ResourceLoaderModule is being registered
188 * @return {bool} false if there were any errors, in which case one or more modules were not registered
190 public function register( $name, ResourceLoaderModule $object = null ) {
192 wfProfileIn( __METHOD__ );
194 // Allow multiple modules to be registered in one call
195 if ( is_array( $name ) && !isset( $object ) ) {
196 foreach ( $name as $key => $value ) {
197 $this->register( $key, $value );
200 wfProfileOut( __METHOD__ );
202 return;
205 // Disallow duplicate registrations
206 if ( isset( $this->modules[$name] ) ) {
207 // A module has already been registered by this name
208 throw new MWException(
209 'ResourceLoader duplicate registration error. Another module has already been registered as ' . $name
213 // Validate the input (type hinting lets null through)
214 if ( !( $object instanceof ResourceLoaderModule ) ) {
215 throw new MWException( 'ResourceLoader invalid module error. Instances of ResourceLoaderModule expected.' );
218 // Attach module
219 $this->modules[$name] = $object;
220 $object->setName( $name );
222 wfProfileOut( __METHOD__ );
226 * Gets a map of all modules and their options
228 * @return {array} array( modulename => ResourceLoaderModule )
230 public function getModules() {
231 return $this->modules;
235 * Get the ResourceLoaderModule object for a given module name.
237 * @param {string} $name module name
238 * @return {mixed} ResourceLoaderModule if module has been registered, null otherwise
240 public function getModule( $name ) {
241 return isset( $this->modules[$name] ) ? $this->modules[$name] : null;
245 * Outputs a response to a resource load-request, including a content-type header.
247 * @param {ResourceLoaderContext} $context Context in which a response should be formed
249 public function respond( ResourceLoaderContext $context ) {
250 global $wgResourceLoaderMaxage, $wgCacheEpoch;
252 wfProfileIn( __METHOD__ );
254 // Split requested modules into two groups, modules and missing
255 $modules = array();
256 $missing = array();
257 foreach ( $context->getModules() as $name ) {
258 if ( isset( $this->modules[$name] ) ) {
259 $modules[$name] = $this->modules[$name];
260 } else {
261 $missing[] = $name;
265 // If a version wasn't specified we need a shorter expiry time for updates to propagate to clients quickly
266 if ( is_null( $context->getVersion() ) ) {
267 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
268 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
270 // If a version was specified we can use a longer expiry time since changing version numbers causes cache misses
271 else {
272 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
273 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
276 // Preload information needed to the mtime calculation below
277 $this->preloadModuleInfo( array_keys( $modules ), $context );
279 wfProfileIn( __METHOD__.'-getModifiedTime' );
281 // To send Last-Modified and support If-Modified-Since, we need to detect the last modified time
282 $mtime = wfTimestamp( TS_UNIX, $wgCacheEpoch );
283 foreach ( $modules as $module ) {
284 // Bypass squid cache if the request includes any private modules
285 if ( $module->getGroup() === 'private' ) {
286 $smaxage = 0;
288 // Calculate maximum modified time
289 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
292 wfProfileOut( __METHOD__.'-getModifiedTime' );
294 header( 'Content-Type: ' . ( $context->getOnly() === 'styles' ? 'text/css' : 'text/javascript' ) );
295 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $mtime ) );
296 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
297 header( 'Expires: ' . wfTimestamp( TS_RFC2822, min( $maxage, $smaxage ) + time() ) );
299 // If there's an If-Modified-Since header, respond with a 304 appropriately
300 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
301 if ( $ims !== false && $mtime <= wfTimestamp( TS_UNIX, $ims ) ) {
302 header( 'HTTP/1.0 304 Not Modified' );
303 header( 'Status: 304 Not Modified' );
304 wfProfileOut( __METHOD__ );
305 return;
308 // Generate a response
309 $response = $this->makeModuleResponse( $context, $modules, $missing );
311 // Tack on PHP warnings as a comment in debug mode
312 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
313 $response .= "/*\n$warnings\n*/";
316 // Clear any warnings from the buffer
317 ob_clean();
318 echo $response;
320 wfProfileOut( __METHOD__ );
324 * Generates code for a response
326 * @param {ResourceLoaderContext} $context Context in which to generate a response
327 * @param {array} $modules List of module objects keyed by module name
328 * @param {array} $missing List of unavailable modules (optional)
329 * @return {string} Response data
331 public function makeModuleResponse( ResourceLoaderContext $context, array $modules, $missing = array() ) {
332 // Pre-fetch blobs
333 $blobs = $context->shouldIncludeMessages() ?
334 MessageBlobStore::get( $this, $modules, $context->getLanguage() ) : array();
336 // Generate output
337 $out = '';
338 foreach ( $modules as $name => $module ) {
340 wfProfileIn( __METHOD__ . '-' . $name );
342 // Scripts
343 $scripts = '';
344 if ( $context->shouldIncludeScripts() ) {
345 $scripts .= $module->getScript( $context ) . "\n";
348 // Styles
349 $styles = array();
350 if ( $context->shouldIncludeStyles() && ( count( $styles = $module->getStyles( $context ) ) ) ) {
351 // Flip CSS on a per-module basis
352 if ( $this->modules[$name]->getFlip( $context ) ) {
353 foreach ( $styles as $media => $style ) {
354 $styles[$media] = $this->filter( 'flip-css', $style );
359 // Messages
360 $messages = isset( $blobs[$name] ) ? $blobs[$name] : '{}';
362 // Append output
363 switch ( $context->getOnly() ) {
364 case 'scripts':
365 $out .= $scripts;
366 break;
367 case 'styles':
368 $out .= self::makeCombinedStyles( $styles );
369 break;
370 case 'messages':
371 $out .= self::makeMessageSetScript( $messages );
372 break;
373 default:
374 // Minify CSS before embedding in mediaWiki.loader.implement call (unless in debug mode)
375 if ( !$context->getDebug() ) {
376 foreach ( $styles as $media => $style ) {
377 $styles[$media] = $this->filter( 'minify-css', $style );
380 $out .= self::makeLoaderImplementScript( $name, $scripts, $styles, $messages );
381 break;
384 wfProfileOut( __METHOD__ . '-' . $name );
387 // Update module states
388 if ( $context->shouldIncludeScripts() ) {
389 // Set the state of modules loaded as only scripts to ready
390 if ( count( $modules ) && $context->getOnly() === 'scripts' && !isset( $modules['startup'] ) ) {
391 $out .= self::makeLoaderStateScript( array_fill_keys( array_keys( $modules ), 'ready' ) );
393 // Set the state of modules which were requested but unavailable as missing
394 if ( is_array( $missing ) && count( $missing ) ) {
395 $out .= self::makeLoaderStateScript( array_fill_keys( $missing, 'missing' ) );
399 if ( $context->getDebug() ) {
400 return $out;
401 } else {
402 if ( $context->getOnly() === 'styles' ) {
403 return $this->filter( 'minify-css', $out );
404 } else {
405 return $this->filter( 'minify-js', $out );
410 /* Static Methods */
412 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
413 if ( is_array( $scripts ) ) {
414 $scripts = implode( $scripts, "\n" );
416 if ( is_array( $styles ) ) {
417 $styles = count( $styles ) ? FormatJson::encode( $styles ) : 'null';
419 if ( is_array( $messages ) ) {
420 $messages = count( $messages ) ? FormatJson::encode( $messages ) : 'null';
422 return "mediaWiki.loader.implement( '$name', function() {{$scripts}},\n$styles,\n$messages );\n";
425 public static function makeMessageSetScript( $messages ) {
426 if ( is_array( $messages ) ) {
427 $messages = count( $messages ) ? FormatJson::encode( $messages ) : 'null';
429 return "mediaWiki.msg.set( $messages );\n";
432 public static function makeCombinedStyles( array $styles ) {
433 $out = '';
434 foreach ( $styles as $media => $style ) {
435 $out .= "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "\n}\n";
437 return $out;
440 public static function makeLoaderStateScript( $name, $state = null ) {
441 if ( is_array( $name ) ) {
442 $statuses = FormatJson::encode( $name );
443 return "mediaWiki.loader.state( $statuses );\n";
444 } else {
445 $name = Xml::escapeJsString( $name );
446 $state = Xml::escapeJsString( $state );
447 return "mediaWiki.loader.state( '$name', '$state' );\n";
451 public static function makeCustomLoaderScript( $name, $version, $dependencies, $group, $script ) {
452 $name = Xml::escapeJsString( $name );
453 $version = (int) $version > 1 ? (int) $version : 1;
454 $dependencies = FormatJson::encode( $dependencies );
455 $group = FormatJson::encode( $group );
456 $script = str_replace( "\n", "\n\t", trim( $script ) );
457 return "( function( name, version, dependencies, group ) {\n\t$script\n} )" .
458 "( '$name', $version, $dependencies, $group );\n";
461 public static function makeLoaderRegisterScript( $name, $version = null, $dependencies = null, $group = null ) {
462 if ( is_array( $name ) ) {
463 $registrations = FormatJson::encode( $name );
464 return "mediaWiki.loader.register( $registrations );\n";
465 } else {
466 $name = Xml::escapeJsString( $name );
467 $version = (int) $version > 1 ? (int) $version : 1;
468 $dependencies = FormatJson::encode( $dependencies );
469 $group = FormatJson::encode( $group );
470 return "mediaWiki.loader.register( '$name', $version, $dependencies, $group );\n";
474 public static function makeLoaderConditionalScript( $script ) {
475 $script = str_replace( "\n", "\n\t", trim( $script ) );
476 return "if ( window.mediaWiki ) {\n\t$script\n}\n";
479 public static function makeConfigSetScript( array $configuration ) {
480 $configuration = FormatJson::encode( $configuration );
481 return "mediaWiki.config.set( $configuration );\n";