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