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