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);
                         }
                     }
                 }
             }
         }
     }
 }
Esempio n. 2
0
function getList($blockId, $fields, $order, $filers)
{
    $entity_requests_data_class = connectToBlock($blockId);
    $main_query_requests = new Entity\Query($entity_requests_data_class);
    $main_query_requests->setSelect($fields);
    //$main_query_requests->setSelect(array('ID','UF_TITLE'));
    if (!empty($order)) {
        $main_query_requests->setOrder($order);
    }
    if (!empty($filers)) {
        $main_query_requests->setFilter($filers);
        /*$main_query_requests->setFilter(
              array(
                  'UF_NAME'=>'Александр',
              )
          );*/
    }
    $result_requests = $main_query_requests->exec();
    $result_requests = new CDBResult($result_requests);
    $requests = array();
    while ($row_requests = $result_requests->Fetch()) {
        $requests[] = $row_requests;
        //массив выбранных элементов
    }
    return $requests;
}
Esempio n. 3
0
 /**
  * Executes the query
  *
  * @param string $filterField
  * @param mixed $filterFieldValue
  * @param string $method
  *
  * @return \Bitrix\Main\DB\MysqlResult
  */
 private function execute($filterField, $filterFieldValue, $method)
 {
     $queryBuilder = new Entity\Query(Model\VarsGroupTable::getEntity());
     $queryBuilder->setSelect(array('ID', 'NAME', 'CODE'))->setOrder(array('ID' => 'ASC'))->setFilter(array($filterField => $filterFieldValue));
     if ($method == 'findOneBy') {
         $queryBuilder->setLimit(1);
     }
     return $queryBuilder->exec();
 }
Esempio n. 4
0
 public function validate($value, $primary, array $row, Entity\Field $field)
 {
     $query = new Entity\Query($this->reference->getEntity());
     $query->setFilter(array('=' . $this->reference->getName() => $value) + $this->filter);
     $query->setLimit(1);
     $result = $query->exec();
     if ($result->fetch()) {
         return true;
     }
     return new Entity\FieldError($field, $this->getErrorMessage($value, $field), self::NOT_EXISTS);
 }
 public function calculateEntityCount(DuplicateCriterion $criterion, array $options = null)
 {
     $entityTypeID = $this->getEntityTypeID();
     $enablePermissionCheck = $this->isPermissionCheckEnabled();
     $userID = $this->getUserID();
     $query = new Main\Entity\Query(DuplicateCommunicationMatchCodeTable::getEntity());
     $query->addSelect('QTY');
     $query->registerRuntimeField('', new Main\Entity\ExpressionField('QTY', 'COUNT(*)'));
     $query->addFilter('=ENTITY_TYPE_ID', $entityTypeID);
     if ($enablePermissionCheck) {
         $permissionSql = $this->preparePermissionSql();
         if ($permissionSql === false) {
             //Access denied;
             return 0;
         }
         if (is_string($permissionSql) && $permissionSql !== '') {
             $query->addFilter('@ENTITY_ID', new Main\DB\SqlExpression($permissionSql));
         }
     }
     $matches = $criterion->getMatches();
     $type = isset($matches['TYPE']) ? $matches['TYPE'] : '';
     if ($type === '') {
         throw new Main\ArgumentException("Parameter 'TYPE' is required.", 'matches');
     }
     $value = isset($matches['VALUE']) ? $matches['VALUE'] : '';
     if ($type === '') {
         throw new Main\ArgumentException("Parameter 'VALUE' is required.", 'matches');
     }
     $query->addFilter('=TYPE', $type);
     $query->addFilter('=VALUE', $value);
     $rootEntityID = 0;
     if (is_array($options) && isset($options['ROOT_ENTITY_ID'])) {
         $rootEntityID = (int) $options['ROOT_ENTITY_ID'];
     }
     if ($rootEntityID > 0) {
         $query->addFilter('!ENTITY_ID', $rootEntityID);
         $query->addFilter('!@ENTITY_ID', DuplicateIndexMismatch::prepareQueryField($criterion, $entityTypeID, $rootEntityID, $userID));
     }
     $limit = 0;
     if (is_array($options) && isset($options['LIMIT'])) {
         $limit = (int) $options['LIMIT'];
     }
     if ($limit > 0) {
         $query->setLimit($limit);
     }
     $dbResult = $query->exec();
     $fields = $dbResult->fetch();
     return is_array($fields) && isset($fields['QTY']) ? intval($fields['QTY']) : 0;
 }
Esempio n. 6
0
 protected function processActionShowObjectInGrid()
 {
     if (!$this->checkRequiredGetParams(array('objectId'))) {
         $this->sendJsonErrorResponse();
     }
     /** @var Folder|File $object */
     $object = BaseObject::loadById((int) $this->request->getQuery('objectId'), array('STORAGE'));
     if (!$object) {
         $this->errorCollection->addOne(new Error('Could not find file or folder', self::ERROR_COULD_NOT_FIND_FILE));
         $this->sendJsonErrorResponse();
     }
     $storage = $object->getStorage();
     $securityContext = $storage->getCurrentUserSecurityContext();
     if (!$object->canRead($securityContext)) {
         $this->errorCollection->addOne(new Error('Could not find file or folder', self::ERROR_COULD_NOT_READ_FILE));
         $this->sendJsonErrorResponse();
     }
     $gridOptions = new Internals\Grid\FolderListOptions($storage);
     $pageSize = $gridOptions->getPageSize();
     $parameters = array('select' => array('ID'), 'filter' => array('PARENT_ID' => $object->getParentId(), 'DELETED_TYPE' => ObjectTable::DELETED_TYPE_NONE), 'order' => $gridOptions->getOrderForOrm(), 'limit' => $pageSize);
     $countQuery = new Query(ObjectTable::getEntity());
     $countQuery->addSelect(new ExpressionField('CNT', 'COUNT(1)'));
     $countQuery->setFilter($parameters['filter']);
     $totalCount = $countQuery->setLimit(null)->setOffset(null)->exec()->fetch();
     $totalCount = $totalCount['CNT'];
     $pageCount = ceil($totalCount / $pageSize);
     $driver = Driver::getInstance();
     $finalPage = null;
     for ($pageNumber = 1; $pageNumber <= $pageCount; $pageNumber++) {
         $fullParameters = $driver->getRightsManager()->addRightsCheck($securityContext, $parameters, array('ID', 'CREATED_BY'));
         $fullParameters['offset'] = $pageSize * ($pageNumber - 1);
         $query = ObjectTable::getList($fullParameters);
         while ($row = $query->fetch()) {
             if ($row['ID'] == $object->getId()) {
                 $finalPage = $pageNumber;
                 break;
             }
         }
         if ($finalPage !== null) {
             break;
         }
     }
     $finalPage = $finalPage ?: 1;
     $command = $this->request->getQuery('cmd') ?: '';
     if ($command) {
         $command = '!' . $command;
     }
     LocalRedirect($driver->getUrlManager()->getPathInListing($object) . "?&pageNumber={$finalPage}#hl-" . $object->getId() . $command);
 }
Esempio n. 7
0
 /**
  * Deletes unnecessary files, which don't relate to version or object.
  *
  * @param int $portion Count of files which we want to delete. Default value is 10.
  * @return string
  */
 public static function deleteUnnecessaryFiles($portion = 10)
 {
     $query = new Query(FileTable::getEntity());
     $query->addSelect('ID')->addFilter('=EXTERNAL_ID', 'unnecessary')->addFilter('=MODULE_ID', Driver::INTERNAL_MODULE_ID)->setLimit($portion);
     $workLoad = false;
     $dbResult = $query->exec();
     while ($row = $dbResult->fetch()) {
         $workLoad = true;
         \CFile::delete($row['ID']);
     }
     if (!$workLoad) {
         return '';
     }
     return static::className() . '::deleteUnnecessaryFiles();';
 }
 /**
  * @return boolean
  */
 public static function isRegistered($ownerID)
 {
     if (!is_int($ownerID)) {
         $ownerID = (int) $ownerID;
     }
     if ($ownerID <= 0) {
         throw new Main\ArgumentException('Owner ID must be greater than zero.', 'ownerID');
     }
     $query = new Query(DealInvoiceStatisticsTable::getEntity());
     $query->addSelect('CREATED_DATE');
     $query->addFilter('=OWNER_ID', $ownerID);
     $query->setLimit(1);
     $dbResult = $query->exec();
     $result = $dbResult->fetch();
     return is_array($result);
 }
 function elemGetEx($elemId = false)
 {
     $hlHandler = $this->hlHandler;
     $getList = new Entity\Query($hlHandler);
     $getList->setSelect(array('*'));
     $getList->setOrder(array("ID" => "ASC"));
     if (!empty($elemId)) {
         $getList->setFilter(array("ID" => $elemId));
     }
     $result = $getList->exec();
     $result = new CDBResult($result);
     $arRes = array();
     while ($row = $result->Fetch()) {
         $arRes[] = $row;
     }
     return $arRes;
 }
Esempio n. 10
0
 public static function checkFields(Result $result, $primary, array $data)
 {
     parent::checkFields($result, $primary, $data);
     if (!$result->isSuccess()) {
         return;
     }
     $query = new Entity\Query(static::getEntity());
     $res = $query->setSelect(array('ID', 'STATUS'))->setFilter(array('=TO_ENTITY' => $data['TO_ENTITY'], '=REAL_OBJECT_ID' => $data['REAL_OBJECT_ID']))->setLimit(2)->exec();
     while ($existing = $res->fetch()) {
         if (!isset($primary) || $primary != $existing['ID']) {
             if ($existing['STATUS'] == self::STATUS_IS_DECLINED) {
                 static::delete($existing['ID']);
             } else {
                 $result->addError(new Entity\EntityError(Loc::getMessage("DISK_SHARING_ENTITY_ERROR_NON_UNIQUE")));
             }
         }
     }
 }
Esempio n. 11
0
 protected function buildQuery()
 {
     if ($this->useIblockSearch()) {
         $this->appendIblockRelatedData();
     } else {
         $entityClass = $this->getEntity()->getDataClass();
         $this->filter['IBLOCK_ID'] = $entityClass::getIblockId();
     }
     return parent::buildQuery();
 }
Esempio n. 12
0
 public function validate($value, $primary, array $row, Entity\Field $field)
 {
     $entity = $field->getEntity();
     $primaryNames = $entity->getPrimaryArray();
     $query = new Entity\Query($entity);
     $query->setSelect($primaryNames);
     $query->setFilter(array('=' . $field->getName() => $value));
     $query->setLimit(2);
     $result = $query->exec();
     while ($existing = $result->fetch()) {
         // check primary
         foreach ($existing as $k => $v) {
             if (!isset($primary[$k]) || $primary[$k] != $existing[$k]) {
                 return $this->getErrorMessage($value, $field);
             }
         }
     }
     return true;
 }
 public static function getMismatches($entityTypeID, $entityID, $typeID, $matchHash, $userID, $limit = 0)
 {
     if (!is_int($limit)) {
         $limit = (int) $limit;
     }
     $results = array();
     $query = new Main\Entity\Query(Entity\DuplicateIndexMismatchTable::getEntity());
     $query->addSelect('R_ENTITY_ID', 'ENTITY_ID');
     $query->addFilter('=USER_ID', $userID);
     $query->addFilter('=ENTITY_TYPE_ID', $entityTypeID);
     $query->addFilter('=TYPE_ID', $typeID);
     $query->addFilter('=MATCH_HASH', $matchHash);
     $query->addFilter('=L_ENTITY_ID', $entityID);
     if ($limit > 0) {
         $query->addOrder('R_ENTITY_ID', 'ASC');
         $query->setLimit($limit);
     }
     $dbResult = $query->exec();
     while ($fields = $dbResult->fetch()) {
         $results[] = (int) $fields['ENTITY_ID'];
     }
     $query = new Main\Entity\Query(Entity\DuplicateIndexMismatchTable::getEntity());
     $query->addSelect('L_ENTITY_ID', 'ENTITY_ID');
     $query->addFilter('=USER_ID', $userID);
     $query->addFilter('=ENTITY_TYPE_ID', $entityTypeID);
     $query->addFilter('=TYPE_ID', $typeID);
     $query->addFilter('=MATCH_HASH', $matchHash);
     $query->addFilter('=R_ENTITY_ID', $entityID);
     if ($limit > 0) {
         $query->addOrder('L_ENTITY_ID', 'ASC');
         $query->setLimit($limit);
     }
     $dbResult = $query->exec();
     while ($fields = $dbResult->fetch()) {
         $results[] = (int) $fields['ENTITY_ID'];
     }
     return $results;
 }
Esempio n. 14
0
 /**
  * Method searches for a custom filter that, needs updating (notifications of new elements).
  * Custom filters are added to the stack of tasks.
  *
  * @param int $limitFilter
  * @return string
  */
 public static function findUserFilterNotify($limitFilter = 1, $limitFilterUser = 100)
 {
     $iblockElement = new \CIBlockElement();
     $connection = \Bitrix\Main\Application::getConnection();
     $sqlHelper = $connection->getSqlHelper();
     $limitFilter = (int) $limitFilter;
     $limitFilterUser = (int) $limitFilterUser;
     if ($limitFilterUser <= 0 || $limitFilterUser <= 0) {
         return;
     }
     $queryBuilder = new Entity\Query(Model\SubscribeTable::getEntity());
     $filterResult = $queryBuilder->setSelect(array('*'))->setFilter(array('ACTIVE' => 'Y'))->setLimit($limitFilter)->exec();
     while ($filterRow = $filterResult->fetch()) {
         $filter['IBLOCK_ID'] = $filterRow['IBLOCK_ID'];
         if ($filterRow['SECTION_ID'] > 0) {
             $filter['SECTION_ID'] = $filterRow['SECTION_ID'];
         }
         $filter = array_merge($filter, unserialize($filterRow['FILTER']));
         $elementResult = $iblockElement->GetList(false, $filter, array('IBLOCK_ID'))->fetch();
         if ($elementResult['CNT'] <= 0) {
             continue;
         }
         // Choose filters which notification less,
         // than the number of elements with filter
         $sql = "\n                SELECT DISTINCT t1.ID\n                FROM b_citfact_filter_subscribe_user as t1\n                LEFT OUTER JOIN b_citfact_filter_subscribe_notify as t2 ON (\n                    t1.ID = t2.FILTER_USER_ID AND\n                    t1.FILTER_ID = '" . $sqlHelper->forSql($filterRow['ID']) . "'\n                )\n                WHERE (SELECT count(ID) FROM b_citfact_filter_subscribe_notify as t3 WHERE t3.FILTER_USER_ID = t1.ID) < '" . $sqlHelper->forSql($elementResult['CNT']) . "'\n                GROUP BY t1.ID\n                LIMIT 0," . $limitFilterUser . "\n            ";
         // Adding custom filters to stack table
         $notifyList = (array) $connection->query($sql)->fetchAll();
         foreach ($notifyList as $key => $notify) {
             Model\SubscribeStackTable::add(array('FILTER_USER_ID' => $notify['ID'], 'ACTION' => 'UPDATE'));
         }
         // If list for stack table is not empty, then deactivate filter
         if (sizeof($notifyList) > 0) {
             Model\SubscribeTable::update($filterRow['ID'], array('ACTIVE' => 'N'));
         }
     }
     return "Citfact\\FilterSubscribe\\Agent::findUserFilterNotify({$limitFilter})";
 }
Esempio n. 15
0
 /** @return array */
 public function prepareEntityListFilter(array $filterParams)
 {
     $filter = self::internalizeFilter($filterParams);
     $query = new Query(DealStageHistoryTable::getEntity());
     $query->addSelect('OWNER_ID');
     $query->addGroup('OWNER_ID');
     $period = $filter->getPeriod();
     $periodStartDate = $period['START'];
     $periodEndDate = $period['END'];
     $query->addFilter('=TYPE_ID', HistoryEntryType::CREATION);
     $query->addFilter('>=START_DATE', $periodStartDate);
     $query->addFilter('<=START_DATE', $periodEndDate);
     $query->registerRuntimeField('', new ExpressionField('E1', '(CASE WHEN NOT EXISTS(' . self::prepareHistoryQuery($periodStartDate, $periodEndDate, HistoryEntryType::MODIFICATION, '%s', '_i')->getQuery() . ') THEN 1 ELSE 0 END)', 'OWNER_ID'));
     $query->addFilter('=E1', 1);
     $query->registerRuntimeField('', new ExpressionField('E2', '(CASE WHEN NOT EXISTS(' . self::prepareHistoryQuery($periodStartDate, $periodEndDate, HistoryEntryType::FINALIZATION, '%s', '_i')->getQuery() . ') THEN 1 ELSE 0 END)', 'OWNER_ID'));
     $query->addFilter('=E2', 1);
     $query->registerRuntimeField('', new ExpressionField('E3', '(CASE WHEN NOT EXISTS(' . self::prepareActivityQuery($periodStartDate, $periodEndDate, '%s')->getQuery() . ') THEN 1 ELSE 0 END)', 'OWNER_ID'));
     $query->addFilter('=E3', 1);
     $query->registerRuntimeField('', new ExpressionField('E4', '(CASE WHEN NOT EXISTS(' . self::prepareInvoiceQuery($periodStartDate, $periodEndDate, '%s')->getQuery() . ') THEN 1 ELSE 0 END)', 'OWNER_ID'));
     $query->addFilter('=E4', 1);
     $responsibleIDs = $filter->getResponsibleIDs();
     if (!empty($responsibleIDs)) {
         $query->addFilter('@RESPONSIBLE_ID', $responsibleIDs);
     }
     return array('__JOINS' => array(array('TYPE' => 'INNER', 'SQL' => 'INNER JOIN(' . $query->getQuery() . ') DS ON DS.OWNER_ID = L.ID')));
 }
Esempio n. 16
0
 public static function getCount()
 {
     $query = new Query(static::getEntity());
     $query->setSelect(array('CNT' => array('expression' => array('COUNT(*)'), 'data_type' => 'integer')));
     $result = $query->exec()->fetch();
     return $result['CNT'];
 }
        $navyParams['PAGEN'] = (int) $navyParams['PAGEN'];
        $navyParams['SIZEN'] = (int) $navyParams['SIZEN'];
    }
}
if ($selectFields['PROPERTY_TYPE']) {
    $selectFields['USER_TYPE'] = true;
}
$selectFields = array_keys($selectFields);
$getListParams = array('select' => $selectFields, 'filter' => $arFilter, 'order' => $propertyOrder);
if ($usePageNavigation) {
    $getListParams['limit'] = $navyParams['SIZEN'];
    $getListParams['offset'] = $navyParams['SIZEN'] * ($navyParams['PAGEN'] - 1);
}
$totalPages = 0;
if ($usePageNavigation) {
    $countQuery = new Main\Entity\Query(Iblock\PropertyTable::getEntity());
    $countQuery->addSelect(new Main\Entity\ExpressionField('CNT', 'COUNT(1)'));
    $countQuery->setFilter($getListParams['filter']);
    $totalCount = $countQuery->setLimit(null)->setOffset(null)->exec()->fetch();
    unset($countQuery);
    $totalCount = (int) $totalCount['CNT'];
    if ($totalCount > 0) {
        $totalPages = ceil($totalCount / $navyParams['SIZEN']);
        if ($navyParams['PAGEN'] > $totalPages) {
            $navyParams['PAGEN'] = $totalPages;
        }
        $getListParams['limit'] = $navyParams['SIZEN'];
        $getListParams['offset'] = $navyParams['SIZEN'] * ($navyParams['PAGEN'] - 1);
    } else {
        $navyParams['PAGEN'] = 1;
        $getListParams['limit'] = $navyParams['SIZEN'];
 public static function synchronize($ownerID, array $entityFields = null)
 {
     if (!is_int($ownerID)) {
         $ownerID = (int) $ownerID;
     }
     if ($ownerID <= 0) {
         throw new Main\ArgumentException('Owner ID must be greater than zero.', 'ownerID');
     }
     $query = new Query(DealStageHistoryTable::getEntity());
     $query->addSelect('START_DATE');
     $query->addSelect('END_DATE');
     $query->addSelect('RESPONSIBLE_ID');
     $query->addFilter('=OWNER_ID', $ownerID);
     $query->setLimit(1);
     $dbResult = $query->exec();
     $first = $dbResult->fetch();
     if (!is_array($first)) {
         return false;
     }
     if (!is_array($entityFields)) {
         $dbResult = \CCrmDeal::GetListEx(array(), array('=ID' => $ownerID, 'CHECK_PERMISSIONS' => 'N'), false, false, array('ASSIGNED_BY_ID', 'BEGINDATE', 'CLOSEDATE'));
         $entityFields = is_object($dbResult) ? $dbResult->Fetch() : null;
         if (!is_array($entityFields)) {
             return false;
         }
     }
     $responsibleID = isset($entityFields['ASSIGNED_BY_ID']) ? (int) $entityFields['ASSIGNED_BY_ID'] : 0;
     $beginDate = isset($entityFields['BEGINDATE']) ? $entityFields['BEGINDATE'] : '';
     /** @var Date $startDate */
     $startDate = new Date($beginDate);
     $closeDate = isset($entityFields['CLOSEDATE']) ? $entityFields['CLOSEDATE'] : '';
     /** @var Date $endDate */
     $endDate = $closeDate !== '' ? new Date($closeDate) : new Date('9999-12-31', 'Y-m-d');
     if ($startDate->getTimestamp() === $first['START_DATE']->getTimestamp() && $endDate->getTimestamp() === $first['END_DATE']->getTimestamp() && $responsibleID === (int) $first['RESPONSIBLE_ID']) {
         return false;
     }
     DealStageHistoryTable::synchronize($ownerID, array('START_DATE' => $startDate, 'END_DATE' => $endDate, 'RESPONSIBLE_ID' => $responsibleID));
     return true;
 }
Esempio n. 19
0
}
use Bitrix\Highloadblock as HL;
use Bitrix\Main\Entity;
global $USER_FIELD_MANAGER;
// hlblock info
$hlblock_id = $arParams['BLOCK_ID'];
if (empty($hlblock_id)) {
    ShowError(GetMessage('HLBLOCK_VIEW_NO_ID'));
    return 0;
}
$hlblock = HL\HighloadBlockTable::getById($hlblock_id)->fetch();
if (empty($hlblock)) {
    ShowError('404');
    return 0;
}
$entity = HL\HighloadBlockTable::compileEntity($hlblock);
// row data
$main_query = new Entity\Query($entity);
$main_query->setSelect(array('*'));
$main_query->setFilter(array('=ID' => $arParams['ROW_ID']));
$result = $main_query->exec();
$result = new CDBResult($result);
$row = $result->Fetch();
$fields = $USER_FIELD_MANAGER->getUserFieldsWithReadyData('HLBLOCK_' . $hlblock['ID'], $row, LANGUAGE_ID);
if (empty($row)) {
    ShowError(sprintf(GetMessage('HLBLOCK_VIEW_NO_ROW'), $arParams['ROW_ID']));
    return 0;
}
$arResult['fields'] = $fields;
$arResult['row'] = $row;
$this->IncludeComponentTemplate();
Esempio n. 20
0
<?php

/*
 * This file is part of the Studio Fact package.
 *
 * (c) Kulichkin Denis (onEXHovia) <*****@*****.**>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
use Bitrix\Main\Localization\Loc;
use Bitrix\Main\Entity;
use Bitrix\Main\Loader;
use Citfact\UserVars\Model;
Loc::loadMessages(__FILE__);
Loader::includeModule('citfact.uservars');
$queryBuilder = new Entity\Query(Model\VarsGroupTable::getEntity());
$queryBuilder->setSelect(array('ID', 'NAME', 'CODE'))->setOrder(array('ID' => 'ASC'));
$varsGroupResult = $queryBuilder->exec();
$varsGroupList = array();
while ($group = $varsGroupResult->fetch()) {
    $varsGroupList[] = array('text' => $group['NAME'], 'url' => 'user_vars_list.php?GROUP_ID=' . $group['ID'] . '&lang=' . LANG, 'module_id' => 'user_vars', 'more_url' => array('user_vars_edit.php?GROUP_ID=' . $group['ID'] . '&lang=' . LANG));
}
$menuList[] = array('parent_menu' => Loader::includeModule('citfact.core') ? 'global_menu_citfact' : 'global_menu_services', 'section' => 'user_vars', 'sort' => 200, 'text' => Loc::getMessage('USER_VARS_TITLE'), 'url' => 'user_vars.php?lang=' . LANGUAGE_ID, 'icon' => 'user_vars_menu_icon', 'page_icon' => 'user_vars_page_icon', 'more_url' => array('user_vars_group_edit.php'), 'items_id' => 'uservars_menu', 'items' => $varsGroupList);
return $menuList;
Esempio n. 21
0
 /**
  * Set values for property with type G(link to section).
  */
 protected function setSectionValue()
 {
     $iblockList = $this->getListByType('G');
     $queryBuilder = new Entity\Query(Iblock\SectionTable::getEntity());
     $queryBuilder->setSelect(array('ID', 'NAME', 'IBLOCK_ID', 'IBLOCK_SECTION_ID', 'XML_ID'))->setFilter(array('IBLOCK_ID' => $iblockList))->setOrder(array());
     $sectionResult = $queryBuilder->exec();
     while ($section = $sectionResult->fetch()) {
         foreach ($this->iblockProperty as &$field) {
             if ($field['PROPERTY_TYPE'] != 'G') {
                 continue;
             }
             if ($field['LINK_IBLOCK_ID'] == $section['IBLOCK_ID']) {
                 $field['VALUE_LIST'][] = $section;
             }
         }
     }
 }
Esempio n. 22
0
 public static function getInstanceByQuery(Query $query, &$entity_name = null)
 {
     if ($entity_name === null) {
         $entity_name = 'Tmp' . randString();
     } elseif (!preg_match('/^[a-z0-9_]+$/i', $entity_name)) {
         throw new Main\ArgumentException(sprintf('Invalid entity name `%s`.', $entity_name));
     }
     $query_string = '(' . $query->getQuery() . ')';
     $query_chains = $query->getChains();
     $replaced_aliases = array_flip($query->getReplacedAliases());
     // generate fieldsMap
     $fieldsMap = array('TMP_ID' => array('data_type' => 'integer', 'primary' => true));
     foreach ($query->getSelect() as $k => $v) {
         if (is_array($v)) {
             // expression
             $fieldsMap[$k] = array('data_type' => $v['data_type']);
         } else {
             if ($v instanceof ExpressionField) {
                 $fieldDefinition = $v->getName();
             } else {
                 $fieldDefinition = is_numeric($k) ? $v : $k;
             }
             // better to initialize fields as objects after entity is created
             $dataType = Field::getOldDataTypeByField($query_chains[$fieldDefinition]->getLastElement()->getValue());
             $fieldsMap[$fieldDefinition] = array('data_type' => $dataType);
         }
         if (isset($replaced_aliases[$k])) {
             $fieldsMap[$k]['column_name'] = $replaced_aliases[$k];
         }
     }
     // generate class content
     $eval = 'class ' . $entity_name . 'Table extends ' . __NAMESPACE__ . '\\DataManager {' . PHP_EOL;
     $eval .= 'public static function getMap() {' . PHP_EOL;
     $eval .= 'return ' . var_export($fieldsMap, true) . ';' . PHP_EOL;
     $eval .= '}';
     $eval .= 'public static function getTableName() {' . PHP_EOL;
     $eval .= 'return ' . var_export($query_string, true) . ';' . PHP_EOL;
     $eval .= '}';
     $eval .= '}';
     eval($eval);
     return self::getInstance($entity_name);
 }
Esempio n. 23
0
 protected static function getHourlyCompanyActivitySince(Type\DateTime $hour = null)
 {
     $query = new Entity\Query('Bitrix\\Intranet\\UStat\\UserHourTable');
     // set all activity columns
     $uStatFields = UserHourTable::getEntity()->getFields();
     foreach ($uStatFields as $uStatField) {
         if ($uStatField instanceof Entity\ScalarField && !$uStatField->isPrimary()) {
             $query->addSelect(new Entity\ExpressionField($uStatField->getName() . '_SUM', 'SUM(%s)', $uStatField->getName()));
         }
     }
     // add & automatically group by hour
     $query->addSelect('HOUR');
     // add filter by date
     if ($hour !== null) {
         $query->setFilter(array('>=HOUR' => \ConvertTimeStamp($hour->getTimestamp(), 'FULL')));
     }
     // collect activity
     $activity = array();
     $result = $query->exec();
     while ($row = $result->fetch()) {
         foreach ($row as $k => $v) {
             if (substr($k, -4) === '_SUM') {
                 $row[substr($k, 0, -4)] = $v;
                 unset($row[$k]);
             }
         }
         $activity[] = $row;
     }
     return $activity;
 }
Esempio n. 24
0
 /**
  * This method is for internal use only. It may be changed without any notification further, or even mystically disappear.
  * 
  * @access private
  */
 public static function getSubtreeRangeSqlForNode($primary, $node = array())
 {
     $primary = Assert::expectIntegerPositive($primary, '$primary');
     if (empty($node)) {
         $node = self::getNodeInfo($primary);
         if (!intval($node['ID'])) {
             throw new Main\SystemException('Node being checked not found');
         }
     }
     if (isset($node['LEFT_MARGIN']) && isset($node['RIGHT_MARGIN'])) {
         $query = new Main\Entity\Query(static::getEntity());
         $query->setSelect(array('ID'));
         $query->setFilter(array('>LEFT_MARGIN' => $node['LEFT_MARGIN'], '<RIGHT_MARGIN' => $node['RIGHT_MARGIN']));
         return $query->getQuery();
     } else {
         throw new Main\SystemException('Node not found or incorrect node info passed');
     }
 }
 /**
  * @return boolean
  */
 public static function synchronize($ownerID, array $entityFields = null)
 {
     if (!is_int($ownerID)) {
         $ownerID = (int) $ownerID;
     }
     if ($ownerID <= 0) {
         throw new Main\ArgumentException('Owner ID must be greater than zero.', 'ownerID');
     }
     $query = new Query(DealActivityStatisticsTable::getEntity());
     $query->addSelect('RESPONSIBLE_ID');
     $query->addFilter('=OWNER_ID', $ownerID);
     $query->setLimit(1);
     $dbResult = $query->exec();
     $first = $dbResult->fetch();
     if (!is_array($first)) {
         return false;
     }
     if (!is_array($entityFields)) {
         $dbResult = \CCrmDeal::GetListEx(array(), array('=ID' => $ownerID, 'CHECK_PERMISSIONS' => 'N'), false, false, array('ASSIGNED_BY_ID'));
         $entityFields = is_object($dbResult) ? $dbResult->Fetch() : null;
         if (!is_array($entityFields)) {
             return false;
         }
     }
     $responsibleID = isset($entityFields['ASSIGNED_BY_ID']) ? (int) $entityFields['ASSIGNED_BY_ID'] : 0;
     if ($responsibleID === (int) $first['RESPONSIBLE_ID']) {
         return false;
     }
     DealActivityStatisticsTable::synchronize($ownerID, array('RESPONSIBLE_ID' => $responsibleID));
     return true;
 }
Esempio n. 26
0
 }
 CReport::rewriteUserShortName($grcSelect, $runtime, $arParams['USER_NAME_FORMAT'], $entity, true);
 // add primary of grc entity field
 $grcChain = Entity\QueryChain::getChainByDefinition($entity, $elem['name']);
 $grc_field = $grcChain->getLastElement()->getValue();
 if (is_array($grc_field)) {
     $grc_field = end($grc_field);
 }
 $grc_primary = end($grc_field->getEntity()->getPrimaryArray());
 $grc_marker = substr($elem['name'], 0, strrpos($elem['name'], '.')) . '.' . $grc_primary;
 $grc_marker_alias = Entity\QueryChain::getAliasByDefinition($entity, $grc_marker);
 $grcSelect[$grc_marker_alias] = $grc_marker;
 // select
 $resultName = $viewColumns[$num]['resultName'];
 $grcData[$resultName] = array();
 $grc_query = new Entity\Query($entity);
 $grc_query->setSelect($grcSelect);
 $grc_query->setFilter($grcFilter);
 foreach ($runtime as $k => $v) {
     $grc_query->registerRuntimeField($k, $v);
 }
 $result = $grc_query->exec();
 while ($row = $result->fetch()) {
     if (empty($row[$grc_marker_alias])) {
         continue;
     }
     $grcData[$resultName][] = $row;
 }
 // add empty values to data
 foreach ($data as $k => $v) {
     $data[$k][$alias] = null;
Esempio n. 27
0
 /**
  * @return Query
  */
 protected static function prepareInvoiceQuery($startDate, $endDate, $responsibleIDs = null, $groupByDate = true)
 {
     $query = new Query(DealInvoiceStatisticsTable::getEntity());
     $query->addSelect('OWNER_ID');
     $query->addFilter('=IS_LOST', false);
     $query->addFilter('>=CREATED_DATE', $startDate);
     $query->addFilter('<=CREATED_DATE', $endDate);
     $query->addGroup('OWNER_ID');
     if (is_array($responsibleIDs) && !empty($responsibleIDs)) {
         $query->addFilter('@RESPONSIBLE_ID', $responsibleIDs);
     }
     if ($groupByDate) {
         $query->addSelect('CREATED_DATE', 'DATE');
         $query->addGroup('CREATED_DATE');
         $query->addOrder('CREATED_DATE', 'ASC');
     }
     return $query;
 }
Esempio n. 28
0
 protected function getFilterCswFields(&$filter)
 {
     $fields = array();
     foreach ($filter as $filter_def => &$filter_match) {
         if ($filter_def === 'LOGIC') {
             continue;
         }
         if (!is_numeric($filter_def)) {
             $csw_result = \CSQLWhere::makeOperation($filter_def);
             list($definition, ) = array_values($csw_result);
             $chain = $this->filter_chains[$definition];
             $last = $chain->getLastElement();
             // need to create an alternative of CSQLWhere in D7.Entity
             $field_type = $last->getValue()->getDataType();
             // rewrite type & value for CSQLWhere
             if ($field_type == 'integer') {
                 $field_type = 'int';
             } elseif ($field_type == 'boolean') {
                 $field_type = 'string';
                 /** @var BooleanField $field */
                 $field = $last->getValue();
                 $values = $field->getValues();
                 if (is_numeric($values[0]) && is_numeric($values[1])) {
                     $field_type = 'int';
                 }
                 if (is_scalar($filter_match)) {
                     $filter_match = $field->normalizeValue($filter_match);
                 }
             } elseif ($field_type == 'float') {
                 $field_type = 'double';
             } elseif ($field_type == 'enum' || $field_type == 'text') {
                 $field_type = 'string';
             }
             $sqlDefinition = $chain->getSqlDefinition();
             $callback = null;
             // data-doubling-off mode
             /** @see disableDataDoubling */
             if ($chain->forcesDataDoublingOff() || $this->data_doubling_off && $chain->hasBackReference()) {
                 $primaryName = $this->init_entity->getPrimary();
                 $uniquePostfix = '_TMP' . rand();
                 // build subquery
                 $subQuery = new Query($this->init_entity);
                 $subQuery->addSelect($primaryName);
                 $subQuery->addFilter($filter_def, $filter_match);
                 $subQuery->setTableAliasPostfix(strtolower($uniquePostfix));
                 $subQuerySql = $subQuery->getQuery();
                 // proxying subquery as value to callback
                 $filter_match = $subQuerySql;
                 $callback = array($this, 'dataDoublingCallback');
                 $field_type = 'callback';
                 // change sql definition
                 $idChain = $this->getRegisteredChain($primaryName);
                 $sqlDefinition = $idChain->getSqlDefinition();
             }
             //$is_having = $last->getValue() instanceof ExpressionField && $last->getValue()->isAggregated();
             // if back-reference found (Entity:REF)
             // if NO_DOUBLING mode enabled, then change getSQLDefinition to subquery exists(...)
             // and those chains should not be in joins if it is possible
             /*if (!$this->data_doubling && $chain->hasBackReference())
             				{
             					$field_type = 'callback';
             					$init_query = $this;
             
             					$callback = function ($field, $operation, $value) use ($init_query, $chain)
             					{
             						$init_entity = $init_query->getEntity();
             						$init_table_alias = CBaseEntity::camel2snake($init_entity->getName()).$init_query->getTableAliasPostfix();
             
             						$filter = array();
             
             						// add primary linking with main query
             						foreach ($init_entity->getPrimaryArray() as $primary)
             						{
             							$filter['='.$primary] = new CSQLWhereExpression('?#', $init_table_alias.'.'.$primary);
             						}
             
             						// add value filter
             						$filter[CSQLWhere::getOperationByCode($operation).$chain->getDefinition()] = $value;
             
             						// build subquery
             						$query_class = __CLASS__;
             						$sub_query = new $query_class($init_entity);
             						$sub_query->setFilter($filter);
             						$sub_query->setTableAliasPostfix('_sub');
             
             						return 'EXISTS(' . $sub_query->getQuery() . ')';
             					};
             				}*/
             $fields[$definition] = array('TABLE_ALIAS' => 'table', 'FIELD_NAME' => $sqlDefinition, 'FIELD_TYPE' => $field_type, 'MULTIPLE' => '', 'JOIN' => '', 'CALLBACK' => $callback);
         }
         if (is_array($filter_match)) {
             $fields = array_merge($fields, $this->getFilterCswFields($filter_match));
         }
     }
     return $fields;
 }
 /** @return array */
 public function prepareEntityListFilter(array $filterParams)
 {
     $filter = self::internalizeFilter($filterParams);
     $query = new Query(DealInvoiceStatisticsTable::getEntity());
     $query->addSelect('OWNER_ID');
     $query->addGroup('OWNER_ID');
     $period = $filter->getPeriod();
     $periodStartDate = $period['START'];
     $periodEndDate = $period['END'];
     $query->addFilter('>=END_DATE', $periodStartDate);
     $query->addFilter('<=START_DATE', $periodEndDate);
     $responsibleIDs = $filter->getResponsibleIDs();
     if (!empty($responsibleIDs)) {
         $query->addFilter('@RESPONSIBLE_ID', $responsibleIDs);
     }
     $semanticID = $filter->getExtraParam('semanticID', PhaseSemantics::UNDEFINED);
     if ($semanticID !== PhaseSemantics::UNDEFINED) {
         $query->addFilter('=STAGE_SEMANTIC_ID', $semanticID);
     }
     return array('__JOINS' => array(array('TYPE' => 'INNER', 'SQL' => 'INNER JOIN(' . $query->getQuery() . ') DS ON DS.OWNER_ID = L.ID')));
 }
Esempio n. 30
0
if (!isset($dataGroup) || empty($dataGroup)) {
    LocalRedirect(sprintf('user_vars.php?lang=%s', LANGUAGE_ID));
}
$includePath = array('prolog' => '/bitrix/modules/main/include/prolog_admin_after.php', 'prolog_js' => '/bitrix/modules/main/include/prolog_admin_js.php', 'epilog' => '/bitrix/modules/main/include/epilog_admin.php', 'epilog_js' => '/bitrix/modules/main/include/epilog_admin_js.php');
$contextMenu[] = array('TEXT' => Loc::getMessage('USER_VARS_ADD'), 'TITLE' => Loc::getMessage('USER_VARS_ADD'), 'LINK' => 'user_vars_edit.php?GROUP_ID=' . $dataGroup['ID'] . '&lang=' . LANGUAGE_ID, 'ICON' => 'btn_new');
$contextMenu[] = array('TEXT' => Loc::getMessage('USER_VARS_EDIT_GROUP'), 'TITLE' => Loc::getMessage('USER_VARS_EDIT_GROUP'), 'LINK' => 'user_vars_group_edit.php?ID=' . $dataGroup['ID'] . '&lang=' . LANGUAGE_ID, 'ICON' => 'btn_edit');
$varsMap = Model\VarsTable::getMap();
$headers = array(array('id' => 'ID', 'content' => 'ID', 'sort' => 'ID', 'default' => true), array('id' => 'NAME', 'content' => $varsMap['NAME']['title'], 'sort' => 'NAME', 'default' => true), array('id' => 'CODE', 'content' => $varsMap['CODE']['title'], 'sort' => 'CODE', 'default' => true), array('id' => 'VALUE', 'content' => $varsMap['VALUE']['title'], 'sort' => 'VALUE', 'default' => true), array('id' => 'DESCRIPTION', 'content' => $varsMap['DESCRIPTION']['title'], 'sort' => 'DESCRIPTION', 'default' => true));
$tableId = 'tbl_user_vars_list';
$adminSort = new CAdminSorting($tableId, 'NAME', 'asc');
$adminList = new CAdminList($tableId, $adminSort);
$adminList->addHeaders($headers);
if ($request->getQuery('mode') != 'list') {
    $context = new CAdminContextMenu($contextMenu);
}
$queryBuilder = new Entity\Query(Model\VarsTable::getEntity());
$queryBuilder->setSelect(array('ID', 'NAME', 'CODE', 'DESCRIPTION', 'VALUE'))->setFilter(array('GROUP_ID' => $dataGroup['ID']));
$sortBy = $request->getQuery('by') ? strtoupper($request->getQuery('by')) : 'ID';
$sortOrder = $request->getQuery('order') ?: 'asc';
$queryBuilder->setOrder(array($sortBy => $sortOrder));
$resultData = new CAdminResult($queryBuilder->exec(), $tableId);
$resultData->navStart();
$adminList->navText($resultData->getNavPrint(Loc::getMessage('PAGES')));
while ($item = $resultData->fetch()) {
    $row = $adminList->addRow($item['ID'], $item);
    $actions = array();
    $actions[] = array('ICON' => 'edit', 'TEXT' => Loc::GetMessage('USER_VARS_ACTION_EDIT_VAR'), 'ACTION' => $adminList->actionRedirect('user_vars_edit.php?ID=' . $item['ID'] . '&GROUP_ID=' . $dataGroup['ID']));
    $actions[] = array('ICON' => 'delete', 'TEXT' => Loc::getMessage('USER_VARS_ACTION_DELETE_VAR'), 'ACTION' => "if(confirm('" . Loc::getMessage('USER_VARS_DELETE_VAR_CONFIRM') . "')) " . $adminList->actionRedirect('user_vars_edit.php?action=delete&ID=' . $item['ID'] . '&GROUP_ID=' . $dataGroup['ID'] . '&' . bitrix_sessid_get()));
    $row->addActions($actions);
}
$prologType = $request->getQuery('mode') == 'list' ? 'prolog_js' : 'prolog';