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