For backwards compatibility with cached HTML generated by MediaWiki 1.17, re-introduc...
[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 'media': media,
525 'rel': 'stylesheet',
526 'href': style[i]
527 } ) );
528 }
529 } else if ( typeof style === 'string' ) {
530 getMarker().before( mw.html.element( 'style', {
531 'type': 'text/css',
532 'media': media
533 }, new mw.html.Cdata( style ) ) );
534 }
535 }
536 }
537 // Add localizations to message system
538 if ( $.isPlainObject( registry[module].messages ) ) {
539 mw.messages.set( registry[module].messages );
540 }
541 // Execute script
542 try {
543 var script = registry[module].script,
544 markModuleReady = function() {
545 registry[module].state = 'ready';
546 handlePending( module );
547 if ( $.isFunction( callback ) ) {
548 callback();
549 }
550 },
551 nestedAddScript = function( arr, callback, i ) {
552 // Recursively call addScript() in its own callback
553 // for each element of arr.
554 if ( i >= arr.length ) {
555 // We're at the end of the array
556 callback();
557 return;
558 }
559
560 addScript( arr[i], function() {
561 nestedAddScript( arr, callback, i + 1 );
562 } );
563 };
564
565 if ( $.isArray( script ) ) {
566 registry[module].state = 'loading';
567 nestedAddScript( script, markModuleReady, 0 );
568 } else if ( $.isFunction( script ) ) {
569 script( $ );
570 markModuleReady();
571 }
572 } catch ( e ) {
573 // This needs to NOT use mw.log because these errors are common in production mode
574 // and not in debug mode, such as when a symbol that should be global isn't exported
575 if ( window.console && typeof window.console.log === 'function' ) {
576 console.log( 'mw.loader::execute> Exception thrown by ' + module + ': ' + e.message );
577 }
578 registry[module].state = 'error';
579 throw e;
580 }
581 }
582
583 /**
584 * Automatically executes jobs and modules which are pending with satistifed dependencies.
585 *
586 * This is used when dependencies are satisfied, such as when a module is executed.
587 */
588 function handlePending( module ) {
589 try {
590 // Run jobs who's dependencies have just been met
591 for ( var j = 0; j < jobs.length; j++ ) {
592 if ( compare(
593 filter( 'ready', jobs[j].dependencies ),
594 jobs[j].dependencies ) )
595 {
596 if ( $.isFunction( jobs[j].ready ) ) {
597 jobs[j].ready();
598 }
599 jobs.splice( j, 1 );
600 j--;
601 }
602 }
603 // Execute modules who's dependencies have just been met
604 for ( var r in registry ) {
605 if ( registry[r].state === 'loaded' ) {
606 if ( compare(
607 filter( ['ready'], registry[r].dependencies ),
608 registry[r].dependencies ) )
609 {
610 execute( r );
611 }
612 }
613 }
614 } catch ( e ) {
615 // Run error callbacks of jobs affected by this condition
616 for ( var j = 0; j < jobs.length; j++ ) {
617 if ( $.inArray( module, jobs[j].dependencies ) !== -1 ) {
618 if ( $.isFunction( jobs[j].error ) ) {
619 jobs[j].error();
620 }
621 jobs.splice( j, 1 );
622 j--;
623 }
624 }
625 }
626 }
627
628 /**
629 * Adds a dependencies to the queue with optional callbacks to be run
630 * when the dependencies are ready or fail
631 *
632 * @param dependencies string module name or array of string module names
633 * @param ready function callback to execute when all dependencies are ready
634 * @param error function callback to execute when any dependency fails
635 */
636 function request( dependencies, ready, error ) {
637 // Allow calling by single module name
638 if ( typeof dependencies === 'string' ) {
639 dependencies = [dependencies];
640 if ( dependencies[0] in registry ) {
641 // Cache repetitively accessed deep level object member
642 var regItemDeps = registry[dependencies[0]].dependencies,
643 // Cache to avoid looped access to length property
644 regItemDepLen = regItemDeps.length;
645 for ( var n = 0; n < regItemDepLen; n++ ) {
646 dependencies[dependencies.length] = regItemDeps[n];
647 }
648 }
649 }
650 // Add ready and error callbacks if they were given
651 if ( arguments.length > 1 ) {
652 jobs[jobs.length] = {
653 'dependencies': filter(
654 ['undefined', 'registered', 'loading', 'loaded'],
655 dependencies
656 ),
657 'ready': ready,
658 'error': error
659 };
660 }
661 // Queue up any dependencies that are undefined or registered
662 dependencies = filter( ['undefined', 'registered'], dependencies );
663 for ( var n = 0; n < dependencies.length; n++ ) {
664 if ( $.inArray( dependencies[n], queue ) === -1 ) {
665 queue[queue.length] = dependencies[n];
666 }
667 }
668 // Work the queue
669 mw.loader.work();
670 }
671
672 function sortQuery(o) {
673 var sorted = {}, key, a = [];
674 for ( key in o ) {
675 if ( o.hasOwnProperty( key ) ) {
676 a.push( key );
677 }
678 }
679 a.sort();
680 for ( key = 0; key < a.length; key++ ) {
681 sorted[a[key]] = o[a[key]];
682 }
683 return sorted;
684 }
685
686 /**
687 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
688 * to a query string of the form foo.bar,baz|bar.baz,quux
689 */
690 function buildModulesString( moduleMap ) {
691 var arr = [], p;
692 for ( var prefix in moduleMap ) {
693 p = prefix === '' ? '' : prefix + '.';
694 arr.push( p + moduleMap[prefix].join( ',' ) );
695 }
696 return arr.join( '|' );
697 }
698
699 /**
700 * Adds a script tag to the body, either using document.write or low-level DOM manipulation,
701 * depending on whether document-ready has occured yet.
702 *
703 * @param src String: URL to script, will be used as the src attribute in the script tag
704 * @param callback Function: Optional callback which will be run when the script is done
705 */
706 function addScript( src, callback ) {
707 var done = false, script;
708 if ( ready ) {
709 // jQuery's getScript method is NOT better than doing this the old-fashioned way
710 // because jQuery will eval the script's code, and errors will not have sane
711 // line numbers.
712 script = document.createElement( 'script' );
713 script.setAttribute( 'src', src );
714 script.setAttribute( 'type', 'text/javascript' );
715 if ( $.isFunction( callback ) ) {
716 // Attach handlers for all browsers -- this is based on jQuery.ajax
717 script.onload = script.onreadystatechange = function() {
718
719 if (
720 !done
721 && (
722 !script.readyState
723 || /loaded|complete/.test( script.readyState )
724 )
725 ) {
726
727 done = true;
728
729 // Handle memory leak in IE
730 script.onload = script.onreadystatechange = null;
731
732 callback();
733
734 if ( script.parentNode ) {
735 script.parentNode.removeChild( script );
736 }
737
738 // Dereference the script
739 script = undefined;
740 }
741 };
742 }
743 document.body.appendChild( script );
744 } else {
745 document.write( mw.html.element(
746 'script', { 'type': 'text/javascript', 'src': src }, ''
747 ) );
748 if ( $.isFunction( callback ) ) {
749 // Document.write is synchronous, so this is called when it's done
750 callback();
751 }
752 }
753 }
754
755 /**
756 * Asynchronously append a script tag to the end of the body
757 * that invokes load.php
758 * @param moduleMap {Object}: Module map, see buildModulesString()
759 * @param currReqBase {Object}: Object with other parameters (other than 'modules') to use in the request
760 * @param sourceLoadScript {String}: URL of load.php
761 */
762 function doRequest( moduleMap, currReqBase, sourceLoadScript ) {
763 var request = $.extend(
764 { 'modules': buildModulesString( moduleMap ) },
765 currReqBase
766 );
767 request = sortQuery( request );
768 // Asynchronously append a script tag to the end of the body
769 // Append &* to avoid triggering the IE6 extension check
770 addScript( sourceLoadScript + '?' + $.param( request ) + '&*' );
771 }
772
773 /* Public Methods */
774
775 /**
776 * Requests dependencies from server, loading and executing when things when ready.
777 */
778 this.work = function() {
779 // Build a list of request parameters common to all requests.
780 var reqBase = {
781 skin: mw.config.get( 'skin' ),
782 lang: mw.config.get( 'wgUserLanguage' ),
783 debug: mw.config.get( 'debug' )
784 },
785 // Split module batch by source and by group.
786 splits = {},
787 maxQueryLength = mw.config.get( 'wgResourceLoaderMaxQueryLength', -1 );
788
789 // Appends a list of modules from the queue to the batch
790 for ( var q = 0; q < queue.length; q++ ) {
791 // Only request modules which are undefined or registered
792 if ( !( queue[q] in registry ) || registry[queue[q]].state === 'registered' ) {
793 // Prevent duplicate entries
794 if ( $.inArray( queue[q], batch ) === -1 ) {
795 batch[batch.length] = queue[q];
796 // Mark registered modules as loading
797 if ( queue[q] in registry ) {
798 registry[queue[q]].state = 'loading';
799 }
800 }
801 }
802 }
803 // Early exit if there's nothing to load...
804 if ( !batch.length ) {
805 return;
806 }
807
808 // The queue has been processed into the batch, clear up the queue.
809 queue = [];
810
811 // Always order modules alphabetically to help reduce cache
812 // misses for otherwise identical content.
813 batch.sort();
814
815 // Split batch by source and by group.
816 for ( var b = 0; b < batch.length; b++ ) {
817 var bSource = registry[batch[b]].source,
818 bGroup = registry[batch[b]].group;
819 if ( !( bSource in splits ) ) {
820 splits[bSource] = {};
821 }
822 if ( !( bGroup in splits[bSource] ) ) {
823 splits[bSource][bGroup] = [];
824 }
825 var bSourceGroup = splits[bSource][bGroup];
826 bSourceGroup[bSourceGroup.length] = batch[b];
827 }
828
829 // Clear the batch - this MUST happen before we append any
830 // script elements to the body or it's possible that a script
831 // will be locally cached, instantly load, and work the batch
832 // again, all before we've cleared it causing each request to
833 // include modules which are already loaded.
834 batch = [];
835
836 var source, group, modules, maxVersion, sourceLoadScript;
837
838 for ( source in splits ) {
839
840 sourceLoadScript = sources[source].loadScript;
841
842 for ( group in splits[source] ) {
843
844 // Cache access to currently selected list of
845 // modules for this group from this source.
846 modules = splits[source][group];
847
848 // Calculate the highest timestamp
849 maxVersion = 0;
850 for ( var g = 0; g < modules.length; g++ ) {
851 if ( registry[modules[g]].version > maxVersion ) {
852 maxVersion = registry[modules[g]].version;
853 }
854 }
855
856 var currReqBase = $.extend( { 'version': formatVersionNumber( maxVersion ) }, reqBase ),
857 currReqBaseLength = $.param( currReqBase ).length,
858 moduleMap = {},
859 // We may need to split up the request to honor the query string length limit,
860 // so build it piece by piece.
861 l = currReqBaseLength + 9; // '&modules='.length == 9
862
863 moduleMap = {}; // { prefix: [ suffixes ] }
864
865 for ( var i = 0; i < modules.length; i++ ) {
866 // Determine how many bytes this module would add to the query string
867 var lastDotIndex = modules[i].lastIndexOf( '.' ),
868 // Note that these substr() calls work even if lastDotIndex == -1
869 prefix = modules[i].substr( 0, lastDotIndex ),
870 suffix = modules[i].substr( lastDotIndex + 1 ),
871 bytesAdded = prefix in moduleMap
872 ? suffix.length + 3 // '%2C'.length == 3
873 : modules[i].length + 3; // '%7C'.length == 3
874
875 // If the request would become too long, create a new one,
876 // but don't create empty requests
877 if ( maxQueryLength > 0 && !$.isEmptyObject( moduleMap ) && l + bytesAdded > maxQueryLength ) {
878 // This request would become too long, create a new one
879 // and fire off the old one
880 doRequest( moduleMap, currReqBase, sourceLoadScript );
881 moduleMap = {};
882 l = currReqBaseLength + 9;
883 }
884 if ( !( prefix in moduleMap ) ) {
885 moduleMap[prefix] = [];
886 }
887 moduleMap[prefix].push( suffix );
888 l += bytesAdded;
889 }
890 // If there's anything left in moduleMap, request that too
891 if ( !$.isEmptyObject( moduleMap ) ) {
892 doRequest( moduleMap, currReqBase, sourceLoadScript );
893 }
894 }
895 }
896 };
897
898 /**
899 * Register a source.
900 *
901 * @param id {String}: Short lowercase a-Z string representing a source, only used internally.
902 * @param props {Object}: Object containing only the loadScript property which is a url to
903 * the load.php location of the source.
904 * @return {Boolean}
905 */
906 this.addSource = function( id, props ) {
907 // Allow multiple additions
908 if ( typeof id === 'object' ) {
909 for ( var source in id ) {
910 mw.loader.addSource( source, id[source] );
911 }
912 return true;
913 }
914
915 if ( sources[id] !== undefined ) {
916 throw new Error( 'source already registered: ' + id );
917 }
918
919 sources[id] = props;
920
921 return true;
922 };
923
924 /**
925 * Registers a module, letting the system know about it and its
926 * properties. Startup modules contain calls to this function.
927 *
928 * @param module {String}: Module name
929 * @param version {Number}: Module version number as a timestamp (falls backs to 0)
930 * @param dependencies {String|Array|Function}: One string or array of strings of module
931 * names on which this module depends, or a function that returns that array.
932 * @param group {String}: Group which the module is in (optional, defaults to null)
933 * @param source {String}: Name of the source. Defaults to local.
934 */
935 this.register = function( module, version, dependencies, group, source ) {
936 // Allow multiple registration
937 if ( typeof module === 'object' ) {
938 for ( var m = 0; m < module.length; m++ ) {
939 // module is an array of module names
940 if ( typeof module[m] === 'string' ) {
941 mw.loader.register( module[m] );
942 // module is an array of arrays
943 } else if ( typeof module[m] === 'object' ) {
944 mw.loader.register.apply( mw.loader, module[m] );
945 }
946 }
947 return;
948 }
949 // Validate input
950 if ( typeof module !== 'string' ) {
951 throw new Error( 'module must be a string, not a ' + typeof module );
952 }
953 if ( registry[module] !== undefined ) {
954 throw new Error( 'module already implemented: ' + module );
955 }
956 // List the module as registered
957 registry[module] = {
958 'version': version !== undefined ? parseInt( version, 10 ) : 0,
959 'dependencies': [],
960 'group': typeof group === 'string' ? group : null,
961 'source': typeof source === 'string' ? source: 'local',
962 'state': 'registered'
963 };
964 if ( typeof dependencies === 'string' ) {
965 // Allow dependencies to be given as a single module name
966 registry[module].dependencies = [dependencies];
967 } else if ( typeof dependencies === 'object' || $.isFunction( dependencies ) ) {
968 // Allow dependencies to be given as an array of module names
969 // or a function which returns an array
970 registry[module].dependencies = dependencies;
971 }
972 };
973
974 /**
975 * Implements a module, giving the system a course of action to take
976 * upon loading. Results of a request for one or more modules contain
977 * calls to this function.
978 *
979 * All arguments are required.
980 *
981 * @param module String: Name of module
982 * @param script Mixed: Function of module code or String of URL to be used as the src
983 * attribute when adding a script element to the body
984 * @param style Object: Object of CSS strings keyed by media-type or Object of lists of URLs
985 * keyed by media-type
986 * @param msgs Object: List of key/value pairs to be passed through mw.messages.set
987 */
988 this.implement = function( module, script, style, msgs ) {
989 // Validate input
990 if ( typeof module !== 'string' ) {
991 throw new Error( 'module must be a string, not a ' + typeof module );
992 }
993 if ( !$.isFunction( script ) && !$.isArray( script ) ) {
994 throw new Error( 'script must be a function or an array, not a ' + typeof script );
995 }
996 if ( !$.isPlainObject( style ) ) {
997 throw new Error( 'style must be an object, not a ' + typeof style );
998 }
999 if ( !$.isPlainObject( msgs ) ) {
1000 throw new Error( 'msgs must be an object, not a ' + typeof msgs );
1001 }
1002 // Automatically register module
1003 if ( registry[module] === undefined ) {
1004 mw.loader.register( module );
1005 }
1006 // Check for duplicate implementation
1007 if ( registry[module] !== undefined && registry[module].script !== undefined ) {
1008 throw new Error( 'module already implemented: ' + module );
1009 }
1010 // Mark module as loaded
1011 registry[module].state = 'loaded';
1012 // Attach components
1013 registry[module].script = script;
1014 registry[module].style = style;
1015 registry[module].messages = msgs;
1016 // Execute or queue callback
1017 if ( compare(
1018 filter( ['ready'], registry[module].dependencies ),
1019 registry[module].dependencies ) )
1020 {
1021 execute( module );
1022 } else {
1023 request( module );
1024 }
1025 };
1026
1027 /**
1028 * Executes a function as soon as one or more required modules are ready
1029 *
1030 * @param dependencies string or array of strings of modules names the callback
1031 * dependencies to be ready before executing
1032 * @param ready function callback to execute when all dependencies are ready (optional)
1033 * @param error function callback to execute when if dependencies have a errors (optional)
1034 */
1035 this.using = function( dependencies, ready, error ) {
1036 var tod = typeof dependencies;
1037 // Validate input
1038 if ( tod !== 'object' && tod !== 'string' ) {
1039 throw new Error( 'dependencies must be a string or an array, not a ' + tod );
1040 }
1041 // Allow calling with a single dependency as a string
1042 if ( tod === 'string' ) {
1043 dependencies = [dependencies];
1044 }
1045 // Resolve entire dependency map
1046 dependencies = resolve( dependencies );
1047 // If all dependencies are met, execute ready immediately
1048 if ( compare( filter( ['ready'], dependencies ), dependencies ) ) {
1049 if ( $.isFunction( ready ) ) {
1050 ready();
1051 }
1052 }
1053 // If any dependencies have errors execute error immediately
1054 else if ( filter( ['error'], dependencies ).length ) {
1055 if ( $.isFunction( error ) ) {
1056 error();
1057 }
1058 }
1059 // Since some dependencies are not yet ready, queue up a request
1060 else {
1061 request( dependencies, ready, error );
1062 }
1063 };
1064
1065 /**
1066 * Loads an external script or one or more modules for future use
1067 *
1068 * @param modules mixed either the name of a module, array of modules,
1069 * or a URL of an external script or style
1070 * @param type string mime-type to use if calling with a URL of an
1071 * external script or style; acceptable values are "text/css" and
1072 * "text/javascript"; if no type is provided, text/javascript is assumed.
1073 */
1074 this.load = function( modules, type ) {
1075 // Validate input
1076 if ( typeof modules !== 'object' && typeof modules !== 'string' ) {
1077 throw new Error( 'modules must be a string or an array, not a ' + typeof modules );
1078 }
1079 // Allow calling with an external script or single dependency as a string
1080 if ( typeof modules === 'string' ) {
1081 // Support adding arbitrary external scripts
1082 if ( /^(https?:)?\/\//.test( modules ) ) {
1083 if ( type === 'text/css' ) {
1084 $( 'head' ).append( $( '<link/>', {
1085 rel: 'stylesheet',
1086 type: 'text/css',
1087 href: modules
1088 } ) );
1089 return true;
1090 } else if ( type === 'text/javascript' || type === undefined ) {
1091 addScript( modules );
1092 return true;
1093 }
1094 // Unknown type
1095 return false;
1096 }
1097 // Called with single module
1098 modules = [modules];
1099 }
1100 // Resolve entire dependency map
1101 modules = resolve( modules );
1102 // If all modules are ready, nothing dependency be done
1103 if ( compare( filter( ['ready'], modules ), modules ) ) {
1104 return true;
1105 }
1106 // If any modules have errors return false
1107 else if ( filter( ['error'], modules ).length ) {
1108 return false;
1109 }
1110 // Since some modules are not yet ready, queue up a request
1111 else {
1112 request( modules );
1113 return true;
1114 }
1115 };
1116
1117 /**
1118 * Changes the state of a module
1119 *
1120 * @param module string module name or object of module name/state pairs
1121 * @param state string state name
1122 */
1123 this.state = function( module, state ) {
1124 if ( typeof module === 'object' ) {
1125 for ( var m in module ) {
1126 mw.loader.state( m, module[m] );
1127 }
1128 return;
1129 }
1130 if ( !( module in registry ) ) {
1131 mw.loader.register( module );
1132 }
1133 registry[module].state = state;
1134 };
1135
1136 /**
1137 * Gets the version of a module
1138 *
1139 * @param module string name of module to get version for
1140 */
1141 this.getVersion = function( module ) {
1142 if ( module in registry && 'version' in registry[module] ) {
1143 return formatVersionNumber( registry[module].version );
1144 }
1145 return null;
1146 };
1147
1148 /**
1149 * @deprecated use mw.loader.getVersion() instead
1150 */
1151 this.version = function() {
1152 return mw.loader.getVersion.apply( mw.loader, arguments );
1153 };
1154
1155 /**
1156 * Gets the state of a module
1157 *
1158 * @param module string name of module to get state for
1159 */
1160 this.getState = function( module ) {
1161 if ( module in registry && 'state' in registry[module] ) {
1162 return registry[module].state;
1163 }
1164 return null;
1165 };
1166
1167 /**
1168 * Get names of all registered modules.
1169 *
1170 * @return {Array}
1171 */
1172 this.getModuleNames = function() {
1173 var names = $.map( registry, function( i, key ) {
1174 return key;
1175 } );
1176 return names;
1177 };
1178
1179 /**
1180 * For backwards-compatibility with Squid-cached pages. Loads mw.user
1181 */
1182 this.go = function() { mw.loader.load( 'mediawiki.user' ); };
1183
1184 /* Cache document ready status */
1185
1186 $(document).ready( function() { ready = true; } );
1187 } )();
1188
1189 /** HTML construction helper functions */
1190 this.html = new ( function () {
1191 var escapeCallback = function( s ) {
1192 switch ( s ) {
1193 case "'":
1194 return '&#039;';
1195 case '"':
1196 return '&quot;';
1197 case '<':
1198 return '&lt;';
1199 case '>':
1200 return '&gt;';
1201 case '&':
1202 return '&amp;';
1203 }
1204 };
1205
1206 /**
1207 * Escape a string for HTML. Converts special characters to HTML entities.
1208 * @param s The string to escape
1209 */
1210 this.escape = function( s ) {
1211 return s.replace( /['"<>&]/g, escapeCallback );
1212 };
1213
1214 /**
1215 * Wrapper object for raw HTML passed to mw.html.element().
1216 */
1217 this.Raw = function( value ) {
1218 this.value = value;
1219 };
1220
1221 /**
1222 * Wrapper object for CDATA element contents passed to mw.html.element()
1223 */
1224 this.Cdata = function( value ) {
1225 this.value = value;
1226 };
1227
1228 /**
1229 * Create an HTML element string, with safe escaping.
1230 *
1231 * @param name The tag name.
1232 * @param attrs An object with members mapping element names to values
1233 * @param contents The contents of the element. May be either:
1234 * - string: The string is escaped.
1235 * - null or undefined: The short closing form is used, e.g. <br/>.
1236 * - this.Raw: The value attribute is included without escaping.
1237 * - this.Cdata: The value attribute is included, and an exception is
1238 * thrown if it contains an illegal ETAGO delimiter.
1239 * See http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.3.2
1240 *
1241 * Example:
1242 * var h = mw.html;
1243 * return h.element( 'div', {},
1244 * new h.Raw( h.element( 'img', {src: '<'} ) ) );
1245 * Returns <div><img src="&lt;"/></div>
1246 */
1247 this.element = function( name, attrs, contents ) {
1248 var v, s = '<' + name;
1249 for ( var attrName in attrs ) {
1250 v = attrs[attrName];
1251 // Convert name=true, to name=name
1252 if ( v === true ) {
1253 v = attrName;
1254 // Skip name=false
1255 } else if ( v === false ) {
1256 continue;
1257 }
1258 s += ' ' + attrName + '="' + this.escape( '' + v ) + '"';
1259 }
1260 if ( contents === undefined || contents === null ) {
1261 // Self close tag
1262 s += '/>';
1263 return s;
1264 }
1265 // Regular open tag
1266 s += '>';
1267 switch ( typeof contents ) {
1268 case 'string':
1269 // Escaped
1270 s += this.escape( contents );
1271 break;
1272 case 'number':
1273 case 'boolean':
1274 // Convert to string
1275 s += '' + contents;
1276 break;
1277 default:
1278 if ( contents instanceof this.Raw ) {
1279 // Raw HTML inclusion
1280 s += contents.value;
1281 } else if ( contents instanceof this.Cdata ) {
1282 // CDATA
1283 if ( /<\/[a-zA-z]/.test( contents.value ) ) {
1284 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
1285 }
1286 s += contents.value;
1287 } else {
1288 throw new Error( 'mw.html.element: Invalid type of contents' );
1289 }
1290 }
1291 s += '</' + name + '>';
1292 return s;
1293 };
1294 } )();
1295
1296 /* Extension points */
1297
1298 this.legacy = {};
1299
1300 } )( jQuery );
1301
1302 // Alias $j to jQuery for backwards compatibility
1303 window.$j = jQuery;
1304
1305 // Auto-register from pre-loaded startup scripts
1306 if ( typeof startUp !== 'undefined' && jQuery.isFunction( startUp ) ) {
1307 startUp();
1308 delete startUp;
1309 }