Merge "Declare visibility for class properties in DatabaseUtility.php"
[lhc/web/wiklou.git] / resources / mediawiki / mediawiki.js
1 /**
2 * Base library for MediaWiki.
3 *
4 * @class mw
5 * @alternateClassName mediaWiki
6 * @singleton
7 */
8
9 var mw = ( function ( $, undefined ) {
10 'use strict';
11
12 /* Private Members */
13
14 var hasOwn = Object.prototype.hasOwnProperty,
15 slice = Array.prototype.slice,
16 trackCallbacks = $.Callbacks( 'memory' ),
17 trackQueue = [];
18
19 /**
20 * Log a message to window.console, if possible. Useful to force logging of some
21 * errors that are otherwise hard to detect (I.e., this logs also in production mode).
22 * Gets console references in each invocation, so that delayed debugging tools work
23 * fine. No need for optimization here, which would only result in losing logs.
24 *
25 * @private
26 * @method log_
27 * @param {string} msg text for the log entry.
28 * @param {Error} [e]
29 */
30 function log( msg, e ) {
31 var console = window.console;
32 if ( console && console.log ) {
33 console.log( msg );
34 // If we have an exception object, log it through .error() to trigger
35 // proper stacktraces in browsers that support it. There are no (known)
36 // browsers that don't support .error(), that do support .log() and
37 // have useful exception handling through .log().
38 if ( e && console.error ) {
39 console.error( String( e ), e );
40 }
41 }
42 }
43
44 /* Object constructors */
45
46 /**
47 * Creates an object that can be read from or written to from prototype functions
48 * that allow both single and multiple variables at once.
49 *
50 * @example
51 *
52 * var addies, wanted, results;
53 *
54 * // Create your address book
55 * addies = new mw.Map();
56 *
57 * // This data could be coming from an external source (eg. API/AJAX)
58 * addies.set( {
59 * 'John Doe' : '10 Wall Street, New York, USA',
60 * 'Jane Jackson' : '21 Oxford St, London, UK',
61 * 'Dominique van Halen' : 'Kalverstraat 7, Amsterdam, NL'
62 * } );
63 *
64 * wanted = ['Dominique van Halen', 'George Johnson', 'Jane Jackson'];
65 *
66 * // You can detect missing keys first
67 * if ( !addies.exists( wanted ) ) {
68 * // One or more are missing (in this case: "George Johnson")
69 * mw.log( 'One or more names were not found in your address book' );
70 * }
71 *
72 * // Or just let it give you what it can
73 * results = addies.get( wanted, 'Middle of Nowhere, Alaska, US' );
74 * mw.log( results['Jane Jackson'] ); // "21 Oxford St, London, UK"
75 * mw.log( results['George Johnson'] ); // "Middle of Nowhere, Alaska, US"
76 *
77 * @class mw.Map
78 *
79 * @constructor
80 * @param {Object|boolean} [values] Value-bearing object to map, or boolean
81 * true to map over the global object. Defaults to an empty object.
82 */
83 function Map( values ) {
84 this.values = values === true ? window : ( values || {} );
85 return this;
86 }
87
88 Map.prototype = {
89 /**
90 * Get the value of one or multiple a keys.
91 *
92 * If called with no arguments, all values will be returned.
93 *
94 * @param {string|Array} selection String key or array of keys to get values for.
95 * @param {Mixed} [fallback] Value to use in case key(s) do not exist.
96 * @return mixed If selection was a string returns the value or null,
97 * If selection was an array, returns an object of key/values (value is null if not found),
98 * If selection was not passed or invalid, will return the 'values' object member (be careful as
99 * objects are always passed by reference in JavaScript!).
100 * @return {string|Object|null} Values as a string or object, null if invalid/inexistant.
101 */
102 get: function ( selection, fallback ) {
103 var results, i;
104 // If we only do this in the `return` block, it'll fail for the
105 // call to get() from the mutli-selection block.
106 fallback = arguments.length > 1 ? fallback : null;
107
108 if ( $.isArray( selection ) ) {
109 selection = slice.call( selection );
110 results = {};
111 for ( i = 0; i < selection.length; i++ ) {
112 results[selection[i]] = this.get( selection[i], fallback );
113 }
114 return results;
115 }
116
117 if ( typeof selection === 'string' ) {
118 if ( !hasOwn.call( this.values, selection ) ) {
119 return fallback;
120 }
121 return this.values[selection];
122 }
123
124 if ( selection === undefined ) {
125 return this.values;
126 }
127
128 // invalid selection key
129 return null;
130 },
131
132 /**
133 * Sets one or multiple key/value pairs.
134 *
135 * @param {string|Object} selection String key to set value for, or object mapping keys to values.
136 * @param {Mixed} [value] Value to set (optional, only in use when key is a string)
137 * @return {Boolean} This returns true on success, false on failure.
138 */
139 set: function ( selection, value ) {
140 var s;
141
142 if ( $.isPlainObject( selection ) ) {
143 for ( s in selection ) {
144 this.values[s] = selection[s];
145 }
146 return true;
147 }
148 if ( typeof selection === 'string' && arguments.length > 1 ) {
149 this.values[selection] = value;
150 return true;
151 }
152 return false;
153 },
154
155 /**
156 * Checks if one or multiple keys exist.
157 *
158 * @param {Mixed} selection String key or array of keys to check
159 * @return {boolean} Existence of key(s)
160 */
161 exists: function ( selection ) {
162 var s;
163
164 if ( $.isArray( selection ) ) {
165 for ( s = 0; s < selection.length; s++ ) {
166 if ( typeof selection[s] !== 'string' || !hasOwn.call( this.values, selection[s] ) ) {
167 return false;
168 }
169 }
170 return true;
171 }
172 return typeof selection === 'string' && hasOwn.call( this.values, selection );
173 }
174 };
175
176 /**
177 * Object constructor for messages.
178 *
179 * Similar to the Message class in MediaWiki PHP.
180 *
181 * Format defaults to 'text'.
182 *
183 * @class mw.Message
184 *
185 * @constructor
186 * @param {mw.Map} map Message storage
187 * @param {string} key
188 * @param {Array} [parameters]
189 */
190 function Message( map, key, parameters ) {
191 this.format = 'text';
192 this.map = map;
193 this.key = key;
194 this.parameters = parameters === undefined ? [] : slice.call( parameters );
195 return this;
196 }
197
198 Message.prototype = {
199 /**
200 * Simple message parser, does $N replacement and nothing else.
201 *
202 * This may be overridden to provide a more complex message parser.
203 *
204 * The primary override is in mediawiki.jqueryMsg.
205 *
206 * This function will not be called for nonexistent messages.
207 */
208 parser: function () {
209 var parameters = this.parameters;
210 return this.map.get( this.key ).replace( /\$(\d+)/g, function ( str, match ) {
211 var index = parseInt( match, 10 ) - 1;
212 return parameters[index] !== undefined ? parameters[index] : '$' + match;
213 } );
214 },
215
216 /**
217 * Appends (does not replace) parameters for replacement to the .parameters property.
218 *
219 * @param {Array} parameters
220 * @chainable
221 */
222 params: function ( parameters ) {
223 var i;
224 for ( i = 0; i < parameters.length; i += 1 ) {
225 this.parameters.push( parameters[i] );
226 }
227 return this;
228 },
229
230 /**
231 * Converts message object to its string form based on the state of format.
232 *
233 * @return {string} Message as a string in the current form or `<key>` if key does not exist.
234 */
235 toString: function () {
236 var text;
237
238 if ( !this.exists() ) {
239 // Use <key> as text if key does not exist
240 if ( this.format === 'escaped' || this.format === 'parse' ) {
241 // format 'escaped' and 'parse' need to have the brackets and key html escaped
242 return mw.html.escape( '<' + this.key + '>' );
243 }
244 return '<' + this.key + '>';
245 }
246
247 if ( this.format === 'plain' || this.format === 'text' || this.format === 'parse' ) {
248 text = this.parser();
249 }
250
251 if ( this.format === 'escaped' ) {
252 text = this.parser();
253 text = mw.html.escape( text );
254 }
255
256 return text;
257 },
258
259 /**
260 * Changes format to 'parse' and converts message to string
261 *
262 * If jqueryMsg is loaded, this parses the message text from wikitext
263 * (where supported) to HTML
264 *
265 * Otherwise, it is equivalent to plain.
266 *
267 * @return {string} String form of parsed message
268 */
269 parse: function () {
270 this.format = 'parse';
271 return this.toString();
272 },
273
274 /**
275 * Changes format to 'plain' and converts message to string
276 *
277 * This substitutes parameters, but otherwise does not change the
278 * message text.
279 *
280 * @return {string} String form of plain message
281 */
282 plain: function () {
283 this.format = 'plain';
284 return this.toString();
285 },
286
287 /**
288 * Changes format to 'text' and converts message to string
289 *
290 * If jqueryMsg is loaded, {{-transformation is done where supported
291 * (such as {{plural:}}, {{gender:}}, {{int:}}).
292 *
293 * Otherwise, it is equivalent to plain.
294 */
295 text: function () {
296 this.format = 'text';
297 return this.toString();
298 },
299
300 /**
301 * Changes the format to 'escaped' and converts message to string
302 *
303 * This is equivalent to using the 'text' format (see text method), then
304 * HTML-escaping the output.
305 *
306 * @return {string} String form of html escaped message
307 */
308 escaped: function () {
309 this.format = 'escaped';
310 return this.toString();
311 },
312
313 /**
314 * Checks if message exists
315 *
316 * @see mw.Map#exists
317 * @return {boolean}
318 */
319 exists: function () {
320 return this.map.exists( this.key );
321 }
322 };
323
324 /**
325 * @class mw
326 */
327 return {
328 /* Public Members */
329
330 /**
331 * Get the current time, measured in milliseconds since January 1, 1970 (UTC).
332 *
333 * On browsers that implement the Navigation Timing API, this function will produce floating-point
334 * values with microsecond precision that are guaranteed to be monotonic. On all other browsers,
335 * it will fall back to using `Date`.
336 *
337 * @returns {number} Current time
338 */
339 now: ( function () {
340 var perf = window.performance,
341 navStart = perf && perf.timing && perf.timing.navigationStart;
342 return navStart && typeof perf.now === 'function' ?
343 function () { return navStart + perf.now(); } :
344 function () { return +new Date(); };
345 }() ),
346
347 /**
348 * Track an analytic event.
349 *
350 * This method provides a generic means for MediaWiki JavaScript code to capture state
351 * information for analysis. Each logged event specifies a string topic name that describes
352 * the kind of event that it is. Topic names consist of dot-separated path components,
353 * arranged from most general to most specific. Each path component should have a clear and
354 * well-defined purpose.
355 *
356 * Data handlers are registered via `mw.trackSubscribe`, and receive the full set of
357 * events that match their subcription, including those that fired before the handler was
358 * bound.
359 *
360 * @param {string} topic Topic name
361 * @param {Object} [data] Data describing the event, encoded as an object
362 */
363 track: function ( topic, data ) {
364 trackQueue.push( { topic: topic, timeStamp: mw.now(), data: data } );
365 trackCallbacks.fire( trackQueue );
366 },
367
368 /**
369 * Register a handler for subset of analytic events, specified by topic
370 *
371 * Handlers will be called once for each tracked event, including any events that fired before the
372 * handler was registered; 'this' is set to a plain object with a 'timeStamp' property indicating
373 * the exact time at which the event fired, a string 'topic' property naming the event, and a
374 * 'data' property which is an object of event-specific data. The event topic and event data are
375 * also passed to the callback as the first and second arguments, respectively.
376 *
377 * @param {string} topic Handle events whose name starts with this string prefix
378 * @param {Function} callback Handler to call for each matching tracked event
379 */
380 trackSubscribe: function ( topic, callback ) {
381 var seen = 0;
382
383 trackCallbacks.add( function ( trackQueue ) {
384 var event;
385 for ( ; seen < trackQueue.length; seen++ ) {
386 event = trackQueue[ seen ];
387 if ( event.topic.indexOf( topic ) === 0 ) {
388 callback.call( event, event.topic, event.data );
389 }
390 }
391 } );
392 },
393
394 /**
395 * Dummy placeholder for {@link mw.log}
396 * @method
397 */
398 log: ( function () {
399 var log = function () {};
400 log.warn = function () {};
401 log.deprecate = function ( obj, key, val ) {
402 obj[key] = val;
403 };
404 return log;
405 }() ),
406
407 // Make the Map constructor publicly available.
408 Map: Map,
409
410 // Make the Message constructor publicly available.
411 Message: Message,
412
413 /**
414 * Map of configuration values
415 *
416 * Check out [the complete list of configuration values](https://www.mediawiki.org/wiki/Manual:Interface/JavaScript#mw.config)
417 * on MediaWiki.org.
418 *
419 * If `$wgLegacyJavaScriptGlobals` is true, this Map will put its values in the
420 * global window object.
421 *
422 * @property {mw.Map} config
423 */
424 // Dummy placeholder. Re-assigned in ResourceLoaderStartupModule with an instance of `mw.Map`.
425 config: null,
426
427 /**
428 * Empty object that plugins can be installed in.
429 * @property
430 */
431 libs: {},
432
433 /**
434 * Access container for deprecated functionality that can be moved from
435 * from their legacy location and attached to this object (e.g. a global
436 * function that is deprecated and as stop-gap can be exposed through here).
437 *
438 * This was reserved for future use but never ended up being used.
439 *
440 * @deprecated since 1.22: Let deprecated identifiers keep their original name
441 * and use mw.log#deprecate to create an access container for tracking.
442 * @property
443 */
444 legacy: {},
445
446 /**
447 * Localization system
448 * @property {mw.Map}
449 */
450 messages: new Map(),
451
452 /* Public Methods */
453
454 /**
455 * Get a message object.
456 *
457 * Similar to wfMessage() in MediaWiki PHP.
458 *
459 * @param {string} key Key of message to get
460 * @param {Mixed...} parameters Parameters for the $N replacements in messages.
461 * @return {mw.Message}
462 */
463 message: function ( key ) {
464 // Variadic arguments
465 var parameters = slice.call( arguments, 1 );
466 return new Message( mw.messages, key, parameters );
467 },
468
469 /**
470 * Get a message string using 'text' format.
471 *
472 * Similar to wfMsg() in MediaWiki PHP.
473 *
474 * @see mw.Message
475 * @param {string} key Key of message to get
476 * @param {Mixed...} parameters Parameters for the $N replacements in messages.
477 * @return {string}
478 */
479 msg: function () {
480 return mw.message.apply( mw.message, arguments ).toString();
481 },
482
483 /**
484 * Client-side module loader which integrates with the MediaWiki ResourceLoader
485 * @class mw.loader
486 * @singleton
487 */
488 loader: ( function () {
489
490 /* Private Members */
491
492 /**
493 * Mapping of registered modules
494 *
495 * The jquery module is pre-registered, because it must have already
496 * been provided for this object to have been built, and in debug mode
497 * jquery would have been provided through a unique loader request,
498 * making it impossible to hold back registration of jquery until after
499 * mediawiki.
500 *
501 * For exact details on support for script, style and messages, look at
502 * mw.loader.implement.
503 *
504 * Format:
505 * {
506 * 'moduleName': {
507 * 'version': ############## (unix timestamp),
508 * 'dependencies': ['required.foo', 'bar.also', ...], (or) function () {}
509 * 'group': 'somegroup', (or) null,
510 * 'source': 'local', 'someforeignwiki', (or) null
511 * 'state': 'registered', 'loaded', 'loading', 'ready', 'error' or 'missing'
512 * 'script': ...,
513 * 'style': ...,
514 * 'messages': { 'key': 'value' },
515 * }
516 * }
517 *
518 * @property
519 * @private
520 */
521 var registry = {},
522 //
523 // Mapping of sources, keyed by source-id, values are objects.
524 // Format:
525 // {
526 // 'sourceId': {
527 // 'loadScript': 'http://foo.bar/w/load.php'
528 // }
529 // }
530 //
531 sources = {},
532 // List of modules which will be loaded as when ready
533 batch = [],
534 // List of modules to be loaded
535 queue = [],
536 // List of callback functions waiting for modules to be ready to be called
537 jobs = [],
538 // Selector cache for the marker element. Use getMarker() to get/use the marker!
539 $marker = null,
540 // Buffer for addEmbeddedCSS.
541 cssBuffer = '',
542 // Callbacks for addEmbeddedCSS.
543 cssCallbacks = $.Callbacks();
544
545 /* Private methods */
546
547 function getMarker() {
548 // Cached ?
549 if ( $marker ) {
550 return $marker;
551 }
552
553 $marker = $( 'meta[name="ResourceLoaderDynamicStyles"]' );
554 if ( $marker.length ) {
555 return $marker;
556 }
557 mw.log( 'getMarker> No <meta name="ResourceLoaderDynamicStyles"> found, inserting dynamically.' );
558 $marker = $( '<meta>' ).attr( 'name', 'ResourceLoaderDynamicStyles' ).appendTo( 'head' );
559
560 return $marker;
561 }
562
563 /**
564 * Create a new style tag and add it to the DOM.
565 *
566 * @private
567 * @param {string} text CSS text
568 * @param {HTMLElement|jQuery} [nextnode=document.head] The element where the style tag should be
569 * inserted before. Otherwise it will be appended to `<head>`.
570 * @return {HTMLElement} Reference to the created `<style>` element.
571 */
572 function newStyleTag( text, nextnode ) {
573 var s = document.createElement( 'style' );
574 // Insert into document before setting cssText (bug 33305)
575 if ( nextnode ) {
576 // Must be inserted with native insertBefore, not $.fn.before.
577 // When using jQuery to insert it, like $nextnode.before( s ),
578 // then IE6 will throw "Access is denied" when trying to append
579 // to .cssText later. Some kind of weird security measure.
580 // http://stackoverflow.com/q/12586482/319266
581 // Works: jsfiddle.net/zJzMy/1
582 // Fails: jsfiddle.net/uJTQz
583 // Works again: http://jsfiddle.net/Azr4w/ (diff: the next 3 lines)
584 if ( nextnode.jquery ) {
585 nextnode = nextnode.get( 0 );
586 }
587 nextnode.parentNode.insertBefore( s, nextnode );
588 } else {
589 document.getElementsByTagName( 'head' )[0].appendChild( s );
590 }
591 if ( s.styleSheet ) {
592 // IE
593 s.styleSheet.cssText = text;
594 } else {
595 // Other browsers.
596 // (Safari sometimes borks on non-string values,
597 // play safe by casting to a string, just in case.)
598 s.appendChild( document.createTextNode( String( text ) ) );
599 }
600 return s;
601 }
602
603 /**
604 * Checks whether it is safe to add this css to a stylesheet.
605 *
606 * @private
607 * @param {string} cssText
608 * @return {boolean} False if a new one must be created.
609 */
610 function canExpandStylesheetWith( cssText ) {
611 // Makes sure that cssText containing `@import`
612 // rules will end up in a new stylesheet (as those only work when
613 // placed at the start of a stylesheet; bug 35562).
614 return cssText.indexOf( '@import' ) === -1;
615 }
616
617 /**
618 * Add a bit of CSS text to the current browser page.
619 *
620 * The CSS will be appended to an existing ResourceLoader-created `<style>` tag
621 * or create a new one based on whether the given `cssText` is safe for extension.
622 *
623 * @param {string} [cssText=cssBuffer] If called without cssText,
624 * the internal buffer will be inserted instead.
625 * @param {Function} [callback]
626 */
627 function addEmbeddedCSS( cssText, callback ) {
628 var $style, styleEl;
629
630 if ( callback ) {
631 cssCallbacks.add( callback );
632 }
633
634 // Yield once before inserting the <style> tag. There are likely
635 // more calls coming up which we can combine this way.
636 // Appending a stylesheet and waiting for the browser to repaint
637 // is fairly expensive, this reduces it (bug 45810)
638 if ( cssText ) {
639 // Be careful not to extend the buffer with css that needs a new stylesheet
640 if ( !cssBuffer || canExpandStylesheetWith( cssText ) ) {
641 // Linebreak for somewhat distinguishable sections
642 // (the rl-cachekey comment separating each)
643 cssBuffer += '\n' + cssText;
644 // TODO: Use requestAnimationFrame in the future which will
645 // perform even better by not injecting styles while the browser
646 // is paiting.
647 setTimeout( function () {
648 // Can't pass addEmbeddedCSS to setTimeout directly because Firefox
649 // (below version 13) has the non-standard behaviour of passing a
650 // numerical "lateness" value as first argument to this callback
651 // http://benalman.com/news/2009/07/the-mysterious-firefox-settime/
652 addEmbeddedCSS();
653 } );
654 return;
655 }
656
657 // This is a delayed call and we got a buffer still
658 } else if ( cssBuffer ) {
659 cssText = cssBuffer;
660 cssBuffer = '';
661 } else {
662 // This is a delayed call, but buffer is already cleared by
663 // another delayed call.
664 return;
665 }
666
667 // By default, always create a new <style>. Appending text
668 // to a <style> tag means the contents have to be re-parsed (bug 45810).
669 // Except, of course, in IE below 9, in there we default to
670 // re-using and appending to a <style> tag due to the
671 // IE stylesheet limit (bug 31676).
672 if ( 'documentMode' in document && document.documentMode <= 9 ) {
673
674 $style = getMarker().prev();
675 // Verify that the the element before Marker actually is a
676 // <style> tag and one that came from ResourceLoader
677 // (not some other style tag or even a `<meta>` or `<script>`).
678 if ( $style.data( 'ResourceLoaderDynamicStyleTag' ) === true ) {
679 // There's already a dynamic <style> tag present and
680 // canExpandStylesheetWith() gave a green light to append more to it.
681 styleEl = $style.get( 0 );
682 if ( styleEl.styleSheet ) {
683 try {
684 styleEl.styleSheet.cssText += cssText; // IE
685 } catch ( e ) {
686 log( 'addEmbeddedCSS fail', e );
687 }
688 } else {
689 styleEl.appendChild( document.createTextNode( String( cssText ) ) );
690 }
691 cssCallbacks.fire().empty();
692 return;
693 }
694 }
695
696 $( newStyleTag( cssText, getMarker() ) ).data( 'ResourceLoaderDynamicStyleTag', true );
697
698 cssCallbacks.fire().empty();
699 }
700
701 /**
702 * Generates an ISO8601 "basic" string from a UNIX timestamp
703 * @private
704 */
705 function formatVersionNumber( timestamp ) {
706 var d = new Date();
707 function pad( a, b, c ) {
708 return [a < 10 ? '0' + a : a, b < 10 ? '0' + b : b, c < 10 ? '0' + c : c].join( '' );
709 }
710 d.setTime( timestamp * 1000 );
711 return [
712 pad( d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate() ), 'T',
713 pad( d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds() ), 'Z'
714 ].join( '' );
715 }
716
717 /**
718 * Resolves dependencies and detects circular references.
719 *
720 * @private
721 * @param {string} module Name of the top-level module whose dependencies shall be
722 * resolved and sorted.
723 * @param {Array} resolved Returns a topological sort of the given module and its
724 * dependencies, such that later modules depend on earlier modules. The array
725 * contains the module names. If the array contains already some module names,
726 * this function appends its result to the pre-existing array.
727 * @param {Object} [unresolved] Hash used to track the current dependency
728 * chain; used to report loops in the dependency graph.
729 * @throws {Error} If any unregistered module or a dependency loop is encountered
730 */
731 function sortDependencies( module, resolved, unresolved ) {
732 var n, deps, len;
733
734 if ( registry[module] === undefined ) {
735 throw new Error( 'Unknown dependency: ' + module );
736 }
737 // Resolves dynamic loader function and replaces it with its own results
738 if ( $.isFunction( registry[module].dependencies ) ) {
739 registry[module].dependencies = registry[module].dependencies();
740 // Ensures the module's dependencies are always in an array
741 if ( typeof registry[module].dependencies !== 'object' ) {
742 registry[module].dependencies = [registry[module].dependencies];
743 }
744 }
745 if ( $.inArray( module, resolved ) !== -1 ) {
746 // Module already resolved; nothing to do.
747 return;
748 }
749 // unresolved is optional, supply it if not passed in
750 if ( !unresolved ) {
751 unresolved = {};
752 }
753 // Tracks down dependencies
754 deps = registry[module].dependencies;
755 len = deps.length;
756 for ( n = 0; n < len; n += 1 ) {
757 if ( $.inArray( deps[n], resolved ) === -1 ) {
758 if ( unresolved[deps[n]] ) {
759 throw new Error(
760 'Circular reference detected: ' + module +
761 ' -> ' + deps[n]
762 );
763 }
764
765 // Add to unresolved
766 unresolved[module] = true;
767 sortDependencies( deps[n], resolved, unresolved );
768 delete unresolved[module];
769 }
770 }
771 resolved[resolved.length] = module;
772 }
773
774 /**
775 * Gets a list of module names that a module depends on in their proper dependency
776 * order.
777 *
778 * @private
779 * @param {string} module Module name or array of string module names
780 * @return {Array} list of dependencies, including 'module'.
781 * @throws {Error} If circular reference is detected
782 */
783 function resolve( module ) {
784 var m, resolved;
785
786 // Allow calling with an array of module names
787 if ( $.isArray( module ) ) {
788 resolved = [];
789 for ( m = 0; m < module.length; m += 1 ) {
790 sortDependencies( module[m], resolved );
791 }
792 return resolved;
793 }
794
795 if ( typeof module === 'string' ) {
796 resolved = [];
797 sortDependencies( module, resolved );
798 return resolved;
799 }
800
801 throw new Error( 'Invalid module argument: ' + module );
802 }
803
804 /**
805 * Narrows a list of module names down to those matching a specific
806 * state (see comment on top of this scope for a list of valid states).
807 * One can also filter for 'unregistered', which will return the
808 * modules names that don't have a registry entry.
809 *
810 * @private
811 * @param {string|string[]} states Module states to filter by
812 * @param {Array} [modules] List of module names to filter (optional, by default the entire
813 * registry is used)
814 * @return {Array} List of filtered module names
815 */
816 function filter( states, modules ) {
817 var list, module, s, m;
818
819 // Allow states to be given as a string
820 if ( typeof states === 'string' ) {
821 states = [states];
822 }
823 // If called without a list of modules, build and use a list of all modules
824 list = [];
825 if ( modules === undefined ) {
826 modules = [];
827 for ( module in registry ) {
828 modules[modules.length] = module;
829 }
830 }
831 // Build a list of modules which are in one of the specified states
832 for ( s = 0; s < states.length; s += 1 ) {
833 for ( m = 0; m < modules.length; m += 1 ) {
834 if ( registry[modules[m]] === undefined ) {
835 // Module does not exist
836 if ( states[s] === 'unregistered' ) {
837 // OK, undefined
838 list[list.length] = modules[m];
839 }
840 } else {
841 // Module exists, check state
842 if ( registry[modules[m]].state === states[s] ) {
843 // OK, correct state
844 list[list.length] = modules[m];
845 }
846 }
847 }
848 }
849 return list;
850 }
851
852 /**
853 * Determine whether all dependencies are in state 'ready', which means we may
854 * execute the module or job now.
855 *
856 * @private
857 * @param {Array} dependencies Dependencies (module names) to be checked.
858 * @return {boolean} True if all dependencies are in state 'ready', false otherwise
859 */
860 function allReady( dependencies ) {
861 return filter( 'ready', dependencies ).length === dependencies.length;
862 }
863
864 /**
865 * A module has entered state 'ready', 'error', or 'missing'. Automatically update pending jobs
866 * and modules that depend upon this module. if the given module failed, propagate the 'error'
867 * state up the dependency tree; otherwise, execute all jobs/modules that now have all their
868 * dependencies satisfied. On jobs depending on a failed module, run the error callback, if any.
869 *
870 * @private
871 * @param {string} module Name of module that entered one of the states 'ready', 'error', or 'missing'.
872 */
873 function handlePending( module ) {
874 var j, job, hasErrors, m, stateChange;
875
876 // Modules.
877 if ( $.inArray( registry[module].state, ['error', 'missing'] ) !== -1 ) {
878 // If the current module failed, mark all dependent modules also as failed.
879 // Iterate until steady-state to propagate the error state upwards in the
880 // dependency tree.
881 do {
882 stateChange = false;
883 for ( m in registry ) {
884 if ( $.inArray( registry[m].state, ['error', 'missing'] ) === -1 ) {
885 if ( filter( ['error', 'missing'], registry[m].dependencies ).length > 0 ) {
886 registry[m].state = 'error';
887 stateChange = true;
888 }
889 }
890 }
891 } while ( stateChange );
892 }
893
894 // Execute all jobs whose dependencies are either all satisfied or contain at least one failed module.
895 for ( j = 0; j < jobs.length; j += 1 ) {
896 hasErrors = filter( ['error', 'missing'], jobs[j].dependencies ).length > 0;
897 if ( hasErrors || allReady( jobs[j].dependencies ) ) {
898 // All dependencies satisfied, or some have errors
899 job = jobs[j];
900 jobs.splice( j, 1 );
901 j -= 1;
902 try {
903 if ( hasErrors ) {
904 if ( $.isFunction( job.error ) ) {
905 job.error( new Error( 'Module ' + module + ' has failed dependencies' ), [module] );
906 }
907 } else {
908 if ( $.isFunction( job.ready ) ) {
909 job.ready();
910 }
911 }
912 } catch ( e ) {
913 // A user-defined callback raised an exception.
914 // Swallow it to protect our state machine!
915 log( 'Exception thrown by job.error', e );
916 }
917 }
918 }
919
920 if ( registry[module].state === 'ready' ) {
921 // The current module became 'ready'. Set it in the module store, and recursively execute all
922 // dependent modules that are loaded and now have all dependencies satisfied.
923 mw.loader.store.set( module, registry[module] );
924 for ( m in registry ) {
925 if ( registry[m].state === 'loaded' && allReady( registry[m].dependencies ) ) {
926 execute( m );
927 }
928 }
929 }
930 }
931
932 /**
933 * Adds a script tag to the DOM, either using document.write or low-level DOM manipulation,
934 * depending on whether document-ready has occurred yet and whether we are in async mode.
935 *
936 * @private
937 * @param {string} src URL to script, will be used as the src attribute in the script tag
938 * @param {Function} [callback] Callback which will be run when the script is done
939 */
940 function addScript( src, callback, async ) {
941 /*jshint evil:true */
942 var script, head, done;
943
944 // Using isReady directly instead of storing it locally from
945 // a $.fn.ready callback (bug 31895).
946 if ( $.isReady || async ) {
947 // Can't use jQuery.getScript because that only uses <script> for cross-domain,
948 // it uses XHR and eval for same-domain scripts, which we don't want because it
949 // messes up line numbers.
950 // The below is based on jQuery ([jquery@1.8.2]/src/ajax/script.js)
951
952 // IE-safe way of getting the <head>. document.head isn't supported
953 // in old IE, and doesn't work when in the <head>.
954 done = false;
955 head = document.getElementsByTagName( 'head' )[0] || document.body;
956
957 script = document.createElement( 'script' );
958 script.async = true;
959 script.src = src;
960 if ( $.isFunction( callback ) ) {
961 script.onload = script.onreadystatechange = function () {
962 if (
963 !done
964 && (
965 !script.readyState
966 || /loaded|complete/.test( script.readyState )
967 )
968 ) {
969 done = true;
970
971 // Handle memory leak in IE
972 script.onload = script.onreadystatechange = null;
973
974 // Detach the element from the document
975 if ( script.parentNode ) {
976 script.parentNode.removeChild( script );
977 }
978
979 // Dereference the element from javascript
980 script = undefined;
981
982 callback();
983 }
984 };
985 }
986
987 if ( window.opera ) {
988 // Appending to the <head> blocks rendering completely in Opera,
989 // so append to the <body> after document ready. This means the
990 // scripts only start loading after the document has been rendered,
991 // but so be it. Opera users don't deserve faster web pages if their
992 // browser makes it impossible.
993 $( function () {
994 document.body.appendChild( script );
995 } );
996 } else {
997 head.appendChild( script );
998 }
999 } else {
1000 document.write( mw.html.element( 'script', { 'src': src }, '' ) );
1001 if ( $.isFunction( callback ) ) {
1002 // Document.write is synchronous, so this is called when it's done
1003 // FIXME: that's a lie. doc.write isn't actually synchronous
1004 callback();
1005 }
1006 }
1007 }
1008
1009 /**
1010 * Executes a loaded module, making it ready to use
1011 *
1012 * @private
1013 * @param {string} module Module name to execute
1014 */
1015 function execute( module ) {
1016 var key, value, media, i, urls, cssHandle, checkCssHandles,
1017 cssHandlesRegistered = false;
1018
1019 if ( registry[module] === undefined ) {
1020 throw new Error( 'Module has not been registered yet: ' + module );
1021 } else if ( registry[module].state === 'registered' ) {
1022 throw new Error( 'Module has not been requested from the server yet: ' + module );
1023 } else if ( registry[module].state === 'loading' ) {
1024 throw new Error( 'Module has not completed loading yet: ' + module );
1025 } else if ( registry[module].state === 'ready' ) {
1026 throw new Error( 'Module has already been executed: ' + module );
1027 }
1028
1029 /**
1030 * Define loop-function here for efficiency
1031 * and to avoid re-using badly scoped variables.
1032 * @ignore
1033 */
1034 function addLink( media, url ) {
1035 var el = document.createElement( 'link' );
1036 getMarker().before( el ); // IE: Insert in dom before setting href
1037 el.rel = 'stylesheet';
1038 if ( media && media !== 'all' ) {
1039 el.media = media;
1040 }
1041 el.href = url;
1042 }
1043
1044 function runScript() {
1045 var script, markModuleReady, nestedAddScript;
1046 try {
1047 script = registry[module].script;
1048 markModuleReady = function () {
1049 registry[module].state = 'ready';
1050 handlePending( module );
1051 };
1052 nestedAddScript = function ( arr, callback, async, i ) {
1053 // Recursively call addScript() in its own callback
1054 // for each element of arr.
1055 if ( i >= arr.length ) {
1056 // We're at the end of the array
1057 callback();
1058 return;
1059 }
1060
1061 addScript( arr[i], function () {
1062 nestedAddScript( arr, callback, async, i + 1 );
1063 }, async );
1064 };
1065
1066 if ( $.isArray( script ) ) {
1067 nestedAddScript( script, markModuleReady, registry[module].async, 0 );
1068 } else if ( $.isFunction( script ) ) {
1069 registry[module].state = 'ready';
1070 script( $ );
1071 handlePending( module );
1072 }
1073 } catch ( e ) {
1074 // This needs to NOT use mw.log because these errors are common in production mode
1075 // and not in debug mode, such as when a symbol that should be global isn't exported
1076 log( 'Exception thrown by ' + module, e );
1077 registry[module].state = 'error';
1078 handlePending( module );
1079 }
1080 }
1081
1082 // This used to be inside runScript, but since that is now fired asychronously
1083 // (after CSS is loaded) we need to set it here right away. It is crucial that
1084 // when execute() is called this is set synchronously, otherwise modules will get
1085 // executed multiple times as the registry will state that it isn't loading yet.
1086 registry[module].state = 'loading';
1087
1088 // Add localizations to message system
1089 if ( $.isPlainObject( registry[module].messages ) ) {
1090 mw.messages.set( registry[module].messages );
1091 }
1092
1093 if ( $.isReady || registry[module].async ) {
1094 // Make sure we don't run the scripts until all (potentially asynchronous)
1095 // stylesheet insertions have completed.
1096 ( function () {
1097 var pending = 0;
1098 checkCssHandles = function () {
1099 // cssHandlesRegistered ensures we don't take off too soon, e.g. when
1100 // one of the cssHandles is fired while we're still creating more handles.
1101 if ( cssHandlesRegistered && pending === 0 && runScript ) {
1102 runScript();
1103 runScript = undefined; // Revoke
1104 }
1105 };
1106 cssHandle = function () {
1107 var check = checkCssHandles;
1108 pending++;
1109 return function () {
1110 if (check) {
1111 pending--;
1112 check();
1113 check = undefined; // Revoke
1114 }
1115 };
1116 };
1117 }() );
1118 } else {
1119 // We are in blocking mode, and so we can't afford to wait for CSS
1120 cssHandle = function () {};
1121 // Run immediately
1122 checkCssHandles = runScript;
1123 }
1124
1125 // Process styles (see also mw.loader.implement)
1126 // * back-compat: { <media>: css }
1127 // * back-compat: { <media>: [url, ..] }
1128 // * { "css": [css, ..] }
1129 // * { "url": { <media>: [url, ..] } }
1130 if ( $.isPlainObject( registry[module].style ) ) {
1131 for ( key in registry[module].style ) {
1132 value = registry[module].style[key];
1133 media = undefined;
1134
1135 if ( key !== 'url' && key !== 'css' ) {
1136 // Backwards compatibility, key is a media-type
1137 if ( typeof value === 'string' ) {
1138 // back-compat: { <media>: css }
1139 // Ignore 'media' because it isn't supported (nor was it used).
1140 // Strings are pre-wrapped in "@media". The media-type was just ""
1141 // (because it had to be set to something).
1142 // This is one of the reasons why this format is no longer used.
1143 addEmbeddedCSS( value, cssHandle() );
1144 } else {
1145 // back-compat: { <media>: [url, ..] }
1146 media = key;
1147 key = 'bc-url';
1148 }
1149 }
1150
1151 // Array of css strings in key 'css',
1152 // or back-compat array of urls from media-type
1153 if ( $.isArray( value ) ) {
1154 for ( i = 0; i < value.length; i += 1 ) {
1155 if ( key === 'bc-url' ) {
1156 // back-compat: { <media>: [url, ..] }
1157 addLink( media, value[i] );
1158 } else if ( key === 'css' ) {
1159 // { "css": [css, ..] }
1160 addEmbeddedCSS( value[i], cssHandle() );
1161 }
1162 }
1163 // Not an array, but a regular object
1164 // Array of urls inside media-type key
1165 } else if ( typeof value === 'object' ) {
1166 // { "url": { <media>: [url, ..] } }
1167 for ( media in value ) {
1168 urls = value[media];
1169 for ( i = 0; i < urls.length; i += 1 ) {
1170 addLink( media, urls[i] );
1171 }
1172 }
1173 }
1174 }
1175 }
1176
1177 // Kick off.
1178 cssHandlesRegistered = true;
1179 checkCssHandles();
1180 }
1181
1182 /**
1183 * Adds a dependencies to the queue with optional callbacks to be run
1184 * when the dependencies are ready or fail
1185 *
1186 * @private
1187 * @param {string|string[]} dependencies Module name or array of string module names
1188 * @param {Function} [ready] Callback to execute when all dependencies are ready
1189 * @param {Function} [error] Callback to execute when any dependency fails
1190 * @param {boolean} [async] If true, load modules asynchronously even if
1191 * document ready has not yet occurred.
1192 */
1193 function request( dependencies, ready, error, async ) {
1194 var n;
1195
1196 // Allow calling by single module name
1197 if ( typeof dependencies === 'string' ) {
1198 dependencies = [dependencies];
1199 }
1200
1201 // Add ready and error callbacks if they were given
1202 if ( ready !== undefined || error !== undefined ) {
1203 jobs[jobs.length] = {
1204 'dependencies': filter(
1205 ['registered', 'loading', 'loaded'],
1206 dependencies
1207 ),
1208 'ready': ready,
1209 'error': error
1210 };
1211 }
1212
1213 // Queue up any dependencies that are registered
1214 dependencies = filter( ['registered'], dependencies );
1215 for ( n = 0; n < dependencies.length; n += 1 ) {
1216 if ( $.inArray( dependencies[n], queue ) === -1 ) {
1217 queue[queue.length] = dependencies[n];
1218 if ( async ) {
1219 // Mark this module as async in the registry
1220 registry[dependencies[n]].async = true;
1221 }
1222 }
1223 }
1224
1225 // Work the queue
1226 mw.loader.work();
1227 }
1228
1229 function sortQuery(o) {
1230 var sorted = {}, key, a = [];
1231 for ( key in o ) {
1232 if ( hasOwn.call( o, key ) ) {
1233 a.push( key );
1234 }
1235 }
1236 a.sort();
1237 for ( key = 0; key < a.length; key += 1 ) {
1238 sorted[a[key]] = o[a[key]];
1239 }
1240 return sorted;
1241 }
1242
1243 /**
1244 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
1245 * to a query string of the form foo.bar,baz|bar.baz,quux
1246 * @private
1247 */
1248 function buildModulesString( moduleMap ) {
1249 var arr = [], p, prefix;
1250 for ( prefix in moduleMap ) {
1251 p = prefix === '' ? '' : prefix + '.';
1252 arr.push( p + moduleMap[prefix].join( ',' ) );
1253 }
1254 return arr.join( '|' );
1255 }
1256
1257 /**
1258 * Asynchronously append a script tag to the end of the body
1259 * that invokes load.php
1260 * @private
1261 * @param {Object} moduleMap Module map, see #buildModulesString
1262 * @param {Object} currReqBase Object with other parameters (other than 'modules') to use in the request
1263 * @param {string} sourceLoadScript URL of load.php
1264 * @param {boolean} async If true, use an asynchronous request even if document ready has not yet occurred
1265 */
1266 function doRequest( moduleMap, currReqBase, sourceLoadScript, async ) {
1267 var request = $.extend(
1268 { modules: buildModulesString( moduleMap ) },
1269 currReqBase
1270 );
1271 request = sortQuery( request );
1272 // Asynchronously append a script tag to the end of the body
1273 // Append &* to avoid triggering the IE6 extension check
1274 addScript( sourceLoadScript + '?' + $.param( request ) + '&*', null, async );
1275 }
1276
1277 /* Public Members */
1278 return {
1279 /**
1280 * The module registry is exposed as an aid for debugging and inspecting page
1281 * state; it is not a public interface for modifying the registry.
1282 *
1283 * @see #registry
1284 * @property
1285 * @private
1286 */
1287 moduleRegistry: registry,
1288
1289 /**
1290 * @inheritdoc #newStyleTag
1291 * @method
1292 */
1293 addStyleTag: newStyleTag,
1294
1295 /**
1296 * Batch-request queued dependencies from the server.
1297 */
1298 work: function () {
1299 var reqBase, splits, maxQueryLength, q, b, bSource, bGroup, bSourceGroup,
1300 source, concatSource, group, g, i, modules, maxVersion, sourceLoadScript,
1301 currReqBase, currReqBaseLength, moduleMap, l,
1302 lastDotIndex, prefix, suffix, bytesAdded, async;
1303
1304 // Build a list of request parameters common to all requests.
1305 reqBase = {
1306 skin: mw.config.get( 'skin' ),
1307 lang: mw.config.get( 'wgUserLanguage' ),
1308 debug: mw.config.get( 'debug' )
1309 };
1310 // Split module batch by source and by group.
1311 splits = {};
1312 maxQueryLength = mw.config.get( 'wgResourceLoaderMaxQueryLength', -1 );
1313
1314 // Appends a list of modules from the queue to the batch
1315 for ( q = 0; q < queue.length; q += 1 ) {
1316 // Only request modules which are registered
1317 if ( registry[queue[q]] !== undefined && registry[queue[q]].state === 'registered' ) {
1318 // Prevent duplicate entries
1319 if ( $.inArray( queue[q], batch ) === -1 ) {
1320 batch[batch.length] = queue[q];
1321 // Mark registered modules as loading
1322 registry[queue[q]].state = 'loading';
1323 }
1324 }
1325 }
1326
1327 mw.loader.store.init();
1328 if ( mw.loader.store.enabled ) {
1329 concatSource = [];
1330 batch = $.grep( batch, function ( module ) {
1331 var source = mw.loader.store.get( module );
1332 if ( source ) {
1333 concatSource.push( source );
1334 return false;
1335 }
1336 return true;
1337 } );
1338 $.globalEval( concatSource.join( ';' ) );
1339 }
1340
1341 // Early exit if there's nothing to load...
1342 if ( !batch.length ) {
1343 return;
1344 }
1345
1346 // The queue has been processed into the batch, clear up the queue.
1347 queue = [];
1348
1349 // Always order modules alphabetically to help reduce cache
1350 // misses for otherwise identical content.
1351 batch.sort();
1352
1353 // Split batch by source and by group.
1354 for ( b = 0; b < batch.length; b += 1 ) {
1355 bSource = registry[batch[b]].source;
1356 bGroup = registry[batch[b]].group;
1357 if ( splits[bSource] === undefined ) {
1358 splits[bSource] = {};
1359 }
1360 if ( splits[bSource][bGroup] === undefined ) {
1361 splits[bSource][bGroup] = [];
1362 }
1363 bSourceGroup = splits[bSource][bGroup];
1364 bSourceGroup[bSourceGroup.length] = batch[b];
1365 }
1366
1367 // Clear the batch - this MUST happen before we append any
1368 // script elements to the body or it's possible that a script
1369 // will be locally cached, instantly load, and work the batch
1370 // again, all before we've cleared it causing each request to
1371 // include modules which are already loaded.
1372 batch = [];
1373
1374 for ( source in splits ) {
1375
1376 sourceLoadScript = sources[source].loadScript;
1377
1378 for ( group in splits[source] ) {
1379
1380 // Cache access to currently selected list of
1381 // modules for this group from this source.
1382 modules = splits[source][group];
1383
1384 // Calculate the highest timestamp
1385 maxVersion = 0;
1386 for ( g = 0; g < modules.length; g += 1 ) {
1387 if ( registry[modules[g]].version > maxVersion ) {
1388 maxVersion = registry[modules[g]].version;
1389 }
1390 }
1391
1392 currReqBase = $.extend( { version: formatVersionNumber( maxVersion ) }, reqBase );
1393 // For user modules append a user name to the request.
1394 if ( group === 'user' && mw.config.get( 'wgUserName' ) !== null ) {
1395 currReqBase.user = mw.config.get( 'wgUserName' );
1396 }
1397 currReqBaseLength = $.param( currReqBase ).length;
1398 async = true;
1399 // We may need to split up the request to honor the query string length limit,
1400 // so build it piece by piece.
1401 l = currReqBaseLength + 9; // '&modules='.length == 9
1402
1403 moduleMap = {}; // { prefix: [ suffixes ] }
1404
1405 for ( i = 0; i < modules.length; i += 1 ) {
1406 // Determine how many bytes this module would add to the query string
1407 lastDotIndex = modules[i].lastIndexOf( '.' );
1408 // Note that these substr() calls work even if lastDotIndex == -1
1409 prefix = modules[i].substr( 0, lastDotIndex );
1410 suffix = modules[i].substr( lastDotIndex + 1 );
1411 bytesAdded = moduleMap[prefix] !== undefined
1412 ? suffix.length + 3 // '%2C'.length == 3
1413 : modules[i].length + 3; // '%7C'.length == 3
1414
1415 // If the request would become too long, create a new one,
1416 // but don't create empty requests
1417 if ( maxQueryLength > 0 && !$.isEmptyObject( moduleMap ) && l + bytesAdded > maxQueryLength ) {
1418 // This request would become too long, create a new one
1419 // and fire off the old one
1420 doRequest( moduleMap, currReqBase, sourceLoadScript, async );
1421 moduleMap = {};
1422 async = true;
1423 l = currReqBaseLength + 9;
1424 }
1425 if ( moduleMap[prefix] === undefined ) {
1426 moduleMap[prefix] = [];
1427 }
1428 moduleMap[prefix].push( suffix );
1429 if ( !registry[modules[i]].async ) {
1430 // If this module is blocking, make the entire request blocking
1431 // This is slightly suboptimal, but in practice mixing of blocking
1432 // and async modules will only occur in debug mode.
1433 async = false;
1434 }
1435 l += bytesAdded;
1436 }
1437 // If there's anything left in moduleMap, request that too
1438 if ( !$.isEmptyObject( moduleMap ) ) {
1439 doRequest( moduleMap, currReqBase, sourceLoadScript, async );
1440 }
1441 }
1442 }
1443 },
1444
1445 /**
1446 * Register a source.
1447 *
1448 * @param {string} id Short lowercase a-Z string representing a source, only used internally.
1449 * @param {Object} props Object containing only the loadScript property which is a url to
1450 * the load.php location of the source.
1451 * @return {boolean}
1452 */
1453 addSource: function ( id, props ) {
1454 var source;
1455 // Allow multiple additions
1456 if ( typeof id === 'object' ) {
1457 for ( source in id ) {
1458 mw.loader.addSource( source, id[source] );
1459 }
1460 return true;
1461 }
1462
1463 if ( sources[id] !== undefined ) {
1464 throw new Error( 'source already registered: ' + id );
1465 }
1466
1467 sources[id] = props;
1468
1469 return true;
1470 },
1471
1472 /**
1473 * Register a module, letting the system know about it and its
1474 * properties. Startup modules contain calls to this function.
1475 *
1476 * @param {string} module Module name
1477 * @param {number} version Module version number as a timestamp (falls backs to 0)
1478 * @param {string|Array|Function} dependencies One string or array of strings of module
1479 * names on which this module depends, or a function that returns that array.
1480 * @param {string} [group=null] Group which the module is in
1481 * @param {string} [source='local'] Name of the source
1482 */
1483 register: function ( module, version, dependencies, group, source ) {
1484 var m;
1485 // Allow multiple registration
1486 if ( typeof module === 'object' ) {
1487 for ( m = 0; m < module.length; m += 1 ) {
1488 // module is an array of module names
1489 if ( typeof module[m] === 'string' ) {
1490 mw.loader.register( module[m] );
1491 // module is an array of arrays
1492 } else if ( typeof module[m] === 'object' ) {
1493 mw.loader.register.apply( mw.loader, module[m] );
1494 }
1495 }
1496 return;
1497 }
1498 // Validate input
1499 if ( typeof module !== 'string' ) {
1500 throw new Error( 'module must be a string, not a ' + typeof module );
1501 }
1502 if ( registry[module] !== undefined ) {
1503 throw new Error( 'module already registered: ' + module );
1504 }
1505 // List the module as registered
1506 registry[module] = {
1507 version: version !== undefined ? parseInt( version, 10 ) : 0,
1508 dependencies: [],
1509 group: typeof group === 'string' ? group : null,
1510 source: typeof source === 'string' ? source: 'local',
1511 state: 'registered'
1512 };
1513 if ( typeof dependencies === 'string' ) {
1514 // Allow dependencies to be given as a single module name
1515 registry[module].dependencies = [ dependencies ];
1516 } else if ( typeof dependencies === 'object' || $.isFunction( dependencies ) ) {
1517 // Allow dependencies to be given as an array of module names
1518 // or a function which returns an array
1519 registry[module].dependencies = dependencies;
1520 }
1521 },
1522
1523 /**
1524 * Implement a module given the components that make up the module.
1525 *
1526 * When #load or #using requests one or more modules, the server
1527 * response contain calls to this function.
1528 *
1529 * All arguments are required.
1530 *
1531 * @param {string} module Name of module
1532 * @param {Function|Array} script Function with module code or Array of URLs to
1533 * be used as the src attribute of a new `<script>` tag.
1534 * @param {Object} style Should follow one of the following patterns:
1535 *
1536 * { "css": [css, ..] }
1537 * { "url": { <media>: [url, ..] } }
1538 *
1539 * And for backwards compatibility (needs to be supported forever due to caching):
1540 *
1541 * { <media>: css }
1542 * { <media>: [url, ..] }
1543 *
1544 * The reason css strings are not concatenated anymore is bug 31676. We now check
1545 * whether it's safe to extend the stylesheet (see #canExpandStylesheetWith).
1546 *
1547 * @param {Object} msgs List of key/value pairs to be added to mw#messages.
1548 */
1549 implement: function ( module, script, style, msgs ) {
1550 // Validate input
1551 if ( typeof module !== 'string' ) {
1552 throw new Error( 'module must be a string, not a ' + typeof module );
1553 }
1554 if ( !$.isFunction( script ) && !$.isArray( script ) ) {
1555 throw new Error( 'script must be a function or an array, not a ' + typeof script );
1556 }
1557 if ( !$.isPlainObject( style ) ) {
1558 throw new Error( 'style must be an object, not a ' + typeof style );
1559 }
1560 if ( !$.isPlainObject( msgs ) ) {
1561 throw new Error( 'msgs must be an object, not a ' + typeof msgs );
1562 }
1563 // Automatically register module
1564 if ( registry[module] === undefined ) {
1565 mw.loader.register( module );
1566 }
1567 // Check for duplicate implementation
1568 if ( registry[module] !== undefined && registry[module].script !== undefined ) {
1569 throw new Error( 'module already implemented: ' + module );
1570 }
1571 // Attach components
1572 registry[module].script = script;
1573 registry[module].style = style;
1574 registry[module].messages = msgs;
1575 // The module may already have been marked as erroneous
1576 if ( $.inArray( registry[module].state, ['error', 'missing'] ) === -1 ) {
1577 registry[module].state = 'loaded';
1578 if ( allReady( registry[module].dependencies ) ) {
1579 execute( module );
1580 }
1581 }
1582 },
1583
1584 /**
1585 * Execute a function as soon as one or more required modules are ready.
1586 *
1587 * @param {string|Array} dependencies Module name or array of modules names the callback
1588 * dependends on to be ready before executing
1589 * @param {Function} [ready] callback to execute when all dependencies are ready
1590 * @param {Function} [error] callback to execute when if dependencies have a errors
1591 */
1592 using: function ( dependencies, ready, error ) {
1593 var tod = typeof dependencies;
1594 // Validate input
1595 if ( tod !== 'object' && tod !== 'string' ) {
1596 throw new Error( 'dependencies must be a string or an array, not a ' + tod );
1597 }
1598 // Allow calling with a single dependency as a string
1599 if ( tod === 'string' ) {
1600 dependencies = [ dependencies ];
1601 }
1602 // Resolve entire dependency map
1603 dependencies = resolve( dependencies );
1604 if ( allReady( dependencies ) ) {
1605 // Run ready immediately
1606 if ( $.isFunction( ready ) ) {
1607 ready();
1608 }
1609 } else if ( filter( ['error', 'missing'], dependencies ).length ) {
1610 // Execute error immediately if any dependencies have errors
1611 if ( $.isFunction( error ) ) {
1612 error( new Error( 'one or more dependencies have state "error" or "missing"' ),
1613 dependencies );
1614 }
1615 } else {
1616 // Not all dependencies are ready: queue up a request
1617 request( dependencies, ready, error );
1618 }
1619 },
1620
1621 /**
1622 * Load an external script or one or more modules.
1623 *
1624 * @param {string|Array} modules Either the name of a module, array of modules,
1625 * or a URL of an external script or style
1626 * @param {string} [type='text/javascript'] mime-type to use if calling with a URL of an
1627 * external script or style; acceptable values are "text/css" and
1628 * "text/javascript"; if no type is provided, text/javascript is assumed.
1629 * @param {boolean} [async] If true, load modules asynchronously
1630 * even if document ready has not yet occurred. If false, block before
1631 * document ready and load async after. If not set, true will be
1632 * assumed if loading a URL, and false will be assumed otherwise.
1633 */
1634 load: function ( modules, type, async ) {
1635 var filtered, m, module, l;
1636
1637 // Validate input
1638 if ( typeof modules !== 'object' && typeof modules !== 'string' ) {
1639 throw new Error( 'modules must be a string or an array, not a ' + typeof modules );
1640 }
1641 // Allow calling with an external url or single dependency as a string
1642 if ( typeof modules === 'string' ) {
1643 // Support adding arbitrary external scripts
1644 if ( /^(https?:)?\/\//.test( modules ) ) {
1645 if ( async === undefined ) {
1646 // Assume async for bug 34542
1647 async = true;
1648 }
1649 if ( type === 'text/css' ) {
1650 // IE7-8 throws security warnings when inserting a <link> tag
1651 // with a protocol-relative URL set though attributes (instead of
1652 // properties) - when on HTTPS. See also bug #.
1653 l = document.createElement( 'link' );
1654 l.rel = 'stylesheet';
1655 l.href = modules;
1656 $( 'head' ).append( l );
1657 return;
1658 }
1659 if ( type === 'text/javascript' || type === undefined ) {
1660 addScript( modules, null, async );
1661 return;
1662 }
1663 // Unknown type
1664 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type );
1665 }
1666 // Called with single module
1667 modules = [ modules ];
1668 }
1669
1670 // Filter out undefined modules, otherwise resolve() will throw
1671 // an exception for trying to load an undefined module.
1672 // Undefined modules are acceptable here in load(), because load() takes
1673 // an array of unrelated modules, whereas the modules passed to
1674 // using() are related and must all be loaded.
1675 for ( filtered = [], m = 0; m < modules.length; m += 1 ) {
1676 module = registry[modules[m]];
1677 if ( module !== undefined ) {
1678 if ( $.inArray( module.state, ['error', 'missing'] ) === -1 ) {
1679 filtered[filtered.length] = modules[m];
1680 }
1681 }
1682 }
1683
1684 if ( filtered.length === 0 ) {
1685 return;
1686 }
1687 // Resolve entire dependency map
1688 filtered = resolve( filtered );
1689 // If all modules are ready, nothing to be done
1690 if ( allReady( filtered ) ) {
1691 return;
1692 }
1693 // If any modules have errors: also quit.
1694 if ( filter( ['error', 'missing'], filtered ).length ) {
1695 return;
1696 }
1697 // Since some modules are not yet ready, queue up a request.
1698 request( filtered, undefined, undefined, async );
1699 },
1700
1701 /**
1702 * Change the state of one or more modules.
1703 *
1704 * @param {string|Object} module Module name or object of module name/state pairs
1705 * @param {string} state State name
1706 */
1707 state: function ( module, state ) {
1708 var m;
1709
1710 if ( typeof module === 'object' ) {
1711 for ( m in module ) {
1712 mw.loader.state( m, module[m] );
1713 }
1714 return;
1715 }
1716 if ( registry[module] === undefined ) {
1717 mw.loader.register( module );
1718 }
1719 if ( $.inArray( state, ['ready', 'error', 'missing'] ) !== -1
1720 && registry[module].state !== state ) {
1721 // Make sure pending modules depending on this one get executed if their
1722 // dependencies are now fulfilled!
1723 registry[module].state = state;
1724 handlePending( module );
1725 } else {
1726 registry[module].state = state;
1727 }
1728 },
1729
1730 /**
1731 * Get the version of a module.
1732 *
1733 * @param {string} module Name of module to get version for
1734 */
1735 getVersion: function ( module ) {
1736 if ( registry[module] !== undefined && registry[module].version !== undefined ) {
1737 return formatVersionNumber( registry[module].version );
1738 }
1739 return null;
1740 },
1741
1742 /**
1743 * @inheritdoc #getVersion
1744 * @deprecated since 1.18 use #getVersion instead
1745 */
1746 version: function () {
1747 return mw.loader.getVersion.apply( mw.loader, arguments );
1748 },
1749
1750 /**
1751 * Get the state of a module.
1752 *
1753 * @param {string} module Name of module to get state for
1754 */
1755 getState: function ( module ) {
1756 if ( registry[module] !== undefined && registry[module].state !== undefined ) {
1757 return registry[module].state;
1758 }
1759 return null;
1760 },
1761
1762 /**
1763 * Get names of all registered modules.
1764 *
1765 * @return {Array}
1766 */
1767 getModuleNames: function () {
1768 return $.map( registry, function ( i, key ) {
1769 return key;
1770 } );
1771 },
1772
1773 /**
1774 * Load the `mediawiki.user` module.
1775 *
1776 * For backwards-compatibility with cached pages from before 2013 where:
1777 *
1778 * - the `mediawiki.user` module didn't exist yet
1779 * - `mw.user` was still part of mediawiki.js
1780 * - `mw.loader.go` still existed and called after `mw.loader.load()`
1781 */
1782 go: function () {
1783 mw.loader.load( 'mediawiki.user' );
1784 },
1785
1786 /**
1787 * @inheritdoc mw.inspect#runReports
1788 * @method
1789 */
1790 inspect: function () {
1791 var args = slice.call( arguments );
1792 mw.loader.using( 'mediawiki.inspect', function () {
1793 mw.inspect.runReports.apply( mw.inspect, args );
1794 } );
1795 },
1796
1797 /**
1798 * On browsers that implement the localStorage API, the module store serves as a
1799 * smart complement to the browser cache. Unlike the browser cache, the module store
1800 * can slice a concatenated response from ResourceLoader into its constituent
1801 * modules and cache each of them separately, using each module's versioning scheme
1802 * to determine when the cache should be invalidated.
1803 *
1804 * @singleton
1805 * @class mw.loader.store
1806 */
1807 store: {
1808 // Whether the store is in use on this page.
1809 enabled: null,
1810
1811 // The contents of the store, mapping '[module name]@[version]' keys
1812 // to module implementations.
1813 items: {},
1814
1815 // Cache hit stats
1816 stats: { hits: 0, misses: 0, expired: 0 },
1817
1818 /**
1819 * Construct a JSON-serializable object representing the content of the store.
1820 * @return {Object} Module store contents.
1821 */
1822 toJSON: function () {
1823 return { items: mw.loader.store.items, vary: mw.loader.store.getVary() };
1824 },
1825
1826 /**
1827 * Get the localStorage key for the entire module store. The key references
1828 * $wgDBname to prevent clashes between wikis which share a common host.
1829 *
1830 * @return {string} localStorage item key
1831 */
1832 getStoreKey: function () {
1833 return 'MediaWikiModuleStore:' + mw.config.get( 'wgDBname' );
1834 },
1835
1836 /**
1837 * Get a string key on which to vary the module cache.
1838 * @return {string} String of concatenated vary conditions.
1839 */
1840 getVary: function () {
1841 return [
1842 mw.config.get( 'skin' ),
1843 mw.config.get( 'wgResourceLoaderStorageVersion' ),
1844 mw.config.get( 'wgUserLanguage' )
1845 ].join(':');
1846 },
1847
1848 /**
1849 * Get a string key for a specific module. The key format is '[name]@[version]'.
1850 *
1851 * @param {string} module Module name
1852 * @return {string|null} Module key or null if module does not exist
1853 */
1854 getModuleKey: function ( module ) {
1855 return typeof registry[module] === 'object' ?
1856 ( module + '@' + registry[module].version ) : null;
1857 },
1858
1859 /**
1860 * Initialize the store.
1861 *
1862 * Retrieves store from localStorage and (if successfully retrieved) decoding
1863 * the stored JSON value to a plain object.
1864 *
1865 * The try / catch block is used for JSON & localStorage feature detection.
1866 * See the in-line documentation for Modernizr's localStorage feature detection
1867 * code for a full account of why we need a try / catch:
1868 * https://github.com/Modernizr/Modernizr/blob/v2.7.1/modernizr.js#L771-L796
1869 */
1870 init: function () {
1871 var raw, data;
1872
1873 if ( mw.loader.store.enabled !== null ) {
1874 // Init already ran
1875 return;
1876 }
1877
1878 if ( !mw.config.get( 'wgResourceLoaderStorageEnabled' ) || mw.config.get( 'debug' ) ) {
1879 // Disabled by configuration, or because debug mode is set
1880 mw.loader.store.enabled = false;
1881 return;
1882 }
1883
1884 try {
1885 raw = localStorage.getItem( mw.loader.store.getStoreKey() );
1886 // If we get here, localStorage is available; mark enabled
1887 mw.loader.store.enabled = true;
1888 data = JSON.parse( raw );
1889 if ( data && typeof data.items === 'object' && data.vary === mw.loader.store.getVary() ) {
1890 mw.loader.store.items = data.items;
1891 return;
1892 }
1893 } catch (e) {}
1894
1895 if ( raw === undefined ) {
1896 // localStorage failed; disable store
1897 mw.loader.store.enabled = false;
1898 } else {
1899 mw.loader.store.update();
1900 }
1901 },
1902
1903 /**
1904 * Retrieve a module from the store and update cache hit stats.
1905 *
1906 * @param {string} module Module name
1907 * @return {string|boolean} Module implementation or false if unavailable
1908 */
1909 get: function ( module ) {
1910 var key;
1911
1912 if ( !mw.loader.store.enabled ) {
1913 return false;
1914 }
1915
1916 key = mw.loader.store.getModuleKey( module );
1917 if ( key in mw.loader.store.items ) {
1918 mw.loader.store.stats.hits++;
1919 return mw.loader.store.items[key];
1920 }
1921 mw.loader.store.stats.misses++;
1922 return false;
1923 },
1924
1925 /**
1926 * Stringify a module and queue it for storage.
1927 *
1928 * @param {string} module Module name
1929 * @param {Object} descriptor The module's descriptor as set in the registry
1930 */
1931 set: function ( module, descriptor ) {
1932 var args, key;
1933
1934 if ( !mw.loader.store.enabled ) {
1935 return false;
1936 }
1937
1938 key = mw.loader.store.getModuleKey( module );
1939
1940 if (
1941 // Already stored a copy of this exact version
1942 key in mw.loader.store.items ||
1943 // Module failed to load
1944 descriptor.state !== 'ready' ||
1945 // Unversioned, private, or site-/user-specific
1946 ( !descriptor.version || $.inArray( descriptor.group, [ 'private', 'user', 'site' ] ) !== -1 ) ||
1947 // Partial descriptor
1948 $.inArray( undefined, [ descriptor.script, descriptor.style, descriptor.messages ] ) !== -1
1949 ) {
1950 // Decline to store
1951 return false;
1952 }
1953
1954 try {
1955 args = [
1956 JSON.stringify( module ),
1957 typeof descriptor.script === 'function' ?
1958 String( descriptor.script ) :
1959 JSON.stringify( descriptor.script ),
1960 JSON.stringify( descriptor.style ),
1961 JSON.stringify( descriptor.messages )
1962 ];
1963 // Attempted workaround for a possible Opera bug (bug 57567).
1964 // This regex should never match under sane conditions.
1965 if ( /^\s*\(/.test( args[1] ) ) {
1966 args[1] = 'function' + args[1];
1967 log( 'Detected malformed function stringification (bug 57567)' );
1968 }
1969 } catch ( e ) {
1970 return;
1971 }
1972
1973 mw.loader.store.items[key] = 'mw.loader.implement(' + args.join(',') + ');';
1974 mw.loader.store.update();
1975 },
1976
1977 /**
1978 * Iterate through the module store, removing any item that does not correspond
1979 * (in name and version) to an item in the module registry.
1980 */
1981 prune: function () {
1982 var key, module;
1983
1984 if ( !mw.loader.store.enabled ) {
1985 return false;
1986 }
1987
1988 for ( key in mw.loader.store.items ) {
1989 module = key.substring( 0, key.indexOf( '@' ) );
1990 if ( mw.loader.store.getModuleKey( module ) !== key ) {
1991 mw.loader.store.stats.expired++;
1992 delete mw.loader.store.items[key];
1993 }
1994 }
1995 },
1996
1997 /**
1998 * Sync modules to localStorage.
1999 *
2000 * This function debounces localStorage updates. When called multiple times in
2001 * quick succession, the calls are coalesced into a single update operation.
2002 * This allows us to call #update without having to consider the module load
2003 * queue; the call to localStorage.setItem will be naturally deferred until the
2004 * page is quiescent.
2005 *
2006 * Because localStorage is shared by all pages with the same origin, if multiple
2007 * pages are loaded with different module sets, the possibility exists that
2008 * modules saved by one page will be clobbered by another. But the impact would
2009 * be minor and the problem would be corrected by subsequent page views.
2010 */
2011 update: ( function () {
2012 var timer;
2013
2014 function flush() {
2015 var data,
2016 key = mw.loader.store.getStoreKey();
2017
2018 if ( !mw.loader.store.enabled ) {
2019 return false;
2020 }
2021 mw.loader.store.prune();
2022 try {
2023 // Replacing the content of the module store might fail if the new
2024 // contents would exceed the browser's localStorage size limit. To
2025 // avoid clogging the browser with stale data, always remove the old
2026 // value before attempting to set the new one.
2027 localStorage.removeItem( key );
2028 data = JSON.stringify( mw.loader.store );
2029 localStorage.setItem( key, data );
2030 } catch ( e ) {}
2031 }
2032
2033 return function () {
2034 clearTimeout( timer );
2035 timer = setTimeout( flush, 2000 );
2036 };
2037 }() )
2038 }
2039 };
2040 }() ),
2041
2042 /**
2043 * HTML construction helper functions
2044 *
2045 * @example
2046 *
2047 * var Html, output;
2048 *
2049 * Html = mw.html;
2050 * output = Html.element( 'div', {}, new Html.Raw(
2051 * Html.element( 'img', { src: '<' } )
2052 * ) );
2053 * mw.log( output ); // <div><img src="&lt;"/></div>
2054 *
2055 * @class mw.html
2056 * @singleton
2057 */
2058 html: ( function () {
2059 function escapeCallback( s ) {
2060 switch ( s ) {
2061 case '\'':
2062 return '&#039;';
2063 case '"':
2064 return '&quot;';
2065 case '<':
2066 return '&lt;';
2067 case '>':
2068 return '&gt;';
2069 case '&':
2070 return '&amp;';
2071 }
2072 }
2073
2074 return {
2075 /**
2076 * Escape a string for HTML. Converts special characters to HTML entities.
2077 * @param {string} s The string to escape
2078 */
2079 escape: function ( s ) {
2080 return s.replace( /['"<>&]/g, escapeCallback );
2081 },
2082
2083 /**
2084 * Create an HTML element string, with safe escaping.
2085 *
2086 * @param {string} name The tag name.
2087 * @param {Object} attrs An object with members mapping element names to values
2088 * @param {Mixed} contents The contents of the element. May be either:
2089 * - string: The string is escaped.
2090 * - null or undefined: The short closing form is used, e.g. <br/>.
2091 * - this.Raw: The value attribute is included without escaping.
2092 * - this.Cdata: The value attribute is included, and an exception is
2093 * thrown if it contains an illegal ETAGO delimiter.
2094 * See http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.3.2
2095 */
2096 element: function ( name, attrs, contents ) {
2097 var v, attrName, s = '<' + name;
2098
2099 for ( attrName in attrs ) {
2100 v = attrs[attrName];
2101 // Convert name=true, to name=name
2102 if ( v === true ) {
2103 v = attrName;
2104 // Skip name=false
2105 } else if ( v === false ) {
2106 continue;
2107 }
2108 s += ' ' + attrName + '="' + this.escape( String( v ) ) + '"';
2109 }
2110 if ( contents === undefined || contents === null ) {
2111 // Self close tag
2112 s += '/>';
2113 return s;
2114 }
2115 // Regular open tag
2116 s += '>';
2117 switch ( typeof contents ) {
2118 case 'string':
2119 // Escaped
2120 s += this.escape( contents );
2121 break;
2122 case 'number':
2123 case 'boolean':
2124 // Convert to string
2125 s += String( contents );
2126 break;
2127 default:
2128 if ( contents instanceof this.Raw ) {
2129 // Raw HTML inclusion
2130 s += contents.value;
2131 } else if ( contents instanceof this.Cdata ) {
2132 // CDATA
2133 if ( /<\/[a-zA-z]/.test( contents.value ) ) {
2134 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
2135 }
2136 s += contents.value;
2137 } else {
2138 throw new Error( 'mw.html.element: Invalid type of contents' );
2139 }
2140 }
2141 s += '</' + name + '>';
2142 return s;
2143 },
2144
2145 /**
2146 * Wrapper object for raw HTML passed to mw.html.element().
2147 * @class mw.html.Raw
2148 */
2149 Raw: function ( value ) {
2150 this.value = value;
2151 },
2152
2153 /**
2154 * Wrapper object for CDATA element contents passed to mw.html.element()
2155 * @class mw.html.Cdata
2156 */
2157 Cdata: function ( value ) {
2158 this.value = value;
2159 }
2160 };
2161 }() ),
2162
2163 // Skeleton user object. mediawiki.user.js extends this
2164 user: {
2165 options: new Map(),
2166 tokens: new Map()
2167 },
2168
2169 /**
2170 * Registry and firing of events.
2171 *
2172 * MediaWiki has various interface components that are extended, enhanced
2173 * or manipulated in some other way by extensions, gadgets and even
2174 * in core itself.
2175 *
2176 * This framework helps streamlining the timing of when these other
2177 * code paths fire their plugins (instead of using document-ready,
2178 * which can and should be limited to firing only once).
2179 *
2180 * Features like navigating to other wiki pages, previewing an edit
2181 * and editing itself – without a refresh – can then retrigger these
2182 * hooks accordingly to ensure everything still works as expected.
2183 *
2184 * Example usage:
2185 *
2186 * mw.hook( 'wikipage.content' ).add( fn ).remove( fn );
2187 * mw.hook( 'wikipage.content' ).fire( $content );
2188 *
2189 * Handlers can be added and fired for arbitrary event names at any time. The same
2190 * event can be fired multiple times. The last run of an event is memorized
2191 * (similar to `$(document).ready` and `$.Deferred().done`).
2192 * This means if an event is fired, and a handler added afterwards, the added
2193 * function will be fired right away with the last given event data.
2194 *
2195 * Like Deferreds and Promises, the mw.hook object is both detachable and chainable.
2196 * Thus allowing flexible use and optimal maintainability and authority control.
2197 * You can pass around the `add` and/or `fire` method to another piece of code
2198 * without it having to know the event name (or `mw.hook` for that matter).
2199 *
2200 * var h = mw.hook( 'bar.ready' );
2201 * new mw.Foo( .. ).fetch( { callback: h.fire } );
2202 *
2203 * Note: Events are documented with an underscore instead of a dot in the event
2204 * name due to jsduck not supporting dots in that position.
2205 *
2206 * @class mw.hook
2207 */
2208 hook: ( function () {
2209 var lists = {};
2210
2211 /**
2212 * Create an instance of mw.hook.
2213 *
2214 * @method hook
2215 * @member mw
2216 * @param {string} name Name of hook.
2217 * @return {mw.hook}
2218 */
2219 return function ( name ) {
2220 var list = lists[name] || ( lists[name] = $.Callbacks( 'memory' ) );
2221
2222 return {
2223 /**
2224 * Register a hook handler
2225 * @param {Function...} handler Function to bind.
2226 * @chainable
2227 */
2228 add: list.add,
2229
2230 /**
2231 * Unregister a hook handler
2232 * @param {Function...} handler Function to unbind.
2233 * @chainable
2234 */
2235 remove: list.remove,
2236
2237 /**
2238 * Run a hook.
2239 * @param {Mixed...} data
2240 * @chainable
2241 */
2242 fire: function () {
2243 return list.fireWith( null, slice.call( arguments ) );
2244 }
2245 };
2246 };
2247 }() )
2248 };
2249
2250 }( jQuery ) );
2251
2252 // Alias $j to jQuery for backwards compatibility
2253 window.$j = jQuery;
2254
2255 // Attach to window and globally alias
2256 window.mw = window.mediaWiki = mw;
2257
2258 // Auto-register from pre-loaded startup scripts
2259 if ( jQuery.isFunction( window.startUp ) ) {
2260 window.startUp();
2261 window.startUp = undefined;
2262 }