AddUserDomainBlock.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <?php
  2. namespace App\Console\Commands;
  3. use Illuminate\Console\Command;
  4. use App\User;
  5. use App\Models\DefaultDomainBlock;
  6. use App\Models\UserDomainBlock;
  7. use function Laravel\Prompts\text;
  8. use function Laravel\Prompts\confirm;
  9. use function Laravel\Prompts\progress;
  10. class AddUserDomainBlock extends Command
  11. {
  12. /**
  13. * The name and signature of the console command.
  14. *
  15. * @var string
  16. */
  17. protected $signature = 'app:add-user-domain-block';
  18. /**
  19. * The console command description.
  20. *
  21. * @var string
  22. */
  23. protected $description = 'Apply a domain block to all users';
  24. /**
  25. * Execute the console command.
  26. */
  27. public function handle()
  28. {
  29. $domain = text('Enter domain you want to block');
  30. $domain = strtolower($domain);
  31. $domain = $this->validateDomain($domain);
  32. if(!$domain || empty($domain)) {
  33. $this->error('Invalid domain');
  34. return;
  35. }
  36. $this->processBlocks($domain);
  37. return;
  38. }
  39. protected function validateDomain($domain)
  40. {
  41. if(!strpos($domain, '.')) {
  42. return;
  43. }
  44. if(str_starts_with($domain, 'https://')) {
  45. $domain = str_replace('https://', '', $domain);
  46. }
  47. if(str_starts_with($domain, 'http://')) {
  48. $domain = str_replace('http://', '', $domain);
  49. }
  50. $domain = strtolower(parse_url('https://' . $domain, PHP_URL_HOST));
  51. $valid = filter_var($domain, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME|FILTER_NULL_ON_FAILURE);
  52. if(!$valid) {
  53. return;
  54. }
  55. if($domain === config('pixelfed.domain.app')) {
  56. $this->error('Invalid domain');
  57. return;
  58. }
  59. $confirmed = confirm('Are you sure you want to block ' . $domain . '?');
  60. if(!$confirmed) {
  61. return;
  62. }
  63. return $domain;
  64. }
  65. protected function processBlocks($domain)
  66. {
  67. DefaultDomainBlock::updateOrCreate([
  68. 'domain' => $domain
  69. ]);
  70. progress(
  71. label: 'Updating user domain blocks...',
  72. steps: User::lazyById(500),
  73. callback: fn ($user) => $this->performTask($user, $domain),
  74. );
  75. }
  76. protected function performTask($user, $domain)
  77. {
  78. if(!$user->profile_id || $user->delete_after) {
  79. return;
  80. }
  81. if($user->status != null && $user->status != 'disabled') {
  82. return;
  83. }
  84. UserDomainBlock::updateOrCreate([
  85. 'profile_id' => $user->profile_id,
  86. 'domain' => $domain
  87. ]);
  88. }
  89. }