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