13 * (don't call before document ready)
16 var profile, $tocTitle, $tocToggleLink, hideTocCookie;
18 /* Set tooltipAccessKeyPrefix */
19 profile = $.client.profile();
21 // Opera on any platform
22 if ( profile.name === 'opera' ) {
23 util.tooltipAccessKeyPrefix = 'shift-esc-';
25 // Chrome on any platform
26 } else if ( profile.name === 'chrome' ) {
28 util.tooltipAccessKeyPrefix = (
29 profile.platform === 'mac'
32 // Chrome on Windows or Linux
33 // (both alt- and alt-shift work, but alt with E, D, F etc does not
34 // work since they are browser shortcuts)
38 // Non-Windows Safari with webkit_version > 526
39 } else if ( profile.platform !== 'win'
40 && profile.name === 'safari'
41 && profile.layoutVersion > 526 ) {
42 util.tooltipAccessKeyPrefix = 'ctrl-alt-';
44 } else if ( profile.platform === 'mac'
45 && profile.name === 'firefox'
46 && profile.versionNumber >= 14 ) {
47 util.tooltipAccessKeyPrefix = 'ctrl-option-';
48 // Safari/Konqueror on any platform, or any browser on Mac
49 // (but not Safari on Windows)
50 } else if ( !( profile.platform === 'win' && profile.name === 'safari' )
51 && ( profile.name === 'safari'
52 || profile.platform === 'mac'
53 || profile.name === 'konqueror' ) ) {
54 util.tooltipAccessKeyPrefix = 'ctrl-';
56 // Firefox 2.x and later
57 } else if ( profile.name === 'firefox' && profile.versionBase > '1' ) {
58 util.tooltipAccessKeyPrefix = 'alt-shift-';
61 /* Fill $content var */
62 util.$content = ( function () {
63 var i, l, $content, selectors;
65 // The preferred standard for setting $content (class="mw-body")
66 // You may also use (class="mw-body mw-body-primary") if you use
67 // mw-body in multiple locations.
68 // Or class="mw-body-primary" if you want $content to be deeper
69 // in the dom than mw-body
73 /* Legacy fallbacks for setting the content */
74 // Vector, Monobook, Chick, etc... based skins
80 // Standard, CologneBlue
83 // #content is present on almost all if not all skins. Most skins (the above cases)
84 // have #content too, but as an outer wrapper instead of the article text container.
85 // The skins that don't have an outer wrapper do have #content for everything
86 // so it's a good fallback
89 // If nothing better is found fall back to our bodytext div that is guaranteed to be here
92 // Should never happen... well, it could if someone is not finished writing a skin and has
93 // not inserted bodytext yet. But in any case <body> should always exist
96 for ( i = 0, l = selectors.length; i < l; i++ ) {
97 $content = $( selectors[i] ).first();
98 if ( $content.length ) {
103 // Make sure we don't unset util.$content if it was preset and we don't find anything
104 return util.$content;
107 mw.hook( 'wikipage.content' ).fire( util.$content );
109 // Table of contents toggle
110 $tocTitle = $( '#toctitle' );
111 $tocToggleLink = $( '#togglelink' );
112 // Only add it if there is a TOC and there is no toggle added already
113 if ( $( '#toc' ).length && $tocTitle.length && !$tocToggleLink.length ) {
114 hideTocCookie = $.cookie( 'mw_hidetoc' );
115 $tocToggleLink = $( '<a href="#" class="internal" id="togglelink"></a>' )
116 .text( mw.msg( 'hidetoc' ) )
117 .click( function ( e ) {
119 util.toggleToc( $(this) );
123 .wrap( '<span class="toctoggle"></span>' )
125 .prepend( ' [' )
129 if ( hideTocCookie === '1' ) {
130 util.toggleToc( $tocToggleLink );
138 * Encode the string like PHP's rawurlencode
140 * @param {string} str String to be encoded.
142 rawurlencode: function ( str ) {
144 return encodeURIComponent( str )
145 .replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' )
146 .replace( /\)/g, '%29' ).replace( /\*/g, '%2A' ).replace( /~/g, '%7E' );
150 * Encode page titles for use in a URL
151 * We want / and : to be included as literal characters in our title URLs
152 * as they otherwise fatally break the title
154 * @param {string} str String to be encoded.
156 wikiUrlencode: function ( str ) {
157 return util.rawurlencode( str )
158 .replace( /%20/g, '_' ).replace( /%3A/g, ':' ).replace( /%2F/g, '/' );
162 * Get the link to a page name (relative to `wgServer`),
164 * @param {string} str Page name to get the link for.
165 * @return {string} Location for a page with name of `str` or boolean false on error.
167 wikiGetlink: function ( str ) {
168 return mw.config.get( 'wgArticlePath' ).replace( '$1',
169 util.wikiUrlencode( typeof str === 'string' ? str : mw.config.get( 'wgPageName' ) ) );
173 * Get address to a script in the wiki root.
174 * For index.php use `mw.config.get( 'wgScript' )`.
177 * @param str string Name of script (eg. 'api'), defaults to 'index'
178 * @return string Address to script (eg. '/w/api.php' )
180 wikiScript: function ( str ) {
181 str = str || 'index';
182 if ( str === 'index' ) {
183 return mw.config.get( 'wgScript' );
184 } else if ( str === 'load' ) {
185 return mw.config.get( 'wgLoadScript' );
187 return mw.config.get( 'wgScriptPath' ) + '/' + str +
188 mw.config.get( 'wgScriptExtension' );
193 * Append a new style block to the head and return the CSSStyleSheet object.
194 * Use .ownerNode to access the `<style>` element, or use mw.loader#addStyleTag.
195 * This function returns the styleSheet object for convience (due to cross-browsers
196 * difference as to where it is located).
198 * var sheet = mw.util.addCSS('.foobar { display: none; }');
199 * $(foo).click(function () {
200 * // Toggle the sheet on and off
201 * sheet.disabled = !sheet.disabled;
204 * @param {string} text CSS to be appended
205 * @return {CSSStyleSheet} Use .ownerNode to get to the `<style>` element.
207 addCSS: function ( text ) {
208 var s = mw.loader.addStyleTag( text );
213 * Hide/show the table of contents element
215 * @param {jQuery} $toggleLink A jQuery object of the toggle link.
216 * @param {Function} [callback] Function to be called after the toggle is
217 * completed (including the animation).
218 * @return {Mixed} Boolean visibility of the toc (true if it's visible)
219 * or Null if there was no table of contents.
221 toggleToc: function ( $toggleLink, callback ) {
222 var $tocList = $( '#toc ul:first' );
224 // This function shouldn't be called if there's no TOC,
225 // but just in case...
226 if ( $tocList.length ) {
227 if ( $tocList.is( ':hidden' ) ) {
228 $tocList.slideDown( 'fast', callback );
229 $toggleLink.text( mw.msg( 'hidetoc' ) );
230 $( '#toc' ).removeClass( 'tochidden' );
231 $.cookie( 'mw_hidetoc', null, {
237 $tocList.slideUp( 'fast', callback );
238 $toggleLink.text( mw.msg( 'showtoc' ) );
239 $( '#toc' ).addClass( 'tochidden' );
240 $.cookie( 'mw_hidetoc', '1', {
252 * Grab the URL parameter value for the given parameter.
253 * Returns null if not found.
255 * @param {string} param The parameter name.
256 * @param {string} [url=document.location.href] URL to search through, defaulting to the current document's URL.
257 * @return {Mixed} Parameter value or null.
259 getParamValue: function ( param, url ) {
260 if ( url === undefined ) {
261 url = document.location.href;
263 // Get last match, stop at hash
264 var re = new RegExp( '^[^#]*[&?]' + $.escapeRE( param ) + '=([^&#]*)' ),
267 // Beware that decodeURIComponent is not required to understand '+'
268 // by spec, as encodeURIComponent does not produce it.
269 return decodeURIComponent( m[1].replace( /\+/g, '%20' ) );
276 * Access key prefix. Will be re-defined based on browser/operating system
277 * detection in mw.util#init.
279 tooltipAccessKeyPrefix: 'alt-',
283 * Regex to match accesskey tooltips.
292 * The accesskey is matched in group $6.
294 tooltipAccessKeyRegexp: /\[(ctrl-)?(option-)?(alt-)?(shift-)?(esc-)?(.)\]$/,
297 * Add the appropriate prefix to the accesskey shown in the tooltip.
298 * If the nodeList parameter is given, only those nodes are updated;
299 * otherwise, all the nodes that will probably have accesskeys by
300 * default are updated.
302 * @param {Array|jQuery} [$nodes] A jQuery object, or array of nodes to update.
304 updateTooltipAccessKeys: function ( $nodes ) {
306 // Rather than going into a loop of all anchor tags, limit to few elements that
307 // contain the relevant anchor tags.
308 // Input and label are rare enough that no such optimization is needed
309 $nodes = $( '#column-one a, #mw-head a, #mw-panel a, #p-logo a, input, label' );
310 } else if ( !( $nodes instanceof $ ) ) {
311 $nodes = $( $nodes );
314 $nodes.attr( 'title', function ( i, val ) {
315 if ( val && util.tooltipAccessKeyRegexp.test( val ) ) {
316 return val.replace( util.tooltipAccessKeyRegexp,
317 '[' + util.tooltipAccessKeyPrefix + '$6]' );
325 * A jQuery object that refers to the content area element.
326 * Populated by #init.
331 * Add a link to a portlet menu on the page, such as:
333 * p-cactions (Content actions), p-personal (Personal tools),
334 * p-navigation (Navigation), p-tb (Toolbox)
336 * The first three paramters are required, the others are optional and
337 * may be null. Though providing an id and tooltip is recommended.
339 * By default the new link will be added to the end of the list. To
340 * add the link before a given existing item, pass the DOM node
341 * (e.g. `document.getElementById( 'foobar' )`) or a jQuery-selector
342 * (e.g. `'#foobar'`) for that item.
344 * mw.util.addPortletLink(
345 * 'p-tb', 'http://mediawiki.org/',
346 * 'MediaWiki.org', 't-mworg', 'Go to MediaWiki.org ', 'm', '#t-print'
349 * @param {string} portlet ID of the target portlet ( 'p-cactions' or 'p-personal' etc.)
350 * @param {string} href Link URL
351 * @param {string} text Link text
352 * @param {string} [id] ID of the new item, should be unique and preferably have
353 * the appropriate prefix ( 'ca-', 'pt-', 'n-' or 't-' )
354 * @param {string} [tooltip] Text to show when hovering over the link, without accesskey suffix
355 * @param {string} [accesskey] Access key to activate this link (one character, try
356 * to avoid conflicts. Use `$( '[accesskey=x]' ).get()` in the console to
357 * see if 'x' is already used.
358 * @param {HTMLElement|jQuery|string} [nextnode] Element or jQuery-selector string to the item that
359 * the new item should be added before, should be another item in the same
360 * list, it will be ignored otherwise
362 * @return {HTMLElement|null} The added element (a ListItem or Anchor element,
363 * depending on the skin) or null if no element was added to the document.
365 addPortletLink: function ( portlet, href, text, id, tooltip, accesskey, nextnode ) {
366 var $item, $link, $portlet, $ul;
368 // Check if there's atleast 3 arguments to prevent a TypeError
369 if ( arguments.length < 3 ) {
372 // Setup the anchor tag
373 $link = $( '<a>' ).attr( 'href', href ).text( text );
375 $link.attr( 'title', tooltip );
378 // Select the specified portlet
379 $portlet = $( '#' + portlet );
380 if ( $portlet.length === 0 ) {
383 // Select the first (most likely only) unordered list inside the portlet
384 $ul = $portlet.find( 'ul' ).eq( 0 );
386 // If it didn't have an unordered list yet, create it
387 if ( $ul.length === 0 ) {
391 // If there's no <div> inside, append it to the portlet directly
392 if ( $portlet.find( 'div:first' ).length === 0 ) {
393 $portlet.append( $ul );
395 // otherwise if there's a div (such as div.body or div.pBody)
396 // append the <ul> to last (most likely only) div
397 $portlet.find( 'div' ).eq( -1 ).append( $ul );
401 if ( $ul.length === 0 ) {
405 // Unhide portlet if it was hidden before
406 $portlet.removeClass( 'emptyPortlet' );
408 // Wrap the anchor tag in a list item (and a span if $portlet is a Vector tab)
409 // and back up the selector to the list item
410 if ( $portlet.hasClass( 'vectorTabs' ) ) {
411 $item = $link.wrap( '<li><span></span></li>' ).parent().parent();
413 $item = $link.wrap( '<li></li>' ).parent();
416 // Implement the properties passed to the function
418 $item.attr( 'id', id );
422 // Trim any existing accesskey hint and the trailing space
423 tooltip = $.trim( tooltip.replace( util.tooltipAccessKeyRegexp, '' ) );
425 tooltip += ' [' + accesskey + ']';
427 $link.attr( 'title', tooltip );
429 util.updateTooltipAccessKeys( $link );
434 $link.attr( 'accesskey', accesskey );
437 // Where to put our node ?
438 // - nextnode is a DOM element (was the only option before MW 1.17, in wikibits.js)
439 if ( nextnode && nextnode.parentNode === $ul[0] ) {
440 $( nextnode ).before( $item );
442 // - nextnode is a CSS selector for jQuery
443 } else if ( typeof nextnode === 'string' && $ul.find( nextnode ).length !== 0 ) {
444 $ul.find( nextnode ).eq( 0 ).before( $item );
446 // If the jQuery selector isn't found within the <ul>,
447 // or if nextnode was invalid or not passed at all,
448 // then just append it at the end of the <ul> (this is the default behavior)
457 * Add a little box at the top of the screen to inform the user of
458 * something, replacing any previous message.
459 * Calling with no arguments, with an empty string or null will hide the message
461 * @param {Mixed} message The DOM-element, jQuery object or HTML-string to be put inside the message box.
462 * to allow CSS/JS to hide different boxes. null = no class used.
463 * @deprecated Use mw#notify
465 jsMessage: function ( message ) {
466 if ( !arguments.length || message === '' || message === null ) {
469 if ( typeof message !== 'object' ) {
470 message = $.parseHTML( message );
472 mw.notify( message, { autoHide: true, tag: 'legacy' } );
477 * Validate a string as representing a valid e-mail address
478 * according to HTML5 specification. Please note the specification
479 * does not validate a domain with one character.
481 * FIXME: should be moved to or replaced by a validation module.
483 * @param {string} mailtxt E-mail address to be validated.
484 * @return {boolean|null} Null if `mailtxt` was an empty string, otherwise true/false
485 * as determined by validation.
487 validateEmail: function ( mailtxt ) {
488 var rfc5322Atext, rfc1034LdhStr, html5EmailRegexp;
490 if ( mailtxt === '' ) {
494 // HTML5 defines a string as valid e-mail address if it matches
496 // 1 * ( atext / "." ) "@" ldh-str 1*( "." ldh-str )
498 // - atext : defined in RFC 5322 section 3.2.3
499 // - ldh-str : defined in RFC 1034 section 3.5
501 // (see STD 68 / RFC 5234 http://tools.ietf.org/html/std68)
502 // First, define the RFC 5322 'atext' which is pretty easy:
503 // atext = ALPHA / DIGIT / ; Printable US-ASCII
504 // "!" / "#" / ; characters not including
505 // "$" / "%" / ; specials. Used for atoms.
514 rfc5322Atext = 'a-z0-9!#$%&\'*+\\-/=?^_`{|}~';
516 // Next define the RFC 1034 'ldh-str'
517 // <domain> ::= <subdomain> | " "
518 // <subdomain> ::= <label> | <subdomain> "." <label>
519 // <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
520 // <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
521 // <let-dig-hyp> ::= <let-dig> | "-"
522 // <let-dig> ::= <letter> | <digit>
523 rfc1034LdhStr = 'a-z0-9\\-';
525 html5EmailRegexp = new RegExp(
529 // User part which is liberal :p
530 '[' + rfc5322Atext + '\\.]+'
536 '[' + rfc1034LdhStr + ']+'
538 // Optional second part and following are separated by a dot
539 '(?:\\.[' + rfc1034LdhStr + ']+)*'
543 // RegExp is case insensitive
546 return (null !== mailtxt.match( html5EmailRegexp ) );
550 * Note: borrows from IP::isIPv4
552 * @param {string} address
553 * @param {boolean} allowBlock
556 isIPv4Address: function ( address, allowBlock ) {
557 if ( typeof address !== 'string' ) {
561 var block = allowBlock ? '(?:\\/(?:3[0-2]|[12]?\\d))?' : '',
562 RE_IP_BYTE = '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])',
563 RE_IP_ADD = '(?:' + RE_IP_BYTE + '\\.){3}' + RE_IP_BYTE;
565 return address.search( new RegExp( '^' + RE_IP_ADD + block + '$' ) ) !== -1;
569 * Note: borrows from IP::isIPv6
571 * @param {string} address
572 * @param {boolean} allowBlock
575 isIPv6Address: function ( address, allowBlock ) {
576 if ( typeof address !== 'string' ) {
580 var block = allowBlock ? '(?:\\/(?:12[0-8]|1[01][0-9]|[1-9]?\\d))?' : '',
582 '(?:' + // starts with "::" (including "::")
583 ':(?::|(?::' + '[0-9A-Fa-f]{1,4}' + '){1,7})' +
584 '|' + // ends with "::" (except "::")
585 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){0,6}::' +
586 '|' + // contains no "::"
587 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){7}' +
590 if ( address.search( new RegExp( '^' + RE_IPV6_ADD + block + '$' ) ) !== -1 ) {
594 RE_IPV6_ADD = // contains one "::" in the middle (single '::' check below)
595 '[0-9A-Fa-f]{1,4}' + '(?:::?' + '[0-9A-Fa-f]{1,4}' + '){1,6}';
597 return address.search( new RegExp( '^' + RE_IPV6_ADD + block + '$' ) ) !== -1
598 && address.search( /::/ ) !== -1 && address.search( /::.*::/ ) === -1;
604 }( mediaWiki, jQuery ) );