This commit is contained in:
deploy-bot committed 2026-12-05 17:25:54 +00:00
commit c63e98e91e
297 files changed
+20546

No files matched your search

+130
View File
@@ -0,0 +1,130 @@
<?php
namespace IriksIT\Manager\Support\Leads;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Mail;
use IriksIT\Manager\Mail\LeadConfirmation;
use IriksIT\Manager\Mail\LeadReceived;
use IriksIT\Manager\Models\Lead;
use IriksIT\Manager\Modules\Statistics\VisitRecorder;
use IriksIT\Manager\Support\ModuleRegistry;
use Throwable;
/**
* Takes a request in: screens it, stores it, and tells the owner and the visitor. The only code that creates a `Lead` from a form.
* The forms themselves are the site's own (their fields, their words, their thank-you page); they validate, then call `take()`.
*
* A form never tells a sender that it was taken for spam: whatever the screening thinks, the visitor gets the normal thank-you.
*/
final class Intake
{
public function __construct(private readonly Screening $screening) {}
/**
* @param array<string, mixed> $attributes what the form gave, already validated: kind, name, phone, email, message, about, answers, ...
* @param int|null $seconds how long the form was open (see `secondsOpen()`)
*/
public function take(array $attributes, ?int $seconds, string $ip, string $userAgent = ''): Lead
{
$attributes['ip'] = $ip;
$message = $attributes['message'] ?? null;
$lead = Lead::create([
...$attributes,
...$this->screening->screen($attributes, $seconds),
'message_hash' => Lead::hashOf(is_string($message) ? $message : null),
// Where the visit came from: a site that counts its visits says so (`manager.leads.source`, an invokable class
// that gets the address and the browser and returns channel and source).
...$this->source($ip, $userAgent),
]);
// Only a real request is worth a mail: to the owner, and back to whoever sent it. A confirmation for junk would be mail
// to an address someone else made up.
if ($lead->folder === Lead::INBOX) {
$this->tellTheOwner($lead);
$this->confirm($lead);
}
return $lead;
}
/** Mails the owner. A mail that cannot be sent never loses the request: it is stored already. */
public function tellTheOwner(Lead $lead): void
{
$to = (string) config('manager.leads.notify');
if ($to === '') {
return;
}
try {
Mail::to($to)->send(new LeadReceived($lead));
$lead->update(['notified_at' => now(), 'notify_failed' => false]);
} catch (Throwable $e) {
report($e);
$lead->update(['notify_failed' => true]);
}
}
/** A signed moment for a form: sent back with it, it tells how long the form was open. */
public static function formToken(): string
{
return Crypt::encryptString((string) now()->timestamp);
}
/** How many seconds a form was open, or null when its token says nothing (missing, tampered with, too old). */
public static function secondsOpen(string $token): ?int
{
if ($token === '' || strlen($token) > 1000) {
return null;
}
try {
$seconds = now()->timestamp - (int) Crypt::decryptString($token);
} catch (DecryptException) {
return null;
}
return $seconds < 0 || $seconds > max(1, (int) config('manager.leads.max_hours', 24)) * 3600 ? null : $seconds;
}
private function confirm(Lead $lead): void
{
if (! config('manager.leads.confirm') || $lead->email === null || $lead->email === '') {
return;
}
try {
Mail::to($lead->email)->send(new LeadConfirmation($lead));
} catch (Throwable $e) {
report($e);
}
}
/**
* Where the visit came from. A site that counts its visits with the statistics module gets it for free; another source is
* `manager.leads.source`, an invokable class that gets the address and the browser and returns `channel` and `source`.
*
* @return array<string, mixed>
*/
private function source(string $ip, string $userAgent): array
{
$class = config('manager.leads.source');
try {
if (is_string($class) && class_exists($class)) {
$found = (array) app($class)($ip, $userAgent);
} elseif (app(ModuleRegistry::class)->enabled('statistics')) {
$found = app(VisitRecorder::class)->sourceOf($ip, $userAgent);
} else {
return [];
}
return array_intersect_key($found, ['channel' => 1, 'source' => 1]);
} catch (Throwable) {
return [];
}
}
}
+47
View File
@@ -0,0 +1,47 @@
<?php
namespace IriksIT\Manager\Support\Leads;
/**
* A phone number as people write it ("06 12 34 56 78", "+31 6 12345678") turned into digits with the country code. A number that
* starts with a single 0 is taken to be of the home country (`manager.leads.country_code`, 31 unless the site says otherwise).
*/
final class Phone
{
/** "31612345678", or null for anything that is no phone number. */
public static function international(string $number): ?string
{
$number = trim($number);
if ($number === '' || preg_match('/^[\d\s().+\-\/]+$/', $number) !== 1) {
return null;
}
// "+31 (0)6 12345678": the zero between brackets is not dialled after a country code.
$number = str_starts_with($number, '+') || str_starts_with($number, '00') ? str_replace('(0)', '', $number) : $number;
$digits = preg_replace('/\D+/', '', $number) ?? '';
if (str_starts_with($number, '+')) {
// already has its country code
} elseif (str_starts_with($digits, '00')) {
$digits = substr($digits, 2);
} elseif (str_starts_with($digits, '0')) {
$digits = self::country().substr($digits, 1);
}
return strlen($digits) >= 9 && strlen($digits) <= 15 ? $digits : null;
}
/** Whether the number is of the home country. */
public static function isHome(string $number): bool
{
$digits = self::international($number);
return $digits !== null && str_starts_with($digits, self::country());
}
private static function country(): string
{
return preg_replace('/\D+/', '', (string) config('manager.leads.country_code', '31')) ?: '31';
}
}
+83
View File
@@ -0,0 +1,83 @@
<?php
namespace IriksIT\Manager\Support\Leads;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use IriksIT\Manager\Models\Lead;
use IriksIT\Manager\Models\LeadTap;
use IriksIT\Manager\Support\Names;
/**
* What the forms and the contact buttons brought in over a number of days: how many requests, through which way in, from which page and
* which source, how many became a job, and how much the screening kept away. For whoever manages the requests. Counted in PHP from a
* handful of columns, so it reads the same on SQLite and MySQL.
*/
final class Report
{
/** One tap on a contact button, counted for a page: a counter and nothing else. */
public static function tap(string $kind, string $path): void
{
if (! in_array($kind, [LeadTap::CALL, LeadTap::WHATSAPP], true)) {
return;
}
$table = Names::table('lead_taps');
// One statement, so two taps at the same moment both count.
DB::table($table)->upsert([['day' => now()->toDateString(), 'kind' => $kind, 'path' => mb_substr($path, 0, 255), 'taps' => 1]], ['day', 'kind', 'path'], ['taps' => DB::raw($table.'.taps + 1')]);
}
/** @return array<string, mixed> */
public function over(int $days): array
{
$since = now()->subDays($days - 1)->startOfDay();
/** @var Collection<int, Lead> $leads */
$leads = Lead::query()->where('created_at', '>=', $since)->get(['id', 'kind', 'folder', 'page', 'channel', 'source', 'subject', 'outcome', 'handled_at']);
$real = $leads->where('folder', Lead::INBOX);
$taps = LeadTap::query()->where('day', '>=', $since->toDateString())->get(['kind', 'path', 'taps']);
$ways = [
['name' => __('Calls (taps on the number)'), 'count' => self::total($taps->where('kind', LeadTap::CALL))],
['name' => __('WhatsApp (taps on the button)'), 'count' => self::total($taps->where('kind', LeadTap::WHATSAPP))],
];
foreach ((array) config('manager.leads.kinds', []) as $kind => $label) {
$ways[] = ['name' => __((string) $label), 'count' => $real->where('kind', $kind)->count()];
}
return [
'days' => $days,
'requests' => $real->count(),
'kept_away' => ['other' => $leads->where('folder', Lead::OTHER)->count(), 'spam' => $leads->where('folder', Lead::SPAM)->count()],
'won' => $real->where('outcome', Lead::WON)->count(),
'lost' => $real->where('outcome', Lead::LOST)->count(),
'waiting' => $real->whereNull('handled_at')->count(),
'ways' => $ways,
'pages' => self::top($real->groupBy(fn (Lead $lead) => $lead->page ?? '(unknown)')),
'sources' => self::top($real->groupBy(fn (Lead $lead) => trim(($lead->channel ?? 'unknown').($lead->source ? ': '.$lead->source : '')))),
'subjects' => self::top($real->groupBy(fn (Lead $lead) => $lead->subject ?: '(none)')),
'tap_pages' => $taps->groupBy('path')->map(fn (Collection $rows, string $path) => ['name' => $path, 'count' => self::total($rows)])->sortByDesc('count')->take(8)->values()->all(),
];
}
/** @param Collection<int, LeadTap> $taps */
private static function total(Collection $taps): int
{
return $taps->reduce(fn (int $sum, LeadTap $tap) => $sum + $tap->taps, 0);
}
/**
* The largest groups, with how many of each became a job.
*
* @param Collection<array-key, Collection<int, Lead>> $groups
* @return list<array{name: string, count: int, won: int}>
*/
private static function top(Collection $groups): array
{
return array_values($groups->map(fn (Collection $leads, int|string $name) => [
'name' => (string) $name, 'count' => $leads->count(), 'won' => $leads->where('outcome', Lead::WON)->count(),
])->sortByDesc('count')->take(8)->values()->all());
}
}
+167
View File
@@ -0,0 +1,167 @@
<?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')) : [];
}
}