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