| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentCommunity\App\Hooks\Handlers; |
| 4 |
|
| 5 |
use FluentCommunity\App\Models\Comment; |
| 6 |
use FluentCommunity\App\Models\Feed; |
| 7 |
use FluentCommunity\App\Models\User; |
| 8 |
|
| 9 |
class RateLimitHandler |
| 10 |
{ |
| 11 |
public function register() |
| 12 |
{ |
| 13 |
add_action('fluent_community/check_rate_limit/create_post', [$this, 'maybeLimitPost'], 10, 1); |
| 14 |
add_action('fluent_community/check_rate_limit/create_comment', [$this, 'maybeLimitComment'], 10, 1); |
| 15 |
} |
| 16 |
|
| 17 |
public function maybeLimitPost(User $user) |
| 18 |
{ |
| 19 |
// Check how many posts user has created in last 5 minutes |
| 20 |
$postsCount = Feed::query()->withoutGlobalScopes()->where('user_id', $user->ID) |
| 21 |
->where('created_at', '>', gmdate('Y-m-d H:i:s', current_time('timestamp') - 300)) |
| 22 |
->count(); |
| 23 |
|
| 24 |
$limitPer5Minutes = apply_filters('fluent_community/rate_limit/posts_per_5_minutes', 5); |
| 25 |
|
| 26 |
if ($postsCount > $limitPer5Minutes) { |
| 27 |
throw new \Exception(esc_html__('You have reached the limit of posting. Please try after some time', 'fluent-community')); |
| 28 |
} |
| 29 |
} |
| 30 |
|
| 31 |
public function maybeLimitComment(User $user) |
| 32 |
{ |
| 33 |
// Check how many comments user has created in last 5 minutes |
| 34 |
$commentsCount = Comment::query()->withoutGlobalScopes()->where('user_id', $user->ID) |
| 35 |
->where('created_at', '>', gmdate('Y-m-d H:i:s', current_time('timestamp') - 60)) |
| 36 |
->count(); |
| 37 |
|
| 38 |
$limitPerMinute = apply_filters('fluent_community/rate_limit/comments_per_minute', 5); |
| 39 |
|
| 40 |
if ($commentsCount > $limitPerMinute) { |
| 41 |
throw new \Exception(esc_html__('You have reached the limit of commenting. Please try after some time', 'fluent-community')); |
| 42 |
} |
| 43 |
} |
| 44 |
} |
| 45 |
|