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 the string like Sanitizer::escapeId() in PHP
70 * @deprecated since 1.30 use escapeIdForAttribute() or escapeIdForLink()
72 * @param {string} str String to be encoded.
73 * @return {string} Encoded string
75 escapeId: function ( str ) {
76 return escapeIdInternal( str, 'legacy' );
80 * Encode string into HTML id compatible form suitable for use in HTML
81 * Analog to PHP Sanitizer::escapeIdForAttribute()
85 * @param {string} str String to encode
86 * @return {string} Encoded string
88 escapeIdForAttribute: function ( str ) {
89 var mode = mw.config.get( 'wgFragmentMode' )[ 0 ];
91 return escapeIdInternal( str, mode );
95 * Encode string into HTML id compatible form suitable for use in links
96 * Analog to PHP Sanitizer::escapeIdForLink()
100 * @param {string} str String to encode
101 * @return {string} Encoded string
103 escapeIdForLink: function ( str ) {
104 var mode = mw.config.get( 'wgFragmentMode' )[ 0 ],
105 id = escapeIdInternal( str, mode );
107 if ( mode === 'html5' ) {
108 id = encodeURIComponent( id ).replace( /%3A/g, ':' );
115 * Encode page titles for use in a URL
117 * We want / and : to be included as literal characters in our title URLs
118 * as they otherwise fatally break the title.
120 * The others are decoded because we can, it's prettier and matches behaviour
121 * of `wfUrlencode` in PHP.
123 * @param {string} str String to be encoded.
124 * @return {string} Encoded string
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, ':' );
144 * Get the link to a page name (relative to `wgServer`),
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`
151 getUrl: function ( pageName, params ) {
152 var titleFragmentStart, url, query,
154 title = typeof pageName === 'string' ? pageName : mw.config.get( 'wgPageName' );
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 );
164 // Produce query string
166 query = $.param( params );
170 util.wikiScript() + '?title=' + util.wikiUrlencode( title ) + '&' + query :
171 util.wikiScript() + '?' + query;
173 url = mw.config.get( 'wgArticlePath' )
174 .replace( '$1', util.wikiUrlencode( title ).replace( /\$/g, '$$$$' ) );
177 // Append the encoded fragment
178 if ( fragment.length ) {
179 url += '#' + util.escapeIdForLink( fragment );
186 * Get address to a script in the wiki root.
187 * For index.php use `mw.config.get( 'wgScript' )`.
190 * @param {string} str Name of script (e.g. 'api'), defaults to 'index'
191 * @return {string} Address to script (e.g. '/w/api.php' )
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' );
200 return mw.config.get( 'wgScriptPath' ) + '/' + str + '.php';
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).
210 * var sheet = util.addCSS( '.foobar { display: none; }' );
211 * $( foo ).click( function () {
212 * // Toggle the sheet on and off
213 * sheet.disabled = !sheet.disabled;
216 * @param {string} text CSS to be appended
217 * @return {CSSStyleSheet} Use .ownerNode to get to the `<style>` element.
219 addCSS: function ( text ) {
220 var s = mw.loader.addStyleTag( text );
221 return s.sheet || s.styleSheet || s;
225 * Grab the URL parameter value for the given parameter.
226 * Returns null if not found.
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.
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 );
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' ) );
246 * The content wrapper of the skin (e.g. `.mw-body`).
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.
253 * Because of the lazy-initialised nature of this property,
254 * you're discouraged from using it.
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).
267 * Add a link to a portlet menu on the page, such as:
269 * p-cactions (Content actions), p-personal (Personal tools),
270 * p-navigation (Navigation), p-tb (Toolbox)
272 * The first three parameters are required, the others are optional and
273 * may be null. Though providing an id and tooltip is recommended.
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.
280 * util.addPortletLink(
281 * 'p-tb', 'https://www.mediawiki.org/',
282 * 'mediawiki.org', 't-mworg', 'Go to mediawiki.org', 'm', '#t-print'
285 * var node = util.addPortletLink(
287 * new mw.Title( 'Special:Example' ).getUrl(),
290 * $( node ).on( 'click', function ( e ) {
291 * console.log( 'Example' );
292 * e.preventDefault();
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
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.
311 addPortletLink: function ( portlet, href, text, id, tooltip, accesskey, nextnode ) {
312 var $item, $link, $portlet, $ul;
314 // Check if there's at least 3 arguments to prevent a TypeError
315 if ( arguments.length < 3 ) {
318 // Setup the anchor tag
319 $link = $( '<a>' ).attr( 'href', href ).text( text );
321 $link.attr( 'title', tooltip );
324 // Select the specified portlet
325 $portlet = $( '#' + portlet );
326 if ( $portlet.length === 0 ) {
329 // Select the first (most likely only) unordered list inside the portlet
330 $ul = $portlet.find( 'ul' ).eq( 0 );
332 // If it didn't have an unordered list yet, create it
333 if ( $ul.length === 0 ) {
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 );
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 );
347 if ( $ul.length === 0 ) {
351 // Unhide portlet if it was hidden before
352 $portlet.removeClass( 'emptyPortlet' );
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();
359 $item = $link.wrap( '<li></li>' ).parent();
362 // Implement the properties passed to the function
364 $item.attr( 'id', id );
368 $link.attr( 'accesskey', accesskey );
372 $link.attr( 'title', tooltip );
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;
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;
391 // Case: nextnode is a jQuery-wrapped DOM element
393 nextnode.before( $item );
395 // Fallback (this is the default behavior)
399 // Update tooltip for the access key after inserting into DOM
400 // to get a localized access key label (T69946).
401 $link.updateTooltipAccessKeys();
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.
411 * FIXME: should be moved to or replaced by a validation module.
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.
417 validateEmail: function ( mailtxt ) {
418 var rfc5322Atext, rfc1034LdhStr, html5EmailRegexp;
420 if ( mailtxt === '' ) {
424 // HTML5 defines a string as valid e-mail address if it matches
426 // 1 * ( atext / "." ) "@" ldh-str 1*( "." ldh-str )
428 // - atext : defined in RFC 5322 section 3.2.3
429 // - ldh-str : defined in RFC 1034 section 3.5
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.
444 rfc5322Atext = 'a
-z0
-9!#$%&\'*+\\-/=?^_
`{|}~';
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\\-';
455 html5EmailRegexp = new RegExp(
458 // User part which is liberal :p
459 '[' + rfc5322Atext + '\\.]+' +
463 '[' + rfc1034LdhStr + ']+' +
464 // Optional second part and following are separated by a dot
465 '(?:\\.[' + rfc1034LdhStr + ']+)*' +
468 // RegExp is case insensitive
471 return ( mailtxt.match( html5EmailRegexp ) !== null );
475 * Note: borrows from IP::isIPv4
477 * @param {string} address
478 * @param {boolean} allowBlock
481 isIPv4Address: function ( address, allowBlock ) {
482 var block, RE_IP_BYTE, RE_IP_ADD;
484 if ( typeof address !== 'string' ) {
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;
492 return ( new RegExp( '^' + RE_IP_ADD + block + '$' ).test( address ) );
496 * Note: borrows from IP::isIPv6
498 * @param {string} address
499 * @param {boolean} allowBlock
502 isIPv6Address: function ( address, allowBlock ) {
503 var block, RE_IPV6_ADD;
505 if ( typeof address !== 'string' ) {
509 block = allowBlock ? '(?:\\/(?:12[0-8]|1[01][0-9]|[1-9]?\\d))?' : '';
511 '(?:' + // starts with "::" (including "::")
515 '|' + // ends with "::" (except "::")
520 '|' + // contains no "::"
527 if ( new RegExp( '^' + RE_IPV6_ADD + block + '$' ).test( address ) ) {
531 // contains one "::" in the middle (single '::' check below)
539 new RegExp( '^' + RE_IPV6_ADD + block + '$' ).test( address ) &&
540 /::/.test( address ) &&
541 !/::.*::/.test( address )
546 * Check whether a string is an IP address
549 * @param {string} address String to check
550 * @param {boolean} allowBlock True if a block of IPs should be allowed
553 isIPAddress: function ( address, allowBlock ) {
554 return util.isIPv4Address( address, allowBlock ) ||
555 util.isIPv6Address( address, allowBlock );
560 * @method wikiGetlink
561 * @inheritdoc #getUrl
562 * @deprecated since 1.23 Use #getUrl instead.
564 mw.log.deprecate( util, 'wikiGetlink', util.getUrl, 'Use mw.util.getUrl instead.' );
567 * Add the appropriate prefix to the accesskey shown in the tooltip.
569 * If the `$nodes
` parameter is given, only those nodes are updated;
570 * otherwise we update all elements with accesskeys on the page.
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.
576 mw.log.deprecate( util, 'updateTooltipAccessKeys', function ( $nodes ) {
578 $nodes = $( '[accesskey]' );
579 } else if ( !( $nodes instanceof $ ) ) {
580 $nodes = $( $nodes );
583 $nodes.updateTooltipAccessKeys();
584 }, 'Use jquery.accessKeyLabel instead.' );
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
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.
596 mw.log.deprecate( util, 'jsMessage', function ( message ) {
597 if ( !arguments.length || message === '' || message === null ) {
600 if ( typeof message !== 'object' ) {
601 message = $.parseHTML( message );
603 mw.notify( message, { autoHide: true, tag: 'legacy' } );
605 }, 'Use mw.notify instead.' );
608 * Initialisation of mw.util.$content
611 util.$content = ( function () {
612 var i, l, $node, 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.
622 // If the skin has no such class, fall back to the parser output
626 for ( i = 0, l = selectors.length; i < l; i++ ) {
627 $node = $( selectors[ i ] );
628 if ( $node.length ) {
629 return $node.first();
633 // Should never happen... well, it could if someone is not finished writing a
634 // skin and has not yet inserted bodytext yet.
640 * Former public initialisation. Now a no-op function.
643 * @deprecated since 1.30
645 mw.log.deprecate( util, 'init', $.noop, 'Remove the call of mw.util.init().', 'mw.util.init' );
650 module.exports = util;
652 }( mediaWiki, jQuery ) );