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