Followup r95332 (bug 30441 fix) -- Roan pointed out that I forgot to do a global...
[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 // Beware that decodeURIComponent is not required to understand '+'
230 // by spec, as encodeURIComponent does not produce it.
231 return decodeURIComponent( m[1].replace( /\+/g, '%20' ) );
232 }
233 return null;
234 },
235
236 /**
237 * @var string
238 * Access key prefix. Will be re-defined based on browser/operating system
239 * detection in mw.util.init().
240 */
241 'tooltipAccessKeyPrefix' : 'alt-',
242
243 /**
244 * @var RegExp
245 * Regex to match accesskey tooltips.
246 */
247 'tooltipAccessKeyRegexp': /\[(ctrl-)?(alt-)?(shift-)?(esc-)?(.)\]$/,
248
249 /**
250 * Add the appropriate prefix to the accesskey shown in the tooltip.
251 * If the nodeList parameter is given, only those nodes are updated;
252 * otherwise, all the nodes that will probably have accesskeys by
253 * default are updated.
254 *
255 * @param nodeList {Array|jQuery} (optional) A jQuery object, or array of elements to update.
256 */
257 'updateTooltipAccessKeys' : function( nodeList ) {
258 var $nodes;
259 if ( !nodeList ) {
260
261 // Rather than scanning all links, just the elements that
262 // contain the relevant links
263 this.updateTooltipAccessKeys(
264 $( '#column-one a, #mw-head a, #mw-panel a, #p-logo a' ) );
265
266 // these are rare enough that no such optimization is needed
267 this.updateTooltipAccessKeys( $( 'input' ) );
268 this.updateTooltipAccessKeys( $( 'label' ) );
269
270 return;
271
272 } else if ( nodeList instanceof $ ) {
273 $nodes = nodeList;
274 } else {
275 $nodes = $( nodeList );
276 }
277
278 $nodes.each( function ( i ) {
279 var tip = $(this).attr( 'title' );
280 if ( !!tip && util.tooltipAccessKeyRegexp.exec( tip ) ) {
281 tip = tip.replace( util.tooltipAccessKeyRegexp,
282 '[' + util.tooltipAccessKeyPrefix + "$5]" );
283 $(this).attr( 'title', tip );
284 }
285 } );
286 },
287
288 /*
289 * @var jQuery
290 * A jQuery object that refers to the page-content element
291 * Populated by init().
292 */
293 '$content' : null,
294
295 /**
296 * Add a link to a portlet menu on the page, such as:
297 *
298 * p-cactions (Content actions), p-personal (Personal tools),
299 * p-navigation (Navigation), p-tb (Toolbox)
300 *
301 * The first three paramters are required, the others are optional and
302 * may be null. Though providing an id and tooltip is recommended.
303 *
304 * By default the new link will be added to the end of the list. To
305 * add the link before a given existing item, pass the DOM node
306 * (document.getElementById( 'foobar' )) or the jQuery-selector
307 * ( '#foobar' ) of that item.
308 *
309 * @example mw.util.addPortletLink(
310 * 'p-tb', 'http://mediawiki.org/',
311 * 'MediaWiki.org', 't-mworg', 'Go to MediaWiki.org ', 'm', '#t-print'
312 * )
313 *
314 * @param portlet string ID of the target portlet ( 'p-cactions' or 'p-personal' etc.)
315 * @param href string Link URL
316 * @param text string Link text
317 * @param id string ID of the new item, should be unique and preferably have
318 * the appropriate prefix ( 'ca-', 'pt-', 'n-' or 't-' )
319 * @param tooltip string Text to show when hovering over the link, without accesskey suffix
320 * @param accesskey string Access key to activate this link (one character, try
321 * to avoid conflicts. Use $( '[accesskey=x]' ).get() in the console to
322 * see if 'x' is already used.
323 * @param nextnode mixed DOM Node or jQuery-selector string of the item that the new
324 * item should be added before, should be another item in the same
325 * list, it will be ignored otherwise
326 *
327 * @return mixed The DOM Node of the added item (a ListItem or Anchor element,
328 * depending on the skin) or null if no element was added to the document.
329 */
330 'addPortletLink' : function( portlet, href, text, id, tooltip, accesskey, nextnode ) {
331
332 // Check if there's atleast 3 arguments to prevent a TypeError
333 if ( arguments.length < 3 ) {
334 return null;
335 }
336 // Setup the anchor tag
337 var $link = $( '<a></a>' ).attr( 'href', href ).text( text );
338 if ( tooltip ) {
339 $link.attr( 'title', tooltip );
340 }
341
342 // Some skins don't have any portlets
343 // just add it to the bottom of their 'sidebar' element as a fallback
344 switch ( mw.config.get( 'skin' ) ) {
345 case 'standard' :
346 case 'cologneblue' :
347 $( '#quickbar' ).append( $link.after( '<br/>' ) );
348 return $link[0];
349 case 'nostalgia' :
350 $( '#searchform' ).before( $link).before( ' &#124; ' );
351 return $link[0];
352 default : // Skins like chick, modern, monobook, myskin, simple, vector...
353
354 // Select the specified portlet
355 var $portlet = $( '#' + portlet );
356 if ( $portlet.length === 0 ) {
357 return null;
358 }
359 // Select the first (most likely only) unordered list inside the portlet
360 var $ul = $portlet.find( 'ul' );
361
362 // If it didn't have an unordered list yet, create it
363 if ( $ul.length === 0 ) {
364 // If there's no <div> inside, append it to the portlet directly
365 if ( $portlet.find( 'div:first' ).length === 0 ) {
366 $portlet.append( '<ul></ul>' );
367 } else {
368 // otherwise if there's a div (such as div.body or div.pBody)
369 // append the <ul> to last (most likely only) div
370 $portlet.find( 'div' ).eq( -1 ).append( '<ul></ul>' );
371 }
372 // Select the created element
373 $ul = $portlet.find( 'ul' ).eq( 0 );
374 }
375 // Just in case..
376 if ( $ul.length === 0 ) {
377 return null;
378 }
379
380 // Unhide portlet if it was hidden before
381 $portlet.removeClass( 'emptyPortlet' );
382
383 // Wrap the anchor tag in a list item (and a span if $portlet is a Vector tab)
384 // and back up the selector to the list item
385 var $item;
386 if ( $portlet.hasClass( 'vectorTabs' ) ) {
387 $item = $link.wrap( '<li><span></span></li>' ).parent().parent();
388 } else {
389 $item = $link.wrap( '<li></li>' ).parent();
390 }
391
392 // Implement the properties passed to the function
393 if ( id ) {
394 $item.attr( 'id', id );
395 }
396 if ( accesskey ) {
397 $link.attr( 'accesskey', accesskey );
398 tooltip += ' [' + accesskey + ']';
399 $link.attr( 'title', tooltip );
400 }
401 if ( accesskey && tooltip ) {
402 this.updateTooltipAccessKeys( $link );
403 }
404
405 // Where to put our node ?
406 // - nextnode is a DOM element (before MW 1.17, in wikibits.js, this was the only option)
407 if ( nextnode && nextnode.parentNode == $ul[0] ) {
408 $(nextnode).before( $item );
409
410 // - nextnode is a CSS selector for jQuery
411 } else if ( typeof nextnode == 'string' && $ul.find( nextnode ).length !== 0 ) {
412 $ul.find( nextnode ).eq( 0 ).before( $item );
413
414
415 // If the jQuery selector isn't found within the <ul>,
416 // or if nextnode was invalid or not passed at all,
417 // then just append it at the end of the <ul> (this is the default behaviour)
418 } else {
419 $ul.append( $item );
420 }
421
422
423 return $item[0];
424 }
425 },
426
427 /**
428 * Add a little box at the top of the screen to inform the user of
429 * something, replacing any previous message.
430 * Calling with no arguments, with an empty string or null will hide the message
431 *
432 * @param message mixed The DOM-element or HTML-string to be put inside the message box.
433 * @param className string Used in adding a class; should be different for each call
434 * to allow CSS/JS to hide different boxes. null = no class used.
435 * @return boolean True on success, false on failure.
436 */
437 'jsMessage' : function( message, className ) {
438
439 if ( !arguments.length || message === '' || message === null ) {
440
441 $( '#mw-js-message' ).empty().hide();
442 return true; // Emptying and hiding message is intended behaviour, return true
443
444 } else {
445 // We special-case skin structures provided by the software. Skins that
446 // choose to abandon or significantly modify our formatting can just define
447 // an mw-js-message div to start with.
448 var $messageDiv = $( '#mw-js-message' );
449 if ( !$messageDiv.length ) {
450 $messageDiv = $( '<div id="mw-js-message">' );
451 if ( util.$content.parent().length ) {
452 util.$content.parent().prepend( $messageDiv );
453 } else {
454 return false;
455 }
456 }
457
458 if ( className ) {
459 $messageDiv.prop( 'class', 'mw-js-message-' + className );
460 }
461
462 if ( typeof message === 'object' ) {
463 $messageDiv.empty();
464 $messageDiv.append( message ); // Append new content
465 } else {
466 $messageDiv.html( message );
467 }
468
469 $messageDiv.slideDown();
470 return true;
471 }
472 },
473
474 /**
475 * Validate a string as representing a valid e-mail address
476 * according to HTML5 specification. Please note the specification
477 * does not validate a domain with one character.
478 *
479 * @todo FIXME: should be moved to or replaced by a JavaScript validation module.
480 *
481 * @param mailtxt string E-mail address to be validated.
482 * @return mixed Null if mailtxt was an empty string, otherwise true/false
483 * is determined by validation.
484 */
485 'validateEmail' : function( mailtxt ) {
486 if( mailtxt === '' ) {
487 return null;
488 }
489
490 /**
491 * HTML5 defines a string as valid e-mail address if it matches
492 * the ABNF:
493 * 1 * ( atext / "." ) "@" ldh-str 1*( "." ldh-str )
494 * With:
495 * - atext : defined in RFC 5322 section 3.2.3
496 * - ldh-str : defined in RFC 1034 section 3.5
497 *
498 * (see STD 68 / RFC 5234 http://tools.ietf.org/html/std68):
499 */
500
501 /**
502 * First, define the RFC 5322 'atext' which is pretty easy :
503 * atext = ALPHA / DIGIT / ; Printable US-ASCII
504 "!" / "#" / ; characters not including
505 "$" / "%" / ; specials. Used for atoms.
506 "&" / "'" /
507 "*" / "+" /
508 "-" / "/" /
509 "=" / "?" /
510 "^" / "_" /
511 "`" / "{" /
512 "|" / "}" /
513 "~"
514 */
515 var rfc5322_atext = "a-z0-9!#$%&'*+\\-/=?^_`{|}~",
516
517 /**
518 * Next define the RFC 1034 'ldh-str'
519 * <domain> ::= <subdomain> | " "
520 * <subdomain> ::= <label> | <subdomain> "." <label>
521 * <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
522 * <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
523 * <let-dig-hyp> ::= <let-dig> | "-"
524 * <let-dig> ::= <letter> | <digit>
525 */
526 rfc1034_ldh_str = "a-z0-9\\-",
527
528 HTML5_email_regexp = new RegExp(
529 // start of string
530 '^'
531 +
532 // User part which is liberal :p
533 '[' + rfc5322_atext + '\\.]+'
534 +
535 // 'at'
536 '@'
537 +
538 // Domain first part
539 '[' + rfc1034_ldh_str + ']+'
540 +
541 // Optional second part and following are separated by a dot
542 '(?:\\.[' + rfc1034_ldh_str + ']+)*'
543 +
544 // End of string
545 '$',
546 // RegExp is case insensitive
547 'i'
548 );
549 return (null !== mailtxt.match( HTML5_email_regexp ) );
550 },
551
552 /**
553 * Note: borrows from IP::isIPv4
554 *
555 * @param address string
556 * @param allowBlock boolean
557 * @return boolean
558 */
559 'isIPv4Address' : function( address, allowBlock ) {
560 if ( typeof address !== 'string' ) {
561 return false;
562 }
563 var block = allowBlock ? '(?:\\/(?:3[0-2]|[12]?\\d))?' : '';
564 var RE_IP_BYTE = '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])';
565 var RE_IP_ADD = '(?:' + RE_IP_BYTE + '\\.){3}' + RE_IP_BYTE;
566 return address.search( new RegExp( '^' + RE_IP_ADD + block + '$' ) ) != -1;
567 },
568 /**
569 * Note: borrows from IP::isIPv6
570 *
571 * @param address string
572 * @param allowBlock boolean
573 * @return boolean
574 */
575 'isIPv6Address' : function( address, allowBlock ) {
576 if ( typeof address !== 'string' ) {
577 return false;
578 }
579 var block = allowBlock ? '(?:\\/(?:12[0-8]|1[01][0-9]|[1-9]?\\d))?' : '';
580 var RE_IPV6_ADD =
581 '(?:' + // starts with "::" (including "::")
582 ':(?::|(?::' + '[0-9A-Fa-f]{1,4}' + '){1,7})' +
583 '|' + // ends with "::" (except "::")
584 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){0,6}::' +
585 '|' + // contains no "::"
586 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){7}' +
587 ')';
588 if ( address.search( new RegExp( '^' + RE_IPV6_ADD + block + '$' ) ) != -1 ) {
589 return true;
590 }
591 RE_IPV6_ADD = // contains one "::" in the middle (single '::' check below)
592 '[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;
595 }
596
597 };
598
599 util.init();
600
601 } )( jQuery );