smtp.php 20 KB

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