5 config
= require( './config.json' ),
9 * Encode the string like PHP's rawurlencode
12 * @param {string} str String to be encoded.
13 * @return {string} Encoded string
15 function rawurlencode( str
) {
17 return encodeURIComponent( str
)
18 .replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' )
19 .replace( /\)/g, '%29' ).replace( /\*/g, '%2A
' ).replace( /~/g, '%7E
' );
23 * Private helper function used by util.escapeId*()
26 * @param {string} str String to be encoded
27 * @param {string} mode Encoding mode, see documentation for $wgFragmentMode
28 * in DefaultSettings.php
29 * @return {string} Encoded string
31 function escapeIdInternal( str, mode ) {
36 return str.replace( / /g, '_
' );
38 return rawurlencode( str.replace( / /g, '_
' ) )
39 .replace( /%3A/g, ':' )
40 .replace( /%/g, '.' );
42 throw new Error( 'Unrecognized ID escaping mode
' + mode );
55 setOptionsForTest: function ( opts ) {
56 if ( !window.QUnit ) {
57 throw new Error( 'Modifying options not allowed outside unit tests
' );
59 config = $.extend( {}, config, opts );
62 resetOptionsForTest: function () {
63 if ( !window.QUnit ) {
64 throw new Error( 'Resetting options not allowed outside unit tests
' );
70 * Encode the string like PHP's rawurlencode
72 * @param
{string
} str String to be encoded
.
73 * @return {string
} Encoded string
75 rawurlencode
: rawurlencode
,
78 * Encode string into HTML id compatible form suitable for use in HTML
79 * Analog to PHP Sanitizer::escapeIdForAttribute()
83 * @param {string} str String to encode
84 * @return {string} Encoded string
86 escapeIdForAttribute: function ( str
) {
87 var mode
= config
.FragmentMode
[ 0 ];
89 return escapeIdInternal( str
, mode
);
93 * Encode string into HTML id compatible form suitable for use in links
94 * Analog to PHP Sanitizer::escapeIdForLink()
98 * @param {string} str String to encode
99 * @return {string} Encoded string
101 escapeIdForLink: function ( str
) {
102 var mode
= config
.FragmentMode
[ 0 ];
104 return escapeIdInternal( str
, mode
);
108 * Encode page titles for use in a URL
110 * We want / and : to be included as literal characters in our title URLs
111 * as they otherwise fatally break the title.
113 * The others are decoded because we can, it's prettier and matches behaviour
114 * of `wfUrlencode` in PHP.
116 * @param {string} str String to be encoded.
117 * @return {string} Encoded string
119 wikiUrlencode: function ( str
) {
120 return util
.rawurlencode( str
)
121 .replace( /%20/g, '_' )
122 // wfUrlencode replacements
123 .replace( /%3B/g, ';' )
124 .replace( /%40/g, '@' )
125 .replace( /%24/g, '$' )
126 .replace( /%21/g, '!' )
127 .replace( /%2A/g, '*' )
128 .replace( /%28/g, '(' )
129 .replace( /%29/g, ')' )
130 .replace( /%2C/g, ',' )
131 .replace( /%2F/g, '/' )
132 .replace( /%7E/g, '~' )
133 .replace( /%3A/g, ':' );
137 * Get the link to a page name (relative to `wgServer`),
139 * @param {string|null} [pageName=wgPageName] Page name
140 * @param {Object} [params] A mapping of query parameter names to values,
141 * e.g. `{ action: 'edit' }`
142 * @return {string} Url of the page with name of `pageName`
144 getUrl: function ( pageName
, params
) {
145 var titleFragmentStart
, url
, query
,
147 title
= typeof pageName
=== 'string' ? pageName
: mw
.config
.get( 'wgPageName' );
150 titleFragmentStart
= title
.indexOf( '#' );
151 if ( titleFragmentStart
!== -1 ) {
152 fragment
= title
.slice( titleFragmentStart
+ 1 );
153 // Exclude the fragment from the page name
154 title
= title
.slice( 0, titleFragmentStart
);
157 // Produce query string
159 query
= $.param( params
);
163 util
.wikiScript() + '?title=' + util
.wikiUrlencode( title
) + '&' + query
:
164 util
.wikiScript() + '?' + query
;
166 url
= mw
.config
.get( 'wgArticlePath' )
167 .replace( '$1', util
.wikiUrlencode( title
).replace( /\$/g, '$$$$' ) );
170 // Append the encoded fragment
171 if ( fragment
.length
) {
172 url
+= '#' + util
.escapeIdForLink( fragment
);
179 * Get address to a script in the wiki root.
180 * For index.php use `mw.config.get( 'wgScript' )`.
183 * @param {string} str Name of script (e.g. 'api'), defaults to 'index'
184 * @return {string} Address to script (e.g. '/w/api.php' )
186 wikiScript: function ( str
) {
187 str
= str
|| 'index';
188 if ( str
=== 'index' ) {
189 return mw
.config
.get( 'wgScript' );
190 } else if ( str
=== 'load' ) {
191 return config
.LoadScript
;
193 return mw
.config
.get( 'wgScriptPath' ) + '/' + str
+ '.php';
198 * Append a new style block to the head and return the CSSStyleSheet object.
199 * Use .ownerNode to access the `<style>` element, or use mw.loader#addStyleTag.
200 * This function returns the styleSheet object for convience (due to cross-browsers
201 * difference as to where it is located).
203 * var sheet = util.addCSS( '.foobar { display: none; }' );
204 * $( foo ).click( function () {
205 * // Toggle the sheet on and off
206 * sheet.disabled = !sheet.disabled;
209 * @param {string} text CSS to be appended
210 * @return {CSSStyleSheet} Use .ownerNode to get to the `<style>` element.
212 addCSS: function ( text
) {
213 var s
= mw
.loader
.addStyleTag( text
);
214 return s
.sheet
|| s
.styleSheet
|| s
;
218 * Grab the URL parameter value for the given parameter.
219 * Returns null if not found.
221 * @param {string} param The parameter name.
222 * @param {string} [url=location.href] URL to search through, defaulting to the current browsing location.
223 * @return {Mixed} Parameter value or null.
225 getParamValue: function ( param
, url
) {
226 // Get last match, stop at hash
227 var re
= new RegExp( '^[^#]*[&?]' + mw
.RegExp
.escape( param
) + '=([^&#]*)' ),
228 m
= re
.exec( url
!== undefined ? url
: location
.href
);
231 // Beware that decodeURIComponent is not required to understand '+'
232 // by spec, as encodeURIComponent does not produce it.
233 return decodeURIComponent( m
[ 1 ].replace( /\+/g, '%20' ) );
239 * The content wrapper of the skin (e.g. `.mw-body`).
241 * Populated on document ready. To use this property,
242 * wait for `$.ready` and be sure to have a module dependency on
243 * `mediawiki.util` which will ensure
244 * your document ready handler fires after initialization.
246 * Because of the lazy-initialised nature of this property,
247 * you're discouraged from using it.
249 * If you need just the wikipage content (not any of the
250 * extra elements output by the skin), use `$( '#mw-content-text' )`
251 * instead. Or listen to mw.hook#wikipage_content which will
252 * allow your code to re-run when the page changes (e.g. live preview
253 * or re-render after ajax save).
260 * Add a link to a portlet menu on the page, such as:
262 * p-cactions (Content actions), p-personal (Personal tools),
263 * p-navigation (Navigation), p-tb (Toolbox)
265 * The first three parameters are required, the others are optional and
266 * may be null. Though providing an id and tooltip is recommended.
268 * By default the new link will be added to the end of the list. To
269 * add the link before a given existing item, pass the DOM node
270 * (e.g. `document.getElementById( 'foobar' )`) or a jQuery-selector
271 * (e.g. `'#foobar'`) for that item.
273 * util.addPortletLink(
274 * 'p-tb', 'https://www.mediawiki.org/',
275 * 'mediawiki.org', 't-mworg', 'Go to mediawiki.org', 'm', '#t-print'
278 * var node = util.addPortletLink(
280 * new mw.Title( 'Special:Example' ).getUrl(),
283 * $( node ).on( 'click', function ( e ) {
284 * console.log( 'Example' );
285 * e.preventDefault();
288 * @param {string} portletId ID of the target portlet (e.g. 'p-cactions' or 'p-personal')
289 * @param {string} href Link URL
290 * @param {string} text Link text
291 * @param {string} [id] ID of the list item, should be unique and preferably have
292 * the appropriate prefix ('ca-', 'pt-', 'n-' or 't-')
293 * @param {string} [tooltip] Text to show when hovering over the link, without accesskey suffix
294 * @param {string} [accesskey] Access key to activate this link. One character only,
295 * avoid conflicts with other links. Use `$( '[accesskey=x]' )` in the console to
296 * see if 'x' is already used.
297 * @param {HTMLElement|jQuery|string} [nextnode] Element that the new item should be added before.
298 * Must be another item in the same list, it will be ignored otherwise.
299 * Can be specified as DOM reference, as jQuery object, or as CSS selector string.
300 * @return {HTMLElement|null} The added list item, or null if no element was added.
302 addPortletLink: function ( portletId
, href
, text
, id
, tooltip
, accesskey
, nextnode
) {
303 var item
, link
, $portlet
, portlet
, portletDiv
, ul
, next
;
306 // Avoid confusing id="undefined" lookup
310 portlet
= document
.getElementById( portletId
);
312 // Invalid portlet ID
316 // Setup the anchor tag and set any the properties
317 link
= document
.createElement( 'a' );
319 link
.textContent
= text
;
321 link
.title
= tooltip
;
324 link
.accessKey
= accesskey
;
327 // Unhide portlet if it was hidden before
328 $portlet
= $( portlet
);
329 $portlet
.removeClass( 'emptyPortlet' );
331 // Setup the list item (and a span if $portlet is a Vector tab)
332 if ( $portlet
.hasClass( 'vectorTabs' ) ) {
333 item
= $( '<li>' ).append( $( '<span>' ).append( link
)[ 0 ] )[ 0 ];
335 item
= $( '<li>' ).append( link
)[ 0 ];
341 // Select the first (most likely only) unordered list inside the portlet
342 ul
= portlet
.querySelector( 'ul' );
344 // If it didn't have an unordered list yet, create one
345 ul
= document
.createElement( 'ul' );
346 portletDiv
= portlet
.querySelector( 'div' );
348 // Support: Legacy skins have a div (such as div.body or div.pBody).
349 // Append the <ul> to that.
350 portletDiv
.appendChild( ul
);
352 // Append it to the portlet directly
353 portlet
.appendChild( ul
);
357 if ( nextnode
&& ( typeof nextnode
=== 'string' || nextnode
.nodeType
|| nextnode
.jquery
) ) {
358 nextnode
= $( ul
).find( nextnode
);
359 if ( nextnode
.length
=== 1 && nextnode
[ 0 ].parentNode
=== ul
) {
360 // Insertion point: Before nextnode
361 nextnode
.before( item
);
364 // Else: Invalid nextnode value (no match, more than one match, or not a direct child)
365 // Else: Invalid nextnode type
369 // Insertion point: End of list (default)
370 ul
.appendChild( item
);
373 // Update tooltip for the access key after inserting into DOM
374 // to get a localized access key label (T69946).
376 $( link
).updateTooltipAccessKeys();
383 * Validate a string as representing a valid e-mail address
384 * according to HTML5 specification. Please note the specification
385 * does not validate a domain with one character.
387 * FIXME: should be moved to or replaced by a validation module.
389 * @param {string} mailtxt E-mail address to be validated.
390 * @return {boolean|null} Null if `mailtxt` was an empty string, otherwise true/false
391 * as determined by validation.
393 validateEmail: function ( mailtxt
) {
394 var rfc5322Atext
, rfc1034LdhStr
, html5EmailRegexp
;
396 if ( mailtxt
=== '' ) {
400 // HTML5 defines a string as valid e-mail address if it matches
402 // 1 * ( atext / "." ) "@" ldh-str 1*( "." ldh-str )
404 // - atext : defined in RFC 5322 section 3.2.3
405 // - ldh-str : defined in RFC 1034 section 3.5
407 // (see STD 68 / RFC 5234 https://tools.ietf.org/html/std68)
408 // First, define the RFC 5322 'atext' which is pretty easy:
409 // atext = ALPHA / DIGIT / ; Printable US-ASCII
410 // "!" / "#" / ; characters not including
411 // "$" / "%" / ; specials. Used for atoms.
420 rfc5322Atext
= 'a-z0-9!#$%&\'*+\\-/=?^_`{|}~';
422 // Next define the RFC 1034 'ldh-str'
423 // <domain> ::= <subdomain> | " "
424 // <subdomain> ::= <label> | <subdomain> "." <label>
425 // <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
426 // <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
427 // <let-dig-hyp> ::= <let-dig> | "-"
428 // <let-dig> ::= <letter> | <digit>
429 rfc1034LdhStr
= 'a-z0-9\\-';
431 html5EmailRegexp
= new RegExp(
434 // User part which is liberal :p
435 '[' + rfc5322Atext
+ '\\.]+' +
439 '[' + rfc1034LdhStr
+ ']+' +
440 // Optional second part and following are separated by a dot
441 '(?:\\.[' + rfc1034LdhStr
+ ']+)*' +
444 // RegExp is case insensitive
447 return ( mailtxt
.match( html5EmailRegexp
) !== null );
451 * Note: borrows from IP::isIPv4
453 * @param {string} address
454 * @param {boolean} [allowBlock=false]
457 isIPv4Address: function ( address
, allowBlock
) {
458 var block
, RE_IP_BYTE
, RE_IP_ADD
;
460 if ( typeof address
!== 'string' ) {
464 block
= allowBlock
? '(?:\\/(?:3[0-2]|[12]?\\d))?' : '';
465 RE_IP_BYTE
= '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])';
466 RE_IP_ADD
= '(?:' + RE_IP_BYTE
+ '\\.){3}' + RE_IP_BYTE
;
468 return ( new RegExp( '^' + RE_IP_ADD
+ block
+ '$' ).test( address
) );
472 * Note: borrows from IP::isIPv6
474 * @param {string} address
475 * @param {boolean} [allowBlock=false]
478 isIPv6Address: function ( address
, allowBlock
) {
479 var block
, RE_IPV6_ADD
;
481 if ( typeof address
!== 'string' ) {
485 block
= allowBlock
? '(?:\\/(?:12[0-8]|1[01][0-9]|[1-9]?\\d))?' : '';
487 '(?:' + // starts with "::" (including "::")
491 '|' + // ends with "::" (except "::")
496 '|' + // contains no "::"
503 if ( new RegExp( '^' + RE_IPV6_ADD
+ block
+ '$' ).test( address
) ) {
507 // contains one "::" in the middle (single '::' check below)
515 new RegExp( '^' + RE_IPV6_ADD
+ block
+ '$' ).test( address
) &&
516 /::/.test( address
) &&
517 !/::.*::/.test( address
)
522 * Check whether a string is an IP address
525 * @param {string} address String to check
526 * @param {boolean} [allowBlock=false] If a block of IPs should be allowed
529 isIPAddress: function ( address
, allowBlock
) {
530 return util
.isIPv4Address( address
, allowBlock
) ||
531 util
.isIPv6Address( address
, allowBlock
);
536 * Initialisation of mw.util.$content
539 util
.$content
= ( function () {
540 var i
, l
, $node
, selectors
;
543 // The preferred standard is class "mw-body".
544 // You may also use class "mw-body mw-body-primary" if you use
545 // mw-body in multiple locations. Or class "mw-body-primary" if
546 // you use mw-body deeper in the DOM.
550 // If the skin has no such class, fall back to the parser output
554 for ( i
= 0, l
= selectors
.length
; i
< l
; i
++ ) {
555 $node
= $( selectors
[ i
] );
556 if ( $node
.length
) {
557 return $node
.first();
561 // Should never happen... well, it could if someone is not finished writing a
562 // skin and has not yet inserted bodytext yet.
570 module
.exports
= util
;