5ac874d2f14fd4b141b9af7936a687d5eab867d9
[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 * Output a response to a load request, including the content-type header.
462 *
463 * @param ResourceLoaderContext $context Context in which a response should be formed
464 */
465 public function respond( ResourceLoaderContext $context ) {
466 global $wgCacheEpoch, $wgUseFileCache;
467
468 // Use file cache if enabled and available...
469 if ( $wgUseFileCache ) {
470 $fileCache = ResourceFileCache::newFromContext( $context );
471 if ( $this->tryRespondFromFileCache( $fileCache, $context ) ) {
472 return; // output handled
473 }
474 }
475
476 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
477 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
478 // is used: ob_clean() will clear the GZIP header in that case and it won't come
479 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
480 // the whole thing in our own output buffer to be sure the active buffer
481 // doesn't use ob_gzhandler.
482 // See http://bugs.php.net/bug.php?id=36514
483 ob_start();
484
485 wfProfileIn( __METHOD__ );
486 $errors = '';
487
488 // Find out which modules are missing and instantiate the others
489 $modules = array();
490 $missing = array();
491 foreach ( $context->getModules() as $name ) {
492 $module = $this->getModule( $name );
493 if ( $module ) {
494 // Do not allow private modules to be loaded from the web.
495 // This is a security issue, see bug 34907.
496 if ( $module->getGroup() === 'private' ) {
497 wfDebugLog( 'resourceloader', __METHOD__ . ": request for private module '$name' denied" );
498 $this->hasErrors = true;
499 // Add exception to the output as a comment
500 $errors .= self::makeComment( "Cannot show private module \"$name\"" );
501
502 continue;
503 }
504 $modules[$name] = $module;
505 } else {
506 $missing[] = $name;
507 }
508 }
509
510 // Preload information needed to the mtime calculation below
511 try {
512 $this->preloadModuleInfo( array_keys( $modules ), $context );
513 } catch ( Exception $e ) {
514 MWExceptionHandler::logException( $e );
515 wfDebugLog( 'resourceloader', __METHOD__ . ": preloading module info failed: $e" );
516 $this->hasErrors = true;
517 // Add exception to the output as a comment
518 $errors .= self::formatException( $e );
519 }
520
521 wfProfileIn( __METHOD__ . '-getModifiedTime' );
522
523 // To send Last-Modified and support If-Modified-Since, we need to detect
524 // the last modified time
525 $mtime = wfTimestamp( TS_UNIX, $wgCacheEpoch );
526 foreach ( $modules as $module ) {
527 /**
528 * @var $module ResourceLoaderModule
529 */
530 try {
531 // Calculate maximum modified time
532 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
533 } catch ( Exception $e ) {
534 MWExceptionHandler::logException( $e );
535 wfDebugLog( 'resourceloader', __METHOD__ . ": calculating maximum modified time failed: $e" );
536 $this->hasErrors = true;
537 // Add exception to the output as a comment
538 $errors .= self::formatException( $e );
539 }
540 }
541
542 wfProfileOut( __METHOD__ . '-getModifiedTime' );
543
544 // If there's an If-Modified-Since header, respond with a 304 appropriately
545 if ( $this->tryRespondLastModified( $context, $mtime ) ) {
546 wfProfileOut( __METHOD__ );
547 return; // output handled (buffers cleared)
548 }
549
550 // Generate a response
551 $response = $this->makeModuleResponse( $context, $modules, $missing );
552
553 // Prepend comments indicating exceptions
554 $response = $errors . $response;
555
556 // Capture any PHP warnings from the output buffer and append them to the
557 // response in a comment if we're in debug mode.
558 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
559 $response = self::makeComment( $warnings ) . $response;
560 $this->hasErrors = true;
561 }
562
563 // Save response to file cache unless there are errors
564 if ( isset( $fileCache ) && !$errors && !count( $missing ) ) {
565 // Cache single modules...and other requests if there are enough hits
566 if ( ResourceFileCache::useFileCache( $context ) ) {
567 if ( $fileCache->isCacheWorthy() ) {
568 $fileCache->saveText( $response );
569 } else {
570 $fileCache->incrMissesRecent( $context->getRequest() );
571 }
572 }
573 }
574
575 // Send content type and cache related headers
576 $this->sendResponseHeaders( $context, $mtime, $this->hasErrors );
577
578 // Remove the output buffer and output the response
579 ob_end_clean();
580 echo $response;
581
582 wfProfileOut( __METHOD__ );
583 }
584
585 /**
586 * Send content type and last modified headers to the client.
587 * @param ResourceLoaderContext $context
588 * @param string $mtime TS_MW timestamp to use for last-modified
589 * @param bool $errors Whether there are commented-out errors in the response
590 * @return void
591 */
592 protected function sendResponseHeaders( ResourceLoaderContext $context, $mtime, $errors ) {
593 global $wgResourceLoaderMaxage;
594 // If a version wasn't specified we need a shorter expiry time for updates
595 // to propagate to clients quickly
596 // If there were errors, we also need a shorter expiry time so we can recover quickly
597 if ( is_null( $context->getVersion() ) || $errors ) {
598 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
599 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
600 // If a version was specified we can use a longer expiry time since changing
601 // version numbers causes cache misses
602 } else {
603 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
604 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
605 }
606 if ( $context->getOnly() === 'styles' ) {
607 header( 'Content-Type: text/css; charset=utf-8' );
608 header( 'Access-Control-Allow-Origin: *' );
609 } else {
610 header( 'Content-Type: text/javascript; charset=utf-8' );
611 }
612 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $mtime ) );
613 if ( $context->getDebug() ) {
614 // Do not cache debug responses
615 header( 'Cache-Control: private, no-cache, must-revalidate' );
616 header( 'Pragma: no-cache' );
617 } else {
618 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
619 $exp = min( $maxage, $smaxage );
620 header( 'Expires: ' . wfTimestamp( TS_RFC2822, $exp + time() ) );
621 }
622 }
623
624 /**
625 * Respond with 304 Last Modified if appropiate.
626 *
627 * If there's an If-Modified-Since header, respond with a 304 appropriately
628 * and clear out the output buffer. If the client cache is too old then do nothing.
629 *
630 * @param ResourceLoaderContext $context
631 * @param string $mtime The TS_MW timestamp to check the header against
632 * @return bool True if 304 header sent and output handled
633 */
634 protected function tryRespondLastModified( ResourceLoaderContext $context, $mtime ) {
635 // If there's an If-Modified-Since header, respond with a 304 appropriately
636 // Some clients send "timestamp;length=123". Strip the part after the first ';'
637 // so we get a valid timestamp.
638 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
639 // Never send 304s in debug mode
640 if ( $ims !== false && !$context->getDebug() ) {
641 $imsTS = strtok( $ims, ';' );
642 if ( $mtime <= wfTimestamp( TS_UNIX, $imsTS ) ) {
643 // There's another bug in ob_gzhandler (see also the comment at
644 // the top of this function) that causes it to gzip even empty
645 // responses, meaning it's impossible to produce a truly empty
646 // response (because the gzip header is always there). This is
647 // a problem because 304 responses have to be completely empty
648 // per the HTTP spec, and Firefox behaves buggily when they're not.
649 // See also http://bugs.php.net/bug.php?id=51579
650 // To work around this, we tear down all output buffering before
651 // sending the 304.
652 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
653
654 header( 'HTTP/1.0 304 Not Modified' );
655 header( 'Status: 304 Not Modified' );
656 return true;
657 }
658 }
659 return false;
660 }
661
662 /**
663 * Send out code for a response from file cache if possible.
664 *
665 * @param ResourceFileCache $fileCache Cache object for this request URL
666 * @param ResourceLoaderContext $context Context in which to generate a response
667 * @return bool If this found a cache file and handled the response
668 */
669 protected function tryRespondFromFileCache(
670 ResourceFileCache $fileCache, ResourceLoaderContext $context
671 ) {
672 global $wgResourceLoaderMaxage;
673 // Buffer output to catch warnings.
674 ob_start();
675 // Get the maximum age the cache can be
676 $maxage = is_null( $context->getVersion() )
677 ? $wgResourceLoaderMaxage['unversioned']['server']
678 : $wgResourceLoaderMaxage['versioned']['server'];
679 // Minimum timestamp the cache file must have
680 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW, time() - $maxage ) );
681 if ( !$good ) {
682 try { // RL always hits the DB on file cache miss...
683 wfGetDB( DB_SLAVE );
684 } catch ( DBConnectionError $e ) { // ...check if we need to fallback to cache
685 $good = $fileCache->isCacheGood(); // cache existence check
686 }
687 }
688 if ( $good ) {
689 $ts = $fileCache->cacheTimestamp();
690 // Send content type and cache headers
691 $this->sendResponseHeaders( $context, $ts, false );
692 // If there's an If-Modified-Since header, respond with a 304 appropriately
693 if ( $this->tryRespondLastModified( $context, $ts ) ) {
694 return false; // output handled (buffers cleared)
695 }
696 $response = $fileCache->fetchText();
697 // Capture any PHP warnings from the output buffer and append them to the
698 // response in a comment if we're in debug mode.
699 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
700 $response = "/*\n$warnings\n*/\n" . $response;
701 }
702 // Remove the output buffer and output the response
703 ob_end_clean();
704 echo $response . "\n/* Cached {$ts} */";
705 return true; // cache hit
706 }
707 // Clear buffer
708 ob_end_clean();
709
710 return false; // cache miss
711 }
712
713 /**
714 * Generate a CSS or JS comment block.
715 *
716 * Only use this for public data, not error message details.
717 *
718 * @param string $text
719 * @return string
720 */
721 public static function makeComment( $text ) {
722 $encText = str_replace( '*/', '* /', $text );
723 return "/*\n$encText\n*/\n";
724 }
725
726 /**
727 * Handle exception display.
728 *
729 * @param Exception $e Exception to be shown to the user
730 * @return string Sanitized text that can be returned to the user
731 */
732 public static function formatException( $e ) {
733 global $wgShowExceptionDetails;
734
735 if ( $wgShowExceptionDetails ) {
736 return self::makeComment( $e->__toString() );
737 } else {
738 return self::makeComment( wfMessage( 'internalerror' )->text() );
739 }
740 }
741
742 /**
743 * Generate code for a response.
744 *
745 * @param ResourceLoaderContext $context Context in which to generate a response
746 * @param array $modules List of module objects keyed by module name
747 * @param array $missing List of requested module names that are unregistered (optional)
748 * @return string Response data
749 */
750 public function makeModuleResponse( ResourceLoaderContext $context,
751 array $modules, array $missing = array()
752 ) {
753 $out = '';
754 $exceptions = '';
755 $states = array();
756
757 if ( !count( $modules ) && !count( $missing ) ) {
758 return "/* This file is the Web entry point for MediaWiki's ResourceLoader:
759 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
760 no modules were requested. Max made me put this here. */";
761 }
762
763 wfProfileIn( __METHOD__ );
764
765 // Pre-fetch blobs
766 if ( $context->shouldIncludeMessages() ) {
767 try {
768 $blobs = MessageBlobStore::get( $this, $modules, $context->getLanguage() );
769 } catch ( Exception $e ) {
770 MWExceptionHandler::logException( $e );
771 wfDebugLog(
772 'resourceloader',
773 __METHOD__ . ": pre-fetching blobs from MessageBlobStore failed: $e"
774 );
775 $this->hasErrors = true;
776 // Add exception to the output as a comment
777 $exceptions .= self::formatException( $e );
778 }
779 } else {
780 $blobs = array();
781 }
782
783 foreach ( $missing as $name ) {
784 $states[$name] = 'missing';
785 }
786
787 // Generate output
788 $isRaw = false;
789 foreach ( $modules as $name => $module ) {
790 /**
791 * @var $module ResourceLoaderModule
792 */
793
794 wfProfileIn( __METHOD__ . '-' . $name );
795 try {
796 $scripts = '';
797 if ( $context->shouldIncludeScripts() ) {
798 // If we are in debug mode, we'll want to return an array of URLs if possible
799 // However, we can't do this if the module doesn't support it
800 // We also can't do this if there is an only= parameter, because we have to give
801 // the module a way to return a load.php URL without causing an infinite loop
802 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
803 $scripts = $module->getScriptURLsForDebug( $context );
804 } else {
805 $scripts = $module->getScript( $context );
806 // rtrim() because there are usually a few line breaks
807 // after the last ';'. A new line at EOF, a new line
808 // added by ResourceLoaderFileModule::readScriptFiles, etc.
809 if ( is_string( $scripts )
810 && strlen( $scripts )
811 && substr( rtrim( $scripts ), -1 ) !== ';'
812 ) {
813 // Append semicolon to prevent weird bugs caused by files not
814 // terminating their statements right (bug 27054)
815 $scripts .= ";\n";
816 }
817 }
818 }
819 // Styles
820 $styles = array();
821 if ( $context->shouldIncludeStyles() ) {
822 // Don't create empty stylesheets like array( '' => '' ) for modules
823 // that don't *have* any stylesheets (bug 38024).
824 $stylePairs = $module->getStyles( $context );
825 if ( count( $stylePairs ) ) {
826 // If we are in debug mode without &only= set, we'll want to return an array of URLs
827 // See comment near shouldIncludeScripts() for more details
828 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
829 $styles = array(
830 'url' => $module->getStyleURLsForDebug( $context )
831 );
832 } else {
833 // Minify CSS before embedding in mw.loader.implement call
834 // (unless in debug mode)
835 if ( !$context->getDebug() ) {
836 foreach ( $stylePairs as $media => $style ) {
837 // Can be either a string or an array of strings.
838 if ( is_array( $style ) ) {
839 $stylePairs[$media] = array();
840 foreach ( $style as $cssText ) {
841 if ( is_string( $cssText ) ) {
842 $stylePairs[$media][] = $this->filter( 'minify-css', $cssText );
843 }
844 }
845 } elseif ( is_string( $style ) ) {
846 $stylePairs[$media] = $this->filter( 'minify-css', $style );
847 }
848 }
849 }
850 // Wrap styles into @media groups as needed and flatten into a numerical array
851 $styles = array(
852 'css' => self::makeCombinedStyles( $stylePairs )
853 );
854 }
855 }
856 }
857
858 // Messages
859 $messagesBlob = isset( $blobs[$name] ) ? $blobs[$name] : '{}';
860
861 // Append output
862 switch ( $context->getOnly() ) {
863 case 'scripts':
864 if ( is_string( $scripts ) ) {
865 // Load scripts raw...
866 $out .= $scripts;
867 } elseif ( is_array( $scripts ) ) {
868 // ...except when $scripts is an array of URLs
869 $out .= self::makeLoaderImplementScript( $name, $scripts, array(), array() );
870 }
871 break;
872 case 'styles':
873 // We no longer seperate into media, they are all combined now with
874 // custom media type groups into @media .. {} sections as part of the css string.
875 // Module returns either an empty array or a numerical array with css strings.
876 $out .= isset( $styles['css'] ) ? implode( '', $styles['css'] ) : '';
877 break;
878 case 'messages':
879 $out .= self::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
880 break;
881 default:
882 $out .= self::makeLoaderImplementScript(
883 $name,
884 $scripts,
885 $styles,
886 new XmlJsCode( $messagesBlob )
887 );
888 break;
889 }
890 } catch ( Exception $e ) {
891 MWExceptionHandler::logException( $e );
892 wfDebugLog( 'resourceloader', __METHOD__ . ": generating module package failed: $e" );
893 $this->hasErrors = true;
894 // Add exception to the output as a comment
895 $exceptions .= self::formatException( $e );
896
897 // Respond to client with error-state instead of module implementation
898 $states[$name] = 'error';
899 unset( $modules[$name] );
900 }
901 $isRaw |= $module->isRaw();
902 wfProfileOut( __METHOD__ . '-' . $name );
903 }
904
905 // Update module states
906 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
907 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
908 // Set the state of modules loaded as only scripts to ready as
909 // they don't have an mw.loader.implement wrapper that sets the state
910 foreach ( $modules as $name => $module ) {
911 $states[$name] = 'ready';
912 }
913 }
914
915 // Set the state of modules we didn't respond to with mw.loader.implement
916 if ( count( $states ) ) {
917 $out .= self::makeLoaderStateScript( $states );
918 }
919 } else {
920 if ( count( $states ) ) {
921 $exceptions .= self::makeComment(
922 'Problematic modules: ' . FormatJson::encode( $states, ResourceLoader::inDebugMode() )
923 );
924 }
925 }
926
927 if ( !$context->getDebug() ) {
928 if ( $context->getOnly() === 'styles' ) {
929 $out = $this->filter( 'minify-css', $out );
930 } else {
931 $out = $this->filter( 'minify-js', $out );
932 }
933 }
934
935 wfProfileOut( __METHOD__ );
936 return $exceptions . $out;
937 }
938
939 /* Static Methods */
940
941 /**
942 * Return JS code that calls mw.loader.implement with given module properties.
943 *
944 * @param string $name Module name
945 * @param mixed $scripts List of URLs to JavaScript files or String of JavaScript code
946 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
947 * to CSS files keyed by media type
948 * @param mixed $messages List of messages associated with this module. May either be an
949 * associative array mapping message key to value, or a JSON-encoded message blob containing
950 * the same data, wrapped in an XmlJsCode object.
951 * @throws MWException
952 * @return string
953 */
954 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
955 if ( is_string( $scripts ) ) {
956 $scripts = new XmlJsCode( "function ( $, jQuery ) {\n{$scripts}\n}" );
957 } elseif ( !is_array( $scripts ) ) {
958 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
959 }
960 return Xml::encodeJsCall(
961 'mw.loader.implement',
962 array(
963 $name,
964 $scripts,
965 // Force objects. mw.loader.implement requires them to be javascript objects.
966 // Although these variables are associative arrays, which become javascript
967 // objects through json_encode. In many cases they will be empty arrays, and
968 // PHP/json_encode() consider empty arrays to be numerical arrays and
969 // output javascript "[]" instead of "{}". This fixes that.
970 (object)$styles,
971 (object)$messages
972 ),
973 ResourceLoader::inDebugMode()
974 );
975 }
976
977 /**
978 * Returns JS code which, when called, will register a given list of messages.
979 *
980 * @param mixed $messages Either an associative array mapping message key to value, or a
981 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
982 * @return string
983 */
984 public static function makeMessageSetScript( $messages ) {
985 return Xml::encodeJsCall(
986 'mw.messages.set',
987 array( (object)$messages ),
988 ResourceLoader::inDebugMode()
989 );
990 }
991
992 /**
993 * Combines an associative array mapping media type to CSS into a
994 * single stylesheet with "@media" blocks.
995 *
996 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
997 * @return array
998 */
999 public static function makeCombinedStyles( array $stylePairs ) {
1000 $out = array();
1001 foreach ( $stylePairs as $media => $styles ) {
1002 // ResourceLoaderFileModule::getStyle can return the styles
1003 // as a string or an array of strings. This is to allow separation in
1004 // the front-end.
1005 $styles = (array)$styles;
1006 foreach ( $styles as $style ) {
1007 $style = trim( $style );
1008 // Don't output an empty "@media print { }" block (bug 40498)
1009 if ( $style !== '' ) {
1010 // Transform the media type based on request params and config
1011 // The way that this relies on $wgRequest to propagate request params is slightly evil
1012 $media = OutputPage::transformCssMedia( $media );
1013
1014 if ( $media === '' || $media == 'all' ) {
1015 $out[] = $style;
1016 } elseif ( is_string( $media ) ) {
1017 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1018 }
1019 // else: skip
1020 }
1021 }
1022 }
1023 return $out;
1024 }
1025
1026 /**
1027 * Returns a JS call to mw.loader.state, which sets the state of a
1028 * module or modules to a given value. Has two calling conventions:
1029 *
1030 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1031 * Set the state of a single module called $name to $state
1032 *
1033 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
1034 * Set the state of modules with the given names to the given states
1035 *
1036 * @param string $name
1037 * @param string $state
1038 * @return string
1039 */
1040 public static function makeLoaderStateScript( $name, $state = null ) {
1041 if ( is_array( $name ) ) {
1042 return Xml::encodeJsCall(
1043 'mw.loader.state',
1044 array( $name ),
1045 ResourceLoader::inDebugMode()
1046 );
1047 } else {
1048 return Xml::encodeJsCall(
1049 'mw.loader.state',
1050 array( $name, $state ),
1051 ResourceLoader::inDebugMode()
1052 );
1053 }
1054 }
1055
1056 /**
1057 * Returns JS code which calls the script given by $script. The script will
1058 * be called with local variables name, version, dependencies and group,
1059 * which will have values corresponding to $name, $version, $dependencies
1060 * and $group as supplied.
1061 *
1062 * @param string $name Module name
1063 * @param int $version Module version number as a timestamp
1064 * @param array $dependencies List of module names on which this module depends
1065 * @param string $group Group which the module is in.
1066 * @param string $source Source of the module, or 'local' if not foreign.
1067 * @param string $script JavaScript code
1068 * @return string
1069 */
1070 public static function makeCustomLoaderScript( $name, $version, $dependencies,
1071 $group, $source, $script
1072 ) {
1073 $script = str_replace( "\n", "\n\t", trim( $script ) );
1074 return Xml::encodeJsCall(
1075 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1076 array( $name, $version, $dependencies, $group, $source ),
1077 ResourceLoader::inDebugMode()
1078 );
1079 }
1080
1081 /**
1082 * Returns JS code which calls mw.loader.register with the given
1083 * parameters. Has three calling conventions:
1084 *
1085 * - ResourceLoader::makeLoaderRegisterScript( $name, $version, $dependencies, $group, $source, $skip ):
1086 * Register a single module.
1087 *
1088 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
1089 * Register modules with the given names.
1090 *
1091 * - ResourceLoader::makeLoaderRegisterScript( array(
1092 * array( $name1, $version1, $dependencies1, $group1, $source1, $skip1 ),
1093 * array( $name2, $version2, $dependencies1, $group2, $source2, $skip2 ),
1094 * ...
1095 * ) ):
1096 * Registers modules with the given names and parameters.
1097 *
1098 * @param string $name Module name
1099 * @param int $version Module version number as a timestamp
1100 * @param array $dependencies List of module names on which this module depends
1101 * @param string $group Group which the module is in
1102 * @param string $source Source of the module, or 'local' if not foreign
1103 * @param string $skip Script body of the skip function
1104 * @return string
1105 */
1106 public static function makeLoaderRegisterScript( $name, $version = null,
1107 $dependencies = null, $group = null, $source = null, $skip = null
1108 ) {
1109 if ( is_array( $name ) ) {
1110 return Xml::encodeJsCall(
1111 'mw.loader.register',
1112 array( $name ),
1113 ResourceLoader::inDebugMode()
1114 );
1115 } else {
1116 $version = (int)$version > 1 ? (int)$version : 1;
1117 return Xml::encodeJsCall(
1118 'mw.loader.register',
1119 array( $name, $version, $dependencies, $group, $source, $skip ),
1120 ResourceLoader::inDebugMode()
1121 );
1122 }
1123 }
1124
1125 /**
1126 * Returns JS code which calls mw.loader.addSource() with the given
1127 * parameters. Has two calling conventions:
1128 *
1129 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1130 * Register a single source
1131 *
1132 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $props1, $id2 => $props2, ... ) );
1133 * Register sources with the given IDs and properties.
1134 *
1135 * @param string $id Source ID
1136 * @param array $properties Source properties (see addSource())
1137 * @return string
1138 */
1139 public static function makeLoaderSourcesScript( $id, $properties = null ) {
1140 if ( is_array( $id ) ) {
1141 return Xml::encodeJsCall(
1142 'mw.loader.addSource',
1143 array( $id ),
1144 ResourceLoader::inDebugMode()
1145 );
1146 } else {
1147 return Xml::encodeJsCall(
1148 'mw.loader.addSource',
1149 array( $id, $properties ),
1150 ResourceLoader::inDebugMode()
1151 );
1152 }
1153 }
1154
1155 /**
1156 * Returns JS code which runs given JS code if the client-side framework is
1157 * present.
1158 *
1159 * @param string $script JavaScript code
1160 * @return string
1161 */
1162 public static function makeLoaderConditionalScript( $script ) {
1163 return "if(window.mw){\n" . trim( $script ) . "\n}";
1164 }
1165
1166 /**
1167 * Returns JS code which will set the MediaWiki configuration array to
1168 * the given value.
1169 *
1170 * @param array $configuration List of configuration values keyed by variable name
1171 * @return string
1172 */
1173 public static function makeConfigSetScript( array $configuration ) {
1174 return Xml::encodeJsCall(
1175 'mw.config.set',
1176 array( $configuration ),
1177 ResourceLoader::inDebugMode()
1178 );
1179 }
1180
1181 /**
1182 * Convert an array of module names to a packed query string.
1183 *
1184 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
1185 * becomes 'foo.bar,baz|bar.baz,quux'
1186 * @param array $modules List of module names (strings)
1187 * @return string Packed query string
1188 */
1189 public static function makePackedModulesString( $modules ) {
1190 $groups = array(); // array( prefix => array( suffixes ) )
1191 foreach ( $modules as $module ) {
1192 $pos = strrpos( $module, '.' );
1193 $prefix = $pos === false ? '' : substr( $module, 0, $pos );
1194 $suffix = $pos === false ? $module : substr( $module, $pos + 1 );
1195 $groups[$prefix][] = $suffix;
1196 }
1197
1198 $arr = array();
1199 foreach ( $groups as $prefix => $suffixes ) {
1200 $p = $prefix === '' ? '' : $prefix . '.';
1201 $arr[] = $p . implode( ',', $suffixes );
1202 }
1203 $str = implode( '|', $arr );
1204 return $str;
1205 }
1206
1207 /**
1208 * Determine whether debug mode was requested
1209 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1210 * @return bool
1211 */
1212 public static function inDebugMode() {
1213 if ( self::$debugMode === null ) {
1214 global $wgRequest, $wgResourceLoaderDebug;
1215 self::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1216 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1217 );
1218 }
1219 return self::$debugMode;
1220 }
1221
1222 /**
1223 * Reset static members used for caching.
1224 *
1225 * Global state and $wgRequest are evil, but we're using it right
1226 * now and sometimes we need to be able to force ResourceLoader to
1227 * re-evaluate the context because it has changed (e.g. in the test suite).
1228 */
1229 public static function clearCache() {
1230 self::$debugMode = null;
1231 }
1232
1233 /**
1234 * Build a load.php URL
1235 * @param array $modules Array of module names (strings)
1236 * @param string $lang Language code
1237 * @param string $skin Skin name
1238 * @param string|null $user User name. If null, the &user= parameter is omitted
1239 * @param string|null $version Versioning timestamp
1240 * @param bool $debug Whether the request should be in debug mode
1241 * @param string|null $only &only= parameter
1242 * @param bool $printable Printable mode
1243 * @param bool $handheld Handheld mode
1244 * @param array $extraQuery Extra query parameters to add
1245 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1246 */
1247 public static function makeLoaderURL( $modules, $lang, $skin, $user = null,
1248 $version = null, $debug = false, $only = null, $printable = false,
1249 $handheld = false, $extraQuery = array()
1250 ) {
1251 global $wgLoadScript;
1252
1253 $query = self::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
1254 $only, $printable, $handheld, $extraQuery
1255 );
1256
1257 // Prevent the IE6 extension check from being triggered (bug 28840)
1258 // by appending a character that's invalid in Windows extensions ('*')
1259 return wfExpandUrl( wfAppendQuery( $wgLoadScript, $query ) . '&*', PROTO_RELATIVE );
1260 }
1261
1262 /**
1263 * Build a query array (array representation of query string) for load.php. Helper
1264 * function for makeLoaderURL().
1265 *
1266 * @param array $modules
1267 * @param string $lang
1268 * @param string $skin
1269 * @param string $user
1270 * @param string $version
1271 * @param bool $debug
1272 * @param string $only
1273 * @param bool $printable
1274 * @param bool $handheld
1275 * @param array $extraQuery
1276 *
1277 * @return array
1278 */
1279 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1280 $version = null, $debug = false, $only = null, $printable = false,
1281 $handheld = false, $extraQuery = array()
1282 ) {
1283 $query = array(
1284 'modules' => self::makePackedModulesString( $modules ),
1285 'lang' => $lang,
1286 'skin' => $skin,
1287 'debug' => $debug ? 'true' : 'false',
1288 );
1289 if ( $user !== null ) {
1290 $query['user'] = $user;
1291 }
1292 if ( $version !== null ) {
1293 $query['version'] = $version;
1294 }
1295 if ( $only !== null ) {
1296 $query['only'] = $only;
1297 }
1298 if ( $printable ) {
1299 $query['printable'] = 1;
1300 }
1301 if ( $handheld ) {
1302 $query['handheld'] = 1;
1303 }
1304 $query += $extraQuery;
1305
1306 // Make queries uniform in order
1307 ksort( $query );
1308 return $query;
1309 }
1310
1311 /**
1312 * Check a module name for validity.
1313 *
1314 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1315 * at most 255 bytes.
1316 *
1317 * @param string $moduleName Module name to check
1318 * @return bool Whether $moduleName is a valid module name
1319 */
1320 public static function isValidModuleName( $moduleName ) {
1321 return !preg_match( '/[|,!]/', $moduleName ) && strlen( $moduleName ) <= 255;
1322 }
1323
1324 /**
1325 * Returns LESS compiler set up for use with MediaWiki
1326 *
1327 * @since 1.22
1328 * @return lessc
1329 */
1330 public static function getLessCompiler() {
1331 global $wgResourceLoaderLESSFunctions, $wgResourceLoaderLESSImportPaths;
1332
1333 // When called from the installer, it is possible that a required PHP extension
1334 // is missing (at least for now; see bug 47564). If this is the case, throw an
1335 // exception (caught by the installer) to prevent a fatal error later on.
1336 if ( !function_exists( 'ctype_digit' ) ) {
1337 throw new MWException( 'lessc requires the Ctype extension' );
1338 }
1339
1340 $less = new lessc();
1341 $less->setPreserveComments( true );
1342 $less->setVariables( self::getLESSVars() );
1343 $less->setImportDir( $wgResourceLoaderLESSImportPaths );
1344 foreach ( $wgResourceLoaderLESSFunctions as $name => $func ) {
1345 $less->registerFunction( $name, $func );
1346 }
1347 return $less;
1348 }
1349
1350 /**
1351 * Get global LESS variables.
1352 *
1353 * $since 1.22
1354 * @return array Map of variable names to string CSS values.
1355 */
1356 public static function getLESSVars() {
1357 global $wgResourceLoaderLESSVars;
1358
1359 $lessVars = $wgResourceLoaderLESSVars;
1360 // Sort by key to ensure consistent hashing for cache lookups.
1361 ksort( $lessVars );
1362 return $lessVars;
1363 }
1364 }