ArticleImgPersistence.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: 中闽 < 1464674022@qq.com >
  5. * Date: 2020/2/4
  6. * Time: 12:47
  7. */
  8. namespace app\common\command;
  9. use app\common\model\Article;
  10. use file\FileHelper;
  11. use file\PathHelper;
  12. use think\console\Command;
  13. use think\console\Input;
  14. use think\console\Output;
  15. use think\Db;
  16. use time\Timestamp;
  17. class ArticleImgPersistence extends Command
  18. {
  19. /**
  20. * 文章网络图片本地化
  21. * php think ArticleImgPersistence
  22. */
  23. protected function configure()
  24. {
  25. $this->setName('ArticleImgPersistence')
  26. ->setDescription('article image save to local');
  27. }
  28. protected function execute(Input $input, Output $output)
  29. {
  30. $articles = (new Article())->where(['content' => ['like', '%http%']])->order('id desc')->select();
  31. $savePath = DS . 'uploads' . DS . 'admin' . DS . 'attachment' . DS . Timestamp::dayStart(time()) . DS;
  32. $count = 0;
  33. foreach ($articles as $article) {
  34. $output->writeln('article id = ' . $article->id);
  35. $imgs = matchImg($article->content);
  36. foreach ($imgs as $img) {
  37. if (ifContain($img, 'http://') || ifContain($img, 'https://')) {
  38. $saveName = PathHelper::getFilename($img);
  39. $output->writeln($img . ' =========>>>>>> ' . $savePath . $saveName);
  40. FileHelper::fetchDownFile($img, ROOT_PATH . 'public' . $savePath, $saveName);
  41. $data = [
  42. 'module' => '',//模块
  43. 'use' => 'articleImgPersistence',//来源
  44. 'filename' => $saveName,//文件名
  45. 'filepath' => $savePath . $saveName,//文件路径
  46. 'fileext' => PathHelper::getExt($img),//文件后缀
  47. 'filesize' => 0,//文件大小
  48. 'create_time' => time(),//时间
  49. 'uploadip' => '',//IP
  50. 'user_id' => 0,
  51. 'status' => \app\common\model\Attachment::STATUS_OPEN,
  52. 'admin_id' => 0,
  53. 'audit_time' => 0,
  54. ];
  55. Db::name('attachment')->insertGetId($data);
  56. $article->save(['content' => str_replace($img, replaceUrlDS($savePath . $saveName), $article->content)]);
  57. $count++;
  58. }
  59. }
  60. }
  61. $output->writeln('finish , save image ' . $count);
  62. }
  63. }