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