smtp.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038
  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('../functions/addressbook.php');
  14. require_once('../functions/plugin.php');
  15. require_once('../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('../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('../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: $prio_headers['Importance'] = 'High';
  848. $prio_headers['X-MSMail-Priority'] = 'High';
  849. break;
  850. case 3: $prio_headers['Importance'] = 'Normal';
  851. $prio_headers['X-MSMail-Priority'] = 'Normal';
  852. break;
  853. case 5:
  854. $prio_headers['Importance'] = 'Low';
  855. $prio_headers['X-MSMail-Priority'] = 'Low';
  856. break;
  857. }
  858. return $prio_headers;
  859. }
  860. function createReceiptHeaders($receipt) {
  861. GLOBAL $data_dir, $username, $identity, $popuser, $domain;
  862. $receipt_headers = Array();
  863. if (isset($identity) && $identity != 'default') {
  864. $from = getPref($data_dir, $username, 'full_name' . $identity);
  865. $from_addr = getPref($data_dir, $username, 'email_address' . $identity);
  866. } else {
  867. $from = getPref($data_dir, $username, 'full_name');
  868. $from_addr = getPref($data_dir, $username, 'email_address');
  869. }
  870. if ($from_addr == '') {
  871. $from_addr = $popuser.'@'.$domain;
  872. }
  873. if ($from == '') {
  874. $from = "<$from_addr>";
  875. }
  876. else {
  877. $from = '"' . encodeHeader($from) . "\" <$from_addr>";
  878. }
  879. /* On Delivery */
  880. if ( $receipt == 1
  881. || $receipt == 3 ) {
  882. $receipt_headers["Return-Receipt-To"] = $from;
  883. }
  884. /* On Read */
  885. if ($receipt == 2
  886. || $receipt == 3 ) {
  887. /* Pegasus Mail */
  888. $receipt_headers["X-Confirm-Reading-To"] = $from;
  889. /* RFC 2298 */
  890. $receipt_headers["Disposition-Notification-To"] = $from;
  891. }
  892. return $receipt_headers;
  893. }
  894. /* Figure out what the 'From:' address is
  895. */
  896. function getFrom() {
  897. global $username, $popuser, $domain, $data_dir, $identity;
  898. if (isset($identity) && $identity != 'default') {
  899. $from_addr = getPref($data_dir, $username,
  900. 'email_address' . $identity);
  901. }
  902. else {
  903. $from_addr = getPref($data_dir, $username, 'email_address');
  904. }
  905. if (!$from_addr) {
  906. $from_addr = "$popuser@$domain";
  907. }
  908. return $from_addr;
  909. }
  910. ?>