rv r97851 for further inspection, causes PHP notices
[lhc/web/wiklou.git] / includes / resourceloader / ResourceLoader.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 * @author Roan Kattouw
20 * @author Trevor Parscal
21 */
22
23 /**
24 * Dynamic JavaScript and CSS resource loading system.
25 *
26 * Most of the documention is on the MediaWiki documentation wiki starting at:
27 * http://www.mediawiki.org/wiki/ResourceLoader
28 */
29 class ResourceLoader {
30
31 /* Protected Static Members */
32 protected static $filterCacheVersion = 5;
33 protected static $requiredSourceProperties = array( 'loadScript' );
34
35 /** Array: List of module name/ResourceLoaderModule object pairs */
36 protected $modules = array();
37
38 /** Associative array mapping module name to info associative array */
39 protected $moduleInfos = array();
40
41 /** array( 'source-id' => array( 'loadScript' => 'http://.../load.php' ) ) **/
42 protected $sources = array();
43
44 /* Protected Methods */
45
46 /**
47 * Loads information stored in the database about modules.
48 *
49 * This method grabs modules dependencies from the database and updates modules
50 * objects.
51 *
52 * This is not inside the module code because it is much faster to
53 * request all of the information at once than it is to have each module
54 * requests its own information. This sacrifice of modularity yields a substantial
55 * performance improvement.
56 *
57 * @param $modules Array: List of module names to preload information for
58 * @param $context ResourceLoaderContext: Context to load the information within
59 */
60 public function preloadModuleInfo( array $modules, ResourceLoaderContext $context ) {
61 if ( !count( $modules ) ) {
62 return; // or else Database*::select() will explode, plus it's cheaper!
63 }
64 $dbr = wfGetDB( DB_SLAVE );
65 $skin = $context->getSkin();
66 $lang = $context->getLanguage();
67
68 // Get file dependency information
69 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
70 'md_module' => $modules,
71 'md_skin' => $skin
72 ), __METHOD__
73 );
74
75 // Set modules' dependencies
76 $modulesWithDeps = array();
77 foreach ( $res as $row ) {
78 $this->getModule( $row->md_module )->setFileDependencies( $skin,
79 FormatJson::decode( $row->md_deps, true )
80 );
81 $modulesWithDeps[] = $row->md_module;
82 }
83
84 // Register the absence of a dependency row too
85 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
86 $this->getModule( $name )->setFileDependencies( $skin, array() );
87 }
88
89 // Get message blob mtimes. Only do this for modules with messages
90 $modulesWithMessages = array();
91 foreach ( $modules as $name ) {
92 if ( count( $this->getModule( $name )->getMessages() ) ) {
93 $modulesWithMessages[] = $name;
94 }
95 }
96 $modulesWithoutMessages = array_flip( $modules ); // Will be trimmed down by the loop below
97 if ( count( $modulesWithMessages ) ) {
98 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
99 'mr_resource' => $modulesWithMessages,
100 'mr_lang' => $lang
101 ), __METHOD__
102 );
103 foreach ( $res as $row ) {
104 $this->getModule( $row->mr_resource )->setMsgBlobMtime( $lang,
105 wfTimestamp( TS_UNIX, $row->mr_timestamp ) );
106 unset( $modulesWithoutMessages[$row->mr_resource] );
107 }
108 }
109 foreach ( array_keys( $modulesWithoutMessages ) as $name ) {
110 $this->getModule( $name )->setMsgBlobMtime( $lang, 0 );
111 }
112 }
113
114 /**
115 * Runs JavaScript or CSS data through a filter, caching the filtered result for future calls.
116 *
117 * Available filters are:
118 * - minify-js \see JavaScriptMinifier::minify
119 * - minify-css \see CSSMin::minify
120 *
121 * If $data is empty, only contains whitespace or the filter was unknown,
122 * $data is returned unmodified.
123 *
124 * @param $filter String: Name of filter to run
125 * @param $data String: Text to filter, such as JavaScript or CSS text
126 * @return String: Filtered data, or a comment containing an error message
127 */
128 protected function filter( $filter, $data ) {
129 global $wgResourceLoaderMinifierStatementsOnOwnLine, $wgResourceLoaderMinifierMaxLineLength;
130 wfProfileIn( __METHOD__ );
131
132 // For empty/whitespace-only data or for unknown filters, don't perform
133 // any caching or processing
134 if ( trim( $data ) === ''
135 || !in_array( $filter, array( 'minify-js', 'minify-css' ) ) )
136 {
137 wfProfileOut( __METHOD__ );
138 return $data;
139 }
140
141 // Try for cache hit
142 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
143 $key = wfMemcKey( 'resourceloader', 'filter', $filter, self::$filterCacheVersion, md5( $data ) );
144 $cache = wfGetCache( CACHE_ANYTHING );
145 $cacheEntry = $cache->get( $key );
146 if ( is_string( $cacheEntry ) ) {
147 wfProfileOut( __METHOD__ );
148 return $cacheEntry;
149 }
150
151 $result = '';
152 // Run the filter - we've already verified one of these will work
153 try {
154 switch ( $filter ) {
155 case 'minify-js':
156 $result = JavaScriptMinifier::minify( $data,
157 $wgResourceLoaderMinifierStatementsOnOwnLine,
158 $wgResourceLoaderMinifierMaxLineLength
159 );
160 $result .= "\n\n/* cache key: $key */\n";
161 break;
162 case 'minify-css':
163 $result = CSSMin::minify( $data );
164 $result .= "\n\n/* cache key: $key */\n";
165 break;
166 }
167
168 // Save filtered text to Memcached
169 $cache->set( $key, $result );
170 } catch ( Exception $exception ) {
171 // Return exception as a comment
172 $result = "/*\n{$exception->__toString()}\n*/\n";
173 }
174
175 wfProfileOut( __METHOD__ );
176
177 return $result;
178 }
179
180 /* Methods */
181
182 /**
183 * Registers core modules and runs registration hooks.
184 */
185 public function __construct() {
186 global $IP, $wgResourceModules, $wgResourceLoaderSources, $wgLoadScript;
187
188 wfProfileIn( __METHOD__ );
189
190 // Add 'local' source first
191 $this->addSource( 'local', array( 'loadScript' => $wgLoadScript, 'apiScript' => wfScript( 'api' ) ) );
192
193 // Add other sources
194 $this->addSource( $wgResourceLoaderSources );
195
196 // Register core modules
197 $this->register( include( "$IP/resources/Resources.php" ) );
198 // Register extension modules
199 wfRunHooks( 'ResourceLoaderRegisterModules', array( &$this ) );
200 $this->register( $wgResourceModules );
201
202 wfProfileOut( __METHOD__ );
203 }
204
205 /**
206 * Registers a module with the ResourceLoader system.
207 *
208 * @param $name Mixed: Name of module as a string or List of name/object pairs as an array
209 * @param $info Module info array. For backwards compatibility with 1.17alpha,
210 * this may also be a ResourceLoaderModule object. Optional when using
211 * multiple-registration calling style.
212 * @throws MWException: If a duplicate module registration is attempted
213 * @throws MWException: If a module name contains illegal characters (pipes or commas)
214 * @throws MWException: If something other than a ResourceLoaderModule is being registered
215 * @return Boolean: False if there were any errors, in which case one or more modules were not
216 * registered
217 */
218 public function register( $name, $info = null ) {
219 wfProfileIn( __METHOD__ );
220
221 // Allow multiple modules to be registered in one call
222 if ( is_array( $name ) ) {
223 foreach ( $name as $key => $value ) {
224 $this->register( $key, $value );
225 }
226 wfProfileOut( __METHOD__ );
227 return;
228 }
229
230 // Disallow duplicate registrations
231 if ( isset( $this->moduleInfos[$name] ) ) {
232 // A module has already been registered by this name
233 throw new MWException(
234 'ResourceLoader duplicate registration error. ' .
235 'Another module has already been registered as ' . $name
236 );
237 }
238
239 // Check $name for illegal characters
240 if ( preg_match( '/[|,!]/', $name ) ) {
241 throw new MWException( "ResourceLoader module name '$name' is invalid. Names may not contain pipes (|), commas (,) or exclamation marks (!)" );
242 }
243
244 // Attach module
245 if ( is_object( $info ) ) {
246 // Old calling convention
247 // Validate the input
248 if ( !( $info instanceof ResourceLoaderModule ) ) {
249 throw new MWException( 'ResourceLoader invalid module error. ' .
250 'Instances of ResourceLoaderModule expected.' );
251 }
252
253 $this->moduleInfos[$name] = array( 'object' => $info );
254 $info->setName( $name );
255 $this->modules[$name] = $info;
256 } else {
257 // New calling convention
258 $this->moduleInfos[$name] = $info;
259 }
260
261 wfProfileOut( __METHOD__ );
262 }
263
264 /**
265 * Add a foreign source of modules.
266 *
267 * Source properties:
268 * 'loadScript': URL (either fully-qualified or protocol-relative) of load.php for this source
269 *
270 * @param $id Mixed: source ID (string), or array( id1 => props1, id2 => props2, ... )
271 * @param $properties Array: source properties
272 */
273 public function addSource( $id, $properties = null) {
274 // Allow multiple sources to be registered in one call
275 if ( is_array( $id ) ) {
276 foreach ( $id as $key => $value ) {
277 $this->addSource( $key, $value );
278 }
279 return;
280 }
281
282 // Disallow duplicates
283 if ( isset( $this->sources[$id] ) ) {
284 throw new MWException(
285 'ResourceLoader duplicate source addition error. ' .
286 'Another source has already been registered as ' . $id
287 );
288 }
289
290 // Validate properties
291 foreach ( self::$requiredSourceProperties as $prop ) {
292 if ( !isset( $properties[$prop] ) ) {
293 throw new MWException( "Required property $prop missing from source ID $id" );
294 }
295 }
296
297 $this->sources[$id] = $properties;
298 }
299
300 /**
301 * Get a list of module names
302 *
303 * @return Array: List of module names
304 */
305 public function getModuleNames() {
306 return array_keys( $this->moduleInfos );
307 }
308
309 /**
310 * Get the ResourceLoaderModule object for a given module name.
311 *
312 * @param $name String: Module name
313 * @return ResourceLoaderModule if module has been registered, null otherwise
314 */
315 public function getModule( $name ) {
316 if ( !isset( $this->modules[$name] ) ) {
317 if ( !isset( $this->moduleInfos[$name] ) ) {
318 // No such module
319 return null;
320 }
321 // Construct the requested object
322 $info = $this->moduleInfos[$name];
323 if ( isset( $info['object'] ) ) {
324 // Object given in info array
325 $object = $info['object'];
326 } else {
327 if ( !isset( $info['class'] ) ) {
328 $class = 'ResourceLoaderFileModule';
329 } else {
330 $class = $info['class'];
331 }
332 $object = new $class( $info );
333 }
334 $object->setName( $name );
335 $this->modules[$name] = $object;
336 }
337
338 return $this->modules[$name];
339 }
340
341 /**
342 * Get the list of sources
343 *
344 * @return Array: array( id => array of properties, .. )
345 */
346 public function getSources() {
347 return $this->sources;
348 }
349
350 /**
351 * Outputs a response to a resource load-request, including a content-type header.
352 *
353 * @param $context ResourceLoaderContext: Context in which a response should be formed
354 */
355 public function respond( ResourceLoaderContext $context ) {
356 global $wgResourceLoaderMaxage, $wgCacheEpoch;
357
358 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
359 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
360 // is used: ob_clean() will clear the GZIP header in that case and it won't come
361 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
362 // the whole thing in our own output buffer to be sure the active buffer
363 // doesn't use ob_gzhandler.
364 // See http://bugs.php.net/bug.php?id=36514
365 ob_start();
366
367 wfProfileIn( __METHOD__ );
368 $exceptions = '';
369
370 // Split requested modules into two groups, modules and missing
371 $modules = array();
372 $missing = array();
373 foreach ( $context->getModules() as $name ) {
374 if ( isset( $this->moduleInfos[$name] ) ) {
375 $modules[$name] = $this->getModule( $name );
376 } else {
377 $missing[] = $name;
378 }
379 }
380
381 // If a version wasn't specified we need a shorter expiry time for updates
382 // to propagate to clients quickly
383 if ( is_null( $context->getVersion() ) ) {
384 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
385 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
386 }
387 // If a version was specified we can use a longer expiry time since changing
388 // version numbers causes cache misses
389 else {
390 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
391 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
392 }
393
394 // Preload information needed to the mtime calculation below
395 try {
396 $this->preloadModuleInfo( array_keys( $modules ), $context );
397 } catch( Exception $e ) {
398 // Add exception to the output as a comment
399 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
400 }
401
402 wfProfileIn( __METHOD__.'-getModifiedTime' );
403
404 $private = false;
405 // To send Last-Modified and support If-Modified-Since, we need to detect
406 // the last modified time
407 $mtime = wfTimestamp( TS_UNIX, $wgCacheEpoch );
408 foreach ( $modules as $module ) {
409 try {
410 // Bypass Squid and other shared caches if the request includes any private modules
411 if ( $module->getGroup() === 'private' ) {
412 $private = true;
413 }
414 // Calculate maximum modified time
415 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
416 } catch ( Exception $e ) {
417 // Add exception to the output as a comment
418 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
419 }
420 }
421
422 wfProfileOut( __METHOD__.'-getModifiedTime' );
423
424 if ( $context->getOnly() === 'styles' ) {
425 header( 'Content-Type: text/css; charset=utf-8' );
426 } else {
427 header( 'Content-Type: text/javascript; charset=utf-8' );
428 }
429 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $mtime ) );
430 if ( $context->getDebug() ) {
431 // Do not cache debug responses
432 header( 'Cache-Control: private, no-cache, must-revalidate' );
433 header( 'Pragma: no-cache' );
434 } else {
435 if ( $private ) {
436 header( "Cache-Control: private, max-age=$maxage" );
437 $exp = $maxage;
438 } else {
439 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
440 $exp = min( $maxage, $smaxage );
441 }
442 header( 'Expires: ' . wfTimestamp( TS_RFC2822, $exp + time() ) );
443 }
444
445 // If there's an If-Modified-Since header, respond with a 304 appropriately
446 // Some clients send "timestamp;length=123". Strip the part after the first ';'
447 // so we get a valid timestamp.
448 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
449 // Never send 304s in debug mode
450 if ( $ims !== false && !$context->getDebug() ) {
451 $imsTS = strtok( $ims, ';' );
452 if ( $mtime <= wfTimestamp( TS_UNIX, $imsTS ) ) {
453 // There's another bug in ob_gzhandler (see also the comment at
454 // the top of this function) that causes it to gzip even empty
455 // responses, meaning it's impossible to produce a truly empty
456 // response (because the gzip header is always there). This is
457 // a problem because 304 responses have to be completely empty
458 // per the HTTP spec, and Firefox behaves buggily when they're not.
459 // See also http://bugs.php.net/bug.php?id=51579
460 // To work around this, we tear down all output buffering before
461 // sending the 304.
462 // On some setups, ob_get_level() doesn't seem to go down to zero
463 // no matter how often we call ob_get_clean(), so instead of doing
464 // the more intuitive while ( ob_get_level() > 0 ) ob_get_clean();
465 // we have to be safe here and avoid an infinite loop.
466 for ( $i = 0; $i < ob_get_level(); $i++ ) {
467 ob_end_clean();
468 }
469
470 header( 'HTTP/1.0 304 Not Modified' );
471 header( 'Status: 304 Not Modified' );
472 wfProfileOut( __METHOD__ );
473 return;
474 }
475 }
476
477 // Generate a response
478 $response = $this->makeModuleResponse( $context, $modules, $missing );
479
480 // Prepend comments indicating exceptions
481 $response = $exceptions . $response;
482
483 // Capture any PHP warnings from the output buffer and append them to the
484 // response in a comment if we're in debug mode.
485 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
486 $response = "/*\n$warnings\n*/\n" . $response;
487 }
488
489 // Remove the output buffer and output the response
490 ob_end_clean();
491 echo $response;
492
493 wfProfileOut( __METHOD__ );
494 }
495
496 /**
497 * Generates code for a response
498 *
499 * @param $context ResourceLoaderContext: Context in which to generate a response
500 * @param $modules Array: List of module objects keyed by module name
501 * @param $missing Array: List of unavailable modules (optional)
502 * @return String: Response data
503 */
504 public function makeModuleResponse( ResourceLoaderContext $context,
505 array $modules, $missing = array() )
506 {
507 $out = '';
508 $exceptions = '';
509 if ( $modules === array() && $missing === array() ) {
510 return '/* No modules requested. Max made me put this here */';
511 }
512
513 wfProfileIn( __METHOD__ );
514 // Pre-fetch blobs
515 if ( $context->shouldIncludeMessages() ) {
516 try {
517 $blobs = MessageBlobStore::get( $this, $modules, $context->getLanguage() );
518 } catch ( Exception $e ) {
519 // Add exception to the output as a comment
520 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
521 }
522 } else {
523 $blobs = array();
524 }
525
526 // Generate output
527 foreach ( $modules as $name => $module ) {
528 wfProfileIn( __METHOD__ . '-' . $name );
529 try {
530 $scripts = '';
531 if ( $context->shouldIncludeScripts() ) {
532 // If we are in debug mode, we'll want to return an array of URLs if possible
533 // However, we can't do this if the module doesn't support it
534 // We also can't do this if there is an only= parameter, because we have to give
535 // the module a way to return a load.php URL without causing an infinite loop
536 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
537 $scripts = $module->getScriptURLsForDebug( $context );
538 } else {
539 $scripts = $module->getScript( $context );
540 if ( is_string( $scripts ) ) {
541 // bug 27054: Append semicolon to prevent weird bugs
542 // caused by files not terminating their statements right
543 $scripts .= ";\n";
544 }
545 }
546 }
547 // Styles
548 $styles = array();
549 if ( $context->shouldIncludeStyles() ) {
550 // If we are in debug mode, we'll want to return an array of URLs
551 // See comment near shouldIncludeScripts() for more details
552 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
553 $styles = $module->getStyleURLsForDebug( $context );
554 } else {
555 $styles = $module->getStyles( $context );
556 }
557 }
558
559 // Messages
560 $messagesBlob = isset( $blobs[$name] ) ? $blobs[$name] : '{}';
561
562 // Append output
563 switch ( $context->getOnly() ) {
564 case 'scripts':
565 if ( is_string( $scripts ) ) {
566 // Load scripts raw...
567 $out .= $scripts;
568 } elseif ( is_array( $scripts ) ) {
569 // ...except when $scripts is an array of URLs
570 $out .= self::makeLoaderImplementScript( $name, $scripts, array(), array() );
571 }
572 break;
573 case 'styles':
574 $out .= self::makeCombinedStyles( $styles );
575 break;
576 case 'messages':
577 $out .= self::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
578 break;
579 default:
580 // Minify CSS before embedding in mw.loader.implement call
581 // (unless in debug mode)
582 if ( !$context->getDebug() ) {
583 foreach ( $styles as $media => $style ) {
584 if ( is_string( $style ) ) {
585 $styles[$media] = $this->filter( 'minify-css', $style );
586 }
587 }
588 }
589 $out .= self::makeLoaderImplementScript( $name, $scripts, $styles,
590 new XmlJsCode( $messagesBlob ) );
591 break;
592 }
593 } catch ( Exception $e ) {
594 // Add exception to the output as a comment
595 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
596
597 // Register module as missing
598 $missing[] = $name;
599 unset( $modules[$name] );
600 }
601 wfProfileOut( __METHOD__ . '-' . $name );
602 }
603
604 // Update module states
605 if ( $context->shouldIncludeScripts() ) {
606 // Set the state of modules loaded as only scripts to ready
607 if ( count( $modules ) && $context->getOnly() === 'scripts'
608 && !isset( $modules['startup'] ) )
609 {
610 $out .= self::makeLoaderStateScript(
611 array_fill_keys( array_keys( $modules ), 'ready' ) );
612 }
613 // Set the state of modules which were requested but unavailable as missing
614 if ( is_array( $missing ) && count( $missing ) ) {
615 $out .= self::makeLoaderStateScript( array_fill_keys( $missing, 'missing' ) );
616 }
617 }
618
619 if ( !$context->getDebug() ) {
620 if ( $context->getOnly() === 'styles' ) {
621 $out = $this->filter( 'minify-css', $out );
622 } else {
623 $out = $this->filter( 'minify-js', $out );
624 }
625 }
626
627 wfProfileOut( __METHOD__ );
628 return $exceptions . $out;
629 }
630
631 /* Static Methods */
632
633 /**
634 * Returns JS code to call to mw.loader.implement for a module with
635 * given properties.
636 *
637 * @param $name Module name
638 * @param $scripts Mixed: List of URLs to JavaScript files or String of JavaScript code
639 * @param $styles Mixed: List of CSS strings keyed by media type, or list of lists of URLs to
640 * CSS files keyed by media type
641 * @param $messages Mixed: List of messages associated with this module. May either be an
642 * associative array mapping message key to value, or a JSON-encoded message blob containing
643 * the same data, wrapped in an XmlJsCode object.
644 *
645 * @return string
646 */
647 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
648 if ( is_string( $scripts ) ) {
649 $scripts = new XmlJsCode( "function( $ ) {{$scripts}}" );
650 } elseif ( !is_array( $scripts ) ) {
651 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
652 }
653 return Xml::encodeJsCall(
654 'mw.loader.implement',
655 array(
656 $name,
657 $scripts,
658 (object)$styles,
659 (object)$messages
660 ) );
661 }
662
663 /**
664 * Returns JS code which, when called, will register a given list of messages.
665 *
666 * @param $messages Mixed: Either an associative array mapping message key to value, or a
667 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
668 *
669 * @return string
670 */
671 public static function makeMessageSetScript( $messages ) {
672 return Xml::encodeJsCall( 'mw.messages.set', array( (object)$messages ) );
673 }
674
675 /**
676 * Combines an associative array mapping media type to CSS into a
677 * single stylesheet with @media blocks.
678 *
679 * @param $styles Array: List of CSS strings keyed by media type
680 *
681 * @return string
682 */
683 public static function makeCombinedStyles( array $styles ) {
684 $out = '';
685 foreach ( $styles as $media => $style ) {
686 // Transform the media type based on request params and config
687 // The way that this relies on $wgRequest to propagate request params is slightly evil
688 $media = OutputPage::transformCssMedia( $media );
689
690 if ( $media === null ) {
691 // Skip
692 } elseif ( $media === '' || $media == 'all' ) {
693 // Don't output invalid or frivolous @media statements
694 $out .= "$style\n";
695 } else {
696 $out .= "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "\n}\n";
697 }
698 }
699 return $out;
700 }
701
702 /**
703 * Returns a JS call to mw.loader.state, which sets the state of a
704 * module or modules to a given value. Has two calling conventions:
705 *
706 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
707 * Set the state of a single module called $name to $state
708 *
709 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
710 * Set the state of modules with the given names to the given states
711 *
712 * @param $name string
713 * @param $state
714 *
715 * @return string
716 */
717 public static function makeLoaderStateScript( $name, $state = null ) {
718 if ( is_array( $name ) ) {
719 return Xml::encodeJsCall( 'mw.loader.state', array( $name ) );
720 } else {
721 return Xml::encodeJsCall( 'mw.loader.state', array( $name, $state ) );
722 }
723 }
724
725 /**
726 * Returns JS code which calls the script given by $script. The script will
727 * be called with local variables name, version, dependencies and group,
728 * which will have values corresponding to $name, $version, $dependencies
729 * and $group as supplied.
730 *
731 * @param $name String: Module name
732 * @param $version Integer: Module version number as a timestamp
733 * @param $dependencies Array: List of module names on which this module depends
734 * @param $group String: Group which the module is in.
735 * @param $source String: Source of the module, or 'local' if not foreign.
736 * @param $script String: JavaScript code
737 *
738 * @return string
739 */
740 public static function makeCustomLoaderScript( $name, $version, $dependencies, $group, $source, $script ) {
741 $script = str_replace( "\n", "\n\t", trim( $script ) );
742 return Xml::encodeJsCall(
743 "( function( name, version, dependencies, group, source ) {\n\t$script\n} )",
744 array( $name, $version, $dependencies, $group, $source ) );
745 }
746
747 /**
748 * Returns JS code which calls mw.loader.register with the given
749 * parameters. Has three calling conventions:
750 *
751 * - ResourceLoader::makeLoaderRegisterScript( $name, $version, $dependencies, $group, $source ):
752 * Register a single module.
753 *
754 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
755 * Register modules with the given names.
756 *
757 * - ResourceLoader::makeLoaderRegisterScript( array(
758 * array( $name1, $version1, $dependencies1, $group1, $source1 ),
759 * array( $name2, $version2, $dependencies1, $group2, $source2 ),
760 * ...
761 * ) ):
762 * Registers modules with the given names and parameters.
763 *
764 * @param $name String: Module name
765 * @param $version Integer: Module version number as a timestamp
766 * @param $dependencies Array: List of module names on which this module depends
767 * @param $group String: group which the module is in.
768 * @param $source String: source of the module, or 'local' if not foreign
769 *
770 * @return string
771 */
772 public static function makeLoaderRegisterScript( $name, $version = null,
773 $dependencies = null, $group = null, $source = null )
774 {
775 if ( is_array( $name ) ) {
776 return Xml::encodeJsCall( 'mw.loader.register', array( $name ) );
777 } else {
778 $version = (int) $version > 1 ? (int) $version : 1;
779 return Xml::encodeJsCall( 'mw.loader.register',
780 array( $name, $version, $dependencies, $group, $source ) );
781 }
782 }
783
784 /**
785 * Returns JS code which calls mw.loader.addSource() with the given
786 * parameters. Has two calling conventions:
787 *
788 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
789 * Register a single source
790 *
791 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $props1, $id2 => $props2, ... ) );
792 * Register sources with the given IDs and properties.
793 *
794 * @param $id String: source ID
795 * @param $properties Array: source properties (see addSource())
796 */
797 public static function makeLoaderSourcesScript( $id, $properties = null ) {
798 if ( is_array( $id ) ) {
799 return Xml::encodeJsCall( 'mw.loader.addSource', array( $id ) );
800 } else {
801 return Xml::encodeJsCall( 'mw.loader.addSource', array( $id, $properties ) );
802 }
803 }
804
805 /**
806 * Returns JS code which runs given JS code if the client-side framework is
807 * present.
808 *
809 * @param $script String: JavaScript code
810 *
811 * @return string
812 */
813 public static function makeLoaderConditionalScript( $script ) {
814 $script = str_replace( "\n", "\n\t", trim( $script ) );
815 return "if ( window.mediaWiki ) {\n\t$script\n}\n";
816 }
817
818 /**
819 * Returns JS code which will set the MediaWiki configuration array to
820 * the given value.
821 *
822 * @param $configuration Array: List of configuration values keyed by variable name
823 *
824 * @return string
825 */
826 public static function makeConfigSetScript( array $configuration ) {
827 return Xml::encodeJsCall( 'mw.config.set', array( $configuration ) );
828 }
829
830 /**
831 * Convert an array of module names to a packed query string.
832 *
833 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
834 * becomes 'foo.bar,baz|bar.baz,quux'
835 * @param $modules array of module names (strings)
836 * @return string Packed query string
837 */
838 public static function makePackedModulesString( $modules ) {
839 $groups = array(); // array( prefix => array( suffixes ) )
840 foreach ( $modules as $module ) {
841 $pos = strrpos( $module, '.' );
842 $prefix = $pos === false ? '' : substr( $module, 0, $pos );
843 $suffix = $pos === false ? $module : substr( $module, $pos + 1 );
844 $groups[$prefix][] = $suffix;
845 }
846
847 $arr = array();
848 foreach ( $groups as $prefix => $suffixes ) {
849 $p = $prefix === '' ? '' : $prefix . '.';
850 $arr[] = $p . implode( ',', $suffixes );
851 }
852 $str = implode( '|', $arr );
853 return $str;
854 }
855
856 /**
857 * Determine whether debug mode was requested
858 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
859 * @return bool
860 */
861 public static function inDebugMode() {
862 global $wgRequest, $wgResourceLoaderDebug;
863 static $retval = null;
864 if ( !is_null( $retval ) ) {
865 return $retval;
866 }
867 return $retval = $wgRequest->getFuzzyBool( 'debug',
868 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug ) );
869 }
870
871 /**
872 * Build a load.php URL
873 * @param $modules array of module names (strings)
874 * @param $lang string Language code
875 * @param $skin string Skin name
876 * @param $user string|null User name. If null, the &user= parameter is omitted
877 * @param $version string|null Versioning timestamp
878 * @param $debug bool Whether the request should be in debug mode
879 * @param $only string|null &only= parameter
880 * @param $printable bool Printable mode
881 * @param $handheld bool Handheld mode
882 * @param $extraQuery array Extra query parameters to add
883 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
884 */
885 public static function makeLoaderURL( $modules, $lang, $skin, $user = null, $version = null, $debug = false, $only = null,
886 $printable = false, $handheld = false, $extraQuery = array() ) {
887 global $wgLoadScript;
888 $query = self::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
889 $only, $printable, $handheld, $extraQuery
890 );
891
892 // Prevent the IE6 extension check from being triggered (bug 28840)
893 // by appending a character that's invalid in Windows extensions ('*')
894 return wfAppendQuery( $wgLoadScript, $query ) . '&*';
895 }
896
897 /**
898 * Build a query array (array representation of query string) for load.php. Helper
899 * function for makeLoaderURL().
900 * @return array
901 */
902 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null, $version = null, $debug = false, $only = null,
903 $printable = false, $handheld = false, $extraQuery = array() ) {
904 $query = array(
905 'modules' => self::makePackedModulesString( $modules ),
906 'lang' => $lang,
907 'skin' => $skin,
908 'debug' => $debug ? 'true' : 'false',
909 );
910 if ( $user !== null ) {
911 $query['user'] = $user;
912 }
913 if ( $version !== null ) {
914 $query['version'] = $version;
915 }
916 if ( $only !== null ) {
917 $query['only'] = $only;
918 }
919 if ( $printable ) {
920 $query['printable'] = 1;
921 }
922 if ( $handheld ) {
923 $query['handheld'] = 1;
924 }
925 $query += $extraQuery;
926
927 // Make queries uniform in order
928 ksort( $query );
929 return $query;
930 }
931 }