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