[mw.util] bug fix and minor clean up
[lhc/web/wiklou.git] / resources / mediawiki / mediawiki.util.js
1 /**
2 * Implements mediaWiki.util library
3 */
4 ( function ( $, mw ) {
5 "use strict";
6
7 // Local cache and alias
8 var util = {
9
10 /**
11 * Initialisation
12 * (don't call before document ready)
13 */
14 init: function () {
15 var profile, $tocTitle, $tocToggleLink, hideTocCookie;
16
17 /* Set up $.messageBox */
18 $.messageBoxNew( {
19 id: 'mw-js-message',
20 parent: '#content'
21 } );
22
23 /* Set tooltipAccessKeyPrefix */
24 profile = $.client.profile();
25
26 // Opera on any platform
27 if ( profile.name === 'opera' ) {
28 util.tooltipAccessKeyPrefix = 'shift-esc-';
29
30 // Chrome on any platform
31 } else if ( profile.name === 'chrome' ) {
32 // Chrome on Mac or Chrome on other platform ?
33 util.tooltipAccessKeyPrefix = ( profile.platform === 'mac'
34 ? 'ctrl-option-' : 'alt-' );
35
36 // Non-Windows Safari with webkit_version > 526
37 } else if ( profile.platform !== 'win'
38 && profile.name === 'safari'
39 && profile.layoutVersion > 526 ) {
40 util.tooltipAccessKeyPrefix = 'ctrl-alt-';
41
42 // Safari/Konqueror on any platform, or any browser on Mac
43 // (but not Safari on Windows)
44 } else if ( !( profile.platform === 'win' && profile.name === 'safari' )
45 && ( profile.name === 'safari'
46 || profile.platform === 'mac'
47 || profile.name === 'konqueror' ) ) {
48 util.tooltipAccessKeyPrefix = 'ctrl-';
49
50 // Firefox 2.x and later
51 } else if ( profile.name === 'firefox' && profile.versionBase > '1' ) {
52 util.tooltipAccessKeyPrefix = 'alt-shift-';
53 }
54
55 /* Fill $content var */
56 if ( $( '#bodyContent' ).length ) {
57 // Vector, Monobook, Chick etc.
58 util.$content = $( '#bodyContent' );
59
60 } else if ( $( '#mw_contentholder' ).length ) {
61 // Modern
62 util.$content = $( '#mw_contentholder' );
63
64 } else if ( $( '#article' ).length ) {
65 // Standard, CologneBlue
66 util.$content = $( '#article' );
67
68 } else {
69 // #content is present on almost all if not all skins. Most skins (the above cases)
70 // have #content too, but as an outer wrapper instead of the article text container.
71 // The skins that don't have an outer wrapper do have #content for everything
72 // so it's a good fallback
73 util.$content = $( '#content' );
74 }
75
76 // Table of contents toggle
77 $tocTitle = $( '#toctitle' );
78 $tocToggleLink = $( '#togglelink' );
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 ) {
85 e.preventDefault();
86 util.toggleToc( $(this) );
87 } );
88 $tocTitle.append(
89 $tocToggleLink
90 .wrap( '<span class="toctoggle"></span>' )
91 .parent()
92 .prepend( '&nbsp;[' )
93 .append( ']&nbsp;' )
94 );
95
96 if ( hideTocCookie === '1' ) {
97 util.toggleToc( $tocToggleLink );
98 }
99 }
100 },
101
102 /* Main body */
103
104 /**
105 * Encode the string like PHP's rawurlencode
106 *
107 * @param str string String to be encoded
108 */
109 rawurlencode: function ( str ) {
110 str = String( 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' );
114 },
115
116 /**
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
120 *
121 * @param str string String to be encoded
122 */
123 wikiUrlencode: function ( str ) {
124 return util.rawurlencode( str )
125 .replace( /%20/g, '_' ).replace( /%3A/g, ':' ).replace( /%2F/g, '/' );
126 },
127
128 /**
129 * Get the link to a page name (relative to wgServer)
130 *
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.
133 */
134 wikiGetlink: function ( str ) {
135 return mw.config.get( 'wgArticlePath' ).replace( '$1',
136 util.wikiUrlencode( typeof str === 'string' ? str : mw.config.get( 'wgPageName' ) ) );
137 },
138
139 /**
140 * Get address to a script in the wiki root.
141 * For index.php use mw.config.get( 'wgScript' )
142 *
143 * @param str string Name of script (eg. 'api'), defaults to 'index'
144 * @return string Address to script (eg. '/w/api.php' )
145 */
146 wikiScript: function ( str ) {
147 return mw.config.get( 'wgScriptPath' ) + '/' + ( str || 'index' ) +
148 mw.config.get( 'wgScriptExtension' );
149 },
150
151 /**
152 * Append a new style block to the head
153 *
154 * @param text string CSS to be appended
155 * @return CSSStyleSheet
156 */
157 addCSS: function ( text ) {
158 var s = document.createElement( 'style' );
159 s.type = 'text/css';
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
165 } else {
166 // Safari sometimes borks on null
167 s.appendChild( document.createTextNode( String( text ) ) );
168 }
169 return s.sheet || s;
170 },
171
172 /**
173 * Hide/show the table of contents element
174 *
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.
180 */
181 toggleToc: function ( $toggleLink, callback ) {
182 var $tocList = $( '#toc ul:first' );
183
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, {
192 expires: 30,
193 path: '/'
194 } );
195 return true;
196 } else {
197 $tocList.slideUp( 'fast', callback );
198 $toggleLink.text( mw.msg( 'showtoc' ) );
199 $( '#toc' ).addClass( 'tochidden' );
200 $.cookie( 'mw_hidetoc', '1', {
201 expires: 30,
202 path: '/'
203 } );
204 return false;
205 }
206 } else {
207 return null;
208 }
209 },
210
211 /**
212 * Grab the URL parameter value for the given parameter.
213 * Returns null if not found.
214 *
215 * @param param string The parameter name.
216 * @param url string URL to search through (optional)
217 * @return mixed Parameter value or null.
218 */
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 ) + '=([^&#]*)' ),
223 m = re.exec( url );
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' ) );
228 }
229 return null;
230 },
231
232 /**
233 * @var string
234 * Access key prefix. Will be re-defined based on browser/operating system
235 * detection in mw.util.init().
236 */
237 tooltipAccessKeyPrefix: 'alt-',
238
239 /**
240 * @var RegExp
241 * Regex to match accesskey tooltips.
242 */
243 tooltipAccessKeyRegexp: /\[(ctrl-)?(alt-)?(shift-)?(esc-)?(.)\]$/,
244
245 /**
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.
250 *
251 * @param $nodes {Array|jQuery} [optional] A jQuery object, or array
252 * of elements to update.
253 */
254 updateTooltipAccessKeys: function ( $nodes ) {
255 if ( !$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 );
262 }
263
264 $nodes.attr( 'title', function ( i, val ) {
265 if ( val && util.tooltipAccessKeyRegexp.exec( val ) ) {
266 return val.replace( util.tooltipAccessKeyRegexp,
267 '[' + util.tooltipAccessKeyPrefix + '$5]' );
268 }
269 return val;
270 } );
271 },
272
273 /*
274 * @var jQuery
275 * A jQuery object that refers to the page-content element
276 * Populated by init().
277 */
278 $content: null,
279
280 /**
281 * Add a link to a portlet menu on the page, such as:
282 *
283 * p-cactions (Content actions), p-personal (Personal tools),
284 * p-navigation (Navigation), p-tb (Toolbox)
285 *
286 * The first three paramters are required, the others are optional and
287 * may be null. Though providing an id and tooltip is recommended.
288 *
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.
293 *
294 * @example mw.util.addPortletLink(
295 * 'p-tb', 'http://mediawiki.org/',
296 * 'MediaWiki.org', 't-mworg', 'Go to MediaWiki.org ', 'm', '#t-print'
297 * )
298 *
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
311 *
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.
314 */
315 addPortletLink: function ( portlet, href, text, id, tooltip, accesskey, nextnode ) {
316 var $item, $link, $portlet, $ul;
317
318 // Check if there's atleast 3 arguments to prevent a TypeError
319 if ( arguments.length < 3 ) {
320 return null;
321 }
322 // Setup the anchor tag
323 $link = $( '<a>' ).attr( 'href', href ).text( text );
324 if ( tooltip ) {
325 $link.attr( 'title', tooltip );
326 }
327
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' ) ) {
331 case 'standard':
332 case 'cologneblue':
333 $( '#quickbar' ).append( $link.after( '<br/>' ) );
334 return $link[0];
335 case 'nostalgia':
336 $( '#searchform' ).before( $link ).before( ' &#124; ' );
337 return $link[0];
338 default: // Skins like chick, modern, monobook, myskin, simple, vector...
339
340 // Select the specified portlet
341 $portlet = $( '#' + portlet );
342 if ( $portlet.length === 0 ) {
343 return null;
344 }
345 // Select the first (most likely only) unordered list inside the portlet
346 $ul = $portlet.find( 'ul' );
347
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>' );
353 } else {
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>' );
357 }
358 // Select the created element
359 $ul = $portlet.find( 'ul' ).eq( 0 );
360 }
361 // Just in case..
362 if ( $ul.length === 0 ) {
363 return null;
364 }
365
366 // Unhide portlet if it was hidden before
367 $portlet.removeClass( 'emptyPortlet' );
368
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();
373 } else {
374 $item = $link.wrap( '<li></li>' ).parent();
375 }
376
377 // Implement the properties passed to the function
378 if ( id ) {
379 $item.attr( 'id', id );
380 }
381 if ( accesskey ) {
382 $link.attr( 'accesskey', accesskey );
383 tooltip += ' [' + accesskey + ']';
384 $link.attr( 'title', tooltip );
385 }
386 if ( accesskey && tooltip ) {
387 util.updateTooltipAccessKeys( $link );
388 }
389
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 );
394
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 );
398
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)
402 } else {
403 $ul.append( $item );
404 }
405
406
407 return $item[0];
408 }
409 },
410
411 /**
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
415 *
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.
420 */
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
425
426 } else {
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 );
435 } else {
436 return false;
437 }
438 }
439
440 if ( className ) {
441 $messageDiv.prop( 'class', 'mw-js-message-' + className );
442 }
443
444 if ( typeof message === 'object' ) {
445 $messageDiv.empty();
446 $messageDiv.append( message );
447 } else {
448 $messageDiv.html( message );
449 }
450
451 $messageDiv.slideDown();
452 return true;
453 }
454 },
455
456 /**
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.
460 *
461 * @todo FIXME: should be moved to or replaced by a JavaScript validation module.
462 *
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.
466 */
467 validateEmail: function ( mailtxt ) {
468 var rfc5322_atext, rfc1034_ldh_str, HTML5_email_regexp;
469
470 if ( mailtxt === '' ) {
471 return null;
472 }
473
474 /**
475 * HTML5 defines a string as valid e-mail address if it matches
476 * the ABNF:
477 * 1 * ( atext / "." ) "@" ldh-str 1*( "." ldh-str )
478 * With:
479 * - atext : defined in RFC 5322 section 3.2.3
480 * - ldh-str : defined in RFC 1034 section 3.5
481 *
482 * (see STD 68 / RFC 5234 http://tools.ietf.org/html/std68):
483 */
484
485 /**
486 * First, define the RFC 5322 'atext' which is pretty easy:
487 * atext = ALPHA / DIGIT / ; Printable US-ASCII
488 "!" / "#" / ; characters not including
489 "$" / "%" / ; specials. Used for atoms.
490 "&" / "'" /
491 "*" / "+" /
492 "-" / "/" /
493 "=" / "?" /
494 "^" / "_" /
495 "`" / "{" /
496 "|" / "}" /
497 "~"
498 */
499 rfc5322_atext = "a-z0-9!#$%&'*+\\-/=?^_`{|}~";
500
501 /**
502 * Next define the RFC 1034 'ldh-str'
503 * <domain> ::= <subdomain> | " "
504 * <subdomain> ::= <label> | <subdomain> "." <label>
505 * <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
506 * <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
507 * <let-dig-hyp> ::= <let-dig> | "-"
508 * <let-dig> ::= <letter> | <digit>
509 */
510 rfc1034_ldh_str = "a-z0-9\\-";
511
512 HTML5_email_regexp = new RegExp(
513 // start of string
514 '^'
515 +
516 // User part which is liberal :p
517 '[' + rfc5322_atext + '\\.]+'
518 +
519 // 'at'
520 '@'
521 +
522 // Domain first part
523 '[' + rfc1034_ldh_str + ']+'
524 +
525 // Optional second part and following are separated by a dot
526 '(?:\\.[' + rfc1034_ldh_str + ']+)*'
527 +
528 // End of string
529 '$',
530 // RegExp is case insensitive
531 'i'
532 );
533 return (null !== mailtxt.match( HTML5_email_regexp ) );
534 },
535
536 /**
537 * Note: borrows from IP::isIPv4
538 *
539 * @param address string
540 * @param allowBlock boolean
541 * @return boolean
542 */
543 isIPv4Address: function ( address, allowBlock ) {
544 if ( typeof address !== 'string' ) {
545 return false;
546 }
547
548 var block = allowBlock ? '(?:\\/(?:3[0-2]|[12]?\\d))?' : '',
549 RE_IP_BYTE = '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])',
550 RE_IP_ADD = '(?:' + RE_IP_BYTE + '\\.){3}' + RE_IP_BYTE;
551
552 return address.search( new RegExp( '^' + RE_IP_ADD + block + '$' ) ) !== -1;
553 },
554
555 /**
556 * Note: borrows from IP::isIPv6
557 *
558 * @param address string
559 * @param allowBlock boolean
560 * @return boolean
561 */
562 isIPv6Address: function ( address, allowBlock ) {
563 if ( typeof address !== 'string' ) {
564 return false;
565 }
566
567 var block = allowBlock ? '(?:\\/(?:12[0-8]|1[01][0-9]|[1-9]?\\d))?' : '',
568 RE_IPV6_ADD =
569 '(?:' + // starts with "::" (including "::")
570 ':(?::|(?::' + '[0-9A-Fa-f]{1,4}' + '){1,7})' +
571 '|' + // ends with "::" (except "::")
572 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){0,6}::' +
573 '|' + // contains no "::"
574 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){7}' +
575 ')';
576
577 if ( address.search( new RegExp( '^' + RE_IPV6_ADD + block + '$' ) ) !== -1 ) {
578 return true;
579 }
580
581 RE_IPV6_ADD = // contains one "::" in the middle (single '::' check below)
582 '[0-9A-Fa-f]{1,4}' + '(?:::?' + '[0-9A-Fa-f]{1,4}' + '){1,6}';
583
584 return address.search( new RegExp( '^' + RE_IPV6_ADD + block + '$' ) ) !== -1
585 && address.search( /::/ ) !== -1 && address.search( /::.*::/ ) === -1;
586 }
587 };
588
589 mw.util = util;
590
591 } )( jQuery, mediaWiki );