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