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