public static function OnSendMentionGetEntityFields($arCommentFields) { if (!in_array($arCommentFields["ENTITY_TYPE"], CCrmLiveFeedEntity::GetAll())) { return false; } if (!CModule::IncludeModule("socialnetwork")) { return true; } $dbLog = CSocNetLog::GetList(array(), array("ID" => $arCommentFields["LOG_ID"]), false, false, array("ID", "ENTITY_ID", "EVENT_ID")); if ($arLog = $dbLog->Fetch()) { $genderSuffix = ""; $dbUser = CUser::GetByID($arCommentFields["USER_ID"]); if ($arUser = $dbUser->Fetch()) { $genderSuffix = $arUser["PERSONAL_GENDER"]; } switch ($arLog["EVENT_ID"]) { case "crm_company_add": $entityName = GetMessage("CRM_LF_COMPANY_ADD_COMMENT_MENTION_TITLE", array("#title#" => htmlspecialcharsbx(CCrmOwnerType::GetCaption(CCrmOwnerType::Company, $arLog["ENTITY_ID"], false)))); $notifyTag = "CRM_COMPANY_ADD|COMMENT_MENTION|" . $arCommentFields["ID"]; break; case "crm_contact_add": $entityName = GetMessage("CRM_LF_CONTACT_ADD_COMMENT_MENTION_TITLE", array("#title#" => htmlspecialcharsbx(CCrmOwnerType::GetCaption(CCrmOwnerType::Contact, $arLog["ENTITY_ID"], false)))); $notifyTag = "CRM_CONTACT_ADD|COMMENT_MENTION|" . $arCommentFields["ID"]; break; case "crm_lead_add": $entityName = GetMessage("CRM_LF_LEAD_ADD_COMMENT_MENTION_TITLE", array("#title#" => htmlspecialcharsbx(CCrmOwnerType::GetCaption(CCrmOwnerType::Lead, $arLog["ENTITY_ID"], false)))); $notifyTag = "CRM_LEAD_ADD|COMMENT_MENTION|" . $arCommentFields["ID"]; break; case "crm_deal_add": $entityName = GetMessage("CRM_LF_DEAL_ADD_COMMENT_MENTION_TITLE", array("#title#" => htmlspecialcharsbx(CCrmOwnerType::GetCaption(CCrmOwnerType::Deal, $arLog["ENTITY_ID"], false)))); $notifyTag = "CRM_DEAL_ADD|COMMENT_MENTION|" . $arCommentFields["ID"]; break; case "crm_company_responsible": $entityName = GetMessage("CRM_LF_COMPANY_RESPONSIBLE_COMMENT_MENTION_TITLE", array("#title#" => htmlspecialcharsbx(CCrmOwnerType::GetCaption(CCrmOwnerType::Company, $arLog["ENTITY_ID"], false)))); $notifyTag = "CRM_COMPANY_RESPONSIBLE|COMMENT_MENTION|" . $arCommentFields["ID"]; break; case "crm_contact_responsible": $entityName = GetMessage("CRM_LF_CONTACT_RESPONSIBLE_COMMENT_MENTION_TITLE", array("#title#" => htmlspecialcharsbx(CCrmOwnerType::GetCaption(CCrmOwnerType::Contact, $arLog["ENTITY_ID"], false)))); $notifyTag = "CRM_CONTACT_RESPONSIBLE|COMMENT_MENTION|" . $arCommentFields["ID"]; break; case "crm_lead_responsible": $entityName = GetMessage("CRM_LF_LEAD_RESPONSIBLE_COMMENT_MENTION_TITLE", array("#title#" => htmlspecialcharsbx(CCrmOwnerType::GetCaption(CCrmOwnerType::Lead, $arLog["ENTITY_ID"], false)))); $notifyTag = "CRM_LEAD_RESPONSIBLE|COMMENT_MENTION|" . $arCommentFields["ID"]; break; case "crm_deal_responsible": $entityName = GetMessage("CRM_LF_DEAL_RESPONSIBLE_COMMENT_MENTION_TITLE", array("#title#" => htmlspecialcharsbx(CCrmOwnerType::GetCaption(CCrmOwnerType::Deal, $arLog["ENTITY_ID"], false)))); $notifyTag = "CRM_DEAL_RESPONSIBLE|COMMENT_MENTION|" . $arCommentFields["ID"]; break; case "crm_company_message": $entityName = GetMessage("CRM_LF_COMPANY_MESSAGE_COMMENT_MENTION_TITLE", array("#title#" => htmlspecialcharsbx(CCrmOwnerType::GetCaption(CCrmOwnerType::Company, $arLog["ENTITY_ID"], false)))); $notifyTag = "CRM_COMPANY_MESSAGE|COMMENT_MENTION|" . $arCommentFields["ID"]; break; case "crm_contact_message": $entityName = GetMessage("CRM_LF_CONTACT_MESSAGE_COMMENT_MENTION_TITLE", array("#title#" => htmlspecialcharsbx(CCrmOwnerType::GetCaption(CCrmOwnerType::Contact, $arLog["ENTITY_ID"], false)))); $notifyTag = "CRM_CONTACT_MESSAGE|COMMENT_MENTION|" . $arCommentFields["ID"]; break; case "crm_lead_message": $entityName = GetMessage("CRM_LF_LEAD_MESSAGE_COMMENT_MENTION_TITLE", array("#title#" => htmlspecialcharsbx(CCrmOwnerType::GetCaption(CCrmOwnerType::Lead, $arLog["ENTITY_ID"], false)))); $notifyTag = "CRM_LEAD_MESSAGE|COMMENT_MENTION|" . $arCommentFields["ID"]; break; case "crm_deal_message": $entityName = GetMessage("CRM_LF_DEAL_MESSAGE_COMMENT_MENTION_TITLE", array("#title#" => htmlspecialcharsbx(CCrmOwnerType::GetCaption(CCrmOwnerType::Deal, $arLog["ENTITY_ID"], false)))); $notifyTag = "CRM_DEAL_MESSAGE|COMMENT_MENTION|" . $arCommentFields["ID"]; break; case "crm_activity_add": if ($arActivity = CCrmActivity::GetByID($arLog["ENTITY_ID"])) { switch ($arActivity["OWNER_TYPE_ID"]) { case CCrmOwnerType::Company: $ownerType = "COMPANY"; break; case CCrmOwnerType::Contact: $ownerType = "CONTACT"; break; case CCrmOwnerType::Lead: $ownerType = "LEAD"; break; case CCrmOwnerType::Deal: $ownerType = "DEAL"; break; } switch ($arActivity["TYPE_ID"]) { case CCrmActivityType::Meeting: $activityType = "MEETING"; break; case CCrmActivityType::Call: $activityType = "CALL"; break; case CCrmActivityType::Email: $activityType = "EMAIL"; break; } if ($ownerType && $activityType) { $entityName = GetMessage("CRM_LF_ACTIVITY_" . $activityType . "_" . $ownerType . "_COMMENT_MENTION_TITLE", array("#title#" => htmlspecialcharsbx(CCrmOwnerType::GetCaption($arActivity["OWNER_TYPE_ID"], $arActivity["OWNER_ID"], false)))); $notifyTag = "CRM_ACTIVITY_ADD|COMMENT_MENTION|" . $arCommentFields["ID"]; } } break; case "crm_invoice_add": if ($arInvoice = CCrmInvoice::GetByID($arLog["ENTITY_ID"])) { $entityName = GetMessage("CRM_LF_INVOICE_ADD_COMMENT_MENTION_TITLE", array("#id#" => $arInvoice["ID"])); $notifyTag = "CRM_INVOICE_ADD|COMMENT_MENTION|" . $arCommentFields["ID"]; } break; } if ($entityName) { $notifyMessage = GetMessage("CRM_LF_COMMENT_MENTION" . (strlen($genderSuffix) > 0 ? "_" . $genderSuffix : ""), array("#title#" => "<a href=\"#url#\" class=\"bx-notifier-item-action\">" . $entityName . "</a>")); $notifyMessageOut = GetMessage("CRM_LF_COMMENT_MENTION" . (strlen($genderSuffix) > 0 ? "_" . $genderSuffix : ""), array("#title#" => $entityName)) . " (" . "#server_name##url#)"; $strPathToLogCrmEntry = str_replace("#log_id#", $arLog["ID"], "/crm/stream/?log_id=#log_id#"); $strPathToLogCrmEntryComment = $strPathToLogCrmEntry . (strpos($strPathToLogCrmEntry, "?") !== false ? "&" : "?") . "commentID=" . $arCommentFields["ID"] . "#com" . $arCommentFields["ID"]; if (in_array($arLog["EVENT_ID"], array("crm_company_message", "crm_contact_message", "crm_deal_message", "crm_lead_message"))) { $strPathToLogEntry = str_replace("#log_id#", $arLog["ID"], COption::GetOptionString("socialnetwork", "log_entry_page", "/company/personal/log/#log_id#/", SITE_ID)); $strPathToLogEntryComment = $strPathToLogEntry . (strpos($strPathToLogEntry, "?") !== false ? "&" : "?") . "commentID=" . $arCommentFields["ID"] . "#com" . $arCommentFields["ID"]; } $arReturn = array("IS_CRM" => "Y", "URL" => $strPathToLogEntryComment, "CRM_URL" => $strPathToLogCrmEntryComment, "NOTIFY_MODULE" => "crm", "NOTIFY_TAG" => $notifyTag, "NOTIFY_MESSAGE" => $notifyMessage, "NOTIFY_MESSAGE_OUT" => $notifyMessageOut); return $arReturn; } else { return false; } } else { return false; } }
} elseif (!check_bitrix_sessid()) { $arResult[0] = "*"; } elseif (in_array($action, array("add_comment", "edit_comment", "delete_comment", "file_comment_upload"))) { $log_id = $_REQUEST["log_id"]; if ($arLog = CSocNetLog::GetByID($log_id)) { $log_entity_type = $arLog["ENTITY_TYPE"]; $arListParams = strpos($log_entity_type, "CRM") === 0 && IsModuleInstalled("crm") ? array("IS_CRM" => "Y", "CHECK_CRM_RIGHTS" => "Y") : array("CHECK_RIGHTS" => "Y", "USE_SUBSCRIBE" => "N"); } else { $log_id = 0; } if (intval($log_id) <= 0 || !($rsLog = CSocNetLog::GetList(array(), array("ID" => $log_id), false, false, array(), $arListParams)) || !($arLog = $rsLog->Fetch())) { $arResult["strMessage"] = GetMessage("Log event not found"); } if (!isset($arResult["strMessage"])) { $arEntityXMLID = array("tasks" => "TASK", "forum" => "FORUM", "photo_photo" => "PHOTO", "sonet" => "SOCNET", "lists_new_element" => array("WF", "WF", "FORUM|COMMENT")); if ($arLog["ENTITY_TYPE"] == "CRMACTIVITY" && CModule::IncludeModule('crm') && ($arActivity = CCrmActivity::GetByID($arLog["ENTITY_ID"], false)) && $arActivity["TYPE_ID"] == CCrmActivityType::Task) { $entity_xml_id = "TASK_" . $arActivity["ASSOCIATED_ENTITY_ID"]; } elseif ($arLog["ENTITY_TYPE"] == "WF" && $arLog["SOURCE_ID"] > 0 && CModule::IncludeModule('bizproc') && ($workflowId = \CBPStateService::getWorkflowByIntegerId($arLog["SOURCE_ID"]))) { $entity_xml_id = "WF_" . $workflowId; } else { $entity_xml_id = array_key_exists($arLog["EVENT_ID"], $arEntityXMLID) && $arLog["SOURCE_ID"] > 0 ? $arEntityXMLID[$arLog["EVENT_ID"]] . "_" . $arLog["SOURCE_ID"] : strtoupper($arLog["EVENT_ID"]) . "_" . $arLog["ID"]; } $arCommentEvent = CSocNetLogTools::FindLogCommentEventByLogEventID($arLog["EVENT_ID"]); if (!$arCommentEvent) { $arResult["strMessage"] = GetMessage("Comment event not found"); } } if (!isset($arResult["strMessage"])) { $feature = CSocNetLogTools::FindFeatureByEventID($arCommentEvent["EVENT_ID"]); if (array_key_exists("OPERATION_ADD", $arCommentEvent) && $arCommentEvent["OPERATION_ADD"] == "log_rights") { $bCanAddComments = CSocNetLogRights::CheckForUser($log_id, $GLOBALS["USER"]->GetID());
$commData[] = array('type' => $arComm['TYPE'], 'value' => $arComm['VALUE'], 'entityId' => $arComm['ENTITY_ID'], 'entityType' => CCrmOwnerType::ResolveName($arComm['ENTITY_TYPE_ID']), 'entityTitle' => $arComm['TITLE'], 'entityUrl' => CCrmOwnerType::GetShowUrl($arComm['ENTITY_TYPE_ID'], $arComm['ENTITY_ID'])); } unset($arComm); $userName = ''; if ($userID > 0) { $dbResUser = CUser::GetByID($userID); $userName = is_array($user = $dbResUser->Fetch()) ? CUser::FormatName(CSite::GetNameFormat(false), $user, true, false) : ''; } $nowStr = ConvertTimeStamp(MakeTimeStamp($now), 'FULL', $siteID); CCrmActivity::PrepareStorageElementIDs($arFields); CCrmActivity::PrepareStorageElementInfo($arFields); $jsonFields = array('ID' => $ID, 'typeID' => CCrmActivityType::Email, 'ownerID' => $arFields['OWNER_ID'], 'ownerType' => CCrmOwnerType::ResolveName($arFields['OWNER_TYPE_ID']), 'ownerTitle' => CCrmOwnerType::GetCaption($arFields['OWNER_TYPE_ID'], $arFields['OWNER_ID']), 'ownerUrl' => CCrmOwnerType::GetShowUrl($arFields['OWNER_TYPE_ID'], $arFields['OWNER_ID']), 'subject' => $subject, 'description' => $description, 'descriptionHtml' => $messageHtml, 'location' => '', 'start' => $nowStr, 'end' => $nowStr, 'deadline' => $nowStr, 'completed' => true, 'notifyType' => CCrmActivityNotifyType::None, 'notifyValue' => 0, 'priority' => CCrmActivityPriority::Medium, 'responsibleName' => $userName, 'responsibleUrl' => CComponentEngine::MakePathFromTemplate('/company/personal/user/#user_id#/', array('user_id' => $userID)), 'storageTypeID' => $storageTypeID, 'files' => isset($arFields['FILES']) ? $arFields['FILES'] : array(), 'webdavelements' => isset($arFields['WEBDAV_ELEMENTS']) ? $arFields['WEBDAV_ELEMENTS'] : array(), 'diskfiles' => isset($arFields['DISK_FILES']) ? $arFields['DISK_FILES'] : array(), 'communications' => $commData); echo CUtil::PhpToJSObject(array('ACTIVITY' => $jsonFields)); } elseif ($action == 'GET_ACTIVITY') { $ID = isset($_POST['ID']) ? intval($_POST['ID']) : 0; $arFields = CCrmActivity::GetByID($ID); if (!is_array($arFields)) { echo CUtil::PhpToJsObject(array('ERROR' => 'NOT FOUND')); die; } $commData = array(); $communications = CCrmActivity::GetCommunications($ID); foreach ($communications as &$arComm) { CCrmActivity::PrepareCommunicationInfo($arComm); $commData[] = array('type' => $arComm['TYPE'], 'value' => $arComm['VALUE'], 'entityId' => $arComm['ENTITY_ID'], 'entityType' => CCrmOwnerType::ResolveName($arComm['ENTITY_TYPE_ID']), 'entityTitle' => $arComm['TITLE']); } unset($arComm); $storageTypeID = isset($arFields['STORAGE_TYPE_ID']) ? intval($arFields['STORAGE_TYPE_ID']) : CCrmActivityStorageType::Undefined; CCrmActivity::PrepareStorageElementIDs($arFields); CCrmActivity::PrepareStorageElementInfo($arFields); echo CUtil::PhpToJSObject(array('ACTIVITY' => array('ID' => $ID, 'typeID' => $arFields['TYPE_ID'], 'associatedEntityID' => isset($arFields['ASSOCIATED_ENTITY_ID']) ? $arFields['ASSOCIATED_ENTITY_ID'] : '0', 'ownerID' => $arFields['OWNER_ID'], 'ownerType' => CCrmOwnerType::ResolveName($arFields['OWNER_TYPE_ID']), 'ownerTitle' => CCrmOwnerType::GetCaption($arFields['OWNER_TYPE_ID'], $arFields['OWNER_ID']), 'ownerUrl' => CCrmOwnerType::GetShowUrl($arFields['OWNER_TYPE_ID'], $arFields['OWNER_ID']), 'subject' => $arFields['SUBJECT'], 'description' => $arFields['DESCRIPTION'], 'location' => $arFields['LOCATION'], 'direction' => intval($arFields['DIRECTION']), 'start' => $arFields['START_TIME'], 'end' => $arFields['END_TIME'], 'completed' => isset($arFields['COMPLETED']) && $arFields['COMPLETED'] === 'Y', 'notifyType' => intval($arFields['NOTIFY_TYPE']), 'notifyValue' => intval($arFields['NOTIFY_VALUE']), 'priority' => intval($arFields['PRIORITY']), 'responsibleName' => CCrmViewHelper::GetFormattedUserName(isset($arFields['RESPONSIBLE_ID']) ? intval($arFields['RESPONSIBLE_ID']) : 0), 'storageTypeID' => $storageTypeID, 'files' => isset($arFields['FILES']) ? $arFields['FILES'] : array(), 'webdavelements' => isset($arFields['WEBDAV_ELEMENTS']) ? $arFields['WEBDAV_ELEMENTS'] : array(), 'diskfiles' => isset($arFields['DISK_FILES']) ? $arFields['DISK_FILES'] : array(), 'communications' => $commData)));
__CrmMobileActivityEditEndResonse(array('DELETED_ENTITY_ID' => $ID)); } else { //$DB->Rollback(); __CrmMobileActivityEditEndResonse(array('ERROR' => GetMessage('CRM_ACTIVITY_COULD_NOT_DELETE'))); } } elseif ($action === 'GET_ENTITY') { __IncludeLang(dirname(__FILE__) . '/lang/' . LANGUAGE_ID . '/' . basename(__FILE__)); $typeName = isset($_REQUEST['ENTITY_TYPE_NAME']) ? $_REQUEST['ENTITY_TYPE_NAME'] : ''; if ($typeName !== 'ACTIVITY') { __CrmMobileActivityEditEndResonse(array('ERROR' => GetMessage('CRM_ENTITY_TYPE_NOT_SUPPORTED', array('#ENTITY_TYPE#' => $typeName)))); } $ID = isset($_REQUEST['ENTITY_ID']) ? intval($_REQUEST['ENTITY_ID']) : 0; if ($ID <= 0) { __CrmMobileActivityEditEndResonse(array('ERROR' => GetMessage('CRM_ENTITY_ID_NOT_FOUND'))); } $item = CCrmActivity::GetByID($ID, true); if (!$item) { __CrmMobileActivityEditEndResonse(array('ERROR' => GetMessage('CRM_ACTIVITY_NOT_FOUND', array('#ID#' => $ID)))); } $formatParams = isset($_REQUEST['FORMAT_PARAMS']) ? $_REQUEST['FORMAT_PARAMS'] : array(); CCrmMobileHelper::PrepareActivityItem($item, $formatParams, array('ENABLE_COMMUNICATIONS' => true)); __CrmMobileActivityEditEndResonse(array('ENTITY' => CCrmMobileHelper::PrepareActivityData($item))); } elseif ($action === 'COMPLETE') { __IncludeLang(dirname(__FILE__) . '/lang/' . LANGUAGE_ID . '/' . basename(__FILE__)); $typeName = isset($_REQUEST['ENTITY_TYPE_NAME']) ? $_REQUEST['ENTITY_TYPE_NAME'] : ''; if ($typeName !== 'ACTIVITY') { __CrmMobileActivityEditEndResonse(array('ERROR' => GetMessage('CRM_ENTITY_TYPE_NOT_SUPPORTED', array('#ENTITY_TYPE#' => $typeName)))); } $data = isset($_REQUEST['ENTITY_DATA']) && is_array($_REQUEST['ENTITY_DATA']) ? $_REQUEST['ENTITY_DATA'] : array(); if (count($data) == 0) { __CrmMobileActivityEditEndResonse(array('ERROR' => GetMessage('CRM_ENTITY_DATA_NOT_FOUND')));
public static function EmailMessageAdd($arMessageFields, $ACTION_VARS) { if (!CModule::IncludeModule('crm')) { return false; } $date = isset($arMessageFields['FIELD_DATE']) ? $arMessageFields['FIELD_DATE'] : ''; $maxAgeDays = intval(COption::GetOptionString('crm', 'email_max_age', 7)); $maxAge = $maxAgeDays > 0 ? $maxAgeDays * 86400 : 0; if ($maxAge > 0 && $date !== '') { $now = time() + CTimeZone::GetOffset(); $timestamp = MakeTimeStamp($date, FORMAT_DATETIME); if ($now - $timestamp > $maxAge) { //Time threshold is exceeded return false; } } $crmEmail = strtolower(trim(COption::GetOptionString('crm', 'mail', ''))); $msgID = isset($arMessageFields['ID']) ? intval($arMessageFields['ID']) : 0; $mailboxID = isset($arMessageFields['MAILBOX_ID']) ? intval($arMessageFields['MAILBOX_ID']) : 0; $from = isset($arMessageFields['FIELD_FROM']) ? $arMessageFields['FIELD_FROM'] : ''; $replyTo = isset($arMessageFields['FIELD_REPLY_TO']) ? $arMessageFields['FIELD_REPLY_TO'] : ''; if ($replyTo !== '') { // Ignore FROM if REPLY_TO EXISTS $from = $replyTo; } $addresserInfo = CCrmMailHelper::ParseEmail($from); if ($crmEmail !== '' && strcasecmp($addresserInfo['EMAIL'], $crmEmail) === 0) { // Ignore emails from ourselves return false; } $to = isset($arMessageFields['FIELD_TO']) ? $arMessageFields['FIELD_TO'] : ''; $cc = isset($arMessageFields['FIELD_CC']) ? $arMessageFields['FIELD_CC'] : ''; $bcc = isset($arMessageFields['FIELD_BCC']) ? $arMessageFields['FIELD_BCC'] : ''; $addresseeEmails = array_unique(array_merge($to !== '' ? CMailUtil::ExtractAllMailAddresses($to) : array(), $cc !== '' ? CMailUtil::ExtractAllMailAddresses($cc) : array(), $bcc !== '' ? CMailUtil::ExtractAllMailAddresses($bcc) : array()), SORT_STRING); if ($mailboxID > 0) { $dbMailbox = CMailBox::GetById($mailboxID); $arMailbox = $dbMailbox->Fetch(); // POP3 mailboxes are ignored - they bound to single email if ($arMailbox && $arMailbox['SERVER_TYPE'] === 'smtp' && (empty($crmEmail) || !in_array($crmEmail, $addresseeEmails, true))) { return false; } } $subject = isset($arMessageFields['SUBJECT']) ? $arMessageFields['SUBJECT'] : ''; $body = isset($arMessageFields['BODY']) ? $arMessageFields['BODY'] : ''; $arBodyEmails = null; $userID = 0; $parentID = 0; $ownerTypeID = CCrmOwnerType::Undefined; $ownerID = 0; $addresserID = self::FindUserIDByEmail($addresserInfo['EMAIL']); if ($addresserID > 0 && Bitrix\Crm\Integration\IntranetManager::isExternalUser($addresserID)) { //Forget about extranet user $addresserID = 0; } $arCommEmails = $addresserID <= 0 ? array($addresserInfo['EMAIL']) : ($crmEmail !== '' ? array_diff($addresseeEmails, array($crmEmail)) : $addresseeEmails); //Trying to fix strange behaviour of array_diff under OPcache (issue #60862) $arCommEmails = array_filter($arCommEmails); $targInfo = CCrmActivity::ParseUrn(CCrmActivity::ExtractUrnFromMessage($arMessageFields, CCrmEMailCodeAllocation::GetCurrent())); $targActivity = $targInfo['ID'] > 0 ? CCrmActivity::GetByID($targInfo['ID'], false) : null; // Check URN if (!$targActivity && (!isset($targActivity['URN']) || strtoupper($targActivity['URN']) !== strtoupper($targInfo['URN']))) { $targActivity = null; } if ($targActivity) { $postingID = self::ExtractPostingID($arMessageFields); if ($postingID > 0 && isset($targActivity['ASSOCIATED_ENTITY_ID']) && intval($targActivity['ASSOCIATED_ENTITY_ID']) === $postingID) { // Ignore - it is our message. return false; } $parentID = $targActivity['ID']; $subject = CCrmActivity::ClearUrn($subject); if ($addresserID > 0) { $userID = $addresserID; } elseif (isset($targActivity['RESPONSIBLE_ID'])) { $userID = $targActivity['RESPONSIBLE_ID']; } if (isset($targActivity['OWNER_TYPE_ID'])) { $ownerTypeID = intval($targActivity['OWNER_TYPE_ID']); } if (isset($targActivity['OWNER_ID'])) { $ownerID = intval($targActivity['OWNER_ID']); } $arCommData = self::ExtractCommsFromEmails($arCommEmails); if ($ownerTypeID > 0 && $ownerID > 0) { if (empty($arCommData)) { if ($addresserID > 0) { foreach ($addresseeEmails as $email) { if ($email === $crmEmail) { continue; } $arCommData = array(self::CreateComm($ownerTypeID, $ownerID, $email)); } } else { $arCommData = array(self::CreateComm($ownerTypeID, $ownerID, $addresserInfo['EMAIL'])); } } elseif ($ownerTypeID !== CCrmOwnerType::Deal) { //Check if owner in communications. Otherwise clear owner. //There is only one exception for DEAL - it entity has no communications $isOwnerInComms = false; foreach ($arCommData as &$arCommItem) { $commEntityTypeID = isset($arCommItem['ENTITY_TYPE_ID']) ? $arCommItem['ENTITY_TYPE_ID'] : CCrmOwnerType::Undefined; $commEntityID = isset($arCommItem['ENTITY_ID']) ? $arCommItem['ENTITY_ID'] : 0; if ($commEntityTypeID === $ownerTypeID && $commEntityID === $ownerID) { $isOwnerInComms = true; break; } } unset($arCommItem); if (!$isOwnerInComms) { $ownerTypeID = CCrmOwnerType::Undefined; $ownerID = 0; } } } } else { if ($addresserID > 0) { //It is email from registred user $userID = $addresserID; if (empty($arCommEmails)) { $arBodyEmails = self::ExtractEmailsFromBody($body); //Clear system user emails if (!empty($arBodyEmails)) { foreach ($arBodyEmails as $email) { if (self::FindUserIDByEmail($email) <= 0) { $arCommEmails[] = $email; } } } } // Try to resolve communications $arCommData = self::ExtractCommsFromEmails($arCommEmails); } else { //It is email from unknown user //Try to resolve bindings from addresser $arCommData = self::ExtractCommsFromEmails($arCommEmails); if (!empty($arCommData)) { // Try to resolve responsible user foreach ($arCommData as &$arComm) { $userID = self::ResolveResponsibleID($arComm['ENTITY_TYPE_ID'], $arComm['ENTITY_ID']); if ($userID > 0) { break; } } unset($arComm); } } // Try to resolve owner by old-style method--> $arACTION_VARS = explode('&', $ACTION_VARS); for ($i = 0, $ic = count($arACTION_VARS); $i < $ic; $i++) { $v = $arACTION_VARS[$i]; if ($pos = strpos($v, '=')) { $name = substr($v, 0, $pos); ${$name} = urldecode(substr($v, $pos + 1)); } } $arTypeNames = CCrmOwnerType::GetNames(array(CCrmOwnerType::Lead, CCrmOwnerType::Deal, CCrmOwnerType::Contact, CCrmOwnerType::Company)); foreach ($arTypeNames as $typeName) { $regexVar = 'W_CRM_ENTITY_REGEXP_' . $typeName; if (empty(${$regexVar})) { continue; } $match = array(); if (preg_match('/' . ${$regexVar} . '/i' . BX_UTF_PCRE_MODIFIER, $subject, $match) === 1) { $ownerID = intval($match[1]); $ownerTypeID = CCrmOwnerType::ResolveID($typeName); break; } } // <-- Try to resolve owner by old-style method // Filter communications by owner if ($ownerTypeID > 0 && $ownerID > 0) { if (!empty($arCommData)) { foreach ($arCommData as $commKey => $arComm) { if ($arComm['ENTITY_TYPE_ID'] === $ownerTypeID && $arComm['ENTITY_ID'] === $ownerID) { continue; } unset($arCommData[$commKey]); } $arCommData = array_values($arCommData); } if (empty($arCommData)) { if ($addresserID > 0) { foreach ($addresseeEmails as $email) { if ($email === $crmEmail) { continue; } $arCommData = array(self::CreateComm($ownerTypeID, $ownerID, $email)); } } else { $arCommData = array(self::CreateComm($ownerTypeID, $ownerID, $addresserInfo['EMAIL'])); } } } } $arBindingData = self::ConvertCommsToBindings($arCommData); // Check bindings for converted leads --> // Not Existed entities are ignored. Converted leads are ignored if their associated entities (contacts, companies, deals) are contained in bindings. $arCorrectedBindingData = array(); $arConvertedLeadData = array(); foreach ($arBindingData as $bindingKey => &$arBinding) { if ($arBinding['TYPE_ID'] !== CCrmOwnerType::Lead) { if (self::IsEntityExists($arBinding['TYPE_ID'], $arBinding['ID'])) { $arCorrectedBindingData[$bindingKey] = $arBinding; } continue; } $arFields = self::GetEntity(CCrmOwnerType::Lead, $arBinding['ID'], array('STATUS_ID')); if (!is_array($arFields)) { continue; } if (isset($arFields['STATUS_ID']) && $arFields['STATUS_ID'] === 'CONVERTED') { $arConvertedLeadData[$bindingKey] = $arBinding; } else { $arCorrectedBindingData[$bindingKey] = $arBinding; } } unset($arBinding); foreach ($arConvertedLeadData as &$arConvertedLead) { $leadID = $arConvertedLead['ID']; $exists = false; $dbRes = CCrmCompany::GetListEx(array(), array('LEAD_ID' => $leadID, 'CHECK_PERMISSIONS' => 'N'), false, false, array('ID')); if ($dbRes) { while ($arRes = $dbRes->Fetch()) { if (isset($arCorrectedBindingData[self::PrepareEntityKey(CCrmOwnerType::Company, $arRes['ID'])])) { $exists = true; break; } } } if ($exists) { continue; } $dbRes = CCrmContact::GetListEx(array(), array('LEAD_ID' => $leadID, 'CHECK_PERMISSIONS' => 'N'), false, false, array('ID')); if ($dbRes) { while ($arRes = $dbRes->Fetch()) { if (isset($arCorrectedBindingData[self::PrepareEntityKey(CCrmOwnerType::Contact, $arRes['ID'])])) { $exists = true; break; } } } if ($exists) { continue; } $dbRes = CCrmDeal::GetListEx(array(), array('LEAD_ID' => $leadID, 'CHECK_PERMISSIONS' => 'N'), false, false, array('ID')); if ($dbRes) { while ($arRes = $dbRes->Fetch()) { if (isset($arCorrectedBindingData[self::PrepareEntityKey(CCrmOwnerType::Deal, $arRes['ID'])])) { $exists = true; break; } } } if ($exists) { continue; } $arCorrectedBindingData[self::PrepareEntityKey(CCrmOwnerType::Lead, $leadID)] = $arConvertedLead; } unset($arConvertedLead); $arBindingData = $arCorrectedBindingData; // <-- Check bindings for converted leads // If no bindings are found then create new lead from this message // Skip lead creation if email list is empty. Otherwise we will create lead with no email-addresses. It is absolutely useless. $emailQty = count($arCommEmails); if (empty($arBindingData) && $emailQty > 0) { if (strtoupper(COption::GetOptionString('crm', 'email_create_lead_for_new_addresser', 'Y')) !== 'Y') { // Creation of new lead is not allowed return true; } //"Lead from forwarded email..." or "Lead from email..." $title = $subject !== '' ? $subject : GetMessage($addresserID > 0 ? 'CRM_MAIL_LEAD_FROM_USER_EMAIL_TITLE' : 'CRM_MAIL_LEAD_FROM_EMAIL_TITLE', array('%SENDER%' => $addresserInfo['ORIGINAL'])); $comment = ''; if ($body !== '') { // Remove extra new lines (fix for #31807) $comment = preg_replace("/(\r\n|\n|\r)+/", '<br/>', htmlspecialcharsbx($body)); } if ($comment === '') { $comment = htmlspecialcharsbx($subject); } $name = ''; if ($addresserID <= 0) { $name = $addresserInfo['NAME']; } else { //Try get name from body for ($i = 0; $i < $emailQty; $i++) { $email = $arCommEmails[$i]; $match = array(); if (preg_match('/"([^"]+)"\\s*<' . $email . '>/i' . BX_UTF_PCRE_MODIFIER, $body, $match) === 1 && count($match) > 1) { $name = $match[1]; break; } if (preg_match('/"([^"]+)"\\s*[\\s*mailto\\:\\s*' . $email . ']/i' . BX_UTF_PCRE_MODIFIER, $body, $match) === 1 && count($match) > 1) { $name = $match[1]; break; } } if ($name === '') { $name = $arCommEmails[0]; } } $arLeadFields = array('TITLE' => $title, 'NAME' => $name, 'STATUS_ID' => 'NEW', 'COMMENTS' => $comment, 'SOURCE_DESCRIPTION' => GetMessage('CRM_MAIL_LEAD_FROM_EMAIL_SOURCE', array('%SENDER%' => $addresserInfo['ORIGINAL'])), 'OPENED' => 'Y', 'FM' => array('EMAIL' => array())); $sourceList = CCrmStatus::GetStatusList('SOURCE'); $sourceID = COption::GetOptionString('crm', 'email_lead_source_id', ''); if ($sourceID === '' || !isset($sourceList[$sourceID])) { if (isset($sourceList['EMAIL'])) { $sourceID = 'EMAIL'; } elseif (isset($sourceList['OTHER'])) { $sourceID = 'OTHER'; } } if ($sourceID !== '') { $arLeadFields['SOURCE_ID'] = $sourceID; } $responsibleID = intval(COption::GetOptionString('crm', 'email_lead_responsible_id', 0)); if ($responsibleID > 0) { $arLeadFields['CREATED_BY_ID'] = $arLeadFields['MODIFY_BY_ID'] = $arLeadFields['ASSIGNED_BY_ID'] = $responsibleID; if ($userID === 0) { $userID = $responsibleID; } } for ($i = 0; $i < $emailQty; $i++) { $arLeadFields['FM']['EMAIL']['n' . ($i + 1)] = array('VALUE_TYPE' => 'WORK', 'VALUE' => $arCommEmails[$i]); } $leadEntity = new CCrmLead(false); $leadID = $leadEntity->Add($arLeadFields, true, array('DISABLE_USER_FIELD_CHECK' => true, 'REGISTER_SONET_EVENT' => true, 'CURRENT_USER' => $responsibleID)); // TODO: log error if ($leadID > 0) { $arBizProcErrors = array(); CCrmBizProcHelper::AutoStartWorkflows(CCrmOwnerType::Lead, $leadID, CCrmBizProcEventType::Create, $arBizProcErrors); $arCommData = array(); for ($i = 0; $i < $emailQty; $i++) { $arCommData[] = self::CreateComm(CCrmOwnerType::Lead, $leadID, $arCommEmails[$i]); } $arBindingData = array(self::PrepareEntityKey(CCrmOwnerType::Lead, $leadID) => self::CreateBinding(CCrmOwnerType::Lead, $leadID)); } } // Terminate processing if no bindings are found. if (empty($arBindingData)) { // Try to export vcf-files before exit if email from registered user if ($addresserID > 0) { $dbAttachment = CMailAttachment::GetList(array(), array('MESSAGE_ID' => $msgID)); while ($arAttachment = $dbAttachment->Fetch()) { if (GetFileExtension(strtolower($arAttachment['FILE_NAME'])) === 'vcf') { if ($arAttachment['FILE_ID']) { $arAttachment['FILE_DATA'] = CMailAttachment::getContents($arAttachment); } self::TryImportVCard($arAttachment['FILE_DATA']); } } } return false; } // If owner info not defined set it by default if ($ownerID <= 0 || $ownerTypeID <= 0) { if (count($arBindingData) > 1) { // Search owner in specified order: Contact, Company, Lead. $arTypeIDs = array(CCrmOwnerType::Contact, CCrmOwnerType::Company, CCrmOwnerType::Lead); foreach ($arTypeIDs as $typeID) { foreach ($arBindingData as &$arBinding) { if ($arBinding['TYPE_ID'] === $typeID) { $ownerTypeID = $typeID; $ownerID = $arBinding['ID']; break; } } unset($arBinding); if ($ownerID > 0 && $ownerTypeID > 0) { break; } } } if ($ownerID <= 0 || $ownerTypeID <= 0) { $arBinding = array_shift(array_values($arBindingData)); $ownerTypeID = $arBinding['TYPE_ID']; $ownerID = $arBinding['ID']; } } // Precessing of attachments --> $attachmentMaxSizeMb = intval(COption::GetOptionString('crm', 'email_attachment_max_size', 16)); $attachmentMaxSize = $attachmentMaxSizeMb > 0 ? $attachmentMaxSizeMb * 1048576 : 0; $arFilesData = array(); $dbAttachment = CMailAttachment::GetList(array(), array('MESSAGE_ID' => $msgID)); $arBannedAttachments = array(); while ($arAttachment = $dbAttachment->Fetch()) { if ($arAttachment['FILE_NAME'] === '1.tmp') { // HACK: For bug in module 'Mail' continue; } elseif (GetFileExtension(strtolower($arAttachment['FILE_NAME'])) === 'vcf') { if ($arAttachment['FILE_ID']) { $arAttachment['FILE_DATA'] = CMailAttachment::getContents($arAttachment); } self::TryImportVCard($arAttachment['FILE_DATA']); } $fileSize = isset($arAttachment['FILE_SIZE']) ? intval($arAttachment['FILE_SIZE']) : 0; if ($fileSize <= 0) { //Skip zero lenth files continue; } if ($attachmentMaxSize > 0 && $fileSize > $attachmentMaxSize) { //File size limit is exceeded $arBannedAttachments[] = array('name' => $arAttachment['FILE_NAME'], 'size' => $fileSize); continue; } if ($arAttachment['FILE_ID'] && empty($arAttachment['FILE_DATA'])) { $arAttachment['FILE_DATA'] = CMailAttachment::getContents($arAttachment); } $arFilesData[] = array('name' => $arAttachment['FILE_NAME'], 'type' => $arAttachment['CONTENT_TYPE'], 'content' => $arAttachment['FILE_DATA'], 'MODULE_ID' => 'crm'); } //<-- Precessing of attachments // Remove extra new lines (fix for #31807) $body = preg_replace("/(\r\n|\n|\r)+/", PHP_EOL, $body); $encodedBody = htmlspecialcharsbx($body); // Creating of new event --> $arEventBindings = array(); foreach ($arBindingData as &$arBinding) { $arEventBindings[] = array('ENTITY_TYPE' => $arBinding['TYPE_NAME'], 'ENTITY_ID' => $arBinding['ID']); } unset($arBinding); $eventText = ''; $eventText .= '<b>' . GetMessage('CRM_EMAIL_SUBJECT') . '</b>: ' . $subject . PHP_EOL; $eventText .= '<b>' . GetMessage('CRM_EMAIL_FROM') . '</b>: ' . $addresserInfo['EMAIL'] . PHP_EOL; $eventText .= '<b>' . GetMessage('CRM_EMAIL_TO') . '</b>: ' . implode($addresseeEmails, '; ') . PHP_EOL; if (!empty($arBannedAttachments)) { $eventText .= '<b>' . GetMessage('CRM_EMAIL_BANNENED_ATTACHMENTS', array('%MAX_SIZE%' => $attachmentMaxSizeMb)) . '</b>: '; foreach ($arBannedAttachments as &$attachmentInfo) { $eventText .= GetMessage('CRM_EMAIL_BANNENED_ATTACHMENT_INFO', array('%NAME%' => $attachmentInfo['name'], '%SIZE%' => round($attachmentInfo['size'] / 1048576, 1))); } unset($attachmentInfo); $eventText .= PHP_EOL; } $eventText .= $encodedBody; $CCrmEvent = new CCrmEvent(); $CCrmEvent->Add(array('USER_ID' => $userID, 'ENTITY' => array_values($arEventBindings), 'ENTITY_TYPE' => CCrmOwnerType::ResolveName($ownerTypeID), 'ENTITY_ID' => $ownerID, 'EVENT_NAME' => GetMessage('CRM_EMAIL_GET_EMAIL'), 'EVENT_TYPE' => 2, 'EVENT_TEXT_1' => $eventText, 'FILES' => $arFilesData), false); // <-- Creating of new event // Creating new activity --> $siteID = ''; $dbSites = CSite::GetList($by = 'sort', $order = 'desc', array('DEFAULT' => 'Y', 'ACTIVE' => 'Y')); $defaultSite = is_object($dbSites) ? $dbSites->Fetch() : null; if (is_array($defaultSite)) { $siteID = $defaultSite['LID']; } if ($siteID === '') { $siteID = 's1'; } $storageTypeID = CCrmActivity::GetDefaultStorageTypeID(); $arElementIDs = array(); foreach ($arFilesData as $fileData) { $fileID = CFile::SaveFile($fileData, 'crm'); if ($fileID > 0) { $elementID = StorageManager::saveEmailAttachment(CFile::GetFileArray($fileID), $storageTypeID, $siteID); if ($elementID > 0) { $arElementIDs[] = (int) $elementID; } } } $descr = preg_replace("/(\r\n|\n|\r)+/", '<br/>', $encodedBody); $now = ConvertTimeStamp(time() + CTimeZone::GetOffset(), 'FULL', $siteID); $direction = CCrmActivityDirection::Incoming; $completed = 'N'; // Incomming emails must be marked as 'Not Completed'. if ($addresserID > 0 && ActivitySettings::getValue(ActivitySettings::MARK_FORWARDED_EMAIL_AS_OUTGOING)) { $direction = CCrmActivityDirection::Outgoing; $completed = 'Y'; } $arActivityFields = array('OWNER_ID' => $ownerID, 'OWNER_TYPE_ID' => $ownerTypeID, 'TYPE_ID' => CCrmActivityType::Email, 'ASSOCIATED_ENTITY_ID' => 0, 'PARENT_ID' => $parentID, 'SUBJECT' => $subject, 'START_TIME' => $now, 'END_TIME' => $now, 'COMPLETED' => $completed, 'AUTHOR_ID' => $userID, 'RESPONSIBLE_ID' => $userID, 'PRIORITY' => CCrmActivityPriority::Medium, 'DESCRIPTION' => $descr, 'DESCRIPTION_TYPE' => CCrmContentType::Html, 'DIRECTION' => $direction, 'LOCATION' => '', 'NOTIFY_TYPE' => CCrmActivityNotifyType::None, 'STORAGE_TYPE_ID' => $storageTypeID, 'STORAGE_ELEMENT_IDS' => $arElementIDs); $arActivityFields['BINDINGS'] = array(); foreach ($arBindingData as &$arBinding) { $entityTypeID = $arBinding['TYPE_ID']; $entityID = $arBinding['ID']; if ($entityTypeID <= 0 || $entityID <= 0) { continue; } $arActivityFields['BINDINGS'][] = array('OWNER_TYPE_ID' => $entityTypeID, 'OWNER_ID' => $entityID); } unset($arBinding); $activityID = CCrmActivity::Add($arActivityFields, false, false, array('REGISTER_SONET_EVENT' => true)); if ($activityID > 0 && !empty($arCommData)) { CCrmActivity::SaveCommunications($activityID, $arCommData, $arActivityFields, false, false); $arActivityFields['COMMUNICATIONS'] = $arCommData; } //Notity responsible user if ($userID > 0 && $direction === CCrmActivityDirection::Incoming) { CCrmActivity::Notify($arActivityFields, CCrmNotifierSchemeType::IncomingEmail); } // <-- Creating new activity return true; }
} $arResult['UID'] = $arParams['UID'] = $uid; $currentUserID = $arResult['USER_ID'] = CCrmSecurityHelper::GetCurrentUserID(); $userPerms = CCrmPerms::GetCurrentUserPermissions(); $typeID = CCrmActivityType::Undefined; $ownerID = 0; $ownerTypeID = CCrmOwnerType::Undefined; $entityID = $arParams['ENTITY_ID'] = isset($arParams['ENTITY_ID']) ? intval($arParams['ENTITY_ID']) : 0; if ($entityID <= 0 && isset($_REQUEST['activity_id'])) { $entityID = $arParams['ENTITY_ID'] = intval($_REQUEST['activity_id']); } $arResult['ENTITY_ID'] = $entityID; $arFields = array(); if ($entityID > 0) { $arResult['MODE'] = 'UPDATE'; $arFields = CCrmActivity::GetByID($entityID, false); if (!is_array($arFields)) { ShowError(GetMessage('CRM_ACTIVITY_EDIT_NOT_FOUND')); return; } $typeID = isset($arFields['TYPE_ID']) ? intval($arFields['TYPE_ID']) : 0; $ownerID = isset($arFields['OWNER_ID']) ? intval($arFields['OWNER_ID']) : 0; $ownerTypeID = isset($arFields['OWNER_TYPE_ID']) ? intval($arFields['OWNER_TYPE_ID']) : CCrmOwnerType::Undefined; } else { $arResult['MODE'] = 'CREATE'; $typeID = $arParams['TYPE_ID'] = isset($arParams['TYPE_ID']) ? intval($arParams['TYPE_ID']) : CCrmActivityType::Undefined; if ($typeID <= 0 && isset($_REQUEST['type_id'])) { $typeID = $arParams['TYPE_ID'] = intval($_REQUEST['type_id']); } $ownerID = $arParams['OWNER_ID'] = isset($arParams['OWNER_ID']) ? intval($arParams['OWNER_ID']) : 0; if ($ownerID <= 0 && isset($_REQUEST['owner_id'])) {
protected function innerDelete($ID, &$errors) { $currentFields = CCrmActivity::GetByID($ID); if (!is_array($currentFields)) { $errors[] = 'Activity is not found.'; return false; } if (!CCrmActivity::CheckDeletePermission($currentFields['OWNER_TYPE_ID'], $currentFields['OWNER_ID'])) { $errors[] = 'Access denied.'; return false; } $result = CCrmActivity::Delete($ID, false, true, array()); if ($result === false) { $errors[] = CCrmActivity::GetLastErrorMessage(); } return $result; }