Поддержка серверов

CCrmLead::Delete: метод Битрикс

Постоянная ссылка: http://bxapi.ru/src/?id=186633

//    CCrmLead::Delete()
//    /bitrix/modules/crm/classes/general/crm_lead.php:2756

    public function Delete($ID, $arOptions = array())
    {
        global $DB, $APPLICATION;
        $ID = intval($ID);

        $this->LAST_ERROR = '';
        $APPLICATION->ResetException();

        if(!is_array($arOptions))
        {
            $arOptions = array();
        }

        if(isset($arOptions['CURRENT_USER']))
        {
            $iUserId = intval($arOptions['CURRENT_USER']);
        }
        else
        {
            $iUserId = CCrmSecurityHelper::GetCurrentUserID();
        }

        $dbRes = self::GetListEx(
            array(),
            array('=ID' => $ID, 'CHECK_PERMISSIONS' => 'N'),
            false,
            false,
            array('*')
        );
        $arFields = $dbRes ? $dbRes->Fetch() : null;
        if(!is_array($arFields))
        {
            $err = GetMessage('CRM_LEAD_DELETION_NOT_FOUND');
            $this->LAST_ERROR = $err;
            $APPLICATION->throwException($err);
            return false;
        }

        $assignedByID = isset($arFields['ASSIGNED_BY_ID']) ? (int)$arFields['ASSIGNED_BY_ID'] : 0;
        $isConverted = isset($arFields['STATUS_ID']) && $arFields['STATUS_ID'] === 'CONVERTED';
        $companyID = isset($arFields['COMPANY_ID']) ? (int)$arFields['COMPANY_ID'] : 0;
        $contactID = isset($arFields['CONTACT_ID']) ? (int)$arFields['CONTACT_ID'] : 0;

        if($companyID > 0 && !CCrmCompany::Exists($companyID))
        {
            $companyID = 0;
        }

        if($contactID > 0 && !CCrmContact::Exists($contactID))
        {
            $contactID = 0;
        }

        $sWherePerm = '';
        if ($this->bCheckPermission)
        {
            $arEntityAttr = $this->cPerms->GetEntityAttr('LEAD', $ID);
            $sEntityPerm = $this->cPerms->GetPermType('LEAD', 'DELETE', $arEntityAttr[$ID]);
            if ($sEntityPerm == BX_CRM_PERM_NONE)
                return false;
            else if ($sEntityPerm == BX_CRM_PERM_SELF)
                $sWherePerm = " AND ASSIGNED_BY_ID = {$iUserId}";
            else if ($sEntityPerm == BX_CRM_PERM_OPEN)
                $sWherePerm = " AND (OPENED = 'Y' OR ASSIGNED_BY_ID = {$iUserId})";
        }

        $events = GetModuleEvents('crm', 'OnBeforeCrmLeadDelete');
        while ($arEvent = $events->Fetch())
        {
            if(ExecuteModuleEventEx($arEvent, array($ID))===false)
            {
                $err = GetMessage("MAIN_BEFORE_DEL_ERR").' '.$arEvent['TO_NAME'];
                if($ex = $APPLICATION->GetException())
                    $err .= ': '.$ex->GetString();
                $APPLICATION->throwException($err);
                $this->LAST_ERROR = $err;
                return false;
            }
        }

        $enableDeferredMode = isset($arOptions['ENABLE_DEFERRED_MODE'])
            ? (bool)$arOptions['ENABLE_DEFERRED_MODE']
            : \Bitrix\Crm\Settings\LeadSettings::getCurrent()->isDeferredCleaningEnabled();

        //By default we need to clean up related bizproc entities
        $processBizproc = isset($arOptions['PROCESS_BIZPROC']) ? (bool)$arOptions['PROCESS_BIZPROC'] : true;
        if($processBizproc)
        {
            $bizproc = new CCrmBizProc('LEAD');
            $bizproc->ProcessDeletion($ID);
        }

        $enableRecycleBin = \Bitrix\Crm\Recycling\LeadController::isEnabled()
            && \Bitrix\Crm\Settings\LeadSettings::getCurrent()->isRecycleBinEnabled();
        if($enableRecycleBin)
        {
            \Bitrix\Crm\Recycling\LeadController::getInstance()->moveToBin($ID, array('FIELDS' => $arFields));
        }

        $tableName = CCrmLead::TABLE_NAME;
        $sSql = "DELETE FROM {$tableName} WHERE ID = {$ID}{$sWherePerm}";
        $obRes = $DB->Query($sSql, false, 'FILE: '.__FILE__.'<br /> LINE: '.__LINE__);
        if (is_object($obRes) && $obRes->AffectedRowsCount() > 0)
        {
            if(defined('BX_COMP_MANAGED_CACHE'))
            {
                $GLOBALS['CACHE_MANAGER']->CleanDir('b_crm_lead');
                $GLOBALS['CACHE_MANAGER']->ClearByTag('b_crm_lead');
            }

            CCrmSearch::DeleteSearch('LEAD', $ID);
            Bitrix\Crm\Kanban\SortTable::clearEntity($ID, \CCrmOwnerType::LeadName);

            $DB->Query("DELETE FROM b_crm_entity_perms WHERE ENTITY='LEAD' AND ENTITY_ID = $ID", false, 'FILE: '.__FILE__.'<br /> LINE: '.__LINE__);
            $GLOBALS['USER_FIELD_MANAGER']->Delete(self::$sUFEntityID, $ID);

            LeadContactTable::unbindAllContacts($ID);

            if(!$enableDeferredMode)
            {
                $CCrmEvent = new CCrmEvent();
                $CCrmEvent->DeleteByElement('LEAD', $ID);
            }
            else
            {
                Bitrix\Crm\Cleaning\CleaningManager::register(CCrmOwnerType::Lead, $ID);
                if(!Bitrix\Crm\Agent\Routine\CleaningAgent::isActive())
                {
                    Bitrix\Crm\Agent\Routine\CleaningAgent::activate();
                }
            }

            Bitrix\Crm\History\LeadStatusHistoryEntry::unregister($ID);
            Bitrix\Crm\Statistics\LeadSumStatisticEntry::unregister($ID);
            Bitrix\Crm\Statistics\LeadActivityStatisticEntry::unregister($ID);
            //Bitrix\Crm\Statistics\LeadProcessStatisticsEntry::unregister($ID);
            LeadChannelBinding::unregisterAll($ID);

            if($isConverted)
            {
                Bitrix\Crm\Statistics\LeadConversionStatisticsEntry::unregister($ID);
            }

            DuplicateEntityRanking::unregisterEntityStatistics(CCrmOwnerType::Lead, $ID);
            DuplicatePersonCriterion::unregister(CCrmOwnerType::Lead, $ID);
            DuplicateOrganizationCriterion::unregister(CCrmOwnerType::Lead, $ID);
            DuplicateCommunicationCriterion::unregister(CCrmOwnerType::Lead, $ID);
            DuplicateIndexMismatch::unregisterEntity(CCrmOwnerType::Lead, $ID);

            if($assignedByID > 0)
            {
                EntityCounterManager::reset(
                    EntityCounterManager::prepareCodes(
                        CCrmOwnerType::Lead,
                        array(
                            EntityCounterType::PENDING,
                            EntityCounterType::OVERDUE,
                            EntityCounterType::IDLE,
                            EntityCounterType::ALL
                        )
                    ),
                    array($assignedByID)
                );
            }

            $enableDupIndexInvalidation = is_array($arOptions) && isset($arOptions['ENABLE_DUP_INDEX_INVALIDATION'])
                ? (bool)$arOptions['ENABLE_DUP_INDEX_INVALIDATION'] : true;
            if($enableDupIndexInvalidation)
            {
                Bitrix\Crm\Integrity\DuplicateIndexBuilder::markAsJunk(CCrmOwnerType::Lead, $ID);
            }

            if($isConverted)
            {
                if($contactID > 0)
                {
                    CCrmActivity::ChangeOwner(CCrmOwnerType::Lead, $ID, CCrmOwnerType::Contact, $contactID);
                }
                elseif($companyID> 0)
                {
                    CCrmActivity::ChangeOwner(CCrmOwnerType::Lead, $ID, CCrmOwnerType::Company, $companyID);
                }
            }

            CCrmActivity::DeleteByOwner(CCrmOwnerType::Lead, $ID);

            if(!$enableRecycleBin)
            {
                $CCrmFieldMulti = new CCrmFieldMulti();
                $CCrmFieldMulti->DeleteByElement('LEAD', $ID);

                CCrmProductRow::DeleteByOwner('L', $ID);
                CCrmProductRow::DeleteSettings('L', $ID);

                Crm\EntityAddress::unregister(CCrmOwnerType::Lead, $ID, \Bitrix\Crm\EntityAddress::Primary);
                Crm\Timeline\TimelineEntry::deleteByOwner(CCrmOwnerType::Lead, $ID);
                Crm\Pseudoactivity\WaitEntry::deleteByOwner(CCrmOwnerType::Lead, $ID);
                Crm\Observer\ObserverManager::deleteByOwner(CCrmOwnerType::Lead, $ID);
                Crm\Ml\Scoring::onEntityDelete(CCrmOwnerType::Lead, $ID);

                Crm\Integration\Im\Chat::deleteChat(
                    array(
                        'ENTITY_TYPE_ID' => \CCrmOwnerType::Lead,
                        'ENTITY_ID' => $ID
                    )
                );

                CCrmSonetSubscription::UnRegisterSubscriptionByEntity(CCrmOwnerType::Lead, $ID);
                CCrmLiveFeed::DeleteLogEvents(
                    array(
                        'ENTITY_TYPE_ID' => CCrmOwnerType::Lead,
                        'ENTITY_ID' => $ID
                    ),
                    array(
                        'UNREGISTER_RELATION' => true,
                        'UNREGISTER_SUBSCRIPTION' => true
                    )
                );
                UtmTable::deleteEntityUtm(CCrmOwnerType::Lead, $ID);
                Tracking\Entity::deleteTrace(CCrmOwnerType::Lead, $ID);
            }

            CCrmContact::ProcessLeadDeletion($ID);
            CCrmCompany::ProcessLeadDeletion($ID);
            CCrmDeal::ProcessLeadDeletion($ID);

            \Bitrix\Crm\Timeline\LeadController::getInstance()->onDelete(
                $ID,
                array('FIELDS' => $arFields)
            );

            if(Bitrix\Crm\Settings\HistorySettings::getCurrent()->isLeadDeletionEventEnabled())
            {
                CCrmEvent::RegisterDeleteEvent(CCrmOwnerType::Lead, $ID, $iUserId, array('FIELDS' => $arFields));
            }

            if(defined("BX_COMP_MANAGED_CACHE"))
            {
                $GLOBALS["CACHE_MANAGER"]->ClearByTag("crm_entity_name_".CCrmOwnerType::Lead."_".$ID);
            }

            $afterEvents = GetModuleEvents('crm', 'OnAfterCrmLeadDelete');
            while ($arEvent = $afterEvents->Fetch())
            {
                ExecuteModuleEventEx($arEvent, array($ID));
            }
        }
        return true;
    }
';

Блог разработчика

9 августа 2016 ResizeImageGet и простой водяной знак налету

Сегодня поговорим о том как проще всего воткнуть водяной знак на картинки в Битрикс. Например, на все изображения каталога.

21 июля 2016 Добавление вкладки в CRM коробки Битрикс24

В этом посте я покажу, как легко и просто добавить вкладку в сущность CRM. И не просто добавить, а вывести там свой контент.

21 июля 2016 Как просто обращаться из коробки Битрикс24 на сайт на базе Битрикс

К примеру вам хочется внутренним скриптом дернуть с сайта-магазина информацию, которая там, в свою очередь, закрыта некоторыми правами. Например, админскими. Можно конечно мутить свой REST, или иной формат общения, но проще всего воспользоваться штатным инструментом:

Текст сообщения*
Загрузить изображение