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