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