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