Example #1
0
 /**
  * @param \yii\web\UrlManager $manager
  * @param \yii\web\Request $request
  * @return array|bool
  */
 public function parseRequest($manager, $request)
 {
     $pathInfo = $request->getPathInfo();
     $params = $request->getQueryParams();
     $sourceOriginalFile = File::object($pathInfo);
     $extension = $sourceOriginalFile->getExtension();
     if (!$extension) {
         return false;
     }
     if (Validate::validate(new AllowExtension(), $extension)->isInvalid()) {
         return false;
     }
     return ['cms/imaging/process', $params];
 }
Example #2
0
 /**
  * @param \yii\web\UrlManager $manager
  * @param \yii\web\Request $request
  * @return array|bool
  */
 public function parseRequest($manager, $request)
 {
     $pathInfo = $request->getPathInfo();
     $params = $request->getQueryParams();
     $sourceOriginalFile = File::object($pathInfo);
     $extension = $sourceOriginalFile->getExtension();
     if (!$extension) {
         return false;
     }
     if (!in_array(StringHelper::strtolower($extension), (array) \Yii::$app->imaging->extensions)) {
         return false;
     }
     return ['cms/imaging/process', $params];
 }
Example #3
0
 /**
  * Lists all StorageFile models.
  * @return mixed
  */
 public function actionProcess()
 {
     ini_set("memory_limit", "512M");
     $imaging = \Yii::$app->imaging;
     if (!$imaging) {
         //TODO: можно добавить проверку YII ensure...
         throw new \yii\base\Exception("Component Imaging not found");
     }
     $newFileSrc = \Yii::$app->request->getPathInfo();
     $extension = Imaging::getExtension($newFileSrc);
     if (!$extension) {
         throw new \yii\base\Exception("Extension not found: " . $newFileSrc);
     }
     if (!$imaging->isAllowExtension($extension)) {
         throw new \yii\base\Exception("Extension '{$extension}' not supported in Imaging component");
     }
     $newFile = File::object($newFileSrc);
     $strposFilter = strpos($newFileSrc, "/" . Imaging::THUMBNAIL_PREFIX);
     if (!$strposFilter) {
         throw new \ErrorException("This is not a filter thumbnail: " . $newFileSrc);
     }
     $originalFileSrc = substr($newFileSrc, 0, $strposFilter) . "." . $newFile->getExtension();
     $webRoot = \Yii::getAlias('@webroot');
     $originalFileRoot = $webRoot . DIRECTORY_SEPARATOR . $originalFileSrc;
     $newFileRoot = $webRoot . DIRECTORY_SEPARATOR . $newFileSrc;
     $newFileRootDefault = $webRoot . DIRECTORY_SEPARATOR . str_replace($newFile->getBaseName(), Imaging::DEFAULT_THUMBNAIL_FILENAME . "." . $extension, $newFileSrc);
     $originalFile = new File($originalFileRoot);
     if (!$originalFile->isExist()) {
         throw new \ErrorException("The original file is not found: " . $newFileSrc);
     }
     //Проверено наличие оригинального файла, есть пути к оригиналу, и результирующему файлу.
     //Отслось собрать фильтр, и проверить наличие параметров. А так же проверить разрешены ли эти параметры, для этого в строке есть захэшированный ключь
     $filterSting = substr($newFileSrc, $strposFilter + strlen(DIRECTORY_SEPARATOR . Imaging::THUMBNAIL_PREFIX), strlen($newFileSrc));
     $filterCode = explode("/", $filterSting);
     $filterCode = $filterCode[0];
     //Код фильтра
     //Если указаны парамтры, то ноужно проверить контрольную строчку, и если они не соответствуют ей, то ничего делать не будем
     if ($params = \Yii::$app->request->get()) {
         $pramsCheckArray = explode(DIRECTORY_SEPARATOR, $filterSting);
         if (count($pramsCheckArray) < 3) {
             throw new \yii\base\Exception("the control line not found: " . $newFileSrc);
         }
         $string = $imaging->getParamsCheckString($params);
         if ($pramsCheckArray[1] != $string) {
             throw new \yii\base\Exception("Parameters invalid: " . $newFileSrc);
         }
     }
     $filterClass = str_replace("-", "\\", $filterCode);
     if (!class_exists($filterClass)) {
         throw new \ErrorException("Filter class is not created: " . $newFileSrc);
     }
     /**
      * @var Filter $filter
      */
     $filter = new $filterClass((array) $params);
     if (!is_subclass_of($filter, Filter::className())) {
         throw new \ErrorException("No child filter class: " . $newFileSrc);
     }
     try {
         //Проверяем а создан ли уже файл, и если да то просто делаем на него ссылку.
         $filter->setOriginalRootFilePath($originalFileRoot)->setNewRootFilePath($newFileRootDefault)->save();
         if (PHP_OS === 'Windows') {
             if ($newFileRoot != $newFileRootDefault) {
                 //Не тестировалось
                 copy($newFileRootDefault, $newFileRoot);
             }
         } else {
             if ($newFileRoot != $newFileRootDefault) {
                 symlink($newFileRootDefault, $newFileRoot);
             }
         }
         $url = \Yii::$app->request->getUrl() . ($params ? "" : '?sx-refresh');
         /*Header("HTTP/1.0 200 OK");
           Image::getImagine()->open($newFileRootDefault)->show('png');
           return '';*/
         return \Yii::$app->response->redirect($url, 302);
     } catch (\Exception $e) {
         return $e->getMessage();
     }
 }
Example #4
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;
 }
Example #5
0
 /**
  * @return File[]
  */
 public function findFiles()
 {
     $dir = $this->getPath();
     $files = array();
     if ($dir[strlen($dir) - 1] != '/') {
         $dir .= '/';
         //добавляем слеш в конец если его нет
     }
     $nDir = opendir($dir);
     while (false !== ($file = readdir($nDir))) {
         if (!is_file($dir . "/" . $file)) {
             continue;
         }
         if ($file != "." and $file != "..") {
             //если это не директория
             $files[] = File::object($dir . "/" . $file);
         }
     }
     closedir($nDir);
     return $files;
 }