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