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