Deliver.class.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816
  1. <?php
  2. /**
  3. * Deliver.class.php
  4. *
  5. * This contains all the functions needed to send messages through
  6. * a delivery backend.
  7. *
  8. * @author Marc Groot Koerkamp
  9. * @copyright &copy; 1999-2007 The SquirrelMail Project Team
  10. * @license http://opensource.org/licenses/gpl-license.php GNU Public License
  11. * @version $Id$
  12. * @package squirrelmail
  13. */
  14. /**
  15. * Deliver Class - called to actually deliver the message
  16. *
  17. * This class is called by compose.php and other code that needs
  18. * to send messages. All delivery functionality should be centralized
  19. * in this class.
  20. *
  21. * Do not place UI code in this class, as UI code should be placed in templates
  22. * going forward.
  23. *
  24. * @author Marc Groot Koerkamp
  25. * @package squirrelmail
  26. */
  27. class Deliver {
  28. /**
  29. * function mail - send the message parts to the SMTP stream
  30. *
  31. * @param Message $message Message class to send
  32. * @param resource $stream file handle to the SMTP stream
  33. *
  34. * @return integer $raw_length
  35. */
  36. function mail($message, $stream=false) {
  37. $rfc822_header = $message->rfc822_header;
  38. if (count($message->entities)) {
  39. $boundary = $this->mimeBoundary();
  40. $rfc822_header->content_type->properties['boundary']='"'.$boundary.'"';
  41. } else {
  42. $boundary='';
  43. }
  44. $raw_length = 0;
  45. $reply_rfc822_header = (isset($message->reply_rfc822_header)
  46. ? $message->reply_rfc822_header : '');
  47. $header = $this->prepareRFC822_Header($rfc822_header, $reply_rfc822_header, $raw_length);
  48. if ($stream) {
  49. $this->preWriteToStream($header);
  50. $this->writeToStream($stream, $header);
  51. }
  52. $this->writeBody($message, $stream, $raw_length, $boundary);
  53. return $raw_length;
  54. }
  55. /**
  56. * function writeBody - generate and write the mime boundaries around each part to the stream
  57. *
  58. * Recursively formats and writes the MIME boundaries of the $message
  59. * to the output stream.
  60. *
  61. * @param Message $message Message object to transform
  62. * @param resource $stream SMTP output stream
  63. * @param integer &$length_raw raw length of the message (part)
  64. * as returned by mail fn
  65. * @param string $boundary custom boundary to call, usually for subparts
  66. *
  67. * @return void
  68. */
  69. function writeBody($message, $stream, &$length_raw, $boundary='') {
  70. // calculate boundary in case of multidimensional mime structures
  71. if ($boundary && $message->entity_id && count($message->entities)) {
  72. if (strpos($boundary,'_part_')) {
  73. $boundary = substr($boundary,0,strpos($boundary,'_part_'));
  74. // the next four lines use strrev to reverse any nested boundaries
  75. // because RFC 2046 (5.1.1) says that if a line starts with the outer
  76. // boundary string (doesn't matter what the line ends with), that
  77. // can be considered a match for the outer boundary; thus the nested
  78. // boundary needs to be unique from the outer one
  79. //
  80. } else if (strpos($boundary,'_trap_')) {
  81. $boundary = substr(strrev($boundary),0,strpos(strrev($boundary),'_part_'));
  82. }
  83. $boundary_new = strrev($boundary . '_part_'.$message->entity_id);
  84. } else {
  85. $boundary_new = $boundary;
  86. }
  87. if ($boundary && !$message->rfc822_header) {
  88. $s = '--'.$boundary."\r\n";
  89. $s .= $this->prepareMIME_Header($message, $boundary_new);
  90. $length_raw += strlen($s);
  91. if ($stream) {
  92. $this->preWriteToStream($s);
  93. $this->writeToStream($stream, $s);
  94. }
  95. }
  96. $this->writeBodyPart($message, $stream, $length_raw);
  97. $last = false;
  98. for ($i=0, $entCount=count($message->entities);$i<$entCount;$i++) {
  99. $msg = $this->writeBody($message->entities[$i], $stream, $length_raw, $boundary_new);
  100. if ($i == $entCount-1) $last = true;
  101. }
  102. if ($boundary && $last) {
  103. $s = "--".$boundary_new."--\r\n\r\n";
  104. $length_raw += strlen($s);
  105. if ($stream) {
  106. $this->preWriteToStream($s);
  107. $this->writeToStream($stream, $s);
  108. }
  109. }
  110. }
  111. /**
  112. * function writeBodyPart - write each individual mimepart
  113. *
  114. * Recursively called by WriteBody to write each mime part to the SMTP stream
  115. *
  116. * @param Message $message Message object to transform
  117. * @param resource $stream SMTP output stream
  118. * @param integer &$length length of the message part
  119. * as returned by mail fn
  120. *
  121. * @return void
  122. */
  123. function writeBodyPart($message, $stream, &$length) {
  124. if ($message->mime_header) {
  125. $type0 = $message->mime_header->type0;
  126. } else {
  127. $type0 = $message->rfc822_header->content_type->type0;
  128. }
  129. $body_part_trailing = $last = '';
  130. switch ($type0)
  131. {
  132. case 'text':
  133. case 'message':
  134. if ($message->body_part) {
  135. $body_part = $message->body_part;
  136. // remove NUL characters
  137. $body_part = str_replace("\0",'',$body_part);
  138. $length += $this->clean_crlf($body_part);
  139. if ($stream) {
  140. $this->preWriteToStream($body_part);
  141. $this->writeToStream($stream, $body_part);
  142. }
  143. $last = $body_part;
  144. } elseif ($message->att_local_name) {
  145. $filename = $message->att_local_name;
  146. $file = fopen ($filename, 'rb');
  147. while ($body_part = fgets($file, 4096)) {
  148. // remove NUL characters
  149. $body_part = str_replace("\0",'',$body_part);
  150. $length += $this->clean_crlf($body_part);
  151. if ($stream) {
  152. $this->preWriteToStream($body_part);
  153. $this->writeToStream($stream, $body_part);
  154. }
  155. $last = $body_part;
  156. }
  157. fclose($file);
  158. }
  159. break;
  160. default:
  161. if ($message->body_part) {
  162. $body_part = $message->body_part;
  163. // remove NUL characters
  164. $body_part = str_replace("\0",'',$body_part);
  165. $length += $this->clean_crlf($body_part);
  166. if ($stream) {
  167. $this->writeToStream($stream, $body_part);
  168. }
  169. } elseif ($message->att_local_name) {
  170. $filename = $message->att_local_name;
  171. $file = fopen ($filename, 'rb');
  172. while ($tmp = fread($file, 570)) {
  173. $body_part = chunk_split(base64_encode($tmp));
  174. // Up to 4.3.10 chunk_split always appends a newline,
  175. // while in 4.3.11 it doesn't if the string to split
  176. // is shorter than the chunk length.
  177. if( substr($body_part, -1 , 1 ) != "\n" )
  178. $body_part .= "\n";
  179. $length += $this->clean_crlf($body_part);
  180. if ($stream) {
  181. $this->writeToStream($stream, $body_part);
  182. }
  183. }
  184. fclose($file);
  185. }
  186. break;
  187. }
  188. $body_part_trailing = '';
  189. if ($last && substr($last,-1) != "\n") {
  190. $body_part_trailing = "\r\n";
  191. }
  192. if ($body_part_trailing) {
  193. $length += strlen($body_part_trailing);
  194. if ($stream) {
  195. $this->preWriteToStream($body_part_trailing);
  196. $this->writeToStream($stream, $body_part_trailing);
  197. }
  198. }
  199. }
  200. /**
  201. * function clean_crlf - change linefeeds and newlines to legal characters
  202. *
  203. * The SMTP format only allows CRLF as line terminators.
  204. * This function replaces illegal teminators with the correct terminator.
  205. *
  206. * @param string &$s string to clean linefeeds on
  207. *
  208. * @return void
  209. */
  210. function clean_crlf(&$s) {
  211. $s = str_replace("\r\n", "\n", $s);
  212. $s = str_replace("\r", "\n", $s);
  213. $s = str_replace("\n", "\r\n", $s);
  214. return strlen($s);
  215. }
  216. /**
  217. * function strip_crlf - strip linefeeds and newlines from a string
  218. *
  219. * The SMTP format only allows CRLF as line terminators.
  220. * This function strips all line terminators from the string.
  221. *
  222. * @param string &$s string to clean linefeeds on
  223. *
  224. * @return void
  225. */
  226. function strip_crlf(&$s) {
  227. $s = str_replace("\r\n ", '', $s);
  228. $s = str_replace("\r", '', $s);
  229. $s = str_replace("\n", '', $s);
  230. }
  231. /**
  232. * function preWriteToStream - reserved for extended functionality
  233. *
  234. * This function is not yet implemented.
  235. * Reserved for extended functionality.
  236. *
  237. * @param string &$s string to operate on
  238. *
  239. * @return void
  240. */
  241. function preWriteToStream(&$s) {
  242. }
  243. /**
  244. * function writeToStream - write data to the SMTP stream
  245. *
  246. * @param resource $stream SMTP output stream
  247. * @param string $data string with data to send to the SMTP stream
  248. *
  249. * @return void
  250. */
  251. function writeToStream($stream, $data) {
  252. fputs($stream, $data);
  253. }
  254. /**
  255. * function initStream - reserved for extended functionality
  256. *
  257. * This function is not yet implemented.
  258. * Reserved for extended functionality.
  259. *
  260. * @param Message $message Message object
  261. * @param string $host host name or IP to connect to
  262. * @param string $user username to log into the SMTP server with
  263. * @param string $pass password to log into the SMTP server with
  264. * @param integer $length
  265. *
  266. * @return handle $stream file handle resource to SMTP stream
  267. */
  268. function initStream($message, $length=0, $host='', $port='', $user='', $pass='') {
  269. return $stream;
  270. }
  271. /**
  272. * function getBCC - reserved for extended functionality
  273. *
  274. * This function is not yet implemented.
  275. * Reserved for extended functionality.
  276. *
  277. */
  278. function getBCC() {
  279. return false;
  280. }
  281. /**
  282. * function prepareMIME_Header - creates the mime header
  283. *
  284. * @param Message $message Message object to act on
  285. * @param string $boundary mime boundary from fn MimeBoundary
  286. *
  287. * @return string $header properly formatted mime header
  288. */
  289. function prepareMIME_Header($message, $boundary) {
  290. $mime_header = $message->mime_header;
  291. $rn="\r\n";
  292. $header = array();
  293. $contenttype = 'Content-Type: '. $mime_header->type0 .'/'.
  294. $mime_header->type1;
  295. if (count($message->entities)) {
  296. $contenttype .= ';' . 'boundary="'.$boundary.'"';
  297. }
  298. if (isset($mime_header->parameters['name'])) {
  299. $contenttype .= '; name="'.
  300. encodeHeader($mime_header->parameters['name']). '"';
  301. }
  302. if (isset($mime_header->parameters['charset'])) {
  303. $charset = $mime_header->parameters['charset'];
  304. $contenttype .= '; charset="'.
  305. encodeHeader($charset). '"';
  306. }
  307. $header[] = $contenttype . $rn;
  308. if ($mime_header->description) {
  309. $header[] = 'Content-Description: ' . $mime_header->description . $rn;
  310. }
  311. if ($mime_header->encoding) {
  312. $header[] = 'Content-Transfer-Encoding: ' . $mime_header->encoding . $rn;
  313. } else {
  314. if ($mime_header->type0 == 'text' || $mime_header->type0 == 'message') {
  315. $header[] = 'Content-Transfer-Encoding: 8bit' . $rn;
  316. } else {
  317. $header[] = 'Content-Transfer-Encoding: base64' . $rn;
  318. }
  319. }
  320. if ($mime_header->id) {
  321. $header[] = 'Content-ID: ' . $mime_header->id . $rn;
  322. }
  323. if ($mime_header->disposition) {
  324. $disposition = $mime_header->disposition;
  325. $contentdisp = 'Content-Disposition: ' . $disposition->name;
  326. if ($disposition->getProperty('filename')) {
  327. $contentdisp .= '; filename="'.
  328. encodeHeader($disposition->getProperty('filename')). '"';
  329. }
  330. $header[] = $contentdisp . $rn;
  331. }
  332. if ($mime_header->md5) {
  333. $header[] = 'Content-MD5: ' . $mime_header->md5 . $rn;
  334. }
  335. if ($mime_header->language) {
  336. $header[] = 'Content-Language: ' . $mime_header->language . $rn;
  337. }
  338. $cnt = count($header);
  339. $hdr_s = '';
  340. for ($i = 0 ; $i < $cnt ; $i++) {
  341. $hdr_s .= $this->foldLine($header[$i], 78,str_pad('',4));
  342. }
  343. $header = $hdr_s;
  344. $header .= $rn; /* One blank line to separate mimeheader and body-entity */
  345. return $header;
  346. }
  347. /**
  348. * function prepareRFC822_Header - prepares the RFC822 header string from Rfc822Header object(s)
  349. *
  350. * This function takes the Rfc822Header object(s) and formats them
  351. * into the RFC822Header string to send to the SMTP server as part
  352. * of the SMTP message.
  353. *
  354. * @param Rfc822Header $rfc822_header
  355. * @param Rfc822Header $reply_rfc822_header
  356. * @param integer &$raw_length length of the message
  357. *
  358. * @return string $header
  359. */
  360. function prepareRFC822_Header($rfc822_header, $reply_rfc822_header, &$raw_length) {
  361. global $domain, $version, $username, $encode_header_key,
  362. $edit_identity, $hide_auth_header;
  363. /* if server var SERVER_NAME not available, use $domain */
  364. if(!sqGetGlobalVar('SERVER_NAME', $SERVER_NAME, SQ_SERVER)) {
  365. $SERVER_NAME = $domain;
  366. }
  367. sqGetGlobalVar('REMOTE_ADDR', $REMOTE_ADDR, SQ_SERVER);
  368. sqGetGlobalVar('REMOTE_PORT', $REMOTE_PORT, SQ_SERVER);
  369. sqGetGlobalVar('REMOTE_HOST', $REMOTE_HOST, SQ_SERVER);
  370. sqGetGlobalVar('HTTP_VIA', $HTTP_VIA, SQ_SERVER);
  371. sqGetGlobalVar('HTTP_X_FORWARDED_FOR', $HTTP_X_FORWARDED_FOR, SQ_SERVER);
  372. $rn = "\r\n";
  373. /* This creates an RFC 822 date */
  374. $date = date('D, j M Y H:i:s ', time()) . $this->timezone();
  375. /* Create a message-id */
  376. $message_id = '<' . $REMOTE_PORT . '.';
  377. if (isset($encode_header_key) && trim($encode_header_key)!='') {
  378. // use encrypted form of remote address
  379. $message_id.= OneTimePadEncrypt($this->ip2hex($REMOTE_ADDR),base64_encode($encode_header_key));
  380. } else {
  381. $message_id.= $REMOTE_ADDR;
  382. }
  383. $message_id .= '.' . time() . '.squirrel@' . $SERVER_NAME .'>';
  384. /* Make an RFC822 Received: line */
  385. if (isset($REMOTE_HOST)) {
  386. $received_from = "$REMOTE_HOST ([$REMOTE_ADDR])";
  387. } else {
  388. $received_from = $REMOTE_ADDR;
  389. }
  390. if (isset($HTTP_VIA) || isset ($HTTP_X_FORWARDED_FOR)) {
  391. if (!isset($HTTP_X_FORWARDED_FOR) || $HTTP_X_FORWARDED_FOR == '') {
  392. $HTTP_X_FORWARDED_FOR = 'unknown';
  393. }
  394. $received_from .= " (proxying for $HTTP_X_FORWARDED_FOR)";
  395. }
  396. $header = array();
  397. /**
  398. * SquirrelMail header
  399. *
  400. * This Received: header provides information that allows to track
  401. * user and machine that was used to send email. Don't remove it
  402. * unless you understand all possible forging issues or your
  403. * webmail installation does not prevent changes in user's email address.
  404. * See SquirrelMail bug tracker #847107 for more details about it.
  405. *
  406. * Add $hide_squirrelmail_header as a candidate for config_local.php
  407. * to allow completely hiding SquirrelMail participation in message
  408. * processing; This is dangerous, especially if users can modify their
  409. * account information, as it makes mapping a sent message back to the
  410. * original sender almost impossible.
  411. */
  412. $show_sm_header = ( defined('hide_squirrelmail_header') ? ! hide_squirrelmail_header : 1 );
  413. if ( $show_sm_header ) {
  414. if (isset($encode_header_key) &&
  415. trim($encode_header_key)!='') {
  416. // use encoded headers, if encryption key is set and not empty
  417. $header[] = 'X-Squirrel-UserHash: '.OneTimePadEncrypt($username,base64_encode($encode_header_key)).$rn;
  418. $header[] = 'X-Squirrel-FromHash: '.OneTimePadEncrypt($this->ip2hex($REMOTE_ADDR),base64_encode($encode_header_key)).$rn;
  419. if (isset($HTTP_X_FORWARDED_FOR))
  420. $header[] = 'X-Squirrel-ProxyHash:'.OneTimePadEncrypt($this->ip2hex($HTTP_X_FORWARDED_FOR),base64_encode($encode_header_key)).$rn;
  421. } else {
  422. // use default received headers
  423. $header[] = "Received: from $received_from" . $rn;
  424. if ($edit_identity || ! isset($hide_auth_header) || ! $hide_auth_header)
  425. $header[] = " (SquirrelMail authenticated user $username)" . $rn;
  426. $header[] = " by $SERVER_NAME with HTTP;" . $rn;
  427. $header[] = " $date" . $rn;
  428. }
  429. }
  430. /* Insert the rest of the header fields */
  431. $header[] = 'Message-ID: '. $message_id . $rn;
  432. if (is_object($reply_rfc822_header) &&
  433. isset($reply_rfc822_header->message_id) &&
  434. $reply_rfc822_header->message_id) {
  435. $rep_message_id = $reply_rfc822_header->message_id;
  436. // $this->strip_crlf($message_id);
  437. $header[] = 'In-Reply-To: '.$rep_message_id . $rn;
  438. $references = $this->calculate_references($reply_rfc822_header);
  439. $header[] = 'References: '.$references . $rn;
  440. }
  441. $header[] = "Date: $date" . $rn;
  442. $header[] = 'Subject: '.encodeHeader($rfc822_header->subject) . $rn;
  443. $header[] = 'From: '. $rfc822_header->getAddr_s('from',",$rn ",true) . $rn;
  444. // folding address list [From|To|Cc|Bcc] happens by using ",$rn<space>"
  445. // as delimiter
  446. // Do not use foldLine for that.
  447. // RFC2822 if from contains more then 1 address
  448. if (count($rfc822_header->from) > 1) {
  449. $header[] = 'Sender: '. $rfc822_header->getAddr_s('sender',',',true) . $rn;
  450. }
  451. if (count($rfc822_header->to)) {
  452. $header[] = 'To: '. $rfc822_header->getAddr_s('to',",$rn ",true) . $rn;
  453. }
  454. if (count($rfc822_header->cc)) {
  455. $header[] = 'Cc: '. $rfc822_header->getAddr_s('cc',",$rn ",true) . $rn;
  456. }
  457. if (count($rfc822_header->reply_to)) {
  458. $header[] = 'Reply-To: '. $rfc822_header->getAddr_s('reply_to',',',true) . $rn;
  459. }
  460. /* Sendmail should return true. Default = false */
  461. $bcc = $this->getBcc();
  462. if (count($rfc822_header->bcc)) {
  463. $s = 'Bcc: '. $rfc822_header->getAddr_s('bcc',",$rn ",true) . $rn;
  464. if (!$bcc) {
  465. $raw_length += strlen($s);
  466. } else {
  467. $header[] = $s;
  468. }
  469. }
  470. /* Identify SquirrelMail */
  471. $header[] = 'User-Agent: SquirrelMail/' . $version . $rn;
  472. /* Do the MIME-stuff */
  473. $header[] = 'MIME-Version: 1.0' . $rn;
  474. $contenttype = 'Content-Type: '. $rfc822_header->content_type->type0 .'/'.
  475. $rfc822_header->content_type->type1;
  476. if (count($rfc822_header->content_type->properties)) {
  477. foreach ($rfc822_header->content_type->properties as $k => $v) {
  478. if ($k && $v) {
  479. $contenttype .= ';' .$k.'='.$v;
  480. }
  481. }
  482. }
  483. $header[] = $contenttype . $rn;
  484. if ($encoding = $rfc822_header->encoding) {
  485. $header[] = 'Content-Transfer-Encoding: ' . $encoding . $rn;
  486. }
  487. if (isset($rfc822_header->dnt) && $rfc822_header->dnt) {
  488. $dnt = $rfc822_header->getAddr_s('dnt');
  489. /* Pegasus Mail */
  490. $header[] = 'X-Confirm-Reading-To: '.$dnt. $rn;
  491. /* RFC 2298 */
  492. $header[] = 'Disposition-Notification-To: '.$dnt. $rn;
  493. }
  494. if ($rfc822_header->priority) {
  495. switch($rfc822_header->priority)
  496. {
  497. case 1:
  498. $header[] = 'X-Priority: 1 (Highest)'.$rn;
  499. $header[] = 'Importance: High'. $rn; break;
  500. case 5:
  501. $header[] = 'X-Priority: 5 (Lowest)'.$rn;
  502. $header[] = 'Importance: Low'. $rn; break;
  503. default: break;
  504. }
  505. }
  506. /* Insert headers from the $more_headers array */
  507. if(count($rfc822_header->more_headers)) {
  508. reset($rfc822_header->more_headers);
  509. foreach ($rfc822_header->more_headers as $k => $v) {
  510. $header[] = $k.': '.$v .$rn;
  511. }
  512. }
  513. $cnt = count($header);
  514. $hdr_s = '';
  515. for ($i = 0 ; $i < $cnt ; $i++) {
  516. $sKey = substr($header[$i],0,strpos($header[$i],':'));
  517. switch ($sKey)
  518. {
  519. case 'Message-ID':
  520. case 'In-Reply_To':
  521. $hdr_s .= $header[$i];
  522. break;
  523. case 'References':
  524. $sRefs = substr($header[$i],12);
  525. $aRefs = explode(' ',$sRefs);
  526. $sLine = 'References:';
  527. foreach ($aRefs as $sReference) {
  528. if ( trim($sReference) == '' ) {
  529. /* Don't add spaces. */
  530. } elseif (strlen($sLine)+strlen($sReference) >76) {
  531. $hdr_s .= $sLine;
  532. $sLine = $rn . ' ' . $sReference;
  533. } else {
  534. $sLine .= ' '. $sReference;
  535. }
  536. }
  537. $hdr_s .= $sLine;
  538. break;
  539. case 'To':
  540. case 'Cc':
  541. case 'Bcc':
  542. case 'From':
  543. $hdr_s .= $header[$i];
  544. break;
  545. default: $hdr_s .= $this->foldLine($header[$i], 78, str_pad('',4)); break;
  546. }
  547. }
  548. $header = $hdr_s;
  549. $header .= $rn; /* One blank line to separate header and body */
  550. $raw_length += strlen($header);
  551. return $header;
  552. }
  553. /**
  554. * function foldLine - for cleanly folding of headerlines
  555. *
  556. * @param string $line
  557. * @param integer $length length to fold the line at
  558. * @param string $pre prefix the line with...
  559. *
  560. * @return string $line folded line with trailing CRLF
  561. */
  562. function foldLine($line, $length, $pre='') {
  563. $line = substr($line,0, -2);
  564. $length -= 2; /* do not fold between \r and \n */
  565. $cnt = strlen($line);
  566. if ($cnt > $length) { /* try folding */
  567. $fold_string = "\r\n " . $pre;
  568. $bFirstFold = false;
  569. $aFoldLine = array();
  570. while (strlen($line) > $length) {
  571. $fold = false;
  572. /* handle encoded parts */
  573. if (preg_match('/(=\?([^?]*)\?(Q|B)\?([^?]*)\?=)(\s+|.*)/Ui',$line,$regs)) {
  574. $fold_tmp = $regs[1];
  575. if (!trim($regs[5])) {
  576. $fold_tmp .= $regs[5];
  577. }
  578. $iPosEnc = strpos($line,$fold_tmp);
  579. $iLengthEnc = strlen($fold_tmp);
  580. $iPosEncEnd = $iPosEnc+$iLengthEnc;
  581. if ($iPosEnc < $length && (($iPosEncEnd) > $length)) {
  582. $fold = true;
  583. /* fold just before the start of the encoded string */
  584. if ($iPosEnc) {
  585. $aFoldLine[] = substr($line,0,$iPosEnc);
  586. }
  587. $line = substr($line,$iPosEnc);
  588. if (!$bFirstFold) {
  589. $bFirstFold = true;
  590. $length -= strlen($fold_string);
  591. }
  592. if ($iLengthEnc > $length) { /* place the encoded
  593. string on a separate line and do not fold inside it*/
  594. /* minimize foldstring */
  595. $fold_string = "\r\n ";
  596. $aFoldLine[] = substr($line,0,$iLengthEnc);
  597. $line = substr($line,$iLengthEnc);
  598. }
  599. } else if ($iPosEnc < $length) { /* the encoded string fits into the foldlength */
  600. /*remainder */
  601. $sLineRem = substr($line,$iPosEncEnd,$length - $iPosEncEnd);
  602. if (preg_match('/^(=\?([^?]*)\?(Q|B)\?([^?]*)\?=)(.*)/Ui',$sLineRem) || !preg_match('/[=,;\s]/',$sLineRem)) {
  603. /*impossible to fold clean in the next part -> fold after the enc string */
  604. $aFoldLine[] = substr($line,0,$iPosEncEnd);
  605. $line = substr($line,$iPosEncEnd);
  606. $fold = true;
  607. if (!$bFirstFold) {
  608. $bFirstFold = true;
  609. $length -= strlen($fold_string);
  610. }
  611. }
  612. }
  613. }
  614. if (!$fold) {
  615. $line_tmp = substr($line,0,$length);
  616. $iFoldPos = false;
  617. /* try to fold at logical places */
  618. switch (true)
  619. {
  620. case ($iFoldPos = strrpos($line_tmp,',')): break;
  621. case ($iFoldPos = strrpos($line_tmp,';')): break;
  622. case ($iFoldPos = strrpos($line_tmp,' ')): break;
  623. case ($iFoldPos = strrpos($line_tmp,'=')): break;
  624. default: break;
  625. }
  626. if (!$iFoldPos) { /* clean folding didn't work */
  627. $iFoldPos = $length;
  628. }
  629. $aFoldLine[] = substr($line,0,$iFoldPos+1);
  630. $line = substr($line,$iFoldPos+1);
  631. if (!$bFirstFold) {
  632. $bFirstFold = true;
  633. $length -= strlen($fold_string);
  634. }
  635. }
  636. }
  637. /*$reconstruct the line */
  638. if ($line) {
  639. $aFoldLine[] = $line;
  640. }
  641. $line = implode($fold_string,$aFoldLine);
  642. }
  643. return $line."\r\n";
  644. }
  645. /**
  646. * function mimeBoundary - calculates the mime boundary to use
  647. *
  648. * This function will generate a random mime boundary base part
  649. * for the message if the boundary has not already been set.
  650. *
  651. * @return string $mimeBoundaryString random mime boundary string
  652. */
  653. function mimeBoundary () {
  654. static $mimeBoundaryString;
  655. if ( !isset( $mimeBoundaryString ) ||
  656. $mimeBoundaryString == '') {
  657. $mimeBoundaryString = '----=_' . date( 'YmdHis' ) . '_' .
  658. mt_rand( 10000, 99999 );
  659. }
  660. return $mimeBoundaryString;
  661. }
  662. /**
  663. * function timezone - Time offset for correct timezone
  664. *
  665. * @return string $result with timezone and offset
  666. */
  667. function timezone () {
  668. global $invert_time;
  669. $diff_second = date('Z');
  670. if ($invert_time) {
  671. $diff_second = - $diff_second;
  672. }
  673. if ($diff_second > 0) {
  674. $sign = '+';
  675. } else {
  676. $sign = '-';
  677. }
  678. $diff_second = abs($diff_second);
  679. $diff_hour = floor ($diff_second / 3600);
  680. $diff_minute = floor (($diff_second-3600*$diff_hour) / 60);
  681. $zonename = '('.strftime('%Z').')';
  682. $result = sprintf ("%s%02d%02d %s", $sign, $diff_hour, $diff_minute,
  683. $zonename);
  684. return ($result);
  685. }
  686. /**
  687. * function calculate_references - calculate correct References string
  688. * Adds the current message ID, and makes sure it doesn't grow forever,
  689. * to that extent it drops message-ID's in a smart way until the string
  690. * length is under the recommended value of 1000 ("References: <986>\r\n").
  691. * It always keeps the first and the last three ID's.
  692. *
  693. * @param Rfc822Header $hdr message header to calculate from
  694. *
  695. * @return string $refer concatenated and trimmed References string
  696. */
  697. function calculate_references($hdr) {
  698. $aReferences = preg_split('/\s+/', $hdr->references);
  699. $message_id = $hdr->message_id;
  700. $in_reply_to = $hdr->in_reply_to;
  701. // if References already exists, add the current message ID at the end.
  702. // no References exists; if we know a IRT, add that aswell
  703. if (count($aReferences) == 0 && $in_reply_to) {
  704. $aReferences[] = $in_reply_to;
  705. }
  706. $aReferences[] = $message_id;
  707. // sanitize the array: trim whitespace, remove dupes
  708. array_walk($aReferences, 'sq_trim_value');
  709. $aReferences = array_unique($aReferences);
  710. while ( count($aReferences) > 4 && strlen(implode(' ', $aReferences)) >= 986 ) {
  711. $aReferences = array_merge(array_slice($aReferences,0,1),array_slice($aReferences,2));
  712. }
  713. return implode(' ', $aReferences);
  714. }
  715. /**
  716. * Converts ip address to hexadecimal string
  717. *
  718. * Function is used to convert ipv4 and ipv6 addresses to hex strings.
  719. * It removes all delimiter symbols from ip addresses, converts decimal
  720. * ipv4 numbers to hex and pads strings in order to present full length
  721. * address. ipv4 addresses are represented as 8 byte strings, ipv6 addresses
  722. * are represented as 32 byte string.
  723. *
  724. * If function fails to detect address format, it returns unprocessed string.
  725. * @param string $string ip address string
  726. * @return string processed ip address string
  727. * @since 1.5.1 and 1.4.5
  728. */
  729. function ip2hex($string) {
  730. if (preg_match("/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/",$string,$match)) {
  731. // ipv4 address
  732. $ret = str_pad(dechex($match[1]),2,'0',STR_PAD_LEFT)
  733. . str_pad(dechex($match[2]),2,'0',STR_PAD_LEFT)
  734. . str_pad(dechex($match[3]),2,'0',STR_PAD_LEFT)
  735. . str_pad(dechex($match[4]),2,'0',STR_PAD_LEFT);
  736. } elseif (preg_match("/^([0-9a-h]+)\:([0-9a-h]+)\:([0-9a-h]+)\:([0-9a-h]+)\:([0-9a-h]+)\:([0-9a-h]+)\:([0-9a-h]+)\:([0-9a-h]+)$/i",$string,$match)) {
  737. // full ipv6 address
  738. $ret = str_pad($match[1],4,'0',STR_PAD_LEFT)
  739. . str_pad($match[2],4,'0',STR_PAD_LEFT)
  740. . str_pad($match[3],4,'0',STR_PAD_LEFT)
  741. . str_pad($match[4],4,'0',STR_PAD_LEFT)
  742. . str_pad($match[5],4,'0',STR_PAD_LEFT)
  743. . str_pad($match[6],4,'0',STR_PAD_LEFT)
  744. . str_pad($match[7],4,'0',STR_PAD_LEFT)
  745. . str_pad($match[8],4,'0',STR_PAD_LEFT);
  746. } elseif (preg_match("/^\:\:([0-9a-h\:]+)$/i",$string,$match)) {
  747. // short ipv6 with all starting symbols nulled
  748. $aAddr=explode(':',$match[1]);
  749. $ret='';
  750. foreach ($aAddr as $addr) {
  751. $ret.=str_pad($addr,4,'0',STR_PAD_LEFT);
  752. }
  753. $ret=str_pad($ret,32,'0',STR_PAD_LEFT);
  754. } elseif (preg_match("/^([0-9a-h\:]+)::([0-9a-h\:]+)$/i",$string,$match)) {
  755. // short ipv6 with middle part nulled
  756. $aStart=explode(':',$match[1]);
  757. $sStart='';
  758. foreach($aStart as $addr) {
  759. $sStart.=str_pad($addr,4,'0',STR_PAD_LEFT);
  760. }
  761. $aEnd = explode(':',$match[2]);
  762. $sEnd='';
  763. foreach($aEnd as $addr) {
  764. $sEnd.=str_pad($addr,4,'0',STR_PAD_LEFT);
  765. }
  766. $ret = $sStart
  767. . str_pad('',(32 - strlen($sStart . $sEnd)),'0',STR_PAD_LEFT)
  768. . $sEnd;
  769. } else {
  770. // unknown addressing
  771. $ret = $string;
  772. }
  773. return $ret;
  774. }
  775. }