4 ** This contains all the functions needed to send messages through
5 ** an smtp server or sendmail.
10 if (defined('smtp_php'))
12 define('smtp_php', true);
14 include('../functions/addressbook.php');
16 global $username, $popuser, $domain;
18 // This should most probably go to some initialization...
19 if (ereg("^([^@%/]+)[@%/](.+)$", $username, $usernamedata)) {
20 $popuser = $usernamedata[1];
21 $domain = $usernamedata[2];
26 // We need domain for smtp
28 $domain = getenv('HOSTNAME');
30 // Returns true only if this message is multipart
31 function isMultipart () {
34 if (count($attachments)>0)
40 // looks up aliases in the addressbook and expands them to
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) {
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]);
53 if (isset($result['email'])) {
54 if (isset($result['name'])) {
55 $ret = '"'.$result['name'].'" ';
57 $ret .= '<'.$result['email'].'>';
62 if (strpos($array[$i], '@') === false)
63 $array[$i] .= '@' . $domain;
64 $array[$i] = '<' . $array[$i] . '>';
70 // Attach the files that are due to be attached
71 function attachFiles ($fp) {
72 global $attachments, $attachment_dir;
77 foreach ($attachments as $info)
79 if (isset($info['type']))
80 $filetype = $info['type'];
82 $filetype = 'application/octet-stream';
84 $header = '--'.mimeBoundary()."\r\n";
85 $header .= "Content-Type: $filetype; name=\"" .
86 $info['remotefilename'] . "\"\r\n";
87 $header .= "Content-Disposition: attachment; filename=\"" .
88 $info['remotefilename'] . "\"\r\n";
90 // Use 'rb' for NT systems -- read binary
91 // Unix doesn't care -- everything's binary! :-)
92 $file = fopen ($attachment_dir . $info['localfilename'], 'rb');
93 if (substr($filetype, 0, 5) == 'text/' ||
94 $filetype == 'message/rfc822') {
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 if (feof($fp) && substr($tmp, -2) != "\r\n")
105 $length +
= strlen($tmp);
108 $header .= "Content-Transfer-Encoding: base64\r\n\r\n";
109 fputs ($fp, $header);
110 $length +
= strlen($header);
111 while ($tmp = fread($file, 570)) {
112 $encoded = chunk_split(base64_encode($tmp));
113 $length +
= strlen($encoded);
114 fputs ($fp, $encoded);
124 // Delete files that are uploaded for attaching
125 function deleteAttachments() {
126 global $attachments, $attachment_dir;
130 while (list($localname, $remotename) = each($attachments)) {
131 if (!ereg ("\\/", $localname)) {
132 unlink ($attachment_dir.$localname);
133 unlink ($attachment_dir.$localname.'.info');
139 // Return a nice MIME-boundary
140 function mimeBoundary () {
141 static $mimeBoundaryString;
143 if ($mimeBoundaryString == "") {
144 $mimeBoundaryString = "----=_" .
145 GenerateRandomString(60, '\'()+,-./:=?_', 7);
148 return $mimeBoundaryString;
151 /* Time offset for correct timezone */
152 function timezone () {
155 $diff_second = date('Z');
157 $diff_second = - $diff_second;
158 if ($diff_second > 0)
163 $diff_second = abs($diff_second);
165 $diff_hour = floor ($diff_second / 3600);
166 $diff_minute = floor (($diff_second-3600*$diff_hour) / 60);
168 $zonename = '('.strftime('%Z').')';
169 $result = sprintf ("%s%02d%02d %s", $sign, $diff_hour, $diff_minute, $zonename);
173 /* Print all the needed RFC822 headers */
174 function write822Header ($fp, $t, $c, $b, $subject, $more_headers) {
175 global $REMOTE_ADDR, $SERVER_NAME, $REMOTE_PORT;
176 global $data_dir, $username, $popuser, $domain, $version, $useSendmail;
177 global $default_charset, $HTTP_VIA, $HTTP_X_FORWARDED_FOR;
178 global $REMOTE_HOST, $identity;
180 // Storing the header to make sure the header is the same
181 // everytime the header is printed.
182 static $header, $headerlength;
185 $to = expandAddrs(parseAddrs($t));
186 $cc = expandAddrs(parseAddrs($c));
187 $bcc = expandAddrs(parseAddrs($b));
188 if (isset($identity) && $identity != 'default')
190 $reply_to = getPref($data_dir, $username, 'reply_to' . $identity);
191 $from = getPref($data_dir, $username, 'full_name' . $identity);
192 $from_addr = getPref($data_dir, $username, 'email_address' . $identity);
196 $reply_to = getPref($data_dir, $username, 'reply_to');
197 $from = getPref($data_dir, $username, 'full_name');
198 $from_addr = getPref($data_dir, $username, 'email_address');
201 if ($from_addr == '')
202 $from_addr = $popuser.'@'.$domain;
204 $to_list = getLineOfAddrs($to);
205 $cc_list = getLineOfAddrs($cc);
206 $bcc_list = getLineOfAddrs($bcc);
208 /* Encoding 8-bit characters and making from line */
209 $subject = encodeHeader($subject);
211 $from = "<$from_addr>";
213 $from = '"' . encodeHeader($from) . "\" <$from_addr>";
215 /* This creates an RFC 822 date */
216 $date = date("D, j M Y H:i:s ", mktime()) . timezone();
218 /* Create a message-id */
219 $message_id = '<' . $REMOTE_PORT . '.' . $REMOTE_ADDR . '.';
220 $message_id .= time() . '.squirrel@' . $SERVER_NAME .'>';
222 /* Make an RFC822 Received: line */
223 if (isset($REMOTE_HOST))
224 $received_from = "$REMOTE_HOST ([$REMOTE_ADDR])";
226 $received_from = $REMOTE_ADDR;
228 if (isset($HTTP_VIA) ||
isset ($HTTP_X_FORWARDED_FOR)) {
229 if ($HTTP_X_FORWARDED_FOR == '')
230 $HTTP_X_FORWARDED_FOR = 'unknown';
231 $received_from .= " (proxying for $HTTP_X_FORWARDED_FOR)";
234 $header = "Received: from $received_from\r\n";
235 $header .= " (SquirrelMail authenticated user $username)\r\n";
236 $header .= " by $SERVER_NAME with HTTP;\r\n";
237 $header .= " $date\r\n";
239 /* Insert the rest of the header fields */
240 $header .= "Message-ID: $message_id\r\n";
241 $header .= "Date: $date\r\n";
242 $header .= "Subject: $subject\r\n";
243 $header .= "From: $from\r\n";
244 $header .= "To: $to_list\r\n"; // Who it's TO
246 /* Insert headers from the $more_headers array */
247 if(is_array($more_headers)) {
248 reset($more_headers);
249 while(list($h_name, $h_val) = each($more_headers)) {
250 $header .= sprintf("%s: %s\r\n", $h_name, $h_val);
255 $header .= "Cc: $cc_list\r\n"; // Who the CCs are
259 $header .= "Reply-To: $reply_to\r\n";
263 // BCCs is removed from header by sendmail
264 $header .= "Bcc: $bcc_list\r\n";
268 $header .= "X-Mailer: SquirrelMail (version $version)\r\n"; // Identify SquirrelMail
271 $header .= "MIME-Version: 1.0\r\n";
274 $header .= 'Content-Type: multipart/mixed; boundary="';
275 $header .= mimeBoundary();
278 if ($default_charset != '')
279 $header .= "Content-Type: text/plain; charset=$default_charset\r\n";
281 $header .= "Content-Type: text/plain;\r\n";
282 $header .= "Content-Transfer-Encoding: 8bit\r\n";
284 $header .= "\r\n"; // One blank line to separate header and body
286 $headerlength = strlen($header);
290 fputs ($fp, $header);
292 return $headerlength;
296 function writeBody ($fp, $passedBody) {
297 global $default_charset;
299 $attachmentlength = 0;
302 $body = '--'.mimeBoundary()."\r\n";
304 if ($default_charset != "")
305 $body .= "Content-Type: text/plain; charset=$default_charset\r\n";
307 $body .= "Content-Type: text/plain\r\n";
309 $body .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
310 $body .= $passedBody . "\r\n\r\n";
313 $attachmentlength = attachFiles($fp);
315 if (!isset($postbody)) $postbody = "";
316 $postbody .= "\r\n--".mimeBoundary()."--\r\n\r\n";
317 fputs ($fp, $postbody);
319 $body = $passedBody . "\r\n";
322 fputs ($fp, $postbody);
325 return (strlen($body) +
strlen($postbody) +
$attachmentlength);
328 // Send mail using the sendmail command
329 function sendSendmail($t, $c, $b, $subject, $body, $more_headers) {
330 global $sendmail_path, $popuser, $username, $domain;
332 // Build envelope sender address. Make sure it doesn't contain
333 // spaces or other "weird" chars that would allow a user to
334 // exploit the shell/pipe it is used in.
335 $envelopefrom = "$popuser@$domain";
336 $envelopefrom = ereg_replace("[[:blank:]]",'', $envelopefrom);
337 $envelopefrom = ereg_replace("[[:space:]]",'', $envelopefrom);
338 $envelopefrom = ereg_replace("[[:cntrl:]]",'', $envelopefrom);
340 // open pipe to sendmail
341 $fp = popen (escapeshellcmd("$sendmail_path -t -f$envelopefrom"), 'w');
343 $headerlength = write822Header ($fp, $t, $c, $b, $subject, $more_headers);
344 $bodylength = writeBody($fp, $body);
348 return ($headerlength +
$bodylength);
351 function smtpReadData($smtpConnection) {
352 $read = fgets($smtpConnection, 1024);
356 $data[$counter] = $read;
357 $read = fgets($smtpConnection, 1024);
362 function sendSMTP($t, $c, $b, $subject, $body, $more_headers) {
363 global $username, $popuser, $domain, $version, $smtpServerAddress, $smtpPort,
364 $data_dir, $color, $use_authenticated_smtp, $identity;
366 $to = expandAddrs(parseAddrs($t));
367 $cc = expandAddrs(parseAddrs($c));
368 $bcc = expandAddrs(parseAddrs($b));
369 if (isset($identity) && $identity != 'default')
370 $from_addr = getPref($data_dir, $username, 'email_address' . $identity);
372 $from_addr = getPref($data_dir, $username, 'email_address');
375 $from_addr = "$popuser@$domain";
377 $smtpConnection = fsockopen($smtpServerAddress, $smtpPort, $errorNumber, $errorString);
378 if (!$smtpConnection) {
379 echo 'Error connecting to SMTP Server.<br>';
380 echo "$errorNumber : $errorString<br>";
383 $tmp = fgets($smtpConnection, 1024);
384 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
386 $to_list = getLineOfAddrs($to);
387 $cc_list = getLineOfAddrs($cc);
389 /** Lets introduce ourselves */
390 if (! isset ($use_authenticated_smtp) ||
$use_authenticated_smtp == false) {
391 fputs($smtpConnection, "HELO $domain\r\n");
392 $tmp = fgets($smtpConnection, 1024);
393 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
395 fputs($smtpConnection, "EHLO $domain\r\n");
396 $tmp = fgets($smtpConnection, 1024);
397 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
399 fputs($smtpConnection, "AUTH LOGIN\r\n");
400 $tmp = fgets($smtpConnection, 1024);
401 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
403 fputs($smtpConnection, base64_encode ($username) . "\r\n");
404 $tmp = fgets($smtpConnection, 1024);
405 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
407 fputs($smtpConnection, base64_encode (OneTimePadDecrypt($key, $onetimepad)) . "\r\n");
408 $tmp = fgets($smtpConnection, 1024);
409 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
412 /** Ok, who is sending the message? */
413 fputs($smtpConnection, "MAIL FROM: <$from_addr>\r\n");
414 $tmp = fgets($smtpConnection, 1024);
415 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
417 /** send who the recipients are */
418 for ($i = 0; $i < count($to); $i++
) {
419 fputs($smtpConnection, "RCPT TO: $to[$i]\r\n");
420 $tmp = fgets($smtpConnection, 1024);
421 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
423 for ($i = 0; $i < count($cc); $i++
) {
424 fputs($smtpConnection, "RCPT TO: $cc[$i]\r\n");
425 $tmp = fgets($smtpConnection, 1024);
426 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
428 for ($i = 0; $i < count($bcc); $i++
) {
429 fputs($smtpConnection, "RCPT TO: $bcc[$i]\r\n");
430 $tmp = fgets($smtpConnection, 1024);
431 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
434 /** Lets start sending the actual message */
435 fputs($smtpConnection, "DATA\r\n");
436 $tmp = fgets($smtpConnection, 1024);
437 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
440 $headerlength = write822Header ($smtpConnection, $t, $c, $b, $subject, $more_headers);
441 $bodylength = writeBody($smtpConnection, $body);
443 fputs($smtpConnection, ".\r\n"); // end the DATA part
444 $tmp = fgets($smtpConnection, 1024);
445 $num = errorCheck($tmp, $smtpConnection, true);
447 $tmp = nl2br(htmlspecialchars($tmp));
448 displayPageHeader($color, 'None');
449 include ("../functions/display_messages.php");
450 $msg = "Message not sent!<br>\nReason given: $tmp";
451 plain_error_message($msg, $color);
455 fputs($smtpConnection, "QUIT\r\n"); // log off
457 fclose($smtpConnection);
459 return ($headerlength +
$bodylength);
463 function errorCheck($line, $smtpConnection, $verbose = false) {
465 include '../functions/page_header.php';
467 // Read new lines on a multiline response
469 while(ereg("^[0-9]+-", $line)) {
470 $line = fgets($smtpConnection, 1024);
477 $err_num = substr($line, 0, strpos($line, " "));
479 case 500: $message = 'Syntax error; command not recognized';
482 case 501: $message = 'Syntax error in parameters or arguments';
485 case 502: $message = 'Command not implemented';
488 case 503: $message = 'Bad sequence of commands';
491 case 504: $message = 'Command parameter not implemented';
496 case 211: $message = 'System status, or system help reply';
499 case 214: $message = 'Help message';
504 case 220: $message = 'Service ready';
507 case 221: $message = 'Service closing transmission channel';
510 case 421: $message = 'Service not available, closing chanel';
514 case 235: return(5); break;
515 case 250: $message = 'Requested mail action okay, completed';
518 case 251: $message = 'User not local; will forward';
521 case 334: return(5); break;
522 case 450: $message = 'Requested mail action not taken: mailbox unavailable';
525 case 550: $message = 'Requested action not taken: mailbox unavailable';
528 case 451: $message = 'Requested action aborted: error in processing';
531 case 551: $message = 'User not local; please try forwarding';
534 case 452: $message = 'Requested action not taken: insufficient system storage';
537 case 552: $message = 'Requested mail action aborted: exceeding storage allocation';
540 case 553: $message = 'Requested action not taken: mailbox name not allowed';
543 case 354: $message = 'Start mail input; end with .';
546 case 554: $message = 'Transaction failed';
549 default: $message = 'Unknown response: '. nl2br(htmlspecialchars($lines));
556 displayPageHeader($color, 'None');
557 include ("../functions/display_messages.php");
558 $lines = nl2br(htmlspecialchars($lines));
559 $msg = $message . "<br>\nServer replied: $lines";
560 plain_error_message($msg, $color);
562 if (! $verbose) return $status;
566 function sendMessage($t, $c, $b, $subject, $body, $reply_id) {
567 global $useSendmail, $msg_id, $is_reply, $mailbox, $onetimepad;
568 global $data_dir, $username, $domain, $key, $version, $sent_folder, $imapServerAddress, $imapPort;
569 $more_headers = Array();
571 $imap_stream = sqimap_login($username, $key, $imapServerAddress, $imapPort, 1);
573 if (isset($reply_id) && $reply_id) {
574 sqimap_mailbox_select ($imap_stream, $mailbox);
575 sqimap_messages_flag ($imap_stream, $reply_id, $reply_id, 'Answered');
577 // Insert In-Reply-To and References headers if the
578 // message-id of the message we reply to is set (longer than "<>")
579 // The References header should really be the old Referenced header
580 // with the message ID appended, but it can be only the message ID too.
581 $hdr = sqimap_get_small_header ($imap_stream, $reply_id, false);
582 if(strlen($hdr->message_id
) > 2) {
583 $more_headers['In-Reply-To'] = $hdr->message_id
;
584 $more_headers['References'] = $hdr->message_id
;
588 // In order to remove the problem of users not able to create
589 // messages with "." on a blank line, RFC821 has made provision
590 // in section 4.5.2 (Transparency).
591 $body = ereg_replace("\n\\.", "\n..", $body);
592 $body = ereg_replace("^\\.", "..", $body);
594 // this is to catch all plain \n instances and
595 // replace them with \r\n.
596 $body = ereg_replace("\r\n", "\n", $body);
597 $body = ereg_replace("\n", "\r\n", $body);
600 $length = sendSendmail($t, $c, $b, $subject, $body, $more_headers);
602 $length = sendSMTP($t, $c, $b, $subject, $body, $more_headers);
605 if (sqimap_mailbox_exists ($imap_stream, $sent_folder)) {
606 sqimap_append ($imap_stream, $sent_folder, $length);
607 write822Header ($imap_stream, $t, $c, $b, $subject, $more_headers);
608 writeBody ($imap_stream, $body);
609 sqimap_append_done ($imap_stream);
611 sqimap_logout($imap_stream);
612 // Delete the files uploaded for attaching (if any).
613 // only if $length != 0 (if there was no error)