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