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

CCrmActivity::Update: метод Битрикс

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

//    CCrmActivity::Update()
//    /bitrix/modules/crm/classes/general/crm_activity.php:368

    public static function Update($ID, $arFields, $checkPerms = true, $regEvent = true, $options = array())
    {
        self::$LAST_UPDATE_FIELDS = null;

        global $DB, $USER_FIELD_MANAGER;
        if(!is_array($options))
        {
            $options = array();
        }

        $arPrevEntity = self::GetByID($ID, false);

        if(!$arPrevEntity)
        {
            return false; // is not exists
        }

        if(!self::CheckFields('UPDATE', $arFields, $ID, array('PREVIOUS_FIELDS' => $arPrevEntity)))
        {
            return false;
        }

        $arPrevBindings = self::GetBindings($ID);
        $arRecordBindings = array();

        $storageElementIDs = isset($arFields['STORAGE_ELEMENT_IDS']) ? $arFields['STORAGE_ELEMENT_IDS'] : null;
        $storageElementsSerialized = false;
        if(is_array($storageElementIDs))
        {
            $storageElementIDs = self::NormalizeStorageElementIDs($storageElementIDs);
            $arFields['STORAGE_ELEMENT_IDS'] = serialize($storageElementIDs);
            $storageElementsSerialized = true;
        }
        elseif($storageElementIDs !== null)
        {
            //Skip Storage Elements Processing - Treat As Not Changed
            $storageElementIDs = null;
        }

        if(isset($arFields['STORAGE_ELEMENT_IDS']))
        {
            $arRecordBindings['STORAGE_ELEMENT_IDS'] = $arFields['STORAGE_ELEMENT_IDS'];
        }

        if(isset($arFields['SETTINGS']))
        {
            if(is_array($arFields['SETTINGS']))
            {
                $arFields['SETTINGS'] = serialize($arFields['SETTINGS']);
            }
            $arRecordBindings['SETTINGS'] = $arFields['SETTINGS'];
        }

        if(isset($arFields['DESCRIPTION']))
        {
            $arRecordBindings['DESCRIPTION'] = $arFields['DESCRIPTION'];
        }
        if(isset($arFields['PROVIDER_PARAMS']))
        {
            $arFields['PROVIDER_PARAMS'] = serialize($arFields['PROVIDER_PARAMS']);
            $arRecordBindings['PROVIDER_PARAMS'] = $arFields['PROVIDER_PARAMS'];
        }
        if(isset($arFields['PROVIDER_DATA']))
        {
            $arRecordBindings['PROVIDER_DATA'] = $arFields['PROVIDER_DATA'];
        }

        $arBindings = (isset($arFields['BINDINGS']) && is_array($arFields['BINDINGS'])) ? $arFields['BINDINGS'] : null;
        if(is_array($arBindings))
        {
            $bindingQty = count($arBindings);
            if($bindingQty === 1)
            {
                // Change activity ownership if only one binding defined
                $arBinding = $arBindings[0];
                $arFields['OWNER_ID'] = $arBinding['OWNER_ID'];
                $arFields['OWNER_TYPE_ID'] = $arBinding['OWNER_TYPE_ID'];
            }
            elseif($bindingQty === 0)
            {
                // Clear activity ownership if only no bindings are defined
                $arFields['OWNER_ID'] = 0;
                $arFields['OWNER_TYPE_ID'] = CCrmOwnerType::Undefined;
            }
        }

        if (isset($arFields['PARENT_ID']) && $arFields['PARENT_ID'] > 0 && $arPrevEntity['PARENT_ID'] == 0)
        {
            $parent = $DB->query(sprintf(
                'SELECT ID, THREAD_ID FROM %s WHERE ID = %u',
                \CCrmActivity::TABLE_NAME, $arFields['PARENT_ID']
            ))->fetch();
        }

        if (!empty($parent))
        {
            $arFields['PARENT_ID'] = $parent['ID'];
            $arFields['THREAD_ID'] = $parent['THREAD_ID'];
        }
        else
        {
            unset($arFields['PARENT_ID']);
            unset($arFields['THREAD_ID']);
        }

        self::NormalizeDateTimeFields($arFields);

        if(isset($arFields['ID']))
        {
            unset($arFields['ID']);
        }

        $sql = 'UPDATE '.CCrmActivity::TABLE_NAME.' SET '.$DB->PrepareUpdate(CCrmActivity::TABLE_NAME, $arFields).' WHERE ID = '.$ID;
        if(!empty($arRecordBindings))
        {
            $DB->QueryBind($sql, $arRecordBindings, false);
        }
        else
        {
            $DB->Query($sql, false, 'File: '.__FILE__.'
Line: '.__LINE__);
        }

        self::$LAST_UPDATE_FIELDS = $arFields;

        if (isset($arFields['PARENT_ID']) && $arFields['PARENT_ID'] > 0 && $arPrevEntity['PARENT_ID'] == 0)
        {
            $DB->query(sprintf(
                'UPDATE %s SET THREAD_ID = %u WHERE THREAD_ID = %u',
                \CCrmActivity::TABLE_NAME, $arFields['THREAD_ID'], $ID
            ));
        }

        $arFields['SETTINGS'] = isset($arFields['SETTINGS']) ? unserialize($arFields['SETTINGS']) : array();
        $arFields['PROVIDER_PARAMS'] = isset($arFields['PROVIDER_PARAMS']) ? unserialize($arFields['PROVIDER_PARAMS']) : array();

        CCrmEntityHelper::RemoveCached(self::CACHE_NAME, $ID);

        $storageTypeID = isset($arFields['STORAGE_TYPE_ID']) ? intval($arFields['STORAGE_TYPE_ID']) : StorageType::Undefined;
        if($storageTypeID === StorageType::Undefined)
        {
            $storageTypeID = isset($arPrevEntity['STORAGE_TYPE_ID']) ? intval($arPrevEntity['STORAGE_TYPE_ID']) : self::GetDefaultStorageTypeID();
        }

        if(is_array($storageElementIDs))
        {
            CCrmActivity::DoSaveElementIDs($ID, $storageTypeID, $storageElementIDs);
        }

        $arCurEntity = self::GetByID($ID, false);
        if(!$arCurEntity)
        {
            return false; // is not exists
        }

        if(is_array($arBindings))
        {
            $bindingsChanged = !self::IsBindingsEquals($arBindings, $arPrevBindings);
            if($bindingsChanged)
            {
                self::SaveBindings($ID, $arBindings, false, false);
            }
        }
        else
        {
            $arBindings = $arPrevBindings;
            $bindingsChanged = false;
        }

        if(isset($arFields['COMMUNICATIONS']) && is_array($arFields['COMMUNICATIONS']))
        {
            self::SaveCommunications($ID, $arFields['COMMUNICATIONS'], $arFields, false, false);
        }

        $prevCompleted = isset($arPrevEntity['COMPLETED']) && $arPrevEntity['COMPLETED'] === 'Y';
        if($prevCompleted && isset($arPrevEntity['STATUS']))
        {
            $prevCompleted = $arPrevEntity['STATUS'] == CCrmActivityStatus::Completed;
        }

        $curCompleted = isset($arCurEntity['COMPLETED']) && $arCurEntity['COMPLETED'] === 'Y';
        if($curCompleted && isset($arCurEntity['STATUS']))
        {
            $curCompleted = $arCurEntity['STATUS'] == CCrmActivityStatus::Completed;
        }

        $prevDeadline = isset($arPrevEntity['DEADLINE']) ? $arPrevEntity['DEADLINE'] : '';
        $curDeadline = isset($arCurEntity['DEADLINE']) ? $arCurEntity['DEADLINE'] : '';

        if($prevCompleted
            && $prevDeadline
            && ($bindingsChanged || $prevCompleted != $curCompleted || $prevDeadline !== $curDeadline))
        {
            $deadline = new \Bitrix\Main\Type\DateTime($prevDeadline);
            $deadline->setTime(0, 0, 0);
            foreach($arPrevBindings as $arBinding)
            {
                $curOwnerTypeID = isset($arBinding['OWNER_TYPE_ID']) ? intval($arBinding['OWNER_TYPE_ID']) : 0;
                $curOwnerID = isset($arBinding['OWNER_ID']) ? intval($arBinding['OWNER_ID']) : 0;
                if($curOwnerID > 0)
                {
                    if($curOwnerTypeID === CCrmOwnerType::Deal)
                    {
                        Bitrix\Crm\Statistics\DealActivityStatisticEntry::register($curOwnerID, null, array('DATE' => $deadline));
                    }
                    elseif($curOwnerTypeID === CCrmOwnerType::Lead)
                    {
                        Bitrix\Crm\Statistics\LeadActivityStatisticEntry::register($curOwnerID, null, array('DATE' => $deadline));
                    }
                }
            }
        }

        if($curCompleted && $curDeadline !== '')
        {
            $deadline = new \Bitrix\Main\Type\DateTime($curDeadline);
            $deadline->setTime(0, 0, 0);
            foreach($arBindings as $arBinding)
            {
                $curOwnerTypeID = isset($arBinding['OWNER_TYPE_ID']) ? (int)$arBinding['OWNER_TYPE_ID'] : 0;
                $curOwnerID = isset($arBinding['OWNER_ID']) ? (int)$arBinding['OWNER_ID'] : 0;
                if($curOwnerID > 0)
                {
                    if($curOwnerTypeID === CCrmOwnerType::Deal)
                    {
                        Bitrix\Crm\Statistics\DealActivityStatisticEntry::register($curOwnerID, null, array('DATE' => $deadline));
                    }
                    elseif($curOwnerTypeID === CCrmOwnerType::Lead)
                    {
                        Bitrix\Crm\Statistics\LeadActivityStatisticEntry::register($curOwnerID, null, array('DATE' => $deadline));
                    }
                }
            }
        }

        $arCurEntity['BINDINGS'] = $arBindings;
        $arPrevEntity['BINDINGS'] = $arPrevBindings;
        \Bitrix\Crm\Activity\CommunicationStatistics::updateActivity($arCurEntity, $arPrevEntity);
        if ($curDeadline)
        {
            \Bitrix\Crm\Statistics\ActivityStatisticEntry::register($ID, $arCurEntity);
        }
        \Bitrix\Crm\Integration\Channel\ActivityChannelBinding::synchronize($ID, $arCurEntity);

        //region Search content index
        Bitrix\Crm\Search\SearchContentBuilderFactory::create(CCrmOwnerType::Activity)->build($ID);
        //endregion

        // Synchronize user activity -->
        $arSyncKeys = array();
        $responsibleID = isset($arFields['RESPONSIBLE_ID'])
            ? intval($arFields['RESPONSIBLE_ID'])
            : (isset($arPrevEntity['RESPONSIBLE_ID']) ? intval($arPrevEntity['RESPONSIBLE_ID']) : 0);

        $counterCodes = EntityCounterManager::prepareCodes(CCrmOwnerType::Activity, EntityCounterType::CURRENT);
        foreach($arBindings as $arBinding)
        {
            if($responsibleID > 0)
            {
                $arSyncKeys[] = "{$arBinding['OWNER_TYPE_ID']}_{$arBinding['OWNER_ID']}_{$responsibleID}";
                self::SynchronizeUserActivity($arBinding['OWNER_TYPE_ID'], $arBinding['OWNER_ID'], $responsibleID);
                $counterCodes = array_merge(
                    $counterCodes,
                    EntityCounterManager::prepareCodes(
                        $arBinding['OWNER_TYPE_ID'],
                        EntityCounterType::getAll(true),
                        array('ENTITY_ID' => $arBinding['OWNER_ID'], 'EXTENDED_MODE' => true)
                    )
                );
            }
            self::SynchronizeUserActivity($arBinding['OWNER_TYPE_ID'], $arBinding['OWNER_ID'], 0);
            $arSyncKeys[] = "{$arBinding['OWNER_TYPE_ID']}_{$arBinding['OWNER_ID']}";
        }
        if(!empty($counterCodes))
        {
            EntityCounterManager::reset($counterCodes, array($responsibleID));
        }

        $prevResponsibleID = isset($arPrevEntity['RESPONSIBLE_ID']) ? intval($arPrevEntity['RESPONSIBLE_ID']) : 0;
        if(!empty($arPrevBindings))
        {
            $counterCodes = EntityCounterManager::prepareCodes(CCrmOwnerType::Activity, EntityCounterType::CURRENT);
            foreach($arPrevBindings as $arBinding)
            {
                if($prevResponsibleID > 0 && !in_array("{$arBinding['OWNER_TYPE_ID']}_{$arBinding['OWNER_ID']}_{$prevResponsibleID}", $arSyncKeys, true))
                {
                    self::SynchronizeUserActivity($arBinding['OWNER_TYPE_ID'], $arBinding['OWNER_ID'], $prevResponsibleID);
                    $counterCodes = array_merge(
                        $counterCodes,
                        EntityCounterManager::prepareCodes(
                            $arBinding['OWNER_TYPE_ID'],
                            EntityCounterType::getAll(true),
                            array('ENTITY_ID' => $arBinding['OWNER_ID'], 'EXTENDED_MODE' => true)
                        )
                    );
                }
                if(!in_array("{$arBinding['OWNER_TYPE_ID']}_{$arBinding['OWNER_ID']}", $arSyncKeys, true))
                {
                    self::SynchronizeUserActivity($arBinding['OWNER_TYPE_ID'], $arBinding['OWNER_ID'], 0);
                }
            }
            if(!empty($counterCodes))
            {
                EntityCounterManager::reset($counterCodes, array($prevResponsibleID));
            }
        }
        // <-- Synchronize user activity

        if($regEvent)
        {
            foreach($arBindings as $arBinding)
            {
                self::RegisterUpdateEvent($arBinding['OWNER_TYPE_ID'], $arBinding['OWNER_ID'], $arCurEntity, $arPrevEntity, false);
            }
            unset($arBinding);
        }

        $providerTypeId = isset($arCurEntity['PROVIDER_TYPE_ID']) ? (string) $arCurEntity['PROVIDER_TYPE_ID'] : null;
        $skipAssocEntity = isset($options['SKIP_ASSOCIATED_ENTITY']) ? (bool)$options['SKIP_ASSOCIATED_ENTITY'] : false;
        $associatedEntityId = isset($arCurEntity['ASSOCIATED_ENTITY_ID']) ? (int)$arCurEntity['ASSOCIATED_ENTITY_ID'] : 0;
        $provider = self::GetActivityProvider($arCurEntity);

        if(!$skipAssocEntity && $provider !== null && $associatedEntityId > 0)
        {
            $provider::updateAssociatedEntity($associatedEntityId, $arCurEntity, $options);
        }

        if ($provider !== null && $provider::canUseCalendarEvents($providerTypeId))
        {
            $skipCalendarEvent = isset($options['SKIP_CALENDAR_EVENT']) ? (bool)$options['SKIP_CALENDAR_EVENT'] : null;
            $completed = isset($arCurEntity['COMPLETED']) ? $arCurEntity['COMPLETED'] === 'Y' : false;

            if (!$skipCalendarEvent)
            {
                $eventID = 0;
                if (!$completed || $provider::canKeepCompletedInCalendar($providerTypeId))
                {
                    $arCurEntity['BINDINGS'] = $arBindings;
                    $eventID = self::SaveCalendarEvent($arCurEntity);
                }
                else
                    self::DeleteCalendarEvent($arCurEntity);

                if (is_int($eventID))
                    self::SetCalendarEventId($eventID, $ID);
            }
        }

        $registerSonetEvent = isset($options['REGISTER_SONET_EVENT']) && $options['REGISTER_SONET_EVENT'] === true;
        $isSonetEventRegistred = false;

        if ($provider !== null && $provider::canUseLiveFeedEvents($providerTypeId) === false)
        {
            $registerSonetEvent = false;
            $isSonetEventRegistred = true;
        }
        \Bitrix\Crm\Timeline\ActivityController::getInstance()->onModify(
            $ID,
            array(
                'CURRENT_FIELDS' => $arCurEntity,
                'CURRENT_BINDINGS' => $arBindings,
                'PREVIOUS_FIELDS' => $arPrevEntity
            )
        );

        if($registerSonetEvent)
        {
            $isSonetEventSynchronized = self::SynchronizeLiveFeedEvent(
                $ID,
                array(
                    'PROCESS_BINDINGS' => $bindingsChanged,
                    'BINDINGS' => $bindingsChanged ? $arBindings : null,
                    'REFRESH_DATE' => isset($arFields['COMPLETED']) && $arFields['COMPLETED'] !== $arPrevEntity['COMPLETED'],
                    'START_RESPONSIBLE_ID' => $arPrevEntity['RESPONSIBLE_ID'],
                    'FINAL_RESPONSIBLE_ID' => $responsibleID,
                    'EDITOR_ID' => (intval($arFields["EDITOR_ID"]) > 0 ? $arFields["EDITOR_ID"] : CCrmSecurityHelper::GetCurrentUserID()),
                    'TYPE_ID' => self::GetActivityType($arCurEntity),
                    'SUBJECT' => (isset($arFields['SUBJECT']) ? $arFields['SUBJECT'] : $arPrevEntity['SUBJECT'])
                )
            );

            if(!$isSonetEventSynchronized)
            {
                $itemFields = self::GetByID($ID);
                if(is_array($itemFields))
                {
                    $itemFields['BINDINGS'] = $arBindings;
                    $sonetEventID = self::RegisterLiveFeedEvent($itemFields);
                    $isSonetEventRegistred = is_int($sonetEventID) && $sonetEventID > 0;

                    if($responsibleID > 0)
                    {
                        CCrmSonetSubscription::RegisterSubscription(
                            CCrmOwnerType::Activity,
                            $ID,
                            CCrmSonetSubscriptionType::Responsibility,
                            $responsibleID
                        );
                    }
                }
            }
        }

        if(!$isSonetEventRegistred && $responsibleID !== $prevResponsibleID)
        {
            CCrmSonetSubscription::ReplaceSubscriptionByEntity(
                CCrmOwnerType::Activity,
                $ID,
                CCrmSonetSubscriptionType::Responsibility,
                $responsibleID,
                $prevResponsibleID,
                $registerSonetEvent
            );
        }

        if($storageElementsSerialized)
        {
            $arFields['STORAGE_ELEMENT_IDS'] = $storageElementIDs;
        }

        $USER_FIELD_MANAGER->update(static::UF_ENTITY_TYPE, $ID, $arFields, $arFields['EDITOR_ID']);

        $rsEvents = GetModuleEvents('crm', 'OnActivityUpdate');
        while ($arEvent = $rsEvents->Fetch())
        {
            ExecuteModuleEventEx($arEvent, array($ID, &$arFields));
        }

        $event = new \Bitrix\Main\Event(
            'crm', 'OnActivityModified',
            array(
                'before' => $arPrevEntity,
                'current' => $arCurEntity,
            )
        );
        $event->send();

        if($arFields['COMPLETED'] === 'Y')
        {
            $ownerId = $arFields['OWNER_ID'] ?: $arPrevEntity['OWNER_ID'];
            $ownerTypeId = $arFields['OWNER_TYPE_ID'] ?: $arPrevEntity['OWNER_TYPE_ID'];
            Crm\Ml\Scoring::queuePredictionUpdate($ownerTypeId, $ownerId, [
                'EVENT_TYPE' => Crm\Ml\Scoring::EVENT_ACTIVITY,
                'ASSOCIATED_ACTIVITY_ID'=> $ID
            ]);
        }

        if(defined("BX_COMP_MANAGED_CACHE"))
        {
            $GLOBALS["CACHE_MANAGER"]->ClearByTag("CRM_ACTIVITY_".$ID);
        }

        return true;
    }

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

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

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

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

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

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

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

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