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