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} [str=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 `str`
109 getUrl: function ( str, params ) {
110 var titleFragmentStart,
113 pageName = typeof str === 'string' ? str : mw.config.get( 'wgPageName' );
115 // Find any fragment should one exist
116 if ( typeof str === 'string' ) {
117 titleFragmentStart = pageName.indexOf( '#' );
118 if ( titleFragmentStart !== -1 ) {
119 fragment = pageName.slice( titleFragmentStart + 1 );
120 // Exclude the fragment from the page name
121 pageName = pageName.slice( 0, titleFragmentStart );
125 url = mw.config.get( 'wgArticlePath' ).replace( '$1', util.wikiUrlencode( pageName ) );
127 // Add query string if necessary
128 if ( params && !$.isEmptyObject( params ) ) {
129 url += ( url.indexOf( '?' ) !== -1 ? '&' : '?' ) + $.param( params );
132 // Append the encoded fragment
133 if ( fragment.length > 0 ) {
134 url += '#' + util.escapeId( fragment );
141 * Get address to a script in the wiki root.
142 * For index.php use `mw.config.get( 'wgScript' )`.
145 * @param {string} str Name of script (e.g. 'api'), defaults to 'index'
146 * @return {string} Address to script (e.g. '/w/api.php' )
148 wikiScript: function ( str ) {
149 str = str || 'index';
150 if ( str === 'index' ) {
151 return mw.config.get( 'wgScript' );
152 } else if ( str === 'load' ) {
153 return mw.config.get( 'wgLoadScript' );
155 return mw.config.get( 'wgScriptPath' ) + '/' + str + '.php';
160 * Append a new style block to the head and return the CSSStyleSheet object.
161 * Use .ownerNode to access the `<style>` element, or use mw.loader#addStyleTag.
162 * This function returns the styleSheet object for convience (due to cross-browsers
163 * difference as to where it is located).
165 * var sheet = mw.util.addCSS( '.foobar { display: none; }' );
166 * $( foo ).click( function () {
167 * // Toggle the sheet on and off
168 * sheet.disabled = !sheet.disabled;
171 * @param {string} text CSS to be appended
172 * @return {CSSStyleSheet} Use .ownerNode to get to the `<style>` element.
174 addCSS: function ( text ) {
175 var s = mw.loader.addStyleTag( text );
176 return s.sheet || s.styleSheet || s;
180 * Grab the URL parameter value for the given parameter.
181 * Returns null if not found.
183 * @param {string} param The parameter name.
184 * @param {string} [url=location.href] URL to search through, defaulting to the current browsing location.
185 * @return {Mixed} Parameter value or null.
187 getParamValue: function ( param, url ) {
188 if ( url === undefined ) {
191 // Get last match, stop at hash
192 var re = new RegExp( '^[^#]*[&?]' + mw.RegExp.escape( param ) + '=([^&#]*)' ),
195 // Beware that decodeURIComponent is not required to understand '+'
196 // by spec, as encodeURIComponent does not produce it.
197 return decodeURIComponent( m[ 1 ].replace( /\+/g, '%20' ) );
203 * The content wrapper of the skin (e.g. `.mw-body`).
205 * Populated on document ready by #init. To use this property,
206 * wait for `$.ready` and be sure to have a module depedendency on
207 * `mediawiki.util` and `mediawiki.page.startup` which will ensure
208 * your document ready handler fires after #init.
210 * Because of the lazy-initialised nature of this property,
211 * you're discouraged from using it.
213 * If you need just the wikipage content (not any of the
214 * extra elements output by the skin), use `$( '#mw-content-text' )`
215 * instead. Or listen to mw.hook#wikipage_content which will
216 * allow your code to re-run when the page changes (e.g. live preview
217 * or re-render after ajax save).
224 * Add a link to a portlet menu on the page, such as:
226 * p-cactions (Content actions), p-personal (Personal tools),
227 * p-navigation (Navigation), p-tb (Toolbox)
229 * The first three parameters are required, the others are optional and
230 * may be null. Though providing an id and tooltip is recommended.
232 * By default the new link will be added to the end of the list. To
233 * add the link before a given existing item, pass the DOM node
234 * (e.g. `document.getElementById( 'foobar' )`) or a jQuery-selector
235 * (e.g. `'#foobar'`) for that item.
237 * mw.util.addPortletLink(
238 * 'p-tb', 'http://mediawiki.org/',
239 * 'MediaWiki.org', 't-mworg', 'Go to MediaWiki.org ', 'm', '#t-print'
242 * @param {string} portlet ID of the target portlet ( 'p-cactions' or 'p-personal' etc.)
243 * @param {string} href Link URL
244 * @param {string} text Link text
245 * @param {string} [id] ID of the new item, should be unique and preferably have
246 * the appropriate prefix ( 'ca-', 'pt-', 'n-' or 't-' )
247 * @param {string} [tooltip] Text to show when hovering over the link, without accesskey suffix
248 * @param {string} [accesskey] Access key to activate this link (one character, try
249 * to avoid conflicts. Use `$( '[accesskey=x]' ).get()` in the console to
250 * see if 'x' is already used.
251 * @param {HTMLElement|jQuery|string} [nextnode] Element or jQuery-selector string to the item that
252 * the new item should be added before, should be another item in the same
253 * list, it will be ignored otherwise
255 * @return {HTMLElement|null} The added element (a ListItem or Anchor element,
256 * depending on the skin) or null if no element was added to the document.
258 addPortletLink: function ( portlet, href, text, id, tooltip, accesskey, nextnode ) {
259 var $item, $link, $portlet, $ul;
261 // Check if there's at least 3 arguments to prevent a TypeError
262 if ( arguments.length < 3 ) {
265 // Setup the anchor tag
266 $link = $( '<a>' ).attr( 'href', href ).text( text );
268 $link.attr( 'title', tooltip );
271 // Select the specified portlet
272 $portlet = $( '#' + portlet );
273 if ( $portlet.length === 0 ) {
276 // Select the first (most likely only) unordered list inside the portlet
277 $ul = $portlet.find( 'ul' ).eq( 0 );
279 // If it didn't have an unordered list yet, create it
280 if ( $ul.length === 0 ) {
284 // If there's no <div> inside, append it to the portlet directly
285 if ( $portlet.find( 'div:first' ).length === 0 ) {
286 $portlet.append( $ul );
288 // otherwise if there's a div (such as div.body or div.pBody)
289 // append the <ul> to last (most likely only) div
290 $portlet.find( 'div' ).eq( -1 ).append( $ul );
294 if ( $ul.length === 0 ) {
298 // Unhide portlet if it was hidden before
299 $portlet.removeClass( 'emptyPortlet' );
301 // Wrap the anchor tag in a list item (and a span if $portlet is a Vector tab)
302 // and back up the selector to the list item
303 if ( $portlet.hasClass( 'vectorTabs' ) ) {
304 $item = $link.wrap( '<li><span></span></li>' ).parent().parent();
306 $item = $link.wrap( '<li></li>' ).parent();
309 // Implement the properties passed to the function
311 $item.attr( 'id', id );
315 $link.attr( 'accesskey', accesskey );
319 $link.attr( 'title', tooltip );
323 // Case: nextnode is a DOM element (was the only option before MW 1.17, in wikibits.js)
324 // Case: nextnode is a CSS selector for jQuery
325 if ( nextnode.nodeType || typeof nextnode === 'string' ) {
326 nextnode = $ul.find( nextnode );
327 } else if ( !nextnode.jquery ) {
328 // Error: Invalid nextnode
329 nextnode = undefined;
331 if ( nextnode && ( nextnode.length !== 1 || nextnode[ 0 ].parentNode !== $ul[ 0 ] ) ) {
332 // Error: nextnode must resolve to a single node
333 // Error: nextnode must have the associated <ul> as its parent
334 nextnode = undefined;
338 // Case: nextnode is a jQuery-wrapped DOM element
340 nextnode.before( $item );
342 // Fallback (this is the default behavior)
346 // Update tooltip for the access key after inserting into DOM
347 // to get a localized access key label (bug 67946).
348 $link.updateTooltipAccessKeys();
354 * Validate a string as representing a valid e-mail address
355 * according to HTML5 specification. Please note the specification
356 * does not validate a domain with one character.
358 * FIXME: should be moved to or replaced by a validation module.
360 * @param {string} mailtxt E-mail address to be validated.
361 * @return {boolean|null} Null if `mailtxt` was an empty string, otherwise true/false
362 * as determined by validation.
364 validateEmail: function ( mailtxt ) {
365 var rfc5322Atext, rfc1034LdhStr, html5EmailRegexp;
367 if ( mailtxt === '' ) {
371 // HTML5 defines a string as valid e-mail address if it matches
373 // 1 * ( atext / "." ) "@" ldh-str 1*( "." ldh-str )
375 // - atext : defined in RFC 5322 section 3.2.3
376 // - ldh-str : defined in RFC 1034 section 3.5
378 // (see STD 68 / RFC 5234 http://tools.ietf.org/html/std68)
379 // First, define the RFC 5322 'atext' which is pretty easy:
380 // atext = ALPHA / DIGIT / ; Printable US-ASCII
381 // "!" / "#" / ; characters not including
382 // "$" / "%" / ; specials. Used for atoms.
391 rfc5322Atext = 'a-z0-9!#$%&\'*+\\-/=?^_`{|}~';
393 // Next define the RFC 1034 'ldh-str'
394 // <domain> ::= <subdomain> | " "
395 // <subdomain> ::= <label> | <subdomain> "." <label>
396 // <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
397 // <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
398 // <let-dig-hyp> ::= <let-dig> | "-"
399 // <let-dig> ::= <letter> | <digit>
400 rfc1034LdhStr = 'a-z0-9\\-';
402 html5EmailRegexp = new RegExp(
406 // User part which is liberal :p
407 '[' + rfc5322Atext + '\\.]+'
413 '[' + rfc1034LdhStr + ']+'
415 // Optional second part and following are separated by a dot
416 '(?:\\.[' + rfc1034LdhStr + ']+)*'
420 // RegExp is case insensitive
423 return ( mailtxt.match( html5EmailRegexp ) !== null );
427 * Note: borrows from IP::isIPv4
429 * @param {string} address
430 * @param {boolean} allowBlock
433 isIPv4Address: function ( address, allowBlock ) {
434 if ( typeof address !== 'string' ) {
438 var block = allowBlock ? '(?:\\/(?:3[0-2]|[12]?\\d))?' : '',
439 RE_IP_BYTE = '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])',
440 RE_IP_ADD = '(?:' + RE_IP_BYTE + '\\.){3}' + RE_IP_BYTE;
442 return address.search( new RegExp( '^' + RE_IP_ADD + block + '$' ) ) !== -1;
446 * Note: borrows from IP::isIPv6
448 * @param {string} address
449 * @param {boolean} allowBlock
452 isIPv6Address: function ( address, allowBlock ) {
453 if ( typeof address !== 'string' ) {
457 var block = allowBlock ? '(?:\\/(?:12[0-8]|1[01][0-9]|[1-9]?\\d))?' : '',
459 '(?:' + // starts with "::" (including "::")
460 ':(?::|(?::' + '[0-9A-Fa-f]{1,4}' + '){1,7})' +
461 '|' + // ends with "::" (except "::")
462 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){0,6}::' +
463 '|' + // contains no "::"
464 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){7}' +
467 if ( address.search( new RegExp( '^' + RE_IPV6_ADD + block + '$' ) ) !== -1 ) {
471 RE_IPV6_ADD = // contains one "::" in the middle (single '::' check below)
472 '[0-9A-Fa-f]{1,4}' + '(?:::?' + '[0-9A-Fa-f]{1,4}' + '){1,6}';
474 return address.search( new RegExp( '^' + RE_IPV6_ADD + block + '$' ) ) !== -1
475 && address.search( /::/ ) !== -1 && address.search( /::.*::/ ) === -1;
479 * Check whether a string is an IP address
482 * @param {string} address String to check
483 * @param {boolean} allowBlock True if a block of IPs should be allowed
486 isIPAddress: function ( address, allowBlock ) {
487 return util.isIPv4Address( address, allowBlock ) ||
488 util.isIPv6Address( address, allowBlock );
493 * @method wikiGetlink
494 * @inheritdoc #getUrl
495 * @deprecated since 1.23 Use #getUrl instead.
497 mw.log.deprecate( util, 'wikiGetlink', util.getUrl, 'Use mw.util.getUrl instead.' );
500 * Access key prefix. Might be wrong for browsers implementing the accessKeyLabel property.
501 * @property {string} tooltipAccessKeyPrefix
502 * @deprecated since 1.24 Use the module jquery.accessKeyLabel instead.
504 mw.log.deprecate( util, 'tooltipAccessKeyPrefix', $.fn.updateTooltipAccessKeys.getAccessKeyPrefix(), 'Use jquery.accessKeyLabel instead.' );
507 * Regex to match accesskey tooltips.
511 * - "[ctrl-option-x]"
516 * The accesskey is matched in group $6.
518 * Will probably not work for browsers implementing the accessKeyLabel property.
520 * @property {RegExp} tooltipAccessKeyRegexp
521 * @deprecated since 1.24 Use the module jquery.accessKeyLabel instead.
523 mw.log.deprecate( util, 'tooltipAccessKeyRegexp', /\[(ctrl-)?(option-)?(alt-)?(shift-)?(esc-)?(.)\]$/, 'Use jquery.accessKeyLabel instead.' );
526 * Add the appropriate prefix to the accesskey shown in the tooltip.
528 * If the `$nodes` parameter is given, only those nodes are updated;
529 * otherwise, depending on browser support, we update either all elements
530 * with accesskeys on the page or a bunch of elements which are likely to
531 * have them on core skins.
533 * @method updateTooltipAccessKeys
534 * @param {Array|jQuery} [$nodes] A jQuery object, or array of nodes to update.
535 * @deprecated since 1.24 Use the module jquery.accessKeyLabel instead.
537 mw.log.deprecate( util, 'updateTooltipAccessKeys', function ( $nodes ) {
539 if ( document.querySelectorAll ) {
540 // If we're running on a browser where we can do this efficiently,
541 // just find all elements that have accesskeys. We can't use jQuery's
542 // polyfill for the selector since looping over all elements on page
543 // load might be too slow.
544 $nodes = $( document.querySelectorAll( '[accesskey]' ) );
546 // Otherwise go through some elements likely to have accesskeys rather
547 // than looping over all of them. Unfortunately this will not fully
548 // work for custom skins with different HTML structures. Input, label
549 // and button should be rare enough that no optimizations are needed.
550 $nodes = $( '#column-one a, #mw-head a, #mw-panel a, #p-logo a, input, label, button' );
552 } else if ( !( $nodes instanceof $ ) ) {
553 $nodes = $( $nodes );
556 $nodes.updateTooltipAccessKeys();
557 }, 'Use jquery.accessKeyLabel instead.' );
560 * Add a little box at the top of the screen to inform the user of
561 * something, replacing any previous message.
562 * Calling with no arguments, with an empty string or null will hide the message
565 * @deprecated since 1.20 Use mw#notify
566 * @param {Mixed} message The DOM-element, jQuery object or HTML-string to be put inside the message box.
567 * to allow CSS/JS to hide different boxes. null = no class used.
569 mw.log.deprecate( util, 'jsMessage', function ( message ) {
570 if ( !arguments.length || message === '' || message === null ) {
573 if ( typeof message !== 'object' ) {
574 message = $.parseHTML( message );
576 mw.notify( message, { autoHide: true, tag: 'legacy' } );
578 }, 'Use mw.notify instead.' );
582 }( mediaWiki, jQuery ) );