Fixes regression in r88125 - if batch is empty we should bail early
[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 /* Private Members */
131
132 // List of messages that have been requested to be loaded
133 var messageQueue = {};
134
135 /* Prototypes */
136
137 /**
138 * An object which allows single and multiple get/set/exists functionality
139 * on a list of key / value pairs.
140 *
141 * @param {boolean} global Whether to get/set/exists values on the window
142 * object or a private object
143 */
144 function Map( global ) {
145 this.values = ( global === true ) ? window : {};
146 }
147
148 /**
149 * Gets the value of a key, or a list of key/value pairs for an array of keys.
150 *
151 * If called with no arguments, all values will be returned.
152 *
153 * @param selection mixed Key or array of keys to get values for
154 * @param fallback mixed Value to use in case key(s) do not exist (optional)
155 */
156 Map.prototype.get = function( selection, fallback ) {
157 if ( typeof selection === 'object' ) {
158 selection = $.makeArray( selection );
159 var results = {};
160 for ( var i = 0; i < selection.length; i++ ) {
161 results[selection[i]] = this.get( selection[i], fallback );
162 }
163 return results;
164 } else if ( typeof selection === 'string' ) {
165 if ( typeof this.values[selection] === 'undefined' ) {
166 if ( typeof fallback !== 'undefined' ) {
167 return fallback;
168 }
169 return null;
170 }
171 return this.values[selection];
172 }
173 return this.values;
174 };
175
176 /**
177 * Sets one or multiple key/value pairs.
178 *
179 * @param selection mixed Key or object of key/value pairs to set
180 * @param value mixed Value to set (optional, only in use when key is a string)
181 */
182 Map.prototype.set = function( selection, value ) {
183 if ( typeof selection === 'object' ) {
184 for ( var s in selection ) {
185 this.values[s] = selection[s];
186 }
187 return true;
188 } else if ( typeof selection === 'string' && typeof value !== 'undefined' ) {
189 this.values[selection] = value;
190 return true;
191 }
192 return false;
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 * Dummy placeholder. Initiated in startUp module as a new instance of mw.Map().
504 * If $wgLegacyJavaScriptGlobals is true, this Map will have its values
505 * in the global window object.
506 */
507 this.config = null;
508
509 /*
510 * Information about the current user
511 */
512 this.user = new User();
513
514 /*
515 * Localization system
516 */
517 this.messages = new this.Map();
518
519 /* Public Methods */
520
521 /**
522 * Gets a message object, similar to wfMessage()
523 *
524 * @param key string Key of message to get
525 * @param parameters mixed First argument in a list of variadic arguments, each a parameter for $
526 * replacement
527 */
528 this.message = function( key, parameters ) {
529 // Support variadic arguments
530 if ( typeof parameters !== 'undefined' ) {
531 parameters = $.makeArray( arguments );
532 parameters.shift();
533 } else {
534 parameters = [];
535 }
536 return new Message( mw.messages, key, parameters );
537 };
538
539 /**
540 * Gets a message string, similar to wfMsg()
541 *
542 * @param key string Key of message to get
543 * @param parameters mixed First argument in a list of variadic arguments, each a parameter for $
544 * replacement
545 */
546 this.msg = function( key, parameters ) {
547 return mw.message.apply( mw.message, arguments ).toString();
548 };
549
550 /**
551 * Client-side module loader which integrates with the MediaWiki ResourceLoader
552 */
553 this.loader = new ( function() {
554
555 /* Private Members */
556
557 /**
558 * Mapping of registered modules
559 *
560 * The jquery module is pre-registered, because it must have already
561 * been provided for this object to have been built, and in debug mode
562 * jquery would have been provided through a unique loader request,
563 * making it impossible to hold back registration of jquery until after
564 * mediawiki.
565 *
566 * Format:
567 * {
568 * 'moduleName': {
569 * 'dependencies': ['required module', 'required module', ...], (or) function() {}
570 * 'state': 'registered', 'loading', 'loaded', 'ready', or 'error'
571 * 'script': function() {},
572 * 'style': 'css code string',
573 * 'messages': { 'key': 'value' },
574 * 'version': ############## (unix timestamp)
575 * }
576 * }
577 */
578 var registry = {};
579 // List of modules which will be loaded as when ready
580 var batch = [];
581 // List of modules to be loaded
582 var queue = [];
583 // List of callback functions waiting for modules to be ready to be called
584 var jobs = [];
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, callback ) {
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 styles
746 if ( $.isPlainObject( registry[module].style ) ) {
747 for ( var media in registry[module].style ) {
748 var style = registry[module].style[media];
749 if ( $.isArray( style ) ) {
750 for ( var i = 0; i < style.length; i++ ) {
751 $marker.before( mw.html.element( 'link', {
752 'type': 'text/css',
753 'rel': 'stylesheet',
754 'href': style[i]
755 } ) );
756 }
757 } else if ( typeof style === 'string' ) {
758 $marker.before( mw.html.element(
759 'style',
760 { 'type': 'text/css', 'media': media },
761 new mw.html.Cdata( style )
762 ) );
763 }
764 }
765 }
766 // Add localizations to message system
767 if ( $.isPlainObject( registry[module].messages ) ) {
768 mw.messages.set( registry[module].messages );
769 }
770 // Execute script
771 try {
772 var script = registry[module].script;
773 if ( $.isArray( script ) ) {
774 var done = 0;
775 for ( var i = 0; i < script.length; i++ ) {
776 registry[module].state = 'loading';
777 addScript( script[i], function() {
778 if ( ++done == script.length ) {
779 registry[module].state = 'ready';
780 handlePending();
781 if ( $.isFunction( callback ) ) {
782 callback();
783 }
784 }
785 } );
786 }
787 } else if ( $.isFunction( script ) ) {
788 script( jQuery );
789 registry[module].state = 'ready';
790 handlePending();
791 if ( $.isFunction( callback ) ) {
792 callback();
793 }
794 }
795 } catch ( e ) {
796 // This needs to NOT use mw.log because these errors are common in production mode
797 // and not in debug mode, such as when a symbol that should be global isn't exported
798 if ( window.console && typeof window.console.log === 'function' ) {
799 console.log( _fn + 'Exception thrown by ' + module + ': ' + e.message );
800 console.log( e );
801 }
802 registry[module].state = 'error';
803 }
804 }
805
806 /**
807 * Automatically executes jobs and modules which are pending with satistifed dependencies.
808 *
809 * This is used when dependencies are satisfied, such as when a module is executed.
810 */
811 function handlePending() {
812 try {
813 // Run jobs who's dependencies have just been met
814 for ( var j = 0; j < jobs.length; j++ ) {
815 if ( compare(
816 filter( 'ready', jobs[j].dependencies ),
817 jobs[j].dependencies ) )
818 {
819 if ( $.isFunction( jobs[j].ready ) ) {
820 jobs[j].ready();
821 }
822 jobs.splice( j, 1 );
823 j--;
824 }
825 }
826 // Execute modules who's dependencies have just been met
827 for ( var r in registry ) {
828 if ( registry[r].state == 'loaded' ) {
829 if ( compare(
830 filter( ['ready'], registry[r].dependencies ),
831 registry[r].dependencies ) )
832 {
833 execute( r );
834 }
835 }
836 }
837 } catch ( e ) {
838 // Run error callbacks of jobs affected by this condition
839 for ( var j = 0; j < jobs.length; j++ ) {
840 if ( $.inArray( module, jobs[j].dependencies ) !== -1 ) {
841 if ( $.isFunction( jobs[j].error ) ) {
842 jobs[j].error();
843 }
844 jobs.splice( j, 1 );
845 j--;
846 }
847 }
848 }
849 }
850
851 /**
852 * Adds a dependencies to the queue with optional callbacks to be run
853 * when the dependencies are ready or fail
854 *
855 * @param dependencies string module name or array of string module names
856 * @param ready function callback to execute when all dependencies are ready
857 * @param error function callback to execute when any dependency fails
858 */
859 function request( dependencies, ready, error ) {
860 // Allow calling by single module name
861 if ( typeof dependencies === 'string' ) {
862 dependencies = [dependencies];
863 if ( dependencies[0] in registry ) {
864 for ( var n = 0; n < registry[dependencies[0]].dependencies.length; n++ ) {
865 dependencies[dependencies.length] =
866 registry[dependencies[0]].dependencies[n];
867 }
868 }
869 }
870 // Add ready and error callbacks if they were given
871 if ( arguments.length > 1 ) {
872 jobs[jobs.length] = {
873 'dependencies': filter(
874 ['undefined', 'registered', 'loading', 'loaded'],
875 dependencies ),
876 'ready': ready,
877 'error': error
878 };
879 }
880 // Queue up any dependencies that are undefined or registered
881 dependencies = filter( ['undefined', 'registered'], dependencies );
882 for ( var n = 0; n < dependencies.length; n++ ) {
883 if ( $.inArray( dependencies[n], queue ) === -1 ) {
884 queue[queue.length] = dependencies[n];
885 }
886 }
887 // Work the queue
888 mw.loader.work();
889 }
890
891 function sortQuery(o) {
892 var sorted = {}, key, a = [];
893 for ( key in o ) {
894 if ( o.hasOwnProperty( key ) ) {
895 a.push( key );
896 }
897 }
898 a.sort();
899 for ( key = 0; key < a.length; key++ ) {
900 sorted[a[key]] = o[a[key]];
901 }
902 return sorted;
903 }
904
905 /**
906 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
907 * to a query string of the form foo.bar,baz|bar.baz,quux
908 */
909 function buildModulesString( moduleMap ) {
910 var arr = [];
911 for ( var prefix in moduleMap ) {
912 var p = prefix === '' ? '' : prefix + '.';
913 arr.push( p + moduleMap[prefix].join( ',' ) );
914 }
915 return arr.join( '|' ).replace( /\./g, '!' );
916 }
917
918 /**
919 * Adds a script tag to the body, either using document.write or low-level DOM manipulation,
920 * depending on whether document-ready has occured yet.
921 *
922 * @param src String: URL to script, will be used as the src attribute in the script tag
923 * @param callback Function: Optional callback which will be run when the script is done
924 */
925 function addScript( src, callback ) {
926 if ( ready ) {
927 // jQuery's getScript method is NOT better than doing this the old-fassioned way
928 // because jQuery will eval the script's code, and errors will not have sane
929 // line numbers.
930 var script = document.createElement( 'script' );
931 script.setAttribute( 'src', src );
932 script.setAttribute( 'type', 'text/javascript' );
933 if ( $.isFunction( callback ) ) {
934 var done = false;
935 // Attach handlers for all browsers -- this is based on jQuery.getScript
936 script.onload = script.onreadystatechange = function() {
937 if (
938 !done
939 && (
940 !this.readyState
941 || this.readyState === "loaded"
942 || this.readyState === "complete"
943 )
944 ) {
945 done = true;
946 callback();
947 // Handle memory leak in IE
948 script.onload = script.onreadystatechange = null;
949 if ( script.parentNode ) {
950 script.parentNode.removeChild( script );
951 }
952 }
953 };
954 }
955 document.body.appendChild( script );
956 } else {
957 document.write( mw.html.element(
958 'script', { 'type': 'text/javascript', 'src': src }, ''
959 ) );
960 if ( $.isFunction( callback ) ) {
961 // Document.write is synchronous, so this is called when it's done
962 callback();
963 }
964 }
965 }
966
967 /* Public Methods */
968
969 /**
970 * Requests dependencies from server, loading and executing when things when ready.
971 */
972 this.work = function() {
973 // Appends a list of modules to the batch
974 for ( var q = 0; q < queue.length; q++ ) {
975 // Only request modules which are undefined or registered
976 if ( !( queue[q] in registry ) || registry[queue[q]].state == 'registered' ) {
977 // Prevent duplicate entries
978 if ( $.inArray( queue[q], batch ) === -1 ) {
979 batch[batch.length] = queue[q];
980 // Mark registered modules as loading
981 if ( queue[q] in registry ) {
982 registry[queue[q]].state = 'loading';
983 }
984 }
985 }
986 }
987 // Early exit if there's nothing to load
988 if ( !batch.length ) {
989 return;
990 }
991 // Clean up the queue
992 queue = [];
993 // Always order modules alphabetically to help reduce cache
994 // misses for otherwise identical content
995 batch.sort();
996 // Build a list of request parameters
997 var base = {
998 'skin': mw.config.get( 'skin' ),
999 'lang': mw.config.get( 'wgUserLanguage' ),
1000 'debug': mw.config.get( 'debug' )
1001 };
1002 // Extend request parameters with a list of modules in the batch
1003 var requests = [];
1004 // Split into groups
1005 var groups = {};
1006 for ( var b = 0; b < batch.length; b++ ) {
1007 var group = registry[batch[b]].group;
1008 if ( !( group in groups ) ) {
1009 groups[group] = [];
1010 }
1011 groups[group][groups[group].length] = batch[b];
1012 }
1013 for ( var group in groups ) {
1014 // Calculate the highest timestamp
1015 var version = 0;
1016 for ( var g = 0; g < groups[group].length; g++ ) {
1017 if ( registry[groups[group][g]].version > version ) {
1018 version = registry[groups[group][g]].version;
1019 }
1020 }
1021 var reqBase = $.extend( { 'version': formatVersionNumber( version ) }, base );
1022 var reqBaseLength = $.param( reqBase ).length;
1023 var reqs = [];
1024 var limit = mw.config.get( 'wgResourceLoaderMaxQueryLength', -1 );
1025 // We may need to split up the request to honor the query string length limit
1026 // So build it piece by piece
1027 var l = reqBaseLength + 9; // '&modules='.length == 9
1028 var r = 0;
1029 reqs[0] = {}; // { prefix: [ suffixes ] }
1030 for ( var i = 0; i < groups[group].length; i++ ) {
1031 // Determine how many bytes this module would add to the query string
1032 var lastDotIndex = groups[group][i].lastIndexOf( '.' );
1033 // Note that these substr() calls work even if lastDotIndex == -1
1034 var prefix = groups[group][i].substr( 0, lastDotIndex );
1035 var suffix = groups[group][i].substr( lastDotIndex + 1 );
1036 var bytesAdded = prefix in reqs[r] ?
1037 suffix.length + 3 : // '%2C'.length == 3
1038 groups[group][i].length + 3; // '%7C'.length == 3
1039
1040 // If the request would become too long, create a new one,
1041 // but don't create empty requests
1042 if ( limit > 0 && reqs[r] != {} && l + bytesAdded > limit ) {
1043 // This request would become too long, create a new one
1044 r++;
1045 reqs[r] = {};
1046 l = reqBaseLength + 9;
1047 }
1048 if ( !( prefix in reqs[r] ) ) {
1049 reqs[r][prefix] = [];
1050 }
1051 reqs[r][prefix].push( suffix );
1052 l += bytesAdded;
1053 }
1054 for ( var r = 0; r < reqs.length; r++ ) {
1055 requests[requests.length] = $.extend(
1056 { 'modules': buildModulesString( reqs[r] ) }, reqBase
1057 );
1058 }
1059 }
1060 // Clear the batch - this MUST happen before we append the
1061 // script element to the body or it's possible that the script
1062 // will be locally cached, instantly load, and work the batch
1063 // again, all before we've cleared it causing each request to
1064 // include modules which are already loaded
1065 batch = [];
1066 // Asynchronously append a script tag to the end of the body
1067 for ( var r = 0; r < requests.length; r++ ) {
1068 requests[r] = sortQuery( requests[r] );
1069 var src = mw.config.get( 'wgLoadScript' ) + '?' + $.param( requests[r] );
1070 addScript( src );
1071 }
1072 };
1073
1074 /**
1075 * Registers a module, letting the system know about it and its
1076 * dependencies. loader.js files contain calls to this function.
1077 */
1078 this.register = function( module, version, dependencies, group ) {
1079 // Allow multiple registration
1080 if ( typeof module === 'object' ) {
1081 for ( var m = 0; m < module.length; m++ ) {
1082 if ( typeof module[m] === 'string' ) {
1083 mw.loader.register( module[m] );
1084 } else if ( typeof module[m] === 'object' ) {
1085 mw.loader.register.apply( mw.loader, module[m] );
1086 }
1087 }
1088 return;
1089 }
1090 // Validate input
1091 if ( typeof module !== 'string' ) {
1092 throw new Error( 'module must be a string, not a ' + typeof module );
1093 }
1094 if ( typeof registry[module] !== 'undefined' ) {
1095 throw new Error( 'module already implemeneted: ' + module );
1096 }
1097 // List the module as registered
1098 registry[module] = {
1099 'state': 'registered',
1100 'group': typeof group === 'string' ? group : null,
1101 'dependencies': [],
1102 'version': typeof version !== 'undefined' ? parseInt( version, 10 ) : 0
1103 };
1104 if ( typeof dependencies === 'string' ) {
1105 // Allow dependencies to be given as a single module name
1106 registry[module].dependencies = [dependencies];
1107 } else if ( typeof dependencies === 'object' || $.isFunction( dependencies ) ) {
1108 // Allow dependencies to be given as an array of module names
1109 // or a function which returns an array
1110 registry[module].dependencies = dependencies;
1111 }
1112 };
1113
1114 /**
1115 * Implements a module, giving the system a course of action to take
1116 * upon loading. Results of a request for one or more modules contain
1117 * calls to this function.
1118 *
1119 * All arguments are required.
1120 *
1121 * @param module String: Name of module
1122 * @param script Mixed: Function of module code or String of URL to be used as the src
1123 * attribute when adding a script element to the body
1124 * @param style Object: Object of CSS strings keyed by media-type or Object of lists of URLs
1125 * keyed by media-type
1126 * @param msgs Object: List of key/value pairs to be passed through mw.messages.set
1127 */
1128 this.implement = function( module, script, style, msgs ) {
1129 // Validate input
1130 if ( typeof module !== 'string' ) {
1131 throw new Error( 'module must be a string, not a ' + typeof module );
1132 }
1133 if ( !$.isFunction( script ) && !$.isArray( script ) ) {
1134 throw new Error( 'script must be a function or an array, not a ' + typeof script );
1135 }
1136 if ( !$.isPlainObject( style ) ) {
1137 throw new Error( 'style must be an object or a string, not a ' + typeof style );
1138 }
1139 if ( !$.isPlainObject( msgs ) ) {
1140 throw new Error( 'msgs must be an object, not a ' + typeof msgs );
1141 }
1142 // Automatically register module
1143 if ( typeof registry[module] === 'undefined' ) {
1144 mw.loader.register( module );
1145 }
1146 // Check for duplicate implementation
1147 if ( typeof registry[module] !== 'undefined'
1148 && typeof registry[module].script !== 'undefined' )
1149 {
1150 throw new Error( 'module already implemeneted: ' + module );
1151 }
1152 // Mark module as loaded
1153 registry[module].state = 'loaded';
1154 // Attach components
1155 registry[module].script = script;
1156 registry[module].style = style;
1157 registry[module].messages = msgs;
1158 // Execute or queue callback
1159 if ( compare(
1160 filter( ['ready'], registry[module].dependencies ),
1161 registry[module].dependencies ) )
1162 {
1163 execute( module );
1164 } else {
1165 request( module );
1166 }
1167 };
1168
1169 /**
1170 * Executes a function as soon as one or more required modules are ready
1171 *
1172 * @param dependencies string or array of strings of modules names the callback
1173 * dependencies to be ready before
1174 * executing
1175 * @param ready function callback to execute when all dependencies are ready (optional)
1176 * @param error function callback to execute when if dependencies have a errors (optional)
1177 */
1178 this.using = function( dependencies, ready, error ) {
1179 // Validate input
1180 if ( typeof dependencies !== 'object' && typeof dependencies !== 'string' ) {
1181 throw new Error( 'dependencies must be a string or an array, not a ' +
1182 typeof dependencies );
1183 }
1184 // Allow calling with a single dependency as a string
1185 if ( typeof dependencies === 'string' ) {
1186 dependencies = [dependencies];
1187 }
1188 // Resolve entire dependency map
1189 dependencies = resolve( dependencies );
1190 // If all dependencies are met, execute ready immediately
1191 if ( compare( filter( ['ready'], dependencies ), dependencies ) ) {
1192 if ( $.isFunction( ready ) ) {
1193 ready();
1194 }
1195 }
1196 // If any dependencies have errors execute error immediately
1197 else if ( filter( ['error'], dependencies ).length ) {
1198 if ( $.isFunction( error ) ) {
1199 error();
1200 }
1201 }
1202 // Since some dependencies are not yet ready, queue up a request
1203 else {
1204 request( dependencies, ready, error );
1205 }
1206 };
1207
1208 /**
1209 * Loads an external script or one or more modules for future use
1210 *
1211 * @param modules mixed either the name of a module, array of modules,
1212 * or a URL of an external script or style
1213 * @param type string mime-type to use if calling with a URL of an
1214 * external script or style; acceptable values are "text/css" and
1215 * "text/javascript"; if no type is provided, text/javascript is
1216 * assumed
1217 */
1218 this.load = function( modules, type ) {
1219 // Validate input
1220 if ( typeof modules !== 'object' && typeof modules !== 'string' ) {
1221 throw new Error( 'modules must be a string or an array, not a ' +
1222 typeof modules );
1223 }
1224 // Allow calling with an external script or single dependency as a string
1225 if ( typeof modules === 'string' ) {
1226 // Support adding arbitrary external scripts
1227 if ( modules.substr( 0, 7 ) == 'http://' || modules.substr( 0, 8 ) == 'https://' ) {
1228 if ( type === 'text/css' ) {
1229 $( 'head' ).append( $( '<link />', {
1230 rel: 'stylesheet',
1231 type: 'text/css',
1232 href: modules
1233 } ) );
1234 return true;
1235 } else if ( type === 'text/javascript' || typeof type === 'undefined' ) {
1236 addScript( modules );
1237 return true;
1238 }
1239 // Unknown type
1240 return false;
1241 }
1242 // Called with single module
1243 modules = [modules];
1244 }
1245 // Resolve entire dependency map
1246 modules = resolve( modules );
1247 // If all modules are ready, nothing dependency be done
1248 if ( compare( filter( ['ready'], modules ), modules ) ) {
1249 return true;
1250 }
1251 // If any modules have errors return false
1252 else if ( filter( ['error'], modules ).length ) {
1253 return false;
1254 }
1255 // Since some modules are not yet ready, queue up a request
1256 else {
1257 request( modules );
1258 return true;
1259 }
1260 };
1261
1262 /**
1263 * Changes the state of a module
1264 *
1265 * @param module string module name or object of module name/state pairs
1266 * @param state string state name
1267 */
1268 this.state = function( module, state ) {
1269 if ( typeof module === 'object' ) {
1270 for ( var m in module ) {
1271 mw.loader.state( m, module[m] );
1272 }
1273 return;
1274 }
1275 if ( !( module in registry ) ) {
1276 mw.loader.register( module );
1277 }
1278 registry[module].state = state;
1279 };
1280
1281 /**
1282 * Gets the version of a module
1283 *
1284 * @param module string name of module to get version for
1285 */
1286 this.version = function( module ) {
1287 if ( module in registry && 'version' in registry[module] ) {
1288 return formatVersionNumber( registry[module].version );
1289 }
1290 return null;
1291 };
1292
1293 /* Cache document ready status */
1294
1295 $(document).ready( function() { ready = true; } );
1296 } )();
1297
1298 /** HTML construction helper functions */
1299 this.html = new ( function () {
1300 var escapeCallback = function( s ) {
1301 switch ( s ) {
1302 case "'":
1303 return '&#039;';
1304 case '"':
1305 return '&quot;';
1306 case '<':
1307 return '&lt;';
1308 case '>':
1309 return '&gt;';
1310 case '&':
1311 return '&amp;';
1312 }
1313 };
1314
1315 /**
1316 * Escape a string for HTML. Converts special characters to HTML entities.
1317 * @param s The string to escape
1318 */
1319 this.escape = function( s ) {
1320 return s.replace( /['"<>&]/g, escapeCallback );
1321 };
1322
1323 /**
1324 * Wrapper object for raw HTML passed to mw.html.element().
1325 */
1326 this.Raw = function( value ) {
1327 this.value = value;
1328 };
1329
1330 /**
1331 * Wrapper object for CDATA element contents passed to mw.html.element()
1332 */
1333 this.Cdata = function( value ) {
1334 this.value = value;
1335 };
1336
1337 /**
1338 * Create an HTML element string, with safe escaping.
1339 *
1340 * @param name The tag name.
1341 * @param attrs An object with members mapping element names to values
1342 * @param contents The contents of the element. May be either:
1343 * - string: The string is escaped.
1344 * - null or undefined: The short closing form is used, e.g. <br/>.
1345 * - this.Raw: The value attribute is included without escaping.
1346 * - this.Cdata: The value attribute is included, and an exception is
1347 * thrown if it contains an illegal ETAGO delimiter.
1348 * See http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.3.2
1349 *
1350 * Example:
1351 * var h = mw.html;
1352 * return h.element( 'div', {},
1353 * new h.Raw( h.element( 'img', {src: '<'} ) ) );
1354 * Returns <div><img src="&lt;"/></div>
1355 */
1356 this.element = function( name, attrs, contents ) {
1357 var s = '<' + name;
1358 for ( var attrName in attrs ) {
1359 s += ' ' + attrName + '="' + this.escape( attrs[attrName] ) + '"';
1360 }
1361 if ( typeof contents == 'undefined' || contents === null ) {
1362 // Self close tag
1363 s += '/>';
1364 return s;
1365 }
1366 // Regular open tag
1367 s += '>';
1368 if ( typeof contents === 'string') {
1369 // Escaped
1370 s += this.escape( contents );
1371 } else if ( contents instanceof this.Raw ) {
1372 // Raw HTML inclusion
1373 s += contents.value;
1374 } else if ( contents instanceof this.Cdata ) {
1375 // CDATA
1376 if ( /<\/[a-zA-z]/.test( contents.value ) ) {
1377 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
1378 }
1379 s += contents.value;
1380 } else {
1381 throw new Error( 'mw.html.element: Invalid type of contents' );
1382 }
1383 s += '</' + name + '>';
1384 return s;
1385 };
1386 } )();
1387
1388 /* Extension points */
1389
1390 this.legacy = {};
1391
1392 } )( jQuery );
1393
1394 // Alias $j to jQuery for backwards compatibility
1395 window.$j = jQuery;
1396 window.mw = mediaWiki;
1397
1398 /* Auto-register from pre-loaded startup scripts */
1399
1400 if ( $.isFunction( startUp ) ) {
1401 startUp();
1402 delete startUp;
1403 }
1404
1405 // Add jQuery Cookie to initial payload (used in mw.user)
1406 mw.loader.load( 'jquery.cookie' );