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