Fix r87203: don't use a for..in loop on an array
[lhc/web/wiklou.git] / resources / mediawiki.util / mediawiki.util.js
1 /**
2 * Utilities
3 */
4 ( function( $, mw ) {
5
6 mw.util = {
7
8 /* Initialisation */
9 'initialised' : false,
10 'init' : function() {
11 if ( this.initialised === false ) {
12 this.initialised = true;
13
14 // Any initialisation after the DOM is ready
15 $( function() {
16
17 /* Set up $.messageBox */
18 $.messageBoxNew( {
19 'id': 'mw-js-message',
20 'parent': '#content'
21 } );
22
23 // Shortcut to client profile return
24 var profile = $.client.profile();
25
26 /* Set tooltipAccessKeyPrefix */
27
28 // Opera on any platform
29 if ( profile.name == 'opera' ) {
30 mw.util.tooltipAccessKeyPrefix = 'shift-esc-';
31
32 // Chrome on any platform
33 } else if ( profile.name == 'chrome' ) {
34 // Chrome on Mac or Chrome on other platform ?
35 mw.util.tooltipAccessKeyPrefix = ( profile.platform == 'mac'
36 ? 'ctrl-option-' : 'alt-' );
37
38 // Non-Windows Safari with webkit_version > 526
39 } else if ( profile.platform !== 'win'
40 && profile.name == 'safari'
41 && profile.layoutVersion > 526 ) {
42 mw.util.tooltipAccessKeyPrefix = 'ctrl-alt-';
43
44 // Safari/Konqueror on any platform, or any browser on Mac
45 // (but not Safari on Windows)
46 } else if ( !( profile.platform == 'win' && profile.name == 'safari' )
47 && ( profile.name == 'safari'
48 || profile.platform == 'mac'
49 || profile.name == 'konqueror' ) ) {
50 mw.util.tooltipAccessKeyPrefix = 'ctrl-';
51
52 // Firefox 2.x
53 } else if ( profile.name == 'firefox' && profile.versionBase == '2' ) {
54 mw.util.tooltipAccessKeyPrefix = 'alt-shift-';
55 }
56
57 /* Enable CheckboxShiftClick */
58 $( 'input[type=checkbox]:not(.noshiftselect)' ).checkboxShiftClick();
59
60 /* Enable Tablesorting */
61 $( 'table.sortable' ).tablesorter();
62
63 /* Emulate placeholder if not supported by browser */
64 if ( !( 'placeholder' in document.createElement( 'input' ) ) ) {
65 $( 'input[placeholder]' ).placeholder();
66 }
67
68 /* Fill $content var */
69 if ( $( '#bodyContent' ).length ) {
70 // Vector, Monobook, Chick etc.
71 mw.util.$content = $( '#bodyContent' );
72
73 } else if ( $( '#mw_contentholder' ).length ) {
74 // Modern
75 mw.util.$content = $( '#mw_contentholder' );
76
77 } else if ( $( '#article' ).length ) {
78 // Standard, CologneBlue
79 mw.util.$content = $( '#article' );
80
81 } else {
82 // #content is present on almost all if not all skins. Most skins (the above cases)
83 // have #content too, but as an outer wrapper instead of the article text container.
84 // The skins that don't have an outer wrapper do have #content for everything
85 // so it's a good fallback
86 mw.util.$content = $( '#content' );
87 }
88
89 /* Enable makeCollapse */
90 $( '.mw-collapsible' ).makeCollapsible();
91
92 /* Table of Contents toggle */
93 var $tocContainer = $( '#toc' ),
94 $tocTitle = $( '#toctitle' ),
95 $tocToggleLink = $( '#togglelink' );
96 // Only add it if there is a TOC and there is no toggle added already
97 if ( $tocContainer.size() && $tocTitle.size() && !$tocToggleLink.size() ) {
98 var hideTocCookie = $.cookie( 'mw_hidetoc' );
99 $tocToggleLink = $( '<a href="#" class="internal" id="togglelink">' ).text( mw.msg( 'hidetoc' ) ).click( function(e){
100 e.preventDefault();
101 mw.util.toggleToc( $(this) );
102 } );
103 $tocTitle.append( $tocToggleLink.wrap( '<span class="toctoggle">' ).parent().prepend( '&nbsp;[' ).append( ']&nbsp;' ) );
104
105 if ( hideTocCookie == '1' ) {
106 // Cookie says user want toc hidden
107 $tocToggleLink.click();
108 }
109 }
110 } );
111
112 return true;
113 }
114 return false;
115 },
116
117 /* Main body */
118
119 /**
120 * Encode the string like PHP's rawurlencode
121 *
122 * @param str String to be encoded
123 */
124 'rawurlencode' : function( str ) {
125 str = ( str + '' ).toString();
126 return encodeURIComponent( str )
127 .replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' )
128 .replace( /\)/g, '%29' ).replace( /\*/g, '%2A' ).replace( /~/g, '%7E' );
129 },
130
131 /**
132 * Encode page titles for use in a URL
133 * We want / and : to be included as literal characters in our title URLs
134 * as they otherwise fatally break the title
135 *
136 * @param str String to be encoded
137 */
138 'wikiUrlencode' : function( str ) {
139 return this.rawurlencode( str )
140 .replace( /%20/g, '_' ).replace( /%3A/g, ':' ).replace( /%2F/g, '/' );
141 },
142
143 /**
144 * Append a new style block to the head
145 *
146 * @param text String CSS to be appended
147 * @return CSSStyleSheet object
148 */
149 'addCSS' : function( text ) {
150 var s = document.createElement( 'style' );
151 s.type = 'text/css';
152 s.rel = 'stylesheet';
153 if ( s.styleSheet ) {
154 s.styleSheet.cssText = text; // IE
155 } else {
156 s.appendChild( document.createTextNode( text + '' ) ); // Safari sometimes borks on null
157 }
158 document.getElementsByTagName("head")[0].appendChild( s );
159 return s.sheet || s;
160 },
161
162 /**
163 * Hide/show the table of contents element
164 *
165 * @param $toggleLink jQuery object of the toggle link
166 * @return String boolean visibility of the toc (true means it's visible)
167 */
168 'toggleToc' : function( $toggleLink ) {
169 var $tocList = $( '#toc ul:first' );
170
171 // This function shouldn't be called if there's no TOC,
172 // but just in case...
173 if ( $tocList.size() ) {
174 if ( $tocList.is( ':hidden' ) ) {
175 $tocList.slideDown( 'fast' );
176 $toggleLink.text( mw.msg( 'hidetoc' ) );
177 $.cookie( 'mw_hidetoc', null, {
178 expires: 30,
179 path: '/'
180 } );
181 return true;
182 } else {
183 $tocList.slideUp( 'fast' );
184 $toggleLink.text( mw.msg( 'showtoc' ) );
185 $.cookie( 'mw_hidetoc', '1', {
186 expires: 30,
187 path: '/'
188 } );
189 return false;
190 }
191 } else {
192 return false;
193 }
194 },
195
196 /**
197 * Get the full URL to a page name
198 *
199 * @param str Page name to link to
200 * @return Full URL for page with name of 'str' or false on error
201 */
202 'wikiGetlink' : function( str ) {
203
204 return mw.config.get( 'wgArticlePath' ).replace( '$1', this.wikiUrlencode( str ) );
205 },
206
207 /**
208 * Grab the URL parameter value for the given parameter.
209 * Returns null if not found.
210 *
211 * @param param The parameter name
212 * @param url URL to search through (optional)
213 */
214 'getParamValue' : function( param, url ) {
215 url = url ? url : document.location.href;
216 // Get last match, stop at hash
217 var re = new RegExp( '[^#]*[&?]' + $.escapeRE( param ) + '=([^&#]*)' );
218 var m = re.exec( url );
219 if ( m && m.length > 1 ) {
220 return decodeURIComponent( m[1] );
221 }
222 return null;
223 },
224
225 // Access key prefix.
226 // Will be re-defined based on browser/operating system detection in
227 // mw.util.init().
228 'tooltipAccessKeyPrefix' : 'alt-',
229
230 // Regex to match accesskey tooltips
231 'tooltipAccessKeyRegexp': /\[(ctrl-)?(alt-)?(shift-)?(esc-)?(.)\]$/,
232
233 /**
234 * Add the appropriate prefix to the accesskey shown in the tooltip.
235 * If the nodeList parameter is given, only those nodes are updated;
236 * otherwise, all the nodes that will probably have accesskeys by
237 * default are updated.
238 *
239 * @param nodeList jQuery object, or array of elements
240 */
241 'updateTooltipAccessKeys' : function( nodeList ) {
242 var $nodes;
243 if ( nodeList instanceof jQuery ) {
244 $nodes = nodeList;
245 } else if ( nodeList ) {
246 $nodes = $( nodeList );
247 } else {
248 // Rather than scanning all links, just the elements that
249 // contain the relevant links
250 this.updateTooltipAccessKeys(
251 $( '#column-one a, #mw-head a, #mw-panel a, #p-logo a' ) );
252
253 // these are rare enough that no such optimization is needed
254 this.updateTooltipAccessKeys( $( 'input' ) );
255 this.updateTooltipAccessKeys( $( 'label' ) );
256 return;
257 }
258
259 $nodes.each( function ( i ) {
260 var tip = $(this).attr( 'title' );
261 if ( !!tip && mw.util.tooltipAccessKeyRegexp.exec( tip ) ) {
262 tip = tip.replace( mw.util.tooltipAccessKeyRegexp,
263 '[' + mw.util.tooltipAccessKeyPrefix + "$5]" );
264 $(this).attr( 'title', tip );
265 }
266 } );
267 },
268
269 // jQuery object that refers to the page-content element
270 // Populated by init()
271 '$content' : null,
272
273 /**
274 * Checks wether the current page is the wiki's main page.
275 *
276 * @return Boolean
277 * @deprecated to be removed in 1.18: Use wgIsMainPage in mw.config instead.
278 */
279 'isMainPage' : function() {
280 return mw.config.get( 'wgIsMainPage' );
281 },
282
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, others are optionals. Though
291 * 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 ID of the target portlet ( 'p-cactions' or 'p-personal' etc.)
304 * @param href Link URL
305 * @param text Link text
306 * @param id ID of the new item, should be unique and preferably have
307 * the appropriate prefix ( 'ca-', 'pt-', 'n-' or 't-' )
308 * @param tooltip Text to show when hovering over the link, without accesskey suffix
309 * @param accesskey 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 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 The DOM node of the new item (a LI element, or A element for
317 * older skins) or null.
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 <span> and create a list item for it
373 // and back up the selector to the list item
374 var $item = $link.wrap( '<li><span></span></li>' ).parent().parent();
375
376 // Implement the properties passed to the function
377 if ( id ) {
378 $item.attr( 'id', id );
379 }
380 if ( accesskey ) {
381 $link.attr( 'accesskey', accesskey );
382 tooltip += ' [' + accesskey + ']';
383 $link.attr( 'title', tooltip );
384 }
385 if ( accesskey && tooltip ) {
386 this.updateTooltipAccessKeys( $link );
387 }
388
389 // Append using DOM-element passing
390 if ( nextnode && nextnode.parentNode == $ul[0] ) {
391 $(nextnode).before( $item );
392 } else {
393 // If the jQuery selector isn't found within the <ul>, just
394 // append it at the end
395 if ( $ul.find( nextnode ).length === 0 ) {
396 $ul.append( $item );
397 } else {
398 // Append using jQuery CSS selector
399 $ul.find( nextnode ).eq( 0 ).before( $item );
400 }
401 }
402
403 return $item[0];
404 }
405 },
406
407 /**
408 * Add a little box at the top of the screen to inform the user of
409 * something, replacing any previous message.
410 * Calling with no arguments, with an empty string or null will hide the message
411 *
412 * @param message mixed The DOM-element or HTML-string to be put inside the message box.
413 * @param className string Used in adding a class; should be different for each call
414 * to allow CSS/JS to hide different boxes. null = no class used.
415 * @return boolean True on success, false on failure
416 */
417 'jsMessage' : function( message, className ) {
418
419 if ( !arguments.length || message === '' || message === null ) {
420
421 $( '#mw-js-message' ).empty().hide();
422 return true; // Emptying and hiding message is intended behaviour, return true
423
424 } else {
425 // We special-case skin structures provided by the software. Skins that
426 // choose to abandon or significantly modify our formatting can just define
427 // an mw-js-message div to start with.
428 var $messageDiv = $( '#mw-js-message' );
429 if ( !$messageDiv.length ) {
430 $messageDiv = $( '<div id="mw-js-message">' );
431 if ( mw.util.$content.parent().length ) {
432 mw.util.$content.parent().prepend( $messageDiv );
433 } else {
434 return false;
435 }
436 }
437
438 if ( className ) {
439 $messageDiv.attr( 'class', 'mw-js-message-' + className );
440 }
441
442 if ( typeof message === 'object' ) {
443 $messageDiv.empty();
444 $messageDiv.append( message ); // Append new content
445 } else {
446 $messageDiv.html( message );
447 }
448
449 $messageDiv.slideDown();
450 return true;
451 }
452 },
453
454 /**
455 * Validate a string as representing a valid e-mail address
456 * according to HTML5 specification. Please note the specification
457 * does not validate a domain with one character.
458 *
459 * FIXME: should be moved to or replaced by a JavaScript validation module.
460 */
461 'validateEmail' : function( mailtxt ) {
462 if( mailtxt === '' ) {
463 return null;
464 }
465
466 /**
467 * HTML5 defines a string as valid e-mail address if it matches
468 * the ABNF:
469 * 1 * ( atext / "." ) "@" ldh-str 1*( "." ldh-str )
470 * With:
471 * - atext : defined in RFC 5322 section 3.2.3
472 * - ldh-str : defined in RFC 1034 section 3.5
473 *
474 * (see STD 68 / RFC 5234 http://tools.ietf.org/html/std68):
475 */
476
477 /**
478 * First, define the RFC 5322 'atext' which is pretty easy :
479 * atext = ALPHA / DIGIT / ; Printable US-ASCII
480 "!" / "#" / ; characters not including
481 "$" / "%" / ; specials. Used for atoms.
482 "&" / "'" /
483 "*" / "+" /
484 "-" / "/" /
485 "=" / "?" /
486 "^" / "_" /
487 "`" / "{" /
488 "|" / "}" /
489 "~"
490 */
491 var rfc5322_atext = "a-z0-9!#$%&'*+\\-/=?^_`{|}~",
492
493 /**
494 * Next define the RFC 1034 'ldh-str'
495 * <domain> ::= <subdomain> | " "
496 * <subdomain> ::= <label> | <subdomain> "." <label>
497 * <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
498 * <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
499 * <let-dig-hyp> ::= <let-dig> | "-"
500 * <let-dig> ::= <letter> | <digit>
501 */
502 rfc1034_ldh_str = "a-z0-9\\-",
503
504 HTML5_email_regexp = new RegExp(
505 // start of string
506 '^'
507 +
508 // User part which is liberal :p
509 '[' + rfc5322_atext + '\\.]+'
510 +
511 // 'at'
512 '@'
513 +
514 // Domain first part
515 '[' + rfc1034_ldh_str + ']+'
516 +
517 // Optional second part and following are separated by a dot
518 '(?:\\.[' + rfc1034_ldh_str + ']+)*'
519 +
520 // End of string
521 '$',
522 // RegExp is case insensitive
523 'i'
524 );
525 return (null !== mailtxt.match( HTML5_email_regexp ) );
526 },
527 // Note: borrows from IP::isIPv4
528 'isIPv4Address' : function( address, allowBlock ) {
529 var block = allowBlock ? '(?:\\/(?:3[0-2]|[12]?\\d))?' : '';
530 var RE_IP_BYTE = '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])';
531 var RE_IP_ADD = '(?:' + RE_IP_BYTE + '\\.){3}' + RE_IP_BYTE;
532 return address.search( new RegExp( '^' + RE_IP_ADD + block + '$' ) ) != -1;
533 },
534 // Note: borrows from IP::isIPv6
535 'isIPv6Address' : function( address, allowBlock ) {
536 var block = allowBlock ? '(?:\\/(?:12[0-8]|1[01][0-9]|[1-9]?\\d))?' : '';
537 var RE_IPV6_ADD =
538 '(?:' + // starts with "::" (including "::")
539 ':(?::|(?::' + '[0-9A-Fa-f]{1,4}' + '){1,7})' +
540 '|' + // ends with "::" (except "::")
541 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){0,6}::' +
542 '|' + // contains no "::"
543 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){7}' +
544 ')';
545 if ( address.search( new RegExp( '^' + RE_IPV6_ADD + block + '$' ) ) != -1 ) {
546 return true;
547 }
548 RE_IPV6_ADD = // contains one "::" in the middle (single '::' check below)
549 '[0-9A-Fa-f]{1,4}' + '(?:::?' + '[0-9A-Fa-f]{1,4}' + '){1,6}';
550 return address.search( new RegExp( '^' + RE_IPV6_ADD + block + '$' ) ) != -1
551 && address.search( /::/ ) != -1 && address.search( /::.*::/ ) == -1;
552 }
553
554 };
555
556 mw.util.init();
557
558 } )( jQuery, mediaWiki );