Merge "Use canonical parser option for linkupdate in api purge"
[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 * Resolves dependencies and detects circular references.
485 *
486 * @param module String Name of the top-level module whose dependencies shall be
487 * resolved and sorted.
488 * @param resolved Array Returns a topological sort of the given module and its
489 * dependencies, such that later modules depend on earlier modules. The array
490 * contains the module names. If the array contains already some module names,
491 * this function appends its result to the pre-existing array.
492 * @param unresolved Object [optional] Hash used to track the current dependency
493 * chain; used to report loops in the dependency graph.
494 * @throws Error if any unregistered module or a dependency loop is encountered
495 */
496 function sortDependencies( module, resolved, unresolved ) {
497 var n, deps, len;
498
499 if ( registry[module] === undefined ) {
500 throw new Error( 'Unknown dependency: ' + module );
501 }
502 // Resolves dynamic loader function and replaces it with its own results
503 if ( $.isFunction( registry[module].dependencies ) ) {
504 registry[module].dependencies = registry[module].dependencies();
505 // Ensures the module's dependencies are always in an array
506 if ( typeof registry[module].dependencies !== 'object' ) {
507 registry[module].dependencies = [registry[module].dependencies];
508 }
509 }
510 if ( $.inArray( module, resolved ) !== -1 ) {
511 // Module already resolved; nothing to do.
512 return;
513 }
514 // unresolved is optional, supply it if not passed in
515 if ( !unresolved ) {
516 unresolved = {};
517 }
518 // Tracks down dependencies
519 deps = registry[module].dependencies;
520 len = deps.length;
521 for ( n = 0; n < len; n += 1 ) {
522 if ( $.inArray( deps[n], resolved ) === -1 ) {
523 if ( unresolved[deps[n]] ) {
524 throw new Error(
525 'Circular reference detected: ' + module +
526 ' -> ' + deps[n]
527 );
528 }
529
530 // Add to unresolved
531 unresolved[module] = true;
532 sortDependencies( deps[n], resolved, unresolved );
533 delete unresolved[module];
534 }
535 }
536 resolved[resolved.length] = module;
537 }
538
539 /**
540 * Gets a list of module names that a module depends on in their proper dependency
541 * order.
542 *
543 * @param module string module name or array of string module names
544 * @return list of dependencies, including 'module'.
545 * @throws Error if circular reference is detected
546 */
547 function resolve( module ) {
548 var m, resolved;
549
550 // Allow calling with an array of module names
551 if ( $.isArray( module ) ) {
552 resolved = [];
553 for ( m = 0; m < module.length; m += 1 ) {
554 sortDependencies( module[m], resolved );
555 }
556 return resolved;
557 }
558
559 if ( typeof module === 'string' ) {
560 resolved = [];
561 sortDependencies( module, resolved );
562 return resolved;
563 }
564
565 throw new Error( 'Invalid module argument: ' + module );
566 }
567
568 /**
569 * Narrows a list of module names down to those matching a specific
570 * state (see comment on top of this scope for a list of valid states).
571 * One can also filter for 'unregistered', which will return the
572 * modules names that don't have a registry entry.
573 *
574 * @param states string or array of strings of module states to filter by
575 * @param modules array list of module names to filter (optional, by default the entire
576 * registry is used)
577 * @return array list of filtered module names
578 */
579 function filter( states, modules ) {
580 var list, module, s, m;
581
582 // Allow states to be given as a string
583 if ( typeof states === 'string' ) {
584 states = [states];
585 }
586 // If called without a list of modules, build and use a list of all modules
587 list = [];
588 if ( modules === undefined ) {
589 modules = [];
590 for ( module in registry ) {
591 modules[modules.length] = module;
592 }
593 }
594 // Build a list of modules which are in one of the specified states
595 for ( s = 0; s < states.length; s += 1 ) {
596 for ( m = 0; m < modules.length; m += 1 ) {
597 if ( registry[modules[m]] === undefined ) {
598 // Module does not exist
599 if ( states[s] === 'unregistered' ) {
600 // OK, undefined
601 list[list.length] = modules[m];
602 }
603 } else {
604 // Module exists, check state
605 if ( registry[modules[m]].state === states[s] ) {
606 // OK, correct state
607 list[list.length] = modules[m];
608 }
609 }
610 }
611 }
612 return list;
613 }
614
615 /**
616 * Determine whether all dependencies are in state 'ready', which means we may
617 * execute the module or job now.
618 *
619 * @param dependencies Array dependencies (module names) to be checked.
620 *
621 * @return Boolean true if all dependencies are in state 'ready', false otherwise
622 */
623 function allReady( dependencies ) {
624 return filter( 'ready', dependencies ).length === dependencies.length;
625 }
626
627 /**
628 * Log a message to window.console, if possible. Useful to force logging of some
629 * errors that are otherwise hard to detect (I.e., this logs also in production mode).
630 * Gets console references in each invocation, so that delayed debugging tools work
631 * fine. No need for optimization here, which would only result in losing logs.
632 *
633 * @param msg String text for the log entry.
634 * @param e Error [optional] to also log.
635 */
636 function log( msg, e ) {
637 var console = window.console;
638 if ( console && console.log ) {
639 console.log( msg );
640 // console.error triggers the proper handling of exception objects in
641 // consoles that support it. Fallback to passing as plain object to log().
642 if ( e ) {
643 (console.error || console.log).call( console, e );
644 }
645 }
646 }
647
648 /**
649 * A module has entered state 'ready', 'error', or 'missing'. Automatically update pending jobs
650 * and modules that depend upon this module. if the given module failed, propagate the 'error'
651 * state up the dependency tree; otherwise, execute all jobs/modules that now have all their
652 * dependencies satisfied. On jobs depending on a failed module, run the error callback, if any.
653 *
654 * @param module String name of module that entered one of the states 'ready', 'error', or 'missing'.
655 */
656 function handlePending( module ) {
657 var j, job, hasErrors, m, stateChange;
658
659 // Modules.
660 if ( $.inArray( registry[module].state, ['error', 'missing'] ) !== -1 ) {
661 // If the current module failed, mark all dependent modules also as failed.
662 // Iterate until steady-state to propagate the error state upwards in the
663 // dependency tree.
664 do {
665 stateChange = false;
666 for ( m in registry ) {
667 if ( $.inArray( registry[m].state, ['error', 'missing'] ) === -1 ) {
668 if ( filter( ['error', 'missing'], registry[m].dependencies ).length > 0 ) {
669 registry[m].state = 'error';
670 stateChange = true;
671 }
672 }
673 }
674 } while ( stateChange );
675 }
676
677 // Execute all jobs whose dependencies are either all satisfied or contain at least one failed module.
678 for ( j = 0; j < jobs.length; j += 1 ) {
679 hasErrors = filter( ['error', 'missing'], jobs[j].dependencies ).length > 0;
680 if ( hasErrors || allReady( jobs[j].dependencies ) ) {
681 // All dependencies satisfied, or some have errors
682 job = jobs[j];
683 jobs.splice( j, 1 );
684 j -= 1;
685 try {
686 if ( hasErrors ) {
687 throw new Error ("Module " + module + " failed.");
688 } else {
689 if ( $.isFunction( job.ready ) ) {
690 job.ready();
691 }
692 }
693 } catch ( e ) {
694 if ( $.isFunction( job.error ) ) {
695 try {
696 job.error( e, [module] );
697 } catch ( ex ) {
698 // A user-defined operation raised an exception. Swallow to protect
699 // our state machine!
700 log( 'mw.loader::handlePending> Exception thrown by job.error()', ex );
701 }
702 }
703 }
704 }
705 }
706
707 if ( registry[module].state === 'ready' ) {
708 // The current module became 'ready'. Recursively execute all dependent modules that are loaded
709 // and now have all dependencies satisfied.
710 for ( m in registry ) {
711 if ( registry[m].state === 'loaded' && allReady( registry[m].dependencies ) ) {
712 execute( m );
713 }
714 }
715 }
716 }
717
718 /**
719 * Adds a script tag to the DOM, either using document.write or low-level DOM manipulation,
720 * depending on whether document-ready has occurred yet and whether we are in async mode.
721 *
722 * @param src String: URL to script, will be used as the src attribute in the script tag
723 * @param callback Function: Optional callback which will be run when the script is done
724 */
725 function addScript( src, callback, async ) {
726 var done = false, script, head;
727 if ( ready || async ) {
728 // jQuery's getScript method is NOT better than doing this the old-fashioned way
729 // because jQuery will eval the script's code, and errors will not have sane
730 // line numbers.
731 script = document.createElement( 'script' );
732 script.setAttribute( 'src', src );
733 script.setAttribute( 'type', 'text/javascript' );
734 if ( $.isFunction( callback ) ) {
735 // Attach handlers for all browsers (based on jQuery.ajax)
736 script.onload = script.onreadystatechange = function() {
737
738 if (
739 !done
740 && (
741 !script.readyState
742 || /loaded|complete/.test( script.readyState )
743 )
744 ) {
745
746 done = true;
747
748 callback();
749
750 // Handle memory leak in IE. This seems to fail in
751 // IE7 sometimes (Permission Denied error when
752 // accessing script.parentNode) so wrap it in
753 // a try catch.
754 try {
755 script.onload = script.onreadystatechange = null;
756 if ( script.parentNode ) {
757 script.parentNode.removeChild( script );
758 }
759
760 // Dereference the script
761 script = undefined;
762 } catch ( e ) { }
763 }
764 };
765 }
766
767 if ( window.opera ) {
768 // Appending to the <head> blocks rendering completely in Opera,
769 // so append to the <body> after document ready. This means the
770 // scripts only start loading after the document has been rendered,
771 // but so be it. Opera users don't deserve faster web pages if their
772 // browser makes it impossible
773 $( function() { document.body.appendChild( script ); } );
774 } else {
775 // IE-safe way of getting the <head> . document.documentElement.head doesn't
776 // work in scripts that run in the <head>
777 head = document.getElementsByTagName( 'head' )[0];
778 ( document.body || head ).appendChild( script );
779 }
780 } else {
781 document.write( mw.html.element(
782 'script', { 'type': 'text/javascript', 'src': src }, ''
783 ) );
784 if ( $.isFunction( callback ) ) {
785 // Document.write is synchronous, so this is called when it's done
786 // FIXME: that's a lie. doc.write isn't actually synchronous
787 callback();
788 }
789 }
790 }
791
792 /**
793 * Executes a loaded module, making it ready to use
794 *
795 * @param module string module name to execute
796 */
797 function execute( module ) {
798 var style, media, i, script, markModuleReady, nestedAddScript;
799
800 if ( registry[module] === undefined ) {
801 throw new Error( 'Module has not been registered yet: ' + module );
802 } else if ( registry[module].state === 'registered' ) {
803 throw new Error( 'Module has not been requested from the server yet: ' + module );
804 } else if ( registry[module].state === 'loading' ) {
805 throw new Error( 'Module has not completed loading yet: ' + module );
806 } else if ( registry[module].state === 'ready' ) {
807 throw new Error( 'Module has already been loaded: ' + module );
808 }
809
810 // Add styles
811 if ( $.isPlainObject( registry[module].style ) ) {
812 // 'media' type ignored, see documentation of mw.loader.implement
813 for ( media in registry[module].style ) {
814 style = registry[module].style[media];
815 if ( $.isArray( style ) ) {
816 for ( i = 0; i < style.length; i += 1 ) {
817 getMarker().before( mw.html.element( 'link', {
818 'type': 'text/css',
819 'rel': 'stylesheet',
820 'href': style[i]
821 } ) );
822 }
823 } else if ( typeof style === 'string' ) {
824 addInlineCSS( style );
825 }
826 }
827 }
828 // Add localizations to message system
829 if ( $.isPlainObject( registry[module].messages ) ) {
830 mw.messages.set( registry[module].messages );
831 }
832 // Execute script
833 try {
834 script = registry[module].script;
835 markModuleReady = function() {
836 registry[module].state = 'ready';
837 handlePending( module );
838 };
839 nestedAddScript = function ( arr, callback, async, i ) {
840 // Recursively call addScript() in its own callback
841 // for each element of arr.
842 if ( i >= arr.length ) {
843 // We're at the end of the array
844 callback();
845 return;
846 }
847
848 addScript( arr[i], function() {
849 nestedAddScript( arr, callback, async, i + 1 );
850 }, async );
851 };
852
853 if ( $.isArray( script ) ) {
854 registry[module].state = 'loading';
855 nestedAddScript( script, markModuleReady, registry[module].async, 0 );
856 } else if ( $.isFunction( script ) ) {
857 script( $ );
858 markModuleReady();
859 }
860 } catch ( e ) {
861 // This needs to NOT use mw.log because these errors are common in production mode
862 // and not in debug mode, such as when a symbol that should be global isn't exported
863 log('mw.loader::execute> Exception thrown by ' + module + ': ' + e.message, e);
864 registry[module].state = 'error';
865 handlePending( module );
866 }
867 }
868
869 /**
870 * Adds a dependencies to the queue with optional callbacks to be run
871 * when the dependencies are ready or fail
872 *
873 * @param dependencies string module name or array of string module names
874 * @param ready function callback to execute when all dependencies are ready
875 * @param error function callback to execute when any dependency fails
876 * @param async (optional) If true, load modules asynchronously even if
877 * document ready has not yet occurred
878 */
879 function request( dependencies, ready, error, async ) {
880 var regItemDeps, regItemDepLen, n;
881
882 // Allow calling by single module name
883 if ( typeof dependencies === 'string' ) {
884 dependencies = [dependencies];
885 if ( registry[dependencies[0]] !== undefined ) {
886 // Cache repetitively accessed deep level object member
887 regItemDeps = registry[dependencies[0]].dependencies;
888 // Cache to avoid looped access to length property
889 regItemDepLen = regItemDeps.length;
890 for ( n = 0; n < regItemDepLen; n += 1 ) {
891 dependencies[dependencies.length] = regItemDeps[n];
892 }
893 }
894 }
895
896 // Add ready and error callbacks if they were given
897 if ( ready !== undefined || error !== undefined ) {
898 jobs[jobs.length] = {
899 'dependencies': filter(
900 ['registered', 'loading', 'loaded'],
901 dependencies
902 ),
903 'ready': ready,
904 'error': error
905 };
906 }
907
908 // Queue up any dependencies that are registered
909 dependencies = filter( ['registered'], dependencies );
910 for ( n = 0; n < dependencies.length; n += 1 ) {
911 if ( $.inArray( dependencies[n], queue ) === -1 ) {
912 queue[queue.length] = dependencies[n];
913 if ( async ) {
914 // Mark this module as async in the registry
915 registry[dependencies[n]].async = true;
916 }
917 }
918 }
919
920 // Work the queue
921 mw.loader.work();
922 }
923
924 function sortQuery(o) {
925 var sorted = {}, key, a = [];
926 for ( key in o ) {
927 if ( hasOwn.call( o, key ) ) {
928 a.push( key );
929 }
930 }
931 a.sort();
932 for ( key = 0; key < a.length; key += 1 ) {
933 sorted[a[key]] = o[a[key]];
934 }
935 return sorted;
936 }
937
938 /**
939 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
940 * to a query string of the form foo.bar,baz|bar.baz,quux
941 */
942 function buildModulesString( moduleMap ) {
943 var arr = [], p, prefix;
944 for ( prefix in moduleMap ) {
945 p = prefix === '' ? '' : prefix + '.';
946 arr.push( p + moduleMap[prefix].join( ',' ) );
947 }
948 return arr.join( '|' );
949 }
950
951 /**
952 * Asynchronously append a script tag to the end of the body
953 * that invokes load.php
954 * @param moduleMap {Object}: Module map, see buildModulesString()
955 * @param currReqBase {Object}: Object with other parameters (other than 'modules') to use in the request
956 * @param sourceLoadScript {String}: URL of load.php
957 * @param async {Boolean}: If true, use an asynchrounous request even if document ready has not yet occurred
958 */
959 function doRequest( moduleMap, currReqBase, sourceLoadScript, async ) {
960 var request = $.extend(
961 { 'modules': buildModulesString( moduleMap ) },
962 currReqBase
963 );
964 request = sortQuery( request );
965 // Asynchronously append a script tag to the end of the body
966 // Append &* to avoid triggering the IE6 extension check
967 addScript( sourceLoadScript + '?' + $.param( request ) + '&*', null, async );
968 }
969
970 /* Public Methods */
971 return {
972 addStyleTag: addStyleTag,
973
974 /**
975 * Requests dependencies from server, loading and executing when things when ready.
976 */
977 work: function () {
978 var reqBase, splits, maxQueryLength, q, b, bSource, bGroup, bSourceGroup,
979 source, group, g, i, modules, maxVersion, sourceLoadScript,
980 currReqBase, currReqBaseLength, moduleMap, l,
981 lastDotIndex, prefix, suffix, bytesAdded, async;
982
983 // Build a list of request parameters common to all requests.
984 reqBase = {
985 skin: mw.config.get( 'skin' ),
986 lang: mw.config.get( 'wgUserLanguage' ),
987 debug: mw.config.get( 'debug' )
988 };
989 // Split module batch by source and by group.
990 splits = {};
991 maxQueryLength = mw.config.get( 'wgResourceLoaderMaxQueryLength', -1 );
992
993 // Appends a list of modules from the queue to the batch
994 for ( q = 0; q < queue.length; q += 1 ) {
995 // Only request modules which are registered
996 if ( registry[queue[q]] !== undefined && registry[queue[q]].state === 'registered' ) {
997 // Prevent duplicate entries
998 if ( $.inArray( queue[q], batch ) === -1 ) {
999 batch[batch.length] = queue[q];
1000 // Mark registered modules as loading
1001 registry[queue[q]].state = 'loading';
1002 }
1003 }
1004 }
1005 // Early exit if there's nothing to load...
1006 if ( !batch.length ) {
1007 return;
1008 }
1009
1010 // The queue has been processed into the batch, clear up the queue.
1011 queue = [];
1012
1013 // Always order modules alphabetically to help reduce cache
1014 // misses for otherwise identical content.
1015 batch.sort();
1016
1017 // Split batch by source and by group.
1018 for ( b = 0; b < batch.length; b += 1 ) {
1019 bSource = registry[batch[b]].source;
1020 bGroup = registry[batch[b]].group;
1021 if ( splits[bSource] === undefined ) {
1022 splits[bSource] = {};
1023 }
1024 if ( splits[bSource][bGroup] === undefined ) {
1025 splits[bSource][bGroup] = [];
1026 }
1027 bSourceGroup = splits[bSource][bGroup];
1028 bSourceGroup[bSourceGroup.length] = batch[b];
1029 }
1030
1031 // Clear the batch - this MUST happen before we append any
1032 // script elements to the body or it's possible that a script
1033 // will be locally cached, instantly load, and work the batch
1034 // again, all before we've cleared it causing each request to
1035 // include modules which are already loaded.
1036 batch = [];
1037
1038 for ( source in splits ) {
1039
1040 sourceLoadScript = sources[source].loadScript;
1041
1042 for ( group in splits[source] ) {
1043
1044 // Cache access to currently selected list of
1045 // modules for this group from this source.
1046 modules = splits[source][group];
1047
1048 // Calculate the highest timestamp
1049 maxVersion = 0;
1050 for ( g = 0; g < modules.length; g += 1 ) {
1051 if ( registry[modules[g]].version > maxVersion ) {
1052 maxVersion = registry[modules[g]].version;
1053 }
1054 }
1055
1056 currReqBase = $.extend( { 'version': formatVersionNumber( maxVersion ) }, reqBase );
1057 // For user modules append a user name to the request.
1058 if ( group === "user" && mw.config.get( 'wgUserName' ) !== null ) {
1059 currReqBase.user = mw.config.get( 'wgUserName' );
1060 }
1061 currReqBaseLength = $.param( currReqBase ).length;
1062 async = true;
1063 // We may need to split up the request to honor the query string length limit,
1064 // so build it piece by piece.
1065 l = currReqBaseLength + 9; // '&modules='.length == 9
1066
1067 moduleMap = {}; // { prefix: [ suffixes ] }
1068
1069 for ( i = 0; i < modules.length; i += 1 ) {
1070 // Determine how many bytes this module would add to the query string
1071 lastDotIndex = modules[i].lastIndexOf( '.' );
1072 // Note that these substr() calls work even if lastDotIndex == -1
1073 prefix = modules[i].substr( 0, lastDotIndex );
1074 suffix = modules[i].substr( lastDotIndex + 1 );
1075 bytesAdded = moduleMap[prefix] !== undefined
1076 ? suffix.length + 3 // '%2C'.length == 3
1077 : modules[i].length + 3; // '%7C'.length == 3
1078
1079 // If the request would become too long, create a new one,
1080 // but don't create empty requests
1081 if ( maxQueryLength > 0 && !$.isEmptyObject( moduleMap ) && l + bytesAdded > maxQueryLength ) {
1082 // This request would become too long, create a new one
1083 // and fire off the old one
1084 doRequest( moduleMap, currReqBase, sourceLoadScript, async );
1085 moduleMap = {};
1086 async = true;
1087 l = currReqBaseLength + 9;
1088 }
1089 if ( moduleMap[prefix] === undefined ) {
1090 moduleMap[prefix] = [];
1091 }
1092 moduleMap[prefix].push( suffix );
1093 if ( !registry[modules[i]].async ) {
1094 // If this module is blocking, make the entire request blocking
1095 // This is slightly suboptimal, but in practice mixing of blocking
1096 // and async modules will only occur in debug mode.
1097 async = false;
1098 }
1099 l += bytesAdded;
1100 }
1101 // If there's anything left in moduleMap, request that too
1102 if ( !$.isEmptyObject( moduleMap ) ) {
1103 doRequest( moduleMap, currReqBase, sourceLoadScript, async );
1104 }
1105 }
1106 }
1107 },
1108
1109 /**
1110 * Register a source.
1111 *
1112 * @param id {String}: Short lowercase a-Z string representing a source, only used internally.
1113 * @param props {Object}: Object containing only the loadScript property which is a url to
1114 * the load.php location of the source.
1115 * @return {Boolean}
1116 */
1117 addSource: function ( id, props ) {
1118 var source;
1119 // Allow multiple additions
1120 if ( typeof id === 'object' ) {
1121 for ( source in id ) {
1122 mw.loader.addSource( source, id[source] );
1123 }
1124 return true;
1125 }
1126
1127 if ( sources[id] !== undefined ) {
1128 throw new Error( 'source already registered: ' + id );
1129 }
1130
1131 sources[id] = props;
1132
1133 return true;
1134 },
1135
1136 /**
1137 * Registers a module, letting the system know about it and its
1138 * properties. Startup modules contain calls to this function.
1139 *
1140 * @param module {String}: Module name
1141 * @param version {Number}: Module version number as a timestamp (falls backs to 0)
1142 * @param dependencies {String|Array|Function}: One string or array of strings of module
1143 * names on which this module depends, or a function that returns that array.
1144 * @param group {String}: Group which the module is in (optional, defaults to null)
1145 * @param source {String}: Name of the source. Defaults to local.
1146 */
1147 register: function ( module, version, dependencies, group, source ) {
1148 var m;
1149 // Allow multiple registration
1150 if ( typeof module === 'object' ) {
1151 for ( m = 0; m < module.length; m += 1 ) {
1152 // module is an array of module names
1153 if ( typeof module[m] === 'string' ) {
1154 mw.loader.register( module[m] );
1155 // module is an array of arrays
1156 } else if ( typeof module[m] === 'object' ) {
1157 mw.loader.register.apply( mw.loader, module[m] );
1158 }
1159 }
1160 return;
1161 }
1162 // Validate input
1163 if ( typeof module !== 'string' ) {
1164 throw new Error( 'module must be a string, not a ' + typeof module );
1165 }
1166 if ( registry[module] !== undefined ) {
1167 throw new Error( 'module already registered: ' + module );
1168 }
1169 // List the module as registered
1170 registry[module] = {
1171 'version': version !== undefined ? parseInt( version, 10 ) : 0,
1172 'dependencies': [],
1173 'group': typeof group === 'string' ? group : null,
1174 'source': typeof source === 'string' ? source: 'local',
1175 'state': 'registered'
1176 };
1177 if ( typeof dependencies === 'string' ) {
1178 // Allow dependencies to be given as a single module name
1179 registry[module].dependencies = [dependencies];
1180 } else if ( typeof dependencies === 'object' || $.isFunction( dependencies ) ) {
1181 // Allow dependencies to be given as an array of module names
1182 // or a function which returns an array
1183 registry[module].dependencies = dependencies;
1184 }
1185 },
1186
1187 /**
1188 * Implements a module, giving the system a course of action to take
1189 * upon loading. Results of a request for one or more modules contain
1190 * calls to this function.
1191 *
1192 * All arguments are required.
1193 *
1194 * @param module String: Name of module
1195 * @param script Mixed: Function of module code or String of URL to be used as the src
1196 * attribute when adding a script element to the body
1197 * @param style Object: Object of CSS strings keyed by media-type or Object of lists of URLs
1198 * keyed by media-type. Media-type should be "all" or "", actual types are not supported
1199 * right now due to the way execute() processes the stylesheets (they are concatenated
1200 * into a single <style> tag). In the past these weren't concatenated together (which is
1201 * these are keyed by media-type), but bug 31676 forces us to. In practice this is not a
1202 * problem because ResourceLoader only generates stylesheets for media-type all (e.g. print
1203 * stylesheets are wrapped in @media print {} and concatenated with the others).
1204 * @param msgs Object: List of key/value pairs to be passed through mw.messages.set
1205 */
1206 implement: function ( module, script, style, msgs ) {
1207 // Validate input
1208 if ( typeof module !== 'string' ) {
1209 throw new Error( 'module must be a string, not a ' + typeof module );
1210 }
1211 if ( !$.isFunction( script ) && !$.isArray( script ) ) {
1212 throw new Error( 'script must be a function or an array, not a ' + typeof script );
1213 }
1214 if ( !$.isPlainObject( style ) ) {
1215 throw new Error( 'style must be an object, not a ' + typeof style );
1216 }
1217 if ( !$.isPlainObject( msgs ) ) {
1218 throw new Error( 'msgs must be an object, not a ' + typeof msgs );
1219 }
1220 // Automatically register module
1221 if ( registry[module] === undefined ) {
1222 mw.loader.register( module );
1223 }
1224 // Check for duplicate implementation
1225 if ( registry[module] !== undefined && registry[module].script !== undefined ) {
1226 throw new Error( 'module already implemented: ' + module );
1227 }
1228 // Attach components
1229 registry[module].script = script;
1230 registry[module].style = style;
1231 registry[module].messages = msgs;
1232 // The module may already have been marked as erroneous
1233 if ( $.inArray( registry[module].state, ['error', 'missing'] ) === -1 ) {
1234 registry[module].state = 'loaded';
1235 if ( allReady( registry[module].dependencies ) ) {
1236 execute( module );
1237 }
1238 }
1239 },
1240
1241 /**
1242 * Executes a function as soon as one or more required modules are ready
1243 *
1244 * @param dependencies {String|Array} Module name or array of modules names the callback
1245 * dependends on to be ready before executing
1246 * @param ready {Function} callback to execute when all dependencies are ready (optional)
1247 * @param error {Function} callback to execute when if dependencies have a errors (optional)
1248 */
1249 using: function ( dependencies, ready, error ) {
1250 var tod = typeof dependencies;
1251 // Validate input
1252 if ( tod !== 'object' && tod !== 'string' ) {
1253 throw new Error( 'dependencies must be a string or an array, not a ' + tod );
1254 }
1255 // Allow calling with a single dependency as a string
1256 if ( tod === 'string' ) {
1257 dependencies = [dependencies];
1258 }
1259 // Resolve entire dependency map
1260 dependencies = resolve( dependencies );
1261 if ( allReady( dependencies ) ) {
1262 // Run ready immediately
1263 if ( $.isFunction( ready ) ) {
1264 ready();
1265 }
1266 } else if ( filter( ['error', 'missing'], dependencies ).length ) {
1267 // Execute error immediately if any dependencies have errors
1268 if ( $.isFunction( error ) ) {
1269 error( new Error( 'one or more dependencies have state "error" or "missing"' ),
1270 dependencies );
1271 }
1272 } else {
1273 // Not all dependencies are ready: queue up a request
1274 request( dependencies, ready, error );
1275 }
1276 },
1277
1278 /**
1279 * Loads an external script or one or more modules for future use
1280 *
1281 * @param modules {mixed} Either the name of a module, array of modules,
1282 * or a URL of an external script or style
1283 * @param type {String} mime-type to use if calling with a URL of an
1284 * external script or style; acceptable values are "text/css" and
1285 * "text/javascript"; if no type is provided, text/javascript is assumed.
1286 * @param async {Boolean} (optional) If true, load modules asynchronously
1287 * even if document ready has not yet occurred. If false (default),
1288 * block before document ready and load async after. If not set, true will
1289 * be assumed if loading a URL, and false will be assumed otherwise.
1290 */
1291 load: function ( modules, type, async ) {
1292 var filtered, m, module;
1293
1294 // Validate input
1295 if ( typeof modules !== 'object' && typeof modules !== 'string' ) {
1296 throw new Error( 'modules must be a string or an array, not a ' + typeof modules );
1297 }
1298 // Allow calling with an external url or single dependency as a string
1299 if ( typeof modules === 'string' ) {
1300 // Support adding arbitrary external scripts
1301 if ( /^(https?:)?\/\//.test( modules ) ) {
1302 if ( async === undefined ) {
1303 // Assume async for bug 34542
1304 async = true;
1305 }
1306 if ( type === 'text/css' ) {
1307 $( 'head' ).append( $( '<link>', {
1308 rel: 'stylesheet',
1309 type: 'text/css',
1310 href: modules
1311 } ) );
1312 return;
1313 }
1314 if ( type === 'text/javascript' || type === undefined ) {
1315 addScript( modules, null, async );
1316 return;
1317 }
1318 // Unknown type
1319 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type );
1320 }
1321 // Called with single module
1322 modules = [modules];
1323 }
1324
1325 // Filter out undefined modules, otherwise resolve() will throw
1326 // an exception for trying to load an undefined module.
1327 // Undefined modules are acceptable here in load(), because load() takes
1328 // an array of unrelated modules, whereas the modules passed to
1329 // using() are related and must all be loaded.
1330 for ( filtered = [], m = 0; m < modules.length; m += 1 ) {
1331 module = registry[modules[m]];
1332 if ( module !== undefined ) {
1333 if ( $.inArray( module.state, ['error', 'missing'] ) === -1 ) {
1334 filtered[filtered.length] = modules[m];
1335 }
1336 }
1337 }
1338
1339 if (filtered.length === 0) {
1340 return;
1341 }
1342 // Resolve entire dependency map
1343 filtered = resolve( filtered );
1344 // If all modules are ready, nothing to be done
1345 if ( allReady( filtered ) ) {
1346 return;
1347 }
1348 // If any modules have errors: also quit.
1349 if ( filter( ['error', 'missing'], filtered ).length ) {
1350 return;
1351 }
1352 // Since some modules are not yet ready, queue up a request.
1353 request( filtered, null, null, async );
1354 },
1355
1356 /**
1357 * Changes the state of a module
1358 *
1359 * @param module {String|Object} module name or object of module name/state pairs
1360 * @param state {String} state name
1361 */
1362 state: function ( module, state ) {
1363 var m;
1364
1365 if ( typeof module === 'object' ) {
1366 for ( m in module ) {
1367 mw.loader.state( m, module[m] );
1368 }
1369 return;
1370 }
1371 if ( registry[module] === undefined ) {
1372 mw.loader.register( module );
1373 }
1374 if ( $.inArray(state, ['ready', 'error', 'missing']) !== -1
1375 && registry[module].state !== state ) {
1376 // Make sure pending modules depending on this one get executed if their
1377 // dependencies are now fulfilled!
1378 registry[module].state = state;
1379 handlePending( module );
1380 } else {
1381 registry[module].state = state;
1382 }
1383 },
1384
1385 /**
1386 * Gets the version of a module
1387 *
1388 * @param module string name of module to get version for
1389 */
1390 getVersion: function ( module ) {
1391 if ( registry[module] !== undefined && registry[module].version !== undefined ) {
1392 return formatVersionNumber( registry[module].version );
1393 }
1394 return null;
1395 },
1396
1397 /**
1398 * @deprecated since 1.18 use mw.loader.getVersion() instead
1399 */
1400 version: function () {
1401 return mw.loader.getVersion.apply( mw.loader, arguments );
1402 },
1403
1404 /**
1405 * Gets the state of a module
1406 *
1407 * @param module string name of module to get state for
1408 */
1409 getState: function ( module ) {
1410 if ( registry[module] !== undefined && registry[module].state !== undefined ) {
1411 return registry[module].state;
1412 }
1413 return null;
1414 },
1415
1416 /**
1417 * Get names of all registered modules.
1418 *
1419 * @return {Array}
1420 */
1421 getModuleNames: function () {
1422 return $.map( registry, function ( i, key ) {
1423 return key;
1424 } );
1425 },
1426
1427 /**
1428 * For backwards-compatibility with Squid-cached pages. Loads mw.user
1429 */
1430 go: function () {
1431 mw.loader.load( 'mediawiki.user' );
1432 }
1433 };
1434 }() ),
1435
1436 /** HTML construction helper functions */
1437 html: ( function () {
1438 function escapeCallback( s ) {
1439 switch ( s ) {
1440 case "'":
1441 return '&#039;';
1442 case '"':
1443 return '&quot;';
1444 case '<':
1445 return '&lt;';
1446 case '>':
1447 return '&gt;';
1448 case '&':
1449 return '&amp;';
1450 }
1451 }
1452
1453 return {
1454 /**
1455 * Escape a string for HTML. Converts special characters to HTML entities.
1456 * @param s The string to escape
1457 */
1458 escape: function ( s ) {
1459 return s.replace( /['"<>&]/g, escapeCallback );
1460 },
1461
1462 /**
1463 * Wrapper object for raw HTML passed to mw.html.element().
1464 * @constructor
1465 */
1466 Raw: function ( value ) {
1467 this.value = value;
1468 },
1469
1470 /**
1471 * Wrapper object for CDATA element contents passed to mw.html.element()
1472 * @constructor
1473 */
1474 Cdata: function ( value ) {
1475 this.value = value;
1476 },
1477
1478 /**
1479 * Create an HTML element string, with safe escaping.
1480 *
1481 * @param name The tag name.
1482 * @param attrs An object with members mapping element names to values
1483 * @param contents The contents of the element. May be either:
1484 * - string: The string is escaped.
1485 * - null or undefined: The short closing form is used, e.g. <br/>.
1486 * - this.Raw: The value attribute is included without escaping.
1487 * - this.Cdata: The value attribute is included, and an exception is
1488 * thrown if it contains an illegal ETAGO delimiter.
1489 * See http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.3.2
1490 *
1491 * Example:
1492 * var h = mw.html;
1493 * return h.element( 'div', {},
1494 * new h.Raw( h.element( 'img', {src: '<'} ) ) );
1495 * Returns <div><img src="&lt;"/></div>
1496 */
1497 element: function ( name, attrs, contents ) {
1498 var v, attrName, s = '<' + name;
1499
1500 for ( attrName in attrs ) {
1501 v = attrs[attrName];
1502 // Convert name=true, to name=name
1503 if ( v === true ) {
1504 v = attrName;
1505 // Skip name=false
1506 } else if ( v === false ) {
1507 continue;
1508 }
1509 s += ' ' + attrName + '="' + this.escape( String( v ) ) + '"';
1510 }
1511 if ( contents === undefined || contents === null ) {
1512 // Self close tag
1513 s += '/>';
1514 return s;
1515 }
1516 // Regular open tag
1517 s += '>';
1518 switch ( typeof contents ) {
1519 case 'string':
1520 // Escaped
1521 s += this.escape( contents );
1522 break;
1523 case 'number':
1524 case 'boolean':
1525 // Convert to string
1526 s += String( contents );
1527 break;
1528 default:
1529 if ( contents instanceof this.Raw ) {
1530 // Raw HTML inclusion
1531 s += contents.value;
1532 } else if ( contents instanceof this.Cdata ) {
1533 // CDATA
1534 if ( /<\/[a-zA-z]/.test( contents.value ) ) {
1535 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
1536 }
1537 s += contents.value;
1538 } else {
1539 throw new Error( 'mw.html.element: Invalid type of contents' );
1540 }
1541 }
1542 s += '</' + name + '>';
1543 return s;
1544 }
1545 };
1546 }() ),
1547
1548 // Skeleton user object. mediawiki.user.js extends this
1549 user: {
1550 options: new Map(),
1551 tokens: new Map()
1552 }
1553 };
1554
1555 }( jQuery ) );
1556
1557 // Alias $j to jQuery for backwards compatibility
1558 window.$j = jQuery;
1559
1560 // Attach to window and globally alias
1561 window.mw = window.mediaWiki = mw;
1562
1563 // Auto-register from pre-loaded startup scripts
1564 if ( jQuery.isFunction( window.startUp ) ) {
1565 window.startUp();
1566 window.startUp = undefined;
1567 }