private static function loadBulk($entityTypeID, array &$entityIDs, array &$itemMap, array $options = null)
 {
     /** @var DuplicateEntityRanking[] $itemMap */
     if ($entityTypeID !== \CCrmOwnerType::Contact && $entityTypeID !== \CCrmOwnerType::Company && $entityTypeID !== \CCrmOwnerType::Lead) {
         return;
     }
     if (!is_array($options)) {
         $options = array();
     }
     $checkPermissions = isset($options['CHECK_PERMISSIONS']) ? (bool) $options['CHECK_PERMISSIONS'] : false;
     $userID = isset($options['USER_ID']) ? (int) $options['USER_ID'] : 0;
     $permissions = $checkPermissions ? \CCrmPerms::GetUserPermissions($userID) : null;
     $limit = isset($options['LIMIT']) ? (int) $options['LIMIT'] : 3000;
     if ($limit <= 0) {
         $limit = 3000;
     }
     $length = count($entityIDs);
     if ($length === 0) {
         return;
     }
     while ($length > 0) {
         if ($length <= $limit) {
             $ids = $entityIDs;
             unset($entityIDs);
             $entityIDs = array();
         } else {
             $ids = array_splice($entityIDs, 0, $limit);
         }
         $length = count($entityIDs);
         if (empty($ids)) {
             continue;
         }
         if ($entityTypeID === \CCrmOwnerType::Lead) {
             $dbResult = Entity\DuplicateEntityStatisticsTable::getList(array('select' => array('ENTITY_ID', 'RANKING_DATA'), 'filter' => array('ENTITY_TYPE_ID' => \CCrmOwnerType::Lead, 'ENTITY_ID' => $ids)));
             while ($fields = $dbResult->fetch()) {
                 $entityID = intval($fields['ENTITY_ID']);
                 $key = "{$entityTypeID}_{$entityID}";
                 if (!isset($itemMap[$key])) {
                     continue;
                 }
                 if (isset($fields['RANKING_DATA']) && $fields['RANKING_DATA'] !== '') {
                     $data = unserialize($fields['RANKING_DATA']);
                     /** @var DuplicateEntityRanking $ranking */
                     $ranking = $itemMap[$key];
                     $ranking->lastChanged = isset($data['LAST_CHANGED']) ? $data['LAST_CHANGED'] : 0;
                     $ranking->completeness = isset($data['COMPLETENESS']) ? $data['COMPLETENESS'] : 0;
                     if ($checkPermissions) {
                         $ranking->editable = \CCrmLead::CheckUpdatePermission($entityID, $permissions);
                         $ranking->deleteable = \CCrmLead::CheckDeletePermission($entityID, $permissions);
                     }
                 }
             }
         } else {
             $query = new Main\Entity\Query(Entity\DuplicateEntityStatisticsTable::getEntity());
             $query->addSelect('ENTITY_ID');
             $query->addSelect('RANKING_DATA');
             $query->addFilter('ENTITY_ID', $ids);
             $query->addFilter('ENTITY_TYPE_ID', $entityTypeID);
             if ($entityTypeID === \CCrmOwnerType::Contact) {
                 $subQuery = new Main\Entity\Query(DealTable::getEntity());
                 $subQuery->addSelect('CONTACT_ID');
                 $subQuery->addFilter('CONTACT_ID', $ids);
                 $subQuery->addSelect('QTY');
                 $subQuery->registerRuntimeField('', new Main\Entity\ExpressionField('QTY', 'COUNT(*)'));
                 $referenceField = new Main\Entity\ReferenceField('D', Main\Entity\Base::getInstanceByQuery($subQuery), array('=this.ENTITY_ID' => 'ref.CONTACT_ID'), array('join_type' => 'LEFT'));
             } else {
                 $subQuery = new Main\Entity\Query(DealTable::getEntity());
                 $subQuery->addSelect('COMPANY_ID');
                 $subQuery->addFilter('COMPANY_ID', $ids);
                 $subQuery->addSelect('QTY');
                 $subQuery->registerRuntimeField('', new Main\Entity\ExpressionField('QTY', 'COUNT(*)'));
                 $referenceField = new Main\Entity\ReferenceField('D', Main\Entity\Base::getInstanceByQuery($subQuery), array('=this.ENTITY_ID' => 'ref.COMPANY_ID'), array('join_type' => 'LEFT'));
             }
             $query->registerRuntimeField('', $referenceField);
             $query->addSelect('D.QTY', 'QTY');
             $dbResult = $query->exec();
             while ($fields = $dbResult->fetch()) {
                 $entityID = intval($fields['ENTITY_ID']);
                 $key = "{$entityTypeID}_{$entityID}";
                 if (!isset($itemMap[$key])) {
                     continue;
                 }
                 $itemMap[$key]->referenceCount = isset($fields['QTY']) ? intval($fields['QTY']) : 0;
                 if (isset($fields['RANKING_DATA']) && $fields['RANKING_DATA'] !== '') {
                     $data = unserialize($fields['RANKING_DATA']);
                     /** @var DuplicateEntityRanking $ranking */
                     $ranking = $itemMap[$key];
                     $ranking->lastChanged = isset($data['LAST_CHANGED']) ? $data['LAST_CHANGED'] : 0;
                     $ranking->completeness = isset($data['COMPLETENESS']) ? $data['COMPLETENESS'] : 0;
                     if ($checkPermissions) {
                         if ($entityTypeID === \CCrmOwnerType::Contact) {
                             $ranking->editable = \CCrmContact::CheckUpdatePermission($entityID, $permissions);
                             $ranking->deleteable = \CCrmContact::CheckDeletePermission($entityID, $permissions);
                         } else {
                             $ranking->editable = \CCrmCompany::CheckUpdatePermission($entityID, $permissions);
                             $ranking->deleteable = \CCrmCompany::CheckDeletePermission($entityID, $permissions);
                         }
                     }
                 }
             }
         }
     }
 }
Beispiel #2
0
 /**
  * @return string|boolean
  */
 protected function preparePermissionSql()
 {
     if ($this->permissionSql !== null) {
         return $this->permissionSql;
     }
     if (\CCrmPerms::IsAdmin($this->userID)) {
         $this->permissionSql = '';
     } else {
         $this->permissionSql = \CCrmPerms::BuildSql(\CCrmOwnerType::DealName, '', 'READ', array('RAW_QUERY' => true, 'PERMS' => \CCrmPerms::GetUserPermissions($this->userID)));
     }
     return $this->permissionSql;
 }
 /**
  * @return Duplicate
  */
 public function createDuplicate($entityTypeID, $rootEntityID, $userID, $enablePermissionCheck, $enableRanking, $limit = 0)
 {
     if ($entityTypeID !== \CCrmOwnerType::Lead && $entityTypeID !== \CCrmOwnerType::Contact && $entityTypeID !== \CCrmOwnerType::Company) {
         throw new Main\NotSupportedException("Entity type: '" . \CCrmOwnerType::ResolveName($entityTypeID) . "' is not supported in current context");
     }
     /** @var Duplicate $dup **/
     $dup = new Duplicate($this, array());
     $query = static::createQuery();
     $query->addSelect('ENTITY_ID');
     $query->addFilter('=ENTITY_TYPE_ID', $entityTypeID);
     static::setQueryFilter($query, $this->getMatches());
     if ($enablePermissionCheck) {
         $permissions = isset($params['PERMISSIONS']) ? $params['PERMISSIONS'] : null;
         if ($permissions === null) {
             $permissions = \CCrmPerms::GetUserPermissions($userID);
         }
         $permissionSql = \CCrmPerms::BuildSql(\CCrmOwnerType::ResolveName($entityTypeID), '', 'READ', array('RAW_QUERY' => true, 'PERMS' => $permissions));
         if ($permissionSql === false) {
             //Access denied;
             return null;
         }
         if ($permissionSql !== '') {
             $query->addFilter('@ENTITY_ID', new Main\DB\SqlExpression($permissionSql));
         }
     }
     if ($limit > 0) {
         $query->setLimit($limit);
     }
     if ($rootEntityID > 0) {
         $dup->setRootEntityID($rootEntityID);
         $query->addFilter('!ENTITY_ID', $rootEntityID);
         $query->addFilter('!@ENTITY_ID', DuplicateIndexMismatch::prepareQueryField($this, $entityTypeID, $rootEntityID, $userID));
     }
     $dbResult = $query->exec();
     $rankings = array();
     while ($fields = $dbResult->fetch()) {
         $entityID = isset($fields['ENTITY_ID']) ? intval($fields['ENTITY_ID']) : 0;
         if ($entityID <= 0) {
             continue;
         }
         $entity = new DuplicateEntity($entityTypeID, $entityID);
         if ($enableRanking) {
             $rankings[] = $entity->getRanking();
         }
         $dup->addEntity($entity);
     }
     $this->onAfterDuplicateCreated($dup, $entityTypeID, $userID, $enablePermissionCheck, $enableRanking, $rankings);
     if ($enableRanking) {
         DuplicateEntityRanking::initializeBulk($rankings, array('CHECK_PERMISSIONS' => $enablePermissionCheck, 'USER_ID' => $userID));
     }
     return $dup;
 }
 protected function preparePermissionSql()
 {
     if ($this->permissionSql !== null) {
         return $this->permissionSql;
     }
     $userID = $this->getUserID();
     if (\CCrmPerms::IsAdmin($userID)) {
         $this->permissionSql = '';
     } else {
         $this->permissionSql = \CCrmPerms::BuildSql(\CCrmOwnerType::ResolveName($this->getEntityTypeID()), '', 'READ', array('RAW_QUERY' => true, 'PERMS' => \CCrmPerms::GetUserPermissions($userID)));
     }
     return $this->permissionSql;
 }
Beispiel #5
0
 public function Add(array &$arFields, $bUpdateSearch = true, $arOptions = array())
 {
     global $DB;
     $this->LAST_ERROR = '';
     if (!is_array($arOptions)) {
         $arOptions = array();
     }
     if (isset($arOptions['CURRENT_USER'])) {
         $iUserId = intval($arOptions['CURRENT_USER']);
     } else {
         $iUserId = CCrmPerms::GetCurrentUserID();
     }
     if (isset($arFields['DATE_CREATE'])) {
         unset($arFields['DATE_CREATE']);
     }
     $arFields['~DATE_CREATE'] = $DB->CurrentTimeFunction();
     $arFields['~DATE_MODIFY'] = $DB->CurrentTimeFunction();
     if (!isset($arFields['CREATED_BY_ID']) || (int) $arFields['CREATED_BY_ID'] <= 0) {
         $arFields['CREATED_BY_ID'] = $iUserId;
     }
     if (!isset($arFields['MODIFY_BY_ID']) || (int) $arFields['MODIFY_BY_ID'] <= 0) {
         $arFields['MODIFY_BY_ID'] = $iUserId;
     }
     if (!isset($arFields['ASSIGNED_BY_ID']) || (int) $arFields['ASSIGNED_BY_ID'] <= 0) {
         $arFields['ASSIGNED_BY_ID'] = $iUserId;
     }
     if (!isset($arFields['OPPORTUNITY'])) {
         $arFields['OPPORTUNITY'] = 0.0;
     }
     if (!$this->CheckFields($arFields, false, $arOptions)) {
         $arFields['RESULT_MESSAGE'] =& $this->LAST_ERROR;
         return false;
     }
     if (isset($arFields['BIRTHDATE'])) {
         if ($arFields['BIRTHDATE'] !== '') {
             $birthDate = $arFields['BIRTHDATE'];
             $arFields['~BIRTHDATE'] = $DB->CharToDateFunction($birthDate, 'SHORT', false);
             $arFields['BIRTHDAY_SORT'] = \Bitrix\Crm\BirthdayReminder::prepareSorting($birthDate);
         } else {
             $arFields['BIRTHDAY_SORT'] = \Bitrix\Crm\BirthdayReminder::prepareSorting('');
         }
         unset($arFields['BIRTHDATE']);
     } else {
         $arFields['BIRTHDAY_SORT'] = \Bitrix\Crm\BirthdayReminder::prepareSorting('');
     }
     if (!isset($arFields['STATUS_ID']) || $arFields['STATUS_ID'] === '') {
         $arFields['STATUS_ID'] = 'NEW';
     }
     if (isset($arFields['DATE_CLOSED'])) {
         unset($arFields['DATE_CLOSED']);
     }
     self::EnsureStatusesLoaded();
     if (in_array($arFields['STATUS_ID'], self::$LEAD_STATUSES_BY_GROUP['FINISHED'])) {
         $arFields['~DATE_CLOSED'] = $DB->CurrentTimeFunction();
     }
     $arAttr = array();
     $arAttr['STATUS_ID'] = $arFields['STATUS_ID'];
     if (!empty($arFields['OPENED'])) {
         $arAttr['OPENED'] = $arFields['OPENED'];
     }
     $sPermission = 'ADD';
     if (isset($arFields['PERMISSION'])) {
         if ($arFields['PERMISSION'] == 'IMPORT') {
             $sPermission = 'IMPORT';
         }
         unset($arFields['PERMISSION']);
     }
     if ($this->bCheckPermission) {
         $arEntityAttr = self::BuildEntityAttr($iUserId, $arAttr);
         $userPerms = $iUserId == CCrmPerms::GetCurrentUserID() ? $this->cPerms : CCrmPerms::GetUserPermissions($iUserId);
         $sEntityPerm = $userPerms->GetPermType('LEAD', $sPermission, $arEntityAttr);
         if ($sEntityPerm == BX_CRM_PERM_NONE) {
             $this->LAST_ERROR = GetMessage('CRM_PERMISSION_DENIED');
             $arFields['RESULT_MESSAGE'] =& $this->LAST_ERROR;
             return false;
         }
         $assignedByID = intval($arFields['ASSIGNED_BY_ID']);
         if ($sEntityPerm == BX_CRM_PERM_SELF && $assignedByID != $iUserId) {
             $arFields['ASSIGNED_BY_ID'] = $iUserId;
         }
         if ($sEntityPerm == BX_CRM_PERM_OPEN && $iUserId == $assignedByID) {
             $arFields['OPENED'] = 'Y';
         }
     }
     $assignedByID = intval($arFields['ASSIGNED_BY_ID']);
     $arEntityAttr = self::BuildEntityAttr($assignedByID, $arAttr);
     $userPerms = $assignedByID == CCrmPerms::GetCurrentUserID() ? $this->cPerms : CCrmPerms::GetUserPermissions($assignedByID);
     $sEntityPerm = $userPerms->GetPermType('LEAD', $sPermission, $arEntityAttr);
     $this->PrepareEntityAttrs($arEntityAttr, $sEntityPerm);
     // Calculation of Account Data
     $accData = CCrmAccountingHelper::PrepareAccountingData(array('CURRENCY_ID' => isset($arFields['CURRENCY_ID']) ? $arFields['CURRENCY_ID'] : null, 'SUM' => isset($arFields['OPPORTUNITY']) ? $arFields['OPPORTUNITY'] : null, 'EXCH_RATE' => isset($arFields['EXCH_RATE']) ? $arFields['EXCH_RATE'] : null));
     if (is_array($accData)) {
         $arFields['ACCOUNT_CURRENCY_ID'] = $accData['ACCOUNT_CURRENCY_ID'];
         $arFields['OPPORTUNITY_ACCOUNT'] = $accData['ACCOUNT_SUM'];
     }
     if (isset($arFields['NAME']) || isset($arFields['LAST_NAME'])) {
         $arFields['FULL_NAME'] = trim((isset($arFields['NAME']) ? $arFields['NAME'] : '') . ' ' . (isset($arFields['LAST_NAME']) ? $arFields['LAST_NAME'] : ''));
     }
     $beforeEvents = GetModuleEvents('crm', 'OnBeforeCrmLeadAdd');
     while ($arEvent = $beforeEvents->Fetch()) {
         if (ExecuteModuleEventEx($arEvent, array(&$arFields)) === false) {
             if (isset($arFields['RESULT_MESSAGE'])) {
                 $this->LAST_ERROR = $arFields['RESULT_MESSAGE'];
             } else {
                 $this->LAST_ERROR = GetMessage('CRM_LEAD_CREATION_CANCELED', array('#NAME#' => $arEvent['TO_NAME']));
                 $arFields['RESULT_MESSAGE'] =& $this->LAST_ERROR;
             }
             return false;
         }
     }
     $ID = intval($DB->Add('b_crm_lead', $arFields, array(), '', false, 'FILE: ' . __FILE__ . '<br /> LINE: ' . __LINE__));
     $arFields['ID'] = $ID;
     CCrmPerms::UpdateEntityAttr('LEAD', $ID, $arEntityAttr);
     $companyTitle = isset($arFields['COMPANY_TITLE']) ? $arFields['COMPANY_TITLE'] : '';
     if ($companyTitle !== '') {
         \Bitrix\Crm\Integrity\DuplicateOrganizationCriterion::register(CCrmOwnerType::Lead, $ID, $companyTitle);
     }
     $lastName = isset($arFields['LAST_NAME']) ? $arFields['LAST_NAME'] : '';
     if ($lastName !== '') {
         \Bitrix\Crm\Integrity\DuplicatePersonCriterion::register(CCrmOwnerType::Lead, $ID, $lastName, isset($arFields['NAME']) ? $arFields['NAME'] : '', isset($arFields['SECOND_NAME']) ? $arFields['SECOND_NAME'] : '');
     }
     \Bitrix\Crm\EntityAddress::register(CCrmOwnerType::Lead, $ID, \Bitrix\Crm\EntityAddress::Primary, array('ADDRESS_1' => isset($arFields['ADDRESS']) ? $arFields['ADDRESS'] : null, 'ADDRESS_2' => isset($arFields['ADDRESS_2']) ? $arFields['ADDRESS_2'] : null, 'CITY' => isset($arFields['ADDRESS_CITY']) ? $arFields['ADDRESS_CITY'] : null, 'POSTAL_CODE' => isset($arFields['ADDRESS_POSTAL_CODE']) ? $arFields['ADDRESS_POSTAL_CODE'] : null, 'REGION' => isset($arFields['ADDRESS_REGION']) ? $arFields['ADDRESS_REGION'] : null, 'PROVINCE' => isset($arFields['ADDRESS_PROVINCE']) ? $arFields['ADDRESS_PROVINCE'] : null, 'COUNTRY' => isset($arFields['ADDRESS_COUNTRY']) ? $arFields['ADDRESS_COUNTRY'] : null, 'COUNTRY_CODE' => isset($arFields['ADDRESS_COUNTRY_CODE']) ? $arFields['ADDRESS_COUNTRY_CODE'] : null));
     CCrmEntityHelper::NormalizeUserFields($arFields, self::$sUFEntityID, $GLOBALS['USER_FIELD_MANAGER'], array('IS_NEW' => true));
     $GLOBALS['USER_FIELD_MANAGER']->Update(self::$sUFEntityID, $ID, $arFields);
     if (isset($arFields['FM']) && is_array($arFields['FM'])) {
         $CCrmFieldMulti = new CCrmFieldMulti();
         $CCrmFieldMulti->SetFields('LEAD', $ID, $arFields['FM']);
         $emails = \Bitrix\Crm\Integrity\DuplicateCommunicationCriterion::extractMultifieldsValues($arFields['FM'], 'EMAIL');
         if (!empty($emails)) {
             \Bitrix\Crm\Integrity\DuplicateCommunicationCriterion::register(CCrmOwnerType::Lead, $ID, 'EMAIL', $emails);
         }
         $phones = \Bitrix\Crm\Integrity\DuplicateCommunicationCriterion::extractMultifieldsValues($arFields['FM'], 'PHONE');
         if (!empty($phones)) {
             \Bitrix\Crm\Integrity\DuplicateCommunicationCriterion::register(CCrmOwnerType::Lead, $ID, 'PHONE', $phones);
         }
     }
     \Bitrix\Crm\Integrity\DuplicateEntityRanking::registerEntityStatistics(CCrmOwnerType::Lead, $ID, $arFields);
     if ($bUpdateSearch) {
         CCrmSearch::UpdateSearch(array('ID' => $ID, 'CHECK_PERMISSIONS' => 'N'), 'LEAD', true);
     }
     if (isset($arOptions['REGISTER_SONET_EVENT']) && $arOptions['REGISTER_SONET_EVENT'] === true) {
         $opportunity = round(isset($arFields['OPPORTUNITY']) ? doubleval($arFields['OPPORTUNITY']) : 0.0, 2);
         $currencyID = isset($arFields['CURRENCY_ID']) ? $arFields['CURRENCY_ID'] : '';
         if ($currencyID === '') {
             $currencyID = CCrmCurrency::GetBaseCurrencyID();
         }
         $assignedByID = intval($arFields['ASSIGNED_BY_ID']);
         $createdByID = intval($arFields['CREATED_BY_ID']);
         $liveFeedFields = array('USER_ID' => $createdByID, 'ENTITY_TYPE_ID' => CCrmOwnerType::Lead, 'ENTITY_ID' => $ID, 'TITLE' => GetMessage('CRM_LEAD_EVENT_ADD'), 'MESSAGE' => '', 'PARAMS' => array('TITLE' => $arFields['TITLE'], 'NAME' => isset($arFields['NAME']) ? $arFields['NAME'] : '', 'SECOND_NAME' => isset($arFields['SECOND_NAME']) ? $arFields['SECOND_NAME'] : '', 'LAST_NAME' => isset($arFields['LAST_NAME']) ? $arFields['LAST_NAME'] : '', 'COMPANY_TITLE' => isset($arFields['COMPANY_TITLE']) ? $arFields['COMPANY_TITLE'] : '', 'STATUS_ID' => $arFields['STATUS_ID'], 'OPPORTUNITY' => strval($opportunity), 'CURRENCY_ID' => $currencyID, 'AUTHOR_ID' => intval($arFields['CREATED_BY_ID']), 'RESPONSIBLE_ID' => $assignedByID));
         CCrmSonetSubscription::RegisterSubscription(CCrmOwnerType::Lead, $ID, CCrmSonetSubscriptionType::Responsibility, $assignedByID);
         $logEventID = CCrmLiveFeed::CreateLogEvent($liveFeedFields, CCrmLiveFeedEvent::Add);
         if ($logEventID && $assignedByID != $createdByID && CModule::IncludeModule("im")) {
             $url = CCrmOwnerType::GetShowUrl(CCrmOwnerType::Lead, $ID);
             $serverName = (CMain::IsHTTPS() ? "https" : "http") . "://" . (defined("SITE_SERVER_NAME") && strlen(SITE_SERVER_NAME) > 0 ? SITE_SERVER_NAME : COption::GetOptionString("main", "server_name", ""));
             $arMessageFields = array("MESSAGE_TYPE" => IM_MESSAGE_SYSTEM, "TO_USER_ID" => $assignedByID, "FROM_USER_ID" => $createdByID, "NOTIFY_TYPE" => IM_NOTIFY_FROM, "NOTIFY_MODULE" => "crm", "LOG_ID" => $logEventID, "NOTIFY_EVENT" => "lead_add", "NOTIFY_TAG" => "CRM|LEAD|" . $ID, "NOTIFY_MESSAGE" => GetMessage("CRM_LEAD_RESPONSIBLE_IM_NOTIFY", array("#title#" => "<a href=\"" . $url . "\" class=\"bx-notifier-item-action\">" . htmlspecialcharsbx($arFields['TITLE']) . "</a>")), "NOTIFY_MESSAGE_OUT" => GetMessage("CRM_LEAD_RESPONSIBLE_IM_NOTIFY", array("#title#" => htmlspecialcharsbx($arFields['TITLE']))) . " (" . $serverName . $url . ")");
             CIMNotify::Add($arMessageFields);
         }
     }
     $afterEvents = GetModuleEvents('crm', 'OnAfterCrmLeadAdd');
     while ($arEvent = $afterEvents->Fetch()) {
         ExecuteModuleEventEx($arEvent, array(&$arFields));
     }
     if (isset($arFields['ORIGIN_ID']) && $arFields['ORIGIN_ID'] !== '') {
         $afterEvents = GetModuleEvents('crm', 'OnAfterExternalCrmLeadAdd');
         while ($arEvent = $afterEvents->Fetch()) {
             ExecuteModuleEventEx($arEvent, array(&$arFields));
         }
     }
     return $ID;
 }
 public function isDeletable($userID = 0, $userPermissions = null)
 {
     if (!is_int($userID)) {
         throw new Main\ArgumentTypeException('userID', 'integer');
     }
     if ($userPermissions === null) {
         $userPermissions = \CCrmPerms::GetUserPermissions($userID);
     }
     return \CCrmAuthorizationHelper::CheckDeletePermission(\CCrmOwnerType::ResolveName($this->entityTypeID), $this->entityID, $userPermissions);
 }
 protected function onAfterDuplicateCreated(Duplicate $dup, $entityTypeID, $userID, $enablePermissionCheck, $enableRanking, array &$rankings)
 {
     $name = $this->name;
     $lastName = $this->lastName;
     $secondName = $this->secondName;
     $rootEntityID = $dup->getRootEntityID();
     if ($secondName === '' && $name === '') {
         return;
     }
     $permissionSql = '';
     if ($enablePermissionCheck) {
         $permissions = isset($params['PERMISSIONS']) ? $params['PERMISSIONS'] : null;
         if ($permissions === null) {
             $permissions = \CCrmPerms::GetUserPermissions($userID);
         }
         $permissionSql = \CCrmPerms::BuildSql(\CCrmOwnerType::ResolveName($entityTypeID), '', 'READ', array('RAW_QUERY' => true, 'PERMS' => $permissions));
         if ($permissionSql === false) {
             //Access denied;
             return;
         }
     }
     if ($secondName !== '') {
         $query = new Main\Entity\Query(DuplicatePersonMatchCodeTable::getEntity());
         $query->addSelect('ENTITY_ID');
         $query->addFilter('=ENTITY_TYPE_ID', $entityTypeID);
         $query->addFilter('=LAST_NAME', $lastName);
         $query->addFilter('=NAME', $name);
         $query->addFilter('=SECOND_NAME', '');
         if ($rootEntityID) {
             $query->addFilter('!ENTITY_ID', $rootEntityID);
             $query->addFilter('!@ENTITY_ID', DuplicateIndexMismatch::prepareQueryField(self::createFromMatches(array('LAST_NAME' => $lastName, 'NAME' => $name)), $entityTypeID, $rootEntityID, $userID));
         }
         if ($enablePermissionCheck && $permissionSql !== '') {
             $query->addFilter('@ENTITY_ID', new Main\DB\SqlExpression($permissionSql));
         }
         $dbResult = $query->exec();
         while ($fields = $dbResult->fetch()) {
             $entityID = isset($fields['ENTITY_ID']) ? intval($fields['ENTITY_ID']) : 0;
             if ($entityID <= 0) {
                 continue;
             }
             $entity = new DuplicateEntity($entityTypeID, $entityID);
             $entity->setCriterion(self::createFromMatches(array('LAST_NAME' => $lastName, 'NAME' => $name)));
             if ($enableRanking) {
                 $rankings[] = $entity->getRanking();
             }
             $dup->addEntity($entity);
         }
     }
     if ($name !== '') {
         $query = new Main\Entity\Query(DuplicatePersonMatchCodeTable::getEntity());
         $query->addSelect('ENTITY_ID');
         $query->addFilter('=ENTITY_TYPE_ID', $entityTypeID);
         $query->addFilter('=LAST_NAME', $lastName);
         $query->addFilter('=NAME', '');
         $query->addFilter('=SECOND_NAME', '');
         if ($rootEntityID) {
             $query->addFilter('!ENTITY_ID', $rootEntityID);
             $query->addFilter('!@ENTITY_ID', DuplicateIndexMismatch::prepareQueryField(self::createFromMatches(array('LAST_NAME' => $lastName)), $entityTypeID, $rootEntityID, $userID));
         }
         if ($enablePermissionCheck && $permissionSql !== '') {
             $query->addFilter('@ENTITY_ID', new Main\DB\SqlExpression($permissionSql));
         }
         $dbResult = $query->exec();
         while ($fields = $dbResult->fetch()) {
             $entityID = isset($fields['ENTITY_ID']) ? intval($fields['ENTITY_ID']) : 0;
             if ($entityID <= 0) {
                 continue;
             }
             $entity = new DuplicateEntity($entityTypeID, $entityID);
             $entity->setCriterion(self::createFromMatches(array('LAST_NAME' => $lastName)));
             if ($enableRanking) {
                 $rankings[] = $entity->getRanking();
             }
             $dup->addEntity($entity);
         }
     }
 }
Beispiel #8
0
 protected function isAuthorizedUser()
 {
     if ($this->isAuthorizedUser === null) {
         /**@var \CCrmPerms $userPermissions @**/
         $userPermissions = CCrmPerms::GetUserPermissions($this->user->GetID());
         $this->isAuthorizedUser = $userPermissions->HavePerm('CONFIG', BX_CRM_PERM_CONFIG, 'WRITE');
     }
     return $this->isAuthorizedUser;
 }
Beispiel #9
0
 public static function ProcessLogEventEditPOST($arPOST, $entityTypeID, $entityID, &$arResult)
 {
     $arEntityData = array();
     $errors = array();
     $enableTitle = isset($arPOST['ENABLE_POST_TITLE']) && strtoupper($arPOST['ENABLE_POST_TITLE']) === 'Y';
     $title = $enableTitle && isset($arPOST['POST_TITLE']) ? $arPOST['POST_TITLE'] : '';
     $message = isset($arPOST['MESSAGE']) ? htmlspecialcharsback($arPOST['MESSAGE']) : '';
     $arResult['EVENT']['MESSAGE'] = $message;
     $arResult['EVENT']['TITLE'] = $title;
     $arResult['ENABLE_TITLE'] = $enableTitle;
     $attachedFiles = array();
     $webDavFileFieldName = $arResult['WEB_DAV_FILE_FIELD_NAME'];
     if ($webDavFileFieldName !== '' && isset($GLOBALS[$webDavFileFieldName]) && is_array($GLOBALS[$webDavFileFieldName])) {
         foreach ($GLOBALS[$webDavFileFieldName] as $fileID) {
             if ($fileID === '') {
                 continue;
             }
             //fileID:  "888|165|16"
             $attachedFiles[] = $fileID;
         }
         if (!empty($attachedFiles) && is_array($arResult['WEB_DAV_FILE_FIELD'])) {
             $arResult['WEB_DAV_FILE_FIELD']['VALUE'] = $attachedFiles;
         }
     }
     $allowToAll = COption::GetOptionString('socialnetwork', 'allow_livefeed_toall', 'Y') === 'Y';
     if ($allowToAll) {
         $arToAllRights = unserialize(COption::GetOptionString("socialnetwork", "livefeed_toall_rights", 'a:1:{i:0;s:2:"AU";}'));
         if (!$arToAllRights) {
             $arToAllRights = array('AU');
         }
         $arUserGroupCode = array_merge(array('AU'), CAccess::GetUserCodesArray($arResult['USER_ID']));
         if (count(array_intersect($arToAllRights, $arUserGroupCode)) <= 0) {
             $allowToAll = false;
         }
     }
     $arSocnetRights = array();
     if (!empty($arPOST['SPERM'])) {
         foreach ($arPOST['SPERM'] as $v => $k) {
             if (strlen($v) > 0 && is_array($k) && !empty($k)) {
                 foreach ($k as $vv) {
                     if (strlen($vv) > 0) {
                         $arSocnetRights[] = $vv;
                     }
                 }
             }
         }
     }
     if (in_array('UA', $arSocnetRights) && !$allowToAll) {
         foreach ($arSocnetRights as $key => $value) {
             if ($value == 'UA') {
                 unset($arSocnetRights[$key]);
                 break;
             }
         }
     }
     foreach ($arSocnetRights as $key => $value) {
         if ($value == 'UA') {
             $arSocnetRights[] = 'AU';
             unset($arSocnetRights[$key]);
             break;
         }
     }
     $arSocnetRights = array_unique($arSocnetRights);
     $allFeedEtityTypes = CCrmLiveFeedEntity::GetAll();
     $userPerms = CCrmPerms::GetCurrentUserPermissions();
     foreach ($arSocnetRights as $key => $value) {
         $groupCodeData = array();
         if (CCrmLiveFeed::TryParseGroupCode($value, $groupCodeData) && in_array($groupCodeData['ENTITY_TYPE'], $allFeedEtityTypes, true)) {
             $groupCodeEntityType = $groupCodeData['ENTITY_TYPE'];
             $groupCodeEntityID = $groupCodeData['ENTITY_ID'];
             if (!CCrmLiveFeed::CheckCreatePermission($groupCodeEntityType, $groupCodeEntityID, $userPerms)) {
                 $canonicalEntityTypeID = CCrmLiveFeedEntity::ResolveEntityTypeID($groupCodeEntityType);
                 $errors[] = GetMessage('CRM_SL_EVENT_EDIT_PERMISSION_DENIED', array('#TITLE#' => CCrmOwnerType::GetCaption($canonicalEntityTypeID, $groupCodeEntityID, false)));
             } else {
                 $arEntityData[] = array('ENTITY_TYPE' => $groupCodeEntityType, 'ENTITY_ID' => $groupCodeEntityID);
             }
         }
     }
     if (!(CCrmOwnerType::IsDefined($entityTypeID) && $entityID > 0) && !empty($arEntityData)) {
         $entityData = $arEntityData[0];
         $entityTypeID = CCrmLiveFeedEntity::ResolveEntityTypeID($entityData['ENTITY_TYPE']);
         $entityID = $entityData['ENTITY_ID'];
     }
     if (!empty($arEntityData)) {
         $arResult['ENTITY_DATA'] = $arEntityData;
     }
     if (!(CCrmOwnerType::IsDefined($entityTypeID) && $entityID > 0)) {
         $errors[] = GetMessage('CRM_SL_EVENT_EDIT_ENTITY_NOT_DEFINED');
     }
     if ($message === '') {
         $errors[] = GetMessage('CRM_SL_EVENT_EDIT_EMPTY_MESSAGE');
     }
     if (empty($errors)) {
         $fields = array('ENTITY_TYPE_ID' => $entityTypeID, 'ENTITY_ID' => $entityID, 'USER_ID' => $arResult['USER_ID'], 'TITLE' => $title, 'MESSAGE' => $message, 'RIGHTS' => $arSocnetRights);
         $parents = array();
         CCrmOwnerType::TryGetOwnerInfos($entityTypeID, $entityID, $parents, array('ENABLE_MAPPING' => true));
         foreach ($arEntityData as $entityData) {
             $curEntityTypeID = CCrmLiveFeedEntity::ResolveEntityTypeID($entityData['ENTITY_TYPE']);
             $curEntityID = $entityData['ENTITY_ID'];
             $entityKey = "{$curEntityTypeID}_{$curEntityID}";
             if (!isset($parents[$entityKey]) && !($curEntityTypeID === $entityTypeID && $curEntityID === $entityID)) {
                 $parents[$entityKey] = array('ENTITY_TYPE_ID' => $curEntityTypeID, 'ENTITY_ID' => $curEntityID);
             }
         }
         if (!empty($parents)) {
             $fields['PARENTS'] = array_values($parents);
         }
         if (!empty($attachedFiles)) {
             $fields['WEB_DAV_FILES'] = array($webDavFileFieldName => $attachedFiles);
         }
         $messageID = CCrmLiveFeed::CreateLogMessage($fields);
         if (!(is_int($messageID) && $messageID > 0)) {
             $errors[] = isset($fields['ERROR']) ? $fields['ERROR'] : 'UNKNOWN ERROR';
         } else {
             preg_match_all("/\\[user\\s*=\\s*([^\\]]*)\\](.+?)\\[\\/user\\]/is" . BX_UTF_PCRE_MODIFIER, $message, $arMention);
             if (!empty($arMention) && !empty($arMention[1]) && CModule::IncludeModule("im")) {
                 $arMention = $arMention[1];
                 $arMention = array_unique($arMention);
                 $arMessageFields = array("MESSAGE_TYPE" => IM_MESSAGE_SYSTEM, "TO_USER_ID" => "", "FROM_USER_ID" => $arResult['USER_ID'], "NOTIFY_TYPE" => IM_NOTIFY_FROM, "NOTIFY_MODULE" => "crm", "NOTIFY_EVENT" => "mention");
                 $genderSuffix = "";
                 $dbUser = CUser::GetByID($arResult['USER_ID']);
                 if ($arUser = $dbUser->Fetch()) {
                     switch ($arUser["PERSONAL_GENDER"]) {
                         case "M":
                             $genderSuffix = "_M";
                             break;
                         case "F":
                             $genderSuffix = "_F";
                             break;
                         default:
                             $genderSuffix = "";
                     }
                 }
                 $strIMMessageTitle = str_replace(array("\r\n", "\n"), " ", strlen($title) > 0 ? $title : $message);
                 if (CModule::IncludeModule("blog")) {
                     $strIMMessageTitle = trim(blogTextParser::killAllTags($strIMMessageTitle));
                 }
                 $strIMMessageTitle = TruncateText($strIMMessageTitle, 100);
                 $strIMMessageTitleOut = TruncateText($strIMMessageTitle, 255);
                 $strLogEntryURL = COption::GetOptionString("socialnetwork", "log_entry_page", SITE_DIR . "company/personal/log/#log_id#/", SITE_ID);
                 $strLogEntryURL = CComponentEngine::MakePathFromTemplate($strLogEntryURL, array("log_id" => $messageID));
                 $strLogEntryCrmURL = CComponentEngine::MakePathFromTemplate(SITE_DIR . "crm/stream/?log_id=#log_id#", array("log_id" => $messageID));
                 $serverName = (CMain::IsHTTPS() ? "https" : "http") . "://" . (defined("SITE_SERVER_NAME") && strlen(SITE_SERVER_NAME) > 0 ? SITE_SERVER_NAME : COption::GetOptionString("main", "server_name", ""));
                 foreach ($arMention as $val) {
                     $val = IntVal($val);
                     if ($val > 0 && $val != $arResult['USER_ID']) {
                         $bHasAccess = false;
                         if (in_array('U' . $val, $arSocnetRights)) {
                             $url = $strLogEntryURL;
                             $bHasAccess = true;
                         }
                         if (!$bHasAccess) {
                             $arAccessCodes = array();
                             $dbAccess = CAccess::GetUserCodes($val);
                             while ($arAccess = $dbAccess->Fetch()) {
                                 $arAccessCodes[] = $arAccess["ACCESS_CODE"];
                             }
                             $arTmp = array_intersect($arAccess, $arSocnetRights);
                             if (!empty($arTmp)) {
                                 $url = $strLogEntryURL;
                                 $bHasAccess = true;
                             }
                         }
                         if (!$bHasAccess) {
                             $userPermissions = CCrmPerms::GetUserPermissions($val);
                             foreach ($arEntityData as $arEntity) {
                                 if (CCrmAuthorizationHelper::CheckReadPermission(CCrmOwnerType::ResolveName(CCrmLiveFeedEntity::ResolveEntityTypeID($arEntity['ENTITY_TYPE'])), $arEntity['ENTITY_ID'], $userPermissions)) {
                                     $url = $strLogEntryCrmURL;
                                     $bHasAccess = true;
                                     break;
                                 }
                             }
                         }
                         if ($bHasAccess) {
                             $arMessageFields["TO_USER_ID"] = $val;
                             $arMessageFields["NOTIFY_TAG"] = "CRM|MESSAGE_MENTION|" . $messageID;
                             $arMessageFields["NOTIFY_MESSAGE"] = GetMessage("CRM_SL_EVENT_IM_MENTION_POST" . $genderSuffix, array("#title#" => "<a href=\"" . $url . "\" class=\"bx-notifier-item-action\">" . htmlspecialcharsbx($strIMMessageTitle) . "</a>"));
                             $arMessageFields["NOTIFY_MESSAGE_OUT"] = GetMessage("CRM_SL_EVENT_IM_MENTION_POST" . $genderSuffix, array("#title#" => htmlspecialcharsbx($strIMMessageTitleOut))) . " (" . $serverName . $url . ")";
                             CIMNotify::Add($arMessageFields);
                         }
                     }
                 }
             }
             return $messageID;
         }
     }
     return $errors;
 }
Beispiel #10
0
 public function Add(&$arFields, $bUpdateSearch = true, $options = array())
 {
     global $DB;
     if (!is_array($options)) {
         $options = array();
     }
     $this->LAST_ERROR = '';
     $iUserId = CCrmSecurityHelper::GetCurrentUserID();
     if (isset($arFields['ID'])) {
         unset($arFields['ID']);
     }
     if (isset($arFields['DATE_CREATE'])) {
         unset($arFields['DATE_CREATE']);
     }
     $arFields['~DATE_CREATE'] = $DB->CurrentTimeFunction();
     $arFields['~DATE_MODIFY'] = $DB->CurrentTimeFunction();
     if (!isset($arFields['CREATED_BY_ID']) || (int) $arFields['CREATED_BY_ID'] <= 0) {
         $arFields['CREATED_BY_ID'] = $iUserId;
     }
     if (!isset($arFields['MODIFY_BY_ID']) || (int) $arFields['MODIFY_BY_ID'] <= 0) {
         $arFields['MODIFY_BY_ID'] = $iUserId;
     }
     if (isset($arFields['ASSIGNED_BY_ID']) && is_array($arFields['ASSIGNED_BY_ID'])) {
         $arFields['ASSIGNED_BY_ID'] = count($arFields['ASSIGNED_BY_ID']) > 0 ? intval($arFields['ASSIGNED_BY_ID'][0]) : $iUserId;
     }
     if (!isset($arFields['ASSIGNED_BY_ID']) || (int) $arFields['ASSIGNED_BY_ID'] <= 0) {
         $arFields['ASSIGNED_BY_ID'] = $iUserId;
     }
     // person type
     if (!isset($arFields['PERSON_TYPE_ID']) || intval($arFields['PERSON_TYPE_ID']) <= 0) {
         $arFields['PERSON_TYPE_ID'] = 0;
         $arPersonTypes = CCrmPaySystem::getPersonTypeIDs();
         if (isset($arPersonTypes['CONTACT']) && (!isset($arFields['COMPANY_ID']) || intval($arFields['COMPANY_ID']) <= 0)) {
             $arFields['PERSON_TYPE_ID'] = intval($arPersonTypes['CONTACT']);
         } else {
             if (isset($arPersonTypes['COMPANY']) && isset($arFields['COMPANY_ID']) && intval($arFields['COMPANY_ID']) > 0) {
                 $arFields['PERSON_TYPE_ID'] = intval($arPersonTypes['COMPANY']);
             }
         }
     }
     // storage type
     $storageTypeID = isset($arFields['STORAGE_TYPE_ID']) ? intval($arFields['STORAGE_TYPE_ID']) : CCrmQuoteStorageType::Undefined;
     if ($storageTypeID === CCrmQuoteStorageType::Undefined || !CCrmQuoteStorageType::IsDefined($storageTypeID)) {
         $storageTypeID = self::GetDefaultStorageTypeID();
     }
     $arFields['STORAGE_TYPE_ID'] = $storageTypeID;
     // storage elements
     $storageElementIDs = isset($arFields['STORAGE_ELEMENT_IDS']) && is_array($arFields['STORAGE_ELEMENT_IDS']) ? $arFields['STORAGE_ELEMENT_IDS'] : null;
     $arFields['STORAGE_ELEMENT_IDS'] = null;
     if ($storageElementIDs !== null) {
         $storageElementIDs = self::NormalizeStorageElementIDs($storageElementIDs);
         $arFields['STORAGE_ELEMENT_IDS'] = serialize($storageElementIDs);
     }
     if (!$this->CheckFields($arFields, false, $options)) {
         $result = false;
         $arFields['RESULT_MESSAGE'] =& $this->LAST_ERROR;
     } else {
         if (!isset($arFields['STATUS_ID'])) {
             $arFields['STATUS_ID'] = 'DRAFT';
         }
         $arAttr = array();
         if (!empty($arFields['STATUS_ID'])) {
             $arAttr['STATUS_ID'] = $arFields['STATUS_ID'];
         }
         if (!empty($arFields['OPENED'])) {
             $arAttr['OPENED'] = $arFields['OPENED'];
         }
         $sPermission = 'ADD';
         if (isset($arFields['PERMISSION'])) {
             if ($arFields['PERMISSION'] == 'IMPORT') {
                 $sPermission = 'IMPORT';
             }
             unset($arFields['PERMISSION']);
         }
         if ($this->bCheckPermission) {
             $arEntityAttr = self::BuildEntityAttr($iUserId, $arAttr);
             $userPerms = $iUserId == CCrmPerms::GetCurrentUserID() ? $this->cPerms : CCrmPerms::GetUserPermissions($iUserId);
             $sEntityPerm = $userPerms->GetPermType('QUOTE', $sPermission, $arEntityAttr);
             if ($sEntityPerm == BX_CRM_PERM_NONE) {
                 $this->LAST_ERROR = GetMessage('CRM_PERMISSION_DENIED');
                 $arFields['RESULT_MESSAGE'] =& $this->LAST_ERROR;
                 return false;
             }
             $assignedByID = intval($arFields['ASSIGNED_BY_ID']);
             if ($sEntityPerm == BX_CRM_PERM_SELF && $assignedByID != $iUserId) {
                 $arFields['ASSIGNED_BY_ID'] = $iUserId;
             }
             if ($sEntityPerm == BX_CRM_PERM_OPEN && $iUserId == $assignedByID) {
                 $arFields['OPENED'] = 'Y';
             }
         }
         $assignedByID = intval($arFields['ASSIGNED_BY_ID']);
         $arEntityAttr = self::BuildEntityAttr($assignedByID, $arAttr);
         $userPerms = $assignedByID == CCrmPerms::GetCurrentUserID() ? $this->cPerms : CCrmPerms::GetUserPermissions($assignedByID);
         $sEntityPerm = $userPerms->GetPermType('QUOTE', $sPermission, $arEntityAttr);
         $this->PrepareEntityAttrs($arEntityAttr, $sEntityPerm);
         // Calculation of Account Data
         $accData = CCrmAccountingHelper::PrepareAccountingData(array('CURRENCY_ID' => isset($arFields['CURRENCY_ID']) ? $arFields['CURRENCY_ID'] : null, 'SUM' => isset($arFields['OPPORTUNITY']) ? $arFields['OPPORTUNITY'] : null, 'EXCH_RATE' => isset($arFields['EXCH_RATE']) ? $arFields['EXCH_RATE'] : null));
         if (is_array($accData)) {
             $arFields['ACCOUNT_CURRENCY_ID'] = $accData['ACCOUNT_CURRENCY_ID'];
             $arFields['OPPORTUNITY_ACCOUNT'] = $accData['ACCOUNT_SUM'];
         }
         $accData = CCrmAccountingHelper::PrepareAccountingData(array('CURRENCY_ID' => isset($arFields['CURRENCY_ID']) ? $arFields['CURRENCY_ID'] : null, 'SUM' => isset($arFields['TAX_VALUE']) ? $arFields['TAX_VALUE'] : null, 'EXCH_RATE' => isset($arFields['EXCH_RATE']) ? $arFields['EXCH_RATE'] : null));
         if (is_array($accData)) {
             $arFields['TAX_VALUE_ACCOUNT'] = $accData['ACCOUNT_SUM'];
         }
         $arFields['CLOSED'] = self::GetStatusSemantics($arFields['STATUS_ID']) === 'process' ? 'N' : 'Y';
         $now = ConvertTimeStamp(time() + CTimeZone::GetOffset(), 'FULL', SITE_ID);
         if (!isset($arFields['BEGINDATE'][0])) {
             $arFields['BEGINDATE'] = $now;
         }
         if ($arFields['CLOSED'] === 'Y' && (!isset($arFields['CLOSEDATE']) || $arFields['CLOSEDATE'] === '')) {
             $arFields['CLOSEDATE'] = $now;
         }
         foreach (GetModuleEvents('crm', 'OnBeforeCrmQuoteAdd', true) as $arEvent) {
             if (ExecuteModuleEventEx($arEvent, array(&$arFields)) === false) {
                 if (isset($arFields['RESULT_MESSAGE'])) {
                     $this->LAST_ERROR = $arFields['RESULT_MESSAGE'];
                 } else {
                     $this->LAST_ERROR = GetMessage('CRM_QUOTE_CREATION_CANCELED', array('#NAME#' => $arEvent['TO_NAME']));
                     $arFields['RESULT_MESSAGE'] =& $this->LAST_ERROR;
                 }
                 return false;
             }
         }
         $clobFieldNames = array('COMMENTS', 'CONTENT', 'STORAGE_ELEMENT_IDS');
         $clobFields = array();
         foreach ($clobFieldNames as $fieldName) {
             if (array_key_exists($fieldName, $arFields)) {
                 $clobFields[] = $fieldName;
             }
         }
         $ID = intval($DB->Add('b_crm_quote', $arFields, $clobFields, 'FILE: ' . __FILE__ . '<br /> LINE: ' . __LINE__));
         if (!self::SetQuoteNumber($ID)) {
             $this->LAST_ERROR = GetMessage('CRM_ERROR_QUOTE_NUMBER_IS_NOT_SET');
             $arFields['RESULT_MESSAGE'] =& $this->LAST_ERROR;
             return false;
         }
         CCrmEntityHelper::NormalizeUserFields($arFields, self::$sUFEntityID, $GLOBALS['USER_FIELD_MANAGER'], array('IS_NEW' => true));
         $GLOBALS['USER_FIELD_MANAGER']->Update(self::$sUFEntityID, $ID, $arFields);
         CCrmPerms::UpdateEntityAttr('QUOTE', $ID, $arEntityAttr);
         if (is_array($storageElementIDs)) {
             CCrmQuote::DoSaveElementIDs($ID, $storageTypeID, $storageElementIDs);
         }
         unset($storageTypeID, $storageElementIDs);
         if ($bUpdateSearch) {
             $arFilterTmp = array('ID' => $ID);
             if (!$this->bCheckPermission) {
                 $arFilterTmp["CHECK_PERMISSIONS"] = "N";
             }
             CCrmSearch::UpdateSearch($arFilterTmp, 'QUOTE', true);
         }
         $result = $arFields['ID'] = $ID;
         if (isset($GLOBALS["USER"]) && isset($arFields['COMPANY_ID']) && intval($arFields['COMPANY_ID']) > 0) {
             if (!class_exists('CUserOptions')) {
                 include_once $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/main/classes/' . $GLOBALS['DBType'] . '/favorites.php';
             }
             CUserOptions::SetOption('crm', 'crm_company_search', array('last_selected' => $arFields['COMPANY_ID']));
         }
         if (isset($GLOBALS["USER"]) && isset($arFields['CONTACT_ID']) && intval($arFields['CONTACT_ID']) > 0) {
             if (!class_exists('CUserOptions')) {
                 include_once $_SERVER['DOCUMENT_ROOT'] . "/bitrix/modules/main/classes/" . $GLOBALS['DBType'] . "/favorites.php";
             }
             CUserOptions::SetOption("crm", "crm_contact_search", array('last_selected' => $arFields['CONTACT_ID']));
         }
         if (isset($arFields['FM']) && is_array($arFields['FM'])) {
             $CCrmFieldMulti = new CCrmFieldMulti();
             $CCrmFieldMulti->SetFields('QUOTE', $ID, $arFields['FM']);
         }
         foreach (GetModuleEvents('crm', 'OnAfterCrmQuoteAdd', true) as $arEvent) {
             ExecuteModuleEventEx($arEvent, array(&$arFields));
         }
     }
     return $result;
 }
Beispiel #11
0
 public static function GetDataForPopup($callId, $phone, $userId = 0)
 {
     if (strlen($phone) <= 0 || !CModule::IncludeModule('crm')) {
         return false;
     }
     if ($userId > 0) {
         $findParams = array('USER_ID' => $userId);
     } else {
         $findParams = array('ENABLE_EXTENDED_MODE' => false);
     }
     $crm = CCrmSipHelper::findByPhoneNumber((string) $phone, $findParams);
     if ($crm) {
         $dealStatuses = CCrmViewHelper::GetDealStageInfos();
         $entity = '';
         $entityData = array();
         $entities = array();
         $arResult = array('FOUND' => 'Y', 'CONTACT' => array(), 'COMPANY' => array(), 'ACTIVITIES' => array(), 'DEALS' => array(), 'RESPONSIBILITY' => array());
         if (isset($crm['CONTACT'])) {
             $entity = 'CONTACT';
             $entityData = $crm[$entity][0];
             $arResult['CONTACT'] = array('NAME' => $entityData['FORMATTED_NAME'], 'POST' => $entityData['POST'], 'PHOTO' => '');
             if (intval($entityData['PHOTO']) > 0) {
                 $arPhoto = CFile::ResizeImageGet($entityData['PHOTO'], array('width' => 37, 'height' => 37), BX_RESIZE_IMAGE_EXACT, false, false, true);
                 $arResult['CONTACT']['PHOTO'] = $arPhoto['src'];
             }
             $arResult['COMPANY'] = $entityData['COMPANY_TITLE'];
             $arResult['CONTACT_DATA'] = array('ID' => $entityData['ID']);
         } else {
             if (isset($crm['LEAD'])) {
                 $entity = 'LEAD';
                 $entityData = $crm[$entity][0];
                 $arResult['CONTACT'] = array('ID' => 0, 'NAME' => !empty($entityData['FORMATTED_NAME']) ? $entityData['FORMATTED_NAME'] : $entityData['TITLE'], 'POST' => $entityData['POST'], 'PHOTO' => '');
                 $arResult['COMPANY'] = $entityData['COMPANY_TITLE'];
                 $arResult['LEAD_DATA'] = array('ID' => $entityData['ID'], 'ASSIGNED_BY_ID' => $entityData['ASSIGNED_BY_ID']);
             } else {
                 if (isset($crm['COMPANY'])) {
                     $entity = 'COMPANY';
                     $entityData = $crm[$entity][0];
                     $arResult['COMPANY'] = $entityData['TITLE'];
                     $arResult['COMPANY_DATA'] = array('ID' => $entityData['ID']);
                 }
             }
         }
         if ($entityData['ASSIGNED_BY_ID'] > 0) {
             $ar = Bitrix\Main\UserTable::getById($entityData['ASSIGNED_BY_ID']);
             if ($user = $ar->fetch()) {
                 $arPhoto = CFile::ResizeImageGet($user['PERSONAL_PHOTO'], array('width' => 37, 'height' => 37), BX_RESIZE_IMAGE_EXACT, false, false, true);
                 $arResult['RESPONSIBILITY'] = array('ID' => $user['ID'], 'NAME' => CUser::FormatName(CSite::GetNameFormat(false), $user, true, false), 'PHOTO' => $arPhoto ? $arPhoto['src'] : '', 'POST' => $user['WORK_POSITION']);
             }
         }
         if (isset($entityData['SHOW_URL'])) {
             $arResult['SHOW_URL'] = $entityData['SHOW_URL'];
         }
         if (isset($entityData['ACTIVITY_LIST_URL'])) {
             $arResult['ACTIVITY_URL'] = $entityData['ACTIVITY_LIST_URL'];
         }
         if (isset($entityData['INVOICE_LIST_URL'])) {
             $arResult['INVOICE_URL'] = $entityData['INVOICE_LIST_URL'];
         }
         if (isset($entityData['DEAL_LIST_URL'])) {
             $arResult['DEAL_URL'] = $entityData['DEAL_LIST_URL'];
         }
         $activityId = CCrmActivity::GetIDByOrigin('VI_' . $callId);
         if ($activityId) {
             $arResult['CURRENT_CALL_URL'] = CCrmOwnerType::GetEditUrl(CCrmOwnerType::Activity, $activityId);
             if ($arResult['CURRENT_CALL_URL'] !== '') {
                 $arResult['CURRENT_CALL_URL'] = CCrmUrlUtil::AddUrlParams($arResult['CURRENT_CALL_URL'], array("disable_storage_edit" => 'Y'));
             }
         }
         if (isset($crm['CONTACT']) && isset($crm['COMPANY'])) {
             $entities = array('CONTACT', 'COMPANY', 'LEAD');
         } else {
             if (isset($crm['CONTACT']) && isset($crm['LEAD']) && !isset($crm['COMPANY'])) {
                 $entities = array('CONTACT', 'LEAD');
             } else {
                 if (isset($crm['LEAD']) && isset($crm['COMPANY']) && !isset($crm['CONTACT'])) {
                     $entities = array('LEAD', 'COMPANY');
                 } else {
                     $entities = array($entity);
                 }
             }
         }
         foreach ($entities as $entity) {
             if (isset($crm[$entity][0]['ACTIVITIES'])) {
                 foreach ($crm[$entity][0]['ACTIVITIES'] as $activity) {
                     if ($activity['ID'] == $activityId) {
                         continue;
                     }
                     $overdue = 'N';
                     if (strlen($activity['DEADLINE']) > 0 && MakeTimeStamp($activity['DEADLINE']) < time()) {
                         $overdue = 'Y';
                     }
                     $arResult['ACTIVITIES'][$activity['ID']] = array('TITLE' => $activity['SUBJECT'], 'DATE' => strlen($activity['DEADLINE']) > 0 ? $activity['DEADLINE'] : $activity['END_TIME'], 'OVERDUE' => $overdue, 'URL' => $activity['SHOW_URL']);
                 }
                 if (!empty($arResult['ACTIVITIES'])) {
                     $arResult['ACTIVITIES'] = array_values($arResult['ACTIVITIES']);
                 }
             }
             if (isset($crm[$entity][0]['DEALS'])) {
                 foreach ($crm[$entity][0]['DEALS'] as $deal) {
                     $opportunity = CCrmCurrency::MoneyToString($deal['OPPORTUNITY'], $deal['CURRENCY_ID']);
                     if (strpos('&', $opportunity)) {
                         $opportunity = CCrmCurrency::MoneyToString($deal['OPPORTUNITY'], $deal['CURRENCY_ID'], '#') . ' ' . $deal['CURRENCY_ID'];
                     }
                     $opportunity = str_replace('.00', '', $opportunity);
                     $arResult['DEALS'][$deal['ID']] = array('ID' => $deal['ID'], 'TITLE' => $deal['TITLE'], 'STAGE' => $dealStatuses[$deal['STAGE_ID']]['NAME'], 'STAGE_COLOR' => $dealStatuses[$deal['STAGE_ID']]['COLOR'] ? $dealStatuses[$deal['STAGE_ID']]['COLOR'] : "#5fa0ce", 'OPPORTUNITY' => $opportunity, 'URL' => $deal['SHOW_URL']);
                 }
                 if (!empty($arResult['DEALS'])) {
                     $arResult['DEALS'] = array_values($arResult['DEALS']);
                 }
             }
         }
     } else {
         $arResult = array('FOUND' => 'N');
         $userPermissions = CCrmPerms::GetUserPermissions($userId);
         if (CCrmLead::CheckCreatePermission($userPermissions)) {
             $arResult['LEAD_URL'] = CCrmOwnerType::GetEditUrl(CCrmOwnerType::Lead, 0);
             if ($arResult['LEAD_URL'] !== '') {
                 $arResult['LEAD_URL'] = CCrmUrlUtil::AddUrlParams($arResult['LEAD_URL'], array("phone" => (string) $phone, 'origin_id' => 'VI_' . $callId));
             }
         }
         if (CCrmContact::CheckCreatePermission($userPermissions)) {
             $arResult['CONTACT_URL'] = CCrmOwnerType::GetEditUrl(CCrmOwnerType::Contact, 0);
             if ($arResult['CONTACT_URL'] !== '') {
                 $arResult['CONTACT_URL'] = CCrmUrlUtil::AddUrlParams($arResult['CONTACT_URL'], array("phone" => (string) $phone, 'origin_id' => 'VI_' . $callId));
             }
         }
     }
     return $arResult;
 }
Beispiel #12
0
 public static function findByPhoneNumber($number, $params = array())
 {
     if (!is_string($number)) {
         throw new \Bitrix\Main\ArgumentTypeException('number', 'string');
     }
     if ($number === '') {
         throw new \Bitrix\Main\ArgumentException('Is empty', 'number');
     }
     if (!is_array($params)) {
         $params = array();
     }
     $userID = isset($params['USER_ID']) ? intval($params['USER_ID']) : 0;
     if ($userID <= 0) {
         $userID = CCrmPerms::GetCurrentUserID();
     }
     $isAdmin = CCrmPerms::IsAdmin($userID);
     $userPermissions = CCrmPerms::GetUserPermissions($userID);
     $enableExtendedMode = isset($params['ENABLE_EXTENDED_MODE']) ? (bool) $params['ENABLE_EXTENDED_MODE'] : true;
     $contactFormID = isset($params['CONTACT_FORM_ID']) ? intval($params['CONTACT_FORM_ID']) : '';
     if ($contactFormID === '') {
         $contactFormID = CCrmContact::DEFAULT_FORM_ID;
     }
     $dups = array();
     $criterion = new \Bitrix\Crm\Integrity\DuplicateCommunicationCriterion('PHONE', $number);
     $entityTypes = array(CCrmOwnerType::Contact, CCrmOwnerType::Company, CCrmOwnerType::Lead);
     foreach ($entityTypes as $entityType) {
         $duplicate = $criterion->find($entityType, 1);
         if ($duplicate !== null) {
             $dups[] = $duplicate;
         }
     }
     $entityByType = array();
     foreach ($dups as &$dup) {
         /** @var \Bitrix\Crm\Integrity\Duplicate $dup */
         $entities = $dup->getEntities();
         if (!(is_array($entities) && !empty($entities))) {
             continue;
         }
         //Each entity type limited by 50 items
         foreach ($entities as &$entity) {
             /** @var \Bitrix\Crm\Integrity\DuplicateEntity $entity */
             $entityTypeID = $entity->getEntityTypeID();
             $entityID = $entity->getEntityID();
             $fields = null;
             if ($entityTypeID === CCrmOwnerType::Contact) {
                 $dbEntity = CCrmContact::GetListEx(array(), array('=ID' => $entityID, 'CHECK_PERMISSIONS' => 'N'), false, false, array('ID', 'HONORIFIC', 'NAME', 'SECOND_NAME', 'LAST_NAME', 'PHOTO', 'POST', 'COMPANY_ID', 'COMPANY_TITLE', 'ASSIGNED_BY_ID'));
                 $entityFields = is_object($dbEntity) ? $dbEntity->Fetch() : null;
                 if (is_array($entityFields)) {
                     $formattedName = CCrmContact::PrepareFormattedName(array('HONORIFIC' => isset($entityFields['HONORIFIC']) ? $entityFields['HONORIFIC'] : '', 'NAME' => isset($entityFields['NAME']) ? $entityFields['NAME'] : '', 'SECOND_NAME' => isset($entityFields['SECOND_NAME']) ? $entityFields['SECOND_NAME'] : '', 'LAST_NAME' => isset($entityFields['LAST_NAME']) ? $entityFields['LAST_NAME'] : ''));
                     $fields = array('ID' => intval($entityFields['ID']), 'FORMATTED_NAME' => $formattedName, 'PHOTO' => isset($entityFields['PHOTO']) ? intval($entityFields['PHOTO']) : 0, 'COMPANY_ID' => isset($entityFields['COMPANY_ID']) ? intval($entityFields['COMPANY_ID']) : 0, 'COMPANY_TITLE' => isset($entityFields['COMPANY_TITLE']) ? $entityFields['COMPANY_TITLE'] : '', 'POST' => isset($entityFields['POST']) ? $entityFields['POST'] : '', 'ASSIGNED_BY_ID' => isset($entityFields['ASSIGNED_BY_ID']) ? intval($entityFields['ASSIGNED_BY_ID']) : 0, 'CAN_READ' => CCrmContact::CheckReadPermission($entityID, $userPermissions));
                     if ($fields['CAN_READ'] && $enableExtendedMode) {
                         $deals = array();
                         $dbDeal = CCrmDeal::GetListEx(array('BEGINDATE' => 'ASC'), array('=CONTACT_ID' => $entityID, 'CLOSED' => 'N', 'CHECK_PERMISSIONS' => $isAdmin ? 'N' : 'Y'), false, array('nTopCount' => 2), array('ID', 'TITLE', 'STAGE_ID'), array('PERMS' => $userPermissions));
                         if (is_object($dbDeal)) {
                             while ($dealFields = $dbDeal->Fetch()) {
                                 $dealID = intval($dealFields['ID']);
                                 //$dealFields['CAN_READ'] = CCrmDeal::CheckReadPermission($dealID, $userPermissions);
                                 $dealFields['SHOW_URL'] = CCrmOwnerType::GetShowUrl(CCrmOwnerType::Deal, $dealID);
                                 $deals[] = $dealFields;
                             }
                         }
                         $fields['DEALS'] =& $deals;
                         unset($deals);
                     }
                 }
             } elseif ($entityTypeID === CCrmOwnerType::Company) {
                 $dbEntity = CCrmCompany::GetListEx(array(), array('=ID' => $entityID, 'CHECK_PERMISSIONS' => 'N'), false, false, array('ID', 'TITLE', 'LOGO', 'ASSIGNED_BY_ID'));
                 $entityFields = is_object($dbEntity) ? $dbEntity->Fetch() : null;
                 if (is_array($entityFields)) {
                     $fields = array('ID' => intval($entityFields['ID']), 'TITLE' => isset($entityFields['TITLE']) ? $entityFields['TITLE'] : '', 'LOGO' => isset($entityFields['LOGO']) ? intval($entityFields['LOGO']) : 0, 'ASSIGNED_BY_ID' => isset($entityFields['ASSIGNED_BY_ID']) ? intval($entityFields['ASSIGNED_BY_ID']) : 0, 'CAN_READ' => CCrmCompany::CheckReadPermission($entityID, $userPermissions));
                     if ($fields['CAN_READ'] && $enableExtendedMode) {
                         $deals = array();
                         $dbDeal = CCrmDeal::GetListEx(array('BEGINDATE' => 'ASC'), array('=COMPANY_ID' => $entityID, 'CLOSED' => 'N', 'CHECK_PERMISSIONS' => $isAdmin ? 'N' : 'Y'), false, array('nTopCount' => 2), array('ID', 'TITLE', 'STAGE_ID'), array('PERMS' => $userPermissions));
                         if (is_object($dbDeal)) {
                             while ($dealFields = $dbDeal->Fetch()) {
                                 $dealID = intval($dealFields['ID']);
                                 //$dealFields['CAN_READ'] = CCrmDeal::CheckReadPermission($dealID, $userPermissions);
                                 $dealFields['SHOW_URL'] = CCrmOwnerType::GetShowUrl(CCrmOwnerType::Deal, $dealID);
                                 $deals[] = $dealFields;
                             }
                         }
                         $fields['DEALS'] =& $deals;
                         unset($deals);
                     }
                 }
             } elseif ($entityTypeID === CCrmOwnerType::Lead) {
                 $dbEntity = CCrmLead::GetListEx(array(), array('=ID' => $entityID, 'CHECK_PERMISSIONS' => 'N'), false, false, array('ID', 'TITLE', 'HONORIFIC', 'NAME', 'SECOND_NAME', 'LAST_NAME', 'POST', 'COMPANY_TITLE', 'ASSIGNED_BY_ID'));
                 $entityFields = is_object($dbEntity) ? $dbEntity->Fetch() : null;
                 if (is_array($entityFields)) {
                     $formattedName = '';
                     if (!empty($entityFields['NAME']) || !empty($entityFields['SECOND_NAME']) || !empty($entityFields['LAST_NAME'])) {
                         $formattedName = CCrmLead::PrepareFormattedName(array('HONORIFIC' => isset($entityFields['HONORIFIC']) ? $entityFields['HONORIFIC'] : '', 'NAME' => isset($entityFields['NAME']) ? $entityFields['NAME'] : '', 'SECOND_NAME' => isset($entityFields['SECOND_NAME']) ? $entityFields['SECOND_NAME'] : '', 'LAST_NAME' => isset($entityFields['LAST_NAME']) ? $entityFields['LAST_NAME'] : ''));
                     }
                     $fields = array('ID' => intval($entityFields['ID']), 'TITLE' => isset($entityFields['TITLE']) ? $entityFields['TITLE'] : '', 'FORMATTED_NAME' => $formattedName, 'COMPANY_TITLE' => isset($entityFields['COMPANY_TITLE']) ? $entityFields['COMPANY_TITLE'] : '', 'POST' => isset($entityFields['POST']) ? $entityFields['POST'] : '', 'ASSIGNED_BY_ID' => isset($entityFields['ASSIGNED_BY_ID']) ? intval($entityFields['ASSIGNED_BY_ID']) : 0, 'CAN_READ' => CCrmLead::CheckReadPermission($entityID, $userPermissions));
                 }
             }
             if (!is_array($fields)) {
                 continue;
             }
             if ($fields['CAN_READ'] && $enableExtendedMode) {
                 $showUrl = $fields['SHOW_URL'] = CCrmOwnerType::GetShowUrl($entityTypeID, $entityID);
                 if ($showUrl !== '') {
                     $fields['ACTIVITY_LIST_URL'] = CCrmUrlUtil::AddUrlParams($showUrl, array("{$contactFormID}_active_tab" => 'tab_activity'));
                     $fields['INVOICE_LIST_URL'] = CCrmUrlUtil::AddUrlParams($showUrl, array("{$contactFormID}_active_tab" => 'tab_invoice'));
                     if ($entityTypeID === CCrmOwnerType::Contact || $entityTypeID === CCrmOwnerType::Company) {
                         $fields['DEAL_LIST_URL'] = CCrmUrlUtil::AddUrlParams($showUrl, array("{$contactFormID}_active_tab" => 'tab_deal'));
                     }
                 }
                 $activities = array();
                 $dbActivity = CCrmActivity::GetList(array('DEADLINE' => 'ASC'), array('COMPLETED' => 'N', 'BINDINGS' => array(array('OWNER_TYPE_ID' => $entityTypeID, 'OWNER_ID' => $entityID)), 'CHECK_PERMISSIONS' => $isAdmin ? 'N' : 'Y'), false, array('nTopCount' => 4), array('ID', 'SUBJECT', 'START_TIME', 'END_TIME', 'DEADLINE'), array('PERMS' => $userPermissions));
                 if (is_object($dbActivity)) {
                     while ($activityFields = $dbActivity->Fetch()) {
                         $activityFields['SHOW_URL'] = CCrmOwnerType::GetShowUrl(CCrmOwnerType::Activity, $activityFields['ID']);
                         $activities[] =& $activityFields;
                         unset($activityFields);
                     }
                 }
                 $fields['ACTIVITIES'] =& $activities;
                 unset($activities);
             }
             $entityTypeName = CCrmOwnerType::ResolveName($entityTypeID);
             if (!isset($entityByType[$entityTypeName])) {
                 $entityByType[$entityTypeName] = array($fields);
             } elseif (!in_array($entityID, $entityByType[$entityTypeName], true)) {
                 $entityByType[$entityTypeName][] = $fields;
             }
         }
     }
     unset($dup);
     return $entityByType;
 }
Beispiel #13
0
 public function Add($arFields, &$arRecalculated = false, $siteId = SITE_ID, $options = array())
 {
     /** @global \CDatabase $DB */
     global $DB;
     if (!CModule::IncludeModule('sale')) {
         return false;
     }
     if (!is_array($options)) {
         $options = array();
     }
     $bRecalculate = is_array($arRecalculated);
     $orderID = false;
     $tmpOrderId = intval($arFields['ID']) <= 0 ? 0 : $arFields['ID'];
     if (isset($arFields['ID'])) {
         unset($arFields['ID']);
     }
     $arPrevOrder = $tmpOrderId !== 0 ? CCrmInvoice::GetByID($tmpOrderId) : null;
     $userId = CCrmSecurityHelper::GetCurrentUserID();
     if (!isset($arFields['RESPONSIBLE_ID']) || (int) $arFields['RESPONSIBLE_ID'] <= 0) {
         if (is_array($arPrevOrder) && isset($arPrevOrder['RESPONSIBLE_ID']) && intval($arPrevOrder['RESPONSIBLE_ID']) > 0) {
             $arFields['RESPONSIBLE_ID'] = $arPrevOrder['RESPONSIBLE_ID'];
         } else {
             $arFields['RESPONSIBLE_ID'] = $userId;
         }
     }
     $orderStatus = '';
     if (isset($arFields['STATUS_ID'])) {
         $orderStatus = $arFields['STATUS_ID'];
         unset($arFields['STATUS_ID']);
     }
     // prepare entity permissions
     $arAttr = array();
     if (!empty($arFields['OPENED'])) {
         $arAttr['OPENED'] = $arFields['OPENED'];
     }
     $sPermission = $tmpOrderId > 0 ? 'WRITE' : 'ADD';
     if ($this->bCheckPermission) {
         $arEntityAttr = self::BuildEntityAttr($userId, $arAttr);
         $userPerms = $userId == CCrmPerms::GetCurrentUserID() ? $this->cPerms : CCrmPerms::GetUserPermissions($userId);
         $sEntityPerm = $userPerms->GetPermType('INVOICE', $sPermission, $arEntityAttr);
         if ($sEntityPerm == BX_CRM_PERM_NONE) {
             $this->LAST_ERROR = GetMessage('CRM_PERMISSION_DENIED');
             $GLOBALS['APPLICATION']->ThrowException($this->LAST_ERROR);
             return false;
         }
         $responsibleID = intval($arFields['RESPONSIBLE_ID']);
         if ($sEntityPerm == BX_CRM_PERM_SELF && $responsibleID != $userId) {
             $arFields['RESPONSIBLE_ID'] = $userId;
         }
         if ($sEntityPerm == BX_CRM_PERM_OPEN && $userId == $responsibleID) {
             $arFields['OPENED'] = 'Y';
         }
     }
     $responsibleID = intval($arFields['RESPONSIBLE_ID']);
     $arEntityAttr = self::BuildEntityAttr($responsibleID, $arAttr);
     $userPerms = $responsibleID == CCrmPerms::GetCurrentUserID() ? $this->cPerms : CCrmPerms::GetUserPermissions($responsibleID);
     $sEntityPerm = $userPerms->GetPermType('INVOICE', $sPermission, $arEntityAttr);
     $this->PrepareEntityAttrs($arEntityAttr, $sEntityPerm);
     // date fields
     if ($tmpOrderId === 0) {
         $arFields['~DATE_BILL'] = $DB->CharToDateFunction(isset($arFields['DATE_BILL']) && $arFields['DATE_BILL'] !== '' ? $arFields['DATE_BILL'] : ConvertTimeStamp(time(), 'SHORT', SITE_ID), 'SHORT', false);
     } else {
         if (isset($arFields['DATE_BILL']) && $arFields['DATE_BILL'] !== '') {
             $arFields['~DATE_BILL'] = $DB->CharToDateFunction($arFields['DATE_BILL'], 'SHORT', false);
         }
     }
     unset($arFields['DATE_BILL']);
     if (isset($arFields['DATE_PAY_BEFORE']) && $arFields['DATE_PAY_BEFORE'] !== '') {
         $arFields['~DATE_PAY_BEFORE'] = $DB->CharToDateFunction($arFields['DATE_PAY_BEFORE'], 'SHORT', false);
     }
     unset($arFields['DATE_PAY_BEFORE']);
     if ($tmpOrderId !== 0 && !isset($arFields['PRODUCT_ROWS']) && !isset($arFields['INVOICE_PROPERTIES'])) {
         if (!is_array($arPrevOrder)) {
             return false;
         }
         $prevResponsibleID = isset($arPrevOrder['RESPONSIBLE_ID']) ? intval($arPrevOrder['RESPONSIBLE_ID']) : 0;
         $responsibleID = isset($arFields['RESPONSIBLE_ID']) ? intval($arFields['RESPONSIBLE_ID']) : 0;
         $prevStatusID = isset($arPrevOrder['STATUS_ID']) ? $arPrevOrder['STATUS_ID'] : '';
         // simple update order fields
         $CSaleOrder = new CSaleOrder();
         $orderID = $CSaleOrder->Update($tmpOrderId, $arFields);
         CCrmEntityHelper::NormalizeUserFields($arFields, self::$sUFEntityID, $GLOBALS['USER_FIELD_MANAGER'], array('IS_NEW' => false));
         $GLOBALS['USER_FIELD_MANAGER']->Update(self::$sUFEntityID, $tmpOrderId, $arFields);
         $registerSonetEvent = isset($options['REGISTER_SONET_EVENT']) && $options['REGISTER_SONET_EVENT'] === true;
         if (is_int($orderID) && $orderID > 0) {
             if ($registerSonetEvent) {
                 $newDealID = isset($arFields['UF_DEAL_ID']) ? intval($arFields['UF_DEAL_ID']) : 0;
                 $oldDealID = isset($arPrevOrder['UF_DEAL_ID']) ? intval($arPrevOrder['UF_DEAL_ID']) : 0;
                 $newCompanyID = isset($arFields['UF_COMPANY_ID']) ? intval($arFields['UF_COMPANY_ID']) : 0;
                 $oldCompanyID = isset($arPrevOrder['UF_COMPANY_ID']) ? intval($arPrevOrder['UF_COMPANY_ID']) : 0;
                 $newContactID = isset($arFields['UF_CONTACT_ID']) ? intval($arFields['UF_CONTACT_ID']) : 0;
                 $oldContactID = isset($arPrevOrder['UF_CONTACT_ID']) ? intval($arPrevOrder['UF_CONTACT_ID']) : 0;
                 $parents = array();
                 $parentsChanged = $newDealID !== $oldDealID || $newCompanyID !== $oldCompanyID || $newContactID !== $oldContactID;
                 if ($parentsChanged) {
                     if ($newDealID > 0) {
                         $parents[] = array('ENTITY_TYPE_ID' => CCrmOwnerType::Deal, 'ENTITY_ID' => $newDealID);
                     }
                     if ($newCompanyID > 0) {
                         $parents[] = array('ENTITY_TYPE_ID' => CCrmOwnerType::Company, 'ENTITY_ID' => $newCompanyID);
                     }
                     if ($newContactID > 0) {
                         $parents[] = array('ENTITY_TYPE_ID' => CCrmOwnerType::Contact, 'ENTITY_ID' => $newContactID);
                     }
                 }
                 $oldOrderStatus = isset($arPrevOrder['STATUS_ID']) ? $arPrevOrder['STATUS_ID'] : '';
                 self::SynchronizeLiveFeedEvent($orderID, array('PROCESS_PARENTS' => $parentsChanged, 'PARENTS' => $parents, 'REFRESH_DATE' => $orderStatus !== $oldOrderStatus, 'START_RESPONSIBLE_ID' => $prevResponsibleID, 'FINAL_RESPONSIBLE_ID' => $responsibleID, 'TOPIC' => isset($arPrevOrder['ORDER_TOPIC']) ? $arPrevOrder['ORDER_TOPIC'] : $orderID));
             }
             if ($responsibleID !== $prevResponsibleID) {
                 CCrmSonetSubscription::ReplaceSubscriptionByEntity(CCrmOwnerType::Invoice, $orderID, CCrmSonetSubscriptionType::Responsibility, $responsibleID, $prevResponsibleID, $registerSonetEvent);
             }
         }
     } else {
         // check product rows
         if (!isset($arFields['PRODUCT_ROWS']) || !is_array($arFields['PRODUCT_ROWS']) || count($arFields['PRODUCT_ROWS']) <= 0) {
             return false;
         }
         $arProduct = $arFields['PRODUCT_ROWS'];
         // prepare shopping cart data
         // <editor-fold defaultstate="collapsed" desc="prepare shopping cart data ...">
         // get xml_id fields
         $catalogXmlId = CCrmCatalog::GetDefaultCatalogXmlId();
         $arNewProducts = array();
         $bGetBasketXmlIds = false;
         foreach ($arProduct as &$productRow) {
             if (isset($productRow['ID']) && intval($productRow['ID']) === 0 && isset($productRow['PRODUCT_ID'])) {
                 $arNewProducts[] = $productRow['PRODUCT_ID'];
             } else {
                 $bGetBasketXmlIds = true;
             }
         }
         unset($productRow);
         $arXmlIds = array();
         $oldProductRows = null;
         if ($bGetBasketXmlIds && intval($tmpOrderId) > 0) {
             $oldProductRows = CCrmInvoice::GetProductRows($tmpOrderId);
             if (count($oldProductRows) > 0) {
                 foreach ($oldProductRows as $row) {
                     $arXmlIds[intval($row['ID'])][$row['PRODUCT_ID']] = array('CATALOG_XML_ID' => $row['CATALOG_XML_ID'], 'PRODUCT_XML_ID' => $row['PRODUCT_XML_ID']);
                 }
                 unset($row);
             }
         }
         unset($bGetBasketXmlIds);
         if (count($arNewProducts) > 0) {
             $dbRes = CCrmProduct::GetList(array(), array('ID' => $arNewProducts), array('ID', 'XML_ID'));
             while ($row = $dbRes->Fetch()) {
                 $arXmlIds[0][$row['ID']] = array('CATALOG_XML_ID' => $catalogXmlId, 'PRODUCT_XML_ID' => $row['XML_ID']);
             }
             unset($dbRes, $row);
         }
         unset($arNewProducts, $arOldProducts);
         // products without measures
         $productMeasures = array();
         $productId = 0;
         $productIds = array();
         foreach ($arProduct as $productRow) {
             $productId = intval($productRow['PRODUCT_ID']);
             if ($productId > 0 && (!array_key_exists('MEASURE_CODE', $productRow) || intval($productRow['MEASURE_CODE']) <= 0)) {
                 $productIds[] = $productId;
             }
         }
         unset($productId, $productRow);
         if (count($productIds) > 0) {
             $productMeasures = \Bitrix\Crm\Measure::getProductMeasures($productIds);
         }
         unset($productIds);
         $currencyId = CCrmInvoice::GetCurrencyID($siteId);
         $i = 0;
         $defaultMeasure = null;
         $oldProductRowsById = null;
         foreach ($arProduct as &$productRow) {
             $productXmlId = $catalogXmlId = null;
             $rowIndex = intval($productRow['ID']);
             $productId = $productRow['PRODUCT_ID'];
             $isCustomized = isset($productRow['CUSTOMIZED']) && $productRow['CUSTOMIZED'] === 'Y';
             $productRow['MODULE'] = $productRow['PRODUCT_PROVIDER_CLASS'] = '';
             if ($productId > 0) {
                 if (!$isCustomized) {
                     $productRow['MODULE'] = 'catalog';
                     $productRow['PRODUCT_PROVIDER_CLASS'] = 'CCatalogProductProvider';
                 }
                 if (is_array($arXmlIds[$rowIndex]) && isset($arXmlIds[$rowIndex][$productId])) {
                     $catalogXmlId = $arXmlIds[$rowIndex][$productId]['CATALOG_XML_ID'];
                     $productXmlId = $arXmlIds[$rowIndex][$productId]['PRODUCT_XML_ID'];
                 }
                 $productRow['CATALOG_XML_ID'] = $catalogXmlId;
                 $productRow['PRODUCT_XML_ID'] = $productXmlId;
             } else {
                 $productRow["PRODUCT_XML_ID"] = "CRM-" . randString(8);
                 $ri = new \Bitrix\Main\Type\RandomSequence($productRow["PRODUCT_XML_ID"]);
                 $productRow["PRODUCT_ID"] = $ri->rand(1000000, 9999999);
                 $productRow['CATALOG_XML_ID'] = '';
             }
             if ($isCustomized) {
                 $productRow['CUSTOM_PRICE'] = 'Y';
             }
             if (isset($productRow['PRODUCT_NAME'])) {
                 $productRow['NAME'] = $productRow['PRODUCT_NAME'];
                 unset($productRow['PRODUCT_NAME']);
             }
             if (isset($productRow['PRICE'])) {
                 $productRow['PRICE_DEFAULT'] = $productRow['PRICE'];
             }
             if (!isset($productRow['CURRENCY'])) {
                 $productRow['CURRENCY'] = $currencyId;
             }
             // measures
             $bRefreshMeasureName = false;
             if (!array_key_exists('MEASURE_CODE', $productRow) || intval($productRow['MEASURE_CODE'] <= 0)) {
                 if ($oldProductRows === null && $tmpOrderId > 0) {
                     $oldProductRows = CCrmInvoice::GetProductRows($tmpOrderId);
                 }
                 if (is_array($oldProductRows) && count($oldProductRows) > 0 && $oldProductRowsById === null) {
                     $oldProductRowsById = array();
                     foreach ($oldProductRows as $row) {
                         $oldProductRowsById[intval($row['ID'])] = $row;
                     }
                     unset($row);
                 }
                 if (is_array($oldProductRowsById) && isset($oldProductRowsById[$rowIndex])) {
                     $row = $oldProductRowsById[$rowIndex];
                     if (intval($productId) === intval($row['PRODUCT_ID'])) {
                         if (isset($row['MEASURE_CODE'])) {
                             $productRow['MEASURE_CODE'] = $row['MEASURE_CODE'];
                         }
                         if (isset($row['MEASURE_NAME'])) {
                             $productRow['MEASURE_NAME'] = $row['MEASURE_NAME'];
                         } else {
                             $bRefreshMeasureName = true;
                         }
                         unset($row);
                     }
                 }
             }
             if (!isset($productRow['MEASURE_CODE']) || intval($productRow['MEASURE_CODE']) <= 0) {
                 if ($productId > 0 && isset($productMeasures[$productId])) {
                     $measure = is_array($productMeasures[$productId][0]) ? $productMeasures[$productId][0] : null;
                     if (is_array($measure)) {
                         if (isset($measure['CODE'])) {
                             $productRow['MEASURE_CODE'] = $measure['CODE'];
                         }
                         if (isset($measure['SYMBOL'])) {
                             $productRow['MEASURE_NAME'] = $measure['SYMBOL'];
                         }
                     }
                     unset($measure);
                 }
             }
             if (!isset($productRow['MEASURE_CODE']) || intval($productRow['MEASURE_CODE']) <= 0) {
                 if ($defaultMeasure === null) {
                     $defaultMeasure = \Bitrix\Crm\Measure::getDefaultMeasure();
                 }
                 if (is_array($defaultMeasure)) {
                     $productRow['MEASURE_CODE'] = $defaultMeasure['CODE'];
                     $productRow['MEASURE_NAME'] = $defaultMeasure['SYMBOL'];
                 }
             }
             if (isset($productRow['MEASURE_CODE']) && intval($productRow['MEASURE_CODE']) > 0 && ($bRefreshMeasureName || !array_key_exists('MEASURE_NAME', $productRow) || empty($productRow['MEASURE_NAME']))) {
                 $measure = \Bitrix\Crm\Measure::getMeasureByCode($productRow['MEASURE_CODE']);
                 if (is_array($measure) && isset($measure['SYMBOL'])) {
                     $productRow['MEASURE_NAME'] = $measure['SYMBOL'];
                 }
                 unset($measure);
             }
             $i++;
         }
         unset($productRow, $productMeasures, $catalogXmlId, $productXmlId);
         $arOrderProductPrice = self::__fGetUserShoppingCart($arProduct, $siteId, 'N');
         foreach ($arOrderProductPrice as &$arItem) {
             $arItem["ID_TMP"] = $arItem["ID"];
             $arItem["NAME_TMP"] = $arItem["NAME"];
             unset($arItem["ID"]);
         }
         unset($arItem);
         // user id for order
         $saleUserId = intval(CSaleUser::GetAnonymousUserID());
         if ($saleUserId <= 0) {
             return false;
         }
         $arErrors = array();
         $arShoppingCart = CSaleBasket::DoGetUserShoppingCart($siteId, $saleUserId, $arOrderProductPrice, $arErrors, array(), $tmpOrderId);
         if (!is_array($arShoppingCart) || count($arShoppingCart) === 0) {
             $GLOBALS['APPLICATION']->ThrowException(GetMessage('CRM_ERROR_EMPTY_INVOICE_SPEC'));
             return false;
         }
         foreach ($arShoppingCart as $key => &$arItem) {
             $arItem["ID"] = $arItem["ID_TMP"];
             $arItem["NAME"] = $arItem["NAME_TMP"];
             unset($arItem["NAME_TMP"], $arItem["ID_TMP"]);
             //$arShoppingCart[$key]["ID"] = $arItem["ID"];
         }
         unset($key, $arItem);
         // </editor-fold>
         // person type
         $personTypeId = 0;
         if (!isset($arFields['PERSON_TYPE_ID']) || intval($arFields['PERSON_TYPE_ID']) <= 0) {
             $arPersonTypes = CCrmPaySystem::getPersonTypeIDs();
             if (isset($arPersonTypes['CONTACT'])) {
                 $personTypeId = intval($arPersonTypes['CONTACT']);
             }
         } else {
             $personTypeId = $arFields['PERSON_TYPE_ID'];
         }
         if ($personTypeId <= 0) {
             return false;
         }
         // preparing order to save
         // <editor-fold defaultstate="collapsed" desc="preparing order to save ...">
         $arOrderPropsValues = array();
         if (isset($arFields['INVOICE_PROPERTIES']) && is_array($arFields['INVOICE_PROPERTIES']) && count($arFields['INVOICE_PROPERTIES']) > 0) {
             $arOrderPropsValues = $arFields['INVOICE_PROPERTIES'];
         }
         if (isset($arFields['INVOICE_PROPERTIES'])) {
             unset($arFields['INVOICE_PROPERTIES']);
         }
         if (count($arOrderPropsValues) <= 0) {
             return false;
         }
         $deliveryId = null;
         $paySystemId = $arFields['PAY_SYSTEM_ID'];
         $arOptions = array('LOCATION_IN_CODES' => true);
         // let DoCalculateOrder know we send location in CODEs
         $arErrors = $arWarnings = array();
         $CSaleOrder = new CSaleOrder();
         $arOrder = $CSaleOrder->DoCalculateOrder($siteId, $saleUserId, $arShoppingCart, $personTypeId, $arOrderPropsValues, $deliveryId, $paySystemId, $arOptions, $arErrors, $arWarnings);
         if (count($arOrder) <= 0) {
             return false;
         }
         // </editor-fold>
         if ($bRecalculate) {
             foreach ($arOrder as $k => $v) {
                 $arRecalculated[$k] = $v;
             }
             return true;
         }
         // merge order fields
         $arAdditionalFields = array();
         foreach ($arFields as $k => $v) {
             if ($k === 'PRODUCT_ROWS') {
                 continue;
             }
             $arAdditionalFields[$k] = $v;
         }
         $arOrder['LOCATION_IN_CODES'] = true;
         // let DoSaveOrder know we send location in IDs
         // saving order
         $arErrors = array();
         $orderID = $CSaleOrder->DoSaveOrder($arOrder, $arAdditionalFields, $tmpOrderId, $arErrors);
         if (is_int($orderID) && $orderID > 0) {
             CCrmEntityHelper::NormalizeUserFields($arFields, self::$sUFEntityID, $GLOBALS['USER_FIELD_MANAGER'], array('IS_NEW' => $tmpOrderId === 0));
             $GLOBALS['USER_FIELD_MANAGER']->Update(self::$sUFEntityID, $orderID, $arFields);
         }
         if (is_int($orderID) && $orderID > 0 && isset($options['REGISTER_SONET_EVENT']) && $options['REGISTER_SONET_EVENT'] === true) {
             $prevResponsibleID = is_array($arPrevOrder) && isset($arPrevOrder['RESPONSIBLE_ID']) ? intval($arPrevOrder['RESPONSIBLE_ID']) : 0;
             $responsibleID = isset($arFields['RESPONSIBLE_ID']) ? intval($arFields['RESPONSIBLE_ID']) : 0;
             if ($tmpOrderId <= 0) {
                 self::RegisterLiveFeedEvent($arFields, $orderID, $userId);
                 if ($responsibleID > 0) {
                     CCrmSonetSubscription::RegisterSubscription(CCrmOwnerType::Invoice, $orderID, CCrmSonetSubscriptionType::Responsibility, $responsibleID);
                 }
             } else {
                 $newDealID = isset($arFields['UF_DEAL_ID']) ? intval($arFields['UF_DEAL_ID']) : 0;
                 $oldDealID = isset($arPrevOrder['UF_DEAL_ID']) ? intval($arPrevOrder['UF_DEAL_ID']) : 0;
                 $newCompanyID = isset($arFields['UF_COMPANY_ID']) ? intval($arFields['UF_COMPANY_ID']) : 0;
                 $oldCompanyID = isset($arPrevOrder['UF_COMPANY_ID']) ? intval($arPrevOrder['UF_COMPANY_ID']) : 0;
                 $newContactID = isset($arFields['UF_CONTACT_ID']) ? intval($arFields['UF_CONTACT_ID']) : 0;
                 $oldContactID = isset($arPrevOrder['UF_CONTACT_ID']) ? intval($arPrevOrder['UF_CONTACT_ID']) : 0;
                 $parents = array();
                 $parentsChanged = $newDealID !== $oldDealID || $newCompanyID !== $oldCompanyID || $newContactID !== $oldContactID;
                 if ($parentsChanged) {
                     if ($newDealID > 0) {
                         $parents[] = array('ENTITY_TYPE_ID' => CCrmOwnerType::Deal, 'ENTITY_ID' => $newDealID);
                     }
                     if ($newCompanyID > 0) {
                         $parents[] = array('ENTITY_TYPE_ID' => CCrmOwnerType::Company, 'ENTITY_ID' => $newCompanyID);
                     }
                     if ($newContactID > 0) {
                         $parents[] = array('ENTITY_TYPE_ID' => CCrmOwnerType::Contact, 'ENTITY_ID' => $newContactID);
                     }
                 }
                 $oldOrderStatus = isset($arPrevOrder['STATUS_ID']) ? $arPrevOrder['STATUS_ID'] : '';
                 self::SynchronizeLiveFeedEvent($orderID, array('PROCESS_PARENTS' => $parentsChanged, 'PARENTS' => $parents, 'REFRESH_DATE' => $orderStatus !== $oldOrderStatus, 'START_RESPONSIBLE_ID' => $prevResponsibleID, 'FINAL_RESPONSIBLE_ID' => $responsibleID, 'TOPIC' => isset($arPrevOrder['ORDER_TOPIC']) ? $arPrevOrder['ORDER_TOPIC'] : $orderID));
                 if ($responsibleID !== $prevResponsibleID) {
                     CCrmSonetSubscription::ReplaceSubscriptionByEntity(CCrmOwnerType::Invoice, $orderID, CCrmSonetSubscriptionType::Responsibility, $responsibleID, $prevResponsibleID, true);
                 }
             }
         }
     }
     if (intval($orderID) > 0 && !empty($orderStatus)) {
         // set status
         $this->SetStatus($orderID, $orderStatus);
         // update entity permissions
         CCrmPerms::UpdateEntityAttr('INVOICE', $orderID, $arEntityAttr);
         $newDealID = isset($arFields['UF_DEAL_ID']) ? (int) $arFields['UF_DEAL_ID'] : 0;
         $oldDealID = is_array($arPrevOrder) && isset($arPrevOrder['UF_DEAL_ID']) ? (int) $arPrevOrder['UF_DEAL_ID'] : 0;
         if ($newDealID) {
             Bitrix\Crm\Statistics\DealInvoiceStatisticEntry::register($newDealID);
         }
         if ($oldDealID > 0 && $oldDealID !== $newDealID) {
             Bitrix\Crm\Statistics\DealInvoiceStatisticEntry::register($oldDealID);
         }
         if (isset($options['UPDATE_SEARCH']) && $options['UPDATE_SEARCH'] === true) {
             $arFilterTmp = array('ID' => $orderID);
             if (!$this->bCheckPermission) {
                 $arFilterTmp["CHECK_PERMISSIONS"] = "N";
             }
             CCrmSearch::UpdateSearch($arFilterTmp, 'INVOICE', true);
         }
     }
     return $orderID;
 }
 public static function getRegisteredCodes($entityTypeID, $entityID, $enablePermissionCheck = false, $userID = 0, $limit = 50)
 {
     if (!is_int($entityTypeID)) {
         throw new Main\ArgumentTypeException('entityTypeID', 'integer');
     }
     if (!is_int($entityID)) {
         throw new Main\ArgumentTypeException('entityID', 'integer');
     }
     if (!is_int($userID)) {
         throw new Main\ArgumentTypeException('userID', 'integer');
     }
     if (!is_bool($enablePermissionCheck)) {
         throw new Main\ArgumentTypeException('enablePermissionCheck', 'boolean');
     }
     if (!is_int($limit)) {
         throw new Main\ArgumentTypeException('limit', 'integer');
     }
     $query = new Main\Entity\Query(DuplicateCommunicationMatchCodeTable::getEntity());
     $query->addSelect('TYPE');
     $query->addSelect('VALUE');
     $query->addFilter('=ENTITY_TYPE_ID', $entityTypeID);
     $query->addFilter('=ENTITY_ID', $entityID);
     if ($enablePermissionCheck && $userID > 0) {
         $permissions = isset($params['PERMISSIONS']) ? $params['PERMISSIONS'] : null;
         if ($permissions === null) {
             $permissions = \CCrmPerms::GetUserPermissions($userID);
         }
         $permissionSql = \CCrmPerms::BuildSql(\CCrmOwnerType::ResolveName($entityTypeID), '', 'READ', array('RAW_QUERY' => true, 'PERMS' => $permissions));
         if ($permissionSql === false) {
             //Access denied;
             return array();
         } elseif ($permissionSql !== '') {
             $query->addFilter('@ENTITY_ID', new Main\DB\SqlExpression($permissionSql));
         }
     }
     if ($limit > 0) {
         $query->setLimit($limit);
     }
     $dbResult = $query->exec();
     $results = array();
     while ($fields = $dbResult->fetch()) {
         $type = isset($fields['TYPE']) ? $fields['TYPE'] : '';
         $value = isset($fields['VALUE']) ? $fields['VALUE'] : '';
         if (!isset($results[$type])) {
             $results[$type] = array();
         }
         $results[$type][] = $value;
     }
     return $results;
 }
Beispiel #15
0
 protected function getUserPermissions()
 {
     if ($this->userPermissions === null) {
         $this->userPermissions = \CCrmPerms::GetUserPermissions($this->userID);
     }
     return $this->userPermissions;
 }
Beispiel #16
0
 public function Add(array &$arFields, $bUpdateSearch = true, $options = array())
 {
     global $DB;
     if (!is_array($options)) {
         $options = array();
     }
     $this->LAST_ERROR = '';
     $iUserId = CCrmSecurityHelper::GetCurrentUserID();
     if (isset($arFields['ID'])) {
         unset($arFields['ID']);
     }
     if (isset($arFields['DATE_CREATE'])) {
         unset($arFields['DATE_CREATE']);
     }
     $arFields['~DATE_CREATE'] = $DB->CurrentTimeFunction();
     $arFields['~DATE_MODIFY'] = $DB->CurrentTimeFunction();
     if (!isset($arFields['CREATED_BY_ID']) || (int) $arFields['CREATED_BY_ID'] <= 0) {
         $arFields['CREATED_BY_ID'] = $iUserId;
     }
     if (!isset($arFields['MODIFY_BY_ID']) || (int) $arFields['MODIFY_BY_ID'] <= 0) {
         $arFields['MODIFY_BY_ID'] = $iUserId;
     }
     if (isset($arFields['ASSIGNED_BY_ID']) && is_array($arFields['ASSIGNED_BY_ID'])) {
         $arFields['ASSIGNED_BY_ID'] = count($arFields['ASSIGNED_BY_ID']) > 0 ? intval($arFields['ASSIGNED_BY_ID'][0]) : $iUserId;
     }
     if (!isset($arFields['ASSIGNED_BY_ID']) || (int) $arFields['ASSIGNED_BY_ID'] <= 0) {
         $arFields['ASSIGNED_BY_ID'] = $iUserId;
     }
     if (!$this->CheckFields($arFields, false, $options)) {
         $result = false;
         $arFields['RESULT_MESSAGE'] =& $this->LAST_ERROR;
     } else {
         if (!isset($arFields['STAGE_ID'])) {
             $arFields['STAGE_ID'] = 'NEW';
         }
         $arAttr = array();
         if (!empty($arFields['STAGE_ID'])) {
             $arAttr['STAGE_ID'] = $arFields['STAGE_ID'];
         }
         if (!empty($arFields['OPENED'])) {
             $arAttr['OPENED'] = $arFields['OPENED'];
         }
         $sPermission = 'ADD';
         if (isset($arFields['PERMISSION'])) {
             if ($arFields['PERMISSION'] == 'IMPORT') {
                 $sPermission = 'IMPORT';
             }
             unset($arFields['PERMISSION']);
         }
         if ($this->bCheckPermission) {
             $arEntityAttr = self::BuildEntityAttr($iUserId, $arAttr);
             $userPerms = $iUserId == CCrmPerms::GetCurrentUserID() ? $this->cPerms : CCrmPerms::GetUserPermissions($iUserId);
             $sEntityPerm = $userPerms->GetPermType('DEAL', $sPermission, $arEntityAttr);
             if ($sEntityPerm == BX_CRM_PERM_NONE) {
                 $this->LAST_ERROR = GetMessage('CRM_PERMISSION_DENIED');
                 $arFields['RESULT_MESSAGE'] =& $this->LAST_ERROR;
                 return false;
             }
             $assignedByID = intval($arFields['ASSIGNED_BY_ID']);
             if ($sEntityPerm == BX_CRM_PERM_SELF && $assignedByID != $iUserId) {
                 $arFields['ASSIGNED_BY_ID'] = $iUserId;
             }
             if ($sEntityPerm == BX_CRM_PERM_OPEN && $iUserId == $assignedByID) {
                 $arFields['OPENED'] = 'Y';
             }
         }
         $assignedByID = intval($arFields['ASSIGNED_BY_ID']);
         $arEntityAttr = self::BuildEntityAttr($assignedByID, $arAttr);
         $userPerms = $assignedByID == CCrmPerms::GetCurrentUserID() ? $this->cPerms : CCrmPerms::GetUserPermissions($assignedByID);
         $sEntityPerm = $userPerms->GetPermType('DEAL', $sPermission, $arEntityAttr);
         $this->PrepareEntityAttrs($arEntityAttr, $sEntityPerm);
         // Calculation of Account Data
         $accData = CCrmAccountingHelper::PrepareAccountingData(array('CURRENCY_ID' => isset($arFields['CURRENCY_ID']) ? $arFields['CURRENCY_ID'] : null, 'SUM' => isset($arFields['OPPORTUNITY']) ? $arFields['OPPORTUNITY'] : null, 'EXCH_RATE' => isset($arFields['EXCH_RATE']) ? $arFields['EXCH_RATE'] : null));
         if (is_array($accData)) {
             $arFields['ACCOUNT_CURRENCY_ID'] = $accData['ACCOUNT_CURRENCY_ID'];
             $arFields['OPPORTUNITY_ACCOUNT'] = $accData['ACCOUNT_SUM'];
         }
         $accData = CCrmAccountingHelper::PrepareAccountingData(array('CURRENCY_ID' => isset($arFields['CURRENCY_ID']) ? $arFields['CURRENCY_ID'] : null, 'SUM' => isset($arFields['TAX_VALUE']) ? $arFields['TAX_VALUE'] : null, 'EXCH_RATE' => isset($arFields['EXCH_RATE']) ? $arFields['EXCH_RATE'] : null));
         if (is_array($accData)) {
             $arFields['TAX_VALUE_ACCOUNT'] = $accData['ACCOUNT_SUM'];
         }
         $now = ConvertTimeStamp(time(), 'SHORT', SITE_ID);
         $arFields['~BEGINDATE'] = $DB->CharToDateFunction(isset($arFields['BEGINDATE']) && $arFields['BEGINDATE'] !== '' ? $arFields['BEGINDATE'] : $now, 'SHORT', false);
         if (isset($arFields['BEGINDATE'])) {
             $arFields['__BEGINDATE'] = $arFields['BEGINDATE'];
             unset($arFields['BEGINDATE']);
         }
         $isFinalStage = self::GetStageSemantics($arFields['STAGE_ID']) !== 'process';
         $enableCloseDateSync = \Bitrix\Crm\Settings\DealSettings::isCloseDateSyncEnabled();
         $arFields['CLOSED'] = $isFinalStage ? 'Y' : 'N';
         if ($enableCloseDateSync && $isFinalStage) {
             $arFields['CLOSEDATE'] = $now;
             $arFields['~CLOSEDATE'] = $DB->CharToDateFunction($now, 'SHORT', false);
         } elseif ($isFinalStage && (!isset($arFields['CLOSEDATE']) || $arFields['CLOSEDATE'] === '')) {
             $arFields['CLOSEDATE'] = $now;
             $arFields['~CLOSEDATE'] = $DB->CharToDateFunction($now, 'SHORT', false);
         } elseif (isset($arFields['CLOSEDATE']) && $arFields['CLOSEDATE'] !== '') {
             $arFields['~CLOSEDATE'] = $DB->CharToDateFunction($arFields['CLOSEDATE'], 'SHORT', false);
         }
         if (isset($arFields['CLOSEDATE'])) {
             $arFields['__CLOSEDATE'] = $arFields['CLOSEDATE'];
             unset($arFields['CLOSEDATE']);
         }
         $beforeEvents = GetModuleEvents('crm', 'OnBeforeCrmDealAdd');
         while ($arEvent = $beforeEvents->Fetch()) {
             if (ExecuteModuleEventEx($arEvent, array(&$arFields)) === false) {
                 if (isset($arFields['RESULT_MESSAGE'])) {
                     $this->LAST_ERROR = $arFields['RESULT_MESSAGE'];
                 } else {
                     $this->LAST_ERROR = GetMessage('CRM_DEAL_CREATION_CANCELED', array('#NAME#' => $arEvent['TO_NAME']));
                     $arFields['RESULT_MESSAGE'] =& $this->LAST_ERROR;
                 }
                 return false;
             }
         }
         $ID = intval($DB->Add('b_crm_deal', $arFields, array(), 'FILE: ' . __FILE__ . '<br /> LINE: ' . __LINE__));
         //Restore BEGINDATE and CLOSEDATE
         if (isset($arFields['__BEGINDATE'])) {
             $arFields['BEGINDATE'] = $arFields['__BEGINDATE'];
             unset($arFields['__BEGINDATE']);
         }
         if (isset($arFields['__CLOSEDATE'])) {
             $arFields['CLOSEDATE'] = $arFields['__CLOSEDATE'];
             unset($arFields['__CLOSEDATE']);
         }
         CCrmEntityHelper::NormalizeUserFields($arFields, self::$sUFEntityID, $GLOBALS['USER_FIELD_MANAGER'], array('IS_NEW' => true));
         $GLOBALS['USER_FIELD_MANAGER']->Update(self::$sUFEntityID, $ID, $arFields);
         CCrmPerms::UpdateEntityAttr('DEAL', $ID, $arEntityAttr);
         //Statistics & History -->
         Bitrix\Crm\Statistics\DealSumStatisticEntry::register($ID, $arFields);
         Bitrix\Crm\History\DealStageHistoryEntry::register($ID, $arFields, array('IS_NEW' => true));
         Bitrix\Crm\Statistics\DealInvoiceStatisticEntry::synchronize($ID, $arFields);
         //<-- Statistics & History
         if ($bUpdateSearch) {
             $arFilterTmp = array('ID' => $ID);
             if (!$this->bCheckPermission) {
                 $arFilterTmp["CHECK_PERMISSIONS"] = "N";
             }
             CCrmSearch::UpdateSearch($arFilterTmp, 'DEAL', true);
         }
         $result = $arFields['ID'] = $ID;
         if (isset($GLOBALS["USER"]) && isset($arFields['COMPANY_ID']) && intval($arFields['COMPANY_ID']) > 0) {
             if (!class_exists('CUserOptions')) {
                 include_once $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/main/classes/' . $GLOBALS['DBType'] . '/favorites.php';
             }
             CUserOptions::SetOption('crm', 'crm_company_search', array('last_selected' => $arFields['COMPANY_ID']));
         }
         if (isset($GLOBALS["USER"]) && isset($arFields['CONTACT_ID']) && intval($arFields['CONTACT_ID']) > 0) {
             if (!class_exists('CUserOptions')) {
                 include_once $_SERVER['DOCUMENT_ROOT'] . "/bitrix/modules/main/classes/" . $GLOBALS['DBType'] . "/favorites.php";
             }
             CUserOptions::SetOption("crm", "crm_contact_search", array('last_selected' => $arFields['CONTACT_ID']));
         }
         if (isset($arFields['FM']) && is_array($arFields['FM'])) {
             $CCrmFieldMulti = new CCrmFieldMulti();
             $CCrmFieldMulti->SetFields('DEAL', $ID, $arFields['FM']);
         }
         if (isset($options['REGISTER_SONET_EVENT']) && $options['REGISTER_SONET_EVENT'] === true) {
             $opportunity = round(isset($arFields['OPPORTUNITY']) ? doubleval($arFields['OPPORTUNITY']) : 0.0, 2);
             $currencyID = isset($arFields['CURRENCY_ID']) ? $arFields['CURRENCY_ID'] : '';
             if ($currencyID === '') {
                 $currencyID = CCrmCurrency::GetBaseCurrencyID();
             }
             $assignedByID = intval($arFields['ASSIGNED_BY_ID']);
             $createdByID = intval($arFields['CREATED_BY_ID']);
             $liveFeedFields = array('USER_ID' => $createdByID, 'ENTITY_TYPE_ID' => CCrmOwnerType::Deal, 'ENTITY_ID' => $ID, 'TITLE' => GetMessage('CRM_DEAL_EVENT_ADD'), 'MESSAGE' => '', 'PARAMS' => array('TITLE' => isset($arFields['TITLE']) ? $arFields['TITLE'] : '', 'STAGE_ID' => isset($arFields['STAGE_ID']) ? $arFields['STAGE_ID'] : '', 'OPPORTUNITY' => strval($opportunity), 'CURRENCY_ID' => $currencyID, 'COMPANY_ID' => isset($arFields['COMPANY_ID']) ? intval($arFields['COMPANY_ID']) : 0, 'CONTACT_ID' => isset($arFields['CONTACT_ID']) ? intval($arFields['CONTACT_ID']) : 0, 'AUTHOR_ID' => intval($arFields['CREATED_BY_ID']), 'RESPONSIBLE_ID' => $assignedByID));
             //Register contact & company relations
             $contactID = isset($arFields['CONTACT_ID']) ? intval($arFields['CONTACT_ID']) : 0;
             $companyID = isset($arFields['COMPANY_ID']) ? intval($arFields['COMPANY_ID']) : 0;
             if ($contactID > 0 || $companyID > 0) {
                 $liveFeedFields['PARENTS'] = array();
                 if ($contactID > 0) {
                     $liveFeedFields['PARENTS'][] = array('ENTITY_TYPE_ID' => CCrmOwnerType::Contact, 'ENTITY_ID' => $contactID);
                 }
                 if ($companyID > 0) {
                     $liveFeedFields['PARENTS'][] = array('ENTITY_TYPE_ID' => CCrmOwnerType::Company, 'ENTITY_ID' => $companyID);
                 }
             }
             CCrmSonetSubscription::RegisterSubscription(CCrmOwnerType::Deal, $ID, CCrmSonetSubscriptionType::Responsibility, $assignedByID);
             $logEventID = CCrmLiveFeed::CreateLogEvent($liveFeedFields, CCrmLiveFeedEvent::Add);
             if ($logEventID && $assignedByID != $createdByID && CModule::IncludeModule("im")) {
                 $url = CCrmOwnerType::GetShowUrl(CCrmOwnerType::Deal, $ID);
                 $serverName = (CMain::IsHTTPS() ? "https" : "http") . "://" . (defined("SITE_SERVER_NAME") && strlen(SITE_SERVER_NAME) > 0 ? SITE_SERVER_NAME : COption::GetOptionString("main", "server_name", ""));
                 $arMessageFields = array("MESSAGE_TYPE" => IM_MESSAGE_SYSTEM, "TO_USER_ID" => $assignedByID, "FROM_USER_ID" => $createdByID, "NOTIFY_TYPE" => IM_NOTIFY_FROM, "NOTIFY_MODULE" => "crm", "LOG_ID" => $logEventID, "NOTIFY_EVENT" => "deal_add", "NOTIFY_TAG" => "CRM|DEAL_RESPONSIBLE|" . $ID, "NOTIFY_MESSAGE" => GetMessage("CRM_DEAL_RESPONSIBLE_IM_NOTIFY", array("#title#" => "<a href=\"" . $url . "\" class=\"bx-notifier-item-action\">" . htmlspecialcharsbx($arFields['TITLE']) . "</a>")), "NOTIFY_MESSAGE_OUT" => GetMessage("CRM_DEAL_RESPONSIBLE_IM_NOTIFY", array("#title#" => htmlspecialcharsbx($arFields['TITLE']))) . " (" . $serverName . $url . ")");
                 CIMNotify::Add($arMessageFields);
             }
         }
         $afterEvents = GetModuleEvents('crm', 'OnAfterCrmDealAdd');
         while ($arEvent = $afterEvents->Fetch()) {
             ExecuteModuleEventEx($arEvent, array(&$arFields));
         }
         if (isset($arFields['ORIGIN_ID']) && $arFields['ORIGIN_ID'] !== '') {
             $afterEvents = GetModuleEvents('crm', 'OnAfterExternalCrmDealAdd');
             while ($arEvent = $afterEvents->Fetch()) {
                 ExecuteModuleEventEx($arEvent, array(&$arFields));
             }
         }
     }
     return $result;
 }
Beispiel #17
0
 public function Add(array &$arFields, $bUpdateSearch = true, $options = array())
 {
     global $DB;
     if (!is_array($options)) {
         $options = array();
     }
     $this->LAST_ERROR = '';
     $iUserId = CCrmSecurityHelper::GetCurrentUserID();
     if (isset($arFields['ID'])) {
         unset($arFields['ID']);
     }
     if (isset($arFields['DATE_CREATE'])) {
         unset($arFields['DATE_CREATE']);
     }
     $arFields['~DATE_CREATE'] = $DB->CurrentTimeFunction();
     $arFields['~DATE_MODIFY'] = $DB->CurrentTimeFunction();
     if (!isset($arFields['CREATED_BY_ID']) || intval($arFields['CREATED_BY_ID']) <= 0) {
         $arFields['CREATED_BY_ID'] = $iUserId;
     }
     if (!isset($arFields['MODIFY_BY_ID']) || intval($arFields['MODIFY_BY_ID']) <= 0) {
         $arFields['MODIFY_BY_ID'] = $iUserId;
     }
     if (!isset($arFields['ASSIGNED_BY_ID']) || intval($arFields['ASSIGNED_BY_ID']) <= 0) {
         $arFields['ASSIGNED_BY_ID'] = $iUserId;
     }
     if (isset($arFields['REVENUE'])) {
         $arFields['REVENUE'] = floatval($arFields['REVENUE']);
     }
     if (!$this->CheckFields($arFields, false, $options)) {
         $result = false;
         $arFields['RESULT_MESSAGE'] =& $this->LAST_ERROR;
     } else {
         $arAttr = array();
         if (!empty($arFields['OPENED'])) {
             $arAttr['OPENED'] = $arFields['OPENED'];
         }
         $sPermission = 'ADD';
         if (isset($arFields['PERMISSION'])) {
             if ($arFields['PERMISSION'] == 'IMPORT') {
                 $sPermission = 'IMPORT';
             }
             unset($arFields['PERMISSION']);
         }
         if ($this->bCheckPermission) {
             $arEntityAttr = self::BuildEntityAttr($iUserId, $arAttr);
             $userPerms = $iUserId == CCrmPerms::GetCurrentUserID() ? $this->cPerms : CCrmPerms::GetUserPermissions($iUserId);
             $sEntityPerm = $userPerms->GetPermType('COMPANY', $sPermission, $arEntityAttr);
             if ($sEntityPerm == BX_CRM_PERM_NONE) {
                 $this->LAST_ERROR = GetMessage('CRM_PERMISSION_DENIED');
                 $arFields['RESULT_MESSAGE'] =& $this->LAST_ERROR;
                 return false;
             }
             $assignedByID = intval($arFields['ASSIGNED_BY_ID']);
             if ($sEntityPerm == BX_CRM_PERM_SELF && $assignedByID != $iUserId) {
                 $arFields['ASSIGNED_BY_ID'] = $iUserId;
             }
             if ($sEntityPerm == BX_CRM_PERM_OPEN && $iUserId == $assignedByID) {
                 $arFields['OPENED'] = 'Y';
             }
         }
         $assignedByID = intval($arFields['ASSIGNED_BY_ID']);
         $arEntityAttr = self::BuildEntityAttr($assignedByID, $arAttr);
         $userPerms = $assignedByID == CCrmPerms::GetCurrentUserID() ? $this->cPerms : CCrmPerms::GetUserPermissions($assignedByID);
         $sEntityPerm = $userPerms->GetPermType('COMPANY', $sPermission, $arEntityAttr);
         $this->PrepareEntityAttrs($arEntityAttr, $sEntityPerm);
         if (isset($arFields['LOGO']) && is_array($arFields['LOGO']) && strlen(CFile::CheckImageFile($arFields['LOGO'])) === 0) {
             $arFields['LOGO']['MODULE_ID'] = 'crm';
             CFile::SaveForDB($arFields, 'LOGO', 'crm');
         }
         $beforeEvents = GetModuleEvents('crm', 'OnBeforeCrmCompanyAdd');
         while ($arEvent = $beforeEvents->Fetch()) {
             if (ExecuteModuleEventEx($arEvent, array(&$arFields)) === false) {
                 if (isset($arFields['RESULT_MESSAGE'])) {
                     $this->LAST_ERROR = $arFields['RESULT_MESSAGE'];
                 } else {
                     $this->LAST_ERROR = GetMessage('CRM_COMPANY_CREATION_CANCELED', array('#NAME#' => $arEvent['TO_NAME']));
                     $arFields['RESULT_MESSAGE'] =& $this->LAST_ERROR;
                 }
                 return false;
             }
         }
         $ID = intval($DB->Add('b_crm_company', $arFields, array(), 'FILE: ' . __FILE__ . '<br /> LINE: ' . __LINE__));
         $result = $arFields['ID'] = $ID;
         CCrmPerms::UpdateEntityAttr('COMPANY', $ID, $arEntityAttr);
         \Bitrix\Crm\Integrity\DuplicateOrganizationCriterion::register(CCrmOwnerType::Company, $ID, $arFields['TITLE']);
         CCrmEntityHelper::NormalizeUserFields($arFields, self::$sUFEntityID, $GLOBALS['USER_FIELD_MANAGER'], array('IS_NEW' => true));
         $GLOBALS['USER_FIELD_MANAGER']->Update(self::$sUFEntityID, $ID, $arFields);
         if (isset($arFields['FM']) && is_array($arFields['FM'])) {
             $CCrmFieldMulti = new CCrmFieldMulti();
             $CCrmFieldMulti->SetFields('COMPANY', $ID, $arFields['FM']);
             $emails = \Bitrix\Crm\Integrity\DuplicateCommunicationCriterion::extractMultifieldsValues($arFields['FM'], 'EMAIL');
             if (!empty($emails)) {
                 \Bitrix\Crm\Integrity\DuplicateCommunicationCriterion::register(CCrmOwnerType::Company, $ID, 'EMAIL', $emails);
             }
             $phones = Bitrix\Crm\Integrity\DuplicateCommunicationCriterion::extractMultifieldsValues($arFields['FM'], 'PHONE');
             if (!empty($phones)) {
                 \Bitrix\Crm\Integrity\DuplicateCommunicationCriterion::register(CCrmOwnerType::Company, $ID, 'PHONE', $phones);
             }
         }
         \Bitrix\Crm\Integrity\DuplicateEntityRanking::registerEntityStatistics(CCrmOwnerType::Company, $ID, $arFields);
         if ($bUpdateSearch) {
             CCrmSearch::UpdateSearch(array('ID' => $ID, 'CHECK_PERMISSIONS' => 'N'), 'COMPANY', true);
         }
         if (isset($arFields['CONTACT_ID']) && is_array($arFields['CONTACT_ID'])) {
             $CCrmContact = new CCrmContact();
             $CCrmContact->UpdateCompanyId($arFields['CONTACT_ID'], $arFields['ID']);
             if (isset($GLOBALS["USER"])) {
                 if (!class_exists('CUserOptions')) {
                     include_once $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/main/classes/' . $GLOBALS['DBType'] . '/favorites.php';
                 }
                 CUserOptions::SetOption('crm', 'crm_contact_search', array('last_selected' => implode(',', $arFields['CONTACT_ID'])));
             }
         }
         if (isset($options['REGISTER_SONET_EVENT']) && $options['REGISTER_SONET_EVENT'] === true) {
             $revenue = round(isset($arFields['REVENUE']) ? doubleval($arFields['REVENUE']) : 0.0, 2);
             $currencyID = isset($arFields['CURRENCY_ID']) ? $arFields['CURRENCY_ID'] : '';
             if ($currencyID === '') {
                 $currencyID = CCrmCurrency::GetBaseCurrencyID();
             }
             $multiFields = isset($arFields['FM']) ? $arFields['FM'] : null;
             $phones = CCrmFieldMulti::ExtractValues($multiFields, 'PHONE');
             $emails = CCrmFieldMulti::ExtractValues($multiFields, 'EMAIL');
             $assignedByID = intval($arFields['ASSIGNED_BY_ID']);
             $createdByID = intval($arFields['CREATED_BY_ID']);
             $liveFeedFields = array('USER_ID' => $createdByID, 'ENTITY_TYPE_ID' => CCrmOwnerType::Company, 'ENTITY_ID' => $ID, 'TITLE' => GetMessage('CRM_COMPANY_EVENT_ADD'), 'MESSAGE' => '', 'PARAMS' => array('TITLE' => $arFields['TITLE'], 'LOGO_ID' => isset($arFields['LOGO']) ? $arFields['LOGO'] : '', 'TYPE' => isset($arFields['COMPANY_TYPE']) ? $arFields['COMPANY_TYPE'] : '', 'REVENUE' => strval($revenue), 'CURRENCY_ID' => $currencyID, 'PHONES' => $phones, 'EMAILS' => $emails, 'AUTHOR_ID' => intval($arFields['CREATED_BY_ID']), 'RESPONSIBLE_ID' => $assignedByID));
             CCrmSonetSubscription::RegisterSubscription(CCrmOwnerType::Company, $ID, CCrmSonetSubscriptionType::Responsibility, $assignedByID);
             $logEventID = CCrmLiveFeed::CreateLogEvent($liveFeedFields, CCrmLiveFeedEvent::Add);
             if ($logEventID && $assignedByID != $createdByID && CModule::IncludeModule("im")) {
                 $url = CCrmOwnerType::GetShowUrl(CCrmOwnerType::Company, $ID);
                 $serverName = (CMain::IsHTTPS() ? "https" : "http") . "://" . (defined("SITE_SERVER_NAME") && strlen(SITE_SERVER_NAME) > 0 ? SITE_SERVER_NAME : COption::GetOptionString("main", "server_name", ""));
                 $arMessageFields = array("MESSAGE_TYPE" => IM_MESSAGE_SYSTEM, "TO_USER_ID" => $assignedByID, "FROM_USER_ID" => $createdByID, "NOTIFY_TYPE" => IM_NOTIFY_FROM, "NOTIFY_MODULE" => "crm", "LOG_ID" => $logEventID, "NOTIFY_EVENT" => "company_add", "NOTIFY_TAG" => "CRM|COMPANY_RESPONSIBLE|" . $ID, "NOTIFY_MESSAGE" => GetMessage("CRM_COMPANY_RESPONSIBLE_IM_NOTIFY", array("#title#" => "<a href=\"" . $url . "\" class=\"bx-notifier-item-action\">" . htmlspecialcharsbx($arFields['TITLE']) . "</a>")), "NOTIFY_MESSAGE_OUT" => GetMessage("CRM_COMPANY_RESPONSIBLE_IM_NOTIFY", array("#title#" => htmlspecialcharsbx($arFields['TITLE']))) . " (" . $serverName . $url . ")");
                 CIMNotify::Add($arMessageFields);
             }
         }
         $afterEvents = GetModuleEvents('crm', 'OnAfterCrmCompanyAdd');
         while ($arEvent = $afterEvents->Fetch()) {
             ExecuteModuleEventEx($arEvent, array(&$arFields));
         }
         if (isset($arFields['ORIGIN_ID']) && $arFields['ORIGIN_ID'] !== '') {
             $afterEvents = GetModuleEvents('crm', 'OnAfterExternalCrmCompanyAdd');
             while ($arEvent = $afterEvents->Fetch()) {
                 ExecuteModuleEventEx($arEvent, array(&$arFields));
             }
         }
     }
     return $result;
 }
Beispiel #18
0
 static function CanUserOperateDocumentType($operation, $userId, $documentType, $arParameters = array())
 {
     $arDocumentID = self::GetDocumentInfo($documentType . '_0');
     if (empty($arDocumentID)) {
         throw new CBPArgumentNullException('documentId');
     }
     $userId = intval($userId);
     if (!array_key_exists('AllUserGroups', $arParameters)) {
         if (!array_key_exists('UserGroups', $arParameters)) {
             $arParameters['UserGroups'] = self::PrepareUserGroups($userId);
         }
         $arParameters['AllUserGroups'] = $arParameters['UserGroups'];
         $arParameters['AllUserGroups'][] = 'Author';
     }
     if (array_key_exists('UserIsAdmin', $arParameters) && $arParameters['UserIsAdmin'] === true) {
         return true;
     } elseif (in_array(1, $arParameters['AllUserGroups'])) {
         return true;
     }
     switch ($operation) {
         case CBPCanUserOperateOperation::ViewWorkflow:
             $op = 'READ';
             break;
         case CBPCanUserOperateOperation::StartWorkflow:
             $op = 'ADD';
             break;
         case CBPCanUserOperateOperation::CreateWorkflow:
             $op = 'ADD';
             break;
         case CBPCanUserOperateOperation::WriteDocument:
             $op = 'ADD';
             break;
         case CBPCanUserOperateOperation::ReadDocument:
             $op = 'READ';
             break;
         default:
             $op = 'ADD';
     }
     $CCrmPerms = CCrmPerms::GetUserPermissions($userId);
     return !$CCrmPerms->HavePerm($arDocumentID['TYPE'], BX_CRM_PERM_NONE, $op);
 }
Beispiel #19
0
    }
}
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
    __CrmDedupeListEndResonse(array('ERROR' => 'Invalid request.'));
}
CUtil::JSPostUnescape();
$action = isset($_POST['ACTION']) ? $_POST['ACTION'] : '';
if (!CModule::IncludeModule('crm')) {
    __CrmDedupeListEndResonse(array('ERROR' => 'Could not load CRM module.'));
}
$currentUser = CCrmSecurityHelper::GetCurrentUser();
if (!$currentUser || !$currentUser->IsAuthorized() || !check_bitrix_sessid()) {
    __CrmDedupeListEndResonse(array('ERROR' => 'Access denied.'));
}
$currentUserID = (int) $currentUser->GetID();
$currentUserPermissions = CCrmPerms::GetUserPermissions($currentUserID);
if ($action === 'GET_DUPLICATE_ENTITIES') {
    __IncludeLang(dirname(__FILE__) . '/lang/' . LANGUAGE_ID . '/' . basename(__FILE__));
    $entityTypeID = isset($_POST['ENTITY_TYPE_NAME']) ? CCrmOwnerType::ResolveID($_POST['ENTITY_TYPE_NAME']) : CCrmOwnerType::Undefined;
    $entityTypeName = CCrmOwnerType::ResolveName($entityTypeID);
    if (!CCrmAuthorizationHelper::CheckReadPermission($entityTypeName, 0)) {
        __CrmDedupeListEndResonse(array('ERROR' => 'Access denied.'));
    }
    $rootEntityID = isset($_POST['ROOT_ENTITY_ID']) ? (int) $_POST['ROOT_ENTITY_ID'] : 0;
    $typeID = isset($_POST['INDEX_TYPE_NAME']) ? Integrity\DuplicateIndexType::resolveID($_POST['INDEX_TYPE_NAME']) : Integrity\DuplicateIndexType::UNDEFINED;
    $layoutName = isset($_POST['LAYOUT_NAME']) ? $_POST['LAYOUT_NAME'] : '';
    $layoutID = CCrmOwnerType::ResolveID($layoutName);
    $matches = isset($_POST['INDEX_MATCHES']) && is_array($_POST['INDEX_MATCHES']) ? $_POST['INDEX_MATCHES'] : array();
    if (empty($matches)) {
        __CrmDedupeListEndResonse(array('ERROR' => 'Matches is not defined.'));
    }
Beispiel #20
0
<?php

if (!defined('B_PROLOG_INCLUDED') || B_PROLOG_INCLUDED !== true) {
    die;
}
global $APPLICATION;
use Bitrix\Crm\BirthdayReminder;
if (!CModule::IncludeModule('crm')) {
    ShowError(GetMessage('CRM_MODULE_NOT_INSTALLED'));
    return;
}
$userID = CCrmSecurityHelper::GetCurrentUserID();
$isAdminUser = CCrmPerms::IsAdmin($userID);
$userPermissions = CCrmPerms::GetUserPermissions($userID);
$canReadLead = CCrmLead::CheckReadPermission(0, $userPermissions);
$canReadContact = CCrmContact::CheckReadPermission(0, $userPermissions);
if (!$canReadLead && !$canReadContact) {
    ShowError(GetMessage('CRM_PERMISSION_DENIED'));
    return;
}
$arResult['USER_ID'] = $userID;
$listID = isset($arParams['LIST_ID']) ? $arParams['LIST_ID'] : '';
if ($listID === '') {
    $listID = uniqid('birthdays_');
}
$arResult['LIST_ID'] = $listID;
$arResult['ERRORS'] = array();
$arResult['MESSAGES'] = array();
$arParams['NAME_FORMAT'] = isset($arParams['NAME_FORMAT']) ? $arParams['NAME_FORMAT'] : '';
$arResult['NAME_FORMAT'] = $arParams['NAME_FORMAT'] !== '' ? $arParams['NAME_FORMAT'] : \Bitrix\Crm\Format\PersonNameFormatter::getFormat();
$utils = new CComponentUtil();
Beispiel #21
0
 /**
  * @return Main\Entity\Query
  */
 private function createQuery($offset = 0, $limit = 0)
 {
     if (!is_int($offset)) {
         $offset = intval($offset);
     }
     if (!is_int($limit)) {
         $limit = intval($limit);
     }
     $typeIDs = $this->getTypeIDs();
     if (empty($typeIDs)) {
         throw new Main\NotSupportedException("Criterion types are required.");
     }
     $query = new Main\Entity\Query(Entity\DuplicateIndexTable::getEntity());
     $query->addSelect('ROOT_ENTITY_ID');
     $query->addSelect('ROOT_ENTITY_NAME');
     $query->addSelect('ROOT_ENTITY_TITLE');
     $query->addSelect('QUANTITY');
     $query->addSelect('TYPE_ID');
     $query->addSelect('MATCHES');
     $query->addSelect('IS_JUNK');
     $permissionSql = '';
     if ($this->enablePermissionCheck) {
         $permissions = \CCrmPerms::GetUserPermissions($this->userID);
         $permissionSql = \CCrmPerms::BuildSql(\CCrmOwnerType::ResolveName($this->entityTypeID), '', 'READ', array('RAW_QUERY' => true, 'PERMS' => $permissions));
         if ($permissionSql === false) {
             //Access denied;
             return null;
         }
     }
     $query->addFilter('=USER_ID', $this->userID);
     $query->addFilter('=ENTITY_TYPE_ID', $this->entityTypeID);
     $query->addFilter('@TYPE_ID', $typeIDs);
     if ($this->enablePermissionCheck && $permissionSql !== '') {
         $query->addFilter('@ROOT_ENTITY_ID', new Main\DB\SqlExpression($permissionSql));
     }
     if ($offset > 0) {
         $query->setOffset($offset);
     }
     if ($limit > 0) {
         $query->setLimit($limit);
     }
     $enableSorting = $this->sortTypeID !== DuplicateIndexType::UNDEFINED;
     if ($enableSorting) {
         $order = $this->sortOrder === SORT_DESC ? 'DESC' : 'ASC';
         if ($this->sortTypeID === DuplicateIndexType::COMMUNICATION_EMAIL) {
             $query->addOrder('ROOT_ENTITY_EMAIL_FLAG', $order);
             $query->addOrder('ROOT_ENTITY_EMAIL', $order);
         } elseif ($this->sortTypeID === DuplicateIndexType::COMMUNICATION_PHONE) {
             $query->addOrder('ROOT_ENTITY_PHONE_FLAG', $order);
             $query->addOrder('ROOT_ENTITY_PHONE', $order);
         } elseif ($this->sortTypeID === DuplicateIndexType::PERSON) {
             $query->addOrder('ROOT_ENTITY_NAME_FLAG', $order);
             $query->addOrder('ROOT_ENTITY_NAME', $order);
         } elseif ($this->sortTypeID === DuplicateIndexType::ORGANIZATION) {
             $query->addOrder('ROOT_ENTITY_TITLE_FLAG', $order);
             $query->addOrder('ROOT_ENTITY_TITLE', $order);
         }
     }
     return $query;
 }
Beispiel #22
0
 private static function SynchronizeLiveFeedEvent($activityID, $params)
 {
     if (!is_array($params)) {
         $params = array();
     }
     $processBindings = isset($params['PROCESS_BINDINGS']) ? (bool) $params['PROCESS_BINDINGS'] : false;
     $bindings = isset($params['BINDINGS']) && is_array($params['BINDINGS']) ? $params['BINDINGS'] : array();
     $hasBindings = !empty($bindings);
     if ($processBindings) {
         CCrmSonetRelation::UnRegisterRelationsByEntity(CCrmOwnerType::Activity, $activityID, array('QUICK' => $hasBindings));
     }
     $arOwners = $hasBindings ? $bindings : self::GetBindings($activityID);
     $slEntities = CCrmLiveFeed::GetLogEvents(array(), array('ENTITY_TYPE_ID' => CCrmOwnerType::Activity, 'ENTITY_ID' => $activityID), array('ID', 'EVENT_ID'));
     if (empty($slEntities)) {
         return false;
     }
     global $DB;
     foreach ($slEntities as &$slEntity) {
         $slID = intval($slEntity['ID']);
         $slEventType = $slEntity['EVENT_ID'];
         if (isset($params['REFRESH_DATE']) ? (bool) $params['REFRESH_DATE'] : false) {
             //Update LOG_UPDATE for force event to rise in global feed
             //Update LOG_DATE for force event to rise in entity feed
             CCrmLiveFeed::UpdateLogEvent($slID, array('=LOG_UPDATE' => $DB->CurrentTimeFunction(), '=LOG_DATE' => $DB->CurrentTimeFunction()));
         } else {
             //HACK: FAKE UPDATE FOR INVALIDATE CACHE
             CCrmLiveFeed::UpdateLogEvent($slID, array('ENTITY_TYPE_ID' => CCrmOwnerType::Activity, 'ENTITY_ID' => $activityID));
         }
         /*
         					'START_RESPONSIBLE_ID' => $arPrevEntity['RESPONSIBLE_ID'],
         					'FINAL_RESPONSIBLE_ID' => $responsibleID
         */
         $userID = intval($params['EDITOR_ID']) > 0 ? $params['EDITOR_ID'] : CCrmSecurityHelper::GetCurrentUserID();
         if (intval($params['START_RESPONSIBLE_ID']) != intval($params['FINAL_RESPONSIBLE_ID']) && CModule::IncludeModule("im")) {
             switch ($params['TYPE_ID']) {
                 case CCrmActivityType::Call:
                     $type = 'CALL';
                     break;
                 case CCrmActivityType::Meeting:
                     $type = 'MEETING';
                     break;
                 default:
                     $type = false;
             }
             if ($type) {
                 $url = "/crm/stream/?log_id=#log_id#";
                 $url = str_replace(array("#log_id#"), array($slID), $url);
                 $serverName = (CMain::IsHTTPS() ? "https" : "http") . "://" . (defined("SITE_SERVER_NAME") && strlen(SITE_SERVER_NAME) > 0 ? SITE_SERVER_NAME : COption::GetOptionString("main", "server_name", ""));
                 $arMessageFields = array("MESSAGE_TYPE" => IM_MESSAGE_SYSTEM, "FROM_USER_ID" => $userID, "NOTIFY_TYPE" => IM_NOTIFY_FROM, "NOTIFY_MODULE" => "crm", "LOG_ID" => $slID, "NOTIFY_EVENT" => "activity_add", "NOTIFY_TAG" => "CRM|ACTIVITY|" . $activityID);
                 if (intval($params['START_RESPONSIBLE_ID']) != $userID) {
                     $bHasPermissions = false;
                     $perms = CCrmPerms::GetUserPermissions($params['START_RESPONSIBLE_ID']);
                     foreach ($arOwners as $arOwner) {
                         if (CCrmActivity::CheckReadPermission($arOwner["OWNER_TYPE_ID"], $arOwner["OWNER_ID"], $perms)) {
                             $bHasPermissions = true;
                             break;
                         }
                     }
                     if ($bHasPermissions) {
                         $arMessageFields["TO_USER_ID"] = $params['START_RESPONSIBLE_ID'];
                         $arMessageFields["NOTIFY_MESSAGE"] = GetMessage("CRM_ACTIVITY_" . $type . "_NOT_RESPONSIBLE_IM_NOTIFY", array("#title#" => '<a href="' . $url . '">' . htmlspecialcharsbx($params['SUBJECT']) . '</a>'));
                         $arMessageFields["NOTIFY_MESSAGE_OUT"] = GetMessage("CRM_ACTIVITY_" . $type . "_NOT_RESPONSIBLE_IM_NOTIFY", array("#title#" => htmlspecialcharsbx($params['SUBJECT']))) . " (" . $serverName . $url . ")";
                         CIMNotify::Add($arMessageFields);
                     }
                 }
                 if (intval($params['FINAL_RESPONSIBLE_ID']) != $userID) {
                     $bHasPermissions = false;
                     $perms = CCrmPerms::GetUserPermissions($params['FINAL_RESPONSIBLE_ID']);
                     foreach ($arOwners as $arOwner) {
                         if (CCrmActivity::CheckReadPermission($arOwner["OWNER_TYPE_ID"], $arOwner["OWNER_ID"], $perms)) {
                             $bHasPermissions = true;
                             break;
                         }
                     }
                     if ($bHasPermissions) {
                         $arMessageFields["TO_USER_ID"] = $params['FINAL_RESPONSIBLE_ID'];
                         $arMessageFields["NOTIFY_MESSAGE"] = GetMessage("CRM_ACTIVITY_" . $type . "_RESPONSIBLE_IM_NOTIFY", array("#title#" => '<a href="' . $url . '">' . htmlspecialcharsbx($params['SUBJECT']) . '</a>'));
                         $arMessageFields["NOTIFY_MESSAGE_OUT"] = GetMessage("CRM_ACTIVITY_" . $type . "_RESPONSIBLE_IM_NOTIFY", array("#title#" => htmlspecialcharsbx($params['SUBJECT']))) . " (" . $serverName . $url . ")";
                         CIMNotify::Add($arMessageFields);
                     }
                 }
             }
         }
         if ($processBindings && $hasBindings) {
             CCrmSonetRelation::RegisterRelationBundle($slID, $slEventType, CCrmOwnerType::Activity, $activityID, $bindings, array('ENTITY_TYPE_ID_KEY' => 'OWNER_TYPE_ID', 'ENTITY_ID_KEY' => 'OWNER_ID', 'TYPE_ID' => CCrmSonetRelationType::Ownership));
         }
     }
     unset($slEntity);
     return true;
 }
Beispiel #23
0
 function CheckPermission($arUserField, $userID = false)
 {
     //permission check is disabled
     if ($userID === false) {
         return true;
     }
     if (!CModule::IncludeModule('crm')) {
         return false;
     }
     $userID = intval($userID);
     $userPerms = $userID > 0 ? CCrmPerms::GetUserPermissions($userID) : CCrmPerms::GetCurrentUserPermissions();
     return CCrmPerms::IsAccessEnabled($userPerms);
 }