AddUserDomainBlock.php 2.4 KB

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