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