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

CRatings::getEntityRatingData: метод Битрикс

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

//    CRatings::getEntityRatingData()
//    /bitrix/modules/main/classes/general/ratings.php:1992

    public static function getEntityRatingData($params = array())
    {
        global $USER, $DB;

        $result = array();

        $entityTypeId = (
            !empty($params['entityTypeId'])
                ? $params['entityTypeId']
                : ''
        );

        $entityIdList = (
            !empty($params['entityId'])
                ? $params['entityId']
                : array()
        );

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

        if (empty($entityIdList))
        {
            return $result;
        }

        $ratingId = \CRatings::getAuthorityRating();
        if (intval($ratingId) <= 0)
        {
            return $result;
        }

        $topCount = (
            isset($params['topCount'])
                ? intval($params['topCount'])
                : 0
        );

        if ($topCount <= 0)
        {
            $topCount = 2;
        }

        if ($topCount > 5)
        {
            $topCount = 5;
        }

        $avatarSize = (
            isset($params['avatarSize'])
                ? intval($params['avatarSize'])
                : 100
        );

        $connection = \Bitrix\Main\Application::getConnection();
        $connection->queryExecute('SET @user_rank = 0');
        $connection->queryExecute('SET @current_entity_id = 0');

        if (\Bitrix\Main\ModuleManager::isModuleInstalled('intranet'))
        {
            $res = $connection->query("SELECT
                @user_rank := IF(
                    @current_entity_id = tmp.ENTITY_ID,
                    @user_rank + 1,
                    1
                ) as USER_RANK,
                @current_entity_id := tmp.ENTITY_ID,
                tmp.USER_ID as USER_ID,
                tmp.ENTITY_ID as ENTITY_ID,
                tmp.WEIGHT as WEIGHT
            FROM (
                SELECT
                    @rownum := @rownum + 1 as ROWNUM,
                    RS1.ENTITY_ID as USER_ID,
                    RV1.ENTITY_ID as ENTITY_ID,
                    MAX(RS1.VOTES) as WEIGHT
                FROM
                    b_rating_subordinate RS1,
                    b_rating_vote RV1
                WHERE
                    RS1.ENTITY_ID = RV1.USER_ID
                    AND RS1.RATING_ID = ".intval($ratingId)."
                    AND RV1.ENTITY_TYPE_ID = '".$DB->ForSQL($entityTypeId)."'
                    AND RV1.ENTITY_ID IN (".implode(',', $entityIdList).")
                GROUP BY
                    RV1.ENTITY_ID, RS1.ENTITY_ID
                ORDER BY
                    RV1.ENTITY_ID,
                    WEIGHT DESC
            ) tmp");
        }
        else
        {
            $res = $connection->query("SELECT
                @user_rank := IF(
                    @current_entity_id = tmp.ENTITY_ID,
                    @user_rank + 1,
                    1
                ) as USER_RANK,
                @current_log_id := tmp.LOG_ID,
                tmp.USER_ID as USER_ID,
                tmp.ENTITY_ID as ENTITY_ID,
                tmp.WEIGHT as WEIGHT
            FROM (
                SELECT
                    @rownum := @rownum + 1 as ROWNUM,
                    RV1.USER_ID as USER_ID,
                    RV1.ENTITY_ID as ENTITY_ID,
                    RV1.VALUE as WEIGHT
                FROM
                    b_rating_vote RV1
                WHERE
                    RV1.ENTITY_TYPE_ID = '".$DB->ForSQL($entityTypeId)."'
                    AND RV1.ENTITY_ID IN (".implode(',', $entityIdList).")
                ORDER BY
                    RV1.ENTITY_ID,
                    WEIGHT DESC
            ) tmp");
        }

        $userWeightData = $entityUserData = array();

        $currentEntityId = false;
        $hasMine = false;

        while ($voteFields = $res->fetch())
        {
            if (
                !$hasMine
                && $voteFields['USER_ID'] == $USER->getId()
            )
            {
                $hasMine = true;
            }

            if ($voteFields['ENTITY_ID'] != $currentEntityId)
            {
                $cnt = 0;
                $hasMine = false;
                $entityUserData[$voteFields['ENTITY_ID']] = array();
            }

            $currentEntityId = $voteFields['ENTITY_ID'];
            $cnt++;

            if ($cnt > ($hasMine ? $topCount+1 : $topCount))
            {
                continue;
            }

            $entityUserData[$voteFields['ENTITY_ID']][] = $voteFields['USER_ID'];
            if (!isset($userWeightData[$voteFields['USER_ID']]))
            {
                $userWeightData[$voteFields['USER_ID']] = floatval($voteFields['WEIGHT']);
            }
        }

        $userData = array();

        if (!empty($userWeightData))
        {
            $res = \Bitrix\Main\UserTable::getList(array(
                'filter' => array(
                    '@ID' => array_keys($userWeightData)
                ),
                'select' => array('ID', 'NAME', 'LAST_NAME', 'SECOND_NAME', 'LOGIN', 'PERSONAL_PHOTO', 'PERSONAL_GENDER')
            ));

            while ($userFields = $res->fetch())
            {
                $userData[$userFields["ID"]] = array(
                    'NAME_FORMATTED' => \CUser::formatName(
                        \CSite::getNameFormat(false),
                        $userFields,
                        true
                    ),
                    'PERSONAL_PHOTO' => array(
                        'ID' => $userFields['PERSONAL_PHOTO'],
                        'SRC' => false
                    ),
                    'PERSONAL_GENDER' => $userFields['PERSONAL_GENDER']
                );

                if (intval($userFields['PERSONAL_PHOTO']) > 0)
                {
                    $imageFile = \CFile::getFileArray($userFields["PERSONAL_PHOTO"]);
                    if ($imageFile !== false)
                    {
                        $file = \CFile::resizeImageGet(
                            $imageFile,
                            array("width" => $avatarSize, "height" => $avatarSize),
                            BX_RESIZE_IMAGE_EXACT,
                            false
                        );
                        $userData[$userFields["ID"]]['PERSONAL_PHOTO']['SRC'] = $file['src'];
                    }
                }
            }
        }

        foreach($entityUserData as $entityId => $userIdList)
        {
            $result[$entityId] = array();

            foreach($userIdList as $userId)
            {
                $result[$entityId][] = array(
                    'ID' => $userId,
                    'NAME_FORMATTED' => $userData[$userId]['NAME_FORMATTED'],
                    'PERSONAL_PHOTO' => $userData[$userId]['PERSONAL_PHOTO']['ID'],
                    'PERSONAL_PHOTO_SRC' => $userData[$userId]['PERSONAL_PHOTO']['SRC'],
                    'PERSONAL_GENDER' => $userData[$userId]['PERSONAL_GENDER'],
                    'WEIGHT' => $userWeightData[$userId]
                );
            }
        }

        foreach($result as $entityId => $data)
        {
            usort(
                $data,
                function($a, $b)
                {
                    if ($a['WEIGHT'] == $b['WEIGHT'])
                    {
                        return 0;
                    }
                    return ($a['WEIGHT'] > $b['WEIGHT']) ? -1 : 1;
                }
            );
            $result[$entityId] = $data;
        }

        return $result;
    }
';

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

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

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

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

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

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

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

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