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} portlet ID of the target portlet ( 'p-cactions' or 'p-personal' etc.)
273 * @param {string} href Link URL
274 * @param {string} text Link text
275 * @param {string} [id] ID of the new 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, try
279 * to avoid conflicts. Use `$( '[accesskey=x]' ).get()` in the console to
280 * see if 'x' is already used.
281 * @param {HTMLElement|jQuery|string} [nextnode] Element or jQuery-selector string to the item that
282 * the new item should be added before, should be another item in the same
283 * list, it will be ignored otherwise
285 * @return {HTMLElement|null} The added element (a ListItem or Anchor element,
286 * depending on the skin) or null if no element was added to the document.
288 addPortletLink: function ( portlet
, href
, text
, id
, tooltip
, accesskey
, nextnode
) {
289 var $item
, $link
, $portlet
, $ul
;
291 // Check if there's at least 3 arguments to prevent a TypeError
292 if ( arguments
.length
< 3 ) {
295 // Setup the anchor tag
296 $link
= $( '<a>' ).attr( 'href', href
).text( text
);
298 $link
.attr( 'title', tooltip
);
301 // Select the specified portlet
302 $portlet
= $( '#' + portlet
);
303 if ( $portlet
.length
=== 0 ) {
306 // Select the first (most likely only) unordered list inside the portlet
307 $ul
= $portlet
.find( 'ul' ).eq( 0 );
309 // If it didn't have an unordered list yet, create it
310 if ( $ul
.length
=== 0 ) {
314 // If there's no <div> inside, append it to the portlet directly
315 if ( $portlet
.find( 'div:first' ).length
=== 0 ) {
316 $portlet
.append( $ul
);
318 // otherwise if there's a div (such as div.body or div.pBody)
319 // append the <ul> to last (most likely only) div
320 $portlet
.find( 'div' ).eq( -1 ).append( $ul
);
324 if ( $ul
.length
=== 0 ) {
328 // Unhide portlet if it was hidden before
329 $portlet
.removeClass( 'emptyPortlet' );
331 // Wrap the anchor tag in a list item (and a span if $portlet is a Vector tab)
332 // and back up the selector to the list item
333 if ( $portlet
.hasClass( 'vectorTabs' ) ) {
334 $item
= $link
.wrap( '<li><span></span></li>' ).parent().parent();
336 $item
= $link
.wrap( '<li></li>' ).parent();
339 // Implement the properties passed to the function
341 $item
.attr( 'id', id
);
345 $link
.attr( 'accesskey', accesskey
);
349 $link
.attr( 'title', tooltip
);
353 // Case: nextnode is a DOM element (was the only option before MW 1.17, in wikibits.js)
354 // Case: nextnode is a CSS selector for jQuery
355 if ( nextnode
.nodeType
|| typeof nextnode
=== 'string' ) {
356 nextnode
= $ul
.find( nextnode
);
357 } else if ( !nextnode
.jquery
) {
358 // Error: Invalid nextnode
359 nextnode
= undefined;
361 if ( nextnode
&& ( nextnode
.length
!== 1 || nextnode
[ 0 ].parentNode
!== $ul
[ 0 ] ) ) {
362 // Error: nextnode must resolve to a single node
363 // Error: nextnode must have the associated <ul> as its parent
364 nextnode
= undefined;
368 // Case: nextnode is a jQuery-wrapped DOM element
370 nextnode
.before( $item
);
372 // Fallback (this is the default behavior)
376 // Update tooltip for the access key after inserting into DOM
377 // to get a localized access key label (T69946).
378 $link
.updateTooltipAccessKeys();
384 * Validate a string as representing a valid e-mail address
385 * according to HTML5 specification. Please note the specification
386 * does not validate a domain with one character.
388 * FIXME: should be moved to or replaced by a validation module.
390 * @param {string} mailtxt E-mail address to be validated.
391 * @return {boolean|null} Null if `mailtxt` was an empty string, otherwise true/false
392 * as determined by validation.
394 validateEmail: function ( mailtxt
) {
395 var rfc5322Atext
, rfc1034LdhStr
, html5EmailRegexp
;
397 if ( mailtxt
=== '' ) {
401 // HTML5 defines a string as valid e-mail address if it matches
403 // 1 * ( atext / "." ) "@" ldh-str 1*( "." ldh-str )
405 // - atext : defined in RFC 5322 section 3.2.3
406 // - ldh-str : defined in RFC 1034 section 3.5
408 // (see STD 68 / RFC 5234 https://tools.ietf.org/html/std68)
409 // First, define the RFC 5322 'atext' which is pretty easy:
410 // atext = ALPHA / DIGIT / ; Printable US-ASCII
411 // "!" / "#" / ; characters not including
412 // "$" / "%" / ; specials. Used for atoms.
421 rfc5322Atext
= 'a-z0-9!#$%&\'*+\\-/=?^_`{|}~';
423 // Next define the RFC 1034 'ldh-str'
424 // <domain> ::= <subdomain> | " "
425 // <subdomain> ::= <label> | <subdomain> "." <label>
426 // <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
427 // <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
428 // <let-dig-hyp> ::= <let-dig> | "-"
429 // <let-dig> ::= <letter> | <digit>
430 rfc1034LdhStr
= 'a-z0-9\\-';
432 html5EmailRegexp
= new RegExp(
435 // User part which is liberal :p
436 '[' + rfc5322Atext
+ '\\.]+' +
440 '[' + rfc1034LdhStr
+ ']+' +
441 // Optional second part and following are separated by a dot
442 '(?:\\.[' + rfc1034LdhStr
+ ']+)*' +
445 // RegExp is case insensitive
448 return ( mailtxt
.match( html5EmailRegexp
) !== null );
452 * Note: borrows from IP::isIPv4
454 * @param {string} address
455 * @param {boolean} [allowBlock=false]
458 isIPv4Address: function ( address
, allowBlock
) {
459 var block
, RE_IP_BYTE
, RE_IP_ADD
;
461 if ( typeof address
!== 'string' ) {
465 block
= allowBlock
? '(?:\\/(?:3[0-2]|[12]?\\d))?' : '';
466 RE_IP_BYTE
= '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])';
467 RE_IP_ADD
= '(?:' + RE_IP_BYTE
+ '\\.){3}' + RE_IP_BYTE
;
469 return ( new RegExp( '^' + RE_IP_ADD
+ block
+ '$' ).test( address
) );
473 * Note: borrows from IP::isIPv6
475 * @param {string} address
476 * @param {boolean} [allowBlock=false]
479 isIPv6Address: function ( address
, allowBlock
) {
480 var block
, RE_IPV6_ADD
;
482 if ( typeof address
!== 'string' ) {
486 block
= allowBlock
? '(?:\\/(?:12[0-8]|1[01][0-9]|[1-9]?\\d))?' : '';
488 '(?:' + // starts with "::" (including "::")
492 '|' + // ends with "::" (except "::")
497 '|' + // contains no "::"
504 if ( new RegExp( '^' + RE_IPV6_ADD
+ block
+ '$' ).test( address
) ) {
508 // contains one "::" in the middle (single '::' check below)
516 new RegExp( '^' + RE_IPV6_ADD
+ block
+ '$' ).test( address
) &&
517 /::/.test( address
) &&
518 !/::.*::/.test( address
)
523 * Check whether a string is an IP address
526 * @param {string} address String to check
527 * @param {boolean} [allowBlock=false] If a block of IPs should be allowed
530 isIPAddress: function ( address
, allowBlock
) {
531 return util
.isIPv4Address( address
, allowBlock
) ||
532 util
.isIPv6Address( address
, allowBlock
);
537 * Add a little box at the top of the screen to inform the user of
538 * something, replacing any previous message.
539 * Calling with no arguments, with an empty string or null will hide the message
542 * @deprecated since 1.20 Use mw#notify
543 * @param {Mixed} message The DOM-element, jQuery object or HTML-string to be put inside the message box.
544 * to allow CSS/JS to hide different boxes. null = no class used.
546 mw
.log
.deprecate( util
, 'jsMessage', function ( message
) {
547 if ( !arguments
.length
|| message
=== '' || message
=== null ) {
550 if ( typeof message
!== 'object' ) {
551 message
= $.parseHTML( message
);
553 mw
.notify( message
, { autoHide
: true, tag
: 'legacy' } );
555 }, 'Use mw.notify instead.', 'mw.util.jsMessage' );
558 * Initialisation of mw.util.$content
561 util
.$content
= ( function () {
562 var i
, l
, $node
, selectors
;
565 // The preferred standard is class "mw-body".
566 // You may also use class "mw-body mw-body-primary" if you use
567 // mw-body in multiple locations. Or class "mw-body-primary" if
568 // you use mw-body deeper in the DOM.
572 // If the skin has no such class, fall back to the parser output
576 for ( i
= 0, l
= selectors
.length
; i
< l
; i
++ ) {
577 $node
= $( selectors
[ i
] );
578 if ( $node
.length
) {
579 return $node
.first();
583 // Should never happen... well, it could if someone is not finished writing a
584 // skin and has not yet inserted bodytext yet.
592 module
.exports
= util
;
594 }( mediaWiki
, jQuery
) );