Example #1
0
 /**
  * Save a SugarFolder 
  */
 public function testSaveNewFolder()
 {
     $newFolderName = "UNIT_TEST";
     $rs = $this->eui->saveNewFolder($newFolderName, 'Home', 0);
     $newFolderID = $rs['id'];
     $this->_folders[] = $newFolderID;
     $sf = new SugarFolder();
     $sf->retrieve($newFolderID);
     $this->assertEquals($newFolderName, $sf->name);
 }
 /**
  * Create a sugar folder for this inbound email account
  * if the Enable Auto Import option is selected
  *
  * @return String Id of the sugar folder created.
  */
 function createAutoImportSugarFolder()
 {
     global $current_user;
     $guid = create_guid();
     $GLOBALS['log']->debug("Creating Sugar Folder for IE with id {$guid}");
     $folder = new SugarFolder();
     $folder->id = $guid;
     $folder->new_with_id = TRUE;
     $folder->name = $this->name;
     $folder->has_child = 0;
     $folder->is_group = 1;
     $folder->assign_to_id = $current_user->id;
     $folder->parent_folder = "";
     //If this inbound email is marked as inactive, don't add subscriptions.
     $addSubscriptions = $this->status == 'Inactive' || $this->mailbox_type == 'bounce' ? FALSE : TRUE;
     $folder->save($addSubscriptions);
     return $guid;
 }
$xtpl->assign('TRASHFOLDER', $trashFolder);
$xtpl->assign('SENTFOLDER', $sentFolder);
$xtpl->assign('SERVER_TYPE', $app_list_strings['dom_email_server_type'][$focus->protocol]);
$xtpl->assign('SSL', $ssl);
$xtpl->assign('TLS', $tls);
$xtpl->assign('CERT', $ca);
$xtpl->assign('MARK_READ', $delete_seen);
// deferred
//$xtpl->assign('QUEUE', $queue);
$createCaseRowStyle = "display:none";
$leaveMessagesOnMailServerStyle = "display:none";
if ($focus->is_personal) {
    $xtpl->assign('EDIT_GROUP_FOLDER_STYLE', "display:none");
} else {
    $groupFolderName = $mod_strings['LBL_NONE'];
    $folder = new SugarFolder();
    if (!empty($focus->groupfolder_id)) {
        $folder->retrieve($focus->groupfolder_id);
        $groupFolderName = $folder->name;
        $leaveMessagesOnMailServerStyle = "display:''";
    }
    // if
    $xtpl->assign('ASSIGN_TO_FOLDER', $groupFolderName);
    $xtpl->assign('EDIT_GROUP_FOLDER_STYLE', "display:''");
    if ($focus->isMailBoxTypeCreateCase()) {
        $createCaseRowStyle = "display:''";
    }
}
$xtpl->assign('LEAVEMESSAGESONMAILSERVER_STYLE', $leaveMessagesOnMailServerStyle);
$xtpl->assign('LEAVEMESSAGESONMAILSERVER', $leaveMessagesOnMailServer);
$xtpl->assign('CREATE_CASE_ROW_STYLE', $createCaseRowStyle);
Example #4
0
/**
 * 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;
}
Example #5
0
 /**
  * Returns the number of "new" items (based on passed criteria)
  * @param string id ID of folder
  * @param array criteria
  * 		expected:
  * 		array('field' => 'status',
  * 				'value' => 'unread');
  * @param array
  * @return int
  */
 function getCountNewItems($id, $criteria, $folder)
 {
     global $current_user;
     $sugarFolder = new SugarFolder();
     return $sugarFolder->getCountUnread($id);
     /*
     $sugarFolder = new SugarFolder();
     return $sugarFolder->getCountUnread($id);
     /*
     $count = 0;
     
     // if dynamic query is for "My Drafts" run special count logic.
     if(!empty($folder['dynamic_query'])) {
     	$folder['dynamic_query'] = from_html($folder['dynamic_query']);
     	if(strpos($folder['dynamic_query'], "type = 'draft'") !== false) {
     		$q = "SELECT COUNT(*) c " . substr($folder['dynamic_query'], strpos($folder['dynamic_query'], "FROM"));
     		$r = $this->db->query($q);
     		$a = $this->db->fetchByAssoc($r);
     		$count = $a['c'];
     	}
     }
     
     $q = "SELECT polymorphic_module, polymorphic_id FROM folders_rel fr JOIN folders f ON fr.folder_id = f.id WHERE f.id = '{$id}'";
     $r = $this->db->query($q);
     $ins = ""; // IN () scope clause
     
     while($a = $this->db->fetchByAssoc($r)) {
     	$table = strtolower($a['polymorphic_module']);
     
     	if(!empty($ins)) {
     		$ins .= ", ";
     	}
     
     	$ins .= "'{$a['polymorphic_id']}'";
     }
     
     if(isset($table)) {
     	$qC = "SELECT count(*) c FROM {$table} WHERE deleted = 0 AND id IN ({$ins}) AND {$criteria['field']} = '{$criteria['value']}'";
     	$rC = $this->db->query($qC);
     	$aC = $this->db->fetchByAssoc($rC);
     
     	return ($count + $aC['c']);
     }
     
     return $count;;
     */
 }
Example #6
0
    $xtpl->assign("EDIT_TEMPLATE", "visibility:hidden");
}
if ($focus->port == 110 || $focus->port == 995) {
    $xtpl->assign('DISPLAY', "display:''");
} else {
    $xtpl->assign('DISPLAY', "display:none");
}
$leaveMessagesOnMailServerStyle = "display:none";
if ($focus->is_personal) {
    $xtpl->assign('DISABLE_GROUP', 'DISABLED');
    $xtpl->assign('EDIT_GROUP_FOLDER_STYLE', "display:none");
    $xtpl->assign('CREATE_GROUP_FOLDER_STYLE', "display:none");
    $xtpl->assign('MAILBOX_TYPE_STYLE', "display:none");
    $xtpl->assign('AUTO_IMPORT_STYLE', "display:none");
} else {
    $folder = new SugarFolder();
    $xtpl->assign('CREATE_GROUP_FOLDER_STYLE', "display:''");
    $xtpl->assign('MAILBOX_TYPE_STYLE', "display:''");
    $xtpl->assign('AUTO_IMPORT_STYLE', "display:''");
    $ret = $folder->getFoldersForSettings($current_user);
    //For existing records, do not allow
    $is_auto_import_disabled = "";
    if (!empty($focus->groupfolder_id)) {
        $is_auto_import = "checked";
        $xtpl->assign('EDIT_GROUP_FOLDER_STYLE', "visibility:inline");
        $leaveMessagesOnMailServerStyle = "display:''";
        $allow_outbound = isset($storedOptions['allow_outbound_group_usage']) && $storedOptions['allow_outbound_group_usage'] == 1 ? 'CHECKED' : '';
    } else {
        $xtpl->assign('EDIT_GROUP_FOLDER_STYLE', "visibility:hidden");
    }
    $xtpl->assign('ALLOW_OUTBOUND_USAGE', $allow_outbound);
Example #7
0
 /**
  * Returns the number of "new" items (based on passed criteria)
  * @param string id ID of folder
  * @param array criteria
  * 		expected:
  * 		array('field' => 'status',
  * 				'value' => 'unread');
  * @param array
  * @return int
  */
 function getCountNewItems($id, $criteria, $folder)
 {
     global $current_user;
     $sugarFolder = new SugarFolder();
     return $sugarFolder->getCountUnread($id);
 }
Example #8
0
 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
 * 
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License version 3.
 * 
 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
 * these Appropriate Legal Notices must retain the display of the "Powered by
 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
 * technical reasons, the Appropriate Legal Notices must display the words
 * "Powered by SugarCRM".
 ********************************************************************************/
/*********************************************************************************
 * Description:  Saves an Account record and then redirects the browser to the
 * defined return URL.
 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
 * All Rights Reserved.
 * Contributor(s): ______________________________________..
 ********************************************************************************/
require_once 'include/SugarFolders/SugarFolders.php';
$folder = new SugarFolder();
$_REQUEST['name'] = $_REQUEST['groupFolderAddName'];
$_REQUEST['parent_folder'] = $_REQUEST['groupFoldersAdd'];
$_REQUEST['group_id'] = $_REQUEST['groupFoldersUser'];
if (empty($_REQUEST['record'])) {
    $folder->setFolder($_REQUEST);
} else {
    $folder->updateFolder($_REQUEST);
}
$body1 = "\n\t<script type='text/javascript'>\n\t\tfunction refreshOpener() {\n\t\t\twindow.opener.refresh_group_folder_list('{$folder->id}','{$folder->name}')\n\t\t\twindow.close();\n\t\t} // fn\n\t\trefreshOpener();\n\t</script>";
echo $body1;
Example #9
0
 /**
  * Re-used option getter for Show Accounts multiselect pane
  */
 function getShowAccountsOptions(&$ie)
 {
     global $current_user;
     global $app_strings;
     global $mod_strings;
     $ieAccountsFull = $ie->retrieveAllByGroupId($current_user->id);
     $ieAccountsShowOptionsMeta = array();
     $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
     $defaultIEAccount = $ie->getUsersDefaultOutboundServerId($current_user);
     foreach ($ieAccountsFull as $k => $v) {
         $selected = !empty($showFolders) && in_array($v->id, $showFolders) ? true : false;
         $default = $defaultIEAccount == $v->id ? TRUE : FALSE;
         $has_groupfolder = !empty($v->groupfolder_id) ? TRUE : FALSE;
         $type = $v->is_personal ? $mod_strings['LBL_MAILBOX_TYPE_PERSONAL'] : $mod_strings['LBL_MAILBOX_TYPE_GROUP'];
         $ieAccountsShowOptionsMeta[] = array("id" => $v->id, "name" => $v->name, 'is_active' => $selected, 'server_url' => $v->server_url, 'is_group' => !$v->is_personal, 'group_id' => $v->group_id, 'is_default' => $default, 'has_groupfolder' => $has_groupfolder, 'type' => $type);
     }
     //Retrieve the grou folders
     $f = new SugarFolder();
     $groupFolders = $f->getGroupFoldersForSettings($current_user);
     foreach ($groupFolders as $singleGroup) {
         //Retrieve the related IE accounts.
         $relatedIEAccounts = $ie->retrieveByGroupFolderId($singleGroup['id']);
         if (count($relatedIEAccounts) == 0) {
             $server_url = $app_strings['LBL_EMAIL_MULT_GROUP_FOLDER_ACCOUNTS_EMPTY'];
         } else {
             if (count($relatedIEAccounts) == 1) {
                 if ($relatedIEAccounts[0]->status != 'Active' || $relatedIEAccounts[0]->mailbox_type == 'bounce') {
                     continue;
                 }
                 $server_url = $relatedIEAccounts[0]->server_url;
             } else {
                 $server_url = $app_strings['LBL_EMAIL_MULT_GROUP_FOLDER_ACCOUNTS'];
             }
         }
         $type = $mod_strings['LBL_MAILBOX_TYPE_GROUP_FOLDER'];
         $ieAccountsShowOptionsMeta[] = array("id" => $singleGroup['id'], "name" => $singleGroup['origName'], 'is_active' => $singleGroup['selected'], 'server_url' => $server_url, 'is_group' => true, 'group_id' => $singleGroup['id'], 'is_default' => FALSE, 'has_groupfolder' => true, 'type' => $type);
     }
     return $ieAccountsShowOptionsMeta;
 }
Example #10
0
/**
 * Certain updates to the IE account need to be reflected in the related SugarFolder since they are
 * created automatically.  Only valid for IE accounts with auto import turned on.
 *
 * @param string $fieldName The field name that changed
 * @param SugarBean $focus The InboundEmail bean being saved.
 */
function syncSugarFoldersWithBeanChanges($fieldName, $focus)
{
    $f = new SugarFolder();
    $f->retrieve($focus->groupfolder_id);
    switch ($fieldName) {
        case 'name':
        case 'team_id':
        case 'team_set_id':
            $f->{$fieldName} = $focus->{$fieldName};
            $f->save();
            break;
        case 'status':
            if ($focus->status == 'Inactive') {
                $f->clearSubscriptionsForFolder($focus->groupfolder_id);
            } else {
                if ($focus->mailbox_type != 'bounce') {
                    $f->addSubscriptionsToGroupFolder();
                }
            }
            break;
    }
}
 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
 * these Appropriate Legal Notices must retain the display of the "Powered by
 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
 * technical reasons, the Appropriate Legal Notices must display the words
 * "Powered by SugarCRM".
 ********************************************************************************/
$_REQUEST['edit'] = 'true';
require_once 'include/SugarFolders/SugarFolders.php';
// GLOBALS
global $mod_strings;
global $app_strings;
global $app_list_strings;
global $current_user;
global $sugar_config;
$ie = new InboundEmail();
$focus = new SugarFolder();
$javascript = new Javascript();
/* Start standard EditView setup logic */
if (isset($_REQUEST['record'])) {
    $GLOBALS['log']->debug("In EditGroupFolder view, about to retrieve record: " . $_REQUEST['record']);
    $result = $focus->retrieve($_REQUEST['record']);
    if ($result == null) {
        sugar_die($app_strings['ERROR_NO_RECORD']);
    }
}
$GLOBALS['log']->info("SugarFolder Edit View");
/* End standard EditView setup logic */
// TEMPLATE ASSIGNMENTS
$smarty = new Sugar_Smarty();
// standard assigns
$smarty->assign('mod_strings', $mod_strings);
Example #12
0
 /**
  * Creates defaults for the User
  * @param object $user User in focus
  */
 function preflightUser(&$user)
 {
     global $mod_strings;
     $goodToGo = $user->getPreference("email2Preflight", "Emails");
     $q = "SELECT count(*) count FROM folders f where f.created_by = '{$user->id}' AND f.folder_type = 'inbound' AND f.deleted = 0";
     $r = $user->db->query($q);
     $a = $user->db->fetchByAssoc($r);
     if ($a['count'] < 1) {
         require_once "include/SugarFolders/SugarFolders.php";
         // My Emails
         $folder = new SugarFolder();
         $folder->new_with_id = true;
         $folder->id = create_guid();
         $folder->name = $mod_strings['LNK_MY_INBOX'];
         $folder->has_child = 1;
         $folder->created_by = $user->id;
         $folder->modified_by = $user->id;
         $folder->is_dynamic = 1;
         $folder->folder_type = "inbound";
         $folder->dynamic_query = $this->generateDynamicFolderQuery('inbound', $user->id);
         $folder->save();
         // My Drafts
         $drafts = new SugarFolder();
         $drafts->name = $mod_strings['LNK_MY_DRAFTS'];
         $drafts->has_child = 0;
         $drafts->parent_folder = $folder->id;
         $drafts->created_by = $user->id;
         $drafts->modified_by = $user->id;
         $drafts->is_dynamic = 1;
         $drafts->folder_type = "draft";
         $drafts->dynamic_query = $this->generateDynamicFolderQuery('draft', $user->id);
         $drafts->save();
         // My Archived
         //$archived = new SugarFolder();
         //$archived->name = $mod_strings['LNK_MY_ARCHIVED_LIST'];
         //$archived->has_child = 0;
         //$archived->parent_folder = $folder->id;
         //$archived->created_by = $user->id;
         //$archived->modified_by = $user->id;
         //$archived->is_dynamic = 1;
         //$archived->dynamic_query = $this->generateDynamicFolderQuery('archived', $user->id);
         //$archived->save();
         // Sent Emails
         $archived = new SugarFolder();
         $archived->name = $mod_strings['LNK_SENT_EMAIL_LIST'];
         $archived->has_child = 0;
         $archived->parent_folder = $folder->id;
         $archived->created_by = $user->id;
         $archived->modified_by = $user->id;
         $archived->is_dynamic = 1;
         $archived->folder_type = "sent";
         $archived->dynamic_query = $this->generateDynamicFolderQuery('sent', $user->id);
         $archived->save();
         // set flag to show that this was run
         $user->setPreference("email2Preflight", true, 1, "Emails");
     }
 }
 /**
  * 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) {
                             if ($email->team_id != $toSugarFolder->team_id) {
                                 $email->team_id = $toSugarFolder->team_id;
                             }
                             // if
                             $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;
         }
         $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;
 }
Example #14
0
 /**
  * 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);
 }
Example #15
0
/**
 * 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;
}
Example #16
0
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;
}