]> git.donarmstrong.com Git - roundcube.git/blob - program/steps/mail/sendmail.inc
Imported Upstream version 0.2~stable
[roundcube.git] / program / steps / mail / sendmail.inc
1 <?php
2
3 /*
4  +-----------------------------------------------------------------------+
5  | program/steps/mail/sendmail.inc                                       |
6  |                                                                       |
7  | This file is part of the RoundCube Webmail client                     |
8  | Copyright (C) 2005-2008, RoundCube Dev. - Switzerland                 |
9  | Licensed under the GNU GPL                                            |
10  |                                                                       |
11  | PURPOSE:                                                              |
12  |   Compose a new mail message with all headers and attachments         |
13  |   and send it using the PEAR::Net_SMTP class or with PHP mail()       |
14  |                                                                       |
15  +-----------------------------------------------------------------------+
16  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
17  +-----------------------------------------------------------------------+
18
19  $Id: sendmail.inc 2193 2008-12-29 14:43:45Z alec $
20
21 */
22
23
24 // remove all scripts and act as called in frame
25 $OUTPUT->reset();
26 $OUTPUT->framed = TRUE;
27
28 $savedraft = !empty($_POST['_draft']) ? TRUE : FALSE;
29
30 /****** checks ********/
31
32 if (!isset($_SESSION['compose']['id'])) {
33   raise_error(array('code' => 500, 'file' => __FILE__, 'message' => "Invalid compose ID"), true, false);
34   console("Sendmail error", $_SESSION['compose']);
35   $OUTPUT->show_message("An internal error occured. Please try again.", 'error');
36   $OUTPUT->send('iframe');
37 }
38
39 if (!$savedraft) {
40   if (empty($_POST['_to']) && empty($_POST['_cc']) && empty($_POST['_bcc'])
41     && empty($_POST['_subject']) && $_POST['_message']) {
42     $OUTPUT->show_message('sendingfailed', 'error');
43     $OUTPUT->send('iframe');
44   }
45
46   if(!empty($CONFIG['sendmail_delay'])) {
47     $wait_sec = time() - intval($CONFIG['sendmail_delay']) - intval($CONFIG['last_message_time']);
48     if($wait_sec < 0) {
49       $OUTPUT->show_message('senttooquickly', 'error', array('sec' => $wait_sec * -1));
50       $OUTPUT->send('iframe');
51     }
52   }
53 }
54
55
56 /****** message sending functions ********/
57
58 // get identity record
59 function rcmail_get_identity($id)
60   {
61   global $USER, $OUTPUT;
62   
63   if ($sql_arr = $USER->get_identity($id))
64     {
65     $out = $sql_arr;
66     $out['mailto'] = $sql_arr['email'];
67     
68     // Special chars as defined by RFC 822 need to in quoted string (or escaped).
69     if (preg_match('/[\(\)\<\>\\\.\[\]@,;:"]/', $sql_arr['name']))
70       $name = '"' . addcslashes($sql_arr['name'], '"') . '"';
71     else
72       $name = $sql_arr['name'];
73
74     $out['string'] = rcube_charset_convert($name, RCMAIL_CHARSET, $OUTPUT->get_charset());
75     if ($sql_arr['email'])
76       $out['string'] .= ' <' . $sql_arr['email'] . '>';
77
78     return $out;
79     }
80
81   return FALSE;  
82   }
83
84 /**
85  * go from this:
86  * <img src=".../tiny_mce/plugins/emotions/images/smiley-cool.gif" border="0" alt="Cool" title="Cool" />
87  *
88  * to this:
89  *
90  * <IMG src="cid:smiley-cool.gif"/>
91  * ...
92  * ------part...
93  * Content-Type: image/gif
94  * Content-Transfer-Encoding: base64
95  * Content-ID: <smiley-cool.gif>
96  */
97 function rcmail_attach_emoticons(&$mime_message)
98 {
99   global $CONFIG;
100
101   $htmlContents = $mime_message->getHtmlBody();
102
103   // remove any null-byte characters before parsing
104   $body = preg_replace('/\x00/', '', $htmlContents);
105   
106   $last_img_pos = 0;
107   $searchstr = 'program/js/tiny_mce/plugins/emotions/img/';
108   $path_len = strlen(INSTALL_PATH . '/');
109
110   // keep track of added images, so they're only added once
111   $included_images = array();
112
113   // find emoticon image tags
114   while ($pos = strpos($body, $searchstr, $last_img_pos))
115     {
116     $pos2 = strpos($body, '"', $pos);
117     $body_pre = substr($body, 0, $pos);
118     $body_post = substr($body, $pos2);
119
120     $image_name = substr($body,
121                          $pos + strlen($searchstr),
122                          $pos2 - ($pos + strlen($searchstr)));
123
124     // sanitize image name so resulting attachment doesn't leave images dir
125     $image_name = preg_replace('/[^a-zA-Z0-9_\.\-]/i','',$image_name);
126     $img_file = INSTALL_PATH . '/' . $searchstr . $image_name;
127
128     if (! in_array($image_name, $included_images))
129       {
130       // add the image to the MIME message
131       if(! $mime_message->addHTMLImage($img_file, 'image/gif', '', true, $image_name))
132         $OUTPUT->show_message("emoticonerror", 'error');
133       array_push($included_images, $image_name);
134       }
135     
136     $body = $body_pre . $img_file . $body_post;
137
138     $last_img_pos = $pos2 + $path_len;
139     }
140
141   $mime_message->setHTMLBody($body);
142 }
143
144
145 /****** compose message ********/
146
147 if (strlen($_POST['_draft_saveid']) > 3)
148   $olddraftmessageid = get_input_value('_draft_saveid', RCUBE_INPUT_POST);
149
150 $message_id = sprintf('<%s@%s>', md5(uniqid('rcmail'.rand(),true)), $RCMAIL->config->mail_domain($_SESSION['imap_host']));
151
152 // set default charset
153 $input_charset = $OUTPUT->get_charset();
154 $message_charset = isset($_POST['_charset']) ? $_POST['_charset'] : $input_charset;
155
156 $mailto_regexp = array('/[,;]\s*[\r\n]+/', '/[\r\n]+/', '/[,;]\s*$/m', '/;/', '/(\S{1})(<\S+@\S+>)/U');
157 $mailto_replace = array(', ', ', ', '', ',', '\\1 \\2');
158
159 // replace new lines and strip ending ', ', make address strings more valid also
160 $mailto = preg_replace($mailto_regexp, $mailto_replace, get_input_value('_to', RCUBE_INPUT_POST, TRUE, $message_charset));
161 $mailcc = preg_replace($mailto_regexp, $mailto_replace, get_input_value('_cc', RCUBE_INPUT_POST, TRUE, $message_charset));
162 $mailbcc = preg_replace($mailto_regexp, $mailto_replace, get_input_value('_bcc', RCUBE_INPUT_POST, TRUE, $message_charset));
163
164 if (empty($mailto) && !empty($mailcc)) {
165   $mailto = $mailcc;
166   $mailcc = null;
167 }
168 else if (empty($mailto))
169   $mailto = 'undisclosed-recipients:;';
170
171 // get sender name and address
172 $from = get_input_value('_from', RCUBE_INPUT_POST);
173 $identity_arr = rcmail_get_identity($from);
174
175 if ($identity_arr)
176   $from = $identity_arr['mailto'];
177
178 if (empty($identity_arr['string']))
179   $identity_arr['string'] = $from;
180
181 // compose headers array
182 $headers = array('Date' => date('r'),
183                  'From' => rcube_charset_convert($identity_arr['string'], RCMAIL_CHARSET, $message_charset),
184                  'To'   => $mailto);
185
186 // additional recipients
187 if (!empty($mailcc))
188   $headers['Cc'] = $mailcc;
189
190 if (!empty($mailbcc))
191   $headers['Bcc'] = $mailbcc;
192   
193 if (!empty($identity_arr['bcc']))
194   $headers['Bcc'] = ($headers['Bcc'] ? $headers['Bcc'].', ' : '') . $identity_arr['bcc'];
195
196 // add subject
197 $headers['Subject'] = trim(get_input_value('_subject', RCUBE_INPUT_POST, FALSE, $message_charset));
198
199 if (!empty($identity_arr['organization']))
200   $headers['Organization'] = $identity_arr['organization'];
201
202 if (!empty($_POST['_replyto']))
203   $headers['Reply-To'] = preg_replace($mailto_regexp, $mailto_replace, get_input_value('_replyto', RCUBE_INPUT_POST, TRUE, $message_charset));
204 else if (!empty($identity_arr['reply-to']))
205   $headers['Reply-To'] = $identity_arr['reply-to'];
206
207 if (!empty($_SESSION['compose']['reply_msgid']))
208   $headers['In-Reply-To'] = $_SESSION['compose']['reply_msgid'];
209
210 if (!empty($_SESSION['compose']['references']))
211   $headers['References'] = $_SESSION['compose']['references'];
212
213 if (!empty($_POST['_priority']))
214   {
215   $priority = intval($_POST['_priority']);
216   $a_priorities = array(1=>'highest', 2=>'high', 4=>'low', 5=>'lowest');
217   if ($str_priority = $a_priorities[$priority])
218     $headers['X-Priority'] = sprintf("%d (%s)", $priority, ucfirst($str_priority));
219   }
220
221 if (!empty($_POST['_receipt']))
222   {
223   $headers['Return-Receipt-To'] = $identity_arr['string'];
224   $headers['Disposition-Notification-To'] = $identity_arr['string'];
225   }
226
227 // additional headers
228 if ($CONFIG['http_received_header'])
229 {
230   $nldlm = $RCMAIL->config->header_delimiter() . "\t";
231   $headers['Received'] =  wordwrap('from ' . (isset($_SERVER['HTTP_X_FORWARDED_FOR']) ?
232       gethostbyaddr($_SERVER['HTTP_X_FORWARDED_FOR']).' ['.$_SERVER['HTTP_X_FORWARDED_FOR'].']'.$nldlm.' via ' : '') .
233     gethostbyaddr($_SERVER['REMOTE_ADDR']).' ['.$_SERVER['REMOTE_ADDR'].']'.$nldlm.'with ' .
234     $_SERVER['SERVER_PROTOCOL'].' ('.$_SERVER['REQUEST_METHOD'].'); ' . date('r'),
235     69, $nldlm);
236 }
237
238 $headers['Message-ID'] = $message_id;
239 $headers['X-Sender'] = $from;
240
241 if (!empty($CONFIG['useragent']))
242   $headers['User-Agent'] = $CONFIG['useragent'];
243
244 $isHtmlVal = strtolower(get_input_value('_is_html', RCUBE_INPUT_POST));
245 $isHtml = ($isHtmlVal == "1");
246
247 // fetch message body
248 $message_body = get_input_value('_message', RCUBE_INPUT_POST, TRUE, $message_charset);
249
250 // remove signature's div ID
251 if (!$savedraft && $isHtml)
252   $message_body = preg_replace('/\s*id="_rc_sig"/', '', $message_body);
253
254 // append generic footer to all messages
255 if (!$savedraft && !empty($CONFIG['generic_message_footer']) && ($footer = file_get_contents(realpath($CONFIG['generic_message_footer']))))
256   $message_body .= "\r\n" . rcube_charset_convert($footer, 'UTF-8', $message_charset);
257
258 // create extended PEAR::Mail_mime instance
259 $MAIL_MIME = new rcube_mail_mime($RCMAIL->config->header_delimiter());
260
261 // For HTML-formatted messages, construct the MIME message with both
262 // the HTML part and the plain-text part
263
264 if ($isHtml)
265   {
266   $MAIL_MIME->setHTMLBody($message_body);
267
268   // add a plain text version of the e-mail as an alternative part.
269   $h2t = new html2text($message_body);
270   $plainTextPart = wordwrap($h2t->get_text(), 998, "\r\n", true);
271   if (!strlen($plainTextPart)) 
272     { 
273     // empty message body breaks attachment handling in drafts 
274     $plainTextPart = "\r\n"; 
275     }
276   $MAIL_MIME->setTXTBody($plainTextPart);
277
278   // look for "emoticon" images from TinyMCE and copy into message as attachments
279   rcmail_attach_emoticons($MAIL_MIME);
280   }
281 else
282   {
283   $message_body = wordwrap($message_body, 75, "\r\n");
284   $message_body = wordwrap($message_body, 998, "\r\n", true);
285   if (!strlen($message_body))  
286     { 
287     // empty message body breaks attachment handling in drafts 
288     $message_body = "\r\n"; 
289     } 
290   $MAIL_MIME->setTXTBody($message_body, FALSE, TRUE);
291   }
292
293 // chose transfer encoding
294 $charset_7bit = array('ASCII', 'ISO-2022-JP', 'ISO-8859-1', 'ISO-8859-2', 'ISO-8859-15');
295 $transfer_encoding = in_array(strtoupper($message_charset), $charset_7bit) ? '7bit' : '8bit';
296
297 // add stored attachments, if any
298 if (is_array($_SESSION['compose']['attachments']))
299   foreach ($_SESSION['compose']['attachments'] as $id => $attachment)
300   {
301     $dispurl = '/\ssrc\s*=\s*[\'"]?\S+display-attachment\S+file=rcmfile' . $id . '[\'"]?/';
302     $match = preg_match($dispurl, $message_body);
303     if ($isHtml && ($match > 0))
304     {
305       $message_body = preg_replace($dispurl, ' src="'.$attachment['name'].'"', $message_body);
306       $MAIL_MIME->setHTMLBody($message_body);
307       $MAIL_MIME->addHTMLImage($attachment['path'], $attachment['mimetype'], $attachment['name']);
308     }
309     else
310     {
311       $ctype = str_replace('image/pjpeg', 'image/jpeg', $attachment['mimetype']); // #1484914
312
313       // .eml attachments send inline
314       $MAIL_MIME->addAttachment($attachment['path'],
315         $ctype, 
316         $attachment['name'], true, 
317         ($ctype == 'message/rfc822' ? $transfer_encoding : 'base64'),
318         ($ctype == 'message/rfc822' ? 'inline' : 'attachment'),
319         $message_charset, '', '', 
320         $CONFIG['mime_param_folding'] ? 'quoted-printable' : NULL,
321         $CONFIG['mime_param_folding'] == 2 ? 'quoted-printable' : NULL
322         );
323     }
324   }
325
326 // add submitted attachments
327 if (is_array($_FILES['_attachments']['tmp_name']))
328   foreach ($_FILES['_attachments']['tmp_name'] as $i => $filepath)
329     {
330     $ctype = $files['type'][$i];
331     $ctype = str_replace('image/pjpeg', 'image/jpeg', $ctype); // #1484914
332     
333     $MAIL_MIME->addAttachment($filepath, $ctype, $files['name'][$i], true,
334         $ctype == 'message/rfc822' ? $transfer_encoding : 'base64',
335         'attachment', $message_charset, '', '', 
336         $CONFIG['mime_param_folding'] ? 'quoted-printable' : NULL,
337         $CONFIG['mime_param_folding'] == 2 ? 'quoted-printable' : NULL
338         );
339     }
340
341
342 // encoding settings for mail composing
343 $MAIL_MIME->setParam(array(
344   'text_encoding' => $transfer_encoding,
345   'html_encoding' => 'quoted-printable',
346   'head_encoding' => 'quoted-printable',
347   'head_charset'  => $message_charset,
348   'html_charset'  => $message_charset,
349   'text_charset'  => $message_charset,
350 ));
351
352 // encoding subject header with mb_encode provides better results with asian characters
353 if (function_exists("mb_encode_mimeheader"))
354 {
355   mb_internal_encoding($message_charset);
356   $headers['Subject'] = mb_encode_mimeheader($headers['Subject'], $message_charset, 'Q');
357   mb_internal_encoding(RCMAIL_CHARSET);
358 }
359
360 // pass headers to message object
361 $MAIL_MIME->headers($headers);
362
363 // Begin SMTP Delivery Block 
364 if (!$savedraft)
365 {
366   // check for 'From' address (identity may be incomplete)
367   if ($identity_arr && !$identity_arr['mailto']) {
368     $OUTPUT->show_message('nofromaddress', 'error');
369     $OUTPUT->send('iframe'); 
370   }
371
372   $sent = rcmail_deliver_message($MAIL_MIME, $from, $mailto);
373   
374   // return to compose page if sending failed
375   if (!$sent)
376     {
377     $OUTPUT->show_message("sendingfailed", 'error'); 
378     $OUTPUT->send('iframe');
379     }
380
381   // save message sent time
382   if (!empty($CONFIG['sendmail_delay']))
383     $RCMAIL->user->save_prefs(array('last_message_time' => time()));
384   
385   // set replied/forwarded flag
386   if ($_SESSION['compose']['reply_uid'])
387     $IMAP->set_flag($_SESSION['compose']['reply_uid'], 'ANSWERED');
388   else if ($_SESSION['compose']['forward_uid'])
389     $IMAP->set_flag($_SESSION['compose']['forward_uid'], 'FORWARDED');
390
391 } // End of SMTP Delivery Block
392
393
394
395 // Determine which folder to save message
396 if ($savedraft)
397   $store_target = $CONFIG['drafts_mbox'];
398 else    
399   $store_target = isset($_POST['_store_target']) ? get_input_value('_store_target', RCUBE_INPUT_POST) : $CONFIG['sent_mbox'];
400
401 if ($store_target)
402   {
403   // check if mailbox exists
404   if (!in_array_nocase($store_target, $IMAP->list_mailboxes()))
405     {
406       // folder may be existing but not subscribed (#1485241)
407       if (!in_array_nocase($store_target, $IMAP->list_unsubscribed()))
408         $store_folder = $IMAP->create_mailbox($store_target, TRUE);
409       else if ($IMAP->subscribe($store_target))
410         $store_folder = TRUE;
411     }
412   else
413     $store_folder = TRUE;
414   
415   // append message to sent box
416   if ($store_folder)
417     $saved = $IMAP->save_message($store_target, $MAIL_MIME->getMessage());
418
419   // raise error if saving failed
420   if (!$saved)
421     {
422     raise_error(array('code' => 800, 'type' => 'imap', 'file' => __FILE__,
423                       'message' => "Could not save message in $store_target"), TRUE, FALSE);
424     
425     if ($savedraft) {
426       $OUTPUT->show_message('errorsaving', 'error');
427       $OUTPUT->send('iframe');
428       }
429     }
430
431   if ($olddraftmessageid)
432     {
433     // delete previous saved draft
434     $a_deleteid = $IMAP->search($CONFIG['drafts_mbox'], 'HEADER Message-ID '.$olddraftmessageid);
435
436     $deleted = $IMAP->delete_message($IMAP->get_uid($a_deleteid[0], $CONFIG['drafts_mbox']), $CONFIG['drafts_mbox']);
437
438     // raise error if deletion of old draft failed
439     if (!$deleted)
440       raise_error(array('code' => 800, 'type' => 'imap', 'file' => __FILE__,
441                         'message' => "Could not delete message from ".$CONFIG['drafts_mbox']), TRUE, FALSE);
442     }
443   }
444
445 if ($savedraft)
446   {
447   $msgid = strtr($message_id, array('>' => '', '<' => ''));
448   
449   // remember new draft-uid
450   $draftids = $IMAP->search($CONFIG['drafts_mbox'], 'HEADER Message-ID '.$msgid);
451   $_SESSION['compose']['param']['_draft_uid'] = $IMAP->get_uid($draftids[0], $CONFIG['drafts_mbox']);
452
453   // display success
454   $OUTPUT->show_message('messagesaved', 'confirmation');
455
456   // update "_draft_saveid" and the "cmp_hash" to prevent "Unsaved changes" warning
457   $OUTPUT->command('set_draft_id', $msgid);
458   $OUTPUT->command('compose_field_hash', true);
459
460   // start the auto-save timer again
461   $OUTPUT->command('auto_save_start');
462
463   $OUTPUT->send('iframe');
464   }
465 else
466   {
467   rcmail_compose_cleanup();
468
469   if ($store_folder && !$saved)
470     $OUTPUT->command('sent_successfully', 'error', rcube_label('errorsavingsent'));
471   else
472     $OUTPUT->command('sent_successfully', 'confirmation', rcube_label('messagesent'));
473   $OUTPUT->send('iframe');
474   }
475
476 ?>