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