4bb004a31c41d03306d6bb3e1dbdd4d4de9e6540
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 i
, l
, $content
, selectors
;
67 // The preferred standard for setting $content (class="mw-body")
68 // You may also use (class="mw-body mw-body-primary") if you use
69 // mw-body in multiple locations.
70 // Or class="mw-body-primary" if you want $content to be deeper
71 // in the dom than mw-body
75 /* Legacy fallbacks for setting the content */
76 // Vector, Monobook, Chick, etc... based skins
82 // Standard, CologneBlue
85 // #content is present on almost all if not all skins. Most skins (the above cases)
86 // have #content too, but as an outer wrapper instead of the article text container.
87 // The skins that don't have an outer wrapper do have #content for everything
88 // so it's a good fallback
91 // If nothing better is found fall back to our bodytext div that is guaranteed to be here
94 // Should never happen... well, it could if someone is not finished writing a skin and has
95 // not inserted bodytext yet. But in any case <body> should always exist
98 for ( i
= 0, l
= selectors
.length
; i
< l
; i
++ ) {
99 $content
= $( selectors
[i
] ).first();
100 if ( $content
.length
) {
105 // Make sure we don't unset util.$content if it was preset and we don't find anything
106 return 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 str string 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 str string 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 str String: 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).
199 * var sheet = mw.util.addCSS('.foobar
{ display
: none
; }');
200 * $(foo).click(function () {
201 * // Toggle the sheet on and off
202 * sheet.disabled = !sheet.disabled;
206 * @param text string CSS to be appended
207 * @return CSSStyleSheet (use .ownerNode to get to the <style> element)
209 addCSS: function ( text ) {
210 var s = mw.loader.addStyleTag( text );
215 * Hide/show the table of contents element
217 * @param $toggleLink jQuery A jQuery object of the toggle link.
218 * @param callback function Function to be called after the toggle is
219 * completed (including the animation) (optional)
220 * @return mixed Boolean visibility of the toc (true if it's visible
)
221 * or Null
if there was no table
of contents
.
223 toggleToc: function ( $toggleLink
, callback
) {
224 var $tocList
= $( '#toc ul:first' );
226 // This function shouldn't be called if there's no TOC,
227 // but just in case...
228 if ( $tocList
.length
) {
229 if ( $tocList
.is( ':hidden' ) ) {
230 $tocList
.slideDown( 'fast', callback
);
231 $toggleLink
.text( mw
.msg( 'hidetoc' ) );
232 $( '#toc' ).removeClass( 'tochidden' );
233 $.cookie( 'mw_hidetoc', null, {
239 $tocList
.slideUp( 'fast', callback
);
240 $toggleLink
.text( mw
.msg( 'showtoc' ) );
241 $( '#toc' ).addClass( 'tochidden' );
242 $.cookie( 'mw_hidetoc', '1', {
254 * Grab the URL parameter value for the given parameter.
255 * Returns null if not found.
257 * @param param string The parameter name.
258 * @param url string URL to search through (optional)
259 * @return mixed Parameter value or null.
261 getParamValue: function ( param
, url
) {
262 if ( url
=== undefined ) {
263 url
= document
.location
.href
;
265 // Get last match, stop at hash
266 var re
= new RegExp( '^[^#]*[&?]' + $.escapeRE( param
) + '=([^&#]*)' ),
269 // Beware that decodeURIComponent is not required to understand '+'
270 // by spec, as encodeURIComponent does not produce it.
271 return decodeURIComponent( m
[1].replace( /\+/g, '%20' ) );
278 * Access key prefix. Will be re-defined based on browser/operating system
279 * detection in mw.util.init().
281 tooltipAccessKeyPrefix
: 'alt-',
285 * Regex to match accesskey tooltips.
287 tooltipAccessKeyRegexp
: /\[(ctrl-)?(alt-)?(shift-)?(esc-)?(.)\]$/,
290 * Add the appropriate prefix to the accesskey shown in the tooltip.
291 * If the nodeList parameter is given, only those nodes are updated;
292 * otherwise, all the nodes that will probably have accesskeys by
293 * default are updated.
295 * @param $nodes {Array|jQuery} [optional] A jQuery object, or array
296 * of elements to update.
298 updateTooltipAccessKeys: function ( $nodes
) {
300 // Rather than going into a loop of all anchor tags, limit to few elements that
301 // contain the relevant anchor tags.
302 // Input and label are rare enough that no such optimization is needed
303 $nodes
= $( '#column-one a, #mw-head a, #mw-panel a, #p-logo a, input, label' );
304 } else if ( !( $nodes
instanceof $ ) ) {
305 $nodes
= $( $nodes
);
308 $nodes
.attr( 'title', function ( i
, val
) {
309 if ( val
&& util
.tooltipAccessKeyRegexp
.exec( val
) ) {
310 return val
.replace( util
.tooltipAccessKeyRegexp
,
311 '[' + util
.tooltipAccessKeyPrefix
+ '$5]' );
319 * A jQuery object that refers to the content area element
320 * Populated by init().
325 * Add a link to a portlet menu on the page, such as:
327 * p-cactions (Content actions), p-personal (Personal tools),
328 * p-navigation (Navigation), p-tb (Toolbox)
330 * The first three paramters are required, the others are optional and
331 * may be null. Though providing an id and tooltip is recommended.
333 * By default the new link will be added to the end of the list. To
334 * add the link before a given existing item, pass the DOM node
335 * (document.getElementById( 'foobar' )) or the jQuery-selector
336 * ( '#foobar' ) of that item.
338 * @example mw.util.addPortletLink(
339 * 'p-tb', 'http://mediawiki.org/',
340 * 'MediaWiki.org', 't-mworg', 'Go to MediaWiki.org ', 'm', '#t-print'
343 * @param portlet string ID of the target portlet ( 'p-cactions' or 'p-personal' etc.)
344 * @param href string Link URL
345 * @param text string Link text
346 * @param id string ID of the new item, should be unique and preferably have
347 * the appropriate prefix ( 'ca-', 'pt-', 'n-' or 't-' )
348 * @param tooltip string Text to show when hovering over the link, without accesskey suffix
349 * @param accesskey string Access key to activate this link (one character, try
350 * to avoid conflicts. Use $( '[accesskey=x]' ).get() in the console to
351 * see if 'x' is already used.
352 * @param nextnode mixed DOM Node or jQuery-selector string of the item that the new
353 * item should be added before, should be another item in the same
354 * list, it will be ignored otherwise
356 * @return mixed The DOM Node of the added item (a ListItem or Anchor element,
357 * depending on the skin) or null if no element was added to the document.
359 addPortletLink: function ( portlet
, href
, text
, id
, tooltip
, accesskey
, nextnode
) {
360 var $item
, $link
, $portlet
, $ul
;
362 // Check if there's atleast 3 arguments to prevent a TypeError
363 if ( arguments
.length
< 3 ) {
366 // Setup the anchor tag
367 $link
= $( '<a>' ).attr( 'href', href
).text( text
);
369 $link
.attr( 'title', tooltip
);
372 // Some skins don't have any portlets
373 // just add it to the bottom of their 'sidebar' element as a fallback
374 switch ( mw
.config
.get( 'skin' ) ) {
377 $( '#quickbar' ).append( $link
.after( '<br/>' ) );
380 $( '#searchform' ).before( $link
).before( ' | ' );
382 default: // Skins like chick, modern, monobook, myskin, simple, vector...
384 // Select the specified portlet
385 $portlet
= $( '#' + portlet
);
386 if ( $portlet
.length
=== 0 ) {
389 // Select the first (most likely only) unordered list inside the portlet
390 $ul
= $portlet
.find( 'ul' ).eq( 0 );
392 // If it didn't have an unordered list yet, create it
393 if ( $ul
.length
=== 0 ) {
397 // If there's no <div> inside, append it to the portlet directly
398 if ( $portlet
.find( 'div:first' ).length
=== 0 ) {
399 $portlet
.append( $ul
);
401 // otherwise if there's a div (such as div.body or div.pBody)
402 // append the <ul> to last (most likely only) div
403 $portlet
.find( 'div' ).eq( -1 ).append( $ul
);
407 if ( $ul
.length
=== 0 ) {
411 // Unhide portlet if it was hidden before
412 $portlet
.removeClass( 'emptyPortlet' );
414 // Wrap the anchor tag in a list item (and a span if $portlet is a Vector tab)
415 // and back up the selector to the list item
416 if ( $portlet
.hasClass( 'vectorTabs' ) ) {
417 $item
= $link
.wrap( '<li><span></span></li>' ).parent().parent();
419 $item
= $link
.wrap( '<li></li>' ).parent();
422 // Implement the properties passed to the function
424 $item
.attr( 'id', id
);
427 $link
.attr( 'accesskey', accesskey
);
428 tooltip
+= ' [' + accesskey
+ ']';
429 $link
.attr( 'title', tooltip
);
431 if ( accesskey
&& tooltip
) {
432 util
.updateTooltipAccessKeys( $link
);
435 // Where to put our node ?
436 // - nextnode is a DOM element (was the only option before MW 1.17, in wikibits.js)
437 if ( nextnode
&& nextnode
.parentNode
=== $ul
[0] ) {
438 $(nextnode
).before( $item
);
440 // - nextnode is a CSS selector for jQuery
441 } else if ( typeof nextnode
=== 'string' && $ul
.find( nextnode
).length
!== 0 ) {
442 $ul
.find( nextnode
).eq( 0 ).before( $item
);
444 // If the jQuery selector isn't found within the <ul>,
445 // or if nextnode was invalid or not passed at all,
446 // then just append it at the end of the <ul> (this is the default behaviour)
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 message {mixed} 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 * @depreceated 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 * @todo FIXME: should be moved to or replaced by a JavaScript validation module.
483 * @param mailtxt string E-mail address to be validated.
484 * @return mixed Null if mailtxt was an empty string, otherwise true/false
485 * is determined by validation.
487 validateEmail: function ( mailtxt
) {
488 var rfc5322Atext
, rfc1034LdhStr
, html5EmailRegexp
;
490 if ( mailtxt
=== '' ) {
495 * HTML5 defines a string as valid e-mail address if it matches
497 * 1 * ( atext / "." ) "@" ldh-str 1*( "." ldh-str )
499 * - atext : defined in RFC 5322 section 3.2.3
500 * - ldh-str : defined in RFC 1034 section 3.5
502 * (see STD 68 / RFC 5234 http://tools.ietf.org/html/std68):
506 * First, define the RFC 5322 'atext' which is pretty easy:
507 * atext = ALPHA / DIGIT / ; Printable US-ASCII
508 "!" / "#" / ; characters not including
509 "$" / "%" / ; specials. Used for atoms.
519 rfc5322Atext
= 'a-z0-9!#$%&\'*+\\-/=?^_`{|}~';
522 * Next define the RFC 1034 'ldh-str'
523 * <domain> ::= <subdomain> | " "
524 * <subdomain> ::= <label> | <subdomain> "." <label>
525 * <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
526 * <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
527 * <let-dig-hyp> ::= <let-dig> | "-"
528 * <let-dig> ::= <letter> | <digit>
530 rfc1034LdhStr
= 'a-z0-9\\-';
532 html5EmailRegexp
= new RegExp(
536 // User part which is liberal :p
537 '[' + rfc5322Atext
+ '\\.]+'
543 '[' + rfc1034LdhStr
+ ']+'
545 // Optional second part and following are separated by a dot
546 '(?:\\.[' + rfc1034LdhStr
+ ']+)*'
550 // RegExp is case insensitive
553 return (null !== mailtxt
.match( html5EmailRegexp
) );
557 * Note: borrows from IP::isIPv4
559 * @param address string
560 * @param allowBlock boolean
563 isIPv4Address: function ( address
, allowBlock
) {
564 if ( typeof address
!== 'string' ) {
568 var block
= allowBlock
? '(?:\\/(?:3[0-2]|[12]?\\d))?' : '',
569 RE_IP_BYTE
= '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])',
570 RE_IP_ADD
= '(?:' + RE_IP_BYTE
+ '\\.){3}' + RE_IP_BYTE
;
572 return address
.search( new RegExp( '^' + RE_IP_ADD
+ block
+ '$' ) ) !== -1;
576 * Note: borrows from IP::isIPv6
578 * @param address string
579 * @param allowBlock boolean
582 isIPv6Address: function ( address
, allowBlock
) {
583 if ( typeof address
!== 'string' ) {
587 var block
= allowBlock
? '(?:\\/(?:12[0-8]|1[01][0-9]|[1-9]?\\d))?' : '',
589 '(?:' + // starts with "::" (including "::")
590 ':(?::|(?::' + '[0-9A-Fa-f]{1,4}' + '){1,7})' +
591 '|' + // ends with "::" (except "::")
592 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){0,6}::' +
593 '|' + // contains no "::"
594 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){7}' +
597 if ( address
.search( new RegExp( '^' + RE_IPV6_ADD
+ block
+ '$' ) ) !== -1 ) {
601 RE_IPV6_ADD
= // contains one "::" in the middle (single '::' check below)
602 '[0-9A-Fa-f]{1,4}' + '(?:::?' + '[0-9A-Fa-f]{1,4}' + '){1,6}';
604 return address
.search( new RegExp( '^' + RE_IPV6_ADD
+ block
+ '$' ) ) !== -1
605 && address
.search( /::/ ) !== -1 && address
.search( /::.*::/ ) === -1;
611 }( mediaWiki
, jQuery
) );