[mediawiki.loader] fix numerous bugs and edge cases discovered with Roan on Etherpad...
[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
12 /* Object constructors */
13
14 /**
15 * Map
16 *
17 * Creates an object that can be read from or written to from prototype functions
18 * that allow both single and multiple variables at once.
19 *
20 * @param global boolean Whether to store the values in the global window
21 * object or a exclusively in the object property 'values'.
22 * @return Map
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 Values as a string or object, null if invalid/inexistant.
42 */
43 get: function ( selection, fallback ) {
44 var results, i;
45
46 if ( $.isArray( selection ) ) {
47 selection = $.makeArray( selection );
48 results = {};
49 for ( i = 0; i < selection.length; i += 1 ) {
50 results[selection[i]] = this.get( selection[i], fallback );
51 }
52 return results;
53 } else if ( typeof selection === 'string' ) {
54 if ( this.values[selection] === undefined ) {
55 if ( fallback !== undefined ) {
56 return fallback;
57 }
58 return null;
59 }
60 return this.values[selection];
61 }
62 if ( selection === undefined ) {
63 return this.values;
64 } else {
65 return null; // invalid selection key
66 }
67 },
68
69 /**
70 * Sets one or multiple key/value pairs.
71 *
72 * @param selection {mixed} String key or array of keys to set values for.
73 * @param value {mixed} Value to set (optional, only in use when key is a string)
74 * @return {Boolean} This returns true on success, false on failure.
75 */
76 set: function ( selection, value ) {
77 var s;
78
79 if ( $.isPlainObject( selection ) ) {
80 for ( s in selection ) {
81 this.values[s] = selection[s];
82 }
83 return true;
84 } else if ( typeof selection === 'string' && value !== undefined ) {
85 this.values[selection] = value;
86 return true;
87 }
88 return false;
89 },
90
91 /**
92 * Checks if one or multiple keys exist.
93 *
94 * @param selection {mixed} String key or array of keys to check
95 * @return {Boolean} Existence of key(s)
96 */
97 exists: function ( selection ) {
98 var s;
99
100 if ( $.isArray( selection ) ) {
101 for ( s = 0; s < selection.length; s += 1 ) {
102 if ( this.values[selection[s]] === undefined ) {
103 return false;
104 }
105 }
106 return true;
107 } else {
108 return this.values[selection] !== undefined;
109 }
110 }
111 };
112
113 /**
114 * Message
115 *
116 * Object constructor for messages,
117 * similar to the Message class in MediaWiki PHP.
118 *
119 * @param map Map Instance of mw.Map
120 * @param key String
121 * @param parameters Array
122 * @return Message
123 */
124 function Message( map, key, parameters ) {
125 this.format = 'plain';
126 this.map = map;
127 this.key = key;
128 this.parameters = parameters === undefined ? [] : $.makeArray( parameters );
129 return this;
130 }
131
132 Message.prototype = {
133 /**
134 * Appends (does not replace) parameters for replacement to the .parameters property.
135 *
136 * @param parameters Array
137 * @return Message
138 */
139 params: function ( parameters ) {
140 var i;
141 for ( i = 0; i < parameters.length; i += 1 ) {
142 this.parameters.push( parameters[i] );
143 }
144 return this;
145 },
146
147 /**
148 * Converts message object to it's string form based on the state of format.
149 *
150 * @return string Message as a string in the current form or <key> if key does not exist.
151 */
152 toString: function() {
153 if ( !this.map.exists( this.key ) ) {
154 // Use <key> as text if key does not exist
155 if ( this.format !== 'plain' ) {
156 // format 'escape' and 'parse' need to have the brackets and key html escaped
157 return mw.html.escape( '<' + this.key + '>' );
158 }
159 return '<' + this.key + '>';
160 }
161 var text = this.map.get( this.key ),
162 parameters = this.parameters;
163
164 text = text.replace( /\$(\d+)/g, function ( str, match ) {
165 var index = parseInt( match, 10 ) - 1;
166 return parameters[index] !== undefined ? parameters[index] : '$' + match;
167 } );
168
169 if ( this.format === 'plain' ) {
170 return text;
171 }
172 if ( this.format === 'escaped' ) {
173 // According to Message.php this needs {{-transformation, which is
174 // still todo
175 return mw.html.escape( text );
176 }
177
178 /* This should be fixed up when we have a parser
179 if ( this.format === 'parse' && 'language' in mw ) {
180 text = mw.language.parse( text );
181 }
182 */
183 return text;
184 },
185
186 /**
187 * Changes format to parse and converts message to string
188 *
189 * @return {string} String form of parsed message
190 */
191 parse: function() {
192 this.format = 'parse';
193 return this.toString();
194 },
195
196 /**
197 * Changes format to plain and converts message to string
198 *
199 * @return {string} String form of plain message
200 */
201 plain: function() {
202 this.format = 'plain';
203 return this.toString();
204 },
205
206 /**
207 * Changes the format to html escaped and converts message to string
208 *
209 * @return {string} String form of html escaped message
210 */
211 escaped: function() {
212 this.format = 'escaped';
213 return this.toString();
214 },
215
216 /**
217 * Checks if message exists
218 *
219 * @return {string} String form of parsed message
220 */
221 exists: function() {
222 return this.map.exists( this.key );
223 }
224 };
225
226 return {
227 /* Public Members */
228
229 /**
230 * Dummy function which in debug mode can be replaced with a function that
231 * emulates console.log in console-less environments.
232 */
233 log: function() { },
234
235 /**
236 * @var constructor Make the Map constructor publicly available.
237 */
238 Map: Map,
239
240 /**
241 * List of configuration values
242 *
243 * Dummy placeholder. Initiated in startUp module as a new instance of mw.Map().
244 * If $wgLegacyJavaScriptGlobals is true, this Map will have its values
245 * in the global window object.
246 */
247 config: null,
248
249 /**
250 * @var object
251 *
252 * Empty object that plugins can be installed in.
253 */
254 libs: {},
255
256 /* Extension points */
257
258 legacy: {},
259
260 /**
261 * Localization system
262 */
263 messages: new Map(),
264
265 /* Public Methods */
266
267 /**
268 * Gets a message object, similar to wfMessage()
269 *
270 * @param key string Key of message to get
271 * @param parameter_1 mixed First argument in a list of variadic arguments,
272 * each a parameter for $N replacement in messages.
273 * @return Message
274 */
275 message: function ( key, parameter_1 /* [, parameter_2] */ ) {
276 var parameters;
277 // Support variadic arguments
278 if ( parameter_1 !== undefined ) {
279 parameters = $.makeArray( arguments );
280 parameters.shift();
281 } else {
282 parameters = [];
283 }
284 return new Message( mw.messages, key, parameters );
285 },
286
287 /**
288 * Gets a message string, similar to wfMsg()
289 *
290 * @param key string Key of message to get
291 * @param parameters mixed First argument in a list of variadic arguments,
292 * each a parameter for $N replacement in messages.
293 * @return String.
294 */
295 msg: function ( key, parameters ) {
296 return mw.message.apply( mw.message, arguments ).toString();
297 },
298
299 /**
300 * Client-side module loader which integrates with the MediaWiki ResourceLoader
301 */
302 loader: ( function() {
303
304 /* Private Members */
305
306 /**
307 * Mapping of registered modules
308 *
309 * The jquery module is pre-registered, because it must have already
310 * been provided for this object to have been built, and in debug mode
311 * jquery would have been provided through a unique loader request,
312 * making it impossible to hold back registration of jquery until after
313 * mediawiki.
314 *
315 * For exact details on support for script, style and messages, look at
316 * mw.loader.implement.
317 *
318 * Format:
319 * {
320 * 'moduleName': {
321 * 'version': ############## (unix timestamp),
322 * 'dependencies': ['required.foo', 'bar.also', ...], (or) function() {}
323 * 'group': 'somegroup', (or) null,
324 * 'source': 'local', 'someforeignwiki', (or) null
325 * 'state': 'registered', 'loading', 'loaded', 'ready', 'error' or 'missing'
326 * 'script': ...,
327 * 'style': ...,
328 * 'messages': { 'key': 'value' },
329 * }
330 * }
331 */
332 var registry = {},
333 /**
334 * Mapping of sources, keyed by source-id, values are objects.
335 * Format:
336 * {
337 * 'sourceId': {
338 * 'loadScript': 'http://foo.bar/w/load.php'
339 * }
340 * }
341 */
342 sources = {},
343 // List of modules which will be loaded as when ready
344 batch = [],
345 // List of modules to be loaded
346 queue = [],
347 // List of callback functions waiting for modules to be ready to be called
348 jobs = [],
349 // Flag inidicating that document ready has occured
350 ready = false,
351 // Selector cache for the marker element. Use getMarker() to get/use the marker!
352 $marker = null;
353
354 /* Cache document ready status */
355
356 $(document).ready( function () {
357 ready = true;
358 } );
359
360 /* Private methods */
361
362 function getMarker(){
363 // Cached ?
364 if ( $marker ) {
365 return $marker;
366 } else {
367 $marker = $( 'meta[name="ResourceLoaderDynamicStyles"]' );
368 if ( $marker.length ) {
369 return $marker;
370 }
371 mw.log( 'getMarker> No <meta name="ResourceLoaderDynamicStyles"> found, inserting dynamically.' );
372 $marker = $( '<meta>' ).attr( 'name', 'ResourceLoaderDynamicStyles' ).appendTo( 'head' );
373 return $marker;
374 }
375 }
376
377 function compare( a, b ) {
378 var i;
379 if ( a.length !== b.length ) {
380 return false;
381 }
382 for ( i = 0; i < b.length; i += 1 ) {
383 if ( $.isArray( a[i] ) ) {
384 if ( !compare( a[i], b[i] ) ) {
385 return false;
386 }
387 }
388 if ( a[i] !== b[i] ) {
389 return false;
390 }
391 }
392 return true;
393 }
394
395 /**
396 * Generates an ISO8601 "basic" string from a UNIX timestamp
397 */
398 function formatVersionNumber( timestamp ) {
399 var pad = function ( a, b, c ) {
400 return [a < 10 ? '0' + a : a, b < 10 ? '0' + b : b, c < 10 ? '0' + c : c].join( '' );
401 },
402 d = new Date();
403 d.setTime( timestamp * 1000 );
404 return [
405 pad( d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate() ), 'T',
406 pad( d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds() ), 'Z'
407 ].join( '' );
408 }
409
410 /**
411 * Recursively resolves dependencies and detects circular references
412 */
413 function recurse( module, resolved, unresolved ) {
414 var n, deps, len;
415
416 if ( registry[module] === undefined ) {
417 throw new Error( 'Unknown dependency: ' + module );
418 }
419 // Resolves dynamic loader function and replaces it with its own results
420 if ( $.isFunction( registry[module].dependencies ) ) {
421 registry[module].dependencies = registry[module].dependencies();
422 // Ensures the module's dependencies are always in an array
423 if ( typeof registry[module].dependencies !== 'object' ) {
424 registry[module].dependencies = [registry[module].dependencies];
425 }
426 }
427 // Tracks down dependencies
428 deps = registry[module].dependencies;
429 len = deps.length;
430 for ( n = 0; n < len; n += 1 ) {
431 if ( $.inArray( deps[n], resolved ) === -1 ) {
432 if ( $.inArray( deps[n], unresolved ) !== -1 ) {
433 throw new Error(
434 'Circular reference detected: ' + module +
435 ' -> ' + deps[n]
436 );
437 }
438
439 // Add to unresolved
440 unresolved[unresolved.length] = module;
441 recurse( deps[n], resolved, unresolved );
442 // module is at the end of unresolved
443 unresolved.pop();
444 }
445 }
446 resolved[resolved.length] = module;
447 }
448
449 /**
450 * Gets a list of module names that a module depends on in their proper dependency order
451 *
452 * @param module string module name or array of string module names
453 * @return list of dependencies, including 'module'.
454 * @throws Error if circular reference is detected
455 */
456 function resolve( module ) {
457 var modules, m, deps, n, resolved;
458
459 // Allow calling with an array of module names
460 if ( $.isArray( module ) ) {
461 modules = [];
462 for ( m = 0; m < module.length; m += 1 ) {
463 deps = resolve( module[m] );
464 for ( n = 0; n < deps.length; n += 1 ) {
465 modules[modules.length] = deps[n];
466 }
467 }
468 return modules;
469 } else if ( typeof module === 'string' ) {
470 resolved = [];
471 recurse( module, resolved, [] );
472 return resolved;
473 }
474 throw new Error( 'Invalid module argument: ' + module );
475 }
476
477 /**
478 * Narrows a list of module names down to those matching a specific
479 * state (see comment on top of this scope for a list of valid states).
480 * One can also filter for 'unregistered', which will return the
481 * modules names that don't have a registry entry.
482 *
483 * @param states string or array of strings of module states to filter by
484 * @param modules array list of module names to filter (optional, by default the entire
485 * registry is used)
486 * @return array list of filtered module names
487 */
488 function filter( states, modules ) {
489 var list, module, s, m;
490
491 // Allow states to be given as a string
492 if ( typeof states === 'string' ) {
493 states = [states];
494 }
495 // If called without a list of modules, build and use a list of all modules
496 list = [];
497 if ( modules === undefined ) {
498 modules = [];
499 for ( module in registry ) {
500 modules[modules.length] = module;
501 }
502 }
503 // Build a list of modules which are in one of the specified states
504 for ( s = 0; s < states.length; s += 1 ) {
505 for ( m = 0; m < modules.length; m += 1 ) {
506 if ( registry[modules[m]] === undefined ) {
507 // Module does not exist
508 if ( states[s] === 'unregistered' ) {
509 // OK, undefined
510 list[list.length] = modules[m];
511 }
512 } else {
513 // Module exists, check state
514 if ( registry[modules[m]].state === states[s] ) {
515 // OK, correct state
516 list[list.length] = modules[m];
517 }
518 }
519 }
520 }
521 return list;
522 }
523
524 /**
525 * Automatically executes jobs and modules which are pending with satistifed dependencies.
526 *
527 * This is used when dependencies are satisfied, such as when a module is executed.
528 */
529 function handlePending( module ) {
530 var j, r;
531
532 try {
533 // Run jobs who's dependencies have just been met
534 for ( j = 0; j < jobs.length; j += 1 ) {
535 if ( compare(
536 filter( 'ready', jobs[j].dependencies ),
537 jobs[j].dependencies ) )
538 {
539 if ( $.isFunction( jobs[j].ready ) ) {
540 jobs[j].ready();
541 }
542 jobs.splice( j, 1 );
543 j -= 1;
544 }
545 }
546 // Execute modules who's dependencies have just been met
547 for ( r in registry ) {
548 if ( registry[r].state === 'loaded' ) {
549 if ( compare(
550 filter( ['ready'], registry[r].dependencies ),
551 registry[r].dependencies ) )
552 {
553 execute( r );
554 }
555 }
556 }
557 } catch ( e ) {
558 // Run error callbacks of jobs affected by this condition
559 for ( j = 0; j < jobs.length; j += 1 ) {
560 if ( $.inArray( module, jobs[j].dependencies ) !== -1 ) {
561 if ( $.isFunction( jobs[j].error ) ) {
562 jobs[j].error( e, module );
563 }
564 jobs.splice( j, 1 );
565 j -= 1;
566 }
567 }
568 }
569 }
570
571 /**
572 * Adds a script tag to the body, either using document.write or low-level DOM manipulation,
573 * depending on whether document-ready has occured yet.
574 *
575 * @param src String: URL to script, will be used as the src attribute in the script tag
576 * @param callback Function: Optional callback which will be run when the script is done
577 */
578 function addScript( src, callback ) {
579 var done = false, script;
580 if ( ready ) {
581 // jQuery's getScript method is NOT better than doing this the old-fashioned way
582 // because jQuery will eval the script's code, and errors will not have sane
583 // line numbers.
584 script = document.createElement( 'script' );
585 script.setAttribute( 'src', src );
586 script.setAttribute( 'type', 'text/javascript' );
587 if ( $.isFunction( callback ) ) {
588 // Attach handlers for all browsers (based on jQuery.ajax)
589 script.onload = script.onreadystatechange = function() {
590
591 if (
592 !done
593 && (
594 !script.readyState
595 || /loaded|complete/.test( script.readyState )
596 )
597 ) {
598
599 done = true;
600
601 // Handle memory leak in IE
602 script.onload = script.onreadystatechange = null;
603
604 callback();
605
606 if ( script.parentNode ) {
607 script.parentNode.removeChild( script );
608 }
609
610 // Dereference the script
611 script = undefined;
612 }
613 };
614 }
615 document.body.appendChild( script );
616 } else {
617 document.write( mw.html.element(
618 'script', { 'type': 'text/javascript', 'src': src }, ''
619 ) );
620 if ( $.isFunction( callback ) ) {
621 // Document.write is synchronous, so this is called when it's done
622 callback();
623 }
624 }
625 }
626
627 /**
628 * Executes a loaded module, making it ready to use
629 *
630 * @param module string module name to execute
631 */
632 function execute( module, callback ) {
633 var style, media, i, script, markModuleReady, nestedAddScript;
634
635 if ( registry[module] === undefined ) {
636 throw new Error( 'Module has not been registered yet: ' + module );
637 } else if ( registry[module].state === 'registered' ) {
638 throw new Error( 'Module has not been requested from the server yet: ' + module );
639 } else if ( registry[module].state === 'loading' ) {
640 throw new Error( 'Module has not completed loading yet: ' + module );
641 } else if ( registry[module].state === 'ready' ) {
642 throw new Error( 'Module has already been loaded: ' + module );
643 }
644
645 // Add styles
646 if ( $.isPlainObject( registry[module].style ) ) {
647 for ( media in registry[module].style ) {
648 style = registry[module].style[media];
649 if ( $.isArray( style ) ) {
650 for ( i = 0; i < style.length; i += 1 ) {
651 getMarker().before( mw.html.element( 'link', {
652 'type': 'text/css',
653 'media': media,
654 'rel': 'stylesheet',
655 'href': style[i]
656 } ) );
657 }
658 } else if ( typeof style === 'string' ) {
659 getMarker().before( mw.html.element( 'style', {
660 'type': 'text/css',
661 'media': media
662 }, new mw.html.Cdata( style ) ) );
663 }
664 }
665 }
666 // Add localizations to message system
667 if ( $.isPlainObject( registry[module].messages ) ) {
668 mw.messages.set( registry[module].messages );
669 }
670 // Execute script
671 try {
672 script = registry[module].script;
673 markModuleReady = function() {
674 registry[module].state = 'ready';
675 handlePending( module );
676 if ( $.isFunction( callback ) ) {
677 callback();
678 }
679 };
680 nestedAddScript = function ( arr, callback, i ) {
681 // Recursively call addScript() in its own callback
682 // for each element of arr.
683 if ( i >= arr.length ) {
684 // We're at the end of the array
685 callback();
686 return;
687 }
688
689 addScript( arr[i], function() {
690 nestedAddScript( arr, callback, i + 1 );
691 } );
692 };
693
694 if ( $.isArray( script ) ) {
695 registry[module].state = 'loading';
696 nestedAddScript( script, markModuleReady, 0 );
697 } else if ( $.isFunction( script ) ) {
698 script( $ );
699 markModuleReady();
700 }
701 } catch ( e ) {
702 // This needs to NOT use mw.log because these errors are common in production mode
703 // and not in debug mode, such as when a symbol that should be global isn't exported
704 if ( window.console && typeof window.console.log === 'function' ) {
705 console.log( 'mw.loader::execute> Exception thrown by ' + module + ': ' + e.message );
706 }
707 registry[module].state = 'error';
708 throw e;
709 }
710 }
711
712 /**
713 * Adds a dependencies to the queue with optional callbacks to be run
714 * when the dependencies are ready or fail
715 *
716 * @param dependencies string module name or array of string module names
717 * @param ready function callback to execute when all dependencies are ready
718 * @param error function callback to execute when any dependency fails
719 */
720 function request( dependencies, ready, error ) {
721 var regItemDeps, regItemDepLen, n;
722
723 // Allow calling by single module name
724 if ( typeof dependencies === 'string' ) {
725 dependencies = [dependencies];
726 if ( registry[dependencies[0]] !== undefined ) {
727 // Cache repetitively accessed deep level object member
728 regItemDeps = registry[dependencies[0]].dependencies;
729 // Cache to avoid looped access to length property
730 regItemDepLen = regItemDeps.length;
731 for ( n = 0; n < regItemDepLen; n += 1 ) {
732 dependencies[dependencies.length] = regItemDeps[n];
733 }
734 }
735 }
736 // Add ready and error callbacks if they were given
737 if ( arguments.length > 1 ) {
738 jobs[jobs.length] = {
739 'dependencies': filter(
740 ['registered', 'loading', 'loaded'],
741 dependencies
742 ),
743 'ready': ready,
744 'error': error
745 };
746 }
747 // Queue up any dependencies that are registered
748 dependencies = filter( ['registered'], dependencies );
749 for ( n = 0; n < dependencies.length; n += 1 ) {
750 if ( $.inArray( dependencies[n], queue ) === -1 ) {
751 queue[queue.length] = dependencies[n];
752 }
753 }
754 // Work the queue
755 mw.loader.work();
756 }
757
758 function sortQuery(o) {
759 var sorted = {}, key, a = [];
760 for ( key in o ) {
761 if ( hasOwn.call( o, key ) ) {
762 a.push( key );
763 }
764 }
765 a.sort();
766 for ( key = 0; key < a.length; key += 1 ) {
767 sorted[a[key]] = o[a[key]];
768 }
769 return sorted;
770 }
771
772 /**
773 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
774 * to a query string of the form foo.bar,baz|bar.baz,quux
775 */
776 function buildModulesString( moduleMap ) {
777 var arr = [], p, prefix;
778 for ( prefix in moduleMap ) {
779 p = prefix === '' ? '' : prefix + '.';
780 arr.push( p + moduleMap[prefix].join( ',' ) );
781 }
782 return arr.join( '|' );
783 }
784
785 /**
786 * Asynchronously append a script tag to the end of the body
787 * that invokes load.php
788 * @param moduleMap {Object}: Module map, see buildModulesString()
789 * @param currReqBase {Object}: Object with other parameters (other than 'modules') to use in the request
790 * @param sourceLoadScript {String}: URL of load.php
791 */
792 function doRequest( moduleMap, currReqBase, sourceLoadScript ) {
793 var request = $.extend(
794 { 'modules': buildModulesString( moduleMap ) },
795 currReqBase
796 );
797 request = sortQuery( request );
798 // Asynchronously append a script tag to the end of the body
799 // Append &* to avoid triggering the IE6 extension check
800 addScript( sourceLoadScript + '?' + $.param( request ) + '&*' );
801 }
802
803 /* Public Methods */
804 return {
805 /**
806 * Requests dependencies from server, loading and executing when things when ready.
807 */
808 work: function () {
809 var reqBase, splits, maxQueryLength, q, b, bSource, bGroup, bSourceGroup,
810 source, group, g, i, modules, maxVersion, sourceLoadScript,
811 currReqBase, currReqBaseLength, moduleMap, l,
812 lastDotIndex, prefix, suffix, bytesAdded;
813
814 // Build a list of request parameters common to all requests.
815 reqBase = {
816 skin: mw.config.get( 'skin' ),
817 lang: mw.config.get( 'wgUserLanguage' ),
818 debug: mw.config.get( 'debug' )
819 };
820 // Split module batch by source and by group.
821 splits = {};
822 maxQueryLength = mw.config.get( 'wgResourceLoaderMaxQueryLength', -1 );
823
824 // Appends a list of modules from the queue to the batch
825 for ( q = 0; q < queue.length; q += 1 ) {
826 // Only request modules which are registered
827 if ( registry[queue[q]] !== undefined && registry[queue[q]].state === 'registered' ) {
828 // Prevent duplicate entries
829 if ( $.inArray( queue[q], batch ) === -1 ) {
830 batch[batch.length] = queue[q];
831 // Mark registered modules as loading
832 registry[queue[q]].state = 'loading';
833 }
834 }
835 }
836 // Early exit if there's nothing to load...
837 if ( !batch.length ) {
838 return;
839 }
840
841 // The queue has been processed into the batch, clear up the queue.
842 queue = [];
843
844 // Always order modules alphabetically to help reduce cache
845 // misses for otherwise identical content.
846 batch.sort();
847
848 // Split batch by source and by group.
849 for ( b = 0; b < batch.length; b += 1 ) {
850 bSource = registry[batch[b]].source;
851 bGroup = registry[batch[b]].group;
852 if ( splits[bSource] === undefined ) {
853 splits[bSource] = {};
854 }
855 if ( splits[bSource][bGroup] === undefined ) {
856 splits[bSource][bGroup] = [];
857 }
858 bSourceGroup = splits[bSource][bGroup];
859 bSourceGroup[bSourceGroup.length] = batch[b];
860 }
861
862 // Clear the batch - this MUST happen before we append any
863 // script elements to the body or it's possible that a script
864 // will be locally cached, instantly load, and work the batch
865 // again, all before we've cleared it causing each request to
866 // include modules which are already loaded.
867 batch = [];
868
869 for ( source in splits ) {
870
871 sourceLoadScript = sources[source].loadScript;
872
873 for ( group in splits[source] ) {
874
875 // Cache access to currently selected list of
876 // modules for this group from this source.
877 modules = splits[source][group];
878
879 // Calculate the highest timestamp
880 maxVersion = 0;
881 for ( g = 0; g < modules.length; g += 1 ) {
882 if ( registry[modules[g]].version > maxVersion ) {
883 maxVersion = registry[modules[g]].version;
884 }
885 }
886
887 currReqBase = $.extend( { 'version': formatVersionNumber( maxVersion ) }, reqBase );
888 currReqBaseLength = $.param( currReqBase ).length;
889 moduleMap = {};
890 // We may need to split up the request to honor the query string length limit,
891 // so build it piece by piece.
892 l = currReqBaseLength + 9; // '&modules='.length == 9
893
894 moduleMap = {}; // { prefix: [ suffixes ] }
895
896 for ( i = 0; i < modules.length; i += 1 ) {
897 // Determine how many bytes this module would add to the query string
898 lastDotIndex = modules[i].lastIndexOf( '.' );
899 // Note that these substr() calls work even if lastDotIndex == -1
900 prefix = modules[i].substr( 0, lastDotIndex );
901 suffix = modules[i].substr( lastDotIndex + 1 );
902 bytesAdded = moduleMap[prefix] !== undefined
903 ? suffix.length + 3 // '%2C'.length == 3
904 : modules[i].length + 3; // '%7C'.length == 3
905
906 // If the request would become too long, create a new one,
907 // but don't create empty requests
908 if ( maxQueryLength > 0 && !$.isEmptyObject( moduleMap ) && l + bytesAdded > maxQueryLength ) {
909 // This request would become too long, create a new one
910 // and fire off the old one
911 doRequest( moduleMap, currReqBase, sourceLoadScript );
912 moduleMap = {};
913 l = currReqBaseLength + 9;
914 }
915 if ( moduleMap[prefix] === undefined ) {
916 moduleMap[prefix] = [];
917 }
918 moduleMap[prefix].push( suffix );
919 l += bytesAdded;
920 }
921 // If there's anything left in moduleMap, request that too
922 if ( !$.isEmptyObject( moduleMap ) ) {
923 doRequest( moduleMap, currReqBase, sourceLoadScript );
924 }
925 }
926 }
927 },
928
929 /**
930 * Register a source.
931 *
932 * @param id {String}: Short lowercase a-Z string representing a source, only used internally.
933 * @param props {Object}: Object containing only the loadScript property which is a url to
934 * the load.php location of the source.
935 * @return {Boolean}
936 */
937 addSource: function ( id, props ) {
938 var source;
939 // Allow multiple additions
940 if ( typeof id === 'object' ) {
941 for ( source in id ) {
942 mw.loader.addSource( source, id[source] );
943 }
944 return true;
945 }
946
947 if ( sources[id] !== undefined ) {
948 throw new Error( 'source already registered: ' + id );
949 }
950
951 sources[id] = props;
952
953 return true;
954 },
955
956 /**
957 * Registers a module, letting the system know about it and its
958 * properties. Startup modules contain calls to this function.
959 *
960 * @param module {String}: Module name
961 * @param version {Number}: Module version number as a timestamp (falls backs to 0)
962 * @param dependencies {String|Array|Function}: One string or array of strings of module
963 * names on which this module depends, or a function that returns that array.
964 * @param group {String}: Group which the module is in (optional, defaults to null)
965 * @param source {String}: Name of the source. Defaults to local.
966 */
967 register: function ( module, version, dependencies, group, source ) {
968 var m;
969 // Allow multiple registration
970 if ( typeof module === 'object' ) {
971 for ( m = 0; m < module.length; m += 1 ) {
972 // module is an array of module names
973 if ( typeof module[m] === 'string' ) {
974 mw.loader.register( module[m] );
975 // module is an array of arrays
976 } else if ( typeof module[m] === 'object' ) {
977 mw.loader.register.apply( mw.loader, module[m] );
978 }
979 }
980 return;
981 }
982 // Validate input
983 if ( typeof module !== 'string' ) {
984 throw new Error( 'module must be a string, not a ' + typeof module );
985 }
986 if ( registry[module] !== undefined ) {
987 throw new Error( 'module already registered: ' + module );
988 }
989 // List the module as registered
990 registry[module] = {
991 'version': version !== undefined ? parseInt( version, 10 ) : 0,
992 'dependencies': [],
993 'group': typeof group === 'string' ? group : null,
994 'source': typeof source === 'string' ? source: 'local',
995 'state': 'registered'
996 };
997 if ( typeof dependencies === 'string' ) {
998 // Allow dependencies to be given as a single module name
999 registry[module].dependencies = [dependencies];
1000 } else if ( typeof dependencies === 'object' || $.isFunction( dependencies ) ) {
1001 // Allow dependencies to be given as an array of module names
1002 // or a function which returns an array
1003 registry[module].dependencies = dependencies;
1004 }
1005 },
1006
1007 /**
1008 * Implements a module, giving the system a course of action to take
1009 * upon loading. Results of a request for one or more modules contain
1010 * calls to this function.
1011 *
1012 * All arguments are required.
1013 *
1014 * @param module String: Name of module
1015 * @param script Mixed: Function of module code or String of URL to be used as the src
1016 * attribute when adding a script element to the body
1017 * @param style Object: Object of CSS strings keyed by media-type or Object of lists of URLs
1018 * keyed by media-type
1019 * @param msgs Object: List of key/value pairs to be passed through mw.messages.set
1020 */
1021 implement: function ( module, script, style, msgs ) {
1022 // Validate input
1023 if ( typeof module !== 'string' ) {
1024 throw new Error( 'module must be a string, not a ' + typeof module );
1025 }
1026 if ( !$.isFunction( script ) && !$.isArray( script ) ) {
1027 throw new Error( 'script must be a function or an array, not a ' + typeof script );
1028 }
1029 if ( !$.isPlainObject( style ) ) {
1030 throw new Error( 'style must be an object, not a ' + typeof style );
1031 }
1032 if ( !$.isPlainObject( msgs ) ) {
1033 throw new Error( 'msgs must be an object, not a ' + typeof msgs );
1034 }
1035 // Automatically register module
1036 if ( registry[module] === undefined ) {
1037 mw.loader.register( module );
1038 }
1039 // Check for duplicate implementation
1040 if ( registry[module] !== undefined && registry[module].script !== undefined ) {
1041 throw new Error( 'module already implemented: ' + module );
1042 }
1043 // Mark module as loaded
1044 registry[module].state = 'loaded';
1045 // Attach components
1046 registry[module].script = script;
1047 registry[module].style = style;
1048 registry[module].messages = msgs;
1049 // Execute or queue callback
1050 if ( compare(
1051 filter( ['ready'], registry[module].dependencies ),
1052 registry[module].dependencies ) )
1053 {
1054 execute( module );
1055 }
1056 },
1057
1058 /**
1059 * Executes a function as soon as one or more required modules are ready
1060 *
1061 * @param dependencies {String|Array} Module name or array of modules names the callback
1062 * dependends on to be ready before executing
1063 * @param ready {Function} callback to execute when all dependencies are ready (optional)
1064 * @param error {Function} callback to execute when if dependencies have a errors (optional)
1065 */
1066 using: function ( dependencies, ready, error ) {
1067 var tod = typeof dependencies;
1068 // Validate input
1069 if ( tod !== 'object' && tod !== 'string' ) {
1070 throw new Error( 'dependencies must be a string or an array, not a ' + tod );
1071 }
1072 // Allow calling with a single dependency as a string
1073 if ( tod === 'string' ) {
1074 dependencies = [dependencies];
1075 }
1076 // Resolve entire dependency map
1077 dependencies = resolve( dependencies );
1078 // If all dependencies are met, execute ready immediately
1079 if ( compare( filter( ['ready'], dependencies ), dependencies ) ) {
1080 if ( $.isFunction( ready ) ) {
1081 ready();
1082 }
1083 }
1084 // If any dependencies have errors execute error immediately
1085 else if ( filter( ['error'], dependencies ).length ) {
1086 if ( $.isFunction( error ) ) {
1087 error( new Error( 'one or more dependencies have state "error"' ),
1088 dependencies );
1089 }
1090 }
1091 // Since some dependencies are not yet ready, queue up a request
1092 else {
1093 request( dependencies, ready, error );
1094 }
1095 },
1096
1097 /**
1098 * Loads an external script or one or more modules for future use
1099 *
1100 * @param modules {mixed} Either the name of a module, array of modules,
1101 * or a URL of an external script or style
1102 * @param type {String} mime-type to use if calling with a URL of an
1103 * external script or style; acceptable values are "text/css" and
1104 * "text/javascript"; if no type is provided, text/javascript is assumed.
1105 */
1106 load: function ( modules, type ) {
1107 var filtered, m;
1108
1109 // Validate input
1110 if ( typeof modules !== 'object' && typeof modules !== 'string' ) {
1111 throw new Error( 'modules must be a string or an array, not a ' + typeof modules );
1112 }
1113 // Allow calling with an external url or single dependency as a string
1114 if ( typeof modules === 'string' ) {
1115 // Support adding arbitrary external scripts
1116 if ( /^(https?:)?\/\//.test( modules ) ) {
1117 if ( type === 'text/css' ) {
1118 $( 'head' ).append( $( '<link>', {
1119 rel: 'stylesheet',
1120 type: 'text/css',
1121 href: modules
1122 } ) );
1123 return;
1124 } else if ( type === 'text/javascript' || type === undefined ) {
1125 addScript( modules );
1126 return;
1127 }
1128 // Unknown type
1129 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type );
1130 }
1131 // Called with single module
1132 modules = [modules];
1133 }
1134
1135 // Filter out undefined modules, otherwise resolve() will throw
1136 // an exception for trying to load an undefined module.
1137 // Undefined modules are acceptable here in load(), because load() takes
1138 // an array of unrelated modules, whereas the modules passed to
1139 // using() are related and must all be loaded.
1140 for ( filtered = [], m = 0; m < modules.length; m += 1 ) {
1141 if ( registry[modules[m]] !== undefined ) {
1142 filtered[filtered.length] = modules[m];
1143 }
1144 }
1145
1146 // Resolve entire dependency map
1147 filtered = resolve( filtered );
1148 // If all modules are ready, nothing dependency be done
1149 if ( compare( filter( ['ready'], filtered ), filtered ) ) {
1150 return;
1151 }
1152 // If any modules have errors
1153 else if ( filter( ['error'], filtered ).length ) {
1154 return;
1155 }
1156 // Since some modules are not yet ready, queue up a request
1157 else {
1158 request( filtered );
1159 return;
1160 }
1161 },
1162
1163 /**
1164 * Changes the state of a module
1165 *
1166 * @param module {String|Object} module name or object of module name/state pairs
1167 * @param state {String} state name
1168 */
1169 state: function ( module, state ) {
1170 var m;
1171 if ( typeof module === 'object' ) {
1172 for ( m in module ) {
1173 mw.loader.state( m, module[m] );
1174 }
1175 return;
1176 }
1177 if ( registry[module] === undefined ) {
1178 mw.loader.register( module );
1179 }
1180 registry[module].state = state;
1181 },
1182
1183 /**
1184 * Gets the version of a module
1185 *
1186 * @param module string name of module to get version for
1187 */
1188 getVersion: function ( module ) {
1189 if ( registry[module] !== undefined && registry[module].version !== undefined ) {
1190 return formatVersionNumber( registry[module].version );
1191 }
1192 return null;
1193 },
1194
1195 /**
1196 * @deprecated since 1.18 use mw.loader.getVersion() instead
1197 */
1198 version: function () {
1199 return mw.loader.getVersion.apply( mw.loader, arguments );
1200 },
1201
1202 /**
1203 * Gets the state of a module
1204 *
1205 * @param module string name of module to get state for
1206 */
1207 getState: function ( module ) {
1208 if ( registry[module] !== undefined && registry[module].state !== undefined ) {
1209 return registry[module].state;
1210 }
1211 return null;
1212 },
1213
1214 /**
1215 * Get names of all registered modules.
1216 *
1217 * @return {Array}
1218 */
1219 getModuleNames: function () {
1220 return $.map( registry, function ( i, key ) {
1221 return key;
1222 } );
1223 },
1224
1225 /**
1226 * For backwards-compatibility with Squid-cached pages. Loads mw.user
1227 */
1228 go: function () {
1229 mw.loader.load( 'mediawiki.user' );
1230 }
1231 };
1232 }() ),
1233
1234 /** HTML construction helper functions */
1235 html: ( function () {
1236 function escapeCallback( s ) {
1237 switch ( s ) {
1238 case "'":
1239 return '&#039;';
1240 case '"':
1241 return '&quot;';
1242 case '<':
1243 return '&lt;';
1244 case '>':
1245 return '&gt;';
1246 case '&':
1247 return '&amp;';
1248 }
1249 }
1250
1251 return {
1252 /**
1253 * Escape a string for HTML. Converts special characters to HTML entities.
1254 * @param s The string to escape
1255 */
1256 escape: function ( s ) {
1257 return s.replace( /['"<>&]/g, escapeCallback );
1258 },
1259
1260 /**
1261 * Wrapper object for raw HTML passed to mw.html.element().
1262 * @constructor
1263 */
1264 Raw: function ( value ) {
1265 this.value = value;
1266 },
1267
1268 /**
1269 * Wrapper object for CDATA element contents passed to mw.html.element()
1270 * @constructor
1271 */
1272 Cdata: function ( value ) {
1273 this.value = value;
1274 },
1275
1276 /**
1277 * Create an HTML element string, with safe escaping.
1278 *
1279 * @param name The tag name.
1280 * @param attrs An object with members mapping element names to values
1281 * @param contents The contents of the element. May be either:
1282 * - string: The string is escaped.
1283 * - null or undefined: The short closing form is used, e.g. <br/>.
1284 * - this.Raw: The value attribute is included without escaping.
1285 * - this.Cdata: The value attribute is included, and an exception is
1286 * thrown if it contains an illegal ETAGO delimiter.
1287 * See http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.3.2
1288 *
1289 * Example:
1290 * var h = mw.html;
1291 * return h.element( 'div', {},
1292 * new h.Raw( h.element( 'img', {src: '<'} ) ) );
1293 * Returns <div><img src="&lt;"/></div>
1294 */
1295 element: function ( name, attrs, contents ) {
1296 var v, attrName, s = '<' + name;
1297
1298 for ( attrName in attrs ) {
1299 v = attrs[attrName];
1300 // Convert name=true, to name=name
1301 if ( v === true ) {
1302 v = attrName;
1303 // Skip name=false
1304 } else if ( v === false ) {
1305 continue;
1306 }
1307 s += ' ' + attrName + '="' + this.escape( String( v ) ) + '"';
1308 }
1309 if ( contents === undefined || contents === null ) {
1310 // Self close tag
1311 s += '/>';
1312 return s;
1313 }
1314 // Regular open tag
1315 s += '>';
1316 switch ( typeof contents ) {
1317 case 'string':
1318 // Escaped
1319 s += this.escape( contents );
1320 break;
1321 case 'number':
1322 case 'boolean':
1323 // Convert to string
1324 s += String( contents );
1325 break;
1326 default:
1327 if ( contents instanceof this.Raw ) {
1328 // Raw HTML inclusion
1329 s += contents.value;
1330 } else if ( contents instanceof this.Cdata ) {
1331 // CDATA
1332 if ( /<\/[a-zA-z]/.test( contents.value ) ) {
1333 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
1334 }
1335 s += contents.value;
1336 } else {
1337 throw new Error( 'mw.html.element: Invalid type of contents' );
1338 }
1339 }
1340 s += '</' + name + '>';
1341 return s;
1342 }
1343 };
1344 })()
1345 };
1346
1347 })( jQuery );
1348
1349 // Alias $j to jQuery for backwards compatibility
1350 window.$j = jQuery;
1351
1352 // Attach to window and globally alias
1353 window.mw = window.mediaWiki = mw;
1354
1355 // Auto-register from pre-loaded startup scripts
1356 if ( typeof startUp !== 'undefined' && jQuery.isFunction( startUp ) ) {
1357 startUp();
1358 startUp = undefined;
1359 }