66c1fe74d10d5aacc32ad93c4d6610154f85ae38
[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 config.LoadScript;
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 // eslint-disable-next-line no-jquery/no-class-state
333 if ( $portlet.hasClass( 'vectorTabs' ) ) {
334 item = $( '<li>' ).append( $( '<span>' ).append( link )[ 0 ] )[ 0 ];
335 } else {
336 item = $( '<li>' ).append( link )[ 0 ];
337 }
338 if ( id ) {
339 item.id = id;
340 }
341
342 // Select the first (most likely only) unordered list inside the portlet
343 ul = portlet.querySelector( 'ul' );
344 if ( !ul ) {
345 // If it didn't have an unordered list yet, create one
346 ul = document.createElement( 'ul' );
347 portletDiv = portlet.querySelector( 'div' );
348 if ( portletDiv ) {
349 // Support: Legacy skins have a div (such as div.body or div.pBody).
350 // Append the <ul> to that.
351 portletDiv.appendChild( ul );
352 } else {
353 // Append it to the portlet directly
354 portlet.appendChild( ul );
355 }
356 }
357
358 if ( nextnode && ( typeof nextnode === 'string' || nextnode.nodeType || nextnode.jquery ) ) {
359 nextnode = $( ul ).find( nextnode );
360 if ( nextnode.length === 1 && nextnode[ 0 ].parentNode === ul ) {
361 // Insertion point: Before nextnode
362 nextnode.before( item );
363 next = true;
364 }
365 // Else: Invalid nextnode value (no match, more than one match, or not a direct child)
366 // Else: Invalid nextnode type
367 }
368
369 if ( !next ) {
370 // Insertion point: End of list (default)
371 ul.appendChild( item );
372 }
373
374 // Update tooltip for the access key after inserting into DOM
375 // to get a localized access key label (T69946).
376 if ( accesskey ) {
377 $( link ).updateTooltipAccessKeys();
378 }
379
380 return item;
381 },
382
383 /**
384 * Validate a string as representing a valid e-mail address
385 * according to HTML5 specification. Please note the specification
386 * does not validate a domain with one character.
387 *
388 * FIXME: should be moved to or replaced by a validation module.
389 *
390 * @param {string} mailtxt E-mail address to be validated.
391 * @return {boolean|null} Null if `mailtxt` was an empty string, otherwise true/false
392 * as determined by validation.
393 */
394 validateEmail: function ( mailtxt ) {
395 var rfc5322Atext, rfc1034LdhStr, html5EmailRegexp;
396
397 if ( mailtxt === '' ) {
398 return null;
399 }
400
401 // HTML5 defines a string as valid e-mail address if it matches
402 // the ABNF:
403 // 1 * ( atext / "." ) "@" ldh-str 1*( "." ldh-str )
404 // With:
405 // - atext : defined in RFC 5322 section 3.2.3
406 // - ldh-str : defined in RFC 1034 section 3.5
407 //
408 // (see STD 68 / RFC 5234 https://tools.ietf.org/html/std68)
409 // First, define the RFC 5322 'atext' which is pretty easy:
410 // atext = ALPHA / DIGIT / ; Printable US-ASCII
411 // "!" / "#" / ; characters not including
412 // "$" / "%" / ; specials. Used for atoms.
413 // "&" / "'" /
414 // "*" / "+" /
415 // "-" / "/" /
416 // "=" / "?" /
417 // "^" / "_" /
418 // "`" / "{" /
419 // "|" / "}" /
420 // "~"
421 rfc5322Atext = 'a-z0-9!#$%&\'*+\\-/=?^_`{|}~';
422
423 // Next define the RFC 1034 'ldh-str'
424 // <domain> ::= <subdomain> | " "
425 // <subdomain> ::= <label> | <subdomain> "." <label>
426 // <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
427 // <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
428 // <let-dig-hyp> ::= <let-dig> | "-"
429 // <let-dig> ::= <letter> | <digit>
430 rfc1034LdhStr = 'a-z0-9\\-';
431
432 html5EmailRegexp = new RegExp(
433 // start of string
434 '^' +
435 // User part which is liberal :p
436 '[' + rfc5322Atext + '\\.]+' +
437 // 'at'
438 '@' +
439 // Domain first part
440 '[' + rfc1034LdhStr + ']+' +
441 // Optional second part and following are separated by a dot
442 '(?:\\.[' + rfc1034LdhStr + ']+)*' +
443 // End of string
444 '$',
445 // RegExp is case insensitive
446 'i'
447 );
448 return ( mailtxt.match( html5EmailRegexp ) !== null );
449 },
450
451 /**
452 * Note: borrows from IP::isIPv4
453 *
454 * @param {string} address
455 * @param {boolean} [allowBlock=false]
456 * @return {boolean}
457 */
458 isIPv4Address: function ( address, allowBlock ) {
459 var block, RE_IP_BYTE, RE_IP_ADD;
460
461 if ( typeof address !== 'string' ) {
462 return false;
463 }
464
465 block = allowBlock ? '(?:\\/(?:3[0-2]|[12]?\\d))?' : '';
466 RE_IP_BYTE = '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])';
467 RE_IP_ADD = '(?:' + RE_IP_BYTE + '\\.){3}' + RE_IP_BYTE;
468
469 return ( new RegExp( '^' + RE_IP_ADD + block + '$' ).test( address ) );
470 },
471
472 /**
473 * Note: borrows from IP::isIPv6
474 *
475 * @param {string} address
476 * @param {boolean} [allowBlock=false]
477 * @return {boolean}
478 */
479 isIPv6Address: function ( address, allowBlock ) {
480 var block, RE_IPV6_ADD;
481
482 if ( typeof address !== 'string' ) {
483 return false;
484 }
485
486 block = allowBlock ? '(?:\\/(?:12[0-8]|1[01][0-9]|[1-9]?\\d))?' : '';
487 RE_IPV6_ADD =
488 '(?:' + // starts with "::" (including "::")
489 ':(?::|(?::' +
490 '[0-9A-Fa-f]{1,4}' +
491 '){1,7})' +
492 '|' + // ends with "::" (except "::")
493 '[0-9A-Fa-f]{1,4}' +
494 '(?::' +
495 '[0-9A-Fa-f]{1,4}' +
496 '){0,6}::' +
497 '|' + // contains no "::"
498 '[0-9A-Fa-f]{1,4}' +
499 '(?::' +
500 '[0-9A-Fa-f]{1,4}' +
501 '){7}' +
502 ')';
503
504 if ( new RegExp( '^' + RE_IPV6_ADD + block + '$' ).test( address ) ) {
505 return true;
506 }
507
508 // contains one "::" in the middle (single '::' check below)
509 RE_IPV6_ADD =
510 '[0-9A-Fa-f]{1,4}' +
511 '(?:::?' +
512 '[0-9A-Fa-f]{1,4}' +
513 '){1,6}';
514
515 return (
516 new RegExp( '^' + RE_IPV6_ADD + block + '$' ).test( address ) &&
517 /::/.test( address ) &&
518 !/::.*::/.test( address )
519 );
520 },
521
522 /**
523 * Check whether a string is an IP address
524 *
525 * @since 1.25
526 * @param {string} address String to check
527 * @param {boolean} [allowBlock=false] If a block of IPs should be allowed
528 * @return {boolean}
529 */
530 isIPAddress: function ( address, allowBlock ) {
531 return util.isIPv4Address( address, allowBlock ) ||
532 util.isIPv6Address( address, allowBlock );
533 }
534 };
535
536 /**
537 * Initialisation of mw.util.$content
538 */
539 function init() {
540 util.$content = ( function () {
541 var i, l, $node, selectors;
542
543 selectors = [
544 // The preferred standard is class "mw-body".
545 // You may also use class "mw-body mw-body-primary" if you use
546 // mw-body in multiple locations. Or class "mw-body-primary" if
547 // you use mw-body deeper in the DOM.
548 '.mw-body-primary',
549 '.mw-body',
550
551 // If the skin has no such class, fall back to the parser output
552 '#mw-content-text'
553 ];
554
555 for ( i = 0, l = selectors.length; i < l; i++ ) {
556 $node = $( selectors[ i ] );
557 if ( $node.length ) {
558 return $node.first();
559 }
560 }
561
562 // Should never happen... well, it could if someone is not finished writing a
563 // skin and has not yet inserted bodytext yet.
564 return $( 'body' );
565 }() );
566 }
567
568 $( init );
569
570 mw.util = util;
571 module.exports = util;
572
573 }() );