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