88bfa9ee1225df3cc5da639b2584a66ddd5efdf3
[squirrelmail.git] / functions / smtp.php
1 <?php
2 /** smtp.php
3 **
4 ** This contains all the functions needed to send messages through
5 ** an smtp server or sendmail.
6 **/
7
8 $smtp_php = true;
9
10 // Returns true only if this message is multipart
11 function isMultipart () {
12 global $attachments;
13
14 if (count($attachments)>0)
15 return true;
16 else
17 return false;
18 }
19
20 // Attach the files that are due to be attached
21 function attachFiles ($fp) {
22 global $attachments, $attachment_dir;
23
24 $length = 0;
25
26 if (isMultipart()) {
27 reset($attachments);
28 while (list($localname, $remotename) = each($attachments)) {
29 // This is to make sure noone is giving a filename in another
30 // directory
31 $localname = ereg_replace ("\\/", "", $localname);
32
33 $fileinfo = fopen ($attachment_dir.$localname.".info", "r");
34 $filetype = fgets ($fileinfo, 8192);
35 fclose ($fileinfo);
36 $filetype = trim ($filetype);
37 if ($filetype=="")
38 $filetype = "application/octet-stream";
39
40 $header = "--".mimeBoundary()."\r\n";
41 $header .= "Content-Type: $filetype\r\n";
42 $header .= "Content-Disposition: attachment; filename=\"$remotename\"\r\n";
43 $header .= "Content-Transfer-Encoding: base64\r\n\r\n";
44 fputs ($fp, $header);
45 $length += strlen($header);
46
47 $file = fopen ($attachment_dir.$localname, "r");
48 while ($tmp = fread($file, 570)) {
49 $encoded = chunk_split(base64_encode($tmp));
50 $length += strlen($encoded);
51 fputs ($fp, $encoded);
52 }
53 fclose ($file);
54 }
55 }
56
57 return $length;
58 }
59
60 // Delete files that are uploaded for attaching
61 function deleteAttachments() {
62 global $attachments, $attachment_dir;
63
64 if (isMultipart()) {
65 reset($attachments);
66 while (list($localname, $remotename) = each($attachments)) {
67 if (!ereg ("\\/", $localname)) {
68 unlink ($attachment_dir.$localname);
69 unlink ($attachment_dir.$localname.".info");
70 }
71 }
72 }
73 }
74
75 // Return a nice MIME-boundary
76 function mimeBoundary () {
77 static $mimeBoundaryString;
78
79 if ($mimeBoundaryString == "") {
80 $mimeBoundaryString = GenerateRandomString(70, '\'()+,-./:=?_', 7);
81 }
82
83 return $mimeBoundaryString;
84 }
85
86 /* Time offset for correct timezone */
87 function timezone () {
88 $diff_second = date("Z");
89 if ($invert_time)
90 $diff_second = - $diff_second;
91 if ($diff_second > 0)
92 $sign = "+";
93 else
94 $sign = "-";
95
96 $diff_second = abs($diff_second);
97
98 $diff_hour = floor ($diff_second / 3600);
99 $diff_minute = floor (($diff_second-3600*$diff_hour) / 60);
100
101 $zonename = "(".strftime("%Z").")";
102 $result = sprintf ("%s%02d%02d %s", $sign, $diff_hour, $diff_minute, $zonename);
103 return ($result);
104 }
105
106 /* Print all the needed RFC822 headers */
107 function write822Header ($fp, $t, $c, $b, $subject, $more_headers) {
108 global $REMOTE_ADDR, $SERVER_NAME, $REMOTE_PORT;
109 global $data_dir, $username, $domain, $version, $useSendmail;
110 global $default_charset, $HTTP_VIA, $HTTP_X_FORWARDED_FOR;
111 global $REMOTE_HOST;
112
113 // Storing the header to make sure the header is the same
114 // everytime the header is printed.
115 static $header, $headerlength;
116
117 if ($header == "") {
118 $to = parseAddrs($t);
119 $cc = parseAddrs($c);
120 $bcc = parseAddrs($b);
121 $reply_to = getPref($data_dir, $username, "reply_to");
122 $from = getPref($data_dir, $username, "full_name");
123 $from_addr = getPref($data_dir, $username, "email_address");
124
125 if ($from_addr == "")
126 $from_addr = "$username@$domain";
127
128 $to_list = getLineOfAddrs($to);
129 $cc_list = getLineOfAddrs($cc);
130 $bcc_list = getLineOfAddrs($bcc);
131
132 /* Encoding 8-bit characters and making from line */
133 $subject = sqStripSlashes(encodeHeader($subject));
134 if ($from == "")
135 $from = "<$from_addr>";
136 else
137 $from = "\"" . encodeHeader($from) . "\" <$from_addr>";
138
139 /* This creates an RFC 822 date */
140 $date = date("D, j M Y H:i:s ", mktime()) . timezone();
141
142 /* Create a message-id */
143 $message_id = "<" . $REMOTE_PORT . "." . $REMOTE_ADDR . ".";
144 $message_id .= time() . ".squirrel@" . $SERVER_NAME .">";
145
146 /* Make an RFC822 Received: line */
147 if (isset($REMOTE_HOST))
148 $received_from = "$REMOTE_HOST ([$REMOTE_ADDR])";
149 else
150 $received_from = $REMOTE_ADDR;
151
152 if (isset($HTTP_VIA) || isset ($HTTP_X_FORWARDED_FOR)) {
153 if ($HTTP_X_FORWARDED_FOR == "")
154 $HTTP_X_FORWARDED_FOR = "unknown";
155 $received_from .= " (proxying for $HTTP_X_FORWARDED_FOR)";
156 }
157
158 $header = "Received: from $received_from\r\n";
159 $header .= " (SquirrelMail authenticated user $username)\r\n";
160 $header .= " by $SERVER_NAME with HTTP;\r\n";
161 $header .= " $date\r\n";
162
163 /* Insert the rest of the header fields */
164 $header .= "Message-ID: $message_id\r\n";
165 $header .= "Date: $date\r\n";
166 $header .= "Subject: $subject\r\n";
167 $header .= "From: $from\r\n";
168 $header .= "To: $to_list \r\n"; // Who it's TO
169
170 /* Insert headers from the $more_headers array */
171 if(is_array($more_headers)) {
172 reset($more_headers);
173 while(list($h_name, $h_val) = each($more_headers)) {
174 $header .= sprintf("%s: %s\r\n", $h_name, $h_val);
175 }
176 }
177
178 if ($cc_list) {
179 $header .= "Cc: $cc_list\r\n"; // Who the CCs are
180 }
181
182 if ($reply_to != "")
183 $header .= "Reply-To: $reply_to\r\n";
184
185 if ($useSendmail) {
186 if ($bcc_list) {
187 // BCCs is removed from header by sendmail
188 $header .= "Bcc: $bcc_list\r\n";
189 }
190 }
191
192 $header .= "X-Mailer: SquirrelMail (version $version)\r\n"; // Identify SquirrelMail
193
194 // Do the MIME-stuff
195 $header .= "MIME-Version: 1.0\r\n";
196
197 if (isMultipart()) {
198 $header .= "Content-Type: multipart/mixed; boundary=\"";
199 $header .= mimeBoundary();
200 $header .= "\"\r\n";
201 } else {
202 if ($default_charset != "")
203 $header .= "Content-Type: text/plain; charset=$default_charset\r\n";
204 else
205 $header .= "Content-Type: text/plain;\r\n";
206 $header .= "Content-Transfer-Encoding: 8bit\r\n";
207 }
208 $header .= "\r\n"; // One blank line to separate header and body
209
210 $headerlength = strlen($header);
211 }
212
213 // Write the header
214 fputs ($fp, $header);
215
216 return $headerlength;
217 }
218
219 // Send the body
220 function writeBody ($fp, $passedBody) {
221 global $default_charset;
222
223 $attachmentlength = 0;
224
225 if (isMultipart()) {
226 $body = "--".mimeBoundary()."\r\n";
227
228 if ($default_charset != "")
229 $body .= "Content-Type: text/plain; charset=$default_charset\r\n";
230 else
231 $body .= "Content-Type: text/plain\r\n";
232
233 $body .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
234 $body .= sqStripSlashes($passedBody) . "\r\n";
235 fputs ($fp, $body);
236
237 $attachmentlength = attachFiles($fp);
238
239 $postbody .= "\r\n--".mimeBoundary()."--\r\n\r\n";
240 fputs ($fp, $postbody);
241 } else {
242 $body = sqStripSlashes($passedBody) . "\r\n";
243 fputs ($fp, $body);
244 $postbody = "\r\n";
245 fputs ($fp, $postbody);
246 }
247
248 return (strlen($body) + strlen($postbody) + $attachmentlength);
249 }
250
251 // Send mail using the sendmail command
252 function sendSendmail($t, $c, $b, $subject, $body, $more_headers) {
253 global $sendmail_path, $username, $domain;
254
255 // Build envelope sender address. Make sure it doesn't contain
256 // spaces or other "weird" chars that would allow a user to
257 // exploit the shell/pipe it is used in.
258 $envelopefrom = "$username@$domain";
259 $envelopefrom = ereg_replace("[[:blank:]]","", $envelopefrom);
260 $envelopefrom = ereg_replace("[[:space:]]","", $envelopefrom);
261 $envelopefrom = ereg_replace("[[:cntrl:]]","", $envelopefrom);
262
263 // open pipe to sendmail
264 $fp = popen (escapeshellcmd("$sendmail_path -t -f$envelopefrom"), "w");
265
266 $headerlength = write822Header ($fp, $t, $c, $b, $subject, $more_headers);
267 $bodylength = writeBody($fp, $body);
268
269 pclose($fp);
270
271 return ($headerlength + $bodylength);
272 }
273
274 function smtpReadData($smtpConnection) {
275 $read = fgets($smtpConnection, 1024);
276 $counter = 0;
277 while ($read) {
278 echo $read . "<BR>";
279 $data[$counter] = $read;
280 $read = fgets($smtpConnection, 1024);
281 $counter++;
282 }
283 }
284
285 function sendSMTP($t, $c, $b, $subject, $body, $more_headers) {
286 global $username, $domain, $version, $smtpServerAddress, $smtpPort,
287 $data_dir, $color;
288
289 $to = parseAddrs($t);
290 $cc = parseAddrs($c);
291 $bcc = parseAddrs($b);
292 $from_addr = getPref($data_dir, $username, "email_address");
293
294
295 /*
296 * A patch from Bill Thousand <billyt@claritytech.com>
297 *
298 * "I don't know if anyone else needs this or not, but it totally makes squirrelmail usable for us.
299 * This quick patch checks the username and from address for the domain information. We use
300 * a virtual domain patch for our imap server that allows multiple domains by using username@domain.com
301 * as the login username."
302 */
303 if ($from_addr == "") {
304 if (strstr($username, "@")) {
305 $from_addr = $username;
306 $address_pieces = explode("@",$username);
307 $domain = $address_pieces[1];
308 } else {
309 $from_addr = "$username@$domain";
310 }
311 } else {
312 // If the From Address is specified, use the domain in the from
313 // address if it's there.
314 if (strstr($from_addr, "@")) {
315 $address_pieces = explode("@", $from_addr);
316 $domain = $address_pieces[1];
317 }
318 }
319 /*
320 * End patch from Bill Thousand
321 */
322
323
324 $smtpConnection = fsockopen($smtpServerAddress, $smtpPort, $errorNumber, $errorString);
325 if (!$smtpConnection) {
326 echo "Error connecting to SMTP Server.<br>";
327 echo "$errorNumber : $errorString<br>";
328 exit;
329 }
330 $tmp = fgets($smtpConnection, 1024);
331 errorCheck($tmp, $smtpConnection);
332
333 $to_list = getLineOfAddrs($to);
334 $cc_list = getLineOfAddrs($cc);
335
336 /** Lets introduce ourselves */
337 fputs($smtpConnection, "HELO $domain\r\n");
338 $tmp = fgets($smtpConnection, 1024);
339 errorCheck($tmp, $smtpConnection);
340
341 /** Ok, who is sending the message? */
342 fputs($smtpConnection, "MAIL FROM:<$from_addr>\r\n");
343 $tmp = fgets($smtpConnection, 1024);
344 errorCheck($tmp, $smtpConnection);
345
346 /** send who the recipients are */
347 for ($i = 0; $i < count($to); $i++) {
348 fputs($smtpConnection, "RCPT TO:<$to[$i]>\r\n");
349 $tmp = fgets($smtpConnection, 1024);
350 errorCheck($tmp, $smtpConnection);
351 }
352 for ($i = 0; $i < count($cc); $i++) {
353 fputs($smtpConnection, "RCPT TO:<$cc[$i]>\r\n");
354 $tmp = fgets($smtpConnection, 1024);
355 errorCheck($tmp, $smtpConnection);
356 }
357 for ($i = 0; $i < count($bcc); $i++) {
358 fputs($smtpConnection, "RCPT TO:<$bcc[$i]>\r\n");
359 $tmp = fgets($smtpConnection, 1024);
360 errorCheck($tmp, $smtpConnection);
361 }
362
363 /** Lets start sending the actual message */
364 fputs($smtpConnection, "DATA\r\n");
365 $tmp = fgets($smtpConnection, 1024);
366 errorCheck($tmp, $smtpConnection);
367
368 // Send the message
369 $headerlength = write822Header ($smtpConnection, $t, $c, $b, $subject, $more_headers);
370 $bodylength = writeBody($smtpConnection, $body);
371
372 fputs($smtpConnection, ".\r\n"); // end the DATA part
373 $tmp = fgets($smtpConnection, 1024);
374 $num = errorCheck($tmp, $smtpConnection);
375 if ($num != 250) {
376 $tmp = nl2br(htmlspecialchars($tmp));
377 echo "ERROR<BR>Message not sent!<BR>Reason given: $tmp<BR></BODY></HTML>";
378 }
379
380 fputs($smtpConnection, "QUIT\r\n"); // log off
381
382 fclose($smtpConnection);
383
384 return ($headerlength + $bodylength);
385 }
386
387
388 function errorCheck($line, $smtpConnection) {
389 global $page_header_php;
390 global $color;
391 if (!isset($page_header_php)) {
392 include "../functions/page_header.php";
393 }
394
395 // Read new lines on a multiline response
396 $lines = $line;
397 while(ereg("^[0-9]+-", $line)) {
398 $line = fgets($smtpConnection, 1024);
399 $lines .= $line;
400 }
401
402 // Status: 0 = fatal
403 // 5 = ok
404
405 $err_num = substr($line, 0, strpos($line, " "));
406 switch ($err_num) {
407 case 500: $message = "Syntax error; command not recognized";
408 $status = 0;
409 break;
410 case 501: $message = "Syntax error in parameters or arguments";
411 $status = 0;
412 break;
413 case 502: $message = "Command not implemented";
414 $status = 0;
415 break;
416 case 503: $message = "Bad sequence of commands";
417 $status = 0;
418 break;
419 case 504: $message = "Command parameter not implemented";
420 $status = 0;
421 break;
422
423
424 case 211: $message = "System status, or system help reply";
425 $status = 5;
426 break;
427 case 214: $message = "Help message";
428 $status = 5;
429 break;
430
431
432 case 220: $message = "Service ready";
433 $status = 5;
434 break;
435 case 221: $message = "Service closing transmission channel";
436 $status = 5;
437 break;
438 case 421: $message = "Service not available, closing chanel";
439 $status = 0;
440 break;
441
442
443 case 250: $message = "Requested mail action okay, completed";
444 $status = 5;
445 break;
446 case 251: $message = "User not local; will forward";
447 $status = 5;
448 break;
449 case 450: $message = "Requested mail action not taken: mailbox unavailable";
450 $status = 0;
451 break;
452 case 550: $message = "Requested action not taken: mailbox unavailable";
453 $status = 0;
454 break;
455 case 451: $message = "Requested action aborted: error in processing";
456 $status = 0;
457 break;
458 case 551: $message = "User not local; please try forwarding";
459 $status = 0;
460 break;
461 case 452: $message = "Requested action not taken: insufficient system storage";
462 $status = 0;
463 break;
464 case 552: $message = "Requested mail action aborted: exceeding storage allocation";
465 $status = 0;
466 break;
467 case 553: $message = "Requested action not taken: mailbox name not allowed";
468 $status = 0;
469 break;
470 case 354: $message = "Start mail input; end with .";
471 $status = 5;
472 break;
473 case 554: $message = "Transaction failed";
474 $status = 0;
475 break;
476 default: $message = "Unknown response: ". nl2br(htmlspecialchars($lines));
477 $status = 0;
478 $error_num = "001";
479 break;
480 }
481
482 if ($status == 0) {
483 displayPageHeader($color, "None");
484 echo "<TT>";
485 echo "<br><b><font color=\"$color[1]\">ERROR</font></b><br><br>";
486 echo "&nbsp;&nbsp;&nbsp;<B>Error Number: </B>$err_num<BR>";
487 echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<B>Reason: </B>$message<BR>";
488 $lines = nl2br(htmlspecialchars($lines));
489 echo "<B>Server Response: </B>$lines<BR>";
490 echo "<BR>MAIL NOT SENT";
491 echo "</TT></BODY></HTML>";
492 exit;
493 }
494 return $err_num;
495 }
496
497 function sendMessage($t, $c, $b, $subject, $body, $reply_id) {
498 global $useSendmail, $msg_id, $is_reply, $mailbox;
499 global $data_dir, $username, $domain, $key, $version, $sent_folder, $imapServerAddress, $imapPort;
500 $more_headers = Array();
501
502 $imap_stream = sqimap_login($username, $key, $imapServerAddress, $imapPort, 1);
503
504 if ($reply_id) {
505 sqimap_mailbox_select ($imap_stream, $mailbox);
506 sqimap_messages_flag ($imap_stream, $reply_id, $reply_id, "Answered");
507
508 // Insert In-Reply-To and References headers if the
509 // message-id of the message we reply to is set (longer than "<>")
510 // The References header should really be the old Referenced header
511 // with the message ID appended, but it can be only the message ID too.
512 $hdr = sqimap_get_small_header ($imap_stream, $reply_id, false);
513 if(strlen($hdr->message_id) > 2) {
514 $more_headers["In-Reply-To"] = $hdr->message_id;
515 $more_headers["References"] = $hdr->message_id;
516 }
517 sqimap_mailbox_close($imap_stream);
518 }
519
520 if ($useSendmail==true) {
521 $length = sendSendmail($t, $c, $b, $subject, $body, $more_headers);
522 } else {
523 $length = sendSMTP($t, $c, $b, $subject, $body, $more_headers);
524 }
525
526 if (sqimap_mailbox_exists ($imap_stream, $sent_folder)) {
527 sqimap_append ($imap_stream, $sent_folder, $length);
528 write822Header ($imap_stream, $t, $c, $b, $subject, $more_headers);
529 writeBody ($imap_stream, $body);
530 sqimap_append_done ($imap_stream);
531 }
532 sqimap_logout($imap_stream);
533 // Delete the files uploaded for attaching (if any).
534 deleteAttachments();
535 }
536
537 ?>