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