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