/** * moves emails from folder to folder * @param string $fromIe I-E id * @param string $fromFolder IMAP path to folder in which the email lives * @param string $toIe I-E id * @param string $toFolder * @param string $uids UIDs of emails to move, either Sugar GUIDS or IMAP * UIDs * @param bool $copy Default false * @return bool True on successful execution */ function moveEmails($fromIe, $fromFolder, $toIe, $toFolder, $uids, $copy = false) { global $app_strings; global $current_user; // same I-E server if ($fromIe == $toIe) { $GLOBALS['log']->debug("********* SUGARFOLDER - moveEmails() moving email from I-E to I-E"); //$exDestFolder = explode("::", $toFolder); //preserve $this->mailbox if (isset($this->mailbox)) { $oldMailbox = $this->mailbox; } $this->retrieve($fromIe); $this->mailbox = $fromFolder; $this->connectMailserver(); $exUids = explode('::;::', $uids); $uids = implode(",", $exUids); // imap_mail_move accepts comma-delimited lists of UIDs if ($copy) { if (imap_mail_copy($this->conn, $uids, $toFolder, CP_UID)) { $this->mailbox = $toFolder; $this->connectMailserver(); $newOverviews = imap_fetch_overview($this->conn, $uids, FT_UID); $this->updateOverviewCacheFile($newOverviews, 'append'); if (isset($oldMailbox)) { $this->mailbox = $oldMailbox; } return true; } else { $GLOBALS['log']->debug("INBOUNDEMAIL: could not imap_mail_copy() [ {$uids} ] to folder [ {$toFolder} ] from folder [ {$fromFolder} ]"); } } else { if (imap_mail_move($this->conn, $uids, $toFolder, CP_UID)) { $GLOBALS['log']->info("INBOUNDEMAIL: imap_mail_move() [ {$uids} ] to folder [ {$toFolder} ] from folder [ {$fromFolder} ]"); imap_expunge($this->conn); // hard deletes moved messages // update cache on fromFolder $newOverviews = $this->getOverviewsFromCacheFile($uids, $fromFolder, true); $this->deleteCachedMessages($uids, $fromFolder); // update cache on toFolder $this->checkEmailOneMailbox($toFolder, true, true); if (isset($oldMailbox)) { $this->mailbox = $oldMailbox; } return true; } else { $GLOBALS['log']->debug("INBOUNDEMAIL: could not imap_mail_move() [ {$uids} ] to folder [ {$toFolder} ] from folder [ {$fromFolder} ]"); } } } elseif ($toIe == 'folder' && $fromFolder == 'sugar::Emails') { $GLOBALS['log']->debug("********* SUGARFOLDER - moveEmails() moving email from SugarFolder to SugarFolder"); // move from sugar folder to sugar folder require_once "include/SugarFolders/SugarFolders.php"; $sugarFolder = new SugarFolder(); $exUids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids); foreach ($exUids as $id) { if ($copy) { $sugarFolder->copyBean($fromIe, $toFolder, $id, "Emails"); } else { $fromSugarFolder = new SugarFolder(); $fromSugarFolder->retrieve($fromIe); $toSugarFolder = new SugarFolder(); $toSugarFolder->retrieve($toFolder); $email = new Email(); $email->retrieve($id); $email->status = 'unread'; // when you move from My Emails to Group Folder, Assign To field for the Email should become null if ($fromSugarFolder->is_dynamic && $toSugarFolder->is_group) { $email->assigned_user_id = ""; $email->save(); if (!$toSugarFolder->checkEmailExistForFolder($id)) { $fromSugarFolder->deleteEmailFromAllFolder($id); $toSugarFolder->addBean($email); } } elseif ($fromSugarFolder->is_group && $toSugarFolder->is_dynamic) { $fromSugarFolder->deleteEmailFromAllFolder($id); $email->assigned_user_id = $current_user->id; $email->save(); } else { // If you are moving something from personal folder then delete an entry from all folder if (!$fromSugarFolder->is_dynamic && !$fromSugarFolder->is_group) { $fromSugarFolder->deleteEmailFromAllFolder($id); } // if if ($fromSugarFolder->is_dynamic && !$toSugarFolder->is_dynamic && !$toSugarFolder->is_group) { $email->assigned_user_id = ""; $toSugarFolder->addBean($email); } // if if (!$toSugarFolder->checkEmailExistForFolder($id)) { if (!$toSugarFolder->is_dynamic) { $fromSugarFolder->deleteEmailFromAllFolder($id); $toSugarFolder->addBean($email); } else { $fromSugarFolder->deleteEmailFromAllFolder($id); $email->assigned_user_id = $current_user->id; } } else { $sugarFolder->move($fromIe, $toFolder, $id); } // else $email->save(); } // else } } return true; } elseif ($toIe == 'folder') { $GLOBALS['log']->debug("********* SUGARFOLDER - moveEmails() moving email from I-E to SugarFolder"); // move to Sugar folder require_once "include/SugarFolders/SugarFolders.php"; $sugarFolder = new SugarFolder(); $sugarFolder->retrieve($toFolder); //Show the import form if we don't have the required info if (!isset($_REQUEST['delete'])) { $json = getJSONobj(); if ($sugarFolder->is_group) { $_REQUEST['showTeam'] = false; $_REQUEST['showAssignTo'] = false; } $ret = $this->email->et->getImportForm($_REQUEST, $this->email); $ret['move'] = true; $ret['srcFolder'] = $fromFolder; $ret['srcIeId'] = $fromIe; $ret['dstFolder'] = $toFolder; $ret['dstIeId'] = $toIe; $out = trim($json->encode($ret, false)); echo $out; return true; } // import to Sugar $this->retrieve($fromIe); $this->mailbox = $fromFolder; $this->connectMailserver(); // If its a group folder the team should be of the folder team if ($sugarFolder->is_group) { $_REQUEST['team_id'] = $sugarFolder->team_id; $_REQUEST['team_set_id'] = $sugarFolder->team_set_id; } else { // TODO - set team_id, team_set for new UI } // else $exUids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids); if (!empty($sugarFolder->id)) { $count = 1; $return = array(); $json = getJSONobj(); foreach ($exUids as $k => $uid) { $msgNo = $uid; if ($this->isPop3Protocol()) { $msgNo = $this->getCorrectMessageNoForPop3($uid); } else { $msgNo = imap_msgno($this->conn, $uid); } if (!empty($msgNo)) { $importStatus = $this->importOneEmail($msgNo, $uid); // add to folder if ($importStatus) { $sugarFolder->addBean($this->email); if (!$copy && isset($_REQUEST['delete']) && $_REQUEST['delete'] == "true" && $importStatus) { $GLOBALS['log']->error("********* delete from mailserver [ {explode(", ", {$uids})} ]"); // delete from mailserver $this->deleteMessageOnMailServer($uid); $this->deleteMessageFromCache($uid); } // if } $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']); $count++; } // if } // foreach echo $json->encode($return); return true; } else { $GLOBALS['log']->error("********* SUGARFOLDER - failed to retrieve folder ID [ {$toFolder} ]"); } } else { $GLOBALS['log']->debug("********* SUGARFOLDER - moveEmails() called with no passing criteria"); } return false; }
/** * Job 1 */ function pollMonitoredInboxes() { $_bck_up = array('team_id' => $GLOBALS['current_user']->team_id, 'team_set_id' => $GLOBALS['current_user']->team_set_id); Log::info('----->Scheduler fired job of type pollMonitoredInboxes()'); global $dictionary; global $app_strings; require_once 'modules/Emails/EmailUI.php'; $ie = new InboundEmail(); $emailUI = new EmailUI(); $r = $ie->db->query('SELECT id, name FROM inbound_email WHERE is_personal = 0 AND deleted=0 AND status=\'Active\' AND mailbox_type != \'bounce\''); Log::debug('Just got Result from get all Inbounds of Inbound Emails'); while ($a = $ie->db->fetchByAssoc($r)) { Log::debug('In while loop of Inbound Emails'); $ieX = new InboundEmail(); $ieX->retrieve($a['id']); $GLOBALS['current_user']->team_id = $ieX->team_id; $GLOBALS['current_user']->team_set_id = $ieX->team_set_id; $mailboxes = $ieX->mailboxarray; foreach ($mailboxes as $mbox) { $ieX->mailbox = $mbox; $newMsgs = array(); $msgNoToUIDL = array(); $connectToMailServer = false; if ($ieX->isPop3Protocol()) { $msgNoToUIDL = $ieX->getPop3NewMessagesToDownloadForCron(); // get all the keys which are msgnos; $newMsgs = array_keys($msgNoToUIDL); } if ($ieX->connectMailserver() == 'true') { $connectToMailServer = true; } // if Log::debug('Trying to connect to mailserver for [ ' . $a['name'] . ' ]'); if ($connectToMailServer) { Log::debug('Connected to mailserver'); if (!$ieX->isPop3Protocol()) { $newMsgs = $ieX->getNewMessageIds(); } if (is_array($newMsgs)) { $current = 1; $total = count($newMsgs); require_once "include/SugarFolders/SugarFolders.php"; $sugarFolder = new SugarFolder(); $groupFolderId = $ieX->groupfolder_id; $isGroupFolderExists = false; $users = array(); if ($groupFolderId != null && $groupFolderId != "") { $sugarFolder->retrieve($groupFolderId); $isGroupFolderExists = true; } // if $messagesToDelete = array(); if ($ieX->isMailBoxTypeCreateCase()) { $users[] = $sugarFolder->assign_to_id; $distributionMethod = $ieX->get_stored_options("distrib_method", ""); if ($distributionMethod != 'roundRobin') { $counts = $emailUI->getAssignedEmailsCountForUsers($users); } else { $lastRobin = $emailUI->getLastRobin($ieX); } Log::debug('distribution method id [ ' . $distributionMethod . ' ]'); } foreach ($newMsgs as $k => $msgNo) { $uid = $msgNo; if ($ieX->isPop3Protocol()) { $uid = $msgNoToUIDL[$msgNo]; } else { $uid = imap_uid($ieX->conn, $msgNo); } // else if ($isGroupFolderExists) { if ($ieX->importOneEmail($msgNo, $uid)) { // add to folder $sugarFolder->addBean($ieX->email); if ($ieX->isPop3Protocol()) { $messagesToDelete[] = $msgNo; } else { $messagesToDelete[] = $uid; } if ($ieX->isMailBoxTypeCreateCase()) { $userId = ""; if ($distributionMethod == 'roundRobin') { if (sizeof($users) == 1) { $userId = $users[0]; $lastRobin = $users[0]; } else { $userIdsKeys = array_flip($users); // now keys are values $thisRobinKey = $userIdsKeys[$lastRobin] + 1; if (!empty($users[$thisRobinKey])) { $userId = $users[$thisRobinKey]; $lastRobin = $users[$thisRobinKey]; } else { $userId = $users[0]; $lastRobin = $users[0]; } } // else } else { if (sizeof($users) == 1) { foreach ($users as $k => $value) { $userId = $value; } // foreach } else { asort($counts); // lowest to highest $countsKeys = array_flip($counts); // keys now the 'count of items' $leastBusy = array_shift($countsKeys); // user id of lowest item count $userId = $leastBusy; $counts[$leastBusy] = $counts[$leastBusy] + 1; } } // else Log::debug('userId [ ' . $userId . ' ]'); $ieX->handleCreateCase($ieX->email, $userId); } // if } // if } else { if ($ieX->isAutoImport()) { $ieX->importOneEmail($msgNo, $uid); } else { /*If the group folder doesn't exist then download only those messages which has caseid in message*/ $ieX->getMessagesInEmailCache($msgNo, $uid); $email = new Email(); $header = imap_headerinfo($ieX->conn, $msgNo); $email->name = $ieX->handleMimeHeaderDecode($header->subject); $email->from_addr = $ieX->convertImapToSugarEmailAddress($header->from); $email->reply_to_email = $ieX->convertImapToSugarEmailAddress($header->reply_to); if (!empty($email->reply_to_email)) { $contactAddr = $email->reply_to_email; } else { $contactAddr = $email->from_addr; } $mailBoxType = $ieX->mailbox_type; $ieX->handleAutoresponse($email, $contactAddr); } // else } // else Log::debug('***** On message [ ' . $current . ' of ' . $total . ' ] *****'); $current++; } // foreach // update Inbound Account with last robin if ($ieX->isMailBoxTypeCreateCase() && $distributionMethod == 'roundRobin') { $emailUI->setLastRobin($ieX, $lastRobin); } // if } // if if ($isGroupFolderExists) { $leaveMessagesOnMailServer = $ieX->get_stored_options("leaveMessagesOnMailServer", 0); if (!$leaveMessagesOnMailServer) { if ($ieX->isPop3Protocol()) { $ieX->deleteMessageOnMailServerForPop3(implode(",", $messagesToDelete)); } else { $ieX->deleteMessageOnMailServer(implode($app_strings['LBL_EMAIL_DELIMITER'], $messagesToDelete)); } } } } else { Log::fatal("SCHEDULERS: could not get an IMAP connection resource for ID [ {$a['id']} ]. Skipping mailbox [ {$a['name']} ]."); // cn: bug 9171 - continue while } // else } // foreach imap_expunge($ieX->conn); imap_close($ieX->conn, CL_EXPUNGE); } // while $GLOBALS['current_user']->team_id = $_bck_up['team_id']; $GLOBALS['current_user']->team_set_id = $_bck_up['team_set_id']; return true; }
/** * Copies an email to a folder * @param array $action Array of options and criteria for the action current being processed * @param string $ieId ID of InboundEmail instance fully retrieved * @param string $uid UID of email * @return bool */ function copy_mail($action, $bean, $ie, $copy = true) { $args = explode("::", $action['action1']); // _pp($bean->uid); // _pp($bean->imap_uid); // _ppf($bean, true); // _ppl($action);_ppl($args); if ($args[0] == 'sugar') { // we're dealing with a target Sugar Folder $folder_id = $args[1]; $GLOBALS['log']->fatal("*** SUGARROUTING: dest folder is Sugar Folder"); // destination is a Sugar folder require_once "include/SugarFolders/SugarFolders.php"; $sf = new SugarFolder(); if ($sf->retrieve($folder_id)) { $result = $ie->setEmailForDisplay($bean->uid, false); if ($result == 'import') { $ie->email->save(); } $sf->addBean($ie->email); if (!$copy) { // remove message from email server /* pending functional abstraction of sugar-side vs imap-side functionality */ //$ie->deleteMessageOnMailServer($bean->uid); } } else { $GLOBALS['log']->fatal("*** SUGARROUTING: baseActions:copy_mail: could not retrieve SugarFolder with id [ {$folder_id} ]"); } } else { $ieId = $args[1]; $folder = ""; for ($i = 2; $i < count($args); $i++) { if (!empty($folder)) { $folder .= "."; } $folder .= $args[$i]; } $GLOBALS['log']->fatal("*** SUGARROUTING: baseActions:copy_email [ {$folder} ] [ {$ieId} ] [ {$bean->uid} ]"); $ie = BeanFactory::getBean('InboundEmail', $ieId, array('disable_row_level_security' => true)); $GLOBALS['log']->fatal("*** SUGARROUTING: dest folder is IMAP Folder"); // destination is an IMAP folder /** * moveEmails($fromIe, $fromFolder, $toIe, $toFolder, $uids) { * $args['toFolder'] - XXXX-XXX-XXXXXXX-XXXX-XXX::INBOX::[folderPath] */ if ($copy) { $ie->copyEmails($ie->id, "INBOX", $ie->id, $folder, $bean->uid); } else { $ie->moveEmails($ie->id, "INBOX", $ie->id, $folder, $bean->uid); } } return true; }
/** * Test retreiving a list of emails for a particular folder. * */ function testGetListItemsForEmailXML() { //Create the my Emails Folder $GLOBALS['mod_strings'] = return_module_language($GLOBALS['current_language'], "Emails"); require_once 'modules/Emails/EmailUI.php'; $emailUI = new EmailUI(); $emailUI->preflightUser($GLOBALS['current_user']); $error_message = "Unable to get list items for email."; $rootNode = new ExtNode('', ''); $folderOpenState = ""; $ret = $this->folder->getUserFolders($rootNode, $folderOpenState, $GLOBALS['current_user'], true); $this->assertEquals(1, count($ret), $error_message); $folderID = $ret[0]['id']; //Create the Email Object $emailParams = array('status' => 'unread', 'assigned_user_id' => $GLOBALS['current_user']->id); $email = $this->_createEmailObject($emailParams); $this->emails[] = $email->id; //Add Email Object to My Email Folder $my_email = new SugarFolder(); $my_email->retrieve($folderID); $my_email->addBean($email, $GLOBALS['current_user']); //Make sure the email was added to the folder. $emailExists = $my_email->checkEmailExistForFolder($email->id); $this->assertTrue($emailExists, $error_message); //Get the list of emails. $emailList = $my_email->getListItemsForEmailXML($folderID); $this->assertEquals($email->id, $emailList['out'][0]['uid'], $error_message); }
function pollMonitoredInboxesAOP() { require_once 'custom/modules/InboundEmail/AOPInboundEmail.php'; $GLOBALS['log']->info('----->Scheduler fired job of type pollMonitoredInboxesAOP()'); global $dictionary; global $app_strings; global $sugar_config; require_once 'modules/Configurator/Configurator.php'; require_once 'modules/Emails/EmailUI.php'; $ie = new AOPInboundEmail(); $emailUI = new EmailUI(); $r = $ie->db->query('SELECT id, name FROM inbound_email WHERE is_personal = 0 AND deleted=0 AND status=\'Active\' AND mailbox_type != \'bounce\''); $GLOBALS['log']->debug('Just got Result from get all Inbounds of Inbound Emails'); while ($a = $ie->db->fetchByAssoc($r)) { $GLOBALS['log']->debug('In while loop of Inbound Emails'); $ieX = new AOPInboundEmail(); $ieX->retrieve($a['id']); $mailboxes = $ieX->mailboxarray; foreach ($mailboxes as $mbox) { $ieX->mailbox = $mbox; $newMsgs = array(); $msgNoToUIDL = array(); $connectToMailServer = false; if ($ieX->isPop3Protocol()) { $msgNoToUIDL = $ieX->getPop3NewMessagesToDownloadForCron(); // get all the keys which are msgnos; $newMsgs = array_keys($msgNoToUIDL); } if ($ieX->connectMailserver() == 'true') { $connectToMailServer = true; } // if $GLOBALS['log']->debug('Trying to connect to mailserver for [ ' . $a['name'] . ' ]'); if ($connectToMailServer) { $GLOBALS['log']->debug('Connected to mailserver'); if (!$ieX->isPop3Protocol()) { $newMsgs = $ieX->getNewMessageIds(); } if (is_array($newMsgs)) { $current = 1; $total = count($newMsgs); require_once "include/SugarFolders/SugarFolders.php"; $sugarFolder = new SugarFolder(); $groupFolderId = $ieX->groupfolder_id; $isGroupFolderExists = false; $users = array(); if ($groupFolderId != null && $groupFolderId != "") { $sugarFolder->retrieve($groupFolderId); $isGroupFolderExists = true; } // if $messagesToDelete = array(); if ($ieX->isMailBoxTypeCreateCase()) { require_once 'modules/AOP_Case_Updates/AOPAssignManager.php'; $assignManager = new AOPAssignManager($ieX); } foreach ($newMsgs as $k => $msgNo) { $uid = $msgNo; if ($ieX->isPop3Protocol()) { $uid = $msgNoToUIDL[$msgNo]; } else { $uid = imap_uid($ieX->conn, $msgNo); } // else if ($isGroupFolderExists) { if ($ieX->importOneEmail($msgNo, $uid)) { // add to folder $sugarFolder->addBean($ieX->email); if ($ieX->isPop3Protocol()) { $messagesToDelete[] = $msgNo; } else { $messagesToDelete[] = $uid; } if ($ieX->isMailBoxTypeCreateCase()) { $userId = $assignManager->getNextAssignedUser(); $GLOBALS['log']->debug('userId [ ' . $userId . ' ]'); $ieX->handleCreateCase($ieX->email, $userId); } // if } // if } else { if ($ieX->isAutoImport()) { $ieX->importOneEmail($msgNo, $uid); } else { /*If the group folder doesn't exist then download only those messages which has caseid in message*/ $ieX->getMessagesInEmailCache($msgNo, $uid); $email = new Email(); $header = imap_headerinfo($ieX->conn, $msgNo); $email->name = $ieX->handleMimeHeaderDecode($header->subject); $email->from_addr = $ieX->convertImapToSugarEmailAddress($header->from); $email->reply_to_email = $ieX->convertImapToSugarEmailAddress($header->reply_to); if (!empty($email->reply_to_email)) { $contactAddr = $email->reply_to_email; } else { $contactAddr = $email->from_addr; } $mailBoxType = $ieX->mailbox_type; $ieX->handleAutoresponse($email, $contactAddr); } // else } // else $GLOBALS['log']->debug('***** On message [ ' . $current . ' of ' . $total . ' ] *****'); $current++; } // foreach // update Inbound Account with last robin } // if if ($isGroupFolderExists) { $leaveMessagesOnMailServer = $ieX->get_stored_options("leaveMessagesOnMailServer", 0); if (!$leaveMessagesOnMailServer) { if ($ieX->isPop3Protocol()) { $ieX->deleteMessageOnMailServerForPop3(implode(",", $messagesToDelete)); } else { $ieX->deleteMessageOnMailServer(implode($app_strings['LBL_EMAIL_DELIMITER'], $messagesToDelete)); } } } } else { $GLOBALS['log']->fatal("SCHEDULERS: could not get an IMAP connection resource for ID [ {$a['id']} ]. Skipping mailbox [ {$a['name']} ]."); // cn: bug 9171 - continue while } // else } // foreach imap_expunge($ieX->conn); imap_close($ieX->conn, CL_EXPUNGE); } // while return true; }