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