RemoveAlwaysElseRector

pull/7361/head
Your Name 5 days ago
parent a2e38e5ffe
commit 0435d08568

1
.gitignore vendored

@ -38,3 +38,4 @@
/storage/psalm-reports /storage/psalm-reports
/psalm.sarif.json /psalm.sarif.json
/.psalm-cache /.psalm-cache
.kiro/

@ -52,68 +52,65 @@ class SendUpdateActor extends Command
); );
return Command::SUCCESS; return Command::SUCCESS;
} else { }
$domain = $this->anticipate('Enter the instance domain', function ($input) { $domain = $this->anticipate('Enter the instance domain', function ($input) {
return Instance::where('domain', 'like', '%'.$input.'%')->pluck('domain')->toArray(); return Instance::where('domain', 'like', '%'.$input.'%')->pluck('domain')->toArray();
}); });
if (! $this->confirm('Are you sure you want to send actor updates to '.$domain.'?')) { if (! $this->confirm('Are you sure you want to send actor updates to '.$domain.'?')) {
return; return;
} }
if ($cur = Instance::whereDomain($domain)->whereNotNull('actors_last_synced_at')->first()) { if ($cur = Instance::whereDomain($domain)->whereNotNull('actors_last_synced_at')->first()) {
if (! $this->option('force')) { if (! $this->option('force')) {
$this->error('ERROR: Cannot re-sync this instance, it was already synced on '.$cur->actors_last_synced_at); $this->error('ERROR: Cannot re-sync this instance, it was already synced on '.$cur->actors_last_synced_at);
return;
}
}
$this->touchStorageCache($domain);
$this->line(' ');
$this->error('Keep this window open during this process or it will not complete!');
$sharedInbox = Profile::whereDomain($domain)->whereNotNull('sharedInbox')->first();
if (! $sharedInbox) {
$this->error('ERROR: Cannot find the sharedInbox of '.$domain);
return; return;
} }
$url = $sharedInbox->sharedInbox;
$this->line(' ');
$this->info('Found sharedInbox: '.$url);
$bar = $this->output->createProgressBar($totalUserCount);
$bar->start();
$startCache = $this->getStorageCache($domain);
User::whereNull('status')->when($startCache, function ($query, $startCache) use ($bar) {
$bar->advance($startCache);
return $query->where('id', '>', $startCache);
})->chunk(50, function ($users) use ($bar, $url, $domain) {
foreach ($users as $user) {
$this->updateStorageCache($domain, $user->id);
$profile = Profile::find($user->profile_id);
if (! $profile) {
continue;
}
$body = $this->updateObject($profile);
try {
Helpers::sendSignedObject($profile, $url, $body);
} catch (\Throwable) {
// Best-effort per user: a single bad host (transport
// failure, invalid destination, etc.) must not abort the
// fleet-wide actor update.
continue;
}
$bar->advance();
}
});
$bar->finish();
$this->line(' ');
$instance = Instance::whereDomain($domain)->firstOrFail();
$instance->actors_last_synced_at = now();
$instance->save();
$this->info('Finished!');
return Command::SUCCESS;
} }
$this->touchStorageCache($domain);
$this->line(' ');
$this->error('Keep this window open during this process or it will not complete!');
$sharedInbox = Profile::whereDomain($domain)->whereNotNull('sharedInbox')->first();
if (! $sharedInbox) {
$this->error('ERROR: Cannot find the sharedInbox of '.$domain);
return;
}
$url = $sharedInbox->sharedInbox;
$this->line(' ');
$this->info('Found sharedInbox: '.$url);
$bar = $this->output->createProgressBar($totalUserCount);
$bar->start();
$startCache = $this->getStorageCache($domain);
User::whereNull('status')->when($startCache, function ($query, $startCache) use ($bar) {
$bar->advance($startCache);
return $query->where('id', '>', $startCache);
})->chunk(50, function ($users) use ($bar, $url, $domain) {
foreach ($users as $user) {
$this->updateStorageCache($domain, $user->id);
$profile = Profile::find($user->profile_id);
if (! $profile) {
continue;
}
$body = $this->updateObject($profile);
try {
Helpers::sendSignedObject($profile, $url, $body);
} catch (\Throwable) {
// Best-effort per user: a single bad host (transport
// failure, invalid destination, etc.) must not abort the
// fleet-wide actor update.
continue;
}
$bar->advance();
}
});
$bar->finish();
$this->line(' ');
$instance = Instance::whereDomain($domain)->firstOrFail();
$instance->actors_last_synced_at = now();
$instance->save();
$this->info('Finished!');
return Command::SUCCESS;
return Command::SUCCESS; return Command::SUCCESS;
} }

@ -37,36 +37,29 @@ class PushGatewayRefresh extends Command
$this->info('Push Notification support is active!'); $this->info('Push Notification support is active!');
return; return;
} else { }
$this->error('Push notification support is NOT active'); $this->error('Push notification support is NOT active');
$action = select(
$action = select( label: 'Do you want to force re-check?',
label: 'Do you want to force re-check?', options: ['Yes', 'No'],
options: ['Yes', 'No'], required: true
required: true );
); if ($action === 'Yes') {
$recheck = NotificationAppGatewayService::forceSupportRecheck();
if ($action === 'Yes') { if ($recheck) {
$recheck = NotificationAppGatewayService::forceSupportRecheck(); $this->info('Success! Push Notifications are now active!');
if ($recheck) {
$this->info('Success! Push Notifications are now active!');
return;
} else {
$this->error('Error, please ensure you have a valid API key.');
$this->line(' ');
$this->line('For more info, visit https://docs.pixelfed.org/running-pixelfed/push-notifications.html');
$this->line(' ');
return;
}
return; return;
} else {
exit;
} }
$this->error('Error, please ensure you have a valid API key.');
$this->line(' ');
$this->line('For more info, visit https://docs.pixelfed.org/running-pixelfed/push-notifications.html');
$this->line(' ');
return;
return; return;
} }
exit;
return;
} }
} }

@ -133,9 +133,8 @@ class AccountController extends Controller
if ($request->wantsJson()) { if ($request->wantsJson()) {
return response()->json($res); return response()->json($res);
} else {
return redirect()->back();
} }
return redirect()->back();
} }
public function unmute(Request $request): JsonResponse|RedirectResponse public function unmute(Request $request): JsonResponse|RedirectResponse
@ -185,9 +184,8 @@ class AccountController extends Controller
if ($request->wantsJson()) { if ($request->wantsJson()) {
return response()->json($res); return response()->json($res);
} else {
return redirect()->back();
} }
return redirect()->back();
} }
public function block(Request $request): JsonResponse|RedirectResponse public function block(Request $request): JsonResponse|RedirectResponse
@ -271,9 +269,8 @@ class AccountController extends Controller
if ($request->wantsJson()) { if ($request->wantsJson()) {
return response()->json($res); return response()->json($res);
} else {
return redirect()->back();
} }
return redirect()->back();
} }
public function unblock(Request $request): JsonResponse|RedirectResponse public function unblock(Request $request): JsonResponse|RedirectResponse
@ -322,9 +319,8 @@ class AccountController extends Controller
if ($request->wantsJson()) { if ($request->wantsJson()) {
return response()->json($res); return response()->json($res);
} else {
return redirect()->back();
} }
return redirect()->back();
} }
public function followRequests(Request $request): View public function followRequests(Request $request): View

@ -704,12 +704,14 @@ trait AdminReportController
]); ]);
$report = Report::whereObjectId($request->input('object_id'))->findOrFail($request->input('id')); $report = Report::whereObjectId($request->input('object_id'))->findOrFail($request->input('id'));
if ($request->input('action_type') === 'profile') { if ($request->input('action_type') === 'profile') {
return $this->reportsHandleProfileAction($report, $request->input('action')); return $this->reportsHandleProfileAction($report, $request->input('action'));
} elseif ($request->input('action_type') === 'post') { }
if ($request->input('action_type') === 'post') {
return $this->reportsHandleStatusAction($report, $request->input('action')); return $this->reportsHandleStatusAction($report, $request->input('action'));
} elseif ($request->input('action_type') === 'story') { }
if ($request->input('action_type') === 'story') {
return $this->reportsHandleStoryAction($report, $request->input('action')); return $this->reportsHandleStoryAction($report, $request->input('action'));
} }

@ -373,15 +373,14 @@ trait AdminSettingsController
if (! $rules) { if (! $rules) {
return []; return [];
} else {
$json = json_decode($rules, true);
$idx = array_search($val, $json);
if ($idx !== false) {
unset($json[$idx]);
$json = array_values($json);
}
ConfigCacheService::put('app.rules', json_encode(array_values($json)));
} }
$json = json_decode($rules, true);
$idx = array_search($val, $json);
if ($idx !== false) {
unset($json[$idx]);
$json = array_values($json);
}
ConfigCacheService::put('app.rules', json_encode(array_values($json)));
Cache::forget('api:v1:instance-data:rules'); Cache::forget('api:v1:instance-data:rules');
Cache::forget('api:v1:instance-data-response-v1'); Cache::forget('api:v1:instance-data-response-v1');
@ -397,9 +396,8 @@ trait AdminSettingsController
if (! $rules) { if (! $rules) {
return []; return [];
} else {
ConfigCacheService::put('app.rules', json_encode([]));
} }
ConfigCacheService::put('app.rules', json_encode([]));
Cache::forget('api:v1:instance-data:rules'); Cache::forget('api:v1:instance-data:rules');
Cache::forget('api:v1:instance-data-response-v1'); Cache::forget('api:v1:instance-data-response-v1');
@ -535,9 +533,8 @@ trait AdminSettingsController
$cloud_ready = ! empty(config('filesystems.disks.'.$cloud_disk.'.key')) && ! empty(config('filesystems.disks.'.$cloud_disk.'.secret')); $cloud_ready = ! empty(config('filesystems.disks.'.$cloud_disk.'.key')) && ! empty(config('filesystems.disks.'.$cloud_disk.'.secret'));
if (! $cloud_ready) { if (! $cloud_ready) {
return redirect()->back()->withErrors(['cloud_storage' => 'Must configure cloud storage before enabling!']); return redirect()->back()->withErrors(['cloud_storage' => 'Must configure cloud storage before enabling!']);
} else {
ConfigCacheService::put('pixelfed.cloud_storage', true);
} }
ConfigCacheService::put('pixelfed.cloud_storage', true);
} }
} }
ConfigCacheService::put('federation.activitypub.authorized_fetch', $request->boolean('authorized_fetch')); ConfigCacheService::put('federation.activitypub.authorized_fetch', $request->boolean('authorized_fetch'));

@ -559,18 +559,22 @@ class AdminController extends Controller
if ($sort == 'all') { if ($sort == 'all') {
if ($pg) { if ($pg) {
return $query->latest(); return $query->latest();
} else {
return $query->groupBy('shortcode')->latest();
} }
} elseif ($sort == 'local') { return $query->groupBy('shortcode')->latest();
}
if ($sort == 'local') {
return $query->latest()->where('domain', '=', config('pixelfed.domain.app')); return $query->latest()->where('domain', '=', config('pixelfed.domain.app'));
} elseif ($sort == 'remote') { }
if ($sort == 'remote') {
return $query->latest()->where('domain', '!=', config('pixelfed.domain.app')); return $query->latest()->where('domain', '!=', config('pixelfed.domain.app'));
} elseif ($sort == 'duplicates') { }
if ($sort == 'duplicates') {
return $query->latest()->duplicateShortcodes(); return $query->latest()->duplicateShortcodes();
} elseif ($sort == 'disabled') { }
if ($sort == 'disabled') {
return $query->latest()->whereDisabled(true); return $query->latest()->whereDisabled(true);
} elseif ($sort == 'search') { }
if ($sort == 'search') {
$q = $query $q = $query
->latest() ->latest()
->where('shortcode', 'like', '%'.$request->input('q').'%') ->where('shortcode', 'like', '%'.$request->input('q').'%')
@ -580,7 +584,6 @@ class AdminController extends Controller
$q = $q->groupBy('shortcode'); $q = $q->groupBy('shortcode');
} }
} }
return $q; return $q;
} }
}) })
@ -698,15 +701,17 @@ class AdminController extends Controller
->when($filter, function ($q, $filter) { ->when($filter, function ($q, $filter) {
if ($filter === 'cw') { if ($filter === 'cw') {
return $q->where('cw', true); return $q->where('cw', true);
} elseif ($filter === 'unlisted') { }
if ($filter === 'unlisted') {
return $q->where('unlisted', true); return $q->where('unlisted', true);
} elseif ($filter === 'banned') { }
if ($filter === 'banned') {
return $q->where('status', 'banned'); return $q->where('status', 'banned');
} elseif ($filter === 'newest') { }
if ($filter === 'newest') {
return $q->orderByDesc('id'); return $q->orderByDesc('id');
} else {
return $q;
} }
return $q;
}) })
->cursorPaginate(10) ->cursorPaginate(10)
->withQueryString(); ->withQueryString();

@ -40,22 +40,27 @@ class AdminCuratedRegisterController extends Controller
}) })
->whereNotNull('email_verified_at') ->whereNotNull('email_verified_at')
->whereIsClosed(false); ->whereIsClosed(false);
} elseif ($filter === 'all') { }
if ($filter === 'all') {
return $q; return $q;
} elseif ($filter === 'responses') { }
if ($filter === 'responses') {
return $q->whereIsClosed(false) return $q->whereIsClosed(false)
->whereNotNull('email_verified_at') ->whereNotNull('email_verified_at')
->where('user_has_responded', true) ->where('user_has_responded', true)
->where('is_awaiting_more_info', true); ->where('is_awaiting_more_info', true);
} elseif ($filter === 'awaiting') { }
if ($filter === 'awaiting') {
return $q->whereIsClosed(false) return $q->whereIsClosed(false)
->where('is_rejected', false) ->where('is_rejected', false)
->where('is_approved', false) ->where('is_approved', false)
->where('user_has_responded', false) ->where('user_has_responded', false)
->where('is_awaiting_more_info', true); ->where('is_awaiting_more_info', true);
} elseif ($filter === 'approved') { }
if ($filter === 'approved') {
return $q->whereIsClosed(true)->whereIsApproved(true); return $q->whereIsClosed(true)->whereIsApproved(true);
} elseif ($filter === 'rejected') { }
if ($filter === 'rejected') {
return $q->whereIsClosed(true)->whereIsRejected(true); return $q->whereIsClosed(true)->whereIsRejected(true);
} }
}) })

@ -23,11 +23,11 @@ class AdminShadowFilterController extends Controller
->when($filter, function ($q, $filter) { ->when($filter, function ($q, $filter) {
if ($filter == 'all') { if ($filter == 'all') {
return $q; return $q;
} elseif ($filter == 'inactive') { }
if ($filter == 'inactive') {
return $q->whereActive(false); return $q->whereActive(false);
} else {
return $q;
} }
return $q;
}, function ($q, $filter) { }, function ($q, $filter) {
return $q->whereActive(true); return $q->whereActive(true);
}) })

@ -560,24 +560,18 @@ class AdminApiController extends Controller
$action = $request->input('action'); $action = $request->input('action');
abort_if($user->is_admin == true && $action !== 'refresh_stats', 400, 'Cannot moderate admin accounts'); abort_if($user->is_admin == true && $action !== 'refresh_stats', 400, 'Cannot moderate admin accounts');
if ($action === 'delete') { if ($action === 'delete') {
if (config('pixelfed.account_deletion') == false) { if (config('pixelfed.account_deletion') == false) {
abort(404); abort(404);
} }
abort_if($user->is_admin, 400, 'Cannot delete an admin account.'); abort_if($user->is_admin, 400, 'Cannot delete an admin account.');
$ts = now()->addMonth(); $ts = now()->addMonth();
$user->status = 'delete'; $user->status = 'delete';
$user->delete_after = $ts; $user->delete_after = $ts;
$user->save(); $user->save();
$profile->status = 'delete'; $profile->status = 'delete';
$profile->delete_after = $ts; $profile->delete_after = $ts;
$profile->save(); $profile->save();
ModLogService::boot() ModLogService::boot()
->objectUid($profile->id) ->objectUid($profile->id)
->objectId($profile->id) ->objectId($profile->id)
@ -586,10 +580,8 @@ class AdminApiController extends Controller
->action('admin.user.delete') ->action('admin.user.delete')
->accessLevel('admin') ->accessLevel('admin')
->save(); ->save();
PublicTimelineService::deleteByProfileId($profile->id); PublicTimelineService::deleteByProfileId($profile->id);
NetworkTimelineService::deleteByProfileId($profile->id); NetworkTimelineService::deleteByProfileId($profile->id);
if ($profile->user_id) { if ($profile->user_id) {
DB::table('oauth_access_tokens')->whereUserId($user->id)->delete(); DB::table('oauth_access_tokens')->whereUserId($user->id)->delete();
DB::table('oauth_auth_codes')->whereUserId($user->id)->delete(); DB::table('oauth_auth_codes')->whereUserId($user->id)->delete();
@ -609,12 +601,13 @@ class AdminApiController extends Controller
AccountService::del($profile->id); AccountService::del($profile->id);
DeleteRemoteProfilePipeline::dispatch($profile)->onQueue('high'); DeleteRemoteProfilePipeline::dispatch($profile)->onQueue('high');
} }
return [ return [
'status' => 200, 'status' => 200,
'msg' => 'deleted', 'msg' => 'deleted',
]; ];
} elseif ($action === 'refresh_stats') { }
if ($action === 'refresh_stats') {
$profile->following_count = DB::table('followers')->whereProfileId($user->profile_id)->count(); $profile->following_count = DB::table('followers')->whereProfileId($user->profile_id)->count();
$profile->followers_count = DB::table('followers')->whereFollowingId($user->profile_id)->count(); $profile->followers_count = DB::table('followers')->whereFollowingId($user->profile_id)->count();
$statusCount = Status::whereProfileId($user->profile_id) $statusCount = Status::whereProfileId($user->profile_id)
@ -685,7 +678,8 @@ class AdminApiController extends Controller
->save(); ->save();
$profile->no_autolink = ! $profile->no_autolink; $profile->no_autolink = ! $profile->no_autolink;
$profile->save(); $profile->save();
} else { }
else {
$profile->{$action} = filter_var($request->input('value'), FILTER_VALIDATE_BOOLEAN); $profile->{$action} = filter_var($request->input('value'), FILTER_VALIDATE_BOOLEAN);
$profile->save(); $profile->save();
@ -741,9 +735,8 @@ class AdminApiController extends Controller
->when($filter, function ($query, $filter) { ->when($filter, function ($query, $filter) {
if ($filter === 'all') { if ($filter === 'all') {
return $query; return $query;
} else {
return $query->where($filter, true);
} }
return $query->where($filter, true);
}) })
->when($sortBy, function ($query, $sortBy) use ($sort) { ->when($sortBy, function ($query, $sortBy) use ($sort) {
return $query->orderBy($sortBy, $sort); return $query->orderBy($sortBy, $sort);

@ -1579,9 +1579,8 @@ class ApiV1Controller extends Controller
} }
return $this->json($res, 200, ['Link' => $link]); return $this->json($res, 200, ['Link' => $link]);
} else {
return $this->json($res);
} }
return $this->json($res);
} }
/** /**
@ -2737,12 +2736,10 @@ class ApiV1Controller extends Controller
Cache::set('pf:services:apiv1:home:cached:coldbootcheck:'.$pid, 1, 86400); Cache::set('pf:services:apiv1:home:cached:coldbootcheck:'.$pid, 1, 86400);
FeedWarmCachePipeline::dispatchSync($pid); FeedWarmCachePipeline::dispatchSync($pid);
return response()->json([], 206);
} else {
Cache::set('pf:services:apiv1:home:cached:coldbootcheck:'.$pid, 1, 86400);
return response()->json([], 206); return response()->json([], 206);
} }
Cache::set('pf:services:apiv1:home:cached:coldbootcheck:'.$pid, 1, 86400);
return response()->json([], 206);
} }
$res = collect($res) $res = collect($res)

@ -155,16 +155,13 @@ class RegisterController extends Controller
} }
return view('auth.register'); return view('auth.register');
} else {
return view('auth.register');
}
} else {
if ((bool) config_cache('instance.curated_registration.enabled') && config('instance.curated_registration.state.fallback_on_closed_reg')) {
return redirect('/auth/sign_up');
} else {
abort(404);
} }
return view('auth.register');
}
if ((bool) config_cache('instance.curated_registration.enabled') && config('instance.curated_registration.state.fallback_on_closed_reg')) {
return redirect('/auth/sign_up');
} }
abort(404);
} }
/** /**

@ -104,9 +104,8 @@ class FederationController extends Controller
return response()->json($webfinger, 200, [], JSON_UNESCAPED_SLASHES) return response()->json($webfinger, 200, [], JSON_UNESCAPED_SLASHES)
->header('Access-Control-Allow-Origin', '*'); ->header('Access-Control-Allow-Origin', '*');
} else {
return response('', 400);
} }
return response('', 400);
} }
$hash = hash('sha256', $resource); $hash = hash('sha256', $resource);
$key = 'federation:webfinger:sha256:'.$hash; $key = 'federation:webfinger:sha256:'.$hash;
@ -182,7 +181,6 @@ class FederationController extends Controller
if (in_array($domain, InstanceService::getBannedDomains())) { if (in_array($domain, InstanceService::getBannedDomains())) {
return; return;
} }
if (isset($obj['type']) && $obj['type'] === 'Delete') { if (isset($obj['type']) && $obj['type'] === 'Delete') {
if (isset($obj['object']) && isset($obj['object']['type']) && isset($obj['object']['id'])) { if (isset($obj['object']) && isset($obj['object']['type']) && isset($obj['object']['id'])) {
if ($obj['object']['type'] === 'Person') { if ($obj['object']['type'] === 'Person') {
@ -207,11 +205,13 @@ class FederationController extends Controller
return; return;
} }
} }
return; return;
} elseif (isset($obj['type']) && in_array($obj['type'], ['Follow', 'Accept'])) { }
if (isset($obj['type']) && in_array($obj['type'], ['Follow', 'Accept'])) {
dispatch(new InboxValidator($username, $headers, $payload))->onQueue('follow'); dispatch(new InboxValidator($username, $headers, $payload))->onQueue('follow');
} else { }
else {
dispatch(new InboxValidator($username, $headers, $payload))->onQueue('high'); dispatch(new InboxValidator($username, $headers, $payload))->onQueue('high');
} }
} }
@ -237,7 +237,6 @@ class FederationController extends Controller
if (in_array($domain, InstanceService::getBannedDomains())) { if (in_array($domain, InstanceService::getBannedDomains())) {
return; return;
} }
if (isset($obj['type']) && $obj['type'] === 'Delete') { if (isset($obj['type']) && $obj['type'] === 'Delete') {
if (isset($obj['object']) && isset($obj['object']['type']) && isset($obj['object']['id'])) { if (isset($obj['object']) && isset($obj['object']['type']) && isset($obj['object']['id'])) {
if ($obj['object']['type'] === 'Person') { if ($obj['object']['type'] === 'Person') {
@ -262,11 +261,13 @@ class FederationController extends Controller
return; return;
} }
} }
return; return;
} elseif (isset($obj['type']) && in_array($obj['type'], ['Follow', 'Accept'])) { }
if (isset($obj['type']) && in_array($obj['type'], ['Follow', 'Accept'])) {
dispatch(new InboxWorker($headers, $payload))->onQueue('follow'); dispatch(new InboxWorker($headers, $payload))->onQueue('follow');
} else { }
else {
dispatch(new InboxWorker($headers, $payload))->onQueue('shared'); dispatch(new InboxWorker($headers, $payload))->onQueue('shared');
} }
} }

@ -253,9 +253,8 @@ class GroupsPostController extends Controller
if ($request->wantsJson()) { if ($request->wantsJson()) {
return response()->json(['Status successfully deleted.']); return response()->json(['Status successfully deleted.']);
} else {
return redirect($user->url());
} }
return redirect($user->url());
} }
public function likePost(Request $request): array public function likePost(Request $request): array

@ -275,27 +275,22 @@ class ImportPostController extends Controller
if ($exts->contains('mp4')) { if ($exts->contains('mp4')) {
if ($exts->contains('jpg', 'png', 'webp')) { if ($exts->contains('jpg', 'png', 'webp')) {
return 'photo:video:album'; return 'photo:video:album';
} else {
return 'video:album';
} }
} else { return 'video:album';
return 'photo:album';
}
} else {
if ($exts->isEmpty()) {
return 'photo';
}
$ext = $exts[0];
if (in_array($ext, ['jpg', 'jpeg', 'png', 'webp'])) {
return 'photo';
} elseif (in_array($ext, ['mp4'])) {
return 'video';
} else {
return 'photo';
} }
return 'photo:album';
} }
if ($exts->isEmpty()) {
return 'photo';
}
$ext = $exts[0];
if (in_array($ext, ['jpg', 'jpeg', 'png', 'webp'])) {
return 'photo';
}
if (in_array($ext, ['mp4'])) {
return 'video';
}
return 'photo';
} }
private function sanitizeFilename($filename): string private function sanitizeFilename($filename): string
@ -320,9 +315,8 @@ class ImportPostController extends Controller
if ($user->is_admin) { if ($user->is_admin) {
if (! $abortOnFail) { if (! $abortOnFail) {
return true; return true;
} else {
return true;
} }
return true;
} }
$admin = User::whereIsAdmin(true)->first(); $admin = User::whereIsAdmin(true)->first();

@ -107,50 +107,43 @@ class ProfileController extends Controller
} }
return view('profile.show', ['profile' => $profile, 'settings' => $settings]); return view('profile.show', ['profile' => $profile, 'settings' => $settings]);
} else {
$key = 'profile:settings:'.$user->id;
$ttl = now()->addHours(6);
$settings = Cache::remember($key, $ttl, function () use ($user) {
$s = $user->user?->settings;
return [
'crawlable' => $s->crawlable ?? true,
'following' => [
'count' => $s->show_profile_following_count ?? true,
'list' => $s->show_profile_following ?? false,
],
'followers' => [
'count' => $s->show_profile_follower_count ?? true,
'list' => $s->show_profile_followers ?? false,
],
];
});
if ($user->is_private == true) {
$isPrivate = $this->privateProfileCheck($user, $loggedIn);
}
$isBlocked = $this->blockedProfileCheck($user);
$owner = $loggedIn && Auth::id() === $user->user_id;
$is_following = ($owner === false && $request->user() !== null) ? $user->followedBy($request->user()->profile) : false;
if ($isPrivate === true || $isBlocked === true) {
$requested = $request->user() !== null ? FollowRequest::whereFollowerId($request->user()->profile_id)
->whereFollowingId($user->id)
->exists() : false;
return view('profile.private', ['user' => $user, 'is_following' => $is_following, 'requested' => $requested]);
}
$is_admin = is_null($user->domain) ? $user->user->is_admin : false;
$profile = $user;
if ($carousel) {
return view('profile.show_carousel', ['profile' => $profile, 'settings' => $settings]);
}
return view('profile.show', ['profile' => $profile, 'settings' => $settings]);
} }
$key = 'profile:settings:'.$user->id;
$ttl = now()->addHours(6);
$settings = Cache::remember($key, $ttl, function () use ($user) {
$s = $user->user?->settings;
return [
'crawlable' => $s->crawlable ?? true,
'following' => [
'count' => $s->show_profile_following_count ?? true,
'list' => $s->show_profile_following ?? false,
],
'followers' => [
'count' => $s->show_profile_follower_count ?? true,
'list' => $s->show_profile_followers ?? false,
],
];
});
if ($user->is_private == true) {
$isPrivate = $this->privateProfileCheck($user, $loggedIn);
}
$isBlocked = $this->blockedProfileCheck($user);
$owner = $loggedIn && Auth::id() === $user->user_id;
$is_following = ($owner === false && $request->user() !== null) ? $user->followedBy($request->user()->profile) : false;
if ($isPrivate === true || $isBlocked === true) {
$requested = $request->user() !== null ? FollowRequest::whereFollowerId($request->user()->profile_id)
->whereFollowingId($user->id)
->exists() : false;
return view('profile.private', ['user' => $user, 'is_following' => $is_following, 'requested' => $requested]);
}
$is_admin = is_null($user->domain) ? $user->user->is_admin : false;
$profile = $user;
if ($carousel) {
return view('profile.show_carousel', ['profile' => $profile, 'settings' => $settings]);
}
return view('profile.show', ['profile' => $profile, 'settings' => $settings]);
} }
protected function getCachedUser($username, $withTrashed = false) protected function getCachedUser($username, $withTrashed = false)
@ -166,12 +159,11 @@ class ProfileController extends Controller
return Profile::whereNull(['domain', 'status']) return Profile::whereNull(['domain', 'status'])
->whereUsername($username) ->whereUsername($username)
->first(); ->first();
} else {
return Profile::withTrashed()
->whereNull(['domain', 'status'])
->whereUsername($username)
->first();
} }
return Profile::withTrashed()
->whereNull(['domain', 'status'])
->whereUsername($username)
->first();
}); });
} }

@ -44,9 +44,8 @@ class PublicApiController extends Controller
{ {
if (! $user) { if (! $user) {
return []; return [];
} else {
return AccountService::get($user->profile_id);
} }
return AccountService::get($user->profile_id);
} }
public function getStatus(Request $request, $id) public function getStatus(Request $request, $id)
@ -482,56 +481,55 @@ class PublicApiController extends Controller
}) })
->values() ->values()
->toArray(); ->toArray();
} else { }
return Status::select( return Status::select(
'id', 'id',
'uri', 'uri',
'caption', 'caption',
'profile_id', 'profile_id',
'type', 'type',
'in_reply_to_id', 'in_reply_to_id',
'reblog_of_id', 'reblog_of_id',
'is_nsfw', 'is_nsfw',
'scope', 'scope',
'local', 'local',
'reply_count', 'reply_count',
'comments_disabled', 'comments_disabled',
'place_id', 'place_id',
'likes_count', 'likes_count',
'reblogs_count', 'reblogs_count',
'created_at', 'created_at',
'updated_at' 'updated_at'
) )
->whereIn('type', $types) ->whereIn('type', $types)
->when(! $textOnlyReplies, function ($q, $textOnlyReplies) { ->when(! $textOnlyReplies, function ($q, $textOnlyReplies) {
return $q->whereNull('in_reply_to_id'); return $q->whereNull('in_reply_to_id');
}) })
->whereIn('profile_id', $following) ->whereIn('profile_id', $following)
->whereIn('visibility', ['public', 'unlisted', 'private']) ->whereIn('visibility', ['public', 'unlisted', 'private'])
->orderBy('created_at', 'desc') ->orderBy('created_at', 'desc')
->limit($limit) ->limit($limit)
->get() ->get()
->map(function ($s) use ($user) { ->map(function ($s) use ($user) {
try { try {
$status = StatusService::get($s->id, false); $status = StatusService::get($s->id, false);
if (! $status) { if (! $status) {
return false;
}
} catch (\Exception) {
return false; return false;
} }
$status['favourited'] = (bool) LikeService::liked($user->profile_id, $s->id); } catch (\Exception) {
$status['bookmarked'] = (bool) BookmarkService::get($user->profile_id, $s->id); return false;
$status['reblogged'] = (bool) ReblogService::get($user->profile_id, $s->id); }
$status['favourited'] = (bool) LikeService::liked($user->profile_id, $s->id);
$status['bookmarked'] = (bool) BookmarkService::get($user->profile_id, $s->id);
$status['reblogged'] = (bool) ReblogService::get($user->profile_id, $s->id);
return $status; return $status;
}) })
->filter(function ($s) use ($filtered) { ->filter(function ($s) use ($filtered) {
return $s && isset($s['account']) && in_array($s['account']['id'], $filtered) === false; return $s && isset($s['account']) && in_array($s['account']['id'], $filtered) === false;
}) })
->values() ->values()
->toArray(); ->toArray();
}
} }
public function networkTimelineApi(Request $request): JsonResponse|Response public function networkTimelineApi(Request $request): JsonResponse|Response
@ -853,16 +851,14 @@ class PublicApiController extends Controller
$isFollowing = FollowerService::follows($pid, $profile['id']); $isFollowing = FollowerService::follows($pid, $profile['id']);
return $isFollowing ? ['public', 'unlisted', 'private'] : ['public']; return $isFollowing ? ['public', 'unlisted', 'private'] : ['public'];
} else { }
if ($user) { if ($user) {
$pid = $user->profile_id; $pid = $user->profile_id;
$isFollowing = FollowerService::follows($pid, $profile['id']); $isFollowing = FollowerService::follows($pid, $profile['id']);
return $isFollowing ? ['public', 'unlisted', 'private'] : ['public', 'unlisted']; return $isFollowing ? ['public', 'unlisted', 'private'] : ['public', 'unlisted'];
} else {
return ['public', 'unlisted'];
}
} }
return ['public', 'unlisted'];
} }
private function processStatuses($statuses, $user, $onlyMedia) private function processStatuses($statuses, $user, $onlyMedia)

@ -555,20 +555,17 @@ class RemoteAuthController extends Controller
$user = User::where('username', $username)->first(); $user = User::where('username', $username)->first();
if ($user) { if ($user) {
return ['id' => (string) $user->profile_id]; return ['id' => (string) $user->profile_id];
} else {
return [];
} }
} else { return [];
try { }
$profile = Helpers::profileFetch($account); try {
if ($profile) { $profile = Helpers::profileFetch($account);
return ['id' => (string) $profile->id]; if ($profile) {
} else { return ['id' => (string) $profile->id];
return [];
}
} catch (RequestException|\Exception) {
return [];
} }
return [];
} catch (RequestException|\Exception) {
return [];
} }
} }

@ -24,9 +24,8 @@ class SiteController extends Controller
{ {
if ($request->user() !== null) { if ($request->user() !== null) {
return $this->homeTimeline($request); return $this->homeTimeline($request);
} else {
return $this->homeGuest();
} }
return $this->homeGuest();
} }
public function homeGuest(): View public function homeGuest(): View

@ -34,14 +34,11 @@ class AccountInterstitial
$res = ['_refresh' => true, 'error' => 403, 'message' => \App\Models\AccountInterstitial::JSON_MESSAGE]; $res = ['_refresh' => true, 'error' => 403, 'message' => \App\Models\AccountInterstitial::JSON_MESSAGE];
return response()->json($res, 403); return response()->json($res, 403);
} else {
return redirect('/i/warning');
} }
} else { return redirect('/i/warning');
return $next($request);
} }
} else {
return $next($request); return $next($request);
} }
return $next($request);
} }
} }

@ -99,31 +99,25 @@ class DeleteWorker implements ShouldQueue
DeleteRemoteProfilePipeline::dispatch($profile)->onQueue('inbox'); DeleteRemoteProfilePipeline::dispatch($profile)->onQueue('inbox');
} }
return 1;
} else {
// Signature verification failed, exit.
return 1; return 1;
} }
} else { // Signature verification failed, exit.
// Remote user doesn't exist, exit early.
return 1; return 1;
} }
// Remote user doesn't exist, exit early.
return 1; return 1;
} else {
return 1;
}
} else {
$profile = null;
if ($this->verifySignature($headers, $payload) == true) {
ActivityHandler::dispatch($headers, $profile, $payload)->onQueue('delete');
return 1;
} else {
return 1; return 1;
} }
return 1;
}
$profile = null;
if ($this->verifySignature($headers, $payload) == true) {
ActivityHandler::dispatch($headers, $profile, $payload)->onQueue('delete');
return 1;
} }
return 1;
} }
@ -200,8 +194,7 @@ class DeleteWorker implements ShouldQueue
[$verified, $headers] = HttpSignature::verify($pkey, $signatureData, $headers, $inboxPath, $body); [$verified, $headers] = HttpSignature::verify($pkey, $signatureData, $headers, $inboxPath, $body);
if ($verified == 1) { if ($verified == 1) {
return true; return true;
} else {
return false;
} }
return false;
} }
} }

@ -159,9 +159,8 @@ class InboxWorker implements ShouldQueue
[$verified, $headers] = HttpSignature::verify($pkey, $signatureData, $headers, $inboxPath, $body); [$verified, $headers] = HttpSignature::verify($pkey, $signatureData, $headers, $inboxPath, $body);
if ($verified == 1) { if ($verified == 1) {
return true; return true;
} else {
return false;
} }
return false;
} }
/** /**

@ -50,10 +50,9 @@ class AutospamService
if (! Storage::exists(self::MODEL_FILE_PATH)) { if (! Storage::exists(self::MODEL_FILE_PATH)) {
return false; return false;
} else { }
if (Storage::size(self::MODEL_FILE_PATH) < 1000) { if (Storage::size(self::MODEL_FILE_PATH) < 1000) {
return false; return false;
}
} }
return true; return true;

@ -139,22 +139,18 @@ class ActiveSharedInboxService
$res = Storage::get(self::CACHE_FILE_NAME); $res = Storage::get(self::CACHE_FILE_NAME);
if (! $res) { if (! $res) {
return false; return false;
} else { }
$res = json_decode($res, true); $res = json_decode($res, true);
if (! $res || isset($res['version'], $res['data'], $res['created'], $res['updated'])) { if (! $res || isset($res['version'], $res['data'], $res['created'], $res['updated'])) {
if (now()->parse($res['updated'])->lt(now()->subMonths(6))) { if (now()->parse($res['updated'])->lt(now()->subMonths(6))) {
return false;
} else {
if ($res['version'] === self::CACHE_FILE_VERSION) {
return $res;
} else {
return false;
}
}
} else {
return false; return false;
} }
if ($res['version'] === self::CACHE_FILE_VERSION) {
return $res;
}
return false;
} }
return false;
} }
return false; return false;

@ -230,146 +230,138 @@ class SearchApiV2Service
if (Helpers::validateLocalUrl($query)) { if (Helpers::validateLocalUrl($query)) {
if (Str::contains($query, '/p/') || Str::contains($query, 'i/web/post/')) { if (Str::contains($query, '/p/') || Str::contains($query, 'i/web/post/')) {
return $this->resolveLocalStatus(); return $this->resolveLocalStatus();
} elseif (Str::contains($query, 'i/web/profile/')) { }
if (Str::contains($query, 'i/web/profile/')) {
return $this->resolveLocalProfileId(); return $this->resolveLocalProfileId();
} else {
return $this->resolveLocalProfile();
} }
} else { return $this->resolveLocalProfile();
if (! Helpers::validateUrl($query) && !str_contains($query, '@')) { }
if (! Helpers::validateUrl($query) && !str_contains($query, '@')) {
return $default;
}
if (
! Str::startsWith($query, 'http') &&
Str::substrCount($query, '@') == 1 &&
str_contains($query, '@') &&
!str_starts_with($query, '@')
) {
try {
$res = WebfingerService::lookup('@'.$query, $mastodonMode);
} catch (\Exception) {
return $default; return $default;
} }
if ($res && isset($res['id'], $res['url'])) {
if ( $domain = strtolower(parse_url($res['url'], PHP_URL_HOST));
! Str::startsWith($query, 'http') && if (in_array($domain, $banned)) {
Str::substrCount($query, '@') == 1 &&
str_contains($query, '@') &&
!str_starts_with($query, '@')
) {
try {
$res = WebfingerService::lookup('@'.$query, $mastodonMode);
} catch (\Exception) {
return $default; return $default;
} }
if ($res && isset($res['id'], $res['url'])) { $paginated = collect($res)->take($limit)->skip($offset)->toArray();
$domain = strtolower(parse_url($res['url'], PHP_URL_HOST)); if (! empty($paginated)) {
if (in_array($domain, $banned)) { $default['accounts'][] = $paginated;
return $default;
}
$paginated = collect($res)->take($limit)->skip($offset)->toArray();
if (! empty($paginated)) {
$default['accounts'][] = $paginated;
} else {
$default['accounts'] = [];
}
return $default;
} else { } else {
return $default; $default['accounts'] = [];
} }
}
if (Str::substrCount($query, '@') == 2) { return $default;
try { }
$res = WebfingerService::lookup($query, $mastodonMode); return $default;
} catch (\Exception) { }
if (Str::substrCount($query, '@') == 2) {
try {
$res = WebfingerService::lookup($query, $mastodonMode);
} catch (\Exception) {
return $default;
}
if ($res && isset($res['id'])) {
$domain = strtolower(parse_url($res['url'], PHP_URL_HOST));
if (in_array($domain, $banned)) {
return $default; return $default;
} }
if ($res && isset($res['id'])) { $paginated = collect($res)->take($limit)->skip($offset)->toArray();
$domain = strtolower(parse_url($res['url'], PHP_URL_HOST)); if (! empty($paginated)) {
if (in_array($domain, $banned)) { $default['accounts'][] = $paginated;
return $default;
}
$paginated = collect($res)->take($limit)->skip($offset)->toArray();
if (! empty($paginated)) {
$default['accounts'][] = $paginated;
} else {
$default['accounts'] = [];
}
return $default;
} else { } else {
return $default; $default['accounts'] = [];
} }
return $default;
} }
return $default;
}
if ($sid = Status::whereUri($query)->first()) {
$s = StatusService::get($sid->id, false);
if (! $s || isset($s['account']['moved'], $s['account']['moved']['id'])) {
return $default;
}
if (in_array($s['visibility'], ['public', 'unlisted'])) {
$default['statuses'][] = $s;
if ($sid = Status::whereUri($query)->first()) { return $default;
$s = StatusService::get($sid->id, false); }
if (! $s || isset($s['account']['moved'], $s['account']['moved']['id'])) { }
return $default; try {
} $res = ActivityPubFetchService::get($query);
if (in_array($s['visibility'], ['public', 'unlisted'])) {
$default['statuses'][] = $s;
return $default; if ($res) {
$json = json_decode($res, true);
if (! $json || ! isset($json['@context']) || ! isset($json['type']) || ! in_array($json['type'], ['Note', 'Person'])) {
return [
'accounts' => [],
'hashtags' => [],
'statuses' => [],
];
} }
}
try { switch ($json['type']) {
$res = ActivityPubFetchService::get($query); case 'Note':
$obj = Helpers::statusFetch($query);
if (! $obj || ! isset($obj['id'])) {
return $default;
}
$note = $mastodonMode ?
StatusService::getMastodon($obj['id'], false) :
StatusService::get($obj['id'], false);
if (! $note) {
return $default;
}
if (! isset($note['visibility']) || ! in_array($note['visibility'], ['public', 'unlisted'])) {
return $default;
}
$default['statuses'][] = $note;
return $default;
case 'Person':
$obj = Helpers::profileFetch($query);
if (! $obj) {
return $default;
}
if (in_array($obj['domain'], $banned)) {
return $default;
}
$default['accounts'][] = $mastodonMode ?
AccountService::getMastodon($obj['id'], true) :
AccountService::get($obj['id'], true);
if ($res) { return $default;
$json = json_decode($res, true);
if (! $json || ! isset($json['@context']) || ! isset($json['type']) || ! in_array($json['type'], ['Note', 'Person'])) { default:
return [ return [
'accounts' => [], 'accounts' => [],
'hashtags' => [], 'hashtags' => [],
'statuses' => [], 'statuses' => [],
]; ];
}
switch ($json['type']) {
case 'Note':
$obj = Helpers::statusFetch($query);
if (! $obj || ! isset($obj['id'])) {
return $default;
}
$note = $mastodonMode ?
StatusService::getMastodon($obj['id'], false) :
StatusService::get($obj['id'], false);
if (! $note) {
return $default;
}
if (! isset($note['visibility']) || ! in_array($note['visibility'], ['public', 'unlisted'])) {
return $default;
}
$default['statuses'][] = $note;
return $default;
case 'Person':
$obj = Helpers::profileFetch($query);
if (! $obj) {
return $default;
}
if (in_array($obj['domain'], $banned)) {
return $default;
}
$default['accounts'][] = $mastodonMode ?
AccountService::getMastodon($obj['id'], true) :
AccountService::get($obj['id'], true);
return $default;
default:
return [
'accounts' => [],
'hashtags' => [],
'statuses' => [],
];
}
} }
} catch (\Exception) {
return [
'accounts' => [],
'hashtags' => [],
'statuses' => [],
];
} }
} catch (\Exception) {
return $default; return [
'accounts' => [],
'hashtags' => [],
'statuses' => [],
];
} }
return $default;
} }
/** /**

@ -540,9 +540,8 @@ class Helpers
$res = json_decode($res, true, 8); $res = json_decode($res, true, 8);
if (json_last_error() === JSON_ERROR_NONE) { if (json_last_error() === JSON_ERROR_NONE) {
return $res; return $res;
} else {
return false;
} }
return false;
}); });
} }

@ -384,8 +384,7 @@ class Validator extends Regex
$found = preg_match($pattern, $string, $matches); $found = preg_match($pattern, $string, $matches);
if (! $optional) { if (! $optional) {
return ($string || $string === '') && $found && $matches[0] === $string; return ($string || $string === '') && $found && $matches[0] === $string;
} else {
return ! (($string || $string === '') && (! $found || $matches[0] !== $string));
} }
return ! (($string || $string === '') && (! $found || $matches[0] !== $string));
} }
} }

@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
use Rector\Config\RectorConfig;
use Rector\EarlyReturn\Rector\If_\RemoveAlwaysElseRector;
return RectorConfig::configure()
->withPaths([
__DIR__.'/app',
])
->withSkip([
__DIR__.'/bootstrap/cache',
__DIR__.'/storage',
__DIR__.'/vendor',
])
->withRules([
RemoveAlwaysElseRector::class,
]);
Loading…
Cancel
Save