/program/js/app.js

https://bitbucket.org/gencer/roundcubemail · JavaScript · 8051 lines · 6584 code · 922 blank · 545 comment · 1733 complexity · f366bf2993d9b6e49680930ff75594b8 MD5 · raw file

  1. /**
  2. * Roundcube Webmail Client Script
  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. * Copyright (C) 2011-2014, Kolab Systems AG
  11. *
  12. * The JavaScript code in this page is free software: you can
  13. * redistribute it and/or modify it under the terms of the GNU
  14. * General Public License (GNU GPL) as published by the Free Software
  15. * Foundation, either version 3 of the License, or (at your option)
  16. * any later version. The code is distributed WITHOUT ANY WARRANTY;
  17. * without even the implied warranty of MERCHANTABILITY or FITNESS
  18. * FOR A PARTICULAR PURPOSE. See the GNU GPL for more details.
  19. *
  20. * As additional permission under GNU GPL version 3 section 7, you
  21. * may distribute non-source (e.g., minimized or compacted) forms of
  22. * that code without the copy of the GNU GPL normally required by
  23. * section 4, provided you include this license notice and a URL
  24. * through which recipients can access the Corresponding Source.
  25. *
  26. * @licend The above is the entire license notice
  27. * for the JavaScript code in this file.
  28. *
  29. * @author Thomas Bruederli <roundcube@gmail.com>
  30. * @author Aleksander 'A.L.E.C' Machniak <alec@alec.pl>
  31. * @author Charles McNulty <charles@charlesmcnulty.com>
  32. *
  33. * @requires jquery.js, common.js, list.js
  34. */
  35. function rcube_webmail()
  36. {
  37. this.labels = {};
  38. this.buttons = {};
  39. this.buttons_sel = {};
  40. this.gui_objects = {};
  41. this.gui_containers = {};
  42. this.commands = {};
  43. this.command_handlers = {};
  44. this.onloads = [];
  45. this.messages = {};
  46. this.group2expand = {};
  47. this.http_request_jobs = {};
  48. this.menu_stack = [];
  49. // webmail client settings
  50. this.dblclick_time = 500;
  51. this.message_time = 5000;
  52. this.identifier_expr = /[^0-9a-z_-]/gi;
  53. // environment defaults
  54. this.env = {
  55. request_timeout: 180, // seconds
  56. draft_autosave: 0, // seconds
  57. comm_path: './',
  58. blankpage: 'program/resources/blank.gif',
  59. recipients_separator: ',',
  60. recipients_delimiter: ', ',
  61. popup_width: 1150,
  62. popup_width_small: 900
  63. };
  64. // create protected reference to myself
  65. this.ref = 'rcmail';
  66. var ref = this;
  67. // set jQuery ajax options
  68. $.ajaxSetup({
  69. cache: false,
  70. timeout: this.env.request_timeout * 1000,
  71. error: function(request, status, err){ ref.http_error(request, status, err); },
  72. beforeSend: function(xmlhttp){ xmlhttp.setRequestHeader('X-Roundcube-Request', ref.env.request_token); }
  73. });
  74. // unload fix
  75. $(window).bind('beforeunload', function() { ref.unload = true; });
  76. // set environment variable(s)
  77. this.set_env = function(p, value)
  78. {
  79. if (p != null && typeof p === 'object' && !value)
  80. for (var n in p)
  81. this.env[n] = p[n];
  82. else
  83. this.env[p] = value;
  84. };
  85. // add a localized label to the client environment
  86. this.add_label = function(p, value)
  87. {
  88. if (typeof p == 'string')
  89. this.labels[p] = value;
  90. else if (typeof p == 'object')
  91. $.extend(this.labels, p);
  92. };
  93. // add a button to the button list
  94. this.register_button = function(command, id, type, act, sel, over)
  95. {
  96. var button_prop = {id:id, type:type};
  97. if (act) button_prop.act = act;
  98. if (sel) button_prop.sel = sel;
  99. if (over) button_prop.over = over;
  100. if (!this.buttons[command])
  101. this.buttons[command] = [];
  102. this.buttons[command].push(button_prop);
  103. if (this.loaded)
  104. init_button(command, button_prop);
  105. };
  106. // register a specific gui object
  107. this.gui_object = function(name, id)
  108. {
  109. this.gui_objects[name] = this.loaded ? rcube_find_object(id) : id;
  110. };
  111. // register a container object
  112. this.gui_container = function(name, id)
  113. {
  114. this.gui_containers[name] = id;
  115. };
  116. // add a GUI element (html node) to a specified container
  117. this.add_element = function(elm, container)
  118. {
  119. if (this.gui_containers[container] && this.gui_containers[container].jquery)
  120. this.gui_containers[container].append(elm);
  121. };
  122. // register an external handler for a certain command
  123. this.register_command = function(command, callback, enable)
  124. {
  125. this.command_handlers[command] = callback;
  126. if (enable)
  127. this.enable_command(command, true);
  128. };
  129. // execute the given script on load
  130. this.add_onload = function(f)
  131. {
  132. this.onloads.push(f);
  133. };
  134. // initialize webmail client
  135. this.init = function()
  136. {
  137. var n;
  138. this.task = this.env.task;
  139. // check browser
  140. if (this.env.server_error != 409 && (!bw.dom || !bw.xmlhttp_test() || (bw.mz && bw.vendver < 1.9) || (bw.ie && bw.vendver < 7))) {
  141. this.goto_url('error', '_code=0x199');
  142. return;
  143. }
  144. // find all registered gui containers
  145. for (n in this.gui_containers)
  146. this.gui_containers[n] = $('#'+this.gui_containers[n]);
  147. // find all registered gui objects
  148. for (n in this.gui_objects)
  149. this.gui_objects[n] = rcube_find_object(this.gui_objects[n]);
  150. // clickjacking protection
  151. if (this.env.x_frame_options) {
  152. try {
  153. // bust frame if not allowed
  154. if (this.env.x_frame_options == 'deny' && top.location.href != self.location.href)
  155. top.location.href = self.location.href;
  156. else if (top.location.hostname != self.location.hostname)
  157. throw 1;
  158. } catch (e) {
  159. // possible clickjacking attack: disable all form elements
  160. $('form').each(function(){ ref.lock_form(this, true); });
  161. this.display_message("Blocked: possible clickjacking attack!", 'error');
  162. return;
  163. }
  164. }
  165. // init registered buttons
  166. this.init_buttons();
  167. // tell parent window that this frame is loaded
  168. if (this.is_framed()) {
  169. parent.rcmail.set_busy(false, null, parent.rcmail.env.frame_lock);
  170. parent.rcmail.env.frame_lock = null;
  171. }
  172. // enable general commands
  173. this.enable_command('close', 'logout', 'mail', 'addressbook', 'settings', 'save-pref',
  174. 'compose', 'undo', 'about', 'switch-task', 'menu-open', 'menu-close', 'menu-save', true);
  175. // set active task button
  176. this.set_button(this.task, 'sel');
  177. if (this.env.permaurl)
  178. this.enable_command('permaurl', 'extwin', true);
  179. switch (this.task) {
  180. case 'mail':
  181. // enable mail commands
  182. this.enable_command('list', 'checkmail', 'add-contact', 'search', 'reset-search', 'collapse-folder', 'import-messages', true);
  183. if (this.gui_objects.messagelist) {
  184. this.message_list = new rcube_list_widget(this.gui_objects.messagelist, {
  185. multiselect:true, multiexpand:true, draggable:true, keyboard:true,
  186. column_movable:this.env.col_movable, dblclick_time:this.dblclick_time
  187. });
  188. this.message_list
  189. .addEventListener('initrow', function(o) { ref.init_message_row(o); })
  190. .addEventListener('dblclick', function(o) { ref.msglist_dbl_click(o); })
  191. .addEventListener('click', function(o) { ref.msglist_click(o); })
  192. .addEventListener('keypress', function(o) { ref.msglist_keypress(o); })
  193. .addEventListener('select', function(o) { ref.msglist_select(o); })
  194. .addEventListener('dragstart', function(o) { ref.drag_start(o); })
  195. .addEventListener('dragmove', function(e) { ref.drag_move(e); })
  196. .addEventListener('dragend', function(e) { ref.drag_end(e); })
  197. .addEventListener('expandcollapse', function(o) { ref.msglist_expand(o); })
  198. .addEventListener('column_replace', function(o) { ref.msglist_set_coltypes(o); })
  199. .addEventListener('listupdate', function(o) { ref.triggerEvent('listupdate', o); })
  200. .init();
  201. // TODO: this should go into the list-widget code
  202. $(this.message_list.thead).on('click', 'a.sortcol', function(e){
  203. return ref.command('sort', $(this).attr('rel'), this);
  204. });
  205. this.enable_command('toggle_status', 'toggle_flag', 'sort', true);
  206. this.enable_command('set-listmode', this.env.threads && !this.is_multifolder_listing());
  207. // load messages
  208. this.command('list');
  209. $(this.gui_objects.qsearchbox).val(this.env.search_text).focusin(function() { ref.message_list.blur(); });
  210. }
  211. this.set_button_titles();
  212. this.env.message_commands = ['show', 'reply', 'reply-all', 'reply-list',
  213. 'move', 'copy', 'delete', 'open', 'mark', 'edit', 'viewsource',
  214. 'print', 'load-attachment', 'download-attachment', 'show-headers', 'hide-headers', 'download',
  215. 'forward', 'forward-inline', 'forward-attachment', 'change-format'];
  216. if (this.env.action == 'show' || this.env.action == 'preview') {
  217. this.enable_command(this.env.message_commands, this.env.uid);
  218. this.enable_command('reply-list', this.env.list_post);
  219. if (this.env.action == 'show') {
  220. this.http_request('pagenav', {_uid: this.env.uid, _mbox: this.env.mailbox, _search: this.env.search_request},
  221. this.display_message('', 'loading'));
  222. }
  223. if (this.env.blockedobjects) {
  224. if (this.gui_objects.remoteobjectsmsg)
  225. this.gui_objects.remoteobjectsmsg.style.display = 'block';
  226. this.enable_command('load-images', 'always-load', true);
  227. }
  228. // make preview/message frame visible
  229. if (this.env.action == 'preview' && this.is_framed()) {
  230. this.enable_command('compose', 'add-contact', false);
  231. parent.rcmail.show_contentframe(true);
  232. }
  233. }
  234. else if (this.env.action == 'compose') {
  235. this.env.address_group_stack = [];
  236. this.env.compose_commands = ['send-attachment', 'remove-attachment', 'send', 'cancel',
  237. 'toggle-editor', 'list-adresses', 'pushgroup', 'search', 'reset-search', 'extwin',
  238. 'insert-response', 'save-response', 'menu-open', 'menu-close'];
  239. if (this.env.drafts_mailbox)
  240. this.env.compose_commands.push('savedraft')
  241. this.enable_command(this.env.compose_commands, 'identities', 'responses', true);
  242. // add more commands (not enabled)
  243. $.merge(this.env.compose_commands, ['add-recipient', 'firstpage', 'previouspage', 'nextpage', 'lastpage']);
  244. if (window.googie) {
  245. this.env.editor_config.spellchecker = googie;
  246. this.env.editor_config.spellcheck_observer = function(s) { ref.spellcheck_state(); };
  247. this.env.compose_commands.push('spellcheck')
  248. this.enable_command('spellcheck', true);
  249. }
  250. // initialize HTML editor
  251. this.editor_init(this.env.editor_config, this.env.composebody);
  252. // init canned response functions
  253. if (this.gui_objects.responseslist) {
  254. $('a.insertresponse', this.gui_objects.responseslist)
  255. .attr('unselectable', 'on')
  256. .mousedown(function(e){ return rcube_event.cancel(e); })
  257. .bind('mouseup keypress', function(e){
  258. if (e.type == 'mouseup' || rcube_event.get_keycode(e) == 13) {
  259. ref.command('insert-response', $(this).attr('rel'));
  260. $(document.body).trigger('mouseup'); // hides the menu
  261. return rcube_event.cancel(e);
  262. }
  263. });
  264. // avoid textarea loosing focus when hitting the save-response button/link
  265. $.each(this.buttons['save-response'] || [], function (i, v) {
  266. $('#' + v.id).mousedown(function(e){ return rcube_event.cancel(e); })
  267. });
  268. }
  269. // init message compose form
  270. this.init_messageform();
  271. }
  272. else if (this.env.action == 'get')
  273. this.enable_command('download', 'print', true);
  274. // show printing dialog
  275. else if (this.env.action == 'print' && this.env.uid) {
  276. if (bw.safari)
  277. setTimeout('window.print()', 10);
  278. else
  279. window.print();
  280. }
  281. // get unread count for each mailbox
  282. if (this.gui_objects.mailboxlist) {
  283. this.env.unread_counts = {};
  284. this.gui_objects.folderlist = this.gui_objects.mailboxlist;
  285. this.http_request('getunread');
  286. }
  287. // init address book widget
  288. if (this.gui_objects.contactslist) {
  289. this.contact_list = new rcube_list_widget(this.gui_objects.contactslist,
  290. { multiselect:true, draggable:false, keyboard:true });
  291. this.contact_list
  292. .addEventListener('initrow', function(o) { ref.triggerEvent('insertrow', { cid:o.uid, row:o }); })
  293. .addEventListener('select', function(o) { ref.compose_recipient_select(o); })
  294. .addEventListener('dblclick', function(o) { ref.compose_add_recipient(); })
  295. .addEventListener('keypress', function(o) {
  296. if (o.key_pressed == o.ENTER_KEY) {
  297. if (!ref.compose_add_recipient()) {
  298. // execute link action on <enter> if not a recipient entry
  299. if (o.last_selected && String(o.last_selected).charAt(0) == 'G') {
  300. $(o.rows[o.last_selected].obj).find('a').first().click();
  301. }
  302. }
  303. }
  304. })
  305. .init();
  306. // remember last focused address field
  307. $('#_to,#_cc,#_bcc').focus(function() { ref.env.focused_field = this; });
  308. }
  309. if (this.gui_objects.addressbookslist) {
  310. this.gui_objects.folderlist = this.gui_objects.addressbookslist;
  311. this.enable_command('list-adresses', true);
  312. }
  313. // ask user to send MDN
  314. if (this.env.mdn_request && this.env.uid) {
  315. var postact = 'sendmdn',
  316. postdata = {_uid: this.env.uid, _mbox: this.env.mailbox};
  317. if (!confirm(this.get_label('mdnrequest'))) {
  318. postdata._flag = 'mdnsent';
  319. postact = 'mark';
  320. }
  321. this.http_post(postact, postdata);
  322. }
  323. // detect browser capabilities
  324. if (!this.is_framed() && !this.env.extwin)
  325. this.browser_capabilities_check();
  326. break;
  327. case 'addressbook':
  328. this.env.address_group_stack = [];
  329. if (this.gui_objects.folderlist)
  330. this.env.contactfolders = $.extend($.extend({}, this.env.address_sources), this.env.contactgroups);
  331. this.enable_command('add', 'import', this.env.writable_source);
  332. this.enable_command('list', 'listgroup', 'pushgroup', 'popgroup', 'listsearch', 'search', 'reset-search', 'advanced-search', true);
  333. if (this.gui_objects.contactslist) {
  334. this.contact_list = new rcube_list_widget(this.gui_objects.contactslist,
  335. {multiselect:true, draggable:this.gui_objects.folderlist?true:false, keyboard:true});
  336. this.contact_list
  337. .addEventListener('initrow', function(o) { ref.triggerEvent('insertrow', { cid:o.uid, row:o }); })
  338. .addEventListener('keypress', function(o) { ref.contactlist_keypress(o); })
  339. .addEventListener('select', function(o) { ref.contactlist_select(o); })
  340. .addEventListener('dragstart', function(o) { ref.drag_start(o); })
  341. .addEventListener('dragmove', function(e) { ref.drag_move(e); })
  342. .addEventListener('dragend', function(e) { ref.drag_end(e); })
  343. .init();
  344. $(this.gui_objects.qsearchbox).focusin(function() { ref.contact_list.blur(); });
  345. this.update_group_commands();
  346. this.command('list');
  347. }
  348. if (this.gui_objects.savedsearchlist) {
  349. this.savedsearchlist = new rcube_treelist_widget(this.gui_objects.savedsearchlist, {
  350. id_prefix: 'rcmli',
  351. id_encode: this.html_identifier_encode,
  352. id_decode: this.html_identifier_decode
  353. });
  354. this.savedsearchlist.addEventListener('select', function(node) {
  355. ref.triggerEvent('selectfolder', { folder:node.id, prefix:'rcmli' }); });
  356. }
  357. this.set_page_buttons();
  358. if (this.env.cid) {
  359. this.enable_command('show', 'edit', true);
  360. // register handlers for group assignment via checkboxes
  361. if (this.gui_objects.editform) {
  362. $('input.groupmember').change(function() {
  363. ref.group_member_change(this.checked ? 'add' : 'del', ref.env.cid, ref.env.source, this.value);
  364. });
  365. }
  366. }
  367. if (this.gui_objects.editform) {
  368. this.enable_command('save', true);
  369. if (this.env.action == 'add' || this.env.action == 'edit' || this.env.action == 'search')
  370. this.init_contact_form();
  371. }
  372. break;
  373. case 'settings':
  374. this.enable_command('preferences', 'identities', 'responses', 'save', 'folders', true);
  375. if (this.env.action == 'identities') {
  376. this.enable_command('add', this.env.identities_level < 2);
  377. }
  378. else if (this.env.action == 'edit-identity' || this.env.action == 'add-identity') {
  379. this.enable_command('save', 'edit', 'toggle-editor', true);
  380. this.enable_command('delete', this.env.identities_level < 2);
  381. // initialize HTML editor
  382. this.editor_init(this.env.editor_config, 'rcmfd_signature');
  383. }
  384. else if (this.env.action == 'folders') {
  385. this.enable_command('subscribe', 'unsubscribe', 'create-folder', 'rename-folder', true);
  386. }
  387. else if (this.env.action == 'edit-folder' && this.gui_objects.editform) {
  388. this.enable_command('save', 'folder-size', true);
  389. parent.rcmail.env.exists = this.env.messagecount;
  390. parent.rcmail.enable_command('purge', this.env.messagecount);
  391. }
  392. else if (this.env.action == 'responses') {
  393. this.enable_command('add', true);
  394. }
  395. if (this.gui_objects.identitieslist) {
  396. this.identity_list = new rcube_list_widget(this.gui_objects.identitieslist,
  397. {multiselect:false, draggable:false, keyboard:true});
  398. this.identity_list
  399. .addEventListener('select', function(o) { ref.identity_select(o); })
  400. .addEventListener('keypress', function(o) {
  401. if (o.key_pressed == o.ENTER_KEY) {
  402. ref.identity_select(o);
  403. }
  404. })
  405. .init()
  406. .focus();
  407. }
  408. else if (this.gui_objects.sectionslist) {
  409. this.sections_list = new rcube_list_widget(this.gui_objects.sectionslist, {multiselect:false, draggable:false, keyboard:true});
  410. this.sections_list
  411. .addEventListener('select', function(o) { ref.section_select(o); })
  412. .addEventListener('keypress', function(o) { if (o.key_pressed == o.ENTER_KEY) ref.section_select(o); })
  413. .init()
  414. .focus();
  415. }
  416. else if (this.gui_objects.subscriptionlist) {
  417. this.init_subscription_list();
  418. }
  419. else if (this.gui_objects.responseslist) {
  420. this.responses_list = new rcube_list_widget(this.gui_objects.responseslist, {multiselect:false, draggable:false, keyboard:true});
  421. this.responses_list
  422. .addEventListener('select', function(list) {
  423. var win, id = list.get_single_selection();
  424. ref.enable_command('delete', !!id && $.inArray(id, ref.env.readonly_responses) < 0);
  425. if (id && (win = ref.get_frame_window(ref.env.contentframe))) {
  426. ref.set_busy(true);
  427. ref.location_href({ _action:'edit-response', _key:id, _framed:1 }, win);
  428. }
  429. })
  430. .init()
  431. .focus();
  432. }
  433. break;
  434. case 'login':
  435. var input_user = $('#rcmloginuser');
  436. input_user.bind('keyup', function(e){ return ref.login_user_keyup(e); });
  437. if (input_user.val() == '')
  438. input_user.focus();
  439. else
  440. $('#rcmloginpwd').focus();
  441. // detect client timezone
  442. if (window.jstz) {
  443. var timezone = jstz.determine();
  444. if (timezone.name())
  445. $('#rcmlogintz').val(timezone.name());
  446. }
  447. else {
  448. $('#rcmlogintz').val(new Date().getStdTimezoneOffset() / -60);
  449. }
  450. // display 'loading' message on form submit, lock submit button
  451. $('form').submit(function () {
  452. $('input[type=submit]', this).prop('disabled', true);
  453. ref.clear_messages();
  454. ref.display_message('', 'loading');
  455. });
  456. this.enable_command('login', true);
  457. break;
  458. }
  459. // select first input field in an edit form
  460. if (this.gui_objects.editform)
  461. $("input,select,textarea", this.gui_objects.editform)
  462. .not(':hidden').not(':disabled').first().select().focus();
  463. // unset contentframe variable if preview_pane is enabled
  464. if (this.env.contentframe && !$('#' + this.env.contentframe).is(':visible'))
  465. this.env.contentframe = null;
  466. // prevent from form submit with Enter key in file input fields
  467. if (bw.ie)
  468. $('input[type=file]').keydown(function(e) { if (e.keyCode == '13') e.preventDefault(); });
  469. // flag object as complete
  470. this.loaded = true;
  471. this.env.lastrefresh = new Date();
  472. // show message
  473. if (this.pending_message)
  474. this.display_message(this.pending_message[0], this.pending_message[1], this.pending_message[2]);
  475. // init treelist widget
  476. if (this.gui_objects.folderlist && window.rcube_treelist_widget) {
  477. this.treelist = new rcube_treelist_widget(this.gui_objects.folderlist, {
  478. selectable: true,
  479. id_prefix: 'rcmli',
  480. id_encode: this.html_identifier_encode,
  481. id_decode: this.html_identifier_decode,
  482. check_droptarget: function(node) { return !node.virtual && ref.check_droptarget(node.id) }
  483. });
  484. this.treelist
  485. .addEventListener('collapse', function(node) { ref.folder_collapsed(node) })
  486. .addEventListener('expand', function(node) { ref.folder_collapsed(node) })
  487. .addEventListener('select', function(node) { ref.triggerEvent('selectfolder', { folder:node.id, prefix:'rcmli' }) });
  488. }
  489. // activate html5 file drop feature (if browser supports it and if configured)
  490. if (this.gui_objects.filedrop && this.env.filedrop && ((window.XMLHttpRequest && XMLHttpRequest.prototype && XMLHttpRequest.prototype.sendAsBinary) || window.FormData)) {
  491. $(document.body).bind('dragover dragleave drop', function(e){ return ref.document_drag_hover(e, e.type == 'dragover'); });
  492. $(this.gui_objects.filedrop).addClass('droptarget')
  493. .bind('dragover dragleave', function(e){ return ref.file_drag_hover(e, e.type == 'dragover'); })
  494. .get(0).addEventListener('drop', function(e){ return ref.file_dropped(e); }, false);
  495. }
  496. // catch document (and iframe) mouse clicks
  497. var body_mouseup = function(e){ return ref.doc_mouse_up(e); };
  498. $(document.body)
  499. .bind('mouseup', body_mouseup)
  500. .bind('keydown', function(e){ return ref.doc_keypress(e); });
  501. $('iframe').load(function(e) {
  502. try { $(this.contentDocument || this.contentWindow).on('mouseup', body_mouseup); }
  503. catch (e) {/* catch possible "Permission denied" error in IE */ }
  504. })
  505. .contents().on('mouseup', body_mouseup);
  506. // trigger init event hook
  507. this.triggerEvent('init', { task:this.task, action:this.env.action });
  508. // execute all foreign onload scripts
  509. // @deprecated
  510. for (n in this.onloads) {
  511. if (typeof this.onloads[n] === 'string')
  512. eval(this.onloads[n]);
  513. else if (typeof this.onloads[n] === 'function')
  514. this.onloads[n]();
  515. }
  516. // start keep-alive and refresh intervals
  517. this.start_refresh();
  518. this.start_keepalive();
  519. };
  520. this.log = function(msg)
  521. {
  522. if (window.console && console.log)
  523. console.log(msg);
  524. };
  525. /*********************************************************/
  526. /********* client command interface *********/
  527. /*********************************************************/
  528. // execute a specific command on the web client
  529. this.command = function(command, props, obj, event)
  530. {
  531. var ret, uid, cid, url, flag, aborted = false;
  532. if (obj && obj.blur && !(event && rcube_event.is_keyboard(event)))
  533. obj.blur();
  534. // do nothing if interface is locked by other command (with exception for searching reset)
  535. if (this.busy && !(command == 'reset-search' && this.last_command == 'search'))
  536. return false;
  537. // let the browser handle this click (shift/ctrl usually opens the link in a new window/tab)
  538. if ((obj && obj.href && String(obj.href).indexOf('#') < 0) && rcube_event.get_modifier(event)) {
  539. return true;
  540. }
  541. // command not supported or allowed
  542. if (!this.commands[command]) {
  543. // pass command to parent window
  544. if (this.is_framed())
  545. parent.rcmail.command(command, props);
  546. return false;
  547. }
  548. // check input before leaving compose step
  549. if (this.task == 'mail' && this.env.action == 'compose' && $.inArray(command, this.env.compose_commands) < 0 && !this.env.server_error) {
  550. if (this.cmp_hash != this.compose_field_hash() && !confirm(this.get_label('notsentwarning')))
  551. return false;
  552. // remove copy from local storage if compose screen is left intentionally
  553. this.remove_compose_data(this.env.compose_id);
  554. this.compose_skip_unsavedcheck = true;
  555. }
  556. this.last_command = command;
  557. // process external commands
  558. if (typeof this.command_handlers[command] === 'function') {
  559. ret = this.command_handlers[command](props, obj, event);
  560. return ret !== undefined ? ret : (obj ? false : true);
  561. }
  562. else if (typeof this.command_handlers[command] === 'string') {
  563. ret = window[this.command_handlers[command]](props, obj, event);
  564. return ret !== undefined ? ret : (obj ? false : true);
  565. }
  566. // trigger plugin hooks
  567. this.triggerEvent('actionbefore', {props:props, action:command, originalEvent:event});
  568. ret = this.triggerEvent('before'+command, props || event);
  569. if (ret !== undefined) {
  570. // abort if one of the handlers returned false
  571. if (ret === false)
  572. return false;
  573. else
  574. props = ret;
  575. }
  576. ret = undefined;
  577. // process internal command
  578. switch (command) {
  579. case 'login':
  580. if (this.gui_objects.loginform)
  581. this.gui_objects.loginform.submit();
  582. break;
  583. // commands to switch task
  584. case 'logout':
  585. case 'mail':
  586. case 'addressbook':
  587. case 'settings':
  588. this.switch_task(command);
  589. break;
  590. case 'about':
  591. this.redirect('?_task=settings&_action=about', false);
  592. break;
  593. case 'permaurl':
  594. if (obj && obj.href && obj.target)
  595. return true;
  596. else if (this.env.permaurl)
  597. parent.location.href = this.env.permaurl;
  598. break;
  599. case 'extwin':
  600. if (this.env.action == 'compose') {
  601. var form = this.gui_objects.messageform,
  602. win = this.open_window('');
  603. if (win) {
  604. this.save_compose_form_local();
  605. this.compose_skip_unsavedcheck = true;
  606. $("input[name='_action']", form).val('compose');
  607. form.action = this.url('mail/compose', { _id: this.env.compose_id, _extwin: 1 });
  608. form.target = win.name;
  609. form.submit();
  610. }
  611. }
  612. else {
  613. this.open_window(this.env.permaurl, true);
  614. }
  615. break;
  616. case 'change-format':
  617. url = this.env.permaurl + '&_format=' + props;
  618. if (this.env.action == 'preview')
  619. url = url.replace(/_action=show/, '_action=preview') + '&_framed=1';
  620. if (this.env.extwin)
  621. url += '&_extwin=1';
  622. location.href = url;
  623. break;
  624. case 'menu-open':
  625. if (props && props.menu == 'attachmentmenu') {
  626. var mimetype = this.env.attachments[props.id];
  627. this.enable_command('open-attachment', mimetype && this.env.mimetypes && $.inArray(mimetype, this.env.mimetypes) >= 0);
  628. }
  629. this.show_menu(props, props.show || undefined, event);
  630. break;
  631. case 'menu-close':
  632. this.hide_menu(props, event);
  633. break;
  634. case 'menu-save':
  635. this.triggerEvent(command, {props:props, originalEvent:event});
  636. return false;
  637. case 'open':
  638. if (uid = this.get_single_uid()) {
  639. obj.href = this.url('show', {_mbox: this.get_message_mailbox(uid), _uid: uid});
  640. return true;
  641. }
  642. break;
  643. case 'close':
  644. if (this.env.extwin)
  645. window.close();
  646. break;
  647. case 'list':
  648. if (props && props != '') {
  649. this.reset_qsearch();
  650. }
  651. if (this.env.action == 'compose' && this.env.extwin) {
  652. window.close();
  653. }
  654. else if (this.task == 'mail') {
  655. this.list_mailbox(props);
  656. this.set_button_titles();
  657. }
  658. else if (this.task == 'addressbook')
  659. this.list_contacts(props);
  660. break;
  661. case 'set-listmode':
  662. this.set_list_options(null, undefined, undefined, props == 'threads' ? 1 : 0);
  663. break;
  664. case 'sort':
  665. var sort_order = this.env.sort_order,
  666. sort_col = !this.env.disabled_sort_col ? props : this.env.sort_col;
  667. if (!this.env.disabled_sort_order)
  668. sort_order = this.env.sort_col == sort_col && sort_order == 'ASC' ? 'DESC' : 'ASC';
  669. // set table header and update env
  670. this.set_list_sorting(sort_col, sort_order);
  671. // reload message list
  672. this.list_mailbox('', '', sort_col+'_'+sort_order);
  673. break;
  674. case 'nextpage':
  675. this.list_page('next');
  676. break;
  677. case 'lastpage':
  678. this.list_page('last');
  679. break;
  680. case 'previouspage':
  681. this.list_page('prev');
  682. break;
  683. case 'firstpage':
  684. this.list_page('first');
  685. break;
  686. case 'expunge':
  687. if (this.env.exists)
  688. this.expunge_mailbox(this.env.mailbox);
  689. break;
  690. case 'purge':
  691. case 'empty-mailbox':
  692. if (this.env.exists)
  693. this.purge_mailbox(this.env.mailbox);
  694. break;
  695. // common commands used in multiple tasks
  696. case 'show':
  697. if (this.task == 'mail') {
  698. uid = this.get_single_uid();
  699. if (uid && (!this.env.uid || uid != this.env.uid)) {
  700. if (this.env.mailbox == this.env.drafts_mailbox)
  701. this.open_compose_step({ _draft_uid: uid, _mbox: this.env.mailbox });
  702. else
  703. this.show_message(uid);
  704. }
  705. }
  706. else if (this.task == 'addressbook') {
  707. cid = props ? props : this.get_single_cid();
  708. if (cid && !(this.env.action == 'show' && cid == this.env.cid))
  709. this.load_contact(cid, 'show');
  710. }
  711. break;
  712. case 'add':
  713. if (this.task == 'addressbook')
  714. this.load_contact(0, 'add');
  715. else if (this.task == 'settings' && this.env.action == 'responses') {
  716. var frame;
  717. if ((frame = this.get_frame_window(this.env.contentframe))) {
  718. this.set_busy(true);
  719. this.location_href({ _action:'add-response', _framed:1 }, frame);
  720. }
  721. }
  722. else if (this.task == 'settings') {
  723. this.identity_list.clear_selection();
  724. this.load_identity(0, 'add-identity');
  725. }
  726. break;
  727. case 'edit':
  728. if (this.task == 'addressbook' && (cid = this.get_single_cid()))
  729. this.load_contact(cid, 'edit');
  730. else if (this.task == 'settings' && props)
  731. this.load_identity(props, 'edit-identity');
  732. else if (this.task == 'mail' && (uid = this.get_single_uid())) {
  733. url = { _mbox: this.get_message_mailbox(uid) };
  734. url[this.env.mailbox == this.env.drafts_mailbox && props != 'new' ? '_draft_uid' : '_uid'] = uid;
  735. this.open_compose_step(url);
  736. }
  737. break;
  738. case 'save':
  739. var input, form = this.gui_objects.editform;
  740. if (form) {
  741. // adv. search
  742. if (this.env.action == 'search') {
  743. }
  744. // user prefs
  745. else if ((input = $("input[name='_pagesize']", form)) && input.length && isNaN(parseInt(input.val()))) {
  746. alert(this.get_label('nopagesizewarning'));
  747. input.focus();
  748. break;
  749. }
  750. // contacts/identities
  751. else {
  752. // reload form
  753. if (props == 'reload') {
  754. form.action += '?_reload=1';
  755. }
  756. else if (this.task == 'settings' && (this.env.identities_level % 2) == 0 &&
  757. (input = $("input[name='_email']", form)) && input.length && !rcube_check_email(input.val())
  758. ) {
  759. alert(this.get_label('noemailwarning'));
  760. input.focus();
  761. break;
  762. }
  763. // clear empty input fields
  764. $('input.placeholder').each(function(){ if (this.value == this._placeholder) this.value = ''; });
  765. }
  766. // add selected source (on the list)
  767. if (parent.rcmail && parent.rcmail.env.source)
  768. form.action = this.add_url(form.action, '_orig_source', parent.rcmail.env.source);
  769. form.submit();
  770. }
  771. break;
  772. case 'delete':
  773. // mail task
  774. if (this.task == 'mail')
  775. this.delete_messages(event);
  776. // addressbook task
  777. else if (this.task == 'addressbook')
  778. this.delete_contacts();
  779. // settings: canned response
  780. else if (this.task == 'settings' && this.env.action == 'responses')
  781. this.delete_response();
  782. // settings: user identities
  783. else if (this.task == 'settings')
  784. this.delete_identity();
  785. break;
  786. // mail task commands
  787. case 'move':
  788. case 'moveto': // deprecated
  789. if (this.task == 'mail')
  790. this.move_messages(props, event);
  791. else if (this.task == 'addressbook')
  792. this.move_contacts(props);
  793. break;
  794. case 'copy':
  795. if (this.task == 'mail')
  796. this.copy_messages(props, event);
  797. else if (this.task == 'addressbook')
  798. this.copy_contacts(props);
  799. break;
  800. case 'mark':
  801. if (props)
  802. this.mark_message(props);
  803. break;
  804. case 'toggle_status':
  805. case 'toggle_flag':
  806. flag = command == 'toggle_flag' ? 'flagged' : 'read';
  807. if (uid = props) {
  808. // toggle flagged/unflagged
  809. if (flag == 'flagged') {
  810. if (this.message_list.rows[uid].flagged)
  811. flag = 'unflagged';
  812. }
  813. // toggle read/unread
  814. else if (this.message_list.rows[uid].deleted)
  815. flag = 'undelete';
  816. else if (!this.message_list.rows[uid].unread)
  817. flag = 'unread';
  818. this.mark_message(flag, uid);
  819. }
  820. break;
  821. case 'always-load':
  822. if (this.env.uid && this.env.sender) {
  823. this.add_contact(this.env.sender);
  824. setTimeout(function(){ ref.command('load-images'); }, 300);
  825. break;
  826. }
  827. case 'load-images':
  828. if (this.env.uid)
  829. this.show_message(this.env.uid, true, this.env.action=='preview');
  830. break;
  831. case 'load-attachment':
  832. case 'open-attachment':
  833. case 'download-attachment':
  834. var qstring = '_mbox='+urlencode(this.env.mailbox)+'&_uid='+this.env.uid+'&_part='+props,
  835. mimetype = this.env.attachments[props];
  836. // open attachment in frame if it's of a supported mimetype
  837. if (command != 'download-attachment' && mimetype && this.env.mimetypes && $.inArray(mimetype, this.env.mimetypes) >= 0) {
  838. if (this.open_window(this.env.comm_path+'&_action=get&'+qstring+'&_frame=1'))
  839. break;
  840. }
  841. this.goto_url('get', qstring+'&_download=1', false);
  842. break;
  843. case 'select-all':
  844. this.select_all_mode = props ? false : true;
  845. this.dummy_select = true; // prevent msg opening if there's only one msg on the list
  846. if (props == 'invert')
  847. this.message_list.invert_selection();
  848. else
  849. this.message_list.select_all(props == 'page' ? '' : props);
  850. this.dummy_select = null;
  851. break;
  852. case 'select-none':
  853. this.select_all_mode = false;
  854. this.message_list.clear_selection();
  855. break;
  856. case 'expand-all':
  857. this.env.autoexpand_threads = 1;
  858. this.message_list.expand_all();
  859. break;
  860. case 'expand-unread':
  861. this.env.autoexpand_threads = 2;
  862. this.message_list.collapse_all();
  863. this.expand_unread();
  864. break;
  865. case 'collapse-all':
  866. this.env.autoexpand_threads = 0;
  867. this.message_list.collapse_all();
  868. break;
  869. case 'nextmessage':
  870. if (this.env.next_uid)
  871. this.show_message(this.env.next_uid, false, this.env.action == 'preview');
  872. break;
  873. case 'lastmessage':
  874. if (this.env.last_uid)
  875. this.show_message(this.env.last_uid);
  876. break;
  877. case 'previousmessage':
  878. if (this.env.prev_uid)
  879. this.show_message(this.env.prev_uid, false, this.env.action == 'preview');
  880. break;
  881. case 'firstmessage':
  882. if (this.env.first_uid)
  883. this.show_message(this.env.first_uid);
  884. break;
  885. case 'compose':
  886. url = {};
  887. if (this.task == 'mail') {
  888. url._mbox = this.env.mailbox;
  889. if (props)
  890. url._to = props;
  891. // also send search request so we can go back to search result after message is sent
  892. if (this.env.search_request)
  893. url._search = this.env.search_request;
  894. }
  895. // modify url if we're in addressbook
  896. else if (this.task == 'addressbook') {
  897. // switch to mail compose step directly
  898. if (props && props.indexOf('@') > 0) {
  899. url._to = props;
  900. }
  901. else {
  902. var a_cids = [];
  903. // use contact id passed as command parameter
  904. if (props)
  905. a_cids.push(props);
  906. // get selected contacts
  907. else if (this.contact_list)
  908. a_cids = this.contact_list.get_selection();
  909. if (a_cids.length)
  910. this.http_post('mailto', { _cid: a_cids.join(','), _source: this.env.source }, true);
  911. else if (this.env.group)
  912. this.http_post('mailto', { _gid: this.env.group, _source: this.env.source }, true);
  913. break;
  914. }
  915. }
  916. else if (props && typeof props == 'string') {
  917. url._to = props;
  918. }
  919. else if (props && typeof props == 'object') {
  920. $.extend(url, props);
  921. }
  922. this.open_compose_step(url);
  923. break;
  924. case 'spellcheck':
  925. if (this.spellcheck_state()) {
  926. this.editor.spellcheck_stop();
  927. }
  928. else {
  929. this.editor.spellcheck_start();
  930. }
  931. break;
  932. case 'savedraft':
  933. // Reset the auto-save timer
  934. clearTimeout(this.save_timer);
  935. // compose form did not change (and draft wasn't saved already)
  936. if (this.env.draft_id && this.cmp_hash == this.compose_field_hash()) {
  937. this.auto_save_start();
  938. break;
  939. }
  940. this.submit_messageform(true);
  941. break;
  942. case 'send':
  943. if (!props.nocheck && !this.check_compose_input(command))
  944. break;
  945. // Reset the auto-save timer
  946. clearTimeout(this.save_timer);
  947. this.submit_messageform();
  948. break;
  949. case 'send-attachment':
  950. // Reset the auto-save timer
  951. clearTimeout(this.save_timer);
  952. if (!(flag = this.upload_file(props || this.gui_objects.uploadform, 'upload'))) {
  953. if (flag !== false)
  954. alert(this.get_label('selectimportfile'));
  955. aborted = true;
  956. }
  957. break;
  958. case 'insert-sig':
  959. this.change_identity($("[name='_from']")[0], true);
  960. break;
  961. case 'list-adresses':
  962. this.list_contacts(props);
  963. this.enable_command('add-recipient', false);
  964. break;
  965. case 'add-recipient':
  966. this.compose_add_recipient(props);
  967. break;
  968. case 'reply-all':
  969. case 'reply-list':
  970. case 'reply':
  971. if (uid = this.get_single_uid()) {
  972. url = {_reply_uid: uid, _mbox: this.get_message_mailbox(uid)};
  973. if (command == 'reply-all')
  974. // do reply-list, when list is detected and popup menu wasn't used
  975. url._all = (!props && this.env.reply_all_mode == 1 && this.commands['reply-list'] ? 'list' : 'all');
  976. else if (command == 'reply-list')
  977. url._all = 'list';
  978. this.open_compose_step(url);
  979. }
  980. break;
  981. case 'forward-attachment':
  982. case 'forward-inline':
  983. case 'forward':
  984. var uids = this.env.uid ? [this.env.uid] : (this.message_list ? this.message_list.get_selection() : []);
  985. if (uids.length) {
  986. url = { _forward_uid: this.uids_to_list(uids), _mbox: this.env.mailbox, _search: this.env.search_request };
  987. if (command == 'forward-attachment' || (!props && this.env.forward_attachment) || uids.length > 1)
  988. url._attachment = 1;
  989. this.open_compose_step(url);
  990. }
  991. break;
  992. case 'print':
  993. if (this.env.action == 'get') {
  994. this.gui_objects.messagepartframe.contentWindow.print();
  995. }
  996. else if (uid = this.get_single_uid()) {
  997. url = '&_action=print&_uid='+uid+'&_mbox='+urlencode(this.get_message_mailbox(uid))+(this.env.safemode ? '&_safe=1' : '');
  998. if (this.open_window(this.env.comm_path + url, true, true)) {
  999. if (this.env.action != 'show')
  1000. this.mark_message('read', uid);
  1001. }
  1002. }
  1003. break;
  1004. case 'viewsource':
  1005. if (uid = this.get_single_uid())
  1006. this.open_window(this.env.comm_path+'&_action=viewsource&_uid='+uid+'&_mbox='+urlencode(this.env.mailbox), true, true);
  1007. break;
  1008. case 'download':
  1009. if (this.env.action == 'get') {
  1010. location.href = location.href.replace(/_frame=/, '_download=');
  1011. }
  1012. else if (uid = this.get_single_uid()) {
  1013. this.goto_url('viewsource', { _uid: uid, _mbox: this.get_message_mailbox(uid), _save: 1 });
  1014. }
  1015. break;
  1016. // quicksearch
  1017. case 'search':
  1018. if (!props && this.gui_objects.qsearchbox)
  1019. props = this.gui_objects.qsearchbox.value;
  1020. if (props) {
  1021. this.qsearch(props);
  1022. break;
  1023. }
  1024. // reset quicksearch
  1025. case 'reset-search':
  1026. var n, s = this.env.search_request || this.env.qsearch;
  1027. this.reset_qsearch();
  1028. this.select_all_mode = false;
  1029. if (s && this.env.action == 'compose') {
  1030. if (this.contact_list)
  1031. this.list_contacts_clear();
  1032. }
  1033. else if (s && this.env.mailbox) {
  1034. this.list_mailbox(this.env.mailbox, 1);
  1035. }
  1036. else if (s && this.task == 'addressbook') {
  1037. if (this.env.source == '') {
  1038. for (n in this.env.address_sources) break;
  1039. this.env.source = n;
  1040. this.env.group = '';
  1041. }
  1042. this.list_contacts(this.env.source, this.env.group, 1);
  1043. }
  1044. break;
  1045. case 'pushgroup':
  1046. // add group ID to stack
  1047. this.env.address_group_stack.push(props.id);
  1048. if (obj && event)
  1049. rcube_event.cancel(event);
  1050. case 'listgroup':
  1051. this.reset_qsearch();
  1052. this.list_contacts(props.source, props.id);
  1053. break;
  1054. case 'popgroup':
  1055. if (this.env.address_group_stack.length > 1) {
  1056. this.env.address_group_stack.pop();
  1057. this.reset_qsearch();
  1058. this.list_contacts(props.source, this.env.address_group_stack[this.env.address_group_stack.length-1]);
  1059. }
  1060. break;
  1061. case 'import-messages':
  1062. var form = props || this.gui_objects.importform,
  1063. importlock = this.set_busy(true, 'importwait');
  1064. $('input[name="_unlock"]', form).val(importlock);
  1065. if (!(flag = this.upload_file(form, 'import'))) {
  1066. this.set_busy(false, null, importlock);
  1067. if (flag !== false)
  1068. alert(this.get_label('selectimportfile'));
  1069. aborted = true;
  1070. }
  1071. break;
  1072. case 'import':
  1073. if (this.env.action == 'import' && this.gui_objects.importform) {
  1074. var file = document.getElementById('rcmimportfile');
  1075. if (file && !file.value) {
  1076. alert(this.get_label('selectimportfile'));
  1077. aborted = true;
  1078. break;
  1079. }
  1080. this.gui_objects.importform.submit();
  1081. this.set_busy(true, 'importwait');
  1082. this.lock_form(this.gui_objects.importform, true);
  1083. }
  1084. else
  1085. this.goto_url('import', (this.env.source ? '_target='+urlencode(this.env.source)+'&' : ''));
  1086. break;
  1087. case 'export':
  1088. if (this.contact_list.rowcount > 0) {
  1089. this.goto_url('export', { _source: this.env.source, _gid: this.env.group, _search: this.env.search_request });
  1090. }
  1091. break;
  1092. case 'export-selected':
  1093. if (this.contact_list.rowcount > 0) {
  1094. this.goto_url('export', { _source: this.env.source, _gid: this.env.group, _cid: this.contact_list.get_selection().join(',') });
  1095. }
  1096. break;
  1097. case 'upload-photo':
  1098. this.upload_contact_photo(props || this.gui_objects.uploadform);
  1099. break;
  1100. case 'delete-photo':
  1101. this.replace_contact_photo('-del-');
  1102. break;
  1103. // user settings commands
  1104. case 'preferences':
  1105. case 'identities':
  1106. case 'responses':
  1107. case 'folders':
  1108. this.goto_url('settings/' + command);
  1109. break;
  1110. case 'undo':
  1111. this.http_request('undo', '', this.display_message('', 'loading'));
  1112. break;
  1113. // unified command call (command name == function name)
  1114. default:
  1115. var func = command.replace(/-/g, '_');
  1116. if (this[func] && typeof this[func] === 'function') {
  1117. ret = this[func](props, obj, event);
  1118. }
  1119. break;
  1120. }
  1121. if (!aborted && this.triggerEvent('after'+command, props) === false)
  1122. ret = false;
  1123. this.triggerEvent('actionafter', { props:props, action:command, aborted:aborted });
  1124. return ret === false ? false : obj ? false : true;
  1125. };
  1126. // set command(s) enabled or disabled
  1127. this.enable_command = function()
  1128. {
  1129. var i, n, args = Array.prototype.slice.call(arguments),
  1130. enable = args.pop(), cmd;
  1131. for (n=0; n<args.length; n++) {
  1132. cmd = args[n];
  1133. // argument of type array
  1134. if (typeof cmd === 'string') {
  1135. this.commands[cmd] = enable;
  1136. this.set_button(cmd, (enable ? 'act' : 'pas'));
  1137. this.triggerEvent('enable-command', {command: cmd, status: enable});
  1138. }
  1139. // push array elements into commands array
  1140. else {
  1141. for (i in cmd)
  1142. args.push(cmd[i]);
  1143. }
  1144. }
  1145. };
  1146. this.command_enabled = function(cmd)
  1147. {
  1148. return this.commands[cmd];
  1149. };
  1150. // lock/unlock interface
  1151. this.set_busy = function(a, message, id)
  1152. {
  1153. if (a && message) {
  1154. var msg = this.get_label(message);
  1155. if (msg == message)
  1156. msg = 'Loading...';
  1157. id = this.display_message(msg, 'loading');
  1158. }
  1159. else if (!a && id) {
  1160. this.hide_message(id);
  1161. }
  1162. this.busy = a;
  1163. //document.body.style.cursor = a ? 'wait' : 'default';
  1164. if (this.gui_objects.editform)
  1165. this.lock_form(this.gui_objects.editform, a);
  1166. return id;
  1167. };
  1168. // return a localized string
  1169. this.get_label = function(name, domain)
  1170. {
  1171. if (domain && this.labels[domain+'.'+name])
  1172. return this.labels[domain+'.'+name];
  1173. else if (this.labels[name])
  1174. return this.labels[name];
  1175. else
  1176. return name;
  1177. };
  1178. // alias for convenience reasons
  1179. this.gettext = this.get_label;
  1180. // switch to another application task
  1181. this.switch_task = function(task)
  1182. {
  1183. if (this.task === task && task != 'mail')
  1184. return;
  1185. var url = this.get_task_url(task);
  1186. if (task == 'mail')
  1187. url += '&_mbox=INBOX';
  1188. else if (task == 'logout' && !this.env.server_error)
  1189. this.clear_compose_data();
  1190. this.redirect(url);
  1191. };
  1192. this.get_task_url = function(task, url)
  1193. {
  1194. if (!url)
  1195. url = this.env.comm_path;
  1196. return url.replace(/_task=[a-z0-9_-]+/i, '_task='+task);
  1197. };
  1198. this.reload = function(delay)
  1199. {
  1200. if (this.is_framed())
  1201. parent.rcmail.reload(delay);
  1202. else if (delay)
  1203. setTimeout(function() { ref.reload(); }, delay);
  1204. else if (window.location)
  1205. location.href = this.env.comm_path + (this.env.action ? '&_action='+this.env.action : '');
  1206. };
  1207. // Add variable to GET string, replace old value if exists
  1208. this.add_url = function(url, name, value)
  1209. {
  1210. value = urlencode(value);
  1211. if (/(\?.*)$/.test(url)) {
  1212. var urldata = RegExp.$1,
  1213. datax = RegExp('((\\?|&)'+RegExp.escape(name)+'=[^&]*)');
  1214. if (datax.test(urldata)) {
  1215. urldata = urldata.replace(datax, RegExp.$2 + name + '=' + value);
  1216. }
  1217. else
  1218. urldata += '&' + name + '=' + value
  1219. return url.replace(/(\?.*)$/, urldata);
  1220. }
  1221. return url + '?' + name + '=' + value;
  1222. };
  1223. this.is_framed = function()
  1224. {
  1225. return (this.env.framed && parent.rcmail && parent.rcmail != this && parent.rcmail.command);
  1226. };
  1227. this.save_pref = function(prop)
  1228. {
  1229. var request = {_name: prop.name, _value: prop.value};
  1230. if (prop.session)
  1231. request._session = prop.session;
  1232. if (prop.env)
  1233. this.env[prop.env] = prop.value;
  1234. this.http_post('save-pref', request);
  1235. };
  1236. this.html_identifier = function(str, encode)
  1237. {
  1238. return encode ? this.html_identifier_encode(str) : String(str).replace(this.identifier_expr, '_');
  1239. };
  1240. this.html_identifier_encode = function(str)
  1241. {
  1242. return Base64.encode(String(str)).replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
  1243. };
  1244. this.html_identifier_decode = function(str)
  1245. {
  1246. str = String(str).replace(/-/g, '+').replace(/_/g, '/');
  1247. while (str.length % 4) str += '=';
  1248. return Base64.decode(str);
  1249. };
  1250. /*********************************************************/
  1251. /********* event handling methods *********/
  1252. /*********************************************************/
  1253. this.drag_menu = function(e, target)
  1254. {
  1255. var modkey = rcube_event.get_modifier(e),
  1256. menu = this.gui_objects.dragmenu;
  1257. if (menu && modkey == SHIFT_KEY && this.commands['copy']) {
  1258. var pos = rcube_event.get_mouse_pos(e);
  1259. this.env.drag_target = target;
  1260. this.show_menu(this.gui_objects.dragmenu.id, true, e);
  1261. $(menu).css({top: (pos.y-10)+'px', left: (pos.x-10)+'px'});
  1262. return true;
  1263. }
  1264. return false;
  1265. };
  1266. this.drag_menu_action = function(action)
  1267. {
  1268. var menu = this.gui_objects.dragmenu;
  1269. if (menu) {
  1270. $(menu).hide();
  1271. }
  1272. this.command(action, this.env.drag_target);
  1273. this.env.drag_target = null;
  1274. };
  1275. this.drag_start = function(list)
  1276. {
  1277. this.drag_active = true;
  1278. if (this.preview_timer)
  1279. clearTimeout(this.preview_timer);
  1280. if (this.preview_read_timer)
  1281. clearTimeout(this.preview_read_timer);
  1282. // prepare treelist widget for dragging interactions
  1283. if (this.treelist)
  1284. this.treelist.drag_start();
  1285. };
  1286. this.drag_end = function(e)
  1287. {
  1288. var list, model;
  1289. if (this.treelist)
  1290. this.treelist.drag_end();
  1291. // execute drag & drop action when mouse was released
  1292. if (list = this.message_list)
  1293. model = this.env.mailboxes;
  1294. else if (list = this.contact_list)
  1295. model = this.env.contactfolders;
  1296. if (this.drag_active && model && this.env.last_folder_target) {
  1297. var target = model[this.env.last_folder_target];
  1298. list.draglayer.hide();
  1299. if (this.contact_list) {
  1300. if (!this.contacts_drag_menu(e, target))
  1301. this.command('move', target);
  1302. }
  1303. else if (!this.drag_menu(e, target))
  1304. this.command('move', target);
  1305. }
  1306. this.drag_active = false;
  1307. this.env.last_folder_target = null;
  1308. };
  1309. this.drag_move = function(e)
  1310. {
  1311. if (this.gui_objects.folderlist) {
  1312. var drag_target, oldclass,
  1313. layerclass = 'draglayernormal',
  1314. mouse = rcube_event.get_mouse_pos(e);
  1315. if (this.contact_list && this.contact_list.draglayer)
  1316. oldclass = this.contact_list.draglayer.attr('class');
  1317. // mouse intersects a valid drop target on the treelist
  1318. if (this.treelist && (drag_target = this.treelist.intersects(mouse, true))) {
  1319. this.env.last_folder_target = drag_target;
  1320. layerclass = 'draglayer' + (this.check_droptarget(drag_target) > 1 ? 'copy' : 'normal');
  1321. }
  1322. else {
  1323. // Clear target, otherwise drag end will trigger move into last valid droptarget
  1324. this.env.last_folder_target = null;
  1325. }
  1326. if (layerclass != oldclass && this.contact_list && this.contact_list.draglayer)
  1327. this.contact_list.draglayer.attr('class', layerclass);
  1328. }
  1329. };
  1330. this.collapse_folder = function(name)
  1331. {
  1332. if (this.treelist)
  1333. this.treelist.toggle(name);
  1334. };
  1335. this.folder_collapsed = function(node)
  1336. {
  1337. var prefname = this.env.task == 'addressbook' ? 'collapsed_abooks' : 'collapsed_folders';
  1338. if (node.collapsed) {
  1339. this.env[prefname] = this.env[prefname] + '&'+urlencode(node.id)+'&';
  1340. // select the folder if one of its childs is currently selected
  1341. // don't select if it's virtual (#1488346)
  1342. if (!node.virtual && this.env.mailbox && this.env.mailbox.startsWith(name + this.env.delimiter))
  1343. this.command('list', name);
  1344. }
  1345. else {
  1346. var reg = new RegExp('&'+urlencode(node.id)+'&');
  1347. this.env[prefname] = this.env[prefname].replace(reg, '');
  1348. }
  1349. if (!this.drag_active) {
  1350. this.command('save-pref', { name: prefname, value: this.env[prefname] });
  1351. if (this.env.unread_counts)
  1352. this.set_unread_count_display(node.id, false);
  1353. }
  1354. };
  1355. // global mouse-click handler to cleanup some UI elements
  1356. this.doc_mouse_up = function(e)
  1357. {
  1358. var list, id, target = rcube_event.get_target(e);
  1359. // ignore event if jquery UI dialog is open
  1360. if ($(target).closest('.ui-dialog, .ui-widget-overlay').length)
  1361. return;
  1362. // remove focus from list widgets
  1363. if (window.rcube_list_widget && rcube_list_widget._instances.length) {
  1364. $.each(rcube_list_widget._instances, function(i,list){
  1365. if (list && !rcube_mouse_is_over(e, list.list.parentNode))
  1366. list.blur();
  1367. });
  1368. }
  1369. // reset 'pressed' buttons
  1370. if (this.buttons_sel) {
  1371. for (id in this.buttons_sel)
  1372. if (typeof id !== 'function')
  1373. this.button_out(this.buttons_sel[id], id);
  1374. this.buttons_sel = {};
  1375. }
  1376. // reset popup menus; delayed to have updated menu_stack data
  1377. setTimeout(function(e){
  1378. var obj, skip, config, id, i, parents = $(target).parents();
  1379. for (i = ref.menu_stack.length - 1; i >= 0; i--) {
  1380. id = ref.menu_stack[i];
  1381. obj = $('#' + id);
  1382. if (obj.is(':visible')
  1383. && target != obj.data('opener')
  1384. && target != obj.get(0) // check if scroll bar was clicked (#1489832)
  1385. && !parents.is(obj.data('opener'))
  1386. && id != skip
  1387. && (obj.attr('data-editable') != 'true' || !$(target).parents('#' + id).length)
  1388. && (obj.attr('data-sticky') != 'true' || !rcube_mouse_is_over(e, obj.get(0)))
  1389. ) {
  1390. ref.hide_menu(id, e);
  1391. }
  1392. skip = obj.data('parent');
  1393. }
  1394. }, 10);
  1395. };
  1396. // global keypress event handler
  1397. this.doc_keypress = function(e)
  1398. {
  1399. // Helper method to move focus to the next/prev active menu item
  1400. var focus_menu_item = function(dir) {
  1401. var obj, item, mod = dir < 0 ? 'prevAll' : 'nextAll', limit = dir < 0 ? 'last' : 'first';
  1402. if (ref.focused_menu && (obj = $('#'+ref.focused_menu))) {
  1403. item = obj.find(':focus').closest('li')[mod](':has(:not([aria-disabled=true]))').find('a,input')[limit]();
  1404. if (!item.length)
  1405. item = obj.find(':focus').closest('ul')[mod](':has(:not([aria-disabled=true]))').find('a,input')[limit]();
  1406. return item.focus().length;
  1407. }
  1408. return 0;
  1409. };
  1410. var target = e.target || {},
  1411. keyCode = rcube_event.get_keycode(e);
  1412. // save global reference for keyboard detection on click events in IE
  1413. rcube_event._last_keyboard_event = e;
  1414. if (e.keyCode != 27 && (!this.menu_keyboard_active || target.nodeName == 'TEXTAREA' || target.nodeName == 'SELECT')) {
  1415. return true;
  1416. }
  1417. switch (keyCode) {
  1418. case 38:
  1419. case 40:
  1420. case 63232: // "up", in safari keypress
  1421. case 63233: // "down", in safari keypress
  1422. focus_menu_item(keyCode == 38 || keyCode == 63232 ? -1 : 1);
  1423. return rcube_event.cancel(e);
  1424. case 9: // tab
  1425. if (this.focused_menu) {
  1426. var mod = rcube_event.get_modifier(e);
  1427. if (!focus_menu_item(mod == SHIFT_KEY ? -1 : 1)) {
  1428. this.hide_menu(this.focused_menu, e);
  1429. }
  1430. }
  1431. return rcube_event.cancel(e);
  1432. case 27: // esc
  1433. if (this.menu_stack.length)
  1434. this.hide_menu(this.menu_stack[this.menu_stack.length-1], e);
  1435. break;
  1436. }
  1437. return true;
  1438. }
  1439. this.msglist_select = function(list)
  1440. {
  1441. if (this.preview_timer)
  1442. clearTimeout(this.preview_timer);
  1443. if (this.preview_read_timer)
  1444. clearTimeout(this.preview_read_timer);
  1445. var selected = list.get_single_selection();
  1446. this.enable_command(this.env.message_commands, selected != null);
  1447. if (selected) {
  1448. // Hide certain command buttons when Drafts folder is selected
  1449. if (this.env.mailbox == this.env.drafts_mailbox)
  1450. this.enable_command('reply', 'reply-all', 'reply-list', 'forward', 'forward-attachment', 'forward-inline', false);
  1451. // Disable reply-list when List-Post header is not set
  1452. else {
  1453. var msg = this.env.messages[selected];
  1454. if (!msg.ml)
  1455. this.enable_command('reply-list', false);
  1456. }
  1457. }
  1458. // Multi-message commands
  1459. this.enable_command('delete', 'move', 'copy', 'mark', 'forward', 'forward-attachment', list.selection.length > 0);
  1460. // reset all-pages-selection
  1461. if (selected || (list.selection.length && list.selection.length != list.rowcount))
  1462. this.select_all_mode = false;
  1463. // start timer for message preview (wait for double click)
  1464. if (selected && this.env.contentframe && !list.multi_selecting && !this.dummy_select)
  1465. this.preview_timer = setTimeout(function() { ref.msglist_get_preview(); }, this.dblclick_time);
  1466. else if (this.env.contentframe)
  1467. this.show_contentframe(false);
  1468. };
  1469. // This allow as to re-select selected message and display it in preview frame
  1470. this.msglist_click = function(list)
  1471. {
  1472. if (list.multi_selecting || !this.env.contentframe)
  1473. return;
  1474. if (list.get_single_selection())
  1475. return;
  1476. var win = this.get_frame_window(this.env.contentframe);
  1477. if (win && win.location.href.indexOf(this.env.blankpage) >= 0) {
  1478. if (this.preview_timer)
  1479. clearTimeout(this.preview_timer);
  1480. if (this.preview_read_timer)
  1481. clearTimeout(this.preview_read_timer);
  1482. this.preview_timer = setTimeout(function() { ref.msglist_get_preview(); }, this.dblclick_time);
  1483. }
  1484. };
  1485. this.msglist_dbl_click = function(list)
  1486. {
  1487. if (this.preview_timer)
  1488. clearTimeout(this.preview_timer);
  1489. if (this.preview_read_timer)
  1490. clearTimeout(this.preview_read_timer);
  1491. var uid = list.get_single_selection();
  1492. if (uid && (this.env.messages[uid].mbox || this.env.mailbox) == this.env.drafts_mailbox)
  1493. this.open_compose_step({ _draft_uid: uid, _mbox: this.env.mailbox });
  1494. else if (uid)
  1495. this.show_message(uid, false, false);
  1496. };
  1497. this.msglist_keypress = function(list)
  1498. {
  1499. if (list.modkey == CONTROL_KEY)
  1500. return;
  1501. if (list.key_pressed == list.ENTER_KEY)
  1502. this.command('show');
  1503. else if (list.key_pressed == list.DELETE_KEY || list.key_pressed == list.BACKSPACE_KEY)
  1504. this.command('delete');
  1505. else if (list.key_pressed == 33)
  1506. this.command('previouspage');
  1507. else if (list.key_pressed == 34)
  1508. this.command('nextpage');
  1509. };
  1510. this.msglist_get_preview = function()
  1511. {
  1512. var uid = this.get_single_uid();
  1513. if (uid && this.env.contentframe && !this.drag_active)
  1514. this.show_message(uid, false, true);
  1515. else if (this.env.contentframe)
  1516. this.show_contentframe(false);
  1517. };
  1518. this.msglist_expand = function(row)
  1519. {
  1520. if (this.env.messages[row.uid])
  1521. this.env.messages[row.uid].expanded = row.expanded;
  1522. $(row.obj)[row.expanded?'addClass':'removeClass']('expanded');
  1523. };
  1524. this.msglist_set_coltypes = function(list)
  1525. {
  1526. var i, found, name, cols = list.thead.rows[0].cells;
  1527. this.env.listcols = [];
  1528. for (i=0; i<cols.length; i++)
  1529. if (cols[i].id && cols[i].id.startsWith('rcm')) {
  1530. name = cols[i].id.slice(3);
  1531. this.env.listcols.push(name);
  1532. }
  1533. if ((found = $.inArray('flag', this.env.listcols)) >= 0)
  1534. this.env.flagged_col = found;
  1535. if ((found = $.inArray('subject', this.env.listcols)) >= 0)
  1536. this.env.subject_col = found;
  1537. this.command('save-pref', { name: 'list_cols', value: this.env.listcols, session: 'list_attrib/columns' });
  1538. };
  1539. this.check_droptarget = function(id)
  1540. {
  1541. switch (this.task) {
  1542. case 'mail':
  1543. return (this.env.mailboxes[id]
  1544. && !this.env.mailboxes[id].virtual
  1545. && (this.env.mailboxes[id].id != this.env.mailbox || this.is_multifolder_listing())) ? 1 : 0;
  1546. case 'addressbook':
  1547. var target;
  1548. if (id != this.env.source && (target = this.env.contactfolders[id])) {
  1549. // droptarget is a group
  1550. if (target.type == 'group') {
  1551. if (target.id != this.env.group && !this.env.contactfolders[target.source].readonly) {
  1552. var is_other = this.env.selection_sources.length > 1 || $.inArray(target.source, this.env.selection_sources) == -1;
  1553. return !is_other || this.commands.move ? 1 : 2;
  1554. }
  1555. }
  1556. // droptarget is a (writable) addressbook and it's not the source
  1557. else if (!target.readonly && (this.env.selection_sources.length > 1 || $.inArray(id, this.env.selection_sources) == -1)) {
  1558. return this.commands.move ? 1 : 2;
  1559. }
  1560. }
  1561. }
  1562. return 0;
  1563. };
  1564. // open popup window
  1565. this.open_window = function(url, small, toolbar)
  1566. {
  1567. var wname = 'rcmextwin' + new Date().getTime();
  1568. url += (url.match(/\?/) ? '&' : '?') + '_extwin=1';
  1569. if (this.env.standard_windows)
  1570. var extwin = window.open(url, wname);
  1571. else {
  1572. var win = this.is_framed() ? parent.window : window,
  1573. page = $(win),
  1574. page_width = page.width(),
  1575. page_height = bw.mz ? $('body', win).height() : page.height(),
  1576. w = Math.min(small ? this.env.popup_width_small : this.env.popup_width, page_width),
  1577. h = page_height, // always use same height
  1578. l = (win.screenLeft || win.screenX) + 20,
  1579. t = (win.screenTop || win.screenY) + 20,
  1580. extwin = window.open(url, wname,
  1581. 'width='+w+',height='+h+',top='+t+',left='+l+',resizable=yes,location=no,scrollbars=yes'
  1582. +(toolbar ? ',toolbar=yes,menubar=yes,status=yes' : ',toolbar=no,menubar=no,status=no'));
  1583. }
  1584. // detect popup blocker (#1489618)
  1585. // don't care this might not work with all browsers
  1586. if (!extwin || extwin.closed) {
  1587. this.display_message(this.get_label('windowopenerror'), 'warning');
  1588. return;
  1589. }
  1590. // write loading... message to empty windows
  1591. if (!url && extwin.document) {
  1592. extwin.document.write('<html><body>' + this.get_label('loading') + '</body></html>');
  1593. }
  1594. // allow plugins to grab the window reference (#1489413)
  1595. this.triggerEvent('openwindow', { url:url, handle:extwin });
  1596. // focus window, delayed to bring to front
  1597. setTimeout(function() { extwin && extwin.focus(); }, 10);
  1598. return extwin;
  1599. };
  1600. /*********************************************************/
  1601. /********* (message) list functionality *********/
  1602. /*********************************************************/
  1603. this.init_message_row = function(row)
  1604. {
  1605. var i, fn = {}, uid = row.uid,
  1606. status_icon = (this.env.status_col != null ? 'status' : 'msg') + 'icn' + row.id;
  1607. if (uid && this.env.messages[uid])
  1608. $.extend(row, this.env.messages[uid]);
  1609. // set eventhandler to status icon
  1610. if (row.icon = document.getElementById(status_icon)) {
  1611. fn.icon = function(e) { ref.command('toggle_status', uid); };
  1612. }
  1613. // save message icon position too
  1614. if (this.env.status_col != null)
  1615. row.msgicon = document.getElementById('msgicn'+row.id);
  1616. else
  1617. row.msgicon = row.icon;
  1618. // set eventhandler to flag icon
  1619. if (this.env.flagged_col != null && (row.flagicon = document.getElementById('flagicn'+row.id))) {
  1620. fn.flagicon = function(e) { ref.command('toggle_flag', uid); };
  1621. }
  1622. // set event handler to thread expand/collapse icon
  1623. if (!row.depth && row.has_children && (row.expando = document.getElementById('rcmexpando'+row.id))) {
  1624. fn.expando = function(e) { ref.expand_message_row(e, uid); };
  1625. }
  1626. // attach events
  1627. $.each(fn, function(i, f) {
  1628. row[i].onclick = function(e) { f(e); return rcube_event.cancel(e); };
  1629. if (bw.touch) {
  1630. row[i].addEventListener('touchend', function(e) {
  1631. if (e.changedTouches.length == 1) {
  1632. f(e);
  1633. return rcube_event.cancel(e);
  1634. }
  1635. }, false);
  1636. }
  1637. });
  1638. this.triggerEvent('insertrow', { uid:uid, row:row });
  1639. };
  1640. // create a table row in the message list
  1641. this.add_message_row = function(uid, cols, flags, attop)
  1642. {
  1643. if (!this.gui_objects.messagelist || !this.message_list)
  1644. return false;
  1645. // Prevent from adding messages from different folder (#1487752)
  1646. if (flags.mbox != this.env.mailbox && !flags.skip_mbox_check)
  1647. return false;
  1648. if (!this.env.messages[uid])
  1649. this.env.messages[uid] = {};
  1650. // merge flags over local message object
  1651. $.extend(this.env.messages[uid], {
  1652. deleted: flags.deleted?1:0,
  1653. replied: flags.answered?1:0,
  1654. unread: !flags.seen?1:0,
  1655. forwarded: flags.forwarded?1:0,
  1656. flagged: flags.flagged?1:0,
  1657. has_children: flags.has_children?1:0,
  1658. depth: flags.depth?flags.depth:0,
  1659. unread_children: flags.unread_children?flags.unread_children:0,
  1660. parent_uid: flags.parent_uid?flags.parent_uid:0,
  1661. selected: this.select_all_mode || this.message_list.in_selection(uid),
  1662. ml: flags.ml?1:0,
  1663. ctype: flags.ctype,
  1664. mbox: flags.mbox,
  1665. // flags from plugins
  1666. flags: flags.extra_flags
  1667. });
  1668. var c, n, col, html, css_class, label, status_class = '', status_label = '',
  1669. tree = '', expando = '',
  1670. list = this.message_list,
  1671. rows = list.rows,
  1672. message = this.env.messages[uid],
  1673. msg_id = this.html_identifier(uid,true),
  1674. row_class = 'message'
  1675. + (!flags.seen ? ' unread' : '')
  1676. + (flags.deleted ? ' deleted' : '')
  1677. + (flags.flagged ? ' flagged' : '')
  1678. + (message.selected ? ' selected' : ''),
  1679. row = { cols:[], style:{}, id:'rcmrow'+msg_id, uid:uid };
  1680. // message status icons
  1681. css_class = 'msgicon';
  1682. if (this.env.status_col === null) {
  1683. css_class += ' status';
  1684. if (flags.deleted) {
  1685. status_class += ' deleted';
  1686. status_label += this.get_label('deleted') + ' ';
  1687. }
  1688. else if (!flags.seen) {
  1689. status_class += ' unread';
  1690. status_label += this.get_label('unread') + ' ';
  1691. }
  1692. else if (flags.unread_children > 0) {
  1693. status_class += ' unreadchildren';
  1694. }
  1695. }
  1696. if (flags.answered) {
  1697. status_class += ' replied';
  1698. status_label += this.get_label('replied') + ' ';
  1699. }
  1700. if (flags.forwarded) {
  1701. status_class += ' forwarded';
  1702. status_label += this.get_label('replied') + ' ';
  1703. }
  1704. // update selection
  1705. if (message.selected && !list.in_selection(uid))
  1706. list.selection.push(uid);
  1707. // threads
  1708. if (this.env.threading) {
  1709. if (message.depth) {
  1710. // This assumes that div width is hardcoded to 15px,
  1711. tree += '<span id="rcmtab' + msg_id + '" class="branch" style="width:' + (message.depth * 15) + 'px;">&nbsp;&nbsp;</span>';
  1712. if ((rows[message.parent_uid] && rows[message.parent_uid].expanded === false)
  1713. || ((this.env.autoexpand_threads == 0 || this.env.autoexpand_threads == 2) &&
  1714. (!rows[message.parent_uid] || !rows[message.parent_uid].expanded))
  1715. ) {
  1716. row.style.display = 'none';
  1717. message.expanded = false;
  1718. }
  1719. else
  1720. message.expanded = true;
  1721. row_class += ' thread expanded';
  1722. }
  1723. else if (message.has_children) {
  1724. if (message.expanded === undefined && (this.env.autoexpand_threads == 1 || (this.env.autoexpand_threads == 2 && message.unread_children))) {
  1725. message.expanded = true;
  1726. }
  1727. expando = '<div id="rcmexpando' + row.id + '" class="' + (message.expanded ? 'expanded' : 'collapsed') + '">&nbsp;&nbsp;</div>';
  1728. row_class += ' thread' + (message.expanded? ' expanded' : '');
  1729. }
  1730. if (flags.unread_children && flags.seen && !message.expanded)
  1731. row_class += ' unroot';
  1732. }
  1733. tree += '<span id="msgicn'+row.id+'" class="'+css_class+status_class+'" title="'+status_label+'"></span>';
  1734. row.className = row_class;
  1735. // build subject link
  1736. if (cols.subject) {
  1737. var action = flags.mbox == this.env.drafts_mailbox ? 'compose' : 'show',
  1738. uid_param = flags.mbox == this.env.drafts_mailbox ? '_draft_uid' : '_uid',
  1739. query = { _mbox: flags.mbox };
  1740. query[uid_param] = uid;
  1741. cols.subject = '<a href="' + this.url(action, query) + '" onclick="return rcube_event.keyboard_only(event)"' +
  1742. ' onmouseover="rcube_webmail.long_subject_title(this,'+(message.depth+1)+')" tabindex="-1"><span>'+cols.subject+'</span></a>';
  1743. }
  1744. // add each submitted col
  1745. for (n in this.env.listcols) {
  1746. c = this.env.listcols[n];
  1747. col = {className: String(c).toLowerCase(), events:{}};
  1748. if (this.env.coltypes[c] && this.env.coltypes[c].hidden) {
  1749. col.className += ' hidden';
  1750. }
  1751. if (c == 'flag') {
  1752. css_class = (flags.flagged ? 'flagged' : 'unflagged');
  1753. label = this.get_label(css_class);
  1754. html = '<span id="flagicn'+row.id+'" class="'+css_class+'" title="'+label+'"></span>';
  1755. }
  1756. else if (c == 'attachment') {
  1757. label = this.get_label('withattachment');
  1758. if (flags.attachmentClass)
  1759. html = '<span class="'+flags.attachmentClass+'" title="'+label+'"></span>';
  1760. else if (/application\/|multipart\/(m|signed)/.test(flags.ctype))
  1761. html = '<span class="attachment" title="'+label+'"></span>';
  1762. else if (/multipart\/report/.test(flags.ctype))
  1763. html = '<span class="report"></span>';
  1764. else
  1765. html = '&nbsp;';
  1766. }
  1767. else if (c == 'status') {
  1768. label = '';
  1769. if (flags.deleted) {
  1770. css_class = 'deleted';
  1771. label = this.get_label('deleted');
  1772. }
  1773. else if (!flags.seen) {
  1774. css_class = 'unread';
  1775. label = this.get_label('unread');
  1776. }
  1777. else if (flags.unread_children > 0) {
  1778. css_class = 'unreadchildren';
  1779. }
  1780. else
  1781. css_class = 'msgicon';
  1782. html = '<span id="statusicn'+row.id+'" class="'+css_class+status_class+'" title="'+label+'"></span>';
  1783. }
  1784. else if (c == 'threads')
  1785. html = expando;
  1786. else if (c == 'subject') {
  1787. if (bw.ie)
  1788. col.events.mouseover = function() { rcube_webmail.long_subject_title_ex(this); };
  1789. html = tree + cols[c];
  1790. }
  1791. else if (c == 'priority') {
  1792. if (flags.prio > 0 && flags.prio < 6) {
  1793. label = this.get_label('priority') + ' ' + flags.prio;
  1794. html = '<span class="prio'+flags.prio+'" title="'+label+'"></span>';
  1795. }
  1796. else
  1797. html = '&nbsp;';
  1798. }
  1799. else if (c == 'folder') {
  1800. html = '<span onmouseover="rcube_webmail.long_subject_title(this)">' + cols[c] + '<span>';
  1801. }
  1802. else
  1803. html = cols[c];
  1804. col.innerHTML = html;
  1805. row.cols.push(col);
  1806. }
  1807. list.insert_row(row, attop);
  1808. // remove 'old' row
  1809. if (attop && this.env.pagesize && list.rowcount > this.env.pagesize) {
  1810. var uid = list.get_last_row();
  1811. list.remove_row(uid);
  1812. list.clear_selection(uid);
  1813. }
  1814. };
  1815. this.set_list_sorting = function(sort_col, sort_order)
  1816. {
  1817. // set table header class
  1818. $('#rcm'+this.env.sort_col).removeClass('sorted'+(this.env.sort_order.toUpperCase()));
  1819. if (sort_col)
  1820. $('#rcm'+sort_col).addClass('sorted'+sort_order);
  1821. this.env.sort_col = sort_col;
  1822. this.env.sort_order = sort_order;
  1823. };
  1824. this.set_list_options = function(cols, sort_col, sort_order, threads)
  1825. {
  1826. var update, post_data = {};
  1827. if (sort_col === undefined)
  1828. sort_col = this.env.sort_col;
  1829. if (!sort_order)
  1830. sort_order = this.env.sort_order;
  1831. if (this.env.sort_col != sort_col || this.env.sort_order != sort_order) {
  1832. update = 1;
  1833. this.set_list_sorting(sort_col, sort_order);
  1834. }
  1835. if (this.env.threading != threads) {
  1836. update = 1;
  1837. post_data._threads = threads;
  1838. }
  1839. if (cols && cols.length) {
  1840. // make sure new columns are added at the end of the list
  1841. var i, idx, name, newcols = [], oldcols = this.env.listcols;
  1842. for (i=0; i<oldcols.length; i++) {
  1843. name = oldcols[i];
  1844. idx = $.inArray(name, cols);
  1845. if (idx != -1) {
  1846. newcols.push(name);
  1847. delete cols[idx];
  1848. }
  1849. }
  1850. for (i=0; i<cols.length; i++)
  1851. if (cols[i])
  1852. newcols.push(cols[i]);
  1853. if (newcols.join() != oldcols.join()) {
  1854. update = 1;
  1855. post_data._cols = newcols.join(',');
  1856. }
  1857. }
  1858. if (update)
  1859. this.list_mailbox('', '', sort_col+'_'+sort_order, post_data);
  1860. };
  1861. // when user double-clicks on a row
  1862. this.show_message = function(id, safe, preview)
  1863. {
  1864. if (!id)
  1865. return;
  1866. var win, target = window,
  1867. action = preview ? 'preview': 'show',
  1868. url = '&_action='+action+'&_uid='+id+'&_mbox='+urlencode(this.get_message_mailbox(id));
  1869. if (preview && (win = this.get_frame_window(this.env.contentframe))) {
  1870. target = win;
  1871. url += '&_framed=1';
  1872. }
  1873. if (safe)
  1874. url += '&_safe=1';
  1875. // also send search request to get the right messages
  1876. if (this.env.search_request)
  1877. url += '&_search='+this.env.search_request;
  1878. // add browser capabilities, so we can properly handle attachments
  1879. url += '&_caps='+urlencode(this.browser_capabilities());
  1880. if (this.env.extwin)
  1881. url += '&_extwin=1';
  1882. if (preview && String(target.location.href).indexOf(url) >= 0) {
  1883. this.show_contentframe(true);
  1884. }
  1885. else {
  1886. if (!preview && this.env.message_extwin && !this.env.extwin)
  1887. this.open_window(this.env.comm_path+url, true);
  1888. else
  1889. this.location_href(this.env.comm_path+url, target, true);
  1890. // mark as read and change mbox unread counter
  1891. if (preview && this.message_list && this.message_list.rows[id] && this.message_list.rows[id].unread && this.env.preview_pane_mark_read > 0) {
  1892. this.preview_read_timer = setTimeout(function() {
  1893. ref.set_unread_message(id, ref.env.mailbox);
  1894. ref.http_post('mark', {_uid: id, _flag: 'read', _quiet: 1});
  1895. }, this.env.preview_pane_mark_read * 1000);
  1896. }
  1897. }
  1898. };
  1899. // update message status and unread counter after marking a message as read
  1900. this.set_unread_message = function(id, folder)
  1901. {
  1902. var self = this;
  1903. // find window with messages list
  1904. if (!self.message_list)
  1905. self = self.opener();
  1906. if (!self && window.parent)
  1907. self = parent.rcmail;
  1908. if (!self || !self.message_list)
  1909. return;
  1910. // this may fail in multifolder mode
  1911. if (self.set_message(id, 'unread', false) === false)
  1912. self.set_message(id + '-' + folder, 'unread', false);
  1913. if (self.env.unread_counts[folder] > 0) {
  1914. self.env.unread_counts[folder] -= 1;
  1915. self.set_unread_count(folder, self.env.unread_counts[folder], folder == 'INBOX' && !self.is_multifolder_listing());
  1916. }
  1917. };
  1918. this.show_contentframe = function(show)
  1919. {
  1920. var frame, win, name = this.env.contentframe;
  1921. if (name && (frame = this.get_frame_element(name))) {
  1922. if (!show && (win = this.get_frame_window(name))) {
  1923. if (win.location.href.indexOf(this.env.blankpage) < 0) {
  1924. if (win.stop)
  1925. win.stop();
  1926. else // IE
  1927. win.document.execCommand('Stop');
  1928. win.location.href = this.env.blankpage;
  1929. }
  1930. }
  1931. else if (!bw.safari && !bw.konq)
  1932. $(frame)[show ? 'show' : 'hide']();
  1933. }
  1934. if (!show && this.env.frame_lock)
  1935. this.set_busy(false, null, this.env.frame_lock);
  1936. };
  1937. this.get_frame_element = function(id)
  1938. {
  1939. var frame;
  1940. if (id && (frame = document.getElementById(id)))
  1941. return frame;
  1942. };
  1943. this.get_frame_window = function(id)
  1944. {
  1945. var frame = this.get_frame_element(id);
  1946. if (frame && frame.name && window.frames)
  1947. return window.frames[frame.name];
  1948. };
  1949. this.lock_frame = function()
  1950. {
  1951. if (!this.env.frame_lock)
  1952. (this.is_framed() ? parent.rcmail : this).env.frame_lock = this.set_busy(true, 'loading');
  1953. };
  1954. // list a specific page
  1955. this.list_page = function(page)
  1956. {
  1957. if (page == 'next')
  1958. page = this.env.current_page+1;
  1959. else if (page == 'last')
  1960. page = this.env.pagecount;
  1961. else if (page == 'prev' && this.env.current_page > 1)
  1962. page = this.env.current_page-1;
  1963. else if (page == 'first' && this.env.current_page > 1)
  1964. page = 1;
  1965. if (page > 0 && page <= this.env.pagecount) {
  1966. this.env.current_page = page;
  1967. if (this.task == 'addressbook' || this.contact_list)
  1968. this.list_contacts(this.env.source, this.env.group, page);
  1969. else if (this.task == 'mail')
  1970. this.list_mailbox(this.env.mailbox, page);
  1971. }
  1972. };
  1973. // sends request to check for recent messages
  1974. this.checkmail = function()
  1975. {
  1976. var lock = this.set_busy(true, 'checkingmail'),
  1977. params = this.check_recent_params();
  1978. this.http_post('check-recent', params, lock);
  1979. };
  1980. // list messages of a specific mailbox using filter
  1981. this.filter_mailbox = function(filter)
  1982. {
  1983. var lock = this.set_busy(true, 'searching');
  1984. this.clear_message_list();
  1985. // reset vars
  1986. this.env.current_page = 1;
  1987. this.env.search_filter = filter;
  1988. this.http_request('search', this.search_params(false, filter), lock);
  1989. };
  1990. // reload the current message listing
  1991. this.refresh_list = function()
  1992. {
  1993. this.list_mailbox(this.env.mailbox, this.env.current_page || 1, null, { _clear:1 }, true);
  1994. if (this.message_list)
  1995. this.message_list.clear_selection();
  1996. };
  1997. // list messages of a specific mailbox
  1998. this.list_mailbox = function(mbox, page, sort, url, update_only)
  1999. {
  2000. var win, target = window;
  2001. if (typeof url != 'object')
  2002. url = {};
  2003. if (!mbox)
  2004. mbox = this.env.mailbox ? this.env.mailbox : 'INBOX';
  2005. // add sort to url if set
  2006. if (sort)
  2007. url._sort = sort;
  2008. // also send search request to get the right messages
  2009. if (this.env.search_request)
  2010. url._search = this.env.search_request;
  2011. // set page=1 if changeing to another mailbox
  2012. if (this.env.mailbox != mbox) {
  2013. page = 1;
  2014. this.env.current_page = page;
  2015. this.select_all_mode = false;
  2016. }
  2017. if (!update_only) {
  2018. // unselect selected messages and clear the list and message data
  2019. this.clear_message_list();
  2020. if (mbox != this.env.mailbox || (mbox == this.env.mailbox && !page && !sort))
  2021. url._refresh = 1;
  2022. this.select_folder(mbox, '', true);
  2023. this.unmark_folder(mbox, 'recent', '', true);
  2024. this.env.mailbox = mbox;
  2025. }
  2026. // load message list remotely
  2027. if (this.gui_objects.messagelist) {
  2028. this.list_mailbox_remote(mbox, page, url);
  2029. return;
  2030. }
  2031. if (win = this.get_frame_window(this.env.contentframe)) {
  2032. target = win;
  2033. url._framed = 1;
  2034. }
  2035. if (this.env.uid)
  2036. url._uid = this.env.uid;
  2037. // load message list to target frame/window
  2038. if (mbox) {
  2039. this.set_busy(true, 'loading');
  2040. url._mbox = mbox;
  2041. if (page)
  2042. url._page = page;
  2043. this.location_href(url, target);
  2044. }
  2045. };
  2046. this.clear_message_list = function()
  2047. {
  2048. this.env.messages = {};
  2049. this.show_contentframe(false);
  2050. if (this.message_list)
  2051. this.message_list.clear(true);
  2052. };
  2053. // send remote request to load message list
  2054. this.list_mailbox_remote = function(mbox, page, url)
  2055. {
  2056. var lock = this.set_busy(true, 'loading');
  2057. if (typeof url != 'object')
  2058. url = {};
  2059. url._mbox = mbox;
  2060. if (page)
  2061. url._page = page;
  2062. this.http_request('list', url, lock);
  2063. this.update_state({ _mbox: mbox, _page: (page && page > 1 ? page : null) });
  2064. };
  2065. // removes messages that doesn't exists from list selection array
  2066. this.update_selection = function()
  2067. {
  2068. var selected = this.message_list.selection,
  2069. rows = this.message_list.rows,
  2070. i, selection = [];
  2071. for (i in selected)
  2072. if (rows[selected[i]])
  2073. selection.push(selected[i]);
  2074. this.message_list.selection = selection;
  2075. };
  2076. // expand all threads with unread children
  2077. this.expand_unread = function()
  2078. {
  2079. var r, tbody = this.gui_objects.messagelist.tBodies[0],
  2080. new_row = tbody.firstChild;
  2081. while (new_row) {
  2082. if (new_row.nodeType == 1 && (r = this.message_list.rows[new_row.uid]) && r.unread_children) {
  2083. this.message_list.expand_all(r);
  2084. this.set_unread_children(r.uid);
  2085. }
  2086. new_row = new_row.nextSibling;
  2087. }
  2088. return false;
  2089. };
  2090. // thread expanding/collapsing handler
  2091. this.expand_message_row = function(e, uid)
  2092. {
  2093. var row = this.message_list.rows[uid];
  2094. // handle unread_children mark
  2095. row.expanded = !row.expanded;
  2096. this.set_unread_children(uid);
  2097. row.expanded = !row.expanded;
  2098. this.message_list.expand_row(e, uid);
  2099. };
  2100. // message list expanding
  2101. this.expand_threads = function()
  2102. {
  2103. if (!this.env.threading || !this.env.autoexpand_threads || !this.message_list)
  2104. return;
  2105. switch (this.env.autoexpand_threads) {
  2106. case 2: this.expand_unread(); break;
  2107. case 1: this.message_list.expand_all(); break;
  2108. }
  2109. };
  2110. // Initializes threads indicators/expanders after list update
  2111. this.init_threads = function(roots, mbox)
  2112. {
  2113. // #1487752
  2114. if (mbox && mbox != this.env.mailbox)
  2115. return false;
  2116. for (var n=0, len=roots.length; n<len; n++)
  2117. this.add_tree_icons(roots[n]);
  2118. this.expand_threads();
  2119. };
  2120. // adds threads tree icons to the list (or specified thread)
  2121. this.add_tree_icons = function(root)
  2122. {
  2123. var i, l, r, n, len, pos, tmp = [], uid = [],
  2124. row, rows = this.message_list.rows;
  2125. if (root)
  2126. row = rows[root] ? rows[root].obj : null;
  2127. else
  2128. row = this.message_list.tbody.firstChild;
  2129. while (row) {
  2130. if (row.nodeType == 1 && (r = rows[row.uid])) {
  2131. if (r.depth) {
  2132. for (i=tmp.length-1; i>=0; i--) {
  2133. len = tmp[i].length;
  2134. if (len > r.depth) {
  2135. pos = len - r.depth;
  2136. if (!(tmp[i][pos] & 2))
  2137. tmp[i][pos] = tmp[i][pos] ? tmp[i][pos]+2 : 2;
  2138. }
  2139. else if (len == r.depth) {
  2140. if (!(tmp[i][0] & 2))
  2141. tmp[i][0] += 2;
  2142. }
  2143. if (r.depth > len)
  2144. break;
  2145. }
  2146. tmp.push(new Array(r.depth));
  2147. tmp[tmp.length-1][0] = 1;
  2148. uid.push(r.uid);
  2149. }
  2150. else {
  2151. if (tmp.length) {
  2152. for (i in tmp) {
  2153. this.set_tree_icons(uid[i], tmp[i]);
  2154. }
  2155. tmp = [];
  2156. uid = [];
  2157. }
  2158. if (root && row != rows[root].obj)
  2159. break;
  2160. }
  2161. }
  2162. row = row.nextSibling;
  2163. }
  2164. if (tmp.length) {
  2165. for (i in tmp) {
  2166. this.set_tree_icons(uid[i], tmp[i]);
  2167. }
  2168. }
  2169. };
  2170. // adds tree icons to specified message row
  2171. this.set_tree_icons = function(uid, tree)
  2172. {
  2173. var i, divs = [], html = '', len = tree.length;
  2174. for (i=0; i<len; i++) {
  2175. if (tree[i] > 2)
  2176. divs.push({'class': 'l3', width: 15});
  2177. else if (tree[i] > 1)
  2178. divs.push({'class': 'l2', width: 15});
  2179. else if (tree[i] > 0)
  2180. divs.push({'class': 'l1', width: 15});
  2181. // separator div
  2182. else if (divs.length && !divs[divs.length-1]['class'])
  2183. divs[divs.length-1].width += 15;
  2184. else
  2185. divs.push({'class': null, width: 15});
  2186. }
  2187. for (i=divs.length-1; i>=0; i--) {
  2188. if (divs[i]['class'])
  2189. html += '<div class="tree '+divs[i]['class']+'" />';
  2190. else
  2191. html += '<div style="width:'+divs[i].width+'px" />';
  2192. }
  2193. if (html)
  2194. $('#rcmtab'+this.html_identifier(uid, true)).html(html);
  2195. };
  2196. // update parent in a thread
  2197. this.update_thread_root = function(uid, flag)
  2198. {
  2199. if (!this.env.threading)
  2200. return;
  2201. var root = this.message_list.find_root(uid);
  2202. if (uid == root)
  2203. return;
  2204. var p = this.message_list.rows[root];
  2205. if (flag == 'read' && p.unread_children) {
  2206. p.unread_children--;
  2207. }
  2208. else if (flag == 'unread' && p.has_children) {
  2209. // unread_children may be undefined
  2210. p.unread_children = p.unread_children ? p.unread_children + 1 : 1;
  2211. }
  2212. else {
  2213. return;
  2214. }
  2215. this.set_message_icon(root);
  2216. this.set_unread_children(root);
  2217. };
  2218. // update thread indicators for all messages in a thread below the specified message
  2219. // return number of removed/added root level messages
  2220. this.update_thread = function (uid)
  2221. {
  2222. if (!this.env.threading)
  2223. return 0;
  2224. var r, parent, count = 0,
  2225. rows = this.message_list.rows,
  2226. row = rows[uid],
  2227. depth = rows[uid].depth,
  2228. roots = [];
  2229. if (!row.depth) // root message: decrease roots count
  2230. count--;
  2231. else if (row.unread) {
  2232. // update unread_children for thread root
  2233. parent = this.message_list.find_root(uid);
  2234. rows[parent].unread_children--;
  2235. this.set_unread_children(parent);
  2236. }
  2237. parent = row.parent_uid;
  2238. // childrens
  2239. row = row.obj.nextSibling;
  2240. while (row) {
  2241. if (row.nodeType == 1 && (r = rows[row.uid])) {
  2242. if (!r.depth || r.depth <= depth)
  2243. break;
  2244. r.depth--; // move left
  2245. // reset width and clear the content of a tab, icons will be added later
  2246. $('#rcmtab'+r.id).width(r.depth * 15).html('');
  2247. if (!r.depth) { // a new root
  2248. count++; // increase roots count
  2249. r.parent_uid = 0;
  2250. if (r.has_children) {
  2251. // replace 'leaf' with 'collapsed'
  2252. $('#'+r.id+' .leaf:first')
  2253. .attr('id', 'rcmexpando' + r.id)
  2254. .attr('class', (r.obj.style.display != 'none' ? 'expanded' : 'collapsed'))
  2255. .bind('mousedown', {uid: r.uid},
  2256. function(e) { return ref.expand_message_row(e, e.data.uid); });
  2257. r.unread_children = 0;
  2258. roots.push(r);
  2259. }
  2260. // show if it was hidden
  2261. if (r.obj.style.display == 'none')
  2262. $(r.obj).show();
  2263. }
  2264. else {
  2265. if (r.depth == depth)
  2266. r.parent_uid = parent;
  2267. if (r.unread && roots.length)
  2268. roots[roots.length-1].unread_children++;
  2269. }
  2270. }
  2271. row = row.nextSibling;
  2272. }
  2273. // update unread_children for roots
  2274. for (r=0; r<roots.length; r++)
  2275. this.set_unread_children(roots[r].uid);
  2276. return count;
  2277. };
  2278. this.delete_excessive_thread_rows = function()
  2279. {
  2280. var rows = this.message_list.rows,
  2281. tbody = this.message_list.tbody,
  2282. row = tbody.firstChild,
  2283. cnt = this.env.pagesize + 1;
  2284. while (row) {
  2285. if (row.nodeType == 1 && (r = rows[row.uid])) {
  2286. if (!r.depth && cnt)
  2287. cnt--;
  2288. if (!cnt)
  2289. this.message_list.remove_row(row.uid);
  2290. }
  2291. row = row.nextSibling;
  2292. }
  2293. };
  2294. // set message icon
  2295. this.set_message_icon = function(uid)
  2296. {
  2297. var css_class, label = '',
  2298. row = this.message_list.rows[uid];
  2299. if (!row)
  2300. return false;
  2301. if (row.icon) {
  2302. css_class = 'msgicon';
  2303. if (row.deleted) {
  2304. css_class += ' deleted';
  2305. label += this.get_label('deleted') + ' ';
  2306. }
  2307. else if (row.unread) {
  2308. css_class += ' unread';
  2309. label += this.get_label('unread') + ' ';
  2310. }
  2311. else if (row.unread_children)
  2312. css_class += ' unreadchildren';
  2313. if (row.msgicon == row.icon) {
  2314. if (row.replied) {
  2315. css_class += ' replied';
  2316. label += this.get_label('replied') + ' ';
  2317. }
  2318. if (row.forwarded) {
  2319. css_class += ' forwarded';
  2320. label += this.get_label('forwarded') + ' ';
  2321. }
  2322. css_class += ' status';
  2323. }
  2324. $(row.icon).attr('class', css_class).attr('title', label);
  2325. }
  2326. if (row.msgicon && row.msgicon != row.icon) {
  2327. label = '';
  2328. css_class = 'msgicon';
  2329. if (!row.unread && row.unread_children) {
  2330. css_class += ' unreadchildren';
  2331. }
  2332. if (row.replied) {
  2333. css_class += ' replied';
  2334. label += this.get_label('replied') + ' ';
  2335. }
  2336. if (row.forwarded) {
  2337. css_class += ' forwarded';
  2338. label += this.get_label('forwarded') + ' ';
  2339. }
  2340. $(row.msgicon).attr('class', css_class).attr('title', label);
  2341. }
  2342. if (row.flagicon) {
  2343. css_class = (row.flagged ? 'flagged' : 'unflagged');
  2344. label = this.get_label(css_class);
  2345. $(row.flagicon).attr('class', css_class)
  2346. .attr('aria-label', label)
  2347. .attr('title', label);
  2348. }
  2349. };
  2350. // set message status
  2351. this.set_message_status = function(uid, flag, status)
  2352. {
  2353. var row = this.message_list.rows[uid];
  2354. if (!row)
  2355. return false;
  2356. if (flag == 'unread') {
  2357. if (row.unread != status)
  2358. this.update_thread_root(uid, status ? 'unread' : 'read');
  2359. }
  2360. if ($.inArray(flag, ['unread', 'deleted', 'replied', 'forwarded', 'flagged']) > -1)
  2361. row[flag] = status;
  2362. };
  2363. // set message row status, class and icon
  2364. this.set_message = function(uid, flag, status)
  2365. {
  2366. var row = this.message_list && this.message_list.rows[uid];
  2367. if (!row)
  2368. return false;
  2369. if (flag)
  2370. this.set_message_status(uid, flag, status);
  2371. if ($.inArray(flag, ['unread', 'deleted', 'flagged']) > -1)
  2372. $(row.obj)[row[flag] ? 'addClass' : 'removeClass'](flag);
  2373. this.set_unread_children(uid);
  2374. this.set_message_icon(uid);
  2375. };
  2376. // sets unroot (unread_children) class of parent row
  2377. this.set_unread_children = function(uid)
  2378. {
  2379. var row = this.message_list.rows[uid];
  2380. if (row.parent_uid)
  2381. return;
  2382. if (!row.unread && row.unread_children && !row.expanded)
  2383. $(row.obj).addClass('unroot');
  2384. else
  2385. $(row.obj).removeClass('unroot');
  2386. };
  2387. // copy selected messages to the specified mailbox
  2388. this.copy_messages = function(mbox, event)
  2389. {
  2390. if (mbox && typeof mbox === 'object')
  2391. mbox = mbox.id;
  2392. else if (!mbox)
  2393. return this.folder_selector(event, function(folder) { ref.command('copy', folder); });
  2394. // exit if current or no mailbox specified
  2395. if (!mbox || mbox == this.env.mailbox)
  2396. return;
  2397. var post_data = this.selection_post_data({_target_mbox: mbox});
  2398. // exit if selection is empty
  2399. if (!post_data._uid)
  2400. return;
  2401. // send request to server
  2402. this.http_post('copy', post_data, this.display_message(this.get_label('copyingmessage'), 'loading'));
  2403. };
  2404. // move selected messages to the specified mailbox
  2405. this.move_messages = function(mbox, event)
  2406. {
  2407. if (mbox && typeof mbox === 'object')
  2408. mbox = mbox.id;
  2409. else if (!mbox)
  2410. return this.folder_selector(event, function(folder) { ref.command('move', folder); });
  2411. // exit if current or no mailbox specified
  2412. if (!mbox || (mbox == this.env.mailbox && !this.is_multifolder_listing()))
  2413. return;
  2414. var lock = false, post_data = this.selection_post_data({_target_mbox: mbox});
  2415. // exit if selection is empty
  2416. if (!post_data._uid)
  2417. return;
  2418. // show wait message
  2419. if (this.env.action == 'show')
  2420. lock = this.set_busy(true, 'movingmessage');
  2421. else
  2422. this.show_contentframe(false);
  2423. // Hide message command buttons until a message is selected
  2424. this.enable_command(this.env.message_commands, false);
  2425. this._with_selected_messages('move', post_data, lock);
  2426. };
  2427. // delete selected messages from the current mailbox
  2428. this.delete_messages = function(event)
  2429. {
  2430. var list = this.message_list, trash = this.env.trash_mailbox;
  2431. // if config is set to flag for deletion
  2432. if (this.env.flag_for_deletion) {
  2433. this.mark_message('delete');
  2434. return false;
  2435. }
  2436. // if there isn't a defined trash mailbox or we are in it
  2437. else if (!trash || this.env.mailbox == trash)
  2438. this.permanently_remove_messages();
  2439. // we're in Junk folder and delete_junk is enabled
  2440. else if (this.env.delete_junk && this.env.junk_mailbox && this.env.mailbox == this.env.junk_mailbox)
  2441. this.permanently_remove_messages();
  2442. // if there is a trash mailbox defined and we're not currently in it
  2443. else {
  2444. // if shift was pressed delete it immediately
  2445. if ((list && list.modkey == SHIFT_KEY) || (event && rcube_event.get_modifier(event) == SHIFT_KEY)) {
  2446. if (confirm(this.get_label('deletemessagesconfirm')))
  2447. this.permanently_remove_messages();
  2448. }
  2449. else
  2450. this.move_messages(trash);
  2451. }
  2452. return true;
  2453. };
  2454. // delete the selected messages permanently
  2455. this.permanently_remove_messages = function()
  2456. {
  2457. var post_data = this.selection_post_data();
  2458. // exit if selection is empty
  2459. if (!post_data._uid)
  2460. return;
  2461. this.show_contentframe(false);
  2462. this._with_selected_messages('delete', post_data);
  2463. };
  2464. // Send a specific move/delete request with UIDs of all selected messages
  2465. // @private
  2466. this._with_selected_messages = function(action, post_data, lock)
  2467. {
  2468. var count = 0, msg,
  2469. remove = (action == 'delete' || !this.is_multifolder_listing());
  2470. // update the list (remove rows, clear selection)
  2471. if (this.message_list) {
  2472. var n, id, root, roots = [],
  2473. selection = this.message_list.get_selection();
  2474. for (n=0, len=selection.length; n<len; n++) {
  2475. id = selection[n];
  2476. if (this.env.threading) {
  2477. count += this.update_thread(id);
  2478. root = this.message_list.find_root(id);
  2479. if (root != id && $.inArray(root, roots) < 0) {
  2480. roots.push(root);
  2481. }
  2482. }
  2483. if (remove)
  2484. this.message_list.remove_row(id, (this.env.display_next && n == selection.length-1));
  2485. }
  2486. // make sure there are no selected rows
  2487. if (!this.env.display_next && remove)
  2488. this.message_list.clear_selection();
  2489. // update thread tree icons
  2490. for (n=0, len=roots.length; n<len; n++) {
  2491. this.add_tree_icons(roots[n]);
  2492. }
  2493. }
  2494. if (count < 0)
  2495. post_data._count = (count*-1);
  2496. // remove threads from the end of the list
  2497. else if (count > 0 && remove)
  2498. this.delete_excessive_thread_rows();
  2499. if (!remove)
  2500. post_data._refresh = 1;
  2501. if (!lock) {
  2502. msg = action == 'move' ? 'movingmessage' : 'deletingmessage';
  2503. lock = this.display_message(this.get_label(msg), 'loading');
  2504. }
  2505. // send request to server
  2506. this.http_post(action, post_data, lock);
  2507. };
  2508. // build post data for message delete/move/copy/flag requests
  2509. this.selection_post_data = function(data)
  2510. {
  2511. if (typeof(data) != 'object')
  2512. data = {};
  2513. data._mbox = this.env.mailbox;
  2514. if (!data._uid) {
  2515. var uids = this.env.uid ? [this.env.uid] : this.message_list.get_selection();
  2516. data._uid = this.uids_to_list(uids);
  2517. }
  2518. if (this.env.action)
  2519. data._from = this.env.action;
  2520. // also send search request to get the right messages
  2521. if (this.env.search_request)
  2522. data._search = this.env.search_request;
  2523. if (this.env.display_next && this.env.next_uid)
  2524. data._next_uid = this.env.next_uid;
  2525. return data;
  2526. };
  2527. // set a specific flag to one or more messages
  2528. this.mark_message = function(flag, uid)
  2529. {
  2530. var a_uids = [], r_uids = [], len, n, id,
  2531. list = this.message_list;
  2532. if (uid)
  2533. a_uids[0] = uid;
  2534. else if (this.env.uid)
  2535. a_uids[0] = this.env.uid;
  2536. else if (list)
  2537. a_uids = list.get_selection();
  2538. if (!list)
  2539. r_uids = a_uids;
  2540. else {
  2541. list.focus();
  2542. for (n=0, len=a_uids.length; n<len; n++) {
  2543. id = a_uids[n];
  2544. if ((flag == 'read' && list.rows[id].unread)
  2545. || (flag == 'unread' && !list.rows[id].unread)
  2546. || (flag == 'delete' && !list.rows[id].deleted)
  2547. || (flag == 'undelete' && list.rows[id].deleted)
  2548. || (flag == 'flagged' && !list.rows[id].flagged)
  2549. || (flag == 'unflagged' && list.rows[id].flagged))
  2550. {
  2551. r_uids.push(id);
  2552. }
  2553. }
  2554. }
  2555. // nothing to do
  2556. if (!r_uids.length && !this.select_all_mode)
  2557. return;
  2558. switch (flag) {
  2559. case 'read':
  2560. case 'unread':
  2561. this.toggle_read_status(flag, r_uids);
  2562. break;
  2563. case 'delete':
  2564. case 'undelete':
  2565. this.toggle_delete_status(r_uids);
  2566. break;
  2567. case 'flagged':
  2568. case 'unflagged':
  2569. this.toggle_flagged_status(flag, a_uids);
  2570. break;
  2571. }
  2572. };
  2573. // set class to read/unread
  2574. this.toggle_read_status = function(flag, a_uids)
  2575. {
  2576. var i, len = a_uids.length,
  2577. post_data = this.selection_post_data({_uid: this.uids_to_list(a_uids), _flag: flag}),
  2578. lock = this.display_message(this.get_label('markingmessage'), 'loading');
  2579. // mark all message rows as read/unread
  2580. for (i=0; i<len; i++)
  2581. this.set_message(a_uids[i], 'unread', (flag == 'unread' ? true : false));
  2582. this.http_post('mark', post_data, lock);
  2583. };
  2584. // set image to flagged or unflagged
  2585. this.toggle_flagged_status = function(flag, a_uids)
  2586. {
  2587. var i, len = a_uids.length,
  2588. post_data = this.selection_post_data({_uid: this.uids_to_list(a_uids), _flag: flag}),
  2589. lock = this.display_message(this.get_label('markingmessage'), 'loading');
  2590. // mark all message rows as flagged/unflagged
  2591. for (i=0; i<len; i++)
  2592. this.set_message(a_uids[i], 'flagged', (flag == 'flagged' ? true : false));
  2593. this.http_post('mark', post_data, lock);
  2594. };
  2595. // mark all message rows as deleted/undeleted
  2596. this.toggle_delete_status = function(a_uids)
  2597. {
  2598. var len = a_uids.length,
  2599. i, uid, all_deleted = true,
  2600. rows = this.message_list ? this.message_list.rows : {};
  2601. if (len == 1) {
  2602. if (!this.message_list || (rows[a_uids[0]] && !rows[a_uids[0]].deleted))
  2603. this.flag_as_deleted(a_uids);
  2604. else
  2605. this.flag_as_undeleted(a_uids);
  2606. return true;
  2607. }
  2608. for (i=0; i<len; i++) {
  2609. uid = a_uids[i];
  2610. if (rows[uid] && !rows[uid].deleted) {
  2611. all_deleted = false;
  2612. break;
  2613. }
  2614. }
  2615. if (all_deleted)
  2616. this.flag_as_undeleted(a_uids);
  2617. else
  2618. this.flag_as_deleted(a_uids);
  2619. return true;
  2620. };
  2621. this.flag_as_undeleted = function(a_uids)
  2622. {
  2623. var i, len = a_uids.length,
  2624. post_data = this.selection_post_data({_uid: this.uids_to_list(a_uids), _flag: 'undelete'}),
  2625. lock = this.display_message(this.get_label('markingmessage'), 'loading');
  2626. for (i=0; i<len; i++)
  2627. this.set_message(a_uids[i], 'deleted', false);
  2628. this.http_post('mark', post_data, lock);
  2629. };
  2630. this.flag_as_deleted = function(a_uids)
  2631. {
  2632. var r_uids = [],
  2633. post_data = this.selection_post_data({_uid: this.uids_to_list(a_uids), _flag: 'delete'}),
  2634. lock = this.display_message(this.get_label('markingmessage'), 'loading'),
  2635. rows = this.message_list ? this.message_list.rows : {},
  2636. count = 0;
  2637. for (var i=0, len=a_uids.length; i<len; i++) {
  2638. uid = a_uids[i];
  2639. if (rows[uid]) {
  2640. if (rows[uid].unread)
  2641. r_uids[r_uids.length] = uid;
  2642. if (this.env.skip_deleted) {
  2643. count += this.update_thread(uid);
  2644. this.message_list.remove_row(uid, (this.env.display_next && i == this.message_list.selection.length-1));
  2645. }
  2646. else
  2647. this.set_message(uid, 'deleted', true);
  2648. }
  2649. }
  2650. // make sure there are no selected rows
  2651. if (this.env.skip_deleted && this.message_list) {
  2652. if (!this.env.display_next)
  2653. this.message_list.clear_selection();
  2654. if (count < 0)
  2655. post_data._count = (count*-1);
  2656. else if (count > 0)
  2657. // remove threads from the end of the list
  2658. this.delete_excessive_thread_rows();
  2659. }
  2660. // set of messages to mark as seen
  2661. if (r_uids.length)
  2662. post_data._ruid = this.uids_to_list(r_uids);
  2663. if (this.env.skip_deleted && this.env.display_next && this.env.next_uid)
  2664. post_data._next_uid = this.env.next_uid;
  2665. this.http_post('mark', post_data, lock);
  2666. };
  2667. // flag as read without mark request (called from backend)
  2668. // argument should be a coma-separated list of uids
  2669. this.flag_deleted_as_read = function(uids)
  2670. {
  2671. var uid, i, len,
  2672. rows = this.message_list ? this.message_list.rows : {};
  2673. if (typeof uids == 'string')
  2674. uids = uids.split(',');
  2675. for (i=0, len=uids.length; i<len; i++) {
  2676. uid = uids[i];
  2677. if (rows[uid])
  2678. this.set_message(uid, 'unread', false);
  2679. }
  2680. };
  2681. // Converts array of message UIDs to comma-separated list for use in URL
  2682. // with select_all mode checking
  2683. this.uids_to_list = function(uids)
  2684. {
  2685. return this.select_all_mode ? '*' : (uids.length <= 1 ? uids.join(',') : uids);
  2686. };
  2687. // Sets title of the delete button
  2688. this.set_button_titles = function()
  2689. {
  2690. var label = 'deletemessage';
  2691. if (!this.env.flag_for_deletion
  2692. && this.env.trash_mailbox && this.env.mailbox != this.env.trash_mailbox
  2693. && (!this.env.delete_junk || !this.env.junk_mailbox || this.env.mailbox != this.env.junk_mailbox)
  2694. )
  2695. label = 'movemessagetotrash';
  2696. this.set_alttext('delete', label);
  2697. };
  2698. /*********************************************************/
  2699. /********* mailbox folders methods *********/
  2700. /*********************************************************/
  2701. this.expunge_mailbox = function(mbox)
  2702. {
  2703. var lock, post_data = {_mbox: mbox};
  2704. // lock interface if it's the active mailbox
  2705. if (mbox == this.env.mailbox) {
  2706. lock = this.set_busy(true, 'loading');
  2707. post_data._reload = 1;
  2708. if (this.env.search_request)
  2709. post_data._search = this.env.search_request;
  2710. }
  2711. // send request to server
  2712. this.http_post('expunge', post_data, lock);
  2713. };
  2714. this.purge_mailbox = function(mbox)
  2715. {
  2716. var lock, post_data = {_mbox: mbox};
  2717. if (!confirm(this.get_label('purgefolderconfirm')))
  2718. return false;
  2719. // lock interface if it's the active mailbox
  2720. if (mbox == this.env.mailbox) {
  2721. lock = this.set_busy(true, 'loading');
  2722. post_data._reload = 1;
  2723. }
  2724. // send request to server
  2725. this.http_post('purge', post_data, lock);
  2726. };
  2727. // test if purge command is allowed
  2728. this.purge_mailbox_test = function()
  2729. {
  2730. return (this.env.exists && (
  2731. this.env.mailbox == this.env.trash_mailbox
  2732. || this.env.mailbox == this.env.junk_mailbox
  2733. || this.env.mailbox.startsWith(this.env.trash_mailbox + this.env.delimiter)
  2734. || this.env.mailbox.startsWith(this.env.junk_mailbox + this.env.delimiter)
  2735. ));
  2736. };
  2737. /*********************************************************/
  2738. /********* login form methods *********/
  2739. /*********************************************************/
  2740. // handler for keyboard events on the _user field
  2741. this.login_user_keyup = function(e)
  2742. {
  2743. var key = rcube_event.get_keycode(e),
  2744. passwd = $('#rcmloginpwd');
  2745. // enter
  2746. if (key == 13 && passwd.length && !passwd.val()) {
  2747. passwd.focus();
  2748. return rcube_event.cancel(e);
  2749. }
  2750. return true;
  2751. };
  2752. /*********************************************************/
  2753. /********* message compose methods *********/
  2754. /*********************************************************/
  2755. this.open_compose_step = function(p)
  2756. {
  2757. var url = this.url('mail/compose', p);
  2758. // open new compose window
  2759. if (this.env.compose_extwin && !this.env.extwin) {
  2760. this.open_window(url);
  2761. }
  2762. else {
  2763. this.redirect(url);
  2764. if (this.env.extwin)
  2765. window.resizeTo(Math.max(this.env.popup_width, $(window).width()), $(window).height() + 24);
  2766. }
  2767. };
  2768. // init message compose form: set focus and eventhandlers
  2769. this.init_messageform = function()
  2770. {
  2771. if (!this.gui_objects.messageform)
  2772. return false;
  2773. var i, input_from = $("[name='_from']"),
  2774. input_to = $("[name='_to']"),
  2775. input_subject = $("input[name='_subject']"),
  2776. input_message = $("[name='_message']").get(0),
  2777. html_mode = $("input[name='_is_html']").val() == '1',
  2778. ac_fields = ['cc', 'bcc', 'replyto', 'followupto'],
  2779. ac_props, opener_rc = this.opener();
  2780. // close compose step in opener
  2781. if (opener_rc && opener_rc.env.action == 'compose') {
  2782. setTimeout(function(){
  2783. if (opener.history.length > 1)
  2784. opener.history.back();
  2785. else
  2786. opener_rc.redirect(opener_rc.get_task_url('mail'));
  2787. }, 100);
  2788. this.env.opened_extwin = true;
  2789. }
  2790. // configure parallel autocompletion
  2791. if (this.env.autocomplete_threads > 0) {
  2792. ac_props = {
  2793. threads: this.env.autocomplete_threads,
  2794. sources: this.env.autocomplete_sources
  2795. };
  2796. }
  2797. // init live search events
  2798. this.init_address_input_events(input_to, ac_props);
  2799. for (i in ac_fields) {
  2800. this.init_address_input_events($("[name='_"+ac_fields[i]+"']"), ac_props);
  2801. }
  2802. if (!html_mode) {
  2803. this.set_caret_pos(input_message, this.env.top_posting ? 0 : $(input_message).val().length);
  2804. // add signature according to selected identity
  2805. // if we have HTML editor, signature is added in callback
  2806. if (input_from.prop('type') == 'select-one') {
  2807. this.change_identity(input_from[0]);
  2808. }
  2809. }
  2810. // check for locally stored compose data
  2811. this.compose_restore_dialog(0, html_mode)
  2812. if (input_to.val() == '')
  2813. input_to.focus();
  2814. else if (input_subject.val() == '')
  2815. input_subject.focus();
  2816. else if (input_message)
  2817. input_message.focus();
  2818. this.env.compose_focus_elem = document.activeElement;
  2819. // get summary of all field values
  2820. this.compose_field_hash(true);
  2821. // start the auto-save timer
  2822. this.auto_save_start();
  2823. };
  2824. this.compose_restore_dialog = function(j, html_mode)
  2825. {
  2826. var i, key, formdata, index = this.local_storage_get_item('compose.index', []);
  2827. var show_next = function(i) {
  2828. if (++i < index.length)
  2829. ref.compose_restore_dialog(i, html_mode)
  2830. }
  2831. for (i = j || 0; i < index.length; i++) {
  2832. key = index[i];
  2833. formdata = this.local_storage_get_item('compose.' + key, null, true);
  2834. if (!formdata) {
  2835. continue;
  2836. }
  2837. // restore saved copy of current compose_id
  2838. if (formdata.changed && key == this.env.compose_id) {
  2839. this.restore_compose_form(key, html_mode);
  2840. break;
  2841. }
  2842. // skip records from 'other' drafts
  2843. if (this.env.draft_id && formdata.draft_id && formdata.draft_id != this.env.draft_id) {
  2844. continue;
  2845. }
  2846. // skip records on reply
  2847. if (this.env.reply_msgid && formdata.reply_msgid != this.env.reply_msgid) {
  2848. continue;
  2849. }
  2850. // show dialog asking to restore the message
  2851. if (formdata.changed && formdata.session != this.env.session_id) {
  2852. this.show_popup_dialog(
  2853. this.get_label('restoresavedcomposedata')
  2854. .replace('$date', new Date(formdata.changed).toLocaleString())
  2855. .replace('$subject', formdata._subject)
  2856. .replace(/\n/g, '<br/>'),
  2857. this.get_label('restoremessage'),
  2858. [{
  2859. text: this.get_label('restore'),
  2860. click: function(){
  2861. ref.restore_compose_form(key, html_mode);
  2862. ref.remove_compose_data(key); // remove old copy
  2863. ref.save_compose_form_local(); // save under current compose_id
  2864. $(this).dialog('close');
  2865. }
  2866. },
  2867. {
  2868. text: this.get_label('delete'),
  2869. click: function(){
  2870. ref.remove_compose_data(key);
  2871. $(this).dialog('close');
  2872. show_next(i);
  2873. }
  2874. },
  2875. {
  2876. text: this.get_label('ignore'),
  2877. click: function(){
  2878. $(this).dialog('close');
  2879. show_next(i);
  2880. }
  2881. }]
  2882. );
  2883. break;
  2884. }
  2885. }
  2886. }
  2887. this.init_address_input_events = function(obj, props)
  2888. {
  2889. this.env.recipients_delimiter = this.env.recipients_separator + ' ';
  2890. obj.keydown(function(e) { return ref.ksearch_keydown(e, this, props); })
  2891. .attr({ 'autocomplete': 'off', 'aria-autocomplete': 'list', 'aria-expanded': 'false', 'role': 'combobox' });
  2892. };
  2893. this.submit_messageform = function(draft)
  2894. {
  2895. var form = this.gui_objects.messageform;
  2896. if (!form)
  2897. return;
  2898. // all checks passed, send message
  2899. var msgid = this.set_busy(true, draft ? 'savingmessage' : 'sendingmessage'),
  2900. lang = this.spellcheck_lang(),
  2901. files = [];
  2902. // send files list
  2903. $('li', this.gui_objects.attachmentlist).each(function() { files.push(this.id.replace(/^rcmfile/, '')); });
  2904. $('input[name="_attachments"]', form).val(files.join());
  2905. form.target = 'savetarget';
  2906. form._draft.value = draft ? '1' : '';
  2907. form.action = this.add_url(form.action, '_unlock', msgid);
  2908. form.action = this.add_url(form.action, '_lang', lang);
  2909. form.action = this.add_url(form.action, '_framed', 1);
  2910. // register timer to notify about connection timeout
  2911. this.submit_timer = setTimeout(function(){
  2912. ref.set_busy(false, null, msgid);
  2913. ref.display_message(ref.get_label('requesttimedout'), 'error');
  2914. }, this.env.request_timeout * 1000);
  2915. form.submit();
  2916. };
  2917. this.compose_recipient_select = function(list)
  2918. {
  2919. var id, n, recipients = 0;
  2920. for (n=0; n < list.selection.length; n++) {
  2921. id = list.selection[n];
  2922. if (this.env.contactdata[id])
  2923. recipients++;
  2924. }
  2925. this.enable_command('add-recipient', recipients);
  2926. };
  2927. this.compose_add_recipient = function(field)
  2928. {
  2929. // find last focused field name
  2930. if (!field) {
  2931. field = $(this.env.focused_field).filter(':visible');
  2932. field = field.length ? field.attr('id').replace('_', '') : 'to';
  2933. }
  2934. var recipients = [], input = $('#_'+field), delim = this.env.recipients_delimiter;
  2935. if (this.contact_list && this.contact_list.selection.length) {
  2936. for (var id, n=0; n < this.contact_list.selection.length; n++) {
  2937. id = this.contact_list.selection[n];
  2938. if (id && this.env.contactdata[id]) {
  2939. recipients.push(this.env.contactdata[id]);
  2940. // group is added, expand it
  2941. if (id.charAt(0) == 'E' && this.env.contactdata[id].indexOf('@') < 0 && input.length) {
  2942. var gid = id.substr(1);
  2943. this.group2expand[gid] = { name:this.env.contactdata[id], input:input.get(0) };
  2944. this.http_request('group-expand', {_source: this.env.source, _gid: gid}, false);
  2945. }
  2946. }
  2947. }
  2948. }
  2949. if (recipients.length && input.length) {
  2950. var oldval = input.val(), rx = new RegExp(RegExp.escape(delim) + '\\s*$');
  2951. if (oldval && !rx.test(oldval))
  2952. oldval += delim + ' ';
  2953. input.val(oldval + recipients.join(delim + ' ') + delim + ' ');
  2954. this.triggerEvent('add-recipient', { field:field, recipients:recipients });
  2955. }
  2956. return recipients.length;
  2957. };
  2958. // checks the input fields before sending a message
  2959. this.check_compose_input = function(cmd)
  2960. {
  2961. // check input fields
  2962. var input_to = $("[name='_to']"),
  2963. input_cc = $("[name='_cc']"),
  2964. input_bcc = $("[name='_bcc']"),
  2965. input_from = $("[name='_from']"),
  2966. input_subject = $("[name='_subject']");
  2967. // check sender (if have no identities)
  2968. if (input_from.prop('type') == 'text' && !rcube_check_email(input_from.val(), true)) {
  2969. alert(this.get_label('nosenderwarning'));
  2970. input_from.focus();
  2971. return false;
  2972. }
  2973. // check for empty recipient
  2974. var recipients = input_to.val() ? input_to.val() : (input_cc.val() ? input_cc.val() : input_bcc.val());
  2975. if (!rcube_check_email(recipients.replace(/^\s+/, '').replace(/[\s,;]+$/, ''), true)) {
  2976. alert(this.get_label('norecipientwarning'));
  2977. input_to.focus();
  2978. return false;
  2979. }
  2980. // check if all files has been uploaded
  2981. for (var key in this.env.attachments) {
  2982. if (typeof this.env.attachments[key] === 'object' && !this.env.attachments[key].complete) {
  2983. alert(this.get_label('notuploadedwarning'));
  2984. return false;
  2985. }
  2986. }
  2987. // display localized warning for missing subject
  2988. if (input_subject.val() == '') {
  2989. var buttons = {},
  2990. myprompt = $('<div class="prompt">').html('<div class="message">' + this.get_label('nosubjectwarning') + '</div>')
  2991. .appendTo(document.body),
  2992. prompt_value = $('<input>').attr({type: 'text', size: 30}).val(this.get_label('nosubject'))
  2993. .appendTo(myprompt),
  2994. save_func = function() {
  2995. input_subject.val(prompt_value.val());
  2996. myprompt.dialog('close');
  2997. ref.command(cmd, { nocheck:true }); // repeat command which triggered this
  2998. };
  2999. buttons[this.get_label('sendmessage')] = function() {
  3000. save_func($(this));
  3001. };
  3002. buttons[this.get_label('cancel')] = function() {
  3003. input_subject.focus();
  3004. $(this).dialog('close');
  3005. };
  3006. myprompt.dialog({
  3007. modal: true,
  3008. resizable: false,
  3009. buttons: buttons,
  3010. close: function(event, ui) { $(this).remove(); }
  3011. });
  3012. prompt_value.select().keydown(function(e) {
  3013. if (e.which == 13) save_func();
  3014. });
  3015. return false;
  3016. }
  3017. // check for empty body
  3018. if (!this.editor.get_content() && !confirm(this.get_label('nobodywarning'))) {
  3019. this.editor.focus();
  3020. return false;
  3021. }
  3022. // move body from html editor to textarea (just to be sure, #1485860)
  3023. this.editor.save();
  3024. return true;
  3025. };
  3026. this.toggle_editor = function(props, obj, e)
  3027. {
  3028. // @todo: this should work also with many editors on page
  3029. var result = this.editor.toggle(props.html);
  3030. if (!result && e) {
  3031. // fix selector value if operation failed
  3032. $(e.target).filter('select').val(props.html ? 'plain' : 'html');
  3033. }
  3034. if (result) {
  3035. // update internal format flag
  3036. $("input[name='_is_html']").val(props.html ? 1 : 0);
  3037. }
  3038. return result;
  3039. };
  3040. this.insert_response = function(key)
  3041. {
  3042. var insert = this.env.textresponses[key] ? this.env.textresponses[key].text : null;
  3043. if (!insert)
  3044. return false;
  3045. this.editor.replace(insert);
  3046. };
  3047. /**
  3048. * Open the dialog to save a new canned response
  3049. */
  3050. this.save_response = function()
  3051. {
  3052. // show dialog to enter a name and to modify the text to be saved
  3053. var buttons = {}, text = this.editor.get_content(true, true),
  3054. html = '<form class="propform">' +
  3055. '<div class="prop block"><label>' + this.get_label('responsename') + '</label>' +
  3056. '<input type="text" name="name" id="ffresponsename" size="40" /></div>' +
  3057. '<div class="prop block"><label>' + this.get_label('responsetext') + '</label>' +
  3058. '<textarea name="text" id="ffresponsetext" cols="40" rows="8"></textarea></div>' +
  3059. '</form>';
  3060. buttons[this.gettext('save')] = function(e) {
  3061. var name = $('#ffresponsename').val(),
  3062. text = $('#ffresponsetext').val();
  3063. if (!text) {
  3064. $('#ffresponsetext').select();
  3065. return false;
  3066. }
  3067. if (!name)
  3068. name = text.substring(0,40);
  3069. var lock = ref.display_message(ref.get_label('savingresponse'), 'loading');
  3070. ref.http_post('settings/responses', { _insert:1, _name:name, _text:text }, lock);
  3071. $(this).dialog('close');
  3072. };
  3073. buttons[this.gettext('cancel')] = function() {
  3074. $(this).dialog('close');
  3075. };
  3076. this.show_popup_dialog(html, this.gettext('newresponse'), buttons);
  3077. $('#ffresponsetext').val(text);
  3078. $('#ffresponsename').select();
  3079. };
  3080. this.add_response_item = function(response)
  3081. {
  3082. var key = response.key;
  3083. this.env.textresponses[key] = response;
  3084. // append to responses list
  3085. if (this.gui_objects.responseslist) {
  3086. var li = $('<li>').appendTo(this.gui_objects.responseslist);
  3087. $('<a>').addClass('insertresponse active')
  3088. .attr('href', '#')
  3089. .attr('rel', key)
  3090. .attr('tabindex', '0')
  3091. .html(this.quote_html(response.name))
  3092. .appendTo(li)
  3093. .mousedown(function(e){
  3094. return rcube_event.cancel(e);
  3095. })
  3096. .bind('mouseup keypress', function(e){
  3097. if (e.type == 'mouseup' || rcube_event.get_keycode(e) == 13) {
  3098. ref.command('insert-response', $(this).attr('rel'));
  3099. $(document.body).trigger('mouseup'); // hides the menu
  3100. return rcube_event.cancel(e);
  3101. }
  3102. });
  3103. }
  3104. };
  3105. this.edit_responses = function()
  3106. {
  3107. // TODO: implement inline editing of responses
  3108. };
  3109. this.delete_response = function(key)
  3110. {
  3111. if (!key && this.responses_list) {
  3112. var selection = this.responses_list.get_selection();
  3113. key = selection[0];
  3114. }
  3115. // submit delete request
  3116. if (key && confirm(this.get_label('deleteresponseconfirm'))) {
  3117. this.http_post('settings/delete-response', { _key: key }, false);
  3118. }
  3119. };
  3120. // updates spellchecker buttons on state change
  3121. this.spellcheck_state = function()
  3122. {
  3123. var active = this.editor.spellcheck_state();
  3124. $.each(this.buttons.spellcheck || [], function(i, v) {
  3125. $('#' + v.id)[active ? 'addClass' : 'removeClass']('selected');
  3126. });
  3127. return active;
  3128. };
  3129. // get selected language
  3130. this.spellcheck_lang = function()
  3131. {
  3132. return this.editor.get_language();
  3133. };
  3134. this.spellcheck_lang_set = function(lang)
  3135. {
  3136. this.editor.set_language(lang);
  3137. };
  3138. // resume spellchecking, highlight provided mispellings without new ajax request
  3139. this.spellcheck_resume = function(data)
  3140. {
  3141. this.editor.spellcheck_resume(data);
  3142. };
  3143. this.set_draft_id = function(id)
  3144. {
  3145. var rc;
  3146. if (id && id != this.env.draft_id) {
  3147. if (rc = this.opener()) {
  3148. // refresh the drafts folder in opener window
  3149. if (rc.env.task == 'mail' && rc.env.action == '' && rc.env.mailbox == this.env.drafts_mailbox)
  3150. rc.command('checkmail');
  3151. }
  3152. this.env.draft_id = id;
  3153. $("input[name='_draft_saveid']").val(id);
  3154. // reset history of hidden iframe used for saving draft (#1489643)
  3155. // but don't do this on timer-triggered draft-autosaving (#1489789)
  3156. if (window.frames['savetarget'] && window.frames['savetarget'].history && !this.draft_autosave_submit) {
  3157. window.frames['savetarget'].history.back();
  3158. }
  3159. this.draft_autosave_submit = false;
  3160. }
  3161. // always remove local copy upon saving as draft
  3162. this.remove_compose_data(this.env.compose_id);
  3163. this.compose_skip_unsavedcheck = false;
  3164. };
  3165. this.auto_save_start = function()
  3166. {
  3167. if (this.env.draft_autosave) {
  3168. this.draft_autosave_submit = false;
  3169. this.save_timer = setTimeout(function(){
  3170. ref.draft_autosave_submit = true; // set auto-saved flag (#1489789)
  3171. ref.command("savedraft");
  3172. }, this.env.draft_autosave * 1000);
  3173. }
  3174. // save compose form content to local storage every 5 seconds
  3175. if (!this.local_save_timer && window.localStorage) {
  3176. // track typing activity and only save on changes
  3177. this.compose_type_activity = this.compose_type_activity_last = 0;
  3178. $(document).bind('keypress', function(e){ ref.compose_type_activity++; });
  3179. this.local_save_timer = setInterval(function(){
  3180. if (ref.compose_type_activity > ref.compose_type_activity_last) {
  3181. ref.save_compose_form_local();
  3182. ref.compose_type_activity_last = ref.compose_type_activity;
  3183. }
  3184. }, 5000);
  3185. $(window).unload(function() {
  3186. // remove copy from local storage if compose screen is left after warning
  3187. if (!ref.env.server_error)
  3188. ref.remove_compose_data(ref.env.compose_id);
  3189. });
  3190. }
  3191. // check for unsaved changes before leaving the compose page
  3192. if (!window.onbeforeunload) {
  3193. window.onbeforeunload = function() {
  3194. if (!ref.compose_skip_unsavedcheck && ref.cmp_hash != ref.compose_field_hash()) {
  3195. return ref.get_label('notsentwarning');
  3196. }
  3197. };
  3198. }
  3199. // Unlock interface now that saving is complete
  3200. this.busy = false;
  3201. };
  3202. this.compose_field_hash = function(save)
  3203. {
  3204. // check input fields
  3205. var i, id, val, str = '', hash_fields = ['to', 'cc', 'bcc', 'subject'];
  3206. for (i=0; i<hash_fields.length; i++)
  3207. if (val = $('[name="_' + hash_fields[i] + '"]').val())
  3208. str += val + ':';
  3209. str += this.editor.get_content();
  3210. if (this.env.attachments)
  3211. for (id in this.env.attachments)
  3212. str += id;
  3213. if (save)
  3214. this.cmp_hash = str;
  3215. return str;
  3216. };
  3217. // store the contents of the compose form to localstorage
  3218. this.save_compose_form_local = function()
  3219. {
  3220. var formdata = { session:this.env.session_id, changed:new Date().getTime() },
  3221. ed, empty = true;
  3222. // get fresh content from editor
  3223. this.editor.save();
  3224. if (this.env.draft_id) {
  3225. formdata.draft_id = this.env.draft_id;
  3226. }
  3227. if (this.env.reply_msgid) {
  3228. formdata.reply_msgid = this.env.reply_msgid;
  3229. }
  3230. $('input, select, textarea', this.gui_objects.messageform).each(function(i, elem) {
  3231. switch (elem.tagName.toLowerCase()) {
  3232. case 'input':
  3233. if (elem.type == 'button' || elem.type == 'submit' || (elem.type == 'hidden' && elem.name != '_is_html')) {
  3234. break;
  3235. }
  3236. formdata[elem.name] = elem.type != 'checkbox' || elem.checked ? $(elem).val() : '';
  3237. if (formdata[elem.name] != '' && elem.type != 'hidden')
  3238. empty = false;
  3239. break;
  3240. case 'select':
  3241. formdata[elem.name] = $('option:checked', elem).val();
  3242. break;
  3243. default:
  3244. formdata[elem.name] = $(elem).val();
  3245. if (formdata[elem.name] != '')
  3246. empty = false;
  3247. }
  3248. });
  3249. if (!empty) {
  3250. var index = this.local_storage_get_item('compose.index', []),
  3251. key = this.env.compose_id;
  3252. if ($.inArray(key, index) < 0) {
  3253. index.push(key);
  3254. }
  3255. this.local_storage_set_item('compose.' + key, formdata, true);
  3256. this.local_storage_set_item('compose.index', index);
  3257. }
  3258. };
  3259. // write stored compose data back to form
  3260. this.restore_compose_form = function(key, html_mode)
  3261. {
  3262. var ed, formdata = this.local_storage_get_item('compose.' + key, true);
  3263. if (formdata && typeof formdata == 'object') {
  3264. $.each(formdata, function(k, value) {
  3265. if (k[0] == '_') {
  3266. var elem = $("*[name='"+k+"']");
  3267. if (elem[0] && elem[0].type == 'checkbox') {
  3268. elem.prop('checked', value != '');
  3269. }
  3270. else {
  3271. elem.val(value);
  3272. }
  3273. }
  3274. });
  3275. // initialize HTML editor
  3276. if ((formdata._is_html == '1' && !html_mode) || (formdata._is_html != '1' && html_mode)) {
  3277. this.command('toggle-editor', {id: this.env.composebody, html: !html_mode});
  3278. }
  3279. }
  3280. };
  3281. // remove stored compose data from localStorage
  3282. this.remove_compose_data = function(key)
  3283. {
  3284. var index = this.local_storage_get_item('compose.index', []);
  3285. if ($.inArray(key, index) >= 0) {
  3286. this.local_storage_remove_item('compose.' + key);
  3287. this.local_storage_set_item('compose.index', $.grep(index, function(val,i) { return val != key; }));
  3288. }
  3289. };
  3290. // clear all stored compose data of this user
  3291. this.clear_compose_data = function()
  3292. {
  3293. var i, index = this.local_storage_get_item('compose.index', []);
  3294. for (i=0; i < index.length; i++) {
  3295. this.local_storage_remove_item('compose.' + index[i]);
  3296. }
  3297. this.local_storage_remove_item('compose.index');
  3298. };
  3299. this.change_identity = function(obj, show_sig)
  3300. {
  3301. if (!obj || !obj.options)
  3302. return false;
  3303. if (!show_sig)
  3304. show_sig = this.env.show_sig;
  3305. // first function execution
  3306. if (!this.env.identities_initialized) {
  3307. this.env.identities_initialized = true;
  3308. if (this.env.show_sig_later)
  3309. this.env.show_sig = true;
  3310. if (this.env.opened_extwin)
  3311. return;
  3312. }
  3313. var id = obj.options[obj.selectedIndex].value,
  3314. sig = this.env.identity,
  3315. delim = this.env.recipients_separator,
  3316. rx_delim = RegExp.escape(delim);
  3317. // update reply-to/bcc fields with addresses defined in identities
  3318. $.each(['replyto', 'bcc'], function() {
  3319. var rx, key = this,
  3320. old_val = sig && ref.env.identities[sig] ? ref.env.identities[sig][key] : '',
  3321. new_val = id && ref.env.identities[id] ? ref.env.identities[id][key] : '',
  3322. input = $('[name="_'+key+'"]'), input_val = input.val();
  3323. // remove old address(es)
  3324. if (old_val && input_val) {
  3325. rx = new RegExp('\\s*' + RegExp.escape(old_val) + '\\s*');
  3326. input_val = input_val.replace(rx, '');
  3327. }
  3328. // cleanup
  3329. rx = new RegExp(rx_delim + '\\s*' + rx_delim, 'g');
  3330. input_val = String(input_val).replace(rx, delim);
  3331. rx = new RegExp('^[\\s' + rx_delim + ']+');
  3332. input_val = input_val.replace(rx, '');
  3333. // add new address(es)
  3334. if (new_val && input_val.indexOf(new_val) == -1 && input_val.indexOf(new_val.replace(/"/g, '')) == -1) {
  3335. if (input_val) {
  3336. rx = new RegExp('[' + rx_delim + '\\s]+$')
  3337. input_val = input_val.replace(rx, '') + delim + ' ';
  3338. }
  3339. input_val += new_val + delim + ' ';
  3340. }
  3341. if (old_val || new_val)
  3342. input.val(input_val).change();
  3343. });
  3344. // enable manual signature insert
  3345. if (this.env.signatures && this.env.signatures[id]) {
  3346. this.enable_command('insert-sig', true);
  3347. this.env.compose_commands.push('insert-sig');
  3348. }
  3349. else
  3350. this.enable_command('insert-sig', false);
  3351. this.editor.change_signature(id, show_sig);
  3352. this.env.identity = id;
  3353. this.triggerEvent('change_identity');
  3354. return true;
  3355. };
  3356. // upload (attachment) file
  3357. this.upload_file = function(form, action)
  3358. {
  3359. if (!form)
  3360. return;
  3361. // count files and size on capable browser
  3362. var size = 0, numfiles = 0;
  3363. $('input[type=file]', form).each(function(i, field) {
  3364. var files = field.files ? field.files.length : (field.value ? 1 : 0);
  3365. // check file size
  3366. if (field.files) {
  3367. for (var i=0; i < files; i++)
  3368. size += field.files[i].size;
  3369. }
  3370. numfiles += files;
  3371. });
  3372. // create hidden iframe and post upload form
  3373. if (numfiles) {
  3374. if (this.env.max_filesize && this.env.filesizeerror && size > this.env.max_filesize) {
  3375. this.display_message(this.env.filesizeerror, 'error');
  3376. return false;
  3377. }
  3378. var frame_name = this.async_upload_form(form, action || 'upload', function(e) {
  3379. var d, content = '';
  3380. try {
  3381. if (this.contentDocument) {
  3382. d = this.contentDocument;
  3383. } else if (this.contentWindow) {
  3384. d = this.contentWindow.document;
  3385. }
  3386. content = d.childNodes[1].innerHTML;
  3387. } catch (err) {}
  3388. if (!content.match(/add2attachment/) && (!bw.opera || (ref.env.uploadframe && ref.env.uploadframe == e.data.ts))) {
  3389. if (!content.match(/display_message/))
  3390. ref.display_message(ref.get_label('fileuploaderror'), 'error');
  3391. ref.remove_from_attachment_list(e.data.ts);
  3392. }
  3393. // Opera hack: handle double onload
  3394. if (bw.opera)
  3395. ref.env.uploadframe = e.data.ts;
  3396. });
  3397. // display upload indicator and cancel button
  3398. var content = '<span>' + this.get_label('uploading' + (numfiles > 1 ? 'many' : '')) + '</span>',
  3399. ts = frame_name.replace(/^rcmupload/, '');
  3400. this.add2attachment_list(ts, { name:'', html:content, classname:'uploading', frame:frame_name, complete:false });
  3401. // upload progress support
  3402. if (this.env.upload_progress_time) {
  3403. this.upload_progress_start('upload', ts);
  3404. }
  3405. // set reference to the form object
  3406. this.gui_objects.attachmentform = form;
  3407. return true;
  3408. }
  3409. };
  3410. // add file name to attachment list
  3411. // called from upload page
  3412. this.add2attachment_list = function(name, att, upload_id)
  3413. {
  3414. if (upload_id)
  3415. this.triggerEvent('fileuploaded', {name: name, attachment: att, id: upload_id});
  3416. if (!this.env.attachments)
  3417. this.env.attachments = {};
  3418. if (upload_id && this.env.attachments[upload_id])
  3419. delete this.env.attachments[upload_id];
  3420. this.env.attachments[name] = att;
  3421. if (!this.gui_objects.attachmentlist)
  3422. return false;
  3423. if (!att.complete && this.env.loadingicon)
  3424. att.html = '<img src="'+this.env.loadingicon+'" alt="" class="uploading" />' + att.html;
  3425. if (!att.complete && att.frame)
  3426. att.html = '<a title="'+this.get_label('cancel')+'" onclick="return rcmail.cancel_attachment_upload(\''+name+'\', \''+att.frame+'\');" href="#cancelupload" class="cancelupload">'
  3427. + (this.env.cancelicon ? '<img src="'+this.env.cancelicon+'" alt="'+this.get_label('cancel')+'" />' : this.get_label('cancel')) + '</a>' + att.html;
  3428. var indicator, li = $('<li>');
  3429. li.attr('id', name)
  3430. .addClass(att.classname)
  3431. .html(att.html)
  3432. .on('mouseover', function() { rcube_webmail.long_subject_title_ex(this); });
  3433. // replace indicator's li
  3434. if (upload_id && (indicator = document.getElementById(upload_id))) {
  3435. li.replaceAll(indicator);
  3436. }
  3437. else { // add new li
  3438. li.appendTo(this.gui_objects.attachmentlist);
  3439. }
  3440. // set tabindex attribute
  3441. var tabindex = $(this.gui_objects.attachmentlist).attr('data-tabindex') || '0';
  3442. li.find('a').attr('tabindex', tabindex);
  3443. return true;
  3444. };
  3445. this.remove_from_attachment_list = function(name)
  3446. {
  3447. if (this.env.attachments) {
  3448. delete this.env.attachments[name];
  3449. $('#'+name).remove();
  3450. }
  3451. };
  3452. this.remove_attachment = function(name)
  3453. {
  3454. if (name && this.env.attachments[name])
  3455. this.http_post('remove-attachment', { _id:this.env.compose_id, _file:name });
  3456. return true;
  3457. };
  3458. this.cancel_attachment_upload = function(name, frame_name)
  3459. {
  3460. if (!name || !frame_name)
  3461. return false;
  3462. this.remove_from_attachment_list(name);
  3463. $("iframe[name='"+frame_name+"']").remove();
  3464. return false;
  3465. };
  3466. this.upload_progress_start = function(action, name)
  3467. {
  3468. setTimeout(function() { ref.http_request(action, {_progress: name}); },
  3469. this.env.upload_progress_time * 1000);
  3470. };
  3471. this.upload_progress_update = function(param)
  3472. {
  3473. var elem = $('#'+param.name + ' > span');
  3474. if (!elem.length || !param.text)
  3475. return;
  3476. elem.text(param.text);
  3477. if (!param.done)
  3478. this.upload_progress_start(param.action, param.name);
  3479. };
  3480. // send remote request to add a new contact
  3481. this.add_contact = function(value)
  3482. {
  3483. if (value)
  3484. this.http_post('addcontact', {_address: value});
  3485. return true;
  3486. };
  3487. // send remote request to search mail or contacts
  3488. this.qsearch = function(value)
  3489. {
  3490. if (value != '') {
  3491. var r, lock = this.set_busy(true, 'searching'),
  3492. url = this.search_params(value),
  3493. action = this.env.action == 'compose' && this.contact_list ? 'search-contacts' : 'search';
  3494. if (this.message_list)
  3495. this.clear_message_list();
  3496. else if (this.contact_list)
  3497. this.list_contacts_clear();
  3498. if (this.env.source)
  3499. url._source = this.env.source;
  3500. if (this.env.group)
  3501. url._gid = this.env.group;
  3502. // reset vars
  3503. this.env.current_page = 1;
  3504. r = this.http_request(action, url, lock);
  3505. this.env.qsearch = {lock: lock, request: r};
  3506. this.enable_command('set-listmode', this.env.threads && (this.env.search_scope || 'base') == 'base');
  3507. return true;
  3508. }
  3509. return false;
  3510. };
  3511. this.continue_search = function(request_id)
  3512. {
  3513. var lock = this.set_busy(true, 'stillsearching');
  3514. setTimeout(function() {
  3515. var url = ref.search_params();
  3516. url._continue = request_id;
  3517. ref.env.qsearch = { lock: lock, request: ref.http_request('search', url, lock) };
  3518. }, 100);
  3519. };
  3520. // build URL params for search
  3521. this.search_params = function(search, filter)
  3522. {
  3523. var n, url = {}, mods_arr = [],
  3524. mods = this.env.search_mods,
  3525. scope = this.env.search_scope || 'base',
  3526. mbox = scope == 'all' ? '*' : this.env.mailbox;
  3527. if (!filter && this.gui_objects.search_filter)
  3528. filter = this.gui_objects.search_filter.value;
  3529. if (!search && this.gui_objects.qsearchbox)
  3530. search = this.gui_objects.qsearchbox.value;
  3531. if (filter)
  3532. url._filter = filter;
  3533. if (search) {
  3534. url._q = search;
  3535. if (mods && this.message_list)
  3536. mods = mods[mbox] || mods['*'];
  3537. if (mods) {
  3538. for (n in mods)
  3539. mods_arr.push(n);
  3540. url._headers = mods_arr.join(',');
  3541. }
  3542. }
  3543. if (scope)
  3544. url._scope = scope;
  3545. if (mbox && scope != 'all')
  3546. url._mbox = mbox;
  3547. return url;
  3548. };
  3549. // reset quick-search form
  3550. this.reset_qsearch = function()
  3551. {
  3552. if (this.gui_objects.qsearchbox)
  3553. this.gui_objects.qsearchbox.value = '';
  3554. if (this.env.qsearch)
  3555. this.abort_request(this.env.qsearch);
  3556. this.env.qsearch = null;
  3557. this.env.search_request = null;
  3558. this.env.search_id = null;
  3559. this.enable_command('set-listmode', this.env.threads);
  3560. };
  3561. this.set_searchscope = function(scope)
  3562. {
  3563. var old = this.env.search_scope;
  3564. this.env.search_scope = scope;
  3565. // re-send search query with new scope
  3566. if (scope != old && this.env.search_request) {
  3567. if (!this.qsearch(this.gui_objects.qsearchbox.value) && this.env.search_filter && this.env.search_filter != 'ALL')
  3568. this.filter_mailbox(this.env.search_filter);
  3569. if (scope != 'all')
  3570. this.select_folder(this.env.mailbox, '', true);
  3571. }
  3572. };
  3573. this.set_searchmods = function(mods)
  3574. {
  3575. var mbox = this.env.mailbox,
  3576. scope = this.env.search_scope || 'base';
  3577. if (scope == 'all')
  3578. mbox = '*';
  3579. if (!this.env.search_mods)
  3580. this.env.search_mods = {};
  3581. if (mbox)
  3582. this.env.search_mods[mbox] = mods;
  3583. };
  3584. this.is_multifolder_listing = function()
  3585. {
  3586. return this.env.multifolder_listing !== undefined ? this.env.multifolder_listing :
  3587. (this.env.search_request && (this.env.search_scope || 'base') != 'base');
  3588. };
  3589. this.sent_successfully = function(type, msg, folders)
  3590. {
  3591. this.display_message(msg, type);
  3592. this.compose_skip_unsavedcheck = true;
  3593. if (this.env.extwin) {
  3594. this.lock_form(this.gui_objects.messageform);
  3595. var rc = this.opener();
  3596. if (rc) {
  3597. rc.display_message(msg, type);
  3598. // refresh the folder where sent message was saved or replied message comes from
  3599. if (folders && rc.env.task == 'mail' && rc.env.action == '' && $.inArray(rc.env.mailbox, folders) >= 0) {
  3600. rc.command('checkmail');
  3601. }
  3602. }
  3603. setTimeout(function() { window.close(); }, 1000);
  3604. }
  3605. else {
  3606. // before redirect we need to wait some time for Chrome (#1486177)
  3607. setTimeout(function() { ref.list_mailbox(); }, 500);
  3608. }
  3609. };
  3610. /*********************************************************/
  3611. /********* keyboard live-search methods *********/
  3612. /*********************************************************/
  3613. // handler for keyboard events on address-fields
  3614. this.ksearch_keydown = function(e, obj, props)
  3615. {
  3616. if (this.ksearch_timer)
  3617. clearTimeout(this.ksearch_timer);
  3618. var key = rcube_event.get_keycode(e),
  3619. mod = rcube_event.get_modifier(e);
  3620. switch (key) {
  3621. case 38: // arrow up
  3622. case 40: // arrow down
  3623. if (!this.ksearch_visible())
  3624. return;
  3625. var dir = key == 38 ? 1 : 0,
  3626. highlight = document.getElementById('rcmkSearchItem' + this.ksearch_selected);
  3627. if (!highlight)
  3628. highlight = this.ksearch_pane.__ul.firstChild;
  3629. if (highlight)
  3630. this.ksearch_select(dir ? highlight.previousSibling : highlight.nextSibling);
  3631. return rcube_event.cancel(e);
  3632. case 9: // tab
  3633. if (mod == SHIFT_KEY || !this.ksearch_visible()) {
  3634. this.ksearch_hide();
  3635. return;
  3636. }
  3637. case 13: // enter
  3638. if (!this.ksearch_visible())
  3639. return false;
  3640. // insert selected address and hide ksearch pane
  3641. this.insert_recipient(this.ksearch_selected);
  3642. this.ksearch_hide();
  3643. return rcube_event.cancel(e);
  3644. case 27: // escape
  3645. this.ksearch_hide();
  3646. return;
  3647. case 37: // left
  3648. case 39: // right
  3649. return;
  3650. }
  3651. // start timer
  3652. this.ksearch_timer = setTimeout(function(){ ref.ksearch_get_results(props); }, 200);
  3653. this.ksearch_input = obj;
  3654. return true;
  3655. };
  3656. this.ksearch_visible = function()
  3657. {
  3658. return this.ksearch_selected !== null && this.ksearch_selected !== undefined && this.ksearch_value;
  3659. };
  3660. this.ksearch_select = function(node)
  3661. {
  3662. if (this.ksearch_pane && node) {
  3663. this.ksearch_pane.find('li.selected').removeClass('selected').removeAttr('aria-selected');
  3664. }
  3665. if (node) {
  3666. $(node).addClass('selected').attr('aria-selected', 'true');
  3667. this.ksearch_selected = node._rcm_id;
  3668. $(this.ksearch_input).attr('aria-activedescendant', 'rcmkSearchItem' + this.ksearch_selected);
  3669. }
  3670. };
  3671. this.insert_recipient = function(id)
  3672. {
  3673. if (id === null || !this.env.contacts[id] || !this.ksearch_input)
  3674. return;
  3675. // get cursor pos
  3676. var inp_value = this.ksearch_input.value,
  3677. cpos = this.get_caret_pos(this.ksearch_input),
  3678. p = inp_value.lastIndexOf(this.ksearch_value, cpos),
  3679. trigger = false,
  3680. insert = '',
  3681. // replace search string with full address
  3682. pre = inp_value.substring(0, p),
  3683. end = inp_value.substring(p+this.ksearch_value.length, inp_value.length);
  3684. this.ksearch_destroy();
  3685. // insert all members of a group
  3686. if (typeof this.env.contacts[id] === 'object' && this.env.contacts[id].type == 'group') {
  3687. insert += this.env.contacts[id].name + this.env.recipients_delimiter;
  3688. this.group2expand[this.env.contacts[id].id] = $.extend({ input: this.ksearch_input }, this.env.contacts[id]);
  3689. this.http_request('mail/group-expand', {_source: this.env.contacts[id].source, _gid: this.env.contacts[id].id}, false);
  3690. }
  3691. else if (typeof this.env.contacts[id] === 'object' && this.env.contacts[id].name) {
  3692. insert = this.env.contacts[id].name + this.env.recipients_delimiter;
  3693. trigger = true;
  3694. }
  3695. else if (typeof this.env.contacts[id] === 'string') {
  3696. insert = this.env.contacts[id] + this.env.recipients_delimiter;
  3697. trigger = true;
  3698. }
  3699. this.ksearch_input.value = pre + insert + end;
  3700. // set caret to insert pos
  3701. this.set_caret_pos(this.ksearch_input, p + insert.length);
  3702. if (trigger) {
  3703. this.triggerEvent('autocomplete_insert', { field:this.ksearch_input, insert:insert, data:this.env.contacts[id] });
  3704. this.compose_type_activity++;
  3705. }
  3706. };
  3707. this.replace_group_recipients = function(id, recipients)
  3708. {
  3709. if (this.group2expand[id]) {
  3710. this.group2expand[id].input.value = this.group2expand[id].input.value.replace(this.group2expand[id].name, recipients);
  3711. this.triggerEvent('autocomplete_insert', { field:this.group2expand[id].input, insert:recipients });
  3712. this.group2expand[id] = null;
  3713. this.compose_type_activity++;
  3714. }
  3715. };
  3716. // address search processor
  3717. this.ksearch_get_results = function(props)
  3718. {
  3719. var inp_value = this.ksearch_input ? this.ksearch_input.value : null;
  3720. if (inp_value === null)
  3721. return;
  3722. if (this.ksearch_pane && this.ksearch_pane.is(":visible"))
  3723. this.ksearch_pane.hide();
  3724. // get string from current cursor pos to last comma
  3725. var cpos = this.get_caret_pos(this.ksearch_input),
  3726. p = inp_value.lastIndexOf(this.env.recipients_separator, cpos-1),
  3727. q = inp_value.substring(p+1, cpos),
  3728. min = this.env.autocomplete_min_length,
  3729. data = this.ksearch_data;
  3730. // trim query string
  3731. q = $.trim(q);
  3732. // Don't (re-)search if the last results are still active
  3733. if (q == this.ksearch_value)
  3734. return;
  3735. this.ksearch_destroy();
  3736. if (q.length && q.length < min) {
  3737. if (!this.ksearch_info) {
  3738. this.ksearch_info = this.display_message(
  3739. this.get_label('autocompletechars').replace('$min', min));
  3740. }
  3741. return;
  3742. }
  3743. var old_value = this.ksearch_value;
  3744. this.ksearch_value = q;
  3745. // ...string is empty
  3746. if (!q.length)
  3747. return;
  3748. // ...new search value contains old one and previous search was not finished or its result was empty
  3749. if (old_value && old_value.length && q.startsWith(old_value) && (!data || data.num <= 0) && this.env.contacts && !this.env.contacts.length)
  3750. return;
  3751. var sources = props && props.sources ? props.sources : [''];
  3752. var reqid = this.multi_thread_http_request({
  3753. items: sources,
  3754. threads: props && props.threads ? props.threads : 1,
  3755. action: props && props.action ? props.action : 'mail/autocomplete',
  3756. postdata: { _search:q, _source:'%s' },
  3757. lock: this.display_message(this.get_label('searching'), 'loading')
  3758. });
  3759. this.ksearch_data = { id:reqid, sources:sources.slice(), num:sources.length };
  3760. };
  3761. this.ksearch_query_results = function(results, search, reqid)
  3762. {
  3763. // trigger multi-thread http response callback
  3764. this.multi_thread_http_response(results, reqid);
  3765. // search stopped in meantime?
  3766. if (!this.ksearch_value)
  3767. return;
  3768. // ignore this outdated search response
  3769. if (this.ksearch_input && search != this.ksearch_value)
  3770. return;
  3771. // display search results
  3772. var i, id, len, ul, text, type, init,
  3773. value = this.ksearch_value,
  3774. maxlen = this.env.autocomplete_max ? this.env.autocomplete_max : 15;
  3775. // create results pane if not present
  3776. if (!this.ksearch_pane) {
  3777. ul = $('<ul>');
  3778. this.ksearch_pane = $('<div>').attr('id', 'rcmKSearchpane').attr('role', 'listbox')
  3779. .css({ position:'absolute', 'z-index':30000 }).append(ul).appendTo(document.body);
  3780. this.ksearch_pane.__ul = ul[0];
  3781. }
  3782. ul = this.ksearch_pane.__ul;
  3783. // remove all search results or add to existing list if parallel search
  3784. if (reqid && this.ksearch_pane.data('reqid') == reqid) {
  3785. maxlen -= ul.childNodes.length;
  3786. }
  3787. else {
  3788. this.ksearch_pane.data('reqid', reqid);
  3789. init = 1;
  3790. // reset content
  3791. ul.innerHTML = '';
  3792. this.env.contacts = [];
  3793. // move the results pane right under the input box
  3794. var pos = $(this.ksearch_input).offset();
  3795. this.ksearch_pane.css({ left:pos.left+'px', top:(pos.top + this.ksearch_input.offsetHeight)+'px', display: 'none'});
  3796. }
  3797. // add each result line to list
  3798. if (results && (len = results.length)) {
  3799. for (i=0; i < len && maxlen > 0; i++) {
  3800. text = typeof results[i] === 'object' ? (results[i].display || results[i].name) : results[i];
  3801. type = typeof results[i] === 'object' ? results[i].type : '';
  3802. id = i + this.env.contacts.length;
  3803. $('<li>').attr('id', 'rcmkSearchItem' + id)
  3804. .attr('role', 'option')
  3805. .html(this.quote_html(text.replace(new RegExp('('+RegExp.escape(value)+')', 'ig'), '##$1%%')).replace(/##([^%]+)%%/g, '<b>$1</b>'))
  3806. .addClass(type || '')
  3807. .appendTo(ul)
  3808. .mouseover(function() { ref.ksearch_select(this); })
  3809. .mouseup(function() { ref.ksearch_click(this); })
  3810. .get(0)._rcm_id = id;
  3811. maxlen -= 1;
  3812. }
  3813. }
  3814. if (ul.childNodes.length) {
  3815. // set the right aria-* attributes to the input field
  3816. $(this.ksearch_input)
  3817. .attr('aria-haspopup', 'true')
  3818. .attr('aria-expanded', 'true')
  3819. .attr('aria-owns', 'rcmKSearchpane');
  3820. this.ksearch_pane.show();
  3821. // select the first
  3822. if (!this.env.contacts.length) {
  3823. this.ksearch_select($('li:first', ul).get(0));
  3824. }
  3825. }
  3826. if (len)
  3827. this.env.contacts = this.env.contacts.concat(results);
  3828. if (this.ksearch_data.id == reqid)
  3829. this.ksearch_data.num--;
  3830. };
  3831. this.ksearch_click = function(node)
  3832. {
  3833. if (this.ksearch_input)
  3834. this.ksearch_input.focus();
  3835. this.insert_recipient(node._rcm_id);
  3836. this.ksearch_hide();
  3837. };
  3838. this.ksearch_blur = function()
  3839. {
  3840. if (this.ksearch_timer)
  3841. clearTimeout(this.ksearch_timer);
  3842. this.ksearch_input = null;
  3843. this.ksearch_hide();
  3844. };
  3845. this.ksearch_hide = function()
  3846. {
  3847. this.ksearch_selected = null;
  3848. this.ksearch_value = '';
  3849. if (this.ksearch_pane)
  3850. this.ksearch_pane.hide();
  3851. $(this.ksearch_input)
  3852. .attr('aria-haspopup', 'false')
  3853. .attr('aria-expanded', 'false')
  3854. .removeAttr('aria-activedescendant')
  3855. .removeAttr('aria-owns');
  3856. this.ksearch_destroy();
  3857. };
  3858. // Clears autocomplete data/requests
  3859. this.ksearch_destroy = function()
  3860. {
  3861. if (this.ksearch_data)
  3862. this.multi_thread_request_abort(this.ksearch_data.id);
  3863. if (this.ksearch_info)
  3864. this.hide_message(this.ksearch_info);
  3865. if (this.ksearch_msg)
  3866. this.hide_message(this.ksearch_msg);
  3867. this.ksearch_data = null;
  3868. this.ksearch_info = null;
  3869. this.ksearch_msg = null;
  3870. };
  3871. /*********************************************************/
  3872. /********* address book methods *********/
  3873. /*********************************************************/
  3874. this.contactlist_keypress = function(list)
  3875. {
  3876. if (list.key_pressed == list.DELETE_KEY)
  3877. this.command('delete');
  3878. };
  3879. this.contactlist_select = function(list)
  3880. {
  3881. if (this.preview_timer)
  3882. clearTimeout(this.preview_timer);
  3883. var n, id, sid, contact, writable = false,
  3884. source = this.env.source ? this.env.address_sources[this.env.source] : null;
  3885. // we don't have dblclick handler here, so use 200 instead of this.dblclick_time
  3886. if (id = list.get_single_selection())
  3887. this.preview_timer = setTimeout(function(){ ref.load_contact(id, 'show'); }, 200);
  3888. else if (this.env.contentframe)
  3889. this.show_contentframe(false);
  3890. if (list.selection.length) {
  3891. list.draggable = false;
  3892. // no source = search result, we'll need to detect if any of
  3893. // selected contacts are in writable addressbook to enable edit/delete
  3894. // we'll also need to know sources used in selection for copy
  3895. // and group-addmember operations (drag&drop)
  3896. this.env.selection_sources = [];
  3897. if (source) {
  3898. this.env.selection_sources.push(this.env.source);
  3899. }
  3900. for (n in list.selection) {
  3901. contact = list.data[list.selection[n]];
  3902. if (!source) {
  3903. sid = String(list.selection[n]).replace(/^[^-]+-/, '');
  3904. if (sid && this.env.address_sources[sid]) {
  3905. writable = writable || (!this.env.address_sources[sid].readonly && !contact.readonly);
  3906. this.env.selection_sources.push(sid);
  3907. }
  3908. }
  3909. else {
  3910. writable = writable || (!source.readonly && !contact.readonly);
  3911. }
  3912. if (contact._type != 'group')
  3913. list.draggable = true;
  3914. }
  3915. this.env.selection_sources = $.unique(this.env.selection_sources);
  3916. }
  3917. // if a group is currently selected, and there is at least one contact selected
  3918. // thend we can enable the group-remove-selected command
  3919. this.enable_command('group-remove-selected', this.env.group && list.selection.length > 0 && writable);
  3920. this.enable_command('compose', this.env.group || list.selection.length > 0);
  3921. this.enable_command('export-selected', 'copy', list.selection.length > 0);
  3922. this.enable_command('edit', id && writable);
  3923. this.enable_command('delete', 'move', list.selection.length > 0 && writable);
  3924. return false;
  3925. };
  3926. this.list_contacts = function(src, group, page)
  3927. {
  3928. var win, folder, url = {},
  3929. target = window;
  3930. if (!src)
  3931. src = this.env.source;
  3932. if (page && this.current_page == page && src == this.env.source && group == this.env.group)
  3933. return false;
  3934. if (src != this.env.source) {
  3935. page = this.env.current_page = 1;
  3936. this.reset_qsearch();
  3937. }
  3938. else if (group != this.env.group)
  3939. page = this.env.current_page = 1;
  3940. if (this.env.search_id)
  3941. folder = 'S'+this.env.search_id;
  3942. else if (!this.env.search_request)
  3943. folder = group ? 'G'+src+group : src;
  3944. this.env.source = src;
  3945. this.env.group = group;
  3946. // truncate groups listing stack
  3947. var index = $.inArray(this.env.group, this.env.address_group_stack);
  3948. if (index < 0)
  3949. this.env.address_group_stack = [];
  3950. else
  3951. this.env.address_group_stack = this.env.address_group_stack.slice(0,index);
  3952. // make sure the current group is on top of the stack
  3953. if (this.env.group) {
  3954. this.env.address_group_stack.push(this.env.group);
  3955. // mark the first group on the stack as selected in the directory list
  3956. folder = 'G'+src+this.env.address_group_stack[0];
  3957. }
  3958. else if (this.gui_objects.addresslist_title) {
  3959. $(this.gui_objects.addresslist_title).html(this.get_label('contacts'));
  3960. }
  3961. if (!this.env.search_id)
  3962. this.select_folder(folder, '', true);
  3963. // load contacts remotely
  3964. if (this.gui_objects.contactslist) {
  3965. this.list_contacts_remote(src, group, page);
  3966. return;
  3967. }
  3968. if (win = this.get_frame_window(this.env.contentframe)) {
  3969. target = win;
  3970. url._framed = 1;
  3971. }
  3972. if (group)
  3973. url._gid = group;
  3974. if (page)
  3975. url._page = page;
  3976. if (src)
  3977. url._source = src;
  3978. // also send search request to get the correct listing
  3979. if (this.env.search_request)
  3980. url._search = this.env.search_request;
  3981. this.set_busy(true, 'loading');
  3982. this.location_href(url, target);
  3983. };
  3984. // send remote request to load contacts list
  3985. this.list_contacts_remote = function(src, group, page)
  3986. {
  3987. // clear message list first
  3988. this.list_contacts_clear();
  3989. // send request to server
  3990. var url = {}, lock = this.set_busy(true, 'loading');
  3991. if (src)
  3992. url._source = src;
  3993. if (page)
  3994. url._page = page;
  3995. if (group)
  3996. url._gid = group;
  3997. this.env.source = src;
  3998. this.env.group = group;
  3999. // also send search request to get the right records
  4000. if (this.env.search_request)
  4001. url._search = this.env.search_request;
  4002. this.http_request(this.env.task == 'mail' ? 'list-contacts' : 'list', url, lock);
  4003. };
  4004. this.list_contacts_clear = function()
  4005. {
  4006. this.contact_list.data = {};
  4007. this.contact_list.clear(true);
  4008. this.show_contentframe(false);
  4009. this.enable_command('delete', 'move', 'copy', false);
  4010. this.enable_command('compose', this.env.group ? true : false);
  4011. };
  4012. this.set_group_prop = function(prop)
  4013. {
  4014. if (this.gui_objects.addresslist_title) {
  4015. var boxtitle = $(this.gui_objects.addresslist_title).html(''); // clear contents
  4016. // add link to pop back to parent group
  4017. if (this.env.address_group_stack.length > 1) {
  4018. $('<a href="#list">...</a>')
  4019. .attr('title', this.gettext('uponelevel'))
  4020. .addClass('poplink')
  4021. .appendTo(boxtitle)
  4022. .click(function(e){ return ref.command('popgroup','',this); });
  4023. boxtitle.append('&nbsp;&raquo;&nbsp;');
  4024. }
  4025. boxtitle.append($('<span>').text(prop.name));
  4026. }
  4027. this.triggerEvent('groupupdate', prop);
  4028. };
  4029. // load contact record
  4030. this.load_contact = function(cid, action, framed)
  4031. {
  4032. var win, url = {}, target = window,
  4033. rec = this.contact_list ? this.contact_list.data[cid] : null;
  4034. if (win = this.get_frame_window(this.env.contentframe)) {
  4035. url._framed = 1;
  4036. target = win;
  4037. this.show_contentframe(true);
  4038. // load dummy content, unselect selected row(s)
  4039. if (!cid)
  4040. this.contact_list.clear_selection();
  4041. this.enable_command('compose', rec && rec.email);
  4042. this.enable_command('export-selected', rec && rec._type != 'group');
  4043. }
  4044. else if (framed)
  4045. return false;
  4046. if (action && (cid || action == 'add') && !this.drag_active) {
  4047. if (this.env.group)
  4048. url._gid = this.env.group;
  4049. url._action = action;
  4050. url._source = this.env.source;
  4051. url._cid = cid;
  4052. this.location_href(url, target, true);
  4053. }
  4054. return true;
  4055. };
  4056. // add/delete member to/from the group
  4057. this.group_member_change = function(what, cid, source, gid)
  4058. {
  4059. if (what != 'add')
  4060. what = 'del';
  4061. var label = this.get_label(what == 'add' ? 'addingmember' : 'removingmember'),
  4062. lock = this.display_message(label, 'loading'),
  4063. post_data = {_cid: cid, _source: source, _gid: gid};
  4064. this.http_post('group-'+what+'members', post_data, lock);
  4065. };
  4066. this.contacts_drag_menu = function(e, to)
  4067. {
  4068. var dest = to.type == 'group' ? to.source : to.id,
  4069. source = this.env.source;
  4070. if (!this.env.address_sources[dest] || this.env.address_sources[dest].readonly)
  4071. return true;
  4072. // search result may contain contacts from many sources, but if there is only one...
  4073. if (source == '' && this.env.selection_sources.length == 1)
  4074. source = this.env.selection_sources[0];
  4075. if (to.type == 'group' && dest == source) {
  4076. var cid = this.contact_list.get_selection().join(',');
  4077. this.group_member_change('add', cid, dest, to.id);
  4078. return true;
  4079. }
  4080. // move action is not possible, "redirect" to copy if menu wasn't requested
  4081. else if (!this.commands.move && rcube_event.get_modifier(e) != SHIFT_KEY) {
  4082. this.copy_contacts(to);
  4083. return true;
  4084. }
  4085. return this.drag_menu(e, to);
  4086. };
  4087. // copy contact(s) to the specified target (group or directory)
  4088. this.copy_contacts = function(to)
  4089. {
  4090. var dest = to.type == 'group' ? to.source : to.id,
  4091. source = this.env.source,
  4092. group = this.env.group ? this.env.group : '',
  4093. cid = this.contact_list.get_selection().join(',');
  4094. if (!cid || !this.env.address_sources[dest] || this.env.address_sources[dest].readonly)
  4095. return;
  4096. // search result may contain contacts from many sources, but if there is only one...
  4097. if (source == '' && this.env.selection_sources.length == 1)
  4098. source = this.env.selection_sources[0];
  4099. // tagret is a group
  4100. if (to.type == 'group') {
  4101. if (dest == source)
  4102. return;
  4103. var lock = this.display_message(this.get_label('copyingcontact'), 'loading'),
  4104. post_data = {_cid: cid, _source: this.env.source, _to: dest, _togid: to.id, _gid: group};
  4105. this.http_post('copy', post_data, lock);
  4106. }
  4107. // target is an addressbook
  4108. else if (to.id != source) {
  4109. var lock = this.display_message(this.get_label('copyingcontact'), 'loading'),
  4110. post_data = {_cid: cid, _source: this.env.source, _to: to.id, _gid: group};
  4111. this.http_post('copy', post_data, lock);
  4112. }
  4113. };
  4114. // move contact(s) to the specified target (group or directory)
  4115. this.move_contacts = function(to)
  4116. {
  4117. var dest = to.type == 'group' ? to.source : to.id,
  4118. source = this.env.source,
  4119. group = this.env.group ? this.env.group : '';
  4120. if (!this.env.address_sources[dest] || this.env.address_sources[dest].readonly)
  4121. return;
  4122. // search result may contain contacts from many sources, but if there is only one...
  4123. if (source == '' && this.env.selection_sources.length == 1)
  4124. source = this.env.selection_sources[0];
  4125. if (to.type == 'group') {
  4126. if (dest == source)
  4127. return;
  4128. this._with_selected_contacts('move', {_to: dest, _togid: to.id});
  4129. }
  4130. // target is an addressbook
  4131. else if (to.id != source)
  4132. this._with_selected_contacts('move', {_to: to.id});
  4133. };
  4134. // delete contact(s)
  4135. this.delete_contacts = function()
  4136. {
  4137. var undelete = this.env.source && this.env.address_sources[this.env.source].undelete;
  4138. if (!undelete && !confirm(this.get_label('deletecontactconfirm')))
  4139. return;
  4140. return this._with_selected_contacts('delete');
  4141. };
  4142. this._with_selected_contacts = function(action, post_data)
  4143. {
  4144. var selection = this.contact_list ? this.contact_list.get_selection() : [];
  4145. // exit if no contact specified or if selection is empty
  4146. if (!selection.length && !this.env.cid)
  4147. return;
  4148. var n, a_cids = [],
  4149. label = action == 'delete' ? 'contactdeleting' : 'movingcontact',
  4150. lock = this.display_message(this.get_label(label), 'loading');
  4151. if (this.env.cid)
  4152. a_cids.push(this.env.cid);
  4153. else {
  4154. for (n=0; n<selection.length; n++) {
  4155. id = selection[n];
  4156. a_cids.push(id);
  4157. this.contact_list.remove_row(id, (n == selection.length-1));
  4158. }
  4159. // hide content frame if we delete the currently displayed contact
  4160. if (selection.length == 1)
  4161. this.show_contentframe(false);
  4162. }
  4163. if (!post_data)
  4164. post_data = {};
  4165. post_data._source = this.env.source;
  4166. post_data._from = this.env.action;
  4167. post_data._cid = a_cids.join(',');
  4168. if (this.env.group)
  4169. post_data._gid = this.env.group;
  4170. // also send search request to get the right records from the next page
  4171. if (this.env.search_request)
  4172. post_data._search = this.env.search_request;
  4173. // send request to server
  4174. this.http_post(action, post_data, lock)
  4175. return true;
  4176. };
  4177. // update a contact record in the list
  4178. this.update_contact_row = function(cid, cols_arr, newcid, source, data)
  4179. {
  4180. var list = this.contact_list;
  4181. cid = this.html_identifier(cid);
  4182. // when in searching mode, concat cid with the source name
  4183. if (!list.rows[cid]) {
  4184. cid = cid + '-' + source;
  4185. if (newcid)
  4186. newcid = newcid + '-' + source;
  4187. }
  4188. list.update_row(cid, cols_arr, newcid, true);
  4189. list.data[cid] = data;
  4190. };
  4191. // add row to contacts list
  4192. this.add_contact_row = function(cid, cols, classes, data)
  4193. {
  4194. if (!this.gui_objects.contactslist)
  4195. return false;
  4196. var c, col, list = this.contact_list,
  4197. row = { cols:[] };
  4198. row.id = 'rcmrow' + this.html_identifier(cid);
  4199. row.className = 'contact ' + (classes || '');
  4200. if (list.in_selection(cid))
  4201. row.className += ' selected';
  4202. // add each submitted col
  4203. for (c in cols) {
  4204. col = {};
  4205. col.className = String(c).toLowerCase();
  4206. col.innerHTML = cols[c];
  4207. row.cols.push(col);
  4208. }
  4209. // store data in list member
  4210. list.data[cid] = data;
  4211. list.insert_row(row);
  4212. this.enable_command('export', list.rowcount > 0);
  4213. };
  4214. this.init_contact_form = function()
  4215. {
  4216. var col;
  4217. if (this.env.coltypes) {
  4218. this.set_photo_actions($('#ff_photo').val());
  4219. for (col in this.env.coltypes)
  4220. this.init_edit_field(col, null);
  4221. }
  4222. $('.contactfieldgroup .row a.deletebutton').click(function() {
  4223. ref.delete_edit_field(this);
  4224. return false;
  4225. });
  4226. $('select.addfieldmenu').change(function() {
  4227. ref.insert_edit_field($(this).val(), $(this).attr('rel'), this);
  4228. this.selectedIndex = 0;
  4229. });
  4230. // enable date pickers on date fields
  4231. if ($.datepicker && this.env.date_format) {
  4232. $.datepicker.setDefaults({
  4233. dateFormat: this.env.date_format,
  4234. changeMonth: true,
  4235. changeYear: true,
  4236. yearRange: '-100:+10',
  4237. showOtherMonths: true,
  4238. selectOtherMonths: true,
  4239. onSelect: function(dateText) { $(this).focus().val(dateText) }
  4240. });
  4241. $('input.datepicker').datepicker();
  4242. }
  4243. // Submit search form on Enter
  4244. if (this.env.action == 'search')
  4245. $(this.gui_objects.editform).append($('<input type="submit">').hide())
  4246. .submit(function() { $('input.mainaction').click(); return false; });
  4247. };
  4248. // group creation dialog
  4249. this.group_create = function()
  4250. {
  4251. var input = $('<input>').attr('type', 'text'),
  4252. content = $('<label>').text(this.get_label('namex')).append(input);
  4253. this.show_popup_dialog(content, this.get_label('newgroup'),
  4254. [{
  4255. text: this.get_label('save'),
  4256. click: function() {
  4257. var name;
  4258. if (name = input.val()) {
  4259. ref.http_post('group-create', {_source: ref.env.source, _name: name},
  4260. ref.set_busy(true, 'loading'));
  4261. }
  4262. $(this).dialog('close');
  4263. }
  4264. }]
  4265. );
  4266. };
  4267. // group rename dialog
  4268. this.group_rename = function()
  4269. {
  4270. if (!this.env.group)
  4271. return;
  4272. var group_name = this.env.contactgroups['G' + this.env.source + this.env.group].name,
  4273. input = $('<input>').attr('type', 'text').val(group_name),
  4274. content = $('<label>').text(this.get_label('namex')).append(input);
  4275. this.show_popup_dialog(content, this.get_label('grouprename'),
  4276. [{
  4277. text: this.get_label('save'),
  4278. click: function() {
  4279. var name;
  4280. if ((name = input.val()) && name != group_name) {
  4281. ref.http_post('group-rename', {_source: ref.env.source, _gid: ref.env.group, _name: name},
  4282. ref.set_busy(true, 'loading'));
  4283. }
  4284. $(this).dialog('close');
  4285. }
  4286. }],
  4287. {open: function() { input.select(); }}
  4288. );
  4289. };
  4290. this.group_delete = function()
  4291. {
  4292. if (this.env.group && confirm(this.get_label('deletegroupconfirm'))) {
  4293. var lock = this.set_busy(true, 'groupdeleting');
  4294. this.http_post('group-delete', {_source: this.env.source, _gid: this.env.group}, lock);
  4295. }
  4296. };
  4297. // callback from server upon group-delete command
  4298. this.remove_group_item = function(prop)
  4299. {
  4300. var key = 'G'+prop.source+prop.id;
  4301. if (this.treelist.remove(key)) {
  4302. this.triggerEvent('group_delete', { source:prop.source, id:prop.id });
  4303. delete this.env.contactfolders[key];
  4304. delete this.env.contactgroups[key];
  4305. }
  4306. this.list_contacts(prop.source, 0);
  4307. };
  4308. //remove selected contacts from current active group
  4309. this.group_remove_selected = function()
  4310. {
  4311. this.http_post('group-delmembers', {_cid: this.contact_list.selection,
  4312. _source: this.env.source, _gid: this.env.group});
  4313. };
  4314. //callback after deleting contact(s) from current group
  4315. this.remove_group_contacts = function(props)
  4316. {
  4317. if (this.env.group !== undefined && (this.env.group === props.gid)) {
  4318. var n, selection = this.contact_list.get_selection();
  4319. for (n=0; n<selection.length; n++) {
  4320. id = selection[n];
  4321. this.contact_list.remove_row(id, (n == selection.length-1));
  4322. }
  4323. }
  4324. };
  4325. // callback for creating a new contact group
  4326. this.insert_contact_group = function(prop)
  4327. {
  4328. prop.type = 'group';
  4329. var key = 'G'+prop.source+prop.id,
  4330. link = $('<a>').attr('href', '#')
  4331. .attr('rel', prop.source+':'+prop.id)
  4332. .click(function() { return ref.command('listgroup', prop, this); })
  4333. .html(prop.name);
  4334. this.env.contactfolders[key] = this.env.contactgroups[key] = prop;
  4335. this.treelist.insert({ id:key, html:link, classes:['contactgroup'] }, prop.source, 'contactgroup');
  4336. this.triggerEvent('group_insert', { id:prop.id, source:prop.source, name:prop.name, li:this.treelist.get_item(key) });
  4337. };
  4338. // callback for renaming a contact group
  4339. this.update_contact_group = function(prop)
  4340. {
  4341. var key = 'G'+prop.source+prop.id,
  4342. newnode = {};
  4343. // group ID has changed, replace link node and identifiers
  4344. if (prop.newid) {
  4345. var newkey = 'G'+prop.source+prop.newid,
  4346. newprop = $.extend({}, prop);
  4347. this.env.contactfolders[newkey] = this.env.contactfolders[key];
  4348. this.env.contactfolders[newkey].id = prop.newid;
  4349. this.env.group = prop.newid;
  4350. delete this.env.contactfolders[key];
  4351. delete this.env.contactgroups[key];
  4352. newprop.id = prop.newid;
  4353. newprop.type = 'group';
  4354. newnode.id = newkey;
  4355. newnode.html = $('<a>').attr('href', '#')
  4356. .attr('rel', prop.source+':'+prop.newid)
  4357. .click(function() { return ref.command('listgroup', newprop, this); })
  4358. .html(prop.name);
  4359. }
  4360. // update displayed group name
  4361. else {
  4362. $(this.treelist.get_item(key)).children().first().html(prop.name);
  4363. this.env.contactfolders[key].name = this.env.contactgroups[key].name = prop.name;
  4364. }
  4365. // update list node and re-sort it
  4366. this.treelist.update(key, newnode, true);
  4367. this.triggerEvent('group_update', { id:prop.id, source:prop.source, name:prop.name, li:this.treelist.get_item(key), newid:prop.newid });
  4368. };
  4369. this.update_group_commands = function()
  4370. {
  4371. var source = this.env.source != '' ? this.env.address_sources[this.env.source] : null,
  4372. supported = source && source.groups && !source.readonly;
  4373. this.enable_command('group-create', supported);
  4374. this.enable_command('group-rename', 'group-delete', supported && this.env.group);
  4375. };
  4376. this.init_edit_field = function(col, elem)
  4377. {
  4378. var label = this.env.coltypes[col].label;
  4379. if (!elem)
  4380. elem = $('.ff_' + col);
  4381. if (label)
  4382. elem.placeholder(label);
  4383. };
  4384. this.insert_edit_field = function(col, section, menu)
  4385. {
  4386. // just make pre-defined input field visible
  4387. var elem = $('#ff_'+col);
  4388. if (elem.length) {
  4389. elem.show().focus();
  4390. $(menu).children('option[value="'+col+'"]').prop('disabled', true);
  4391. }
  4392. else {
  4393. var lastelem = $('.ff_'+col),
  4394. appendcontainer = $('#contactsection'+section+' .contactcontroller'+col);
  4395. if (!appendcontainer.length) {
  4396. var sect = $('#contactsection'+section),
  4397. lastgroup = $('.contactfieldgroup', sect).last();
  4398. appendcontainer = $('<fieldset>').addClass('contactfieldgroup contactcontroller'+col);
  4399. if (lastgroup.length)
  4400. appendcontainer.insertAfter(lastgroup);
  4401. else
  4402. sect.prepend(appendcontainer);
  4403. }
  4404. if (appendcontainer.length && appendcontainer.get(0).nodeName == 'FIELDSET') {
  4405. var input, colprop = this.env.coltypes[col],
  4406. input_id = 'ff_' + col + (colprop.count || 0),
  4407. row = $('<div>').addClass('row'),
  4408. cell = $('<div>').addClass('contactfieldcontent data'),
  4409. label = $('<div>').addClass('contactfieldlabel label');
  4410. if (colprop.subtypes_select)
  4411. label.html(colprop.subtypes_select);
  4412. else
  4413. label.html('<label for="' + input_id + '">' + colprop.label + '</label>');
  4414. var name_suffix = colprop.limit != 1 ? '[]' : '';
  4415. if (colprop.type == 'text' || colprop.type == 'date') {
  4416. input = $('<input>')
  4417. .addClass('ff_'+col)
  4418. .attr({type: 'text', name: '_'+col+name_suffix, size: colprop.size, id: input_id})
  4419. .appendTo(cell);
  4420. this.init_edit_field(col, input);
  4421. if (colprop.type == 'date' && $.datepicker)
  4422. input.datepicker();
  4423. }
  4424. else if (colprop.type == 'textarea') {
  4425. input = $('<textarea>')
  4426. .addClass('ff_'+col)
  4427. .attr({ name: '_'+col+name_suffix, cols:colprop.size, rows:colprop.rows, id: input_id })
  4428. .appendTo(cell);
  4429. this.init_edit_field(col, input);
  4430. }
  4431. else if (colprop.type == 'composite') {
  4432. var i, childcol, cp, first, templ, cols = [], suffices = [];
  4433. // read template for composite field order
  4434. if ((templ = this.env[col+'_template'])) {
  4435. for (i=0; i < templ.length; i++) {
  4436. cols.push(templ[i][1]);
  4437. suffices.push(templ[i][2]);
  4438. }
  4439. }
  4440. else { // list fields according to appearance in colprop
  4441. for (childcol in colprop.childs)
  4442. cols.push(childcol);
  4443. }
  4444. for (i=0; i < cols.length; i++) {
  4445. childcol = cols[i];
  4446. cp = colprop.childs[childcol];
  4447. input = $('<input>')
  4448. .addClass('ff_'+childcol)
  4449. .attr({ type: 'text', name: '_'+childcol+name_suffix, size: cp.size })
  4450. .appendTo(cell);
  4451. cell.append(suffices[i] || " ");
  4452. this.init_edit_field(childcol, input);
  4453. if (!first) first = input;
  4454. }
  4455. input = first; // set focus to the first of this composite fields
  4456. }
  4457. else if (colprop.type == 'select') {
  4458. input = $('<select>')
  4459. .addClass('ff_'+col)
  4460. .attr({ 'name': '_'+col+name_suffix, id: input_id })
  4461. .appendTo(cell);
  4462. var options = input.attr('options');
  4463. options[options.length] = new Option('---', '');
  4464. if (colprop.options)
  4465. $.each(colprop.options, function(i, val){ options[options.length] = new Option(val, i); });
  4466. }
  4467. if (input) {
  4468. var delbutton = $('<a href="#del"></a>')
  4469. .addClass('contactfieldbutton deletebutton')
  4470. .attr({title: this.get_label('delete'), rel: col})
  4471. .html(this.env.delbutton)
  4472. .click(function(){ ref.delete_edit_field(this); return false })
  4473. .appendTo(cell);
  4474. row.append(label).append(cell).appendTo(appendcontainer.show());
  4475. input.first().focus();
  4476. // disable option if limit reached
  4477. if (!colprop.count) colprop.count = 0;
  4478. if (++colprop.count == colprop.limit && colprop.limit)
  4479. $(menu).children('option[value="'+col+'"]').prop('disabled', true);
  4480. }
  4481. }
  4482. }
  4483. };
  4484. this.delete_edit_field = function(elem)
  4485. {
  4486. var col = $(elem).attr('rel'),
  4487. colprop = this.env.coltypes[col],
  4488. fieldset = $(elem).parents('fieldset.contactfieldgroup'),
  4489. addmenu = fieldset.parent().find('select.addfieldmenu');
  4490. // just clear input but don't hide the last field
  4491. if (--colprop.count <= 0 && colprop.visible)
  4492. $(elem).parent().children('input').val('').blur();
  4493. else {
  4494. $(elem).parents('div.row').remove();
  4495. // hide entire fieldset if no more rows
  4496. if (!fieldset.children('div.row').length)
  4497. fieldset.hide();
  4498. }
  4499. // enable option in add-field selector or insert it if necessary
  4500. if (addmenu.length) {
  4501. var option = addmenu.children('option[value="'+col+'"]');
  4502. if (option.length)
  4503. option.prop('disabled', false);
  4504. else
  4505. option = $('<option>').attr('value', col).html(colprop.label).appendTo(addmenu);
  4506. addmenu.show();
  4507. }
  4508. };
  4509. this.upload_contact_photo = function(form)
  4510. {
  4511. if (form && form.elements._photo.value) {
  4512. this.async_upload_form(form, 'upload-photo', function(e) {
  4513. ref.set_busy(false, null, ref.file_upload_id);
  4514. });
  4515. // display upload indicator
  4516. this.file_upload_id = this.set_busy(true, 'uploading');
  4517. }
  4518. };
  4519. this.replace_contact_photo = function(id)
  4520. {
  4521. var img_src = id == '-del-' ? this.env.photo_placeholder :
  4522. this.env.comm_path + '&_action=photo&_source=' + this.env.source + '&_cid=' + (this.env.cid || 0) + '&_photo=' + id;
  4523. this.set_photo_actions(id);
  4524. $(this.gui_objects.contactphoto).children('img').attr('src', img_src);
  4525. };
  4526. this.photo_upload_end = function()
  4527. {
  4528. this.set_busy(false, null, this.file_upload_id);
  4529. delete this.file_upload_id;
  4530. };
  4531. this.set_photo_actions = function(id)
  4532. {
  4533. var n, buttons = this.buttons['upload-photo'];
  4534. for (n=0; buttons && n < buttons.length; n++)
  4535. $('a#'+buttons[n].id).html(this.get_label(id == '-del-' ? 'addphoto' : 'replacephoto'));
  4536. $('#ff_photo').val(id);
  4537. this.enable_command('upload-photo', this.env.coltypes.photo ? true : false);
  4538. this.enable_command('delete-photo', this.env.coltypes.photo && id != '-del-');
  4539. };
  4540. // load advanced search page
  4541. this.advanced_search = function()
  4542. {
  4543. var win, url = {_form: 1, _action: 'search'}, target = window;
  4544. if (win = this.get_frame_window(this.env.contentframe)) {
  4545. url._framed = 1;
  4546. target = win;
  4547. this.contact_list.clear_selection();
  4548. }
  4549. this.location_href(url, target, true);
  4550. return true;
  4551. };
  4552. // unselect directory/group
  4553. this.unselect_directory = function()
  4554. {
  4555. this.select_folder('');
  4556. this.enable_command('search-delete', false);
  4557. };
  4558. // callback for creating a new saved search record
  4559. this.insert_saved_search = function(name, id)
  4560. {
  4561. var key = 'S'+id,
  4562. link = $('<a>').attr('href', '#')
  4563. .attr('rel', id)
  4564. .click(function() { return ref.command('listsearch', id, this); })
  4565. .html(name),
  4566. prop = { name:name, id:id };
  4567. this.savedsearchlist.insert({ id:key, html:link, classes:['contactsearch'] }, null, 'contactsearch');
  4568. this.select_folder(key,'',true);
  4569. this.enable_command('search-delete', true);
  4570. this.env.search_id = id;
  4571. this.triggerEvent('abook_search_insert', prop);
  4572. };
  4573. // creates a dialog for saved search
  4574. this.search_create = function()
  4575. {
  4576. var input = $('<input>').attr('type', 'text'),
  4577. content = $('<label>').text(this.get_label('namex')).append(input);
  4578. this.show_popup_dialog(content, this.get_label('searchsave'),
  4579. [{
  4580. text: this.get_label('save'),
  4581. click: function() {
  4582. var name;
  4583. if (name = input.val()) {
  4584. ref.http_post('search-create', {_search: ref.env.search_request, _name: name},
  4585. ref.set_busy(true, 'loading'));
  4586. }
  4587. $(this).dialog('close');
  4588. }
  4589. }]
  4590. );
  4591. };
  4592. this.search_delete = function()
  4593. {
  4594. if (this.env.search_request) {
  4595. var lock = this.set_busy(true, 'savedsearchdeleting');
  4596. this.http_post('search-delete', {_sid: this.env.search_id}, lock);
  4597. }
  4598. };
  4599. // callback from server upon search-delete command
  4600. this.remove_search_item = function(id)
  4601. {
  4602. var li, key = 'S'+id;
  4603. if (this.savedsearchlist.remove(key)) {
  4604. this.triggerEvent('search_delete', { id:id, li:li });
  4605. }
  4606. this.env.search_id = null;
  4607. this.env.search_request = null;
  4608. this.list_contacts_clear();
  4609. this.reset_qsearch();
  4610. this.enable_command('search-delete', 'search-create', false);
  4611. };
  4612. this.listsearch = function(id)
  4613. {
  4614. var lock = this.set_busy(true, 'searching');
  4615. if (this.contact_list) {
  4616. this.list_contacts_clear();
  4617. }
  4618. this.reset_qsearch();
  4619. if (this.savedsearchlist) {
  4620. this.treelist.select('');
  4621. this.savedsearchlist.select('S'+id);
  4622. }
  4623. else
  4624. this.select_folder('S'+id, '', true);
  4625. // reset vars
  4626. this.env.current_page = 1;
  4627. this.http_request('search', {_sid: id}, lock);
  4628. };
  4629. /*********************************************************/
  4630. /********* user settings methods *********/
  4631. /*********************************************************/
  4632. // preferences section select and load options frame
  4633. this.section_select = function(list)
  4634. {
  4635. var win, id = list.get_single_selection(), target = window,
  4636. url = {_action: 'edit-prefs', _section: id};
  4637. if (id) {
  4638. if (win = this.get_frame_window(this.env.contentframe)) {
  4639. url._framed = 1;
  4640. target = win;
  4641. }
  4642. this.location_href(url, target, true);
  4643. }
  4644. return true;
  4645. };
  4646. this.identity_select = function(list)
  4647. {
  4648. var id;
  4649. if (id = list.get_single_selection()) {
  4650. this.enable_command('delete', list.rowcount > 1 && this.env.identities_level < 2);
  4651. this.load_identity(id, 'edit-identity');
  4652. }
  4653. };
  4654. // load identity record
  4655. this.load_identity = function(id, action)
  4656. {
  4657. if (action == 'edit-identity' && (!id || id == this.env.iid))
  4658. return false;
  4659. var win, target = window,
  4660. url = {_action: action, _iid: id};
  4661. if (win = this.get_frame_window(this.env.contentframe)) {
  4662. url._framed = 1;
  4663. target = win;
  4664. }
  4665. if (id || action == 'add-identity') {
  4666. this.location_href(url, target, true);
  4667. }
  4668. return true;
  4669. };
  4670. this.delete_identity = function(id)
  4671. {
  4672. // exit if no identity is specified or if selection is empty
  4673. var selection = this.identity_list.get_selection();
  4674. if (!(selection.length || this.env.iid))
  4675. return;
  4676. if (!id)
  4677. id = this.env.iid ? this.env.iid : selection[0];
  4678. // submit request with appended token
  4679. if (id && confirm(this.get_label('deleteidentityconfirm')))
  4680. this.http_post('settings/delete-identity', { _iid: id }, true);
  4681. };
  4682. this.update_identity_row = function(id, name, add)
  4683. {
  4684. var list = this.identity_list,
  4685. rid = this.html_identifier(id);
  4686. if (add) {
  4687. list.insert_row({ id:'rcmrow'+rid, cols:[ { className:'mail', innerHTML:name } ] });
  4688. list.select(rid);
  4689. }
  4690. else {
  4691. list.update_row(rid, [ name ]);
  4692. }
  4693. };
  4694. this.update_response_row = function(response, oldkey)
  4695. {
  4696. var list = this.responses_list;
  4697. if (list && oldkey) {
  4698. list.update_row(oldkey, [ response.name ], response.key, true);
  4699. }
  4700. else if (list) {
  4701. list.insert_row({ id:'rcmrow'+response.key, cols:[ { className:'name', innerHTML:response.name } ] });
  4702. list.select(response.key);
  4703. }
  4704. };
  4705. this.remove_response = function(key)
  4706. {
  4707. var frame;
  4708. if (this.env.textresponses) {
  4709. delete this.env.textresponses[key];
  4710. }
  4711. if (this.responses_list) {
  4712. this.responses_list.remove_row(key);
  4713. if (this.env.contentframe && (frame = this.get_frame_window(this.env.contentframe))) {
  4714. frame.location.href = this.env.blankpage;
  4715. }
  4716. }
  4717. this.enable_command('delete', false);
  4718. };
  4719. this.remove_identity = function(id)
  4720. {
  4721. var frame, list = this.identity_list,
  4722. rid = this.html_identifier(id);
  4723. if (list && id) {
  4724. list.remove_row(rid);
  4725. if (this.env.contentframe && (frame = this.get_frame_window(this.env.contentframe))) {
  4726. frame.location.href = this.env.blankpage;
  4727. }
  4728. }
  4729. this.enable_command('delete', false);
  4730. };
  4731. /*********************************************************/
  4732. /********* folder manager methods *********/
  4733. /*********************************************************/
  4734. this.init_subscription_list = function()
  4735. {
  4736. var delim = RegExp.escape(this.env.delimiter);
  4737. this.last_sub_rx = RegExp('['+delim+']?[^'+delim+']+$');
  4738. this.subscription_list = new rcube_treelist_widget(this.gui_objects.subscriptionlist, {
  4739. selectable: true,
  4740. id_prefix: 'rcmli',
  4741. id_encode: this.html_identifier_encode,
  4742. id_decode: this.html_identifier_decode
  4743. });
  4744. this.subscription_list
  4745. .addEventListener('select', function(node) { ref.subscription_select(node.id); })
  4746. .addEventListener('collapse', function(node) { ref.folder_collapsed(node) })
  4747. .addEventListener('expand', function(node) { ref.folder_collapsed(node) })
  4748. .draggable({cancel: 'li.mailbox.root'})
  4749. .droppable({
  4750. // @todo: find better way, accept callback is executed for every folder
  4751. // on the list when dragging starts (and stops), this is slow, but
  4752. // I didn't find a method to check droptarget on over event
  4753. accept: function(node) {
  4754. var source_folder = ref.folder_id2name($(node).attr('id')),
  4755. dest_folder = ref.folder_id2name(this.id),
  4756. source = ref.env.subscriptionrows[source_folder],
  4757. dest = ref.env.subscriptionrows[dest_folder];
  4758. return source && !source[2]
  4759. && dest_folder != source_folder.replace(ref.last_sub_rx, '')
  4760. && !dest_folder.startsWith(source_folder + ref.env.delimiter);
  4761. },
  4762. drop: function(e, ui) {
  4763. var source = ref.folder_id2name(ui.draggable.attr('id')),
  4764. dest = ref.folder_id2name(this.id);
  4765. ref.subscription_move_folder(source, dest);
  4766. }
  4767. });
  4768. };
  4769. this.folder_id2name = function(id)
  4770. {
  4771. return ref.html_identifier_decode(id.replace(/^rcmli/, ''));
  4772. };
  4773. this.subscription_select = function(id)
  4774. {
  4775. var folder;
  4776. if (id && id != '*' && (folder = this.env.subscriptionrows[id])) {
  4777. this.env.mailbox = id;
  4778. this.show_folder(id);
  4779. this.enable_command('delete-folder', !folder[2]);
  4780. }
  4781. else {
  4782. this.env.mailbox = null;
  4783. this.show_contentframe(false);
  4784. this.enable_command('delete-folder', 'purge', false);
  4785. }
  4786. };
  4787. this.subscription_move_folder = function(from, to)
  4788. {
  4789. if (from && to !== null && from != to && to != from.replace(this.last_sub_rx, '')) {
  4790. var path = from.split(this.env.delimiter),
  4791. basename = path.pop(),
  4792. newname = to === '' || to === '*' ? basename : to + this.env.delimiter + basename;
  4793. if (newname != from) {
  4794. this.http_post('rename-folder', {_folder_oldname: from, _folder_newname: newname},
  4795. this.set_busy(true, 'foldermoving'));
  4796. }
  4797. }
  4798. };
  4799. // tell server to create and subscribe a new mailbox
  4800. this.create_folder = function()
  4801. {
  4802. this.show_folder('', this.env.mailbox);
  4803. };
  4804. // delete a specific mailbox with all its messages
  4805. this.delete_folder = function(name)
  4806. {
  4807. if (!name)
  4808. name = this.env.mailbox;
  4809. if (name && confirm(this.get_label('deletefolderconfirm'))) {
  4810. this.http_post('delete-folder', {_mbox: name}, this.set_busy(true, 'folderdeleting'));
  4811. }
  4812. };
  4813. // Add folder row to the table and initialize it
  4814. this.add_folder_row = function (id, name, display_name, is_protected, subscribed, class_name, refrow, subfolders)
  4815. {
  4816. if (!this.gui_objects.subscriptionlist)
  4817. return false;
  4818. // disable drag-n-drop temporarily
  4819. this.subscription_list.draggable('destroy').droppable('destroy');
  4820. var row, n, tmp, tmp_name, rowid, collator, pos, p, parent = '',
  4821. folders = [], list = [], slist = [],
  4822. list_element = $(this.gui_objects.subscriptionlist);
  4823. row = refrow ? refrow : $($('li', list_element).get(1)).clone(true);
  4824. if (!row.length) {
  4825. // Refresh page if we don't have a table row to clone
  4826. this.goto_url('folders');
  4827. return false;
  4828. }
  4829. // set ID, reset css class
  4830. row.attr({id: 'rcmli' + this.html_identifier_encode(id), 'class': class_name});
  4831. if (!refrow || !refrow.length) {
  4832. // remove old subfolders and toggle
  4833. $('ul,div.treetoggle', row).remove();
  4834. }
  4835. // set folder name
  4836. $('a:first', row).text(display_name);
  4837. // update subscription checkbox
  4838. $('input[name="_subscribed[]"]:first', row).val(id)
  4839. .prop({checked: subscribed ? true : false, disabled: is_protected ? true : false});
  4840. // add to folder/row-ID map
  4841. this.env.subscriptionrows[id] = [name, display_name, false];
  4842. // copy folders data to an array for sorting
  4843. $.each(this.env.subscriptionrows, function(k, v) { v[3] = k; folders.push(v); });
  4844. try {
  4845. // use collator if supported (FF29, IE11, Opera15, Chrome24)
  4846. collator = new Intl.Collator(this.env.locale.replace('_', '-'));
  4847. }
  4848. catch (e) {};
  4849. // sort folders
  4850. folders.sort(function(a, b) {
  4851. var i, f1, f2,
  4852. path1 = a[0].split(ref.env.delimiter),
  4853. path2 = b[0].split(ref.env.delimiter),
  4854. len = path1.length;
  4855. for (i=0; i<len; i++) {
  4856. f1 = path1[i];
  4857. f2 = path2[i];
  4858. if (f1 !== f2) {
  4859. if (f2 === undefined)
  4860. return 1;
  4861. if (collator)
  4862. return collator.compare(f1, f2);
  4863. else
  4864. return f1 < f2 ? -1 : 1;
  4865. }
  4866. else if (i == len-1) {
  4867. return -1
  4868. }
  4869. }
  4870. });
  4871. for (n in folders) {
  4872. p = folders[n][3];
  4873. // protected folder
  4874. if (folders[n][2]) {
  4875. tmp_name = p + this.env.delimiter;
  4876. // prefix namespace cannot have subfolders (#1488349)
  4877. if (tmp_name == this.env.prefix_ns)
  4878. continue;
  4879. slist.push(p);
  4880. tmp = tmp_name;
  4881. }
  4882. // protected folder's child
  4883. else if (tmp && p.startsWith(tmp))
  4884. slist.push(p);
  4885. // other
  4886. else {
  4887. list.push(p);
  4888. tmp = null;
  4889. }
  4890. }
  4891. // check if subfolder of a protected folder
  4892. for (n=0; n<slist.length; n++) {
  4893. if (id.startsWith(slist[n] + this.env.delimiter))
  4894. rowid = slist[n];
  4895. }
  4896. // find folder position after sorting
  4897. for (n=0; !rowid && n<list.length; n++) {
  4898. if (n && list[n] == id)
  4899. rowid = list[n-1];
  4900. }
  4901. // add row to the table
  4902. if (rowid && (n = this.subscription_list.get_item(rowid, true))) {
  4903. // find parent folder
  4904. if (pos = id.lastIndexOf(this.env.delimiter)) {
  4905. parent = id.substring(0, pos);
  4906. parent = this.subscription_list.get_item(parent, true);
  4907. // add required tree elements to the parent if not already there
  4908. if (!$('div.treetoggle', parent).length) {
  4909. $('<div>&nbsp;</div>').addClass('treetoggle collapsed').appendTo(parent);
  4910. }
  4911. if (!$('ul', parent).length) {
  4912. $('<ul>').css('display', 'none').appendTo(parent);
  4913. }
  4914. }
  4915. if (parent && n == parent) {
  4916. $('ul:first', parent).append(row);
  4917. }
  4918. else {
  4919. while (p = $(n).parent().parent().get(0)) {
  4920. if (parent && p == parent)
  4921. break;
  4922. if (!$(p).is('li.mailbox'))
  4923. break;
  4924. n = p;
  4925. }
  4926. $(n).after(row);
  4927. }
  4928. }
  4929. else {
  4930. list_element.append(row);
  4931. }
  4932. // add subfolders
  4933. $.extend(this.env.subscriptionrows, subfolders || {});
  4934. // update list widget
  4935. this.subscription_list.reset(true);
  4936. this.subscription_select();
  4937. // expand parent
  4938. if (parent) {
  4939. this.subscription_list.expand(this.folder_id2name(parent.id));
  4940. }
  4941. row = row.get(0);
  4942. if (row.scrollIntoView)
  4943. row.scrollIntoView();
  4944. return row;
  4945. };
  4946. // replace an existing table row with a new folder line (with subfolders)
  4947. this.replace_folder_row = function(oldid, id, name, display_name, is_protected, class_name)
  4948. {
  4949. if (!this.gui_objects.subscriptionlist) {
  4950. if (this.is_framed)
  4951. return parent.rcmail.replace_folder_row(oldid, id, name, display_name, is_protected, class_name);
  4952. return false;
  4953. }
  4954. var subfolders = {},
  4955. row = this.subscription_list.get_item(oldid, true),
  4956. parent = $(row).parent(),
  4957. old_folder = this.env.subscriptionrows[oldid],
  4958. prefix_len_id = oldid.length,
  4959. prefix_len_name = old_folder[0].length,
  4960. subscribed = $('input[name="_subscribed[]"]:first', row).prop('checked');
  4961. // no renaming, only update class_name
  4962. if (oldid == id) {
  4963. $(row).attr('class', class_name || '');
  4964. return;
  4965. }
  4966. // update subfolders
  4967. $('li', row).each(function() {
  4968. var fname = ref.folder_id2name(this.id),
  4969. folder = ref.env.subscriptionrows[fname],
  4970. newid = id + fname.slice(prefix_len_id);
  4971. this.id = 'rcmli' + ref.html_identifier_encode(newid);
  4972. $('input[name="_subscribed[]"]:first', this).val(newid);
  4973. folder[0] = name + folder[0].slice(prefix_len_name);
  4974. subfolders[newid] = folder;
  4975. delete ref.env.subscriptionrows[fname];
  4976. });
  4977. // get row off the list
  4978. row = $(row).detach();
  4979. delete this.env.subscriptionrows[oldid];
  4980. // remove parent list/toggle elements if not needed
  4981. if (parent.get(0) != this.gui_objects.subscriptionlist && !$('li', parent).length) {
  4982. $('ul,div.treetoggle', parent.parent()).remove();
  4983. }
  4984. // move the existing table row
  4985. this.add_folder_row(id, name, display_name, is_protected, subscribed, class_name, row, subfolders);
  4986. };
  4987. // remove the table row of a specific mailbox from the table
  4988. this.remove_folder_row = function(folder)
  4989. {
  4990. var list = [], row = this.subscription_list.get_item(folder, true);
  4991. // get subfolders if any
  4992. $('li', row).each(function() { list.push(ref.folder_id2name(this.id)); });
  4993. // remove folder row (and subfolders)
  4994. this.subscription_list.remove(folder);
  4995. // update local list variable
  4996. list.push(folder);
  4997. $.each(list, function(i, v) { delete ref.env.subscriptionrows[v]; });
  4998. };
  4999. this.subscribe = function(folder)
  5000. {
  5001. if (folder) {
  5002. var lock = this.display_message(this.get_label('foldersubscribing'), 'loading');
  5003. this.http_post('subscribe', {_mbox: folder}, lock);
  5004. }
  5005. };
  5006. this.unsubscribe = function(folder)
  5007. {
  5008. if (folder) {
  5009. var lock = this.display_message(this.get_label('folderunsubscribing'), 'loading');
  5010. this.http_post('unsubscribe', {_mbox: folder}, lock);
  5011. }
  5012. };
  5013. // when user select a folder in manager
  5014. this.show_folder = function(folder, path, force)
  5015. {
  5016. var win, target = window,
  5017. url = '&_action=edit-folder&_mbox='+urlencode(folder);
  5018. if (path)
  5019. url += '&_path='+urlencode(path);
  5020. if (win = this.get_frame_window(this.env.contentframe)) {
  5021. target = win;
  5022. url += '&_framed=1';
  5023. }
  5024. if (String(target.location.href).indexOf(url) >= 0 && !force)
  5025. this.show_contentframe(true);
  5026. else
  5027. this.location_href(this.env.comm_path+url, target, true);
  5028. };
  5029. // disables subscription checkbox (for protected folder)
  5030. this.disable_subscription = function(folder)
  5031. {
  5032. var row = this.subscription_list.get_item(folder, true);
  5033. if (row)
  5034. $('input[name="_subscribed[]"]:first', row).prop('disabled', true);
  5035. };
  5036. this.folder_size = function(folder)
  5037. {
  5038. var lock = this.set_busy(true, 'loading');
  5039. this.http_post('folder-size', {_mbox: folder}, lock);
  5040. };
  5041. this.folder_size_update = function(size)
  5042. {
  5043. $('#folder-size').replaceWith(size);
  5044. };
  5045. /*********************************************************/
  5046. /********* GUI functionality *********/
  5047. /*********************************************************/
  5048. var init_button = function(cmd, prop)
  5049. {
  5050. var elm = document.getElementById(prop.id);
  5051. if (!elm)
  5052. return;
  5053. var preload = false;
  5054. if (prop.type == 'image') {
  5055. elm = elm.parentNode;
  5056. preload = true;
  5057. }
  5058. elm._command = cmd;
  5059. elm._id = prop.id;
  5060. if (prop.sel) {
  5061. elm.onmousedown = function(e) { return ref.button_sel(this._command, this._id); };
  5062. elm.onmouseup = function(e) { return ref.button_out(this._command, this._id); };
  5063. if (preload)
  5064. new Image().src = prop.sel;
  5065. }
  5066. if (prop.over) {
  5067. elm.onmouseover = function(e) { return ref.button_over(this._command, this._id); };
  5068. elm.onmouseout = function(e) { return ref.button_out(this._command, this._id); };
  5069. if (preload)
  5070. new Image().src = prop.over;
  5071. }
  5072. };
  5073. // set event handlers on registered buttons
  5074. this.init_buttons = function()
  5075. {
  5076. for (var cmd in this.buttons) {
  5077. if (typeof cmd !== 'string')
  5078. continue;
  5079. for (var i=0; i<this.buttons[cmd].length; i++) {
  5080. init_button(cmd, this.buttons[cmd][i]);
  5081. }
  5082. }
  5083. };
  5084. // set button to a specific state
  5085. this.set_button = function(command, state)
  5086. {
  5087. var n, button, obj, $obj, a_buttons = this.buttons[command],
  5088. len = a_buttons ? a_buttons.length : 0;
  5089. for (n=0; n<len; n++) {
  5090. button = a_buttons[n];
  5091. obj = document.getElementById(button.id);
  5092. if (!obj || button.status === state)
  5093. continue;
  5094. // get default/passive setting of the button
  5095. if (button.type == 'image' && !button.status) {
  5096. button.pas = obj._original_src ? obj._original_src : obj.src;
  5097. // respect PNG fix on IE browsers
  5098. if (obj.runtimeStyle && obj.runtimeStyle.filter && obj.runtimeStyle.filter.match(/src=['"]([^'"]+)['"]/))
  5099. button.pas = RegExp.$1;
  5100. }
  5101. else if (!button.status)
  5102. button.pas = String(obj.className);
  5103. button.status = state;
  5104. // set image according to button state
  5105. if (button.type == 'image' && button[state]) {
  5106. obj.src = button[state];
  5107. }
  5108. // set class name according to button state
  5109. else if (button[state] !== undefined) {
  5110. obj.className = button[state];
  5111. }
  5112. // disable/enable input buttons
  5113. if (button.type == 'input') {
  5114. obj.disabled = state == 'pas';
  5115. }
  5116. else if (button.type == 'uibutton') {
  5117. button.status = state;
  5118. $(obj).button('option', 'disabled', state == 'pas');
  5119. }
  5120. else {
  5121. $obj = $(obj);
  5122. $obj
  5123. .attr('tabindex', state == 'pas' || state == 'sel' ? '-1' : ($obj.attr('data-tabindex') || '0'))
  5124. .attr('aria-disabled', state == 'pas' || state == 'sel' ? 'true' : 'false');
  5125. }
  5126. }
  5127. };
  5128. // display a specific alttext
  5129. this.set_alttext = function(command, label)
  5130. {
  5131. var n, button, obj, link, a_buttons = this.buttons[command],
  5132. len = a_buttons ? a_buttons.length : 0;
  5133. for (n=0; n<len; n++) {
  5134. button = a_buttons[n];
  5135. obj = document.getElementById(button.id);
  5136. if (button.type == 'image' && obj) {
  5137. obj.setAttribute('alt', this.get_label(label));
  5138. if ((link = obj.parentNode) && link.tagName.toLowerCase() == 'a')
  5139. link.setAttribute('title', this.get_label(label));
  5140. }
  5141. else if (obj)
  5142. obj.setAttribute('title', this.get_label(label));
  5143. }
  5144. };
  5145. // mouse over button
  5146. this.button_over = function(command, id)
  5147. {
  5148. this.button_event(command, id, 'over');
  5149. };
  5150. // mouse down on button
  5151. this.button_sel = function(command, id)
  5152. {
  5153. this.button_event(command, id, 'sel');
  5154. };
  5155. // mouse out of button
  5156. this.button_out = function(command, id)
  5157. {
  5158. this.button_event(command, id, 'act');
  5159. };
  5160. // event of button
  5161. this.button_event = function(command, id, event)
  5162. {
  5163. var n, button, obj, a_buttons = this.buttons[command],
  5164. len = a_buttons ? a_buttons.length : 0;
  5165. for (n=0; n<len; n++) {
  5166. button = a_buttons[n];
  5167. if (button.id == id && button.status == 'act') {
  5168. if (button[event] && (obj = document.getElementById(button.id))) {
  5169. obj[button.type == 'image' ? 'src' : 'className'] = button[event];
  5170. }
  5171. if (event == 'sel') {
  5172. this.buttons_sel[id] = command;
  5173. }
  5174. }
  5175. }
  5176. };
  5177. // write to the document/window title
  5178. this.set_pagetitle = function(title)
  5179. {
  5180. if (title && document.title)
  5181. document.title = title;
  5182. };
  5183. // display a system message, list of types in common.css (below #message definition)
  5184. this.display_message = function(msg, type, timeout)
  5185. {
  5186. // pass command to parent window
  5187. if (this.is_framed())
  5188. return parent.rcmail.display_message(msg, type, timeout);
  5189. if (!this.gui_objects.message) {
  5190. // save message in order to display after page loaded
  5191. if (type != 'loading')
  5192. this.pending_message = [msg, type, timeout];
  5193. return 1;
  5194. }
  5195. type = type ? type : 'notice';
  5196. var key = this.html_identifier(msg),
  5197. date = new Date(),
  5198. id = type + date.getTime();
  5199. if (!timeout)
  5200. timeout = this.message_time * (type == 'error' || type == 'warning' ? 2 : 1);
  5201. if (type == 'loading') {
  5202. key = 'loading';
  5203. timeout = this.env.request_timeout * 1000;
  5204. if (!msg)
  5205. msg = this.get_label('loading');
  5206. }
  5207. // The same message is already displayed
  5208. if (this.messages[key]) {
  5209. // replace label
  5210. if (this.messages[key].obj)
  5211. this.messages[key].obj.html(msg);
  5212. // store label in stack
  5213. if (type == 'loading') {
  5214. this.messages[key].labels.push({'id': id, 'msg': msg});
  5215. }
  5216. // add element and set timeout
  5217. this.messages[key].elements.push(id);
  5218. setTimeout(function() { ref.hide_message(id, type == 'loading'); }, timeout);
  5219. return id;
  5220. }
  5221. // create DOM object and display it
  5222. var obj = $('<div>').addClass(type).html(msg).data('key', key),
  5223. cont = $(this.gui_objects.message).append(obj).show();
  5224. this.messages[key] = {'obj': obj, 'elements': [id]};
  5225. if (type == 'loading') {
  5226. this.messages[key].labels = [{'id': id, 'msg': msg}];
  5227. }
  5228. else {
  5229. obj.click(function() { return ref.hide_message(obj); })
  5230. .attr('role', 'alert');
  5231. }
  5232. this.triggerEvent('message', { message:msg, type:type, timeout:timeout, object:obj });
  5233. if (timeout > 0)
  5234. setTimeout(function() { ref.hide_message(id, type != 'loading'); }, timeout);
  5235. return id;
  5236. };
  5237. // make a message to disapear
  5238. this.hide_message = function(obj, fade)
  5239. {
  5240. // pass command to parent window
  5241. if (this.is_framed())
  5242. return parent.rcmail.hide_message(obj, fade);
  5243. if (!this.gui_objects.message)
  5244. return;
  5245. var k, n, i, o, m = this.messages;
  5246. // Hide message by object, don't use for 'loading'!
  5247. if (typeof obj === 'object') {
  5248. o = $(obj);
  5249. k = o.data('key');
  5250. this.hide_message_object(o, fade);
  5251. if (m[k])
  5252. delete m[k];
  5253. }
  5254. // Hide message by id
  5255. else {
  5256. for (k in m) {
  5257. for (n in m[k].elements) {
  5258. if (m[k] && m[k].elements[n] == obj) {
  5259. m[k].elements.splice(n, 1);
  5260. // hide DOM element if last instance is removed
  5261. if (!m[k].elements.length) {
  5262. this.hide_message_object(m[k].obj, fade);
  5263. delete m[k];
  5264. }
  5265. // set pending action label for 'loading' message
  5266. else if (k == 'loading') {
  5267. for (i in m[k].labels) {
  5268. if (m[k].labels[i].id == obj) {
  5269. delete m[k].labels[i];
  5270. }
  5271. else {
  5272. o = m[k].labels[i].msg;
  5273. m[k].obj.html(o);
  5274. }
  5275. }
  5276. }
  5277. }
  5278. }
  5279. }
  5280. }
  5281. };
  5282. // hide message object and remove from the DOM
  5283. this.hide_message_object = function(o, fade)
  5284. {
  5285. if (fade)
  5286. o.fadeOut(600, function() {$(this).remove(); });
  5287. else
  5288. o.hide().remove();
  5289. };
  5290. // remove all messages immediately
  5291. this.clear_messages = function()
  5292. {
  5293. // pass command to parent window
  5294. if (this.is_framed())
  5295. return parent.rcmail.clear_messages();
  5296. var k, n, m = this.messages;
  5297. for (k in m)
  5298. for (n in m[k].elements)
  5299. if (m[k].obj)
  5300. this.hide_message_object(m[k].obj);
  5301. this.messages = {};
  5302. };
  5303. // open a jquery UI dialog with the given content
  5304. this.show_popup_dialog = function(content, title, buttons, options)
  5305. {
  5306. // forward call to parent window
  5307. if (this.is_framed()) {
  5308. return parent.rcmail.show_popup_dialog(content, title, buttons, options);
  5309. }
  5310. var popup = $('<div class="popup">');
  5311. if (typeof content == 'object')
  5312. popup.append(content);
  5313. else
  5314. popup.html(html);
  5315. popup.dialog($.extend({
  5316. title: title,
  5317. buttons: buttons,
  5318. modal: true,
  5319. resizable: true,
  5320. width: 500,
  5321. close: function(event, ui) { $(this).remove(); }
  5322. }, options || {}));
  5323. // resize and center popup
  5324. var win = $(window), w = win.width(), h = win.height(),
  5325. width = popup.width(), height = popup.height();
  5326. popup.dialog('option', {
  5327. height: Math.min(h - 40, height + 75 + (buttons ? 50 : 0)),
  5328. width: Math.min(w - 20, width + 36)
  5329. });
  5330. return popup;
  5331. };
  5332. // enable/disable buttons for page shifting
  5333. this.set_page_buttons = function()
  5334. {
  5335. this.enable_command('nextpage', 'lastpage', this.env.pagecount > this.env.current_page);
  5336. this.enable_command('previouspage', 'firstpage', this.env.current_page > 1);
  5337. };
  5338. // mark a mailbox as selected and set environment variable
  5339. this.select_folder = function(name, prefix, encode)
  5340. {
  5341. if (this.savedsearchlist) {
  5342. this.savedsearchlist.select('');
  5343. }
  5344. if (this.treelist) {
  5345. this.treelist.select(name);
  5346. }
  5347. else if (this.gui_objects.folderlist) {
  5348. $('li.selected', this.gui_objects.folderlist).removeClass('selected');
  5349. $(this.get_folder_li(name, prefix, encode)).addClass('selected');
  5350. // trigger event hook
  5351. this.triggerEvent('selectfolder', { folder:name, prefix:prefix });
  5352. }
  5353. };
  5354. // adds a class to selected folder
  5355. this.mark_folder = function(name, class_name, prefix, encode)
  5356. {
  5357. $(this.get_folder_li(name, prefix, encode)).addClass(class_name);
  5358. this.triggerEvent('markfolder', {folder: name, mark: class_name, status: true});
  5359. };
  5360. // adds a class to selected folder
  5361. this.unmark_folder = function(name, class_name, prefix, encode)
  5362. {
  5363. $(this.get_folder_li(name, prefix, encode)).removeClass(class_name);
  5364. this.triggerEvent('markfolder', {folder: name, mark: class_name, status: false});
  5365. };
  5366. // helper method to find a folder list item
  5367. this.get_folder_li = function(name, prefix, encode)
  5368. {
  5369. if (!prefix)
  5370. prefix = 'rcmli';
  5371. if (this.gui_objects.folderlist) {
  5372. name = this.html_identifier(name, encode);
  5373. return document.getElementById(prefix+name);
  5374. }
  5375. };
  5376. // for reordering column array (Konqueror workaround)
  5377. // and for setting some message list global variables
  5378. this.set_message_coltypes = function(listcols, repl, smart_col)
  5379. {
  5380. var list = this.message_list,
  5381. thead = list ? list.thead : null,
  5382. repl, cell, col, n, len, tr;
  5383. this.env.listcols = listcols;
  5384. // replace old column headers
  5385. if (thead) {
  5386. if (repl) {
  5387. thead.innerHTML = '';
  5388. tr = document.createElement('tr');
  5389. for (c=0, len=repl.length; c < len; c++) {
  5390. cell = document.createElement('th');
  5391. cell.innerHTML = repl[c].html || '';
  5392. if (repl[c].id) cell.id = repl[c].id;
  5393. if (repl[c].className) cell.className = repl[c].className;
  5394. tr.appendChild(cell);
  5395. }
  5396. thead.appendChild(tr);
  5397. }
  5398. for (n=0, len=this.env.listcols.length; n<len; n++) {
  5399. col = this.env.listcols[n];
  5400. if ((cell = thead.rows[0].cells[n]) && (col == 'from' || col == 'to' || col == 'fromto')) {
  5401. $(cell).attr('rel', col).find('span,a').text(this.get_label(col == 'fromto' ? smart_col : col));
  5402. }
  5403. }
  5404. }
  5405. this.env.subject_col = null;
  5406. this.env.flagged_col = null;
  5407. this.env.status_col = null;
  5408. if (this.env.coltypes.folder)
  5409. this.env.coltypes.folder.hidden = !(this.env.search_request || this.env.search_id) || this.env.search_scope == 'base';
  5410. if ((n = $.inArray('subject', this.env.listcols)) >= 0) {
  5411. this.env.subject_col = n;
  5412. if (list)
  5413. list.subject_col = n;
  5414. }
  5415. if ((n = $.inArray('flag', this.env.listcols)) >= 0)
  5416. this.env.flagged_col = n;
  5417. if ((n = $.inArray('status', this.env.listcols)) >= 0)
  5418. this.env.status_col = n;
  5419. if (list) {
  5420. list.hide_column('folder', (this.env.coltypes.folder && this.env.coltypes.folder.hidden) || $.inArray('folder', this.env.listcols) < 0);
  5421. list.init_header();
  5422. }
  5423. };
  5424. // replace content of row count display
  5425. this.set_rowcount = function(text, mbox)
  5426. {
  5427. // #1487752
  5428. if (mbox && mbox != this.env.mailbox)
  5429. return false;
  5430. $(this.gui_objects.countdisplay).html(text);
  5431. // update page navigation buttons
  5432. this.set_page_buttons();
  5433. };
  5434. // replace content of mailboxname display
  5435. this.set_mailboxname = function(content)
  5436. {
  5437. if (this.gui_objects.mailboxname && content)
  5438. this.gui_objects.mailboxname.innerHTML = content;
  5439. };
  5440. // replace content of quota display
  5441. this.set_quota = function(content)
  5442. {
  5443. if (this.gui_objects.quotadisplay && content && content.type == 'text')
  5444. $(this.gui_objects.quotadisplay).html(content.percent+'%').attr('title', content.title);
  5445. this.triggerEvent('setquota', content);
  5446. this.env.quota_content = content;
  5447. };
  5448. // update trash folder state
  5449. this.set_trash_count = function(count)
  5450. {
  5451. this[(count ? 'un' : '') + 'mark_folder'](this.env.trash_mailbox, 'empty', '', true);
  5452. };
  5453. // update the mailboxlist
  5454. this.set_unread_count = function(mbox, count, set_title, mark)
  5455. {
  5456. if (!this.gui_objects.mailboxlist)
  5457. return false;
  5458. this.env.unread_counts[mbox] = count;
  5459. this.set_unread_count_display(mbox, set_title);
  5460. if (mark)
  5461. this.mark_folder(mbox, mark, '', true);
  5462. else if (!count)
  5463. this.unmark_folder(mbox, 'recent', '', true);
  5464. };
  5465. // update the mailbox count display
  5466. this.set_unread_count_display = function(mbox, set_title)
  5467. {
  5468. var reg, link, text_obj, item, mycount, childcount, div;
  5469. if (item = this.get_folder_li(mbox, '', true)) {
  5470. mycount = this.env.unread_counts[mbox] ? this.env.unread_counts[mbox] : 0;
  5471. link = $(item).children('a').eq(0);
  5472. text_obj = link.children('span.unreadcount');
  5473. if (!text_obj.length && mycount)
  5474. text_obj = $('<span>').addClass('unreadcount').appendTo(link);
  5475. reg = /\s+\([0-9]+\)$/i;
  5476. childcount = 0;
  5477. if ((div = item.getElementsByTagName('div')[0]) &&
  5478. div.className.match(/collapsed/)) {
  5479. // add children's counters
  5480. for (var k in this.env.unread_counts)
  5481. if (k.startsWith(mbox + this.env.delimiter))
  5482. childcount += this.env.unread_counts[k];
  5483. }
  5484. if (mycount && text_obj.length)
  5485. text_obj.html(this.env.unreadwrap.replace(/%[sd]/, mycount));
  5486. else if (text_obj.length)
  5487. text_obj.remove();
  5488. // set parent's display
  5489. reg = new RegExp(RegExp.escape(this.env.delimiter) + '[^' + RegExp.escape(this.env.delimiter) + ']+$');
  5490. if (mbox.match(reg))
  5491. this.set_unread_count_display(mbox.replace(reg, ''), false);
  5492. // set the right classes
  5493. if ((mycount+childcount)>0)
  5494. $(item).addClass('unread');
  5495. else
  5496. $(item).removeClass('unread');
  5497. }
  5498. // set unread count to window title
  5499. reg = /^\([0-9]+\)\s+/i;
  5500. if (set_title && document.title) {
  5501. var new_title = '',
  5502. doc_title = String(document.title);
  5503. if (mycount && doc_title.match(reg))
  5504. new_title = doc_title.replace(reg, '('+mycount+') ');
  5505. else if (mycount)
  5506. new_title = '('+mycount+') '+doc_title;
  5507. else
  5508. new_title = doc_title.replace(reg, '');
  5509. this.set_pagetitle(new_title);
  5510. }
  5511. };
  5512. // display fetched raw headers
  5513. this.set_headers = function(content)
  5514. {
  5515. if (this.gui_objects.all_headers_row && this.gui_objects.all_headers_box && content)
  5516. $(this.gui_objects.all_headers_box).html(content).show();
  5517. };
  5518. // display all-headers row and fetch raw message headers
  5519. this.show_headers = function(props, elem)
  5520. {
  5521. if (!this.gui_objects.all_headers_row || !this.gui_objects.all_headers_box || !this.env.uid)
  5522. return;
  5523. $(elem).removeClass('show-headers').addClass('hide-headers');
  5524. $(this.gui_objects.all_headers_row).show();
  5525. elem.onclick = function() { ref.command('hide-headers', '', elem); };
  5526. // fetch headers only once
  5527. if (!this.gui_objects.all_headers_box.innerHTML) {
  5528. this.http_post('headers', {_uid: this.env.uid, _mbox: this.env.mailbox},
  5529. this.display_message(this.get_label('loading'), 'loading')
  5530. );
  5531. }
  5532. };
  5533. // hide all-headers row
  5534. this.hide_headers = function(props, elem)
  5535. {
  5536. if (!this.gui_objects.all_headers_row || !this.gui_objects.all_headers_box)
  5537. return;
  5538. $(elem).removeClass('hide-headers').addClass('show-headers');
  5539. $(this.gui_objects.all_headers_row).hide();
  5540. elem.onclick = function() { ref.command('show-headers', '', elem); };
  5541. };
  5542. // create folder selector popup, position and display it
  5543. this.folder_selector = function(event, callback)
  5544. {
  5545. var container = this.folder_selector_element;
  5546. if (!container) {
  5547. var rows = [],
  5548. delim = this.env.delimiter,
  5549. ul = $('<ul class="toolbarmenu">'),
  5550. link = document.createElement('a');
  5551. container = $('<div id="folder-selector" class="popupmenu"></div>');
  5552. link.href = '#';
  5553. link.className = 'icon';
  5554. // loop over sorted folders list
  5555. $.each(this.env.mailboxes_list, function() {
  5556. var n = 0, s = 0,
  5557. folder = ref.env.mailboxes[this],
  5558. id = folder.id,
  5559. a = $(link.cloneNode(false)),
  5560. row = $('<li>');
  5561. if (folder.virtual)
  5562. a.addClass('virtual').attr('aria-disabled', 'true').attr('tabindex', '-1');
  5563. else
  5564. a.addClass('active').data('id', folder.id);
  5565. if (folder['class'])
  5566. a.addClass(folder['class']);
  5567. // calculate/set indentation level
  5568. while ((s = id.indexOf(delim, s)) >= 0) {
  5569. n++; s++;
  5570. }
  5571. a.css('padding-left', n ? (n * 16) + 'px' : 0);
  5572. // add folder name element
  5573. a.append($('<span>').text(folder.name));
  5574. row.append(a);
  5575. rows.push(row);
  5576. });
  5577. ul.append(rows).appendTo(container);
  5578. // temporarily show element to calculate its size
  5579. container.css({left: '-1000px', top: '-1000px'})
  5580. .appendTo($('body')).show();
  5581. // set max-height if the list is long
  5582. if (rows.length > 10)
  5583. container.css('max-height', $('li', container)[0].offsetHeight * 10 + 9);
  5584. // register delegate event handler for folder item clicks
  5585. container.on('click', 'a.active', function(e){
  5586. container.data('callback')($(this).data('id'));
  5587. return false;
  5588. });
  5589. this.folder_selector_element = container;
  5590. }
  5591. container.data('callback', callback);
  5592. // position menu on the screen
  5593. this.show_menu('folder-selector', true, event);
  5594. };
  5595. /***********************************************/
  5596. /********* popup menu functions *********/
  5597. /***********************************************/
  5598. // Show/hide a specific popup menu
  5599. this.show_menu = function(prop, show, event)
  5600. {
  5601. var name = typeof prop == 'object' ? prop.menu : prop,
  5602. obj = $('#'+name),
  5603. ref = event && event.target ? $(event.target) : $(obj.attr('rel') || '#'+name+'link'),
  5604. keyboard = rcube_event.is_keyboard(event),
  5605. align = obj.attr('data-align') || '',
  5606. stack = false;
  5607. // find "real" button element
  5608. if (ref.get(0).tagName != 'A' && ref.closest('a').length)
  5609. ref = ref.closest('a');
  5610. if (typeof prop == 'string')
  5611. prop = { menu:name };
  5612. // let plugins or skins provide the menu element
  5613. if (!obj.length) {
  5614. obj = this.triggerEvent('menu-get', { name:name, props:prop, originalEvent:event });
  5615. }
  5616. if (!obj || !obj.length) {
  5617. // just delegate the action to subscribers
  5618. return this.triggerEvent(show === false ? 'menu-close' : 'menu-open', { name:name, props:prop, originalEvent:event });
  5619. }
  5620. // move element to top for proper absolute positioning
  5621. obj.appendTo(document.body);
  5622. if (typeof show == 'undefined')
  5623. show = obj.is(':visible') ? false : true;
  5624. if (show && ref.length) {
  5625. var win = $(window),
  5626. pos = ref.offset(),
  5627. above = align.indexOf('bottom') >= 0;
  5628. stack = ref.attr('role') == 'menuitem' || ref.closest('[role=menuitem]').length > 0;
  5629. ref.offsetWidth = ref.outerWidth();
  5630. ref.offsetHeight = ref.outerHeight();
  5631. if (!above && pos.top + ref.offsetHeight + obj.height() > win.height()) {
  5632. above = true;
  5633. }
  5634. if (align.indexOf('right') >= 0) {
  5635. pos.left = pos.left + ref.outerWidth() - obj.width();
  5636. }
  5637. else if (stack) {
  5638. pos.left = pos.left + ref.offsetWidth - 5;
  5639. pos.top -= ref.offsetHeight;
  5640. }
  5641. if (pos.left + obj.width() > win.width()) {
  5642. pos.left = win.width() - obj.width() - 12;
  5643. }
  5644. pos.top = Math.max(0, pos.top + (above ? -obj.height() : ref.offsetHeight));
  5645. obj.css({ left:pos.left+'px', top:pos.top+'px' });
  5646. }
  5647. // add menu to stack
  5648. if (show) {
  5649. // truncate stack down to the one containing the ref link
  5650. for (var i = this.menu_stack.length - 1; stack && i >= 0; i--) {
  5651. if (!$(ref).parents('#'+this.menu_stack[i]).length)
  5652. this.hide_menu(this.menu_stack[i]);
  5653. }
  5654. if (stack && this.menu_stack.length) {
  5655. obj.data('parent', $.last(this.menu_stack));
  5656. obj.css('z-index', ($('#'+$.last(this.menu_stack)).css('z-index') || 0) + 1);
  5657. }
  5658. else if (!stack && this.menu_stack.length) {
  5659. this.hide_menu(this.menu_stack[0], event);
  5660. }
  5661. obj.show().attr('aria-hidden', 'false').data('opener', ref.attr('aria-expanded', 'true').get(0));
  5662. this.triggerEvent('menu-open', { name:name, obj:obj, props:prop, originalEvent:event });
  5663. this.menu_stack.push(name);
  5664. this.menu_keyboard_active = show && keyboard;
  5665. if (this.menu_keyboard_active) {
  5666. this.focused_menu = name;
  5667. obj.find('a,input:not(:disabled)').not('[aria-disabled=true]').first().focus();
  5668. }
  5669. }
  5670. else { // close menu
  5671. this.hide_menu(name, event);
  5672. }
  5673. return show;
  5674. };
  5675. // hide the given popup menu (and it's childs)
  5676. this.hide_menu = function(name, event)
  5677. {
  5678. if (!this.menu_stack.length) {
  5679. // delegate to subscribers
  5680. this.triggerEvent('menu-close', { name:name, props:{ menu:name }, originalEvent:event });
  5681. return;
  5682. }
  5683. var obj, keyboard = rcube_event.is_keyboard(event);
  5684. for (var j=this.menu_stack.length-1; j >= 0; j--) {
  5685. obj = $('#' + this.menu_stack[j]).hide().attr('aria-hidden', 'true').data('parent', false);
  5686. this.triggerEvent('menu-close', { name:this.menu_stack[j], obj:obj, props:{ menu:this.menu_stack[j] }, originalEvent:event });
  5687. if (this.menu_stack[j] == name) {
  5688. j = -1; // stop loop
  5689. if (obj.data('opener')) {
  5690. $(obj.data('opener')).attr('aria-expanded', 'false');
  5691. if (keyboard)
  5692. obj.data('opener').focus();
  5693. }
  5694. }
  5695. this.menu_stack.pop();
  5696. }
  5697. // focus previous menu in stack
  5698. if (this.menu_stack.length && keyboard) {
  5699. this.menu_keyboard_active = true;
  5700. this.focused_menu = $.last(this.menu_stack);
  5701. if (!obj || !obj.data('opener'))
  5702. $('#'+this.focused_menu).find('a,input:not(:disabled)').not('[aria-disabled=true]').first().focus();
  5703. }
  5704. else {
  5705. this.focused_menu = null;
  5706. this.menu_keyboard_active = false;
  5707. }
  5708. }
  5709. // position a menu element on the screen in relation to other object
  5710. this.element_position = function(element, obj)
  5711. {
  5712. var obj = $(obj), win = $(window),
  5713. width = obj.outerWidth(),
  5714. height = obj.outerHeight(),
  5715. menu_pos = obj.data('menu-pos'),
  5716. win_height = win.height(),
  5717. elem_height = $(element).height(),
  5718. elem_width = $(element).width(),
  5719. pos = obj.offset(),
  5720. top = pos.top,
  5721. left = pos.left + width;
  5722. if (menu_pos == 'bottom') {
  5723. top += height;
  5724. left -= width;
  5725. }
  5726. else
  5727. left -= 5;
  5728. if (top + elem_height > win_height) {
  5729. top -= elem_height - height;
  5730. if (top < 0)
  5731. top = Math.max(0, (win_height - elem_height) / 2);
  5732. }
  5733. if (left + elem_width > win.width())
  5734. left -= elem_width + width;
  5735. element.css({left: left + 'px', top: top + 'px'});
  5736. };
  5737. // initialize HTML editor
  5738. this.editor_init = function(config, id)
  5739. {
  5740. this.editor = new rcube_text_editor(config, id);
  5741. };
  5742. /********************************************************/
  5743. /********* html to text conversion functions *********/
  5744. /********************************************************/
  5745. this.html2plain = function(html, func)
  5746. {
  5747. return this.format_converter(html, 'html', func);
  5748. };
  5749. this.plain2html = function(plain, func)
  5750. {
  5751. return this.format_converter(plain, 'plain', func);
  5752. };
  5753. this.format_converter = function(text, format, func)
  5754. {
  5755. // warn the user (if converted content is not empty)
  5756. if (!text
  5757. || (format == 'html' && !(text.replace(/<[^>]+>|&nbsp;|\xC2\xA0|\s/g, '')).length)
  5758. || (format != 'html' && !(text.replace(/\xC2\xA0|\s/g, '')).length)
  5759. ) {
  5760. // without setTimeout() here, textarea is filled with initial (onload) content
  5761. if (func)
  5762. setTimeout(function() { func(''); }, 50);
  5763. return true;
  5764. }
  5765. var confirmed = this.env.editor_warned || confirm(this.get_label('editorwarning'));
  5766. this.env.editor_warned = true;
  5767. if (!confirmed)
  5768. return false;
  5769. var url = '?_task=utils&_action=' + (format == 'html' ? 'html2text' : 'text2html'),
  5770. lock = this.set_busy(true, 'converting');
  5771. this.log('HTTP POST: ' + url);
  5772. $.ajax({ type: 'POST', url: url, data: text, contentType: 'application/octet-stream',
  5773. error: function(o, status, err) { ref.http_error(o, status, err, lock); },
  5774. success: function(data) {
  5775. ref.set_busy(false, null, lock);
  5776. if (func) func(data);
  5777. }
  5778. });
  5779. return true;
  5780. };
  5781. /********************************************************/
  5782. /********* remote request methods *********/
  5783. /********************************************************/
  5784. // compose a valid url with the given parameters
  5785. this.url = function(action, query)
  5786. {
  5787. var querystring = typeof query === 'string' ? '&' + query : '';
  5788. if (typeof action !== 'string')
  5789. query = action;
  5790. else if (!query || typeof query !== 'object')
  5791. query = {};
  5792. if (action)
  5793. query._action = action;
  5794. else if (this.env.action)
  5795. query._action = this.env.action;
  5796. var base = this.env.comm_path, k, param = {};
  5797. // overwrite task name
  5798. if (action && action.match(/([a-z0-9_-]+)\/([a-z0-9-_.]+)/)) {
  5799. query._action = RegExp.$2;
  5800. base = base.replace(/\_task=[a-z0-9_-]+/, '_task='+RegExp.$1);
  5801. }
  5802. // remove undefined values
  5803. for (k in query) {
  5804. if (query[k] !== undefined && query[k] !== null)
  5805. param[k] = query[k];
  5806. }
  5807. return base + (base.indexOf('?') > -1 ? '&' : '?') + $.param(param) + querystring;
  5808. };
  5809. this.redirect = function(url, lock)
  5810. {
  5811. if (lock || lock === null)
  5812. this.set_busy(true);
  5813. if (this.is_framed()) {
  5814. parent.rcmail.redirect(url, lock);
  5815. }
  5816. else {
  5817. if (this.env.extwin) {
  5818. if (typeof url == 'string')
  5819. url += (url.indexOf('?') < 0 ? '?' : '&') + '_extwin=1';
  5820. else
  5821. url._extwin = 1;
  5822. }
  5823. this.location_href(url, window);
  5824. }
  5825. };
  5826. this.goto_url = function(action, query, lock)
  5827. {
  5828. this.redirect(this.url(action, query), lock);
  5829. };
  5830. this.location_href = function(url, target, frame)
  5831. {
  5832. if (frame)
  5833. this.lock_frame();
  5834. if (typeof url == 'object')
  5835. url = this.env.comm_path + '&' + $.param(url);
  5836. // simulate real link click to force IE to send referer header
  5837. if (bw.ie && target == window)
  5838. $('<a>').attr('href', url).appendTo(document.body).get(0).click();
  5839. else
  5840. target.location.href = url;
  5841. // reset keep-alive interval
  5842. this.start_keepalive();
  5843. };
  5844. // update browser location to remember current view
  5845. this.update_state = function(query)
  5846. {
  5847. if (window.history.replaceState)
  5848. window.history.replaceState({}, document.title, rcmail.url('', query));
  5849. };
  5850. // send a http request to the server
  5851. this.http_request = function(action, query, lock)
  5852. {
  5853. var url = this.url(action, query);
  5854. // trigger plugin hook
  5855. var result = this.triggerEvent('request'+action, query);
  5856. if (result !== undefined) {
  5857. // abort if one the handlers returned false
  5858. if (result === false)
  5859. return false;
  5860. else
  5861. url = this.url(action, result);
  5862. }
  5863. url += '&_remote=1';
  5864. // send request
  5865. this.log('HTTP GET: ' + url);
  5866. // reset keep-alive interval
  5867. this.start_keepalive();
  5868. return $.ajax({
  5869. type: 'GET', url: url, data: { _unlock:(lock?lock:0) }, dataType: 'json',
  5870. success: function(data){ ref.http_response(data); },
  5871. error: function(o, status, err) { ref.http_error(o, status, err, lock, action); }
  5872. });
  5873. };
  5874. // send a http POST request to the server
  5875. this.http_post = function(action, postdata, lock)
  5876. {
  5877. var url = this.url(action);
  5878. if (postdata && typeof postdata === 'object') {
  5879. postdata._remote = 1;
  5880. postdata._unlock = (lock ? lock : 0);
  5881. }
  5882. else
  5883. postdata += (postdata ? '&' : '') + '_remote=1' + (lock ? '&_unlock='+lock : '');
  5884. // trigger plugin hook
  5885. var result = this.triggerEvent('request'+action, postdata);
  5886. if (result !== undefined) {
  5887. // abort if one of the handlers returned false
  5888. if (result === false)
  5889. return false;
  5890. else
  5891. postdata = result;
  5892. }
  5893. // send request
  5894. this.log('HTTP POST: ' + url);
  5895. // reset keep-alive interval
  5896. this.start_keepalive();
  5897. return $.ajax({
  5898. type: 'POST', url: url, data: postdata, dataType: 'json',
  5899. success: function(data){ ref.http_response(data); },
  5900. error: function(o, status, err) { ref.http_error(o, status, err, lock, action); }
  5901. });
  5902. };
  5903. // aborts ajax request
  5904. this.abort_request = function(r)
  5905. {
  5906. if (r.request)
  5907. r.request.abort();
  5908. if (r.lock)
  5909. this.set_busy(false, null, r.lock);
  5910. };
  5911. // handle HTTP response
  5912. this.http_response = function(response)
  5913. {
  5914. if (!response)
  5915. return;
  5916. if (response.unlock)
  5917. this.set_busy(false);
  5918. this.triggerEvent('responsebefore', {response: response});
  5919. this.triggerEvent('responsebefore'+response.action, {response: response});
  5920. // set env vars
  5921. if (response.env)
  5922. this.set_env(response.env);
  5923. // we have labels to add
  5924. if (typeof response.texts === 'object') {
  5925. for (var name in response.texts)
  5926. if (typeof response.texts[name] === 'string')
  5927. this.add_label(name, response.texts[name]);
  5928. }
  5929. // if we get javascript code from server -> execute it
  5930. if (response.exec) {
  5931. this.log(response.exec);
  5932. eval(response.exec);
  5933. }
  5934. // execute callback functions of plugins
  5935. if (response.callbacks && response.callbacks.length) {
  5936. for (var i=0; i < response.callbacks.length; i++)
  5937. this.triggerEvent(response.callbacks[i][0], response.callbacks[i][1]);
  5938. }
  5939. // process the response data according to the sent action
  5940. switch (response.action) {
  5941. case 'delete':
  5942. if (this.task == 'addressbook') {
  5943. var sid, uid = this.contact_list.get_selection(), writable = false;
  5944. if (uid && this.contact_list.rows[uid]) {
  5945. // search results, get source ID from record ID
  5946. if (this.env.source == '') {
  5947. sid = String(uid).replace(/^[^-]+-/, '');
  5948. writable = sid && this.env.address_sources[sid] && !this.env.address_sources[sid].readonly;
  5949. }
  5950. else {
  5951. writable = !this.env.address_sources[this.env.source].readonly;
  5952. }
  5953. }
  5954. this.enable_command('compose', (uid && this.contact_list.rows[uid]));
  5955. this.enable_command('delete', 'edit', writable);
  5956. this.enable_command('export', (this.contact_list && this.contact_list.rowcount > 0));
  5957. this.enable_command('export-selected', false);
  5958. }
  5959. case 'move':
  5960. if (this.env.action == 'show') {
  5961. // re-enable commands on move/delete error
  5962. this.enable_command(this.env.message_commands, true);
  5963. if (!this.env.list_post)
  5964. this.enable_command('reply-list', false);
  5965. }
  5966. else if (this.task == 'addressbook') {
  5967. this.triggerEvent('listupdate', { folder:this.env.source, rowcount:this.contact_list.rowcount });
  5968. }
  5969. case 'purge':
  5970. case 'expunge':
  5971. if (this.task == 'mail') {
  5972. if (!this.env.exists) {
  5973. // clear preview pane content
  5974. if (this.env.contentframe)
  5975. this.show_contentframe(false);
  5976. // disable commands useless when mailbox is empty
  5977. this.enable_command(this.env.message_commands, 'purge', 'expunge',
  5978. 'select-all', 'select-none', 'expand-all', 'expand-unread', 'collapse-all', false);
  5979. }
  5980. if (this.message_list)
  5981. this.triggerEvent('listupdate', { folder:this.env.mailbox, rowcount:this.message_list.rowcount });
  5982. }
  5983. break;
  5984. case 'refresh':
  5985. case 'check-recent':
  5986. // update message flags
  5987. $.each(this.env.recent_flags || {}, function(uid, flags) {
  5988. ref.set_message(uid, 'deleted', flags.deleted);
  5989. ref.set_message(uid, 'replied', flags.answered);
  5990. ref.set_message(uid, 'unread', !flags.seen);
  5991. ref.set_message(uid, 'forwarded', flags.forwarded);
  5992. ref.set_message(uid, 'flagged', flags.flagged);
  5993. });
  5994. delete this.env.recent_flags;
  5995. case 'getunread':
  5996. case 'search':
  5997. this.env.qsearch = null;
  5998. case 'list':
  5999. if (this.task == 'mail') {
  6000. var is_multifolder = this.is_multifolder_listing();
  6001. this.enable_command('show', 'select-all', 'select-none', this.env.messagecount > 0);
  6002. this.enable_command('expunge', this.env.exists && !is_multifolder);
  6003. this.enable_command('purge', this.purge_mailbox_test() && !is_multifolder);
  6004. this.enable_command('import-messages', !is_multifolder);
  6005. this.enable_command('expand-all', 'expand-unread', 'collapse-all', this.env.threading && this.env.messagecount && !is_multifolder);
  6006. if ((response.action == 'list' || response.action == 'search') && this.message_list) {
  6007. var list = this.message_list, uid = this.env.list_uid;
  6008. // highlight message row when we're back from message page
  6009. if (uid) {
  6010. if (!list.rows[uid])
  6011. uid += '-' + this.env.mailbox;
  6012. if (list.rows[uid]) {
  6013. list.select(uid);
  6014. }
  6015. delete this.env.list_uid;
  6016. }
  6017. this.enable_command('set-listmode', this.env.threads && !is_multifolder);
  6018. if (list.rowcount > 0)
  6019. list.focus();
  6020. this.msglist_select(list);
  6021. this.triggerEvent('listupdate', { folder:this.env.mailbox, rowcount:list.rowcount });
  6022. }
  6023. }
  6024. else if (this.task == 'addressbook') {
  6025. this.enable_command('export', (this.contact_list && this.contact_list.rowcount > 0));
  6026. if (response.action == 'list' || response.action == 'search') {
  6027. this.enable_command('search-create', this.env.source == '');
  6028. this.enable_command('search-delete', this.env.search_id);
  6029. this.update_group_commands();
  6030. if (this.contact_list.rowcount > 0)
  6031. this.contact_list.focus();
  6032. this.triggerEvent('listupdate', { folder:this.env.source, rowcount:this.contact_list.rowcount });
  6033. }
  6034. }
  6035. break;
  6036. case 'list-contacts':
  6037. case 'search-contacts':
  6038. if (this.contact_list && this.contact_list.rowcount > 0)
  6039. this.contact_list.focus();
  6040. break;
  6041. }
  6042. if (response.unlock)
  6043. this.hide_message(response.unlock);
  6044. this.triggerEvent('responseafter', {response: response});
  6045. this.triggerEvent('responseafter'+response.action, {response: response});
  6046. // reset keep-alive interval
  6047. this.start_keepalive();
  6048. };
  6049. // handle HTTP request errors
  6050. this.http_error = function(request, status, err, lock, action)
  6051. {
  6052. var errmsg = request.statusText;
  6053. this.set_busy(false, null, lock);
  6054. request.abort();
  6055. // don't display error message on page unload (#1488547)
  6056. if (this.unload)
  6057. return;
  6058. if (request.status && errmsg)
  6059. this.display_message(this.get_label('servererror') + ' (' + errmsg + ')', 'error');
  6060. else if (status == 'timeout')
  6061. this.display_message(this.get_label('requesttimedout'), 'error');
  6062. else if (request.status == 0 && status != 'abort')
  6063. this.display_message(this.get_label('connerror'), 'error');
  6064. // redirect to url specified in location header if not empty
  6065. var location_url = request.getResponseHeader("Location");
  6066. if (location_url && this.env.action != 'compose') // don't redirect on compose screen, contents might get lost (#1488926)
  6067. this.redirect(location_url);
  6068. // 403 Forbidden response (CSRF prevention) - reload the page.
  6069. // In case there's a new valid session it will be used, otherwise
  6070. // login form will be presented (#1488960).
  6071. if (request.status == 403) {
  6072. (this.is_framed() ? parent : window).location.reload();
  6073. return;
  6074. }
  6075. // re-send keep-alive requests after 30 seconds
  6076. if (action == 'keep-alive')
  6077. setTimeout(function(){ ref.keep_alive(); ref.start_keepalive(); }, 30000);
  6078. };
  6079. // handler for session errors detected on the server
  6080. this.session_error = function(redirect_url)
  6081. {
  6082. this.env.server_error = 401;
  6083. // save message in local storage and do not redirect
  6084. if (this.env.action == 'compose') {
  6085. this.save_compose_form_local();
  6086. this.compose_skip_unsavedcheck = true;
  6087. }
  6088. else if (redirect_url) {
  6089. setTimeout(function(){ ref.redirect(redirect_url, true); }, 2000);
  6090. }
  6091. };
  6092. // callback when an iframe finished loading
  6093. this.iframe_loaded = function(unlock)
  6094. {
  6095. this.set_busy(false, null, unlock);
  6096. if (this.submit_timer)
  6097. clearTimeout(this.submit_timer);
  6098. };
  6099. /**
  6100. Send multi-threaded parallel HTTP requests to the server for a list if items.
  6101. The string '%' in either a GET query or POST parameters will be replaced with the respective item value.
  6102. This is the argument object expected: {
  6103. items: ['foo','bar','gna'], // list of items to send requests for
  6104. action: 'task/some-action', // Roudncube action to call
  6105. query: { q:'%s' }, // GET query parameters
  6106. postdata: { source:'%s' }, // POST data (sends a POST request if present)
  6107. threads: 3, // max. number of concurrent requests
  6108. onresponse: function(data){ }, // Callback function called for every response received from server
  6109. whendone: function(alldata){ } // Callback function called when all requests have been sent
  6110. }
  6111. */
  6112. this.multi_thread_http_request = function(prop)
  6113. {
  6114. var i, item, reqid = new Date().getTime(),
  6115. threads = prop.threads || 1;
  6116. prop.reqid = reqid;
  6117. prop.running = 0;
  6118. prop.requests = [];
  6119. prop.result = [];
  6120. prop._items = $.extend([], prop.items); // copy items
  6121. if (!prop.lock)
  6122. prop.lock = this.display_message(this.get_label('loading'), 'loading');
  6123. // add the request arguments to the jobs pool
  6124. this.http_request_jobs[reqid] = prop;
  6125. // start n threads
  6126. for (i=0; i < threads; i++) {
  6127. item = prop._items.shift();
  6128. if (item === undefined)
  6129. break;
  6130. prop.running++;
  6131. prop.requests.push(this.multi_thread_send_request(prop, item));
  6132. }
  6133. return reqid;
  6134. };
  6135. // helper method to send an HTTP request with the given iterator value
  6136. this.multi_thread_send_request = function(prop, item)
  6137. {
  6138. var k, postdata, query;
  6139. // replace %s in post data
  6140. if (prop.postdata) {
  6141. postdata = {};
  6142. for (k in prop.postdata) {
  6143. postdata[k] = String(prop.postdata[k]).replace('%s', item);
  6144. }
  6145. postdata._reqid = prop.reqid;
  6146. }
  6147. // replace %s in query
  6148. else if (typeof prop.query == 'string') {
  6149. query = prop.query.replace('%s', item);
  6150. query += '&_reqid=' + prop.reqid;
  6151. }
  6152. else if (typeof prop.query == 'object' && prop.query) {
  6153. query = {};
  6154. for (k in prop.query) {
  6155. query[k] = String(prop.query[k]).replace('%s', item);
  6156. }
  6157. query._reqid = prop.reqid;
  6158. }
  6159. // send HTTP GET or POST request
  6160. return postdata ? this.http_post(prop.action, postdata) : this.http_request(prop.action, query);
  6161. };
  6162. // callback function for multi-threaded http responses
  6163. this.multi_thread_http_response = function(data, reqid)
  6164. {
  6165. var prop = this.http_request_jobs[reqid];
  6166. if (!prop || prop.running <= 0 || prop.cancelled)
  6167. return;
  6168. prop.running--;
  6169. // trigger response callback
  6170. if (prop.onresponse && typeof prop.onresponse == 'function') {
  6171. prop.onresponse(data);
  6172. }
  6173. prop.result = $.extend(prop.result, data);
  6174. // send next request if prop.items is not yet empty
  6175. var item = prop._items.shift();
  6176. if (item !== undefined) {
  6177. prop.running++;
  6178. prop.requests.push(this.multi_thread_send_request(prop, item));
  6179. }
  6180. // trigger whendone callback and mark this request as done
  6181. else if (prop.running == 0) {
  6182. if (prop.whendone && typeof prop.whendone == 'function') {
  6183. prop.whendone(prop.result);
  6184. }
  6185. this.set_busy(false, '', prop.lock);
  6186. // remove from this.http_request_jobs pool
  6187. delete this.http_request_jobs[reqid];
  6188. }
  6189. };
  6190. // abort a running multi-thread request with the given identifier
  6191. this.multi_thread_request_abort = function(reqid)
  6192. {
  6193. var prop = this.http_request_jobs[reqid];
  6194. if (prop) {
  6195. for (var i=0; prop.running > 0 && i < prop.requests.length; i++) {
  6196. if (prop.requests[i].abort)
  6197. prop.requests[i].abort();
  6198. }
  6199. prop.running = 0;
  6200. prop.cancelled = true;
  6201. this.set_busy(false, '', prop.lock);
  6202. }
  6203. };
  6204. // post the given form to a hidden iframe
  6205. this.async_upload_form = function(form, action, onload)
  6206. {
  6207. // create hidden iframe
  6208. var ts = new Date().getTime(),
  6209. frame_name = 'rcmupload' + ts,
  6210. frame = this.async_upload_form_frame(frame_name);
  6211. // upload progress support
  6212. if (this.env.upload_progress_name) {
  6213. var fname = this.env.upload_progress_name,
  6214. field = $('input[name='+fname+']', form);
  6215. if (!field.length) {
  6216. field = $('<input>').attr({type: 'hidden', name: fname});
  6217. field.prependTo(form);
  6218. }
  6219. field.val(ts);
  6220. }
  6221. // handle upload errors by parsing iframe content in onload
  6222. frame.bind('load', {ts:ts}, onload);
  6223. $(form).attr({
  6224. target: frame_name,
  6225. action: this.url(action, {_id: this.env.compose_id || '', _uploadid: ts, _from: this.env.action}),
  6226. method: 'POST'})
  6227. .attr(form.encoding ? 'encoding' : 'enctype', 'multipart/form-data')
  6228. .submit();
  6229. return frame_name;
  6230. };
  6231. // create iframe element for files upload
  6232. this.async_upload_form_frame = function(name)
  6233. {
  6234. return $('<iframe>').attr({name: name, style: 'border: none; width: 0; height: 0; visibility: hidden'})
  6235. .appendTo(document.body);
  6236. };
  6237. // html5 file-drop API
  6238. this.document_drag_hover = function(e, over)
  6239. {
  6240. e.preventDefault();
  6241. $(this.gui_objects.filedrop)[(over?'addClass':'removeClass')]('active');
  6242. };
  6243. this.file_drag_hover = function(e, over)
  6244. {
  6245. e.preventDefault();
  6246. e.stopPropagation();
  6247. $(this.gui_objects.filedrop)[(over?'addClass':'removeClass')]('hover');
  6248. };
  6249. // handler when files are dropped to a designated area.
  6250. // compose a multipart form data and submit it to the server
  6251. this.file_dropped = function(e)
  6252. {
  6253. // abort event and reset UI
  6254. this.file_drag_hover(e, false);
  6255. // prepare multipart form data composition
  6256. var files = e.target.files || e.dataTransfer.files,
  6257. formdata = window.FormData ? new FormData() : null,
  6258. fieldname = (this.env.filedrop.fieldname || '_file') + (this.env.filedrop.single ? '' : '[]'),
  6259. boundary = '------multipartformboundary' + (new Date).getTime(),
  6260. dashdash = '--', crlf = '\r\n',
  6261. multipart = dashdash + boundary + crlf;
  6262. if (!files || !files.length)
  6263. return;
  6264. // inline function to submit the files to the server
  6265. var submit_data = function() {
  6266. var multiple = files.length > 1,
  6267. ts = new Date().getTime(),
  6268. content = '<span>' + (multiple ? ref.get_label('uploadingmany') : files[0].name) + '</span>';
  6269. // add to attachments list
  6270. if (!ref.add2attachment_list(ts, { name:'', html:content, classname:'uploading', complete:false }))
  6271. ref.file_upload_id = ref.set_busy(true, 'uploading');
  6272. // complete multipart content and post request
  6273. multipart += dashdash + boundary + dashdash + crlf;
  6274. $.ajax({
  6275. type: 'POST',
  6276. dataType: 'json',
  6277. url: ref.url(ref.env.filedrop.action || 'upload', {_id: ref.env.compose_id||ref.env.cid||'', _uploadid: ts, _remote: 1, _from: ref.env.action}),
  6278. contentType: formdata ? false : 'multipart/form-data; boundary=' + boundary,
  6279. processData: false,
  6280. timeout: 0, // disable default timeout set in ajaxSetup()
  6281. data: formdata || multipart,
  6282. headers: {'X-Roundcube-Request': ref.env.request_token},
  6283. xhr: function() { var xhr = jQuery.ajaxSettings.xhr(); if (!formdata && xhr.sendAsBinary) xhr.send = xhr.sendAsBinary; return xhr; },
  6284. success: function(data){ ref.http_response(data); },
  6285. error: function(o, status, err) { ref.http_error(o, status, err, null, 'attachment'); }
  6286. });
  6287. };
  6288. // get contents of all dropped files
  6289. var last = this.env.filedrop.single ? 0 : files.length - 1;
  6290. for (var j=0, i=0, f; j <= last && (f = files[i]); i++) {
  6291. if (!f.name) f.name = f.fileName;
  6292. if (!f.size) f.size = f.fileSize;
  6293. if (!f.type) f.type = 'application/octet-stream';
  6294. // file name contains non-ASCII characters, do UTF8-binary string conversion.
  6295. if (!formdata && /[^\x20-\x7E]/.test(f.name))
  6296. f.name_bin = unescape(encodeURIComponent(f.name));
  6297. // filter by file type if requested
  6298. if (this.env.filedrop.filter && !f.type.match(new RegExp(this.env.filedrop.filter))) {
  6299. // TODO: show message to user
  6300. continue;
  6301. }
  6302. // do it the easy way with FormData (FF 4+, Chrome 5+, Safari 5+)
  6303. if (formdata) {
  6304. formdata.append(fieldname, f);
  6305. if (j == last)
  6306. return submit_data();
  6307. }
  6308. // use FileReader supporetd by Firefox 3.6
  6309. else if (window.FileReader) {
  6310. var reader = new FileReader();
  6311. // closure to pass file properties to async callback function
  6312. reader.onload = (function(file, j) {
  6313. return function(e) {
  6314. multipart += 'Content-Disposition: form-data; name="' + fieldname + '"';
  6315. multipart += '; filename="' + (f.name_bin || file.name) + '"' + crlf;
  6316. multipart += 'Content-Length: ' + file.size + crlf;
  6317. multipart += 'Content-Type: ' + file.type + crlf + crlf;
  6318. multipart += reader.result + crlf;
  6319. multipart += dashdash + boundary + crlf;
  6320. if (j == last) // we're done, submit the data
  6321. return submit_data();
  6322. }
  6323. })(f,j);
  6324. reader.readAsBinaryString(f);
  6325. }
  6326. // Firefox 3
  6327. else if (f.getAsBinary) {
  6328. multipart += 'Content-Disposition: form-data; name="' + fieldname + '"';
  6329. multipart += '; filename="' + (f.name_bin || f.name) + '"' + crlf;
  6330. multipart += 'Content-Length: ' + f.size + crlf;
  6331. multipart += 'Content-Type: ' + f.type + crlf + crlf;
  6332. multipart += f.getAsBinary() + crlf;
  6333. multipart += dashdash + boundary +crlf;
  6334. if (j == last)
  6335. return submit_data();
  6336. }
  6337. j++;
  6338. }
  6339. };
  6340. // starts interval for keep-alive signal
  6341. this.start_keepalive = function()
  6342. {
  6343. if (!this.env.session_lifetime || this.env.framed || this.env.extwin || this.task == 'login' || this.env.action == 'print')
  6344. return;
  6345. if (this._keepalive)
  6346. clearInterval(this._keepalive);
  6347. this._keepalive = setInterval(function(){ ref.keep_alive(); }, this.env.session_lifetime * 0.5 * 1000);
  6348. };
  6349. // starts interval for refresh signal
  6350. this.start_refresh = function()
  6351. {
  6352. if (!this.env.refresh_interval || this.env.framed || this.env.extwin || this.task == 'login' || this.env.action == 'print')
  6353. return;
  6354. if (this._refresh)
  6355. clearInterval(this._refresh);
  6356. this._refresh = setInterval(function(){ ref.refresh(); }, this.env.refresh_interval * 1000);
  6357. };
  6358. // sends keep-alive signal
  6359. this.keep_alive = function()
  6360. {
  6361. if (!this.busy)
  6362. this.http_request('keep-alive');
  6363. };
  6364. // sends refresh signal
  6365. this.refresh = function()
  6366. {
  6367. if (this.busy) {
  6368. // try again after 10 seconds
  6369. setTimeout(function(){ ref.refresh(); ref.start_refresh(); }, 10000);
  6370. return;
  6371. }
  6372. var params = {}, lock = this.set_busy(true, 'refreshing');
  6373. if (this.task == 'mail' && this.gui_objects.mailboxlist)
  6374. params = this.check_recent_params();
  6375. params._last = Math.floor(this.env.lastrefresh.getTime() / 1000);
  6376. this.env.lastrefresh = new Date();
  6377. // plugins should bind to 'requestrefresh' event to add own params
  6378. this.http_post('refresh', params, lock);
  6379. };
  6380. // returns check-recent request parameters
  6381. this.check_recent_params = function()
  6382. {
  6383. var params = {_mbox: this.env.mailbox};
  6384. if (this.gui_objects.mailboxlist)
  6385. params._folderlist = 1;
  6386. if (this.gui_objects.quotadisplay)
  6387. params._quota = 1;
  6388. if (this.env.search_request)
  6389. params._search = this.env.search_request;
  6390. if (this.gui_objects.messagelist) {
  6391. params._list = 1;
  6392. // message uids for flag updates check
  6393. params._uids = $.map(this.message_list.rows, function(row, uid) { return uid; }).join(',');
  6394. }
  6395. return params;
  6396. };
  6397. /********************************************************/
  6398. /********* helper methods *********/
  6399. /********************************************************/
  6400. /**
  6401. * Quote html entities
  6402. */
  6403. this.quote_html = function(str)
  6404. {
  6405. return String(str).replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
  6406. };
  6407. // get window.opener.rcmail if available
  6408. this.opener = function()
  6409. {
  6410. // catch Error: Permission denied to access property rcmail
  6411. try {
  6412. if (window.opener && !opener.closed && opener.rcmail)
  6413. return opener.rcmail;
  6414. }
  6415. catch (e) {}
  6416. };
  6417. // check if we're in show mode or if we have a unique selection
  6418. // and return the message uid
  6419. this.get_single_uid = function()
  6420. {
  6421. return this.env.uid ? this.env.uid : (this.message_list ? this.message_list.get_single_selection() : null);
  6422. };
  6423. // same as above but for contacts
  6424. this.get_single_cid = function()
  6425. {
  6426. return this.env.cid ? this.env.cid : (this.contact_list ? this.contact_list.get_single_selection() : null);
  6427. };
  6428. // get the IMP mailbox of the message with the given UID
  6429. this.get_message_mailbox = function(uid)
  6430. {
  6431. var msg = this.env.messages ? this.env.messages[uid] : {};
  6432. return msg.mbox || this.env.mailbox;
  6433. };
  6434. // gets cursor position
  6435. this.get_caret_pos = function(obj)
  6436. {
  6437. if (obj.selectionEnd !== undefined)
  6438. return obj.selectionEnd;
  6439. return obj.value.length;
  6440. };
  6441. // moves cursor to specified position
  6442. this.set_caret_pos = function(obj, pos)
  6443. {
  6444. try {
  6445. if (obj.setSelectionRange)
  6446. obj.setSelectionRange(pos, pos);
  6447. }
  6448. catch(e) {} // catch Firefox exception if obj is hidden
  6449. };
  6450. // get selected text from an input field
  6451. this.get_input_selection = function(obj)
  6452. {
  6453. var start = 0, end = 0, normalizedValue = '';
  6454. if (typeof obj.selectionStart == "number" && typeof obj.selectionEnd == "number") {
  6455. normalizedValue = obj.value;
  6456. start = obj.selectionStart;
  6457. end = obj.selectionEnd;
  6458. }
  6459. return {start: start, end: end, text: normalizedValue.substr(start, end-start)};
  6460. };
  6461. // disable/enable all fields of a form
  6462. this.lock_form = function(form, lock)
  6463. {
  6464. if (!form || !form.elements)
  6465. return;
  6466. var n, len, elm;
  6467. if (lock)
  6468. this.disabled_form_elements = [];
  6469. for (n=0, len=form.elements.length; n<len; n++) {
  6470. elm = form.elements[n];
  6471. if (elm.type == 'hidden')
  6472. continue;
  6473. // remember which elem was disabled before lock
  6474. if (lock && elm.disabled)
  6475. this.disabled_form_elements.push(elm);
  6476. else if (lock || $.inArray(elm, this.disabled_form_elements) < 0)
  6477. elm.disabled = lock;
  6478. }
  6479. };
  6480. this.mailto_handler_uri = function()
  6481. {
  6482. return location.href.split('?')[0] + '?_task=mail&_action=compose&_to=%s';
  6483. };
  6484. this.register_protocol_handler = function(name)
  6485. {
  6486. try {
  6487. window.navigator.registerProtocolHandler('mailto', this.mailto_handler_uri(), name);
  6488. }
  6489. catch(e) {
  6490. this.display_message(String(e), 'error');
  6491. }
  6492. };
  6493. this.check_protocol_handler = function(name, elem)
  6494. {
  6495. var nav = window.navigator;
  6496. if (!nav || (typeof nav.registerProtocolHandler != 'function')) {
  6497. $(elem).addClass('disabled').click(function(){ return false; });
  6498. }
  6499. else if (typeof nav.isProtocolHandlerRegistered == 'function') {
  6500. var status = nav.isProtocolHandlerRegistered('mailto', this.mailto_handler_uri());
  6501. if (status)
  6502. $(elem).parent().find('.mailtoprotohandler-status').html(status);
  6503. }
  6504. else {
  6505. $(elem).click(function() { ref.register_protocol_handler(name); return false; });
  6506. }
  6507. };
  6508. // Checks browser capabilities eg. PDF support, TIF support
  6509. this.browser_capabilities_check = function()
  6510. {
  6511. if (!this.env.browser_capabilities)
  6512. this.env.browser_capabilities = {};
  6513. if (this.env.browser_capabilities.pdf === undefined)
  6514. this.env.browser_capabilities.pdf = this.pdf_support_check();
  6515. if (this.env.browser_capabilities.flash === undefined)
  6516. this.env.browser_capabilities.flash = this.flash_support_check();
  6517. if (this.env.browser_capabilities.tif === undefined)
  6518. this.tif_support_check();
  6519. };
  6520. // Returns browser capabilities string
  6521. this.browser_capabilities = function()
  6522. {
  6523. if (!this.env.browser_capabilities)
  6524. return '';
  6525. var n, ret = [];
  6526. for (n in this.env.browser_capabilities)
  6527. ret.push(n + '=' + this.env.browser_capabilities[n]);
  6528. return ret.join();
  6529. };
  6530. this.tif_support_check = function()
  6531. {
  6532. var img = new Image();
  6533. img.onload = function() { ref.env.browser_capabilities.tif = 1; };
  6534. img.onerror = function() { ref.env.browser_capabilities.tif = 0; };
  6535. img.src = 'program/resources/blank.tif';
  6536. };
  6537. this.pdf_support_check = function()
  6538. {
  6539. var plugin = navigator.mimeTypes ? navigator.mimeTypes["application/pdf"] : {},
  6540. plugins = navigator.plugins,
  6541. len = plugins.length,
  6542. regex = /Adobe Reader|PDF|Acrobat/i;
  6543. if (plugin && plugin.enabledPlugin)
  6544. return 1;
  6545. if (window.ActiveXObject) {
  6546. try {
  6547. if (plugin = new ActiveXObject("AcroPDF.PDF"))
  6548. return 1;
  6549. }
  6550. catch (e) {}
  6551. try {
  6552. if (plugin = new ActiveXObject("PDF.PdfCtrl"))
  6553. return 1;
  6554. }
  6555. catch (e) {}
  6556. }
  6557. for (i=0; i<len; i++) {
  6558. plugin = plugins[i];
  6559. if (typeof plugin === 'String') {
  6560. if (regex.test(plugin))
  6561. return 1;
  6562. }
  6563. else if (plugin.name && regex.test(plugin.name))
  6564. return 1;
  6565. }
  6566. return 0;
  6567. };
  6568. this.flash_support_check = function()
  6569. {
  6570. var plugin = navigator.mimeTypes ? navigator.mimeTypes["application/x-shockwave-flash"] : {};
  6571. if (plugin && plugin.enabledPlugin)
  6572. return 1;
  6573. if (window.ActiveXObject) {
  6574. try {
  6575. if (plugin = new ActiveXObject("ShockwaveFlash.ShockwaveFlash"))
  6576. return 1;
  6577. }
  6578. catch (e) {}
  6579. }
  6580. return 0;
  6581. };
  6582. // Cookie setter
  6583. this.set_cookie = function(name, value, expires)
  6584. {
  6585. setCookie(name, value, expires, this.env.cookie_path, this.env.cookie_domain, this.env.cookie_secure);
  6586. };
  6587. this.get_local_storage_prefix = function()
  6588. {
  6589. if (!this.local_storage_prefix)
  6590. this.local_storage_prefix = 'roundcube.' + (this.env.user_id || 'anonymous') + '.';
  6591. return this.local_storage_prefix;
  6592. };
  6593. // wrapper for localStorage.getItem(key)
  6594. this.local_storage_get_item = function(key, deflt, encrypted)
  6595. {
  6596. var item;
  6597. // TODO: add encryption
  6598. try {
  6599. item = localStorage.getItem(this.get_local_storage_prefix() + key);
  6600. }
  6601. catch (e) { }
  6602. return item !== null ? JSON.parse(item) : (deflt || null);
  6603. };
  6604. // wrapper for localStorage.setItem(key, data)
  6605. this.local_storage_set_item = function(key, data, encrypted)
  6606. {
  6607. // try/catch to handle no localStorage support, but also error
  6608. // in Safari-in-private-browsing-mode where localStorage exists
  6609. // but can't be used (#1489996)
  6610. try {
  6611. // TODO: add encryption
  6612. localStorage.setItem(this.get_local_storage_prefix() + key, JSON.stringify(data));
  6613. return true;
  6614. }
  6615. catch (e) {
  6616. return false;
  6617. }
  6618. };
  6619. // wrapper for localStorage.removeItem(key)
  6620. this.local_storage_remove_item = function(key)
  6621. {
  6622. try {
  6623. localStorage.removeItem(this.get_local_storage_prefix() + key);
  6624. return true;
  6625. }
  6626. catch (e) {
  6627. return false;
  6628. }
  6629. };
  6630. } // end object rcube_webmail
  6631. // some static methods
  6632. rcube_webmail.long_subject_title = function(elem, indent)
  6633. {
  6634. if (!elem.title) {
  6635. var $elem = $(elem);
  6636. if ($elem.width() + (indent || 0) * 15 > $elem.parent().width())
  6637. elem.title = $elem.text();
  6638. }
  6639. };
  6640. rcube_webmail.long_subject_title_ex = function(elem)
  6641. {
  6642. if (!elem.title) {
  6643. var $elem = $(elem),
  6644. txt = $.trim($elem.text()),
  6645. tmp = $('<span>').text(txt)
  6646. .css({'position': 'absolute', 'float': 'left', 'visibility': 'hidden',
  6647. 'font-size': $elem.css('font-size'), 'font-weight': $elem.css('font-weight')})
  6648. .appendTo($('body')),
  6649. w = tmp.width();
  6650. tmp.remove();
  6651. if (w + $('span.branch', $elem).width() * 15 > $elem.width())
  6652. elem.title = txt;
  6653. }
  6654. };
  6655. rcube_webmail.prototype.get_cookie = getCookie;
  6656. // copy event engine prototype
  6657. rcube_webmail.prototype.addEventListener = rcube_event_engine.prototype.addEventListener;
  6658. rcube_webmail.prototype.removeEventListener = rcube_event_engine.prototype.removeEventListener;
  6659. rcube_webmail.prototype.triggerEvent = rcube_event_engine.prototype.triggerEvent;