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 return rawurlencode( str.replace( / /g, '_
' ) )
37 .replace( /%3A/g, ':' )
38 .replace( /%/g, '.' );
40 throw new Error( 'Unrecognized ID escaping mode
' + mode );
54 * Encode the string like PHP's rawurlencode
56 * @param
{string
} str String to be encoded
.
57 * @return {string
} Encoded string
59 rawurlencode
: rawurlencode
,
62 * Encode string into HTML id compatible form suitable for use in HTML
63 * Analog to PHP Sanitizer::escapeIdForAttribute()
67 * @param {string} str String to encode
68 * @return {string} Encoded string
70 escapeIdForAttribute: function ( str
) {
71 var mode
= mw
.config
.get( 'wgFragmentMode' )[ 0 ];
73 return escapeIdInternal( str
, mode
);
77 * Encode string into HTML id compatible form suitable for use in links
78 * Analog to PHP Sanitizer::escapeIdForLink()
82 * @param {string} str String to encode
83 * @return {string} Encoded string
85 escapeIdForLink: function ( str
) {
86 var mode
= mw
.config
.get( 'wgFragmentMode' )[ 0 ];
88 return escapeIdInternal( str
, mode
);
92 * Encode page titles for use in a URL
94 * We want / and : to be included as literal characters in our title URLs
95 * as they otherwise fatally break the title.
97 * The others are decoded because we can, it's prettier and matches behaviour
98 * of `wfUrlencode` in PHP.
100 * @param {string} str String to be encoded.
101 * @return {string} Encoded string
103 wikiUrlencode: function ( str
) {
104 return util
.rawurlencode( str
)
105 .replace( /%20/g, '_' )
106 // wfUrlencode replacements
107 .replace( /%3B/g, ';' )
108 .replace( /%40/g, '@' )
109 .replace( /%24/g, '$' )
110 .replace( /%21/g, '!' )
111 .replace( /%2A/g, '*' )
112 .replace( /%28/g, '(' )
113 .replace( /%29/g, ')' )
114 .replace( /%2C/g, ',' )
115 .replace( /%2F/g, '/' )
116 .replace( /%7E/g, '~' )
117 .replace( /%3A/g, ':' );
121 * Get the link to a page name (relative to `wgServer`),
123 * @param {string|null} [pageName=wgPageName] Page name
124 * @param {Object} [params] A mapping of query parameter names to values,
125 * e.g. `{ action: 'edit' }`
126 * @return {string} Url of the page with name of `pageName`
128 getUrl: function ( pageName
, params
) {
129 var titleFragmentStart
, url
, query
,
131 title
= typeof pageName
=== 'string' ? pageName
: mw
.config
.get( 'wgPageName' );
134 titleFragmentStart
= title
.indexOf( '#' );
135 if ( titleFragmentStart
!== -1 ) {
136 fragment
= title
.slice( titleFragmentStart
+ 1 );
137 // Exclude the fragment from the page name
138 title
= title
.slice( 0, titleFragmentStart
);
141 // Produce query string
143 query
= $.param( params
);
147 util
.wikiScript() + '?title=' + util
.wikiUrlencode( title
) + '&' + query
:
148 util
.wikiScript() + '?' + query
;
150 url
= mw
.config
.get( 'wgArticlePath' )
151 .replace( '$1', util
.wikiUrlencode( title
).replace( /\$/g, '$$$$' ) );
154 // Append the encoded fragment
155 if ( fragment
.length
) {
156 url
+= '#' + util
.escapeIdForLink( fragment
);
163 * Get address to a script in the wiki root.
164 * For index.php use `mw.config.get( 'wgScript' )`.
167 * @param {string} str Name of script (e.g. 'api'), defaults to 'index'
168 * @return {string} Address to script (e.g. '/w/api.php' )
170 wikiScript: function ( str
) {
171 str
= str
|| 'index';
172 if ( str
=== 'index' ) {
173 return mw
.config
.get( 'wgScript' );
174 } else if ( str
=== 'load' ) {
175 return mw
.config
.get( 'wgLoadScript' );
177 return mw
.config
.get( 'wgScriptPath' ) + '/' + str
+ '.php';
182 * Append a new style block to the head and return the CSSStyleSheet object.
183 * Use .ownerNode to access the `<style>` element, or use mw.loader#addStyleTag.
184 * This function returns the styleSheet object for convience (due to cross-browsers
185 * difference as to where it is located).
187 * var sheet = util.addCSS( '.foobar { display: none; }' );
188 * $( foo ).click( function () {
189 * // Toggle the sheet on and off
190 * sheet.disabled = !sheet.disabled;
193 * @param {string} text CSS to be appended
194 * @return {CSSStyleSheet} Use .ownerNode to get to the `<style>` element.
196 addCSS: function ( text
) {
197 var s
= mw
.loader
.addStyleTag( text
);
198 return s
.sheet
|| s
.styleSheet
|| s
;
202 * Grab the URL parameter value for the given parameter.
203 * Returns null if not found.
205 * @param {string} param The parameter name.
206 * @param {string} [url=location.href] URL to search through, defaulting to the current browsing location.
207 * @return {Mixed} Parameter value or null.
209 getParamValue: function ( param
, url
) {
210 // Get last match, stop at hash
211 var re
= new RegExp( '^[^#]*[&?]' + mw
.RegExp
.escape( param
) + '=([^&#]*)' ),
212 m
= re
.exec( url
!== undefined ? url
: location
.href
);
215 // Beware that decodeURIComponent is not required to understand '+'
216 // by spec, as encodeURIComponent does not produce it.
217 return decodeURIComponent( m
[ 1 ].replace( /\+/g, '%20' ) );
223 * The content wrapper of the skin (e.g. `.mw-body`).
225 * Populated on document ready. To use this property,
226 * wait for `$.ready` and be sure to have a module dependency on
227 * `mediawiki.util` which will ensure
228 * your document ready handler fires after initialization.
230 * Because of the lazy-initialised nature of this property,
231 * you're discouraged from using it.
233 * If you need just the wikipage content (not any of the
234 * extra elements output by the skin), use `$( '#mw-content-text' )`
235 * instead. Or listen to mw.hook#wikipage_content which will
236 * allow your code to re-run when the page changes (e.g. live preview
237 * or re-render after ajax save).
244 * Add a link to a portlet menu on the page, such as:
246 * p-cactions (Content actions), p-personal (Personal tools),
247 * p-navigation (Navigation), p-tb (Toolbox)
249 * The first three parameters are required, the others are optional and
250 * may be null. Though providing an id and tooltip is recommended.
252 * By default the new link will be added to the end of the list. To
253 * add the link before a given existing item, pass the DOM node
254 * (e.g. `document.getElementById( 'foobar' )`) or a jQuery-selector
255 * (e.g. `'#foobar'`) for that item.
257 * util.addPortletLink(
258 * 'p-tb', 'https://www.mediawiki.org/',
259 * 'mediawiki.org', 't-mworg', 'Go to mediawiki.org', 'm', '#t-print'
262 * var node = util.addPortletLink(
264 * new mw.Title( 'Special:Example' ).getUrl(),
267 * $( node ).on( 'click', function ( e ) {
268 * console.log( 'Example' );
269 * e.preventDefault();
272 * @param {string} portletId ID of the target portlet (e.g. 'p-cactions' or 'p-personal')
273 * @param {string} href Link URL
274 * @param {string} text Link text
275 * @param {string} [id] ID of the list item, should be unique and preferably have
276 * the appropriate prefix ('ca-', 'pt-', 'n-' or 't-')
277 * @param {string} [tooltip] Text to show when hovering over the link, without accesskey suffix
278 * @param {string} [accesskey] Access key to activate this link. One character only,
279 * avoid conflicts with other links. Use `$( '[accesskey=x]' )` in the console to
280 * see if 'x' is already used.
281 * @param {HTMLElement|jQuery|string} [nextnode] Element that the new item should be added before.
282 * Must be another item in the same list, it will be ignored otherwise.
283 * Can be specified as DOM reference, as jQuery object, or as CSS selector string.
284 * @return {HTMLElement|null} The added list item, or null if no element was added.
286 addPortletLink: function ( portletId
, href
, text
, id
, tooltip
, accesskey
, nextnode
) {
287 var item
, link
, $portlet
, portlet
, portletDiv
, ul
, next
;
290 // Avoid confusing id="undefined" lookup
294 portlet
= document
.getElementById( portletId
);
296 // Invalid portlet ID
300 // Setup the anchor tag and set any the properties
301 link
= document
.createElement( 'a' );
303 link
.textContent
= text
;
305 link
.title
= tooltip
;
308 link
.accessKey
= accesskey
;
311 // Unhide portlet if it was hidden before
312 $portlet
= $( portlet
);
313 $portlet
.removeClass( 'emptyPortlet' );
315 // Setup the list item (and a span if $portlet is a Vector tab)
316 if ( $portlet
.hasClass( 'vectorTabs' ) ) {
317 item
= $( '<li>' ).append( $( '<span>' ).append( link
)[ 0 ] )[ 0 ];
319 item
= $( '<li>' ).append( link
)[ 0 ];
325 // Select the first (most likely only) unordered list inside the portlet
326 ul
= portlet
.querySelector( 'ul' );
328 // If it didn't have an unordered list yet, create one
329 ul
= document
.createElement( 'ul' );
330 portletDiv
= portlet
.querySelector( 'div' );
332 // Support: Legacy skins have a div (such as div.body or div.pBody).
333 // Append the <ul> to that.
334 portletDiv
.appendChild( ul
);
336 // Append it to the portlet directly
337 portlet
.appendChild( ul
);
341 if ( nextnode
&& ( typeof nextnode
=== 'string' || nextnode
.nodeType
|| nextnode
.jquery
) ) {
342 nextnode
= $( ul
).find( nextnode
);
343 if ( nextnode
.length
=== 1 && nextnode
[ 0 ].parentNode
=== ul
) {
344 // Insertion point: Before nextnode
345 nextnode
.before( item
);
348 // Else: Invalid nextnode value (no match, more than one match, or not a direct child)
349 // Else: Invalid nextnode type
353 // Insertion point: End of list (default)
354 ul
.appendChild( item
);
357 // Update tooltip for the access key after inserting into DOM
358 // to get a localized access key label (T69946).
360 $( link
).updateTooltipAccessKeys();
367 * Validate a string as representing a valid e-mail address
368 * according to HTML5 specification. Please note the specification
369 * does not validate a domain with one character.
371 * FIXME: should be moved to or replaced by a validation module.
373 * @param {string} mailtxt E-mail address to be validated.
374 * @return {boolean|null} Null if `mailtxt` was an empty string, otherwise true/false
375 * as determined by validation.
377 validateEmail: function ( mailtxt
) {
378 var rfc5322Atext
, rfc1034LdhStr
, html5EmailRegexp
;
380 if ( mailtxt
=== '' ) {
384 // HTML5 defines a string as valid e-mail address if it matches
386 // 1 * ( atext / "." ) "@" ldh-str 1*( "." ldh-str )
388 // - atext : defined in RFC 5322 section 3.2.3
389 // - ldh-str : defined in RFC 1034 section 3.5
391 // (see STD 68 / RFC 5234 https://tools.ietf.org/html/std68)
392 // First, define the RFC 5322 'atext' which is pretty easy:
393 // atext = ALPHA / DIGIT / ; Printable US-ASCII
394 // "!" / "#" / ; characters not including
395 // "$" / "%" / ; specials. Used for atoms.
404 rfc5322Atext
= 'a-z0-9!#$%&\'*+\\-/=?^_`{|}~';
406 // Next define the RFC 1034 'ldh-str'
407 // <domain> ::= <subdomain> | " "
408 // <subdomain> ::= <label> | <subdomain> "." <label>
409 // <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
410 // <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
411 // <let-dig-hyp> ::= <let-dig> | "-"
412 // <let-dig> ::= <letter> | <digit>
413 rfc1034LdhStr
= 'a-z0-9\\-';
415 html5EmailRegexp
= new RegExp(
418 // User part which is liberal :p
419 '[' + rfc5322Atext
+ '\\.]+' +
423 '[' + rfc1034LdhStr
+ ']+' +
424 // Optional second part and following are separated by a dot
425 '(?:\\.[' + rfc1034LdhStr
+ ']+)*' +
428 // RegExp is case insensitive
431 return ( mailtxt
.match( html5EmailRegexp
) !== null );
435 * Note: borrows from IP::isIPv4
437 * @param {string} address
438 * @param {boolean} [allowBlock=false]
441 isIPv4Address: function ( address
, allowBlock
) {
442 var block
, RE_IP_BYTE
, RE_IP_ADD
;
444 if ( typeof address
!== 'string' ) {
448 block
= allowBlock
? '(?:\\/(?:3[0-2]|[12]?\\d))?' : '';
449 RE_IP_BYTE
= '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])';
450 RE_IP_ADD
= '(?:' + RE_IP_BYTE
+ '\\.){3}' + RE_IP_BYTE
;
452 return ( new RegExp( '^' + RE_IP_ADD
+ block
+ '$' ).test( address
) );
456 * Note: borrows from IP::isIPv6
458 * @param {string} address
459 * @param {boolean} [allowBlock=false]
462 isIPv6Address: function ( address
, allowBlock
) {
463 var block
, RE_IPV6_ADD
;
465 if ( typeof address
!== 'string' ) {
469 block
= allowBlock
? '(?:\\/(?:12[0-8]|1[01][0-9]|[1-9]?\\d))?' : '';
471 '(?:' + // starts with "::" (including "::")
475 '|' + // ends with "::" (except "::")
480 '|' + // contains no "::"
487 if ( new RegExp( '^' + RE_IPV6_ADD
+ block
+ '$' ).test( address
) ) {
491 // contains one "::" in the middle (single '::' check below)
499 new RegExp( '^' + RE_IPV6_ADD
+ block
+ '$' ).test( address
) &&
500 /::/.test( address
) &&
501 !/::.*::/.test( address
)
506 * Check whether a string is an IP address
509 * @param {string} address String to check
510 * @param {boolean} [allowBlock=false] If a block of IPs should be allowed
513 isIPAddress: function ( address
, allowBlock
) {
514 return util
.isIPv4Address( address
, allowBlock
) ||
515 util
.isIPv6Address( address
, allowBlock
);
520 * Initialisation of mw.util.$content
523 util
.$content
= ( function () {
524 var i
, l
, $node
, selectors
;
527 // The preferred standard is class "mw-body".
528 // You may also use class "mw-body mw-body-primary" if you use
529 // mw-body in multiple locations. Or class "mw-body-primary" if
530 // you use mw-body deeper in the DOM.
534 // If the skin has no such class, fall back to the parser output
538 for ( i
= 0, l
= selectors
.length
; i
< l
; i
++ ) {
539 $node
= $( selectors
[ i
] );
540 if ( $node
.length
) {
541 return $node
.first();
545 // Should never happen... well, it could if someone is not finished writing a
546 // skin and has not yet inserted bodytext yet.
554 module
.exports
= util
;