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