/** * Add a new file based on the source to the storage system. * * When using the $_FILES array you can also make usage of the file helper methods: * * + {{luya\admin\helpers\Storage::uploadFromFiles}} * + {{luya\admin\helpers\Storage::uploadFromFileArray}} * * When not using the $_FILES array: * * ```php * Yii::$app->storage->addFile('/the/path/to/File.jpg', 'File.jpg', 0, 1); * ``` * * @param string $fileSource Path to the file source where the file should be created from * @param string $fileName The name of this file (must contain data type suffix). * @param integer $folderId The id of the folder where the file should be stored in. * @param boolean $isHidden Should the file visible in the filemanager or not. * @return \luya\admin\file\Item|\luya\Exception|boolean Returns the item object, if an error happens an exception is thrown. */ public function addFile($fileSource, $fileName, $folderId = 0, $isHidden = false) { if (empty($fileSource) || empty($fileName)) { throw new Exception("Unable to create file where file source and/or file name is empty."); } if ($fileName == 'blob') { $ext = FileHelper::getExtensionsByMimeType(FileHelper::getMimeType($fileSource)); $fileName = 'paste-' . date("Y-m-d-H-i") . '.' . $ext[0]; } $fileInfo = FileHelper::getFileInfo($fileName); $baseName = Inflector::slug($fileInfo->name, '-'); $fileHashName = Storage::createFileHash($fileName); $fileHash = FileHelper::getFileHash($fileSource); $mimeType = FileHelper::getMimeType($fileSource); $newName = implode([$baseName . '_' . $fileHashName, $fileInfo->extension], '.'); $savePath = $this->serverPath . '/' . $newName; if (is_uploaded_file($fileSource)) { if (!@move_uploaded_file($fileSource, $savePath)) { throw new Exception("error while moving uploaded file from {$fileSource} to {$savePath}"); } } else { if (!@copy($fileSource, $savePath)) { throw new Exception("error while copy file from {$fileSource} to {$savePath}."); } } $model = new StorageFile(); $model->setAttributes(['name_original' => $fileName, 'name_new' => $baseName, 'name_new_compound' => $newName, 'mime_type' => $mimeType, 'extension' => strtolower($fileInfo->extension), 'folder_id' => (int) $folderId, 'hash_file' => $fileHash, 'hash_name' => $fileHashName, 'is_hidden' => $isHidden ? 1 : 0, 'is_deleted' => 0, 'file_size' => @filesize($savePath), 'caption' => null]); if ($model->validate()) { if ($model->save()) { $this->deleteHasCache($this->_fileCacheKey); $this->_filesArray[$model->id] = $model->toArray(); return $this->getFile($model->id); } } return false; }