Example #1
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));
 }
 /**
  * @inheritdoc
  */
 public function getExtension()
 {
     // Generate the extension based on the MIME type if possible, eliminates inconsistencies
     $mimeType = end(FileHelper::getExtensionsByMimeType($this->getType()));
     // Fallback on the file extension
     if ($mimeType === false) {
         $mimeType = substr($this->uri, strrpos($this->uri, '.') + 1);
     }
     return $mimeType;
 }
Example #3
0
 /**
  * @return null|string
  */
 function generateName()
 {
     if (!file_exists($this->tmp_name)) {
         return null;
     }
     $finfo = new finfo(FILEINFO_MIME_TYPE);
     $extension = FileHelper::getExtensionsByMimeType($finfo->buffer(file_get_contents($this->tmp_name, FILEINFO_MIME_TYPE)));
     $extension = empty($extension) ? '' : $extension[0];
     $hash = sha1_file($this->tmp_name);
     return "{$hash}.{$this->size}.{$extension}";
 }
Example #4
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;
 }
Example #5
0
 /**
  *
  * Загрузить файл в хранилище, добавить в базу, вернуть модель 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;
 }
 public static function getExtensionByMimeType($mimeType)
 {
     $extensions = FileHelper::getExtensionsByMimeType($mimeType);
     if (empty($extensions)) {
         return false;
     }
     return mb_strtolower($extensions[0], 'utf-8');
 }
Example #7
0
 /**
  * @return mixed
  */
 public function getExtensionByMimeType()
 {
     $extensions = FileHelper::getExtensionsByMimeType($this->getMimeType());
     return array_shift($extensions);
 }
 /**
  * @param $body
  * @return array|null
  * @throws InvalidConfigException
  */
 protected static function getExtensionName($body)
 {
     if (@is_file($body)) {
         $info = getimagesize($body);
         if (empty($info)) {
             $mimeType = FileHelper::getMimeType($body);
             if ($mimeType && ($extensions = FileHelper::getExtensionsByMimeType($mimeType))) {
                 return $extensions ? current($extensions) : null;
             }
         } else {
             $mimeType = $info[2];
             return image_type_to_extension($mimeType, false);
         }
     } elseif ($info = getimagesizefromstring($body)) {
         $mimeType = $info[2];
         return image_type_to_extension($mimeType, false);
     }
     return null;
 }
Example #9
0
 /**
  * Upload file
  * @param \yii\web\UploadedFile $file
  * @return bool
  */
 public function upload($file)
 {
     if (is_string($file)) {
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, $file);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
         curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
         $content = curl_exec($ch);
         $info = curl_getinfo($ch);
         if (curl_error($ch)) {
             return false;
         }
         curl_close($ch);
         if ($info['http_code'] != 200) {
             return false;
         }
         $tempName = tempnam(sys_get_temp_dir(), 'php');
         $tempHandle = fopen($tempName, 'w');
         fwrite($tempHandle, $content);
         fclose($tempHandle);
         $arr = explode('/', $file);
         $fileName = explode('?', end($arr))[0];
         $this->model->size = filesize($tempName);
         $this->model->content_type = mime_content_type($tempName);
         $types = FileHelper::getExtensionsByMimeType($this->model->content_type);
         $this->model->ext = end($types);
         $this->model->file_name = $fileName ? $fileName : 'unnamed.' . $this->model->ext;
     } elseif ($file instanceof \yii\web\UploadedFile) {
         $tempName = $file->tempName;
         $this->model->size = $file->size;
         $this->model->file_name = $file->name;
         $this->model->content_type = $file->type;
         $this->model->ext = $file->extension;
     } else {
         return false;
     }
     if (($imageInfo = getimagesize($tempName)) !== false) {
         $this->model->width = $imageInfo[0];
         $this->model->height = $imageInfo[1];
         $this->model->is_image = true;
     }
     $this->model->code = md5(time() . implode('', $this->model->attributes));
     if (!$this->model->save()) {
         return false;
     }
     $dir = $this->dir . '/' . $this->model->id . '/';
     FileHelper::createDirectory($dir);
     $original = $dir . 'original.' . $this->model->ext;
     if (is_string($file)) {
         @rename($tempName, $original);
     } else {
         if (!$file->saveAs($original)) {
             return false;
         }
     }
     if ($fp = fopen($dir . $this->model->code . '.txt', 'w')) {
         fclose($fp);
     } else {
         return false;
     }
     return true;
 }
Example #10
0
 public static function upload($file, $name = null, $dir = self::F_FILES, $slug = null, $data = null, $delete = true)
 {
     if (is_null($dir)) {
         $dir = self::F_FILES;
     }
     $dir = trim($dir);
     $filePath = '';
     if (strpos($file, 'http') === 0) {
         $tmp = Yii::getAlias('@runtime') . DIRECTORY_SEPARATOR . uniqid("fu");
         file_put_contents($tmp, file_get_contents($file));
         $filePath = $tmp;
         $name = $name ? $name : basename($file);
     } elseif (is_string($file)) {
         $filePath = Yii::getAlias($file);
     } elseif ($file instanceof UploadedFile) {
         $filePath = $file->tempName;
         $name = $name ? $name : $file->name;
     }
     $name = $name ? $name : basename($filePath);
     $sec = new Security();
     while (FileUpload::find()->where(["path" => $uniquePath = md5($sec->generateRandomString())])->one()) {
     }
     $dirSlug = $dir;
     if (!is_dir($dir) && !($dir = self::getFolder($dirSlug))) {
         if (!$dir) {
             throw new \Exception("Folder for param '{$dirSlug}' is not set");
         } else {
             throw new \Exception("Folder '{$dir}' not found");
         }
     }
     $fullPath = self::formPath($uniquePath, $dir);
     if (!FileHelper::createDirectory(dirname($fullPath))) {
         throw new \Exception("Can't create folder '{" . dirname($fullPath) . "}'");
     }
     if (!file_exists($filePath)) {
         throw new \Exception('File not loaded or not exist');
     }
     if (is_uploaded_file($filePath)) {
         if (!move_uploaded_file($filePath, $fullPath)) {
             throw new \Exception('Unknown upload error');
         }
     } elseif ($delete ? !rename($filePath, $fullPath) : !copy($filePath, $fullPath)) {
         throw new \Exception('Failed to write file to disk');
     }
     $info = pathinfo($name);
     $fileUpload = new self();
     //Фиск для сессии, при аяксовом запросе
     if (isset(Yii::$app->session)) {
         Yii::$app->session->open();
         $fileUpload->session = Yii::$app->session->getIsActive() ? Yii::$app->session->getId() : null;
         Yii::$app->session->close();
     }
     $fileUpload->user_id = CurrentUser::getId(1);
     $fileUpload->data = !is_null($data) ? json_encode($data) : null;
     $fileUpload->mime_type = FileHelper::getMimeType($fullPath);
     $fileUpload->md5 = md5_file($fullPath);
     $fileUpload->folder = $dirSlug;
     $fileUpload->path = $uniquePath;
     $fileUpload->slug = $slug;
     $fileUpload->size = filesize($fullPath);
     if (!($extension = strtolower(ArrayHelper::getValue($info, "extension")))) {
         $extension = ArrayHelper::getValue(FileHelper::getExtensionsByMimeType($fileUpload->mime_type), 0);
     }
     $fileUpload->name = basename($name, '.' . $extension);
     $fileUpload->extension = $extension;
     if ($fileUpload->save()) {
         return $fileUpload;
     } else {
         $fileUpload->deleteFile();
         return null;
     }
 }