smtp.php 30 KB

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