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