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