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