PageRenderTime 68ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/program/steps/mail/func.inc

https://github.com/fretelweb/roundcubemail
PHP | 1953 lines | 1344 code | 326 blank | 283 comment | 402 complexity | e25ac7bf50baf324c35a44e6ce9bfef2 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.1

Large files files are truncated, but you can click here to view the full file

  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-2012, 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. +-----------------------------------------------------------------------+
  19. */
  20. // setup some global vars used by mail steps
  21. $SENT_MBOX = $RCMAIL->config->get('sent_mbox');
  22. $DRAFTS_MBOX = $RCMAIL->config->get('drafts_mbox');
  23. $SEARCH_MODS_DEFAULT = array(
  24. '*' => array('subject'=>1, 'from'=>1),
  25. $SENT_MBOX => array('subject'=>1, 'to'=>1),
  26. $DRAFTS_MBOX => array('subject'=>1, 'to'=>1)
  27. );
  28. // always instantiate storage object (but not connect to server yet)
  29. $RCMAIL->storage_init();
  30. // set imap properties and session vars
  31. if (strlen(trim($mbox = get_input_value('_mbox', RCUBE_INPUT_GPC, true))))
  32. $RCMAIL->storage->set_folder(($_SESSION['mbox'] = $mbox));
  33. else if ($RCMAIL->storage)
  34. $_SESSION['mbox'] = $RCMAIL->storage->get_folder();
  35. if (!empty($_GET['_page']))
  36. $RCMAIL->storage->set_page(($_SESSION['page'] = intval($_GET['_page'])));
  37. // set default sort col/order to session
  38. if (!isset($_SESSION['sort_col']))
  39. $_SESSION['sort_col'] = !empty($CONFIG['message_sort_col']) ? $CONFIG['message_sort_col'] : '';
  40. if (!isset($_SESSION['sort_order']))
  41. $_SESSION['sort_order'] = strtoupper($CONFIG['message_sort_order']) == 'ASC' ? 'ASC' : 'DESC';
  42. // set threads mode
  43. $a_threading = $RCMAIL->config->get('message_threading', array());
  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. $search_request = md5($mbox_name.$_SESSION['search_filter']);
  69. $RCMAIL->storage->search($mbox_name, $_SESSION['search_filter'], RCMAIL_CHARSET, rcmail_sort_column());
  70. $_SESSION['search'] = $RCMAIL->storage->get_search_set();
  71. $_SESSION['search_request'] = $search_request;
  72. $OUTPUT->set_env('search_request', $search_request);
  73. }
  74. $search_mods = $RCMAIL->config->get('search_mods', $SEARCH_MODS_DEFAULT);
  75. $OUTPUT->set_env('search_mods', $search_mods);
  76. }
  77. $threading = (bool) $RCMAIL->storage->get_threading();
  78. $delimiter = $RCMAIL->storage->get_hierarchy_delimiter();
  79. // set current mailbox and some other vars in client environment
  80. $OUTPUT->set_env('mailbox', $mbox_name);
  81. $OUTPUT->set_env('pagesize', $RCMAIL->storage->get_pagesize());
  82. $OUTPUT->set_env('delimiter', $delimiter);
  83. $OUTPUT->set_env('threading', $threading);
  84. $OUTPUT->set_env('threads', $threading || $RCMAIL->storage->get_capability('THREAD'));
  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. foreach (array('delete_junk','flag_for_deletion','read_when_deleted','skip_deleted','display_next','message_extwin','compose_extwin','forward_attachment') as $prop) {
  90. if ($CONFIG[$prop])
  91. $OUTPUT->set_env($prop, true);
  92. }
  93. if ($CONFIG['trash_mbox'])
  94. $OUTPUT->set_env('trash_mailbox', $CONFIG['trash_mbox']);
  95. if ($CONFIG['drafts_mbox'])
  96. $OUTPUT->set_env('drafts_mailbox', $CONFIG['drafts_mbox']);
  97. if ($CONFIG['junk_mbox'])
  98. $OUTPUT->set_env('junk_mailbox', $CONFIG['junk_mbox']);
  99. if (!empty($_SESSION['browser_caps']))
  100. $OUTPUT->set_env('browser_capabilities', $_SESSION['browser_caps']);
  101. if (!$OUTPUT->ajax_call)
  102. $OUTPUT->add_label('checkingmail', 'deletemessage', 'movemessagetotrash',
  103. 'movingmessage', 'copyingmessage', 'deletingmessage', 'markingmessage',
  104. 'copy', 'move', 'quota', 'replyall', 'replylist', 'importwait');
  105. $pagetitle = $RCMAIL->localize_foldername($RCMAIL->storage->mod_folder($mbox_name), true);
  106. $pagetitle = str_replace($delimiter, " \xC2\xBB ", $pagetitle);
  107. $OUTPUT->set_pagetitle($pagetitle);
  108. }
  109. // register UI objects
  110. $OUTPUT->add_handlers(array(
  111. 'mailboxlist' => 'rcmail_mailbox_list',
  112. 'messages' => 'rcmail_message_list',
  113. 'messagecountdisplay' => 'rcmail_messagecount_display',
  114. 'quotadisplay' => 'rcmail_quota_display',
  115. 'mailboxname' => 'rcmail_mailbox_name_display',
  116. 'messageheaders' => 'rcmail_message_headers',
  117. 'messagefullheaders' => 'rcmail_message_full_headers',
  118. 'messagebody' => 'rcmail_message_body',
  119. 'messagecontentframe' => 'rcmail_messagecontent_frame',
  120. 'messageimportform' => 'rcmail_message_import_form',
  121. 'searchfilter' => 'rcmail_search_filter',
  122. 'searchform' => array($OUTPUT, 'search_form'),
  123. ));
  124. // register action aliases
  125. $RCMAIL->register_action_map(array(
  126. 'refresh' => 'check_recent.inc',
  127. 'preview' => 'show.inc',
  128. 'print' => 'show.inc',
  129. 'move' => 'move_del.inc',
  130. 'delete' => 'move_del.inc',
  131. 'send' => 'sendmail.inc',
  132. 'expunge' => 'folders.inc',
  133. 'purge' => 'folders.inc',
  134. 'remove-attachment' => 'attachments.inc',
  135. 'display-attachment' => 'attachments.inc',
  136. 'upload' => 'attachments.inc',
  137. 'group-expand' => 'autocomplete.inc',
  138. ));
  139. /**
  140. * Returns 'to' if current folder is configured Sent or Drafts
  141. * or their subfolders, otherwise returns 'from'.
  142. *
  143. * @return string Column name
  144. */
  145. function rcmail_message_list_smart_column_name()
  146. {
  147. global $RCMAIL;
  148. $delim = $RCMAIL->storage->get_hierarchy_delimiter();
  149. $mbox = $RCMAIL->storage->get_folder();
  150. $sent_mbox = $RCMAIL->config->get('sent_mbox');
  151. $drafts_mbox = $RCMAIL->config->get('drafts_mbox');
  152. if (strpos($mbox.$delim, $sent_mbox.$delim) === 0 || strpos($mbox.$delim, $drafts_mbox.$delim) === 0) {
  153. return 'to';
  154. }
  155. return 'from';
  156. }
  157. /**
  158. * Returns configured messages list sorting column name
  159. * The name is context-sensitive, which means if sorting is set to 'fromto'
  160. * it will return 'from' or 'to' according to current folder type.
  161. *
  162. * @return string Column name
  163. */
  164. function rcmail_sort_column()
  165. {
  166. global $RCMAIL;
  167. if (isset($_SESSION['sort_col'])) {
  168. $column = $_SESSION['sort_col'];
  169. }
  170. else {
  171. $column = $RCMAIL->config->get('message_sort_col');
  172. }
  173. // get name of smart From/To column in folder context
  174. if ($column == 'fromto') {
  175. $column = rcmail_message_list_smart_column_name();
  176. }
  177. return $column;
  178. }
  179. /**
  180. * Returns configured message list sorting order
  181. *
  182. * @return string Sorting order (ASC|DESC)
  183. */
  184. function rcmail_sort_order()
  185. {
  186. global $RCMAIL;
  187. if (isset($_SESSION['sort_order'])) {
  188. return $_SESSION['sort_order'];
  189. }
  190. return $RCMAIL->config->get('message_sort_order');
  191. }
  192. /**
  193. * return the message list as HTML table
  194. */
  195. function rcmail_message_list($attrib)
  196. {
  197. global $CONFIG, $OUTPUT;
  198. // add some labels to client
  199. $OUTPUT->add_label('from', 'to');
  200. // add id to message list table if not specified
  201. if (!strlen($attrib['id']))
  202. $attrib['id'] = 'rcubemessagelist';
  203. // define list of cols to be displayed based on parameter or config
  204. if (empty($attrib['columns'])) {
  205. $a_show_cols = is_array($CONFIG['list_cols']) ? $CONFIG['list_cols'] : array('subject');
  206. $OUTPUT->set_env('col_movable', !in_array('list_cols', (array)$CONFIG['dont_override']));
  207. }
  208. else {
  209. $a_show_cols = preg_split('/[\s,;]+/', strip_quotes($attrib['columns']));
  210. $attrib['columns'] = $a_show_cols;
  211. }
  212. // save some variables for use in ajax list
  213. $_SESSION['list_attrib'] = $attrib;
  214. // make sure 'threads' and 'subject' columns are present
  215. if (!in_array('subject', $a_show_cols))
  216. array_unshift($a_show_cols, 'subject');
  217. if (!in_array('threads', $a_show_cols))
  218. array_unshift($a_show_cols, 'threads');
  219. $_SESSION['skin_path'] = $CONFIG['skin_path'];
  220. // set client env
  221. $OUTPUT->add_gui_object('messagelist', $attrib['id']);
  222. $OUTPUT->set_env('autoexpand_threads', intval($CONFIG['autoexpand_threads']));
  223. $OUTPUT->set_env('sort_col', $_SESSION['sort_col']);
  224. $OUTPUT->set_env('sort_order', $_SESSION['sort_order']);
  225. $OUTPUT->set_env('messages', array());
  226. $OUTPUT->set_env('coltypes', $a_show_cols);
  227. $OUTPUT->include_script('list.js');
  228. $table = new html_table($attrib);
  229. if (!$attrib['noheader']) {
  230. foreach (rcmail_message_list_head($attrib, $a_show_cols) as $cell)
  231. $table->add_header(array('class' => $cell['className'], 'id' => $cell['id']), $cell['html']);
  232. }
  233. return $table->show();
  234. }
  235. /**
  236. * return javascript commands to add rows to the message list
  237. */
  238. function rcmail_js_message_list($a_headers, $insert_top=FALSE, $a_show_cols=null)
  239. {
  240. global $CONFIG, $RCMAIL, $OUTPUT;
  241. if (empty($a_show_cols)) {
  242. if (!empty($_SESSION['list_attrib']['columns']))
  243. $a_show_cols = $_SESSION['list_attrib']['columns'];
  244. else
  245. $a_show_cols = is_array($CONFIG['list_cols']) ? $CONFIG['list_cols'] : array('subject');
  246. }
  247. else {
  248. if (!is_array($a_show_cols))
  249. $a_show_cols = preg_split('/[\s,;]+/', strip_quotes($a_show_cols));
  250. $head_replace = true;
  251. }
  252. $mbox = $RCMAIL->storage->get_folder();
  253. // make sure 'threads' and 'subject' columns are present
  254. if (!in_array('subject', $a_show_cols))
  255. array_unshift($a_show_cols, 'subject');
  256. if (!in_array('threads', $a_show_cols))
  257. array_unshift($a_show_cols, 'threads');
  258. $_SESSION['list_attrib']['columns'] = $a_show_cols;
  259. // Make sure there are no duplicated columns (#1486999)
  260. $a_show_cols = array_unique($a_show_cols);
  261. // Plugins may set header's list_cols/list_flags and other rcube_message_header variables
  262. // and list columns
  263. $plugin = $RCMAIL->plugins->exec_hook('messages_list',
  264. array('messages' => $a_headers, 'cols' => $a_show_cols));
  265. $a_show_cols = $plugin['cols'];
  266. $a_headers = $plugin['messages'];
  267. $thead = $head_replace ? rcmail_message_list_head($_SESSION['list_attrib'], $a_show_cols) : NULL;
  268. // get name of smart From/To column in folder context
  269. if (array_search('fromto', $a_show_cols) !== false) {
  270. $smart_col = rcmail_message_list_smart_column_name();
  271. }
  272. $OUTPUT->command('set_message_coltypes', $a_show_cols, $thead, $smart_col);
  273. if (empty($a_headers))
  274. return;
  275. // remove 'threads', 'attachment', 'flag', 'status' columns, we don't need them here
  276. foreach (array('threads', 'attachment', 'flag', 'status', 'priority') as $col) {
  277. if (($key = array_search($col, $a_show_cols)) !== FALSE)
  278. unset($a_show_cols[$key]);
  279. }
  280. // loop through message headers
  281. foreach ($a_headers as $header) {
  282. if (empty($header))
  283. continue;
  284. $a_msg_cols = array();
  285. $a_msg_flags = array();
  286. // format each col; similar as in rcmail_message_list()
  287. foreach ($a_show_cols as $col) {
  288. $col_name = $col == 'fromto' ? $smart_col : $col;
  289. if (in_array($col_name, array('from', 'to', 'cc', 'replyto')))
  290. $cont = rcmail_address_string($header->$col_name, 3, false, null, $header->charset);
  291. else if ($col == 'subject') {
  292. $cont = trim(rcube_mime::decode_header($header->$col, $header->charset));
  293. if (!$cont) $cont = rcube_label('nosubject');
  294. $cont = Q($cont);
  295. }
  296. else if ($col == 'size')
  297. $cont = show_bytes($header->$col);
  298. else if ($col == 'date')
  299. $cont = format_date($header->date);
  300. else
  301. $cont = Q($header->$col);
  302. $a_msg_cols[$col] = $cont;
  303. }
  304. $a_msg_flags = array_change_key_case(array_map('intval', (array) $header->flags));
  305. if ($header->depth)
  306. $a_msg_flags['depth'] = $header->depth;
  307. else if ($header->has_children)
  308. $roots[] = $header->uid;
  309. if ($header->parent_uid)
  310. $a_msg_flags['parent_uid'] = $header->parent_uid;
  311. if ($header->has_children)
  312. $a_msg_flags['has_children'] = $header->has_children;
  313. if ($header->unread_children)
  314. $a_msg_flags['unread_children'] = $header->unread_children;
  315. if ($header->others['list-post'])
  316. $a_msg_flags['ml'] = 1;
  317. if ($header->priority)
  318. $a_msg_flags['prio'] = (int) $header->priority;
  319. $a_msg_flags['ctype'] = Q($header->ctype);
  320. $a_msg_flags['mbox'] = $mbox;
  321. // merge with plugin result (Deprecated, use $header->flags)
  322. if (!empty($header->list_flags) && is_array($header->list_flags))
  323. $a_msg_flags = array_merge($a_msg_flags, $header->list_flags);
  324. if (!empty($header->list_cols) && is_array($header->list_cols))
  325. $a_msg_cols = array_merge($a_msg_cols, $header->list_cols);
  326. $OUTPUT->command('add_message_row',
  327. $header->uid,
  328. $a_msg_cols,
  329. $a_msg_flags,
  330. $insert_top);
  331. }
  332. if ($RCMAIL->storage->get_threading()) {
  333. $OUTPUT->command('init_threads', (array) $roots, $mbox);
  334. }
  335. }
  336. /*
  337. * Creates <THEAD> for message list table
  338. */
  339. function rcmail_message_list_head($attrib, $a_show_cols)
  340. {
  341. global $RCMAIL;
  342. $skin_path = $_SESSION['skin_path'];
  343. // check to see if we have some settings for sorting
  344. $sort_col = $_SESSION['sort_col'];
  345. $sort_order = $_SESSION['sort_order'];
  346. $dont_override = (array)$RCMAIL->config->get('dont_override');
  347. $disabled_sort = in_array('message_sort_col', $dont_override);
  348. $disabled_order = in_array('message_sort_order', $dont_override);
  349. $RCMAIL->output->set_env('disabled_sort_col', $disabled_sort);
  350. $RCMAIL->output->set_env('disabled_sort_order', $disabled_order);
  351. // define sortable columns
  352. if ($disabled_sort)
  353. $a_sort_cols = $sort_col && !$disabled_order ? array($sort_col) : array();
  354. else
  355. $a_sort_cols = array('subject', 'date', 'from', 'to', 'fromto', 'size', 'cc');
  356. if (!empty($attrib['optionsmenuicon'])) {
  357. $onclick = 'return ' . JS_OBJECT_NAME . ".command('menu-open', 'messagelistmenu')";
  358. if ($attrib['optionsmenuicon'] === true || $attrib['optionsmenuicon'] == 'true')
  359. $list_menu = html::div(array('onclick' => $onclick, 'class' => 'listmenu',
  360. 'id' => 'listmenulink', 'title' => rcube_label('listoptions')));
  361. else
  362. $list_menu = html::a(array('href' => '#', 'onclick' => $onclick),
  363. html::img(array('src' => $skin_path . $attrib['optionsmenuicon'],
  364. 'id' => 'listmenulink', 'title' => rcube_label('listoptions')))
  365. );
  366. }
  367. else
  368. $list_menu = '';
  369. $cells = array();
  370. // get name of smart From/To column in folder context
  371. if (array_search('fromto', $a_show_cols) !== false) {
  372. $smart_col = rcmail_message_list_smart_column_name();
  373. }
  374. foreach ($a_show_cols as $col) {
  375. // get column name
  376. switch ($col) {
  377. case 'flag':
  378. $col_name = '<span class="flagged">&nbsp;</span>';
  379. break;
  380. case 'attachment':
  381. case 'priority':
  382. case 'status':
  383. $col_name = '<span class="' . $col .'">&nbsp;</span>';
  384. break;
  385. case 'threads':
  386. $col_name = $list_menu;
  387. break;
  388. case 'fromto':
  389. $col_name = Q(rcube_label($smart_col));
  390. break;
  391. default:
  392. $col_name = Q(rcube_label($col));
  393. }
  394. // make sort links
  395. if (in_array($col, $a_sort_cols))
  396. $col_name = html::a(array('href'=>"./#sort", 'onclick' => 'return '.JS_OBJECT_NAME.".command('sort','".$col."',this)", 'title' => rcube_label('sortby')), $col_name);
  397. else if ($col_name[0] != '<')
  398. $col_name = '<span class="' . $col .'">' . $col_name . '</span>';
  399. $sort_class = $col == $sort_col && !$disabled_order ? " sorted$sort_order" : '';
  400. $class_name = $col.$sort_class;
  401. // put it all together
  402. $cells[] = array('className' => $class_name, 'id' => "rcm$col", 'html' => $col_name);
  403. }
  404. return $cells;
  405. }
  406. /**
  407. * return an HTML iframe for loading mail content
  408. */
  409. function rcmail_messagecontent_frame($attrib)
  410. {
  411. global $OUTPUT, $RCMAIL;
  412. if (empty($attrib['id']))
  413. $attrib['id'] = 'rcmailcontentwindow';
  414. $attrib['name'] = $attrib['id'];
  415. if ($RCMAIL->config->get('preview_pane'))
  416. $OUTPUT->set_env('contentframe', $attrib['id']);
  417. $OUTPUT->set_env('blankpage', $attrib['src'] ? $OUTPUT->abs_url($attrib['src']) : 'program/resources/blank.gif');
  418. return $OUTPUT->frame($attrib, true);
  419. }
  420. function rcmail_messagecount_display($attrib)
  421. {
  422. global $RCMAIL;
  423. if (!$attrib['id'])
  424. $attrib['id'] = 'rcmcountdisplay';
  425. $RCMAIL->output->add_gui_object('countdisplay', $attrib['id']);
  426. $content = $RCMAIL->action != 'show' ? rcmail_get_messagecount_text() : rcube_label('loading');
  427. return html::span($attrib, $content);
  428. }
  429. function rcmail_get_messagecount_text($count=NULL, $page=NULL)
  430. {
  431. global $RCMAIL;
  432. if ($page === NULL) {
  433. $page = $RCMAIL->storage->get_page();
  434. }
  435. $page_size = $RCMAIL->storage->get_pagesize();
  436. $start_msg = ($page-1) * $page_size + 1;
  437. if ($count!==NULL)
  438. $max = $count;
  439. else if ($RCMAIL->action)
  440. $max = $RCMAIL->storage->count(NULL, $RCMAIL->storage->get_threading() ? 'THREADS' : 'ALL');
  441. if ($max==0)
  442. $out = rcube_label('mailboxempty');
  443. else
  444. $out = rcube_label(array('name' => $RCMAIL->storage->get_threading() ? 'threadsfromto' : 'messagesfromto',
  445. 'vars' => array('from' => $start_msg,
  446. 'to' => min($max, $start_msg + $page_size - 1),
  447. 'count' => $max)));
  448. return Q($out);
  449. }
  450. function rcmail_mailbox_name_display($attrib)
  451. {
  452. global $RCMAIL;
  453. if (!$attrib['id'])
  454. $attrib['id'] = 'rcmmailboxname';
  455. $RCMAIL->output->add_gui_object('mailboxname', $attrib['id']);
  456. return html::span($attrib, rcmail_get_mailbox_name_text());
  457. }
  458. function rcmail_get_mailbox_name_text()
  459. {
  460. global $RCMAIL;
  461. return rcmail_localize_foldername($RCMAIL->storage->get_folder());
  462. }
  463. function rcmail_send_unread_count($mbox_name, $force=false, $count=null, $mark='')
  464. {
  465. global $RCMAIL;
  466. $old_unseen = rcmail_get_unseen_count($mbox_name);
  467. if ($count === null)
  468. $unseen = $RCMAIL->storage->count($mbox_name, 'UNSEEN', $force);
  469. else
  470. $unseen = $count;
  471. if ($unseen != $old_unseen || ($mbox_name == 'INBOX'))
  472. $RCMAIL->output->command('set_unread_count', $mbox_name, $unseen,
  473. ($mbox_name == 'INBOX'), $unseen && $mark ? $mark : '');
  474. rcmail_set_unseen_count($mbox_name, $unseen);
  475. return $unseen;
  476. }
  477. function rcmail_set_unseen_count($mbox_name, $count)
  478. {
  479. // @TODO: this data is doubled (session and cache tables) if caching is enabled
  480. // Make sure we have an array here (#1487066)
  481. if (!is_array($_SESSION['unseen_count']))
  482. $_SESSION['unseen_count'] = array();
  483. $_SESSION['unseen_count'][$mbox_name] = $count;
  484. }
  485. function rcmail_get_unseen_count($mbox_name)
  486. {
  487. if (is_array($_SESSION['unseen_count']) && array_key_exists($mbox_name, $_SESSION['unseen_count']))
  488. return $_SESSION['unseen_count'][$mbox_name];
  489. else
  490. return null;
  491. }
  492. /**
  493. * Sets message is_safe flag according to 'show_images' option value
  494. *
  495. * @param object rcube_message Message
  496. */
  497. function rcmail_check_safe(&$message)
  498. {
  499. global $RCMAIL;
  500. if (!$message->is_safe
  501. && ($show_images = $RCMAIL->config->get('show_images'))
  502. && $message->has_html_part()
  503. ) {
  504. switch ($show_images) {
  505. case 1: // known senders only
  506. // get default addressbook, like in addcontact.inc
  507. $CONTACTS = $RCMAIL->get_address_book(-1, true);
  508. if ($CONTACTS) {
  509. $result = $CONTACTS->search('email', $message->sender['mailto'], 1, false);
  510. if ($result->count) {
  511. $message->set_safe(true);
  512. }
  513. }
  514. break;
  515. case 2: // always
  516. $message->set_safe(true);
  517. break;
  518. }
  519. }
  520. }
  521. /**
  522. * Cleans up the given message HTML Body (for displaying)
  523. *
  524. * @param string HTML
  525. * @param array Display parameters
  526. * @param array CID map replaces (inline images)
  527. * @return string Clean HTML
  528. */
  529. function rcmail_wash_html($html, $p, $cid_replaces)
  530. {
  531. global $REMOTE_OBJECTS;
  532. $p += array('safe' => false, 'inline_html' => true);
  533. // charset was converted to UTF-8 in rcube_storage::get_message_part(),
  534. // change/add charset specification in HTML accordingly,
  535. // washtml cannot work without that
  536. $meta = '<meta http-equiv="Content-Type" content="text/html; charset='.RCMAIL_CHARSET.'" />';
  537. // remove old meta tag and add the new one, making sure
  538. // that it is placed in the head (#1488093)
  539. $html = preg_replace('/<meta[^>]+charset=[a-z0-9-_]+[^>]*>/Ui', '', $html);
  540. $html = preg_replace('/(<head[^>]*>)/Ui', '\\1'.$meta, $html, -1, $rcount);
  541. if (!$rcount) {
  542. $html = '<head>' . $meta . '</head>' . $html;
  543. }
  544. // clean HTML with washhtml by Frederic Motte
  545. $wash_opts = array(
  546. 'show_washed' => false,
  547. 'allow_remote' => $p['safe'],
  548. 'blocked_src' => "./program/resources/blocked.gif",
  549. 'charset' => RCMAIL_CHARSET,
  550. 'cid_map' => $cid_replaces,
  551. 'html_elements' => array('body'),
  552. );
  553. if (!$p['inline_html']) {
  554. $wash_opts['html_elements'] = array('html','head','title','body');
  555. }
  556. if ($p['safe']) {
  557. $wash_opts['html_elements'][] = 'link';
  558. $wash_opts['html_attribs'] = array('rel','type');
  559. }
  560. // overwrite washer options with options from plugins
  561. if (isset($p['html_elements']))
  562. $wash_opts['html_elements'] = $p['html_elements'];
  563. if (isset($p['html_attribs']))
  564. $wash_opts['html_attribs'] = $p['html_attribs'];
  565. // initialize HTML washer
  566. $washer = new rcube_washtml($wash_opts);
  567. if (!$p['skip_washer_form_callback'])
  568. $washer->add_callback('form', 'rcmail_washtml_callback');
  569. // allow CSS styles, will be sanitized by rcmail_washtml_callback()
  570. if (!$p['skip_washer_style_callback'])
  571. $washer->add_callback('style', 'rcmail_washtml_callback');
  572. // Remove non-UTF8 characters (#1487813)
  573. $html = rc_utf8_clean($html);
  574. $html = $washer->wash($html);
  575. $REMOTE_OBJECTS = $washer->extlinks;
  576. return $html;
  577. }
  578. /**
  579. * Convert the given message part to proper HTML
  580. * which can be displayed the message view
  581. *
  582. * @param object rcube_message_part Message part
  583. * @param array Display parameters array
  584. * @return string Formatted HTML string
  585. */
  586. function rcmail_print_body($part, $p = array())
  587. {
  588. global $RCMAIL;
  589. // trigger plugin hook
  590. $data = $RCMAIL->plugins->exec_hook('message_part_before',
  591. array('type' => $part->ctype_secondary, 'body' => $part->body, 'id' => $part->mime_id)
  592. + $p + array('safe' => false, 'plain' => false, 'inline_html' => true));
  593. // convert html to text/plain
  594. if ($data['plain'] && ($data['type'] == 'html' || $data['type'] == 'enriched')) {
  595. if ($data['type'] == 'enriched') {
  596. $data['body'] = rcube_enriched::to_html($data['body']);
  597. }
  598. $txt = new rcube_html2text($data['body'], false, true);
  599. $body = $txt->get_text();
  600. $part->ctype_secondary = 'plain';
  601. }
  602. // text/html
  603. else if ($data['type'] == 'html') {
  604. $body = rcmail_wash_html($data['body'], $data, $part->replaces);
  605. $part->ctype_secondary = $data['type'];
  606. }
  607. // text/enriched
  608. else if ($data['type'] == 'enriched') {
  609. $body = rcube_enriched::to_html($data['body']);
  610. $body = rcmail_wash_html($body, $data, $part->replaces);
  611. $part->ctype_secondary = 'html';
  612. }
  613. else {
  614. // assert plaintext
  615. $body = $part->body;
  616. $part->ctype_secondary = $data['type'] = 'plain';
  617. }
  618. // free some memory (hopefully)
  619. unset($data['body']);
  620. // plaintext postprocessing
  621. if ($part->ctype_secondary == 'plain') {
  622. if ($part->ctype_secondary == 'plain' && $part->ctype_parameters['format'] == 'flowed') {
  623. $body = rcube_mime::unfold_flowed($body);
  624. }
  625. $body = rcmail_plain_body($body);
  626. }
  627. // allow post-processing of the message body
  628. $data = $RCMAIL->plugins->exec_hook('message_part_after',
  629. array('type' => $part->ctype_secondary, 'body' => $body, 'id' => $part->mime_id) + $data);
  630. return $data['type'] == 'html' ? $data['body'] : html::tag('pre', array(), $data['body']);
  631. }
  632. /**
  633. * Handle links and citation marks in plain text message
  634. *
  635. * @param string Plain text string
  636. *
  637. * @return string Formatted HTML string
  638. */
  639. function rcmail_plain_body($body)
  640. {
  641. global $RCMAIL;
  642. // make links and email-addresses clickable
  643. $attribs = array('link_attribs' => array('rel' => 'noreferrer', 'target' => '_blank'));
  644. $replacer = new rcmail_string_replacer($attribs);
  645. // search for patterns like links and e-mail addresses and replace with tokens
  646. $body = $replacer->replace($body);
  647. // split body into single lines
  648. $body = preg_split('/\r?\n/', $body);
  649. $quote_level = 0;
  650. $last = -1;
  651. // find/mark quoted lines...
  652. for ($n=0, $cnt=count($body); $n < $cnt; $n++) {
  653. if ($body[$n][0] == '>' && preg_match('/^(>+ {0,1})+/', $body[$n], $regs)) {
  654. $q = substr_count($regs[0], '>');
  655. $body[$n] = substr($body[$n], strlen($regs[0]));
  656. if ($q > $quote_level) {
  657. $body[$n] = $replacer->get_replacement($replacer->add(
  658. str_repeat('<blockquote>', $q - $quote_level))) . $body[$n];
  659. $last = $n;
  660. }
  661. else if ($q < $quote_level) {
  662. $body[$n] = $replacer->get_replacement($replacer->add(
  663. str_repeat('</blockquote>', $quote_level - $q))) . $body[$n];
  664. $last = $n;
  665. }
  666. }
  667. else {
  668. $q = 0;
  669. if ($quote_level > 0)
  670. $body[$n] = $replacer->get_replacement($replacer->add(
  671. str_repeat('</blockquote>', $quote_level))) . $body[$n];
  672. }
  673. $quote_level = $q;
  674. }
  675. $body = join("\n", $body);
  676. // quote plain text (don't use Q() here, to display entities "as is")
  677. $table = get_html_translation_table(HTML_SPECIALCHARS);
  678. unset($table['?']);
  679. $body = strtr($body, $table);
  680. // colorize signature (up to <sig_max_lines> lines)
  681. $len = strlen($body);
  682. $sig_max_lines = $RCMAIL->config->get('sig_max_lines', 15);
  683. while (($sp = strrpos($body, "-- \n", $sp ? -$len+$sp-1 : 0)) !== false) {
  684. if ($sp == 0 || $body[$sp-1] == "\n") {
  685. // do not touch blocks with more that X lines
  686. if (substr_count($body, "\n", $sp) < $sig_max_lines)
  687. $body = substr($body, 0, max(0, $sp))
  688. .'<span class="sig">'.substr($body, $sp).'</span>';
  689. break;
  690. }
  691. }
  692. // insert url/mailto links and citation tags
  693. $body = $replacer->resolve($body);
  694. return $body;
  695. }
  696. /**
  697. * Callback function for washtml cleaning class
  698. */
  699. function rcmail_washtml_callback($tagname, $attrib, $content, $washtml)
  700. {
  701. switch ($tagname) {
  702. case 'form':
  703. $out = html::div('form', $content);
  704. break;
  705. case 'style':
  706. // decode all escaped entities and reduce to ascii strings
  707. $stripped = preg_replace('/[^a-zA-Z\(:;]/', '', rcmail_xss_entity_decode($content));
  708. // now check for evil strings like expression, behavior or url()
  709. if (!preg_match('/expression|behavior|javascript:|import[^a]/i', $stripped)) {
  710. if (!$washtml->get_config('allow_remote') && stripos($stripped, 'url('))
  711. $washtml->extlinks = true;
  712. else
  713. $out = html::tag('style', array('type' => 'text/css'), $content);
  714. break;
  715. }
  716. default:
  717. $out = '';
  718. }
  719. return $out;
  720. }
  721. /**
  722. * return table with message headers
  723. */
  724. function rcmail_message_headers($attrib, $headers=null)
  725. {
  726. global $MESSAGE, $PRINT_MODE, $RCMAIL;
  727. static $sa_attrib;
  728. // keep header table attrib
  729. if (is_array($attrib) && !$sa_attrib && !$attrib['valueof'])
  730. $sa_attrib = $attrib;
  731. else if (!is_array($attrib) && is_array($sa_attrib))
  732. $attrib = $sa_attrib;
  733. if (!isset($MESSAGE))
  734. return FALSE;
  735. // get associative array of headers object
  736. if (!$headers) {
  737. $headers_obj = $MESSAGE->headers;
  738. $headers = get_object_vars($MESSAGE->headers);
  739. }
  740. else if (is_object($headers)) {
  741. $headers_obj = $headers;
  742. $headers = get_object_vars($headers_obj);
  743. }
  744. else {
  745. $headers_obj = rcube_message_header::from_array($headers);
  746. }
  747. // show these headers
  748. $standard_headers = array('subject', 'from', 'sender', 'to', 'cc', 'bcc', 'replyto',
  749. 'mail-reply-to', 'mail-followup-to', 'date', 'priority');
  750. $exclude_headers = $attrib['exclude'] ? explode(',', $attrib['exclude']) : array();
  751. $output_headers = array();
  752. foreach ($standard_headers as $hkey) {
  753. $ishtml = false;
  754. if ($headers[$hkey])
  755. $value = $headers[$hkey];
  756. else if ($headers['others'][$hkey])
  757. $value = $headers['others'][$hkey];
  758. else if (!$attrib['valueof'])
  759. continue;
  760. if (in_array($hkey, $exclude_headers))
  761. continue;
  762. $header_title = rcube_label(preg_replace('/(^mail-|-)/', '', $hkey));
  763. if ($hkey == 'date') {
  764. if ($PRINT_MODE)
  765. $header_value = format_date($value, $RCMAIL->config->get('date_long', 'x'));
  766. else
  767. $header_value = format_date($value);
  768. }
  769. else if ($hkey == 'priority') {
  770. if ($value) {
  771. $header_value = html::span('prio' . $value, rcmail_localized_priority($value));
  772. }
  773. else
  774. continue;
  775. }
  776. else if ($hkey == 'replyto') {
  777. if ($headers['replyto'] != $headers['from']) {
  778. $header_value = rcmail_address_string($value, $attrib['max'], true, $attrib['addicon'], $headers['charset'], $header_title);
  779. $ishtml = true;
  780. }
  781. else
  782. continue;
  783. }
  784. else if ($hkey == 'mail-reply-to') {
  785. if ($headers['mail-replyto'] != $headers['reply-to']
  786. && $headers['reply-to'] != $headers['from']
  787. ) {
  788. $header_value = rcmail_address_string($value, $attrib['max'], true, $attrib['addicon'], $headers['charset'], $header_title);
  789. $ishtml = true;
  790. }
  791. else
  792. continue;
  793. }
  794. else if ($hkey == 'sender') {
  795. if ($headers['sender'] != $headers['from']) {
  796. $header_value = rcmail_address_string($value, $attrib['max'], true, $attrib['addicon'], $headers['charset'], $header_title);
  797. $ishtml = true;
  798. }
  799. else
  800. continue;
  801. }
  802. else if ($hkey == 'mail-followup-to') {
  803. $header_value = rcmail_address_string($value, $attrib['max'], true, $attrib['addicon'], $headers['charset'], $header_title);
  804. $ishtml = true;
  805. }
  806. else if (in_array($hkey, array('from', 'to', 'cc', 'bcc'))) {
  807. $header_value = rcmail_address_string($value, $attrib['max'], true, $attrib['addicon'], $headers['charset'], $header_title);
  808. $ishtml = true;
  809. }
  810. else if ($hkey == 'subject' && empty($value))
  811. $header_value = rcube_label('nosubject');
  812. else
  813. $header_value = trim(rcube_mime::decode_header($value, $headers['charset']));
  814. $output_headers[$hkey] = array(
  815. 'title' => $header_title,
  816. 'value' => $header_value,
  817. 'raw' => $value,
  818. 'html' => $ishtml,
  819. );
  820. }
  821. $plugin = $RCMAIL->plugins->exec_hook('message_headers_output',
  822. array('output' => $output_headers, 'headers' => $headers_obj, 'exclude' => $exclude_headers));
  823. // single header value is requested
  824. if (!empty($attrib['valueof']))
  825. return Q($plugin['output'][$attrib['valueof']]['value'], ($attrib['valueof'] == 'subject' ? 'strict' : 'show'));
  826. // compose html table
  827. $table = new html_table(array('cols' => 2));
  828. foreach ($plugin['output'] as $hkey => $row) {
  829. $table->add(array('class' => 'header-title'), Q($row['title']));
  830. $table->add(array('class' => 'header '.$hkey), $row['html'] ? $row['value'] : Q($row['value'], ($hkey == 'subject' ? 'strict' : 'show')));
  831. }
  832. return $table->show($attrib);
  833. }
  834. /**
  835. * Convert Priority header value into a localized string
  836. */
  837. function rcmail_localized_priority($value)
  838. {
  839. $labels_map = array(
  840. '1' => 'highest',
  841. '2' => 'high',
  842. '3' => 'normal',
  843. '4' => 'low',
  844. '5' => 'lowest',
  845. );
  846. if ($value && $labels_map[$value])
  847. return rcube_label($labels_map[$value]);
  848. return '';
  849. }
  850. /**
  851. * return block to show full message headers
  852. */
  853. function rcmail_message_full_headers($attrib, $headers=NULL)
  854. {
  855. global $OUTPUT;
  856. $html = html::div(array('id' => "all-headers", 'class' => "all", 'style' => 'display:none'), html::div(array('id' => 'headers-source'), ''));
  857. $html .= html::div(array('class' => "more-headers show-headers", 'onclick' => "return ".JS_OBJECT_NAME.".command('show-headers','',this)", 'title' => rcube_label('togglefullheaders')), '');
  858. $OUTPUT->add_gui_object('all_headers_row', 'all-headers');
  859. $OUTPUT->add_gui_object('all_headers_box', 'headers-source');
  860. return html::div($attrib, $html);
  861. }
  862. /**
  863. * Handler for the 'messagebody' GUI object
  864. *
  865. * @param array Named parameters
  866. * @return string HTML content showing the message body
  867. */
  868. function rcmail_message_body($attrib)
  869. {
  870. global $CONFIG, $OUTPUT, $MESSAGE, $RCMAIL, $REMOTE_OBJECTS;
  871. if (!is_array($MESSAGE->parts) && empty($MESSAGE->body))
  872. return '';
  873. if (!$attrib['id'])
  874. $attrib['id'] = 'rcmailMsgBody';
  875. $safe_mode = $MESSAGE->is_safe || intval($_GET['_safe']);
  876. $out = '';
  877. $header_attrib = array();
  878. foreach ($attrib as $attr => $value)
  879. if (preg_match('/^headertable([a-z]+)$/i', $attr, $regs))
  880. $header_attrib[$regs[1]] = $value;
  881. if (!empty($MESSAGE->parts)) {
  882. foreach ($MESSAGE->parts as $part) {
  883. if ($part->type == 'headers') {
  884. $out .= html::div('message-partheaders', rcmail_message_headers(sizeof($header_attrib) ? $header_attrib : null, $part->headers));
  885. }
  886. else if ($part->type == 'content') {
  887. // unsupported (e.g. encrypted)
  888. if ($part->realtype) {
  889. if ($part->realtype == 'multipart/encrypted' || $part->realtype == 'application/pkcs7-mime') {
  890. $out .= html::span('part-notice', rcube_label('encryptedmessage'));
  891. }
  892. continue;
  893. }
  894. else if (!$part->size) {
  895. continue;
  896. }
  897. // Check if we have enough memory to handle the message in it
  898. // #1487424: we need up to 10x more memory than the body
  899. else if (!rcmail_mem_check($part->size * 10)) {
  900. $out .= html::span('part-notice', rcube_label('messagetoobig'). ' '
  901. . html::a('?_task=mail&_action=get&_download=1&_uid='.$MESSAGE->uid.'&_part='.$part->mime_id
  902. .'&_mbox='. urlencode($RCMAIL->storage->get_folder()), rcube_label('download')));
  903. continue;
  904. }
  905. if (empty($part->ctype_parameters) || empty($part->ctype_parameters['charset']))
  906. $part->ctype_parameters['charset'] = $MESSAGE->headers->charset;
  907. // fetch part if not available
  908. if (!isset($part->body))
  909. $part->body = $MESSAGE->get_part_content($part->mime_id);
  910. // extract headers from message/rfc822 parts
  911. if ($part->mimetype == 'message/rfc822') {
  912. $msgpart = rcube_mime::parse_message($part->body);
  913. if (!empty($msgpart->headers)) {
  914. $part = $msgpart;
  915. $out .= html::div('message-partheaders', rcmail_message_headers(sizeof($header_attrib) ? $header_attrib : null, $part->headers));
  916. }
  917. }
  918. // message is cached but not exists (#1485443), or other error
  919. if ($part->body === false) {
  920. rcmail_message_error($MESSAGE->uid);
  921. }
  922. $plugin = $RCMAIL->plugins->exec_hook('message_body_prefix', array(
  923. 'part' => $part, 'prefix' => ''));
  924. $body = rcmail_print_body($part, array('safe' => $safe_mode, 'plain' => !$CONFIG['prefer_html']));
  925. if ($part->ctype_secondary == 'html') {
  926. $body = rcmail_html4inline($body, $attrib['id'], 'rcmBody', $attrs, $safe_mode);
  927. $div_attr = array('class' => 'message-htmlpart');
  928. $style = array();
  929. if (!empty($attrs)) {
  930. foreach ($attrs as $a_idx => $a_val)
  931. $style[] = $a_idx . ': ' . $a_val;
  932. if (!empty($style))
  933. $div_attr['style'] = implode('; ', $style);
  934. }
  935. $out .= html::div($div_attr, $plugin['prefix'] . $body);
  936. }
  937. else
  938. $out .= html::div('message-part', $plugin['prefix'] . $body);
  939. }
  940. }
  941. }
  942. else {
  943. // Check if we have enough memory to handle the message in it
  944. // #1487424: we need up to 10x more memory than the body
  945. if (!rcmail_mem_check(strlen($MESSAGE->body) * 10)) {
  946. $out .= html::span('part-notice', rcube_label('messagetoobig'). ' '
  947. . html::a('?_task=mail&_action=get&_download=1&_uid='.$MESSAGE->uid.'&_part=0'
  948. .'&_mbox='. urlencode($RCMAIL->storage->get_folder()), rcube_label('download')));
  949. }
  950. else {
  951. $plugin = $RCMAIL->plugins->exec_hook('message_body_prefix', array(
  952. 'part' => $MESSAGE, 'prefix' => ''));
  953. $out .= html::div('message-part', $plugin['prefix'] . html::tag('pre', array(),
  954. rcmail_plain_body(Q($MESSAGE->body, 'strict', false))));
  955. }
  956. }
  957. // list images after mail body
  958. if ($RCMAIL->config->get('inline_images', true) && !empty($MESSAGE->attachments)) {
  959. $thumbnail_size = $RCMAIL->config->get('image_thumbnail_size', 240);
  960. $client_mimetypes = (array)$RCMAIL->config->get('client_mimetypes');
  961. foreach ($MESSAGE->attachments as $attach_prop) {
  962. // skip inline images
  963. if ($attach_prop->content_id && $attach_prop->disposition == 'inline') {
  964. continue;
  965. }
  966. // Content-Type: image/*...
  967. if ($mimetype = rcmail_part_image_type($attach_prop)) {
  968. // display thumbnails
  969. if ($thumbnail_size) {
  970. $show_link = array(
  971. 'href' => $MESSAGE->get_part_url($attach_prop->mime_id, false),
  972. 'onclick' => sprintf(
  973. 'return %s.command(\'load-attachment\',\'%s\',this)',
  974. JS_OBJECT_NAME,
  975. $attach_prop->mime_id)
  976. );
  977. $out .= html::p('image-attachment',
  978. html::a($show_link + array('class' => 'image-link', 'style' => sprintf('width:%dpx', $thumbnail_size)),
  979. html::img(array(
  980. 'class' => 'image-thumbnail',
  981. 'src' => $MESSAGE->get_part_url($attach_prop->mime_id, 'image') . '&_thumb=1',
  982. 'title' => $attach_prop->filename,
  983. 'alt' => $attach_prop->filename,
  984. 'style' => sprintf('max-width:%dpx; max-height:%dpx', $thumbnail_size, $thumbnail_size),
  985. ))
  986. ) .
  987. html::span('image-filename', Q($attach_prop->filename)) .
  988. html::span('image-filesize', Q($RCMAIL->message_part_size($attach_prop))) .
  989. html::span('attachment-links',
  990. (in_array($mimetype, $client_mimetypes) ? html::a($show_link, rcube_label('showattachment')) . '&nbsp;' : '') .
  991. html::a($show_link['href'] . '&_download=1', rcube_label('download'))
  992. ) .
  993. html::br(array('style' => 'clear:both'))
  994. );
  995. }
  996. else {
  997. $out .= html::tag('fieldset', 'image-attachment',
  998. html::tag('legend', 'image-filename', Q($attach_prop->filename)) .
  999. html::p(array('align' => "center"),
  1000. html::img(array(
  1001. 'src' => $MESSAGE->get_part_url($attach_prop->mime_id, 'image'),
  1002. 'title' => $attach_prop->filename,
  1003. 'alt' => $attach_prop->filename,
  1004. )))
  1005. );
  1006. }
  1007. }
  1008. }
  1009. }
  1010. // tell client that there are blocked remote objects
  1011. if ($REMOTE_OBJECTS && !$safe_mode)
  1012. $OUTPUT->set_env('blockedobjects', true);
  1013. return html::div($attrib, $out);
  1014. }
  1015. function rcmail_part_image_type($part)
  1016. {
  1017. $rcmail = rcmail::get_instance();
  1018. // Skip TIFF images if browser doesn't support this format...
  1019. $tiff_support = !empty($_SESSION['browser_caps']) && !empty($_SESSION['browser_caps']['tif']);
  1020. // until we can convert them to JPEG
  1021. $tiff_support = $tiff_support || $rcmail->config->get('im_convert_path');
  1022. // Content-type regexp
  1023. $mime_regex = $tiff_support ? '/^image\//i' : '/^image\/(?!tif)/i';
  1024. // Content-Type: image/*...
  1025. if (preg_match($mime_regex, $part->mimetype)) {
  1026. return rcmail_fix_mimetype($part->mimetype);
  1027. }
  1028. // Many clients use application/octet-stream, we'll detect mimetype
  1029. // by checking filename extension
  1030. // Supported image filename extensions to image type map
  1031. $types = array(
  1032. 'jpg' => 'image/jpeg',
  1033. 'jpeg' => 'image/jpeg',
  1034. 'png' => 'image/png',
  1035. 'gif' => 'image/gif',
  1036. 'bmp' => 'image/bmp',
  1037. );
  1038. if ($tiff_support) {
  1039. $types['tif'] = 'image/tiff';
  1040. $types['tiff'] = 'image/tiff';
  1041. }
  1042. if ($part->filename
  1043. && preg_match('/^application\/octet-stream$/i', $part->mimetype)
  1044. && preg_match('/\.([^.]+)$/i', $part->filename, $m)
  1045. && ($extension = strtolower($m[1]))
  1046. && isset($types[$extension])
  1047. ) {
  1048. return $types[$extension];
  1049. }
  1050. }
  1051. /**
  1052. * modify a HTML message that it can be displayed inside a HTML page
  1053. */
  1054. function rcmail_html4inline($body, $container_id, $body_id='', &$attributes=null, $allow_remote=false)
  1055. {
  1056. $last_style_pos = 0;
  1057. $cont_id = $container_id.($body_id ? ' div.'.$body_id : '');
  1058. // find STYLE tags
  1059. while (($pos = stripos($body, '<style', $last_style_pos)) && ($pos2 = stripos($body, '</style>', $pos)))
  1060. {
  1061. $pos = strpos($body, '>', $pos) + 1;
  1062. $len = $pos2 - $pos;
  1063. // replace all css definitions with #container [def]
  1064. $styles = substr($body, $pos, $len);
  1065. $styles = rcmail_mod_css_styles($styles, $cont_id, $allow_remote);
  1066. $body = substr_replace($body, $styles, $pos, $len);
  1067. $last_style_pos = $pos2 + strlen($styles) - $len;
  1068. }
  1069. // modify HTML links to open a new window if clicked
  1070. $GLOBALS['rcmail_html_container_id'] = $container_id;
  1071. $body = preg_replace_callback('/<(a|link|area)\s+([^>]+)>/Ui', 'rcmail_alter_html_link', $body);
  1072. unset($GLOBALS['rcmail_html_container_id']);
  1073. $body = preg_replace(array(
  1074. // add comments arround html and other tags
  1075. '/(<!DOCTYPE[^>]*>)/i',
  1076. '/(<\?xml[^>]*>)/i',
  1077. '/(<\/?html[^>]*>)/i',
  1078. '/(<\/?head[^>]*>)/i',
  1079. '/(<title[^>]*>.*<\/title>)/Ui',
  1080. '/(<\/?meta[^>]*>)/i',
  1081. // quote <? of php and xml files that are specified as text/html
  1082. '/<\?/',
  1083. '/\?>/',
  1084. // replace <body> with <div>
  1085. '/<body([^>]*)>/i',
  1086. '/<\/body>/i',
  1087. ),
  1088. array(
  1089. '<!--\\1-->',
  1090. '<!--\\1-->',
  1091. '<!--\\1-->',
  1092. '<!--\\1-->',
  1093. '<!--\\1-->',
  1094. '<!--\\1-->',
  1095. '&lt;?',
  1096. '?&gt;',
  1097. '<div class="'.$body_id.'"\\1>',
  1098. '</div>',
  1099. ),
  1100. $body);
  1101. $attributes = array();
  1102. // Handle body attributes that doesn't play nicely with div elements
  1103. $regexp = '/<div class="' . preg_quote($body_id, '/') . '"([^>]*)/';
  1104. if (preg_match($regexp, $body, $m)) {
  1105. $attrs = $m[0];
  1106. // Get bgcolor, we'll set it as background-color of the message container
  1107. if ($m[1] && preg_match('/bgcolor=["\']*([a-z0-9#]+)["\']*/', $attrs, $mb)) {
  1108. $attributes['background-color'] = $mb[1];
  1109. $attrs = preg_replace('/bgcolor=["\']*([a-z0-9#]+)["\']*/', '', $attrs);
  1110. }
  1111. // Get background, we'll set it as background-image of the message container
  1112. if ($m[1] && preg_match('/background=["\']*([^"\'>\s]+)["\']*/', $attrs, $mb)) {
  1113. $attributes['background-image'] = 'url('.$mb[1].')';
  1114. $attrs = preg_replace('/background=["\']*([^"\'>\s]+)["\']*/', '', $attrs);
  1115. }
  1116. if (!empty($attributes)) {
  1117. $body = preg_replace($regexp, rtrim($attrs), $body, 1);
  1118. }
  1119. // handle body styles related to background image
  1120. if ($attributes['background-image']) {
  1121. // get body style
  1122. if (preg_match('/#'.preg_quote($cont_id, '/').'\s+\{([^}]+)}/i', $body, $m)) {
  1123. // get background related style
  1124. if (preg_match_all('/(background-position|background-repeat)\s*:\s*([^;]+);/i', $m[1], $ma, PREG_SET_ORDER)) {
  1125. foreach ($ma as $style)
  1126. $attributes[$style[1]] = $style[2];
  1127. }
  1128. }
  1129. }
  1130. }
  1131. // make sure there's 'rcmBody' div, we need it for proper css modification
  1132. // its name is hardcoded in rcmail_message_body() also
  1133. else {
  1134. $body = '<div class="' . $body_id . '">' . $body . '</div>';
  1135. }
  1136. return $body;
  1137. }
  1138. /**
  1139. * parse link (a, link, area) attributes and set correct target
  1140. */
  1141. function rcmail_alter_html_link($matches)
  1142. {
  1143. global $RCMAIL;
  1144. // Support unicode/punycode in top-level domain part
  1145. $EMAIL_PATTERN = '([a-z0-9][a-z0-9\-\.\+\_]*@[^&@"\'.][^@&"\']*\\.([^\\x00-\\x40\\x5b-\\x60\\x7b-\\x7f]{2,}|xn--[a-z0-9]{2,}))';
  1146. $tag = strtolower($matches[1]);
  1147. $attrib = parse_attrib_string($matches[2]);
  1148. $end = '>';
  1149. // Remove non-printable characters in URL (#1487805)
  1150. if ($attrib['href'])
  1151. $attrib['href'] = preg_replace('/[\x00-\x1F]/', '', $attrib['href']);
  1152. if ($tag == 'link' && preg_match('/^https?:\/\//i', $attrib['href'])) {
  1153. $tempurl = 'tmp-' . md5($attrib['href']) . '.css';
  1154. $_SESSION['modcssurls'][$tempurl] = $attrib['href'];
  1155. $attrib['href'] = $RCMAIL->url(array('task' => 'utils', 'action' => 'modcss', 'u' => $tempurl, 'c' => $GLOBALS['rcmail_html_container_id']));
  1156. $end = ' />';
  1157. }
  1158. else if (preg_match('/^mailto:'.$EMAIL_PATTERN.'(\?[^"\'>]+)?/i', $attrib['href'], $mailto)) {
  1159. $attrib['href'] = $mailto[0];
  1160. $attrib['onclick'] = sprintf(
  1161. "return %s.command('compose','%s',this)",
  1162. JS_OBJECT_NAME,
  1163. JQ($mailto[1].$mailto[3]));
  1164. }
  1165. else if (empty($attrib['href']) && !$attrib['name']) {
  1166. $attrib['href'] = './#NOP';
  1167. $attrib['onclick'] = 'return false';
  1168. }
  1169. else if (!empty($attrib['href']) && $attrib['href'][0] != '#') {
  1170. $attrib['target'] = '_blank';
  1171. }
  1172. // Better security by adding rel="noreferrer" (#1484686)
  1173. if (($tag == 'a' || $tag == 'area') && $attrib['href'] && $attrib['href'][0] != '#') {
  1174. $attrib['rel'] = 'noreferrer';
  1175. }
  1176. // allowed attributes for a|link|area tags
  1177. $allow = array('href','name','target','onclick','id','class','style','title',
  1178. 'rel','type','media','alt','coords','nohref','hreflang','shape');
  1179. return "<$tag" . html::attrib_string($attrib, $allow) . $end;
  1180. }
  1181. /**
  1182. * decode address string and re-format it as HTML links
  1183. */
  1184. function rcmail_address_string($input, $max=null, $linked=false, $addicon=null, $default_charset=null, $title=null)
  1185. {
  1186. global $RCMAIL, $PRINT_MODE, $CONFIG;
  1187. $a_parts = rcube_mime::decode_address_list($input, null, true, $default_charset);
  1188. if (!sizeof($a_parts))
  1189. return $input;
  1190. $c = count($a_parts);
  1191. $j = 0;
  1192. $out = '';
  1193. $allvalues = array();
  1194. $show_email = $RCMAIL->config->get('message_show_email');
  1195. if ($addicon && !isset($_SESSION['writeable_abook'])) {
  1196. $_SESSION['writeable_abook'] = $RCMAIL->get_address_sources(true) ? true : false;
  1197. }
  1198. foreach ($a_parts as $part) {
  1199. $j++;
  1200. $name = $part['name'];
  1201. $mailto = $part['mailto'];
  1202. $string = $part['string'];
  1203. $valid = check_email($mailto, false);
  1204. // phishing email prevention (#1488981), e.g. "valid@email.addr <phishing@email.addr>"
  1205. if (!$show_email && $valid && $name && $name != $mailto && strpos($name, '@')) {
  1206. $name = '';
  1207. }
  1208. // IDNA ASCII to Unicode
  1209. if ($name == $mailto)
  1210. $name = rcube_idn_to_utf8($name);
  1211. if ($string == $mailto)
  1212. $string = rcube_idn_to_utf8($string);
  1213. $mailto = rcube_idn_to_utf8($mailto);
  1214. if ($PRINT_MODE) {
  1215. $out .= ($out ? ', ' : '') . sprintf('%s &lt;%s&gt;', Q($name), $mailto);
  1216. // for printing we display all addresses
  1217. continue;
  1218. }
  1219. else if ($valid) {
  1220. if ($linked) {
  1221. $attrs = array(
  1222. 'href' => 'mailto:' . $mailto,
  1223. 'onclick' => sprintf("return %s.command('compose','%s',this)", JS_OBJECT_NAME, JQ($mailto)),
  1224. 'class' => "rcmContactAddress",
  1225. );
  1226. if ($show_email && $name && $mailto) {
  1227. $content = Q($name ? sprintf('%s <%s>', $name, $mailto) : $mailto);
  1228. }
  1229. else {
  1230. $content = Q($name ? $name : $mailto);
  1231. $attrs['title'] = $mailto;
  1232. }
  1233. $address = html::a($attrs, $content);
  1234. }
  1235. else {
  1236. $address = html::span(array('title' => $mailto, 'class' => "rcmContactAddress"),
  1237. Q($name ? $name : $mailto));
  1238. }
  1239. if ($addicon && $_SESSION['writeable_abook']) {
  1240. $address .= html::a(array(
  1241. 'href' => "#add",
  1242. 'onclick' => sprintf("return %s.command('add-contact','%s',this)", JS_OBJECT_NAME, JQ($string)),
  1243. 'title' => rcube_label('addtoaddressbook'),
  1244. 'class' => 'rcmaddcontact',
  1245. ),
  1246. html::img(array(
  1247. 'src' => $CONFIG['skin_path'] . $addicon,
  1248. 'alt' => "Add contact",
  1249. )));
  1250. }
  1251. }
  1252. else {
  1253. $address = '';
  1254. if ($name)
  1255. $address .= Q($name);
  1256. if ($mailto)
  1257. $address = trim($address . ' ' . Q($name ? sprintf('<%s>', $mailto) : $mailto)

Large files files are truncated, but you can click here to view the full file