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