2 * Implements mediaWiki.util library
7 // Local cache and alias
12 * (don't call before document ready)
15 var profile
= $.client
.profile(),
16 $tocTitle
= $( '#toctitle' ),
17 $tocToggleLink
= $( '#togglelink' ),
20 /* Set up $.messageBox */
26 /* Set tooltipAccessKeyPrefix */
28 // Opera on any platform
29 if ( profile
.name
=== 'opera' ) {
30 util
.tooltipAccessKeyPrefix
= 'shift-esc-';
32 // Chrome on any platform
33 } else if ( profile
.name
=== 'chrome' ) {
34 // Chrome on Mac or Chrome on other platform ?
35 util
.tooltipAccessKeyPrefix
= ( profile
.platform
=== 'mac'
36 ? 'ctrl-option-' : 'alt-' );
38 // Non-Windows Safari with webkit_version > 526
39 } else if ( profile
.platform
!== 'win'
40 && profile
.name
=== 'safari'
41 && profile
.layoutVersion
> 526 ) {
42 util
.tooltipAccessKeyPrefix
= 'ctrl-alt-';
44 // Safari/Konqueror on any platform, or any browser on Mac
45 // (but not Safari on Windows)
46 } else if ( !( profile
.platform
=== 'win' && profile
.name
=== 'safari' )
47 && ( profile
.name
=== 'safari'
48 || profile
.platform
=== 'mac'
49 || profile
.name
=== 'konqueror' ) ) {
50 util
.tooltipAccessKeyPrefix
= 'ctrl-';
52 // Firefox 2.x and later
53 } else if ( profile
.name
=== 'firefox' && profile
.versionBase
> '1' ) {
54 util
.tooltipAccessKeyPrefix
= 'alt-shift-';
57 /* Fill $content var */
58 if ( $( '#bodyContent' ).length
) {
59 // Vector, Monobook, Chick etc.
60 util
.$content
= $( '#bodyContent' );
62 } else if ( $( '#mw_contentholder' ).length
) {
64 util
.$content
= $( '#mw_contentholder' );
66 } else if ( $( '#article' ).length
) {
67 // Standard, CologneBlue
68 util
.$content
= $( '#article' );
71 // #content is present on almost all if not all skins. Most skins (the above cases)
72 // have #content too, but as an outer wrapper instead of the article text container.
73 // The skins that don't have an outer wrapper do have #content for everything
74 // so it's a good fallback
75 util
.$content
= $( '#content' );
78 // Table of contents toggle
79 // Only add it if there is a TOC and there is no toggle added already
80 if ( $( '#toc' ).length
&& $tocTitle
.length
&& !$tocToggleLink
.length
) {
81 hideTocCookie
= $.cookie( 'mw_hidetoc' );
82 $tocToggleLink
= $( '<a href="#" class="internal" id="togglelink"></a>' )
83 .text( mw
.msg( 'hidetoc' ) )
84 .click( function( e
) {
86 util
.toggleToc( $(this) );
90 .wrap( '<span class="toctoggle"></span>' )
96 if ( hideTocCookie
=== '1' ) {
97 util
.toggleToc( $tocToggleLink
);
105 * Encode the string like PHP's rawurlencode
107 * @param str string String to be encoded
109 rawurlencode: function( str
) {
111 return encodeURIComponent( str
)
112 .replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' )
113 .replace( /\)/g, '%29' ).replace( /\*/g, '%2A
' ).replace( /~/g, '%7E
' );
117 * Encode page titles for use in a URL
118 * We want / and : to be included as literal characters in our title URLs
119 * as they otherwise fatally break the title
121 * @param str string String to be encoded
123 wikiUrlencode: function( str ) {
124 return this.rawurlencode( str )
125 .replace( /%20/g, '_
' ).replace( /%3A/g, ':' ).replace( /%2F/g, '/' );
129 * Get the link to a page name (relative to wgServer)
131 * @param str string Page name to get the link for.
132 * @return string Location for a page with name of 'str
' or boolean false on error.
134 wikiGetlink: function( str ) {
135 return mw.config.get( 'wgArticlePath
' ).replace( '$1',
136 this.wikiUrlencode( str || mw.config.get( 'wgPageName
' ) ) );
140 * Get address to a script in the wiki root.
141 * For index.php use mw.config.get( 'wgScript
' )
143 * @param str string Name of script (eg. 'api
'), defaults to 'index
'
144 * @return string Address to script (eg. '/w
/api
.php
' )
146 wikiScript: function( str ) {
147 return mw.config.get( 'wgScriptPath
' ) + '/' + ( str || 'index
' ) +
148 mw.config.get( 'wgScriptExtension
' );
152 * Append a new style block to the head
154 * @param text string CSS to be appended
155 * @return CSSStyleSheet
157 addCSS: function( text ) {
158 var s = document.createElement( 'style
' );
160 s.rel = 'stylesheet
';
161 // Insert into document before setting cssText (bug 33305)
162 document.getElementsByTagName('head
')[0].appendChild( s );
163 if ( s.styleSheet ) {
164 s.styleSheet.cssText = text; // IE
166 // Safari sometimes borks on null
167 s.appendChild( document.createTextNode( text + '' ) );
173 * Hide/show the table of contents element
175 * @param $toggleLink jQuery A jQuery object of the toggle link.
176 * @param callback function Function to be called after the toggle is
177 * completed (including the animation) (optional)
178 * @return mixed Boolean visibility of the toc (true if it's visible
)
179 * or Null
if there was no table
of contents
.
181 toggleToc: function( $toggleLink
, callback
) {
182 var $tocList
= $( '#toc ul:first' );
184 // This function shouldn't be called if there's no TOC,
185 // but just in case...
186 if ( $tocList
.length
) {
187 if ( $tocList
.is( ':hidden' ) ) {
188 $tocList
.slideDown( 'fast', callback
);
189 $toggleLink
.text( mw
.msg( 'hidetoc' ) );
190 $( '#toc' ).removeClass( 'tochidden' );
191 $.cookie( 'mw_hidetoc', null, {
197 $tocList
.slideUp( 'fast', callback
);
198 $toggleLink
.text( mw
.msg( 'showtoc' ) );
199 $( '#toc' ).addClass( 'tochidden' );
200 $.cookie( 'mw_hidetoc', '1', {
212 * Grab the URL parameter value for the given parameter.
213 * Returns null if not found.
215 * @param param string The parameter name.
216 * @param url string URL to search through (optional)
217 * @return mixed Parameter value or null.
219 getParamValue: function( param
, url
) {
220 url
= url
|| document
.location
.href
;
221 // Get last match, stop at hash
222 var re
= new RegExp( '^[^#]*[&?]' + $.escapeRE( param
) + '=([^&#]*)' ),
224 if ( m
&& m
.length
> 1 ) {
225 // Beware that decodeURIComponent is not required to understand '+'
226 // by spec, as encodeURIComponent does not produce it.
227 return decodeURIComponent( m
[1].replace( /\+/g, '%20' ) );
234 * Access key prefix. Will be re-defined based on browser/operating system
235 * detection in mw.util.init().
237 tooltipAccessKeyPrefix
: 'alt-',
241 * Regex to match accesskey tooltips.
243 tooltipAccessKeyRegexp
: /\[(ctrl-)?(alt-)?(shift-)?(esc-)?(.)\]$/,
246 * Add the appropriate prefix to the accesskey shown in the tooltip.
247 * If the nodeList parameter is given, only those nodes are updated;
248 * otherwise, all the nodes that will probably have accesskeys by
249 * default are updated.
251 * @param $nodes {Array|jQuery} [optional] A jQuery object, or array
252 * of elements to update.
254 updateTooltipAccessKeys: function( $nodes
) {
256 // Rather than going into a loop of all anchor tags, limit to few elements that
257 // contain the relevant anchor tags.
258 // Input and label are rare enough that no such optimization is needed
259 $nodes
= $( '#column-one a, #mw-head a, #mw-panel a, #p-logo a, input, label' );
260 } else if ( !( $nodes
instanceof $ ) ) {
261 $nodes
= $( $nodes
);
264 $nodes
.attr( 'title', function( i
, val
) {
265 if ( val
&& util
.tooltipAccessKeyRegexp
.exec( val
) ) {
266 return val
.replace( util
.tooltipAccessKeyRegexp
,
267 '[' + util
.tooltipAccessKeyPrefix
+ '$5]' );
275 * A jQuery object that refers to the page-content element
276 * Populated by init().
281 * Add a link to a portlet menu on the page, such as:
283 * p-cactions (Content actions), p-personal (Personal tools),
284 * p-navigation (Navigation), p-tb (Toolbox)
286 * The first three paramters are required, the others are optional and
287 * may be null. Though providing an id and tooltip is recommended.
289 * By default the new link will be added to the end of the list. To
290 * add the link before a given existing item, pass the DOM node
291 * (document.getElementById( 'foobar' )) or the jQuery-selector
292 * ( '#foobar' ) of that item.
294 * @example mw.util.addPortletLink(
295 * 'p-tb', 'http://mediawiki.org/',
296 * 'MediaWiki.org', 't-mworg', 'Go to MediaWiki.org ', 'm', '#t-print'
299 * @param portlet string ID of the target portlet ( 'p-cactions' or 'p-personal' etc.)
300 * @param href string Link URL
301 * @param text string Link text
302 * @param id string ID of the new item, should be unique and preferably have
303 * the appropriate prefix ( 'ca-', 'pt-', 'n-' or 't-' )
304 * @param tooltip string Text to show when hovering over the link, without accesskey suffix
305 * @param accesskey string Access key to activate this link (one character, try
306 * to avoid conflicts. Use $( '[accesskey=x]' ).get() in the console to
307 * see if 'x' is already used.
308 * @param nextnode mixed DOM Node or jQuery-selector string of the item that the new
309 * item should be added before, should be another item in the same
310 * list, it will be ignored otherwise
312 * @return mixed The DOM Node of the added item (a ListItem or Anchor element,
313 * depending on the skin) or null if no element was added to the document.
315 addPortletLink: function( portlet
, href
, text
, id
, tooltip
, accesskey
, nextnode
) {
316 var $item
, $link
, $portlet
, $ul
;
318 // Check if there's atleast 3 arguments to prevent a TypeError
319 if ( arguments
.length
< 3 ) {
322 // Setup the anchor tag
323 $link
= $( '<a>' ).attr( 'href', href
).text( text
);
325 $link
.attr( 'title', tooltip
);
328 // Some skins don't have any portlets
329 // just add it to the bottom of their 'sidebar' element as a fallback
330 switch ( mw
.config
.get( 'skin' ) ) {
333 $( '#quickbar' ).append( $link
.after( '<br/>' ) );
336 $( '#searchform' ).before( $link
).before( ' | ' );
338 default : // Skins like chick, modern, monobook, myskin, simple, vector...
340 // Select the specified portlet
341 $portlet
= $( '#' + portlet
);
342 if ( $portlet
.length
=== 0 ) {
345 // Select the first (most likely only) unordered list inside the portlet
346 $ul
= $portlet
.find( 'ul' );
348 // If it didn't have an unordered list yet, create it
349 if ( $ul
.length
=== 0 ) {
350 // If there's no <div> inside, append it to the portlet directly
351 if ( $portlet
.find( 'div:first' ).length
=== 0 ) {
352 $portlet
.append( '<ul></ul>' );
354 // otherwise if there's a div (such as div.body or div.pBody)
355 // append the <ul> to last (most likely only) div
356 $portlet
.find( 'div' ).eq( -1 ).append( '<ul></ul>' );
358 // Select the created element
359 $ul
= $portlet
.find( 'ul' ).eq( 0 );
362 if ( $ul
.length
=== 0 ) {
366 // Unhide portlet if it was hidden before
367 $portlet
.removeClass( 'emptyPortlet' );
369 // Wrap the anchor tag in a list item (and a span if $portlet is a Vector tab)
370 // and back up the selector to the list item
371 if ( $portlet
.hasClass( 'vectorTabs' ) ) {
372 $item
= $link
.wrap( '<li><span></span></li>' ).parent().parent();
374 $item
= $link
.wrap( '<li></li>' ).parent();
377 // Implement the properties passed to the function
379 $item
.attr( 'id', id
);
382 $link
.attr( 'accesskey', accesskey
);
383 tooltip
+= ' [' + accesskey
+ ']';
384 $link
.attr( 'title', tooltip
);
386 if ( accesskey
&& tooltip
) {
387 this.updateTooltipAccessKeys( $link
);
390 // Where to put our node ?
391 // - nextnode is a DOM element (was the only option before MW 1.17, in wikibits.js)
392 if ( nextnode
&& nextnode
.parentNode
=== $ul
[0] ) {
393 $(nextnode
).before( $item
);
395 // - nextnode is a CSS selector for jQuery
396 } else if ( typeof nextnode
=== 'string' && $ul
.find( nextnode
).length
!== 0 ) {
397 $ul
.find( nextnode
).eq( 0 ).before( $item
);
399 // If the jQuery selector isn't found within the <ul>,
400 // or if nextnode was invalid or not passed at all,
401 // then just append it at the end of the <ul> (this is the default behaviour)
412 * Add a little box at the top of the screen to inform the user of
413 * something, replacing any previous message.
414 * Calling with no arguments, with an empty string or null will hide the message
416 * @param message {mixed} The DOM-element, jQuery object or HTML-string to be put inside the message box.
417 * @param className {String} Used in adding a class; should be different for each call
418 * to allow CSS/JS to hide different boxes. null = no class used.
419 * @return {Boolean} True on success, false on failure.
421 jsMessage: function( message
, className
) {
422 if ( !arguments
.length
|| message
=== '' || message
=== null ) {
423 $( '#mw-js-message' ).empty().hide();
424 return true; // Emptying and hiding message is intended behaviour, return true
427 // We special-case skin structures provided by the software. Skins that
428 // choose to abandon or significantly modify our formatting can just define
429 // an mw-js-message div to start with.
430 var $messageDiv
= $( '#mw-js-message' );
431 if ( !$messageDiv
.length
) {
432 $messageDiv
= $( '<div id="mw-js-message"></div>' );
433 if ( util
.$content
.parent().length
) {
434 util
.$content
.parent().prepend( $messageDiv
);
441 $messageDiv
.prop( 'class', 'mw-js-message-' + className
);
444 if ( typeof message
=== 'object' ) {
446 $messageDiv
.append( message
);
448 $messageDiv
.html( message
);
451 $messageDiv
.slideDown();
457 * Validate a string as representing a valid e-mail address
458 * according to HTML5 specification. Please note the specification
459 * does not validate a domain with one character.
461 * @todo FIXME: should be moved to or replaced by a JavaScript validation module.
463 * @param mailtxt string E-mail address to be validated.
464 * @return mixed Null if mailtxt was an empty string, otherwise true/false
465 * is determined by validation.
467 validateEmail: function( mailtxt
) {
468 if( mailtxt
=== '' ) {
473 * HTML5 defines a string as valid e-mail address if it matches
475 * 1 * ( atext / "." ) "@" ldh-str 1*( "." ldh-str )
477 * - atext : defined in RFC 5322 section 3.2.3
478 * - ldh-str : defined in RFC 1034 section 3.5
480 * (see STD 68 / RFC 5234 http://tools.ietf.org/html/std68):
484 * First, define the RFC 5322 'atext' which is pretty easy :
485 * atext = ALPHA / DIGIT / ; Printable US-ASCII
486 "!" / "#" / ; characters not including
487 "$" / "%" / ; specials. Used for atoms.
497 var rfc5322_atext
= "a-z0-9!#$%&'*+\\-/=?^_`{|}~",
500 * Next define the RFC 1034 'ldh-str'
501 * <domain> ::= <subdomain> | " "
502 * <subdomain> ::= <label> | <subdomain> "." <label>
503 * <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
504 * <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
505 * <let-dig-hyp> ::= <let-dig> | "-"
506 * <let-dig> ::= <letter> | <digit>
508 rfc1034_ldh_str
= "a-z0-9\\-",
510 HTML5_email_regexp
= new RegExp(
514 // User part which is liberal :p
515 '[' + rfc5322_atext
+ '\\.]+'
521 '[' + rfc1034_ldh_str
+ ']+'
523 // Optional second part and following are separated by a dot
524 '(?:\\.[' + rfc1034_ldh_str
+ ']+)*'
528 // RegExp is case insensitive
531 return (null !== mailtxt
.match( HTML5_email_regexp
) );
535 * Note: borrows from IP::isIPv4
537 * @param address string
538 * @param allowBlock boolean
541 isIPv4Address: function( address
, allowBlock
) {
542 if ( typeof address
!== 'string' ) {
546 var block
= allowBlock
? '(?:\\/(?:3[0-2]|[12]?\\d))?' : '',
547 RE_IP_BYTE
= '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])',
548 RE_IP_ADD
= '(?:' + RE_IP_BYTE
+ '\\.){3}' + RE_IP_BYTE
;
550 return address
.search( new RegExp( '^' + RE_IP_ADD
+ block
+ '$' ) ) !== -1;
554 * Note: borrows from IP::isIPv6
556 * @param address string
557 * @param allowBlock boolean
560 isIPv6Address: function( address
, allowBlock
) {
561 if ( typeof address
!== 'string' ) {
565 var block
= allowBlock
? '(?:\\/(?:12[0-8]|1[01][0-9]|[1-9]?\\d))?' : '',
567 '(?:' + // starts with "::" (including "::")
568 ':(?::|(?::' + '[0-9A-Fa-f]{1,4}' + '){1,7})' +
569 '|' + // ends with "::" (except "::")
570 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){0,6}::' +
571 '|' + // contains no "::"
572 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){7}' +
575 if ( address
.search( new RegExp( '^' + RE_IPV6_ADD
+ block
+ '$' ) ) !== -1 ) {
579 RE_IPV6_ADD
= // contains one "::" in the middle (single '::' check below)
580 '[0-9A-Fa-f]{1,4}' + '(?:::?' + '[0-9A-Fa-f]{1,4}' + '){1,6}';
582 return address
.search( new RegExp( '^' + RE_IPV6_ADD
+ block
+ '$' ) ) !== -1
583 && address
.search( /::/ ) !== -1 && address
.search( /::.*::/ ) === -1;
589 } )( jQuery
, mediaWiki
);