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' ) {
33 util
.tooltipAccessKeyPrefix
= (
34 profile
.platform
=== 'mac'
37 : profile
.platform
=== 'win'
39 // (both alt- and alt-shift work, but alt-f triggers Chrome wrench menu
40 // which alt-shift-f does not)
42 // Chrome on other (Ubuntu?)
46 // Non-Windows Safari with webkit_version > 526
47 } else if ( profile
.platform
!== 'win'
48 && profile
.name
=== 'safari'
49 && profile
.layoutVersion
> 526 ) {
50 util
.tooltipAccessKeyPrefix
= 'ctrl-alt-';
52 // Safari/Konqueror on any platform, or any browser on Mac
53 // (but not Safari on Windows)
54 } else if ( !( profile
.platform
=== 'win' && profile
.name
=== 'safari' )
55 && ( profile
.name
=== 'safari'
56 || profile
.platform
=== 'mac'
57 || profile
.name
=== 'konqueror' ) ) {
58 util
.tooltipAccessKeyPrefix
= 'ctrl-';
60 // Firefox 2.x and later
61 } else if ( profile
.name
=== 'firefox' && profile
.versionBase
> '1' ) {
62 util
.tooltipAccessKeyPrefix
= 'alt-shift-';
65 /* Fill $content var */
66 if ( $( '#bodyContent' ).length
) {
67 // Vector, Monobook, Chick etc.
68 util
.$content
= $( '#bodyContent' );
70 } else if ( $( '#mw_contentholder' ).length
) {
72 util
.$content
= $( '#mw_contentholder' );
74 } else if ( $( '#article' ).length
) {
75 // Standard, CologneBlue
76 util
.$content
= $( '#article' );
79 // #content is present on almost all if not all skins. Most skins (the above cases)
80 // have #content too, but as an outer wrapper instead of the article text container.
81 // The skins that don't have an outer wrapper do have #content for everything
82 // so it's a good fallback
83 util
.$content
= $( '#content' );
86 // Table of contents toggle
87 $tocTitle
= $( '#toctitle' );
88 $tocToggleLink
= $( '#togglelink' );
89 // Only add it if there is a TOC and there is no toggle added already
90 if ( $( '#toc' ).length
&& $tocTitle
.length
&& !$tocToggleLink
.length
) {
91 hideTocCookie
= $.cookie( 'mw_hidetoc' );
92 $tocToggleLink
= $( '<a href="#" class="internal" id="togglelink"></a>' )
93 .text( mw
.msg( 'hidetoc' ) )
94 .click( function ( e
) {
96 util
.toggleToc( $(this) );
100 .wrap( '<span class="toctoggle"></span>' )
102 .prepend( ' [' )
106 if ( hideTocCookie
=== '1' ) {
107 util
.toggleToc( $tocToggleLink
);
115 * Encode the string like PHP's rawurlencode
117 * @param str string String to be encoded
119 rawurlencode: function ( str
) {
121 return encodeURIComponent( str
)
122 .replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' )
123 .replace( /\)/g, '%29' ).replace( /\*/g, '%2A
' ).replace( /~/g, '%7E
' );
127 * Encode page titles for use in a URL
128 * We want / and : to be included as literal characters in our title URLs
129 * as they otherwise fatally break the title
131 * @param str string String to be encoded
133 wikiUrlencode: function ( str ) {
134 return util.rawurlencode( str )
135 .replace( /%20/g, '_
' ).replace( /%3A/g, ':' ).replace( /%2F/g, '/' );
139 * Get the link to a page name (relative to wgServer)
141 * @param str String: Page name to get the link for.
142 * @return String: Location for a page with name of 'str
' or boolean false on error.
144 wikiGetlink: function ( str ) {
145 return mw.config.get( 'wgArticlePath
' ).replace( '$1',
146 util.wikiUrlencode( typeof str === 'string
' ? str : mw.config.get( 'wgPageName
' ) ) );
150 * Get address to a script in the wiki root.
151 * For index.php use mw.config.get( 'wgScript
' )
154 * @param str string Name of script (eg. 'api
'), defaults to 'index
'
155 * @return string Address to script (eg. '/w
/api
.php
' )
157 wikiScript: function ( str ) {
158 return mw.config.get( 'wgScriptPath
' ) + '/' + ( str || 'index
' ) +
159 mw.config.get( 'wgScriptExtension
' );
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).
169 * var sheet = mw.util.addCSS('.foobar
{ display
: none
; }');
170 * $(foo).click(function () {
171 * // Toggle the sheet on and off
172 * sheet.disabled = !sheet.disabled;
176 * @param text string CSS to be appended
177 * @return CSSStyleSheet (use .ownerNode to get to the <style> element)
179 addCSS: function ( text ) {
180 var s = mw.loader.addStyleTag( text );
185 * Hide/show the table of contents element
187 * @param $toggleLink jQuery A jQuery object of the toggle link.
188 * @param callback function Function to be called after the toggle is
189 * completed (including the animation) (optional)
190 * @return mixed Boolean visibility of the toc (true if it's visible
)
191 * or Null
if there was no table
of contents
.
193 toggleToc: function ( $toggleLink
, callback
) {
194 var $tocList
= $( '#toc ul:first' );
196 // This function shouldn't be called if there's no TOC,
197 // but just in case...
198 if ( $tocList
.length
) {
199 if ( $tocList
.is( ':hidden' ) ) {
200 $tocList
.slideDown( 'fast', callback
);
201 $toggleLink
.text( mw
.msg( 'hidetoc' ) );
202 $( '#toc' ).removeClass( 'tochidden' );
203 $.cookie( 'mw_hidetoc', null, {
209 $tocList
.slideUp( 'fast', callback
);
210 $toggleLink
.text( mw
.msg( 'showtoc' ) );
211 $( '#toc' ).addClass( 'tochidden' );
212 $.cookie( 'mw_hidetoc', '1', {
224 * Grab the URL parameter value for the given parameter.
225 * Returns null if not found.
227 * @param param string The parameter name.
228 * @param url string URL to search through (optional)
229 * @return mixed Parameter value or null.
231 getParamValue: function ( param
, url
) {
232 url
= url
|| document
.location
.href
;
233 // Get last match, stop at hash
234 var re
= new RegExp( '^[^#]*[&?]' + $.escapeRE( param
) + '=([^&#]*)' ),
237 // Beware that decodeURIComponent is not required to understand '+'
238 // by spec, as encodeURIComponent does not produce it.
239 return decodeURIComponent( m
[1].replace( /\+/g, '%20' ) );
246 * Access key prefix. Will be re-defined based on browser/operating system
247 * detection in mw.util.init().
249 tooltipAccessKeyPrefix
: 'alt-',
253 * Regex to match accesskey tooltips.
255 tooltipAccessKeyRegexp
: /\[(ctrl-)?(alt-)?(shift-)?(esc-)?(.)\]$/,
258 * Add the appropriate prefix to the accesskey shown in the tooltip.
259 * If the nodeList parameter is given, only those nodes are updated;
260 * otherwise, all the nodes that will probably have accesskeys by
261 * default are updated.
263 * @param $nodes {Array|jQuery} [optional] A jQuery object, or array
264 * of elements to update.
266 updateTooltipAccessKeys: function ( $nodes
) {
268 // Rather than going into a loop of all anchor tags, limit to few elements that
269 // contain the relevant anchor tags.
270 // Input and label are rare enough that no such optimization is needed
271 $nodes
= $( '#column-one a, #mw-head a, #mw-panel a, #p-logo a, input, label' );
272 } else if ( !( $nodes
instanceof $ ) ) {
273 $nodes
= $( $nodes
);
276 $nodes
.attr( 'title', function ( i
, val
) {
277 if ( val
&& util
.tooltipAccessKeyRegexp
.exec( val
) ) {
278 return val
.replace( util
.tooltipAccessKeyRegexp
,
279 '[' + util
.tooltipAccessKeyPrefix
+ '$5]' );
287 * A jQuery object that refers to the page-content element
288 * Populated by init().
293 * Add a link to a portlet menu on the page, such as:
295 * p-cactions (Content actions), p-personal (Personal tools),
296 * p-navigation (Navigation), p-tb (Toolbox)
298 * The first three paramters are required, the others are optional and
299 * may be null. Though providing an id and tooltip is recommended.
301 * By default the new link will be added to the end of the list. To
302 * add the link before a given existing item, pass the DOM node
303 * (document.getElementById( 'foobar' )) or the jQuery-selector
304 * ( '#foobar' ) of that item.
306 * @example mw.util.addPortletLink(
307 * 'p-tb', 'http://mediawiki.org/',
308 * 'MediaWiki.org', 't-mworg', 'Go to MediaWiki.org ', 'm', '#t-print'
311 * @param portlet string ID of the target portlet ( 'p-cactions' or 'p-personal' etc.)
312 * @param href string Link URL
313 * @param text string Link text
314 * @param id string ID of the new item, should be unique and preferably have
315 * the appropriate prefix ( 'ca-', 'pt-', 'n-' or 't-' )
316 * @param tooltip string Text to show when hovering over the link, without accesskey suffix
317 * @param accesskey string Access key to activate this link (one character, try
318 * to avoid conflicts. Use $( '[accesskey=x]' ).get() in the console to
319 * see if 'x' is already used.
320 * @param nextnode mixed DOM Node or jQuery-selector string of the item that the new
321 * item should be added before, should be another item in the same
322 * list, it will be ignored otherwise
324 * @return mixed The DOM Node of the added item (a ListItem or Anchor element,
325 * depending on the skin) or null if no element was added to the document.
327 addPortletLink: function ( portlet
, href
, text
, id
, tooltip
, accesskey
, nextnode
) {
328 var $item
, $link
, $portlet
, $ul
;
330 // Check if there's atleast 3 arguments to prevent a TypeError
331 if ( arguments
.length
< 3 ) {
334 // Setup the anchor tag
335 $link
= $( '<a>' ).attr( 'href', href
).text( text
);
337 $link
.attr( 'title', tooltip
);
340 // Some skins don't have any portlets
341 // just add it to the bottom of their 'sidebar' element as a fallback
342 switch ( mw
.config
.get( 'skin' ) ) {
345 $( '#quickbar' ).append( $link
.after( '<br/>' ) );
348 $( '#searchform' ).before( $link
).before( ' | ' );
350 default: // Skins like chick, modern, monobook, myskin, simple, vector...
352 // Select the specified portlet
353 $portlet
= $( '#' + portlet
);
354 if ( $portlet
.length
=== 0 ) {
357 // Select the first (most likely only) unordered list inside the portlet
358 $ul
= $portlet
.find( 'ul' ).eq( 0 );
360 // If it didn't have an unordered list yet, create it
361 if ( $ul
.length
=== 0 ) {
365 // If there's no <div> inside, append it to the portlet directly
366 if ( $portlet
.find( 'div:first' ).length
=== 0 ) {
367 $portlet
.append( $ul
);
369 // otherwise if there's a div (such as div.body or div.pBody)
370 // append the <ul> to last (most likely only) div
371 $portlet
.find( 'div' ).eq( -1 ).append( $ul
);
375 if ( $ul
.length
=== 0 ) {
379 // Unhide portlet if it was hidden before
380 $portlet
.removeClass( 'emptyPortlet' );
382 // Wrap the anchor tag in a list item (and a span if $portlet is a Vector tab)
383 // and back up the selector to the list item
384 if ( $portlet
.hasClass( 'vectorTabs' ) ) {
385 $item
= $link
.wrap( '<li><span></span></li>' ).parent().parent();
387 $item
= $link
.wrap( '<li></li>' ).parent();
390 // Implement the properties passed to the function
392 $item
.attr( 'id', id
);
395 $link
.attr( 'accesskey', accesskey
);
396 tooltip
+= ' [' + accesskey
+ ']';
397 $link
.attr( 'title', tooltip
);
399 if ( accesskey
&& tooltip
) {
400 util
.updateTooltipAccessKeys( $link
);
403 // Where to put our node ?
404 // - nextnode is a DOM element (was the only option before MW 1.17, in wikibits.js)
405 if ( nextnode
&& nextnode
.parentNode
=== $ul
[0] ) {
406 $(nextnode
).before( $item
);
408 // - nextnode is a CSS selector for jQuery
409 } else if ( typeof nextnode
=== 'string' && $ul
.find( nextnode
).length
!== 0 ) {
410 $ul
.find( nextnode
).eq( 0 ).before( $item
);
412 // If the jQuery selector isn't found within the <ul>,
413 // or if nextnode was invalid or not passed at all,
414 // then just append it at the end of the <ul> (this is the default behaviour)
425 * Add a little box at the top of the screen to inform the user of
426 * something, replacing any previous message.
427 * Calling with no arguments, with an empty string or null will hide the message
429 * @param message {mixed} The DOM-element, jQuery object or HTML-string to be put inside the message box.
430 * @param className {String} Used in adding a class; should be different for each call
431 * to allow CSS/JS to hide different boxes. null = no class used.
432 * @return {Boolean} True on success, false on failure.
434 jsMessage: function ( message
, className
) {
435 if ( !arguments
.length
|| message
=== '' || message
=== null ) {
436 $( '#mw-js-message' ).empty().hide();
437 return true; // Emptying and hiding message is intended behaviour, return true
440 // We special-case skin structures provided by the software. Skins that
441 // choose to abandon or significantly modify our formatting can just define
442 // an mw-js-message div to start with.
443 var $messageDiv
= $( '#mw-js-message' );
444 if ( !$messageDiv
.length
) {
445 $messageDiv
= $( '<div id="mw-js-message"></div>' );
446 if ( util
.$content
.parent().length
) {
447 util
.$content
.parent().prepend( $messageDiv
);
454 $messageDiv
.prop( 'class', 'mw-js-message-' + className
);
457 if ( typeof message
=== 'object' ) {
459 $messageDiv
.append( message
);
461 $messageDiv
.html( message
);
464 $messageDiv
.slideDown();
470 * Validate a string as representing a valid e-mail address
471 * according to HTML5 specification. Please note the specification
472 * does not validate a domain with one character.
474 * @todo FIXME: should be moved to or replaced by a JavaScript validation module.
476 * @param mailtxt string E-mail address to be validated.
477 * @return mixed Null if mailtxt was an empty string, otherwise true/false
478 * is determined by validation.
480 validateEmail: function ( mailtxt
) {
481 var rfc5322_atext
, rfc1034_ldh_str
, HTML5_email_regexp
;
483 if ( mailtxt
=== '' ) {
488 * HTML5 defines a string as valid e-mail address if it matches
490 * 1 * ( atext / "." ) "@" ldh-str 1*( "." ldh-str )
492 * - atext : defined in RFC 5322 section 3.2.3
493 * - ldh-str : defined in RFC 1034 section 3.5
495 * (see STD 68 / RFC 5234 http://tools.ietf.org/html/std68):
499 * First, define the RFC 5322 'atext' which is pretty easy:
500 * atext = ALPHA / DIGIT / ; Printable US-ASCII
501 "!" / "#" / ; characters not including
502 "$" / "%" / ; specials. Used for atoms.
512 rfc5322_atext
= "a-z0-9!#$%&'*+\\-/=?^_`{|}~";
515 * Next define the RFC 1034 'ldh-str'
516 * <domain> ::= <subdomain> | " "
517 * <subdomain> ::= <label> | <subdomain> "." <label>
518 * <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
519 * <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
520 * <let-dig-hyp> ::= <let-dig> | "-"
521 * <let-dig> ::= <letter> | <digit>
523 rfc1034_ldh_str
= "a-z0-9\\-";
525 HTML5_email_regexp
= new RegExp(
529 // User part which is liberal :p
530 '[' + rfc5322_atext
+ '\\.]+'
536 '[' + rfc1034_ldh_str
+ ']+'
538 // Optional second part and following are separated by a dot
539 '(?:\\.[' + rfc1034_ldh_str
+ ']+)*'
543 // RegExp is case insensitive
546 return (null !== mailtxt
.match( HTML5_email_regexp
) );
550 * Note: borrows from IP::isIPv4
552 * @param address string
553 * @param allowBlock boolean
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 address string
572 * @param allowBlock boolean
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 } )( jQuery
, mediaWiki
);