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