Local.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 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\basic\BaseUpload;
  13. use crmeb\exceptions\UploadException;
  14. use crmeb\services\DownloadImageService;
  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. //
  46. }
  47. public function getTempKeys()
  48. {
  49. //
  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')
  101. {
  102. $fileHandle = app()->request->file($file);
  103. if (!$fileHandle) {
  104. return $this->setError('Upload file does not exist');
  105. }
  106. if ($this->validate) {
  107. try {
  108. $error = [
  109. $file . '.filesize' => 'Upload filesize error',
  110. $file . '.fileExt' => 'Upload fileExt error',
  111. $file . '.fileMime' => 'Upload fileMine error'
  112. ];
  113. validate([$file => $this->validate], $error)->check([$file => $fileHandle]);
  114. } catch (ValidateException $e) {
  115. return $this->setError($e->getMessage());
  116. }
  117. }
  118. $fileName = Filesystem::putFileAs($this->path, $fileHandle, strtolower($fileHandle->hashName()));
  119. if (!$fileName)
  120. return $this->setError('Upload failure');
  121. $filePath = Filesystem::path($fileName);
  122. $this->fileInfo->uploadInfo = new File($filePath);
  123. $this->fileInfo->realName = $fileHandle->getOriginalName();
  124. $this->fileInfo->fileName = $this->fileInfo->uploadInfo->getFilename();
  125. $this->fileInfo->filePath = $this->defaultPath . '/' . str_replace('\\', '/', $fileName);
  126. if ($this->checkImage(root_path() . 'public' . $this->fileInfo->filePath) && $this->authThumb) {
  127. try {
  128. $this->thumb($this->fileInfo->filePath);
  129. } catch (\Throwable $e) {
  130. return $this->setError($e->getMessage());
  131. }
  132. }
  133. return $this->fileInfo;
  134. }
  135. /**
  136. * 文件流上传
  137. * @param string $fileContent
  138. * @param string|null $key
  139. * @return array|bool|mixed|\StdClass
  140. */
  141. public function stream(string $fileContent, string $key = null)
  142. {
  143. if (!$key) {
  144. $key = $this->saveFileName();
  145. }
  146. $dir = $this->uploadDir($this->path);
  147. if (!$this->validDir($dir)) {
  148. return $this->setError('Failed to generate upload directory, please check the permission!');
  149. }
  150. $fileName = $dir . '/' . $key;
  151. file_put_contents($fileName, $fileContent);
  152. $this->fileInfo->uploadInfo = new File($fileName);
  153. $this->fileInfo->realName = $key;
  154. $this->fileInfo->fileName = $key;
  155. $this->fileInfo->filePath = $this->defaultPath . '/' . $this->path . '/' . $key;
  156. if ($this->checkImage(root_path() . 'public' . $this->fileInfo->filePath) && $this->authThumb) {
  157. try {
  158. $this->thumb($this->fileInfo->filePath);
  159. } catch (\Throwable $e) {
  160. return $this->setError($e->getMessage());
  161. }
  162. }
  163. return $this->fileInfo;
  164. }
  165. /**
  166. * 文件流下载保存图片
  167. * @param string $fileContent
  168. * @param string|null $key
  169. * @return array|bool|mixed|\StdClass
  170. */
  171. public function down(string $fileContent, string $key = null)
  172. {
  173. if (!$key) {
  174. $key = $this->saveFileName();
  175. }
  176. $dir = $this->uploadDir($this->path);
  177. if (!$this->validDir($dir)) {
  178. return $this->setError('Failed to generate upload directory, please check the permission!');
  179. }
  180. $fileName = $dir . '/' . $key;
  181. file_put_contents($fileName, $fileContent);
  182. $this->downFileInfo->downloadInfo = new File($fileName);
  183. $this->downFileInfo->downloadRealName = $key;
  184. $this->downFileInfo->downloadFileName = $key;
  185. $this->downFileInfo->downloadFilePath = $this->defaultPath . '/' . $this->path . '/' . $key;
  186. return $this->downFileInfo;
  187. }
  188. /**
  189. * 生成缩略图
  190. * @param string $filePath
  191. * @param string $type
  192. * @return array|mixed|string[]
  193. */
  194. public function thumb(string $filePath = '', string $type = 'all')
  195. {
  196. $filePath = $this->getFilePath($filePath, true);
  197. $data = ['big' => $filePath, 'mid' => $filePath, 'small' => $filePath];
  198. $this->fileInfo->filePathBig = $this->fileInfo->filePathMid = $this->fileInfo->filePathSmall = $this->fileInfo->filePathWater = $filePath;
  199. //地址存在且不是远程地址
  200. if ($filePath && !$this->checkFilePathIsRemote($filePath) && strpos($filePath, 'uploads/' . $this->thumbWaterPath) === false) {
  201. $dir = $this->uploadDir($this->thumbWaterPath);
  202. if (!$this->validDir($dir)) {
  203. throw new ValidateException('缩略图生成目录生成失败,目录:' . $dir);
  204. }
  205. $filePath = $this->water($filePath);
  206. $this->fileInfo->filePathWater = $filePath;
  207. $config = $this->thumbConfig;
  208. try {
  209. foreach ($this->thumb as $v) {
  210. if ($type == 'all' || $type == $v) {
  211. $height = 'thumb_' . $v . '_height';
  212. $width = 'thumb_' . $v . '_width';
  213. if (isset($config[$height]) && isset($config[$width]) && $config[$height] && $config[$width]) {
  214. $savePath = $this->createSaveFilePath($filePath, $this->thumbWaterPath, [$height => $config[$height], $width => $config[$width]]);
  215. //防止重复生成
  216. if (!file_exists(root_path() . 'public' . $savePath)) {
  217. if ($this->authThumb) {//生成
  218. $Image = Image::open(app()->getRootPath() . 'public' . $filePath);
  219. $Image->thumb($config[$width], $config[$height])->save(root_path() . 'public' . $savePath);
  220. } else {
  221. $savePath = $filePath;
  222. }
  223. }
  224. $key = 'filePath' . ucfirst($v);
  225. $data[$v] = $this->fileInfo->$key = $savePath;
  226. }
  227. }
  228. }
  229. } catch (\Throwable $e) {
  230. throw new ValidateException($e->getMessage());
  231. }
  232. }
  233. return $data;
  234. }
  235. /**
  236. * 添加水印
  237. * @param string $filePath
  238. * @return mixed|string
  239. */
  240. public function water(string $filePath = '')
  241. {
  242. $waterPath = $filePath = $this->getFilePath($filePath);
  243. //地址存在且不是远程地址
  244. if ($filePath && !$this->checkFilePathIsRemote($filePath)) {
  245. $waterConfig = $this->waterConfig;
  246. if ($waterConfig['image_watermark_status'] && $filePath) {
  247. $waterPath = $this->createSaveFilePath($filePath, $this->thumbWaterPath, $waterConfig);
  248. switch ($waterConfig['watermark_type']) {
  249. case 1:
  250. if ($waterConfig['watermark_image']) $waterPath = $this->image($filePath, $waterConfig, $waterPath);
  251. break;
  252. case 2:
  253. $waterPath = $this->text($filePath, $waterConfig, $waterPath);
  254. break;
  255. }
  256. }
  257. }
  258. return $waterPath;
  259. }
  260. /**
  261. * 图片水印
  262. * @param string $filePath
  263. * @param array $waterConfig
  264. * @param string $waterPath
  265. * @return string
  266. */
  267. public function image(string $filePath, array $waterConfig = [], string $waterPath = '')
  268. {
  269. if (!$waterConfig) {
  270. $waterConfig = $this->waterConfig;
  271. }
  272. $watermark_image = $waterConfig['watermark_image'];
  273. //远程图片
  274. if ($watermark_image && $this->checkFilePathIsRemote($watermark_image)) {
  275. //看是否在本地
  276. if (!$this->isLocal($watermark_image)) {//不再本地 继续下载
  277. [$p, $e] = $this->getFileName($watermark_image);
  278. $name = 'water_image_' . md5($watermark_image) . '.' . $e;
  279. $watermark_image = $this->defaultPath . '/' . $this->thumbWaterPath . '/' . $name;
  280. if (!file_exists(root_path() . 'public' . $watermark_image)) {
  281. try {
  282. /** @var DownloadImageService $down */
  283. $down = app()->make(DownloadImageService::class);
  284. $data = $down->path($this->thumbWaterPath)->downloadImage($waterConfig['watermark_image'], $name);
  285. $watermark_image = $data['path'] ?? '';
  286. } catch (\Throwable $e) {
  287. throw new ValidateException('远程水印图片下载失败,原因:' . $e->getMessage());
  288. }
  289. }
  290. } else {
  291. $watermark_image = $this->getFilePath($watermark_image, true);
  292. }
  293. }
  294. if (!$watermark_image) {
  295. throw new ValidateException('请先配置水印图片');
  296. }
  297. if (!$waterPath) {
  298. [$path, $ext] = $this->getFileName($filePath);
  299. $waterPath = $path . '_water_image.' . $ext;
  300. }
  301. try {
  302. if (!file_exists(root_path() . 'public' . $waterPath)) {
  303. if ($this->authThumb) {//生成
  304. $Image = Image::open(app()->getRootPath() . 'public' . $filePath);
  305. $Image->water(app()->getRootPath() . 'public' . $watermark_image, $waterConfig['watermark_position'] ?: 1, $waterConfig['watermark_opacity'])->save(root_path() . 'public' . $waterPath);
  306. } else {
  307. $waterPath = $filePath;
  308. }
  309. }
  310. } catch (\Throwable $e) {
  311. throw new ValidateException($e->getMessage());
  312. }
  313. return $waterPath;
  314. }
  315. /**
  316. * 文字水印
  317. * @param string $filePath
  318. * @param array $waterConfig
  319. * @param string $waterPath
  320. * @return string
  321. */
  322. public function text(string $filePath, array $waterConfig = [], string $waterPath = '')
  323. {
  324. if (!$waterConfig) {
  325. $waterConfig = $this->waterConfig;
  326. }
  327. if (!$waterConfig['watermark_text']) {
  328. throw new ValidateException('请先配置水印文字');
  329. }
  330. if (!$waterPath) {
  331. [$path, $ext] = $this->getFileName($filePath);
  332. $waterPath = $path . '_water_text.' . $ext;
  333. }
  334. try {
  335. if (!file_exists(root_path() . 'public' . $waterPath)) {
  336. if ($this->authThumb) {//生成
  337. $Image = Image::open(app()->getRootPath() . 'public' . $filePath);
  338. if (strlen($waterConfig['watermark_text_color']) < 7) {
  339. $waterConfig['watermark_text_color'] = substr($waterConfig['watermark_text_color'], 1);
  340. $waterConfig['watermark_text_color'] = '#' . $waterConfig['watermark_text_color'] . $waterConfig['watermark_text_color'];
  341. }
  342. if (strlen($waterConfig['watermark_text_color']) > 7) {
  343. $waterConfig['watermark_text_color'] = substr($waterConfig['watermark_text_color'], 0, 7);
  344. }
  345. $Image->text($waterConfig['watermark_text'], $waterConfig['watermark_text_font'], $waterConfig['watermark_text_size'], $waterConfig['watermark_text_color'], $waterConfig['watermark_position'], [$waterConfig['watermark_x'], $waterConfig['watermark_y'], $waterConfig['watermark_text_angle']])->save(root_path() . 'public' . $waterPath);
  346. } else {
  347. $waterPath = $filePath;
  348. }
  349. }
  350. } catch (\Throwable $e) {
  351. throw new ValidateException($e->getMessage() . $e->getLine());
  352. }
  353. return $waterPath;
  354. }
  355. /**
  356. * 删除文件
  357. * @param string $filePath
  358. * @return bool|mixed
  359. */
  360. public function delete(string $filePath)
  361. {
  362. if (file_exists($filePath)) {
  363. try {
  364. unlink($filePath);
  365. $waterConfig = $this->waterConfig;
  366. //水印图片
  367. $waterPath = $this->createSaveFilePath($filePath, $this->thumbWaterPath, $waterConfig, null);
  368. if (file_exists($waterPath)) unlink($waterPath);
  369. $config = $this->thumbConfig;
  370. //缩略图
  371. foreach ($this->thumb as $v) {
  372. $height = 'thumb_' . $v . '_height';
  373. $width = 'thumb_' . $v . '_width';
  374. if (isset($config[$height]) && isset($config[$width]) && $config[$height] && $config[$width]) {
  375. $thumbPath = $this->createSaveFilePath($waterPath, $this->thumbWaterPath, [$height => $config[$height], $width => $config[$width]], null);
  376. if (file_exists($thumbPath)) unlink($thumbPath);
  377. }
  378. }
  379. return true;
  380. } catch (UploadException $e) {
  381. return $this->setError($e->getMessage());
  382. }
  383. }
  384. return false;
  385. }
  386. public function listbuckets(string $region, bool $line = false, bool $shared = false)
  387. {
  388. return [];
  389. }
  390. public function createBucket(string $name, string $region)
  391. {
  392. return null;
  393. }
  394. public function deleteBucket(string $name)
  395. {
  396. return null;
  397. }
  398. public function setBucketCors(string $name, string $region)
  399. {
  400. return true;
  401. }
  402. public function getRegion()
  403. {
  404. return [];
  405. }
  406. public function bindDomian(string $name, string $domain, string $region = null)
  407. {
  408. return true;
  409. }
  410. public function getDomian(string $name, string $region = null)
  411. {
  412. return [];
  413. }
  414. }