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 function expandAddrs ($array) {
43 $abook = addressbook_init();
44 for ($i=0; $i < count($array); $i++
) {
45 $result = $abook->lookup($array[$i]);
47 if (isset($result['email'])) {
48 if (isset($result['name'])) {
49 $ret = '"'.$result['name'].'" ';
51 $ret .= '<'.$result['email'].'>';
56 $array[$i] = '<' . $array[$i] . '>';
62 // Attach the files that are due to be attached
63 function attachFiles ($fp) {
64 global $attachments, $attachment_dir;
69 foreach ($attachments as $info)
71 if (isset($info['type']))
72 $filetype = $info['type'];
74 $filetype = 'application/octet-stream';
76 $header = '--'.mimeBoundary()."\r\n";
77 $header .= "Content-Type: $filetype; name=\"" .
78 $info['remotefilename'] . "\"\r\n";
79 $header .= "Content-Disposition: attachment; filename=\"" .
80 $info['remotefilename'] . "\"\r\n";
81 $header .= "Content-Transfer-Encoding: base64\r\n\r\n";
83 $length +
= strlen($header);
85 $file = fopen ($attachment_dir . $info['localfilename'], 'r');
86 while ($tmp = fread($file, 570)) {
87 $encoded = chunk_split(base64_encode($tmp));
88 $length +
= strlen($encoded);
89 fputs ($fp, $encoded);
98 // Delete files that are uploaded for attaching
99 function deleteAttachments() {
100 global $attachments, $attachment_dir;
104 while (list($localname, $remotename) = each($attachments)) {
105 if (!ereg ("\\/", $localname)) {
106 unlink ($attachment_dir.$localname);
107 unlink ($attachment_dir.$localname.'.info');
113 // Return a nice MIME-boundary
114 function mimeBoundary () {
115 static $mimeBoundaryString;
117 if ($mimeBoundaryString == "") {
118 $mimeBoundaryString = "----=_" .
119 GenerateRandomString(60, '\'()+,-./:=?_', 7);
122 return $mimeBoundaryString;
125 /* Time offset for correct timezone */
126 function timezone () {
129 $diff_second = date('Z');
131 $diff_second = - $diff_second;
132 if ($diff_second > 0)
137 $diff_second = abs($diff_second);
139 $diff_hour = floor ($diff_second / 3600);
140 $diff_minute = floor (($diff_second-3600*$diff_hour) / 60);
142 $zonename = '('.strftime('%Z').')';
143 $result = sprintf ("%s%02d%02d %s", $sign, $diff_hour, $diff_minute, $zonename);
147 /* Print all the needed RFC822 headers */
148 function write822Header ($fp, $t, $c, $b, $subject, $more_headers) {
149 global $REMOTE_ADDR, $SERVER_NAME, $REMOTE_PORT;
150 global $data_dir, $username, $popuser, $domain, $version, $useSendmail;
151 global $default_charset, $HTTP_VIA, $HTTP_X_FORWARDED_FOR;
154 // Storing the header to make sure the header is the same
155 // everytime the header is printed.
156 static $header, $headerlength;
159 $to = expandAddrs(parseAddrs($t));
160 $cc = expandAddrs(parseAddrs($c));
161 $bcc = expandAddrs(parseAddrs($b));
162 $reply_to = getPref($data_dir, $username, 'reply_to');
163 $from = getPref($data_dir, $username, 'full_name');
164 $from_addr = getPref($data_dir, $username, 'email_address');
166 if ($from_addr == '')
167 $from_addr = $popuser.'@'.$domain;
169 $to_list = getLineOfAddrs($to);
170 $cc_list = getLineOfAddrs($cc);
171 $bcc_list = getLineOfAddrs($bcc);
173 /* Encoding 8-bit characters and making from line */
174 $subject = encodeHeader($subject);
176 $from = "<$from_addr>";
178 $from = '"' . encodeHeader($from) . "\" <$from_addr>";
180 /* This creates an RFC 822 date */
181 $date = date("D, j M Y H:i:s ", mktime()) . timezone();
183 /* Create a message-id */
184 $message_id = '<' . $REMOTE_PORT . '.' . $REMOTE_ADDR . '.';
185 $message_id .= time() . '.squirrel@' . $SERVER_NAME .'>';
187 /* Make an RFC822 Received: line */
188 if (isset($REMOTE_HOST))
189 $received_from = "$REMOTE_HOST ([$REMOTE_ADDR])";
191 $received_from = $REMOTE_ADDR;
193 if (isset($HTTP_VIA) ||
isset ($HTTP_X_FORWARDED_FOR)) {
194 if ($HTTP_X_FORWARDED_FOR == '')
195 $HTTP_X_FORWARDED_FOR = 'unknown';
196 $received_from .= " (proxying for $HTTP_X_FORWARDED_FOR)";
199 $header = "Received: from $received_from\r\n";
200 $header .= " (SquirrelMail authenticated user $username)\r\n";
201 $header .= " by $SERVER_NAME with HTTP;\r\n";
202 $header .= " $date\r\n";
204 /* Insert the rest of the header fields */
205 $header .= "Message-ID: $message_id\r\n";
206 $header .= "Date: $date\r\n";
207 $header .= "Subject: $subject\r\n";
208 $header .= "From: $from\r\n";
209 $header .= "To: $to_list\r\n"; // Who it's TO
211 /* Insert headers from the $more_headers array */
212 if(is_array($more_headers)) {
213 reset($more_headers);
214 while(list($h_name, $h_val) = each($more_headers)) {
215 $header .= sprintf("%s: %s\r\n", $h_name, $h_val);
220 $header .= "Cc: $cc_list\r\n"; // Who the CCs are
224 $header .= "Reply-To: $reply_to\r\n";
228 // BCCs is removed from header by sendmail
229 $header .= "Bcc: $bcc_list\r\n";
233 $header .= "X-Mailer: SquirrelMail (version $version)\r\n"; // Identify SquirrelMail
236 $header .= "MIME-Version: 1.0\r\n";
239 $header .= 'Content-Type: multipart/mixed; boundary="';
240 $header .= mimeBoundary();
243 if ($default_charset != '')
244 $header .= "Content-Type: text/plain; charset=$default_charset\r\n";
246 $header .= "Content-Type: text/plain;\r\n";
247 $header .= "Content-Transfer-Encoding: 8bit\r\n";
249 $header .= "\r\n"; // One blank line to separate header and body
251 $headerlength = strlen($header);
255 fputs ($fp, $header);
257 return $headerlength;
261 function writeBody ($fp, $passedBody) {
262 global $default_charset;
264 $attachmentlength = 0;
267 $body = '--'.mimeBoundary()."\r\n";
269 if ($default_charset != "")
270 $body .= "Content-Type: text/plain; charset=$default_charset\r\n";
272 $body .= "Content-Type: text/plain\r\n";
274 $body .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
275 $body .= $passedBody . "\r\n\r\n";
278 $attachmentlength = attachFiles($fp);
280 if (!isset($postbody)) $postbody = "";
281 $postbody .= "\r\n--".mimeBoundary()."--\r\n\r\n";
282 fputs ($fp, $postbody);
284 $body = $passedBody . "\r\n";
287 fputs ($fp, $postbody);
290 return (strlen($body) +
strlen($postbody) +
$attachmentlength);
293 // Send mail using the sendmail command
294 function sendSendmail($t, $c, $b, $subject, $body, $more_headers) {
295 global $sendmail_path, $popuser, $username, $domain;
297 // Build envelope sender address. Make sure it doesn't contain
298 // spaces or other "weird" chars that would allow a user to
299 // exploit the shell/pipe it is used in.
300 $envelopefrom = "$popuser@$domain";
301 $envelopefrom = ereg_replace("[[:blank:]]",'', $envelopefrom);
302 $envelopefrom = ereg_replace("[[:space:]]",'', $envelopefrom);
303 $envelopefrom = ereg_replace("[[:cntrl:]]",'', $envelopefrom);
305 // open pipe to sendmail
306 $fp = popen (escapeshellcmd("$sendmail_path -t -f$envelopefrom"), 'w');
308 $headerlength = write822Header ($fp, $t, $c, $b, $subject, $more_headers);
309 $bodylength = writeBody($fp, $body);
313 return ($headerlength +
$bodylength);
316 function smtpReadData($smtpConnection) {
317 $read = fgets($smtpConnection, 1024);
321 $data[$counter] = $read;
322 $read = fgets($smtpConnection, 1024);
327 function sendSMTP($t, $c, $b, $subject, $body, $more_headers) {
328 global $username, $popuser, $domain, $version, $smtpServerAddress, $smtpPort,
329 $data_dir, $color, $use_authenticated_smtp;
331 $to = expandAddrs(parseAddrs($t));
332 $cc = expandAddrs(parseAddrs($c));
333 $bcc = expandAddrs(parseAddrs($b));
334 $from_addr = getPref($data_dir, $username, 'email_address');
337 $from_addr = "$popuser@$domain";
339 $smtpConnection = fsockopen($smtpServerAddress, $smtpPort, $errorNumber, $errorString);
340 if (!$smtpConnection) {
341 echo 'Error connecting to SMTP Server.<br>';
342 echo "$errorNumber : $errorString<br>";
345 $tmp = fgets($smtpConnection, 1024);
346 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
348 $to_list = getLineOfAddrs($to);
349 $cc_list = getLineOfAddrs($cc);
351 /** Lets introduce ourselves */
352 if (! isset ($use_authenticated_smtp) ||
$use_authenticated_smtp == false) {
353 fputs($smtpConnection, "HELO $domain\r\n");
354 $tmp = fgets($smtpConnection, 1024);
355 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
357 fputs($smtpConnection, "EHLO $domain\r\n");
358 $tmp = fgets($smtpConnection, 1024);
359 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
361 fputs($smtpConnection, "AUTH LOGIN\r\n");
362 $tmp = fgets($smtpConnection, 1024);
363 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
365 fputs($smtpConnection, base64_encode ($username) . "\r\n");
366 $tmp = fgets($smtpConnection, 1024);
367 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
369 fputs($smtpConnection, base64_encode ($OneTimePadDecrypt($key, $onetimepad)) . "\r\n");
370 $tmp = fgets($smtpConnection, 1024);
371 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
374 /** Ok, who is sending the message? */
375 fputs($smtpConnection, "MAIL FROM: <$from_addr>\r\n");
376 $tmp = fgets($smtpConnection, 1024);
377 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
379 /** send who the recipients are */
380 for ($i = 0; $i < count($to); $i++
) {
381 fputs($smtpConnection, "RCPT TO: $to[$i]\r\n");
382 $tmp = fgets($smtpConnection, 1024);
383 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
385 for ($i = 0; $i < count($cc); $i++
) {
386 fputs($smtpConnection, "RCPT TO: $cc[$i]\r\n");
387 $tmp = fgets($smtpConnection, 1024);
388 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
390 for ($i = 0; $i < count($bcc); $i++
) {
391 fputs($smtpConnection, "RCPT TO: $bcc[$i]\r\n");
392 $tmp = fgets($smtpConnection, 1024);
393 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
396 /** Lets start sending the actual message */
397 fputs($smtpConnection, "DATA\r\n");
398 $tmp = fgets($smtpConnection, 1024);
399 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
402 $headerlength = write822Header ($smtpConnection, $t, $c, $b, $subject, $more_headers);
403 $bodylength = writeBody($smtpConnection, $body);
405 fputs($smtpConnection, ".\r\n"); // end the DATA part
406 $tmp = fgets($smtpConnection, 1024);
407 $num = errorCheck($tmp, $smtpConnection, true);
409 $tmp = nl2br(htmlspecialchars($tmp));
410 displayPageHeader($color, 'None');
411 include ("../functions/display_messages.php");
412 $msg = "Message not sent!<br>\nReason given: $tmp";
413 plain_error_message($msg, $color);
417 fputs($smtpConnection, "QUIT\r\n"); // log off
419 fclose($smtpConnection);
421 return ($headerlength +
$bodylength);
425 function errorCheck($line, $smtpConnection, $verbose = false) {
427 include '../functions/page_header.php';
429 // Read new lines on a multiline response
431 while(ereg("^[0-9]+-", $line)) {
432 $line = fgets($smtpConnection, 1024);
439 $err_num = substr($line, 0, strpos($line, " "));
441 case 500: $message = 'Syntax error; command not recognized';
444 case 501: $message = 'Syntax error in parameters or arguments';
447 case 502: $message = 'Command not implemented';
450 case 503: $message = 'Bad sequence of commands';
453 case 504: $message = 'Command parameter not implemented';
458 case 211: $message = 'System status, or system help reply';
461 case 214: $message = 'Help message';
466 case 220: $message = 'Service ready';
469 case 221: $message = 'Service closing transmission channel';
472 case 421: $message = 'Service not available, closing chanel';
476 case 235: return(5); break;
477 case 250: $message = 'Requested mail action okay, completed';
480 case 251: $message = 'User not local; will forward';
483 case 334: return(5); break;
484 case 450: $message = 'Requested mail action not taken: mailbox unavailable';
487 case 550: $message = 'Requested action not taken: mailbox unavailable';
490 case 451: $message = 'Requested action aborted: error in processing';
493 case 551: $message = 'User not local; please try forwarding';
496 case 452: $message = 'Requested action not taken: insufficient system storage';
499 case 552: $message = 'Requested mail action aborted: exceeding storage allocation';
502 case 553: $message = 'Requested action not taken: mailbox name not allowed';
505 case 354: $message = 'Start mail input; end with .';
508 case 554: $message = 'Transaction failed';
511 default: $message = 'Unknown response: '. nl2br(htmlspecialchars($lines));
518 displayPageHeader($color, 'None');
519 include ("../functions/display_messages.php");
520 $lines = nl2br(htmlspecialchars($lines));
521 $msg = $message . "<br>\nServer replied: $lines";
522 plain_error_message($msg, $color);
524 if (! $verbose) return $status;
528 function sendMessage($t, $c, $b, $subject, $body, $reply_id) {
529 global $useSendmail, $msg_id, $is_reply, $mailbox, $onetimepad;
530 global $data_dir, $username, $domain, $key, $version, $sent_folder, $imapServerAddress, $imapPort;
531 $more_headers = Array();
533 $imap_stream = sqimap_login($username, $key, $imapServerAddress, $imapPort, 1);
535 if (isset($reply_id) && $reply_id) {
536 sqimap_mailbox_select ($imap_stream, $mailbox);
537 sqimap_messages_flag ($imap_stream, $reply_id, $reply_id, 'Answered');
539 // Insert In-Reply-To and References headers if the
540 // message-id of the message we reply to is set (longer than "<>")
541 // The References header should really be the old Referenced header
542 // with the message ID appended, but it can be only the message ID too.
543 $hdr = sqimap_get_small_header ($imap_stream, $reply_id, false);
544 if(strlen($hdr->message_id
) > 2) {
545 $more_headers['In-Reply-To'] = $hdr->message_id
;
546 $more_headers['References'] = $hdr->message_id
;
550 // In order to remove the problem of users not able to create
551 // messages with "." on a blank line, RFC821 has made provision
552 // in section 4.5.2 (Transparency).
553 $body = ereg_replace("\n\\.", "\n..", $body);
554 $body = ereg_replace("^\\.", "..", $body);
556 // this is to catch all plain \n instances and
557 // replace them with \r\n.
558 $body = ereg_replace("\r\n", "\n", $body);
559 $body = ereg_replace("\n", "\r\n", $body);
562 $length = sendSendmail($t, $c, $b, $subject, $body, $more_headers);
564 $length = sendSMTP($t, $c, $b, $subject, $body, $more_headers);
567 if (sqimap_mailbox_exists ($imap_stream, $sent_folder)) {
568 sqimap_append ($imap_stream, $sent_folder, $length);
569 write822Header ($imap_stream, $t, $c, $b, $subject, $more_headers);
570 writeBody ($imap_stream, $body);
571 sqimap_append_done ($imap_stream);
573 sqimap_logout($imap_stream);
574 // Delete the files uploaded for attaching (if any).
575 // only if $length != 0 (if there was no error)