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