Fixes r78104 much better than r78344 did. By adding jquery.cookie to the loading...
[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. It's uniqueness should not be depended on.
305 *
306 * @return string random set of 32 alpha-numeric characters
307 */
308 function generateSessionId() {
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 the current user's name or a random session ID automatically generated and kept in
329 * a cookie.
330 *
331 * @return string user name or random session ID
332 */
333 this.sessionId = function () {
334 var name = that.name();
335 if ( name ) {
336 return name;
337 }
338 var sessionId = $.cookie( 'mediaWiki.user.sessionId' );
339 if ( typeof sessionId == 'undefined' || sessionId == null ) {
340 sessionId = generateSessionId();
341 $.cookie( 'mediaWiki.user.sessionId', sessionId, { 'expires': 30, 'path': '/' } );
342 }
343 return sessionId;
344 };
345 }
346
347 /* Public Members */
348
349 /*
350 * Dummy function which in debug mode can be replaced with a function that
351 * does something clever
352 */
353 this.log = function() { };
354
355 /*
356 * Make the Map-class publicly available
357 */
358 this.Map = Map;
359
360 /*
361 * List of configuration values
362 *
363 * In legacy mode the values this object wraps will be in the global space
364 */
365 this.config = new this.Map( LEGACY_GLOBALS );
366
367 /*
368 * Information about the current user
369 */
370 this.user = new User();
371
372 /*
373 * Localization system
374 */
375 this.messages = new this.Map();
376
377 /* Public Methods */
378
379 /**
380 * Gets a message object, similar to wfMessage()
381 *
382 * @param key string Key of message to get
383 * @param parameters mixed First argument in a list of variadic arguments, each a parameter for $
384 * replacement
385 */
386 this.message = function( key, parameters ) {
387 // Support variadic arguments
388 if ( typeof parameters !== 'undefined' ) {
389 parameters = $.makeArray( arguments );
390 parameters.shift();
391 } else {
392 parameters = [];
393 }
394 return new Message( mediaWiki.messages, key, parameters );
395 };
396
397 /**
398 * Gets a message string, similar to wfMsg()
399 *
400 * @param key string Key of message to get
401 * @param parameters mixed First argument in a list of variadic arguments, each a parameter for $
402 * replacement
403 */
404 this.msg = function( key, parameters ) {
405 return mediaWiki.message.apply( mediaWiki.message, arguments ).toString();
406 };
407
408 /**
409 * Client-side module loader which integrates with the MediaWiki ResourceLoader
410 */
411 this.loader = new ( function() {
412
413 /* Private Members */
414
415 /**
416 * Mapping of registered modules
417 *
418 * The jquery module is pre-registered, because it must have already
419 * been provided for this object to have been built, and in debug mode
420 * jquery would have been provided through a unique loader request,
421 * making it impossible to hold back registration of jquery until after
422 * mediawiki.
423 *
424 * Format:
425 * {
426 * 'moduleName': {
427 * 'dependencies': ['required module', 'required module', ...], (or) function() {}
428 * 'state': 'registered', 'loading', 'loaded', 'ready', or 'error'
429 * 'script': function() {},
430 * 'style': 'css code string',
431 * 'messages': { 'key': 'value' },
432 * 'version': ############## (unix timestamp)
433 * }
434 * }
435 */
436 var registry = {};
437 // List of modules which will be loaded as when ready
438 var batch = [];
439 // List of modules to be loaded
440 var queue = [];
441 // List of callback functions waiting for modules to be ready to be called
442 var jobs = [];
443 // Flag indicating that requests should be suspended
444 var suspended = true;
445 // Flag inidicating that document ready has occured
446 var ready = false;
447
448 /* Private Methods */
449
450 function compare( a, b ) {
451 if ( a.length != b.length ) {
452 return false;
453 }
454 for ( var i = 0; i < b.length; i++ ) {
455 if ( $.isArray( a[i] ) ) {
456 if ( !compare( a[i], b[i] ) ) {
457 return false;
458 }
459 }
460 if ( a[i] !== b[i] ) {
461 return false;
462 }
463 }
464 return true;
465 }
466
467 /**
468 * Generates an ISO8601 "basic" string from a UNIX timestamp
469 */
470 function formatVersionNumber( timestamp ) {
471 function pad( a, b, c ) {
472 return [a < 10 ? '0' + a : a, b < 10 ? '0' + b : b, c < 10 ? '0' + c : c].join( '' );
473 }
474 var d = new Date();
475 d.setTime( timestamp * 1000 );
476 return [
477 pad( d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate() ), 'T',
478 pad( d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds() ), 'Z'
479 ].join( '' );
480 }
481
482 /**
483 * Recursively resolves dependencies and detects circular references
484 */
485 function recurse( module, resolved, unresolved ) {
486 if ( typeof registry[module] === 'undefined' ) {
487 throw new Error( 'Unknown dependency: ' + module );
488 }
489 // Resolves dynamic loader function and replaces it with its own results
490 if ( typeof registry[module].dependencies === 'function' ) {
491 registry[module].dependencies = registry[module].dependencies();
492 // Ensures the module's dependencies are always in an array
493 if ( typeof registry[module].dependencies !== 'object' ) {
494 registry[module].dependencies = [registry[module].dependencies];
495 }
496 }
497 // Tracks down dependencies
498 for ( var n = 0; n < registry[module].dependencies.length; n++ ) {
499 if ( $.inArray( registry[module].dependencies[n], resolved ) === -1 ) {
500 if ( $.inArray( registry[module].dependencies[n], unresolved ) !== -1 ) {
501 throw new Error(
502 'Circular reference detected: ' + module +
503 ' -> ' + registry[module].dependencies[n]
504 );
505 }
506 recurse( registry[module].dependencies[n], resolved, unresolved );
507 }
508 }
509 resolved[resolved.length] = module;
510 unresolved.splice( $.inArray( module, unresolved ), 1 );
511 }
512
513 /**
514 * Gets a list of module names that a module depends on in their proper dependency order
515 *
516 * @param module string module name or array of string module names
517 * @return list of dependencies
518 * @throws Error if circular reference is detected
519 */
520 function resolve( module, resolved, unresolved ) {
521 // Allow calling with an array of module names
522 if ( typeof module === 'object' ) {
523 var modules = [];
524 for ( var m = 0; m < module.length; m++ ) {
525 var dependencies = resolve( module[m] );
526 for ( var n = 0; n < dependencies.length; n++ ) {
527 modules[modules.length] = dependencies[n];
528 }
529 }
530 return modules;
531 } else if ( typeof module === 'string' ) {
532 // Undefined modules have no dependencies
533 if ( !( module in registry ) ) {
534 return [];
535 }
536 var resolved = [];
537 recurse( module, resolved, [] );
538 return resolved;
539 }
540 throw new Error( 'Invalid module argument: ' + module );
541 }
542
543 /**
544 * Narrows a list of module names down to those matching a specific
545 * state. Possible states are 'undefined', 'registered', 'loading',
546 * 'loaded', or 'ready'
547 *
548 * @param states string or array of strings of module states to filter by
549 * @param modules array list of module names to filter (optional, all modules
550 * will be used by default)
551 * @return array list of filtered module names
552 */
553 function filter( states, modules ) {
554 // Allow states to be given as a string
555 if ( typeof states === 'string' ) {
556 states = [states];
557 }
558 // If called without a list of modules, build and use a list of all modules
559 var list = [];
560 if ( typeof modules === 'undefined' ) {
561 modules = [];
562 for ( module in registry ) {
563 modules[modules.length] = module;
564 }
565 }
566 // Build a list of modules which are in one of the specified states
567 for ( var s = 0; s < states.length; s++ ) {
568 for ( var m = 0; m < modules.length; m++ ) {
569 if ( typeof registry[modules[m]] === 'undefined' ) {
570 // Module does not exist
571 if ( states[s] == 'undefined' ) {
572 // OK, undefined
573 list[list.length] = modules[m];
574 }
575 } else {
576 // Module exists, check state
577 if ( registry[modules[m]].state === states[s] ) {
578 // OK, correct state
579 list[list.length] = modules[m];
580 }
581 }
582 }
583 }
584 return list;
585 }
586
587 /**
588 * Executes a loaded module, making it ready to use
589 *
590 * @param module string module name to execute
591 */
592 function execute( module ) {
593 if ( typeof registry[module] === 'undefined' ) {
594 throw new Error( 'Module has not been registered yet: ' + module );
595 } else if ( registry[module].state === 'registered' ) {
596 throw new Error( 'Module has not been requested from the server yet: ' + module );
597 } else if ( registry[module].state === 'loading' ) {
598 throw new Error( 'Module has not completed loading yet: ' + module );
599 } else if ( registry[module].state === 'ready' ) {
600 throw new Error( 'Module has already been loaded: ' + module );
601 }
602 // Add style sheet to document
603 if ( typeof registry[module].style === 'string' && registry[module].style.length ) {
604 $( 'head' )
605 .append( mediaWiki.html.element( 'style',
606 { type: "text/css" },
607 new mediaWiki.html.Cdata( registry[module].style )
608 ) );
609 } else if ( typeof registry[module].style === 'object'
610 && !( registry[module].style instanceof Array ) )
611 {
612 for ( var media in registry[module].style ) {
613 $( 'head' ).append( mediaWiki.html.element( 'style',
614 { type: 'text/css', media: media },
615 new mediaWiki.html.Cdata( registry[module].style[media] )
616 ) );
617 }
618 }
619 // Add localizations to message system
620 if ( typeof registry[module].messages === 'object' ) {
621 mediaWiki.messages.set( registry[module].messages );
622 }
623 // Execute script
624 try {
625 registry[module].script();
626 registry[module].state = 'ready';
627 // Run jobs who's dependencies have just been met
628 for ( var j = 0; j < jobs.length; j++ ) {
629 if ( compare(
630 filter( 'ready', jobs[j].dependencies ),
631 jobs[j].dependencies ) )
632 {
633 if ( typeof jobs[j].ready === 'function' ) {
634 jobs[j].ready();
635 }
636 jobs.splice( j, 1 );
637 j--;
638 }
639 }
640 // Execute modules who's dependencies have just been met
641 for ( r in registry ) {
642 if ( registry[r].state == 'loaded' ) {
643 if ( compare(
644 filter( ['ready'], registry[r].dependencies ),
645 registry[r].dependencies ) )
646 {
647 execute( r );
648 }
649 }
650 }
651 } catch ( e ) {
652 mediaWiki.log( 'Exception thrown by ' + module + ': ' + e.message );
653 mediaWiki.log( e );
654 registry[module].state = 'error';
655 // Run error callbacks of jobs affected by this condition
656 for ( var j = 0; j < jobs.length; j++ ) {
657 if ( $.inArray( module, jobs[j].dependencies ) !== -1 ) {
658 if ( typeof jobs[j].error === 'function' ) {
659 jobs[j].error();
660 }
661 jobs.splice( j, 1 );
662 j--;
663 }
664 }
665 }
666 }
667
668 /**
669 * Adds a dependencies to the queue with optional callbacks to be run
670 * when the dependencies are ready or fail
671 *
672 * @param dependencies string module name or array of string module names
673 * @param ready function callback to execute when all dependencies are ready
674 * @param error function callback to execute when any dependency fails
675 */
676 function request( dependencies, ready, error ) {
677 // Allow calling by single module name
678 if ( typeof dependencies === 'string' ) {
679 dependencies = [dependencies];
680 if ( dependencies[0] in registry ) {
681 for ( var n = 0; n < registry[dependencies[0]].dependencies.length; n++ ) {
682 dependencies[dependencies.length] =
683 registry[dependencies[0]].dependencies[n];
684 }
685 }
686 }
687 // Add ready and error callbacks if they were given
688 if ( arguments.length > 1 ) {
689 jobs[jobs.length] = {
690 'dependencies': filter(
691 ['undefined', 'registered', 'loading', 'loaded'],
692 dependencies ),
693 'ready': ready,
694 'error': error
695 };
696 }
697 // Queue up any dependencies that are undefined or registered
698 dependencies = filter( ['undefined', 'registered'], dependencies );
699 for ( var n = 0; n < dependencies.length; n++ ) {
700 if ( $.inArray( dependencies[n], queue ) === -1 ) {
701 queue[queue.length] = dependencies[n];
702 }
703 }
704 // Work the queue
705 mediaWiki.loader.work();
706 }
707
708 function sortQuery(o) {
709 var sorted = {}, key, a = [];
710 for ( key in o ) {
711 if ( o.hasOwnProperty( key ) ) {
712 a.push( key );
713 }
714 }
715 a.sort();
716 for ( key = 0; key < a.length; key++ ) {
717 sorted[a[key]] = o[a[key]];
718 }
719 return sorted;
720 }
721
722 /* Public Methods */
723
724 /**
725 * Requests dependencies from server, loading and executing when things when ready.
726 */
727 this.work = function() {
728 // Appends a list of modules to the batch
729 for ( var q = 0; q < queue.length; q++ ) {
730 // Only request modules which are undefined or registered
731 if ( !( queue[q] in registry ) || registry[queue[q]].state == 'registered' ) {
732 // Prevent duplicate entries
733 if ( $.inArray( queue[q], batch ) === -1 ) {
734 batch[batch.length] = queue[q];
735 // Mark registered modules as loading
736 if ( queue[q] in registry ) {
737 registry[queue[q]].state = 'loading';
738 }
739 }
740 }
741 }
742 // Clean up the queue
743 queue = [];
744 // After document ready, handle the batch
745 if ( !suspended && batch.length ) {
746 // Always order modules alphabetically to help reduce cache
747 // misses for otherwise identical content
748 batch.sort();
749 // Build a list of request parameters
750 var base = {
751 'skin': mediaWiki.config.get( 'skin' ),
752 'lang': mediaWiki.config.get( 'wgUserLanguage' ),
753 'debug': mediaWiki.config.get( 'debug' )
754 };
755 // Extend request parameters with a list of modules in the batch
756 var requests = [];
757 // Split into groups
758 var groups = {};
759 for ( var b = 0; b < batch.length; b++ ) {
760 var group = registry[batch[b]].group;
761 if ( !( group in groups ) ) {
762 groups[group] = [];
763 }
764 groups[group][groups[group].length] = batch[b];
765 }
766 for ( var group in groups ) {
767 // Calculate the highest timestamp
768 var version = 0;
769 for ( var g = 0; g < groups[group].length; g++ ) {
770 if ( registry[groups[group][g]].version > version ) {
771 version = registry[groups[group][g]].version;
772 }
773 }
774 requests[requests.length] = $.extend(
775 { 'modules': groups[group].join( '|' ), 'version': formatVersionNumber( version ) }, base
776 );
777 }
778 // Clear the batch - this MUST happen before we append the
779 // script element to the body or it's possible that the script
780 // will be locally cached, instantly load, and work the batch
781 // again, all before we've cleared it causing each request to
782 // include modules which are already loaded
783 batch = [];
784 // Asynchronously append a script tag to the end of the body
785 function request() {
786 var html = '';
787 for ( var r = 0; r < requests.length; r++ ) {
788 requests[r] = sortQuery( requests[r] );
789 // Build out the HTML
790 var src = mediaWiki.config.get( 'wgLoadScript' ) + '?' + $.param( requests[r] );
791 html += mediaWiki.html.element( 'script',
792 { type: 'text/javascript', src: src }, '' );
793 }
794 return html;
795 }
796 // Load asynchronously after doumument ready
797 if ( ready ) {
798 setTimeout( function() { $( 'body' ).append( request() ); }, 0 )
799 } else {
800 document.write( request() );
801 }
802 }
803 };
804
805 /**
806 * Registers a module, letting the system know about it and its
807 * dependencies. loader.js files contain calls to this function.
808 */
809 this.register = function( module, version, dependencies, group ) {
810 // Allow multiple registration
811 if ( typeof module === 'object' ) {
812 for ( var m = 0; m < module.length; m++ ) {
813 if ( typeof module[m] === 'string' ) {
814 mediaWiki.loader.register( module[m] );
815 } else if ( typeof module[m] === 'object' ) {
816 mediaWiki.loader.register.apply( mediaWiki.loader, module[m] );
817 }
818 }
819 return;
820 }
821 // Validate input
822 if ( typeof module !== 'string' ) {
823 throw new Error( 'module must be a string, not a ' + typeof module );
824 }
825 if ( typeof registry[module] !== 'undefined' ) {
826 throw new Error( 'module already implemeneted: ' + module );
827 }
828 // List the module as registered
829 registry[module] = {
830 'state': 'registered',
831 'group': typeof group === 'string' ? group : null,
832 'dependencies': [],
833 'version': typeof version !== 'undefined' ? parseInt( version ) : 0
834 };
835 if ( typeof dependencies === 'string' ) {
836 // Allow dependencies to be given as a single module name
837 registry[module].dependencies = [dependencies];
838 } else if ( typeof dependencies === 'object' || typeof dependencies === 'function' ) {
839 // Allow dependencies to be given as an array of module names
840 // or a function which returns an array
841 registry[module].dependencies = dependencies;
842 }
843 };
844
845 /**
846 * Implements a module, giving the system a course of action to take
847 * upon loading. Results of a request for one or more modules contain
848 * calls to this function.
849 */
850 this.implement = function( module, script, style, localization ) {
851 // Automatically register module
852 if ( typeof registry[module] === 'undefined' ) {
853 mediaWiki.loader.register( module );
854 }
855 // Validate input
856 if ( typeof script !== 'function' ) {
857 throw new Error( 'script must be a function, not a ' + typeof script );
858 }
859 if ( typeof style !== 'undefined'
860 && typeof style !== 'string'
861 && typeof style !== 'object' )
862 {
863 throw new Error( 'style must be a string or object, not a ' + typeof style );
864 }
865 if ( typeof localization !== 'undefined'
866 && typeof localization !== 'object' )
867 {
868 throw new Error( 'localization must be an object, not a ' + typeof localization );
869 }
870 if ( typeof registry[module] !== 'undefined'
871 && typeof registry[module].script !== 'undefined' )
872 {
873 throw new Error( 'module already implemeneted: ' + module );
874 }
875 // Mark module as loaded
876 registry[module].state = 'loaded';
877 // Attach components
878 registry[module].script = script;
879 if ( typeof style === 'string'
880 || typeof style === 'object' && !( style instanceof Array ) )
881 {
882 registry[module].style = style;
883 }
884 if ( typeof localization === 'object' ) {
885 registry[module].messages = localization;
886 }
887 // Execute or queue callback
888 if ( compare(
889 filter( ['ready'], registry[module].dependencies ),
890 registry[module].dependencies ) )
891 {
892 execute( module );
893 } else {
894 request( module );
895 }
896 };
897
898 /**
899 * Executes a function as soon as one or more required modules are ready
900 *
901 * @param dependencies string or array of strings of modules names the callback
902 * dependencies to be ready before
903 * executing
904 * @param ready function callback to execute when all dependencies are ready (optional)
905 * @param error function callback to execute when if dependencies have a errors (optional)
906 */
907 this.using = function( dependencies, ready, error ) {
908 // Validate input
909 if ( typeof dependencies !== 'object' && typeof dependencies !== 'string' ) {
910 throw new Error( 'dependencies must be a string or an array, not a ' +
911 typeof dependencies )
912 }
913 // Allow calling with a single dependency as a string
914 if ( typeof dependencies === 'string' ) {
915 dependencies = [dependencies];
916 }
917 // Resolve entire dependency map
918 dependencies = resolve( dependencies );
919 // If all dependencies are met, execute ready immediately
920 if ( compare( filter( ['ready'], dependencies ), dependencies ) ) {
921 if ( typeof ready === 'function' ) {
922 ready();
923 }
924 }
925 // If any dependencies have errors execute error immediately
926 else if ( filter( ['error'], dependencies ).length ) {
927 if ( typeof error === 'function' ) {
928 error();
929 }
930 }
931 // Since some dependencies are not yet ready, queue up a request
932 else {
933 request( dependencies, ready, error );
934 }
935 };
936
937 /**
938 * Loads an external script or one or more modules for future use
939 *
940 * @param modules mixed either the name of a module, array of modules,
941 * or a URL of an external script or style
942 * @param type string mime-type to use if calling with a URL of an
943 * external script or style; acceptable values are "text/css" and
944 * "text/javascript"; if no type is provided, text/javascript is
945 * assumed
946 */
947 this.load = function( modules, type ) {
948 // Validate input
949 if ( typeof modules !== 'object' && typeof modules !== 'string' ) {
950 throw new Error( 'dependencies must be a string or an array, not a ' +
951 typeof dependencies )
952 }
953 // Allow calling with an external script or single dependency as a string
954 if ( typeof modules === 'string' ) {
955 // Support adding arbitrary external scripts
956 if ( modules.substr( 0, 7 ) == 'http://'
957 || modules.substr( 0, 8 ) == 'https://' )
958 {
959 if ( type === 'text/css' ) {
960 $( 'head' )
961 .append( $( '<link rel="stylesheet" type="text/css" />' )
962 .attr( 'href', modules ) );
963 return true;
964 } else if ( type === 'text/javascript' || typeof type === 'undefined' ) {
965 var script = mediaWiki.html.element( 'script',
966 { type: 'text/javascript', src: modules }, '' );
967 if ( ready ) {
968 $( 'body' ).append( script );
969 } else {
970 document.write( script );
971 }
972 return true;
973 }
974 // Unknown type
975 return false;
976 }
977 // Called with single module
978 modules = [modules];
979 }
980 // Resolve entire dependency map
981 modules = resolve( modules );
982 // If all modules are ready, nothing dependency be done
983 if ( compare( filter( ['ready'], modules ), modules ) ) {
984 return true;
985 }
986 // If any modules have errors return false
987 else if ( filter( ['error'], modules ).length ) {
988 return false;
989 }
990 // Since some modules are not yet ready, queue up a request
991 else {
992 request( modules );
993 return true;
994 }
995 };
996
997 /**
998 * Flushes the request queue and begin executing load requests on demand
999 */
1000 this.go = function() {
1001 suspended = false;
1002 mediaWiki.loader.work();
1003 };
1004
1005 /**
1006 * Changes the state of a module
1007 *
1008 * @param module string module name or object of module name/state pairs
1009 * @param state string state name
1010 */
1011 this.state = function( module, state ) {
1012 if ( typeof module === 'object' ) {
1013 for ( var m in module ) {
1014 mediaWiki.loader.state( m, module[m] );
1015 }
1016 return;
1017 }
1018 if ( !( module in registry ) ) {
1019 mediaWiki.loader.register( module );
1020 }
1021 registry[module].state = state;
1022 };
1023
1024 /**
1025 * Gets the version of a module
1026 *
1027 * @param module string name of module to get version for
1028 */
1029 this.version = function( module ) {
1030 if ( module in registry && 'version' in registry[module] ) {
1031 return formatVersionNumber( registry[module].version );
1032 }
1033 return null;
1034 };
1035
1036 /* Cache document ready status */
1037
1038 $(document).ready( function() { ready = true; } );
1039 } )();
1040
1041 /** HTML construction helper functions */
1042 this.html = new ( function () {
1043 function escapeCallback( s ) {
1044 switch ( s ) {
1045 case "'":
1046 return '&#039;';
1047 case '"':
1048 return '&quot;';
1049 case '<':
1050 return '&lt;';
1051 case '>':
1052 return '&gt;';
1053 case '&':
1054 return '&amp;';
1055 }
1056 }
1057
1058 /**
1059 * Escape a string for HTML. Converts special characters to HTML entities.
1060 * @param s The string to escape
1061 */
1062 this.escape = function( s ) {
1063 return s.replace( /['"<>&]/g, escapeCallback );
1064 };
1065
1066 /**
1067 * Wrapper object for raw HTML passed to mediaWiki.html.element().
1068 */
1069 this.Raw = function( value ) {
1070 this.value = value;
1071 };
1072
1073 /**
1074 * Wrapper object for CDATA element contents passed to mediaWiki.html.element()
1075 */
1076 this.Cdata = function( value ) {
1077 this.value = value;
1078 };
1079
1080 /**
1081 * Create an HTML element string, with safe escaping.
1082 *
1083 * @param name The tag name.
1084 * @param attrs An object with members mapping element names to values
1085 * @param contents The contents of the element. May be either:
1086 * - string: The string is escaped.
1087 * - null or undefined: The short closing form is used, e.g. <br/>.
1088 * - this.Raw: The value attribute is included without escaping.
1089 * - this.Cdata: The value attribute is included, and an exception is
1090 * thrown if it contains an illegal ETAGO delimiter.
1091 * See http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.3.2
1092 *
1093 * Example:
1094 * var h = mediaWiki.html;
1095 * return h.element( 'div', {},
1096 * new h.Raw( h.element( 'img', {src: '<'} ) ) );
1097 * Returns <div><img src="&lt;"/></div>
1098 */
1099 this.element = function( name, attrs, contents ) {
1100 var s = '<' + name;
1101 for ( attrName in attrs ) {
1102 s += ' ' + attrName + '="' + this.escape( attrs[attrName] ) + '"';
1103 }
1104 if ( typeof contents == 'undefined' || contents === null ) {
1105 // Self close tag
1106 s += '/>';
1107 return s;
1108 }
1109 // Regular open tag
1110 s += '>';
1111 if (typeof contents === 'string') {
1112 // Escaped
1113 s += this.escape( contents );
1114 } else if ( contents instanceof this.Raw ) {
1115 // Raw HTML inclusion
1116 s += contents.value;
1117 } else if ( contents instanceof this.Cdata ) {
1118 // CDATA
1119 if ( /<\/[a-zA-z]/.test( contents.value ) ) {
1120 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
1121 }
1122 s += contents.value;
1123 } else {
1124 throw new Error( 'mw.html.element: Invalid type of contents' );
1125 }
1126 s += '</' + name + '>';
1127 return s;
1128 };
1129 } )();
1130
1131
1132 /* Extension points */
1133
1134 this.legacy = {};
1135
1136 } )( jQuery );
1137
1138 /* Auto-register from pre-loaded startup scripts */
1139
1140 if ( typeof startUp === 'function' ) {
1141 startUp();
1142 delete startUp;
1143 }
1144
1145 // Add jQuery Cookie to initial payload (used in mediaWiki.user)
1146 mediaWiki.loader.load( 'jquery.cookie' );
1147
1148 // Alias $j to jQuery for backwards compatibility
1149 window.$j = jQuery;
1150 window.mw = mediaWiki;