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