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