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 // echo "<pre>Attachment Info:\n";
82 if (isset($info['type']))
83 $filetype = $info['type'];
85 $filetype = 'application/octet-stream';
87 $header = '--'.mimeBoundary()."\r\n";
88 $header .= "Content-Type: $filetype; name=\"" .
89 $info['remotefilename'] . "\"\r\n";
90 $header .= "Content-Disposition: attachment; filename=\"" .
91 $info['remotefilename'] . "\"\r\n";
93 $file = fopen ($attachment_dir . $info['localfilename'], 'r');
94 if (substr($filetype, 0, 5) == 'text/' ||
95 $filetype == 'message/rfc822') {
98 $length +
= strlen($header);
99 while ($tmp = fgets($file, 4096)) {
100 $tmp = str_replace("\r\n", "\n", $tmp);
101 $tmp = str_replace("\r", "\n", $tmp);
102 $tmp = str_replace("\n", "\r\n", $tmp);
103 if (feof($fp) && substr($tmp, -2) != "\r\n")
106 $length +
= strlen($tmp);
109 $header .= "Content-Transfer-Encoding: base64\r\n\r\n";
110 fputs ($fp, $header);
111 $length +
= strlen($header);
112 while ($tmp = fread($file, 570)) {
113 $encoded = chunk_split(base64_encode($tmp));
114 $length +
= strlen($encoded);
115 fputs ($fp, $encoded);
125 // Delete files that are uploaded for attaching
126 function deleteAttachments() {
127 global $attachments, $attachment_dir;
131 while (list($localname, $remotename) = each($attachments)) {
132 if (!ereg ("\\/", $localname)) {
133 unlink ($attachment_dir.$localname);
134 unlink ($attachment_dir.$localname.'.info');
140 // Return a nice MIME-boundary
141 function mimeBoundary () {
142 static $mimeBoundaryString;
144 if ($mimeBoundaryString == "") {
145 $mimeBoundaryString = "----=_" .
146 GenerateRandomString(60, '\'()+,-./:=?_', 7);
149 return $mimeBoundaryString;
152 /* Time offset for correct timezone */
153 function timezone () {
156 $diff_second = date('Z');
158 $diff_second = - $diff_second;
159 if ($diff_second > 0)
164 $diff_second = abs($diff_second);
166 $diff_hour = floor ($diff_second / 3600);
167 $diff_minute = floor (($diff_second-3600*$diff_hour) / 60);
169 $zonename = '('.strftime('%Z').')';
170 $result = sprintf ("%s%02d%02d %s", $sign, $diff_hour, $diff_minute, $zonename);
174 /* Print all the needed RFC822 headers */
175 function write822Header ($fp, $t, $c, $b, $subject, $more_headers) {
176 global $REMOTE_ADDR, $SERVER_NAME, $REMOTE_PORT;
177 global $data_dir, $username, $popuser, $domain, $version, $useSendmail;
178 global $default_charset, $HTTP_VIA, $HTTP_X_FORWARDED_FOR;
179 global $REMOTE_HOST, $identity;
181 // Storing the header to make sure the header is the same
182 // everytime the header is printed.
183 static $header, $headerlength;
186 $to = expandAddrs(parseAddrs($t));
187 $cc = expandAddrs(parseAddrs($c));
188 $bcc = expandAddrs(parseAddrs($b));
189 if (isset($identity) && $identity != 'default')
191 $reply_to = getPref($data_dir, $username, 'reply_to' . $identity);
192 $from = getPref($data_dir, $username, 'full_name' . $identity);
193 $from_addr = getPref($data_dir, $username, 'email_address' . $identity);
197 $reply_to = getPref($data_dir, $username, 'reply_to');
198 $from = getPref($data_dir, $username, 'full_name');
199 $from_addr = getPref($data_dir, $username, 'email_address');
202 if ($from_addr == '')
203 $from_addr = $popuser.'@'.$domain;
205 $to_list = getLineOfAddrs($to);
206 $cc_list = getLineOfAddrs($cc);
207 $bcc_list = getLineOfAddrs($bcc);
209 /* Encoding 8-bit characters and making from line */
210 $subject = encodeHeader($subject);
212 $from = "<$from_addr>";
214 $from = '"' . encodeHeader($from) . "\" <$from_addr>";
216 /* This creates an RFC 822 date */
217 $date = date("D, j M Y H:i:s ", mktime()) . timezone();
219 /* Create a message-id */
220 $message_id = '<' . $REMOTE_PORT . '.' . $REMOTE_ADDR . '.';
221 $message_id .= time() . '.squirrel@' . $SERVER_NAME .'>';
223 /* Make an RFC822 Received: line */
224 if (isset($REMOTE_HOST))
225 $received_from = "$REMOTE_HOST ([$REMOTE_ADDR])";
227 $received_from = $REMOTE_ADDR;
229 if (isset($HTTP_VIA) ||
isset ($HTTP_X_FORWARDED_FOR)) {
230 if ($HTTP_X_FORWARDED_FOR == '')
231 $HTTP_X_FORWARDED_FOR = 'unknown';
232 $received_from .= " (proxying for $HTTP_X_FORWARDED_FOR)";
235 $header = "Received: from $received_from\r\n";
236 $header .= " (SquirrelMail authenticated user $username)\r\n";
237 $header .= " by $SERVER_NAME with HTTP;\r\n";
238 $header .= " $date\r\n";
240 /* Insert the rest of the header fields */
241 $header .= "Message-ID: $message_id\r\n";
242 $header .= "Date: $date\r\n";
243 $header .= "Subject: $subject\r\n";
244 $header .= "From: $from\r\n";
245 $header .= "To: $to_list\r\n"; // Who it's TO
247 /* Insert headers from the $more_headers array */
248 if(is_array($more_headers)) {
249 reset($more_headers);
250 while(list($h_name, $h_val) = each($more_headers)) {
251 $header .= sprintf("%s: %s\r\n", $h_name, $h_val);
256 $header .= "Cc: $cc_list\r\n"; // Who the CCs are
260 $header .= "Reply-To: $reply_to\r\n";
264 // BCCs is removed from header by sendmail
265 $header .= "Bcc: $bcc_list\r\n";
269 $header .= "X-Mailer: SquirrelMail (version $version)\r\n"; // Identify SquirrelMail
272 $header .= "MIME-Version: 1.0\r\n";
275 $header .= 'Content-Type: multipart/mixed; boundary="';
276 $header .= mimeBoundary();
279 if ($default_charset != '')
280 $header .= "Content-Type: text/plain; charset=$default_charset\r\n";
282 $header .= "Content-Type: text/plain;\r\n";
283 $header .= "Content-Transfer-Encoding: 8bit\r\n";
285 $header .= "\r\n"; // One blank line to separate header and body
287 $headerlength = strlen($header);
291 fputs ($fp, $header);
293 return $headerlength;
297 function writeBody ($fp, $passedBody) {
298 global $default_charset;
300 $attachmentlength = 0;
303 $body = '--'.mimeBoundary()."\r\n";
305 if ($default_charset != "")
306 $body .= "Content-Type: text/plain; charset=$default_charset\r\n";
308 $body .= "Content-Type: text/plain\r\n";
310 $body .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
311 $body .= $passedBody . "\r\n\r\n";
314 $attachmentlength = attachFiles($fp);
316 if (!isset($postbody)) $postbody = "";
317 $postbody .= "\r\n--".mimeBoundary()."--\r\n\r\n";
318 fputs ($fp, $postbody);
320 $body = $passedBody . "\r\n";
323 fputs ($fp, $postbody);
326 return (strlen($body) +
strlen($postbody) +
$attachmentlength);
329 // Send mail using the sendmail command
330 function sendSendmail($t, $c, $b, $subject, $body, $more_headers) {
331 global $sendmail_path, $popuser, $username, $domain;
333 // Build envelope sender address. Make sure it doesn't contain
334 // spaces or other "weird" chars that would allow a user to
335 // exploit the shell/pipe it is used in.
336 $envelopefrom = "$popuser@$domain";
337 $envelopefrom = ereg_replace("[[:blank:]]",'', $envelopefrom);
338 $envelopefrom = ereg_replace("[[:space:]]",'', $envelopefrom);
339 $envelopefrom = ereg_replace("[[:cntrl:]]",'', $envelopefrom);
341 // open pipe to sendmail
342 $fp = popen (escapeshellcmd("$sendmail_path -t -f$envelopefrom"), 'w');
344 $headerlength = write822Header ($fp, $t, $c, $b, $subject, $more_headers);
345 $bodylength = writeBody($fp, $body);
349 return ($headerlength +
$bodylength);
352 function smtpReadData($smtpConnection) {
353 $read = fgets($smtpConnection, 1024);
357 $data[$counter] = $read;
358 $read = fgets($smtpConnection, 1024);
363 function sendSMTP($t, $c, $b, $subject, $body, $more_headers) {
364 global $username, $popuser, $domain, $version, $smtpServerAddress, $smtpPort,
365 $data_dir, $color, $use_authenticated_smtp, $identity;
367 $to = expandAddrs(parseAddrs($t));
368 $cc = expandAddrs(parseAddrs($c));
369 $bcc = expandAddrs(parseAddrs($b));
370 if (isset($identity) && $identity != 'default')
371 $from_addr = getPref($data_dir, $username, 'email_address' . $identity);
373 $from_addr = getPref($data_dir, $username, 'email_address');
376 $from_addr = "$popuser@$domain";
378 $smtpConnection = fsockopen($smtpServerAddress, $smtpPort, $errorNumber, $errorString);
379 if (!$smtpConnection) {
380 echo 'Error connecting to SMTP Server.<br>';
381 echo "$errorNumber : $errorString<br>";
384 $tmp = fgets($smtpConnection, 1024);
385 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
387 $to_list = getLineOfAddrs($to);
388 $cc_list = getLineOfAddrs($cc);
390 /** Lets introduce ourselves */
391 if (! isset ($use_authenticated_smtp) ||
$use_authenticated_smtp == false) {
392 fputs($smtpConnection, "HELO $domain\r\n");
393 $tmp = fgets($smtpConnection, 1024);
394 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
396 fputs($smtpConnection, "EHLO $domain\r\n");
397 $tmp = fgets($smtpConnection, 1024);
398 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
400 fputs($smtpConnection, "AUTH LOGIN\r\n");
401 $tmp = fgets($smtpConnection, 1024);
402 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
404 fputs($smtpConnection, base64_encode ($username) . "\r\n");
405 $tmp = fgets($smtpConnection, 1024);
406 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
408 fputs($smtpConnection, base64_encode (OneTimePadDecrypt($key, $onetimepad)) . "\r\n");
409 $tmp = fgets($smtpConnection, 1024);
410 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
413 /** Ok, who is sending the message? */
414 fputs($smtpConnection, "MAIL FROM: <$from_addr>\r\n");
415 $tmp = fgets($smtpConnection, 1024);
416 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
418 /** send who the recipients are */
419 for ($i = 0; $i < count($to); $i++
) {
420 fputs($smtpConnection, "RCPT TO: $to[$i]\r\n");
421 $tmp = fgets($smtpConnection, 1024);
422 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
424 for ($i = 0; $i < count($cc); $i++
) {
425 fputs($smtpConnection, "RCPT TO: $cc[$i]\r\n");
426 $tmp = fgets($smtpConnection, 1024);
427 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
429 for ($i = 0; $i < count($bcc); $i++
) {
430 fputs($smtpConnection, "RCPT TO: $bcc[$i]\r\n");
431 $tmp = fgets($smtpConnection, 1024);
432 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
435 /** Lets start sending the actual message */
436 fputs($smtpConnection, "DATA\r\n");
437 $tmp = fgets($smtpConnection, 1024);
438 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
441 $headerlength = write822Header ($smtpConnection, $t, $c, $b, $subject, $more_headers);
442 $bodylength = writeBody($smtpConnection, $body);
444 fputs($smtpConnection, ".\r\n"); // end the DATA part
445 $tmp = fgets($smtpConnection, 1024);
446 $num = errorCheck($tmp, $smtpConnection, true);
448 $tmp = nl2br(htmlspecialchars($tmp));
449 displayPageHeader($color, 'None');
450 include ("../functions/display_messages.php");
451 $msg = "Message not sent!<br>\nReason given: $tmp";
452 plain_error_message($msg, $color);
456 fputs($smtpConnection, "QUIT\r\n"); // log off
458 fclose($smtpConnection);
460 return ($headerlength +
$bodylength);
464 function errorCheck($line, $smtpConnection, $verbose = false) {
466 include '../functions/page_header.php';
468 // Read new lines on a multiline response
470 while(ereg("^[0-9]+-", $line)) {
471 $line = fgets($smtpConnection, 1024);
478 $err_num = substr($line, 0, strpos($line, " "));
480 case 500: $message = 'Syntax error; command not recognized';
483 case 501: $message = 'Syntax error in parameters or arguments';
486 case 502: $message = 'Command not implemented';
489 case 503: $message = 'Bad sequence of commands';
492 case 504: $message = 'Command parameter not implemented';
497 case 211: $message = 'System status, or system help reply';
500 case 214: $message = 'Help message';
505 case 220: $message = 'Service ready';
508 case 221: $message = 'Service closing transmission channel';
511 case 421: $message = 'Service not available, closing chanel';
515 case 235: return(5); break;
516 case 250: $message = 'Requested mail action okay, completed';
519 case 251: $message = 'User not local; will forward';
522 case 334: return(5); break;
523 case 450: $message = 'Requested mail action not taken: mailbox unavailable';
526 case 550: $message = 'Requested action not taken: mailbox unavailable';
529 case 451: $message = 'Requested action aborted: error in processing';
532 case 551: $message = 'User not local; please try forwarding';
535 case 452: $message = 'Requested action not taken: insufficient system storage';
538 case 552: $message = 'Requested mail action aborted: exceeding storage allocation';
541 case 553: $message = 'Requested action not taken: mailbox name not allowed';
544 case 354: $message = 'Start mail input; end with .';
547 case 554: $message = 'Transaction failed';
550 default: $message = 'Unknown response: '. nl2br(htmlspecialchars($lines));
557 displayPageHeader($color, 'None');
558 include ("../functions/display_messages.php");
559 $lines = nl2br(htmlspecialchars($lines));
560 $msg = $message . "<br>\nServer replied: $lines";
561 plain_error_message($msg, $color);
563 if (! $verbose) return $status;
567 function sendMessage($t, $c, $b, $subject, $body, $reply_id) {
568 global $useSendmail, $msg_id, $is_reply, $mailbox, $onetimepad;
569 global $data_dir, $username, $domain, $key, $version, $sent_folder, $imapServerAddress, $imapPort;
570 $more_headers = Array();
572 $imap_stream = sqimap_login($username, $key, $imapServerAddress, $imapPort, 1);
574 if (isset($reply_id) && $reply_id) {
575 sqimap_mailbox_select ($imap_stream, $mailbox);
576 sqimap_messages_flag ($imap_stream, $reply_id, $reply_id, 'Answered');
578 // Insert In-Reply-To and References headers if the
579 // message-id of the message we reply to is set (longer than "<>")
580 // The References header should really be the old Referenced header
581 // with the message ID appended, but it can be only the message ID too.
582 $hdr = sqimap_get_small_header ($imap_stream, $reply_id, false);
583 if(strlen($hdr->message_id
) > 2) {
584 $more_headers['In-Reply-To'] = $hdr->message_id
;
585 $more_headers['References'] = $hdr->message_id
;
589 // In order to remove the problem of users not able to create
590 // messages with "." on a blank line, RFC821 has made provision
591 // in section 4.5.2 (Transparency).
592 $body = ereg_replace("\n\\.", "\n..", $body);
593 $body = ereg_replace("^\\.", "..", $body);
595 // this is to catch all plain \n instances and
596 // replace them with \r\n.
597 $body = ereg_replace("\r\n", "\n", $body);
598 $body = ereg_replace("\n", "\r\n", $body);
601 $length = sendSendmail($t, $c, $b, $subject, $body, $more_headers);
603 $length = sendSMTP($t, $c, $b, $subject, $body, $more_headers);
606 if (sqimap_mailbox_exists ($imap_stream, $sent_folder)) {
607 sqimap_append ($imap_stream, $sent_folder, $length);
608 write822Header ($imap_stream, $t, $c, $b, $subject, $more_headers);
609 writeBody ($imap_stream, $body);
610 sqimap_append_done ($imap_stream);
612 sqimap_logout($imap_stream);
613 // Delete the files uploaded for attaching (if any).
614 // only if $length != 0 (if there was no error)