Aleksander Machniak
2016-02-22 9ae41d906e5c68da2e6dca295f9404b177fbc0d1
commit | author | age
b34d67 1 /**
TB 2  * Roundcube common js library
3  *
4  * This file is part of the Roundcube Webmail client
5  *
6  * @licstart  The following is the entire license notice for the
7  * JavaScript code in this file.
8  *
9  * Copyright (c) 2005-2014, The Roundcube Dev Team
10  *
11  * The JavaScript code in this page is free software: you can
12  * redistribute it and/or modify it under the terms of the GNU
13  * General Public License (GNU GPL) as published by the Free Software
14  * Foundation, either version 3 of the License, or (at your option)
15  * any later version.  The code is distributed WITHOUT ANY WARRANTY;
16  * without even the implied warranty of MERCHANTABILITY or FITNESS
17  * FOR A PARTICULAR PURPOSE.  See the GNU GPL for more details.
18  *
19  * As additional permission under GNU GPL version 3 section 7, you
20  * may distribute non-source (e.g., minimized or compacted) forms of
21  * that code without the copy of the GNU GPL normally required by
22  * section 4, provided you include this license notice and a URL
23  * through which recipients can access the Corresponding Source.
24  *
25  * @licend  The above is the entire license notice
26  * for the JavaScript code in this file.
27  */
4e17e6 28
6b47de 29 // Constants
T 30 var CONTROL_KEY = 1;
31 var SHIFT_KEY = 2;
32 var CONTROL_SHIFT_KEY = 3;
4e17e6 33
6b47de 34 /**
T 35  * Default browser check class
186537 36  * @constructor
6b47de 37  */
4e17e6 38 function roundcube_browser()
8fa922 39 {
8fd1cf 40   var n = navigator;
A 41
42   this.agent = n.userAgent;
43   this.agent_lc = n.userAgent.toLowerCase();
44   this.name = n.appName;
45   this.vendor = n.vendor ? n.vendor : '';
46   this.vendver = n.vendorSub ? parseFloat(n.vendorSub) : 0;
47   this.product = n.product ? n.product : '';
48   this.platform = String(n.platform).toLowerCase();
741ddc 49   this.lang = n.language ? n.language.substring(0,2) :
AM 50               n.browserLanguage ? n.browserLanguage.substring(0,2) :
51               n.systemLanguage ? n.systemLanguage.substring(0,2) : 'en';
4e17e6 52
741ddc 53   this.win = this.platform.indexOf('win') >= 0;
AM 54   this.mac = this.platform.indexOf('mac') >= 0;
55   this.linux = this.platform.indexOf('linux') >= 0;
56   this.unix = this.platform.indexOf('unix') >= 0;
4e17e6 57
T 58   this.dom = document.getElementById ? true : false;
741ddc 59   this.dom2 = document.addEventListener && document.removeEventListener;
4e17e6 60
03f169 61   this.webkit = this.agent_lc.indexOf('applewebkit') > 0;
f03ed8 62   this.ie = (document.all && !window.opera) || (this.win && this.agent_lc.indexOf('trident/') > 0);
4e17e6 63
f03ed8 64   if (this.ie) {
06d424 65     this.ie7 = n.appVersion.indexOf('MSIE 7') > 0;
AM 66     this.ie8 = n.appVersion.indexOf('MSIE 8') > 0;
67     this.ie9 = n.appVersion.indexOf('MSIE 9') > 0;
f03ed8 68   }
03f169 69   else if (window.opera) {
06d424 70     this.opera = true; // Opera < 15
03f169 71     this.vendver = opera.version();
AM 72   }
f03ed8 73   else {
AM 74     this.chrome = this.agent_lc.indexOf('chrome') > 0;
06d424 75     this.opera = this.webkit && this.agent.indexOf(' OPR/') > 0; // Opera >= 15
AM 76     this.safari = !this.chrome && !this.opera && (this.webkit || this.agent_lc.indexOf('safari') > 0);
f03ed8 77     this.konq = this.agent_lc.indexOf('konqueror') > 0;
06d424 78     this.mz = this.dom && !this.chrome && !this.safari && !this.konq && !this.opera && this.agent.indexOf('Mozilla') >= 0;
f03ed8 79     this.iphone = this.safari && (this.agent_lc.indexOf('iphone') > 0 || this.agent_lc.indexOf('ipod') > 0);
AM 80     this.ipad = this.safari && this.agent_lc.indexOf('ipad') > 0;
81   }
4e17e6 82
741ddc 83   if (!this.vendver) {
AM 84     // common version strings
03f169 85     this.vendver = /(opera|opr|khtml|chrome|safari|applewebkit|msie)(\s|\/)([0-9\.]+)/.test(this.agent_lc) ? parseFloat(RegExp.$3) : 0;
741ddc 86
AM 87     // any other (Mozilla, Camino, IE>=11)
88     if (!this.vendver)
89       this.vendver = /rv:([0-9\.]+)/.test(this.agent) ? parseFloat(RegExp.$1) : 0;
90   }
42b113 91
4e17e6 92   // get real language out of safari's user agent
129aef 93   if (this.safari && (/;\s+([a-z]{2})-[a-z]{2}\)/.test(this.agent_lc)))
4e17e6 94     this.lang = RegExp.$1;
T 95
4910b0 96   this.tablet = /ipad|android|xoom|sch-i800|playbook|tablet|kindle/i.test(this.agent_lc);
TB 97   this.mobile = /iphone|ipod|blackberry|iemobile|opera mini|opera mobi|mobile/i.test(this.agent_lc);
98   this.touch = this.mobile || this.tablet;
8fd1cf 99   this.cookies = n.cookieEnabled;
b231f6 100
a95e0e 101   // test for XMLHTTP support
89e31b 102   this.xmlhttp_test = function()
T 103   {
a95e0e 104     var activeX_test = new Function("try{var o=new ActiveXObject('Microsoft.XMLHTTP');return true;}catch(err){return false;}");
b6b285 105     this.xmlhttp = window.XMLHttpRequest || (('ActiveXObject' in window) && activeX_test());
a95e0e 106     return this.xmlhttp;
89e31b 107   };
b231f6 108
89e31b 109   // set class names to html tag according to the current user agent detection
T 110   // this allows browser-specific css selectors like "html.chrome .someclass"
111   this.set_html_class = function()
112   {
113     var classname = ' js';
114
43d98b 115     if (this.ie)
T 116       classname += ' ie ie'+parseInt(this.vendver);
89e31b 117     else if (this.opera)
T 118       classname += ' opera';
119     else if (this.konq)
120       classname += ' konqueror';
121     else if (this.safari)
122       classname += ' chrome';
071c78 123     else if (this.chrome)
T 124       classname += ' chrome';
4188c6 125     else if (this.mz)
AM 126       classname += ' mozilla';
071c78 127
T 128     if (this.iphone)
89e31b 129       classname += ' iphone';
T 130     else if (this.ipad)
131       classname += ' ipad';
03f169 132     else if (this.webkit)
071c78 133       classname += ' webkit';
89e31b 134
1257dd 135     if (this.mobile)
AM 136       classname += ' mobile';
4910b0 137     if (this.tablet)
TB 138       classname += ' tablet';
1257dd 139
89e31b 140     if (document.documentElement)
T 141       document.documentElement.className += classname;
142   };
8fa922 143 };
4e17e6 144
T 145
cc97ea 146 // static functions for DOM event handling
6b47de 147 var rcube_event = {
T 148
a0ce2f 149 /**
T 150  * returns the event target element
151  */
152 get_target: function(e)
153 {
154   e = e || window.event;
155   return e && e.target ? e.target : e.srcElement;
156 },
157
158 /**
159  * returns the event key code
160  */
161 get_keycode: function(e)
162 {
163   e = e || window.event;
164   return e && e.keyCode ? e.keyCode : (e && e.which ? e.which : 0);
165 },
9bbb17 166
6b47de 167 /**
f89f03 168  * returns the event key code
T 169  */
170 get_button: function(e)
171 {
172   e = e || window.event;
ef4f59 173   return e && e.button !== undefined ? e.button : (e && e.which ? e.which : 0);
f89f03 174 },
T 175
176 /**
6b47de 177  * returns modifier key (constants defined at top of file)
T 178  */
179 get_modifier: function(e)
180 {
181   var opcode = 0;
182   e = e || window.event;
183
699a25 184   if (bw.mac && e)
6b47de 185     opcode += (e.metaKey && CONTROL_KEY) + (e.shiftKey && SHIFT_KEY);
699a25 186   else if (e)
6b47de 187     opcode += (e.ctrlKey && CONTROL_KEY) + (e.shiftKey && SHIFT_KEY);
699a25 188
A 189   return opcode;
6b47de 190 },
T 191
192 /**
193  * Return absolute mouse position of an event
194  */
195 get_mouse_pos: function(e)
196 {
197   if (!e) e = window.event;
b231f6 198   var mX = (e.pageX) ? e.pageX : e.clientX,
A 199     mY = (e.pageY) ? e.pageY : e.clientY;
6b47de 200
8fa922 201   if (document.body && document.all) {
6b47de 202     mX += document.body.scrollLeft;
T 203     mY += document.body.scrollTop;
204   }
205
cf6bc5 206   if (e._offset) {
cc97ea 207     mX += e._offset.left;
T 208     mY += e._offset.top;
cf6bc5 209   }
A 210
6b47de 211   return { x:mX, y:mY };
T 212 },
213
214 /**
215  * Add an object method as event listener to a certain element
216  */
217 add_listener: function(p)
218 {
219   if (!p.object || !p.method)  // not enough arguments
220     return;
221   if (!p.element)
222     p.element = document;
223
224   if (!p.object._rc_events)
f923d4 225     p.object._rc_events = {};
b231f6 226
6b47de 227   var key = p.event + '*' + p.method;
T 228   if (!p.object._rc_events[key])
229     p.object._rc_events[key] = function(e){ return p.object[p.method](e); };
230
231   if (p.element.addEventListener)
232     p.element.addEventListener(p.event, p.object._rc_events[key], false);
8fa922 233   else if (p.element.attachEvent) {
a265ab 234     // IE allows multiple events with the same function to be applied to the same object
T 235     // forcibly detach the event, then attach
236     p.element.detachEvent('on'+p.event, p.object._rc_events[key]);
6b47de 237     p.element.attachEvent('on'+p.event, p.object._rc_events[key]);
8fa922 238   }
6b47de 239   else
T 240     p.element['on'+p.event] = p.object._rc_events[key];
241 },
242
243 /**
244  * Remove event listener
245  */
246 remove_listener: function(p)
247 {
248   if (!p.element)
249     p.element = document;
250
251   var key = p.event + '*' + p.method;
252   if (p.object && p.object._rc_events && p.object._rc_events[key]) {
253     if (p.element.removeEventListener)
254       p.element.removeEventListener(p.event, p.object._rc_events[key], false);
255     else if (p.element.detachEvent)
256       p.element.detachEvent('on'+p.event, p.object._rc_events[key]);
257     else
258       p.element['on'+p.event] = null;
259   }
260 },
261
262 /**
3d78d5 263  * Prevent event propagation and bubbling
6b47de 264  */
T 265 cancel: function(evt)
266 {
267   var e = evt ? evt : window.event;
398b7a 268
6b47de 269   if (e.preventDefault)
T 270     e.preventDefault();
398b7a 271   else
AM 272     e.returnValue = false;
273
6b47de 274   if (e.stopPropagation)
T 275     e.stopPropagation();
276
277   e.cancelBubble = true;
398b7a 278
6b47de 279   return false;
8ef2f3 280 },
T 281
e8bcf0 282 /**
TB 283  * Determine whether the given event was trigered from keyboard
284  */
285 is_keyboard: function(e)
286 {
287   return e && (
bf3379 288       (e.pointerType !== undefined && e.pointerType !== 'mouse') ||       // IE 11+
TB 289       (e.mozInputSource && e.mozInputSource == e.MOZ_SOURCE_KEYBOARD) ||  // Firefox
51cae1 290       (e.offsetX === 0 && e.offsetY === 0) || // Opera
bf3379 291       (!e.pageX && (e.pageY || 0) <= 0 && !e.clientX && (e.clientY || 0) <= 0) ||  // others
TB 292       (bw.ie && rcube_event._last_keyboard_event && rcube_event._last_keyboard_event.target == e.target)  // hack for IE <= 10
e8bcf0 293     );
TB 294 },
295
296 /**
297  * Accept event if triggered from keyboard action (e.g. <Enter>)
298  */
299 keyboard_only: function(e)
300 {
301   return rcube_event.is_keyboard(e) ? true : rcube_event.cancel(e);
302 },
303
8ef2f3 304 touchevent: function(e)
T 305 {
306   return { pageX:e.pageX, pageY:e.pageY, offsetX:e.pageX - e.target.offsetLeft, offsetY:e.pageY - e.target.offsetTop, target:e.target, istouch:true };
6b47de 307 }
T 308
309 };
4e17e6 310
T 311
cc97ea 312 /**
T 313  * rcmail objects event interface
314  */
315 function rcube_event_engine()
316 {
317   this._events = {};
8fa922 318 };
cc97ea 319
T 320 rcube_event_engine.prototype = {
321
322 /**
323  * Setter for object event handlers
324  *
325  * @param {String}   Event name
326  * @param {Function} Handler function
327  */
328 addEventListener: function(evt, func, obj)
329 {
330   if (!this._events)
331     this._events = {};
332   if (!this._events[evt])
333     this._events[evt] = [];
b231f6 334
235504 335   this._events[evt].push({func:func, obj:obj ? obj : window});
772bec 336
AM 337   return this; // chainable
cc97ea 338 },
T 339
340 /**
341  * Removes a specific event listener
342  *
343  * @param {String} Event name
344  * @param {Int}    Listener ID to remove
345  */
346 removeEventListener: function(evt, func, obj)
347 {
ef4f59 348   if (obj === undefined)
cc97ea 349     obj = window;
b231f6 350
cc97ea 351   for (var h,i=0; this._events && this._events[evt] && i < this._events[evt].length; i++)
T 352     if ((h = this._events[evt][i]) && h.func == func && h.obj == obj)
353       this._events[evt][i] = null;
354 },
355
356 /**
357  * This will execute all registered event handlers
358  *
359  * @param {String} Event to trigger
360  * @param {Object} Event object/arguments
361  */
362 triggerEvent: function(evt, e)
363 {
364   var ret, h;
1db17a 365
ef4f59 366   if (e === undefined)
0e99d3 367     e = this;
ef4f59 368   else if (typeof e === 'object')
cc97ea 369     e.event = evt;
f52c93 370
1db17a 371   if (!this._event_exec)
AM 372     this._event_exec = {};
373
374   if (this._events && this._events[evt] && !this._event_exec[evt]) {
375     this._event_exec[evt] = true;
cc97ea 376     for (var i=0; i < this._events[evt].length; i++) {
T 377       if ((h = this._events[evt][i])) {
ef4f59 378         if (typeof h.func === 'function')
0e99d3 379           ret = h.func.call ? h.func.call(h.obj, e) : h.func(e);
ef4f59 380         else if (typeof h.obj[h.func] === 'function')
0e99d3 381           ret = h.obj[h.func](e);
b231f6 382
cc97ea 383         // cancel event execution
ef4f59 384         if (ret !== undefined && !ret)
cc97ea 385           break;
T 386       }
387     }
6e1626 388     if (ret && ret.event) {
A 389       try {
390         delete ret.event;
391       } catch (err) {
392         // IE6-7 doesn't support deleting HTMLFormElement attributes (#1488017)
393         $(ret).removeAttr('event');
394       }
395     }
cc97ea 396   }
T 397
1db17a 398   delete this._event_exec[evt];
AM 399
6e1626 400   if (e.event) {
A 401     try {
402       delete e.event;
403     } catch (err) {
404       // IE6-7 doesn't support deleting HTMLFormElement attributes (#1488017)
405       $(e).removeAttr('event');
406     }
407   }
24958a 408
cc97ea 409   return ret;
T 410 }
411
8fa922 412 };  // end rcube_event_engine.prototype
4e17e6 413
6b47de 414
10a699 415 // check if input is a valid email address
2c5762 416 // By Cal Henderson <cal@iamcal.com>
S 417 // http://code.iamcal.com/php/rfc822/
10a699 418 function rcube_check_email(input, inline)
8fa922 419 {
A 420   if (input && window.RegExp) {
e99991 421     var qtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]',
A 422       dtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]',
423       atom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+',
424       quoted_pair = '\\x5c[\\x00-\\x7f]',
425       quoted_string = '\\x22('+qtext+'|'+quoted_pair+')*\\x22',
da2812 426       ipv4 = '\\[(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}\\]',
AM 427       ipv6 = '\\[IPv6:[0-9a-f:.]+\\]',
428       ip_addr = '(' + ipv4 + ')|(' + ipv6 + ')',
e99991 429       // Use simplified domain matching, because we need to allow Unicode characters here
A 430       // So, e-mail address should be validated also on server side after idn_to_ascii() use
431       //domain_literal = '\\x5b('+dtext+'|'+quoted_pair+')*\\x5d',
432       //sub_domain = '('+atom+'|'+domain_literal+')',
5c1dfb 433       // allow punycode/unicode top-level domain
ff8053 434       domain = '(('+ip_addr+')|(([^@\\x2e]+\\x2e)+([^\\x00-\\x40\\x5b-\\x60\\x7b-\\x7f]{2,}|xn--[a-z0-9]{2,})))',
47f55c 435       // ICANN e-mail test (http://idn.icann.org/E-mail_test)
A 436       icann_domains = [
437         '\\u0645\\u062b\\u0627\\u0644\\x2e\\u0625\\u062e\\u062a\\u0628\\u0627\\u0631',
438         '\\u4f8b\\u5b50\\x2e\\u6d4b\\u8bd5',
439         '\\u4f8b\\u5b50\\x2e\\u6e2c\\u8a66',
440         '\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1\\x2e\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae',
441         '\\u0909\\u0926\\u093e\\u0939\\u0930\\u0923\\x2e\\u092a\\u0930\\u0940\\u0915\\u094d\\u0937\\u093e',
442         '\\u4f8b\\u3048\\x2e\\u30c6\\u30b9\\u30c8',
443         '\\uc2e4\\ub840\\x2e\\ud14c\\uc2a4\\ud2b8',
444         '\\u0645\\u062b\\u0627\\u0644\\x2e\\u0622\\u0632\\u0645\\u0627\\u06cc\\u0634\u06cc',
445         '\\u043f\\u0440\\u0438\\u043c\\u0435\\u0440\\x2e\\u0438\\u0441\\u043f\\u044b\\u0442\\u0430\\u043d\\u0438\\u0435',
446         '\\u0b89\\u0ba4\\u0bbe\\u0bb0\\u0ba3\\u0bae\\u0bcd\\x2e\\u0baa\\u0bb0\\u0bbf\\u0b9f\\u0bcd\\u0b9a\\u0bc8',
447         '\\u05d1\\u05f2\\u05b7\\u05e9\\u05e4\\u05bc\\u05d9\\u05dc\\x2e\\u05d8\\u05e2\\u05e1\\u05d8'
448       ],
449       icann_addr = 'mailtest\\x40('+icann_domains.join('|')+')',
e99991 450       word = '('+atom+'|'+quoted_string+')',
bcbc45 451       delim = '[,;\\s\\n]',
e99991 452       local_part = word+'(\\x2e'+word+')*',
47f55c 453       addr_spec = '(('+local_part+'\\x40'+domain+')|('+icann_addr+'))',
e99991 454       reg1 = inline ? new RegExp('(^|<|'+delim+')'+addr_spec+'($|>|'+delim+')', 'i') : new RegExp('^'+addr_spec+'$', 'i');
A 455
2c5762 456     return reg1.test(input) ? true : false;
10a699 457   }
e99991 458
8fa922 459   return false;
A 460 };
4e17e6 461
7910c0 462 // recursively copy an object
T 463 function rcube_clone_object(obj)
464 {
465   var out = {};
b231f6 466
7910c0 467   for (var key in obj) {
ef4f59 468     if (obj[key] && typeof obj[key] === 'object')
abe798 469       out[key] = rcube_clone_object(obj[key]);
7910c0 470     else
T 471       out[key] = obj[key];
472   }
b231f6 473
7910c0 474   return out;
8fa922 475 };
4e17e6 476
be58b5 477 // make a string URL safe (and compatible with PHP's rawurlencode())
4d4264 478 function urlencode(str)
T 479 {
be58b5 480   if (window.encodeURIComponent)
A 481     return encodeURIComponent(str).replace('*', '%2A');
482
483   return escape(str)
484     .replace('+', '%2B')
485     .replace('*', '%2A')
486     .replace('/', '%2F')
487     .replace('@', '%40');
8fa922 488 };
4d4264 489
T 490
4e17e6 491 // get any type of html objects by id/name
T 492 function rcube_find_object(id, d)
cc97ea 493 {
4e17e6 494   var n, f, obj, e;
T 495
c0037f 496   if (!d) d = document;
AM 497
498   if (d.getElementById)
499     if (obj = d.getElementById(id))
500       return obj;
501
502   if (!obj && d.getElementsByName && (e = d.getElementsByName(id)))
4e17e6 503     obj = e[0];
c0037f 504
AM 505   if (!obj && d.all)
4e17e6 506     obj = d.all[id];
T 507
c0037f 508   if (!obj && d.images.length)
4e17e6 509     obj = d.images[id];
T 510
cc97ea 511   if (!obj && d.forms.length) {
T 512     for (f=0; f<d.forms.length; f++) {
c0037f 513       if (d.forms[f].name == id)
4e17e6 514         obj = d.forms[f];
T 515       else if(d.forms[f].elements[id])
516         obj = d.forms[f].elements[id];
517     }
cc97ea 518   }
T 519
520   if (!obj && d.layers) {
c0037f 521     if (d.layers[id])
AM 522       obj = d.layers[id];
cc97ea 523     for (n=0; !obj && n<d.layers.length; n++)
T 524       obj = rcube_find_object(id, d.layers[n].document);
525   }
4e17e6 526
T 527   return obj;
8fa922 528 };
a7d5c6 529
f89f03 530 // determine whether the mouse is over the given object or not
T 531 function rcube_mouse_is_over(ev, obj)
532 {
129aef 533   var mouse = rcube_event.get_mouse_pos(ev),
A 534     pos = $(obj).offset();
cc97ea 535
f923d4 536   return (mouse.x >= pos.left) && (mouse.x < (pos.left + obj.offsetWidth)) &&
AM 537     (mouse.y >= pos.top) && (mouse.y < (pos.top + obj.offsetHeight));
8fa922 538 };
f89f03 539
dd53e2 540
T 541 // cookie functions by GoogieSpell
542 function setCookie(name, value, expires, path, domain, secure)
8fa922 543 {
dd53e2 544   var curCookie = name + "=" + escape(value) +
T 545       (expires ? "; expires=" + expires.toGMTString() : "") +
546       (path ? "; path=" + path : "") +
547       (domain ? "; domain=" + domain : "") +
548       (secure ? "; secure" : "");
f923d4 549
dd53e2 550   document.cookie = curCookie;
8fa922 551 };
dd53e2 552
T 553 function getCookie(name)
8fa922 554 {
129aef 555   var dc = document.cookie,
A 556     prefix = name + "=",
557     begin = dc.indexOf("; " + prefix);
558
8fa922 559   if (begin == -1) {
dd53e2 560     begin = dc.indexOf(prefix);
129aef 561     if (begin != 0)
A 562       return null;
8fa922 563   }
129aef 564   else {
90a6af 565     begin += 2;
129aef 566   }
A 567
90a6af 568   var end = dc.indexOf(";", begin);
dd53e2 569   if (end == -1)
T 570     end = dc.length;
129aef 571
dd53e2 572   return unescape(dc.substring(begin + prefix.length, end));
8fa922 573 };
dd53e2 574
ae7027 575 // deprecated aliases, to be removed, use rcmail.set_cookie/rcmail.get_cookie
8fa922 576 roundcube_browser.prototype.set_cookie = setCookie;
a7d5c6 577 roundcube_browser.prototype.get_cookie = getCookie;
T 578
b4b081 579 var bw = new roundcube_browser();
89e31b 580 bw.set_html_class();
b0dbf3 581
S 582
583 // Add escape() method to RegExp object
584 // http://dev.rubyonrails.org/changeset/7271
585 RegExp.escape = function(str)
8fa922 586 {
b0dbf3 587   return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
8fa922 588 };
bafadd 589
65082b 590 // Extend Date prototype to detect Standard timezone without DST
T 591 // from http://www.michaelapproved.com/articles/timezone-detect-and-ignore-daylight-saving-time-dst/
592 Date.prototype.getStdTimezoneOffset = function()
593 {
594   var m = 12,
595     d = new Date(null, m, 1),
596     tzo = d.getTimezoneOffset();
597
598     while (--m) {
599       d.setUTCMonth(m);
600       if (tzo != d.getTimezoneOffset()) {
601         return Math.max(tzo, d.getTimezoneOffset());
602     }
603   }
604
605   return tzo;
606 }
bafadd 607
6a9144 608 // define String's startsWith() method for old browsers
AM 609 if (!String.prototype.startsWith) {
610   String.prototype.startsWith = function(search, position) {
611     position = position || 0;
612     return this.slice(position, search.length) === search;
613   };
b231f6 614 }
fb6d86 615
6789bf 616 // array utility function
f5de03 617 jQuery.last = function(arr) {
TB 618   return arr && arr.length ? arr[arr.length-1] : undefined;
6789bf 619 }
TB 620
9e2c94 621 // jQuery plugin to emulate HTML5 placeholder attributes on input elements
T 622 jQuery.fn.placeholder = function(text) {
623   return this.each(function() {
0c974b 624     var active = false, elem = $(this);
9e2c94 625     this.title = text;
T 626
39f401 627     // Try HTML5 placeholder attribute first
9e2c94 628     if ('placeholder' in this) {
39f401 629       elem.attr('placeholder', text);
9e2c94 630     }
39f401 631     // Fallback to Javascript emulation of placeholder
AM 632     else {
9e2c94 633       this._placeholder = text;
T 634       elem.blur(function(e) {
635         if ($.trim(elem.val()) == "")
636           elem.val(text);
637         elem.triggerHandler('change');
638       })
639       .focus(function(e) {
640         if ($.trim(elem.val()) == text)
641           elem.val("");
642         elem.triggerHandler('change');
643       })
644       .change(function(e) {
645         var active = elem.val() == text;
646         elem[(active ? 'addClass' : 'removeClass')]('placeholder').attr('spellcheck', active);
647       });
648
0c974b 649       // Do not blur currently focused element (catch exception: #1489008)
AM 650       try { active = this == document.activeElement; } catch(e) {}
651       if (!active)
f38d15 652         elem.blur();
9e2c94 653     }
T 654   });
655 };
656
c2df5d 657 // function to parse query string into an object
AM 658 rcube_parse_query = function(query)
659 {
660   if (!query)
661     return {};
662
663   var params = {}, e, k, v,
664     re = /([^&=]+)=?([^&]*)/g,
665     decodeRE = /\+/g, // Regex for replacing addition symbol with a space
666     decode = function (str) { return decodeURIComponent(str.replace(decodeRE, ' ')); };
667
668   query = query.replace(/\?/, '');
669
670   while (e = re.exec(query)) {
671     k = decode(e[1]);
672     v = decode(e[2]);
673
674     if (k.substring(k.length - 2) === '[]') {
675       k = k.substring(0, k.length - 2);
676       (params[k] || (params[k] = [])).push(v);
677     }
678     else
679       params[k] = v;
680   }
681
682   return params;
683 };
684
9e2c94 685
fb6d86 686 // Base64 code from Tyler Akins -- http://rumkin.com
A 687 var Base64 = (function () {
688   var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
284aac 689
AM 690   // private method for UTF-8 encoding
691   var utf8_encode = function(string) {
692     string = string.replace(/\r\n/g, "\n");
693     var utftext = '';
694
695     for (var n = 0; n < string.length; n++) {
696       var c = string.charCodeAt(n);
697
698       if (c < 128) {
699         utftext += String.fromCharCode(c);
700       }
701       else if(c > 127 && c < 2048) {
702         utftext += String.fromCharCode((c >> 6) | 192);
703         utftext += String.fromCharCode((c & 63) | 128);
704       }
705       else {
706         utftext += String.fromCharCode((c >> 12) | 224);
707         utftext += String.fromCharCode(((c >> 6) & 63) | 128);
708         utftext += String.fromCharCode((c & 63) | 128);
709       }
710     }
711
712     return utftext;
713   };
714
715   // private method for UTF-8 decoding
716   var utf8_decode = function (utftext) {
717     var i = 0, string = '', c = c2 = c3 = 0;
718
719     while (i < utftext.length) {
720       c = utftext.charCodeAt(i);
721       if (c < 128) {
722         string += String.fromCharCode(c);
723         i++;
724       }
725       else if (c > 191 && c < 224) {
726         c2 = utftext.charCodeAt(i + 1);
727         string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
728         i += 2;
729       }
730       else {
731         c2 = utftext.charCodeAt(i + 1);
732         c3 = utftext.charCodeAt(i + 2);
733         string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
734         i += 3;
735       }
736     }
737
738     return string;
739   };
fb6d86 740
A 741   var obj = {
742     /**
743      * Encodes a string in base64
744      * @param {String} input The string to encode in base64.
745      */
746     encode: function (input) {
9ae41d 747       // encode UTF8 as btoa() may fail on some characters
AM 748       input = utf8_encode(input);
749
c16ac7 750       if (typeof(window.btoa) === 'function') {
AM 751         try {
752           return btoa(input);
753         }
754         catch (e) {};
755       }
284aac 756
fb6d86 757       var chr1, chr2, chr3, enc1, enc2, enc3, enc4, i = 0, output = '', len = input.length;
A 758
284aac 759       while (i < len) {
fb6d86 760         chr1 = input.charCodeAt(i++);
A 761         chr2 = input.charCodeAt(i++);
762         chr3 = input.charCodeAt(i++);
763
764         enc1 = chr1 >> 2;
765         enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
766         enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
767         enc4 = chr3 & 63;
768
769         if (isNaN(chr2))
770           enc3 = enc4 = 64;
771         else if (isNaN(chr3))
772           enc4 = 64;
773
774         output = output
775           + keyStr.charAt(enc1) + keyStr.charAt(enc2)
776           + keyStr.charAt(enc3) + keyStr.charAt(enc4);
284aac 777       }
fb6d86 778
A 779       return output;
780     },
781
782     /**
783      * Decodes a base64 string.
784      * @param {String} input The string to decode.
785      */
786     decode: function (input) {
c16ac7 787       if (typeof(window.atob) === 'function') {
AM 788         try {
284aac 789           return utf8_decode(atob(input));
c16ac7 790         }
AM 791         catch (e) {};
792       }
fb6d86 793
A 794       var chr1, chr2, chr3, enc1, enc2, enc3, enc4, len, i = 0, output = '';
795
796       // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
797       input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
798       len = input.length;
799
284aac 800       while (i < len) {
fb6d86 801         enc1 = keyStr.indexOf(input.charAt(i++));
A 802         enc2 = keyStr.indexOf(input.charAt(i++));
803         enc3 = keyStr.indexOf(input.charAt(i++));
804         enc4 = keyStr.indexOf(input.charAt(i++));
805
806         chr1 = (enc1 << 2) | (enc2 >> 4);
807         chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
808         chr3 = ((enc3 & 3) << 6) | enc4;
809
810         output = output + String.fromCharCode(chr1);
811
812         if (enc3 != 64)
813           output = output + String.fromCharCode(chr2);
814         if (enc4 != 64)
815           output = output + String.fromCharCode(chr3);
284aac 816       }
fb6d86 817
284aac 818       return utf8_decode(output);
fb6d86 819     }
A 820   };
821
822   return obj;
823 })();