Merge "Consistent use the same IIFE style in javascript"
[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 * Add the appropriate prefix to the accesskey shown in the tooltip.
175 *
176 * If the `$nodes` parameter is given, only those nodes are updated;
177 * otherwise, depending on browser support, we update either all elements
178 * with accesskeys on the page or a bunch of elements which are likely to
179 * have them on core skins.
180 *
181 * @param {Array|jQuery} [$nodes] A jQuery object, or array of nodes to update.
182 */
183 updateTooltipAccessKeys: function ( $nodes ) {
184 if ( !$nodes ) {
185 if ( document.querySelectorAll ) {
186 // If we're running on a browser where we can do this efficiently,
187 // just find all elements that have accesskeys. We can't use jQuery's
188 // polyfill for the selector since looping over all elements on page
189 // load might be too slow.
190 $nodes = $( document.querySelectorAll( '[accesskey]' ) );
191 } else {
192 // Otherwise go through some elements likely to have accesskeys rather
193 // than looping over all of them. Unfortunately this will not fully
194 // work for custom skins with different HTML structures. Input, label
195 // and button should be rare enough that no optimizations are needed.
196 $nodes = $( '#column-one a, #mw-head a, #mw-panel a, #p-logo a, input, label, button' );
197 }
198 } else if ( !( $nodes instanceof $ ) ) {
199 $nodes = $( $nodes );
200 }
201
202 $nodes.updateTooltipAccessKeys();
203 },
204
205 /*
206 * @property {jQuery}
207 * A jQuery object that refers to the content area element.
208 * Populated by #init.
209 */
210 $content: null,
211
212 /**
213 * Add a link to a portlet menu on the page, such as:
214 *
215 * p-cactions (Content actions), p-personal (Personal tools),
216 * p-navigation (Navigation), p-tb (Toolbox)
217 *
218 * The first three paramters are required, the others are optional and
219 * may be null. Though providing an id and tooltip is recommended.
220 *
221 * By default the new link will be added to the end of the list. To
222 * add the link before a given existing item, pass the DOM node
223 * (e.g. `document.getElementById( 'foobar' )`) or a jQuery-selector
224 * (e.g. `'#foobar'`) for that item.
225 *
226 * mw.util.addPortletLink(
227 * 'p-tb', 'http://mediawiki.org/',
228 * 'MediaWiki.org', 't-mworg', 'Go to MediaWiki.org ', 'm', '#t-print'
229 * );
230 *
231 * @param {string} portlet ID of the target portlet ( 'p-cactions' or 'p-personal' etc.)
232 * @param {string} href Link URL
233 * @param {string} text Link text
234 * @param {string} [id] ID of the new item, should be unique and preferably have
235 * the appropriate prefix ( 'ca-', 'pt-', 'n-' or 't-' )
236 * @param {string} [tooltip] Text to show when hovering over the link, without accesskey suffix
237 * @param {string} [accesskey] Access key to activate this link (one character, try
238 * to avoid conflicts. Use `$( '[accesskey=x]' ).get()` in the console to
239 * see if 'x' is already used.
240 * @param {HTMLElement|jQuery|string} [nextnode] Element or jQuery-selector string to the item that
241 * the new item should be added before, should be another item in the same
242 * list, it will be ignored otherwise
243 *
244 * @return {HTMLElement|null} The added element (a ListItem or Anchor element,
245 * depending on the skin) or null if no element was added to the document.
246 */
247 addPortletLink: function ( portlet, href, text, id, tooltip, accesskey, nextnode ) {
248 var $item, $link, $portlet, $ul;
249
250 // Check if there's atleast 3 arguments to prevent a TypeError
251 if ( arguments.length < 3 ) {
252 return null;
253 }
254 // Setup the anchor tag
255 $link = $( '<a>' ).attr( 'href', href ).text( text );
256 if ( tooltip ) {
257 $link.attr( 'title', tooltip );
258 }
259
260 // Select the specified portlet
261 $portlet = $( '#' + portlet );
262 if ( $portlet.length === 0 ) {
263 return null;
264 }
265 // Select the first (most likely only) unordered list inside the portlet
266 $ul = $portlet.find( 'ul' ).eq( 0 );
267
268 // If it didn't have an unordered list yet, create it
269 if ( $ul.length === 0 ) {
270
271 $ul = $( '<ul>' );
272
273 // If there's no <div> inside, append it to the portlet directly
274 if ( $portlet.find( 'div:first' ).length === 0 ) {
275 $portlet.append( $ul );
276 } else {
277 // otherwise if there's a div (such as div.body or div.pBody)
278 // append the <ul> to last (most likely only) div
279 $portlet.find( 'div' ).eq( -1 ).append( $ul );
280 }
281 }
282 // Just in case..
283 if ( $ul.length === 0 ) {
284 return null;
285 }
286
287 // Unhide portlet if it was hidden before
288 $portlet.removeClass( 'emptyPortlet' );
289
290 // Wrap the anchor tag in a list item (and a span if $portlet is a Vector tab)
291 // and back up the selector to the list item
292 if ( $portlet.hasClass( 'vectorTabs' ) ) {
293 $item = $link.wrap( '<li><span></span></li>' ).parent().parent();
294 } else {
295 $item = $link.wrap( '<li></li>' ).parent();
296 }
297
298 // Implement the properties passed to the function
299 if ( id ) {
300 $item.attr( 'id', id );
301 }
302
303 if ( accesskey ) {
304 $link.attr( 'accesskey', accesskey );
305 }
306
307 if ( tooltip ) {
308 $link.attr( 'title', tooltip ).updateTooltipAccessKeys();
309 }
310
311 if ( nextnode ) {
312 if ( nextnode.nodeType || typeof nextnode === 'string' ) {
313 // nextnode is a DOM element (was the only option before MW 1.17, in wikibits.js)
314 // or nextnode is a CSS selector for jQuery
315 nextnode = $ul.find( nextnode );
316 } else if ( !nextnode.jquery || ( nextnode.length && nextnode[0].parentNode !== $ul[0] ) ) {
317 // Fallback
318 $ul.append( $item );
319 return $item[0];
320 }
321 if ( nextnode.length === 1 ) {
322 // nextnode is a jQuery object that represents exactly one element
323 nextnode.before( $item );
324 return $item[0];
325 }
326 }
327
328 // Fallback (this is the default behavior)
329 $ul.append( $item );
330 return $item[0];
331
332 },
333
334 /**
335 * Validate a string as representing a valid e-mail address
336 * according to HTML5 specification. Please note the specification
337 * does not validate a domain with one character.
338 *
339 * FIXME: should be moved to or replaced by a validation module.
340 *
341 * @param {string} mailtxt E-mail address to be validated.
342 * @return {boolean|null} Null if `mailtxt` was an empty string, otherwise true/false
343 * as determined by validation.
344 */
345 validateEmail: function ( mailtxt ) {
346 var rfc5322Atext, rfc1034LdhStr, html5EmailRegexp;
347
348 if ( mailtxt === '' ) {
349 return null;
350 }
351
352 // HTML5 defines a string as valid e-mail address if it matches
353 // the ABNF:
354 // 1 * ( atext / "." ) "@" ldh-str 1*( "." ldh-str )
355 // With:
356 // - atext : defined in RFC 5322 section 3.2.3
357 // - ldh-str : defined in RFC 1034 section 3.5
358 //
359 // (see STD 68 / RFC 5234 http://tools.ietf.org/html/std68)
360 // First, define the RFC 5322 'atext' which is pretty easy:
361 // atext = ALPHA / DIGIT / ; Printable US-ASCII
362 // "!" / "#" / ; characters not including
363 // "$" / "%" / ; specials. Used for atoms.
364 // "&" / "'" /
365 // "*" / "+" /
366 // "-" / "/" /
367 // "=" / "?" /
368 // "^" / "_" /
369 // "`" / "{" /
370 // "|" / "}" /
371 // "~"
372 rfc5322Atext = 'a-z0-9!#$%&\'*+\\-/=?^_`{|}~';
373
374 // Next define the RFC 1034 'ldh-str'
375 // <domain> ::= <subdomain> | " "
376 // <subdomain> ::= <label> | <subdomain> "." <label>
377 // <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
378 // <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
379 // <let-dig-hyp> ::= <let-dig> | "-"
380 // <let-dig> ::= <letter> | <digit>
381 rfc1034LdhStr = 'a-z0-9\\-';
382
383 html5EmailRegexp = new RegExp(
384 // start of string
385 '^'
386 +
387 // User part which is liberal :p
388 '[' + rfc5322Atext + '\\.]+'
389 +
390 // 'at'
391 '@'
392 +
393 // Domain first part
394 '[' + rfc1034LdhStr + ']+'
395 +
396 // Optional second part and following are separated by a dot
397 '(?:\\.[' + rfc1034LdhStr + ']+)*'
398 +
399 // End of string
400 '$',
401 // RegExp is case insensitive
402 'i'
403 );
404 return ( null !== mailtxt.match( html5EmailRegexp ) );
405 },
406
407 /**
408 * Note: borrows from IP::isIPv4
409 *
410 * @param {string} address
411 * @param {boolean} allowBlock
412 * @return {boolean}
413 */
414 isIPv4Address: function ( address, allowBlock ) {
415 if ( typeof address !== 'string' ) {
416 return false;
417 }
418
419 var block = allowBlock ? '(?:\\/(?:3[0-2]|[12]?\\d))?' : '',
420 RE_IP_BYTE = '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])',
421 RE_IP_ADD = '(?:' + RE_IP_BYTE + '\\.){3}' + RE_IP_BYTE;
422
423 return address.search( new RegExp( '^' + RE_IP_ADD + block + '$' ) ) !== -1;
424 },
425
426 /**
427 * Note: borrows from IP::isIPv6
428 *
429 * @param {string} address
430 * @param {boolean} allowBlock
431 * @return {boolean}
432 */
433 isIPv6Address: function ( address, allowBlock ) {
434 if ( typeof address !== 'string' ) {
435 return false;
436 }
437
438 var block = allowBlock ? '(?:\\/(?:12[0-8]|1[01][0-9]|[1-9]?\\d))?' : '',
439 RE_IPV6_ADD =
440 '(?:' + // starts with "::" (including "::")
441 ':(?::|(?::' + '[0-9A-Fa-f]{1,4}' + '){1,7})' +
442 '|' + // ends with "::" (except "::")
443 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){0,6}::' +
444 '|' + // contains no "::"
445 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){7}' +
446 ')';
447
448 if ( address.search( new RegExp( '^' + RE_IPV6_ADD + block + '$' ) ) !== -1 ) {
449 return true;
450 }
451
452 RE_IPV6_ADD = // contains one "::" in the middle (single '::' check below)
453 '[0-9A-Fa-f]{1,4}' + '(?:::?' + '[0-9A-Fa-f]{1,4}' + '){1,6}';
454
455 return address.search( new RegExp( '^' + RE_IPV6_ADD + block + '$' ) ) !== -1
456 && address.search( /::/ ) !== -1 && address.search( /::.*::/ ) === -1;
457 }
458 };
459
460 /**
461 * @method wikiGetlink
462 * @inheritdoc #getUrl
463 * @deprecated since 1.23 Use #getUrl instead.
464 */
465 mw.log.deprecate( util, 'wikiGetlink', util.getUrl, 'Use mw.util.getUrl instead.' );
466
467 /**
468 * @property {string} tooltipAccessKeyPrefix
469 * Access key prefix. Might be wrong for browsers implementing the accessKeyLabel property.
470 * @deprecated since 1.24 Use the module jquery.accessKeyLabel instead.
471 */
472 mw.log.deprecate( util, 'tooltipAccessKeyPrefix', $.fn.updateTooltipAccessKeys.getAccessKeyPrefix(), 'Use jquery.accessKeyLabel instead.' );
473
474 /**
475 * @property {RegExp} tooltipAccessKeyRegexp
476 * Regex to match accesskey tooltips.
477 *
478 * Should match:
479 *
480 * - "ctrl-option-"
481 * - "alt-shift-"
482 * - "ctrl-alt-"
483 * - "ctrl-"
484 *
485 * The accesskey is matched in group $6.
486 *
487 * Will probably not work for browsers implementing the accessKeyLabel property.
488 *
489 * @deprecated since 1.24 Use the module jquery.accessKeyLabel instead.
490 */
491 mw.log.deprecate( util, 'tooltipAccessKeyRegexp', /\[(ctrl-)?(option-)?(alt-)?(shift-)?(esc-)?(.)\]$/, 'Use jquery.accessKeyLabel instead.' );
492
493 /**
494 * @method jsMessage
495 * Add a little box at the top of the screen to inform the user of
496 * something, replacing any previous message.
497 * Calling with no arguments, with an empty string or null will hide the message
498 *
499 * @param {Mixed} message The DOM-element, jQuery object or HTML-string to be put inside the message box.
500 * to allow CSS/JS to hide different boxes. null = no class used.
501 * @deprecated since 1.20 Use mw#notify
502 */
503 mw.log.deprecate( util, 'jsMessage', function ( message ) {
504 if ( !arguments.length || message === '' || message === null ) {
505 return true;
506 }
507 if ( typeof message !== 'object' ) {
508 message = $.parseHTML( message );
509 }
510 mw.notify( message, { autoHide: true, tag: 'legacy' } );
511 return true;
512 }, 'Use mw.notify instead.' );
513
514 mw.util = util;
515
516 }( mediaWiki, jQuery ) );