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