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