Fix usage of the jQuery global in a few spots.
[lhc/web/wiklou.git] / resources / mediawiki / mediawiki.util.js
1 /**
2 * Utilities
3 */
4 ( function( $ ) {
5
6 // Local cache and alias
7 var util = mw.util = {
8
9 /* Initialisation */
10 /**
11 * @var boolean Wether or not already initialised
12 */
13 'initialised' : false,
14 'init' : function() {
15 if ( this.initialised === false ) {
16 this.initialised = true;
17
18 // Following the initialisation after the DOM is ready
19 $(document).ready( function() {
20
21 /* Set up $.messageBox */
22 $.messageBoxNew( {
23 'id': 'mw-js-message',
24 'parent': '#content'
25 } );
26
27 // Shortcut to client profile return
28 var profile = $.client.profile();
29
30 /* Set tooltipAccessKeyPrefix */
31
32 // Opera on any platform
33 if ( profile.name == 'opera' ) {
34 util.tooltipAccessKeyPrefix = 'shift-esc-';
35
36 // Chrome on any platform
37 } else if ( profile.name == 'chrome' ) {
38 // Chrome on Mac or Chrome on other platform ?
39 util.tooltipAccessKeyPrefix = ( profile.platform == 'mac'
40 ? 'ctrl-option-' : 'alt-' );
41
42 // Non-Windows Safari with webkit_version > 526
43 } else if ( profile.platform !== 'win'
44 && profile.name == 'safari'
45 && profile.layoutVersion > 526 ) {
46 util.tooltipAccessKeyPrefix = 'ctrl-alt-';
47
48 // Safari/Konqueror on any platform, or any browser on Mac
49 // (but not Safari on Windows)
50 } else if ( !( profile.platform == 'win' && profile.name == 'safari' )
51 && ( profile.name == 'safari'
52 || profile.platform == 'mac'
53 || profile.name == 'konqueror' ) ) {
54 util.tooltipAccessKeyPrefix = 'ctrl-';
55
56 // Firefox 2.x and later
57 } else if ( profile.name == 'firefox' && profile.versionBase > '1' ) {
58 util.tooltipAccessKeyPrefix = 'alt-shift-';
59 }
60
61 /* Fill $content var */
62 if ( $( '#bodyContent' ).length ) {
63 // Vector, Monobook, Chick etc.
64 util.$content = $( '#bodyContent' );
65
66 } else if ( $( '#mw_contentholder' ).length ) {
67 // Modern
68 util.$content = $( '#mw_contentholder' );
69
70 } else if ( $( '#article' ).length ) {
71 // Standard, CologneBlue
72 util.$content = $( '#article' );
73
74 } else {
75 // #content is present on almost all if not all skins. Most skins (the above cases)
76 // have #content too, but as an outer wrapper instead of the article text container.
77 // The skins that don't have an outer wrapper do have #content for everything
78 // so it's a good fallback
79 util.$content = $( '#content' );
80 }
81
82 /* Table of Contents toggle */
83 var $tocContainer = $( '#toc' ),
84 $tocTitle = $( '#toctitle' ),
85 $tocToggleLink = $( '#togglelink' );
86 // Only add it if there is a TOC and there is no toggle added already
87 if ( $tocContainer.length && $tocTitle.length && !$tocToggleLink.length ) {
88 var hideTocCookie = $.cookie( 'mw_hidetoc' );
89 $tocToggleLink = $( '<a href="#" class="internal" id="togglelink"></a>' )
90 .text( mw.msg( 'hidetoc' ) )
91 .click( function(e){
92 e.preventDefault();
93 util.toggleToc( $(this) );
94 } );
95 $tocTitle.append( $tocToggleLink.wrap( '<span class="toctoggle"></span>' ).parent().prepend( '&nbsp;[' ).append( ']&nbsp;' ) );
96
97 if ( hideTocCookie == '1' ) {
98 // Cookie says user want toc hidden
99 $tocToggleLink.click();
100 }
101 }
102 } );
103
104 return true;
105 }
106 return false;
107 },
108
109 /* Main body */
110
111 /**
112 * Encode the string like PHP's rawurlencode
113 *
114 * @param str string String to be encoded
115 */
116 'rawurlencode' : function( str ) {
117 str = ( str + '' ).toString();
118 return encodeURIComponent( str )
119 .replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' )
120 .replace( /\)/g, '%29' ).replace( /\*/g, '%2A' ).replace( /~/g, '%7E' );
121 },
122
123 /**
124 * Encode page titles for use in a URL
125 * We want / and : to be included as literal characters in our title URLs
126 * as they otherwise fatally break the title
127 *
128 * @param str string String to be encoded
129 */
130 'wikiUrlencode' : function( str ) {
131 return this.rawurlencode( str )
132 .replace( /%20/g, '_' ).replace( /%3A/g, ':' ).replace( /%2F/g, '/' );
133 },
134
135 /**
136 * Get the link to a page name (relative to wgServer)
137 *
138 * @param str string Page name to get the link for.
139 * @return string Location for a page with name of 'str' or boolean false on error.
140 */
141 'wikiGetlink' : function( str ) {
142 return mw.config.get( 'wgArticlePath' ).replace( '$1',
143 this.wikiUrlencode( str || mw.config.get( 'wgPageName' ) ) );
144 },
145
146 /**
147 * Get address to a script in the wiki root.
148 * For index.php use mw.config.get( 'wgScript' )
149 *
150 * @param str string Name of script (eg. 'api'), defaults to 'index'
151 * @return string Address to script (eg. '/w/api.php' )
152 */
153 'wikiScript' : function( str ) {
154 return mw.config.get( 'wgScriptPath' ) + '/' + ( str || 'index' ) + mw.config.get( 'wgScriptExtension' );
155 },
156
157 /**
158 * Append a new style block to the head
159 *
160 * @param text string CSS to be appended
161 * @return CSSStyleSheet
162 */
163 'addCSS' : function( text ) {
164 var s = document.createElement( 'style' );
165 s.type = 'text/css';
166 s.rel = 'stylesheet';
167 if ( s.styleSheet ) {
168 s.styleSheet.cssText = text; // IE
169 } else {
170 s.appendChild( document.createTextNode( text + '' ) ); // Safari sometimes borks on null
171 }
172 document.getElementsByTagName('head')[0].appendChild( s );
173 return s.sheet || s;
174 },
175
176 /**
177 * Hide/show the table of contents element
178 *
179 * @param $toggleLink jQuery A jQuery object of the toggle link.
180 * @param callback function Function to be called after the toggle is
181 * completed (including the animation) (optional)
182 * @return mixed Boolean visibility of the toc (true if it's visible)
183 * or Null if there was no table of contents.
184 */
185 'toggleToc' : function( $toggleLink, callback ) {
186 var $tocList = $( '#toc ul:first' );
187
188 // This function shouldn't be called if there's no TOC,
189 // but just in case...
190 if ( $tocList.length ) {
191 if ( $tocList.is( ':hidden' ) ) {
192 $tocList.slideDown( 'fast', callback );
193 $toggleLink.text( mw.msg( 'hidetoc' ) );
194 $( '#toc' ).removeClass( 'tochidden' );
195 $.cookie( 'mw_hidetoc', null, {
196 expires: 30,
197 path: '/'
198 } );
199 return true;
200 } else {
201 $tocList.slideUp( 'fast', callback );
202 $toggleLink.text( mw.msg( 'showtoc' ) );
203 $( '#toc' ).addClass( 'tochidden' );
204 $.cookie( 'mw_hidetoc', '1', {
205 expires: 30,
206 path: '/'
207 } );
208 return false;
209 }
210 } else {
211 return null;
212 }
213 },
214
215 /**
216 * Grab the URL parameter value for the given parameter.
217 * Returns null if not found.
218 *
219 * @param param string The parameter name.
220 * @param url string URL to search through (optional)
221 * @return mixed Parameter value or null.
222 */
223 'getParamValue' : function( param, url ) {
224 url = url ? url : document.location.href;
225 // Get last match, stop at hash
226 var re = new RegExp( '^[^#]*[&?]' + $.escapeRE( param ) + '=([^&#]*)' );
227 var m = re.exec( url );
228 if ( m && m.length > 1 ) {
229 return decodeURIComponent( m[1] );
230 }
231 return null;
232 },
233
234 /**
235 * @var string
236 * Access key prefix. Will be re-defined based on browser/operating system
237 * detection in mw.util.init().
238 */
239 'tooltipAccessKeyPrefix' : 'alt-',
240
241 /**
242 * @var RegExp
243 * Regex to match accesskey tooltips.
244 */
245 'tooltipAccessKeyRegexp': /\[(ctrl-)?(alt-)?(shift-)?(esc-)?(.)\]$/,
246
247 /**
248 * Add the appropriate prefix to the accesskey shown in the tooltip.
249 * If the nodeList parameter is given, only those nodes are updated;
250 * otherwise, all the nodes that will probably have accesskeys by
251 * default are updated.
252 *
253 * @param nodeList {Array|jQuery} (optional) A jQuery object, or array of elements to update.
254 */
255 'updateTooltipAccessKeys' : function( nodeList ) {
256 var $nodes;
257 if ( !nodeList ) {
258
259 // Rather than scanning all links, just the elements that
260 // contain the relevant links
261 this.updateTooltipAccessKeys(
262 $( '#column-one a, #mw-head a, #mw-panel a, #p-logo a' ) );
263
264 // these are rare enough that no such optimization is needed
265 this.updateTooltipAccessKeys( $( 'input' ) );
266 this.updateTooltipAccessKeys( $( 'label' ) );
267
268 return;
269
270 } else if ( nodeList instanceof $ ) {
271 $nodes = nodeList;
272 } else {
273 $nodes = $( nodeList );
274 }
275
276 $nodes.each( function ( i ) {
277 var tip = $(this).attr( 'title' );
278 if ( !!tip && util.tooltipAccessKeyRegexp.exec( tip ) ) {
279 tip = tip.replace( util.tooltipAccessKeyRegexp,
280 '[' + util.tooltipAccessKeyPrefix + "$5]" );
281 $(this).attr( 'title', tip );
282 }
283 } );
284 },
285
286 /*
287 * @var jQuery
288 * A jQuery object that refers to the page-content element
289 * Populated by init().
290 */
291 '$content' : null,
292
293 /**
294 * Add a link to a portlet menu on the page, such as:
295 *
296 * p-cactions (Content actions), p-personal (Personal tools),
297 * p-navigation (Navigation), p-tb (Toolbox)
298 *
299 * The first three paramters are required, the others are optional and
300 * may be null. Though providing an id and tooltip is recommended.
301 *
302 * By default the new link will be added to the end of the list. To
303 * add the link before a given existing item, pass the DOM node
304 * (document.getElementById( 'foobar' )) or the jQuery-selector
305 * ( '#foobar' ) of that item.
306 *
307 * @example mw.util.addPortletLink(
308 * 'p-tb', 'http://mediawiki.org/',
309 * 'MediaWiki.org', 't-mworg', 'Go to MediaWiki.org ', 'm', '#t-print'
310 * )
311 *
312 * @param portlet string ID of the target portlet ( 'p-cactions' or 'p-personal' etc.)
313 * @param href string Link URL
314 * @param text string Link text
315 * @param id string ID of the new item, should be unique and preferably have
316 * the appropriate prefix ( 'ca-', 'pt-', 'n-' or 't-' )
317 * @param tooltip string Text to show when hovering over the link, without accesskey suffix
318 * @param accesskey string Access key to activate this link (one character, try
319 * to avoid conflicts. Use $( '[accesskey=x]' ).get() in the console to
320 * see if 'x' is already used.
321 * @param nextnode mixed DOM Node or jQuery-selector string of the item that the new
322 * item should be added before, should be another item in the same
323 * list, it will be ignored otherwise
324 *
325 * @return mixed The DOM Node of the added item (a ListItem or Anchor element,
326 * depending on the skin) or null if no element was added to the document.
327 */
328 'addPortletLink' : function( portlet, href, text, id, tooltip, accesskey, nextnode ) {
329
330 // Check if there's atleast 3 arguments to prevent a TypeError
331 if ( arguments.length < 3 ) {
332 return null;
333 }
334 // Setup the anchor tag
335 var $link = $( '<a></a>' ).attr( 'href', href ).text( text );
336 if ( tooltip ) {
337 $link.attr( 'title', tooltip );
338 }
339
340 // Some skins don't have any portlets
341 // just add it to the bottom of their 'sidebar' element as a fallback
342 switch ( mw.config.get( 'skin' ) ) {
343 case 'standard' :
344 case 'cologneblue' :
345 $( '#quickbar' ).append( $link.after( '<br/>' ) );
346 return $link[0];
347 case 'nostalgia' :
348 $( '#searchform' ).before( $link).before( ' &#124; ' );
349 return $link[0];
350 default : // Skins like chick, modern, monobook, myskin, simple, vector...
351
352 // Select the specified portlet
353 var $portlet = $( '#' + portlet );
354 if ( $portlet.length === 0 ) {
355 return null;
356 }
357 // Select the first (most likely only) unordered list inside the portlet
358 var $ul = $portlet.find( 'ul' );
359
360 // If it didn't have an unordered list yet, create it
361 if ( $ul.length === 0 ) {
362 // If there's no <div> inside, append it to the portlet directly
363 if ( $portlet.find( 'div:first' ).length === 0 ) {
364 $portlet.append( '<ul></ul>' );
365 } else {
366 // otherwise if there's a div (such as div.body or div.pBody)
367 // append the <ul> to last (most likely only) div
368 $portlet.find( 'div' ).eq( -1 ).append( '<ul></ul>' );
369 }
370 // Select the created element
371 $ul = $portlet.find( 'ul' ).eq( 0 );
372 }
373 // Just in case..
374 if ( $ul.length === 0 ) {
375 return null;
376 }
377
378 // Unhide portlet if it was hidden before
379 $portlet.removeClass( 'emptyPortlet' );
380
381 // Wrap the anchor tag in a list item (and a span if $portlet is a Vector tab)
382 // and back up the selector to the list item
383 var $item;
384 if ( $portlet.hasClass( 'vectorTabs' ) ) {
385 $item = $link.wrap( '<li><span></span></li>' ).parent().parent();
386 } else {
387 $item = $link.wrap( '<li></li>' ).parent();
388 }
389
390 // Implement the properties passed to the function
391 if ( id ) {
392 $item.attr( 'id', id );
393 }
394 if ( accesskey ) {
395 $link.attr( 'accesskey', accesskey );
396 tooltip += ' [' + accesskey + ']';
397 $link.attr( 'title', tooltip );
398 }
399 if ( accesskey && tooltip ) {
400 this.updateTooltipAccessKeys( $link );
401 }
402
403 // Where to put our node ?
404 // - nextnode is a DOM element (before MW 1.17, in wikibits.js, this was the only option)
405 if ( nextnode && nextnode.parentNode == $ul[0] ) {
406 $(nextnode).before( $item );
407
408 // - nextnode is a CSS selector for jQuery
409 } else if ( typeof nextnode == 'string' && $ul.find( nextnode ).length !== 0 ) {
410 $ul.find( nextnode ).eq( 0 ).before( $item );
411
412
413 // If the jQuery selector isn't found within the <ul>,
414 // or if nextnode was invalid or not passed at all,
415 // then just append it at the end of the <ul> (this is the default behaviour)
416 } else {
417 $ul.append( $item );
418 }
419
420
421 return $item[0];
422 }
423 },
424
425 /**
426 * Add a little box at the top of the screen to inform the user of
427 * something, replacing any previous message.
428 * Calling with no arguments, with an empty string or null will hide the message
429 *
430 * @param message mixed The DOM-element or HTML-string to be put inside the message box.
431 * @param className string Used in adding a class; should be different for each call
432 * to allow CSS/JS to hide different boxes. null = no class used.
433 * @return boolean True on success, false on failure.
434 */
435 'jsMessage' : function( message, className ) {
436
437 if ( !arguments.length || message === '' || message === null ) {
438
439 $( '#mw-js-message' ).empty().hide();
440 return true; // Emptying and hiding message is intended behaviour, return true
441
442 } else {
443 // We special-case skin structures provided by the software. Skins that
444 // choose to abandon or significantly modify our formatting can just define
445 // an mw-js-message div to start with.
446 var $messageDiv = $( '#mw-js-message' );
447 if ( !$messageDiv.length ) {
448 $messageDiv = $( '<div id="mw-js-message">' );
449 if ( util.$content.parent().length ) {
450 util.$content.parent().prepend( $messageDiv );
451 } else {
452 return false;
453 }
454 }
455
456 if ( className ) {
457 $messageDiv.attr( 'class', 'mw-js-message-' + className );
458 }
459
460 if ( typeof message === 'object' ) {
461 $messageDiv.empty();
462 $messageDiv.append( message ); // Append new content
463 } else {
464 $messageDiv.html( message );
465 }
466
467 $messageDiv.slideDown();
468 return true;
469 }
470 },
471
472 /**
473 * Validate a string as representing a valid e-mail address
474 * according to HTML5 specification. Please note the specification
475 * does not validate a domain with one character.
476 *
477 * @todo FIXME: should be moved to or replaced by a JavaScript validation module.
478 *
479 * @param mailtxt string E-mail address to be validated.
480 * @return mixed Null if mailtxt was an empty string, otherwise true/false
481 * is determined by validation.
482 */
483 'validateEmail' : function( mailtxt ) {
484 if( mailtxt === '' ) {
485 return null;
486 }
487
488 /**
489 * HTML5 defines a string as valid e-mail address if it matches
490 * the ABNF:
491 * 1 * ( atext / "." ) "@" ldh-str 1*( "." ldh-str )
492 * With:
493 * - atext : defined in RFC 5322 section 3.2.3
494 * - ldh-str : defined in RFC 1034 section 3.5
495 *
496 * (see STD 68 / RFC 5234 http://tools.ietf.org/html/std68):
497 */
498
499 /**
500 * First, define the RFC 5322 'atext' which is pretty easy :
501 * atext = ALPHA / DIGIT / ; Printable US-ASCII
502 "!" / "#" / ; characters not including
503 "$" / "%" / ; specials. Used for atoms.
504 "&" / "'" /
505 "*" / "+" /
506 "-" / "/" /
507 "=" / "?" /
508 "^" / "_" /
509 "`" / "{" /
510 "|" / "}" /
511 "~"
512 */
513 var rfc5322_atext = "a-z0-9!#$%&'*+\\-/=?^_`{|}~",
514
515 /**
516 * Next define the RFC 1034 'ldh-str'
517 * <domain> ::= <subdomain> | " "
518 * <subdomain> ::= <label> | <subdomain> "." <label>
519 * <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
520 * <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
521 * <let-dig-hyp> ::= <let-dig> | "-"
522 * <let-dig> ::= <letter> | <digit>
523 */
524 rfc1034_ldh_str = "a-z0-9\\-",
525
526 HTML5_email_regexp = new RegExp(
527 // start of string
528 '^'
529 +
530 // User part which is liberal :p
531 '[' + rfc5322_atext + '\\.]+'
532 +
533 // 'at'
534 '@'
535 +
536 // Domain first part
537 '[' + rfc1034_ldh_str + ']+'
538 +
539 // Optional second part and following are separated by a dot
540 '(?:\\.[' + rfc1034_ldh_str + ']+)*'
541 +
542 // End of string
543 '$',
544 // RegExp is case insensitive
545 'i'
546 );
547 return (null !== mailtxt.match( HTML5_email_regexp ) );
548 },
549
550 /**
551 * Note: borrows from IP::isIPv4
552 *
553 * @param address string
554 * @param allowBlock boolean
555 * @return boolean
556 */
557 'isIPv4Address' : function( address, allowBlock ) {
558 if ( typeof address !== 'string' ) {
559 return false;
560 }
561 var block = allowBlock ? '(?:\\/(?:3[0-2]|[12]?\\d))?' : '';
562 var RE_IP_BYTE = '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])';
563 var RE_IP_ADD = '(?:' + RE_IP_BYTE + '\\.){3}' + RE_IP_BYTE;
564 return address.search( new RegExp( '^' + RE_IP_ADD + block + '$' ) ) != -1;
565 },
566 /**
567 * Note: borrows from IP::isIPv6
568 *
569 * @param address string
570 * @param allowBlock boolean
571 * @return boolean
572 */
573 'isIPv6Address' : function( address, allowBlock ) {
574 if ( typeof address !== 'string' ) {
575 return false;
576 }
577 var block = allowBlock ? '(?:\\/(?:12[0-8]|1[01][0-9]|[1-9]?\\d))?' : '';
578 var RE_IPV6_ADD =
579 '(?:' + // starts with "::" (including "::")
580 ':(?::|(?::' + '[0-9A-Fa-f]{1,4}' + '){1,7})' +
581 '|' + // ends with "::" (except "::")
582 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){0,6}::' +
583 '|' + // contains no "::"
584 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){7}' +
585 ')';
586 if ( address.search( new RegExp( '^' + RE_IPV6_ADD + block + '$' ) ) != -1 ) {
587 return true;
588 }
589 RE_IPV6_ADD = // contains one "::" in the middle (single '::' check below)
590 '[0-9A-Fa-f]{1,4}' + '(?:::?' + '[0-9A-Fa-f]{1,4}' + '){1,6}';
591 return address.search( new RegExp( '^' + RE_IPV6_ADD + block + '$' ) ) != -1
592 && address.search( /::/ ) != -1 && address.search( /::.*::/ ) == -1;
593 }
594
595 };
596
597 util.init();
598
599 } )( jQuery );