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