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