예제 #1
1
 public function upload()
 {
     // $this->getAttributes()
     $mime_type = \yii\helpers\FileHelper::getMimeType($this->file->tempName);
     if ($this->validate($mime_type)) {
         $this->file_path = 'uploads/' . $this->file->baseName . '.' . $this->file->extension;
         return $this->file->saveAs($this->file_path);
     } else {
         return false;
     }
 }
 /**
  * Returns UploadFile created from url
  * Notice that this file cannot be saved by move_uploaded_file
  * @param $url
  * @throws \yii\base\InvalidConfigException
  */
 public static function getFromUrl($url)
 {
     $tmpFile = null;
     if (static::isExternalUrl($url)) {
         //External url
         $tmpFile = static::downloadToTmp($url);
     } else {
         //File must be in static folder
         $staticPath = Yii::getAlias('@static/');
         $path = str_replace(Yii::getAlias('@staticUrl/'), Yii::getAlias('@static/'), Yii::getAlias($url), $count);
         //If we can replace static url to path
         if ($count > 0) {
             //Check staticPath after normalize
             $path = FileHelper::normalizePath($path);
             if (strpos($path, $staticPath) === 0) {
                 if (file_exists($path)) {
                     $tmpFile = tempnam(sys_get_temp_dir(), 'CURL');
                     if (!copy($path, $tmpFile)) {
                         $tmpFile = null;
                     }
                 }
             }
         }
     }
     if ($tmpFile) {
         return new static(['name' => basename($url), 'tempName' => $tmpFile, 'type' => FileHelper::getMimeType($tmpFile), 'size' => filesize($tmpFile), 'error' => UPLOAD_ERR_OK]);
     }
     return null;
 }
예제 #3
0
 /**
  * @return string
  */
 public function toJson()
 {
     $toJson = [];
     foreach (FileHelper::findFiles($this->getPath()) as $this->_file) {
         $toJson = ArrayHelper::merge($toJson, [['title' => $this->normalizeFilename(), 'name' => FileHelper::getMimeType($this->_file), 'link' => $this->getUrl(), 'size' => $this->getSize()]]);
     }
     return Json::encode($toJson);
 }
예제 #4
0
 private function getImageFormat($fn)
 {
     $f = FileHelper::getMimeType($fn);
     if ($f === null) {
         throw new NotSupportedException("ImageBehavior - Неизвестный тип файла");
     }
     $this->_format = str_replace('image/', '', $f);
 }
예제 #5
0
 /**
  * @param $content
  *
  * @return mixed
  * @throws \yii\base\InvalidConfigException
  */
 protected function determineExtension($content)
 {
     $filename = \Yii::getAlias('@runtime/' . uniqid());
     file_put_contents($filename, $content);
     $mime = FileHelper::getMimeType($filename);
     $extensions = FileHelper::getExtensionsByMimeType($mime);
     unlink($filename);
     return ArrayHelper::getValue($extensions, max(count($extensions) - 1, 0));
 }
예제 #6
0
 /**
  * @inheritdoc
  */
 public function init()
 {
     $this->tempName = $this->flowConfig->getTempDir() . DIRECTORY_SEPARATOR . $this->tempName;
     $this->error = file_exists($this->tempName) ? UPLOAD_ERR_OK : UPLOAD_ERR_NO_FILE;
     if ($this->error === UPLOAD_ERR_OK) {
         $this->type = FileHelper::getMimeType($this->tempName);
         $this->size = filesize($this->tempName);
     }
 }
예제 #7
0
 /**
  * Create file from path
  *
  * @param string $path Path in filesystem or URL
  * @param int $ownerId
  * @param int $ownerType
  * @param bool $saveAfterUpload Save the file immediately after upload
  * @param bool $protected File is protected?
  * @return \rkit\filemanager\models\File|bool
  */
 public function createFromPath($path, $ownerId = -1, $ownerType = -1, $saveAfterUpload = false, $protected = false)
 {
     $tempfile = tempnam(sys_get_temp_dir(), 'FMR');
     if ($filecontent = @file_get_contents($path)) {
         file_put_contents($tempfile, $filecontent);
         $pathInfo = pathinfo($path);
         $file = new File(['tmp' => true, 'owner_id' => $ownerId, 'owner_type' => $ownerType, 'size' => filesize($tempfile), 'mime' => FileHelper::getMimeType($tempfile), 'title' => $pathInfo['filename'], 'name' => File::generateName($pathInfo['extension']), 'protected' => $protected]);
         return $file->saveToTmp($tempfile, $saveAfterUpload, false);
     } else {
         throw new InvalidValueException('Unable to create from `' . $path . '`');
     }
 }
예제 #8
0
 /**
  * Uploads the file into S3 in that bucket.
  *
  * @param string $filePath Full path of the file. Can be from tmp file path.
  * @param string $fileName Filename to save this file into S3. May include directories.
  * @param bool $bucket Override configured bucket.
  * @return bool|string The S3 generated url that is publicly-accessible.
  */
 public function uploadFile($filePath, $fileName, $bucket = false)
 {
     if (!$bucket) {
         $bucket = $this->bucket;
     }
     try {
         $result = $this->_client->putObject(['ACL' => 'public-read', 'Bucket' => $bucket, 'Key' => $fileName, 'SourceFile' => $filePath, 'ContentType' => \yii\helpers\FileHelper::getMimeType($filePath)]);
         return $result->get('ObjectURL');
     } catch (\Exception $e) {
         return false;
     }
 }
예제 #9
0
 /**
  * Create manually UploadedFile instance by file path
  *
  * @param string $path file path
  * @return UploadedFile
  */
 private function makeUploadedFile($path)
 {
     $tmpFile = tempnam(sys_get_temp_dir(), 'app');
     file_put_contents($tmpFile, file_get_contents($path));
     $uploadedFile = new UploadedFile();
     $uploadedFile->name = pathinfo($path, PATHINFO_BASENAME);
     $uploadedFile->tempName = $tmpFile;
     $uploadedFile->type = FileHelper::getMimeType($tmpFile);
     $uploadedFile->size = filesize($tmpFile);
     $uploadedFile->error = 0;
     return $uploadedFile;
 }
예제 #10
0
 public static function createFromUploadedFile(UploadedFile $file)
 {
     $upload = new static();
     $upload->mimetype = FileHelper::getMimeType($file->tempName);
     $upload->checksum = hash_file('sha256', $file->tempName);
     $upload->filename = $file->getBaseName() . '.' . $file->getExtension();
     $upload->filesize = $file->size;
     $upload->createContainerDir();
     $file->SaveAs($upload->getContainerDir() . '/' . $upload->filename);
     $upload->save();
     return $upload;
 }
예제 #11
0
 public function getInitialPreview()
 {
     $initialPreview = [];
     $userTempDir = $this->getModule()->getUserDirPath();
     foreach (FileHelper::findFiles($userTempDir) as $file) {
         if (substr(FileHelper::getMimeType($file), 0, 5) === 'image') {
             $initialPreview[] = Html::img(['/attachments/file/download-temp', 'filename' => basename($file)], ['class' => 'file-preview-image']);
         } else {
             $initialPreview[] = Html::beginTag('div', ['class' => 'file-preview-other']) . Html::beginTag('h2') . Html::tag('i', '', ['class' => 'glyphicon glyphicon-file']) . Html::endTag('h2') . Html::endTag('div');
         }
     }
     foreach ($this->getFiles() as $file) {
         if (substr($file->mime, 0, 5) === 'image') {
             $initialPreview[] = Html::img($file->getUrl(), ['class' => 'file-preview-image']);
         } else {
             $initialPreview[] = Html::beginTag('div', ['class' => 'file-preview-other']) . Html::beginTag('h2') . Html::tag('i', '', ['class' => 'glyphicon glyphicon-file']) . Html::endTag('h2') . Html::endTag('div');
         }
     }
     return $initialPreview;
 }
예제 #12
0
 /**
  * @inheritdoc
  */
 public function rules()
 {
     return [[['file'], 'required'], [['file'], 'file', 'skipOnEmpty' => false], [['uploadPath'], 'required', 'when' => function ($obj) {
         return empty($obj->filename);
     }], [['name', 'size'], 'default', 'value' => function ($obj, $attribute) {
         return $obj->file->{$attribute};
     }], [['type'], 'default', 'value' => function () {
         return FileHelper::getMimeType($this->file->tempName);
     }], [['filename'], 'default', 'value' => function () {
         $key = md5(microtime() . $this->file->name);
         $base = Yii::getAlias($this->uploadPath);
         if ($this->directoryLevel > 0) {
             for ($i = 0; $i < $this->directoryLevel; ++$i) {
                 if (($prefix = substr($key, $i + $i, 2)) !== false) {
                     $base .= DIRECTORY_SEPARATOR . $prefix;
                 }
             }
         }
         return $base . DIRECTORY_SEPARATOR . "{$key}_{$this->file->name}";
     }], [['size'], 'integer'], [['name'], 'string', 'max' => 64], [['type'], 'string', 'max' => 32], [['filename'], 'string', 'max' => 256]];
 }
예제 #13
0
 public function validateExtension($attribute, $params)
 {
     $file = $this->{$attribute};
     $pathinfo = pathinfo(mb_strtolower($file->name, 'utf-8'));
     if (!empty($pathinfo['extension'])) {
         $extension = $pathinfo['extension'];
     } else {
         return false;
     }
     if ($this->checkExtensionByMimeType) {
         $mimeType = FileHelper::getMimeType($file->tempName, null, false);
         if ($mimeType === null) {
             return false;
         }
         if (!FileHelper::getMimeTypeByExtension($file)) {
             return false;
         }
     }
     if (!in_array($extension, $this->extensions, true)) {
         return false;
     }
     return true;
 }
예제 #14
0
 /**
  * Saves UploadedFile from fileData if exists and puts in it FileInfo
  * @return bool
  */
 public function save()
 {
     if (empty($this->uploadedFile)) {
         return $this->fileInfo ? true : false;
     }
     $file = $this->uploadedFile;
     $fileHash = md5_file($file->tempName);
     // just in case if file already exists
     $existingFileInfo = FileInfo::findOne(['hash' => $fileHash]);
     if ($existingFileInfo) {
         $this->fileInfo = $existingFileInfo;
         return true;
     }
     $filePath = Yii::getAlias('@files/' . $fileHash . '.' . $file->extension);
     if (!$file->saveAs($filePath)) {
         return false;
     }
     $mimeType = MimeType::findOne(['name' => FileHelper::getMimeType($filePath)]);
     $fileInfo = new FileInfo(['filePath' => $filePath, 'originalName' => $file->name, 'hash' => $fileHash, 'mimeTypeId' => $mimeType->id, 'size' => $file->size]);
     $result = $fileInfo->save();
     $this->fileInfo = $result ? $fileInfo : null;
     return $result;
 }
예제 #15
0
파일: UploadForm.php 프로젝트: 2377635/test
 /**
  * Загрузка файла. При успехе создание и сохранение модели Attachment
  * @return boolean
  */
 public function upload()
 {
     $ext = $this->file->extension;
     $origName = $this->file->baseName . '.' . $ext;
     $size = $this->file->size;
     $fileName = md5(uniqid()) . '.' . $ext;
     $path = $this->getUploadDir() . '/' . $fileName;
     if ($this->file->saveAs($path)) {
         // создаем и сохраняем модель Attachment
         $attachment = new Attachment();
         $attachment->document_id = $this->documentID;
         $attachment->origname = $origName;
         $attachment->filename = $fileName;
         $attachment->mimetype = FileHelper::getMimeType($path);
         $attachment->size = $size;
         if ($attachment->save()) {
             return true;
         } else {
             // если ничего не получилось, удаляем загруженный файл
             unlink($path);
         }
     }
     return false;
 }
예제 #16
0
 /**
  * @param string $attribute Attribute name
  *
  * @return string Attribute mime-type
  */
 public function getMimeType($attribute)
 {
     return FileHelper::getMimeType($this->file($attribute));
 }
예제 #17
0
 /**
  * Register event handlers
  */
 protected function registerEventHandlers()
 {
     $this->on(static::EVENT_BEFORE_VALIDATE, function (\yii\base\ModelEvent $Event) {
         /** @var static $Model */
         $Model = $Event->sender;
         $Model->size = filesize($Model->path);
         $Model->mime = FileHelper::getMimeType($Model->path);
         $Model->sha1 = sha1_file($Model->path);
     });
 }
예제 #18
0
 /**
  * Shows file to the browser.
  * @throws NotFoundHttpException
  */
 public function showFile()
 {
     $file = $this->getFilePath();
     if (!file_exists($file)) {
         throw new NotFoundHttpException();
     }
     if (ob_get_contents()) {
         ob_end_clean();
     }
     header('Content-Type: ' . FileHelper::getMimeType($file), true);
     header('Content-Length: ' . filesize($file));
     readfile($file);
 }
예제 #19
0
 /**
  * @param $filePath string
  * @param $owner
  * @return bool|File
  * @throws \Exception
  * @throws \yii\base\InvalidConfigException
  */
 public function attachFile($filePath, $owner)
 {
     if (!$owner->id) {
         throw new \Exception('Owner must have id when you attach file');
     }
     if (!file_exists($filePath)) {
         throw new \Exception('File not exist :' . $filePath);
     }
     $fileHash = md5(microtime(true) . $filePath);
     $fileType = pathinfo($filePath, PATHINFO_EXTENSION);
     $newFileName = $fileHash . '.' . $fileType;
     $fileDirPath = $this->getFilesDirPath($fileHash);
     $newFilePath = $fileDirPath . DIRECTORY_SEPARATOR . $newFileName;
     copy($filePath, $newFilePath);
     if (!file_exists($filePath)) {
         throw new \Exception('Cannot copy file! ' . $filePath . ' to ' . $newFilePath);
     }
     $file = new File();
     $file->name = pathinfo($filePath, PATHINFO_FILENAME);
     $file->model = $this->getShortClass($owner);
     $file->itemId = $owner->id;
     $file->hash = $fileHash;
     $file->size = filesize($filePath);
     $file->type = $fileType;
     $file->mime = FileHelper::getMimeType($filePath);
     if ($file->save()) {
         unlink($filePath);
         return $file;
     } else {
         if (count($file->getErrors()) > 0) {
             $ar = array_shift($file->getErrors());
             unlink($newFilePath);
             throw new \Exception(array_shift($ar));
         }
         return false;
     }
 }
예제 #20
0
 public function testEmbedFile()
 {
     $message = new Message();
     $fileName = __DIR__ . '/../test_image.png';
     $cid = $message->embed($fileName);
     $this->assertEquals('image_0', $cid);
     $images = $message->getImages();
     $this->assertCount(1, $images);
     $image = $images[0];
     $this->assertEquals($image['name'], 'test_image.png');
     $this->assertEquals($image['type'], \yii\helpers\FileHelper::getMimeType($fileName));
     $this->assertEquals($image['data'], base64_encode(file_get_contents($fileName)));
     $cid1 = $message->embed($fileName);
     $images = $message->getImages();
     $this->assertEquals('image_1', $cid1);
     $this->assertCount(2, $images);
 }
예제 #21
0
파일: File.php 프로젝트: heartshare/yii2-sx
 /**
  * @return string
  * @throws \yii\base\InvalidConfigException
  */
 public function getMimeType()
 {
     return FileHelper::getMimeType($this->getPath());
 }
예제 #22
0
 public function save(UploadedFile $uploadedFile, $storageId = null)
 {
     $storageId = $storageId ?: $this->defaultStorage;
     $file = new File();
     $file->path = $uploadedFile->tempName;
     $file->size = filesize($file->path);
     $file->mime = FileHelper::getMimeType($file->path);
     # image params
     $imageInfo = getimagesize($file->path);
     if ($imageInfo) {
         list($width, $height) = $imageInfo;
         if ($width && $height) {
             $file->width = $width;
             $file->height = $height;
         }
     }
     $file->temp = 1;
     $file->original_name = $uploadedFile->name;
     #TODO пока хардкором
     //$file->storage_id = $storageId;
     $file->storage_id = 1;
     if ($file->save()) {
         $newName = sprintf('%010d', $file->id);
         $newName = substr($newName, -3) . '/' . substr($newName, -6, 3) . '/' . $newName;
         $ext = $uploadedFile->extension;
         if ($ext) {
             $newName = $newName . '.' . mb_strtolower($ext);
         }
         $storage = $this->getStorage($storageId);
         #TODO не учитывает разные стораджи
         $stream = fopen($file->path, 'r+');
         if ($storage->writeStream($newName, $stream)) {
             $file->path = $newName;
             $file->temp = null;
             if ($file->save()) {
                 return $file;
             }
         }
     } else {
         print_r($file->errors);
     }
     return false;
 }
예제 #23
0
 /**
  * Finds the uploaded through the web file, creating [[UploadedFile]] instance.
  * If parameter $fullFileName is passed, creates a mock up instance of [[UploadedFile]] from the local file,
  * passed with this parameter.
  * @param UploadedFile|string|null $uploadedFile - source full file name for the [[UploadedFile]] mock up.
  * @return UploadedFile|null uploaded file.
  */
 protected function ensureUploadedFile($uploadedFile = null)
 {
     if ($uploadedFile instanceof UploadedFile) {
         return $uploadedFile;
     }
     if (!empty($uploadedFile)) {
         return new UploadedFile(['name' => basename($uploadedFile), 'tempName' => $uploadedFile, 'type' => FileHelper::getMimeType($uploadedFile), 'size' => filesize($uploadedFile), 'error' => UPLOAD_ERR_OK]);
     }
     if ($this->autoFetchUploadedFile) {
         $owner = $this->owner;
         $fileAttributeName = $this->fileAttribute;
         $tabularInputIndex = $this->fileTabularInputIndex;
         if ($tabularInputIndex !== null) {
             $fileAttributeName = "[{$tabularInputIndex}]{$fileAttributeName}";
         }
         $uploadedFile = UploadedFile::getInstance($owner, $fileAttributeName);
         if (is_object($uploadedFile)) {
             if (!$uploadedFile->getHasError() && !file_exists($uploadedFile->tempName)) {
                 // uploaded file has been already processed:
                 return null;
             } else {
                 return $uploadedFile;
             }
         }
     }
     return null;
 }
예제 #24
0
 /**
  * Create a cfile model and create and connect it with its basefile File model from a given data file, connect it with its parent folder.
  * TODO: This method has a lot in common with BrowseController/actionUpload, common logic needs to be extracted and reused
  *
  * @param Response $response
  *            the response errors will be parsed to.
  * @param int $parentFolderId
  *            the files pid.
  * @param string $folderPath
  *            the path of the folder the file data lies in.
  * @param string $filename
  *            the files name.
  */
 protected function generateModelFromFile(&$response, $parentFolderId, $folderPath, $filename)
 {
     $filepath = $folderPath . DIRECTORY_SEPARATOR . $filename;
     // check if the file already exists in this dir
     $filesQuery = File::find()->joinWith('baseFile')->readable()->andWhere(['title' => File::sanitizeFilename($filename), 'parent_folder_id' => $parentFolderId]);
     $file = $filesQuery->one();
     // if not, initialize new File
     if (empty($file)) {
         $file = new File();
         $humhubFile = new \humhub\modules\file\models\File();
     } else {
         // else replace the existing file
         $humhubFile = $file->baseFile;
         // logging file replacement
         $response['infomessages'][] = Yii::t('CfilesModule.base', '%title% was replaced by a newer version.', ['%title%' => $file->title]);
         $response['log'] = true;
     }
     // populate the file
     $humhubFile->mime_type = FileHelper::getMimeType($filepath);
     if ($humhubFile->mime_type == 'image/jpeg') {
         ImageConverter::TransformToJpeg($filepath, $filepath);
     }
     $humhubFile->size = filesize($filepath);
     $humhubFile->file_name = $filename;
     $humhubFile->newFileContent = stream_get_contents(fopen($filepath, 'r'));
     if ($humhubFile->save()) {
         $file->content->container = $this->contentContainer;
         $file->parent_folder_id = $parentFolderId;
         if ($file->save()) {
             $humhubFile->object_model = $file->className();
             $humhubFile->object_id = $file->id;
             $humhubFile->save();
             $this->files[] = array_merge($humhubFile->getInfoArray(), ['fileList' => $this->renderFileList()]);
         } else {
             $count = 0;
             $messages = "";
             // show multiple occurred errors
             foreach ($file->errors as $key => $message) {
                 $messages .= ($count++ ? ' | ' : '') . $message[0];
             }
             $response['errormessages'][] = Yii::t('CfilesModule.base', 'Could not save file %title%. ', ['%title%' => $file->title]) . $messages;
             $response['log'] = true;
         }
     } else {
         $count = 0;
         $messages = "";
         // show multiple occurred errors
         foreach ($humhubFile->errors as $key => $message) {
             $messages .= ($count++ ? ' | ' : '') . $message[0];
         }
         $response['errormessages'][] = Yii::t('CfilesModule.base', 'Could not save file %title%. ', ['%title%' => $humhubFile->filename]) . $messages;
         $response['log'] = true;
     }
 }
예제 #25
0
$tplFooter = <<<'TPL'
    <div class="file-thumbnail-footer">
        <div style="margin:5px 0">
            <input class="kv-input kv-new form-control input-sm" type="hidden" value="{caption}" />
        </div>
        {actions}
    </div>
TPL;
$initialPreview = [];
$initialPreviewConfig = [];
$layoutTemplates = ['footer' => $tplFooter];
foreach ($model->{$property_key} as $file) {
    if (file_exists(Yii::getAlias($additional['uploadDir']) . '/' . $file) === false) {
        continue;
    }
    $_preview = \yii\helpers\FileHelper::getMimeType(Yii::getAlias($additional['uploadDir']) . '/' . $file);
    $_preview = false !== strpos(strval($_preview), 'image/') ? Html::img(['property-handler', 'handler_action' => 'show-file', 'fileName' => $file, 'property_id' => $property_id, 'model_id' => $model->ownerModel->id], ['class' => 'file-preview-image', 'alt' => $file, 'title' => $file]) : \kartik\icons\Icon::show('file', ['style' => 'font-size: 42px']);
    $initialPreview[] = $_preview . Html::hiddenInput($model->formName() . '[' . $property_key . '][]', $file);
    $initialPreviewConfig[] = ['caption' => $file, 'url' => $urlDelete, 'key' => $property_key, 'extra' => ['value' => $file]];
}
$modelArrayMode = $model->setArrayMode(false);
// @TODO: maybe it's a good to replace fileuploaded with fileloaded (and this part of code for it)
//    $_js = <<< 'JSCODE'
//    function(event, file, previewId, index, reader) {
//        var name = file.name;
//        var hi = $('<input type="hidden" name="%s" />').val(name);
//        $('div.file-preview-frame[title="'+name+'"]').append(hi);
//    }
//JSCODE;
?>
<div class="file_input_preview">
 public function attachFile($file, $moveFile = false)
 {
     if (!$this->owner->getIsNewRecord()) {
         $this->clearAttachData();
     }
     $extension = pathinfo($file, PATHINFO_EXTENSION);
     if (empty($extension)) {
         $extension = static::getExtensionByMimeType(FileHelper::getMimeType($file));
     }
     $this->generateAttr($extension);
     $filePath = $this->getPath();
     if (!FileHelper::createDirectory(dirname($filePath))) {
         return false;
     }
     if ($moveFile) {
         if (!rename($file, $filePath)) {
             return false;
         }
     } else {
         if (!copy($file, $filePath)) {
             return false;
         }
     }
     return true;
 }
예제 #27
0
 /**
  * Adds a file for upload as multi-part content.
  * @see addContent()
  * @param string $name part (form input) name
  * @param string $fileName full name of the source file.
  * @param array $options content part options, valid options are:
  *  - fileName - string, base name of the uploading file, if not set it base name of the source file will be used.
  *  - mimeType - string, file mime type, if not set it will be determine automatically from source file.
  * @return $this
  */
 public function addFile($name, $fileName, $options = [])
 {
     $content = file_get_contents($fileName);
     if (!isset($options['mimeType'])) {
         $options['mimeType'] = FileHelper::getMimeType($fileName);
     }
     if (!isset($options['fileName'])) {
         $options['fileName'] = basename($fileName);
     }
     return $this->addContent($name, $content, $options);
 }
예제 #28
0
파일: Storage.php 프로젝트: Liv1020/cms
 /**
  *
  * Загрузить файл в хранилище, добавить в базу, вернуть модель StorageFile
  *
  * @param UploadedFile|string|File $file    объект UploadedFile или File или rootPath до файла локально или http:// путь к файлу (TODO:: доделать)
  * @param array $data                       данные для сохранения в базу
  * @param null $clusterId                   идентификатор кластера по умолчанию будет выбран первый из конфигурации
  * @return StorageFile
  * @throws Exception
  */
 public function upload($file, $data = [], $clusterId = null)
 {
     //Для начала всегда загружаем файл во временную диррикторию
     $tmpdir = Dir::runtimeTmp();
     $tmpfile = $tmpdir->newFile();
     if ($file instanceof UploadedFile) {
         $extension = File::object($file->name)->getExtension();
         $tmpfile->setExtension($extension);
         if (!$file->saveAs($tmpfile->getPath())) {
             throw new Exception("Файл не загружен во временную диррикторию");
         }
     } else {
         if ($file instanceof File || is_string($file) && BaseUrl::isRelative($file)) {
             $file = File::object($file);
             $tmpfile->setExtension($file->getExtension());
             $tmpfile = $file->move($tmpfile);
         } else {
             if (is_string($file) && !BaseUrl::isRelative($file)) {
                 $curl_session = curl_init($file);
                 if (!$curl_session) {
                     throw new Exception("Неверная ссылка");
                 }
                 curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, true);
                 curl_setopt($curl_session, CURLOPT_BINARYTRANSFER, true);
                 $file_content = curl_exec($curl_session);
                 curl_close($curl_session);
                 if (!$file_content) {
                     throw new Exception("Не удалось скачать файл");
                 }
                 $extension = pathinfo($file, PATHINFO_EXTENSION);
                 $pos = strpos($extension, "?");
                 if ($pos === false) {
                 } else {
                     $extension = substr($extension, 0, $pos);
                 }
                 if ($extension) {
                     $tmpfile->setExtension($extension);
                 }
                 $is_file_saved = file_put_contents($tmpfile, $file_content);
                 if (!$is_file_saved) {
                     throw new Exception("Не удалось сохранить файл");
                 }
                 //Если в ссылке нет расширения
                 if (!$extension) {
                     $tmpfile = new File($tmpfile->getPath());
                     try {
                         $mimeType = FileHelper::getMimeType($tmpfile->getPath(), null, false);
                     } catch (InvalidConfigException $e) {
                         throw new Exception("Не удалось пределить расширение файла: " . $e->getMessage());
                     }
                     if (!$mimeType) {
                         throw new Exception("Не удалось пределить расширение файла");
                     }
                     $extensions = FileHelper::getExtensionsByMimeType($mimeType);
                     if ($extensions) {
                         if (in_array("jpg", $extensions)) {
                             $extension = 'jpg';
                         } else {
                             if (in_array("png", $extensions)) {
                                 $extension = 'png';
                             } else {
                                 $extension = $extensions[0];
                             }
                         }
                         $newFile = new File($tmpfile->getPath());
                         $newFile->setExtension($extension);
                         $tmpfile = $tmpfile->copy($newFile);
                     }
                 }
             } else {
                 throw new Exception("Файл должен быть определен как \\yii\\web\\UploadedFile или \\skeeks\\sx\\File или string");
             }
         }
     }
     $data["type"] = $tmpfile->getType();
     $data["mime_type"] = $tmpfile->getMimeType();
     $data["size"] = $tmpfile->size()->getBytes();
     $data["extension"] = $tmpfile->getExtension();
     //Елси это изображение
     if ($tmpfile->getType() == 'image') {
         if (extension_loaded('gd')) {
             list($width, $height, $type, $attr) = getimagesize($tmpfile->toString());
             $data["image_height"] = $height;
             $data["image_width"] = $width;
         }
     }
     if ($cluster = $this->getCluster($clusterId)) {
         if ($newFileSrc = $cluster->upload($tmpfile)) {
             $data = array_merge($data, ["src" => $cluster->getPublicSrc($newFileSrc), "cluster_id" => $cluster->getId(), "cluster_file" => $newFileSrc]);
         }
     }
     $file = new StorageFile($data);
     $file->save(false);
     return $file;
 }
예제 #29
0
 /**
  * @return string|boolean
  */
 public function getMimeType()
 {
     return file_exists($this->filePath) ? FileHelper::getMimeType($this->filePath) : false;
 }
예제 #30
0
 /**
  * Checks if given uploaded file have correct type (extension) according current validator settings.
  * @param UploadedFile $file
  * @return boolean
  */
 protected function validateExtension($file)
 {
     $extension = mb_strtolower($file->extension, 'utf-8');
     if ($this->checkExtensionByMimeType) {
         $mimeType = FileHelper::getMimeType($file->tempName, null, false);
         if ($mimeType === null) {
             return false;
         }
         $extensionsByMimeType = FileHelper::getExtensionsByMimeType($mimeType);
         if (!in_array($extension, $extensionsByMimeType, true)) {
             return false;
         }
     }
     if (!in_array($extension, $this->extensions, true)) {
         return false;
     }
     return true;
 }