smtp.php 21 KB

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