36b7751a71a56b1c3b11b17f56d85473c0afb999
4 ** This contains all the functions needed to send messages through
5 ** an smtp server or sendmail.
11 if (!isset($addressbook_php))
12 include('../functions/addressbook.php');
14 // This should most probably go to some initialization...
15 if (ereg("^([^@%/]+)[@%/](.+)$", $username, $usernamedata)) {
16 $popuser = $usernamedata[1];
17 $domain = $usernamedata[2];
22 // We need domain for smtp
24 $domain = getenv('HOSTNAME');
26 // Returns true only if this message is multipart
27 function isMultipart () {
30 if (count($attachments)>0)
36 // looks up aliases in the addressbook and expands them to
38 function expandAddrs ($array) {
39 $abook = addressbook_init();
40 for ($i=0; $i < count($array); $i++
) {
41 $result = $abook->lookup($array[$i]);
43 if (isset($result['email'])) {
44 if (isset($result['name'])) {
45 $ret = '"'.$result['name'].'" ';
47 $ret .= '<'.$result['email'].'>';
54 // Attach the files that are due to be attached
55 function attachFiles ($fp) {
56 global $attachments, $attachment_dir;
62 while (list($localname, $remotename) = each($attachments)) {
63 // This is to make sure noone is giving a filename in another
65 $localname = ereg_replace ("\\/", '', $localname);
67 $fileinfo = fopen ($attachment_dir.$localname.'.info', 'r');
68 $filetype = fgets ($fileinfo, 8192);
70 $filetype = trim ($filetype);
72 $filetype = 'application/octet-stream';
74 $header = '--'.mimeBoundary()."\r\n";
75 $header .= "Content-Type: $filetype;name=\"$remotename\"\r\n";
76 $header .= "Content-Disposition: attachment; filename=\"$remotename\"\r\n";
77 $header .= "Content-Transfer-Encoding: base64\r\n\r\n";
79 $length +
= strlen($header);
81 $file = fopen ($attachment_dir.$localname, 'r');
82 while ($tmp = fread($file, 570)) {
83 $encoded = chunk_split(base64_encode($tmp));
84 $length +
= strlen($encoded);
85 fputs ($fp, $encoded);
94 // Delete files that are uploaded for attaching
95 function deleteAttachments() {
96 global $attachments, $attachment_dir;
100 while (list($localname, $remotename) = each($attachments)) {
101 if (!ereg ("\\/", $localname)) {
102 unlink ($attachment_dir.$localname);
103 unlink ($attachment_dir.$localname.'.info');
109 // Return a nice MIME-boundary
110 function mimeBoundary () {
111 static $mimeBoundaryString;
113 if ($mimeBoundaryString == "") {
114 $mimeBoundaryString = "----=" .
115 GenerateRandomString(60, '\'()+,-./:=?_', 7);
118 return $mimeBoundaryString;
121 /* Time offset for correct timezone */
122 function timezone () {
125 $diff_second = date('Z');
127 $diff_second = - $diff_second;
128 if ($diff_second > 0)
133 $diff_second = abs($diff_second);
135 $diff_hour = floor ($diff_second / 3600);
136 $diff_minute = floor (($diff_second-3600*$diff_hour) / 60);
138 $zonename = '('.strftime('%Z').')';
139 $result = sprintf ("%s%02d%02d %s", $sign, $diff_hour, $diff_minute, $zonename);
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;
150 // Storing the header to make sure the header is the same
151 // everytime the header is printed.
152 static $header, $headerlength;
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');
162 if ($from_addr == '')
163 $from_addr = $popuser.'@'.$domain;
165 $to_list = getLineOfAddrs($to);
166 $cc_list = getLineOfAddrs($cc);
167 $bcc_list = getLineOfAddrs($bcc);
169 /* Encoding 8-bit characters and making from line */
170 $subject = encodeHeader($subject);
172 $from = "<$from_addr>";
174 $from = '"' . encodeHeader($from) . "\" <$from_addr>";
176 /* This creates an RFC 822 date */
177 $date = date("D, j M Y H:i:s ", mktime()) . timezone();
179 /* Create a message-id */
180 $message_id = '<' . $REMOTE_PORT . '.' . $REMOTE_ADDR . '.';
181 $message_id .= time() . '.squirrel@' . $SERVER_NAME .'>';
183 /* Make an RFC822 Received: line */
184 if (isset($REMOTE_HOST))
185 $received_from = "$REMOTE_HOST ([$REMOTE_ADDR])";
187 $received_from = $REMOTE_ADDR;
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)";
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";
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
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);
216 $header .= "Cc: $cc_list\r\n"; // Who the CCs are
220 $header .= "Reply-To: $reply_to\r\n";
224 // BCCs is removed from header by sendmail
225 $header .= "Bcc: $bcc_list\r\n";
229 $header .= "X-Mailer: SquirrelMail (version $version)\r\n"; // Identify SquirrelMail
232 $header .= "MIME-Version: 1.0\r\n";
235 $header .= 'Content-Type: multipart/mixed; boundary="';
236 $header .= mimeBoundary();
239 if ($default_charset != '')
240 $header .= "Content-Type: text/plain; charset=$default_charset\r\n";
242 $header .= "Content-Type: text/plain;\r\n";
243 $header .= "Content-Transfer-Encoding: 8bit\r\n";
245 $header .= "\r\n"; // One blank line to separate header and body
247 $headerlength = strlen($header);
251 fputs ($fp, $header);
253 return $headerlength;
257 function writeBody ($fp, $passedBody) {
258 global $default_charset;
260 $attachmentlength = 0;
263 $body = '--'.mimeBoundary()."\r\n";
265 if ($default_charset != "")
266 $body .= "Content-Type: text/plain; charset=$default_charset\r\n";
268 $body .= "Content-Type: text/plain\r\n";
270 $body .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
271 $body .= $passedBody . "\r\n\r\n";
274 $attachmentlength = attachFiles($fp);
276 if (!isset($postbody)) $postbody = "";
277 $postbody .= "\r\n--".mimeBoundary()."--\r\n\r\n";
278 fputs ($fp, $postbody);
280 $body = $passedBody . "\r\n";
283 fputs ($fp, $postbody);
286 return (strlen($body) +
strlen($postbody) +
$attachmentlength);
289 // Send mail using the sendmail command
290 function sendSendmail($t, $c, $b, $subject, $body, $more_headers) {
291 global $sendmail_path, $popuser, $username, $domain;
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);
301 // open pipe to sendmail
302 $fp = popen (escapeshellcmd("$sendmail_path -t -f$envelopefrom"), 'w');
304 $headerlength = write822Header ($fp, $t, $c, $b, $subject, $more_headers);
305 $bodylength = writeBody($fp, $body);
309 return ($headerlength +
$bodylength);
312 function smtpReadData($smtpConnection) {
313 $read = fgets($smtpConnection, 1024);
317 $data[$counter] = $read;
318 $read = fgets($smtpConnection, 1024);
323 function sendSMTP($t, $c, $b, $subject, $body, $more_headers) {
324 global $username, $popuser, $domain, $version, $smtpServerAddress, $smtpPort,
327 $to = expandAddrs(parseAddrs($t));
328 $cc = expandAddrs(parseAddrs($c));
329 $bcc = expandAddrs(parseAddrs($b));
330 $from_addr = getPref($data_dir, $username, 'email_address');
333 $from_addr = "$popuser@$domain";
335 $smtpConnection = fsockopen($smtpServerAddress, $smtpPort, $errorNumber, $errorString);
336 if (!$smtpConnection) {
337 echo 'Error connecting to SMTP Server.<br>';
338 echo "$errorNumber : $errorString<br>";
341 $tmp = fgets($smtpConnection, 1024);
342 errorCheck($tmp, $smtpConnection);
344 $to_list = getLineOfAddrs($to);
345 $cc_list = getLineOfAddrs($cc);
347 /** Lets introduce ourselves */
348 fputs($smtpConnection, "HELO $domain\r\n");
349 $tmp = fgets($smtpConnection, 1024);
350 errorCheck($tmp, $smtpConnection);
352 /** Ok, who is sending the message? */
353 fputs($smtpConnection, "MAIL FROM:<$from_addr>\r\n");
354 $tmp = fgets($smtpConnection, 1024);
355 errorCheck($tmp, $smtpConnection);
357 /** send who the recipients are */
358 for ($i = 0; $i < count($to); $i++
) {
359 fputs($smtpConnection, "RCPT TO:<$to[$i]>\r\n");
360 $tmp = fgets($smtpConnection, 1024);
361 errorCheck($tmp, $smtpConnection);
363 for ($i = 0; $i < count($cc); $i++
) {
364 fputs($smtpConnection, "RCPT TO:<$cc[$i]>\r\n");
365 $tmp = fgets($smtpConnection, 1024);
366 errorCheck($tmp, $smtpConnection);
368 for ($i = 0; $i < count($bcc); $i++
) {
369 fputs($smtpConnection, "RCPT TO:<$bcc[$i]>\r\n");
370 $tmp = fgets($smtpConnection, 1024);
371 errorCheck($tmp, $smtpConnection);
374 /** Lets start sending the actual message */
375 fputs($smtpConnection, "DATA\r\n");
376 $tmp = fgets($smtpConnection, 1024);
377 errorCheck($tmp, $smtpConnection);
380 $headerlength = write822Header ($smtpConnection, $t, $c, $b, $subject, $more_headers);
381 $bodylength = writeBody($smtpConnection, $body);
383 fputs($smtpConnection, ".\r\n"); // end the DATA part
384 $tmp = fgets($smtpConnection, 1024);
385 $num = errorCheck($tmp, $smtpConnection);
387 $tmp = nl2br(htmlspecialchars($tmp));
388 echo "ERROR<BR>Message not sent!<BR>Reason given: $tmp<BR></BODY></HTML>";
391 fputs($smtpConnection, "QUIT\r\n"); // log off
393 fclose($smtpConnection);
395 return ($headerlength +
$bodylength);
399 function errorCheck($line, $smtpConnection) {
400 global $page_header_php;
402 if (!isset($page_header_php)) {
403 include '../functions/page_header.php';
406 // Read new lines on a multiline response
408 while(ereg("^[0-9]+-", $line)) {
409 $line = fgets($smtpConnection, 1024);
416 $err_num = substr($line, 0, strpos($line, " "));
418 case 500: $message = 'Syntax error; command not recognized';
421 case 501: $message = 'Syntax error in parameters or arguments';
424 case 502: $message = 'Command not implemented';
427 case 503: $message = 'Bad sequence of commands';
430 case 504: $message = 'Command parameter not implemented';
435 case 211: $message = 'System status, or system help reply';
438 case 214: $message = 'Help message';
443 case 220: $message = 'Service ready';
446 case 221: $message = 'Service closing transmission channel';
449 case 421: $message = 'Service not available, closing chanel';
454 case 250: $message = 'Requested mail action okay, completed';
457 case 251: $message = 'User not local; will forward';
460 case 450: $message = 'Requested mail action not taken: mailbox unavailable';
463 case 550: $message = 'Requested action not taken: mailbox unavailable';
466 case 451: $message = 'Requested action aborted: error in processing';
469 case 551: $message = 'User not local; please try forwarding';
472 case 452: $message = 'Requested action not taken: insufficient system storage';
475 case 552: $message = 'Requested mail action aborted: exceeding storage allocation';
478 case 553: $message = 'Requested action not taken: mailbox name not allowed';
481 case 354: $message = 'Start mail input; end with .';
484 case 554: $message = 'Transaction failed';
487 default: $message = 'Unknown response: '. nl2br(htmlspecialchars($lines));
494 displayPageHeader($color, 'None');
496 echo "<br><b><font color=\"$color[1]\">ERROR</font></b><br><br>";
497 echo " <B>Error Number: </B>$err_num<BR>";
498 echo " <B>Reason: </B>$message<BR>";
499 $lines = nl2br(htmlspecialchars($lines));
500 echo "<B>Server Response: </B>$lines<BR>";
501 echo '<BR>MAIL NOT SENT';
502 echo '</TT></BODY></HTML>';
508 function sendMessage($t, $c, $b, $subject, $body, $reply_id) {
509 global $useSendmail, $msg_id, $is_reply, $mailbox;
510 global $data_dir, $username, $domain, $key, $version, $sent_folder, $imapServerAddress, $imapPort;
511 $more_headers = Array();
513 $imap_stream = sqimap_login($username, $key, $imapServerAddress, $imapPort, 1);
515 if (isset($reply_id) && $reply_id) {
516 sqimap_mailbox_select ($imap_stream, $mailbox);
517 sqimap_messages_flag ($imap_stream, $reply_id, $reply_id, 'Answered');
519 // Insert In-Reply-To and References headers if the
520 // message-id of the message we reply to is set (longer than "<>")
521 // The References header should really be the old Referenced header
522 // with the message ID appended, but it can be only the message ID too.
523 $hdr = sqimap_get_small_header ($imap_stream, $reply_id, false);
524 if(strlen($hdr->message_id
) > 2) {
525 $more_headers['In-Reply-To'] = $hdr->message_id
;
526 $more_headers['References'] = $hdr->message_id
;
530 // In order to remove the problem of users not able to create
531 // messages with "." on a blank line, RFC821 has made provision
532 // in section 4.5.2 (Transparency).
533 $body = ereg_replace("\n\\.", "\n..", $body);
534 $body = ereg_replace("^\\.", "..", $body);
536 // this is to catch all plain \n instances and
537 // replace them with \r\n.
538 $body = ereg_replace("\r\n", "\n", $body);
539 $body = ereg_replace("\n", "\r\n", $body);
542 $length = sendSendmail($t, $c, $b, $subject, $body, $more_headers);
544 $length = sendSMTP($t, $c, $b, $subject, $body, $more_headers);
547 if (sqimap_mailbox_exists ($imap_stream, $sent_folder)) {
548 sqimap_append ($imap_stream, $sent_folder, $length);
549 write822Header ($imap_stream, $t, $c, $b, $subject, $more_headers);
550 writeBody ($imap_stream, $body);
551 sqimap_append_done ($imap_stream);
553 sqimap_logout($imap_stream);
554 // Delete the files uploaded for attaching (if any).