common.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  1. /**
  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. */
  28. // Constants
  29. var CONTROL_KEY = 1;
  30. var SHIFT_KEY = 2;
  31. var CONTROL_SHIFT_KEY = 3;
  32. /**
  33. * Default browser check class
  34. * @constructor
  35. */
  36. function roundcube_browser()
  37. {
  38. var n = navigator;
  39. this.agent = n.userAgent;
  40. this.agent_lc = n.userAgent.toLowerCase();
  41. this.name = n.appName;
  42. this.vendor = n.vendor ? n.vendor : '';
  43. this.vendver = n.vendorSub ? parseFloat(n.vendorSub) : 0;
  44. this.product = n.product ? n.product : '';
  45. this.platform = String(n.platform).toLowerCase();
  46. this.lang = n.language ? n.language.substring(0,2) :
  47. n.browserLanguage ? n.browserLanguage.substring(0,2) :
  48. n.systemLanguage ? n.systemLanguage.substring(0,2) : 'en';
  49. this.win = this.platform.indexOf('win') >= 0;
  50. this.mac = this.platform.indexOf('mac') >= 0;
  51. this.linux = this.platform.indexOf('linux') >= 0;
  52. this.unix = this.platform.indexOf('unix') >= 0;
  53. this.dom = document.getElementById ? true : false;
  54. this.dom2 = document.addEventListener && document.removeEventListener;
  55. this.webkit = this.agent_lc.indexOf('applewebkit') > 0;
  56. this.ie = (document.all && !window.opera) || (this.win && this.agent_lc.indexOf('trident/') > 0);
  57. if (window.opera) {
  58. this.opera = true; // Opera < 15
  59. this.vendver = opera.version();
  60. }
  61. else if (!this.ie) {
  62. this.chrome = this.agent_lc.indexOf('chrome') > 0;
  63. this.opera = this.webkit && this.agent.indexOf(' OPR/') > 0; // Opera >= 15
  64. this.safari = !this.chrome && !this.opera && (this.webkit || this.agent_lc.indexOf('safari') > 0);
  65. this.konq = this.agent_lc.indexOf('konqueror') > 0;
  66. this.mz = this.dom && !this.chrome && !this.safari && !this.konq && !this.opera && this.agent.indexOf('Mozilla') >= 0;
  67. this.iphone = this.safari && (this.agent_lc.indexOf('iphone') > 0 || this.agent_lc.indexOf('ipod') > 0);
  68. this.ipad = this.safari && this.agent_lc.indexOf('ipad') > 0;
  69. }
  70. if (!this.vendver) {
  71. // common version strings
  72. this.vendver = /(opera|opr|khtml|chrome|safari|applewebkit|msie)(\s|\/)([0-9\.]+)/.test(this.agent_lc) ? parseFloat(RegExp.$3) : 0;
  73. // any other (Mozilla, Camino, IE>=11)
  74. if (!this.vendver)
  75. this.vendver = /rv:([0-9\.]+)/.test(this.agent) ? parseFloat(RegExp.$1) : 0;
  76. }
  77. // get real language out of safari's user agent
  78. if (this.safari && (/;\s+([a-z]{2})-[a-z]{2}\)/.test(this.agent_lc)))
  79. this.lang = RegExp.$1;
  80. this.tablet = /ipad|android|xoom|sch-i800|playbook|tablet|kindle/i.test(this.agent_lc);
  81. this.mobile = /iphone|ipod|blackberry|iemobile|opera mini|opera mobi|mobile/i.test(this.agent_lc);
  82. this.touch = this.mobile || this.tablet;
  83. this.cookies = n.cookieEnabled;
  84. // test for XMLHTTP support
  85. this.xmlhttp_test = function()
  86. {
  87. var activeX_test = new Function("try{var o=new ActiveXObject('Microsoft.XMLHTTP');return true;}catch(err){return false;}");
  88. this.xmlhttp = window.XMLHttpRequest || (('ActiveXObject' in window) && activeX_test());
  89. return this.xmlhttp;
  90. };
  91. // set class names to html tag according to the current user agent detection
  92. // this allows browser-specific css selectors like "html.chrome .someclass"
  93. this.set_html_class = function()
  94. {
  95. var classname = ' js';
  96. if (this.ie)
  97. classname += ' ie ie'+parseInt(this.vendver);
  98. else if (this.opera)
  99. classname += ' opera';
  100. else if (this.konq)
  101. classname += ' konqueror';
  102. else if (this.safari)
  103. classname += ' chrome';
  104. else if (this.chrome)
  105. classname += ' chrome';
  106. else if (this.mz)
  107. classname += ' mozilla';
  108. if (this.iphone)
  109. classname += ' iphone';
  110. else if (this.ipad)
  111. classname += ' ipad';
  112. else if (this.webkit)
  113. classname += ' webkit';
  114. if (this.mobile)
  115. classname += ' mobile';
  116. if (this.tablet)
  117. classname += ' tablet';
  118. if (document.documentElement)
  119. document.documentElement.className += classname;
  120. };
  121. };
  122. // static functions for DOM event handling
  123. var rcube_event = {
  124. /**
  125. * returns the event target element
  126. */
  127. get_target: function(e)
  128. {
  129. e = e || window.event;
  130. return e && e.target ? e.target : e.srcElement;
  131. },
  132. /**
  133. * returns the event key code
  134. */
  135. get_keycode: function(e)
  136. {
  137. e = e || window.event;
  138. return e && e.keyCode ? e.keyCode : (e && e.which ? e.which : 0);
  139. },
  140. /**
  141. * returns the event key code
  142. */
  143. get_button: function(e)
  144. {
  145. e = e || window.event;
  146. return e && e.button !== undefined ? e.button : (e && e.which ? e.which : 0);
  147. },
  148. /**
  149. * returns modifier key (constants defined at top of file)
  150. */
  151. get_modifier: function(e)
  152. {
  153. var opcode = 0;
  154. e = e || window.event;
  155. if (bw.mac && e)
  156. opcode += (e.metaKey && CONTROL_KEY) + (e.shiftKey && SHIFT_KEY);
  157. else if (e)
  158. opcode += (e.ctrlKey && CONTROL_KEY) + (e.shiftKey && SHIFT_KEY);
  159. return opcode;
  160. },
  161. /**
  162. * Return absolute mouse position of an event
  163. */
  164. get_mouse_pos: function(e)
  165. {
  166. if (!e) e = window.event;
  167. var mX = (e.pageX) ? e.pageX : e.clientX,
  168. mY = (e.pageY) ? e.pageY : e.clientY;
  169. if (document.body && document.all) {
  170. mX += document.body.scrollLeft;
  171. mY += document.body.scrollTop;
  172. }
  173. if (e._offset) {
  174. mX += e._offset.left;
  175. mY += e._offset.top;
  176. }
  177. return { x:mX, y:mY };
  178. },
  179. /**
  180. * Add an object method as event listener to a certain element
  181. */
  182. add_listener: function(p)
  183. {
  184. if (!p.object || !p.method) // not enough arguments
  185. return;
  186. if (!p.element)
  187. p.element = document;
  188. if (!p.object._rc_events)
  189. p.object._rc_events = {};
  190. var key = p.event + '*' + p.method;
  191. if (!p.object._rc_events[key])
  192. p.object._rc_events[key] = function(e){ return p.object[p.method](e); };
  193. if (p.element.addEventListener)
  194. p.element.addEventListener(p.event, p.object._rc_events[key], false);
  195. else if (p.element.attachEvent) {
  196. // IE allows multiple events with the same function to be applied to the same object
  197. // forcibly detach the event, then attach
  198. p.element.detachEvent('on'+p.event, p.object._rc_events[key]);
  199. p.element.attachEvent('on'+p.event, p.object._rc_events[key]);
  200. }
  201. else
  202. p.element['on'+p.event] = p.object._rc_events[key];
  203. },
  204. /**
  205. * Remove event listener
  206. */
  207. remove_listener: function(p)
  208. {
  209. if (!p.element)
  210. p.element = document;
  211. var key = p.event + '*' + p.method;
  212. if (p.object && p.object._rc_events && p.object._rc_events[key]) {
  213. if (p.element.removeEventListener)
  214. p.element.removeEventListener(p.event, p.object._rc_events[key], false);
  215. else if (p.element.detachEvent)
  216. p.element.detachEvent('on'+p.event, p.object._rc_events[key]);
  217. else
  218. p.element['on'+p.event] = null;
  219. }
  220. },
  221. /**
  222. * Prevent event propagation and bubbling
  223. */
  224. cancel: function(evt)
  225. {
  226. var e = evt ? evt : window.event;
  227. if (e.preventDefault)
  228. e.preventDefault();
  229. else
  230. e.returnValue = false;
  231. if (e.stopPropagation)
  232. e.stopPropagation();
  233. e.cancelBubble = true;
  234. return false;
  235. },
  236. /**
  237. * Determine whether the given event was trigered from keyboard
  238. */
  239. is_keyboard: function(e)
  240. {
  241. return e && (
  242. (e.type && String(e.type).match(/^key/)) // DOM3-compatible
  243. || (!e.pageX && (e.pageY || 0) <= 0 && !e.clientX && (e.clientY || 0) <= 0) // others
  244. );
  245. },
  246. /**
  247. * Accept event if triggered from keyboard action (e.g. <Enter>)
  248. */
  249. keyboard_only: function(e)
  250. {
  251. return rcube_event.is_keyboard(e) ? true : rcube_event.cancel(e);
  252. },
  253. touchevent: function(e)
  254. {
  255. return { pageX:e.pageX, pageY:e.pageY, offsetX:e.pageX - e.target.offsetLeft, offsetY:e.pageY - e.target.offsetTop, target:e.target, istouch:true };
  256. }
  257. };
  258. /**
  259. * rcmail objects event interface
  260. */
  261. function rcube_event_engine()
  262. {
  263. this._events = {};
  264. };
  265. rcube_event_engine.prototype = {
  266. /**
  267. * Setter for object event handlers
  268. *
  269. * @param {String} Event name
  270. * @param {Function} Handler function
  271. */
  272. addEventListener: function(evt, func, obj)
  273. {
  274. if (!this._events)
  275. this._events = {};
  276. if (!this._events[evt])
  277. this._events[evt] = [];
  278. this._events[evt].push({func:func, obj:obj ? obj : window});
  279. return this; // chainable
  280. },
  281. /**
  282. * Removes a specific event listener
  283. *
  284. * @param {String} Event name
  285. * @param {Int} Listener ID to remove
  286. */
  287. removeEventListener: function(evt, func, obj)
  288. {
  289. if (obj === undefined)
  290. obj = window;
  291. for (var h,i=0; this._events && this._events[evt] && i < this._events[evt].length; i++)
  292. if ((h = this._events[evt][i]) && h.func == func && h.obj == obj)
  293. this._events[evt][i] = null;
  294. },
  295. /**
  296. * This will execute all registered event handlers
  297. *
  298. * @param {String} Event to trigger
  299. * @param {Object} Event object/arguments
  300. */
  301. triggerEvent: function(evt, e)
  302. {
  303. var ret, h;
  304. if (e === undefined)
  305. e = this;
  306. else if (typeof e === 'object')
  307. e.event = evt;
  308. if (!this._event_exec)
  309. this._event_exec = {};
  310. if (this._events && this._events[evt] && !this._event_exec[evt]) {
  311. this._event_exec[evt] = true;
  312. for (var i=0; i < this._events[evt].length; i++) {
  313. if ((h = this._events[evt][i])) {
  314. if (typeof h.func === 'function')
  315. ret = h.func.call ? h.func.call(h.obj, e) : h.func(e);
  316. else if (typeof h.obj[h.func] === 'function')
  317. ret = h.obj[h.func](e);
  318. // cancel event execution
  319. if (ret !== undefined && !ret)
  320. break;
  321. }
  322. }
  323. if (ret && ret.event) {
  324. try {
  325. delete ret.event;
  326. } catch (err) {
  327. // IE6-7 doesn't support deleting HTMLFormElement attributes (#1488017)
  328. $(ret).removeAttr('event');
  329. }
  330. }
  331. }
  332. delete this._event_exec[evt];
  333. if (e.event) {
  334. try {
  335. delete e.event;
  336. } catch (err) {
  337. // IE6-7 doesn't support deleting HTMLFormElement attributes (#1488017)
  338. $(e).removeAttr('event');
  339. }
  340. }
  341. return ret;
  342. }
  343. }; // end rcube_event_engine.prototype
  344. // check if input is a valid email address
  345. // By Cal Henderson <cal@iamcal.com>
  346. // http://code.iamcal.com/php/rfc822/
  347. function rcube_check_email(input, inline, count)
  348. {
  349. if (!input)
  350. return count ? 0 : false;
  351. if (count) inline = true;
  352. var qtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]',
  353. dtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]',
  354. atom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+',
  355. quoted_pair = '\\x5c[\\x00-\\x7f]',
  356. quoted_string = '\\x22('+qtext+'|'+quoted_pair+')*\\x22',
  357. 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}\\]',
  358. ipv6 = '\\[IPv6:[0-9a-f:.]+\\]',
  359. ip_addr = '(' + ipv4 + ')|(' + ipv6 + ')',
  360. // Use simplified domain matching, because we need to allow Unicode characters here
  361. // So, e-mail address should be validated also on server side after idn_to_ascii() use
  362. //domain_literal = '\\x5b('+dtext+'|'+quoted_pair+')*\\x5d',
  363. //sub_domain = '('+atom+'|'+domain_literal+')',
  364. // allow punycode/unicode top-level domain
  365. domain = '(('+ip_addr+')|(([^@\\x2e]+\\x2e)+([^\\x00-\\x40\\x5b-\\x60\\x7b-\\x7f]{2,}|xn--[a-z0-9]{2,})))',
  366. // ICANN e-mail test (http://idn.icann.org/E-mail_test)
  367. icann_domains = [
  368. '\\u0645\\u062b\\u0627\\u0644\\x2e\\u0625\\u062e\\u062a\\u0628\\u0627\\u0631',
  369. '\\u4f8b\\u5b50\\x2e\\u6d4b\\u8bd5',
  370. '\\u4f8b\\u5b50\\x2e\\u6e2c\\u8a66',
  371. '\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1\\x2e\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae',
  372. '\\u0909\\u0926\\u093e\\u0939\\u0930\\u0923\\x2e\\u092a\\u0930\\u0940\\u0915\\u094d\\u0937\\u093e',
  373. '\\u4f8b\\u3048\\x2e\\u30c6\\u30b9\\u30c8',
  374. '\\uc2e4\\ub840\\x2e\\ud14c\\uc2a4\\ud2b8',
  375. '\\u0645\\u062b\\u0627\\u0644\\x2e\\u0622\\u0632\\u0645\\u0627\\u06cc\\u0634\u06cc',
  376. '\\u043f\\u0440\\u0438\\u043c\\u0435\\u0440\\x2e\\u0438\\u0441\\u043f\\u044b\\u0442\\u0430\\u043d\\u0438\\u0435',
  377. '\\u0b89\\u0ba4\\u0bbe\\u0bb0\\u0ba3\\u0bae\\u0bcd\\x2e\\u0baa\\u0bb0\\u0bbf\\u0b9f\\u0bcd\\u0b9a\\u0bc8',
  378. '\\u05d1\\u05f2\\u05b7\\u05e9\\u05e4\\u05bc\\u05d9\\u05dc\\x2e\\u05d8\\u05e2\\u05e1\\u05d8'
  379. ],
  380. icann_addr = 'mailtest\\x40('+icann_domains.join('|')+')',
  381. word = '('+atom+'|'+quoted_string+')',
  382. delim = '[,;\\s\\n]',
  383. local_part = word+'(\\x2e'+word+')*',
  384. addr_spec = '(('+local_part+'\\x40'+domain+')|('+icann_addr+'))',
  385. rx_flag = count ? 'ig' : 'i',
  386. rx = inline ? new RegExp('(^|<|'+delim+')'+addr_spec+'($|>|'+delim+')', rx_flag) : new RegExp('^'+addr_spec+'$', 'i');
  387. if (count)
  388. return input.match(rx).length;
  389. return rx.test(input);
  390. };
  391. // recursively copy an object
  392. function rcube_clone_object(obj)
  393. {
  394. var out = {};
  395. for (var key in obj) {
  396. if (obj[key] && typeof obj[key] === 'object')
  397. out[key] = rcube_clone_object(obj[key]);
  398. else
  399. out[key] = obj[key];
  400. }
  401. return out;
  402. };
  403. // make a string URL safe (and compatible with PHP's rawurlencode())
  404. function urlencode(str)
  405. {
  406. if (window.encodeURIComponent)
  407. return encodeURIComponent(str).replace('*', '%2A');
  408. return escape(str)
  409. .replace('+', '%2B')
  410. .replace('*', '%2A')
  411. .replace('/', '%2F')
  412. .replace('@', '%40');
  413. };
  414. // get any type of html objects by id/name
  415. function rcube_find_object(id, d)
  416. {
  417. var n, f, obj, e;
  418. if (!d) d = document;
  419. if (d.getElementById)
  420. if (obj = d.getElementById(id))
  421. return obj;
  422. if (!obj && d.getElementsByName && (e = d.getElementsByName(id)))
  423. obj = e[0];
  424. if (!obj && d.all)
  425. obj = d.all[id];
  426. if (!obj && d.images.length)
  427. obj = d.images[id];
  428. if (!obj && d.forms.length) {
  429. for (f=0; f<d.forms.length; f++) {
  430. if (d.forms[f].name == id)
  431. obj = d.forms[f];
  432. else if(d.forms[f].elements[id])
  433. obj = d.forms[f].elements[id];
  434. }
  435. }
  436. if (!obj && d.layers) {
  437. if (d.layers[id])
  438. obj = d.layers[id];
  439. for (n=0; !obj && n<d.layers.length; n++)
  440. obj = rcube_find_object(id, d.layers[n].document);
  441. }
  442. return obj;
  443. };
  444. // determine whether the mouse is over the given object or not
  445. function rcube_mouse_is_over(ev, obj)
  446. {
  447. var mouse = rcube_event.get_mouse_pos(ev),
  448. pos = $(obj).offset();
  449. return (mouse.x >= pos.left) && (mouse.x < (pos.left + obj.offsetWidth)) &&
  450. (mouse.y >= pos.top) && (mouse.y < (pos.top + obj.offsetHeight));
  451. };
  452. // cookie functions by GoogieSpell
  453. function setCookie(name, value, expires, path, domain, secure)
  454. {
  455. var curCookie = name + "=" + escape(value) +
  456. (expires ? "; expires=" + expires.toGMTString() : "") +
  457. (path ? "; path=" + path : "") +
  458. (domain ? "; domain=" + domain : "") +
  459. (secure ? "; secure" : "");
  460. document.cookie = curCookie;
  461. };
  462. function getCookie(name)
  463. {
  464. var dc = document.cookie,
  465. prefix = name + "=",
  466. begin = dc.indexOf("; " + prefix);
  467. if (begin == -1) {
  468. begin = dc.indexOf(prefix);
  469. if (begin != 0)
  470. return null;
  471. }
  472. else {
  473. begin += 2;
  474. }
  475. var end = dc.indexOf(";", begin);
  476. if (end == -1)
  477. end = dc.length;
  478. return unescape(dc.substring(begin + prefix.length, end));
  479. };
  480. // deprecated aliases, to be removed, use rcmail.set_cookie/rcmail.get_cookie
  481. roundcube_browser.prototype.set_cookie = setCookie;
  482. roundcube_browser.prototype.get_cookie = getCookie;
  483. var bw = new roundcube_browser();
  484. bw.set_html_class();
  485. // Add escape() method to RegExp object
  486. // http://dev.rubyonrails.org/changeset/7271
  487. RegExp.escape = function(str)
  488. {
  489. return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
  490. };
  491. // Extend Date prototype to detect Standard timezone without DST
  492. // from http://www.michaelapproved.com/articles/timezone-detect-and-ignore-daylight-saving-time-dst/
  493. Date.prototype.getStdTimezoneOffset = function()
  494. {
  495. var m = 12,
  496. d = new Date(null, m, 1),
  497. tzo = d.getTimezoneOffset();
  498. while (--m) {
  499. d.setUTCMonth(m);
  500. if (tzo != d.getTimezoneOffset()) {
  501. return Math.max(tzo, d.getTimezoneOffset());
  502. }
  503. }
  504. return tzo;
  505. }
  506. // define String's startsWith() method for old browsers
  507. if (!String.prototype.startsWith) {
  508. String.prototype.startsWith = function(search, position) {
  509. position = position || 0;
  510. return this.slice(position, search.length) === search;
  511. };
  512. }
  513. // array utility function
  514. jQuery.last = function(arr) {
  515. return arr && arr.length ? arr[arr.length-1] : undefined;
  516. }
  517. // jQuery plugin to set HTML5 placeholder and title attributes on input elements
  518. jQuery.fn.placeholder = function(text) {
  519. return this.each(function() {
  520. $(this).prop({title: text, placeholder: text});
  521. });
  522. };
  523. // function to parse query string into an object
  524. var rcube_parse_query = function(query)
  525. {
  526. if (!query)
  527. return {};
  528. var params = {}, e, k, v,
  529. re = /([^&=]+)=?([^&]*)/g,
  530. decodeRE = /\+/g, // Regex for replacing addition symbol with a space
  531. decode = function (str) { return decodeURIComponent(str.replace(decodeRE, ' ')); };
  532. query = query.replace(/\?/, '');
  533. while (e = re.exec(query)) {
  534. k = decode(e[1]);
  535. v = decode(e[2]);
  536. if (k.substring(k.length - 2) === '[]') {
  537. k = k.substring(0, k.length - 2);
  538. (params[k] || (params[k] = [])).push(v);
  539. }
  540. else
  541. params[k] = v;
  542. }
  543. return params;
  544. };
  545. // Base64 code from Tyler Akins -- http://rumkin.com
  546. var Base64 = (function () {
  547. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  548. // private method for UTF-8 encoding
  549. var utf8_encode = function(string) {
  550. string = string.replace(/\r\n/g, "\n");
  551. var utftext = '';
  552. for (var n = 0; n < string.length; n++) {
  553. var c = string.charCodeAt(n);
  554. if (c < 128) {
  555. utftext += String.fromCharCode(c);
  556. }
  557. else if(c > 127 && c < 2048) {
  558. utftext += String.fromCharCode((c >> 6) | 192);
  559. utftext += String.fromCharCode((c & 63) | 128);
  560. }
  561. else {
  562. utftext += String.fromCharCode((c >> 12) | 224);
  563. utftext += String.fromCharCode(((c >> 6) & 63) | 128);
  564. utftext += String.fromCharCode((c & 63) | 128);
  565. }
  566. }
  567. return utftext;
  568. };
  569. // private method for UTF-8 decoding
  570. var utf8_decode = function (utftext) {
  571. var i = 0, string = '', c = 0, c2 = 0, c3 = 0;
  572. while (i < utftext.length) {
  573. c = utftext.charCodeAt(i);
  574. if (c < 128) {
  575. string += String.fromCharCode(c);
  576. i++;
  577. }
  578. else if (c > 191 && c < 224) {
  579. c2 = utftext.charCodeAt(i + 1);
  580. string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
  581. i += 2;
  582. }
  583. else {
  584. c2 = utftext.charCodeAt(i + 1);
  585. c3 = utftext.charCodeAt(i + 2);
  586. string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
  587. i += 3;
  588. }
  589. }
  590. return string;
  591. };
  592. var obj = {
  593. /**
  594. * Encodes a string in base64
  595. * @param {String} input The string to encode in base64.
  596. */
  597. encode: function (input) {
  598. // encode UTF8 as btoa() may fail on some characters
  599. input = utf8_encode(input);
  600. if (typeof(window.btoa) === 'function') {
  601. try {
  602. return btoa(input);
  603. }
  604. catch (e) {};
  605. }
  606. var chr1, chr2, chr3, enc1, enc2, enc3, enc4, i = 0, output = '', len = input.length;
  607. while (i < len) {
  608. chr1 = input.charCodeAt(i++);
  609. chr2 = input.charCodeAt(i++);
  610. chr3 = input.charCodeAt(i++);
  611. enc1 = chr1 >> 2;
  612. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  613. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  614. enc4 = chr3 & 63;
  615. if (isNaN(chr2))
  616. enc3 = enc4 = 64;
  617. else if (isNaN(chr3))
  618. enc4 = 64;
  619. output = output
  620. + keyStr.charAt(enc1) + keyStr.charAt(enc2)
  621. + keyStr.charAt(enc3) + keyStr.charAt(enc4);
  622. }
  623. return output;
  624. },
  625. /**
  626. * Decodes a base64 string.
  627. * @param {String} input The string to decode.
  628. */
  629. decode: function (input) {
  630. if (typeof(window.atob) === 'function') {
  631. try {
  632. return utf8_decode(atob(input));
  633. }
  634. catch (e) {};
  635. }
  636. var chr1, chr2, chr3, enc1, enc2, enc3, enc4, len, i = 0, output = '';
  637. // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
  638. input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
  639. len = input.length;
  640. while (i < len) {
  641. enc1 = keyStr.indexOf(input.charAt(i++));
  642. enc2 = keyStr.indexOf(input.charAt(i++));
  643. enc3 = keyStr.indexOf(input.charAt(i++));
  644. enc4 = keyStr.indexOf(input.charAt(i++));
  645. chr1 = (enc1 << 2) | (enc2 >> 4);
  646. chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
  647. chr3 = ((enc3 & 3) << 6) | enc4;
  648. output = output + String.fromCharCode(chr1);
  649. if (enc3 != 64)
  650. output = output + String.fromCharCode(chr2);
  651. if (enc4 != 64)
  652. output = output + String.fromCharCode(chr3);
  653. }
  654. return utf8_decode(output);
  655. }
  656. };
  657. return obj;
  658. })();