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