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