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