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