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