Example #1
0
 public function __construct($type)
 {
     parent::__construct();
     $type = trim(strtolower($type), '.');
     if (!$this->issetType($type)) {
         throw new SystemException("Could not find type '{$type}' in BlankFile");
     }
     $typeData = $this->getType($type);
     $this->name = $typeData['newFileName'] . $typeData['ext'];
     $this->mimeType = TypeFile::getMimeTypeByFilename($this->name);
     $this->src = $typeData['src'];
     $this->size = IO\File::isFileExists($typeData['src']) ? filesize($typeData['src']) : 0;
 }
 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));
 }
Example #3
0
 protected function getDownloadUrl(FileData $fileData, $fileMetaData = array())
 {
     if (!$this->checkRequiredInputParams($fileData->toArray(), array('id'))) {
         return null;
     }
     if (!$fileMetaData) {
         $fileMetaData = $this->getFileMetadataInternal($fileData);
     }
     if (!$fileMetaData) {
         return null;
     }
     if (!empty($fileMetaData['downloadUrl'])) {
         return self::API_URL_V2 . "/files/{$fileData->getId()}?alt=media";
     }
     if (empty($fileMetaData['exportLinks'])) {
         return null;
     }
     $links = $fileMetaData['exportLinks'];
     $mimeType = TypeFile::getMimeTypeByFilename($fileMetaData['title']);
     if ($mimeType && isset($links[$mimeType])) {
         return $links[$mimeType];
     }
     if (isset($links['application/vnd.openxmlformats-officedocument.wordprocessingml.document'])) {
         return $links['application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
     }
     if (isset($links['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'])) {
         return $links['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
     }
     if (isset($links['image/png'])) {
         return $links['image/png'];
     }
     if (isset($links['application/vnd.openxmlformats-officedocument.presentationml.presentation'])) {
         return $links['application/vnd.openxmlformats-officedocument.presentationml.presentation'];
     }
     return null;
 }
Example #4
0
 /**
  * Gets a file's metadata by ID.
  *
  * @param FileData $fileData
  * @return array|null Describes file (id, title, size)
  */
 public function getFileMetadata(FileData $fileData)
 {
     if (!$this->checkRequiredInputParams($fileData->toArray(), array('id'))) {
         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 {$this->getAccessToken()}");
     if ($http->get(self::API_URL_V2 . "/files/{$fileData->getId()}") === false) {
         $errorString = implode('; ', array_keys($http->getError()));
         $this->errorCollection->add(array(new Error($errorString, self::ERROR_HTTP_GET_METADATA)));
         return null;
     }
     if (!$this->checkHttpResponse($http)) {
         return null;
     }
     $metaData = Json::decode($http->getResult());
     if ($metaData === null) {
         $this->errorCollection->add(array(new Error('Could not decode response as json', self::ERROR_BAD_JSON)));
         return null;
     }
     return array('id' => $metaData['id'], 'name' => $metaData['name'], 'size' => $metaData['size'], 'mimeType' => TypeFile::getMimeTypeByFilename($metaData['name']), 'etag' => $metaData['sha1']);
 }
Example #5
0
 public static function createDocument($parentDocumentId, $fields)
 {
     /** @var File $file */
     $file = File::loadById($parentDocumentId, array('STORAGE'));
     if (!$file) {
         return false;
     }
     $targetObject = $file->getParent();
     if (!$targetObject) {
         return false;
     }
     $uploadFile = $targetObject->addBlankFile(array('NAME' => $fields['NAME'], 'CREATED_BY' => SystemUser::SYSTEM_USER_ID, 'MIME_TYPE' => TypeFile::getMimeTypeByFilename($fields['NAME'])), array(), true);
     if ($uploadFile) {
         $ufFields = array();
         foreach ($fields as $codeField => $valueField) {
             $search = 'UF_';
             $res = strpos($codeField, $search);
             if ($res === 0) {
                 $ufFields[$codeField] = $valueField;
             }
         }
         if (!empty($ufFields)) {
             global $USER_FIELD_MANAGER;
             $storageId = $uploadFile->getStorageId();
             $USER_FIELD_MANAGER->update('DISK_FILE_' . $storageId, $uploadFile->getId(), $ufFields);
         }
         return $uploadFile->getId();
     } else {
         return false;
     }
 }
 protected function migrateVersion()
 {
     if (!$this->runWorkWithBizproc) {
         return;
     }
     if ($this->isStepFinished(__METHOD__)) {
         return;
     }
     $uploadDir = COption::getOptionString("main", "upload_dir", "upload");
     $isCloud = CModule::IncludeModule("clouds");
     $useGZipCompressionOption = \Bitrix\Main\Config\Option::get("bizproc", "use_gzip_compression", "");
     $isBitrix24 = IsModuleInstalled('bitrix24');
     $bucket = null;
     if ($isBitrix24 && $isCloud) {
         $bucket = new CCloudStorageBucket(1);
         $bucket->init();
     }
     if ($useGZipCompressionOption === "Y") {
         $this->useGZipCompression = true;
     } elseif ($useGZipCompressionOption === "N") {
         $this->useGZipCompression = false;
     } else {
         $this->useGZipCompression = function_exists("gzcompress") && ($GLOBALS["DB"]->type != "ORACLE" || !defined('BX_UTF'));
     }
     $sqlHelper = $this->connection->getSqlHelper();
     $lastId = $this->getStorageId();
     $versionQuery = $this->connection->query("\n\t\t\tSELECT\n\t\t\t\tobj.*,\n\t\t\t\th.ID VERSION_ID,\n\t\t\t\th.NAME VERSION_NAME,\n\t\t\t\th.DOCUMENT VERSION_DOC,\n\t\t\t\th.USER_ID VERSION_USER_ID,\n\t\t\t\th.MODIFIED VERSION_MODIFIED\n\t\t\tFROM b_disk_object obj\n\t\t\t\tINNER JOIN b_bp_history h ON h.DOCUMENT_ID = obj.WEBDAV_ELEMENT_ID AND h.MODULE_ID = 'webdav'\n\n\t\t\tWHERE obj.TYPE = 3 AND h.ID > {$lastId} ORDER BY h.ID\n\t\t");
     while ($version = $versionQuery->fetch()) {
         $this->abortIfNeeded();
         if (strlen($version['VERSION_DOC']) > 0) {
             if ($this->useGZipCompression) {
                 $version['VERSION_DOC'] = gzuncompress($version['VERSION_DOC']);
             }
             $version['VERSION_DOC'] = unserialize($version['VERSION_DOC']);
             if (!is_array($version['VERSION_DOC'])) {
                 $version['VERSION_DOC'] = array();
             }
         } else {
             $version['VERSION_DOC'] = array();
         }
         if (empty($version['VERSION_DOC']) || empty($version['VERSION_DOC']['PROPERTIES']['WEBDAV_VERSION']['VALUE']) || empty($version['VERSION_DOC']['PROPERTIES']['FILE']['VALUE'])) {
             $this->storeStorageId($version['VERSION_ID']);
             continue;
         }
         $version['VERSION_NAME'] = $sqlHelper->forSql($version['VERSION_NAME']);
         $version['VERSION_MODIFIED'] = $sqlHelper->getCharToDateFunction($version['VERSION_MODIFIED']->format("Y-m-d H:i:s"));
         $version['UPDATE_TIME'] = $sqlHelper->getCharToDateFunction($version['UPDATE_TIME']->format("Y-m-d H:i:s"));
         $fullPath = $version['VERSION_DOC']['PROPERTIES']['FILE']['VALUE'];
         $handlerId = '';
         $filename = bx_basename($fullPath);
         if (substr($fullPath, 0, 4) == "http") {
             if (!$isCloud) {
                 $this->storeStorageId($version['VERSION_ID']);
                 continue;
             }
             if (!$isBitrix24) {
                 $bucket = CCloudStorage::findBucketByFile($fullPath);
                 if (!$bucket) {
                     $this->storeStorageId($version['VERSION_ID']);
                     continue;
                 }
             }
             $handlerId = $bucket->ID;
             $subDir = trim(substr(getDirPath($fullPath), strlen($bucket->getFileSRC('/'))), '/');
             $contentType = \Bitrix\Disk\TypeFile::getMimeTypeByFilename($filename);
         } else {
             $subDir = trim(substr(getDirPath($fullPath), strlen('/' . $uploadDir)), '/');
             $contentType = CFile::getContentType($_SERVER["DOCUMENT_ROOT"] . $fullPath);
             $contentType = \Bitrix\Disk\TypeFile::normalizeMimeType($contentType, $filename);
         }
         $webdavSize = $version['VERSION_DOC']['PROPERTIES']['WEBDAV_SIZE']['VALUE'];
         if (empty($webdavSize)) {
             $webdavSize = 0;
         }
         $fileId = CFile::doInsert(array('HEIGHT' => 0, 'WIDTH' => 0, 'FILE_SIZE' => $webdavSize, 'CONTENT_TYPE' => $contentType, 'SUBDIR' => $subDir, 'FILE_NAME' => $filename, 'MODULE_ID' => Driver::INTERNAL_MODULE_ID, 'ORIGINAL_NAME' => $filename, 'DESCRIPTION' => '', 'HANDLER_ID' => $handlerId, 'EXTERNAL_ID' => md5(mt_rand())));
         if (!$fileId) {
             $this->storeStorageId($version['VERSION_ID']);
             continue;
         }
         $this->connection->queryExecute("\n\t\t\t\tINSERT INTO b_disk_version (OBJECT_ID, FILE_ID, " . $this->sqlHelper->quote('SIZE') . ", NAME, CREATE_TIME, CREATED_BY, MISC_DATA, OBJECT_CREATE_TIME, OBJECT_CREATED_BY, OBJECT_UPDATE_TIME, OBJECT_UPDATED_BY, GLOBAL_CONTENT_VERSION, BP_VERSION_ID)\n\t\t\t\tVALUES ({$version['ID']}, {$fileId}, {$webdavSize}, '{$version['VERSION_NAME']}', {$version['VERSION_MODIFIED']},  {$version['VERSION_USER_ID']}, null, {$version['VERSION_MODIFIED']}, {$version['CREATED_BY']}, {$version['UPDATE_TIME']}, {$version['UPDATED_BY']}, {$version['VERSION_DOC']['PROPERTIES']['WEBDAV_VERSION']['VALUE']}, {$version['VERSION_ID']})\n\t\t\t");
         $this->storeStorageId($version['VERSION_ID']);
     }
     $this->abortIfNeeded();
     $this->storeStorageId(0);
     $this->setStepFinished(__METHOD__);
 }