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