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