Merge "Add structure test to ensure PSR-4 autoloader covers everything"
[lhc/web/wiklou.git] / resources / src / mediawiki.util.js
1 ( function ( mw, $ ) {
2 'use strict';
3
4 var util;
5
6 /**
7 * Encode the string like PHP's rawurlencode
8 * @ignore
9 *
10 * @param {string} str String to be encoded.
11 * @return {string} Encoded string
12 */
13 function rawurlencode( str ) {
14 str = String( str );
15 return encodeURIComponent( str )
16 .replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' )
17 .replace( /\)/g, '%29' ).replace( /\*/g, '%2A' ).replace( /~/g, '%7E' );
18 }
19
20 /**
21 * Private helper function used by util.escapeId*()
22 * @ignore
23 *
24 * @param {string} str String to be encoded
25 * @param {string} mode Encoding mode, see documentation for $wgFragmentMode
26 * in DefaultSettings.php
27 * @return {string} Encoded string
28 */
29 function escapeIdInternal( str, mode ) {
30 str = String( str );
31
32 switch ( mode ) {
33 case 'html5':
34 return str.replace( / /g, '_' );
35 case 'legacy':
36 return rawurlencode( str.replace( / /g, '_' ) )
37 .replace( /%3A/g, ':' )
38 .replace( /%/g, '.' );
39 default:
40 throw new Error( 'Unrecognized ID escaping mode ' + mode );
41 }
42 }
43
44 /**
45 * Utility library
46 * @class mw.util
47 * @singleton
48 */
49 util = {
50
51 /* Main body */
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 = mw.config.get( 'wgFragmentMode' )[ 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 = mw.config.get( 'wgFragmentMode' )[ 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 mw.config.get( 'wgLoadScript' );
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( '^[^#]*[&?]' + mw.RegExp.escape( 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} portlet ID of the target portlet ( 'p-cactions' or 'p-personal' etc.)
273 * @param {string} href Link URL
274 * @param {string} text Link text
275 * @param {string} [id] ID of the new 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, try
279 * to avoid conflicts. Use `$( '[accesskey=x]' ).get()` in the console to
280 * see if 'x' is already used.
281 * @param {HTMLElement|jQuery|string} [nextnode] Element or jQuery-selector string to the item that
282 * the new item should be added before, should be another item in the same
283 * list, it will be ignored otherwise
284 *
285 * @return {HTMLElement|null} The added element (a ListItem or Anchor element,
286 * depending on the skin) or null if no element was added to the document.
287 */
288 addPortletLink: function ( portlet, href, text, id, tooltip, accesskey, nextnode ) {
289 var $item, $link, $portlet, $ul;
290
291 // Check if there's at least 3 arguments to prevent a TypeError
292 if ( arguments.length < 3 ) {
293 return null;
294 }
295 // Setup the anchor tag
296 $link = $( '<a>' ).attr( 'href', href ).text( text );
297 if ( tooltip ) {
298 $link.attr( 'title', tooltip );
299 }
300
301 // Select the specified portlet
302 $portlet = $( '#' + portlet );
303 if ( $portlet.length === 0 ) {
304 return null;
305 }
306 // Select the first (most likely only) unordered list inside the portlet
307 $ul = $portlet.find( 'ul' ).eq( 0 );
308
309 // If it didn't have an unordered list yet, create it
310 if ( $ul.length === 0 ) {
311
312 $ul = $( '<ul>' );
313
314 // If there's no <div> inside, append it to the portlet directly
315 if ( $portlet.find( 'div:first' ).length === 0 ) {
316 $portlet.append( $ul );
317 } else {
318 // otherwise if there's a div (such as div.body or div.pBody)
319 // append the <ul> to last (most likely only) div
320 $portlet.find( 'div' ).eq( -1 ).append( $ul );
321 }
322 }
323 // Just in case..
324 if ( $ul.length === 0 ) {
325 return null;
326 }
327
328 // Unhide portlet if it was hidden before
329 $portlet.removeClass( 'emptyPortlet' );
330
331 // Wrap the anchor tag in a list item (and a span if $portlet is a Vector tab)
332 // and back up the selector to the list item
333 if ( $portlet.hasClass( 'vectorTabs' ) ) {
334 $item = $link.wrap( '<li><span></span></li>' ).parent().parent();
335 } else {
336 $item = $link.wrap( '<li></li>' ).parent();
337 }
338
339 // Implement the properties passed to the function
340 if ( id ) {
341 $item.attr( 'id', id );
342 }
343
344 if ( accesskey ) {
345 $link.attr( 'accesskey', accesskey );
346 }
347
348 if ( tooltip ) {
349 $link.attr( 'title', tooltip );
350 }
351
352 if ( nextnode ) {
353 // Case: nextnode is a DOM element (was the only option before MW 1.17, in wikibits.js)
354 // Case: nextnode is a CSS selector for jQuery
355 if ( nextnode.nodeType || typeof nextnode === 'string' ) {
356 nextnode = $ul.find( nextnode );
357 } else if ( !nextnode.jquery ) {
358 // Error: Invalid nextnode
359 nextnode = undefined;
360 }
361 if ( nextnode && ( nextnode.length !== 1 || nextnode[ 0 ].parentNode !== $ul[ 0 ] ) ) {
362 // Error: nextnode must resolve to a single node
363 // Error: nextnode must have the associated <ul> as its parent
364 nextnode = undefined;
365 }
366 }
367
368 // Case: nextnode is a jQuery-wrapped DOM element
369 if ( nextnode ) {
370 nextnode.before( $item );
371 } else {
372 // Fallback (this is the default behavior)
373 $ul.append( $item );
374 }
375
376 // Update tooltip for the access key after inserting into DOM
377 // to get a localized access key label (T69946).
378 $link.updateTooltipAccessKeys();
379
380 return $item[ 0 ];
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 * Add a little box at the top of the screen to inform the user of
538 * something, replacing any previous message.
539 * Calling with no arguments, with an empty string or null will hide the message
540 *
541 * @method jsMessage
542 * @deprecated since 1.20 Use mw#notify
543 * @param {Mixed} message The DOM-element, jQuery object or HTML-string to be put inside the message box.
544 * to allow CSS/JS to hide different boxes. null = no class used.
545 */
546 mw.log.deprecate( util, 'jsMessage', function ( message ) {
547 if ( !arguments.length || message === '' || message === null ) {
548 return true;
549 }
550 if ( typeof message !== 'object' ) {
551 message = $.parseHTML( message );
552 }
553 mw.notify( message, { autoHide: true, tag: 'legacy' } );
554 return true;
555 }, 'Use mw.notify instead.', 'mw.util.jsMessage' );
556
557 /**
558 * Initialisation of mw.util.$content
559 */
560 function init() {
561 util.$content = ( function () {
562 var i, l, $node, selectors;
563
564 selectors = [
565 // The preferred standard is class "mw-body".
566 // You may also use class "mw-body mw-body-primary" if you use
567 // mw-body in multiple locations. Or class "mw-body-primary" if
568 // you use mw-body deeper in the DOM.
569 '.mw-body-primary',
570 '.mw-body',
571
572 // If the skin has no such class, fall back to the parser output
573 '#mw-content-text'
574 ];
575
576 for ( i = 0, l = selectors.length; i < l; i++ ) {
577 $node = $( selectors[ i ] );
578 if ( $node.length ) {
579 return $node.first();
580 }
581 }
582
583 // Should never happen... well, it could if someone is not finished writing a
584 // skin and has not yet inserted bodytext yet.
585 return $( 'body' );
586 }() );
587 }
588
589 /**
590 * Former public initialisation. Now a no-op function.
591 *
592 * @method util_init
593 * @deprecated since 1.30
594 */
595 mw.log.deprecate( util, 'init', $.noop, 'Remove the call of mw.util.init().', 'mw.util.init' );
596
597 $( init );
598
599 mw.util = util;
600 module.exports = util;
601
602 }( mediaWiki, jQuery ) );