2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4 * SugarCRM Community Edition is a customer relationship management program developed by
5 * SugarCRM, Inc. Copyright (C) 2004-2012 SugarCRM Inc.
7 * This program is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU Affero General Public License version 3 as published by the
9 * Free Software Foundation with the addition of the following permission added
10 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
14 * This program is distributed in the hope that it will be useful, but WITHOUT
15 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
19 * You should have received a copy of the GNU Affero General Public License along with
20 * this program; if not, see http://www.gnu.org/licenses or write to the Free
21 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
24 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
27 * The interactive user interfaces in modified source and object code versions
28 * of this program must display Appropriate Legal Notices, as required under
29 * Section 5 of the GNU Affero General Public License version 3.
31 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32 * these Appropriate Legal Notices must retain the display of the "Powered by
33 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34 * technical reasons, the Appropriate Legal Notices must display the words
35 * "Powered by SugarCRM".
36 ********************************************************************************/
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, $encode=true, $deleted=true) {
209 $ret = parent::retrieve($id,$encode,$deleted);
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 = $this->convertToUtf8($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 .= $this->convertToUtf8(imap_body($this->conn, $uid, FT_UID));
352 $raw = to_html($raw);
361 * helper method to convert text to utf-8 if necessary
363 * @param string $input text
364 * @return string output text
366 function convertToUtf8($input)
368 $charset = $GLOBALS['locale']->detectCharset($input, true);
370 // we haven't a clue due to missing package?, just return as itself
371 if ($charset === FALSE) {
375 // convert if we can or must
376 return $this->handleCharsetTranslation($input, $charset);
380 * constructs a nicely formatted version of email headers.
384 function getFormattedHeaders($uid) {
387 //if($this->protocol == 'pop3') {
388 // $header = $app_strings['LBL_EMAIL_VIEW_UNSUPPORTED'];
390 if ($this->isPop3Protocol()) {
391 $uid = $this->getCorrectMessageNoForPop3($uid);
393 $headers = imap_fetchheader($this->conn, $uid, FT_UID);
395 $lines = explode("\n", $headers);
397 $header = "<table cellspacing='0' cellpadding='2' border='0' width='100%'>";
399 foreach($lines as $line) {
403 $key = trim(substr($line, 0, strpos($line, ":")));
404 $value = trim(substr($line, strpos($line, ":") + 1));
405 $value = to_html($value);
408 $header .= "<td class='displayEmailLabel' NOWRAP><b>{$key}</b> </td>";
409 $header .= "<td class='displayEmailValueWhite'>{$value} </td>";
414 $header .= "</table>";
420 * Empties Trash folders
422 function emptyTrash() {
423 global $sugar_config;
425 $this->mailbox = $this->get_stored_options("trashFolder");
426 if (empty($this->mailbox)) {
427 $this->mailbox = 'INBOX.Trash';
429 $this->connectMailserver();
431 $uids = imap_search($this->conn, "ALL", SE_UID);
433 foreach($uids as $uid) {
434 if(!imap_delete($this->conn, $uid, FT_UID)) {
435 $lastError = imap_last_error();
436 $GLOBALS['log']->warn("INBOUNDEMAIL: emptyTrash() Could not delete message [ {$uid} ] from [ {$this->mailbox} ]. IMAP_ERROR [ {$lastError} ]");
440 // remove local cache file
441 $q = "DELETE FROM email_cache WHERE mbox = '{$this->mailbox}' AND ie_id = '{$this->id}'";
442 $r = $this->db->query($q);
446 * Fetches a timestamp
448 function getCacheTimestamp($mbox) {
449 $key = $this->db->quote("{$this->id}_{$mbox}");
450 $q = "SELECT ie_timestamp FROM inbound_email_cache_ts WHERE id = '{$key}'";
451 $r = $this->db->query($q);
452 $a = $this->db->fetchByAssoc($r);
457 return $a['ie_timestamp'];
461 * sets the cache timestamp
464 function setCacheTimestamp($mbox) {
465 $key = $this->db->quote("{$this->id}_{$mbox}");
467 $tsOld = $this->getCacheTimestamp($mbox);
470 $q = "INSERT INTO inbound_email_cache_ts (id, ie_timestamp) VALUES ('{$key}', {$ts})";
472 $q = "UPDATE inbound_email_cache_ts SET ie_timestamp = {$ts} WHERE id = '{$key}'";
475 $r = $this->db->query($q, true);
476 $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: setting timestamp query [ {$q} ]");
481 * Gets a count of all rows that are flagged seen = 0
482 * @param string $mbox
485 function getCacheUnreadCount($mbox) {
486 $q = "SELECT count(*) c FROM email_cache WHERE mbox = '{$mbox}' AND seen = 0 AND ie_id = '{$this->id}'";
487 $r = $this->db->query($q);
488 $a = $this->db->fetchByAssoc($r);
494 * Returns total number of emails for a mailbox
498 function getCacheCount($mbox) {
499 $q = "SELECT count(*) c FROM email_cache WHERE mbox = '{$mbox}' AND ie_id = '{$this->id}'";
500 $r = $this->db->query($q);
501 $a = $this->db->fetchByAssoc($r);
506 function getCacheUnread($mbox) {
507 $q = "SELECT count(*) c FROM email_cache WHERE mbox = '{$mbox}' AND ie_id = '{$this->id}' AND seen = '0'";
508 $r = $this->db->query($q);
509 $a = $this->db->fetchByAssoc($r);
516 * Deletes all rows for a given instance
518 function deleteCache() {
519 $q = "DELETE FROM email_cache WHERE ie_id = '{$this->id}'";
521 $GLOBALS['log']->info("INBOUNDEMAIL: deleting cache using query [ {$q} ]");
523 $r = $this->db->query($q);
527 * Deletes all the pop3 data which has been deleted from server
529 function deletePop3Cache() {
530 global $sugar_config;
531 $UIDLs = $this->pop3_getUIDL();
532 $cacheUIDLs = $this->pop3_getCacheUidls();
533 foreach($cacheUIDLs as $msgNo => $msgId) {
534 if (!in_array($msgId, $UIDLs)) {
535 $md5msgIds = md5($msgId);
536 $file = "{$this->EmailCachePath}/{$this->id}/messages/INBOX{$md5msgIds}.PHP";
537 $GLOBALS['log']->debug("INBOUNDEMAIL: deleting file [ {$file} ] ");
538 if(file_exists($file)) {
540 $GLOBALS['log']->debug("INBOUNDEMAIL: Could not delete [ {$file} ] ");
543 $q = "DELETE from email_cache where imap_uid = {$msgNo} AND msgno = {$msgNo} AND ie_id = '{$this->id}' AND message_id = '{$msgId}'";
544 $r = $this->db->query($q);
550 * Retrieves cached headers
553 function getCacheValueForUIDs($mbox, $UIDs) {
554 if (!is_array($UIDs) || empty($UIDs)) {
558 $q = "SELECT * FROM email_cache WHERE ie_id = '{$this->id}' AND mbox = '{$mbox}' AND ";
562 $slicedArray = array_slice($UIDs, $startIndex ,$endIndex);
563 $columnName = ($this->isPop3Protocol() ? "message_id" : "imap_uid");
565 'timestamp' => $this->getCacheTimestamp($mbox),
569 while (!empty($slicedArray)) {
570 $messageIdString = implode(',', $slicedArray);
571 $GLOBALS['log']->debug("sliced array = {$messageIdString}");
572 $extraWhere = "{$columnName} IN (";
574 foreach($slicedArray as $UID) {
576 $extraWhere = $extraWhere . ",";
579 $extraWhere = "{$extraWhere} '{$UID}'";
581 $newQuery = $q . $extraWhere . ")";
582 $r = $this->db->query($newQuery);
584 while($a = $this->db->fetchByAssoc($r)) {
585 if (isset($a['uid'])) {
586 if ($this->isPop3Protocol()) {
587 $ret['uids'][] = $a['message_id'];
589 $ret['uids'][] = $a['uid'];
593 $overview = new Overview();
595 foreach($a as $k => $v) {
599 $overview->imap_uid = $v;
600 if ($this->isPop3Protocol()) {
601 $overview->uid = $a['message_id'];
607 $overview->to = from_html($v);
611 $overview->from = from_html($v);
615 $overview->size = $v;
619 $overview->date = $v;
623 $overview->$k = from_html($v);
627 $ret['retArr'][] = $overview;
629 $startIndex = $startIndex + $endIndex;
630 $slicedArray = array_slice($UIDs, $startIndex ,$endIndex);
631 $messageIdString = implode(',', $slicedArray);
632 $GLOBALS['log']->debug("sliced array = {$messageIdString}");
638 * Retrieves cached headers
641 function getCacheValue($mbox, $limit = 20, $page = 1, $sort='', $direction='') {
642 // try optimizing this call as we don't want repeat queries
643 if(!empty($this->currentCache)) {
644 return $this->currentCache;
647 $sort = (empty($sort)) ? $this->defaultSort : $sort;
648 $direction = (empty($direction)) ? $this->defaultDirection : $direction;
649 $order = " ORDER BY {$this->hrSortLocal[$sort]} {$direction}";
651 $q = "SELECT * FROM email_cache WHERE ie_id = '{$this->id}' AND mbox = '{$mbox}' {$order}";
654 $start = ( $page - 1 ) * $limit;
655 $r = $this->db->limitQuery($q, $start, $limit);
657 $r = $this->db->query($q);
661 'timestamp' => $this->getCacheTimestamp($mbox),
666 while($a = $this->db->fetchByAssoc($r)) {
667 if (isset($a['uid'])) {
668 if ($this->isPop3Protocol()) {
669 $ret['uids'][] = $a['message_id'];
671 $ret['uids'][] = $a['uid'];
675 $overview = new Overview();
677 foreach($a as $k => $v) {
681 $overview->imap_uid = $v;
682 if ($this->isPop3Protocol()) {
683 $overview->uid = $a['message_id'];
689 $overview->to = from_html($v);
693 $overview->from = from_html($v);
697 $overview->size = $v;
701 $overview->date = $v;
705 $overview->$k = from_html($v);
709 $ret['retArr'][] = $overview;
712 $this->currentCache = $ret;
720 function setCacheValue($mbox, $insert, $update=array(), $remove=array()) {
727 // reset in-memory cache
728 $this->currentCache = null;
730 $table = 'email_cache';
731 $where = "WHERE ie_id = '{$this->id}' AND mbox = '{$mbox}'";
733 // handle removed rows
734 if(!empty($remove)) {
736 foreach($remove as $overview) {
737 if(!empty($removeIds)) {
741 $removeIds .= "'{$overview->imap_uid}'";
744 $q = "DELETE FROM {$table} {$where} AND imap_uid IN ({$removeIds})";
746 $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: delete query [ {$q} ]");
748 $r = $this->db->query($q, true, $q);
751 // handle insert rows
752 if(!empty($insert)) {
753 $q = "SELECT imap_uid FROM {$table} {$where}";
754 $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: filter UIDs query [ {$q} ]");
755 $r = $this->db->query($q);
758 while($a = $this->db->fetchByAssoc($r)) {
759 $uids[] = $a['imap_uid'];
761 $count = count($uids);
762 $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: found [ {$count} ] UIDs to filter against");
765 foreach($uids as $uid) {
770 $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: filter UIDs: [ {$tmp} ]");
774 foreach($this->overview->fieldDefs as $colDef) {
778 $cols .= "{$colDef['name']}";
780 foreach($insert as $overview) {
781 if(in_array($overview->imap_uid, $uids))
783 // fixing bug #49543: setting 'mbox' property for the following updating of other items in this box
784 if (!isset($overview->mbox))
786 $overview->mbox = $mbox;
788 $update[] = $overview;
794 foreach($this->overview->fieldDefs as $colDef) {
795 if(!empty($values)) {
799 // trim values for Oracle/MSSql
800 if( isset($colDef['len']) && !empty($colDef['len']) &&
801 isset($colDef['type']) && !empty($colDef['type']) &&
802 $colDef['type'] == 'varchar'
805 if (isset($overview->$colDef['name']))
807 $overview->$colDef['name'] = substr($overview->$colDef['name'], 0, $colDef['len']);
811 switch($colDef['name']) {
813 if(isset($overview->uid) && !empty($overview->uid)) {
814 $this->imap_uid = $overview->uid;
816 $values .= "'{$this->imap_uid}'";
820 $values .= "'{$this->id}'";
824 $values .= $this->db->quoted($overview->to);
828 $values .= $this->db->quoted($overview->from);
832 $values .= $this->db->quoted($overview->message_id);
836 $values .= $overview->size;
840 $conv=$timedate->fromString($overview->date);
842 $values .= $this->db->quoted($conv->asDb());
849 $values .= "'{$mbox}'";
853 $overview->$colDef['name'] = from_html($overview->$colDef['name']);
854 $overview->$colDef['name'] = $this->cleanContent($overview->$colDef['name']);
855 $values .= $this->db->quoted($overview->$colDef['name']);
860 $q = "INSERT INTO {$table} ({$cols}) VALUES ({$values})";
861 $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: insert query [ {$q} ]");
862 $r = $this->db->query($q, true, $q);
866 // handle update rows
867 if(!empty($update)) {
869 foreach($this->overview->fieldDefs as $colDef) {
873 $cols .= "{$colDef['name']}";
876 foreach($update as $overview) {
877 $q = "UPDATE {$table} SET ";
880 foreach($this->overview->fieldDefs as $colDef) {
882 switch($colDef['name']) {
896 if (isset($overview->$colDef['name']))
898 $value = $this->db->quoted($overview->$colDef['name']);
902 $value = $this->db->quoted($value);
904 $set .= "{$colDef['name']} = " . $value;
909 $q .= $set . " WHERE ie_id = '{$this->id}' AND mbox = '{$overview->mbox}' AND imap_uid = '{$overview->imap_uid}'";
910 $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: update query [ {$q} ]");
911 $r = $this->db->query($q, true, $q);
918 * Opens a socket connection to the pop3 server
921 function pop3_open() {
922 if(!is_resource($this->pop3socket)) {
923 $GLOBALS['log']->info("*** INBOUNDEMAIL: opening socket connection");
924 $exServ = explode('::', $this->service);
925 $socket = ($exServ[2] == 'ssl') ? "ssl://" : "tcp://";
926 $socket .= $this->server_url;
927 $this->pop3socket = fsockopen($socket, $this->port);
929 $GLOBALS['log']->info("*** INBOUNDEMAIL: REUSING socket connection");
933 if(!is_resource($this->pop3socket)) {
934 $GLOBALS['log']->debug("*** INBOUNDEMAIL: unable to open socket connection");
939 $ret = trim(fgets($this->pop3socket, 1024));
940 $GLOBALS['log']->info("*** INBOUNDEMAIL: got socket connection [ {$ret} ]");
945 * Closes connections and runs clean-up routines
947 function pop3_cleanUp() {
948 $GLOBALS['log']->info("*** INBOUNDEMAIL: cleaning up socket connection");
949 fputs($this->pop3socket, "QUIT\r\n");
950 $buf = fgets($this->pop3socket, 1024);
951 fclose($this->pop3socket);
955 * sends a command down to the POP3 server
956 * @param string command
961 function pop3_sendCommand($command, $args='', $return=true) {
962 $command .= " {$args}";
963 $command = trim($command);
964 $GLOBALS['log']->info("*** INBOUNDEMAIL: pop3_sendCommand() SEND [ {$command} ]");
967 fputs($this->pop3socket, $command);
970 $ret = trim(fgets($this->pop3socket, 1024));
971 $GLOBALS['log']->info("*** INBOUNDEMAIL: pop3_sendCommand() RECEIVE [ {$ret} ]");
976 function getPop3NewMessagesToDownload() {
977 $pop3UIDL = $this->pop3_getUIDL();
978 $cacheUIDLs = $this->pop3_getCacheUidls();
979 // new email cache values we should deal with
980 $diff = array_diff_assoc($pop3UIDL, $cacheUIDLs);
981 // this is msgNo to UIDL array
982 $diff = $this->pop3_shiftCache($diff, $cacheUIDLs);
983 // get all the keys which are msgnos;
984 return array_keys($diff);
987 function getPop3NewMessagesToDownloadForCron() {
988 $pop3UIDL = $this->pop3_getUIDL();
989 $cacheUIDLs = $this->pop3_getCacheUidls();
990 // new email cache values we should deal with
991 $diff = array_diff_assoc($pop3UIDL, $cacheUIDLs);
992 // this is msgNo to UIDL array
993 $diff = $this->pop3_shiftCache($diff, $cacheUIDLs);
994 // insert data into email_cache
995 if ($this->groupfolder_id != null && $this->groupfolder_id != "" && $this->isPop3Protocol()) {
996 $searchResults = array_keys($diff);
997 $concatResults = implode(",", $searchResults);
998 if ($this->connectMailserver() == 'true') {
999 $fetchedOverviews = imap_fetch_overview($this->conn, $concatResults);
1000 // clean up cache entry
1001 foreach($fetchedOverviews as $k => $overview) {
1002 $overview->message_id = trim($diff[$overview->msgno]);
1003 $fetchedOverviews[$k] = $overview;
1005 $this->updateOverviewCacheFile($fetchedOverviews);
1012 * This method returns all the UIDL for this account. This should be called if the protocol is pop3
1013 * @return array od messageno to UIDL array
1015 function pop3_getUIDL() {
1017 if($this->pop3_open()) {
1019 $this->pop3_sendCommand("USER", $this->email_user);
1020 $this->pop3_sendCommand("PASS", $this->email_password);
1023 $this->pop3_sendCommand("UIDL", '', false); // leave socket buffer alone until the while()
1024 fgets($this->pop3socket, 1024); // handle "OK+";
1029 if(is_resource($this->pop3socket)) {
1030 while(!feof($this->pop3socket)) {
1031 $buf = fgets($this->pop3socket, 1024); // 8kb max buffer - shouldn't be more than 80 chars via pop3...
1034 if(trim($buf) == '.') {
1035 $GLOBALS['log']->debug("*** GOT '.'");
1039 // format is [msgNo] [UIDL]
1040 $exUidl = explode(" ", $buf);
1041 $UIDLs[$exUidl[0]] = trim($exUidl[1]);
1044 $this->pop3_cleanUp();
1050 * Special handler for POP3 boxes. Standard IMAP commands are useless.
1051 * This will fetch only partial emails for POP3 and hence needs to be call again and again based on status it returns
1053 function pop3_checkPartialEmail($synch = false) {
1054 require_once('include/utils/array_utils.php');
1055 global $current_user;
1056 global $sugar_config;
1058 $cacheDataExists = false;
1061 $cacheFilePath = clean_path("{$this->EmailCachePath}/{$this->id}/folders/MsgNOToUIDLData.php");
1062 if(file_exists($cacheFilePath)) {
1063 $cacheDataExists = true;
1064 if($fh = @fopen($cacheFilePath, "rb")) {
1066 $chunksize = 1*(1024*1024); // how many bytes per chunk
1068 $buf = fgets($fh, $chunksize); // 8kb max buffer - shouldn't be more than 80 chars via pop3...
1069 $data = $data . $buf;
1073 $diff = unserialize($data);
1074 if (!empty($diff)) {
1075 if (count($diff)> 50) {
1076 $newDiff = array_slice($diff, 50, count($diff), true);
1080 $results = array_slice(array_keys($diff), 0 ,50);
1081 $data = serialize($newDiff);
1082 if($fh = @fopen($cacheFilePath, "w")) {
1089 if (!$cacheDataExists) {
1091 $this->deletePop3Cache();
1093 $UIDLs = $this->pop3_getUIDL();
1094 if(count($UIDLs) > 0) {
1096 $cacheUIDLs = $this->pop3_getCacheUidls();
1098 // new email cache values we should deal with
1099 $diff = array_diff_assoc($UIDLs, $cacheUIDLs);
1100 $diff = $this->pop3_shiftCache($diff, $cacheUIDLs);
1101 require_once('modules/Emails/EmailUI.php');
1102 EmailUI::preflightEmailCache("{$this->EmailCachePath}/{$this->id}");
1104 if (count($diff)> 50) {
1105 $newDiff = array_slice($diff, 50, count($diff), true);
1110 $results = array_slice(array_keys($diff), 0 ,50);
1111 $data = serialize($newDiff);
1112 if($fh = @fopen($cacheFilePath, "w")) {
1117 $GLOBALS['log']->debug("*** INBOUNDEMAIL: could not open socket connection to POP3 server");
1118 return "could not open socket connection to POP3 server";
1122 // build up msgNo request
1123 if(count($diff) > 0) {
1124 // remove dirty cache entries
1126 if (isset($_REQUEST['currentCount']) && $_REQUEST['currentCount'] > -1) {
1127 $startingNo = $_REQUEST['currentCount'];
1130 $this->mailbox = 'INBOX';
1131 $this->connectMailserver();
1132 //$searchResults = array_keys($diff);
1133 //$fetchedOverviews = array();
1134 //$chunkArraySerachResults = array_chunk($searchResults, 50);
1135 $concatResults = implode(",", $results);
1136 $GLOBALS['log']->info('$$$$ '.$concatResults);
1137 $GLOBALS['log']->info("[EMAIL] Start POP3 fetch overview on mailbox [{$this->mailbox}] for user [{$current_user->user_name}] on 50 data");
1138 $fetchedOverviews = imap_fetch_overview($this->conn, $concatResults);
1139 $GLOBALS['log']->info("[EMAIL] End POP3 fetch overview on mailbox [{$this->mailbox}] for user [{$current_user->user_name}] on "
1140 . sizeof($fetchedOverviews) . " data");
1142 // clean up cache entry
1143 foreach($fetchedOverviews as $k => $overview) {
1144 $overview->message_id = trim($diff[$overview->msgno]);
1145 $fetchedOverviews[$k] = $overview;
1148 $GLOBALS['log']->info("[EMAIL] Start updating overview cache for pop3 mailbox [{$this->mailbox}] for user [{$current_user->user_name}]");
1149 $this->updateOverviewCacheFile($fetchedOverviews);
1150 $GLOBALS['log']->info("[EMAIL] Start updating overview cache for pop3 mailbox [{$this->mailbox}] for user [{$current_user->user_name}]");
1151 return array('status' => "In Progress", 'mbox' => $this->mailbox, 'count'=> (count($results) + $startingNo), 'totalcount' => count($diff), 'ieid' => $this->id);
1153 unlink($cacheFilePath);
1154 return array('status' => "done");
1159 * Special handler for POP3 boxes. Standard IMAP commands are useless.
1161 function pop3_checkEmail() {
1162 if($this->pop3_open()) {
1164 $this->pop3_sendCommand("USER", $this->email_user);
1165 $this->pop3_sendCommand("PASS", $this->email_password);
1168 $this->pop3_sendCommand("UIDL", '', false); // leave socket buffer alone until the while()
1169 fgets($this->pop3socket, 1024); // handle "OK+";
1174 if(is_resource($this->pop3socket)) {
1175 while(!feof($this->pop3socket)) {
1176 $buf = fgets($this->pop3socket, 1024); // 8kb max buffer - shouldn't be more than 80 chars via pop3...
1179 if(trim($buf) == '.') {
1180 $GLOBALS['log']->debug("*** GOT '.'");
1184 // format is [msgNo] [UIDL]
1185 $exUidl = explode(" ", $buf);
1186 $UIDLs[$exUidl[0]] = trim($exUidl[1]);
1190 $this->pop3_cleanUp();
1193 $cacheUIDLs = $this->pop3_getCacheUidls();
1194 // _pp($UIDLs);_pp($cacheUIDLs);
1196 // new email cache values we should deal with
1197 $diff = array_diff_assoc($UIDLs, $cacheUIDLs);
1199 // remove dirty cache entries
1200 $diff = $this->pop3_shiftCache($diff, $cacheUIDLs);
1202 // build up msgNo request
1204 $this->mailbox = 'INBOX';
1205 $this->connectMailserver();
1206 $searchResults = array_keys($diff);
1207 $concatResults = implode(",", $searchResults);
1208 $fetchedOverviews = imap_fetch_overview($this->conn, $concatResults);
1210 // clean up cache entry
1211 foreach($fetchedOverviews as $k => $overview) {
1212 $overview->message_id = trim($diff[$overview->msgno]);
1213 $fetchedOverviews[$k] = $overview;
1216 $this->updateOverviewCacheFile($fetchedOverviews);
1219 $GLOBALS['log']->debug("*** INBOUNDEMAIL: could not open socket connection to POP3 server");
1225 * Iterates through msgno and message_id to remove dirty cache entries
1228 function pop3_shiftCache($diff, $cacheUIDLs) {
1231 $newArray = array();
1232 foreach($diff as $msgNo => $msgId) {
1233 if (in_array($msgId, $cacheUIDLs)) {
1234 $q1 = "UPDATE email_cache SET imap_uid = {$msgNo}, msgno = {$msgNo} WHERE ie_id = '{$this->id}' AND message_id = '{$msgId}'";
1235 $this->db->query($q1);
1237 $newArray[$msgNo] = $msgId;
1242 foreach($diff as $msgNo => $msgId) {
1243 if(!empty($msgNos)) {
1246 if(!empty($msgIds)) {
1251 $msgIds .= "'{$msgId}'";
1254 if(!empty($msgNos)) {
1255 $q1 = "DELETE FROM email_cache WHERE ie_id = '{$this->id}' AND msgno IN ({$msgNos})";
1256 $this->db->query($q1);
1258 if(!empty($msgIds)) {
1259 $q2 = "DELETE FROM email_cache WHERE ie_id = '{$this->id}' AND message_id IN ({$msgIds})";
1260 $this->db->query($q2);
1266 * retrieves cached uidl values.
1267 * When dealing with POP3 accounts, the message_id column in email_cache will contain the UIDL.
1270 function pop3_getCacheUidls() {
1271 $q = "SELECT msgno, message_id FROM email_cache WHERE ie_id = '{$this->id}'";
1272 $r = $this->db->query($q);
1275 while($a = $this->db->fetchByAssoc($r)) {
1276 $ret[$a['msgno']] = $a['message_id'];
1283 * This function is used by cron job for group mailbox without group folder
1284 * @param string $msgno for pop
1285 * @param string $uid for imap
1287 function getMessagesInEmailCache($msgno, $uid) {
1288 $fetchedOverviews = array();
1289 if ($this->isPop3Protocol()) {
1290 $fetchedOverviews = imap_fetch_overview($this->conn, $msgno);
1291 foreach($fetchedOverviews as $k => $overview) {
1292 $overview->message_id = $uid;
1293 $fetchedOverviews[$k] = $overview;
1296 $fetchedOverviews = imap_fetch_overview($this->conn, $uid, FT_UID);
1298 $this->updateOverviewCacheFile($fetchedOverviews);
1303 * Checks email (local caching too) for one mailbox
1304 * @param string $mailbox IMAP Mailbox path
1305 * @param bool $prefetch Flag to prefetch email body on check
1307 function checkEmailOneMailbox($mailbox, $prefetch=true, $synchronize=false) {
1308 global $sugar_config;
1309 global $current_user;
1310 global $app_strings;
1314 $GLOBALS['log']->info("INBOUNDEMAIL: checking mailbox [ {$mailbox} ]");
1315 $this->mailbox = $mailbox;
1316 $this->connectMailserver();
1319 $shouldProcessRules = true;
1321 $timestamp = $this->getCacheTimestamp($mailbox);
1323 if($timestamp > 0) {
1324 $checkTime = date('r', $timestamp);
1327 /* first time through, process ALL emails */
1328 if(empty($checkTime) || $synchronize) {
1329 // do not process rules for the first time or sunchronize
1330 $shouldProcessRules = false;
1331 $criteria = "ALL UNDELETED";
1332 $prefetch = false; // do NOT prefetch emails on a brand new account - timeouts happen.
1333 $GLOBALS['log']->info("INBOUNDEMAIL: new account detected - not prefetching email bodies.");
1335 $criteria = "SINCE \"{$checkTime}\" UNDELETED"; // not using UNSEEN
1337 $this->setCacheTimestamp($mailbox);
1338 $GLOBALS['log']->info("[EMAIL] Performing IMAP search using criteria [{$criteria}] on mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1339 $searchResults = imap_search($this->conn, $criteria, SE_UID);
1340 $GLOBALS['log']->info("[EMAIL] Done IMAP search on mailbox [{$mailbox}] for user [{$current_user->user_name}]. Result count = ".count($searchResults));
1342 if(!empty($searchResults)) {
1344 $concatResults = implode(",", $searchResults);
1345 $GLOBALS['log']->info("[EMAIL] Start IMAP fetch overview on mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1346 $fetchedOverview = imap_fetch_overview($this->conn, $concatResults, FT_UID);
1347 $GLOBALS['log']->info("[EMAIL] Done IMAP fetch overview on mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1349 $GLOBALS['log']->info("[EMAIL] Start updating overview cache for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1350 $this->updateOverviewCacheFile($fetchedOverview);
1351 $GLOBALS['log']->info("[EMAIL] Done updating overview cache for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1354 if($prefetch == true) {
1355 $GLOBALS['log']->info("[EMAIL] Start fetching emails for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1356 if(!$this->fetchCheckedEmails($fetchedOverview))
1360 $GLOBALS['log']->info("[EMAIL] Done fetching emails for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1363 $GLOBALS['log']->info("INBOUNDEMAIL: no results for mailbox [ {$mailbox} ]");
1368 * To handle the use case where an external client is also connected, deleting emails, we need to clear our
1369 * local cache of all emails with the "DELETED" flag
1371 $criteria = 'DELETED';
1372 $criteria .= (!empty($checkTime)) ? " SINCE \"{$checkTime}\"" : "";
1373 $GLOBALS['log']->info("INBOUNDEMAIL: checking for deleted emails using [ {$criteria} ]");
1375 $trashFolder = $this->get_stored_options("trashFolder");
1376 if (empty($trashFolder)) {
1377 $trashFolder = "INBOX.Trash";
1380 if($this->mailbox != $trashFolder) {
1381 $searchResults = imap_search($this->conn, $criteria, SE_UID);
1382 if(!empty($searchResults)) {
1383 $uids = implode($app_strings['LBL_EMAIL_DELIMITER'], $searchResults);
1384 $GLOBALS['log']->info("INBOUNDEMAIL: removing UIDs found deleted [ {$uids} ]");
1385 $this->getOverviewsFromCacheFile($uids, $mailbox, true);
1392 * Checks email (local caching too) for one mailbox
1393 * @param string $mailbox IMAP Mailbox path
1394 * @param bool $prefetch Flag to prefetch email body on check
1396 function checkEmailOneMailboxPartial($mailbox, $prefetch=true, $synchronize=false, $start = 0, $max = -1) {
1397 global $sugar_config;
1398 global $current_user;
1399 global $app_strings;
1401 $GLOBALS['log']->info("INBOUNDEMAIL: checking mailbox [ {$mailbox} ]");
1402 $this->mailbox = $mailbox;
1403 $this->connectMailserver();
1406 $shouldProcessRules = true;
1408 $timestamp = $this->getCacheTimestamp($mailbox);
1410 if($timestamp > 0) {
1411 $checkTime = date('r', $timestamp);
1414 /* first time through, process ALL emails */
1415 if(empty($checkTime) || $synchronize) {
1416 // do not process rules for the first time or sunchronize
1417 $shouldProcessRules = false;
1418 $criteria = "ALL UNDELETED";
1419 $prefetch = false; // do NOT prefetch emails on a brand new account - timeouts happen.
1420 $GLOBALS['log']->info("INBOUNDEMAIL: new account detected - not prefetching email bodies.");
1422 $criteria = "SINCE \"{$checkTime}\" UNDELETED"; // not using UNSEEN
1424 $this->setCacheTimestamp($mailbox);
1425 $GLOBALS['log']->info("[EMAIL] Performing IMAP search using criteria [{$criteria}] on mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1426 $searchResults = $this->getCachedIMAPSearch($criteria);
1428 if(!empty($searchResults)) {
1430 $total = sizeof($searchResults);
1431 $searchResults = array_slice($searchResults, $start, $max);
1433 $GLOBALS['log']->info("INBOUNDEMAIL: there are $total messages in [{$mailbox}], we are on $start");
1434 $GLOBALS['log']->info("INBOUNDEMAIL: getting the next " . sizeof($searchResults) . " messages");
1435 $concatResults = implode(",", $searchResults);
1436 $GLOBALS['log']->info("INBOUNDEMAIL: Start IMAP fetch overview on mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1437 $fetchedOverview = imap_fetch_overview($this->conn, $concatResults, FT_UID);
1438 $GLOBALS['log']->info("INBOUNDEMAIL: Done IMAP fetch overview on mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1440 $GLOBALS['log']->info("INBOUNDEMAIL: Start updating overview cache for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1441 $this->updateOverviewCacheFile($fetchedOverview);
1442 $GLOBALS['log']->info("INBOUNDEMAIL: Done updating overview cache for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1445 if($prefetch == true) {
1446 $GLOBALS['log']->info("INBOUNDEMAIL: Start fetching emails for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1447 $this->fetchCheckedEmails($fetchedOverview);
1448 $GLOBALS['log']->info("INBOUNDEMAIL: Done fetching emails for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1450 $status = ($total > $start + sizeof($searchResults)) ? 'continue' : 'done';
1451 $ret = array('status' => $status, 'count' => $start + sizeof($searchResults), 'mbox' => $mailbox, 'totalcount' => $total);
1452 $GLOBALS['log']->info("INBOUNDEMAIL: $status : Downloaded " . $start + sizeof($searchResults) . "messages of $total");
1455 $GLOBALS['log']->info("INBOUNDEMAIL: no results for mailbox [ {$mailbox} ]");
1456 $ret = array('status' =>'done');
1459 if ($ret['status'] == 'done') {
1460 //Remove the cached search if we are done with this mailbox
1461 $cacheFilePath = clean_path("{$this->EmailCachePath}/{$this->id}/folders/SearchData.php");
1462 unlink($cacheFilePath);
1464 * To handle the use case where an external client is also connected, deleting emails, we need to clear our
1465 * local cache of all emails with the "DELETED" flag
1467 $criteria = 'DELETED';
1468 $criteria .= (!empty($checkTime)) ? " SINCE \"{$checkTime}\"" : "";
1469 $GLOBALS['log']->info("INBOUNDEMAIL: checking for deleted emails using [ {$criteria} ]");
1471 $trashFolder = $this->get_stored_options("trashFolder");
1472 if (empty($trashFolder)) {
1473 $trashFolder = "INBOX.Trash";
1476 if($this->mailbox != $trashFolder) {
1477 $searchResults = imap_search($this->conn, $criteria, SE_UID);
1478 if(!empty($searchResults)) {
1479 $uids = implode($app_strings['LBL_EMAIL_DELIMITER'], $searchResults);
1480 $GLOBALS['log']->info("INBOUNDEMAIL: removing UIDs found deleted [ {$uids} ]");
1481 $this->getOverviewsFromCacheFile($uids, $mailbox, true);
1488 function getCachedIMAPSearch($criteria) {
1489 global $current_user;
1490 global $sugar_config;
1492 $cacheDataExists = false;
1495 $cacheFolderPath = clean_path("{$this->EmailCachePath}/{$this->id}/folders");
1496 if (!file_exists($cacheFolderPath)) {
1497 mkdir_recursive($cacheFolderPath);
1499 $cacheFilePath = $cacheFolderPath . '/SearchData.php';
1500 $GLOBALS['log']->info("INBOUNDEMAIL: Cache path is $cacheFilePath");
1501 if(file_exists($cacheFilePath)) {
1502 $cacheDataExists = true;
1503 if($fh = @fopen($cacheFilePath, "rb")) {
1505 $chunksize = 1*(1024*1024); // how many bytes per chunk
1507 $buf = fgets($fh, $chunksize); // 8kb max buffer - shouldn't be more than 80 chars via pop3...
1508 $data = $data . $buf;
1512 $results = unserialize($data);
1515 if (!$cacheDataExists) {
1516 $searchResults = imap_search($this->conn, $criteria, SE_UID);
1517 if(count($searchResults) > 0) {
1518 $results = $searchResults;
1519 $data = serialize($searchResults);
1520 if($fh = @fopen($cacheFilePath, "w")) {
1529 function checkEmailIMAPPartial($prefetch=true, $synch = false) {
1530 $GLOBALS['log']->info("*****************INBOUNDEMAIL: at IMAP check partial");
1531 global $sugar_config;
1532 $result = $this->connectMailserver();
1533 if ($result == 'false')
1536 'status' => 'error',
1537 'message' => 'Email server is down'
1540 $mailboxes = $this->getMailboxes(true);
1541 if (!in_array('INBOX', $mailboxes)) {
1542 $mailboxes[] = 'INBOX';
1545 if (isset($_REQUEST['mbox']) && !empty($_REQUEST['mbox']) && isset($_REQUEST['currentCount'])) {
1546 $GLOBALS['log']->info("INBOUNDEMAIL: Picking up from where we left off");
1547 $mbox = $_REQUEST['mbox'];
1548 $count = $_REQUEST['currentCount'];
1551 $GLOBALS['log']->info("INBOUNDEMAIL: Cleaning out the cache");
1552 $this->cleanOutCache();
1554 $mbox = $mailboxes[0];
1557 $GLOBALS['log']->info("INBOUNDEMAIL:found " . sizeof($mailboxes) . " Mailboxes");
1558 $index = array_search($mbox, $mailboxes) + 1;
1559 $ret = $this->checkEmailOneMailboxPartial($mbox, $prefetch, $synch, $count, 100);
1560 while($ret['status'] == 'done' && $index < sizeof($mailboxes)) {
1561 if ($ret['count'] > 100) {
1562 $ret['mbox'] = $mailboxes[$index];
1563 $ret['status'] = 'continue';
1566 $GLOBALS['log']->info("INBOUNDEMAIL: checking account [ $index => $mbox : $count]");
1567 $mbox = $mailboxes[$index];
1568 $ret = $this->checkEmailOneMailboxPartial($mbox, $prefetch, $synch, 0, 100);
1575 function checkEmail2_meta() {
1576 global $sugar_config;
1578 $this->connectMailserver();
1579 $mailboxes = $this->getMailboxes(true);
1580 $mailboxes[] = 'INBOX';
1583 $GLOBALS['log']->info("INBOUNDEMAIL: checking account [ {$this->name} ]");
1585 $mailboxes_meta = array();
1586 foreach($mailboxes as $mailbox) {
1587 $mailboxes_meta[$mailbox] = $this->getMailboxProcessCount($mailbox);
1591 $ret['mailboxes'] = $mailboxes_meta;
1593 foreach($mailboxes_meta as $count) {
1594 $ret['processCount'] += $count;
1599 function getMailboxProcessCount($mailbox) {
1600 global $sugar_config;
1602 $GLOBALS['log']->info("INBOUNDEMAIL: checking mailbox [ {$mailbox} ]");
1603 $this->mailbox = $mailbox;
1604 $this->connectMailserver();
1606 $timestamp = $this->getCacheTimestamp($mailbox);
1609 if($timestamp > 0) {
1610 $checkTime = date('r', $timestamp);
1613 /* first time through, process ALL emails */
1614 if(empty($checkTime)) {
1615 $criteria = "ALL UNDELETED";
1616 $prefetch = false; // do NOT prefetch emails on a brand new account - timeouts happen.
1617 $GLOBALS['log']->info("INBOUNDEMAIL: new account detected - not prefetching email bodies.");
1619 $criteria = "SINCE \"{$checkTime}\" UNDELETED"; // not using UNSEEN
1622 $GLOBALS['log']->info("INBOUNDEMAIL: using [ {$criteria} ]");
1623 $searchResults = imap_search($this->conn, $criteria, SE_UID);
1625 if(!empty($searchResults)) {
1626 $concatResults = implode(",", $searchResults);
1628 $GLOBALS['log']->info("INBOUNDEMAIL: no results for mailbox [ {$mailbox} ]");
1631 if(empty($searchResults)) {
1635 return count($searchResults);
1641 function checkEmail($prefetch=true, $synch = false) {
1642 global $sugar_config;
1644 if($this->protocol == 'pop3') {
1645 $this->pop3_checkEmail();
1647 $this->connectMailserver();
1648 $mailboxes = $this->getMailboxes(true);
1651 $GLOBALS['log']->info("INBOUNDEMAIL: checking account [ {$this->name} ]");
1653 foreach($mailboxes as $mailbox) {
1654 $this->checkEmailOneMailbox($mailbox, $prefetch, $synch);
1660 * full synchronization
1662 function syncEmail() {
1663 global $sugar_config;
1664 global $current_user;
1666 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
1668 if(empty($showFolders)) {
1669 $showFolders = array();
1672 $email = new Email();
1673 $email->email2init();
1675 // personal accounts
1676 if($current_user->hasPersonalEmail()) {
1677 $personals = $this->retrieveByGroupId($current_user->id);
1679 foreach($personals as $personalAccount) {
1680 if(in_array($personalAccount->id, $showFolders)) {
1681 $personalAccount->email = $email;
1682 if ($personalAccount->isPop3Protocol()) {
1683 $personalAccount->deletePop3Cache();
1686 $personalAccount->cleanOutCache();
1687 $personalAccount->connectMailserver();
1688 $mailboxes = $personalAccount->getMailboxes(true);
1689 $mailboxes[] = 'INBOX';
1692 $GLOBALS['log']->info("[EMAIL] Start checking account [{$personalAccount->name}] for user [{$current_user->user_name}]");
1694 foreach($mailboxes as $mailbox) {
1695 $GLOBALS['log']->info("[EMAIL] Start checking mailbox [{$mailbox}] of account [{$personalAccount->name}] for user [{$current_user->user_name}]");
1696 $personalAccount->checkEmailOneMailbox($mailbox, false, true);
1697 $GLOBALS['log']->info("[EMAIL] Done checking mailbox [{$mailbox}] of account [{$personalAccount->name}] for user [{$current_user->user_name}]");
1699 $GLOBALS['log']->info("[EMAIL] Done checking account [{$personalAccount->name}] for user [{$current_user->user_name}]");
1705 $beans = $this->retrieveAllByGroupId($current_user->id, false);
1706 foreach($beans as $k => $groupAccount) {
1707 if(in_array($groupAccount->id, $showFolders)) {
1708 $groupAccount->email = $email;
1709 $groupAccount->cleanOutCache();
1710 $groupAccount->connectMailserver();
1711 $mailboxes = $groupAccount->getMailboxes(true);
1712 $mailboxes[] = 'INBOX';
1715 $GLOBALS['log']->info("INBOUNDEMAIL: checking account [ {$groupAccount->name} ]");
1717 foreach($mailboxes as $mailbox) {
1718 $groupAccount->checkEmailOneMailbox($mailbox, false, true);
1726 * Deletes cached messages when moving from folder to folder
1727 * @param string $uids
1728 * @param string $fromFolder
1729 * @param string $toFolder
1731 function deleteCachedMessages($uids, $fromFolder) {
1732 global $sugar_config;
1734 if(!isset($this->email) && !isset($this->email->et)) {
1735 $this->email = new Email();
1736 $this->email->email2init();
1739 $uids = $this->email->et->_cleanUIDList($uids);
1741 foreach($uids as $uid) {
1742 $file = "{$this->EmailCachePath}/{$this->id}/messages/{$fromFolder}{$uid}.php";
1744 if(file_exists($file)) {
1745 if(!unlink($file)) {
1746 $GLOBALS['log']->debug("INBOUNDEMAIL: Could not delete [ {$file} ]");
1753 * similar to imap_fetch_overview, but it gets overviews from a local cache
1755 * @param string $uids UIDs in comma-delimited format
1756 * @param string $mailbox The mailbox in focus, will default to $this->mailbox
1757 * @param bool $remove Default false
1760 function getOverviewsFromCacheFile($uids, $mailbox='', $remove=false) {
1761 global $app_strings;
1762 if(!isset($this->email) && !isset($this->email->et)) {
1763 $this->email = new Email();
1764 $this->email->email2init();
1767 $uids = $this->email->et->_cleanUIDList($uids, true);
1769 // load current cache file
1770 $mailbox = empty($mailbox) ? $this->mailbox : $mailbox;
1771 $cacheValue = $this->getCacheValue($mailbox);
1775 $exUids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
1776 foreach($exUids as $k => $uid) {
1777 $exUids[$k] = trim($uid);
1780 // fill $ret will requested $uids
1781 foreach($cacheValue['retArr'] as $k => $overview) {
1782 if(in_array($overview->imap_uid, $exUids)) {
1787 // remove requested $uids from current cache file (move_mail() type action)
1789 $this->setCacheValue($mailbox, array(), array(), $ret);
1795 * merges new info with the saved cached file
1796 * @param array $array Array of email Overviews
1797 * @param string $type 'append' or 'remove'
1798 * @param string $mailbox Target mailbox if not current assigned
1800 function updateOverviewCacheFile($array, $type='append', $mailbox='') {
1801 $mailbox = empty($mailbox) ? $this->mailbox : $mailbox;
1803 $cacheValue = $this->getCacheValue($mailbox);
1804 $uids = $cacheValue['uids'];
1806 $updateRows = array();
1807 $insertRows = array();
1808 $removeRows = array();
1811 if($type == 'append') { // append
1812 /* we are adding overviews to the cache file */
1813 foreach($array as $overview) {
1814 if(isset($overview->uid)) {
1815 $overview->imap_uid = $overview->uid; // coming from imap_fetch_overview() call
1818 if(!in_array($overview->imap_uid, $uids)) {
1819 $insertRows[] = $overview;
1823 $updatedCacheOverviews = array();
1824 // compare against generated list
1825 /* we are removing overviews from the cache file */
1826 foreach($cacheValue['retArr'] as $cacheOverview) {
1827 if(!in_array($cacheOverview->imap_uid, $uids)) {
1828 $insertRows[] = $cacheOverview;
1830 $removeRows[] = $cacheOverview;
1834 $cacheValue['retArr'] = $updatedCacheOverviews;
1837 $this->setCacheValue($mailbox, $insertRows, $updateRows, $removeRows);
1841 * Check email prefetches email bodies for quicker display
1842 * @param array array of fetched overviews
1844 function fetchCheckedEmails($fetchedOverviews) {
1845 global $sugar_config;
1847 if(is_array($fetchedOverviews) && !empty($fetchedOverviews)) {
1848 foreach($fetchedOverviews as $overview) {
1849 if($overview->size < 10000) {
1851 $uid = $overview->imap_uid;
1854 $file = "{$this->mailbox}{$uid}.php";
1855 $cacheFile = clean_path("{$this->EmailCachePath}/{$this->id}/messages/{$file}");
1857 if(!file_exists($cacheFile)) {
1858 $GLOBALS['log']->info("INBOUNDEMAIL: Prefetching email [ {$file} ]");
1859 $this->setEmailForDisplay($uid);
1860 $out = $this->displayOneEmail($uid, $this->mailbox);
1861 $this->email->et->writeCacheFile('out', $out, $this->id, 'messages', "{$this->mailbox}{$uid}.php");
1863 $GLOBALS['log']->debug("INBOUNDEMAIL: Trying to prefetch an email we already fetched! [ {$cacheFile} ]");
1866 $GLOBALS['log']->debug("*** INBOUNDEMAIL: prefetch has a message with no UID");
1870 $GLOBALS['log']->debug("INBOUNDEMAIL: skipping email prefetch - size too large [ {$overview->size} ]");
1878 * Sets flags on emails. Assumes that connection is live, correct folder is
1880 * @param string $uids Sequence of UIDs, comma separated
1881 * @param string $type Flag to mark
1883 function markEmails($uids, $type) {
1886 $result = imap_clearflag_full($this->conn, $uids, '\\SEEN', ST_UID);
1889 $result = imap_setflag_full($this->conn, $uids, '\\SEEN', ST_UID);
1892 $result = imap_setflag_full($this->conn, $uids, '\\FLAGGED', ST_UID);
1895 $result = imap_clearflag_full($this->conn, $uids, '\\FLAGGED', ST_UID);
1898 $result = imap_setflag_full($this->conn, $uids, '\\Answered', ST_UID);
1902 //// END EMAIL 2.0 SPECIFIC
1903 ///////////////////////////////////////////////////////////////////////////
1907 ///////////////////////////////////////////////////////////////////////////
1908 //// SERVER MANIPULATION METHODS
1910 * Deletes the specified folder
1911 * @param string $mbox "::" delimited IMAP mailbox path, ie, INBOX.saved.stuff
1914 function deleteFolder($mbox) {
1915 $returnArray = array();
1916 if ($this->getCacheCount($mbox) > 0) {
1917 $returnArray['status'] = false;
1918 $returnArray['errorMessage'] = "Can not delete {$mbox} as it has emails.";
1919 return $returnArray;
1921 $connectString = $this->getConnectString('', $mbox);
1922 //Remove Folder cache
1923 global $sugar_config;
1924 unlink("{$this->EmailCachePath}/{$this->id}/folders/folders.php");
1926 if(imap_unsubscribe($this->conn, imap_utf7_encode($connectString))) {
1927 if(imap_deletemailbox($this->conn, $connectString)) {
1928 $this->mailbox = str_replace(("," . $mbox), "", $this->mailbox);
1930 $sessionFoldersString = $this->getSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol);
1931 $sessionFoldersString = str_replace(("," . $mbox), "", $sessionFoldersString);
1932 $this->setSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol, $sessionFoldersString);
1933 $returnArray['status'] = true;
1934 return $returnArray;
1936 $GLOBALS['log']->error("*** ERROR: EMAIL2.0 - could not delete IMAP mailbox with path: [ {$connectString} ]");
1937 $returnArray['status'] = false;
1938 $returnArray['errorMessage'] = "NOOP: could not delete folder: {$connectString}";
1939 return $returnArray;
1943 $GLOBALS['log']->error("*** ERROR: EMAIL2.0 - could not unsubscribe from folder, {$connectString} before deletion.");
1944 $returnArray['status'] = false;
1945 $returnArray['errorMessage'] = "NOOP: could not unsubscribe from folder, {$connectString} before deletion.";
1946 return $returnArray;
1952 * @param string $name Name of new IMAP mailbox
1953 * @param string $mbox "::" delimited IMAP mailbox path, ie, INBOX.saved.stuff
1954 * @return bool True on success
1956 function saveNewFolder($name, $mbox) {
1957 global $sugar_config;
1958 //Remove Folder cache
1959 global $sugar_config;
1960 //unlink("{$this->EmailCachePath}/{$this->id}/folders/folders.php");
1962 //$mboxImap = $this->getImapMboxFromSugarProprietary($mbox);
1963 $delimiter = $this->get_stored_options('folderDelimiter');
1968 $newFolder = $mbox . $delimiter . $name;
1969 $mbox .= $delimiter.str_replace($delimiter, "_", $name);
1970 $connectString = $this->getConnectString('', $mbox);
1972 if(imap_createmailbox($this->conn, imap_utf7_encode($connectString))) {
1973 imap_subscribe($this->conn, imap_utf7_encode($connectString));
1974 $status = imap_status($this->conn, str_replace("{$delimiter}{$name}","",$connectString), SA_ALL);
1975 $this->mailbox = $this->mailbox . "," . $newFolder;
1977 $sessionFoldersString = $this->getSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol);
1978 $sessionFoldersString = $sessionFoldersString . "," . $newFolder;
1979 $this->setSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol, $sessionFoldersString);
1981 echo json_encode($status);
1984 echo "NOOP: could not create folder";
1985 $GLOBALS['log']->error("*** ERROR: EMAIL2.0 - could not create IMAP mailbox with path: [ {$connectString} ]");
1992 * Constructs an IMAP c-client compatible folder path from Sugar proprietary
1993 * @param string $mbox "::" delimited IMAP mailbox path, ie, INBOX.saved.stuff
1996 function getImapMboxFromSugarProprietary($mbox) {
1997 $exMbox = explode("::", $mbox);
2001 for($i=2; $i<count($exMbox); $i++) {
2002 if(!empty($mboxImap)) {
2005 $mboxImap .= $exMbox[$i];
2012 * Searches IMAP (and POP3?) accounts/folders for emails with qualifying criteria
2014 function search($ieId, $subject='', $from='', $to='', $body='', $dateFrom='', $dateTo='') {
2015 global $current_user;
2016 global $app_strings;
2020 $bean = new InboundEmail();
2021 $bean->retrieve($ieId);
2023 //$beans = $this->retrieveAllByGroupId($current_user->id, true);
2025 $subject = urldecode($subject);
2028 $criteria .= (!empty($subject)) ? 'SUBJECT '.from_html($subject).'' : "";
2029 $criteria .= (!empty($from)) ? ' FROM "'.$from.'"' : "";
2030 $criteria .= (!empty($to)) ? ' FROM "'.$to.'"' : "";
2031 $criteria .= (!empty($body)) ? ' TEXT "'.$body.'"' : "";
2032 $criteria .= (!empty($dateFrom)) ? ' SINCE "'.$timedate->fromString($dateFrom)->format('d-M-Y').'"' : "";
2033 $criteria .= (!empty($dateTo)) ? ' BEFORE "'.$timedate->fromString($dateTo)->format('d-M-Y').'"' : "";
2034 //$criteria .= (!empty($from)) ? ' FROM "'.$from.'"' : "";
2036 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
2040 foreach($beans as $bean) {
2041 if(!in_array($bean->id, $showFolders)) {
2045 $GLOBALS['log']->info("*** INBOUNDEMAIL: searching [ {$bean->name} ] for [ {$subject}{$from}{$to}{$body}{$dateFrom}{$dateTo} ]");
2046 $group = (!$bean->is_personal) ? 'group.' : '';
2047 $bean->connectMailServer();
2048 $mailboxes = $bean->getMailboxes(true);
2049 if (!in_array('INBOX', $mailboxes)) {
2050 $mailboxes[] = 'INBOX';
2054 foreach($mailboxes as $mbox) {
2055 $bean->mailbox = $mbox;
2056 $searchOverviews = array();
2057 if ($bean->protocol == 'pop3') {
2058 $pop3Criteria = "SELECT * FROM email_cache WHERE ie_id = '{$bean->id}' AND mbox = '{$mbox}'";
2059 $pop3Criteria .= (!empty($subject)) ? ' AND subject like "%'.$bean->db->quote($subject).'%"' : "";
2060 $pop3Criteria .= (!empty($from)) ? ' AND fromaddr like "%'.$from.'%"' : "";
2061 $pop3Criteria .= (!empty($to)) ? ' AND toaddr like "%'.$to.'%"' : "";
2062 $pop3Criteria .= (!empty($dateFrom)) ? ' AND senddate > "'.$dateFrom.'"' : "";
2063 $pop3Criteria .= (!empty($dateTo)) ? ' AND senddate < "'.$dateTo.'"' : "";
2064 $GLOBALS['log']->info("*** INBOUNDEMAIL: searching [ {$mbox} ] using criteria [ {$pop3Criteria} ]");
2066 $r = $bean->db->query($pop3Criteria);
2067 while($a = $bean->db->fetchByAssoc($r)) {
2068 $overview = new Overview();
2070 foreach($a as $k => $v) {
2074 $overview->imap_uid = $v;
2075 $overview->uid = $a['message_id'];
2078 $overview->to = from_html($v);
2082 $overview->from = from_html($v);
2086 $overview->size = $v;
2090 $overview->date = $timedate->fromString($v)->format('r');
2094 $overview->$k = from_html($v);
2098 $searchOverviews[] = $overview;
2101 $bean->connectMailServer();
2102 $searchResult = imap_search($bean->conn, $criteria, SE_UID);
2103 if (!empty($searchResult)) {
2104 $searchOverviews = imap_fetch_overview($bean->conn, implode(',', $searchResult), FT_UID);
2107 $numHits = count($searchOverviews);
2110 $totalHits = $totalHits + $numHits;
2111 $ret = $bean->sortFetchedOverview($searchOverviews, 'date', 'desc', true);
2112 $mbox = "{$bean->id}.SEARCH";
2113 $out = array_merge($out, $bean->displayFetchedSortedListXML($ret, $mbox, false));
2118 $metadata = array();
2119 $metadata['mbox'] = $app_strings['LBL_EMAIL_SEARCH_RESULTS_TITLE'];
2120 $metadata['ieId'] = $this->id;
2121 $metadata['name'] = $this->name;
2122 $metadata['unreadChecked'] = ($current_user->getPreference('showUnreadOnly', 'Emails') == 1) ? 'CHECKED' : '';
2123 $metadata['out'] = $out;
2129 * repairs the encrypted password for a given I-E account
2130 * @return bool True on success
2132 function repairAccount() {
2134 for($i=0; $i<3; $i++) {
2135 if($i != 0) { // decode is performed on retrieve already
2136 $this->email_password = blowfishDecode(blowfishGetKey('InboundEmail'), $this->email_password);
2139 if($this->connectMailserver() == 'true') {
2140 $this->save(); // save decoded password (is encoded on save())
2149 * soft deletes a User's personal inbox
2150 * @param string id I-E id
2151 * @param string user_name User name of User in focus, NOT current_user
2152 * @return bool True on success
2154 function deletePersonalEmailAccount($id, $user_name) {
2155 $q = "SELECT ie.id FROM inbound_email ie LEFT JOIN users u ON ie.group_id = u.id WHERE u.user_name = '{$user_name}'";
2156 $r = $this->db->query($q, true);
2158 while($a = $this->db->fetchByAssoc($r)) {
2159 if(!empty($a) && $a['id'] == $id) {
2160 $this->retrieve($id);
2169 function getTeamSetIdForTeams($teamIds) {
2170 if(!is_array($teamIds)){
2171 $teamIds = array($teamIds);
2173 $teamSet = new TeamSet();
2174 $team_set_id = $teamSet->addTeams($teamIds);
2175 return $team_set_id;
2179 * Saves Personal Inbox settings for Users
2180 * @param string userId ID of user to assign all emails for this account
2181 * @param strings userName Name of account, for Sugar purposes
2182 * @param bool forceSave Default true. Flag to save errored settings.
2183 * @return boolean true on success, false on fail
2185 function savePersonalEmailAccount($userId = '', $userName = '', $forceSave=true) {
2187 $accountExists = false;
2188 if(isset($_REQUEST['ie_id']) && !empty($_REQUEST['ie_id'])) {
2189 $this->retrieve($_REQUEST['ie_id']);
2190 $accountExists = true;
2192 $ie_name = $_REQUEST['ie_name'];
2194 $this->is_personal = 1;
2195 $this->name = $ie_name;
2196 $this->group_id = $groupId;
2197 $this->status = $_REQUEST['ie_status'];
2198 $this->server_url = trim($_REQUEST['server_url']);
2199 $this->email_user = trim($_REQUEST['email_user']);
2200 if(!empty($_REQUEST['email_password'])) {
2201 $this->email_password = html_entity_decode($_REQUEST['email_password'], ENT_QUOTES);
2203 $this->port = trim($_REQUEST['port']);
2204 $this->protocol = $_REQUEST['protocol'];
2205 if ($this->protocol == "pop3") {
2206 $_REQUEST['mailbox'] = "INBOX";
2208 $this->mailbox = $_REQUEST['mailbox'];
2209 $this->mailbox_type = 'pick'; // forcing this
2212 if(isset($_REQUEST['ssl']) && $_REQUEST['ssl'] == 1) { $useSsl = true; }
2213 else $useSsl = false;
2214 $this->service = '::::::::::';
2217 $id = $this->save(); // saving here to prevent user from having to re-enter all the info in case of error
2218 $this->retrieve($id);
2221 $this->protocol = $_REQUEST['protocol']; // need to set this again since we safe the "service" string to empty explode values
2222 $opts = $this->getSessionConnectionString($this->server_url, $this->email_user, $this->port, $this->protocol);
2223 $detectedOpts = $this->findOptimumSettings($useSsl);
2225 //If $detectedOpts is empty, there was an error connecting, so clear $opts. If $opts was empty, use $detectedOpts
2226 if (empty($opts) || empty($detectedOpts) || (empty($detectedOpts['good']) && empty($detectedOpts['serial'])))
2228 $opts = $detectedOpts;
2230 $delimiter = $this->getSessionInboundDelimiterString($this->server_url, $this->email_user, $this->port, $this->protocol);
2232 if(isset($opts['serial']) && !empty($opts['serial'])) {
2233 $this->service = $opts['serial'];
2234 if(isset($_REQUEST['mark_read']) && $_REQUEST['mark_read'] == 1) {
2235 $this->delete_seen = 0;
2237 $this->delete_seen = 1;
2240 // handle stored_options serialization
2241 if(isset($_REQUEST['only_since']) && $_REQUEST['only_since'] == 1) {
2247 $focusUser = new User();
2248 $focusUser->retrieve($groupId);
2249 $mailerId = (isset($_REQUEST['outbound_email'])) ? $_REQUEST['outbound_email'] : "";
2251 $oe = new OutboundEmail();
2252 $oe->getSystemMailerSettings($focusUser, $mailerId);
2254 $stored_options = array();
2255 $stored_options['from_name'] = trim($_REQUEST['from_name']);
2256 $stored_options['from_addr'] = trim($_REQUEST['from_addr']);
2257 $stored_options['reply_to_addr'] = trim($_REQUEST['reply_to_addr']);
2259 if (!$this->isPop3Protocol()) {
2260 $stored_options['trashFolder'] = (isset($_REQUEST['trashFolder']) ? trim($_REQUEST['trashFolder']) : "");
2261 $stored_options['sentFolder'] = (isset($_REQUEST['sentFolder']) ? trim($_REQUEST['sentFolder']) : "");
2263 $stored_options['only_since'] = $onlySince;
2264 $stored_options['filter_domain'] = '';
2265 $storedOptions['folderDelimiter'] = $delimiter;
2266 $stored_options['outbound_email'] = (isset($_REQUEST['outbound_email'])) ? $_REQUEST['outbound_email'] : $oe->id;
2267 $this->stored_options = base64_encode(serialize($stored_options));
2269 $ieId = $this->save();
2271 //If this is the first personal account the user has setup mark it as default for them.
2272 $currentIECount = $this->getUserPersonalAccountCount($focusUser);
2273 if($currentIECount == 1)
2274 $this->setUsersDefaultOutboundServerId($focusUser, $ieId);
2278 // could not find opts, no save
2279 $GLOBALS['log']->debug('-----> InboundEmail could not find optimums for User: '.$ie_name);
2284 * Determines if this instance of I-E is for a Group Inbox or Personal Inbox
2286 function handleIsPersonal() {
2287 $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.'\'';
2288 $rp = $this->db->query($qp, true);
2289 $personalBox = array();
2290 while($ap = $this->db->fetchByAssoc($rp)) {
2291 $personalBox[] = array($ap['id'], $ap['user_name']);
2293 if(count($personalBox) > 0) {
2300 function getUserNameFromGroupId() {
2301 $r = $this->db->query('SELECT users.user_name FROM users WHERE deleted=0 AND id=\''.$this->group_id.'\'', true);
2302 while($a = $this->db->fetchByAssoc($r)) {
2303 return $a['user_name'];
2308 function getFoldersListForMailBox() {
2310 $foldersList = $this->getSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol);
2311 if (empty($foldersList)) {
2312 global $mod_strings;
2313 $msg = $this->connectMailserver(true);
2314 if (strpos($msg, "successfully")) {
2315 $foldersList = $this->getSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol);
2316 $return['status'] = true;
2317 $return['foldersList'] = $foldersList;
2318 $return['statusMessage'] = "";
2320 $return['status'] = false;
2321 $return['statusMessage'] = $msg;
2324 $return['status'] = true;
2325 $return['foldersList'] = $foldersList;
2326 $return['statusMessage'] = "";
2331 * Programatically determines best-case settings for imap_open()
2333 function findOptimumSettings($useSsl=false, $user='', $pass='', $server='', $port='', $prot='', $mailbox='') {
2334 global $mod_strings;
2335 $serviceArr = array();
2336 $returnService = array();
2337 $badService = array();
2338 $goodService = array();
2339 $errorArr = array();
2341 $retArray = array( 'good' => $goodService,
2342 'bad' => $badService,
2343 'err' => $errorArr);
2345 if(!function_exists('imap_open')) {
2346 $retArray['err'][0] = $mod_strings['ERR_NO_IMAP'];
2350 imap_errors(); // clearing error stack
2351 error_reporting(0); // turn off notices from IMAP
2353 if(isset($_REQUEST['ssl']) && $_REQUEST['ssl'] == 1) {
2357 $exServ = explode('::', $this->service);
2358 $service = '/'.$exServ[1];
2360 $nonSsl = array('both-secure' => '/notls/novalidate-cert/secure',
2361 'both' => '/notls/novalidate-cert',
2362 'nocert-secure' => '/novalidate-cert/secure',
2363 'nocert' => '/novalidate-cert',
2364 'notls-secure' => '/notls/secure',
2365 'secure' => '/secure', // for POP3 servers that force CRAM-MD5
2366 'notls' => '/notls',
2367 'none' => '', // try default nothing
2370 'ssl-both-on-secure' => '/ssl/tls/validate-cert/secure',
2371 'ssl-both-on' => '/ssl/tls/validate-cert',
2372 'ssl-cert-secure' => '/ssl/validate-cert/secure',
2373 'ssl-cert' => '/ssl/validate-cert',
2374 'ssl-tls-secure' => '/ssl/tls/secure',
2375 'ssl-tls' => '/ssl/tls',
2376 'ssl-both-off-secure' => '/ssl/notls/novalidate-cert/secure',
2377 'ssl-both-off' => '/ssl/notls/novalidate-cert',
2378 'ssl-nocert-secure' => '/ssl/novalidate-cert/secure',
2379 'ssl-nocert' => '/ssl/novalidate-cert',
2380 'ssl-notls-secure' => '/ssl/notls/secure',
2381 'ssl-notls' => '/ssl/notls',
2382 'ssl-secure' => '/ssl/secure',
2383 'ssl-none' => '/ssl',
2386 if(isset($user) && !empty($user) && isset($pass) && !empty($pass)) {
2387 $this->email_password = $pass;
2388 $this->email_user = $user;
2389 $this->server_url = $server;
2390 $this->port = $port;
2391 $this->protocol = $prot;
2392 $this->mailbox = $mailbox;
2395 // in case we flip from IMAP to POP3
2396 if($this->protocol == 'pop3')
2397 $this->mailbox = 'INBOX';
2399 //If user has selected multiple mailboxes, we only need to test the first mailbox for the connection string.
2400 $a_mailbox = explode(",", $this->mailbox);
2401 $tmpMailbox = isset($a_mailbox[0]) ? $a_mailbox[0] : "";
2405 foreach($ssl as $k => $service)
2407 $returnService[$k] = 'foo'.$service;
2408 $serviceArr[$k] = '{'.$this->server_url.':'.$this->port.'/service='.$this->protocol.$service.'}'.$tmpMailbox;
2413 foreach($nonSsl as $k => $service)
2415 $returnService[$k] = 'foo'.$service;
2416 $serviceArr[$k] = '{'.$this->server_url.':'.$this->port.'/service='.$this->protocol.$service.'}'.$tmpMailbox;
2420 $GLOBALS['log']->debug('---------------STARTING FINDOPTIMUMS LOOP----------------');
2423 //php imap library will capture c-client library warnings as errors causing good connections to be ignored.
2424 //Check against known warnings to ensure good connections are used.
2425 $acceptableWarnings = array("SECURITY PROBLEM: insecure server advertised AUTH=PLAIN", //c-client auth_pla.c
2426 "Mailbox is empty");
2427 $login = $this->email_user;
2428 $passw = $this->email_password;
2429 $foundGoodConnection = false;
2430 foreach($serviceArr as $k => $serviceTest) {
2433 $GLOBALS['log']->debug($l.': I-E testing string: '.$serviceTest);
2435 // open the connection and try the test string
2436 $this->conn = imap_open($serviceTest, $login, $passw);
2438 if(($errors = imap_last_error()) || ($alerts = imap_alerts())) {
2439 if($errors == 'Too many login failures' || $errors == '[CLOSED] IMAP connection broken (server response)') { // login failure means don't bother trying the rest
2440 $GLOBALS['log']->debug($l.': I-E failed using ['.$serviceTest.']');
2441 $retArray['err'][$k] = $mod_strings['ERR_BAD_LOGIN_PASSWORD'];
2442 $retArray['bad'][$k] = $serviceTest;
2443 $GLOBALS['log']->debug($l.': I-E ERROR: $ie->findOptimums() failed due to bad user credentials for user login: '.$this->email_user);
2445 } elseif( in_array($errors, $acceptableWarnings, TRUE)) { // false positive
2446 $GLOBALS['log']->debug($l.': I-E found good connection but with warnings ['.$serviceTest.'] Errors:' . $errors);
2447 $retArray['good'][$k] = $returnService[$k];
2448 $foundGoodConnection = true;
2451 $GLOBALS['log']->debug($l.': I-E failed using ['.$serviceTest.'] - error: '.$errors);
2452 $retArray['err'][$k] = $errors;
2453 $retArray['bad'][$k] = $serviceTest;
2456 $GLOBALS['log']->debug($l.': I-E found good connect using ['.$serviceTest.']');
2457 $retArray['good'][$k] = $returnService[$k];
2458 $foundGoodConnection = true;
2461 if(is_resource($this->conn)) {
2462 if (!$this->isPop3Protocol()) {
2463 $serviceTest = str_replace("INBOX", "", $serviceTest);
2464 $boxes = imap_getmailboxes($this->conn, $serviceTest, "*");
2466 // clean MBOX path names
2467 foreach($boxes as $k => $mbox) {
2468 $raw[] = $mbox->name;
2469 if ($mbox->delimiter) {
2470 $delimiter = $mbox->delimiter;
2473 $this->setSessionInboundDelimiterString($this->server_url, $this->email_user, $this->port, $this->protocol, $delimiter);
2476 if(!imap_close($this->conn)) $GLOBALS['log']->debug('imap_close() failed!');
2479 $GLOBALS['log']->debug($l.': I-E clearing error and alert stacks.');
2480 imap_errors(); // clear stacks
2482 // If you find a good connection, then don't do any further testing to find URL
2483 if ($foundGoodConnection) {
2488 $GLOBALS['log']->debug('---------------end FINDOPTIMUMS LOOP----------------');
2490 if(!empty($retArray['good'])) {
2495 $newNovalidate_cert = '';
2496 $good = array_pop($retArray['good']); // get most complete string
2497 $exGood = explode('/', $good);
2498 foreach($exGood as $v) {
2507 $newNotls = 'notls';
2510 $newCert = 'validate-cert';
2512 case 'novalidate-cert':
2513 $newNovalidate_cert = 'novalidate-cert';
2521 $goodStr['serial'] = $newTls.'::'.$newCert.'::'.$newSsl.'::'.$this->protocol.'::'.$newNovalidate_cert.'::'.$newNotls.'::'.$secure;
2522 $goodStr['service'] = $good;
2523 $testConnectString = str_replace('foo','', $good);
2524 $testConnectString = '{'.$this->server_url.':'.$this->port.'/service='.$this->protocol.$testConnectString.'}';
2525 $this->setSessionConnectionString($this->server_url, $this->email_user, $this->port, $this->protocol, $goodStr);
2527 foreach($raw as $mbox)
2529 $raw[$i] = str_replace($testConnectString, "", $GLOBALS['locale']->translateCharset($mbox, "UTF7-IMAP", "UTF8" ));
2533 $this->setSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol, implode(",", $raw));
2540 function getSessionConnectionString($server_url, $email_user, $port, $protocol) {
2541 $sessionConnectionString = $server_url . $email_user . $port . $protocol;
2542 return (isset($_SESSION[$sessionConnectionString]) ? $_SESSION[$sessionConnectionString] : "");
2545 function setSessionConnectionString($server_url, $email_user, $port, $protocol, $goodStr) {
2546 $sessionConnectionString = $server_url . $email_user . $port . $protocol;
2547 $_SESSION[$sessionConnectionString] = $goodStr;
2550 function getSessionInboundDelimiterString($server_url, $email_user, $port, $protocol) {
2551 $sessionInboundDelimiterString = $server_url . $email_user . $port . $protocol . "delimiter";
2552 return (isset($_SESSION[$sessionInboundDelimiterString]) ? $_SESSION[$sessionInboundDelimiterString] : "");
2555 function setSessionInboundDelimiterString($server_url, $email_user, $port, $protocol, $delimiter) {
2556 $sessionInboundDelimiterString = $server_url . $email_user . $port . $protocol . "delimiter";
2557 $_SESSION[$sessionInboundDelimiterString] = $delimiter;
2560 function getSessionInboundFoldersString($server_url, $email_user, $port, $protocol) {
2561 $sessionInboundFoldersListString = $server_url . $email_user . $port . $protocol . "foldersList";
2562 return (isset($_SESSION[$sessionInboundFoldersListString]) ? $_SESSION[$sessionInboundFoldersListString] : "");
2565 function setSessionInboundFoldersString($server_url, $email_user, $port, $protocol, $foldersList) {
2566 $sessionInboundFoldersListString = $server_url . $email_user . $port . $protocol . "foldersList";
2567 $_SESSION[$sessionInboundFoldersListString] = $foldersList;
2571 * Checks for duplicate Group User names when creating a new one at save()
2572 * @return GUID returns GUID of Group User if user_name match is
2574 * @return boolean false if NO DUPE IS FOUND
2576 function groupUserDupeCheck() {
2577 $q = "SELECT u.id FROM users u WHERE u.deleted=0 AND u.is_group=1 AND u.user_name = '".$this->name."'";
2578 $r = $this->db->query($q, true);
2580 while($a = $this->db->fetchByAssoc($r)) {
2584 if(strlen($uid) > 0) {
2592 * Returns <option> markup with the contents of Group users
2593 * @param array $groups default empty array
2594 * @return string HTML options
2596 function getGroupsWithSelectOptions($groups = array()) {
2597 $r = $this->db->query('SELECT id, user_name FROM users WHERE users.is_group = 1 AND deleted = 0', true);
2598 if(is_resource($r)) {
2599 while($a = $this->db->fetchByAssoc($r)) {
2600 $groups[$a['id']] = $a['user_name'];
2604 $selectOptions = get_select_options_with_id_separate_key($groups, $groups, $this->group_id);
2605 return $selectOptions;
2609 * handles auto-responses to inbound emails
2611 * @param object email Email passed as reference
2613 function handleAutoresponse(&$email, &$contactAddr) {
2614 if($this->template_id) {
2615 $GLOBALS['log']->debug('found auto-reply template id - prefilling and mailing response');
2617 if($this->getAutoreplyStatus($contactAddr)
2618 && $this->checkOutOfOffice($email->name)
2619 && $this->checkFilterDomain($email)) { // if we haven't sent this guy 10 replies in 24hours
2621 if(!empty($this->stored_options)) {
2622 $storedOptions = unserialize(base64_decode($this->stored_options));
2625 if(!empty($storedOptions['from_name'])) {
2626 $from_name = $storedOptions['from_name'];
2627 $GLOBALS['log']->debug('got from_name from storedOptions: '.$from_name);
2628 } else { // use system default
2629 $rName = $this->db->query('SELECT value FROM config WHERE name = \'fromname\'', true);
2630 if(is_resource($rName)) {
2631 $aName = $this->db->fetchByAssoc($rName);
2633 if(!empty($aName['value'])) {
2634 $from_name = $aName['value'];
2640 if(!empty($storedOptions['from_addr'])) {
2641 $from_addr = $storedOptions['from_addr'];
2643 $rAddr = $this->db->query('SELECT value FROM config WHERE name = \'fromaddress\'', true);
2644 if(is_resource($rAddr)) {
2645 $aAddr = $this->db->fetchByAssoc($rAddr);
2647 if(!empty($aAddr['value'])) {
2648 $from_addr = $aAddr['value'];
2654 $replyToName = (!empty($storedOptions['reply_to_name']))? from_html($storedOptions['reply_to_name']) :$from_name ;
2655 $replyToAddr = (!empty($storedOptions['reply_to_addr'])) ? $storedOptions['reply_to_addr'] : $from_addr;
2658 if(!empty($email->reply_to_email)) {
2659 $to[0]['email'] = $email->reply_to_email;
2661 $to[0]['email'] = $email->from_addr;
2663 // handle to name: address, prefer reply-to
2664 if(!empty($email->reply_to_name)) {
2665 $to[0]['display'] = $email->reply_to_name;
2666 } elseif(!empty($email->from_name)) {
2667 $to[0]['display'] = $email->from_name;
2670 $et = new EmailTemplate();
2671 $et->retrieve($this->template_id);
2672 if(empty($et->subject)) { $et->subject = ''; }
2673 if(empty($et->body)) { $et->body = ''; }
2674 if(empty($et->body_html)) { $et->body_html = ''; }
2676 $reply = new Email();
2677 $reply->type = 'out';
2678 $reply->to_addrs = $to[0]['email'];
2679 $reply->to_addrs_arr = $to;
2680 $reply->cc_addrs_arr = array();
2681 $reply->bcc_addrs_arr = array();
2682 $reply->from_name = $from_name;
2683 $reply->from_addr = $from_addr;
2684 $reply->name = $et->subject;
2685 $reply->description = $et->body;
2686 $reply->description_html = $et->body_html;
2687 $reply->reply_to_name = $replyToName;
2688 $reply->reply_to_addr = $replyToAddr;
2690 $GLOBALS['log']->debug('saving and sending auto-reply email');
2691 //$reply->save(); // don't save the actual email.
2693 $this->setAutoreplyStatus($contactAddr);
2695 $GLOBALS['log']->debug('InboundEmail: auto-reply threshold reached for email ('.$contactAddr.') - not sending auto-reply');
2700 function handleCaseAssignment($email) {
2702 if($caseId = $this->getCaseIdFromCaseNumber($email->name, $c)) {
2703 $c->retrieve($caseId);
2704 $email->retrieve($email->id);
2705 //assign the case info to parent id and parent type so that the case can be linked to the email on Email Save
2706 $email->parent_type = "Cases";
2707 $email->parent_id = $caseId;
2708 // assign the email to the case owner
2709 $email->assigned_user_id = $c->assigned_user_id;
2711 $GLOBALS['log']->debug('InboundEmail found exactly 1 match for a case: '.$c->name);
2718 * handles functionality specific to the Mailbox type (Cases, bounced
2721 * @param object email Email object passed as a reference
2722 * @param object header Header object generated by imap_headerinfo();
2724 function handleMailboxType(&$email, &$header) {
2725 switch($this->mailbox_type) {
2727 $this->handleCaseAssignment($email);
2734 // do something with this?
2737 // do something with leads? we don't have an email_leads table
2743 require_once('modules/Campaigns/ProcessBouncedEmails.php');
2744 campaign_process_bounced_emails($email, $header);
2746 case 'pick': // do all except bounce handling
2747 $GLOBALS['log']->debug('looking for a case for '.$email->name);
2748 $this->handleCaseAssignment($email);
2753 function isMailBoxTypeCreateCase() {
2754 return ($this->mailbox_type == 'createcase' && !empty($this->groupfolder_id));
2757 function handleCreateCase($email, $userId) {
2758 global $current_user, $mod_strings, $current_language;
2759 $mod_strings = return_module_language($current_language, "Emails");
2760 $GLOBALS['log']->debug('In handleCreateCase');
2762 $this->getCaseIdFromCaseNumber($email->name, $c);
2764 if (!$this->handleCaseAssignment($email) && $this->isMailBoxTypeCreateCase()) {
2766 $GLOBALS['log']->debug('retrieveing email');
2767 $email->retrieve($email->id);
2769 $c->description = $email->description;
2770 $c->assigned_user_id = $userId;
2771 $c->name = $email->name;
2773 $c->priority = 'P1';
2775 if(!empty($email->reply_to_email)) {
2776 $contactAddr = $email->reply_to_email;
2778 $contactAddr = $email->from_addr;
2781 $GLOBALS['log']->debug('finding related accounts with address ' . $contactAddr);
2782 if($accountIds = $this->getRelatedId($contactAddr, 'accounts')) {
2783 if (sizeof($accountIds) == 1) {
2784 $c->account_id = $accountIds[0];
2786 $acct = new Account();
2787 $acct->retrieve($c->account_id);
2788 $c->account_name = $acct->name;
2794 $c->retrieve($caseId);
2795 if($c->load_relationship('emails')) {
2796 $c->emails->add($email->id);
2798 if($contactIds = $this->getRelatedId($contactAddr, 'contacts')) {
2799 if(!empty($contactIds) && $c->load_relationship('contacts')) {
2800 $c->contacts->add($contactIds);
2803 $c->email_id = $email->id;
2804 $email->parent_type = "Cases";
2805 $email->parent_id = $caseId;
2806 // assign the email to the case owner
2807 $email->assigned_user_id = $c->assigned_user_id;
2808 $email->name = str_replace('%1', $c->case_number, $c->getEmailSubjectMacro()) . " ". $email->name;
2810 $GLOBALS['log']->debug('InboundEmail created one case with number: '.$c->case_number);
2811 $createCaseTemplateId = $this->get_stored_options('create_case_email_template', "");
2812 if(!empty($this->stored_options)) {
2813 $storedOptions = unserialize(base64_decode($this->stored_options));
2815 if(!empty($createCaseTemplateId)) {
2818 if (!empty($this->stored_options)) {
2819 $fromAddress = $storedOptions['from_addr'];
2820 $fromName = from_html($storedOptions['from_name']);
2821 $replyToName = (!empty($storedOptions['reply_to_name']))? from_html($storedOptions['reply_to_name']) :$fromName ;
2822 $replyToAddr = (!empty($storedOptions['reply_to_addr'])) ? $storedOptions['reply_to_addr'] : $fromAddress;
2824 $defaults = $current_user->getPreferredEmail();
2825 $fromAddress = (!empty($fromAddress)) ? $fromAddress : $defaults['email'];
2826 $fromName = (!empty($fromName)) ? $fromName : $defaults['name'];
2827 $to[0]['email'] = $contactAddr;
2829 // handle to name: address, prefer reply-to
2830 if(!empty($email->reply_to_name)) {
2831 $to[0]['display'] = $email->reply_to_name;
2832 } elseif(!empty($email->from_name)) {
2833 $to[0]['display'] = $email->from_name;
2836 $et = new EmailTemplate();
2837 $et->retrieve($createCaseTemplateId);
2838 if(empty($et->subject)) { $et->subject = ''; }
2839 if(empty($et->body)) { $et->body = ''; }
2840 if(empty($et->body_html)) { $et->body_html = ''; }
2842 $et->subject = "Re:" . " " . str_replace('%1', $c->case_number, $c->getEmailSubjectMacro() . " ". $c->name);
2844 $html = trim($email->description_html);
2845 $plain = trim($email->description);
2847 $email->email2init();
2848 $email->from_addr = $email->from_addr_name;
2849 $email->to_addrs = $email->to_addrs_names;
2850 $email->cc_addrs = $email->cc_addrs_names;
2851 $email->bcc_addrs = $email->bcc_addrs_names;
2852 $email->from_name = $email->from_addr;
2854 $email = $email->et->handleReplyType($email, "reply");
2855 $ret = $email->et->displayComposeEmail($email);
2856 $ret['description'] = empty($email->description_html) ? str_replace("\n", "\n<BR/>", $email->description) : $email->description_html;
2858 $reply = new Email();
2859 $reply->type = 'out';
2860 $reply->to_addrs = $to[0]['email'];
2861 $reply->to_addrs_arr = $to;
2862 $reply->cc_addrs_arr = array();
2863 $reply->bcc_addrs_arr = array();
2864 $reply->from_name = $fromName;
2865 $reply->from_addr = $fromAddress;
2866 $reply->reply_to_name = $replyToName;
2867 $reply->reply_to_addr = $replyToAddr;
2868 $reply->name = $et->subject;
2869 $reply->description = $et->body . "<div><hr /></div>" . $email->description;
2870 if (!$et->text_only) {
2871 $reply->description_html = $et->body_html . "<div><hr /></div>" . $email->description;
2873 $GLOBALS['log']->debug('saving and sending auto-reply email');
2874 //$reply->save(); // don't save the actual email.
2879 if(!empty($email->reply_to_email)) {
2880 $contactAddr = $email->reply_to_email;
2882 $contactAddr = $email->from_addr;
2884 $this->handleAutoresponse($email, $contactAddr);
2890 * handles linking contacts, accounts, etc. to an email
2892 * @param object Email bean to be linked against
2893 * @return string contactAddr is the email address of the sender
2895 function handleLinking(&$email) {
2896 // link email to an User if emails match TO addr
2897 if($userIds = $this->getRelatedId($email->to_addrs, 'users')) {
2898 $GLOBALS['log']->debug('I-E linking email to User');
2899 // link the user to the email
2900 $email->load_relationship('users');
2901 $email->users->add($userIds);
2904 // link email to a Contact, Lead, or Account if the emails match
2905 // give precedence to REPLY-TO above FROM
2906 if(!empty($email->reply_to_email)) {
2907 $contactAddr = $email->reply_to_email;
2909 $contactAddr = $email->from_addr;
2912 // Samir Gandhi : 12/06/07
2913 // This changes has been done because the linking was done only with the from address and
2914 // not with to address
2915 $relationShipAddress = $contactAddr;
2916 if (empty($relationShipAddress)) {
2917 $relationShipAddress .= $email->to_addrs;
2919 $relationShipAddress = $relationShipAddress . "," . $email->to_addrs;
2921 if($leadIds = $this->getRelatedId($relationShipAddress, 'leads')) {
2922 $GLOBALS['log']->debug('I-E linking email to Lead');
2923 $email->load_relationship('leads');
2924 $email->leads->add($leadIds);
2926 foreach($leadIds as $leadId) {
2928 $lead->retrieve($leadId);
2929 $lead->load_relationship('emails');
2930 $lead->emails->add($email->id);
2934 if($contactIds = $this->getRelatedId($relationShipAddress, 'contacts')) {
2935 $GLOBALS['log']->debug('I-E linking email to Contact');
2936 // link the contact to the email
2937 $email->load_relationship('contacts');
2938 $email->contacts->add($contactIds);
2941 if($accountIds = $this->getRelatedId($relationShipAddress, 'accounts')) {
2942 $GLOBALS['log']->debug('I-E linking email to Account');
2943 // link the account to the email
2944 $email->load_relationship('accounts');
2945 $email->accounts->add($accountIds);
2947 /* cn: bug 9171 another cause of dying I-E - bad linking
2948 foreach($accountIds as $accountId) {
2949 $GLOBALS['log']->debug('I-E reverse-linking Accounts to Emails');
2950 $acct = new Account();
2951 $acct->retrieve($accountId);
2952 $acct->load_relationship('emails');
2953 $acct->account_emails->add($email->id);
2957 return $contactAddr;
2961 * Gets part by following breadcrumb path
2962 * @param string $bc the breadcrumb string in format (1.1.1)
2963 * @param array parts the root level parts array
2965 protected function getPartByPath($bc, $parts)
2967 if(strstr($bc,'.')) {
2968 $exBc = explode('.', $bc);
2973 foreach($exBc as $step) {
2974 if(empty($parts)) return false;
2975 $res = $parts[$step-1]; // MIME starts with 1, array starts with 0
2976 if(!empty($res->parts)) {
2977 $parts = $res->parts;
2986 * takes a breadcrumb and returns the encoding at that level
2987 * @param string bc the breadcrumb string in format (1.1.1)
2988 * @param array parts the root level parts array
2989 * @return int retInt Int key to transfer encoding (see handleTranserEncoding())
2991 function getEncodingFromBreadCrumb($bc, $parts) {
2992 if(strstr($bc,'.')) {
2993 $exBc = explode('.', $bc);
2998 $depth = count($exBc);
3000 for($i=0; $i<$depth; $i++) {
3001 $tempObj[$i] = $parts[($exBc[$i]-1)];
3002 $retInt = imap_utf8($tempObj[$i]->encoding);
3003 if(!empty($tempObj[$i]->parts)) {
3004 $parts = $tempObj[$i]->parts;
3011 * retrieves the charset for a given part of an email body
3013 * @param string bc target part of the message in format (1.1.1)
3014 * @param array parts 1 level above ROOT array of Objects representing a multipart body
3015 * @return string charset name
3017 function getCharsetFromBreadCrumb($bc, $parts)
3019 $tempObj = $this->getPartByPath($bc, $parts);
3020 // now we have the tempObj at the end of the breadCrumb trail
3022 if(!empty($tempObj->ifparameters)) {
3023 foreach($tempObj->parameters as $param) {
3024 if(strtolower($param->attribute) == 'charset') {
3025 return $param->value;
3034 * Get the message text from a single mime section, html or plain.
3036 * @param string $msgNo
3037 * @param string $section
3038 * @param stdObject $structure
3041 function getMessageTextFromSingleMimePart($msgNo,$section,$structure)
3043 $msgPartTmp = imap_fetchbody($this->conn, $msgNo, $section);
3044 $enc = $this->getEncodingFromBreadCrumb($section, $structure->parts);
3045 $charset = $this->getCharsetFromBreadCrumb($section, $structure->parts);
3046 $msgPartTmp = $this->handleTranserEncoding($msgPartTmp, $enc);
3047 return $this->handleCharsetTranslation($msgPartTmp, $charset);
3051 * Givin an existing breadcrumb add a cooresponding offset
3054 * @param string $offset
3057 function addBreadCrumbOffset($bc, $offset)
3059 if( (empty($bc) || is_null($bc)) && !empty($offset) )
3062 $a_bc = explode(".", $bc);
3063 $a_offset = explode(".",$offset);
3064 if(count($a_bc) < count($a_offset))
3065 $a_bc = array_merge($a_bc,array_fill( count($a_bc), count($a_offset) - count($a_bc), 0));
3068 for($i=0;$i < count($a_bc); $i++)
3070 if(isset($a_offset[$i]))
3071 $results[] = $a_bc[$i] + $a_offset[$i];
3073 $results[] = $a_bc[$i];
3075 return implode(".", $results);
3079 * returns the HTML text part of a multi-part message
3081 * @param int msgNo the relative message number for the monitored mailbox
3082 * @param string $type the type of text processed, either 'PLAIN' or 'HTML'
3083 * @return string UTF-8 encoded version of the requested message text
3085 function getMessageText($msgNo, $type, $structure, $fullHeader,$clean_email=true, $bcOffset = "") {
3086 global $sugar_config;
3089 $bc = $this->buildBreadCrumbs($structure->parts, $type);
3090 //Add an offset if specified
3091 if(!empty($bcOffset))
3092 $bc = $this->addBreadCrumbOffset($bc, $bcOffset);
3094 if(!empty($bc)) { // multi-part
3095 // HUGE difference between PLAIN and HTML
3096 if($type == 'PLAIN') {
3097 $msgPart = $this->getMessageTextFromSingleMimePart($msgNo,$bc,$structure);
3099 // get part of structure that will
3101 $bcArray = $this->buildBreadCrumbsHTML($structure->parts,$bcOffset);
3102 // construct inline HTML/Rich msg
3103 foreach($bcArray as $bcArryKey => $bcArr) {
3104 foreach($bcArr as $type => $bcTrail) {
3106 $msgPartRaw .= $this->getMessageTextFromSingleMimePart($msgNo,$bcTrail,$structure);
3108 // deal with inline image
3109 $part = $this->getPartByPath($bcTrail, $structure->parts);
3110 if(empty($part) || empty($part->id)) continue;
3111 $partid = substr($part->id, 1, -1); // strip <> around
3112 if(isset($this->inlineImages[$partid])) {
3113 $imageName = $this->inlineImages[$partid];
3114 $newImagePath = "class=\"image\" src=\"{$this->imagePrefix}{$imageName}\"";
3115 $preImagePath = "src=\"cid:$partid\"";
3116 $msgPartRaw = str_replace($preImagePath, $newImagePath, $msgPartRaw);
3121 $msgPart = $msgPartRaw;
3123 } else { // either PLAIN message type (flowed) or b0rk3d RFC
3124 // make sure we're working on valid data here.
3125 if($structure->subtype != $type) {
3129 $decodedHeader = $this->decodeHeader($fullHeader);
3131 // now get actual body contents
3132 $text = imap_body($this->conn, $msgNo);
3134 $upperCaseKeyDecodeHeader = array();
3135 if (is_array($decodedHeader)) {
3136 $upperCaseKeyDecodeHeader = array_change_key_case($decodedHeader, CASE_UPPER);
3138 if(isset($upperCaseKeyDecodeHeader[strtoupper('Content-Transfer-Encoding')])) {
3139 $flip = array_flip($this->transferEncoding);
3140 $text = $this->handleTranserEncoding($text, $flip[strtoupper($upperCaseKeyDecodeHeader[strtoupper('Content-Transfer-Encoding')])]);
3143 if(is_array($upperCaseKeyDecodeHeader['CONTENT-TYPE']) && isset($upperCaseKeyDecodeHeader['CONTENT-TYPE']['charset']) && !empty($upperCaseKeyDecodeHeader['CONTENT-TYPE']['charset'])) {
3144 // we have an explicit content type, use it
3145 $msgPart = $this->handleCharsetTranslation($text, $upperCaseKeyDecodeHeader['CONTENT-TYPE']['charset']);
3147 // make a best guess as to what our content type is
3148 $msgPart = $this->convertToUtf8($text);
3150 } // end else clause
3152 $msgPart = $this->customGetMessageText($msgPart);
3153 // Bug 50241: can't process <?xml:namespace .../> properly. Strip <?xml ...> tag first.
3154 $msgPart = preg_replace("/<\?xml[^>]*>/","",$msgPart);
3156 /* cn: bug 9176 - htmlEntitites hide XSS attacks.
3157 * decode to pass refreshed HTML to HTML_Safe */
3158 if ($type == 'PLAIN')
3159 return $this->cleanXssContent(to_html($msgPart));
3162 $safedMsgPart = $this->cleanContent($msgPart);
3163 return str_replace("<img />", '', $safedMsgPart); /*SKIP_IMAGE_TAG*/
3168 * decodes raw header information and passes back an associative array with
3169 * the important elements key'd by name
3170 * @param header string the raw header
3171 * @return decodedHeader array the associative array
3173 function decodeHeader($fullHeader) {
3174 $decodedHeader = array();
3175 $exHeaders = explode("\r", $fullHeader);
3176 if (!is_array($exHeaders)) {
3177 $exHeaders = explode("\r\n", $fullHeader);
3179 $quotes = array('"', "'");
3181 foreach($exHeaders as $lineNum => $head) {
3183 $key = trim(substr($head, 0, strpos($head, ':')));
3185 $value = trim(substr($head, (strpos($head, ':') + 1), strlen($head)));
3187 // handle content-type section in headers
3188 if(strtolower($key) == 'content-type' && strpos($value, ';')) { // ";" means something follows related to (such as Charset)
3189 $semiColPos = mb_strpos($value, ';');
3190 $strLenVal = mb_strlen($value);
3191 if(($semiColPos + 4) >= $strLenVal) {
3192 // the charset="[something]" is on the next line
3193 $value .= str_replace($quotes, "", trim($exHeaders[$lineNum+1]));
3196 $newValue = array();
3197 $exValue = explode(';', $value);
3198 $newValue['type'] = $exValue[0];
3200 for($i=1; $i<count($exValue); $i++) {
3201 $exContent = explode('=', $exValue[$i]);
3202 $newValue[trim($exContent[0])] = trim($exContent[1], "\t \"");
3207 if(!empty($key) && !empty($value)) {
3208 $decodedHeader[$key] = $value;
3212 return $decodedHeader;
3216 * handles translating message text from orignal encoding into UTF-8
3218 * @param string text test to be re-encoded
3219 * @param string charset original character set
3220 * @return string utf8 re-encoded text
3222 function handleCharsetTranslation($text, $charset) {
3225 if(empty($charset)) {
3226 $GLOBALS['log']->debug("***ERROR: InboundEmail::handleCharsetTranslation() called without a \$charset!");
3227 $GLOBALS['log']->debug("***STACKTRACE: ".print_r(debug_backtrace(), true));
3231 // typical headers have no charset - let destination pick (since it's all ASCII anyways)
3232 if(strtolower($charset) == 'default' || strtolower($charset) == 'utf-8') {
3236 return $locale->translateCharset($text, $charset);
3242 * Builds up the "breadcrumb" trail that imap_fetchbody() uses to return
3243 * parts of an email message, including attachments and inline images
3244 * @param $parts array of objects
3245 * @param $subtype what type of trail to return? HTML? Plain? binaries?
3246 * @param $breadcrumb text trail to build up
3248 function buildBreadCrumbs($parts, $subtype, $breadcrumb = '0') {
3249 //_pp('buildBreadCrumbs building for '.$subtype.' with BC at '.$breadcrumb);
3250 // loop through available parts in the array
3251 foreach($parts as $k => $part) {
3252 // mark passage through level
3254 // if this is not the first time through, start building the map
3255 if($breadcrumb != 0) {
3256 $thisBc = $breadcrumb.'.'.$thisBc;
3259 // found a multi-part/mixed 'part' - keep digging
3260 if($part->type == 1 && (strtoupper($part->subtype) == 'RELATED' || strtoupper($part->subtype) == 'ALTERNATIVE' || strtoupper($part->subtype) == 'MIXED')) {
3261 //_pp('in loop: going deeper with subtype: '.$part->subtype.' $k is: '.$k);
3262 $thisBc = $this->buildBreadCrumbs($part->parts, $subtype, $thisBc);
3265 } elseif(strtolower($part->subtype) == strtolower($subtype)) { // found the subtype we want, return the breadcrumb value
3266 //_pp('found '.$subtype.' bc! returning: '.$thisBc);
3269 //_pp('found '.$part->subtype.' instead');
3275 * Similar to buildBreadCrumbs() but returns an ordered array containing all parts of the message that would be
3276 * considered "HTML" or Richtext (embedded images, formatting, etc.).
3277 * @param array parts Array of parts of a message
3278 * @param int breadcrumb Passed integer value to start breadcrumb trail
3279 * @param array stackedBreadcrumbs Persistent trail of breadcrumbs
3280 * @return array Ordered array of parts to retrieve via imap_fetchbody()
3282 function buildBreadCrumbsHTML($parts, $breadcrumb = '0', $stackedBreadcrumbs = array()) {
3284 $disposition = 'inline';
3286 foreach($parts as $k => $part) {
3287 // mark passage through level
3290 if($breadcrumb != 0) {
3291 $thisBc = $breadcrumb.'.'.$thisBc;
3293 // found a multi-part/mixed 'part' - keep digging
3294 if($part->type == 1 && (strtoupper($part->subtype) == 'RELATED' || strtoupper($part->subtype) == 'ALTERNATIVE' || strtoupper($part->subtype) == 'MIXED')) {
3295 $stackedBreadcrumbs = $this->buildBreadCrumbsHTML($part->parts, $thisBc, $stackedBreadcrumbs);
3297 (strtolower($part->subtype) == strtolower($subtype)) ||
3299 isset($part->disposition) && strtolower($part->disposition) == 'inline' &&
3300 in_array(strtoupper($part->subtype), $this->imageTypes)
3303 // found the subtype we want, return the breadcrumb value
3304 $stackedBreadcrumbs[] = array(strtolower($part->subtype) => $thisBc);
3305 } elseif($part->type == 5) {
3306 $stackedBreadcrumbs[] = array(strtolower($part->subtype) => $thisBc);
3310 return $stackedBreadcrumbs;
3314 * Takes a PHP imap_* object's to/from/cc/bcc address field and converts it
3315 * to a standard string that SugarCRM expects
3316 * @param $arr an array of email address objects
3318 function convertImapToSugarEmailAddress($arr) {
3319 if(is_array($arr)) {
3321 foreach($arr as $key => $obj) {
3322 $addr .= $obj->mailbox.'@'.$obj->host.', ';
3325 $ret = substr_replace($addr,'',-2,-1);
3331 * tries to figure out what character set a given filename is using and
3332 * decode based on that
3334 * @param string name Name of attachment
3335 * @return string decoded name
3337 function handleEncodedFilename($name) {
3338 $imapDecode = imap_mime_header_decode($name);
3339 /******************************
3340 $imapDecode => stdClass Object
3343 [text] => w�hlen.php
3348 $imapDecode => stdClass Object
3350 [charset] => default
3351 [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
3353 *******************************/
3354 if($imapDecode[0]->charset != 'default') { // mime-header encoded charset
3355 $encoding = $imapDecode[0]->charset;
3356 $name = $imapDecode[0]->text; // encoded in that charset
3358 /* encoded filenames are formatted as [encoding]''[filename] */
3359 if(strpos($name, "''") !== false) {
3361 $encoding = substr($name, 0, strpos($name, "'"));
3363 while(strpos($name, "'") !== false) {
3364 $name = trim(substr($name, (strpos($name, "'")+1), strlen($name)));
3367 $name = urldecode($name);
3369 return (strtolower($encoding) == 'utf-8') ? $name : $GLOBALS['locale']->translateCharset($name, $encoding, 'UTF-8');
3373 Primary body types for a part of a mail structure (imap_fetchstructure returned object)
3385 Primary body types for a part of a mail structure (imap_fetchstructure returned object)
3386 @var array $imap_types
3388 public $imap_types = array(
3398 public function getMimeType($type, $subtype)
3400 if(isset($this->imap_types[$type])) {
3401 return $this->imap_types[$type]."/$subtype";
3403 return "other/$subtype";
3408 * Takes the "parts" attribute of the object that imap_fetchbody() method
3409 * returns, and recursively goes through looking for objects that have a
3410 * disposition of "attachement" or "inline"
3411 * @param int $msgNo The relative message number for the monitored mailbox
3412 * @param object $parts Array of objects to examine
3413 * @param string $emailId The GUID of the email saved prior to calling this method
3414 * @param array $breadcrumb Default 0, build up of the parts mapping
3415 * @param bool $forDisplay Default false
3417 function saveAttachments($msgNo, $parts, $emailId, $breadcrumb='0', $forDisplay) {
3418 global $sugar_config;
3420 Primary body types for a part of a mail structure (imap_fetchstructure returned object)
3431 foreach($parts as $k => $part) {
3433 if($breadcrumb != '0') {
3434 $thisBc = $breadcrumb.'.'.$thisBc;
3437 // check if we need to recurse into the object
3438 //if($part->type == 1 && !empty($part->parts)) {
3439 if(isset($part->parts) && !empty($part->parts) && !( isset($part->subtype) && strtolower($part->subtype) == 'rfc822') ) {
3440 $this->saveAttachments($msgNo, $part->parts, $emailId, $thisBc, $forDisplay);
3442 } elseif($part->ifdisposition) {
3443 // we will take either 'attachments' or 'inline'
3444 if(strtolower($part->disposition) == 'attachment' || ((strtolower($part->disposition) == 'inline') && $part->type != 0)) {
3445 $attach = $this->getNoteBeanForAttachment($emailId);
3446 $fname = $this->handleEncodedFilename($this->retrieveAttachmentNameFromStructure($part->dparameters));
3448 if(!empty($fname)) {//assign name to attachment
3449 $attach->name = $fname;
3450 } else {//if name is empty, default to filename
3451 $attach->name = urlencode($this->retrieveAttachmentNameFromStructure($part->dparameters));
3453 $attach->filename = $attach->name;
3454 if (empty($attach->filename)) {
3458 // deal with the MIME types email has
3459 $attach->file_mime_type = $this->getMimeType($part->type, $part->subtype);
3460 $attach->safeAttachmentName();
3462 $attach->id = $this->getTempFilename();
3464 // only save if doing a full import, else we want only the binaries
3467 } // end if disposition type 'attachment'
3468 }// end ifdisposition
3469 //Retrieve contents of subtype rfc8822
3470 elseif ($part->type == 2 && isset($part->subtype) && strtolower($part->subtype) == 'rfc822' )
3472 $tmp_eml = imap_fetchbody($this->conn, $msgNo, $thisBc);
3473 $attach = $this->getNoteBeanForAttachment($emailId);
3474 $attach->file_mime_type = 'messsage/rfc822';
3475 $attach->description = $tmp_eml;
3476 $attach->filename = 'bounce.eml';
3477 $attach->safeAttachmentName();
3479 $attach->id = $this->getTempFilename();
3481 // only save if doing a full import, else we want only the binaries
3484 } elseif(!$part->ifdisposition && $part->type != 1 && $part->type != 2 && $thisBc != '1') {
3485 // No disposition here, but some IMAP servers lie about disposition headers, try to find the truth
3486 // Also Outlook puts inline attachments as type 5 (image) without a disposition
3487 if($part->ifparameters) {
3488 foreach($part->parameters as $param) {
3489 if(strtolower($param->attribute) == "name" || strtolower($param->attribute) == "filename") {
3490 $fname = $this->handleEncodedFilename($param->value);
3494 if(empty($fname)) continue;
3496 // we assume that named parts are attachments too
3497 $attach = $this->getNoteBeanForAttachment($emailId);
3499 $attach->filename = $attach->name = $fname;
3500 $attach->file_mime_type = $this->getMimeType($part->type, $part->subtype);
3502 $attach->safeAttachmentName();
3504 $attach->id = $this->getTempFilename();
3506 // only save if doing a full import, else we want only the binaries
3511 $this->saveAttachmentBinaries($attach, $msgNo, $thisBc, $part, $forDisplay);
3516 * Return a new note object for attachments.
3518 * @param string $emailId
3521 function getNoteBeanForAttachment($emailId)
3523 $attach = new Note();
3524 $attach->parent_id = $emailId;
3525 $attach->parent_type = 'Emails';
3531 * Return the filename of the attachment by examining the dparameters returned from imap_fetch_structure which
3532 * represet the content-disposition of the MIME header.
3534 * @param array $dparamaters
3537 function retrieveAttachmentNameFromStructure($dparamaters)
3541 foreach ($dparamaters as $k => $v)
3543 if( strtolower($v->attribute) == 'filename')
3545 $result = $v->value;
3554 * saves the actual binary file of a given attachment
3555 * @param object attach Note object that is attached to the binary file
3556 * @param string msgNo Message Number on IMAP/POP3 server
3557 * @param string thisBc Breadcrumb to navigate email structure to find the content
3558 * @param object part IMAP standard object that contains the "parts" of this section of email
3559 * @param bool $forDisplay
3561 function saveAttachmentBinaries($attach, $msgNo, $thisBc, $part, $forDisplay) {
3562 // decide where to place the file temporarily
3563 $uploadDir = ($forDisplay) ? "{$this->EmailCachePath}/{$this->id}/attachments/" : "upload://";
3565 // decide what name to save file as
3566 $fileName = $attach->id;
3568 // download the attachment if we didn't do it yet
3569 if(!file_exists($uploadDir.$fileName)) {
3570 $msgPartRaw = imap_fetchbody($this->conn, $msgNo, $thisBc);
3571 // deal with attachment encoding and decode the text string
3572 $msgPart = $this->handleTranserEncoding($msgPartRaw, $part->encoding);
3574 if(file_put_contents($uploadDir.$fileName, $msgPart)) {
3575 $GLOBALS['log']->debug('InboundEmail saved attachment file: '.$attach->filename);
3577 $GLOBALS['log']->debug('InboundEmail could not create attachment file: '.$attach->filename ." - temp file target: [ {$uploadDir}{$fileName} ]");
3582 $this->tempAttachment[$fileName] = urldecode($attach->filename);
3583 // if all was successful, feel for inline and cache Note ID for display:
3584 if((strtolower($part->disposition) == 'inline' && in_array($part->subtype, $this->imageTypes))
3585 || ($part->type == 5)) {
3586 if(copy($uploadDir.$fileName, sugar_cached("images/{$fileName}.").strtolower($part->subtype))) {
3587 $id = substr($part->id, 1, -1); //strip <> around
3588 $this->inlineImages[$id] = $attach->id.".".strtolower($part->subtype);
3590 $GLOBALS['log']->debug('InboundEmail could not copy '.$uploadDir.$fileName.' to cache');
3596 * decodes a string based on its associated encoding
3597 * if nothing is passed, we default to no-encoding type
3598 * @param $str encoded string
3599 * @param $enc detected encoding
3601 function handleTranserEncoding($str, $enc=0) {
3607 $ret = base64_decode($str);
3609 case 4:// QUOTED-PRINTABLE
3610 $ret = quoted_printable_decode($str);
3612 case 0:// 7BIT or 8BIT
3613 case 1:// already in a string-useable format - do nothing
3615 default:// catch all
3625 * Some emails do not get assigned a message_id, specifically from
3628 * We need to derive a reliable one for duplicate import checking.
3630 function getMessageId($header) {
3631 $message_id = md5(print_r($header, true));
3636 * checks for duplicate emails on polling. The uniqueness of a given email message is determined by a concatenation
3637 * of 2 values, the messageID and the delivered-to field. This allows multiple To: and B/CC: destination addresses
3638 * to be imported by Sugar without violating the true duplicate-email issues.
3640 * @param string message_id message ID generated by sending server
3641 * @param int message number (mailserver's key) of email
3642 * @param object header object generated by imap_headerinfo()
3643 * @param string textHeader Headers in normal text format
3646 function importDupeCheck($message_id, $header, $textHeader) {
3647 $GLOBALS['log']->debug('*********** InboundEmail doing dupe check.');
3649 // generate "delivered-to" seed for email duplicate check
3650 $deliveredTo = $this->id; // cn: bug 12236 - cc's failing dupe check
3651 $exHeader = explode("\n", $textHeader);
3653 foreach($exHeader as $headerLine) {
3654 if(strpos(strtolower($headerLine), 'delivered-to:') !== false) {
3655 $deliveredTo = substr($headerLine, strpos($headerLine, " "), strlen($headerLine));
3656 $GLOBALS['log']->debug('********* InboundEmail found [ '.$deliveredTo.' ] as the destination address for email [ '.$message_id.' ]');
3657 } elseif(strpos(strtolower($headerLine), 'x-real-to:') !== false) {
3658 $deliveredTo = substr($headerLine, strpos($headerLine, " "), strlen($headerLine));
3659 $GLOBALS['log']->debug('********* InboundEmail found [ '.$deliveredTo.' ] for non-standards compliant email x-header [ '.$message_id.' ]');
3663 //if(empty($message_id) && !isset($message_id)) {
3664 if(empty($message_id) || !isset($message_id)) {
3665 $GLOBALS['log']->debug('*********** NO MESSAGE_ID.');
3666 $message_id = $this->getMessageId($header);
3669 // generate compound messageId
3670 $this->compoundMessageId = trim($message_id).trim($deliveredTo);
3671 // if the length > 255 then md5 it so that the data will be of smaller length
3672 if (strlen($this->compoundMessageId) > 255) {
3673 $this->compoundMessageId = md5($this->compoundMessageId);
3676 if (empty($this->compoundMessageId)) {
3677 $GLOBALS['log']->error('Inbound Email found a message without a header and message_id');
3681 $potentials = clean_xss($this->compoundMessageId, false);
3683 if(is_array($potentials) && !empty($potentials)) {
3684 foreach($potentials as $bad) {
3685 $this->compoundMessageId = str_replace($bad, "", $this->compoundMessageId);
3689 $query = 'SELECT count(emails.id) AS c FROM emails WHERE emails.message_id = \''.$this->compoundMessageId.'\' and emails.deleted = 0';
3690 $r = $this->db->query($query, true);
3691 $a = $this->db->fetchByAssoc($r);
3694 $GLOBALS['log']->debug('InboundEmail found a duplicate email with ID ('.$this->compoundMessageId.')');
3695 return false; // we have a dupe and don't want to import the email'
3702 * takes the output from imap_mime_hader_decode() and handles multiple types of encoding
3703 * @param string subject Raw subject string from email
3704 * @return string ret properly formatted UTF-8 string
3706 function handleMimeHeaderDecode($subject) {
3707 $subjectDecoded = imap_mime_header_decode($subject);
3710 foreach($subjectDecoded as $object) {
3711 if($object->charset != 'default') {
3712 $ret .= $this->handleCharsetTranslation($object->text, $object->charset);
3714 $ret .= $object->text;
3721 * URL cleanup function
3722 * Until we have comprehensive CSRF protection, we need to sanitize URLs in emails
3723 * to avoid CSRF attacks
3725 public function urlCleaner($attr, $value)
3728 if(strtolower($attr) == "href") return true;
3729 $items = parse_url($value);
3730 if(empty($items)) return false;
3731 if(!empty($items['scheme']) && strtolower($items['scheme']) != 'http' && strtolower($items['scheme']) != 'https') {
3732 // do not touch non-HTTP URLs
3735 // don't allow relative URLs
3736 if(empty($items['host'])) return false;
3737 // allow URLs with no query
3738 if(empty($items['query'])) return true;
3739 // allow URLs that don't start with /? or /index.php?
3740 if(!empty($items['path']) && $items['path'] != '/' && strtolower(substr($items['path'], -10)) != '/index.php') {
3743 // now we have blah-blah/index.php?query - let's see if query looks dangerous
3744 $query_items = array();
3745 parse_str(from_html($items['query']), $query_items);
3746 // weird query, probably harmless
3747 if(empty($query_items)) return true;
3748 // suspiciously like SugarCRM query, reject
3749 if(!empty($query_items['module']) && !empty($query_items['action'])) return false;
3750 // looks like non-download entry point - allow only specific entry points
3751 if(!empty($query_items['entryPoint']) && !in_array($query_items['entryPoint'], array('download', 'image', 'getImage'))) {
3759 * Cleans content for XSS and other types of attack vectors
3760 * @param string str String to clean
3763 function cleanContent($str) {
3765 $this->safe->clear();
3766 $this->safe->setUrlCallback(array($this, "urlCleaner"));
3767 $str = $this->safe->parse($str, false);
3768 return $this->cleanXssContent($str);
3772 * Cleans content for XSS
3773 * @param string str String to clean
3776 function cleanXssContent($str) {
3778 $potentials = clean_xss($str, false);
3779 if(is_array($potentials) && !empty($potentials)) {
3780 foreach($potentials as $bad) {
3781 $str = str_replace($bad, "", $str);
3787 * Calculates the appropriate display date/time sent for an email.
3788 * @param string headerDate The date sent of email in MIME header format
3789 * @return string GMT-0 Unix timestamp
3791 function getUnixHeaderDate($headerDate) {
3794 if (empty($headerDate)) {
3797 ///////////////////////////////////////////////////////////////////
3798 //// CALCULATE CORRECT SENT DATE/TIME FOR EMAIL
3799 if(!empty($headerDate)) {
3800 // Bug 25254 - Strip trailing space that come in some header dates (maybe ones with 1-digit day number)
3801 $headerDate = trim($headerDate);
3802 // need to hack PHP/windows' bad handling of strings when using POP3
3803 if(strstr($headerDate,'+0000 GMT')) {
3804 $headerDate = str_replace('GMT','', $headerDate);
3805 } elseif(!strtotime($headerDate)) {
3806 $headerDate = 'now'; // catch non-standard format times.
3808 // cn: bug 9196 parse the GMT offset
3809 if(strpos($headerDate, '-') || strpos($headerDate, '+')) {
3810 // cn: bug make sure last 5 chars are [+|-]nnnn
3811 if(strpos($headerDate, "(")) {
3812 $headerDate = preg_replace('/\([\w]+\)/i', "", $headerDate);
3813 $headerDate = trim($headerDate);
3816 // parse mailserver time
3817 $gmtEmail = trim(substr($headerDate, -5, 5));
3818 $posNeg = substr($gmtEmail, 0, 1);
3819 $gmtHours = substr($gmtEmail, 1, 2);
3820 $gmtMins = substr($gmtEmail, -2, 2);
3823 $secsHours = $gmtHours * 60 * 60;
3824 $secsTotal = $secsHours + ($gmtMins * 60);
3825 $secsTotal = ($posNeg == '-') ? $secsTotal : -1 * $secsTotal;
3827 $headerDate = trim(substr_replace($headerDate, '', -5)); // mfh: bug 10961/12855 - date time values with GMT offsets not properly formatted
3831 $headerDate = 'now';
3834 $unixHeaderDate = strtotime($headerDate);
3836 if(isset($secsTotal)) {
3837 // this gets the timestamp to true GMT-0
3838 $unixHeaderDate += $secsTotal;
3841 if(strtotime('Jan 1, 2001') > $unixHeaderDate) {
3842 $unixHeaderDate = strtotime('now');
3845 return $unixHeaderDate;
3846 //// END CALCULATE CORRECT SENT DATE/TIME FOR EMAIL
3847 ///////////////////////////////////////////////////////////////////
3851 * This method returns the correct messageno for the pop3 protocol
3852 * @param String UIDL
3853 * @return returnMsgNo
3855 function getCorrectMessageNoForPop3($messageId) {
3857 if ($this->protocol == 'pop3') {
3858 if($this->pop3_open()) {
3859 // get the UIDL from database;
3860 $query = "SELECT msgno FROM email_cache WHERE ie_id = '{$this->id}' AND message_id = '{$messageId}'";
3861 $r = $this->db->query($query);
3862 $a = $this->db->fetchByAssoc($r);
3863 $msgNo = $a['msgno'];
3864 $returnMsgNo = $msgNo;
3867 $this->pop3_sendCommand("USER", $this->email_user);
3868 $this->pop3_sendCommand("PASS", $this->email_password);
3870 // get UIDL for this msgNo
3871 $this->pop3_sendCommand("UIDL {$msgNo}", '', false); // leave socket buffer alone until the while()
3872 $buf = fgets($this->pop3socket, 1024); // handle "OK+ msgNo UIDL(UIDL for this messageno)";
3874 // if it returns OK then we have found the message else get all the UIDL
3875 // and search for the correct msgNo;
3876 $foundMessageNo = false;
3877 if (preg_match("/OK/", $buf) > 0) {
3878 $mailserverResponse = explode(" ", $buf);
3879 // if the cachedUIDL and the UIDL from mail server matches then its the correct messageno
3880 if (trim($mailserverResponse[sizeof($mailserverResponse) - 1]) == $messageId) {
3881 $foundMessageNo = true;
3885 //get all the UIDL and then find the correct messageno
3886 if (!$foundMessageNo) {
3888 $this->pop3_sendCommand("UIDL", '', false); // leave socket buffer alone until the while()
3889 fgets($this->pop3socket, 1024); // handle "OK+";
3892 if(is_resource($this->pop3socket)) {
3893 while(!feof($this->pop3socket)) {
3894 $buf = fgets($this->pop3socket, 1024); // 8kb max buffer - shouldn't be more than 80 chars via pop3...
3895 if(trim($buf) == '.') {
3896 $GLOBALS['log']->debug("*** GOT '.'");
3899 // format is [msgNo] [UIDL]
3900 $exUidl = explode(" ", $buf);
3901 $UIDLs[trim($exUidl[1])] = trim($exUidl[0]);
3903 if (array_key_exists($messageId, $UIDLs)) {
3904 $returnMsgNo = $UIDLs[$messageId];
3906 // message could not be found on server
3912 $this->pop3_cleanUp();
3915 return $returnMsgNo;
3919 * If the importOneEmail returns false, then findout if the duplicate email
3921 function getDuplicateEmailId($msgNo, $uid) {
3923 global $app_strings;
3924 global $app_list_strings;
3925 global $sugar_config;
3926 global $current_user;
3928 $header = imap_headerinfo($this->conn, $msgNo);
3929 $fullHeader = imap_fetchheader($this->conn, $msgNo); // raw headers
3931 // reset inline images cache
3932 $this->inlineImages = array();
3934 // handle messages deleted on server
3935 if(empty($header)) {
3936 if(!isset($this->email) || empty($this->email)) {
3937 $this->email = new Email();
3941 $dupeCheckResult = $this->importDupeCheck($header->message_id, $header, $fullHeader);
3942 if (!$dupeCheckResult && !empty($this->compoundMessageId)) {
3943 // we have a duplicate email
3944 $query = 'SELECT id FROM emails WHERE emails.message_id = \''.$this->compoundMessageId.'\' and emails.deleted = 0';
3945 $r = $this->db->query($query, true);
3946 $a = $this->db->fetchByAssoc($r);
3948 $this->email = new Email();
3949 $this->email->id = $a['id'];
3958 * shiny new importOneEmail() method
3960 * @param bool forDisplay
3961 * @param clean_email boolean, default true,
3963 function importOneEmail($msgNo, $uid, $forDisplay=false, $clean_email=true) {
3964 $GLOBALS['log']->debug("InboundEmail processing 1 email {$msgNo}-----------------------------------------------------------------------------------------");
3966 global $app_strings;
3967 global $app_list_strings;
3968 global $sugar_config;
3969 global $current_user;
3972 // So, on older versions of PHP (PHP VERSION < 5.3),
3973 // calling imap_headerinfo and imap_fetchheader can cause a buffer overflow for exteremly large headers,
3974 // This leads to the remaining messages not being read because Sugar crashes everytime it tries to read the headers.
3975 // The workaround is to mark a message as read before making trying to read the header of the msg in question
3976 // This forces this message not be read again, and we can continue processing remaining msgs.
3978 // UNCOMMENT THIS IF YOU HAVE THIS PROBLEM! See notes on Bug # 45477
3979 // $this->markEmails($uid, "read");
3981 $header = imap_headerinfo($this->conn, $msgNo);
3982 $fullHeader = imap_fetchheader($this->conn, $msgNo); // raw headers
3984 // reset inline images cache
3985 $this->inlineImages = array();
3987 // handle messages deleted on server
3988 if(empty($header)) {
3989 if(!isset($this->email) || empty($this->email)) {
3990 $this->email = new Email();
3994 if ($this->isPop3Protocol()) {
3995 $this->email->name = $app_strings['LBL_EMAIL_ERROR_MESSAGE_DELETED'];
3996 $q = "DELETE FROM email_cache WHERE message_id = '{$uid}' AND ie_id = '{$this->id}' AND mbox = '{$this->mailbox}'";
3998 $this->email->name = $app_strings['LBL_EMAIL_ERROR_IMAP_MESSAGE_DELETED'];
3999 $q = "DELETE FROM email_cache WHERE imap_uid = {$uid} AND ie_id = '{$this->id}' AND mbox = '{$this->mailbox}'";
4001 // delete local cache
4002 $r = $this->db->query($q);
4004 $this->email->date_sent = $timedate->nowDb();
4006 //return "Message deleted from server.";
4009 ///////////////////////////////////////////////////////////////////////
4010 //// DUPLICATE CHECK
4011 $dupeCheckResult = $this->importDupeCheck($header->message_id, $header, $fullHeader);
4012 if($forDisplay || $dupeCheckResult) {
4013 $GLOBALS['log']->debug('*********** NO duplicate found, continuing with processing.');
4015 $structure = imap_fetchstructure($this->conn, $msgNo); // map of email
4017 ///////////////////////////////////////////////////////////////////
4018 //// CREATE SEED EMAIL OBJECT
4019 $email = new Email();
4020 $email->isDuplicate = ($dupeCheckResult) ? false : true;
4021 $email->mailbox_id = $this->id;
4023 $email->id = create_guid();
4024 $email->new_with_id = true; //forcing a GUID here to prevent double saves.
4025 //// END CREATE SEED EMAIL
4026 ///////////////////////////////////////////////////////////////////
4028 ///////////////////////////////////////////////////////////////////
4029 //// PREP SYSTEM USER
4030 if(empty($current_user)) {
4031 // I-E runs as admin, get admin prefs
4033 $current_user = new User();
4034 $current_user->getSystemUser();
4036 $tPref = $current_user->getUserDateTimePreferences();
4038 ///////////////////////////////////////////////////////////////////
4039 if(!empty($header->date)) {
4040 $unixHeaderDate = $timedate->fromString($header->date);
4042 ///////////////////////////////////////////////////////////////////
4043 //// HANDLE EMAIL ATTACHEMENTS OR HTML TEXT
4044 //// Inline images require that I-E handle attachments before body text
4045 // parts defines attachments - be mindful of .html being interpreted as an attachment
4046 if($structure->type == 1 && !empty($structure->parts)) {
4047 $GLOBALS['log']->debug('InboundEmail found multipart email - saving attachments if found.');
4048 $this->saveAttachments($msgNo, $structure->parts, $email->id, 0, $forDisplay);
4049 } elseif($structure->type == 0) {
4050 $uuemail = ($this->isUuencode($email->description)) ? true : false;
4052 * UUEncoded attachments - legacy, but still have to deal with it
4054 * begin 777 filename.txt
4059 // set body to the filtered one
4061 $email->description = $this->handleUUEncodedEmailBody($email->description, $email->id);
4062 $email->retrieve($email->id);
4066 if($this->port != 110) {
4067 $GLOBALS['log']->debug('InboundEmail found a multi-part email (id:'.$msgNo.') with no child parts to parse.');
4070 //// END HANDLE EMAIL ATTACHEMENTS OR HTML TEXT
4071 ///////////////////////////////////////////////////////////////////
4073 ///////////////////////////////////////////////////////////////////
4074 //// ASSIGN APPROPRIATE ATTRIBUTES TO NEW EMAIL OBJECT
4075 // handle UTF-8/charset encoding in the ***headers***
4077 $email->name = $this->handleMimeHeaderDecode($header->subject);
4078 $email->date_start = (!empty($unixHeaderDate)) ? $timedate->asUserDate($unixHeaderDate) : "";
4079 $email->time_start = (!empty($unixHeaderDate)) ? $timedate->asUserTime($unixHeaderDate) : "";
4080 $email->type = 'inbound';
4081 $email->date_created = (!empty($unixHeaderDate)) ? $timedate->asUser($unixHeaderDate) : "";
4082 $email->status = 'unread'; // this is used in Contacts' Emails SubPanel
4083 if(!empty($header->toaddress)) {
4084 $email->to_name = $this->handleMimeHeaderDecode($header->toaddress);
4085 $email->to_addrs_names = $email->to_name;
4087 if(!empty($header->to)) {
4088 $email->to_addrs = $this->convertImapToSugarEmailAddress($header->to);
4090 $email->from_name = $this->handleMimeHeaderDecode($header->fromaddress);
4091 $email->from_addr_name = $email->from_name;
4092 $email->from_addr = $this->convertImapToSugarEmailAddress($header->from);
4093 if(!empty($header->cc)) {
4094 $email->cc_addrs = $this->convertImapToSugarEmailAddress($header->cc);
4096 if(!empty($header->ccaddress)) {
4097 $email->cc_addrs_names = $this->handleMimeHeaderDecode($header->ccaddress);
4099 $email->reply_to_name = $this->handleMimeHeaderDecode($header->reply_toaddress);
4100 $email->reply_to_email = $this->convertImapToSugarEmailAddress($header->reply_to);
4101 if (!empty($email->reply_to_email)) {
4102 $email->reply_to_addr = $email->reply_to_name;
4104 $email->intent = $this->mailbox_type;
4106 $email->message_id = $this->compoundMessageId; // filled by importDupeCheck();
4108 $oldPrefix = $this->imagePrefix;
4110 // Store CIDs in imported messages, convert on display
4111 $this->imagePrefix = "cid:";
4113 // handle multi-part email bodies
4114 $email->description_html= $this->getMessageText($msgNo, 'HTML', $structure, $fullHeader,$clean_email); // runs through handleTranserEncoding() already
4115 $email->description = $this->getMessageText($msgNo, 'PLAIN', $structure, $fullHeader,$clean_email); // runs through handleTranserEncoding() already
4116 $this->imagePrefix = $oldPrefix;
4118 // empty() check for body content
4119 if(empty($email->description)) {
4120 $GLOBALS['log']->debug('InboundEmail Message (id:'.$email->message_id.') has no body');
4124 if (!empty($_REQUEST['user_id'])) {
4125 $email->assigned_user_id = $_REQUEST['user_id'];
4127 // Samir Gandhi : Commented out this code as its not needed
4128 //$email->assigned_user_id = $this->group_id;
4131 //Assign Parent Values if set
4132 if (!empty($_REQUEST['parent_id']) && !empty($_REQUEST['parent_type'])) {
4133 $email->parent_id = $_REQUEST['parent_id'];
4134 $email->parent_type = $_REQUEST['parent_type'];
4136 $mod = strtolower($email->parent_type);
4137 $rel = array_key_exists($mod, $email->field_defs) ? $mod : $mod . "_activities_emails"; //Custom modules rel name
4139 if(! $email->load_relationship($rel) )
4141 $email->$rel->add($email->parent_id);
4144 // override $forDisplay w/user pref
4146 if($this->isAutoImport()) {
4147 $forDisplay = false; // triggers save of imported email
4154 $email->new_with_id = false; // to allow future saves by UPDATE, instead of INSERT
4155 //// ASSIGN APPROPRIATE ATTRIBUTES TO NEW EMAIL OBJECT
4156 ///////////////////////////////////////////////////////////////////
4158 ///////////////////////////////////////////////////////////////////
4159 //// LINK APPROPRIATE BEANS TO NEWLY SAVED EMAIL
4160 //$contactAddr = $this->handleLinking($email);
4161 //// END LINK APPROPRIATE BEANS TO NEWLY SAVED EMAIL
4162 ///////////////////////////////////////////////////////////////////
4164 ///////////////////////////////////////////////////////////////////
4165 //// MAILBOX TYPE HANDLING
4166 $this->handleMailboxType($email, $header);
4167 //// END MAILBOX TYPE HANDLING
4168 ///////////////////////////////////////////////////////////////////
4170 ///////////////////////////////////////////////////////////////////
4171 //// SEND AUTORESPONSE
4172 if(!empty($email->reply_to_email)) {
4173 $contactAddr = $email->reply_to_email;
4175 $contactAddr = $email->from_addr;
4177 if (!$this->isMailBoxTypeCreateCase()) {
4178 $this->handleAutoresponse($email, $contactAddr);
4180 //// END SEND AUTORESPONSE
4181 ///////////////////////////////////////////////////////////////////
4182 //// END IMPORT ONE EMAIL
4183 ///////////////////////////////////////////////////////////////////
4186 // only log if not POP3; pop3 iterates through ALL mail
4187 if($this->protocol != 'pop3') {
4188 $GLOBALS['log']->info("InboundEmail found a duplicate email: ".$header->message_id);
4189 //echo "This email has already been imported";
4193 //// END DUPLICATE CHECK
4194 ///////////////////////////////////////////////////////////////////////
4196 ///////////////////////////////////////////////////////////////////////
4197 //// DEAL WITH THE MAILBOX
4199 $r = imap_setflag_full($this->conn, $msgNo, '\\SEEN');
4201 // if delete_seen, mark msg as deleted
4202 if($this->delete_seen == 1 && !$forDisplay) {
4203 $GLOBALS['log']->info("INBOUNDEMAIL: delete_seen == 1 - deleting email");
4204 imap_setflag_full($this->conn, $msgNo, '\\DELETED');
4207 // for display - don't touch server files?
4208 //imap_setflag_full($this->conn, $msgNo, '\\UNSEEN');
4211 $GLOBALS['log']->debug('********************************* InboundEmail finished import of 1 email: '.$email->name);
4212 //// END DEAL WITH THE MAILBOX
4213 ///////////////////////////////////////////////////////////////////////
4215 ///////////////////////////////////////////////////////////////////////
4216 //// TO SUPPORT EMAIL 2.0
4217 $this->email = $email;
4219 if(empty($this->email->et)) {
4220 $this->email->email2init();
4227 * figures out if a plain text email body has UUEncoded attachments
4228 * @param string string The email body
4229 * @return bool True if UUEncode is detected.
4231 function isUuencode($string) {
4232 $rx = "begin [0-9]{3} .*";
4234 $exBody = explode("\r", $string);
4235 foreach($exBody as $line) {
4236 if(preg_match("/begin [0-9]{3} .*/i", $line)) {
4245 * handles UU Encoded emails - a legacy from pre-RFC 822 which must still be supported (?)
4246 * @param string raw The raw email body
4247 * @param string id Parent email ID
4248 * @return string The filtered email body, stripped of attachments
4250 function handleUUEncodedEmailBody($raw, $id) {
4254 $attachmentBody = '';
4255 $inAttachment = false;
4257 $exRaw = explode("\n", $raw);
4259 foreach($exRaw as $k => $line) {
4260 $line = trim($line);
4262 if(preg_match("/begin [0-9]{3} .*/i", $line, $m)) {
4263 $inAttachment = true;
4264 $fileName = $this->handleEncodedFilename(substr($m[0], 10, strlen($m[0])));
4266 $attachmentBody = ''; // reset for next part of loop;
4271 if(strpos($line, "end") === 0) {
4272 if(!empty($fileName) && !empty($attachmentBody)) {
4273 $this->handleUUDecode($id, $fileName, trim($attachmentBody));
4274 $attachmentBody = ''; // reset for next part of loop;
4278 if($inAttachment === false) {
4279 $emailBody .= "\n".$line;
4281 $attachmentBody .= "\n".$line;
4285 /* 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 */
4286 $emailBody = $locale->translateCharset($emailBody, $locale->getExportCharset(), 'UTF-8');
4291 * wrapper for UUDecode
4292 * @param string id Id of the email
4293 * @param string UUEncode Encode US-ASCII
4295 function handleUUDecode($id, $fileName, $UUEncode) {
4296 global $sugar_config;
4297 /* include PHP_Compat library; it auto-feels for PHP5's compiled convert_uuencode() function */
4298 require_once('include/PHP_Compat/convert_uudecode.php');
4300 $attach = new Note();
4301 $attach->parent_id = $id;
4302 $attach->parent_type = 'Emails';
4304 $fname = $this->handleEncodedFilename($fileName);
4306 if(!empty($fname)) {//assign name to attachment
4307 $attach->name = $fname;
4308 } else {//if name is empty, default to filename
4309 $attach->name = urlencode($fileName);
4312 $attach->filename = urlencode($attach->name);
4314 //get position of last "." in file name
4315 $file_ext_beg = strrpos($attach->filename,".");
4317 //get file extension
4318 if($file_ext_beg >0) {
4319 $file_ext = substr($attach->filename, $file_ext_beg+1);
4321 //check to see if this is a file with extension located in "badext"
4322 foreach($sugar_config['upload_badext'] as $badExt) {
4323 if(strtolower($file_ext) == strtolower($badExt)) {
4324 //if found, then append with .txt and break out of lookup
4325 $attach->name = $attach->name . ".txt";
4326 $attach->file_mime_type = 'text/';
4327 $attach->filename = $attach->filename . ".txt";
4328 break; // no need to look for more
4333 $bin = convert_uudecode($UUEncode);
4334 $filename = "upload://{$attach->id}";
4335 if(file_put_contents($filename, $bin)) {
4336 $GLOBALS['log']->debug('InboundEmail saved attachment file: '.$filename);
4338 $GLOBALS['log']->debug('InboundEmail could not create attachment file: '.$filename);
4343 * returns true if the email's domain is NOT in the filter domain string
4345 * @param object email Email object in question
4346 * @return bool true if not filtered, false if filtered
4348 function checkFilterDomain($email) {
4349 $filterDomain = $this->get_stored_options('filter_domain');
4350 if(!isset($filterDomain) || empty($filterDomain)) {
4351 return true; // nothing set for this
4353 $replyTo = strtolower($email->reply_to_email);
4354 $from = strtolower($email->from_addr);
4355 $filterDomain = '@'.strtolower($filterDomain);
4356 if(strpos($replyTo, $filterDomain) !== false) {
4357 $GLOBALS['log']->debug('Autoreply cancelled - [reply to] address domain matches filter domain.');
4359 } elseif(strpos($from, $filterDomain) !== false) {
4360 $GLOBALS['log']->debug('Autoreply cancelled - [from] address domain matches filter domain.');
4363 return true; // no match
4369 * returns true if subject is NOT "out of the office" type
4371 * @param string subject Subject line of email in question
4372 * @return bool returns false if OOTO found
4374 function checkOutOfOffice($subject) {
4375 $ooto = array("Out of the Office", "Out of Office");
4377 foreach($ooto as $str) {
4378 if(preg_match('/'.$str.'/i', $subject)) {
4379 $GLOBALS['log']->debug('Autoreply cancelled - found "Out of Office" type of subject.');
4383 return true; // no matches to ooto strings
4388 * sets a timestamp for an autoreply to a single email addy
4390 * @param string addr Address of auto-replied target
4392 function setAutoreplyStatus($addr) {
4393 $timedate = TimeDate::getInstance();
4394 $this->db->query( 'INSERT INTO inbound_email_autoreply (id, deleted, date_entered, date_modified, autoreplied_to, ie_id) VALUES (
4395 \''.create_guid().'\',
4397 \''.$timedate->nowDb().'\',
4398 \''.$timedate->nowDb().'\',
4400 \''.$this->id.'\') ', true);
4405 * returns true if recipient has NOT received 10 auto-replies in 24 hours
4407 * @param string from target address for auto-reply
4408 * @return bool true if target is valid/under limit
4410 function getAutoreplyStatus($from) {
4411 global $sugar_config;
4412 $timedate = TimeDate::getInstance();
4414 $q_clean = 'UPDATE inbound_email_autoreply SET deleted = 1 WHERE date_entered < \''.$timedate->getNow()->modify("-24 hours")->asDb().'\'';
4415 $r_clean = $this->db->query($q_clean, true);
4417 $q = 'SELECT count(*) AS c FROM inbound_email_autoreply WHERE deleted = 0 AND autoreplied_to = \''.$from.'\' AND ie_id = \''.$this->id.'\'';
4418 $r = $this->db->query($q, true);
4419 $a = $this->db->fetchByAssoc($r);
4421 $email_num_autoreplies_24_hours = $this->get_stored_options('email_num_autoreplies_24_hours');
4422 $maxReplies = (isset($email_num_autoreplies_24_hours)) ? $email_num_autoreplies_24_hours : $this->maxEmailNumAutoreplies24Hours;
4424 if($a['c'] >= $maxReplies) {
4425 $GLOBALS['log']->debug('Autoreply cancelled - more than ' . $maxReplies . ' replies sent in 24 hours.');
4433 * returns exactly 1 id match. if more than one, than returns false
4434 * @param $emailName the subject of the email to match
4435 * @param $tableName the table of the matching bean type
4437 function getSingularRelatedId($emailName, $tableName) {
4438 $repStrings = array('RE:','Re:','re:');
4439 $preppedName = str_replace($repStrings,'',trim($emailName));
4441 //TODO add team security to this query
4442 $q = 'SELECT count(id) AS c FROM '.$tableName.' WHERE deleted = 0 AND name LIKE \'%'.$preppedName.'%\'';
4443 $r = $this->db->query($q, true);
4444 $a = $this->db->fetchByAssoc($r);
4447 $q = 'SELECT id FROM '.$tableName.' WHERE deleted = 0 AND name LIKE \'%'.$preppedName.'%\'';
4448 $r = $this->db->query($q, true);
4449 $a = $this->db->fetchByAssoc($r);
4457 * saves InboundEmail parse macros to config.php
4458 * @param string type Bean to link
4459 * @param string macro The new macro
4461 function saveInboundEmailSystemSettings($type, $macro) {
4462 global $sugar_config;
4464 // inbound_email_case_subject_macro
4465 $var = "inbound_email_".strtolower($type)."_subject_macro";
4466 $sugar_config[$var] = $macro;
4468 ksort($sugar_config);
4470 $sugar_config_string = "<?php\n" .
4471 '// created: ' . date('Y-m-d H:i:s') . "\n" .
4472 '$sugar_config = ' .
4473 var_export($sugar_config, true) .
4476 write_array_to_file("sugar_config", $sugar_config, "config.php");
4480 * returns the HTML for InboundEmail system settings
4481 * @return string HTML
4483 function getSystemSettingsForm() {
4484 global $sugar_config;
4485 global $mod_strings;
4486 global $app_strings;
4487 global $app_list_strings;
4492 $macro = $c->getEmailSubjectMacro();
4495 <form action="index.php" method="post" name="Macro" id="form">
4496 <input type="hidden" name="module" value="InboundEmail">
4497 <input type="hidden" name="action" value="ListView">
4498 <input type="hidden" name="save" value="true">
4500 <table width="100%" cellpadding="0" cellspacing="0" border="0">
4503 <input title="{$app_strings['LBL_SAVE_BUTTON_TITLE']}"
4504 accessKey="{$app_strings['LBL_SAVE_BUTTON_KEY']}"
4506 onclick="this.form.return_module.value='InboundEmail'; this.form.return_action.value='ListView';"
4507 type="submit" name="Edit" value=" {$app_strings['LBL_SAVE_BUTTON_LABEL']} ">
4512 <table width="100%" border="0" cellspacing="0" cellpadding="0" class="detail view">
4514 <td valign="top" width='10%' NOWRAP scope="row">
4516 <b>{$mod_strings['LBL_CASE_MACRO']}:</b>
4519 <td valign="top" width='20%'>
4521 <input name="inbound_email_case_macro" type="text" value="{$macro}">
4524 <td valign="top" width='70%'>
4526 {$mod_strings['LBL_CASE_MACRO_DESC']}
4528 <i>{$mod_strings['LBL_CASE_MACRO_DESC2']}</i>
4539 * for mailboxes of type "Support" parse for '[CASE:%1]'
4540 * @param $emailName the subject line of the email
4541 * @param $aCase a Case object
4543 function getCaseIdFromCaseNumber($emailName, $aCase) {
4544 //$emailSubjectMacro
4545 $exMacro = explode('%1', $aCase->getEmailSubjectMacro());
4546 $open = $exMacro[0];
4547 $close = $exMacro[1];
4549 if($sub = stristr($emailName, $open)) { // eliminate everything up to the beginning of the macro and return the rest
4550 // $sub is [CASE:XX] xxxxxxxxxxxxxxxxxxxxxx
4551 $sub2 = str_replace($open, '', $sub);
4552 // $sub2 is XX] xxxxxxxxxxxxxx
4553 $sub3 = substr($sub2, 0, strpos($sub2, $close));
4555 // filter out deleted records in order to create a new case
4556 // if email is related to deleted one (bug #49840)
4557 $r = $this->db->query("SELECT id FROM cases WHERE case_number = '{$sub3}' and deleted = 0", true);
4558 $a = $this->db->fetchByAssoc($r);
4559 if(!empty($a['id'])) {
4569 function get_stored_options($option_name,$default_value=null,$stored_options=null) {
4570 if (empty($stored_options)) {
4571 $stored_options=$this->stored_options;
4573 if(!empty($stored_options)) {
4574 $storedOptions = unserialize(base64_decode($stored_options));
4575 if (isset($storedOptions[$option_name])) {
4576 $default_value=$storedOptions[$option_name];
4579 return $default_value;
4584 * This function returns a contact or user ID if a matching email is found
4585 * @param $email the email address to match
4586 * @param $table which table to query
4588 function getRelatedId($email, $module) {
4589 $email = trim(strtoupper($email));
4590 if(strpos($email, ',') !== false) {
4591 $emailsArray = explode(',', $email);
4592 $emailAddressString = "";
4593 foreach($emailsArray as $emailAddress) {
4594 if (!empty($emailAddressString)) {
4595 $emailAddressString .= ",";
4597 $emailAddressString .= "'" . $emailAddress. "'";
4599 $email = $emailAddressString;
4601 $email = "'" . $email . "'";
4603 $module = ucfirst($module);
4605 $q = "SELECT bean_id FROM email_addr_bean_rel eabr
4606 JOIN email_addresses ea ON (eabr.email_address_id = ea.id)
4607 WHERE bean_module = '{$module}' AND ea.email_address_caps in ( {$email} ) AND eabr.deleted=0";
4609 $r = $this->db->query($q, true);
4612 while($a = $this->db->fetchByAssoc($r)) {
4613 $retArr[] = $a['bean_id'];
4615 if(count($retArr) > 0) {
4623 * finds emails tagged "//UNSEEN" on mailserver and "SINCE: [date]" if that
4626 * @return array Array of messageNumbers (mail server's internal keys)
4628 function getNewMessageIds() {
4629 $storedOptions = unserialize(base64_decode($this->stored_options));
4631 //TODO figure out if the since date is UDT
4632 if($storedOptions['only_since']) {// POP3 does not support Unseen flags
4633 if(!isset($storedOptions['only_since_last']) && !empty($storedOptions['only_since_last'])) {
4634 $q = 'SELECT last_run FROM schedulers WHERE job = \'function::pollMonitoredInboxes\'';
4635 $r = $this->db->query($q, true);
4636 $a = $this->db->fetchByAssoc($r);
4638 $date = date('r', strtotime($a['last_run']));
4640 $date = $storedOptions['only_since_last'];
4642 $ret = imap_search($this->conn, 'SINCE "'.$date.'" UNDELETED UNSEEN');
4643 $check = imap_check($this->conn);
4644 $storedOptions['only_since_last'] = $check->Date;
4645 $this->stored_options = base64_encode(serialize($storedOptions));
4648 $ret = imap_search($this->conn, 'UNDELETED UNSEEN');
4651 $GLOBALS['log']->debug('-----> getNewMessageIds() got '.count($ret).' new Messages');
4656 * Constructs the resource connection string that IMAP needs
4657 * @param string $service Service string, will generate if not passed
4660 function getConnectString($service='', $mbox='', $includeMbox=true) {
4661 $service = empty($service) ? $this->getServiceString() : $service;
4662 $mbox = empty($mbox) ? $this->mailbox : $mbox;
4664 $connectString = '{'.$this->server_url.':'.$this->port.'/service='.$this->protocol.$service.'}';
4665 $connectString .= ($includeMbox) ? $mbox : "";
4667 return $connectString;
4670 function disconnectMailserver() {
4671 if(is_resource($this->conn)) {
4672 imap_close($this->conn);
4677 * Connects to mailserver. If an existing IMAP resource is available, it
4678 * will attempt to reuse the connection, updating the mailbox path.
4680 * @param bool test Flag to test connection
4681 * @param bool force Force reconnect
4682 * @return string "true" on success, "false" or $errorMessage on failure
4684 function connectMailserver($test=false, $force=false) {
4685 global $mod_strings;
4686 if(!function_exists("imap_open")) {
4687 $GLOBALS['log']->debug('------------------------- IMAP libraries NOT available!!!! die()ing thread.----');
4688 return $mod_strings['LBL_WARN_NO_IMAP'];
4691 imap_errors(); // clearing error stack
4692 error_reporting(0); // turn off notices from IMAP
4694 // tls::ca::ssl::protocol::novalidate-cert::notls
4695 $useSsl = ($_REQUEST['ssl'] == 'true') ? true : false;
4697 imap_timeout(1, 15); // 60 secs is the default
4698 imap_timeout(2, 15);
4699 imap_timeout(3, 15);
4701 $opts = $this->findOptimumSettings($useSsl);
4702 if(isset($opts['good']) && empty($opts['good'])) {
4703 return array_pop($opts['err']);
4705 $service = $opts['service'];
4706 $service = str_replace('foo','', $service); // foo there to support no-item explodes
4709 $service = $this->getServiceString();
4712 $connectString = $this->getConnectString($service, $this->mailbox);
4715 * Try to recycle the current connection to reduce response times
4717 if(is_resource($this->conn)) {
4720 imap_close($this->conn);
4723 if(imap_ping($this->conn)) {
4724 // we have a live connection
4725 imap_reopen($this->conn, $connectString, CL_EXPUNGE);
4730 if(!is_resource($this->conn) && !$test) {
4731 $this->conn = imap_open($connectString, $this->email_user, $this->email_password, CL_EXPUNGE);
4735 if ($opts == false && !is_resource($this->conn)) {
4736 $this->conn = imap_open($connectString, $this->email_user, $this->email_password, CL_EXPUNGE);
4740 $successful = false;
4741 if(($errors = imap_last_error()) || ($alerts = imap_alerts())) {
4742 if($errors == 'Mailbox is empty') { // false positive
4746 $msg .= '<p>'.$alerts.'<p>';
4747 $msg .= '<p>'.$mod_strings['ERR_TEST_MAILBOX'];
4754 if($this->protocol == 'imap') {
4755 $msg .= $mod_strings['LBL_TEST_SUCCESSFUL'];
4757 $testConnectString = '{'.$this->server_url.':'.$this->port.'/service='.$this->protocol.$service.'}';
4758 if (!is_resource($this->conn)) {
4759 $this->conn = imap_open($connectString, $this->email_user, $this->email_password, CL_EXPUNGE);
4761 $list = imap_getmailboxes($this->conn, $testConnectString, "*");
4762 if(isset($_REQUEST['personal']) && $_REQUEST['personal'] == 'true') {
4763 $msg .= $mod_strings['LBL_TEST_SUCCESSFUL'];
4764 } elseif (is_array($list)) {
4768 $msg .= '<b>'.$mod_strings['LBL_FOUND_MAILBOXES'].'</b><p>';
4769 foreach ($list as $key => $val) {
4770 $mb = imap_utf7_decode(str_replace($testConnectString,'',$val->name));
4771 $msg .= '<a onClick=\'setMailbox(\"'.$mb.'\"); window.close();\'>';
4777 $msg .= '<p>'.$mod_strings['ERR_MAILBOX_FAIL'].imap_last_error().'</p>';
4778 $msg .= '<p>'.$mod_strings['ERR_TEST_MAILBOX'].'</p>';
4782 $msg .= $mod_strings['LBL_POP3_SUCCESS'];
4786 imap_errors(); // collapse error stack
4787 imap_close($this->conn);
4789 } elseif(!is_resource($this->conn)) {
4798 function checkImap() {
4799 global $mod_strings;
4801 if(!function_exists('imap_open')) {
4803 <table cellpadding="0" cellspacing="0" width="100%" border="0" class="list view">
4805 <td scope="col" width="25%" colspan="2"><slot>
4806 '.$mod_strings['LBL_WARN_IMAP_TITLE'].'
4810 <td scope="row" valign=TOP bgcolor="#fdfdfd" width="20%"><slot>
4811 '.$mod_strings['LBL_WARN_IMAP'].'
4812 <td scope="row" valign=TOP class="oddListRowS1" bgcolor="#fdfdfd" width="80%"><slot>
4813 <span class=error>'.$mod_strings['LBL_WARN_NO_IMAP'].'</span>
4822 * retrieves an array of I-E beans based on the group_id
4823 * @param string $groupId GUID of the group user or Individual
4824 * @return array $beans array of beans
4825 * @return boolean false if none returned
4827 function retrieveByGroupId($groupId) {
4828 $q = 'SELECT id FROM inbound_email WHERE group_id = \''.$groupId.'\' AND deleted = 0 AND status = \'Active\'';
4829 $r = $this->db->query($q, true);
4832 while($a = $this->db->fetchByAssoc($r)) {
4833 $ie = new InboundEmail();
4834 $ie->retrieve($a['id']);
4835 $beans[$a['id']] = $ie;
4841 * Retrieves the current count of personal accounts for the user specified.
4843 * @param unknown_type $user
4845 function getUserPersonalAccountCount($user = null)
4848 $user = $GLOBALS['current_user'];
4850 $query = "SELECT count(*) as c FROM inbound_email WHERE deleted=0 AND is_personal='1' AND group_id='{$user->id}' AND status='Active'";
4852 $rs = $this->db->query($query);
4853 $row = $this->db->fetchByAssoc($rs);
4858 * retrieves an array of I-E beans based on the group folder id
4859 * @param string $groupFolderId GUID of the group folder
4860 * @return array $beans array of beans
4861 * @return boolean false if none returned
4863 function retrieveByGroupFolderId($groupFolderId) {
4864 $q = 'SELECT id FROM inbound_email WHERE groupfolder_id = \''.$groupFolderId.'\' AND deleted = 0 ';
4865 $r = $this->db->query($q, true);
4868 while($a = $this->db->fetchByAssoc($r)) {
4869 $ie = new InboundEmail();
4870 $ie->retrieve($a['id']);
4877 * Retrieves an array of I-E beans that the user has team access to
4879 function retrieveAllByGroupId($id, $includePersonal=true) {
4880 global $current_user;
4882 $beans = ($includePersonal) ? $this->retrieveByGroupId($id) : array();
4888 // bug 50536: groupfolder_id cannot be updated to NULL from sugarbean's nullable check ('type' set to ID in the vardef)
4889 // hence the awkward or check -- rbacon
4890 $q = "SELECT inbound_email.id FROM inbound_email {$teamJoin} WHERE is_personal = 0 AND (groupfolder_id is null OR groupfolder_id = '') AND mailbox_type not like 'bounce' AND inbound_email.deleted = 0 AND status = 'Active' ";
4894 $r = $this->db->query($q, true);
4896 while($a = $this->db->fetchByAssoc($r)) {
4898 foreach($beans as $bean) {
4899 if($bean->id == $a['id']) {
4905 $ie = new InboundEmail();
4906 $ie->retrieve($a['id']);
4907 $beans[$a['id']] = $ie;
4915 * Retrieves an array of I-E beans that the user has team access to including group
4917 function retrieveAllByGroupIdWithGroupAccounts($id, $includePersonal=true) {
4918 global $current_user;
4920 $beans = ($includePersonal) ? $this->retrieveByGroupId($id) : array();
4929 $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 ";
4931 $r = $this->db->query($q, true);
4933 while($a = $this->db->fetchByAssoc($r)) {
4935 foreach($beans as $bean) {
4936 if($bean->id == $a['id']) {
4942 $ie = new InboundEmail();
4943 $ie->retrieve($a['id']);
4944 $beans[$a['id']] = $ie;
4953 * returns the bean name - overrides SugarBean's
4955 function get_summary_text() {
4960 * Override's SugarBean's
4962 function create_export_query($order_by, $where, $show_deleted = 0) {
4963 return $this->create_new_list_query($order_by, $where, $show_deleted = 0);
4967 * Override's SugarBean's
4971 * Override's SugarBean's
4973 function get_list_view_data(){
4974 global $mod_strings;
4975 global $app_list_strings;
4976 $temp_array = $this->get_list_view_array();
4977 $temp_array['MAILBOX_TYPE_NAME']= $app_list_strings['dom_mailbox_type'][$this->mailbox_type];
4978 //cma, fix bug 21670.
4979 $temp_array['GLOBAL_PERSONAL_STRING']= ($this->is_personal ? $mod_strings['LBL_IS_PERSONAL'] : $mod_strings['LBL_IS_GROUP']);
4980 $temp_array['STATUS'] = ($this->status == 'Active') ? $mod_strings['LBL_STATUS_ACTIVE'] : $mod_strings['LBL_STATUS_INACTIVE'];
4985 * Override's SugarBean's
4987 function fill_in_additional_list_fields() {
4988 $this->fill_in_additional_detail_fields();
4992 * Override's SugarBean's
4994 function fill_in_additional_detail_fields() {
4995 if(!empty($this->service)) {
4996 $exServ = explode('::', $this->service);
4997 $this->tls = $exServ[0];
4998 if ( isset($exServ[1]) )
4999 $this->ca = $exServ[1];
5000 if ( isset($exServ[2]) )
5001 $this->ssl = $exServ[2];
5002 if ( isset($exServ[3]) )
5003 $this->protocol = $exServ[3];
5020 ///////////////////////////////////////////////////////////////////////////
5021 //// IN SUPPORT OF EMAIL 2.0
5023 * Checks for $user's autoImport setting and returns the current value
5024 * @param object $user User in focus, defaults to $current_user
5027 function isAutoImport($user=null) {
5028 if(!empty($this->autoImport)) {
5029 return $this->autoImport;
5032 global $current_user;
5033 if(empty($user)) $user = $current_user;
5035 $emailSettings = $current_user->getPreference('emailSettings', 'Emails');
5036 $emailSettings = is_string($emailSettings) ? unserialize($emailSettings) : $emailSettings;
5038 $this->autoImport = (isset($emailSettings['autoImport']) && !empty($emailSettings['autoImport'])) ? true : false;
5039 return $this->autoImport;
5043 * Clears out cache files for a user
5045 function cleanOutCache() {
5046 $GLOBALS['log']->debug("INBOUNDEMAIL: at cleanOutCache()");
5047 $this->deleteCache();
5051 * moves emails from folder to folder
5052 * @param string $fromIe I-E id
5053 * @param string $fromFolder IMAP path to folder in which the email lives
5054 * @param string $toIe I-E id
5055 * @param string $toFolder
5056 * @param string $uids UIDs of emails to move, either Sugar GUIDS or IMAP
5059 function copyEmails($fromIe, $fromFolder, $toIe, $toFolder, $uids) {
5060 $this->moveEmails($fromIe, $fromFolder, $toIe, $toFolder, $uids, true);
5064 * moves emails from folder to folder
5065 * @param string $fromIe I-E id
5066 * @param string $fromFolder IMAP path to folder in which the email lives
5067 * @param string $toIe I-E id
5068 * @param string $toFolder
5069 * @param string $uids UIDs of emails to move, either Sugar GUIDS or IMAP
5071 * @param bool $copy Default false
5072 * @return bool True on successful execution
5074 function moveEmails($fromIe, $fromFolder, $toIe, $toFolder, $uids, $copy=false) {
5075 global $app_strings;
5076 global $current_user;
5080 if($fromIe == $toIe) {
5081 $GLOBALS['log']->debug("********* SUGARFOLDER - moveEmails() moving email from I-E to I-E");
5082 //$exDestFolder = explode("::", $toFolder);
5083 //preserve $this->mailbox
5084 if (isset($this->mailbox)) {
5085 $oldMailbox = $this->mailbox;
5089 $this->retrieve($fromIe);
5090 $this->mailbox = $fromFolder;
5091 $this->connectMailserver();
5092 $exUids = explode('::;::', $uids);
5093 $uids = implode(",", $exUids);
5094 // imap_mail_move accepts comma-delimited lists of UIDs
5096 if(imap_mail_copy($this->conn, $uids, $toFolder, CP_UID)) {
5097 $this->mailbox = $toFolder;
5098 $this->connectMailserver();
5099 $newOverviews = imap_fetch_overview($this->conn, $uids, FT_UID);
5100 $this->updateOverviewCacheFile($newOverviews, 'append');
5101 if (isset($oldMailbox)) {
5102 $this->mailbox = $oldMailbox;
5106 $GLOBALS['log']->debug("INBOUNDEMAIL: could not imap_mail_copy() [ {$uids} ] to folder [ {$toFolder} ] from folder [ {$fromFolder} ]");
5109 if(imap_mail_move($this->conn, $uids, $toFolder, CP_UID)) {
5110 $GLOBALS['log']->info("INBOUNDEMAIL: imap_mail_move() [ {$uids} ] to folder [ {$toFolder} ] from folder [ {$fromFolder} ]");
5111 imap_expunge($this->conn); // hard deletes moved messages
5113 // update cache on fromFolder
5114 $newOverviews = $this->getOverviewsFromCacheFile($uids, $fromFolder, true);
5115 $this->deleteCachedMessages($uids, $fromFolder);
5117 // update cache on toFolder
5118 $this->checkEmailOneMailbox($toFolder, true, true);
5119 if (isset($oldMailbox)) {
5120 $this->mailbox = $oldMailbox;
5125 $GLOBALS['log']->debug("INBOUNDEMAIL: could not imap_mail_move() [ {$uids} ] to folder [ {$toFolder} ] from folder [ {$fromFolder} ]");
5128 } elseif($toIe == 'folder' && $fromFolder == 'sugar::Emails') {
5129 $GLOBALS['log']->debug("********* SUGARFOLDER - moveEmails() moving email from SugarFolder to SugarFolder");
5130 // move from sugar folder to sugar folder
5131 require_once("include/SugarFolders/SugarFolders.php");
5132 $sugarFolder = new SugarFolder();
5133 $exUids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
5134 foreach($exUids as $id) {
5136 $sugarFolder->copyBean($fromIe, $toFolder, $id, "Emails");
5138 $fromSugarFolder = new SugarFolder();
5139 $fromSugarFolder->retrieve($fromIe);
5140 $toSugarFolder = new SugarFolder();
5141 $toSugarFolder->retrieve($toFolder);
5143 $email = new Email();
5144 $email->retrieve($id);
5145 $email->status = 'unread';
5147 // when you move from My Emails to Group Folder, Assign To field for the Email should become null
5148 if ($fromSugarFolder->is_dynamic && $toSugarFolder->is_group) {
5149 $email->assigned_user_id = "";
5151 if (!$toSugarFolder->checkEmailExistForFolder($id)) {
5152 $fromSugarFolder->deleteEmailFromAllFolder($id);
5153 $toSugarFolder->addBean($email);
5155 } elseif ($fromSugarFolder->is_group && $toSugarFolder->is_dynamic) {
5156 $fromSugarFolder->deleteEmailFromAllFolder($id);
5157 $email->assigned_user_id = $current_user->id;
5160 // If you are moving something from personal folder then delete an entry from all folder
5161 if (!$fromSugarFolder->is_dynamic && !$fromSugarFolder->is_group) {
5162 $fromSugarFolder->deleteEmailFromAllFolder($id);
5165 if ($fromSugarFolder->is_dynamic && !$toSugarFolder->is_dynamic && !$toSugarFolder->is_group) {
5166 $email->assigned_user_id = "";
5167 $toSugarFolder->addBean($email);
5169 if (!$toSugarFolder->checkEmailExistForFolder($id)) {
5170 if (!$toSugarFolder->is_dynamic) {
5171 $fromSugarFolder->deleteEmailFromAllFolder($id);
5172 $toSugarFolder->addBean($email);
5174 $fromSugarFolder->deleteEmailFromAllFolder($id);
5175 $email->assigned_user_id = $current_user->id;
5178 $sugarFolder->move($fromIe, $toFolder, $id);
5186 } elseif($toIe == 'folder') {
5187 $GLOBALS['log']->debug("********* SUGARFOLDER - moveEmails() moving email from I-E to SugarFolder");
5188 // move to Sugar folder
5189 require_once("include/SugarFolders/SugarFolders.php");
5190 $sugarFolder = new SugarFolder();
5191 $sugarFolder->retrieve($toFolder);
5192 //Show the import form if we don't have the required info
5193 if (!isset($_REQUEST['delete'])) {
5194 $json = getJSONobj();
5195 if ($sugarFolder->is_group) {
5196 $_REQUEST['showTeam'] = false;
5197 $_REQUEST['showAssignTo'] = false;
5199 $ret = $this->email->et->getImportForm($_REQUEST, $this->email);
5200 $ret['move'] = true;
5201 $ret['srcFolder'] = $fromFolder;
5202 $ret['srcIeId'] = $fromIe;
5203 $ret['dstFolder'] = $toFolder;
5204 $ret['dstIeId'] = $toIe;
5205 $out = trim($json->encode($ret, false));
5212 $this->retrieve($fromIe);
5213 $this->mailbox = $fromFolder;
5214 $this->connectMailserver();
5215 // If its a group folder the team should be of the folder team
5216 if ($sugarFolder->is_group) {
5217 $_REQUEST['team_id'] = $sugarFolder->team_id;
5218 $_REQUEST['team_set_id'] = $sugarFolder->team_set_id;
5220 // TODO - set team_id, team_set for new UI
5223 $exUids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
5225 if(!empty($sugarFolder->id)) {
5228 $json = getJSONobj();
5229 foreach($exUids as $k => $uid) {
5231 if ($this->isPop3Protocol()) {
5232 $msgNo = $this->getCorrectMessageNoForPop3($uid);
5234 $msgNo = imap_msgno($this->conn, $uid);
5237 if(!empty($msgNo)) {
5238 $importStatus = $this->importOneEmail($msgNo, $uid);
5241 $sugarFolder->addBean($this->email);
5242 if(!$copy && isset($_REQUEST['delete']) && ($_REQUEST['delete'] == "true") && $importStatus) {
5243 $GLOBALS['log']->error("********* delete from mailserver [ {explode(",", $uids)} ]");
5244 // delete from mailserver
5245 $this->deleteMessageOnMailServer($uid);
5246 $this->deleteMessageFromCache($uid);
5249 $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']);
5253 echo $json->encode($return);
5256 $GLOBALS['log']->error("********* SUGARFOLDER - failed to retrieve folder ID [ {$toFolder} ]");
5259 $GLOBALS['log']->debug("********* SUGARFOLDER - moveEmails() called with no passing criteria");
5267 * Hard deletes an I-E account
5268 * @param string id GUID
5270 function hardDelete($id) {
5271 $q = "DELETE FROM inbound_email WHERE id = '{$id}'";
5272 $r = $this->db->query($q, true);
5276 * Generate a unique filename for attachments based on the message id. There are no maximum
5277 * specifications for the length of the message id, the only requirement is that it be globally unique.
5279 * @param bool $nameOnly Whether or not the attachment count should be appended to the filename.
5280 * @return string The temp file name
5282 function getTempFilename($nameOnly=false) {
5284 $str = md5($this->compoundMessageId);
5287 $str = $str.$this->attachmentCount;
5288 $this->attachmentCount++;
5295 * deletes and expunges emails on server
5296 * @param string $uid UID(s), comma delimited, of email(s) on server
5297 * @return bool true on success
5299 function deleteMessageOnMailServer($uid) {
5300 global $app_strings;
5301 $this->connectMailserver();
5303 if(strpos($uid, $app_strings['LBL_EMAIL_DELIMITER']) !== false) {
5304 $uids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uid);
5311 if($this->protocol == 'imap') {
5312 $trashFolder = $this->get_stored_options("trashFolder");
5313 if (empty($trashFolder)) {
5314 $trashFolder = "INBOX.Trash";
5316 foreach($uids as $uid) {
5317 if($this->moveEmails($this->id, $this->mailbox, $this->id, $trashFolder, $uid))
5318 $GLOBALS['log']->debug("INBOUNDEMAIL: MoveEmail to {$trashFolder} successful.");
5320 $GLOBALS['log']->debug("INBOUNDEMAIL: MoveEmail to {$trashFolder} FAILED - trying hard delete for message: $uid");
5321 imap_delete($this->conn, $uid, FT_UID);
5328 foreach($uids as $uid) {
5329 $msgnos[] = $this->getCorrectMessageNoForPop3($uid);
5331 $msgnos = implode(',', $msgnos);
5332 imap_delete($this->conn, $msgnos);
5336 if(!imap_expunge($this->conn)) {
5337 $GLOBALS['log']->debug("NOOP: could not expunge deleted email.");
5341 $GLOBALS['log']->info("INBOUNDEMAIL: hard-deleted mail with MSgno's' [ {$msgnos} ]");
5347 * deletes and expunges emails on server
5348 * @param string $uid UID(s), comma delimited, of email(s) on server
5350 function deleteMessageOnMailServerForPop3($uid) {
5351 if(imap_delete($this->conn, $uid)) {
5352 if(!imap_expunge($this->conn)) {
5353 $GLOBALS['log']->debug("NOOP: could not expunge deleted email.");
5356 $GLOBALS['log']->info("INBOUNDEMAIL: hard-deleted mail with MSgno's' [ {$uid} ]");
5362 * Checks if this is a pop3 type of an account or not
5365 function isPop3Protocol() {
5366 return ($this->protocol == 'pop3');
5370 * Gets the UIDL from database for the corresponding msgno
5371 * @param int messageNo of a message
5372 * @return UIDL for the message
5374 function getUIDLForMessage($msgNo) {
5375 $query = "SELECT message_id FROM email_cache WHERE ie_id = '{$this->id}' AND msgno = '{$msgNo}'";
5376 $r = $this->db->query($query);
5377 $a = $this->db->fetchByAssoc($r);
5378 return $a['message_id'];
5381 * Get the users default IE account id
5386 function getUsersDefaultOutboundServerId($user)
5388 $id = $user->getPreference($this->keyForUsersDefaultIEAccount,'Emails',$user);
5389 //If no preference has been set, grab the default system id.
5392 $oe = new OutboundEmail();
5393 $system = $oe->getSystemMailerSettings();
5394 $id=empty($system->id) ? '' : $system->id;
5401 * Get the users default IE account id
5405 function setUsersDefaultOutboundServerId($user,$oe_id)
5407 $user->setPreference($this->keyForUsersDefaultIEAccount, $oe_id, '', 'Emails');
5410 * Gets the UIDL from database for the corresponding msgno
5411 * @param int messageNo of a message
5412 * @return UIDL for the message
5414 function getMsgnoForMessageID($messageid) {
5415 $query = "SELECT msgno FROM email_cache WHERE ie_id = '{$this->id}' AND message_id = '{$messageid}'";
5416 $r = $this->db->query($query);
5417 $a = $this->db->fetchByAssoc($r);
5418 return $a['message_id'];
5422 * fills InboundEmail->email with an email's details
5423 * @param int uid Unique ID of email
5424 * @param bool isMsgNo flag that passed ID is msgNo, default false
5425 * @param bool setRead Sets the 'seen' flag in cache
5426 * @param bool forceRefresh Skips cache file
5429 function setEmailForDisplay($uid, $isMsgNo=false, $setRead=false, $forceRefresh=false) {
5432 $GLOBALS['log']->debug("*** ERROR: INBOUNDEMAIL trying to setEmailForDisplay() with no UID");
5436 global $sugar_config;
5437 global $app_strings;
5439 // if its a pop3 then get the UIDL and see if this file name exist or not
5440 if ($this->isPop3Protocol()) {
5441 // get the UIDL from database;
5442 $cachedUIDL = md5($uid);
5443 $cache = "{$this->EmailCachePath}/{$this->id}/messages/{$this->mailbox}{$cachedUIDL}.php";
5445 $cache = "{$this->EmailCachePath}/{$this->id}/messages/{$this->mailbox}{$uid}.php";
5448 if(file_exists($cache) && !$forceRefresh) {
5449 $GLOBALS['log']->info("INBOUNDEMAIL: Using cache file for setEmailForDisplay()");
5451 include($cache); // profides $cacheFile
5452 /** @var $cacheFile array */
5454 $metaOut = unserialize($cacheFile['out']);
5455 $meta = $metaOut['meta']['email'];
5456 $email = new Email();
5458 foreach($meta as $k => $v) {
5462 $email->to_addrs = $meta['toaddrs'];
5463 $email->date_sent = $meta['date_start'];
5464 //_ppf($email,true);
5466 $this->email = $email;
5467 $this->email->email2init();
5470 $GLOBALS['log']->info("INBOUNDEMAIL: opening new connection for setEmailForDisplay()");
5471 if($this->isPop3Protocol()) {
5472 $msgNo = $this->getCorrectMessageNoForPop3($uid);
5474 if(empty($this->conn)) {
5475 $this->connectMailserver();
5477 $msgNo = ($isMsgNo) ? $uid : imap_msgno($this->conn, $uid);
5479 if(empty($this->conn)) {
5480 $status = $this->connectMailserver();
5481 if($status == "false") {
5482 $this->email = new Email();
5483 $this->email->name = $app_strings['LBL_EMAIL_ERROR_MAILSERVERCONNECTION'];
5490 $this->importOneEmail($msgNo, $uid, true);
5491 $this->email->id = '';
5492 $this->email->new_with_id = false;
5497 $this->setStatuses($uid, 'seen', 1);
5505 * Sets status for a particular attribute on the mailserver and the local cache file
5507 function setStatuses($uid, $field, $value) {
5508 global $sugar_config;
5509 /** available status fields
5513 [date] => Mon, 22 Jan 2007 17:32:57 -0800
5526 $file = "{$this->mailbox}.imapFetchOverview.php";
5527 $overviews = $this->getCacheValueForUIDs($this->mailbox, array($uid));
5529 if(!empty($overviews)) {
5532 foreach($overviews['retArr'] as $k => $obj) {
5533 if($obj->imap_uid == $uid) {
5534 $obj->$field = $value;
5539 if(!empty($updates)) {
5540 $this->setCacheValue($this->mailbox, array(), $updates);
5546 * Removes an email from the cache file, deletes the message from the cache too
5547 * @param string String of uids, comma delimited
5549 function deleteMessageFromCache($uids) {
5550 global $sugar_config;
5551 global $app_strings;
5553 // delete message cache file and email_cache file
5554 $exUids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
5556 foreach($exUids as $uid) {
5558 if ($this->isPop3Protocol()) {
5559 $q = "DELETE FROM email_cache WHERE message_id = '{$uid}' AND ie_id = '{$this->id}'";
5561 $q = "DELETE FROM email_cache WHERE imap_uid = {$uid} AND ie_id = '{$this->id}'";
5563 $r = $this->db->query($q);
5564 if ($this->isPop3Protocol()) {
5567 $msgCacheFile = "{$this->EmailCachePath}/{$this->id}/messages/{$this->mailbox}{$uid}.php";
5568 if(file_exists($msgCacheFile)) {
5569 if(!unlink($msgCacheFile)) {
5570 $GLOBALS['log']->error("***ERROR: InboundEmail could not delete the cache file [ {$msgCacheFile} ]");
5579 * @param int uid UID of email to display
5580 * @param string mbox Mailbox to look in for the message
5581 * @param bool isMsgNo Flag to assume $uid is a MessageNo, not UniqueID, default false
5583 function displayOneEmail($uid, $mbox, $isMsgNo=false) {
5584 require_once("include/JSON.php");
5587 global $app_strings;
5588 global $app_list_strings;
5589 global $sugar_smarty;
5591 global $current_user;
5592 global $sugar_config;
5594 $fetchedAttributes = array(
5603 $souEmail = array();
5604 foreach($fetchedAttributes as $k) {
5605 if ($k == 'date_start') {
5606 $this->email->$k . " " . $this->email->time_start;
5607 $souEmail[$k] = $this->email->$k . " " . $this->email->time_start;
5608 } elseif ($k == 'time_start') {
5611 $souEmail[$k] = trim($this->email->$k);
5615 // if a MsgNo is passed in, convert to UID
5617 $uid = imap_uid($this->conn, $uid);
5619 // meta object to allow quick retrieval for replies
5621 $meta['type'] = $this->email->type;
5622 $meta['uid'] = $uid;
5623 $meta['ieId'] = $this->id;
5624 $meta['email'] = $souEmail;
5625 $meta['mbox'] = $this->mailbox;
5630 $exMbox = explode("::", $mbox);
5634 if(!empty($this->email->cc_addrs)) {
5635 //$ccs = $this->collapseLongMailingList($this->email->cc_addrs);
5636 $ccs = to_html($this->email->cc_addrs_names);
5639 <td NOWRAP valign="top" class="displayEmailLabel">
5640 {$app_strings['LBL_EMAIL_CC']}:
5642 <td class="displayEmailValue">
5649 $meta['email']['cc_addrs'] = $ccs;
5652 if ($mbox == "sugar::Emails") {
5654 $q = "SELECT id, filename, file_mime_type FROM notes WHERE parent_id = '{$uid}' AND deleted = 0";
5655 $r = $this->db->query($q);
5657 while($a = $this->db->fetchByAssoc($r)) {
5658 $url = "index.php?entryPoint=download&type=notes&id={$a['id']}";
5659 $lbl = ($i == 0) ? $app_strings['LBL_EMAIL_ATTACHMENTS'].":" : '';
5661 $attachments .=<<<EOQ
5663 <td NOWRAP valign="top" class="displayEmailLabel">
5666 <td NOWRAP valign="top" colspan="2" class="displayEmailValue">
5667 <a href="{$url}">{$a['filename']}</a>
5671 $this->email->cid2Link($a['id'], $a['file_mime_type']);
5677 if($this->attachmentCount > 0) {
5678 $theCount = $this->attachmentCount;
5680 for($i=0; $i<$theCount; $i++) {
5681 $lbl = ($i == 0) ? $app_strings['LBL_EMAIL_ATTACHMENTS'].":" : '';
5682 $name = $this->getTempFilename(true).$i;
5683 $tempName = urlencode($this->tempAttachment[$name]);
5685 $url = "index.php?entryPoint=download&type=temp&isTempFile=true&ieId={$this->id}&tempName={$tempName}&id={$name}";
5687 $attachments .=<<<eoq
5689 <td NOWRAP valign="top" class="displayEmailLabel">
5692 <td NOWRAP valign="top" colspan="2" class="displayEmailValue">
5693 <a href="{$url}">{$this->tempAttachment[$name]}</a>
5700 $meta['email']['attachments'] = $attachments;
5703 $meta['email']['toaddrs'] = $this->collapseLongMailingList($this->email->to_addrs);
5704 $meta['email']['cc_addrs'] = $ccs;
5707 $description = (empty($this->email->description_html)) ? nl2br($this->email->description) : $this->email->description_html;
5708 $meta['email']['description'] = $description;
5711 $meta['is_sugarEmail'] = ($exMbox[0] == 'sugar') ? true : false;
5713 if(!$meta['is_sugarEmail']) {
5714 if($this->isAutoImport) {
5715 $meta['is_sugarEmail'] = true;
5718 if( $this->email->status != 'sent' ){
5719 // mark SugarEmail read
5720 $q = "UPDATE emails SET status = 'read' WHERE id = '{$uid}'";
5721 $r = $this->db->query($q);
5726 $meta['email']['name'] = to_html($this->email->name);
5727 $meta['email']['from_addr'] = ( !empty($this->email->from_addr_name) ) ? to_html($this->email->from_addr_name) : to_html($this->email->from_addr);
5728 $meta['email']['toaddrs'] = ( !empty($this->email->to_addrs_names) ) ? to_html($this->email->to_addrs_names) : to_html($this->email->to_addrs);
5729 $meta['email']['cc_addrs'] = to_html($this->email->cc_addrs_names);
5730 $meta['email']['reply_to_addr'] = to_html($this->email->reply_to_addr);
5731 $return['meta'] = $meta;
5737 * Takes a long list of email addresses from a To or CC field and shows the first 3, the rest hidden
5738 * @param string emails
5741 function collapseLongMailingList($emails) {
5742 global $app_strings;
5744 $ex = explode(",", $emails);
5748 if(count($ex) > 3) {
5752 foreach($ex as $email) {
5754 if(!empty($emails)) {
5757 $emails .= trim($email);
5759 if(!empty($emailsHidden)) {
5760 $emailsHidden .= ", ";
5762 $emailsHidden .= trim($email);
5768 if(!empty($emailsHidden)) {
5770 $emails = "<span onclick='javascript:SUGAR.email2.detailView.showFullEmailList(this);' style='cursor:pointer;'>{$emails} [...{$j} {$app_strings['LBL_MORE']}]</span>";
5771 $emailsHidden = "<span onclick='javascript:SUGAR.email2.detailView.showCroppedEmailList(this)' style='cursor:pointer; display:none;'>{$email2}, {$emailsHidden} [ {$app_strings['LBL_LESS']} ]</span>";
5774 $emails .= $emailsHidden;
5782 * Sorts IMAP's imap_fetch_overview() results
5783 * @param array $arr Array of standard objects
5784 * @param string $sort Column to sort by
5785 * @param string direction Direction to sort by (asc/desc)
5786 * @return array Sorted array of obj.
5788 function sortFetchedOverview($arr, $sort=4, $direction='DESC', $forceSeen=false) {
5789 global $current_user;
5791 $sortPrefs = $current_user->getPreference('folderSortOrder', 'Emails');
5792 if(!empty($sortPrefs))
5793 $listPrefs = $sortPrefs;
5795 $listPrefs = array();
5797 if(isset($listPrefs[$this->id][$this->mailbox])) {
5798 $currentNode = $listPrefs[$this->id][$this->mailbox];
5801 if(isset($currentNode['current']) && !empty($currentNode['current'])) {
5802 $sort = $currentNode['current']['sort'];
5803 $direction = $currentNode['current']['direction'];
5808 $sort = $this->defaultSort;//4;
5809 $direction = $this->defaultDirection; //'DESC';
5810 } elseif(!is_numeric($sort)) {
5811 // handle bad sort index
5812 $sort = $this->defaultSort;
5814 // translate numeric index to human readable
5815 $sort = $this->hrSort[$sort];
5817 if(empty($direction)) {
5818 $direction = 'DESC';
5826 foreach($arr as $k => $overview) {
5827 $sorts['flagged'][$k] = $overview->flagged;
5828 $sorts['status'][$k] = $overview->answered;
5829 $sorts['from'][$k] = str_replace('"', "", $this->handleMimeHeaderDecode($overview->from));
5830 $sorts['subj'][$k] = $this->handleMimeHeaderDecode(quoted_printable_decode($overview->subject));
5831 $sorts['date'][$k] = $overview->date;
5835 natcasesort($sorts[$sort]);
5836 //_ppd($sorts[$sort]);
5838 if(strtolower($direction) == 'desc') {
5839 $revSorts = array();
5840 $keys = array_reverse(array_keys($sorts[$sort]));
5841 // _pp("count keys in DESC: ".count($keys));
5842 // _pp("count elements in sort[sort]: ".count($sorts[$sort]));
5844 for($i=0; $i<count($keys); $i++) {
5846 $revSorts[$v] = $sorts[$sort][$v];
5849 //_pp("count post-sort: ".count($revSorts));
5850 $sorts[$sort] = $revSorts;
5852 $timedate = TimeDate::getInstance();
5853 foreach($sorts[$sort] as $k2 => $overview2) {
5854 $arr[$k2]->date = $timedate->fromString($arr[$k2]->date)->asDb();
5855 $retArr[] = $arr[$k2];
5857 //_pp("final count: ".count($retArr));
5859 $finalReturn = array();
5860 $finalReturn['retArr'] = $retArr;
5861 $finalReturn['sortBy'] = $sort;
5862 $finalReturn['direction'] = $direction;
5863 return $finalReturn;
5867 function setReadFlagOnFolderCache($mbox, $uid) {
5868 global $sugar_config;
5870 $this->mailbox = $mbox;
5873 if($this->validCacheExists($this->mailbox)) {
5874 $ret = $this->getCacheValue($this->mailbox);
5878 foreach($ret as $k => $v) {
5879 if($v->imap_uid == $uid) {
5886 $this->setCacheValue($this->mailbox, array(), $updates);
5891 * Returns a list of emails in a mailbox.
5892 * @param string mbox Name of mailbox using dot notation paths to display
5893 * @param string $forceRefresh Flag to use cache or not
5895 function displayFolderContents($mbox, $forceRefresh='false', $page) {
5896 global $current_user;
5898 $delimiter = $this->get_stored_options('folderDelimiter');
5900 $mbox = str_replace('.', $delimiter, $mbox);
5903 $this->mailbox = $mbox;
5905 // jchi #9424, get sort and direction from user preference
5907 $direction = 'desc';
5908 $sortSerial = $current_user->getPreference('folderSortOrder', 'Emails');
5909 if(!empty($sortSerial) && !empty($_REQUEST['ieId']) && !empty($_REQUEST['mbox'])) {
5910 $sortArray = unserialize($sortSerial);
5911 $sort = $sortArray[$_REQUEST['ieId']][$_REQUEST['mbox']]['current']['sort'];
5912 $direction = $sortArray[$_REQUEST['ieId']][$_REQUEST['mbox']]['current']['direction'];
5917 if(!empty($_REQUEST['sort']) && !empty($_REQUEST['dir'])) {
5918 $this->email->et->saveListViewSortOrder($_REQUEST['ieId'], $_REQUEST['mbox'], $_REQUEST['sort'], $_REQUEST['dir']);
5919 $sort = $_REQUEST['sort'];
5920 $direction = $_REQUEST['dir'];
5922 $_REQUEST['sort'] = '';
5923 $_REQUEST['dir'] = '';
5929 if($forceRefresh == 'false' && $this->validCacheExists($this->mailbox)) {
5930 $emailSettings = $current_user->getPreference('emailSettings', 'Emails');
5932 // cn: default to a low number until user specifies otherwise
5933 if(empty($emailSettings['showNumInList'])) {
5934 $emailSettings['showNumInList'] = 20;
5937 $ret = $this->getCacheValue($this->mailbox, $emailSettings['showNumInList'], $page, $sort, $direction);
5941 $out = $this->displayFetchedSortedListXML($ret, $mbox);
5943 $metadata = array();
5944 $metadata['mbox'] = $mbox;
5945 $metadata['ieId'] = $this->id;
5946 $metadata['name'] = $this->name;
5947 $metadata['fromCache'] = $cacheUsed ? 1 : 0;
5948 $metadata['out'] = $out;
5954 * For a group email account, create subscriptions for all users associated with the
5955 * team assigned to the account.
5958 function createUserSubscriptionsForGroupAccount()
5961 $team->retrieve($this->team_id);
5962 $usersList = $team->get_team_members(true);
5963 foreach($usersList as $userObject)
5965 $previousSubscriptions = unserialize(base64_decode($userObject->getPreference('showFolders', 'Emails',$userObject)));
5966 if($previousSubscriptions === FALSE)
5967 $previousSubscriptions = array();
5969 $previousSubscriptions[] = $this->id;
5971 $encodedSubs = base64_encode(serialize($previousSubscriptions));
5972 $userObject->setPreference('showFolders',$encodedSubs , '', 'Emails');
5973 $userObject->savePreferencesToDB();
5977 * Create a sugar folder for this inbound email account
5978 * if the Enable Auto Import option is selected
5980 * @return String Id of the sugar folder created.
5982 function createAutoImportSugarFolder()
5984 global $current_user;
5985 $guid = create_guid();
5986 $GLOBALS['log']->debug("Creating Sugar Folder for IE with id $guid");
5987 $folder = new SugarFolder();
5988 $folder->id = $guid;
5989 $folder->new_with_id = TRUE;
5990 $folder->name = $this->name;
5991 $folder->has_child = 0;
5992 $folder->is_group = 1;
5993 $folder->assign_to_id = $current_user->id;
5994 $folder->parent_folder = "";
5997 //If this inbound email is marked as inactive, don't add subscriptions.
5998 $addSubscriptions = ($this->status == 'Inactive' || $this->mailbox_type == 'bounce') ? FALSE : TRUE;
5999 $folder->save($addSubscriptions);
6004 function validCacheExists($mbox) {
6005 $q = "SELECT count(*) c FROM email_cache WHERE ie_id = '{$this->id}'";
6006 $r = $this->db->query($q);
6007 $a = $this->db->fetchByAssoc($r);
6020 function displayFetchedSortedListXML($ret, $mbox) {
6023 global $current_user;
6024 global $sugar_config;
6026 if(empty($ret['retArr'])) {
6030 $tPref = $current_user->getUserDateTimePreferences();
6034 foreach($ret['retArr'] as $msg) {
6036 $flagged = ($msg->flagged == 0) ? "" : $this->iconFlagged;
6037 $status = ($msg->deleted) ? $this->iconDeleted : "";
6038 $status = ($msg->draft == 0) ? $status : $this->iconDraft;
6039 $status = ($msg->answered == 0) ? $status : $this->iconAnswered;
6040 $from = $this->handleMimeHeaderDecode($msg->from);
6041 $subject = $this->handleMimeHeaderDecode($msg->subject);
6042 //$date = date($tPref['date']." ".$tPref['time'], $msg->date);
6043 $date = $timedate->to_display_date_time($this->db->fromConvert($msg->date, 'datetime'));
6044 //$date = date($tPref['date'], $this->getUnixHeaderDate($msg->date));
6047 $temp['flagged'] = $flagged;
6048 $temp['status'] = $status;
6049 $temp['from'] = to_html($from);
6050 $temp['subject'] = $subject;
6051 $temp['date'] = $date;
6052 $temp['uid'] = $msg->uid; // either from an imap_search() or massaged cache value
6053 $temp['mbox'] = $this->mailbox;
6054 $temp['ieId'] = $this->id;
6055 $temp['site_url'] = $sugar_config['site_url'];
6056 $temp['seen'] = $msg->seen;
6057 $temp['type'] = (isset($msg->type)) ? $msg->type: 'remote';
6058 $temp['to_addrs'] = to_html($msg->to);
6059 $temp['hasAttach'] = '0';
6070 * retrieves the mailboxes for a given account in the following format
6075 [Builder] => Builder
6082 * @param bool $justRaw Default false
6085 function getMailboxes($justRaw=false) {
6086 if($justRaw == true) {
6087 return $this->mailboxarray;
6090 return $this->generateMultiDimArrayFromFlatArray($this->mailboxarray, $this->retrieveDelimiter());
6092 $serviceString = $this->getConnectString('', '', false);
6094 if(strpos($serviceString, 'pop3')) {
6096 $obj->name = $serviceString."INBOX";
6097 $boxes = array("INBOX" => $obj);
6099 $boxes = imap_getmailboxes($this->conn, $serviceString, "*");
6104 // clean MBOX path names
6105 foreach($boxes as $k => $mbox) {
6106 $raw[] = str_replace($serviceString, "", $mbox->name);
6107 if ($mbox->delimiter) {
6108 $delimiter = $mbox->delimiter;
6111 $storedOptions = unserialize(base64_decode($this->stored_options));
6112 $storedOptions['folderDelimiter'] = $delimiter;
6113 $this->stored_options = base64_encode(serialize($storedOptions));
6119 // used by $this->search()
6120 if($justRaw == true) {
6125 // generate a multi-dimensional array to iterate through
6127 foreach($raw as $mbox) {
6128 $ret = $this->sortMailboxes($mbox, $ret, $delimiter);
6135 function getMailBoxesForGroupAccount() {
6136 $mailboxes = $this->generateMultiDimArrayFromFlatArray(explode(",", $this->mailbox), $this->retrieveDelimiter());
6137 $mailboxesArray = $this->generateFlatArrayFromMultiDimArray($mailboxes, $this->retrieveDelimiter());
6138 $mailboxesArray = $this->filterMailBoxFromRaw(explode(",", $this->mailbox), $mailboxesArray);
6139 $this->saveMailBoxFolders($mailboxesArray);
6141 if ($this->mailbox != $this->$email_user) {
6142 $mailboxes = $this->sortMailboxes($this->mailbox, $this->retrieveDelimiter());
6143 $mailboxesArray = $this->generateFlatArrayFromMultiDimArray($mailboxes, $this->retrieveDelimiter());
6144 $this->saveMailBoxFolders($mailboxesArray);
6145 // save mailbox value of an inbound email account to email user
6146 $this->saveMailBoxValueOfInboundEmail();
6148 $mailboxes = $this->getMailboxes();
6154 function saveMailBoxFolders($value) {
6155 if (is_array($value)) {
6156 $value = implode(",", $value);
6158 $this->mailboxarray = explode(",", $value);
6159 $value = $this->db->quoted($value);
6160 $query = "update inbound_email set mailbox = $value where id ='{$this->id}'";
6161 $this->db->query($query);
6164 function insertMailBoxFolders($value) {
6165 $query = "select value from config where category='InboundEmail' and name='{$this->id}'";
6166 $r = $this->db->query($query);
6167 $a = $this->db->fetchByAssoc($r);
6168 if (empty($a['value'])) {
6169 if (is_array($value)) {
6170 $value = implode(",", $value);
6172 $this->mailboxarray = explode(",", $value);
6173 $value = $this->db->quoted($value);
6175 $query = "INSERT INTO config VALUES('InboundEmail', '{$this->id}', $value)";
6176 $this->db->query($query);
6180 function saveMailBoxValueOfInboundEmail() {
6181 $query = "update Inbound_email set mailbox = '{$this->email_user}'";
6182 $this->db->query($query);
6185 function retrieveMailBoxFolders() {
6186 $this->mailboxarray = explode(",", $this->mailbox);
6188 $query = "select value from config where category='InboundEmail' and name='{$this->id}'";
6189 $r = $this->db->query($query);
6190 $a = $this->db->fetchByAssoc($r);
6191 $this->mailboxarray = explode(",", $a['value']);
6196 function retrieveDelimiter() {
6197 $delimiter = $this->get_stored_options('folderDelimiter');
6204 function generateFlatArrayFromMultiDimArray($arraymbox, $delimiter) {
6206 foreach($arraymbox as $key => $value) {
6207 $this->generateArrayData($key, $value, $ret, $delimiter);
6213 function generateMultiDimArrayFromFlatArray($raw, $delimiter) {
6214 // generate a multi-dimensional array to iterate through
6216 foreach($raw as $mbox) {
6217 $ret = $this->sortMailboxes($mbox, $ret, $delimiter);
6223 function generateArrayData($key, $arraymbox, &$ret, $delimiter) {
6225 if (is_array($arraymbox)) {
6226 foreach($arraymbox as $mboxKey => $value) {
6227 $newKey = $key . $delimiter . $mboxKey;
6228 $this->generateArrayData($newKey, $value, $ret, $delimiter);
6234 * sorts the folders in a mailbox in a multi-dimensional array
6235 * @param string $MBOX
6239 function sortMailboxes($mbox, $ret, $delimeter = ".") {
6240 if(strpos($mbox, $delimeter)) {
6241 $node = substr($mbox, 0, strpos($mbox, $delimeter));
6242 $nodeAfter = substr($mbox, strpos($mbox, $node) + strlen($node) + 1, strlen($mbox));
6244 if(!isset($ret[$node])) {
6245 $ret[$node] = array();
6246 } elseif(isset($ret[$node]) && !is_array($ret[$node])) {
6247 $ret[$node] = array();
6249 $ret[$node] = $this->sortMailboxes($nodeAfter, $ret[$node], $delimeter);
6251 $ret[$mbox] = $mbox;
6258 * parses Sugar's storage method for imap server service strings
6261 function getServiceString() {
6263 $exServ = explode('::', $this->service);
6265 foreach($exServ as $v) {
6266 if(!empty($v) && ($v != 'imap' && $v !='pop3')) {
6275 * Get Email messages IDs from server which aren't in database
6276 * @return array Ids of messages, which aren't still in database
6278 public function getNewEmailsForSyncedMailbox()
6280 // ids's count limit for batch processing
6282 $msgIds = imap_search($this->conn, 'ALL UNDELETED');
6285 if(count($msgIds) > 0)
6288 * @var collect results of queries and message headers
6294 // sort IDs to get lastest on top
6296 $GLOBALS['log']->debug('-----> getNewEmailsForSyncedMailbox() got '.count($msgIds).' Messages');
6297 foreach($msgIds as $k => &$msgNo)
6299 $uid = imap_uid($this->conn, $msgNo);
6300 $header = imap_headerinfo($this->conn, $msgNo);
6301 $fullHeader = imap_fetchheader($this->conn, $msgNo);
6302 $message_id = $header->message_id;
6303 $deliveredTo = $this->id;
6305 preg_match('/(delivered-to:|x-real-to:){1}\s*(\S+)\s*\n{1}/im', $fullHeader, $matches);
6308 $deliveredTo = $matches[2];
6310 if(empty($message_id) || !isset($message_id))
6312 $GLOBALS['log']->debug('*********** NO MESSAGE_ID.');
6313 $message_id = $this->getMessageId($header);
6316 // generate compound messageId
6317 $this->compoundMessageId = trim($message_id) . trim($deliveredTo);
6318 // if the length > 255 then md5 it so that the data will be of smaller length
6319 if (strlen($this->compoundMessageId) > 255)
6321 $this->compoundMessageId = md5($this->compoundMessageId);
6324 if (empty($this->compoundMessageId))
6329 $potentials = clean_xss($this->compoundMessageId, false);
6331 if(is_array($potentials) && !empty($potentials))
6333 foreach($potentials as $bad)
6335 $this->compoundMessageId = str_replace($bad, "", $this->compoundMessageId);
6338 array_push($tmpMsgs, array('msgNo' => $msgNo, 'msgId' => $this->compoundMessageId, 'exists' => 0));
6339 if($counter == $limit)
6343 foreach(array_slice($tmpMsgs, -$limit, $limit) as $k1 => $v1)
6345 $query[] = $v1['msgId'];
6347 $query = 'SELECT count(emails.message_id) as cnt, emails.message_id AS mid FROM emails WHERE emails.message_id IN ("' . implode('","', $query) . '") and emails.deleted = 0 group by emails.message_id';
6348 $r = $this->db->query($query);
6350 while($a = $this->db->fetchByAssoc($r))
6352 $tmp[html_entity_decode($a['mid'])] = $a['cnt'];
6354 foreach($tmpMsgs as $k1 => $v1)
6356 if(isset($tmp[$v1['msgId']]) && $tmp[$v1['msgId']] > 0)
6358 $tmpMsgs[$k1]['exists'] = 1;
6361 foreach($tmpMsgs as $k1 => $v1)
6363 if($v1['exists'] == 0)
6366 array_push($result, $v1['msgNo']);
6373 if($repeats >= $limit)
6379 $tmpMsgs = array_splice($tmpMsgs, -$repeats, $repeats);
6390 }catch(Exception $ex)
6392 $GLOBALS['log']->fatal($ex->getMessage());
6394 $GLOBALS['log']->debug('-----> getNewEmailsForSyncedMailbox() got '.count($result).' unsynced messages');
6398 } // end class definition
6402 * Simple class to mirror the passed object from an imap_fetch_overview() call
6421 var $indices; /* = array(
6424 'name' => 'mail_date',
6432 'name' => 'mail_from',
6440 'name' => 'mail_subj',
6449 var $fieldDefs;/* = array(
6452 'type' => 'varchar',
6457 'name' => 'subject',
6458 'type' => 'varchar',
6460 'required' => false,
6462 'fromaddr' => array(
6463 'name' => 'fromaddr',
6464 'type' => 'varchar',
6470 'type' => 'varchar',
6474 'senddate' => array(
6475 'name' => 'senddate',
6476 'type' => 'datetime',
6479 'message_id' => array(
6480 'name' => 'message_id',
6481 'type' => 'varchar',
6483 'required' => false,
6485 'mailsize' => array(
6486 'name' => 'mailsize',
6501 'required' => false,
6505 'type' => 'tinyint',
6510 'name' => 'flagged',
6511 'type' => 'tinyint',
6515 'answered' => array(
6516 'name' => 'answered',
6517 'type' => 'tinyint',
6522 'name' => 'deleted',
6523 'type' => 'tinyint',
6529 'type' => 'tinyint',
6535 'type' => 'tinyint',
6541 function Overview() {
6544 if(!isset($dictionary['email_cache']) || empty($dictionary['email_cache'])) {
6545 if(file_exists('custom/metadata/email_cacheMetaData.php')) {
6546 include('custom/metadata/email_cacheMetaData.php');
6548 include('metadata/email_cacheMetaData.php');
6552 $this->fieldDefs = $dictionary['email_cache']['fields'];
6553 $this->indices = $dictionary['email_cache']['indices'];