4e515bc5183657aa0411bdccb9b8b9a463a61d82
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 if ( url
=== undefined ) {
262 url
= document
.location
.href
;
264 // Get last match, stop at hash
265 var re
= new RegExp( '^[^#]*[&?]' + $.escapeRE( param
) + '=([^&#]*)' ),
268 // Beware that decodeURIComponent is not required to understand '+'
269 // by spec, as encodeURIComponent does not produce it.
270 return decodeURIComponent( m
[1].replace( /\+/g, '%20' ) );
277 * Access key prefix. Will be re-defined based on browser/operating system
278 * detection in mw.util.init().
280 tooltipAccessKeyPrefix
: 'alt-',
284 * Regex to match accesskey tooltips.
286 tooltipAccessKeyRegexp
: /\[(ctrl-)?(alt-)?(shift-)?(esc-)?(.)\]$/,
289 * Add the appropriate prefix to the accesskey shown in the tooltip.
290 * If the nodeList parameter is given, only those nodes are updated;
291 * otherwise, all the nodes that will probably have accesskeys by
292 * default are updated.
294 * @param $nodes {Array|jQuery} [optional] A jQuery object, or array
295 * of elements to update.
297 updateTooltipAccessKeys: function ( $nodes
) {
299 // Rather than going into a loop of all anchor tags, limit to few elements that
300 // contain the relevant anchor tags.
301 // Input and label are rare enough that no such optimization is needed
302 $nodes
= $( '#column-one a, #mw-head a, #mw-panel a, #p-logo a, input, label' );
303 } else if ( !( $nodes
instanceof $ ) ) {
304 $nodes
= $( $nodes
);
307 $nodes
.attr( 'title', function ( i
, val
) {
308 if ( val
&& util
.tooltipAccessKeyRegexp
.exec( val
) ) {
309 return val
.replace( util
.tooltipAccessKeyRegexp
,
310 '[' + util
.tooltipAccessKeyPrefix
+ '$5]' );
318 * A jQuery object that refers to the content area element
319 * Populated by init().
324 * Add a link to a portlet menu on the page, such as:
326 * p-cactions (Content actions), p-personal (Personal tools),
327 * p-navigation (Navigation), p-tb (Toolbox)
329 * The first three paramters are required, the others are optional and
330 * may be null. Though providing an id and tooltip is recommended.
332 * By default the new link will be added to the end of the list. To
333 * add the link before a given existing item, pass the DOM node
334 * (document.getElementById( 'foobar' )) or the jQuery-selector
335 * ( '#foobar' ) of that item.
337 * @example mw.util.addPortletLink(
338 * 'p-tb', 'http://mediawiki.org/',
339 * 'MediaWiki.org', 't-mworg', 'Go to MediaWiki.org ', 'm', '#t-print'
342 * @param portlet string ID of the target portlet ( 'p-cactions' or 'p-personal' etc.)
343 * @param href string Link URL
344 * @param text string Link text
345 * @param id string ID of the new item, should be unique and preferably have
346 * the appropriate prefix ( 'ca-', 'pt-', 'n-' or 't-' )
347 * @param tooltip string Text to show when hovering over the link, without accesskey suffix
348 * @param accesskey string Access key to activate this link (one character, try
349 * to avoid conflicts. Use $( '[accesskey=x]' ).get() in the console to
350 * see if 'x' is already used.
351 * @param nextnode mixed DOM Node or jQuery-selector string of the item that the new
352 * item should be added before, should be another item in the same
353 * list, it will be ignored otherwise
355 * @return mixed The DOM Node of the added item (a ListItem or Anchor element,
356 * depending on the skin) or null if no element was added to the document.
358 addPortletLink: function ( portlet
, href
, text
, id
, tooltip
, accesskey
, nextnode
) {
359 var $item
, $link
, $portlet
, $ul
;
361 // Check if there's atleast 3 arguments to prevent a TypeError
362 if ( arguments
.length
< 3 ) {
365 // Setup the anchor tag
366 $link
= $( '<a>' ).attr( 'href', href
).text( text
);
368 $link
.attr( 'title', tooltip
);
371 // Some skins don't have any portlets
372 // just add it to the bottom of their 'sidebar' element as a fallback
373 switch ( mw
.config
.get( 'skin' ) ) {
376 $( '#quickbar' ).append( $link
.after( '<br/>' ) );
379 $( '#searchform' ).before( $link
).before( ' | ' );
381 default: // Skins like chick, modern, monobook, myskin, simple, vector...
383 // Select the specified portlet
384 $portlet
= $( '#' + portlet
);
385 if ( $portlet
.length
=== 0 ) {
388 // Select the first (most likely only) unordered list inside the portlet
389 $ul
= $portlet
.find( 'ul' ).eq( 0 );
391 // If it didn't have an unordered list yet, create it
392 if ( $ul
.length
=== 0 ) {
396 // If there's no <div> inside, append it to the portlet directly
397 if ( $portlet
.find( 'div:first' ).length
=== 0 ) {
398 $portlet
.append( $ul
);
400 // otherwise if there's a div (such as div.body or div.pBody)
401 // append the <ul> to last (most likely only) div
402 $portlet
.find( 'div' ).eq( -1 ).append( $ul
);
406 if ( $ul
.length
=== 0 ) {
410 // Unhide portlet if it was hidden before
411 $portlet
.removeClass( 'emptyPortlet' );
413 // Wrap the anchor tag in a list item (and a span if $portlet is a Vector tab)
414 // and back up the selector to the list item
415 if ( $portlet
.hasClass( 'vectorTabs' ) ) {
416 $item
= $link
.wrap( '<li><span></span></li>' ).parent().parent();
418 $item
= $link
.wrap( '<li></li>' ).parent();
421 // Implement the properties passed to the function
423 $item
.attr( 'id', id
);
426 $link
.attr( 'accesskey', accesskey
);
427 tooltip
+= ' [' + accesskey
+ ']';
428 $link
.attr( 'title', tooltip
);
430 if ( accesskey
&& tooltip
) {
431 util
.updateTooltipAccessKeys( $link
);
434 // Where to put our node ?
435 // - nextnode is a DOM element (was the only option before MW 1.17, in wikibits.js)
436 if ( nextnode
&& nextnode
.parentNode
=== $ul
[0] ) {
437 $(nextnode
).before( $item
);
439 // - nextnode is a CSS selector for jQuery
440 } else if ( typeof nextnode
=== 'string' && $ul
.find( nextnode
).length
!== 0 ) {
441 $ul
.find( nextnode
).eq( 0 ).before( $item
);
443 // If the jQuery selector isn't found within the <ul>,
444 // or if nextnode was invalid or not passed at all,
445 // then just append it at the end of the <ul> (this is the default behaviour)
456 * Add a little box at the top of the screen to inform the user of
457 * something, replacing any previous message.
458 * Calling with no arguments, with an empty string or null will hide the message
460 * @param message {mixed} The DOM-element, jQuery object or HTML-string to be put inside the message box.
461 * to allow CSS/JS to hide different boxes. null = no class used.
462 * @depreceated Use mw.notify
464 jsMessage: function ( message
) {
465 if ( !arguments
.length
|| message
=== '' || message
=== null ) {
468 if ( typeof message
!== 'object' ) {
469 message
= $.parseHTML( message
);
471 mw
.notify( message
, { autoHide
: true, tag
: 'legacy' } );
476 * Validate a string as representing a valid e-mail address
477 * according to HTML5 specification. Please note the specification
478 * does not validate a domain with one character.
480 * @todo FIXME: should be moved to or replaced by a JavaScript validation module.
482 * @param mailtxt string E-mail address to be validated.
483 * @return mixed Null if mailtxt was an empty string, otherwise true/false
484 * is determined by validation.
486 validateEmail: function ( mailtxt
) {
487 var rfc5322_atext
, rfc1034_ldh_str
, HTML5_email_regexp
;
489 if ( mailtxt
=== '' ) {
494 * HTML5 defines a string as valid e-mail address if it matches
496 * 1 * ( atext / "." ) "@" ldh-str 1*( "." ldh-str )
498 * - atext : defined in RFC 5322 section 3.2.3
499 * - ldh-str : defined in RFC 1034 section 3.5
501 * (see STD 68 / RFC 5234 http://tools.ietf.org/html/std68):
505 * First, define the RFC 5322 'atext' which is pretty easy:
506 * atext = ALPHA / DIGIT / ; Printable US-ASCII
507 "!" / "#" / ; characters not including
508 "$" / "%" / ; specials. Used for atoms.
518 rfc5322_atext
= "a-z0-9!#$%&'*+\\-/=?^_`{|}~";
521 * Next define the RFC 1034 'ldh-str'
522 * <domain> ::= <subdomain> | " "
523 * <subdomain> ::= <label> | <subdomain> "." <label>
524 * <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
525 * <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
526 * <let-dig-hyp> ::= <let-dig> | "-"
527 * <let-dig> ::= <letter> | <digit>
529 rfc1034_ldh_str
= "a-z0-9\\-";
531 HTML5_email_regexp
= new RegExp(
535 // User part which is liberal :p
536 '[' + rfc5322_atext
+ '\\.]+'
542 '[' + rfc1034_ldh_str
+ ']+'
544 // Optional second part and following are separated by a dot
545 '(?:\\.[' + rfc1034_ldh_str
+ ']+)*'
549 // RegExp is case insensitive
552 return (null !== mailtxt
.match( HTML5_email_regexp
) );
556 * Note: borrows from IP::isIPv4
558 * @param address string
559 * @param allowBlock boolean
562 isIPv4Address: function ( address
, allowBlock
) {
563 if ( typeof address
!== 'string' ) {
567 var block
= allowBlock
? '(?:\\/(?:3[0-2]|[12]?\\d))?' : '',
568 RE_IP_BYTE
= '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])',
569 RE_IP_ADD
= '(?:' + RE_IP_BYTE
+ '\\.){3}' + RE_IP_BYTE
;
571 return address
.search( new RegExp( '^' + RE_IP_ADD
+ block
+ '$' ) ) !== -1;
575 * Note: borrows from IP::isIPv6
577 * @param address string
578 * @param allowBlock boolean
581 isIPv6Address: function ( address
, allowBlock
) {
582 if ( typeof address
!== 'string' ) {
586 var block
= allowBlock
? '(?:\\/(?:12[0-8]|1[01][0-9]|[1-9]?\\d))?' : '',
588 '(?:' + // starts with "::" (including "::")
589 ':(?::|(?::' + '[0-9A-Fa-f]{1,4}' + '){1,7})' +
590 '|' + // ends with "::" (except "::")
591 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){0,6}::' +
592 '|' + // contains no "::"
593 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){7}' +
596 if ( address
.search( new RegExp( '^' + RE_IPV6_ADD
+ block
+ '$' ) ) !== -1 ) {
600 RE_IPV6_ADD
= // contains one "::" in the middle (single '::' check below)
601 '[0-9A-Fa-f]{1,4}' + '(?:::?' + '[0-9A-Fa-f]{1,4}' + '){1,6}';
603 return address
.search( new RegExp( '^' + RE_IPV6_ADD
+ block
+ '$' ) ) !== -1
604 && address
.search( /::/ ) !== -1 && address
.search( /::.*::/ ) === -1;
610 }( mediaWiki
, jQuery
) );