smtp.php 18 KB

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