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