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. if (isset($info['type']))
  69. $filetype = $info['type'];
  70. else
  71. $filetype = 'application/octet-stream';
  72. $header = '--'.mimeBoundary()."\r\n";
  73. $header .= "Content-Type: $filetype; name=\"" .
  74. $info['remotefilename'] . "\"\r\n";
  75. $header .= "Content-Disposition: attachment; filename=\"" .
  76. $info['remotefilename'] . "\"\r\n";
  77. // Use 'rb' for NT systems -- read binary
  78. // Unix doesn't care -- everything's binary! :-)
  79. $file = fopen ($attachment_dir . $info['localfilename'], 'rb');
  80. if (substr($filetype, 0, 5) == 'text/' ||
  81. $filetype == 'message/rfc822') {
  82. $header .= "\r\n";
  83. fputs ($fp, $header);
  84. $length += strlen($header);
  85. while ($tmp = fgets($file, 4096)) {
  86. $tmp = str_replace("\r\n", "\n", $tmp);
  87. $tmp = str_replace("\r", "\n", $tmp);
  88. $tmp = str_replace("\n", "\r\n", $tmp);
  89. if (feof($fp) && substr($tmp, -2) != "\r\n")
  90. $tmp .= "\r\n";
  91. fputs($fp, $tmp);
  92. $length += strlen($tmp);
  93. }
  94. } else {
  95. $header .= "Content-Transfer-Encoding: base64\r\n\r\n";
  96. fputs ($fp, $header);
  97. $length += strlen($header);
  98. while ($tmp = fread($file, 570)) {
  99. $encoded = chunk_split(base64_encode($tmp));
  100. $length += strlen($encoded);
  101. fputs ($fp, $encoded);
  102. }
  103. }
  104. fclose ($file);
  105. }
  106. }
  107. return $length;
  108. }
  109. // Delete files that are uploaded for attaching
  110. function deleteAttachments() {
  111. global $attachments, $attachment_dir;
  112. if (isMultipart()) {
  113. reset($attachments);
  114. while (list($localname, $remotename) = each($attachments)) {
  115. if (!ereg ("\\/", $localname)) {
  116. unlink ($attachment_dir.$localname);
  117. unlink ($attachment_dir.$localname.'.info');
  118. }
  119. }
  120. }
  121. }
  122. // Return a nice MIME-boundary
  123. function mimeBoundary () {
  124. static $mimeBoundaryString;
  125. if ($mimeBoundaryString == "") {
  126. $mimeBoundaryString = "----=_" .
  127. GenerateRandomString(60, '\'()+,-./:=?_', 7);
  128. }
  129. return $mimeBoundaryString;
  130. }
  131. /* Time offset for correct timezone */
  132. function timezone () {
  133. global $invert_time;
  134. $diff_second = date('Z');
  135. if ($invert_time)
  136. $diff_second = - $diff_second;
  137. if ($diff_second > 0)
  138. $sign = '+';
  139. else
  140. $sign = '-';
  141. $diff_second = abs($diff_second);
  142. $diff_hour = floor ($diff_second / 3600);
  143. $diff_minute = floor (($diff_second-3600*$diff_hour) / 60);
  144. $zonename = '('.strftime('%Z').')';
  145. $result = sprintf ("%s%02d%02d %s", $sign, $diff_hour, $diff_minute, $zonename);
  146. return ($result);
  147. }
  148. /* Print all the needed RFC822 headers */
  149. function write822Header ($fp, $t, $c, $b, $subject, $more_headers) {
  150. global $REMOTE_ADDR, $SERVER_NAME, $REMOTE_PORT;
  151. global $data_dir, $username, $popuser, $domain, $version, $useSendmail;
  152. global $default_charset, $HTTP_VIA, $HTTP_X_FORWARDED_FOR;
  153. global $REMOTE_HOST, $identity;
  154. // Storing the header to make sure the header is the same
  155. // everytime the header is printed.
  156. static $header, $headerlength;
  157. if ($header == '') {
  158. $to = expandAddrs(parseAddrs($t));
  159. $cc = expandAddrs(parseAddrs($c));
  160. $bcc = expandAddrs(parseAddrs($b));
  161. if (isset($identity) && $identity != 'default')
  162. {
  163. $reply_to = getPref($data_dir, $username, 'reply_to' . $identity);
  164. $from = getPref($data_dir, $username, 'full_name' . $identity);
  165. $from_addr = getPref($data_dir, $username, 'email_address' . $identity);
  166. }
  167. else
  168. {
  169. $reply_to = getPref($data_dir, $username, 'reply_to');
  170. $from = getPref($data_dir, $username, 'full_name');
  171. $from_addr = getPref($data_dir, $username, 'email_address');
  172. }
  173. if ($from_addr == '')
  174. $from_addr = $popuser.'@'.$domain;
  175. $to_list = getLineOfAddrs($to);
  176. $cc_list = getLineOfAddrs($cc);
  177. $bcc_list = getLineOfAddrs($bcc);
  178. /* Encoding 8-bit characters and making from line */
  179. $subject = encodeHeader($subject);
  180. if ($from == '')
  181. $from = "<$from_addr>";
  182. else
  183. $from = '"' . encodeHeader($from) . "\" <$from_addr>";
  184. /* This creates an RFC 822 date */
  185. $date = date("D, j M Y H:i:s ", mktime()) . timezone();
  186. /* Create a message-id */
  187. $message_id = '<' . $REMOTE_PORT . '.' . $REMOTE_ADDR . '.';
  188. $message_id .= time() . '.squirrel@' . $SERVER_NAME .'>';
  189. /* Make an RFC822 Received: line */
  190. if (isset($REMOTE_HOST))
  191. $received_from = "$REMOTE_HOST ([$REMOTE_ADDR])";
  192. else
  193. $received_from = $REMOTE_ADDR;
  194. if (isset($HTTP_VIA) || isset ($HTTP_X_FORWARDED_FOR)) {
  195. if ($HTTP_X_FORWARDED_FOR == '')
  196. $HTTP_X_FORWARDED_FOR = 'unknown';
  197. $received_from .= " (proxying for $HTTP_X_FORWARDED_FOR)";
  198. }
  199. $header = "Received: from $received_from\r\n";
  200. $header .= " (SquirrelMail authenticated user $username)\r\n";
  201. $header .= " by $SERVER_NAME with HTTP;\r\n";
  202. $header .= " $date\r\n";
  203. /* Insert the rest of the header fields */
  204. $header .= "Message-ID: $message_id\r\n";
  205. $header .= "Date: $date\r\n";
  206. $header .= "Subject: $subject\r\n";
  207. $header .= "From: $from\r\n";
  208. $header .= "To: $to_list\r\n"; // Who it's TO
  209. /* Insert headers from the $more_headers array */
  210. if(is_array($more_headers)) {
  211. reset($more_headers);
  212. while(list($h_name, $h_val) = each($more_headers)) {
  213. $header .= sprintf("%s: %s\r\n", $h_name, $h_val);
  214. }
  215. }
  216. if ($cc_list) {
  217. $header .= "Cc: $cc_list\r\n"; // Who the CCs are
  218. }
  219. if ($reply_to != '')
  220. $header .= "Reply-To: $reply_to\r\n";
  221. if ($useSendmail) {
  222. if ($bcc_list) {
  223. // BCCs is removed from header by sendmail
  224. $header .= "Bcc: $bcc_list\r\n";
  225. }
  226. }
  227. $header .= "X-Mailer: SquirrelMail (version $version)\r\n"; // Identify SquirrelMail
  228. // Do the MIME-stuff
  229. $header .= "MIME-Version: 1.0\r\n";
  230. if (isMultipart()) {
  231. $header .= 'Content-Type: multipart/mixed; boundary="';
  232. $header .= mimeBoundary();
  233. $header .= "\"\r\n";
  234. } else {
  235. if ($default_charset != '')
  236. $header .= "Content-Type: text/plain; charset=$default_charset\r\n";
  237. else
  238. $header .= "Content-Type: text/plain;\r\n";
  239. $header .= "Content-Transfer-Encoding: 8bit\r\n";
  240. }
  241. $header .= "\r\n"; // One blank line to separate header and body
  242. $headerlength = strlen($header);
  243. }
  244. // Write the header
  245. fputs ($fp, $header);
  246. return $headerlength;
  247. }
  248. // Send the body
  249. function writeBody ($fp, $passedBody) {
  250. global $default_charset;
  251. $attachmentlength = 0;
  252. if (isMultipart()) {
  253. $body = '--'.mimeBoundary()."\r\n";
  254. if ($default_charset != "")
  255. $body .= "Content-Type: text/plain; charset=$default_charset\r\n";
  256. else
  257. $body .= "Content-Type: text/plain\r\n";
  258. $body .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
  259. $body .= $passedBody . "\r\n\r\n";
  260. fputs ($fp, $body);
  261. $attachmentlength = attachFiles($fp);
  262. if (!isset($postbody)) $postbody = "";
  263. $postbody .= "\r\n--".mimeBoundary()."--\r\n\r\n";
  264. fputs ($fp, $postbody);
  265. } else {
  266. $body = $passedBody . "\r\n";
  267. fputs ($fp, $body);
  268. $postbody = "\r\n";
  269. fputs ($fp, $postbody);
  270. }
  271. return (strlen($body) + strlen($postbody) + $attachmentlength);
  272. }
  273. // Send mail using the sendmail command
  274. function sendSendmail($t, $c, $b, $subject, $body, $more_headers) {
  275. global $sendmail_path, $popuser, $username, $domain;
  276. // Build envelope sender address. Make sure it doesn't contain
  277. // spaces or other "weird" chars that would allow a user to
  278. // exploit the shell/pipe it is used in.
  279. $envelopefrom = "$popuser@$domain";
  280. $envelopefrom = ereg_replace("[[:blank:]]",'', $envelopefrom);
  281. $envelopefrom = ereg_replace("[[:space:]]",'', $envelopefrom);
  282. $envelopefrom = ereg_replace("[[:cntrl:]]",'', $envelopefrom);
  283. // open pipe to sendmail
  284. $fp = popen (escapeshellcmd("$sendmail_path -t -f$envelopefrom"), 'w');
  285. $headerlength = write822Header ($fp, $t, $c, $b, $subject, $more_headers);
  286. $bodylength = writeBody($fp, $body);
  287. pclose($fp);
  288. return ($headerlength + $bodylength);
  289. }
  290. function smtpReadData($smtpConnection) {
  291. $read = fgets($smtpConnection, 1024);
  292. $counter = 0;
  293. while ($read) {
  294. echo $read . '<BR>';
  295. $data[$counter] = $read;
  296. $read = fgets($smtpConnection, 1024);
  297. $counter++;
  298. }
  299. }
  300. function sendSMTP($t, $c, $b, $subject, $body, $more_headers) {
  301. global $username, $popuser, $domain, $version, $smtpServerAddress,
  302. $smtpPort, $data_dir, $color, $use_authenticated_smtp, $identity,
  303. $key, $onetimepad;
  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. // Read new lines on a multiline response
  387. $lines = $line;
  388. while(ereg("^[0-9]+-", $line)) {
  389. $line = fgets($smtpConnection, 1024);
  390. $lines .= $line;
  391. }
  392. // Status: 0 = fatal
  393. // 5 = ok
  394. $err_num = substr($line, 0, strpos($line, " "));
  395. switch ($err_num) {
  396. case 500: $message = 'Syntax error; command not recognized';
  397. $status = 0;
  398. break;
  399. case 501: $message = 'Syntax error in parameters or arguments';
  400. $status = 0;
  401. break;
  402. case 502: $message = 'Command not implemented';
  403. $status = 0;
  404. break;
  405. case 503: $message = 'Bad sequence of commands';
  406. $status = 0;
  407. break;
  408. case 504: $message = 'Command parameter not implemented';
  409. $status = 0;
  410. break;
  411. case 211: $message = 'System status, or system help reply';
  412. $status = 5;
  413. break;
  414. case 214: $message = 'Help message';
  415. $status = 5;
  416. break;
  417. case 220: $message = 'Service ready';
  418. $status = 5;
  419. break;
  420. case 221: $message = 'Service closing transmission channel';
  421. $status = 5;
  422. break;
  423. case 421: $message = 'Service not available, closing chanel';
  424. $status = 0;
  425. break;
  426. case 235: return(5); break;
  427. case 250: $message = 'Requested mail action okay, completed';
  428. $status = 5;
  429. break;
  430. case 251: $message = 'User not local; will forward';
  431. $status = 5;
  432. break;
  433. case 334: return(5); break;
  434. case 450: $message = 'Requested mail action not taken: mailbox unavailable';
  435. $status = 0;
  436. break;
  437. case 550: $message = 'Requested action not taken: mailbox unavailable';
  438. $status = 0;
  439. break;
  440. case 451: $message = 'Requested action aborted: error in processing';
  441. $status = 0;
  442. break;
  443. case 551: $message = 'User not local; please try forwarding';
  444. $status = 0;
  445. break;
  446. case 452: $message = 'Requested action not taken: insufficient system storage';
  447. $status = 0;
  448. break;
  449. case 552: $message = 'Requested mail action aborted: exceeding storage allocation';
  450. $status = 0;
  451. break;
  452. case 553: $message = 'Requested action not taken: mailbox name not allowed';
  453. $status = 0;
  454. break;
  455. case 354: $message = 'Start mail input; end with .';
  456. $status = 5;
  457. break;
  458. case 554: $message = 'Transaction failed';
  459. $status = 0;
  460. break;
  461. default: $message = 'Unknown response: '. nl2br(htmlspecialchars($lines));
  462. $status = 0;
  463. $error_num = '001';
  464. break;
  465. }
  466. if ($status == 0) {
  467. include '../functions/page_header.php';
  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. All newlines were converted
  502. // into just \n inside the compose.php file.
  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. ?>