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