Adding wfLogWarning for production warnings.
[lhc/web/wiklou.git] / resources / mediawiki / mediawiki.js
1 /*
2 * Core MediaWiki JavaScript Library
3 */
4
5 var mw = ( function ( $, undefined ) {
6 'use strict';
7
8 /* Private Members */
9
10 var hasOwn = Object.prototype.hasOwnProperty,
11 slice = Array.prototype.slice;
12
13 /* Object constructors */
14
15 /**
16 * Creates an object that can be read from or written to from prototype functions
17 * that allow both single and multiple variables at once.
18 * @class mw.Map
19 *
20 * @constructor
21 * @param {boolean} global Whether to store the values in the global window
22 * object or a exclusively in the object property 'values'.
23 */
24 function Map( global ) {
25 this.values = global === true ? window : {};
26 return this;
27 }
28
29 Map.prototype = {
30 /**
31 * Get the value of one or multiple a keys.
32 *
33 * If called with no arguments, all values will be returned.
34 *
35 * @param selection mixed String key or array of keys to get values for.
36 * @param fallback mixed Value to use in case key(s) do not exist (optional).
37 * @return mixed If selection was a string returns the value or null,
38 * If selection was an array, returns an object of key/values (value is null if not found),
39 * If selection was not passed or invalid, will return the 'values' object member (be careful as
40 * objects are always passed by reference in JavaScript!).
41 * @return {string|Object|null} Values as a string or object, null if invalid/inexistant.
42 */
43 get: function ( selection, fallback ) {
44 var results, i;
45 // If we only do this in the `return` block, it'll fail for the
46 // call to get() from the mutli-selection block.
47 fallback = arguments.length > 1 ? fallback : null;
48
49 if ( $.isArray( selection ) ) {
50 selection = slice.call( selection );
51 results = {};
52 for ( i = 0; i < selection.length; i++ ) {
53 results[selection[i]] = this.get( selection[i], fallback );
54 }
55 return results;
56 }
57
58 if ( typeof selection === 'string' ) {
59 if ( !hasOwn.call( this.values, selection ) ) {
60 return fallback;
61 }
62 return this.values[selection];
63 }
64
65 if ( selection === undefined ) {
66 return this.values;
67 }
68
69 // invalid selection key
70 return null;
71 },
72
73 /**
74 * Sets one or multiple key/value pairs.
75 *
76 * @param selection {mixed} String key or array of keys to set values for.
77 * @param value {mixed} Value to set (optional, only in use when key is a string)
78 * @return {Boolean} This returns true on success, false on failure.
79 */
80 set: function ( selection, value ) {
81 var s;
82
83 if ( $.isPlainObject( selection ) ) {
84 for ( s in selection ) {
85 this.values[s] = selection[s];
86 }
87 return true;
88 }
89 if ( typeof selection === 'string' && arguments.length > 1 ) {
90 this.values[selection] = value;
91 return true;
92 }
93 return false;
94 },
95
96 /**
97 * Checks if one or multiple keys exist.
98 *
99 * @param selection {mixed} String key or array of keys to check
100 * @return {boolean} Existence of key(s)
101 */
102 exists: function ( selection ) {
103 var s;
104
105 if ( $.isArray( selection ) ) {
106 for ( s = 0; s < selection.length; s++ ) {
107 if ( typeof selection[s] !== 'string' || !hasOwn.call( this.values, selection[s] ) ) {
108 return false;
109 }
110 }
111 return true;
112 }
113 return typeof selection === 'string' && hasOwn.call( this.values, selection );
114 }
115 };
116
117 /**
118 * Object constructor for messages,
119 * similar to the Message class in MediaWiki PHP.
120 * @class mw.Message
121 *
122 * @constructor
123 * @param {mw.Map} map Message storage
124 * @param {string} key
125 * @param {Array} [parameters]
126 */
127 function Message( map, key, parameters ) {
128 this.format = 'text';
129 this.map = map;
130 this.key = key;
131 this.parameters = parameters === undefined ? [] : slice.call( parameters );
132 return this;
133 }
134
135 Message.prototype = {
136 /**
137 * Simple message parser, does $N replacement, HTML-escaping (only for
138 * 'escaped' format), and nothing else.
139 *
140 * This may be overridden to provide a more complex message parser.
141 *
142 * The primary override is in mediawiki.jqueryMsg.
143 *
144 * This function will not be called for nonexistent messages.
145 */
146 parser: function () {
147 var parameters = this.parameters;
148 return this.map.get( this.key ).replace( /\$(\d+)/g, function ( str, match ) {
149 var index = parseInt( match, 10 ) - 1;
150 return parameters[index] !== undefined ? parameters[index] : '$' + match;
151 } );
152 },
153
154 /**
155 * Appends (does not replace) parameters for replacement to the .parameters property.
156 *
157 * @param {Array} parameters
158 * @chainable
159 */
160 params: function ( parameters ) {
161 var i;
162 for ( i = 0; i < parameters.length; i += 1 ) {
163 this.parameters.push( parameters[i] );
164 }
165 return this;
166 },
167
168 /**
169 * Converts message object to it's string form based on the state of format.
170 *
171 * @return {string} Message as a string in the current form or `<key>` if key does not exist.
172 */
173 toString: function () {
174 var text;
175
176 if ( !this.exists() ) {
177 // Use <key> as text if key does not exist
178 if ( this.format === 'escaped' || this.format === 'parse' ) {
179 // format 'escaped' and 'parse' need to have the brackets and key html escaped
180 return mw.html.escape( '<' + this.key + '>' );
181 }
182 return '<' + this.key + '>';
183 }
184
185 if ( this.format === 'plain' || this.format === 'text' || this.format === 'parse' ) {
186 text = this.parser();
187 }
188
189 if ( this.format === 'escaped' ) {
190 text = this.parser();
191 text = mw.html.escape( text );
192 }
193
194 return text;
195 },
196
197 /**
198 * Changes format to 'parse' and converts message to string
199 *
200 * If jqueryMsg is loaded, this parses the message text from wikitext
201 * (where supported) to HTML
202 *
203 * Otherwise, it is equivalent to plain.
204 *
205 * @return {string} String form of parsed message
206 */
207 parse: function () {
208 this.format = 'parse';
209 return this.toString();
210 },
211
212 /**
213 * Changes format to 'plain' and converts message to string
214 *
215 * This substitutes parameters, but otherwise does not change the
216 * message text.
217 *
218 * @return {string} String form of plain message
219 */
220 plain: function () {
221 this.format = 'plain';
222 return this.toString();
223 },
224
225 /**
226 * Changes format to 'text' and converts message to string
227 *
228 * If jqueryMsg is loaded, {{-transformation is done where supported
229 * (such as {{plural:}}, {{gender:}}, {{int:}}).
230 *
231 * Otherwise, it is equivalent to plain.
232 */
233 text: function () {
234 this.format = 'text';
235 return this.toString();
236 },
237
238 /**
239 * Changes the format to 'escaped' and converts message to string
240 *
241 * This is equivalent to using the 'text' format (see text method), then
242 * HTML-escaping the output.
243 *
244 * @return {string} String form of html escaped message
245 */
246 escaped: function () {
247 this.format = 'escaped';
248 return this.toString();
249 },
250
251 /**
252 * Checks if message exists
253 *
254 * @see mw.Map#exists
255 * @return {boolean}
256 */
257 exists: function () {
258 return this.map.exists( this.key );
259 }
260 };
261
262 /**
263 * @class mw
264 * @alternateClassName mediaWiki
265 * @singleton
266 */
267 return {
268 /* Public Members */
269
270 /**
271 * Dummy function which in debug mode can be replaced with a function that
272 * emulates console.log in console-less environments.
273 */
274 log: function () { },
275
276 // Make the Map constructor publicly available.
277 Map: Map,
278
279 // Make the Message constructor publicly available.
280 Message: Message,
281
282 /**
283 * List of configuration values
284 *
285 * Dummy placeholder. Initiated in startUp module as a new instance of mw.Map().
286 * If `$wgLegacyJavaScriptGlobals` is true, this Map will have its values
287 * in the global window object.
288 * @property
289 */
290 config: null,
291
292 /**
293 * Empty object that plugins can be installed in.
294 * @property
295 */
296 libs: {},
297
298 /* Extension points */
299
300 /**
301 * @property
302 */
303 legacy: {},
304
305 /**
306 * Localization system
307 * @property {mw.Map}
308 */
309 messages: new Map(),
310
311 /* Public Methods */
312
313 /**
314 * Gets a message object, similar to wfMessage().
315 *
316 * @param {string} key Key of message to get
317 * @param {Mixed...} parameters Parameters for the $N replacements in messages.
318 * @return {mw.Message}
319 */
320 message: function ( key ) {
321 // Variadic arguments
322 var parameters = slice.call( arguments, 1 );
323 return new Message( mw.messages, key, parameters );
324 },
325
326 /**
327 * Gets a message string, similar to wfMessage()
328 *
329 * @see mw.Message#toString
330 * @param {string} key Key of message to get
331 * @param {Mixed...} parameters Parameters for the $N replacements in messages.
332 * @return {string}
333 */
334 msg: function ( /* key, parameters... */ ) {
335 return mw.message.apply( mw.message, arguments ).toString();
336 },
337
338 /**
339 * Client-side module loader which integrates with the MediaWiki ResourceLoader
340 * @class mw.loader
341 * @singleton
342 */
343 loader: ( function () {
344
345 /* Private Members */
346
347 /**
348 * Mapping of registered modules
349 *
350 * The jquery module is pre-registered, because it must have already
351 * been provided for this object to have been built, and in debug mode
352 * jquery would have been provided through a unique loader request,
353 * making it impossible to hold back registration of jquery until after
354 * mediawiki.
355 *
356 * For exact details on support for script, style and messages, look at
357 * mw.loader.implement.
358 *
359 * Format:
360 * {
361 * 'moduleName': {
362 * 'version': ############## (unix timestamp),
363 * 'dependencies': ['required.foo', 'bar.also', ...], (or) function () {}
364 * 'group': 'somegroup', (or) null,
365 * 'source': 'local', 'someforeignwiki', (or) null
366 * 'state': 'registered', 'loading', 'loaded', 'ready', 'error' or 'missing'
367 * 'script': ...,
368 * 'style': ...,
369 * 'messages': { 'key': 'value' },
370 * }
371 * }
372 *
373 * @property
374 * @private
375 */
376 var registry = {},
377 //
378 // Mapping of sources, keyed by source-id, values are objects.
379 // Format:
380 // {
381 // 'sourceId': {
382 // 'loadScript': 'http://foo.bar/w/load.php'
383 // }
384 // }
385 //
386 sources = {},
387 // List of modules which will be loaded as when ready
388 batch = [],
389 // List of modules to be loaded
390 queue = [],
391 // List of callback functions waiting for modules to be ready to be called
392 jobs = [],
393 // Selector cache for the marker element. Use getMarker() to get/use the marker!
394 $marker = null,
395 // Buffer for addEmbeddedCSS.
396 cssBuffer = '';
397
398 /* Private methods */
399
400 function getMarker() {
401 // Cached ?
402 if ( $marker ) {
403 return $marker;
404 }
405
406 $marker = $( 'meta[name="ResourceLoaderDynamicStyles"]' );
407 if ( $marker.length ) {
408 return $marker;
409 }
410 mw.log( 'getMarker> No <meta name="ResourceLoaderDynamicStyles"> found, inserting dynamically.' );
411 $marker = $( '<meta>' ).attr( 'name', 'ResourceLoaderDynamicStyles' ).appendTo( 'head' );
412
413 return $marker;
414 }
415
416 /**
417 * Create a new style tag and add it to the DOM.
418 *
419 * @private
420 * @param {string} text CSS text
421 * @param {Mixed} [nextnode] An Element or jQuery object for an element where
422 * the style tag should be inserted before. Otherwise appended to the `<head>`.
423 * @return {HTMLElement} Node reference to the created `<style>` tag.
424 */
425 function addStyleTag( text, nextnode ) {
426 var s = document.createElement( 'style' );
427 // Insert into document before setting cssText (bug 33305)
428 if ( nextnode ) {
429 // Must be inserted with native insertBefore, not $.fn.before.
430 // When using jQuery to insert it, like $nextnode.before( s ),
431 // then IE6 will throw "Access is denied" when trying to append
432 // to .cssText later. Some kind of weird security measure.
433 // http://stackoverflow.com/q/12586482/319266
434 // Works: jsfiddle.net/zJzMy/1
435 // Fails: jsfiddle.net/uJTQz
436 // Works again: http://jsfiddle.net/Azr4w/ (diff: the next 3 lines)
437 if ( nextnode.jquery ) {
438 nextnode = nextnode.get( 0 );
439 }
440 nextnode.parentNode.insertBefore( s, nextnode );
441 } else {
442 document.getElementsByTagName( 'head' )[0].appendChild( s );
443 }
444 if ( s.styleSheet ) {
445 // IE
446 s.styleSheet.cssText = text;
447 } else {
448 // Other browsers.
449 // (Safari sometimes borks on non-string values,
450 // play safe by casting to a string, just in case.)
451 s.appendChild( document.createTextNode( String( text ) ) );
452 }
453 return s;
454 }
455
456 /**
457 * Checks whether it is safe to add this css to a stylesheet.
458 *
459 * @private
460 * @param {string} cssText
461 * @return {boolean} False if a new one must be created.
462 */
463 function canExpandStylesheetWith( cssText ) {
464 // Makes sure that cssText containing `@import`
465 // rules will end up in a new stylesheet (as those only work when
466 // placed at the start of a stylesheet; bug 35562).
467 return cssText.indexOf( '@import' ) === -1;
468 }
469
470 /**
471 * @param {string} [cssText=cssBuffer] If called without cssText,
472 * the internal buffer will be inserted instead.
473 */
474 function addEmbeddedCSS( cssText ) {
475 var $style, styleEl;
476
477 // Yield once before inserting the <style> tag. There are likely
478 // more calls coming up which we can combine this way.
479 // Appending a stylesheet and waiting for the browser to repaint
480 // is fairly expensive, this reduces it (bug 45810)
481 if ( cssText ) {
482 // Be careful not to extend the buffer with css that needs a new stylesheet
483 if ( !cssBuffer || canExpandStylesheetWith( cssText ) ) {
484 // Linebreak for somewhat distinguishable sections
485 // (the rl-cachekey comment separating each)
486 cssBuffer += '\n' + cssText;
487 // TODO: Use requestAnimationFrame in the future which will
488 // perform even better by not injecting styles while the browser
489 // is paiting.
490 setTimeout( addEmbeddedCSS );
491 return;
492 }
493
494 // This is a delayed call and we got a buffer still
495 } else if ( cssBuffer ) {
496 cssText = cssBuffer;
497 cssBuffer = '';
498 } else {
499 // This is a delayed call, but buffer is already cleared by
500 // another delayed call.
501 return;
502 }
503
504 // By default, always create a new <style>. Appending text
505 // to a <style> tag means the contents have to be re-parsed (bug 45810).
506 // Except, of course, in IE below 9, in there we default to
507 // re-using and appending to a <style> tag due to the
508 // IE stylesheet limit (bug 31676).
509 if ( 'documentMode' in document && document.documentMode <= 9 ) {
510
511 $style = getMarker().prev();
512 // Verify that the the element before Marker actually is a
513 // <style> tag and one that came from ResourceLoader
514 // (not some other style tag or even a `<meta>` or `<script>`).
515 if ( $style.data( 'ResourceLoaderDynamicStyleTag' ) === true ) {
516 // There's already a dynamic <style> tag present and
517 // canExpandStylesheetWith() gave a green light to append more to it.
518 styleEl = $style.get( 0 );
519 if ( styleEl.styleSheet ) {
520 try {
521 styleEl.styleSheet.cssText += cssText; // IE
522 } catch ( e ) {
523 log( 'addEmbeddedCSS fail\ne.message: ' + e.message, e );
524 }
525 } else {
526 styleEl.appendChild( document.createTextNode( String( cssText ) ) );
527 }
528 return;
529 }
530 }
531
532 $( addStyleTag( cssText, getMarker() ) ).data( 'ResourceLoaderDynamicStyleTag', true );
533 }
534
535 /**
536 * Generates an ISO8601 "basic" string from a UNIX timestamp
537 * @private
538 */
539 function formatVersionNumber( timestamp ) {
540 var d = new Date();
541 function pad( a, b, c ) {
542 return [a < 10 ? '0' + a : a, b < 10 ? '0' + b : b, c < 10 ? '0' + c : c].join( '' );
543 }
544 d.setTime( timestamp * 1000 );
545 return [
546 pad( d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate() ), 'T',
547 pad( d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds() ), 'Z'
548 ].join( '' );
549 }
550
551 /**
552 * Resolves dependencies and detects circular references.
553 *
554 * @private
555 * @param {string} module Name of the top-level module whose dependencies shall be
556 * resolved and sorted.
557 * @param {Array} resolved Returns a topological sort of the given module and its
558 * dependencies, such that later modules depend on earlier modules. The array
559 * contains the module names. If the array contains already some module names,
560 * this function appends its result to the pre-existing array.
561 * @param {Object} [unresolved] Hash used to track the current dependency
562 * chain; used to report loops in the dependency graph.
563 * @throws {Error} If any unregistered module or a dependency loop is encountered
564 */
565 function sortDependencies( module, resolved, unresolved ) {
566 var n, deps, len;
567
568 if ( registry[module] === undefined ) {
569 throw new Error( 'Unknown dependency: ' + module );
570 }
571 // Resolves dynamic loader function and replaces it with its own results
572 if ( $.isFunction( registry[module].dependencies ) ) {
573 registry[module].dependencies = registry[module].dependencies();
574 // Ensures the module's dependencies are always in an array
575 if ( typeof registry[module].dependencies !== 'object' ) {
576 registry[module].dependencies = [registry[module].dependencies];
577 }
578 }
579 if ( $.inArray( module, resolved ) !== -1 ) {
580 // Module already resolved; nothing to do.
581 return;
582 }
583 // unresolved is optional, supply it if not passed in
584 if ( !unresolved ) {
585 unresolved = {};
586 }
587 // Tracks down dependencies
588 deps = registry[module].dependencies;
589 len = deps.length;
590 for ( n = 0; n < len; n += 1 ) {
591 if ( $.inArray( deps[n], resolved ) === -1 ) {
592 if ( unresolved[deps[n]] ) {
593 throw new Error(
594 'Circular reference detected: ' + module +
595 ' -> ' + deps[n]
596 );
597 }
598
599 // Add to unresolved
600 unresolved[module] = true;
601 sortDependencies( deps[n], resolved, unresolved );
602 delete unresolved[module];
603 }
604 }
605 resolved[resolved.length] = module;
606 }
607
608 /**
609 * Gets a list of module names that a module depends on in their proper dependency
610 * order.
611 *
612 * @private
613 * @param {string} module Module name or array of string module names
614 * @return {Array} list of dependencies, including 'module'.
615 * @throws {Error} If circular reference is detected
616 */
617 function resolve( module ) {
618 var m, resolved;
619
620 // Allow calling with an array of module names
621 if ( $.isArray( module ) ) {
622 resolved = [];
623 for ( m = 0; m < module.length; m += 1 ) {
624 sortDependencies( module[m], resolved );
625 }
626 return resolved;
627 }
628
629 if ( typeof module === 'string' ) {
630 resolved = [];
631 sortDependencies( module, resolved );
632 return resolved;
633 }
634
635 throw new Error( 'Invalid module argument: ' + module );
636 }
637
638 /**
639 * Narrows a list of module names down to those matching a specific
640 * state (see comment on top of this scope for a list of valid states).
641 * One can also filter for 'unregistered', which will return the
642 * modules names that don't have a registry entry.
643 *
644 * @private
645 * @param {string|string[]} states Module states to filter by
646 * @param {Array} modules List of module names to filter (optional, by default the entire
647 * registry is used)
648 * @return {Array} List of filtered module names
649 */
650 function filter( states, modules ) {
651 var list, module, s, m;
652
653 // Allow states to be given as a string
654 if ( typeof states === 'string' ) {
655 states = [states];
656 }
657 // If called without a list of modules, build and use a list of all modules
658 list = [];
659 if ( modules === undefined ) {
660 modules = [];
661 for ( module in registry ) {
662 modules[modules.length] = module;
663 }
664 }
665 // Build a list of modules which are in one of the specified states
666 for ( s = 0; s < states.length; s += 1 ) {
667 for ( m = 0; m < modules.length; m += 1 ) {
668 if ( registry[modules[m]] === undefined ) {
669 // Module does not exist
670 if ( states[s] === 'unregistered' ) {
671 // OK, undefined
672 list[list.length] = modules[m];
673 }
674 } else {
675 // Module exists, check state
676 if ( registry[modules[m]].state === states[s] ) {
677 // OK, correct state
678 list[list.length] = modules[m];
679 }
680 }
681 }
682 }
683 return list;
684 }
685
686 /**
687 * Determine whether all dependencies are in state 'ready', which means we may
688 * execute the module or job now.
689 *
690 * @private
691 * @param {Array} dependencies Dependencies (module names) to be checked.
692 * @return {boolean} True if all dependencies are in state 'ready', false otherwise
693 */
694 function allReady( dependencies ) {
695 return filter( 'ready', dependencies ).length === dependencies.length;
696 }
697
698 /**
699 * Log a message to window.console, if possible. Useful to force logging of some
700 * errors that are otherwise hard to detect (I.e., this logs also in production mode).
701 * Gets console references in each invocation, so that delayed debugging tools work
702 * fine. No need for optimization here, which would only result in losing logs.
703 *
704 * @private
705 * @param {string} msg text for the log entry.
706 * @param {Error} [e]
707 */
708 function log( msg, e ) {
709 var console = window.console;
710 if ( console && console.log ) {
711 console.log( msg );
712 // If we have an exception object, log it through .error() to trigger
713 // proper stacktraces in browsers that support it. There are no (known)
714 // browsers that don't support .error(), that do support .log() and
715 // have useful exception handling through .log().
716 if ( e && console.error ) {
717 console.error( e );
718 }
719 }
720 }
721
722 /**
723 * A module has entered state 'ready', 'error', or 'missing'. Automatically update pending jobs
724 * and modules that depend upon this module. if the given module failed, propagate the 'error'
725 * state up the dependency tree; otherwise, execute all jobs/modules that now have all their
726 * dependencies satisfied. On jobs depending on a failed module, run the error callback, if any.
727 *
728 * @private
729 * @param {string} module Name of module that entered one of the states 'ready', 'error', or 'missing'.
730 */
731 function handlePending( module ) {
732 var j, job, hasErrors, m, stateChange;
733
734 // Modules.
735 if ( $.inArray( registry[module].state, ['error', 'missing'] ) !== -1 ) {
736 // If the current module failed, mark all dependent modules also as failed.
737 // Iterate until steady-state to propagate the error state upwards in the
738 // dependency tree.
739 do {
740 stateChange = false;
741 for ( m in registry ) {
742 if ( $.inArray( registry[m].state, ['error', 'missing'] ) === -1 ) {
743 if ( filter( ['error', 'missing'], registry[m].dependencies ).length > 0 ) {
744 registry[m].state = 'error';
745 stateChange = true;
746 }
747 }
748 }
749 } while ( stateChange );
750 }
751
752 // Execute all jobs whose dependencies are either all satisfied or contain at least one failed module.
753 for ( j = 0; j < jobs.length; j += 1 ) {
754 hasErrors = filter( ['error', 'missing'], jobs[j].dependencies ).length > 0;
755 if ( hasErrors || allReady( jobs[j].dependencies ) ) {
756 // All dependencies satisfied, or some have errors
757 job = jobs[j];
758 jobs.splice( j, 1 );
759 j -= 1;
760 try {
761 if ( hasErrors ) {
762 throw new Error( 'Module ' + module + ' failed.');
763 } else {
764 if ( $.isFunction( job.ready ) ) {
765 job.ready();
766 }
767 }
768 } catch ( e ) {
769 if ( $.isFunction( job.error ) ) {
770 try {
771 job.error( e, [module] );
772 } catch ( ex ) {
773 // A user-defined operation raised an exception. Swallow to protect
774 // our state machine!
775 log( 'Exception thrown by job.error()', ex );
776 }
777 }
778 }
779 }
780 }
781
782 if ( registry[module].state === 'ready' ) {
783 // The current module became 'ready'. Recursively execute all dependent modules that are loaded
784 // and now have all dependencies satisfied.
785 for ( m in registry ) {
786 if ( registry[m].state === 'loaded' && allReady( registry[m].dependencies ) ) {
787 execute( m );
788 }
789 }
790 }
791 }
792
793 /**
794 * Adds a script tag to the DOM, either using document.write or low-level DOM manipulation,
795 * depending on whether document-ready has occurred yet and whether we are in async mode.
796 *
797 * @private
798 * @param {string} src URL to script, will be used as the src attribute in the script tag
799 * @param {Function} [callback] Callback which will be run when the script is done
800 */
801 function addScript( src, callback, async ) {
802 /*jshint evil:true */
803 var script, head,
804 done = false;
805
806 // Using isReady directly instead of storing it locally from
807 // a $.fn.ready callback (bug 31895).
808 if ( $.isReady || async ) {
809 // Can't use jQuery.getScript because that only uses <script> for cross-domain,
810 // it uses XHR and eval for same-domain scripts, which we don't want because it
811 // messes up line numbers.
812 // The below is based on jQuery ([jquery@1.8.2]/src/ajax/script.js)
813
814 // IE-safe way of getting the <head>. document.head isn't supported
815 // in old IE, and doesn't work when in the <head>.
816 head = document.getElementsByTagName( 'head' )[0] || document.body;
817
818 script = document.createElement( 'script' );
819 script.async = true;
820 script.src = src;
821 if ( $.isFunction( callback ) ) {
822 script.onload = script.onreadystatechange = function () {
823 if (
824 !done
825 && (
826 !script.readyState
827 || /loaded|complete/.test( script.readyState )
828 )
829 ) {
830 done = true;
831
832 // Handle memory leak in IE
833 script.onload = script.onreadystatechange = null;
834
835 // Remove the script
836 if ( script.parentNode ) {
837 script.parentNode.removeChild( script );
838 }
839
840 // Dereference the script
841 script = undefined;
842
843 callback();
844 }
845 };
846 }
847
848 if ( window.opera ) {
849 // Appending to the <head> blocks rendering completely in Opera,
850 // so append to the <body> after document ready. This means the
851 // scripts only start loading after the document has been rendered,
852 // but so be it. Opera users don't deserve faster web pages if their
853 // browser makes it impossible.
854 $( function () {
855 document.body.appendChild( script );
856 } );
857 } else {
858 head.appendChild( script );
859 }
860 } else {
861 document.write( mw.html.element( 'script', { 'src': src }, '' ) );
862 if ( $.isFunction( callback ) ) {
863 // Document.write is synchronous, so this is called when it's done
864 // FIXME: that's a lie. doc.write isn't actually synchronous
865 callback();
866 }
867 }
868 }
869
870 /**
871 * Executes a loaded module, making it ready to use
872 *
873 * @private
874 * @param {string} module Module name to execute
875 */
876 function execute( module ) {
877 var key, value, media, i, urls, script, markModuleReady, nestedAddScript;
878
879 if ( registry[module] === undefined ) {
880 throw new Error( 'Module has not been registered yet: ' + module );
881 } else if ( registry[module].state === 'registered' ) {
882 throw new Error( 'Module has not been requested from the server yet: ' + module );
883 } else if ( registry[module].state === 'loading' ) {
884 throw new Error( 'Module has not completed loading yet: ' + module );
885 } else if ( registry[module].state === 'ready' ) {
886 throw new Error( 'Module has already been loaded: ' + module );
887 }
888
889 /**
890 * Define loop-function here for efficiency
891 * and to avoid re-using badly scoped variables.
892 * @ignore
893 */
894 function addLink( media, url ) {
895 var el = document.createElement( 'link' );
896 getMarker().before( el ); // IE: Insert in dom before setting href
897 el.rel = 'stylesheet';
898 if ( media && media !== 'all' ) {
899 el.media = media;
900 }
901 el.href = url;
902 }
903
904 // Process styles (see also mw.loader.implement)
905 // * back-compat: { <media>: css }
906 // * back-compat: { <media>: [url, ..] }
907 // * { "css": [css, ..] }
908 // * { "url": { <media>: [url, ..] } }
909 if ( $.isPlainObject( registry[module].style ) ) {
910 for ( key in registry[module].style ) {
911 value = registry[module].style[key];
912 media = undefined;
913
914 if ( key !== 'url' && key !== 'css' ) {
915 // Backwards compatibility, key is a media-type
916 if ( typeof value === 'string' ) {
917 // back-compat: { <media>: css }
918 // Ignore 'media' because it isn't supported (nor was it used).
919 // Strings are pre-wrapped in "@media". The media-type was just ""
920 // (because it had to be set to something).
921 // This is one of the reasons why this format is no longer used.
922 addEmbeddedCSS( value );
923 } else {
924 // back-compat: { <media>: [url, ..] }
925 media = key;
926 key = 'bc-url';
927 }
928 }
929
930 // Array of css strings in key 'css',
931 // or back-compat array of urls from media-type
932 if ( $.isArray( value ) ) {
933 for ( i = 0; i < value.length; i += 1 ) {
934 if ( key === 'bc-url' ) {
935 // back-compat: { <media>: [url, ..] }
936 addLink( media, value[i] );
937 } else if ( key === 'css' ) {
938 // { "css": [css, ..] }
939 addEmbeddedCSS( value[i] );
940 }
941 }
942 // Not an array, but a regular object
943 // Array of urls inside media-type key
944 } else if ( typeof value === 'object' ) {
945 // { "url": { <media>: [url, ..] } }
946 for ( media in value ) {
947 urls = value[media];
948 for ( i = 0; i < urls.length; i += 1 ) {
949 addLink( media, urls[i] );
950 }
951 }
952 }
953 }
954 }
955
956 // Add localizations to message system
957 if ( $.isPlainObject( registry[module].messages ) ) {
958 mw.messages.set( registry[module].messages );
959 }
960
961 // Execute script
962 try {
963 script = registry[module].script;
964 markModuleReady = function () {
965 registry[module].state = 'ready';
966 handlePending( module );
967 };
968 nestedAddScript = function ( arr, callback, async, i ) {
969 // Recursively call addScript() in its own callback
970 // for each element of arr.
971 if ( i >= arr.length ) {
972 // We're at the end of the array
973 callback();
974 return;
975 }
976
977 addScript( arr[i], function () {
978 nestedAddScript( arr, callback, async, i + 1 );
979 }, async );
980 };
981
982 if ( $.isArray( script ) ) {
983 registry[module].state = 'loading';
984 nestedAddScript( script, markModuleReady, registry[module].async, 0 );
985 } else if ( $.isFunction( script ) ) {
986 registry[module].state = 'ready';
987 script( $ );
988 handlePending( module );
989 }
990 } catch ( e ) {
991 // This needs to NOT use mw.log because these errors are common in production mode
992 // and not in debug mode, such as when a symbol that should be global isn't exported
993 log( 'Exception thrown by ' + module + ': ' + e.message, e );
994 registry[module].state = 'error';
995 handlePending( module );
996 }
997 }
998
999 /**
1000 * Adds a dependencies to the queue with optional callbacks to be run
1001 * when the dependencies are ready or fail
1002 *
1003 * @private
1004 * @param {string|string[]} dependencies Module name or array of string module names
1005 * @param {Function} [ready] Callback to execute when all dependencies are ready
1006 * @param {Function} [error] Callback to execute when any dependency fails
1007 * @param {boolean} [async] If true, load modules asynchronously even if
1008 * document ready has not yet occurred.
1009 */
1010 function request( dependencies, ready, error, async ) {
1011 var n;
1012
1013 // Allow calling by single module name
1014 if ( typeof dependencies === 'string' ) {
1015 dependencies = [dependencies];
1016 }
1017
1018 // Add ready and error callbacks if they were given
1019 if ( ready !== undefined || error !== undefined ) {
1020 jobs[jobs.length] = {
1021 'dependencies': filter(
1022 ['registered', 'loading', 'loaded'],
1023 dependencies
1024 ),
1025 'ready': ready,
1026 'error': error
1027 };
1028 }
1029
1030 // Queue up any dependencies that are registered
1031 dependencies = filter( ['registered'], dependencies );
1032 for ( n = 0; n < dependencies.length; n += 1 ) {
1033 if ( $.inArray( dependencies[n], queue ) === -1 ) {
1034 queue[queue.length] = dependencies[n];
1035 if ( async ) {
1036 // Mark this module as async in the registry
1037 registry[dependencies[n]].async = true;
1038 }
1039 }
1040 }
1041
1042 // Work the queue
1043 mw.loader.work();
1044 }
1045
1046 function sortQuery(o) {
1047 var sorted = {}, key, a = [];
1048 for ( key in o ) {
1049 if ( hasOwn.call( o, key ) ) {
1050 a.push( key );
1051 }
1052 }
1053 a.sort();
1054 for ( key = 0; key < a.length; key += 1 ) {
1055 sorted[a[key]] = o[a[key]];
1056 }
1057 return sorted;
1058 }
1059
1060 /**
1061 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
1062 * to a query string of the form foo.bar,baz|bar.baz,quux
1063 * @private
1064 */
1065 function buildModulesString( moduleMap ) {
1066 var arr = [], p, prefix;
1067 for ( prefix in moduleMap ) {
1068 p = prefix === '' ? '' : prefix + '.';
1069 arr.push( p + moduleMap[prefix].join( ',' ) );
1070 }
1071 return arr.join( '|' );
1072 }
1073
1074 /**
1075 * Asynchronously append a script tag to the end of the body
1076 * that invokes load.php
1077 * @private
1078 * @param {Object} moduleMap Module map, see #buildModulesString
1079 * @param {Object} currReqBase Object with other parameters (other than 'modules') to use in the request
1080 * @param {string} sourceLoadScript URL of load.php
1081 * @param {boolean} async If true, use an asynchrounous request even if document ready has not yet occurred
1082 */
1083 function doRequest( moduleMap, currReqBase, sourceLoadScript, async ) {
1084 var request = $.extend(
1085 { modules: buildModulesString( moduleMap ) },
1086 currReqBase
1087 );
1088 request = sortQuery( request );
1089 // Asynchronously append a script tag to the end of the body
1090 // Append &* to avoid triggering the IE6 extension check
1091 addScript( sourceLoadScript + '?' + $.param( request ) + '&*', null, async );
1092 }
1093
1094 /* Public Methods */
1095 return {
1096 addStyleTag: addStyleTag,
1097
1098 /**
1099 * Requests dependencies from server, loading and executing when things when ready.
1100 */
1101 work: function () {
1102 var reqBase, splits, maxQueryLength, q, b, bSource, bGroup, bSourceGroup,
1103 source, group, g, i, modules, maxVersion, sourceLoadScript,
1104 currReqBase, currReqBaseLength, moduleMap, l,
1105 lastDotIndex, prefix, suffix, bytesAdded, async;
1106
1107 // Build a list of request parameters common to all requests.
1108 reqBase = {
1109 skin: mw.config.get( 'skin' ),
1110 lang: mw.config.get( 'wgUserLanguage' ),
1111 debug: mw.config.get( 'debug' )
1112 };
1113 // Split module batch by source and by group.
1114 splits = {};
1115 maxQueryLength = mw.config.get( 'wgResourceLoaderMaxQueryLength', -1 );
1116
1117 // Appends a list of modules from the queue to the batch
1118 for ( q = 0; q < queue.length; q += 1 ) {
1119 // Only request modules which are registered
1120 if ( registry[queue[q]] !== undefined && registry[queue[q]].state === 'registered' ) {
1121 // Prevent duplicate entries
1122 if ( $.inArray( queue[q], batch ) === -1 ) {
1123 batch[batch.length] = queue[q];
1124 // Mark registered modules as loading
1125 registry[queue[q]].state = 'loading';
1126 }
1127 }
1128 }
1129 // Early exit if there's nothing to load...
1130 if ( !batch.length ) {
1131 return;
1132 }
1133
1134 // The queue has been processed into the batch, clear up the queue.
1135 queue = [];
1136
1137 // Always order modules alphabetically to help reduce cache
1138 // misses for otherwise identical content.
1139 batch.sort();
1140
1141 // Split batch by source and by group.
1142 for ( b = 0; b < batch.length; b += 1 ) {
1143 bSource = registry[batch[b]].source;
1144 bGroup = registry[batch[b]].group;
1145 if ( splits[bSource] === undefined ) {
1146 splits[bSource] = {};
1147 }
1148 if ( splits[bSource][bGroup] === undefined ) {
1149 splits[bSource][bGroup] = [];
1150 }
1151 bSourceGroup = splits[bSource][bGroup];
1152 bSourceGroup[bSourceGroup.length] = batch[b];
1153 }
1154
1155 // Clear the batch - this MUST happen before we append any
1156 // script elements to the body or it's possible that a script
1157 // will be locally cached, instantly load, and work the batch
1158 // again, all before we've cleared it causing each request to
1159 // include modules which are already loaded.
1160 batch = [];
1161
1162 for ( source in splits ) {
1163
1164 sourceLoadScript = sources[source].loadScript;
1165
1166 for ( group in splits[source] ) {
1167
1168 // Cache access to currently selected list of
1169 // modules for this group from this source.
1170 modules = splits[source][group];
1171
1172 // Calculate the highest timestamp
1173 maxVersion = 0;
1174 for ( g = 0; g < modules.length; g += 1 ) {
1175 if ( registry[modules[g]].version > maxVersion ) {
1176 maxVersion = registry[modules[g]].version;
1177 }
1178 }
1179
1180 currReqBase = $.extend( { version: formatVersionNumber( maxVersion ) }, reqBase );
1181 // For user modules append a user name to the request.
1182 if ( group === 'user' && mw.config.get( 'wgUserName' ) !== null ) {
1183 currReqBase.user = mw.config.get( 'wgUserName' );
1184 }
1185 currReqBaseLength = $.param( currReqBase ).length;
1186 async = true;
1187 // We may need to split up the request to honor the query string length limit,
1188 // so build it piece by piece.
1189 l = currReqBaseLength + 9; // '&modules='.length == 9
1190
1191 moduleMap = {}; // { prefix: [ suffixes ] }
1192
1193 for ( i = 0; i < modules.length; i += 1 ) {
1194 // Determine how many bytes this module would add to the query string
1195 lastDotIndex = modules[i].lastIndexOf( '.' );
1196 // Note that these substr() calls work even if lastDotIndex == -1
1197 prefix = modules[i].substr( 0, lastDotIndex );
1198 suffix = modules[i].substr( lastDotIndex + 1 );
1199 bytesAdded = moduleMap[prefix] !== undefined
1200 ? suffix.length + 3 // '%2C'.length == 3
1201 : modules[i].length + 3; // '%7C'.length == 3
1202
1203 // If the request would become too long, create a new one,
1204 // but don't create empty requests
1205 if ( maxQueryLength > 0 && !$.isEmptyObject( moduleMap ) && l + bytesAdded > maxQueryLength ) {
1206 // This request would become too long, create a new one
1207 // and fire off the old one
1208 doRequest( moduleMap, currReqBase, sourceLoadScript, async );
1209 moduleMap = {};
1210 async = true;
1211 l = currReqBaseLength + 9;
1212 }
1213 if ( moduleMap[prefix] === undefined ) {
1214 moduleMap[prefix] = [];
1215 }
1216 moduleMap[prefix].push( suffix );
1217 if ( !registry[modules[i]].async ) {
1218 // If this module is blocking, make the entire request blocking
1219 // This is slightly suboptimal, but in practice mixing of blocking
1220 // and async modules will only occur in debug mode.
1221 async = false;
1222 }
1223 l += bytesAdded;
1224 }
1225 // If there's anything left in moduleMap, request that too
1226 if ( !$.isEmptyObject( moduleMap ) ) {
1227 doRequest( moduleMap, currReqBase, sourceLoadScript, async );
1228 }
1229 }
1230 }
1231 },
1232
1233 /**
1234 * Register a source.
1235 *
1236 * @param {string} id Short lowercase a-Z string representing a source, only used internally.
1237 * @param {Object} props Object containing only the loadScript property which is a url to
1238 * the load.php location of the source.
1239 * @return {boolean}
1240 */
1241 addSource: function ( id, props ) {
1242 var source;
1243 // Allow multiple additions
1244 if ( typeof id === 'object' ) {
1245 for ( source in id ) {
1246 mw.loader.addSource( source, id[source] );
1247 }
1248 return true;
1249 }
1250
1251 if ( sources[id] !== undefined ) {
1252 throw new Error( 'source already registered: ' + id );
1253 }
1254
1255 sources[id] = props;
1256
1257 return true;
1258 },
1259
1260 /**
1261 * Registers a module, letting the system know about it and its
1262 * properties. Startup modules contain calls to this function.
1263 *
1264 * @param module {String}: Module name
1265 * @param version {Number}: Module version number as a timestamp (falls backs to 0)
1266 * @param dependencies {String|Array|Function}: One string or array of strings of module
1267 * names on which this module depends, or a function that returns that array.
1268 * @param group {String}: Group which the module is in (optional, defaults to null)
1269 * @param source {String}: Name of the source. Defaults to local.
1270 */
1271 register: function ( module, version, dependencies, group, source ) {
1272 var m;
1273 // Allow multiple registration
1274 if ( typeof module === 'object' ) {
1275 for ( m = 0; m < module.length; m += 1 ) {
1276 // module is an array of module names
1277 if ( typeof module[m] === 'string' ) {
1278 mw.loader.register( module[m] );
1279 // module is an array of arrays
1280 } else if ( typeof module[m] === 'object' ) {
1281 mw.loader.register.apply( mw.loader, module[m] );
1282 }
1283 }
1284 return;
1285 }
1286 // Validate input
1287 if ( typeof module !== 'string' ) {
1288 throw new Error( 'module must be a string, not a ' + typeof module );
1289 }
1290 if ( registry[module] !== undefined ) {
1291 throw new Error( 'module already registered: ' + module );
1292 }
1293 // List the module as registered
1294 registry[module] = {
1295 version: version !== undefined ? parseInt( version, 10 ) : 0,
1296 dependencies: [],
1297 group: typeof group === 'string' ? group : null,
1298 source: typeof source === 'string' ? source: 'local',
1299 state: 'registered'
1300 };
1301 if ( typeof dependencies === 'string' ) {
1302 // Allow dependencies to be given as a single module name
1303 registry[module].dependencies = [ dependencies ];
1304 } else if ( typeof dependencies === 'object' || $.isFunction( dependencies ) ) {
1305 // Allow dependencies to be given as an array of module names
1306 // or a function which returns an array
1307 registry[module].dependencies = dependencies;
1308 }
1309 },
1310
1311 /**
1312 * Implements a module, giving the system a course of action to take
1313 * upon loading. Results of a request for one or more modules contain
1314 * calls to this function.
1315 *
1316 * All arguments are required.
1317 *
1318 * @param {string} module Name of module
1319 * @param {Function|Array} script Function with module code or Array of URLs to
1320 * be used as the src attribute of a new `<script>` tag.
1321 * @param {Object} style Should follow one of the following patterns:
1322 * { "css": [css, ..] }
1323 * { "url": { <media>: [url, ..] } }
1324 * And for backwards compatibility (needs to be supported forever due to caching):
1325 * { <media>: css }
1326 * { <media>: [url, ..] }
1327 *
1328 * The reason css strings are not concatenated anymore is bug 31676. We now check
1329 * whether it's safe to extend the stylesheet (see #canExpandStylesheetWith).
1330 *
1331 * @param {Object} msgs List of key/value pairs to be added to {@link mw#messages}.
1332 */
1333 implement: function ( module, script, style, msgs ) {
1334 // Validate input
1335 if ( typeof module !== 'string' ) {
1336 throw new Error( 'module must be a string, not a ' + typeof module );
1337 }
1338 if ( !$.isFunction( script ) && !$.isArray( script ) ) {
1339 throw new Error( 'script must be a function or an array, not a ' + typeof script );
1340 }
1341 if ( !$.isPlainObject( style ) ) {
1342 throw new Error( 'style must be an object, not a ' + typeof style );
1343 }
1344 if ( !$.isPlainObject( msgs ) ) {
1345 throw new Error( 'msgs must be an object, not a ' + typeof msgs );
1346 }
1347 // Automatically register module
1348 if ( registry[module] === undefined ) {
1349 mw.loader.register( module );
1350 }
1351 // Check for duplicate implementation
1352 if ( registry[module] !== undefined && registry[module].script !== undefined ) {
1353 throw new Error( 'module already implemented: ' + module );
1354 }
1355 // Attach components
1356 registry[module].script = script;
1357 registry[module].style = style;
1358 registry[module].messages = msgs;
1359 // The module may already have been marked as erroneous
1360 if ( $.inArray( registry[module].state, ['error', 'missing'] ) === -1 ) {
1361 registry[module].state = 'loaded';
1362 if ( allReady( registry[module].dependencies ) ) {
1363 execute( module );
1364 }
1365 }
1366 },
1367
1368 /**
1369 * Executes a function as soon as one or more required modules are ready
1370 *
1371 * @param dependencies {String|Array} Module name or array of modules names the callback
1372 * dependends on to be ready before executing
1373 * @param ready {Function} callback to execute when all dependencies are ready (optional)
1374 * @param error {Function} callback to execute when if dependencies have a errors (optional)
1375 */
1376 using: function ( dependencies, ready, error ) {
1377 var tod = typeof dependencies;
1378 // Validate input
1379 if ( tod !== 'object' && tod !== 'string' ) {
1380 throw new Error( 'dependencies must be a string or an array, not a ' + tod );
1381 }
1382 // Allow calling with a single dependency as a string
1383 if ( tod === 'string' ) {
1384 dependencies = [ dependencies ];
1385 }
1386 // Resolve entire dependency map
1387 dependencies = resolve( dependencies );
1388 if ( allReady( dependencies ) ) {
1389 // Run ready immediately
1390 if ( $.isFunction( ready ) ) {
1391 ready();
1392 }
1393 } else if ( filter( ['error', 'missing'], dependencies ).length ) {
1394 // Execute error immediately if any dependencies have errors
1395 if ( $.isFunction( error ) ) {
1396 error( new Error( 'one or more dependencies have state "error" or "missing"' ),
1397 dependencies );
1398 }
1399 } else {
1400 // Not all dependencies are ready: queue up a request
1401 request( dependencies, ready, error );
1402 }
1403 },
1404
1405 /**
1406 * Loads an external script or one or more modules for future use
1407 *
1408 * @param modules {mixed} Either the name of a module, array of modules,
1409 * or a URL of an external script or style
1410 * @param type {String} mime-type to use if calling with a URL of an
1411 * external script or style; acceptable values are "text/css" and
1412 * "text/javascript"; if no type is provided, text/javascript is assumed.
1413 * @param async {Boolean} (optional) If true, load modules asynchronously
1414 * even if document ready has not yet occurred. If false (default),
1415 * block before document ready and load async after. If not set, true will
1416 * be assumed if loading a URL, and false will be assumed otherwise.
1417 */
1418 load: function ( modules, type, async ) {
1419 var filtered, m, module, l;
1420
1421 // Validate input
1422 if ( typeof modules !== 'object' && typeof modules !== 'string' ) {
1423 throw new Error( 'modules must be a string or an array, not a ' + typeof modules );
1424 }
1425 // Allow calling with an external url or single dependency as a string
1426 if ( typeof modules === 'string' ) {
1427 // Support adding arbitrary external scripts
1428 if ( /^(https?:)?\/\//.test( modules ) ) {
1429 if ( async === undefined ) {
1430 // Assume async for bug 34542
1431 async = true;
1432 }
1433 if ( type === 'text/css' ) {
1434 // IE7-8 throws security warnings when inserting a <link> tag
1435 // with a protocol-relative URL set though attributes (instead of
1436 // properties) - when on HTTPS. See also bug #.
1437 l = document.createElement( 'link' );
1438 l.rel = 'stylesheet';
1439 l.href = modules;
1440 $( 'head' ).append( l );
1441 return;
1442 }
1443 if ( type === 'text/javascript' || type === undefined ) {
1444 addScript( modules, null, async );
1445 return;
1446 }
1447 // Unknown type
1448 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type );
1449 }
1450 // Called with single module
1451 modules = [ modules ];
1452 }
1453
1454 // Filter out undefined modules, otherwise resolve() will throw
1455 // an exception for trying to load an undefined module.
1456 // Undefined modules are acceptable here in load(), because load() takes
1457 // an array of unrelated modules, whereas the modules passed to
1458 // using() are related and must all be loaded.
1459 for ( filtered = [], m = 0; m < modules.length; m += 1 ) {
1460 module = registry[modules[m]];
1461 if ( module !== undefined ) {
1462 if ( $.inArray( module.state, ['error', 'missing'] ) === -1 ) {
1463 filtered[filtered.length] = modules[m];
1464 }
1465 }
1466 }
1467
1468 if ( filtered.length === 0 ) {
1469 return;
1470 }
1471 // Resolve entire dependency map
1472 filtered = resolve( filtered );
1473 // If all modules are ready, nothing to be done
1474 if ( allReady( filtered ) ) {
1475 return;
1476 }
1477 // If any modules have errors: also quit.
1478 if ( filter( ['error', 'missing'], filtered ).length ) {
1479 return;
1480 }
1481 // Since some modules are not yet ready, queue up a request.
1482 request( filtered, undefined, undefined, async );
1483 },
1484
1485 /**
1486 * Changes the state of a module
1487 *
1488 * @param module {String|Object} module name or object of module name/state pairs
1489 * @param state {String} state name
1490 */
1491 state: function ( module, state ) {
1492 var m;
1493
1494 if ( typeof module === 'object' ) {
1495 for ( m in module ) {
1496 mw.loader.state( m, module[m] );
1497 }
1498 return;
1499 }
1500 if ( registry[module] === undefined ) {
1501 mw.loader.register( module );
1502 }
1503 if ( $.inArray( state, ['ready', 'error', 'missing'] ) !== -1
1504 && registry[module].state !== state ) {
1505 // Make sure pending modules depending on this one get executed if their
1506 // dependencies are now fulfilled!
1507 registry[module].state = state;
1508 handlePending( module );
1509 } else {
1510 registry[module].state = state;
1511 }
1512 },
1513
1514 /**
1515 * Gets the version of a module
1516 *
1517 * @param module string name of module to get version for
1518 */
1519 getVersion: function ( module ) {
1520 if ( registry[module] !== undefined && registry[module].version !== undefined ) {
1521 return formatVersionNumber( registry[module].version );
1522 }
1523 return null;
1524 },
1525
1526 /**
1527 * @deprecated since 1.18 use mw.loader.getVersion() instead
1528 */
1529 version: function () {
1530 return mw.loader.getVersion.apply( mw.loader, arguments );
1531 },
1532
1533 /**
1534 * Gets the state of a module
1535 *
1536 * @param module string name of module to get state for
1537 */
1538 getState: function ( module ) {
1539 if ( registry[module] !== undefined && registry[module].state !== undefined ) {
1540 return registry[module].state;
1541 }
1542 return null;
1543 },
1544
1545 /**
1546 * Get names of all registered modules.
1547 *
1548 * @return {Array}
1549 */
1550 getModuleNames: function () {
1551 return $.map( registry, function ( i, key ) {
1552 return key;
1553 } );
1554 },
1555
1556 /**
1557 * For backwards-compatibility with Squid-cached pages. Loads mw.user
1558 */
1559 go: function () {
1560 mw.loader.load( 'mediawiki.user' );
1561 }
1562 };
1563 }() ),
1564
1565 /**
1566 * HTML construction helper functions
1567 * @class mw.html
1568 * @singleton
1569 */
1570 html: ( function () {
1571 function escapeCallback( s ) {
1572 switch ( s ) {
1573 case '\'':
1574 return '&#039;';
1575 case '"':
1576 return '&quot;';
1577 case '<':
1578 return '&lt;';
1579 case '>':
1580 return '&gt;';
1581 case '&':
1582 return '&amp;';
1583 }
1584 }
1585
1586 return {
1587 /**
1588 * Escape a string for HTML. Converts special characters to HTML entities.
1589 * @param {string} s The string to escape
1590 */
1591 escape: function ( s ) {
1592 return s.replace( /['"<>&]/g, escapeCallback );
1593 },
1594
1595 /**
1596 * Wrapper object for raw HTML passed to mw.html.element().
1597 * @class mw.html.Raw
1598 */
1599 Raw: function ( value ) {
1600 this.value = value;
1601 },
1602
1603 /**
1604 * Wrapper object for CDATA element contents passed to mw.html.element()
1605 * @class mw.html.Cdata
1606 */
1607 Cdata: function ( value ) {
1608 this.value = value;
1609 },
1610
1611 /**
1612 * Create an HTML element string, with safe escaping.
1613 *
1614 * @param name The tag name.
1615 * @param attrs An object with members mapping element names to values
1616 * @param contents The contents of the element. May be either:
1617 * - string: The string is escaped.
1618 * - null or undefined: The short closing form is used, e.g. <br/>.
1619 * - this.Raw: The value attribute is included without escaping.
1620 * - this.Cdata: The value attribute is included, and an exception is
1621 * thrown if it contains an illegal ETAGO delimiter.
1622 * See http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.3.2
1623 *
1624 * Example:
1625 * var h = mw.html;
1626 * return h.element( 'div', {},
1627 * new h.Raw( h.element( 'img', {src: '<'} ) ) );
1628 * Returns <div><img src="&lt;"/></div>
1629 */
1630 element: function ( name, attrs, contents ) {
1631 var v, attrName, s = '<' + name;
1632
1633 for ( attrName in attrs ) {
1634 v = attrs[attrName];
1635 // Convert name=true, to name=name
1636 if ( v === true ) {
1637 v = attrName;
1638 // Skip name=false
1639 } else if ( v === false ) {
1640 continue;
1641 }
1642 s += ' ' + attrName + '="' + this.escape( String( v ) ) + '"';
1643 }
1644 if ( contents === undefined || contents === null ) {
1645 // Self close tag
1646 s += '/>';
1647 return s;
1648 }
1649 // Regular open tag
1650 s += '>';
1651 switch ( typeof contents ) {
1652 case 'string':
1653 // Escaped
1654 s += this.escape( contents );
1655 break;
1656 case 'number':
1657 case 'boolean':
1658 // Convert to string
1659 s += String( contents );
1660 break;
1661 default:
1662 if ( contents instanceof this.Raw ) {
1663 // Raw HTML inclusion
1664 s += contents.value;
1665 } else if ( contents instanceof this.Cdata ) {
1666 // CDATA
1667 if ( /<\/[a-zA-z]/.test( contents.value ) ) {
1668 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
1669 }
1670 s += contents.value;
1671 } else {
1672 throw new Error( 'mw.html.element: Invalid type of contents' );
1673 }
1674 }
1675 s += '</' + name + '>';
1676 return s;
1677 }
1678 };
1679 }() ),
1680
1681 // Skeleton user object. mediawiki.user.js extends this
1682 user: {
1683 options: new Map(),
1684 tokens: new Map()
1685 }
1686 };
1687
1688 }( jQuery ) );
1689
1690 // Alias $j to jQuery for backwards compatibility
1691 window.$j = jQuery;
1692
1693 // Attach to window and globally alias
1694 window.mw = window.mediaWiki = mw;
1695
1696 // Auto-register from pre-loaded startup scripts
1697 if ( jQuery.isFunction( window.startUp ) ) {
1698 window.startUp();
1699 window.startUp = undefined;
1700 }