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