PluginProbe
Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder / 3.2.1
Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder v3.2.1
V-3.3.0 3.2.2 3.2.1 3.2.0 3.1.4 3.1.3 3.1.2 3.1.1 3.1.0 V3.0.3 V3.0.2 -3.0.1 V_3.0.0 1.1.1 1.1.8 1.2 1.3 1.4 1.4.18 1.5.2 1.9 2.0 2.10.0 2.10.1 2.10.2 All 137 releases
bit-form / includes / Core / Util / MailNotifier.php

MailNotifier.php in Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder 3.2.1, at includes/Core/Util/MailNotifier.php

343 lines 14.7 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace BitCode\BitForm\Core\Util;
4
5 if (!defined('ABSPATH')) {
6 exit;
7 }
8
9 use BitCode\BitForm\Admin\Form\Helpers;
10 use BitCode\BitForm\Core\Database\FormEntryMetaModel;
11 use BitCode\BitForm\Core\Form\FormManager;
12 use BitCode\BitForm\Core\Messages\EmailTemplateHandler;
13
14 final class MailNotifier
15 {
16 public static function notify($notifyDetails, $formID, $fieldValue, $entryID, $isDblOptin = false, $logId = '')
17 {
18 $apiResponse = new ApiResponse();
19 $formManager = FormManager::getInstance($formID);
20 $entryDetails = ['formId' => $formID, 'entryId' => $entryID, 'fieldValues' => $fieldValue];
21 $emailTemplateHandler = new EmailTemplateHandler($formID);
22 $attachments = [];
23 $tempPdfLinks = [];
24 if (is_string($notifyDetails->id)) {
25 $mailTemplateID = Utilities::jsonObj($notifyDetails->id)->id ?? null;
26 $mailTemplate = $emailTemplateHandler->getATemplate($mailTemplateID);
27 if (!is_wp_error($mailTemplate)) {
28 // Honor template enable/disable: a disabled email template is never sent.
29 if (isset($mailTemplate[0]->status) && empty($mailTemplate[0]->status)) {
30 return;
31 }
32 $mailTo = FieldValueHandler::validateMailArry($notifyDetails->to, $fieldValue);
33 // Conditional email routing (Pro): add recipients resolved from value-based rules in the template config.
34 $mailTo = apply_filters('bitform_email_conditional_routing', $mailTo, $mailTemplate[0], $fieldValue, $formID);
35 if (!empty($mailTo)) {
36 $from_name = '';
37 if (isset($notifyDetails->from_name) && !empty($notifyDetails->from_name)) {
38 $from_name = $notifyDetails->from_name;
39 }
40 $mailHeaders = [
41 // 'Content-Type: text/html; charset=UTF-8',
42 // $embeddedMailHeader
43 ];
44 $from_mail = '';
45 if (!empty($notifyDetails->from)) {
46 $fromMail = FieldValueHandler::validateMailArry($notifyDetails->from, $fieldValue);
47 $headerFromName = !empty($notifyDetails->from_name) ? $notifyDetails->from_name : explode('@', $fromMail[0])[0];
48 $mailHeaders[] = "FROM: $headerFromName " . '<' . sanitize_email($fromMail[0]) . '>';
49 $from_mail = $fromMail[0];
50 }
51 (new MailConfig())->sendMail(['from_name' => $from_name, 'from_email' => $from_mail]);
52 $mailSubject = FieldValueHandler::replaceFieldWithValue($mailTemplate[0]->sub, $fieldValue, $formID);
53
54 // allow developers to modify email subject
55 $mailSubject = apply_filters(
56 'bitform_filter_email_subject',
57 $mailSubject,
58 [
59 'form_id' => $formID,
60 'entry_id' => $entryID,
61 'field_values' => $fieldValue,
62 'template' => $mailTemplate[0] ?? null,
63 'is_double_optin' => (bool) $isDblOptin,
64 ]
65 );
66
67 $mailBody = $mailTemplate[0]->body;
68 if (class_exists('\BitCode\BitFormPro\Admin\DownloadFile')) {
69 $downloadFile = new \BitCode\BitFormPro\Admin\DownloadFile();
70 $mailBody = $downloadFile->replacePdfShortCodeToLink($mailBody, $formID, $entryID);
71 $mailBody = $downloadFile->replaceShortCodeToPdfPassword($mailBody, $formID, $entryID);
72 }
73
74 $mailBody = FieldValueHandler::replaceFieldWithValue($mailBody, $fieldValue, $formID);
75 // Signature images: embed inline (cid:) so they render for non-logged-in recipients.
76 // Must run before changeImagePathInHTMLString so the src is still the raw filename.
77 $cidMap = [];
78 $sigBasePath = FileHandler::getEntriesFileUploadDir($formID, $entryID) . DIRECTORY_SEPARATOR;
79 $mailBody = self::embedSignatureImages($mailBody, $formManager, $fieldValue, $sigBasePath, $cidMap);
80 $webUrl = Helpers::getWebPathWithEncryptedEntryId($formID, $entryID);
81 $mailBody = FieldValueHandler::changeImagePathInHTMLString($mailBody, $webUrl);
82 $mailBody = FieldValueHandler::changeHrefPathInHTMLString($mailBody, $webUrl); // replace anchor tag href with constructed weburl
83
84 // allow developers to modify email body
85 $mailBody = apply_filters(
86 'bitform_filter_email_body',
87 $mailBody,
88 [
89 'form_id' => $formID,
90 'entry_id' => $entryID,
91 'field_values' => $fieldValue,
92 'template' => $mailTemplate[0] ?? null,
93 'is_double_optin' => (bool) $isDblOptin,
94 ]
95 );
96 if (!empty($notifyDetails->replyto)) {
97 $mailReplyTo = FieldValueHandler::validateMailArry($notifyDetails->replyto, $fieldValue);
98 if (is_array($mailReplyTo)) {
99 foreach ($mailReplyTo as $key => $emailAddress) {
100 $mailHeaders[] = 'Reply-To: ' . explode('@', $emailAddress)[0] . '<' . sanitize_email($emailAddress) . '>';
101 }
102 } else {
103 $mailHeaders[] = 'Reply-To: ' . explode('@', $mailReplyTo)[0] . '<' . sanitize_email($mailReplyTo) . '>';
104 }
105 }
106 $oldMailBody = $mailBody;
107 $data = [];
108 if ($isDblOptin && true === has_filter('bitform_email_body_text')) {
109 $urlParams = $formID . '_' . $entryID . '_' . $logId;
110 $data = apply_filters('bitform_email_body_text', $mailBody, $urlParams);
111 $mailBody = $data['mailbody'];
112 }
113
114 if (!empty($notifyDetails->bcc)) {
115 $mailBCC = FieldValueHandler::validateMailArry($notifyDetails->bcc, $fieldValue);
116 if (is_array($mailBCC)) {
117 foreach ($mailBCC as $key => $emailAddress) {
118 $mailHeaders[] = 'Bcc: ' . sanitize_email($emailAddress);
119 }
120 } else {
121 $mailHeaders[] = 'Bcc: ' . sanitize_email($mailBCC);
122 }
123 }
124 if (!empty($notifyDetails->cc)) {
125 $mailCC = FieldValueHandler::validateMailArry($notifyDetails->cc, $fieldValue);
126 if (is_array($mailCC)) {
127 foreach ($mailCC as $key => $emailAddress) {
128 $mailHeaders[] = 'Cc: ' . sanitize_email($emailAddress);
129 }
130 } else {
131 $mailHeaders[] = 'Cc: ' . sanitize_email($mailCC);
132 }
133 }
134 // PDF generation is a Pro feature; Pro hooks this filter and returns the generated
135 // file path(s) — an array (one per configured template), or a single path string
136 // from Pro versions that predate multi-PDF. Generated here (not before the
137 // template/recipient checks) so disabled templates and empty recipients never
138 // generate PDFs — and never leak temp files.
139 $tempPdfLinks = apply_filters('bitform_generate_pdf_attachment', [], $notifyDetails, $entryDetails, $logId);
140 $tempPdfLinks = is_array($tempPdfLinks) ? $tempPdfLinks : [$tempPdfLinks];
141 $tempPdfLinks = array_values(array_unique(array_filter($tempPdfLinks, static function ($pdfPath) {
142 return !empty($pdfPath) && is_string($pdfPath) && file_exists($pdfPath);
143 })));
144 $attachments = array_merge($attachments, $tempPdfLinks);
145 if (!empty($notifyDetails->attachment)) {
146 $fileFldKeys = $notifyDetails->attachment;
147 $fileBasePath = FileHandler::getEntriesFileUploadDir($formID, $entryID) . DIRECTORY_SEPARATOR;
148
149 // Normalize to array for consistent processing
150 $fileFldKeys = is_array($fileFldKeys) ? $fileFldKeys : [$fileFldKeys];
151
152 foreach ($fileFldKeys as $fldKey) {
153 $repeaterFieldKey = $formManager->isRepeatedField($fldKey);
154
155 if ($repeaterFieldKey) {
156 // Handle repeated file field
157 FileHandler::processRepeaterAttachment(
158 $repeaterFieldKey,
159 $fldKey,
160 $fieldValue,
161 $fileBasePath,
162 $attachments
163 );
164 } else {
165 // Handle regular file field
166 FileHandler::processRegularAttachment(
167 $fldKey,
168 $fieldValue,
169 $fileBasePath,
170 $attachments
171 );
172 }
173 }
174 }
175 // WordPress Media Library attachments (stored as attachment IDs in the template config).
176 if (!empty($notifyDetails->mediaAttachment)) {
177 $mediaIds = is_array($notifyDetails->mediaAttachment) ? $notifyDetails->mediaAttachment : [$notifyDetails->mediaAttachment];
178 foreach ($mediaIds as $mediaId) {
179 $mediaPath = get_attached_file(absint($mediaId));
180 if ($mediaPath && file_exists($mediaPath)) {
181 $attachments[] = $mediaPath;
182 }
183 }
184 }
185 $mailBody = stripcslashes($mailBody);
186 $mailSubject = stripcslashes($mailSubject);
187 $embedCb = static function ($phpmailer) use ($cidMap) {
188 foreach ($cidMap as $cid => $info) {
189 try {
190 $phpmailer->addEmbeddedImage($info['path'], $cid, $info['name']);
191 } catch (\Throwable $e) {
192 Log::debug_log("[Signature Embed] failed for {$info['path']} - " . $e->getMessage());
193 }
194 }
195 };
196 if (!empty($cidMap)) {
197 add_action('phpmailer_init', $embedCb);
198 }
199 add_filter('wp_mail_content_type', [self::class, 'filterMailContentType']);
200 $fromNameCb = null;
201 if (!empty($from_name)) {
202 $fromNameCb = static function () use ($from_name) {
203 return $from_name;
204 };
205 add_filter('wp_mail_from_name', $fromNameCb);
206 }
207 $status = wp_mail($mailTo, $mailSubject, $mailBody, $mailHeaders, $attachments);
208
209 if (!$status) {
210 Log::debug_log([
211 'status' => 'error',
212 'code' => 'mail_not_sent',
213 'message' => 'Mail not sent',
214 'inputDetails' => [
215 'to' => $mailTo,
216 'subject' => $mailSubject,
217 'body' => $mailBody,
218 'headers' => $mailHeaders,
219 'attachments' => $attachments,
220 'notifyDetails' => $notifyDetails,
221 'formID' => $formID,
222 'entryID' => $entryID,
223 'isDblOptin' => $isDblOptin,
224 'logId' => $logId
225 ],
226 'responseDetails' => $status
227 ]);
228 $apiResponse->apiResponse($logId, '', ['type' => 'record', 'type_name' => 'smtp'], 'errors', 'Mail dose not send successfully', $entryDetails);
229 } else {
230 Log::debug_log([
231 'status' => 'success',
232 'code' => 'mail_sent',
233 'message' => 'Mail successfully sent',
234 'inputDetails' => [
235 'to' => $mailTo,
236 'subject' => $mailSubject,
237 'body' => $mailBody,
238 'headers' => $mailHeaders,
239 'attachments' => $attachments,
240 'notifyDetails' => $notifyDetails,
241 'formID' => $formID,
242 'entryID' => $entryID,
243 'isDblOptin' => $isDblOptin,
244 'logId' => $logId
245 ],
246 'responseDetails' => $status
247 ]);
248 $apiResponse->apiResponse($logId, '', ['type' => 'record', 'type_name' => 'smtp'], 'success', 'Mail successfully send.', $entryDetails);
249 }
250 if ($status && $isDblOptin && false !== strpos($oldMailBody, 'entry_confirmation_url')) {
251 $entryMeta = new FormEntryMetaModel();
252 $apiResponse->apiResponse($logId, '', ['type' => 'record', 'type_name' => 'smtp'], 'success', 'Mail successfully send.', $entryDetails);
253 // Form entry meta insert; meta_key/meta_value required to store dynamic field data per entry.
254 $entryMeta->insert(
255 [
256 'bitforms_form_entry_id' => $entryID,
257 'meta_key' => 'entry_confirm_activation',
258 'meta_value' => $data['token']
259 ]
260 );
261 }
262 remove_filter('wp_mail_content_type', [self::class, 'filterMailContentType']);
263 if (null !== $fromNameCb) {
264 remove_filter('wp_mail_from_name', $fromNameCb);
265 }
266 if (!empty($cidMap)) {
267 remove_action('phpmailer_init', $embedCb);
268 }
269 }
270 }
271 }
272
273 foreach ($tempPdfLinks as $tempPdfLink) {
274 wp_delete_file($tempPdfLink);
275 }
276 }
277
278 public static function filterMailContentType()
279 {
280 return 'text/html; charset=UTF-8';
281 }
282
283 /**
284 * Rewrite signature <img> tags to inline cid: references and collect the files
285 * to embed. Only signature-field images that are local & readable are embedded;
286 * external URLs and non-signature images are left untouched. When the form has
287 * no signature (or none is in the body) $cidMap stays empty and nothing changes.
288 */
289 private static function embedSignatureImages($html, $formManager, $fieldValue, $baseDir, &$cidMap)
290 {
291 if (empty($html)) {
292 return $html;
293 }
294
295 // Collect signature filenames for this entry.
296 $sigFiles = [];
297 foreach ($formManager->getFields() as $key => $detail) {
298 if (!isset($detail['type']) || 'signature' !== $detail['type']) {
299 continue;
300 }
301 $val = isset($fieldValue[$key]) ? $fieldValue[$key] : '';
302 foreach ((array) $val as $fn) {
303 $fn = is_string($fn) ? trim($fn) : '';
304 if ('' !== $fn && 'signature-failed.png' !== $fn) {
305 $sigFiles[basename($fn)] = true;
306 }
307 }
308 }
309 if (empty($sigFiles)) {
310 return $html;
311 }
312
313 return preg_replace_callback(
314 '/<img\s+[^>]*src=[\'"]([^\'"]+)[\'"][^>]*>/i',
315 function ($m) use ($baseDir, $sigFiles, &$cidMap) {
316 $src = $m[1];
317 if (filter_var($src, FILTER_VALIDATE_URL)) {
318 return $m[0]; // external URL, leave as-is
319 }
320 $name = basename($src);
321 if (!isset($sigFiles[$name])) {
322 return $m[0]; // not a signature image
323 }
324 $file = $baseDir . $name;
325 if (!is_readable($file)) {
326 return $m[0];
327 }
328 $cid = 'bfsig_' . md5($file);
329 $cidMap[$cid] = ['path' => $file, 'name' => $name];
330
331 // Replace only the src attribute value (leave alt untouched).
332 return preg_replace(
333 '/(src=[\'"])' . preg_quote($src, '/') . '([\'"])/i',
334 '${1}cid:' . $cid . '${2}',
335 $m[0],
336 1
337 );
338 },
339 $html
340 );
341 }
342 }
343