PageRenderTime 33ms CodeModel.GetById 4ms RepoModel.GetById 0ms app.codeStats 1ms

/etc/apps/webmail/program/steps/mail/func.inc

https://github.com/raiman264/zpanelx
PHP | 2127 lines | 1491 code | 330 blank | 306 comment | 408 complexity | 7587a3b9575e0dff78053191af489f0f MD5 | raw file
Possible License(s): GPL-2.0, LGPL-3.0, LGPL-2.1, CC-BY-SA-4.0, GPL-3.0
  1. <?php
  2. /*
  3. +-----------------------------------------------------------------------+
  4. | program/steps/mail/func.inc |
  5. | |
  6. | This file is part of the Roundcube Webmail client |
  7. | Copyright (C) 2005-2014, The Roundcube Dev Team |
  8. | |
  9. | Licensed under the GNU General Public License version 3 or |
  10. | any later version with exceptions for skins & plugins. |
  11. | See the README file for a full license statement. |
  12. | |
  13. | PURPOSE: |
  14. | Provide webmail functionality and GUI objects |
  15. | |
  16. +-----------------------------------------------------------------------+
  17. | Author: Thomas Bruederli <roundcube@gmail.com> |
  18. | Author: Aleksander Machniak <alec@alec.pl> |
  19. +-----------------------------------------------------------------------+
  20. */
  21. // always instantiate storage object (but not connect to server yet)
  22. $RCMAIL->storage_init();
  23. // set imap properties and session vars
  24. if (strlen(trim($mbox = rcube_utils::get_input_value('_mbox', rcube_utils::INPUT_GPC, true)))) {
  25. $RCMAIL->storage->set_folder(($_SESSION['mbox'] = $mbox));
  26. }
  27. else if ($RCMAIL->storage) {
  28. $_SESSION['mbox'] = $RCMAIL->storage->get_folder();
  29. }
  30. if (!empty($_GET['_page'])) {
  31. $RCMAIL->storage->set_page(($_SESSION['page'] = intval($_GET['_page'])));
  32. }
  33. $a_threading = $RCMAIL->config->get('message_threading', array());
  34. $message_sort_col = $RCMAIL->config->get('message_sort_col');
  35. $message_sort_order = $RCMAIL->config->get('message_sort_order');
  36. // set default sort col/order to session
  37. if (!isset($_SESSION['sort_col'])) {
  38. $_SESSION['sort_col'] = $message_sort_col ? $message_sort_col : '';
  39. }
  40. if (!isset($_SESSION['sort_order'])) {
  41. $_SESSION['sort_order'] = strtoupper($message_sort_order) == 'ASC' ? 'ASC' : 'DESC';
  42. }
  43. // set threads mode
  44. if (isset($_GET['_threads'])) {
  45. if ($_GET['_threads'])
  46. $a_threading[$_SESSION['mbox']] = true;
  47. else
  48. unset($a_threading[$_SESSION['mbox']]);
  49. $RCMAIL->user->save_prefs(array('message_threading' => $a_threading));
  50. }
  51. $RCMAIL->storage->set_threading($a_threading[$_SESSION['mbox']]);
  52. // set message set for search result
  53. if (!empty($_REQUEST['_search']) && isset($_SESSION['search'])
  54. && $_SESSION['search_request'] == $_REQUEST['_search']
  55. ) {
  56. $RCMAIL->storage->set_search_set($_SESSION['search']);
  57. $OUTPUT->set_env('search_request', $_REQUEST['_search']);
  58. $OUTPUT->set_env('search_text', $_SESSION['last_text_search']);
  59. }
  60. // set main env variables, labels and page title
  61. if (empty($RCMAIL->action) || $RCMAIL->action == 'list') {
  62. // connect to storage server and trigger error on failure
  63. $RCMAIL->storage_connect();
  64. $mbox_name = $RCMAIL->storage->get_folder();
  65. if (empty($RCMAIL->action)) {
  66. // initialize searching result if search_filter is used
  67. if ($_SESSION['search_filter'] && $_SESSION['search_filter'] != 'ALL') {
  68. $RCMAIL->storage->search($mbox_name, $_SESSION['search_filter'], RCUBE_CHARSET, rcmail_sort_column());
  69. $search_request = md5($mbox_name.$_SESSION['search_filter']);
  70. $_SESSION['search'] = $RCMAIL->storage->get_search_set();
  71. $_SESSION['search_request'] = $search_request;
  72. $OUTPUT->set_env('search_request', $search_request);
  73. }
  74. $OUTPUT->set_env('search_mods', rcmail_search_mods());
  75. }
  76. $threading = (bool) $RCMAIL->storage->get_threading();
  77. $delimiter = $RCMAIL->storage->get_hierarchy_delimiter();
  78. // set current mailbox and some other vars in client environment
  79. $OUTPUT->set_env('mailbox', $mbox_name);
  80. $OUTPUT->set_env('pagesize', $RCMAIL->storage->get_pagesize());
  81. $OUTPUT->set_env('delimiter', $delimiter);
  82. $OUTPUT->set_env('threading', $threading);
  83. $OUTPUT->set_env('threads', $threading || $RCMAIL->storage->get_capability('THREAD'));
  84. $OUTPUT->set_env('reply_all_mode', (int) $RCMAIL->config->get('reply_all_mode'));
  85. $OUTPUT->set_env('preview_pane_mark_read', $RCMAIL->config->get('preview_pane_mark_read', 0));
  86. if ($RCMAIL->storage->get_capability('QUOTA')) {
  87. $OUTPUT->set_env('quota', true);
  88. }
  89. // set special folders
  90. foreach (array('drafts', 'trash', 'junk') as $mbox) {
  91. if ($folder = $RCMAIL->config->get($mbox . '_mbox')) {
  92. $OUTPUT->set_env($mbox . '_mailbox', $folder);
  93. }
  94. }
  95. // set configuration
  96. $RCMAIL->set_env_config(array('delete_junk', 'flag_for_deletion', 'read_when_deleted',
  97. 'skip_deleted', 'display_next', 'message_extwin', 'compose_extwin', 'forward_attachment'));
  98. if (!empty($_SESSION['browser_caps'])) {
  99. $OUTPUT->set_env('browser_capabilities', $_SESSION['browser_caps']);
  100. }
  101. if (!$OUTPUT->ajax_call) {
  102. $OUTPUT->add_label('checkingmail', 'deletemessage', 'movemessagetotrash',
  103. 'movingmessage', 'copyingmessage', 'deletingmessage', 'markingmessage',
  104. 'copy', 'move', 'quota', 'replyall', 'replylist');
  105. }
  106. $pagetitle = $RCMAIL->localize_foldername($RCMAIL->storage->mod_folder($mbox_name), true);
  107. $pagetitle = str_replace($delimiter, " \xC2\xBB ", $pagetitle);
  108. $OUTPUT->set_pagetitle($pagetitle);
  109. }
  110. // register UI objects
  111. $OUTPUT->add_handlers(array(
  112. 'mailboxlist' => array($RCMAIL, 'folder_list'),
  113. 'quotadisplay' => array($RCMAIL, 'quota_display'),
  114. 'messages' => 'rcmail_message_list',
  115. 'messagecountdisplay' => 'rcmail_messagecount_display',
  116. 'mailboxname' => 'rcmail_mailbox_name_display',
  117. 'messageheaders' => 'rcmail_message_headers',
  118. 'messagefullheaders' => 'rcmail_message_full_headers',
  119. 'messagebody' => 'rcmail_message_body',
  120. 'messagecontentframe' => 'rcmail_messagecontent_frame',
  121. 'messageimportform' => 'rcmail_message_import_form',
  122. 'searchfilter' => 'rcmail_search_filter',
  123. 'searchform' => array($OUTPUT, 'search_form'),
  124. ));
  125. // register action aliases
  126. $RCMAIL->register_action_map(array(
  127. 'refresh' => 'check_recent.inc',
  128. 'preview' => 'show.inc',
  129. 'print' => 'show.inc',
  130. 'move' => 'move_del.inc',
  131. 'delete' => 'move_del.inc',
  132. 'send' => 'sendmail.inc',
  133. 'expunge' => 'folders.inc',
  134. 'purge' => 'folders.inc',
  135. 'remove-attachment' => 'attachments.inc',
  136. 'display-attachment' => 'attachments.inc',
  137. 'upload' => 'attachments.inc',
  138. 'group-expand' => 'autocomplete.inc',
  139. ));
  140. /**
  141. * Returns default search mods
  142. */
  143. function rcmail_search_mods()
  144. {
  145. global $RCMAIL;
  146. $mods = $RCMAIL->config->get('search_mods');
  147. if (empty($mods)) {
  148. $mods = array('*' => array('subject' => 1, 'from' => 1));
  149. foreach (array('sent', 'drafts') as $mbox) {
  150. if ($mbox = $RCMAIL->config->get($mbox . '_mbox')) {
  151. $mods[$mbox] = array('subject' => 1, 'to' => 1);
  152. }
  153. }
  154. }
  155. return $mods;
  156. }
  157. /**
  158. * Returns 'to' if current folder is configured Sent or Drafts
  159. * or their subfolders, otherwise returns 'from'.
  160. *
  161. * @return string Column name
  162. */
  163. function rcmail_message_list_smart_column_name()
  164. {
  165. global $RCMAIL;
  166. $delim = $RCMAIL->storage->get_hierarchy_delimiter();
  167. $mbox = $RCMAIL->storage->get_folder();
  168. $sent_mbox = $RCMAIL->config->get('sent_mbox');
  169. $drafts_mbox = $RCMAIL->config->get('drafts_mbox');
  170. if ((strpos($mbox.$delim, $sent_mbox.$delim) === 0 || strpos($mbox.$delim, $drafts_mbox.$delim) === 0)
  171. && strtoupper($mbox) != 'INBOX'
  172. ) {
  173. return 'to';
  174. }
  175. return 'from';
  176. }
  177. /**
  178. * Returns configured messages list sorting column name
  179. * The name is context-sensitive, which means if sorting is set to 'fromto'
  180. * it will return 'from' or 'to' according to current folder type.
  181. *
  182. * @return string Column name
  183. */
  184. function rcmail_sort_column()
  185. {
  186. global $RCMAIL;
  187. if (isset($_SESSION['sort_col'])) {
  188. $column = $_SESSION['sort_col'];
  189. }
  190. else {
  191. $column = $RCMAIL->config->get('message_sort_col');
  192. }
  193. // get name of smart From/To column in folder context
  194. if ($column == 'fromto') {
  195. $column = rcmail_message_list_smart_column_name();
  196. }
  197. return $column;
  198. }
  199. /**
  200. * Returns configured message list sorting order
  201. *
  202. * @return string Sorting order (ASC|DESC)
  203. */
  204. function rcmail_sort_order()
  205. {
  206. global $RCMAIL;
  207. if (isset($_SESSION['sort_order'])) {
  208. return $_SESSION['sort_order'];
  209. }
  210. return $RCMAIL->config->get('message_sort_order');
  211. }
  212. /**
  213. * return the message list as HTML table
  214. */
  215. function rcmail_message_list($attrib)
  216. {
  217. global $RCMAIL, $OUTPUT;
  218. // add some labels to client
  219. $OUTPUT->add_label('from', 'to');
  220. // add id to message list table if not specified
  221. if (!strlen($attrib['id']))
  222. $attrib['id'] = 'rcubemessagelist';
  223. // define list of cols to be displayed based on parameter or config
  224. if (empty($attrib['columns'])) {
  225. $list_cols = $RCMAIL->config->get('list_cols');
  226. $a_show_cols = !empty($list_cols) && is_array($list_cols) ? $list_cols : array('subject');
  227. $OUTPUT->set_env('col_movable', !in_array('list_cols', (array)$RCMAIL->config->get('dont_override')));
  228. }
  229. else {
  230. $a_show_cols = preg_split('/[\s,;]+/', str_replace(array("'", '"'), '', $attrib['columns']));
  231. $attrib['columns'] = $a_show_cols;
  232. }
  233. // save some variables for use in ajax list
  234. $_SESSION['list_attrib'] = $attrib;
  235. // make sure 'threads' and 'subject' columns are present
  236. if (!in_array('subject', $a_show_cols))
  237. array_unshift($a_show_cols, 'subject');
  238. if (!in_array('threads', $a_show_cols))
  239. array_unshift($a_show_cols, 'threads');
  240. $_SESSION['skin_path'] = $RCMAIL->config->get('skin_path');
  241. // set client env
  242. $OUTPUT->add_gui_object('messagelist', $attrib['id']);
  243. $OUTPUT->set_env('autoexpand_threads', intval($RCMAIL->config->get('autoexpand_threads')));
  244. $OUTPUT->set_env('sort_col', $_SESSION['sort_col']);
  245. $OUTPUT->set_env('sort_order', $_SESSION['sort_order']);
  246. $OUTPUT->set_env('messages', array());
  247. $OUTPUT->set_env('coltypes', $a_show_cols);
  248. $OUTPUT->include_script('list.js');
  249. $table = new html_table($attrib);
  250. if (!$attrib['noheader']) {
  251. foreach (rcmail_message_list_head($attrib, $a_show_cols) as $cell)
  252. $table->add_header(array('class' => $cell['className'], 'id' => $cell['id']), $cell['html']);
  253. }
  254. return $table->show();
  255. }
  256. /**
  257. * return javascript commands to add rows to the message list
  258. */
  259. function rcmail_js_message_list($a_headers, $insert_top=FALSE, $a_show_cols=null)
  260. {
  261. global $RCMAIL, $OUTPUT;
  262. if (empty($a_show_cols)) {
  263. if (!empty($_SESSION['list_attrib']['columns']))
  264. $a_show_cols = $_SESSION['list_attrib']['columns'];
  265. else {
  266. $list_cols = $RCMAIL->config->get('list_cols');
  267. $a_show_cols = !empty($list_cols) && is_array($list_cols) ? $list_cols : array('subject');
  268. }
  269. }
  270. else {
  271. if (!is_array($a_show_cols)) {
  272. $a_show_cols = preg_split('/[\s,;]+/', str_replace(array("'", '"'), '', $a_show_cols));
  273. }
  274. $head_replace = true;
  275. }
  276. $mbox = $RCMAIL->storage->get_folder();
  277. // make sure 'threads' and 'subject' columns are present
  278. if (!in_array('subject', $a_show_cols))
  279. array_unshift($a_show_cols, 'subject');
  280. if (!in_array('threads', $a_show_cols))
  281. array_unshift($a_show_cols, 'threads');
  282. $_SESSION['list_attrib']['columns'] = $a_show_cols;
  283. // Make sure there are no duplicated columns (#1486999)
  284. $a_show_cols = array_unique($a_show_cols);
  285. // Plugins may set header's list_cols/list_flags and other rcube_message_header variables
  286. // and list columns
  287. $plugin = $RCMAIL->plugins->exec_hook('messages_list',
  288. array('messages' => $a_headers, 'cols' => $a_show_cols));
  289. $a_show_cols = $plugin['cols'];
  290. $a_headers = $plugin['messages'];
  291. $thead = $head_replace ? rcmail_message_list_head($_SESSION['list_attrib'], $a_show_cols) : NULL;
  292. // get name of smart From/To column in folder context
  293. if (array_search('fromto', $a_show_cols) !== false) {
  294. $smart_col = rcmail_message_list_smart_column_name();
  295. }
  296. $OUTPUT->command('set_message_coltypes', $a_show_cols, $thead, $smart_col);
  297. if (empty($a_headers)) {
  298. return;
  299. }
  300. // remove 'threads', 'attachment', 'flag', 'status' columns, we don't need them here
  301. foreach (array('threads', 'attachment', 'flag', 'status', 'priority') as $col) {
  302. if (($key = array_search($col, $a_show_cols)) !== FALSE) {
  303. unset($a_show_cols[$key]);
  304. }
  305. }
  306. // loop through message headers
  307. foreach ($a_headers as $header) {
  308. if (empty($header))
  309. continue;
  310. $a_msg_cols = array();
  311. $a_msg_flags = array();
  312. // format each col; similar as in rcmail_message_list()
  313. foreach ($a_show_cols as $col) {
  314. $col_name = $col == 'fromto' ? $smart_col : $col;
  315. if (in_array($col_name, array('from', 'to', 'cc', 'replyto')))
  316. $cont = rcmail_address_string($header->$col_name, 3, false, null, $header->charset);
  317. else if ($col == 'subject') {
  318. $cont = trim(rcube_mime::decode_header($header->$col, $header->charset));
  319. if (!$cont) $cont = $RCMAIL->gettext('nosubject');
  320. $cont = rcube::Q($cont);
  321. }
  322. else if ($col == 'size')
  323. $cont = show_bytes($header->$col);
  324. else if ($col == 'date')
  325. $cont = $RCMAIL->format_date($header->date);
  326. else
  327. $cont = rcube::Q($header->$col);
  328. $a_msg_cols[$col] = $cont;
  329. }
  330. $a_msg_flags = array_change_key_case(array_map('intval', (array) $header->flags));
  331. if ($header->depth)
  332. $a_msg_flags['depth'] = $header->depth;
  333. else if ($header->has_children)
  334. $roots[] = $header->uid;
  335. if ($header->parent_uid)
  336. $a_msg_flags['parent_uid'] = $header->parent_uid;
  337. if ($header->has_children)
  338. $a_msg_flags['has_children'] = $header->has_children;
  339. if ($header->unread_children)
  340. $a_msg_flags['unread_children'] = $header->unread_children;
  341. if ($header->others['list-post'])
  342. $a_msg_flags['ml'] = 1;
  343. if ($header->priority)
  344. $a_msg_flags['prio'] = (int) $header->priority;
  345. $a_msg_flags['ctype'] = rcube::Q($header->ctype);
  346. $a_msg_flags['mbox'] = $mbox;
  347. // merge with plugin result (Deprecated, use $header->flags)
  348. if (!empty($header->list_flags) && is_array($header->list_flags))
  349. $a_msg_flags = array_merge($a_msg_flags, $header->list_flags);
  350. if (!empty($header->list_cols) && is_array($header->list_cols))
  351. $a_msg_cols = array_merge($a_msg_cols, $header->list_cols);
  352. $OUTPUT->command('add_message_row',
  353. $header->uid,
  354. $a_msg_cols,
  355. $a_msg_flags,
  356. $insert_top);
  357. }
  358. if ($RCMAIL->storage->get_threading()) {
  359. $OUTPUT->command('init_threads', (array) $roots, $mbox);
  360. }
  361. }
  362. /*
  363. * Creates <THEAD> for message list table
  364. */
  365. function rcmail_message_list_head($attrib, $a_show_cols)
  366. {
  367. global $RCMAIL;
  368. $skin_path = $_SESSION['skin_path'];
  369. // check to see if we have some settings for sorting
  370. $sort_col = $_SESSION['sort_col'];
  371. $sort_order = $_SESSION['sort_order'];
  372. $dont_override = (array) $RCMAIL->config->get('dont_override');
  373. $disabled_sort = in_array('message_sort_col', $dont_override);
  374. $disabled_order = in_array('message_sort_order', $dont_override);
  375. $RCMAIL->output->set_env('disabled_sort_col', $disabled_sort);
  376. $RCMAIL->output->set_env('disabled_sort_order', $disabled_order);
  377. // define sortable columns
  378. if ($disabled_sort)
  379. $a_sort_cols = $sort_col && !$disabled_order ? array($sort_col) : array();
  380. else
  381. $a_sort_cols = array('subject', 'date', 'from', 'to', 'fromto', 'size', 'cc');
  382. if (!empty($attrib['optionsmenuicon'])) {
  383. $onclick = 'return ' . rcmail_output::JS_OBJECT_NAME . ".command('menu-open', 'messagelistmenu')";
  384. if ($attrib['optionsmenuicon'] === true || $attrib['optionsmenuicon'] == 'true')
  385. $list_menu = html::div(array('onclick' => $onclick, 'class' => 'listmenu',
  386. 'id' => 'listmenulink', 'title' => $RCMAIL->gettext('listoptions')));
  387. else
  388. $list_menu = html::a(array('href' => '#', 'onclick' => $onclick),
  389. html::img(array('src' => $skin_path . $attrib['optionsmenuicon'],
  390. 'id' => 'listmenulink', 'title' => $RCMAIL->gettext('listoptions'))));
  391. }
  392. else {
  393. $list_menu = '';
  394. }
  395. $cells = array();
  396. // get name of smart From/To column in folder context
  397. if (array_search('fromto', $a_show_cols) !== false) {
  398. $smart_col = rcmail_message_list_smart_column_name();
  399. }
  400. foreach ($a_show_cols as $col) {
  401. // get column name
  402. switch ($col) {
  403. case 'flag':
  404. $col_name = '<span class="flagged">&nbsp;</span>';
  405. break;
  406. case 'attachment':
  407. case 'priority':
  408. case 'status':
  409. $col_name = '<span class="' . $col .'">&nbsp;</span>';
  410. break;
  411. case 'threads':
  412. $col_name = $list_menu;
  413. break;
  414. case 'fromto':
  415. $col_name = rcube::Q($RCMAIL->gettext($smart_col));
  416. break;
  417. default:
  418. $col_name = rcube::Q($RCMAIL->gettext($col));
  419. }
  420. // make sort links
  421. if (in_array($col, $a_sort_cols)) {
  422. $col_name = html::a(array(
  423. 'href' => "./#sort",
  424. 'onclick' => 'return '.rcmail_output::JS_OBJECT_NAME.".command('sort','".$col."',this)",
  425. 'title' => $RCMAIL->gettext('sortby')
  426. ), $col_name);
  427. }
  428. else if ($col_name[0] != '<') {
  429. $col_name = '<span class="' . $col .'">' . $col_name . '</span>';
  430. }
  431. $sort_class = $col == $sort_col && !$disabled_order ? " sorted$sort_order" : '';
  432. $class_name = $col.$sort_class;
  433. // put it all together
  434. $cells[] = array('className' => $class_name, 'id' => "rcm$col", 'html' => $col_name);
  435. }
  436. return $cells;
  437. }
  438. /**
  439. * return an HTML iframe for loading mail content
  440. */
  441. function rcmail_messagecontent_frame($attrib)
  442. {
  443. global $OUTPUT, $RCMAIL;
  444. if (empty($attrib['id']))
  445. $attrib['id'] = 'rcmailcontentwindow';
  446. $attrib['name'] = $attrib['id'];
  447. if ($RCMAIL->config->get('preview_pane')) {
  448. $OUTPUT->set_env('contentframe', $attrib['id']);
  449. }
  450. $OUTPUT->set_env('blankpage', $attrib['src'] ? $OUTPUT->abs_url($attrib['src']) : 'program/resources/blank.gif');
  451. return $OUTPUT->frame($attrib, true);
  452. }
  453. function rcmail_messagecount_display($attrib)
  454. {
  455. global $RCMAIL;
  456. if (!$attrib['id'])
  457. $attrib['id'] = 'rcmcountdisplay';
  458. $RCMAIL->output->add_gui_object('countdisplay', $attrib['id']);
  459. $content = $RCMAIL->action != 'show' ? rcmail_get_messagecount_text() : $RCMAIL->gettext('loading');
  460. return html::span($attrib, $content);
  461. }
  462. function rcmail_get_messagecount_text($count = null, $page = null)
  463. {
  464. global $RCMAIL;
  465. if ($page === null) {
  466. $page = $RCMAIL->storage->get_page();
  467. }
  468. $page_size = $RCMAIL->storage->get_pagesize();
  469. $start_msg = ($page-1) * $page_size + 1;
  470. if ($count !== null)
  471. $max = $count;
  472. else if ($RCMAIL->action)
  473. $max = $RCMAIL->storage->count(NULL, $RCMAIL->storage->get_threading() ? 'THREADS' : 'ALL');
  474. if ($max == 0)
  475. $out = $RCMAIL->storage->get_search_set() ? $RCMAIL->gettext('nomessages') : $RCMAIL->gettext('mailboxempty');
  476. else
  477. $out = $RCMAIL->gettext(array('name' => $RCMAIL->storage->get_threading() ? 'threadsfromto' : 'messagesfromto',
  478. 'vars' => array('from' => $start_msg,
  479. 'to' => min($max, $start_msg + $page_size - 1),
  480. 'count' => $max)));
  481. return rcube::Q($out);
  482. }
  483. function rcmail_mailbox_name_display($attrib)
  484. {
  485. global $RCMAIL;
  486. if (!$attrib['id'])
  487. $attrib['id'] = 'rcmmailboxname';
  488. $RCMAIL->output->add_gui_object('mailboxname', $attrib['id']);
  489. return html::span($attrib, rcmail_get_mailbox_name_text());
  490. }
  491. function rcmail_get_mailbox_name_text()
  492. {
  493. global $RCMAIL;
  494. return $RCMAIL->localize_foldername($RCMAIL->storage->get_folder());
  495. }
  496. function rcmail_send_unread_count($mbox_name, $force=false, $count=null, $mark='')
  497. {
  498. global $RCMAIL;
  499. $old_unseen = rcmail_get_unseen_count($mbox_name);
  500. if ($count === null)
  501. $unseen = $RCMAIL->storage->count($mbox_name, 'UNSEEN', $force);
  502. else
  503. $unseen = $count;
  504. if ($unseen != $old_unseen || ($mbox_name == 'INBOX'))
  505. $RCMAIL->output->command('set_unread_count', $mbox_name, $unseen,
  506. ($mbox_name == 'INBOX'), $unseen && $mark ? $mark : '');
  507. rcmail_set_unseen_count($mbox_name, $unseen);
  508. return $unseen;
  509. }
  510. function rcmail_set_unseen_count($mbox_name, $count)
  511. {
  512. // @TODO: this data is doubled (session and cache tables) if caching is enabled
  513. // Make sure we have an array here (#1487066)
  514. if (!is_array($_SESSION['unseen_count'])) {
  515. $_SESSION['unseen_count'] = array();
  516. }
  517. $_SESSION['unseen_count'][$mbox_name] = $count;
  518. }
  519. function rcmail_get_unseen_count($mbox_name)
  520. {
  521. if (is_array($_SESSION['unseen_count']) && array_key_exists($mbox_name, $_SESSION['unseen_count'])) {
  522. return $_SESSION['unseen_count'][$mbox_name];
  523. }
  524. }
  525. /**
  526. * Sets message is_safe flag according to 'show_images' option value
  527. *
  528. * @param object rcube_message Message
  529. */
  530. function rcmail_check_safe(&$message)
  531. {
  532. global $RCMAIL;
  533. if (!$message->is_safe
  534. && ($show_images = $RCMAIL->config->get('show_images'))
  535. && $message->has_html_part()
  536. ) {
  537. switch ($show_images) {
  538. case 1: // known senders only
  539. // get default addressbook, like in addcontact.inc
  540. $CONTACTS = $RCMAIL->get_address_book(-1, true);
  541. if ($CONTACTS) {
  542. $result = $CONTACTS->search('email', $message->sender['mailto'], 1, false);
  543. if ($result->count) {
  544. $message->set_safe(true);
  545. }
  546. }
  547. $RCMAIL->plugins->exec_hook('message_check_safe', array('message' => $message));
  548. break;
  549. case 2: // always
  550. $message->set_safe(true);
  551. break;
  552. }
  553. }
  554. }
  555. /**
  556. * Cleans up the given message HTML Body (for displaying)
  557. *
  558. * @param string HTML
  559. * @param array Display parameters
  560. * @param array CID map replaces (inline images)
  561. * @return string Clean HTML
  562. */
  563. function rcmail_wash_html($html, $p, $cid_replaces)
  564. {
  565. global $REMOTE_OBJECTS;
  566. $p += array('safe' => false, 'inline_html' => true);
  567. // charset was converted to UTF-8 in rcube_storage::get_message_part(),
  568. // change/add charset specification in HTML accordingly,
  569. // washtml cannot work without that
  570. $meta = '<meta http-equiv="Content-Type" content="text/html; charset='.RCUBE_CHARSET.'" />';
  571. // remove old meta tag and add the new one, making sure
  572. // that it is placed in the head (#1488093)
  573. $html = preg_replace('/<meta[^>]+charset=[a-z0-9-_]+[^>]*>/Ui', '', $html);
  574. $html = preg_replace('/(<head[^>]*>)/Ui', '\\1'.$meta, $html, -1, $rcount);
  575. if (!$rcount) {
  576. $html = '<head>' . $meta . '</head>' . $html;
  577. }
  578. // clean HTML with washhtml by Frederic Motte
  579. $wash_opts = array(
  580. 'show_washed' => false,
  581. 'allow_remote' => $p['safe'],
  582. 'blocked_src' => "./program/resources/blocked.gif",
  583. 'charset' => RCUBE_CHARSET,
  584. 'cid_map' => $cid_replaces,
  585. 'html_elements' => array('body'),
  586. );
  587. if (!$p['inline_html']) {
  588. $wash_opts['html_elements'] = array('html','head','title','body');
  589. }
  590. if ($p['safe']) {
  591. $wash_opts['html_elements'][] = 'link';
  592. $wash_opts['html_attribs'] = array('rel','type');
  593. }
  594. // overwrite washer options with options from plugins
  595. if (isset($p['html_elements']))
  596. $wash_opts['html_elements'] = $p['html_elements'];
  597. if (isset($p['html_attribs']))
  598. $wash_opts['html_attribs'] = $p['html_attribs'];
  599. // initialize HTML washer
  600. $washer = new rcube_washtml($wash_opts);
  601. if (!$p['skip_washer_form_callback']) {
  602. $washer->add_callback('form', 'rcmail_washtml_callback');
  603. }
  604. // allow CSS styles, will be sanitized by rcmail_washtml_callback()
  605. if (!$p['skip_washer_style_callback']) {
  606. $washer->add_callback('style', 'rcmail_washtml_callback');
  607. }
  608. // Remove non-UTF8 characters (#1487813)
  609. $html = rcube_charset::clean($html);
  610. $html = $washer->wash($html);
  611. $REMOTE_OBJECTS = $washer->extlinks;
  612. return $html;
  613. }
  614. /**
  615. * Convert the given message part to proper HTML
  616. * which can be displayed the message view
  617. *
  618. * @param object rcube_message_part Message part
  619. * @param array Display parameters array
  620. * @return string Formatted HTML string
  621. */
  622. function rcmail_print_body($part, $p = array())
  623. {
  624. global $RCMAIL;
  625. // trigger plugin hook
  626. $data = $RCMAIL->plugins->exec_hook('message_part_before',
  627. array('type' => $part->ctype_secondary, 'body' => $part->body, 'id' => $part->mime_id)
  628. + $p + array('safe' => false, 'plain' => false, 'inline_html' => true));
  629. // convert html to text/plain
  630. if ($data['plain'] && ($data['type'] == 'html' || $data['type'] == 'enriched')) {
  631. if ($data['type'] == 'enriched') {
  632. $data['body'] = rcube_enriched::to_html($data['body']);
  633. }
  634. $txt = new rcube_html2text($data['body'], false, true);
  635. $body = $txt->get_text();
  636. $part->ctype_secondary = 'plain';
  637. }
  638. // text/html
  639. else if ($data['type'] == 'html') {
  640. $body = rcmail_wash_html($data['body'], $data, $part->replaces);
  641. $part->ctype_secondary = $data['type'];
  642. }
  643. // text/enriched
  644. else if ($data['type'] == 'enriched') {
  645. $body = rcube_enriched::to_html($data['body']);
  646. $body = rcmail_wash_html($body, $data, $part->replaces);
  647. $part->ctype_secondary = 'html';
  648. }
  649. else {
  650. // assert plaintext
  651. $body = $part->body;
  652. $part->ctype_secondary = $data['type'] = 'plain';
  653. }
  654. // free some memory (hopefully)
  655. unset($data['body']);
  656. // plaintext postprocessing
  657. if ($part->ctype_secondary == 'plain') {
  658. if ($part->ctype_secondary == 'plain' && $part->ctype_parameters['format'] == 'flowed') {
  659. $body = rcube_mime::unfold_flowed($body);
  660. }
  661. $body = rcmail_plain_body($body);
  662. }
  663. // allow post-processing of the message body
  664. $data = $RCMAIL->plugins->exec_hook('message_part_after',
  665. array('type' => $part->ctype_secondary, 'body' => $body, 'id' => $part->mime_id) + $data);
  666. return $data['type'] == 'html' ? $data['body'] : html::tag('pre', array(), $data['body']);
  667. }
  668. /**
  669. * Handle links and citation marks in plain text message
  670. *
  671. * @param string Plain text string
  672. *
  673. * @return string Formatted HTML string
  674. */
  675. function rcmail_plain_body($body)
  676. {
  677. global $RCMAIL;
  678. // make links and email-addresses clickable
  679. $attribs = array('link_attribs' => array('rel' => 'noreferrer', 'target' => '_blank'));
  680. $replacer = new rcmail_string_replacer($attribs);
  681. // search for patterns like links and e-mail addresses and replace with tokens
  682. $body = $replacer->replace($body);
  683. // split body into single lines
  684. $body = preg_split('/\r?\n/', $body);
  685. $quote_level = 0;
  686. $last = -1;
  687. // find/mark quoted lines...
  688. for ($n=0, $cnt=count($body); $n < $cnt; $n++) {
  689. if ($body[$n][0] == '>' && preg_match('/^(>+ {0,1})+/', $body[$n], $regs)) {
  690. $q = substr_count($regs[0], '>');
  691. $body[$n] = substr($body[$n], strlen($regs[0]));
  692. if ($q > $quote_level) {
  693. $body[$n] = $replacer->get_replacement($replacer->add(
  694. str_repeat('<blockquote>', $q - $quote_level))) . $body[$n];
  695. $last = $n;
  696. }
  697. else if ($q < $quote_level) {
  698. $body[$n] = $replacer->get_replacement($replacer->add(
  699. str_repeat('</blockquote>', $quote_level - $q))) . $body[$n];
  700. $last = $n;
  701. }
  702. }
  703. else {
  704. $q = 0;
  705. if ($quote_level > 0)
  706. $body[$n] = $replacer->get_replacement($replacer->add(
  707. str_repeat('</blockquote>', $quote_level))) . $body[$n];
  708. }
  709. $quote_level = $q;
  710. }
  711. $body = join("\n", $body);
  712. // quote plain text (don't use rcube::Q() here, to display entities "as is")
  713. $table = get_html_translation_table(HTML_SPECIALCHARS);
  714. unset($table['?']);
  715. $body = strtr($body, $table);
  716. // colorize signature (up to <sig_max_lines> lines)
  717. $len = strlen($body);
  718. $sig_max_lines = $RCMAIL->config->get('sig_max_lines', 15);
  719. while (($sp = strrpos($body, "-- \n", $sp ? -$len+$sp-1 : 0)) !== false) {
  720. if ($sp == 0 || $body[$sp-1] == "\n") {
  721. // do not touch blocks with more that X lines
  722. if (substr_count($body, "\n", $sp) < $sig_max_lines) {
  723. $body = substr($body, 0, max(0, $sp))
  724. . '<span class="sig">'.substr($body, $sp).'</span>';
  725. }
  726. break;
  727. }
  728. }
  729. // insert url/mailto links and citation tags
  730. $body = $replacer->resolve($body);
  731. return $body;
  732. }
  733. /**
  734. * Callback function for washtml cleaning class
  735. */
  736. function rcmail_washtml_callback($tagname, $attrib, $content, $washtml)
  737. {
  738. switch ($tagname) {
  739. case 'form':
  740. $out = html::div('form', $content);
  741. break;
  742. case 'style':
  743. // decode all escaped entities and reduce to ascii strings
  744. $stripped = preg_replace('/[^a-zA-Z\(:;]/', '', rcube_utils::xss_entity_decode($content));
  745. // now check for evil strings like expression, behavior or url()
  746. if (!preg_match('/expression|behavior|javascript:|import[^a]/i', $stripped)) {
  747. if (!$washtml->get_config('allow_remote') && stripos($stripped, 'url('))
  748. $washtml->extlinks = true;
  749. else
  750. $out = html::tag('style', array('type' => 'text/css'), $content);
  751. break;
  752. }
  753. default:
  754. $out = '';
  755. }
  756. return $out;
  757. }
  758. /**
  759. * return table with message headers
  760. */
  761. function rcmail_message_headers($attrib, $headers=null)
  762. {
  763. global $MESSAGE, $PRINT_MODE, $RCMAIL;
  764. static $sa_attrib;
  765. // keep header table attrib
  766. if (is_array($attrib) && !$sa_attrib && !$attrib['valueof'])
  767. $sa_attrib = $attrib;
  768. else if (!is_array($attrib) && is_array($sa_attrib))
  769. $attrib = $sa_attrib;
  770. if (!isset($MESSAGE)) {
  771. return false;
  772. }
  773. // get associative array of headers object
  774. if (!$headers) {
  775. $headers_obj = $MESSAGE->headers;
  776. $headers = get_object_vars($MESSAGE->headers);
  777. }
  778. else if (is_object($headers)) {
  779. $headers_obj = $headers;
  780. $headers = get_object_vars($headers_obj);
  781. }
  782. else {
  783. $headers_obj = rcube_message_header::from_array($headers);
  784. }
  785. // show these headers
  786. $standard_headers = array('subject', 'from', 'sender', 'to', 'cc', 'bcc', 'replyto',
  787. 'mail-reply-to', 'mail-followup-to', 'date', 'priority');
  788. $exclude_headers = $attrib['exclude'] ? explode(',', $attrib['exclude']) : array();
  789. $output_headers = array();
  790. foreach ($standard_headers as $hkey) {
  791. $ishtml = false;
  792. if ($headers[$hkey])
  793. $value = $headers[$hkey];
  794. else if ($headers['others'][$hkey])
  795. $value = $headers['others'][$hkey];
  796. else if (!$attrib['valueof'])
  797. continue;
  798. if (in_array($hkey, $exclude_headers))
  799. continue;
  800. $header_title = $RCMAIL->gettext(preg_replace('/(^mail-|-)/', '', $hkey));
  801. if ($hkey == 'date') {
  802. if ($PRINT_MODE)
  803. $header_value = $RCMAIL->format_date($value, $RCMAIL->config->get('date_long', 'x'));
  804. else
  805. $header_value = $RCMAIL->format_date($value);
  806. }
  807. else if ($hkey == 'priority') {
  808. if ($value) {
  809. $header_value = html::span('prio' . $value, rcmail_localized_priority($value));
  810. }
  811. else
  812. continue;
  813. }
  814. else if ($hkey == 'replyto') {
  815. if ($headers['replyto'] != $headers['from']) {
  816. $header_value = rcmail_address_string($value, $attrib['max'], true,
  817. $attrib['addicon'], $headers['charset'], $header_title);
  818. $ishtml = true;
  819. }
  820. else
  821. continue;
  822. }
  823. else if ($hkey == 'mail-reply-to') {
  824. if ($headers['mail-replyto'] != $headers['reply-to']
  825. && $headers['reply-to'] != $headers['from']
  826. ) {
  827. $header_value = rcmail_address_string($value, $attrib['max'], true,
  828. $attrib['addicon'], $headers['charset'], $header_title);
  829. $ishtml = true;
  830. }
  831. else
  832. continue;
  833. }
  834. else if ($hkey == 'sender') {
  835. if ($headers['sender'] != $headers['from']) {
  836. $header_value = rcmail_address_string($value, $attrib['max'], true,
  837. $attrib['addicon'], $headers['charset'], $header_title);
  838. $ishtml = true;
  839. }
  840. else
  841. continue;
  842. }
  843. else if ($hkey == 'mail-followup-to') {
  844. $header_value = rcmail_address_string($value, $attrib['max'], true,
  845. $attrib['addicon'], $headers['charset'], $header_title);
  846. $ishtml = true;
  847. }
  848. else if (in_array($hkey, array('from', 'to', 'cc', 'bcc'))) {
  849. $header_value = rcmail_address_string($value, $attrib['max'], true,
  850. $attrib['addicon'], $headers['charset'], $header_title);
  851. $ishtml = true;
  852. }
  853. else if ($hkey == 'subject' && empty($value))
  854. $header_value = $RCMAIL->gettext('nosubject');
  855. else
  856. $header_value = trim(rcube_mime::decode_header($value, $headers['charset']));
  857. $output_headers[$hkey] = array(
  858. 'title' => $header_title,
  859. 'value' => $header_value,
  860. 'raw' => $value,
  861. 'html' => $ishtml,
  862. );
  863. }
  864. $plugin = $RCMAIL->plugins->exec_hook('message_headers_output', array(
  865. 'output' => $output_headers,
  866. 'headers' => $headers_obj,
  867. 'exclude' => $exclude_headers
  868. ));
  869. // single header value is requested
  870. if (!empty($attrib['valueof'])) {
  871. return rcube::Q($plugin['output'][$attrib['valueof']]['value'], ($attrib['valueof'] == 'subject' ? 'strict' : 'show'));
  872. }
  873. // compose html table
  874. $table = new html_table(array('cols' => 2));
  875. foreach ($plugin['output'] as $hkey => $row) {
  876. $val = $row['html'] ? $row['value'] : rcube::Q($row['value'], ($hkey == 'subject' ? 'strict' : 'show'));
  877. $table->add(array('class' => 'header-title'), rcube::Q($row['title']));
  878. $table->add(array('class' => 'header '.$hkey), $val);
  879. }
  880. return $table->show($attrib);
  881. }
  882. /**
  883. * Convert Priority header value into a localized string
  884. */
  885. function rcmail_localized_priority($value)
  886. {
  887. global $RCMAIL;
  888. $labels_map = array(
  889. '1' => 'highest',
  890. '2' => 'high',
  891. '3' => 'normal',
  892. '4' => 'low',
  893. '5' => 'lowest',
  894. );
  895. if ($value && $labels_map[$value]) {
  896. return $RCMAIL->gettext($labels_map[$value]);
  897. }
  898. return '';
  899. }
  900. /**
  901. * return block to show full message headers
  902. */
  903. function rcmail_message_full_headers($attrib, $headers=NULL)
  904. {
  905. global $OUTPUT, $RCMAIL;
  906. $html = html::div(array('id' => "all-headers", 'class' => "all", 'style' => 'display:none'), html::div(array('id' => 'headers-source'), ''));
  907. $html .= html::div(array(
  908. 'class' => "more-headers show-headers",
  909. 'onclick' => "return ".rcmail_output::JS_OBJECT_NAME.".command('show-headers','',this)",
  910. 'title' => $RCMAIL->gettext('togglefullheaders')
  911. ), '');
  912. $OUTPUT->add_gui_object('all_headers_row', 'all-headers');
  913. $OUTPUT->add_gui_object('all_headers_box', 'headers-source');
  914. return html::div($attrib, $html);
  915. }
  916. /**
  917. * Handler for the 'messagebody' GUI object
  918. *
  919. * @param array Named parameters
  920. * @return string HTML content showing the message body
  921. */
  922. function rcmail_message_body($attrib)
  923. {
  924. global $OUTPUT, $MESSAGE, $RCMAIL, $REMOTE_OBJECTS;
  925. if (!is_array($MESSAGE->parts) && empty($MESSAGE->body)) {
  926. return '';
  927. }
  928. if (!$attrib['id'])
  929. $attrib['id'] = 'rcmailMsgBody';
  930. $safe_mode = $MESSAGE->is_safe || intval($_GET['_safe']);
  931. $out = '';
  932. $header_attrib = array();
  933. foreach ($attrib as $attr => $value) {
  934. if (preg_match('/^headertable([a-z]+)$/i', $attr, $regs)) {
  935. $header_attrib[$regs[1]] = $value;
  936. }
  937. }
  938. if (!empty($MESSAGE->parts)) {
  939. foreach ($MESSAGE->parts as $part) {
  940. if ($part->type == 'headers') {
  941. $out .= html::div('message-partheaders', rcmail_message_headers(sizeof($header_attrib) ? $header_attrib : null, $part->headers));
  942. }
  943. else if ($part->type == 'content') {
  944. // unsupported (e.g. encrypted)
  945. if ($part->realtype) {
  946. if ($part->realtype == 'multipart/encrypted' || $part->realtype == 'application/pkcs7-mime') {
  947. $out .= html::span('part-notice', $RCMAIL->gettext('encryptedmessage'));
  948. }
  949. continue;
  950. }
  951. else if (!$part->size) {
  952. continue;
  953. }
  954. // Check if we have enough memory to handle the message in it
  955. // #1487424: we need up to 10x more memory than the body
  956. else if (!rcube_utils::mem_check($part->size * 10)) {
  957. $out .= html::span('part-notice', $RCMAIL->gettext('messagetoobig'). ' '
  958. . html::a('?_task=mail&_action=get&_download=1&_uid='.$MESSAGE->uid.'&_part='.$part->mime_id
  959. .'&_mbox='. urlencode($RCMAIL->storage->get_folder()), $RCMAIL->gettext('download')));
  960. continue;
  961. }
  962. if (empty($part->ctype_parameters) || empty($part->ctype_parameters['charset'])) {
  963. $part->ctype_parameters['charset'] = $MESSAGE->headers->charset;
  964. }
  965. // fetch part if not available
  966. if (!isset($part->body)) {
  967. $part->body = $MESSAGE->get_part_content($part->mime_id);
  968. }
  969. // extract headers from message/rfc822 parts
  970. if ($part->mimetype == 'message/rfc822') {
  971. $msgpart = rcube_mime::parse_message($part->body);
  972. if (!empty($msgpart->headers)) {
  973. $part = $msgpart;
  974. $out .= html::div('message-partheaders', rcmail_message_headers(sizeof($header_attrib) ? $header_attrib : null, $part->headers));
  975. }
  976. }
  977. // message is cached but not exists (#1485443), or other error
  978. if ($part->body === false) {
  979. rcmail_message_error($MESSAGE->uid);
  980. }
  981. $plugin = $RCMAIL->plugins->exec_hook('message_body_prefix',
  982. array('part' => $part, 'prefix' => ''));
  983. $body = rcmail_print_body($part, array('safe' => $safe_mode, 'plain' => !$RCMAIL->config->get('prefer_html')));
  984. if ($part->ctype_secondary == 'html') {
  985. $body = rcmail_html4inline($body, $attrib['id'], 'rcmBody', $attrs, $safe_mode);
  986. $div_attr = array('class' => 'message-htmlpart');
  987. $style = array();
  988. if (!empty($attrs)) {
  989. foreach ($attrs as $a_idx => $a_val)
  990. $style[] = $a_idx . ': ' . $a_val;
  991. if (!empty($style))
  992. $div_attr['style'] = implode('; ', $style);
  993. }
  994. $out .= html::div($div_attr, $plugin['prefix'] . $body);
  995. }
  996. else
  997. $out .= html::div('message-part', $plugin['prefix'] . $body);
  998. }
  999. }
  1000. }
  1001. else {
  1002. // Check if we have enough memory to handle the message in it
  1003. // #1487424: we need up to 10x more memory than the body
  1004. if (!rcube_utils::mem_check(strlen($MESSAGE->body) * 10)) {
  1005. $out .= html::span('part-notice', $RCMAIL->gettext('messagetoobig'). ' '
  1006. . html::a('?_task=mail&_action=get&_download=1&_uid='.$MESSAGE->uid.'&_part=0'
  1007. .'&_mbox='. urlencode($RCMAIL->storage->get_folder()), $RCMAIL->gettext('download')));
  1008. }
  1009. else {
  1010. $plugin = $RCMAIL->plugins->exec_hook('message_body_prefix',
  1011. array('part' => $MESSAGE, 'prefix' => ''));
  1012. $out .= html::div('message-part', $plugin['prefix'] . html::tag('pre', array(),
  1013. rcmail_plain_body(rcube::Q($MESSAGE->body, 'strict', false))));
  1014. }
  1015. }
  1016. // list images after mail body
  1017. if ($RCMAIL->config->get('inline_images', true) && !empty($MESSAGE->attachments)) {
  1018. $thumbnail_size = $RCMAIL->config->get('image_thumbnail_size', 240);
  1019. $client_mimetypes = (array)$RCMAIL->config->get('client_mimetypes');
  1020. foreach ($MESSAGE->attachments as $attach_prop) {
  1021. // skip inline images
  1022. if ($attach_prop->content_id && $attach_prop->disposition == 'inline') {
  1023. continue;
  1024. }
  1025. // Content-Type: image/*...
  1026. if ($mimetype = rcmail_part_image_type($attach_prop)) {
  1027. // display thumbnails
  1028. if ($thumbnail_size) {
  1029. $show_link = array(
  1030. 'href' => $MESSAGE->get_part_url($attach_prop->mime_id, false),
  1031. 'onclick' => sprintf(
  1032. 'return %s.command(\'load-attachment\',\'%s\',this)',
  1033. rcmail_output::JS_OBJECT_NAME,
  1034. $attach_prop->mime_id)
  1035. );
  1036. $out .= html::p('image-attachment',
  1037. html::a($show_link + array('class' => 'image-link', 'style' => sprintf('width:%dpx', $thumbnail_size)),
  1038. html::img(array(
  1039. 'class' => 'image-thumbnail',
  1040. 'src' => $MESSAGE->get_part_url($attach_prop->mime_id, 'image') . '&_thumb=1',
  1041. 'title' => $attach_prop->filename,
  1042. 'alt' => $attach_prop->filename,
  1043. 'style' => sprintf('max-width:%dpx; max-height:%dpx', $thumbnail_size, $thumbnail_size),
  1044. ))
  1045. ) .
  1046. html::span('image-filename', rcube::Q($attach_prop->filename)) .
  1047. html::span('image-filesize', rcube::Q($RCMAIL->message_part_size($attach_prop))) .
  1048. html::span('attachment-links',
  1049. (in_array($mimetype, $client_mimetypes) ? html::a($show_link, $RCMAIL->gettext('showattachment')) . '&nbsp;' : '') .
  1050. html::a($show_link['href'] . '&_download=1', $RCMAIL->gettext('download'))
  1051. ) .
  1052. html::br(array('style' => 'clear:both'))
  1053. );
  1054. }
  1055. else {
  1056. $out .= html::tag('fieldset', 'image-attachment',
  1057. html::tag('legend', 'image-filename', rcube::Q($attach_prop->filename)) .
  1058. html::p(array('align' => 'center'),
  1059. html::img(array(
  1060. 'src' => $MESSAGE->get_part_url($attach_prop->mime_id, 'image'),
  1061. 'title' => $attach_prop->filename,
  1062. 'alt' => $attach_prop->filename,
  1063. )))
  1064. );
  1065. }
  1066. }
  1067. }
  1068. }
  1069. // tell client that there are blocked remote objects
  1070. if ($REMOTE_OBJECTS && !$safe_mode) {
  1071. $OUTPUT->set_env('blockedobjects', true);
  1072. }
  1073. return html::div($attrib, $out);
  1074. }
  1075. function rcmail_part_image_type($part)
  1076. {
  1077. $rcmail = rcmail::get_instance();
  1078. // Skip TIFF images if browser doesn't support this format...
  1079. $tiff_support = !empty($_SESSION['browser_caps']) && !empty($_SESSION['browser_caps']['tif']);
  1080. // until we can convert them to JPEG
  1081. $tiff_support = $tiff_support || $rcmail->config->get('im_convert_path');
  1082. // Content-type regexp
  1083. $mime_regex = $tiff_support ? '/^image\//i' : '/^image\/(?!tif)/i';
  1084. // Content-Type: image/*...
  1085. if (preg_match($mime_regex, $part->mimetype)) {
  1086. return rcmail_fix_mimetype($part->mimetype);
  1087. }
  1088. // Many clients use application/octet-stream, we'll detect mimetype
  1089. // by checking filename extension
  1090. // Supported image filename extensions to image type map
  1091. $types = array(
  1092. 'jpg' => 'image/jpeg',
  1093. 'jpeg' => 'image/jpeg',
  1094. 'png' => 'image/png',
  1095. 'gif' => 'image/gif',
  1096. 'bmp' => 'image/bmp',
  1097. );
  1098. if ($tiff_support) {
  1099. $types['tif'] = 'image/tiff';
  1100. $types['tiff'] = 'image/tiff';
  1101. }
  1102. if ($part->filename
  1103. && preg_match('/^application\/octet-stream$/i', $part->mimetype)
  1104. && preg_match('/\.([^.]+)$/i', $part->filename, $m)
  1105. && ($extension = strtolower($m[1]))
  1106. && isset($types[$extension])
  1107. ) {
  1108. return $types[$extension];
  1109. }
  1110. }
  1111. /**
  1112. * modify a HTML message that it can be displayed inside a HTML page
  1113. */
  1114. function rcmail_html4inline($body, $container_id, $body_id='', &$attributes=null, $allow_remote=false)
  1115. {
  1116. $last_style_pos = 0;
  1117. $cont_id = $container_id.($body_id ? ' div.'.$body_id : '');
  1118. // find STYLE tags
  1119. while (($pos = stripos($body, '<style', $last_style_pos)) && ($pos2 = stripos($body, '</style>', $pos))) {
  1120. $pos = strpos($body, '>', $pos) + 1;
  1121. $len = $pos2 - $pos;
  1122. // replace all css definitions with #container [def]
  1123. $styles = substr($body, $pos, $len);
  1124. $styles = rcube_utils::mod_css_styles($styles, $cont_id, $allow_remote);
  1125. $body = substr_replace($body, $styles, $pos, $len);
  1126. $last_style_pos = $pos2 + strlen($styles) - $len;
  1127. }
  1128. // modify HTML links to open a new window if clicked
  1129. $GLOBALS['rcmail_html_container_id'] = $container_id;
  1130. $body = preg_replace_callback('/<(a|link|area)\s+([^>]+)>/Ui', 'rcmail_alter_html_link', $body);
  1131. unset($GLOBALS['rcmail_html_container_id']);
  1132. $body = preg_replace(array(
  1133. // add comments arround html and other tags
  1134. '/(<!DOCTYPE[^>]*>)/i',
  1135. '/(<\?xml[^>]*>)/i',
  1136. '/(<\/?html[^>]*>)/i',
  1137. '/(<\/?head[^>]*>)/i',
  1138. '/(<title[^>]*>.*<\/title>)/Ui',
  1139. '/(<\/?meta[^>]*>)/i',
  1140. // quote <? of php and xml files that are specified as text/html
  1141. '/<\?/',
  1142. '/\?>/',
  1143. // replace <body> with <div>
  1144. '/<body([^>]*)>/i',
  1145. '/<\/body>/i',
  1146. ),
  1147. array(
  1148. '<!--\\1-->',
  1149. '<!--\\1-->',
  1150. '<!--\\1-->',
  1151. '<!--\\1-->',
  1152. '<!--\\1-->',
  1153. '<!--\\1-->',
  1154. '&lt;?',
  1155. '?&gt;',
  1156. '<div class="'.$body_id.'"\\1>',
  1157. '</div>',
  1158. ),
  1159. $body);
  1160. $attributes = array();
  1161. // Handle body attributes that doesn't play nicely with div elements
  1162. $regexp = '/<div class="' . preg_quote($body_id, '/') . '"([^>]*)/';
  1163. if (preg_match($regexp, $body, $m)) {
  1164. $attrs = $m[0];
  1165. // Get bgcolor, we'll set it as background-color of the message container
  1166. if ($m[1] && preg_match('/bgcolor=["\']*([a-z0-9#]+)["\']*/i', $attrs, $mb)) {
  1167. $attributes['background-color'] = $mb[1];
  1168. $attrs = preg_replace('/bgcolor=["\']*[a-z0-9#]+["\']*/i', '', $attrs);
  1169. }
  1170. // Get background, we'll set it as background-image of the message container
  1171. if ($m[1] && preg_match('/background=["\']*([^"\'>\s]+)["\']*/', $attrs, $mb)) {
  1172. $attributes['background-image'] = 'url('.$mb[1].')';
  1173. $attrs = preg_replace('/background=["\']*([^"\'>\s]+)["\']*/', '', $attrs);
  1174. }
  1175. if (!empty($attributes)) {
  1176. $body = preg_replace($regexp, rtrim($attrs), $body, 1);
  1177. }
  1178. // handle body styles related to background image
  1179. if ($attributes['background-image']) {
  1180. // get body style
  1181. if (preg_match('/#'.preg_quote($cont_id, '/').'\s+\{([^}]+)}/i', $body, $m)) {
  1182. // get background related style
  1183. $regexp = '/(background-position|background-repeat)\s*:\s*([^;]+);/i';
  1184. if (preg_match_all($regexp, $m[1], $ma, PREG_SET_ORDER)) {
  1185. foreach ($ma as $style) {
  1186. $attributes[$style[1]] = $style[2];
  1187. }
  1188. }
  1189. }
  1190. }
  1191. }
  1192. // make sure there's 'rcmBody' div, we need it for proper css modification
  1193. // its name is hardcoded in rcmail_message_body() also
  1194. else {
  1195. $body = '<div class="' . $body_id . '">' . $body . '</div>';
  1196. }
  1197. return $body;
  1198. }
  1199. /**
  1200. * parse link (a, link, area) attributes and set correct target
  1201. */
  1202. function rcmail_alter_html_link($matches)
  1203. {
  1204. global $RCMAIL;
  1205. $tag = strtolower($matches[1]);
  1206. $attrib = html::parse_attrib_string($matches[2]);
  1207. $end = '>';
  1208. // Remove non-printable characters in URL (#1487805)
  1209. if ($attrib['href'])
  1210. $attrib['href'] = preg_replace('/[\x00-\x1F]/', '', $attrib['href']);
  1211. if ($tag == 'link' && preg_match('/^https?:\/\//i', $attrib['href'])) {
  1212. $tempurl = 'tmp-' . md5($attrib['href']) . '.css';
  1213. $_SESSION['modcssurls'][$tempurl] = $attrib['href'];
  1214. $attrib['href'] = $RCMAIL->url(array('task' => 'utils', 'action' => 'modcss', 'u' => $tempurl, 'c' => $GLOBALS['rcmail_html_container_id']));
  1215. $end = ' />';
  1216. }
  1217. else if (preg_match('/^mailto:(.+)/i', $attrib['href'], $mailto)) {
  1218. list($mailto, $url) = explode('?', html_entity_decode($mailto[1], ENT_QUOTES, 'UTF-8'), 2);
  1219. $url = urldecode($url);
  1220. $mailto = urldecode($mailto);
  1221. $addresses = rcube_mime::decode_address_list($mailto, null, true);
  1222. $mailto = array();
  1223. // do sanity checks on recipients
  1224. foreach ($addresses as $idx => $addr) {
  1225. if (rcube_utils::check_email($addr['mailto'], false)) {
  1226. $addresses[$idx] = $addr['mailto'];
  1227. $mailto[] = $addr['string'];
  1228. }
  1229. else {
  1230. unset($addresses[$idx]);
  1231. }
  1232. }
  1233. if (!empty($addresses)) {
  1234. $attrib['href'] = 'mailto:' . implode(',', $addresses);
  1235. $attrib['onclick'] = sprintf(
  1236. "return %s.command('compose','%s',this)",
  1237. rcmail_output::JS_OBJECT_NAME,
  1238. rcube::JQ(implode(',', $mailto) . ($url ? "?$url" : '')));
  1239. }
  1240. else {
  1241. $attrib['href'] = '#NOP';
  1242. $attrib['onclick'] = '';
  1243. }
  1244. }
  1245. else if (empty($attrib['href']) && !$attrib['name']) {
  1246. $attrib['href'] = './#NOP';
  1247. $attrib['onclick'] = 'return false';
  1248. }
  1249. else if (!empty($attrib['href']) && $attrib['href'][0] != '#') {
  1250. $attrib['target'] = '_blank';
  1251. }
  1252. // Better security by adding rel="noreferrer" (#1484686)
  1253. if (($tag == 'a' || $tag == 'area') && $attrib['href'] && $attrib['href'][0] != '#') {
  1254. $attrib['rel'] = 'noreferrer';
  1255. }
  1256. // allowed attributes for a|link|area tags
  1257. $allow = array('href','name','target','onclick','id','class','style','title',
  1258. 'rel','type','media','alt','coords','nohref','hreflang','shape');
  1259. return "<$tag" . html::attrib_string($attrib, $allow) . $end;
  1260. }
  1261. /**
  1262. * decode address string and re-format it as HTML links
  1263. */
  1264. function rcmail_address_string($input, $max=null, $linked=false, $addicon=null, $default_charset=null, $title=null)
  1265. {
  1266. global $RCMAIL, $PRINT_MODE;
  1267. $a_parts = rcube_mime::decode_address_list($input, null, true, $default_charset);
  1268. if (!sizeof($a_parts)) {
  1269. return $input;
  1270. }
  1271. $c = count($a_parts);
  1272. $j = 0;
  1273. $out = '';
  1274. $allvalues = array();
  1275. $show_email = $RCMAIL->config->get('message_show_email');
  1276. if ($addicon && !isset($_SESSION['writeable_abook'])) {
  1277. $_SESSION['writeable_abook'] = $RCMAIL->get_address_sources(true) ? true : false;
  1278. }
  1279. foreach ($a_parts as $part) {
  1280. $j++;
  1281. $name = $part['name'];
  1282. $mailto = $part['mailto'];
  1283. $string = $part['string'];
  1284. $valid = rcube_utils::check_email($mailto, false);
  1285. // phishing email prevention (#1488981), e.g. "valid@email.addr <phishing@email.addr>"
  1286. if (!$show_email && $valid && $name && $name != $mailto && strpos($name, '@')) {
  1287. $name = '';
  1288. }
  1289. // IDNA ASCII to Unicode
  1290. if ($name == $mailto)
  1291. $name = rcube_utils::idn_to_utf8($name);
  1292. if ($string == $mailto)
  1293. $string = rcube_utils::idn_to_utf8($string);
  1294. $mailto = rcube_utils::idn_to_utf8($mailto);
  1295. if ($PRINT_MODE) {
  1296. $address = sprintf('%s &lt;%s&gt;', rcube::Q($name), rcube::Q($mailto));
  1297. }
  1298. else if ($valid) {
  1299. if ($linked) {
  1300. $attrs = array(
  1301. 'href' => 'mailto:' . $mailto,
  1302. 'class' => 'rcmContactAddress',
  1303. 'onclick' => sprintf("return %s.command('compose','%s',this)",
  1304. rcmail_output::JS_OBJECT_NAME, rcube::JQ(format_email_recipient($mailto, $name))),
  1305. );
  1306. if ($show_email && $name && $mailto) {
  1307. $content = rcube::Q($name ? sprintf('%s <%s>', $name, $mailto) : $mailto);
  1308. }
  1309. else {
  1310. $content = rcube::Q($name ? $name : $mailto);
  1311. $attrs['title'] = $mailto;
  1312. }
  1313. $address = html::a($attrs, $content);
  1314. }
  1315. else {
  1316. $address = html::span(array('title' => $mailto, 'class' => "rcmContactAddress"),
  1317. rcube::Q($name ? $name : $mailto));
  1318. }
  1319. if ($addicon && $_SESSION['writeable_abook']) {
  1320. $address .= html::a(array(
  1321. 'href' => "#add",
  1322. 'title' => $RCMAIL->gettext('addtoaddressbook'),
  1323. 'class' => 'rcmaddcontact',
  1324. 'onclick' => sprintf("return %s.command('add-contact','%s',this)",
  1325. rcmail_output::JS_OBJECT_NAME, rcube::JQ($string)),
  1326. ),
  1327. html::img(array(
  1328. 'src' => $RCMAIL->config->get('skin_path') . $addicon,
  1329. 'alt' => "Add contact",
  1330. )));
  1331. }
  1332. }
  1333. else {
  1334. $address = '';
  1335. if ($name)
  1336. $address .= rcube::Q($name);
  1337. if ($mailto)
  1338. $address = trim($address . ' ' . rcube::Q($name ? sprintf('<%s>', $mailto) : $mailto));
  1339. }
  1340. $address = html::span('adr', $address);
  1341. $allvalues[] = $address;
  1342. if (!$moreadrs)
  1343. $out .= ($out ? ', ' : '') . $address;
  1344. if ($max && $j == $max && $c > $j) {
  1345. if ($linked) {
  1346. $moreadrs = $c - $j;
  1347. }
  1348. else {
  1349. $out .= '...';
  1350. break;
  1351. }
  1352. }
  1353. }
  1354. if ($moreadrs) {
  1355. if ($PRINT_MODE) {
  1356. $out .= ' ' . html::a(array(
  1357. 'href' => '#more',
  1358. 'class' => 'morelink',
  1359. 'onclick' => '$(this).hide().next().show()',
  1360. ),
  1361. rcube::Q($RCMAIL->gettext(array('name' => 'andnmore', 'vars' => array('nr' => $moreadrs)))))
  1362. . html::span(array('style' => 'display:none'), join(', ', $allvalues));
  1363. }
  1364. else {
  1365. $out .= ' ' . html::a(array(
  1366. 'href' => '#more',
  1367. 'class' => 'morelink',
  1368. 'onclick' => sprintf("return %s.show_popup_dialog('%s','%s')",
  1369. rcmail_output::JS_OBJECT_NAME,
  1370. rcube::JQ(join(', ', $allvalues)),
  1371. rcube::JQ($title))
  1372. ),
  1373. rcube::Q($RCMAIL->gettext(array('name' => 'andnmore', 'vars' => array('nr' => $moreadrs)))));
  1374. }
  1375. }
  1376. return $out;
  1377. }
  1378. /**
  1379. * Wrap text to a given number of characters per line
  1380. * but respect the mail quotation of replies messages (>).
  1381. * Finally add another quotation level by prepending the lines
  1382. * with >
  1383. *
  1384. * @param string Text to wrap
  1385. * @param int The line width
  1386. * @return string The wrapped text
  1387. */
  1388. function rcmail_wrap_and_quote($text, $length = 72)
  1389. {
  1390. // Rebuild the message body with a maximum of $max chars, while keeping quoted message.
  1391. $max = max(75, $length + 8);
  1392. $lines = preg_split('/\r?\n/', trim($text));
  1393. $out = '';
  1394. foreach ($lines as $line) {
  1395. // don't wrap already quoted lines
  1396. if ($line[0] == '>') {
  1397. $line = '>' . rtrim($line);
  1398. }
  1399. else if (mb_strlen($line) > $max) {
  1400. $newline = '';
  1401. foreach (explode("\n", rcube_mime::wordwrap($line, $length - 2)) as $l) {
  1402. if (strlen($l))
  1403. $newline .= '> ' . $l . "\n";
  1404. else
  1405. $newline .= ">\n";
  1406. }
  1407. $line = rtrim($newline);
  1408. }
  1409. else {
  1410. $line = '> ' . $line;
  1411. }
  1412. // Append the line
  1413. $out .= $line . "\n";
  1414. }
  1415. return rtrim($out, "\n");
  1416. }
  1417. function rcmail_draftinfo_encode($p)
  1418. {
  1419. $parts = array();
  1420. foreach ($p as $key => $val) {
  1421. $parts[] = $key . '=' . ($key == 'folder' ? base64_encode($val) : $val);
  1422. }
  1423. return join('; ', $parts);
  1424. }
  1425. function rcmail_draftinfo_decode($str)
  1426. {
  1427. $info = array();
  1428. foreach (preg_split('/;\s+/', $str) as $part) {
  1429. list($key, $val) = explode('=', $part, 2);
  1430. if ($key == 'folder') {
  1431. $val = base64_decode($val);
  1432. }
  1433. $info[$key] = $val;
  1434. }
  1435. return $info;
  1436. }
  1437. /**
  1438. * clear message composing settings
  1439. */
  1440. function rcmail_compose_cleanup($id)
  1441. {
  1442. if (!isset($_SESSION['compose_data_'.$id])) {
  1443. return;
  1444. }
  1445. $rcmail = rcmail::get_instance();
  1446. $rcmail->plugins->exec_hook('attachments_cleanup', array('group' => $id));
  1447. $rcmail->session->remove('compose_data_'.$id);
  1448. }
  1449. /**
  1450. * Send the MDN response
  1451. *
  1452. * @param mixed $message Original message object (rcube_message) or UID
  1453. * @param array $smtp_error SMTP error array (reference)
  1454. *
  1455. * @return boolean Send status
  1456. */
  1457. function rcmail_send_mdn($message, &$smtp_error)
  1458. {
  1459. global $RCMAIL;
  1460. if (!is_object($message) || !is_a($message, 'rcube_message')) {
  1461. $message = new rcube_message($message);
  1462. }
  1463. if ($message->headers->mdn_to && empty($message->headers->flags['MDNSENT']) &&
  1464. ($RCMAIL->storage->check_permflag('MDNSENT') || $RCMAIL->storage->check_permflag('*'))
  1465. ) {
  1466. $identity = rcmail_identity_select($message);
  1467. $sender = format_email_recipient($identity['email'], $identity['name']);
  1468. $recipient = array_shift(rcube_mime::decode_address_list(
  1469. $message->headers->mdn_to, 1, true, $message->headers->charset));
  1470. $mailto = $recipient['mailto'];
  1471. $compose = new Mail_mime("\r\n");
  1472. $compose->setParam('text_encoding', 'quoted-printable');
  1473. $compose->setParam('html_encoding', 'quoted-printable');
  1474. $compose->setParam('head_encoding', 'quoted-printable');
  1475. $compose->setParam('head_charset', RCUBE_CHARSET);
  1476. $compose->setParam('html_charset', RCUBE_CHARSET);
  1477. $compose->setParam('text_charset', RCUBE_CHARSET);
  1478. // compose headers array
  1479. $headers = array(
  1480. 'Date' => $RCMAIL->user_date(),
  1481. 'From' => $sender,
  1482. 'To' => $message->headers->mdn_to,
  1483. 'Subject' => $RCMAIL->gettext('receiptread') . ': ' . $message->subject,
  1484. 'Message-ID' => $RCMAIL->gen_message_id(),
  1485. 'X-Sender' => $identity['email'],
  1486. 'References' => trim($message->headers->references . ' ' . $message->headers->messageID),
  1487. );
  1488. $report = "Final-Recipient: rfc822; {$identity['email']}\r\n"
  1489. . "Original-Message-ID: {$message->headers->messageID}\r\n"
  1490. . "Disposition: manual-action/MDN-sent-manually; displayed\r\n";
  1491. if ($message->headers->to) {
  1492. $report .= "Original-Recipient: {$message->headers->to}\r\n";
  1493. }
  1494. if ($agent = $RCMAIL->config->get('useragent')) {
  1495. $headers['User-Agent'] = $agent;
  1496. $report .= "Reporting-UA: $agent\r\n";
  1497. }
  1498. $body = $RCMAIL->gettext("yourmessage") . "\r\n\r\n" .
  1499. "\t" . $RCMAIL->gettext("to") . ': ' . rcube_mime::decode_mime_string($message->headers->to, $message->headers->charset) . "\r\n" .
  1500. "\t" . $RCMAIL->gettext("subject") . ': ' . $message->subject . "\r\n" .
  1501. "\t" . $RCMAIL->gettext("sent") . ': ' . $RCMAIL->format_date($message->headers->date, $RCMAIL->config->get('date_long')) . "\r\n" .
  1502. "\r\n" . $RCMAIL->gettext("receiptnote");
  1503. $compose->headers($headers);
  1504. $compose->setContentType('multipart/report', array('report-type'=> 'disposition-notification'));
  1505. $compose->setTXTBody(rcube_mime::wordwrap($body, 75, "\r\n"));
  1506. $compose->addAttachment($report, 'message/disposition-notification', 'MDNPart2.txt', false, '7bit', 'inline');
  1507. if ($RCMAIL->config->get('mdn_use_from')) {
  1508. $options['mdn_use_from'] = true;
  1509. }
  1510. $sent = $RCMAIL->deliver_message($compose, $identity['email'], $mailto, $smtp_error, $body_file, $options);
  1511. if ($sent) {
  1512. $RCMAIL->storage->set_flag($message->uid, 'MDNSENT');
  1513. return true;
  1514. }
  1515. }
  1516. return false;
  1517. }
  1518. /**
  1519. * Detect recipient identity from specified message
  1520. */
  1521. function rcmail_identity_select($MESSAGE, $identities = null, $compose_mode = 'reply')
  1522. {
  1523. $a_recipients = array();
  1524. $a_names = array();
  1525. if ($identities === null) {
  1526. $identities = rcmail::get_instance()->user->list_identities(null, true);
  1527. }
  1528. // extract all recipients of the reply-message
  1529. if (is_object($MESSAGE->headers) && in_array($compose_mode, array('reply', 'forward'))) {
  1530. $a_to = rcube_mime::decode_address_list($MESSAGE->headers->to, null, true, $MESSAGE->headers->charset);
  1531. foreach ($a_to as $addr) {
  1532. if (!empty($addr['mailto'])) {
  1533. $a_recipients[] = strtolower($addr['mailto']);
  1534. $a_names[] = $addr['name'];
  1535. }
  1536. }
  1537. if (!empty($MESSAGE->headers->cc)) {
  1538. $a_cc = rcube_mime::decode_address_list($MESSAGE->headers->cc, null, true, $MESSAGE->headers->charset);
  1539. foreach ($a_cc as $addr) {
  1540. if (!empty($addr['mailto'])) {
  1541. $a_recipients[] = strtolower($addr['mailto']);
  1542. $a_names[] = $addr['name'];
  1543. }
  1544. }
  1545. }
  1546. }
  1547. // decode From: address
  1548. $from = rcube_mime::decode_address_list($MESSAGE->headers->from, null, true, $MESSAGE->headers->charset);
  1549. $from = array_shift($from);
  1550. $from['mailto'] = strtolower($from['mailto']);
  1551. $from_idx = null;
  1552. $found_idx = array('to' => null, 'from' => null);
  1553. $check_from = in_array($compose_mode, array('draft', 'edit', 'reply'));
  1554. // Select identity
  1555. foreach ($identities as $idx => $ident) {
  1556. // use From: header when in edit/draft or reply-to-self
  1557. if ($check_from && $from['mailto'] == strtolower($ident['email_ascii'])) {
  1558. // remember first matching identity address
  1559. if ($found_idx['from'] === null) {
  1560. $found_idx['from'] = $idx;
  1561. }
  1562. // match identity name
  1563. if ($from['name'] && $ident['name'] && $from['name'] == $ident['name']) {
  1564. $from_idx = $idx;
  1565. break;
  1566. }
  1567. }
  1568. // use replied/forwarded message recipients
  1569. else if (($found = array_search(strtolower($ident['email_ascii']), $a_recipients)) !== false) {
  1570. // remember first matching identity address
  1571. if ($found_idx['to'] === null) {
  1572. $found_idx['to'] = $idx;
  1573. }
  1574. // match identity name
  1575. if ($a_names[$found] && $ident['name'] && $a_names[$found] == $ident['name']) {
  1576. $from_idx = $idx;
  1577. break;
  1578. }
  1579. }
  1580. }
  1581. // If matching by name+address didn't find any matches,
  1582. // get first found identity (address) if any
  1583. if ($from_idx === null) {
  1584. $from_idx = $found_idx['from'] !== null ? $found_idx['from'] : $found_idx['to'];
  1585. }
  1586. // Try Return-Path
  1587. if ($from_idx === null && ($return_path = $MESSAGE->headers->others['return-path'])) {
  1588. $return_path = array_map('strtolower', (array) $return_path);
  1589. foreach ($identities as $idx => $ident) {
  1590. // Return-Path header contains an email address, but on some mailing list
  1591. // it can be e.g. <pear-dev-return-55250-local=domain.tld@lists.php.net>
  1592. // where local@domain.tld is the address we're looking for (#1489241)
  1593. $ident1 = strtolower($ident['email_ascii']);
  1594. $ident2 = str_replace('@', '=', $ident1);
  1595. $ident1 = '<' . $ident1 . '>';
  1596. $ident2 = '-' . $ident2 . '@';
  1597. foreach ($return_path as $path) {
  1598. if ($path == $ident1 || stripos($path, $ident2)) {
  1599. $from_idx = $idx;
  1600. break 2;
  1601. }
  1602. }
  1603. }
  1604. }
  1605. // See identity_select plugin for example usage of this hook
  1606. $plugin = rcmail::get_instance()->plugins->exec_hook('identity_select',
  1607. array('message' => $MESSAGE, 'identities' => $identities, 'selected' => $from_idx));
  1608. $selected = $plugin['selected'];
  1609. // default identity is always first on the list
  1610. return $identities[$selected !== null ? $selected : 0];
  1611. }
  1612. // Fixes some content-type names
  1613. function rcmail_fix_mimetype($name)
  1614. {
  1615. // Some versions of Outlook create garbage Content-Type:
  1616. // application/pdf.A520491B_3BF7_494D_8855_7FAC2C6C0608
  1617. if (preg_match('/^application\/pdf.+/', $name)) {
  1618. $name = 'application/pdf';
  1619. }
  1620. // treat image/pjpeg (image/pjpg, image/jpg) as image/jpeg (#1489097)
  1621. else if (preg_match('/^image\/p?jpe?g$/', $name)) {
  1622. $name = 'image/jpeg';
  1623. }
  1624. return $name;
  1625. }
  1626. // return attachment filename, handle empty filename case
  1627. function rcmail_attachment_name($attachment, $display = false)
  1628. {
  1629. global $RCMAIL;
  1630. $filename = $attachment->filename;
  1631. if ($filename === null || $filename === '') {
  1632. if ($attachment->mimetype == 'text/html') {
  1633. $filename = $RCMAIL->gettext('htmlmessage');
  1634. }
  1635. else {
  1636. $ext = (array) rcube_mime::get_mime_extensions($attachment->mimetype);
  1637. $ext = array_shift($ext);
  1638. $filename = $RCMAIL->gettext('messagepart') . ' ' . $attachment->mime_id;
  1639. if ($ext) {
  1640. $filename .= '.' . $ext;
  1641. }
  1642. }
  1643. }
  1644. $filename = preg_replace('[\r\n]', '', $filename);
  1645. // Display smart names for some known mimetypes
  1646. if ($display) {
  1647. if (preg_match('/application\/(pgp|pkcs7)-signature/i', $attachment->mimetype)) {
  1648. $filename = $RCMAIL->gettext('digitalsig');
  1649. }
  1650. }
  1651. return $filename;
  1652. }
  1653. function rcmail_search_filter($attrib)
  1654. {
  1655. global $RCMAIL;
  1656. if (!strlen($attrib['id']))
  1657. $attrib['id'] = 'rcmlistfilter';
  1658. $attrib['onchange'] = rcmail_output::JS_OBJECT_NAME.'.filter_mailbox(this.value)';
  1659. // Content-Type values of messages with attachments
  1660. // the same as in app.js:add_message_row()
  1661. $ctypes = array('application/', 'multipart/m', 'multipart/signed', 'multipart/report');
  1662. // Build search string of "with attachment" filter
  1663. $attachment = str_repeat(' OR', count($ctypes)-1);
  1664. foreach ($ctypes as $type) {
  1665. $attachment .= ' HEADER Content-Type ' . rcube_imap_generic::escape($type);
  1666. }
  1667. $select_filter = new html_select($attrib);
  1668. $select_filter->add($RCMAIL->gettext('all'), 'ALL');
  1669. $select_filter->add($RCMAIL->gettext('unread'), 'UNSEEN');
  1670. $select_filter->add($RCMAIL->gettext('flagged'), 'FLAGGED');
  1671. $select_filter->add($RCMAIL->gettext('unanswered'), 'UNANSWERED');
  1672. if (!$RCMAIL->config->get('skip_deleted')) {
  1673. $select_filter->add($RCMAIL->gettext('deleted'), 'DELETED');
  1674. $select_filter->add($RCMAIL->gettext('undeleted'), 'UNDELETED');
  1675. }
  1676. $select_filter->add($RCMAIL->gettext('withattachment'), $attachment);
  1677. $select_filter->add($RCMAIL->gettext('priority').': '.$RCMAIL->gettext('highest'), 'HEADER X-PRIORITY 1');
  1678. $select_filter->add($RCMAIL->gettext('priority').': '.$RCMAIL->gettext('high'), 'HEADER X-PRIORITY 2');
  1679. $select_filter->add($RCMAIL->gettext('priority').': '.$RCMAIL->gettext('normal'), 'NOT HEADER X-PRIORITY 1 NOT HEADER X-PRIORITY 2 NOT HEADER X-PRIORITY 4 NOT HEADER X-PRIORITY 5');
  1680. $select_filter->add($RCMAIL->gettext('priority').': '.$RCMAIL->gettext('low'), 'HEADER X-PRIORITY 4');
  1681. $select_filter->add($RCMAIL->gettext('priority').': '.$RCMAIL->gettext('lowest'), 'HEADER X-PRIORITY 5');
  1682. $out = $select_filter->show($_SESSION['search_filter']);
  1683. $RCMAIL->output->add_gui_object('search_filter', $attrib['id']);
  1684. return $out;
  1685. }
  1686. function rcmail_message_error($uid=null)
  1687. {
  1688. global $RCMAIL;
  1689. // Set env variables for messageerror.html template
  1690. if ($RCMAIL->action == 'show') {
  1691. $mbox_name = $RCMAIL->storage->get_folder();
  1692. $RCMAIL->output->set_env('mailbox', $mbox_name);
  1693. $RCMAIL->output->set_env('uid', null);
  1694. }
  1695. // display error message
  1696. $RCMAIL->output->show_message('messageopenerror', 'error');
  1697. // ... display message error page
  1698. $RCMAIL->output->send('messageerror');
  1699. }
  1700. function rcmail_message_import_form($attrib = array())
  1701. {
  1702. global $RCMAIL;
  1703. // set defaults
  1704. $attrib += array('id' => 'rcmImportform', 'buttons' => 'yes');
  1705. // Get filesize, enable upload progress bar
  1706. $max_filesize = $RCMAIL->upload_init();
  1707. $button = new html_inputfield(array('type' => 'button'));
  1708. $fileinput = new html_inputfield(array(
  1709. 'type' => 'file',
  1710. 'name' => '_file[]',
  1711. 'multiple' => 'multiple',
  1712. 'accept' => ".eml, .mbox, message/rfc822, text/*",
  1713. ));
  1714. $content = html::tag('input', array('type' => 'hidden', 'name' => '_unlock', 'value' => ''))
  1715. . html::div(null, $fileinput->show())
  1716. . html::div('hint', $RCMAIL->gettext(array('name' => 'maxuploadsize', 'vars' => array('size' => $max_filesize))));
  1717. if (rcube_utils::get_boolean($attrib['buttons'])) {
  1718. $content .= html::div('buttons',
  1719. $button->show($RCMAIL->gettext('close'), array('class' => 'button', 'onclick' => "$('#$attrib[id]').hide()"))
  1720. . ' ' .
  1721. $button->show($RCMAIL->gettext('upload'), array(
  1722. 'class' => 'button mainaction',
  1723. 'onclick' => rcmail_output::JS_OBJECT_NAME . ".command('import-messages', this.form)"
  1724. )));
  1725. }
  1726. $out = $RCMAIL->output->form_tag(array(
  1727. 'id' => $attrib['id'].'Frm',
  1728. 'method' => 'post',
  1729. 'enctype' => 'multipart/form-data'
  1730. ),
  1731. $content);
  1732. $RCMAIL->output->add_gui_object('importform', $attrib['id'].'Frm');
  1733. $RCMAIL->output->add_label('selectimportfile','importwait');
  1734. return html::div($attrib, $out);
  1735. }
  1736. /**
  1737. * Add groups from the given address source to the address book widget
  1738. */
  1739. function rcmail_compose_contact_groups($abook, $source_id, $search = null, $search_mode = 0)
  1740. {
  1741. global $RCMAIL, $OUTPUT;
  1742. $jsresult = array();
  1743. foreach ($abook->list_groups($search, $search_mode) as $group) {
  1744. $abook->reset();
  1745. $abook->set_group($group['ID']);
  1746. $group_prop = $abook->get_group($group['ID']);
  1747. // group (distribution list) with email address(es)
  1748. if ($group_prop['email']) {
  1749. foreach ((array)$group_prop['email'] as $email) {
  1750. $row_id = 'G'.$group['ID'];
  1751. $jsresult[$row_id] = format_email_recipient($email, $group['name']);
  1752. $OUTPUT->command('add_contact_row', $row_id, array(
  1753. 'contactgroup' => html::span(array('title' => $email), rcube::Q($group['name']))), 'group');
  1754. }
  1755. }
  1756. // make virtual groups clickable to list their members
  1757. else if ($group_prop['virtual']) {
  1758. $row_id = 'G'.$group['ID'];
  1759. $OUTPUT->command('add_contact_row', $row_id, array(
  1760. 'contactgroup' => html::a(array(
  1761. 'href' => '#list',
  1762. 'rel' => $group['ID'],
  1763. 'title' => $RCMAIL->gettext('listgroup'),
  1764. 'onclick' => sprintf("return %s.command('pushgroup',{'source':'%s','id':'%s'},this,event)",
  1765. rcmail_output::JS_OBJECT_NAME, $source_id, $group['ID']),
  1766. ), rcube::Q($group['name']) . '&nbsp;' . html::span('action', '&raquo;'))),
  1767. 'group',
  1768. array('ID' => $group['ID'], 'name' => $group['name'], 'virtual' => true));
  1769. }
  1770. // show group with count
  1771. else if (($result = $abook->count()) && $result->count) {
  1772. $row_id = 'E'.$group['ID'];
  1773. $jsresult[$row_id] = $group['name'];
  1774. $OUTPUT->command('add_contact_row', $row_id, array(
  1775. 'contactgroup' => rcube::Q($group['name'] . ' (' . intval($result->count) . ')')), 'group');
  1776. }
  1777. }
  1778. $abook->reset();
  1779. $abook->set_group(0);
  1780. return $jsresult;
  1781. }