smtp.php 19 KB

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