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 $array[$i] = '<' . $array[$i] . '>';
65 if (strpos($array[$i], '@') === false) {
66 $array[$i] .= '@' . $domain;
72 // Attach the files that are due to be attached
73 function attachFiles ($fp) {
74 global $attachments, $attachment_dir;
79 foreach ($attachments as $info)
81 if (isset($info['type']))
82 $filetype = $info['type'];
84 $filetype = 'application/octet-stream';
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";
92 $file = fopen ($attachment_dir . $info['localfilename'], 'r');
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);
103 $length +
= strlen($tmp);
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);
122 // Delete files that are uploaded for attaching
123 function deleteAttachments() {
124 global $attachments, $attachment_dir;
128 while (list($localname, $remotename) = each($attachments)) {
129 if (!ereg ("\\/", $localname)) {
130 unlink ($attachment_dir.$localname);
131 unlink ($attachment_dir.$localname.'.info');
137 // Return a nice MIME-boundary
138 function mimeBoundary () {
139 static $mimeBoundaryString;
141 if ($mimeBoundaryString == "") {
142 $mimeBoundaryString = "----=_" .
143 GenerateRandomString(60, '\'()+,-./:=?_', 7);
146 return $mimeBoundaryString;
149 /* Time offset for correct timezone */
150 function timezone () {
153 $diff_second = date('Z');
155 $diff_second = - $diff_second;
156 if ($diff_second > 0)
161 $diff_second = abs($diff_second);
163 $diff_hour = floor ($diff_second / 3600);
164 $diff_minute = floor (($diff_second-3600*$diff_hour) / 60);
166 $zonename = '('.strftime('%Z').')';
167 $result = sprintf ("%s%02d%02d %s", $sign, $diff_hour, $diff_minute, $zonename);
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;
178 // Storing the header to make sure the header is the same
179 // everytime the header is printed.
180 static $header, $headerlength;
183 $to = expandAddrs(parseAddrs($t));
184 $cc = expandAddrs(parseAddrs($c));
185 $bcc = expandAddrs(parseAddrs($b));
186 if (isset($identity) && $identity != 'default')
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);
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');
199 if ($from_addr == '')
200 $from_addr = $popuser.'@'.$domain;
202 $to_list = getLineOfAddrs($to);
203 $cc_list = getLineOfAddrs($cc);
204 $bcc_list = getLineOfAddrs($bcc);
206 /* Encoding 8-bit characters and making from line */
207 $subject = encodeHeader($subject);
209 $from = "<$from_addr>";
211 $from = '"' . encodeHeader($from) . "\" <$from_addr>";
213 /* This creates an RFC 822 date */
214 $date = date("D, j M Y H:i:s ", mktime()) . timezone();
216 /* Create a message-id */
217 $message_id = '<' . $REMOTE_PORT . '.' . $REMOTE_ADDR . '.';
218 $message_id .= time() . '.squirrel@' . $SERVER_NAME .'>';
220 /* Make an RFC822 Received: line */
221 if (isset($REMOTE_HOST))
222 $received_from = "$REMOTE_HOST ([$REMOTE_ADDR])";
224 $received_from = $REMOTE_ADDR;
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)";
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";
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
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);
253 $header .= "Cc: $cc_list\r\n"; // Who the CCs are
257 $header .= "Reply-To: $reply_to\r\n";
261 // BCCs is removed from header by sendmail
262 $header .= "Bcc: $bcc_list\r\n";
266 $header .= "X-Mailer: SquirrelMail (version $version)\r\n"; // Identify SquirrelMail
269 $header .= "MIME-Version: 1.0\r\n";
272 $header .= 'Content-Type: multipart/mixed; boundary="';
273 $header .= mimeBoundary();
276 if ($default_charset != '')
277 $header .= "Content-Type: text/plain; charset=$default_charset\r\n";
279 $header .= "Content-Type: text/plain;\r\n";
280 $header .= "Content-Transfer-Encoding: 8bit\r\n";
282 $header .= "\r\n"; // One blank line to separate header and body
284 $headerlength = strlen($header);
288 fputs ($fp, $header);
290 return $headerlength;
294 function writeBody ($fp, $passedBody) {
295 global $default_charset;
297 $attachmentlength = 0;
300 $body = '--'.mimeBoundary()."\r\n";
302 if ($default_charset != "")
303 $body .= "Content-Type: text/plain; charset=$default_charset\r\n";
305 $body .= "Content-Type: text/plain\r\n";
307 $body .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
308 $body .= $passedBody . "\r\n\r\n";
311 $attachmentlength = attachFiles($fp);
313 if (!isset($postbody)) $postbody = "";
314 $postbody .= "\r\n--".mimeBoundary()."--\r\n\r\n";
315 fputs ($fp, $postbody);
317 $body = $passedBody . "\r\n";
320 fputs ($fp, $postbody);
323 return (strlen($body) +
strlen($postbody) +
$attachmentlength);
326 // Send mail using the sendmail command
327 function sendSendmail($t, $c, $b, $subject, $body, $more_headers) {
328 global $sendmail_path, $popuser, $username, $domain;
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);
338 // open pipe to sendmail
339 $fp = popen (escapeshellcmd("$sendmail_path -t -f$envelopefrom"), 'w');
341 $headerlength = write822Header ($fp, $t, $c, $b, $subject, $more_headers);
342 $bodylength = writeBody($fp, $body);
346 return ($headerlength +
$bodylength);
349 function smtpReadData($smtpConnection) {
350 $read = fgets($smtpConnection, 1024);
354 $data[$counter] = $read;
355 $read = fgets($smtpConnection, 1024);
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;
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);
370 $from_addr = getPref($data_dir, $username, 'email_address');
373 $from_addr = "$popuser@$domain";
375 $smtpConnection = fsockopen($smtpServerAddress, $smtpPort, $errorNumber, $errorString);
376 if (!$smtpConnection) {
377 echo 'Error connecting to SMTP Server.<br>';
378 echo "$errorNumber : $errorString<br>";
381 $tmp = fgets($smtpConnection, 1024);
382 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
384 $to_list = getLineOfAddrs($to);
385 $cc_list = getLineOfAddrs($cc);
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);
393 fputs($smtpConnection, "EHLO $domain\r\n");
394 $tmp = fgets($smtpConnection, 1024);
395 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
397 fputs($smtpConnection, "AUTH LOGIN\r\n");
398 $tmp = fgets($smtpConnection, 1024);
399 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
401 fputs($smtpConnection, base64_encode ($username) . "\r\n");
402 $tmp = fgets($smtpConnection, 1024);
403 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
405 fputs($smtpConnection, base64_encode ($OneTimePadDecrypt($key, $onetimepad)) . "\r\n");
406 $tmp = fgets($smtpConnection, 1024);
407 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
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);
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);
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);
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);
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);
438 $headerlength = write822Header ($smtpConnection, $t, $c, $b, $subject, $more_headers);
439 $bodylength = writeBody($smtpConnection, $body);
441 fputs($smtpConnection, ".\r\n"); // end the DATA part
442 $tmp = fgets($smtpConnection, 1024);
443 $num = errorCheck($tmp, $smtpConnection, true);
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);
453 fputs($smtpConnection, "QUIT\r\n"); // log off
455 fclose($smtpConnection);
457 return ($headerlength +
$bodylength);
461 function errorCheck($line, $smtpConnection, $verbose = false) {
463 include '../functions/page_header.php';
465 // Read new lines on a multiline response
467 while(ereg("^[0-9]+-", $line)) {
468 $line = fgets($smtpConnection, 1024);
475 $err_num = substr($line, 0, strpos($line, " "));
477 case 500: $message = 'Syntax error; command not recognized';
480 case 501: $message = 'Syntax error in parameters or arguments';
483 case 502: $message = 'Command not implemented';
486 case 503: $message = 'Bad sequence of commands';
489 case 504: $message = 'Command parameter not implemented';
494 case 211: $message = 'System status, or system help reply';
497 case 214: $message = 'Help message';
502 case 220: $message = 'Service ready';
505 case 221: $message = 'Service closing transmission channel';
508 case 421: $message = 'Service not available, closing chanel';
512 case 235: return(5); break;
513 case 250: $message = 'Requested mail action okay, completed';
516 case 251: $message = 'User not local; will forward';
519 case 334: return(5); break;
520 case 450: $message = 'Requested mail action not taken: mailbox unavailable';
523 case 550: $message = 'Requested action not taken: mailbox unavailable';
526 case 451: $message = 'Requested action aborted: error in processing';
529 case 551: $message = 'User not local; please try forwarding';
532 case 452: $message = 'Requested action not taken: insufficient system storage';
535 case 552: $message = 'Requested mail action aborted: exceeding storage allocation';
538 case 553: $message = 'Requested action not taken: mailbox name not allowed';
541 case 354: $message = 'Start mail input; end with .';
544 case 554: $message = 'Transaction failed';
547 default: $message = 'Unknown response: '. nl2br(htmlspecialchars($lines));
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);
560 if (! $verbose) return $status;
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();
569 $imap_stream = sqimap_login($username, $key, $imapServerAddress, $imapPort, 1);
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');
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
;
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);
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);
598 $length = sendSendmail($t, $c, $b, $subject, $body, $more_headers);
600 $length = sendSMTP($t, $c, $b, $subject, $body, $more_headers);
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);
609 sqimap_logout($imap_stream);
610 // Delete the files uploaded for attaching (if any).
611 // only if $length != 0 (if there was no error)