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