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