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 : profile
.platform
=== 'win'
33 // (both alt- and alt-shift work, but alt-f triggers Chrome wrench menu
34 // which alt-shift-f does not)
36 // Chrome on other (Ubuntu?)
40 // Non-Windows Safari with webkit_version > 526
41 } else if ( profile
.platform
!== 'win'
42 && profile
.name
=== 'safari'
43 && profile
.layoutVersion
> 526 ) {
44 util
.tooltipAccessKeyPrefix
= 'ctrl-alt-';
46 } else if ( profile
.platform
=== 'mac'
47 && profile
.name
=== 'firefox'
48 && profile
.versionNumber
>= 14 ) {
49 util
.tooltipAccessKeyPrefix
= 'ctrl-option-';
50 // Safari/Konqueror on any platform, or any browser on Mac
51 // (but not Safari on Windows)
52 } else if ( !( profile
.platform
=== 'win' && profile
.name
=== 'safari' )
53 && ( profile
.name
=== 'safari'
54 || profile
.platform
=== 'mac'
55 || profile
.name
=== 'konqueror' ) ) {
56 util
.tooltipAccessKeyPrefix
= 'ctrl-';
58 // Firefox 2.x and later
59 } else if ( profile
.name
=== 'firefox' && profile
.versionBase
> '1' ) {
60 util
.tooltipAccessKeyPrefix
= 'alt-shift-';
63 /* Fill $content var */
64 util
.$content
= ( function () {
65 var $content
, selectors
= [
66 // The preferred standard for setting $content (class="mw-body")
67 // You may also use (class="mw-body mw-body-primary") if you use
68 // mw-body in multiple locations.
69 // Or class="mw-body-primary" if you want $content to be deeper
70 // in the dom than mw-body
74 /* Legacy fallbacks for setting the content */
75 // Vector, Monobook, Chick, etc... based skins
81 // Standard, CologneBlue
84 // #content is present on almost all if not all skins. Most skins (the above cases)
85 // have #content too, but as an outer wrapper instead of the article text container.
86 // The skins that don't have an outer wrapper do have #content for everything
87 // so it's a good fallback
90 // If nothing better is found fall back to our bodytext div that is guaranteed to be here
93 // Should never happen... well, it could if someone is not finished writing a skin and has
94 // not inserted bodytext yet. But in any case <body> should always exist
97 for ( var i
= 0, l
= selectors
.length
; i
< l
; i
++ ) {
98 $content
= $( selectors
[i
] ).first();
99 if ( $content
.length
) {
104 // Make sure we don't unset util.$content if it was preset and we don't find anything
105 return util
.$content
;
108 // Table of contents toggle
109 $tocTitle
= $( '#toctitle' );
110 $tocToggleLink
= $( '#togglelink' );
111 // Only add it if there is a TOC and there is no toggle added already
112 if ( $( '#toc' ).length
&& $tocTitle
.length
&& !$tocToggleLink
.length
) {
113 hideTocCookie
= $.cookie( 'mw_hidetoc' );
114 $tocToggleLink
= $( '<a href="#" class="internal" id="togglelink"></a>' )
115 .text( mw
.msg( 'hidetoc' ) )
116 .click( function ( e
) {
118 util
.toggleToc( $(this) );
122 .wrap( '<span class="toctoggle"></span>' )
124 .prepend( ' [' )
128 if ( hideTocCookie
=== '1' ) {
129 util
.toggleToc( $tocToggleLink
);
137 * Encode the string like PHP's rawurlencode
139 * @param str string String to be encoded
141 rawurlencode: function ( str
) {
143 return encodeURIComponent( str
)
144 .replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' )
145 .replace( /\)/g, '%29' ).replace( /\*/g, '%2A
' ).replace( /~/g, '%7E
' );
149 * Encode page titles for use in a URL
150 * We want / and : to be included as literal characters in our title URLs
151 * as they otherwise fatally break the title
153 * @param str string String to be encoded
155 wikiUrlencode: function ( str ) {
156 return util.rawurlencode( str )
157 .replace( /%20/g, '_
' ).replace( /%3A/g, ':' ).replace( /%2F/g, '/' );
161 * Get the link to a page name (relative to wgServer)
163 * @param str String: Page name to get the link for.
164 * @return String: Location for a page with name of 'str
' or boolean false on error.
166 wikiGetlink: function ( str ) {
167 return mw.config.get( 'wgArticlePath
' ).replace( '$1',
168 util.wikiUrlencode( typeof str === 'string
' ? str : mw.config.get( 'wgPageName
' ) ) );
172 * Get address to a script in the wiki root.
173 * For index.php use mw.config.get( 'wgScript
' )
176 * @param str string Name of script (eg. 'api
'), defaults to 'index
'
177 * @return string Address to script (eg. '/w
/api
.php
' )
179 wikiScript: function ( str ) {
180 str = str || 'index
';
181 if ( str === 'index
' ) {
182 return mw.config.get( 'wgScript
' );
183 } else if ( str === 'load
' ) {
184 return mw.config.get( 'wgLoadScript
' );
186 return mw.config.get( 'wgScriptPath
' ) + '/' + str +
187 mw.config.get( 'wgScriptExtension
' );
192 * Append a new style block to the head and return the CSSStyleSheet object.
193 * Use .ownerNode to access the <style> element, or use mw.loader.addStyleTag.
194 * This function returns the styleSheet object for convience (due to cross-browsers
195 * 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;
205 * @param text string CSS to be appended
206 * @return CSSStyleSheet (use .ownerNode to get to the <style> element)
208 addCSS: function ( text ) {
209 var s = mw.loader.addStyleTag( text );
214 * Hide/show the table of contents element
216 * @param $toggleLink jQuery A jQuery object of the toggle link.
217 * @param callback function Function to be called after the toggle is
218 * completed (including the animation) (optional)
219 * @return mixed Boolean visibility of the toc (true if it's visible
)
220 * or Null
if there was no table
of contents
.
222 toggleToc: function ( $toggleLink
, callback
) {
223 var $tocList
= $( '#toc ul:first' );
225 // This function shouldn't be called if there's no TOC,
226 // but just in case...
227 if ( $tocList
.length
) {
228 if ( $tocList
.is( ':hidden' ) ) {
229 $tocList
.slideDown( 'fast', callback
);
230 $toggleLink
.text( mw
.msg( 'hidetoc' ) );
231 $( '#toc' ).removeClass( 'tochidden' );
232 $.cookie( 'mw_hidetoc', null, {
238 $tocList
.slideUp( 'fast', callback
);
239 $toggleLink
.text( mw
.msg( 'showtoc' ) );
240 $( '#toc' ).addClass( 'tochidden' );
241 $.cookie( 'mw_hidetoc', '1', {
253 * Grab the URL parameter value for the given parameter.
254 * Returns null if not found.
256 * @param param string The parameter name.
257 * @param url string URL to search through (optional)
258 * @return mixed Parameter value or null.
260 getParamValue: function ( param
, url
) {
261 url
= 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' ) ) {
374 $( '#quickbar' ).append( $link
.after( '<br/>' ) );
377 $( '#searchform' ).before( $link
).before( ' | ' );
379 default: // Skins like chick, modern, monobook, myskin, simple, vector...
381 // Select the specified portlet
382 $portlet
= $( '#' + portlet
);
383 if ( $portlet
.length
=== 0 ) {
386 // Select the first (most likely only) unordered list inside the portlet
387 $ul
= $portlet
.find( 'ul' ).eq( 0 );
389 // If it didn't have an unordered list yet, create it
390 if ( $ul
.length
=== 0 ) {
394 // If there's no <div> inside, append it to the portlet directly
395 if ( $portlet
.find( 'div:first' ).length
=== 0 ) {
396 $portlet
.append( $ul
);
398 // otherwise if there's a div (such as div.body or div.pBody)
399 // append the <ul> to last (most likely only) div
400 $portlet
.find( 'div' ).eq( -1 ).append( $ul
);
404 if ( $ul
.length
=== 0 ) {
408 // Unhide portlet if it was hidden before
409 $portlet
.removeClass( 'emptyPortlet' );
411 // Wrap the anchor tag in a list item (and a span if $portlet is a Vector tab)
412 // and back up the selector to the list item
413 if ( $portlet
.hasClass( 'vectorTabs' ) ) {
414 $item
= $link
.wrap( '<li><span></span></li>' ).parent().parent();
416 $item
= $link
.wrap( '<li></li>' ).parent();
419 // Implement the properties passed to the function
421 $item
.attr( 'id', id
);
424 $link
.attr( 'accesskey', accesskey
);
425 tooltip
+= ' [' + accesskey
+ ']';
426 $link
.attr( 'title', tooltip
);
428 if ( accesskey
&& tooltip
) {
429 util
.updateTooltipAccessKeys( $link
);
432 // Where to put our node ?
433 // - nextnode is a DOM element (was the only option before MW 1.17, in wikibits.js)
434 if ( nextnode
&& nextnode
.parentNode
=== $ul
[0] ) {
435 $(nextnode
).before( $item
);
437 // - nextnode is a CSS selector for jQuery
438 } else if ( typeof nextnode
=== 'string' && $ul
.find( nextnode
).length
!== 0 ) {
439 $ul
.find( nextnode
).eq( 0 ).before( $item
);
441 // If the jQuery selector isn't found within the <ul>,
442 // or if nextnode was invalid or not passed at all,
443 // then just append it at the end of the <ul> (this is the default behaviour)
454 * Add a little box at the top of the screen to inform the user of
455 * something, replacing any previous message.
456 * Calling with no arguments, with an empty string or null will hide the message
458 * @param message {mixed} The DOM-element, jQuery object or HTML-string to be put inside the message box.
459 * to allow CSS/JS to hide different boxes. null = no class used.
460 * @depreceated Use mw.notify
462 jsMessage: function ( message
) {
463 if ( !arguments
.length
|| message
=== '' || message
=== null ) {
466 if ( typeof message
!== 'object' ) {
467 message
= $.parseHTML( message
);
469 mw
.notify( message
, { autoHide
: true, tag
: 'legacy' } );
474 * Validate a string as representing a valid e-mail address
475 * according to HTML5 specification. Please note the specification
476 * does not validate a domain with one character.
478 * @todo FIXME: should be moved to or replaced by a JavaScript validation module.
480 * @param mailtxt string E-mail address to be validated.
481 * @return mixed Null if mailtxt was an empty string, otherwise true/false
482 * is determined by validation.
484 validateEmail: function ( mailtxt
) {
485 var rfc5322_atext
, rfc1034_ldh_str
, HTML5_email_regexp
;
487 if ( mailtxt
=== '' ) {
492 * HTML5 defines a string as valid e-mail address if it matches
494 * 1 * ( atext / "." ) "@" ldh-str 1*( "." ldh-str )
496 * - atext : defined in RFC 5322 section 3.2.3
497 * - ldh-str : defined in RFC 1034 section 3.5
499 * (see STD 68 / RFC 5234 http://tools.ietf.org/html/std68):
503 * First, define the RFC 5322 'atext' which is pretty easy:
504 * atext = ALPHA / DIGIT / ; Printable US-ASCII
505 "!" / "#" / ; characters not including
506 "$" / "%" / ; specials. Used for atoms.
516 rfc5322_atext
= "a-z0-9!#$%&'*+\\-/=?^_`{|}~";
519 * Next define the RFC 1034 'ldh-str'
520 * <domain> ::= <subdomain> | " "
521 * <subdomain> ::= <label> | <subdomain> "." <label>
522 * <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
523 * <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
524 * <let-dig-hyp> ::= <let-dig> | "-"
525 * <let-dig> ::= <letter> | <digit>
527 rfc1034_ldh_str
= "a-z0-9\\-";
529 HTML5_email_regexp
= new RegExp(
533 // User part which is liberal :p
534 '[' + rfc5322_atext
+ '\\.]+'
540 '[' + rfc1034_ldh_str
+ ']+'
542 // Optional second part and following are separated by a dot
543 '(?:\\.[' + rfc1034_ldh_str
+ ']+)*'
547 // RegExp is case insensitive
550 return (null !== mailtxt
.match( HTML5_email_regexp
) );
554 * Note: borrows from IP::isIPv4
556 * @param address string
557 * @param allowBlock boolean
560 isIPv4Address: function ( address
, allowBlock
) {
561 if ( typeof address
!== 'string' ) {
565 var block
= allowBlock
? '(?:\\/(?:3[0-2]|[12]?\\d))?' : '',
566 RE_IP_BYTE
= '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])',
567 RE_IP_ADD
= '(?:' + RE_IP_BYTE
+ '\\.){3}' + RE_IP_BYTE
;
569 return address
.search( new RegExp( '^' + RE_IP_ADD
+ block
+ '$' ) ) !== -1;
573 * Note: borrows from IP::isIPv6
575 * @param address string
576 * @param allowBlock boolean
579 isIPv6Address: function ( address
, allowBlock
) {
580 if ( typeof address
!== 'string' ) {
584 var block
= allowBlock
? '(?:\\/(?:12[0-8]|1[01][0-9]|[1-9]?\\d))?' : '',
586 '(?:' + // starts with "::" (including "::")
587 ':(?::|(?::' + '[0-9A-Fa-f]{1,4}' + '){1,7})' +
588 '|' + // ends with "::" (except "::")
589 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){0,6}::' +
590 '|' + // contains no "::"
591 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){7}' +
594 if ( address
.search( new RegExp( '^' + RE_IPV6_ADD
+ block
+ '$' ) ) !== -1 ) {
598 RE_IPV6_ADD
= // contains one "::" in the middle (single '::' check below)
599 '[0-9A-Fa-f]{1,4}' + '(?:::?' + '[0-9A-Fa-f]{1,4}' + '){1,6}';
601 return address
.search( new RegExp( '^' + RE_IPV6_ADD
+ block
+ '$' ) ) !== -1
602 && address
.search( /::/ ) !== -1 && address
.search( /::.*::/ ) === -1;
608 }( mediaWiki
, jQuery
) );