0c66f44e96779aecea0d956e03ef2925b49ed5d9
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'].'>';
52 $array[$i] = '<' . $array[$i] . '>';
58 // Attach the files that are due to be attached
59 function attachFiles ($fp) {
60 global $attachments, $attachment_dir;
65 foreach ($attachments as $info)
67 $filetype = $info['type'];
69 $filetype = 'application/octet-stream';
71 $header = '--'.mimeBoundary()."\r\n";
72 $header .= "Content-Type: $filetype; name=\"" .
73 $info['remotefilename'] . "\"\r\n";
74 $header .= "Content-Disposition: attachment; filename=\"" .
75 $info['remotefilename'] . "\"\r\n";
76 $header .= "Content-Transfer-Encoding: base64\r\n\r\n";
78 $length +
= strlen($header);
80 $file = fopen ($attachment_dir . $info['localfilename'], 'r');
81 while ($tmp = fread($file, 570)) {
82 $encoded = chunk_split(base64_encode($tmp));
83 $length +
= strlen($encoded);
84 fputs ($fp, $encoded);
93 // Delete files that are uploaded for attaching
94 function deleteAttachments() {
95 global $attachments, $attachment_dir;
99 while (list($localname, $remotename) = each($attachments)) {
100 if (!ereg ("\\/", $localname)) {
101 unlink ($attachment_dir.$localname);
102 unlink ($attachment_dir.$localname.'.info');
108 // Return a nice MIME-boundary
109 function mimeBoundary () {
110 static $mimeBoundaryString;
112 if ($mimeBoundaryString == "") {
113 $mimeBoundaryString = "----=_" .
114 GenerateRandomString(60, '\'()+,-./:=?_', 7);
117 return $mimeBoundaryString;
120 /* Time offset for correct timezone */
121 function timezone () {
124 $diff_second = date('Z');
126 $diff_second = - $diff_second;
127 if ($diff_second > 0)
132 $diff_second = abs($diff_second);
134 $diff_hour = floor ($diff_second / 3600);
135 $diff_minute = floor (($diff_second-3600*$diff_hour) / 60);
137 $zonename = '('.strftime('%Z').')';
138 $result = sprintf ("%s%02d%02d %s", $sign, $diff_hour, $diff_minute, $zonename);
142 /* Print all the needed RFC822 headers */
143 function write822Header ($fp, $t, $c, $b, $subject, $more_headers) {
144 global $REMOTE_ADDR, $SERVER_NAME, $REMOTE_PORT;
145 global $data_dir, $username, $popuser, $domain, $version, $useSendmail;
146 global $default_charset, $HTTP_VIA, $HTTP_X_FORWARDED_FOR;
149 // Storing the header to make sure the header is the same
150 // everytime the header is printed.
151 static $header, $headerlength;
154 $to = expandAddrs(parseAddrs($t));
155 $cc = expandAddrs(parseAddrs($c));
156 $bcc = expandAddrs(parseAddrs($b));
157 $reply_to = getPref($data_dir, $username, 'reply_to');
158 $from = getPref($data_dir, $username, 'full_name');
159 $from_addr = getPref($data_dir, $username, 'email_address');
161 if ($from_addr == '')
162 $from_addr = $popuser.'@'.$domain;
164 $to_list = getLineOfAddrs($to);
165 $cc_list = getLineOfAddrs($cc);
166 $bcc_list = getLineOfAddrs($bcc);
168 /* Encoding 8-bit characters and making from line */
169 $subject = encodeHeader($subject);
171 $from = "<$from_addr>";
173 $from = '"' . encodeHeader($from) . "\" <$from_addr>";
175 /* This creates an RFC 822 date */
176 $date = date("D, j M Y H:i:s ", mktime()) . timezone();
178 /* Create a message-id */
179 $message_id = '<' . $REMOTE_PORT . '.' . $REMOTE_ADDR . '.';
180 $message_id .= time() . '.squirrel@' . $SERVER_NAME .'>';
182 /* Make an RFC822 Received: line */
183 if (isset($REMOTE_HOST))
184 $received_from = "$REMOTE_HOST ([$REMOTE_ADDR])";
186 $received_from = $REMOTE_ADDR;
188 if (isset($HTTP_VIA) ||
isset ($HTTP_X_FORWARDED_FOR)) {
189 if ($HTTP_X_FORWARDED_FOR == '')
190 $HTTP_X_FORWARDED_FOR = 'unknown';
191 $received_from .= " (proxying for $HTTP_X_FORWARDED_FOR)";
194 $header = "Received: from $received_from\r\n";
195 $header .= " (SquirrelMail authenticated user $username)\r\n";
196 $header .= " by $SERVER_NAME with HTTP;\r\n";
197 $header .= " $date\r\n";
199 /* Insert the rest of the header fields */
200 $header .= "Message-ID: $message_id\r\n";
201 $header .= "Date: $date\r\n";
202 $header .= "Subject: $subject\r\n";
203 $header .= "From: $from\r\n";
204 $header .= "To: $to_list\r\n"; // Who it's TO
206 /* Insert headers from the $more_headers array */
207 if(is_array($more_headers)) {
208 reset($more_headers);
209 while(list($h_name, $h_val) = each($more_headers)) {
210 $header .= sprintf("%s: %s\r\n", $h_name, $h_val);
215 $header .= "Cc: $cc_list\r\n"; // Who the CCs are
219 $header .= "Reply-To: $reply_to\r\n";
223 // BCCs is removed from header by sendmail
224 $header .= "Bcc: $bcc_list\r\n";
228 $header .= "X-Mailer: SquirrelMail (version $version)\r\n"; // Identify SquirrelMail
231 $header .= "MIME-Version: 1.0\r\n";
234 $header .= 'Content-Type: multipart/mixed; boundary="';
235 $header .= mimeBoundary();
238 if ($default_charset != '')
239 $header .= "Content-Type: text/plain; charset=$default_charset\r\n";
241 $header .= "Content-Type: text/plain;\r\n";
242 $header .= "Content-Transfer-Encoding: 8bit\r\n";
244 $header .= "\r\n"; // One blank line to separate header and body
246 $headerlength = strlen($header);
250 fputs ($fp, $header);
252 return $headerlength;
256 function writeBody ($fp, $passedBody) {
257 global $default_charset;
259 $attachmentlength = 0;
262 $body = '--'.mimeBoundary()."\r\n";
264 if ($default_charset != "")
265 $body .= "Content-Type: text/plain; charset=$default_charset\r\n";
267 $body .= "Content-Type: text/plain\r\n";
269 $body .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
270 $body .= $passedBody . "\r\n\r\n";
273 $attachmentlength = attachFiles($fp);
275 if (!isset($postbody)) $postbody = "";
276 $postbody .= "\r\n--".mimeBoundary()."--\r\n\r\n";
277 fputs ($fp, $postbody);
279 $body = $passedBody . "\r\n";
282 fputs ($fp, $postbody);
285 return (strlen($body) +
strlen($postbody) +
$attachmentlength);
288 // Send mail using the sendmail command
289 function sendSendmail($t, $c, $b, $subject, $body, $more_headers) {
290 global $sendmail_path, $popuser, $username, $domain;
292 // Build envelope sender address. Make sure it doesn't contain
293 // spaces or other "weird" chars that would allow a user to
294 // exploit the shell/pipe it is used in.
295 $envelopefrom = "$popuser@$domain";
296 $envelopefrom = ereg_replace("[[:blank:]]",'', $envelopefrom);
297 $envelopefrom = ereg_replace("[[:space:]]",'', $envelopefrom);
298 $envelopefrom = ereg_replace("[[:cntrl:]]",'', $envelopefrom);
300 // open pipe to sendmail
301 $fp = popen (escapeshellcmd("$sendmail_path -t -f$envelopefrom"), 'w');
303 $headerlength = write822Header ($fp, $t, $c, $b, $subject, $more_headers);
304 $bodylength = writeBody($fp, $body);
308 return ($headerlength +
$bodylength);
311 function smtpReadData($smtpConnection) {
312 $read = fgets($smtpConnection, 1024);
316 $data[$counter] = $read;
317 $read = fgets($smtpConnection, 1024);
322 function sendSMTP($t, $c, $b, $subject, $body, $more_headers) {
323 global $username, $popuser, $domain, $version, $smtpServerAddress, $smtpPort,
326 $to = expandAddrs(parseAddrs($t));
327 $cc = expandAddrs(parseAddrs($c));
328 $bcc = expandAddrs(parseAddrs($b));
329 $from_addr = getPref($data_dir, $username, 'email_address');
332 $from_addr = "$popuser@$domain";
334 $smtpConnection = fsockopen($smtpServerAddress, $smtpPort, $errorNumber, $errorString);
335 if (!$smtpConnection) {
336 echo 'Error connecting to SMTP Server.<br>';
337 echo "$errorNumber : $errorString<br>";
340 $tmp = fgets($smtpConnection, 1024);
341 errorCheck($tmp, $smtpConnection);
343 $to_list = getLineOfAddrs($to);
344 $cc_list = getLineOfAddrs($cc);
346 /** Lets introduce ourselves */
347 fputs($smtpConnection, "HELO $domain\r\n");
348 $tmp = fgets($smtpConnection, 1024);
349 errorCheck($tmp, $smtpConnection);
351 /** Ok, who is sending the message? */
352 fputs($smtpConnection, "MAIL FROM: <$from_addr>\r\n");
353 $tmp = fgets($smtpConnection, 1024);
354 errorCheck($tmp, $smtpConnection);
356 /** send who the recipients are */
357 for ($i = 0; $i < count($to); $i++
) {
358 fputs($smtpConnection, "RCPT TO: $to[$i]\r\n");
359 $tmp = fgets($smtpConnection, 1024);
360 errorCheck($tmp, $smtpConnection);
362 for ($i = 0; $i < count($cc); $i++
) {
363 fputs($smtpConnection, "RCPT TO: $cc[$i]\r\n");
364 $tmp = fgets($smtpConnection, 1024);
365 errorCheck($tmp, $smtpConnection);
367 for ($i = 0; $i < count($bcc); $i++
) {
368 fputs($smtpConnection, "RCPT TO: $bcc[$i]\r\n");
369 $tmp = fgets($smtpConnection, 1024);
370 errorCheck($tmp, $smtpConnection);
373 /** Lets start sending the actual message */
374 fputs($smtpConnection, "DATA\r\n");
375 $tmp = fgets($smtpConnection, 1024);
376 errorCheck($tmp, $smtpConnection);
379 $headerlength = write822Header ($smtpConnection, $t, $c, $b, $subject, $more_headers);
380 $bodylength = writeBody($smtpConnection, $body);
382 fputs($smtpConnection, ".\r\n"); // end the DATA part
383 $tmp = fgets($smtpConnection, 1024);
384 $num = errorCheck($tmp, $smtpConnection);
386 $tmp = nl2br(htmlspecialchars($tmp));
387 echo "ERROR<BR>Message not sent!<BR>Reason given: $tmp<BR></BODY></HTML>";
390 fputs($smtpConnection, "QUIT\r\n"); // log off
392 fclose($smtpConnection);
394 return ($headerlength +
$bodylength);
398 function errorCheck($line, $smtpConnection) {
399 global $page_header_php;
401 if (!isset($page_header_php)) {
402 include '../functions/page_header.php';
405 // Read new lines on a multiline response
407 while(ereg("^[0-9]+-", $line)) {
408 $line = fgets($smtpConnection, 1024);
415 $err_num = substr($line, 0, strpos($line, " "));
417 case 500: $message = 'Syntax error; command not recognized';
420 case 501: $message = 'Syntax error in parameters or arguments';
423 case 502: $message = 'Command not implemented';
426 case 503: $message = 'Bad sequence of commands';
429 case 504: $message = 'Command parameter not implemented';
434 case 211: $message = 'System status, or system help reply';
437 case 214: $message = 'Help message';
442 case 220: $message = 'Service ready';
445 case 221: $message = 'Service closing transmission channel';
448 case 421: $message = 'Service not available, closing chanel';
453 case 250: $message = 'Requested mail action okay, completed';
456 case 251: $message = 'User not local; will forward';
459 case 450: $message = 'Requested mail action not taken: mailbox unavailable';
462 case 550: $message = 'Requested action not taken: mailbox unavailable';
465 case 451: $message = 'Requested action aborted: error in processing';
468 case 551: $message = 'User not local; please try forwarding';
471 case 452: $message = 'Requested action not taken: insufficient system storage';
474 case 552: $message = 'Requested mail action aborted: exceeding storage allocation';
477 case 553: $message = 'Requested action not taken: mailbox name not allowed';
480 case 354: $message = 'Start mail input; end with .';
483 case 554: $message = 'Transaction failed';
486 default: $message = 'Unknown response: '. nl2br(htmlspecialchars($lines));
493 displayPageHeader($color, 'None');
495 echo "<br><b><font color=\"$color[1]\">ERROR</font></b><br><br>";
496 echo " <B>Error Number: </B>$err_num<BR>";
497 echo " <B>Reason: </B>$message<BR>";
498 $lines = nl2br(htmlspecialchars($lines));
499 echo "<B>Server Response: </B>$lines<BR>";
500 echo '<BR>MAIL NOT SENT';
501 echo '</TT></BODY></HTML>';
507 function sendMessage($t, $c, $b, $subject, $body, $reply_id) {
508 global $useSendmail, $msg_id, $is_reply, $mailbox;
509 global $data_dir, $username, $domain, $key, $version, $sent_folder, $imapServerAddress, $imapPort;
510 $more_headers = Array();
512 $imap_stream = sqimap_login($username, $key, $imapServerAddress, $imapPort, 1);
514 if (isset($reply_id) && $reply_id) {
515 sqimap_mailbox_select ($imap_stream, $mailbox);
516 sqimap_messages_flag ($imap_stream, $reply_id, $reply_id, 'Answered');
518 // Insert In-Reply-To and References headers if the
519 // message-id of the message we reply to is set (longer than "<>")
520 // The References header should really be the old Referenced header
521 // with the message ID appended, but it can be only the message ID too.
522 $hdr = sqimap_get_small_header ($imap_stream, $reply_id, false);
523 if(strlen($hdr->message_id
) > 2) {
524 $more_headers['In-Reply-To'] = $hdr->message_id
;
525 $more_headers['References'] = $hdr->message_id
;
529 // In order to remove the problem of users not able to create
530 // messages with "." on a blank line, RFC821 has made provision
531 // in section 4.5.2 (Transparency).
532 $body = ereg_replace("\n\\.", "\n..", $body);
533 $body = ereg_replace("^\\.", "..", $body);
535 // this is to catch all plain \n instances and
536 // replace them with \r\n.
537 $body = ereg_replace("\r\n", "\n", $body);
538 $body = ereg_replace("\n", "\r\n", $body);
541 $length = sendSendmail($t, $c, $b, $subject, $body, $more_headers);
543 $length = sendSMTP($t, $c, $b, $subject, $body, $more_headers);
546 if (sqimap_mailbox_exists ($imap_stream, $sent_folder)) {
547 sqimap_append ($imap_stream, $sent_folder, $length);
548 write822Header ($imap_stream, $t, $c, $b, $subject, $more_headers);
549 writeBody ($imap_stream, $body);
550 sqimap_append_done ($imap_stream);
552 sqimap_logout($imap_stream);
553 // Delete the files uploaded for attaching (if any).