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