smtp.php 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037
  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 $REMOTE_ADDR, $SERVER_NAME, $REMOTE_PORT;
  247. global $data_dir, $username, $popuser, $domain, $version, $useSendmail;
  248. global $default_charset, $HTTP_VIA, $HTTP_X_FORWARDED_FOR;
  249. global $REMOTE_HOST, $identity;
  250. /* Storing the header to make sure the header is the same
  251. * everytime the header is printed.
  252. */
  253. static $header, $headerlength, $headerrn;
  254. if ($header == '') {
  255. $headerrn = $rn;
  256. $to = expandAddrs(parseAddrs($t));
  257. $cc = expandAddrs(parseAddrs($c));
  258. $bcc = expandAddrs(parseAddrs($b));
  259. if (isset($identity) && $identity != 'default') {
  260. $reply_to = getPref($data_dir, $username, 'reply_to' . $identity);
  261. $from = getPref($data_dir, $username, 'full_name' . $identity);
  262. $from_addr = getFrom();
  263. } else {
  264. $reply_to = getPref($data_dir, $username, 'reply_to');
  265. $from = getPref($data_dir, $username, 'full_name');
  266. $from_addr = getFrom();
  267. }
  268. $to_list = getLineOfAddrs($to);
  269. $cc_list = getLineOfAddrs($cc);
  270. $bcc_list = getLineOfAddrs($bcc);
  271. /* Encoding 8-bit characters and making from line */
  272. $subject = encodeHeader($subject);
  273. if ($from == '') {
  274. $from = "<$from_addr>";
  275. }
  276. else {
  277. $from = '"' . encodeHeader($from) . "\" <$from_addr>";
  278. }
  279. /* This creates an RFC 822 date */
  280. $date = date("D, j M Y H:i:s ", mktime()) . timezone();
  281. /* Create a message-id */
  282. $message_id = '<' . $REMOTE_PORT . '.' . $REMOTE_ADDR . '.';
  283. $message_id .= time() . '.squirrel@' . $SERVER_NAME .'>';
  284. /* Make an RFC822 Received: line */
  285. if (isset($REMOTE_HOST)) {
  286. $received_from = "$REMOTE_HOST ([$REMOTE_ADDR])";
  287. }
  288. else {
  289. $received_from = $REMOTE_ADDR;
  290. }
  291. if (isset($HTTP_VIA) || isset ($HTTP_X_FORWARDED_FOR)) {
  292. if ($HTTP_X_FORWARDED_FOR == '') {
  293. $HTTP_X_FORWARDED_FOR = 'unknown';
  294. }
  295. $received_from .= " (proxying for $HTTP_X_FORWARDED_FOR)";
  296. }
  297. $header = "Received: from $received_from" . $rn;
  298. $header .= " (SquirrelMail authenticated user $username)" . $rn;
  299. $header .= " by $SERVER_NAME with HTTP;" . $rn;
  300. $header .= " $date" . $rn;
  301. /* Insert the rest of the header fields */
  302. $header .= "Message-ID: $message_id" . $rn;
  303. $header .= "Date: $date" . $rn;
  304. $header .= "Subject: $subject" . $rn;
  305. $header .= "From: $from" . $rn;
  306. $header .= "To: $to_list" . $rn; // Who it's TO
  307. if (isset($more_headers["Content-Type"])) {
  308. $contentType = $more_headers["Content-Type"];
  309. unset($more_headers["Content-Type"]);
  310. }
  311. else {
  312. if (isMultipart($session)) {
  313. $contentType = "multipart/mixed;";
  314. }
  315. else {
  316. if ($default_charset != '') {
  317. $contentType = 'text/plain; charset='.$default_charset;
  318. }
  319. else {
  320. $contentType = 'text/plain;';
  321. }
  322. }
  323. }
  324. /* Insert headers from the $more_headers array */
  325. if(is_array($more_headers)) {
  326. reset($more_headers);
  327. while(list($h_name, $h_val) = each($more_headers)) {
  328. if ($h_name == 'References') {
  329. $h_val = str_replace(' ', "$rn ", $h_val);
  330. }
  331. $header .= sprintf("%s: %s%s", $h_name, $h_val, $rn);
  332. }
  333. }
  334. if ($cc_list) {
  335. $header .= "Cc: $cc_list" . $rn; // Who the CCs are
  336. }
  337. if ($reply_to != '') {
  338. $header .= "Reply-To: $reply_to" . $rn;
  339. }
  340. if ($useSendmail) {
  341. if ($bcc_list) {
  342. // BCCs is removed from header by sendmail
  343. $header .= "Bcc: $bcc_list" . $rn;
  344. }
  345. }
  346. /* Identify SquirrelMail */
  347. $header .= "X-Mailer: SquirrelMail (version $version)" . $rn;
  348. /* Do the MIME-stuff */
  349. $header .= "MIME-Version: 1.0" . $rn;
  350. if (isMultipart($session)) {
  351. $header .= 'Content-Type: '.$contentType.' boundary="';
  352. $header .= mimeBoundary();
  353. $header .= "\"$rn";
  354. } else {
  355. if (strtolower($default_charset) == 'iso-2022-jp') {
  356. if (mb_detect_encoding($body) == 'ASCII') {
  357. $header .= 'Content-Type: text/plain; US-ASCII' . $rn;
  358. $header .= "Content-Transfer-Encoding: 8bit" . $rn;
  359. } else {
  360. $header .= 'Content-Type: '.$contentType . $rn;
  361. $header .= "Content-Transfer-Encoding: 7bit" . $rn;
  362. }
  363. } else {
  364. $header .= 'Content-Type: ' . $contentType . $rn;
  365. $header .= "Content-Transfer-Encoding: 8bit" . $rn;
  366. }
  367. }
  368. $header .= $rn; // One blank line to separate header and body
  369. $headerlength = strlen($header);
  370. }
  371. if ($headerrn != $rn) {
  372. $header = str_replace($headerrn, $rn, $header);
  373. $headerlength = strlen($header);
  374. $headerrn = $rn;
  375. }
  376. /* Write the header */
  377. if ($fp) fputs ($fp, $header);
  378. return $headerlength;
  379. }
  380. /* Send the body
  381. */
  382. function writeBody ($fp, $passedBody, $session, $rn="\r\n", $checkdot = false) {
  383. global $default_charset;
  384. $attachmentlength = 0;
  385. if (isMultipart($session)) {
  386. $body = '--'.mimeBoundary() . $rn;
  387. if ($default_charset != "") {
  388. $body .= "Content-Type: text/plain; charset=$default_charset".$rn;
  389. }
  390. else {
  391. $body .= "Content-Type: text/plain" . $rn;
  392. }
  393. if (strtolower($default_charset) == 'iso-2022-jp') {
  394. if (mb_detect_encoding($passedBody) == 'ASCII') {
  395. $body .= "Content-Transfer-Encoding: 8bit" . $rn . $rn .
  396. $passedBody . $rn . $rn;
  397. } else {
  398. $body .= "Content-Transfer-Encoding: 7bit\r\n\r\n" .
  399. mb_convert_encoding($passedBody, 'JIS') . "\r\n\r\n";
  400. }
  401. } else {
  402. $body .= "Content-Transfer-Encoding: 8bit" . $rn . $rn .
  403. $passedBody . $rn . $rn;
  404. }
  405. if ($fp) {
  406. fputs ($fp, $body);
  407. }
  408. $attachmentlength = attachFiles($fp, $session, $rn, $checkdot);
  409. if (!isset($postbody)) {
  410. $postbody = "";
  411. }
  412. $postbody .= $rn . "--" . mimeBoundary() . "--" . $rn . $rn;
  413. if ($fp) fputs ($fp, $postbody);
  414. } else {
  415. if (strtolower($default_charset) == 'iso-2022-jp') {
  416. $body = mb_convert_encoding($passedBody, 'JIS') . $rn;
  417. } else {
  418. $body = $passedBody . $rn;
  419. }
  420. if ($fp) {
  421. fputs ($fp, $body);
  422. }
  423. $postbody = $rn;
  424. if ($fp) {
  425. fputs ($fp, $postbody);
  426. }
  427. }
  428. return (strlen($body) + strlen($postbody) + $attachmentlength);
  429. }
  430. /* Send mail using the sendmail command
  431. */
  432. function sendSendmail($t, $c, $b, $subject, $body, $more_headers, $session) {
  433. global $sendmail_path, $popuser, $username, $domain;
  434. /* Build envelope sender address. Make sure it doesn't contain
  435. * spaces or other "weird" chars that would allow a user to
  436. * exploit the shell/pipe it is used in.
  437. */
  438. $envelopefrom = getFrom();
  439. $envelopefrom = ereg_replace("[[:blank:]]",'', $envelopefrom);
  440. $envelopefrom = ereg_replace("[[:space:]]",'', $envelopefrom);
  441. $envelopefrom = ereg_replace("[[:cntrl:]]",'', $envelopefrom);
  442. /**
  443. * open pipe to sendmail or qmail-inject
  444. * (qmail-inject doesn't accept -t param)
  445. */
  446. if (strstr($sendmail_path, "qmail-inject")) {
  447. $fp = popen (escapeshellcmd("$sendmail_path -f$envelopefrom"), "w");
  448. } else {
  449. $fp = popen (escapeshellcmd("$sendmail_path -t -f$envelopefrom"), "w");
  450. }
  451. $headerlength = write822Header ($fp, $t, $c, $b, $subject, $body,
  452. $more_headers, $session, "\n");
  453. $bodylength = writeBody($fp, $body, $session, "\n", true);
  454. pclose($fp);
  455. return ($headerlength + $bodylength);
  456. }
  457. function smtpReadData($smtpConnection) {
  458. $read = fgets($smtpConnection, 1024);
  459. $counter = 0;
  460. while ($read) {
  461. echo $read . '<BR>';
  462. $data[$counter] = $read;
  463. $read = fgets($smtpConnection, 1024);
  464. $counter++;
  465. }
  466. }
  467. function sendSMTP($t, $c, $b, $subject, $body, $more_headers, $session) {
  468. global $username, $popuser, $domain, $version, $smtpServerAddress,
  469. $smtpPort, $data_dir, $color, $use_authenticated_smtp, $identity,
  470. $key, $onetimepad;
  471. $to = expandRcptAddrs(parseAddrs($t));
  472. $cc = expandRcptAddrs(parseAddrs($c));
  473. $bcc = expandRcptAddrs(parseAddrs($b));
  474. if (isset($identity) && $identity != 'default') {
  475. $from_addr = getPref($data_dir, $username,
  476. 'email_address' . $identity);
  477. }
  478. else {
  479. $from_addr = getPref($data_dir, $username, 'email_address');
  480. }
  481. if (!$from_addr) {
  482. $from_addr = "$popuser@$domain";
  483. }
  484. /* POP3 BEFORE SMTP CODE HERE */
  485. global $pop_before_smtp;
  486. if (isset($pop_before_smtp) && $pop_before_smtp === true) {
  487. if (!isset($pop_port)) {
  488. $pop_port = 110;
  489. }
  490. if (!isset($pop_server)) {
  491. $pop_server = $smtpServerAddress; /* usually the same host! */
  492. }
  493. $popConnection = fsockopen($pop_server, $pop_port, $err_no, $err_str);
  494. if (!$popConnection) {
  495. error_log("Error connecting to POP Server ($pop_server:$pop_port)"
  496. . " $err_no : $err_str");
  497. } else {
  498. $tmp = fgets($popConnection, 1024); /* banner */
  499. if (!eregi("^\+OK", $tmp, $regs)) {
  500. return(0);
  501. }
  502. fputs($popConnection, "USER $username\r\n");
  503. $tmp = fgets($popConnection, 1024);
  504. if (!eregi("^\+OK", $tmp, $regs)) {
  505. return(0);
  506. }
  507. fputs($popConnection, 'PASS ' . OneTimePadDecrypt($key, $onetimepad) . "\r\n");
  508. $tmp = fgets($popConnection, 1024);
  509. if (!eregi("^\+OK", $tmp, $regs)) {
  510. return(0);
  511. }
  512. fputs($popConnection, "QUIT\r\n"); /* log off */
  513. fclose($popConnection);
  514. }
  515. }
  516. $smtpConnection = fsockopen($smtpServerAddress, $smtpPort,
  517. $errorNumber, $errorString);
  518. if (!$smtpConnection) {
  519. echo 'Error connecting to SMTP Server.<br>';
  520. echo "$errorNumber : $errorString<br>";
  521. exit;
  522. }
  523. $tmp = fgets($smtpConnection, 1024);
  524. if (errorCheck($tmp, $smtpConnection)!=5) {
  525. return(0);
  526. }
  527. $to_list = getLineOfAddrs($to);
  528. $cc_list = getLineOfAddrs($cc);
  529. /* Lets introduce ourselves */
  530. if (! isset ($use_authenticated_smtp)
  531. || $use_authenticated_smtp == false) {
  532. fputs($smtpConnection, "HELO $domain\r\n");
  533. $tmp = fgets($smtpConnection, 1024);
  534. if (errorCheck($tmp, $smtpConnection)!=5) return(0);
  535. } else {
  536. fputs($smtpConnection, "EHLO $domain\r\n");
  537. $tmp = fgets($smtpConnection, 1024);
  538. if (errorCheck($tmp, $smtpConnection)!=5) return(0);
  539. fputs($smtpConnection, "AUTH LOGIN\r\n");
  540. $tmp = fgets($smtpConnection, 1024);
  541. if (errorCheck($tmp, $smtpConnection)!=5) {
  542. return(0);
  543. }
  544. fputs($smtpConnection, base64_encode ($username) . "\r\n");
  545. $tmp = fgets($smtpConnection, 1024);
  546. if (errorCheck($tmp, $smtpConnection)!=5) {
  547. return(0);
  548. }
  549. fputs($smtpConnection, base64_encode
  550. (OneTimePadDecrypt($key, $onetimepad)) . "\r\n");
  551. $tmp = fgets($smtpConnection, 1024);
  552. if (errorCheck($tmp, $smtpConnection)!=5) {
  553. return(0);
  554. }
  555. }
  556. /* Ok, who is sending the message? */
  557. fputs($smtpConnection, "MAIL FROM: <$from_addr>\r\n");
  558. $tmp = fgets($smtpConnection, 1024);
  559. if (errorCheck($tmp, $smtpConnection)!=5) {
  560. return(0);
  561. }
  562. /* send who the recipients are */
  563. for ($i = 0; $i < count($to); $i++) {
  564. fputs($smtpConnection, "RCPT TO: $to[$i]\r\n");
  565. $tmp = fgets($smtpConnection, 1024);
  566. if (errorCheck($tmp, $smtpConnection)!=5) {
  567. return(0);
  568. }
  569. }
  570. for ($i = 0; $i < count($cc); $i++) {
  571. fputs($smtpConnection, "RCPT TO: $cc[$i]\r\n");
  572. $tmp = fgets($smtpConnection, 1024);
  573. if (errorCheck($tmp, $smtpConnection)!=5) {
  574. return(0);
  575. }
  576. }
  577. for ($i = 0; $i < count($bcc); $i++) {
  578. fputs($smtpConnection, "RCPT TO: $bcc[$i]\r\n");
  579. $tmp = fgets($smtpConnection, 1024);
  580. if (errorCheck($tmp, $smtpConnection)!=5) {
  581. return(0);
  582. }
  583. }
  584. /* Lets start sending the actual message */
  585. fputs($smtpConnection, "DATA\r\n");
  586. $tmp = fgets($smtpConnection, 1024);
  587. if (errorCheck($tmp, $smtpConnection)!=5) {
  588. return(0);
  589. }
  590. /* Send the message */
  591. $headerlength = write822Header ($smtpConnection, $t, $c, $b,
  592. $subject, $body, $more_headers, $session);
  593. $bodylength = writeBody($smtpConnection, $body, $session,"\r\n", true);
  594. fputs($smtpConnection, ".\r\n"); /* end the DATA part */
  595. $tmp = fgets($smtpConnection, 1024);
  596. $num = errorCheck($tmp, $smtpConnection, true);
  597. if ($num != 250) {
  598. return(0);
  599. }
  600. fputs($smtpConnection, "QUIT\r\n"); /* log off */
  601. fclose($smtpConnection);
  602. return ($headerlength + $bodylength);
  603. }
  604. function errorCheck($line, $smtpConnection, $verbose = false) {
  605. global $color, $compose_new_win;
  606. /* Read new lines on a multiline response */
  607. $lines = $line;
  608. while(ereg("^[0-9]+-", $line)) {
  609. $line = fgets($smtpConnection, 1024);
  610. $lines .= $line;
  611. }
  612. /* Status: 0 = fatal
  613. * 5 = ok
  614. */
  615. $err_num = substr($line, 0, strpos($line, " "));
  616. switch ($err_num) {
  617. case 500: $message = 'Syntax error; command not recognized';
  618. $status = 0;
  619. break;
  620. case 501: $message = 'Syntax error in parameters or arguments';
  621. $status = 0;
  622. break;
  623. case 502: $message = 'Command not implemented';
  624. $status = 0;
  625. break;
  626. case 503: $message = 'Bad sequence of commands';
  627. $status = 0;
  628. break;
  629. case 504: $message = 'Command parameter not implemented';
  630. $status = 0;
  631. break;
  632. case 211: $message = 'System status, or system help reply';
  633. $status = 5;
  634. break;
  635. case 214: $message = 'Help message';
  636. $status = 5;
  637. break;
  638. case 220: $message = 'Service ready';
  639. $status = 5;
  640. break;
  641. case 221: $message = 'Service closing transmission channel';
  642. $status = 5;
  643. break;
  644. case 421: $message = 'Service not available, closing chanel';
  645. $status = 0;
  646. break;
  647. case 235: return(5);
  648. break;
  649. case 250: $message = 'Requested mail action okay, completed';
  650. $status = 5;
  651. break;
  652. case 251: $message = 'User not local; will forward';
  653. $status = 5;
  654. break;
  655. case 334: return(5); break;
  656. case 450: $message = 'Requested mail action not taken: mailbox unavailable';
  657. $status = 0;
  658. break;
  659. case 550: $message = 'Requested action not taken: mailbox unavailable';
  660. $status = 0;
  661. break;
  662. case 451: $message = 'Requested action aborted: error in processing';
  663. $status = 0;
  664. break;
  665. case 551: $message = 'User not local; please try forwarding';
  666. $status = 0;
  667. break;
  668. case 452: $message = 'Requested action not taken: insufficient system storage';
  669. $status = 0;
  670. break;
  671. case 552: $message = 'Requested mail action aborted: exceeding storage allocation';
  672. $status = 0;
  673. break;
  674. case 553: $message = 'Requested action not taken: mailbox name not allowed';
  675. $status = 0;
  676. break;
  677. case 354: $message = 'Start mail input; end with .';
  678. $status = 5;
  679. break;
  680. case 554: $message = 'Transaction failed';
  681. $status = 0;
  682. break;
  683. default: $message = 'Unknown response: '. nl2br(htmlspecialchars($lines));
  684. $status = 0;
  685. $error_num = '001';
  686. break;
  687. }
  688. if ($status == 0) {
  689. include_once(SM_PATH . 'functions/page_header.php');
  690. if ($compose_new_win == '1') {
  691. compose_Header($color, 'None');
  692. }
  693. else {
  694. displayPageHeader($color, 'None');
  695. }
  696. include_once(SM_PATH . 'functions/display_messages.php');
  697. $lines = nl2br(htmlspecialchars($lines));
  698. $msg = $message . "<br>\nServer replied: $lines";
  699. plain_error_message($msg, $color);
  700. }
  701. if (! $verbose) return $status;
  702. return $err_num;
  703. }
  704. /* create new reference header per rfc2822 */
  705. function calculate_references($refs, $inreplyto, $old_reply_to) {
  706. $refer = "";
  707. for ($i=1;$i<count($refs[0]);$i++) {
  708. if (!empty($refs[0][$i])) {
  709. if (preg_match("/^References:(.+)$/UAi", $refs[0][$i], $regs)) {
  710. $refer = trim($regs[1]);
  711. }
  712. else {
  713. $refer .= ' ' . trim($refs[0][$i]);
  714. }
  715. }
  716. }
  717. $refer_a = explode(' ', $refer);
  718. $refer = '';
  719. foreach ($refer_a as $ref) {
  720. $ref = trim($ref);
  721. if ($ref && $ref{0} == '<' && $ref{(strlen($ref)-1)} == '>') {
  722. $refer .= $ref . ' ';
  723. }
  724. }
  725. $refer = trim($refer);
  726. if (strlen($refer) > 2) {
  727. $refer .= ' ' . $inreplyto;
  728. }
  729. else {
  730. if (!empty($old_reply_to)) {
  731. $refer .= $old_reply_to . ' ' . $inreplyto;
  732. }
  733. else {
  734. $refer .= $inreplyto;
  735. }
  736. }
  737. trim($refer);
  738. return $refer;
  739. }
  740. function sendMessage($t, $c, $b, $subject, $body, $reply_id, $MDN,
  741. $prio = 3, $session) {
  742. global $useSendmail, $msg_id, $is_reply, $mailbox, $onetimepad,
  743. $data_dir, $username, $domain, $key, $version, $sent_folder,
  744. $imapServerAddress, $imapPort, $default_use_priority, $more_headers,
  745. $request_mdn, $request_dr, $uid_support;
  746. $more_headers = Array();
  747. do_hook('smtp_send');
  748. $imap_stream = sqimap_login($username, $key, $imapServerAddress,
  749. $imapPort, 1);
  750. if (isset($reply_id) && $reply_id) {
  751. sqimap_mailbox_select ($imap_stream, $mailbox);
  752. sqimap_messages_flag ($imap_stream, $reply_id, $reply_id, 'Answered', true);
  753. /* Insert In-Reply-To and References headers if the
  754. * message-id of the message we reply to is set (longer than "<>")
  755. * The References header should really be the old Referenced header
  756. * with the message ID appended, and now it is (jmunro)
  757. */
  758. $sid = sqimap_session_id($uid_support);
  759. $query = "$sid FETCH $reply_id (BODY.PEEK[HEADER.FIELDS (Message-Id In-Reply-To)])\r\n";
  760. fputs ($imap_stream, $query);
  761. $read = sqimap_read_data($imap_stream, $sid, true, $response, $message);
  762. $message_id = '';
  763. $in_reply_to = '';
  764. foreach ($read as $r) {
  765. if (preg_match("/^message-id:(.*)/iA", $r, $regs)) {
  766. $message_id = trim($regs[1]);
  767. }
  768. if (preg_match("/^in-reply-to:(.*)/iA", $r, $regs)) {
  769. $in_reply_to = trim($regs[1]);
  770. }
  771. }
  772. if(strlen($message_id) > 2) {
  773. $refs = get_reference_header ($imap_stream, $reply_id);
  774. $inreplyto = $message_id;
  775. $old_reply_to = $in_reply_to;
  776. $refer = calculate_references ($refs, $inreplyto, $old_reply_to);
  777. $more_headers['In-Reply-To'] = $inreplyto;
  778. $more_headers['References'] = $refer;
  779. }
  780. }
  781. if ($default_use_priority) {
  782. $more_headers = array_merge($more_headers, createPriorityHeaders($prio));
  783. }
  784. $requestRecipt = 0;
  785. if (isset($request_dr)) {
  786. $requestRecipt += 1;
  787. }
  788. if (isset($request_mdn)) {
  789. $requestRecipt += 2;
  790. }
  791. if ( $requestRecipt > 0) {
  792. $more_headers = array_merge($more_headers, createReceiptHeaders($requestRecipt));
  793. }
  794. if ($MDN) {
  795. $more_headers["Content-Type"] = "multipart/report; ".
  796. "report-type=disposition-notification;";
  797. }
  798. $imap_body = $body;
  799. if ($useSendmail) {
  800. /* In order to remove the problem of users not able to create
  801. * messages with "." on a blank line, RFC821 has made provision
  802. * in section 4.5.2 (Transparency).
  803. */
  804. if (($body && $body{0} == '.')) {
  805. $body = '.' . $body;
  806. }
  807. $body = str_replace("\n.","\n..",$body);
  808. $length = sendSendmail($t, $c, $b, $subject, $body, $more_headers,
  809. $session);
  810. } else {
  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 = sendSMTP($t, $c, $b, $subject, $body, $more_headers,
  820. $session);
  821. }
  822. if (sqimap_mailbox_exists ($imap_stream, $sent_folder)) {
  823. $body = $imap_body;
  824. $body = ereg_replace("\n", "\r\n", $body);
  825. $headerlength = write822Header (false, $t, $c, $b, $subject, $body, $more_headers, $session, "\r\n");
  826. $bodylength = writeBody(false, $body, $session, "\r\n");
  827. $length = $headerlength + $bodylength;
  828. sqimap_append ($imap_stream, $sent_folder, $length);
  829. write822Header ($imap_stream, $t, $c, $b, $subject, $body, $more_headers,
  830. $session);
  831. writeBody ($imap_stream, $body, $session);
  832. sqimap_append_done ($imap_stream);
  833. }
  834. sqimap_logout($imap_stream);
  835. /* Delete the files uploaded for attaching (if any).
  836. * only if $length != 0 (if there was no error)
  837. */
  838. if ($length) {
  839. ClearAttachments($session);
  840. }
  841. return $length;
  842. }
  843. function createPriorityHeaders($prio) {
  844. $prio_headers = Array();
  845. $prio_headers['X-Priority'] = $prio;
  846. switch($prio) {
  847. case 1:
  848. $prio_headers['Importance'] = 'High';
  849. break;
  850. case 3:
  851. $prio_headers['Importance'] = 'Normal';
  852. break;
  853. case 5:
  854. $prio_headers['Importance'] = 'Low';
  855. break;
  856. }
  857. return $prio_headers;
  858. }
  859. function createReceiptHeaders($receipt) {
  860. GLOBAL $data_dir, $username, $identity, $popuser, $domain;
  861. $receipt_headers = Array();
  862. if (isset($identity) && $identity != 'default') {
  863. $from = getPref($data_dir, $username, 'full_name' . $identity);
  864. $from_addr = getPref($data_dir, $username, 'email_address' . $identity);
  865. } else {
  866. $from = getPref($data_dir, $username, 'full_name');
  867. $from_addr = getPref($data_dir, $username, 'email_address');
  868. }
  869. if ($from_addr == '') {
  870. $from_addr = $popuser.'@'.$domain;
  871. }
  872. if ($from == '') {
  873. $from = "<$from_addr>";
  874. }
  875. else {
  876. $from = '"' . encodeHeader($from) . "\" <$from_addr>";
  877. }
  878. /* On Delivery */
  879. if ( $receipt == 1
  880. || $receipt == 3 ) {
  881. $receipt_headers["Return-Receipt-To"] = $from;
  882. }
  883. /* On Read */
  884. if ($receipt == 2
  885. || $receipt == 3 ) {
  886. /* Pegasus Mail */
  887. $receipt_headers["X-Confirm-Reading-To"] = $from;
  888. /* RFC 2298 */
  889. $receipt_headers["Disposition-Notification-To"] = $from;
  890. }
  891. return $receipt_headers;
  892. }
  893. /* Figure out what the 'From:' address is
  894. */
  895. function getFrom() {
  896. global $username, $popuser, $domain, $data_dir, $identity;
  897. if (isset($identity) && $identity != 'default') {
  898. $from_addr = getPref($data_dir, $username,
  899. 'email_address' . $identity);
  900. }
  901. else {
  902. $from_addr = getPref($data_dir, $username, 'email_address');
  903. }
  904. if (!$from_addr) {
  905. $from_addr = "$popuser@$domain";
  906. }
  907. return $from_addr;
  908. }
  909. ?>