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