Removed remaining profile calls
[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
216 return $result;
217 }
218
219 /* Methods */
220
221 /**
222 * Register core modules and runs registration hooks.
223 * @param Config|null $config
224 */
225 public function __construct( Config $config = null ) {
226 global $IP;
227
228
229 if ( $config === null ) {
230 wfDebug( __METHOD__ . ' was called without providing a Config instance' );
231 $config = ConfigFactory::getDefaultInstance()->makeConfig( 'main' );
232 }
233
234 $this->config = $config;
235
236 // Add 'local' source first
237 $this->addSource( 'local', wfScript( 'load' ) );
238
239 // Add other sources
240 $this->addSource( $config->get( 'ResourceLoaderSources' ) );
241
242 // Register core modules
243 $this->register( include "$IP/resources/Resources.php" );
244 // Register extension modules
245 Hooks::run( 'ResourceLoaderRegisterModules', array( &$this ) );
246 $this->register( $config->get( 'ResourceModules' ) );
247
248 if ( $config->get( 'EnableJavaScriptTest' ) === true ) {
249 $this->registerTestModules();
250 }
251
252 }
253
254 /**
255 * @return Config
256 */
257 public function getConfig() {
258 return $this->config;
259 }
260
261 /**
262 * Register a module with the ResourceLoader system.
263 *
264 * @param mixed $name Name of module as a string or List of name/object pairs as an array
265 * @param array $info Module info array. For backwards compatibility with 1.17alpha,
266 * this may also be a ResourceLoaderModule object. Optional when using
267 * multiple-registration calling style.
268 * @throws MWException If a duplicate module registration is attempted
269 * @throws MWException If a module name contains illegal characters (pipes or commas)
270 * @throws MWException If something other than a ResourceLoaderModule is being registered
271 * @return bool False if there were any errors, in which case one or more modules were
272 * not registered
273 */
274 public function register( $name, $info = null ) {
275
276 // Allow multiple modules to be registered in one call
277 $registrations = is_array( $name ) ? $name : array( $name => $info );
278 foreach ( $registrations as $name => $info ) {
279 // Disallow duplicate registrations
280 if ( isset( $this->moduleInfos[$name] ) ) {
281 // A module has already been registered by this name
282 throw new MWException(
283 'ResourceLoader duplicate registration error. ' .
284 'Another module has already been registered as ' . $name
285 );
286 }
287
288 // Check $name for validity
289 if ( !self::isValidModuleName( $name ) ) {
290 throw new MWException( "ResourceLoader module name '$name' is invalid, "
291 . "see ResourceLoader::isValidModuleName()" );
292 }
293
294 // Attach module
295 if ( $info instanceof ResourceLoaderModule ) {
296 $this->moduleInfos[$name] = array( 'object' => $info );
297 $info->setName( $name );
298 $this->modules[$name] = $info;
299 } elseif ( is_array( $info ) ) {
300 // New calling convention
301 $this->moduleInfos[$name] = $info;
302 } else {
303 throw new MWException(
304 'ResourceLoader module info type error for module \'' . $name .
305 '\': expected ResourceLoaderModule or array (got: ' . gettype( $info ) . ')'
306 );
307 }
308
309 // Last-minute changes
310
311 // Apply custom skin-defined styles to existing modules.
312 if ( $this->isFileModule( $name ) ) {
313 foreach ( $this->config->get( 'ResourceModuleSkinStyles' ) as $skinName => $skinStyles ) {
314 // If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
315 if ( isset( $this->moduleInfos[$name]['skinStyles'][$skinName] ) ) {
316 continue;
317 }
318
319 // If $name is preceded with a '+', the defined style files will be added to 'default'
320 // skinStyles, otherwise 'default' will be ignored as it normally would be.
321 if ( isset( $skinStyles[$name] ) ) {
322 $paths = (array)$skinStyles[$name];
323 $styleFiles = array();
324 } elseif ( isset( $skinStyles['+' . $name] ) ) {
325 $paths = (array)$skinStyles['+' . $name];
326 $styleFiles = isset( $this->moduleInfos[$name]['skinStyles']['default'] ) ?
327 $this->moduleInfos[$name]['skinStyles']['default'] :
328 array();
329 } else {
330 continue;
331 }
332
333 // Add new file paths, remapping them to refer to our directories and not use settings
334 // from the module we're modifying. These can come from the base definition or be defined
335 // for each module.
336 list( $localBasePath, $remoteBasePath ) =
337 ResourceLoaderFileModule::extractBasePaths( $skinStyles );
338 list( $localBasePath, $remoteBasePath ) =
339 ResourceLoaderFileModule::extractBasePaths( $paths, $localBasePath, $remoteBasePath );
340
341 foreach ( $paths as $path ) {
342 $styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
343 }
344
345 $this->moduleInfos[$name]['skinStyles'][$skinName] = $styleFiles;
346 }
347 }
348 }
349
350 }
351
352 /**
353 */
354 public function registerTestModules() {
355 global $IP;
356
357 if ( $this->config->get( 'EnableJavaScriptTest' ) !== true ) {
358 throw new MWException( 'Attempt to register JavaScript test modules '
359 . 'but <code>$wgEnableJavaScriptTest</code> is false. '
360 . 'Edit your <code>LocalSettings.php</code> to enable it.' );
361 }
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
570 // Find out which modules are missing and instantiate the others
571 $modules = array();
572 $missing = array();
573 foreach ( $context->getModules() as $name ) {
574 $module = $this->getModule( $name );
575 if ( $module ) {
576 // Do not allow private modules to be loaded from the web.
577 // This is a security issue, see bug 34907.
578 if ( $module->getGroup() === 'private' ) {
579 wfDebugLog( 'resourceloader', __METHOD__ . ": request for private module '$name' denied" );
580 $this->errors[] = "Cannot show private module \"$name\"";
581 continue;
582 }
583 $modules[$name] = $module;
584 } else {
585 $missing[] = $name;
586 }
587 }
588
589 // Preload information needed to the mtime calculation below
590 try {
591 $this->preloadModuleInfo( array_keys( $modules ), $context );
592 } catch ( Exception $e ) {
593 MWExceptionHandler::logException( $e );
594 wfDebugLog( 'resourceloader', __METHOD__ . ": preloading module info failed: $e" );
595 $this->errors[] = self::formatExceptionNoComment( $e );
596 }
597
598
599 // To send Last-Modified and support If-Modified-Since, we need to detect
600 // the last modified time
601 $mtime = wfTimestamp( TS_UNIX, $this->config->get( 'CacheEpoch' ) );
602 foreach ( $modules as $module ) {
603 /**
604 * @var $module ResourceLoaderModule
605 */
606 try {
607 // Calculate maximum modified time
608 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
609 } catch ( Exception $e ) {
610 MWExceptionHandler::logException( $e );
611 wfDebugLog( 'resourceloader', __METHOD__ . ": calculating maximum modified time failed: $e" );
612 $this->errors[] = self::formatExceptionNoComment( $e );
613 }
614 }
615
616
617 // If there's an If-Modified-Since header, respond with a 304 appropriately
618 if ( $this->tryRespondLastModified( $context, $mtime ) ) {
619 return; // output handled (buffers cleared)
620 }
621
622 // Generate a response
623 $response = $this->makeModuleResponse( $context, $modules, $missing );
624
625 // Capture any PHP warnings from the output buffer and append them to the
626 // error list if we're in debug mode.
627 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
628 $this->errors[] = $warnings;
629 }
630
631 // Save response to file cache unless there are errors
632 if ( isset( $fileCache ) && !$this->errors && !count( $missing ) ) {
633 // Cache single modules and images...and other requests if there are enough hits
634 if ( ResourceFileCache::useFileCache( $context ) ) {
635 if ( $fileCache->isCacheWorthy() ) {
636 $fileCache->saveText( $response );
637 } else {
638 $fileCache->incrMissesRecent( $context->getRequest() );
639 }
640 }
641 }
642
643 // Send content type and cache related headers
644 $this->sendResponseHeaders( $context, $mtime, (bool)$this->errors );
645
646 // Remove the output buffer and output the response
647 ob_end_clean();
648
649 if ( $context->getImageObj() && $this->errors ) {
650 // We can't show both the error messages and the response when it's an image.
651 $errorText = '';
652 foreach ( $this->errors as $error ) {
653 $errorText .= $error . "\n";
654 }
655 $response = $errorText;
656 } elseif ( $this->errors ) {
657 // Prepend comments indicating errors
658 $errorText = '';
659 foreach ( $this->errors as $error ) {
660 $errorText .= self::makeComment( $error );
661 }
662 $response = $errorText . $response;
663 }
664
665 $this->errors = array();
666 echo $response;
667
668 }
669
670 /**
671 * Send content type and last modified headers to the client.
672 * @param ResourceLoaderContext $context
673 * @param string $mtime TS_MW timestamp to use for last-modified
674 * @param bool $errors Whether there are errors in the response
675 * @return void
676 */
677 protected function sendResponseHeaders( ResourceLoaderContext $context, $mtime, $errors ) {
678 $rlMaxage = $this->config->get( 'ResourceLoaderMaxage' );
679 // If a version wasn't specified we need a shorter expiry time for updates
680 // to propagate to clients quickly
681 // If there were errors, we also need a shorter expiry time so we can recover quickly
682 if ( is_null( $context->getVersion() ) || $errors ) {
683 $maxage = $rlMaxage['unversioned']['client'];
684 $smaxage = $rlMaxage['unversioned']['server'];
685 // If a version was specified we can use a longer expiry time since changing
686 // version numbers causes cache misses
687 } else {
688 $maxage = $rlMaxage['versioned']['client'];
689 $smaxage = $rlMaxage['versioned']['server'];
690 }
691 if ( $context->getImageObj() ) {
692 // Output different headers if we're outputting textual errors.
693 if ( $errors ) {
694 header( 'Content-Type: text/plain; charset=utf-8' );
695 } else {
696 $context->getImageObj()->sendResponseHeaders( $context );
697 }
698 } elseif ( $context->getOnly() === 'styles' ) {
699 header( 'Content-Type: text/css; charset=utf-8' );
700 header( 'Access-Control-Allow-Origin: *' );
701 } else {
702 header( 'Content-Type: text/javascript; charset=utf-8' );
703 }
704 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $mtime ) );
705 if ( $context->getDebug() ) {
706 // Do not cache debug responses
707 header( 'Cache-Control: private, no-cache, must-revalidate' );
708 header( 'Pragma: no-cache' );
709 } else {
710 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
711 $exp = min( $maxage, $smaxage );
712 header( 'Expires: ' . wfTimestamp( TS_RFC2822, $exp + time() ) );
713 }
714 }
715
716 /**
717 * Respond with 304 Last Modified if appropiate.
718 *
719 * If there's an If-Modified-Since header, respond with a 304 appropriately
720 * and clear out the output buffer. If the client cache is too old then do nothing.
721 *
722 * @param ResourceLoaderContext $context
723 * @param string $mtime The TS_MW timestamp to check the header against
724 * @return bool True if 304 header sent and output handled
725 */
726 protected function tryRespondLastModified( ResourceLoaderContext $context, $mtime ) {
727 // If there's an If-Modified-Since header, respond with a 304 appropriately
728 // Some clients send "timestamp;length=123". Strip the part after the first ';'
729 // so we get a valid timestamp.
730 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
731 // Never send 304s in debug mode
732 if ( $ims !== false && !$context->getDebug() ) {
733 $imsTS = strtok( $ims, ';' );
734 if ( $mtime <= wfTimestamp( TS_UNIX, $imsTS ) ) {
735 // There's another bug in ob_gzhandler (see also the comment at
736 // the top of this function) that causes it to gzip even empty
737 // responses, meaning it's impossible to produce a truly empty
738 // response (because the gzip header is always there). This is
739 // a problem because 304 responses have to be completely empty
740 // per the HTTP spec, and Firefox behaves buggily when they're not.
741 // See also http://bugs.php.net/bug.php?id=51579
742 // To work around this, we tear down all output buffering before
743 // sending the 304.
744 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
745
746 header( 'HTTP/1.0 304 Not Modified' );
747 header( 'Status: 304 Not Modified' );
748 return true;
749 }
750 }
751 return false;
752 }
753
754 /**
755 * Send out code for a response from file cache if possible.
756 *
757 * @param ResourceFileCache $fileCache Cache object for this request URL
758 * @param ResourceLoaderContext $context Context in which to generate a response
759 * @return bool If this found a cache file and handled the response
760 */
761 protected function tryRespondFromFileCache(
762 ResourceFileCache $fileCache, ResourceLoaderContext $context
763 ) {
764 $rlMaxage = $this->config->get( 'ResourceLoaderMaxage' );
765 // Buffer output to catch warnings.
766 ob_start();
767 // Get the maximum age the cache can be
768 $maxage = is_null( $context->getVersion() )
769 ? $rlMaxage['unversioned']['server']
770 : $rlMaxage['versioned']['server'];
771 // Minimum timestamp the cache file must have
772 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW, time() - $maxage ) );
773 if ( !$good ) {
774 try { // RL always hits the DB on file cache miss...
775 wfGetDB( DB_SLAVE );
776 } catch ( DBConnectionError $e ) { // ...check if we need to fallback to cache
777 $good = $fileCache->isCacheGood(); // cache existence check
778 }
779 }
780 if ( $good ) {
781 $ts = $fileCache->cacheTimestamp();
782 // Send content type and cache headers
783 $this->sendResponseHeaders( $context, $ts, false );
784 // If there's an If-Modified-Since header, respond with a 304 appropriately
785 if ( $this->tryRespondLastModified( $context, $ts ) ) {
786 return false; // output handled (buffers cleared)
787 }
788 $response = $fileCache->fetchText();
789 // Capture any PHP warnings from the output buffer and append them to the
790 // response in a comment if we're in debug mode.
791 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
792 $response = "/*\n$warnings\n*/\n" . $response;
793 }
794 // Remove the output buffer and output the response
795 ob_end_clean();
796 echo $response . "\n/* Cached {$ts} */";
797 return true; // cache hit
798 }
799 // Clear buffer
800 ob_end_clean();
801
802 return false; // cache miss
803 }
804
805 /**
806 * Generate a CSS or JS comment block.
807 *
808 * Only use this for public data, not error message details.
809 *
810 * @param string $text
811 * @return string
812 */
813 public static function makeComment( $text ) {
814 $encText = str_replace( '*/', '* /', $text );
815 return "/*\n$encText\n*/\n";
816 }
817
818 /**
819 * Handle exception display.
820 *
821 * @param Exception $e Exception to be shown to the user
822 * @return string Sanitized text in a CSS/JS comment that can be returned to the user
823 */
824 public static function formatException( $e ) {
825 return self::makeComment( self::formatExceptionNoComment( $e ) );
826 }
827
828 /**
829 * Handle exception display.
830 *
831 * @since 1.25
832 * @param Exception $e Exception to be shown to the user
833 * @return string Sanitized text that can be returned to the user
834 */
835 protected static function formatExceptionNoComment( $e ) {
836 global $wgShowExceptionDetails;
837
838 if ( $wgShowExceptionDetails ) {
839 return $e->__toString();
840 } else {
841 return wfMessage( 'internalerror' )->text();
842 }
843 }
844
845 /**
846 * Generate code for a response.
847 *
848 * @param ResourceLoaderContext $context Context in which to generate a response
849 * @param array $modules List of module objects keyed by module name
850 * @param array $missing List of requested module names that are unregistered (optional)
851 * @return string Response data
852 */
853 public function makeModuleResponse( ResourceLoaderContext $context,
854 array $modules, array $missing = array()
855 ) {
856 $out = '';
857 $states = array();
858
859 if ( !count( $modules ) && !count( $missing ) ) {
860 return "/* This file is the Web entry point for MediaWiki's ResourceLoader:
861 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
862 no modules were requested. Max made me put this here. */";
863 }
864
865
866 $image = $context->getImageObj();
867 if ( $image ) {
868 $data = $image->getImageData( $context );
869 if ( $data === false ) {
870 $data = '';
871 $this->errors[] = 'Image generation failed';
872 }
873 return $data;
874 }
875
876 // Pre-fetch blobs
877 if ( $context->shouldIncludeMessages() ) {
878 try {
879 $blobs = MessageBlobStore::getInstance()->get( $this, $modules, $context->getLanguage() );
880 } catch ( Exception $e ) {
881 MWExceptionHandler::logException( $e );
882 wfDebugLog(
883 'resourceloader',
884 __METHOD__ . ": pre-fetching blobs from MessageBlobStore failed: $e"
885 );
886 $this->errors[] = self::formatExceptionNoComment( $e );
887 }
888 } else {
889 $blobs = array();
890 }
891
892 foreach ( $missing as $name ) {
893 $states[$name] = 'missing';
894 }
895
896 // Generate output
897 $isRaw = false;
898 foreach ( $modules as $name => $module ) {
899 /**
900 * @var $module ResourceLoaderModule
901 */
902
903 try {
904 $scripts = '';
905 if ( $context->shouldIncludeScripts() ) {
906 // If we are in debug mode, we'll want to return an array of URLs if possible
907 // However, we can't do this if the module doesn't support it
908 // We also can't do this if there is an only= parameter, because we have to give
909 // the module a way to return a load.php URL without causing an infinite loop
910 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
911 $scripts = $module->getScriptURLsForDebug( $context );
912 } else {
913 $scripts = $module->getScript( $context );
914 // rtrim() because there are usually a few line breaks
915 // after the last ';'. A new line at EOF, a new line
916 // added by ResourceLoaderFileModule::readScriptFiles, etc.
917 if ( is_string( $scripts )
918 && strlen( $scripts )
919 && substr( rtrim( $scripts ), -1 ) !== ';'
920 ) {
921 // Append semicolon to prevent weird bugs caused by files not
922 // terminating their statements right (bug 27054)
923 $scripts .= ";\n";
924 }
925 }
926 }
927 // Styles
928 $styles = array();
929 if ( $context->shouldIncludeStyles() ) {
930 // Don't create empty stylesheets like array( '' => '' ) for modules
931 // that don't *have* any stylesheets (bug 38024).
932 $stylePairs = $module->getStyles( $context );
933 if ( count( $stylePairs ) ) {
934 // If we are in debug mode without &only= set, we'll want to return an array of URLs
935 // See comment near shouldIncludeScripts() for more details
936 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
937 $styles = array(
938 'url' => $module->getStyleURLsForDebug( $context )
939 );
940 } else {
941 // Minify CSS before embedding in mw.loader.implement call
942 // (unless in debug mode)
943 if ( !$context->getDebug() ) {
944 foreach ( $stylePairs as $media => $style ) {
945 // Can be either a string or an array of strings.
946 if ( is_array( $style ) ) {
947 $stylePairs[$media] = array();
948 foreach ( $style as $cssText ) {
949 if ( is_string( $cssText ) ) {
950 $stylePairs[$media][] = $this->filter( 'minify-css', $cssText );
951 }
952 }
953 } elseif ( is_string( $style ) ) {
954 $stylePairs[$media] = $this->filter( 'minify-css', $style );
955 }
956 }
957 }
958 // Wrap styles into @media groups as needed and flatten into a numerical array
959 $styles = array(
960 'css' => self::makeCombinedStyles( $stylePairs )
961 );
962 }
963 }
964 }
965
966 // Messages
967 $messagesBlob = isset( $blobs[$name] ) ? $blobs[$name] : '{}';
968
969 // Append output
970 switch ( $context->getOnly() ) {
971 case 'scripts':
972 if ( is_string( $scripts ) ) {
973 // Load scripts raw...
974 $out .= $scripts;
975 } elseif ( is_array( $scripts ) ) {
976 // ...except when $scripts is an array of URLs
977 $out .= self::makeLoaderImplementScript( $name, $scripts, array(), array() );
978 }
979 break;
980 case 'styles':
981 // We no longer seperate into media, they are all combined now with
982 // custom media type groups into @media .. {} sections as part of the css string.
983 // Module returns either an empty array or a numerical array with css strings.
984 $out .= isset( $styles['css'] ) ? implode( '', $styles['css'] ) : '';
985 break;
986 case 'messages':
987 $out .= self::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
988 break;
989 case 'templates':
990 $out .= Xml::encodeJsCall(
991 'mw.templates.set',
992 array( $name, (object)$module->getTemplates() ),
993 ResourceLoader::inDebugMode()
994 );
995 break;
996 default:
997 $out .= self::makeLoaderImplementScript(
998 $name,
999 $scripts,
1000 $styles,
1001 new XmlJsCode( $messagesBlob ),
1002 $module->getTemplates()
1003 );
1004 break;
1005 }
1006 } catch ( Exception $e ) {
1007 MWExceptionHandler::logException( $e );
1008 wfDebugLog( 'resourceloader', __METHOD__ . ": generating module package failed: $e" );
1009 $this->errors[] = self::formatExceptionNoComment( $e );
1010
1011 // Respond to client with error-state instead of module implementation
1012 $states[$name] = 'error';
1013 unset( $modules[$name] );
1014 }
1015 $isRaw |= $module->isRaw();
1016 }
1017
1018 // Update module states
1019 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
1020 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
1021 // Set the state of modules loaded as only scripts to ready as
1022 // they don't have an mw.loader.implement wrapper that sets the state
1023 foreach ( $modules as $name => $module ) {
1024 $states[$name] = 'ready';
1025 }
1026 }
1027
1028 // Set the state of modules we didn't respond to with mw.loader.implement
1029 if ( count( $states ) ) {
1030 $out .= self::makeLoaderStateScript( $states );
1031 }
1032 } else {
1033 if ( count( $states ) ) {
1034 $this->errors[] = 'Problematic modules: ' .
1035 FormatJson::encode( $states, ResourceLoader::inDebugMode() );
1036 }
1037 }
1038
1039 if ( !$context->getDebug() ) {
1040 if ( $context->getOnly() === 'styles' ) {
1041 $out = $this->filter( 'minify-css', $out );
1042 } else {
1043 $out = $this->filter( 'minify-js', $out );
1044 }
1045 }
1046
1047 return $out;
1048 }
1049
1050 /* Static Methods */
1051
1052 /**
1053 * Return JS code that calls mw.loader.implement with given module properties.
1054 *
1055 * @param string $name Module name
1056 * @param mixed $scripts List of URLs to JavaScript files or String of JavaScript code
1057 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1058 * to CSS files keyed by media type
1059 * @param mixed $messages List of messages associated with this module. May either be an
1060 * associative array mapping message key to value, or a JSON-encoded message blob containing
1061 * the same data, wrapped in an XmlJsCode object.
1062 * @param array $templates Keys are name of templates and values are the source of
1063 * the template.
1064 * @throws MWException
1065 * @return string
1066 */
1067 public static function makeLoaderImplementScript( $name, $scripts, $styles,
1068 $messages, $templates
1069 ) {
1070 if ( is_string( $scripts ) ) {
1071 $scripts = new XmlJsCode( "function ( $, jQuery ) {\n{$scripts}\n}" );
1072 } elseif ( !is_array( $scripts ) ) {
1073 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1074 }
1075
1076 return Xml::encodeJsCall(
1077 'mw.loader.implement',
1078 array(
1079 $name,
1080 $scripts,
1081 // Force objects. mw.loader.implement requires them to be javascript objects.
1082 // Although these variables are associative arrays, which become javascript
1083 // objects through json_encode. In many cases they will be empty arrays, and
1084 // PHP/json_encode() consider empty arrays to be numerical arrays and
1085 // output javascript "[]" instead of "{}". This fixes that.
1086 (object)$styles,
1087 (object)$messages,
1088 (object)$templates,
1089 ),
1090 ResourceLoader::inDebugMode()
1091 );
1092 }
1093
1094 /**
1095 * Returns JS code which, when called, will register a given list of messages.
1096 *
1097 * @param mixed $messages Either an associative array mapping message key to value, or a
1098 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1099 * @return string
1100 */
1101 public static function makeMessageSetScript( $messages ) {
1102 return Xml::encodeJsCall(
1103 'mw.messages.set',
1104 array( (object)$messages ),
1105 ResourceLoader::inDebugMode()
1106 );
1107 }
1108
1109 /**
1110 * Combines an associative array mapping media type to CSS into a
1111 * single stylesheet with "@media" blocks.
1112 *
1113 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1114 * @return array
1115 */
1116 public static function makeCombinedStyles( array $stylePairs ) {
1117 $out = array();
1118 foreach ( $stylePairs as $media => $styles ) {
1119 // ResourceLoaderFileModule::getStyle can return the styles
1120 // as a string or an array of strings. This is to allow separation in
1121 // the front-end.
1122 $styles = (array)$styles;
1123 foreach ( $styles as $style ) {
1124 $style = trim( $style );
1125 // Don't output an empty "@media print { }" block (bug 40498)
1126 if ( $style !== '' ) {
1127 // Transform the media type based on request params and config
1128 // The way that this relies on $wgRequest to propagate request params is slightly evil
1129 $media = OutputPage::transformCssMedia( $media );
1130
1131 if ( $media === '' || $media == 'all' ) {
1132 $out[] = $style;
1133 } elseif ( is_string( $media ) ) {
1134 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1135 }
1136 // else: skip
1137 }
1138 }
1139 }
1140 return $out;
1141 }
1142
1143 /**
1144 * Returns a JS call to mw.loader.state, which sets the state of a
1145 * module or modules to a given value. Has two calling conventions:
1146 *
1147 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1148 * Set the state of a single module called $name to $state
1149 *
1150 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
1151 * Set the state of modules with the given names to the given states
1152 *
1153 * @param string $name
1154 * @param string $state
1155 * @return string
1156 */
1157 public static function makeLoaderStateScript( $name, $state = null ) {
1158 if ( is_array( $name ) ) {
1159 return Xml::encodeJsCall(
1160 'mw.loader.state',
1161 array( $name ),
1162 ResourceLoader::inDebugMode()
1163 );
1164 } else {
1165 return Xml::encodeJsCall(
1166 'mw.loader.state',
1167 array( $name, $state ),
1168 ResourceLoader::inDebugMode()
1169 );
1170 }
1171 }
1172
1173 /**
1174 * Returns JS code which calls the script given by $script. The script will
1175 * be called with local variables name, version, dependencies and group,
1176 * which will have values corresponding to $name, $version, $dependencies
1177 * and $group as supplied.
1178 *
1179 * @param string $name Module name
1180 * @param int $version Module version number as a timestamp
1181 * @param array $dependencies List of module names on which this module depends
1182 * @param string $group Group which the module is in.
1183 * @param string $source Source of the module, or 'local' if not foreign.
1184 * @param string $script JavaScript code
1185 * @return string
1186 */
1187 public static function makeCustomLoaderScript( $name, $version, $dependencies,
1188 $group, $source, $script
1189 ) {
1190 $script = str_replace( "\n", "\n\t", trim( $script ) );
1191 return Xml::encodeJsCall(
1192 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1193 array( $name, $version, $dependencies, $group, $source ),
1194 ResourceLoader::inDebugMode()
1195 );
1196 }
1197
1198 /**
1199 * Remove empty values from the end of an array.
1200 *
1201 * Values considered empty:
1202 *
1203 * - null
1204 * - empty array
1205 *
1206 * @param Array $array
1207 */
1208 private static function trimArray( Array &$array ) {
1209 $i = count( $array );
1210 while ( $i-- ) {
1211 if ( $array[$i] === null || $array[$i] === array() ) {
1212 unset( $array[$i] );
1213 } else {
1214 break;
1215 }
1216 }
1217 }
1218
1219 /**
1220 * Returns JS code which calls mw.loader.register with the given
1221 * parameters. Has three calling conventions:
1222 *
1223 * - ResourceLoader::makeLoaderRegisterScript( $name, $version,
1224 * $dependencies, $group, $source, $skip
1225 * ):
1226 * Register a single module.
1227 *
1228 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
1229 * Register modules with the given names.
1230 *
1231 * - ResourceLoader::makeLoaderRegisterScript( array(
1232 * array( $name1, $version1, $dependencies1, $group1, $source1, $skip1 ),
1233 * array( $name2, $version2, $dependencies1, $group2, $source2, $skip2 ),
1234 * ...
1235 * ) ):
1236 * Registers modules with the given names and parameters.
1237 *
1238 * @param string $name Module name
1239 * @param int $version Module version number as a timestamp
1240 * @param array $dependencies List of module names on which this module depends
1241 * @param string $group Group which the module is in
1242 * @param string $source Source of the module, or 'local' if not foreign
1243 * @param string $skip Script body of the skip function
1244 * @return string
1245 */
1246 public static function makeLoaderRegisterScript( $name, $version = null,
1247 $dependencies = null, $group = null, $source = null, $skip = null
1248 ) {
1249 if ( is_array( $name ) ) {
1250 // Build module name index
1251 $index = array();
1252 foreach ( $name as $i => &$module ) {
1253 $index[$module[0]] = $i;
1254 }
1255
1256 // Transform dependency names into indexes when possible, they will be resolved by
1257 // mw.loader.register on the other end
1258 foreach ( $name as &$module ) {
1259 if ( isset( $module[2] ) ) {
1260 foreach ( $module[2] as &$dependency ) {
1261 if ( isset( $index[$dependency] ) ) {
1262 $dependency = $index[$dependency];
1263 }
1264 }
1265 }
1266 }
1267
1268 array_walk( $name, array( 'self', 'trimArray' ) );
1269
1270 return Xml::encodeJsCall(
1271 'mw.loader.register',
1272 array( $name ),
1273 ResourceLoader::inDebugMode()
1274 );
1275 } else {
1276 $registration = array( $name, $version, $dependencies, $group, $source, $skip );
1277 self::trimArray( $registration );
1278 return Xml::encodeJsCall(
1279 'mw.loader.register',
1280 $registration,
1281 ResourceLoader::inDebugMode()
1282 );
1283 }
1284 }
1285
1286 /**
1287 * Returns JS code which calls mw.loader.addSource() with the given
1288 * parameters. Has two calling conventions:
1289 *
1290 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1291 * Register a single source
1292 *
1293 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $loadUrl, $id2 => $loadUrl, ... ) );
1294 * Register sources with the given IDs and properties.
1295 *
1296 * @param string $id Source ID
1297 * @param array $properties Source properties (see addSource())
1298 * @return string
1299 */
1300 public static function makeLoaderSourcesScript( $id, $properties = null ) {
1301 if ( is_array( $id ) ) {
1302 return Xml::encodeJsCall(
1303 'mw.loader.addSource',
1304 array( $id ),
1305 ResourceLoader::inDebugMode()
1306 );
1307 } else {
1308 return Xml::encodeJsCall(
1309 'mw.loader.addSource',
1310 array( $id, $properties ),
1311 ResourceLoader::inDebugMode()
1312 );
1313 }
1314 }
1315
1316 /**
1317 * Returns JS code which runs given JS code if the client-side framework is
1318 * present.
1319 *
1320 * @param string $script JavaScript code
1321 * @return string
1322 */
1323 public static function makeLoaderConditionalScript( $script ) {
1324 return "if(window.mw){\n" . trim( $script ) . "\n}";
1325 }
1326
1327 /**
1328 * Returns JS code which will set the MediaWiki configuration array to
1329 * the given value.
1330 *
1331 * @param array $configuration List of configuration values keyed by variable name
1332 * @return string
1333 */
1334 public static function makeConfigSetScript( array $configuration ) {
1335 return Xml::encodeJsCall(
1336 'mw.config.set',
1337 array( $configuration ),
1338 ResourceLoader::inDebugMode()
1339 );
1340 }
1341
1342 /**
1343 * Convert an array of module names to a packed query string.
1344 *
1345 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
1346 * becomes 'foo.bar,baz|bar.baz,quux'
1347 * @param array $modules List of module names (strings)
1348 * @return string Packed query string
1349 */
1350 public static function makePackedModulesString( $modules ) {
1351 $groups = array(); // array( prefix => array( suffixes ) )
1352 foreach ( $modules as $module ) {
1353 $pos = strrpos( $module, '.' );
1354 $prefix = $pos === false ? '' : substr( $module, 0, $pos );
1355 $suffix = $pos === false ? $module : substr( $module, $pos + 1 );
1356 $groups[$prefix][] = $suffix;
1357 }
1358
1359 $arr = array();
1360 foreach ( $groups as $prefix => $suffixes ) {
1361 $p = $prefix === '' ? '' : $prefix . '.';
1362 $arr[] = $p . implode( ',', $suffixes );
1363 }
1364 $str = implode( '|', $arr );
1365 return $str;
1366 }
1367
1368 /**
1369 * Determine whether debug mode was requested
1370 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1371 * @return bool
1372 */
1373 public static function inDebugMode() {
1374 if ( self::$debugMode === null ) {
1375 global $wgRequest, $wgResourceLoaderDebug;
1376 self::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1377 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1378 );
1379 }
1380 return self::$debugMode;
1381 }
1382
1383 /**
1384 * Reset static members used for caching.
1385 *
1386 * Global state and $wgRequest are evil, but we're using it right
1387 * now and sometimes we need to be able to force ResourceLoader to
1388 * re-evaluate the context because it has changed (e.g. in the test suite).
1389 */
1390 public static function clearCache() {
1391 self::$debugMode = null;
1392 }
1393
1394 /**
1395 * Build a load.php URL
1396 *
1397 * @since 1.24
1398 * @param string $source Name of the ResourceLoader source
1399 * @param ResourceLoaderContext $context
1400 * @param array $extraQuery
1401 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1402 */
1403 public function createLoaderURL( $source, ResourceLoaderContext $context,
1404 $extraQuery = array()
1405 ) {
1406 $query = self::createLoaderQuery( $context, $extraQuery );
1407 $script = $this->getLoadScript( $source );
1408
1409 // Prevent the IE6 extension check from being triggered (bug 28840)
1410 // by appending a character that's invalid in Windows extensions ('*')
1411 return wfExpandUrl( wfAppendQuery( $script, $query ) . '&*', PROTO_RELATIVE );
1412 }
1413
1414 /**
1415 * Build a load.php URL
1416 * @deprecated since 1.24, use createLoaderURL instead
1417 * @param array $modules Array of module names (strings)
1418 * @param string $lang Language code
1419 * @param string $skin Skin name
1420 * @param string|null $user User name. If null, the &user= parameter is omitted
1421 * @param string|null $version Versioning timestamp
1422 * @param bool $debug Whether the request should be in debug mode
1423 * @param string|null $only &only= parameter
1424 * @param bool $printable Printable mode
1425 * @param bool $handheld Handheld mode
1426 * @param array $extraQuery Extra query parameters to add
1427 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1428 */
1429 public static function makeLoaderURL( $modules, $lang, $skin, $user = null,
1430 $version = null, $debug = false, $only = null, $printable = false,
1431 $handheld = false, $extraQuery = array()
1432 ) {
1433 global $wgLoadScript;
1434
1435 $query = self::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
1436 $only, $printable, $handheld, $extraQuery
1437 );
1438
1439 // Prevent the IE6 extension check from being triggered (bug 28840)
1440 // by appending a character that's invalid in Windows extensions ('*')
1441 return wfExpandUrl( wfAppendQuery( $wgLoadScript, $query ) . '&*', PROTO_RELATIVE );
1442 }
1443
1444 /**
1445 * Helper for createLoaderURL()
1446 *
1447 * @since 1.24
1448 * @see makeLoaderQuery
1449 * @param ResourceLoaderContext $context
1450 * @param array $extraQuery
1451 * @return array
1452 */
1453 public static function createLoaderQuery( ResourceLoaderContext $context, $extraQuery = array() ) {
1454 return self::makeLoaderQuery(
1455 $context->getModules(),
1456 $context->getLanguage(),
1457 $context->getSkin(),
1458 $context->getUser(),
1459 $context->getVersion(),
1460 $context->getDebug(),
1461 $context->getOnly(),
1462 $context->getRequest()->getBool( 'printable' ),
1463 $context->getRequest()->getBool( 'handheld' ),
1464 $extraQuery
1465 );
1466 }
1467
1468 /**
1469 * Build a query array (array representation of query string) for load.php. Helper
1470 * function for makeLoaderURL().
1471 *
1472 * @param array $modules
1473 * @param string $lang
1474 * @param string $skin
1475 * @param string $user
1476 * @param string $version
1477 * @param bool $debug
1478 * @param string $only
1479 * @param bool $printable
1480 * @param bool $handheld
1481 * @param array $extraQuery
1482 *
1483 * @return array
1484 */
1485 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1486 $version = null, $debug = false, $only = null, $printable = false,
1487 $handheld = false, $extraQuery = array()
1488 ) {
1489 $query = array(
1490 'modules' => self::makePackedModulesString( $modules ),
1491 'lang' => $lang,
1492 'skin' => $skin,
1493 'debug' => $debug ? 'true' : 'false',
1494 );
1495 if ( $user !== null ) {
1496 $query['user'] = $user;
1497 }
1498 if ( $version !== null ) {
1499 $query['version'] = $version;
1500 }
1501 if ( $only !== null ) {
1502 $query['only'] = $only;
1503 }
1504 if ( $printable ) {
1505 $query['printable'] = 1;
1506 }
1507 if ( $handheld ) {
1508 $query['handheld'] = 1;
1509 }
1510 $query += $extraQuery;
1511
1512 // Make queries uniform in order
1513 ksort( $query );
1514 return $query;
1515 }
1516
1517 /**
1518 * Check a module name for validity.
1519 *
1520 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1521 * at most 255 bytes.
1522 *
1523 * @param string $moduleName Module name to check
1524 * @return bool Whether $moduleName is a valid module name
1525 */
1526 public static function isValidModuleName( $moduleName ) {
1527 return !preg_match( '/[|,!]/', $moduleName ) && strlen( $moduleName ) <= 255;
1528 }
1529
1530 /**
1531 * Returns LESS compiler set up for use with MediaWiki
1532 *
1533 * @param Config $config
1534 * @throws MWException
1535 * @since 1.22
1536 * @return lessc
1537 */
1538 public static function getLessCompiler( Config $config ) {
1539 // When called from the installer, it is possible that a required PHP extension
1540 // is missing (at least for now; see bug 47564). If this is the case, throw an
1541 // exception (caught by the installer) to prevent a fatal error later on.
1542 if ( !class_exists( 'lessc' ) ) {
1543 throw new MWException( 'MediaWiki requires the lessphp compiler' );
1544 }
1545 if ( !function_exists( 'ctype_digit' ) ) {
1546 throw new MWException( 'lessc requires the Ctype extension' );
1547 }
1548
1549 $less = new lessc();
1550 $less->setPreserveComments( true );
1551 $less->setVariables( self::getLessVars( $config ) );
1552 $less->setImportDir( $config->get( 'ResourceLoaderLESSImportPaths' ) );
1553 foreach ( $config->get( 'ResourceLoaderLESSFunctions' ) as $name => $func ) {
1554 $less->registerFunction( $name, $func );
1555 }
1556 return $less;
1557 }
1558
1559 /**
1560 * Get global LESS variables.
1561 *
1562 * @param Config $config
1563 * @since 1.22
1564 * @return array Map of variable names to string CSS values.
1565 */
1566 public static function getLessVars( Config $config ) {
1567 $lessVars = $config->get( 'ResourceLoaderLESSVars' );
1568 // Sort by key to ensure consistent hashing for cache lookups.
1569 ksort( $lessVars );
1570 return $lessVars;
1571 }
1572 }