You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

sendmail.inc 32KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951
  1. <?php
  2. /**
  3. +-----------------------------------------------------------------------+
  4. | program/steps/mail/sendmail.inc |
  5. | |
  6. | This file is part of the Roundcube Webmail client |
  7. | Copyright (C) 2005-2013, 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. | Compose a new mail message with all headers and attachments |
  15. | and send it using the PEAR::Net_SMTP class or with PHP mail() |
  16. | |
  17. +-----------------------------------------------------------------------+
  18. | Author: Thomas Bruederli <roundcube@gmail.com> |
  19. +-----------------------------------------------------------------------+
  20. */
  21. // remove all scripts and act as called in frame
  22. $OUTPUT->reset();
  23. $OUTPUT->framed = TRUE;
  24. $saveonly = !empty($_GET['_saveonly']);
  25. $savedraft = !empty($_POST['_draft']) && !$saveonly;
  26. $sendmail_delay = (int) $RCMAIL->config->get('sendmail_delay');
  27. $drafts_mbox = $RCMAIL->config->get('drafts_mbox');
  28. $COMPOSE_ID = rcube_utils::get_input_value('_id', rcube_utils::INPUT_GPC);
  29. $COMPOSE =& $_SESSION['compose_data_'.$COMPOSE_ID];
  30. /****** checks ********/
  31. if (!isset($COMPOSE['id'])) {
  32. rcube::raise_error(array('code' => 500, 'type' => 'php',
  33. 'file' => __FILE__, 'line' => __LINE__,
  34. 'message' => "Invalid compose ID"), true, false);
  35. $OUTPUT->show_message('internalerror', 'error');
  36. $OUTPUT->send('iframe');
  37. }
  38. if (!$savedraft) {
  39. if (empty($_POST['_to']) && empty($_POST['_cc']) && empty($_POST['_bcc'])
  40. && empty($_POST['_subject']) && $_POST['_message']
  41. ) {
  42. $OUTPUT->show_message('sendingfailed', 'error');
  43. $OUTPUT->send('iframe');
  44. }
  45. if ($sendmail_delay) {
  46. $wait_sec = time() - $sendmail_delay - intval($RCMAIL->config->get('last_message_time'));
  47. if ($wait_sec < 0) {
  48. $OUTPUT->show_message('senttooquickly', 'error', array('sec' => $wait_sec * -1));
  49. $OUTPUT->send('iframe');
  50. }
  51. }
  52. }
  53. /****** compose message ********/
  54. // set default charset
  55. $message_charset = isset($_POST['_charset']) ? $_POST['_charset'] : $OUTPUT->get_charset();
  56. $EMAIL_FORMAT_ERROR = NULL;
  57. $RECIPIENT_COUNT = 0;
  58. $mailto = rcmail_email_input_format(rcube_utils::get_input_value('_to', rcube_utils::INPUT_POST, TRUE, $message_charset), true);
  59. $mailcc = rcmail_email_input_format(rcube_utils::get_input_value('_cc', rcube_utils::INPUT_POST, TRUE, $message_charset), true);
  60. $mailbcc = rcmail_email_input_format(rcube_utils::get_input_value('_bcc', rcube_utils::INPUT_POST, TRUE, $message_charset), true);
  61. if ($EMAIL_FORMAT_ERROR && !$savedraft) {
  62. $OUTPUT->show_message('emailformaterror', 'error', array('email' => $EMAIL_FORMAT_ERROR));
  63. $OUTPUT->send('iframe');
  64. }
  65. if (empty($mailto) && !empty($mailcc)) {
  66. $mailto = $mailcc;
  67. $mailcc = null;
  68. }
  69. else if (empty($mailto)) {
  70. $mailto = 'undisclosed-recipients:;';
  71. }
  72. // Get sender name and address...
  73. $from = rcube_utils::get_input_value('_from', rcube_utils::INPUT_POST, true, $message_charset);
  74. // ... from identity...
  75. if (is_numeric($from)) {
  76. if (is_array($identity_arr = rcmail_get_identity($from))) {
  77. if ($identity_arr['mailto'])
  78. $from = $identity_arr['mailto'];
  79. if ($identity_arr['string'])
  80. $from_string = $identity_arr['string'];
  81. }
  82. else {
  83. $from = null;
  84. }
  85. }
  86. // ... if there is no identity record, this might be a custom from
  87. else if ($from_string = rcmail_email_input_format($from)) {
  88. if (preg_match('/(\S+@\S+)/', $from_string, $m))
  89. $from = trim($m[1], '<>');
  90. else
  91. $from = null;
  92. }
  93. // check 'From' address (identity may be incomplete)
  94. if (!$savedraft && !$saveonly && empty($from)) {
  95. $OUTPUT->show_message('nofromaddress', 'error');
  96. $OUTPUT->send('iframe');
  97. }
  98. if (!$from_string && $from) {
  99. $from_string = $from;
  100. }
  101. if (empty($COMPOSE['param']['message-id'])) {
  102. $COMPOSE['param']['message-id'] = $RCMAIL->gen_message_id($from);
  103. }
  104. $message_id = $COMPOSE['param']['message-id'];
  105. // compose headers array
  106. $headers = array();
  107. // if configured, the Received headers goes to top, for good measure
  108. if ($RCMAIL->config->get('http_received_header')) {
  109. $nldlm = "\r\n\t";
  110. $http_header = 'from ';
  111. // FROM/VIA
  112. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  113. $hosts = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'], 2);
  114. $http_header .= rcmail_received_host($hosts[0]) . $nldlm . ' via ';
  115. }
  116. $http_header .= rcmail_received_host($_SERVER['REMOTE_ADDR']);
  117. // BY
  118. $http_header .= $nldlm . 'by ' . $_SERVER['HTTP_HOST'];
  119. // WITH
  120. $http_header .= $nldlm . 'with HTTP (' . $_SERVER['SERVER_PROTOCOL']
  121. . ' ' . $_SERVER['REQUEST_METHOD'] . '); ' . date('r');
  122. $headers['Received'] = wordwrap($http_header, 69, $nldlm);
  123. }
  124. $headers['Date'] = $RCMAIL->user_date();
  125. $headers['From'] = rcube_charset::convert($from_string, RCUBE_CHARSET, $message_charset);
  126. $headers['To'] = $mailto;
  127. // additional recipients
  128. if (!empty($mailcc)) {
  129. $headers['Cc'] = $mailcc;
  130. }
  131. if (!empty($mailbcc)) {
  132. $headers['Bcc'] = $mailbcc;
  133. }
  134. if (($max_recipients = (int) $RCMAIL->config->get('max_recipients')) > 0) {
  135. if ($RECIPIENT_COUNT > $max_recipients) {
  136. $OUTPUT->show_message('toomanyrecipients', 'error', array('max' => $max_recipients));
  137. $OUTPUT->send('iframe');
  138. }
  139. }
  140. $dont_override = (array) $RCMAIL->config->get('dont_override');
  141. $mdn_enabled = in_array('mdn_default', $dont_override) ? $RCMAIL->config->get('mdn_default') : !empty($_POST['_mdn']);
  142. $dsn_enabled = in_array('dsn_default', $dont_override) ? $RCMAIL->config->get('dsn_default') : !empty($_POST['_dsn']);
  143. // add subject
  144. $headers['Subject'] = trim(rcube_utils::get_input_value('_subject', rcube_utils::INPUT_POST, TRUE, $message_charset));
  145. if (!empty($identity_arr['organization'])) {
  146. $headers['Organization'] = $identity_arr['organization'];
  147. }
  148. if ($hdr = rcube_utils::get_input_value('_replyto', rcube_utils::INPUT_POST, TRUE, $message_charset)) {
  149. $headers['Reply-To'] = rcmail_email_input_format($hdr);
  150. }
  151. if (!empty($headers['Reply-To'])) {
  152. $headers['Mail-Reply-To'] = $headers['Reply-To'];
  153. }
  154. if ($hdr = rcube_utils::get_input_value('_followupto', rcube_utils::INPUT_POST, TRUE, $message_charset)) {
  155. $headers['Mail-Followup-To'] = rcmail_email_input_format($hdr);
  156. }
  157. // remember reply/forward UIDs in special headers
  158. if (!empty($COMPOSE['reply_uid']) && $savedraft) {
  159. $headers['X-Draft-Info'] = array('type' => 'reply', 'uid' => $COMPOSE['reply_uid']);
  160. }
  161. else if (!empty($COMPOSE['forward_uid']) && $savedraft) {
  162. $headers['X-Draft-Info'] = array('type' => 'forward', 'uid' => rcube_imap_generic::compressMessageSet($COMPOSE['forward_uid']));
  163. }
  164. if (!empty($COMPOSE['reply_msgid'])) {
  165. $headers['In-Reply-To'] = $COMPOSE['reply_msgid'];
  166. }
  167. if (!empty($COMPOSE['references'])) {
  168. $headers['References'] = $COMPOSE['references'];
  169. }
  170. if (!empty($_POST['_priority'])) {
  171. $priority = intval($_POST['_priority']);
  172. $a_priorities = array(1 => 'highest', 2 => 'high', 4 => 'low', 5 => 'lowest');
  173. if ($str_priority = $a_priorities[$priority]) {
  174. $headers['X-Priority'] = sprintf("%d (%s)", $priority, ucfirst($str_priority));
  175. }
  176. }
  177. if ($mdn_enabled) {
  178. $headers['Return-Receipt-To'] = $from_string;
  179. $headers['Disposition-Notification-To'] = $from_string;
  180. }
  181. // additional headers
  182. $headers['Message-ID'] = $message_id;
  183. $headers['X-Sender'] = $from;
  184. if (is_array($headers['X-Draft-Info'])) {
  185. $headers['X-Draft-Info'] = rcmail_draftinfo_encode($headers['X-Draft-Info'] + array('folder' => $COMPOSE['mailbox']));
  186. }
  187. if ($hdr = $RCMAIL->config->get('useragent')) {
  188. $headers['User-Agent'] = $hdr;
  189. }
  190. // exec hook for header checking and manipulation
  191. // Depracated: use message_before_send hook instead
  192. $data = $RCMAIL->plugins->exec_hook('message_outgoing_headers', array('headers' => $headers));
  193. // sending aborted by plugin
  194. if ($data['abort'] && !$savedraft) {
  195. $OUTPUT->show_message($data['message'] ?: 'sendingfailed');
  196. $OUTPUT->send('iframe');
  197. }
  198. else {
  199. $headers = $data['headers'];
  200. }
  201. $isHtml = (bool) rcube_utils::get_input_value('_is_html', rcube_utils::INPUT_POST);
  202. // fetch message body
  203. $message_body = rcube_utils::get_input_value('_message', rcube_utils::INPUT_POST, TRUE, $message_charset);
  204. if (isset($_POST['_pgpmime'])) {
  205. $pgp_mime = rcube_utils::get_input_value('_pgpmime', rcube_utils::INPUT_POST);
  206. $isHtml = false;
  207. $message_body = '';
  208. // clear unencrypted attachments
  209. foreach ((array) $COMPOSE['attachments'] as $attach) {
  210. $RCMAIL->plugins->exec_hook('attachment_delete', $attach);
  211. }
  212. $COMPOSE['attachments'] = array();
  213. }
  214. if ($isHtml) {
  215. $bstyle = array();
  216. if ($font_size = $RCMAIL->config->get('default_font_size')) {
  217. $bstyle[] = 'font-size: ' . $font_size;
  218. }
  219. if ($font_family = $RCMAIL->config->get('default_font')) {
  220. $bstyle[] = 'font-family: ' . rcmail::font_defs($font_family);
  221. }
  222. // append doctype and html/body wrappers
  223. $bstyle = !empty($bstyle) ? (" style='" . implode($bstyle, '; ') . "'") : '';
  224. $message_body = '<html><head>'
  225. . '<meta http-equiv="Content-Type" content="text/html; charset=' . $message_charset . '" /></head>'
  226. . "<body" . $bstyle . ">\r\n" . $message_body;
  227. }
  228. if (!$savedraft) {
  229. if ($isHtml) {
  230. $b_style = 'padding: 0 0.4em; border-left: #1010ff 2px solid; margin: 0';
  231. $pre_style = 'margin: 0; padding: 0; font-family: monospace';
  232. $message_body = preg_replace(
  233. array(
  234. // remove empty signature div
  235. '/<div id="_rc_sig">(&nbsp;)?<\/div>[\s\r\n]*$/',
  236. // remove signature's div ID
  237. '/\s*id="_rc_sig"/',
  238. // add inline css for blockquotes and container
  239. '/<blockquote>/',
  240. '/<div class="pre">/',
  241. // convert TinyMCE's new-line sequences (#1490463)
  242. '/<p>&nbsp;<\/p>/',
  243. ),
  244. array(
  245. '',
  246. '',
  247. '<blockquote type="cite" style="'.$b_style.'">',
  248. '<div class="pre" style="'.$pre_style.'">',
  249. '<p><br /></p>',
  250. ),
  251. $message_body);
  252. }
  253. // Check spelling before send
  254. if ($RCMAIL->config->get('spellcheck_before_send') && $RCMAIL->config->get('enable_spellcheck')
  255. && empty($COMPOSE['spell_checked']) && !empty($message_body)
  256. ) {
  257. $message_body = str_replace("\r\n", "\n", $message_body);
  258. $spellchecker = new rcube_spellchecker(rcube_utils::get_input_value('_lang', rcube_utils::INPUT_GPC));
  259. $spell_result = $spellchecker->check($message_body, $isHtml);
  260. $COMPOSE['spell_checked'] = true;
  261. if (!$spell_result) {
  262. if ($isHtml) {
  263. $result['words'] = $spellchecker->get();
  264. $result['dictionary'] = (bool) $RCMAIL->config->get('spellcheck_dictionary');
  265. }
  266. else {
  267. $result = $spellchecker->get_xml();
  268. }
  269. $OUTPUT->show_message('mispellingsfound', 'error');
  270. $OUTPUT->command('spellcheck_resume', $result);
  271. $OUTPUT->send('iframe');
  272. }
  273. }
  274. // generic footer for all messages
  275. if ($footer = rcmail_generic_message_footer($isHtml)) {
  276. $footer = rcube_charset::convert($footer, RCUBE_CHARSET, $message_charset);
  277. $message_body .= "\r\n" . $footer;
  278. }
  279. }
  280. if ($isHtml) {
  281. $message_body .= "\r\n</body></html>\r\n";
  282. }
  283. // sort attachments to make sure the order is the same as in the UI (#1488423)
  284. if ($files = rcube_utils::get_input_value('_attachments', rcube_utils::INPUT_POST)) {
  285. $files = explode(',', $files);
  286. $files = array_flip($files);
  287. foreach ($files as $idx => $val) {
  288. $files[$idx] = $COMPOSE['attachments'][$idx];
  289. unset($COMPOSE['attachments'][$idx]);
  290. }
  291. $COMPOSE['attachments'] = array_merge(array_filter($files), $COMPOSE['attachments']);
  292. }
  293. // set line length for body wrapping
  294. $LINE_LENGTH = $RCMAIL->config->get('line_length', 72);
  295. // Since we can handle big messages with disk usage, we need more time to work
  296. @set_time_limit(0);
  297. // create PEAR::Mail_mime instance
  298. $MAIL_MIME = new Mail_mime("\r\n");
  299. // Check if we have enough memory to handle the message in it
  300. // It's faster than using files, so we'll do this if we only can
  301. if (is_array($COMPOSE['attachments']) && $RCMAIL->config->get('smtp_server')
  302. && ($mem_limit = parse_bytes(ini_get('memory_limit')))
  303. ) {
  304. $memory = 0;
  305. foreach ($COMPOSE['attachments'] as $id => $attachment) {
  306. $memory += $attachment['size'];
  307. }
  308. // Yeah, Net_SMTP needs up to 12x more memory, 1.33 is for base64
  309. if (!rcube_utils::mem_check($memory * 1.33 * 12)) {
  310. $MAIL_MIME->setParam('delay_file_io', true);
  311. }
  312. }
  313. // For HTML-formatted messages, construct the MIME message with both
  314. // the HTML part and the plain-text part
  315. if ($isHtml) {
  316. $plugin = $RCMAIL->plugins->exec_hook('message_outgoing_body',
  317. array('body' => $message_body, 'type' => 'html', 'message' => $MAIL_MIME));
  318. $MAIL_MIME->setHTMLBody($plugin['body']);
  319. $plainTextPart = $RCMAIL->html2text($plugin['body'], array('width' => 0, 'charset' => $message_charset));
  320. $plainTextPart = rcube_mime::wordwrap($plainTextPart, $LINE_LENGTH, "\r\n", false, $message_charset);
  321. $plainTextPart = wordwrap($plainTextPart, 998, "\r\n", true);
  322. // There's no sense to use multipart/alternative if the text/plain
  323. // part would be blank. Completely blank text/plain part may confuse
  324. // some mail clients (#5283)
  325. if (strlen(trim($plainTextPart)) > 0) {
  326. // make sure all line endings are CRLF (#1486712)
  327. $plainTextPart = preg_replace('/\r?\n/', "\r\n", $plainTextPart);
  328. $plugin = $RCMAIL->plugins->exec_hook('message_outgoing_body',
  329. array('body' => $plainTextPart, 'type' => 'alternative', 'message' => $MAIL_MIME));
  330. // add a plain text version of the e-mail as an alternative part.
  331. $MAIL_MIME->setTXTBody($plugin['body']);
  332. }
  333. // Extract image Data URIs into message attachments (#1488502)
  334. rcmail_extract_inline_images($MAIL_MIME, $from);
  335. }
  336. else {
  337. $plugin = $RCMAIL->plugins->exec_hook('message_outgoing_body',
  338. array('body' => $message_body, 'type' => 'plain', 'message' => $MAIL_MIME));
  339. $message_body = $plugin['body'];
  340. // compose format=flowed content if enabled
  341. if ($flowed = ($savedraft || $RCMAIL->config->get('send_format_flowed', true)))
  342. $message_body = rcube_mime::format_flowed($message_body, min($LINE_LENGTH+2, 79), $message_charset);
  343. else
  344. $message_body = rcube_mime::wordwrap($message_body, $LINE_LENGTH, "\r\n", false, $message_charset);
  345. $message_body = wordwrap($message_body, 998, "\r\n", true);
  346. $MAIL_MIME->setTXTBody($message_body, false, true);
  347. }
  348. // add stored attachments, if any
  349. if (is_array($COMPOSE['attachments'])) {
  350. foreach ($COMPOSE['attachments'] as $id => $attachment) {
  351. // This hook retrieves the attachment contents from the file storage backend
  352. $attachment = $RCMAIL->plugins->exec_hook('attachment_get', $attachment);
  353. if ($isHtml) {
  354. $dispurl = '/[\'"]\S+display-attachment\S+file=rcmfile' . preg_quote($attachment['id']) . '[\'"]/';
  355. $message_body = $MAIL_MIME->getHTMLBody();
  356. $is_inline = preg_match($dispurl, $message_body);
  357. }
  358. else {
  359. $is_inline = false;
  360. }
  361. // inline image
  362. if ($is_inline) {
  363. // Mail_Mime does not support many inline attachments with the same name (#1489406)
  364. // we'll generate cid: urls here to workaround this
  365. $cid = preg_replace('/[^0-9a-zA-Z]/', '', uniqid(time(), true));
  366. if (preg_match('#(@[0-9a-zA-Z\-\.]+)#', $from, $matches)) {
  367. $cid .= $matches[1];
  368. }
  369. else {
  370. $cid .= '@localhost';
  371. }
  372. $message_body = preg_replace($dispurl, '"cid:' . $cid . '"', $message_body);
  373. $MAIL_MIME->setHTMLBody($message_body);
  374. if ($attachment['data'])
  375. $MAIL_MIME->addHTMLImage($attachment['data'], $attachment['mimetype'], $attachment['name'], false, $cid);
  376. else
  377. $MAIL_MIME->addHTMLImage($attachment['path'], $attachment['mimetype'], $attachment['name'], true, $cid);
  378. }
  379. else {
  380. $ctype = str_replace('image/pjpeg', 'image/jpeg', $attachment['mimetype']); // #1484914
  381. $file = $attachment['data'] ?: $attachment['path'];
  382. $folding = (int) $RCMAIL->config->get('mime_param_folding');
  383. $MAIL_MIME->addAttachment($file,
  384. $ctype,
  385. $attachment['name'],
  386. $attachment['data'] ? false : true,
  387. $ctype == 'message/rfc822' ? '8bit' : 'base64',
  388. 'attachment',
  389. $attachment['charset'],
  390. '', '',
  391. $folding ? 'quoted-printable' : NULL,
  392. $folding == 2 ? 'quoted-printable' : NULL,
  393. '', RCUBE_CHARSET
  394. );
  395. }
  396. }
  397. }
  398. // choose transfer encoding for plain/text body
  399. if (preg_match('/[^\x00-\x7F]/', $MAIL_MIME->getTXTBody())) {
  400. $text_charset = $message_charset;
  401. $transfer_encoding = $RCMAIL->config->get('force_7bit') ? 'quoted-printable' : '8bit';
  402. }
  403. else {
  404. $text_charset = 'US-ASCII';
  405. $transfer_encoding = '7bit';
  406. }
  407. if ($flowed) {
  408. $text_charset .= ";\r\n format=flowed";
  409. }
  410. // compose PGP/Mime message
  411. if ($pgp_mime) {
  412. $MAIL_MIME->addAttachment(new Mail_mimePart('Version: 1', array(
  413. 'content_type' => 'application/pgp-encrypted',
  414. 'description' => 'PGP/MIME version identification',
  415. )));
  416. $MAIL_MIME->addAttachment(new Mail_mimePart($pgp_mime, array(
  417. 'content_type' => 'application/octet-stream',
  418. 'filename' => 'encrypted.asc',
  419. 'disposition' => 'inline',
  420. )));
  421. $MAIL_MIME->setContentType('multipart/encrypted', array('protocol' => 'application/pgp-encrypted'));
  422. $MAIL_MIME->setParam('preamble', 'This is an OpenPGP/MIME encrypted message (RFC 2440 and 3156)');
  423. }
  424. // encoding settings for mail composing
  425. $MAIL_MIME->setParam('text_encoding', $transfer_encoding);
  426. $MAIL_MIME->setParam('html_encoding', 'quoted-printable');
  427. $MAIL_MIME->setParam('head_encoding', 'quoted-printable');
  428. $MAIL_MIME->setParam('head_charset', $message_charset);
  429. $MAIL_MIME->setParam('html_charset', $message_charset);
  430. $MAIL_MIME->setParam('text_charset', $text_charset);
  431. // pass headers to message object
  432. $MAIL_MIME->headers($headers);
  433. // This hook allows to modify the message before send or save action
  434. $plugin = $RCMAIL->plugins->exec_hook('message_ready', array('message' => $MAIL_MIME));
  435. $MAIL_MIME = $plugin['message'];
  436. // Begin SMTP Delivery Block
  437. if (!$savedraft && !$saveonly) {
  438. // Handle Delivery Status Notification request
  439. $smtp_opts['dsn'] = $dsn_enabled;
  440. $sent = $RCMAIL->deliver_message($MAIL_MIME, $from, $mailto,
  441. $smtp_error, $mailbody_file, $smtp_opts);
  442. // return to compose page if sending failed
  443. if (!$sent) {
  444. // remove temp file
  445. if ($mailbody_file) {
  446. unlink($mailbody_file);
  447. }
  448. if ($smtp_error && is_string($smtp_error)) {
  449. $OUTPUT->show_message($smtp_error, 'error');
  450. }
  451. else if ($smtp_error && !empty($smtp_error['label'])) {
  452. $OUTPUT->show_message($smtp_error['label'], 'error', $smtp_error['vars']);
  453. }
  454. else {
  455. $OUTPUT->show_message('sendingfailed', 'error');
  456. }
  457. $OUTPUT->send('iframe');
  458. }
  459. // save message sent time
  460. if ($sendmail_delay) {
  461. $RCMAIL->user->save_prefs(array('last_message_time' => time()));
  462. }
  463. // set replied/forwarded flag
  464. if ($COMPOSE['reply_uid']) {
  465. foreach (rcmail::get_uids($COMPOSE['reply_uid'], $COMPOSE['mailbox']) as $mbox => $uids) {
  466. $RCMAIL->storage->set_flag($uids, 'ANSWERED', $mbox);
  467. }
  468. }
  469. else if ($COMPOSE['forward_uid']) {
  470. foreach (rcmail::get_uids($COMPOSE['forward_uid'], $COMPOSE['mailbox']) as $mbox => $uids) {
  471. $RCMAIL->storage->set_flag($uids, 'FORWARDED', $mbox);
  472. }
  473. }
  474. }
  475. // Determine which folder to save message
  476. if ($savedraft) {
  477. $store_target = $drafts_mbox;
  478. }
  479. else if (!$RCMAIL->config->get('no_save_sent_messages')) {
  480. if (isset($_POST['_store_target'])) {
  481. $store_target = rcube_utils::get_input_value('_store_target', rcube_utils::INPUT_POST);
  482. }
  483. else {
  484. $store_target = $RCMAIL->config->get('sent_mbox');
  485. }
  486. }
  487. if ($store_target) {
  488. // check if folder is subscribed
  489. if ($RCMAIL->storage->folder_exists($store_target, true)) {
  490. $store_folder = true;
  491. }
  492. // folder may be existing but not subscribed (#1485241)
  493. else if (!$RCMAIL->storage->folder_exists($store_target)) {
  494. $store_folder = $RCMAIL->storage->create_folder($store_target, true);
  495. }
  496. else if ($RCMAIL->storage->subscribe($store_target)) {
  497. $store_folder = true;
  498. }
  499. // append message to sent box
  500. if ($store_folder) {
  501. // message body in file
  502. if ($mailbody_file || $MAIL_MIME->getParam('delay_file_io')) {
  503. $headers = $MAIL_MIME->txtHeaders();
  504. // file already created
  505. if ($mailbody_file) {
  506. $msg = $mailbody_file;
  507. }
  508. else {
  509. $temp_dir = $RCMAIL->config->get('temp_dir');
  510. $mailbody_file = tempnam($temp_dir, 'rcmMsg');
  511. $msg = $MAIL_MIME->saveMessageBody($mailbody_file);
  512. if (!is_a($msg, 'PEAR_Error')) {
  513. $msg = $mailbody_file;
  514. }
  515. }
  516. }
  517. else {
  518. $msg = $MAIL_MIME->getMessage();
  519. $headers = '';
  520. }
  521. if (is_a($msg, 'PEAR_Error')) {
  522. rcube::raise_error(array('code' => 650, 'type' => 'php',
  523. 'file' => __FILE__, 'line' => __LINE__,
  524. 'message' => "Could not create message: ".$msg->getMessage()),
  525. true, false);
  526. }
  527. else {
  528. $saved = $RCMAIL->storage->save_message($store_target, $msg, $headers,
  529. $mailbody_file ? true : false, array('SEEN'));
  530. }
  531. if ($mailbody_file) {
  532. unlink($mailbody_file);
  533. $mailbody_file = null;
  534. }
  535. }
  536. // raise error if saving failed
  537. if (!$saved) {
  538. rcube::raise_error(array('code' => 800, 'type' => 'imap',
  539. 'file' => __FILE__, 'line' => __LINE__,
  540. 'message' => "Could not save message in $store_target"), true, false);
  541. if ($savedraft) {
  542. $RCMAIL->display_server_error('errorsaving');
  543. // start the auto-save timer again
  544. $OUTPUT->command('auto_save_start');
  545. $OUTPUT->send('iframe');
  546. }
  547. }
  548. }
  549. // remove temp file
  550. else if ($mailbody_file) {
  551. unlink($mailbody_file);
  552. }
  553. // delete previous saved draft
  554. $old_id = rcube_utils::get_input_value('_draft_saveid', rcube_utils::INPUT_POST);
  555. if ($old_id && ($sent || $saved)) {
  556. $deleted = $RCMAIL->storage->delete_message($old_id, $drafts_mbox);
  557. // raise error if deletion of old draft failed
  558. if (!$deleted) {
  559. rcube::raise_error(array('code' => 800, 'type' => 'imap',
  560. 'file' => __FILE__, 'line' => __LINE__,
  561. 'message' => "Could not delete message from $drafts_mbox"), true, false);
  562. }
  563. }
  564. if ($savedraft) {
  565. // remember new draft-uid ($saved could be an UID or true/false here)
  566. if ($saved && is_bool($saved)) {
  567. $index = $RCMAIL->storage->search_once($drafts_mbox, 'HEADER Message-ID ' . $message_id);
  568. $saved = @max($index->get());
  569. }
  570. if ($saved) {
  571. $plugin = $RCMAIL->plugins->exec_hook('message_draftsaved',
  572. array('msgid' => $message_id, 'uid' => $saved, 'folder' => $store_target));
  573. // display success
  574. $OUTPUT->show_message($plugin['message'] ?: 'messagesaved', 'confirmation');
  575. // update "_draft_saveid" and the "cmp_hash" to prevent "Unsaved changes" warning
  576. $COMPOSE['param']['draft_uid'] = $plugin['uid'];
  577. $OUTPUT->command('set_draft_id', $plugin['uid']);
  578. $OUTPUT->command('compose_field_hash', true);
  579. }
  580. // start the auto-save timer again
  581. $OUTPUT->command('auto_save_start');
  582. }
  583. else {
  584. // Collect folders which could contain the composed message,
  585. // we'll refresh the list if currently opened folder is one of them (#1490238)
  586. $folders = array();
  587. if (!$saveonly) {
  588. if (in_array($COMPOSE['mode'], array('reply', 'forward', 'draft'))) {
  589. $folders[] = $COMPOSE['mailbox'];
  590. }
  591. if (!empty($COMPOSE['param']['draft_uid']) && $drafts_mbox) {
  592. $folders[] = $drafts_mbox;
  593. }
  594. }
  595. if ($store_folder && !$saved) {
  596. $params = $saveonly ? null : array('prefix' => true);
  597. $RCMAIL->display_server_error('errorsavingsent', null, null, $params);
  598. if ($saveonly) {
  599. $OUTPUT->send('iframe');
  600. }
  601. $save_error = true;
  602. }
  603. else {
  604. rcmail_compose_cleanup($COMPOSE_ID);
  605. $OUTPUT->command('remove_compose_data', $COMPOSE_ID);
  606. if ($store_folder) {
  607. $folders[] = $store_target;
  608. }
  609. }
  610. $msg = $RCMAIL->gettext($saveonly ? 'successfullysaved' : 'messagesent');
  611. $OUTPUT->command('sent_successfully', 'confirmation', $msg, $folders, $save_error);
  612. }
  613. $OUTPUT->send('iframe');
  614. /****** message sending functions ********/
  615. function rcmail_received_host($host)
  616. {
  617. $hostname = gethostbyaddr($host);
  618. $result = rcmail_encrypt_host($hostname);
  619. if ($host != $hostname) {
  620. $result .= ' (' . rcmail_encrypt_host($host) . ')';
  621. }
  622. return $result;
  623. }
  624. // encrypt host IP or hostname for Received header
  625. function rcmail_encrypt_host($host)
  626. {
  627. global $RCMAIL;
  628. if ($RCMAIL->config->get('http_received_header_encrypt')) {
  629. return $RCMAIL->encrypt($host);
  630. }
  631. if (!preg_match('/[^0-9:.]/', $host)) {
  632. return "[$host]";
  633. }
  634. return $host;
  635. }
  636. // get identity record
  637. function rcmail_get_identity($id)
  638. {
  639. global $RCMAIL, $message_charset;
  640. if ($sql_arr = $RCMAIL->user->get_identity($id)) {
  641. $out = $sql_arr;
  642. if ($message_charset != RCUBE_CHARSET) {
  643. foreach ($out as $k => $v) {
  644. $out[$k] = rcube_charset::convert($v, RCUBE_CHARSET, $message_charset);
  645. }
  646. }
  647. $out['mailto'] = $sql_arr['email'];
  648. $out['string'] = format_email_recipient($sql_arr['email'], $sql_arr['name']);
  649. return $out;
  650. }
  651. return false;
  652. }
  653. /**
  654. * Extract image attachments from HTML content (data URIs)
  655. */
  656. function rcmail_extract_inline_images($mime_message, $from)
  657. {
  658. $body = $mime_message->getHTMLBody();
  659. $offset = 0;
  660. $list = array();
  661. $domain = 'localhost';
  662. $regexp = '#img[^>]+src=[\'"](data:([^;]*);base64,([a-z0-9+/=\r\n]+))([\'"])#i';
  663. if (preg_match_all($regexp, $body, $matches, PREG_OFFSET_CAPTURE)) {
  664. // get domain for the Content-ID, must be the same as in Mail_Mime::get()
  665. if (preg_match('#@([0-9a-zA-Z\-\.]+)#', $from, $m)) {
  666. $domain = $m[1];
  667. }
  668. foreach ($matches[1] as $idx => $m) {
  669. $data = preg_replace('/\r\n/', '', $matches[3][$idx][0]);
  670. $data = base64_decode($data);
  671. if (empty($data)) {
  672. continue;
  673. }
  674. $hash = md5($data) . '@' . $domain;
  675. $mime_type = $matches[2][$idx][0];
  676. $name = $list[$hash];
  677. if (empty($mime_type)) {
  678. $mime_type = rcube_mime::image_content_type($data);
  679. }
  680. // add the image to the MIME message
  681. if (!$name) {
  682. $ext = preg_replace('#^[^/]+/#', '', $mime_type);
  683. $name = substr($hash, 0, 8) . '.' . $ext;
  684. $list[$hash] = $name;
  685. $mime_message->addHTMLImage($data, $mime_type, $name, false, $hash);
  686. }
  687. $body = substr_replace($body, $name, $m[1] + $offset, strlen($m[0]));
  688. $offset += strlen($name) - strlen($m[0]);
  689. }
  690. }
  691. $mime_message->setHTMLBody($body);
  692. }
  693. /**
  694. * Parse and cleanup email address input (and count addresses)
  695. *
  696. * @param string Address input
  697. * @param boolean Do count recipients (saved in global $RECIPIENT_COUNT)
  698. * @param boolean Validate addresses (errors saved in global $EMAIL_FORMAT_ERROR)
  699. * @return string Canonical recipients string separated by comma
  700. */
  701. function rcmail_email_input_format($mailto, $count=false, $check=true)
  702. {
  703. global $RCMAIL, $EMAIL_FORMAT_ERROR, $RECIPIENT_COUNT;
  704. // simplified email regexp, supporting quoted local part
  705. $email_regexp = '(\S+|("[^"]+"))@\S+';
  706. $delim = trim($RCMAIL->config->get('recipients_separator', ','));
  707. $regexp = array("/[,;$delim]\s*[\r\n]+/", '/[\r\n]+/', "/[,;$delim]\s*\$/m", '/;/', '/(\S{1})(<'.$email_regexp.'>)/U');
  708. $replace = array($delim.' ', ', ', '', $delim, '\\1 \\2');
  709. // replace new lines and strip ending ', ', make address input more valid
  710. $mailto = trim(preg_replace($regexp, $replace, $mailto));
  711. $items = rcube_utils::explode_quoted_string($delim, $mailto);
  712. $result = array();
  713. foreach ($items as $item) {
  714. $item = trim($item);
  715. // address in brackets without name (do nothing)
  716. if (preg_match('/^<'.$email_regexp.'>$/', $item)) {
  717. $item = rcube_utils::idn_to_ascii(trim($item, '<>'));
  718. $result[] = $item;
  719. }
  720. // address without brackets and without name (add brackets)
  721. else if (preg_match('/^'.$email_regexp.'$/', $item)) {
  722. $item = rcube_utils::idn_to_ascii($item);
  723. $result[] = $item;
  724. }
  725. // address with name (handle name)
  726. else if (preg_match('/<*'.$email_regexp.'>*$/', $item, $matches)) {
  727. $address = $matches[0];
  728. $name = trim(str_replace($address, '', $item));
  729. if ($name[0] == '"' && $name[count($name)-1] == '"') {
  730. $name = substr($name, 1, -1);
  731. }
  732. $name = stripcslashes($name);
  733. $address = rcube_utils::idn_to_ascii(trim($address, '<>'));
  734. $result[] = format_email_recipient($address, $name);
  735. $item = $address;
  736. }
  737. else if (trim($item)) {
  738. continue;
  739. }
  740. // check address format
  741. $item = trim($item, '<>');
  742. if ($item && $check && !rcube_utils::check_email($item)) {
  743. $EMAIL_FORMAT_ERROR = $item;
  744. return;
  745. }
  746. }
  747. if ($count) {
  748. $RECIPIENT_COUNT += count($result);
  749. }
  750. return implode(', ', $result);
  751. }
  752. function rcmail_generic_message_footer($isHtml)
  753. {
  754. global $RCMAIL;
  755. if ($isHtml && ($file = $RCMAIL->config->get('generic_message_footer_html'))) {
  756. $html_footer = true;
  757. }
  758. else {
  759. $file = $RCMAIL->config->get('generic_message_footer');
  760. $html_footer = false;
  761. }
  762. if ($file && realpath($file)) {
  763. // sanity check
  764. if (!preg_match('/\.(php|ini|conf)$/', $file) && strpos($file, '/etc/') === false) {
  765. $footer = file_get_contents($file);
  766. if ($isHtml && !$html_footer) {
  767. $t2h = new rcube_text2html($footer, false);
  768. $footer = $t2h->get_html();
  769. }
  770. return $footer;
  771. }
  772. }
  773. return false;
  774. }
  775. /**
  776. * clear message composing settings
  777. */
  778. function rcmail_compose_cleanup($id)
  779. {
  780. if (!isset($_SESSION['compose_data_'.$id])) {
  781. return;
  782. }
  783. $rcmail = rcmail::get_instance();
  784. $rcmail->plugins->exec_hook('attachments_cleanup', array('group' => $id));
  785. $rcmail->session->remove('compose_data_'.$id);
  786. $_SESSION['last_compose_session'] = $id;
  787. }