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