4 ** This contains all the functions needed to send messages through
5 ** an smtp server or sendmail.
10 require_once('../functions/addressbook.php');
11 require_once('../functions/plugin.php');
13 global $username, $popuser, $domain;
15 // This should most probably go to some initialization...
16 if (ereg("^([^@%/]+)[@%/](.+)$", $username, $usernamedata)) {
17 $popuser = $usernamedata[1];
18 $domain = $usernamedata[2];
23 // We need domain for smtp
25 $domain = getenv('HOSTNAME');
27 // Returns true only if this message is multipart
28 function isMultipart () {
31 if (count($attachments)>0)
37 // looks up aliases in the addressbook and expands them to
39 // Adds @$domain if it wasn't in the address book and if it
40 // doesn't have an @ symbol in it
41 function expandAddrs ($array) {
44 // don't show errors -- kinda critical that we don't see
45 // them here since the redirect won't work if we do show them
46 $abook = addressbook_init(false);
47 for ($i=0; $i < count($array); $i++
) {
48 $result = $abook->lookup($array[$i]);
50 if (isset($result['email'])) {
51 if (isset($result['name'])) {
52 $ret = '"'.$result['name'].'" ';
54 $ret .= '<'.$result['email'].'>';
59 if (strpos($array[$i], '@') === false)
60 $array[$i] .= '@' . $domain;
61 $array[$i] = '<' . $array[$i] . '>';
68 // looks up aliases in the addressbook and expands them to
69 // the RFC 821 valid RCPT address. ie <user@example.com>
70 // Adds @$domain if it wasn't in the address book and if it
71 // doesn't have an @ symbol in it
72 function expandRcptAddrs ($array) {
75 // don't show errors -- kinda critical that we don't see
76 // them here since the redirect won't work if we do show them
77 $abook = addressbook_init(false);
78 for ($i=0; $i < count($array); $i++
) {
79 $result = $abook->lookup($array[$i]);
81 if (isset($result['email'])) {
82 $ret = '<'.$result['email'].'>';
87 if (strpos($array[$i], '@') === false)
88 $array[$i] .= '@' . $domain;
89 $array[$i] = '<' . $array[$i] . '>';
96 // Attach the files that are due to be attached
97 function attachFiles ($fp) {
98 global $attachments, $attachment_dir;
103 foreach ($attachments as $info)
105 if (isset($info['type']))
106 $filetype = $info['type'];
108 $filetype = 'application/octet-stream';
110 $header = '--'.mimeBoundary()."\r\n";
111 $header .= "Content-Type: $filetype; name=\"" .
112 $info['remotefilename'] . "\"\r\n";
113 $header .= "Content-Disposition: attachment; filename=\"" .
114 $info['remotefilename'] . "\"\r\n";
116 // Use 'rb' for NT systems -- read binary
117 // Unix doesn't care -- everything's binary! :-)
118 $file = fopen ($attachment_dir . $info['localfilename'], 'rb');
119 if (substr($filetype, 0, 5) == 'text/' ||
120 $filetype == 'message/rfc822') {
122 fputs ($fp, $header);
123 $length +
= strlen($header);
124 while ($tmp = fgets($file, 4096)) {
125 $tmp = str_replace("\r\n", "\n", $tmp);
126 $tmp = str_replace("\r", "\n", $tmp);
127 $tmp = str_replace("\n", "\r\n", $tmp);
128 if (feof($fp) && substr($tmp, -2) != "\r\n")
131 $length +
= strlen($tmp);
134 $header .= "Content-Transfer-Encoding: base64\r\n\r\n";
135 fputs ($fp, $header);
136 $length +
= strlen($header);
137 while ($tmp = fread($file, 570)) {
138 $encoded = chunk_split(base64_encode($tmp));
139 $length +
= strlen($encoded);
140 fputs ($fp, $encoded);
150 // Delete files that are uploaded for attaching
151 function deleteAttachments() {
152 global $attachments, $attachment_dir;
156 while (list($localname, $remotename) = each($attachments)) {
157 if (!ereg ("\\/", $localname)) {
158 unlink ($attachment_dir.$localname);
159 unlink ($attachment_dir.$localname.'.info');
165 // Return a nice MIME-boundary
166 function mimeBoundary () {
167 static $mimeBoundaryString;
169 if ($mimeBoundaryString == "") {
170 $mimeBoundaryString = "----=_" .
171 GenerateRandomString(60, '\'()+,-./:=?_', 7);
174 return $mimeBoundaryString;
177 /* Time offset for correct timezone */
178 function timezone () {
181 $diff_second = date('Z');
183 $diff_second = - $diff_second;
184 if ($diff_second > 0)
189 $diff_second = abs($diff_second);
191 $diff_hour = floor ($diff_second / 3600);
192 $diff_minute = floor (($diff_second-3600*$diff_hour) / 60);
194 $zonename = '('.strftime('%Z').')';
195 $result = sprintf ("%s%02d%02d %s", $sign, $diff_hour, $diff_minute, $zonename);
199 /* Print all the needed RFC822 headers */
200 function write822Header ($fp, $t, $c, $b, $subject, $more_headers) {
201 global $REMOTE_ADDR, $SERVER_NAME, $REMOTE_PORT;
202 global $data_dir, $username, $popuser, $domain, $version, $useSendmail;
203 global $default_charset, $HTTP_VIA, $HTTP_X_FORWARDED_FOR;
204 global $REMOTE_HOST, $identity;
206 // Storing the header to make sure the header is the same
207 // everytime the header is printed.
208 static $header, $headerlength;
211 $to = expandAddrs(parseAddrs($t));
212 $cc = expandAddrs(parseAddrs($c));
213 $bcc = expandAddrs(parseAddrs($b));
214 if (isset($identity) && $identity != 'default')
216 $reply_to = getPref($data_dir, $username, 'reply_to' . $identity);
217 $from = getPref($data_dir, $username, 'full_name' . $identity);
218 $from_addr = getPref($data_dir, $username, 'email_address' . $identity);
222 $reply_to = getPref($data_dir, $username, 'reply_to');
223 $from = getPref($data_dir, $username, 'full_name');
224 $from_addr = getPref($data_dir, $username, 'email_address');
227 if ($from_addr == '')
228 $from_addr = $popuser.'@'.$domain;
230 $to_list = getLineOfAddrs($to);
231 $cc_list = getLineOfAddrs($cc);
232 $bcc_list = getLineOfAddrs($bcc);
234 /* Encoding 8-bit characters and making from line */
235 $subject = encodeHeader($subject);
237 $from = "<$from_addr>";
239 $from = '"' . encodeHeader($from) . "\" <$from_addr>";
241 /* This creates an RFC 822 date */
242 $date = date("D, j M Y H:i:s ", mktime()) . timezone();
244 /* Create a message-id */
245 $message_id = '<' . $REMOTE_PORT . '.' . $REMOTE_ADDR . '.';
246 $message_id .= time() . '.squirrel@' . $SERVER_NAME .'>';
248 /* Make an RFC822 Received: line */
249 if (isset($REMOTE_HOST))
250 $received_from = "$REMOTE_HOST ([$REMOTE_ADDR])";
252 $received_from = $REMOTE_ADDR;
254 if (isset($HTTP_VIA) ||
isset ($HTTP_X_FORWARDED_FOR)) {
255 if ($HTTP_X_FORWARDED_FOR == '')
256 $HTTP_X_FORWARDED_FOR = 'unknown';
257 $received_from .= " (proxying for $HTTP_X_FORWARDED_FOR)";
260 $header = "Received: from $received_from\r\n";
261 $header .= " (SquirrelMail authenticated user $username)\r\n";
262 $header .= " by $SERVER_NAME with HTTP;\r\n";
263 $header .= " $date\r\n";
265 /* Insert the rest of the header fields */
266 $header .= "Message-ID: $message_id\r\n";
267 $header .= "Date: $date\r\n";
268 $header .= "Subject: $subject\r\n";
269 $header .= "From: $from\r\n";
270 $header .= "To: $to_list\r\n"; // Who it's TO
272 /* Insert headers from the $more_headers array */
273 if(is_array($more_headers)) {
274 reset($more_headers);
275 while(list($h_name, $h_val) = each($more_headers)) {
276 $header .= sprintf("%s: %s\r\n", $h_name, $h_val);
281 $header .= "Cc: $cc_list\r\n"; // Who the CCs are
285 $header .= "Reply-To: $reply_to\r\n";
289 // BCCs is removed from header by sendmail
290 $header .= "Bcc: $bcc_list\r\n";
294 $header .= "X-Mailer: SquirrelMail (version $version)\r\n"; // Identify SquirrelMail
297 $header .= "MIME-Version: 1.0\r\n";
300 $header .= 'Content-Type: multipart/mixed; boundary="';
301 $header .= mimeBoundary();
304 if ($default_charset != '')
305 $header .= "Content-Type: text/plain; charset=$default_charset\r\n";
307 $header .= "Content-Type: text/plain;\r\n";
308 $header .= "Content-Transfer-Encoding: 8bit\r\n";
310 $header .= "\r\n"; // One blank line to separate header and body
312 $headerlength = strlen($header);
316 fputs ($fp, $header);
318 return $headerlength;
322 function writeBody ($fp, $passedBody) {
323 global $default_charset;
325 $attachmentlength = 0;
328 $body = '--'.mimeBoundary()."\r\n";
330 if ($default_charset != "")
331 $body .= "Content-Type: text/plain; charset=$default_charset\r\n";
333 $body .= "Content-Type: text/plain\r\n";
335 $body .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
336 $body .= $passedBody . "\r\n\r\n";
339 $attachmentlength = attachFiles($fp);
341 if (!isset($postbody)) $postbody = "";
342 $postbody .= "\r\n--".mimeBoundary()."--\r\n\r\n";
343 fputs ($fp, $postbody);
345 $body = $passedBody . "\r\n";
348 fputs ($fp, $postbody);
351 return (strlen($body) +
strlen($postbody) +
$attachmentlength);
354 // Send mail using the sendmail command
355 function sendSendmail($t, $c, $b, $subject, $body, $more_headers) {
356 global $sendmail_path, $popuser, $username, $domain;
358 // Build envelope sender address. Make sure it doesn't contain
359 // spaces or other "weird" chars that would allow a user to
360 // exploit the shell/pipe it is used in.
361 $envelopefrom = "$popuser@$domain";
362 $envelopefrom = ereg_replace("[[:blank:]]",'', $envelopefrom);
363 $envelopefrom = ereg_replace("[[:space:]]",'', $envelopefrom);
364 $envelopefrom = ereg_replace("[[:cntrl:]]",'', $envelopefrom);
366 // open pipe to sendmail or qmail-inject (qmail-inject doesn't accept -t param)
367 if (strstr($sendmail_path, "qmail-inject")) {
368 $fp = popen (escapeshellcmd("$sendmail_path -f$envelopefrom"), "w");
370 $fp = popen (escapeshellcmd("$sendmail_path -t -f$envelopefrom"), "w");
373 $headerlength = write822Header ($fp, $t, $c, $b, $subject, $more_headers);
374 $bodylength = writeBody($fp, $body);
378 return ($headerlength +
$bodylength);
381 function smtpReadData($smtpConnection) {
382 $read = fgets($smtpConnection, 1024);
386 $data[$counter] = $read;
387 $read = fgets($smtpConnection, 1024);
392 function sendSMTP($t, $c, $b, $subject, $body, $more_headers) {
393 global $username, $popuser, $domain, $version, $smtpServerAddress,
394 $smtpPort, $data_dir, $color, $use_authenticated_smtp, $identity,
397 $to = expandRcptAddrs(parseAddrs($t));
398 $cc = expandRcptAddrs(parseAddrs($c));
399 $bcc = expandRcptAddrs(parseAddrs($b));
400 if (isset($identity) && $identity != 'default')
401 $from_addr = getPref($data_dir, $username, 'email_address' . $identity);
403 $from_addr = getPref($data_dir, $username, 'email_address');
406 $from_addr = "$popuser@$domain";
408 $smtpConnection = fsockopen($smtpServerAddress, $smtpPort, $errorNumber, $errorString);
409 if (!$smtpConnection) {
410 echo 'Error connecting to SMTP Server.<br>';
411 echo "$errorNumber : $errorString<br>";
414 $tmp = fgets($smtpConnection, 1024);
415 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
417 $to_list = getLineOfAddrs($to);
418 $cc_list = getLineOfAddrs($cc);
420 /** Lets introduce ourselves */
421 if (! isset ($use_authenticated_smtp) ||
$use_authenticated_smtp == false) {
422 fputs($smtpConnection, "HELO $domain\r\n");
423 $tmp = fgets($smtpConnection, 1024);
424 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
426 fputs($smtpConnection, "EHLO $domain\r\n");
427 $tmp = fgets($smtpConnection, 1024);
428 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
430 fputs($smtpConnection, "AUTH LOGIN\r\n");
431 $tmp = fgets($smtpConnection, 1024);
432 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
434 fputs($smtpConnection, base64_encode ($username) . "\r\n");
435 $tmp = fgets($smtpConnection, 1024);
436 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
438 fputs($smtpConnection, base64_encode (OneTimePadDecrypt($key, $onetimepad)) . "\r\n");
439 $tmp = fgets($smtpConnection, 1024);
440 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
443 /** Ok, who is sending the message? */
444 fputs($smtpConnection, "MAIL FROM: <$from_addr>\r\n");
445 $tmp = fgets($smtpConnection, 1024);
446 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
448 /** send who the recipients are */
449 for ($i = 0; $i < count($to); $i++
) {
450 fputs($smtpConnection, "RCPT TO: $to[$i]\r\n");
451 $tmp = fgets($smtpConnection, 1024);
452 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
454 for ($i = 0; $i < count($cc); $i++
) {
455 fputs($smtpConnection, "RCPT TO: $cc[$i]\r\n");
456 $tmp = fgets($smtpConnection, 1024);
457 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
459 for ($i = 0; $i < count($bcc); $i++
) {
460 fputs($smtpConnection, "RCPT TO: $bcc[$i]\r\n");
461 $tmp = fgets($smtpConnection, 1024);
462 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
465 /** Lets start sending the actual message */
466 fputs($smtpConnection, "DATA\r\n");
467 $tmp = fgets($smtpConnection, 1024);
468 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
471 $headerlength = write822Header ($smtpConnection, $t, $c, $b, $subject, $more_headers);
472 $bodylength = writeBody($smtpConnection, $body);
474 fputs($smtpConnection, ".\r\n"); // end the DATA part
475 $tmp = fgets($smtpConnection, 1024);
476 $num = errorCheck($tmp, $smtpConnection, true);
478 $tmp = nl2br(htmlspecialchars($tmp));
479 displayPageHeader($color, 'None');
480 include_once('../functions/display_messages.php');
481 $msg = "Message not sent!<br>\nReason given: $tmp";
482 plain_error_message($msg, $color);
486 fputs($smtpConnection, "QUIT\r\n"); // log off
488 fclose($smtpConnection);
490 return ($headerlength +
$bodylength);
494 function errorCheck($line, $smtpConnection, $verbose = false) {
497 // Read new lines on a multiline response
499 while(ereg("^[0-9]+-", $line)) {
500 $line = fgets($smtpConnection, 1024);
507 $err_num = substr($line, 0, strpos($line, " "));
509 case 500: $message = 'Syntax error; command not recognized';
512 case 501: $message = 'Syntax error in parameters or arguments';
515 case 502: $message = 'Command not implemented';
518 case 503: $message = 'Bad sequence of commands';
521 case 504: $message = 'Command parameter not implemented';
526 case 211: $message = 'System status, or system help reply';
529 case 214: $message = 'Help message';
534 case 220: $message = 'Service ready';
537 case 221: $message = 'Service closing transmission channel';
540 case 421: $message = 'Service not available, closing chanel';
544 case 235: return(5); break;
545 case 250: $message = 'Requested mail action okay, completed';
548 case 251: $message = 'User not local; will forward';
551 case 334: return(5); break;
552 case 450: $message = 'Requested mail action not taken: mailbox unavailable';
555 case 550: $message = 'Requested action not taken: mailbox unavailable';
558 case 451: $message = 'Requested action aborted: error in processing';
561 case 551: $message = 'User not local; please try forwarding';
564 case 452: $message = 'Requested action not taken: insufficient system storage';
567 case 552: $message = 'Requested mail action aborted: exceeding storage allocation';
570 case 553: $message = 'Requested action not taken: mailbox name not allowed';
573 case 354: $message = 'Start mail input; end with .';
576 case 554: $message = 'Transaction failed';
579 default: $message = 'Unknown response: '. nl2br(htmlspecialchars($lines));
586 include_once('../functions/page_header.php');
587 displayPageHeader($color, 'None');
588 include_once('../functions/display_messages.php');
589 $lines = nl2br(htmlspecialchars($lines));
590 $msg = $message . "<br>\nServer replied: $lines";
591 plain_error_message($msg, $color);
593 if (! $verbose) return $status;
597 function sendMessage($t, $c, $b, $subject, $body, $reply_id, $prio = 3) {
598 global $useSendmail, $msg_id, $is_reply, $mailbox, $onetimepad;
599 global $data_dir, $username, $domain, $key, $version, $sent_folder, $imapServerAddress, $imapPort;
600 global $default_use_priority;
601 global $more_headers;
602 $more_headers = Array();
604 do_hook("smtp_send");
606 $imap_stream = sqimap_login($username, $key, $imapServerAddress, $imapPort, 1);
608 if (isset($reply_id) && $reply_id) {
609 sqimap_mailbox_select ($imap_stream, $mailbox);
610 sqimap_messages_flag ($imap_stream, $reply_id, $reply_id, 'Answered');
612 // Insert In-Reply-To and References headers if the
613 // message-id of the message we reply to is set (longer than "<>")
614 // The References header should really be the old Referenced header
615 // with the message ID appended, but it can be only the message ID too.
616 $hdr = sqimap_get_small_header ($imap_stream, $reply_id, false);
617 if(strlen($hdr->message_id
) > 2) {
618 $more_headers['In-Reply-To'] = $hdr->message_id
;
619 $more_headers['References'] = $hdr->message_id
;
622 if ($default_use_priority) {
623 $more_headers = array_merge($more_headers, createPriorityHeaders($prio));
626 // In order to remove the problem of users not able to create
627 // messages with "." on a blank line, RFC821 has made provision
628 // in section 4.5.2 (Transparency).
629 $body = ereg_replace("\n\\.", "\n..", $body);
630 $body = ereg_replace("^\\.", "..", $body);
632 // this is to catch all plain \n instances and
633 // replace them with \r\n. All newlines were converted
634 // into just \n inside the compose.php file.
635 $body = ereg_replace("\n", "\r\n", $body);
638 $length = sendSendmail($t, $c, $b, $subject, $body, $more_headers);
640 $length = sendSMTP($t, $c, $b, $subject, $body, $more_headers);
643 if (sqimap_mailbox_exists ($imap_stream, $sent_folder)) {
644 sqimap_append ($imap_stream, $sent_folder, $length);
645 write822Header ($imap_stream, $t, $c, $b, $subject, $more_headers);
646 writeBody ($imap_stream, $body);
647 sqimap_append_done ($imap_stream);
649 sqimap_logout($imap_stream);
650 // Delete the files uploaded for attaching (if any).
651 // only if $length != 0 (if there was no error)
658 function createPriorityHeaders($prio) {
659 $prio_headers = Array();
660 $prio_headers["X-Priority"] = $prio;
663 case 1: $prio_headers["Importance"] = "High";
664 $prio_headers["X-MSMail-Priority"] = "High";
667 case 3: $prio_headers["Importance"] = "Normal";
668 $prio_headers["X-MSMail-Priority"] = "Normal";
672 $prio_headers["Importance"] = "Low";
673 $prio_headers["X-MSMail-Priority"] = "Low";
676 return $prio_headers;