Files
laravel-manager-packagist/src/Support/Leads/Screening.php
T
2026-12-05 19:00:02 +00:00

168 lines
6.9 KiB
PHP

<?php
namespace IriksIT\Manager\Support\Leads;
use IriksIT\Manager\Models\Lead;
use IriksIT\Manager\Models\LeadBlock;
/**
* Decides in which folder a request lands: the inbox (a real request), "other" (acquisition and what the visitor called something
* else) or spam. The only code that decides a folder. Nothing is refused here: a sender always gets the normal thank-you, and the
* worst that happens to a real customer with an odd message is the folder "other". The reasons are kept with the request, so a wrong
* call can be seen and undone. All rules and thresholds are in `manager.leads`.
*/
final class Screening
{
/**
* @param array<string, mixed> $lead the attributes of the request
* @param int|null $seconds how long the form was open; null when that could not be told
* @return array{folder: string, reasons: list<string>}
*/
public function screen(array $lead, ?int $seconds): array
{
$message = self::text($lead['message'] ?? null);
$email = mb_strtolower(self::text($lead['email'] ?? null));
$phone = self::text($lead['phone'] ?? null);
$ip = self::text($lead['ip'] ?? null);
if (($block = $this->blocked($email, $phone, $ip)) !== null) {
return ['folder' => Lead::SPAM, 'reasons' => [$block]];
}
$spam = 0;
$other = 0;
$reasons = [];
$links = preg_match_all('#https?://|www\.|\b[a-z0-9-]+\.(?:com|net|org|info|biz|ru|cn|xyz|top|online|site)\b#i', $message);
if ($links > 0) {
$spam += $links > 1 ? 5 : 3;
$reasons[] = $links > 1 ? 'Several links in the text' : 'A link in the text';
}
$words = $this->acquisitionWords($message);
if ($words !== []) {
$other += min(6, 2 * count($words));
$reasons[] = 'Words of selling to a business: '.implode(', ', array_slice($words, 0, 5));
}
if ($message !== '' && ! $this->inExpectedLanguage($message)) {
$spam += 3;
$reasons[] = 'The text is not in the expected language';
}
if ($seconds === null) {
$spam += 2;
$reasons[] = 'The form could not tell how long it was open';
} elseif ($seconds < self::number('min_seconds')) {
$spam += 4;
$reasons[] = "Sent within {$seconds} seconds of opening the form";
}
if ($email !== '' && in_array(substr((string) strrchr($email, '@'), 1), self::list('throwaway_domains'), true)) {
$spam += 4;
$reasons[] = 'A throwaway mail address';
}
$hash = Lead::hashOf($message);
if ($hash !== null && Lead::query()->where('message_hash', $hash)->exists()) {
$spam += 4;
$reasons[] = 'The same text was sent before';
}
// Worth knowing, but no reason to put a request aside: it may be a holiday home.
if ($phone !== '' && ! Phone::isHome($phone)) {
$reasons[] = 'Note: the phone number is not of this country';
}
$chosenOther = ($lead['about'] ?? 'job') === 'other';
$folder = match (true) {
$spam >= self::number('spam_from') => Lead::SPAM,
$chosenOther, $other >= self::number('other_from') => Lead::OTHER,
default => Lead::INBOX,
};
if ($chosenOther) {
array_unshift($reasons, 'The visitor chose "something else"');
}
return ['folder' => $folder, 'reasons' => $reasons];
}
/** Why this sender is kept out, or null when they are not. */
private function blocked(string $email, string $phone, string $ip): ?string
{
$domain = $email !== '' ? substr((string) strrchr($email, '@'), 1) : '';
$digits = $phone !== '' ? Phone::international($phone) : null;
$block = LeadBlock::query()
->where(fn ($query) => $query->whereNull('expires_at')->orWhere('expires_at', '>', now()))
->where(function ($query) use ($email, $domain, $digits, $ip) {
$query->whereRaw('1 = 0');
foreach ([[LeadBlock::EMAIL, $email], [LeadBlock::DOMAIN, $domain], [LeadBlock::PHONE, (string) $digits], [LeadBlock::IP, $ip]] as [$type, $value]) {
if ($value !== '') {
$query->orWhere(fn ($q) => $q->where('type', $type)->where('value', $value));
}
}
})->first();
return $block instanceof LeadBlock ? 'This sender is blocked ('.$block->type.')' : null;
}
/** @return list<string> the words of the list that are in the text, as whole words */
private function acquisitionWords(string $message): array
{
$text = ' '.preg_replace('/[^\p{L}\p{N}]+/u', ' ', mb_strtolower($message)).' ';
return array_values(array_filter(self::list('acquisition_words'), fn (string $word) => str_contains($text, ' '.$word.' ')));
}
/**
* Whether a text is in the language the site expects (`manager.leads.language`: `nl`, `en` or null for no check): it has no
* other alphabet, and of the small words every sentence has the expected language is not outnumbered by the other one.
* A text too short to tell counts as fine.
*/
private function inExpectedLanguage(string $message): bool
{
$language = config('manager.leads.language');
if (! in_array($language, ['nl', 'en'], true)) {
return true;
}
if (preg_match('/[\p{Cyrillic}\p{Han}\p{Arabic}\p{Hebrew}\p{Thai}\p{Hangul}\p{Hiragana}\p{Katakana}]/u', $message) === 1) {
return false;
}
$words = preg_split('/[^\p{L}]+/u', mb_strtolower($message), -1, PREG_SPLIT_NO_EMPTY) ?: [];
if (count($words) < 6) {
return true;
}
$dutch = count(array_intersect($words, ['de', 'het', 'een', 'en', 'ik', 'wij', 'we', 'van', 'voor', 'met', 'niet', 'is', 'zijn', 'op', 'dat', 'die', 'graag', 'ook', 'bij', 'naar', 'om', 'te', 'er', 'aan', 'mijn', 'onze', 'u', 'je', 'kan', 'kunt', 'wil', 'hebben', 'heb', 'of', 'als', 'maar']));
$english = count(array_intersect($words, ['the', 'and', 'you', 'your', 'our', 'for', 'with', 'that', 'this', 'are', 'have', 'will', 'can', 'to', 'of', 'in', 'on', 'it', 'be', 'from', 'would', 'please', 'hello', 'hi', 'dear']));
return $language === 'nl' ? ($english === 0 || $dutch >= $english) : ($dutch === 0 || $english >= $dutch);
}
private static function text(mixed $value): string
{
return is_string($value) ? trim($value) : '';
}
private static function number(string $key): int
{
$value = config("manager.leads.{$key}");
return is_numeric($value) ? (int) $value : 0;
}
/** @return list<string> */
private static function list(string $key): array
{
$value = config("manager.leads.{$key}");
return is_array($value) ? array_values(array_filter($value, 'is_string')) : [];
}
}