Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

sendmail.inc 32KB

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