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