5 config
= require( './config.json' );
8 * Encode the string like PHP's rawurlencode
11 * @param {string} str String to be encoded.
12 * @return {string} Encoded string
14 function rawurlencode( str
) {
16 return encodeURIComponent( str
)
17 .replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' )
18 .replace( /\)/g, '%29' ).replace( /\*/g, '%2A
' ).replace( /~/g, '%7E
' );
22 * Private helper function used by util.escapeId*()
25 * @param {string} str String to be encoded
26 * @param {string} mode Encoding mode, see documentation for $wgFragmentMode
27 * in DefaultSettings.php
28 * @return {string} Encoded string
30 function escapeIdInternal( str, mode ) {
35 return str.replace( / /g, '_
' );
37 return rawurlencode( str.replace( / /g, '_
' ) )
38 .replace( /%3A/g, ':' )
39 .replace( /%/g, '.' );
41 throw new Error( 'Unrecognized ID escaping mode
' + mode );
53 * Encode the string like PHP's rawurlencode
55 * @param
{string
} str String to be encoded
.
56 * @return {string
} Encoded string
58 rawurlencode
: rawurlencode
,
61 * Encode string into HTML id compatible form suitable for use in HTML
62 * Analog to PHP Sanitizer::escapeIdForAttribute()
66 * @param {string} str String to encode
67 * @return {string} Encoded string
69 escapeIdForAttribute: function ( str
) {
70 var mode
= config
.FragmentMode
[ 0 ];
72 return escapeIdInternal( str
, mode
);
76 * Encode string into HTML id compatible form suitable for use in links
77 * Analog to PHP Sanitizer::escapeIdForLink()
81 * @param {string} str String to encode
82 * @return {string} Encoded string
84 escapeIdForLink: function ( str
) {
85 var mode
= config
.FragmentMode
[ 0 ];
87 return escapeIdInternal( str
, mode
);
91 * Encode page titles for use in a URL
93 * We want / and : to be included as literal characters in our title URLs
94 * as they otherwise fatally break the title.
96 * The others are decoded because we can, it's prettier and matches behaviour
97 * of `wfUrlencode` in PHP.
99 * @param {string} str String to be encoded.
100 * @return {string} Encoded string
102 wikiUrlencode: function ( str
) {
103 return util
.rawurlencode( str
)
104 .replace( /%20/g, '_' )
105 // wfUrlencode replacements
106 .replace( /%3B/g, ';' )
107 .replace( /%40/g, '@' )
108 .replace( /%24/g, '$' )
109 .replace( /%21/g, '!' )
110 .replace( /%2A/g, '*' )
111 .replace( /%28/g, '(' )
112 .replace( /%29/g, ')' )
113 .replace( /%2C/g, ',' )
114 .replace( /%2F/g, '/' )
115 .replace( /%7E/g, '~' )
116 .replace( /%3A/g, ':' );
120 * Get the link to a page name (relative to `wgServer`),
122 * @param {string|null} [pageName=wgPageName] Page name
123 * @param {Object} [params] A mapping of query parameter names to values,
124 * e.g. `{ action: 'edit' }`
125 * @return {string} Url of the page with name of `pageName`
127 getUrl: function ( pageName
, params
) {
128 var titleFragmentStart
, url
, query
,
130 title
= typeof pageName
=== 'string' ? pageName
: mw
.config
.get( 'wgPageName' );
133 titleFragmentStart
= title
.indexOf( '#' );
134 if ( titleFragmentStart
!== -1 ) {
135 fragment
= title
.slice( titleFragmentStart
+ 1 );
136 // Exclude the fragment from the page name
137 title
= title
.slice( 0, titleFragmentStart
);
140 // Produce query string
142 query
= $.param( params
);
146 util
.wikiScript() + '?title=' + util
.wikiUrlencode( title
) + '&' + query
:
147 util
.wikiScript() + '?' + query
;
149 url
= mw
.config
.get( 'wgArticlePath' )
150 .replace( '$1', util
.wikiUrlencode( title
).replace( /\$/g, '$$$$' ) );
153 // Append the encoded fragment
154 if ( fragment
.length
) {
155 url
+= '#' + util
.escapeIdForLink( fragment
);
162 * Get address to a script in the wiki root.
163 * For index.php use `mw.config.get( 'wgScript' )`.
166 * @param {string} str Name of script (e.g. 'api'), defaults to 'index'
167 * @return {string} Address to script (e.g. '/w/api.php' )
169 wikiScript: function ( str
) {
170 str
= str
|| 'index';
171 if ( str
=== 'index' ) {
172 return mw
.config
.get( 'wgScript' );
173 } else if ( str
=== 'load' ) {
174 return config
.LoadScript
;
176 return mw
.config
.get( 'wgScriptPath' ) + '/' + str
+ '.php';
181 * Append a new style block to the head and return the CSSStyleSheet object.
182 * Use .ownerNode to access the `<style>` element, or use mw.loader#addStyleTag.
183 * This function returns the styleSheet object for convience (due to cross-browsers
184 * difference as to where it is located).
186 * var sheet = util.addCSS( '.foobar { display: none; }' );
187 * $( foo ).click( function () {
188 * // Toggle the sheet on and off
189 * sheet.disabled = !sheet.disabled;
192 * @param {string} text CSS to be appended
193 * @return {CSSStyleSheet} Use .ownerNode to get to the `<style>` element.
195 addCSS: function ( text
) {
196 var s
= mw
.loader
.addStyleTag( text
);
197 return s
.sheet
|| s
.styleSheet
|| s
;
201 * Grab the URL parameter value for the given parameter.
202 * Returns null if not found.
204 * @param {string} param The parameter name.
205 * @param {string} [url=location.href] URL to search through, defaulting to the current browsing location.
206 * @return {Mixed} Parameter value or null.
208 getParamValue: function ( param
, url
) {
209 // Get last match, stop at hash
210 var re
= new RegExp( '^[^#]*[&?]' + mw
.RegExp
.escape( param
) + '=([^&#]*)' ),
211 m
= re
.exec( url
!== undefined ? url
: location
.href
);
214 // Beware that decodeURIComponent is not required to understand '+'
215 // by spec, as encodeURIComponent does not produce it.
216 return decodeURIComponent( m
[ 1 ].replace( /\+/g, '%20' ) );
222 * The content wrapper of the skin (e.g. `.mw-body`).
224 * Populated on document ready. To use this property,
225 * wait for `$.ready` and be sure to have a module dependency on
226 * `mediawiki.util` which will ensure
227 * your document ready handler fires after initialization.
229 * Because of the lazy-initialised nature of this property,
230 * you're discouraged from using it.
232 * If you need just the wikipage content (not any of the
233 * extra elements output by the skin), use `$( '#mw-content-text' )`
234 * instead. Or listen to mw.hook#wikipage_content which will
235 * allow your code to re-run when the page changes (e.g. live preview
236 * or re-render after ajax save).
243 * Add a link to a portlet menu on the page, such as:
245 * p-cactions (Content actions), p-personal (Personal tools),
246 * p-navigation (Navigation), p-tb (Toolbox)
248 * The first three parameters are required, the others are optional and
249 * may be null. Though providing an id and tooltip is recommended.
251 * By default the new link will be added to the end of the list. To
252 * add the link before a given existing item, pass the DOM node
253 * (e.g. `document.getElementById( 'foobar' )`) or a jQuery-selector
254 * (e.g. `'#foobar'`) for that item.
256 * util.addPortletLink(
257 * 'p-tb', 'https://www.mediawiki.org/',
258 * 'mediawiki.org', 't-mworg', 'Go to mediawiki.org', 'm', '#t-print'
261 * var node = util.addPortletLink(
263 * new mw.Title( 'Special:Example' ).getUrl(),
266 * $( node ).on( 'click', function ( e ) {
267 * console.log( 'Example' );
268 * e.preventDefault();
271 * @param {string} portletId ID of the target portlet (e.g. 'p-cactions' or 'p-personal')
272 * @param {string} href Link URL
273 * @param {string} text Link text
274 * @param {string} [id] ID of the list item, should be unique and preferably have
275 * the appropriate prefix ('ca-', 'pt-', 'n-' or 't-')
276 * @param {string} [tooltip] Text to show when hovering over the link, without accesskey suffix
277 * @param {string} [accesskey] Access key to activate this link. One character only,
278 * avoid conflicts with other links. Use `$( '[accesskey=x]' )` in the console to
279 * see if 'x' is already used.
280 * @param {HTMLElement|jQuery|string} [nextnode] Element that the new item should be added before.
281 * Must be another item in the same list, it will be ignored otherwise.
282 * Can be specified as DOM reference, as jQuery object, or as CSS selector string.
283 * @return {HTMLElement|null} The added list item, or null if no element was added.
285 addPortletLink: function ( portletId
, href
, text
, id
, tooltip
, accesskey
, nextnode
) {
286 var item
, link
, $portlet
, portlet
, portletDiv
, ul
, next
;
289 // Avoid confusing id="undefined" lookup
293 portlet
= document
.getElementById( portletId
);
295 // Invalid portlet ID
299 // Setup the anchor tag and set any the properties
300 link
= document
.createElement( 'a' );
302 link
.textContent
= text
;
304 link
.title
= tooltip
;
307 link
.accessKey
= accesskey
;
310 // Unhide portlet if it was hidden before
311 $portlet
= $( portlet
);
312 $portlet
.removeClass( 'emptyPortlet' );
314 // Setup the list item (and a span if $portlet is a Vector tab)
315 // eslint-disable-next-line no-jquery/no-class-state
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
);
519 // Not allowed outside unit tests
520 if ( window
.QUnit
) {
521 util
.setOptionsForTest = function ( opts
) {
522 var oldConfig
= config
;
523 config
= $.extend( {}, config
, opts
);
529 * Initialisation of mw.util.$content
532 util
.$content
= ( function () {
533 var i
, l
, $node
, selectors
;
536 // The preferred standard is class "mw-body".
537 // You may also use class "mw-body mw-body-primary" if you use
538 // mw-body in multiple locations. Or class "mw-body-primary" if
539 // you use mw-body deeper in the DOM.
543 // If the skin has no such class, fall back to the parser output
547 for ( i
= 0, l
= selectors
.length
; i
< l
; i
++ ) {
548 $node
= $( selectors
[ i
] );
549 if ( $node
.length
) {
550 return $node
.first();
554 // Should never happen... well, it could if someone is not finished writing a
555 // skin and has not yet inserted bodytext yet.
563 module
.exports
= util
;