smtp.php 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051
  1. <?php
  2. /**
  3. * smtp.php
  4. *
  5. * Copyright (c) 1999-2002 The SquirrelMail Project Team
  6. * Licensed under the GNU GPL. For full terms see the file COPYING.
  7. *
  8. * This contains all the functions needed to send messages through
  9. * an smtp server or sendmail.
  10. *
  11. * $Id$
  12. */
  13. require_once(SM_PATH . 'functions/addressbook.php');
  14. require_once(SM_PATH . 'functions/plugin.php');
  15. require_once(SM_PATH . 'functions/prefs.php');
  16. global $username, $popuser, $domain;
  17. /* This should most probably go to some initialization... */
  18. if (ereg("^([^@%/]+)[@%/](.+)$", $username, $usernamedata)) {
  19. $popuser = $usernamedata[1];
  20. $domain = $usernamedata[2];
  21. unset($usernamedata);
  22. } else {
  23. $popuser = $username;
  24. }
  25. /* We need domain for smtp */
  26. if (!$domain) {
  27. $domain = getenv('HOSTNAME');
  28. }
  29. /* Returns true only if this message is multipart */
  30. function isMultipart ($session) {
  31. global $attachments;
  32. foreach ($attachments as $info) {
  33. if ($info['session'] == $session) {
  34. return true;
  35. }
  36. }
  37. return false;
  38. }
  39. /* looks up aliases in the addressbook and expands them to
  40. * the full address.
  41. *
  42. * Adds @$domain if it wasn't in the address book and if it
  43. * doesn't have an @ symbol in it
  44. */
  45. function expandAddrs ($array) {
  46. global $domain;
  47. /* don't show errors -- kinda critical that we don't see
  48. * them here since the redirect won't work if we do show them
  49. */
  50. $abook = addressbook_init(false, true);
  51. for ($i=0; $i < count($array); $i++) {
  52. $result = $abook->lookup($array[$i]);
  53. $ret = "";
  54. if (isset($result['email'])) {
  55. if (isset($result['name'])) {
  56. $ret = '"'.$result['name'].'" ';
  57. }
  58. $ret .= '<'.$result['email'].'>';
  59. $array[$i] = $ret;
  60. }
  61. else
  62. {
  63. if (strpos($array[$i], '@') === false) {
  64. $array[$i] .= '@' . $domain;
  65. }
  66. $array[$i] = '<' . $array[$i] . '>';
  67. }
  68. }
  69. return $array;
  70. }
  71. /* looks up aliases in the addressbook and expands them to
  72. * the RFC 821 valid RCPT address. ie <user@example.com>
  73. * Adds @$domain if it wasn't in the address book and if it
  74. * doesn't have an @ symbol in it
  75. */
  76. function expandRcptAddrs ($array) {
  77. global $domain;
  78. /* don't show errors -- kinda critical that we don't see
  79. * them here since the redirect won't work if we do show them
  80. */
  81. $abook = addressbook_init(false, true);
  82. for ($i=0; $i < count($array); $i++) {
  83. $result = $abook->lookup($array[$i]);
  84. $ret = "";
  85. if (isset($result['email'])) {
  86. $ret = '<'.$result['email'].'>';
  87. $array[$i] = $ret;
  88. }
  89. else {
  90. if (strpos($array[$i], '@') === false) {
  91. $array[$i] .= '@' . $domain;
  92. }
  93. $array[$i] = '<' . $array[$i] . '>';
  94. }
  95. }
  96. return $array;
  97. }
  98. /* Attach the files that are due to be attached
  99. */
  100. function attachFiles ($fp, $session, $rn="\r\n", $checkdot = false) {
  101. global $attachments, $attachment_dir, $username, $languages, $squirrelmail_language;
  102. $length = 0;
  103. $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
  104. if (isMultipart($session)) {
  105. foreach ($attachments as $info) {
  106. if ($info['session'] == $session) {
  107. if (isset($info['type'])) {
  108. $filetype = $info['type'];
  109. }
  110. else {
  111. $filetype = 'application/octet-stream';
  112. }
  113. $header = '--' . mimeBoundary() . "$rn";
  114. if ( isset($info['remotefilename'])
  115. && $info['remotefilename'] != '') {
  116. $remotefilename = $info['remotefilename'];
  117. if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
  118. function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
  119. $remotefilename =
  120. $languages[$squirrelmail_language]['XTRA_CODE']('encode', $remotefilename);
  121. }
  122. $header .= "Content-Type: $filetype; name=\"" .
  123. encodeHeader($remotefilename) . "\"$rn";
  124. $header .= "Content-Disposition: attachment; filename=\""
  125. . encodeHeader($remotefilename) . "\"$rn";
  126. } else {
  127. $header .= "Content-Type: $filetype$rn";
  128. }
  129. /* Use 'rb' for NT systems -- read binary
  130. * Unix doesn't care -- everything's binary! :-)
  131. */
  132. $filename = $hashed_attachment_dir . '/'
  133. . $info['localfilename'];
  134. $file = fopen ($filename, 'rb');
  135. if (substr($filetype, 0, 5) == 'text/' ||
  136. substr($filetype, 0, 8) == 'message/' ) {
  137. $header .= $rn;
  138. if ($fp) {
  139. fputs ($fp, $header);
  140. }
  141. $length += strlen($header);
  142. if ($checkdot) {
  143. $checkdot_begin=true;
  144. } else {
  145. $checkdot_begin=false;
  146. }
  147. while ($tmp = fgets($file, 4096)) {
  148. $tmp = str_replace("\r\n", "\n", $tmp);
  149. $tmp = str_replace("\r", "\n", $tmp);
  150. if ($rn == "\r\n"){
  151. $tmp = str_replace("\n", "\r\n", $tmp);
  152. }
  153. if ($tmp{0} == '.' && $checkdot_begin) {
  154. $tmp = '.' . $tmp;
  155. }
  156. if ($checkdot) {
  157. $tmp = str_replace("\n.","\n..",$tmp);
  158. }
  159. $tmp_length = strlen($tmp);
  160. if ($tmp_length && $tmp{$tmp_length-1} == "\n" && $checkdot) {
  161. $checkdot_begin = true;
  162. } else {
  163. $checkdot_begin = false;
  164. }
  165. if ($fp) {
  166. fputs($fp, $tmp);
  167. }
  168. $length += $tmp_length;
  169. }
  170. if (substr($tmp, $tmp_length - strlen($rn), strlen($rn)) != $rn) {
  171. if ($fp) {
  172. fputs($fp, $rn);
  173. }
  174. $length += strlen($rn);
  175. }
  176. } else {
  177. $header .= "Content-Transfer-Encoding: base64"
  178. . "$rn" . "$rn";
  179. if ($fp) fputs ($fp, $header);
  180. $length += strlen($header);
  181. while ($tmp = fread($file, 570)) {
  182. $encoded = chunk_split(base64_encode($tmp));
  183. $length += strlen($encoded);
  184. if ($fp) fputs ($fp, $encoded);
  185. }
  186. }
  187. fclose ($file);
  188. }
  189. }
  190. }
  191. return $length;
  192. }
  193. /* Delete files that are uploaded for attaching
  194. */
  195. function deleteAttachments($session) {
  196. global $username, $attachments, $attachment_dir, $data_dir;
  197. $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
  198. $rem_attachments = array();
  199. foreach ($attachments as $info) {
  200. if ($info['session'] == $session) {
  201. $attached_file = "$hashed_attachment_dir/$info[localfilename]";
  202. if (file_exists($attached_file)) {
  203. unlink($attached_file);
  204. }
  205. } else {
  206. $rem_attachments[] = $info;
  207. }
  208. }
  209. $attachments = $rem_attachments;
  210. setPref($data_dir, $username, 'attachments', serialize($attachments));
  211. }
  212. /* Return a nice MIME-boundary
  213. */
  214. function mimeBoundary () {
  215. static $mimeBoundaryString;
  216. if ( !isset( $mimeBoundaryString ) ||
  217. $mimeBoundaryString == '') {
  218. $mimeBoundaryString = '----=_' . date( 'YmdHis' ) . '_' .
  219. mt_rand( 10000, 99999 );
  220. }
  221. return $mimeBoundaryString;
  222. }
  223. /* Time offset for correct timezone */
  224. function timezone () {
  225. global $invert_time;
  226. $diff_second = date('Z');
  227. if ($invert_time) {
  228. $diff_second = - $diff_second;
  229. }
  230. if ($diff_second > 0) {
  231. $sign = '+';
  232. }
  233. else {
  234. $sign = '-';
  235. }
  236. $diff_second = abs($diff_second);
  237. $diff_hour = floor ($diff_second / 3600);
  238. $diff_minute = floor (($diff_second-3600*$diff_hour) / 60);
  239. $zonename = '('.strftime('%Z').')';
  240. $result = sprintf ("%s%02d%02d %s", $sign, $diff_hour, $diff_minute,
  241. $zonename);
  242. return ($result);
  243. }
  244. /* Print all the needed RFC822 headers */
  245. function write822Header ($fp, $t, $c, $b, $subject, $body, $more_headers, $session, $rn="\r\n") {
  246. global $data_dir, $username, $popuser, $domain, $version, $useSendmail,
  247. $default_charset, $identity, $_SERVER;
  248. /* Storing the header to make sure the header is the same
  249. * everytime the header is printed.
  250. */
  251. /* get those globals */
  252. $REMOTE_ADDR = $_SERVER['REMOTE_ADDR'];
  253. $SERVER_NAME = $_SERVER['SERVER_NAME'];
  254. $REMOTE_PORT = $_SERVER['REMOTE_PORT'];
  255. if(isset($_SERVER['REMOTE_HOST'])) {
  256. $REMOTE_HOST = $_SERVER['REMOTE_HOST'];
  257. }
  258. if(isset($_SERVER['HTTP_VIA'])) {
  259. $HTTP_VIA = $_SERVER['HTTP_VIA'];
  260. }
  261. if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  262. $HTTP_X_FORWARDED_FOR = $_SERVER['HTTP_X_FORWARDED_FOR'];
  263. }
  264. static $header, $headerlength, $headerrn;
  265. if ($header == '') {
  266. $headerrn = $rn;
  267. $to = expandAddrs(parseAddrs($t));
  268. $cc = expandAddrs(parseAddrs($c));
  269. $bcc = expandAddrs(parseAddrs($b));
  270. if (isset($identity) && $identity != 'default') {
  271. $reply_to = getPref($data_dir, $username, 'reply_to' . $identity);
  272. $from = getPref($data_dir, $username, 'full_name' . $identity);
  273. $from_addr = getFrom();
  274. } else {
  275. $reply_to = getPref($data_dir, $username, 'reply_to');
  276. $from = getPref($data_dir, $username, 'full_name');
  277. $from_addr = getFrom();
  278. }
  279. $to_list = getLineOfAddrs($to);
  280. $cc_list = getLineOfAddrs($cc);
  281. $bcc_list = getLineOfAddrs($bcc);
  282. /* Encoding 8-bit characters and making from line */
  283. $subject = encodeHeader($subject);
  284. if ($from == '') {
  285. $from = "<$from_addr>";
  286. }
  287. else {
  288. $from = '"' . encodeHeader($from) . "\" <$from_addr>";
  289. }
  290. /* This creates an RFC 822 date */
  291. $date = date("D, j M Y H:i:s ", mktime()) . timezone();
  292. /* Create a message-id */
  293. $message_id = '<' . $REMOTE_PORT . '.' . $REMOTE_ADDR . '.';
  294. $message_id .= time() . '.squirrel@' . $SERVER_NAME .'>';
  295. /* Make an RFC822 Received: line */
  296. if (isset($REMOTE_HOST)) {
  297. $received_from = "$REMOTE_HOST ([$REMOTE_ADDR])";
  298. }
  299. else {
  300. $received_from = $REMOTE_ADDR;
  301. }
  302. if (isset($HTTP_VIA) || isset ($HTTP_X_FORWARDED_FOR)) {
  303. if ($HTTP_X_FORWARDED_FOR == '') {
  304. $HTTP_X_FORWARDED_FOR = 'unknown';
  305. }
  306. $received_from .= " (proxying for $HTTP_X_FORWARDED_FOR)";
  307. }
  308. $header = "Received: from $received_from" . $rn;
  309. $header .= " (SquirrelMail authenticated user $username)" . $rn;
  310. $header .= " by $SERVER_NAME with HTTP;" . $rn;
  311. $header .= " $date" . $rn;
  312. /* Insert the rest of the header fields */
  313. $header .= "Message-ID: $message_id" . $rn;
  314. $header .= "Date: $date" . $rn;
  315. $header .= "Subject: $subject" . $rn;
  316. $header .= "From: $from" . $rn;
  317. $header .= "To: $to_list" . $rn; // Who it's TO
  318. if (isset($more_headers["Content-Type"])) {
  319. $contentType = $more_headers["Content-Type"];
  320. unset($more_headers["Content-Type"]);
  321. }
  322. else {
  323. if (isMultipart($session)) {
  324. $contentType = "multipart/mixed;";
  325. }
  326. else {
  327. if ($default_charset != '') {
  328. $contentType = 'text/plain; charset='.$default_charset;
  329. }
  330. else {
  331. $contentType = 'text/plain;';
  332. }
  333. }
  334. }
  335. /* Insert headers from the $more_headers array */
  336. if(is_array($more_headers)) {
  337. reset($more_headers);
  338. while(list($h_name, $h_val) = each($more_headers)) {
  339. if ($h_name == 'References') {
  340. $h_val = str_replace(' ', "$rn ", $h_val);
  341. }
  342. $header .= sprintf("%s: %s%s", $h_name, $h_val, $rn);
  343. }
  344. }
  345. if ($cc_list) {
  346. $header .= "Cc: $cc_list" . $rn; // Who the CCs are
  347. }
  348. if ($reply_to != '') {
  349. $header .= "Reply-To: $reply_to" . $rn;
  350. }
  351. if ($useSendmail) {
  352. if ($bcc_list) {
  353. // BCCs is removed from header by sendmail
  354. $header .= "Bcc: $bcc_list" . $rn;
  355. }
  356. }
  357. /* Identify SquirrelMail */
  358. $header .= "X-Mailer: SquirrelMail (version $version)" . $rn;
  359. /* Do the MIME-stuff */
  360. $header .= "MIME-Version: 1.0" . $rn;
  361. if (isMultipart($session)) {
  362. $header .= 'Content-Type: '.$contentType.' boundary="';
  363. $header .= mimeBoundary();
  364. $header .= "\"$rn";
  365. } else {
  366. if (strtolower($default_charset) == 'iso-2022-jp') {
  367. if (mb_detect_encoding($body) == 'ASCII') {
  368. $header .= 'Content-Type: text/plain; US-ASCII' . $rn;
  369. $header .= "Content-Transfer-Encoding: 8bit" . $rn;
  370. } else {
  371. $header .= 'Content-Type: '.$contentType . $rn;
  372. $header .= "Content-Transfer-Encoding: 7bit" . $rn;
  373. }
  374. } else {
  375. $header .= 'Content-Type: ' . $contentType . $rn;
  376. $header .= "Content-Transfer-Encoding: 8bit" . $rn;
  377. }
  378. }
  379. $header .= $rn; // One blank line to separate header and body
  380. $headerlength = strlen($header);
  381. }
  382. if ($headerrn != $rn) {
  383. $header = str_replace($headerrn, $rn, $header);
  384. $headerlength = strlen($header);
  385. $headerrn = $rn;
  386. }
  387. /* Write the header */
  388. if ($fp) fputs ($fp, $header);
  389. return $headerlength;
  390. }
  391. /* Send the body
  392. */
  393. function writeBody ($fp, $passedBody, $session, $rn="\r\n", $checkdot = false) {
  394. global $default_charset;
  395. $attachmentlength = 0;
  396. if (isMultipart($session)) {
  397. $body = '--'.mimeBoundary() . $rn;
  398. if ($default_charset != "") {
  399. $body .= "Content-Type: text/plain; charset=$default_charset".$rn;
  400. }
  401. else {
  402. $body .= "Content-Type: text/plain" . $rn;
  403. }
  404. if (strtolower($default_charset) == 'iso-2022-jp') {
  405. if (mb_detect_encoding($passedBody) == 'ASCII') {
  406. $body .= "Content-Transfer-Encoding: 8bit" . $rn . $rn .
  407. $passedBody . $rn . $rn;
  408. } else {
  409. $body .= "Content-Transfer-Encoding: 7bit\r\n\r\n" .
  410. mb_convert_encoding($passedBody, 'JIS') . "\r\n\r\n";
  411. }
  412. } else {
  413. $body .= "Content-Transfer-Encoding: 8bit" . $rn . $rn .
  414. $passedBody . $rn . $rn;
  415. }
  416. if ($fp) {
  417. fputs ($fp, $body);
  418. }
  419. $attachmentlength = attachFiles($fp, $session, $rn, $checkdot);
  420. if (!isset($postbody)) {
  421. $postbody = "";
  422. }
  423. $postbody .= $rn . "--" . mimeBoundary() . "--" . $rn . $rn;
  424. if ($fp) fputs ($fp, $postbody);
  425. } else {
  426. if (strtolower($default_charset) == 'iso-2022-jp') {
  427. $body = mb_convert_encoding($passedBody, 'JIS') . $rn;
  428. } else {
  429. $body = $passedBody . $rn;
  430. }
  431. if ($fp) {
  432. fputs ($fp, $body);
  433. }
  434. $postbody = $rn;
  435. if ($fp) {
  436. fputs ($fp, $postbody);
  437. }
  438. }
  439. return (strlen($body) + strlen($postbody) + $attachmentlength);
  440. }
  441. /* Send mail using the sendmail command
  442. */
  443. function sendSendmail($t, $c, $b, $subject, $body, $more_headers, $session) {
  444. global $sendmail_path, $popuser, $username, $domain;
  445. /* Build envelope sender address. Make sure it doesn't contain
  446. * spaces or other "weird" chars that would allow a user to
  447. * exploit the shell/pipe it is used in.
  448. */
  449. $envelopefrom = getFrom();
  450. $envelopefrom = ereg_replace("[[:blank:]]",'', $envelopefrom);
  451. $envelopefrom = ereg_replace("[[:space:]]",'', $envelopefrom);
  452. $envelopefrom = ereg_replace("[[:cntrl:]]",'', $envelopefrom);
  453. /**
  454. * open pipe to sendmail or qmail-inject
  455. * (qmail-inject doesn't accept -t param)
  456. */
  457. if (strstr($sendmail_path, "qmail-inject")) {
  458. $fp = popen (escapeshellcmd("$sendmail_path -f$envelopefrom"), "w");
  459. } else {
  460. $fp = popen (escapeshellcmd("$sendmail_path -t -f$envelopefrom"), "w");
  461. }
  462. $headerlength = write822Header ($fp, $t, $c, $b, $subject, $body,
  463. $more_headers, $session, "\n");
  464. $bodylength = writeBody($fp, $body, $session, "\n", true);
  465. pclose($fp);
  466. return ($headerlength + $bodylength);
  467. }
  468. function smtpReadData($smtpConnection) {
  469. $read = fgets($smtpConnection, 1024);
  470. $counter = 0;
  471. while ($read) {
  472. echo $read . '<BR>';
  473. $data[$counter] = $read;
  474. $read = fgets($smtpConnection, 1024);
  475. $counter++;
  476. }
  477. }
  478. function sendSMTP($t, $c, $b, $subject, $body, $more_headers, $session) {
  479. global $username, $popuser, $domain, $version, $smtpServerAddress,
  480. $smtpPort, $data_dir, $color, $use_authenticated_smtp, $identity,
  481. $key, $onetimepad;
  482. $to = expandRcptAddrs(parseAddrs($t));
  483. $cc = expandRcptAddrs(parseAddrs($c));
  484. $bcc = expandRcptAddrs(parseAddrs($b));
  485. if (isset($identity) && $identity != 'default') {
  486. $from_addr = getPref($data_dir, $username,
  487. 'email_address' . $identity);
  488. }
  489. else {
  490. $from_addr = getPref($data_dir, $username, 'email_address');
  491. }
  492. if (!$from_addr) {
  493. $from_addr = "$popuser@$domain";
  494. }
  495. /* POP3 BEFORE SMTP CODE HERE */
  496. global $pop_before_smtp;
  497. if (isset($pop_before_smtp) && $pop_before_smtp === true) {
  498. if (!isset($pop_port)) {
  499. $pop_port = 110;
  500. }
  501. if (!isset($pop_server)) {
  502. $pop_server = $smtpServerAddress; /* usually the same host! */
  503. }
  504. $popConnection = fsockopen($pop_server, $pop_port, $err_no, $err_str);
  505. if (!$popConnection) {
  506. error_log("Error connecting to POP Server ($pop_server:$pop_port)"
  507. . " $err_no : $err_str");
  508. } else {
  509. $tmp = fgets($popConnection, 1024); /* banner */
  510. if (!eregi("^\+OK", $tmp, $regs)) {
  511. return(0);
  512. }
  513. fputs($popConnection, "USER $username\r\n");
  514. $tmp = fgets($popConnection, 1024);
  515. if (!eregi("^\+OK", $tmp, $regs)) {
  516. return(0);
  517. }
  518. fputs($popConnection, 'PASS ' . OneTimePadDecrypt($key, $onetimepad) . "\r\n");
  519. $tmp = fgets($popConnection, 1024);
  520. if (!eregi("^\+OK", $tmp, $regs)) {
  521. return(0);
  522. }
  523. fputs($popConnection, "QUIT\r\n"); /* log off */
  524. fclose($popConnection);
  525. }
  526. }
  527. $smtpConnection = fsockopen($smtpServerAddress, $smtpPort,
  528. $errorNumber, $errorString);
  529. if (!$smtpConnection) {
  530. echo 'Error connecting to SMTP Server.<br>';
  531. echo "$errorNumber : $errorString<br>";
  532. exit;
  533. }
  534. $tmp = fgets($smtpConnection, 1024);
  535. if (errorCheck($tmp, $smtpConnection)!=5) {
  536. return(0);
  537. }
  538. $to_list = getLineOfAddrs($to);
  539. $cc_list = getLineOfAddrs($cc);
  540. /* Lets introduce ourselves */
  541. if (! isset ($use_authenticated_smtp)
  542. || $use_authenticated_smtp == false) {
  543. fputs($smtpConnection, "HELO $domain\r\n");
  544. $tmp = fgets($smtpConnection, 1024);
  545. if (errorCheck($tmp, $smtpConnection)!=5) return(0);
  546. } else {
  547. fputs($smtpConnection, "EHLO $domain\r\n");
  548. $tmp = fgets($smtpConnection, 1024);
  549. if (errorCheck($tmp, $smtpConnection)!=5) return(0);
  550. fputs($smtpConnection, "AUTH LOGIN\r\n");
  551. $tmp = fgets($smtpConnection, 1024);
  552. if (errorCheck($tmp, $smtpConnection)!=5) {
  553. return(0);
  554. }
  555. fputs($smtpConnection, base64_encode ($username) . "\r\n");
  556. $tmp = fgets($smtpConnection, 1024);
  557. if (errorCheck($tmp, $smtpConnection)!=5) {
  558. return(0);
  559. }
  560. fputs($smtpConnection, base64_encode
  561. (OneTimePadDecrypt($key, $onetimepad)) . "\r\n");
  562. $tmp = fgets($smtpConnection, 1024);
  563. if (errorCheck($tmp, $smtpConnection)!=5) {
  564. return(0);
  565. }
  566. }
  567. /* Ok, who is sending the message? */
  568. fputs($smtpConnection, "MAIL FROM: <$from_addr>\r\n");
  569. $tmp = fgets($smtpConnection, 1024);
  570. if (errorCheck($tmp, $smtpConnection)!=5) {
  571. return(0);
  572. }
  573. /* send who the recipients are */
  574. for ($i = 0; $i < count($to); $i++) {
  575. fputs($smtpConnection, "RCPT TO: $to[$i]\r\n");
  576. $tmp = fgets($smtpConnection, 1024);
  577. if (errorCheck($tmp, $smtpConnection)!=5) {
  578. return(0);
  579. }
  580. }
  581. for ($i = 0; $i < count($cc); $i++) {
  582. fputs($smtpConnection, "RCPT TO: $cc[$i]\r\n");
  583. $tmp = fgets($smtpConnection, 1024);
  584. if (errorCheck($tmp, $smtpConnection)!=5) {
  585. return(0);
  586. }
  587. }
  588. for ($i = 0; $i < count($bcc); $i++) {
  589. fputs($smtpConnection, "RCPT TO: $bcc[$i]\r\n");
  590. $tmp = fgets($smtpConnection, 1024);
  591. if (errorCheck($tmp, $smtpConnection)!=5) {
  592. return(0);
  593. }
  594. }
  595. /* Lets start sending the actual message */
  596. fputs($smtpConnection, "DATA\r\n");
  597. $tmp = fgets($smtpConnection, 1024);
  598. if (errorCheck($tmp, $smtpConnection)!=5) {
  599. return(0);
  600. }
  601. /* Send the message */
  602. $headerlength = write822Header ($smtpConnection, $t, $c, $b,
  603. $subject, $body, $more_headers, $session);
  604. $bodylength = writeBody($smtpConnection, $body, $session,"\r\n", true);
  605. fputs($smtpConnection, ".\r\n"); /* end the DATA part */
  606. $tmp = fgets($smtpConnection, 1024);
  607. $num = errorCheck($tmp, $smtpConnection, true);
  608. if ($num != 250) {
  609. return(0);
  610. }
  611. fputs($smtpConnection, "QUIT\r\n"); /* log off */
  612. fclose($smtpConnection);
  613. return ($headerlength + $bodylength);
  614. }
  615. function errorCheck($line, $smtpConnection, $verbose = false) {
  616. global $color, $compose_new_win;
  617. /* Read new lines on a multiline response */
  618. $lines = $line;
  619. while(ereg("^[0-9]+-", $line)) {
  620. $line = fgets($smtpConnection, 1024);
  621. $lines .= $line;
  622. }
  623. /* Status: 0 = fatal
  624. * 5 = ok
  625. */
  626. $err_num = substr($line, 0, strpos($line, " "));
  627. switch ($err_num) {
  628. case 500: $message = 'Syntax error; command not recognized';
  629. $status = 0;
  630. break;
  631. case 501: $message = 'Syntax error in parameters or arguments';
  632. $status = 0;
  633. break;
  634. case 502: $message = 'Command not implemented';
  635. $status = 0;
  636. break;
  637. case 503: $message = 'Bad sequence of commands';
  638. $status = 0;
  639. break;
  640. case 504: $message = 'Command parameter not implemented';
  641. $status = 0;
  642. break;
  643. case 211: $message = 'System status, or system help reply';
  644. $status = 5;
  645. break;
  646. case 214: $message = 'Help message';
  647. $status = 5;
  648. break;
  649. case 220: $message = 'Service ready';
  650. $status = 5;
  651. break;
  652. case 221: $message = 'Service closing transmission channel';
  653. $status = 5;
  654. break;
  655. case 421: $message = 'Service not available, closing chanel';
  656. $status = 0;
  657. break;
  658. case 235: return(5);
  659. break;
  660. case 250: $message = 'Requested mail action okay, completed';
  661. $status = 5;
  662. break;
  663. case 251: $message = 'User not local; will forward';
  664. $status = 5;
  665. break;
  666. case 334: return(5); break;
  667. case 450: $message = 'Requested mail action not taken: mailbox unavailable';
  668. $status = 0;
  669. break;
  670. case 550: $message = 'Requested action not taken: mailbox unavailable';
  671. $status = 0;
  672. break;
  673. case 451: $message = 'Requested action aborted: error in processing';
  674. $status = 0;
  675. break;
  676. case 551: $message = 'User not local; please try forwarding';
  677. $status = 0;
  678. break;
  679. case 452: $message = 'Requested action not taken: insufficient system storage';
  680. $status = 0;
  681. break;
  682. case 552: $message = 'Requested mail action aborted: exceeding storage allocation';
  683. $status = 0;
  684. break;
  685. case 553: $message = 'Requested action not taken: mailbox name not allowed';
  686. $status = 0;
  687. break;
  688. case 354: $message = 'Start mail input; end with .';
  689. $status = 5;
  690. break;
  691. case 554: $message = 'Transaction failed';
  692. $status = 0;
  693. break;
  694. default: $message = 'Unknown response: '. nl2br(htmlspecialchars($lines));
  695. $status = 0;
  696. $error_num = '001';
  697. break;
  698. }
  699. if ($status == 0) {
  700. include_once(SM_PATH . 'functions/page_header.php');
  701. if ($compose_new_win == '1') {
  702. compose_Header($color, 'None');
  703. }
  704. else {
  705. displayPageHeader($color, 'None');
  706. }
  707. include_once(SM_PATH . 'functions/display_messages.php');
  708. $lines = nl2br(htmlspecialchars($lines));
  709. $msg = $message . "<br>\nServer replied: $lines";
  710. plain_error_message($msg, $color);
  711. }
  712. if (! $verbose) return $status;
  713. return $err_num;
  714. }
  715. /* create new reference header per rfc2822 */
  716. function calculate_references($refs, $inreplyto, $old_reply_to) {
  717. $refer = "";
  718. for ($i=1;$i<count($refs[0]);$i++) {
  719. if (!empty($refs[0][$i])) {
  720. if (preg_match("/^References:(.+)$/UAi", $refs[0][$i], $regs)) {
  721. $refer = trim($regs[1]);
  722. }
  723. else {
  724. $refer .= ' ' . trim($refs[0][$i]);
  725. }
  726. }
  727. }
  728. $refer_a = explode(' ', $refer);
  729. $refer = '';
  730. foreach ($refer_a as $ref) {
  731. $ref = trim($ref);
  732. if ($ref && $ref{0} == '<' && $ref{(strlen($ref)-1)} == '>') {
  733. $refer .= $ref . ' ';
  734. }
  735. }
  736. $refer = trim($refer);
  737. if (strlen($refer) > 2) {
  738. $refer .= ' ' . $inreplyto;
  739. }
  740. else {
  741. if (!empty($old_reply_to)) {
  742. $refer .= $old_reply_to . ' ' . $inreplyto;
  743. }
  744. else {
  745. $refer .= $inreplyto;
  746. }
  747. }
  748. trim($refer);
  749. return $refer;
  750. }
  751. function sendMessage($t, $c, $b, $subject, $body, $reply_id, $MDN,
  752. $prio = 3, $session) {
  753. global $useSendmail, $msg_id, $is_reply, $mailbox, $onetimepad,
  754. $data_dir, $username, $domain, $key, $version, $sent_folder,
  755. $imapServerAddress, $imapPort, $default_use_priority, $more_headers,
  756. $request_mdn, $request_dr, $uid_support;
  757. $more_headers = Array();
  758. do_hook('smtp_send');
  759. $imap_stream = sqimap_login($username, $key, $imapServerAddress,
  760. $imapPort, 1);
  761. if (isset($reply_id) && $reply_id) {
  762. sqimap_mailbox_select ($imap_stream, $mailbox);
  763. sqimap_messages_flag ($imap_stream, $reply_id, $reply_id, 'Answered', true);
  764. /* Insert In-Reply-To and References headers if the
  765. * message-id of the message we reply to is set (longer than "<>")
  766. * The References header should really be the old Referenced header
  767. * with the message ID appended, and now it is (jmunro)
  768. */
  769. $sid = sqimap_session_id($uid_support);
  770. $query = "$sid FETCH $reply_id (BODY.PEEK[HEADER.FIELDS (Message-Id In-Reply-To)])\r\n";
  771. fputs ($imap_stream, $query);
  772. $read = sqimap_read_data($imap_stream, $sid, true, $response, $message);
  773. $message_id = '';
  774. $in_reply_to = '';
  775. foreach ($read as $r) {
  776. if (preg_match("/^message-id:(.*)/iA", $r, $regs)) {
  777. $message_id = trim($regs[1]);
  778. }
  779. if (preg_match("/^in-reply-to:(.*)/iA", $r, $regs)) {
  780. $in_reply_to = trim($regs[1]);
  781. }
  782. }
  783. if(strlen($message_id) > 2) {
  784. $refs = get_reference_header ($imap_stream, $reply_id);
  785. $inreplyto = $message_id;
  786. $old_reply_to = $in_reply_to;
  787. $refer = calculate_references ($refs, $inreplyto, $old_reply_to);
  788. $more_headers['In-Reply-To'] = $inreplyto;
  789. $more_headers['References'] = $refer;
  790. }
  791. }
  792. if ($default_use_priority) {
  793. $more_headers = array_merge($more_headers, createPriorityHeaders($prio));
  794. }
  795. $requestRecipt = 0;
  796. if (isset($request_dr)) {
  797. $requestRecipt += 1;
  798. }
  799. if (isset($request_mdn)) {
  800. $requestRecipt += 2;
  801. }
  802. if ( $requestRecipt > 0) {
  803. $more_headers = array_merge($more_headers, createReceiptHeaders($requestRecipt));
  804. }
  805. if ($MDN) {
  806. $more_headers["Content-Type"] = "multipart/report; ".
  807. "report-type=disposition-notification;";
  808. }
  809. $imap_body = $body;
  810. if ($useSendmail) {
  811. /* In order to remove the problem of users not able to create
  812. * messages with "." on a blank line, RFC821 has made provision
  813. * in section 4.5.2 (Transparency).
  814. */
  815. if (($body && $body{0} == '.')) {
  816. $body = '.' . $body;
  817. }
  818. $body = str_replace("\n.","\n..",$body);
  819. $length = sendSendmail($t, $c, $b, $subject, $body, $more_headers,
  820. $session);
  821. } else {
  822. /* In order to remove the problem of users not able to create
  823. * messages with "." on a blank line, RFC821 has made provision
  824. * in section 4.5.2 (Transparency).
  825. */
  826. if (($body && $body{0} == '.')) {
  827. $body = '.' . $body;
  828. }
  829. $body = str_replace("\n.","\n..",$body);
  830. $length = sendSMTP($t, $c, $b, $subject, $body, $more_headers,
  831. $session);
  832. }
  833. if (sqimap_mailbox_exists ($imap_stream, $sent_folder)) {
  834. $body = $imap_body;
  835. $body = ereg_replace("\n", "\r\n", $body);
  836. $headerlength = write822Header (false, $t, $c, $b, $subject, $body, $more_headers, $session, "\r\n");
  837. $bodylength = writeBody(false, $body, $session, "\r\n");
  838. $length = $headerlength + $bodylength;
  839. sqimap_append ($imap_stream, $sent_folder, $length);
  840. write822Header ($imap_stream, $t, $c, $b, $subject, $body, $more_headers,
  841. $session);
  842. writeBody ($imap_stream, $body, $session);
  843. sqimap_append_done ($imap_stream);
  844. }
  845. sqimap_logout($imap_stream);
  846. /* Delete the files uploaded for attaching (if any).
  847. * only if $length != 0 (if there was no error)
  848. */
  849. if ($length) {
  850. ClearAttachments($session);
  851. }
  852. return $length;
  853. }
  854. function createPriorityHeaders($prio) {
  855. $prio_headers = Array();
  856. $prio_headers['X-Priority'] = $prio;
  857. switch($prio) {
  858. case 1:
  859. $prio_headers['Importance'] = 'High';
  860. break;
  861. case 3:
  862. $prio_headers['Importance'] = 'Normal';
  863. break;
  864. case 5:
  865. $prio_headers['Importance'] = 'Low';
  866. break;
  867. }
  868. return $prio_headers;
  869. }
  870. function createReceiptHeaders($receipt) {
  871. GLOBAL $data_dir, $username, $identity, $popuser, $domain;
  872. $receipt_headers = Array();
  873. if (isset($identity) && $identity != 'default') {
  874. $from = getPref($data_dir, $username, 'full_name' . $identity);
  875. $from_addr = getPref($data_dir, $username, 'email_address' . $identity);
  876. } else {
  877. $from = getPref($data_dir, $username, 'full_name');
  878. $from_addr = getPref($data_dir, $username, 'email_address');
  879. }
  880. if ($from_addr == '') {
  881. $from_addr = $popuser.'@'.$domain;
  882. }
  883. if ($from == '') {
  884. $from = "<$from_addr>";
  885. }
  886. else {
  887. $from = '"' . encodeHeader($from) . "\" <$from_addr>";
  888. }
  889. /* On Delivery */
  890. if ( $receipt == 1
  891. || $receipt == 3 ) {
  892. $receipt_headers["Return-Receipt-To"] = $from;
  893. }
  894. /* On Read */
  895. if ($receipt == 2
  896. || $receipt == 3 ) {
  897. /* Pegasus Mail */
  898. $receipt_headers["X-Confirm-Reading-To"] = $from;
  899. /* RFC 2298 */
  900. $receipt_headers["Disposition-Notification-To"] = $from;
  901. }
  902. return $receipt_headers;
  903. }
  904. /* Figure out what the 'From:' address is
  905. */
  906. function getFrom() {
  907. global $username, $popuser, $domain, $data_dir, $identity;
  908. if (isset($identity) && $identity != 'default') {
  909. $from_addr = getPref($data_dir, $username,
  910. 'email_address' . $identity);
  911. }
  912. else {
  913. $from_addr = getPref($data_dir, $username, 'email_address');
  914. }
  915. if (!$from_addr) {
  916. $from_addr = "$popuser@$domain";
  917. }
  918. return $from_addr;
  919. }
  920. ?>