Merge "Type hint against LinkTarget in WatchedItemStore"
[lhc/web/wiklou.git] / resources / src / mediawiki.util.js
1 ( function () {
2 'use strict';
3
4 var util,
5 config = require( './config.json' );
6
7 /**
8 * Encode the string like PHP's rawurlencode
9 * @ignore
10 *
11 * @param {string} str String to be encoded.
12 * @return {string} Encoded string
13 */
14 function rawurlencode( str ) {
15 str = String( str );
16 return encodeURIComponent( str )
17 .replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' )
18 .replace( /\)/g, '%29' ).replace( /\*/g, '%2A' ).replace( /~/g, '%7E' );
19 }
20
21 /**
22 * Private helper function used by util.escapeId*()
23 * @ignore
24 *
25 * @param {string} str String to be encoded
26 * @param {string} mode Encoding mode, see documentation for $wgFragmentMode
27 * in DefaultSettings.php
28 * @return {string} Encoded string
29 */
30 function escapeIdInternal( str, mode ) {
31 str = String( str );
32
33 switch ( mode ) {
34 case 'html5':
35 return str.replace( / /g, '_' );
36 case 'legacy':
37 return rawurlencode( str.replace( / /g, '_' ) )
38 .replace( /%3A/g, ':' )
39 .replace( /%/g, '.' );
40 default:
41 throw new Error( 'Unrecognized ID escaping mode ' + mode );
42 }
43 }
44
45 /**
46 * Utility library
47 * @class mw.util
48 * @singleton
49 */
50 util = {
51
52 /**
53 * Encode the string like PHP's rawurlencode
54 *
55 * @param {string} str String to be encoded.
56 * @return {string} Encoded string
57 */
58 rawurlencode: rawurlencode,
59
60 /**
61 * Encode string into HTML id compatible form suitable for use in HTML
62 * Analog to PHP Sanitizer::escapeIdForAttribute()
63 *
64 * @since 1.30
65 *
66 * @param {string} str String to encode
67 * @return {string} Encoded string
68 */
69 escapeIdForAttribute: function ( str ) {
70 var mode = config.FragmentMode[ 0 ];
71
72 return escapeIdInternal( str, mode );
73 },
74
75 /**
76 * Encode string into HTML id compatible form suitable for use in links
77 * Analog to PHP Sanitizer::escapeIdForLink()
78 *
79 * @since 1.30
80 *
81 * @param {string} str String to encode
82 * @return {string} Encoded string
83 */
84 escapeIdForLink: function ( str ) {
85 var mode = config.FragmentMode[ 0 ];
86
87 return escapeIdInternal( str, mode );
88 },
89
90 /**
91 * Encode page titles for use in a URL
92 *
93 * We want / and : to be included as literal characters in our title URLs
94 * as they otherwise fatally break the title.
95 *
96 * The others are decoded because we can, it's prettier and matches behaviour
97 * of `wfUrlencode` in PHP.
98 *
99 * @param {string} str String to be encoded.
100 * @return {string} Encoded string
101 */
102 wikiUrlencode: function ( str ) {
103 return util.rawurlencode( str )
104 .replace( /%20/g, '_' )
105 // wfUrlencode replacements
106 .replace( /%3B/g, ';' )
107 .replace( /%40/g, '@' )
108 .replace( /%24/g, '$' )
109 .replace( /%21/g, '!' )
110 .replace( /%2A/g, '*' )
111 .replace( /%28/g, '(' )
112 .replace( /%29/g, ')' )
113 .replace( /%2C/g, ',' )
114 .replace( /%2F/g, '/' )
115 .replace( /%7E/g, '~' )
116 .replace( /%3A/g, ':' );
117 },
118
119 /**
120 * Get the link to a page name (relative to `wgServer`),
121 *
122 * @param {string|null} [pageName=wgPageName] Page name
123 * @param {Object} [params] A mapping of query parameter names to values,
124 * e.g. `{ action: 'edit' }`
125 * @return {string} Url of the page with name of `pageName`
126 */
127 getUrl: function ( pageName, params ) {
128 var titleFragmentStart, url, query,
129 fragment = '',
130 title = typeof pageName === 'string' ? pageName : mw.config.get( 'wgPageName' );
131
132 // Find any fragment
133 titleFragmentStart = title.indexOf( '#' );
134 if ( titleFragmentStart !== -1 ) {
135 fragment = title.slice( titleFragmentStart + 1 );
136 // Exclude the fragment from the page name
137 title = title.slice( 0, titleFragmentStart );
138 }
139
140 // Produce query string
141 if ( params ) {
142 query = $.param( params );
143 }
144 if ( query ) {
145 url = title ?
146 util.wikiScript() + '?title=' + util.wikiUrlencode( title ) + '&' + query :
147 util.wikiScript() + '?' + query;
148 } else {
149 url = mw.config.get( 'wgArticlePath' )
150 .replace( '$1', util.wikiUrlencode( title ).replace( /\$/g, '$$$$' ) );
151 }
152
153 // Append the encoded fragment
154 if ( fragment.length ) {
155 url += '#' + util.escapeIdForLink( fragment );
156 }
157
158 return url;
159 },
160
161 /**
162 * Get address to a script in the wiki root.
163 * For index.php use `mw.config.get( 'wgScript' )`.
164 *
165 * @since 1.18
166 * @param {string} str Name of script (e.g. 'api'), defaults to 'index'
167 * @return {string} Address to script (e.g. '/w/api.php' )
168 */
169 wikiScript: function ( str ) {
170 str = str || 'index';
171 if ( str === 'index' ) {
172 return mw.config.get( 'wgScript' );
173 } else if ( str === 'load' ) {
174 return config.LoadScript;
175 } else {
176 return mw.config.get( 'wgScriptPath' ) + '/' + str + '.php';
177 }
178 },
179
180 /**
181 * Append a new style block to the head and return the CSSStyleSheet object.
182 * Use .ownerNode to access the `<style>` element, or use mw.loader#addStyleTag.
183 * This function returns the styleSheet object for convience (due to cross-browsers
184 * difference as to where it is located).
185 *
186 * var sheet = util.addCSS( '.foobar { display: none; }' );
187 * $( foo ).click( function () {
188 * // Toggle the sheet on and off
189 * sheet.disabled = !sheet.disabled;
190 * } );
191 *
192 * @param {string} text CSS to be appended
193 * @return {CSSStyleSheet} Use .ownerNode to get to the `<style>` element.
194 */
195 addCSS: function ( text ) {
196 var s = mw.loader.addStyleTag( text );
197 return s.sheet || s.styleSheet || s;
198 },
199
200 /**
201 * Grab the URL parameter value for the given parameter.
202 * Returns null if not found.
203 *
204 * @param {string} param The parameter name.
205 * @param {string} [url=location.href] URL to search through, defaulting to the current browsing location.
206 * @return {Mixed} Parameter value or null.
207 */
208 getParamValue: function ( param, url ) {
209 // Get last match, stop at hash
210 var re = new RegExp( '^[^#]*[&?]' + mw.RegExp.escape( param ) + '=([^&#]*)' ),
211 m = re.exec( url !== undefined ? url : location.href );
212
213 if ( m ) {
214 // Beware that decodeURIComponent is not required to understand '+'
215 // by spec, as encodeURIComponent does not produce it.
216 return decodeURIComponent( m[ 1 ].replace( /\+/g, '%20' ) );
217 }
218 return null;
219 },
220
221 /**
222 * The content wrapper of the skin (e.g. `.mw-body`).
223 *
224 * Populated on document ready. To use this property,
225 * wait for `$.ready` and be sure to have a module dependency on
226 * `mediawiki.util` which will ensure
227 * your document ready handler fires after initialization.
228 *
229 * Because of the lazy-initialised nature of this property,
230 * you're discouraged from using it.
231 *
232 * If you need just the wikipage content (not any of the
233 * extra elements output by the skin), use `$( '#mw-content-text' )`
234 * instead. Or listen to mw.hook#wikipage_content which will
235 * allow your code to re-run when the page changes (e.g. live preview
236 * or re-render after ajax save).
237 *
238 * @property {jQuery}
239 */
240 $content: null,
241
242 /**
243 * Add a link to a portlet menu on the page, such as:
244 *
245 * p-cactions (Content actions), p-personal (Personal tools),
246 * p-navigation (Navigation), p-tb (Toolbox)
247 *
248 * The first three parameters are required, the others are optional and
249 * may be null. Though providing an id and tooltip is recommended.
250 *
251 * By default the new link will be added to the end of the list. To
252 * add the link before a given existing item, pass the DOM node
253 * (e.g. `document.getElementById( 'foobar' )`) or a jQuery-selector
254 * (e.g. `'#foobar'`) for that item.
255 *
256 * util.addPortletLink(
257 * 'p-tb', 'https://www.mediawiki.org/',
258 * 'mediawiki.org', 't-mworg', 'Go to mediawiki.org', 'm', '#t-print'
259 * );
260 *
261 * var node = util.addPortletLink(
262 * 'p-tb',
263 * new mw.Title( 'Special:Example' ).getUrl(),
264 * 'Example'
265 * );
266 * $( node ).on( 'click', function ( e ) {
267 * console.log( 'Example' );
268 * e.preventDefault();
269 * } );
270 *
271 * @param {string} portletId ID of the target portlet (e.g. 'p-cactions' or 'p-personal')
272 * @param {string} href Link URL
273 * @param {string} text Link text
274 * @param {string} [id] ID of the list item, should be unique and preferably have
275 * the appropriate prefix ('ca-', 'pt-', 'n-' or 't-')
276 * @param {string} [tooltip] Text to show when hovering over the link, without accesskey suffix
277 * @param {string} [accesskey] Access key to activate this link. One character only,
278 * avoid conflicts with other links. Use `$( '[accesskey=x]' )` in the console to
279 * see if 'x' is already used.
280 * @param {HTMLElement|jQuery|string} [nextnode] Element that the new item should be added before.
281 * Must be another item in the same list, it will be ignored otherwise.
282 * Can be specified as DOM reference, as jQuery object, or as CSS selector string.
283 * @return {HTMLElement|null} The added list item, or null if no element was added.
284 */
285 addPortletLink: function ( portletId, href, text, id, tooltip, accesskey, nextnode ) {
286 var item, link, $portlet, portlet, portletDiv, ul, next;
287
288 if ( !portletId ) {
289 // Avoid confusing id="undefined" lookup
290 return null;
291 }
292
293 portlet = document.getElementById( portletId );
294 if ( !portlet ) {
295 // Invalid portlet ID
296 return null;
297 }
298
299 // Setup the anchor tag and set any the properties
300 link = document.createElement( 'a' );
301 link.href = href;
302 link.textContent = text;
303 if ( tooltip ) {
304 link.title = tooltip;
305 }
306 if ( accesskey ) {
307 link.accessKey = accesskey;
308 }
309
310 // Unhide portlet if it was hidden before
311 $portlet = $( portlet );
312 $portlet.removeClass( 'emptyPortlet' );
313
314 // Setup the list item (and a span if $portlet is a Vector tab)
315 // eslint-disable-next-line no-jquery/no-class-state
316 if ( $portlet.hasClass( 'vectorTabs' ) ) {
317 item = $( '<li>' ).append( $( '<span>' ).append( link )[ 0 ] )[ 0 ];
318 } else {
319 item = $( '<li>' ).append( link )[ 0 ];
320 }
321 if ( id ) {
322 item.id = id;
323 }
324
325 // Select the first (most likely only) unordered list inside the portlet
326 ul = portlet.querySelector( 'ul' );
327 if ( !ul ) {
328 // If it didn't have an unordered list yet, create one
329 ul = document.createElement( 'ul' );
330 portletDiv = portlet.querySelector( 'div' );
331 if ( portletDiv ) {
332 // Support: Legacy skins have a div (such as div.body or div.pBody).
333 // Append the <ul> to that.
334 portletDiv.appendChild( ul );
335 } else {
336 // Append it to the portlet directly
337 portlet.appendChild( ul );
338 }
339 }
340
341 if ( nextnode && ( typeof nextnode === 'string' || nextnode.nodeType || nextnode.jquery ) ) {
342 nextnode = $( ul ).find( nextnode );
343 if ( nextnode.length === 1 && nextnode[ 0 ].parentNode === ul ) {
344 // Insertion point: Before nextnode
345 nextnode.before( item );
346 next = true;
347 }
348 // Else: Invalid nextnode value (no match, more than one match, or not a direct child)
349 // Else: Invalid nextnode type
350 }
351
352 if ( !next ) {
353 // Insertion point: End of list (default)
354 ul.appendChild( item );
355 }
356
357 // Update tooltip for the access key after inserting into DOM
358 // to get a localized access key label (T69946).
359 if ( accesskey ) {
360 $( link ).updateTooltipAccessKeys();
361 }
362
363 return item;
364 },
365
366 /**
367 * Validate a string as representing a valid e-mail address
368 * according to HTML5 specification. Please note the specification
369 * does not validate a domain with one character.
370 *
371 * FIXME: should be moved to or replaced by a validation module.
372 *
373 * @param {string} mailtxt E-mail address to be validated.
374 * @return {boolean|null} Null if `mailtxt` was an empty string, otherwise true/false
375 * as determined by validation.
376 */
377 validateEmail: function ( mailtxt ) {
378 var rfc5322Atext, rfc1034LdhStr, html5EmailRegexp;
379
380 if ( mailtxt === '' ) {
381 return null;
382 }
383
384 // HTML5 defines a string as valid e-mail address if it matches
385 // the ABNF:
386 // 1 * ( atext / "." ) "@" ldh-str 1*( "." ldh-str )
387 // With:
388 // - atext : defined in RFC 5322 section 3.2.3
389 // - ldh-str : defined in RFC 1034 section 3.5
390 //
391 // (see STD 68 / RFC 5234 https://tools.ietf.org/html/std68)
392 // First, define the RFC 5322 'atext' which is pretty easy:
393 // atext = ALPHA / DIGIT / ; Printable US-ASCII
394 // "!" / "#" / ; characters not including
395 // "$" / "%" / ; specials. Used for atoms.
396 // "&" / "'" /
397 // "*" / "+" /
398 // "-" / "/" /
399 // "=" / "?" /
400 // "^" / "_" /
401 // "`" / "{" /
402 // "|" / "}" /
403 // "~"
404 rfc5322Atext = 'a-z0-9!#$%&\'*+\\-/=?^_`{|}~';
405
406 // Next define the RFC 1034 'ldh-str'
407 // <domain> ::= <subdomain> | " "
408 // <subdomain> ::= <label> | <subdomain> "." <label>
409 // <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
410 // <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
411 // <let-dig-hyp> ::= <let-dig> | "-"
412 // <let-dig> ::= <letter> | <digit>
413 rfc1034LdhStr = 'a-z0-9\\-';
414
415 html5EmailRegexp = new RegExp(
416 // start of string
417 '^' +
418 // User part which is liberal :p
419 '[' + rfc5322Atext + '\\.]+' +
420 // 'at'
421 '@' +
422 // Domain first part
423 '[' + rfc1034LdhStr + ']+' +
424 // Optional second part and following are separated by a dot
425 '(?:\\.[' + rfc1034LdhStr + ']+)*' +
426 // End of string
427 '$',
428 // RegExp is case insensitive
429 'i'
430 );
431 return ( mailtxt.match( html5EmailRegexp ) !== null );
432 },
433
434 /**
435 * Note: borrows from IP::isIPv4
436 *
437 * @param {string} address
438 * @param {boolean} [allowBlock=false]
439 * @return {boolean}
440 */
441 isIPv4Address: function ( address, allowBlock ) {
442 var block, RE_IP_BYTE, RE_IP_ADD;
443
444 if ( typeof address !== 'string' ) {
445 return false;
446 }
447
448 block = allowBlock ? '(?:\\/(?:3[0-2]|[12]?\\d))?' : '';
449 RE_IP_BYTE = '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])';
450 RE_IP_ADD = '(?:' + RE_IP_BYTE + '\\.){3}' + RE_IP_BYTE;
451
452 return ( new RegExp( '^' + RE_IP_ADD + block + '$' ).test( address ) );
453 },
454
455 /**
456 * Note: borrows from IP::isIPv6
457 *
458 * @param {string} address
459 * @param {boolean} [allowBlock=false]
460 * @return {boolean}
461 */
462 isIPv6Address: function ( address, allowBlock ) {
463 var block, RE_IPV6_ADD;
464
465 if ( typeof address !== 'string' ) {
466 return false;
467 }
468
469 block = allowBlock ? '(?:\\/(?:12[0-8]|1[01][0-9]|[1-9]?\\d))?' : '';
470 RE_IPV6_ADD =
471 '(?:' + // starts with "::" (including "::")
472 ':(?::|(?::' +
473 '[0-9A-Fa-f]{1,4}' +
474 '){1,7})' +
475 '|' + // ends with "::" (except "::")
476 '[0-9A-Fa-f]{1,4}' +
477 '(?::' +
478 '[0-9A-Fa-f]{1,4}' +
479 '){0,6}::' +
480 '|' + // contains no "::"
481 '[0-9A-Fa-f]{1,4}' +
482 '(?::' +
483 '[0-9A-Fa-f]{1,4}' +
484 '){7}' +
485 ')';
486
487 if ( new RegExp( '^' + RE_IPV6_ADD + block + '$' ).test( address ) ) {
488 return true;
489 }
490
491 // contains one "::" in the middle (single '::' check below)
492 RE_IPV6_ADD =
493 '[0-9A-Fa-f]{1,4}' +
494 '(?:::?' +
495 '[0-9A-Fa-f]{1,4}' +
496 '){1,6}';
497
498 return (
499 new RegExp( '^' + RE_IPV6_ADD + block + '$' ).test( address ) &&
500 /::/.test( address ) &&
501 !/::.*::/.test( address )
502 );
503 },
504
505 /**
506 * Check whether a string is an IP address
507 *
508 * @since 1.25
509 * @param {string} address String to check
510 * @param {boolean} [allowBlock=false] If a block of IPs should be allowed
511 * @return {boolean}
512 */
513 isIPAddress: function ( address, allowBlock ) {
514 return util.isIPv4Address( address, allowBlock ) ||
515 util.isIPv6Address( address, allowBlock );
516 }
517 };
518
519 // Not allowed outside unit tests
520 if ( window.QUnit ) {
521 util.setOptionsForTest = function ( opts ) {
522 var oldConfig = config;
523 config = $.extend( {}, config, opts );
524 return oldConfig;
525 };
526 }
527
528 /**
529 * Initialisation of mw.util.$content
530 */
531 function init() {
532 util.$content = ( function () {
533 var i, l, $node, selectors;
534
535 selectors = [
536 // The preferred standard is class "mw-body".
537 // You may also use class "mw-body mw-body-primary" if you use
538 // mw-body in multiple locations. Or class "mw-body-primary" if
539 // you use mw-body deeper in the DOM.
540 '.mw-body-primary',
541 '.mw-body',
542
543 // If the skin has no such class, fall back to the parser output
544 '#mw-content-text'
545 ];
546
547 for ( i = 0, l = selectors.length; i < l; i++ ) {
548 $node = $( selectors[ i ] );
549 if ( $node.length ) {
550 return $node.first();
551 }
552 }
553
554 // Should never happen... well, it could if someone is not finished writing a
555 // skin and has not yet inserted bodytext yet.
556 return $( 'body' );
557 }() );
558 }
559
560 $( init );
561
562 mw.util = util;
563 module.exports = util;
564
565 }() );