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