<?php
 namespace App\Services\EmailCampaign\Drivers; use App\Models\EmailCampaign; use App\Models\EmailCampaignLink; use App\Models\EmailCampaignRecipient; use App\Services\EmailCampaign\Contracts\EmailCampaignDriverInterface; abstract class AbstractEmailCampaignDriver implements EmailCampaignDriverInterface { protected function compileBody(EmailCampaign $campaign, ?EmailCampaignRecipient $recipient): string { $html = (string) ($campaign->content_html ?? ''); if ($html === '') { return ''; } $token = $recipient?->recipient_token ?? 'test'; $appUrl = rtrim((string) config('app.url'), '/'); $html = preg_replace_callback( '#<a([^>]*)href=(["\'])(.*?)\2#i', function ($m) use ($campaign, $token, $appUrl) { $url = $m[3]; if (! preg_match('#^https?://#i', $url)) { return $m[0]; } $linkHash = substr(md5($campaign->id.'|'.$url), 0, 16); EmailCampaignLink::firstOrCreate( ['campaign_id' => $campaign->id, 'link_hash' => $linkHash], ['url' => $url], ); $tracked = "$appUrl/email/campaign-track/click/$token/$linkHash"; return "<a{$m[1]}href={$m[2]}{$tracked}{$m[2]}"; }, $html ); $pixel = '<img src="'.$appUrl.'/email/campaign-track/open/'.$token.'.gif" width="1" height="1" alt="" style="display:none" />'; if (stripos($html, '</body>') !== false) { $html = preg_replace('#</body>#i', $pixel.'</body>', $html, 1); } else { $html .= $pixel; } return $html; } } 