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