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