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