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);
195 $this->email_password = blowfishDecode(blowfishGetKey('InboundEmail'), $this->email_password);
196 $this->retrieveMailBoxFolders();
201 * wraps SugarBean->save()
202 * @param string ID of saved bean
204 function save($check_notify=false) {
205 // generate cache table for email 2.0
206 $multiDImArray = $this->generateMultiDimArrayFromFlatArray(explode(",", $this->mailbox), $this->retrieveDelimiter());
207 $raw = $this->generateFlatArrayFromMultiDimArray($multiDImArray, $this->retrieveDelimiter());
209 //_pp(explode(",", $this->mailbox));
211 $raw = $this->filterMailBoxFromRaw(explode(",", $this->mailbox), $raw);
212 $this->mailbox = implode(",", $raw);
213 if(!empty($this->email_password)) {
214 $this->email_password = blowfishEncode(blowfishGetKey('InboundEmail'), $this->email_password);
216 $ret = parent::save($check_notify);
220 function filterMailBoxFromRaw($mailboxArray, $rawArray) {
221 $newArray = array_intersect($mailboxArray, $rawArray);
227 * Overrides SugarBean's mark_deleted() to drop the related cache table
228 * @param string $id GUID of I-E instance
230 function mark_deleted($id) {
231 parent::mark_deleted($id);
232 $q = "update inbound_email set groupfolder_id = null WHERE id = '{$id}'";
233 $r = $this->db->query($q);
234 $this->deleteCache();
238 * Mark cached email answered (replied)
239 * @param string $mailid (uid for imap, message_id for pop3)
241 function mark_answered($mailid, $type = 'smtp') {
244 $q = "update email_cache set answered = 1 WHERE imap_uid = $mailid and ie_id = '{$this->id}'";
245 $this->db->query($q);
248 $q = "update email_cache set answered = 1 WHERE message_id = '$mailid' and ie_id = '{$this->id}'";
249 $this->db->query($q);
255 * Renames an IMAP mailbox
256 * @param string $newName
258 function renameFolder($oldName, $newName) {
259 //$this->mailbox = "INBOX"
260 $this->connectMailserver();
261 $oldConnect = $this->getConnectString('', $oldName);
262 $newConnect = $this->getConnectString('', $newName);
263 if(!imap_renamemailbox($this->conn, $oldConnect , $newConnect)) {
264 $GLOBALS['log']->debug("***INBOUNDEMAIL: failed to rename mailbox [ {$oldConnect} ] to [ {$newConnect} ]");
266 $this->mailbox = str_replace($oldName, $newName, $this->mailbox);
268 $sessionFoldersString = $this->getSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol);
269 $sessionFoldersString = str_replace($oldName, $newName, $sessionFoldersString);
270 $this->setSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol, $sessionFoldersString);
275 ///////////////////////////////////////////////////////////////////////////
276 //// CUSTOM LOGIC HOOKS
278 * Called from $this->getMessageText()
279 * Allows upgrade-safe custom processing of message text.
282 * 1. Create a directory path: ./custom/modules/InboundEmail if it does not exist
283 * 2. Create a file in the ./custom/InboundEmail/ folder called "getMessageText.php"
284 * 3. Define a function named "custom_getMessageText()" that takes a string as an argument and returns a string
286 * @param string $msgPart
289 function customGetMessageText($msgPart) {
290 $custom = "custom/modules/InboundEmail/getMessageText.php";
292 if(file_exists($custom)) {
293 include_once($custom);
295 if(function_exists("custom_getMessageText")) {
296 $GLOBALS['log']->debug("*** INBOUND EMAIL-CUSTOM_LOGIC: calling custom_getMessageText()");
297 $msgPart = custom_getMessageText($msgPart);
303 //// END CUSTOM LOGIC HOOKS
304 ///////////////////////////////////////////////////////////////////////////
308 ///////////////////////////////////////////////////////////////////////////
309 //// EMAIL 2.0 SPECIFIC
311 * constructs a nicely formatted version of raw source
312 * @param int $uid UID of email
315 function getFormattedRawSource($uid) {
318 //if($this->protocol == 'pop3') {
319 //$raw = $app_strings['LBL_EMAIL_VIEW_UNSUPPORTED'];
321 if (empty($this->id)) {
322 $q = "SELECT raw_source FROM emails_text WHERE email_id = '{$uid}'";
323 $r = $this->db->query($q);
324 $a = $this->db->fetchByAssoc($r);
326 $raw = $this->convertToUtf8($a['raw_source']);
328 $raw = $app_strings['LBL_EMAIL_ERROR_VIEW_RAW_SOURCE'];
331 if ($this->isPop3Protocol()) {
332 $uid = $this->getCorrectMessageNoForPop3($uid);
334 $raw = imap_fetchheader($this->conn, $uid, FT_UID+FT_PREFETCHTEXT);
335 $raw .= $this->convertToUtf8(imap_body($this->conn, $uid, FT_UID));
337 $raw = to_html($raw);
346 * helper method to convert text to utf-8 if necessary
348 * @param string $input text
349 * @return string output text
351 function convertToUtf8($input)
353 $charset = $GLOBALS['locale']->detectCharset($input, true);
355 // we haven't a clue due to missing package?, just return as itself
356 if ($charset === FALSE) {
360 // convert if we can or must
361 return $this->handleCharsetTranslation($input, $charset);
365 * constructs a nicely formatted version of email headers.
369 function getFormattedHeaders($uid) {
372 //if($this->protocol == 'pop3') {
373 // $header = $app_strings['LBL_EMAIL_VIEW_UNSUPPORTED'];
375 if ($this->isPop3Protocol()) {
376 $uid = $this->getCorrectMessageNoForPop3($uid);
378 $headers = imap_fetchheader($this->conn, $uid, FT_UID);
380 $lines = explode("\n", $headers);
382 $header = "<table cellspacing='0' cellpadding='2' border='0' width='100%'>";
384 foreach($lines as $line) {
388 $key = trim(substr($line, 0, strpos($line, ":")));
389 $value = trim(substr($line, strpos($line, ":") + 1));
390 $value = to_html($value);
393 $header .= "<td class='displayEmailLabel' NOWRAP><b>{$key}</b> </td>";
394 $header .= "<td class='displayEmailValueWhite'>{$value} </td>";
399 $header .= "</table>";
405 * Empties Trash folders
407 function emptyTrash() {
408 global $sugar_config;
410 $this->mailbox = $this->get_stored_options("trashFolder");
411 if (empty($this->mailbox)) {
412 $this->mailbox = 'INBOX.Trash';
414 $this->connectMailserver();
416 $uids = imap_search($this->conn, "ALL", SE_UID);
418 foreach($uids as $uid) {
419 if(!imap_delete($this->conn, $uid, FT_UID)) {
420 $lastError = imap_last_error();
421 $GLOBALS['log']->warn("INBOUNDEMAIL: emptyTrash() Could not delete message [ {$uid} ] from [ {$this->mailbox} ]. IMAP_ERROR [ {$lastError} ]");
425 // remove local cache file
426 $q = "DELETE FROM email_cache WHERE mbox = '{$this->mailbox}' AND ie_id = '{$this->id}'";
427 $r = $this->db->query($q);
431 * Fetches a timestamp
433 function getCacheTimestamp($mbox) {
434 $key = $this->db->quote("{$this->id}_{$mbox}");
435 $q = "SELECT ie_timestamp FROM inbound_email_cache_ts WHERE id = '{$key}'";
436 $r = $this->db->query($q);
437 $a = $this->db->fetchByAssoc($r);
442 return $a['ie_timestamp'];
446 * sets the cache timestamp
449 function setCacheTimestamp($mbox) {
450 $key = $this->db->quote("{$this->id}_{$mbox}");
452 $tsOld = $this->getCacheTimestamp($mbox);
455 $q = "INSERT INTO inbound_email_cache_ts (id, ie_timestamp) VALUES ('{$key}', {$ts})";
457 $q = "UPDATE inbound_email_cache_ts SET ie_timestamp = {$ts} WHERE id = '{$key}'";
460 $r = $this->db->query($q, true);
461 $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: setting timestamp query [ {$q} ]");
466 * Gets a count of all rows that are flagged seen = 0
467 * @param string $mbox
470 function getCacheUnreadCount($mbox) {
471 $q = "SELECT count(*) c FROM email_cache WHERE mbox = '{$mbox}' AND seen = 0 AND ie_id = '{$this->id}'";
472 $r = $this->db->query($q);
473 $a = $this->db->fetchByAssoc($r);
479 * Returns total number of emails for a mailbox
483 function getCacheCount($mbox) {
484 $q = "SELECT count(*) c FROM email_cache WHERE mbox = '{$mbox}' AND ie_id = '{$this->id}'";
485 $r = $this->db->query($q);
486 $a = $this->db->fetchByAssoc($r);
491 function getCacheUnread($mbox) {
492 $q = "SELECT count(*) c FROM email_cache WHERE mbox = '{$mbox}' AND ie_id = '{$this->id}' AND seen = '0'";
493 $r = $this->db->query($q);
494 $a = $this->db->fetchByAssoc($r);
501 * Deletes all rows for a given instance
503 function deleteCache() {
504 $q = "DELETE FROM email_cache WHERE ie_id = '{$this->id}'";
506 $GLOBALS['log']->info("INBOUNDEMAIL: deleting cache using query [ {$q} ]");
508 $r = $this->db->query($q);
512 * Deletes all the pop3 data which has been deleted from server
514 function deletePop3Cache() {
515 global $sugar_config;
516 $UIDLs = $this->pop3_getUIDL();
517 $cacheUIDLs = $this->pop3_getCacheUidls();
518 foreach($cacheUIDLs as $msgNo => $msgId) {
519 if (!in_array($msgId, $UIDLs)) {
520 $md5msgIds = md5($msgId);
521 $file = "{$this->EmailCachePath}/{$this->id}/messages/INBOX{$md5msgIds}.PHP";
522 $GLOBALS['log']->debug("INBOUNDEMAIL: deleting file [ {$file} ] ");
523 if(file_exists($file)) {
525 $GLOBALS['log']->debug("INBOUNDEMAIL: Could not delete [ {$file} ] ");
528 $q = "DELETE from email_cache where imap_uid = {$msgNo} AND msgno = {$msgNo} AND ie_id = '{$this->id}' AND message_id = '{$msgId}'";
529 $r = $this->db->query($q);
535 * Retrieves cached headers
538 function getCacheValueForUIDs($mbox, $UIDs) {
539 if (!is_array($UIDs) || empty($UIDs)) {
543 $q = "SELECT * FROM email_cache WHERE ie_id = '{$this->id}' AND mbox = '{$mbox}' AND ";
547 $slicedArray = array_slice($UIDs, $startIndex ,$endIndex);
548 $columnName = ($this->isPop3Protocol() ? "message_id" : "imap_uid");
550 'timestamp' => $this->getCacheTimestamp($mbox),
554 while (!empty($slicedArray)) {
555 $messageIdString = implode(',', $slicedArray);
556 $GLOBALS['log']->debug("sliced array = {$messageIdString}");
557 $extraWhere = "{$columnName} IN (";
559 foreach($slicedArray as $UID) {
561 $extraWhere = $extraWhere . ",";
564 $extraWhere = "{$extraWhere} '{$UID}'";
566 $newQuery = $q . $extraWhere . ")";
567 $r = $this->db->query($newQuery);
569 while($a = $this->db->fetchByAssoc($r)) {
570 if (isset($a['uid'])) {
571 if ($this->isPop3Protocol()) {
572 $ret['uids'][] = $a['message_id'];
574 $ret['uids'][] = $a['uid'];
578 $overview = new Overview();
580 foreach($a as $k => $v) {
584 $overview->imap_uid = $v;
585 if ($this->isPop3Protocol()) {
586 $overview->uid = $a['message_id'];
592 $overview->to = from_html($v);
596 $overview->from = from_html($v);
600 $overview->size = $v;
604 $overview->date = $v;
608 $overview->$k = from_html($v);
612 $ret['retArr'][] = $overview;
614 $startIndex = $startIndex + $endIndex;
615 $slicedArray = array_slice($UIDs, $startIndex ,$endIndex);
616 $messageIdString = implode(',', $slicedArray);
617 $GLOBALS['log']->debug("sliced array = {$messageIdString}");
623 * Retrieves cached headers
626 function getCacheValue($mbox, $limit = 20, $page = 1, $sort='', $direction='') {
627 // try optimizing this call as we don't want repeat queries
628 if(!empty($this->currentCache)) {
629 return $this->currentCache;
632 $sort = (empty($sort)) ? $this->defaultSort : $sort;
633 $direction = (empty($direction)) ? $this->defaultDirection : $direction;
634 $order = " ORDER BY {$this->hrSortLocal[$sort]} {$direction}";
636 $q = "SELECT * FROM email_cache WHERE ie_id = '{$this->id}' AND mbox = '{$mbox}' {$order}";
639 $start = ( $page - 1 ) * $limit;
640 $r = $this->db->limitQuery($q, $start, $limit);
642 $r = $this->db->query($q);
646 'timestamp' => $this->getCacheTimestamp($mbox),
651 while($a = $this->db->fetchByAssoc($r)) {
652 if (isset($a['uid'])) {
653 if ($this->isPop3Protocol()) {
654 $ret['uids'][] = $a['message_id'];
656 $ret['uids'][] = $a['uid'];
660 $overview = new Overview();
662 foreach($a as $k => $v) {
666 $overview->imap_uid = $v;
667 if ($this->isPop3Protocol()) {
668 $overview->uid = $a['message_id'];
674 $overview->to = from_html($v);
678 $overview->from = from_html($v);
682 $overview->size = $v;
686 $overview->date = $v;
690 $overview->$k = from_html($v);
694 $ret['retArr'][] = $overview;
697 $this->currentCache = $ret;
705 function setCacheValue($mbox, $insert, $update=array(), $remove=array()) {
712 // reset in-memory cache
713 $this->currentCache = null;
715 $table = 'email_cache';
716 $where = "WHERE ie_id = '{$this->id}' AND mbox = '{$mbox}'";
718 // handle removed rows
719 if(!empty($remove)) {
721 foreach($remove as $overview) {
722 if(!empty($removeIds)) {
726 $removeIds .= "'{$overview->imap_uid}'";
729 $q = "DELETE FROM {$table} {$where} AND imap_uid IN ({$removeIds})";
731 $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: delete query [ {$q} ]");
733 $r = $this->db->query($q, true, $q);
736 // handle insert rows
737 if(!empty($insert)) {
738 $q = "SELECT imap_uid FROM {$table} {$where}";
739 $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: filter UIDs query [ {$q} ]");
740 $r = $this->db->query($q);
743 while($a = $this->db->fetchByAssoc($r)) {
744 $uids[] = $a['imap_uid'];
746 $count = count($uids);
747 $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: found [ {$count} ] UIDs to filter against");
750 foreach($uids as $uid) {
755 $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: filter UIDs: [ {$tmp} ]");
759 foreach($this->overview->fieldDefs as $colDef) {
763 $cols .= "{$colDef['name']}";
765 foreach($insert as $overview) {
766 if(in_array($overview->imap_uid, $uids))
768 // fixing bug #49543: setting 'mbox' property for the following updating of other items in this box
769 if (!isset($overview->mbox))
771 $overview->mbox = $mbox;
773 $update[] = $overview;
779 foreach($this->overview->fieldDefs as $colDef) {
780 if(!empty($values)) {
784 // trim values for Oracle/MSSql
785 if( isset($colDef['len']) && !empty($colDef['len']) &&
786 isset($colDef['type']) && !empty($colDef['type']) &&
787 $colDef['type'] == 'varchar'
790 if (isset($overview->$colDef['name']))
792 $overview->$colDef['name'] = substr($overview->$colDef['name'], 0, $colDef['len']);
796 switch($colDef['name']) {
798 if(isset($overview->uid) && !empty($overview->uid)) {
799 $this->imap_uid = $overview->uid;
801 $values .= "'{$this->imap_uid}'";
805 $values .= "'{$this->id}'";
809 $values .= $this->db->quoted($overview->to);
813 $values .= $this->db->quoted($overview->from);
817 $values .= $this->db->quoted($overview->message_id);
821 $values .= $overview->size;
825 $conv=$timedate->fromString($overview->date);
827 $values .= $this->db->quoted($conv->asDb());
834 $values .= "'{$mbox}'";
838 $overview->$colDef['name'] = SugarCleaner::cleanHtml(from_html($overview->$colDef['name']));
839 $values .= $this->db->quoted($overview->$colDef['name']);
844 $q = "INSERT INTO {$table} ({$cols}) VALUES ({$values})";
845 $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: insert query [ {$q} ]");
846 $r = $this->db->query($q, true, $q);
850 // handle update rows
851 if(!empty($update)) {
853 foreach($this->overview->fieldDefs as $colDef) {
857 $cols .= "{$colDef['name']}";
860 foreach($update as $overview) {
861 $q = "UPDATE {$table} SET ";
864 foreach($this->overview->fieldDefs as $colDef) {
866 switch($colDef['name']) {
880 if (isset($overview->$colDef['name']))
882 $value = $this->db->quoted($overview->$colDef['name']);
886 $value = $this->db->quoted($value);
888 $set .= "{$colDef['name']} = " . $value;
893 $q .= $set . " WHERE ie_id = '{$this->id}' AND mbox = '{$overview->mbox}' AND imap_uid = '{$overview->imap_uid}'";
894 $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: update query [ {$q} ]");
895 $r = $this->db->query($q, true, $q);
902 * Opens a socket connection to the pop3 server
905 function pop3_open() {
906 if(!is_resource($this->pop3socket)) {
907 $GLOBALS['log']->info("*** INBOUNDEMAIL: opening socket connection");
908 $exServ = explode('::', $this->service);
909 $socket = ($exServ[2] == 'ssl') ? "ssl://" : "tcp://";
910 $socket .= $this->server_url;
911 $this->pop3socket = fsockopen($socket, $this->port);
913 $GLOBALS['log']->info("*** INBOUNDEMAIL: REUSING socket connection");
917 if(!is_resource($this->pop3socket)) {
918 $GLOBALS['log']->debug("*** INBOUNDEMAIL: unable to open socket connection");
923 $ret = trim(fgets($this->pop3socket, 1024));
924 $GLOBALS['log']->info("*** INBOUNDEMAIL: got socket connection [ {$ret} ]");
929 * Closes connections and runs clean-up routines
931 function pop3_cleanUp() {
932 $GLOBALS['log']->info("*** INBOUNDEMAIL: cleaning up socket connection");
933 fputs($this->pop3socket, "QUIT\r\n");
934 $buf = fgets($this->pop3socket, 1024);
935 fclose($this->pop3socket);
939 * sends a command down to the POP3 server
940 * @param string command
945 function pop3_sendCommand($command, $args='', $return=true) {
946 $command .= " {$args}";
947 $command = trim($command);
948 $GLOBALS['log']->info("*** INBOUNDEMAIL: pop3_sendCommand() SEND [ {$command} ]");
951 fputs($this->pop3socket, $command);
954 $ret = trim(fgets($this->pop3socket, 1024));
955 $GLOBALS['log']->info("*** INBOUNDEMAIL: pop3_sendCommand() RECEIVE [ {$ret} ]");
960 function getPop3NewMessagesToDownload() {
961 $pop3UIDL = $this->pop3_getUIDL();
962 $cacheUIDLs = $this->pop3_getCacheUidls();
963 // new email cache values we should deal with
964 $diff = array_diff_assoc($pop3UIDL, $cacheUIDLs);
965 // this is msgNo to UIDL array
966 $diff = $this->pop3_shiftCache($diff, $cacheUIDLs);
967 // get all the keys which are msgnos;
968 return array_keys($diff);
971 function getPop3NewMessagesToDownloadForCron() {
972 $pop3UIDL = $this->pop3_getUIDL();
973 $cacheUIDLs = $this->pop3_getCacheUidls();
974 // new email cache values we should deal with
975 $diff = array_diff_assoc($pop3UIDL, $cacheUIDLs);
976 // this is msgNo to UIDL array
977 $diff = $this->pop3_shiftCache($diff, $cacheUIDLs);
978 // insert data into email_cache
979 if ($this->groupfolder_id != null && $this->groupfolder_id != "" && $this->isPop3Protocol()) {
980 $searchResults = array_keys($diff);
981 $concatResults = implode(",", $searchResults);
982 if ($this->connectMailserver() == 'true') {
983 $fetchedOverviews = imap_fetch_overview($this->conn, $concatResults);
984 // clean up cache entry
985 foreach($fetchedOverviews as $k => $overview) {
986 $overview->message_id = trim($diff[$overview->msgno]);
987 $fetchedOverviews[$k] = $overview;
989 $this->updateOverviewCacheFile($fetchedOverviews);
996 * This method returns all the UIDL for this account. This should be called if the protocol is pop3
997 * @return array od messageno to UIDL array
999 function pop3_getUIDL() {
1001 if($this->pop3_open()) {
1003 $this->pop3_sendCommand("USER", $this->email_user);
1004 $this->pop3_sendCommand("PASS", $this->email_password);
1007 $this->pop3_sendCommand("UIDL", '', false); // leave socket buffer alone until the while()
1008 fgets($this->pop3socket, 1024); // handle "OK+";
1013 if(is_resource($this->pop3socket)) {
1014 while(!feof($this->pop3socket)) {
1015 $buf = fgets($this->pop3socket, 1024); // 8kb max buffer - shouldn't be more than 80 chars via pop3...
1018 if(trim($buf) == '.') {
1019 $GLOBALS['log']->debug("*** GOT '.'");
1023 // format is [msgNo] [UIDL]
1024 $exUidl = explode(" ", $buf);
1025 $UIDLs[$exUidl[0]] = trim($exUidl[1]);
1028 $this->pop3_cleanUp();
1034 * Special handler for POP3 boxes. Standard IMAP commands are useless.
1035 * This will fetch only partial emails for POP3 and hence needs to be call again and again based on status it returns
1037 function pop3_checkPartialEmail($synch = false) {
1038 require_once('include/utils/array_utils.php');
1039 global $current_user;
1040 global $sugar_config;
1042 $cacheDataExists = false;
1045 $cacheFilePath = clean_path("{$this->EmailCachePath}/{$this->id}/folders/MsgNOToUIDLData.php");
1046 if(file_exists($cacheFilePath)) {
1047 $cacheDataExists = true;
1048 if($fh = @fopen($cacheFilePath, "rb")) {
1050 $chunksize = 1*(1024*1024); // how many bytes per chunk
1052 $buf = fgets($fh, $chunksize); // 8kb max buffer - shouldn't be more than 80 chars via pop3...
1053 $data = $data . $buf;
1057 $diff = unserialize($data);
1058 if (!empty($diff)) {
1059 if (count($diff)> 50) {
1060 $newDiff = array_slice($diff, 50, count($diff), true);
1064 $results = array_slice(array_keys($diff), 0 ,50);
1065 $data = serialize($newDiff);
1066 if($fh = @fopen($cacheFilePath, "w")) {
1073 if (!$cacheDataExists) {
1075 $this->deletePop3Cache();
1077 $UIDLs = $this->pop3_getUIDL();
1078 if(count($UIDLs) > 0) {
1080 $cacheUIDLs = $this->pop3_getCacheUidls();
1082 // new email cache values we should deal with
1083 $diff = array_diff_assoc($UIDLs, $cacheUIDLs);
1084 $diff = $this->pop3_shiftCache($diff, $cacheUIDLs);
1085 require_once('modules/Emails/EmailUI.php');
1086 EmailUI::preflightEmailCache("{$this->EmailCachePath}/{$this->id}");
1088 if (count($diff)> 50) {
1089 $newDiff = array_slice($diff, 50, count($diff), true);
1094 $results = array_slice(array_keys($diff), 0 ,50);
1095 $data = serialize($newDiff);
1096 if($fh = @fopen($cacheFilePath, "w")) {
1101 $GLOBALS['log']->debug("*** INBOUNDEMAIL: could not open socket connection to POP3 server");
1102 return "could not open socket connection to POP3 server";
1106 // build up msgNo request
1107 if(count($diff) > 0) {
1108 // remove dirty cache entries
1110 if (isset($_REQUEST['currentCount']) && $_REQUEST['currentCount'] > -1) {
1111 $startingNo = $_REQUEST['currentCount'];
1114 $this->mailbox = 'INBOX';
1115 $this->connectMailserver();
1116 //$searchResults = array_keys($diff);
1117 //$fetchedOverviews = array();
1118 //$chunkArraySerachResults = array_chunk($searchResults, 50);
1119 $concatResults = implode(",", $results);
1120 $GLOBALS['log']->info('$$$$ '.$concatResults);
1121 $GLOBALS['log']->info("[EMAIL] Start POP3 fetch overview on mailbox [{$this->mailbox}] for user [{$current_user->user_name}] on 50 data");
1122 $fetchedOverviews = imap_fetch_overview($this->conn, $concatResults);
1123 $GLOBALS['log']->info("[EMAIL] End POP3 fetch overview on mailbox [{$this->mailbox}] for user [{$current_user->user_name}] on "
1124 . sizeof($fetchedOverviews) . " data");
1126 // clean up cache entry
1127 foreach($fetchedOverviews as $k => $overview) {
1128 $overview->message_id = trim($diff[$overview->msgno]);
1129 $fetchedOverviews[$k] = $overview;
1132 $GLOBALS['log']->info("[EMAIL] Start updating overview cache for pop3 mailbox [{$this->mailbox}] for user [{$current_user->user_name}]");
1133 $this->updateOverviewCacheFile($fetchedOverviews);
1134 $GLOBALS['log']->info("[EMAIL] Start updating overview cache for pop3 mailbox [{$this->mailbox}] for user [{$current_user->user_name}]");
1135 return array('status' => "In Progress", 'mbox' => $this->mailbox, 'count'=> (count($results) + $startingNo), 'totalcount' => count($diff), 'ieid' => $this->id);
1137 unlink($cacheFilePath);
1138 return array('status' => "done");
1143 * Special handler for POP3 boxes. Standard IMAP commands are useless.
1145 function pop3_checkEmail() {
1146 if($this->pop3_open()) {
1148 $this->pop3_sendCommand("USER", $this->email_user);
1149 $this->pop3_sendCommand("PASS", $this->email_password);
1152 $this->pop3_sendCommand("UIDL", '', false); // leave socket buffer alone until the while()
1153 fgets($this->pop3socket, 1024); // handle "OK+";
1158 if(is_resource($this->pop3socket)) {
1159 while(!feof($this->pop3socket)) {
1160 $buf = fgets($this->pop3socket, 1024); // 8kb max buffer - shouldn't be more than 80 chars via pop3...
1163 if(trim($buf) == '.') {
1164 $GLOBALS['log']->debug("*** GOT '.'");
1168 // format is [msgNo] [UIDL]
1169 $exUidl = explode(" ", $buf);
1170 $UIDLs[$exUidl[0]] = trim($exUidl[1]);
1174 $this->pop3_cleanUp();
1177 $cacheUIDLs = $this->pop3_getCacheUidls();
1178 // _pp($UIDLs);_pp($cacheUIDLs);
1180 // new email cache values we should deal with
1181 $diff = array_diff_assoc($UIDLs, $cacheUIDLs);
1183 // remove dirty cache entries
1184 $diff = $this->pop3_shiftCache($diff, $cacheUIDLs);
1186 // build up msgNo request
1188 $this->mailbox = 'INBOX';
1189 $this->connectMailserver();
1190 $searchResults = array_keys($diff);
1191 $concatResults = implode(",", $searchResults);
1192 $fetchedOverviews = imap_fetch_overview($this->conn, $concatResults);
1194 // clean up cache entry
1195 foreach($fetchedOverviews as $k => $overview) {
1196 $overview->message_id = trim($diff[$overview->msgno]);
1197 $fetchedOverviews[$k] = $overview;
1200 $this->updateOverviewCacheFile($fetchedOverviews);
1203 $GLOBALS['log']->debug("*** INBOUNDEMAIL: could not open socket connection to POP3 server");
1209 * Iterates through msgno and message_id to remove dirty cache entries
1212 function pop3_shiftCache($diff, $cacheUIDLs) {
1215 $newArray = array();
1216 foreach($diff as $msgNo => $msgId) {
1217 if (in_array($msgId, $cacheUIDLs)) {
1218 $q1 = "UPDATE email_cache SET imap_uid = {$msgNo}, msgno = {$msgNo} WHERE ie_id = '{$this->id}' AND message_id = '{$msgId}'";
1219 $this->db->query($q1);
1221 $newArray[$msgNo] = $msgId;
1226 foreach($diff as $msgNo => $msgId) {
1227 if(!empty($msgNos)) {
1230 if(!empty($msgIds)) {
1235 $msgIds .= "'{$msgId}'";
1238 if(!empty($msgNos)) {
1239 $q1 = "DELETE FROM email_cache WHERE ie_id = '{$this->id}' AND msgno IN ({$msgNos})";
1240 $this->db->query($q1);
1242 if(!empty($msgIds)) {
1243 $q2 = "DELETE FROM email_cache WHERE ie_id = '{$this->id}' AND message_id IN ({$msgIds})";
1244 $this->db->query($q2);
1250 * retrieves cached uidl values.
1251 * When dealing with POP3 accounts, the message_id column in email_cache will contain the UIDL.
1254 function pop3_getCacheUidls() {
1255 $q = "SELECT msgno, message_id FROM email_cache WHERE ie_id = '{$this->id}'";
1256 $r = $this->db->query($q);
1259 while($a = $this->db->fetchByAssoc($r)) {
1260 $ret[$a['msgno']] = $a['message_id'];
1267 * This function is used by cron job for group mailbox without group folder
1268 * @param string $msgno for pop
1269 * @param string $uid for imap
1271 function getMessagesInEmailCache($msgno, $uid) {
1272 $fetchedOverviews = array();
1273 if ($this->isPop3Protocol()) {
1274 $fetchedOverviews = imap_fetch_overview($this->conn, $msgno);
1275 foreach($fetchedOverviews as $k => $overview) {
1276 $overview->message_id = $uid;
1277 $fetchedOverviews[$k] = $overview;
1280 $fetchedOverviews = imap_fetch_overview($this->conn, $uid, FT_UID);
1282 $this->updateOverviewCacheFile($fetchedOverviews);
1287 * Checks email (local caching too) for one mailbox
1288 * @param string $mailbox IMAP Mailbox path
1289 * @param bool $prefetch Flag to prefetch email body on check
1291 function checkEmailOneMailbox($mailbox, $prefetch=true, $synchronize=false) {
1292 global $sugar_config;
1293 global $current_user;
1294 global $app_strings;
1298 $GLOBALS['log']->info("INBOUNDEMAIL: checking mailbox [ {$mailbox} ]");
1299 $this->mailbox = $mailbox;
1300 $this->connectMailserver();
1303 $shouldProcessRules = true;
1305 $timestamp = $this->getCacheTimestamp($mailbox);
1307 if($timestamp > 0) {
1308 $checkTime = date('r', $timestamp);
1311 /* first time through, process ALL emails */
1312 if(empty($checkTime) || $synchronize) {
1313 // do not process rules for the first time or sunchronize
1314 $shouldProcessRules = false;
1315 $criteria = "ALL UNDELETED";
1316 $prefetch = false; // do NOT prefetch emails on a brand new account - timeouts happen.
1317 $GLOBALS['log']->info("INBOUNDEMAIL: new account detected - not prefetching email bodies.");
1319 $criteria = "SINCE \"{$checkTime}\" UNDELETED"; // not using UNSEEN
1321 $this->setCacheTimestamp($mailbox);
1322 $GLOBALS['log']->info("[EMAIL] Performing IMAP search using criteria [{$criteria}] on mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1323 $searchResults = imap_search($this->conn, $criteria, SE_UID);
1324 $GLOBALS['log']->info("[EMAIL] Done IMAP search on mailbox [{$mailbox}] for user [{$current_user->user_name}]. Result count = ".count($searchResults));
1326 if(!empty($searchResults)) {
1328 $concatResults = implode(",", $searchResults);
1329 $GLOBALS['log']->info("[EMAIL] Start IMAP fetch overview on mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1330 $fetchedOverview = imap_fetch_overview($this->conn, $concatResults, FT_UID);
1331 $GLOBALS['log']->info("[EMAIL] Done IMAP fetch overview on mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1333 $GLOBALS['log']->info("[EMAIL] Start updating overview cache for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1334 $this->updateOverviewCacheFile($fetchedOverview);
1335 $GLOBALS['log']->info("[EMAIL] Done updating overview cache for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1338 if($prefetch == true) {
1339 $GLOBALS['log']->info("[EMAIL] Start fetching emails for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1340 if(!$this->fetchCheckedEmails($fetchedOverview))
1344 $GLOBALS['log']->info("[EMAIL] Done fetching emails for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1347 $GLOBALS['log']->info("INBOUNDEMAIL: no results for mailbox [ {$mailbox} ]");
1352 * To handle the use case where an external client is also connected, deleting emails, we need to clear our
1353 * local cache of all emails with the "DELETED" flag
1355 $criteria = 'DELETED';
1356 $criteria .= (!empty($checkTime)) ? " SINCE \"{$checkTime}\"" : "";
1357 $GLOBALS['log']->info("INBOUNDEMAIL: checking for deleted emails using [ {$criteria} ]");
1359 $trashFolder = $this->get_stored_options("trashFolder");
1360 if (empty($trashFolder)) {
1361 $trashFolder = "INBOX.Trash";
1364 if($this->mailbox != $trashFolder) {
1365 $searchResults = imap_search($this->conn, $criteria, SE_UID);
1366 if(!empty($searchResults)) {
1367 $uids = implode($app_strings['LBL_EMAIL_DELIMITER'], $searchResults);
1368 $GLOBALS['log']->info("INBOUNDEMAIL: removing UIDs found deleted [ {$uids} ]");
1369 $this->getOverviewsFromCacheFile($uids, $mailbox, true);
1376 * Checks email (local caching too) for one mailbox
1377 * @param string $mailbox IMAP Mailbox path
1378 * @param bool $prefetch Flag to prefetch email body on check
1380 function checkEmailOneMailboxPartial($mailbox, $prefetch=true, $synchronize=false, $start = 0, $max = -1) {
1381 global $sugar_config;
1382 global $current_user;
1383 global $app_strings;
1385 $GLOBALS['log']->info("INBOUNDEMAIL: checking mailbox [ {$mailbox} ]");
1386 $this->mailbox = $mailbox;
1387 $this->connectMailserver();
1390 $shouldProcessRules = true;
1392 $timestamp = $this->getCacheTimestamp($mailbox);
1394 if($timestamp > 0) {
1395 $checkTime = date('r', $timestamp);
1398 /* first time through, process ALL emails */
1399 if(empty($checkTime) || $synchronize) {
1400 // do not process rules for the first time or sunchronize
1401 $shouldProcessRules = false;
1402 $criteria = "ALL UNDELETED";
1403 $prefetch = false; // do NOT prefetch emails on a brand new account - timeouts happen.
1404 $GLOBALS['log']->info("INBOUNDEMAIL: new account detected - not prefetching email bodies.");
1406 $criteria = "SINCE \"{$checkTime}\" UNDELETED"; // not using UNSEEN
1408 $this->setCacheTimestamp($mailbox);
1409 $GLOBALS['log']->info("[EMAIL] Performing IMAP search using criteria [{$criteria}] on mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1410 $searchResults = $this->getCachedIMAPSearch($criteria);
1412 if(!empty($searchResults)) {
1414 $total = sizeof($searchResults);
1415 $searchResults = array_slice($searchResults, $start, $max);
1417 $GLOBALS['log']->info("INBOUNDEMAIL: there are $total messages in [{$mailbox}], we are on $start");
1418 $GLOBALS['log']->info("INBOUNDEMAIL: getting the next " . sizeof($searchResults) . " messages");
1419 $concatResults = implode(",", $searchResults);
1420 $GLOBALS['log']->info("INBOUNDEMAIL: Start IMAP fetch overview on mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1421 $fetchedOverview = imap_fetch_overview($this->conn, $concatResults, FT_UID);
1422 $GLOBALS['log']->info("INBOUNDEMAIL: Done IMAP fetch overview on mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1424 $GLOBALS['log']->info("INBOUNDEMAIL: Start updating overview cache for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1425 $this->updateOverviewCacheFile($fetchedOverview);
1426 $GLOBALS['log']->info("INBOUNDEMAIL: Done updating overview cache for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1429 if($prefetch == true) {
1430 $GLOBALS['log']->info("INBOUNDEMAIL: Start fetching emails for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1431 $this->fetchCheckedEmails($fetchedOverview);
1432 $GLOBALS['log']->info("INBOUNDEMAIL: Done fetching emails for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1434 $status = ($total > $start + sizeof($searchResults)) ? 'continue' : 'done';
1435 $ret = array('status' => $status, 'count' => $start + sizeof($searchResults), 'mbox' => $mailbox, 'totalcount' => $total);
1436 $GLOBALS['log']->info("INBOUNDEMAIL: $status : Downloaded " . $start + sizeof($searchResults) . "messages of $total");
1439 $GLOBALS['log']->info("INBOUNDEMAIL: no results for mailbox [ {$mailbox} ]");
1440 $ret = array('status' =>'done');
1443 if ($ret['status'] == 'done') {
1444 //Remove the cached search if we are done with this mailbox
1445 $cacheFilePath = clean_path("{$this->EmailCachePath}/{$this->id}/folders/SearchData.php");
1446 unlink($cacheFilePath);
1448 * To handle the use case where an external client is also connected, deleting emails, we need to clear our
1449 * local cache of all emails with the "DELETED" flag
1451 $criteria = 'DELETED';
1452 $criteria .= (!empty($checkTime)) ? " SINCE \"{$checkTime}\"" : "";
1453 $GLOBALS['log']->info("INBOUNDEMAIL: checking for deleted emails using [ {$criteria} ]");
1455 $trashFolder = $this->get_stored_options("trashFolder");
1456 if (empty($trashFolder)) {
1457 $trashFolder = "INBOX.Trash";
1460 if($this->mailbox != $trashFolder) {
1461 $searchResults = imap_search($this->conn, $criteria, SE_UID);
1462 if(!empty($searchResults)) {
1463 $uids = implode($app_strings['LBL_EMAIL_DELIMITER'], $searchResults);
1464 $GLOBALS['log']->info("INBOUNDEMAIL: removing UIDs found deleted [ {$uids} ]");
1465 $this->getOverviewsFromCacheFile($uids, $mailbox, true);
1472 function getCachedIMAPSearch($criteria) {
1473 global $current_user;
1474 global $sugar_config;
1476 $cacheDataExists = false;
1479 $cacheFolderPath = clean_path("{$this->EmailCachePath}/{$this->id}/folders");
1480 if (!file_exists($cacheFolderPath)) {
1481 mkdir_recursive($cacheFolderPath);
1483 $cacheFilePath = $cacheFolderPath . '/SearchData.php';
1484 $GLOBALS['log']->info("INBOUNDEMAIL: Cache path is $cacheFilePath");
1485 if(file_exists($cacheFilePath)) {
1486 $cacheDataExists = true;
1487 if($fh = @fopen($cacheFilePath, "rb")) {
1489 $chunksize = 1*(1024*1024); // how many bytes per chunk
1491 $buf = fgets($fh, $chunksize); // 8kb max buffer - shouldn't be more than 80 chars via pop3...
1492 $data = $data . $buf;
1496 $results = unserialize($data);
1499 if (!$cacheDataExists) {
1500 $searchResults = imap_search($this->conn, $criteria, SE_UID);
1501 if(count($searchResults) > 0) {
1502 $results = $searchResults;
1503 $data = serialize($searchResults);
1504 if($fh = @fopen($cacheFilePath, "w")) {
1513 function checkEmailIMAPPartial($prefetch=true, $synch = false) {
1514 $GLOBALS['log']->info("*****************INBOUNDEMAIL: at IMAP check partial");
1515 global $sugar_config;
1516 $result = $this->connectMailserver();
1517 if ($result == 'false')
1520 'status' => 'error',
1521 'message' => 'Email server is down'
1524 $mailboxes = $this->getMailboxes(true);
1525 if (!in_array('INBOX', $mailboxes)) {
1526 $mailboxes[] = 'INBOX';
1529 if (isset($_REQUEST['mbox']) && !empty($_REQUEST['mbox']) && isset($_REQUEST['currentCount'])) {
1530 $GLOBALS['log']->info("INBOUNDEMAIL: Picking up from where we left off");
1531 $mbox = $_REQUEST['mbox'];
1532 $count = $_REQUEST['currentCount'];
1535 $GLOBALS['log']->info("INBOUNDEMAIL: Cleaning out the cache");
1536 $this->cleanOutCache();
1538 $mbox = $mailboxes[0];
1541 $GLOBALS['log']->info("INBOUNDEMAIL:found " . sizeof($mailboxes) . " Mailboxes");
1542 $index = array_search($mbox, $mailboxes) + 1;
1543 $ret = $this->checkEmailOneMailboxPartial($mbox, $prefetch, $synch, $count, 100);
1544 while($ret['status'] == 'done' && $index < sizeof($mailboxes)) {
1545 if ($ret['count'] > 100) {
1546 $ret['mbox'] = $mailboxes[$index];
1547 $ret['status'] = 'continue';
1550 $GLOBALS['log']->info("INBOUNDEMAIL: checking account [ $index => $mbox : $count]");
1551 $mbox = $mailboxes[$index];
1552 $ret = $this->checkEmailOneMailboxPartial($mbox, $prefetch, $synch, 0, 100);
1559 function checkEmail2_meta() {
1560 global $sugar_config;
1562 $this->connectMailserver();
1563 $mailboxes = $this->getMailboxes(true);
1564 $mailboxes[] = 'INBOX';
1567 $GLOBALS['log']->info("INBOUNDEMAIL: checking account [ {$this->name} ]");
1569 $mailboxes_meta = array();
1570 foreach($mailboxes as $mailbox) {
1571 $mailboxes_meta[$mailbox] = $this->getMailboxProcessCount($mailbox);
1575 $ret['mailboxes'] = $mailboxes_meta;
1577 foreach($mailboxes_meta as $count) {
1578 $ret['processCount'] += $count;
1583 function getMailboxProcessCount($mailbox) {
1584 global $sugar_config;
1586 $GLOBALS['log']->info("INBOUNDEMAIL: checking mailbox [ {$mailbox} ]");
1587 $this->mailbox = $mailbox;
1588 $this->connectMailserver();
1590 $timestamp = $this->getCacheTimestamp($mailbox);
1593 if($timestamp > 0) {
1594 $checkTime = date('r', $timestamp);
1597 /* first time through, process ALL emails */
1598 if(empty($checkTime)) {
1599 $criteria = "ALL UNDELETED";
1600 $prefetch = false; // do NOT prefetch emails on a brand new account - timeouts happen.
1601 $GLOBALS['log']->info("INBOUNDEMAIL: new account detected - not prefetching email bodies.");
1603 $criteria = "SINCE \"{$checkTime}\" UNDELETED"; // not using UNSEEN
1606 $GLOBALS['log']->info("INBOUNDEMAIL: using [ {$criteria} ]");
1607 $searchResults = imap_search($this->conn, $criteria, SE_UID);
1609 if(!empty($searchResults)) {
1610 $concatResults = implode(",", $searchResults);
1612 $GLOBALS['log']->info("INBOUNDEMAIL: no results for mailbox [ {$mailbox} ]");
1615 if(empty($searchResults)) {
1619 return count($searchResults);
1625 function checkEmail($prefetch=true, $synch = false) {
1626 global $sugar_config;
1628 if($this->protocol == 'pop3') {
1629 $this->pop3_checkEmail();
1631 $this->connectMailserver();
1632 $mailboxes = $this->getMailboxes(true);
1635 $GLOBALS['log']->info("INBOUNDEMAIL: checking account [ {$this->name} ]");
1637 foreach($mailboxes as $mailbox) {
1638 $this->checkEmailOneMailbox($mailbox, $prefetch, $synch);
1644 * full synchronization
1646 function syncEmail() {
1647 global $sugar_config;
1648 global $current_user;
1650 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
1652 if(empty($showFolders)) {
1653 $showFolders = array();
1656 $email = new Email();
1657 $email->email2init();
1659 // personal accounts
1660 if($current_user->hasPersonalEmail()) {
1661 $personals = $this->retrieveByGroupId($current_user->id);
1663 foreach($personals as $personalAccount) {
1664 if(in_array($personalAccount->id, $showFolders)) {
1665 $personalAccount->email = $email;
1666 if ($personalAccount->isPop3Protocol()) {
1667 $personalAccount->deletePop3Cache();
1670 $personalAccount->cleanOutCache();
1671 $personalAccount->connectMailserver();
1672 $mailboxes = $personalAccount->getMailboxes(true);
1673 $mailboxes[] = 'INBOX';
1676 $GLOBALS['log']->info("[EMAIL] Start checking account [{$personalAccount->name}] for user [{$current_user->user_name}]");
1678 foreach($mailboxes as $mailbox) {
1679 $GLOBALS['log']->info("[EMAIL] Start checking mailbox [{$mailbox}] of account [{$personalAccount->name}] for user [{$current_user->user_name}]");
1680 $personalAccount->checkEmailOneMailbox($mailbox, false, true);
1681 $GLOBALS['log']->info("[EMAIL] Done checking mailbox [{$mailbox}] of account [{$personalAccount->name}] for user [{$current_user->user_name}]");
1683 $GLOBALS['log']->info("[EMAIL] Done checking account [{$personalAccount->name}] for user [{$current_user->user_name}]");
1689 $beans = $this->retrieveAllByGroupId($current_user->id, false);
1690 foreach($beans as $k => $groupAccount) {
1691 if(in_array($groupAccount->id, $showFolders)) {
1692 $groupAccount->email = $email;
1693 $groupAccount->cleanOutCache();
1694 $groupAccount->connectMailserver();
1695 $mailboxes = $groupAccount->getMailboxes(true);
1696 $mailboxes[] = 'INBOX';
1699 $GLOBALS['log']->info("INBOUNDEMAIL: checking account [ {$groupAccount->name} ]");
1701 foreach($mailboxes as $mailbox) {
1702 $groupAccount->checkEmailOneMailbox($mailbox, false, true);
1710 * Deletes cached messages when moving from folder to folder
1711 * @param string $uids
1712 * @param string $fromFolder
1713 * @param string $toFolder
1715 function deleteCachedMessages($uids, $fromFolder) {
1716 global $sugar_config;
1718 if(!isset($this->email) && !isset($this->email->et)) {
1719 $this->email = new Email();
1720 $this->email->email2init();
1723 $uids = $this->email->et->_cleanUIDList($uids);
1725 foreach($uids as $uid) {
1726 $file = "{$this->EmailCachePath}/{$this->id}/messages/{$fromFolder}{$uid}.php";
1728 if(file_exists($file)) {
1729 if(!unlink($file)) {
1730 $GLOBALS['log']->debug("INBOUNDEMAIL: Could not delete [ {$file} ]");
1737 * similar to imap_fetch_overview, but it gets overviews from a local cache
1739 * @param string $uids UIDs in comma-delimited format
1740 * @param string $mailbox The mailbox in focus, will default to $this->mailbox
1741 * @param bool $remove Default false
1744 function getOverviewsFromCacheFile($uids, $mailbox='', $remove=false) {
1745 global $app_strings;
1746 if(!isset($this->email) && !isset($this->email->et)) {
1747 $this->email = new Email();
1748 $this->email->email2init();
1751 $uids = $this->email->et->_cleanUIDList($uids, true);
1753 // load current cache file
1754 $mailbox = empty($mailbox) ? $this->mailbox : $mailbox;
1755 $cacheValue = $this->getCacheValue($mailbox);
1759 $exUids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
1760 foreach($exUids as $k => $uid) {
1761 $exUids[$k] = trim($uid);
1764 // fill $ret will requested $uids
1765 foreach($cacheValue['retArr'] as $k => $overview) {
1766 if(in_array($overview->imap_uid, $exUids)) {
1771 // remove requested $uids from current cache file (move_mail() type action)
1773 $this->setCacheValue($mailbox, array(), array(), $ret);
1779 * merges new info with the saved cached file
1780 * @param array $array Array of email Overviews
1781 * @param string $type 'append' or 'remove'
1782 * @param string $mailbox Target mailbox if not current assigned
1784 function updateOverviewCacheFile($array, $type='append', $mailbox='') {
1785 $mailbox = empty($mailbox) ? $this->mailbox : $mailbox;
1787 $cacheValue = $this->getCacheValue($mailbox);
1788 $uids = $cacheValue['uids'];
1790 $updateRows = array();
1791 $insertRows = array();
1792 $removeRows = array();
1795 if($type == 'append') { // append
1796 /* we are adding overviews to the cache file */
1797 foreach($array as $overview) {
1798 if(isset($overview->uid)) {
1799 $overview->imap_uid = $overview->uid; // coming from imap_fetch_overview() call
1802 if(!in_array($overview->imap_uid, $uids)) {
1803 $insertRows[] = $overview;
1807 $updatedCacheOverviews = array();
1808 // compare against generated list
1809 /* we are removing overviews from the cache file */
1810 foreach($cacheValue['retArr'] as $cacheOverview) {
1811 if(!in_array($cacheOverview->imap_uid, $uids)) {
1812 $insertRows[] = $cacheOverview;
1814 $removeRows[] = $cacheOverview;
1818 $cacheValue['retArr'] = $updatedCacheOverviews;
1821 $this->setCacheValue($mailbox, $insertRows, $updateRows, $removeRows);
1825 * Check email prefetches email bodies for quicker display
1826 * @param array array of fetched overviews
1828 function fetchCheckedEmails($fetchedOverviews) {
1829 global $sugar_config;
1831 if(is_array($fetchedOverviews) && !empty($fetchedOverviews)) {
1832 foreach($fetchedOverviews as $overview) {
1833 if($overview->size < 10000) {
1835 $uid = $overview->imap_uid;
1838 $file = "{$this->mailbox}{$uid}.php";
1839 $cacheFile = clean_path("{$this->EmailCachePath}/{$this->id}/messages/{$file}");
1841 if(!file_exists($cacheFile)) {
1842 $GLOBALS['log']->info("INBOUNDEMAIL: Prefetching email [ {$file} ]");
1843 $this->setEmailForDisplay($uid);
1844 $out = $this->displayOneEmail($uid, $this->mailbox);
1845 $this->email->et->writeCacheFile('out', $out, $this->id, 'messages', "{$this->mailbox}{$uid}.php");
1847 $GLOBALS['log']->debug("INBOUNDEMAIL: Trying to prefetch an email we already fetched! [ {$cacheFile} ]");
1850 $GLOBALS['log']->debug("*** INBOUNDEMAIL: prefetch has a message with no UID");
1854 $GLOBALS['log']->debug("INBOUNDEMAIL: skipping email prefetch - size too large [ {$overview->size} ]");
1862 * Sets flags on emails. Assumes that connection is live, correct folder is
1864 * @param string $uids Sequence of UIDs, comma separated
1865 * @param string $type Flag to mark
1867 function markEmails($uids, $type) {
1870 $result = imap_clearflag_full($this->conn, $uids, '\\SEEN', ST_UID);
1873 $result = imap_setflag_full($this->conn, $uids, '\\SEEN', ST_UID);
1876 $result = imap_setflag_full($this->conn, $uids, '\\FLAGGED', ST_UID);
1879 $result = imap_clearflag_full($this->conn, $uids, '\\FLAGGED', ST_UID);
1882 $result = imap_setflag_full($this->conn, $uids, '\\Answered', ST_UID);
1886 //// END EMAIL 2.0 SPECIFIC
1887 ///////////////////////////////////////////////////////////////////////////
1891 ///////////////////////////////////////////////////////////////////////////
1892 //// SERVER MANIPULATION METHODS
1894 * Deletes the specified folder
1895 * @param string $mbox "::" delimited IMAP mailbox path, ie, INBOX.saved.stuff
1898 function deleteFolder($mbox) {
1899 $returnArray = array();
1900 if ($this->getCacheCount($mbox) > 0) {
1901 $returnArray['status'] = false;
1902 $returnArray['errorMessage'] = "Can not delete {$mbox} as it has emails.";
1903 return $returnArray;
1905 $connectString = $this->getConnectString('', $mbox);
1906 //Remove Folder cache
1907 global $sugar_config;
1908 unlink("{$this->EmailCachePath}/{$this->id}/folders/folders.php");
1910 if(imap_unsubscribe($this->conn, imap_utf7_encode($connectString))) {
1911 if(imap_deletemailbox($this->conn, $connectString)) {
1912 $this->mailbox = str_replace(("," . $mbox), "", $this->mailbox);
1914 $sessionFoldersString = $this->getSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol);
1915 $sessionFoldersString = str_replace(("," . $mbox), "", $sessionFoldersString);
1916 $this->setSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol, $sessionFoldersString);
1917 $returnArray['status'] = true;
1918 return $returnArray;
1920 $GLOBALS['log']->error("*** ERROR: EMAIL2.0 - could not delete IMAP mailbox with path: [ {$connectString} ]");
1921 $returnArray['status'] = false;
1922 $returnArray['errorMessage'] = "NOOP: could not delete folder: {$connectString}";
1923 return $returnArray;
1927 $GLOBALS['log']->error("*** ERROR: EMAIL2.0 - could not unsubscribe from folder, {$connectString} before deletion.");
1928 $returnArray['status'] = false;
1929 $returnArray['errorMessage'] = "NOOP: could not unsubscribe from folder, {$connectString} before deletion.";
1930 return $returnArray;
1936 * @param string $name Name of new IMAP mailbox
1937 * @param string $mbox "::" delimited IMAP mailbox path, ie, INBOX.saved.stuff
1938 * @return bool True on success
1940 function saveNewFolder($name, $mbox) {
1941 global $sugar_config;
1942 //Remove Folder cache
1943 global $sugar_config;
1944 //unlink("{$this->EmailCachePath}/{$this->id}/folders/folders.php");
1946 //$mboxImap = $this->getImapMboxFromSugarProprietary($mbox);
1947 $delimiter = $this->get_stored_options('folderDelimiter');
1952 $newFolder = $mbox . $delimiter . $name;
1953 $mbox .= $delimiter.str_replace($delimiter, "_", $name);
1954 $connectString = $this->getConnectString('', $mbox);
1956 if(imap_createmailbox($this->conn, imap_utf7_encode($connectString))) {
1957 imap_subscribe($this->conn, imap_utf7_encode($connectString));
1958 $status = imap_status($this->conn, str_replace("{$delimiter}{$name}","",$connectString), SA_ALL);
1959 $this->mailbox = $this->mailbox . "," . $newFolder;
1961 $sessionFoldersString = $this->getSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol);
1962 $sessionFoldersString = $sessionFoldersString . "," . $newFolder;
1963 $this->setSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol, $sessionFoldersString);
1965 echo json_encode($status);
1968 echo "NOOP: could not create folder";
1969 $GLOBALS['log']->error("*** ERROR: EMAIL2.0 - could not create IMAP mailbox with path: [ {$connectString} ]");
1976 * Constructs an IMAP c-client compatible folder path from Sugar proprietary
1977 * @param string $mbox "::" delimited IMAP mailbox path, ie, INBOX.saved.stuff
1980 function getImapMboxFromSugarProprietary($mbox) {
1981 $exMbox = explode("::", $mbox);
1985 for($i=2; $i<count($exMbox); $i++) {
1986 if(!empty($mboxImap)) {
1989 $mboxImap .= $exMbox[$i];
1996 * Searches IMAP (and POP3?) accounts/folders for emails with qualifying criteria
1998 function search($ieId, $subject='', $from='', $to='', $body='', $dateFrom='', $dateTo='') {
1999 global $current_user;
2000 global $app_strings;
2004 $bean = new InboundEmail();
2005 $bean->retrieve($ieId);
2007 //$beans = $this->retrieveAllByGroupId($current_user->id, true);
2009 $subject = urldecode($subject);
2012 $criteria .= (!empty($subject)) ? 'SUBJECT '.from_html($subject).'' : "";
2013 $criteria .= (!empty($from)) ? ' FROM "'.$from.'"' : "";
2014 $criteria .= (!empty($to)) ? ' FROM "'.$to.'"' : "";
2015 $criteria .= (!empty($body)) ? ' TEXT "'.$body.'"' : "";
2016 $criteria .= (!empty($dateFrom)) ? ' SINCE "'.$timedate->fromString($dateFrom)->format('d-M-Y').'"' : "";
2017 $criteria .= (!empty($dateTo)) ? ' BEFORE "'.$timedate->fromString($dateTo)->format('d-M-Y').'"' : "";
2018 //$criteria .= (!empty($from)) ? ' FROM "'.$from.'"' : "";
2020 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
2024 foreach($beans as $bean) {
2025 if(!in_array($bean->id, $showFolders)) {
2029 $GLOBALS['log']->info("*** INBOUNDEMAIL: searching [ {$bean->name} ] for [ {$subject}{$from}{$to}{$body}{$dateFrom}{$dateTo} ]");
2030 $group = (!$bean->is_personal) ? 'group.' : '';
2031 $bean->connectMailServer();
2032 $mailboxes = $bean->getMailboxes(true);
2033 if (!in_array('INBOX', $mailboxes)) {
2034 $mailboxes[] = 'INBOX';
2038 foreach($mailboxes as $mbox) {
2039 $bean->mailbox = $mbox;
2040 $searchOverviews = array();
2041 if ($bean->protocol == 'pop3') {
2042 $pop3Criteria = "SELECT * FROM email_cache WHERE ie_id = '{$bean->id}' AND mbox = '{$mbox}'";
2043 $pop3Criteria .= (!empty($subject)) ? ' AND subject like "%'.$bean->db->quote($subject).'%"' : "";
2044 $pop3Criteria .= (!empty($from)) ? ' AND fromaddr like "%'.$from.'%"' : "";
2045 $pop3Criteria .= (!empty($to)) ? ' AND toaddr like "%'.$to.'%"' : "";
2046 $pop3Criteria .= (!empty($dateFrom)) ? ' AND senddate > "'.$dateFrom.'"' : "";
2047 $pop3Criteria .= (!empty($dateTo)) ? ' AND senddate < "'.$dateTo.'"' : "";
2048 $GLOBALS['log']->info("*** INBOUNDEMAIL: searching [ {$mbox} ] using criteria [ {$pop3Criteria} ]");
2050 $r = $bean->db->query($pop3Criteria);
2051 while($a = $bean->db->fetchByAssoc($r)) {
2052 $overview = new Overview();
2054 foreach($a as $k => $v) {
2058 $overview->imap_uid = $v;
2059 $overview->uid = $a['message_id'];
2062 $overview->to = from_html($v);
2066 $overview->from = from_html($v);
2070 $overview->size = $v;
2074 $overview->date = $timedate->fromString($v)->format('r');
2078 $overview->$k = from_html($v);
2082 $searchOverviews[] = $overview;
2085 $bean->connectMailServer();
2086 $searchResult = imap_search($bean->conn, $criteria, SE_UID);
2087 if (!empty($searchResult)) {
2088 $searchOverviews = imap_fetch_overview($bean->conn, implode(',', $searchResult), FT_UID);
2091 $numHits = count($searchOverviews);
2094 $totalHits = $totalHits + $numHits;
2095 $ret = $bean->sortFetchedOverview($searchOverviews, 'date', 'desc', true);
2096 $mbox = "{$bean->id}.SEARCH";
2097 $out = array_merge($out, $bean->displayFetchedSortedListXML($ret, $mbox, false));
2102 $metadata = array();
2103 $metadata['mbox'] = $app_strings['LBL_EMAIL_SEARCH_RESULTS_TITLE'];
2104 $metadata['ieId'] = $this->id;
2105 $metadata['name'] = $this->name;
2106 $metadata['unreadChecked'] = ($current_user->getPreference('showUnreadOnly', 'Emails') == 1) ? 'CHECKED' : '';
2107 $metadata['out'] = $out;
2113 * repairs the encrypted password for a given I-E account
2114 * @return bool True on success
2116 function repairAccount() {
2118 for($i=0; $i<3; $i++) {
2119 if($i != 0) { // decode is performed on retrieve already
2120 $this->email_password = blowfishDecode(blowfishGetKey('InboundEmail'), $this->email_password);
2123 if($this->connectMailserver() == 'true') {
2124 $this->save(); // save decoded password (is encoded on save())
2133 * soft deletes a User's personal inbox
2134 * @param string id I-E id
2135 * @param string user_name User name of User in focus, NOT current_user
2136 * @return bool True on success
2138 function deletePersonalEmailAccount($id, $user_name) {
2139 $q = "SELECT ie.id FROM inbound_email ie LEFT JOIN users u ON ie.group_id = u.id WHERE u.user_name = '{$user_name}'";
2140 $r = $this->db->query($q, true);
2142 while($a = $this->db->fetchByAssoc($r)) {
2143 if(!empty($a) && $a['id'] == $id) {
2144 $this->retrieve($id);
2153 function getTeamSetIdForTeams($teamIds) {
2154 if(!is_array($teamIds)){
2155 $teamIds = array($teamIds);
2157 $teamSet = new TeamSet();
2158 $team_set_id = $teamSet->addTeams($teamIds);
2159 return $team_set_id;
2163 * Saves Personal Inbox settings for Users
2164 * @param string userId ID of user to assign all emails for this account
2165 * @param strings userName Name of account, for Sugar purposes
2166 * @param bool forceSave Default true. Flag to save errored settings.
2167 * @return boolean true on success, false on fail
2169 function savePersonalEmailAccount($userId = '', $userName = '', $forceSave=true) {
2171 $accountExists = false;
2172 if(isset($_REQUEST['ie_id']) && !empty($_REQUEST['ie_id'])) {
2173 $this->retrieve($_REQUEST['ie_id']);
2174 $accountExists = true;
2176 $ie_name = $_REQUEST['ie_name'];
2178 $this->is_personal = 1;
2179 $this->name = $ie_name;
2180 $this->group_id = $groupId;
2181 $this->status = $_REQUEST['ie_status'];
2182 $this->server_url = trim($_REQUEST['server_url']);
2183 $this->email_user = trim($_REQUEST['email_user']);
2184 if(!empty($_REQUEST['email_password'])) {
2185 $this->email_password = html_entity_decode($_REQUEST['email_password'], ENT_QUOTES);
2187 $this->port = trim($_REQUEST['port']);
2188 $this->protocol = $_REQUEST['protocol'];
2189 if ($this->protocol == "pop3") {
2190 $_REQUEST['mailbox'] = "INBOX";
2192 $this->mailbox = $_REQUEST['mailbox'];
2193 $this->mailbox_type = 'pick'; // forcing this
2196 if(isset($_REQUEST['ssl']) && $_REQUEST['ssl'] == 1) { $useSsl = true; }
2197 else $useSsl = false;
2198 $this->service = '::::::::::';
2201 $id = $this->save(); // saving here to prevent user from having to re-enter all the info in case of error
2202 $this->retrieve($id);
2205 $this->protocol = $_REQUEST['protocol']; // need to set this again since we safe the "service" string to empty explode values
2206 $opts = $this->getSessionConnectionString($this->server_url, $this->email_user, $this->port, $this->protocol);
2207 $detectedOpts = $this->findOptimumSettings($useSsl);
2209 //If $detectedOpts is empty, there was an error connecting, so clear $opts. If $opts was empty, use $detectedOpts
2210 if (empty($opts) || empty($detectedOpts) || (empty($detectedOpts['good']) && empty($detectedOpts['serial'])))
2212 $opts = $detectedOpts;
2214 $delimiter = $this->getSessionInboundDelimiterString($this->server_url, $this->email_user, $this->port, $this->protocol);
2216 if(isset($opts['serial']) && !empty($opts['serial'])) {
2217 $this->service = $opts['serial'];
2218 if(isset($_REQUEST['mark_read']) && $_REQUEST['mark_read'] == 1) {
2219 $this->delete_seen = 0;
2221 $this->delete_seen = 1;
2224 // handle stored_options serialization
2225 if(isset($_REQUEST['only_since']) && $_REQUEST['only_since'] == 1) {
2231 $focusUser = new User();
2232 $focusUser->retrieve($groupId);
2233 $mailerId = (isset($_REQUEST['outbound_email'])) ? $_REQUEST['outbound_email'] : "";
2235 $oe = new OutboundEmail();
2236 $oe->getSystemMailerSettings($focusUser, $mailerId);
2238 $stored_options = array();
2239 $stored_options['from_name'] = trim($_REQUEST['from_name']);
2240 $stored_options['from_addr'] = trim($_REQUEST['from_addr']);
2241 $stored_options['reply_to_addr'] = trim($_REQUEST['reply_to_addr']);
2243 if (!$this->isPop3Protocol()) {
2244 $stored_options['trashFolder'] = (isset($_REQUEST['trashFolder']) ? trim($_REQUEST['trashFolder']) : "");
2245 $stored_options['sentFolder'] = (isset($_REQUEST['sentFolder']) ? trim($_REQUEST['sentFolder']) : "");
2247 $stored_options['only_since'] = $onlySince;
2248 $stored_options['filter_domain'] = '';
2249 $storedOptions['folderDelimiter'] = $delimiter;
2250 $stored_options['outbound_email'] = (isset($_REQUEST['outbound_email'])) ? $_REQUEST['outbound_email'] : $oe->id;
2251 $this->stored_options = base64_encode(serialize($stored_options));
2253 $ieId = $this->save();
2255 //If this is the first personal account the user has setup mark it as default for them.
2256 $currentIECount = $this->getUserPersonalAccountCount($focusUser);
2257 if($currentIECount == 1)
2258 $this->setUsersDefaultOutboundServerId($focusUser, $ieId);
2262 // could not find opts, no save
2263 $GLOBALS['log']->debug('-----> InboundEmail could not find optimums for User: '.$ie_name);
2268 * Determines if this instance of I-E is for a Group Inbox or Personal Inbox
2270 function handleIsPersonal() {
2271 $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.'\'';
2272 $rp = $this->db->query($qp, true);
2273 $personalBox = array();
2274 while($ap = $this->db->fetchByAssoc($rp)) {
2275 $personalBox[] = array($ap['id'], $ap['user_name']);
2277 if(count($personalBox) > 0) {
2284 function getUserNameFromGroupId() {
2285 $r = $this->db->query('SELECT users.user_name FROM users WHERE deleted=0 AND id=\''.$this->group_id.'\'', true);
2286 while($a = $this->db->fetchByAssoc($r)) {
2287 return $a['user_name'];
2292 function getFoldersListForMailBox() {
2294 $foldersList = $this->getSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol);
2295 if (empty($foldersList)) {
2296 global $mod_strings;
2297 $msg = $this->connectMailserver(true);
2298 if (strpos($msg, "successfully")) {
2299 $foldersList = $this->getSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol);
2300 $return['status'] = true;
2301 $return['foldersList'] = $foldersList;
2302 $return['statusMessage'] = "";
2304 $return['status'] = false;
2305 $return['statusMessage'] = $msg;
2308 $return['status'] = true;
2309 $return['foldersList'] = $foldersList;
2310 $return['statusMessage'] = "";
2315 * Programatically determines best-case settings for imap_open()
2317 function findOptimumSettings($useSsl=false, $user='', $pass='', $server='', $port='', $prot='', $mailbox='') {
2318 global $mod_strings;
2319 $serviceArr = array();
2320 $returnService = array();
2321 $badService = array();
2322 $goodService = array();
2323 $errorArr = array();
2325 $retArray = array( 'good' => $goodService,
2326 'bad' => $badService,
2327 'err' => $errorArr);
2329 if(!function_exists('imap_open')) {
2330 $retArray['err'][0] = $mod_strings['ERR_NO_IMAP'];
2334 imap_errors(); // clearing error stack
2335 error_reporting(0); // turn off notices from IMAP
2337 if(isset($_REQUEST['ssl']) && $_REQUEST['ssl'] == 1) {
2341 $exServ = explode('::', $this->service);
2342 $service = '/'.$exServ[1];
2344 $nonSsl = array('both-secure' => '/notls/novalidate-cert/secure',
2345 'both' => '/notls/novalidate-cert',
2346 'nocert-secure' => '/novalidate-cert/secure',
2347 'nocert' => '/novalidate-cert',
2348 'notls-secure' => '/notls/secure',
2349 'secure' => '/secure', // for POP3 servers that force CRAM-MD5
2350 'notls' => '/notls',
2351 'none' => '', // try default nothing
2354 'ssl-both-on-secure' => '/ssl/tls/validate-cert/secure',
2355 'ssl-both-on' => '/ssl/tls/validate-cert',
2356 'ssl-cert-secure' => '/ssl/validate-cert/secure',
2357 'ssl-cert' => '/ssl/validate-cert',
2358 'ssl-tls-secure' => '/ssl/tls/secure',
2359 'ssl-tls' => '/ssl/tls',
2360 'ssl-both-off-secure' => '/ssl/notls/novalidate-cert/secure',
2361 'ssl-both-off' => '/ssl/notls/novalidate-cert',
2362 'ssl-nocert-secure' => '/ssl/novalidate-cert/secure',
2363 'ssl-nocert' => '/ssl/novalidate-cert',
2364 'ssl-notls-secure' => '/ssl/notls/secure',
2365 'ssl-notls' => '/ssl/notls',
2366 'ssl-secure' => '/ssl/secure',
2367 'ssl-none' => '/ssl',
2370 if(isset($user) && !empty($user) && isset($pass) && !empty($pass)) {
2371 $this->email_password = $pass;
2372 $this->email_user = $user;
2373 $this->server_url = $server;
2374 $this->port = $port;
2375 $this->protocol = $prot;
2376 $this->mailbox = $mailbox;
2379 // in case we flip from IMAP to POP3
2380 if($this->protocol == 'pop3')
2381 $this->mailbox = 'INBOX';
2383 //If user has selected multiple mailboxes, we only need to test the first mailbox for the connection string.
2384 $a_mailbox = explode(",", $this->mailbox);
2385 $tmpMailbox = isset($a_mailbox[0]) ? $a_mailbox[0] : "";
2389 foreach($ssl as $k => $service)
2391 $returnService[$k] = 'foo'.$service;
2392 $serviceArr[$k] = '{'.$this->server_url.':'.$this->port.'/service='.$this->protocol.$service.'}'.$tmpMailbox;
2397 foreach($nonSsl as $k => $service)
2399 $returnService[$k] = 'foo'.$service;
2400 $serviceArr[$k] = '{'.$this->server_url.':'.$this->port.'/service='.$this->protocol.$service.'}'.$tmpMailbox;
2404 $GLOBALS['log']->debug('---------------STARTING FINDOPTIMUMS LOOP----------------');
2407 //php imap library will capture c-client library warnings as errors causing good connections to be ignored.
2408 //Check against known warnings to ensure good connections are used.
2409 $acceptableWarnings = array("SECURITY PROBLEM: insecure server advertised AUTH=PLAIN", //c-client auth_pla.c
2410 "Mailbox is empty");
2411 $login = $this->email_user;
2412 $passw = $this->email_password;
2413 $foundGoodConnection = false;
2414 foreach($serviceArr as $k => $serviceTest) {
2417 $GLOBALS['log']->debug($l.': I-E testing string: '.$serviceTest);
2419 // open the connection and try the test string
2420 $this->conn = imap_open($serviceTest, $login, $passw);
2422 if(($errors = imap_last_error()) || ($alerts = imap_alerts())) {
2423 if($errors == 'Too many login failures' || $errors == '[CLOSED] IMAP connection broken (server response)') { // login failure means don't bother trying the rest
2424 $GLOBALS['log']->debug($l.': I-E failed using ['.$serviceTest.']');
2425 $retArray['err'][$k] = $mod_strings['ERR_BAD_LOGIN_PASSWORD'];
2426 $retArray['bad'][$k] = $serviceTest;
2427 $GLOBALS['log']->debug($l.': I-E ERROR: $ie->findOptimums() failed due to bad user credentials for user login: '.$this->email_user);
2429 } elseif( in_array($errors, $acceptableWarnings, TRUE)) { // false positive
2430 $GLOBALS['log']->debug($l.': I-E found good connection but with warnings ['.$serviceTest.'] Errors:' . $errors);
2431 $retArray['good'][$k] = $returnService[$k];
2432 $foundGoodConnection = true;
2435 $GLOBALS['log']->debug($l.': I-E failed using ['.$serviceTest.'] - error: '.$errors);
2436 $retArray['err'][$k] = $errors;
2437 $retArray['bad'][$k] = $serviceTest;
2440 $GLOBALS['log']->debug($l.': I-E found good connect using ['.$serviceTest.']');
2441 $retArray['good'][$k] = $returnService[$k];
2442 $foundGoodConnection = true;
2445 if(is_resource($this->conn)) {
2446 if (!$this->isPop3Protocol()) {
2447 $serviceTest = str_replace("INBOX", "", $serviceTest);
2448 $boxes = imap_getmailboxes($this->conn, $serviceTest, "*");
2450 // clean MBOX path names
2451 foreach($boxes as $k => $mbox) {
2452 $raw[] = $mbox->name;
2453 if ($mbox->delimiter) {
2454 $delimiter = $mbox->delimiter;
2457 $this->setSessionInboundDelimiterString($this->server_url, $this->email_user, $this->port, $this->protocol, $delimiter);
2460 if(!imap_close($this->conn)) $GLOBALS['log']->debug('imap_close() failed!');
2463 $GLOBALS['log']->debug($l.': I-E clearing error and alert stacks.');
2464 imap_errors(); // clear stacks
2466 // If you find a good connection, then don't do any further testing to find URL
2467 if ($foundGoodConnection) {
2472 $GLOBALS['log']->debug('---------------end FINDOPTIMUMS LOOP----------------');
2474 if(!empty($retArray['good'])) {
2479 $newNovalidate_cert = '';
2480 $good = array_pop($retArray['good']); // get most complete string
2481 $exGood = explode('/', $good);
2482 foreach($exGood as $v) {
2491 $newNotls = 'notls';
2494 $newCert = 'validate-cert';
2496 case 'novalidate-cert':
2497 $newNovalidate_cert = 'novalidate-cert';
2505 $goodStr['serial'] = $newTls.'::'.$newCert.'::'.$newSsl.'::'.$this->protocol.'::'.$newNovalidate_cert.'::'.$newNotls.'::'.$secure;
2506 $goodStr['service'] = $good;
2507 $testConnectString = str_replace('foo','', $good);
2508 $testConnectString = '{'.$this->server_url.':'.$this->port.'/service='.$this->protocol.$testConnectString.'}';
2509 $this->setSessionConnectionString($this->server_url, $this->email_user, $this->port, $this->protocol, $goodStr);
2511 foreach($raw as $mbox)
2513 $raw[$i] = str_replace($testConnectString, "", $GLOBALS['locale']->translateCharset($mbox, "UTF7-IMAP", "UTF8" ));
2517 $this->setSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol, implode(",", $raw));
2524 function getSessionConnectionString($server_url, $email_user, $port, $protocol) {
2525 $sessionConnectionString = $server_url . $email_user . $port . $protocol;
2526 return (isset($_SESSION[$sessionConnectionString]) ? $_SESSION[$sessionConnectionString] : "");
2529 function setSessionConnectionString($server_url, $email_user, $port, $protocol, $goodStr) {
2530 $sessionConnectionString = $server_url . $email_user . $port . $protocol;
2531 $_SESSION[$sessionConnectionString] = $goodStr;
2534 function getSessionInboundDelimiterString($server_url, $email_user, $port, $protocol) {
2535 $sessionInboundDelimiterString = $server_url . $email_user . $port . $protocol . "delimiter";
2536 return (isset($_SESSION[$sessionInboundDelimiterString]) ? $_SESSION[$sessionInboundDelimiterString] : "");
2539 function setSessionInboundDelimiterString($server_url, $email_user, $port, $protocol, $delimiter) {
2540 $sessionInboundDelimiterString = $server_url . $email_user . $port . $protocol . "delimiter";
2541 $_SESSION[$sessionInboundDelimiterString] = $delimiter;
2544 function getSessionInboundFoldersString($server_url, $email_user, $port, $protocol) {
2545 $sessionInboundFoldersListString = $server_url . $email_user . $port . $protocol . "foldersList";
2546 return (isset($_SESSION[$sessionInboundFoldersListString]) ? $_SESSION[$sessionInboundFoldersListString] : "");
2549 function setSessionInboundFoldersString($server_url, $email_user, $port, $protocol, $foldersList) {
2550 $sessionInboundFoldersListString = $server_url . $email_user . $port . $protocol . "foldersList";
2551 $_SESSION[$sessionInboundFoldersListString] = $foldersList;
2555 * Checks for duplicate Group User names when creating a new one at save()
2556 * @return GUID returns GUID of Group User if user_name match is
2558 * @return boolean false if NO DUPE IS FOUND
2560 function groupUserDupeCheck() {
2561 $q = "SELECT u.id FROM users u WHERE u.deleted=0 AND u.is_group=1 AND u.user_name = '".$this->name."'";
2562 $r = $this->db->query($q, true);
2564 while($a = $this->db->fetchByAssoc($r)) {
2568 if(strlen($uid) > 0) {
2576 * Returns <option> markup with the contents of Group users
2577 * @param array $groups default empty array
2578 * @return string HTML options
2580 function getGroupsWithSelectOptions($groups = array()) {
2581 $r = $this->db->query('SELECT id, user_name FROM users WHERE users.is_group = 1 AND deleted = 0', true);
2582 if(is_resource($r)) {
2583 while($a = $this->db->fetchByAssoc($r)) {
2584 $groups[$a['id']] = $a['user_name'];
2588 $selectOptions = get_select_options_with_id_separate_key($groups, $groups, $this->group_id);
2589 return $selectOptions;
2593 * handles auto-responses to inbound emails
2595 * @param object email Email passed as reference
2597 function handleAutoresponse(&$email, &$contactAddr) {
2598 if($this->template_id) {
2599 $GLOBALS['log']->debug('found auto-reply template id - prefilling and mailing response');
2601 if($this->getAutoreplyStatus($contactAddr)
2602 && $this->checkOutOfOffice($email->name)
2603 && $this->checkFilterDomain($email)) { // if we haven't sent this guy 10 replies in 24hours
2605 if(!empty($this->stored_options)) {
2606 $storedOptions = unserialize(base64_decode($this->stored_options));
2609 if(!empty($storedOptions['from_name'])) {
2610 $from_name = $storedOptions['from_name'];
2611 $GLOBALS['log']->debug('got from_name from storedOptions: '.$from_name);
2612 } else { // use system default
2613 $rName = $this->db->query('SELECT value FROM config WHERE name = \'fromname\'', true);
2614 if(is_resource($rName)) {
2615 $aName = $this->db->fetchByAssoc($rName);
2617 if(!empty($aName['value'])) {
2618 $from_name = $aName['value'];
2624 if(!empty($storedOptions['from_addr'])) {
2625 $from_addr = $storedOptions['from_addr'];
2627 $rAddr = $this->db->query('SELECT value FROM config WHERE name = \'fromaddress\'', true);
2628 if(is_resource($rAddr)) {
2629 $aAddr = $this->db->fetchByAssoc($rAddr);
2631 if(!empty($aAddr['value'])) {
2632 $from_addr = $aAddr['value'];
2638 $replyToName = (!empty($storedOptions['reply_to_name']))? from_html($storedOptions['reply_to_name']) :$from_name ;
2639 $replyToAddr = (!empty($storedOptions['reply_to_addr'])) ? $storedOptions['reply_to_addr'] : $from_addr;
2642 if(!empty($email->reply_to_email)) {
2643 $to[0]['email'] = $email->reply_to_email;
2645 $to[0]['email'] = $email->from_addr;
2647 // handle to name: address, prefer reply-to
2648 if(!empty($email->reply_to_name)) {
2649 $to[0]['display'] = $email->reply_to_name;
2650 } elseif(!empty($email->from_name)) {
2651 $to[0]['display'] = $email->from_name;
2654 $et = new EmailTemplate();
2655 $et->retrieve($this->template_id);
2656 if(empty($et->subject)) { $et->subject = ''; }
2657 if(empty($et->body)) { $et->body = ''; }
2658 if(empty($et->body_html)) { $et->body_html = ''; }
2660 $reply = new Email();
2661 $reply->type = 'out';
2662 $reply->to_addrs = $to[0]['email'];
2663 $reply->to_addrs_arr = $to;
2664 $reply->cc_addrs_arr = array();
2665 $reply->bcc_addrs_arr = array();
2666 $reply->from_name = $from_name;
2667 $reply->from_addr = $from_addr;
2668 $reply->name = $et->subject;
2669 $reply->description = $et->body;
2670 $reply->description_html = $et->body_html;
2671 $reply->reply_to_name = $replyToName;
2672 $reply->reply_to_addr = $replyToAddr;
2674 $GLOBALS['log']->debug('saving and sending auto-reply email');
2675 //$reply->save(); // don't save the actual email.
2677 $this->setAutoreplyStatus($contactAddr);
2679 $GLOBALS['log']->debug('InboundEmail: auto-reply threshold reached for email ('.$contactAddr.') - not sending auto-reply');
2684 function handleCaseAssignment($email) {
2686 if($caseId = $this->getCaseIdFromCaseNumber($email->name, $c)) {
2687 $c->retrieve($caseId);
2688 $email->retrieve($email->id);
2689 //assign the case info to parent id and parent type so that the case can be linked to the email on Email Save
2690 $email->parent_type = "Cases";
2691 $email->parent_id = $caseId;
2692 // assign the email to the case owner
2693 $email->assigned_user_id = $c->assigned_user_id;
2695 $GLOBALS['log']->debug('InboundEmail found exactly 1 match for a case: '.$c->name);
2702 * handles functionality specific to the Mailbox type (Cases, bounced
2705 * @param object email Email object passed as a reference
2706 * @param object header Header object generated by imap_headerinfo();
2708 function handleMailboxType(&$email, &$header) {
2709 switch($this->mailbox_type) {
2711 $this->handleCaseAssignment($email);
2718 // do something with this?
2721 // do something with leads? we don't have an email_leads table
2727 require_once('modules/Campaigns/ProcessBouncedEmails.php');
2728 campaign_process_bounced_emails($email, $header);
2730 case 'pick': // do all except bounce handling
2731 $GLOBALS['log']->debug('looking for a case for '.$email->name);
2732 $this->handleCaseAssignment($email);
2737 function isMailBoxTypeCreateCase() {
2738 return ($this->mailbox_type == 'createcase' && !empty($this->groupfolder_id));
2741 function handleCreateCase($email, $userId) {
2742 global $current_user, $mod_strings, $current_language;
2743 $mod_strings = return_module_language($current_language, "Emails");
2744 $GLOBALS['log']->debug('In handleCreateCase');
2746 $this->getCaseIdFromCaseNumber($email->name, $c);
2748 if (!$this->handleCaseAssignment($email) && $this->isMailBoxTypeCreateCase()) {
2750 $GLOBALS['log']->debug('retrieveing email');
2751 $email->retrieve($email->id);
2753 $c->description = $email->description;
2754 $c->assigned_user_id = $userId;
2755 $c->name = $email->name;
2757 $c->priority = 'P1';
2759 if(!empty($email->reply_to_email)) {
2760 $contactAddr = $email->reply_to_email;
2762 $contactAddr = $email->from_addr;
2765 $GLOBALS['log']->debug('finding related accounts with address ' . $contactAddr);
2766 if($accountIds = $this->getRelatedId($contactAddr, 'accounts')) {
2767 if (sizeof($accountIds) == 1) {
2768 $c->account_id = $accountIds[0];
2770 $acct = new Account();
2771 $acct->retrieve($c->account_id);
2772 $c->account_name = $acct->name;
2778 $c->retrieve($caseId);
2779 if($c->load_relationship('emails')) {
2780 $c->emails->add($email->id);
2782 if($contactIds = $this->getRelatedId($contactAddr, 'contacts')) {
2783 if(!empty($contactIds) && $c->load_relationship('contacts')) {
2784 $c->contacts->add($contactIds);
2787 $c->email_id = $email->id;
2788 $email->parent_type = "Cases";
2789 $email->parent_id = $caseId;
2790 // assign the email to the case owner
2791 $email->assigned_user_id = $c->assigned_user_id;
2792 $email->name = str_replace('%1', $c->case_number, $c->getEmailSubjectMacro()) . " ". $email->name;
2794 $GLOBALS['log']->debug('InboundEmail created one case with number: '.$c->case_number);
2795 $createCaseTemplateId = $this->get_stored_options('create_case_email_template', "");
2796 if(!empty($this->stored_options)) {
2797 $storedOptions = unserialize(base64_decode($this->stored_options));
2799 if(!empty($createCaseTemplateId)) {
2802 if (!empty($this->stored_options)) {
2803 $fromAddress = $storedOptions['from_addr'];
2804 $fromName = from_html($storedOptions['from_name']);
2805 $replyToName = (!empty($storedOptions['reply_to_name']))? from_html($storedOptions['reply_to_name']) :$fromName ;
2806 $replyToAddr = (!empty($storedOptions['reply_to_addr'])) ? $storedOptions['reply_to_addr'] : $fromAddress;
2808 $defaults = $current_user->getPreferredEmail();
2809 $fromAddress = (!empty($fromAddress)) ? $fromAddress : $defaults['email'];
2810 $fromName = (!empty($fromName)) ? $fromName : $defaults['name'];
2811 $to[0]['email'] = $contactAddr;
2813 // handle to name: address, prefer reply-to
2814 if(!empty($email->reply_to_name)) {
2815 $to[0]['display'] = $email->reply_to_name;
2816 } elseif(!empty($email->from_name)) {
2817 $to[0]['display'] = $email->from_name;
2820 $et = new EmailTemplate();
2821 $et->retrieve($createCaseTemplateId);
2822 if(empty($et->subject)) { $et->subject = ''; }
2823 if(empty($et->body)) { $et->body = ''; }
2824 if(empty($et->body_html)) { $et->body_html = ''; }
2826 $et->subject = "Re:" . " " . str_replace('%1', $c->case_number, $c->getEmailSubjectMacro() . " ". $c->name);
2828 $html = trim($email->description_html);
2829 $plain = trim($email->description);
2831 $email->email2init();
2832 $email->from_addr = $email->from_addr_name;
2833 $email->to_addrs = $email->to_addrs_names;
2834 $email->cc_addrs = $email->cc_addrs_names;
2835 $email->bcc_addrs = $email->bcc_addrs_names;
2836 $email->from_name = $email->from_addr;
2838 $email = $email->et->handleReplyType($email, "reply");
2839 $ret = $email->et->displayComposeEmail($email);
2840 $ret['description'] = empty($email->description_html) ? str_replace("\n", "\n<BR/>", $email->description) : $email->description_html;
2842 $reply = new Email();
2843 $reply->type = 'out';
2844 $reply->to_addrs = $to[0]['email'];
2845 $reply->to_addrs_arr = $to;
2846 $reply->cc_addrs_arr = array();
2847 $reply->bcc_addrs_arr = array();
2848 $reply->from_name = $fromName;
2849 $reply->from_addr = $fromAddress;
2850 $reply->reply_to_name = $replyToName;
2851 $reply->reply_to_addr = $replyToAddr;
2852 $reply->name = $et->subject;
2853 $reply->description = $et->body . "<div><hr /></div>" . $email->description;
2854 if (!$et->text_only) {
2855 $reply->description_html = $et->body_html . "<div><hr /></div>" . $email->description;
2857 $GLOBALS['log']->debug('saving and sending auto-reply email');
2858 //$reply->save(); // don't save the actual email.
2863 if(!empty($email->reply_to_email)) {
2864 $contactAddr = $email->reply_to_email;
2866 $contactAddr = $email->from_addr;
2868 $this->handleAutoresponse($email, $contactAddr);
2874 * handles linking contacts, accounts, etc. to an email
2876 * @param object Email bean to be linked against
2877 * @return string contactAddr is the email address of the sender
2879 function handleLinking(&$email) {
2880 // link email to an User if emails match TO addr
2881 if($userIds = $this->getRelatedId($email->to_addrs, 'users')) {
2882 $GLOBALS['log']->debug('I-E linking email to User');
2883 // link the user to the email
2884 $email->load_relationship('users');
2885 $email->users->add($userIds);
2888 // link email to a Contact, Lead, or Account if the emails match
2889 // give precedence to REPLY-TO above FROM
2890 if(!empty($email->reply_to_email)) {
2891 $contactAddr = $email->reply_to_email;
2893 $contactAddr = $email->from_addr;
2896 // Samir Gandhi : 12/06/07
2897 // This changes has been done because the linking was done only with the from address and
2898 // not with to address
2899 $relationShipAddress = $contactAddr;
2900 if (empty($relationShipAddress)) {
2901 $relationShipAddress .= $email->to_addrs;
2903 $relationShipAddress = $relationShipAddress . "," . $email->to_addrs;
2905 if($leadIds = $this->getRelatedId($relationShipAddress, 'leads')) {
2906 $GLOBALS['log']->debug('I-E linking email to Lead');
2907 $email->load_relationship('leads');
2908 $email->leads->add($leadIds);
2910 foreach($leadIds as $leadId) {
2912 $lead->retrieve($leadId);
2913 $lead->load_relationship('emails');
2914 $lead->emails->add($email->id);
2918 if($contactIds = $this->getRelatedId($relationShipAddress, 'contacts')) {
2919 $GLOBALS['log']->debug('I-E linking email to Contact');
2920 // link the contact to the email
2921 $email->load_relationship('contacts');
2922 $email->contacts->add($contactIds);
2925 if($accountIds = $this->getRelatedId($relationShipAddress, 'accounts')) {
2926 $GLOBALS['log']->debug('I-E linking email to Account');
2927 // link the account to the email
2928 $email->load_relationship('accounts');
2929 $email->accounts->add($accountIds);
2931 /* cn: bug 9171 another cause of dying I-E - bad linking
2932 foreach($accountIds as $accountId) {
2933 $GLOBALS['log']->debug('I-E reverse-linking Accounts to Emails');
2934 $acct = new Account();
2935 $acct->retrieve($accountId);
2936 $acct->load_relationship('emails');
2937 $acct->account_emails->add($email->id);
2941 return $contactAddr;
2945 * Gets part by following breadcrumb path
2946 * @param string $bc the breadcrumb string in format (1.1.1)
2947 * @param array parts the root level parts array
2949 protected function getPartByPath($bc, $parts)
2951 if(strstr($bc,'.')) {
2952 $exBc = explode('.', $bc);
2957 foreach($exBc as $step) {
2958 if(empty($parts)) return false;
2959 $res = $parts[$step-1]; // MIME starts with 1, array starts with 0
2960 if(!empty($res->parts)) {
2961 $parts = $res->parts;
2970 * takes a breadcrumb and returns the encoding at that level
2971 * @param string bc the breadcrumb string in format (1.1.1)
2972 * @param array parts the root level parts array
2973 * @return int retInt Int key to transfer encoding (see handleTranserEncoding())
2975 function getEncodingFromBreadCrumb($bc, $parts) {
2976 if(strstr($bc,'.')) {
2977 $exBc = explode('.', $bc);
2982 $depth = count($exBc);
2984 for($i=0; $i<$depth; $i++) {
2985 $tempObj[$i] = $parts[($exBc[$i]-1)];
2986 $retInt = imap_utf8($tempObj[$i]->encoding);
2987 if(!empty($tempObj[$i]->parts)) {
2988 $parts = $tempObj[$i]->parts;
2995 * retrieves the charset for a given part of an email body
2997 * @param string bc target part of the message in format (1.1.1)
2998 * @param array parts 1 level above ROOT array of Objects representing a multipart body
2999 * @return string charset name
3001 function getCharsetFromBreadCrumb($bc, $parts)
3003 $tempObj = $this->getPartByPath($bc, $parts);
3004 // now we have the tempObj at the end of the breadCrumb trail
3006 if(!empty($tempObj->ifparameters)) {
3007 foreach($tempObj->parameters as $param) {
3008 if(strtolower($param->attribute) == 'charset') {
3009 return $param->value;
3018 * Get the message text from a single mime section, html or plain.
3020 * @param string $msgNo
3021 * @param string $section
3022 * @param stdObject $structure
3025 function getMessageTextFromSingleMimePart($msgNo,$section,$structure)
3027 $msgPartTmp = imap_fetchbody($this->conn, $msgNo, $section);
3028 $enc = $this->getEncodingFromBreadCrumb($section, $structure->parts);
3029 $charset = $this->getCharsetFromBreadCrumb($section, $structure->parts);
3030 $msgPartTmp = $this->handleTranserEncoding($msgPartTmp, $enc);
3031 return $this->handleCharsetTranslation($msgPartTmp, $charset);
3035 * Givin an existing breadcrumb add a cooresponding offset
3038 * @param string $offset
3041 function addBreadCrumbOffset($bc, $offset)
3043 if( (empty($bc) || is_null($bc)) && !empty($offset) )
3046 $a_bc = explode(".", $bc);
3047 $a_offset = explode(".",$offset);
3048 if(count($a_bc) < count($a_offset))
3049 $a_bc = array_merge($a_bc,array_fill( count($a_bc), count($a_offset) - count($a_bc), 0));
3052 for($i=0;$i < count($a_bc); $i++)
3054 if(isset($a_offset[$i]))
3055 $results[] = $a_bc[$i] + $a_offset[$i];
3057 $results[] = $a_bc[$i];
3059 return implode(".", $results);
3063 * returns the HTML text part of a multi-part message
3065 * @param int msgNo the relative message number for the monitored mailbox
3066 * @param string $type the type of text processed, either 'PLAIN' or 'HTML'
3067 * @return string UTF-8 encoded version of the requested message text
3069 function getMessageText($msgNo, $type, $structure, $fullHeader,$clean_email=true, $bcOffset = "") {
3070 global $sugar_config;
3073 $bc = $this->buildBreadCrumbs($structure->parts, $type);
3074 //Add an offset if specified
3075 if(!empty($bcOffset))
3076 $bc = $this->addBreadCrumbOffset($bc, $bcOffset);
3078 if(!empty($bc)) { // multi-part
3079 // HUGE difference between PLAIN and HTML
3080 if($type == 'PLAIN') {
3081 $msgPart = $this->getMessageTextFromSingleMimePart($msgNo,$bc,$structure);
3083 // get part of structure that will
3085 $bcArray = $this->buildBreadCrumbsHTML($structure->parts,$bcOffset);
3086 // construct inline HTML/Rich msg
3087 foreach($bcArray as $bcArryKey => $bcArr) {
3088 foreach($bcArr as $type => $bcTrail) {
3090 $msgPartRaw .= $this->getMessageTextFromSingleMimePart($msgNo,$bcTrail,$structure);
3092 // deal with inline image
3093 $part = $this->getPartByPath($bcTrail, $structure->parts);
3094 if(empty($part) || empty($part->id)) continue;
3095 $partid = substr($part->id, 1, -1); // strip <> around
3096 if(isset($this->inlineImages[$partid])) {
3097 $imageName = $this->inlineImages[$partid];
3098 $newImagePath = "class=\"image\" src=\"{$this->imagePrefix}{$imageName}\"";
3099 $preImagePath = "src=\"cid:$partid\"";
3100 $msgPartRaw = str_replace($preImagePath, $newImagePath, $msgPartRaw);
3105 $msgPart = $msgPartRaw;
3107 } else { // either PLAIN message type (flowed) or b0rk3d RFC
3108 // make sure we're working on valid data here.
3109 if($structure->subtype != $type) {
3113 $decodedHeader = $this->decodeHeader($fullHeader);
3115 // now get actual body contents
3116 $text = imap_body($this->conn, $msgNo);
3118 $upperCaseKeyDecodeHeader = array();
3119 if (is_array($decodedHeader)) {
3120 $upperCaseKeyDecodeHeader = array_change_key_case($decodedHeader, CASE_UPPER);
3122 if(isset($upperCaseKeyDecodeHeader[strtoupper('Content-Transfer-Encoding')])) {
3123 $flip = array_flip($this->transferEncoding);
3124 $text = $this->handleTranserEncoding($text, $flip[strtoupper($upperCaseKeyDecodeHeader[strtoupper('Content-Transfer-Encoding')])]);
3127 if(is_array($upperCaseKeyDecodeHeader['CONTENT-TYPE']) && isset($upperCaseKeyDecodeHeader['CONTENT-TYPE']['charset']) && !empty($upperCaseKeyDecodeHeader['CONTENT-TYPE']['charset'])) {
3128 // we have an explicit content type, use it
3129 $msgPart = $this->handleCharsetTranslation($text, $upperCaseKeyDecodeHeader['CONTENT-TYPE']['charset']);
3131 // make a best guess as to what our content type is
3132 $msgPart = $this->convertToUtf8($text);
3134 } // end else clause
3136 $msgPart = $this->customGetMessageText($msgPart);
3137 /* cn: bug 9176 - htmlEntitites hide XSS attacks. */
3138 if($type == 'PLAIN') {
3139 return SugarCleaner::cleanHtml(to_html($msgPart), false);
3141 // Bug 50241: can't process <?xml:namespace .../> properly. Strip <?xml ...> tag first.
3142 $msgPart = preg_replace("/<\?xml[^>]*>/","",$msgPart);
3144 return SugarCleaner::cleanHtml($msgPart, false);
3148 * decodes raw header information and passes back an associative array with
3149 * the important elements key'd by name
3150 * @param header string the raw header
3151 * @return decodedHeader array the associative array
3153 function decodeHeader($fullHeader) {
3154 $decodedHeader = array();
3155 $exHeaders = explode("\r", $fullHeader);
3156 if (!is_array($exHeaders)) {
3157 $exHeaders = explode("\r\n", $fullHeader);
3159 $quotes = array('"', "'");
3161 foreach($exHeaders as $lineNum => $head) {
3163 $key = trim(substr($head, 0, strpos($head, ':')));
3165 $value = trim(substr($head, (strpos($head, ':') + 1), strlen($head)));
3167 // handle content-type section in headers
3168 if(strtolower($key) == 'content-type' && strpos($value, ';')) { // ";" means something follows related to (such as Charset)
3169 $semiColPos = mb_strpos($value, ';');
3170 $strLenVal = mb_strlen($value);
3171 if(($semiColPos + 4) >= $strLenVal) {
3172 // the charset="[something]" is on the next line
3173 $value .= str_replace($quotes, "", trim($exHeaders[$lineNum+1]));
3176 $newValue = array();
3177 $exValue = explode(';', $value);
3178 $newValue['type'] = $exValue[0];
3180 for($i=1; $i<count($exValue); $i++) {
3181 $exContent = explode('=', $exValue[$i]);
3182 $newValue[trim($exContent[0])] = trim($exContent[1], "\t \"");
3187 if(!empty($key) && !empty($value)) {
3188 $decodedHeader[$key] = $value;
3192 return $decodedHeader;
3196 * handles translating message text from orignal encoding into UTF-8
3198 * @param string text test to be re-encoded
3199 * @param string charset original character set
3200 * @return string utf8 re-encoded text
3202 function handleCharsetTranslation($text, $charset) {
3205 if(empty($charset)) {
3206 $GLOBALS['log']->debug("***ERROR: InboundEmail::handleCharsetTranslation() called without a \$charset!");
3207 $GLOBALS['log']->debug("***STACKTRACE: ".print_r(debug_backtrace(), true));
3211 // typical headers have no charset - let destination pick (since it's all ASCII anyways)
3212 if(strtolower($charset) == 'default' || strtolower($charset) == 'utf-8') {
3216 return $locale->translateCharset($text, $charset);
3222 * Builds up the "breadcrumb" trail that imap_fetchbody() uses to return
3223 * parts of an email message, including attachments and inline images
3224 * @param $parts array of objects
3225 * @param $subtype what type of trail to return? HTML? Plain? binaries?
3226 * @param $breadcrumb text trail to build up
3228 function buildBreadCrumbs($parts, $subtype, $breadcrumb = '0') {
3229 //_pp('buildBreadCrumbs building for '.$subtype.' with BC at '.$breadcrumb);
3230 // loop through available parts in the array
3231 foreach($parts as $k => $part) {
3232 // mark passage through level
3234 // if this is not the first time through, start building the map
3235 if($breadcrumb != 0) {
3236 $thisBc = $breadcrumb.'.'.$thisBc;
3239 // found a multi-part/mixed 'part' - keep digging
3240 if($part->type == 1 && (strtoupper($part->subtype) == 'RELATED' || strtoupper($part->subtype) == 'ALTERNATIVE' || strtoupper($part->subtype) == 'MIXED')) {
3241 //_pp('in loop: going deeper with subtype: '.$part->subtype.' $k is: '.$k);
3242 $thisBc = $this->buildBreadCrumbs($part->parts, $subtype, $thisBc);
3245 } elseif(strtolower($part->subtype) == strtolower($subtype)) { // found the subtype we want, return the breadcrumb value
3246 //_pp('found '.$subtype.' bc! returning: '.$thisBc);
3249 //_pp('found '.$part->subtype.' instead');
3255 * Similar to buildBreadCrumbs() but returns an ordered array containing all parts of the message that would be
3256 * considered "HTML" or Richtext (embedded images, formatting, etc.).
3257 * @param array parts Array of parts of a message
3258 * @param int breadcrumb Passed integer value to start breadcrumb trail
3259 * @param array stackedBreadcrumbs Persistent trail of breadcrumbs
3260 * @return array Ordered array of parts to retrieve via imap_fetchbody()
3262 function buildBreadCrumbsHTML($parts, $breadcrumb = '0', $stackedBreadcrumbs = array()) {
3264 $disposition = 'inline';
3266 foreach($parts as $k => $part) {
3267 // mark passage through level
3270 if($breadcrumb != 0) {
3271 $thisBc = $breadcrumb.'.'.$thisBc;
3273 // found a multi-part/mixed 'part' - keep digging
3274 if($part->type == 1 && (strtoupper($part->subtype) == 'RELATED' || strtoupper($part->subtype) == 'ALTERNATIVE' || strtoupper($part->subtype) == 'MIXED')) {
3275 $stackedBreadcrumbs = $this->buildBreadCrumbsHTML($part->parts, $thisBc, $stackedBreadcrumbs);
3277 (strtolower($part->subtype) == strtolower($subtype)) ||
3279 isset($part->disposition) && strtolower($part->disposition) == 'inline' &&
3280 in_array(strtoupper($part->subtype), $this->imageTypes)
3283 // found the subtype we want, return the breadcrumb value
3284 $stackedBreadcrumbs[] = array(strtolower($part->subtype) => $thisBc);
3285 } elseif($part->type == 5) {
3286 $stackedBreadcrumbs[] = array(strtolower($part->subtype) => $thisBc);
3290 return $stackedBreadcrumbs;
3294 * Takes a PHP imap_* object's to/from/cc/bcc address field and converts it
3295 * to a standard string that SugarCRM expects
3296 * @param $arr an array of email address objects
3298 function convertImapToSugarEmailAddress($arr) {
3299 if(is_array($arr)) {
3301 foreach($arr as $key => $obj) {
3302 $addr .= $obj->mailbox.'@'.$obj->host.', ';
3305 $ret = substr_replace($addr,'',-2,-1);
3311 * tries to figure out what character set a given filename is using and
3312 * decode based on that
3314 * @param string name Name of attachment
3315 * @return string decoded name
3317 function handleEncodedFilename($name) {
3318 $imapDecode = imap_mime_header_decode($name);
3319 /******************************
3320 $imapDecode => stdClass Object
3323 [text] => w�hlen.php
3328 $imapDecode => stdClass Object
3330 [charset] => default
3331 [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
3333 *******************************/
3334 if($imapDecode[0]->charset != 'default') { // mime-header encoded charset
3335 $encoding = $imapDecode[0]->charset;
3336 $name = $imapDecode[0]->text; // encoded in that charset
3338 /* encoded filenames are formatted as [encoding]''[filename] */
3339 if(strpos($name, "''") !== false) {
3341 $encoding = substr($name, 0, strpos($name, "'"));
3343 while(strpos($name, "'") !== false) {
3344 $name = trim(substr($name, (strpos($name, "'")+1), strlen($name)));
3347 $name = urldecode($name);
3349 return (strtolower($encoding) == 'utf-8') ? $name : $GLOBALS['locale']->translateCharset($name, $encoding, 'UTF-8');
3353 Primary body types for a part of a mail structure (imap_fetchstructure returned object)
3365 Primary body types for a part of a mail structure (imap_fetchstructure returned object)
3366 @var array $imap_types
3368 public $imap_types = array(
3378 public function getMimeType($type, $subtype)
3380 if(isset($this->imap_types[$type])) {
3381 return $this->imap_types[$type]."/$subtype";
3383 return "other/$subtype";
3388 * Takes the "parts" attribute of the object that imap_fetchbody() method
3389 * returns, and recursively goes through looking for objects that have a
3390 * disposition of "attachement" or "inline"
3391 * @param int $msgNo The relative message number for the monitored mailbox
3392 * @param object $parts Array of objects to examine
3393 * @param string $emailId The GUID of the email saved prior to calling this method
3394 * @param array $breadcrumb Default 0, build up of the parts mapping
3395 * @param bool $forDisplay Default false
3397 function saveAttachments($msgNo, $parts, $emailId, $breadcrumb='0', $forDisplay) {
3398 global $sugar_config;
3400 Primary body types for a part of a mail structure (imap_fetchstructure returned object)
3411 foreach($parts as $k => $part) {
3413 if($breadcrumb != '0') {
3414 $thisBc = $breadcrumb.'.'.$thisBc;
3417 // check if we need to recurse into the object
3418 //if($part->type == 1 && !empty($part->parts)) {
3419 if(isset($part->parts) && !empty($part->parts) && !( isset($part->subtype) && strtolower($part->subtype) == 'rfc822') ) {
3420 $this->saveAttachments($msgNo, $part->parts, $emailId, $thisBc, $forDisplay);
3422 } elseif($part->ifdisposition) {
3423 // we will take either 'attachments' or 'inline'
3424 if(strtolower($part->disposition) == 'attachment' || ((strtolower($part->disposition) == 'inline') && $part->type != 0)) {
3425 $attach = $this->getNoteBeanForAttachment($emailId);
3426 $fname = $this->handleEncodedFilename($this->retrieveAttachmentNameFromStructure($part->dparameters));
3428 if(!empty($fname)) {//assign name to attachment
3429 $attach->name = $fname;
3430 } else {//if name is empty, default to filename
3431 $attach->name = urlencode($this->retrieveAttachmentNameFromStructure($part->dparameters));
3433 $attach->filename = $attach->name;
3434 if (empty($attach->filename)) {
3438 // deal with the MIME types email has
3439 $attach->file_mime_type = $this->getMimeType($part->type, $part->subtype);
3440 $attach->safeAttachmentName();
3442 $attach->id = $this->getTempFilename();
3444 // only save if doing a full import, else we want only the binaries
3447 } // end if disposition type 'attachment'
3448 }// end ifdisposition
3449 //Retrieve contents of subtype rfc8822
3450 elseif ($part->type == 2 && isset($part->subtype) && strtolower($part->subtype) == 'rfc822' )
3452 $tmp_eml = imap_fetchbody($this->conn, $msgNo, $thisBc);
3453 $attach = $this->getNoteBeanForAttachment($emailId);
3454 $attach->file_mime_type = 'messsage/rfc822';
3455 $attach->description = $tmp_eml;
3456 $attach->filename = 'bounce.eml';
3457 $attach->safeAttachmentName();
3459 $attach->id = $this->getTempFilename();
3461 // only save if doing a full import, else we want only the binaries
3464 } elseif(!$part->ifdisposition && $part->type != 1 && $part->type != 2 && $thisBc != '1') {
3465 // No disposition here, but some IMAP servers lie about disposition headers, try to find the truth
3466 // Also Outlook puts inline attachments as type 5 (image) without a disposition
3467 if($part->ifparameters) {
3468 foreach($part->parameters as $param) {
3469 if(strtolower($param->attribute) == "name" || strtolower($param->attribute) == "filename") {
3470 $fname = $this->handleEncodedFilename($param->value);
3474 if(empty($fname)) continue;
3476 // we assume that named parts are attachments too
3477 $attach = $this->getNoteBeanForAttachment($emailId);
3479 $attach->filename = $attach->name = $fname;
3480 $attach->file_mime_type = $this->getMimeType($part->type, $part->subtype);
3482 $attach->safeAttachmentName();
3484 $attach->id = $this->getTempFilename();
3486 // only save if doing a full import, else we want only the binaries
3491 $this->saveAttachmentBinaries($attach, $msgNo, $thisBc, $part, $forDisplay);
3496 * Return a new note object for attachments.
3498 * @param string $emailId
3501 function getNoteBeanForAttachment($emailId)
3503 $attach = new Note();
3504 $attach->parent_id = $emailId;
3505 $attach->parent_type = 'Emails';
3511 * Return the filename of the attachment by examining the dparameters returned from imap_fetch_structure which
3512 * represet the content-disposition of the MIME header.
3514 * @param array $dparamaters
3517 function retrieveAttachmentNameFromStructure($dparamaters)
3521 foreach ($dparamaters as $k => $v)
3523 if( strtolower($v->attribute) == 'filename')
3525 $result = $v->value;
3534 * saves the actual binary file of a given attachment
3535 * @param object attach Note object that is attached to the binary file
3536 * @param string msgNo Message Number on IMAP/POP3 server
3537 * @param string thisBc Breadcrumb to navigate email structure to find the content
3538 * @param object part IMAP standard object that contains the "parts" of this section of email
3539 * @param bool $forDisplay
3541 function saveAttachmentBinaries($attach, $msgNo, $thisBc, $part, $forDisplay) {
3542 // decide where to place the file temporarily
3543 $uploadDir = ($forDisplay) ? "{$this->EmailCachePath}/{$this->id}/attachments/" : "upload://";
3545 // decide what name to save file as
3546 $fileName = $attach->id;
3548 // download the attachment if we didn't do it yet
3549 if(!file_exists($uploadDir.$fileName)) {
3550 $msgPartRaw = imap_fetchbody($this->conn, $msgNo, $thisBc);
3551 // deal with attachment encoding and decode the text string
3552 $msgPart = $this->handleTranserEncoding($msgPartRaw, $part->encoding);
3554 if(file_put_contents($uploadDir.$fileName, $msgPart)) {
3555 $GLOBALS['log']->debug('InboundEmail saved attachment file: '.$attach->filename);
3557 $GLOBALS['log']->debug('InboundEmail could not create attachment file: '.$attach->filename ." - temp file target: [ {$uploadDir}{$fileName} ]");
3562 $this->tempAttachment[$fileName] = urldecode($attach->filename);
3563 // if all was successful, feel for inline and cache Note ID for display:
3564 if((strtolower($part->disposition) == 'inline' && in_array($part->subtype, $this->imageTypes))
3565 || ($part->type == 5)) {
3566 if(copy($uploadDir.$fileName, sugar_cached("images/{$fileName}.").strtolower($part->subtype))) {
3567 $id = substr($part->id, 1, -1); //strip <> around
3568 $this->inlineImages[$id] = $attach->id.".".strtolower($part->subtype);
3570 $GLOBALS['log']->debug('InboundEmail could not copy '.$uploadDir.$fileName.' to cache');
3576 * decodes a string based on its associated encoding
3577 * if nothing is passed, we default to no-encoding type
3578 * @param $str encoded string
3579 * @param $enc detected encoding
3581 function handleTranserEncoding($str, $enc=0) {
3587 $ret = base64_decode($str);
3589 case 4:// QUOTED-PRINTABLE
3590 $ret = quoted_printable_decode($str);
3592 case 0:// 7BIT or 8BIT
3593 case 1:// already in a string-useable format - do nothing
3595 default:// catch all
3605 * Some emails do not get assigned a message_id, specifically from
3608 * We need to derive a reliable one for duplicate import checking.
3610 function getMessageId($header) {
3611 $message_id = md5(print_r($header, true));
3616 * checks for duplicate emails on polling. The uniqueness of a given email message is determined by a concatenation
3617 * of 2 values, the messageID and the delivered-to field. This allows multiple To: and B/CC: destination addresses
3618 * to be imported by Sugar without violating the true duplicate-email issues.
3620 * @param string message_id message ID generated by sending server
3621 * @param int message number (mailserver's key) of email
3622 * @param object header object generated by imap_headerinfo()
3623 * @param string textHeader Headers in normal text format
3626 function importDupeCheck($message_id, $header, $textHeader) {
3627 $GLOBALS['log']->debug('*********** InboundEmail doing dupe check.');
3629 // generate "delivered-to" seed for email duplicate check
3630 $deliveredTo = $this->id; // cn: bug 12236 - cc's failing dupe check
3631 $exHeader = explode("\n", $textHeader);
3633 foreach($exHeader as $headerLine) {
3634 if(strpos(strtolower($headerLine), 'delivered-to:') !== false) {
3635 $deliveredTo = substr($headerLine, strpos($headerLine, " "), strlen($headerLine));
3636 $GLOBALS['log']->debug('********* InboundEmail found [ '.$deliveredTo.' ] as the destination address for email [ '.$message_id.' ]');
3637 } elseif(strpos(strtolower($headerLine), 'x-real-to:') !== false) {
3638 $deliveredTo = substr($headerLine, strpos($headerLine, " "), strlen($headerLine));
3639 $GLOBALS['log']->debug('********* InboundEmail found [ '.$deliveredTo.' ] for non-standards compliant email x-header [ '.$message_id.' ]');
3643 //if(empty($message_id) && !isset($message_id)) {
3644 if(empty($message_id) || !isset($message_id)) {
3645 $GLOBALS['log']->debug('*********** NO MESSAGE_ID.');
3646 $message_id = $this->getMessageId($header);
3649 // generate compound messageId
3650 $this->compoundMessageId = trim($message_id).trim($deliveredTo);
3651 if (empty($this->compoundMessageId)) {
3652 $GLOBALS['log']->error('Inbound Email found a message without a header and message_id');
3655 $this->compoundMessageId = md5($this->compoundMessageId);
3657 $query = 'SELECT count(emails.id) AS c FROM emails WHERE emails.message_id = \''.$this->compoundMessageId.'\' and emails.deleted = 0';
3658 $r = $this->db->query($query, true);
3659 $a = $this->db->fetchByAssoc($r);
3662 $GLOBALS['log']->debug('InboundEmail found a duplicate email with ID ('.$this->compoundMessageId.')');
3663 return false; // we have a dupe and don't want to import the email'
3670 * takes the output from imap_mime_hader_decode() and handles multiple types of encoding
3671 * @param string subject Raw subject string from email
3672 * @return string ret properly formatted UTF-8 string
3674 function handleMimeHeaderDecode($subject) {
3675 $subjectDecoded = imap_mime_header_decode($subject);
3678 foreach($subjectDecoded as $object) {
3679 if($object->charset != 'default') {
3680 $ret .= $this->handleCharsetTranslation($object->text, $object->charset);
3682 $ret .= $object->text;
3689 * Calculates the appropriate display date/time sent for an email.
3690 * @param string headerDate The date sent of email in MIME header format
3691 * @return string GMT-0 Unix timestamp
3693 function getUnixHeaderDate($headerDate) {
3696 if (empty($headerDate)) {
3699 ///////////////////////////////////////////////////////////////////
3700 //// CALCULATE CORRECT SENT DATE/TIME FOR EMAIL
3701 if(!empty($headerDate)) {
3702 // Bug 25254 - Strip trailing space that come in some header dates (maybe ones with 1-digit day number)
3703 $headerDate = trim($headerDate);
3704 // need to hack PHP/windows' bad handling of strings when using POP3
3705 if(strstr($headerDate,'+0000 GMT')) {
3706 $headerDate = str_replace('GMT','', $headerDate);
3707 } elseif(!strtotime($headerDate)) {
3708 $headerDate = 'now'; // catch non-standard format times.
3710 // cn: bug 9196 parse the GMT offset
3711 if(strpos($headerDate, '-') || strpos($headerDate, '+')) {
3712 // cn: bug make sure last 5 chars are [+|-]nnnn
3713 if(strpos($headerDate, "(")) {
3714 $headerDate = preg_replace('/\([\w]+\)/i', "", $headerDate);
3715 $headerDate = trim($headerDate);
3718 // parse mailserver time
3719 $gmtEmail = trim(substr($headerDate, -5, 5));
3720 $posNeg = substr($gmtEmail, 0, 1);
3721 $gmtHours = substr($gmtEmail, 1, 2);
3722 $gmtMins = substr($gmtEmail, -2, 2);
3725 $secsHours = $gmtHours * 60 * 60;
3726 $secsTotal = $secsHours + ($gmtMins * 60);
3727 $secsTotal = ($posNeg == '-') ? $secsTotal : -1 * $secsTotal;
3729 $headerDate = trim(substr_replace($headerDate, '', -5)); // mfh: bug 10961/12855 - date time values with GMT offsets not properly formatted
3733 $headerDate = 'now';
3736 $unixHeaderDate = strtotime($headerDate);
3738 if(isset($secsTotal)) {
3739 // this gets the timestamp to true GMT-0
3740 $unixHeaderDate += $secsTotal;
3743 if(strtotime('Jan 1, 2001') > $unixHeaderDate) {
3744 $unixHeaderDate = strtotime('now');
3747 return $unixHeaderDate;
3748 //// END CALCULATE CORRECT SENT DATE/TIME FOR EMAIL
3749 ///////////////////////////////////////////////////////////////////
3753 * This method returns the correct messageno for the pop3 protocol
3754 * @param String UIDL
3755 * @return returnMsgNo
3757 function getCorrectMessageNoForPop3($messageId) {
3759 if ($this->protocol == 'pop3') {
3760 if($this->pop3_open()) {
3761 // get the UIDL from database;
3762 $query = "SELECT msgno FROM email_cache WHERE ie_id = '{$this->id}' AND message_id = '{$messageId}'";
3763 $r = $this->db->query($query);
3764 $a = $this->db->fetchByAssoc($r);
3765 $msgNo = $a['msgno'];
3766 $returnMsgNo = $msgNo;
3769 $this->pop3_sendCommand("USER", $this->email_user);
3770 $this->pop3_sendCommand("PASS", $this->email_password);
3772 // get UIDL for this msgNo
3773 $this->pop3_sendCommand("UIDL {$msgNo}", '', false); // leave socket buffer alone until the while()
3774 $buf = fgets($this->pop3socket, 1024); // handle "OK+ msgNo UIDL(UIDL for this messageno)";
3776 // if it returns OK then we have found the message else get all the UIDL
3777 // and search for the correct msgNo;
3778 $foundMessageNo = false;
3779 if (preg_match("/OK/", $buf) > 0) {
3780 $mailserverResponse = explode(" ", $buf);
3781 // if the cachedUIDL and the UIDL from mail server matches then its the correct messageno
3782 if (trim($mailserverResponse[sizeof($mailserverResponse) - 1]) == $messageId) {
3783 $foundMessageNo = true;
3787 //get all the UIDL and then find the correct messageno
3788 if (!$foundMessageNo) {
3790 $this->pop3_sendCommand("UIDL", '', false); // leave socket buffer alone until the while()
3791 fgets($this->pop3socket, 1024); // handle "OK+";
3794 if(is_resource($this->pop3socket)) {
3795 while(!feof($this->pop3socket)) {
3796 $buf = fgets($this->pop3socket, 1024); // 8kb max buffer - shouldn't be more than 80 chars via pop3...
3797 if(trim($buf) == '.') {
3798 $GLOBALS['log']->debug("*** GOT '.'");
3801 // format is [msgNo] [UIDL]
3802 $exUidl = explode(" ", $buf);
3803 $UIDLs[trim($exUidl[1])] = trim($exUidl[0]);
3805 if (array_key_exists($messageId, $UIDLs)) {
3806 $returnMsgNo = $UIDLs[$messageId];
3808 // message could not be found on server
3814 $this->pop3_cleanUp();
3817 return $returnMsgNo;
3821 * If the importOneEmail returns false, then findout if the duplicate email
3823 function getDuplicateEmailId($msgNo, $uid) {
3825 global $app_strings;
3826 global $app_list_strings;
3827 global $sugar_config;
3828 global $current_user;
3830 $header = imap_headerinfo($this->conn, $msgNo);
3831 $fullHeader = imap_fetchheader($this->conn, $msgNo); // raw headers
3833 // reset inline images cache
3834 $this->inlineImages = array();
3836 // handle messages deleted on server
3837 if(empty($header)) {
3838 if(!isset($this->email) || empty($this->email)) {
3839 $this->email = new Email();
3843 $dupeCheckResult = $this->importDupeCheck($header->message_id, $header, $fullHeader);
3844 if (!$dupeCheckResult && !empty($this->compoundMessageId)) {
3845 // we have a duplicate email
3846 $query = 'SELECT id FROM emails WHERE emails.message_id = \''.$this->compoundMessageId.'\' and emails.deleted = 0';
3847 $r = $this->db->query($query, true);
3848 $a = $this->db->fetchByAssoc($r);
3850 $this->email = new Email();
3851 $this->email->id = $a['id'];
3860 * shiny new importOneEmail() method
3862 * @param bool forDisplay
3863 * @param clean_email boolean, default true,
3865 function importOneEmail($msgNo, $uid, $forDisplay=false, $clean_email=true) {
3866 $GLOBALS['log']->debug("InboundEmail processing 1 email {$msgNo}-----------------------------------------------------------------------------------------");
3868 global $app_strings;
3869 global $app_list_strings;
3870 global $sugar_config;
3871 global $current_user;
3874 // So, on older versions of PHP (PHP VERSION < 5.3),
3875 // calling imap_headerinfo and imap_fetchheader can cause a buffer overflow for exteremly large headers,
3876 // This leads to the remaining messages not being read because Sugar crashes everytime it tries to read the headers.
3877 // The workaround is to mark a message as read before making trying to read the header of the msg in question
3878 // This forces this message not be read again, and we can continue processing remaining msgs.
3880 // UNCOMMENT THIS IF YOU HAVE THIS PROBLEM! See notes on Bug # 45477
3881 // $this->markEmails($uid, "read");
3883 $header = imap_headerinfo($this->conn, $msgNo);
3884 $fullHeader = imap_fetchheader($this->conn, $msgNo); // raw headers
3886 // reset inline images cache
3887 $this->inlineImages = array();
3889 // handle messages deleted on server
3890 if(empty($header)) {
3891 if(!isset($this->email) || empty($this->email)) {
3892 $this->email = new Email();
3896 if ($this->isPop3Protocol()) {
3897 $this->email->name = $app_strings['LBL_EMAIL_ERROR_MESSAGE_DELETED'];
3898 $q = "DELETE FROM email_cache WHERE message_id = '{$uid}' AND ie_id = '{$this->id}' AND mbox = '{$this->mailbox}'";
3900 $this->email->name = $app_strings['LBL_EMAIL_ERROR_IMAP_MESSAGE_DELETED'];
3901 $q = "DELETE FROM email_cache WHERE imap_uid = {$uid} AND ie_id = '{$this->id}' AND mbox = '{$this->mailbox}'";
3903 // delete local cache
3904 $r = $this->db->query($q);
3906 $this->email->date_sent = $timedate->nowDb();
3908 //return "Message deleted from server.";
3911 ///////////////////////////////////////////////////////////////////////
3912 //// DUPLICATE CHECK
3913 $dupeCheckResult = $this->importDupeCheck($header->message_id, $header, $fullHeader);
3914 if($forDisplay || $dupeCheckResult) {
3915 $GLOBALS['log']->debug('*********** NO duplicate found, continuing with processing.');
3917 $structure = imap_fetchstructure($this->conn, $msgNo); // map of email
3919 ///////////////////////////////////////////////////////////////////
3920 //// CREATE SEED EMAIL OBJECT
3921 $email = new Email();
3922 $email->isDuplicate = ($dupeCheckResult) ? false : true;
3923 $email->mailbox_id = $this->id;
3925 $email->id = create_guid();
3926 $email->new_with_id = true; //forcing a GUID here to prevent double saves.
3927 //// END CREATE SEED EMAIL
3928 ///////////////////////////////////////////////////////////////////
3930 ///////////////////////////////////////////////////////////////////
3931 //// PREP SYSTEM USER
3932 if(empty($current_user)) {
3933 // I-E runs as admin, get admin prefs
3935 $current_user = new User();
3936 $current_user->getSystemUser();
3938 $tPref = $current_user->getUserDateTimePreferences();
3940 ///////////////////////////////////////////////////////////////////
3941 if(!empty($header->date)) {
3942 $unixHeaderDate = $timedate->fromString($header->date);
3944 ///////////////////////////////////////////////////////////////////
3945 //// HANDLE EMAIL ATTACHEMENTS OR HTML TEXT
3946 //// Inline images require that I-E handle attachments before body text
3947 // parts defines attachments - be mindful of .html being interpreted as an attachment
3948 if($structure->type == 1 && !empty($structure->parts)) {
3949 $GLOBALS['log']->debug('InboundEmail found multipart email - saving attachments if found.');
3950 $this->saveAttachments($msgNo, $structure->parts, $email->id, 0, $forDisplay);
3951 } elseif($structure->type == 0) {
3952 $uuemail = ($this->isUuencode($email->description)) ? true : false;
3954 * UUEncoded attachments - legacy, but still have to deal with it
3956 * begin 777 filename.txt
3961 // set body to the filtered one
3963 $email->description = $this->handleUUEncodedEmailBody($email->description, $email->id);
3964 $email->retrieve($email->id);
3968 if($this->port != 110) {
3969 $GLOBALS['log']->debug('InboundEmail found a multi-part email (id:'.$msgNo.') with no child parts to parse.');
3972 //// END HANDLE EMAIL ATTACHEMENTS OR HTML TEXT
3973 ///////////////////////////////////////////////////////////////////
3975 ///////////////////////////////////////////////////////////////////
3976 //// ASSIGN APPROPRIATE ATTRIBUTES TO NEW EMAIL OBJECT
3977 // handle UTF-8/charset encoding in the ***headers***
3979 $email->name = $this->handleMimeHeaderDecode($header->subject);
3980 $email->date_start = (!empty($unixHeaderDate)) ? $timedate->asUserDate($unixHeaderDate) : "";
3981 $email->time_start = (!empty($unixHeaderDate)) ? $timedate->asUserTime($unixHeaderDate) : "";
3982 $email->type = 'inbound';
3983 $email->date_created = (!empty($unixHeaderDate)) ? $timedate->asUser($unixHeaderDate) : "";
3984 $email->status = 'unread'; // this is used in Contacts' Emails SubPanel
3985 if(!empty($header->toaddress)) {
3986 $email->to_name = $this->handleMimeHeaderDecode($header->toaddress);
3987 $email->to_addrs_names = $email->to_name;
3989 if(!empty($header->to)) {
3990 $email->to_addrs = $this->convertImapToSugarEmailAddress($header->to);
3992 $email->from_name = $this->handleMimeHeaderDecode($header->fromaddress);
3993 $email->from_addr_name = $email->from_name;
3994 $email->from_addr = $this->convertImapToSugarEmailAddress($header->from);
3995 if(!empty($header->cc)) {
3996 $email->cc_addrs = $this->convertImapToSugarEmailAddress($header->cc);
3998 if(!empty($header->ccaddress)) {
3999 $email->cc_addrs_names = $this->handleMimeHeaderDecode($header->ccaddress);
4001 $email->reply_to_name = $this->handleMimeHeaderDecode($header->reply_toaddress);
4002 $email->reply_to_email = $this->convertImapToSugarEmailAddress($header->reply_to);
4003 if (!empty($email->reply_to_email)) {
4004 $email->reply_to_addr = $email->reply_to_name;
4006 $email->intent = $this->mailbox_type;
4008 $email->message_id = $this->compoundMessageId; // filled by importDupeCheck();
4010 $oldPrefix = $this->imagePrefix;
4012 // Store CIDs in imported messages, convert on display
4013 $this->imagePrefix = "cid:";
4015 // handle multi-part email bodies
4016 $email->description_html= $this->getMessageText($msgNo, 'HTML', $structure, $fullHeader,$clean_email); // runs through handleTranserEncoding() already
4017 $email->description = $this->getMessageText($msgNo, 'PLAIN', $structure, $fullHeader,$clean_email); // runs through handleTranserEncoding() already
4018 $this->imagePrefix = $oldPrefix;
4020 // empty() check for body content
4021 if(empty($email->description)) {
4022 $GLOBALS['log']->debug('InboundEmail Message (id:'.$email->message_id.') has no body');
4026 if (!empty($_REQUEST['user_id'])) {
4027 $email->assigned_user_id = $_REQUEST['user_id'];
4029 // Samir Gandhi : Commented out this code as its not needed
4030 //$email->assigned_user_id = $this->group_id;
4033 //Assign Parent Values if set
4034 if (!empty($_REQUEST['parent_id']) && !empty($_REQUEST['parent_type'])) {
4035 $email->parent_id = $_REQUEST['parent_id'];
4036 $email->parent_type = $_REQUEST['parent_type'];
4038 $mod = strtolower($email->parent_type);
4039 $rel = array_key_exists($mod, $email->field_defs) ? $mod : $mod . "_activities_emails"; //Custom modules rel name
4041 if(! $email->load_relationship($rel) )
4043 $email->$rel->add($email->parent_id);
4046 // override $forDisplay w/user pref
4048 if($this->isAutoImport()) {
4049 $forDisplay = false; // triggers save of imported email
4056 $email->new_with_id = false; // to allow future saves by UPDATE, instead of INSERT
4057 //// ASSIGN APPROPRIATE ATTRIBUTES TO NEW EMAIL OBJECT
4058 ///////////////////////////////////////////////////////////////////
4060 ///////////////////////////////////////////////////////////////////
4061 //// LINK APPROPRIATE BEANS TO NEWLY SAVED EMAIL
4062 //$contactAddr = $this->handleLinking($email);
4063 //// END LINK APPROPRIATE BEANS TO NEWLY SAVED EMAIL
4064 ///////////////////////////////////////////////////////////////////
4066 ///////////////////////////////////////////////////////////////////
4067 //// MAILBOX TYPE HANDLING
4068 $this->handleMailboxType($email, $header);
4069 //// END MAILBOX TYPE HANDLING
4070 ///////////////////////////////////////////////////////////////////
4072 ///////////////////////////////////////////////////////////////////
4073 //// SEND AUTORESPONSE
4074 if(!empty($email->reply_to_email)) {
4075 $contactAddr = $email->reply_to_email;
4077 $contactAddr = $email->from_addr;
4079 if (!$this->isMailBoxTypeCreateCase()) {
4080 $this->handleAutoresponse($email, $contactAddr);
4082 //// END SEND AUTORESPONSE
4083 ///////////////////////////////////////////////////////////////////
4084 //// END IMPORT ONE EMAIL
4085 ///////////////////////////////////////////////////////////////////
4088 // only log if not POP3; pop3 iterates through ALL mail
4089 if($this->protocol != 'pop3') {
4090 $GLOBALS['log']->info("InboundEmail found a duplicate email: ".$header->message_id);
4091 //echo "This email has already been imported";
4095 //// END DUPLICATE CHECK
4096 ///////////////////////////////////////////////////////////////////////
4098 ///////////////////////////////////////////////////////////////////////
4099 //// DEAL WITH THE MAILBOX
4101 $r = imap_setflag_full($this->conn, $msgNo, '\\SEEN');
4103 // if delete_seen, mark msg as deleted
4104 if($this->delete_seen == 1 && !$forDisplay) {
4105 $GLOBALS['log']->info("INBOUNDEMAIL: delete_seen == 1 - deleting email");
4106 imap_setflag_full($this->conn, $msgNo, '\\DELETED');
4109 // for display - don't touch server files?
4110 //imap_setflag_full($this->conn, $msgNo, '\\UNSEEN');
4113 $GLOBALS['log']->debug('********************************* InboundEmail finished import of 1 email: '.$email->name);
4114 //// END DEAL WITH THE MAILBOX
4115 ///////////////////////////////////////////////////////////////////////
4117 ///////////////////////////////////////////////////////////////////////
4118 //// TO SUPPORT EMAIL 2.0
4119 $this->email = $email;
4121 if(empty($this->email->et)) {
4122 $this->email->email2init();
4129 * figures out if a plain text email body has UUEncoded attachments
4130 * @param string string The email body
4131 * @return bool True if UUEncode is detected.
4133 function isUuencode($string) {
4134 $rx = "begin [0-9]{3} .*";
4136 $exBody = explode("\r", $string);
4137 foreach($exBody as $line) {
4138 if(preg_match("/begin [0-9]{3} .*/i", $line)) {
4147 * handles UU Encoded emails - a legacy from pre-RFC 822 which must still be supported (?)
4148 * @param string raw The raw email body
4149 * @param string id Parent email ID
4150 * @return string The filtered email body, stripped of attachments
4152 function handleUUEncodedEmailBody($raw, $id) {
4156 $attachmentBody = '';
4157 $inAttachment = false;
4159 $exRaw = explode("\n", $raw);
4161 foreach($exRaw as $k => $line) {
4162 $line = trim($line);
4164 if(preg_match("/begin [0-9]{3} .*/i", $line, $m)) {
4165 $inAttachment = true;
4166 $fileName = $this->handleEncodedFilename(substr($m[0], 10, strlen($m[0])));
4168 $attachmentBody = ''; // reset for next part of loop;
4173 if(strpos($line, "end") === 0) {
4174 if(!empty($fileName) && !empty($attachmentBody)) {
4175 $this->handleUUDecode($id, $fileName, trim($attachmentBody));
4176 $attachmentBody = ''; // reset for next part of loop;
4180 if($inAttachment === false) {
4181 $emailBody .= "\n".$line;
4183 $attachmentBody .= "\n".$line;
4187 /* 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 */
4188 $emailBody = $locale->translateCharset($emailBody, $locale->getExportCharset(), 'UTF-8');
4193 * wrapper for UUDecode
4194 * @param string id Id of the email
4195 * @param string UUEncode Encode US-ASCII
4197 function handleUUDecode($id, $fileName, $UUEncode) {
4198 global $sugar_config;
4199 /* include PHP_Compat library; it auto-feels for PHP5's compiled convert_uuencode() function */
4200 require_once('include/PHP_Compat/convert_uudecode.php');
4202 $attach = new Note();
4203 $attach->parent_id = $id;
4204 $attach->parent_type = 'Emails';
4206 $fname = $this->handleEncodedFilename($fileName);
4208 if(!empty($fname)) {//assign name to attachment
4209 $attach->name = $fname;
4210 } else {//if name is empty, default to filename
4211 $attach->name = urlencode($fileName);
4214 $attach->filename = urlencode($attach->name);
4216 //get position of last "." in file name
4217 $file_ext_beg = strrpos($attach->filename,".");
4219 //get file extension
4220 if($file_ext_beg >0) {
4221 $file_ext = substr($attach->filename, $file_ext_beg+1);
4223 //check to see if this is a file with extension located in "badext"
4224 foreach($sugar_config['upload_badext'] as $badExt) {
4225 if(strtolower($file_ext) == strtolower($badExt)) {
4226 //if found, then append with .txt and break out of lookup
4227 $attach->name = $attach->name . ".txt";
4228 $attach->file_mime_type = 'text/';
4229 $attach->filename = $attach->filename . ".txt";
4230 break; // no need to look for more
4235 $bin = convert_uudecode($UUEncode);
4236 $filename = "upload://{$attach->id}";
4237 if(file_put_contents($filename, $bin)) {
4238 $GLOBALS['log']->debug('InboundEmail saved attachment file: '.$filename);
4240 $GLOBALS['log']->debug('InboundEmail could not create attachment file: '.$filename);
4245 * returns true if the email's domain is NOT in the filter domain string
4247 * @param object email Email object in question
4248 * @return bool true if not filtered, false if filtered
4250 function checkFilterDomain($email) {
4251 $filterDomain = $this->get_stored_options('filter_domain');
4252 if(!isset($filterDomain) || empty($filterDomain)) {
4253 return true; // nothing set for this
4255 $replyTo = strtolower($email->reply_to_email);
4256 $from = strtolower($email->from_addr);
4257 $filterDomain = '@'.strtolower($filterDomain);
4258 if(strpos($replyTo, $filterDomain) !== false) {
4259 $GLOBALS['log']->debug('Autoreply cancelled - [reply to] address domain matches filter domain.');
4261 } elseif(strpos($from, $filterDomain) !== false) {
4262 $GLOBALS['log']->debug('Autoreply cancelled - [from] address domain matches filter domain.');
4265 return true; // no match
4271 * returns true if subject is NOT "out of the office" type
4273 * @param string subject Subject line of email in question
4274 * @return bool returns false if OOTO found
4276 function checkOutOfOffice($subject) {
4277 $ooto = array("Out of the Office", "Out of Office");
4279 foreach($ooto as $str) {
4280 if(preg_match('/'.$str.'/i', $subject)) {
4281 $GLOBALS['log']->debug('Autoreply cancelled - found "Out of Office" type of subject.');
4285 return true; // no matches to ooto strings
4290 * sets a timestamp for an autoreply to a single email addy
4292 * @param string addr Address of auto-replied target
4294 function setAutoreplyStatus($addr) {
4295 $timedate = TimeDate::getInstance();
4296 $this->db->query( 'INSERT INTO inbound_email_autoreply (id, deleted, date_entered, date_modified, autoreplied_to, ie_id) VALUES (
4297 \''.create_guid().'\',
4299 \''.$timedate->nowDb().'\',
4300 \''.$timedate->nowDb().'\',
4302 \''.$this->id.'\') ', true);
4307 * returns true if recipient has NOT received 10 auto-replies in 24 hours
4309 * @param string from target address for auto-reply
4310 * @return bool true if target is valid/under limit
4312 function getAutoreplyStatus($from) {
4313 global $sugar_config;
4314 $timedate = TimeDate::getInstance();
4316 $q_clean = 'UPDATE inbound_email_autoreply SET deleted = 1 WHERE date_entered < \''.$timedate->getNow()->modify("-24 hours")->asDb().'\'';
4317 $r_clean = $this->db->query($q_clean, true);
4319 $q = 'SELECT count(*) AS c FROM inbound_email_autoreply WHERE deleted = 0 AND autoreplied_to = \''.$from.'\' AND ie_id = \''.$this->id.'\'';
4320 $r = $this->db->query($q, true);
4321 $a = $this->db->fetchByAssoc($r);
4323 $email_num_autoreplies_24_hours = $this->get_stored_options('email_num_autoreplies_24_hours');
4324 $maxReplies = (isset($email_num_autoreplies_24_hours)) ? $email_num_autoreplies_24_hours : $this->maxEmailNumAutoreplies24Hours;
4326 if($a['c'] >= $maxReplies) {
4327 $GLOBALS['log']->debug('Autoreply cancelled - more than ' . $maxReplies . ' replies sent in 24 hours.');
4335 * returns exactly 1 id match. if more than one, than returns false
4336 * @param $emailName the subject of the email to match
4337 * @param $tableName the table of the matching bean type
4339 function getSingularRelatedId($emailName, $tableName) {
4340 $repStrings = array('RE:','Re:','re:');
4341 $preppedName = str_replace($repStrings,'',trim($emailName));
4343 //TODO add team security to this query
4344 $q = 'SELECT count(id) AS c FROM '.$tableName.' WHERE deleted = 0 AND name LIKE \'%'.$preppedName.'%\'';
4345 $r = $this->db->query($q, true);
4346 $a = $this->db->fetchByAssoc($r);
4349 $q = 'SELECT id FROM '.$tableName.' WHERE deleted = 0 AND name LIKE \'%'.$preppedName.'%\'';
4350 $r = $this->db->query($q, true);
4351 $a = $this->db->fetchByAssoc($r);
4359 * saves InboundEmail parse macros to config.php
4360 * @param string type Bean to link
4361 * @param string macro The new macro
4363 function saveInboundEmailSystemSettings($type, $macro) {
4364 global $sugar_config;
4366 // inbound_email_case_subject_macro
4367 $var = "inbound_email_".strtolower($type)."_subject_macro";
4368 $sugar_config[$var] = $macro;
4370 ksort($sugar_config);
4372 $sugar_config_string = "<?php\n" .
4373 '// created: ' . date('Y-m-d H:i:s') . "\n" .
4374 '$sugar_config = ' .
4375 var_export($sugar_config, true) .
4378 write_array_to_file("sugar_config", $sugar_config, "config.php");
4382 * returns the HTML for InboundEmail system settings
4383 * @return string HTML
4385 function getSystemSettingsForm() {
4386 global $sugar_config;
4387 global $mod_strings;
4388 global $app_strings;
4389 global $app_list_strings;
4394 $macro = $c->getEmailSubjectMacro();
4397 <form action="index.php" method="post" name="Macro" id="form">
4398 <input type="hidden" name="module" value="InboundEmail">
4399 <input type="hidden" name="action" value="ListView">
4400 <input type="hidden" name="save" value="true">
4402 <table width="100%" cellpadding="0" cellspacing="0" border="0">
4405 <input title="{$app_strings['LBL_SAVE_BUTTON_TITLE']}"
4406 accessKey="{$app_strings['LBL_SAVE_BUTTON_KEY']}"
4408 onclick="this.form.return_module.value='InboundEmail'; this.form.return_action.value='ListView';"
4409 type="submit" name="Edit" value=" {$app_strings['LBL_SAVE_BUTTON_LABEL']} ">
4414 <table width="100%" border="0" cellspacing="0" cellpadding="0" class="detail view">
4416 <td valign="top" width='10%' NOWRAP scope="row">
4418 <b>{$mod_strings['LBL_CASE_MACRO']}:</b>
4421 <td valign="top" width='20%'>
4423 <input name="inbound_email_case_macro" type="text" value="{$macro}">
4426 <td valign="top" width='70%'>
4428 {$mod_strings['LBL_CASE_MACRO_DESC']}
4430 <i>{$mod_strings['LBL_CASE_MACRO_DESC2']}</i>
4441 * for mailboxes of type "Support" parse for '[CASE:%1]'
4442 * @param $emailName the subject line of the email
4443 * @param $aCase a Case object
4445 function getCaseIdFromCaseNumber($emailName, $aCase) {
4446 //$emailSubjectMacro
4447 $exMacro = explode('%1', $aCase->getEmailSubjectMacro());
4448 $open = $exMacro[0];
4449 $close = $exMacro[1];
4451 if($sub = stristr($emailName, $open)) { // eliminate everything up to the beginning of the macro and return the rest
4452 // $sub is [CASE:XX] xxxxxxxxxxxxxxxxxxxxxx
4453 $sub2 = str_replace($open, '', $sub);
4454 // $sub2 is XX] xxxxxxxxxxxxxx
4455 $sub3 = substr($sub2, 0, strpos($sub2, $close));
4457 // filter out deleted records in order to create a new case
4458 // if email is related to deleted one (bug #49840)
4459 $r = $this->db->query("SELECT id FROM cases WHERE case_number = '{$sub3}' and deleted = 0", true);
4460 $a = $this->db->fetchByAssoc($r);
4461 if(!empty($a['id'])) {
4471 function get_stored_options($option_name,$default_value=null,$stored_options=null) {
4472 if (empty($stored_options)) {
4473 $stored_options=$this->stored_options;
4475 if(!empty($stored_options)) {
4476 $storedOptions = unserialize(base64_decode($stored_options));
4477 if (isset($storedOptions[$option_name])) {
4478 $default_value=$storedOptions[$option_name];
4481 return $default_value;
4486 * This function returns a contact or user ID if a matching email is found
4487 * @param $email the email address to match
4488 * @param $table which table to query
4490 function getRelatedId($email, $module) {
4491 $email = trim(strtoupper($email));
4492 if(strpos($email, ',') !== false) {
4493 $emailsArray = explode(',', $email);
4494 $emailAddressString = "";
4495 foreach($emailsArray as $emailAddress) {
4496 if (!empty($emailAddressString)) {
4497 $emailAddressString .= ",";
4499 $emailAddressString .= "'" . $emailAddress. "'";
4501 $email = $emailAddressString;
4503 $email = "'" . $email . "'";
4505 $module = ucfirst($module);
4507 $q = "SELECT bean_id FROM email_addr_bean_rel eabr
4508 JOIN email_addresses ea ON (eabr.email_address_id = ea.id)
4509 WHERE bean_module = '{$module}' AND ea.email_address_caps in ( {$email} ) AND eabr.deleted=0";
4511 $r = $this->db->query($q, true);
4514 while($a = $this->db->fetchByAssoc($r)) {
4515 $retArr[] = $a['bean_id'];
4517 if(count($retArr) > 0) {
4525 * finds emails tagged "//UNSEEN" on mailserver and "SINCE: [date]" if that
4528 * @return array Array of messageNumbers (mail server's internal keys)
4530 function getNewMessageIds() {
4531 $storedOptions = unserialize(base64_decode($this->stored_options));
4533 //TODO figure out if the since date is UDT
4534 if($storedOptions['only_since']) {// POP3 does not support Unseen flags
4535 if(!isset($storedOptions['only_since_last']) && !empty($storedOptions['only_since_last'])) {
4536 $q = 'SELECT last_run FROM schedulers WHERE job = \'function::pollMonitoredInboxes\'';
4537 $r = $this->db->query($q, true);
4538 $a = $this->db->fetchByAssoc($r);
4540 $date = date('r', strtotime($a['last_run']));
4542 $date = $storedOptions['only_since_last'];
4544 $ret = imap_search($this->conn, 'SINCE "'.$date.'" UNDELETED UNSEEN');
4545 $check = imap_check($this->conn);
4546 $storedOptions['only_since_last'] = $check->Date;
4547 $this->stored_options = base64_encode(serialize($storedOptions));
4550 $ret = imap_search($this->conn, 'UNDELETED UNSEEN');
4553 $GLOBALS['log']->debug('-----> getNewMessageIds() got '.count($ret).' new Messages');
4558 * Constructs the resource connection string that IMAP needs
4559 * @param string $service Service string, will generate if not passed
4562 function getConnectString($service='', $mbox='', $includeMbox=true) {
4563 $service = empty($service) ? $this->getServiceString() : $service;
4564 $mbox = empty($mbox) ? $this->mailbox : $mbox;
4566 $connectString = '{'.$this->server_url.':'.$this->port.'/service='.$this->protocol.$service.'}';
4567 $connectString .= ($includeMbox) ? $mbox : "";
4569 return $connectString;
4572 function disconnectMailserver() {
4573 if(is_resource($this->conn)) {
4574 imap_close($this->conn);
4579 * Connects to mailserver. If an existing IMAP resource is available, it
4580 * will attempt to reuse the connection, updating the mailbox path.
4582 * @param bool test Flag to test connection
4583 * @param bool force Force reconnect
4584 * @return string "true" on success, "false" or $errorMessage on failure
4586 function connectMailserver($test=false, $force=false) {
4587 global $mod_strings;
4588 if(!function_exists("imap_open")) {
4589 $GLOBALS['log']->debug('------------------------- IMAP libraries NOT available!!!! die()ing thread.----');
4590 return $mod_strings['LBL_WARN_NO_IMAP'];
4593 imap_errors(); // clearing error stack
4594 error_reporting(0); // turn off notices from IMAP
4596 // tls::ca::ssl::protocol::novalidate-cert::notls
4597 $useSsl = ($_REQUEST['ssl'] == 'true') ? true : false;
4599 imap_timeout(1, 15); // 60 secs is the default
4600 imap_timeout(2, 15);
4601 imap_timeout(3, 15);
4603 $opts = $this->findOptimumSettings($useSsl);
4604 if(isset($opts['good']) && empty($opts['good'])) {
4605 return array_pop($opts['err']);
4607 $service = $opts['service'];
4608 $service = str_replace('foo','', $service); // foo there to support no-item explodes
4611 $service = $this->getServiceString();
4614 $connectString = $this->getConnectString($service, $this->mailbox);
4617 * Try to recycle the current connection to reduce response times
4619 if(is_resource($this->conn)) {
4622 imap_close($this->conn);
4625 if(imap_ping($this->conn)) {
4626 // we have a live connection
4627 imap_reopen($this->conn, $connectString, CL_EXPUNGE);
4632 if(!is_resource($this->conn) && !$test) {
4633 $this->conn = imap_open($connectString, $this->email_user, $this->email_password, CL_EXPUNGE);
4637 if ($opts == false && !is_resource($this->conn)) {
4638 $this->conn = imap_open($connectString, $this->email_user, $this->email_password, CL_EXPUNGE);
4642 $successful = false;
4643 if(($errors = imap_last_error()) || ($alerts = imap_alerts())) {
4644 if($errors == 'Mailbox is empty') { // false positive
4648 $msg .= '<p>'.$alerts.'<p>';
4649 $msg .= '<p>'.$mod_strings['ERR_TEST_MAILBOX'];
4656 if($this->protocol == 'imap') {
4657 $msg .= $mod_strings['LBL_TEST_SUCCESSFUL'];
4659 $testConnectString = '{'.$this->server_url.':'.$this->port.'/service='.$this->protocol.$service.'}';
4660 if (!is_resource($this->conn)) {
4661 $this->conn = imap_open($connectString, $this->email_user, $this->email_password, CL_EXPUNGE);
4663 $list = imap_getmailboxes($this->conn, $testConnectString, "*");
4664 if(isset($_REQUEST['personal']) && $_REQUEST['personal'] == 'true') {
4665 $msg .= $mod_strings['LBL_TEST_SUCCESSFUL'];
4666 } elseif (is_array($list)) {
4670 $msg .= '<b>'.$mod_strings['LBL_FOUND_MAILBOXES'].'</b><p>';
4671 foreach ($list as $key => $val) {
4672 $mb = imap_utf7_decode(str_replace($testConnectString,'',$val->name));
4673 $msg .= '<a onClick=\'setMailbox(\"'.$mb.'\"); window.close();\'>';
4679 $msg .= '<p>'.$mod_strings['ERR_MAILBOX_FAIL'].imap_last_error().'</p>';
4680 $msg .= '<p>'.$mod_strings['ERR_TEST_MAILBOX'].'</p>';
4684 $msg .= $mod_strings['LBL_POP3_SUCCESS'];
4688 imap_errors(); // collapse error stack
4689 imap_close($this->conn);
4691 } elseif(!is_resource($this->conn)) {
4700 function checkImap() {
4701 global $mod_strings;
4703 if(!function_exists('imap_open')) {
4705 <table cellpadding="0" cellspacing="0" width="100%" border="0" class="list view">
4707 <td scope="col" width="25%" colspan="2"><slot>
4708 '.$mod_strings['LBL_WARN_IMAP_TITLE'].'
4712 <td scope="row" valign=TOP bgcolor="#fdfdfd" width="20%"><slot>
4713 '.$mod_strings['LBL_WARN_IMAP'].'
4714 <td scope="row" valign=TOP class="oddListRowS1" bgcolor="#fdfdfd" width="80%"><slot>
4715 <span class=error>'.$mod_strings['LBL_WARN_NO_IMAP'].'</span>
4724 * retrieves an array of I-E beans based on the group_id
4725 * @param string $groupId GUID of the group user or Individual
4726 * @return array $beans array of beans
4727 * @return boolean false if none returned
4729 function retrieveByGroupId($groupId) {
4730 $q = 'SELECT id FROM inbound_email WHERE group_id = \''.$groupId.'\' AND deleted = 0 AND status = \'Active\'';
4731 $r = $this->db->query($q, true);
4734 while($a = $this->db->fetchByAssoc($r)) {
4735 $ie = new InboundEmail();
4736 $ie->retrieve($a['id']);
4737 $beans[$a['id']] = $ie;
4743 * Retrieves the current count of personal accounts for the user specified.
4745 * @param unknown_type $user
4747 function getUserPersonalAccountCount($user = null)
4750 $user = $GLOBALS['current_user'];
4752 $query = "SELECT count(*) as c FROM inbound_email WHERE deleted=0 AND is_personal='1' AND group_id='{$user->id}' AND status='Active'";
4754 $rs = $this->db->query($query);
4755 $row = $this->db->fetchByAssoc($rs);
4760 * retrieves an array of I-E beans based on the group folder id
4761 * @param string $groupFolderId GUID of the group folder
4762 * @return array $beans array of beans
4763 * @return boolean false if none returned
4765 function retrieveByGroupFolderId($groupFolderId) {
4766 $q = 'SELECT id FROM inbound_email WHERE groupfolder_id = \''.$groupFolderId.'\' AND deleted = 0 ';
4767 $r = $this->db->query($q, true);
4770 while($a = $this->db->fetchByAssoc($r)) {
4771 $ie = new InboundEmail();
4772 $ie->retrieve($a['id']);
4779 * Retrieves an array of I-E beans that the user has team access to
4781 function retrieveAllByGroupId($id, $includePersonal=true) {
4782 global $current_user;
4784 $beans = ($includePersonal) ? $this->retrieveByGroupId($id) : array();
4790 // bug 50536: groupfolder_id cannot be updated to NULL from sugarbean's nullable check ('type' set to ID in the vardef)
4791 // hence the awkward or check -- rbacon
4792 $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' ";
4796 $r = $this->db->query($q, true);
4798 while($a = $this->db->fetchByAssoc($r)) {
4800 foreach($beans as $bean) {
4801 if($bean->id == $a['id']) {
4807 $ie = new InboundEmail();
4808 $ie->retrieve($a['id']);
4809 $beans[$a['id']] = $ie;
4817 * Retrieves an array of I-E beans that the user has team access to including group
4819 function retrieveAllByGroupIdWithGroupAccounts($id, $includePersonal=true) {
4820 global $current_user;
4822 $beans = ($includePersonal) ? $this->retrieveByGroupId($id) : array();
4831 $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 ";
4833 $r = $this->db->query($q, true);
4835 while($a = $this->db->fetchByAssoc($r)) {
4837 foreach($beans as $bean) {
4838 if($bean->id == $a['id']) {
4844 $ie = new InboundEmail();
4845 $ie->retrieve($a['id']);
4846 $beans[$a['id']] = $ie;
4855 * returns the bean name - overrides SugarBean's
4857 function get_summary_text() {
4862 * Override's SugarBean's
4864 function create_export_query($order_by, $where, $show_deleted = 0) {
4865 return $this->create_new_list_query($order_by, $where, $show_deleted = 0);
4869 * Override's SugarBean's
4873 * Override's SugarBean's
4875 function get_list_view_data(){
4876 global $mod_strings;
4877 global $app_list_strings;
4878 $temp_array = $this->get_list_view_array();
4879 $temp_array['MAILBOX_TYPE_NAME']= $app_list_strings['dom_mailbox_type'][$this->mailbox_type];
4880 //cma, fix bug 21670.
4881 $temp_array['GLOBAL_PERSONAL_STRING']= ($this->is_personal ? $mod_strings['LBL_IS_PERSONAL'] : $mod_strings['LBL_IS_GROUP']);
4882 $temp_array['STATUS'] = ($this->status == 'Active') ? $mod_strings['LBL_STATUS_ACTIVE'] : $mod_strings['LBL_STATUS_INACTIVE'];
4887 * Override's SugarBean's
4889 function fill_in_additional_list_fields() {
4890 $this->fill_in_additional_detail_fields();
4894 * Override's SugarBean's
4896 function fill_in_additional_detail_fields() {
4897 if(!empty($this->service)) {
4898 $exServ = explode('::', $this->service);
4899 $this->tls = $exServ[0];
4900 if ( isset($exServ[1]) )
4901 $this->ca = $exServ[1];
4902 if ( isset($exServ[2]) )
4903 $this->ssl = $exServ[2];
4904 if ( isset($exServ[3]) )
4905 $this->protocol = $exServ[3];
4922 ///////////////////////////////////////////////////////////////////////////
4923 //// IN SUPPORT OF EMAIL 2.0
4925 * Checks for $user's autoImport setting and returns the current value
4926 * @param object $user User in focus, defaults to $current_user
4929 function isAutoImport($user=null) {
4930 if(!empty($this->autoImport)) {
4931 return $this->autoImport;
4934 global $current_user;
4935 if(empty($user)) $user = $current_user;
4937 $emailSettings = $current_user->getPreference('emailSettings', 'Emails');
4938 $emailSettings = is_string($emailSettings) ? unserialize($emailSettings) : $emailSettings;
4940 $this->autoImport = (isset($emailSettings['autoImport']) && !empty($emailSettings['autoImport'])) ? true : false;
4941 return $this->autoImport;
4945 * Clears out cache files for a user
4947 function cleanOutCache() {
4948 $GLOBALS['log']->debug("INBOUNDEMAIL: at cleanOutCache()");
4949 $this->deleteCache();
4953 * moves emails from folder to folder
4954 * @param string $fromIe I-E id
4955 * @param string $fromFolder IMAP path to folder in which the email lives
4956 * @param string $toIe I-E id
4957 * @param string $toFolder
4958 * @param string $uids UIDs of emails to move, either Sugar GUIDS or IMAP
4961 function copyEmails($fromIe, $fromFolder, $toIe, $toFolder, $uids) {
4962 $this->moveEmails($fromIe, $fromFolder, $toIe, $toFolder, $uids, true);
4966 * moves emails from folder to folder
4967 * @param string $fromIe I-E id
4968 * @param string $fromFolder IMAP path to folder in which the email lives
4969 * @param string $toIe I-E id
4970 * @param string $toFolder
4971 * @param string $uids UIDs of emails to move, either Sugar GUIDS or IMAP
4973 * @param bool $copy Default false
4974 * @return bool True on successful execution
4976 function moveEmails($fromIe, $fromFolder, $toIe, $toFolder, $uids, $copy=false) {
4977 global $app_strings;
4978 global $current_user;
4982 if($fromIe == $toIe) {
4983 $GLOBALS['log']->debug("********* SUGARFOLDER - moveEmails() moving email from I-E to I-E");
4984 //$exDestFolder = explode("::", $toFolder);
4985 //preserve $this->mailbox
4986 if (isset($this->mailbox)) {
4987 $oldMailbox = $this->mailbox;
4991 $this->retrieve($fromIe);
4992 $this->mailbox = $fromFolder;
4993 $this->connectMailserver();
4994 $exUids = explode('::;::', $uids);
4995 $uids = implode(",", $exUids);
4996 // imap_mail_move accepts comma-delimited lists of UIDs
4998 if(imap_mail_copy($this->conn, $uids, $toFolder, CP_UID)) {
4999 $this->mailbox = $toFolder;
5000 $this->connectMailserver();
5001 $newOverviews = imap_fetch_overview($this->conn, $uids, FT_UID);
5002 $this->updateOverviewCacheFile($newOverviews, 'append');
5003 if (isset($oldMailbox)) {
5004 $this->mailbox = $oldMailbox;
5008 $GLOBALS['log']->debug("INBOUNDEMAIL: could not imap_mail_copy() [ {$uids} ] to folder [ {$toFolder} ] from folder [ {$fromFolder} ]");
5011 if(imap_mail_move($this->conn, $uids, $toFolder, CP_UID)) {
5012 $GLOBALS['log']->info("INBOUNDEMAIL: imap_mail_move() [ {$uids} ] to folder [ {$toFolder} ] from folder [ {$fromFolder} ]");
5013 imap_expunge($this->conn); // hard deletes moved messages
5015 // update cache on fromFolder
5016 $newOverviews = $this->getOverviewsFromCacheFile($uids, $fromFolder, true);
5017 $this->deleteCachedMessages($uids, $fromFolder);
5019 // update cache on toFolder
5020 $this->checkEmailOneMailbox($toFolder, true, true);
5021 if (isset($oldMailbox)) {
5022 $this->mailbox = $oldMailbox;
5027 $GLOBALS['log']->debug("INBOUNDEMAIL: could not imap_mail_move() [ {$uids} ] to folder [ {$toFolder} ] from folder [ {$fromFolder} ]");
5030 } elseif($toIe == 'folder' && $fromFolder == 'sugar::Emails') {
5031 $GLOBALS['log']->debug("********* SUGARFOLDER - moveEmails() moving email from SugarFolder to SugarFolder");
5032 // move from sugar folder to sugar folder
5033 require_once("include/SugarFolders/SugarFolders.php");
5034 $sugarFolder = new SugarFolder();
5035 $exUids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
5036 foreach($exUids as $id) {
5038 $sugarFolder->copyBean($fromIe, $toFolder, $id, "Emails");
5040 $fromSugarFolder = new SugarFolder();
5041 $fromSugarFolder->retrieve($fromIe);
5042 $toSugarFolder = new SugarFolder();
5043 $toSugarFolder->retrieve($toFolder);
5045 $email = new Email();
5046 $email->retrieve($id);
5047 $email->status = 'unread';
5049 // when you move from My Emails to Group Folder, Assign To field for the Email should become null
5050 if ($fromSugarFolder->is_dynamic && $toSugarFolder->is_group) {
5051 $email->assigned_user_id = "";
5053 if (!$toSugarFolder->checkEmailExistForFolder($id)) {
5054 $fromSugarFolder->deleteEmailFromAllFolder($id);
5055 $toSugarFolder->addBean($email);
5057 } elseif ($fromSugarFolder->is_group && $toSugarFolder->is_dynamic) {
5058 $fromSugarFolder->deleteEmailFromAllFolder($id);
5059 $email->assigned_user_id = $current_user->id;
5062 // If you are moving something from personal folder then delete an entry from all folder
5063 if (!$fromSugarFolder->is_dynamic && !$fromSugarFolder->is_group) {
5064 $fromSugarFolder->deleteEmailFromAllFolder($id);
5067 if ($fromSugarFolder->is_dynamic && !$toSugarFolder->is_dynamic && !$toSugarFolder->is_group) {
5068 $email->assigned_user_id = "";
5069 $toSugarFolder->addBean($email);
5071 if (!$toSugarFolder->checkEmailExistForFolder($id)) {
5072 if (!$toSugarFolder->is_dynamic) {
5073 $fromSugarFolder->deleteEmailFromAllFolder($id);
5074 $toSugarFolder->addBean($email);
5076 $fromSugarFolder->deleteEmailFromAllFolder($id);
5077 $email->assigned_user_id = $current_user->id;
5080 $sugarFolder->move($fromIe, $toFolder, $id);
5088 } elseif($toIe == 'folder') {
5089 $GLOBALS['log']->debug("********* SUGARFOLDER - moveEmails() moving email from I-E to SugarFolder");
5090 // move to Sugar folder
5091 require_once("include/SugarFolders/SugarFolders.php");
5092 $sugarFolder = new SugarFolder();
5093 $sugarFolder->retrieve($toFolder);
5094 //Show the import form if we don't have the required info
5095 if (!isset($_REQUEST['delete'])) {
5096 $json = getJSONobj();
5097 if ($sugarFolder->is_group) {
5098 $_REQUEST['showTeam'] = false;
5099 $_REQUEST['showAssignTo'] = false;
5101 $ret = $this->email->et->getImportForm($_REQUEST, $this->email);
5102 $ret['move'] = true;
5103 $ret['srcFolder'] = $fromFolder;
5104 $ret['srcIeId'] = $fromIe;
5105 $ret['dstFolder'] = $toFolder;
5106 $ret['dstIeId'] = $toIe;
5107 $out = trim($json->encode($ret, false));
5114 $this->retrieve($fromIe);
5115 $this->mailbox = $fromFolder;
5116 $this->connectMailserver();
5117 // If its a group folder the team should be of the folder team
5118 if ($sugarFolder->is_group) {
5119 $_REQUEST['team_id'] = $sugarFolder->team_id;
5120 $_REQUEST['team_set_id'] = $sugarFolder->team_set_id;
5122 // TODO - set team_id, team_set for new UI
5125 $exUids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
5127 if(!empty($sugarFolder->id)) {
5130 $json = getJSONobj();
5131 foreach($exUids as $k => $uid) {
5133 if ($this->isPop3Protocol()) {
5134 $msgNo = $this->getCorrectMessageNoForPop3($uid);
5136 $msgNo = imap_msgno($this->conn, $uid);
5139 if(!empty($msgNo)) {
5140 $importStatus = $this->importOneEmail($msgNo, $uid);
5143 $sugarFolder->addBean($this->email);
5144 if(!$copy && isset($_REQUEST['delete']) && ($_REQUEST['delete'] == "true") && $importStatus) {
5145 $GLOBALS['log']->error("********* delete from mailserver [ {explode(",", $uids)} ]");
5146 // delete from mailserver
5147 $this->deleteMessageOnMailServer($uid);
5148 $this->deleteMessageFromCache($uid);
5151 $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']);
5155 echo $json->encode($return);
5158 $GLOBALS['log']->error("********* SUGARFOLDER - failed to retrieve folder ID [ {$toFolder} ]");
5161 $GLOBALS['log']->debug("********* SUGARFOLDER - moveEmails() called with no passing criteria");
5169 * Hard deletes an I-E account
5170 * @param string id GUID
5172 function hardDelete($id) {
5173 $q = "DELETE FROM inbound_email WHERE id = '{$id}'";
5174 $r = $this->db->query($q, true);
5178 * Generate a unique filename for attachments based on the message id. There are no maximum
5179 * specifications for the length of the message id, the only requirement is that it be globally unique.
5181 * @param bool $nameOnly Whether or not the attachment count should be appended to the filename.
5182 * @return string The temp file name
5184 function getTempFilename($nameOnly=false) {
5186 $str = $this->compoundMessageId;
5189 $str = $str.$this->attachmentCount;
5190 $this->attachmentCount++;
5197 * deletes and expunges emails on server
5198 * @param string $uid UID(s), comma delimited, of email(s) on server
5199 * @return bool true on success
5201 function deleteMessageOnMailServer($uid) {
5202 global $app_strings;
5203 $this->connectMailserver();
5205 if(strpos($uid, $app_strings['LBL_EMAIL_DELIMITER']) !== false) {
5206 $uids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uid);
5213 if($this->protocol == 'imap') {
5214 $trashFolder = $this->get_stored_options("trashFolder");
5215 if (empty($trashFolder)) {
5216 $trashFolder = "INBOX.Trash";
5218 foreach($uids as $uid) {
5219 if($this->moveEmails($this->id, $this->mailbox, $this->id, $trashFolder, $uid))
5220 $GLOBALS['log']->debug("INBOUNDEMAIL: MoveEmail to {$trashFolder} successful.");
5222 $GLOBALS['log']->debug("INBOUNDEMAIL: MoveEmail to {$trashFolder} FAILED - trying hard delete for message: $uid");
5223 imap_delete($this->conn, $uid, FT_UID);
5230 foreach($uids as $uid) {
5231 $msgnos[] = $this->getCorrectMessageNoForPop3($uid);
5233 $msgnos = implode(',', $msgnos);
5234 imap_delete($this->conn, $msgnos);
5238 if(!imap_expunge($this->conn)) {
5239 $GLOBALS['log']->debug("NOOP: could not expunge deleted email.");
5243 $GLOBALS['log']->info("INBOUNDEMAIL: hard-deleted mail with MSgno's' [ {$msgnos} ]");
5249 * deletes and expunges emails on server
5250 * @param string $uid UID(s), comma delimited, of email(s) on server
5252 function deleteMessageOnMailServerForPop3($uid) {
5253 if(imap_delete($this->conn, $uid)) {
5254 if(!imap_expunge($this->conn)) {
5255 $GLOBALS['log']->debug("NOOP: could not expunge deleted email.");
5258 $GLOBALS['log']->info("INBOUNDEMAIL: hard-deleted mail with MSgno's' [ {$uid} ]");
5264 * Checks if this is a pop3 type of an account or not
5267 function isPop3Protocol() {
5268 return ($this->protocol == 'pop3');
5272 * Gets the UIDL from database for the corresponding msgno
5273 * @param int messageNo of a message
5274 * @return UIDL for the message
5276 function getUIDLForMessage($msgNo) {
5277 $query = "SELECT message_id FROM email_cache WHERE ie_id = '{$this->id}' AND msgno = '{$msgNo}'";
5278 $r = $this->db->query($query);
5279 $a = $this->db->fetchByAssoc($r);
5280 return $a['message_id'];
5283 * Get the users default IE account id
5288 function getUsersDefaultOutboundServerId($user)
5290 $id = $user->getPreference($this->keyForUsersDefaultIEAccount,'Emails',$user);
5291 //If no preference has been set, grab the default system id.
5294 $oe = new OutboundEmail();
5295 $system = $oe->getSystemMailerSettings();
5296 $id=empty($system->id) ? '' : $system->id;
5303 * Get the users default IE account id
5307 function setUsersDefaultOutboundServerId($user,$oe_id)
5309 $user->setPreference($this->keyForUsersDefaultIEAccount, $oe_id, '', 'Emails');
5312 * Gets the UIDL from database for the corresponding msgno
5313 * @param int messageNo of a message
5314 * @return UIDL for the message
5316 function getMsgnoForMessageID($messageid) {
5317 $query = "SELECT msgno FROM email_cache WHERE ie_id = '{$this->id}' AND message_id = '{$messageid}'";
5318 $r = $this->db->query($query);
5319 $a = $this->db->fetchByAssoc($r);
5320 return $a['message_id'];
5324 * fills InboundEmail->email with an email's details
5325 * @param int uid Unique ID of email
5326 * @param bool isMsgNo flag that passed ID is msgNo, default false
5327 * @param bool setRead Sets the 'seen' flag in cache
5328 * @param bool forceRefresh Skips cache file
5331 function setEmailForDisplay($uid, $isMsgNo=false, $setRead=false, $forceRefresh=false) {
5334 $GLOBALS['log']->debug("*** ERROR: INBOUNDEMAIL trying to setEmailForDisplay() with no UID");
5338 global $sugar_config;
5339 global $app_strings;
5341 // if its a pop3 then get the UIDL and see if this file name exist or not
5342 if ($this->isPop3Protocol()) {
5343 // get the UIDL from database;
5344 $cachedUIDL = md5($uid);
5345 $cache = "{$this->EmailCachePath}/{$this->id}/messages/{$this->mailbox}{$cachedUIDL}.php";
5347 $cache = "{$this->EmailCachePath}/{$this->id}/messages/{$this->mailbox}{$uid}.php";
5350 if(file_exists($cache) && !$forceRefresh) {
5351 $GLOBALS['log']->info("INBOUNDEMAIL: Using cache file for setEmailForDisplay()");
5353 include($cache); // profides $cacheFile
5354 /** @var $cacheFile array */
5356 $metaOut = unserialize($cacheFile['out']);
5357 $meta = $metaOut['meta']['email'];
5358 $email = new Email();
5360 foreach($meta as $k => $v) {
5364 $email->to_addrs = $meta['toaddrs'];
5365 $email->date_sent = $meta['date_start'];
5366 //_ppf($email,true);
5368 $this->email = $email;
5369 $this->email->email2init();
5372 $GLOBALS['log']->info("INBOUNDEMAIL: opening new connection for setEmailForDisplay()");
5373 if($this->isPop3Protocol()) {
5374 $msgNo = $this->getCorrectMessageNoForPop3($uid);
5376 if(empty($this->conn)) {
5377 $this->connectMailserver();
5379 $msgNo = ($isMsgNo) ? $uid : imap_msgno($this->conn, $uid);
5381 if(empty($this->conn)) {
5382 $status = $this->connectMailserver();
5383 if($status == "false") {
5384 $this->email = new Email();
5385 $this->email->name = $app_strings['LBL_EMAIL_ERROR_MAILSERVERCONNECTION'];
5392 $this->importOneEmail($msgNo, $uid, true);
5393 $this->email->id = '';
5394 $this->email->new_with_id = false;
5399 $this->setStatuses($uid, 'seen', 1);
5407 * Sets status for a particular attribute on the mailserver and the local cache file
5409 function setStatuses($uid, $field, $value) {
5410 global $sugar_config;
5411 /** available status fields
5415 [date] => Mon, 22 Jan 2007 17:32:57 -0800
5428 $file = "{$this->mailbox}.imapFetchOverview.php";
5429 $overviews = $this->getCacheValueForUIDs($this->mailbox, array($uid));
5431 if(!empty($overviews)) {
5434 foreach($overviews['retArr'] as $k => $obj) {
5435 if($obj->imap_uid == $uid) {
5436 $obj->$field = $value;
5441 if(!empty($updates)) {
5442 $this->setCacheValue($this->mailbox, array(), $updates);
5448 * Removes an email from the cache file, deletes the message from the cache too
5449 * @param string String of uids, comma delimited
5451 function deleteMessageFromCache($uids) {
5452 global $sugar_config;
5453 global $app_strings;
5455 // delete message cache file and email_cache file
5456 $exUids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
5458 foreach($exUids as $uid) {
5460 if ($this->isPop3Protocol()) {
5461 $q = "DELETE FROM email_cache WHERE message_id = '{$uid}' AND ie_id = '{$this->id}'";
5463 $q = "DELETE FROM email_cache WHERE imap_uid = {$uid} AND ie_id = '{$this->id}'";
5465 $r = $this->db->query($q);
5466 if ($this->isPop3Protocol()) {
5469 $msgCacheFile = "{$this->EmailCachePath}/{$this->id}/messages/{$this->mailbox}{$uid}.php";
5470 if(file_exists($msgCacheFile)) {
5471 if(!unlink($msgCacheFile)) {
5472 $GLOBALS['log']->error("***ERROR: InboundEmail could not delete the cache file [ {$msgCacheFile} ]");
5481 * @param int uid UID of email to display
5482 * @param string mbox Mailbox to look in for the message
5483 * @param bool isMsgNo Flag to assume $uid is a MessageNo, not UniqueID, default false
5485 function displayOneEmail($uid, $mbox, $isMsgNo=false) {
5486 require_once("include/JSON.php");
5489 global $app_strings;
5490 global $app_list_strings;
5491 global $sugar_smarty;
5493 global $current_user;
5494 global $sugar_config;
5496 $fetchedAttributes = array(
5505 $souEmail = array();
5506 foreach($fetchedAttributes as $k) {
5507 if ($k == 'date_start') {
5508 $this->email->$k . " " . $this->email->time_start;
5509 $souEmail[$k] = $this->email->$k . " " . $this->email->time_start;
5510 } elseif ($k == 'time_start') {
5513 $souEmail[$k] = trim($this->email->$k);
5517 // if a MsgNo is passed in, convert to UID
5519 $uid = imap_uid($this->conn, $uid);
5521 // meta object to allow quick retrieval for replies
5523 $meta['type'] = $this->email->type;
5524 $meta['uid'] = $uid;
5525 $meta['ieId'] = $this->id;
5526 $meta['email'] = $souEmail;
5527 $meta['mbox'] = $this->mailbox;
5532 $exMbox = explode("::", $mbox);
5536 if(!empty($this->email->cc_addrs)) {
5537 //$ccs = $this->collapseLongMailingList($this->email->cc_addrs);
5538 $ccs = to_html($this->email->cc_addrs_names);
5541 <td NOWRAP valign="top" class="displayEmailLabel">
5542 {$app_strings['LBL_EMAIL_CC']}:
5544 <td class="displayEmailValue">
5551 $meta['email']['cc_addrs'] = $ccs;
5554 if ($mbox == "sugar::Emails") {
5556 $q = "SELECT id, filename, file_mime_type FROM notes WHERE parent_id = '{$uid}' AND deleted = 0";
5557 $r = $this->db->query($q);
5559 while($a = $this->db->fetchByAssoc($r)) {
5560 $url = "index.php?entryPoint=download&type=notes&id={$a['id']}";
5561 $lbl = ($i == 0) ? $app_strings['LBL_EMAIL_ATTACHMENTS'].":" : '';
5563 $attachments .=<<<EOQ
5565 <td NOWRAP valign="top" class="displayEmailLabel">
5568 <td NOWRAP valign="top" colspan="2" class="displayEmailValue">
5569 <a href="{$url}">{$a['filename']}</a>
5573 $this->email->cid2Link($a['id'], $a['file_mime_type']);
5579 if($this->attachmentCount > 0) {
5580 $theCount = $this->attachmentCount;
5582 for($i=0; $i<$theCount; $i++) {
5583 $lbl = ($i == 0) ? $app_strings['LBL_EMAIL_ATTACHMENTS'].":" : '';
5584 $name = $this->getTempFilename(true).$i;
5585 $tempName = urlencode($this->tempAttachment[$name]);
5587 $url = "index.php?entryPoint=download&type=temp&isTempFile=true&ieId={$this->id}&tempName={$tempName}&id={$name}";
5589 $attachments .=<<<eoq
5591 <td NOWRAP valign="top" class="displayEmailLabel">
5594 <td NOWRAP valign="top" colspan="2" class="displayEmailValue">
5595 <a href="{$url}">{$this->tempAttachment[$name]}</a>
5602 $meta['email']['attachments'] = $attachments;
5605 $meta['email']['toaddrs'] = $this->collapseLongMailingList($this->email->to_addrs);
5606 $meta['email']['cc_addrs'] = $ccs;
5609 $description = (empty($this->email->description_html)) ? nl2br($this->email->description) : $this->email->description_html;
5610 $meta['email']['description'] = $description;
5613 $meta['is_sugarEmail'] = ($exMbox[0] == 'sugar') ? true : false;
5615 if(!$meta['is_sugarEmail']) {
5616 if($this->isAutoImport) {
5617 $meta['is_sugarEmail'] = true;
5620 if( $this->email->status != 'sent' ){
5621 // mark SugarEmail read
5622 $q = "UPDATE emails SET status = 'read' WHERE id = '{$uid}'";
5623 $r = $this->db->query($q);
5628 $meta['email']['name'] = to_html($this->email->name);
5629 $meta['email']['from_addr'] = ( !empty($this->email->from_addr_name) ) ? to_html($this->email->from_addr_name) : to_html($this->email->from_addr);
5630 $meta['email']['toaddrs'] = ( !empty($this->email->to_addrs_names) ) ? to_html($this->email->to_addrs_names) : to_html($this->email->to_addrs);
5631 $meta['email']['cc_addrs'] = to_html($this->email->cc_addrs_names);
5632 $meta['email']['reply_to_addr'] = to_html($this->email->reply_to_addr);
5633 $return['meta'] = $meta;
5639 * Takes a long list of email addresses from a To or CC field and shows the first 3, the rest hidden
5640 * @param string emails
5643 function collapseLongMailingList($emails) {
5644 global $app_strings;
5646 $ex = explode(",", $emails);
5650 if(count($ex) > 3) {
5654 foreach($ex as $email) {
5656 if(!empty($emails)) {
5659 $emails .= trim($email);
5661 if(!empty($emailsHidden)) {
5662 $emailsHidden .= ", ";
5664 $emailsHidden .= trim($email);
5670 if(!empty($emailsHidden)) {
5672 $emails = "<span onclick='javascript:SUGAR.email2.detailView.showFullEmailList(this);' style='cursor:pointer;'>{$emails} [...{$j} {$app_strings['LBL_MORE']}]</span>";
5673 $emailsHidden = "<span onclick='javascript:SUGAR.email2.detailView.showCroppedEmailList(this)' style='cursor:pointer; display:none;'>{$email2}, {$emailsHidden} [ {$app_strings['LBL_LESS']} ]</span>";
5676 $emails .= $emailsHidden;
5684 * Sorts IMAP's imap_fetch_overview() results
5685 * @param array $arr Array of standard objects
5686 * @param string $sort Column to sort by
5687 * @param string direction Direction to sort by (asc/desc)
5688 * @return array Sorted array of obj.
5690 function sortFetchedOverview($arr, $sort=4, $direction='DESC', $forceSeen=false) {
5691 global $current_user;
5693 $sortPrefs = $current_user->getPreference('folderSortOrder', 'Emails');
5694 if(!empty($sortPrefs))
5695 $listPrefs = $sortPrefs;
5697 $listPrefs = array();
5699 if(isset($listPrefs[$this->id][$this->mailbox])) {
5700 $currentNode = $listPrefs[$this->id][$this->mailbox];
5703 if(isset($currentNode['current']) && !empty($currentNode['current'])) {
5704 $sort = $currentNode['current']['sort'];
5705 $direction = $currentNode['current']['direction'];
5710 $sort = $this->defaultSort;//4;
5711 $direction = $this->defaultDirection; //'DESC';
5712 } elseif(!is_numeric($sort)) {
5713 // handle bad sort index
5714 $sort = $this->defaultSort;
5716 // translate numeric index to human readable
5717 $sort = $this->hrSort[$sort];
5719 if(empty($direction)) {
5720 $direction = 'DESC';
5728 foreach($arr as $k => $overview) {
5729 $sorts['flagged'][$k] = $overview->flagged;
5730 $sorts['status'][$k] = $overview->answered;
5731 $sorts['from'][$k] = str_replace('"', "", $this->handleMimeHeaderDecode($overview->from));
5732 $sorts['subj'][$k] = $this->handleMimeHeaderDecode(quoted_printable_decode($overview->subject));
5733 $sorts['date'][$k] = $overview->date;
5737 natcasesort($sorts[$sort]);
5738 //_ppd($sorts[$sort]);
5740 if(strtolower($direction) == 'desc') {
5741 $revSorts = array();
5742 $keys = array_reverse(array_keys($sorts[$sort]));
5743 // _pp("count keys in DESC: ".count($keys));
5744 // _pp("count elements in sort[sort]: ".count($sorts[$sort]));
5746 for($i=0; $i<count($keys); $i++) {
5748 $revSorts[$v] = $sorts[$sort][$v];
5751 //_pp("count post-sort: ".count($revSorts));
5752 $sorts[$sort] = $revSorts;
5754 $timedate = TimeDate::getInstance();
5755 foreach($sorts[$sort] as $k2 => $overview2) {
5756 $arr[$k2]->date = $timedate->fromString($arr[$k2]->date)->asDb();
5757 $retArr[] = $arr[$k2];
5759 //_pp("final count: ".count($retArr));
5761 $finalReturn = array();
5762 $finalReturn['retArr'] = $retArr;
5763 $finalReturn['sortBy'] = $sort;
5764 $finalReturn['direction'] = $direction;
5765 return $finalReturn;
5769 function setReadFlagOnFolderCache($mbox, $uid) {
5770 global $sugar_config;
5772 $this->mailbox = $mbox;
5775 if($this->validCacheExists($this->mailbox)) {
5776 $ret = $this->getCacheValue($this->mailbox);
5780 foreach($ret as $k => $v) {
5781 if($v->imap_uid == $uid) {
5788 $this->setCacheValue($this->mailbox, array(), $updates);
5793 * Returns a list of emails in a mailbox.
5794 * @param string mbox Name of mailbox using dot notation paths to display
5795 * @param string $forceRefresh Flag to use cache or not
5797 function displayFolderContents($mbox, $forceRefresh='false', $page) {
5798 global $current_user;
5800 $delimiter = $this->get_stored_options('folderDelimiter');
5802 $mbox = str_replace('.', $delimiter, $mbox);
5805 $this->mailbox = $mbox;
5807 // jchi #9424, get sort and direction from user preference
5809 $direction = 'desc';
5810 $sortSerial = $current_user->getPreference('folderSortOrder', 'Emails');
5811 if(!empty($sortSerial) && !empty($_REQUEST['ieId']) && !empty($_REQUEST['mbox'])) {
5812 $sortArray = unserialize($sortSerial);
5813 $sort = $sortArray[$_REQUEST['ieId']][$_REQUEST['mbox']]['current']['sort'];
5814 $direction = $sortArray[$_REQUEST['ieId']][$_REQUEST['mbox']]['current']['direction'];
5819 if(!empty($_REQUEST['sort']) && !empty($_REQUEST['dir'])) {
5820 $this->email->et->saveListViewSortOrder($_REQUEST['ieId'], $_REQUEST['mbox'], $_REQUEST['sort'], $_REQUEST['dir']);
5821 $sort = $_REQUEST['sort'];
5822 $direction = $_REQUEST['dir'];
5824 $_REQUEST['sort'] = '';
5825 $_REQUEST['dir'] = '';
5831 if($forceRefresh == 'false' && $this->validCacheExists($this->mailbox)) {
5832 $emailSettings = $current_user->getPreference('emailSettings', 'Emails');
5834 // cn: default to a low number until user specifies otherwise
5835 if(empty($emailSettings['showNumInList'])) {
5836 $emailSettings['showNumInList'] = 20;
5839 $ret = $this->getCacheValue($this->mailbox, $emailSettings['showNumInList'], $page, $sort, $direction);
5843 $out = $this->displayFetchedSortedListXML($ret, $mbox);
5845 $metadata = array();
5846 $metadata['mbox'] = $mbox;
5847 $metadata['ieId'] = $this->id;
5848 $metadata['name'] = $this->name;
5849 $metadata['fromCache'] = $cacheUsed ? 1 : 0;
5850 $metadata['out'] = $out;
5856 * For a group email account, create subscriptions for all users associated with the
5857 * team assigned to the account.
5860 function createUserSubscriptionsForGroupAccount()
5863 $team->retrieve($this->team_id);
5864 $usersList = $team->get_team_members(true);
5865 foreach($usersList as $userObject)
5867 $previousSubscriptions = unserialize(base64_decode($userObject->getPreference('showFolders', 'Emails',$userObject)));
5868 if($previousSubscriptions === FALSE)
5869 $previousSubscriptions = array();
5871 $previousSubscriptions[] = $this->id;
5873 $encodedSubs = base64_encode(serialize($previousSubscriptions));
5874 $userObject->setPreference('showFolders',$encodedSubs , '', 'Emails');
5875 $userObject->savePreferencesToDB();
5879 * Create a sugar folder for this inbound email account
5880 * if the Enable Auto Import option is selected
5882 * @return String Id of the sugar folder created.
5884 function createAutoImportSugarFolder()
5886 global $current_user;
5887 $guid = create_guid();
5888 $GLOBALS['log']->debug("Creating Sugar Folder for IE with id $guid");
5889 $folder = new SugarFolder();
5890 $folder->id = $guid;
5891 $folder->new_with_id = TRUE;
5892 $folder->name = $this->name;
5893 $folder->has_child = 0;
5894 $folder->is_group = 1;
5895 $folder->assign_to_id = $current_user->id;
5896 $folder->parent_folder = "";
5899 //If this inbound email is marked as inactive, don't add subscriptions.
5900 $addSubscriptions = ($this->status == 'Inactive' || $this->mailbox_type == 'bounce') ? FALSE : TRUE;
5901 $folder->save($addSubscriptions);
5906 function validCacheExists($mbox) {
5907 $q = "SELECT count(*) c FROM email_cache WHERE ie_id = '{$this->id}'";
5908 $r = $this->db->query($q);
5909 $a = $this->db->fetchByAssoc($r);
5922 function displayFetchedSortedListXML($ret, $mbox) {
5925 global $current_user;
5926 global $sugar_config;
5928 if(empty($ret['retArr'])) {
5932 $tPref = $current_user->getUserDateTimePreferences();
5936 foreach($ret['retArr'] as $msg) {
5938 $flagged = ($msg->flagged == 0) ? "" : $this->iconFlagged;
5939 $status = ($msg->deleted) ? $this->iconDeleted : "";
5940 $status = ($msg->draft == 0) ? $status : $this->iconDraft;
5941 $status = ($msg->answered == 0) ? $status : $this->iconAnswered;
5942 $from = $this->handleMimeHeaderDecode($msg->from);
5943 $subject = $this->handleMimeHeaderDecode($msg->subject);
5944 //$date = date($tPref['date']." ".$tPref['time'], $msg->date);
5945 $date = $timedate->to_display_date_time($this->db->fromConvert($msg->date, 'datetime'));
5946 //$date = date($tPref['date'], $this->getUnixHeaderDate($msg->date));
5949 $temp['flagged'] = $flagged;
5950 $temp['status'] = $status;
5951 $temp['from'] = to_html($from);
5952 $temp['subject'] = $subject;
5953 $temp['date'] = $date;
5954 $temp['uid'] = $msg->uid; // either from an imap_search() or massaged cache value
5955 $temp['mbox'] = $this->mailbox;
5956 $temp['ieId'] = $this->id;
5957 $temp['site_url'] = $sugar_config['site_url'];
5958 $temp['seen'] = $msg->seen;
5959 $temp['type'] = (isset($msg->type)) ? $msg->type: 'remote';
5960 $temp['to_addrs'] = to_html($msg->to);
5961 $temp['hasAttach'] = '0';
5972 * retrieves the mailboxes for a given account in the following format
5977 [Builder] => Builder
5984 * @param bool $justRaw Default false
5987 function getMailboxes($justRaw=false) {
5988 if($justRaw == true) {
5989 return $this->mailboxarray;
5992 return $this->generateMultiDimArrayFromFlatArray($this->mailboxarray, $this->retrieveDelimiter());
5994 $serviceString = $this->getConnectString('', '', false);
5996 if(strpos($serviceString, 'pop3')) {
5998 $obj->name = $serviceString."INBOX";
5999 $boxes = array("INBOX" => $obj);
6001 $boxes = imap_getmailboxes($this->conn, $serviceString, "*");
6006 // clean MBOX path names
6007 foreach($boxes as $k => $mbox) {
6008 $raw[] = str_replace($serviceString, "", $mbox->name);
6009 if ($mbox->delimiter) {
6010 $delimiter = $mbox->delimiter;
6013 $storedOptions = unserialize(base64_decode($this->stored_options));
6014 $storedOptions['folderDelimiter'] = $delimiter;
6015 $this->stored_options = base64_encode(serialize($storedOptions));
6021 // used by $this->search()
6022 if($justRaw == true) {
6027 // generate a multi-dimensional array to iterate through
6029 foreach($raw as $mbox) {
6030 $ret = $this->sortMailboxes($mbox, $ret, $delimiter);
6037 function getMailBoxesForGroupAccount() {
6038 $mailboxes = $this->generateMultiDimArrayFromFlatArray(explode(",", $this->mailbox), $this->retrieveDelimiter());
6039 $mailboxesArray = $this->generateFlatArrayFromMultiDimArray($mailboxes, $this->retrieveDelimiter());
6040 $mailboxesArray = $this->filterMailBoxFromRaw(explode(",", $this->mailbox), $mailboxesArray);
6041 $this->saveMailBoxFolders($mailboxesArray);
6043 if ($this->mailbox != $this->$email_user) {
6044 $mailboxes = $this->sortMailboxes($this->mailbox, $this->retrieveDelimiter());
6045 $mailboxesArray = $this->generateFlatArrayFromMultiDimArray($mailboxes, $this->retrieveDelimiter());
6046 $this->saveMailBoxFolders($mailboxesArray);
6047 // save mailbox value of an inbound email account to email user
6048 $this->saveMailBoxValueOfInboundEmail();
6050 $mailboxes = $this->getMailboxes();
6056 function saveMailBoxFolders($value) {
6057 if (is_array($value)) {
6058 $value = implode(",", $value);
6060 $this->mailboxarray = explode(",", $value);
6061 $value = $this->db->quoted($value);
6062 $query = "update inbound_email set mailbox = $value where id ='{$this->id}'";
6063 $this->db->query($query);
6066 function insertMailBoxFolders($value) {
6067 $query = "select value from config where category='InboundEmail' and name='{$this->id}'";
6068 $r = $this->db->query($query);
6069 $a = $this->db->fetchByAssoc($r);
6070 if (empty($a['value'])) {
6071 if (is_array($value)) {
6072 $value = implode(",", $value);
6074 $this->mailboxarray = explode(",", $value);
6075 $value = $this->db->quoted($value);
6077 $query = "INSERT INTO config VALUES('InboundEmail', '{$this->id}', $value)";
6078 $this->db->query($query);
6082 function saveMailBoxValueOfInboundEmail() {
6083 $query = "update Inbound_email set mailbox = '{$this->email_user}'";
6084 $this->db->query($query);
6087 function retrieveMailBoxFolders() {
6088 $this->mailboxarray = explode(",", $this->mailbox);
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 $this->mailboxarray = explode(",", $a['value']);
6098 function retrieveDelimiter() {
6099 $delimiter = $this->get_stored_options('folderDelimiter');
6106 function generateFlatArrayFromMultiDimArray($arraymbox, $delimiter) {
6108 foreach($arraymbox as $key => $value) {
6109 $this->generateArrayData($key, $value, $ret, $delimiter);
6115 function generateMultiDimArrayFromFlatArray($raw, $delimiter) {
6116 // generate a multi-dimensional array to iterate through
6118 foreach($raw as $mbox) {
6119 $ret = $this->sortMailboxes($mbox, $ret, $delimiter);
6125 function generateArrayData($key, $arraymbox, &$ret, $delimiter) {
6127 if (is_array($arraymbox)) {
6128 foreach($arraymbox as $mboxKey => $value) {
6129 $newKey = $key . $delimiter . $mboxKey;
6130 $this->generateArrayData($newKey, $value, $ret, $delimiter);
6136 * sorts the folders in a mailbox in a multi-dimensional array
6137 * @param string $MBOX
6141 function sortMailboxes($mbox, $ret, $delimeter = ".") {
6142 if(strpos($mbox, $delimeter)) {
6143 $node = substr($mbox, 0, strpos($mbox, $delimeter));
6144 $nodeAfter = substr($mbox, strpos($mbox, $node) + strlen($node) + 1, strlen($mbox));
6146 if(!isset($ret[$node])) {
6147 $ret[$node] = array();
6148 } elseif(isset($ret[$node]) && !is_array($ret[$node])) {
6149 $ret[$node] = array();
6151 $ret[$node] = $this->sortMailboxes($nodeAfter, $ret[$node], $delimeter);
6153 $ret[$mbox] = $mbox;
6160 * parses Sugar's storage method for imap server service strings
6163 function getServiceString() {
6165 $exServ = explode('::', $this->service);
6167 foreach($exServ as $v) {
6168 if(!empty($v) && ($v != 'imap' && $v !='pop3')) {
6177 * Get Email messages IDs from server which aren't in database
6178 * @return array Ids of messages, which aren't still in database
6180 public function getNewEmailsForSyncedMailbox()
6182 // ids's count limit for batch processing
6184 $msgIds = imap_search($this->conn, 'ALL UNDELETED');
6187 if(count($msgIds) > 0)
6190 * @var collect results of queries and message headers
6196 // sort IDs to get lastest on top
6198 $GLOBALS['log']->debug('-----> getNewEmailsForSyncedMailbox() got '.count($msgIds).' Messages');
6199 foreach($msgIds as $k => &$msgNo)
6201 $uid = imap_uid($this->conn, $msgNo);
6202 $header = imap_headerinfo($this->conn, $msgNo);
6203 $fullHeader = imap_fetchheader($this->conn, $msgNo);
6204 $message_id = $header->message_id;
6205 $deliveredTo = $this->id;
6207 preg_match('/(delivered-to:|x-real-to:){1}\s*(\S+)\s*\n{1}/im', $fullHeader, $matches);
6210 $deliveredTo = $matches[2];
6212 if(empty($message_id) || !isset($message_id))
6214 $GLOBALS['log']->debug('*********** NO MESSAGE_ID.');
6215 $message_id = $this->getMessageId($header);
6218 // generate compound messageId
6219 $this->compoundMessageId = trim($message_id) . trim($deliveredTo);
6220 // if the length > 255 then md5 it so that the data will be of smaller length
6221 if (strlen($this->compoundMessageId) > 255)
6223 $this->compoundMessageId = md5($this->compoundMessageId);
6226 if (empty($this->compoundMessageId))
6231 $potentials = clean_xss($this->compoundMessageId, false);
6233 if(is_array($potentials) && !empty($potentials))
6235 foreach($potentials as $bad)
6237 $this->compoundMessageId = str_replace($bad, "", $this->compoundMessageId);
6240 array_push($tmpMsgs, array('msgNo' => $msgNo, 'msgId' => $this->compoundMessageId, 'exists' => 0));
6241 if($counter == $limit)
6245 foreach(array_slice($tmpMsgs, -$limit, $limit) as $k1 => $v1)
6247 $query[] = $v1['msgId'];
6249 $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';
6250 $r = $this->db->query($query);
6252 while($a = $this->db->fetchByAssoc($r))
6254 $tmp[html_entity_decode($a['mid'])] = $a['cnt'];
6256 foreach($tmpMsgs as $k1 => $v1)
6258 if(isset($tmp[$v1['msgId']]) && $tmp[$v1['msgId']] > 0)
6260 $tmpMsgs[$k1]['exists'] = 1;
6263 foreach($tmpMsgs as $k1 => $v1)
6265 if($v1['exists'] == 0)
6268 array_push($result, $v1['msgNo']);
6275 if($repeats >= $limit)
6281 $tmpMsgs = array_splice($tmpMsgs, -$repeats, $repeats);
6292 }catch(Exception $ex)
6294 $GLOBALS['log']->fatal($ex->getMessage());
6296 $GLOBALS['log']->debug('-----> getNewEmailsForSyncedMailbox() got '.count($result).' unsynced messages');
6300 } // end class definition
6304 * Simple class to mirror the passed object from an imap_fetch_overview() call
6323 var $indices; /* = array(
6326 'name' => 'mail_date',
6334 'name' => 'mail_from',
6342 'name' => 'mail_subj',
6351 var $fieldDefs;/* = array(
6354 'type' => 'varchar',
6359 'name' => 'subject',
6360 'type' => 'varchar',
6362 'required' => false,
6364 'fromaddr' => array(
6365 'name' => 'fromaddr',
6366 'type' => 'varchar',
6372 'type' => 'varchar',
6376 'senddate' => array(
6377 'name' => 'senddate',
6378 'type' => 'datetime',
6381 'message_id' => array(
6382 'name' => 'message_id',
6383 'type' => 'varchar',
6385 'required' => false,
6387 'mailsize' => array(
6388 'name' => 'mailsize',
6403 'required' => false,
6407 'type' => 'tinyint',
6412 'name' => 'flagged',
6413 'type' => 'tinyint',
6417 'answered' => array(
6418 'name' => 'answered',
6419 'type' => 'tinyint',
6424 'name' => 'deleted',
6425 'type' => 'tinyint',
6431 'type' => 'tinyint',
6437 'type' => 'tinyint',
6443 function Overview() {
6446 if(!isset($dictionary['email_cache']) || empty($dictionary['email_cache'])) {
6447 if(file_exists('custom/metadata/email_cacheMetaData.php')) {
6448 include('custom/metadata/email_cacheMetaData.php');
6450 include('metadata/email_cacheMetaData.php');
6454 $this->fieldDefs = $dictionary['email_cache']['fields'];
6455 $this->indices = $dictionary['email_cache']['indices'];