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