This fixes the broken smtp transport when dot's are not handled properly.
[squirrelmail.git] / functions / smtp.php
1 <?php
2
3 /**
4 * smtp.php
5 *
6 * Copyright (c) 1999-2002 The SquirrelMail Project Team
7 * Licensed under the GNU GPL. For full terms see the file COPYING.
8 *
9 * This contains all the functions needed to send messages through
10 * an smtp server or sendmail.
11 *
12 * $Id$
13 */
14
15 require_once('../functions/addressbook.php');
16 require_once('../functions/plugin.php');
17 require_once('../functions/prefs.php');
18
19 global $username, $popuser, $domain;
20
21 /* This should most probably go to some initialization... */
22 if (ereg("^([^@%/]+)[@%/](.+)$", $username, $usernamedata)) {
23 $popuser = $usernamedata[1];
24 $domain = $usernamedata[2];
25 unset($usernamedata);
26 } else {
27 $popuser = $username;
28 }
29 /* We need domain for smtp */
30 if (!$domain) {
31 $domain = getenv('HOSTNAME');
32 }
33
34 /* Returns true only if this message is multipart */
35 function isMultipart ($session) {
36 global $attachments;
37
38 foreach ($attachments as $info) {
39 if ($info['session'] == $session) {
40 return true;
41 }
42 }
43 return false;
44 }
45
46 /* looks up aliases in the addressbook and expands them to
47 * the full address.
48 *
49 * Adds @$domain if it wasn't in the address book and if it
50 * doesn't have an @ symbol in it
51 */
52 function expandAddrs ($array) {
53 global $domain;
54
55 /* don't show errors -- kinda critical that we don't see
56 * them here since the redirect won't work if we do show them
57 */
58 $abook = addressbook_init(false, true);
59 for ($i=0; $i < count($array); $i++) {
60 $result = $abook->lookup($array[$i]);
61 $ret = "";
62 if (isset($result['email'])) {
63 if (isset($result['name'])) {
64 $ret = '"'.$result['name'].'" ';
65 }
66 $ret .= '<'.$result['email'].'>';
67 $array[$i] = $ret;
68 }
69 else
70 {
71 if (strpos($array[$i], '@') === false) {
72 $array[$i] .= '@' . $domain;
73 }
74 $array[$i] = '<' . $array[$i] . '>';
75 }
76 }
77 return $array;
78 }
79
80
81 /* looks up aliases in the addressbook and expands them to
82 * the RFC 821 valid RCPT address. ie <user@example.com>
83 * Adds @$domain if it wasn't in the address book and if it
84 * doesn't have an @ symbol in it
85 */
86 function expandRcptAddrs ($array) {
87 global $domain;
88
89 /* don't show errors -- kinda critical that we don't see
90 * them here since the redirect won't work if we do show them
91 */
92 $abook = addressbook_init(false, true);
93 for ($i=0; $i < count($array); $i++) {
94 $result = $abook->lookup($array[$i]);
95 $ret = "";
96 if (isset($result['email'])) {
97 $ret = '<'.$result['email'].'>';
98 $array[$i] = $ret;
99 }
100 else {
101 if (strpos($array[$i], '@') === false) {
102 $array[$i] .= '@' . $domain;
103 }
104 $array[$i] = '<' . $array[$i] . '>';
105 }
106 }
107 return $array;
108 }
109
110
111 /* Attach the files that are due to be attached
112 */
113 function attachFiles ($fp, $session, $rn="\r\n", $checkdot = false) {
114 global $attachments, $attachment_dir, $username;
115
116 $length = 0;
117
118 $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
119 if (isMultipart($session)) {
120 foreach ($attachments as $info) {
121 if ($info['session'] == $session) {
122 if (isset($info['type'])) {
123 $filetype = $info['type'];
124 }
125 else {
126 $filetype = 'application/octet-stream';
127 }
128
129 $header = '--' . mimeBoundary() . "$rn";
130 if ( isset($info['remotefilename'])
131 && $info['remotefilename'] != '') {
132 $header .= "Content-Type: $filetype; name=\"" .
133 encodeHeader(charset_encode_japanese($info['remotefilename'])) . "\"$rn";
134 $header .= "Content-Disposition: attachment; filename=\""
135 . encodeHeader(charset_encode_japanese($info['remotefilename'])) . "\"$rn";
136 } else {
137 $header .= "Content-Type: $filetype$rn";
138 }
139
140
141 /* Use 'rb' for NT systems -- read binary
142 * Unix doesn't care -- everything's binary! :-)
143 */
144
145 $filename = $hashed_attachment_dir . '/'
146 . $info['localfilename'];
147 $file = fopen ($filename, 'rb');
148 if (substr($filetype, 0, 5) == 'text/' ||
149 substr($filetype, 0, 8) == 'message/' ) {
150 $header .= $rn;
151 if ($fp) {
152 fputs ($fp, $header);
153 }
154 $length += strlen($header);
155 if ($checkdot) {
156 $checkdot_begin=true;
157 } else {
158 $checkdot_begin=false;
159 }
160 while ($tmp = fgets($file, 4096)) {
161 $tmp = str_replace("\r\n", "\n", $tmp);
162 $tmp = str_replace("\r", "\n", $tmp);
163 /* In order to remove the problem of users not able to create
164 * messages with "." on a blank line, RFC821 has made provision
165 * in section 4.5.2 (Transparency).
166 */
167 if ($tmp{0} == '.' && $checkdot_begin) {
168 $tmp = '.' . $tmp;
169 }
170 if ($checkdot) {
171 $tmp = str_replace("\n.","\n..",$tmp);
172 }
173
174 if ($rn == "\r\n"){
175 $tmp = str_replace("\n", "\r\n", $tmp);
176 }
177 $tmp_length = strlen($tmp);
178 if ($tmp{$tmp_length-1} == "\n" && $checkdot) {
179 $checkdot_begin = true;
180 } else {
181 $checkdot_begin = false;
182 }
183 if ($fp) {
184 fputs($fp, $tmp);
185 }
186 $length += strlen($tmp_length);
187 }
188
189 if (substr($tmp, strlen($tmp) - strlen($rn), strlen($rn)) != $rn) {
190 if ($fp) {
191 fputs($fp, $rn);
192 }
193 }
194 } else {
195 $header .= "Content-Transfer-Encoding: base64"
196 . "$rn" . "$rn";
197 if ($fp) fputs ($fp, $header);
198 $length += strlen($header);
199 while ($tmp = fread($file, 570)) {
200 $encoded = chunk_split(base64_encode($tmp));
201 $length += strlen($encoded);
202 if ($fp) fputs ($fp, $encoded);
203 }
204 }
205 fclose ($file);
206 }
207 }
208 }
209 return $length;
210 }
211
212 /* Delete files that are uploaded for attaching
213 */
214 function deleteAttachments($session) {
215 global $username, $attachments, $attachment_dir, $data_dir;
216 $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
217
218 $rem_attachments = array();
219 foreach ($attachments as $info) {
220 if ($info['session'] == $session) {
221 $attached_file = "$hashed_attachment_dir/$info[localfilename]";
222 if (file_exists($attached_file)) {
223 unlink($attached_file);
224 }
225 } else {
226 $rem_attachments[] = $info;
227 }
228 }
229 $attachments = $rem_attachments;
230 setPref($data_dir, $username, 'attachments', serialize($attachments));
231 }
232
233 /* Return a nice MIME-boundary
234 */
235 function mimeBoundary () {
236 static $mimeBoundaryString;
237
238 if ( !isset( $mimeBoundaryString ) ||
239 $mimeBoundaryString == '') {
240 $mimeBoundaryString = '----=_' . date( 'YmdHis' ) . '_' .
241 mt_rand( 10000, 99999 );
242 }
243
244 return $mimeBoundaryString;
245 }
246
247 /* Time offset for correct timezone */
248 function timezone () {
249 global $invert_time;
250
251 $diff_second = date('Z');
252 if ($invert_time) {
253 $diff_second = - $diff_second;
254 }
255 if ($diff_second > 0) {
256 $sign = '+';
257 }
258 else {
259 $sign = '-';
260 }
261
262 $diff_second = abs($diff_second);
263
264 $diff_hour = floor ($diff_second / 3600);
265 $diff_minute = floor (($diff_second-3600*$diff_hour) / 60);
266
267 $zonename = '('.strftime('%Z').')';
268 $result = sprintf ("%s%02d%02d %s", $sign, $diff_hour, $diff_minute,
269 $zonename);
270 return ($result);
271 }
272
273 /* Print all the needed RFC822 headers */
274 function write822Header ($fp, $t, $c, $b, $subject, $body, $more_headers, $session, $rn="\r\n") {
275 global $REMOTE_ADDR, $SERVER_NAME, $REMOTE_PORT;
276 global $data_dir, $username, $popuser, $domain, $version, $useSendmail;
277 global $default_charset, $HTTP_VIA, $HTTP_X_FORWARDED_FOR;
278 global $REMOTE_HOST, $identity;
279
280 /* Storing the header to make sure the header is the same
281 * everytime the header is printed.
282 */
283 static $header, $headerlength, $headerrn;
284
285 if ($header == '') {
286 $headerrn = $rn;
287 $to = expandAddrs(parseAddrs($t));
288 $cc = expandAddrs(parseAddrs($c));
289 $bcc = expandAddrs(parseAddrs($b));
290 if (isset($identity) && $identity != 'default') {
291 $reply_to = getPref($data_dir, $username, 'reply_to' . $identity);
292 $from = getPref($data_dir, $username, 'full_name' . $identity);
293 $from_addr = getFrom();
294 } else {
295 $reply_to = getPref($data_dir, $username, 'reply_to');
296 $from = getPref($data_dir, $username, 'full_name');
297 $from_addr = getFrom();
298 }
299
300 $to_list = getLineOfAddrs($to);
301 $cc_list = getLineOfAddrs($cc);
302 $bcc_list = getLineOfAddrs($bcc);
303
304 /* Encoding 8-bit characters and making from line */
305 $subject = encodeHeader($subject);
306 if ($from == '') {
307 $from = "<$from_addr>";
308 }
309 else {
310 $from = '"' . encodeHeader($from) . "\" <$from_addr>";
311 }
312
313 /* This creates an RFC 822 date */
314 $date = date("D, j M Y H:i:s ", mktime()) . timezone();
315
316 /* Create a message-id */
317 $message_id = '<' . $REMOTE_PORT . '.' . $REMOTE_ADDR . '.';
318 $message_id .= time() . '.squirrel@' . $SERVER_NAME .'>';
319
320 /* Make an RFC822 Received: line */
321 if (isset($REMOTE_HOST)) {
322 $received_from = "$REMOTE_HOST ([$REMOTE_ADDR])";
323 }
324 else {
325 $received_from = $REMOTE_ADDR;
326 }
327
328 if (isset($HTTP_VIA) || isset ($HTTP_X_FORWARDED_FOR)) {
329 if ($HTTP_X_FORWARDED_FOR == '') {
330 $HTTP_X_FORWARDED_FOR = 'unknown';
331 }
332 $received_from .= " (proxying for $HTTP_X_FORWARDED_FOR)";
333 }
334
335 $header = "Received: from $received_from" . $rn;
336 $header .= " (SquirrelMail authenticated user $username)" . $rn;
337 $header .= " by $SERVER_NAME with HTTP;" . $rn;
338 $header .= " $date" . $rn;
339
340 /* Insert the rest of the header fields */
341 $header .= "Message-ID: $message_id" . $rn;
342 $header .= "Date: $date" . $rn;
343 $header .= "Subject: $subject" . $rn;
344 $header .= "From: $from" . $rn;
345 $header .= "To: $to_list" . $rn; // Who it's TO
346
347 if (isset($more_headers["Content-Type"])) {
348 $contentType = $more_headers["Content-Type"];
349 unset($more_headers["Content-Type"]);
350 }
351 else {
352 if (isMultipart($session)) {
353 $contentType = "multipart/mixed;";
354 }
355 else {
356 if ($default_charset != '') {
357 $contentType = 'text/plain; charset='.$default_charset;
358 }
359 else {
360 $contentType = 'text/plain;';
361 }
362 }
363 }
364
365 /* Insert headers from the $more_headers array */
366 if(is_array($more_headers)) {
367 reset($more_headers);
368 while(list($h_name, $h_val) = each($more_headers)) {
369 if ($h_name == 'References') {
370 $h_val = str_replace(' ', "$rn ", $h_val);
371 }
372 $header .= sprintf("%s: %s%s", $h_name, $h_val, $rn);
373 }
374 }
375
376 if ($cc_list) {
377 $header .= "Cc: $cc_list" . $rn; // Who the CCs are
378 }
379
380 if ($reply_to != '') {
381 $header .= "Reply-To: $reply_to" . $rn;
382 }
383
384 if ($useSendmail) {
385 if ($bcc_list) {
386 // BCCs is removed from header by sendmail
387 $header .= "Bcc: $bcc_list" . $rn;
388 }
389 }
390
391 /* Identify SquirrelMail */
392 $header .= "X-Mailer: SquirrelMail (version $version)" . $rn;
393
394 /* Do the MIME-stuff */
395 $header .= "MIME-Version: 1.0" . $rn;
396
397 if (isMultipart($session)) {
398 $header .= 'Content-Type: '.$contentType.' boundary="';
399 $header .= mimeBoundary();
400 $header .= "\"$rn";
401 } else {
402 if (strtolower($default_charset) == 'iso-2022-jp') {
403 if (mb_detect_encoding($body) == 'ASCII') {
404 $header .= 'Content-Type: text/plain; US-ASCII' . $rn;
405 $header .= "Content-Transfer-Encoding: 8bit" . $rn;
406 } else {
407 $header .= 'Content-Type: '.$contentType . $rn;
408 $header .= "Content-Transfer-Encoding: 7bit" . $rn;
409 }
410 } else {
411 $header .= 'Content-Type: ' . $contentType . $rn;
412 $header .= "Content-Transfer-Encoding: 8bit" . $rn;
413 }
414 }
415 $header .= $rn; // One blank line to separate header and body
416
417 $headerlength = strlen($header);
418 }
419
420 if ($headerrn != $rn) {
421 $header = str_replace($headerrn, $rn, $header);
422 $headerlength = strlen($header);
423 $headerrn = $rn;
424 }
425
426 /* Write the header */
427 if ($fp) fputs ($fp, $header);
428
429 return $headerlength;
430 }
431
432 /* Send the body
433 */
434 function writeBody ($fp, $passedBody, $session, $rn="\r\n", $checkdot = false) {
435 global $default_charset;
436
437 $attachmentlength = 0;
438
439 if (isMultipart($session)) {
440 $body = '--'.mimeBoundary() . $rn;
441
442 if ($default_charset != "") {
443 $body .= "Content-Type: text/plain; charset=$default_charset".$rn;
444 }
445 else {
446 $body .= "Content-Type: text/plain" . $rn;
447 }
448
449 if (strtolower($default_charset) == 'iso-2022-jp') {
450 if (mb_detect_encoding($passedBody) == 'ASCII') {
451 $body .= "Content-Transfer-Encoding: 8bit" . $rn . $rn .
452 $passedBody . $rn . $rn;
453 } else {
454 $body .= "Content-Transfer-Encoding: 7bit\r\n\r\n" .
455 mb_convert_encoding($passedBody, 'JIS') . "\r\n\r\n";
456 }
457 } else {
458 $body .= "Content-Transfer-Encoding: 8bit" . $rn . $rn .
459 $passedBody . $rn . $rn;
460 }
461 if ($fp) {
462 fputs ($fp, $body);
463 }
464
465 $attachmentlength = attachFiles($fp, $session, $rn, $checkdot);
466
467 if (!isset($postbody)) {
468 $postbody = "";
469 }
470 $postbody .= $rn . "--" . mimeBoundary() . "--" . $rn . $rn;
471 if ($fp) fputs ($fp, $postbody);
472 } else {
473 if (strtolower($default_charset) == 'iso-2022-jp') {
474 $body = mb_convert_encoding($passedBody, 'JIS') . $rn;
475 } else {
476 $body = $passedBody . $rn;
477 }
478 if ($fp) {
479 fputs ($fp, $body);
480 }
481 $postbody = $rn;
482 if ($fp) {
483 fputs ($fp, $postbody);
484 }
485 }
486
487 return (strlen($body) + strlen($postbody) + $attachmentlength);
488 }
489
490 /* Send mail using the sendmail command
491 */
492 function sendSendmail($t, $c, $b, $subject, $body, $more_headers, $session) {
493 global $sendmail_path, $popuser, $username, $domain;
494
495 /* Build envelope sender address. Make sure it doesn't contain
496 * spaces or other "weird" chars that would allow a user to
497 * exploit the shell/pipe it is used in.
498 */
499 $envelopefrom = getFrom();
500 $envelopefrom = ereg_replace("[[:blank:]]",'', $envelopefrom);
501 $envelopefrom = ereg_replace("[[:space:]]",'', $envelopefrom);
502 $envelopefrom = ereg_replace("[[:cntrl:]]",'', $envelopefrom);
503
504 /**
505 * open pipe to sendmail or qmail-inject
506 * (qmail-inject doesn't accept -t param)
507 */
508 if (strstr($sendmail_path, "qmail-inject")) {
509 $fp = popen (escapeshellcmd("$sendmail_path -f$envelopefrom"), "w");
510 } else {
511 $fp = popen (escapeshellcmd("$sendmail_path -t -f$envelopefrom"), "w");
512 }
513
514 $headerlength = write822Header ($fp, $t, $c, $b, $subject, $body,
515 $more_headers, $session, "\n");
516 $bodylength = writeBody($fp, $body, $session, "\n", true);
517
518 pclose($fp);
519
520 return ($headerlength + $bodylength);
521 }
522
523 function smtpReadData($smtpConnection) {
524 $read = fgets($smtpConnection, 1024);
525 $counter = 0;
526 while ($read) {
527 echo $read . '<BR>';
528 $data[$counter] = $read;
529 $read = fgets($smtpConnection, 1024);
530 $counter++;
531 }
532 }
533
534 function sendSMTP($t, $c, $b, $subject, $body, $more_headers, $session) {
535 global $username, $popuser, $domain, $version, $smtpServerAddress,
536 $smtpPort, $data_dir, $color, $use_authenticated_smtp, $identity,
537 $key, $onetimepad;
538
539 $to = expandRcptAddrs(parseAddrs($t));
540 $cc = expandRcptAddrs(parseAddrs($c));
541 $bcc = expandRcptAddrs(parseAddrs($b));
542 if (isset($identity) && $identity != 'default') {
543 $from_addr = getPref($data_dir, $username,
544 'email_address' . $identity);
545 }
546 else {
547 $from_addr = getPref($data_dir, $username, 'email_address');
548 }
549
550 if (!$from_addr) {
551 $from_addr = "$popuser@$domain";
552 }
553
554 /* POP3 BEFORE SMTP CODE HERE */
555 global $pop_before_smtp;
556 if (isset($pop_before_smtp) && $pop_before_smtp === true) {
557 if (!isset($pop_port)) {
558 $pop_port = 110;
559 }
560 if (!isset($pop_server)) {
561 $pop_server = $smtpServerAddress; /* usually the same host! */
562 }
563 $popConnection = fsockopen($pop_server, $pop_port, $err_no, $err_str);
564 if (!$popConnection) {
565 error_log("Error connecting to POP Server ($pop_server:$pop_port)"
566 . " $err_no : $err_str");
567 } else {
568 $tmp = fgets($popConnection, 1024); /* banner */
569 if (!eregi("^\+OK", $tmp, $regs)) {
570 return(0);
571 }
572 fputs($popConnection, "USER $username\r\n");
573 $tmp = fgets($popConnection, 1024);
574 if (!eregi("^\+OK", $tmp, $regs)) {
575 return(0);
576 }
577 fputs($popConnection, 'PASS ' . OneTimePadDecrypt($key, $onetimepad) . "\r\n");
578 $tmp = fgets($popConnection, 1024);
579 if (!eregi("^\+OK", $tmp, $regs)) {
580 return(0);
581 }
582 fputs($popConnection, "QUIT\r\n"); /* log off */
583 fclose($popConnection);
584 }
585 }
586
587 $smtpConnection = fsockopen($smtpServerAddress, $smtpPort,
588 $errorNumber, $errorString);
589 if (!$smtpConnection) {
590 echo 'Error connecting to SMTP Server.<br>';
591 echo "$errorNumber : $errorString<br>";
592 exit;
593 }
594 $tmp = fgets($smtpConnection, 1024);
595 if (errorCheck($tmp, $smtpConnection)!=5) {
596 return(0);
597 }
598
599 $to_list = getLineOfAddrs($to);
600 $cc_list = getLineOfAddrs($cc);
601
602 /* Lets introduce ourselves */
603 if (! isset ($use_authenticated_smtp)
604 || $use_authenticated_smtp == false) {
605 fputs($smtpConnection, "HELO $domain\r\n");
606 $tmp = fgets($smtpConnection, 1024);
607 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
608 } else {
609 fputs($smtpConnection, "EHLO $domain\r\n");
610 $tmp = fgets($smtpConnection, 1024);
611 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
612
613 fputs($smtpConnection, "AUTH LOGIN\r\n");
614 $tmp = fgets($smtpConnection, 1024);
615 if (errorCheck($tmp, $smtpConnection)!=5) {
616 return(0);
617 }
618
619 fputs($smtpConnection, base64_encode ($username) . "\r\n");
620 $tmp = fgets($smtpConnection, 1024);
621 if (errorCheck($tmp, $smtpConnection)!=5) {
622 return(0);
623 }
624
625 fputs($smtpConnection, base64_encode
626 (OneTimePadDecrypt($key, $onetimepad)) . "\r\n");
627 $tmp = fgets($smtpConnection, 1024);
628 if (errorCheck($tmp, $smtpConnection)!=5) {
629 return(0);
630 }
631 }
632
633 /* Ok, who is sending the message? */
634 fputs($smtpConnection, "MAIL FROM: <$from_addr>\r\n");
635 $tmp = fgets($smtpConnection, 1024);
636 if (errorCheck($tmp, $smtpConnection)!=5) {
637 return(0);
638 }
639
640 /* send who the recipients are */
641 for ($i = 0; $i < count($to); $i++) {
642 fputs($smtpConnection, "RCPT TO: $to[$i]\r\n");
643 $tmp = fgets($smtpConnection, 1024);
644 if (errorCheck($tmp, $smtpConnection)!=5) {
645 return(0);
646 }
647 }
648 for ($i = 0; $i < count($cc); $i++) {
649 fputs($smtpConnection, "RCPT TO: $cc[$i]\r\n");
650 $tmp = fgets($smtpConnection, 1024);
651 if (errorCheck($tmp, $smtpConnection)!=5) {
652 return(0);
653 }
654 }
655 for ($i = 0; $i < count($bcc); $i++) {
656 fputs($smtpConnection, "RCPT TO: $bcc[$i]\r\n");
657 $tmp = fgets($smtpConnection, 1024);
658 if (errorCheck($tmp, $smtpConnection)!=5) {
659 return(0);
660 }
661 }
662
663 /* Lets start sending the actual message */
664 fputs($smtpConnection, "DATA\r\n");
665 $tmp = fgets($smtpConnection, 1024);
666 if (errorCheck($tmp, $smtpConnection)!=5) {
667 return(0);
668 }
669
670 /* Send the message */
671 $headerlength = write822Header ($smtpConnection, $t, $c, $b,
672 $subject, $body, $more_headers, $session);
673 $bodylength = writeBody($smtpConnection, $body, $session, "\r\n", true);
674
675 fputs($smtpConnection, ".\r\n"); /* end the DATA part */
676 $tmp = fgets($smtpConnection, 1024);
677 $num = errorCheck($tmp, $smtpConnection, true);
678 if ($num != 250) {
679 return(0);
680 }
681
682 fputs($smtpConnection, "QUIT\r\n"); /* log off */
683
684 fclose($smtpConnection);
685
686 return ($headerlength + $bodylength);
687 }
688
689
690 function errorCheck($line, $smtpConnection, $verbose = false) {
691 global $color, $compose_new_win;
692
693 /* Read new lines on a multiline response */
694 $lines = $line;
695 while(ereg("^[0-9]+-", $line)) {
696 $line = fgets($smtpConnection, 1024);
697 $lines .= $line;
698 }
699
700 /* Status: 0 = fatal
701 * 5 = ok
702 */
703 $err_num = substr($line, 0, strpos($line, " "));
704 switch ($err_num) {
705 case 500: $message = 'Syntax error; command not recognized';
706 $status = 0;
707 break;
708 case 501: $message = 'Syntax error in parameters or arguments';
709 $status = 0;
710 break;
711 case 502: $message = 'Command not implemented';
712 $status = 0;
713 break;
714 case 503: $message = 'Bad sequence of commands';
715 $status = 0;
716 break;
717 case 504: $message = 'Command parameter not implemented';
718 $status = 0;
719 break;
720
721 case 211: $message = 'System status, or system help reply';
722 $status = 5;
723 break;
724 case 214: $message = 'Help message';
725 $status = 5;
726 break;
727
728 case 220: $message = 'Service ready';
729 $status = 5;
730 break;
731 case 221: $message = 'Service closing transmission channel';
732 $status = 5;
733 break;
734
735 case 421: $message = 'Service not available, closing chanel';
736 $status = 0;
737 break;
738
739 case 235: return(5);
740 break;
741 case 250: $message = 'Requested mail action okay, completed';
742 $status = 5;
743 break;
744 case 251: $message = 'User not local; will forward';
745 $status = 5;
746 break;
747 case 334: return(5); break;
748 case 450: $message = 'Requested mail action not taken: mailbox unavailable';
749 $status = 0;
750 break;
751 case 550: $message = 'Requested action not taken: mailbox unavailable';
752 $status = 0;
753 break;
754 case 451: $message = 'Requested action aborted: error in processing';
755 $status = 0;
756 break;
757 case 551: $message = 'User not local; please try forwarding';
758 $status = 0;
759 break;
760 case 452: $message = 'Requested action not taken: insufficient system storage';
761 $status = 0;
762 break;
763 case 552: $message = 'Requested mail action aborted: exceeding storage allocation';
764 $status = 0;
765 break;
766 case 553: $message = 'Requested action not taken: mailbox name not allowed';
767 $status = 0;
768 break;
769 case 354: $message = 'Start mail input; end with .';
770 $status = 5;
771 break;
772 case 554: $message = 'Transaction failed';
773 $status = 0;
774 break;
775 default: $message = 'Unknown response: '. nl2br(htmlspecialchars($lines));
776 $status = 0;
777 $error_num = '001';
778 break;
779 }
780
781 if ($status == 0) {
782 include_once('../functions/page_header.php');
783 if ($compose_new_win == '1') {
784 compose_Header($color, 'None');
785 }
786 else {
787 displayPageHeader($color, 'None');
788 }
789 include_once('../functions/display_messages.php');
790 $lines = nl2br(htmlspecialchars($lines));
791 $msg = $message . "<br>\nServer replied: $lines";
792 plain_error_message($msg, $color);
793 }
794 if (! $verbose) return $status;
795 return $err_num;
796 }
797
798 /* create new reference header per rfc2822 */
799
800 function calculate_references($refs, $inreplyto, $old_reply_to) {
801
802 $refer = "";
803 for ($i=1;$i<count($refs[0]);$i++) {
804 if (!empty($refs[0][$i])) {
805 if (preg_match("/^References:(.+)$/UA", $refs[0][$i], $regs)) {
806 $refer = trim($regs[1]);
807 }
808 else {
809 $refer .= ' ' . trim($refs[0][$i]);
810 }
811
812 }
813 }
814 $refer_a = explode(' ', $refer);
815 $refer = '';
816 foreach ($refer_a as $ref) {
817 $ref = trim($ref);
818 if ($ref{0} == '<' && $ref{(strlen($ref)-1)} == '>') {
819 $refer .= $ref . ' ';
820 }
821 }
822 $refer = trim($refer);
823 if (strlen($refer) > 2) {
824 $refer .= ' ' . $inreplyto;
825 }
826 else {
827 if (!empty($old_reply_to)) {
828 $refer .= $old_reply_to . ' ' . $inreplyto;
829 }
830 else {
831 $refer .= $inreplyto;
832 }
833 }
834 trim($refer);
835 return $refer;
836 }
837
838 function sendMessage($t, $c, $b, $subject, $body, $reply_id, $MDN,
839 $prio = 3, $session) {
840 global $useSendmail, $msg_id, $is_reply, $mailbox, $onetimepad,
841 $data_dir, $username, $domain, $key, $version, $sent_folder,
842 $imapServerAddress, $imapPort, $default_use_priority, $more_headers,
843 $request_mdn, $request_dr, $uid_support;
844
845 $more_headers = Array();
846
847 do_hook('smtp_send');
848
849 $imap_stream = sqimap_login($username, $key, $imapServerAddress,
850 $imapPort, 1);
851
852 if (isset($reply_id) && $reply_id) {
853 sqimap_mailbox_select ($imap_stream, $mailbox);
854 sqimap_messages_flag ($imap_stream, $reply_id, $reply_id, 'Answered', false);
855
856 /* Insert In-Reply-To and References headers if the
857 * message-id of the message we reply to is set (longer than "<>")
858 * The References header should really be the old Referenced header
859 * with the message ID appended, and now it is (jmunro)
860 */
861 $sid = sqimap_session_id($uid_support);
862 $query = "$sid FETCH $reply_id (BODY.PEEK[HEADER.FIELDS (Message-Id In-Reply-To)])\r\n";
863 fputs ($imap_stream, $query);
864 $read = sqimap_read_data($imap_stream, $sid, true, $response, $message);
865 $message_id = '';
866 $in_reply_to = '';
867
868 foreach ($read as $r) {
869 if (preg_match("/^message-id:(.*)/iA", $r, $regs)) {
870 $message_id = trim($regs[1]);
871 }
872 if (preg_match("/^in-reply-to:(.*)/iA", $r, $regs)) {
873 $in_reply_to = trim($regs[1]);
874 }
875 }
876
877 if(strlen($message_id) > 2) {
878 $refs = get_reference_header ($imap_stream, $reply_id);
879 $inreplyto = $message_id;
880 $old_reply_to = $in_reply_to;
881 $refer = calculate_references ($refs, $inreplyto, $old_reply_to);
882 $more_headers['In-Reply-To'] = $inreplyto;
883 $more_headers['References'] = $refer;
884 }
885
886 }
887 if ($default_use_priority) {
888 $more_headers = array_merge($more_headers, createPriorityHeaders($prio));
889 }
890
891 $requestRecipt = 0;
892 if (isset($request_dr)) {
893 $requestRecipt += 1;
894 }
895 if (isset($request_mdn)) {
896 $requestRecipt += 2;
897 }
898 if ( $requestRecipt > 0) {
899 $more_headers = array_merge($more_headers, createReceiptHeaders($requestRecipt));
900 }
901
902 /* this is to catch all plain \n instances and
903 * replace them with \r\n. All newlines were converted
904 * into just \n inside the compose.php file.
905 * But only if delimiter is, in fact, \r\n.
906 */
907
908 if ($MDN) {
909 $more_headers["Content-Type"] = "multipart/report; ".
910 "report-type=disposition-notification;";
911 }
912
913 if ($useSendmail) {
914 /* In order to remove the problem of users not able to create
915 * messages with "." on a blank line, RFC821 has made provision
916 * in section 4.5.2 (Transparency).
917 */
918 $body_sendmail = $body;
919 if (($body_sendmail{0} == '.')) {
920 $body_sendmail = '.' . $body_sendmail;
921 }
922 $body_sendmail = str_replace("\n.","\n..",$body_sendmail);
923
924 $length = sendSendmail($t, $c, $b, $subject, $body_sendmail, $more_headers,
925 $session);
926 $body = ereg_replace("\n", "\r\n", $body);
927 } else {
928 $body = ereg_replace("\n", "\r\n", $body);
929 /* In order to remove the problem of users not able to create
930 * messages with "." on a blank line, RFC821 has made provision
931 * in section 4.5.2 (Transparency).
932 */
933 $body_smtp = $body;
934 if (($body_smtp{0} == '.')) {
935 $body_smtp = '.' . $body_smtp;
936 }
937 $body_smtp = str_replace("\n.","\n..",$body_smtp);
938
939
940 $length = sendSMTP($t, $c, $b, $subject, $body_smtp, $more_headers,
941 $session);
942 }
943 if (sqimap_mailbox_exists ($imap_stream, $sent_folder)) {
944 $headerlength = write822Header (false, $t, $c, $b, $subject, $more_headers, $session, "\r\n");
945 $bodylength = writeBody(false, $body, $session, "\r\n");
946 $length = $headerlength + $bodylength;
947
948 sqimap_append ($imap_stream, $sent_folder, $length);
949 write822Header ($imap_stream, $t, $c, $b, $subject, $body, $more_headers,
950 $session);
951 writeBody ($imap_stream, $body, $session);
952 sqimap_append_done ($imap_stream);
953 }
954 sqimap_logout($imap_stream);
955 /* Delete the files uploaded for attaching (if any).
956 * only if $length != 0 (if there was no error)
957 */
958 if ($length) {
959 ClearAttachments($session);
960 }
961
962 return $length;
963 }
964
965 function createPriorityHeaders($prio) {
966 $prio_headers = Array();
967 $prio_headers['X-Priority'] = $prio;
968
969 switch($prio) {
970 case 1: $prio_headers['Importance'] = 'High';
971 $prio_headers['X-MSMail-Priority'] = 'High';
972 break;
973
974 case 3: $prio_headers['Importance'] = 'Normal';
975 $prio_headers['X-MSMail-Priority'] = 'Normal';
976 break;
977
978 case 5:
979 $prio_headers['Importance'] = 'Low';
980 $prio_headers['X-MSMail-Priority'] = 'Low';
981 break;
982 }
983 return $prio_headers;
984 }
985
986 function createReceiptHeaders($receipt) {
987
988 GLOBAL $data_dir, $username, $identity, $popuser, $domain;
989
990 $receipt_headers = Array();
991 if (isset($identity) && $identity != 'default') {
992 $from = getPref($data_dir, $username, 'full_name' . $identity);
993 $from_addr = getPref($data_dir, $username, 'email_address' . $identity);
994 } else {
995 $from = getPref($data_dir, $username, 'full_name');
996 $from_addr = getPref($data_dir, $username, 'email_address');
997 }
998 if ($from_addr == '') {
999 $from_addr = $popuser.'@'.$domain;
1000 }
1001
1002 if ($from == '') {
1003 $from = "<$from_addr>";
1004 }
1005 else {
1006 $from = '"' . encodeHeader($from) . "\" <$from_addr>";
1007 }
1008
1009 /* On Delivery */
1010 if ( $receipt == 1
1011 || $receipt == 3 ) {
1012 $receipt_headers["Return-Receipt-To"] = $from;
1013 }
1014 /* On Read */
1015 if ($receipt == 2
1016 || $receipt == 3 ) {
1017 /* Pegasus Mail */
1018 $receipt_headers["X-Confirm-Reading-To"] = $from;
1019 /* RFC 2298 */
1020 $receipt_headers["Disposition-Notification-To"] = $from;
1021 }
1022 return $receipt_headers;
1023 }
1024
1025 /* Figure out what the 'From:' address is
1026 */
1027
1028 function getFrom() {
1029 global $username, $popuser, $domain, $data_dir, $identity;
1030 if (isset($identity) && $identity != 'default') {
1031 $from_addr = getPref($data_dir, $username,
1032 'email_address' . $identity);
1033 }
1034 else {
1035 $from_addr = getPref($data_dir, $username, 'email_address');
1036 }
1037
1038 if (!$from_addr) {
1039 $from_addr = "$popuser@$domain";
1040 }
1041 return $from_addr;
1042 }
1043
1044
1045 ?>