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