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