function attachFile($source) { /** @var Model $this */ \DB::beginTransaction(); try { if ($source instanceof UploadedFile) { // $source = new UploadedFile(1, 1); $ext = $source->getClientOriginalExtension(); $file_name = mb_substr($source->getClientOriginalName(), 0, 0 - mb_strlen($ext) - 1); } else { $ext = \File::extension($source); $file_name = \File::name($source); } $ext = mb_strtolower($ext); $tmp = file_get_contents($source); $tmp_name = storage_path('/attaches/' . date('Y_m_d_H-i-s') . '/' . \Str::slug($this->getMorphClass()) . '.' . $ext); if (!file_exists(dirname($tmp_name))) { mkdir(dirname($tmp_name), 0777, true); } file_put_contents($tmp_name, $tmp); unset($tmp); if (!file_exists($tmp_name)) { throw new Exception(laralang('larakit::attach.errors.exists', ['file' => larasafepath($tmp_name)])); } $attach = Attach\Attach::fromModel($this); $config = $this->attachConfig(); //проверка на максимальный размер $maxsize = Arr::get($config, 'maxsize'); $size = \File::size($tmp_name); if ($maxsize < $size) { throw new Exception(laralang('larakit::attach.errors.maxsize', ['maxsize' => HelperText::fileSize($maxsize, 0)])); } //проверка на разрешенные EXT $enabled_exts = Arr::get($config, 'ext'); if (!in_array($ext, $enabled_exts)) { throw new Exception(laralang('larakit::attach.errors.ext', ['enabled_exts' => implode(', ', $enabled_exts)])); } //проверка на разрешенные MIME $expected_mimes = HelperFile::mimes_by_ext($ext); $mime = HelperFile::mime($tmp_name); if (!in_array($mime, $expected_mimes)) { throw new Exception(laralang('larakit::attach.errors.ext', ['enabled_exts' => implode(', ', $enabled_exts)])); } $img = getimagesize($tmp_name); if (false !== $img) { $this->attach_w = Arr::get($img, 0); $this->attach_h = Arr::get($img, 1); } $this->attach_user_id = Me::id(); $this->attach_ext = $ext; $this->attach_size = $size; $this->attach_mime = $mime; $this->attach_file = $file_name . '.' . $ext; $this->attach_name = $file_name; $this->save(); $attach->setId($this->id)->processing($tmp_name); \DB::commit(); $val = true; } catch (\Exception $e) { \DB::rollBack(); $val = $e->getMessage(); } if (file_exists($tmp_name)) { if (false !== mb_strpos($source, '//')) { unlink($tmp_name); } } return $val; }
function only_admin() { return !\Larakit\User\Me::is_admin() ? 'Действие доступно только администратору' : false; }