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