smtp.php 30 KB

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