7 * Encode the string like PHP's rawurlencode
10 * @param {string} str String to be encoded.
11 * @return {string} Encoded string
13 function rawurlencode( 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
' );
21 * Private helper function used by util.escapeId*()
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
29 function escapeIdInternal( str, mode ) {
34 return str.replace( / /g, '_
' );
36 str = str.replace( /[ \t\n\r\f_'"&#%]+/g, '_' )
37 .replace( /^_+|_+$/, '' );
43 return rawurlencode( str.replace( / /g, '_' ) )
44 .replace( /%3A/g, ':' )
45 .replace( /%/g, '.' );
47 throw new Error( 'Unrecognized ID escaping mode ' + mode );
61 * Encode the string like PHP's rawurlencode
63 * @param {string} str String to be encoded.
64 * @return {string} Encoded string
66 rawurlencode: rawurlencode,
69 * Encode string into HTML id compatible form suitable for use in HTML
70 * Analog to PHP Sanitizer::escapeIdForAttribute()
74 * @param {string} str String to encode
75 * @return {string} Encoded string
77 escapeIdForAttribute: function ( str ) {
78 var mode = mw.config.get( 'wgFragmentMode' )[ 0 ];
80 return escapeIdInternal( str, mode );
84 * Encode string into HTML id compatible form suitable for use in links
85 * Analog to PHP Sanitizer::escapeIdForLink()
89 * @param {string} str String to encode
90 * @return {string} Encoded string
92 escapeIdForLink: function ( str ) {
93 var mode = mw.config.get( 'wgFragmentMode' )[ 0 ],
94 id = escapeIdInternal( str, mode );
96 if ( mode === 'html5' ) {
97 id = encodeURIComponent( id ).replace( /%3A/g, ':' );
104 * Encode page titles for use in a URL
106 * We want / and : to be included as literal characters in our title URLs
107 * as they otherwise fatally break the title.
109 * The others are decoded because we can, it's prettier and matches behaviour
110 * of `wfUrlencode` in PHP.
112 * @param {string} str String to be encoded.
113 * @return {string} Encoded string
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, ':' );
133 * Get the link to a page name (relative to `wgServer`),
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`
140 getUrl: function ( pageName, params ) {
141 var titleFragmentStart, url, query,
143 title = typeof pageName === 'string' ? pageName : mw.config.get( 'wgPageName' );
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 );
153 // Produce query string
155 query = $.param( params );
159 util.wikiScript() + '?title=' + util.wikiUrlencode( title ) + '&' + query :
160 util.wikiScript() + '?' + query;
162 url = mw.config.get( 'wgArticlePath' )
163 .replace( '$1', util.wikiUrlencode( title ).replace( /\$/g, '$$$$' ) );
166 // Append the encoded fragment
167 if ( fragment.length ) {
168 url += '#' + util.escapeIdForLink( fragment );
175 * Get address to a script in the wiki root.
176 * For index.php use `mw.config.get( 'wgScript' )`.
179 * @param {string} str Name of script (e.g. 'api'), defaults to 'index'
180 * @return {string} Address to script (e.g. '/w/api.php' )
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' );
189 return mw.config.get( 'wgScriptPath' ) + '/' + str + '.php';
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).
199 * var sheet = util.addCSS( '.foobar { display: none; }' );
200 * $( foo ).click( function () {
201 * // Toggle the sheet on and off
202 * sheet.disabled = !sheet.disabled;
205 * @param {string} text CSS to be appended
206 * @return {CSSStyleSheet} Use .ownerNode to get to the `<style>` element.
208 addCSS: function ( text ) {
209 var s = mw.loader.addStyleTag( text );
210 return s.sheet || s.styleSheet || s;
214 * Grab the URL parameter value for the given parameter.
215 * Returns null if not found.
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.
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 );
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' ) );
235 * The content wrapper of the skin (e.g. `.mw-body`).
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.
242 * Because of the lazy-initialised nature of this property,
243 * you're discouraged from using it.
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).
256 * Add a link to a portlet menu on the page, such as:
258 * p-cactions (Content actions), p-personal (Personal tools),
259 * p-navigation (Navigation), p-tb (Toolbox)
261 * The first three parameters are required, the others are optional and
262 * may be null. Though providing an id and tooltip is recommended.
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.
269 * util.addPortletLink(
270 * 'p-tb', 'https://www.mediawiki.org/',
271 * 'mediawiki.org', 't-mworg', 'Go to mediawiki.org', 'm', '#t-print'
274 * var node = util.addPortletLink(
276 * new mw.Title( 'Special:Example' ).getUrl(),
279 * $( node ).on( 'click', function ( e ) {
280 * console.log( 'Example' );
281 * e.preventDefault();
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
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.
300 addPortletLink: function ( portlet, href, text, id, tooltip, accesskey, nextnode ) {
301 var $item, $link, $portlet, $ul;
303 // Check if there's at least 3 arguments to prevent a TypeError
304 if ( arguments.length < 3 ) {
307 // Setup the anchor tag
308 $link = $( '<a>' ).attr( 'href', href ).text( text );
310 $link.attr( 'title', tooltip );
313 // Select the specified portlet
314 $portlet = $( '#' + portlet );
315 if ( $portlet.length === 0 ) {
318 // Select the first (most likely only) unordered list inside the portlet
319 $ul = $portlet.find( 'ul' ).eq( 0 );
321 // If it didn't have an unordered list yet, create it
322 if ( $ul.length === 0 ) {
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 );
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 );
336 if ( $ul.length === 0 ) {
340 // Unhide portlet if it was hidden before
341 $portlet.removeClass( 'emptyPortlet' );
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();
348 $item = $link.wrap( '<li></li>' ).parent();
351 // Implement the properties passed to the function
353 $item.attr( 'id', id );
357 $link.attr( 'accesskey', accesskey );
361 $link.attr( 'title', tooltip );
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;
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;
380 // Case: nextnode is a jQuery-wrapped DOM element
382 nextnode.before( $item );
384 // Fallback (this is the default behavior)
388 // Update tooltip for the access key after inserting into DOM
389 // to get a localized access key label (T69946).
390 $link.updateTooltipAccessKeys();
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.
400 * FIXME: should be moved to or replaced by a validation module.
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.
406 validateEmail: function ( mailtxt ) {
407 var rfc5322Atext, rfc1034LdhStr, html5EmailRegexp;
409 if ( mailtxt === '' ) {
413 // HTML5 defines a string as valid e-mail address if it matches
415 // 1 * ( atext / "." ) "@" ldh-str 1*( "." ldh-str )
417 // - atext : defined in RFC 5322 section 3.2.3
418 // - ldh-str : defined in RFC 1034 section 3.5
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.
433 rfc5322Atext = 'a
-z0
-9!#$%&\'*+\\-/=?^_
`{|}~';
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\\-';
444 html5EmailRegexp = new RegExp(
447 // User part which is liberal :p
448 '[' + rfc5322Atext + '\\.]+' +
452 '[' + rfc1034LdhStr + ']+' +
453 // Optional second part and following are separated by a dot
454 '(?:\\.[' + rfc1034LdhStr + ']+)*' +
457 // RegExp is case insensitive
460 return ( mailtxt.match( html5EmailRegexp ) !== null );
464 * Note: borrows from IP::isIPv4
466 * @param {string} address
467 * @param {boolean} allowBlock
470 isIPv4Address: function ( address, allowBlock ) {
471 var block, RE_IP_BYTE, RE_IP_ADD;
473 if ( typeof address !== 'string' ) {
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;
481 return ( new RegExp( '^' + RE_IP_ADD + block + '$' ).test( address ) );
485 * Note: borrows from IP::isIPv6
487 * @param {string} address
488 * @param {boolean} allowBlock
491 isIPv6Address: function ( address, allowBlock ) {
492 var block, RE_IPV6_ADD;
494 if ( typeof address !== 'string' ) {
498 block = allowBlock ? '(?:\\/(?:12[0-8]|1[01][0-9]|[1-9]?\\d))?' : '';
500 '(?:' + // starts with "::" (including "::")
504 '|' + // ends with "::" (except "::")
509 '|' + // contains no "::"
516 if ( new RegExp( '^' + RE_IPV6_ADD + block + '$' ).test( address ) ) {
520 // contains one "::" in the middle (single '::' check below)
528 new RegExp( '^' + RE_IPV6_ADD + block + '$' ).test( address ) &&
529 /::/.test( address ) &&
530 !/::.*::/.test( address )
535 * Check whether a string is an IP address
538 * @param {string} address String to check
539 * @param {boolean} allowBlock True if a block of IPs should be allowed
542 isIPAddress: function ( address, allowBlock ) {
543 return util.isIPv4Address( address, allowBlock ) ||
544 util.isIPv6Address( address, allowBlock );
549 * @method wikiGetlink
550 * @inheritdoc #getUrl
551 * @deprecated since 1.23 Use #getUrl instead.
553 mw.log.deprecate( util, 'wikiGetlink', util.getUrl, 'Use mw.util.getUrl instead.', 'mw.util.wikiGetlink' );
556 * Add the appropriate prefix to the accesskey shown in the tooltip.
558 * If the `$nodes
` parameter is given, only those nodes are updated;
559 * otherwise we update all elements with accesskeys on the page.
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.
565 mw.log.deprecate( util, 'updateTooltipAccessKeys', function ( $nodes ) {
567 $nodes = $( '[accesskey]' );
568 } else if ( !( $nodes instanceof $ ) ) {
569 $nodes = $( $nodes );
572 $nodes.updateTooltipAccessKeys();
573 }, 'Use jquery.accessKeyLabel instead.', 'mw.util.updateTooltipAccessKeys' );
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
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.
585 mw.log.deprecate( util, 'jsMessage', function ( message ) {
586 if ( !arguments.length || message === '' || message === null ) {
589 if ( typeof message !== 'object' ) {
590 message = $.parseHTML( message );
592 mw.notify( message, { autoHide: true, tag: 'legacy' } );
594 }, 'Use mw.notify instead.', 'mw.util.jsMessage' );
597 * Encode the string like Sanitizer::escapeId() in PHP
600 * @deprecated since 1.30 use escapeIdForAttribute() or escapeIdForLink()
601 * @param {string} str String to be encoded.
602 * @return {string} Encoded string
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' );
609 * Initialisation of mw.util.$content
612 util.$content = ( function () {
613 var i, l, $node, 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.
623 // If the skin has no such class, fall back to the parser output
627 for ( i = 0, l = selectors.length; i < l; i++ ) {
628 $node = $( selectors[ i ] );
629 if ( $node.length ) {
630 return $node.first();
634 // Should never happen... well, it could if someone is not finished writing a
635 // skin and has not yet inserted bodytext yet.
641 * Former public initialisation. Now a no-op function.
644 * @deprecated since 1.30
646 mw.log.deprecate( util, 'init', $.noop, 'Remove the call of mw.util.init().', 'mw.util.init' );
651 module.exports = util;
653 }( mediaWiki, jQuery ) );