14 * Encode the string like PHP's rawurlencode
16 * @param {string} str String to be encoded.
17 * @return {string} Encoded string
19 rawurlencode: function ( str
) {
21 return encodeURIComponent( str
)
22 .replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' )
23 .replace( /\)/g, '%29' ).replace( /\*/g, '%2A
' ).replace( /~/g, '%7E
' );
27 * Encode the string like Sanitizer::escapeId in PHP
29 * @param {string} str String to be encoded.
30 * @return {string} Encoded string
32 escapeId: function ( str ) {
34 return util.rawurlencode( str.replace( / /g, '_
' ) )
35 .replace( /%3A/g, ':' )
36 .replace( /%/g, '.' );
40 * Encode page titles for use in a URL
42 * We want / and : to be included as literal characters in our title URLs
43 * as they otherwise fatally break the title.
45 * The others are decoded because we can, it's prettier and matches behaviour
46 * of `wfUrlencode` in PHP
.
48 * @param
{string
} str String to be encoded
.
49 * @return {string
} Encoded string
51 wikiUrlencode: function ( str
) {
52 return util
.rawurlencode( str
)
53 .replace( /%20/g, '_' )
54 // wfUrlencode replacements
55 .replace( /%3B/g, ';' )
56 .replace( /%40/g, '@' )
57 .replace( /%24/g, '$' )
58 .replace( /%21/g, '!' )
59 .replace( /%2A/g, '*' )
60 .replace( /%28/g, '(' )
61 .replace( /%29/g, ')' )
62 .replace( /%2C/g, ',' )
63 .replace( /%2F/g, '/' )
64 .replace( /%7E/g, '~' )
65 .replace( /%3A/g, ':' );
69 * Get the link to a page name (relative to `wgServer`),
71 * @param {string|null} [pageName=wgPageName] Page name
72 * @param {Object} [params] A mapping of query parameter names to values,
73 * e.g. `{ action: 'edit' }`
74 * @return {string} Url of the page with name of `pageName`
76 getUrl: function ( pageName
, params
) {
77 var titleFragmentStart
, url
, query
,
79 title
= typeof pageName
=== 'string' ? pageName
: mw
.config
.get( 'wgPageName' );
82 titleFragmentStart
= title
.indexOf( '#' );
83 if ( titleFragmentStart
!== -1 ) {
84 fragment
= title
.slice( titleFragmentStart
+ 1 );
85 // Exclude the fragment from the page name
86 title
= title
.slice( 0, titleFragmentStart
);
89 // Produce query string
91 query
= $.param( params
);
95 util
.wikiScript() + '?title=' + util
.wikiUrlencode( title
) + '&' + query
:
96 util
.wikiScript() + '?' + query
;
98 url
= mw
.config
.get( 'wgArticlePath' )
99 .replace( '$1', util
.wikiUrlencode( title
).replace( /\$/g, '$$$$' ) );
102 // Append the encoded fragment
103 if ( fragment
.length
) {
104 url
+= '#' + util
.escapeId( fragment
);
111 * Get address to a script in the wiki root.
112 * For index.php use `mw.config.get( 'wgScript' )`.
115 * @param {string} str Name of script (e.g. 'api'), defaults to 'index'
116 * @return {string} Address to script (e.g. '/w/api.php' )
118 wikiScript: function ( str
) {
119 str
= str
|| 'index';
120 if ( str
=== 'index' ) {
121 return mw
.config
.get( 'wgScript' );
122 } else if ( str
=== 'load' ) {
123 return mw
.config
.get( 'wgLoadScript' );
125 return mw
.config
.get( 'wgScriptPath' ) + '/' + str
+ '.php';
130 * Append a new style block to the head and return the CSSStyleSheet object.
131 * Use .ownerNode to access the `<style>` element, or use mw.loader#addStyleTag.
132 * This function returns the styleSheet object for convience (due to cross-browsers
133 * difference as to where it is located).
135 * var sheet = util.addCSS( '.foobar { display: none; }' );
136 * $( foo ).click( function () {
137 * // Toggle the sheet on and off
138 * sheet.disabled = !sheet.disabled;
141 * @param {string} text CSS to be appended
142 * @return {CSSStyleSheet} Use .ownerNode to get to the `<style>` element.
144 addCSS: function ( text
) {
145 var s
= mw
.loader
.addStyleTag( text
);
146 return s
.sheet
|| s
.styleSheet
|| s
;
150 * Grab the URL parameter value for the given parameter.
151 * Returns null if not found.
153 * @param {string} param The parameter name.
154 * @param {string} [url=location.href] URL to search through, defaulting to the current browsing location.
155 * @return {Mixed} Parameter value or null.
157 getParamValue: function ( param
, url
) {
158 // Get last match, stop at hash
159 var re
= new RegExp( '^[^#]*[&?]' + mw
.RegExp
.escape( param
) + '=([^&#]*)' ),
160 m
= re
.exec( url
!== undefined ? url
: location
.href
);
163 // Beware that decodeURIComponent is not required to understand '+'
164 // by spec, as encodeURIComponent does not produce it.
165 return decodeURIComponent( m
[ 1 ].replace( /\+/g, '%20' ) );
171 * The content wrapper of the skin (e.g. `.mw-body`).
173 * Populated on document ready. To use this property,
174 * wait for `$.ready` and be sure to have a module dependency on
175 * `mediawiki.util` which will ensure
176 * your document ready handler fires after initialization.
178 * Because of the lazy-initialised nature of this property,
179 * you're discouraged from using it.
181 * If you need just the wikipage content (not any of the
182 * extra elements output by the skin), use `$( '#mw-content-text' )`
183 * instead. Or listen to mw.hook#wikipage_content which will
184 * allow your code to re-run when the page changes (e.g. live preview
185 * or re-render after ajax save).
192 * Add a link to a portlet menu on the page, such as:
194 * p-cactions (Content actions), p-personal (Personal tools),
195 * p-navigation (Navigation), p-tb (Toolbox)
197 * The first three parameters are required, the others are optional and
198 * may be null. Though providing an id and tooltip is recommended.
200 * By default the new link will be added to the end of the list. To
201 * add the link before a given existing item, pass the DOM node
202 * (e.g. `document.getElementById( 'foobar' )`) or a jQuery-selector
203 * (e.g. `'#foobar'`) for that item.
205 * util.addPortletLink(
206 * 'p-tb', 'https://www.mediawiki.org/',
207 * 'mediawiki.org', 't-mworg', 'Go to mediawiki.org', 'm', '#t-print'
210 * var node = util.addPortletLink(
212 * new mw.Title( 'Special:Example' ).getUrl(),
215 * $( node ).on( 'click', function ( e ) {
216 * console.log( 'Example' );
217 * e.preventDefault();
220 * @param {string} portlet ID of the target portlet ( 'p-cactions' or 'p-personal' etc.)
221 * @param {string} href Link URL
222 * @param {string} text Link text
223 * @param {string} [id] ID of the new item, should be unique and preferably have
224 * the appropriate prefix ( 'ca-', 'pt-', 'n-' or 't-' )
225 * @param {string} [tooltip] Text to show when hovering over the link, without accesskey suffix
226 * @param {string} [accesskey] Access key to activate this link (one character, try
227 * to avoid conflicts. Use `$( '[accesskey=x]' ).get()` in the console to
228 * see if 'x' is already used.
229 * @param {HTMLElement|jQuery|string} [nextnode] Element or jQuery-selector string to the item that
230 * the new item should be added before, should be another item in the same
231 * list, it will be ignored otherwise
233 * @return {HTMLElement|null} The added element (a ListItem or Anchor element,
234 * depending on the skin) or null if no element was added to the document.
236 addPortletLink: function ( portlet
, href
, text
, id
, tooltip
, accesskey
, nextnode
) {
237 var $item
, $link
, $portlet
, $ul
;
239 // Check if there's at least 3 arguments to prevent a TypeError
240 if ( arguments
.length
< 3 ) {
243 // Setup the anchor tag
244 $link
= $( '<a>' ).attr( 'href', href
).text( text
);
246 $link
.attr( 'title', tooltip
);
249 // Select the specified portlet
250 $portlet
= $( '#' + portlet
);
251 if ( $portlet
.length
=== 0 ) {
254 // Select the first (most likely only) unordered list inside the portlet
255 $ul
= $portlet
.find( 'ul' ).eq( 0 );
257 // If it didn't have an unordered list yet, create it
258 if ( $ul
.length
=== 0 ) {
262 // If there's no <div> inside, append it to the portlet directly
263 if ( $portlet
.find( 'div:first' ).length
=== 0 ) {
264 $portlet
.append( $ul
);
266 // otherwise if there's a div (such as div.body or div.pBody)
267 // append the <ul> to last (most likely only) div
268 $portlet
.find( 'div' ).eq( -1 ).append( $ul
);
272 if ( $ul
.length
=== 0 ) {
276 // Unhide portlet if it was hidden before
277 $portlet
.removeClass( 'emptyPortlet' );
279 // Wrap the anchor tag in a list item (and a span if $portlet is a Vector tab)
280 // and back up the selector to the list item
281 if ( $portlet
.hasClass( 'vectorTabs' ) ) {
282 $item
= $link
.wrap( '<li><span></span></li>' ).parent().parent();
284 $item
= $link
.wrap( '<li></li>' ).parent();
287 // Implement the properties passed to the function
289 $item
.attr( 'id', id
);
293 $link
.attr( 'accesskey', accesskey
);
297 $link
.attr( 'title', tooltip
);
301 // Case: nextnode is a DOM element (was the only option before MW 1.17, in wikibits.js)
302 // Case: nextnode is a CSS selector for jQuery
303 if ( nextnode
.nodeType
|| typeof nextnode
=== 'string' ) {
304 nextnode
= $ul
.find( nextnode
);
305 } else if ( !nextnode
.jquery
) {
306 // Error: Invalid nextnode
307 nextnode
= undefined;
309 if ( nextnode
&& ( nextnode
.length
!== 1 || nextnode
[ 0 ].parentNode
!== $ul
[ 0 ] ) ) {
310 // Error: nextnode must resolve to a single node
311 // Error: nextnode must have the associated <ul> as its parent
312 nextnode
= undefined;
316 // Case: nextnode is a jQuery-wrapped DOM element
318 nextnode
.before( $item
);
320 // Fallback (this is the default behavior)
324 // Update tooltip for the access key after inserting into DOM
325 // to get a localized access key label (T69946).
326 $link
.updateTooltipAccessKeys();
332 * Validate a string as representing a valid e-mail address
333 * according to HTML5 specification. Please note the specification
334 * does not validate a domain with one character.
336 * FIXME: should be moved to or replaced by a validation module.
338 * @param {string} mailtxt E-mail address to be validated.
339 * @return {boolean|null} Null if `mailtxt` was an empty string, otherwise true/false
340 * as determined by validation.
342 validateEmail: function ( mailtxt
) {
343 var rfc5322Atext
, rfc1034LdhStr
, html5EmailRegexp
;
345 if ( mailtxt
=== '' ) {
349 // HTML5 defines a string as valid e-mail address if it matches
351 // 1 * ( atext / "." ) "@" ldh-str 1*( "." ldh-str )
353 // - atext : defined in RFC 5322 section 3.2.3
354 // - ldh-str : defined in RFC 1034 section 3.5
356 // (see STD 68 / RFC 5234 https://tools.ietf.org/html/std68)
357 // First, define the RFC 5322 'atext' which is pretty easy:
358 // atext = ALPHA / DIGIT / ; Printable US-ASCII
359 // "!" / "#" / ; characters not including
360 // "$" / "%" / ; specials. Used for atoms.
369 rfc5322Atext
= 'a-z0-9!#$%&\'*+\\-/=?^_`{|}~';
371 // Next define the RFC 1034 'ldh-str'
372 // <domain> ::= <subdomain> | " "
373 // <subdomain> ::= <label> | <subdomain> "." <label>
374 // <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
375 // <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
376 // <let-dig-hyp> ::= <let-dig> | "-"
377 // <let-dig> ::= <letter> | <digit>
378 rfc1034LdhStr
= 'a-z0-9\\-';
380 html5EmailRegexp
= new RegExp(
383 // User part which is liberal :p
384 '[' + rfc5322Atext
+ '\\.]+' +
388 '[' + rfc1034LdhStr
+ ']+' +
389 // Optional second part and following are separated by a dot
390 '(?:\\.[' + rfc1034LdhStr
+ ']+)*' +
393 // RegExp is case insensitive
396 return ( mailtxt
.match( html5EmailRegexp
) !== null );
400 * Note: borrows from IP::isIPv4
402 * @param {string} address
403 * @param {boolean} allowBlock
406 isIPv4Address: function ( address
, allowBlock
) {
407 var block
, RE_IP_BYTE
, RE_IP_ADD
;
409 if ( typeof address
!== 'string' ) {
413 block
= allowBlock
? '(?:\\/(?:3[0-2]|[12]?\\d))?' : '';
414 RE_IP_BYTE
= '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])';
415 RE_IP_ADD
= '(?:' + RE_IP_BYTE
+ '\\.){3}' + RE_IP_BYTE
;
417 return ( new RegExp( '^' + RE_IP_ADD
+ block
+ '$' ).test( address
) );
421 * Note: borrows from IP::isIPv6
423 * @param {string} address
424 * @param {boolean} allowBlock
427 isIPv6Address: function ( address
, allowBlock
) {
428 var block
, RE_IPV6_ADD
;
430 if ( typeof address
!== 'string' ) {
434 block
= allowBlock
? '(?:\\/(?:12[0-8]|1[01][0-9]|[1-9]?\\d))?' : '';
436 '(?:' + // starts with "::" (including "::")
440 '|' + // ends with "::" (except "::")
445 '|' + // contains no "::"
452 if ( new RegExp( '^' + RE_IPV6_ADD
+ block
+ '$' ).test( address
) ) {
456 // contains one "::" in the middle (single '::' check below)
464 new RegExp( '^' + RE_IPV6_ADD
+ block
+ '$' ).test( address
) &&
465 /::/.test( address
) &&
466 !/::.*::/.test( address
)
471 * Check whether a string is an IP address
474 * @param {string} address String to check
475 * @param {boolean} allowBlock True if a block of IPs should be allowed
478 isIPAddress: function ( address
, allowBlock
) {
479 return util
.isIPv4Address( address
, allowBlock
) ||
480 util
.isIPv6Address( address
, allowBlock
);
485 * @method wikiGetlink
486 * @inheritdoc #getUrl
487 * @deprecated since 1.23 Use #getUrl instead.
489 mw
.log
.deprecate( util
, 'wikiGetlink', util
.getUrl
, 'Use mw.util.getUrl instead.' );
492 * Add the appropriate prefix to the accesskey shown in the tooltip.
494 * If the `$nodes` parameter is given, only those nodes are updated;
495 * otherwise we update all elements with accesskeys on the page.
497 * @method updateTooltipAccessKeys
498 * @param {Array|jQuery} [$nodes] A jQuery object, or array of nodes to update.
499 * @deprecated since 1.24 Use the module jquery.accessKeyLabel instead.
501 mw
.log
.deprecate( util
, 'updateTooltipAccessKeys', function ( $nodes
) {
503 $nodes
= $( '[accesskey]' );
504 } else if ( !( $nodes
instanceof $ ) ) {
505 $nodes
= $( $nodes
);
508 $nodes
.updateTooltipAccessKeys();
509 }, 'Use jquery.accessKeyLabel instead.' );
512 * Add a little box at the top of the screen to inform the user of
513 * something, replacing any previous message.
514 * Calling with no arguments, with an empty string or null will hide the message
517 * @deprecated since 1.20 Use mw#notify
518 * @param {Mixed} message The DOM-element, jQuery object or HTML-string to be put inside the message box.
519 * to allow CSS/JS to hide different boxes. null = no class used.
521 mw
.log
.deprecate( util
, 'jsMessage', function ( message
) {
522 if ( !arguments
.length
|| message
=== '' || message
=== null ) {
525 if ( typeof message
!== 'object' ) {
526 message
= $.parseHTML( message
);
528 mw
.notify( message
, { autoHide
: true, tag
: 'legacy' } );
530 }, 'Use mw.notify instead.' );
533 * Initialisation of mw.util.$content
536 util
.$content
= ( function () {
537 var i
, l
, $node
, selectors
;
540 // The preferred standard is class "mw-body".
541 // You may also use class "mw-body mw-body-primary" if you use
542 // mw-body in multiple locations. Or class "mw-body-primary" if
543 // you use mw-body deeper in the DOM.
547 // If the skin has no such class, fall back to the parser output
551 for ( i
= 0, l
= selectors
.length
; i
< l
; i
++ ) {
552 $node
= $( selectors
[ i
] );
553 if ( $node
.length
) {
554 return $node
.first();
558 // Should never happen... well, it could if someone is not finished writing a
559 // skin and has not yet inserted bodytext yet.
565 * Former public initialisation. Now a no-op function.
568 * @deprecated since 1.30
570 mw
.log
.deprecate( util
, 'init', $.noop
, 'Remove the call of mw.util.init().', 'mw.util.init' );
575 module
.exports
= util
;
577 }( mediaWiki
, jQuery
) );