smtp.php 18 KB

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