Attachment.php 29 KB

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