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