eade86ba3790b328fb08988fb76c4743b4ab668d
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
= (
35 profile
.platform
=== 'mac' ? 'ctrl-option-' :
37 // (both alt- and alt-shift work, but alt-f triggers Chrome wrench menu
38 // which alt-shift-f does not)
39 profile
.platform
=== 'win' ? 'alt-shift-' :
40 // Chrome on Ubuntu (and other?)
44 // Non-Windows Safari with webkit_version > 526
45 } else if ( profile
.platform
!== 'win'
46 && profile
.name
=== 'safari'
47 && profile
.layoutVersion
> 526 ) {
48 util
.tooltipAccessKeyPrefix
= 'ctrl-alt-';
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 if ( $( '#bodyContent' ).length
) {
65 // Vector, Monobook, Chick etc.
66 util
.$content
= $( '#bodyContent' );
68 } else if ( $( '#mw_contentholder' ).length
) {
70 util
.$content
= $( '#mw_contentholder' );
72 } else if ( $( '#article' ).length
) {
73 // Standard, CologneBlue
74 util
.$content
= $( '#article' );
77 // #content is present on almost all if not all skins. Most skins (the above cases)
78 // have #content too, but as an outer wrapper instead of the article text container.
79 // The skins that don't have an outer wrapper do have #content for everything
80 // so it's a good fallback
81 util
.$content
= $( '#content' );
84 // Table of contents toggle
85 $tocTitle
= $( '#toctitle' );
86 $tocToggleLink
= $( '#togglelink' );
87 // Only add it if there is a TOC and there is no toggle added already
88 if ( $( '#toc' ).length
&& $tocTitle
.length
&& !$tocToggleLink
.length
) {
89 hideTocCookie
= $.cookie( 'mw_hidetoc' );
90 $tocToggleLink
= $( '<a href="#" class="internal" id="togglelink"></a>' )
91 .text( mw
.msg( 'hidetoc' ) )
92 .click( function ( e
) {
94 util
.toggleToc( $(this) );
98 .wrap( '<span class="toctoggle"></span>' )
100 .prepend( ' [' )
104 if ( hideTocCookie
=== '1' ) {
105 util
.toggleToc( $tocToggleLink
);
113 * Encode the string like PHP's rawurlencode
115 * @param str string String to be encoded
117 rawurlencode: function ( str
) {
119 return encodeURIComponent( str
)
120 .replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' )
121 .replace( /\)/g, '%29' ).replace( /\*/g, '%2A
' ).replace( /~/g, '%7E
' );
125 * Encode page titles for use in a URL
126 * We want / and : to be included as literal characters in our title URLs
127 * as they otherwise fatally break the title
129 * @param str string String to be encoded
131 wikiUrlencode: function ( str ) {
132 return util.rawurlencode( str )
133 .replace( /%20/g, '_
' ).replace( /%3A/g, ':' ).replace( /%2F/g, '/' );
137 * Get the link to a page name (relative to wgServer)
139 * @param str String: Page name to get the link for.
140 * @return String: Location for a page with name of 'str
' or boolean false on error.
142 wikiGetlink: function ( str ) {
143 return mw.config.get( 'wgArticlePath
' ).replace( '$1',
144 util.wikiUrlencode( typeof str === 'string
' ? str : mw.config.get( 'wgPageName
' ) ) );
148 * Get address to a script in the wiki root.
149 * For index.php use mw.config.get( 'wgScript
' )
151 * @param str string Name of script (eg. 'api
'), defaults to 'index
'
152 * @return string Address to script (eg. '/w
/api
.php
' )
154 wikiScript: function ( str ) {
155 return mw.config.get( 'wgScriptPath
' ) + '/' + ( str || 'index
' ) +
156 mw.config.get( 'wgScriptExtension
' );
160 * Append a new style block to the head and return the CSSStyleSheet object.
161 * Use .ownerNode to access the <style> element, or use mw.loader.addStyleTag.
162 * This function returns the styleSheet object for convience (due to cross-browsers
163 * difference as to where it is located).
166 * var sheet = mw.util.addCSS('.foobar
{ display
: none
; }');
167 * $(foo).click(function () {
168 * // Toggle the sheet on and off
169 * sheet.disabled = !sheet.disabled;
173 * @param text string CSS to be appended
174 * @return CSSStyleSheet (use .ownerNode to get to the <style> element)
176 addCSS: function ( text ) {
177 var s = mw.loader.addStyleTag( text );
182 * Hide/show the table of contents element
184 * @param $toggleLink jQuery A jQuery object of the toggle link.
185 * @param callback function Function to be called after the toggle is
186 * completed (including the animation) (optional)
187 * @return mixed Boolean visibility of the toc (true if it's visible
)
188 * or Null
if there was no table
of contents
.
190 toggleToc: function ( $toggleLink
, callback
) {
191 var $tocList
= $( '#toc ul:first' );
193 // This function shouldn't be called if there's no TOC,
194 // but just in case...
195 if ( $tocList
.length
) {
196 if ( $tocList
.is( ':hidden' ) ) {
197 $tocList
.slideDown( 'fast', callback
);
198 $toggleLink
.text( mw
.msg( 'hidetoc' ) );
199 $( '#toc' ).removeClass( 'tochidden' );
200 $.cookie( 'mw_hidetoc', null, {
206 $tocList
.slideUp( 'fast', callback
);
207 $toggleLink
.text( mw
.msg( 'showtoc' ) );
208 $( '#toc' ).addClass( 'tochidden' );
209 $.cookie( 'mw_hidetoc', '1', {
221 * Grab the URL parameter value for the given parameter.
222 * Returns null if not found.
224 * @param param string The parameter name.
225 * @param url string URL to search through (optional)
226 * @return mixed Parameter value or null.
228 getParamValue: function ( param
, url
) {
229 url
= url
|| document
.location
.href
;
230 // Get last match, stop at hash
231 var re
= new RegExp( '^[^#]*[&?]' + $.escapeRE( param
) + '=([^&#]*)' ),
233 if ( m
&& m
.length
> 1 ) {
234 // Beware that decodeURIComponent is not required to understand '+'
235 // by spec, as encodeURIComponent does not produce it.
236 return decodeURIComponent( m
[1].replace( /\+/g, '%20' ) );
243 * Access key prefix. Will be re-defined based on browser/operating system
244 * detection in mw.util.init().
246 tooltipAccessKeyPrefix
: 'alt-',
250 * Regex to match accesskey tooltips.
252 tooltipAccessKeyRegexp
: /\[(ctrl-)?(alt-)?(shift-)?(esc-)?(.)\]$/,
255 * Add the appropriate prefix to the accesskey shown in the tooltip.
256 * If the nodeList parameter is given, only those nodes are updated;
257 * otherwise, all the nodes that will probably have accesskeys by
258 * default are updated.
260 * @param $nodes {Array|jQuery} [optional] A jQuery object, or array
261 * of elements to update.
263 updateTooltipAccessKeys: function ( $nodes
) {
265 // Rather than going into a loop of all anchor tags, limit to few elements that
266 // contain the relevant anchor tags.
267 // Input and label are rare enough that no such optimization is needed
268 $nodes
= $( '#column-one a, #mw-head a, #mw-panel a, #p-logo a, input, label' );
269 } else if ( !( $nodes
instanceof $ ) ) {
270 $nodes
= $( $nodes
);
273 $nodes
.attr( 'title', function ( i
, val
) {
274 if ( val
&& util
.tooltipAccessKeyRegexp
.exec( val
) ) {
275 return val
.replace( util
.tooltipAccessKeyRegexp
,
276 '[' + util
.tooltipAccessKeyPrefix
+ '$5]' );
284 * A jQuery object that refers to the page-content element
285 * Populated by init().
290 * Add a link to a portlet menu on the page, such as:
292 * p-cactions (Content actions), p-personal (Personal tools),
293 * p-navigation (Navigation), p-tb (Toolbox)
295 * The first three paramters are required, the others are optional and
296 * may be null. Though providing an id and tooltip is recommended.
298 * By default the new link will be added to the end of the list. To
299 * add the link before a given existing item, pass the DOM node
300 * (document.getElementById( 'foobar' )) or the jQuery-selector
301 * ( '#foobar' ) of that item.
303 * @example mw.util.addPortletLink(
304 * 'p-tb', 'http://mediawiki.org/',
305 * 'MediaWiki.org', 't-mworg', 'Go to MediaWiki.org ', 'm', '#t-print'
308 * @param portlet string ID of the target portlet ( 'p-cactions' or 'p-personal' etc.)
309 * @param href string Link URL
310 * @param text string Link text
311 * @param id string ID of the new item, should be unique and preferably have
312 * the appropriate prefix ( 'ca-', 'pt-', 'n-' or 't-' )
313 * @param tooltip string Text to show when hovering over the link, without accesskey suffix
314 * @param accesskey string Access key to activate this link (one character, try
315 * to avoid conflicts. Use $( '[accesskey=x]' ).get() in the console to
316 * see if 'x' is already used.
317 * @param nextnode mixed DOM Node or jQuery-selector string of the item that the new
318 * item should be added before, should be another item in the same
319 * list, it will be ignored otherwise
321 * @return mixed The DOM Node of the added item (a ListItem or Anchor element,
322 * depending on the skin) or null if no element was added to the document.
324 addPortletLink: function ( portlet
, href
, text
, id
, tooltip
, accesskey
, nextnode
) {
325 var $item
, $link
, $portlet
, $ul
;
327 // Check if there's atleast 3 arguments to prevent a TypeError
328 if ( arguments
.length
< 3 ) {
331 // Setup the anchor tag
332 $link
= $( '<a>' ).attr( 'href', href
).text( text
);
334 $link
.attr( 'title', tooltip
);
337 // Some skins don't have any portlets
338 // just add it to the bottom of their 'sidebar' element as a fallback
339 switch ( mw
.config
.get( 'skin' ) ) {
342 $( '#quickbar' ).append( $link
.after( '<br/>' ) );
345 $( '#searchform' ).before( $link
).before( ' | ' );
347 default: // Skins like chick, modern, monobook, myskin, simple, vector...
349 // Select the specified portlet
350 $portlet
= $( '#' + portlet
);
351 if ( $portlet
.length
=== 0 ) {
354 // Select the first (most likely only) unordered list inside the portlet
355 $ul
= $portlet
.find( 'ul' );
357 // If it didn't have an unordered list yet, create it
358 if ( $ul
.length
=== 0 ) {
359 // If there's no <div> inside, append it to the portlet directly
360 if ( $portlet
.find( 'div:first' ).length
=== 0 ) {
361 $portlet
.append( '<ul></ul>' );
363 // otherwise if there's a div (such as div.body or div.pBody)
364 // append the <ul> to last (most likely only) div
365 $portlet
.find( 'div' ).eq( -1 ).append( '<ul></ul>' );
367 // Select the created element
368 $ul
= $portlet
.find( 'ul' ).eq( 0 );
371 if ( $ul
.length
=== 0 ) {
375 // Unhide portlet if it was hidden before
376 $portlet
.removeClass( 'emptyPortlet' );
378 // Wrap the anchor tag in a list item (and a span if $portlet is a Vector tab)
379 // and back up the selector to the list item
380 if ( $portlet
.hasClass( 'vectorTabs' ) ) {
381 $item
= $link
.wrap( '<li><span></span></li>' ).parent().parent();
383 $item
= $link
.wrap( '<li></li>' ).parent();
386 // Implement the properties passed to the function
388 $item
.attr( 'id', id
);
391 $link
.attr( 'accesskey', accesskey
);
392 tooltip
+= ' [' + accesskey
+ ']';
393 $link
.attr( 'title', tooltip
);
395 if ( accesskey
&& tooltip
) {
396 util
.updateTooltipAccessKeys( $link
);
399 // Where to put our node ?
400 // - nextnode is a DOM element (was the only option before MW 1.17, in wikibits.js)
401 if ( nextnode
&& nextnode
.parentNode
=== $ul
[0] ) {
402 $(nextnode
).before( $item
);
404 // - nextnode is a CSS selector for jQuery
405 } else if ( typeof nextnode
=== 'string' && $ul
.find( nextnode
).length
!== 0 ) {
406 $ul
.find( nextnode
).eq( 0 ).before( $item
);
408 // If the jQuery selector isn't found within the <ul>,
409 // or if nextnode was invalid or not passed at all,
410 // then just append it at the end of the <ul> (this is the default behaviour)
421 * Add a little box at the top of the screen to inform the user of
422 * something, replacing any previous message.
423 * Calling with no arguments, with an empty string or null will hide the message
425 * @param message {mixed} The DOM-element, jQuery object or HTML-string to be put inside the message box.
426 * @param className {String} Used in adding a class; should be different for each call
427 * to allow CSS/JS to hide different boxes. null = no class used.
428 * @return {Boolean} True on success, false on failure.
430 jsMessage: function ( message
, className
) {
431 if ( !arguments
.length
|| message
=== '' || message
=== null ) {
432 $( '#mw-js-message' ).empty().hide();
433 return true; // Emptying and hiding message is intended behaviour, return true
436 // We special-case skin structures provided by the software. Skins that
437 // choose to abandon or significantly modify our formatting can just define
438 // an mw-js-message div to start with.
439 var $messageDiv
= $( '#mw-js-message' );
440 if ( !$messageDiv
.length
) {
441 $messageDiv
= $( '<div id="mw-js-message"></div>' );
442 if ( util
.$content
.parent().length
) {
443 util
.$content
.parent().prepend( $messageDiv
);
450 $messageDiv
.prop( 'class', 'mw-js-message-' + className
);
453 if ( typeof message
=== 'object' ) {
455 $messageDiv
.append( message
);
457 $messageDiv
.html( message
);
460 $messageDiv
.slideDown();
466 * Validate a string as representing a valid e-mail address
467 * according to HTML5 specification. Please note the specification
468 * does not validate a domain with one character.
470 * @todo FIXME: should be moved to or replaced by a JavaScript validation module.
472 * @param mailtxt string E-mail address to be validated.
473 * @return mixed Null if mailtxt was an empty string, otherwise true/false
474 * is determined by validation.
476 validateEmail: function ( mailtxt
) {
477 var rfc5322_atext
, rfc1034_ldh_str
, HTML5_email_regexp
;
479 if ( mailtxt
=== '' ) {
484 * HTML5 defines a string as valid e-mail address if it matches
486 * 1 * ( atext / "." ) "@" ldh-str 1*( "." ldh-str )
488 * - atext : defined in RFC 5322 section 3.2.3
489 * - ldh-str : defined in RFC 1034 section 3.5
491 * (see STD 68 / RFC 5234 http://tools.ietf.org/html/std68):
495 * First, define the RFC 5322 'atext' which is pretty easy:
496 * atext = ALPHA / DIGIT / ; Printable US-ASCII
497 "!" / "#" / ; characters not including
498 "$" / "%" / ; specials. Used for atoms.
508 rfc5322_atext
= "a-z0-9!#$%&'*+\\-/=?^_`{|}~";
511 * Next define the RFC 1034 'ldh-str'
512 * <domain> ::= <subdomain> | " "
513 * <subdomain> ::= <label> | <subdomain> "." <label>
514 * <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
515 * <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
516 * <let-dig-hyp> ::= <let-dig> | "-"
517 * <let-dig> ::= <letter> | <digit>
519 rfc1034_ldh_str
= "a-z0-9\\-";
521 HTML5_email_regexp
= new RegExp(
525 // User part which is liberal :p
526 '[' + rfc5322_atext
+ '\\.]+'
532 '[' + rfc1034_ldh_str
+ ']+'
534 // Optional second part and following are separated by a dot
535 '(?:\\.[' + rfc1034_ldh_str
+ ']+)*'
539 // RegExp is case insensitive
542 return (null !== mailtxt
.match( HTML5_email_regexp
) );
546 * Note: borrows from IP::isIPv4
548 * @param address string
549 * @param allowBlock boolean
552 isIPv4Address: function ( address
, allowBlock
) {
553 if ( typeof address
!== 'string' ) {
557 var block
= allowBlock
? '(?:\\/(?:3[0-2]|[12]?\\d))?' : '',
558 RE_IP_BYTE
= '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])',
559 RE_IP_ADD
= '(?:' + RE_IP_BYTE
+ '\\.){3}' + RE_IP_BYTE
;
561 return address
.search( new RegExp( '^' + RE_IP_ADD
+ block
+ '$' ) ) !== -1;
565 * Note: borrows from IP::isIPv6
567 * @param address string
568 * @param allowBlock boolean
571 isIPv6Address: function ( address
, allowBlock
) {
572 if ( typeof address
!== 'string' ) {
576 var block
= allowBlock
? '(?:\\/(?:12[0-8]|1[01][0-9]|[1-9]?\\d))?' : '',
578 '(?:' + // starts with "::" (including "::")
579 ':(?::|(?::' + '[0-9A-Fa-f]{1,4}' + '){1,7})' +
580 '|' + // ends with "::" (except "::")
581 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){0,6}::' +
582 '|' + // contains no "::"
583 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){7}' +
586 if ( address
.search( new RegExp( '^' + RE_IPV6_ADD
+ block
+ '$' ) ) !== -1 ) {
590 RE_IPV6_ADD
= // contains one "::" in the middle (single '::' check below)
591 '[0-9A-Fa-f]{1,4}' + '(?:::?' + '[0-9A-Fa-f]{1,4}' + '){1,6}';
593 return address
.search( new RegExp( '^' + RE_IPV6_ADD
+ block
+ '$' ) ) !== -1
594 && address
.search( /::/ ) !== -1 && address
.search( /::.*::/ ) === -1;
600 } )( jQuery
, mediaWiki
);