Merge "rdbms: make some LBFactory fields private"
[lhc/web/wiklou.git] / resources / src / mediawiki / mediawiki.base.js
1 /*!
2 * This file is currently loaded as part of the 'mediawiki' module and therefore
3 * concatenated to mediawiki.js and executed at the same time. This file exists
4 * to help prepare for splitting up the 'mediawiki' module.
5 * This effort is tracked at https://phabricator.wikimedia.org/T192623
6 *
7 * In short:
8 *
9 * - mediawiki.js will be reduced to the minimum needed to define mw.loader and
10 * mw.config, and then moved to its own private "mediawiki.loader" module that
11 * can be embedded within the StartupModule response.
12 *
13 * - mediawiki.base.js and other files in this directory will remain part of the
14 * "mediawiki" module, and will remain a default/implicit dependency for all
15 * regular modules, just like jquery and wikibits already are.
16 */
17 /* globals mw */
18 ( function () {
19 'use strict';
20
21 var slice = Array.prototype.slice,
22 mwLoaderTrack = mw.track,
23 trackCallbacks = $.Callbacks( 'memory' ),
24 trackHandlers = [],
25 hasOwn = Object.prototype.hasOwnProperty;
26
27 /**
28 * Object constructor for messages.
29 *
30 * Similar to the Message class in MediaWiki PHP.
31 *
32 * Format defaults to 'text'.
33 *
34 * @example
35 *
36 * var obj, str;
37 * mw.messages.set( {
38 * 'hello': 'Hello world',
39 * 'hello-user': 'Hello, $1!',
40 * 'welcome-user': 'Welcome back to $2, $1! Last visit by $1: $3'
41 * } );
42 *
43 * obj = new mw.Message( mw.messages, 'hello' );
44 * mw.log( obj.text() );
45 * // Hello world
46 *
47 * obj = new mw.Message( mw.messages, 'hello-user', [ 'John Doe' ] );
48 * mw.log( obj.text() );
49 * // Hello, John Doe!
50 *
51 * obj = new mw.Message( mw.messages, 'welcome-user', [ 'John Doe', 'Wikipedia', '2 hours ago' ] );
52 * mw.log( obj.text() );
53 * // Welcome back to Wikipedia, John Doe! Last visit by John Doe: 2 hours ago
54 *
55 * // Using mw.message shortcut
56 * obj = mw.message( 'hello-user', 'John Doe' );
57 * mw.log( obj.text() );
58 * // Hello, John Doe!
59 *
60 * // Using mw.msg shortcut
61 * str = mw.msg( 'hello-user', 'John Doe' );
62 * mw.log( str );
63 * // Hello, John Doe!
64 *
65 * // Different formats
66 * obj = new mw.Message( mw.messages, 'hello-user', [ 'John "Wiki" <3 Doe' ] );
67 *
68 * obj.format = 'text';
69 * str = obj.toString();
70 * // Same as:
71 * str = obj.text();
72 *
73 * mw.log( str );
74 * // Hello, John "Wiki" <3 Doe!
75 *
76 * mw.log( obj.escaped() );
77 * // Hello, John &quot;Wiki&quot; &lt;3 Doe!
78 *
79 * @class mw.Message
80 *
81 * @constructor
82 * @param {mw.Map} map Message store
83 * @param {string} key
84 * @param {Array} [parameters]
85 */
86 function Message( map, key, parameters ) {
87 this.format = 'text';
88 this.map = map;
89 this.key = key;
90 this.parameters = parameters === undefined ? [] : slice.call( parameters );
91 return this;
92 }
93
94 Message.prototype = {
95 /**
96 * Get parsed contents of the message.
97 *
98 * The default parser does simple $N replacements and nothing else.
99 * This may be overridden to provide a more complex message parser.
100 * The primary override is in the mediawiki.jqueryMsg module.
101 *
102 * This function will not be called for nonexistent messages.
103 *
104 * @return {string} Parsed message
105 */
106 parser: function () {
107 return mw.format.apply( null, [ this.map.get( this.key ) ].concat( this.parameters ) );
108 },
109
110 /**
111 * Add (does not replace) parameters for `$N` placeholder values.
112 *
113 * @param {Array} parameters
114 * @return {mw.Message}
115 * @chainable
116 */
117 params: function ( parameters ) {
118 var i;
119 for ( i = 0; i < parameters.length; i++ ) {
120 this.parameters.push( parameters[ i ] );
121 }
122 return this;
123 },
124
125 /**
126 * Convert message object to its string form based on current format.
127 *
128 * @return {string} Message as a string in the current form, or `<key>` if key
129 * does not exist.
130 */
131 toString: function () {
132 var text;
133
134 if ( !this.exists() ) {
135 // Use ⧼key⧽ as text if key does not exist
136 // Err on the side of safety, ensure that the output
137 // is always html safe in the event the message key is
138 // missing, since in that case its highly likely the
139 // message key is user-controlled.
140 // '⧼' is used instead of '<' to side-step any
141 // double-escaping issues.
142 // (Keep synchronised with Message::toString() in PHP.)
143 return '⧼' + mw.html.escape( this.key ) + '⧽';
144 }
145
146 if ( this.format === 'plain' || this.format === 'text' || this.format === 'parse' ) {
147 text = this.parser();
148 }
149
150 if ( this.format === 'escaped' ) {
151 text = this.parser();
152 text = mw.html.escape( text );
153 }
154
155 return text;
156 },
157
158 /**
159 * Change format to 'parse' and convert message to string
160 *
161 * If jqueryMsg is loaded, this parses the message text from wikitext
162 * (where supported) to HTML
163 *
164 * Otherwise, it is equivalent to plain.
165 *
166 * @return {string} String form of parsed message
167 */
168 parse: function () {
169 this.format = 'parse';
170 return this.toString();
171 },
172
173 /**
174 * Change format to 'plain' and convert message to string
175 *
176 * This substitutes parameters, but otherwise does not change the
177 * message text.
178 *
179 * @return {string} String form of plain message
180 */
181 plain: function () {
182 this.format = 'plain';
183 return this.toString();
184 },
185
186 /**
187 * Change format to 'text' and convert message to string
188 *
189 * If jqueryMsg is loaded, {{-transformation is done where supported
190 * (such as {{plural:}}, {{gender:}}, {{int:}}).
191 *
192 * Otherwise, it is equivalent to plain
193 *
194 * @return {string} String form of text message
195 */
196 text: function () {
197 this.format = 'text';
198 return this.toString();
199 },
200
201 /**
202 * Change the format to 'escaped' and convert message to string
203 *
204 * This is equivalent to using the 'text' format (see #text), then
205 * HTML-escaping the output.
206 *
207 * @return {string} String form of html escaped message
208 */
209 escaped: function () {
210 this.format = 'escaped';
211 return this.toString();
212 },
213
214 /**
215 * Check if a message exists
216 *
217 * @see mw.Map#exists
218 * @return {boolean}
219 */
220 exists: function () {
221 return this.map.exists( this.key );
222 }
223 };
224
225 /**
226 * @class mw
227 * @singleton
228 */
229
230 /**
231 * @inheritdoc mw.inspect#runReports
232 * @method
233 */
234 mw.inspect = function () {
235 var args = arguments;
236 mw.loader.using( 'mediawiki.inspect', function () {
237 mw.inspect.runReports.apply( mw.inspect, args );
238 } );
239 };
240
241 /**
242 * Format a string. Replace $1, $2 ... $N with positional arguments.
243 *
244 * Used by Message#parser().
245 *
246 * @since 1.25
247 * @param {string} formatString Format string
248 * @param {...Mixed} parameters Values for $N replacements
249 * @return {string} Formatted string
250 */
251 mw.format = function ( formatString ) {
252 var parameters = slice.call( arguments, 1 );
253 return formatString.replace( /\$(\d+)/g, function ( str, match ) {
254 var index = parseInt( match, 10 ) - 1;
255 return parameters[ index ] !== undefined ? parameters[ index ] : '$' + match;
256 } );
257 };
258
259 // Expose Message constructor
260 mw.Message = Message;
261
262 /**
263 * Get a message object.
264 *
265 * Shortcut for `new mw.Message( mw.messages, key, parameters )`.
266 *
267 * @see mw.Message
268 * @param {string} key Key of message to get
269 * @param {...Mixed} parameters Values for $N replacements
270 * @return {mw.Message}
271 */
272 mw.message = function ( key ) {
273 var parameters = slice.call( arguments, 1 );
274 return new Message( mw.messages, key, parameters );
275 };
276
277 /**
278 * Get a message string using the (default) 'text' format.
279 *
280 * Shortcut for `mw.message( key, parameters... ).text()`.
281 *
282 * @see mw.Message
283 * @param {string} key Key of message to get
284 * @param {...Mixed} parameters Values for $N replacements
285 * @return {string}
286 */
287 mw.msg = function () {
288 return mw.message.apply( mw.message, arguments ).toString();
289 };
290
291 /**
292 * Track an analytic event.
293 *
294 * This method provides a generic means for MediaWiki JavaScript code to capture state
295 * information for analysis. Each logged event specifies a string topic name that describes
296 * the kind of event that it is. Topic names consist of dot-separated path components,
297 * arranged from most general to most specific. Each path component should have a clear and
298 * well-defined purpose.
299 *
300 * Data handlers are registered via `mw.trackSubscribe`, and receive the full set of
301 * events that match their subcription, including those that fired before the handler was
302 * bound.
303 *
304 * @param {string} topic Topic name
305 * @param {Object} [data] Data describing the event, encoded as an object
306 */
307 mw.track = function ( topic, data ) {
308 mwLoaderTrack( topic, data );
309 trackCallbacks.fire( mw.trackQueue );
310 };
311
312 /**
313 * Register a handler for subset of analytic events, specified by topic.
314 *
315 * Handlers will be called once for each tracked event, including any events that fired before the
316 * handler was registered; 'this' is set to a plain object with a 'timeStamp' property indicating
317 * the exact time at which the event fired, a string 'topic' property naming the event, and a
318 * 'data' property which is an object of event-specific data. The event topic and event data are
319 * also passed to the callback as the first and second arguments, respectively.
320 *
321 * @param {string} topic Handle events whose name starts with this string prefix
322 * @param {Function} callback Handler to call for each matching tracked event
323 * @param {string} callback.topic
324 * @param {Object} [callback.data]
325 */
326 mw.trackSubscribe = function ( topic, callback ) {
327 var seen = 0;
328 function handler( trackQueue ) {
329 var event;
330 for ( ; seen < trackQueue.length; seen++ ) {
331 event = trackQueue[ seen ];
332 if ( event.topic.indexOf( topic ) === 0 ) {
333 callback.call( event, event.topic, event.data );
334 }
335 }
336 }
337
338 trackHandlers.push( [ handler, callback ] );
339
340 trackCallbacks.add( handler );
341 };
342
343 /**
344 * Stop handling events for a particular handler
345 *
346 * @param {Function} callback
347 */
348 mw.trackUnsubscribe = function ( callback ) {
349 trackHandlers = trackHandlers.filter( function ( fns ) {
350 if ( fns[ 1 ] === callback ) {
351 trackCallbacks.remove( fns[ 0 ] );
352 // Ensure the tuple is removed to avoid holding on to closures
353 return false;
354 }
355 return true;
356 } );
357 };
358
359 // Fire events from before track() triggred fire()
360 trackCallbacks.fire( mw.trackQueue );
361
362 /**
363 * Registry and firing of events.
364 *
365 * MediaWiki has various interface components that are extended, enhanced
366 * or manipulated in some other way by extensions, gadgets and even
367 * in core itself.
368 *
369 * This framework helps streamlining the timing of when these other
370 * code paths fire their plugins (instead of using document-ready,
371 * which can and should be limited to firing only once).
372 *
373 * Features like navigating to other wiki pages, previewing an edit
374 * and editing itself – without a refresh – can then retrigger these
375 * hooks accordingly to ensure everything still works as expected.
376 *
377 * Example usage:
378 *
379 * mw.hook( 'wikipage.content' ).add( fn ).remove( fn );
380 * mw.hook( 'wikipage.content' ).fire( $content );
381 *
382 * Handlers can be added and fired for arbitrary event names at any time. The same
383 * event can be fired multiple times. The last run of an event is memorized
384 * (similar to `$(document).ready` and `$.Deferred().done`).
385 * This means if an event is fired, and a handler added afterwards, the added
386 * function will be fired right away with the last given event data.
387 *
388 * Like Deferreds and Promises, the mw.hook object is both detachable and chainable.
389 * Thus allowing flexible use and optimal maintainability and authority control.
390 * You can pass around the `add` and/or `fire` method to another piece of code
391 * without it having to know the event name (or `mw.hook` for that matter).
392 *
393 * var h = mw.hook( 'bar.ready' );
394 * new mw.Foo( .. ).fetch( { callback: h.fire } );
395 *
396 * Note: Events are documented with an underscore instead of a dot in the event
397 * name due to jsduck not supporting dots in that position.
398 *
399 * @class mw.hook
400 */
401 mw.hook = ( function () {
402 var lists = {};
403
404 /**
405 * Create an instance of mw.hook.
406 *
407 * @method hook
408 * @member mw
409 * @param {string} name Name of hook.
410 * @return {mw.hook}
411 */
412 return function ( name ) {
413 var list = hasOwn.call( lists, name ) ?
414 lists[ name ] :
415 lists[ name ] = $.Callbacks( 'memory' );
416
417 return {
418 /**
419 * Register a hook handler
420 *
421 * @param {...Function} handler Function to bind.
422 * @chainable
423 */
424 add: list.add,
425
426 /**
427 * Unregister a hook handler
428 *
429 * @param {...Function} handler Function to unbind.
430 * @chainable
431 */
432 remove: list.remove,
433
434 /**
435 * Run a hook.
436 *
437 * @param {...Mixed} data
438 * @return {mw.hook}
439 * @chainable
440 */
441 fire: function () {
442 return list.fireWith.call( this, null, slice.call( arguments ) );
443 }
444 };
445 };
446 }() );
447
448 /**
449 * HTML construction helper functions
450 *
451 * @example
452 *
453 * var Html, output;
454 *
455 * Html = mw.html;
456 * output = Html.element( 'div', {}, new Html.Raw(
457 * Html.element( 'img', { src: '<' } )
458 * ) );
459 * mw.log( output ); // <div><img src="&lt;"/></div>
460 *
461 * @class mw.html
462 * @singleton
463 */
464 mw.html = ( function () {
465 function escapeCallback( s ) {
466 switch ( s ) {
467 case '\'':
468 return '&#039;';
469 case '"':
470 return '&quot;';
471 case '<':
472 return '&lt;';
473 case '>':
474 return '&gt;';
475 case '&':
476 return '&amp;';
477 }
478 }
479
480 return {
481 /**
482 * Escape a string for HTML.
483 *
484 * Converts special characters to HTML entities.
485 *
486 * mw.html.escape( '< > \' & "' );
487 * // Returns &lt; &gt; &#039; &amp; &quot;
488 *
489 * @param {string} s The string to escape
490 * @return {string} HTML
491 */
492 escape: function ( s ) {
493 return s.replace( /['"<>&]/g, escapeCallback );
494 },
495
496 /**
497 * Create an HTML element string, with safe escaping.
498 *
499 * @param {string} name The tag name.
500 * @param {Object} [attrs] An object with members mapping element names to values
501 * @param {string|mw.html.Raw|mw.html.Cdata|null} [contents=null] The contents of the element.
502 *
503 * - string: Text to be escaped.
504 * - null: The element is treated as void with short closing form, e.g. `<br/>`.
505 * - this.Raw: The raw value is directly included.
506 * - this.Cdata: The raw value is directly included. An exception is
507 * thrown if it contains any illegal ETAGO delimiter.
508 * See <https://www.w3.org/TR/html401/appendix/notes.html#h-B.3.2>.
509 * @return {string} HTML
510 */
511 element: function ( name, attrs, contents ) {
512 var v, attrName, s = '<' + name;
513
514 if ( attrs ) {
515 for ( attrName in attrs ) {
516 v = attrs[ attrName ];
517 // Convert name=true, to name=name
518 if ( v === true ) {
519 v = attrName;
520 // Skip name=false
521 } else if ( v === false ) {
522 continue;
523 }
524 s += ' ' + attrName + '="' + this.escape( String( v ) ) + '"';
525 }
526 }
527 if ( contents === undefined || contents === null ) {
528 // Self close tag
529 s += '/>';
530 return s;
531 }
532 // Regular open tag
533 s += '>';
534 switch ( typeof contents ) {
535 case 'string':
536 // Escaped
537 s += this.escape( contents );
538 break;
539 case 'number':
540 case 'boolean':
541 // Convert to string
542 s += String( contents );
543 break;
544 default:
545 if ( contents instanceof this.Raw ) {
546 // Raw HTML inclusion
547 s += contents.value;
548 } else if ( contents instanceof this.Cdata ) {
549 // CDATA
550 if ( /<\/[a-zA-z]/.test( contents.value ) ) {
551 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
552 }
553 s += contents.value;
554 } else {
555 throw new Error( 'mw.html.element: Invalid type of contents' );
556 }
557 }
558 s += '</' + name + '>';
559 return s;
560 },
561
562 /**
563 * Wrapper object for raw HTML passed to mw.html.element().
564 *
565 * @class mw.html.Raw
566 * @constructor
567 * @param {string} value
568 */
569 Raw: function ( value ) {
570 this.value = value;
571 },
572
573 /**
574 * Wrapper object for CDATA element contents passed to mw.html.element()
575 *
576 * @class mw.html.Cdata
577 * @constructor
578 * @param {string} value
579 */
580 Cdata: function ( value ) {
581 this.value = value;
582 }
583 };
584 }() );
585
586 /**
587 * Execute a function as soon as one or more required modules are ready.
588 *
589 * Example of inline dependency on OOjs:
590 *
591 * mw.loader.using( 'oojs', function () {
592 * OO.compare( [ 1 ], [ 1 ] );
593 * } );
594 *
595 * Example of inline dependency obtained via `require()`:
596 *
597 * mw.loader.using( [ 'mediawiki.util' ], function ( require ) {
598 * var util = require( 'mediawiki.util' );
599 * } );
600 *
601 * Since MediaWiki 1.23 this also returns a promise.
602 *
603 * Since MediaWiki 1.28 the promise is resolved with a `require` function.
604 *
605 * @member mw.loader
606 * @param {string|Array} dependencies Module name or array of modules names the
607 * callback depends on to be ready before executing
608 * @param {Function} [ready] Callback to execute when all dependencies are ready
609 * @param {Function} [error] Callback to execute if one or more dependencies failed
610 * @return {jQuery.Promise} With a `require` function
611 */
612 mw.loader.using = function ( dependencies, ready, error ) {
613 var deferred = $.Deferred();
614
615 // Allow calling with a single dependency as a string
616 if ( typeof dependencies === 'string' ) {
617 dependencies = [ dependencies ];
618 }
619
620 if ( ready ) {
621 deferred.done( ready );
622 }
623 if ( error ) {
624 deferred.fail( error );
625 }
626
627 try {
628 // Resolve entire dependency map
629 dependencies = mw.loader.resolve( dependencies );
630 } catch ( e ) {
631 return deferred.reject( e ).promise();
632 }
633
634 mw.loader.enqueue( dependencies, function () {
635 deferred.resolve( mw.loader.require );
636 }, deferred.reject );
637
638 return deferred.promise();
639 };
640
641 // Alias $j to jQuery for backwards compatibility
642 // @deprecated since 1.23 Use $ or jQuery instead
643 mw.log.deprecate( window, '$j', $, 'Use $ or jQuery instead.' );
644 }() );