2 * Implements mediaWiki.util library
7 // Local cache and alias
12 * (don't call before document ready)
15 var profile
, $tocTitle
, $tocToggleLink
, hideTocCookie
;
17 /* Set up $.messageBox */
23 /* Set tooltipAccessKeyPrefix */
24 profile
= $.client
.profile();
26 // Opera on any platform
27 if ( profile
.name
=== 'opera' ) {
28 util
.tooltipAccessKeyPrefix
= 'shift-esc-';
30 // Chrome on any platform
31 } else if ( profile
.name
=== 'chrome' ) {
32 // Chrome on Mac or Chrome on other platform ?
33 util
.tooltipAccessKeyPrefix
= ( profile
.platform
=== 'mac'
34 ? 'ctrl-option-' : 'alt-' );
36 // Non-Windows Safari with webkit_version > 526
37 } else if ( profile
.platform
!== 'win'
38 && profile
.name
=== 'safari'
39 && profile
.layoutVersion
> 526 ) {
40 util
.tooltipAccessKeyPrefix
= 'ctrl-alt-';
42 // Safari/Konqueror on any platform, or any browser on Mac
43 // (but not Safari on Windows)
44 } else if ( !( profile
.platform
=== 'win' && profile
.name
=== 'safari' )
45 && ( profile
.name
=== 'safari'
46 || profile
.platform
=== 'mac'
47 || profile
.name
=== 'konqueror' ) ) {
48 util
.tooltipAccessKeyPrefix
= 'ctrl-';
50 // Firefox 2.x and later
51 } else if ( profile
.name
=== 'firefox' && profile
.versionBase
> '1' ) {
52 util
.tooltipAccessKeyPrefix
= 'alt-shift-';
55 /* Fill $content var */
56 if ( $( '#bodyContent' ).length
) {
57 // Vector, Monobook, Chick etc.
58 util
.$content
= $( '#bodyContent' );
60 } else if ( $( '#mw_contentholder' ).length
) {
62 util
.$content
= $( '#mw_contentholder' );
64 } else if ( $( '#article' ).length
) {
65 // Standard, CologneBlue
66 util
.$content
= $( '#article' );
69 // #content is present on almost all if not all skins. Most skins (the above cases)
70 // have #content too, but as an outer wrapper instead of the article text container.
71 // The skins that don't have an outer wrapper do have #content for everything
72 // so it's a good fallback
73 util
.$content
= $( '#content' );
76 // Table of contents toggle
77 $tocTitle
= $( '#toctitle' );
78 $tocToggleLink
= $( '#togglelink' );
79 // Only add it if there is a TOC and there is no toggle added already
80 if ( $( '#toc' ).length
&& $tocTitle
.length
&& !$tocToggleLink
.length
) {
81 hideTocCookie
= $.cookie( 'mw_hidetoc' );
82 $tocToggleLink
= $( '<a href="#" class="internal" id="togglelink"></a>' )
83 .text( mw
.msg( 'hidetoc' ) )
84 .click( function ( e
) {
86 util
.toggleToc( $(this) );
90 .wrap( '<span class="toctoggle"></span>' )
96 if ( hideTocCookie
=== '1' ) {
97 util
.toggleToc( $tocToggleLink
);
105 * Encode the string like PHP's rawurlencode
107 * @param str string String to be encoded
109 rawurlencode: function ( str
) {
111 return encodeURIComponent( str
)
112 .replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' )
113 .replace( /\)/g, '%29' ).replace( /\*/g, '%2A
' ).replace( /~/g, '%7E
' );
117 * Encode page titles for use in a URL
118 * We want / and : to be included as literal characters in our title URLs
119 * as they otherwise fatally break the title
121 * @param str string String to be encoded
123 wikiUrlencode: function ( str ) {
124 return util.rawurlencode( str )
125 .replace( /%20/g, '_
' ).replace( /%3A/g, ':' ).replace( /%2F/g, '/' );
129 * Get the link to a page name (relative to wgServer)
131 * @param str String: Page name to get the link for.
132 * @return String: Location for a page with name of 'str
' or boolean false on error.
134 wikiGetlink: function ( str ) {
135 return mw.config.get( 'wgArticlePath
' ).replace( '$1',
136 util.wikiUrlencode( typeof str === 'string
' ? str : mw.config.get( 'wgPageName
' ) ) );
140 * Get address to a script in the wiki root.
141 * For index.php use mw.config.get( 'wgScript
' )
143 * @param str string Name of script (eg. 'api
'), defaults to 'index
'
144 * @return string Address to script (eg. '/w
/api
.php
' )
146 wikiScript: function ( str ) {
147 return mw.config.get( 'wgScriptPath
' ) + '/' + ( str || 'index
' ) +
148 mw.config.get( 'wgScriptExtension
' );
152 * Append a new style block to the head and return the CSSStyleSheet object.
153 * Use .ownerNode to access the <style> element, or use mw.loader.addStyleTag.
154 * This function returns the styleSheet object for convience (due to cross-browsers
155 * difference as to where it is located).
158 * var sheet = mw.util.addCSS('.foobar
{ display
: none
; }');
159 * $(foo).click(function () {
160 * // Toggle the sheet on and off
161 * sheet.disabled = !sheet.disabled;
165 * @param text string CSS to be appended
166 * @return CSSStyleSheet (use .ownerNode to get to the <style> element)
168 addCSS: function ( text ) {
169 var s = mw.loader.addStyleTag( text );
174 * Hide/show the table of contents element
176 * @param $toggleLink jQuery A jQuery object of the toggle link.
177 * @param callback function Function to be called after the toggle is
178 * completed (including the animation) (optional)
179 * @return mixed Boolean visibility of the toc (true if it's visible
)
180 * or Null
if there was no table
of contents
.
182 toggleToc: function ( $toggleLink
, callback
) {
183 var $tocList
= $( '#toc ul:first' );
185 // This function shouldn't be called if there's no TOC,
186 // but just in case...
187 if ( $tocList
.length
) {
188 if ( $tocList
.is( ':hidden' ) ) {
189 $tocList
.slideDown( 'fast', callback
);
190 $toggleLink
.text( mw
.msg( 'hidetoc' ) );
191 $( '#toc' ).removeClass( 'tochidden' );
192 $.cookie( 'mw_hidetoc', null, {
198 $tocList
.slideUp( 'fast', callback
);
199 $toggleLink
.text( mw
.msg( 'showtoc' ) );
200 $( '#toc' ).addClass( 'tochidden' );
201 $.cookie( 'mw_hidetoc', '1', {
213 * Grab the URL parameter value for the given parameter.
214 * Returns null if not found.
216 * @param param string The parameter name.
217 * @param url string URL to search through (optional)
218 * @return mixed Parameter value or null.
220 getParamValue: function ( param
, url
) {
221 url
= url
|| document
.location
.href
;
222 // Get last match, stop at hash
223 var re
= new RegExp( '^[^#]*[&?]' + $.escapeRE( param
) + '=([^&#]*)' ),
225 if ( m
&& m
.length
> 1 ) {
226 // Beware that decodeURIComponent is not required to understand '+'
227 // by spec, as encodeURIComponent does not produce it.
228 return decodeURIComponent( m
[1].replace( /\+/g, '%20' ) );
235 * Access key prefix. Will be re-defined based on browser/operating system
236 * detection in mw.util.init().
238 tooltipAccessKeyPrefix
: 'alt-',
242 * Regex to match accesskey tooltips.
244 tooltipAccessKeyRegexp
: /\[(ctrl-)?(alt-)?(shift-)?(esc-)?(.)\]$/,
247 * Add the appropriate prefix to the accesskey shown in the tooltip.
248 * If the nodeList parameter is given, only those nodes are updated;
249 * otherwise, all the nodes that will probably have accesskeys by
250 * default are updated.
252 * @param $nodes {Array|jQuery} [optional] A jQuery object, or array
253 * of elements to update.
255 updateTooltipAccessKeys: function ( $nodes
) {
257 // Rather than going into a loop of all anchor tags, limit to few elements that
258 // contain the relevant anchor tags.
259 // Input and label are rare enough that no such optimization is needed
260 $nodes
= $( '#column-one a, #mw-head a, #mw-panel a, #p-logo a, input, label' );
261 } else if ( !( $nodes
instanceof $ ) ) {
262 $nodes
= $( $nodes
);
265 $nodes
.attr( 'title', function ( i
, val
) {
266 if ( val
&& util
.tooltipAccessKeyRegexp
.exec( val
) ) {
267 return val
.replace( util
.tooltipAccessKeyRegexp
,
268 '[' + util
.tooltipAccessKeyPrefix
+ '$5]' );
276 * A jQuery object that refers to the page-content element
277 * Populated by init().
282 * Add a link to a portlet menu on the page, such as:
284 * p-cactions (Content actions), p-personal (Personal tools),
285 * p-navigation (Navigation), p-tb (Toolbox)
287 * The first three paramters are required, the others are optional and
288 * may be null. Though providing an id and tooltip is recommended.
290 * By default the new link will be added to the end of the list. To
291 * add the link before a given existing item, pass the DOM node
292 * (document.getElementById( 'foobar' )) or the jQuery-selector
293 * ( '#foobar' ) of that item.
295 * @example mw.util.addPortletLink(
296 * 'p-tb', 'http://mediawiki.org/',
297 * 'MediaWiki.org', 't-mworg', 'Go to MediaWiki.org ', 'm', '#t-print'
300 * @param portlet string ID of the target portlet ( 'p-cactions' or 'p-personal' etc.)
301 * @param href string Link URL
302 * @param text string Link text
303 * @param id string ID of the new item, should be unique and preferably have
304 * the appropriate prefix ( 'ca-', 'pt-', 'n-' or 't-' )
305 * @param tooltip string Text to show when hovering over the link, without accesskey suffix
306 * @param accesskey string Access key to activate this link (one character, try
307 * to avoid conflicts. Use $( '[accesskey=x]' ).get() in the console to
308 * see if 'x' is already used.
309 * @param nextnode mixed DOM Node or jQuery-selector string of the item that the new
310 * item should be added before, should be another item in the same
311 * list, it will be ignored otherwise
313 * @return mixed The DOM Node of the added item (a ListItem or Anchor element,
314 * depending on the skin) or null if no element was added to the document.
316 addPortletLink: function ( portlet
, href
, text
, id
, tooltip
, accesskey
, nextnode
) {
317 var $item
, $link
, $portlet
, $ul
;
319 // Check if there's atleast 3 arguments to prevent a TypeError
320 if ( arguments
.length
< 3 ) {
323 // Setup the anchor tag
324 $link
= $( '<a>' ).attr( 'href', href
).text( text
);
326 $link
.attr( 'title', tooltip
);
329 // Some skins don't have any portlets
330 // just add it to the bottom of their 'sidebar' element as a fallback
331 switch ( mw
.config
.get( 'skin' ) ) {
334 $( '#quickbar' ).append( $link
.after( '<br/>' ) );
337 $( '#searchform' ).before( $link
).before( ' | ' );
339 default: // Skins like chick, modern, monobook, myskin, simple, vector...
341 // Select the specified portlet
342 $portlet
= $( '#' + portlet
);
343 if ( $portlet
.length
=== 0 ) {
346 // Select the first (most likely only) unordered list inside the portlet
347 $ul
= $portlet
.find( 'ul' );
349 // If it didn't have an unordered list yet, create it
350 if ( $ul
.length
=== 0 ) {
351 // If there's no <div> inside, append it to the portlet directly
352 if ( $portlet
.find( 'div:first' ).length
=== 0 ) {
353 $portlet
.append( '<ul></ul>' );
355 // otherwise if there's a div (such as div.body or div.pBody)
356 // append the <ul> to last (most likely only) div
357 $portlet
.find( 'div' ).eq( -1 ).append( '<ul></ul>' );
359 // Select the created element
360 $ul
= $portlet
.find( 'ul' ).eq( 0 );
363 if ( $ul
.length
=== 0 ) {
367 // Unhide portlet if it was hidden before
368 $portlet
.removeClass( 'emptyPortlet' );
370 // Wrap the anchor tag in a list item (and a span if $portlet is a Vector tab)
371 // and back up the selector to the list item
372 if ( $portlet
.hasClass( 'vectorTabs' ) ) {
373 $item
= $link
.wrap( '<li><span></span></li>' ).parent().parent();
375 $item
= $link
.wrap( '<li></li>' ).parent();
378 // Implement the properties passed to the function
380 $item
.attr( 'id', id
);
383 $link
.attr( 'accesskey', accesskey
);
384 tooltip
+= ' [' + accesskey
+ ']';
385 $link
.attr( 'title', tooltip
);
387 if ( accesskey
&& tooltip
) {
388 util
.updateTooltipAccessKeys( $link
);
391 // Where to put our node ?
392 // - nextnode is a DOM element (was the only option before MW 1.17, in wikibits.js)
393 if ( nextnode
&& nextnode
.parentNode
=== $ul
[0] ) {
394 $(nextnode
).before( $item
);
396 // - nextnode is a CSS selector for jQuery
397 } else if ( typeof nextnode
=== 'string' && $ul
.find( nextnode
).length
!== 0 ) {
398 $ul
.find( nextnode
).eq( 0 ).before( $item
);
400 // If the jQuery selector isn't found within the <ul>,
401 // or if nextnode was invalid or not passed at all,
402 // then just append it at the end of the <ul> (this is the default behaviour)
413 * Add a little box at the top of the screen to inform the user of
414 * something, replacing any previous message.
415 * Calling with no arguments, with an empty string or null will hide the message
417 * @param message {mixed} The DOM-element, jQuery object or HTML-string to be put inside the message box.
418 * @param className {String} Used in adding a class; should be different for each call
419 * to allow CSS/JS to hide different boxes. null = no class used.
420 * @return {Boolean} True on success, false on failure.
422 jsMessage: function ( message
, className
) {
423 if ( !arguments
.length
|| message
=== '' || message
=== null ) {
424 $( '#mw-js-message' ).empty().hide();
425 return true; // Emptying and hiding message is intended behaviour, return true
428 // We special-case skin structures provided by the software. Skins that
429 // choose to abandon or significantly modify our formatting can just define
430 // an mw-js-message div to start with.
431 var $messageDiv
= $( '#mw-js-message' );
432 if ( !$messageDiv
.length
) {
433 $messageDiv
= $( '<div id="mw-js-message"></div>' );
434 if ( util
.$content
.parent().length
) {
435 util
.$content
.parent().prepend( $messageDiv
);
442 $messageDiv
.prop( 'class', 'mw-js-message-' + className
);
445 if ( typeof message
=== 'object' ) {
447 $messageDiv
.append( message
);
449 $messageDiv
.html( message
);
452 $messageDiv
.slideDown();
458 * Validate a string as representing a valid e-mail address
459 * according to HTML5 specification. Please note the specification
460 * does not validate a domain with one character.
462 * @todo FIXME: should be moved to or replaced by a JavaScript validation module.
464 * @param mailtxt string E-mail address to be validated.
465 * @return mixed Null if mailtxt was an empty string, otherwise true/false
466 * is determined by validation.
468 validateEmail: function ( mailtxt
) {
469 var rfc5322_atext
, rfc1034_ldh_str
, HTML5_email_regexp
;
471 if ( mailtxt
=== '' ) {
476 * HTML5 defines a string as valid e-mail address if it matches
478 * 1 * ( atext / "." ) "@" ldh-str 1*( "." ldh-str )
480 * - atext : defined in RFC 5322 section 3.2.3
481 * - ldh-str : defined in RFC 1034 section 3.5
483 * (see STD 68 / RFC 5234 http://tools.ietf.org/html/std68):
487 * First, define the RFC 5322 'atext' which is pretty easy:
488 * atext = ALPHA / DIGIT / ; Printable US-ASCII
489 "!" / "#" / ; characters not including
490 "$" / "%" / ; specials. Used for atoms.
500 rfc5322_atext
= "a-z0-9!#$%&'*+\\-/=?^_`{|}~";
503 * Next define the RFC 1034 'ldh-str'
504 * <domain> ::= <subdomain> | " "
505 * <subdomain> ::= <label> | <subdomain> "." <label>
506 * <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
507 * <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
508 * <let-dig-hyp> ::= <let-dig> | "-"
509 * <let-dig> ::= <letter> | <digit>
511 rfc1034_ldh_str
= "a-z0-9\\-";
513 HTML5_email_regexp
= new RegExp(
517 // User part which is liberal :p
518 '[' + rfc5322_atext
+ '\\.]+'
524 '[' + rfc1034_ldh_str
+ ']+'
526 // Optional second part and following are separated by a dot
527 '(?:\\.[' + rfc1034_ldh_str
+ ']+)*'
531 // RegExp is case insensitive
534 return (null !== mailtxt
.match( HTML5_email_regexp
) );
538 * Note: borrows from IP::isIPv4
540 * @param address string
541 * @param allowBlock boolean
544 isIPv4Address: function ( address
, allowBlock
) {
545 if ( typeof address
!== 'string' ) {
549 var block
= allowBlock
? '(?:\\/(?:3[0-2]|[12]?\\d))?' : '',
550 RE_IP_BYTE
= '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])',
551 RE_IP_ADD
= '(?:' + RE_IP_BYTE
+ '\\.){3}' + RE_IP_BYTE
;
553 return address
.search( new RegExp( '^' + RE_IP_ADD
+ block
+ '$' ) ) !== -1;
557 * Note: borrows from IP::isIPv6
559 * @param address string
560 * @param allowBlock boolean
563 isIPv6Address: function ( address
, allowBlock
) {
564 if ( typeof address
!== 'string' ) {
568 var block
= allowBlock
? '(?:\\/(?:12[0-8]|1[01][0-9]|[1-9]?\\d))?' : '',
570 '(?:' + // starts with "::" (including "::")
571 ':(?::|(?::' + '[0-9A-Fa-f]{1,4}' + '){1,7})' +
572 '|' + // ends with "::" (except "::")
573 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){0,6}::' +
574 '|' + // contains no "::"
575 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){7}' +
578 if ( address
.search( new RegExp( '^' + RE_IPV6_ADD
+ block
+ '$' ) ) !== -1 ) {
582 RE_IPV6_ADD
= // contains one "::" in the middle (single '::' check below)
583 '[0-9A-Fa-f]{1,4}' + '(?:::?' + '[0-9A-Fa-f]{1,4}' + '){1,6}';
585 return address
.search( new RegExp( '^' + RE_IPV6_ADD
+ block
+ '$' ) ) !== -1
586 && address
.search( /::/ ) !== -1 && address
.search( /::.*::/ ) === -1;
592 } )( jQuery
, mediaWiki
);