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