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