Attachment.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | 海豚PHP框架 [ DolphinPHP ]
  4. // +----------------------------------------------------------------------
  5. // | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
  6. // +----------------------------------------------------------------------
  7. // | 官方网站: http://dolphinphp.com
  8. // +----------------------------------------------------------------------
  9. namespace app\admin\controller;
  10. use app\admin\model\Attachment as AttachmentModel;
  11. use app\common\builder\ZBuilder;
  12. use think\Db;
  13. use think\facade\Env;
  14. use think\facade\Hook;
  15. use think\File;
  16. use think\Image;
  17. /**
  18. * 附件控制器
  19. * @package app\admin\controller
  20. */
  21. class Attachment extends Admin {
  22. /**
  23. * 附件列表
  24. * @author 蔡伟明 <314013107@qq.com>
  25. */
  26. public function index() {
  27. // 查询
  28. $map = $this->getMap();
  29. // 数据列表
  30. $data_list = AttachmentModel::where($map)->order('sort asc,id desc')->paginate();
  31. foreach ($data_list as $key => &$value) {
  32. if (in_array(strtolower($value['ext']), ['jpg', 'jpeg', 'png', 'gif', 'bmp'])) {
  33. if ($value['driver'] == 'local') {
  34. $thumb = $value['thumb'] != '' ? $value['thumb'] : $value['path'];
  35. $value['type'] = '<div class="js-gallery"><img class="image" title="点击查看大图" data-original="' . PUBLIC_PATH . $value['path'] . '" src="' . PUBLIC_PATH . $thumb . '"></div>';
  36. } else {
  37. $value['type'] = '<div class="js-gallery"><img class="image" title="点击查看大图" data-original="' . $value['path'] . '" src="' . $value['path'] . '"></div>';
  38. }
  39. } else {
  40. if ($value['driver'] == 'local') {
  41. $path = PUBLIC_PATH . $value['path'];
  42. } else {
  43. $path = $value['path'];
  44. }
  45. if (is_file('.' . config('public_static_path') . 'admin/img/files/' . $value['ext'] . '.png')) {
  46. $value['type'] = '<a href="' . $path . '"
  47. data-toggle="tooltip" title="点击下载">
  48. <img class="image" src="' . config('public_static_path') . 'admin/img/files/' . $value['ext'] . '.png"></a>';
  49. } else {
  50. $value['type'] = '<a href="' . $path . '"
  51. data-toggle="tooltip" title="点击下载">
  52. <img class="image" src="' . config('public_static_path') . 'admin/img/files/file.png"></a>';
  53. }
  54. }
  55. }
  56. // 使用ZBuilder快速创建数据表格
  57. return ZBuilder::make('table')
  58. ->setSearch(['name' => '名称']) // 设置搜索框
  59. ->addColumns([ // 批量添加数据列
  60. ['id', 'ID'],
  61. ['type', '类型'],
  62. ['name', '名称'],
  63. ['size', '大小', 'byte'],
  64. ['driver', '上传驱动', parse_attr(Db::name('admin_config')->where('name', 'upload_driver')->value('options'))],
  65. ['create_time', '上传时间', 'datetime'],
  66. ['status', '状态', 'switch'],
  67. ['right_button', '操作', 'btn'],
  68. ])
  69. ->addTopButtons('enable,disable,delete') // 批量添加顶部按钮
  70. ->addRightButtons('delete') // 批量添加右侧按钮
  71. ->setRowList($data_list) // 设置表格数据
  72. ->fetch(); // 渲染模板
  73. }
  74. /**
  75. * 上传附件
  76. * @param string $dir 保存的目录:images,files,videos,voices
  77. * @param string $from 来源,wangeditor:wangEditor编辑器, ueditor:ueditor编辑器, editormd:editormd编辑器等
  78. * @param string $module 来自哪个模块
  79. * @author 蔡伟明 <314013107@qq.com>
  80. * @return mixed
  81. */
  82. public function upload($dir = '', $from = '', $module = '') {
  83. // 临时取消执行时间限制
  84. set_time_limit(0);
  85. if ($dir == '') {
  86. $this->error('没有指定上传目录');
  87. }
  88. if ($from == 'ueditor') {
  89. return $this->ueditor($module);
  90. }
  91. if ($from == 'jcrop') {
  92. return $this->jcrop();
  93. }
  94. return $this->saveFile($dir, $from, $module);
  95. }
  96. /**
  97. * 保存附件
  98. * @param string $dir 附件存放的目录
  99. * @param string $from 来源
  100. * @param string $module 来自哪个模块
  101. * @author 蔡伟明 <314013107@qq.com>
  102. * @return string|\think\response\Json
  103. */
  104. private function saveFile($dir = '', $from = '', $module = '') {
  105. // 附件大小限制
  106. $size_limit = $dir == 'images' ? config('upload_image_size') : config('upload_file_size');
  107. $size_limit = $size_limit * 1024;
  108. // 附件类型限制
  109. $ext_limit = $dir == 'images' ? config('upload_image_ext') : config('upload_file_ext');
  110. $ext_limit = $ext_limit != '' ? parse_attr($ext_limit) : '';
  111. // 缩略图参数
  112. $thumb = $this->request->post('thumb', '');
  113. // 水印参数
  114. $watermark = $this->request->post('watermark', '');
  115. // 获取附件数据
  116. $callback = '';
  117. switch ($from) {
  118. case 'editormd':
  119. $file_input_name = 'editormd-image-file';
  120. break;
  121. case 'ckeditor':
  122. $file_input_name = 'upload';
  123. $callback = $this->request->get('CKEditorFuncNum');
  124. break;
  125. case 'ueditor_scrawl':
  126. return $this->saveScrawl();
  127. break;
  128. default:
  129. $file_input_name = 'file';
  130. }
  131. $file = $this->request->file($file_input_name);
  132. // 判断附件是否已存在
  133. if ($file_exists = AttachmentModel::get(['md5' => $file->hash('md5')])) {
  134. if ($file_exists['driver'] == 'local') {
  135. $file_path = PUBLIC_PATH . $file_exists['path'];
  136. } else {
  137. $file_path = $file_exists['path'];
  138. }
  139. // 附件已存在
  140. return $this->uploadSuccess($from, $file_path, $file_exists['name'], $file_exists['id'], $callback);
  141. }
  142. // 判断附件大小是否超过限制
  143. if ($size_limit > 0 && ($file->getInfo('size') > $size_limit)) {
  144. return $this->uploadError($from, '附件过大', $callback);
  145. }
  146. // 判断附件格式是否符合
  147. $file_name = $file->getInfo('name');
  148. $file_ext = strtolower(substr($file_name, strrpos($file_name, '.') + 1));
  149. $error_msg = '';
  150. if ($ext_limit == '') {
  151. $error_msg = '获取文件信息失败!';
  152. }
  153. if ($file->getMime() == 'text/x-php' || $file->getMime() == 'text/html') {
  154. $error_msg = '禁止上传非法文件!';
  155. }
  156. if (preg_grep("/php/i", $ext_limit)) {
  157. $error_msg = '禁止上传非法文件!';
  158. }
  159. if (!preg_grep("/$file_ext/i", $ext_limit)) {
  160. $error_msg = '附件类型不正确!';
  161. }
  162. if ($error_msg != '') {
  163. // 上传错误
  164. return $this->uploadError($from, $error_msg, $callback);
  165. }
  166. // 附件上传钩子,用于第三方文件上传扩展
  167. if (config('upload_driver') != 'local') {
  168. $hook_result = Hook::listen('upload_attachment', ['file' => $file, 'from' => $from, 'module' => $module], true);
  169. if (false !== $hook_result) {
  170. return $hook_result;
  171. }
  172. }
  173. // 移动到框架应用根目录/uploads/ 目录下
  174. $info = $file->move(config('upload_path') . DIRECTORY_SEPARATOR . $dir);
  175. if ($info) {
  176. // 缩略图路径
  177. $thumb_path_name = '';
  178. // 图片宽度
  179. $img_width = '';
  180. // 图片高度
  181. $img_height = '';
  182. if ($dir == 'images') {
  183. $img = Image::open($info);
  184. $img_width = $img->width();
  185. $img_height = $img->height();
  186. // 水印功能
  187. if ($watermark == '') {
  188. if (config('upload_thumb_water') == 1 && config('upload_thumb_water_pic') > 0) {
  189. $this->create_water($info->getRealPath(), config('upload_thumb_water_pic'));
  190. }
  191. } else {
  192. if (strtolower($watermark) != 'close') {
  193. list($watermark_img, $watermark_pos, $watermark_alpha) = explode('|', $watermark);
  194. $this->create_water($info->getRealPath(), $watermark_img, $watermark_pos, $watermark_alpha);
  195. }
  196. }
  197. // 生成缩略图
  198. if ($thumb == '') {
  199. if (config('upload_image_thumb') != '') {
  200. $thumb_path_name = $this->create_thumb($info, $info->getPathInfo()->getfileName(), $info->getFilename());
  201. }
  202. } else {
  203. if (strtolower($thumb) != 'close') {
  204. list($thumb_size, $thumb_type) = explode('|', $thumb);
  205. $thumb_path_name = $this->create_thumb($info, $info->getPathInfo()->getfileName(), $info->getFilename(), $thumb_size, $thumb_type);
  206. }
  207. }
  208. }
  209. // 获取附件信息
  210. $file_info = [
  211. 'uid' => session('user_auth.uid'),
  212. 'name' => $file->getInfo('name'),
  213. 'mime' => $file->getInfo('type'),
  214. 'path' => 'uploads/' . $dir . '/' . str_replace('\\', '/', $info->getSaveName()),
  215. 'ext' => $info->getExtension(),
  216. 'size' => $info->getSize(),
  217. 'md5' => $info->hash('md5'),
  218. 'sha1' => $info->hash('sha1'),
  219. 'thumb' => $thumb_path_name,
  220. 'module' => $module,
  221. 'width' => $img_width,
  222. 'height' => $img_height,
  223. ];
  224. // 写入数据库
  225. if ($file_add = AttachmentModel::create($file_info)) {
  226. $file_path = PUBLIC_PATH . $file_info['path'];
  227. return $this->uploadSuccess($from, $file_path, $file_info['name'], $file_add['id'], $callback);
  228. } else {
  229. return $this->uploadError($from, '上传失败', $callback);
  230. }
  231. } else {
  232. return $this->uploadError($from, $file->getError(), $callback);
  233. }
  234. }
  235. /**
  236. * 处理ueditor上传
  237. * @author 蔡伟明 <314013107@qq.com>
  238. * @param string $module 来自哪个模块
  239. * @return string|\think\response\Json
  240. */
  241. private function ueditor($module = '') {
  242. $action = $this->request->get('action');
  243. $config_file = './static/libs/ueditor/php/config.json';
  244. $config = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents($config_file)), true);
  245. switch ($action) {
  246. /* 获取配置信息 */
  247. case 'config':
  248. $result = $config;
  249. break;
  250. /* 上传图片 */
  251. case 'uploadimage':
  252. return $this->saveFile('images', 'ueditor', $module);
  253. break;
  254. /* 上传涂鸦 */
  255. case 'uploadscrawl':
  256. return $this->saveFile('images', 'ueditor_scrawl', $module);
  257. break;
  258. /* 上传视频 */
  259. case 'uploadvideo':
  260. return $this->saveFile('videos', 'ueditor', $module);
  261. break;
  262. /* 上传附件 */
  263. case 'uploadfile':
  264. return $this->saveFile('files', 'ueditor', $module);
  265. break;
  266. /* 列出图片 */
  267. case 'listimage':
  268. return $this->showFile('listimage', $config);
  269. break;
  270. /* 列出附件 */
  271. case 'listfile':
  272. return $this->showFile('listfile', $config);
  273. break;
  274. /* 抓取远程附件 */
  275. // case 'catchimage':
  276. // $result = include("action_crawler.php");
  277. // break;
  278. default:
  279. $result = ['state' => '请求地址出错'];
  280. break;
  281. }
  282. /* 输出结果 */
  283. if (isset($_GET["callback"])) {
  284. if (preg_match("/^[\w_]+$/", $_GET["callback"])) {
  285. return htmlspecialchars($_GET["callback"]) . '(' . $result . ')';
  286. } else {
  287. return json(['state' => 'callback参数不合法']);
  288. }
  289. } else {
  290. return json($result);
  291. }
  292. }
  293. /**
  294. * 保存涂鸦(ueditor)
  295. * @author 蔡伟明 <314013107@qq.com>
  296. * @return \think\response\Json
  297. */
  298. private function saveScrawl() {
  299. $file = $this->request->post('file');
  300. $file_content = base64_decode($file);
  301. $file_name = md5($file) . '.jpg';
  302. $dir = config('upload_path') . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . date('Ymd', $this->request->time());
  303. $file_path = $dir . DIRECTORY_SEPARATOR . $file_name;
  304. if (!is_dir($dir)) {
  305. mkdir($dir, 0755, true);
  306. }
  307. if (false === file_put_contents($file_path, $file_content)) {
  308. return json(['state' => '涂鸦上传出错']);
  309. }
  310. $file = new File($file_path);
  311. $img = Image::open($file);
  312. $file_info = [
  313. 'uid' => session('user_auth.uid'),
  314. 'name' => $file_name,
  315. 'mime' => 'image/png',
  316. 'path' => 'uploads/images/' . date('Ymd', $this->request->time()) . '/' . $file_name,
  317. 'ext' => 'png',
  318. 'size' => $file->getSize(),
  319. 'md5' => $file->hash('md5'),
  320. 'sha1' => $file->hash('sha1'),
  321. 'module' => $this->request->param('module', ''),
  322. 'width' => $img->width(),
  323. 'height' => $img->height(),
  324. ];
  325. if ($file_add = AttachmentModel::create($file_info)) {
  326. // 返回成功信息
  327. return json([
  328. "state" => "SUCCESS", // 上传状态,上传成功时必须返回"SUCCESS"
  329. "url" => PUBLIC_PATH . $file_info['path'], // 返回的地址
  330. "title" => $file_info['name'], // 附件名
  331. ]);
  332. } else {
  333. return json(['state' => '涂鸦上传出错']);
  334. }
  335. }
  336. /**
  337. * 显示附件列表(ueditor)
  338. * @param string $type 类型
  339. * @param $config
  340. * @author 蔡伟明 <314013107@qq.com>
  341. * @return \think\response\Json
  342. */
  343. private function showFile($type, $config) {
  344. /* 判断类型 */
  345. switch ($type) {
  346. /* 列出附件 */
  347. case 'listfile':
  348. $allowFiles = $config['fileManagerAllowFiles'];
  349. $listSize = $config['fileManagerListSize'];
  350. $path = realpath(config('upload_path') . '/files/');
  351. break;
  352. /* 列出图片 */
  353. case 'listimage':
  354. default:
  355. $allowFiles = $config['imageManagerAllowFiles'];
  356. $listSize = $config['imageManagerListSize'];
  357. $path = realpath(config('upload_path') . '/images/');
  358. }
  359. $allowFiles = substr(str_replace(".", "|", join("", $allowFiles)), 1);
  360. /* 获取参数 */
  361. $size = isset($_GET['size']) ? htmlspecialchars($_GET['size']) : $listSize;
  362. $start = isset($_GET['start']) ? htmlspecialchars($_GET['start']) : 0;
  363. $end = $start + $size;
  364. /* 获取附件列表 */
  365. $files = $this->getfiles($path, $allowFiles);
  366. if (!count($files)) {
  367. return json(array(
  368. "state" => "no match file",
  369. "list" => array(),
  370. "start" => $start,
  371. "total" => count($files),
  372. ));
  373. }
  374. /* 获取指定范围的列表 */
  375. $len = count($files);
  376. for ($i = min($end, $len) - 1, $list = array(); $i < $len && $i >= 0 && $i >= $start; $i--) {
  377. $list[] = $files[$i];
  378. }
  379. //倒序
  380. //for ($i = $end, $list = array(); $i < $len && $i < $end; $i++){
  381. // $list[] = $files[$i];
  382. //}
  383. /* 返回数据 */
  384. $result = array(
  385. "state" => "SUCCESS",
  386. "list" => $list,
  387. "start" => $start,
  388. "total" => count($files),
  389. );
  390. return json($result);
  391. }
  392. /**
  393. * 处理Jcrop图片裁剪
  394. * @author 蔡伟明 <314013107@qq.com>
  395. */
  396. private function jcrop() {
  397. $file_path = $this->request->post('path', '');
  398. $cut_info = $this->request->post('cut', '');
  399. $thumb = $this->request->post('thumb', '');
  400. $watermark = $this->request->post('watermark', '');
  401. $module = $this->request->param('module', '');
  402. // 上传图片
  403. if ($file_path == '') {
  404. $file = $this->request->file('file');
  405. // 附件类型限制
  406. $ext_limit = config('upload_image_ext');
  407. $ext_limit = $ext_limit != '' ? parse_attr($ext_limit) : '';
  408. // 判断附件格式是否符合
  409. $file_name = $file->getInfo('name');
  410. $file_ext = strtolower(substr($file_name, strrpos($file_name, '.') + 1));
  411. if ($ext_limit == '') {
  412. $this->error('获取文件信息失败!');
  413. }
  414. if (strtolower($file_ext) == 'php') {
  415. $this->error('禁止上传非法文件!');
  416. }
  417. if ($file->getMime() == 'text/x-php' || $file->getMime() == 'text/html') {
  418. $this->error('禁止上传非法文件!');
  419. }
  420. if (preg_grep("/php/i", $ext_limit)) {
  421. $this->error('禁止上传非法文件!');
  422. }
  423. if (!preg_grep("/$file_ext/i", $ext_limit)) {
  424. $this->error('附件类型不正确!');
  425. }
  426. if (!is_dir(config('upload_temp_path'))) {
  427. mkdir(config('upload_temp_path'), 0766, true);
  428. }
  429. $info = $file->move(config('upload_temp_path'), $file->hash('md5'));
  430. if ($info) {
  431. return json(['code' => 1, 'src' => PUBLIC_PATH . 'uploads/temp/' . $info->getFilename()]);
  432. } else {
  433. $this->error('上传失败');
  434. }
  435. }
  436. $file_path = config('upload_temp_path') . str_replace(PUBLIC_PATH . 'uploads/temp/', '', $file_path);
  437. if (is_file($file_path)) {
  438. // 获取裁剪信息
  439. $cut_info = explode(',', $cut_info);
  440. // 读取图片
  441. $image = Image::open($file_path);
  442. $dir_name = date('Ymd');
  443. $file_dir = config('upload_path') . DIRECTORY_SEPARATOR . 'images/' . $dir_name . '/';
  444. if (!is_dir($file_dir)) {
  445. mkdir($file_dir, 0766, true);
  446. }
  447. $file_name = md5(microtime(true)) . '.' . $image->type();
  448. $new_file_path = $file_dir . $file_name;
  449. // 裁剪图片
  450. $image->crop($cut_info[0], $cut_info[1], $cut_info[2], $cut_info[3], $cut_info[4], $cut_info[5])->save($new_file_path);
  451. // 水印功能
  452. if ($watermark == '') {
  453. if (config('upload_thumb_water') == 1 && config('upload_thumb_water_pic') > 0) {
  454. $this->create_water($new_file_path, config('upload_thumb_water_pic'));
  455. }
  456. } else {
  457. if (strtolower($watermark) != 'close') {
  458. list($watermark_img, $watermark_pos, $watermark_alpha) = explode('|', $watermark);
  459. $this->create_water($new_file_path, $watermark_img, $watermark_pos, $watermark_alpha);
  460. }
  461. }
  462. // 是否创建缩略图
  463. $thumb_path_name = '';
  464. if ($thumb == '') {
  465. if (config('upload_image_thumb') != '') {
  466. $thumb_path_name = $this->create_thumb($new_file_path, $dir_name, $file_name);
  467. }
  468. } else {
  469. if (strtolower($thumb) != 'close') {
  470. list($thumb_size, $thumb_type) = explode('|', $thumb);
  471. $thumb_path_name = $this->create_thumb($new_file_path, $dir_name, $file_name, $thumb_size, $thumb_type);
  472. }
  473. }
  474. // 保存图片
  475. $file = new File($new_file_path);
  476. $file_info = [
  477. 'uid' => session('user_auth.uid'),
  478. 'name' => $file_name,
  479. 'mime' => $image->mime(),
  480. 'path' => 'uploads/images/' . $dir_name . '/' . $file_name,
  481. 'ext' => $image->type(),
  482. 'size' => $file->getSize(),
  483. 'md5' => $file->hash('md5'),
  484. 'sha1' => $file->hash('sha1'),
  485. 'thumb' => $thumb_path_name,
  486. 'module' => $module,
  487. 'width' => $image->width(),
  488. 'height' => $image->height(),
  489. ];
  490. if ($file_add = AttachmentModel::create($file_info)) {
  491. // 删除临时图片
  492. unlink($file_path);
  493. // 返回成功信息
  494. return json([
  495. 'code' => 1,
  496. 'id' => $file_add['id'],
  497. 'src' => PUBLIC_PATH . $file_info['path'],
  498. 'thumb' => $thumb_path_name == '' ? '' : PUBLIC_PATH . $thumb_path_name,
  499. ]);
  500. } else {
  501. $this->error('上传失败');
  502. }
  503. }
  504. $this->error('文件不存在');
  505. }
  506. /**
  507. * 创建缩略图
  508. * @param string $file 目标文件,可以是文件对象或文件路径
  509. * @param string $dir 保存目录,即目标文件所在的目录名
  510. * @param string $save_name 缩略图名
  511. * @param string $thumb_size 尺寸
  512. * @param string $thumb_type 裁剪类型
  513. * @author 蔡伟明 <314013107@qq.com>
  514. * @return string 缩略图路径
  515. */
  516. private function create_thumb($file = '', $dir = '', $save_name = '', $thumb_size = '', $thumb_type = '') {
  517. // 获取要生成的缩略图最大宽度和高度
  518. $thumb_size = $thumb_size == '' ? config('upload_image_thumb') : $thumb_size;
  519. list($thumb_max_width, $thumb_max_height) = explode(',', $thumb_size);
  520. // 读取图片
  521. $image = Image::open($file);
  522. // 生成缩略图
  523. $thumb_type = $thumb_type == '' ? config('upload_image_thumb_type') : $thumb_type;
  524. $image->thumb($thumb_max_width, $thumb_max_height, $thumb_type);
  525. // 保存缩略图
  526. $thumb_path = config('upload_path') . DIRECTORY_SEPARATOR . 'images/' . $dir . '/thumb/';
  527. if (!is_dir($thumb_path)) {
  528. mkdir($thumb_path, 0766, true);
  529. }
  530. $thumb_path_name = $thumb_path . $save_name;
  531. $image->save($thumb_path_name);
  532. $thumb_path_name = 'uploads/images/' . $dir . '/thumb/' . $save_name;
  533. return $thumb_path_name;
  534. }
  535. /**
  536. * 添加水印
  537. * @param string $file 要添加水印的文件路径
  538. * @param string $watermark_img 水印图片id
  539. * @param string $watermark_pos 水印位置
  540. * @param string $watermark_alpha 水印透明度
  541. * @author 蔡伟明 <314013107@qq.com>
  542. */
  543. private function create_water($file = '', $watermark_img = '', $watermark_pos = '', $watermark_alpha = '') {
  544. $path = model('admin/attachment')->getFilePath($watermark_img, 1);
  545. $thumb_water_pic = realpath(Env::get('root_path') . 'public/' . $path);
  546. if (is_file($thumb_water_pic)) {
  547. // 读取图片
  548. $image = Image::open($file);
  549. // 添加水印
  550. $watermark_pos = $watermark_pos == '' ? config('upload_thumb_water_position') : $watermark_pos;
  551. $watermark_alpha = $watermark_alpha == '' ? config('upload_thumb_water_alpha') : $watermark_alpha;
  552. $image->water($thumb_water_pic, $watermark_pos, $watermark_alpha);
  553. // 保存水印图片,覆盖原图
  554. $image->save($file);
  555. }
  556. }
  557. /**
  558. * 上传成功信息
  559. * @param $from
  560. * @param string $file_path
  561. * @param string $file_name
  562. * @param string $file_id
  563. * @param string $callback
  564. * @return string|\think\response\Json
  565. * @author 蔡伟明 <314013107@qq.com>
  566. */
  567. private function uploadSuccess($from, $file_path = '', $file_name = '', $file_id = '', $callback = '') {
  568. switch ($from) {
  569. case 'wangeditor':
  570. return $file_path;
  571. break;
  572. case 'ueditor':
  573. return json([
  574. "state" => "SUCCESS", // 上传状态,上传成功时必须返回"SUCCESS"
  575. "url" => $file_path, // 返回的地址
  576. "title" => $file_name, // 附件名
  577. ]);
  578. break;
  579. case 'editormd':
  580. return json([
  581. "success" => 1,
  582. "message" => '上传成功',
  583. "url" => $file_path,
  584. ]);
  585. break;
  586. case 'ckeditor':
  587. return ck_js($callback, $file_path);
  588. break;
  589. default:
  590. return json([
  591. 'code' => 1,
  592. 'info' => '上传成功',
  593. 'class' => 'success',
  594. 'id' => $file_id,
  595. 'path' => $file_path,
  596. ]);
  597. }
  598. }
  599. /**
  600. * 上传错误信息
  601. * @param $from
  602. * @param string $msg
  603. * @param string $callback
  604. * @return string|\think\response\Json
  605. * @author 蔡伟明 <314013107@qq.com>
  606. */
  607. private function uploadError($from, $msg = '', $callback = '') {
  608. switch ($from) {
  609. case 'wangeditor':
  610. return "error|" . $msg;
  611. break;
  612. case 'ueditor':
  613. return json(['state' => $msg]);
  614. break;
  615. case 'editormd':
  616. return json(["success" => 0, "message" => $msg]);
  617. break;
  618. case 'ckeditor':
  619. return ck_js($callback, '', $msg);
  620. break;
  621. default:
  622. return json([
  623. 'code' => 0,
  624. 'class' => 'danger',
  625. 'info' => $msg,
  626. ]);
  627. }
  628. }
  629. /**
  630. * 遍历获取目录下的指定类型的附件
  631. * @param string $path 路径
  632. * @param string $allowFiles 允许查看的类型
  633. * @param array $files 文件列表
  634. * @author 蔡伟明 <314013107@qq.com>
  635. * @return array|null
  636. */
  637. public function getfiles($path = '', $allowFiles = '', &$files = array()) {
  638. if (!is_dir($path)) {
  639. return null;
  640. }
  641. if (substr($path, strlen($path) - 1) != '/') {
  642. $path .= '/';
  643. }
  644. $handle = opendir($path);
  645. while (false !== ($file = readdir($handle))) {
  646. if ($file != '.' && $file != '..') {
  647. $path2 = $path . $file;
  648. if (is_dir($path2)) {
  649. $this->getfiles($path2, $allowFiles, $files);
  650. } else {
  651. if (preg_match("/\.(" . $allowFiles . ")$/i", $file)) {
  652. $files[] = array(
  653. 'url' => str_replace("\\", "/", substr($path2, strlen($_SERVER['DOCUMENT_ROOT']))),
  654. 'mtime' => filemtime($path2),
  655. );
  656. }
  657. }
  658. }
  659. }
  660. return $files;
  661. }
  662. /**
  663. * 启用附件
  664. * @param array $record 行为日志
  665. * @author 蔡伟明 <314013107@qq.com>
  666. * @return mixed
  667. */
  668. public function enable($record = []) {
  669. return $this->setStatus('enable');
  670. }
  671. /**
  672. * 禁用附件
  673. * @param array $record 行为日志
  674. * @author 蔡伟明 <314013107@qq.com>
  675. * @return mixed
  676. */
  677. public function disable($record = []) {
  678. return $this->setStatus('disable');
  679. }
  680. /**
  681. * 设置附件状态:删除、禁用、启用
  682. * @param string $type 类型:delete/enable/disable
  683. * @param array $record
  684. * @author 蔡伟明 <314013107@qq.com>
  685. * @throws \think\Exception
  686. * @throws \think\exception\PDOException
  687. */
  688. public function setStatus($type = '', $record = []) {
  689. $ids = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
  690. $ids = is_array($ids) ? implode(',', $ids) : $ids;
  691. return parent::setStatus($type, ['attachment_' . $type, 'admin_attachment', 0, UID, $ids]);
  692. }
  693. /**
  694. * 删除附件
  695. * @param string $ids 附件id
  696. * @author 蔡伟明 <314013107@qq.com>
  697. * @throws \think\Exception
  698. * @throws \think\exception\PDOException
  699. */
  700. public function delete($ids = '') {
  701. $ids = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
  702. if (empty($ids)) {
  703. $this->error('缺少主键');
  704. }
  705. $files_path = AttachmentModel::where('id', 'in', $ids)->column('path,thumb', 'id');
  706. foreach ($files_path as $value) {
  707. $real_path = realpath(config('upload_path') . '/../' . $value['path']);
  708. $real_path_thumb = realpath(config('upload_path') . '/../' . $value['thumb']);
  709. if (is_file($real_path) && !unlink($real_path)) {
  710. $this->error('删除失败');
  711. }
  712. if (is_file($real_path_thumb) && !unlink($real_path_thumb)) {
  713. $this->error('删除缩略图失败');
  714. }
  715. }
  716. if (AttachmentModel::where('id', 'in', $ids)->delete()) {
  717. // 记录行为
  718. $ids = is_array($ids) ? implode(',', $ids) : $ids;
  719. action_log('attachment_delete', 'admin_attachment', 0, UID, $ids);
  720. $this->success('删除成功');
  721. } else {
  722. $this->error('删除失败');
  723. }
  724. }
  725. /**
  726. * 快速编辑
  727. * @param array $record 行为日志
  728. * @author 蔡伟明 <314013107@qq.com>
  729. * @return mixed
  730. */
  731. public function quickEdit($record = []) {
  732. $id = input('post.pk', '');
  733. return parent::quickEdit(['attachment_edit', 'admin_attachment', 0, UID, $id]);
  734. }
  735. }