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