auto create sent/trash folders
[squirrelmail.git] / functions / smtp.php
1 <?php
2 /** smtp.php
3 **
4 ** This contains all the functions needed to send messages through
5 ** an smtp server or sendmail.
6 **
7 ** $Id$
8 **/
9
10 if (defined('smtp_php'))
11 return;
12 define('smtp_php', true);
13
14 include('../functions/addressbook.php');
15
16 global $username, $popuser, $domain;
17
18 // This should most probably go to some initialization...
19 if (ereg("^([^@%/]+)[@%/](.+)$", $username, $usernamedata)) {
20 $popuser = $usernamedata[1];
21 $domain = $usernamedata[2];
22 unset($usernamedata);
23 } else {
24 $popuser = $username;
25 }
26 // We need domain for smtp
27 if (!$domain)
28 $domain = getenv('HOSTNAME');
29
30 // Returns true only if this message is multipart
31 function isMultipart () {
32 global $attachments;
33
34 if (count($attachments)>0)
35 return true;
36 else
37 return false;
38 }
39
40 // looks up aliases in the addressbook and expands them to
41 // the full address.
42 // Adds @$domain if it wasn't in the address book and if it
43 // doesn't have an @ symbol in it
44 function expandAddrs ($array) {
45 global $domain;
46
47 // don't show errors -- kinda critical that we don't see
48 // them here since the redirect won't work if we do show them
49 $abook = addressbook_init(false);
50 for ($i=0; $i < count($array); $i++) {
51 $result = $abook->lookup($array[$i]);
52 $ret = "";
53 if (isset($result['email'])) {
54 if (isset($result['name'])) {
55 $ret = '"'.$result['name'].'" ';
56 }
57 $ret .= '<'.$result['email'].'>';
58 $array[$i] = $ret;
59 }
60 else
61 {
62 $array[$i] = '<' . $array[$i] . '>';
63 }
64
65 if (strpos($array[$i], '@') === false) {
66 $array[$i] .= '@' . $domain;
67 }
68 }
69 return $array;
70 }
71
72 // Attach the files that are due to be attached
73 function attachFiles ($fp) {
74 global $attachments, $attachment_dir;
75
76 $length = 0;
77
78 if (isMultipart()) {
79 foreach ($attachments as $info)
80 {
81 if (isset($info['type']))
82 $filetype = $info['type'];
83 else
84 $filetype = 'application/octet-stream';
85
86 $header = '--'.mimeBoundary()."\r\n";
87 $header .= "Content-Type: $filetype; name=\"" .
88 $info['remotefilename'] . "\"\r\n";
89 $header .= "Content-Disposition: attachment; filename=\"" .
90 $info['remotefilename'] . "\"\r\n";
91
92 $file = fopen ($attachment_dir . $info['localfilename'], 'r');
93 if (substr($filetype, 0, 5) == 'text/' ||
94 $filetype == 'message/rfc822') {
95 $header .= "\r\n";
96 fputs ($fp, $header);
97 $length += strlen($header);
98 while ($tmp = fgets($file, 4096)) {
99 $tmp = str_replace("\r\n", "\n", $tmp);
100 $tmp = str_replace("\r", "\n", $tmp);
101 $tmp = str_replace("\n", "\r\n", $tmp);
102 fputs($fp, $tmp);
103 $length += strlen($tmp);
104 }
105 } else {
106 $header .= "Content-Transfer-Encoding: base64\r\n\r\n";
107 fputs ($fp, $header);
108 $length += strlen($header);
109 while ($tmp = fread($file, 570)) {
110 $encoded = chunk_split(base64_encode($tmp));
111 $length += strlen($encoded);
112 fputs ($fp, $encoded);
113 }
114 }
115 fclose ($file);
116 }
117 }
118
119 return $length;
120 }
121
122 // Delete files that are uploaded for attaching
123 function deleteAttachments() {
124 global $attachments, $attachment_dir;
125
126 if (isMultipart()) {
127 reset($attachments);
128 while (list($localname, $remotename) = each($attachments)) {
129 if (!ereg ("\\/", $localname)) {
130 unlink ($attachment_dir.$localname);
131 unlink ($attachment_dir.$localname.'.info');
132 }
133 }
134 }
135 }
136
137 // Return a nice MIME-boundary
138 function mimeBoundary () {
139 static $mimeBoundaryString;
140
141 if ($mimeBoundaryString == "") {
142 $mimeBoundaryString = "----=_" .
143 GenerateRandomString(60, '\'()+,-./:=?_', 7);
144 }
145
146 return $mimeBoundaryString;
147 }
148
149 /* Time offset for correct timezone */
150 function timezone () {
151 global $invert_time;
152
153 $diff_second = date('Z');
154 if ($invert_time)
155 $diff_second = - $diff_second;
156 if ($diff_second > 0)
157 $sign = '+';
158 else
159 $sign = '-';
160
161 $diff_second = abs($diff_second);
162
163 $diff_hour = floor ($diff_second / 3600);
164 $diff_minute = floor (($diff_second-3600*$diff_hour) / 60);
165
166 $zonename = '('.strftime('%Z').')';
167 $result = sprintf ("%s%02d%02d %s", $sign, $diff_hour, $diff_minute, $zonename);
168 return ($result);
169 }
170
171 /* Print all the needed RFC822 headers */
172 function write822Header ($fp, $t, $c, $b, $subject, $more_headers) {
173 global $REMOTE_ADDR, $SERVER_NAME, $REMOTE_PORT;
174 global $data_dir, $username, $popuser, $domain, $version, $useSendmail;
175 global $default_charset, $HTTP_VIA, $HTTP_X_FORWARDED_FOR;
176 global $REMOTE_HOST, $identity;
177
178 // Storing the header to make sure the header is the same
179 // everytime the header is printed.
180 static $header, $headerlength;
181
182 if ($header == '') {
183 $to = expandAddrs(parseAddrs($t));
184 $cc = expandAddrs(parseAddrs($c));
185 $bcc = expandAddrs(parseAddrs($b));
186 if (isset($identity) && $identity != 'default')
187 {
188 $reply_to = getPref($data_dir, $username, 'reply_to' . $identity);
189 $from = getPref($data_dir, $username, 'full_name' . $identity);
190 $from_addr = getPref($data_dir, $username, 'email_address' . $identity);
191 }
192 else
193 {
194 $reply_to = getPref($data_dir, $username, 'reply_to');
195 $from = getPref($data_dir, $username, 'full_name');
196 $from_addr = getPref($data_dir, $username, 'email_address');
197 }
198
199 if ($from_addr == '')
200 $from_addr = $popuser.'@'.$domain;
201
202 $to_list = getLineOfAddrs($to);
203 $cc_list = getLineOfAddrs($cc);
204 $bcc_list = getLineOfAddrs($bcc);
205
206 /* Encoding 8-bit characters and making from line */
207 $subject = encodeHeader($subject);
208 if ($from == '')
209 $from = "<$from_addr>";
210 else
211 $from = '"' . encodeHeader($from) . "\" <$from_addr>";
212
213 /* This creates an RFC 822 date */
214 $date = date("D, j M Y H:i:s ", mktime()) . timezone();
215
216 /* Create a message-id */
217 $message_id = '<' . $REMOTE_PORT . '.' . $REMOTE_ADDR . '.';
218 $message_id .= time() . '.squirrel@' . $SERVER_NAME .'>';
219
220 /* Make an RFC822 Received: line */
221 if (isset($REMOTE_HOST))
222 $received_from = "$REMOTE_HOST ([$REMOTE_ADDR])";
223 else
224 $received_from = $REMOTE_ADDR;
225
226 if (isset($HTTP_VIA) || isset ($HTTP_X_FORWARDED_FOR)) {
227 if ($HTTP_X_FORWARDED_FOR == '')
228 $HTTP_X_FORWARDED_FOR = 'unknown';
229 $received_from .= " (proxying for $HTTP_X_FORWARDED_FOR)";
230 }
231
232 $header = "Received: from $received_from\r\n";
233 $header .= " (SquirrelMail authenticated user $username)\r\n";
234 $header .= " by $SERVER_NAME with HTTP;\r\n";
235 $header .= " $date\r\n";
236
237 /* Insert the rest of the header fields */
238 $header .= "Message-ID: $message_id\r\n";
239 $header .= "Date: $date\r\n";
240 $header .= "Subject: $subject\r\n";
241 $header .= "From: $from\r\n";
242 $header .= "To: $to_list\r\n"; // Who it's TO
243
244 /* Insert headers from the $more_headers array */
245 if(is_array($more_headers)) {
246 reset($more_headers);
247 while(list($h_name, $h_val) = each($more_headers)) {
248 $header .= sprintf("%s: %s\r\n", $h_name, $h_val);
249 }
250 }
251
252 if ($cc_list) {
253 $header .= "Cc: $cc_list\r\n"; // Who the CCs are
254 }
255
256 if ($reply_to != '')
257 $header .= "Reply-To: $reply_to\r\n";
258
259 if ($useSendmail) {
260 if ($bcc_list) {
261 // BCCs is removed from header by sendmail
262 $header .= "Bcc: $bcc_list\r\n";
263 }
264 }
265
266 $header .= "X-Mailer: SquirrelMail (version $version)\r\n"; // Identify SquirrelMail
267
268 // Do the MIME-stuff
269 $header .= "MIME-Version: 1.0\r\n";
270
271 if (isMultipart()) {
272 $header .= 'Content-Type: multipart/mixed; boundary="';
273 $header .= mimeBoundary();
274 $header .= "\"\r\n";
275 } else {
276 if ($default_charset != '')
277 $header .= "Content-Type: text/plain; charset=$default_charset\r\n";
278 else
279 $header .= "Content-Type: text/plain;\r\n";
280 $header .= "Content-Transfer-Encoding: 8bit\r\n";
281 }
282 $header .= "\r\n"; // One blank line to separate header and body
283
284 $headerlength = strlen($header);
285 }
286
287 // Write the header
288 fputs ($fp, $header);
289
290 return $headerlength;
291 }
292
293 // Send the body
294 function writeBody ($fp, $passedBody) {
295 global $default_charset;
296
297 $attachmentlength = 0;
298
299 if (isMultipart()) {
300 $body = '--'.mimeBoundary()."\r\n";
301
302 if ($default_charset != "")
303 $body .= "Content-Type: text/plain; charset=$default_charset\r\n";
304 else
305 $body .= "Content-Type: text/plain\r\n";
306
307 $body .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
308 $body .= $passedBody . "\r\n\r\n";
309 fputs ($fp, $body);
310
311 $attachmentlength = attachFiles($fp);
312
313 if (!isset($postbody)) $postbody = "";
314 $postbody .= "\r\n--".mimeBoundary()."--\r\n\r\n";
315 fputs ($fp, $postbody);
316 } else {
317 $body = $passedBody . "\r\n";
318 fputs ($fp, $body);
319 $postbody = "\r\n";
320 fputs ($fp, $postbody);
321 }
322
323 return (strlen($body) + strlen($postbody) + $attachmentlength);
324 }
325
326 // Send mail using the sendmail command
327 function sendSendmail($t, $c, $b, $subject, $body, $more_headers) {
328 global $sendmail_path, $popuser, $username, $domain;
329
330 // Build envelope sender address. Make sure it doesn't contain
331 // spaces or other "weird" chars that would allow a user to
332 // exploit the shell/pipe it is used in.
333 $envelopefrom = "$popuser@$domain";
334 $envelopefrom = ereg_replace("[[:blank:]]",'', $envelopefrom);
335 $envelopefrom = ereg_replace("[[:space:]]",'', $envelopefrom);
336 $envelopefrom = ereg_replace("[[:cntrl:]]",'', $envelopefrom);
337
338 // open pipe to sendmail
339 $fp = popen (escapeshellcmd("$sendmail_path -t -f$envelopefrom"), 'w');
340
341 $headerlength = write822Header ($fp, $t, $c, $b, $subject, $more_headers);
342 $bodylength = writeBody($fp, $body);
343
344 pclose($fp);
345
346 return ($headerlength + $bodylength);
347 }
348
349 function smtpReadData($smtpConnection) {
350 $read = fgets($smtpConnection, 1024);
351 $counter = 0;
352 while ($read) {
353 echo $read . '<BR>';
354 $data[$counter] = $read;
355 $read = fgets($smtpConnection, 1024);
356 $counter++;
357 }
358 }
359
360 function sendSMTP($t, $c, $b, $subject, $body, $more_headers) {
361 global $username, $popuser, $domain, $version, $smtpServerAddress, $smtpPort,
362 $data_dir, $color, $use_authenticated_smtp, $identity;
363
364 $to = expandAddrs(parseAddrs($t));
365 $cc = expandAddrs(parseAddrs($c));
366 $bcc = expandAddrs(parseAddrs($b));
367 if (isset($identity) && $identity != 'default')
368 $from_addr = getPref($data_dir, $username, 'email_address' . $identity);
369 else
370 $from_addr = getPref($data_dir, $username, 'email_address');
371
372 if (!$from_addr)
373 $from_addr = "$popuser@$domain";
374
375 $smtpConnection = fsockopen($smtpServerAddress, $smtpPort, $errorNumber, $errorString);
376 if (!$smtpConnection) {
377 echo 'Error connecting to SMTP Server.<br>';
378 echo "$errorNumber : $errorString<br>";
379 exit;
380 }
381 $tmp = fgets($smtpConnection, 1024);
382 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
383
384 $to_list = getLineOfAddrs($to);
385 $cc_list = getLineOfAddrs($cc);
386
387 /** Lets introduce ourselves */
388 if (! isset ($use_authenticated_smtp) || $use_authenticated_smtp == false) {
389 fputs($smtpConnection, "HELO $domain\r\n");
390 $tmp = fgets($smtpConnection, 1024);
391 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
392 } else {
393 fputs($smtpConnection, "EHLO $domain\r\n");
394 $tmp = fgets($smtpConnection, 1024);
395 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
396
397 fputs($smtpConnection, "AUTH LOGIN\r\n");
398 $tmp = fgets($smtpConnection, 1024);
399 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
400
401 fputs($smtpConnection, base64_encode ($username) . "\r\n");
402 $tmp = fgets($smtpConnection, 1024);
403 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
404
405 fputs($smtpConnection, base64_encode ($OneTimePadDecrypt($key, $onetimepad)) . "\r\n");
406 $tmp = fgets($smtpConnection, 1024);
407 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
408 }
409
410 /** Ok, who is sending the message? */
411 fputs($smtpConnection, "MAIL FROM: <$from_addr>\r\n");
412 $tmp = fgets($smtpConnection, 1024);
413 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
414
415 /** send who the recipients are */
416 for ($i = 0; $i < count($to); $i++) {
417 fputs($smtpConnection, "RCPT TO: $to[$i]\r\n");
418 $tmp = fgets($smtpConnection, 1024);
419 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
420 }
421 for ($i = 0; $i < count($cc); $i++) {
422 fputs($smtpConnection, "RCPT TO: $cc[$i]\r\n");
423 $tmp = fgets($smtpConnection, 1024);
424 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
425 }
426 for ($i = 0; $i < count($bcc); $i++) {
427 fputs($smtpConnection, "RCPT TO: $bcc[$i]\r\n");
428 $tmp = fgets($smtpConnection, 1024);
429 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
430 }
431
432 /** Lets start sending the actual message */
433 fputs($smtpConnection, "DATA\r\n");
434 $tmp = fgets($smtpConnection, 1024);
435 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
436
437 // Send the message
438 $headerlength = write822Header ($smtpConnection, $t, $c, $b, $subject, $more_headers);
439 $bodylength = writeBody($smtpConnection, $body);
440
441 fputs($smtpConnection, ".\r\n"); // end the DATA part
442 $tmp = fgets($smtpConnection, 1024);
443 $num = errorCheck($tmp, $smtpConnection, true);
444 if ($num != 250) {
445 $tmp = nl2br(htmlspecialchars($tmp));
446 displayPageHeader($color, 'None');
447 include ("../functions/display_messages.php");
448 $msg = "Message not sent!<br>\nReason given: $tmp";
449 plain_error_message($msg, $color);
450 return(0);
451 }
452
453 fputs($smtpConnection, "QUIT\r\n"); // log off
454
455 fclose($smtpConnection);
456
457 return ($headerlength + $bodylength);
458 }
459
460
461 function errorCheck($line, $smtpConnection, $verbose = false) {
462 global $color;
463 include '../functions/page_header.php';
464
465 // Read new lines on a multiline response
466 $lines = $line;
467 while(ereg("^[0-9]+-", $line)) {
468 $line = fgets($smtpConnection, 1024);
469 $lines .= $line;
470 }
471
472 // Status: 0 = fatal
473 // 5 = ok
474
475 $err_num = substr($line, 0, strpos($line, " "));
476 switch ($err_num) {
477 case 500: $message = 'Syntax error; command not recognized';
478 $status = 0;
479 break;
480 case 501: $message = 'Syntax error in parameters or arguments';
481 $status = 0;
482 break;
483 case 502: $message = 'Command not implemented';
484 $status = 0;
485 break;
486 case 503: $message = 'Bad sequence of commands';
487 $status = 0;
488 break;
489 case 504: $message = 'Command parameter not implemented';
490 $status = 0;
491 break;
492
493
494 case 211: $message = 'System status, or system help reply';
495 $status = 5;
496 break;
497 case 214: $message = 'Help message';
498 $status = 5;
499 break;
500
501
502 case 220: $message = 'Service ready';
503 $status = 5;
504 break;
505 case 221: $message = 'Service closing transmission channel';
506 $status = 5;
507 break;
508 case 421: $message = 'Service not available, closing chanel';
509 $status = 0;
510 break;
511
512 case 235: return(5); break;
513 case 250: $message = 'Requested mail action okay, completed';
514 $status = 5;
515 break;
516 case 251: $message = 'User not local; will forward';
517 $status = 5;
518 break;
519 case 334: return(5); break;
520 case 450: $message = 'Requested mail action not taken: mailbox unavailable';
521 $status = 0;
522 break;
523 case 550: $message = 'Requested action not taken: mailbox unavailable';
524 $status = 0;
525 break;
526 case 451: $message = 'Requested action aborted: error in processing';
527 $status = 0;
528 break;
529 case 551: $message = 'User not local; please try forwarding';
530 $status = 0;
531 break;
532 case 452: $message = 'Requested action not taken: insufficient system storage';
533 $status = 0;
534 break;
535 case 552: $message = 'Requested mail action aborted: exceeding storage allocation';
536 $status = 0;
537 break;
538 case 553: $message = 'Requested action not taken: mailbox name not allowed';
539 $status = 0;
540 break;
541 case 354: $message = 'Start mail input; end with .';
542 $status = 5;
543 break;
544 case 554: $message = 'Transaction failed';
545 $status = 0;
546 break;
547 default: $message = 'Unknown response: '. nl2br(htmlspecialchars($lines));
548 $status = 0;
549 $error_num = '001';
550 break;
551 }
552
553 if ($status == 0) {
554 displayPageHeader($color, 'None');
555 include ("../functions/display_messages.php");
556 $lines = nl2br(htmlspecialchars($lines));
557 $msg = $message . "<br>\nServer replied: $lines";
558 plain_error_message($msg, $color);
559 }
560 if (! $verbose) return $status;
561 return $err_num;
562 }
563
564 function sendMessage($t, $c, $b, $subject, $body, $reply_id) {
565 global $useSendmail, $msg_id, $is_reply, $mailbox, $onetimepad;
566 global $data_dir, $username, $domain, $key, $version, $sent_folder, $imapServerAddress, $imapPort;
567 $more_headers = Array();
568
569 $imap_stream = sqimap_login($username, $key, $imapServerAddress, $imapPort, 1);
570
571 if (isset($reply_id) && $reply_id) {
572 sqimap_mailbox_select ($imap_stream, $mailbox);
573 sqimap_messages_flag ($imap_stream, $reply_id, $reply_id, 'Answered');
574
575 // Insert In-Reply-To and References headers if the
576 // message-id of the message we reply to is set (longer than "<>")
577 // The References header should really be the old Referenced header
578 // with the message ID appended, but it can be only the message ID too.
579 $hdr = sqimap_get_small_header ($imap_stream, $reply_id, false);
580 if(strlen($hdr->message_id) > 2) {
581 $more_headers['In-Reply-To'] = $hdr->message_id;
582 $more_headers['References'] = $hdr->message_id;
583 }
584 }
585
586 // In order to remove the problem of users not able to create
587 // messages with "." on a blank line, RFC821 has made provision
588 // in section 4.5.2 (Transparency).
589 $body = ereg_replace("\n\\.", "\n..", $body);
590 $body = ereg_replace("^\\.", "..", $body);
591
592 // this is to catch all plain \n instances and
593 // replace them with \r\n.
594 $body = ereg_replace("\r\n", "\n", $body);
595 $body = ereg_replace("\n", "\r\n", $body);
596
597 if ($useSendmail) {
598 $length = sendSendmail($t, $c, $b, $subject, $body, $more_headers);
599 } else {
600 $length = sendSMTP($t, $c, $b, $subject, $body, $more_headers);
601 }
602
603 if (sqimap_mailbox_exists ($imap_stream, $sent_folder)) {
604 sqimap_append ($imap_stream, $sent_folder, $length);
605 write822Header ($imap_stream, $t, $c, $b, $subject, $more_headers);
606 writeBody ($imap_stream, $body);
607 sqimap_append_done ($imap_stream);
608 }
609 sqimap_logout($imap_stream);
610 // Delete the files uploaded for attaching (if any).
611 // only if $length != 0 (if there was no error)
612 if ($length)
613 ClearAttachments();
614
615 return $length;
616 }
617
618 ?>