Merge "Add support for mulitpart mime email to email sending code"
[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 tooltipAccessKeyPrefix */
18 profile = $.client.profile();
19
20 // Opera on any platform
21 if ( profile.name === 'opera' ) {
22 util.tooltipAccessKeyPrefix = 'shift-esc-';
23
24 // Chrome on any platform
25 } else if ( profile.name === 'chrome' ) {
26
27 util.tooltipAccessKeyPrefix = (
28 profile.platform === 'mac'
29 // Chrome on Mac
30 ? 'ctrl-option-'
31 // Chrome on Windows or Linux
32 // (both alt- and alt-shift work, but alt with E, D, F etc does not
33 // work since they are browser shortcuts)
34 : 'alt-shift-'
35 );
36
37 // Non-Windows Safari with webkit_version > 526
38 } else if ( profile.platform !== 'win'
39 && profile.name === 'safari'
40 && profile.layoutVersion > 526 ) {
41 util.tooltipAccessKeyPrefix = 'ctrl-alt-';
42 // Firefox 14+ on Mac
43 } else if ( profile.platform === 'mac'
44 && profile.name === 'firefox'
45 && profile.versionNumber >= 14 ) {
46 util.tooltipAccessKeyPrefix = 'ctrl-option-';
47 // Safari/Konqueror on any platform, or any browser on Mac
48 // (but not Safari on Windows)
49 } else if ( !( profile.platform === 'win' && profile.name === 'safari' )
50 && ( profile.name === 'safari'
51 || profile.platform === 'mac'
52 || profile.name === 'konqueror' ) ) {
53 util.tooltipAccessKeyPrefix = 'ctrl-';
54
55 // Firefox 2.x and later
56 } else if ( profile.name === 'firefox' && profile.versionBase > '1' ) {
57 util.tooltipAccessKeyPrefix = 'alt-shift-';
58 }
59
60 /* Fill $content var */
61 util.$content = ( function () {
62 var i, l, $content, selectors;
63 selectors = [
64 // The preferred standard for setting $content (class="mw-body")
65 // You may also use (class="mw-body mw-body-primary") if you use
66 // mw-body in multiple locations.
67 // Or class="mw-body-primary" if you want $content to be deeper
68 // in the dom than mw-body
69 '.mw-body-primary',
70 '.mw-body',
71
72 /* Legacy fallbacks for setting the content */
73 // Vector, Monobook, Chick, etc... based skins
74 '#bodyContent',
75
76 // Modern based skins
77 '#mw_contentholder',
78
79 // Standard, CologneBlue
80 '#article',
81
82 // #content is present on almost all if not all skins. Most skins (the above cases)
83 // have #content too, but as an outer wrapper instead of the article text container.
84 // The skins that don't have an outer wrapper do have #content for everything
85 // so it's a good fallback
86 '#content',
87
88 // If nothing better is found fall back to our bodytext div that is guaranteed to be here
89 '#mw-content-text',
90
91 // Should never happen... well, it could if someone is not finished writing a skin and has
92 // not inserted bodytext yet. But in any case <body> should always exist
93 'body'
94 ];
95 for ( i = 0, l = selectors.length; i < l; i++ ) {
96 $content = $( selectors[i] ).first();
97 if ( $content.length ) {
98 return $content;
99 }
100 }
101
102 // Make sure we don't unset util.$content if it was preset and we don't find anything
103 return util.$content;
104 } )();
105
106 // Table of contents toggle
107 $tocTitle = $( '#toctitle' );
108 $tocToggleLink = $( '#togglelink' );
109 // Only add it if there is a TOC and there is no toggle added already
110 if ( $( '#toc' ).length && $tocTitle.length && !$tocToggleLink.length ) {
111 hideTocCookie = $.cookie( 'mw_hidetoc' );
112 $tocToggleLink = $( '<a href="#" class="internal" id="togglelink"></a>' )
113 .text( mw.msg( 'hidetoc' ) )
114 .click( function ( e ) {
115 e.preventDefault();
116 util.toggleToc( $(this) );
117 } );
118 $tocTitle.append(
119 $tocToggleLink
120 .wrap( '<span class="toctoggle"></span>' )
121 .parent()
122 .prepend( '&nbsp;[' )
123 .append( ']&nbsp;' )
124 );
125
126 if ( hideTocCookie === '1' ) {
127 util.toggleToc( $tocToggleLink );
128 }
129 }
130 },
131
132 /* Main body */
133
134 /**
135 * Encode the string like PHP's rawurlencode
136 *
137 * @param str string String to be encoded
138 */
139 rawurlencode: function ( str ) {
140 str = String( str );
141 return encodeURIComponent( str )
142 .replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' )
143 .replace( /\)/g, '%29' ).replace( /\*/g, '%2A' ).replace( /~/g, '%7E' );
144 },
145
146 /**
147 * Encode page titles for use in a URL
148 * We want / and : to be included as literal characters in our title URLs
149 * as they otherwise fatally break the title
150 *
151 * @param str string String to be encoded
152 */
153 wikiUrlencode: function ( str ) {
154 return util.rawurlencode( str )
155 .replace( /%20/g, '_' ).replace( /%3A/g, ':' ).replace( /%2F/g, '/' );
156 },
157
158 /**
159 * Get the link to a page name (relative to wgServer)
160 *
161 * @param str String: Page name to get the link for.
162 * @return String: Location for a page with name of 'str' or boolean false on error.
163 */
164 wikiGetlink: function ( str ) {
165 return mw.config.get( 'wgArticlePath' ).replace( '$1',
166 util.wikiUrlencode( typeof str === 'string' ? str : mw.config.get( 'wgPageName' ) ) );
167 },
168
169 /**
170 * Get address to a script in the wiki root.
171 * For index.php use mw.config.get( 'wgScript' )
172 *
173 * @since 1.18
174 * @param str string Name of script (eg. 'api'), defaults to 'index'
175 * @return string Address to script (eg. '/w/api.php' )
176 */
177 wikiScript: function ( str ) {
178 str = str || 'index';
179 if ( str === 'index' ) {
180 return mw.config.get( 'wgScript' );
181 } else if ( str === 'load' ) {
182 return mw.config.get( 'wgLoadScript' );
183 } else {
184 return mw.config.get( 'wgScriptPath' ) + '/' + str +
185 mw.config.get( 'wgScriptExtension' );
186 }
187 },
188
189 /**
190 * Append a new style block to the head and return the CSSStyleSheet object.
191 * Use .ownerNode to access the <style> element, or use mw.loader.addStyleTag.
192 * This function returns the styleSheet object for convience (due to cross-browsers
193 * difference as to where it is located).
194 * @example
195 * <code>
196 * var sheet = mw.util.addCSS('.foobar { display: none; }');
197 * $(foo).click(function () {
198 * // Toggle the sheet on and off
199 * sheet.disabled = !sheet.disabled;
200 * });
201 * </code>
202 *
203 * @param text string CSS to be appended
204 * @return CSSStyleSheet (use .ownerNode to get to the <style> element)
205 */
206 addCSS: function ( text ) {
207 var s = mw.loader.addStyleTag( text );
208 return s.sheet || s;
209 },
210
211 /**
212 * Hide/show the table of contents element
213 *
214 * @param $toggleLink jQuery A jQuery object of the toggle link.
215 * @param callback function Function to be called after the toggle is
216 * completed (including the animation) (optional)
217 * @return mixed Boolean visibility of the toc (true if it's visible)
218 * or Null if there was no table of contents.
219 */
220 toggleToc: function ( $toggleLink, callback ) {
221 var $tocList = $( '#toc ul:first' );
222
223 // This function shouldn't be called if there's no TOC,
224 // but just in case...
225 if ( $tocList.length ) {
226 if ( $tocList.is( ':hidden' ) ) {
227 $tocList.slideDown( 'fast', callback );
228 $toggleLink.text( mw.msg( 'hidetoc' ) );
229 $( '#toc' ).removeClass( 'tochidden' );
230 $.cookie( 'mw_hidetoc', null, {
231 expires: 30,
232 path: '/'
233 } );
234 return true;
235 } else {
236 $tocList.slideUp( 'fast', callback );
237 $toggleLink.text( mw.msg( 'showtoc' ) );
238 $( '#toc' ).addClass( 'tochidden' );
239 $.cookie( 'mw_hidetoc', '1', {
240 expires: 30,
241 path: '/'
242 } );
243 return false;
244 }
245 } else {
246 return null;
247 }
248 },
249
250 /**
251 * Grab the URL parameter value for the given parameter.
252 * Returns null if not found.
253 *
254 * @param param string The parameter name.
255 * @param url string URL to search through (optional)
256 * @return mixed Parameter value or null.
257 */
258 getParamValue: function ( param, url ) {
259 if ( url === undefined ) {
260 url = document.location.href;
261 }
262 // Get last match, stop at hash
263 var re = new RegExp( '^[^#]*[&?]' + $.escapeRE( param ) + '=([^&#]*)' ),
264 m = re.exec( url );
265 if ( m ) {
266 // Beware that decodeURIComponent is not required to understand '+'
267 // by spec, as encodeURIComponent does not produce it.
268 return decodeURIComponent( m[1].replace( /\+/g, '%20' ) );
269 }
270 return null;
271 },
272
273 /**
274 * @var string
275 * Access key prefix. Will be re-defined based on browser/operating system
276 * detection in mw.util.init().
277 */
278 tooltipAccessKeyPrefix: 'alt-',
279
280 /**
281 * @var RegExp
282 * Regex to match accesskey tooltips.
283 */
284 tooltipAccessKeyRegexp: /\[(ctrl-)?(alt-)?(shift-)?(esc-)?(.)\]$/,
285
286 /**
287 * Add the appropriate prefix to the accesskey shown in the tooltip.
288 * If the nodeList parameter is given, only those nodes are updated;
289 * otherwise, all the nodes that will probably have accesskeys by
290 * default are updated.
291 *
292 * @param $nodes {Array|jQuery} [optional] A jQuery object, or array
293 * of elements to update.
294 */
295 updateTooltipAccessKeys: function ( $nodes ) {
296 if ( !$nodes ) {
297 // Rather than going into a loop of all anchor tags, limit to few elements that
298 // contain the relevant anchor tags.
299 // Input and label are rare enough that no such optimization is needed
300 $nodes = $( '#column-one a, #mw-head a, #mw-panel a, #p-logo a, input, label' );
301 } else if ( !( $nodes instanceof $ ) ) {
302 $nodes = $( $nodes );
303 }
304
305 $nodes.attr( 'title', function ( i, val ) {
306 if ( val && util.tooltipAccessKeyRegexp.exec( val ) ) {
307 return val.replace( util.tooltipAccessKeyRegexp,
308 '[' + util.tooltipAccessKeyPrefix + '$5]' );
309 }
310 return val;
311 } );
312 },
313
314 /*
315 * @var jQuery
316 * A jQuery object that refers to the content area element
317 * Populated by init().
318 */
319 $content: null,
320
321 /**
322 * Add a link to a portlet menu on the page, such as:
323 *
324 * p-cactions (Content actions), p-personal (Personal tools),
325 * p-navigation (Navigation), p-tb (Toolbox)
326 *
327 * The first three paramters are required, the others are optional and
328 * may be null. Though providing an id and tooltip is recommended.
329 *
330 * By default the new link will be added to the end of the list. To
331 * add the link before a given existing item, pass the DOM node
332 * (document.getElementById( 'foobar' )) or the jQuery-selector
333 * ( '#foobar' ) of that item.
334 *
335 * @example mw.util.addPortletLink(
336 * 'p-tb', 'http://mediawiki.org/',
337 * 'MediaWiki.org', 't-mworg', 'Go to MediaWiki.org ', 'm', '#t-print'
338 * )
339 *
340 * @param portlet string ID of the target portlet ( 'p-cactions' or 'p-personal' etc.)
341 * @param href string Link URL
342 * @param text string Link text
343 * @param id string ID of the new item, should be unique and preferably have
344 * the appropriate prefix ( 'ca-', 'pt-', 'n-' or 't-' )
345 * @param tooltip string Text to show when hovering over the link, without accesskey suffix
346 * @param accesskey string Access key to activate this link (one character, try
347 * to avoid conflicts. Use $( '[accesskey=x]' ).get() in the console to
348 * see if 'x' is already used.
349 * @param nextnode mixed DOM Node or jQuery-selector string of the item that the new
350 * item should be added before, should be another item in the same
351 * list, it will be ignored otherwise
352 *
353 * @return mixed The DOM Node of the added item (a ListItem or Anchor element,
354 * depending on the skin) or null if no element was added to the document.
355 */
356 addPortletLink: function ( portlet, href, text, id, tooltip, accesskey, nextnode ) {
357 var $item, $link, $portlet, $ul;
358
359 // Check if there's atleast 3 arguments to prevent a TypeError
360 if ( arguments.length < 3 ) {
361 return null;
362 }
363 // Setup the anchor tag
364 $link = $( '<a>' ).attr( 'href', href ).text( text );
365 if ( tooltip ) {
366 $link.attr( 'title', tooltip );
367 }
368
369 // Some skins don't have any portlets
370 // just add it to the bottom of their 'sidebar' element as a fallback
371 switch ( mw.config.get( 'skin' ) ) {
372 case 'standard':
373 $( '#quickbar' ).append( $link.after( '<br/>' ) );
374 return $link[0];
375 case 'nostalgia':
376 $( '#searchform' ).before( $link ).before( ' &#124; ' );
377 return $link[0];
378 default: // Skins like chick, modern, monobook, myskin, simple, vector...
379
380 // Select the specified portlet
381 $portlet = $( '#' + portlet );
382 if ( $portlet.length === 0 ) {
383 return null;
384 }
385 // Select the first (most likely only) unordered list inside the portlet
386 $ul = $portlet.find( 'ul' ).eq( 0 );
387
388 // If it didn't have an unordered list yet, create it
389 if ( $ul.length === 0 ) {
390
391 $ul = $( '<ul>' );
392
393 // If there's no <div> inside, append it to the portlet directly
394 if ( $portlet.find( 'div:first' ).length === 0 ) {
395 $portlet.append( $ul );
396 } else {
397 // otherwise if there's a div (such as div.body or div.pBody)
398 // append the <ul> to last (most likely only) div
399 $portlet.find( 'div' ).eq( -1 ).append( $ul );
400 }
401 }
402 // Just in case..
403 if ( $ul.length === 0 ) {
404 return null;
405 }
406
407 // Unhide portlet if it was hidden before
408 $portlet.removeClass( 'emptyPortlet' );
409
410 // Wrap the anchor tag in a list item (and a span if $portlet is a Vector tab)
411 // and back up the selector to the list item
412 if ( $portlet.hasClass( 'vectorTabs' ) ) {
413 $item = $link.wrap( '<li><span></span></li>' ).parent().parent();
414 } else {
415 $item = $link.wrap( '<li></li>' ).parent();
416 }
417
418 // Implement the properties passed to the function
419 if ( id ) {
420 $item.attr( 'id', id );
421 }
422 if ( accesskey ) {
423 $link.attr( 'accesskey', accesskey );
424 tooltip += ' [' + accesskey + ']';
425 $link.attr( 'title', tooltip );
426 }
427 if ( accesskey && tooltip ) {
428 util.updateTooltipAccessKeys( $link );
429 }
430
431 // Where to put our node ?
432 // - nextnode is a DOM element (was the only option before MW 1.17, in wikibits.js)
433 if ( nextnode && nextnode.parentNode === $ul[0] ) {
434 $(nextnode).before( $item );
435
436 // - nextnode is a CSS selector for jQuery
437 } else if ( typeof nextnode === 'string' && $ul.find( nextnode ).length !== 0 ) {
438 $ul.find( nextnode ).eq( 0 ).before( $item );
439
440 // If the jQuery selector isn't found within the <ul>,
441 // or if nextnode was invalid or not passed at all,
442 // then just append it at the end of the <ul> (this is the default behaviour)
443 } else {
444 $ul.append( $item );
445 }
446
447
448 return $item[0];
449 }
450 },
451
452 /**
453 * Add a little box at the top of the screen to inform the user of
454 * something, replacing any previous message.
455 * Calling with no arguments, with an empty string or null will hide the message
456 *
457 * @param message {mixed} The DOM-element, jQuery object or HTML-string to be put inside the message box.
458 * to allow CSS/JS to hide different boxes. null = no class used.
459 * @depreceated Use mw.notify
460 */
461 jsMessage: function ( message ) {
462 if ( !arguments.length || message === '' || message === null ) {
463 return true;
464 }
465 if ( typeof message !== 'object' ) {
466 message = $.parseHTML( message );
467 }
468 mw.notify( message, { autoHide: true, tag: 'legacy' } );
469 return true;
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 var rfc5322Atext, rfc1034LdhStr, html5EmailRegexp;
485
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 rfc5322Atext = '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 rfc1034LdhStr = 'a-z0-9\\-';
527
528 html5EmailRegexp = new RegExp(
529 // start of string
530 '^'
531 +
532 // User part which is liberal :p
533 '[' + rfc5322Atext + '\\.]+'
534 +
535 // 'at'
536 '@'
537 +
538 // Domain first part
539 '[' + rfc1034LdhStr + ']+'
540 +
541 // Optional second part and following are separated by a dot
542 '(?:\\.[' + rfc1034LdhStr + ']+)*'
543 +
544 // End of string
545 '$',
546 // RegExp is case insensitive
547 'i'
548 );
549 return (null !== mailtxt.match( html5EmailRegexp ) );
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
564 var block = allowBlock ? '(?:\\/(?:3[0-2]|[12]?\\d))?' : '',
565 RE_IP_BYTE = '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])',
566 RE_IP_ADD = '(?:' + RE_IP_BYTE + '\\.){3}' + RE_IP_BYTE;
567
568 return address.search( new RegExp( '^' + RE_IP_ADD + block + '$' ) ) !== -1;
569 },
570
571 /**
572 * Note: borrows from IP::isIPv6
573 *
574 * @param address string
575 * @param allowBlock boolean
576 * @return boolean
577 */
578 isIPv6Address: function ( address, allowBlock ) {
579 if ( typeof address !== 'string' ) {
580 return false;
581 }
582
583 var block = allowBlock ? '(?:\\/(?:12[0-8]|1[01][0-9]|[1-9]?\\d))?' : '',
584 RE_IPV6_ADD =
585 '(?:' + // starts with "::" (including "::")
586 ':(?::|(?::' + '[0-9A-Fa-f]{1,4}' + '){1,7})' +
587 '|' + // ends with "::" (except "::")
588 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){0,6}::' +
589 '|' + // contains no "::"
590 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){7}' +
591 ')';
592
593 if ( address.search( new RegExp( '^' + RE_IPV6_ADD + block + '$' ) ) !== -1 ) {
594 return true;
595 }
596
597 RE_IPV6_ADD = // contains one "::" in the middle (single '::' check below)
598 '[0-9A-Fa-f]{1,4}' + '(?:::?' + '[0-9A-Fa-f]{1,4}' + '){1,6}';
599
600 return address.search( new RegExp( '^' + RE_IPV6_ADD + block + '$' ) ) !== -1
601 && address.search( /::/ ) !== -1 && address.search( /::.*::/ ) === -1;
602 }
603 };
604
605 mw.util = util;
606
607 }( mediaWiki, jQuery ) );