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