示例#1
0
 public static function WriteEventFileToResponse($eventID, $fileID, &$errors, $options = array())
 {
     $eventID = intval($eventID);
     $fileID = intval($fileID);
     if ($eventID <= 0 || $fileID <= 0) {
         $errors[] = 'File not found';
         return false;
     }
     //Get event file IDs and check permissions
     $dbResult = CCrmEvent::GetListEx(array(), array('=ID' => $eventID), false, false, array('ID', 'FILES'), array());
     $event = $dbResult ? $dbResult->Fetch() : null;
     if (!$event) {
         $errors[] = 'File not found';
         return false;
     }
     if (is_array($event['FILES'])) {
         $eventFiles = $event['FILES'];
     } elseif (is_string($event['FILES']) && $event['FILES'] !== '') {
         $eventFiles = unserialize($event['FILES']);
     } else {
         $eventFiles = array();
     }
     if (empty($eventFiles) || !is_array($eventFiles) || !in_array($fileID, $eventFiles, true)) {
         $errors[] = 'File not found';
         return false;
     }
     return self::InnerWriteFileToResponse($fileID, $errors, $options);
 }
 public function Execute()
 {
     if (!CModule::IncludeModule('crm')) {
         return CBPActivityExecutionStatus::Closed;
     }
     $rootActivity = $this->GetRootActivity();
     $documentId = $rootActivity->GetDocumentId();
     $arDocumentInfo = explode('_', $documentId['2']);
     $documentService = $this->workflow->GetService('DocumentService');
     $arEntity[$arDocumentInfo[1]] = array('ENTITY_TYPE' => $arDocumentInfo[0], 'ENTITY_ID' => (int) $arDocumentInfo[1]);
     $arFields = array('ENTITY' => $arEntity, 'EVENT_ID' => $this->EventType, 'EVENT_TEXT_1' => $this->EventText, 'USER_ID' => 0);
     $CCrmEvent = new CCrmEvent();
     if (!$CCrmEvent->Add($arFields, false)) {
         global $APPLICATION;
         $e = $APPLICATION->GetException();
         throw new Exception($e->GetString());
     }
     return CBPActivityExecutionStatus::Closed;
 }
示例#3
0
 public function Delete($ID, $options = array())
 {
     global $DB, $APPLICATION;
     $ID = intval($ID);
     $iUserId = CCrmSecurityHelper::GetCurrentUserID();
     $sWherePerm = '';
     if ($this->bCheckPermission) {
         $arEntityAttr = $this->cPerms->GetEntityAttr('QUOTE', $ID);
         $sEntityPerm = $this->cPerms->GetPermType('QUOTE', 'DELETE', $arEntityAttr[$ID]);
         if ($sEntityPerm == BX_CRM_PERM_NONE) {
             return false;
         } else {
             if ($sEntityPerm == BX_CRM_PERM_SELF) {
                 $sWherePerm = " AND ASSIGNED_BY_ID = {$iUserId}";
             } else {
                 if ($sEntityPerm == BX_CRM_PERM_OPEN) {
                     $sWherePerm = " AND (OPENED = 'Y' OR ASSIGNED_BY_ID = {$iUserId})";
                 }
             }
         }
     }
     $APPLICATION->ResetException();
     foreach (GetModuleEvents('crm', 'OnBeforeCrmQuoteDelete', true) as $arEvent) {
         if (ExecuteModuleEventEx($arEvent, array($ID)) === false) {
             $err = GetMessage("MAIN_BEFORE_DEL_ERR") . ' ' . $arEvent['TO_NAME'];
             if ($ex = $APPLICATION->GetException()) {
                 $err .= ': ' . $ex->GetString();
             }
             $APPLICATION->throwException($err);
             return false;
         }
     }
     if (!(isset($options['SKIP_FILES']) && $options['SKIP_FILES'])) {
         if (!self::DeleteStorageElements($ID)) {
             return false;
         }
         if (!$DB->Query('DELETE FROM ' . CCrmQuote::ELEMENT_TABLE_NAME . ' WHERE QUOTE_ID = ' . $ID, false, 'File: ' . __FILE__ . '<br/>Line: ' . __LINE__)) {
             $APPLICATION->throwException(GetMessage('CRM_QUOTE_ERR_DELETE_STORAGE_ELEMENTS_QUERY'));
             return false;
         }
     }
     $dbRes = $DB->Query("DELETE FROM b_crm_quote WHERE ID = {$ID}{$sWherePerm}", false, 'FILE: ' . __FILE__ . '<br /> LINE: ' . __LINE__);
     if (is_object($dbRes) && $dbRes->AffectedRowsCount() > 0) {
         $DB->Query("DELETE FROM b_crm_entity_perms WHERE ENTITY='QUOTE' AND ENTITY_ID = {$ID}", false, 'FILE: ' . __FILE__ . '<br /> LINE: ' . __LINE__);
         $GLOBALS['USER_FIELD_MANAGER']->Delete(self::$sUFEntityID, $ID);
         $CCrmFieldMulti = new CCrmFieldMulti();
         $CCrmFieldMulti->DeleteByElement('QUOTE', $ID);
         $CCrmEvent = new CCrmEvent();
         $CCrmEvent->DeleteByElement('QUOTE', $ID);
         CCrmSearch::DeleteSearch('QUOTE', $ID);
         // Deletion of quote details
         CCrmProductRow::DeleteByOwner(self::OWNER_TYPE, $ID);
         CCrmProductRow::DeleteSettings(self::OWNER_TYPE, $ID);
         /*CCrmActivity::DeleteByOwner(CCrmOwnerType::Quote, $ID);*/
         if (defined("BX_COMP_MANAGED_CACHE")) {
             $GLOBALS["CACHE_MANAGER"]->ClearByTag("crm_entity_name_" . CCrmOwnerType::Quote . "_" . $ID);
         }
         $afterEvents = GetModuleEvents('crm', 'OnAfterCrmQuoteDelete');
         while ($arEvent = $afterEvents->Fetch()) {
             ExecuteModuleEventEx($arEvent, array($ID));
         }
     }
     return true;
 }
示例#4
0
 public function Delete($ID, $arOptions = array())
 {
     global $DB, $APPLICATION;
     $ID = intval($ID);
     $iUserId = CCrmSecurityHelper::GetCurrentUserID();
     if (!is_array($arOptions)) {
         $arOptions = array();
     }
     $sWherePerm = '';
     if ($this->bCheckPermission) {
         $arEntityAttr = $this->cPerms->GetEntityAttr('DEAL', $ID);
         $sEntityPerm = $this->cPerms->GetPermType('DEAL', 'DELETE', $arEntityAttr[$ID]);
         if ($sEntityPerm == BX_CRM_PERM_NONE) {
             return false;
         } else {
             if ($sEntityPerm == BX_CRM_PERM_SELF) {
                 $sWherePerm = " AND ASSIGNED_BY_ID = {$iUserId}";
             } else {
                 if ($sEntityPerm == BX_CRM_PERM_OPEN) {
                     $sWherePerm = " AND (OPENED = 'Y' OR ASSIGNED_BY_ID = {$iUserId})";
                 }
             }
         }
     }
     $APPLICATION->ResetException();
     $events = GetModuleEvents('crm', 'OnBeforeCrmDealDelete');
     while ($arEvent = $events->Fetch()) {
         if (ExecuteModuleEventEx($arEvent, array($ID)) === false) {
             $err = GetMessage("MAIN_BEFORE_DEL_ERR") . ' ' . $arEvent['TO_NAME'];
             if ($ex = $APPLICATION->GetException()) {
                 $err .= ': ' . $ex->GetString();
             }
             $APPLICATION->throwException($err);
             return false;
         }
     }
     //By defaut we need to clean up related bizproc entities
     $processBizproc = isset($arOptions['PROCESS_BIZPROC']) ? (bool) $arOptions['PROCESS_BIZPROC'] : true;
     if ($processBizproc) {
         $bizproc = new CCrmBizProc('DEAL');
         $bizproc->ProcessDeletion($ID);
     }
     $dbRes = $DB->Query("DELETE FROM b_crm_deal WHERE ID = {$ID}{$sWherePerm}", false, 'FILE: ' . __FILE__ . '<br /> LINE: ' . __LINE__);
     if (is_object($dbRes) && $dbRes->AffectedRowsCount() > 0) {
         CCrmSearch::DeleteSearch('DEAL', $ID);
         $DB->Query("DELETE FROM b_crm_entity_perms WHERE ENTITY='DEAL' AND ENTITY_ID = {$ID}", false, 'FILE: ' . __FILE__ . '<br /> LINE: ' . __LINE__);
         $GLOBALS['USER_FIELD_MANAGER']->Delete(self::$sUFEntityID, $ID);
         $CCrmFieldMulti = new CCrmFieldMulti();
         $CCrmFieldMulti->DeleteByElement('DEAL', $ID);
         $CCrmEvent = new CCrmEvent();
         $CCrmEvent->DeleteByElement('DEAL', $ID);
         Bitrix\Crm\History\DealStageHistoryEntry::unregister($ID);
         Bitrix\Crm\Statistics\DealSumStatisticEntry::unregister($ID);
         Bitrix\Crm\Statistics\DealInvoiceStatisticEntry::unregister($ID);
         Bitrix\Crm\Statistics\DealActivityStatisticEntry::unregister($ID);
         // Deletion of deal details
         CCrmProductRow::DeleteByOwner('D', $ID);
         CCrmProductRow::DeleteSettings('D', $ID);
         CCrmActivity::DeleteByOwner(CCrmOwnerType::Deal, $ID);
         CCrmSonetSubscription::UnRegisterSubscriptionByEntity(CCrmOwnerType::Deal, $ID);
         CCrmLiveFeed::DeleteLogEvents(array('ENTITY_TYPE_ID' => CCrmOwnerType::Deal, 'ENTITY_ID' => $ID));
         self::PullChange('DELETE', array('ID' => $ID));
         if (defined("BX_COMP_MANAGED_CACHE")) {
             $GLOBALS["CACHE_MANAGER"]->ClearByTag("crm_entity_name_" . CCrmOwnerType::Deal . "_" . $ID);
         }
         $afterEvents = GetModuleEvents('crm', 'OnAfterCrmDealDelete');
         while ($arEvent = $afterEvents->Fetch()) {
             ExecuteModuleEventEx($arEvent, array($ID));
         }
     }
     return true;
 }
示例#5
0
 if ($formID === '') {
     $formID = 'CRM_' . trim($_POST['ENTITY_TYPE']) . '_' . trim($_POST['FORM_TYPE']) . '_V12';
 }
 $arResult['EVENT_PAGE'] = CHTTP::urlAddParams($eventPage, array($formID . '_active_tab' => !empty($_POST['TAB_ID']) ? $_POST['TAB_ID'] : 'tab_event'));
 if (check_bitrix_sessid()) {
     $entityTypeID = isset($_POST['ENTITY_TYPE']) ? trim($_POST['ENTITY_TYPE']) : '';
     $entityID = isset($_POST['ENTITY_ID']) ? intval($_POST['ENTITY_ID']) : 0;
     $eventID = isset($_POST['EVENT_ID']) ? trim($_POST['EVENT_ID']) : '';
     $eventDesc = isset($_POST['EVENT_DESC']) ? trim($_POST['EVENT_DESC']) : '';
     $eventDate = isset($_POST['EVENT_DATE']) ? trim($_POST['EVENT_DATE']) : '';
     $postFiles = isset($_FILES['ATTACH']) ? $_FILES['ATTACH'] : array();
     $attachedFiles = array();
     if (!empty($postFiles)) {
         CAllFile::ConvertFilesToPost($postFiles, $attachedFiles);
     }
     $CCrmEvent = new CCrmEvent();
     $eventFiles = array();
     foreach ($attachedFiles as &$arFile) {
         if (isset($arFile['tmp_name']) && is_uploaded_file($arFile['tmp_name'])) {
             $eventFiles[] = $arFile;
         }
     }
     unset($arFile);
     if ($eventDate !== '') {
         if (!CheckDateTime($eventDate, FORMAT_DATETIME)) {
             $eventDate = '';
         } else {
             // Check for max database datetime
             $eventTimestamp = MakeTimeStamp($eventDate, FORMAT_DATETIME);
             if (!is_int($eventTimestamp)) {
                 $eventDate = '';
示例#6
0
 protected function rebind($seedID, $targID)
 {
     \CCrmDeal::Rebind(\CCrmOwnerType::Contact, $seedID, $targID);
     \CCrmQuote::Rebind(\CCrmOwnerType::Contact, $seedID, $targID);
     \CCrmActivity::Rebind(\CCrmOwnerType::Contact, $seedID, $targID);
     \CCrmLiveFeed::Rebind(\CCrmOwnerType::Contact, $seedID, $targID);
     \CCrmSonetRelation::RebindRelations(\CCrmOwnerType::Contact, $seedID, $targID);
     \CCrmEvent::Rebind(\CCrmOwnerType::Contact, $seedID, $targID);
 }
 public static function prepareRecoveryData($entityTypeID, $entityID, array $options = null)
 {
     if (!is_int($entityTypeID)) {
         $entityTypeID = intval($entityTypeID);
     }
     if (!\CCrmOwnerType::IsDefined($entityTypeID)) {
         throw new Main\ArgumentException('Is not defined', 'entityTypeID');
     }
     if (!is_int($entityID)) {
         $entityID = intval($entityID);
     }
     if ($entityID <= 0) {
         throw new Main\ArgumentException('Must be greater than zero', 'entityID');
     }
     if (!is_array($options)) {
         $options = array();
     }
     $item = new EntityRecoveryData();
     $item->setEntityTypeID($entityTypeID);
     $item->setEntityID($entityID);
     $userID = isset($options['USER_ID']) ? intval($options['USER_ID']) : 0;
     if ($userID > 0) {
         $item->setUserID($userID);
     }
     if ($entityTypeID === \CCrmOwnerType::Lead) {
         $result = \CCrmLead::GetListEx(array(), array('=ID' => $entityID, 'CHECK_PERMISSIONS' => 'N'), false, false, array('*', 'UF_*'));
         $fields = is_object($result) ? $result->Fetch() : null;
         if (!is_array($fields)) {
             throw new Main\ObjectNotFoundException("The lead with ID '{$entityTypeID}' is not found");
         }
         $item->setDataItem('FIELDS', $fields);
         if (isset($fields['TITLE'])) {
             $item->setTitle($fields['TITLE']);
         }
         if (isset($fields['ASSIGNED_BY_ID'])) {
             $item->setResponsibleID(intval($fields['ASSIGNED_BY_ID']));
         }
     } elseif ($entityTypeID === \CCrmOwnerType::Contact) {
         $result = \CCrmContact::GetListEx(array(), array('=ID' => $entityID, 'CHECK_PERMISSIONS' => 'N'), false, false, array('*', 'UF_*'));
         $fields = is_object($result) ? $result->Fetch() : null;
         if (!is_array($fields)) {
             throw new Main\ObjectNotFoundException("The contact with ID '{$entityTypeID}' is not found");
         }
         $item->setDataItem('FIELDS', $fields);
         $item->setTitle(\CCrmContact::GetFullName($fields, true));
         if (isset($fields['ASSIGNED_BY_ID'])) {
             $item->setResponsibleID(intval($fields['ASSIGNED_BY_ID']));
         }
     } elseif ($entityTypeID === \CCrmOwnerType::Company) {
         $result = \CCrmCompany::GetListEx(array(), array('=ID' => $entityID, 'CHECK_PERMISSIONS' => 'N'), false, false, array('*', 'UF_*'));
         $fields = is_object($result) ? $result->Fetch() : null;
         if (!is_array($fields)) {
             throw new Main\ObjectNotFoundException("The company with ID '{$entityTypeID}' is not found");
         }
         $item->setDataItem('FIELDS', $fields);
         if (isset($fields['TITLE'])) {
             $item->setTitle($fields['TITLE']);
         }
         if (isset($fields['ASSIGNED_BY_ID'])) {
             $item->setResponsibleID(intval($fields['ASSIGNED_BY_ID']));
         }
     } else {
         throw new Main\NotSupportedException("The entity type '" . \CCrmOwnerType::ResolveName($entityTypeID) . "' is not supported in current context");
     }
     $entityTypeName = \CCrmOwnerType::ResolveName($entityTypeID);
     //MULTI FIELDS -->
     $multiFieldData = array();
     $multiFieldTypes = array(\CCrmFieldMulti::PHONE, \CCrmFieldMulti::EMAIL, \CCrmFieldMulti::WEB, \CCrmFieldMulti::IM);
     foreach ($multiFieldTypes as $multiFieldType) {
         $result = \CCrmFieldMulti::GetListEx(array('ID' => 'ASC'), array('TYPE_ID' => $multiFieldType, 'ENTITY_ID' => $entityTypeName, 'ELEMENT_ID' => $entityID, 'CHECK_PERMISSIONS' => 'N'), false, array('nTopCount' => 50), array('VALUE_TYPE', 'VALUE'));
         if (!is_object($result)) {
             continue;
         }
         while ($multiFields = $result->Fetch()) {
             $valueType = isset($multiFields['VALUE_TYPE']) ? $multiFields['VALUE_TYPE'] : '';
             $value = isset($multiFields['VALUE']) ? $multiFields['VALUE'] : '';
             if ($value === '') {
                 continue;
             }
             if (!isset($multiFieldData[$multiFieldType])) {
                 $multiFieldData[$multiFieldType] = array();
             }
             $multiFieldData[$multiFieldType][] = array('VALUE_TYPE' => $valueType, 'VALUE' => $value);
         }
     }
     if (!empty($multiFieldData)) {
         $item->setDataItem('MULTI_FIELDS', $multiFieldData);
     }
     //<-- MULTI FIELDS
     //ACTIVITIES -->
     $activityIDs = \CCrmActivity::GetBoundIDs($entityTypeID, $entityID);
     if (!empty($activityIDs)) {
         $item->setDataItem('ACTIVITY_IDS', $activityIDs);
     }
     //<-- ACTIVITIES
     //EVENTS -->
     $eventIDs = array();
     $result = \CCrmEvent::GetListEx(array('EVENT_REL_ID' => 'ASC'), array('ENTITY_TYPE' => $entityTypeName, 'ENTITY_ID' => $entityID, 'EVENT_TYPE' => 0, 'CHECK_PERMISSIONS' => 'N'), false, false, array('EVENT_REL_ID'));
     if (is_object($result)) {
         while ($eventFields = $result->Fetch()) {
             $eventIDs[] = intval($eventFields['EVENT_REL_ID']);
         }
     }
     if (!empty($eventIDs)) {
         $item->setDataItem('EVENT_IDS', $eventIDs);
     }
     //<-- EVENTS
     return $item;
 }
示例#8
0
 public static function TrySendEmail($ID, &$arFields, &$arErrors)
 {
     global $APPLICATION;
     if (!CModule::IncludeModule('subscribe')) {
         $arErrors[] = array('CODE' => self::ERR_CANT_LOAD_SUBSCRIBE);
         return false;
     }
     $ID = intval($ID);
     if ($ID <= 0 && isset($arFields['ID'])) {
         $ID = intval($arFields['ID']);
     }
     if ($ID <= 0 || !is_array($arFields)) {
         $arErrors[] = array('CODE' => self::ERR_INVALID_DATA);
         return false;
     }
     $typeID = isset($arFields['TYPE_ID']) ? intval($arFields['TYPE_ID']) : CCrmActivityType::Undefined;
     if ($typeID !== CCrmActivityType::Email) {
         $arErrors[] = array('CODE' => self::ERR_INVALID_DATA);
         return false;
     }
     $urn = CCrmActivity::PrepareUrn($arFields);
     if (!($urn !== '' && CCrmActivity::Update($ID, array('URN' => $urn), false, false))) {
         $arErrors[] = array('CODE' => self::ERR_CANT_UPDATE_ACTIVITY);
         return false;
     }
     $settings = isset($arFields['SETTINGS']) && is_array($arFields['SETTINGS']) ? $arFields['SETTINGS'] : array();
     // Creating Email -->
     $crmEmail = CCrmMailHelper::ExtractEmail(COption::GetOptionString('crm', 'mail', ''));
     $from = isset($settings['MESSAGE_FROM']) ? trim(strval($settings['MESSAGE_FROM'])) : '';
     if ($from === '') {
         if ($crmEmail !== '') {
             $from = $crmEmail;
         } else {
             $arErrors[] = array('CODE' => self::ERR_CANT_FIND_EMAIL_FROM);
         }
     } elseif (!check_email($from)) {
         $arErrors[] = array('CODE' => self::ERR_INVALID_EMAIL, 'DATA' => array('EMAIL' => $from));
     }
     //Save user email in settings -->
     if ($from !== CUserOptions::GetOption('crm', 'activity_email_addresser', '')) {
         CUserOptions::SetOption('crm', 'activity_email_addresser', $from);
     }
     //<-- Save user email in settings
     $to = array();
     $commData = isset($arFields['COMMUNICATIONS']) ? $arFields['COMMUNICATIONS'] : array();
     foreach ($commData as &$commDatum) {
         $commType = isset($commDatum['TYPE']) ? strtoupper(strval($commDatum['TYPE'])) : '';
         $commValue = isset($commDatum['VALUE']) ? strval($commDatum['VALUE']) : '';
         if ($commType !== 'EMAIL' || $commValue === '') {
             continue;
         }
         if (!check_email($commValue)) {
             $arErrors[] = array('CODE' => self::ERR_INVALID_EMAIL, 'DATA' => array('EMAIL' => $commValue));
             continue;
         }
         $to[] = strtolower(trim($commValue));
     }
     unset($commDatum);
     if (count($to) == 0) {
         $arErrors[] = array('CODE' => self::ERR_CANT_FIND_EMAIL_TO);
     }
     if (!empty($arErrors)) {
         return false;
     }
     // Try to resolve posting charset -->
     $postingCharset = '';
     $siteCharset = defined('LANG_CHARSET') ? LANG_CHARSET : (defined('SITE_CHARSET') ? SITE_CHARSET : 'windows-1251');
     $arSupportedCharset = explode(',', COption::GetOptionString('subscribe', 'posting_charset'));
     if (count($arSupportedCharset) === 0) {
         $postingCharset = $siteCharset;
     } else {
         foreach ($arSupportedCharset as $curCharset) {
             if (strcasecmp($curCharset, $siteCharset) === 0) {
                 $postingCharset = $curCharset;
                 break;
             }
         }
         if ($postingCharset === '') {
             $postingCharset = $arSupportedCharset[0];
         }
     }
     //<-- Try to resolve posting charset
     $subject = isset($arFields['SUBJECT']) ? $arFields['SUBJECT'] : '';
     $description = isset($arFields['DESCRIPTION']) ? $arFields['DESCRIPTION'] : '';
     $descriptionType = isset($arFields['DESCRIPTION_TYPE']) ? intval($arFields['DESCRIPTION_TYPE']) : CCrmContentType::PlainText;
     $descriptionHtml = '';
     if ($descriptionType === CCrmContentType::Html) {
         $descriptionHtml = $description;
     } elseif ($descriptionType === CCrmContentType::BBCode) {
         $parser = new CTextParser();
         $descriptionHtml = $parser->convertText($description);
     } elseif ($descriptionType === CCrmContentType::PlainText) {
         $descriptionHtml = htmlspecialcharsbx($description);
     }
     $postingData = array('STATUS' => 'D', 'FROM_FIELD' => $from, 'TO_FIELD' => $from, 'BCC_FIELD' => implode(',', $to), 'SUBJECT' => $subject, 'BODY_TYPE' => 'html', 'BODY' => $descriptionHtml, 'DIRECT_SEND' => 'Y', 'SUBSCR_FORMAT' => 'html', 'CHARSET' => $postingCharset);
     CCrmActivity::InjectUrnInMessage($postingData, $urn, CCrmEMailCodeAllocation::GetCurrent());
     $posting = new CPosting();
     $postingID = $posting->Add($postingData);
     if ($postingID === false) {
         $arErrors[] = array('CODE' => self::ERR_CANT_ADD_POSTING, 'MESSAGE' => $posting->LAST_ERROR);
         return false;
     }
     $arUpdateFields = array('COMPLETED' => 'Y', 'ASSOCIATED_ENTITY_ID' => $postingID, 'SETTINGS' => $settings);
     $fromEmail = strtolower(trim(CCrmMailHelper::ExtractEmail($from)));
     if ($crmEmail !== '' && $fromEmail !== $crmEmail) {
         $arUpdateFields['SETTINGS']['MESSAGE_HEADERS'] = array('Reply-To' => "<{$fromEmail}>, <{$crmEmail}>");
     }
     $arUpdateFields['SETTINGS']['IS_MESSAGE_SENT'] = true;
     if (!CCrmActivity::Update($ID, $arUpdateFields, false, false)) {
         $arErrors[] = array('CODE' => self::ERR_CANT_UPDATE_ACTIVITY);
         return false;
     }
     // <-- Creating Email
     // Attaching files -->
     $storageTypeID = isset($arFields['STORAGE_TYPE_ID']) ? intval($arFields['STORAGE_TYPE_ID']) : StorageType::Undefined;
     $storageElementsID = isset($arFields['STORAGE_ELEMENT_IDS']) && is_array($arFields['STORAGE_ELEMENT_IDS']) ? $arFields['STORAGE_ELEMENT_IDS'] : array();
     $arRawFiles = StorageManager::makeFileArray($storageElementsID, $storageTypeID);
     foreach ($arRawFiles as &$arRawFile) {
         if (!$posting->SaveFile($postingID, $arRawFile)) {
             $arErrors[] = array('CODE' => self::ERR_CANT_SAVE_POSTING_FILE, 'MESSAGE' => $posting->LAST_ERROR);
             return false;
         }
     }
     unset($arRawFile);
     // <-- Attaching files
     // Sending Email -->
     if ($posting->ChangeStatus($postingID, 'P')) {
         $rsAgents = CAgent::GetList(array('ID' => 'DESC'), array('MODULE_ID' => 'subscribe', 'NAME' => 'CPosting::AutoSend(' . $postingID . ',%'));
         if (!$rsAgents->Fetch()) {
             CAgent::AddAgent('CPosting::AutoSend(' . $postingID . ',true);', 'subscribe', 'N', 0);
         }
     }
     // Try add event to entity
     $CCrmEvent = new CCrmEvent();
     $ownerID = isset($arFields['OWNER_ID']) ? intval($arFields['OWNER_ID']) : 0;
     $ownerTypeID = isset($arFields['OWNER_TYPE_ID']) ? intval($arFields['OWNER_TYPE_ID']) : 0;
     if ($ownerID > 0 && $ownerTypeID > 0) {
         $eventText = '';
         $eventText .= GetMessage('CRM_ACTIVITY_EMAIL_SUBJECT') . ': ' . $subject . "\n\r";
         $eventText .= GetMessage('CRM_ACTIVITY_EMAIL_FROM') . ': ' . $from . "\n\r";
         $eventText .= GetMessage('CRM_ACTIVITY_EMAIL_TO') . ': ' . implode(',', $to) . "\n\r\n\r";
         $eventText .= $description;
         // Register event only for owner
         $CCrmEvent->Add(array('ENTITY' => array($ownerID => array('ENTITY_TYPE' => CCrmOwnerType::ResolveName($ownerTypeID), 'ENTITY_ID' => $ownerID)), 'EVENT_ID' => 'MESSAGE', 'EVENT_TEXT_1' => $eventText, 'FILES' => $arRawFiles));
     }
     // <-- Sending Email
     return true;
 }
示例#9
0
 public function Delete($ID, $arOptions = array())
 {
     global $DB, $APPLICATION;
     $ID = intval($ID);
     $iUserId = CCrmSecurityHelper::GetCurrentUserID();
     $sWherePerm = '';
     if ($this->bCheckPermission) {
         $arEntityAttr = $this->cPerms->GetEntityAttr('COMPANY', $ID);
         $sEntityPerm = $this->cPerms->GetPermType('COMPANY', 'DELETE', $arEntityAttr[$ID]);
         if ($sEntityPerm == BX_CRM_PERM_NONE) {
             return false;
         } else {
             if ($sEntityPerm == BX_CRM_PERM_SELF) {
                 $sWherePerm = " AND ASSIGNED_BY_ID = {$iUserId}";
             } else {
                 if ($sEntityPerm == BX_CRM_PERM_OPEN) {
                     $sWherePerm = " AND (OPENED = 'Y' OR ASSIGNED_BY_ID = {$iUserId})";
                 }
             }
         }
     }
     $APPLICATION->ResetException();
     $events = GetModuleEvents('crm', 'OnBeforeCrmCompanyDelete');
     while ($arEvent = $events->Fetch()) {
         if (ExecuteModuleEventEx($arEvent, array($ID)) === false) {
             $err = GetMessage("MAIN_BEFORE_DEL_ERR") . ' ' . $arEvent['TO_NAME'];
             if ($ex = $APPLICATION->GetException()) {
                 $err .= ': ' . $ex->GetString();
             }
             $APPLICATION->throwException($err);
             return false;
         }
     }
     $obRes = $DB->Query("DELETE FROM b_crm_company WHERE ID = {$ID}{$sWherePerm}", false, 'FILE: ' . __FILE__ . '<br /> LINE: ' . __LINE__);
     if (is_object($obRes) && $obRes->AffectedRowsCount() > 0) {
         $DB->Query("DELETE FROM b_crm_entity_perms WHERE ENTITY='COMPANY' AND ENTITY_ID = {$ID}", false, 'FILE: ' . __FILE__ . '<br /> LINE: ' . __LINE__);
         $GLOBALS['USER_FIELD_MANAGER']->Delete(self::$sUFEntityID, $ID);
         $CCrmFieldMulti = new CCrmFieldMulti();
         $CCrmFieldMulti->DeleteByElement('COMPANY', $ID);
         $CCrmEvent = new CCrmEvent();
         $CCrmEvent->DeleteByElement('COMPANY', $ID);
         \Bitrix\Crm\Integrity\DuplicateEntityRanking::unregisterEntityStatistics(CCrmOwnerType::Company, $ID);
         \Bitrix\Crm\Integrity\DuplicateOrganizationCriterion::unregister(CCrmOwnerType::Company, $ID);
         \Bitrix\Crm\Integrity\DuplicateCommunicationCriterion::unregister(CCrmOwnerType::Company, $ID);
         \Bitrix\Crm\Integrity\DuplicateIndexMismatch::unregisterEntity(CCrmOwnerType::Company, $ID);
         $enableDupIndexInvalidation = is_array($arOptions) && isset($arOptions['ENABLE_DUP_INDEX_INVALIDATION']) ? (bool) $arOptions['ENABLE_DUP_INDEX_INVALIDATION'] : true;
         if ($enableDupIndexInvalidation) {
             \Bitrix\Crm\Integrity\DuplicateIndexBuilder::markAsJunk(CCrmOwnerType::Company, $ID);
         }
         CCrmActivity::DeleteByOwner(CCrmOwnerType::Company, $ID);
         CCrmSearch::DeleteSearch('COMPANY', $ID);
         CCrmSonetSubscription::UnRegisterSubscriptionByEntity(CCrmOwnerType::Company, $ID);
         CCrmLiveFeed::DeleteLogEvents(array('ENTITY_TYPE_ID' => CCrmOwnerType::Company, 'ENTITY_ID' => $ID));
         if (defined("BX_COMP_MANAGED_CACHE")) {
             $GLOBALS["CACHE_MANAGER"]->ClearByTag("crm_entity_name_" . CCrmOwnerType::Company . "_" . $ID);
         }
     }
     return true;
 }
示例#10
0
     if ($isNew) {
         $arErrors[] = GetMessage('CRM_ACTIVITY_EMAIL_CREATION_CANCELED');
         CCrmActivity::Delete($ID);
     }
     echo CUtil::PhpToJSObject(array('ERROR' => $arErrors));
     die;
 }
 // Sending Email -->
 if ($posting->ChangeStatus($postingID, 'P')) {
     $rsAgents = CAgent::GetList(array('ID' => 'DESC'), array('MODULE_ID' => 'subscribe', 'NAME' => 'CPosting::AutoSend(' . $postingID . ',%'));
     if (!$rsAgents->Fetch()) {
         CAgent::AddAgent('CPosting::AutoSend(' . $postingID . ',true);', 'subscribe', 'N', 0);
     }
 }
 // Try add event to entity
 $CCrmEvent = new CCrmEvent();
 $eventText = '';
 $eventText .= GetMessage('CRM_TITLE_EMAIL_SUBJECT') . ': ' . $subject . "\n\r";
 $eventText .= GetMessage('CRM_TITLE_EMAIL_FROM') . ': ' . $from . "\n\r";
 $eventText .= GetMessage('CRM_TITLE_EMAIL_TO') . ': ' . implode(',', $to) . "\n\r\n\r";
 $eventText .= $message;
 // Register event only for owner
 $CCrmEvent->Add(array('ENTITY' => array($ownerID => array('ENTITY_TYPE' => $ownerTypeName, 'ENTITY_ID' => $ownerID)), 'EVENT_ID' => 'MESSAGE', 'EVENT_TEXT_1' => $eventText, 'FILES' => $arRawFiles));
 // <-- Sending Email
 $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'], 'entityUrl' => CCrmOwnerType::GetShowUrl($arComm['ENTITY_TYPE_ID'], $arComm['ENTITY_ID']));
 }
 unset($arComm);
示例#11
0
 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;
 }
示例#12
0
 public static function RegisterExportEvent($entityTypeID, $entityID, $userID = 0)
 {
     if ($userID <= 0) {
         $userID = CCrmSecurityHelper::GetCurrentUserID();
         if ($userID <= 0) {
             return false;
         }
     }
     $eventType = CCrmEvent::TYPE_EXPORT;
     $timestamp = time() + CTimeZone::GetOffset();
     $entityTypeName = CCrmOwnerType::ResolveName($entityTypeID);
     $entity = new CCrmEvent();
     $entity->Add(array('USER_ID' => $userID, 'ENTITY_ID' => $entityID, 'ENTITY_TYPE' => $entityTypeName, 'EVENT_TYPE' => $eventType, 'EVENT_NAME' => CCrmEvent::GetEventTypeName($eventType), 'DATE_CREATE' => ConvertTimeStamp($timestamp, 'FULL', SITE_ID)), false);
     return true;
 }
示例#13
0
            $rsAgents = CAgent::GetList(array('ID' => 'DESC'), array('MODULE_ID' => 'subscribe', 'NAME' => 'CPosting::AutoSend(' . $SID . ',%'));
            if (!$rsAgents->Fetch()) {
                CAgent::AddAgent('CPosting::AutoSend(' . $SID . ',true);', 'subscribe', 'N', 0);
            }
        }
        $arFilter = array();
        $arEntity = array();
        foreach ($arFmUserList as $_sEmail) {
            $arFilter[] = array('TYPE_ID' => 'EMAIL', 'VALUE' => $_sEmail);
        }
        $obEntityR = CCrmFieldMulti::GetList(array(), array('ENTITY_ID' => 'LEAD|CONTACT|COMPANY', 'FILTER' => $arFilter), array('ID', 'ENTITY_ID'));
        while ($arEntityR = $obEntityR->Fetch()) {
            // key to disable dublicate
            $arEntity[$arEntityR['ELEMENT_ID']] = array('ENTITY_TYPE' => $arEntityR['ENTITY_ID'], 'ENTITY_ID' => (int) $arEntityR['ELEMENT_ID']);
        }
        $CCrmEvent = new CCrmEvent();
        $sBodyEvent = '';
        $sBodyEvent .= GetMessage('CRM_SUBSCRIBE_SUBJECT') . ': ' . $arFields['SUBJECT'] . "\n\r";
        $sBodyEvent .= GetMessage('CRM_SUBSCRIBE_FROM') . ': ' . $arFields['FROM_FIELD'] . "\n\r";
        $sBodyEvent .= GetMessage('CRM_SUBSCRIBE_TO') . ': ' . $arFields['BCC_FIELD'] . "\n\r\n\r";
        $sBodyEvent .= $_POST['COMMENTS'];
        if (!empty($arEntity)) {
            $CCrmEvent->Add(array('ENTITY' => $arEntity, 'EVENT_ID' => 'MESSAGE', 'EVENT_TEXT_1' => $sBodyEvent, 'FILES' => !empty($_FILES['ATTACH']) ? $_FILES['ATTACH'] : array()));
        }
        // Try add event to entity of context
        if ($arResult['FORM_ENTITY_TYPE'] !== $arResult['ENTITY_TYPE'] && $arResult['FORM_ENTITY_ID'] !== $arResult['ENTITY_ID']) {
            $CCrmEvent->Add(array('ENTITY' => array($arResult['FORM_ENTITY_ID'] => array('ENTITY_TYPE' => $arResult['FORM_ENTITY_TYPE'], 'ENTITY_ID' => $arResult['FORM_ENTITY_ID'])), 'EVENT_ID' => 'MESSAGE', 'EVENT_TEXT_1' => $sBodyEvent, 'FILES' => !empty($_FILES['ATTACH']) ? $_FILES['ATTACH'] : array()));
        }
    }
    $arResult['EVENT_PAGE'] = CHTTP::urlAddParams($_POST['EVENT_PAGE'], array('CRM_' . trim($arResult['FORM_ENTITY_TYPE']) . '_' . trim($arParams['FORM_TYPE']) . '_active_tab' => !empty($_REQUEST['TAB_ID']) ? $_REQUEST['TAB_ID'] : 'tab_event'));
}
示例#14
0
 private static function RegisterEvents($ownerType, $ownerID, $arEvents, $checkPerms)
 {
     global $USER;
     $userID = isset($USER) && $USER instanceof CUser && 'CUser' === get_class($USER) ? $USER->GetId() : 0;
     $CCrmEvent = new CCrmEvent();
     foreach ($arEvents as $arEvent) {
         $arEvent['EVENT_TYPE'] = 1;
         $arEvent['ENTITY_TYPE'] = CCrmOwnerTypeAbbr::ResolveName($ownerType);
         $arEvent['ENTITY_ID'] = $ownerID;
         $arEvent['ENTITY_FIELD'] = 'PRODUCT_ROWS';
         if ($userID > 0) {
             $arEvent['USER_ID'] = $userID;
         }
         $CCrmEvent->Add($arEvent, $checkPerms);
     }
     return true;
 }
示例#15
0
        }
    }
    if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_REQUEST['action_' . $arResult['GRID_ID']])) {
        if ($_REQUEST['action_' . $arResult['GRID_ID']] == 'delete' && isset($_REQUEST['ID']) && $_REQUEST['ID'] > 0) {
            $CCrmEvent = new CCrmEvent();
            $CCrmEvent->Delete((int) $_REQUEST['ID']);
            unset($_REQUEST['ID']);
            // otherwise the filter will work
        }
        if (!$arResult['IS_AJAX_CALL']) {
            LocalRedirect('?' . $arParams['FORM_ID'] . '_active_tab=tab_event');
        }
    } else {
        if ($_SERVER['REQUEST_METHOD'] == 'GET' && isset($_GET['action_' . $arResult['GRID_ID']])) {
            if ($_GET['action_' . $arResult['GRID_ID']] == 'delete') {
                $CCrmEvent = new CCrmEvent();
                $CCrmEvent->Delete((int) $_GET['ID']);
                unset($_GET['ID'], $_REQUEST['ID']);
                // otherwise the filter will work
            }
            if (!$arResult['IS_AJAX_CALL']) {
                LocalRedirect($bInternal ? '?' . $arParams['FORM_ID'] . '_active_tab=' . $arResult['TAB_ID'] : '');
            }
        }
    }
}
$arResult['FILTER'] = array();
$arResult['FILTER2LOGIC'] = array('EVENT_DESC');
$arResult['FILTER_PRESETS'] = array();
if (!$bInternal) {
    $arResult['FILTER2LOGIC'] = array('EVENT_DESC');
示例#16
0
 public static function CreateLogMessage(&$fields, $options = array())
 {
     if (!CModule::IncludeModule('socialnetwork')) {
         return false;
     }
     global $APPLICATION, $DB;
     if (!is_array($options)) {
         $options = array();
     }
     $entityTypeID = isset($fields['ENTITY_TYPE_ID']) ? intval($fields['ENTITY_TYPE_ID']) : CCrmOwnerType::Undefined;
     if (!CCrmOwnerType::IsDefined($entityTypeID)) {
         $fields['ERROR'] = GetMessage('CRM_LF_MSG_ENTITY_TYPE_NOT_FOUND');
         return false;
     }
     $entityType = CCrmOwnerType::ResolveName($entityTypeID);
     $entityID = isset($fields['ENTITY_ID']) ? intval($fields['ENTITY_ID']) : 0;
     if ($entityID < 0) {
         $fields['ERROR'] = GetMessage('CRM_LF_MSG_ENTITY_TYPE_NOT_FOUND');
         return false;
     }
     $message = isset($fields['MESSAGE']) && is_string($fields['MESSAGE']) ? $fields['MESSAGE'] : '';
     if ($message === '') {
         $fields['ERROR'] = GetMessage('CRM_LF_MSG_EMPTY');
         return false;
     }
     $title = isset($fields['TITLE']) && is_string($fields['TITLE']) ? $fields['TITLE'] : '';
     if ($title === '') {
         $title = self::UntitledMessageStub;
     }
     $userID = isset($fields['USER_ID']) ? intval($fields['USER_ID']) : 0;
     if ($userID <= 0) {
         $userID = CCrmSecurityHelper::GetCurrentUserID();
     }
     $bbCodeParser = new CTextParser();
     $bbCodeParser->allow["HTML"] = "Y";
     $eventText = $bbCodeParser->convert4mail($message);
     $CCrmEvent = new CCrmEvent();
     $eventID = $CCrmEvent->Add(array('ENTITY_TYPE' => $entityType, 'ENTITY_ID' => $entityID, 'EVENT_ID' => 'INFO', 'EVENT_TYPE' => 0, 'EVENT_TEXT_1' => $eventText, 'DATE_CREATE' => ConvertTimeStamp(time() + CTimeZone::GetOffset(), 'FULL', SITE_ID), 'FILES' => array()));
     if (is_string($eventID)) {
         //MS SQL RETURNS STRING INSTEAD INT
         $eventID = intval($eventID);
     }
     if (!(is_int($eventID) && $eventID > 0)) {
         $fields['ERROR'] = 'Could not create event';
         return false;
     }
     $liveFeedEntityType = CCrmLiveFeedEntity::GetByEntityTypeID($entityTypeID);
     $eventID = CCrmLiveFeedEvent::GetEventID($liveFeedEntityType, CCrmLiveFeedEvent::Message);
     $eventFields = array('EVENT_ID' => $eventID, '=LOG_DATE' => $DB->CurrentTimeFunction(), 'TITLE' => $title, 'MESSAGE' => $message, 'TEXT_MESSAGE' => '', 'MODULE_ID' => 'crm_shared', 'CALLBACK_FUNC' => false, 'ENABLE_COMMENTS' => 'Y', 'PARAMS' => '', 'USER_ID' => $userID, 'ENTITY_TYPE' => $liveFeedEntityType, 'ENTITY_ID' => $entityID, 'SOURCE_ID' => $eventID, 'URL' => CCrmUrlUtil::AddUrlParams(CCrmOwnerType::GetShowUrl($entityTypeID, $entityID), array()));
     if (isset($fields['WEB_DAV_FILES']) && is_array($fields['WEB_DAV_FILES'])) {
         $eventFields = array_merge($eventFields, $fields['WEB_DAV_FILES']);
     }
     $sendMessage = isset($options['SEND_MESSAGE']) && is_bool($options['SEND_MESSAGE']) ? $options['SEND_MESSAGE'] : false;
     $logEventID = CSocNetLog::Add($eventFields, $sendMessage);
     if (is_int($logEventID) && $logEventID > 0) {
         $arSocnetRights = $fields["RIGHTS"];
         if (!empty($arSocnetRights)) {
             $socnetPermsAdd = array();
             foreach ($arSocnetRights as $perm_tmp) {
                 if (preg_match('/^SG(\\d+)$/', $perm_tmp, $matches)) {
                     if (!in_array("SG" . $matches[1] . "_" . SONET_ROLES_USER, $arSocnetRights)) {
                         $socnetPermsAdd[] = "SG" . $matches[1] . "_" . SONET_ROLES_USER;
                     }
                     if (!in_array("SG" . $matches[1] . "_" . SONET_ROLES_MODERATOR, $arSocnetRights)) {
                         $socnetPermsAdd[] = "SG" . $matches[1] . "_" . SONET_ROLES_MODERATOR;
                     }
                     if (!in_array("SG" . $matches[1] . "_" . SONET_ROLES_OWNER, $arSocnetRights)) {
                         $socnetPermsAdd[] = "SG" . $matches[1] . "_" . SONET_ROLES_OWNER;
                     }
                 }
             }
             if (count($socnetPermsAdd) > 0) {
                 $arSocnetRights = array_merge($arSocnetRights, $socnetPermsAdd);
             }
             CSocNetLogRights::DeleteByLogID($logEventID);
             CSocNetLogRights::Add($logEventID, $arSocnetRights);
             if (array_key_exists("UF_SONET_LOG_DOC", $eventFields) && is_array($eventFields["UF_SONET_LOG_DOC"]) && count($eventFields["UF_SONET_LOG_DOC"]) > 0) {
                 if (!in_array("U" . $userID, $arSocnetRights)) {
                     $arSocnetRights[] = "U" . $userID;
                 }
                 CSocNetLogTools::SetUFRights($eventFields["UF_SONET_LOG_DOC"], $arSocnetRights);
             }
         }
         $arUpdateFields = array("RATING_TYPE_ID" => "LOG_ENTRY", "RATING_ENTITY_ID" => $logEventID);
         CSocNetLog::Update($logEventID, $arUpdateFields);
         self::RegisterOwnershipRelations($logEventID, $eventID, $fields);
         $eventFields["LOG_ID"] = $logEventID;
         CCrmLiveFeed::CounterIncrement($eventFields);
         return $logEventID;
     }
     $ex = $APPLICATION->GetException();
     $fields['ERROR'] = $ex->GetString();
     return false;
 }
示例#17
0
if ($arResult['GRID_FILTER_APPLIED']) {
    $filterID = $arResult['GRID_FILTER_ID'] = isset($filter['GRID_FILTER_ID']) ? $filter['GRID_FILTER_ID'] : '';
    $arResult['GRID_FILTER_NAME'] = isset($arResult['FILTER_PRESETS'][$filterID]) ? $arResult['FILTER_PRESETS'][$filterID]['name'] : '';
} else {
    $arResult['GRID_FILTER_ID'] = '';
    $arResult['GRID_FILTER_NAME'] = '';
}
if ($entityTypeID > 0 && $entityID > 0) {
    $arResult['RUBRIC']['ENABLED'] = true;
    $filter['ENTITY_TYPE'] = CCrmOwnerType::ResolveName($entityTypeID);
    $filter['ENTITY_ID'] = $entityID;
    $arResult['RUBRIC']['TITLE'] = CCrmOwnerType::GetCaption($entityTypeID, $entityID);
    $arResult['RUBRIC']['FILTER_PRESETS'] = array('clear_filter', 'filter_custom');
}
$arResult['ITEMS'] = array();
$dbRes = CCrmEvent::GetListEx($sort, $filter, false, $arNavParams, $select, array());
$dbRes->NavStart($navParams['nPageSize'], false);
$arResult['PAGE_NAVNUM'] = intval($dbRes->NavNum);
// pager index
$arResult['PAGE_NUMBER'] = intval($dbRes->NavPageNomer);
// current page index
$arResult['PAGE_NAVCOUNT'] = intval($dbRes->NavPageCount);
// page count
$arResult['PAGER_PARAM'] = "PAGEN_{$arResult['PAGE_NAVNUM']}";
$arResult['PAGE_NEXT_NUMBER'] = $arResult['PAGE_NUMBER'] + 1;
while ($item = $dbRes->Fetch()) {
    CCrmMobileHelper::PrepareEventItem($item, $arParams);
    $arResult['ITEMS'][] =& $item;
    unset($item);
}
//NEXT_PAGE_URL, SEARCH_PAGE_URL, SERVICE_URL -->
示例#18
0
 public function Delete($ID, $arOptions = array())
 {
     global $DB, $APPLICATION;
     $ID = intval($ID);
     $iUserId = CCrmSecurityHelper::GetCurrentUserID();
     $this->LAST_ERROR = '';
     $APPLICATION->ResetException();
     if (!is_array($arOptions)) {
         $arOptions = array();
     }
     if (isset($arOptions['CHECK_DEPENDENCIES']) && (bool) $arOptions['CHECK_DEPENDENCIES']) {
         $dbRes = self::GetListEx(array(), array('=ID' => $ID), false, false, array('TITLE', 'STATUS_ID', 'COMPANY_ID', 'CONTACT_ID'));
         $arFields = $dbRes ? $dbRes->Fetch() : null;
         if (is_array($arFields) && isset($arFields['STATUS_ID']) && $arFields['STATUS_ID'] === 'CONVERTED' && (CCrmCompany::Exists(isset($arFields['COMPANY_ID']) ? intval($arFields['COMPANY_ID']) : 0) || CCrmContact::Exists(isset($arFields['CONTACT_ID']) ? intval($arFields['CONTACT_ID']) : 0))) {
             $title = isset($arFields['TITLE']) && $arFields['TITLE'] !== '' ? $arFields['TITLE'] : $ID;
             $err = GetMessage('CRM_LEAD_DELETION_DEPENDENCIES_FOUND', array('#TITLE#' => $title));
             $this->LAST_ERROR = $err;
             $APPLICATION->throwException($err);
             return false;
         }
     }
     $sWherePerm = '';
     if ($this->bCheckPermission) {
         $arEntityAttr = $this->cPerms->GetEntityAttr('LEAD', $ID);
         $sEntityPerm = $this->cPerms->GetPermType('LEAD', 'DELETE', $arEntityAttr[$ID]);
         if ($sEntityPerm == BX_CRM_PERM_NONE) {
             return false;
         } else {
             if ($sEntityPerm == BX_CRM_PERM_SELF) {
                 $sWherePerm = " AND ASSIGNED_BY_ID = {$iUserId}";
             } else {
                 if ($sEntityPerm == BX_CRM_PERM_OPEN) {
                     $sWherePerm = " AND (OPENED = 'Y' OR ASSIGNED_BY_ID = {$iUserId})";
                 }
             }
         }
     }
     $events = GetModuleEvents('crm', 'OnBeforeCrmLeadDelete');
     while ($arEvent = $events->Fetch()) {
         if (ExecuteModuleEventEx($arEvent, array($ID)) === false) {
             $err = GetMessage("MAIN_BEFORE_DEL_ERR") . ' ' . $arEvent['TO_NAME'];
             if ($ex = $APPLICATION->GetException()) {
                 $err .= ': ' . $ex->GetString();
             }
             $APPLICATION->throwException($err);
             $this->LAST_ERROR = $err;
             return false;
         }
     }
     //By defaut we need to clean up related bizproc entities
     $processBizproc = isset($arOptions['PROCESS_BIZPROC']) ? (bool) $arOptions['PROCESS_BIZPROC'] : true;
     if ($processBizproc) {
         $bizproc = new CCrmBizProc('LEAD');
         $bizproc->ProcessDeletion($ID);
     }
     $tableName = CCrmLead::TABLE_NAME;
     $sSql = "DELETE FROM {$tableName} WHERE ID = {$ID}{$sWherePerm}";
     $obRes = $DB->Query($sSql, false, 'FILE: ' . __FILE__ . '<br /> LINE: ' . __LINE__);
     if (is_object($obRes) && $obRes->AffectedRowsCount() > 0) {
         CCrmSearch::DeleteSearch('LEAD', $ID);
         $DB->Query("DELETE FROM b_crm_entity_perms WHERE ENTITY='LEAD' AND ENTITY_ID = {$ID}", false, 'FILE: ' . __FILE__ . '<br /> LINE: ' . __LINE__);
         $GLOBALS['USER_FIELD_MANAGER']->Delete(self::$sUFEntityID, $ID);
         $CCrmFieldMulti = new CCrmFieldMulti();
         $CCrmFieldMulti->DeleteByElement('LEAD', $ID);
         $CCrmEvent = new CCrmEvent();
         $CCrmEvent->DeleteByElement('LEAD', $ID);
         \Bitrix\Crm\EntityAddress::unregister(CCrmOwnerType::Lead, $ID, \Bitrix\Crm\EntityAddress::Primary);
         \Bitrix\Crm\Integrity\DuplicateEntityRanking::unregisterEntityStatistics(CCrmOwnerType::Lead, $ID);
         \Bitrix\Crm\Integrity\DuplicatePersonCriterion::unregister(CCrmOwnerType::Lead, $ID);
         \Bitrix\Crm\Integrity\DuplicateOrganizationCriterion::unregister(CCrmOwnerType::Lead, $ID);
         \Bitrix\Crm\Integrity\DuplicateCommunicationCriterion::unregister(CCrmOwnerType::Lead, $ID);
         \Bitrix\Crm\Integrity\DuplicateIndexMismatch::unregisterEntity(CCrmOwnerType::Lead, $ID);
         $enableDupIndexInvalidation = is_array($arOptions) && isset($arOptions['ENABLE_DUP_INDEX_INVALIDATION']) ? (bool) $arOptions['ENABLE_DUP_INDEX_INVALIDATION'] : true;
         if ($enableDupIndexInvalidation) {
             \Bitrix\Crm\Integrity\DuplicateIndexBuilder::markAsJunk(CCrmOwnerType::Lead, $ID);
         }
         // Deletion of lead details
         CCrmProductRow::DeleteByOwner('L', $ID);
         CCrmProductRow::DeleteSettings('L', $ID);
         CCrmActivity::DeleteByOwner(CCrmOwnerType::Lead, $ID);
         CCrmSonetSubscription::UnRegisterSubscriptionByEntity(CCrmOwnerType::Lead, $ID);
         CCrmLiveFeed::DeleteLogEvents(array('ENTITY_TYPE_ID' => CCrmOwnerType::Lead, 'ENTITY_ID' => $ID));
         if (defined("BX_COMP_MANAGED_CACHE")) {
             $GLOBALS["CACHE_MANAGER"]->ClearByTag("crm_entity_name_" . CCrmOwnerType::Lead . "_" . $ID);
         }
         $afterEvents = GetModuleEvents('crm', 'OnAfterCrmLeadDelete');
         while ($arEvent = $afterEvents->Fetch()) {
             ExecuteModuleEventEx($arEvent, array($ID));
         }
     }
     return true;
 }
示例#19
0
     $dealID = $CCrmDeal->Add($arParams);
     $arDeals[$ID]['ID'] = $dealID;
     if (is_array($arProductRows)) {
         foreach ($arProductRows as &$arProductRow) {
             $originID = $arProductRow['ORIGIN_ID'];
             $arProduct = CCrmProduct::GetByOriginID($originID, $catalogID);
             if (!is_array($arProduct)) {
                 continue;
             }
             CCrmDeal::SaveProductRows($dealID, array(array('PRODUCT_ID' => intval($arProduct['ID']), 'PRICE' => doubleval($arProduct['PRICE']), 'QUANTITY' => 1)));
         }
     }
 }
 // Add event
 require_once "event.demo.php";
 $CCrmEvent = new CCrmEvent();
 foreach ($arEvents as $ID => $arParams) {
     $arEvents[$ID]['ID'] = $CCrmEvent->Add($arParams);
 }
 // Add relation
 $arParams = array('COMPANY_ID' => $arCompany['39']['ID'], 'CONTACT_ID' => $arContacts['51']['ID']);
 $CCrmLead->Update($arLeads['57']['ID'], $arParams);
 // Add activity
 require_once "activity.demo.php";
 $CCrmActivity = new CCrmActivity();
 foreach ($arActivities as $ID => $arParams) {
     $activityId = $CCrmActivity->Add($arParams["FIELDS"], false, false);
     CCrmActivity::SaveCommunications($activityId, array($arParams["COMMUNICATIONS"]), $arParams["FIELDS"], false, false);
 }
 //Add invoice
 CCrmInvoice::installDisableSaleEvents();
示例#20
0
 if ($bConvertCompany) {
     $iCompanyId = $CCrmCompany->Add($arFields['COMPANY'], true, array('REGISTER_SONET_EVENT' => true));
     if ($iCompanyId > 0) {
         $CCrmCompanyBizProc = new CCrmBizProc('COMPANY');
         $arCompanyBizProcParams = $CCrmCompanyBizProc->CheckFields(false, false, $arFields['COMPANY']['ASSIGNED_BY_ID'], null);
         if ($arCompanyBizProcParams !== false) {
             $CCrmCompanyBizProc->StartWorkflow($iCompanyId, $arCompanyBizProcParams);
         }
     }
 }
 $arFields['CONTACT']['COMPANY_ID'] = $iCompanyId;
 $arFields['DEAL']['COMPANY_ID'] = $iCompanyId;
 if ($bConvertContact) {
     $iContactId = $CCrmContact->Add($arFields['CONTACT'], true, array('REGISTER_SONET_EVENT' => true));
     if ($iContactId > 0) {
         $CCrmEvent = new CCrmEvent();
         $CCrmEvent->Share(array('ENTITY_TYPE' => 'LEAD', 'ENTITY_ID' => $arParams['ELEMENT_ID']), array(array('ENTITY_TYPE' => 'CONTACT', 'ENTITY_ID' => $iContactId)), 'MESSAGE');
         $CCrmContactBizProc = new CCrmBizProc('CONTACT');
         $arContactBizProcParams = $CCrmContactBizProc->CheckFields(false, false, $arFields['CONTACT']['ASSIGNED_BY_ID'], null);
         if ($arContactBizProcParams !== false) {
             $CCrmContactBizProc->StartWorkflow($iContactId, $arContactBizProcParams);
         }
     }
 }
 $arFields['DEAL']['CONTACT_ID'] = $iContactId;
 if (!$CrmPerms->HavePerm('DEAL', BX_CRM_PERM_NONE, 'ADD')) {
     if ($bConvertDeal) {
         $arDealFields = $arFields['DEAL'];
         $iDealId = $CCrmDeal->Add($arDealFields, true, array('REGISTER_SONET_EVENT' => true));
         if ($iDealId > 0) {
             if (!empty($arDealFields['PRODUCT_ROWS'])) {