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 tooltipAccessKeyPrefix */
18 profile
= $.client
.profile();
20 // Opera on any platform
21 if ( profile
.name
=== 'opera' ) {
22 util
.tooltipAccessKeyPrefix
= 'shift-esc-';
24 // Chrome on any platform
25 } else if ( profile
.name
=== 'chrome' ) {
27 util
.tooltipAccessKeyPrefix
= (
28 profile
.platform
=== 'mac'
31 // Chrome on Windows or Linux
32 // (both alt- and alt-shift work, but alt with E, D, F etc does not
33 // work since they are browser shortcuts)
37 // Non-Windows Safari with webkit_version > 526
38 } else if ( profile
.platform
!== 'win'
39 && profile
.name
=== 'safari'
40 && profile
.layoutVersion
> 526 ) {
41 util
.tooltipAccessKeyPrefix
= 'ctrl-alt-';
43 } else if ( profile
.platform
=== 'mac'
44 && profile
.name
=== 'firefox'
45 && profile
.versionNumber
>= 14 ) {
46 util
.tooltipAccessKeyPrefix
= 'ctrl-option-';
47 // Safari/Konqueror on any platform, or any browser on Mac
48 // (but not Safari on Windows)
49 } else if ( !( profile
.platform
=== 'win' && profile
.name
=== 'safari' )
50 && ( profile
.name
=== 'safari'
51 || profile
.platform
=== 'mac'
52 || profile
.name
=== 'konqueror' ) ) {
53 util
.tooltipAccessKeyPrefix
= 'ctrl-';
55 // Firefox 2.x and later
56 } else if ( profile
.name
=== 'firefox' && profile
.versionBase
> '1' ) {
57 util
.tooltipAccessKeyPrefix
= 'alt-shift-';
60 /* Fill $content var */
61 util
.$content
= ( function () {
62 var i
, l
, $content
, selectors
;
64 // The preferred standard for setting $content (class="mw-body")
65 // You may also use (class="mw-body mw-body-primary") if you use
66 // mw-body in multiple locations.
67 // Or class="mw-body-primary" if you want $content to be deeper
68 // in the dom than mw-body
72 /* Legacy fallbacks for setting the content */
73 // Vector, Monobook, Chick, etc... based skins
79 // Standard, CologneBlue
82 // #content is present on almost all if not all skins. Most skins (the above cases)
83 // have #content too, but as an outer wrapper instead of the article text container.
84 // The skins that don't have an outer wrapper do have #content for everything
85 // so it's a good fallback
88 // If nothing better is found fall back to our bodytext div that is guaranteed to be here
91 // Should never happen... well, it could if someone is not finished writing a skin and has
92 // not inserted bodytext yet. But in any case <body> should always exist
95 for ( i
= 0, l
= selectors
.length
; i
< l
; i
++ ) {
96 $content
= $( selectors
[i
] ).first();
97 if ( $content
.length
) {
102 // Make sure we don't unset util.$content if it was preset and we don't find anything
103 return util
.$content
;
106 // Table of contents toggle
107 $tocTitle
= $( '#toctitle' );
108 $tocToggleLink
= $( '#togglelink' );
109 // Only add it if there is a TOC and there is no toggle added already
110 if ( $( '#toc' ).length
&& $tocTitle
.length
&& !$tocToggleLink
.length
) {
111 hideTocCookie
= $.cookie( 'mw_hidetoc' );
112 $tocToggleLink
= $( '<a href="#" class="internal" id="togglelink"></a>' )
113 .text( mw
.msg( 'hidetoc' ) )
114 .click( function ( e
) {
116 util
.toggleToc( $(this) );
120 .wrap( '<span class="toctoggle"></span>' )
122 .prepend( ' [' )
126 if ( hideTocCookie
=== '1' ) {
127 util
.toggleToc( $tocToggleLink
);
135 * Encode the string like PHP's rawurlencode
137 * @param str string String to be encoded
139 rawurlencode: function ( str
) {
141 return encodeURIComponent( str
)
142 .replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' )
143 .replace( /\)/g, '%29' ).replace( /\*/g, '%2A
' ).replace( /~/g, '%7E
' );
147 * Encode page titles for use in a URL
148 * We want / and : to be included as literal characters in our title URLs
149 * as they otherwise fatally break the title
151 * @param str string String to be encoded
153 wikiUrlencode: function ( str ) {
154 return util.rawurlencode( str )
155 .replace( /%20/g, '_
' ).replace( /%3A/g, ':' ).replace( /%2F/g, '/' );
159 * Get the link to a page name (relative to wgServer)
161 * @param str String: Page name to get the link for.
162 * @return String: Location for a page with name of 'str
' or boolean false on error.
164 wikiGetlink: function ( str ) {
165 return mw.config.get( 'wgArticlePath
' ).replace( '$1',
166 util.wikiUrlencode( typeof str === 'string
' ? str : mw.config.get( 'wgPageName
' ) ) );
170 * Get address to a script in the wiki root.
171 * For index.php use mw.config.get( 'wgScript
' )
174 * @param str string Name of script (eg. 'api
'), defaults to 'index
'
175 * @return string Address to script (eg. '/w
/api
.php
' )
177 wikiScript: function ( str ) {
178 str = str || 'index
';
179 if ( str === 'index
' ) {
180 return mw.config.get( 'wgScript
' );
181 } else if ( str === 'load
' ) {
182 return mw.config.get( 'wgLoadScript
' );
184 return mw.config.get( 'wgScriptPath
' ) + '/' + str +
185 mw.config.get( 'wgScriptExtension
' );
190 * Append a new style block to the head and return the CSSStyleSheet object.
191 * Use .ownerNode to access the <style> element, or use mw.loader.addStyleTag.
192 * This function returns the styleSheet object for convience (due to cross-browsers
193 * difference as to where it is located).
196 * var sheet = mw.util.addCSS('.foobar
{ display
: none
; }');
197 * $(foo).click(function () {
198 * // Toggle the sheet on and off
199 * sheet.disabled = !sheet.disabled;
203 * @param text string CSS to be appended
204 * @return CSSStyleSheet (use .ownerNode to get to the <style> element)
206 addCSS: function ( text ) {
207 var s = mw.loader.addStyleTag( text );
212 * Hide/show the table of contents element
214 * @param $toggleLink jQuery A jQuery object of the toggle link.
215 * @param callback function Function to be called after the toggle is
216 * completed (including the animation) (optional)
217 * @return mixed Boolean visibility of the toc (true if it's visible
)
218 * or Null
if there was no table
of contents
.
220 toggleToc: function ( $toggleLink
, callback
) {
221 var $tocList
= $( '#toc ul:first' );
223 // This function shouldn't be called if there's no TOC,
224 // but just in case...
225 if ( $tocList
.length
) {
226 if ( $tocList
.is( ':hidden' ) ) {
227 $tocList
.slideDown( 'fast', callback
);
228 $toggleLink
.text( mw
.msg( 'hidetoc' ) );
229 $( '#toc' ).removeClass( 'tochidden' );
230 $.cookie( 'mw_hidetoc', null, {
236 $tocList
.slideUp( 'fast', callback
);
237 $toggleLink
.text( mw
.msg( 'showtoc' ) );
238 $( '#toc' ).addClass( 'tochidden' );
239 $.cookie( 'mw_hidetoc', '1', {
251 * Grab the URL parameter value for the given parameter.
252 * Returns null if not found.
254 * @param param string The parameter name.
255 * @param url string URL to search through (optional)
256 * @return mixed Parameter value or null.
258 getParamValue: function ( param
, url
) {
259 if ( url
=== undefined ) {
260 url
= document
.location
.href
;
262 // Get last match, stop at hash
263 var re
= new RegExp( '^[^#]*[&?]' + $.escapeRE( param
) + '=([^&#]*)' ),
266 // Beware that decodeURIComponent is not required to understand '+'
267 // by spec, as encodeURIComponent does not produce it.
268 return decodeURIComponent( m
[1].replace( /\+/g, '%20' ) );
275 * Access key prefix. Will be re-defined based on browser/operating system
276 * detection in mw.util.init().
278 tooltipAccessKeyPrefix
: 'alt-',
282 * Regex to match accesskey tooltips.
284 tooltipAccessKeyRegexp
: /\[(ctrl-)?(alt-)?(shift-)?(esc-)?(.)\]$/,
287 * Add the appropriate prefix to the accesskey shown in the tooltip.
288 * If the nodeList parameter is given, only those nodes are updated;
289 * otherwise, all the nodes that will probably have accesskeys by
290 * default are updated.
292 * @param $nodes {Array|jQuery} [optional] A jQuery object, or array
293 * of elements to update.
295 updateTooltipAccessKeys: function ( $nodes
) {
297 // Rather than going into a loop of all anchor tags, limit to few elements that
298 // contain the relevant anchor tags.
299 // Input and label are rare enough that no such optimization is needed
300 $nodes
= $( '#column-one a, #mw-head a, #mw-panel a, #p-logo a, input, label' );
301 } else if ( !( $nodes
instanceof $ ) ) {
302 $nodes
= $( $nodes
);
305 $nodes
.attr( 'title', function ( i
, val
) {
306 if ( val
&& util
.tooltipAccessKeyRegexp
.exec( val
) ) {
307 return val
.replace( util
.tooltipAccessKeyRegexp
,
308 '[' + util
.tooltipAccessKeyPrefix
+ '$5]' );
316 * A jQuery object that refers to the content area element
317 * Populated by init().
322 * Add a link to a portlet menu on the page, such as:
324 * p-cactions (Content actions), p-personal (Personal tools),
325 * p-navigation (Navigation), p-tb (Toolbox)
327 * The first three paramters are required, the others are optional and
328 * may be null. Though providing an id and tooltip is recommended.
330 * By default the new link will be added to the end of the list. To
331 * add the link before a given existing item, pass the DOM node
332 * (document.getElementById( 'foobar' )) or the jQuery-selector
333 * ( '#foobar' ) of that item.
335 * @example mw.util.addPortletLink(
336 * 'p-tb', 'http://mediawiki.org/',
337 * 'MediaWiki.org', 't-mworg', 'Go to MediaWiki.org ', 'm', '#t-print'
340 * @param portlet string ID of the target portlet ( 'p-cactions' or 'p-personal' etc.)
341 * @param href string Link URL
342 * @param text string Link text
343 * @param id string ID of the new item, should be unique and preferably have
344 * the appropriate prefix ( 'ca-', 'pt-', 'n-' or 't-' )
345 * @param tooltip string Text to show when hovering over the link, without accesskey suffix
346 * @param accesskey string Access key to activate this link (one character, try
347 * to avoid conflicts. Use $( '[accesskey=x]' ).get() in the console to
348 * see if 'x' is already used.
349 * @param nextnode mixed DOM Node or jQuery-selector string of the item that the new
350 * item should be added before, should be another item in the same
351 * list, it will be ignored otherwise
353 * @return mixed The DOM Node of the added item (a ListItem or Anchor element,
354 * depending on the skin) or null if no element was added to the document.
356 addPortletLink: function ( portlet
, href
, text
, id
, tooltip
, accesskey
, nextnode
) {
357 var $item
, $link
, $portlet
, $ul
;
359 // Check if there's atleast 3 arguments to prevent a TypeError
360 if ( arguments
.length
< 3 ) {
363 // Setup the anchor tag
364 $link
= $( '<a>' ).attr( 'href', href
).text( text
);
366 $link
.attr( 'title', tooltip
);
369 // Some skins don't have any portlets
370 // just add it to the bottom of their 'sidebar' element as a fallback
371 switch ( mw
.config
.get( 'skin' ) ) {
373 $( '#quickbar' ).append( $link
.after( '<br/>' ) );
376 $( '#searchform' ).before( $link
).before( ' | ' );
378 default: // Skins like chick, modern, monobook, myskin, simple, vector...
380 // Select the specified portlet
381 $portlet
= $( '#' + portlet
);
382 if ( $portlet
.length
=== 0 ) {
385 // Select the first (most likely only) unordered list inside the portlet
386 $ul
= $portlet
.find( 'ul' ).eq( 0 );
388 // If it didn't have an unordered list yet, create it
389 if ( $ul
.length
=== 0 ) {
393 // If there's no <div> inside, append it to the portlet directly
394 if ( $portlet
.find( 'div:first' ).length
=== 0 ) {
395 $portlet
.append( $ul
);
397 // otherwise if there's a div (such as div.body or div.pBody)
398 // append the <ul> to last (most likely only) div
399 $portlet
.find( 'div' ).eq( -1 ).append( $ul
);
403 if ( $ul
.length
=== 0 ) {
407 // Unhide portlet if it was hidden before
408 $portlet
.removeClass( 'emptyPortlet' );
410 // Wrap the anchor tag in a list item (and a span if $portlet is a Vector tab)
411 // and back up the selector to the list item
412 if ( $portlet
.hasClass( 'vectorTabs' ) ) {
413 $item
= $link
.wrap( '<li><span></span></li>' ).parent().parent();
415 $item
= $link
.wrap( '<li></li>' ).parent();
418 // Implement the properties passed to the function
420 $item
.attr( 'id', id
);
423 $link
.attr( 'accesskey', accesskey
);
424 tooltip
+= ' [' + accesskey
+ ']';
425 $link
.attr( 'title', tooltip
);
427 if ( accesskey
&& tooltip
) {
428 util
.updateTooltipAccessKeys( $link
);
431 // Where to put our node ?
432 // - nextnode is a DOM element (was the only option before MW 1.17, in wikibits.js)
433 if ( nextnode
&& nextnode
.parentNode
=== $ul
[0] ) {
434 $(nextnode
).before( $item
);
436 // - nextnode is a CSS selector for jQuery
437 } else if ( typeof nextnode
=== 'string' && $ul
.find( nextnode
).length
!== 0 ) {
438 $ul
.find( nextnode
).eq( 0 ).before( $item
);
440 // If the jQuery selector isn't found within the <ul>,
441 // or if nextnode was invalid or not passed at all,
442 // then just append it at the end of the <ul> (this is the default behaviour)
453 * Add a little box at the top of the screen to inform the user of
454 * something, replacing any previous message.
455 * Calling with no arguments, with an empty string or null will hide the message
457 * @param message {mixed} The DOM-element, jQuery object or HTML-string to be put inside the message box.
458 * to allow CSS/JS to hide different boxes. null = no class used.
459 * @depreceated Use mw.notify
461 jsMessage: function ( message
) {
462 if ( !arguments
.length
|| message
=== '' || message
=== null ) {
465 if ( typeof message
!== 'object' ) {
466 message
= $.parseHTML( message
);
468 mw
.notify( message
, { autoHide
: true, tag
: 'legacy' } );
473 * Validate a string as representing a valid e-mail address
474 * according to HTML5 specification. Please note the specification
475 * does not validate a domain with one character.
477 * @todo FIXME: should be moved to or replaced by a JavaScript validation module.
479 * @param mailtxt string E-mail address to be validated.
480 * @return mixed Null if mailtxt was an empty string, otherwise true/false
481 * is determined by validation.
483 validateEmail: function ( mailtxt
) {
484 var rfc5322Atext
, rfc1034LdhStr
, html5EmailRegexp
;
486 if ( mailtxt
=== '' ) {
491 * HTML5 defines a string as valid e-mail address if it matches
493 * 1 * ( atext / "." ) "@" ldh-str 1*( "." ldh-str )
495 * - atext : defined in RFC 5322 section 3.2.3
496 * - ldh-str : defined in RFC 1034 section 3.5
498 * (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.
515 rfc5322Atext
= 'a-z0-9!#$%&\'*+\\-/=?^_`{|}~';
518 * Next define the RFC 1034 'ldh-str'
519 * <domain> ::= <subdomain> | " "
520 * <subdomain> ::= <label> | <subdomain> "." <label>
521 * <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
522 * <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
523 * <let-dig-hyp> ::= <let-dig> | "-"
524 * <let-dig> ::= <letter> | <digit>
526 rfc1034LdhStr
= 'a-z0-9\\-';
528 html5EmailRegexp
= new RegExp(
532 // User part which is liberal :p
533 '[' + rfc5322Atext
+ '\\.]+'
539 '[' + rfc1034LdhStr
+ ']+'
541 // Optional second part and following are separated by a dot
542 '(?:\\.[' + rfc1034LdhStr
+ ']+)*'
546 // RegExp is case insensitive
549 return (null !== mailtxt
.match( html5EmailRegexp
) );
553 * Note: borrows from IP::isIPv4
555 * @param address string
556 * @param allowBlock boolean
559 isIPv4Address: function ( address
, allowBlock
) {
560 if ( typeof address
!== 'string' ) {
564 var block
= allowBlock
? '(?:\\/(?:3[0-2]|[12]?\\d))?' : '',
565 RE_IP_BYTE
= '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])',
566 RE_IP_ADD
= '(?:' + RE_IP_BYTE
+ '\\.){3}' + RE_IP_BYTE
;
568 return address
.search( new RegExp( '^' + RE_IP_ADD
+ block
+ '$' ) ) !== -1;
572 * Note: borrows from IP::isIPv6
574 * @param address string
575 * @param allowBlock boolean
578 isIPv6Address: function ( address
, allowBlock
) {
579 if ( typeof address
!== 'string' ) {
583 var block
= allowBlock
? '(?:\\/(?:12[0-8]|1[01][0-9]|[1-9]?\\d))?' : '',
585 '(?:' + // starts with "::" (including "::")
586 ':(?::|(?::' + '[0-9A-Fa-f]{1,4}' + '){1,7})' +
587 '|' + // ends with "::" (except "::")
588 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){0,6}::' +
589 '|' + // contains no "::"
590 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){7}' +
593 if ( address
.search( new RegExp( '^' + RE_IPV6_ADD
+ block
+ '$' ) ) !== -1 ) {
597 RE_IPV6_ADD
= // contains one "::" in the middle (single '::' check below)
598 '[0-9A-Fa-f]{1,4}' + '(?:::?' + '[0-9A-Fa-f]{1,4}' + '){1,6}';
600 return address
.search( new RegExp( '^' + RE_IPV6_ADD
+ block
+ '$' ) ) !== -1
601 && address
.search( /::/ ) !== -1 && address
.search( /::.*::/ ) === -1;
607 }( mediaWiki
, jQuery
) );