Local.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace crmeb\services\upload\storage;
  12. use crmeb\services\upload\BaseUpload;
  13. use crmeb\exceptions\AdminException;
  14. use crmeb\utils\DownloadImage;
  15. use think\exception\ValidateException;
  16. use think\facade\Config;
  17. use think\facade\Filesystem;
  18. use think\File;
  19. use think\Image;
  20. /**
  21. * 本地上传
  22. * Class Local
  23. * @package crmeb\services\upload\storage
  24. */
  25. class Local extends BaseUpload
  26. {
  27. /**
  28. * 默认存放路径
  29. * @var string
  30. */
  31. protected $defaultPath;
  32. /**
  33. * 缩略图、水印图存放位置
  34. * @var string
  35. */
  36. public $thumbWaterPath = 'thumb_water';
  37. public function initialize(array $config)
  38. {
  39. parent::initialize($config);
  40. $this->defaultPath = Config::get('filesystem.disks.' . Config::get('filesystem.default') . '.url');
  41. $this->waterConfig['watermark_text_font'] = app()->getRootPath() . 'public' . '/statics/font/simsunb.ttf';
  42. }
  43. protected function app()
  44. {
  45. // TODO: Implement app() method.
  46. }
  47. public function getTempKeys()
  48. {
  49. // TODO: Implement getTempKeys() method.
  50. return $this->setError('请检查您的上传配置,视频默认oss上传');
  51. }
  52. /**
  53. * 生成上传文件目录
  54. * @param $path
  55. * @param null $root
  56. * @return string
  57. */
  58. public function uploadDir($path, $root = null)
  59. {
  60. if ($root === null) $root = app()->getRootPath() . 'public/';
  61. return str_replace('\\', '/', $root . 'uploads/' . $path);
  62. }
  63. /**
  64. * 检查上传目录不存在则生成
  65. * @param $dir
  66. * @return bool
  67. */
  68. protected function validDir($dir)
  69. {
  70. return is_dir($dir) == true || mkdir($dir, 0777, true) == true;
  71. }
  72. /**
  73. * 检测filepath是否是远程地址
  74. * @param string $filePath
  75. * @return bool
  76. */
  77. public function checkFilePathIsRemote(string $filePath)
  78. {
  79. return strpos($filePath, 'https:') !== false || strpos($filePath, 'http:') !== false || substr($filePath, 0, 2) === '//';
  80. }
  81. /**
  82. * 生成与配置相关的文件名称以及路径
  83. * @param string $filePath 原地址
  84. * @param string $toPath 保存目录
  85. * @param array $config 配置相关参数
  86. * @param string $root
  87. * @return string
  88. */
  89. public function createSaveFilePath(string $filePath, string $toPath, array $config = [], $root = '/')
  90. {
  91. [$path, $ext] = $this->getFileName($filePath);
  92. $fileName = md5(json_encode($config) . $filePath);
  93. return $this->uploadDir($toPath, $root) . '/' . $fileName . '.' . $ext;
  94. }
  95. /**
  96. * 文件上传
  97. * @param string $file
  98. * @return array|bool|mixed|\StdClass
  99. */
  100. public function move(string $file = 'file', $realName = false)
  101. {
  102. $fileHandle = app()->request->file($file);
  103. if (!$fileHandle) {
  104. return $this->setError('上传的文件不存在');
  105. }
  106. if ($this->validate) {
  107. if (!in_array(strtolower(pathinfo($fileHandle->getOriginalName(), PATHINFO_EXTENSION)), $this->validate['fileExt'])) {
  108. return $this->setError('不合法的文件后缀');
  109. }
  110. if (filesize($fileHandle) > $this->validate['filesize']) {
  111. return $this->setError('文件过大');
  112. }
  113. if (!in_array($fileHandle->getOriginalMime(), $this->validate['fileMime'])) {
  114. return $this->setError('不合法的文件类型');
  115. }
  116. $stream = fopen($fileHandle->getPathname(), 'r');
  117. $content = (fread($stream, filesize($fileHandle->getPathname())));
  118. if (is_resource($stream)) {
  119. fclose($stream);
  120. }
  121. if (preg_match('/think|php|log|phar|Socket|Channel|Flysystem|Psr6Cache|Cached|Request|debug|Psr6Cachepool|eval/i', $content)) {
  122. return $this->setError('文件内容不合法');
  123. }
  124. }
  125. if ($realName) {
  126. $fileName = Filesystem::putFileAs($this->path, $fileHandle, $fileHandle->getOriginalName());
  127. } else {
  128. $fileName = Filesystem::putFile($this->path, $fileHandle);
  129. }
  130. if (!$fileName)
  131. return $this->setError('Upload failure');
  132. $filePath = Filesystem::path($fileName);
  133. $this->fileInfo->uploadInfo = new File($filePath);
  134. $this->fileInfo->realName = $fileHandle->getOriginalName();
  135. $this->fileInfo->fileName = $this->fileInfo->uploadInfo->getFilename();
  136. $this->fileInfo->filePath = $this->defaultPath . '/' . str_replace('\\', '/', $fileName);
  137. if ($this->checkImage(public_path() . $this->fileInfo->filePath) && $this->authThumb && pathinfo($fileName, PATHINFO_EXTENSION) != 'ico' && pathinfo($fileName, PATHINFO_EXTENSION) != 'gif') {
  138. try {
  139. $this->thumb($this->fileInfo->filePath, $this->fileInfo->fileName);
  140. } catch (\Throwable $e) {
  141. return $this->setError($e->getMessage());
  142. }
  143. }
  144. return $this->fileInfo;
  145. }
  146. /**
  147. * 文件流上传
  148. * @param $fileContent
  149. * @param string|null $key
  150. * @return array|bool|mixed|\StdClass
  151. */
  152. public function stream($fileContent, string $key = null)
  153. {
  154. if (!$key) {
  155. $key = $this->saveFileName();
  156. }
  157. $dir = $this->uploadDir($this->path);
  158. if (!$this->validDir($dir)) {
  159. return $this->setError('Failed to generate upload directory, please check the permission!');
  160. }
  161. $fileName = $dir . '/' . $key;
  162. file_put_contents($fileName, $fileContent);
  163. $this->fileInfo->uploadInfo = new File($fileName);
  164. $this->fileInfo->realName = $key;
  165. $this->fileInfo->fileName = $key;
  166. $this->fileInfo->filePath = $this->defaultPath . '/' . $this->path . '/' . $key;
  167. if ($this->checkImage(public_path() . $this->fileInfo->filePath) && $this->authThumb) {
  168. try {
  169. $this->thumb($this->fileInfo->filePath, $this->fileInfo->fileName);
  170. } catch (\Throwable $e) {
  171. return $this->setError($e->getMessage());
  172. }
  173. }
  174. return $this->fileInfo;
  175. }
  176. /**
  177. * 文件流下载保存图片
  178. * @param string $fileContent
  179. * @param string|null $key
  180. * @return array|bool|mixed|\StdClass
  181. */
  182. public function down(string $fileContent, string $key = null)
  183. {
  184. if (!$key) {
  185. $key = $this->saveFileName();
  186. }
  187. $dir = $this->uploadDir($this->path);
  188. if (!$this->validDir($dir)) {
  189. return $this->setError('Failed to generate upload directory, please check the permission!');
  190. }
  191. $fileName = $dir . '/' . $key;
  192. file_put_contents($fileName, $fileContent);
  193. $this->downFileInfo->downloadInfo = new File($fileName);
  194. $this->downFileInfo->downloadRealName = $key;
  195. $this->downFileInfo->downloadFileName = $key;
  196. $this->downFileInfo->downloadFilePath = $this->defaultPath . '/' . $this->path . '/' . $key;
  197. return $this->downFileInfo;
  198. }
  199. /**
  200. * 生成缩略图
  201. * @param string $filePath
  202. * @param string $fileName
  203. * @param string $type
  204. * @return array|mixed|string[]
  205. */
  206. public function thumb(string $filePath = '', string $fileName = '', string $type = 'all')
  207. {
  208. $config = $this->thumbConfig;
  209. $data = ['big' => $filePath, 'mid' => $filePath, 'small' => $filePath];
  210. $this->fileInfo->filePathBig = $this->fileInfo->filePathMid = $this->fileInfo->filePathSmall = $this->fileInfo->filePathWater = $filePath;
  211. //地址存在且不是远程地址
  212. $filePath = str_replace(sys_config('site_url'), '', $filePath);
  213. if ($filePath && !$this->checkFilePathIsRemote($filePath)) {
  214. $findPath = str_replace($fileName, $type . '_' . $fileName, $filePath);
  215. if (file_exists('.' . $findPath)) {
  216. return [
  217. 'big' => str_replace($fileName, 'big_' . $fileName, $filePath),
  218. 'mid' => str_replace($fileName, 'mid_' . $fileName, $filePath),
  219. 'small' => str_replace($fileName, 'small_' . $fileName, $filePath)
  220. ];
  221. }
  222. try {
  223. $this->water($filePath);
  224. foreach ($this->thumb as $v) {
  225. if ($type == 'all' || $type == $v) {
  226. $height = 'thumb_' . $v . '_height';
  227. $width = 'thumb_' . $v . '_width';
  228. $savePath = str_replace($fileName, $v . '_' . $fileName, $filePath);
  229. //防止重复生成
  230. if (!file_exists('.' . $savePath)) {
  231. $Image = Image::open(app()->getRootPath() . 'public' . $filePath);
  232. $Image->thumb($config[$width], $config[$height])->save(root_path() . 'public' . $savePath);
  233. }
  234. $key = 'filePath' . ucfirst($v);
  235. $data[$v] = $this->fileInfo->$key = $savePath;
  236. }
  237. }
  238. } catch (\Throwable $e) {
  239. throw new AdminException($e->getMessage());
  240. }
  241. }
  242. return $data;
  243. }
  244. /**
  245. * 添加水印
  246. * @param string $filePath
  247. * @return mixed|string
  248. */
  249. public function water(string $filePath = '')
  250. {
  251. $waterConfig = $this->waterConfig;
  252. if ($waterConfig['image_watermark_status'] && $filePath) {
  253. switch ($waterConfig['watermark_type']) {
  254. case 1:
  255. if ($waterConfig['watermark_image']) $filePath = $this->image($filePath, $waterConfig);
  256. break;
  257. case 2:
  258. $filePath = $this->text($filePath, $waterConfig);
  259. break;
  260. }
  261. }
  262. return $filePath;
  263. }
  264. /**
  265. * 图片水印
  266. * @param string $filePath
  267. * @param array $waterConfig
  268. * @param string $waterPath
  269. * @return string
  270. */
  271. public function image(string $filePath, array $waterConfig = [])
  272. {
  273. if (!$waterConfig) {
  274. $waterConfig = $this->waterConfig;
  275. }
  276. $watermark_image = $waterConfig['watermark_image'];
  277. //远程图片
  278. $filePath = str_replace(sys_config('site_url'), '', $filePath);
  279. if ($watermark_image && $this->checkFilePathIsRemote($watermark_image)) {
  280. //看是否在本地
  281. $pathName = $this->getFilePath($watermark_image, true);
  282. if ($pathName == $watermark_image) {//不再本地 继续下载
  283. [$p, $e] = $this->getFileName($watermark_image);
  284. $name = 'water_image_' . md5($watermark_image) . '.' . $e;
  285. $watermark_image = '.' . $this->defaultPath . '/' . $this->thumbWaterPath . '/' . $name;
  286. if (!file_exists($watermark_image)) {
  287. try {
  288. /** @var DownloadImage $down */
  289. $down = app()->make(DownloadImage::class);
  290. $data = $down->path($this->thumbWaterPath)->downloadImage($waterConfig['watermark_image'], $name);
  291. $watermark_image = $data['path'] ?? '';
  292. } catch (\Throwable $e) {
  293. throw new AdminException(400724);
  294. }
  295. }
  296. } else {
  297. $watermark_image = '.' . $pathName;
  298. }
  299. }
  300. if (!$watermark_image) {
  301. throw new AdminException(400722);
  302. }
  303. $savePath = public_path() . $filePath;
  304. try {
  305. $Image = Image::open(app()->getRootPath() . 'public' . $filePath);
  306. $Image->water($watermark_image, $waterConfig['watermark_position'] ?: 1, (int)$waterConfig['watermark_opacity'])->save($savePath);
  307. } catch (\Throwable $e) {
  308. throw new AdminException($e->getMessage());
  309. }
  310. return $savePath;
  311. }
  312. /**
  313. * 文字水印
  314. * @param string $filePath
  315. * @param array $waterConfig
  316. * @return string
  317. */
  318. public function text(string $filePath, array $waterConfig = [])
  319. {
  320. if (!$waterConfig) {
  321. $waterConfig = $this->waterConfig;
  322. }
  323. if (!$waterConfig['watermark_text']) {
  324. throw new AdminException(400723);
  325. }
  326. $savePath = public_path() . $filePath;
  327. try {
  328. $Image = Image::open(app()->getRootPath() . 'public' . $filePath);
  329. if (strlen($waterConfig['watermark_text_color']) < 7) {
  330. $waterConfig['watermark_text_color'] = substr($waterConfig['watermark_text_color'], 1);
  331. $waterConfig['watermark_text_color'] = '#' . $waterConfig['watermark_text_color'] . $waterConfig['watermark_text_color'];
  332. }
  333. if (strlen($waterConfig['watermark_text_color']) > 7) {
  334. $waterConfig['watermark_text_color'] = substr($waterConfig['watermark_text_color'], 0, 7);
  335. }
  336. $Image->text($waterConfig['watermark_text'], $waterConfig['watermark_text_font'], (float)$waterConfig['watermark_text_size'], $waterConfig['watermark_text_color'], $waterConfig['watermark_position'], [$waterConfig['watermark_x'], $waterConfig['watermark_y'], $waterConfig['watermark_text_angle']])->save($savePath);
  337. } catch (\Throwable $e) {
  338. throw new AdminException($e->getMessage() . $e->getLine());
  339. }
  340. return $savePath;
  341. }
  342. /**
  343. * 删除文件
  344. * @param string $filePath
  345. * @return bool|mixed
  346. */
  347. public function delete(string $filePath)
  348. {
  349. if (file_exists($filePath)) {
  350. try {
  351. $fileArr = explode('/', $filePath);
  352. $fileName = end($fileArr);
  353. unlink($filePath);
  354. unlink(str_replace($fileName, 'big_' . $fileName, $filePath));
  355. unlink(str_replace($fileName, 'mid_' . $fileName, $filePath));
  356. unlink(str_replace($fileName, 'small_' . $fileName, $filePath));
  357. return true;
  358. } catch (\Exception $e) {
  359. return $this->setError($e->getMessage());
  360. }
  361. }
  362. return false;
  363. }
  364. public function listbuckets(string $region, bool $line = false, bool $shared = false)
  365. {
  366. return [];
  367. }
  368. public function createBucket(string $name, string $region)
  369. {
  370. return null;
  371. }
  372. public function deleteBucket(string $name)
  373. {
  374. return null;
  375. }
  376. public function setBucketCors(string $name, string $region)
  377. {
  378. return true;
  379. }
  380. public function getRegion()
  381. {
  382. return [];
  383. }
  384. public function bindDomian(string $name, string $domain, string $region = null)
  385. {
  386. return true;
  387. }
  388. public function getDomian(string $name, string $region = null)
  389. {
  390. return [];
  391. }
  392. }