5 config
= require( './config.json' );
7 require( './jquery.accessKeyLabel.js' );
10 * Encode the string like PHP's rawurlencode
13 * @param {string} str String to be encoded.
14 * @return {string} Encoded string
16 function rawurlencode( str
) {
18 return encodeURIComponent( str
)
19 .replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' )
20 .replace( /\)/g, '%29' ).replace( /\*/g, '%2A
' ).replace( /~/g, '%7E
' );
24 * Private helper function used by util.escapeId*()
27 * @param {string} str String to be encoded
28 * @param {string} mode Encoding mode, see documentation for $wgFragmentMode
29 * in DefaultSettings.php
30 * @return {string} Encoded string
32 function escapeIdInternal( str, mode ) {
37 return str.replace( / /g, '_
' );
39 return rawurlencode( str.replace( / /g, '_
' ) )
40 .replace( /%3A/g, ':' )
41 .replace( /%/g, '.' );
43 throw new Error( 'Unrecognized ID escaping mode
' + mode );
55 * Encode the string like PHP's rawurlencode
57 * @param
{string
} str String to be encoded
.
58 * @return {string
} Encoded string
60 rawurlencode
: rawurlencode
,
63 * Encode string into HTML id compatible form suitable for use in HTML
64 * Analog to PHP Sanitizer::escapeIdForAttribute()
68 * @param {string} str String to encode
69 * @return {string} Encoded string
71 escapeIdForAttribute: function ( str
) {
72 var mode
= config
.FragmentMode
[ 0 ];
74 return escapeIdInternal( str
, mode
);
78 * Encode string into HTML id compatible form suitable for use in links
79 * Analog to PHP Sanitizer::escapeIdForLink()
83 * @param {string} str String to encode
84 * @return {string} Encoded string
86 escapeIdForLink: function ( str
) {
87 var mode
= config
.FragmentMode
[ 0 ];
89 return escapeIdInternal( str
, mode
);
93 * Encode page titles for use in a URL
95 * We want / and : to be included as literal characters in our title URLs
96 * as they otherwise fatally break the title.
98 * The others are decoded because we can, it's prettier and matches behaviour
99 * of `wfUrlencode` in PHP.
101 * @param {string} str String to be encoded.
102 * @return {string} Encoded string
104 wikiUrlencode: function ( str
) {
105 return util
.rawurlencode( str
)
106 .replace( /%20/g, '_' )
107 // wfUrlencode replacements
108 .replace( /%3B/g, ';' )
109 .replace( /%40/g, '@' )
110 .replace( /%24/g, '$' )
111 .replace( /%21/g, '!' )
112 .replace( /%2A/g, '*' )
113 .replace( /%28/g, '(' )
114 .replace( /%29/g, ')' )
115 .replace( /%2C/g, ',' )
116 .replace( /%2F/g, '/' )
117 .replace( /%7E/g, '~' )
118 .replace( /%3A/g, ':' );
122 * Get the link to a page name (relative to `wgServer`),
124 * @param {string|null} [pageName=wgPageName] Page name
125 * @param {Object} [params] A mapping of query parameter names to values,
126 * e.g. `{ action: 'edit' }`
127 * @return {string} Url of the page with name of `pageName`
129 getUrl: function ( pageName
, params
) {
130 var titleFragmentStart
, url
, query
,
132 title
= typeof pageName
=== 'string' ? pageName
: mw
.config
.get( 'wgPageName' );
135 titleFragmentStart
= title
.indexOf( '#' );
136 if ( titleFragmentStart
!== -1 ) {
137 fragment
= title
.slice( titleFragmentStart
+ 1 );
138 // Exclude the fragment from the page name
139 title
= title
.slice( 0, titleFragmentStart
);
142 // Produce query string
144 query
= $.param( params
);
148 util
.wikiScript() + '?title=' + util
.wikiUrlencode( title
) + '&' + query
:
149 util
.wikiScript() + '?' + query
;
151 url
= mw
.config
.get( 'wgArticlePath' )
152 .replace( '$1', util
.wikiUrlencode( title
).replace( /\$/g, '$$$$' ) );
155 // Append the encoded fragment
156 if ( fragment
.length
) {
157 url
+= '#' + util
.escapeIdForLink( fragment
);
164 * Get address to a script in the wiki root.
165 * For index.php use `mw.config.get( 'wgScript' )`.
168 * @param {string} str Name of script (e.g. 'api'), defaults to 'index'
169 * @return {string} Address to script (e.g. '/w/api.php' )
171 wikiScript: function ( str
) {
172 str
= str
|| 'index';
173 if ( str
=== 'index' ) {
174 return mw
.config
.get( 'wgScript' );
175 } else if ( str
=== 'load' ) {
176 return config
.LoadScript
;
178 return mw
.config
.get( 'wgScriptPath' ) + '/' + str
+ '.php';
183 * Append a new style block to the head and return the CSSStyleSheet object.
184 * Use .ownerNode to access the `<style>` element, or use mw.loader#addStyleTag.
185 * This function returns the styleSheet object for convience (due to cross-browsers
186 * difference as to where it is located).
188 * var sheet = util.addCSS( '.foobar { display: none; }' );
189 * $( foo ).click( function () {
190 * // Toggle the sheet on and off
191 * sheet.disabled = !sheet.disabled;
194 * @param {string} text CSS to be appended
195 * @return {CSSStyleSheet} Use .ownerNode to get to the `<style>` element.
197 addCSS: function ( text
) {
198 var s
= mw
.loader
.addStyleTag( text
);
199 return s
.sheet
|| s
.styleSheet
|| s
;
203 * Grab the URL parameter value for the given parameter.
204 * Returns null if not found.
206 * @param {string} param The parameter name.
207 * @param {string} [url=location.href] URL to search through, defaulting to the current browsing location.
208 * @return {Mixed} Parameter value or null.
210 getParamValue: function ( param
, url
) {
211 // Get last match, stop at hash
212 var re
= new RegExp( '^[^#]*[&?]' + mw
.RegExp
.escape( param
) + '=([^&#]*)' ),
213 m
= re
.exec( url
!== undefined ? url
: location
.href
);
216 // Beware that decodeURIComponent is not required to understand '+'
217 // by spec, as encodeURIComponent does not produce it.
218 return decodeURIComponent( m
[ 1 ].replace( /\+/g, '%20' ) );
224 * The content wrapper of the skin (e.g. `.mw-body`).
226 * Populated on document ready. To use this property,
227 * wait for `$.ready` and be sure to have a module dependency on
228 * `mediawiki.util` which will ensure
229 * your document ready handler fires after initialization.
231 * Because of the lazy-initialised nature of this property,
232 * you're discouraged from using it.
234 * If you need just the wikipage content (not any of the
235 * extra elements output by the skin), use `$( '#mw-content-text' )`
236 * instead. Or listen to mw.hook#wikipage_content which will
237 * allow your code to re-run when the page changes (e.g. live preview
238 * or re-render after ajax save).
245 * Add a link to a portlet menu on the page, such as:
247 * p-cactions (Content actions), p-personal (Personal tools),
248 * p-navigation (Navigation), p-tb (Toolbox)
250 * The first three parameters are required, the others are optional and
251 * may be null. Though providing an id and tooltip is recommended.
253 * By default the new link will be added to the end of the list. To
254 * add the link before a given existing item, pass the DOM node
255 * (e.g. `document.getElementById( 'foobar' )`) or a jQuery-selector
256 * (e.g. `'#foobar'`) for that item.
258 * util.addPortletLink(
259 * 'p-tb', 'https://www.mediawiki.org/',
260 * 'mediawiki.org', 't-mworg', 'Go to mediawiki.org', 'm', '#t-print'
263 * var node = util.addPortletLink(
265 * new mw.Title( 'Special:Example' ).getUrl(),
268 * $( node ).on( 'click', function ( e ) {
269 * console.log( 'Example' );
270 * e.preventDefault();
273 * @param {string} portletId ID of the target portlet (e.g. 'p-cactions' or 'p-personal')
274 * @param {string} href Link URL
275 * @param {string} text Link text
276 * @param {string} [id] ID of the list item, should be unique and preferably have
277 * the appropriate prefix ('ca-', 'pt-', 'n-' or 't-')
278 * @param {string} [tooltip] Text to show when hovering over the link, without accesskey suffix
279 * @param {string} [accesskey] Access key to activate this link. One character only,
280 * avoid conflicts with other links. Use `$( '[accesskey=x]' )` in the console to
281 * see if 'x' is already used.
282 * @param {HTMLElement|jQuery|string} [nextnode] Element that the new item should be added before.
283 * Must be another item in the same list, it will be ignored otherwise.
284 * Can be specified as DOM reference, as jQuery object, or as CSS selector string.
285 * @return {HTMLElement|null} The added list item, or null if no element was added.
287 addPortletLink: function ( portletId
, href
, text
, id
, tooltip
, accesskey
, nextnode
) {
288 var item
, link
, $portlet
, portlet
, portletDiv
, ul
, next
;
291 // Avoid confusing id="undefined" lookup
295 portlet
= document
.getElementById( portletId
);
297 // Invalid portlet ID
301 // Setup the anchor tag and set any the properties
302 link
= document
.createElement( 'a' );
304 link
.textContent
= text
;
306 link
.title
= tooltip
;
309 link
.accessKey
= accesskey
;
312 // Unhide portlet if it was hidden before
313 $portlet
= $( portlet
);
314 $portlet
.removeClass( 'emptyPortlet' );
316 // Setup the list item (and a span if $portlet is a Vector tab)
317 // eslint-disable-next-line no-jquery/no-class-state
318 if ( $portlet
.hasClass( 'vectorTabs' ) ) {
319 item
= $( '<li>' ).append( $( '<span>' ).append( link
)[ 0 ] )[ 0 ];
321 item
= $( '<li>' ).append( link
)[ 0 ];
327 // Select the first (most likely only) unordered list inside the portlet
328 ul
= portlet
.querySelector( 'ul' );
330 // If it didn't have an unordered list yet, create one
331 ul
= document
.createElement( 'ul' );
332 portletDiv
= portlet
.querySelector( 'div' );
334 // Support: Legacy skins have a div (such as div.body or div.pBody).
335 // Append the <ul> to that.
336 portletDiv
.appendChild( ul
);
338 // Append it to the portlet directly
339 portlet
.appendChild( ul
);
343 if ( nextnode
&& ( typeof nextnode
=== 'string' || nextnode
.nodeType
|| nextnode
.jquery
) ) {
344 nextnode
= $( ul
).find( nextnode
);
345 if ( nextnode
.length
=== 1 && nextnode
[ 0 ].parentNode
=== ul
) {
346 // Insertion point: Before nextnode
347 nextnode
.before( item
);
350 // Else: Invalid nextnode value (no match, more than one match, or not a direct child)
351 // Else: Invalid nextnode type
355 // Insertion point: End of list (default)
356 ul
.appendChild( item
);
359 // Update tooltip for the access key after inserting into DOM
360 // to get a localized access key label (T69946).
362 $( link
).updateTooltipAccessKeys();
369 * Validate a string as representing a valid e-mail address
370 * according to HTML5 specification. Please note the specification
371 * does not validate a domain with one character.
373 * FIXME: should be moved to or replaced by a validation module.
375 * @param {string} mailtxt E-mail address to be validated.
376 * @return {boolean|null} Null if `mailtxt` was an empty string, otherwise true/false
377 * as determined by validation.
379 validateEmail: function ( mailtxt
) {
380 var rfc5322Atext
, rfc1034LdhStr
, html5EmailRegexp
;
382 if ( mailtxt
=== '' ) {
386 // HTML5 defines a string as valid e-mail address if it matches
388 // 1 * ( atext / "." ) "@" ldh-str 1*( "." ldh-str )
390 // - atext : defined in RFC 5322 section 3.2.3
391 // - ldh-str : defined in RFC 1034 section 3.5
393 // (see STD 68 / RFC 5234 https://tools.ietf.org/html/std68)
394 // First, define the RFC 5322 'atext' which is pretty easy:
395 // atext = ALPHA / DIGIT / ; Printable US-ASCII
396 // "!" / "#" / ; characters not including
397 // "$" / "%" / ; specials. Used for atoms.
406 rfc5322Atext
= 'a-z0-9!#$%&\'*+\\-/=?^_`{|}~';
408 // Next define the RFC 1034 'ldh-str'
409 // <domain> ::= <subdomain> | " "
410 // <subdomain> ::= <label> | <subdomain> "." <label>
411 // <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
412 // <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
413 // <let-dig-hyp> ::= <let-dig> | "-"
414 // <let-dig> ::= <letter> | <digit>
415 rfc1034LdhStr
= 'a-z0-9\\-';
417 html5EmailRegexp
= new RegExp(
420 // User part which is liberal :p
421 '[' + rfc5322Atext
+ '\\.]+' +
425 '[' + rfc1034LdhStr
+ ']+' +
426 // Optional second part and following are separated by a dot
427 '(?:\\.[' + rfc1034LdhStr
+ ']+)*' +
430 // RegExp is case insensitive
433 return ( mailtxt
.match( html5EmailRegexp
) !== null );
437 * Note: borrows from IP::isIPv4
439 * @param {string} address
440 * @param {boolean} [allowBlock=false]
443 isIPv4Address: function ( address
, allowBlock
) {
444 var block
, RE_IP_BYTE
, RE_IP_ADD
;
446 if ( typeof address
!== 'string' ) {
450 block
= allowBlock
? '(?:\\/(?:3[0-2]|[12]?\\d))?' : '';
451 RE_IP_BYTE
= '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])';
452 RE_IP_ADD
= '(?:' + RE_IP_BYTE
+ '\\.){3}' + RE_IP_BYTE
;
454 return ( new RegExp( '^' + RE_IP_ADD
+ block
+ '$' ).test( address
) );
458 * Note: borrows from IP::isIPv6
460 * @param {string} address
461 * @param {boolean} [allowBlock=false]
464 isIPv6Address: function ( address
, allowBlock
) {
465 var block
, RE_IPV6_ADD
;
467 if ( typeof address
!== 'string' ) {
471 block
= allowBlock
? '(?:\\/(?:12[0-8]|1[01][0-9]|[1-9]?\\d))?' : '';
473 '(?:' + // starts with "::" (including "::")
477 '|' + // ends with "::" (except "::")
482 '|' + // contains no "::"
489 if ( new RegExp( '^' + RE_IPV6_ADD
+ block
+ '$' ).test( address
) ) {
493 // contains one "::" in the middle (single '::' check below)
501 new RegExp( '^' + RE_IPV6_ADD
+ block
+ '$' ).test( address
) &&
502 /::/.test( address
) &&
503 !/::.*::/.test( address
)
508 * Check whether a string is an IP address
511 * @param {string} address String to check
512 * @param {boolean} [allowBlock=false] If a block of IPs should be allowed
515 isIPAddress: function ( address
, allowBlock
) {
516 return util
.isIPv4Address( address
, allowBlock
) ||
517 util
.isIPv6Address( address
, allowBlock
);
521 // Not allowed outside unit tests
522 if ( window
.QUnit
) {
523 util
.setOptionsForTest = function ( opts
) {
524 var oldConfig
= config
;
525 config
= $.extend( {}, config
, opts
);
531 * Initialisation of mw.util.$content
534 util
.$content
= ( function () {
535 var i
, l
, $node
, selectors
;
538 // The preferred standard is class "mw-body".
539 // You may also use class "mw-body mw-body-primary" if you use
540 // mw-body in multiple locations. Or class "mw-body-primary" if
541 // you use mw-body deeper in the DOM.
545 // If the skin has no such class, fall back to the parser output
549 for ( i
= 0, l
= selectors
.length
; i
< l
; i
++ ) {
550 $node
= $( selectors
[ i
] );
551 if ( $node
.length
) {
552 return $node
.first();
556 // Should never happen... well, it could if someone is not finished writing a
557 // skin and has not yet inserted bodytext yet.
565 module
.exports
= util
;