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-2011 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 ********************************************************************************/
38 /*********************************************************************************
40 * Description: TODO: To be written.
41 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
42 * All Rights Reserved.
43 * Contributor(s): ______________________________________..
44 ********************************************************************************/
48 require_once('include/OutboundEmail/OutboundEmail.php');
49 require_once('include/Pear/HTML_Safe/Safe.php');
51 function this_callback($str) {
52 foreach($str as $match) {
53 $ret .= chr(hexdec(str_replace("%","",$match)));
59 * Stub for certain interactions;
65 class InboundEmail extends SugarBean {
68 var $purifier; // HTMLPurifier object placeholder
76 var $modified_user_id;
79 var $modified_by_name;
99 var $outboundInstance; // id to outbound_email instance
101 var $iconFlagged = "F";
102 var $iconDraft = "D";
103 var $iconAnswered = "A";
104 var $iconDeleted = "del";
105 var $isAutoImport = false;
107 var $attachmentCount = 0;
108 var $tempAttachment = array();
109 var $unsafeChars = array("&", "!", "'", '"', '\\', '/', '<', '>', '|', '$',);
111 var $defaultSort = 'date';
112 var $defaultDirection = "DESC";
120 var $hrSortLocal = array(
121 'flagged' => 'flagged',
122 'status' => 'answered',
123 'from' => 'fromaddr',
124 'subject' => 'subject',
125 'date' => 'senddate',
128 // default attributes
129 var $transferEncoding = array(0 => '7BIT',
133 4 => 'QUOTED-PRINTABLE',
137 var $safe; // place holder for HTML_Safe class
138 var $compoundMessageId; // concatenation of messageID and deliveredToEmail
139 var $serverConnectString;
140 var $disable_row_level_security = true;
141 var $InboundEmailCachePath;
142 var $InboundEmailCacheFile = 'InboundEmail.cache.php';
143 var $object_name = 'InboundEmail';
144 var $module_dir = 'InboundEmail';
145 var $table_name = 'inbound_email';
146 var $new_schema = true;
147 var $process_save_dates = true;
153 var $required_fields = array('name' => 'name',
154 'server_url' => 'server_url',
155 'mailbox' => 'mailbox',
159 var $imageTypes = array("JPG", "JPEG", "GIF", "PNG");
160 var $inlineImages = array(); // temporary space to store ID of inlined images
161 var $defaultEmailNumAutoreplies24Hours = 10;
162 var $maxEmailNumAutoreplies24Hours = 10;
163 // custom ListView attributes
164 var $mailbox_type_name;
165 var $global_personal_string;
166 // service attributes
171 var $keyForUsersDefaultIEAccount = 'defaultIEAccount';
172 // prefix to use when importing inlinge images in emails
178 function InboundEmail() {
179 $this->InboundEmailCachePath = sugar_cached('modules/InboundEmail');
180 $this->EmailCachePath = sugar_cached('modules/Emails');
182 if(function_exists("imap_timeout")) {
194 $this->safe = new HTML_Safe();
195 $this->safe->whiteProtocols[] = "cid";
196 $this->safe->clear();
198 $this->smarty = new Sugar_Smarty();
199 $this->overview = new Overview();
200 $this->imagePrefix = "{$GLOBALS['sugar_config']['site_url']}/cache/images/";
206 * @return object Bean
208 function retrieve($id) {
209 $ret = parent::retrieve($id);
210 $this->email_password = blowfishDecode(blowfishGetKey('InboundEmail'), $this->email_password);
211 $this->retrieveMailBoxFolders();
216 * wraps SugarBean->save()
217 * @param string ID of saved bean
219 function save($check_notify=false) {
220 // generate cache table for email 2.0
221 $multiDImArray = $this->generateMultiDimArrayFromFlatArray(explode(",", $this->mailbox), $this->retrieveDelimiter());
222 $raw = $this->generateFlatArrayFromMultiDimArray($multiDImArray, $this->retrieveDelimiter());
224 //_pp(explode(",", $this->mailbox));
226 $raw = $this->filterMailBoxFromRaw(explode(",", $this->mailbox), $raw);
227 $this->mailbox = implode(",", $raw);
228 if(!empty($this->email_password)) {
229 $this->email_password = blowfishEncode(blowfishGetKey('InboundEmail'), $this->email_password);
231 $ret = parent::save($check_notify);
235 function filterMailBoxFromRaw($mailboxArray, $rawArray) {
236 $newArray = array_intersect($mailboxArray, $rawArray);
242 * Overrides SugarBean's mark_deleted() to drop the related cache table
243 * @param string $id GUID of I-E instance
245 function mark_deleted($id) {
246 parent::mark_deleted($id);
247 $q = "update inbound_email set groupfolder_id = null WHERE id = $id";
248 $r = $this->db->query($q);
249 $this->deleteCache();
253 * Mark cached email answered (replied)
254 * @param string $mailid (uid for imap, message_id for pop3)
256 function mark_answered($mailid, $type = 'smtp') {
259 $q = "update email_cache set answered = 1 WHERE imap_uid = $mailid and ie_id = '$this->id'";
260 $this->db->query($q);
263 $q = "update email_cache set answered = 1 WHERE message_id = '$mailid' and ie_id = '$this->id'";
264 $this->db->query($q);
270 * Renames an IMAP mailbox
271 * @param string $newName
273 function renameFolder($oldName, $newName) {
274 //$this->mailbox = "INBOX"
275 $this->connectMailserver();
276 $oldConnect = $this->getConnectString('', $oldName);
277 $newConnect = $this->getConnectString('', $newName);
278 if(!imap_renamemailbox($this->conn, $oldConnect , $newConnect)) {
279 $GLOBALS['log']->debug("***INBOUNDEMAIL: failed to rename mailbox [ {$oldConnect} ] to [ {$newConnect} ]");
281 $this->mailbox = str_replace($oldName, $newName, $this->mailbox);
283 $sessionFoldersString = $this->getSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol);
284 $sessionFoldersString = str_replace($oldName, $newName, $sessionFoldersString);
285 $this->setSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol, $sessionFoldersString);
290 ///////////////////////////////////////////////////////////////////////////
291 //// CUSTOM LOGIC HOOKS
293 * Called from $this->getMessageText()
294 * Allows upgrade-safe custom processing of message text.
297 * 1. Create a directory path: ./custom/modules/InboundEmail if it does not exist
298 * 2. Create a file in the ./custom/InboundEmail/ folder called "getMessageText.php"
299 * 3. Define a function named "custom_getMessageText()" that takes a string as an argument and returns a string
301 * @param string $msgPart
304 function customGetMessageText($msgPart) {
305 $custom = "custom/modules/InboundEmail/getMessageText.php";
307 if(file_exists($custom)) {
308 include_once($custom);
310 if(function_exists("custom_getMessageText")) {
311 $GLOBALS['log']->debug("*** INBOUND EMAIL-CUSTOM_LOGIC: calling custom_getMessageText()");
312 $msgPart = custom_getMessageText($msgPart);
318 //// END CUSTOM LOGIC HOOKS
319 ///////////////////////////////////////////////////////////////////////////
323 ///////////////////////////////////////////////////////////////////////////
324 //// EMAIL 2.0 SPECIFIC
326 * constructs a nicely formatted version of raw source
327 * @param int $uid UID of email
330 function getFormattedRawSource($uid) {
333 //if($this->protocol == 'pop3') {
334 //$raw = $app_strings['LBL_EMAIL_VIEW_UNSUPPORTED'];
336 if (empty($this->id)) {
337 $q = "SELECT raw_source FROM emails_text WHERE email_id = '{$uid}'";
338 $r = $this->db->query($q);
339 $a = $this->db->fetchByAssoc($r);
341 $raw = utf8_encode($a['raw_source']);
343 $raw = $app_strings['LBL_EMAIL_ERROR_VIEW_RAW_SOURCE'];
346 if ($this->isPop3Protocol()) {
347 $uid = $this->getCorrectMessageNoForPop3($uid);
349 $raw = imap_fetchheader($this->conn, $uid, FT_UID+FT_PREFETCHTEXT);
350 $raw .= utf8_encode(imap_body($this->conn, $uid, FT_UID));
352 $raw = to_html($raw);
360 * constructs a nicely formatted version of email headers.
364 function getFormattedHeaders($uid) {
367 //if($this->protocol == 'pop3') {
368 // $header = $app_strings['LBL_EMAIL_VIEW_UNSUPPORTED'];
370 if ($this->isPop3Protocol()) {
371 $uid = $this->getCorrectMessageNoForPop3($uid);
373 $headers = imap_fetchheader($this->conn, $uid, FT_UID);
375 $lines = explode("\n", $headers);
377 $header = "<table cellspacing='0' cellpadding='2' border='0' width='100%'>";
379 foreach($lines as $line) {
383 $key = trim(substr($line, 0, strpos($line, ":")));
384 $value = trim(substr($line, strpos($line, ":") + 1));
385 $value = to_html($value);
388 $header .= "<td class='displayEmailLabel' NOWRAP><b>{$key}</b> </td>";
389 $header .= "<td class='displayEmailValueWhite'>{$value} </td>";
394 $header .= "</table>";
400 * Empties Trash folders
402 function emptyTrash() {
403 global $sugar_config;
405 $this->mailbox = $this->get_stored_options("trashFolder");
406 if (empty($this->mailbox)) {
407 $this->mailbox = 'INBOX.Trash';
409 $this->connectMailserver();
411 $uids = imap_search($this->conn, "ALL", SE_UID);
413 foreach($uids as $uid) {
414 if(!imap_delete($this->conn, $uid, FT_UID)) {
415 $lastError = imap_last_error();
416 $GLOBALS['log']->warn("INBOUNDEMAIL: emptyTrash() Could not delete message [ {$uid} ] from [ {$this->mailbox} ]. IMAP_ERROR [ {$lastError} ]");
420 // remove local cache file
421 $q = "DELETE FROM email_cache WHERE mbox = '{$this->mailbox}' AND ie_id = '{$this->id}'";
422 $r = $this->db->query($q);
426 * Fetches a timestamp
428 function getCacheTimestamp($mbox) {
429 $key = $this->db->quote("{$this->id}_{$mbox}");
430 $q = "SELECT ie_timestamp FROM inbound_email_cache_ts WHERE id = '{$key}'";
431 $r = $this->db->query($q);
432 $a = $this->db->fetchByAssoc($r);
437 return $a['ie_timestamp'];
441 * sets the cache timestamp
444 function setCacheTimestamp($mbox) {
445 $key = $this->db->quote("{$this->id}_{$mbox}");
447 $tsOld = $this->getCacheTimestamp($mbox);
450 $q = "INSERT INTO inbound_email_cache_ts (id, ie_timestamp) VALUES ('{$key}', {$ts})";
452 $q = "UPDATE inbound_email_cache_ts SET ie_timestamp = {$ts} WHERE id = '{$key}'";
455 $r = $this->db->query($q, true);
456 $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: setting timestamp query [ {$q} ]");
461 * Gets a count of all rows that are flagged seen = 0
462 * @param string $mbox
465 function getCacheUnreadCount($mbox) {
466 $q = "SELECT count(*) c FROM email_cache WHERE mbox = '{$mbox}' AND seen = 0 AND ie_id = '{$this->id}'";
467 $r = $this->db->query($q);
468 $a = $this->db->fetchByAssoc($r);
474 * Returns total number of emails for a mailbox
478 function getCacheCount($mbox) {
479 $q = "SELECT count(*) c FROM email_cache WHERE mbox = '{$mbox}' AND ie_id = '{$this->id}'";
480 $r = $this->db->query($q);
481 $a = $this->db->fetchByAssoc($r);
486 function getCacheUnread($mbox) {
487 $q = "SELECT count(*) c FROM email_cache WHERE mbox = '{$mbox}' AND ie_id = '{$this->id}' AND seen = '0'";
488 $r = $this->db->query($q);
489 $a = $this->db->fetchByAssoc($r);
496 * Deletes all rows for a given instance
498 function deleteCache() {
499 $q = "DELETE FROM email_cache WHERE ie_id = '{$this->id}'";
501 $GLOBALS['log']->info("INBOUNDEMAIL: deleting cache using query [ {$q} ]");
503 $r = $this->db->query($q);
507 * Deletes all the pop3 data which has been deleted from server
509 function deletePop3Cache() {
510 global $sugar_config;
511 $UIDLs = $this->pop3_getUIDL();
512 $cacheUIDLs = $this->pop3_getCacheUidls();
513 foreach($cacheUIDLs as $msgNo => $msgId) {
514 if (!in_array($msgId, $UIDLs)) {
515 $md5msgIds = md5($msgId);
516 $file = "{$this->EmailCachePath}/{$this->id}/messages/INBOX{$md5msgIds}.PHP";
517 $GLOBALS['log']->debug("INBOUNDEMAIL: deleting file [ {$file} ] ");
518 if(file_exists($file)) {
520 $GLOBALS['log']->debug("INBOUNDEMAIL: Could not delete [ {$file} ] ");
523 $q = "DELETE from email_cache where imap_uid = {$msgNo} AND msgno = {$msgNo} AND ie_id = '{$this->id}' AND message_id = '{$msgId}'";
524 $r = $this->db->query($q);
530 * Retrieves cached headers
533 function getCacheValueForUIDs($mbox, $UIDs) {
534 if (!is_array($UIDs) || empty($UIDs)) {
538 $q = "SELECT * FROM email_cache WHERE ie_id = '{$this->id}' AND mbox = '{$mbox}' AND ";
542 $slicedArray = array_slice($UIDs, $startIndex ,$endIndex);
543 $columnName = ($this->isPop3Protocol() ? "message_id" : "imap_uid");
545 'timestamp' => $this->getCacheTimestamp($mbox),
549 while (!empty($slicedArray)) {
550 $messageIdString = implode(',', $slicedArray);
551 $GLOBALS['log']->debug("sliced array = {$messageIdString}");
552 $extraWhere = "{$columnName} IN (";
554 foreach($slicedArray as $UID) {
556 $extraWhere = $extraWhere . ",";
559 $extraWhere = "{$extraWhere} '{$UID}'";
561 $newQuery = $q . $extraWhere . ")";
562 $r = $this->db->query($newQuery);
564 while($a = $this->db->fetchByAssoc($r)) {
565 if (isset($a['uid'])) {
566 if ($this->isPop3Protocol()) {
567 $ret['uids'][] = $a['message_id'];
569 $ret['uids'][] = $a['uid'];
573 $overview = new Overview();
575 foreach($a as $k => $v) {
579 $overview->imap_uid = $v;
580 if ($this->isPop3Protocol()) {
581 $overview->uid = $a['message_id'];
587 $overview->to = from_html($v);
591 $overview->from = from_html($v);
595 $overview->size = $v;
599 $overview->date = $v;
603 $overview->$k = from_html($v);
607 $ret['retArr'][] = $overview;
609 $startIndex = $startIndex + $endIndex;
610 $slicedArray = array_slice($UIDs, $startIndex ,$endIndex);
611 $messageIdString = implode(',', $slicedArray);
612 $GLOBALS['log']->debug("sliced array = {$messageIdString}");
618 * Retrieves cached headers
621 function getCacheValue($mbox, $limit = 20, $page = 1, $sort='', $direction='') {
622 // try optimizing this call as we don't want repeat queries
623 if(!empty($this->currentCache)) {
624 return $this->currentCache;
627 $sort = (empty($sort)) ? $this->defaultSort : $sort;
628 $direction = (empty($direction)) ? $this->defaultDirection : $direction;
629 $order = " ORDER BY {$this->hrSortLocal[$sort]} {$direction}";
631 $q = "SELECT * FROM email_cache WHERE ie_id = '{$this->id}' AND mbox = '{$mbox}' {$order}";
634 $start = ( $page - 1 ) * $limit;
635 $r = $this->db->limitQuery($q, $start, $limit);
637 $r = $this->db->query($q);
641 'timestamp' => $this->getCacheTimestamp($mbox),
646 while($a = $this->db->fetchByAssoc($r)) {
647 if (isset($a['uid'])) {
648 if ($this->isPop3Protocol()) {
649 $ret['uids'][] = $a['message_id'];
651 $ret['uids'][] = $a['uid'];
655 $overview = new Overview();
657 foreach($a as $k => $v) {
661 $overview->imap_uid = $v;
662 if ($this->isPop3Protocol()) {
663 $overview->uid = $a['message_id'];
669 $overview->to = from_html($v);
673 $overview->from = from_html($v);
677 $overview->size = $v;
681 $overview->date = $v;
685 $overview->$k = from_html($v);
689 $ret['retArr'][] = $overview;
692 $this->currentCache = $ret;
700 function setCacheValue($mbox, $insert, $update=array(), $remove=array()) {
707 // reset in-memory cache
708 $this->currentCache = null;
710 $table = 'email_cache';
711 $where = "WHERE ie_id = '{$this->id}' AND mbox = '{$mbox}'";
713 // handle removed rows
714 if(!empty($remove)) {
716 foreach($remove as $overview) {
717 if(!empty($removeIds)) {
721 $removeIds .= "'{$overview->imap_uid}'";
724 $q = "DELETE FROM {$table} {$where} AND imap_uid IN ({$removeIds})";
726 $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: delete query [ {$q} ]");
728 $r = $this->db->query($q, true, $q);
731 // handle insert rows
732 if(!empty($insert)) {
733 $q = "SELECT imap_uid FROM {$table} {$where}";
734 $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: filter UIDs query [ {$q} ]");
735 $r = $this->db->query($q);
738 while($a = $this->db->fetchByAssoc($r)) {
739 $uids[] = $a['imap_uid'];
741 $count = count($uids);
742 $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: found [ {$count} ] UIDs to filter against");
745 foreach($uids as $uid) {
750 $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: filter UIDs: [ {$tmp} ]");
754 foreach($this->overview->fieldDefs as $colDef) {
758 $cols .= "{$colDef['name']}";
760 foreach($insert as $overview) {
761 if(in_array($overview->imap_uid, $uids)) {
762 $update[] = $overview;
768 foreach($this->overview->fieldDefs as $colDef) {
769 if(!empty($values)) {
773 // trim values for Oracle/MSSql
774 if( isset($colDef['len']) && !empty($colDef['len']) &&
775 isset($colDef['type']) && !empty($colDef['type']) &&
776 $colDef['type'] == 'varchar'
778 $overview->$colDef['name'] = substr($overview->$colDef['name'], 0, $colDef['len']);
781 switch($colDef['name']) {
783 if(isset($overview->uid) && !empty($overview->uid)) {
784 $this->imap_uid = $overview->uid;
786 $values .= "'{$this->imap_uid}'";
790 $values .= "'{$this->id}'";
794 $values .= $this->db->quoted($overview->to);
798 $values .= $this->db->quoted($overview->from);
802 $values .= $this->db->quoted($overview->message_id);
806 $values .= $overview->size;
810 $conv=$timedate->fromString($overview->date);
812 $values .= $this->db->quoted($conv->asDb());
819 $values .= "'{$mbox}'";
823 $overview->$colDef['name'] = from_html($overview->$colDef['name']);
824 $overview->$colDef['name'] = $this->cleanContent($overview->$colDef['name']);
825 $values .= $this->db->quoted($overview->$colDef['name']);
830 $q = "INSERT INTO {$table} ({$cols}) VALUES ({$values})";
831 $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: insert query [ {$q} ]");
832 $r = $this->db->query($q, true, $q);
836 // handle update rows
837 if(!empty($update)) {
839 foreach($this->overview->fieldDefs as $colDef) {
843 $cols .= "{$colDef['name']}";
846 foreach($update as $overview) {
847 $q = "UPDATE {$table} SET ";
850 foreach($this->overview->fieldDefs as $colDef) {
852 switch($colDef['name']) {
864 $set .= "{$colDef['name']} = ".$this->db->quoted($overview->$colDef['name']);
869 $q .= $set . " WHERE ie_id = '{$this->id}' AND mbox = '{$overview->mbox}' AND imap_uid = '{$overview->imap_uid}'";
870 $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: update query [ {$q} ]");
871 $r = $this->db->query($q, true, $q);
878 * Opens a socket connection to the pop3 server
881 function pop3_open() {
882 if(!is_resource($this->pop3socket)) {
883 $GLOBALS['log']->info("*** INBOUNDEMAIL: opening socket connection");
884 $exServ = explode('::', $this->service);
885 $socket = ($exServ[2] == 'ssl') ? "ssl://" : "tcp://";
886 $socket .= $this->server_url;
887 $this->pop3socket = fsockopen($socket, $this->port);
889 $GLOBALS['log']->info("*** INBOUNDEMAIL: REUSING socket connection");
893 if(!is_resource($this->pop3socket)) {
894 $GLOBALS['log']->debug("*** INBOUNDEMAIL: unable to open socket connection");
899 $ret = trim(fgets($this->pop3socket, 1024));
900 $GLOBALS['log']->info("*** INBOUNDEMAIL: got socket connection [ {$ret} ]");
905 * Closes connections and runs clean-up routines
907 function pop3_cleanUp() {
908 $GLOBALS['log']->info("*** INBOUNDEMAIL: cleaning up socket connection");
909 fputs($this->pop3socket, "QUIT\r\n");
910 $buf = fgets($this->pop3socket, 1024);
911 fclose($this->pop3socket);
915 * sends a command down to the POP3 server
916 * @param string command
921 function pop3_sendCommand($command, $args='', $return=true) {
922 $command .= " {$args}";
923 $command = trim($command);
924 $GLOBALS['log']->info("*** INBOUNDEMAIL: pop3_sendCommand() SEND [ {$command} ]");
927 fputs($this->pop3socket, $command);
930 $ret = trim(fgets($this->pop3socket, 1024));
931 $GLOBALS['log']->info("*** INBOUNDEMAIL: pop3_sendCommand() RECEIVE [ {$ret} ]");
936 function getPop3NewMessagesToDownload() {
937 $pop3UIDL = $this->pop3_getUIDL();
938 $cacheUIDLs = $this->pop3_getCacheUidls();
939 // new email cache values we should deal with
940 $diff = array_diff_assoc($pop3UIDL, $cacheUIDLs);
941 // this is msgNo to UIDL array
942 $diff = $this->pop3_shiftCache($diff, $cacheUIDLs);
943 // get all the keys which are msgnos;
944 return array_keys($diff);
947 function getPop3NewMessagesToDownloadForCron() {
948 $pop3UIDL = $this->pop3_getUIDL();
949 $cacheUIDLs = $this->pop3_getCacheUidls();
950 // new email cache values we should deal with
951 $diff = array_diff_assoc($pop3UIDL, $cacheUIDLs);
952 // this is msgNo to UIDL array
953 $diff = $this->pop3_shiftCache($diff, $cacheUIDLs);
954 // insert data into email_cache
955 if ($this->groupfolder_id != null && $this->groupfolder_id != "" && $this->isPop3Protocol()) {
956 $searchResults = array_keys($diff);
957 $concatResults = implode(",", $searchResults);
958 if ($this->connectMailserver() == 'true') {
959 $fetchedOverviews = imap_fetch_overview($this->conn, $concatResults);
960 // clean up cache entry
961 foreach($fetchedOverviews as $k => $overview) {
962 $overview->message_id = trim($diff[$overview->msgno]);
963 $fetchedOverviews[$k] = $overview;
965 $this->updateOverviewCacheFile($fetchedOverviews);
972 * This method returns all the UIDL for this account. This should be called if the protocol is pop3
973 * @return array od messageno to UIDL array
975 function pop3_getUIDL() {
977 if($this->pop3_open()) {
979 $this->pop3_sendCommand("USER", $this->email_user);
980 $this->pop3_sendCommand("PASS", $this->email_password);
983 $this->pop3_sendCommand("UIDL", '', false); // leave socket buffer alone until the while()
984 fgets($this->pop3socket, 1024); // handle "OK+";
989 if(is_resource($this->pop3socket)) {
990 while(!feof($this->pop3socket)) {
991 $buf = fgets($this->pop3socket, 1024); // 8kb max buffer - shouldn't be more than 80 chars via pop3...
994 if(trim($buf) == '.') {
995 $GLOBALS['log']->debug("*** GOT '.'");
999 // format is [msgNo] [UIDL]
1000 $exUidl = explode(" ", $buf);
1001 $UIDLs[$exUidl[0]] = trim($exUidl[1]);
1004 $this->pop3_cleanUp();
1010 * Special handler for POP3 boxes. Standard IMAP commands are useless.
1011 * This will fetch only partial emails for POP3 and hence needs to be call again and again based on status it returns
1013 function pop3_checkPartialEmail($synch = false) {
1014 require_once('include/utils/array_utils.php');
1015 global $current_user;
1016 global $sugar_config;
1018 $cacheDataExists = false;
1021 $cacheFilePath = clean_path("{$this->EmailCachePath}/{$this->id}/folders/MsgNOToUIDLData.php");
1022 if(file_exists($cacheFilePath)) {
1023 $cacheDataExists = true;
1024 if($fh = @fopen($cacheFilePath, "rb")) {
1026 $chunksize = 1*(1024*1024); // how many bytes per chunk
1028 $buf = fgets($fh, $chunksize); // 8kb max buffer - shouldn't be more than 80 chars via pop3...
1029 $data = $data . $buf;
1033 $diff = unserialize($data);
1034 if (!empty($diff)) {
1035 if (count($diff)> 50) {
1036 $newDiff = array_slice($diff, 50, count($diff), true);
1040 $results = array_slice(array_keys($diff), 0 ,50);
1041 $data = serialize($newDiff);
1042 if($fh = @fopen($cacheFilePath, "w")) {
1049 if (!$cacheDataExists) {
1051 $this->deletePop3Cache();
1053 $UIDLs = $this->pop3_getUIDL();
1054 if(count($UIDLs) > 0) {
1056 $cacheUIDLs = $this->pop3_getCacheUidls();
1058 // new email cache values we should deal with
1059 $diff = array_diff_assoc($UIDLs, $cacheUIDLs);
1060 $diff = $this->pop3_shiftCache($diff, $cacheUIDLs);
1061 require_once('modules/Emails/EmailUI.php');
1062 EmailUI::preflightEmailCache("{$this->EmailCachePath}/{$this->id}");
1064 if (count($diff)> 50) {
1065 $newDiff = array_slice($diff, 50, count($diff), true);
1070 $results = array_slice(array_keys($diff), 0 ,50);
1071 $data = serialize($newDiff);
1072 if($fh = @fopen($cacheFilePath, "w")) {
1077 $GLOBALS['log']->debug("*** INBOUNDEMAIL: could not open socket connection to POP3 server");
1078 return "could not open socket connection to POP3 server";
1082 // build up msgNo request
1083 if(count($diff) > 0) {
1084 // remove dirty cache entries
1086 if (isset($_REQUEST['currentCount']) && $_REQUEST['currentCount'] > -1) {
1087 $startingNo = $_REQUEST['currentCount'];
1090 $this->mailbox = 'INBOX';
1091 $this->connectMailserver();
1092 //$searchResults = array_keys($diff);
1093 //$fetchedOverviews = array();
1094 //$chunkArraySerachResults = array_chunk($searchResults, 50);
1095 $concatResults = implode(",", $results);
1096 $GLOBALS['log']->info('$$$$ '.$concatResults);
1097 $GLOBALS['log']->info("[EMAIL] Start POP3 fetch overview on mailbox [{$this->mailbox}] for user [{$current_user->user_name}] on 50 data");
1098 $fetchedOverviews = imap_fetch_overview($this->conn, $concatResults);
1099 $GLOBALS['log']->info("[EMAIL] End POP3 fetch overview on mailbox [{$this->mailbox}] for user [{$current_user->user_name}] on "
1100 . sizeof($fetchedOverviews) . " data");
1102 // clean up cache entry
1103 foreach($fetchedOverviews as $k => $overview) {
1104 $overview->message_id = trim($diff[$overview->msgno]);
1105 $fetchedOverviews[$k] = $overview;
1108 $GLOBALS['log']->info("[EMAIL] Start updating overview cache for pop3 mailbox [{$this->mailbox}] for user [{$current_user->user_name}]");
1109 $this->updateOverviewCacheFile($fetchedOverviews);
1110 $GLOBALS['log']->info("[EMAIL] Start updating overview cache for pop3 mailbox [{$this->mailbox}] for user [{$current_user->user_name}]");
1111 return array('status' => "In Progress", 'mbox' => $this->mailbox, 'count'=> (count($results) + $startingNo), 'totalcount' => count($diff), 'ieid' => $this->id);
1113 unlink($cacheFilePath);
1114 return array('status' => "done");
1119 * Special handler for POP3 boxes. Standard IMAP commands are useless.
1121 function pop3_checkEmail() {
1122 if($this->pop3_open()) {
1124 $this->pop3_sendCommand("USER", $this->email_user);
1125 $this->pop3_sendCommand("PASS", $this->email_password);
1128 $this->pop3_sendCommand("UIDL", '', false); // leave socket buffer alone until the while()
1129 fgets($this->pop3socket, 1024); // handle "OK+";
1134 if(is_resource($this->pop3socket)) {
1135 while(!feof($this->pop3socket)) {
1136 $buf = fgets($this->pop3socket, 1024); // 8kb max buffer - shouldn't be more than 80 chars via pop3...
1139 if(trim($buf) == '.') {
1140 $GLOBALS['log']->debug("*** GOT '.'");
1144 // format is [msgNo] [UIDL]
1145 $exUidl = explode(" ", $buf);
1146 $UIDLs[$exUidl[0]] = trim($exUidl[1]);
1150 $this->pop3_cleanUp();
1153 $cacheUIDLs = $this->pop3_getCacheUidls();
1154 // _pp($UIDLs);_pp($cacheUIDLs);
1156 // new email cache values we should deal with
1157 $diff = array_diff_assoc($UIDLs, $cacheUIDLs);
1159 // remove dirty cache entries
1160 $diff = $this->pop3_shiftCache($diff, $cacheUIDLs);
1162 // build up msgNo request
1164 $this->mailbox = 'INBOX';
1165 $this->connectMailserver();
1166 $searchResults = array_keys($diff);
1167 $concatResults = implode(",", $searchResults);
1168 $fetchedOverviews = imap_fetch_overview($this->conn, $concatResults);
1170 // clean up cache entry
1171 foreach($fetchedOverviews as $k => $overview) {
1172 $overview->message_id = trim($diff[$overview->msgno]);
1173 $fetchedOverviews[$k] = $overview;
1176 $this->updateOverviewCacheFile($fetchedOverviews);
1179 $GLOBALS['log']->debug("*** INBOUNDEMAIL: could not open socket connection to POP3 server");
1185 * Iterates through msgno and message_id to remove dirty cache entries
1188 function pop3_shiftCache($diff, $cacheUIDLs) {
1191 $newArray = array();
1192 foreach($diff as $msgNo => $msgId) {
1193 if (in_array($msgId, $cacheUIDLs)) {
1194 $q1 = "UPDATE email_cache SET imap_uid = {$msgNo}, msgno = {$msgNo} WHERE ie_id = '{$this->id}' AND message_id = '{$msgId}'";
1195 $this->db->query($q1);
1197 $newArray[$msgNo] = $msgId;
1202 foreach($diff as $msgNo => $msgId) {
1203 if(!empty($msgNos)) {
1206 if(!empty($msgIds)) {
1211 $msgIds .= "'{$msgId}'";
1214 if(!empty($msgNos)) {
1215 $q1 = "DELETE FROM email_cache WHERE ie_id = '{$this->id}' AND msgno IN ({$msgNos})";
1216 $this->db->query($q1);
1218 if(!empty($msgIds)) {
1219 $q2 = "DELETE FROM email_cache WHERE ie_id = '{$this->id}' AND message_id IN ({$msgIds})";
1220 $this->db->query($q2);
1226 * retrieves cached uidl values.
1227 * When dealing with POP3 accounts, the message_id column in email_cache will contain the UIDL.
1230 function pop3_getCacheUidls() {
1231 $q = "SELECT msgno, message_id FROM email_cache WHERE ie_id = '{$this->id}'";
1232 $r = $this->db->query($q);
1235 while($a = $this->db->fetchByAssoc($r)) {
1236 $ret[$a['msgno']] = $a['message_id'];
1243 * This function is used by cron job for group mailbox without group folder
1244 * @param string $msgno for pop
1245 * @param string $uid for imap
1247 function getMessagesInEmailCache($msgno, $uid) {
1248 $fetchedOverviews = array();
1249 if ($this->isPop3Protocol()) {
1250 $fetchedOverviews = imap_fetch_overview($this->conn, $msgno);
1251 foreach($fetchedOverviews as $k => $overview) {
1252 $overview->message_id = $uid;
1253 $fetchedOverviews[$k] = $overview;
1256 $fetchedOverviews = imap_fetch_overview($this->conn, $uid, FT_UID);
1258 $this->updateOverviewCacheFile($fetchedOverviews);
1263 * Checks email (local caching too) for one mailbox
1264 * @param string $mailbox IMAP Mailbox path
1265 * @param bool $prefetch Flag to prefetch email body on check
1267 function checkEmailOneMailbox($mailbox, $prefetch=true, $synchronize=false) {
1268 global $sugar_config;
1269 global $current_user;
1270 global $app_strings;
1272 $GLOBALS['log']->info("INBOUNDEMAIL: checking mailbox [ {$mailbox} ]");
1273 $this->mailbox = $mailbox;
1274 $this->connectMailserver();
1277 $shouldProcessRules = true;
1279 $timestamp = $this->getCacheTimestamp($mailbox);
1281 if($timestamp > 0) {
1282 $checkTime = date('r', $timestamp);
1285 /* first time through, process ALL emails */
1286 if(empty($checkTime) || $synchronize) {
1287 // do not process rules for the first time or sunchronize
1288 $shouldProcessRules = false;
1289 $criteria = "ALL UNDELETED";
1290 $prefetch = false; // do NOT prefetch emails on a brand new account - timeouts happen.
1291 $GLOBALS['log']->info("INBOUNDEMAIL: new account detected - not prefetching email bodies.");
1293 $criteria = "SINCE \"{$checkTime}\" UNDELETED"; // not using UNSEEN
1295 $this->setCacheTimestamp($mailbox);
1296 $GLOBALS['log']->info("[EMAIL] Performing IMAP search using criteria [{$criteria}] on mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1297 $searchResults = imap_search($this->conn, $criteria, SE_UID);
1298 $GLOBALS['log']->info("[EMAIL] Done IMAP search on mailbox [{$mailbox}] for user [{$current_user->user_name}]. Result count = ".count($searchResults));
1300 if(!empty($searchResults)) {
1302 $concatResults = implode(",", $searchResults);
1303 $GLOBALS['log']->info("[EMAIL] Start IMAP fetch overview on mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1304 $fetchedOverview = imap_fetch_overview($this->conn, $concatResults, FT_UID);
1305 $GLOBALS['log']->info("[EMAIL] Done IMAP fetch overview on mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1307 $GLOBALS['log']->info("[EMAIL] Start updating overview cache for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1308 $this->updateOverviewCacheFile($fetchedOverview);
1309 $GLOBALS['log']->info("[EMAIL] Done updating overview cache for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1312 if($prefetch == true) {
1313 $GLOBALS['log']->info("[EMAIL] Start fetching emails for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1314 $this->fetchCheckedEmails($fetchedOverview);
1315 $GLOBALS['log']->info("[EMAIL] Done fetching emails for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1318 $GLOBALS['log']->info("INBOUNDEMAIL: no results for mailbox [ {$mailbox} ]");
1322 * To handle the use case where an external client is also connected, deleting emails, we need to clear our
1323 * local cache of all emails with the "DELETED" flag
1325 $criteria = 'DELETED';
1326 $criteria .= (!empty($checkTime)) ? " SINCE \"{$checkTime}\"" : "";
1327 $GLOBALS['log']->info("INBOUNDEMAIL: checking for deleted emails using [ {$criteria} ]");
1329 $trashFolder = $this->get_stored_options("trashFolder");
1330 if (empty($trashFolder)) {
1331 $trashFolder = "INBOX.Trash";
1334 if($this->mailbox != $trashFolder) {
1335 $searchResults = imap_search($this->conn, $criteria, SE_UID);
1336 if(!empty($searchResults)) {
1337 $uids = implode($app_strings['LBL_EMAIL_DELIMITER'], $searchResults);
1338 $GLOBALS['log']->info("INBOUNDEMAIL: removing UIDs found deleted [ {$uids} ]");
1339 $this->getOverviewsFromCacheFile($uids, $mailbox, true);
1345 * Checks email (local caching too) for one mailbox
1346 * @param string $mailbox IMAP Mailbox path
1347 * @param bool $prefetch Flag to prefetch email body on check
1349 function checkEmailOneMailboxPartial($mailbox, $prefetch=true, $synchronize=false, $start = 0, $max = -1) {
1350 global $sugar_config;
1351 global $current_user;
1352 global $app_strings;
1354 $GLOBALS['log']->info("INBOUNDEMAIL: checking mailbox [ {$mailbox} ]");
1355 $this->mailbox = $mailbox;
1356 $this->connectMailserver();
1359 $shouldProcessRules = true;
1361 $timestamp = $this->getCacheTimestamp($mailbox);
1363 if($timestamp > 0) {
1364 $checkTime = date('r', $timestamp);
1367 /* first time through, process ALL emails */
1368 if(empty($checkTime) || $synchronize) {
1369 // do not process rules for the first time or sunchronize
1370 $shouldProcessRules = false;
1371 $criteria = "ALL UNDELETED";
1372 $prefetch = false; // do NOT prefetch emails on a brand new account - timeouts happen.
1373 $GLOBALS['log']->info("INBOUNDEMAIL: new account detected - not prefetching email bodies.");
1375 $criteria = "SINCE \"{$checkTime}\" UNDELETED"; // not using UNSEEN
1377 $this->setCacheTimestamp($mailbox);
1378 $GLOBALS['log']->info("[EMAIL] Performing IMAP search using criteria [{$criteria}] on mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1379 $searchResults = $this->getCachedIMAPSearch($criteria);
1381 if(!empty($searchResults)) {
1383 $total = sizeof($searchResults);
1384 $searchResults = array_slice($searchResults, $start, $max);
1386 $GLOBALS['log']->info("INBOUNDEMAIL: there are $total messages in [{$mailbox}], we are on $start");
1387 $GLOBALS['log']->info("INBOUNDEMAIL: getting the next " . sizeof($searchResults) . " messages");
1388 $concatResults = implode(",", $searchResults);
1389 $GLOBALS['log']->info("INBOUNDEMAIL: Start IMAP fetch overview on mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1390 $fetchedOverview = imap_fetch_overview($this->conn, $concatResults, FT_UID);
1391 $GLOBALS['log']->info("INBOUNDEMAIL: Done IMAP fetch overview on mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1393 $GLOBALS['log']->info("INBOUNDEMAIL: Start updating overview cache for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1394 $this->updateOverviewCacheFile($fetchedOverview);
1395 $GLOBALS['log']->info("INBOUNDEMAIL: Done updating overview cache for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1398 if($prefetch == true) {
1399 $GLOBALS['log']->info("INBOUNDEMAIL: Start fetching emails for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1400 $this->fetchCheckedEmails($fetchedOverview);
1401 $GLOBALS['log']->info("INBOUNDEMAIL: Done fetching emails for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1403 $status = ($total > $start + sizeof($searchResults)) ? 'continue' : 'done';
1404 $ret = array('status' => $status, 'count' => $start + sizeof($searchResults), 'mbox' => $mailbox, 'totalcount' => $total);
1405 $GLOBALS['log']->info("INBOUNDEMAIL: $status : Downloaded " . $start + sizeof($searchResults) . "messages of $total");
1408 $GLOBALS['log']->info("INBOUNDEMAIL: no results for mailbox [ {$mailbox} ]");
1409 $ret = array('status' =>'done');
1412 if ($ret['status'] == 'done') {
1413 //Remove the cached search if we are done with this mailbox
1414 $cacheFilePath = clean_path("{$this->EmailCachePath}/{$this->id}/folders/SearchData.php");
1415 unlink($cacheFilePath);
1417 * To handle the use case where an external client is also connected, deleting emails, we need to clear our
1418 * local cache of all emails with the "DELETED" flag
1420 $criteria = 'DELETED';
1421 $criteria .= (!empty($checkTime)) ? " SINCE \"{$checkTime}\"" : "";
1422 $GLOBALS['log']->info("INBOUNDEMAIL: checking for deleted emails using [ {$criteria} ]");
1424 $trashFolder = $this->get_stored_options("trashFolder");
1425 if (empty($trashFolder)) {
1426 $trashFolder = "INBOX.Trash";
1429 if($this->mailbox != $trashFolder) {
1430 $searchResults = imap_search($this->conn, $criteria, SE_UID);
1431 if(!empty($searchResults)) {
1432 $uids = implode($app_strings['LBL_EMAIL_DELIMITER'], $searchResults);
1433 $GLOBALS['log']->info("INBOUNDEMAIL: removing UIDs found deleted [ {$uids} ]");
1434 $this->getOverviewsFromCacheFile($uids, $mailbox, true);
1441 function getCachedIMAPSearch($criteria) {
1442 global $current_user;
1443 global $sugar_config;
1445 $cacheDataExists = false;
1448 $cacheFolderPath = clean_path("{$this->EmailCachePath}/{$this->id}/folders");
1449 if (!file_exists($cacheFolderPath)) {
1450 mkdir_recursive($cacheFolderPath);
1452 $cacheFilePath = $cacheFolderPath . '/SearchData.php';
1453 $GLOBALS['log']->info("INBOUNDEMAIL: Cache path is $cacheFilePath");
1454 if(file_exists($cacheFilePath)) {
1455 $cacheDataExists = true;
1456 if($fh = @fopen($cacheFilePath, "rb")) {
1458 $chunksize = 1*(1024*1024); // how many bytes per chunk
1460 $buf = fgets($fh, $chunksize); // 8kb max buffer - shouldn't be more than 80 chars via pop3...
1461 $data = $data . $buf;
1465 $results = unserialize($data);
1468 if (!$cacheDataExists) {
1469 $searchResults = imap_search($this->conn, $criteria, SE_UID);
1470 if(count($searchResults) > 0) {
1471 $results = $searchResults;
1472 $data = serialize($searchResults);
1473 if($fh = @fopen($cacheFilePath, "w")) {
1482 function checkEmailIMAPPartial($prefetch=true, $synch = false) {
1483 $GLOBALS['log']->info("*****************INBOUNDEMAIL: at IMAP check partial");
1484 global $sugar_config;
1485 $this->connectMailserver();
1486 $mailboxes = $this->getMailboxes(true);
1487 if (!in_array('INBOX', $mailboxes)) {
1488 $mailboxes[] = 'INBOX';
1491 if (isset($_REQUEST['mbox']) && !empty($_REQUEST['mbox']) && isset($_REQUEST['currentCount'])) {
1492 $GLOBALS['log']->info("INBOUNDEMAIL: Picking up from where we left off");
1493 $mbox = $_REQUEST['mbox'];
1494 $count = $_REQUEST['currentCount'];
1497 $GLOBALS['log']->info("INBOUNDEMAIL: Cleaning out the cache");
1498 $this->cleanOutCache();
1500 $mbox = $mailboxes[0];
1503 $GLOBALS['log']->info("INBOUNDEMAIL:found " . sizeof($mailboxes) . " Mailboxes");
1504 $index = array_search($mbox, $mailboxes) + 1;
1505 $ret = $this->checkEmailOneMailboxPartial($mbox, $prefetch, $synch, $count, 100);
1506 while($ret['status'] == 'done' && $index < sizeof($mailboxes)) {
1507 if ($ret['count'] > 100) {
1508 $ret['mbox'] = $mailboxes[$index];
1509 $ret['status'] = 'continue';
1512 $GLOBALS['log']->info("INBOUNDEMAIL: checking account [ $index => $mbox : $count]");
1513 $mbox = $mailboxes[$index];
1514 $ret = $this->checkEmailOneMailboxPartial($mbox, $prefetch, $synch, 0, 100);
1521 function checkEmail2_meta() {
1522 global $sugar_config;
1524 $this->connectMailserver();
1525 $mailboxes = $this->getMailboxes(true);
1526 $mailboxes[] = 'INBOX';
1529 $GLOBALS['log']->info("INBOUNDEMAIL: checking account [ {$this->name} ]");
1531 $mailboxes_meta = array();
1532 foreach($mailboxes as $mailbox) {
1533 $mailboxes_meta[$mailbox] = $this->getMailboxProcessCount($mailbox);
1537 $ret['mailboxes'] = $mailboxes_meta;
1539 foreach($mailboxes_meta as $count) {
1540 $ret['processCount'] += $count;
1545 function getMailboxProcessCount($mailbox) {
1546 global $sugar_config;
1548 $GLOBALS['log']->info("INBOUNDEMAIL: checking mailbox [ {$mailbox} ]");
1549 $this->mailbox = $mailbox;
1550 $this->connectMailserver();
1552 $timestamp = $this->getCacheTimestamp($mailbox);
1555 if($timestamp > 0) {
1556 $checkTime = date('r', $timestamp);
1559 /* first time through, process ALL emails */
1560 if(empty($checkTime)) {
1561 $criteria = "ALL UNDELETED";
1562 $prefetch = false; // do NOT prefetch emails on a brand new account - timeouts happen.
1563 $GLOBALS['log']->info("INBOUNDEMAIL: new account detected - not prefetching email bodies.");
1565 $criteria = "SINCE \"{$checkTime}\" UNDELETED"; // not using UNSEEN
1568 $GLOBALS['log']->info("INBOUNDEMAIL: using [ {$criteria} ]");
1569 $searchResults = imap_search($this->conn, $criteria, SE_UID);
1571 if(!empty($searchResults)) {
1572 $concatResults = implode(",", $searchResults);
1574 $GLOBALS['log']->info("INBOUNDEMAIL: no results for mailbox [ {$mailbox} ]");
1577 if(empty($searchResults)) {
1581 return count($searchResults);
1587 function checkEmail($prefetch=true, $synch = false) {
1588 global $sugar_config;
1590 if($this->protocol == 'pop3') {
1591 $this->pop3_checkEmail();
1593 $this->connectMailserver();
1594 $mailboxes = $this->getMailboxes(true);
1595 $mailboxes[] = 'INBOX';
1598 $GLOBALS['log']->info("INBOUNDEMAIL: checking account [ {$this->name} ]");
1600 foreach($mailboxes as $mailbox) {
1601 $this->checkEmailOneMailbox($mailbox, $prefetch, $synch);
1607 * full synchronization
1609 function syncEmail() {
1610 global $sugar_config;
1611 global $current_user;
1613 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
1615 if(empty($showFolders)) {
1616 $showFolders = array();
1619 $email = new Email();
1620 $email->email2init();
1622 // personal accounts
1623 if($current_user->hasPersonalEmail()) {
1624 $personals = $this->retrieveByGroupId($current_user->id);
1626 foreach($personals as $personalAccount) {
1627 if(in_array($personalAccount->id, $showFolders)) {
1628 $personalAccount->email = $email;
1629 if ($personalAccount->isPop3Protocol()) {
1630 $personalAccount->deletePop3Cache();
1633 $personalAccount->cleanOutCache();
1634 $personalAccount->connectMailserver();
1635 $mailboxes = $personalAccount->getMailboxes(true);
1636 $mailboxes[] = 'INBOX';
1639 $GLOBALS['log']->info("[EMAIL] Start checking account [{$personalAccount->name}] for user [{$current_user->user_name}]");
1641 foreach($mailboxes as $mailbox) {
1642 $GLOBALS['log']->info("[EMAIL] Start checking mailbox [{$mailbox}] of account [{$personalAccount->name}] for user [{$current_user->user_name}]");
1643 $personalAccount->checkEmailOneMailbox($mailbox, false, true);
1644 $GLOBALS['log']->info("[EMAIL] Done checking mailbox [{$mailbox}] of account [{$personalAccount->name}] for user [{$current_user->user_name}]");
1646 $GLOBALS['log']->info("[EMAIL] Done checking account [{$personalAccount->name}] for user [{$current_user->user_name}]");
1652 $beans = $this->retrieveAllByGroupId($current_user->id, false);
1653 foreach($beans as $k => $groupAccount) {
1654 if(in_array($groupAccount->id, $showFolders)) {
1655 $groupAccount->email = $email;
1656 $groupAccount->cleanOutCache();
1657 $groupAccount->connectMailserver();
1658 $mailboxes = $groupAccount->getMailboxes(true);
1659 $mailboxes[] = 'INBOX';
1662 $GLOBALS['log']->info("INBOUNDEMAIL: checking account [ {$groupAccount->name} ]");
1664 foreach($mailboxes as $mailbox) {
1665 $groupAccount->checkEmailOneMailbox($mailbox, false, true);
1673 * Deletes cached messages when moving from folder to folder
1674 * @param string $uids
1675 * @param string $fromFolder
1676 * @param string $toFolder
1678 function deleteCachedMessages($uids, $fromFolder) {
1679 global $sugar_config;
1681 if(!isset($this->email) && !isset($this->email->et)) {
1682 $this->email = new Email();
1683 $this->email->email2init();
1686 $uids = $this->email->et->_cleanUIDList($uids);
1688 foreach($uids as $uid) {
1689 $file = "{$this->EmailCachePath}/{$this->id}/messages/{$fromFolder}{$uid}.php";
1691 if(file_exists($file)) {
1692 if(!unlink($file)) {
1693 $GLOBALS['log']->debug("INBOUNDEMAIL: Could not delete [ {$file} ]");
1700 * similar to imap_fetch_overview, but it gets overviews from a local cache
1702 * @param string $uids UIDs in comma-delimited format
1703 * @param string $mailbox The mailbox in focus, will default to $this->mailbox
1704 * @param bool $remove Default false
1707 function getOverviewsFromCacheFile($uids, $mailbox='', $remove=false) {
1708 global $app_strings;
1709 if(!isset($this->email) && !isset($this->email->et)) {
1710 $this->email = new Email();
1711 $this->email->email2init();
1714 $uids = $this->email->et->_cleanUIDList($uids, true);
1716 // load current cache file
1717 $mailbox = empty($mailbox) ? $this->mailbox : $mailbox;
1718 $cacheValue = $this->getCacheValue($mailbox);
1722 $exUids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
1723 foreach($exUids as $k => $uid) {
1724 $exUids[$k] = trim($uid);
1727 // fill $ret will requested $uids
1728 foreach($cacheValue['retArr'] as $k => $overview) {
1729 if(in_array($overview->imap_uid, $exUids)) {
1734 // remove requested $uids from current cache file (move_mail() type action)
1736 $this->setCacheValue($mailbox, array(), array(), $ret);
1742 * merges new info with the saved cached file
1743 * @param array $array Array of email Overviews
1744 * @param string $type 'append' or 'remove'
1745 * @param string $mailbox Target mailbox if not current assigned
1747 function updateOverviewCacheFile($array, $type='append', $mailbox='') {
1748 $mailbox = empty($mailbox) ? $this->mailbox : $mailbox;
1750 $cacheValue = $this->getCacheValue($mailbox);
1751 $uids = $cacheValue['uids'];
1753 $updateRows = array();
1754 $insertRows = array();
1755 $removeRows = array();
1758 if($type == 'append') { // append
1759 /* we are adding overviews to the cache file */
1760 foreach($array as $overview) {
1761 if(isset($overview->uid)) {
1762 $overview->imap_uid = $overview->uid; // coming from imap_fetch_overview() call
1765 if(!in_array($overview->imap_uid, $uids)) {
1766 $insertRows[] = $overview;
1770 $updatedCacheOverviews = array();
1771 // compare against generated list
1772 /* we are removing overviews from the cache file */
1773 foreach($cacheValue['retArr'] as $cacheOverview) {
1774 if(!in_array($cacheOverview->imap_uid, $uids)) {
1775 $insertRows[] = $cacheOverview;
1777 $removeRows[] = $cacheOverview;
1781 $cacheValue['retArr'] = $updatedCacheOverviews;
1784 $this->setCacheValue($mailbox, $insertRows, $updateRows, $removeRows);
1788 * Check email prefetches email bodies for quicker display
1789 * @param array array of fetched overviews
1791 function fetchCheckedEmails($fetchedOverviews) {
1792 global $sugar_config;
1794 if(is_array($fetchedOverviews) && !empty($fetchedOverviews)) {
1795 foreach($fetchedOverviews as $overview) {
1796 if($overview->size < 10000) {
1798 $uid = $overview->imap_uid;
1801 $file = "{$this->mailbox}{$uid}.php";
1802 $cacheFile = clean_path("{$this->EmailCachePath}/{$this->id}/messages/{$file}");
1804 if(!file_exists($cacheFile)) {
1805 $GLOBALS['log']->info("INBOUNDEMAIL: Prefetching email [ {$file} ]");
1806 $this->setEmailForDisplay($uid);
1807 $out = $this->displayOneEmail($uid, $this->mailbox);
1808 $this->email->et->writeCacheFile('out', $out, $this->id, 'messages', "{$this->mailbox}{$uid}.php");
1810 $GLOBALS['log']->debug("INBOUNDEMAIL: Trying to prefetch an email we already fetched! [ {$cacheFile} ]");
1813 $GLOBALS['log']->debug("*** INBOUNDEMAIL: prefetch has a message with no UID");
1816 $GLOBALS['log']->debug("INBOUNDEMAIL: skipping email prefetch - size too large [ {$overview->size} ]");
1823 * Sets flags on emails. Assumes that connection is live, correct folder is
1825 * @param string $uids Sequence of UIDs, comma separated
1826 * @param string $type Flag to mark
1828 function markEmails($uids, $type) {
1831 $result = imap_clearflag_full($this->conn, $uids, '\\SEEN', ST_UID);
1834 $result = imap_setflag_full($this->conn, $uids, '\\SEEN', ST_UID);
1837 $result = imap_setflag_full($this->conn, $uids, '\\FLAGGED', ST_UID);
1840 $result = imap_clearflag_full($this->conn, $uids, '\\FLAGGED', ST_UID);
1843 $result = imap_setflag_full($this->conn, $uids, '\\Answered', ST_UID);
1847 //// END EMAIL 2.0 SPECIFIC
1848 ///////////////////////////////////////////////////////////////////////////
1852 ///////////////////////////////////////////////////////////////////////////
1853 //// SERVER MANIPULATION METHODS
1855 * Deletes the specified folder
1856 * @param string $mbox "::" delimited IMAP mailbox path, ie, INBOX.saved.stuff
1859 function deleteFolder($mbox) {
1860 $returnArray = array();
1861 if ($this->getCacheCount($mbox) > 0) {
1862 $returnArray['status'] = false;
1863 $returnArray['errorMessage'] = "Can not delete {$mbox} as it has emails.";
1864 return $returnArray;
1866 $connectString = $this->getConnectString('', $mbox);
1867 //Remove Folder cache
1868 global $sugar_config;
1869 unlink("{$this->EmailCachePath}/{$this->id}/folders/folders.php");
1871 if(imap_unsubscribe($this->conn, imap_utf7_encode($connectString))) {
1872 if(imap_deletemailbox($this->conn, $connectString)) {
1873 $this->mailbox = str_replace(("," . $mbox), "", $this->mailbox);
1875 $sessionFoldersString = $this->getSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol);
1876 $sessionFoldersString = str_replace(("," . $mbox), "", $sessionFoldersString);
1877 $this->setSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol, $sessionFoldersString);
1878 $returnArray['status'] = true;
1879 return $returnArray;
1881 $GLOBALS['log']->error("*** ERROR: EMAIL2.0 - could not delete IMAP mailbox with path: [ {$connectString} ]");
1882 $returnArray['status'] = false;
1883 $returnArray['errorMessage'] = "NOOP: could not delete folder: {$connectString}";
1884 return $returnArray;
1888 $GLOBALS['log']->error("*** ERROR: EMAIL2.0 - could not unsubscribe from folder, {$connectString} before deletion.");
1889 $returnArray['status'] = false;
1890 $returnArray['errorMessage'] = "NOOP: could not unsubscribe from folder, {$connectString} before deletion.";
1891 return $returnArray;
1897 * @param string $name Name of new IMAP mailbox
1898 * @param string $mbox "::" delimited IMAP mailbox path, ie, INBOX.saved.stuff
1899 * @return bool True on success
1901 function saveNewFolder($name, $mbox) {
1902 global $sugar_config;
1903 //Remove Folder cache
1904 global $sugar_config;
1905 //unlink("{$this->EmailCachePath}/{$this->id}/folders/folders.php");
1907 //$mboxImap = $this->getImapMboxFromSugarProprietary($mbox);
1908 $delimiter = $this->get_stored_options('folderDelimiter');
1913 $newFolder = $mbox . $delimiter . $name;
1914 $mbox .= $delimiter.str_replace($delimiter, "_", $name);
1915 $connectString = $this->getConnectString('', $mbox);
1917 if(imap_createmailbox($this->conn, imap_utf7_encode($connectString))) {
1918 imap_subscribe($this->conn, imap_utf7_encode($connectString));
1919 $status = imap_status($this->conn, str_replace("{$delimiter}{$name}","",$connectString), SA_ALL);
1920 $this->mailbox = $this->mailbox . "," . $newFolder;
1922 $sessionFoldersString = $this->getSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol);
1923 $sessionFoldersString = $sessionFoldersString . "," . $newFolder;
1924 $this->setSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol, $sessionFoldersString);
1926 echo json_encode($status);
1929 echo "NOOP: could not create folder";
1930 $GLOBALS['log']->error("*** ERROR: EMAIL2.0 - could not create IMAP mailbox with path: [ {$connectString} ]");
1937 * Constructs an IMAP c-client compatible folder path from Sugar proprietary
1938 * @param string $mbox "::" delimited IMAP mailbox path, ie, INBOX.saved.stuff
1941 function getImapMboxFromSugarProprietary($mbox) {
1942 $exMbox = explode("::", $mbox);
1946 for($i=2; $i<count($exMbox); $i++) {
1947 if(!empty($mboxImap)) {
1950 $mboxImap .= $exMbox[$i];
1957 * Searches IMAP (and POP3?) accounts/folders for emails with qualifying criteria
1959 function search($ieId, $subject='', $from='', $to='', $body='', $dateFrom='', $dateTo='') {
1960 global $current_user;
1961 global $app_strings;
1965 $bean = new InboundEmail();
1966 $bean->retrieve($ieId);
1968 //$beans = $this->retrieveAllByGroupId($current_user->id, true);
1970 $subject = urldecode($subject);
1973 $criteria .= (!empty($subject)) ? 'SUBJECT '.from_html($subject).'' : "";
1974 $criteria .= (!empty($from)) ? ' FROM "'.$from.'"' : "";
1975 $criteria .= (!empty($to)) ? ' FROM "'.$to.'"' : "";
1976 $criteria .= (!empty($body)) ? ' TEXT "'.$body.'"' : "";
1977 $criteria .= (!empty($dateFrom)) ? ' SINCE "'.$timedate->fromString($dateFrom)->format('d-M-Y').'"' : "";
1978 $criteria .= (!empty($dateTo)) ? ' BEFORE "'.$timedate->fromString($dateTo)->format('d-M-Y').'"' : "";
1979 //$criteria .= (!empty($from)) ? ' FROM "'.$from.'"' : "";
1981 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
1985 foreach($beans as $bean) {
1986 if(!in_array($bean->id, $showFolders)) {
1990 $GLOBALS['log']->info("*** INBOUNDEMAIL: searching [ {$bean->name} ] for [ {$subject}{$from}{$to}{$body}{$dateFrom}{$dateTo} ]");
1991 $group = (!$bean->is_personal) ? 'group.' : '';
1992 $bean->connectMailServer();
1993 $mailboxes = $bean->getMailboxes(true);
1994 if (!in_array('INBOX', $mailboxes)) {
1995 $mailboxes[] = 'INBOX';
1999 foreach($mailboxes as $mbox) {
2000 $bean->mailbox = $mbox;
2001 $searchOverviews = array();
2002 if ($bean->protocol == 'pop3') {
2003 $pop3Criteria = "SELECT * FROM email_cache WHERE ie_id = '{$bean->id}' AND mbox = '{$mbox}'";
2004 $pop3Criteria .= (!empty($subject)) ? ' AND subject like "%'.$bean->db->quote($subject).'%"' : "";
2005 $pop3Criteria .= (!empty($from)) ? ' AND fromaddr like "%'.$from.'%"' : "";
2006 $pop3Criteria .= (!empty($to)) ? ' AND toaddr like "%'.$to.'%"' : "";
2007 $pop3Criteria .= (!empty($dateFrom)) ? ' AND senddate > "'.$dateFrom.'"' : "";
2008 $pop3Criteria .= (!empty($dateTo)) ? ' AND senddate < "'.$dateTo.'"' : "";
2009 $GLOBALS['log']->info("*** INBOUNDEMAIL: searching [ {$mbox} ] using criteria [ {$pop3Criteria} ]");
2011 $r = $bean->db->query($pop3Criteria);
2012 while($a = $bean->db->fetchByAssoc($r)) {
2013 $overview = new Overview();
2015 foreach($a as $k => $v) {
2019 $overview->imap_uid = $v;
2020 $overview->uid = $a['message_id'];
2023 $overview->to = from_html($v);
2027 $overview->from = from_html($v);
2031 $overview->size = $v;
2035 $overview->date = $timedate->fromString($v)->format('r');
2039 $overview->$k = from_html($v);
2043 $searchOverviews[] = $overview;
2046 $bean->connectMailServer();
2047 $searchResult = imap_search($bean->conn, $criteria, SE_UID);
2048 if (!empty($searchResult)) {
2049 $searchOverviews = imap_fetch_overview($bean->conn, implode(',', $searchResult), FT_UID);
2052 $numHits = count($searchOverviews);
2055 $totalHits = $totalHits + $numHits;
2056 $ret = $bean->sortFetchedOverview($searchOverviews, 'date', 'desc', true);
2057 $mbox = "{$bean->id}.SEARCH";
2058 $out = array_merge($out, $bean->displayFetchedSortedListXML($ret, $mbox, false));
2063 $metadata = array();
2064 $metadata['mbox'] = $app_strings['LBL_EMAIL_SEARCH_RESULTS_TITLE'];
2065 $metadata['ieId'] = $this->id;
2066 $metadata['name'] = $this->name;
2067 $metadata['unreadChecked'] = ($current_user->getPreference('showUnreadOnly', 'Emails') == 1) ? 'CHECKED' : '';
2068 $metadata['out'] = $out;
2074 * repairs the encrypted password for a given I-E account
2075 * @return bool True on success
2077 function repairAccount() {
2079 for($i=0; $i<3; $i++) {
2080 if($i != 0) { // decode is performed on retrieve already
2081 $this->email_password = blowfishDecode(blowfishGetKey('InboundEmail'), $this->email_password);
2084 if($this->connectMailserver() == 'true') {
2085 $this->save(); // save decoded password (is encoded on save())
2094 * soft deletes a User's personal inbox
2095 * @param string id I-E id
2096 * @param string user_name User name of User in focus, NOT current_user
2097 * @return bool True on success
2099 function deletePersonalEmailAccount($id, $user_name) {
2100 $q = "SELECT ie.id FROM inbound_email ie LEFT JOIN users u ON ie.group_id = u.id WHERE u.user_name = '{$user_name}'";
2101 $r = $this->db->query($q, true);
2103 while($a = $this->db->fetchByAssoc($r)) {
2104 if(!empty($a) && $a['id'] == $id) {
2105 $this->retrieve($id);
2114 function getTeamSetIdForTeams($teamIds) {
2115 if(!is_array($teamIds)){
2116 $teamIds = array($teamIds);
2118 $teamSet = new TeamSet();
2119 $team_set_id = $teamSet->addTeams($teamIds);
2120 return $team_set_id;
2124 * Saves Personal Inbox settings for Users
2125 * @param string userId ID of user to assign all emails for this account
2126 * @param strings userName Name of account, for Sugar purposes
2127 * @param bool forceSave Default true. Flag to save errored settings.
2128 * @return boolean true on success, false on fail
2130 function savePersonalEmailAccount($userId = '', $userName = '', $forceSave=true) {
2132 $accountExists = false;
2133 if(isset($_REQUEST['ie_id']) && !empty($_REQUEST['ie_id'])) {
2134 $this->retrieve($_REQUEST['ie_id']);
2135 $accountExists = true;
2137 $ie_name = $_REQUEST['ie_name'];
2139 $this->is_personal = 1;
2140 $this->name = $ie_name;
2141 $this->group_id = $groupId;
2142 $this->status = $_REQUEST['ie_status'];
2143 $this->server_url = trim($_REQUEST['server_url']);
2144 $this->email_user = trim($_REQUEST['email_user']);
2145 if(!empty($_REQUEST['email_password'])) {
2146 $this->email_password = html_entity_decode($_REQUEST['email_password'], ENT_QUOTES);
2148 $this->port = trim($_REQUEST['port']);
2149 $this->protocol = $_REQUEST['protocol'];
2150 if ($this->protocol == "pop3") {
2151 $_REQUEST['mailbox'] = "INBOX";
2153 $this->mailbox = $_REQUEST['mailbox'];
2154 $this->mailbox_type = 'pick'; // forcing this
2157 if(isset($_REQUEST['ssl']) && $_REQUEST['ssl'] == 1) { $useSsl = true; }
2158 else $useSsl = false;
2159 $this->service = '::::::::::';
2162 $id = $this->save(); // saving here to prevent user from having to re-enter all the info in case of error
2163 $this->retrieve($id);
2166 $this->protocol = $_REQUEST['protocol']; // need to set this again since we safe the "service" string to empty explode values
2167 $opts = $this->getSessionConnectionString($this->server_url, $this->email_user, $this->port, $this->protocol);
2168 $detectedOpts = $this->findOptimumSettings($useSsl);
2170 //If $detectedOpts is empty, there was an error connecting, so clear $opts. If $opts was empty, use $detectedOpts
2171 if (empty($opts) || empty($detectedOpts) || (empty($detectedOpts['good']) && empty($detectedOpts['serial'])))
2173 $opts = $detectedOpts;
2175 $delimiter = $this->getSessionInboundDelimiterString($this->server_url, $this->email_user, $this->port, $this->protocol);
2177 if(isset($opts['serial']) && !empty($opts['serial'])) {
2178 $this->service = $opts['serial'];
2179 if(isset($_REQUEST['mark_read']) && $_REQUEST['mark_read'] == 1) {
2180 $this->delete_seen = 0;
2182 $this->delete_seen = 1;
2185 // handle stored_options serialization
2186 if(isset($_REQUEST['only_since']) && $_REQUEST['only_since'] == 1) {
2192 $focusUser = new User();
2193 $focusUser->retrieve($groupId);
2194 $mailerId = (isset($_REQUEST['outbound_email'])) ? $_REQUEST['outbound_email'] : "";
2196 $oe = new OutboundEmail();
2197 $oe->getSystemMailerSettings($focusUser, $mailerId);
2199 $stored_options = array();
2200 $stored_options['from_name'] = trim($_REQUEST['from_name']);
2201 $stored_options['from_addr'] = trim($_REQUEST['from_addr']);
2202 $stored_options['reply_to_addr'] = trim($_REQUEST['reply_to_addr']);
2204 if (!$this->isPop3Protocol()) {
2205 $stored_options['trashFolder'] = (isset($_REQUEST['trashFolder']) ? trim($_REQUEST['trashFolder']) : "");
2206 $stored_options['sentFolder'] = (isset($_REQUEST['sentFolder']) ? trim($_REQUEST['sentFolder']) : "");
2208 $stored_options['only_since'] = $onlySince;
2209 $stored_options['filter_domain'] = '';
2210 $storedOptions['folderDelimiter'] = $delimiter;
2211 $stored_options['outbound_email'] = (isset($_REQUEST['outbound_email'])) ? $_REQUEST['outbound_email'] : $oe->id;
2212 $this->stored_options = base64_encode(serialize($stored_options));
2214 $ieId = $this->save();
2216 //If this is the first personal account the user has setup mark it as default for them.
2217 $currentIECount = $this->getUserPersonalAccountCount($focusUser);
2218 if($currentIECount == 1)
2219 $this->setUsersDefaultOutboundServerId($focusUser, $ieId);
2223 // could not find opts, no save
2224 $GLOBALS['log']->debug('-----> InboundEmail could not find optimums for User: '.$ie_name);
2229 * Determines if this instance of I-E is for a Group Inbox or Personal Inbox
2231 function handleIsPersonal() {
2232 $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.'\'';
2233 $rp = $this->db->query($qp, true);
2234 $personalBox = array();
2235 while($ap = $this->db->fetchByAssoc($rp)) {
2236 $personalBox[] = array($ap['id'], $ap['user_name']);
2238 if(count($personalBox) > 0) {
2245 function getUserNameFromGroupId() {
2246 $r = $this->db->query('SELECT users.user_name FROM users WHERE deleted=0 AND id=\''.$this->group_id.'\'', true);
2247 while($a = $this->db->fetchByAssoc($r)) {
2248 return $a['user_name'];
2253 function getFoldersListForMailBox() {
2255 $foldersList = $this->getSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol);
2256 if (empty($foldersList)) {
2257 global $mod_strings;
2258 $msg = $this->connectMailserver(true);
2259 if (strpos($msg, "successfully")) {
2260 $foldersList = $this->getSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol);
2261 $return['status'] = true;
2262 $return['foldersList'] = $foldersList;
2263 $return['statusMessage'] = "";
2265 $return['status'] = false;
2266 $return['statusMessage'] = $msg;
2269 $return['status'] = true;
2270 $return['foldersList'] = $foldersList;
2271 $return['statusMessage'] = "";
2276 * Programatically determines best-case settings for imap_open()
2278 function findOptimumSettings($useSsl=false, $user='', $pass='', $server='', $port='', $prot='', $mailbox='') {
2279 global $mod_strings;
2280 $serviceArr = array();
2281 $returnService = array();
2282 $badService = array();
2283 $goodService = array();
2284 $errorArr = array();
2286 $retArray = array( 'good' => $goodService,
2287 'bad' => $badService,
2288 'err' => $errorArr);
2290 if(!function_exists('imap_open')) {
2291 $retArray['err'][0] = $mod_strings['ERR_NO_IMAP'];
2295 imap_errors(); // clearing error stack
2296 error_reporting(0); // turn off notices from IMAP
2298 if(isset($_REQUEST['ssl']) && $_REQUEST['ssl'] == 1) {
2302 $exServ = explode('::', $this->service);
2303 $service = '/'.$exServ[1];
2305 $nonSsl = array('both-secure' => '/notls/novalidate-cert/secure',
2306 'both' => '/notls/novalidate-cert',
2307 'nocert-secure' => '/novalidate-cert/secure',
2308 'nocert' => '/novalidate-cert',
2309 'notls-secure' => '/notls/secure',
2310 'secure' => '/secure', // for POP3 servers that force CRAM-MD5
2311 'notls' => '/notls',
2312 'none' => '', // try default nothing
2315 'ssl-both-on-secure' => '/ssl/tls/validate-cert/secure',
2316 'ssl-both-on' => '/ssl/tls/validate-cert',
2317 'ssl-cert-secure' => '/ssl/validate-cert/secure',
2318 'ssl-cert' => '/ssl/validate-cert',
2319 'ssl-tls-secure' => '/ssl/tls/secure',
2320 'ssl-tls' => '/ssl/tls',
2321 'ssl-both-off-secure' => '/ssl/notls/novalidate-cert/secure',
2322 'ssl-both-off' => '/ssl/notls/novalidate-cert',
2323 'ssl-nocert-secure' => '/ssl/novalidate-cert/secure',
2324 'ssl-nocert' => '/ssl/novalidate-cert',
2325 'ssl-notls-secure' => '/ssl/notls/secure',
2326 'ssl-notls' => '/ssl/notls',
2327 'ssl-secure' => '/ssl/secure',
2328 'ssl-none' => '/ssl',
2331 if(isset($user) && !empty($user) && isset($pass) && !empty($pass)) {
2332 $this->email_password = $pass;
2333 $this->email_user = $user;
2334 $this->server_url = $server;
2335 $this->port = $port;
2336 $this->protocol = $prot;
2337 $this->mailbox = $mailbox;
2340 // in case we flip from IMAP to POP3
2341 if($this->protocol == 'pop3')
2342 $this->mailbox = 'INBOX';
2344 //If user has selected multiple mailboxes, we only need to test the first mailbox for the connection string.
2345 $a_mailbox = explode(",", $this->mailbox);
2346 $tmpMailbox = isset($a_mailbox[0]) ? $a_mailbox[0] : "";
2350 foreach($ssl as $k => $service)
2352 $returnService[$k] = 'foo'.$service;
2353 $serviceArr[$k] = '{'.$this->server_url.':'.$this->port.'/service='.$this->protocol.$service.'}'.$tmpMailbox;
2358 foreach($nonSsl as $k => $service)
2360 $returnService[$k] = 'foo'.$service;
2361 $serviceArr[$k] = '{'.$this->server_url.':'.$this->port.'/service='.$this->protocol.$service.'}'.$tmpMailbox;
2365 $GLOBALS['log']->debug('---------------STARTING FINDOPTIMUMS LOOP----------------');
2368 //php imap library will capture c-client library warnings as errors causing good connections to be ignored.
2369 //Check against known warnings to ensure good connections are used.
2370 $acceptableWarnings = array("SECURITY PROBLEM: insecure server advertised AUTH=PLAIN", //c-client auth_pla.c
2371 "Mailbox is empty");
2372 $login = $this->email_user;
2373 $passw = $this->email_password;
2374 $foundGoodConnection = false;
2375 foreach($serviceArr as $k => $serviceTest) {
2378 $GLOBALS['log']->debug($l.': I-E testing string: '.$serviceTest);
2380 // open the connection and try the test string
2381 $this->conn = imap_open($serviceTest, $login, $passw);
2383 if(($errors = imap_last_error()) || ($alerts = imap_alerts())) {
2384 if($errors == 'Too many login failures' || $errors == '[CLOSED] IMAP connection broken (server response)') { // login failure means don't bother trying the rest
2385 $GLOBALS['log']->debug($l.': I-E failed using ['.$serviceTest.']');
2386 $retArray['err'][$k] = $mod_strings['ERR_BAD_LOGIN_PASSWORD'];
2387 $retArray['bad'][$k] = $serviceTest;
2388 $GLOBALS['log']->debug($l.': I-E ERROR: $ie->findOptimums() failed due to bad user credentials for user login: '.$this->email_user);
2390 } elseif( in_array($errors, $acceptableWarnings, TRUE)) { // false positive
2391 $GLOBALS['log']->debug($l.': I-E found good connection but with warnings ['.$serviceTest.'] Errors:' . $errors);
2392 $retArray['good'][$k] = $returnService[$k];
2393 $foundGoodConnection = true;
2396 $GLOBALS['log']->debug($l.': I-E failed using ['.$serviceTest.'] - error: '.$errors);
2397 $retArray['err'][$k] = $errors;
2398 $retArray['bad'][$k] = $serviceTest;
2401 $GLOBALS['log']->debug($l.': I-E found good connect using ['.$serviceTest.']');
2402 $retArray['good'][$k] = $returnService[$k];
2403 $foundGoodConnection = true;
2406 if(is_resource($this->conn)) {
2407 if (!$this->isPop3Protocol()) {
2408 $serviceTest = str_replace("INBOX", "", $serviceTest);
2409 $boxes = imap_getmailboxes($this->conn, $serviceTest, "*");
2411 // clean MBOX path names
2412 foreach($boxes as $k => $mbox) {
2413 $raw[] = $mbox->name;
2414 if ($mbox->delimiter) {
2415 $delimiter = $mbox->delimiter;
2418 $this->setSessionInboundDelimiterString($this->server_url, $this->email_user, $this->port, $this->protocol, $delimiter);
2421 if(!imap_close($this->conn)) $GLOBALS['log']->debug('imap_close() failed!');
2424 $GLOBALS['log']->debug($l.': I-E clearing error and alert stacks.');
2425 imap_errors(); // clear stacks
2427 // If you find a good connection, then don't do any further testing to find URL
2428 if ($foundGoodConnection) {
2433 $GLOBALS['log']->debug('---------------end FINDOPTIMUMS LOOP----------------');
2435 if(!empty($retArray['good'])) {
2440 $newNovalidate_cert = '';
2441 $good = array_pop($retArray['good']); // get most complete string
2442 $exGood = explode('/', $good);
2443 foreach($exGood as $v) {
2452 $newNotls = 'notls';
2455 $newCert = 'validate-cert';
2457 case 'novalidate-cert':
2458 $newNovalidate_cert = 'novalidate-cert';
2466 $goodStr['serial'] = $newTls.'::'.$newCert.'::'.$newSsl.'::'.$this->protocol.'::'.$newNovalidate_cert.'::'.$newNotls.'::'.$secure;
2467 $goodStr['service'] = $good;
2468 $testConnectString = str_replace('foo','', $good);
2469 $testConnectString = '{'.$this->server_url.':'.$this->port.'/service='.$this->protocol.$testConnectString.'}';
2470 $this->setSessionConnectionString($this->server_url, $this->email_user, $this->port, $this->protocol, $goodStr);
2472 foreach($raw as $mbox)
2474 $raw[$i] = str_replace($testConnectString, "", $GLOBALS['locale']->translateCharset($mbox, "UTF7-IMAP", "UTF8" ));
2478 $this->setSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol, implode(",", $raw));
2485 function getSessionConnectionString($server_url, $email_user, $port, $protocol) {
2486 $sessionConnectionString = $server_url . $email_user . $port . $protocol;
2487 return (isset($_SESSION[$sessionConnectionString]) ? $_SESSION[$sessionConnectionString] : "");
2490 function setSessionConnectionString($server_url, $email_user, $port, $protocol, $goodStr) {
2491 $sessionConnectionString = $server_url . $email_user . $port . $protocol;
2492 $_SESSION[$sessionConnectionString] = $goodStr;
2495 function getSessionInboundDelimiterString($server_url, $email_user, $port, $protocol) {
2496 $sessionInboundDelimiterString = $server_url . $email_user . $port . $protocol . "delimiter";
2497 return (isset($_SESSION[$sessionInboundDelimiterString]) ? $_SESSION[$sessionInboundDelimiterString] : "");
2500 function setSessionInboundDelimiterString($server_url, $email_user, $port, $protocol, $delimiter) {
2501 $sessionInboundDelimiterString = $server_url . $email_user . $port . $protocol . "delimiter";
2502 $_SESSION[$sessionInboundDelimiterString] = $delimiter;
2505 function getSessionInboundFoldersString($server_url, $email_user, $port, $protocol) {
2506 $sessionInboundFoldersListString = $server_url . $email_user . $port . $protocol . "foldersList";
2507 return (isset($_SESSION[$sessionInboundFoldersListString]) ? $_SESSION[$sessionInboundFoldersListString] : "");
2510 function setSessionInboundFoldersString($server_url, $email_user, $port, $protocol, $foldersList) {
2511 $sessionInboundFoldersListString = $server_url . $email_user . $port . $protocol . "foldersList";
2512 $_SESSION[$sessionInboundFoldersListString] = $foldersList;
2516 * Checks for duplicate Group User names when creating a new one at save()
2517 * @return GUID returns GUID of Group User if user_name match is
2519 * @return boolean false if NO DUPE IS FOUND
2521 function groupUserDupeCheck() {
2522 $q = "SELECT u.id FROM users u WHERE u.deleted=0 AND u.is_group=1 AND u.user_name = '".$this->name."'";
2523 $r = $this->db->query($q, true);
2525 while($a = $this->db->fetchByAssoc($r)) {
2529 if(strlen($uid) > 0) {
2537 * Returns <option> markup with the contents of Group users
2538 * @param array $groups default empty array
2539 * @return string HTML options
2541 function getGroupsWithSelectOptions($groups = array()) {
2542 $r = $this->db->query('SELECT id, user_name FROM users WHERE users.is_group = 1 AND deleted = 0', true);
2543 if(is_resource($r)) {
2544 while($a = $this->db->fetchByAssoc($r)) {
2545 $groups[$a['id']] = $a['user_name'];
2549 $selectOptions = get_select_options_with_id_separate_key($groups, $groups, $this->group_id);
2550 return $selectOptions;
2554 * handles auto-responses to inbound emails
2556 * @param object email Email passed as reference
2558 function handleAutoresponse(&$email, &$contactAddr) {
2559 if($this->template_id) {
2560 $GLOBALS['log']->debug('found auto-reply template id - prefilling and mailing response');
2562 if($this->getAutoreplyStatus($contactAddr)
2563 && $this->checkOutOfOffice($email->name)
2564 && $this->checkFilterDomain($email)) { // if we haven't sent this guy 10 replies in 24hours
2566 if(!empty($this->stored_options)) {
2567 $storedOptions = unserialize(base64_decode($this->stored_options));
2570 if(!empty($storedOptions['from_name'])) {
2571 $from_name = $storedOptions['from_name'];
2572 $GLOBALS['log']->debug('got from_name from storedOptions: '.$from_name);
2573 } else { // use system default
2574 $rName = $this->db->query('SELECT value FROM config WHERE name = \'fromname\'', true);
2575 if(is_resource($rName)) {
2576 $aName = $this->db->fetchByAssoc($rName);
2578 if(!empty($aName['value'])) {
2579 $from_name = $aName['value'];
2585 if(!empty($storedOptions['from_addr'])) {
2586 $from_addr = $storedOptions['from_addr'];
2588 $rAddr = $this->db->query('SELECT value FROM config WHERE name = \'fromaddress\'', true);
2589 if(is_resource($rAddr)) {
2590 $aAddr = $this->db->fetchByAssoc($rAddr);
2592 if(!empty($aAddr['value'])) {
2593 $from_addr = $aAddr['value'];
2599 $replyToName = (!empty($storedOptions['reply_to_name']))? from_html($storedOptions['reply_to_name']) :$from_name ;
2600 $replyToAddr = (!empty($storedOptions['reply_to_addr'])) ? $storedOptions['reply_to_addr'] : $from_addr;
2603 if(!empty($email->reply_to_email)) {
2604 $to[0]['email'] = $email->reply_to_email;
2606 $to[0]['email'] = $email->from_addr;
2608 // handle to name: address, prefer reply-to
2609 if(!empty($email->reply_to_name)) {
2610 $to[0]['display'] = $email->reply_to_name;
2611 } elseif(!empty($email->from_name)) {
2612 $to[0]['display'] = $email->from_name;
2615 $et = new EmailTemplate();
2616 $et->retrieve($this->template_id);
2617 if(empty($et->subject)) { $et->subject = ''; }
2618 if(empty($et->body)) { $et->body = ''; }
2619 if(empty($et->body_html)) { $et->body_html = ''; }
2621 $reply = new Email();
2622 $reply->type = 'out';
2623 $reply->to_addrs = $to[0]['email'];
2624 $reply->to_addrs_arr = $to;
2625 $reply->cc_addrs_arr = array();
2626 $reply->bcc_addrs_arr = array();
2627 $reply->from_name = $from_name;
2628 $reply->from_addr = $from_addr;
2629 $reply->name = $et->subject;
2630 $reply->description = $et->body;
2631 $reply->description_html = $et->body_html;
2632 $reply->reply_to_name = $replyToName;
2633 $reply->reply_to_addr = $replyToAddr;
2635 $GLOBALS['log']->debug('saving and sending auto-reply email');
2636 //$reply->save(); // don't save the actual email.
2638 $this->setAutoreplyStatus($contactAddr);
2640 $GLOBALS['log']->debug('InboundEmail: auto-reply threshold reached for email ('.$contactAddr.') - not sending auto-reply');
2645 function handleCaseAssignment($email) {
2647 if($caseId = $this->getCaseIdFromCaseNumber($email->name, $c)) {
2648 $c->retrieve($caseId);
2649 $c->load_relationship('emails');
2650 $c->emails->add($email->id);
2652 $email->retrieve($email->id);
2653 $email->parent_type = "Cases";
2654 $email->parent_id = $caseId;
2655 // assign the email to the case owner
2656 $email->assigned_user_id = $c->assigned_user_id;
2658 $GLOBALS['log']->debug('InboundEmail found exactly 1 match for a case: '.$c->name);
2665 * handles functionality specific to the Mailbox type (Cases, bounced
2668 * @param object email Email object passed as a reference
2669 * @param object header Header object generated by imap_headerinfo();
2671 function handleMailboxType(&$email, &$header) {
2672 switch($this->mailbox_type) {
2674 $this->handleCaseAssignment($email);
2681 // do something with this?
2684 // do something with leads? we don't have an email_leads table
2690 require_once('modules/Campaigns/ProcessBouncedEmails.php');
2691 campaign_process_bounced_emails($email, $header);
2693 case 'pick': // do all except bounce handling
2694 $GLOBALS['log']->debug('looking for a case for '.$email->name);
2695 $this->handleCaseAssignment($email);
2700 function isMailBoxTypeCreateCase() {
2701 return ($this->mailbox_type == 'createcase' && !empty($this->groupfolder_id));
2704 function handleCreateCase($email, $userId) {
2705 global $current_user, $mod_strings, $current_language;
2706 $mod_strings = return_module_language($current_language, "Emails");
2707 $GLOBALS['log']->debug('In handleCreateCase');
2709 $this->getCaseIdFromCaseNumber($email->name, $c);
2711 if (!$this->handleCaseAssignment($email) && $this->isMailBoxTypeCreateCase()) {
2713 $GLOBALS['log']->debug('retrieveing email');
2714 $email->retrieve($email->id);
2716 $c->description = $email->description;
2717 $c->assigned_user_id = $userId;
2718 $c->name = $email->name;
2720 $c->priority = 'P1';
2722 if(!empty($email->reply_to_email)) {
2723 $contactAddr = $email->reply_to_email;
2725 $contactAddr = $email->from_addr;
2728 $GLOBALS['log']->debug('finding related accounts with address ' . $contactAddr);
2729 if($accountIds = $this->getRelatedId($contactAddr, 'accounts')) {
2730 if (sizeof($accountIds) == 1) {
2731 $c->account_id = $accountIds[0];
2733 $acct = new Account();
2734 $acct->retrieve($c->account_id);
2735 $c->account_name = $acct->name;
2741 $c->retrieve($caseId);
2742 if($c->load_relationship('emails')) {
2743 $c->emails->add($email->id);
2745 if($contactIds = $this->getRelatedId($contactAddr, 'contacts')) {
2746 if(!empty($contactIds) && $c->load_relationship('contacts')) {
2747 $c->contacts->add($contactIds);
2750 $c->email_id = $email->id;
2751 $email->parent_type = "Cases";
2752 $email->parent_id = $caseId;
2753 // assign the email to the case owner
2754 $email->assigned_user_id = $c->assigned_user_id;
2755 $email->name = str_replace('%1', $c->case_number, $c->getEmailSubjectMacro()) . " ". $email->name;
2757 $GLOBALS['log']->debug('InboundEmail created one case with number: '.$c->case_number);
2758 $createCaseTemplateId = $this->get_stored_options('create_case_email_template', "");
2759 if(!empty($this->stored_options)) {
2760 $storedOptions = unserialize(base64_decode($this->stored_options));
2762 if(!empty($createCaseTemplateId)) {
2765 if (!empty($this->stored_options)) {
2766 $fromAddress = $storedOptions['from_addr'];
2767 $fromName = from_html($storedOptions['from_name']);
2768 $replyToName = (!empty($storedOptions['reply_to_name']))? from_html($storedOptions['reply_to_name']) :$fromName ;
2769 $replyToAddr = (!empty($storedOptions['reply_to_addr'])) ? $storedOptions['reply_to_addr'] : $fromAddress;
2771 $defaults = $current_user->getPreferredEmail();
2772 $fromAddress = (!empty($fromAddress)) ? $fromAddress : $defaults['email'];
2773 $fromName = (!empty($fromName)) ? $fromName : $defaults['name'];
2774 $to[0]['email'] = $contactAddr;
2776 // handle to name: address, prefer reply-to
2777 if(!empty($email->reply_to_name)) {
2778 $to[0]['display'] = $email->reply_to_name;
2779 } elseif(!empty($email->from_name)) {
2780 $to[0]['display'] = $email->from_name;
2783 $et = new EmailTemplate();
2784 $et->retrieve($createCaseTemplateId);
2785 if(empty($et->subject)) { $et->subject = ''; }
2786 if(empty($et->body)) { $et->body = ''; }
2787 if(empty($et->body_html)) { $et->body_html = ''; }
2789 $et->subject = "Re:" . " " . str_replace('%1', $c->case_number, $c->getEmailSubjectMacro() . " ". $c->name);
2791 $html = trim($email->description_html);
2792 $plain = trim($email->description);
2794 $email->email2init();
2795 $email->from_addr = $email->from_addr_name;
2796 $email->to_addrs = $email->to_addrs_names;
2797 $email->cc_addrs = $email->cc_addrs_names;
2798 $email->bcc_addrs = $email->bcc_addrs_names;
2799 $email->from_name = $email->from_addr;
2801 $email = $email->et->handleReplyType($email, "reply");
2802 $ret = $email->et->displayComposeEmail($email);
2803 $ret['description'] = empty($email->description_html) ? str_replace("\n", "\n<BR/>", $email->description) : $email->description_html;
2805 $reply = new Email();
2806 $reply->type = 'out';
2807 $reply->to_addrs = $to[0]['email'];
2808 $reply->to_addrs_arr = $to;
2809 $reply->cc_addrs_arr = array();
2810 $reply->bcc_addrs_arr = array();
2811 $reply->from_name = $fromName;
2812 $reply->from_addr = $fromAddress;
2813 $reply->reply_to_name = $replyToName;
2814 $reply->reply_to_addr = $replyToAddr;
2815 $reply->name = $et->subject;
2816 $reply->description = $et->body . "<div><hr /></div>" . $email->description;
2817 if (!$et->text_only) {
2818 $reply->description_html = $et->body_html . "<div><hr /></div>" . $email->description;
2820 $GLOBALS['log']->debug('saving and sending auto-reply email');
2821 //$reply->save(); // don't save the actual email.
2826 if(!empty($email->reply_to_email)) {
2827 $contactAddr = $email->reply_to_email;
2829 $contactAddr = $email->from_addr;
2831 $this->handleAutoresponse($email, $contactAddr);
2837 * handles linking contacts, accounts, etc. to an email
2839 * @param object Email bean to be linked against
2840 * @return string contactAddr is the email address of the sender
2842 function handleLinking(&$email) {
2843 // link email to an User if emails match TO addr
2844 if($userIds = $this->getRelatedId($email->to_addrs, 'users')) {
2845 $GLOBALS['log']->debug('I-E linking email to User');
2846 // link the user to the email
2847 $email->load_relationship('users');
2848 $email->users->add($userIds);
2851 // link email to a Contact, Lead, or Account if the emails match
2852 // give precedence to REPLY-TO above FROM
2853 if(!empty($email->reply_to_email)) {
2854 $contactAddr = $email->reply_to_email;
2856 $contactAddr = $email->from_addr;
2859 // Samir Gandhi : 12/06/07
2860 // This changes has been done because the linking was done only with the from address and
2861 // not with to address
2862 $relationShipAddress = $contactAddr;
2863 if (empty($relationShipAddress)) {
2864 $relationShipAddress .= $email->to_addrs;
2866 $relationShipAddress = $relationShipAddress . "," . $email->to_addrs;
2868 if($leadIds = $this->getRelatedId($relationShipAddress, 'leads')) {
2869 $GLOBALS['log']->debug('I-E linking email to Lead');
2870 $email->load_relationship('leads');
2871 $email->leads->add($leadIds);
2873 foreach($leadIds as $leadId) {
2875 $lead->retrieve($leadId);
2876 $lead->load_relationship('emails');
2877 $lead->emails->add($email->id);
2881 if($contactIds = $this->getRelatedId($relationShipAddress, 'contacts')) {
2882 $GLOBALS['log']->debug('I-E linking email to Contact');
2883 // link the contact to the email
2884 $email->load_relationship('contacts');
2885 $email->contacts->add($contactIds);
2888 if($accountIds = $this->getRelatedId($relationShipAddress, 'accounts')) {
2889 $GLOBALS['log']->debug('I-E linking email to Account');
2890 // link the account to the email
2891 $email->load_relationship('accounts');
2892 $email->accounts->add($accountIds);
2894 /* cn: bug 9171 another cause of dying I-E - bad linking
2895 foreach($accountIds as $accountId) {
2896 $GLOBALS['log']->debug('I-E reverse-linking Accounts to Emails');
2897 $acct = new Account();
2898 $acct->retrieve($accountId);
2899 $acct->load_relationship('emails');
2900 $acct->account_emails->add($email->id);
2904 return $contactAddr;
2908 * Gets part by following breadcrumb path
2909 * @param string $bc the breadcrumb string in format (1.1.1)
2910 * @param array parts the root level parts array
2912 protected function getPartByPath($bc, $parts)
2914 if(strstr($bc,'.')) {
2915 $exBc = explode('.', $bc);
2920 foreach($exBc as $step) {
2921 if(empty($parts)) return false;
2922 $res = $parts[$step-1]; // MIME starts with 1, array starts with 0
2923 if(!empty($res->parts)) {
2924 $parts = $res->parts;
2933 * takes a breadcrumb and returns the encoding at that level
2934 * @param string bc the breadcrumb string in format (1.1.1)
2935 * @param array parts the root level parts array
2936 * @return int retInt Int key to transfer encoding (see handleTranserEncoding())
2938 function getEncodingFromBreadCrumb($bc, $parts) {
2939 if(strstr($bc,'.')) {
2940 $exBc = explode('.', $bc);
2945 $depth = count($exBc);
2947 for($i=0; $i<$depth; $i++) {
2948 $tempObj[$i] = $parts[($exBc[$i]-1)];
2949 $retInt = imap_utf8($tempObj[$i]->encoding);
2950 if(!empty($tempObj[$i]->parts)) {
2951 $parts = $tempObj[$i]->parts;
2958 * retrieves the charset for a given part of an email body
2960 * @param string bc target part of the message in format (1.1.1)
2961 * @param array parts 1 level above ROOT array of Objects representing a multipart body
2962 * @return string charset name
2964 function getCharsetFromBreadCrumb($bc, $parts)
2966 $tempObj = $this->getPartByPath($bc, $parts);
2967 // now we have the tempObj at the end of the breadCrumb trail
2969 if(!empty($tempObj->ifparameters)) {
2970 foreach($tempObj->parameters as $param) {
2971 if(strtolower($param->attribute) == 'charset') {
2972 return $param->value;
2981 * Get the message text from a single mime section, html or plain.
2983 * @param string $msgNo
2984 * @param string $section
2985 * @param stdObject $structure
2988 function getMessageTextFromSingleMimePart($msgNo,$section,$structure)
2990 $msgPartTmp = imap_fetchbody($this->conn, $msgNo, $section);
2991 $enc = $this->getEncodingFromBreadCrumb($section, $structure->parts);
2992 $charset = $this->getCharsetFromBreadCrumb($section, $structure->parts);
2993 $msgPartTmp = $this->handleTranserEncoding($msgPartTmp, $enc);
2994 return $this->handleCharsetTranslation($msgPartTmp, $charset);
2998 * Givin an existing breadcrumb add a cooresponding offset
3001 * @param string $offset
3004 function addBreadCrumbOffset($bc, $offset)
3006 if( (empty($bc) || is_null($bc)) && !empty($offset) )
3009 $a_bc = explode(".", $bc);
3010 $a_offset = explode(".",$offset);
3011 if(count($a_bc) < count($a_offset))
3012 $a_bc = array_merge($a_bc,array_fill( count($a_bc), count($a_offset) - count($a_bc), 0));
3015 for($i=0;$i < count($a_bc); $i++)
3017 if(isset($a_offset[$i]))
3018 $results[] = $a_bc[$i] + $a_offset[$i];
3020 $results[] = $a_bc[$i];
3022 return implode(".", $results);
3026 * returns the HTML text part of a multi-part message
3028 * @param int msgNo the relative message number for the monitored mailbox
3029 * @param string $type the type of text processed, either 'PLAIN' or 'HTML'
3030 * @return string UTF-8 encoded version of the requested message text
3032 function getMessageText($msgNo, $type, $structure, $fullHeader,$clean_email=true, $bcOffset = "") {
3033 global $sugar_config;
3036 $bc = $this->buildBreadCrumbs($structure->parts, $type);
3037 //Add an offset if specified
3038 if(!empty($bcOffset))
3039 $bc = $this->addBreadCrumbOffset($bc, $bcOffset);
3041 if(!empty($bc)) { // multi-part
3042 // HUGE difference between PLAIN and HTML
3043 if($type == 'PLAIN') {
3044 $msgPart = $this->getMessageTextFromSingleMimePart($msgNo,$bc,$structure);
3046 // get part of structure that will
3048 $bcArray = $this->buildBreadCrumbsHTML($structure->parts,$bcOffset);
3049 // construct inline HTML/Rich msg
3050 foreach($bcArray as $bcArryKey => $bcArr) {
3051 foreach($bcArr as $type => $bcTrail) {
3053 $msgPartRaw .= $this->getMessageTextFromSingleMimePart($msgNo,$bcTrail,$structure);
3055 // deal with inline image
3056 $part = $this->getPartByPath($bcTrail, $structure->parts);
3057 if(empty($part) || empty($part->id)) continue;
3058 $partid = substr($part->id, 1, -1); // strip <> around
3059 if(isset($this->inlineImages[$partid])) {
3060 $imageName = $this->inlineImages[$partid];
3061 $newImagePath = "class=\"image\" src=\"{$this->imagePrefix}{$imageName}\"";
3062 $preImagePath = "src=\"cid:$partid\"";
3063 $msgPartRaw = str_replace($preImagePath, $newImagePath, $msgPartRaw);
3068 $msgPart = $msgPartRaw;
3070 } else { // either PLAIN message type (flowed) or b0rk3d RFC
3071 // make sure we're working on valid data here.
3072 if($structure->subtype != $type) {
3076 $decodedHeader = $this->decodeHeader($fullHeader);
3078 // now get actual body contents
3079 $text = imap_body($this->conn, $msgNo);
3081 $upperCaseKeyDecodeHeader = array();
3082 if (is_array($decodedHeader)) {
3083 $upperCaseKeyDecodeHeader = array_change_key_case($decodedHeader, CASE_UPPER);
3085 if(isset($upperCaseKeyDecodeHeader[strtoupper('Content-Transfer-Encoding')])) {
3086 $flip = array_flip($this->transferEncoding);
3087 $text = $this->handleTranserEncoding($text, $flip[strtoupper($upperCaseKeyDecodeHeader[strtoupper('Content-Transfer-Encoding')])]);
3091 if(isset($upperCaseKeyDecodeHeader[strtoupper('Content-Type')]['charset']) && !empty($upperCaseKeyDecodeHeader[strtoupper('Content-Type')]['charset'])) {
3092 $msgPart = $this->handleCharsetTranslation($text, $upperCaseKeyDecodeHeader[strtoupper('Content-Type')]['charset']);
3094 } // end else clause
3096 $msgPart = $this->customGetMessageText($msgPart);
3097 /* cn: bug 9176 - htmlEntitites hide XSS attacks.
3098 * decode to pass refreshed HTML to HTML_Safe */
3099 if ($type == 'PLAIN')
3100 return $this->cleanXssContent(to_html($msgPart));
3103 $safedMsgPart = $this->cleanContent($msgPart);
3104 return str_replace("<img />", '', $safedMsgPart); /*SKIP_IMAGE_TAG*/
3109 * decodes raw header information and passes back an associative array with
3110 * the important elements key'd by name
3111 * @param header string the raw header
3112 * @return decodedHeader array the associative array
3114 function decodeHeader($fullHeader) {
3115 $decodedHeader = array();
3116 $exHeaders = explode("\r", $fullHeader);
3117 if (!is_array($exHeaders)) {
3118 $exHeaders = explode("\r\n", $fullHeader);
3120 $quotes = array('"', "'");
3122 foreach($exHeaders as $lineNum => $head) {
3124 $key = trim(substr($head, 0, strpos($head, ':')));
3126 $value = trim(substr($head, (strpos($head, ':') + 1), strlen($head)));
3128 // handle content-type section in headers
3129 if(strtolower($key) == 'content-type' && strpos($value, ';')) { // ";" means something follows related to (such as Charset)
3130 $semiColPos = mb_strpos($value, ';');
3131 $strLenVal = mb_strlen($value);
3132 if(($semiColPos + 4) >= $strLenVal) {
3133 // the charset="[something]" is on the next line
3134 $value .= str_replace($quotes, "", trim($exHeaders[$lineNum+1]));
3137 $newValue = array();
3138 $exValue = explode(';', $value);
3139 $newValue['type'] = $exValue[0];
3141 for($i=1; $i<count($exValue); $i++) {
3142 $exContent = explode('=', $exValue[$i]);
3143 $newValue[trim($exContent[0])] = trim($exContent[1]);
3148 if(!empty($key) && !empty($value)) {
3149 $decodedHeader[$key] = $value;
3153 return $decodedHeader;
3157 * handles translating message text from orignal encoding into UTF-8
3159 * @param string text test to be re-encoded
3160 * @param string charset original character set
3161 * @return string utf8 re-encoded text
3163 function handleCharsetTranslation($text, $charset) {
3166 if(empty($charset)) {
3167 $GLOBALS['log']->debug("***ERROR: InboundEmail::handleCharsetTranslation() called without a \$charset!");
3168 $GLOBALS['log']->debug("***STACKTRACE: ".print_r(debug_backtrace(), true));
3172 // typical headers have no charset - let destination pick (since it's all ASCII anyways)
3173 if(strtolower($charset) == 'default' || strtolower($charset) == 'utf-8') {
3177 return $locale->translateCharset($text, $charset);
3183 * Builds up the "breadcrumb" trail that imap_fetchbody() uses to return
3184 * parts of an email message, including attachments and inline images
3185 * @param $parts array of objects
3186 * @param $subtype what type of trail to return? HTML? Plain? binaries?
3187 * @param $breadcrumb text trail to build up
3189 function buildBreadCrumbs($parts, $subtype, $breadcrumb = '0') {
3190 //_pp('buildBreadCrumbs building for '.$subtype.' with BC at '.$breadcrumb);
3191 // loop through available parts in the array
3192 foreach($parts as $k => $part) {
3193 // mark passage through level
3195 // if this is not the first time through, start building the map
3196 if($breadcrumb != 0) {
3197 $thisBc = $breadcrumb.'.'.$thisBc;
3200 // found a multi-part/mixed 'part' - keep digging
3201 if($part->type == 1 && (strtoupper($part->subtype) == 'RELATED' || strtoupper($part->subtype) == 'ALTERNATIVE' || strtoupper($part->subtype) == 'MIXED')) {
3202 //_pp('in loop: going deeper with subtype: '.$part->subtype.' $k is: '.$k);
3203 $thisBc = $this->buildBreadCrumbs($part->parts, $subtype, $thisBc);
3206 } elseif(strtolower($part->subtype) == strtolower($subtype)) { // found the subtype we want, return the breadcrumb value
3207 //_pp('found '.$subtype.' bc! returning: '.$thisBc);
3210 //_pp('found '.$part->subtype.' instead');
3216 * Similar to buildBreadCrumbs() but returns an ordered array containing all parts of the message that would be
3217 * considered "HTML" or Richtext (embedded images, formatting, etc.).
3218 * @param array parts Array of parts of a message
3219 * @param int breadcrumb Passed integer value to start breadcrumb trail
3220 * @param array stackedBreadcrumbs Persistent trail of breadcrumbs
3221 * @return array Ordered array of parts to retrieve via imap_fetchbody()
3223 function buildBreadCrumbsHTML($parts, $breadcrumb = '0', $stackedBreadcrumbs = array()) {
3225 $disposition = 'inline';
3227 foreach($parts as $k => $part) {
3228 // mark passage through level
3231 if($breadcrumb != 0) {
3232 $thisBc = $breadcrumb.'.'.$thisBc;
3234 // found a multi-part/mixed 'part' - keep digging
3235 if($part->type == 1 && (strtoupper($part->subtype) == 'RELATED' || strtoupper($part->subtype) == 'ALTERNATIVE' || strtoupper($part->subtype) == 'MIXED')) {
3236 $stackedBreadcrumbs = $this->buildBreadCrumbsHTML($part->parts, $thisBc, $stackedBreadcrumbs);
3238 (strtolower($part->subtype) == strtolower($subtype)) ||
3240 isset($part->disposition) && strtolower($part->disposition) == 'inline' &&
3241 in_array(strtoupper($part->subtype), $this->imageTypes)
3244 // found the subtype we want, return the breadcrumb value
3245 $stackedBreadcrumbs[] = array(strtolower($part->subtype) => $thisBc);
3246 } elseif($part->type == 5) {
3247 $stackedBreadcrumbs[] = array(strtolower($part->subtype) => $thisBc);
3251 return $stackedBreadcrumbs;
3255 * Takes a PHP imap_* object's to/from/cc/bcc address field and converts it
3256 * to a standard string that SugarCRM expects
3257 * @param $arr an array of email address objects
3259 function convertImapToSugarEmailAddress($arr) {
3260 if(is_array($arr)) {
3262 foreach($arr as $key => $obj) {
3263 $addr .= $obj->mailbox.'@'.$obj->host.', ';
3266 $ret = substr_replace($addr,'',-2,-1);
3272 * tries to figure out what character set a given filename is using and
3273 * decode based on that
3275 * @param string name Name of attachment
3276 * @return string decoded name
3278 function handleEncodedFilename($name) {
3279 $imapDecode = imap_mime_header_decode($name);
3280 /******************************
3281 $imapDecode => stdClass Object
3284 [text] => w�hlen.php
3289 $imapDecode => stdClass Object
3291 [charset] => default
3292 [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
3294 *******************************/
3295 if($imapDecode[0]->charset != 'default') { // mime-header encoded charset
3296 $encoding = $imapDecode[0]->charset;
3297 $name = $imapDecode[0]->text; // encoded in that charset
3299 /* encoded filenames are formatted as [encoding]''[filename] */
3300 if(strpos($name, "''") !== false) {
3302 $encoding = substr($name, 0, strpos($name, "'"));
3304 while(strpos($name, "'") !== false) {
3305 $name = trim(substr($name, (strpos($name, "'")+1), strlen($name)));
3308 $name = urldecode($name);
3310 return (strtolower($encoding) == 'utf-8') ? $name : $GLOBALS['locale']->translateCharset($name, $encoding, 'UTF-8');
3314 Primary body types for a part of a mail structure (imap_fetchstructure returned object)
3326 Primary body types for a part of a mail structure (imap_fetchstructure returned object)
3327 @var array $imap_types
3329 public $imap_types = array(
3339 public function getMimeType($type, $subtype)
3341 if(isset($this->imap_types[$type])) {
3342 return $this->imap_types[$type]."/$subtype";
3344 return "other/$subtype";
3349 * Takes the "parts" attribute of the object that imap_fetchbody() method
3350 * returns, and recursively goes through looking for objects that have a
3351 * disposition of "attachement" or "inline"
3352 * @param int $msgNo The relative message number for the monitored mailbox
3353 * @param object $parts Array of objects to examine
3354 * @param string $emailId The GUID of the email saved prior to calling this method
3355 * @param array $breadcrumb Default 0, build up of the parts mapping
3356 * @param bool $forDisplay Default false
3358 function saveAttachments($msgNo, $parts, $emailId, $breadcrumb='0', $forDisplay) {
3359 global $sugar_config;
3361 Primary body types for a part of a mail structure (imap_fetchstructure returned object)
3372 foreach($parts as $k => $part) {
3374 if($breadcrumb != '0') {
3375 $thisBc = $breadcrumb.'.'.$thisBc;
3378 // check if we need to recurse into the object
3379 //if($part->type == 1 && !empty($part->parts)) {
3380 if(isset($part->parts) && !empty($part->parts) && !( isset($part->subtype) && strtolower($part->subtype) == 'rfc822') ) {
3381 $this->saveAttachments($msgNo, $part->parts, $emailId, $thisBc, $forDisplay);
3383 } elseif($part->ifdisposition) {
3384 // we will take either 'attachments' or 'inline'
3385 if(strtolower($part->disposition) == 'attachment' || ((strtolower($part->disposition) == 'inline') && $part->type != 0)) {
3386 $attach = $this->getNoteBeanForAttachment($emailId);
3387 $fname = $this->handleEncodedFilename($this->retrieveAttachmentNameFromStructure($part->dparameters));
3389 if(!empty($fname)) {//assign name to attachment
3390 $attach->name = $fname;
3391 } else {//if name is empty, default to filename
3392 $attach->name = urlencode($this->retrieveAttachmentNameFromStructure($part->dparameters));
3394 $attach->filename = $attach->name;
3395 if (empty($attach->filename)) {
3399 // deal with the MIME types email has
3400 $attach->file_mime_type = $this->getMimeType($part->type, $part->subtype);
3401 $attach->safeAttachmentName();
3403 $attach->id = $this->getTempFilename();
3405 // only save if doing a full import, else we want only the binaries
3408 } // end if disposition type 'attachment'
3409 }// end ifdisposition
3410 //Retrieve contents of subtype rfc8822
3411 elseif ($part->type == 2 && isset($part->subtype) && strtolower($part->subtype) == 'rfc822' )
3413 $tmp_eml = imap_fetchbody($this->conn, $msgNo, $thisBc);
3414 $attach = $this->getNoteBeanForAttachment($emailId);
3415 $attach->file_mime_type = 'messsage/rfc822';
3416 $attach->description = $tmp_eml;
3417 $attach->filename = 'bounce.eml';
3418 $attach->safeAttachmentName();
3420 $attach->id = $this->getTempFilename();
3422 // only save if doing a full import, else we want only the binaries
3425 } elseif(!$part->ifdisposition && $part->type != 1 && $part->type != 2 && $thisBc != '1') {
3426 // No disposition here, but some IMAP servers lie about disposition headers, try to find the truth
3427 // Also Outlook puts inline attachments as type 5 (image) without a disposition
3428 if($part->ifparameters) {
3429 foreach($part->parameters as $param) {
3430 if(strtolower($param->attribute) == "name" || strtolower($param->attribute) == "filename") {
3431 $fname = $this->handleEncodedFilename($param->value);
3435 if(empty($fname)) continue;
3437 // we assume that named parts are attachments too
3438 $attach = $this->getNoteBeanForAttachment($emailId);
3440 $attach->filename = $attach->name = $fname;
3441 $attach->file_mime_type = $this->getMimeType($part->type, $part->subtype);
3443 $attach->safeAttachmentName();
3445 $attach->id = $this->getTempFilename();
3447 // only save if doing a full import, else we want only the binaries
3452 $this->saveAttachmentBinaries($attach, $msgNo, $thisBc, $part, $forDisplay);
3457 * Return a new note object for attachments.
3459 * @param string $emailId
3462 function getNoteBeanForAttachment($emailId)
3464 $attach = new Note();
3465 $attach->parent_id = $emailId;
3466 $attach->parent_type = 'Emails';
3472 * Return the filename of the attachment by examining the dparameters returned from imap_fetch_structure which
3473 * represet the content-disposition of the MIME header.
3475 * @param array $dparamaters
3478 function retrieveAttachmentNameFromStructure($dparamaters)
3482 foreach ($dparamaters as $k => $v)
3484 if( strtolower($v->attribute) == 'filename')
3486 $result = $v->value;
3495 * saves the actual binary file of a given attachment
3496 * @param object attach Note object that is attached to the binary file
3497 * @param string msgNo Message Number on IMAP/POP3 server
3498 * @param string thisBc Breadcrumb to navigate email structure to find the content
3499 * @param object part IMAP standard object that contains the "parts" of this section of email
3500 * @param bool $forDisplay
3502 function saveAttachmentBinaries($attach, $msgNo, $thisBc, $part, $forDisplay) {
3503 // decide where to place the file temporarily
3504 $uploadDir = ($forDisplay) ? "{$this->EmailCachePath}/{$this->id}/attachments/" : "upload://";
3506 // decide what name to save file as
3507 $fileName = $attach->id;
3509 // download the attachment if we didn't do it yet
3510 if(!file_exists($uploadDir.$fileName)) {
3511 $msgPartRaw = imap_fetchbody($this->conn, $msgNo, $thisBc);
3512 // deal with attachment encoding and decode the text string
3513 $msgPart = $this->handleTranserEncoding($msgPartRaw, $part->encoding);
3515 if(file_put_contents($uploadDir.$fileName, $msgPart)) {
3516 $GLOBALS['log']->debug('InboundEmail saved attachment file: '.$attach->filename);
3518 $GLOBALS['log']->debug('InboundEmail could not create attachment file: '.$attach->filename ." - temp file target: [ {$uploadDir}{$fileName} ]");
3523 $this->tempAttachment[$fileName] = urldecode($attach->filename);
3524 // if all was successful, feel for inline and cache Note ID for display:
3525 if((strtolower($part->disposition) == 'inline' && in_array($part->subtype, $this->imageTypes))
3526 || ($part->type == 5)) {
3527 if(copy($uploadDir.$fileName, sugar_cached("images/{$fileName}.").strtolower($part->subtype))) {
3528 $id = substr($part->id, 1, -1); //strip <> around
3529 $this->inlineImages[$id] = $attach->id.".".strtolower($part->subtype);
3531 $GLOBALS['log']->debug('InboundEmail could not copy '.$uploadDir.$fileName.' to cache');
3537 * decodes a string based on its associated encoding
3538 * if nothing is passed, we default to no-encoding type
3539 * @param $str encoded string
3540 * @param $enc detected encoding
3542 function handleTranserEncoding($str, $enc=0) {
3548 $ret = base64_decode($str);
3550 case 4:// QUOTED-PRINTABLE
3551 $ret = quoted_printable_decode($str);
3553 case 0:// 7BIT or 8BIT
3554 case 1:// already in a string-useable format - do nothing
3556 default:// catch all
3566 * Some emails do not get assigned a message_id, specifically from
3569 * We need to derive a reliable one for duplicate import checking.
3571 function getMessageId($header) {
3572 $message_id = md5(print_r($header, true));
3577 * checks for duplicate emails on polling. The uniqueness of a given email message is determined by a concatenation
3578 * of 2 values, the messageID and the delivered-to field. This allows multiple To: and B/CC: destination addresses
3579 * to be imported by Sugar without violating the true duplicate-email issues.
3581 * @param string message_id message ID generated by sending server
3582 * @param int message number (mailserver's key) of email
3583 * @param object header object generated by imap_headerinfo()
3584 * @param string textHeader Headers in normal text format
3587 function importDupeCheck($message_id, $header, $textHeader) {
3588 $GLOBALS['log']->debug('*********** InboundEmail doing dupe check.');
3590 // generate "delivered-to" seed for email duplicate check
3591 $deliveredTo = $this->id; // cn: bug 12236 - cc's failing dupe check
3592 $exHeader = explode("\n", $textHeader);
3594 foreach($exHeader as $headerLine) {
3595 if(strpos(strtolower($headerLine), 'delivered-to:') !== false) {
3596 $deliveredTo = substr($headerLine, strpos($headerLine, " "), strlen($headerLine));
3597 $GLOBALS['log']->debug('********* InboundEmail found [ '.$deliveredTo.' ] as the destination address for email [ '.$message_id.' ]');
3598 } elseif(strpos(strtolower($headerLine), 'x-real-to:') !== false) {
3599 $deliveredTo = substr($headerLine, strpos($headerLine, " "), strlen($headerLine));
3600 $GLOBALS['log']->debug('********* InboundEmail found [ '.$deliveredTo.' ] for non-standards compliant email x-header [ '.$message_id.' ]');
3604 //if(empty($message_id) && !isset($message_id)) {
3605 if(empty($message_id) || !isset($message_id)) {
3606 $GLOBALS['log']->debug('*********** NO MESSAGE_ID.');
3607 $message_id = $this->getMessageId($header);
3610 // generate compound messageId
3611 $this->compoundMessageId = trim($message_id).trim($deliveredTo);
3612 // if the length > 255 then md5 it so that the data will be of smaller length
3613 if (strlen($this->compoundMessageId) > 255) {
3614 $this->compoundMessageId = md5($this->compoundMessageId);
3617 if (empty($this->compoundMessageId)) {
3618 $GLOBALS['log']->error('Inbound Email found a message without a header and message_id');
3622 $potentials = clean_xss($this->compoundMessageId, false);
3624 if(is_array($potentials) && !empty($potentials)) {
3625 foreach($potentials as $bad) {
3626 $this->compoundMessageId = str_replace($bad, "", $this->compoundMessageId);
3630 $query = 'SELECT count(emails.id) AS c FROM emails WHERE emails.message_id = \''.$this->compoundMessageId.'\' and emails.deleted = 0';
3631 $r = $this->db->query($query, true);
3632 $a = $this->db->fetchByAssoc($r);
3635 $GLOBALS['log']->debug('InboundEmail found a duplicate email with ID ('.$this->compoundMessageId.')');
3636 return false; // we have a dupe and don't want to import the email'
3643 * takes the output from imap_mime_hader_decode() and handles multiple types of encoding
3644 * @param string subject Raw subject string from email
3645 * @return string ret properly formatted UTF-8 string
3647 function handleMimeHeaderDecode($subject) {
3648 $subjectDecoded = imap_mime_header_decode($subject);
3651 foreach($subjectDecoded as $object) {
3652 if($object->charset != 'default') {
3653 $ret .= $this->handleCharsetTranslation($object->text, $object->charset);
3655 $ret .= $object->text;
3662 * URL cleanup function
3663 * Until we have comprehensive CSRF protection, we need to sanitize URLs in emails
3664 * to avoid CSRF attacks
3666 public function urlCleaner($attr, $value)
3669 if(strtolower($attr) == "href") return true;
3670 $items = parse_url($value);
3671 if(empty($items)) return false;
3672 if(!empty($items['scheme']) && strtolower($items['scheme']) != 'http' && strtolower($items['scheme']) != 'https') {
3673 // do not touch non-HTTP URLs
3676 // don't allow relative URLs
3677 if(empty($items['host'])) return false;
3678 // allow URLs with no query
3679 if(empty($items['query'])) return true;
3680 // allow URLs that don't start with /? or /index.php?
3681 if(!empty($items['path']) && $items['path'] != '/' && strtolower(substr($items['path'], -10)) != '/index.php') {
3684 // now we have blah-blah/index.php?query - let's see if query looks dangerous
3685 $query_items = array();
3686 parse_str(from_html($items['query']), $query_items);
3687 // weird query, probably harmless
3688 if(empty($query_items)) return true;
3689 // suspiciously like SugarCRM query, reject
3690 if(!empty($query_items['module']) && !empty($query_items['action'])) return false;
3691 // looks like non-download entry point - allow only specific entry points
3692 if(!empty($query_items['entryPoint']) && !in_array($query_items['entryPoint'], array('download', 'image', 'getImage'))) {
3700 * Cleans content for XSS and other types of attack vectors
3701 * @param string str String to clean
3704 function cleanContent($str) {
3706 $this->safe->clear();
3707 $this->safe->setUrlCallback(array($this, "urlCleaner"));
3708 $str = $this->safe->parse($str);
3709 return $this->cleanXssContent($str);
3713 * Cleans content for XSS
3714 * @param string str String to clean
3717 function cleanXssContent($str) {
3719 $potentials = clean_xss($str, false);
3720 if(is_array($potentials) && !empty($potentials)) {
3721 foreach($potentials as $bad) {
3722 $str = str_replace($bad, "", $str);
3728 * Calculates the appropriate display date/time sent for an email.
3729 * @param string headerDate The date sent of email in MIME header format
3730 * @return string GMT-0 Unix timestamp
3732 function getUnixHeaderDate($headerDate) {
3735 if (empty($headerDate)) {
3738 ///////////////////////////////////////////////////////////////////
3739 //// CALCULATE CORRECT SENT DATE/TIME FOR EMAIL
3740 if(!empty($headerDate)) {
3741 // Bug 25254 - Strip trailing space that come in some header dates (maybe ones with 1-digit day number)
3742 $headerDate = trim($headerDate);
3743 // need to hack PHP/windows' bad handling of strings when using POP3
3744 if(strstr($headerDate,'+0000 GMT')) {
3745 $headerDate = str_replace('GMT','', $headerDate);
3746 } elseif(!strtotime($headerDate)) {
3747 $headerDate = 'now'; // catch non-standard format times.
3749 // cn: bug 9196 parse the GMT offset
3750 if(strpos($headerDate, '-') || strpos($headerDate, '+')) {
3751 // cn: bug make sure last 5 chars are [+|-]nnnn
3752 if(strpos($headerDate, "(")) {
3753 $headerDate = preg_replace('/\([\w]+\)/i', "", $headerDate);
3754 $headerDate = trim($headerDate);
3757 // parse mailserver time
3758 $gmtEmail = trim(substr($headerDate, -5, 5));
3759 $posNeg = substr($gmtEmail, 0, 1);
3760 $gmtHours = substr($gmtEmail, 1, 2);
3761 $gmtMins = substr($gmtEmail, -2, 2);
3764 $secsHours = $gmtHours * 60 * 60;
3765 $secsTotal = $secsHours + ($gmtMins * 60);
3766 $secsTotal = ($posNeg == '-') ? $secsTotal : -1 * $secsTotal;
3768 $headerDate = trim(substr_replace($headerDate, '', -5)); // mfh: bug 10961/12855 - date time values with GMT offsets not properly formatted
3772 $headerDate = 'now';
3775 $unixHeaderDate = strtotime($headerDate);
3777 if(isset($secsTotal)) {
3778 // this gets the timestamp to true GMT-0
3779 $unixHeaderDate += $secsTotal;
3782 if(strtotime('Jan 1, 2001') > $unixHeaderDate) {
3783 $unixHeaderDate = strtotime('now');
3786 return $unixHeaderDate;
3787 //// END CALCULATE CORRECT SENT DATE/TIME FOR EMAIL
3788 ///////////////////////////////////////////////////////////////////
3792 * This method returns the correct messageno for the pop3 protocol
3793 * @param String UIDL
3794 * @return returnMsgNo
3796 function getCorrectMessageNoForPop3($messageId) {
3798 if ($this->protocol == 'pop3') {
3799 if($this->pop3_open()) {
3800 // get the UIDL from database;
3801 $query = "SELECT msgno FROM email_cache WHERE ie_id = '{$this->id}' AND message_id = '{$messageId}'";
3802 $r = $this->db->query($query);
3803 $a = $this->db->fetchByAssoc($r);
3804 $msgNo = $a['msgno'];
3805 $returnMsgNo = $msgNo;
3808 $this->pop3_sendCommand("USER", $this->email_user);
3809 $this->pop3_sendCommand("PASS", $this->email_password);
3811 // get UIDL for this msgNo
3812 $this->pop3_sendCommand("UIDL {$msgNo}", '', false); // leave socket buffer alone until the while()
3813 $buf = fgets($this->pop3socket, 1024); // handle "OK+ msgNo UIDL(UIDL for this messageno)";
3815 // if it returns OK then we have found the message else get all the UIDL
3816 // and search for the correct msgNo;
3817 $foundMessageNo = false;
3818 if (preg_match("/OK/", $buf) > 0) {
3819 $mailserverResponse = explode(" ", $buf);
3820 // if the cachedUIDL and the UIDL from mail server matches then its the correct messageno
3821 if (trim($mailserverResponse[sizeof($mailserverResponse) - 1]) == $messageId) {
3822 $foundMessageNo = true;
3826 //get all the UIDL and then find the correct messageno
3827 if (!$foundMessageNo) {
3829 $this->pop3_sendCommand("UIDL", '', false); // leave socket buffer alone until the while()
3830 fgets($this->pop3socket, 1024); // handle "OK+";
3833 if(is_resource($this->pop3socket)) {
3834 while(!feof($this->pop3socket)) {
3835 $buf = fgets($this->pop3socket, 1024); // 8kb max buffer - shouldn't be more than 80 chars via pop3...
3836 if(trim($buf) == '.') {
3837 $GLOBALS['log']->debug("*** GOT '.'");
3840 // format is [msgNo] [UIDL]
3841 $exUidl = explode(" ", $buf);
3842 $UIDLs[trim($exUidl[1])] = trim($exUidl[0]);
3844 if (array_key_exists($messageId, $UIDLs)) {
3845 $returnMsgNo = $UIDLs[$messageId];
3847 // message could not be found on server
3853 $this->pop3_cleanUp();
3856 return $returnMsgNo;
3860 * If the importOneEmail returns false, then findout if the duplicate email
3862 function getDuplicateEmailId($msgNo, $uid) {
3864 global $app_strings;
3865 global $app_list_strings;
3866 global $sugar_config;
3867 global $current_user;
3869 $header = imap_headerinfo($this->conn, $msgNo);
3870 $fullHeader = imap_fetchheader($this->conn, $msgNo); // raw headers
3872 // reset inline images cache
3873 $this->inlineImages = array();
3875 // handle messages deleted on server
3876 if(empty($header)) {
3877 if(!isset($this->email) || empty($this->email)) {
3878 $this->email = new Email();
3882 $dupeCheckResult = $this->importDupeCheck($header->message_id, $header, $fullHeader);
3883 if (!$dupeCheckResult && !empty($this->compoundMessageId)) {
3884 // we have a duplicate email
3885 $query = 'SELECT id FROM emails WHERE emails.message_id = \''.$this->compoundMessageId.'\' and emails.deleted = 0';
3886 $r = $this->db->query($query, true);
3887 $a = $this->db->fetchByAssoc($r);
3889 $this->email = new Email();
3890 $this->email->id = $a['id'];
3899 * shiny new importOneEmail() method
3901 * @param bool forDisplay
3902 * @param clean_email boolean, default true,
3904 function importOneEmail($msgNo, $uid, $forDisplay=false, $clean_email=true) {
3905 $GLOBALS['log']->debug("InboundEmail processing 1 email {$msgNo}-----------------------------------------------------------------------------------------");
3907 global $app_strings;
3908 global $app_list_strings;
3909 global $sugar_config;
3910 global $current_user;
3913 // So, on older versions of PHP (PHP VERSION < 5.3),
3914 // calling imap_headerinfo and imap_fetchheader can cause a buffer overflow for exteremly large headers,
3915 // This leads to the remaining messages not being read because Sugar crashes everytime it tries to read the headers.
3916 // The workaround is to mark a message as read before making trying to read the header of the msg in question
3917 // This forces this message not be read again, and we can continue processing remaining msgs.
3919 // UNCOMMENT THIS IF YOU HAVE THIS PROBLEM! See notes on Bug # 45477
3920 // $this->markEmails($uid, "read");
3922 $header = imap_headerinfo($this->conn, $msgNo);
3923 $fullHeader = imap_fetchheader($this->conn, $msgNo); // raw headers
3925 // reset inline images cache
3926 $this->inlineImages = array();
3928 // handle messages deleted on server
3929 if(empty($header)) {
3930 if(!isset($this->email) || empty($this->email)) {
3931 $this->email = new Email();
3935 if ($this->isPop3Protocol()) {
3936 $this->email->name = $app_strings['LBL_EMAIL_ERROR_MESSAGE_DELETED'];
3937 $q = "DELETE FROM email_cache WHERE message_id = '{$uid}' AND ie_id = '{$this->id}' AND mbox = '{$this->mailbox}'";
3939 $this->email->name = $app_strings['LBL_EMAIL_ERROR_IMAP_MESSAGE_DELETED'];
3940 $q = "DELETE FROM email_cache WHERE imap_uid = {$uid} AND ie_id = '{$this->id}' AND mbox = '{$this->mailbox}'";
3942 // delete local cache
3943 $r = $this->db->query($q);
3945 $this->email->date_sent = $timedate->nowDb();
3947 //return "Message deleted from server.";
3950 ///////////////////////////////////////////////////////////////////////
3951 //// DUPLICATE CHECK
3952 $dupeCheckResult = $this->importDupeCheck($header->message_id, $header, $fullHeader);
3953 if($forDisplay || $dupeCheckResult) {
3954 $GLOBALS['log']->debug('*********** NO duplicate found, continuing with processing.');
3956 $structure = imap_fetchstructure($this->conn, $msgNo); // map of email
3958 ///////////////////////////////////////////////////////////////////
3959 //// CREATE SEED EMAIL OBJECT
3960 $email = new Email();
3961 $email->isDuplicate = ($dupeCheckResult) ? false : true;
3962 $email->mailbox_id = $this->id;
3964 $email->id = create_guid();
3965 $email->new_with_id = true; //forcing a GUID here to prevent double saves.
3966 //// END CREATE SEED EMAIL
3967 ///////////////////////////////////////////////////////////////////
3969 ///////////////////////////////////////////////////////////////////
3970 //// PREP SYSTEM USER
3971 if(empty($current_user)) {
3972 // I-E runs as admin, get admin prefs
3974 $current_user = new User();
3975 $current_user->getSystemUser();
3977 $tPref = $current_user->getUserDateTimePreferences();
3979 ///////////////////////////////////////////////////////////////////
3980 if(!empty($header->date)) {
3981 $unixHeaderDate = $timedate->fromString($header->date);
3983 ///////////////////////////////////////////////////////////////////
3984 //// HANDLE EMAIL ATTACHEMENTS OR HTML TEXT
3985 //// Inline images require that I-E handle attachments before body text
3986 // parts defines attachments - be mindful of .html being interpreted as an attachment
3987 if($structure->type == 1 && !empty($structure->parts)) {
3988 $GLOBALS['log']->debug('InboundEmail found multipart email - saving attachments if found.');
3989 $this->saveAttachments($msgNo, $structure->parts, $email->id, 0, $forDisplay);
3990 } elseif($structure->type == 0) {
3991 $uuemail = ($this->isUuencode($email->description)) ? true : false;
3993 * UUEncoded attachments - legacy, but still have to deal with it
3995 * begin 777 filename.txt
4000 // set body to the filtered one
4002 $email->description = $this->handleUUEncodedEmailBody($email->description, $email->id);
4003 $email->retrieve($email->id);
4007 if($this->port != 110) {
4008 $GLOBALS['log']->debug('InboundEmail found a multi-part email (id:'.$msgNo.') with no child parts to parse.');
4011 //// END HANDLE EMAIL ATTACHEMENTS OR HTML TEXT
4012 ///////////////////////////////////////////////////////////////////
4014 ///////////////////////////////////////////////////////////////////
4015 //// ASSIGN APPROPRIATE ATTRIBUTES TO NEW EMAIL OBJECT
4016 // handle UTF-8/charset encoding in the ***headers***
4018 $email->name = $this->handleMimeHeaderDecode($header->subject);
4019 $email->date_start = (!empty($unixHeaderDate)) ? $timedate->asUserDate($unixHeaderDate) : "";
4020 $email->time_start = (!empty($unixHeaderDate)) ? $timedate->asUserTime($unixHeaderDate) : "";
4021 $email->type = 'inbound';
4022 $email->date_created = (!empty($unixHeaderDate)) ? $timedate->asUser($unixHeaderDate) : "";
4023 $email->status = 'unread'; // this is used in Contacts' Emails SubPanel
4024 if(!empty($header->toaddress)) {
4025 $email->to_name = $this->handleMimeHeaderDecode($header->toaddress);
4026 $email->to_addrs_names = $email->to_name;
4028 if(!empty($header->to)) {
4029 $email->to_addrs = $this->convertImapToSugarEmailAddress($header->to);
4031 $email->from_name = $this->handleMimeHeaderDecode($header->fromaddress);
4032 $email->from_addr_name = $email->from_name;
4033 $email->from_addr = $this->convertImapToSugarEmailAddress($header->from);
4034 if(!empty($header->cc)) {
4035 $email->cc_addrs = $this->convertImapToSugarEmailAddress($header->cc);
4037 if(!empty($header->ccaddress)) {
4038 $email->cc_addrs_names = $this->handleMimeHeaderDecode($header->ccaddress);
4040 $email->reply_to_name = $this->handleMimeHeaderDecode($header->reply_toaddress);
4041 $email->reply_to_email = $this->convertImapToSugarEmailAddress($header->reply_to);
4042 if (!empty($email->reply_to_email)) {
4043 $email->reply_to_addr = $email->reply_to_name;
4045 $email->intent = $this->mailbox_type;
4047 $email->message_id = $this->compoundMessageId; // filled by importDupeCheck();
4049 $oldPrefix = $this->imagePrefix;
4051 // Store CIDs in imported messages, convert on display
4052 $this->imagePrefix = "cid:";
4054 // handle multi-part email bodies
4055 $email->description_html= $this->getMessageText($msgNo, 'HTML', $structure, $fullHeader,$clean_email); // runs through handleTranserEncoding() already
4056 $email->description = $this->getMessageText($msgNo, 'PLAIN', $structure, $fullHeader,$clean_email); // runs through handleTranserEncoding() already
4057 $this->imagePrefix = $oldPrefix;
4059 // empty() check for body content
4060 if(empty($email->description)) {
4061 $GLOBALS['log']->debug('InboundEmail Message (id:'.$email->message_id.') has no body');
4065 if (!empty($_REQUEST['user_id'])) {
4066 $email->assigned_user_id = $_REQUEST['user_id'];
4068 // Samir Gandhi : Commented out this code as its not needed
4069 //$email->assigned_user_id = $this->group_id;
4072 //Assign Parent Values if set
4073 if (!empty($_REQUEST['parent_id']) && !empty($_REQUEST['parent_type'])) {
4074 $email->parent_id = $_REQUEST['parent_id'];
4075 $email->parent_type = $_REQUEST['parent_type'];
4077 $mod = strtolower($email->parent_type);
4078 $rel = array_key_exists($mod, $email->field_defs) ? $mod : $mod . "_activities_emails"; //Custom modules rel name
4080 if(! $email->load_relationship($rel) )
4082 $email->$rel->add($email->parent_id);
4085 // override $forDisplay w/user pref
4087 if($this->isAutoImport()) {
4088 $forDisplay = false; // triggers save of imported email
4095 $email->new_with_id = false; // to allow future saves by UPDATE, instead of INSERT
4096 //// ASSIGN APPROPRIATE ATTRIBUTES TO NEW EMAIL OBJECT
4097 ///////////////////////////////////////////////////////////////////
4099 ///////////////////////////////////////////////////////////////////
4100 //// LINK APPROPRIATE BEANS TO NEWLY SAVED EMAIL
4101 //$contactAddr = $this->handleLinking($email);
4102 //// END LINK APPROPRIATE BEANS TO NEWLY SAVED EMAIL
4103 ///////////////////////////////////////////////////////////////////
4105 ///////////////////////////////////////////////////////////////////
4106 //// MAILBOX TYPE HANDLING
4107 $this->handleMailboxType($email, $header);
4108 //// END MAILBOX TYPE HANDLING
4109 ///////////////////////////////////////////////////////////////////
4111 ///////////////////////////////////////////////////////////////////
4112 //// SEND AUTORESPONSE
4113 if(!empty($email->reply_to_email)) {
4114 $contactAddr = $email->reply_to_email;
4116 $contactAddr = $email->from_addr;
4118 if (!$this->isMailBoxTypeCreateCase()) {
4119 $this->handleAutoresponse($email, $contactAddr);
4121 //// END SEND AUTORESPONSE
4122 ///////////////////////////////////////////////////////////////////
4123 //// END IMPORT ONE EMAIL
4124 ///////////////////////////////////////////////////////////////////
4127 // only log if not POP3; pop3 iterates through ALL mail
4128 if($this->protocol != 'pop3') {
4129 $GLOBALS['log']->info("InboundEmail found a duplicate email: ".$header->message_id);
4130 //echo "This email has already been imported";
4134 //// END DUPLICATE CHECK
4135 ///////////////////////////////////////////////////////////////////////
4137 ///////////////////////////////////////////////////////////////////////
4138 //// DEAL WITH THE MAILBOX
4140 imap_setflag_full($this->conn, $msgNo, '\\SEEN');
4142 // if delete_seen, mark msg as deleted
4143 if($this->delete_seen == 1 && !$forDisplay) {
4144 $GLOBALS['log']->info("INBOUNDEMAIL: delete_seen == 1 - deleting email");
4145 imap_setflag_full($this->conn, $msgNo, '\\DELETED');
4148 // for display - don't touch server files?
4149 //imap_setflag_full($this->conn, $msgNo, '\\UNSEEN');
4152 $GLOBALS['log']->debug('********************************* InboundEmail finished import of 1 email: '.$email->name);
4153 //// END DEAL WITH THE MAILBOX
4154 ///////////////////////////////////////////////////////////////////////
4156 ///////////////////////////////////////////////////////////////////////
4157 //// TO SUPPORT EMAIL 2.0
4158 $this->email = $email;
4160 if(empty($this->email->et)) {
4161 $this->email->email2init();
4168 * figures out if a plain text email body has UUEncoded attachments
4169 * @param string string The email body
4170 * @return bool True if UUEncode is detected.
4172 function isUuencode($string) {
4173 $rx = "begin [0-9]{3} .*";
4175 $exBody = explode("\r", $string);
4176 foreach($exBody as $line) {
4177 if(preg_match("/begin [0-9]{3} .*/i", $line)) {
4186 * handles UU Encoded emails - a legacy from pre-RFC 822 which must still be supported (?)
4187 * @param string raw The raw email body
4188 * @param string id Parent email ID
4189 * @return string The filtered email body, stripped of attachments
4191 function handleUUEncodedEmailBody($raw, $id) {
4195 $attachmentBody = '';
4196 $inAttachment = false;
4198 $exRaw = explode("\n", $raw);
4200 foreach($exRaw as $k => $line) {
4201 $line = trim($line);
4203 if(preg_match("/begin [0-9]{3} .*/i", $line, $m)) {
4204 $inAttachment = true;
4205 $fileName = $this->handleEncodedFilename(substr($m[0], 10, strlen($m[0])));
4207 $attachmentBody = ''; // reset for next part of loop;
4212 if(strpos($line, "end") === 0) {
4213 if(!empty($fileName) && !empty($attachmentBody)) {
4214 $this->handleUUDecode($id, $fileName, trim($attachmentBody));
4215 $attachmentBody = ''; // reset for next part of loop;
4219 if($inAttachment === false) {
4220 $emailBody .= "\n".$line;
4222 $attachmentBody .= "\n".$line;
4226 /* 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 */
4227 $emailBody = $locale->translateCharset($emailBody, $locale->getExportCharset(), 'UTF-8');
4232 * wrapper for UUDecode
4233 * @param string id Id of the email
4234 * @param string UUEncode Encode US-ASCII
4236 function handleUUDecode($id, $fileName, $UUEncode) {
4237 global $sugar_config;
4238 /* include PHP_Compat library; it auto-feels for PHP5's compiled convert_uuencode() function */
4239 require_once('include/PHP_Compat/convert_uudecode.php');
4241 $attach = new Note();
4242 $attach->parent_id = $id;
4243 $attach->parent_type = 'Emails';
4245 $fname = $this->handleEncodedFilename($fileName);
4247 if(!empty($fname)) {//assign name to attachment
4248 $attach->name = $fname;
4249 } else {//if name is empty, default to filename
4250 $attach->name = urlencode($fileName);
4253 $attach->filename = urlencode($attach->name);
4255 //get position of last "." in file name
4256 $file_ext_beg = strrpos($attach->filename,".");
4258 //get file extension
4259 if($file_ext_beg >0) {
4260 $file_ext = substr($attach->filename, $file_ext_beg+1);
4262 //check to see if this is a file with extension located in "badext"
4263 foreach($sugar_config['upload_badext'] as $badExt) {
4264 if(strtolower($file_ext) == strtolower($badExt)) {
4265 //if found, then append with .txt and break out of lookup
4266 $attach->name = $attach->name . ".txt";
4267 $attach->file_mime_type = 'text/';
4268 $attach->filename = $attach->filename . ".txt";
4269 break; // no need to look for more
4274 $bin = convert_uudecode($UUEncode);
4275 $filename = "upload://{$attach->id}";
4276 if(file_put_contents($filename, $bin)) {
4277 $GLOBALS['log']->debug('InboundEmail saved attachment file: '.$filename);
4279 $GLOBALS['log']->debug('InboundEmail could not create attachment file: '.$filename);
4284 * returns true if the email's domain is NOT in the filter domain string
4286 * @param object email Email object in question
4287 * @return bool true if not filtered, false if filtered
4289 function checkFilterDomain($email) {
4290 $filterDomain = $this->get_stored_options('filter_domain');
4291 if(!isset($filterDomain) || empty($filterDomain)) {
4292 return true; // nothing set for this
4294 $replyTo = strtolower($email->reply_to_email);
4295 $from = strtolower($email->from_addr);
4296 $filterDomain = '@'.strtolower($filterDomain);
4297 if(strpos($replyTo, $filterDomain) !== false) {
4298 $GLOBALS['log']->debug('Autoreply cancelled - [reply to] address domain matches filter domain.');
4300 } elseif(strpos($from, $filterDomain) !== false) {
4301 $GLOBALS['log']->debug('Autoreply cancelled - [from] address domain matches filter domain.');
4304 return true; // no match
4310 * returns true if subject is NOT "out of the office" type
4312 * @param string subject Subject line of email in question
4313 * @return bool returns false if OOTO found
4315 function checkOutOfOffice($subject) {
4316 $ooto = array("Out of the Office", "Out of Office");
4318 foreach($ooto as $str) {
4319 if(preg_match('/'.$str.'/i', $subject)) {
4320 $GLOBALS['log']->debug('Autoreply cancelled - found "Out of Office" type of subject.');
4324 return true; // no matches to ooto strings
4329 * sets a timestamp for an autoreply to a single email addy
4331 * @param string addr Address of auto-replied target
4333 function setAutoreplyStatus($addr) {
4334 $timedate = TimeDate::getInstance();
4335 $this->db->query( 'INSERT INTO inbound_email_autoreply (id, deleted, date_entered, date_modified, autoreplied_to, ie_id) VALUES (
4336 \''.create_guid().'\',
4338 \''.$timedate->nowDb().'\',
4339 \''.$timedate->nowDb().'\',
4341 \''.$this->id.'\') ', true);
4346 * returns true if recipient has NOT received 10 auto-replies in 24 hours
4348 * @param string from target address for auto-reply
4349 * @return bool true if target is valid/under limit
4351 function getAutoreplyStatus($from) {
4352 global $sugar_config;
4353 $timedate = TimeDate::getInstance();
4355 $q_clean = 'UPDATE inbound_email_autoreply SET deleted = 1 WHERE date_entered < \''.$timedate->getNow()->modify("-24 hours")->asDb().'\'';
4356 $r_clean = $this->db->query($q_clean, true);
4358 $q = 'SELECT count(*) AS c FROM inbound_email_autoreply WHERE deleted = 0 AND autoreplied_to = \''.$from.'\' AND ie_id = \''.$this->id.'\'';
4359 $r = $this->db->query($q, true);
4360 $a = $this->db->fetchByAssoc($r);
4362 $email_num_autoreplies_24_hours = $this->get_stored_options('email_num_autoreplies_24_hours');
4363 $maxReplies = (isset($email_num_autoreplies_24_hours)) ? $email_num_autoreplies_24_hours : $this->maxEmailNumAutoreplies24Hours;
4365 if($a['c'] >= $maxReplies) {
4366 $GLOBALS['log']->debug('Autoreply cancelled - more than ' . $maxReplies . ' replies sent in 24 hours.');
4374 * returns exactly 1 id match. if more than one, than returns false
4375 * @param $emailName the subject of the email to match
4376 * @param $tableName the table of the matching bean type
4378 function getSingularRelatedId($emailName, $tableName) {
4379 $repStrings = array('RE:','Re:','re:');
4380 $preppedName = str_replace($repStrings,'',trim($emailName));
4382 //TODO add team security to this query
4383 $q = 'SELECT count(id) AS c FROM '.$tableName.' WHERE deleted = 0 AND name LIKE \'%'.$preppedName.'%\'';
4384 $r = $this->db->query($q, true);
4385 $a = $this->db->fetchByAssoc($r);
4388 $q = 'SELECT id FROM '.$tableName.' WHERE deleted = 0 AND name LIKE \'%'.$preppedName.'%\'';
4389 $r = $this->db->query($q, true);
4390 $a = $this->db->fetchByAssoc($r);
4398 * saves InboundEmail parse macros to config.php
4399 * @param string type Bean to link
4400 * @param string macro The new macro
4402 function saveInboundEmailSystemSettings($type, $macro) {
4403 global $sugar_config;
4405 // inbound_email_case_subject_macro
4406 $var = "inbound_email_".strtolower($type)."_subject_macro";
4407 $sugar_config[$var] = $macro;
4409 ksort($sugar_config);
4411 $sugar_config_string = "<?php\n" .
4412 '// created: ' . date('Y-m-d H:i:s') . "\n" .
4413 '$sugar_config = ' .
4414 var_export($sugar_config, true) .
4417 write_array_to_file("sugar_config", $sugar_config, "config.php");
4421 * returns the HTML for InboundEmail system settings
4422 * @return string HTML
4424 function getSystemSettingsForm() {
4425 global $sugar_config;
4426 global $mod_strings;
4427 global $app_strings;
4428 global $app_list_strings;
4433 $macro = $c->getEmailSubjectMacro();
4436 <form action="index.php" method="post" name="Macro" id="form">
4437 <input type="hidden" name="module" value="InboundEmail">
4438 <input type="hidden" name="action" value="ListView">
4439 <input type="hidden" name="save" value="true">
4441 <table width="100%" cellpadding="0" cellspacing="0" border="0">
4444 <input title="{$app_strings['LBL_SAVE_BUTTON_TITLE']}"
4445 accessKey="{$app_strings['LBL_SAVE_BUTTON_KEY']}"
4447 onclick="this.form.return_module.value='InboundEmail'; this.form.return_action.value='ListView';"
4448 type="submit" name="Edit" value=" {$app_strings['LBL_SAVE_BUTTON_LABEL']} ">
4453 <table width="100%" border="0" cellspacing="0" cellpadding="0" class="detail view">
4455 <td valign="top" width='10%' NOWRAP scope="row">
4457 <b>{$mod_strings['LBL_CASE_MACRO']}:</b>
4460 <td valign="top" width='20%'>
4462 <input name="inbound_email_case_macro" type="text" value="{$macro}">
4465 <td valign="top" width='70%'>
4467 {$mod_strings['LBL_CASE_MACRO_DESC']}
4469 <i>{$mod_strings['LBL_CASE_MACRO_DESC2']}</i>
4480 * for mailboxes of type "Support" parse for '[CASE:%1]'
4481 * @param $emailName the subject line of the email
4482 * @param $aCase a Case object
4484 function getCaseIdFromCaseNumber($emailName, $aCase) {
4485 //$emailSubjectMacro
4486 $exMacro = explode('%1', $aCase->getEmailSubjectMacro());
4487 $open = $exMacro[0];
4488 $close = $exMacro[1];
4490 if($sub = stristr($emailName, $open)) { // eliminate everything up to the beginning of the macro and return the rest
4491 // $sub is [CASE:XX] xxxxxxxxxxxxxxxxxxxxxx
4492 $sub2 = str_replace($open, '', $sub);
4493 // $sub2 is XX] xxxxxxxxxxxxxx
4494 $sub3 = substr($sub2, 0, strpos($sub2, $close));
4496 $r = $this->db->query("SELECT id FROM cases WHERE case_number = '{$sub3}'", true);
4497 $a = $this->db->fetchByAssoc($r);
4498 if(!empty($a['id'])) {
4508 function get_stored_options($option_name,$default_value=null,$stored_options=null) {
4509 if (empty($stored_options)) {
4510 $stored_options=$this->stored_options;
4512 if(!empty($stored_options)) {
4513 $storedOptions = unserialize(base64_decode($stored_options));
4514 if (isset($storedOptions[$option_name])) {
4515 $default_value=$storedOptions[$option_name];
4518 return $default_value;
4523 * This function returns a contact or user ID if a matching email is found
4524 * @param $email the email address to match
4525 * @param $table which table to query
4527 function getRelatedId($email, $module) {
4528 $email = trim(strtoupper($email));
4529 if(strpos($email, ',') !== false) {
4530 $emailsArray = explode(',', $email);
4531 $emailAddressString = "";
4532 foreach($emailsArray as $emailAddress) {
4533 if (!empty($emailAddressString)) {
4534 $emailAddressString .= ",";
4536 $emailAddressString .= "'" . $emailAddress. "'";
4538 $email = $emailAddressString;
4540 $email = "'" . $email . "'";
4542 $module = ucfirst($module);
4544 $q = "SELECT bean_id FROM email_addr_bean_rel eabr
4545 JOIN email_addresses ea ON (eabr.email_address_id = ea.id)
4546 WHERE bean_module = '{$module}' AND ea.email_address_caps in ( {$email} ) AND eabr.deleted=0";
4548 $r = $this->db->query($q, true);
4551 while($a = $this->db->fetchByAssoc($r)) {
4552 $retArr[] = $a['bean_id'];
4554 if(count($retArr) > 0) {
4562 * finds emails tagged "//UNSEEN" on mailserver and "SINCE: [date]" if that
4565 * @return array Array of messageNumbers (mail server's internal keys)
4567 function getNewMessageIds() {
4568 $storedOptions = unserialize(base64_decode($this->stored_options));
4570 //TODO figure out if the since date is UDT
4571 if($storedOptions['only_since']) {// POP3 does not support Unseen flags
4572 if(!isset($storedOptions['only_since_last']) && !empty($storedOptions['only_since_last'])) {
4573 $q = 'SELECT last_run FROM schedulers WHERE job = \'function::pollMonitoredInboxes\'';
4574 $r = $this->db->query($q, true);
4575 $a = $this->db->fetchByAssoc($r);
4577 $date = date('r', strtotime($a['last_run']));
4579 $date = $storedOptions['only_since_last'];
4581 $ret = imap_search($this->conn, 'SINCE "'.$date.'" UNDELETED UNSEEN');
4582 $check = imap_check($this->conn);
4583 $storedOptions['only_since_last'] = $check->Date;
4584 $this->stored_options = base64_encode(serialize($storedOptions));
4587 $ret = imap_search($this->conn, 'UNDELETED UNSEEN');
4590 $GLOBALS['log']->debug('-----> getNewMessageIds() got '.count($ret).' new Messages');
4595 * Constructs the resource connection string that IMAP needs
4596 * @param string $service Service string, will generate if not passed
4599 function getConnectString($service='', $mbox='', $includeMbox=true) {
4600 $service = empty($service) ? $this->getServiceString() : $service;
4601 $mbox = empty($mbox) ? $this->mailbox : $mbox;
4603 $connectString = '{'.$this->server_url.':'.$this->port.'/service='.$this->protocol.$service.'}';
4604 $connectString .= ($includeMbox) ? $mbox : "";
4606 return $connectString;
4609 function disconnectMailserver() {
4610 if(is_resource($this->conn)) {
4611 imap_close($this->conn);
4616 * Connects to mailserver. If an existing IMAP resource is available, it
4617 * will attempt to reuse the connection, updating the mailbox path.
4619 * @param bool test Flag to test connection
4620 * @param bool force Force reconnect
4621 * @return string "true" on success, "false" or $errorMessage on failure
4623 function connectMailserver($test=false, $force=false) {
4624 global $mod_strings;
4625 if(!function_exists("imap_open")) {
4626 $GLOBALS['log']->debug('------------------------- IMAP libraries NOT available!!!! die()ing thread.----');
4627 return $mod_strings['LBL_WARN_NO_IMAP'];
4630 imap_errors(); // clearing error stack
4631 error_reporting(0); // turn off notices from IMAP
4633 // tls::ca::ssl::protocol::novalidate-cert::notls
4634 $useSsl = ($_REQUEST['ssl'] == 'true') ? true : false;
4636 imap_timeout(1, 15); // 60 secs is the default
4637 imap_timeout(2, 15);
4638 imap_timeout(3, 15);
4640 $opts = $this->findOptimumSettings($useSsl);
4641 if(isset($opts['good']) && empty($opts['good'])) {
4642 return array_pop($opts['err']);
4644 $service = $opts['service'];
4645 $service = str_replace('foo','', $service); // foo there to support no-item explodes
4648 $service = $this->getServiceString();
4651 $connectString = $this->getConnectString($service, $this->mailbox);
4654 * Try to recycle the current connection to reduce response times
4656 if(is_resource($this->conn)) {
4659 imap_close($this->conn);
4662 if(imap_ping($this->conn)) {
4663 // we have a live connection
4664 imap_reopen($this->conn, $connectString, CL_EXPUNGE);
4669 if(!is_resource($this->conn) && !$test) {
4670 $this->conn = imap_open($connectString, $this->email_user, $this->email_password, CL_EXPUNGE);
4674 if ($opts == false && !is_resource($this->conn)) {
4675 $this->conn = imap_open($connectString, $this->email_user, $this->email_password, CL_EXPUNGE);
4679 $successful = false;
4680 if(($errors = imap_last_error()) || ($alerts = imap_alerts())) {
4681 if($errors == 'Mailbox is empty') { // false positive
4685 $msg .= '<p>'.$alerts.'<p>';
4686 $msg .= '<p>'.$mod_strings['ERR_TEST_MAILBOX'];
4693 if($this->protocol == 'imap') {
4694 $msg .= $mod_strings['LBL_TEST_SUCCESSFUL'];
4696 $testConnectString = '{'.$this->server_url.':'.$this->port.'/service='.$this->protocol.$service.'}';
4697 if (!is_resource($this->conn)) {
4698 $this->conn = imap_open($connectString, $this->email_user, $this->email_password, CL_EXPUNGE);
4700 $list = imap_getmailboxes($this->conn, $testConnectString, "*");
4701 if(isset($_REQUEST['personal']) && $_REQUEST['personal'] == 'true') {
4702 $msg .= $mod_strings['LBL_TEST_SUCCESSFUL'];
4703 } elseif (is_array($list)) {
4707 $msg .= '<b>'.$mod_strings['LBL_FOUND_MAILBOXES'].'</b><p>';
4708 foreach ($list as $key => $val) {
4709 $mb = imap_utf7_decode(str_replace($testConnectString,'',$val->name));
4710 $msg .= '<a onClick=\'setMailbox(\"'.$mb.'\"); window.close();\'>';
4716 $msg .= '<p>'.$mod_strings['ERR_MAILBOX_FAIL'].imap_last_error().'</p>';
4717 $msg .= '<p>'.$mod_strings['ERR_TEST_MAILBOX'].'</p>';
4721 $msg .= $mod_strings['LBL_POP3_SUCCESS'];
4725 imap_errors(); // collapse error stack
4726 imap_close($this->conn);
4728 } elseif(!is_resource($this->conn)) {
4737 function checkImap() {
4738 global $mod_strings;
4740 if(!function_exists('imap_open')) {
4742 <table cellpadding="0" cellspacing="0" width="100%" border="0" class="list view">
4744 <td scope="col" width="25%" colspan="2"><slot>
4745 '.$mod_strings['LBL_WARN_IMAP_TITLE'].'
4749 <td scope="row" valign=TOP bgcolor="#fdfdfd" width="20%"><slot>
4750 '.$mod_strings['LBL_WARN_IMAP'].'
4751 <td scope="row" valign=TOP class="oddListRowS1" bgcolor="#fdfdfd" width="80%"><slot>
4752 <span class=error>'.$mod_strings['LBL_WARN_NO_IMAP'].'</span>
4761 * retrieves an array of I-E beans based on the group_id
4762 * @param string $groupId GUID of the group user or Individual
4763 * @return array $beans array of beans
4764 * @return boolean false if none returned
4766 function retrieveByGroupId($groupId) {
4767 $q = 'SELECT id FROM inbound_email WHERE group_id = \''.$groupId.'\' AND deleted = 0 AND status = \'Active\'';
4768 $r = $this->db->query($q, true);
4771 while($a = $this->db->fetchByAssoc($r)) {
4772 $ie = new InboundEmail();
4773 $ie->retrieve($a['id']);
4774 $beans[$a['id']] = $ie;
4780 * Retrieves the current count of personal accounts for the user specified.
4782 * @param unknown_type $user
4784 function getUserPersonalAccountCount($user = null)
4787 $user = $GLOBALS['current_user'];
4789 $query = "SELECT count(*) as c FROM inbound_email WHERE deleted=0 AND is_personal='1' AND group_id='{$user->id}' AND status='Active'";
4791 $rs = $this->db->query($query);
4792 $row = $this->db->fetchByAssoc($rs);
4797 * retrieves an array of I-E beans based on the group folder id
4798 * @param string $groupFolderId GUID of the group folder
4799 * @return array $beans array of beans
4800 * @return boolean false if none returned
4802 function retrieveByGroupFolderId($groupFolderId) {
4803 $q = 'SELECT id FROM inbound_email WHERE groupfolder_id = \''.$groupFolderId.'\' AND deleted = 0 ';
4804 $r = $this->db->query($q, true);
4807 while($a = $this->db->fetchByAssoc($r)) {
4808 $ie = new InboundEmail();
4809 $ie->retrieve($a['id']);
4816 * Retrieves an array of I-E beans that the user has team access to
4818 function retrieveAllByGroupId($id, $includePersonal=true) {
4819 global $current_user;
4821 $beans = ($includePersonal) ? $this->retrieveByGroupId($id) : array();
4827 $q = "SELECT inbound_email.id FROM inbound_email {$teamJoin} WHERE is_personal = 0 AND groupfolder_id is null AND mailbox_type not like 'bounce' AND inbound_email.deleted = 0 AND status = 'Active' ";
4831 $r = $this->db->query($q, true);
4833 while($a = $this->db->fetchByAssoc($r)) {
4835 foreach($beans as $bean) {
4836 if($bean->id == $a['id']) {
4842 $ie = new InboundEmail();
4843 $ie->retrieve($a['id']);
4844 $beans[$a['id']] = $ie;
4852 * Retrieves an array of I-E beans that the user has team access to including group
4854 function retrieveAllByGroupIdWithGroupAccounts($id, $includePersonal=true) {
4855 global $current_user;
4857 $beans = ($includePersonal) ? $this->retrieveByGroupId($id) : array();
4866 $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 ";
4868 $r = $this->db->query($q, true);
4870 while($a = $this->db->fetchByAssoc($r)) {
4872 foreach($beans as $bean) {
4873 if($bean->id == $a['id']) {
4879 $ie = new InboundEmail();
4880 $ie->retrieve($a['id']);
4881 $beans[$a['id']] = $ie;
4890 * returns the bean name - overrides SugarBean's
4892 function get_summary_text() {
4897 * Override's SugarBean's
4899 function create_export_query($order_by, $where, $show_deleted = 0) {
4900 return $this->create_new_list_query($order_by, $where, $show_deleted = 0);
4904 * Override's SugarBean's
4908 * Override's SugarBean's
4910 function get_list_view_data(){
4911 global $mod_strings;
4912 global $app_list_strings;
4913 $temp_array = $this->get_list_view_array();
4914 $temp_array['MAILBOX_TYPE_NAME']= $app_list_strings['dom_mailbox_type'][$this->mailbox_type];
4915 //cma, fix bug 21670.
4916 $temp_array['GLOBAL_PERSONAL_STRING']= ($this->is_personal ? $mod_strings['LBL_IS_PERSONAL'] : $mod_strings['LBL_IS_GROUP']);
4917 $temp_array['STATUS'] = ($this->status == 'Active') ? $mod_strings['LBL_STATUS_ACTIVE'] : $mod_strings['LBL_STATUS_INACTIVE'];
4922 * Override's SugarBean's
4924 function fill_in_additional_list_fields() {
4925 $this->fill_in_additional_detail_fields();
4929 * Override's SugarBean's
4931 function fill_in_additional_detail_fields() {
4932 if(!empty($this->service)) {
4933 $exServ = explode('::', $this->service);
4934 $this->tls = $exServ[0];
4935 if ( isset($exServ[1]) )
4936 $this->ca = $exServ[1];
4937 if ( isset($exServ[2]) )
4938 $this->ssl = $exServ[2];
4939 if ( isset($exServ[3]) )
4940 $this->protocol = $exServ[3];
4957 ///////////////////////////////////////////////////////////////////////////
4958 //// IN SUPPORT OF EMAIL 2.0
4960 * Checks for $user's autoImport setting and returns the current value
4961 * @param object $user User in focus, defaults to $current_user
4964 function isAutoImport($user=null) {
4965 if(!empty($this->autoImport)) {
4966 return $this->autoImport;
4969 global $current_user;
4970 if(empty($user)) $user = $current_user;
4972 $emailSettings = $current_user->getPreference('emailSettings', 'Emails');
4973 $emailSettings = is_string($emailSettings) ? unserialize($emailSettings) : $emailSettings;
4975 $this->autoImport = (isset($emailSettings['autoImport']) && !empty($emailSettings['autoImport'])) ? true : false;
4976 return $this->autoImport;
4980 * Clears out cache files for a user
4982 function cleanOutCache() {
4983 $GLOBALS['log']->debug("INBOUNDEMAIL: at cleanOutCache()");
4984 $this->deleteCache();
4988 * moves emails from folder to folder
4989 * @param string $fromIe I-E id
4990 * @param string $fromFolder IMAP path to folder in which the email lives
4991 * @param string $toIe I-E id
4992 * @param string $toFolder
4993 * @param string $uids UIDs of emails to move, either Sugar GUIDS or IMAP
4996 function copyEmails($fromIe, $fromFolder, $toIe, $toFolder, $uids) {
4997 $this->moveEmails($fromIe, $fromFolder, $toIe, $toFolder, $uids, true);
5001 * moves emails from folder to folder
5002 * @param string $fromIe I-E id
5003 * @param string $fromFolder IMAP path to folder in which the email lives
5004 * @param string $toIe I-E id
5005 * @param string $toFolder
5006 * @param string $uids UIDs of emails to move, either Sugar GUIDS or IMAP
5008 * @param bool $copy Default false
5009 * @return bool True on successful execution
5011 function moveEmails($fromIe, $fromFolder, $toIe, $toFolder, $uids, $copy=false) {
5012 global $app_strings;
5013 global $current_user;
5017 if($fromIe == $toIe) {
5018 $GLOBALS['log']->debug("********* SUGARFOLDER - moveEmails() moving email from I-E to I-E");
5019 //$exDestFolder = explode("::", $toFolder);
5020 //preserve $this->mailbox
5021 if (isset($this->mailbox)) {
5022 $oldMailbox = $this->mailbox;
5026 $this->retrieve($fromIe);
5027 $this->mailbox = $fromFolder;
5028 $this->connectMailserver();
5029 $exUids = explode('::;::', $uids);
5030 $uids = implode(",", $exUids);
5031 // imap_mail_move accepts comma-delimited lists of UIDs
5033 if(imap_mail_copy($this->conn, $uids, $toFolder, CP_UID)) {
5034 $this->mailbox = $toFolder;
5035 $this->connectMailserver();
5036 $newOverviews = imap_fetch_overview($this->conn, $uids, FT_UID);
5037 $this->updateOverviewCacheFile($newOverviews, 'append');
5038 if (isset($oldMailbox)) {
5039 $this->mailbox = $oldMailbox;
5043 $GLOBALS['log']->debug("INBOUNDEMAIL: could not imap_mail_copy() [ {$uids} ] to folder [ {$toFolder} ] from folder [ {$fromFolder} ]");
5046 if(imap_mail_move($this->conn, $uids, $toFolder, CP_UID)) {
5047 $GLOBALS['log']->info("INBOUNDEMAIL: imap_mail_move() [ {$uids} ] to folder [ {$toFolder} ] from folder [ {$fromFolder} ]");
5048 imap_expunge($this->conn); // hard deletes moved messages
5050 // update cache on fromFolder
5051 $newOverviews = $this->getOverviewsFromCacheFile($uids, $fromFolder, true);
5052 $this->deleteCachedMessages($uids, $fromFolder);
5054 // update cache on toFolder
5055 $this->checkEmailOneMailbox($toFolder, true, true);
5056 if (isset($oldMailbox)) {
5057 $this->mailbox = $oldMailbox;
5062 $GLOBALS['log']->debug("INBOUNDEMAIL: could not imap_mail_move() [ {$uids} ] to folder [ {$toFolder} ] from folder [ {$fromFolder} ]");
5065 } elseif($toIe == 'folder' && $fromFolder == 'sugar::Emails') {
5066 $GLOBALS['log']->debug("********* SUGARFOLDER - moveEmails() moving email from SugarFolder to SugarFolder");
5067 // move from sugar folder to sugar folder
5068 require_once("include/SugarFolders/SugarFolders.php");
5069 $sugarFolder = new SugarFolder();
5070 $exUids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
5071 foreach($exUids as $id) {
5073 $sugarFolder->copyBean($fromIe, $toFolder, $id, "Emails");
5075 $fromSugarFolder = new SugarFolder();
5076 $fromSugarFolder->retrieve($fromIe);
5077 $toSugarFolder = new SugarFolder();
5078 $toSugarFolder->retrieve($toFolder);
5080 $email = new Email();
5081 $email->retrieve($id);
5082 $email->status = 'unread';
5084 // when you move from My Emails to Group Folder, Assign To field for the Email should become null
5085 if ($fromSugarFolder->is_dynamic && $toSugarFolder->is_group) {
5086 $email->assigned_user_id = "";
5088 if (!$toSugarFolder->checkEmailExistForFolder($id)) {
5089 $fromSugarFolder->deleteEmailFromAllFolder($id);
5090 $toSugarFolder->addBean($email);
5092 } elseif ($fromSugarFolder->is_group && $toSugarFolder->is_dynamic) {
5093 $fromSugarFolder->deleteEmailFromAllFolder($id);
5094 $email->assigned_user_id = $current_user->id;
5097 // If you are moving something from personal folder then delete an entry from all folder
5098 if (!$fromSugarFolder->is_dynamic && !$fromSugarFolder->is_group) {
5099 $fromSugarFolder->deleteEmailFromAllFolder($id);
5102 if ($fromSugarFolder->is_dynamic && !$toSugarFolder->is_dynamic && !$toSugarFolder->is_group) {
5103 $email->assigned_user_id = "";
5104 $toSugarFolder->addBean($email);
5106 if (!$toSugarFolder->checkEmailExistForFolder($id)) {
5107 if (!$toSugarFolder->is_dynamic) {
5108 $fromSugarFolder->deleteEmailFromAllFolder($id);
5109 $toSugarFolder->addBean($email);
5111 $fromSugarFolder->deleteEmailFromAllFolder($id);
5112 $email->assigned_user_id = $current_user->id;
5115 $sugarFolder->move($fromIe, $toFolder, $id);
5123 } elseif($toIe == 'folder') {
5124 $GLOBALS['log']->debug("********* SUGARFOLDER - moveEmails() moving email from I-E to SugarFolder");
5125 // move to Sugar folder
5126 require_once("include/SugarFolders/SugarFolders.php");
5127 $sugarFolder = new SugarFolder();
5128 $sugarFolder->retrieve($toFolder);
5129 //Show the import form if we don't have the required info
5130 if (!isset($_REQUEST['delete'])) {
5131 $json = getJSONobj();
5132 if ($sugarFolder->is_group) {
5133 $_REQUEST['showTeam'] = false;
5134 $_REQUEST['showAssignTo'] = false;
5136 $ret = $this->email->et->getImportForm($_REQUEST, $this->email);
5137 $ret['move'] = true;
5138 $ret['srcFolder'] = $fromFolder;
5139 $ret['srcIeId'] = $fromIe;
5140 $ret['dstFolder'] = $toFolder;
5141 $ret['dstIeId'] = $toIe;
5142 $out = trim($json->encode($ret, false));
5149 $this->retrieve($fromIe);
5150 $this->mailbox = $fromFolder;
5151 $this->connectMailserver();
5152 // If its a group folder the team should be of the folder team
5153 if ($sugarFolder->is_group) {
5154 $_REQUEST['team_id'] = $sugarFolder->team_id;
5155 $_REQUEST['team_set_id'] = $sugarFolder->team_set_id;
5157 // TODO - set team_id, team_set for new UI
5160 $exUids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
5162 if(!empty($sugarFolder->id)) {
5165 $json = getJSONobj();
5166 foreach($exUids as $k => $uid) {
5168 if ($this->isPop3Protocol()) {
5169 $msgNo = $this->getCorrectMessageNoForPop3($uid);
5171 $msgNo = imap_msgno($this->conn, $uid);
5174 if(!empty($msgNo)) {
5175 $importStatus = $this->importOneEmail($msgNo, $uid);
5178 $sugarFolder->addBean($this->email);
5179 if(!$copy && isset($_REQUEST['delete']) && ($_REQUEST['delete'] == "true") && $importStatus) {
5180 $GLOBALS['log']->error("********* delete from mailserver [ {explode(",", $uids)} ]");
5181 // delete from mailserver
5182 $this->deleteMessageOnMailServer($uid);
5183 $this->deleteMessageFromCache($uid);
5186 $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']);
5190 echo $json->encode($return);
5193 $GLOBALS['log']->error("********* SUGARFOLDER - failed to retrieve folder ID [ {$toFolder} ]");
5196 $GLOBALS['log']->debug("********* SUGARFOLDER - moveEmails() called with no passing criteria");
5204 * Hard deletes an I-E account
5205 * @param string id GUID
5207 function hardDelete($id) {
5208 $q = "DELETE FROM inbound_email WHERE id = '{$id}'";
5209 $r = $this->db->query($q, true);
5213 * Generate a unique filename for attachments based on the message id. There are no maximum
5214 * specifications for the length of the message id, the only requirement is that it be globally unique.
5216 * @param bool $nameOnly Whether or not the attachment count should be appended to the filename.
5217 * @return string The temp file name
5219 function getTempFilename($nameOnly=false) {
5221 $str = md5($this->compoundMessageId);
5224 $str = $str.$this->attachmentCount;
5225 $this->attachmentCount++;
5232 * deletes and expunges emails on server
5233 * @param string $uid UID(s), comma delimited, of email(s) on server
5234 * @return bool true on success
5236 function deleteMessageOnMailServer($uid) {
5237 global $app_strings;
5238 $this->connectMailserver();
5240 if(strpos($uid, $app_strings['LBL_EMAIL_DELIMITER']) !== false) {
5241 $uids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uid);
5248 if($this->protocol == 'imap') {
5249 $trashFolder = $this->get_stored_options("trashFolder");
5250 if (empty($trashFolder)) {
5251 $trashFolder = "INBOX.Trash";
5253 foreach($uids as $uid) {
5254 if($this->moveEmails($this->id, $this->mailbox, $this->id, $trashFolder, $uid))
5255 $GLOBALS['log']->debug("INBOUNDEMAIL: MoveEmail to {$trashFolder} successful.");
5257 $GLOBALS['log']->debug("INBOUNDEMAIL: MoveEmail to {$trashFolder} FAILED - trying hard delete for message: $uid");
5258 imap_delete($this->conn, $uid, FT_UID);
5265 foreach($uids as $uid) {
5266 $msgnos[] = $this->getCorrectMessageNoForPop3($uid);
5268 $msgnos = implode(',', $msgnos);
5269 imap_delete($this->conn, $msgnos);
5273 if(!imap_expunge($this->conn)) {
5274 $GLOBALS['log']->debug("NOOP: could not expunge deleted email.");
5278 $GLOBALS['log']->info("INBOUNDEMAIL: hard-deleted mail with MSgno's' [ {$msgnos} ]");
5284 * deletes and expunges emails on server
5285 * @param string $uid UID(s), comma delimited, of email(s) on server
5287 function deleteMessageOnMailServerForPop3($uid) {
5288 if(imap_delete($this->conn, $uid)) {
5289 if(!imap_expunge($this->conn)) {
5290 $GLOBALS['log']->debug("NOOP: could not expunge deleted email.");
5293 $GLOBALS['log']->info("INBOUNDEMAIL: hard-deleted mail with MSgno's' [ {$uid} ]");
5299 * Checks if this is a pop3 type of an account or not
5302 function isPop3Protocol() {
5303 return ($this->protocol == 'pop3');
5307 * Gets the UIDL from database for the corresponding msgno
5308 * @param int messageNo of a message
5309 * @return UIDL for the message
5311 function getUIDLForMessage($msgNo) {
5312 $query = "SELECT message_id FROM email_cache WHERE ie_id = '{$this->id}' AND msgno = '{$msgNo}'";
5313 $r = $this->db->query($query);
5314 $a = $this->db->fetchByAssoc($r);
5315 return $a['message_id'];
5318 * Get the users default IE account id
5323 function getUsersDefaultOutboundServerId($user)
5325 $id = $user->getPreference($this->keyForUsersDefaultIEAccount,'Emails',$user);
5326 //If no preference has been set, grab the default system id.
5329 $oe = new OutboundEmail();
5330 $system = $oe->getSystemMailerSettings();
5331 $id=empty($system->id) ? '' : $system->id;
5338 * Get the users default IE account id
5342 function setUsersDefaultOutboundServerId($user,$oe_id)
5344 $user->setPreference($this->keyForUsersDefaultIEAccount, $oe_id, '', 'Emails');
5347 * Gets the UIDL from database for the corresponding msgno
5348 * @param int messageNo of a message
5349 * @return UIDL for the message
5351 function getMsgnoForMessageID($messageid) {
5352 $query = "SELECT msgno FROM email_cache WHERE ie_id = '{$this->id}' AND message_id = '{$messageid}'";
5353 $r = $this->db->query($query);
5354 $a = $this->db->fetchByAssoc($r);
5355 return $a['message_id'];
5359 * fills InboundEmail->email with an email's details
5360 * @param int uid Unique ID of email
5361 * @param bool isMsgNo flag that passed ID is msgNo, default false
5362 * @param bool setRead Sets the 'seen' flag in cache
5363 * @param bool forceRefresh Skips cache file
5366 function setEmailForDisplay($uid, $isMsgNo=false, $setRead=false, $forceRefresh=false) {
5369 $GLOBALS['log']->debug("*** ERROR: INBOUNDEMAIL trying to setEmailForDisplay() with no UID");
5373 global $sugar_config;
5374 global $app_strings;
5376 // if its a pop3 then get the UIDL and see if this file name exist or not
5377 if ($this->isPop3Protocol()) {
5378 // get the UIDL from database;
5379 $cachedUIDL = md5($uid);
5380 $cache = "{$this->EmailCachePath}/{$this->id}/messages/{$this->mailbox}{$cachedUIDL}.php";
5382 $cache = "{$this->EmailCachePath}/{$this->id}/messages/{$this->mailbox}{$uid}.php";
5385 if(file_exists($cache) && !$forceRefresh) {
5386 $GLOBALS['log']->info("INBOUNDEMAIL: Using cache file for setEmailForDisplay()");
5388 include($cache); // profides $cacheFile
5389 /** @var $cacheFile array */
5391 $metaOut = unserialize($cacheFile['out']);
5392 $meta = $metaOut['meta']['email'];
5393 $email = new Email();
5395 foreach($meta as $k => $v) {
5399 $email->to_addrs = $meta['toaddrs'];
5400 $email->date_sent = $meta['date_start'];
5401 //_ppf($email,true);
5403 $this->email = $email;
5404 $this->email->email2init();
5407 $GLOBALS['log']->info("INBOUNDEMAIL: opening new connection for setEmailForDisplay()");
5408 if($this->isPop3Protocol()) {
5409 $msgNo = $this->getCorrectMessageNoForPop3($uid);
5411 if(empty($this->conn)) {
5412 $this->connectMailserver();
5414 $msgNo = ($isMsgNo) ? $uid : imap_msgno($this->conn, $uid);
5416 if(empty($this->conn)) {
5417 $status = $this->connectMailserver();
5418 if($status == "false") {
5419 $this->email = new Email();
5420 $this->email->name = $app_strings['LBL_EMAIL_ERROR_MAILSERVERCONNECTION'];
5427 $this->importOneEmail($msgNo, $uid, true);
5428 $this->email->id = '';
5429 $this->email->new_with_id = false;
5434 $this->setStatuses($uid, 'seen', 1);
5442 * Sets status for a particular attribute on the mailserver and the local cache file
5444 function setStatuses($uid, $field, $value) {
5445 global $sugar_config;
5446 /** available status fields
5450 [date] => Mon, 22 Jan 2007 17:32:57 -0800
5463 $file = "{$this->mailbox}.imapFetchOverview.php";
5464 $overviews = $this->getCacheValueForUIDs($this->mailbox, array($uid));
5466 if(!empty($overviews)) {
5469 foreach($overviews['retArr'] as $k => $obj) {
5470 if($obj->imap_uid == $uid) {
5471 $obj->$field = $value;
5476 if(!empty($updates)) {
5477 $this->setCacheValue($this->mailbox, array(), $updates);
5483 * Removes an email from the cache file, deletes the message from the cache too
5484 * @param string String of uids, comma delimited
5486 function deleteMessageFromCache($uids) {
5487 global $sugar_config;
5488 global $app_strings;
5490 // delete message cache file and email_cache file
5491 $exUids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
5493 foreach($exUids as $uid) {
5495 if ($this->isPop3Protocol()) {
5496 $q = "DELETE FROM email_cache WHERE message_id = '{$uid}' AND ie_id = '{$this->id}'";
5498 $q = "DELETE FROM email_cache WHERE imap_uid = {$uid} AND ie_id = '{$this->id}'";
5500 $r = $this->db->query($q);
5501 if ($this->isPop3Protocol()) {
5504 $msgCacheFile = "{$this->EmailCachePath}/{$this->id}/messages/{$this->mailbox}{$uid}.php";
5505 if(file_exists($msgCacheFile)) {
5506 if(!unlink($msgCacheFile)) {
5507 $GLOBALS['log']->error("***ERROR: InboundEmail could not delete the cache file [ {$msgCacheFile} ]");
5516 * @param int uid UID of email to display
5517 * @param string mbox Mailbox to look in for the message
5518 * @param bool isMsgNo Flag to assume $uid is a MessageNo, not UniqueID, default false
5520 function displayOneEmail($uid, $mbox, $isMsgNo=false) {
5521 require_once("include/JSON.php");
5524 global $app_strings;
5525 global $app_list_strings;
5526 global $sugar_smarty;
5528 global $current_user;
5529 global $sugar_config;
5531 $fetchedAttributes = array(
5540 $souEmail = array();
5541 foreach($fetchedAttributes as $k) {
5542 if ($k == 'date_start') {
5543 $this->email->$k . " " . $this->email->time_start;
5544 $souEmail[$k] = $this->email->$k . " " . $this->email->time_start;
5545 } elseif ($k == 'time_start') {
5548 $souEmail[$k] = trim($this->email->$k);
5552 // if a MsgNo is passed in, convert to UID
5554 $uid = imap_uid($this->conn, $uid);
5556 // meta object to allow quick retrieval for replies
5558 $meta['type'] = $this->email->type;
5559 $meta['uid'] = $uid;
5560 $meta['ieId'] = $this->id;
5561 $meta['email'] = $souEmail;
5562 $meta['mbox'] = $this->mailbox;
5567 $exMbox = explode("::", $mbox);
5571 if(!empty($this->email->cc_addrs)) {
5572 //$ccs = $this->collapseLongMailingList($this->email->cc_addrs);
5573 $ccs = to_html($this->email->cc_addrs_names);
5576 <td NOWRAP valign="top" class="displayEmailLabel">
5577 {$app_strings['LBL_EMAIL_CC']}:
5579 <td class="displayEmailValue">
5586 $meta['email']['cc_addrs'] = $ccs;
5589 if ($mbox == "sugar::Emails") {
5591 $q = "SELECT id, filename, file_mime_type FROM notes WHERE parent_id = '{$uid}' AND deleted = 0";
5592 $r = $this->db->query($q);
5594 while($a = $this->db->fetchByAssoc($r)) {
5595 $url = "index.php?entryPoint=download&type=notes&id={$a['id']}";
5596 $lbl = ($i == 0) ? $app_strings['LBL_EMAIL_ATTACHMENTS'].":" : '';
5598 $attachments .=<<<EOQ
5600 <td NOWRAP valign="top" class="displayEmailLabel">
5603 <td NOWRAP valign="top" colspan="2" class="displayEmailValue">
5604 <a href="{$url}">{$a['filename']}</a>
5608 $this->email->cid2Link($a['id'], $a['file_mime_type']);
5614 if($this->attachmentCount > 0) {
5615 $theCount = $this->attachmentCount;
5617 for($i=0; $i<$theCount; $i++) {
5618 $lbl = ($i == 0) ? $app_strings['LBL_EMAIL_ATTACHMENTS'].":" : '';
5619 $name = $this->getTempFilename(true).$i;
5620 $tempName = urlencode($this->tempAttachment[$name]);
5622 $url = "index.php?entryPoint=download&type=temp&isTempFile=true&ieId={$this->id}&tempName={$tempName}&id={$name}";
5624 $attachments .=<<<eoq
5626 <td NOWRAP valign="top" class="displayEmailLabel">
5629 <td NOWRAP valign="top" colspan="2" class="displayEmailValue">
5630 <a href="{$url}">{$this->tempAttachment[$name]}</a>
5637 $meta['email']['attachments'] = $attachments;
5640 $meta['email']['toaddrs'] = $this->collapseLongMailingList($this->email->to_addrs);
5641 $meta['email']['cc_addrs'] = $ccs;
5644 $description = (empty($this->email->description_html)) ? nl2br($this->email->description) : $this->email->description_html;
5645 $meta['email']['description'] = $description;
5648 $meta['is_sugarEmail'] = ($exMbox[0] == 'sugar') ? true : false;
5650 if(!$meta['is_sugarEmail']) {
5651 if($this->isAutoImport) {
5652 $meta['is_sugarEmail'] = true;
5655 if( $this->email->status != 'sent' ){
5656 // mark SugarEmail read
5657 $q = "UPDATE emails SET status = 'read' WHERE id = '{$uid}'";
5658 $r = $this->db->query($q);
5663 $meta['email']['name'] = to_html($this->email->name);
5664 $meta['email']['from_addr'] = ( !empty($this->email->from_addr_name) ) ? to_html($this->email->from_addr_name) : to_html($this->email->from_addr);
5665 $meta['email']['toaddrs'] = ( !empty($this->email->to_addrs_names) ) ? to_html($this->email->to_addrs_names) : to_html($this->email->to_addrs);
5666 $meta['email']['cc_addrs'] = to_html($this->email->cc_addrs_names);
5667 $meta['email']['reply_to_addr'] = to_html($this->email->reply_to_addr);
5668 $return['meta'] = $meta;
5674 * Takes a long list of email addresses from a To or CC field and shows the first 3, the rest hidden
5675 * @param string emails
5678 function collapseLongMailingList($emails) {
5679 global $app_strings;
5681 $ex = explode(",", $emails);
5685 if(count($ex) > 3) {
5689 foreach($ex as $email) {
5691 if(!empty($emails)) {
5694 $emails .= trim($email);
5696 if(!empty($emailsHidden)) {
5697 $emailsHidden .= ", ";
5699 $emailsHidden .= trim($email);
5705 if(!empty($emailsHidden)) {
5707 $emails = "<span onclick='javascript:SUGAR.email2.detailView.showFullEmailList(this);' style='cursor:pointer;'>{$emails} [...{$j} {$app_strings['LBL_MORE']}]</span>";
5708 $emailsHidden = "<span onclick='javascript:SUGAR.email2.detailView.showCroppedEmailList(this)' style='cursor:pointer; display:none;'>{$email2}, {$emailsHidden} [ {$app_strings['LBL_LESS']} ]</span>";
5711 $emails .= $emailsHidden;
5719 * Sorts IMAP's imap_fetch_overview() results
5720 * @param array $arr Array of standard objects
5721 * @param string $sort Column to sort by
5722 * @param string direction Direction to sort by (asc/desc)
5723 * @return array Sorted array of obj.
5725 function sortFetchedOverview($arr, $sort=4, $direction='DESC', $forceSeen=false) {
5726 global $current_user;
5728 $sortPrefs = $current_user->getPreference('folderSortOrder', 'Emails');
5729 if(!empty($sortPrefs))
5730 $listPrefs = $sortPrefs;
5732 $listPrefs = array();
5734 if(isset($listPrefs[$this->id][$this->mailbox])) {
5735 $currentNode = $listPrefs[$this->id][$this->mailbox];
5738 if(isset($currentNode['current']) && !empty($currentNode['current'])) {
5739 $sort = $currentNode['current']['sort'];
5740 $direction = $currentNode['current']['direction'];
5745 $sort = $this->defaultSort;//4;
5746 $direction = $this->defaultDirection; //'DESC';
5747 } elseif(!is_numeric($sort)) {
5748 // handle bad sort index
5749 $sort = $this->defaultSort;
5751 // translate numeric index to human readable
5752 $sort = $this->hrSort[$sort];
5754 if(empty($direction)) {
5755 $direction = 'DESC';
5763 foreach($arr as $k => $overview) {
5764 $sorts['flagged'][$k] = $overview->flagged;
5765 $sorts['status'][$k] = $overview->answered;
5766 $sorts['from'][$k] = str_replace('"', "", $this->handleMimeHeaderDecode($overview->from));
5767 $sorts['subj'][$k] = $this->handleMimeHeaderDecode(quoted_printable_decode($overview->subject));
5768 $sorts['date'][$k] = $overview->date;
5772 natcasesort($sorts[$sort]);
5773 //_ppd($sorts[$sort]);
5775 if(strtolower($direction) == 'desc') {
5776 $revSorts = array();
5777 $keys = array_reverse(array_keys($sorts[$sort]));
5778 // _pp("count keys in DESC: ".count($keys));
5779 // _pp("count elements in sort[sort]: ".count($sorts[$sort]));
5781 for($i=0; $i<count($keys); $i++) {
5783 $revSorts[$v] = $sorts[$sort][$v];
5786 //_pp("count post-sort: ".count($revSorts));
5787 $sorts[$sort] = $revSorts;
5789 $timedate = TimeDate::getInstance();
5790 foreach($sorts[$sort] as $k2 => $overview2) {
5791 $arr[$k2]->date = $timedate->fromString($arr[$k2]->date)->asDb();
5792 $retArr[] = $arr[$k2];
5794 //_pp("final count: ".count($retArr));
5796 $finalReturn = array();
5797 $finalReturn['retArr'] = $retArr;
5798 $finalReturn['sortBy'] = $sort;
5799 $finalReturn['direction'] = $direction;
5800 return $finalReturn;
5804 function setReadFlagOnFolderCache($mbox, $uid) {
5805 global $sugar_config;
5807 $this->mailbox = $mbox;
5810 if($this->validCacheExists($this->mailbox)) {
5811 $ret = $this->getCacheValue($this->mailbox);
5815 foreach($ret as $k => $v) {
5816 if($v->imap_uid == $uid) {
5823 $this->setCacheValue($this->mailbox, array(), $updates);
5828 * Returns a list of emails in a mailbox.
5829 * @param string mbox Name of mailbox using dot notation paths to display
5830 * @param string $forceRefresh Flag to use cache or not
5832 function displayFolderContents($mbox, $forceRefresh='false', $page) {
5833 global $current_user;
5835 $delimiter = $this->get_stored_options('folderDelimiter');
5837 $mbox = str_replace('.', $delimiter, $mbox);
5840 $this->mailbox = $mbox;
5842 // jchi #9424, get sort and direction from user preference
5844 $direction = 'desc';
5845 $sortSerial = $current_user->getPreference('folderSortOrder', 'Emails');
5846 if(!empty($sortSerial) && !empty($_REQUEST['ieId']) && !empty($_REQUEST['mbox'])) {
5847 $sortArray = unserialize($sortSerial);
5848 $sort = $sortArray[$_REQUEST['ieId']][$_REQUEST['mbox']]['current']['sort'];
5849 $direction = $sortArray[$_REQUEST['ieId']][$_REQUEST['mbox']]['current']['direction'];
5854 if(!empty($_REQUEST['sort']) && !empty($_REQUEST['dir'])) {
5855 $this->email->et->saveListViewSortOrder($_REQUEST['ieId'], $_REQUEST['mbox'], $_REQUEST['sort'], $_REQUEST['dir']);
5856 $sort = $_REQUEST['sort'];
5857 $direction = $_REQUEST['dir'];
5859 $_REQUEST['sort'] = '';
5860 $_REQUEST['dir'] = '';
5866 if($forceRefresh == 'false' && $this->validCacheExists($this->mailbox)) {
5867 $emailSettings = $current_user->getPreference('emailSettings', 'Emails');
5869 // cn: default to a low number until user specifies otherwise
5870 if(empty($emailSettings['showNumInList'])) {
5871 $emailSettings['showNumInList'] = 20;
5874 $ret = $this->getCacheValue($this->mailbox, $emailSettings['showNumInList'], $page, $sort, $direction);
5878 $out = $this->displayFetchedSortedListXML($ret, $mbox);
5880 $metadata = array();
5881 $metadata['mbox'] = $mbox;
5882 $metadata['ieId'] = $this->id;
5883 $metadata['name'] = $this->name;
5884 $metadata['fromCache'] = $cacheUsed ? 1 : 0;
5885 $metadata['out'] = $out;
5891 * For a group email account, create subscriptions for all users associated with the
5892 * team assigned to the account.
5895 function createUserSubscriptionsForGroupAccount()
5898 $team->retrieve($this->team_id);
5899 $usersList = $team->get_team_members(true);
5900 foreach($usersList as $userObject)
5902 $previousSubscriptions = unserialize(base64_decode($userObject->getPreference('showFolders', 'Emails',$userObject)));
5903 if($previousSubscriptions === FALSE)
5904 $previousSubscriptions = array();
5906 $previousSubscriptions[] = $this->id;
5908 $encodedSubs = base64_encode(serialize($previousSubscriptions));
5909 $userObject->setPreference('showFolders',$encodedSubs , '', 'Emails');
5910 $userObject->savePreferencesToDB();
5914 * Create a sugar folder for this inbound email account
5915 * if the Enable Auto Import option is selected
5917 * @return String Id of the sugar folder created.
5919 function createAutoImportSugarFolder()
5921 global $current_user;
5922 $guid = create_guid();
5923 $GLOBALS['log']->debug("Creating Sugar Folder for IE with id $guid");
5924 $folder = new SugarFolder();
5925 $folder->id = $guid;
5926 $folder->new_with_id = TRUE;
5927 $folder->name = $this->name;
5928 $folder->has_child = 0;
5929 $folder->is_group = 1;
5930 $folder->assign_to_id = $current_user->id;
5931 $folder->parent_folder = "";
5934 //If this inbound email is marked as inactive, don't add subscriptions.
5935 $addSubscriptions = ($this->status == 'Inactive' || $this->mailbox_type == 'bounce') ? FALSE : TRUE;
5936 $folder->save($addSubscriptions);
5941 function validCacheExists($mbox) {
5942 $q = "SELECT count(*) c FROM email_cache WHERE ie_id = '{$this->id}'";
5943 $r = $this->db->query($q);
5944 $a = $this->db->fetchByAssoc($r);
5957 function displayFetchedSortedListXML($ret, $mbox) {
5960 global $current_user;
5961 global $sugar_config;
5963 if(empty($ret['retArr'])) {
5967 $tPref = $current_user->getUserDateTimePreferences();
5971 foreach($ret['retArr'] as $msg) {
5973 $flagged = ($msg->flagged == 0) ? "" : $this->iconFlagged;
5974 $status = ($msg->deleted) ? $this->iconDeleted : "";
5975 $status = ($msg->draft == 0) ? $status : $this->iconDraft;
5976 $status = ($msg->answered == 0) ? $status : $this->iconAnswered;
5977 $from = $this->handleMimeHeaderDecode($msg->from);
5978 $subject = $this->handleMimeHeaderDecode($msg->subject);
5979 //$date = date($tPref['date']." ".$tPref['time'], $msg->date);
5980 $date = $timedate->to_display_date_time($msg->date);
5981 //$date = date($tPref['date'], $this->getUnixHeaderDate($msg->date));
5984 $temp['flagged'] = $flagged;
5985 $temp['status'] = $status;
5986 $temp['from'] = to_html($from);
5987 $temp['subject'] = $subject;
5988 $temp['date'] = $date;
5989 $temp['uid'] = $msg->uid; // either from an imap_search() or massaged cache value
5990 $temp['mbox'] = $this->mailbox;
5991 $temp['ieId'] = $this->id;
5992 $temp['site_url'] = $sugar_config['site_url'];
5993 $temp['seen'] = $msg->seen;
5994 $temp['type'] = (isset($msg->type)) ? $msg->type: 'remote';
5995 $temp['to_addrs'] = to_html($msg->to);
5996 $temp['hasAttach'] = '0';
6007 * retrieves the mailboxes for a given account in the following format
6012 [Builder] => Builder
6019 * @param bool $justRaw Default false
6022 function getMailboxes($justRaw=false) {
6023 if($justRaw == true) {
6024 return $this->mailboxarray;
6027 return $this->generateMultiDimArrayFromFlatArray($this->mailboxarray, $this->retrieveDelimiter());
6029 $serviceString = $this->getConnectString('', '', false);
6031 if(strpos($serviceString, 'pop3')) {
6033 $obj->name = $serviceString."INBOX";
6034 $boxes = array("INBOX" => $obj);
6036 $boxes = imap_getmailboxes($this->conn, $serviceString, "*");
6041 // clean MBOX path names
6042 foreach($boxes as $k => $mbox) {
6043 $raw[] = str_replace($serviceString, "", $mbox->name);
6044 if ($mbox->delimiter) {
6045 $delimiter = $mbox->delimiter;
6048 $storedOptions = unserialize(base64_decode($this->stored_options));
6049 $storedOptions['folderDelimiter'] = $delimiter;
6050 $this->stored_options = base64_encode(serialize($storedOptions));
6056 // used by $this->search()
6057 if($justRaw == true) {
6062 // generate a multi-dimensional array to iterate through
6064 foreach($raw as $mbox) {
6065 $ret = $this->sortMailboxes($mbox, $ret, $delimiter);
6072 function getMailBoxesForGroupAccount() {
6073 $mailboxes = $this->generateMultiDimArrayFromFlatArray(explode(",", $this->mailbox), $this->retrieveDelimiter());
6074 $mailboxesArray = $this->generateFlatArrayFromMultiDimArray($mailboxes, $this->retrieveDelimiter());
6075 $mailboxesArray = $this->filterMailBoxFromRaw(explode(",", $this->mailbox), $mailboxesArray);
6076 $this->saveMailBoxFolders($mailboxesArray);
6078 if ($this->mailbox != $this->$email_user) {
6079 $mailboxes = $this->sortMailboxes($this->mailbox, $this->retrieveDelimiter());
6080 $mailboxesArray = $this->generateFlatArrayFromMultiDimArray($mailboxes, $this->retrieveDelimiter());
6081 $this->saveMailBoxFolders($mailboxesArray);
6082 // save mailbox value of an inbound email account to email user
6083 $this->saveMailBoxValueOfInboundEmail();
6085 $mailboxes = $this->getMailboxes();
6091 function saveMailBoxFolders($value) {
6092 if (is_array($value)) {
6093 $value = implode(",", $value);
6095 $this->mailboxarray = explode(",", $value);
6096 $value = $this->db->quoted($value);
6097 $query = "update inbound_email set mailbox = $value where id ='{$this->id}'";
6098 $this->db->query($query);
6101 function insertMailBoxFolders($value) {
6102 $query = "select value from config where category='InboundEmail' and name='{$this->id}'";
6103 $r = $this->db->query($query);
6104 $a = $this->db->fetchByAssoc($r);
6105 if (empty($a['value'])) {
6106 if (is_array($value)) {
6107 $value = implode(",", $value);
6109 $this->mailboxarray = explode(",", $value);
6110 $value = $this->db->quoted($value);
6112 $query = "INSERT INTO config VALUES('InboundEmail', '{$this->id}', $value)";
6113 $this->db->query($query);
6117 function saveMailBoxValueOfInboundEmail() {
6118 $query = "update Inbound_email set mailbox = '{$this->email_user}'";
6119 $this->db->query($query);
6122 function retrieveMailBoxFolders() {
6123 $this->mailboxarray = explode(",", $this->mailbox);
6125 $query = "select value from config where category='InboundEmail' and name='{$this->id}'";
6126 $r = $this->db->query($query);
6127 $a = $this->db->fetchByAssoc($r);
6128 $this->mailboxarray = explode(",", $a['value']);
6133 function retrieveDelimiter() {
6134 $delimiter = $this->get_stored_options('folderDelimiter');
6141 function generateFlatArrayFromMultiDimArray($arraymbox, $delimiter) {
6143 foreach($arraymbox as $key => $value) {
6144 $this->generateArrayData($key, $value, $ret, $delimiter);
6150 function generateMultiDimArrayFromFlatArray($raw, $delimiter) {
6151 // generate a multi-dimensional array to iterate through
6153 foreach($raw as $mbox) {
6154 $ret = $this->sortMailboxes($mbox, $ret, $delimiter);
6160 function generateArrayData($key, $arraymbox, &$ret, $delimiter) {
6162 if (is_array($arraymbox)) {
6163 foreach($arraymbox as $mboxKey => $value) {
6164 $newKey = $key . $delimiter . $mboxKey;
6165 $this->generateArrayData($newKey, $value, $ret, $delimiter);
6171 * sorts the folders in a mailbox in a multi-dimensional array
6172 * @param string $MBOX
6176 function sortMailboxes($mbox, $ret, $delimeter = ".") {
6177 if(strpos($mbox, $delimeter)) {
6178 $node = substr($mbox, 0, strpos($mbox, $delimeter));
6179 $nodeAfter = substr($mbox, strpos($mbox, $node) + strlen($node) + 1, strlen($mbox));
6181 if(!isset($ret[$node])) {
6182 $ret[$node] = array();
6183 } elseif(isset($ret[$node]) && !is_array($ret[$node])) {
6184 $ret[$node] = array();
6186 $ret[$node] = $this->sortMailboxes($nodeAfter, $ret[$node], $delimeter);
6188 $ret[$mbox] = $mbox;
6195 * parses Sugar's storage method for imap server service strings
6198 function getServiceString() {
6200 $exServ = explode('::', $this->service);
6202 foreach($exServ as $v) {
6203 if(!empty($v) && ($v != 'imap' && $v !='pop3')) {
6210 } // end class definition
6214 * Simple class to mirror the passed object from an imap_fetch_overview() call
6233 var $indices; /* = array(
6236 'name' => 'mail_date',
6244 'name' => 'mail_from',
6252 'name' => 'mail_subj',
6261 var $fieldDefs;/* = array(
6264 'type' => 'varchar',
6269 'name' => 'subject',
6270 'type' => 'varchar',
6272 'required' => false,
6274 'fromaddr' => array(
6275 'name' => 'fromaddr',
6276 'type' => 'varchar',
6282 'type' => 'varchar',
6286 'senddate' => array(
6287 'name' => 'senddate',
6288 'type' => 'datetime',
6291 'message_id' => array(
6292 'name' => 'message_id',
6293 'type' => 'varchar',
6295 'required' => false,
6297 'mailsize' => array(
6298 'name' => 'mailsize',
6313 'required' => false,
6317 'type' => 'tinyint',
6322 'name' => 'flagged',
6323 'type' => 'tinyint',
6327 'answered' => array(
6328 'name' => 'answered',
6329 'type' => 'tinyint',
6334 'name' => 'deleted',
6335 'type' => 'tinyint',
6341 'type' => 'tinyint',
6347 'type' => 'tinyint',
6353 function Overview() {
6356 if(!isset($dictionary['email_cache']) || empty($dictionary['email_cache'])) {
6357 if(file_exists('custom/metadata/email_cacheMetaData.php')) {
6358 include('custom/metadata/email_cacheMetaData.php');
6360 include('metadata/email_cacheMetaData.php');
6364 $this->fieldDefs = $dictionary['email_cache']['fields'];
6365 $this->indices = $dictionary['email_cache']['indices'];