Completely rewritten table sorting script.
[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 = 4;
33
34 /** Array: List of module name/ResourceLoaderModule object pairs */
35 protected $modules = array();
36 /** Associative array mapping module name to info associative array */
37 protected $moduleInfos = array();
38
39 /* Protected Methods */
40
41 /**
42 * Loads information stored in the database about modules.
43 *
44 * This method grabs modules dependencies from the database and updates modules
45 * objects.
46 *
47 * This is not inside the module code because it is much faster to
48 * request all of the information at once than it is to have each module
49 * requests its own information. This sacrifice of modularity yields a substantial
50 * performance improvement.
51 *
52 * @param $modules Array: List of module names to preload information for
53 * @param $context ResourceLoaderContext: Context to load the information within
54 */
55 public function preloadModuleInfo( array $modules, ResourceLoaderContext $context ) {
56 if ( !count( $modules ) ) {
57 return; // or else Database*::select() will explode, plus it's cheaper!
58 }
59 $dbr = wfGetDB( DB_SLAVE );
60 $skin = $context->getSkin();
61 $lang = $context->getLanguage();
62
63 // Get file dependency information
64 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
65 'md_module' => $modules,
66 'md_skin' => $context->getSkin()
67 ), __METHOD__
68 );
69
70 // Set modules' dependencies
71 $modulesWithDeps = array();
72 foreach ( $res as $row ) {
73 $this->getModule( $row->md_module )->setFileDependencies( $skin,
74 FormatJson::decode( $row->md_deps, true )
75 );
76 $modulesWithDeps[] = $row->md_module;
77 }
78
79 // Register the absence of a dependency row too
80 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
81 $this->getModule( $name )->setFileDependencies( $skin, array() );
82 }
83
84 // Get message blob mtimes. Only do this for modules with messages
85 $modulesWithMessages = array();
86 foreach ( $modules as $name ) {
87 if ( count( $this->getModule( $name )->getMessages() ) ) {
88 $modulesWithMessages[] = $name;
89 }
90 }
91 $modulesWithoutMessages = array_flip( $modules ); // Will be trimmed down by the loop below
92 if ( count( $modulesWithMessages ) ) {
93 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
94 'mr_resource' => $modulesWithMessages,
95 'mr_lang' => $lang
96 ), __METHOD__
97 );
98 foreach ( $res as $row ) {
99 $this->getModule( $row->mr_resource )->setMsgBlobMtime( $lang,
100 wfTimestamp( TS_UNIX, $row->mr_timestamp ) );
101 unset( $modulesWithoutMessages[$row->mr_resource] );
102 }
103 }
104 foreach ( array_keys( $modulesWithoutMessages ) as $name ) {
105 $this->getModule( $name )->setMsgBlobMtime( $lang, 0 );
106 }
107 }
108
109 /**
110 * Runs JavaScript or CSS data through a filter, caching the filtered result for future calls.
111 *
112 * Available filters are:
113 * - minify-js \see JavaScriptMinifier::minify
114 * - minify-css \see CSSMin::minify
115 *
116 * If $data is empty, only contains whitespace or the filter was unknown,
117 * $data is returned unmodified.
118 *
119 * @param $filter String: Name of filter to run
120 * @param $data String: Text to filter, such as JavaScript or CSS text
121 * @return String: Filtered data, or a comment containing an error message
122 */
123 protected function filter( $filter, $data ) {
124 global $wgResourceLoaderMinifierStatementsOnOwnLine, $wgResourceLoaderMinifierMaxLineLength;
125 wfProfileIn( __METHOD__ );
126
127 // For empty/whitespace-only data or for unknown filters, don't perform
128 // any caching or processing
129 if ( trim( $data ) === ''
130 || !in_array( $filter, array( 'minify-js', 'minify-css' ) ) )
131 {
132 wfProfileOut( __METHOD__ );
133 return $data;
134 }
135
136 // Try for cache hit
137 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
138 $key = wfMemcKey( 'resourceloader', 'filter', $filter, self::$filterCacheVersion, md5( $data ) );
139 $cache = wfGetCache( CACHE_ANYTHING );
140 $cacheEntry = $cache->get( $key );
141 if ( is_string( $cacheEntry ) ) {
142 wfProfileOut( __METHOD__ );
143 return $cacheEntry;
144 }
145
146 $result = '';
147 // Run the filter - we've already verified one of these will work
148 try {
149 switch ( $filter ) {
150 case 'minify-js':
151 $result = JavaScriptMinifier::minify( $data,
152 $wgResourceLoaderMinifierStatementsOnOwnLine,
153 $wgResourceLoaderMinifierMaxLineLength
154 );
155 $result .= "\n\n/* cache key: $key */\n";
156 break;
157 case 'minify-css':
158 $result = CSSMin::minify( $data );
159 $result .= "\n\n/* cache key: $key */\n";
160 break;
161 }
162
163 // Save filtered text to Memcached
164 $cache->set( $key, $result );
165 } catch ( Exception $exception ) {
166 // Return exception as a comment
167 $result = "/*\n{$exception->__toString()}\n*/\n";
168 }
169
170 wfProfileOut( __METHOD__ );
171
172 return $result;
173 }
174
175 /* Methods */
176
177 /**
178 * Registers core modules and runs registration hooks.
179 */
180 public function __construct() {
181 global $IP, $wgResourceModules;
182
183 wfProfileIn( __METHOD__ );
184
185 // Register core modules
186 $this->register( include( "$IP/resources/Resources.php" ) );
187 // Register extension modules
188 wfRunHooks( 'ResourceLoaderRegisterModules', array( &$this ) );
189 $this->register( $wgResourceModules );
190
191 wfProfileOut( __METHOD__ );
192 }
193
194 /**
195 * Registers a module with the ResourceLoader system.
196 *
197 * @param $name Mixed: Name of module as a string or List of name/object pairs as an array
198 * @param $info Module info array. For backwards compatibility with 1.17alpha,
199 * this may also be a ResourceLoaderModule object. Optional when using
200 * multiple-registration calling style.
201 * @throws MWException: If a duplicate module registration is attempted
202 * @throws MWException: If something other than a ResourceLoaderModule is being registered
203 * @return Boolean: False if there were any errors, in which case one or more modules were not
204 * registered
205 */
206 public function register( $name, $info = null ) {
207 wfProfileIn( __METHOD__ );
208
209 // Allow multiple modules to be registered in one call
210 if ( is_array( $name ) ) {
211 foreach ( $name as $key => $value ) {
212 $this->register( $key, $value );
213 }
214 wfProfileOut( __METHOD__ );
215 return;
216 }
217
218 // Disallow duplicate registrations
219 if ( isset( $this->moduleInfos[$name] ) ) {
220 // A module has already been registered by this name
221 throw new MWException(
222 'ResourceLoader duplicate registration error. ' .
223 'Another module has already been registered as ' . $name
224 );
225 }
226
227 // Attach module
228 if ( is_object( $info ) ) {
229 // Old calling convention
230 // Validate the input
231 if ( !( $info instanceof ResourceLoaderModule ) ) {
232 throw new MWException( 'ResourceLoader invalid module error. ' .
233 'Instances of ResourceLoaderModule expected.' );
234 }
235
236 $this->moduleInfos[$name] = array( 'object' => $info );
237 $info->setName( $name );
238 $this->modules[$name] = $info;
239 } else {
240 // New calling convention
241 $this->moduleInfos[$name] = $info;
242 }
243
244 wfProfileOut( __METHOD__ );
245 }
246
247 /**
248 * Get a list of module names
249 *
250 * @return Array: List of module names
251 */
252 public function getModuleNames() {
253 return array_keys( $this->moduleInfos );
254 }
255
256 /**
257 * Get the ResourceLoaderModule object for a given module name.
258 *
259 * @param $name String: Module name
260 * @return ResourceLoaderModule if module has been registered, null otherwise
261 */
262 public function getModule( $name ) {
263 if ( !isset( $this->modules[$name] ) ) {
264 if ( !isset( $this->moduleInfos[$name] ) ) {
265 // No such module
266 return null;
267 }
268 // Construct the requested object
269 $info = $this->moduleInfos[$name];
270 if ( isset( $info['object'] ) ) {
271 // Object given in info array
272 $object = $info['object'];
273 } else {
274 if ( !isset( $info['class'] ) ) {
275 $class = 'ResourceLoaderFileModule';
276 } else {
277 $class = $info['class'];
278 }
279 $object = new $class( $info );
280 }
281 $object->setName( $name );
282 $this->modules[$name] = $object;
283 }
284
285 return $this->modules[$name];
286 }
287
288 /**
289 * Outputs a response to a resource load-request, including a content-type header.
290 *
291 * @param $context ResourceLoaderContext: Context in which a response should be formed
292 */
293 public function respond( ResourceLoaderContext $context ) {
294 global $wgResourceLoaderMaxage, $wgCacheEpoch;
295
296 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
297 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
298 // is used: ob_clean() will clear the GZIP header in that case and it won't come
299 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
300 // the whole thing in our own output buffer to be sure the active buffer
301 // doesn't use ob_gzhandler.
302 // See http://bugs.php.net/bug.php?id=36514
303 ob_start();
304
305 wfProfileIn( __METHOD__ );
306 $exceptions = '';
307
308 // Split requested modules into two groups, modules and missing
309 $modules = array();
310 $missing = array();
311 foreach ( $context->getModules() as $name ) {
312 if ( isset( $this->moduleInfos[$name] ) ) {
313 $modules[$name] = $this->getModule( $name );
314 } else {
315 $missing[] = $name;
316 }
317 }
318
319 // If a version wasn't specified we need a shorter expiry time for updates
320 // to propagate to clients quickly
321 if ( is_null( $context->getVersion() ) ) {
322 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
323 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
324 }
325 // If a version was specified we can use a longer expiry time since changing
326 // version numbers causes cache misses
327 else {
328 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
329 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
330 }
331
332 // Preload information needed to the mtime calculation below
333 try {
334 $this->preloadModuleInfo( array_keys( $modules ), $context );
335 } catch( Exception $e ) {
336 // Add exception to the output as a comment
337 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
338 }
339
340 wfProfileIn( __METHOD__.'-getModifiedTime' );
341
342 $private = false;
343 // To send Last-Modified and support If-Modified-Since, we need to detect
344 // the last modified time
345 $mtime = wfTimestamp( TS_UNIX, $wgCacheEpoch );
346 foreach ( $modules as $module ) {
347 try {
348 // Bypass Squid and other shared caches if the request includes any private modules
349 if ( $module->getGroup() === 'private' ) {
350 $private = true;
351 }
352 // Calculate maximum modified time
353 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
354 } catch ( Exception $e ) {
355 // Add exception to the output as a comment
356 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
357 }
358 }
359
360 wfProfileOut( __METHOD__.'-getModifiedTime' );
361
362 if ( $context->getOnly() === 'styles' ) {
363 header( 'Content-Type: text/css; charset=utf-8' );
364 } else {
365 header( 'Content-Type: text/javascript; charset=utf-8' );
366 }
367 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $mtime ) );
368 if ( $context->getDebug() ) {
369 // Do not cache debug responses
370 header( 'Cache-Control: private, no-cache, must-revalidate' );
371 header( 'Pragma: no-cache' );
372 } else {
373 if ( $private ) {
374 header( "Cache-Control: private, max-age=$maxage" );
375 $exp = $maxage;
376 } else {
377 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
378 $exp = min( $maxage, $smaxage );
379 }
380 header( 'Expires: ' . wfTimestamp( TS_RFC2822, $exp + time() ) );
381 }
382
383 // If there's an If-Modified-Since header, respond with a 304 appropriately
384 // Some clients send "timestamp;length=123". Strip the part after the first ';'
385 // so we get a valid timestamp.
386 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
387 // Never send 304s in debug mode
388 if ( $ims !== false && !$context->getDebug() ) {
389 $imsTS = strtok( $ims, ';' );
390 if ( $mtime <= wfTimestamp( TS_UNIX, $imsTS ) ) {
391 // There's another bug in ob_gzhandler (see also the comment at
392 // the top of this function) that causes it to gzip even empty
393 // responses, meaning it's impossible to produce a truly empty
394 // response (because the gzip header is always there). This is
395 // a problem because 304 responses have to be completely empty
396 // per the HTTP spec, and Firefox behaves buggily when they're not.
397 // See also http://bugs.php.net/bug.php?id=51579
398 // To work around this, we tear down all output buffering before
399 // sending the 304.
400 // On some setups, ob_get_level() doesn't seem to go down to zero
401 // no matter how often we call ob_get_clean(), so instead of doing
402 // the more intuitive while ( ob_get_level() > 0 ) ob_get_clean();
403 // we have to be safe here and avoid an infinite loop.
404 for ( $i = 0; $i < ob_get_level(); $i++ ) {
405 ob_end_clean();
406 }
407
408 header( 'HTTP/1.0 304 Not Modified' );
409 header( 'Status: 304 Not Modified' );
410 wfProfileOut( __METHOD__ );
411 return;
412 }
413 }
414
415 // Generate a response
416 $response = $this->makeModuleResponse( $context, $modules, $missing );
417
418 // Prepend comments indicating exceptions
419 $response = $exceptions . $response;
420
421 // Capture any PHP warnings from the output buffer and append them to the
422 // response in a comment if we're in debug mode.
423 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
424 $response = "/*\n$warnings\n*/\n" . $response;
425 }
426
427 // Remove the output buffer and output the response
428 ob_end_clean();
429 echo $response;
430
431 wfProfileOut( __METHOD__ );
432 }
433
434 /**
435 * Generates code for a response
436 *
437 * @param $context ResourceLoaderContext: Context in which to generate a response
438 * @param $modules Array: List of module objects keyed by module name
439 * @param $missing Array: List of unavailable modules (optional)
440 * @return String: Response data
441 */
442 public function makeModuleResponse( ResourceLoaderContext $context,
443 array $modules, $missing = array() )
444 {
445 $out = '';
446 $exceptions = '';
447 if ( $modules === array() && $missing === array() ) {
448 return '/* No modules requested. Max made me put this here */';
449 }
450
451 wfProfileIn( __METHOD__ );
452 // Pre-fetch blobs
453 if ( $context->shouldIncludeMessages() ) {
454 try {
455 $blobs = MessageBlobStore::get( $this, $modules, $context->getLanguage() );
456 } catch ( Exception $e ) {
457 // Add exception to the output as a comment
458 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
459 }
460 } else {
461 $blobs = array();
462 }
463
464 // Generate output
465 foreach ( $modules as $name => $module ) {
466 wfProfileIn( __METHOD__ . '-' . $name );
467 try {
468 // Scripts
469 $scripts = '';
470 if ( $context->shouldIncludeScripts() ) {
471 // bug 27054: Append semicolon to prevent weird bugs
472 // caused by files not terminating their statements right
473 $scripts .= $module->getScript( $context ) . ";\n";
474 }
475
476 // Styles
477 $styles = array();
478 if ( $context->shouldIncludeStyles() ) {
479 $styles = $module->getStyles( $context );
480 }
481
482 // Messages
483 $messagesBlob = isset( $blobs[$name] ) ? $blobs[$name] : '{}';
484
485 // Append output
486 switch ( $context->getOnly() ) {
487 case 'scripts':
488 $out .= $scripts;
489 break;
490 case 'styles':
491 $out .= self::makeCombinedStyles( $styles );
492 break;
493 case 'messages':
494 $out .= self::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
495 break;
496 default:
497 // Minify CSS before embedding in mw.loader.implement call
498 // (unless in debug mode)
499 if ( !$context->getDebug() ) {
500 foreach ( $styles as $media => $style ) {
501 $styles[$media] = $this->filter( 'minify-css', $style );
502 }
503 }
504 $out .= self::makeLoaderImplementScript( $name, $scripts, $styles,
505 new XmlJsCode( $messagesBlob ) );
506 break;
507 }
508 } catch ( Exception $e ) {
509 // Add exception to the output as a comment
510 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
511
512 // Register module as missing
513 $missing[] = $name;
514 unset( $modules[$name] );
515 }
516 wfProfileOut( __METHOD__ . '-' . $name );
517 }
518
519 // Update module states
520 if ( $context->shouldIncludeScripts() ) {
521 // Set the state of modules loaded as only scripts to ready
522 if ( count( $modules ) && $context->getOnly() === 'scripts'
523 && !isset( $modules['startup'] ) )
524 {
525 $out .= self::makeLoaderStateScript(
526 array_fill_keys( array_keys( $modules ), 'ready' ) );
527 }
528 // Set the state of modules which were requested but unavailable as missing
529 if ( is_array( $missing ) && count( $missing ) ) {
530 $out .= self::makeLoaderStateScript( array_fill_keys( $missing, 'missing' ) );
531 }
532 }
533
534 if ( !$context->getDebug() ) {
535 if ( $context->getOnly() === 'styles' ) {
536 $out = $this->filter( 'minify-css', $out );
537 } else {
538 $out = $this->filter( 'minify-js', $out );
539 }
540 }
541
542 wfProfileOut( __METHOD__ );
543 return $exceptions . $out;
544 }
545
546 /* Static Methods */
547
548 /**
549 * Returns JS code to call to mw.loader.implement for a module with
550 * given properties.
551 *
552 * @param $name Module name
553 * @param $scripts Array: List of JavaScript code snippets to be executed after the
554 * module is loaded
555 * @param $styles Array: List of CSS strings keyed by media type
556 * @param $messages Mixed: List of messages associated with this module. May either be an
557 * associative array mapping message key to value, or a JSON-encoded message blob containing
558 * the same data, wrapped in an XmlJsCode object.
559 */
560 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
561 if ( is_array( $scripts ) ) {
562 $scripts = implode( $scripts, "\n" );
563 }
564 return Xml::encodeJsCall(
565 'mw.loader.implement',
566 array(
567 $name,
568 new XmlJsCode( "function( $ ) {{$scripts}}" ),
569 (object)$styles,
570 (object)$messages
571 ) );
572 }
573
574 /**
575 * Returns JS code which, when called, will register a given list of messages.
576 *
577 * @param $messages Mixed: Either an associative array mapping message key to value, or a
578 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
579 */
580 public static function makeMessageSetScript( $messages ) {
581 return Xml::encodeJsCall( 'mw.messages.set', array( (object)$messages ) );
582 }
583
584 /**
585 * Combines an associative array mapping media type to CSS into a
586 * single stylesheet with @media blocks.
587 *
588 * @param $styles Array: List of CSS strings keyed by media type
589 */
590 public static function makeCombinedStyles( array $styles ) {
591 $out = '';
592 foreach ( $styles as $media => $style ) {
593 // Transform the media type based on request params and config
594 // The way that this relies on $wgRequest to propagate request params is slightly evil
595 $media = OutputPage::transformCssMedia( $media );
596
597 if ( $media === null ) {
598 // Skip
599 } else if ( $media === '' || $media == 'all' ) {
600 // Don't output invalid or frivolous @media statements
601 $out .= "$style\n";
602 } else {
603 $out .= "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "\n}\n";
604 }
605 }
606 return $out;
607 }
608
609 /**
610 * Returns a JS call to mw.loader.state, which sets the state of a
611 * module or modules to a given value. Has two calling conventions:
612 *
613 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
614 * Set the state of a single module called $name to $state
615 *
616 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
617 * Set the state of modules with the given names to the given states
618 */
619 public static function makeLoaderStateScript( $name, $state = null ) {
620 if ( is_array( $name ) ) {
621 return Xml::encodeJsCall( 'mw.loader.state', array( $name ) );
622 } else {
623 return Xml::encodeJsCall( 'mw.loader.state', array( $name, $state ) );
624 }
625 }
626
627 /**
628 * Returns JS code which calls the script given by $script. The script will
629 * be called with local variables name, version, dependencies and group,
630 * which will have values corresponding to $name, $version, $dependencies
631 * and $group as supplied.
632 *
633 * @param $name String: Module name
634 * @param $version Integer: Module version number as a timestamp
635 * @param $dependencies Array: List of module names on which this module depends
636 * @param $group String: Group which the module is in.
637 * @param $script String: JavaScript code
638 */
639 public static function makeCustomLoaderScript( $name, $version, $dependencies, $group, $script ) {
640 $script = str_replace( "\n", "\n\t", trim( $script ) );
641 return Xml::encodeJsCall(
642 "( function( name, version, dependencies, group ) {\n\t$script\n} )",
643 array( $name, $version, $dependencies, $group ) );
644 }
645
646 /**
647 * Returns JS code which calls mw.loader.register with the given
648 * parameters. Has three calling conventions:
649 *
650 * - ResourceLoader::makeLoaderRegisterScript( $name, $version, $dependencies, $group ):
651 * Register a single module.
652 *
653 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
654 * Register modules with the given names.
655 *
656 * - ResourceLoader::makeLoaderRegisterScript( array(
657 * array( $name1, $version1, $dependencies1, $group1 ),
658 * array( $name2, $version2, $dependencies1, $group2 ),
659 * ...
660 * ) ):
661 * Registers modules with the given names and parameters.
662 *
663 * @param $name String: Module name
664 * @param $version Integer: Module version number as a timestamp
665 * @param $dependencies Array: List of module names on which this module depends
666 * @param $group String: group which the module is in.
667 */
668 public static function makeLoaderRegisterScript( $name, $version = null,
669 $dependencies = null, $group = null )
670 {
671 if ( is_array( $name ) ) {
672 return Xml::encodeJsCall( 'mediaWiki.loader.register', array( $name ) );
673 } else {
674 $version = (int) $version > 1 ? (int) $version : 1;
675 return Xml::encodeJsCall( 'mediaWiki.loader.register',
676 array( $name, $version, $dependencies, $group ) );
677 }
678 }
679
680 /**
681 * Returns JS code which runs given JS code if the client-side framework is
682 * present.
683 *
684 * @param $script String: JavaScript code
685 */
686 public static function makeLoaderConditionalScript( $script ) {
687 $script = str_replace( "\n", "\n\t", trim( $script ) );
688 return "if ( window.mediaWiki ) {\n\t$script\n}\n";
689 }
690
691 /**
692 * Returns JS code which will set the MediaWiki configuration array to
693 * the given value.
694 *
695 * @param $configuration Array: List of configuration values keyed by variable name
696 */
697 public static function makeConfigSetScript( array $configuration ) {
698 return Xml::encodeJsCall( 'mediaWiki.config.set', array( $configuration ) );
699 }
700
701 /**
702 * Determine whether debug mode was requested
703 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
704 * @return bool
705 */
706 public static function inDebugMode() {
707 global $wgRequest, $wgResourceLoaderDebug;
708 static $retval = null;
709 if ( !is_null( $retval ) )
710 return $retval;
711 return $retval = $wgRequest->getFuzzyBool( 'debug',
712 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug ) );
713 }
714 }