2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4 * SugarCRM Community Edition is a customer relationship management program developed by
5 * SugarCRM, Inc. Copyright (C) 2004-2012 SugarCRM Inc.
7 * This program is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU Affero General Public License version 3 as published by the
9 * Free Software Foundation with the addition of the following permission added
10 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
14 * This program is distributed in the hope that it will be useful, but WITHOUT
15 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
19 * You should have received a copy of the GNU Affero General Public License along with
20 * this program; if not, see http://www.gnu.org/licenses or write to the Free
21 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
24 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
27 * The interactive user interfaces in modified source and object code versions
28 * of this program must display Appropriate Legal Notices, as required under
29 * Section 5 of the GNU Affero General Public License version 3.
31 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32 * these Appropriate Legal Notices must retain the display of the "Powered by
33 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34 * technical reasons, the Appropriate Legal Notices must display the words
35 * "Powered by SugarCRM".
36 ********************************************************************************/
39 require_once('include/OutboundEmail/OutboundEmail.php');
41 function this_callback($str) {
42 foreach($str as $match) {
43 $ret .= chr(hexdec(str_replace("%","",$match)));
49 * Stub for certain interactions;
55 class InboundEmail extends SugarBean {
58 var $purifier; // HTMLPurifier object placeholder
66 var $modified_user_id;
69 var $modified_by_name;
89 var $outboundInstance; // id to outbound_email instance
91 var $iconFlagged = "F";
93 var $iconAnswered = "A";
94 var $iconDeleted = "del";
95 var $isAutoImport = false;
97 var $attachmentCount = 0;
98 var $tempAttachment = array();
99 var $unsafeChars = array("&", "!", "'", '"', '\\', '/', '<', '>', '|', '$',);
101 var $defaultSort = 'date';
102 var $defaultDirection = "DESC";
110 var $hrSortLocal = array(
111 'flagged' => 'flagged',
112 'status' => 'answered',
113 'from' => 'fromaddr',
114 'subject' => 'subject',
115 'date' => 'senddate',
118 // default attributes
119 var $transferEncoding = array(0 => '7BIT',
123 4 => 'QUOTED-PRINTABLE',
127 var $compoundMessageId; // concatenation of messageID and deliveredToEmail
128 var $serverConnectString;
129 var $disable_row_level_security = true;
130 var $InboundEmailCachePath;
131 var $InboundEmailCacheFile = 'InboundEmail.cache.php';
132 var $object_name = 'InboundEmail';
133 var $module_dir = 'InboundEmail';
134 var $table_name = 'inbound_email';
135 var $new_schema = true;
136 var $process_save_dates = true;
142 var $required_fields = array('name' => 'name',
143 'server_url' => 'server_url',
144 'mailbox' => 'mailbox',
148 var $imageTypes = array("JPG", "JPEG", "GIF", "PNG");
149 var $inlineImages = array(); // temporary space to store ID of inlined images
150 var $defaultEmailNumAutoreplies24Hours = 10;
151 var $maxEmailNumAutoreplies24Hours = 10;
152 // custom ListView attributes
153 var $mailbox_type_name;
154 var $global_personal_string;
155 // service attributes
160 var $keyForUsersDefaultIEAccount = 'defaultIEAccount';
161 // prefix to use when importing inlinge images in emails
167 function InboundEmail() {
168 $this->InboundEmailCachePath = sugar_cached('modules/InboundEmail');
169 $this->EmailCachePath = sugar_cached('modules/Emails');
171 if(function_exists("imap_timeout")) {
183 $this->smarty = new Sugar_Smarty();
184 $this->overview = new Overview();
185 $this->imagePrefix = "{$GLOBALS['sugar_config']['site_url']}/cache/images/";
191 * @return object Bean
193 function retrieve($id, $encode=true, $deleted=true) {
194 $ret = parent::retrieve($id,$encode,$deleted);
196 if (!is_null($ret)) {
197 $this->email_password = blowfishDecode(blowfishGetKey('InboundEmail'), $this->email_password);
198 $this->retrieveMailBoxFolders();
204 * wraps SugarBean->save()
205 * @param string ID of saved bean
207 function save($check_notify=false) {
208 // generate cache table for email 2.0
209 $multiDImArray = $this->generateMultiDimArrayFromFlatArray(explode(",", $this->mailbox), $this->retrieveDelimiter());
210 $raw = $this->generateFlatArrayFromMultiDimArray($multiDImArray, $this->retrieveDelimiter());
212 //_pp(explode(",", $this->mailbox));
214 $raw = $this->filterMailBoxFromRaw(explode(",", $this->mailbox), $raw);
215 $this->mailbox = implode(",", $raw);
216 if(!empty($this->email_password)) {
217 $this->email_password = blowfishEncode(blowfishGetKey('InboundEmail'), $this->email_password);
219 $ret = parent::save($check_notify);
223 function filterMailBoxFromRaw($mailboxArray, $rawArray) {
224 $newArray = array_intersect($mailboxArray, $rawArray);
230 * Overrides SugarBean's mark_deleted() to drop the related cache table
231 * @param string $id GUID of I-E instance
233 function mark_deleted($id) {
234 parent::mark_deleted($id);
235 $q = "update inbound_email set groupfolder_id = null WHERE id = '{$id}'";
236 $r = $this->db->query($q);
237 $this->deleteCache();
241 * Mark cached email answered (replied)
242 * @param string $mailid (uid for imap, message_id for pop3)
244 function mark_answered($mailid, $type = 'smtp') {
247 $q = "update email_cache set answered = 1 WHERE imap_uid = $mailid and ie_id = '{$this->id}'";
248 $this->db->query($q);
251 $q = "update email_cache set answered = 1 WHERE message_id = '$mailid' and ie_id = '{$this->id}'";
252 $this->db->query($q);
258 * Renames an IMAP mailbox
259 * @param string $newName
261 function renameFolder($oldName, $newName) {
262 //$this->mailbox = "INBOX"
263 $this->connectMailserver();
264 $oldConnect = $this->getConnectString('', $oldName);
265 $newConnect = $this->getConnectString('', $newName);
266 if(!imap_renamemailbox($this->conn, $oldConnect , $newConnect)) {
267 $GLOBALS['log']->debug("***INBOUNDEMAIL: failed to rename mailbox [ {$oldConnect} ] to [ {$newConnect} ]");
269 $this->mailbox = str_replace($oldName, $newName, $this->mailbox);
271 $sessionFoldersString = $this->getSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol);
272 $sessionFoldersString = str_replace($oldName, $newName, $sessionFoldersString);
273 $this->setSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol, $sessionFoldersString);
278 ///////////////////////////////////////////////////////////////////////////
279 //// CUSTOM LOGIC HOOKS
281 * Called from $this->getMessageText()
282 * Allows upgrade-safe custom processing of message text.
285 * 1. Create a directory path: ./custom/modules/InboundEmail if it does not exist
286 * 2. Create a file in the ./custom/InboundEmail/ folder called "getMessageText.php"
287 * 3. Define a function named "custom_getMessageText()" that takes a string as an argument and returns a string
289 * @param string $msgPart
292 function customGetMessageText($msgPart) {
293 $custom = "custom/modules/InboundEmail/getMessageText.php";
295 if(file_exists($custom)) {
296 include_once($custom);
298 if(function_exists("custom_getMessageText")) {
299 $GLOBALS['log']->debug("*** INBOUND EMAIL-CUSTOM_LOGIC: calling custom_getMessageText()");
300 $msgPart = custom_getMessageText($msgPart);
306 //// END CUSTOM LOGIC HOOKS
307 ///////////////////////////////////////////////////////////////////////////
311 ///////////////////////////////////////////////////////////////////////////
312 //// EMAIL 2.0 SPECIFIC
314 * constructs a nicely formatted version of raw source
315 * @param int $uid UID of email
318 function getFormattedRawSource($uid) {
321 //if($this->protocol == 'pop3') {
322 //$raw = $app_strings['LBL_EMAIL_VIEW_UNSUPPORTED'];
324 if (empty($this->id)) {
325 $q = "SELECT raw_source FROM emails_text WHERE email_id = '{$uid}'";
326 $r = $this->db->query($q);
327 $a = $this->db->fetchByAssoc($r);
329 $raw = $this->convertToUtf8($a['raw_source']);
331 $raw = $app_strings['LBL_EMAIL_ERROR_VIEW_RAW_SOURCE'];
334 if ($this->isPop3Protocol()) {
335 $uid = $this->getCorrectMessageNoForPop3($uid);
337 $raw = imap_fetchheader($this->conn, $uid, FT_UID+FT_PREFETCHTEXT);
338 $raw .= $this->convertToUtf8(imap_body($this->conn, $uid, FT_UID));
340 $raw = to_html($raw);
349 * helper method to convert text to utf-8 if necessary
351 * @param string $input text
352 * @return string output text
354 function convertToUtf8($input)
356 $charset = $GLOBALS['locale']->detectCharset($input, true);
358 // we haven't a clue due to missing package?, just return as itself
359 if ($charset === FALSE) {
363 // convert if we can or must
364 return $this->handleCharsetTranslation($input, $charset);
368 * constructs a nicely formatted version of email headers.
372 function getFormattedHeaders($uid) {
375 //if($this->protocol == 'pop3') {
376 // $header = $app_strings['LBL_EMAIL_VIEW_UNSUPPORTED'];
378 if ($this->isPop3Protocol()) {
379 $uid = $this->getCorrectMessageNoForPop3($uid);
381 $headers = imap_fetchheader($this->conn, $uid, FT_UID);
383 $lines = explode("\n", $headers);
385 $header = "<table cellspacing='0' cellpadding='2' border='0' width='100%'>";
387 foreach($lines as $line) {
391 $key = trim(substr($line, 0, strpos($line, ":")));
392 $key = strip_tags($key);
393 $value = trim(substr($line, strpos($line, ":") + 1));
394 $value = to_html($value);
397 $header .= "<td class='displayEmailLabel' NOWRAP><b>{$key}</b> </td>";
398 $header .= "<td class='displayEmailValueWhite'>{$value} </td>";
403 $header .= "</table>";
409 * Empties Trash folders
411 function emptyTrash() {
412 global $sugar_config;
414 $this->mailbox = $this->get_stored_options("trashFolder");
415 if (empty($this->mailbox)) {
416 $this->mailbox = 'INBOX.Trash';
418 $this->connectMailserver();
420 $uids = imap_search($this->conn, "ALL", SE_UID);
422 foreach($uids as $uid) {
423 if(!imap_delete($this->conn, $uid, FT_UID)) {
424 $lastError = imap_last_error();
425 $GLOBALS['log']->warn("INBOUNDEMAIL: emptyTrash() Could not delete message [ {$uid} ] from [ {$this->mailbox} ]. IMAP_ERROR [ {$lastError} ]");
429 // remove local cache file
430 $q = "DELETE FROM email_cache WHERE mbox = '{$this->mailbox}' AND ie_id = '{$this->id}'";
431 $r = $this->db->query($q);
435 * Fetches a timestamp
437 function getCacheTimestamp($mbox) {
438 $key = $this->db->quote("{$this->id}_{$mbox}");
439 $q = "SELECT ie_timestamp FROM inbound_email_cache_ts WHERE id = '{$key}'";
440 $r = $this->db->query($q);
441 $a = $this->db->fetchByAssoc($r);
446 return $a['ie_timestamp'];
450 * sets the cache timestamp
453 function setCacheTimestamp($mbox) {
454 $key = $this->db->quote("{$this->id}_{$mbox}");
456 $tsOld = $this->getCacheTimestamp($mbox);
459 $q = "INSERT INTO inbound_email_cache_ts (id, ie_timestamp) VALUES ('{$key}', {$ts})";
461 $q = "UPDATE inbound_email_cache_ts SET ie_timestamp = {$ts} WHERE id = '{$key}'";
464 $r = $this->db->query($q, true);
465 $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: setting timestamp query [ {$q} ]");
470 * Gets a count of all rows that are flagged seen = 0
471 * @param string $mbox
474 function getCacheUnreadCount($mbox) {
475 $q = "SELECT count(*) c FROM email_cache WHERE mbox = '{$mbox}' AND seen = 0 AND ie_id = '{$this->id}'";
476 $r = $this->db->query($q);
477 $a = $this->db->fetchByAssoc($r);
483 * Returns total number of emails for a mailbox
487 function getCacheCount($mbox) {
488 $q = "SELECT count(*) c FROM email_cache WHERE mbox = '{$mbox}' AND ie_id = '{$this->id}'";
489 $r = $this->db->query($q);
490 $a = $this->db->fetchByAssoc($r);
495 function getCacheUnread($mbox) {
496 $q = "SELECT count(*) c FROM email_cache WHERE mbox = '{$mbox}' AND ie_id = '{$this->id}' AND seen = '0'";
497 $r = $this->db->query($q);
498 $a = $this->db->fetchByAssoc($r);
505 * Deletes all rows for a given instance
507 function deleteCache() {
508 $q = "DELETE FROM email_cache WHERE ie_id = '{$this->id}'";
510 $GLOBALS['log']->info("INBOUNDEMAIL: deleting cache using query [ {$q} ]");
512 $r = $this->db->query($q);
516 * Deletes all the pop3 data which has been deleted from server
518 function deletePop3Cache() {
519 global $sugar_config;
520 $UIDLs = $this->pop3_getUIDL();
521 $cacheUIDLs = $this->pop3_getCacheUidls();
522 foreach($cacheUIDLs as $msgNo => $msgId) {
523 if (!in_array($msgId, $UIDLs)) {
524 $md5msgIds = md5($msgId);
525 $file = "{$this->EmailCachePath}/{$this->id}/messages/INBOX{$md5msgIds}.PHP";
526 $GLOBALS['log']->debug("INBOUNDEMAIL: deleting file [ {$file} ] ");
527 if(file_exists($file)) {
529 $GLOBALS['log']->debug("INBOUNDEMAIL: Could not delete [ {$file} ] ");
532 $q = "DELETE from email_cache where imap_uid = {$msgNo} AND msgno = {$msgNo} AND ie_id = '{$this->id}' AND message_id = '{$msgId}'";
533 $r = $this->db->query($q);
539 * Retrieves cached headers
542 function getCacheValueForUIDs($mbox, $UIDs) {
543 if (!is_array($UIDs) || empty($UIDs)) {
547 $q = "SELECT * FROM email_cache WHERE ie_id = '{$this->id}' AND mbox = '{$mbox}' AND ";
551 $slicedArray = array_slice($UIDs, $startIndex ,$endIndex);
552 $columnName = ($this->isPop3Protocol() ? "message_id" : "imap_uid");
554 'timestamp' => $this->getCacheTimestamp($mbox),
558 while (!empty($slicedArray)) {
559 $messageIdString = implode(',', $slicedArray);
560 $GLOBALS['log']->debug("sliced array = {$messageIdString}");
561 $extraWhere = "{$columnName} IN (";
563 foreach($slicedArray as $UID) {
565 $extraWhere = $extraWhere . ",";
568 $extraWhere = "{$extraWhere} '{$UID}'";
570 $newQuery = $q . $extraWhere . ")";
571 $r = $this->db->query($newQuery);
573 while($a = $this->db->fetchByAssoc($r)) {
574 if (isset($a['uid'])) {
575 if ($this->isPop3Protocol()) {
576 $ret['uids'][] = $a['message_id'];
578 $ret['uids'][] = $a['uid'];
582 $overview = new Overview();
584 foreach($a as $k => $v) {
588 $overview->imap_uid = $v;
589 if ($this->isPop3Protocol()) {
590 $overview->uid = $a['message_id'];
596 $overview->to = from_html($v);
600 $overview->from = from_html($v);
604 $overview->size = $v;
608 $overview->date = $v;
612 $overview->$k = from_html($v);
616 $ret['retArr'][] = $overview;
618 $startIndex = $startIndex + $endIndex;
619 $slicedArray = array_slice($UIDs, $startIndex ,$endIndex);
620 $messageIdString = implode(',', $slicedArray);
621 $GLOBALS['log']->debug("sliced array = {$messageIdString}");
627 * Retrieves cached headers
630 function getCacheValue($mbox, $limit = 20, $page = 1, $sort='', $direction='') {
631 // try optimizing this call as we don't want repeat queries
632 if(!empty($this->currentCache)) {
633 return $this->currentCache;
636 $sort = (empty($sort)) ? $this->defaultSort : $sort;
637 $direction = (empty($direction)) ? $this->defaultDirection : $direction;
638 $order = " ORDER BY {$this->hrSortLocal[$sort]} {$direction}";
640 $q = "SELECT * FROM email_cache WHERE ie_id = '{$this->id}' AND mbox = '{$mbox}' {$order}";
643 $start = ( $page - 1 ) * $limit;
644 $r = $this->db->limitQuery($q, $start, $limit);
646 $r = $this->db->query($q);
650 'timestamp' => $this->getCacheTimestamp($mbox),
655 while($a = $this->db->fetchByAssoc($r)) {
656 if (isset($a['uid'])) {
657 if ($this->isPop3Protocol()) {
658 $ret['uids'][] = $a['message_id'];
660 $ret['uids'][] = $a['uid'];
664 $overview = new Overview();
666 foreach($a as $k => $v) {
670 $overview->imap_uid = $v;
671 if ($this->isPop3Protocol()) {
672 $overview->uid = $a['message_id'];
678 $overview->to = from_html($v);
682 $overview->from = from_html($v);
686 $overview->size = $v;
690 $overview->date = $v;
694 $overview->$k = from_html($v);
698 $ret['retArr'][] = $overview;
701 $this->currentCache = $ret;
709 function setCacheValue($mbox, $insert, $update=array(), $remove=array()) {
716 // reset in-memory cache
717 $this->currentCache = null;
719 $table = 'email_cache';
720 $where = "WHERE ie_id = '{$this->id}' AND mbox = '{$mbox}'";
722 // handle removed rows
723 if(!empty($remove)) {
725 foreach($remove as $overview) {
726 if(!empty($removeIds)) {
730 $removeIds .= "'{$overview->imap_uid}'";
733 $q = "DELETE FROM {$table} {$where} AND imap_uid IN ({$removeIds})";
735 $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: delete query [ {$q} ]");
737 $r = $this->db->query($q, true, $q);
740 // handle insert rows
741 if(!empty($insert)) {
742 $q = "SELECT imap_uid FROM {$table} {$where}";
743 $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: filter UIDs query [ {$q} ]");
744 $r = $this->db->query($q);
747 while($a = $this->db->fetchByAssoc($r)) {
748 $uids[] = $a['imap_uid'];
750 $count = count($uids);
751 $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: found [ {$count} ] UIDs to filter against");
754 foreach($uids as $uid) {
759 $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: filter UIDs: [ {$tmp} ]");
763 foreach($this->overview->fieldDefs as $colDef) {
767 $cols .= "{$colDef['name']}";
769 foreach($insert as $overview) {
770 if(in_array($overview->imap_uid, $uids))
772 // fixing bug #49543: setting 'mbox' property for the following updating of other items in this box
773 if (!isset($overview->mbox))
775 $overview->mbox = $mbox;
777 $update[] = $overview;
783 foreach($this->overview->fieldDefs as $colDef) {
784 if(!empty($values)) {
788 // trim values for Oracle/MSSql
789 if( isset($colDef['len']) && !empty($colDef['len']) &&
790 isset($colDef['type']) && !empty($colDef['type']) &&
791 $colDef['type'] == 'varchar'
794 if (isset($overview->$colDef['name']))
796 $overview->$colDef['name'] = substr($overview->$colDef['name'], 0, $colDef['len']);
800 switch($colDef['name']) {
802 if(isset($overview->uid) && !empty($overview->uid)) {
803 $this->imap_uid = $overview->uid;
805 $values .= "'{$this->imap_uid}'";
809 $values .= "'{$this->id}'";
813 $values .= $this->db->quoted($overview->to);
817 $values .= $this->db->quoted($overview->from);
821 $values .= $this->db->quoted($overview->message_id);
825 $values .= $overview->size;
829 $conv=$timedate->fromString($overview->date);
831 $values .= $this->db->quoted($conv->asDb());
838 $values .= "'{$mbox}'";
842 $overview->$colDef['name'] = SugarCleaner::cleanHtml(from_html($overview->$colDef['name']));
843 $values .= $this->db->quoted($overview->$colDef['name']);
848 $q = "INSERT INTO {$table} ({$cols}) VALUES ({$values})";
849 $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: insert query [ {$q} ]");
850 $r = $this->db->query($q, true, $q);
854 // handle update rows
855 if(!empty($update)) {
857 foreach($this->overview->fieldDefs as $colDef) {
861 $cols .= "{$colDef['name']}";
864 foreach($update as $overview) {
865 $q = "UPDATE {$table} SET ";
868 foreach($this->overview->fieldDefs as $colDef) {
870 switch($colDef['name']) {
885 if (isset($overview->$colDef['name']))
887 $value = $this->db->quoted($overview->$colDef['name']);
891 $value = $this->db->quoted($value);
893 $set .= "{$colDef['name']} = " . $value;
898 $q .= $set . " WHERE ie_id = '{$this->id}' AND mbox = '{$overview->mbox}' AND imap_uid = '{$overview->imap_uid}'";
899 $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: update query [ {$q} ]");
900 $r = $this->db->query($q, true, $q);
907 * Opens a socket connection to the pop3 server
910 function pop3_open() {
911 if(!is_resource($this->pop3socket)) {
912 $GLOBALS['log']->info("*** INBOUNDEMAIL: opening socket connection");
913 $exServ = explode('::', $this->service);
914 $socket = ($exServ[2] == 'ssl') ? "ssl://" : "tcp://";
915 $socket .= $this->server_url;
916 $this->pop3socket = fsockopen($socket, $this->port);
918 $GLOBALS['log']->info("*** INBOUNDEMAIL: REUSING socket connection");
922 if(!is_resource($this->pop3socket)) {
923 $GLOBALS['log']->debug("*** INBOUNDEMAIL: unable to open socket connection");
928 $ret = trim(fgets($this->pop3socket, 1024));
929 $GLOBALS['log']->info("*** INBOUNDEMAIL: got socket connection [ {$ret} ]");
934 * Closes connections and runs clean-up routines
936 function pop3_cleanUp() {
937 $GLOBALS['log']->info("*** INBOUNDEMAIL: cleaning up socket connection");
938 fputs($this->pop3socket, "QUIT\r\n");
939 $buf = fgets($this->pop3socket, 1024);
940 fclose($this->pop3socket);
944 * sends a command down to the POP3 server
945 * @param string command
950 function pop3_sendCommand($command, $args='', $return=true) {
951 $command .= " {$args}";
952 $command = trim($command);
953 $GLOBALS['log']->info("*** INBOUNDEMAIL: pop3_sendCommand() SEND [ {$command} ]");
956 fputs($this->pop3socket, $command);
959 $ret = trim(fgets($this->pop3socket, 1024));
960 $GLOBALS['log']->info("*** INBOUNDEMAIL: pop3_sendCommand() RECEIVE [ {$ret} ]");
965 function getPop3NewMessagesToDownload() {
966 $pop3UIDL = $this->pop3_getUIDL();
967 $cacheUIDLs = $this->pop3_getCacheUidls();
968 // new email cache values we should deal with
969 $diff = array_diff_assoc($pop3UIDL, $cacheUIDLs);
970 // this is msgNo to UIDL array
971 $diff = $this->pop3_shiftCache($diff, $cacheUIDLs);
972 // get all the keys which are msgnos;
973 return array_keys($diff);
976 function getPop3NewMessagesToDownloadForCron() {
977 $pop3UIDL = $this->pop3_getUIDL();
978 $cacheUIDLs = $this->pop3_getCacheUidls();
979 // new email cache values we should deal with
980 $diff = array_diff_assoc($pop3UIDL, $cacheUIDLs);
981 // this is msgNo to UIDL array
982 $diff = $this->pop3_shiftCache($diff, $cacheUIDLs);
983 // insert data into email_cache
984 if ($this->groupfolder_id != null && $this->groupfolder_id != "" && $this->isPop3Protocol()) {
985 $searchResults = array_keys($diff);
986 $concatResults = implode(",", $searchResults);
987 if ($this->connectMailserver() == 'true') {
988 $fetchedOverviews = imap_fetch_overview($this->conn, $concatResults);
989 // clean up cache entry
990 foreach($fetchedOverviews as $k => $overview) {
991 $overview->message_id = trim($diff[$overview->msgno]);
992 $fetchedOverviews[$k] = $overview;
994 $this->updateOverviewCacheFile($fetchedOverviews);
1001 * This method returns all the UIDL for this account. This should be called if the protocol is pop3
1002 * @return array od messageno to UIDL array
1004 function pop3_getUIDL() {
1006 if($this->pop3_open()) {
1008 $this->pop3_sendCommand("USER", $this->email_user);
1009 $this->pop3_sendCommand("PASS", $this->email_password);
1012 $this->pop3_sendCommand("UIDL", '', false); // leave socket buffer alone until the while()
1013 fgets($this->pop3socket, 1024); // handle "OK+";
1018 if(is_resource($this->pop3socket)) {
1019 while(!feof($this->pop3socket)) {
1020 $buf = fgets($this->pop3socket, 1024); // 8kb max buffer - shouldn't be more than 80 chars via pop3...
1023 if(trim($buf) == '.') {
1024 $GLOBALS['log']->debug("*** GOT '.'");
1028 // format is [msgNo] [UIDL]
1029 $exUidl = explode(" ", $buf);
1030 $UIDLs[$exUidl[0]] = trim($exUidl[1]);
1033 $this->pop3_cleanUp();
1039 * Special handler for POP3 boxes. Standard IMAP commands are useless.
1040 * This will fetch only partial emails for POP3 and hence needs to be call again and again based on status it returns
1042 function pop3_checkPartialEmail($synch = false) {
1043 require_once('include/utils/array_utils.php');
1044 global $current_user;
1045 global $sugar_config;
1047 $cacheDataExists = false;
1050 $cacheFilePath = clean_path("{$this->EmailCachePath}/{$this->id}/folders/MsgNOToUIDLData.php");
1051 if(file_exists($cacheFilePath)) {
1052 $cacheDataExists = true;
1053 if($fh = @fopen($cacheFilePath, "rb")) {
1055 $chunksize = 1*(1024*1024); // how many bytes per chunk
1057 $buf = fgets($fh, $chunksize); // 8kb max buffer - shouldn't be more than 80 chars via pop3...
1058 $data = $data . $buf;
1062 $diff = unserialize($data);
1063 if (!empty($diff)) {
1064 if (count($diff)> 50) {
1065 $newDiff = array_slice($diff, 50, count($diff), true);
1069 $results = array_slice(array_keys($diff), 0 ,50);
1070 $data = serialize($newDiff);
1071 if($fh = @fopen($cacheFilePath, "w")) {
1078 if (!$cacheDataExists) {
1080 $this->deletePop3Cache();
1082 $UIDLs = $this->pop3_getUIDL();
1083 if(count($UIDLs) > 0) {
1085 $cacheUIDLs = $this->pop3_getCacheUidls();
1087 // new email cache values we should deal with
1088 $diff = array_diff_assoc($UIDLs, $cacheUIDLs);
1089 $diff = $this->pop3_shiftCache($diff, $cacheUIDLs);
1090 require_once('modules/Emails/EmailUI.php');
1091 EmailUI::preflightEmailCache("{$this->EmailCachePath}/{$this->id}");
1093 if (count($diff)> 50) {
1094 $newDiff = array_slice($diff, 50, count($diff), true);
1099 $results = array_slice(array_keys($diff), 0 ,50);
1100 $data = serialize($newDiff);
1101 if($fh = @fopen($cacheFilePath, "w")) {
1106 $GLOBALS['log']->debug("*** INBOUNDEMAIL: could not open socket connection to POP3 server");
1107 return "could not open socket connection to POP3 server";
1111 // build up msgNo request
1112 if(count($diff) > 0) {
1113 // remove dirty cache entries
1115 if (isset($_REQUEST['currentCount']) && $_REQUEST['currentCount'] > -1) {
1116 $startingNo = $_REQUEST['currentCount'];
1119 $this->mailbox = 'INBOX';
1120 $this->connectMailserver();
1121 //$searchResults = array_keys($diff);
1122 //$fetchedOverviews = array();
1123 //$chunkArraySerachResults = array_chunk($searchResults, 50);
1124 $concatResults = implode(",", $results);
1125 $GLOBALS['log']->info('$$$$ '.$concatResults);
1126 $GLOBALS['log']->info("[EMAIL] Start POP3 fetch overview on mailbox [{$this->mailbox}] for user [{$current_user->user_name}] on 50 data");
1127 $fetchedOverviews = imap_fetch_overview($this->conn, $concatResults);
1128 $GLOBALS['log']->info("[EMAIL] End POP3 fetch overview on mailbox [{$this->mailbox}] for user [{$current_user->user_name}] on "
1129 . sizeof($fetchedOverviews) . " data");
1131 // clean up cache entry
1132 foreach($fetchedOverviews as $k => $overview) {
1133 $overview->message_id = trim($diff[$overview->msgno]);
1134 $fetchedOverviews[$k] = $overview;
1137 $GLOBALS['log']->info("[EMAIL] Start updating overview cache for pop3 mailbox [{$this->mailbox}] for user [{$current_user->user_name}]");
1138 $this->updateOverviewCacheFile($fetchedOverviews);
1139 $GLOBALS['log']->info("[EMAIL] Start updating overview cache for pop3 mailbox [{$this->mailbox}] for user [{$current_user->user_name}]");
1140 return array('status' => "In Progress", 'mbox' => $this->mailbox, 'count'=> (count($results) + $startingNo), 'totalcount' => count($diff), 'ieid' => $this->id);
1142 unlink($cacheFilePath);
1143 return array('status' => "done");
1148 * Special handler for POP3 boxes. Standard IMAP commands are useless.
1150 function pop3_checkEmail() {
1151 if($this->pop3_open()) {
1153 $this->pop3_sendCommand("USER", $this->email_user);
1154 $this->pop3_sendCommand("PASS", $this->email_password);
1157 $this->pop3_sendCommand("UIDL", '', false); // leave socket buffer alone until the while()
1158 fgets($this->pop3socket, 1024); // handle "OK+";
1163 if(is_resource($this->pop3socket)) {
1164 while(!feof($this->pop3socket)) {
1165 $buf = fgets($this->pop3socket, 1024); // 8kb max buffer - shouldn't be more than 80 chars via pop3...
1168 if(trim($buf) == '.') {
1169 $GLOBALS['log']->debug("*** GOT '.'");
1173 // format is [msgNo] [UIDL]
1174 $exUidl = explode(" ", $buf);
1175 $UIDLs[$exUidl[0]] = trim($exUidl[1]);
1179 $this->pop3_cleanUp();
1182 $cacheUIDLs = $this->pop3_getCacheUidls();
1183 // _pp($UIDLs);_pp($cacheUIDLs);
1185 // new email cache values we should deal with
1186 $diff = array_diff_assoc($UIDLs, $cacheUIDLs);
1188 // remove dirty cache entries
1189 $diff = $this->pop3_shiftCache($diff, $cacheUIDLs);
1191 // build up msgNo request
1193 $this->mailbox = 'INBOX';
1194 $this->connectMailserver();
1195 $searchResults = array_keys($diff);
1196 $concatResults = implode(",", $searchResults);
1197 $fetchedOverviews = imap_fetch_overview($this->conn, $concatResults);
1199 // clean up cache entry
1200 foreach($fetchedOverviews as $k => $overview) {
1201 $overview->message_id = trim($diff[$overview->msgno]);
1202 $fetchedOverviews[$k] = $overview;
1205 $this->updateOverviewCacheFile($fetchedOverviews);
1208 $GLOBALS['log']->debug("*** INBOUNDEMAIL: could not open socket connection to POP3 server");
1214 * Iterates through msgno and message_id to remove dirty cache entries
1217 function pop3_shiftCache($diff, $cacheUIDLs) {
1220 $newArray = array();
1221 foreach($diff as $msgNo => $msgId) {
1222 if (in_array($msgId, $cacheUIDLs)) {
1223 $q1 = "UPDATE email_cache SET imap_uid = {$msgNo}, msgno = {$msgNo} WHERE ie_id = '{$this->id}' AND message_id = '{$msgId}'";
1224 $this->db->query($q1);
1226 $newArray[$msgNo] = $msgId;
1231 foreach($diff as $msgNo => $msgId) {
1232 if(!empty($msgNos)) {
1235 if(!empty($msgIds)) {
1240 $msgIds .= "'{$msgId}'";
1243 if(!empty($msgNos)) {
1244 $q1 = "DELETE FROM email_cache WHERE ie_id = '{$this->id}' AND msgno IN ({$msgNos})";
1245 $this->db->query($q1);
1247 if(!empty($msgIds)) {
1248 $q2 = "DELETE FROM email_cache WHERE ie_id = '{$this->id}' AND message_id IN ({$msgIds})";
1249 $this->db->query($q2);
1255 * retrieves cached uidl values.
1256 * When dealing with POP3 accounts, the message_id column in email_cache will contain the UIDL.
1259 function pop3_getCacheUidls() {
1260 $q = "SELECT msgno, message_id FROM email_cache WHERE ie_id = '{$this->id}'";
1261 $r = $this->db->query($q);
1264 while($a = $this->db->fetchByAssoc($r)) {
1265 $ret[$a['msgno']] = $a['message_id'];
1272 * This function is used by cron job for group mailbox without group folder
1273 * @param string $msgno for pop
1274 * @param string $uid for imap
1276 function getMessagesInEmailCache($msgno, $uid) {
1277 $fetchedOverviews = array();
1278 if ($this->isPop3Protocol()) {
1279 $fetchedOverviews = imap_fetch_overview($this->conn, $msgno);
1280 foreach($fetchedOverviews as $k => $overview) {
1281 $overview->message_id = $uid;
1282 $fetchedOverviews[$k] = $overview;
1285 $fetchedOverviews = imap_fetch_overview($this->conn, $uid, FT_UID);
1287 $this->updateOverviewCacheFile($fetchedOverviews);
1292 * Checks email (local caching too) for one mailbox
1293 * @param string $mailbox IMAP Mailbox path
1294 * @param bool $prefetch Flag to prefetch email body on check
1296 function checkEmailOneMailbox($mailbox, $prefetch=true, $synchronize=false) {
1297 global $sugar_config;
1298 global $current_user;
1299 global $app_strings;
1303 $GLOBALS['log']->info("INBOUNDEMAIL: checking mailbox [ {$mailbox} ]");
1304 $this->mailbox = $mailbox;
1305 $this->connectMailserver();
1308 $shouldProcessRules = true;
1310 $timestamp = $this->getCacheTimestamp($mailbox);
1312 if($timestamp > 0) {
1313 $checkTime = date('r', $timestamp);
1316 /* first time through, process ALL emails */
1317 if(empty($checkTime) || $synchronize) {
1318 // do not process rules for the first time or sunchronize
1319 $shouldProcessRules = false;
1320 $criteria = "ALL UNDELETED";
1321 $prefetch = false; // do NOT prefetch emails on a brand new account - timeouts happen.
1322 $GLOBALS['log']->info("INBOUNDEMAIL: new account detected - not prefetching email bodies.");
1324 $criteria = "SINCE \"{$checkTime}\" UNDELETED"; // not using UNSEEN
1326 $this->setCacheTimestamp($mailbox);
1327 $GLOBALS['log']->info("[EMAIL] Performing IMAP search using criteria [{$criteria}] on mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1328 $searchResults = imap_search($this->conn, $criteria, SE_UID);
1329 $GLOBALS['log']->info("[EMAIL] Done IMAP search on mailbox [{$mailbox}] for user [{$current_user->user_name}]. Result count = ".count($searchResults));
1331 if(!empty($searchResults)) {
1333 $concatResults = implode(",", $searchResults);
1334 $GLOBALS['log']->info("[EMAIL] Start IMAP fetch overview on mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1335 $fetchedOverview = imap_fetch_overview($this->conn, $concatResults, FT_UID);
1336 $GLOBALS['log']->info("[EMAIL] Done IMAP fetch overview on mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1338 $GLOBALS['log']->info("[EMAIL] Start updating overview cache for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1339 $this->updateOverviewCacheFile($fetchedOverview);
1340 $GLOBALS['log']->info("[EMAIL] Done updating overview cache for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1343 if($prefetch == true) {
1344 $GLOBALS['log']->info("[EMAIL] Start fetching emails for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1345 if(!$this->fetchCheckedEmails($fetchedOverview))
1349 $GLOBALS['log']->info("[EMAIL] Done fetching emails for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1352 $GLOBALS['log']->info("INBOUNDEMAIL: no results for mailbox [ {$mailbox} ]");
1357 * To handle the use case where an external client is also connected, deleting emails, we need to clear our
1358 * local cache of all emails with the "DELETED" flag
1360 $criteria = 'DELETED';
1361 $criteria .= (!empty($checkTime)) ? " SINCE \"{$checkTime}\"" : "";
1362 $GLOBALS['log']->info("INBOUNDEMAIL: checking for deleted emails using [ {$criteria} ]");
1364 $trashFolder = $this->get_stored_options("trashFolder");
1365 if (empty($trashFolder)) {
1366 $trashFolder = "INBOX.Trash";
1369 if($this->mailbox != $trashFolder) {
1370 $searchResults = imap_search($this->conn, $criteria, SE_UID);
1371 if(!empty($searchResults)) {
1372 $uids = implode($app_strings['LBL_EMAIL_DELIMITER'], $searchResults);
1373 $GLOBALS['log']->info("INBOUNDEMAIL: removing UIDs found deleted [ {$uids} ]");
1374 $this->getOverviewsFromCacheFile($uids, $mailbox, true);
1381 * Checks email (local caching too) for one mailbox
1382 * @param string $mailbox IMAP Mailbox path
1383 * @param bool $prefetch Flag to prefetch email body on check
1385 function checkEmailOneMailboxPartial($mailbox, $prefetch=true, $synchronize=false, $start = 0, $max = -1) {
1386 global $sugar_config;
1387 global $current_user;
1388 global $app_strings;
1390 $GLOBALS['log']->info("INBOUNDEMAIL: checking mailbox [ {$mailbox} ]");
1391 $this->mailbox = $mailbox;
1392 $this->connectMailserver();
1395 $shouldProcessRules = true;
1397 $timestamp = $this->getCacheTimestamp($mailbox);
1399 if($timestamp > 0) {
1400 $checkTime = date('r', $timestamp);
1403 /* first time through, process ALL emails */
1404 if(empty($checkTime) || $synchronize) {
1405 // do not process rules for the first time or sunchronize
1406 $shouldProcessRules = false;
1407 $criteria = "ALL UNDELETED";
1408 $prefetch = false; // do NOT prefetch emails on a brand new account - timeouts happen.
1409 $GLOBALS['log']->info("INBOUNDEMAIL: new account detected - not prefetching email bodies.");
1411 $criteria = "SINCE \"{$checkTime}\" UNDELETED"; // not using UNSEEN
1413 $this->setCacheTimestamp($mailbox);
1414 $GLOBALS['log']->info("[EMAIL] Performing IMAP search using criteria [{$criteria}] on mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1415 $searchResults = $this->getCachedIMAPSearch($criteria);
1417 if(!empty($searchResults)) {
1419 $total = sizeof($searchResults);
1420 $searchResults = array_slice($searchResults, $start, $max);
1422 $GLOBALS['log']->info("INBOUNDEMAIL: there are $total messages in [{$mailbox}], we are on $start");
1423 $GLOBALS['log']->info("INBOUNDEMAIL: getting the next " . sizeof($searchResults) . " messages");
1424 $concatResults = implode(",", $searchResults);
1425 $GLOBALS['log']->info("INBOUNDEMAIL: Start IMAP fetch overview on mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1426 $fetchedOverview = imap_fetch_overview($this->conn, $concatResults, FT_UID);
1427 $GLOBALS['log']->info("INBOUNDEMAIL: Done IMAP fetch overview on mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1429 $GLOBALS['log']->info("INBOUNDEMAIL: Start updating overview cache for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1430 $this->updateOverviewCacheFile($fetchedOverview);
1431 $GLOBALS['log']->info("INBOUNDEMAIL: Done updating overview cache for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1434 if($prefetch == true) {
1435 $GLOBALS['log']->info("INBOUNDEMAIL: Start fetching emails for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1436 $this->fetchCheckedEmails($fetchedOverview);
1437 $GLOBALS['log']->info("INBOUNDEMAIL: Done fetching emails for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1439 $status = ($total > $start + sizeof($searchResults)) ? 'continue' : 'done';
1440 $ret = array('status' => $status, 'count' => $start + sizeof($searchResults), 'mbox' => $mailbox, 'totalcount' => $total);
1441 $GLOBALS['log']->info("INBOUNDEMAIL: $status : Downloaded " . $start + sizeof($searchResults) . "messages of $total");
1444 $GLOBALS['log']->info("INBOUNDEMAIL: no results for mailbox [ {$mailbox} ]");
1445 $ret = array('status' =>'done');
1448 if ($ret['status'] == 'done') {
1449 //Remove the cached search if we are done with this mailbox
1450 $cacheFilePath = clean_path("{$this->EmailCachePath}/{$this->id}/folders/SearchData.php");
1451 unlink($cacheFilePath);
1453 * To handle the use case where an external client is also connected, deleting emails, we need to clear our
1454 * local cache of all emails with the "DELETED" flag
1456 $criteria = 'DELETED';
1457 $criteria .= (!empty($checkTime)) ? " SINCE \"{$checkTime}\"" : "";
1458 $GLOBALS['log']->info("INBOUNDEMAIL: checking for deleted emails using [ {$criteria} ]");
1460 $trashFolder = $this->get_stored_options("trashFolder");
1461 if (empty($trashFolder)) {
1462 $trashFolder = "INBOX.Trash";
1465 if($this->mailbox != $trashFolder) {
1466 $searchResults = imap_search($this->conn, $criteria, SE_UID);
1467 if(!empty($searchResults)) {
1468 $uids = implode($app_strings['LBL_EMAIL_DELIMITER'], $searchResults);
1469 $GLOBALS['log']->info("INBOUNDEMAIL: removing UIDs found deleted [ {$uids} ]");
1470 $this->getOverviewsFromCacheFile($uids, $mailbox, true);
1477 function getCachedIMAPSearch($criteria) {
1478 global $current_user;
1479 global $sugar_config;
1481 $cacheDataExists = false;
1484 $cacheFolderPath = clean_path("{$this->EmailCachePath}/{$this->id}/folders");
1485 if (!file_exists($cacheFolderPath)) {
1486 mkdir_recursive($cacheFolderPath);
1488 $cacheFilePath = $cacheFolderPath . '/SearchData.php';
1489 $GLOBALS['log']->info("INBOUNDEMAIL: Cache path is $cacheFilePath");
1490 if(file_exists($cacheFilePath)) {
1491 $cacheDataExists = true;
1492 if($fh = @fopen($cacheFilePath, "rb")) {
1494 $chunksize = 1*(1024*1024); // how many bytes per chunk
1496 $buf = fgets($fh, $chunksize); // 8kb max buffer - shouldn't be more than 80 chars via pop3...
1497 $data = $data . $buf;
1501 $results = unserialize($data);
1504 if (!$cacheDataExists) {
1505 $searchResults = imap_search($this->conn, $criteria, SE_UID);
1506 if(count($searchResults) > 0) {
1507 $results = $searchResults;
1508 $data = serialize($searchResults);
1509 if($fh = @fopen($cacheFilePath, "w")) {
1518 function checkEmailIMAPPartial($prefetch=true, $synch = false) {
1519 $GLOBALS['log']->info("*****************INBOUNDEMAIL: at IMAP check partial");
1520 global $sugar_config;
1521 $result = $this->connectMailserver();
1522 if ($result == 'false')
1525 'status' => 'error',
1526 'message' => 'Email server is down'
1529 $mailboxes = $this->getMailboxes(true);
1530 if (!in_array('INBOX', $mailboxes)) {
1531 $mailboxes[] = 'INBOX';
1534 if (isset($_REQUEST['mbox']) && !empty($_REQUEST['mbox']) && isset($_REQUEST['currentCount'])) {
1535 $GLOBALS['log']->info("INBOUNDEMAIL: Picking up from where we left off");
1536 $mbox = $_REQUEST['mbox'];
1537 $count = $_REQUEST['currentCount'];
1540 $GLOBALS['log']->info("INBOUNDEMAIL: Cleaning out the cache");
1541 $this->cleanOutCache();
1543 $mbox = $mailboxes[0];
1546 $GLOBALS['log']->info("INBOUNDEMAIL:found " . sizeof($mailboxes) . " Mailboxes");
1547 $index = array_search($mbox, $mailboxes) + 1;
1548 $ret = $this->checkEmailOneMailboxPartial($mbox, $prefetch, $synch, $count, 100);
1549 while($ret['status'] == 'done' && $index < sizeof($mailboxes)) {
1550 if ($ret['count'] > 100) {
1551 $ret['mbox'] = $mailboxes[$index];
1552 $ret['status'] = 'continue';
1555 $GLOBALS['log']->info("INBOUNDEMAIL: checking account [ $index => $mbox : $count]");
1556 $mbox = $mailboxes[$index];
1557 $ret = $this->checkEmailOneMailboxPartial($mbox, $prefetch, $synch, 0, 100);
1564 function checkEmail2_meta() {
1565 global $sugar_config;
1567 $this->connectMailserver();
1568 $mailboxes = $this->getMailboxes(true);
1569 $mailboxes[] = 'INBOX';
1572 $GLOBALS['log']->info("INBOUNDEMAIL: checking account [ {$this->name} ]");
1574 $mailboxes_meta = array();
1575 foreach($mailboxes as $mailbox) {
1576 $mailboxes_meta[$mailbox] = $this->getMailboxProcessCount($mailbox);
1580 $ret['mailboxes'] = $mailboxes_meta;
1582 foreach($mailboxes_meta as $count) {
1583 $ret['processCount'] += $count;
1588 function getMailboxProcessCount($mailbox) {
1589 global $sugar_config;
1591 $GLOBALS['log']->info("INBOUNDEMAIL: checking mailbox [ {$mailbox} ]");
1592 $this->mailbox = $mailbox;
1593 $this->connectMailserver();
1595 $timestamp = $this->getCacheTimestamp($mailbox);
1598 if($timestamp > 0) {
1599 $checkTime = date('r', $timestamp);
1602 /* first time through, process ALL emails */
1603 if(empty($checkTime)) {
1604 $criteria = "ALL UNDELETED";
1605 $prefetch = false; // do NOT prefetch emails on a brand new account - timeouts happen.
1606 $GLOBALS['log']->info("INBOUNDEMAIL: new account detected - not prefetching email bodies.");
1608 $criteria = "SINCE \"{$checkTime}\" UNDELETED"; // not using UNSEEN
1611 $GLOBALS['log']->info("INBOUNDEMAIL: using [ {$criteria} ]");
1612 $searchResults = imap_search($this->conn, $criteria, SE_UID);
1614 if(!empty($searchResults)) {
1615 $concatResults = implode(",", $searchResults);
1617 $GLOBALS['log']->info("INBOUNDEMAIL: no results for mailbox [ {$mailbox} ]");
1620 if(empty($searchResults)) {
1624 return count($searchResults);
1630 function checkEmail($prefetch=true, $synch = false) {
1631 global $sugar_config;
1633 if($this->protocol == 'pop3') {
1634 $this->pop3_checkEmail();
1636 $this->connectMailserver();
1637 $mailboxes = $this->getMailboxes(true);
1640 $GLOBALS['log']->info("INBOUNDEMAIL: checking account [ {$this->name} ]");
1642 foreach($mailboxes as $mailbox) {
1643 $this->checkEmailOneMailbox($mailbox, $prefetch, $synch);
1649 * full synchronization
1651 function syncEmail() {
1652 global $sugar_config;
1653 global $current_user;
1655 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
1657 if(empty($showFolders)) {
1658 $showFolders = array();
1661 $email = new Email();
1662 $email->email2init();
1664 // personal accounts
1665 if($current_user->hasPersonalEmail()) {
1666 $personals = $this->retrieveByGroupId($current_user->id);
1668 foreach($personals as $personalAccount) {
1669 if(in_array($personalAccount->id, $showFolders)) {
1670 $personalAccount->email = $email;
1671 if ($personalAccount->isPop3Protocol()) {
1672 $personalAccount->deletePop3Cache();
1675 $personalAccount->cleanOutCache();
1676 $personalAccount->connectMailserver();
1677 $mailboxes = $personalAccount->getMailboxes(true);
1678 $mailboxes[] = 'INBOX';
1681 $GLOBALS['log']->info("[EMAIL] Start checking account [{$personalAccount->name}] for user [{$current_user->user_name}]");
1683 foreach($mailboxes as $mailbox) {
1684 $GLOBALS['log']->info("[EMAIL] Start checking mailbox [{$mailbox}] of account [{$personalAccount->name}] for user [{$current_user->user_name}]");
1685 $personalAccount->checkEmailOneMailbox($mailbox, false, true);
1686 $GLOBALS['log']->info("[EMAIL] Done checking mailbox [{$mailbox}] of account [{$personalAccount->name}] for user [{$current_user->user_name}]");
1688 $GLOBALS['log']->info("[EMAIL] Done checking account [{$personalAccount->name}] for user [{$current_user->user_name}]");
1694 $beans = $this->retrieveAllByGroupId($current_user->id, false);
1695 foreach($beans as $k => $groupAccount) {
1696 if(in_array($groupAccount->id, $showFolders)) {
1697 $groupAccount->email = $email;
1698 $groupAccount->cleanOutCache();
1699 $groupAccount->connectMailserver();
1700 $mailboxes = $groupAccount->getMailboxes(true);
1701 $mailboxes[] = 'INBOX';
1704 $GLOBALS['log']->info("INBOUNDEMAIL: checking account [ {$groupAccount->name} ]");
1706 foreach($mailboxes as $mailbox) {
1707 $groupAccount->checkEmailOneMailbox($mailbox, false, true);
1715 * Deletes cached messages when moving from folder to folder
1716 * @param string $uids
1717 * @param string $fromFolder
1718 * @param string $toFolder
1720 function deleteCachedMessages($uids, $fromFolder) {
1721 global $sugar_config;
1723 if(!isset($this->email) && !isset($this->email->et)) {
1724 $this->email = new Email();
1725 $this->email->email2init();
1728 $uids = $this->email->et->_cleanUIDList($uids);
1730 foreach($uids as $uid) {
1731 $file = "{$this->EmailCachePath}/{$this->id}/messages/{$fromFolder}{$uid}.php";
1733 if(file_exists($file)) {
1734 if(!unlink($file)) {
1735 $GLOBALS['log']->debug("INBOUNDEMAIL: Could not delete [ {$file} ]");
1742 * similar to imap_fetch_overview, but it gets overviews from a local cache
1744 * @param string $uids UIDs in comma-delimited format
1745 * @param string $mailbox The mailbox in focus, will default to $this->mailbox
1746 * @param bool $remove Default false
1749 function getOverviewsFromCacheFile($uids, $mailbox='', $remove=false) {
1750 global $app_strings;
1751 if(!isset($this->email) && !isset($this->email->et)) {
1752 $this->email = new Email();
1753 $this->email->email2init();
1756 $uids = $this->email->et->_cleanUIDList($uids, true);
1758 // load current cache file
1759 $mailbox = empty($mailbox) ? $this->mailbox : $mailbox;
1760 $cacheValue = $this->getCacheValue($mailbox);
1764 $exUids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
1765 foreach($exUids as $k => $uid) {
1766 $exUids[$k] = trim($uid);
1769 // fill $ret will requested $uids
1770 foreach($cacheValue['retArr'] as $k => $overview) {
1771 if(in_array($overview->imap_uid, $exUids)) {
1776 // remove requested $uids from current cache file (move_mail() type action)
1778 $this->setCacheValue($mailbox, array(), array(), $ret);
1784 * merges new info with the saved cached file
1785 * @param array $array Array of email Overviews
1786 * @param string $type 'append' or 'remove'
1787 * @param string $mailbox Target mailbox if not current assigned
1789 function updateOverviewCacheFile($array, $type='append', $mailbox='') {
1790 $mailbox = empty($mailbox) ? $this->mailbox : $mailbox;
1792 $cacheValue = $this->getCacheValue($mailbox);
1793 $uids = $cacheValue['uids'];
1795 $updateRows = array();
1796 $insertRows = array();
1797 $removeRows = array();
1800 if($type == 'append') { // append
1801 /* we are adding overviews to the cache file */
1802 foreach($array as $overview) {
1803 if(isset($overview->uid)) {
1804 $overview->imap_uid = $overview->uid; // coming from imap_fetch_overview() call
1807 if(!in_array($overview->imap_uid, $uids)) {
1808 $insertRows[] = $overview;
1812 $updatedCacheOverviews = array();
1813 // compare against generated list
1814 /* we are removing overviews from the cache file */
1815 foreach($cacheValue['retArr'] as $cacheOverview) {
1816 if(!in_array($cacheOverview->imap_uid, $uids)) {
1817 $insertRows[] = $cacheOverview;
1819 $removeRows[] = $cacheOverview;
1823 $cacheValue['retArr'] = $updatedCacheOverviews;
1826 $this->setCacheValue($mailbox, $insertRows, $updateRows, $removeRows);
1830 * Check email prefetches email bodies for quicker display
1831 * @param array array of fetched overviews
1833 function fetchCheckedEmails($fetchedOverviews) {
1834 global $sugar_config;
1836 if(is_array($fetchedOverviews) && !empty($fetchedOverviews)) {
1837 foreach($fetchedOverviews as $overview) {
1838 if($overview->size < 10000) {
1840 $uid = $overview->imap_uid;
1843 $file = "{$this->mailbox}{$uid}.php";
1844 $cacheFile = clean_path("{$this->EmailCachePath}/{$this->id}/messages/{$file}");
1846 if(!file_exists($cacheFile)) {
1847 $GLOBALS['log']->info("INBOUNDEMAIL: Prefetching email [ {$file} ]");
1848 $this->setEmailForDisplay($uid);
1849 $out = $this->displayOneEmail($uid, $this->mailbox);
1850 $this->email->et->writeCacheFile('out', $out, $this->id, 'messages', "{$this->mailbox}{$uid}.php");
1852 $GLOBALS['log']->debug("INBOUNDEMAIL: Trying to prefetch an email we already fetched! [ {$cacheFile} ]");
1855 $GLOBALS['log']->debug("*** INBOUNDEMAIL: prefetch has a message with no UID");
1859 $GLOBALS['log']->debug("INBOUNDEMAIL: skipping email prefetch - size too large [ {$overview->size} ]");
1867 * Sets flags on emails. Assumes that connection is live, correct folder is
1869 * @param string $uids Sequence of UIDs, comma separated
1870 * @param string $type Flag to mark
1872 function markEmails($uids, $type) {
1875 $result = imap_clearflag_full($this->conn, $uids, '\\SEEN', ST_UID);
1878 $result = imap_setflag_full($this->conn, $uids, '\\SEEN', ST_UID);
1881 $result = imap_setflag_full($this->conn, $uids, '\\FLAGGED', ST_UID);
1884 $result = imap_clearflag_full($this->conn, $uids, '\\FLAGGED', ST_UID);
1887 $result = imap_setflag_full($this->conn, $uids, '\\Answered', ST_UID);
1891 //// END EMAIL 2.0 SPECIFIC
1892 ///////////////////////////////////////////////////////////////////////////
1896 ///////////////////////////////////////////////////////////////////////////
1897 //// SERVER MANIPULATION METHODS
1899 * Deletes the specified folder
1900 * @param string $mbox "::" delimited IMAP mailbox path, ie, INBOX.saved.stuff
1903 function deleteFolder($mbox) {
1904 $returnArray = array();
1905 if ($this->getCacheCount($mbox) > 0) {
1906 $returnArray['status'] = false;
1907 $returnArray['errorMessage'] = "Can not delete {$mbox} as it has emails.";
1908 return $returnArray;
1910 $connectString = $this->getConnectString('', $mbox);
1911 //Remove Folder cache
1912 global $sugar_config;
1913 unlink("{$this->EmailCachePath}/{$this->id}/folders/folders.php");
1915 if(imap_unsubscribe($this->conn, imap_utf7_encode($connectString))) {
1916 if(imap_deletemailbox($this->conn, $connectString)) {
1917 $this->mailbox = str_replace(("," . $mbox), "", $this->mailbox);
1919 $sessionFoldersString = $this->getSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol);
1920 $sessionFoldersString = str_replace(("," . $mbox), "", $sessionFoldersString);
1921 $this->setSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol, $sessionFoldersString);
1922 $returnArray['status'] = true;
1923 return $returnArray;
1925 $GLOBALS['log']->error("*** ERROR: EMAIL2.0 - could not delete IMAP mailbox with path: [ {$connectString} ]");
1926 $returnArray['status'] = false;
1927 $returnArray['errorMessage'] = "NOOP: could not delete folder: {$connectString}";
1928 return $returnArray;
1932 $GLOBALS['log']->error("*** ERROR: EMAIL2.0 - could not unsubscribe from folder, {$connectString} before deletion.");
1933 $returnArray['status'] = false;
1934 $returnArray['errorMessage'] = "NOOP: could not unsubscribe from folder, {$connectString} before deletion.";
1935 return $returnArray;
1941 * @param string $name Name of new IMAP mailbox
1942 * @param string $mbox "::" delimited IMAP mailbox path, ie, INBOX.saved.stuff
1943 * @return bool True on success
1945 function saveNewFolder($name, $mbox) {
1946 global $sugar_config;
1947 //Remove Folder cache
1948 global $sugar_config;
1949 //unlink("{$this->EmailCachePath}/{$this->id}/folders/folders.php");
1951 //$mboxImap = $this->getImapMboxFromSugarProprietary($mbox);
1952 $delimiter = $this->get_stored_options('folderDelimiter');
1957 $newFolder = $mbox . $delimiter . $name;
1958 $mbox .= $delimiter.str_replace($delimiter, "_", $name);
1959 $connectString = $this->getConnectString('', $mbox);
1961 if(imap_createmailbox($this->conn, imap_utf7_encode($connectString))) {
1962 imap_subscribe($this->conn, imap_utf7_encode($connectString));
1963 $status = imap_status($this->conn, str_replace("{$delimiter}{$name}","",$connectString), SA_ALL);
1964 $this->mailbox = $this->mailbox . "," . $newFolder;
1966 $sessionFoldersString = $this->getSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol);
1967 $sessionFoldersString = $sessionFoldersString . "," . $newFolder;
1968 $this->setSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol, $sessionFoldersString);
1970 echo json_encode($status);
1973 echo "NOOP: could not create folder";
1974 $GLOBALS['log']->error("*** ERROR: EMAIL2.0 - could not create IMAP mailbox with path: [ {$connectString} ]");
1981 * Constructs an IMAP c-client compatible folder path from Sugar proprietary
1982 * @param string $mbox "::" delimited IMAP mailbox path, ie, INBOX.saved.stuff
1985 function getImapMboxFromSugarProprietary($mbox) {
1986 $exMbox = explode("::", $mbox);
1990 for($i=2; $i<count($exMbox); $i++) {
1991 if(!empty($mboxImap)) {
1994 $mboxImap .= $exMbox[$i];
2001 * Searches IMAP (and POP3?) accounts/folders for emails with qualifying criteria
2003 function search($ieId, $subject='', $from='', $to='', $body='', $dateFrom='', $dateTo='') {
2004 global $current_user;
2005 global $app_strings;
2009 $bean = new InboundEmail();
2010 $bean->retrieve($ieId);
2012 //$beans = $this->retrieveAllByGroupId($current_user->id, true);
2014 $subject = urldecode($subject);
2017 $criteria .= (!empty($subject)) ? 'SUBJECT '.from_html($subject).'' : "";
2018 $criteria .= (!empty($from)) ? ' FROM "'.$from.'"' : "";
2019 $criteria .= (!empty($to)) ? ' FROM "'.$to.'"' : "";
2020 $criteria .= (!empty($body)) ? ' TEXT "'.$body.'"' : "";
2021 $criteria .= (!empty($dateFrom)) ? ' SINCE "'.$timedate->fromString($dateFrom)->format('d-M-Y').'"' : "";
2022 $criteria .= (!empty($dateTo)) ? ' BEFORE "'.$timedate->fromString($dateTo)->format('d-M-Y').'"' : "";
2023 //$criteria .= (!empty($from)) ? ' FROM "'.$from.'"' : "";
2025 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
2029 foreach($beans as $bean) {
2030 if(!in_array($bean->id, $showFolders)) {
2034 $GLOBALS['log']->info("*** INBOUNDEMAIL: searching [ {$bean->name} ] for [ {$subject}{$from}{$to}{$body}{$dateFrom}{$dateTo} ]");
2035 $group = (!$bean->is_personal) ? 'group.' : '';
2036 $bean->connectMailServer();
2037 $mailboxes = $bean->getMailboxes(true);
2038 if (!in_array('INBOX', $mailboxes)) {
2039 $mailboxes[] = 'INBOX';
2043 foreach($mailboxes as $mbox) {
2044 $bean->mailbox = $mbox;
2045 $searchOverviews = array();
2046 if ($bean->protocol == 'pop3') {
2047 $pop3Criteria = "SELECT * FROM email_cache WHERE ie_id = '{$bean->id}' AND mbox = '{$mbox}'";
2048 $pop3Criteria .= (!empty($subject)) ? ' AND subject like "%'.$bean->db->quote($subject).'%"' : "";
2049 $pop3Criteria .= (!empty($from)) ? ' AND fromaddr like "%'.$from.'%"' : "";
2050 $pop3Criteria .= (!empty($to)) ? ' AND toaddr like "%'.$to.'%"' : "";
2051 $pop3Criteria .= (!empty($dateFrom)) ? ' AND senddate > "'.$dateFrom.'"' : "";
2052 $pop3Criteria .= (!empty($dateTo)) ? ' AND senddate < "'.$dateTo.'"' : "";
2053 $GLOBALS['log']->info("*** INBOUNDEMAIL: searching [ {$mbox} ] using criteria [ {$pop3Criteria} ]");
2055 $r = $bean->db->query($pop3Criteria);
2056 while($a = $bean->db->fetchByAssoc($r)) {
2057 $overview = new Overview();
2059 foreach($a as $k => $v) {
2063 $overview->imap_uid = $v;
2064 $overview->uid = $a['message_id'];
2067 $overview->to = from_html($v);
2071 $overview->from = from_html($v);
2075 $overview->size = $v;
2079 $overview->date = $timedate->fromString($v)->format('r');
2083 $overview->$k = from_html($v);
2087 $searchOverviews[] = $overview;
2090 $bean->connectMailServer();
2091 $searchResult = imap_search($bean->conn, $criteria, SE_UID);
2092 if (!empty($searchResult)) {
2093 $searchOverviews = imap_fetch_overview($bean->conn, implode(',', $searchResult), FT_UID);
2096 $numHits = count($searchOverviews);
2099 $totalHits = $totalHits + $numHits;
2100 $ret = $bean->sortFetchedOverview($searchOverviews, 'date', 'desc', true);
2101 $mbox = "{$bean->id}.SEARCH";
2102 $out = array_merge($out, $bean->displayFetchedSortedListXML($ret, $mbox, false));
2107 $metadata = array();
2108 $metadata['mbox'] = $app_strings['LBL_EMAIL_SEARCH_RESULTS_TITLE'];
2109 $metadata['ieId'] = $this->id;
2110 $metadata['name'] = $this->name;
2111 $metadata['unreadChecked'] = ($current_user->getPreference('showUnreadOnly', 'Emails') == 1) ? 'CHECKED' : '';
2112 $metadata['out'] = $out;
2118 * repairs the encrypted password for a given I-E account
2119 * @return bool True on success
2121 function repairAccount() {
2123 for($i=0; $i<3; $i++) {
2124 if($i != 0) { // decode is performed on retrieve already
2125 $this->email_password = blowfishDecode(blowfishGetKey('InboundEmail'), $this->email_password);
2128 if($this->connectMailserver() == 'true') {
2129 $this->save(); // save decoded password (is encoded on save())
2138 * soft deletes a User's personal inbox
2139 * @param string id I-E id
2140 * @param string user_name User name of User in focus, NOT current_user
2141 * @return bool True on success
2143 function deletePersonalEmailAccount($id, $user_name) {
2144 $q = "SELECT ie.id FROM inbound_email ie LEFT JOIN users u ON ie.group_id = u.id WHERE u.user_name = '{$user_name}'";
2145 $r = $this->db->query($q, true);
2147 while($a = $this->db->fetchByAssoc($r)) {
2148 if(!empty($a) && $a['id'] == $id) {
2149 $this->retrieve($id);
2158 function getTeamSetIdForTeams($teamIds) {
2159 if(!is_array($teamIds)){
2160 $teamIds = array($teamIds);
2162 $teamSet = new TeamSet();
2163 $team_set_id = $teamSet->addTeams($teamIds);
2164 return $team_set_id;
2168 * Saves Personal Inbox settings for Users
2169 * @param string userId ID of user to assign all emails for this account
2170 * @param strings userName Name of account, for Sugar purposes
2171 * @param bool forceSave Default true. Flag to save errored settings.
2172 * @return boolean true on success, false on fail
2174 function savePersonalEmailAccount($userId = '', $userName = '', $forceSave=true) {
2176 $accountExists = false;
2177 if(isset($_REQUEST['ie_id']) && !empty($_REQUEST['ie_id'])) {
2178 $this->retrieve($_REQUEST['ie_id']);
2179 $accountExists = true;
2181 $ie_name = $_REQUEST['ie_name'];
2183 $this->is_personal = 1;
2184 $this->name = $ie_name;
2185 $this->group_id = $groupId;
2186 $this->status = $_REQUEST['ie_status'];
2187 $this->server_url = trim($_REQUEST['server_url']);
2188 $this->email_user = trim($_REQUEST['email_user']);
2189 if(!empty($_REQUEST['email_password'])) {
2190 $this->email_password = html_entity_decode($_REQUEST['email_password'], ENT_QUOTES);
2192 $this->port = trim($_REQUEST['port']);
2193 $this->protocol = $_REQUEST['protocol'];
2194 if ($this->protocol == "pop3") {
2195 $_REQUEST['mailbox'] = "INBOX";
2197 $this->mailbox = $_REQUEST['mailbox'];
2198 $this->mailbox_type = 'pick'; // forcing this
2201 if(isset($_REQUEST['ssl']) && $_REQUEST['ssl'] == 1) { $useSsl = true; }
2202 else $useSsl = false;
2203 $this->service = '::::::::::';
2206 $id = $this->save(); // saving here to prevent user from having to re-enter all the info in case of error
2207 $this->retrieve($id);
2210 $this->protocol = $_REQUEST['protocol']; // need to set this again since we safe the "service" string to empty explode values
2211 $opts = $this->getSessionConnectionString($this->server_url, $this->email_user, $this->port, $this->protocol);
2212 $detectedOpts = $this->findOptimumSettings($useSsl);
2214 //If $detectedOpts is empty, there was an error connecting, so clear $opts. If $opts was empty, use $detectedOpts
2215 if (empty($opts) || empty($detectedOpts) || (empty($detectedOpts['good']) && empty($detectedOpts['serial'])))
2217 $opts = $detectedOpts;
2219 $delimiter = $this->getSessionInboundDelimiterString($this->server_url, $this->email_user, $this->port, $this->protocol);
2221 if(isset($opts['serial']) && !empty($opts['serial'])) {
2222 $this->service = $opts['serial'];
2223 if(isset($_REQUEST['mark_read']) && $_REQUEST['mark_read'] == 1) {
2224 $this->delete_seen = 0;
2226 $this->delete_seen = 1;
2229 // handle stored_options serialization
2230 if(isset($_REQUEST['only_since']) && $_REQUEST['only_since'] == 1) {
2236 $focusUser = new User();
2237 $focusUser->retrieve($groupId);
2238 $mailerId = (isset($_REQUEST['outbound_email'])) ? $_REQUEST['outbound_email'] : "";
2240 $oe = new OutboundEmail();
2241 $oe->getSystemMailerSettings($focusUser, $mailerId);
2243 $stored_options = array();
2244 $stored_options['from_name'] = trim($_REQUEST['from_name']);
2245 $stored_options['from_addr'] = trim($_REQUEST['from_addr']);
2246 $stored_options['reply_to_addr'] = trim($_REQUEST['reply_to_addr']);
2248 if (!$this->isPop3Protocol()) {
2249 $stored_options['trashFolder'] = (isset($_REQUEST['trashFolder']) ? trim($_REQUEST['trashFolder']) : "");
2250 $stored_options['sentFolder'] = (isset($_REQUEST['sentFolder']) ? trim($_REQUEST['sentFolder']) : "");
2252 $stored_options['only_since'] = $onlySince;
2253 $stored_options['filter_domain'] = '';
2254 $storedOptions['folderDelimiter'] = $delimiter;
2255 $stored_options['outbound_email'] = (isset($_REQUEST['outbound_email'])) ? $_REQUEST['outbound_email'] : $oe->id;
2256 $this->stored_options = base64_encode(serialize($stored_options));
2258 $ieId = $this->save();
2260 //If this is the first personal account the user has setup mark it as default for them.
2261 $currentIECount = $this->getUserPersonalAccountCount($focusUser);
2262 if($currentIECount == 1)
2263 $this->setUsersDefaultOutboundServerId($focusUser, $ieId);
2267 // could not find opts, no save
2268 $GLOBALS['log']->debug('-----> InboundEmail could not find optimums for User: '.$ie_name);
2273 * Determines if this instance of I-E is for a Group Inbox or Personal Inbox
2275 function handleIsPersonal() {
2276 $qp = 'SELECT users.id, users.user_name FROM users WHERE users.is_group = 0 AND users.deleted = 0 AND users.status = \'active\' AND users.id = \''.$this->group_id.'\'';
2277 $rp = $this->db->query($qp, true);
2278 $personalBox = array();
2279 while($ap = $this->db->fetchByAssoc($rp)) {
2280 $personalBox[] = array($ap['id'], $ap['user_name']);
2282 if(count($personalBox) > 0) {
2289 function getUserNameFromGroupId() {
2290 $r = $this->db->query('SELECT users.user_name FROM users WHERE deleted=0 AND id=\''.$this->group_id.'\'', true);
2291 while($a = $this->db->fetchByAssoc($r)) {
2292 return $a['user_name'];
2297 function getFoldersListForMailBox() {
2299 $foldersList = $this->getSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol);
2300 if (empty($foldersList)) {
2301 global $mod_strings;
2302 $msg = $this->connectMailserver(true);
2303 if (strpos($msg, "successfully")) {
2304 $foldersList = $this->getSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol);
2305 $return['status'] = true;
2306 $return['foldersList'] = $foldersList;
2307 $return['statusMessage'] = "";
2309 $return['status'] = false;
2310 $return['statusMessage'] = $msg;
2313 $return['status'] = true;
2314 $return['foldersList'] = $foldersList;
2315 $return['statusMessage'] = "";
2320 * Programatically determines best-case settings for imap_open()
2322 function findOptimumSettings($useSsl=false, $user='', $pass='', $server='', $port='', $prot='', $mailbox='') {
2323 global $mod_strings;
2324 $serviceArr = array();
2325 $returnService = array();
2326 $badService = array();
2327 $goodService = array();
2328 $errorArr = array();
2330 $retArray = array( 'good' => $goodService,
2331 'bad' => $badService,
2332 'err' => $errorArr);
2334 if(!function_exists('imap_open')) {
2335 $retArray['err'][0] = $mod_strings['ERR_NO_IMAP'];
2339 imap_errors(); // clearing error stack
2340 error_reporting(0); // turn off notices from IMAP
2342 if(isset($_REQUEST['ssl']) && $_REQUEST['ssl'] == 1) {
2346 $exServ = explode('::', $this->service);
2347 $service = '/'.$exServ[1];
2349 $nonSsl = array('both-secure' => '/notls/novalidate-cert/secure',
2350 'both' => '/notls/novalidate-cert',
2351 'nocert-secure' => '/novalidate-cert/secure',
2352 'nocert' => '/novalidate-cert',
2353 'notls-secure' => '/notls/secure',
2354 'secure' => '/secure', // for POP3 servers that force CRAM-MD5
2355 'notls' => '/notls',
2356 'none' => '', // try default nothing
2359 'ssl-both-on-secure' => '/ssl/tls/validate-cert/secure',
2360 'ssl-both-on' => '/ssl/tls/validate-cert',
2361 'ssl-cert-secure' => '/ssl/validate-cert/secure',
2362 'ssl-cert' => '/ssl/validate-cert',
2363 'ssl-tls-secure' => '/ssl/tls/secure',
2364 'ssl-tls' => '/ssl/tls',
2365 'ssl-both-off-secure' => '/ssl/notls/novalidate-cert/secure',
2366 'ssl-both-off' => '/ssl/notls/novalidate-cert',
2367 'ssl-nocert-secure' => '/ssl/novalidate-cert/secure',
2368 'ssl-nocert' => '/ssl/novalidate-cert',
2369 'ssl-notls-secure' => '/ssl/notls/secure',
2370 'ssl-notls' => '/ssl/notls',
2371 'ssl-secure' => '/ssl/secure',
2372 'ssl-none' => '/ssl',
2375 if(isset($user) && !empty($user) && isset($pass) && !empty($pass)) {
2376 $this->email_password = $pass;
2377 $this->email_user = $user;
2378 $this->server_url = $server;
2379 $this->port = $port;
2380 $this->protocol = $prot;
2381 $this->mailbox = $mailbox;
2384 // in case we flip from IMAP to POP3
2385 if($this->protocol == 'pop3')
2386 $this->mailbox = 'INBOX';
2388 //If user has selected multiple mailboxes, we only need to test the first mailbox for the connection string.
2389 $a_mailbox = explode(",", $this->mailbox);
2390 $tmpMailbox = isset($a_mailbox[0]) ? $a_mailbox[0] : "";
2394 foreach($ssl as $k => $service)
2396 $returnService[$k] = 'foo'.$service;
2397 $serviceArr[$k] = '{'.$this->server_url.':'.$this->port.'/service='.$this->protocol.$service.'}'.$tmpMailbox;
2402 foreach($nonSsl as $k => $service)
2404 $returnService[$k] = 'foo'.$service;
2405 $serviceArr[$k] = '{'.$this->server_url.':'.$this->port.'/service='.$this->protocol.$service.'}'.$tmpMailbox;
2409 $GLOBALS['log']->debug('---------------STARTING FINDOPTIMUMS LOOP----------------');
2412 //php imap library will capture c-client library warnings as errors causing good connections to be ignored.
2413 //Check against known warnings to ensure good connections are used.
2414 $acceptableWarnings = array("SECURITY PROBLEM: insecure server advertised AUTH=PLAIN", //c-client auth_pla.c
2415 "Mailbox is empty");
2416 $login = $this->email_user;
2417 $passw = $this->email_password;
2418 $foundGoodConnection = false;
2419 foreach($serviceArr as $k => $serviceTest) {
2422 $GLOBALS['log']->debug($l.': I-E testing string: '.$serviceTest);
2424 // open the connection and try the test string
2425 $this->conn = imap_open($serviceTest, $login, $passw);
2427 if(($errors = imap_last_error()) || ($alerts = imap_alerts())) {
2428 if($errors == 'Too many login failures' || $errors == '[CLOSED] IMAP connection broken (server response)') { // login failure means don't bother trying the rest
2429 $GLOBALS['log']->debug($l.': I-E failed using ['.$serviceTest.']');
2430 $retArray['err'][$k] = $mod_strings['ERR_BAD_LOGIN_PASSWORD'];
2431 $retArray['bad'][$k] = $serviceTest;
2432 $GLOBALS['log']->debug($l.': I-E ERROR: $ie->findOptimums() failed due to bad user credentials for user login: '.$this->email_user);
2434 } elseif( in_array($errors, $acceptableWarnings, TRUE)) { // false positive
2435 $GLOBALS['log']->debug($l.': I-E found good connection but with warnings ['.$serviceTest.'] Errors:' . $errors);
2436 $retArray['good'][$k] = $returnService[$k];
2437 $foundGoodConnection = true;
2440 $GLOBALS['log']->debug($l.': I-E failed using ['.$serviceTest.'] - error: '.$errors);
2441 $retArray['err'][$k] = $errors;
2442 $retArray['bad'][$k] = $serviceTest;
2445 $GLOBALS['log']->debug($l.': I-E found good connect using ['.$serviceTest.']');
2446 $retArray['good'][$k] = $returnService[$k];
2447 $foundGoodConnection = true;
2450 if(is_resource($this->conn)) {
2451 if (!$this->isPop3Protocol()) {
2452 $serviceTest = str_replace("INBOX", "", $serviceTest);
2453 $boxes = imap_getmailboxes($this->conn, $serviceTest, "*");
2455 // clean MBOX path names
2456 foreach($boxes as $k => $mbox) {
2457 $raw[] = $mbox->name;
2458 if ($mbox->delimiter) {
2459 $delimiter = $mbox->delimiter;
2462 $this->setSessionInboundDelimiterString($this->server_url, $this->email_user, $this->port, $this->protocol, $delimiter);
2465 if(!imap_close($this->conn)) $GLOBALS['log']->debug('imap_close() failed!');
2468 $GLOBALS['log']->debug($l.': I-E clearing error and alert stacks.');
2469 imap_errors(); // clear stacks
2471 // If you find a good connection, then don't do any further testing to find URL
2472 if ($foundGoodConnection) {
2477 $GLOBALS['log']->debug('---------------end FINDOPTIMUMS LOOP----------------');
2479 if(!empty($retArray['good'])) {
2484 $newNovalidate_cert = '';
2485 $good = array_pop($retArray['good']); // get most complete string
2486 $exGood = explode('/', $good);
2487 foreach($exGood as $v) {
2496 $newNotls = 'notls';
2499 $newCert = 'validate-cert';
2501 case 'novalidate-cert':
2502 $newNovalidate_cert = 'novalidate-cert';
2510 $goodStr['serial'] = $newTls.'::'.$newCert.'::'.$newSsl.'::'.$this->protocol.'::'.$newNovalidate_cert.'::'.$newNotls.'::'.$secure;
2511 $goodStr['service'] = $good;
2512 $testConnectString = str_replace('foo','', $good);
2513 $testConnectString = '{'.$this->server_url.':'.$this->port.'/service='.$this->protocol.$testConnectString.'}';
2514 $this->setSessionConnectionString($this->server_url, $this->email_user, $this->port, $this->protocol, $goodStr);
2516 foreach($raw as $mbox)
2518 $raw[$i] = str_replace($testConnectString, "", $GLOBALS['locale']->translateCharset($mbox, "UTF7-IMAP", "UTF8" ));
2522 $this->setSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol, implode(",", $raw));
2529 function getSessionConnectionString($server_url, $email_user, $port, $protocol) {
2530 $sessionConnectionString = $server_url . $email_user . $port . $protocol;
2531 return (isset($_SESSION[$sessionConnectionString]) ? $_SESSION[$sessionConnectionString] : "");
2534 function setSessionConnectionString($server_url, $email_user, $port, $protocol, $goodStr) {
2535 $sessionConnectionString = $server_url . $email_user . $port . $protocol;
2536 $_SESSION[$sessionConnectionString] = $goodStr;
2539 function getSessionInboundDelimiterString($server_url, $email_user, $port, $protocol) {
2540 $sessionInboundDelimiterString = $server_url . $email_user . $port . $protocol . "delimiter";
2541 return (isset($_SESSION[$sessionInboundDelimiterString]) ? $_SESSION[$sessionInboundDelimiterString] : "");
2544 function setSessionInboundDelimiterString($server_url, $email_user, $port, $protocol, $delimiter) {
2545 $sessionInboundDelimiterString = $server_url . $email_user . $port . $protocol . "delimiter";
2546 $_SESSION[$sessionInboundDelimiterString] = $delimiter;
2549 function getSessionInboundFoldersString($server_url, $email_user, $port, $protocol) {
2550 $sessionInboundFoldersListString = $server_url . $email_user . $port . $protocol . "foldersList";
2551 return (isset($_SESSION[$sessionInboundFoldersListString]) ? $_SESSION[$sessionInboundFoldersListString] : "");
2554 function setSessionInboundFoldersString($server_url, $email_user, $port, $protocol, $foldersList) {
2555 $sessionInboundFoldersListString = $server_url . $email_user . $port . $protocol . "foldersList";
2556 $_SESSION[$sessionInboundFoldersListString] = $foldersList;
2560 * Checks for duplicate Group User names when creating a new one at save()
2561 * @return GUID returns GUID of Group User if user_name match is
2563 * @return boolean false if NO DUPE IS FOUND
2565 function groupUserDupeCheck() {
2566 $q = "SELECT u.id FROM users u WHERE u.deleted=0 AND u.is_group=1 AND u.user_name = '".$this->name."'";
2567 $r = $this->db->query($q, true);
2569 while($a = $this->db->fetchByAssoc($r)) {
2573 if(strlen($uid) > 0) {
2581 * Returns <option> markup with the contents of Group users
2582 * @param array $groups default empty array
2583 * @return string HTML options
2585 function getGroupsWithSelectOptions($groups = array()) {
2586 $r = $this->db->query('SELECT id, user_name FROM users WHERE users.is_group = 1 AND deleted = 0', true);
2587 if(is_resource($r)) {
2588 while($a = $this->db->fetchByAssoc($r)) {
2589 $groups[$a['id']] = $a['user_name'];
2593 $selectOptions = get_select_options_with_id_separate_key($groups, $groups, $this->group_id);
2594 return $selectOptions;
2598 * handles auto-responses to inbound emails
2600 * @param object email Email passed as reference
2602 function handleAutoresponse(&$email, &$contactAddr) {
2603 if($this->template_id) {
2604 $GLOBALS['log']->debug('found auto-reply template id - prefilling and mailing response');
2606 if($this->getAutoreplyStatus($contactAddr)
2607 && $this->checkOutOfOffice($email->name)
2608 && $this->checkFilterDomain($email)) { // if we haven't sent this guy 10 replies in 24hours
2610 if(!empty($this->stored_options)) {
2611 $storedOptions = unserialize(base64_decode($this->stored_options));
2614 if(!empty($storedOptions['from_name'])) {
2615 $from_name = $storedOptions['from_name'];
2616 $GLOBALS['log']->debug('got from_name from storedOptions: '.$from_name);
2617 } else { // use system default
2618 $rName = $this->db->query('SELECT value FROM config WHERE name = \'fromname\'', true);
2619 if(is_resource($rName)) {
2620 $aName = $this->db->fetchByAssoc($rName);
2622 if(!empty($aName['value'])) {
2623 $from_name = $aName['value'];
2629 if(!empty($storedOptions['from_addr'])) {
2630 $from_addr = $storedOptions['from_addr'];
2632 $rAddr = $this->db->query('SELECT value FROM config WHERE name = \'fromaddress\'', true);
2633 if(is_resource($rAddr)) {
2634 $aAddr = $this->db->fetchByAssoc($rAddr);
2636 if(!empty($aAddr['value'])) {
2637 $from_addr = $aAddr['value'];
2643 $replyToName = (!empty($storedOptions['reply_to_name']))? from_html($storedOptions['reply_to_name']) :$from_name ;
2644 $replyToAddr = (!empty($storedOptions['reply_to_addr'])) ? $storedOptions['reply_to_addr'] : $from_addr;
2647 if(!empty($email->reply_to_email)) {
2648 $to[0]['email'] = $email->reply_to_email;
2650 $to[0]['email'] = $email->from_addr;
2652 // handle to name: address, prefer reply-to
2653 if(!empty($email->reply_to_name)) {
2654 $to[0]['display'] = $email->reply_to_name;
2655 } elseif(!empty($email->from_name)) {
2656 $to[0]['display'] = $email->from_name;
2659 $et = new EmailTemplate();
2660 $et->retrieve($this->template_id);
2661 if(empty($et->subject)) { $et->subject = ''; }
2662 if(empty($et->body)) { $et->body = ''; }
2663 if(empty($et->body_html)) { $et->body_html = ''; }
2665 $reply = new Email();
2666 $reply->type = 'out';
2667 $reply->to_addrs = $to[0]['email'];
2668 $reply->to_addrs_arr = $to;
2669 $reply->cc_addrs_arr = array();
2670 $reply->bcc_addrs_arr = array();
2671 $reply->from_name = $from_name;
2672 $reply->from_addr = $from_addr;
2673 $reply->name = $et->subject;
2674 $reply->description = $et->body;
2675 $reply->description_html = $et->body_html;
2676 $reply->reply_to_name = $replyToName;
2677 $reply->reply_to_addr = $replyToAddr;
2679 $GLOBALS['log']->debug('saving and sending auto-reply email');
2680 //$reply->save(); // don't save the actual email.
2682 $this->setAutoreplyStatus($contactAddr);
2684 $GLOBALS['log']->debug('InboundEmail: auto-reply threshold reached for email ('.$contactAddr.') - not sending auto-reply');
2689 function handleCaseAssignment($email) {
2691 if($caseId = $this->getCaseIdFromCaseNumber($email->name, $c)) {
2692 $c->retrieve($caseId);
2693 $email->retrieve($email->id);
2694 //assign the case info to parent id and parent type so that the case can be linked to the email on Email Save
2695 $email->parent_type = "Cases";
2696 $email->parent_id = $caseId;
2697 // assign the email to the case owner
2698 $email->assigned_user_id = $c->assigned_user_id;
2700 $GLOBALS['log']->debug('InboundEmail found exactly 1 match for a case: '.$c->name);
2707 * handles functionality specific to the Mailbox type (Cases, bounced
2710 * @param object email Email object passed as a reference
2711 * @param object header Header object generated by imap_headerinfo();
2713 function handleMailboxType(&$email, &$header) {
2714 switch($this->mailbox_type) {
2716 $this->handleCaseAssignment($email);
2723 // do something with this?
2726 // do something with leads? we don't have an email_leads table
2732 require_once('modules/Campaigns/ProcessBouncedEmails.php');
2733 campaign_process_bounced_emails($email, $header);
2735 case 'pick': // do all except bounce handling
2736 $GLOBALS['log']->debug('looking for a case for '.$email->name);
2737 $this->handleCaseAssignment($email);
2742 function isMailBoxTypeCreateCase() {
2743 return ($this->mailbox_type == 'createcase' && !empty($this->groupfolder_id));
2746 function handleCreateCase($email, $userId) {
2747 global $current_user, $mod_strings, $current_language;
2748 $mod_strings = return_module_language($current_language, "Emails");
2749 $GLOBALS['log']->debug('In handleCreateCase');
2751 $this->getCaseIdFromCaseNumber($email->name, $c);
2753 if (!$this->handleCaseAssignment($email) && $this->isMailBoxTypeCreateCase()) {
2755 $GLOBALS['log']->debug('retrieveing email');
2756 $email->retrieve($email->id);
2758 $c->description = $email->description;
2759 $c->assigned_user_id = $userId;
2760 $c->name = $email->name;
2762 $c->priority = 'P1';
2764 if(!empty($email->reply_to_email)) {
2765 $contactAddr = $email->reply_to_email;
2767 $contactAddr = $email->from_addr;
2770 $GLOBALS['log']->debug('finding related accounts with address ' . $contactAddr);
2771 if($accountIds = $this->getRelatedId($contactAddr, 'accounts')) {
2772 if (sizeof($accountIds) == 1) {
2773 $c->account_id = $accountIds[0];
2775 $acct = new Account();
2776 $acct->retrieve($c->account_id);
2777 $c->account_name = $acct->name;
2783 $c->retrieve($caseId);
2784 if($c->load_relationship('emails')) {
2785 $c->emails->add($email->id);
2787 if($contactIds = $this->getRelatedId($contactAddr, 'contacts')) {
2788 if(!empty($contactIds) && $c->load_relationship('contacts')) {
2789 $c->contacts->add($contactIds);
2792 $c->email_id = $email->id;
2793 $email->parent_type = "Cases";
2794 $email->parent_id = $caseId;
2795 // assign the email to the case owner
2796 $email->assigned_user_id = $c->assigned_user_id;
2797 $email->name = str_replace('%1', $c->case_number, $c->getEmailSubjectMacro()) . " ". $email->name;
2799 $GLOBALS['log']->debug('InboundEmail created one case with number: '.$c->case_number);
2800 $createCaseTemplateId = $this->get_stored_options('create_case_email_template', "");
2801 if(!empty($this->stored_options)) {
2802 $storedOptions = unserialize(base64_decode($this->stored_options));
2804 if(!empty($createCaseTemplateId)) {
2807 if (!empty($this->stored_options)) {
2808 $fromAddress = $storedOptions['from_addr'];
2809 $fromName = from_html($storedOptions['from_name']);
2810 $replyToName = (!empty($storedOptions['reply_to_name']))? from_html($storedOptions['reply_to_name']) :$fromName ;
2811 $replyToAddr = (!empty($storedOptions['reply_to_addr'])) ? $storedOptions['reply_to_addr'] : $fromAddress;
2813 $defaults = $current_user->getPreferredEmail();
2814 $fromAddress = (!empty($fromAddress)) ? $fromAddress : $defaults['email'];
2815 $fromName = (!empty($fromName)) ? $fromName : $defaults['name'];
2816 $to[0]['email'] = $contactAddr;
2818 // handle to name: address, prefer reply-to
2819 if(!empty($email->reply_to_name)) {
2820 $to[0]['display'] = $email->reply_to_name;
2821 } elseif(!empty($email->from_name)) {
2822 $to[0]['display'] = $email->from_name;
2825 $et = new EmailTemplate();
2826 $et->retrieve($createCaseTemplateId);
2827 if(empty($et->subject)) { $et->subject = ''; }
2828 if(empty($et->body)) { $et->body = ''; }
2829 if(empty($et->body_html)) { $et->body_html = ''; }
2831 $et->subject = "Re:" . " " . str_replace('%1', $c->case_number, $c->getEmailSubjectMacro() . " ". $c->name);
2833 $html = trim($email->description_html);
2834 $plain = trim($email->description);
2836 $email->email2init();
2837 $email->from_addr = $email->from_addr_name;
2838 $email->to_addrs = $email->to_addrs_names;
2839 $email->cc_addrs = $email->cc_addrs_names;
2840 $email->bcc_addrs = $email->bcc_addrs_names;
2841 $email->from_name = $email->from_addr;
2843 $email = $email->et->handleReplyType($email, "reply");
2844 $ret = $email->et->displayComposeEmail($email);
2845 $ret['description'] = empty($email->description_html) ? str_replace("\n", "\n<BR/>", $email->description) : $email->description_html;
2847 $reply = new Email();
2848 $reply->type = 'out';
2849 $reply->to_addrs = $to[0]['email'];
2850 $reply->to_addrs_arr = $to;
2851 $reply->cc_addrs_arr = array();
2852 $reply->bcc_addrs_arr = array();
2853 $reply->from_name = $fromName;
2854 $reply->from_addr = $fromAddress;
2855 $reply->reply_to_name = $replyToName;
2856 $reply->reply_to_addr = $replyToAddr;
2857 $reply->name = $et->subject;
2858 $reply->description = $et->body . "<div><hr /></div>" . $email->description;
2859 if (!$et->text_only) {
2860 $reply->description_html = $et->body_html . "<div><hr /></div>" . $email->description;
2862 $GLOBALS['log']->debug('saving and sending auto-reply email');
2863 //$reply->save(); // don't save the actual email.
2868 if(!empty($email->reply_to_email)) {
2869 $contactAddr = $email->reply_to_email;
2871 $contactAddr = $email->from_addr;
2873 $this->handleAutoresponse($email, $contactAddr);
2879 * handles linking contacts, accounts, etc. to an email
2881 * @param object Email bean to be linked against
2882 * @return string contactAddr is the email address of the sender
2884 function handleLinking(&$email) {
2885 // link email to an User if emails match TO addr
2886 if($userIds = $this->getRelatedId($email->to_addrs, 'users')) {
2887 $GLOBALS['log']->debug('I-E linking email to User');
2888 // link the user to the email
2889 $email->load_relationship('users');
2890 $email->users->add($userIds);
2893 // link email to a Contact, Lead, or Account if the emails match
2894 // give precedence to REPLY-TO above FROM
2895 if(!empty($email->reply_to_email)) {
2896 $contactAddr = $email->reply_to_email;
2898 $contactAddr = $email->from_addr;
2901 // Samir Gandhi : 12/06/07
2902 // This changes has been done because the linking was done only with the from address and
2903 // not with to address
2904 $relationShipAddress = $contactAddr;
2905 if (empty($relationShipAddress)) {
2906 $relationShipAddress .= $email->to_addrs;
2908 $relationShipAddress = $relationShipAddress . "," . $email->to_addrs;
2910 if($leadIds = $this->getRelatedId($relationShipAddress, 'leads')) {
2911 $GLOBALS['log']->debug('I-E linking email to Lead');
2912 $email->load_relationship('leads');
2913 $email->leads->add($leadIds);
2915 foreach($leadIds as $leadId) {
2917 $lead->retrieve($leadId);
2918 $lead->load_relationship('emails');
2919 $lead->emails->add($email->id);
2923 if($contactIds = $this->getRelatedId($relationShipAddress, 'contacts')) {
2924 $GLOBALS['log']->debug('I-E linking email to Contact');
2925 // link the contact to the email
2926 $email->load_relationship('contacts');
2927 $email->contacts->add($contactIds);
2930 if($accountIds = $this->getRelatedId($relationShipAddress, 'accounts')) {
2931 $GLOBALS['log']->debug('I-E linking email to Account');
2932 // link the account to the email
2933 $email->load_relationship('accounts');
2934 $email->accounts->add($accountIds);
2936 /* cn: bug 9171 another cause of dying I-E - bad linking
2937 foreach($accountIds as $accountId) {
2938 $GLOBALS['log']->debug('I-E reverse-linking Accounts to Emails');
2939 $acct = new Account();
2940 $acct->retrieve($accountId);
2941 $acct->load_relationship('emails');
2942 $acct->account_emails->add($email->id);
2946 return $contactAddr;
2950 * Gets part by following breadcrumb path
2951 * @param string $bc the breadcrumb string in format (1.1.1)
2952 * @param array parts the root level parts array
2954 protected function getPartByPath($bc, $parts)
2956 if(strstr($bc,'.')) {
2957 $exBc = explode('.', $bc);
2962 foreach($exBc as $step) {
2963 if(empty($parts)) return false;
2964 $res = $parts[$step-1]; // MIME starts with 1, array starts with 0
2965 if(!empty($res->parts)) {
2966 $parts = $res->parts;
2975 * takes a breadcrumb and returns the encoding at that level
2976 * @param string bc the breadcrumb string in format (1.1.1)
2977 * @param array parts the root level parts array
2978 * @return int retInt Int key to transfer encoding (see handleTranserEncoding())
2980 function getEncodingFromBreadCrumb($bc, $parts) {
2981 if(strstr($bc,'.')) {
2982 $exBc = explode('.', $bc);
2987 $depth = count($exBc);
2989 for($i=0; $i<$depth; $i++) {
2990 $tempObj[$i] = $parts[($exBc[$i]-1)];
2991 $retInt = imap_utf8($tempObj[$i]->encoding);
2992 if(!empty($tempObj[$i]->parts)) {
2993 $parts = $tempObj[$i]->parts;
3000 * retrieves the charset for a given part of an email body
3002 * @param string bc target part of the message in format (1.1.1)
3003 * @param array parts 1 level above ROOT array of Objects representing a multipart body
3004 * @return string charset name
3006 function getCharsetFromBreadCrumb($bc, $parts)
3008 $tempObj = $this->getPartByPath($bc, $parts);
3009 // now we have the tempObj at the end of the breadCrumb trail
3011 if(!empty($tempObj->ifparameters)) {
3012 foreach($tempObj->parameters as $param) {
3013 if(strtolower($param->attribute) == 'charset') {
3014 return $param->value;
3023 * Get the message text from a single mime section, html or plain.
3025 * @param string $msgNo
3026 * @param string $section
3027 * @param stdObject $structure
3030 function getMessageTextFromSingleMimePart($msgNo,$section,$structure)
3032 $msgPartTmp = imap_fetchbody($this->conn, $msgNo, $section);
3033 $enc = $this->getEncodingFromBreadCrumb($section, $structure->parts);
3034 $charset = $this->getCharsetFromBreadCrumb($section, $structure->parts);
3035 $msgPartTmp = $this->handleTranserEncoding($msgPartTmp, $enc);
3036 return $this->handleCharsetTranslation($msgPartTmp, $charset);
3040 * Givin an existing breadcrumb add a cooresponding offset
3043 * @param string $offset
3046 function addBreadCrumbOffset($bc, $offset)
3048 if( (empty($bc) || is_null($bc)) && !empty($offset) )
3051 $a_bc = explode(".", $bc);
3052 $a_offset = explode(".",$offset);
3053 if(count($a_bc) < count($a_offset))
3054 $a_bc = array_merge($a_bc,array_fill( count($a_bc), count($a_offset) - count($a_bc), 0));
3057 for($i=0;$i < count($a_bc); $i++)
3059 if(isset($a_offset[$i]))
3060 $results[] = $a_bc[$i] + $a_offset[$i];
3062 $results[] = $a_bc[$i];
3064 return implode(".", $results);
3068 * returns the HTML text part of a multi-part message
3070 * @param int msgNo the relative message number for the monitored mailbox
3071 * @param string $type the type of text processed, either 'PLAIN' or 'HTML'
3072 * @return string UTF-8 encoded version of the requested message text
3074 function getMessageText($msgNo, $type, $structure, $fullHeader,$clean_email=true, $bcOffset = "") {
3075 global $sugar_config;
3078 $bc = $this->buildBreadCrumbs($structure->parts, $type);
3079 //Add an offset if specified
3080 if(!empty($bcOffset))
3081 $bc = $this->addBreadCrumbOffset($bc, $bcOffset);
3083 if(!empty($bc)) { // multi-part
3084 // HUGE difference between PLAIN and HTML
3085 if($type == 'PLAIN') {
3086 $msgPart = $this->getMessageTextFromSingleMimePart($msgNo,$bc,$structure);
3088 // get part of structure that will
3090 $bcArray = $this->buildBreadCrumbsHTML($structure->parts,$bcOffset);
3091 // construct inline HTML/Rich msg
3092 foreach($bcArray as $bcArryKey => $bcArr) {
3093 foreach($bcArr as $type => $bcTrail) {
3095 $msgPartRaw .= $this->getMessageTextFromSingleMimePart($msgNo,$bcTrail,$structure);
3097 // deal with inline image
3098 $part = $this->getPartByPath($bcTrail, $structure->parts);
3099 if(empty($part) || empty($part->id)) continue;
3100 $partid = substr($part->id, 1, -1); // strip <> around
3101 if(isset($this->inlineImages[$partid])) {
3102 $imageName = $this->inlineImages[$partid];
3103 $newImagePath = "class=\"image\" src=\"{$this->imagePrefix}{$imageName}\"";
3104 $preImagePath = "src=\"cid:$partid\"";
3105 $msgPartRaw = str_replace($preImagePath, $newImagePath, $msgPartRaw);
3110 $msgPart = $msgPartRaw;
3112 } else { // either PLAIN message type (flowed) or b0rk3d RFC
3113 // make sure we're working on valid data here.
3114 if($structure->subtype != $type) {
3118 $decodedHeader = $this->decodeHeader($fullHeader);
3120 // now get actual body contents
3121 $text = imap_body($this->conn, $msgNo);
3123 $upperCaseKeyDecodeHeader = array();
3124 if (is_array($decodedHeader)) {
3125 $upperCaseKeyDecodeHeader = array_change_key_case($decodedHeader, CASE_UPPER);
3127 if(isset($upperCaseKeyDecodeHeader[strtoupper('Content-Transfer-Encoding')])) {
3128 $flip = array_flip($this->transferEncoding);
3129 $text = $this->handleTranserEncoding($text, $flip[strtoupper($upperCaseKeyDecodeHeader[strtoupper('Content-Transfer-Encoding')])]);
3132 if(is_array($upperCaseKeyDecodeHeader['CONTENT-TYPE']) && isset($upperCaseKeyDecodeHeader['CONTENT-TYPE']['charset']) && !empty($upperCaseKeyDecodeHeader['CONTENT-TYPE']['charset'])) {
3133 // we have an explicit content type, use it
3134 $msgPart = $this->handleCharsetTranslation($text, $upperCaseKeyDecodeHeader['CONTENT-TYPE']['charset']);
3136 // make a best guess as to what our content type is
3137 $msgPart = $this->convertToUtf8($text);
3139 } // end else clause
3141 $msgPart = $this->customGetMessageText($msgPart);
3142 /* cn: bug 9176 - htmlEntitites hide XSS attacks. */
3143 if($type == 'PLAIN') {
3144 return SugarCleaner::cleanHtml(to_html($msgPart), false);
3146 // Bug 50241: can't process <?xml:namespace .../> properly. Strip <?xml ...> tag first.
3147 $msgPart = preg_replace("/<\?xml[^>]*>/","",$msgPart);
3149 return SugarCleaner::cleanHtml($msgPart, false);
3153 * decodes raw header information and passes back an associative array with
3154 * the important elements key'd by name
3155 * @param header string the raw header
3156 * @return decodedHeader array the associative array
3158 function decodeHeader($fullHeader) {
3159 $decodedHeader = array();
3160 $exHeaders = explode("\r", $fullHeader);
3161 if (!is_array($exHeaders)) {
3162 $exHeaders = explode("\r\n", $fullHeader);
3164 $quotes = array('"', "'");
3166 foreach($exHeaders as $lineNum => $head) {
3168 $key = trim(substr($head, 0, strpos($head, ':')));
3170 $value = trim(substr($head, (strpos($head, ':') + 1), strlen($head)));
3172 // handle content-type section in headers
3173 if(strtolower($key) == 'content-type' && strpos($value, ';')) { // ";" means something follows related to (such as Charset)
3174 $semiColPos = mb_strpos($value, ';');
3175 $strLenVal = mb_strlen($value);
3176 if(($semiColPos + 4) >= $strLenVal) {
3177 // the charset="[something]" is on the next line
3178 $value .= str_replace($quotes, "", trim($exHeaders[$lineNum+1]));
3181 $newValue = array();
3182 $exValue = explode(';', $value);
3183 $newValue['type'] = $exValue[0];
3185 for($i=1; $i<count($exValue); $i++) {
3186 $exContent = explode('=', $exValue[$i]);
3187 $newValue[trim($exContent[0])] = trim($exContent[1], "\t \"");
3192 if(!empty($key) && !empty($value)) {
3193 $decodedHeader[$key] = $value;
3197 return $decodedHeader;
3201 * handles translating message text from orignal encoding into UTF-8
3203 * @param string text test to be re-encoded
3204 * @param string charset original character set
3205 * @return string utf8 re-encoded text
3207 function handleCharsetTranslation($text, $charset) {
3210 if(empty($charset)) {
3211 $GLOBALS['log']->debug("***ERROR: InboundEmail::handleCharsetTranslation() called without a \$charset!");
3212 $GLOBALS['log']->debug("***STACKTRACE: ".print_r(debug_backtrace(), true));
3216 // typical headers have no charset - let destination pick (since it's all ASCII anyways)
3217 if(strtolower($charset) == 'default' || strtolower($charset) == 'utf-8') {
3221 return $locale->translateCharset($text, $charset);
3227 * Builds up the "breadcrumb" trail that imap_fetchbody() uses to return
3228 * parts of an email message, including attachments and inline images
3229 * @param $parts array of objects
3230 * @param $subtype what type of trail to return? HTML? Plain? binaries?
3231 * @param $breadcrumb text trail to build up
3233 function buildBreadCrumbs($parts, $subtype, $breadcrumb = '0') {
3234 //_pp('buildBreadCrumbs building for '.$subtype.' with BC at '.$breadcrumb);
3235 // loop through available parts in the array
3236 foreach($parts as $k => $part) {
3237 // mark passage through level
3239 // if this is not the first time through, start building the map
3240 if($breadcrumb != 0) {
3241 $thisBc = $breadcrumb.'.'.$thisBc;
3244 // found a multi-part/mixed 'part' - keep digging
3245 if($part->type == 1 && (strtoupper($part->subtype) == 'RELATED' || strtoupper($part->subtype) == 'ALTERNATIVE' || strtoupper($part->subtype) == 'MIXED')) {
3246 //_pp('in loop: going deeper with subtype: '.$part->subtype.' $k is: '.$k);
3247 $thisBc = $this->buildBreadCrumbs($part->parts, $subtype, $thisBc);
3250 } elseif(strtolower($part->subtype) == strtolower($subtype)) { // found the subtype we want, return the breadcrumb value
3251 //_pp('found '.$subtype.' bc! returning: '.$thisBc);
3254 //_pp('found '.$part->subtype.' instead');
3260 * Similar to buildBreadCrumbs() but returns an ordered array containing all parts of the message that would be
3261 * considered "HTML" or Richtext (embedded images, formatting, etc.).
3262 * @param array parts Array of parts of a message
3263 * @param int breadcrumb Passed integer value to start breadcrumb trail
3264 * @param array stackedBreadcrumbs Persistent trail of breadcrumbs
3265 * @return array Ordered array of parts to retrieve via imap_fetchbody()
3267 function buildBreadCrumbsHTML($parts, $breadcrumb = '0', $stackedBreadcrumbs = array()) {
3269 $disposition = 'inline';
3271 foreach($parts as $k => $part) {
3272 // mark passage through level
3275 if($breadcrumb != 0) {
3276 $thisBc = $breadcrumb.'.'.$thisBc;
3278 // found a multi-part/mixed 'part' - keep digging
3279 if($part->type == 1 && (strtoupper($part->subtype) == 'RELATED' || strtoupper($part->subtype) == 'ALTERNATIVE' || strtoupper($part->subtype) == 'MIXED')) {
3280 $stackedBreadcrumbs = $this->buildBreadCrumbsHTML($part->parts, $thisBc, $stackedBreadcrumbs);
3282 (strtolower($part->subtype) == strtolower($subtype)) ||
3284 isset($part->disposition) && strtolower($part->disposition) == 'inline' &&
3285 in_array(strtoupper($part->subtype), $this->imageTypes)
3288 // found the subtype we want, return the breadcrumb value
3289 $stackedBreadcrumbs[] = array(strtolower($part->subtype) => $thisBc);
3290 } elseif($part->type == 5) {
3291 $stackedBreadcrumbs[] = array(strtolower($part->subtype) => $thisBc);
3295 return $stackedBreadcrumbs;
3299 * Takes a PHP imap_* object's to/from/cc/bcc address field and converts it
3300 * to a standard string that SugarCRM expects
3301 * @param $arr an array of email address objects
3303 function convertImapToSugarEmailAddress($arr) {
3304 if(is_array($arr)) {
3306 foreach($arr as $key => $obj) {
3307 $addr .= $obj->mailbox.'@'.$obj->host.', ';
3310 $ret = substr_replace($addr,'',-2,-1);
3316 * tries to figure out what character set a given filename is using and
3317 * decode based on that
3319 * @param string name Name of attachment
3320 * @return string decoded name
3322 function handleEncodedFilename($name) {
3323 $imapDecode = imap_mime_header_decode($name);
3324 /******************************
3325 $imapDecode => stdClass Object
3328 [text] => w�hlen.php
3333 $imapDecode => stdClass Object
3335 [charset] => default
3336 [text] => UTF-8''%E3%83%8F%E3%82%99%E3%82%A4%E3%82%AA%E3%82%AF%E3%82%99%E3%83%A9%E3%83%95%E3%82%A3%E3%83%BC.txt
3338 *******************************/
3339 if($imapDecode[0]->charset != 'default') { // mime-header encoded charset
3340 $encoding = $imapDecode[0]->charset;
3341 $name = $imapDecode[0]->text; // encoded in that charset
3343 /* encoded filenames are formatted as [encoding]''[filename] */
3344 if(strpos($name, "''") !== false) {
3346 $encoding = substr($name, 0, strpos($name, "'"));
3348 while(strpos($name, "'") !== false) {
3349 $name = trim(substr($name, (strpos($name, "'")+1), strlen($name)));
3352 $name = urldecode($name);
3354 return (strtolower($encoding) == 'utf-8') ? $name : $GLOBALS['locale']->translateCharset($name, $encoding, 'UTF-8');
3358 Primary body types for a part of a mail structure (imap_fetchstructure returned object)
3370 Primary body types for a part of a mail structure (imap_fetchstructure returned object)
3371 @var array $imap_types
3373 public $imap_types = array(
3383 public function getMimeType($type, $subtype)
3385 if(isset($this->imap_types[$type])) {
3386 return $this->imap_types[$type]."/$subtype";
3388 return "other/$subtype";
3393 * Takes the "parts" attribute of the object that imap_fetchbody() method
3394 * returns, and recursively goes through looking for objects that have a
3395 * disposition of "attachement" or "inline"
3396 * @param int $msgNo The relative message number for the monitored mailbox
3397 * @param object $parts Array of objects to examine
3398 * @param string $emailId The GUID of the email saved prior to calling this method
3399 * @param array $breadcrumb Default 0, build up of the parts mapping
3400 * @param bool $forDisplay Default false
3402 function saveAttachments($msgNo, $parts, $emailId, $breadcrumb='0', $forDisplay) {
3403 global $sugar_config;
3405 Primary body types for a part of a mail structure (imap_fetchstructure returned object)
3416 foreach($parts as $k => $part) {
3418 if($breadcrumb != '0') {
3419 $thisBc = $breadcrumb.'.'.$thisBc;
3422 // check if we need to recurse into the object
3423 //if($part->type == 1 && !empty($part->parts)) {
3424 if(isset($part->parts) && !empty($part->parts) && !( isset($part->subtype) && strtolower($part->subtype) == 'rfc822') ) {
3425 $this->saveAttachments($msgNo, $part->parts, $emailId, $thisBc, $forDisplay);
3427 } elseif($part->ifdisposition) {
3428 // we will take either 'attachments' or 'inline'
3429 if(strtolower($part->disposition) == 'attachment' || ((strtolower($part->disposition) == 'inline') && $part->type != 0)) {
3430 $attach = $this->getNoteBeanForAttachment($emailId);
3431 $fname = $this->handleEncodedFilename($this->retrieveAttachmentNameFromStructure($part));
3433 if(!empty($fname)) {//assign name to attachment
3434 $attach->name = $fname;
3435 } else {//if name is empty, default to filename
3436 $attach->name = urlencode($this->retrieveAttachmentNameFromStructure($part));
3438 $attach->filename = $attach->name;
3439 if (empty($attach->filename)) {
3443 // deal with the MIME types email has
3444 $attach->file_mime_type = $this->getMimeType($part->type, $part->subtype);
3445 $attach->safeAttachmentName();
3447 $attach->id = $this->getTempFilename();
3449 // only save if doing a full import, else we want only the binaries
3452 } // end if disposition type 'attachment'
3453 }// end ifdisposition
3454 //Retrieve contents of subtype rfc8822
3455 elseif ($part->type == 2 && isset($part->subtype) && strtolower($part->subtype) == 'rfc822' )
3457 $tmp_eml = imap_fetchbody($this->conn, $msgNo, $thisBc);
3458 $attach = $this->getNoteBeanForAttachment($emailId);
3459 $attach->file_mime_type = 'messsage/rfc822';
3460 $attach->description = $tmp_eml;
3461 $attach->filename = 'bounce.eml';
3462 $attach->safeAttachmentName();
3464 $attach->id = $this->getTempFilename();
3466 // only save if doing a full import, else we want only the binaries
3469 } elseif(!$part->ifdisposition && $part->type != 1 && $part->type != 2 && $thisBc != '1') {
3470 // No disposition here, but some IMAP servers lie about disposition headers, try to find the truth
3471 // Also Outlook puts inline attachments as type 5 (image) without a disposition
3472 if($part->ifparameters) {
3473 foreach($part->parameters as $param) {
3474 if(strtolower($param->attribute) == "name" || strtolower($param->attribute) == "filename") {
3475 $fname = $this->handleEncodedFilename($param->value);
3479 if(empty($fname)) continue;
3481 // we assume that named parts are attachments too
3482 $attach = $this->getNoteBeanForAttachment($emailId);
3484 $attach->filename = $attach->name = $fname;
3485 $attach->file_mime_type = $this->getMimeType($part->type, $part->subtype);
3487 $attach->safeAttachmentName();
3489 $attach->id = $this->getTempFilename();
3491 // only save if doing a full import, else we want only the binaries
3496 $this->saveAttachmentBinaries($attach, $msgNo, $thisBc, $part, $forDisplay);
3501 * Return a new note object for attachments.
3503 * @param string $emailId
3506 function getNoteBeanForAttachment($emailId)
3508 $attach = new Note();
3509 $attach->parent_id = $emailId;
3510 $attach->parent_type = 'Emails';
3516 * Return the filename of the attachment by examining the dparameters or parameters returned from imap_fetch_structure
3518 * @param object $part
3521 function retrieveAttachmentNameFromStructure($part)
3525 foreach ($part->dparamaters as $k => $v)
3527 if( strtolower($v->attribute) == 'filename')
3529 $result = $v->value;
3534 if (empty($result)) {
3535 foreach ($part->parameters as $k => $v) {
3536 if (strtolower($v->attribute) == 'name') {
3537 $result = $v->value;
3547 * saves the actual binary file of a given attachment
3548 * @param object attach Note object that is attached to the binary file
3549 * @param string msgNo Message Number on IMAP/POP3 server
3550 * @param string thisBc Breadcrumb to navigate email structure to find the content
3551 * @param object part IMAP standard object that contains the "parts" of this section of email
3552 * @param bool $forDisplay
3554 function saveAttachmentBinaries($attach, $msgNo, $thisBc, $part, $forDisplay) {
3555 // decide where to place the file temporarily
3556 $uploadDir = ($forDisplay) ? "{$this->EmailCachePath}/{$this->id}/attachments/" : "upload://";
3558 // decide what name to save file as
3559 $fileName = $attach->id;
3561 // download the attachment if we didn't do it yet
3562 if(!file_exists($uploadDir.$fileName)) {
3563 $msgPartRaw = imap_fetchbody($this->conn, $msgNo, $thisBc);
3564 // deal with attachment encoding and decode the text string
3565 $msgPart = $this->handleTranserEncoding($msgPartRaw, $part->encoding);
3567 if(file_put_contents($uploadDir.$fileName, $msgPart)) {
3568 $GLOBALS['log']->debug('InboundEmail saved attachment file: '.$attach->filename);
3570 $GLOBALS['log']->debug('InboundEmail could not create attachment file: '.$attach->filename ." - temp file target: [ {$uploadDir}{$fileName} ]");
3575 $this->tempAttachment[$fileName] = urldecode($attach->filename);
3576 // if all was successful, feel for inline and cache Note ID for display:
3577 if((strtolower($part->disposition) == 'inline' && in_array($part->subtype, $this->imageTypes))
3578 || ($part->type == 5)) {
3579 if(copy($uploadDir.$fileName, sugar_cached("images/{$fileName}.").strtolower($part->subtype))) {
3580 $id = substr($part->id, 1, -1); //strip <> around
3581 $this->inlineImages[$id] = $attach->id.".".strtolower($part->subtype);
3583 $GLOBALS['log']->debug('InboundEmail could not copy '.$uploadDir.$fileName.' to cache');
3589 * decodes a string based on its associated encoding
3590 * if nothing is passed, we default to no-encoding type
3591 * @param $str encoded string
3592 * @param $enc detected encoding
3594 function handleTranserEncoding($str, $enc=0) {
3600 $ret = base64_decode($str);
3602 case 4:// QUOTED-PRINTABLE
3603 $ret = quoted_printable_decode($str);
3605 case 0:// 7BIT or 8BIT
3606 case 1:// already in a string-useable format - do nothing
3608 default:// catch all
3618 * Some emails do not get assigned a message_id, specifically from
3621 * We need to derive a reliable one for duplicate import checking.
3623 function getMessageId($header) {
3624 $message_id = md5(print_r($header, true));
3629 * checks for duplicate emails on polling. The uniqueness of a given email message is determined by a concatenation
3630 * of 2 values, the messageID and the delivered-to field. This allows multiple To: and B/CC: destination addresses
3631 * to be imported by Sugar without violating the true duplicate-email issues.
3633 * @param string message_id message ID generated by sending server
3634 * @param int message number (mailserver's key) of email
3635 * @param object header object generated by imap_headerinfo()
3636 * @param string textHeader Headers in normal text format
3639 function importDupeCheck($message_id, $header, $textHeader) {
3640 $GLOBALS['log']->debug('*********** InboundEmail doing dupe check.');
3642 // generate "delivered-to" seed for email duplicate check
3643 $deliveredTo = $this->id; // cn: bug 12236 - cc's failing dupe check
3644 $exHeader = explode("\n", $textHeader);
3646 foreach($exHeader as $headerLine) {
3647 if(strpos(strtolower($headerLine), 'delivered-to:') !== false) {
3648 $deliveredTo = substr($headerLine, strpos($headerLine, " "), strlen($headerLine));
3649 $GLOBALS['log']->debug('********* InboundEmail found [ '.$deliveredTo.' ] as the destination address for email [ '.$message_id.' ]');
3650 } elseif(strpos(strtolower($headerLine), 'x-real-to:') !== false) {
3651 $deliveredTo = substr($headerLine, strpos($headerLine, " "), strlen($headerLine));
3652 $GLOBALS['log']->debug('********* InboundEmail found [ '.$deliveredTo.' ] for non-standards compliant email x-header [ '.$message_id.' ]');
3656 //if(empty($message_id) && !isset($message_id)) {
3657 if(empty($message_id) || !isset($message_id)) {
3658 $GLOBALS['log']->debug('*********** NO MESSAGE_ID.');
3659 $message_id = $this->getMessageId($header);
3662 // generate compound messageId
3663 $this->compoundMessageId = trim($message_id).trim($deliveredTo);
3664 if (empty($this->compoundMessageId)) {
3665 $GLOBALS['log']->error('Inbound Email found a message without a header and message_id');
3668 $this->compoundMessageId = md5($this->compoundMessageId);
3670 $query = 'SELECT count(emails.id) AS c FROM emails WHERE emails.message_id = \''.$this->compoundMessageId.'\' and emails.deleted = 0';
3671 $r = $this->db->query($query, true);
3672 $a = $this->db->fetchByAssoc($r);
3675 $GLOBALS['log']->debug('InboundEmail found a duplicate email with ID ('.$this->compoundMessageId.')');
3676 return false; // we have a dupe and don't want to import the email'
3683 * takes the output from imap_mime_hader_decode() and handles multiple types of encoding
3684 * @param string subject Raw subject string from email
3685 * @return string ret properly formatted UTF-8 string
3687 function handleMimeHeaderDecode($subject) {
3688 $subjectDecoded = imap_mime_header_decode($subject);
3691 foreach($subjectDecoded as $object) {
3692 if($object->charset != 'default') {
3693 $ret .= $this->handleCharsetTranslation($object->text, $object->charset);
3695 $ret .= $object->text;
3702 * Calculates the appropriate display date/time sent for an email.
3703 * @param string headerDate The date sent of email in MIME header format
3704 * @return string GMT-0 Unix timestamp
3706 function getUnixHeaderDate($headerDate) {
3709 if (empty($headerDate)) {
3712 ///////////////////////////////////////////////////////////////////
3713 //// CALCULATE CORRECT SENT DATE/TIME FOR EMAIL
3714 if(!empty($headerDate)) {
3715 // Bug 25254 - Strip trailing space that come in some header dates (maybe ones with 1-digit day number)
3716 $headerDate = trim($headerDate);
3717 // need to hack PHP/windows' bad handling of strings when using POP3
3718 if(strstr($headerDate,'+0000 GMT')) {
3719 $headerDate = str_replace('GMT','', $headerDate);
3720 } elseif(!strtotime($headerDate)) {
3721 $headerDate = 'now'; // catch non-standard format times.
3723 // cn: bug 9196 parse the GMT offset
3724 if(strpos($headerDate, '-') || strpos($headerDate, '+')) {
3725 // cn: bug make sure last 5 chars are [+|-]nnnn
3726 if(strpos($headerDate, "(")) {
3727 $headerDate = preg_replace('/\([\w]+\)/i', "", $headerDate);
3728 $headerDate = trim($headerDate);
3731 // parse mailserver time
3732 $gmtEmail = trim(substr($headerDate, -5, 5));
3733 $posNeg = substr($gmtEmail, 0, 1);
3734 $gmtHours = substr($gmtEmail, 1, 2);
3735 $gmtMins = substr($gmtEmail, -2, 2);
3738 $secsHours = $gmtHours * 60 * 60;
3739 $secsTotal = $secsHours + ($gmtMins * 60);
3740 $secsTotal = ($posNeg == '-') ? $secsTotal : -1 * $secsTotal;
3742 $headerDate = trim(substr_replace($headerDate, '', -5)); // mfh: bug 10961/12855 - date time values with GMT offsets not properly formatted
3746 $headerDate = 'now';
3749 $unixHeaderDate = strtotime($headerDate);
3751 if(isset($secsTotal)) {
3752 // this gets the timestamp to true GMT-0
3753 $unixHeaderDate += $secsTotal;
3756 if(strtotime('Jan 1, 2001') > $unixHeaderDate) {
3757 $unixHeaderDate = strtotime('now');
3760 return $unixHeaderDate;
3761 //// END CALCULATE CORRECT SENT DATE/TIME FOR EMAIL
3762 ///////////////////////////////////////////////////////////////////
3766 * This method returns the correct messageno for the pop3 protocol
3767 * @param String UIDL
3768 * @return returnMsgNo
3770 function getCorrectMessageNoForPop3($messageId) {
3772 if ($this->protocol == 'pop3') {
3773 if($this->pop3_open()) {
3774 // get the UIDL from database;
3775 $query = "SELECT msgno FROM email_cache WHERE ie_id = '{$this->id}' AND message_id = '{$messageId}'";
3776 $r = $this->db->query($query);
3777 $a = $this->db->fetchByAssoc($r);
3778 $msgNo = $a['msgno'];
3779 $returnMsgNo = $msgNo;
3782 $this->pop3_sendCommand("USER", $this->email_user);
3783 $this->pop3_sendCommand("PASS", $this->email_password);
3785 // get UIDL for this msgNo
3786 $this->pop3_sendCommand("UIDL {$msgNo}", '', false); // leave socket buffer alone until the while()
3787 $buf = fgets($this->pop3socket, 1024); // handle "OK+ msgNo UIDL(UIDL for this messageno)";
3789 // if it returns OK then we have found the message else get all the UIDL
3790 // and search for the correct msgNo;
3791 $foundMessageNo = false;
3792 if (preg_match("/OK/", $buf) > 0) {
3793 $mailserverResponse = explode(" ", $buf);
3794 // if the cachedUIDL and the UIDL from mail server matches then its the correct messageno
3795 if (trim($mailserverResponse[sizeof($mailserverResponse) - 1]) == $messageId) {
3796 $foundMessageNo = true;
3800 //get all the UIDL and then find the correct messageno
3801 if (!$foundMessageNo) {
3803 $this->pop3_sendCommand("UIDL", '', false); // leave socket buffer alone until the while()
3804 fgets($this->pop3socket, 1024); // handle "OK+";
3807 if(is_resource($this->pop3socket)) {
3808 while(!feof($this->pop3socket)) {
3809 $buf = fgets($this->pop3socket, 1024); // 8kb max buffer - shouldn't be more than 80 chars via pop3...
3810 if(trim($buf) == '.') {
3811 $GLOBALS['log']->debug("*** GOT '.'");
3814 // format is [msgNo] [UIDL]
3815 $exUidl = explode(" ", $buf);
3816 $UIDLs[trim($exUidl[1])] = trim($exUidl[0]);
3818 if (array_key_exists($messageId, $UIDLs)) {
3819 $returnMsgNo = $UIDLs[$messageId];
3821 // message could not be found on server
3827 $this->pop3_cleanUp();
3830 return $returnMsgNo;
3834 * If the importOneEmail returns false, then findout if the duplicate email
3836 function getDuplicateEmailId($msgNo, $uid) {
3838 global $app_strings;
3839 global $app_list_strings;
3840 global $sugar_config;
3841 global $current_user;
3843 $header = imap_headerinfo($this->conn, $msgNo);
3844 $fullHeader = imap_fetchheader($this->conn, $msgNo); // raw headers
3846 // reset inline images cache
3847 $this->inlineImages = array();
3849 // handle messages deleted on server
3850 if(empty($header)) {
3851 if(!isset($this->email) || empty($this->email)) {
3852 $this->email = new Email();
3856 $dupeCheckResult = $this->importDupeCheck($header->message_id, $header, $fullHeader);
3857 if (!$dupeCheckResult && !empty($this->compoundMessageId)) {
3858 // we have a duplicate email
3859 $query = 'SELECT id FROM emails WHERE emails.message_id = \''.$this->compoundMessageId.'\' and emails.deleted = 0';
3860 $r = $this->db->query($query, true);
3861 $a = $this->db->fetchByAssoc($r);
3863 $this->email = new Email();
3864 $this->email->id = $a['id'];
3873 * shiny new importOneEmail() method
3875 * @param bool forDisplay
3876 * @param clean_email boolean, default true,
3878 function importOneEmail($msgNo, $uid, $forDisplay=false, $clean_email=true) {
3879 $GLOBALS['log']->debug("InboundEmail processing 1 email {$msgNo}-----------------------------------------------------------------------------------------");
3881 global $app_strings;
3882 global $app_list_strings;
3883 global $sugar_config;
3884 global $current_user;
3887 // So, on older versions of PHP (PHP VERSION < 5.3),
3888 // calling imap_headerinfo and imap_fetchheader can cause a buffer overflow for exteremly large headers,
3889 // This leads to the remaining messages not being read because Sugar crashes everytime it tries to read the headers.
3890 // The workaround is to mark a message as read before making trying to read the header of the msg in question
3891 // This forces this message not be read again, and we can continue processing remaining msgs.
3893 // UNCOMMENT THIS IF YOU HAVE THIS PROBLEM! See notes on Bug # 45477
3894 // $this->markEmails($uid, "read");
3896 $header = imap_headerinfo($this->conn, $msgNo);
3897 $fullHeader = imap_fetchheader($this->conn, $msgNo); // raw headers
3899 // reset inline images cache
3900 $this->inlineImages = array();
3902 // handle messages deleted on server
3903 if(empty($header)) {
3904 if(!isset($this->email) || empty($this->email)) {
3905 $this->email = new Email();
3909 if ($this->isPop3Protocol()) {
3910 $this->email->name = $app_strings['LBL_EMAIL_ERROR_MESSAGE_DELETED'];
3911 $q = "DELETE FROM email_cache WHERE message_id = '{$uid}' AND ie_id = '{$this->id}' AND mbox = '{$this->mailbox}'";
3913 $this->email->name = $app_strings['LBL_EMAIL_ERROR_IMAP_MESSAGE_DELETED'];
3914 $q = "DELETE FROM email_cache WHERE imap_uid = {$uid} AND ie_id = '{$this->id}' AND mbox = '{$this->mailbox}'";
3916 // delete local cache
3917 $r = $this->db->query($q);
3919 $this->email->date_sent = $timedate->nowDb();
3921 //return "Message deleted from server.";
3924 ///////////////////////////////////////////////////////////////////////
3925 //// DUPLICATE CHECK
3926 $dupeCheckResult = $this->importDupeCheck($header->message_id, $header, $fullHeader);
3927 if($forDisplay || $dupeCheckResult) {
3928 $GLOBALS['log']->debug('*********** NO duplicate found, continuing with processing.');
3930 $structure = imap_fetchstructure($this->conn, $msgNo); // map of email
3932 ///////////////////////////////////////////////////////////////////
3933 //// CREATE SEED EMAIL OBJECT
3934 $email = new Email();
3935 $email->isDuplicate = ($dupeCheckResult) ? false : true;
3936 $email->mailbox_id = $this->id;
3938 $email->id = create_guid();
3939 $email->new_with_id = true; //forcing a GUID here to prevent double saves.
3940 //// END CREATE SEED EMAIL
3941 ///////////////////////////////////////////////////////////////////
3943 ///////////////////////////////////////////////////////////////////
3944 //// PREP SYSTEM USER
3945 if(empty($current_user)) {
3946 // I-E runs as admin, get admin prefs
3948 $current_user = new User();
3949 $current_user->getSystemUser();
3951 $tPref = $current_user->getUserDateTimePreferences();
3953 ///////////////////////////////////////////////////////////////////
3954 if(!empty($header->date)) {
3955 $unixHeaderDate = $timedate->fromString($header->date);
3957 ///////////////////////////////////////////////////////////////////
3958 //// HANDLE EMAIL ATTACHEMENTS OR HTML TEXT
3959 //// Inline images require that I-E handle attachments before body text
3960 // parts defines attachments - be mindful of .html being interpreted as an attachment
3961 if($structure->type == 1 && !empty($structure->parts)) {
3962 $GLOBALS['log']->debug('InboundEmail found multipart email - saving attachments if found.');
3963 $this->saveAttachments($msgNo, $structure->parts, $email->id, 0, $forDisplay);
3964 } elseif($structure->type == 0) {
3965 $uuemail = ($this->isUuencode($email->description)) ? true : false;
3967 * UUEncoded attachments - legacy, but still have to deal with it
3969 * begin 777 filename.txt
3974 // set body to the filtered one
3976 $email->description = $this->handleUUEncodedEmailBody($email->description, $email->id);
3977 $email->retrieve($email->id);
3981 if($this->port != 110) {
3982 $GLOBALS['log']->debug('InboundEmail found a multi-part email (id:'.$msgNo.') with no child parts to parse.');
3985 //// END HANDLE EMAIL ATTACHEMENTS OR HTML TEXT
3986 ///////////////////////////////////////////////////////////////////
3988 ///////////////////////////////////////////////////////////////////
3989 //// ASSIGN APPROPRIATE ATTRIBUTES TO NEW EMAIL OBJECT
3990 // handle UTF-8/charset encoding in the ***headers***
3992 $email->name = $this->handleMimeHeaderDecode($header->subject);
3993 $email->type = 'inbound';
3994 if(!empty($unixHeaderDate)) {
3995 $email->date_sent = $timedate->asUser($unixHeaderDate);
3996 list($email->date_start, $email->time_start) = $timedate->split_date_time($email->date_sent);
3998 $email->date_start = $email->time_start = $email->date_sent = "";
4000 $email->status = 'unread'; // this is used in Contacts' Emails SubPanel
4001 if(!empty($header->toaddress)) {
4002 $email->to_name = $this->handleMimeHeaderDecode($header->toaddress);
4003 $email->to_addrs_names = $email->to_name;
4005 if(!empty($header->to)) {
4006 $email->to_addrs = $this->convertImapToSugarEmailAddress($header->to);
4008 $email->from_name = $this->handleMimeHeaderDecode($header->fromaddress);
4009 $email->from_addr_name = $email->from_name;
4010 $email->from_addr = $this->convertImapToSugarEmailAddress($header->from);
4011 if(!empty($header->cc)) {
4012 $email->cc_addrs = $this->convertImapToSugarEmailAddress($header->cc);
4014 if(!empty($header->ccaddress)) {
4015 $email->cc_addrs_names = $this->handleMimeHeaderDecode($header->ccaddress);
4017 $email->reply_to_name = $this->handleMimeHeaderDecode($header->reply_toaddress);
4018 $email->reply_to_email = $this->convertImapToSugarEmailAddress($header->reply_to);
4019 if (!empty($email->reply_to_email)) {
4020 $email->reply_to_addr = $email->reply_to_name;
4022 $email->intent = $this->mailbox_type;
4024 $email->message_id = $this->compoundMessageId; // filled by importDupeCheck();
4026 $oldPrefix = $this->imagePrefix;
4028 // Store CIDs in imported messages, convert on display
4029 $this->imagePrefix = "cid:";
4031 // handle multi-part email bodies
4032 $email->description_html= $this->getMessageText($msgNo, 'HTML', $structure, $fullHeader,$clean_email); // runs through handleTranserEncoding() already
4033 $email->description = $this->getMessageText($msgNo, 'PLAIN', $structure, $fullHeader,$clean_email); // runs through handleTranserEncoding() already
4034 $this->imagePrefix = $oldPrefix;
4036 // empty() check for body content
4037 if(empty($email->description)) {
4038 $GLOBALS['log']->debug('InboundEmail Message (id:'.$email->message_id.') has no body');
4042 if (!empty($_REQUEST['user_id'])) {
4043 $email->assigned_user_id = $_REQUEST['user_id'];
4045 // Samir Gandhi : Commented out this code as its not needed
4046 //$email->assigned_user_id = $this->group_id;
4049 //Assign Parent Values if set
4050 if (!empty($_REQUEST['parent_id']) && !empty($_REQUEST['parent_type'])) {
4051 $email->parent_id = $_REQUEST['parent_id'];
4052 $email->parent_type = $_REQUEST['parent_type'];
4054 $mod = strtolower($email->parent_type);
4055 $rel = array_key_exists($mod, $email->field_defs) ? $mod : $mod . "_activities_emails"; //Custom modules rel name
4057 if(! $email->load_relationship($rel) )
4059 $email->$rel->add($email->parent_id);
4062 // override $forDisplay w/user pref
4064 if($this->isAutoImport()) {
4065 $forDisplay = false; // triggers save of imported email
4072 $email->new_with_id = false; // to allow future saves by UPDATE, instead of INSERT
4073 //// ASSIGN APPROPRIATE ATTRIBUTES TO NEW EMAIL OBJECT
4074 ///////////////////////////////////////////////////////////////////
4076 ///////////////////////////////////////////////////////////////////
4077 //// LINK APPROPRIATE BEANS TO NEWLY SAVED EMAIL
4078 //$contactAddr = $this->handleLinking($email);
4079 //// END LINK APPROPRIATE BEANS TO NEWLY SAVED EMAIL
4080 ///////////////////////////////////////////////////////////////////
4082 ///////////////////////////////////////////////////////////////////
4083 //// MAILBOX TYPE HANDLING
4084 $this->handleMailboxType($email, $header);
4085 //// END MAILBOX TYPE HANDLING
4086 ///////////////////////////////////////////////////////////////////
4088 ///////////////////////////////////////////////////////////////////
4089 //// SEND AUTORESPONSE
4090 if(!empty($email->reply_to_email)) {
4091 $contactAddr = $email->reply_to_email;
4093 $contactAddr = $email->from_addr;
4095 if (!$this->isMailBoxTypeCreateCase()) {
4096 $this->handleAutoresponse($email, $contactAddr);
4098 //// END SEND AUTORESPONSE
4099 ///////////////////////////////////////////////////////////////////
4100 //// END IMPORT ONE EMAIL
4101 ///////////////////////////////////////////////////////////////////
4104 // only log if not POP3; pop3 iterates through ALL mail
4105 if($this->protocol != 'pop3') {
4106 $GLOBALS['log']->info("InboundEmail found a duplicate email: ".$header->message_id);
4107 //echo "This email has already been imported";
4111 //// END DUPLICATE CHECK
4112 ///////////////////////////////////////////////////////////////////////
4114 ///////////////////////////////////////////////////////////////////////
4115 //// DEAL WITH THE MAILBOX
4117 $r = imap_setflag_full($this->conn, $msgNo, '\\SEEN');
4119 // if delete_seen, mark msg as deleted
4120 if($this->delete_seen == 1 && !$forDisplay) {
4121 $GLOBALS['log']->info("INBOUNDEMAIL: delete_seen == 1 - deleting email");
4122 imap_setflag_full($this->conn, $msgNo, '\\DELETED');
4125 // for display - don't touch server files?
4126 //imap_setflag_full($this->conn, $msgNo, '\\UNSEEN');
4129 $GLOBALS['log']->debug('********************************* InboundEmail finished import of 1 email: '.$email->name);
4130 //// END DEAL WITH THE MAILBOX
4131 ///////////////////////////////////////////////////////////////////////
4133 ///////////////////////////////////////////////////////////////////////
4134 //// TO SUPPORT EMAIL 2.0
4135 $this->email = $email;
4137 if(empty($this->email->et)) {
4138 $this->email->email2init();
4145 * figures out if a plain text email body has UUEncoded attachments
4146 * @param string string The email body
4147 * @return bool True if UUEncode is detected.
4149 function isUuencode($string) {
4150 $rx = "begin [0-9]{3} .*";
4152 $exBody = explode("\r", $string);
4153 foreach($exBody as $line) {
4154 if(preg_match("/begin [0-9]{3} .*/i", $line)) {
4163 * handles UU Encoded emails - a legacy from pre-RFC 822 which must still be supported (?)
4164 * @param string raw The raw email body
4165 * @param string id Parent email ID
4166 * @return string The filtered email body, stripped of attachments
4168 function handleUUEncodedEmailBody($raw, $id) {
4172 $attachmentBody = '';
4173 $inAttachment = false;
4175 $exRaw = explode("\n", $raw);
4177 foreach($exRaw as $k => $line) {
4178 $line = trim($line);
4180 if(preg_match("/begin [0-9]{3} .*/i", $line, $m)) {
4181 $inAttachment = true;
4182 $fileName = $this->handleEncodedFilename(substr($m[0], 10, strlen($m[0])));
4184 $attachmentBody = ''; // reset for next part of loop;
4189 if(strpos($line, "end") === 0) {
4190 if(!empty($fileName) && !empty($attachmentBody)) {
4191 $this->handleUUDecode($id, $fileName, trim($attachmentBody));
4192 $attachmentBody = ''; // reset for next part of loop;
4196 if($inAttachment === false) {
4197 $emailBody .= "\n".$line;
4199 $attachmentBody .= "\n".$line;
4203 /* since UUEncode was developed before MIME, we have NO idea what character set encoding was used. we will assume the user's locale character set */
4204 $emailBody = $locale->translateCharset($emailBody, $locale->getExportCharset(), 'UTF-8');
4209 * wrapper for UUDecode
4210 * @param string id Id of the email
4211 * @param string UUEncode Encode US-ASCII
4213 function handleUUDecode($id, $fileName, $UUEncode) {
4214 global $sugar_config;
4215 /* include PHP_Compat library; it auto-feels for PHP5's compiled convert_uuencode() function */
4216 require_once('include/PHP_Compat/convert_uudecode.php');
4218 $attach = new Note();
4219 $attach->parent_id = $id;
4220 $attach->parent_type = 'Emails';
4222 $fname = $this->handleEncodedFilename($fileName);
4224 if(!empty($fname)) {//assign name to attachment
4225 $attach->name = $fname;
4226 } else {//if name is empty, default to filename
4227 $attach->name = urlencode($fileName);
4230 $attach->filename = urlencode($attach->name);
4232 //get position of last "." in file name
4233 $file_ext_beg = strrpos($attach->filename,".");
4235 //get file extension
4236 if($file_ext_beg >0) {
4237 $file_ext = substr($attach->filename, $file_ext_beg+1);
4239 //check to see if this is a file with extension located in "badext"
4240 foreach($sugar_config['upload_badext'] as $badExt) {
4241 if(strtolower($file_ext) == strtolower($badExt)) {
4242 //if found, then append with .txt and break out of lookup
4243 $attach->name = $attach->name . ".txt";
4244 $attach->file_mime_type = 'text/';
4245 $attach->filename = $attach->filename . ".txt";
4246 break; // no need to look for more
4251 $bin = convert_uudecode($UUEncode);
4252 $filename = "upload://{$attach->id}";
4253 if(file_put_contents($filename, $bin)) {
4254 $GLOBALS['log']->debug('InboundEmail saved attachment file: '.$filename);
4256 $GLOBALS['log']->debug('InboundEmail could not create attachment file: '.$filename);
4261 * returns true if the email's domain is NOT in the filter domain string
4263 * @param object email Email object in question
4264 * @return bool true if not filtered, false if filtered
4266 function checkFilterDomain($email) {
4267 $filterDomain = $this->get_stored_options('filter_domain');
4268 if(!isset($filterDomain) || empty($filterDomain)) {
4269 return true; // nothing set for this
4271 $replyTo = strtolower($email->reply_to_email);
4272 $from = strtolower($email->from_addr);
4273 $filterDomain = '@'.strtolower($filterDomain);
4274 if(strpos($replyTo, $filterDomain) !== false) {
4275 $GLOBALS['log']->debug('Autoreply cancelled - [reply to] address domain matches filter domain.');
4277 } elseif(strpos($from, $filterDomain) !== false) {
4278 $GLOBALS['log']->debug('Autoreply cancelled - [from] address domain matches filter domain.');
4281 return true; // no match
4287 * returns true if subject is NOT "out of the office" type
4289 * @param string subject Subject line of email in question
4290 * @return bool returns false if OOTO found
4292 function checkOutOfOffice($subject) {
4293 $ooto = array("Out of the Office", "Out of Office");
4295 foreach($ooto as $str) {
4296 if(preg_match('/'.$str.'/i', $subject)) {
4297 $GLOBALS['log']->debug('Autoreply cancelled - found "Out of Office" type of subject.');
4301 return true; // no matches to ooto strings
4306 * sets a timestamp for an autoreply to a single email addy
4308 * @param string addr Address of auto-replied target
4310 function setAutoreplyStatus($addr) {
4311 $timedate = TimeDate::getInstance();
4312 $this->db->query( 'INSERT INTO inbound_email_autoreply (id, deleted, date_entered, date_modified, autoreplied_to, ie_id) VALUES (
4313 \''.create_guid().'\',
4315 \''.$timedate->nowDb().'\',
4316 \''.$timedate->nowDb().'\',
4318 \''.$this->id.'\') ', true);
4323 * returns true if recipient has NOT received 10 auto-replies in 24 hours
4325 * @param string from target address for auto-reply
4326 * @return bool true if target is valid/under limit
4328 function getAutoreplyStatus($from) {
4329 global $sugar_config;
4330 $timedate = TimeDate::getInstance();
4332 $q_clean = 'UPDATE inbound_email_autoreply SET deleted = 1 WHERE date_entered < \''.$timedate->getNow()->modify("-24 hours")->asDb().'\'';
4333 $r_clean = $this->db->query($q_clean, true);
4335 $q = 'SELECT count(*) AS c FROM inbound_email_autoreply WHERE deleted = 0 AND autoreplied_to = \''.$from.'\' AND ie_id = \''.$this->id.'\'';
4336 $r = $this->db->query($q, true);
4337 $a = $this->db->fetchByAssoc($r);
4339 $email_num_autoreplies_24_hours = $this->get_stored_options('email_num_autoreplies_24_hours');
4340 $maxReplies = (isset($email_num_autoreplies_24_hours)) ? $email_num_autoreplies_24_hours : $this->maxEmailNumAutoreplies24Hours;
4342 if($a['c'] >= $maxReplies) {
4343 $GLOBALS['log']->debug('Autoreply cancelled - more than ' . $maxReplies . ' replies sent in 24 hours.');
4351 * returns exactly 1 id match. if more than one, than returns false
4352 * @param $emailName the subject of the email to match
4353 * @param $tableName the table of the matching bean type
4355 function getSingularRelatedId($emailName, $tableName) {
4356 $repStrings = array('RE:','Re:','re:');
4357 $preppedName = str_replace($repStrings,'',trim($emailName));
4359 //TODO add team security to this query
4360 $q = 'SELECT count(id) AS c FROM '.$tableName.' WHERE deleted = 0 AND name LIKE \'%'.$preppedName.'%\'';
4361 $r = $this->db->query($q, true);
4362 $a = $this->db->fetchByAssoc($r);
4365 $q = 'SELECT id FROM '.$tableName.' WHERE deleted = 0 AND name LIKE \'%'.$preppedName.'%\'';
4366 $r = $this->db->query($q, true);
4367 $a = $this->db->fetchByAssoc($r);
4375 * saves InboundEmail parse macros to config.php
4376 * @param string type Bean to link
4377 * @param string macro The new macro
4379 function saveInboundEmailSystemSettings($type, $macro) {
4380 global $sugar_config;
4382 // inbound_email_case_subject_macro
4383 $var = "inbound_email_".strtolower($type)."_subject_macro";
4384 $sugar_config[$var] = $macro;
4386 ksort($sugar_config);
4388 $sugar_config_string = "<?php\n" .
4389 '// created: ' . date('Y-m-d H:i:s') . "\n" .
4390 '$sugar_config = ' .
4391 var_export($sugar_config, true) .
4394 write_array_to_file("sugar_config", $sugar_config, "config.php");
4398 * returns the HTML for InboundEmail system settings
4399 * @return string HTML
4401 function getSystemSettingsForm() {
4402 global $sugar_config;
4403 global $mod_strings;
4404 global $app_strings;
4405 global $app_list_strings;
4410 $macro = $c->getEmailSubjectMacro();
4413 <form action="index.php" method="post" name="Macro" id="form">
4414 <input type="hidden" name="module" value="InboundEmail">
4415 <input type="hidden" name="action" value="ListView">
4416 <input type="hidden" name="save" value="true">
4418 <table width="100%" cellpadding="0" cellspacing="0" border="0">
4421 <input title="{$app_strings['LBL_SAVE_BUTTON_TITLE']}"
4422 accessKey="{$app_strings['LBL_SAVE_BUTTON_KEY']}"
4424 onclick="this.form.return_module.value='InboundEmail'; this.form.return_action.value='ListView';"
4425 type="submit" name="Edit" value=" {$app_strings['LBL_SAVE_BUTTON_LABEL']} ">
4430 <table width="100%" border="0" cellspacing="0" cellpadding="0" class="detail view">
4432 <td valign="top" width='10%' NOWRAP scope="row">
4434 <b>{$mod_strings['LBL_CASE_MACRO']}:</b>
4437 <td valign="top" width='20%'>
4439 <input name="inbound_email_case_macro" type="text" value="{$macro}">
4442 <td valign="top" width='70%'>
4444 {$mod_strings['LBL_CASE_MACRO_DESC']}
4446 <i>{$mod_strings['LBL_CASE_MACRO_DESC2']}</i>
4457 * for mailboxes of type "Support" parse for '[CASE:%1]'
4458 * @param $emailName the subject line of the email
4459 * @param $aCase a Case object
4461 function getCaseIdFromCaseNumber($emailName, $aCase) {
4462 //$emailSubjectMacro
4463 $exMacro = explode('%1', $aCase->getEmailSubjectMacro());
4464 $open = $exMacro[0];
4465 $close = $exMacro[1];
4467 if($sub = stristr($emailName, $open)) { // eliminate everything up to the beginning of the macro and return the rest
4468 // $sub is [CASE:XX] xxxxxxxxxxxxxxxxxxxxxx
4469 $sub2 = str_replace($open, '', $sub);
4470 // $sub2 is XX] xxxxxxxxxxxxxx
4471 $sub3 = substr($sub2, 0, strpos($sub2, $close));
4473 // filter out deleted records in order to create a new case
4474 // if email is related to deleted one (bug #49840)
4475 $r = $this->db->query("SELECT id FROM cases WHERE case_number = '{$sub3}' and deleted = 0", true);
4476 $a = $this->db->fetchByAssoc($r);
4477 if(!empty($a['id'])) {
4487 function get_stored_options($option_name,$default_value=null,$stored_options=null) {
4488 if (empty($stored_options)) {
4489 $stored_options=$this->stored_options;
4491 if(!empty($stored_options)) {
4492 $storedOptions = unserialize(base64_decode($stored_options));
4493 if (isset($storedOptions[$option_name])) {
4494 $default_value=$storedOptions[$option_name];
4497 return $default_value;
4502 * This function returns a contact or user ID if a matching email is found
4503 * @param $email the email address to match
4504 * @param $table which table to query
4506 function getRelatedId($email, $module) {
4507 $email = trim(strtoupper($email));
4508 if(strpos($email, ',') !== false) {
4509 $emailsArray = explode(',', $email);
4510 $emailAddressString = "";
4511 foreach($emailsArray as $emailAddress) {
4512 if (!empty($emailAddressString)) {
4513 $emailAddressString .= ",";
4515 $emailAddressString .= "'" . $emailAddress. "'";
4517 $email = $emailAddressString;
4519 $email = "'" . $email . "'";
4521 $module = ucfirst($module);
4523 $q = "SELECT bean_id FROM email_addr_bean_rel eabr
4524 JOIN email_addresses ea ON (eabr.email_address_id = ea.id)
4525 WHERE bean_module = '{$module}' AND ea.email_address_caps in ( {$email} ) AND eabr.deleted=0";
4527 $r = $this->db->query($q, true);
4530 while($a = $this->db->fetchByAssoc($r)) {
4531 $retArr[] = $a['bean_id'];
4533 if(count($retArr) > 0) {
4541 * finds emails tagged "//UNSEEN" on mailserver and "SINCE: [date]" if that
4544 * @return array Array of messageNumbers (mail server's internal keys)
4546 function getNewMessageIds() {
4547 $storedOptions = unserialize(base64_decode($this->stored_options));
4549 //TODO figure out if the since date is UDT
4550 if($storedOptions['only_since']) {// POP3 does not support Unseen flags
4551 if(!isset($storedOptions['only_since_last']) && !empty($storedOptions['only_since_last'])) {
4552 $q = 'SELECT last_run FROM schedulers WHERE job = \'function::pollMonitoredInboxes\'';
4553 $r = $this->db->query($q, true);
4554 $a = $this->db->fetchByAssoc($r);
4556 $date = date('r', strtotime($a['last_run']));
4558 $date = $storedOptions['only_since_last'];
4560 $ret = imap_search($this->conn, 'SINCE "'.$date.'" UNDELETED UNSEEN');
4561 $check = imap_check($this->conn);
4562 $storedOptions['only_since_last'] = $check->Date;
4563 $this->stored_options = base64_encode(serialize($storedOptions));
4566 $ret = imap_search($this->conn, 'UNDELETED UNSEEN');
4569 $GLOBALS['log']->debug('-----> getNewMessageIds() got '.count($ret).' new Messages');
4574 * Constructs the resource connection string that IMAP needs
4575 * @param string $service Service string, will generate if not passed
4578 function getConnectString($service='', $mbox='', $includeMbox=true) {
4579 $service = empty($service) ? $this->getServiceString() : $service;
4580 $mbox = empty($mbox) ? $this->mailbox : $mbox;
4582 $connectString = '{'.$this->server_url.':'.$this->port.'/service='.$this->protocol.$service.'}';
4583 $connectString .= ($includeMbox) ? $mbox : "";
4585 return $connectString;
4588 function disconnectMailserver() {
4589 if(is_resource($this->conn)) {
4590 imap_close($this->conn);
4595 * Connects to mailserver. If an existing IMAP resource is available, it
4596 * will attempt to reuse the connection, updating the mailbox path.
4598 * @param bool test Flag to test connection
4599 * @param bool force Force reconnect
4600 * @return string "true" on success, "false" or $errorMessage on failure
4602 function connectMailserver($test=false, $force=false) {
4603 global $mod_strings;
4604 if(!function_exists("imap_open")) {
4605 $GLOBALS['log']->debug('------------------------- IMAP libraries NOT available!!!! die()ing thread.----');
4606 return $mod_strings['LBL_WARN_NO_IMAP'];
4609 imap_errors(); // clearing error stack
4610 error_reporting(0); // turn off notices from IMAP
4612 // tls::ca::ssl::protocol::novalidate-cert::notls
4613 $useSsl = ($_REQUEST['ssl'] == 'true') ? true : false;
4615 imap_timeout(1, 15); // 60 secs is the default
4616 imap_timeout(2, 15);
4617 imap_timeout(3, 15);
4619 $opts = $this->findOptimumSettings($useSsl);
4620 if(isset($opts['good']) && empty($opts['good'])) {
4621 return array_pop($opts['err']);
4623 $service = $opts['service'];
4624 $service = str_replace('foo','', $service); // foo there to support no-item explodes
4627 $service = $this->getServiceString();
4630 $connectString = $this->getConnectString($service, $this->mailbox);
4633 * Try to recycle the current connection to reduce response times
4635 if(is_resource($this->conn)) {
4638 imap_close($this->conn);
4641 if(imap_ping($this->conn)) {
4642 // we have a live connection
4643 imap_reopen($this->conn, $connectString, CL_EXPUNGE);
4648 if(!is_resource($this->conn) && !$test) {
4649 $this->conn = imap_open($connectString, $this->email_user, $this->email_password, CL_EXPUNGE);
4653 if ($opts == false && !is_resource($this->conn)) {
4654 $this->conn = imap_open($connectString, $this->email_user, $this->email_password, CL_EXPUNGE);
4658 $successful = false;
4659 if(($errors = imap_last_error()) || ($alerts = imap_alerts())) {
4660 if($errors == 'Mailbox is empty') { // false positive
4664 $msg .= '<p>'.$alerts.'<p>';
4665 $msg .= '<p>'.$mod_strings['ERR_TEST_MAILBOX'];
4672 if($this->protocol == 'imap') {
4673 $msg .= $mod_strings['LBL_TEST_SUCCESSFUL'];
4675 $testConnectString = '{'.$this->server_url.':'.$this->port.'/service='.$this->protocol.$service.'}';
4676 if (!is_resource($this->conn)) {
4677 $this->conn = imap_open($connectString, $this->email_user, $this->email_password, CL_EXPUNGE);
4679 $list = imap_getmailboxes($this->conn, $testConnectString, "*");
4680 if(isset($_REQUEST['personal']) && $_REQUEST['personal'] == 'true') {
4681 $msg .= $mod_strings['LBL_TEST_SUCCESSFUL'];
4682 } elseif (is_array($list)) {
4686 $msg .= '<b>'.$mod_strings['LBL_FOUND_MAILBOXES'].'</b><p>';
4687 foreach ($list as $key => $val) {
4688 $mb = imap_utf7_decode(str_replace($testConnectString,'',$val->name));
4689 $msg .= '<a onClick=\'setMailbox(\"'.$mb.'\"); window.close();\'>';
4695 $msg .= '<p>'.$mod_strings['ERR_MAILBOX_FAIL'].imap_last_error().'</p>';
4696 $msg .= '<p>'.$mod_strings['ERR_TEST_MAILBOX'].'</p>';
4700 $msg .= $mod_strings['LBL_POP3_SUCCESS'];
4704 imap_errors(); // collapse error stack
4705 imap_close($this->conn);
4707 } elseif(!is_resource($this->conn)) {
4716 function checkImap() {
4717 global $mod_strings;
4719 if(!function_exists('imap_open')) {
4721 <table cellpadding="0" cellspacing="0" width="100%" border="0" class="list view">
4723 <td scope="col" width="25%" colspan="2"><slot>
4724 '.$mod_strings['LBL_WARN_IMAP_TITLE'].'
4728 <td scope="row" valign=TOP bgcolor="#fdfdfd" width="20%"><slot>
4729 '.$mod_strings['LBL_WARN_IMAP'].'
4730 <td scope="row" valign=TOP class="oddListRowS1" bgcolor="#fdfdfd" width="80%"><slot>
4731 <span class=error>'.$mod_strings['LBL_WARN_NO_IMAP'].'</span>
4740 * retrieves an array of I-E beans based on the group_id
4741 * @param string $groupId GUID of the group user or Individual
4742 * @return array $beans array of beans
4743 * @return boolean false if none returned
4745 function retrieveByGroupId($groupId) {
4746 $q = 'SELECT id FROM inbound_email WHERE group_id = \''.$groupId.'\' AND deleted = 0 AND status = \'Active\'';
4747 $r = $this->db->query($q, true);
4750 while($a = $this->db->fetchByAssoc($r)) {
4751 $ie = new InboundEmail();
4752 $ie->retrieve($a['id']);
4753 $beans[$a['id']] = $ie;
4759 * Retrieves the current count of personal accounts for the user specified.
4761 * @param unknown_type $user
4763 function getUserPersonalAccountCount($user = null)
4766 $user = $GLOBALS['current_user'];
4768 $query = "SELECT count(*) as c FROM inbound_email WHERE deleted=0 AND is_personal='1' AND group_id='{$user->id}' AND status='Active'";
4770 $rs = $this->db->query($query);
4771 $row = $this->db->fetchByAssoc($rs);
4776 * retrieves an array of I-E beans based on the group folder id
4777 * @param string $groupFolderId GUID of the group folder
4778 * @return array $beans array of beans
4779 * @return boolean false if none returned
4781 function retrieveByGroupFolderId($groupFolderId) {
4782 $q = 'SELECT id FROM inbound_email WHERE groupfolder_id = \''.$groupFolderId.'\' AND deleted = 0 ';
4783 $r = $this->db->query($q, true);
4786 while($a = $this->db->fetchByAssoc($r)) {
4787 $ie = new InboundEmail();
4788 $ie->retrieve($a['id']);
4795 * Retrieves an array of I-E beans that the user has team access to
4797 function retrieveAllByGroupId($id, $includePersonal=true) {
4798 global $current_user;
4800 $beans = ($includePersonal) ? $this->retrieveByGroupId($id) : array();
4806 // bug 50536: groupfolder_id cannot be updated to NULL from sugarbean's nullable check ('type' set to ID in the vardef)
4807 // hence the awkward or check -- rbacon
4808 $q = "SELECT inbound_email.id FROM inbound_email {$teamJoin} WHERE is_personal = 0 AND (groupfolder_id is null OR groupfolder_id = '') AND mailbox_type not like 'bounce' AND inbound_email.deleted = 0 AND status = 'Active' ";
4812 $r = $this->db->query($q, true);
4814 while($a = $this->db->fetchByAssoc($r)) {
4816 foreach($beans as $bean) {
4817 if($bean->id == $a['id']) {
4823 $ie = new InboundEmail();
4824 $ie->retrieve($a['id']);
4825 $beans[$a['id']] = $ie;
4833 * Retrieves an array of I-E beans that the user has team access to including group
4835 function retrieveAllByGroupIdWithGroupAccounts($id, $includePersonal=true) {
4836 global $current_user;
4838 $beans = ($includePersonal) ? $this->retrieveByGroupId($id) : array();
4847 $q = "SELECT DISTINCT inbound_email.id FROM inbound_email {$teamJoin} WHERE is_personal = 0 AND mailbox_type not like 'bounce' AND status = 'Active' AND inbound_email.deleted = 0 ";
4849 $r = $this->db->query($q, true);
4851 while($a = $this->db->fetchByAssoc($r)) {
4853 foreach($beans as $bean) {
4854 if($bean->id == $a['id']) {
4860 $ie = new InboundEmail();
4861 $ie->retrieve($a['id']);
4862 $beans[$a['id']] = $ie;
4871 * returns the bean name - overrides SugarBean's
4873 function get_summary_text() {
4878 * Override's SugarBean's
4880 function create_export_query($order_by, $where, $show_deleted = 0) {
4881 return $this->create_new_list_query($order_by, $where, $show_deleted = 0);
4885 * Override's SugarBean's
4889 * Override's SugarBean's
4891 function get_list_view_data(){
4892 global $mod_strings;
4893 global $app_list_strings;
4894 $temp_array = $this->get_list_view_array();
4895 $temp_array['MAILBOX_TYPE_NAME']= $app_list_strings['dom_mailbox_type'][$this->mailbox_type];
4896 //cma, fix bug 21670.
4897 $temp_array['GLOBAL_PERSONAL_STRING']= ($this->is_personal ? $mod_strings['LBL_IS_PERSONAL'] : $mod_strings['LBL_IS_GROUP']);
4898 $temp_array['STATUS'] = ($this->status == 'Active') ? $mod_strings['LBL_STATUS_ACTIVE'] : $mod_strings['LBL_STATUS_INACTIVE'];
4903 * Override's SugarBean's
4905 function fill_in_additional_list_fields() {
4906 $this->fill_in_additional_detail_fields();
4910 * Override's SugarBean's
4912 function fill_in_additional_detail_fields() {
4913 if(!empty($this->service)) {
4914 $exServ = explode('::', $this->service);
4915 $this->tls = $exServ[0];
4916 if ( isset($exServ[1]) )
4917 $this->ca = $exServ[1];
4918 if ( isset($exServ[2]) )
4919 $this->ssl = $exServ[2];
4920 if ( isset($exServ[3]) )
4921 $this->protocol = $exServ[3];
4938 ///////////////////////////////////////////////////////////////////////////
4939 //// IN SUPPORT OF EMAIL 2.0
4941 * Checks for $user's autoImport setting and returns the current value
4942 * @param object $user User in focus, defaults to $current_user
4945 function isAutoImport($user=null) {
4946 if(!empty($this->autoImport)) {
4947 return $this->autoImport;
4950 global $current_user;
4951 if(empty($user)) $user = $current_user;
4953 $emailSettings = $current_user->getPreference('emailSettings', 'Emails');
4954 $emailSettings = is_string($emailSettings) ? unserialize($emailSettings) : $emailSettings;
4956 $this->autoImport = (isset($emailSettings['autoImport']) && !empty($emailSettings['autoImport'])) ? true : false;
4957 return $this->autoImport;
4961 * Clears out cache files for a user
4963 function cleanOutCache() {
4964 $GLOBALS['log']->debug("INBOUNDEMAIL: at cleanOutCache()");
4965 $this->deleteCache();
4969 * moves emails from folder to folder
4970 * @param string $fromIe I-E id
4971 * @param string $fromFolder IMAP path to folder in which the email lives
4972 * @param string $toIe I-E id
4973 * @param string $toFolder
4974 * @param string $uids UIDs of emails to move, either Sugar GUIDS or IMAP
4977 function copyEmails($fromIe, $fromFolder, $toIe, $toFolder, $uids) {
4978 $this->moveEmails($fromIe, $fromFolder, $toIe, $toFolder, $uids, true);
4982 * moves emails from folder to folder
4983 * @param string $fromIe I-E id
4984 * @param string $fromFolder IMAP path to folder in which the email lives
4985 * @param string $toIe I-E id
4986 * @param string $toFolder
4987 * @param string $uids UIDs of emails to move, either Sugar GUIDS or IMAP
4989 * @param bool $copy Default false
4990 * @return bool True on successful execution
4992 function moveEmails($fromIe, $fromFolder, $toIe, $toFolder, $uids, $copy=false) {
4993 global $app_strings;
4994 global $current_user;
4998 if($fromIe == $toIe) {
4999 $GLOBALS['log']->debug("********* SUGARFOLDER - moveEmails() moving email from I-E to I-E");
5000 //$exDestFolder = explode("::", $toFolder);
5001 //preserve $this->mailbox
5002 if (isset($this->mailbox)) {
5003 $oldMailbox = $this->mailbox;
5007 $this->retrieve($fromIe);
5008 $this->mailbox = $fromFolder;
5009 $this->connectMailserver();
5010 $exUids = explode('::;::', $uids);
5011 $uids = implode(",", $exUids);
5012 // imap_mail_move accepts comma-delimited lists of UIDs
5014 if(imap_mail_copy($this->conn, $uids, $toFolder, CP_UID)) {
5015 $this->mailbox = $toFolder;
5016 $this->connectMailserver();
5017 $newOverviews = imap_fetch_overview($this->conn, $uids, FT_UID);
5018 $this->updateOverviewCacheFile($newOverviews, 'append');
5019 if (isset($oldMailbox)) {
5020 $this->mailbox = $oldMailbox;
5024 $GLOBALS['log']->debug("INBOUNDEMAIL: could not imap_mail_copy() [ {$uids} ] to folder [ {$toFolder} ] from folder [ {$fromFolder} ]");
5027 if(imap_mail_move($this->conn, $uids, $toFolder, CP_UID)) {
5028 $GLOBALS['log']->info("INBOUNDEMAIL: imap_mail_move() [ {$uids} ] to folder [ {$toFolder} ] from folder [ {$fromFolder} ]");
5029 imap_expunge($this->conn); // hard deletes moved messages
5031 // update cache on fromFolder
5032 $newOverviews = $this->getOverviewsFromCacheFile($uids, $fromFolder, true);
5033 $this->deleteCachedMessages($uids, $fromFolder);
5035 // update cache on toFolder
5036 $this->checkEmailOneMailbox($toFolder, true, true);
5037 if (isset($oldMailbox)) {
5038 $this->mailbox = $oldMailbox;
5043 $GLOBALS['log']->debug("INBOUNDEMAIL: could not imap_mail_move() [ {$uids} ] to folder [ {$toFolder} ] from folder [ {$fromFolder} ]");
5046 } elseif($toIe == 'folder' && $fromFolder == 'sugar::Emails') {
5047 $GLOBALS['log']->debug("********* SUGARFOLDER - moveEmails() moving email from SugarFolder to SugarFolder");
5048 // move from sugar folder to sugar folder
5049 require_once("include/SugarFolders/SugarFolders.php");
5050 $sugarFolder = new SugarFolder();
5051 $exUids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
5052 foreach($exUids as $id) {
5054 $sugarFolder->copyBean($fromIe, $toFolder, $id, "Emails");
5056 $fromSugarFolder = new SugarFolder();
5057 $fromSugarFolder->retrieve($fromIe);
5058 $toSugarFolder = new SugarFolder();
5059 $toSugarFolder->retrieve($toFolder);
5061 $email = new Email();
5062 $email->retrieve($id);
5063 $email->status = 'unread';
5065 // when you move from My Emails to Group Folder, Assign To field for the Email should become null
5066 if ($fromSugarFolder->is_dynamic && $toSugarFolder->is_group) {
5067 // Bug 50972 - assigned_user_id set to empty string not true null
5068 // Modifying the field defs in just this one place to allow
5069 // a true null since this is what is expected when reading
5071 $email->setFieldNullable('assigned_user_id');
5072 $email->assigned_user_id = "";
5074 $email->revertFieldNullable('assigned_user_id');
5076 if (!$toSugarFolder->checkEmailExistForFolder($id)) {
5077 $fromSugarFolder->deleteEmailFromAllFolder($id);
5078 $toSugarFolder->addBean($email);
5080 } elseif ($fromSugarFolder->is_group && $toSugarFolder->is_dynamic) {
5081 $fromSugarFolder->deleteEmailFromAllFolder($id);
5082 $email->assigned_user_id = $current_user->id;
5085 // If you are moving something from personal folder then delete an entry from all folder
5086 if (!$fromSugarFolder->is_dynamic && !$fromSugarFolder->is_group) {
5087 $fromSugarFolder->deleteEmailFromAllFolder($id);
5090 if ($fromSugarFolder->is_dynamic && !$toSugarFolder->is_dynamic && !$toSugarFolder->is_group) {
5091 $email->assigned_user_id = "";
5092 $toSugarFolder->addBean($email);
5094 if (!$toSugarFolder->checkEmailExistForFolder($id)) {
5095 if (!$toSugarFolder->is_dynamic) {
5096 $fromSugarFolder->deleteEmailFromAllFolder($id);
5097 $toSugarFolder->addBean($email);
5099 $fromSugarFolder->deleteEmailFromAllFolder($id);
5100 $email->assigned_user_id = $current_user->id;
5103 $sugarFolder->move($fromIe, $toFolder, $id);
5111 } elseif($toIe == 'folder') {
5112 $GLOBALS['log']->debug("********* SUGARFOLDER - moveEmails() moving email from I-E to SugarFolder");
5113 // move to Sugar folder
5114 require_once("include/SugarFolders/SugarFolders.php");
5115 $sugarFolder = new SugarFolder();
5116 $sugarFolder->retrieve($toFolder);
5117 //Show the import form if we don't have the required info
5118 if (!isset($_REQUEST['delete'])) {
5119 $json = getJSONobj();
5120 if ($sugarFolder->is_group) {
5121 $_REQUEST['showTeam'] = false;
5122 $_REQUEST['showAssignTo'] = false;
5124 $ret = $this->email->et->getImportForm($_REQUEST, $this->email);
5125 $ret['move'] = true;
5126 $ret['srcFolder'] = $fromFolder;
5127 $ret['srcIeId'] = $fromIe;
5128 $ret['dstFolder'] = $toFolder;
5129 $ret['dstIeId'] = $toIe;
5130 $out = trim($json->encode($ret, false));
5137 $this->retrieve($fromIe);
5138 $this->mailbox = $fromFolder;
5139 $this->connectMailserver();
5140 // If its a group folder the team should be of the folder team
5141 if ($sugarFolder->is_group) {
5142 $_REQUEST['team_id'] = $sugarFolder->team_id;
5143 $_REQUEST['team_set_id'] = $sugarFolder->team_set_id;
5145 // TODO - set team_id, team_set for new UI
5148 $exUids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
5150 if(!empty($sugarFolder->id)) {
5153 $json = getJSONobj();
5154 foreach($exUids as $k => $uid) {
5156 if ($this->isPop3Protocol()) {
5157 $msgNo = $this->getCorrectMessageNoForPop3($uid);
5159 $msgNo = imap_msgno($this->conn, $uid);
5162 if(!empty($msgNo)) {
5163 $importStatus = $this->importOneEmail($msgNo, $uid);
5166 $sugarFolder->addBean($this->email);
5167 if(!$copy && isset($_REQUEST['delete']) && ($_REQUEST['delete'] == "true") && $importStatus) {
5168 $GLOBALS['log']->error("********* delete from mailserver [ {explode(",", $uids)} ]");
5169 // delete from mailserver
5170 $this->deleteMessageOnMailServer($uid);
5171 $this->deleteMessageFromCache($uid);
5174 $return[] = $app_strings['LBL_EMAIL_MESSAGE_NO'] . " " . $count . ", " . $app_strings['LBL_STATUS'] . " " . ($importStatus ? $app_strings['LBL_EMAIL_IMPORT_SUCCESS'] : $app_strings['LBL_EMAIL_IMPORT_FAIL']);
5178 echo $json->encode($return);
5181 $GLOBALS['log']->error("********* SUGARFOLDER - failed to retrieve folder ID [ {$toFolder} ]");
5184 $GLOBALS['log']->debug("********* SUGARFOLDER - moveEmails() called with no passing criteria");
5192 * Hard deletes an I-E account
5193 * @param string id GUID
5195 function hardDelete($id) {
5196 $q = "DELETE FROM inbound_email WHERE id = '{$id}'";
5197 $r = $this->db->query($q, true);
5201 * Generate a unique filename for attachments based on the message id. There are no maximum
5202 * specifications for the length of the message id, the only requirement is that it be globally unique.
5204 * @param bool $nameOnly Whether or not the attachment count should be appended to the filename.
5205 * @return string The temp file name
5207 function getTempFilename($nameOnly=false) {
5209 $str = $this->compoundMessageId;
5212 $str = $str.$this->attachmentCount;
5213 $this->attachmentCount++;
5220 * deletes and expunges emails on server
5221 * @param string $uid UID(s), comma delimited, of email(s) on server
5222 * @return bool true on success
5224 function deleteMessageOnMailServer($uid) {
5225 global $app_strings;
5226 $this->connectMailserver();
5228 if(strpos($uid, $app_strings['LBL_EMAIL_DELIMITER']) !== false) {
5229 $uids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uid);
5236 if($this->protocol == 'imap') {
5237 $trashFolder = $this->get_stored_options("trashFolder");
5238 if (empty($trashFolder)) {
5239 $trashFolder = "INBOX.Trash";
5241 foreach($uids as $uid) {
5242 if($this->moveEmails($this->id, $this->mailbox, $this->id, $trashFolder, $uid))
5243 $GLOBALS['log']->debug("INBOUNDEMAIL: MoveEmail to {$trashFolder} successful.");
5245 $GLOBALS['log']->debug("INBOUNDEMAIL: MoveEmail to {$trashFolder} FAILED - trying hard delete for message: $uid");
5246 imap_delete($this->conn, $uid, FT_UID);
5253 foreach($uids as $uid) {
5254 $msgnos[] = $this->getCorrectMessageNoForPop3($uid);
5256 $msgnos = implode(',', $msgnos);
5257 imap_delete($this->conn, $msgnos);
5261 if(!imap_expunge($this->conn)) {
5262 $GLOBALS['log']->debug("NOOP: could not expunge deleted email.");
5266 $GLOBALS['log']->info("INBOUNDEMAIL: hard-deleted mail with MSgno's' [ {$msgnos} ]");
5272 * deletes and expunges emails on server
5273 * @param string $uid UID(s), comma delimited, of email(s) on server
5275 function deleteMessageOnMailServerForPop3($uid) {
5276 if(imap_delete($this->conn, $uid)) {
5277 if(!imap_expunge($this->conn)) {
5278 $GLOBALS['log']->debug("NOOP: could not expunge deleted email.");
5281 $GLOBALS['log']->info("INBOUNDEMAIL: hard-deleted mail with MSgno's' [ {$uid} ]");
5287 * Checks if this is a pop3 type of an account or not
5290 function isPop3Protocol() {
5291 return ($this->protocol == 'pop3');
5295 * Gets the UIDL from database for the corresponding msgno
5296 * @param int messageNo of a message
5297 * @return UIDL for the message
5299 function getUIDLForMessage($msgNo) {
5300 $query = "SELECT message_id FROM email_cache WHERE ie_id = '{$this->id}' AND msgno = '{$msgNo}'";
5301 $r = $this->db->query($query);
5302 $a = $this->db->fetchByAssoc($r);
5303 return $a['message_id'];
5306 * Get the users default IE account id
5311 function getUsersDefaultOutboundServerId($user)
5313 $id = $user->getPreference($this->keyForUsersDefaultIEAccount,'Emails',$user);
5314 //If no preference has been set, grab the default system id.
5317 $oe = new OutboundEmail();
5318 $system = $oe->getSystemMailerSettings();
5319 $id=empty($system->id) ? '' : $system->id;
5326 * Get the users default IE account id
5330 function setUsersDefaultOutboundServerId($user,$oe_id)
5332 $user->setPreference($this->keyForUsersDefaultIEAccount, $oe_id, '', 'Emails');
5335 * Gets the UIDL from database for the corresponding msgno
5336 * @param int messageNo of a message
5337 * @return UIDL for the message
5339 function getMsgnoForMessageID($messageid) {
5340 $query = "SELECT msgno FROM email_cache WHERE ie_id = '{$this->id}' AND message_id = '{$messageid}'";
5341 $r = $this->db->query($query);
5342 $a = $this->db->fetchByAssoc($r);
5343 return $a['message_id'];
5347 * fills InboundEmail->email with an email's details
5348 * @param int uid Unique ID of email
5349 * @param bool isMsgNo flag that passed ID is msgNo, default false
5350 * @param bool setRead Sets the 'seen' flag in cache
5351 * @param bool forceRefresh Skips cache file
5354 function setEmailForDisplay($uid, $isMsgNo=false, $setRead=false, $forceRefresh=false) {
5357 $GLOBALS['log']->debug("*** ERROR: INBOUNDEMAIL trying to setEmailForDisplay() with no UID");
5361 global $sugar_config;
5362 global $app_strings;
5364 // if its a pop3 then get the UIDL and see if this file name exist or not
5365 if ($this->isPop3Protocol()) {
5366 // get the UIDL from database;
5367 $cachedUIDL = md5($uid);
5368 $cache = "{$this->EmailCachePath}/{$this->id}/messages/{$this->mailbox}{$cachedUIDL}.php";
5370 $cache = "{$this->EmailCachePath}/{$this->id}/messages/{$this->mailbox}{$uid}.php";
5373 if(file_exists($cache) && !$forceRefresh) {
5374 $GLOBALS['log']->info("INBOUNDEMAIL: Using cache file for setEmailForDisplay()");
5376 include($cache); // profides $cacheFile
5377 /** @var $cacheFile array */
5379 $metaOut = unserialize($cacheFile['out']);
5380 $meta = $metaOut['meta']['email'];
5381 $email = new Email();
5383 foreach($meta as $k => $v) {
5387 $email->to_addrs = $meta['toaddrs'];
5388 $email->date_sent = $meta['date_start'];
5389 //_ppf($email,true);
5391 $this->email = $email;
5392 $this->email->email2init();
5395 $GLOBALS['log']->info("INBOUNDEMAIL: opening new connection for setEmailForDisplay()");
5396 if($this->isPop3Protocol()) {
5397 $msgNo = $this->getCorrectMessageNoForPop3($uid);
5399 if(empty($this->conn)) {
5400 $this->connectMailserver();
5402 $msgNo = ($isMsgNo) ? $uid : imap_msgno($this->conn, $uid);
5404 if(empty($this->conn)) {
5405 $status = $this->connectMailserver();
5406 if($status == "false") {
5407 $this->email = new Email();
5408 $this->email->name = $app_strings['LBL_EMAIL_ERROR_MAILSERVERCONNECTION'];
5415 $this->importOneEmail($msgNo, $uid, true);
5416 $this->email->id = '';
5417 $this->email->new_with_id = false;
5422 $this->setStatuses($uid, 'seen', 1);
5430 * Sets status for a particular attribute on the mailserver and the local cache file
5432 function setStatuses($uid, $field, $value) {
5433 global $sugar_config;
5434 /** available status fields
5438 [date] => Mon, 22 Jan 2007 17:32:57 -0800
5451 $file = "{$this->mailbox}.imapFetchOverview.php";
5452 $overviews = $this->getCacheValueForUIDs($this->mailbox, array($uid));
5454 if(!empty($overviews)) {
5457 foreach($overviews['retArr'] as $k => $obj) {
5458 if($obj->imap_uid == $uid) {
5459 $obj->$field = $value;
5464 if(!empty($updates)) {
5465 $this->setCacheValue($this->mailbox, array(), $updates);
5471 * Removes an email from the cache file, deletes the message from the cache too
5472 * @param string String of uids, comma delimited
5474 function deleteMessageFromCache($uids) {
5475 global $sugar_config;
5476 global $app_strings;
5478 // delete message cache file and email_cache file
5479 $exUids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
5481 foreach($exUids as $uid) {
5483 if ($this->isPop3Protocol()) {
5484 $q = "DELETE FROM email_cache WHERE message_id = '{$uid}' AND ie_id = '{$this->id}'";
5486 $q = "DELETE FROM email_cache WHERE imap_uid = {$uid} AND ie_id = '{$this->id}'";
5488 $r = $this->db->query($q);
5489 if ($this->isPop3Protocol()) {
5492 $msgCacheFile = "{$this->EmailCachePath}/{$this->id}/messages/{$this->mailbox}{$uid}.php";
5493 if(file_exists($msgCacheFile)) {
5494 if(!unlink($msgCacheFile)) {
5495 $GLOBALS['log']->error("***ERROR: InboundEmail could not delete the cache file [ {$msgCacheFile} ]");
5504 * @param int uid UID of email to display
5505 * @param string mbox Mailbox to look in for the message
5506 * @param bool isMsgNo Flag to assume $uid is a MessageNo, not UniqueID, default false
5508 function displayOneEmail($uid, $mbox, $isMsgNo=false) {
5509 require_once("include/JSON.php");
5512 global $app_strings;
5513 global $app_list_strings;
5514 global $sugar_smarty;
5516 global $current_user;
5517 global $sugar_config;
5519 $fetchedAttributes = array(
5528 $souEmail = array();
5529 foreach($fetchedAttributes as $k) {
5530 if ($k == 'date_start') {
5531 $this->email->$k . " " . $this->email->time_start;
5532 $souEmail[$k] = $this->email->$k . " " . $this->email->time_start;
5533 } elseif ($k == 'time_start') {
5536 $souEmail[$k] = trim($this->email->$k);
5540 // if a MsgNo is passed in, convert to UID
5542 $uid = imap_uid($this->conn, $uid);
5544 // meta object to allow quick retrieval for replies
5546 $meta['type'] = $this->email->type;
5547 $meta['uid'] = $uid;
5548 $meta['ieId'] = $this->id;
5549 $meta['email'] = $souEmail;
5550 $meta['mbox'] = $this->mailbox;
5555 $exMbox = explode("::", $mbox);
5559 if(!empty($this->email->cc_addrs)) {
5560 //$ccs = $this->collapseLongMailingList($this->email->cc_addrs);
5561 $ccs = to_html($this->email->cc_addrs_names);
5564 <td NOWRAP valign="top" class="displayEmailLabel">
5565 {$app_strings['LBL_EMAIL_CC']}:
5567 <td class="displayEmailValue">
5574 $meta['email']['cc_addrs'] = $ccs;
5577 if ($mbox == "sugar::Emails") {
5579 $q = "SELECT id, filename, file_mime_type FROM notes WHERE parent_id = '{$uid}' AND deleted = 0";
5580 $r = $this->db->query($q);
5582 while($a = $this->db->fetchByAssoc($r)) {
5583 $url = "index.php?entryPoint=download&type=notes&id={$a['id']}";
5584 $lbl = ($i == 0) ? $app_strings['LBL_EMAIL_ATTACHMENTS'].":" : '';
5586 $attachments .=<<<EOQ
5588 <td NOWRAP valign="top" class="displayEmailLabel">
5591 <td NOWRAP valign="top" colspan="2" class="displayEmailValue">
5592 <a href="{$url}">{$a['filename']}</a>
5596 $this->email->cid2Link($a['id'], $a['file_mime_type']);
5602 if($this->attachmentCount > 0) {
5603 $theCount = $this->attachmentCount;
5605 for($i=0; $i<$theCount; $i++) {
5606 $lbl = ($i == 0) ? $app_strings['LBL_EMAIL_ATTACHMENTS'].":" : '';
5607 $name = $this->getTempFilename(true).$i;
5608 $tempName = urlencode($this->tempAttachment[$name]);
5610 $url = "index.php?entryPoint=download&type=temp&isTempFile=true&ieId={$this->id}&tempName={$tempName}&id={$name}";
5612 $attachments .=<<<eoq
5614 <td NOWRAP valign="top" class="displayEmailLabel">
5617 <td NOWRAP valign="top" colspan="2" class="displayEmailValue">
5618 <a href="{$url}">{$this->tempAttachment[$name]}</a>
5625 $meta['email']['attachments'] = $attachments;
5628 $meta['email']['toaddrs'] = $this->collapseLongMailingList($this->email->to_addrs);
5629 $meta['email']['cc_addrs'] = $ccs;
5632 $description = (empty($this->email->description_html)) ? nl2br($this->email->description) : $this->email->description_html;
5633 $meta['email']['description'] = $description;
5636 $meta['is_sugarEmail'] = ($exMbox[0] == 'sugar') ? true : false;
5638 if(!$meta['is_sugarEmail']) {
5639 if($this->isAutoImport) {
5640 $meta['is_sugarEmail'] = true;
5643 if( $this->email->status != 'sent' ){
5644 // mark SugarEmail read
5645 $q = "UPDATE emails SET status = 'read' WHERE id = '{$uid}'";
5646 $r = $this->db->query($q);
5651 $meta['email']['name'] = to_html($this->email->name);
5652 $meta['email']['from_addr'] = ( !empty($this->email->from_addr_name) ) ? to_html($this->email->from_addr_name) : to_html($this->email->from_addr);
5653 $meta['email']['toaddrs'] = ( !empty($this->email->to_addrs_names) ) ? to_html($this->email->to_addrs_names) : to_html($this->email->to_addrs);
5654 $meta['email']['cc_addrs'] = to_html($this->email->cc_addrs_names);
5655 $meta['email']['reply_to_addr'] = to_html($this->email->reply_to_addr);
5656 $return['meta'] = $meta;
5662 * Takes a long list of email addresses from a To or CC field and shows the first 3, the rest hidden
5663 * @param string emails
5666 function collapseLongMailingList($emails) {
5667 global $app_strings;
5669 $ex = explode(",", $emails);
5673 if(count($ex) > 3) {
5677 foreach($ex as $email) {
5679 if(!empty($emails)) {
5682 $emails .= trim($email);
5684 if(!empty($emailsHidden)) {
5685 $emailsHidden .= ", ";
5687 $emailsHidden .= trim($email);
5693 if(!empty($emailsHidden)) {
5695 $emails = "<span onclick='javascript:SUGAR.email2.detailView.showFullEmailList(this);' style='cursor:pointer;'>{$emails} [...{$j} {$app_strings['LBL_MORE']}]</span>";
5696 $emailsHidden = "<span onclick='javascript:SUGAR.email2.detailView.showCroppedEmailList(this)' style='cursor:pointer; display:none;'>{$email2}, {$emailsHidden} [ {$app_strings['LBL_LESS']} ]</span>";
5699 $emails .= $emailsHidden;
5707 * Sorts IMAP's imap_fetch_overview() results
5708 * @param array $arr Array of standard objects
5709 * @param string $sort Column to sort by
5710 * @param string direction Direction to sort by (asc/desc)
5711 * @return array Sorted array of obj.
5713 function sortFetchedOverview($arr, $sort=4, $direction='DESC', $forceSeen=false) {
5714 global $current_user;
5716 $sortPrefs = $current_user->getPreference('folderSortOrder', 'Emails');
5717 if(!empty($sortPrefs))
5718 $listPrefs = $sortPrefs;
5720 $listPrefs = array();
5722 if(isset($listPrefs[$this->id][$this->mailbox])) {
5723 $currentNode = $listPrefs[$this->id][$this->mailbox];
5726 if(isset($currentNode['current']) && !empty($currentNode['current'])) {
5727 $sort = $currentNode['current']['sort'];
5728 $direction = $currentNode['current']['direction'];
5733 $sort = $this->defaultSort;//4;
5734 $direction = $this->defaultDirection; //'DESC';
5735 } elseif(!is_numeric($sort)) {
5736 // handle bad sort index
5737 $sort = $this->defaultSort;
5739 // translate numeric index to human readable
5740 $sort = $this->hrSort[$sort];
5742 if(empty($direction)) {
5743 $direction = 'DESC';
5751 foreach($arr as $k => $overview) {
5752 $sorts['flagged'][$k] = $overview->flagged;
5753 $sorts['status'][$k] = $overview->answered;
5754 $sorts['from'][$k] = str_replace('"', "", $this->handleMimeHeaderDecode($overview->from));
5755 $sorts['subj'][$k] = $this->handleMimeHeaderDecode(quoted_printable_decode($overview->subject));
5756 $sorts['date'][$k] = $overview->date;
5760 natcasesort($sorts[$sort]);
5761 //_ppd($sorts[$sort]);
5763 if(strtolower($direction) == 'desc') {
5764 $revSorts = array();
5765 $keys = array_reverse(array_keys($sorts[$sort]));
5766 // _pp("count keys in DESC: ".count($keys));
5767 // _pp("count elements in sort[sort]: ".count($sorts[$sort]));
5769 for($i=0; $i<count($keys); $i++) {
5771 $revSorts[$v] = $sorts[$sort][$v];
5774 //_pp("count post-sort: ".count($revSorts));
5775 $sorts[$sort] = $revSorts;
5777 $timedate = TimeDate::getInstance();
5778 foreach($sorts[$sort] as $k2 => $overview2) {
5779 $arr[$k2]->date = $timedate->fromString($arr[$k2]->date)->asDb();
5780 $retArr[] = $arr[$k2];
5782 //_pp("final count: ".count($retArr));
5784 $finalReturn = array();
5785 $finalReturn['retArr'] = $retArr;
5786 $finalReturn['sortBy'] = $sort;
5787 $finalReturn['direction'] = $direction;
5788 return $finalReturn;
5792 function setReadFlagOnFolderCache($mbox, $uid) {
5793 global $sugar_config;
5795 $this->mailbox = $mbox;
5798 if($this->validCacheExists($this->mailbox)) {
5799 $ret = $this->getCacheValue($this->mailbox);
5803 foreach($ret as $k => $v) {
5804 if($v->imap_uid == $uid) {
5811 $this->setCacheValue($this->mailbox, array(), $updates);
5816 * Returns a list of emails in a mailbox.
5817 * @param string mbox Name of mailbox using dot notation paths to display
5818 * @param string $forceRefresh Flag to use cache or not
5820 function displayFolderContents($mbox, $forceRefresh='false', $page) {
5821 global $current_user;
5823 $delimiter = $this->get_stored_options('folderDelimiter');
5825 $mbox = str_replace('.', $delimiter, $mbox);
5828 $this->mailbox = $mbox;
5830 // jchi #9424, get sort and direction from user preference
5832 $direction = 'desc';
5833 $sortSerial = $current_user->getPreference('folderSortOrder', 'Emails');
5834 if(!empty($sortSerial) && !empty($_REQUEST['ieId']) && !empty($_REQUEST['mbox'])) {
5835 $sortArray = unserialize($sortSerial);
5836 $sort = $sortArray[$_REQUEST['ieId']][$_REQUEST['mbox']]['current']['sort'];
5837 $direction = $sortArray[$_REQUEST['ieId']][$_REQUEST['mbox']]['current']['direction'];
5842 if(!empty($_REQUEST['sort']) && !empty($_REQUEST['dir'])) {
5843 $this->email->et->saveListViewSortOrder($_REQUEST['ieId'], $_REQUEST['mbox'], $_REQUEST['sort'], $_REQUEST['dir']);
5844 $sort = $_REQUEST['sort'];
5845 $direction = $_REQUEST['dir'];
5847 $_REQUEST['sort'] = '';
5848 $_REQUEST['dir'] = '';
5854 if($forceRefresh == 'false' && $this->validCacheExists($this->mailbox)) {
5855 $emailSettings = $current_user->getPreference('emailSettings', 'Emails');
5857 // cn: default to a low number until user specifies otherwise
5858 if(empty($emailSettings['showNumInList'])) {
5859 $emailSettings['showNumInList'] = 20;
5862 $ret = $this->getCacheValue($this->mailbox, $emailSettings['showNumInList'], $page, $sort, $direction);
5866 $out = $this->displayFetchedSortedListXML($ret, $mbox);
5868 $metadata = array();
5869 $metadata['mbox'] = $mbox;
5870 $metadata['ieId'] = $this->id;
5871 $metadata['name'] = $this->name;
5872 $metadata['fromCache'] = $cacheUsed ? 1 : 0;
5873 $metadata['out'] = $out;
5879 * For a group email account, create subscriptions for all users associated with the
5880 * team assigned to the account.
5883 function createUserSubscriptionsForGroupAccount()
5886 $team->retrieve($this->team_id);
5887 $usersList = $team->get_team_members(true);
5888 foreach($usersList as $userObject)
5890 $previousSubscriptions = unserialize(base64_decode($userObject->getPreference('showFolders', 'Emails',$userObject)));
5891 if($previousSubscriptions === FALSE)
5892 $previousSubscriptions = array();
5894 $previousSubscriptions[] = $this->id;
5896 $encodedSubs = base64_encode(serialize($previousSubscriptions));
5897 $userObject->setPreference('showFolders',$encodedSubs , '', 'Emails');
5898 $userObject->savePreferencesToDB();
5902 * Create a sugar folder for this inbound email account
5903 * if the Enable Auto Import option is selected
5905 * @return String Id of the sugar folder created.
5907 function createAutoImportSugarFolder()
5909 global $current_user;
5910 $guid = create_guid();
5911 $GLOBALS['log']->debug("Creating Sugar Folder for IE with id $guid");
5912 $folder = new SugarFolder();
5913 $folder->id = $guid;
5914 $folder->new_with_id = TRUE;
5915 $folder->name = $this->name;
5916 $folder->has_child = 0;
5917 $folder->is_group = 1;
5918 $folder->assign_to_id = $current_user->id;
5919 $folder->parent_folder = "";
5922 //If this inbound email is marked as inactive, don't add subscriptions.
5923 $addSubscriptions = ($this->status == 'Inactive' || $this->mailbox_type == 'bounce') ? FALSE : TRUE;
5924 $folder->save($addSubscriptions);
5929 function validCacheExists($mbox) {
5930 $q = "SELECT count(*) c FROM email_cache WHERE ie_id = '{$this->id}'";
5931 $r = $this->db->query($q);
5932 $a = $this->db->fetchByAssoc($r);
5945 function displayFetchedSortedListXML($ret, $mbox) {
5948 global $current_user;
5949 global $sugar_config;
5951 if(empty($ret['retArr'])) {
5955 $tPref = $current_user->getUserDateTimePreferences();
5959 foreach($ret['retArr'] as $msg) {
5961 $flagged = ($msg->flagged == 0) ? "" : $this->iconFlagged;
5962 $status = ($msg->deleted) ? $this->iconDeleted : "";
5963 $status = ($msg->draft == 0) ? $status : $this->iconDraft;
5964 $status = ($msg->answered == 0) ? $status : $this->iconAnswered;
5965 $from = $this->handleMimeHeaderDecode($msg->from);
5966 $subject = $this->handleMimeHeaderDecode($msg->subject);
5967 //$date = date($tPref['date']." ".$tPref['time'], $msg->date);
5968 $date = $timedate->to_display_date_time($this->db->fromConvert($msg->date, 'datetime'));
5969 //$date = date($tPref['date'], $this->getUnixHeaderDate($msg->date));
5972 $temp['flagged'] = $flagged;
5973 $temp['status'] = $status;
5974 $temp['from'] = to_html($from);
5975 $temp['subject'] = $subject;
5976 $temp['date'] = $date;
5977 $temp['uid'] = $msg->uid; // either from an imap_search() or massaged cache value
5978 $temp['mbox'] = $this->mailbox;
5979 $temp['ieId'] = $this->id;
5980 $temp['site_url'] = $sugar_config['site_url'];
5981 $temp['seen'] = $msg->seen;
5982 $temp['type'] = (isset($msg->type)) ? $msg->type: 'remote';
5983 $temp['to_addrs'] = to_html($msg->to);
5984 $temp['hasAttach'] = '0';
5995 * retrieves the mailboxes for a given account in the following format
6000 [Builder] => Builder
6007 * @param bool $justRaw Default false
6010 function getMailboxes($justRaw=false) {
6011 if($justRaw == true) {
6012 return $this->mailboxarray;
6015 return $this->generateMultiDimArrayFromFlatArray($this->mailboxarray, $this->retrieveDelimiter());
6017 $serviceString = $this->getConnectString('', '', false);
6019 if(strpos($serviceString, 'pop3')) {
6021 $obj->name = $serviceString."INBOX";
6022 $boxes = array("INBOX" => $obj);
6024 $boxes = imap_getmailboxes($this->conn, $serviceString, "*");
6029 // clean MBOX path names
6030 foreach($boxes as $k => $mbox) {
6031 $raw[] = str_replace($serviceString, "", $mbox->name);
6032 if ($mbox->delimiter) {
6033 $delimiter = $mbox->delimiter;
6036 $storedOptions = unserialize(base64_decode($this->stored_options));
6037 $storedOptions['folderDelimiter'] = $delimiter;
6038 $this->stored_options = base64_encode(serialize($storedOptions));
6044 // used by $this->search()
6045 if($justRaw == true) {
6050 // generate a multi-dimensional array to iterate through
6052 foreach($raw as $mbox) {
6053 $ret = $this->sortMailboxes($mbox, $ret, $delimiter);
6060 function getMailBoxesForGroupAccount() {
6061 $mailboxes = $this->generateMultiDimArrayFromFlatArray(explode(",", $this->mailbox), $this->retrieveDelimiter());
6062 $mailboxesArray = $this->generateFlatArrayFromMultiDimArray($mailboxes, $this->retrieveDelimiter());
6063 $mailboxesArray = $this->filterMailBoxFromRaw(explode(",", $this->mailbox), $mailboxesArray);
6064 $this->saveMailBoxFolders($mailboxesArray);
6066 if ($this->mailbox != $this->$email_user) {
6067 $mailboxes = $this->sortMailboxes($this->mailbox, $this->retrieveDelimiter());
6068 $mailboxesArray = $this->generateFlatArrayFromMultiDimArray($mailboxes, $this->retrieveDelimiter());
6069 $this->saveMailBoxFolders($mailboxesArray);
6070 // save mailbox value of an inbound email account to email user
6071 $this->saveMailBoxValueOfInboundEmail();
6073 $mailboxes = $this->getMailboxes();
6079 function saveMailBoxFolders($value) {
6080 if (is_array($value)) {
6081 $value = implode(",", $value);
6083 $this->mailboxarray = explode(",", $value);
6084 $value = $this->db->quoted($value);
6085 $query = "update inbound_email set mailbox = $value where id ='{$this->id}'";
6086 $this->db->query($query);
6089 function insertMailBoxFolders($value) {
6090 $query = "select value from config where category='InboundEmail' and name='{$this->id}'";
6091 $r = $this->db->query($query);
6092 $a = $this->db->fetchByAssoc($r);
6093 if (empty($a['value'])) {
6094 if (is_array($value)) {
6095 $value = implode(",", $value);
6097 $this->mailboxarray = explode(",", $value);
6098 $value = $this->db->quoted($value);
6100 $query = "INSERT INTO config VALUES('InboundEmail', '{$this->id}', $value)";
6101 $this->db->query($query);
6105 function saveMailBoxValueOfInboundEmail() {
6106 $query = "update Inbound_email set mailbox = '{$this->email_user}'";
6107 $this->db->query($query);
6110 function retrieveMailBoxFolders() {
6111 $this->mailboxarray = explode(",", $this->mailbox);
6113 $query = "select value from config where category='InboundEmail' and name='{$this->id}'";
6114 $r = $this->db->query($query);
6115 $a = $this->db->fetchByAssoc($r);
6116 $this->mailboxarray = explode(",", $a['value']);
6121 function retrieveDelimiter() {
6122 $delimiter = $this->get_stored_options('folderDelimiter');
6129 function generateFlatArrayFromMultiDimArray($arraymbox, $delimiter) {
6131 foreach($arraymbox as $key => $value) {
6132 $this->generateArrayData($key, $value, $ret, $delimiter);
6138 function generateMultiDimArrayFromFlatArray($raw, $delimiter) {
6139 // generate a multi-dimensional array to iterate through
6141 foreach($raw as $mbox) {
6142 $ret = $this->sortMailboxes($mbox, $ret, $delimiter);
6148 function generateArrayData($key, $arraymbox, &$ret, $delimiter) {
6150 if (is_array($arraymbox)) {
6151 foreach($arraymbox as $mboxKey => $value) {
6152 $newKey = $key . $delimiter . $mboxKey;
6153 $this->generateArrayData($newKey, $value, $ret, $delimiter);
6159 * sorts the folders in a mailbox in a multi-dimensional array
6160 * @param string $MBOX
6164 function sortMailboxes($mbox, $ret, $delimeter = ".") {
6165 if(strpos($mbox, $delimeter)) {
6166 $node = substr($mbox, 0, strpos($mbox, $delimeter));
6167 $nodeAfter = substr($mbox, strpos($mbox, $node) + strlen($node) + 1, strlen($mbox));
6169 if(!isset($ret[$node])) {
6170 $ret[$node] = array();
6171 } elseif(isset($ret[$node]) && !is_array($ret[$node])) {
6172 $ret[$node] = array();
6174 $ret[$node] = $this->sortMailboxes($nodeAfter, $ret[$node], $delimeter);
6176 $ret[$mbox] = $mbox;
6183 * parses Sugar's storage method for imap server service strings
6186 function getServiceString() {
6188 $exServ = explode('::', $this->service);
6190 foreach($exServ as $v) {
6191 if(!empty($v) && ($v != 'imap' && $v !='pop3')) {
6200 * Get Email messages IDs from server which aren't in database
6201 * @return array Ids of messages, which aren't still in database
6203 public function getNewEmailsForSyncedMailbox()
6205 // ids's count limit for batch processing
6207 $msgIds = imap_search($this->conn, 'ALL UNDELETED');
6210 if(count($msgIds) > 0)
6213 * @var collect results of queries and message headers
6219 // sort IDs to get lastest on top
6221 $GLOBALS['log']->debug('-----> getNewEmailsForSyncedMailbox() got '.count($msgIds).' Messages');
6222 foreach($msgIds as $k => &$msgNo)
6224 $uid = imap_uid($this->conn, $msgNo);
6225 $header = imap_headerinfo($this->conn, $msgNo);
6226 $fullHeader = imap_fetchheader($this->conn, $msgNo);
6227 $message_id = $header->message_id;
6228 $deliveredTo = $this->id;
6230 preg_match('/(delivered-to:|x-real-to:){1}\s*(\S+)\s*\n{1}/im', $fullHeader, $matches);
6233 $deliveredTo = $matches[2];
6235 if(empty($message_id) || !isset($message_id))
6237 $GLOBALS['log']->debug('*********** NO MESSAGE_ID.');
6238 $message_id = $this->getMessageId($header);
6241 // generate compound messageId
6242 $this->compoundMessageId = trim($message_id) . trim($deliveredTo);
6243 // if the length > 255 then md5 it so that the data will be of smaller length
6244 if (strlen($this->compoundMessageId) > 255)
6246 $this->compoundMessageId = md5($this->compoundMessageId);
6249 if (empty($this->compoundMessageId))
6254 $potentials = clean_xss($this->compoundMessageId, false);
6256 if(is_array($potentials) && !empty($potentials))
6258 foreach($potentials as $bad)
6260 $this->compoundMessageId = str_replace($bad, "", $this->compoundMessageId);
6263 array_push($tmpMsgs, array('msgNo' => $msgNo, 'msgId' => $this->compoundMessageId, 'exists' => 0));
6264 if($counter == $limit)
6268 foreach(array_slice($tmpMsgs, -$limit, $limit) as $k1 => $v1)
6270 $query[] = $v1['msgId'];
6272 $query = 'SELECT count(emails.message_id) as cnt, emails.message_id AS mid FROM emails WHERE emails.message_id IN ("' . implode('","', $query) . '") and emails.deleted = 0 group by emails.message_id';
6273 $r = $this->db->query($query);
6275 while($a = $this->db->fetchByAssoc($r))
6277 $tmp[html_entity_decode($a['mid'])] = $a['cnt'];
6279 foreach($tmpMsgs as $k1 => $v1)
6281 if(isset($tmp[$v1['msgId']]) && $tmp[$v1['msgId']] > 0)
6283 $tmpMsgs[$k1]['exists'] = 1;
6286 foreach($tmpMsgs as $k1 => $v1)
6288 if($v1['exists'] == 0)
6291 array_push($result, $v1['msgNo']);
6298 if($repeats >= $limit)
6304 $tmpMsgs = array_splice($tmpMsgs, -$repeats, $repeats);
6315 }catch(Exception $ex)
6317 $GLOBALS['log']->fatal($ex->getMessage());
6319 $GLOBALS['log']->debug('-----> getNewEmailsForSyncedMailbox() got '.count($result).' unsynced messages');
6323 } // end class definition
6327 * Simple class to mirror the passed object from an imap_fetch_overview() call
6346 var $indices; /* = array(
6349 'name' => 'mail_date',
6357 'name' => 'mail_from',
6365 'name' => 'mail_subj',
6374 var $fieldDefs;/* = array(
6377 'type' => 'varchar',
6382 'name' => 'subject',
6383 'type' => 'varchar',
6385 'required' => false,
6387 'fromaddr' => array(
6388 'name' => 'fromaddr',
6389 'type' => 'varchar',
6395 'type' => 'varchar',
6399 'senddate' => array(
6400 'name' => 'senddate',
6401 'type' => 'datetime',
6404 'message_id' => array(
6405 'name' => 'message_id',
6406 'type' => 'varchar',
6408 'required' => false,
6410 'mailsize' => array(
6411 'name' => 'mailsize',
6426 'required' => false,
6430 'type' => 'tinyint',
6435 'name' => 'flagged',
6436 'type' => 'tinyint',
6440 'answered' => array(
6441 'name' => 'answered',
6442 'type' => 'tinyint',
6447 'name' => 'deleted',
6448 'type' => 'tinyint',
6454 'type' => 'tinyint',
6460 'type' => 'tinyint',
6466 function Overview() {
6469 if(!isset($dictionary['email_cache']) || empty($dictionary['email_cache'])) {
6470 if(file_exists('custom/metadata/email_cacheMetaData.php')) {
6471 include('custom/metadata/email_cacheMetaData.php');
6473 include('metadata/email_cacheMetaData.php');
6477 $this->fieldDefs = $dictionary['email_cache']['fields'];
6478 $this->indices = $dictionary['email_cache']['indices'];