13 * (don't call before document ready)
16 util
.$content
= ( function () {
17 var i
, l
, $node
, selectors
;
20 // The preferred standard is class "mw-body".
21 // You may also use class "mw-body mw-body-primary" if you use
22 // mw-body in multiple locations. Or class "mw-body-primary" if
23 // you use mw-body deeper in the DOM.
27 // If the skin has no such class, fall back to the parser output
30 // Should never happen... well, it could if someone is not finished writing a
31 // skin and has not yet inserted bodytext yet.
35 for ( i
= 0, l
= selectors
.length
; i
< l
; i
++ ) {
36 $node
= $( selectors
[ i
] );
42 // Preserve existing customized value in case it was preset
50 * Encode the string like PHP's rawurlencode
52 * @param {string} str String to be encoded.
54 rawurlencode: function ( str
) {
56 return encodeURIComponent( str
)
57 .replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' )
58 .replace( /\)/g, '%29' ).replace( /\*/g, '%2A
' ).replace( /~/g, '%7E
' );
62 * Encode the string like Sanitizer::escapeId in PHP
64 * @param {string} str String to be encoded.
66 escapeId: function ( str ) {
68 return util.rawurlencode( str.replace( / /g, '_
' ) )
69 .replace( /%3A/g, ':' )
70 .replace( /%/g, '.' );
74 * Encode page titles for use in a URL
76 * We want / and : to be included as literal characters in our title URLs
77 * as they otherwise fatally break the title.
79 * The others are decoded because we can, it's prettier and matches behaviour
80 * of `wfUrlencode` in PHP
.
82 * @param
{string
} str String to be encoded
.
84 wikiUrlencode: function ( str
) {
85 return util
.rawurlencode( str
)
86 .replace( /%20/g, '_' )
87 // wfUrlencode replacements
88 .replace( /%3B/g, ';' )
89 .replace( /%40/g, '@' )
90 .replace( /%24/g, '$' )
91 .replace( /%21/g, '!' )
92 .replace( /%2A/g, '*' )
93 .replace( /%28/g, '(' )
94 .replace( /%29/g, ')' )
95 .replace( /%2C/g, ',' )
96 .replace( /%2F/g, '/' )
97 .replace( /%7E/g, '~' )
98 .replace( /%3A/g, ':' );
102 * Get the link to a page name (relative to `wgServer`),
104 * @param {string|null} [pageName=wgPageName] Page name
105 * @param {Object} [params] A mapping of query parameter names to values,
106 * e.g. `{ action: 'edit' }`
107 * @return {string} Url of the page with name of `pageName`
109 getUrl: function ( pageName
, params
) {
110 var titleFragmentStart
, url
, query
,
112 title
= typeof pageName
=== 'string' ? pageName
: mw
.config
.get( 'wgPageName' );
115 titleFragmentStart
= title
.indexOf( '#' );
116 if ( titleFragmentStart
!== -1 ) {
117 fragment
= title
.slice( titleFragmentStart
+ 1 );
118 // Exclude the fragment from the page name
119 title
= title
.slice( 0, titleFragmentStart
);
122 // Produce query string
124 query
= $.param( params
);
128 util
.wikiScript() + '?title=' + util
.wikiUrlencode( title
) + '&' + query
:
129 util
.wikiScript() + '?' + query
;
131 url
= mw
.config
.get( 'wgArticlePath' )
132 .replace( '$1', util
.wikiUrlencode( title
).replace( /\$/g, '$$$$' ) );
135 // Append the encoded fragment
136 if ( fragment
.length
) {
137 url
+= '#' + util
.escapeId( fragment
);
144 * Get address to a script in the wiki root.
145 * For index.php use `mw.config.get( 'wgScript' )`.
148 * @param {string} str Name of script (e.g. 'api'), defaults to 'index'
149 * @return {string} Address to script (e.g. '/w/api.php' )
151 wikiScript: function ( str
) {
152 str
= str
|| 'index';
153 if ( str
=== 'index' ) {
154 return mw
.config
.get( 'wgScript' );
155 } else if ( str
=== 'load' ) {
156 return mw
.config
.get( 'wgLoadScript' );
158 return mw
.config
.get( 'wgScriptPath' ) + '/' + str
+ '.php';
163 * Append a new style block to the head and return the CSSStyleSheet object.
164 * Use .ownerNode to access the `<style>` element, or use mw.loader#addStyleTag.
165 * This function returns the styleSheet object for convience (due to cross-browsers
166 * difference as to where it is located).
168 * var sheet = mw.util.addCSS( '.foobar { display: none; }' );
169 * $( foo ).click( function () {
170 * // Toggle the sheet on and off
171 * sheet.disabled = !sheet.disabled;
174 * @param {string} text CSS to be appended
175 * @return {CSSStyleSheet} Use .ownerNode to get to the `<style>` element.
177 addCSS: function ( text
) {
178 var s
= mw
.loader
.addStyleTag( text
);
179 return s
.sheet
|| s
.styleSheet
|| s
;
183 * Grab the URL parameter value for the given parameter.
184 * Returns null if not found.
186 * @param {string} param The parameter name.
187 * @param {string} [url=location.href] URL to search through, defaulting to the current browsing location.
188 * @return {Mixed} Parameter value or null.
190 getParamValue: function ( param
, url
) {
191 // Get last match, stop at hash
192 var re
= new RegExp( '^[^#]*[&?]' + mw
.RegExp
.escape( param
) + '=([^&#]*)' ),
193 m
= re
.exec( url
!== undefined ? url
: location
.href
);
196 // Beware that decodeURIComponent is not required to understand '+'
197 // by spec, as encodeURIComponent does not produce it.
198 return decodeURIComponent( m
[ 1 ].replace( /\+/g, '%20' ) );
204 * The content wrapper of the skin (e.g. `.mw-body`).
206 * Populated on document ready by #init. To use this property,
207 * wait for `$.ready` and be sure to have a module depedendency on
208 * `mediawiki.util` and `mediawiki.page.startup` which will ensure
209 * your document ready handler fires after #init.
211 * Because of the lazy-initialised nature of this property,
212 * you're discouraged from using it.
214 * If you need just the wikipage content (not any of the
215 * extra elements output by the skin), use `$( '#mw-content-text' )`
216 * instead. Or listen to mw.hook#wikipage_content which will
217 * allow your code to re-run when the page changes (e.g. live preview
218 * or re-render after ajax save).
225 * Add a link to a portlet menu on the page, such as:
227 * p-cactions (Content actions), p-personal (Personal tools),
228 * p-navigation (Navigation), p-tb (Toolbox)
230 * The first three parameters are required, the others are optional and
231 * may be null. Though providing an id and tooltip is recommended.
233 * By default the new link will be added to the end of the list. To
234 * add the link before a given existing item, pass the DOM node
235 * (e.g. `document.getElementById( 'foobar' )`) or a jQuery-selector
236 * (e.g. `'#foobar'`) for that item.
238 * mw.util.addPortletLink(
239 * 'p-tb', 'https://www.mediawiki.org/',
240 * 'mediawiki.org', 't-mworg', 'Go to mediawiki.org', 'm', '#t-print'
243 * var node = mw.util.addPortletLink(
245 * new mw.Title( 'Special:Example' ).getUrl(),
248 * $( node ).on( 'click', function ( e ) {
249 * console.log( 'Example' );
250 * e.preventDefault();
253 * @param {string} portlet ID of the target portlet ( 'p-cactions' or 'p-personal' etc.)
254 * @param {string} href Link URL
255 * @param {string} text Link text
256 * @param {string} [id] ID of the new item, should be unique and preferably have
257 * the appropriate prefix ( 'ca-', 'pt-', 'n-' or 't-' )
258 * @param {string} [tooltip] Text to show when hovering over the link, without accesskey suffix
259 * @param {string} [accesskey] Access key to activate this link (one character, try
260 * to avoid conflicts. Use `$( '[accesskey=x]' ).get()` in the console to
261 * see if 'x' is already used.
262 * @param {HTMLElement|jQuery|string} [nextnode] Element or jQuery-selector string to the item that
263 * the new item should be added before, should be another item in the same
264 * list, it will be ignored otherwise
266 * @return {HTMLElement|null} The added element (a ListItem or Anchor element,
267 * depending on the skin) or null if no element was added to the document.
269 addPortletLink: function ( portlet
, href
, text
, id
, tooltip
, accesskey
, nextnode
) {
270 var $item
, $link
, $portlet
, $ul
;
272 // Check if there's at least 3 arguments to prevent a TypeError
273 if ( arguments
.length
< 3 ) {
276 // Setup the anchor tag
277 $link
= $( '<a>' ).attr( 'href', href
).text( text
);
279 $link
.attr( 'title', tooltip
);
282 // Select the specified portlet
283 $portlet
= $( '#' + portlet
);
284 if ( $portlet
.length
=== 0 ) {
287 // Select the first (most likely only) unordered list inside the portlet
288 $ul
= $portlet
.find( 'ul' ).eq( 0 );
290 // If it didn't have an unordered list yet, create it
291 if ( $ul
.length
=== 0 ) {
295 // If there's no <div> inside, append it to the portlet directly
296 if ( $portlet
.find( 'div:first' ).length
=== 0 ) {
297 $portlet
.append( $ul
);
299 // otherwise if there's a div (such as div.body or div.pBody)
300 // append the <ul> to last (most likely only) div
301 $portlet
.find( 'div' ).eq( -1 ).append( $ul
);
305 if ( $ul
.length
=== 0 ) {
309 // Unhide portlet if it was hidden before
310 $portlet
.removeClass( 'emptyPortlet' );
312 // Wrap the anchor tag in a list item (and a span if $portlet is a Vector tab)
313 // and back up the selector to the list item
314 if ( $portlet
.hasClass( 'vectorTabs' ) ) {
315 $item
= $link
.wrap( '<li><span></span></li>' ).parent().parent();
317 $item
= $link
.wrap( '<li></li>' ).parent();
320 // Implement the properties passed to the function
322 $item
.attr( 'id', id
);
326 $link
.attr( 'accesskey', accesskey
);
330 $link
.attr( 'title', tooltip
);
334 // Case: nextnode is a DOM element (was the only option before MW 1.17, in wikibits.js)
335 // Case: nextnode is a CSS selector for jQuery
336 if ( nextnode
.nodeType
|| typeof nextnode
=== 'string' ) {
337 nextnode
= $ul
.find( nextnode
);
338 } else if ( !nextnode
.jquery
) {
339 // Error: Invalid nextnode
340 nextnode
= undefined;
342 if ( nextnode
&& ( nextnode
.length
!== 1 || nextnode
[ 0 ].parentNode
!== $ul
[ 0 ] ) ) {
343 // Error: nextnode must resolve to a single node
344 // Error: nextnode must have the associated <ul> as its parent
345 nextnode
= undefined;
349 // Case: nextnode is a jQuery-wrapped DOM element
351 nextnode
.before( $item
);
353 // Fallback (this is the default behavior)
357 // Update tooltip for the access key after inserting into DOM
358 // to get a localized access key label (bug 67946).
359 $link
.updateTooltipAccessKeys();
365 * Validate a string as representing a valid e-mail address
366 * according to HTML5 specification. Please note the specification
367 * does not validate a domain with one character.
369 * FIXME: should be moved to or replaced by a validation module.
371 * @param {string} mailtxt E-mail address to be validated.
372 * @return {boolean|null} Null if `mailtxt` was an empty string, otherwise true/false
373 * as determined by validation.
375 validateEmail: function ( mailtxt
) {
376 var rfc5322Atext
, rfc1034LdhStr
, html5EmailRegexp
;
378 if ( mailtxt
=== '' ) {
382 // HTML5 defines a string as valid e-mail address if it matches
384 // 1 * ( atext / "." ) "@" ldh-str 1*( "." ldh-str )
386 // - atext : defined in RFC 5322 section 3.2.3
387 // - ldh-str : defined in RFC 1034 section 3.5
389 // (see STD 68 / RFC 5234 https://tools.ietf.org/html/std68)
390 // First, define the RFC 5322 'atext' which is pretty easy:
391 // atext = ALPHA / DIGIT / ; Printable US-ASCII
392 // "!" / "#" / ; characters not including
393 // "$" / "%" / ; specials. Used for atoms.
402 rfc5322Atext
= 'a-z0-9!#$%&\'*+\\-/=?^_`{|}~';
404 // Next define the RFC 1034 'ldh-str'
405 // <domain> ::= <subdomain> | " "
406 // <subdomain> ::= <label> | <subdomain> "." <label>
407 // <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
408 // <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
409 // <let-dig-hyp> ::= <let-dig> | "-"
410 // <let-dig> ::= <letter> | <digit>
411 rfc1034LdhStr
= 'a-z0-9\\-';
413 html5EmailRegexp
= new RegExp(
416 // User part which is liberal :p
417 '[' + rfc5322Atext
+ '\\.]+' +
421 '[' + rfc1034LdhStr
+ ']+' +
422 // Optional second part and following are separated by a dot
423 '(?:\\.[' + rfc1034LdhStr
+ ']+)*' +
426 // RegExp is case insensitive
429 return ( mailtxt
.match( html5EmailRegexp
) !== null );
433 * Note: borrows from IP::isIPv4
435 * @param {string} address
436 * @param {boolean} allowBlock
439 isIPv4Address: function ( address
, allowBlock
) {
440 var block
, RE_IP_BYTE
, RE_IP_ADD
;
442 if ( typeof address
!== 'string' ) {
446 block
= allowBlock
? '(?:\\/(?:3[0-2]|[12]?\\d))?' : '';
447 RE_IP_BYTE
= '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])';
448 RE_IP_ADD
= '(?:' + RE_IP_BYTE
+ '\\.){3}' + RE_IP_BYTE
;
450 return ( new RegExp( '^' + RE_IP_ADD
+ block
+ '$' ).test( address
) );
454 * Note: borrows from IP::isIPv6
456 * @param {string} address
457 * @param {boolean} allowBlock
460 isIPv6Address: function ( address
, allowBlock
) {
461 var block
, RE_IPV6_ADD
;
463 if ( typeof address
!== 'string' ) {
467 block
= allowBlock
? '(?:\\/(?:12[0-8]|1[01][0-9]|[1-9]?\\d))?' : '';
469 '(?:' + // starts with "::" (including "::")
470 ':(?::|(?::' + '[0-9A-Fa-f]{1,4}' + '){1,7})' +
471 '|' + // ends with "::" (except "::")
472 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){0,6}::' +
473 '|' + // contains no "::"
474 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){7}' +
477 if ( new RegExp( '^' + RE_IPV6_ADD
+ block
+ '$' ).test( address
) ) {
481 // contains one "::" in the middle (single '::' check below)
482 RE_IPV6_ADD
= '[0-9A-Fa-f]{1,4}' + '(?:::?' + '[0-9A-Fa-f]{1,4}' + '){1,6}';
485 new RegExp( '^' + RE_IPV6_ADD
+ block
+ '$' ).test( address
) &&
486 /::/.test( address
) &&
487 !/::.*::/.test( address
)
492 * Check whether a string is an IP address
495 * @param {string} address String to check
496 * @param {boolean} allowBlock True if a block of IPs should be allowed
499 isIPAddress: function ( address
, allowBlock
) {
500 return util
.isIPv4Address( address
, allowBlock
) ||
501 util
.isIPv6Address( address
, allowBlock
);
506 * @method wikiGetlink
507 * @inheritdoc #getUrl
508 * @deprecated since 1.23 Use #getUrl instead.
510 mw
.log
.deprecate( util
, 'wikiGetlink', util
.getUrl
, 'Use mw.util.getUrl instead.' );
513 * Add the appropriate prefix to the accesskey shown in the tooltip.
515 * If the `$nodes` parameter is given, only those nodes are updated;
516 * otherwise we update all elements with accesskeys on the page.
518 * @method updateTooltipAccessKeys
519 * @param {Array|jQuery} [$nodes] A jQuery object, or array of nodes to update.
520 * @deprecated since 1.24 Use the module jquery.accessKeyLabel instead.
522 mw
.log
.deprecate( util
, 'updateTooltipAccessKeys', function ( $nodes
) {
524 $nodes
= $( '[accesskey]' );
525 } else if ( !( $nodes
instanceof $ ) ) {
526 $nodes
= $( $nodes
);
529 $nodes
.updateTooltipAccessKeys();
530 }, 'Use jquery.accessKeyLabel instead.' );
533 * Add a little box at the top of the screen to inform the user of
534 * something, replacing any previous message.
535 * Calling with no arguments, with an empty string or null will hide the message
538 * @deprecated since 1.20 Use mw#notify
539 * @param {Mixed} message The DOM-element, jQuery object or HTML-string to be put inside the message box.
540 * to allow CSS/JS to hide different boxes. null = no class used.
542 mw
.log
.deprecate( util
, 'jsMessage', function ( message
) {
543 if ( !arguments
.length
|| message
=== '' || message
=== null ) {
546 if ( typeof message
!== 'object' ) {
547 message
= $.parseHTML( message
);
549 mw
.notify( message
, { autoHide
: true, tag
: 'legacy' } );
551 }, 'Use mw.notify instead.' );
555 }( mediaWiki
, jQuery
) );