New mediawiki.page modules
[lhc/web/wiklou.git] / resources / mediawiki / mediawiki.util.js
1 /**
2 * Utilities
3 */
4 ( function( $, mw ) {
5
6 mw.util = {
7
8 /* Initialisation */
9 /**
10 * @var boolean Wether or not already initialised
11 */
12 'initialised' : false,
13 'init' : function() {
14 if ( this.initialised === false ) {
15 this.initialised = true;
16
17 // Any initialisation after the DOM is ready
18 $( function() {
19
20 /* Set up $.messageBox */
21 $.messageBoxNew( {
22 'id': 'mw-js-message',
23 'parent': '#content'
24 } );
25
26 // Shortcut to client profile return
27 var profile = $.client.profile();
28
29 /* Set tooltipAccessKeyPrefix */
30
31 // Opera on any platform
32 if ( profile.name == 'opera' ) {
33 mw.util.tooltipAccessKeyPrefix = 'shift-esc-';
34
35 // Chrome on any platform
36 } else if ( profile.name == 'chrome' ) {
37 // Chrome on Mac or Chrome on other platform ?
38 mw.util.tooltipAccessKeyPrefix = ( profile.platform == 'mac'
39 ? 'ctrl-option-' : 'alt-' );
40
41 // Non-Windows Safari with webkit_version > 526
42 } else if ( profile.platform !== 'win'
43 && profile.name == 'safari'
44 && profile.layoutVersion > 526 ) {
45 mw.util.tooltipAccessKeyPrefix = 'ctrl-alt-';
46
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 mw.util.tooltipAccessKeyPrefix = 'ctrl-';
54
55 // Firefox 2.x
56 } else if ( profile.name == 'firefox' && profile.versionBase == '2' ) {
57 mw.util.tooltipAccessKeyPrefix = 'alt-shift-';
58 }
59
60 /* Fill $content var */
61 if ( $( '#bodyContent' ).length ) {
62 // Vector, Monobook, Chick etc.
63 mw.util.$content = $( '#bodyContent' );
64
65 } else if ( $( '#mw_contentholder' ).length ) {
66 // Modern
67 mw.util.$content = $( '#mw_contentholder' );
68
69 } else if ( $( '#article' ).length ) {
70 // Standard, CologneBlue
71 mw.util.$content = $( '#article' );
72
73 } else {
74 // #content is present on almost all if not all skins. Most skins (the above cases)
75 // have #content too, but as an outer wrapper instead of the article text container.
76 // The skins that don't have an outer wrapper do have #content for everything
77 // so it's a good fallback
78 mw.util.$content = $( '#content' );
79 }
80
81 /* Table of Contents toggle */
82 var $tocContainer = $( '#toc' ),
83 $tocTitle = $( '#toctitle' ),
84 $tocToggleLink = $( '#togglelink' );
85 // Only add it if there is a TOC and there is no toggle added already
86 if ( $tocContainer.size() && $tocTitle.size() && !$tocToggleLink.size() ) {
87 var hideTocCookie = $.cookie( 'mw_hidetoc' );
88 $tocToggleLink = $( '<a href="#" class="internal" id="togglelink">' )
89 .text( mw.msg( 'hidetoc' ) )
90 .click( function(e){
91 e.preventDefault();
92 mw.util.toggleToc( $(this) );
93 } );
94 $tocTitle.append( $tocToggleLink.wrap( '<span class="toctoggle">' ).parent().prepend( '&nbsp;[' ).append( ']&nbsp;' ) );
95
96 if ( hideTocCookie == '1' ) {
97 // Cookie says user want toc hidden
98 $tocToggleLink.click();
99 }
100 }
101 } );
102
103 return true;
104 }
105 return false;
106 },
107
108 /* Main body */
109
110 /**
111 * Encode the string like PHP's rawurlencode
112 *
113 * @param str string String to be encoded
114 */
115 'rawurlencode' : function( str ) {
116 str = ( str + '' ).toString();
117 return encodeURIComponent( str )
118 .replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' )
119 .replace( /\)/g, '%29' ).replace( /\*/g, '%2A' ).replace( /~/g, '%7E' );
120 },
121
122 /**
123 * Encode page titles for use in a URL
124 * We want / and : to be included as literal characters in our title URLs
125 * as they otherwise fatally break the title
126 *
127 * @param str string String to be encoded
128 */
129 'wikiUrlencode' : function( str ) {
130 return this.rawurlencode( str )
131 .replace( /%20/g, '_' ).replace( /%3A/g, ':' ).replace( /%2F/g, '/' );
132 },
133
134 /**
135 * Get the link to a page name (relative to wgServer)
136 *
137 * @param str string Page name to get the link for.
138 * @return string Location for a page with name of 'str' or boolean false on error.
139 */
140 'wikiGetlink' : function( str ) {
141
142 return mw.config.get( 'wgArticlePath' ).replace( '$1', this.wikiUrlencode( str ) );
143 },
144
145 /**
146 * Get address to a script in the wiki root.
147 * For index.php use mw.config.get( 'wgScript' )
148 *
149 * @param str string Name of script (eg. 'api'), defaults to 'index'
150 * @return string Address to script (eg. '/w/api.php' )
151 */
152 'wikiScript' : function( str ) {
153 return mw.config.get( 'wgScriptPath' ) + '/' + ( str || 'index' ) + mw.config.get( 'wgScriptExtension' );
154 },
155
156 /**
157 * Append a new style block to the head
158 *
159 * @param text string CSS to be appended
160 * @return CSSStyleSheet
161 */
162 'addCSS' : function( text ) {
163 var s = document.createElement( 'style' );
164 s.type = 'text/css';
165 s.rel = 'stylesheet';
166 if ( s.styleSheet ) {
167 s.styleSheet.cssText = text; // IE
168 } else {
169 s.appendChild( document.createTextNode( text + '' ) ); // Safari sometimes borks on null
170 }
171 document.getElementsByTagName('head')[0].appendChild( s );
172 return s.sheet || s;
173 },
174
175 /**
176 * Hide/show the table of contents element
177 *
178 * @param $toggleLink jQuery A jQuery object of the toggle link.
179 * @param callback function Function to be called after the toggle is
180 * completed (including the animation) (optional)
181 * @return mixed Boolean visibility of the toc (true if it's visible)
182 * or Null if there was no table of contents.
183 */
184 'toggleToc' : function( $toggleLink, callback ) {
185 var $tocList = $( '#toc ul:first' );
186
187 // This function shouldn't be called if there's no TOC,
188 // but just in case...
189 if ( $tocList.size() ) {
190 if ( $tocList.is( ':hidden' ) ) {
191 $tocList.slideDown( 'fast', callback );
192 $toggleLink.text( mw.msg( 'hidetoc' ) );
193 $( '#toc' ).removeClass( 'tochidden' );
194 $.cookie( 'mw_hidetoc', null, {
195 expires: 30,
196 path: '/'
197 } );
198 return true;
199 } else {
200 $tocList.slideUp( 'fast', callback );
201 $toggleLink.text( mw.msg( 'showtoc' ) );
202 $( '#toc' ).addClass( 'tochidden' );
203 $.cookie( 'mw_hidetoc', '1', {
204 expires: 30,
205 path: '/'
206 } );
207 return false;
208 }
209 } else {
210 return null;
211 }
212 },
213
214 /**
215 * Grab the URL parameter value for the given parameter.
216 * Returns null if not found.
217 *
218 * @param param string The parameter name.
219 * @param url string URL to search through (optional)
220 * @return mixed Parameter value or null.
221 */
222 'getParamValue' : function( param, url ) {
223 url = url ? url : document.location.href;
224 // Get last match, stop at hash
225 var re = new RegExp( '[^#]*[&?]' + $.escapeRE( param ) + '=([^&#]*)' );
226 var m = re.exec( url );
227 if ( m && m.length > 1 ) {
228 return decodeURIComponent( m[1] );
229 }
230 return null;
231 },
232
233 /**
234 * @var string
235 * Access key prefix. Will be re-defined based on browser/operating system
236 * detection in mw.util.init().
237 */
238 'tooltipAccessKeyPrefix' : 'alt-',
239
240 /**
241 * @var RegExp
242 * Regex to match accesskey tooltips.
243 */
244 'tooltipAccessKeyRegexp': /\[(ctrl-)?(alt-)?(shift-)?(esc-)?(.)\]$/,
245
246 /**
247 * Add the appropriate prefix to the accesskey shown in the tooltip.
248 * If the nodeList parameter is given, only those nodes are updated;
249 * otherwise, all the nodes that will probably have accesskeys by
250 * default are updated.
251 *
252 * @param nodeList mixed A jQuery object, or array of elements to update.
253 */
254 'updateTooltipAccessKeys' : function( nodeList ) {
255 var $nodes;
256 if ( nodeList instanceof jQuery ) {
257 $nodes = nodeList;
258 } else if ( nodeList ) {
259 $nodes = $( nodeList );
260 } else {
261 // Rather than scanning all links, just the elements that
262 // contain the relevant links
263 this.updateTooltipAccessKeys(
264 $( '#column-one a, #mw-head a, #mw-panel a, #p-logo a' ) );
265
266 // these are rare enough that no such optimization is needed
267 this.updateTooltipAccessKeys( $( 'input' ) );
268 this.updateTooltipAccessKeys( $( 'label' ) );
269 return;
270 }
271
272 $nodes.each( function ( i ) {
273 var tip = $(this).attr( 'title' );
274 if ( !!tip && mw.util.tooltipAccessKeyRegexp.exec( tip ) ) {
275 tip = tip.replace( mw.util.tooltipAccessKeyRegexp,
276 '[' + mw.util.tooltipAccessKeyPrefix + "$5]" );
277 $(this).attr( 'title', tip );
278 }
279 } );
280 },
281
282 /*
283 * @var jQuery
284 * A jQuery object that refers to the page-content element
285 * Populated by init().
286 */
287 '$content' : null,
288
289 /**
290 * Add a link to a portlet menu on the page, such as:
291 *
292 * p-cactions (Content actions), p-personal (Personal tools),
293 * p-navigation (Navigation), p-tb (Toolbox)
294 *
295 * The first three paramters are required, the others are optional and
296 * may be null. Though providing an id and tooltip is recommended.
297 *
298 * By default the new link will be added to the end of the list. To
299 * add the link before a given existing item, pass the DOM node
300 * (document.getElementById( 'foobar' )) or the jQuery-selector
301 * ( '#foobar' ) of that item.
302 *
303 * @example mw.util.addPortletLink(
304 * 'p-tb', 'http://mediawiki.org/',
305 * 'MediaWiki.org', 't-mworg', 'Go to MediaWiki.org ', 'm', '#t-print'
306 * )
307 *
308 * @param portlet string ID of the target portlet ( 'p-cactions' or 'p-personal' etc.)
309 * @param href string Link URL
310 * @param text string Link text
311 * @param id string ID of the new item, should be unique and preferably have
312 * the appropriate prefix ( 'ca-', 'pt-', 'n-' or 't-' )
313 * @param tooltip string Text to show when hovering over the link, without accesskey suffix
314 * @param accesskey string Access key to activate this link (one character, try
315 * to avoid conflicts. Use $( '[accesskey=x]' ).get() in the console to
316 * see if 'x' is already used.
317 * @param nextnode mixed DOM Node or jQuery-selector string of the item that the new
318 * item should be added before, should be another item in the same
319 * list, it will be ignored otherwise
320 *
321 * @return mixed The DOM Node of the added item (a ListItem or Anchor element,
322 * depending on the skin) or null if no element was added to the document.
323 */
324 'addPortletLink' : function( portlet, href, text, id, tooltip, accesskey, nextnode ) {
325
326 // Check if there's atleast 3 arguments to prevent a TypeError
327 if ( arguments.length < 3 ) {
328 return null;
329 }
330 // Setup the anchor tag
331 var $link = $( '<a></a>' ).attr( 'href', href ).text( text );
332 if ( tooltip ) {
333 $link.attr( 'title', tooltip );
334 }
335
336 // Some skins don't have any portlets
337 // just add it to the bottom of their 'sidebar' element as a fallback
338 switch ( mw.config.get( 'skin' ) ) {
339 case 'standard' :
340 case 'cologneblue' :
341 $( '#quickbar' ).append( $link.after( '<br />' ) );
342 return $link[0];
343 case 'nostalgia' :
344 $( '#searchform' ).before( $link).before( ' &#124; ' );
345 return $link[0];
346 default : // Skins like chick, modern, monobook, myskin, simple, vector...
347
348 // Select the specified portlet
349 var $portlet = $( '#' + portlet );
350 if ( $portlet.length === 0 ) {
351 return null;
352 }
353 // Select the first (most likely only) unordered list inside the portlet
354 var $ul = $portlet.find( 'ul' );
355
356 // If it didn't have an unordered list yet, create it
357 if ( $ul.length === 0 ) {
358 // If there's no <div> inside, append it to the portlet directly
359 if ( $portlet.find( 'div:first' ).length === 0 ) {
360 $portlet.append( '<ul></ul>' );
361 } else {
362 // otherwise if there's a div (such as div.body or div.pBody)
363 // append the <ul> to last (most likely only) div
364 $portlet.find( 'div' ).eq( -1 ).append( '<ul></ul>' );
365 }
366 // Select the created element
367 $ul = $portlet.find( 'ul' ).eq( 0 );
368 }
369 // Just in case..
370 if ( $ul.length === 0 ) {
371 return null;
372 }
373
374 // Unhide portlet if it was hidden before
375 $portlet.removeClass( 'emptyPortlet' );
376
377 // Wrap the anchor tag in a <span> and create a list item for it
378 // and back up the selector to the list item
379 var $item = $link.wrap( '<li><span></span></li>' ).parent().parent();
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 ( mw.util.$content.parent().length ) {
441 mw.util.$content.parent().prepend( $messageDiv );
442 } else {
443 return false;
444 }
445 }
446
447 if ( className ) {
448 $messageDiv.attr( '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 var block = allowBlock ? '(?:\\/(?:3[0-2]|[12]?\\d))?' : '';
550 var RE_IP_BYTE = '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])';
551 var RE_IP_ADD = '(?:' + RE_IP_BYTE + '\\.){3}' + RE_IP_BYTE;
552 return typeof address === 'string' && address.search( new RegExp( '^' + RE_IP_ADD + block + '$' ) ) != -1;
553 },
554 /**
555 * Note: borrows from IP::isIPv6
556 *
557 * @param address string
558 * @param allowBlock boolean
559 * @return boolean
560 */
561 'isIPv6Address' : function( address, allowBlock ) {
562 if ( typeof address !== 'string' ) {
563 return false;
564 }
565 var block = allowBlock ? '(?:\\/(?:12[0-8]|1[01][0-9]|[1-9]?\\d))?' : '';
566 var RE_IPV6_ADD =
567 '(?:' + // starts with "::" (including "::")
568 ':(?::|(?::' + '[0-9A-Fa-f]{1,4}' + '){1,7})' +
569 '|' + // ends with "::" (except "::")
570 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){0,6}::' +
571 '|' + // contains no "::"
572 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){7}' +
573 ')';
574 if ( address.search( new RegExp( '^' + RE_IPV6_ADD + block + '$' ) ) != -1 ) {
575 return true;
576 }
577 RE_IPV6_ADD = // contains one "::" in the middle (single '::' check below)
578 '[0-9A-Fa-f]{1,4}' + '(?:::?' + '[0-9A-Fa-f]{1,4}' + '){1,6}';
579 return address.search( new RegExp( '^' + RE_IPV6_ADD + block + '$' ) ) != -1
580 && address.search( /::/ ) != -1 && address.search( /::.*::/ ) == -1;
581 }
582
583 };
584
585 mw.util.init();
586
587 } )( jQuery, mediaWiki );