/** * Create new blank file in cloud service. * It is not necessary set shared rights on file. * @param FileData $fileData * @return FileData|null */ public function createBlankFile(FileData $fileData) { if (!$this->checkRequiredInputParams($fileData->toArray(), array('name'))) { return null; } $accessToken = $this->getAccessToken(); $googleMimeType = $this->getInternalMimeTypeByExtension(getFileExtension($fileData->getName())); $fileName = getFileNameWithoutExtension($fileData->getName()); $fileName = $this->convertToUtf8($fileName); if (!$googleMimeType) { $this->errorCollection->add(array(new Error("Unsupported file format with name {$fileData->getName()}", self::ERROR_UNSUPPORTED_FILE_FORMAT))); return null; } $http = new HttpClient(array('socketTimeout' => 10, 'streamTimeout' => 30, 'version' => HttpClient::HTTP_1_1)); $http->setHeader('Content-Type', 'application/json; charset=UTF-8'); $http->setHeader('Authorization', "Bearer {$accessToken}"); $postFields = "{\"title\":\"{$fileName}\",\"mimeType\":\"{$googleMimeType}\"}"; if ($http->post(self::API_URL_V2 . '/files', $postFields) === false) { $errorString = implode('; ', array_keys($http->getError())); $this->errorCollection->add(array(new Error($errorString, self::ERROR_HTTP_CREATE_BLANK))); return null; } if (!$this->checkHttpResponse($http)) { return null; } $finalOutput = Json::decode($http->getResult()); if ($finalOutput === null) { $this->errorCollection->add(array(new Error('Could not decode response as json', self::ERROR_BAD_JSON))); return null; } if (empty($finalOutput['id']) || empty($finalOutput['alternateLink'])) { $this->errorCollection->add(array(new Error('Could not find id or alternateLink in response from Google.', self::ERROR_COULD_NOT_FIND_ID))); return null; } $fileData->setLinkInService($finalOutput['alternateLink']); $fileData->setId($finalOutput['id']); //last signed user must delete file from google drive $this->insertPermission($fileData); return $fileData; }
protected function processActionCommit() { $this->checkRequiredPostParams(array('editSessionId')); if ($this->errorCollection->hasErrors()) { $this->sendJsonErrorResponse(); } $this->checkUpdatePermissions(); $currentSession = $this->getEditSessionByCurrentUser((int) $this->request->getPost('editSessionId')); if (!$currentSession) { $this->errorCollection->add(array(new Error(Loc::getMessage('DISK_DOC_CONTROLLER_ERROR_COULD_NOT_FIND_EDIT_SESSION'), self::ERROR_COULD_NOT_FIND_EDIT_SESSION))); $this->sendJsonErrorResponse(); } $tmpFile = \CTempFile::getFileName(uniqid('_wd')); checkDirPath($tmpFile); $fileData = new FileData(); $fileData->setId($currentSession->getServiceFileId()); $fileData->setSrc($tmpFile); $newNameFileAfterConvert = null; if ($this->documentHandler->isNeedConvertExtension($this->file->getExtension())) { $newNameFileAfterConvert = getFileNameWithoutExtension($this->file->getName()) . '.' . $this->documentHandler->getConvertExtension($this->file->getExtension()); $fileData->setMimeType(TypeFile::getMimeTypeByFilename($newNameFileAfterConvert)); } else { $fileData->setMimeType(TypeFile::getMimeTypeByFilename($this->file->getName())); } $fileData = $this->documentHandler->downloadFile($fileData); if (!$fileData) { if ($this->documentHandler->isRequiredAuthorization()) { $this->sendNeedAuth(); } $this->errorCollection->add($this->documentHandler->getErrors()); $this->sendJsonErrorResponse(); } $this->deleteEditSession($currentSession); $oldName = $this->file->getName(); //rename in cloud service $renameInCloud = $fileData->getName() && $fileData->getName() != $this->file->getName(); if ($newNameFileAfterConvert || $renameInCloud) { if ($newNameFileAfterConvert && $renameInCloud) { $newNameFileAfterConvert = getFileNameWithoutExtension($fileData->getName()) . '.' . getFileExtension($newNameFileAfterConvert); } $this->file->rename($newNameFileAfterConvert); } $fileArray = \CFile::makeFileArray($tmpFile); $fileArray['name'] = $this->file->getName(); $fileArray['type'] = $fileData->getMimeType(); $fileArray['MODULE_ID'] = Driver::INTERNAL_MODULE_ID; /** @noinspection PhpDynamicAsStaticMethodCallInspection */ $fileId = \CFile::saveFile($fileArray, Driver::INTERNAL_MODULE_ID); if (!$fileId) { \CFile::delete($fileId); $this->errorCollection->add(array(new Error(Loc::getMessage('DISK_DOC_CONTROLLER_ERROR_COULD_NOT_SAVE_FILE'), self::ERROR_COULD_NOT_SAVE_FILE))); $this->sendJsonErrorResponse(); } $versionModel = $this->file->addVersion(array('ID' => $fileId, 'FILE_SIZE' => $fileArray['size']), $this->getUser()->getId(), true); if (!$versionModel) { \CFile::delete($fileId); $this->errorCollection->add(array(new Error(Loc::getMessage('DISK_DOC_CONTROLLER_ERROR_COULD_NOT_ADD_VERSION'), self::ERROR_COULD_NOT_ADD_VERSION))); $this->errorCollection->add($this->file->getErrors()); $this->sendJsonErrorResponse(); } if ($this->isLastEditSessionForFile()) { $this->deleteFile($currentSession, $fileData); } $this->sendJsonSuccessResponse(array('objectId' => $this->file->getId(), 'newName' => $this->file->getName(), 'oldName' => $oldName)); }
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); }
protected function processActionPublishBlank() { $this->checkRequiredGetParams(array('type')); if ($this->errorCollection->hasErrors()) { $this->sendJsonErrorResponse(); } $fileData = new BlankFileData($this->request->getQuery('type')); if ($this->request->getPost('targetFolderId')) { $folder = Folder::loadById((int) $this->request->getPost('targetFolderId'), array('STORAGE')); if (!$folder) { $this->errorCollection->add(array(new Error(Loc::getMessage('DISK_LOCAL_DOC_CONTROLLER_ERROR_COULD_NOT_FIND_FOLDER'), self::ERROR_COULD_NOT_FIND_FOLDER))); $this->sendJsonErrorResponse(); } } else { $userStorage = Driver::getInstance()->getStorageByUserId($this->getUser()->getId()); if (!$userStorage) { $this->errorCollection->add(array(new Error(Loc::getMessage('DISK_LOCAL_DOC_CONTROLLER_ERROR_COULD_NOT_FIND_STORAGE'), self::ERROR_COULD_NOT_FIND_STORAGE))); $this->sendJsonErrorResponse(); } $folder = $userStorage->getFolderForCreatedFiles(); } if (!$folder) { $this->errorCollection->add(array(new Error(Loc::getMessage('DISK_LOCAL_DOC_CONTROLLER_ERROR_COULD_NOT_FIND_FOLDER_FOR_CREATED_FILES'), self::ERROR_COULD_NOT_FIND_FOLDER_FOR_CREATED_FILES))); $this->sendJsonErrorResponse(); } $storage = $folder->getStorage(); if (!$folder->canAdd($storage->getCurrentUserSecurityContext())) { $this->errorCollection->add(array(new Error(Loc::getMessage('DISK_LOCAL_DOC_CONTROLLER_ERROR_BAD_RIGHTS'), self::ERROR_BAD_RIGHTS))); $this->sendJsonErrorResponse(); } $newFile = $folder->addBlankFile(array('NAME' => $fileData->getName(), 'CREATED_BY' => $this->getUser()->getId(), 'MIME_TYPE' => $fileData->getMimeType()), array(), true); if (!$newFile) { $this->errorCollection->add(array(new Error(Loc::getMessage('DISK_LOCAL_DOC_CONTROLLER_ERROR_COULD_NOT_CREATE_FILE'), self::ERROR_COULD_NOT_CREATE_FILE))); $this->errorCollection->add($folder->getErrors()); $this->sendJsonErrorResponse(); } $this->sendJsonSuccessResponse(array('ufValue' => FileUserType::NEW_FILE_PREFIX . $newFile->getId(), 'id' => $newFile->getId(), 'object' => array('id' => $newFile->getId(), 'name' => $newFile->getName(), 'sizeInt' => $newFile->getSize(), 'size' => \CFile::formatSize($newFile->getSize()), 'extension' => $newFile->getExtension(), 'nameWithoutExtension' => getFileNameWithoutExtension($newFile->getName())), 'folderName' => $storage->getProxyType()->getTitleForCurrentUser() . ' / ' . $folder->getName(), 'link' => Driver::getInstance()->getUrlManager()->getUrlForStartEditFile($newFile->getId(), self::CODE))); }
/** * @internal * @param $fileName * @param $mimeType * @return string */ protected function recoverExtensionInName($fileName, $mimeType) { $specificMimeTypes = array('application/vnd.google-apps.document' => 'docx', 'application/vnd.google-apps.spreadsheet' => 'xlsx', 'application/vnd.google-apps.presentation' => 'pptx'); if (isset($specificMimeTypes[$mimeType])) { $originalExtension = $specificMimeTypes[$mimeType]; } else { $originalExtension = TypeFile::getExtensionByMimeType($mimeType); } $newExtension = strtolower(trim(getFileExtension($fileName), '.')); if ($originalExtension !== $newExtension && $originalExtension !== null) { return getFileNameWithoutExtension($fileName) . '.' . $originalExtension; } return $fileName; }
protected function recoverExtensionInName(&$fileName, $mimeType) { $originalExtension = TypeFile::getExtensionByMimeType($mimeType); $newExtension = strtolower(trim(getFileExtension($fileName), '.')); if ($originalExtension != $newExtension) { $fileName = getFileNameWithoutExtension($fileName) . '.' . $originalExtension; return true; } return false; }
public function createBlankFile(array $fileData) { $accessToken = $this->getAccessToken(); $googleMimeType = $this->getInternalMimeTypeListByExtension(getFileExtension($fileData['name'])); $fileName = getFileNameWithoutExtension($fileData['name']); CWebDavTools::convertToUtf8($fileName); if (!$googleMimeType) { return false; } $http = new CHTTP(); $http->http_timeout = 10; $arUrl = $http->ParseURL('https://www.googleapis.com/drive/v2/files'); $http->SetAdditionalHeaders(array("Authorization" => "Bearer {$accessToken}")); $postFields = "{\"title\":\"{$fileName}\",\"mimeType\":\"{$googleMimeType}\"}"; $postContentType = 'application/json; charset=UTF-8'; if (!$http->Query('POST', $arUrl['host'], $arUrl['port'], $arUrl['path_query'], $postFields, $arUrl['proto'], $postContentType)) { return false; } $this->checkHttpResponse($http); // access token expired, let's get a new one and try again if ($http->status == "401") { //todo: invalid credential response return false; } // error checking if ($http->status != "200") { return false; } $finalOutput = json_decode($http->result); //last signed user must delete file from google drive $this->insertPermission(array('link' => $finalOutput->alternateLink, 'id' => $finalOutput->id)); return array('link' => $finalOutput->alternateLink, 'id' => $finalOutput->id); }