smtp.php 30 KB

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