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