PageRenderTime 611ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 1ms

/program/steps/mail/func.inc

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

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