Merge "Added VirtualRESTServiceClient/VirtualRESTService classes"
[lhc/web/wiklou.git] / includes / resourceloader / ResourceLoader.php
1 <?php
2 /**
3 * Base class for resource loading system.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @author Roan Kattouw
22 * @author Trevor Parscal
23 */
24
25 /**
26 * Dynamic JavaScript and CSS resource loading system.
27 *
28 * Most of the documentation is on the MediaWiki documentation wiki starting at:
29 * https://www.mediawiki.org/wiki/ResourceLoader
30 */
31 class ResourceLoader {
32
33 /**
34 * @var int
35 */
36 protected static $filterCacheVersion = 7;
37 /**
38 * @var array
39 */
40 protected static $requiredSourceProperties = array( 'loadScript' );
41
42 /**
43 * @var array Module name/ResourceLoaderModule object pairs
44 */
45 protected $modules = array();
46
47 /**
48 * @var array Associative array mapping module name to info associative array
49 */
50 protected $moduleInfos = array();
51
52 /**
53 * @var array Associative array mapping framework ids to a list of names of test suite modules
54 * like array( 'qunit' => array( 'mediawiki.tests.qunit.suites', 'ext.foo.tests', .. ), .. )
55 */
56 protected $testModuleNames = array();
57
58 /**
59 * @var array e.g. array( 'source-id' => array( 'loadScript' => 'http://.../load.php' ) )
60 */
61 protected $sources = array();
62
63 /**
64 * @var bool
65 */
66 protected $hasErrors = false;
67
68 /**
69 * Load information stored in the database about modules.
70 *
71 * This method grabs modules dependencies from the database and updates modules
72 * objects.
73 *
74 * This is not inside the module code because it is much faster to
75 * request all of the information at once than it is to have each module
76 * requests its own information. This sacrifice of modularity yields a substantial
77 * performance improvement.
78 *
79 * @param array $modules List of module names to preload information for
80 * @param ResourceLoaderContext $context Context to load the information within
81 */
82 public function preloadModuleInfo( array $modules, ResourceLoaderContext $context ) {
83 if ( !count( $modules ) ) {
84 // Or else Database*::select() will explode, plus it's cheaper!
85 return;
86 }
87 $dbr = wfGetDB( DB_SLAVE );
88 $skin = $context->getSkin();
89 $lang = $context->getLanguage();
90
91 // Get file dependency information
92 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
93 'md_module' => $modules,
94 'md_skin' => $skin
95 ), __METHOD__
96 );
97
98 // Set modules' dependencies
99 $modulesWithDeps = array();
100 foreach ( $res as $row ) {
101 $module = $this->getModule( $row->md_module );
102 if ( $module ) {
103 $module->setFileDependencies( $skin, FormatJson::decode( $row->md_deps, true ) );
104 $modulesWithDeps[] = $row->md_module;
105 }
106 }
107
108 // Register the absence of a dependency row too
109 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
110 $module = $this->getModule( $name );
111 if ( $module ) {
112 $this->getModule( $name )->setFileDependencies( $skin, array() );
113 }
114 }
115
116 // Get message blob mtimes. Only do this for modules with messages
117 $modulesWithMessages = array();
118 foreach ( $modules as $name ) {
119 $module = $this->getModule( $name );
120 if ( $module && count( $module->getMessages() ) ) {
121 $modulesWithMessages[] = $name;
122 }
123 }
124 $modulesWithoutMessages = array_flip( $modules ); // Will be trimmed down by the loop below
125 if ( count( $modulesWithMessages ) ) {
126 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
127 'mr_resource' => $modulesWithMessages,
128 'mr_lang' => $lang
129 ), __METHOD__
130 );
131 foreach ( $res as $row ) {
132 $module = $this->getModule( $row->mr_resource );
133 if ( $module ) {
134 $module->setMsgBlobMtime( $lang, wfTimestamp( TS_UNIX, $row->mr_timestamp ) );
135 unset( $modulesWithoutMessages[$row->mr_resource] );
136 }
137 }
138 }
139 foreach ( array_keys( $modulesWithoutMessages ) as $name ) {
140 $module = $this->getModule( $name );
141 if ( $module ) {
142 $module->setMsgBlobMtime( $lang, 0 );
143 }
144 }
145 }
146
147 /**
148 * Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
149 *
150 * Available filters are:
151 *
152 * - minify-js \see JavaScriptMinifier::minify
153 * - minify-css \see CSSMin::minify
154 *
155 * If $data is empty, only contains whitespace or the filter was unknown,
156 * $data is returned unmodified.
157 *
158 * @param string $filter Name of filter to run
159 * @param string $data Text to filter, such as JavaScript or CSS text
160 * @return string Filtered data, or a comment containing an error message
161 */
162 protected function filter( $filter, $data ) {
163 global $wgResourceLoaderMinifierStatementsOnOwnLine, $wgResourceLoaderMinifierMaxLineLength;
164 wfProfileIn( __METHOD__ );
165
166 // For empty/whitespace-only data or for unknown filters, don't perform
167 // any caching or processing
168 if ( trim( $data ) === '' || !in_array( $filter, array( 'minify-js', 'minify-css' ) ) ) {
169 wfProfileOut( __METHOD__ );
170 return $data;
171 }
172
173 // Try for cache hit
174 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
175 $key = wfMemcKey( 'resourceloader', 'filter', $filter, self::$filterCacheVersion, md5( $data ) );
176 $cache = wfGetCache( CACHE_ANYTHING );
177 $cacheEntry = $cache->get( $key );
178 if ( is_string( $cacheEntry ) ) {
179 wfIncrStats( "rl-$filter-cache-hits" );
180 wfProfileOut( __METHOD__ );
181 return $cacheEntry;
182 }
183
184 $result = '';
185 // Run the filter - we've already verified one of these will work
186 try {
187 wfIncrStats( "rl-$filter-cache-misses" );
188 switch ( $filter ) {
189 case 'minify-js':
190 $result = JavaScriptMinifier::minify( $data,
191 $wgResourceLoaderMinifierStatementsOnOwnLine,
192 $wgResourceLoaderMinifierMaxLineLength
193 );
194 $result .= "\n/* cache key: $key */";
195 break;
196 case 'minify-css':
197 $result = CSSMin::minify( $data );
198 $result .= "\n/* cache key: $key */";
199 break;
200 }
201
202 // Save filtered text to Memcached
203 $cache->set( $key, $result );
204 } catch ( Exception $e ) {
205 MWExceptionHandler::logException( $e );
206 wfDebugLog( 'resourceloader', __METHOD__ . ": minification failed: $e" );
207 $this->hasErrors = true;
208 // Return exception as a comment
209 $result = self::formatException( $e );
210 }
211
212 wfProfileOut( __METHOD__ );
213
214 return $result;
215 }
216
217 /* Methods */
218
219 /**
220 * Register core modules and runs registration hooks.
221 */
222 public function __construct() {
223 global $IP, $wgResourceModules, $wgResourceLoaderSources, $wgLoadScript, $wgEnableJavaScriptTest;
224
225 wfProfileIn( __METHOD__ );
226
227 // Add 'local' source first
228 $this->addSource( 'local', array( 'loadScript' => $wgLoadScript, 'apiScript' => wfScript( 'api' ) ) );
229
230 // Add other sources
231 $this->addSource( $wgResourceLoaderSources );
232
233 // Register core modules
234 $this->register( include "$IP/resources/Resources.php" );
235 // Register extension modules
236 wfRunHooks( 'ResourceLoaderRegisterModules', array( &$this ) );
237 $this->register( $wgResourceModules );
238
239 if ( $wgEnableJavaScriptTest === true ) {
240 $this->registerTestModules();
241 }
242
243 wfProfileOut( __METHOD__ );
244 }
245
246 /**
247 * Register a module with the ResourceLoader system.
248 *
249 * @param mixed $name Name of module as a string or List of name/object pairs as an array
250 * @param array $info Module info array. For backwards compatibility with 1.17alpha,
251 * this may also be a ResourceLoaderModule object. Optional when using
252 * multiple-registration calling style.
253 * @throws MWException If a duplicate module registration is attempted
254 * @throws MWException If a module name contains illegal characters (pipes or commas)
255 * @throws MWException If something other than a ResourceLoaderModule is being registered
256 * @return bool False if there were any errors, in which case one or more modules were
257 * not registered
258 */
259 public function register( $name, $info = null ) {
260 wfProfileIn( __METHOD__ );
261
262 // Allow multiple modules to be registered in one call
263 $registrations = is_array( $name ) ? $name : array( $name => $info );
264 foreach ( $registrations as $name => $info ) {
265 // Disallow duplicate registrations
266 if ( isset( $this->moduleInfos[$name] ) ) {
267 wfProfileOut( __METHOD__ );
268 // A module has already been registered by this name
269 throw new MWException(
270 'ResourceLoader duplicate registration error. ' .
271 'Another module has already been registered as ' . $name
272 );
273 }
274
275 // Check $name for validity
276 if ( !self::isValidModuleName( $name ) ) {
277 wfProfileOut( __METHOD__ );
278 throw new MWException( "ResourceLoader module name '$name' is invalid, see ResourceLoader::isValidModuleName()" );
279 }
280
281 // Attach module
282 if ( $info instanceof ResourceLoaderModule ) {
283 $this->moduleInfos[$name] = array( 'object' => $info );
284 $info->setName( $name );
285 $this->modules[$name] = $info;
286 } elseif ( is_array( $info ) ) {
287 // New calling convention
288 $this->moduleInfos[$name] = $info;
289 } else {
290 wfProfileOut( __METHOD__ );
291 throw new MWException(
292 'ResourceLoader module info type error for module \'' . $name .
293 '\': expected ResourceLoaderModule or array (got: ' . gettype( $info ) . ')'
294 );
295 }
296 }
297
298 wfProfileOut( __METHOD__ );
299 }
300
301 /**
302 */
303 public function registerTestModules() {
304 global $IP, $wgEnableJavaScriptTest;
305
306 if ( $wgEnableJavaScriptTest !== true ) {
307 throw new MWException( 'Attempt to register JavaScript test modules but <code>$wgEnableJavaScriptTest</code> is false. Edit your <code>LocalSettings.php</code> to enable it.' );
308 }
309
310 wfProfileIn( __METHOD__ );
311
312 // Get core test suites
313 $testModules = array();
314 $testModules['qunit'] = array();
315 // Get other test suites (e.g. from extensions)
316 wfRunHooks( 'ResourceLoaderTestModules', array( &$testModules, &$this ) );
317
318 // Add the testrunner (which configures QUnit) to the dependencies.
319 // Since it must be ready before any of the test suites are executed.
320 foreach ( $testModules['qunit'] as &$module ) {
321 // Make sure all test modules are top-loading so that when QUnit starts
322 // on document-ready, it will run once and finish. If some tests arrive
323 // later (possibly after QUnit has already finished) they will be ignored.
324 $module['position'] = 'top';
325 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
326 }
327
328 $testModules['qunit'] = ( include "$IP/tests/qunit/QUnitTestResources.php" ) + $testModules['qunit'];
329
330 foreach ( $testModules as $id => $names ) {
331 // Register test modules
332 $this->register( $testModules[$id] );
333
334 // Keep track of their names so that they can be loaded together
335 $this->testModuleNames[$id] = array_keys( $testModules[$id] );
336 }
337
338 wfProfileOut( __METHOD__ );
339 }
340
341 /**
342 * Add a foreign source of modules.
343 *
344 * Source properties:
345 * 'loadScript': URL (either fully-qualified or protocol-relative) of load.php for this source
346 *
347 * @param mixed $id Source ID (string), or array( id1 => props1, id2 => props2, ... )
348 * @param array $properties Source properties
349 * @throws MWException
350 */
351 public function addSource( $id, $properties = null ) {
352 // Allow multiple sources to be registered in one call
353 if ( is_array( $id ) ) {
354 foreach ( $id as $key => $value ) {
355 $this->addSource( $key, $value );
356 }
357 return;
358 }
359
360 // Disallow duplicates
361 if ( isset( $this->sources[$id] ) ) {
362 throw new MWException(
363 'ResourceLoader duplicate source addition error. ' .
364 'Another source has already been registered as ' . $id
365 );
366 }
367
368 // Validate properties
369 foreach ( self::$requiredSourceProperties as $prop ) {
370 if ( !isset( $properties[$prop] ) ) {
371 throw new MWException( "Required property $prop missing from source ID $id" );
372 }
373 }
374
375 $this->sources[$id] = $properties;
376 }
377
378 /**
379 * Get a list of module names.
380 *
381 * @return array List of module names
382 */
383 public function getModuleNames() {
384 return array_keys( $this->moduleInfos );
385 }
386
387 /**
388 * Get a list of test module names for one (or all) frameworks.
389 *
390 * If the given framework id is unknkown, or if the in-object variable is not an array,
391 * then it will return an empty array.
392 *
393 * @param string $framework Get only the test module names for one
394 * particular framework (optional)
395 * @return array
396 */
397 public function getTestModuleNames( $framework = 'all' ) {
398 /// @todo api siteinfo prop testmodulenames modulenames
399 if ( $framework == 'all' ) {
400 return $this->testModuleNames;
401 } elseif ( isset( $this->testModuleNames[$framework] ) && is_array( $this->testModuleNames[$framework] ) ) {
402 return $this->testModuleNames[$framework];
403 } else {
404 return array();
405 }
406 }
407
408 /**
409 * Get the ResourceLoaderModule object for a given module name.
410 *
411 * If an array of module parameters exists but a ResourceLoaderModule object has not
412 * yet been instantiated, this method will instantiate and cache that object such that
413 * subsequent calls simply return the same object.
414 *
415 * @param string $name Module name
416 * @return ResourceLoaderModule|null If module has been registered, return a
417 * ResourceLoaderModule instance. Otherwise, return null.
418 */
419 public function getModule( $name ) {
420 if ( !isset( $this->modules[$name] ) ) {
421 if ( !isset( $this->moduleInfos[$name] ) ) {
422 // No such module
423 return null;
424 }
425 // Construct the requested object
426 $info = $this->moduleInfos[$name];
427 /** @var ResourceLoaderModule $object */
428 if ( isset( $info['object'] ) ) {
429 // Object given in info array
430 $object = $info['object'];
431 } else {
432 if ( !isset( $info['class'] ) ) {
433 $class = 'ResourceLoaderFileModule';
434 } else {
435 $class = $info['class'];
436 }
437 $object = new $class( $info );
438 }
439 $object->setName( $name );
440 $this->modules[$name] = $object;
441 }
442
443 return $this->modules[$name];
444 }
445
446 /**
447 * Get the list of sources.
448 *
449 * @return array Like array( id => array of properties, .. )
450 */
451 public function getSources() {
452 return $this->sources;
453 }
454
455 /**
456 * Output a response to a load request, including the content-type header.
457 *
458 * @param ResourceLoaderContext $context Context in which a response should be formed
459 */
460 public function respond( ResourceLoaderContext $context ) {
461 global $wgCacheEpoch, $wgUseFileCache;
462
463 // Use file cache if enabled and available...
464 if ( $wgUseFileCache ) {
465 $fileCache = ResourceFileCache::newFromContext( $context );
466 if ( $this->tryRespondFromFileCache( $fileCache, $context ) ) {
467 return; // output handled
468 }
469 }
470
471 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
472 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
473 // is used: ob_clean() will clear the GZIP header in that case and it won't come
474 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
475 // the whole thing in our own output buffer to be sure the active buffer
476 // doesn't use ob_gzhandler.
477 // See http://bugs.php.net/bug.php?id=36514
478 ob_start();
479
480 wfProfileIn( __METHOD__ );
481 $errors = '';
482
483 // Find out which modules are missing and instantiate the others
484 $modules = array();
485 $missing = array();
486 foreach ( $context->getModules() as $name ) {
487 $module = $this->getModule( $name );
488 if ( $module ) {
489 // Do not allow private modules to be loaded from the web.
490 // This is a security issue, see bug 34907.
491 if ( $module->getGroup() === 'private' ) {
492 wfDebugLog( 'resourceloader', __METHOD__ . ": request for private module '$name' denied" );
493 $this->hasErrors = true;
494 // Add exception to the output as a comment
495 $errors .= self::makeComment( "Cannot show private module \"$name\"" );
496
497 continue;
498 }
499 $modules[$name] = $module;
500 } else {
501 $missing[] = $name;
502 }
503 }
504
505 // Preload information needed to the mtime calculation below
506 try {
507 $this->preloadModuleInfo( array_keys( $modules ), $context );
508 } catch ( Exception $e ) {
509 MWExceptionHandler::logException( $e );
510 wfDebugLog( 'resourceloader', __METHOD__ . ": preloading module info failed: $e" );
511 $this->hasErrors = true;
512 // Add exception to the output as a comment
513 $errors .= self::formatException( $e );
514 }
515
516 wfProfileIn( __METHOD__ . '-getModifiedTime' );
517
518 // To send Last-Modified and support If-Modified-Since, we need to detect
519 // the last modified time
520 $mtime = wfTimestamp( TS_UNIX, $wgCacheEpoch );
521 foreach ( $modules as $module ) {
522 /**
523 * @var $module ResourceLoaderModule
524 */
525 try {
526 // Calculate maximum modified time
527 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
528 } catch ( Exception $e ) {
529 MWExceptionHandler::logException( $e );
530 wfDebugLog( 'resourceloader', __METHOD__ . ": calculating maximum modified time failed: $e" );
531 $this->hasErrors = true;
532 // Add exception to the output as a comment
533 $errors .= self::formatException( $e );
534 }
535 }
536
537 wfProfileOut( __METHOD__ . '-getModifiedTime' );
538
539 // If there's an If-Modified-Since header, respond with a 304 appropriately
540 if ( $this->tryRespondLastModified( $context, $mtime ) ) {
541 wfProfileOut( __METHOD__ );
542 return; // output handled (buffers cleared)
543 }
544
545 // Generate a response
546 $response = $this->makeModuleResponse( $context, $modules, $missing );
547
548 // Prepend comments indicating exceptions
549 $response = $errors . $response;
550
551 // Capture any PHP warnings from the output buffer and append them to the
552 // response in a comment if we're in debug mode.
553 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
554 $response = self::makeComment( $warnings ) . $response;
555 $this->hasErrors = true;
556 }
557
558 // Save response to file cache unless there are errors
559 if ( isset( $fileCache ) && !$errors && !count( $missing ) ) {
560 // Cache single modules...and other requests if there are enough hits
561 if ( ResourceFileCache::useFileCache( $context ) ) {
562 if ( $fileCache->isCacheWorthy() ) {
563 $fileCache->saveText( $response );
564 } else {
565 $fileCache->incrMissesRecent( $context->getRequest() );
566 }
567 }
568 }
569
570 // Send content type and cache related headers
571 $this->sendResponseHeaders( $context, $mtime, $this->hasErrors );
572
573 // Remove the output buffer and output the response
574 ob_end_clean();
575 echo $response;
576
577 wfProfileOut( __METHOD__ );
578 }
579
580 /**
581 * Send content type and last modified headers to the client.
582 * @param ResourceLoaderContext $context
583 * @param string $mtime TS_MW timestamp to use for last-modified
584 * @param bool $errors Whether there are commented-out errors in the response
585 * @return void
586 */
587 protected function sendResponseHeaders( ResourceLoaderContext $context, $mtime, $errors ) {
588 global $wgResourceLoaderMaxage;
589 // If a version wasn't specified we need a shorter expiry time for updates
590 // to propagate to clients quickly
591 // If there were errors, we also need a shorter expiry time so we can recover quickly
592 if ( is_null( $context->getVersion() ) || $errors ) {
593 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
594 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
595 // If a version was specified we can use a longer expiry time since changing
596 // version numbers causes cache misses
597 } else {
598 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
599 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
600 }
601 if ( $context->getOnly() === 'styles' ) {
602 header( 'Content-Type: text/css; charset=utf-8' );
603 header( 'Access-Control-Allow-Origin: *' );
604 } else {
605 header( 'Content-Type: text/javascript; charset=utf-8' );
606 }
607 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $mtime ) );
608 if ( $context->getDebug() ) {
609 // Do not cache debug responses
610 header( 'Cache-Control: private, no-cache, must-revalidate' );
611 header( 'Pragma: no-cache' );
612 } else {
613 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
614 $exp = min( $maxage, $smaxage );
615 header( 'Expires: ' . wfTimestamp( TS_RFC2822, $exp + time() ) );
616 }
617 }
618
619 /**
620 * Respond with 304 Last Modified if appropiate.
621 *
622 * If there's an If-Modified-Since header, respond with a 304 appropriately
623 * and clear out the output buffer. If the client cache is too old then do nothing.
624 *
625 * @param ResourceLoaderContext $context
626 * @param string $mtime The TS_MW timestamp to check the header against
627 * @return bool True if 304 header sent and output handled
628 */
629 protected function tryRespondLastModified( ResourceLoaderContext $context, $mtime ) {
630 // If there's an If-Modified-Since header, respond with a 304 appropriately
631 // Some clients send "timestamp;length=123". Strip the part after the first ';'
632 // so we get a valid timestamp.
633 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
634 // Never send 304s in debug mode
635 if ( $ims !== false && !$context->getDebug() ) {
636 $imsTS = strtok( $ims, ';' );
637 if ( $mtime <= wfTimestamp( TS_UNIX, $imsTS ) ) {
638 // There's another bug in ob_gzhandler (see also the comment at
639 // the top of this function) that causes it to gzip even empty
640 // responses, meaning it's impossible to produce a truly empty
641 // response (because the gzip header is always there). This is
642 // a problem because 304 responses have to be completely empty
643 // per the HTTP spec, and Firefox behaves buggily when they're not.
644 // See also http://bugs.php.net/bug.php?id=51579
645 // To work around this, we tear down all output buffering before
646 // sending the 304.
647 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
648
649 header( 'HTTP/1.0 304 Not Modified' );
650 header( 'Status: 304 Not Modified' );
651 return true;
652 }
653 }
654 return false;
655 }
656
657 /**
658 * Send out code for a response from file cache if possible.
659 *
660 * @param ResourceFileCache $fileCache Cache object for this request URL
661 * @param ResourceLoaderContext $context Context in which to generate a response
662 * @return bool If this found a cache file and handled the response
663 */
664 protected function tryRespondFromFileCache(
665 ResourceFileCache $fileCache, ResourceLoaderContext $context
666 ) {
667 global $wgResourceLoaderMaxage;
668 // Buffer output to catch warnings.
669 ob_start();
670 // Get the maximum age the cache can be
671 $maxage = is_null( $context->getVersion() )
672 ? $wgResourceLoaderMaxage['unversioned']['server']
673 : $wgResourceLoaderMaxage['versioned']['server'];
674 // Minimum timestamp the cache file must have
675 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW, time() - $maxage ) );
676 if ( !$good ) {
677 try { // RL always hits the DB on file cache miss...
678 wfGetDB( DB_SLAVE );
679 } catch ( DBConnectionError $e ) { // ...check if we need to fallback to cache
680 $good = $fileCache->isCacheGood(); // cache existence check
681 }
682 }
683 if ( $good ) {
684 $ts = $fileCache->cacheTimestamp();
685 // Send content type and cache headers
686 $this->sendResponseHeaders( $context, $ts, false );
687 // If there's an If-Modified-Since header, respond with a 304 appropriately
688 if ( $this->tryRespondLastModified( $context, $ts ) ) {
689 return false; // output handled (buffers cleared)
690 }
691 $response = $fileCache->fetchText();
692 // Capture any PHP warnings from the output buffer and append them to the
693 // response in a comment if we're in debug mode.
694 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
695 $response = "/*\n$warnings\n*/\n" . $response;
696 }
697 // Remove the output buffer and output the response
698 ob_end_clean();
699 echo $response . "\n/* Cached {$ts} */";
700 return true; // cache hit
701 }
702 // Clear buffer
703 ob_end_clean();
704
705 return false; // cache miss
706 }
707
708 /**
709 * Generate a CSS or JS comment block.
710 *
711 * Only use this for public data, not error message details.
712 *
713 * @param string $text
714 * @return string
715 */
716 public static function makeComment( $text ) {
717 $encText = str_replace( '*/', '* /', $text );
718 return "/*\n$encText\n*/\n";
719 }
720
721 /**
722 * Handle exception display.
723 *
724 * @param Exception $e Exception to be shown to the user
725 * @return string Sanitized text that can be returned to the user
726 */
727 public static function formatException( $e ) {
728 global $wgShowExceptionDetails;
729
730 if ( $wgShowExceptionDetails ) {
731 return self::makeComment( $e->__toString() );
732 } else {
733 return self::makeComment( wfMessage( 'internalerror' )->text() );
734 }
735 }
736
737 /**
738 * Generate code for a response.
739 *
740 * @param ResourceLoaderContext $context Context in which to generate a response
741 * @param array $modules List of module objects keyed by module name
742 * @param array $missing List of requested module names that are unregistered (optional)
743 * @return string Response data
744 */
745 public function makeModuleResponse( ResourceLoaderContext $context,
746 array $modules, array $missing = array()
747 ) {
748 $out = '';
749 $exceptions = '';
750 $states = array();
751
752 if ( !count( $modules ) && !count( $missing ) ) {
753 return "/* This file is the Web entry point for MediaWiki's ResourceLoader:
754 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
755 no modules were requested. Max made me put this here. */";
756 }
757
758 wfProfileIn( __METHOD__ );
759
760 // Pre-fetch blobs
761 if ( $context->shouldIncludeMessages() ) {
762 try {
763 $blobs = MessageBlobStore::get( $this, $modules, $context->getLanguage() );
764 } catch ( Exception $e ) {
765 MWExceptionHandler::logException( $e );
766 wfDebugLog( 'resourceloader', __METHOD__ . ": pre-fetching blobs from MessageBlobStore failed: $e" );
767 $this->hasErrors = true;
768 // Add exception to the output as a comment
769 $exceptions .= self::formatException( $e );
770 }
771 } else {
772 $blobs = array();
773 }
774
775 foreach ( $missing as $name ) {
776 $states[$name] = 'missing';
777 }
778
779 // Generate output
780 $isRaw = false;
781 foreach ( $modules as $name => $module ) {
782 /**
783 * @var $module ResourceLoaderModule
784 */
785
786 wfProfileIn( __METHOD__ . '-' . $name );
787 try {
788 $scripts = '';
789 if ( $context->shouldIncludeScripts() ) {
790 // If we are in debug mode, we'll want to return an array of URLs if possible
791 // However, we can't do this if the module doesn't support it
792 // We also can't do this if there is an only= parameter, because we have to give
793 // the module a way to return a load.php URL without causing an infinite loop
794 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
795 $scripts = $module->getScriptURLsForDebug( $context );
796 } else {
797 $scripts = $module->getScript( $context );
798 // rtrim() because there are usually a few line breaks after the last ';'.
799 // A new line at EOF, a new line added by ResourceLoaderFileModule::readScriptFiles, etc.
800 if ( is_string( $scripts ) && strlen( $scripts ) && substr( rtrim( $scripts ), -1 ) !== ';' ) {
801 // Append semicolon to prevent weird bugs caused by files not
802 // terminating their statements right (bug 27054)
803 $scripts .= ";\n";
804 }
805 }
806 }
807 // Styles
808 $styles = array();
809 if ( $context->shouldIncludeStyles() ) {
810 // Don't create empty stylesheets like array( '' => '' ) for modules
811 // that don't *have* any stylesheets (bug 38024).
812 $stylePairs = $module->getStyles( $context );
813 if ( count ( $stylePairs ) ) {
814 // If we are in debug mode without &only= set, we'll want to return an array of URLs
815 // See comment near shouldIncludeScripts() for more details
816 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
817 $styles = array(
818 'url' => $module->getStyleURLsForDebug( $context )
819 );
820 } else {
821 // Minify CSS before embedding in mw.loader.implement call
822 // (unless in debug mode)
823 if ( !$context->getDebug() ) {
824 foreach ( $stylePairs as $media => $style ) {
825 // Can be either a string or an array of strings.
826 if ( is_array( $style ) ) {
827 $stylePairs[$media] = array();
828 foreach ( $style as $cssText ) {
829 if ( is_string( $cssText ) ) {
830 $stylePairs[$media][] = $this->filter( 'minify-css', $cssText );
831 }
832 }
833 } elseif ( is_string( $style ) ) {
834 $stylePairs[$media] = $this->filter( 'minify-css', $style );
835 }
836 }
837 }
838 // Wrap styles into @media groups as needed and flatten into a numerical array
839 $styles = array(
840 'css' => self::makeCombinedStyles( $stylePairs )
841 );
842 }
843 }
844 }
845
846 // Messages
847 $messagesBlob = isset( $blobs[$name] ) ? $blobs[$name] : '{}';
848
849 // Append output
850 switch ( $context->getOnly() ) {
851 case 'scripts':
852 if ( is_string( $scripts ) ) {
853 // Load scripts raw...
854 $out .= $scripts;
855 } elseif ( is_array( $scripts ) ) {
856 // ...except when $scripts is an array of URLs
857 $out .= self::makeLoaderImplementScript( $name, $scripts, array(), array() );
858 }
859 break;
860 case 'styles':
861 // We no longer seperate into media, they are all combined now with
862 // custom media type groups into @media .. {} sections as part of the css string.
863 // Module returns either an empty array or a numerical array with css strings.
864 $out .= isset( $styles['css'] ) ? implode( '', $styles['css'] ) : '';
865 break;
866 case 'messages':
867 $out .= self::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
868 break;
869 default:
870 $out .= self::makeLoaderImplementScript(
871 $name,
872 $scripts,
873 $styles,
874 new XmlJsCode( $messagesBlob )
875 );
876 break;
877 }
878 } catch ( Exception $e ) {
879 MWExceptionHandler::logException( $e );
880 wfDebugLog( 'resourceloader', __METHOD__ . ": generating module package failed: $e" );
881 $this->hasErrors = true;
882 // Add exception to the output as a comment
883 $exceptions .= self::formatException( $e );
884
885 // Respond to client with error-state instead of module implementation
886 $states[$name] = 'error';
887 unset( $modules[$name] );
888 }
889 $isRaw |= $module->isRaw();
890 wfProfileOut( __METHOD__ . '-' . $name );
891 }
892
893 // Update module states
894 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
895 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
896 // Set the state of modules loaded as only scripts to ready as
897 // they don't have an mw.loader.implement wrapper that sets the state
898 foreach ( $modules as $name => $module ) {
899 $states[$name] = 'ready';
900 }
901 }
902
903 // Set the state of modules we didn't respond to with mw.loader.implement
904 if ( count( $states ) ) {
905 $out .= self::makeLoaderStateScript( $states );
906 }
907 }
908
909 if ( !$context->getDebug() ) {
910 if ( $context->getOnly() === 'styles' ) {
911 $out = $this->filter( 'minify-css', $out );
912 } else {
913 $out = $this->filter( 'minify-js', $out );
914 }
915 }
916
917 wfProfileOut( __METHOD__ );
918 return $exceptions . $out;
919 }
920
921 /* Static Methods */
922
923 /**
924 * Return JS code that calls mw.loader.implement with given module properties.
925 *
926 * @param string $name Module name
927 * @param mixed $scripts List of URLs to JavaScript files or String of JavaScript code
928 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
929 * to CSS files keyed by media type
930 * @param mixed $messages List of messages associated with this module. May either be an
931 * associative array mapping message key to value, or a JSON-encoded message blob containing
932 * the same data, wrapped in an XmlJsCode object.
933 * @throws MWException
934 * @return string
935 */
936 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
937 if ( is_string( $scripts ) ) {
938 $scripts = new XmlJsCode( "function ( $, jQuery ) {\n{$scripts}\n}" );
939 } elseif ( !is_array( $scripts ) ) {
940 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
941 }
942 return Xml::encodeJsCall(
943 'mw.loader.implement',
944 array(
945 $name,
946 $scripts,
947 // Force objects. mw.loader.implement requires them to be javascript objects.
948 // Although these variables are associative arrays, which become javascript
949 // objects through json_encode. In many cases they will be empty arrays, and
950 // PHP/json_encode() consider empty arrays to be numerical arrays and
951 // output javascript "[]" instead of "{}". This fixes that.
952 (object)$styles,
953 (object)$messages
954 ),
955 ResourceLoader::inDebugMode()
956 );
957 }
958
959 /**
960 * Returns JS code which, when called, will register a given list of messages.
961 *
962 * @param mixed $messages Either an associative array mapping message key to value, or a
963 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
964 * @return string
965 */
966 public static function makeMessageSetScript( $messages ) {
967 return Xml::encodeJsCall(
968 'mw.messages.set',
969 array( (object)$messages ),
970 ResourceLoader::inDebugMode()
971 );
972 }
973
974 /**
975 * Combines an associative array mapping media type to CSS into a
976 * single stylesheet with "@media" blocks.
977 *
978 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
979 * @return array
980 */
981 private static function makeCombinedStyles( array $stylePairs ) {
982 $out = array();
983 foreach ( $stylePairs as $media => $styles ) {
984 // ResourceLoaderFileModule::getStyle can return the styles
985 // as a string or an array of strings. This is to allow separation in
986 // the front-end.
987 $styles = (array)$styles;
988 foreach ( $styles as $style ) {
989 $style = trim( $style );
990 // Don't output an empty "@media print { }" block (bug 40498)
991 if ( $style !== '' ) {
992 // Transform the media type based on request params and config
993 // The way that this relies on $wgRequest to propagate request params is slightly evil
994 $media = OutputPage::transformCssMedia( $media );
995
996 if ( $media === '' || $media == 'all' ) {
997 $out[] = $style;
998 } elseif ( is_string( $media ) ) {
999 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1000 }
1001 // else: skip
1002 }
1003 }
1004 }
1005 return $out;
1006 }
1007
1008 /**
1009 * Returns a JS call to mw.loader.state, which sets the state of a
1010 * module or modules to a given value. Has two calling conventions:
1011 *
1012 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1013 * Set the state of a single module called $name to $state
1014 *
1015 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
1016 * Set the state of modules with the given names to the given states
1017 *
1018 * @param string $name
1019 * @param string $state
1020 * @return string
1021 */
1022 public static function makeLoaderStateScript( $name, $state = null ) {
1023 if ( is_array( $name ) ) {
1024 return Xml::encodeJsCall(
1025 'mw.loader.state',
1026 array( $name ),
1027 ResourceLoader::inDebugMode()
1028 );
1029 } else {
1030 return Xml::encodeJsCall(
1031 'mw.loader.state',
1032 array( $name, $state ),
1033 ResourceLoader::inDebugMode()
1034 );
1035 }
1036 }
1037
1038 /**
1039 * Returns JS code which calls the script given by $script. The script will
1040 * be called with local variables name, version, dependencies and group,
1041 * which will have values corresponding to $name, $version, $dependencies
1042 * and $group as supplied.
1043 *
1044 * @param string $name Module name
1045 * @param int $version Module version number as a timestamp
1046 * @param array $dependencies List of module names on which this module depends
1047 * @param string $group Group which the module is in.
1048 * @param string $source Source of the module, or 'local' if not foreign.
1049 * @param string $script JavaScript code
1050 * @return string
1051 */
1052 public static function makeCustomLoaderScript( $name, $version, $dependencies, $group, $source, $script ) {
1053 $script = str_replace( "\n", "\n\t", trim( $script ) );
1054 return Xml::encodeJsCall(
1055 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1056 array( $name, $version, $dependencies, $group, $source ),
1057 ResourceLoader::inDebugMode()
1058 );
1059 }
1060
1061 /**
1062 * Returns JS code which calls mw.loader.register with the given
1063 * parameters. Has three calling conventions:
1064 *
1065 * - ResourceLoader::makeLoaderRegisterScript( $name, $version, $dependencies, $group, $source ):
1066 * Register a single module.
1067 *
1068 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
1069 * Register modules with the given names.
1070 *
1071 * - ResourceLoader::makeLoaderRegisterScript( array(
1072 * array( $name1, $version1, $dependencies1, $group1, $source1 ),
1073 * array( $name2, $version2, $dependencies1, $group2, $source2 ),
1074 * ...
1075 * ) ):
1076 * Registers modules with the given names and parameters.
1077 *
1078 * @param string $name Module name
1079 * @param int $version Module version number as a timestamp
1080 * @param array $dependencies List of module names on which this module depends
1081 * @param string $group Group which the module is in
1082 * @param string $source Source of the module, or 'local' if not foreign
1083 * @return string
1084 */
1085 public static function makeLoaderRegisterScript( $name, $version = null,
1086 $dependencies = null, $group = null, $source = null
1087 ) {
1088 if ( is_array( $name ) ) {
1089 return Xml::encodeJsCall(
1090 'mw.loader.register',
1091 array( $name ),
1092 ResourceLoader::inDebugMode()
1093 );
1094 } else {
1095 $version = (int)$version > 1 ? (int)$version : 1;
1096 return Xml::encodeJsCall(
1097 'mw.loader.register',
1098 array( $name, $version, $dependencies, $group, $source ),
1099 ResourceLoader::inDebugMode()
1100 );
1101 }
1102 }
1103
1104 /**
1105 * Returns JS code which calls mw.loader.addSource() with the given
1106 * parameters. Has two calling conventions:
1107 *
1108 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1109 * Register a single source
1110 *
1111 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $props1, $id2 => $props2, ... ) );
1112 * Register sources with the given IDs and properties.
1113 *
1114 * @param string $id Source ID
1115 * @param array $properties Source properties (see addSource())
1116 * @return string
1117 */
1118 public static function makeLoaderSourcesScript( $id, $properties = null ) {
1119 if ( is_array( $id ) ) {
1120 return Xml::encodeJsCall(
1121 'mw.loader.addSource',
1122 array( $id ),
1123 ResourceLoader::inDebugMode()
1124 );
1125 } else {
1126 return Xml::encodeJsCall(
1127 'mw.loader.addSource',
1128 array( $id, $properties ),
1129 ResourceLoader::inDebugMode()
1130 );
1131 }
1132 }
1133
1134 /**
1135 * Returns JS code which runs given JS code if the client-side framework is
1136 * present.
1137 *
1138 * @param string $script JavaScript code
1139 * @return string
1140 */
1141 public static function makeLoaderConditionalScript( $script ) {
1142 return "if(window.mw){\n" . trim( $script ) . "\n}";
1143 }
1144
1145 /**
1146 * Returns JS code which will set the MediaWiki configuration array to
1147 * the given value.
1148 *
1149 * @param array $configuration List of configuration values keyed by variable name
1150 * @return string
1151 */
1152 public static function makeConfigSetScript( array $configuration ) {
1153 return Xml::encodeJsCall(
1154 'mw.config.set',
1155 array( $configuration ),
1156 ResourceLoader::inDebugMode()
1157 );
1158 }
1159
1160 /**
1161 * Convert an array of module names to a packed query string.
1162 *
1163 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
1164 * becomes 'foo.bar,baz|bar.baz,quux'
1165 * @param array $modules List of module names (strings)
1166 * @return string Packed query string
1167 */
1168 public static function makePackedModulesString( $modules ) {
1169 $groups = array(); // array( prefix => array( suffixes ) )
1170 foreach ( $modules as $module ) {
1171 $pos = strrpos( $module, '.' );
1172 $prefix = $pos === false ? '' : substr( $module, 0, $pos );
1173 $suffix = $pos === false ? $module : substr( $module, $pos + 1 );
1174 $groups[$prefix][] = $suffix;
1175 }
1176
1177 $arr = array();
1178 foreach ( $groups as $prefix => $suffixes ) {
1179 $p = $prefix === '' ? '' : $prefix . '.';
1180 $arr[] = $p . implode( ',', $suffixes );
1181 }
1182 $str = implode( '|', $arr );
1183 return $str;
1184 }
1185
1186 /**
1187 * Determine whether debug mode was requested
1188 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1189 * @return bool
1190 */
1191 public static function inDebugMode() {
1192 global $wgRequest, $wgResourceLoaderDebug;
1193 static $retval = null;
1194 if ( is_null( $retval ) ) {
1195 $retval = $wgRequest->getFuzzyBool( 'debug',
1196 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug ) );
1197 }
1198 return $retval;
1199 }
1200
1201 /**
1202 * Build a load.php URL
1203 * @param array $modules Array of module names (strings)
1204 * @param string $lang Language code
1205 * @param string $skin Skin name
1206 * @param string|null $user User name. If null, the &user= parameter is omitted
1207 * @param string|null $version Versioning timestamp
1208 * @param bool $debug Whether the request should be in debug mode
1209 * @param string|null $only &only= parameter
1210 * @param bool $printable Printable mode
1211 * @param bool $handheld Handheld mode
1212 * @param array $extraQuery Extra query parameters to add
1213 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1214 */
1215 public static function makeLoaderURL( $modules, $lang, $skin, $user = null, $version = null, $debug = false, $only = null,
1216 $printable = false, $handheld = false, $extraQuery = array() ) {
1217 global $wgLoadScript;
1218 $query = self::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
1219 $only, $printable, $handheld, $extraQuery
1220 );
1221
1222 // Prevent the IE6 extension check from being triggered (bug 28840)
1223 // by appending a character that's invalid in Windows extensions ('*')
1224 return wfExpandUrl( wfAppendQuery( $wgLoadScript, $query ) . '&*', PROTO_RELATIVE );
1225 }
1226
1227 /**
1228 * Build a query array (array representation of query string) for load.php. Helper
1229 * function for makeLoaderURL().
1230 *
1231 * @param array $modules
1232 * @param string $lang
1233 * @param string $skin
1234 * @param string $user
1235 * @param string $version
1236 * @param bool $debug
1237 * @param string $only
1238 * @param bool $printable
1239 * @param bool $handheld
1240 * @param array $extraQuery
1241 *
1242 * @return array
1243 */
1244 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null, $version = null, $debug = false, $only = null,
1245 $printable = false, $handheld = false, $extraQuery = array() ) {
1246 $query = array(
1247 'modules' => self::makePackedModulesString( $modules ),
1248 'lang' => $lang,
1249 'skin' => $skin,
1250 'debug' => $debug ? 'true' : 'false',
1251 );
1252 if ( $user !== null ) {
1253 $query['user'] = $user;
1254 }
1255 if ( $version !== null ) {
1256 $query['version'] = $version;
1257 }
1258 if ( $only !== null ) {
1259 $query['only'] = $only;
1260 }
1261 if ( $printable ) {
1262 $query['printable'] = 1;
1263 }
1264 if ( $handheld ) {
1265 $query['handheld'] = 1;
1266 }
1267 $query += $extraQuery;
1268
1269 // Make queries uniform in order
1270 ksort( $query );
1271 return $query;
1272 }
1273
1274 /**
1275 * Check a module name for validity.
1276 *
1277 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1278 * at most 255 bytes.
1279 *
1280 * @param string $moduleName Module name to check
1281 * @return bool Whether $moduleName is a valid module name
1282 */
1283 public static function isValidModuleName( $moduleName ) {
1284 return !preg_match( '/[|,!]/', $moduleName ) && strlen( $moduleName ) <= 255;
1285 }
1286
1287 /**
1288 * Returns LESS compiler set up for use with MediaWiki
1289 *
1290 * @since 1.22
1291 * @return lessc
1292 */
1293 public static function getLessCompiler() {
1294 global $wgResourceLoaderLESSFunctions, $wgResourceLoaderLESSImportPaths;
1295
1296 // When called from the installer, it is possible that a required PHP extension
1297 // is missing (at least for now; see bug 47564). If this is the case, throw an
1298 // exception (caught by the installer) to prevent a fatal error later on.
1299 if ( !function_exists( 'ctype_digit' ) ) {
1300 throw new MWException( 'lessc requires the Ctype extension' );
1301 }
1302
1303 $less = new lessc();
1304 $less->setPreserveComments( true );
1305 $less->setVariables( self::getLESSVars() );
1306 $less->setImportDir( $wgResourceLoaderLESSImportPaths );
1307 foreach ( $wgResourceLoaderLESSFunctions as $name => $func ) {
1308 $less->registerFunction( $name, $func );
1309 }
1310 return $less;
1311 }
1312
1313 /**
1314 * Get global LESS variables.
1315 *
1316 * $since 1.22
1317 * @return array Map of variable names to string CSS values.
1318 */
1319 public static function getLESSVars() {
1320 global $wgResourceLoaderLESSVars;
1321
1322 $lessVars = $wgResourceLoaderLESSVars;
1323 // Sort by key to ensure consistent hashing for cache lookups.
1324 ksort( $lessVars );
1325 return $lessVars;
1326 }
1327 }