Fixed bug with 8-bit characters in personal name when sending mail.
[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 global $version, $REMOTE_ADDR, $SERVER_NAME, $REMOTE_PORT;
78
79 static $mimeBoundaryString;
80
81 if ($mimeBoundaryString == "") {
82 $temp = "SquirrelMail".$version.$REMOTE_ADDR.$SERVER_NAME.
83 $REMOTE_PORT;
84 $mimeBoundaryString = "=-_+".substr(md5($temp),1,20);
85 }
86
87 return $mimeBoundaryString;
88 }
89
90 /* Time offset for correct timezone */
91 function timezone () {
92 $diff_second = date("Z");
93 if ($diff_second > 0)
94 $sign = "+";
95 else
96 $sign = "-";
97
98 $diff_second = abs($diff_second);
99
100 $diff_hour = floor ($diff_second / 3600);
101 $diff_minute = floor (($diff_second-3600*$diff_hour) / 60);
102
103 $zonename = "(".strftime("%Z").")";
104 $result = sprintf ("%s%02d%02d %s", $sign, $diff_hour, $diff_minute, $zonename);
105 return ($result);
106 }
107
108 /* Print all the needed RFC822 headers */
109 function write822Header ($fp, $t, $c, $b, $subject, $more_headers) {
110 global $REMOTE_ADDR, $SERVER_NAME, $REMOTE_PORT;
111 global $data_dir, $username, $domain, $version, $useSendmail;
112 global $default_charset;
113
114 // Storing the header to make sure the header is the same
115 // everytime the header is printed.
116 static $header, $headerlength;
117
118 if ($header == "") {
119 $to = parseAddrs($t);
120 $cc = parseAddrs($c);
121 $bcc = parseAddrs($b);
122 $reply_to = getPref($data_dir, $username, "reply_to");
123 $from = getPref($data_dir, $username, "full_name");
124 $from_addr = getPref($data_dir, $username, "email_address");
125
126 if ($from_addr == "")
127 $from_addr = "$username@$domain";
128
129 $to_list = getLineOfAddrs($to);
130 $cc_list = getLineOfAddrs($cc);
131 $bcc_list = getLineOfAddrs($bcc);
132
133 /* Encoding 8-bit characters and making from line */
134 $subject = encodeHeader($subject);
135 if ($from == "")
136 $from = "<$from_addr>";
137 else
138 $from = encodeHeader($from) . " <$from_addr>";
139
140 /* This creates an RFC 822 date */
141 $date = date("D, j M Y H:i:s ", mktime()) . timezone();
142
143 /* Create a message-id */
144 $message_id = "<" . $REMOTE_PORT . "." . $REMOTE_ADDR . ".";
145 $message_id .= time() . "@" . $SERVER_NAME .">";
146
147 /* Make an RFC822 Received: line */
148 $header = "Received: from $REMOTE_ADDR by $SERVER_NAME with HTTP; ";
149 $header .= "$date\r\n";
150
151 /* Insert the rest of the header fields */
152 $header .= "Message-ID: $message_id\r\n";
153 $header .= "Date: $date\r\n";
154 $header .= "Subject: $subject\r\n";
155 $header .= "From: $from\r\n";
156 $header .= "To: $to_list \r\n"; // Who it's TO
157
158 /* Insert headers from the $more_headers array */
159 if(is_array($more_headers)) {
160 reset($more_headers);
161 while(list($h_name, $h_val) = each($more_headers)) {
162 $header .= sprintf("%s: %s\r\n", $h_name, $h_val);
163 }
164 }
165
166 if ($cc_list) {
167 $header .= "Cc: $cc_list\r\n"; // Who the CCs are
168 }
169
170 if ($reply_to != "")
171 $header .= "Reply-To: $reply_to\r\n";
172
173 if ($useSendmail) {
174 if ($bcc_list) {
175 // BCCs is removed from header by sendmail
176 $header .= "Bcc: $bcc_list\r\n";
177 }
178 }
179
180 $header .= "X-Mailer: SquirrelMail (version $version)\r\n"; // Identify SquirrelMail
181
182 // Do the MIME-stuff
183 $header .= "MIME-Version: 1.0\r\n";
184
185 if (isMultipart()) {
186 $header .= "Content-Type: multipart/mixed; boundary=\"";
187 $header .= mimeBoundary();
188 $header .= "\"\r\n";
189 } else {
190 if ($default_charset != "")
191 $header .= "Content-Type: text/plain; charset=$default_charset\r\n";
192 else
193 $header .= "Content-Type: text/plain;\r\n";
194 $header .= "Content-Transfer-Encoding: 8bit\r\n";
195 }
196 $header .= "\r\n"; // One blank line to separate header and body
197
198 $headerlength = strlen($header);
199 }
200
201 // Write the header
202 fputs ($fp, $header);
203
204 return $headerlength;
205 }
206
207 // Send the body
208 function writeBody ($fp, $passedBody) {
209 global $default_charset;
210
211 $attachmentlength = 0;
212
213 if (isMultipart()) {
214 $body = "--".mimeBoundary()."\r\n";
215
216 if ($default_charset != "")
217 $body .= "Content-Type: text/plain; charset=$default_charset\r\n";
218 else
219 $body .= "Content-Type: text/plain\r\n";
220
221 $body .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
222 $body .= stripslashes($passedBody) . "\r\n";
223 fputs ($fp, $body);
224
225 $attachmentlength = attachFiles($fp);
226
227 $postbody .= "\r\n--".mimeBoundary()."--\r\n\r\n";
228 fputs ($fp, $postbody);
229 } else {
230 $body = stripslashes($passedBody) . "\r\n";
231 fputs ($fp, $body);
232 $postbody = "\r\n";
233 fputs ($fp, $postbody);
234 }
235
236 return (strlen($body) + strlen($postbody) + $attachmentlength);
237 }
238
239 // Send mail using the sendmail command
240 function sendSendmail($t, $c, $b, $subject, $body, $more_headers) {
241 global $sendmail_path, $username, $domain;
242
243 // open pipe to sendmail
244 $fp = popen (escapeshellcmd("$sendmail_path -t -f$username@$domain"), "w");
245
246 $headerlength = write822Header ($fp, $t, $c, $b, $subject, $more_headers);
247 $bodylength = writeBody($fp, $body);
248
249 pclose($fp);
250
251 return ($headerlength + $bodylength);
252 }
253
254 function smtpReadData($smtpConnection) {
255 $read = fgets($smtpConnection, 1024);
256 $counter = 0;
257 while ($read) {
258 echo $read . "<BR>";
259 $data[$counter] = $read;
260 $read = fgets($smtpConnection, 1024);
261 $counter++;
262 }
263 }
264
265 function sendSMTP($t, $c, $b, $subject, $body, $more_headers) {
266 global $username, $domain, $version, $smtpServerAddress, $smtpPort,
267 $data_dir, $color;
268
269 $to = parseAddrs($t);
270 $cc = parseAddrs($c);
271 $bcc = parseAddrs($b);
272 $from_addr = getPref($data_dir, $username, "email_address");
273
274 if ($from_addr == "")
275 $from_addr = "$username@$domain";
276
277 $smtpConnection = fsockopen($smtpServerAddress, $smtpPort, $errorNumber, $errorString);
278 if (!$smtpConnection) {
279 echo "Error connecting to SMTP Server.<br>";
280 echo "$errorNumber : $errorString<br>";
281 exit;
282 }
283 $tmp = nl2br(htmlspecialchars(fgets($smtpConnection, 1024)));
284 errorCheck($tmp);
285
286 $to_list = getLineOfAddrs($to);
287 $cc_list = getLineOfAddrs($cc);
288
289 /** Lets introduce ourselves */
290 fputs($smtpConnection, "HELO $domain\r\n");
291 $tmp = nl2br(htmlspecialchars(fgets($smtpConnection, 1024)));
292 errorCheck($tmp);
293
294 /** Ok, who is sending the message? */
295 fputs($smtpConnection, "MAIL FROM:<$from_addr>\r\n");
296 $tmp = nl2br(htmlspecialchars(fgets($smtpConnection, 1024)));
297 errorCheck($tmp);
298
299 /** send who the recipients are */
300 for ($i = 0; $i < count($to); $i++) {
301 fputs($smtpConnection, "RCPT TO:<$to[$i]>\r\n");
302 $tmp = nl2br(htmlspecialchars(fgets($smtpConnection, 1024)));
303 errorCheck($tmp);
304 }
305 for ($i = 0; $i < count($cc); $i++) {
306 fputs($smtpConnection, "RCPT TO:<$cc[$i]>\r\n");
307 $tmp = nl2br(htmlspecialchars(fgets($smtpConnection, 1024)));
308 errorCheck($tmp);
309 }
310 for ($i = 0; $i < count($bcc); $i++) {
311 fputs($smtpConnection, "RCPT TO:<$bcc[$i]>\r\n");
312 $tmp = nl2br(htmlspecialchars(fgets($smtpConnection, 1024)));
313 errorCheck($tmp);
314 }
315
316 /** Lets start sending the actual message */
317 fputs($smtpConnection, "DATA\r\n");
318 $tmp = nl2br(htmlspecialchars(fgets($smtpConnection, 1024)));
319 errorCheck($tmp);
320
321 // Send the message
322 $headerlength = write822Header ($smtpConnection, $t, $c, $b, $subject, $more_headers);
323 $bodylength = writeBody($smtpConnection, $body);
324
325 fputs($smtpConnection, ".\r\n"); // end the DATA part
326 $tmp = nl2br(htmlspecialchars(fgets($smtpConnection, 1024)));
327 $num = errorCheck($tmp);
328 if ($num != 250) {
329 echo "ERROR<BR>Message not sent!<BR>Reason given: $tmp<BR></BODY></HTML>";
330 }
331
332 fputs($smtpConnection, "QUIT\r\n"); // log off
333
334 fclose($smtpConnection);
335
336 return ($headerlength + $bodylength);
337 }
338
339
340 function errorCheck($line) {
341 global $color;
342 // Status: 0 = fatal
343 // 5 = ok
344
345 $err_num = substr($line, 0, strpos($line, " "));
346 switch ($err_num) {
347 case 500: $message = "Syntax error; command not recognized";
348 $status = 0;
349 break;
350 case 501: $message = "Syntax error in parameters or arguments";
351 $status = 0;
352 break;
353 case 502: $message = "Command not implemented";
354 $status = 0;
355 break;
356 case 503: $message = "Bad sequence of commands";
357 $status = 0;
358 break;
359 case 504: $message = "Command parameter not implemented";
360 $status = 0;
361 break;
362
363
364 case 211: $message = "System status, or system help reply";
365 $status = 5;
366 break;
367 case 214: $message = "Help message";
368 $status = 5;
369 break;
370
371
372 case 220: $message = "Service ready";
373 $status = 5;
374 break;
375 case 221: $message = "Service closing transmission channel";
376 $status = 5;
377 break;
378 case 421: $message = "Service not available, closing chanel";
379 $status = 0;
380 break;
381
382
383 case 250: $message = "Requested mail action okay, completed";
384 $status = 5;
385 break;
386 case 251: $message = "User not local; will forward";
387 $status = 5;
388 break;
389 case 450: $message = "Requested mail action not taken: mailbox unavailable";
390 $status = 0;
391 break;
392 case 550: $message = "Requested action not taken: mailbox unavailable";
393 $status = 0;
394 break;
395 case 451: $message = "Requested action aborted: error in processing";
396 $status = 0;
397 break;
398 case 551: $message = "User not local; please try forwarding";
399 $status = 0;
400 break;
401 case 452: $message = "Requested action not taken: insufficient system storage";
402 $status = 0;
403 break;
404 case 552: $message = "Requested mail action aborted: exceeding storage allocation";
405 $status = 0;
406 break;
407 case 553: $message = "Requested action not taken: mailbox name not allowed";
408 $status = 0;
409 break;
410 case 354: $message = "Start mail input; end with .";
411 $status = 5;
412 break;
413 case 554: $message = "Transaction failed";
414 $status = 0;
415 break;
416 default: $message = "Unknown response: $line";
417 $status = 0;
418 $error_num = "001";
419 break;
420 }
421
422 if ($status == 0) {
423 echo "<HTML><BODY BGCOLOR=#ffffff>";
424 echo "<TT>";
425 echo "<BR><B>ERROR</B><BR><BR>";
426 echo "&nbsp;&nbsp;&nbsp;<B>Error Number: </B>$err_num<BR>";
427 echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<B>Reason: </B>$message<BR>";
428 echo "<B>Server Response: </B>$line<BR>";
429 echo "<BR>MAIL NOT SENT";
430 echo "</TT></BODY></HTML>";
431 exit;
432 }
433 return $err_num;
434 }
435
436 function sendMessage($t, $c, $b, $subject, $body, $reply_id) {
437 global $useSendmail, $msg_id, $is_reply, $mailbox;
438 global $data_dir, $username, $domain, $key, $version, $sent_folder, $imapServerAddress, $imapPort;
439 $more_headers = Array();
440
441 $imap_stream = sqimap_login($username, $key, $imapServerAddress, $imapPort, 1);
442
443 if ($reply_id) {
444 sqimap_mailbox_select ($imap_stream, $mailbox);
445 sqimap_messages_flag ($imap_stream, $reply_id, $reply_id, "Answered");
446
447 // Insert In-Reply-To and References headers if the
448 // message-id of the message we reply to is set (longer than "<>")
449 // The References header should really be the old Referenced header
450 // with the message ID appended, but it can be only the message ID too.
451 $hdr = sqimap_get_small_header ($imap_stream, $reply_id, false);
452 if(strlen($hdr->message_id) > 2) {
453 $more_headers["In-Reply-To"] = $hdr->message_id;
454 $more_headers["References"] = $hdr->message_id;
455 }
456 }
457
458 if ($useSendmail==true) {
459 $length = sendSendmail($t, $c, $b, $subject, $body, $more_headers);
460 } else {
461 $length = sendSMTP($t, $c, $b, $subject, $body, $more_headers);
462 }
463
464 if (sqimap_mailbox_exists ($imap_stream, $sent_folder)) {
465 sqimap_append ($imap_stream, $sent_folder, $length);
466 write822Header ($imap_stream, $t, $c, $b, $subject, $more_headers);
467 writeBody ($imap_stream, $body);
468 sqimap_append_done ($imap_stream);
469 }
470
471 // Delete the files uploaded for attaching (if any).
472 deleteAttachments();
473 }
474 ?>