/** * Returns list of recently files by user. * @param mixed|int|User|\CAllUser $user User. * @param array $filter Filter. * @return File[] * @internal */ public function getFileModelListByUser($user, array $filter = array()) { $userId = User::resolveUserId($user); if (!$userId) { $this->errorCollection->addOne(new Error('Could not get user id.')); return array(); } $driver = Driver::getInstance(); $storage = $driver->getStorageByUserId($userId); if (!$storage) { $this->errorCollection->addOne(new Error('Could not get storage by user id.')); return array(); } if ($this->isFirstRun($userId)) { if (!$this->hasData($userId)) { $this->fixColdStart($userId); } $this->saveFirstRun($userId); } $securityContext = $storage->getCurrentUserSecurityContext(); $parameters = array('filter' => array('RECENTLY_USED.USER_ID' => $userId, 'DELETED_TYPE' => ObjectTable::DELETED_TYPE_NONE, 'TYPE' => ObjectTable::TYPE_FILE), 'order' => array('RECENTLY_USED.CREATE_TIME' => 'DESC'), 'limit' => RecentlyUsedTable::MAX_COUNT_FOR_USER); if ($filter) { $parameters['filter'] = array_merge($parameters['filter'], $filter); } $parameters = $driver->getRightsManager()->addRightsCheck($securityContext, $parameters, array('ID', 'CREATED_BY')); return File::getModelList($parameters); }
/** * Adds row to entity table, fills error collection and builds model. * @param array $data Data. * @param ErrorCollection $errorCollection Error collection. * @return \Bitrix\Disk\Internals\Model|static|null * @throws \Bitrix\Main\NotImplementedException * @internal */ public static function add(array $data, ErrorCollection $errorCollection) { $result = FileTable::add($data); if (!$result->isSuccess()) { $errorCollection->addFromResult($result); return null; } $file = static::buildFromResult($result); return $file; }
/** * Adds row to entity table, fills error collection and builds model. * @param array $data Data. * @param ErrorCollection $errorCollection Error collection. * @return \Bitrix\Disk\Internals\Model|static|null * @throws \Bitrix\Main\NotImplementedException * @internal */ public static function add(array $data, ErrorCollection $errorCollection) { $result = FileTable::add($data); if (!$result->isSuccess()) { $errorCollection->addFromResult($result); return null; } $file = static::buildFromResult($result); if ($file && $file->getCreatedBy()) { $driver = Driver::getInstance(); $driver->getRecentlyUsedManager()->push($file->getCreatedBy(), $file->getId()); } return $file; }
protected static function prepareDataToInsertFromFileArray(array $fileData, array $data, ErrorCollection $errorCollection) { list($relativePath, $absolutePath) = self::generatePath(); $file = new IO\File($fileData['tmp_name']); if (!$file->isExists()) { $errorCollection->addOne(new Error('Could not find file', self::ERROR_EXISTS_FILE)); return null; } if (!$file->rename($absolutePath)) { $errorCollection->addOne(new Error('Could not move file', self::ERROR_MOVE_FILE)); return null; } //now you can set CREATED_BY $data = array_intersect_key($data, array('CREATED_BY' => true)); return array_merge(array('TOKEN' => bx_basename($relativePath), 'FILENAME' => $fileData['name'], 'PATH' => $relativePath, 'BUCKET_ID' => '', 'SIZE' => '', 'IS_CLOUD' => '', 'WIDTH' => empty($fileData['width']) ? '' : $fileData['width'], 'HEIGHT' => empty($fileData['height']) ? '' : $fileData['height']), $data); }
/** * Checks required parameters. * Fills error collection if required parameter is missed. * @param array $inputParams Input data. * @param array $required Required parameters. * @return bool */ protected function checkRequiredInputParams(array $inputParams, array $required) { foreach ($required as $item) { if (!isset($inputParams[$item]) || !$inputParams[$item] && !(is_string($inputParams[$item]) && strlen($inputParams[$item]))) { $this->errorCollection->add(array(new Error(Loc::getMessage('DISK_CONTROLLER_ERROR_REQUIRED_PARAMETER', array('#PARAM#' => $item)), self::ERROR_REQUIRED_PARAMETER))); return false; } } return true; }
protected function checkRequiredInputParams(array $inputParams, array $required) { foreach ($required as $item) { if (!isset($inputParams[$item]) || !$inputParams[$item] && !(is_string($inputParams[$item]) && strlen($inputParams[$item]))) { $this->errorCollection->add(array(new Error("Error: required parameter {$item}", self::ERROR_REQUIRED_PARAMETER))); return false; } } return true; }
/** * Clones uf values from entity and creates new files (copies from attach) to save in new entity. * @param array $attachedIds List of attached objects id. * @param int $userId Id of user. * @internal * @return array */ public function cloneUfValuesFromAttachedObject(array $attachedIds, $userId) { $this->errorCollection->clear(); $userId = (int) $userId; if ($userId <= 0) { $this->errorCollection->addOne(new Error('Invalid $userId')); return null; } $userStorage = Driver::getInstance()->getStorageByUserId($userId); if (!$userStorage) { $this->errorCollection->addOne(new Error("Could not find storage for user {$userId}")); $this->errorCollection->add(Driver::getInstance()->getErrors()); return null; } $folder = $userStorage->getFolderForUploadedFiles(); if (!$folder) { $this->errorCollection->addOne(new Error("Could not create/find folder for upload")); $this->errorCollection->add($userStorage->getErrors()); return null; } $newValues = array(); foreach ($attachedIds as $id) { list($type, $realValue) = FileUserType::detectType($id); if (FileUserType::TYPE_ALREADY_ATTACHED != $type) { continue; } $attachedObject = AttachedObject::loadById($realValue, array('OBJECT')); if (!$attachedObject) { continue; } if (!$attachedObject->canRead($userId)) { continue; } $file = $attachedObject->getFile(); if (!$file) { continue; } $newFile = $file->copyTo($folder, $userId, true); if (!$newFile) { $this->errorCollection->add($file->getErrors()); continue; } $newValues[] = FileUserType::NEW_FILE_PREFIX . $newFile->getId(); } return $newValues; }
protected function checkAction() { if ($this->errorCollection->hasErrors()) { $this->sendJsonErrorResponse(); } $description = $this->getActionDescription(); //if does not exist check_csrf_token we have to check csrf for only POST method. if ($description['check_csrf_token'] === true || $this->request->isPost() && !isset($description['check_csrf_token'])) { if (!check_bitrix_sessid()) { if ($this->isAjaxRequest()) { $this->sendJsonAccessDeniedResponse('Wrong csrf token'); } else { $this->showAccessDenied(); } } } }
/** * Rollback upload by token. Destroy temporary content. * @return bool Status of delete. */ public function rollbackByToken() { if (!$this->hasToken()) { $this->errorCollection->addOne(new Error("Could not delete content file by token. Have to set token parameter.", self::ERROR_EMPTY_TOKEN)); return false; } $tmpFile = $this->findUserSpecificTmpFileByToken(); if (!$tmpFile) { $this->errorCollection->addOne(new Error("Could not find file by token", self::ERROR_UNKNOWN_TOKEN)); return false; } $success = $tmpFile->delete(); if (!$success) { $this->errorCollection->add($tmpFile->getErrors()); } return $success; }
/** * Connect object $data['REAL_OBJECT'] (or $data['REAL_OBJECT_ID']) to user storage * $data['SELF_CONNECT'] - don't ask about connecting object, * @param $userId * @param array $data * @param ErrorCollection $errorCollection * @return Sharing|null * @throws \Bitrix\Main\NotImplementedException * @throws \Bitrix\Main\SystemException */ public static function connectToUserStorage($userId, array $data, ErrorCollection $errorCollection) { $storage = Driver::getInstance()->getStorageByUserId($userId); if (!$storage) { $storage = Driver::getInstance()->addUserStorage($userId); } if (!$storage) { $errorCollection->add(array(new Error(Loc::getMessage('DISK_SHARING_MODEL_ERROR_COULD_NOT_FIND_USER_STORAGE', array('#USER_ID#' => $userId)), self::ERROR_COULD_NOT_FIND_USER_STORAGE))); return null; } $selfConnect = !empty($data['SELF_CONNECT']); $linkName = !empty($data['LINK_NAME']) ? $data['LINK_NAME'] : null; unset($data['SELF_CONNECT'], $data['LINK_NAME']); $data['TYPE'] = SharingTable::TYPE_TO_USER; $data['FROM_ENTITY'] = self::CODE_USER . (int) $userId; $data['TO_ENTITY'] = self::CODE_USER . (int) $userId; $data['TASK_NAME'] = RightsManager::TASK_READ; if (isset($data['REAL_OBJECT']) && $data['REAL_OBJECT'] instanceof BaseObject) { /** @noinspection PhpUndefinedMethodInspection */ $data['REAL_OBJECT_ID'] = $data['REAL_OBJECT']->getId(); } elseif (isset($data['REAL_OBJECT_ID'])) { $data['REAL_OBJECT'] = BaseObject::loadById($data['REAL_OBJECT_ID']); } else { $errorCollection->add(array(new Error(Loc::getMessage('DISK_SHARING_MODEL_ERROR_EMPTY_REAL_OBJECT'), self::ERROR_EMPTY_REAL_OBJECT))); return null; } /** @var \Bitrix\Disk\BaseObject $objectToSharing */ $objectToSharing = $data['REAL_OBJECT']; //resolve to last real object. In table we write only real (not link) id. $objectToSharing = $objectToSharing->getRealObject(); $data['REAL_OBJECT_ID'] = $objectToSharing->getId(); $data['REAL_STORAGE_ID'] = $objectToSharing->getStorageId(); $dataToInsert = $data; unset($dataToInsert['REAL_OBJECT']); $sharingModel = parent::add($dataToInsert, $errorCollection); if (!$sharingModel) { return null; } $sharingModel->setAttributes(array('REAL_OBJECT' => $objectToSharing)); if (!$selfConnect) { self::processConnectAndNotify(array($sharingModel), $objectToSharing); } else { if (!$sharingModel->approve(array('LINK_NAME' => $linkName))) { $errorCollection->add($sharingModel->getErrors()); $sharingModel->delete($userId); return null; } } return $sharingModel; }
/** * @inheritdoc */ public function getErrorByCode($code) { return $this->errorCollection->getErrorByCode($code); }
protected static function prepareDataToInsertFromFileArray(array $fileData, array $data, ErrorCollection $errorCollection) { if (($fileData['error'] = intval($fileData['error'])) > 0) { if ($fileData['error'] < 3) { $errorCollection->addOne(new Error('upload_max_filesize: ' . intval(ini_get('upload_max_filesize')), static::ERROR_UPLOAD_MAX_FILE_SIZE)); return null; } $errorCollection->addOne(new Error('upload_error ' . $fileData['error'], static::ERROR_UPLOAD_FILE)); return null; } if (!is_uploaded_file($fileData['tmp_name'])) { $errorCollection->addOne(new Error('Current file is unsafe (is_uploaded_file check)', static::ERROR_IS_NOT_UPLOADED_FILE)); return null; } list($relativePath, $absolutePath) = static::generatePath(); if (!move_uploaded_file($fileData['tmp_name'], $absolutePath)) { $errorCollection->addOne(new Error('Could not move uploaded file (move_uploaded_file)', static::ERROR_MOVE_UPLOADED_FILE)); return null; } //now you can set CREATED_BY $data = array_intersect_key($data, array('CREATED_BY' => true)); return array_merge(array('TOKEN' => bx_basename($relativePath), 'FILENAME' => $fileData['name'], 'CONTENT_TYPE' => empty($fileData['type']) ? \CFile::getContentType($absolutePath) : $fileData['type'], 'PATH' => $relativePath, 'BUCKET_ID' => '', 'SIZE' => '', 'IS_CLOUD' => '', 'WIDTH' => empty($fileData['width']) ? '' : $fileData['width'], 'HEIGHT' => empty($fileData['height']) ? '' : $fileData['height']), $data); }
function processActionHandleFile($hash, &$file, &$package, &$upload, &$error) { $errorCollection = new ErrorCollection(); $storage = Driver::getInstance()->getStorageByUserId($this->getUser()->getId()); if (!$storage) { $errorCollection->add(array(new Error(Loc::getMessage('DISK_UF_CONTROLLER_ERROR_COULD_NOT_FIND_USER_STORAGE'), self::ERROR_COULD_NOT_FIND_USER_STORAGE))); $error = implode(" ", $errorCollection->toArray()); return false; } $folder = $storage->getFolderForUploadedFiles(); if (!$folder) { $errorCollection->add(array(new Error(Loc::getMessage('DISK_UF_CONTROLLER_ERROR_COULD_NOT_FIND_FIND_FOLDER'), self::ERROR_COULD_NOT_FIND_FOLDER))); $error = implode(" ", $errorCollection->toArray()); return false; } $urlManager = Driver::getInstance()->getUrlManager(); if ($folder->canAdd($storage->getCurrentUserSecurityContext())) { $fileModel = $folder->uploadFile($file["files"]["default"], array('NAME' => $file['name'], 'CREATED_BY' => $this->getUser()->getId()), array(), true); if ($fileModel) { $name = $fileModel->getName(); $id = FileUserType::NEW_FILE_PREFIX . $fileModel->getId(); $file = array_merge($file, array('id' => $id, 'originalId' => $fileModel->getId(), 'name' => $name, 'label' => getFileNameWithoutExtension($name), 'ext' => $fileModel->getExtension(), 'size' => \CFile::formatSize($fileModel->getSize()), 'sizeInt' => $fileModel->getSize(), 'storage' => $storage->getProxyType()->getTitleForCurrentUser() . ' / ' . $folder->getName(), 'deleteUrl' => $urlManager->getUrlUfController('deleteFile', array('attachedId' => $id)), 'canChangeName' => true), TypeFile::isImage($name) ? array('previewUrl' => $urlManager->getUrlForShowFile($fileModel, array("width" => self::$previewParams["width"], "height" => self::$previewParams["height"]))) : array()); } else { $error = is_array($folder->getErrors()) ? implode(" ", $folder->getErrors()) : 'The file has not been saved'; } } return empty($error); }
/** * Validates value. * Uses validating logic by table class (DataManager). * Be careful! This method may be deleted or changed. * @param $fieldName * @param $value * @param ErrorCollection $errorCollection * @return bool * @throws ArgumentException * @throws NotImplementedException * @internal */ public static function isValidValueForField($fieldName, $value, ErrorCollection $errorCollection = null) { $result = new Result(); /** @var DataManager $tableClassName */ $tableClassName = static::getTableClassName(); $tableClassName::getEntity()->getField($fieldName)->validateValue($value, null, array(), $result); if (!$result->isSuccess()) { $errorCollection && $errorCollection->addFromResult($result); return false; } return true; }