UserExpireAutoWarning.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Components\Helpers;
  4. use Illuminate\Console\Command;
  5. use App\Http\Models\User;
  6. use App\Mail\userExpireWarning;
  7. use App\Mail\userExpireWarningToday;
  8. use Mail;
  9. use Log;
  10. class UserExpireAutoWarning extends Command
  11. {
  12. protected $signature = 'userExpireAutoWarning';
  13. protected $description = '用户临近到期自动发邮件提醒';
  14. protected static $systemConfig;
  15. public function __construct()
  16. {
  17. parent::__construct();
  18. self::$systemConfig = Helpers::systemConfig();
  19. }
  20. public function handle()
  21. {
  22. $jobStartTime = microtime(true);
  23. // 用户临近到期自动发邮件提醒
  24. if (self::$systemConfig['expire_warning']) {
  25. $this->userExpireWarning();
  26. }
  27. $jobEndTime = microtime(true);
  28. $jobUsedTime = round(($jobEndTime - $jobStartTime), 4);
  29. Log::info('执行定时任务【' . $this->description . '】,耗时' . $jobUsedTime . '秒');
  30. }
  31. private function userExpireWarning()
  32. {
  33. // 只取SSR没被禁用的用户,其他不用管
  34. $userList = User::query()->where('enable', 1)->get();
  35. foreach ($userList as $user) {
  36. // 用户名不是邮箱的跳过
  37. if (false === filter_var($user->username, FILTER_VALIDATE_EMAIL)) {
  38. continue;
  39. }
  40. // 计算剩余可用时间
  41. $lastCanUseDays = ceil(round(strtotime($user->expire_time) - strtotime(date('Y-m-d H:i:s'))) / 3600 / 24);
  42. if ($lastCanUseDays == 0) {
  43. $title = '账号过期提醒';
  44. $content = '您的账号将于今天晚上【24:00】过期。';
  45. try {
  46. Mail::to($user->username)->send(new userExpireWarningToday(self::$systemConfig['website_name']));
  47. Helpers::addEmailLog($user->username, $title, $content);
  48. } catch (\Exception $e) {
  49. Helpers::addEmailLog($user->username, $title, $content, 0, $e->getMessage());
  50. }
  51. } elseif ($lastCanUseDays > 0 && $lastCanUseDays <= self::$systemConfig['expire_days']) {
  52. $title = '账号过期提醒';
  53. $content = '您的账号还剩' . $lastCanUseDays . '天即将过期。';
  54. try {
  55. Mail::to($user->username)->send(new userExpireWarning(self::$systemConfig['website_name'], $lastCanUseDays));
  56. Helpers::addEmailLog($user->username, $title, $content);
  57. } catch (\Exception $e) {
  58. Helpers::addEmailLog($user->username, $title, $content, 0, $e->getMessage());
  59. }
  60. }
  61. }
  62. }
  63. }