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