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

CCrmLiveFeedComponent::ProcessLogEventEditPOST: метод Битрикс

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

//    CCrmLiveFeedComponent::ProcessLogEventEditPOST()
//    /bitrix/modules/crm/classes/general/livefeed.php:6201

    public static function ProcessLogEventEditPOST($arPOST, $entityTypeID, $entityID, &$arResult, $arUfCode = array())
    {
        global $USER_FIELD_MANAGER;

        $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 !== '')
        {
            if (
                !isset($arPOST[$webDavFileFieldName])
                && isset($GLOBALS[$webDavFileFieldName])
                && is_array($GLOBALS[$webDavFileFieldName])
            )
            {
                $arPOST[$webDavFileFieldName] = $GLOBALS[$webDavFileFieldName];
            }

            if (
                isset($arPOST[$webDavFileFieldName])
                && is_array($arPOST[$webDavFileFieldName])
            )
            {
                foreach($arPOST[$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 = \Bitrix\Socialnetwork\ComponentHelper::getAllowToAllDestination($arResult['USER_ID']);

        $arSocnetRights = array();
        $arUserIdToMail = array();
        $bMailModuleInstalled = IsModuleInstalled('mail');
        $arCrmEmailEntities = array();

        if (isset($arPOST['DEST_CODES']))
        {
            if (empty($arPOST['SPERM']))
            {
                $arPOST['SPERM'] = array();
            }

            foreach($arPOST['DEST_CODES'] as $destCode)
            {
                if ($destCode == 'UA')
                {
                    if (empty($arPOST['SPERM']['UA']))
                    {
                        $arPOST['SPERM']['UA'] = array();
                    }
                    $arPOST['SPERM']['UA'][] = 'UA';
                }
                elseif (preg_match('/^UE(.+)$/i', $destCode, $matches))
                {
                    if (empty($arPOST['SPERM']['UE']))
                    {
                        $arPOST['SPERM']['UE'] = array();
                    }
                    $arPOST['SPERM']['UE'][] = $matches[1];
                }
                elseif (preg_match('/^U(\d+)$/i', $destCode, $matches))
                {
                    if (empty($arPOST['SPERM']['U']))
                    {
                        $arPOST['SPERM']['U'] = array();
                    }
                    $arPOST['SPERM']['U'][] = 'U'.$matches[1];
                }
                elseif (preg_match('/^SG(\d+)$/i', $destCode, $matches))
                {
                    if (empty($arPOST['SPERM']['SG']))
                    {
                        $arPOST['SPERM']['SG'] = array();
                    }
                    $arPOST['SPERM']['SG'][] = 'SG'.$matches[1];
                }
                elseif (preg_match('/^DR(\d+)$/i', $destCode, $matches))
                {
                    if (empty($arPOST['SPERM']['DR']))
                    {
                        $arPOST['SPERM']['DR'] = array();
                    }
                    $arPOST['SPERM']['DR'][] = 'DR'.$matches[1];
                }
                elseif (preg_match('/^CRMCONTACT(\d+)$/i', $destCode, $matches))
                {
                    if (empty($arPOST['SPERM']['CRMCONTACT']))
                    {
                        $arPOST['SPERM']['CRMCONTACT'] = array();
                    }
                    $arPOST['SPERM']['CRMCONTACT'][] = 'CRMCONTACT'.$matches[1];
                }
                elseif (preg_match('/^CRMCOMPANY(\d+)$/i', $destCode, $matches))
                {
                    if (empty($arPOST['SPERM']['CRMCOMPANY']))
                    {
                        $arPOST['SPERM']['CRMCOMPANY'] = array();
                    }
                    $arPOST['SPERM']['CRMCOMPANY'][] = 'CRMCOMPANY'.$matches[1];
                }
                elseif (preg_match('/^CRMLEAD(\d+)$/i', $destCode, $matches))
                {
                    if (empty($arPOST['SPERM']['CRMLEAD']))
                    {
                        $arPOST['SPERM']['CRMLEAD'] = array();
                    }
                    $arPOST['SPERM']['CRMLEAD'][] = 'CRMLEAD'.$matches[1];
                }
                elseif (preg_match('/^CRMDEAL(\d+)$/i', $destCode, $matches))
                {
                    if (empty($arPOST['SPERM']['CRMDEAL']))
                    {
                        $arPOST['SPERM']['CRMDEAL'] = array();
                    }
                    $arPOST['SPERM']['CRMDEAL'][] = 'CRMDEAL'.$matches[1];
                }
            }
            unset($arPOST['DEST_CODES']);
        }

        self::ProcessLogEventEditPOSTCrmEmailUsers($arPOST, $arCrmEmailEntities);

        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);
                }
            }
            else
            {
                if (preg_match('/^SG(\d+)$/', $value, $matches))
                {
                    $arResult["FEED_DESTINATION"]['SELECTED']['SG'.$matches[1]] = 'sonetgroups';
                }
                elseif (preg_match('/^DR(\d+)$/', $value, $matches))
                {
                    $arResult["FEED_DESTINATION"]['SELECTED']['DR'.$matches[1]] = 'department';
                }
                elseif (preg_match('/^U(\d+)$/', $value, $matches))
                {
                    $arResult["FEED_DESTINATION"]['SELECTED']['U'.$matches[1]] = 'users';
                }
            }

            if (
                $bMailModuleInstalled
                && preg_match('/^U(\d+)$/i', $value, $matches)
            )
            {
                $arUserIdToMail[] = intval($matches[1]);
            }
        }

        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);
            }

            $fields['UF'] = array();
            if (
                is_array($arUfCode)
                && !empty($arUfCode)
            )
            {
                $arTmp = array();
                $USER_FIELD_MANAGER->EditFormAddFields("SONET_LOG", $arTmp);

                foreach ($arTmp as $key => $value)
                {
                    if (in_array($key, $arUfCode))
                    {
                        $fields['UF'][$key] = $value;
                    }
                }
            }

            $messageID = CCrmLiveFeed::CreateLogMessage($fields);
            if(!(is_int($messageID) && $messageID > 0))
            {
                $errors[] = isset($fields['ERROR']) ? $fields['ERROR'] : 'UNKNOWN ERROR';
            }
            else
            {
                if (
                    !empty($arUserIdToMail)
                    && CModule::IncludeModule('socialnetwork')
                )
                {
                    $arUserIdToMail = array_unique($arUserIdToMail);
                    \Bitrix\Socialnetwork\Util::notifyMail(array(
                        "type" => "LOG_ENTRY",
                        "siteId" => SITE_ID,
                        "userId" => $arUserIdToMail,
                        "authorId" => $arResult['USER_ID'],
                        "logEntryId" => $messageID,
                        "logEntryUrl" => CComponentEngine::MakePathFromTemplate(
                            '/pub/log_entry.php?log_id=#log_id#',
                            array(
                                "log_id"=> $messageID
                            )
                        )
                    ));
                }

                $arUsers = $arMention = array();

                if (IsModuleInstalled("im"))
                {
                    $arUserIDSent = array();

                    // send recipients notifications
                    if(!empty($arSocnetRights))
                    {
                        foreach($arSocnetRights as $v)
                        {
                            if(substr($v, 0, 1) == "U")
                            {
                                $u = IntVal(substr($v, 1));
                                if (
                                    $u > 0
                                    && !in_array($u, $arUsers)
                                    && $u != $arResult['USER_ID']
                                )
                                {
                                    $arUsers[] = $u;
                                }
                            }
                        }
                    }

                    // send mention notifications
                    preg_match_all("/\[user\s*=\s*([^\]]*)\](.+?)\[\/user\]/is".BX_UTF_PCRE_MODIFIER, $message, $arMention);
                    if (
                        !empty($arMention)
                        && !empty($arMention[1])
                    )
                    {
                        $arMention = $arMention[1];
                        $arMention = array_unique($arMention);
                    }
                    else
                    {
                        $arMention = array();
                    }
                }

                if (
                    (
                        !empty($arUsers)
                        || !empty($arMention)
                    )
                    && CModule::IncludeModule("im")
                )
                {
                    $serverName = (CMain::IsHTTPS() ? "https" : "http")."://".((defined("SITE_SERVER_NAME") && strlen(SITE_SERVER_NAME) > 0) ? SITE_SERVER_NAME : COption::GetOptionString("main", "server_name", ""));

                    $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
                        )
                    );

                    $url = $strLogEntryURL;

                    $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 = "";
                        }
                    }

                    if (!empty($arUsers))
                    {
                        foreach($arUsers as $val)
                        {
                            $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" => "post"
                            );

                            $arMessageFields["TO_USER_ID"] = $val;
                            $arMessageFields["NOTIFY_TAG"] = "CRM|POST|".$messageID;
                            $arMessageFields["NOTIFY_MESSAGE"] = GetMessage(
                                "CRM_LF_EVENT_IM_POST".$genderSuffix,
                                array(
                                    "#title#" => "".htmlspecialcharsbx($strIMMessageTitle).""
                                )
                            );
                            $arMessageFields["NOTIFY_MESSAGE_OUT"] = GetMessage(
                                "CRM_LF_EVENT_IM_POST".$genderSuffix,
                                array(
                                    "#title#" => htmlspecialcharsbx($strIMMessageTitleOut)
                                )
                            )." (".$serverName.$strLogEntryCrmURL.")";

                            CIMNotify::Add($arMessageFields);
                        }
                    }

                    if (!empty($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"
                        );

                        foreach($arMention as $val)
                        {
                            $val = IntVal($val);
                            if (
                                $val > 0
                                && ($val != $arResult['USER_ID'])
                            )
                            {
                                $bHasAccess = false;
/*
commented in http://jabber.bx/view.php?id=0063797

                                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($arAccessCodes, $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#" => "".htmlspecialcharsbx($strIMMessageTitle).""
                                        )
                                    );
                                    $arMessageFields["NOTIFY_MESSAGE_OUT"] = GetMessage(
                                        "CRM_SL_EVENT_IM_MENTION_POST".$genderSuffix,
                                        array(
                                            "#title#" => htmlspecialcharsbx($strIMMessageTitleOut)
                                        )
                                    )." (".$serverName.$url.")";

                                    CIMNotify::Add($arMessageFields);
                                }
                            }
                        }
                    }
                }

                if (!empty($arMention))
                {
                    $arMentionedDestCode = array();
                    foreach($arMention as $val)
                    {
                        $arMentionedDestCode[] = "U".$val;
                    }

                    \Bitrix\Main\FinderDestTable::merge(array(
                        "CONTEXT" => "mention",
                        "CODE" => array_unique($arMentionedDestCode)
                    ));
                }

                if (
                    !empty($arCrmEmailEntities)
                    && (
                        !empty($arCrmEmailEntities[CCrmLiveFeedEntity::Contact])
                        || !empty($arCrmEmailEntities[CCrmLiveFeedEntity::Company])
                        || !empty($arCrmEmailEntities[CCrmLiveFeedEntity::Lead])
                    )
                )
                {
                    $communications = $bindings = array();

                    foreach(\CCrmLiveFeedEntity::GetAll() as $type)
                    {
                        if (
                            !empty($arCrmEmailEntities[$type])
                            && is_array($arCrmEmailEntities[$type])
                        )
                        {
                            foreach($arCrmEmailEntities[$type] as $crmEmailEntity)
                            {
                                $bindings = self::mergeBindings($bindings, array(array(
                                    'OWNER_ID' => intval($crmEmailEntity["ID"]),
                                    'OWNER_TYPE_ID' => \CCrmLiveFeedEntity::resolveEntityTypeID($type)
                                )));

                                $communications = self::mergeCommunications($communications, array(array(
                                    'ID' => 0,
                                    'TYPE' => 'EMAIL',
                                    'VALUE' => $crmEmailEntity["EMAIL"],
                                    'ENTITY_ID' => intval($crmEmailEntity["ID"]),
                                    'ENTITY_TYPE_ID' => \CCrmLiveFeedEntity::resolveEntityTypeID($type)
                                )));
                            }
                        }
                    }

                    if (
                        !empty($bindings)
                        && !empty($communications)
                    )
                    {
                        \Bitrix\Crm\Activity\Provider\Livefeed::addActivity(array(
                            "TYPE" => "ENTRY",
                            "COMMUNICATIONS" => $communications,
                            "BINDINGS" => $bindings,
                            "TITLE" => $title,
                            "MESSAGE" => $message,
                            "USER_ID" => $arResult['USER_ID'],
                            "ENTITY_ID" => $messageID
                        ));
                    }
                }

                return $messageID;
            }
        }

        return $errors;
    }

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

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

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

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

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

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

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

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