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