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