smtp.php 29 KB

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