Slight improvements to FormSpecialPage behavior.
[lhc/web/wiklou.git] / resources / 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 var profile, $tocTitle, $tocToggleLink, hideTocCookie;
17
18 /* Set tooltipAccessKeyPrefix */
19 profile = $.client.profile();
20
21 // Opera on any platform
22 if ( profile.name === 'opera' ) {
23 util.tooltipAccessKeyPrefix = 'shift-esc-';
24
25 // Chrome on any platform
26 } else if ( profile.name === 'chrome' ) {
27
28 util.tooltipAccessKeyPrefix = (
29 profile.platform === 'mac'
30 // Chrome on Mac
31 ? 'ctrl-option-'
32 // Chrome on Windows or Linux
33 // (both alt- and alt-shift work, but alt with E, D, F etc does not
34 // work since they are browser shortcuts)
35 : 'alt-shift-'
36 );
37
38 // Non-Windows Safari with webkit_version > 526
39 } else if ( profile.platform !== 'win'
40 && profile.name === 'safari'
41 && profile.layoutVersion > 526 ) {
42 util.tooltipAccessKeyPrefix = 'ctrl-alt-';
43 // Firefox 14+ on Mac
44 } else if ( profile.platform === 'mac'
45 && profile.name === 'firefox'
46 && profile.versionNumber >= 14 ) {
47 util.tooltipAccessKeyPrefix = 'ctrl-option-';
48 // Safari/Konqueror on any platform, or any browser on Mac
49 // (but not Safari on Windows)
50 } else if ( !( profile.platform === 'win' && profile.name === 'safari' )
51 && ( profile.name === 'safari'
52 || profile.platform === 'mac'
53 || profile.name === 'konqueror' ) ) {
54 util.tooltipAccessKeyPrefix = 'ctrl-';
55
56 // Firefox 2.x and later
57 } else if ( profile.name === 'firefox' && profile.versionBase > '1' ) {
58 util.tooltipAccessKeyPrefix = 'alt-shift-';
59 }
60
61 /* Fill $content var */
62 util.$content = ( function () {
63 var i, l, $content, selectors;
64 selectors = [
65 // The preferred standard for setting $content (class="mw-body")
66 // You may also use (class="mw-body mw-body-primary") if you use
67 // mw-body in multiple locations.
68 // Or class="mw-body-primary" if you want $content to be deeper
69 // in the dom than mw-body
70 '.mw-body-primary',
71 '.mw-body',
72
73 /* Legacy fallbacks for setting the content */
74 // Vector, Monobook, Chick, etc... based skins
75 '#bodyContent',
76
77 // Modern based skins
78 '#mw_contentholder',
79
80 // Standard, CologneBlue
81 '#article',
82
83 // #content is present on almost all if not all skins. Most skins (the above cases)
84 // have #content too, but as an outer wrapper instead of the article text container.
85 // The skins that don't have an outer wrapper do have #content for everything
86 // so it's a good fallback
87 '#content',
88
89 // If nothing better is found fall back to our bodytext div that is guaranteed to be here
90 '#mw-content-text',
91
92 // Should never happen... well, it could if someone is not finished writing a skin and has
93 // not inserted bodytext yet. But in any case <body> should always exist
94 'body'
95 ];
96 for ( i = 0, l = selectors.length; i < l; i++ ) {
97 $content = $( selectors[i] ).first();
98 if ( $content.length ) {
99 return $content;
100 }
101 }
102
103 // Make sure we don't unset util.$content if it was preset and we don't find anything
104 return util.$content;
105 } )();
106
107 // Table of contents toggle
108 $tocTitle = $( '#toctitle' );
109 $tocToggleLink = $( '#togglelink' );
110 // Only add it if there is a TOC and there is no toggle added already
111 if ( $( '#toc' ).length && $tocTitle.length && !$tocToggleLink.length ) {
112 hideTocCookie = $.cookie( 'mw_hidetoc' );
113 $tocToggleLink = $( '<a href="#" class="internal" id="togglelink"></a>' )
114 .text( mw.msg( 'hidetoc' ) )
115 .click( function ( e ) {
116 e.preventDefault();
117 util.toggleToc( $(this) );
118 } );
119 $tocTitle.append(
120 $tocToggleLink
121 .wrap( '<span class="toctoggle"></span>' )
122 .parent()
123 .prepend( '&nbsp;[' )
124 .append( ']&nbsp;' )
125 );
126
127 if ( hideTocCookie === '1' ) {
128 util.toggleToc( $tocToggleLink );
129 }
130 }
131 },
132
133 /* Main body */
134
135 /**
136 * Encode the string like PHP's rawurlencode
137 *
138 * @param {string} str String to be encoded.
139 */
140 rawurlencode: function ( str ) {
141 str = String( str );
142 return encodeURIComponent( str )
143 .replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' )
144 .replace( /\)/g, '%29' ).replace( /\*/g, '%2A' ).replace( /~/g, '%7E' );
145 },
146
147 /**
148 * Encode page titles for use in a URL
149 * We want / and : to be included as literal characters in our title URLs
150 * as they otherwise fatally break the title
151 *
152 * @param {string} str String to be encoded.
153 */
154 wikiUrlencode: function ( str ) {
155 return util.rawurlencode( str )
156 .replace( /%20/g, '_' ).replace( /%3A/g, ':' ).replace( /%2F/g, '/' );
157 },
158
159 /**
160 * Get the link to a page name (relative to `wgServer`),
161 *
162 * @param {string} str Page name to get the link for.
163 * @return {string} Location for a page with name of `str` or boolean false on error.
164 */
165 wikiGetlink: function ( str ) {
166 return mw.config.get( 'wgArticlePath' ).replace( '$1',
167 util.wikiUrlencode( typeof str === 'string' ? str : mw.config.get( 'wgPageName' ) ) );
168 },
169
170 /**
171 * Get address to a script in the wiki root.
172 * For index.php use `mw.config.get( 'wgScript' )`.
173 *
174 * @since 1.18
175 * @param str string Name of script (eg. 'api'), defaults to 'index'
176 * @return string Address to script (eg. '/w/api.php' )
177 */
178 wikiScript: function ( str ) {
179 str = str || 'index';
180 if ( str === 'index' ) {
181 return mw.config.get( 'wgScript' );
182 } else if ( str === 'load' ) {
183 return mw.config.get( 'wgLoadScript' );
184 } else {
185 return mw.config.get( 'wgScriptPath' ) + '/' + str +
186 mw.config.get( 'wgScriptExtension' );
187 }
188 },
189
190 /**
191 * Append a new style block to the head and return the CSSStyleSheet object.
192 * Use .ownerNode to access the `<style>` element, or use mw.loader#addStyleTag.
193 * This function returns the styleSheet object for convience (due to cross-browsers
194 * difference as to where it is located).
195 *
196 * var sheet = mw.util.addCSS('.foobar { display: none; }');
197 * $(foo).click(function () {
198 * // Toggle the sheet on and off
199 * sheet.disabled = !sheet.disabled;
200 * });
201 *
202 * @param {string} text CSS to be appended
203 * @return {CSSStyleSheet} Use .ownerNode to get to the `<style>` element.
204 */
205 addCSS: function ( text ) {
206 var s = mw.loader.addStyleTag( text );
207 return s.sheet || s;
208 },
209
210 /**
211 * Hide/show the table of contents element
212 *
213 * @param {jQuery} $toggleLink A jQuery object of the toggle link.
214 * @param {Function} [callback] Function to be called after the toggle is
215 * completed (including the animation).
216 * @return {Mixed} Boolean visibility of the toc (true if it's visible)
217 * or Null if there was no table of contents.
218 */
219 toggleToc: function ( $toggleLink, callback ) {
220 var $tocList = $( '#toc ul:first' );
221
222 // This function shouldn't be called if there's no TOC,
223 // but just in case...
224 if ( $tocList.length ) {
225 if ( $tocList.is( ':hidden' ) ) {
226 $tocList.slideDown( 'fast', callback );
227 $toggleLink.text( mw.msg( 'hidetoc' ) );
228 $( '#toc' ).removeClass( 'tochidden' );
229 $.cookie( 'mw_hidetoc', null, {
230 expires: 30,
231 path: '/'
232 } );
233 return true;
234 } else {
235 $tocList.slideUp( 'fast', callback );
236 $toggleLink.text( mw.msg( 'showtoc' ) );
237 $( '#toc' ).addClass( 'tochidden' );
238 $.cookie( 'mw_hidetoc', '1', {
239 expires: 30,
240 path: '/'
241 } );
242 return false;
243 }
244 } else {
245 return null;
246 }
247 },
248
249 /**
250 * Grab the URL parameter value for the given parameter.
251 * Returns null if not found.
252 *
253 * @param {string} param The parameter name.
254 * @param {string} [url] URL to search through.
255 * @return {Mixed} Parameter value or null.
256 */
257 getParamValue: function ( param, url ) {
258 if ( url === undefined ) {
259 url = document.location.href;
260 }
261 // Get last match, stop at hash
262 var re = new RegExp( '^[^#]*[&?]' + $.escapeRE( param ) + '=([^&#]*)' ),
263 m = re.exec( url );
264 if ( m ) {
265 // Beware that decodeURIComponent is not required to understand '+'
266 // by spec, as encodeURIComponent does not produce it.
267 return decodeURIComponent( m[1].replace( /\+/g, '%20' ) );
268 }
269 return null;
270 },
271
272 /**
273 * @property {string}
274 * Access key prefix. Will be re-defined based on browser/operating system
275 * detection in mw.util#init.
276 */
277 tooltipAccessKeyPrefix: 'alt-',
278
279 /**
280 * @property {RegExp}
281 * Regex to match accesskey tooltips.
282 */
283 tooltipAccessKeyRegexp: /\[(ctrl-)?(alt-)?(shift-)?(esc-)?(.)\]$/,
284
285 /**
286 * Add the appropriate prefix to the accesskey shown in the tooltip.
287 * If the nodeList parameter is given, only those nodes are updated;
288 * otherwise, all the nodes that will probably have accesskeys by
289 * default are updated.
290 *
291 * @param {Array|jQuery} [$nodes] A jQuery object, or array of nodes to update.
292 */
293 updateTooltipAccessKeys: function ( $nodes ) {
294 if ( !$nodes ) {
295 // Rather than going into a loop of all anchor tags, limit to few elements that
296 // contain the relevant anchor tags.
297 // Input and label are rare enough that no such optimization is needed
298 $nodes = $( '#column-one a, #mw-head a, #mw-panel a, #p-logo a, input, label' );
299 } else if ( !( $nodes instanceof $ ) ) {
300 $nodes = $( $nodes );
301 }
302
303 $nodes.attr( 'title', function ( i, val ) {
304 if ( val && util.tooltipAccessKeyRegexp.exec( val ) ) {
305 return val.replace( util.tooltipAccessKeyRegexp,
306 '[' + util.tooltipAccessKeyPrefix + '$5]' );
307 }
308 return val;
309 } );
310 },
311
312 /*
313 * @property {jQuery}
314 * A jQuery object that refers to the content area element.
315 * Populated by #init.
316 */
317 $content: null,
318
319 /**
320 * Add a link to a portlet menu on the page, such as:
321 *
322 * p-cactions (Content actions), p-personal (Personal tools),
323 * p-navigation (Navigation), p-tb (Toolbox)
324 *
325 * The first three paramters are required, the others are optional and
326 * may be null. Though providing an id and tooltip is recommended.
327 *
328 * By default the new link will be added to the end of the list. To
329 * add the link before a given existing item, pass the DOM node
330 * (e.g. `document.getElementById( 'foobar' )`) or a jQuery-selector
331 * (e.g. `'#foobar'`) for that item.
332 *
333 * mw.util.addPortletLink(
334 * 'p-tb', 'http://mediawiki.org/',
335 * 'MediaWiki.org', 't-mworg', 'Go to MediaWiki.org ', 'm', '#t-print'
336 * );
337 *
338 * @param {string} portlet ID of the target portlet ( 'p-cactions' or 'p-personal' etc.)
339 * @param {string} href Link URL
340 * @param {string} text Link text
341 * @param {string} [id] ID of the new item, should be unique and preferably have
342 * the appropriate prefix ( 'ca-', 'pt-', 'n-' or 't-' )
343 * @param {string} [tooltip] Text to show when hovering over the link, without accesskey suffix
344 * @param {string} [accesskey] Access key to activate this link (one character, try
345 * to avoid conflicts. Use `$( '[accesskey=x]' ).get()` in the console to
346 * see if 'x' is already used.
347 * @param {HTMLElement|jQuery|string} [nextnode] Element or jQuery-selector string to the item that
348 * the new item should be added before, should be another item in the same
349 * list, it will be ignored otherwise
350 *
351 * @return {HTMLElement|null} The added element (a ListItem or Anchor element,
352 * depending on the skin) or null if no element was added to the document.
353 */
354 addPortletLink: function ( portlet, href, text, id, tooltip, accesskey, nextnode ) {
355 var $item, $link, $portlet, $ul;
356
357 // Check if there's atleast 3 arguments to prevent a TypeError
358 if ( arguments.length < 3 ) {
359 return null;
360 }
361 // Setup the anchor tag
362 $link = $( '<a>' ).attr( 'href', href ).text( text );
363 if ( tooltip ) {
364 $link.attr( 'title', tooltip );
365 }
366
367 // Select the specified portlet
368 $portlet = $( '#' + portlet );
369 if ( $portlet.length === 0 ) {
370 return null;
371 }
372 // Select the first (most likely only) unordered list inside the portlet
373 $ul = $portlet.find( 'ul' ).eq( 0 );
374
375 // If it didn't have an unordered list yet, create it
376 if ( $ul.length === 0 ) {
377
378 $ul = $( '<ul>' );
379
380 // If there's no <div> inside, append it to the portlet directly
381 if ( $portlet.find( 'div:first' ).length === 0 ) {
382 $portlet.append( $ul );
383 } else {
384 // otherwise if there's a div (such as div.body or div.pBody)
385 // append the <ul> to last (most likely only) div
386 $portlet.find( 'div' ).eq( -1 ).append( $ul );
387 }
388 }
389 // Just in case..
390 if ( $ul.length === 0 ) {
391 return null;
392 }
393
394 // Unhide portlet if it was hidden before
395 $portlet.removeClass( 'emptyPortlet' );
396
397 // Wrap the anchor tag in a list item (and a span if $portlet is a Vector tab)
398 // and back up the selector to the list item
399 if ( $portlet.hasClass( 'vectorTabs' ) ) {
400 $item = $link.wrap( '<li><span></span></li>' ).parent().parent();
401 } else {
402 $item = $link.wrap( '<li></li>' ).parent();
403 }
404
405 // Implement the properties passed to the function
406 if ( id ) {
407 $item.attr( 'id', id );
408 }
409 if ( accesskey ) {
410 $link.attr( 'accesskey', accesskey );
411 tooltip += ' [' + accesskey + ']';
412 $link.attr( 'title', tooltip );
413 }
414 if ( accesskey && tooltip ) {
415 util.updateTooltipAccessKeys( $link );
416 }
417
418 // Where to put our node ?
419 // - nextnode is a DOM element (was the only option before MW 1.17, in wikibits.js)
420 if ( nextnode && nextnode.parentNode === $ul[0] ) {
421 $(nextnode).before( $item );
422
423 // - nextnode is a CSS selector for jQuery
424 } else if ( typeof nextnode === 'string' && $ul.find( nextnode ).length !== 0 ) {
425 $ul.find( nextnode ).eq( 0 ).before( $item );
426
427 // If the jQuery selector isn't found within the <ul>,
428 // or if nextnode was invalid or not passed at all,
429 // then just append it at the end of the <ul> (this is the default behavior)
430 } else {
431 $ul.append( $item );
432 }
433
434 return $item[0];
435 },
436
437 /**
438 * Add a little box at the top of the screen to inform the user of
439 * something, replacing any previous message.
440 * Calling with no arguments, with an empty string or null will hide the message
441 *
442 * @param {Mixed} message The DOM-element, jQuery object or HTML-string to be put inside the message box.
443 * to allow CSS/JS to hide different boxes. null = no class used.
444 * @deprecated Use mw#notify
445 */
446 jsMessage: function ( message ) {
447 if ( !arguments.length || message === '' || message === null ) {
448 return true;
449 }
450 if ( typeof message !== 'object' ) {
451 message = $.parseHTML( message );
452 }
453 mw.notify( message, { autoHide: true, tag: 'legacy' } );
454 return true;
455 },
456
457 /**
458 * Validate a string as representing a valid e-mail address
459 * according to HTML5 specification. Please note the specification
460 * does not validate a domain with one character.
461 *
462 * FIXME: should be moved to or replaced by a validation module.
463 *
464 * @param {string} mailtxt E-mail address to be validated.
465 * @return {boolean|null} Null if `mailtxt` was an empty string, otherwise true/false
466 * as determined by validation.
467 */
468 validateEmail: function ( mailtxt ) {
469 var rfc5322Atext, rfc1034LdhStr, html5EmailRegexp;
470
471 if ( mailtxt === '' ) {
472 return null;
473 }
474
475 // HTML5 defines a string as valid e-mail address if it matches
476 // the ABNF:
477 // 1 * ( atext / "." ) "@" ldh-str 1*( "." ldh-str )
478 // With:
479 // - atext : defined in RFC 5322 section 3.2.3
480 // - ldh-str : defined in RFC 1034 section 3.5
481 //
482 // (see STD 68 / RFC 5234 http://tools.ietf.org/html/std68)
483 // First, define the RFC 5322 'atext' which is pretty easy:
484 // atext = ALPHA / DIGIT / ; Printable US-ASCII
485 // "!" / "#" / ; characters not including
486 // "$" / "%" / ; specials. Used for atoms.
487 // "&" / "'" /
488 // "*" / "+" /
489 // "-" / "/" /
490 // "=" / "?" /
491 // "^" / "_" /
492 // "`" / "{" /
493 // "|" / "}" /
494 // "~"
495 rfc5322Atext = 'a-z0-9!#$%&\'*+\\-/=?^_`{|}~';
496
497 // Next define the RFC 1034 'ldh-str'
498 // <domain> ::= <subdomain> | " "
499 // <subdomain> ::= <label> | <subdomain> "." <label>
500 // <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
501 // <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
502 // <let-dig-hyp> ::= <let-dig> | "-"
503 // <let-dig> ::= <letter> | <digit>
504 rfc1034LdhStr = 'a-z0-9\\-';
505
506 html5EmailRegexp = new RegExp(
507 // start of string
508 '^'
509 +
510 // User part which is liberal :p
511 '[' + rfc5322Atext + '\\.]+'
512 +
513 // 'at'
514 '@'
515 +
516 // Domain first part
517 '[' + rfc1034LdhStr + ']+'
518 +
519 // Optional second part and following are separated by a dot
520 '(?:\\.[' + rfc1034LdhStr + ']+)*'
521 +
522 // End of string
523 '$',
524 // RegExp is case insensitive
525 'i'
526 );
527 return (null !== mailtxt.match( html5EmailRegexp ) );
528 },
529
530 /**
531 * Note: borrows from IP::isIPv4
532 *
533 * @param {string} address
534 * @param {boolean} allowBlock
535 * @return {boolean}
536 */
537 isIPv4Address: function ( address, allowBlock ) {
538 if ( typeof address !== 'string' ) {
539 return false;
540 }
541
542 var block = allowBlock ? '(?:\\/(?:3[0-2]|[12]?\\d))?' : '',
543 RE_IP_BYTE = '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])',
544 RE_IP_ADD = '(?:' + RE_IP_BYTE + '\\.){3}' + RE_IP_BYTE;
545
546 return address.search( new RegExp( '^' + RE_IP_ADD + block + '$' ) ) !== -1;
547 },
548
549 /**
550 * Note: borrows from IP::isIPv6
551 *
552 * @param {string} address
553 * @param {boolean} allowBlock
554 * @return {boolean}
555 */
556 isIPv6Address: function ( address, allowBlock ) {
557 if ( typeof address !== 'string' ) {
558 return false;
559 }
560
561 var block = allowBlock ? '(?:\\/(?:12[0-8]|1[01][0-9]|[1-9]?\\d))?' : '',
562 RE_IPV6_ADD =
563 '(?:' + // starts with "::" (including "::")
564 ':(?::|(?::' + '[0-9A-Fa-f]{1,4}' + '){1,7})' +
565 '|' + // ends with "::" (except "::")
566 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){0,6}::' +
567 '|' + // contains no "::"
568 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){7}' +
569 ')';
570
571 if ( address.search( new RegExp( '^' + RE_IPV6_ADD + block + '$' ) ) !== -1 ) {
572 return true;
573 }
574
575 RE_IPV6_ADD = // contains one "::" in the middle (single '::' check below)
576 '[0-9A-Fa-f]{1,4}' + '(?:::?' + '[0-9A-Fa-f]{1,4}' + '){1,6}';
577
578 return address.search( new RegExp( '^' + RE_IPV6_ADD + block + '$' ) ) !== -1
579 && address.search( /::/ ) !== -1 && address.search( /::.*::/ ) === -1;
580 }
581 };
582
583 mw.util = util;
584
585 }( mediaWiki, jQuery ) );