| 1 |
<?php |
| 2 |
/** |
| 3 |
* The spam comment model class. |
| 4 |
* |
| 5 |
* @package WP_Defender\Model |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace WP_Defender\Model; |
| 9 |
|
| 10 |
/** |
| 11 |
* Class Spam_Comment |
| 12 |
* |
| 13 |
* Provides methods to retrieve spam comment IPs from WordPress database. |
| 14 |
*/ |
| 15 |
class Spam_Comment { |
| 16 |
/** |
| 17 |
* Retrieve aggregated spam comment IPs across all sites in a multisite setup or from a single site. |
| 18 |
* |
| 19 |
* @return array Associative array of IP addresses as keys and their spam comment count as values. |
| 20 |
*/ |
| 21 |
public static function get_spam_comments_ip(): array { |
| 22 |
global $wpdb; |
| 23 |
|
| 24 |
$spam_ips = array(); |
| 25 |
|
| 26 |
if ( is_multisite() ) { |
| 27 |
$offset = 0; |
| 28 |
$limit = 100; |
| 29 |
$mu_spam_ips = array(); |
| 30 |
while ( $blogs = $wpdb->get_results( "SELECT blog_id FROM {$wpdb->blogs} LIMIT {$offset}, {$limit}", ARRAY_A ) ) { // phpcs:ignore |
| 31 |
if ( ! empty( $blogs ) && is_array( $blogs ) ) { |
| 32 |
foreach ( $blogs as $blog ) { |
| 33 |
switch_to_blog( $blog['blog_id'] ); |
| 34 |
|
| 35 |
$mu_spam_ips = self::fetch_manual_spam_comments_ip(); |
| 36 |
|
| 37 |
if ( ! empty( $mu_spam_ips ) && is_array( $mu_spam_ips ) ) { |
| 38 |
foreach ( $mu_spam_ips as $ip => $count ) { |
| 39 |
$spam_ips[ $ip ] = isset( $spam_ips[ $ip ] ) |
| 40 |
? $spam_ips[ $ip ] + $count |
| 41 |
: $count; |
| 42 |
} |
| 43 |
} |
| 44 |
|
| 45 |
restore_current_blog(); |
| 46 |
} |
| 47 |
} |
| 48 |
$offset += $limit; |
| 49 |
} |
| 50 |
} else { |
| 51 |
$spam_ips = self::fetch_manual_spam_comments_ip(); |
| 52 |
} |
| 53 |
|
| 54 |
return is_array( $spam_ips ) ? $spam_ips : array(); |
| 55 |
} |
| 56 |
|
| 57 |
/** |
| 58 |
* Fetches spam comment IPs and their counts from the current WordPress site which are flagged by moderator. |
| 59 |
* |
| 60 |
* @return array Associative array of IP addresses as keys and their spam comment count as values. |
| 61 |
*/ |
| 62 |
private static function fetch_manual_spam_comments_ip(): array { |
| 63 |
global $wpdb; |
| 64 |
|
| 65 |
$sql = "SELECT c.comment_author_IP as ip, COUNT(*) as count |
| 66 |
FROM {$wpdb->comments} c |
| 67 |
JOIN {$wpdb->commentmeta} cm ON c.comment_ID = cm.comment_id |
| 68 |
WHERE c.comment_approved = 'spam' |
| 69 |
AND c.comment_author_IP IS NOT NULL AND c.comment_author_IP != '' |
| 70 |
AND cm.meta_key = '_wp_trash_meta_time' |
| 71 |
AND cm.meta_value >= UNIX_TIMESTAMP(NOW() - INTERVAL 12 HOUR) |
| 72 |
GROUP BY c.comment_author_IP |
| 73 |
ORDER BY count DESC"; |
| 74 |
|
| 75 |
$results = $wpdb->get_results( $sql, ARRAY_A ); // phpcs:ignore |
| 76 |
|
| 77 |
$spam_ips = array(); |
| 78 |
if ( is_array( $results ) && ! empty( $results ) ) { |
| 79 |
foreach ( $results as $row ) { |
| 80 |
$spam_ips[ $row['ip'] ] = (int) $row['count']; |
| 81 |
} |
| 82 |
} |
| 83 |
|
| 84 |
return $spam_ips; |
| 85 |
} |
| 86 |
} |
| 87 |
|