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