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