protected static function uploadFile($name, $content, array $parameters = array()) { static::includeDisk(); $storage = Driver::getInstance()->getStorageByUserId($parameters['USER_ID']); if (!$storage) { throw new RestException("Could not find storage for user '" . $parameters['USER_ID'] . "'.", RestException::ERROR_NOT_FOUND); } $folder = $storage->getFolderForUploadedFiles(); if (!$folder) { return false; } $securityContext = $storage->getCurrentUserSecurityContext(); if (!$folder->canAdd($securityContext)) { throw new AccessException(); } $fileData = \CRestUtil::saveFile($content); if (!$fileData) { throw new RestException('Could not save file'); } $file = $folder->uploadFile($fileData, array('NAME' => $name, 'CREATED_BY' => $parameters['USER_ID']), array(), true); if (!$file) { //$folder->getErrors(); throw new RestException("Could not upload file to the storage"); } return $file->getId(); }
public static function mailserviceUpdate($arParams) { global $USER; IncludeModuleLangFile(__FILE__); if (!$USER->CanDoOperation('bitrix24_config')) { throw new Exception(GetMessage('ACCESS_DENIED')); } if (empty($arParams['ID'])) { throw new Exception(GetMessage('MAIL_MAILSERVICE_EMPTY_ID')); } $result = Bitrix\Mail\MailServicesTable::getList(array('filter' => array('=ID' => $arParams['ID'], '=SITE_ID' => SITE_ID))); if (!$result->fetch()) { throw new Exception(GetMessage('MAIL_MAILSERVICE_EMPTY')); } $arFields = array('ACTIVE' => $arParams['ACTIVE'], 'NAME' => $arParams['NAME'], 'SERVER' => $arParams['SERVER'], 'PORT' => $arParams['PORT'], 'ENCRYPTION' => $arParams['ENCRYPTION'], 'LINK' => $arParams['LINK'], 'ICON' => CRestUtil::saveFile($arParams['ICON']) ?: $arParams['ICON'], 'SORT' => $arParams['SORT']); foreach ($arFields as $name => $value) { if (empty($value)) { unset($arFields[$name]); } } $result = Bitrix\Mail\MailServicesTable::update($arParams['ID'], $arFields); if (!$result->isSuccess()) { throw new Exception(join('; ', $result->getErrorMessages())); } return true; }
/** * Gets fields which Externalizer or Internalizer should modify. * @return array */ public function getFieldsForMap() { return array('TYPE' => array('IN' => function ($externalValue) { switch ($externalValue) { case 'folder': return ObjectTable::TYPE_FOLDER; case 'file': return ObjectTable::TYPE_FILE; } return null; }, 'OUT' => function ($internalValue) { switch ($internalValue) { case ObjectTable::TYPE_FOLDER: return 'folder'; case ObjectTable::TYPE_FILE: return 'file'; } return null; }), 'CREATE_TIME' => array('IN' => function ($externalValue) { return \CRestUtil::unConvertDateTime($externalValue); }, 'OUT' => function (DateTime $internalValue = null) { return \CRestUtil::convertDateTime($internalValue); }), 'UPDATE_TIME' => array('IN' => function ($externalValue) { return \CRestUtil::unConvertDateTime($externalValue); }, 'OUT' => function (DateTime $internalValue = null) { return \CRestUtil::convertDateTime($internalValue); }), 'DELETE_TIME' => array('IN' => function ($externalValue) { return \CRestUtil::unConvertDateTime($externalValue); }, 'OUT' => function (DateTime $internalValue = null) { return \CRestUtil::convertDateTime($internalValue); })); }
public function Execute() { $activityData = $this->getRestActivityData(); if (!$activityData || !Loader::includeModule('rest')) { return CBPActivityExecutionStatus::Closed; } $propertiesData = array(); if (!empty($activityData['PROPERTIES'])) { foreach ($activityData['PROPERTIES'] as $name => $property) { $propertiesData[$name] = $this->{$name}; } } $auth = null; $userId = $this->AuthUserId; if ($userId > 0) { $auth = CRestUtil::getAuthForEvent($activityData['APP_ID'], $userId, array('WORKFLOW_ID' => $this->getWorkflowInstanceId(), 'ACTIVITY_NAME' => $this->name, 'CODE' => $activityData['CODE'])); } $this->eventId = \Bitrix\Main\Security\Random::getString(32, true); $queryItems = array(Sqs::queryItem($activityData['HANDLER'], array('workflow_id' => $this->getWorkflowInstanceId(), 'code' => $activityData['CODE'], 'event_token' => self::generateToken($this->getWorkflowInstanceId(), $this->name, $this->eventId), 'properties' => $propertiesData, 'auth' => $auth, 'ts' => time()))); Sqs::query($queryItems); if ($this->SetStatusMessage == 'Y') { $message = $this->StatusMessage; if (empty($message)) { $message = Loc::getMessage('BPRA_DEFAULT_STATUS_MESSAGE'); } $this->SetStatusTitle($message); } if ($this->isInEventActivityMode || $this->UseSubscription != 'Y') { return CBPActivityExecutionStatus::Closed; } $this->Subscribe($this); $this->isInEventActivityMode = false; return CBPActivityExecutionStatus::Executing; }
/** * Gets fields which Externalizer or Internalizer should modify. * @return array */ public function getFieldsForMap() { return array('CREATE_TIME' => array('IN' => function ($externalValue) { return \CRestUtil::unConvertDateTime($externalValue); }, 'OUT' => function (DateTime $internalValue = null) { return \CRestUtil::convertDateTime($internalValue); })); }
private function convertDateTimeFields($data) { if ($data instanceof DateTime) { return \CRestUtil::convertDateTime($data); } if (!is_array($data)) { return $data; } foreach ($data as $key => $item) { $data[$key] = $this->convertDateTimeFields($data[$key]); } unset($item); return $data; }
/** * Creates new version of file. * @param int $id Id of file. * @param string|array $fileContent File content. General format in REST. * @return Disk\Version|null * @throws AccessException * @throws RestException */ protected function uploadVersion($id, $fileContent) { $file = $this->getFileById($id); $securityContext = $file->getStorage()->getCurrentUserSecurityContext(); if (!$file->canUpdate($securityContext)) { throw new AccessException(); } $fileData = \CRestUtil::saveFile($fileContent); if (!$fileData) { throw new RestException('Could not save file.'); } $newFile = $file->uploadVersion($fileData, $this->userId); if (!$newFile) { $this->errorCollection->add($file->getErrors()); return null; } return $file; }
/** * Gets fields which Externalizer or Internalizer should modify. * @return array */ public function getFieldsForMap() { return array('CREATE_TIME' => array('IN' => function ($externalValue) { return \CRestUtil::unConvertDateTime($externalValue); }, 'OUT' => function (DateTime $internalValue = null) { return \CRestUtil::convertDateTime($internalValue); }), 'ENTITY_TYPE' => array('IN' => function ($externalValue) { switch ($externalValue) { case 'blog_comment': return BlogPostCommentConnector::className(); case 'blog_post': return BlogPostConnector::className(); case 'calendar_event': return CalendarEventConnector::className(); case 'forum_message': return ForumMessageConnector::className(); case 'tasks_task': return TaskConnector::className(); case 'sonet_log': return SonetLogConnector::className(); case 'sonet_comment': return SonetCommentConnector::className(); } return null; }, 'OUT' => function ($internalValue) { switch ($internalValue) { case BlogPostCommentConnector::className(): return 'blog_comment'; case BlogPostConnector::className(): return 'blog_post'; case CalendarEventConnector::className(): return 'calendar_event'; case ForumMessageConnector::className(): return 'forum_message'; case TaskConnector::className(): return 'tasks_task'; case SonetLogConnector::className(): return 'sonet_log'; case SonetCommentConnector::className(): return 'sonet_comment'; } return null; })); }
private function toArrayFromModel(Disk\Internals\Model $model) { $entity = null; if ($model instanceof Disk\Storage) { $entity = new Entity\Storage(); } elseif ($model instanceof Disk\File) { $entity = new Entity\Folder(); } elseif ($model instanceof Disk\Folder) { $entity = new Entity\File(); } elseif ($model instanceof Disk\AttachedObject) { $entity = new Entity\AttachedObject(); } else { throw new RestException('Unknown object ' . get_class($model)); } $toArray = array_intersect_key($model->toArray(), $entity->getFieldsForShow()); foreach ($entity->getFieldsForMap() as $fieldName => $modifiers) { if (!isset($toArray[$fieldName])) { continue; } $toArray[$fieldName] = call_user_func_array($modifiers['OUT'], array($toArray[$fieldName])); } unset($fieldName, $modifiers); if ($model instanceof Disk\File) { $toArray['DOWNLOAD_URL'] = \CRestUtil::getDownloadUrl(array('id' => $model->getId()), $this->restServer); if ($model->getStorage()->getProxyType() instanceof Disk\ProxyType\RestApp) { $toArray['DETAIL_URL'] = null; } else { $toArray['DETAIL_URL'] = $this->host . $this->urlManager->getPathFileDetail($model); } } elseif ($model instanceof Disk\Folder) { if ($model->getStorage()->getProxyType() instanceof Disk\ProxyType\RestApp) { $toArray['DETAIL_URL'] = null; } else { $toArray['DETAIL_URL'] = $this->host . $this->urlManager->getPathInListing($model) . $model->getName(); } } elseif ($model instanceof Disk\AttachedObject) { $toArray['DOWNLOAD_URL'] = $this->host . $this->urlManager->getUrlUfController('download', array('attachedId' => $model->getId(), 'auth' => $this->restServer->getAuth())); $toArray['NAME'] = $model->getFile()->getName(); $toArray['SIZE'] = $model->getFile()->getSize(); } return $toArray; }
<?php define("NOT_CHECK_PERMISSIONS", true); define("EXTRANET_NO_REDIRECT", true); define("STOP_STATISTICS", true); define("PUBLIC_AJAX_MODE", true); define("NO_KEEP_STATISTIC", "Y"); define("NO_AGENT_STATISTIC", "Y"); define("DisableEventsCheck", true); if (isset($_GET['action']) && ($_GET['action'] === 'showFile' || $_GET['action'] === 'downloadFile')) { define('BX_SECURITY_SESSION_READONLY', true); } require_once $_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/main/include/prolog_before.php"; if (!\Bitrix\Main\Loader::includeModule('disk')) { die; } $httpRequest = \Bitrix\Main\Context::getCurrent()->getRequest(); if (!$httpRequest->getQuery('action')) { die; } $oauthToken = $httpRequest->getQuery('auth'); if ($oauthToken && \Bitrix\Main\Loader::includeModule('rest')) { $authResult = null; if (\CrestUtil::checkAuth($oauthToken, array(\Bitrix\Disk\Driver::INTERNAL_MODULE_ID), $authResult)) { \CRestUtil::makeAuth($authResult); } } $controller = new \Bitrix\Disk\DownloadController(); $controller->setActionName($httpRequest->getQuery('action'))->exec();
public static function MeetingAccessibilityGet($arParams = array(), $nav = null, $server = null) { $userId = CCalendar::GetCurUserId(); $methodName = "calendar.accessibility.get"; $necessaryParams = array('from', 'to', 'users'); foreach ($necessaryParams as $param) { if (!isset($arParams[$param]) || empty($arParams[$param])) { throw new Exception(GetMessage('CAL_REST_PARAM_EXCEPTION', array('#PARAM_NAME#' => $param, '#REST_METHOD#' => $methodName))); } } $from = CRestUtil::unConvertDate($arParams['from']); $to = CRestUtil::unConvertDate($arParams['to']); $res = CCalendar::GetAccessibilityForUsers(array('users' => $arParams['users'], 'from' => $from, 'to' => $to, 'getFromHR' => true)); return $res; }
public static function onCallEnd($arParams) { $arParams['CALL_START_DATE'] = CRestUtil::ConvertDateTime($arParams['CALL_START_DATE']); return $arParams; }
/** * Creates new file in folder. * @param int $id Id of folder. * @param string|array $fileContent File content. General format in REST. * @param array $data Data for new file. * @param array $rights Specific rights on file. If empty, then use parents rights. * @return Disk\File|null * @throws AccessException * @throws RestException */ protected function uploadFile($id, $fileContent, array $data, array $rights = array()) { if (!$this->checkRequiredInputParams($data, array('NAME'))) { return null; } $folder = $this->getFolderById($id); $securityContext = $folder->getStorage()->getCurrentUserSecurityContext(); if (!$folder->canAdd($securityContext)) { throw new AccessException(); } $fileData = \CRestUtil::saveFile($fileContent); if (!$fileData) { throw new RestException('Could not save file.'); } $file = $folder->uploadFile($fileData, array('NAME' => $data['NAME'], 'CREATED_BY' => $this->userId), $rights); if (!$file) { $this->errorCollection->add($folder->getErrors()); return null; } return $file; }
public static function WriteFileToResponse($ownerTypeID, $ownerID, $fieldName, $fileID, &$errors, $options = array()) { $ownerTypeID = intval($ownerTypeID); $ownerTypeName = CCrmOwnerType::ResolveName($ownerTypeID); $ownerID = intval($ownerID); $fieldName = strval($fieldName); $fileID = intval($fileID); $options = is_array($options) ? $options : array(); if (!CCrmOwnerType::IsDefined($ownerTypeID) || $ownerID <= 0 || $fieldName === '' || $fileID <= 0) { $errors[] = 'File not found'; return false; } $authToken = isset($options['oauth_token']) ? strval($options['oauth_token']) : ''; if ($authToken !== '') { $authData = array(); if (!(CModule::IncludeModule('rest') && CRestUtil::checkAuth($authToken, CCrmRestService::SCOPE_NAME, $authData) && CRestUtil::makeAuth($authData))) { $errors[] = 'Access denied.'; return false; } } if (!CCrmPerms::IsAdmin()) { $userPermissions = CCrmPerms::GetCurrentUserPermissions(); $attrs = $userPermissions->GetEntityAttr($ownerTypeName, $ownerID); if ($userPermissions->HavePerm($ownerTypeName, BX_CRM_PERM_NONE, 'READ') || !$userPermissions->CheckEnityAccess($ownerTypeName, 'READ', isset($attrs[$ownerID]) ? $attrs[$ownerID] : array())) { $errors[] = 'Access denied.'; return false; } } $isDynamic = isset($options['is_dynamic']) ? (bool) $options['is_dynamic'] : true; if ($isDynamic) { $userFields = $GLOBALS['USER_FIELD_MANAGER']->GetUserFields(CCrmOwnerType::ResolveUserFieldEntityID($ownerTypeID), $ownerID, LANGUAGE_ID); $field = is_array($userFields) && isset($userFields[$fieldName]) ? $userFields[$fieldName] : null; if (!(is_array($field) && $field['USER_TYPE_ID'] === 'file')) { $errors[] = 'File not found'; return false; } $fileIDs = isset($field['VALUE']) ? is_array($field['VALUE']) ? $field['VALUE'] : array($field['VALUE']) : array(); //The 'strict' flag must be 'false'. In MULTIPLE mode value is an array of integers. In SIGLE mode value is a string. if (!in_array($fileID, $fileIDs, false)) { $errors[] = 'File not found'; return false; } return self::InnerWriteFileToResponse($fileID, $errors, $options); } else { $fieldsInfo = isset($options['fields_info']) ? $options['fields_info'] : null; if (!is_array($fieldsInfo)) { $fieldsInfo = CCrmOwnerType::GetFieldsInfo($ownerTypeID); } $fieldInfo = is_array($fieldsInfo) && isset($fieldsInfo[$fieldName]) ? $fieldsInfo[$fieldName] : array(); $fieldInfoType = isset($fieldInfo['TYPE']) ? $fieldInfo['TYPE'] : ''; if ($fieldInfoType !== 'file') { $errors[] = 'File not found'; return false; } if ($fileID !== CCrmOwnerType::GetFieldIntValue($ownerTypeID, $ownerID, $fieldName)) { $errors[] = 'File not found'; return false; } return self::InnerWriteFileToResponse($fileID, $errors, $options); } }
protected function internalizeFilterFields(&$filter, &$fieldsInfo) { if (!is_array($filter)) { return; } foreach ($filter as $k => $v) { $operationInfo = CSqlUtil::GetFilterOperation($k); $fieldName = $operationInfo['FIELD']; $info = isset($fieldsInfo[$fieldName]) ? $fieldsInfo[$fieldName] : null; if (!$info) { unset($filter[$k]); continue; } $fieldType = isset($info['TYPE']) ? $info['TYPE'] : ''; if ($fieldType === 'datetime') { $filter[$k] = CRestUtil::unConvertDateTime($v); } } CCrmEntityHelper::PrepareMultiFieldFilter($filter); }
/** * This function is for internal use only, not a part of public API * * @access private */ public static function _parseRestParams($className, $methodName, $inArgs) { CTaskAssert::assert(is_array($inArgs) && isset(self::$arMethodsMetaInfo[$className][$methodName])); $arMethodMetaInfo = self::$arMethodsMetaInfo[$className][$methodName]; $arAllowedParams = $arMethodMetaInfo['params']; $mandatoryParamsCount = $arMethodMetaInfo['mandatoryParamsCount']; $arDateFields = array(); if (isset(self::$arManifests[$className]['REST: date fields'])) { $arDateFields = self::$arManifests[$className]['REST: date fields']; } $outArgs = array(); foreach ($arAllowedParams as $paramIndex => $paramMetaInfo) { // No more params given? if (!array_key_exists($paramIndex, $inArgs)) { // Set default value, if need if (array_key_exists('defaultValue', $paramMetaInfo)) { $inArgs[$paramIndex] = $paramMetaInfo['defaultValue']; } elseif ($paramIndex < $mandatoryParamsCount) { throw new TasksException('Param #' . $paramIndex . ' (' . $paramMetaInfo['description'] . ')' . ' expected by method ' . $className . '::' . $methodName . '(), but not given.', TasksException::TE_WRONG_ARGUMENTS); } else { break; } // no more params to be processed } // for "galvanic isolation" of input/output $paramValue = $inArgs[$paramIndex]; // Check param type /** @noinspection PhpUnusedLocalVariableInspection */ $isCorrectValue = false; switch ($paramMetaInfo['type']) { case 'boolean': if ($paramValue === '0' || $paramValue === 0) { $paramValue = false; } elseif ($paramValue === '1' || $paramValue === 1) { $paramValue = true; } $isCorrectValue = is_bool($paramValue); break; case 'array': $isCorrectValue = is_array($paramValue); break; case 'string': $isCorrectValue = is_string($paramValue); break; case 'integer': $isCorrectValue = CTaskAssert::isLaxIntegers($paramValue); break; default: throw new TasksException('Internal error: unknown param type: ' . $paramMetaInfo['type'], TasksException::TE_UNKNOWN_ERROR); break; } if (!$isCorrectValue) { throw new TasksException('Param #' . $paramIndex . ' (' . $paramMetaInfo['description'] . ')' . ' for method ' . $className . '::' . $methodName . '()' . ' expected to be of type "' . $paramMetaInfo['type'] . '",' . ' but given something else.', TasksException::TE_WRONG_ARGUMENTS); } // add legal aggregated columns in keys & values array if (is_array($paramMetaInfo['allowedAggregations'])) { // for keys if (is_array($paramMetaInfo['allowedKeysInAggregation'])) { $fields = $paramMetaInfo['allowedKeysInAggregation']; } else { $fields = $paramMetaInfo['allowedKeys']; } if (is_array($fields)) { $aggrCombos = static::getAllowedAggregateCombos($paramMetaInfo['allowedAggregations'], $fields); $paramMetaInfo['allowedKeys'] = array_merge($paramMetaInfo['allowedKeys'], $aggrCombos); } // for values if (is_array($paramMetaInfo['allowedValuesInAggregation'])) { $fields = $paramMetaInfo['allowedValuesInAggregation']; } else { $fields = $paramMetaInfo['allowedValues']; } if (is_array($fields)) { $aggrCombos = static::getAllowedAggregateCombos($paramMetaInfo['allowedAggregations'], $fields); $paramMetaInfo['allowedValues'] = array_merge($paramMetaInfo['allowedValues'], $aggrCombos); } } if (isset($paramMetaInfo['allowedKeys'])) { CTaskAssert::assert(is_array($paramValue)); // ensure that $paramValue is array /** @var $paramValue array */ foreach (array_keys($paramValue) as $key) { // a little fix to be able to pass an empty array in order to "skip" argument if ((string) $key == '0' && $paramValue[$key] == '') { unset($paramValue[$key]); continue; } if (isset($paramMetaInfo['allowedKeyPrefixes'])) { $keyWoPrefix = str_replace($paramMetaInfo['allowedKeyPrefixes'], '', $key); } else { $keyWoPrefix = $key; } if (!in_array((string) $keyWoPrefix, $paramMetaInfo['allowedKeys'], true)) { throw new TasksException('Param #' . $paramIndex . ' (' . $paramMetaInfo['description'] . ')' . ' for method ' . $className . '::' . $methodName . '()' . ' must not contain key "' . $key . '".', TasksException::TE_WRONG_ARGUMENTS); } // Additionally convert datetime fields from ISO 8601 if (in_array((string) $keyWoPrefix, $arDateFields, true) && !in_array($paramValue[$key], array('asc', 'desc'))) { $paramValue[$key] = (string) CRestUtil::unConvertDateTime($paramValue[$key]); } } } if (isset($paramMetaInfo['allowedValues'])) { CTaskAssert::assert(is_array($paramValue)); foreach ($paramValue as $value) { if ($value !== null && !is_bool($value)) { $value = (string) $value; } if (!in_array($value, $paramMetaInfo['allowedValues'], true)) { throw new TasksException('Param #' . $paramIndex . ' (' . $paramMetaInfo['description'] . ')' . ' for method ' . $className . '::' . $methodName . '()' . ' must not contain value "' . $value . '".', TasksException::TE_WRONG_ARGUMENTS); } } } // "galvanic isolation" of input/output $outArgs[] = $paramValue; } if (count($inArgs) > count($arAllowedParams)) { throw new TasksException('Too much params(' . count($inArgs) . ') given for method ' . $className . '::' . $methodName . '()' . ', but expected not more than ' . count($arAllowedParams) . '.', TasksException::TE_WRONG_ARGUMENTS); } return $outArgs; }
require_once $_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/main/include/prolog_before.php"; } else { $oAuthMode = false; } if (!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED !== true) { die; } $arResult = array("MESSAGE" => array(), "FILE" => null); $isUserAuthorized = false; if (!$oAuthMode) { if (isset($USER) && is_object($USER) && method_exists($USER, 'getId') && $USER->getId() > 0) { $isUserAuthorized = true; } } else { // Try to authorize throughs oAuth if (isset($_GET['auth']) && CModule::IncludeModule('rest') && class_exists('CRestUtil') && method_exists('CRestUtil', 'checkAuth') && CRestUtil::checkAuth($_GET['auth'], CTaskRestService::SCOPE_NAME, $res = array()) && CRestUtil::makeAuth($res)) { $isUserAuthorized = true; } } if ($isUserAuthorized) { CModule::IncludeModule("tasks"); $arParams = array('FILE_ID' => false, 'TEMPLATE_ID' => false, 'TASK_ID' => false); if (isset($_GET['fid'])) { $arParams['FILE_ID'] = (int) $_GET['fid']; } if (isset($_GET['tid'])) { $arParams['TEMPLATE_ID'] = (int) $_GET['tid']; } if (isset($_GET['TASK_ID'])) { $arParams['TASK_ID'] = (int) $_GET['TASK_ID']; }
public static function WriteDiskFileToResponse($ownerTypeID, $ownerID, $fileID, &$errors, $options = array()) { $ownerTypeID = (int) $ownerTypeID; $ownerTypeName = CCrmOwnerType::ResolveName($ownerTypeID); $ownerID = (int) $ownerID; $fileID = (int) $fileID; $options = is_array($options) ? $options : array(); if (!CCrmOwnerType::IsDefined($ownerTypeID) || $ownerID <= 0 || $fileID <= 0) { $errors[] = 'Invalid data ownerTypeID = ' . $ownerTypeID . ', ownerID = ' . $ownerID . ', fileID = ' . $fileID; return false; } if ($ownerTypeID !== CCrmOwnerType::Activity) { $errors[] = "The owner type '{$ownerTypeName}' is not supported in current context"; return false; } $authToken = isset($options['oauth_token']) ? $options['oauth_token'] : ''; if ($authToken !== '') { $authData = array(); if (!(CModule::IncludeModule('rest') && CRestUtil::checkAuth($authToken, CCrmRestService::SCOPE_NAME, $authData) && CRestUtil::makeAuth($authData))) { $errors[] = 'Access denied.'; return false; } } if (!CCrmActivity::CheckStorageElementExists($ownerID, CCrmActivityStorageType::Disk, $fileID)) { $errors[] = 'File not found'; return false; } $isPermitted = false; if (CCrmPerms::IsAdmin()) { $isPermitted = true; } else { $userPermissions = CCrmPerms::GetCurrentUserPermissions(); $bindings = CCrmActivity::GetBindings($ownerID); foreach ($bindings as $binding) { if (CCrmAuthorizationHelper::CheckReadPermission($binding['OWNER_TYPE_ID'], $binding['OWNER_ID'], $userPermissions)) { $isPermitted = true; break; } } } if (!$isPermitted) { $errors[] = 'Access denied.'; return false; } Bitrix\Crm\Integration\DiskManager::writeFileToResponse($fileID); return true; }
private static function prepareFilter($arFilter) { if (!is_array($arFilter)) { $arFilter = array(); } else { $fieldsInfo = self::getFieldsInfo(); $arAllowedFilterFields = array(); foreach ($fieldsInfo as $fieldName => $fieldInfo) { if ($fieldInfo['filter'] === true) { $arAllowedFilterFields[] = $fieldName; } } if (count($arFilter) > 0) { $arFilter = array_change_key_case($arFilter, CASE_UPPER); foreach ($arFilter as $key => $value) { $matches = array(); if (preg_match('/^([^a-zA-Z]*)(.*)/', $key, $matches)) { $operation = $matches[1]; $field = $matches[2]; if (!in_array($field, $arAllowedFilterFields, true) || !in_array($operation, self::$arAllowedFilterOperations, true)) { unset($arFilter[$key]); } else { switch ($fieldsInfo[$field]['type']) { case 'datetime': $arFilter[$key] = CRestUtil::unConvertDateTime($value); break; case 'date': $arFilter[$key] = CRestUtil::unConvertDate($value); break; default: break; } } } else { unset($arFilter[$key]); } } } } return $arFilter; }
/** * @param array $params Input params. * @param int $n Offset. * @param \CRestServer $server Rest server instance. * @return array * @throws AccessException */ public static function getTaskList($params, $n, $server) { global $USER; self::checkAdminPermissions(); $params = array_change_key_case($params, CASE_UPPER); $fields = array('ID' => 'ID', 'WORKFLOW_ID' => 'WORKFLOW_ID', 'DOCUMENT_NAME' => 'DOCUMENT_NAME', 'DESCRIPTION' => 'DESCRIPTION', 'NAME' => 'NAME', 'MODIFIED' => 'MODIFIED', 'WORKFLOW_STARTED' => 'WORKFLOW_STARTED', 'WORKFLOW_STARTED_BY' => 'WORKFLOW_STARTED_BY', 'OVERDUE_DATE' => 'OVERDUE_DATE', 'WORKFLOW_TEMPLATE_ID' => 'WORKFLOW_TEMPLATE_ID', 'WORKFLOW_TEMPLATE_NAME' => 'WORKFLOW_TEMPLATE_NAME', 'WORKFLOW_STATE' => 'WORKFLOW_STATE', 'STATUS' => 'STATUS', 'USER_ID' => 'USER_ID', 'USER_STATUS' => 'USER_STATUS', 'MODULE_ID' => 'MODULE_ID', 'ENTITY' => 'ENTITY', 'DOCUMENT_ID' => 'DOCUMENT_ID'); $select = static::getSelect($params['SELECT'], $fields, array('ID', 'WORKFLOW_ID', 'DOCUMENT_NAME', 'NAME')); $select = array_merge(array('MODULE', 'ENTITY', 'DOCUMENT_ID'), $select); $filter = static::getFilter($params['FILTER'], $fields); $order = static::getOrder($params['ORDER'], $fields); $currentUserId = (int) $USER->getId(); $targetUserId = isset($filter['USER_ID']) ? (int) $filter['USER_ID'] : 0; if ($targetUserId !== $currentUserId && !\CBPHelper::checkUserSubordination($currentUserId, $targetUserId)) { self::checkAdminPermissions(); } $iterator = \CBPTaskService::getList($order, $filter, false, static::getNavData($n), $select); $result = array(); while ($row = $iterator->fetch()) { if (isset($row['MODIFIED'])) { $row['MODIFIED'] = \CRestUtil::convertDateTime($row['MODIFIED']); } if (isset($row['WORKFLOW_STARTED'])) { $row['WORKFLOW_STARTED'] = \CRestUtil::convertDateTime($row['WORKFLOW_STARTED']); } if (isset($row['OVERDUE_DATE'])) { $row['OVERDUE_DATE'] = \CRestUtil::convertDateTime($row['OVERDUE_DATE']); } $row['DOCUMENT_URL'] = \CBPDocument::getDocumentAdminPage(array($row['MODULE_ID'], $row['ENTITY'], $row['DOCUMENT_ID'])); $result[] = $row; } return $result; }
private static function checkGroupFilter($arFilter) { if(!is_array($arFilter)) { $arFilter = array(); } else { foreach ($arFilter as $key => $value) { if(preg_match('/^([^a-zA-Z]*)(.*)/', $key, $matches)) { $operation = $matches[1]; $field = $matches[2]; if(!in_array($operation, self::$arAllowedOperations)) { unset($arFilter[$key]); } else { switch($field) { case 'DATE_CREATE': case 'DATE_ACTIVITY': case 'DATE_UPDATE': $arFilter[$key] = CRestUtil::unConvertDateTime($value); break; case 'CHECK_PERMISSIONS': unset($arFilter[$key]); break; default: break; } } } } } return $arFilter; }
protected function internalizeFilterFields(&$filter, &$fieldsInfo) { if (!is_array($filter)) { return; } foreach ($filter as $k => $v) { $operationInfo = CSqlUtil::GetFilterOperation($k); $fieldName = $operationInfo['FIELD']; $info = isset($fieldsInfo[$fieldName]) ? $fieldsInfo[$fieldName] : null; if (!$info) { unset($filter[$k]); continue; } $operation = substr($k, 0, strlen($k) - strlen($fieldName)); if (isset($info['FORBIDDEN_FILTERS']) && is_array($info['FORBIDDEN_FILTERS']) && in_array($operation, $info['FORBIDDEN_FILTERS'], true)) { unset($filter[$k]); continue; } $fieldType = isset($info['TYPE']) ? $info['TYPE'] : ''; if (($fieldType === 'crm_status' || $fieldType === 'crm_company' || $fieldType === 'crm_contact') && ($operation === '%' || $operation === '%=' || $operation === '=%')) { //Prevent filtration by LIKE due to performance considerations $filter["={$fieldName}"] = $v; unset($filter[$k]); continue; } if ($fieldType === 'datetime') { $filter[$k] = CRestUtil::unConvertDateTime($v); } elseif ($fieldType === 'date') { $filter[$k] = CRestUtil::unConvertDate($v); } } CCrmEntityHelper::PrepareMultiFieldFilter($filter, array(), '=%', true); }