smtp.php 19 KB

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