PluginProbe
Fluent Forms – Customizable Contact Forms, Survey, Quiz, & Conversational Form Builder / 4.3.21
Fluent Forms – Customizable Contact Forms, Survey, Quiz, & Conversational Form Builder v4.3.21
6.2.13 6.2.12 6.2.10 6.2.11 6.2.9 6.2.8 6.2.7 6.2.6 6.2.5 6.2.4 6.2.3 6.2.2 3.6.22 3.6.31 3.6.40 3.6.41 3.6.42 3.6.50 3.6.51 3.6.60 3.6.61 3.6.62 3.6.64 3.6.65 3.6.66 All 195 releases
fluentform / app / Modules / Entries / Entries.php

Entries.php in Fluent Forms – Customizable Contact Forms, Survey, Quiz, & Conversational Form Builder 4.3.21, at app/Modules/Entries/Entries.php

916 lines 30.2 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace FluentForm\App\Modules\Entries;
4
5 use FluentForm\App\Helpers\Helper;
6 use FluentForm\App\Modules\Form\FormDataParser;
7 use FluentForm\App\Modules\Form\FormFieldsParser;
8 use FluentForm\App\Modules\Registerer\TranslationString;
9 use FluentForm\Framework\Helpers\ArrayHelper;
10 use FluentForm\View;
11
12 class Entries extends EntryQuery
13 {
14 /**
15 * The form response model.
16 *
17 * @var \WpFluent\QueryBuilder\QueryBuilderHandler $responseMetaModel
18 */
19 protected $responseMetaModel;
20
21 /**
22 * Entries constructor.
23 *
24 * @throws \Exception
25 */
26 public function __construct()
27 {
28 parent::__construct();
29
30 $this->responseMetaModel = wpFluent()->table('fluentform_submission_meta');
31 }
32
33 public function getAllFormEntries()
34 {
35 $formId = intval($this->request->get('form_id'));
36
37 $limit = $this->request->get('per_page', 10);
38 $page = $this->request->get('page', 1);
39 $offset = ($page - 1) * $limit;
40
41 $search = $this->request->get('search');
42 $status = $this->request->get('entry_status');
43
44 $query = wpFluent()->table('fluentform_submissions')
45 ->select([
46 'fluentform_submissions.id',
47 'fluentform_submissions.form_id',
48 'fluentform_submissions.status',
49 'fluentform_submissions.created_at',
50 'fluentform_submissions.browser',
51 'fluentform_submissions.currency',
52 'fluentform_submissions.total_paid',
53 'fluentform_forms.title',
54 ])
55 ->join('fluentform_forms', 'fluentform_forms.id', '=', 'fluentform_submissions.form_id')
56 ->orderBy('fluentform_submissions.id', 'DESC')
57 ->limit($limit)
58 ->offset($offset);
59
60 if ($formId) {
61 $query->where('fluentform_submissions.form_id', $formId);
62 }
63
64 if ($status) {
65 $query->where('fluentform_submissions.status', $status);
66 } else {
67 $query->where('fluentform_submissions.status', '!=', 'trashed');
68 }
69
70 $dateRange = $this->request->get('date_range');
71 if ($dateRange) {
72 $query->where('fluentform_submissions.created_at', '>=', $dateRange[0] . ' 00:00:01');
73 $query->where('fluentform_submissions.created_at', '<=', $dateRange[1] . ' 23:59:59');
74 }
75
76 if ($search) {
77 $query->where('fluentform_submissions.response', 'LIKE', '%' . $search . '%');
78 $query->orWhere('fluentform_forms.title', 'LIKE', '%' . $search . '%');
79 $query->orWhere('fluentform_submissions.id', 'LIKE', '%' . $search . '%');
80 }
81
82 $total = $query->count();
83 $entries = $query->get();
84 foreach ($entries as $entry) {
85 $entry->entry_url = admin_url('admin.php?page=fluent_forms&route=entries&form_id=' . $entry->form_id . '#/entries/' . $entry->id);
86 $entry->human_date = human_time_diff(strtotime($entry->created_at), strtotime(current_time('mysql')));
87 }
88 wp_send_json_success([
89 'entries' => $entries,
90 'total' => $total,
91 'last_page' => ceil($total / $limit),
92 'available_forms' => $this->getAvailableForms(),
93 ]);
94 }
95
96 public function getEntriesReport()
97 {
98 $from = date('Y-m-d H:i:s', strtotime('-30 days'));
99 $to = date('Y-m-d H:i:s', strtotime('+1 days'));
100
101 $ranges = $this->request->get('date_range', []);
102
103 if (!empty($ranges[0])) {
104 $from = $ranges[0];
105 }
106
107 if (!empty($ranges[1])) {
108 $time = strtotime($ranges[1]) + 24 * 60 * 60;
109 $to = date('Y-m-d H:i:s', $time);
110 }
111
112 $period = new \DatePeriod(new \DateTime($from), new \DateInterval('P1D'), new \DateTime($to));
113
114 $range = [];
115
116 foreach ($period as $date) {
117 $range[$date->format('Y-m-d')] = 0;
118 }
119
120 $itemsQuery = wpFluent()->table('fluentform_submissions')->select([
121 wpFluent()->raw('DATE(created_at) AS date'),
122 wpFluent()->raw('COUNT(id) AS count'),
123 ])
124 ->whereBetween('created_at', $from, $to)
125 ->groupBy('date')
126 ->orderBy('date', 'ASC');
127
128 $formId = $this->request->get('form_id');
129
130 if ($formId) {
131 $itemsQuery = $itemsQuery->where('form_id', $formId);
132 }
133
134 $items = $itemsQuery->get();
135 foreach ($items as $item) {
136 $range[$item->date] = $item->count; //Filling value in the array
137 }
138
139 wp_send_json_success([
140 'stats' => $range,
141 ]);
142 }
143
144 public function renderEntries($form_id)
145 {
146 wp_enqueue_script('fluentform_form_entries');
147
148 $forms = wpFluent()
149 ->table('fluentform_forms')
150 ->select(['id', 'title'])
151 ->orderBy('id', 'DESC')
152 ->get();
153
154 $emailNotifications = wpFluent()
155 ->table('fluentform_form_meta')
156 ->where('form_id', $form_id)
157 ->where('meta_key', 'notifications')
158 ->get();
159
160 $formattedNotification = [];
161
162 foreach ($emailNotifications as $notification) {
163 $value = \json_decode($notification->value, true);
164 $formattedNotification[] = [
165 'id' => $notification->id,
166 'name' => ArrayHelper::get($value, 'name'),
167 ];
168 }
169
170 $form = wpFluent()->table('fluentform_forms')->find($form_id);
171
172 $app = wpFluentForm();
173
174 $fluentFormEntriesVars = apply_filters('fluent_form_entries_vars', [
175 'all_forms_url' => admin_url('admin.php?page=fluent_forms'),
176 'forms' => $forms,
177 'form_id' => $form->id,
178 'enabled_auto_delete' => Helper::isEntryAutoDeleteEnabled($form_id),
179 'current_form_title' => $form->title,
180 'entry_statuses' => Helper::getEntryStatuses($form_id),
181 'entries_url_base' => admin_url('admin.php?page=fluent_forms&route=entries&form_id='),
182 'no_found_text' => __('Sorry! No entries found. All your entries will be shown here once you start getting form submissions', 'fluentform'),
183 'has_pro' => defined('FLUENTFORMPRO'),
184 'printStyles' => [fluentformMix('css/settings_global.css')],
185 'email_notifications' => $formattedNotification,
186 'available_countries' => $app->load(
187 $app->appPath('Services/FormBuilder/CountryNames.php')
188 ),
189 'upgrade_url' => fluentform_upgrade_url(),
190 'form_entries_str' => TranslationString::getEntriesI18n(),
191 ], $form);
192
193 wp_localize_script(
194 'fluentform_form_entries',
195 'fluent_form_entries_vars',
196 $fluentFormEntriesVars
197 );
198
199 View::render('admin.form.entries', [
200 'form_id' => $form_id,
201 'has_pdf' => defined('FLUENTFORM_PDF_VERSION') ? 'true' : 'false',
202 ]);
203 }
204
205 public function getEntriesGroup()
206 {
207 $formId = intval($this->request->get('form_id'));
208 $counts = $this->groupCount($formId);
209 wp_send_json_success([
210 'counts' => $counts,
211 ], 200);
212 }
213
214 public function _getEntries(
215 $formId,
216 $currentPage,
217 $perPage,
218 $sortBy,
219 $entryType,
220 $search,
221 $wheres = []
222 ) {
223 $this->formId = $formId;
224 $this->per_page = $perPage;
225 $this->sort_by = $sortBy;
226 $this->page_number = $currentPage;
227 $this->search = $search;
228 $this->wheres = $wheres;
229
230 if ('favorite' == $entryType) {
231 $this->is_favourite = true;
232 } elseif ('all' != $entryType && $entryType) {
233 $this->status = $entryType;
234 }
235
236 $dateRange = $this->request->get('date_range');
237 if ($dateRange) {
238 $this->startDate = $dateRange[0];
239 $this->endDate = $dateRange[1];
240 }
241
242 $form = $this->formModel->find($formId);
243 $formMeta = $this->getFormInputsAndLabels($form);
244 $formLabels = $formMeta['labels'];
245 $formLabels = apply_filters('fluentfoform_entry_lists_labels', $formLabels, $form);
246 $submissions = $this->getResponses();
247 $submissions['data'] = FormDataParser::parseFormEntries($submissions['data'], $form);
248
249 return compact('submissions', 'formLabels');
250 }
251
252 public function getEntries()
253 {
254 if (!defined('FLUENTFORM_RENDERING_ENTRIES')) {
255 define('FLUENTFORM_RENDERING_ENTRIES', true);
256 }
257
258 $wheres = [];
259
260 if ($paymentStatuses = $this->request->get('payment_statuses')) {
261 if (is_array($paymentStatuses)) {
262 $wheres[] = ['payment_status', $paymentStatuses];
263 }
264 }
265
266 $entries = $this->_getEntries(
267 intval($this->request->get('form_id')),
268 intval($this->request->get('current_page', 1)),
269 intval($this->request->get('per_page', 10)),
270 sanitize_text_field($this->request->get('sort_by', 'DESC')),
271 sanitize_text_field($this->request->get('entry_type', 'all')),
272 sanitize_text_field($this->request->get('search')),
273 $wheres
274 );
275
276 $labels = apply_filters(
277 'fluentform_all_entry_labels',
278 $entries['formLabels'],
279 $this->request->get('form_id')
280 );
281
282 $form = $this->formModel->find($this->request->get('form_id'));
283
284 if ($form->has_payment) {
285 $labels = apply_filters(
286 'fluentform_all_entry_labels_with_payment',
287 $entries['formLabels'],
288 false,
289 $form
290 );
291 }
292 $formId = $this->request->get('form_id');
293 $visible_columns = Helper::getFormMeta($formId, '_visible_columns', null);
294 $columns_order = Helper::getFormMeta($formId, '_columns_order', null);
295
296 wp_send_json_success([
297 'submissions' => apply_filters('fluentform_all_entries', $entries['submissions']),
298 'labels' => $labels,
299 'visible_columns' => $visible_columns,
300 'columns_order' => $columns_order,
301 ], 200);
302 }
303
304 public function _getEntry()
305 {
306 $this->formId = intval($this->request->get('form_id'));
307
308 $entryId = intval($this->request->get('entry_id'));
309
310 $entry_type = sanitize_key($this->request->get('entry_type', 'all'));
311
312 if ('favorite' === $entry_type) {
313 $this->is_favourite = true;
314 } elseif ('all' !== $entry_type) {
315 $this->status = $entry_type;
316 }
317
318 $this->sort_by = sanitize_text_field($this->request->get('sort_by', 'ASC'));
319
320 $this->search = sanitize_text_field($this->request->get('search'));
321
322 $submission = $this->getResponse($entryId);
323
324 if (!$submission) {
325 wp_send_json_error([
326 'message' => 'No Entry found.',
327 ], 422);
328 }
329
330 $form = $this->formModel->find($this->formId);
331
332 if ('unread' == $submission->status && apply_filters('fluentform_auto_read', true, $form)) {
333 wpFluent()->table('fluentform_submissions')
334 ->where('id', $entryId)
335 ->update([
336 'status' => 'read',
337 ]);
338
339 $submission->status = 'read';
340 }
341
342 $formMeta = $this->getFormInputsAndLabels($form);
343
344 $submission = FormDataParser::parseFormEntry($submission, $form, $formMeta['inputs'], true);
345
346 if ($submission->user_id) {
347 $user = get_user_by('ID', $submission->user_id);
348 $user_data = [
349 'name' => $user->display_name,
350 'email' => $user->user_email,
351 'ID' => $user->ID,
352 'permalink' => get_edit_user_link($user->ID),
353 ];
354 $submission->user = $user_data;
355 }
356
357 $submission = apply_filters('fluentform_single_response_data', $submission, $this->formId);
358
359 $fields = apply_filters(
360 'fluentform_single_response_input_fields',
361 $formMeta['inputs'],
362 $this->formId
363 );
364
365 $labels = apply_filters(
366 'fluentform_single_response_input_labels',
367 $formMeta['labels'],
368 $this->formId
369 );
370
371 $order_data = false;
372
373 if ($submission->payment_status || $submission->payment_total || 'subscription' === $submission->payment_type) {
374 $order_data = apply_filters(
375 'fluentform_submission_order_data',
376 false,
377 $submission,
378 $form
379 );
380
381 $labels = apply_filters(
382 'fluentform_submission_entry_labels_with_payment',
383 $labels,
384 $submission,
385 $form
386 );
387 }
388
389 $nextSubmissionId = $this->getNextResponse($entryId);
390
391 $previousSubmissionId = $this->getPrevResponse($entryId);
392
393 return [
394 'submission' => $submission,
395 'next' => $nextSubmissionId,
396 'prev' => $previousSubmissionId,
397 'labels' => $labels,
398 'fields' => $fields,
399 'order_data' => $order_data,
400 ];
401 }
402
403 public function getEntry()
404 {
405 if (!defined('FLUENTFORM_RENDERING_ENTRY')) {
406 define('FLUENTFORM_RENDERING_ENTRY', true);
407 }
408
409 $entryData = $this->_getEntry();
410
411 $entryData['widgets'] = apply_filters('fluentform_single_entry_widgets', [], $entryData);
412 $entryData['extraCards'] = apply_filters('fluentform_single_entry_cards', [], $entryData);
413
414 wp_send_json_success($entryData, 200);
415 }
416
417 /**
418 * @param $form
419 * @param array $with
420 *
421 * @return array
422 *
423 * @todo: Implement Caching mechanism so we don't have to parse these things for every request
424 */
425 public function getFormInputsAndLabels($form, $with = ['admin_label', 'raw'])
426 {
427 $formInputs = FormFieldsParser::getEntryInputs($form, $with);
428 $inputLabels = FormFieldsParser::getAdminLabels($form, $formInputs);
429 return [
430 'inputs' => $formInputs,
431 'labels' => $inputLabels,
432 ];
433 }
434
435 public function getNotes()
436 {
437 $formId = intval($this->request->get('form_id'));
438 $entry_id = intval($this->request->get('entry_id'));
439 $apiLog = 'yes' == sanitize_text_field($this->request->get('api_log'));
440
441 $metaKeys = ['_notes'];
442
443 if ($apiLog) {
444 $metaKeys[] = 'api_log';
445 }
446
447 $notes = $this->responseMetaModel
448 ->where('form_id', $formId)
449 ->where('response_id', $entry_id)
450 ->whereIn('meta_key', $metaKeys)
451 ->orderBy('id', 'DESC')
452 ->get();
453
454 foreach ($notes as $note) {
455 if ($note->user_id) {
456 $note->pemalink = get_edit_user_link($note->user_id);
457 $user = get_user_by('ID', $note->user_id);
458 if ($user) {
459 $note->created_by = $user->display_name;
460 } else {
461 $note->created_by = __('Fluent Forms Bot', 'fluentform');
462 }
463 } else {
464 $note->pemalink = false;
465 }
466 }
467
468 $notes = apply_filters('fluentform_entry_notes', $notes, $entry_id, $formId);
469
470 wp_send_json_success([
471 'notes' => $notes,
472 ], 200);
473 }
474
475 public function addNote()
476 {
477 $entryId = intval($this->request->get('entry_id'));
478 $formId = intval($this->request->get('form_id'));
479 $note = $this->request->get('note');
480 $note_content = sanitize_textarea_field($note['content']);
481 $note_status = sanitize_text_field($note['status']);
482 $user = get_user_by('ID', get_current_user_id());
483
484 $response_note = [
485 'response_id' => $entryId,
486 'form_id' => $formId,
487 'meta_key' => '_notes',
488 'value' => $note_content,
489 'status' => $note_status,
490 'user_id' => $user->ID,
491 'name' => $user->display_name,
492 'created_at' => current_time('mysql'),
493 'updated_at' => current_time('mysql'),
494 ];
495
496 $response_note = apply_filters('fluentform_add_response_note', $response_note);
497
498 $insertId = $this->responseMetaModel->insert($response_note);
499
500 $added_note = $this->responseMetaModel->find($insertId);
501
502 do_action('fluentform_new_response_note_added', $insertId, $added_note);
503
504 wp_send_json_success([
505 'message' => __('Note has been successfully added', 'fluentform'),
506 'note' => $added_note,
507 'insert_id' => $insertId,
508 ], 200);
509 }
510
511 public function changeEntryStatus()
512 {
513 $formId = intval($this->request->get('form_id'));
514 $entryId = intval($this->request->get('entry_id'));
515 $newStatus = sanitize_text_field($this->request->get('status'));
516
517 $this->responseModel
518 ->where('form_id', $formId)
519 ->where('id', $entryId)
520 ->update(['status' => $newStatus]);
521
522 wp_send_json_success([
523 'message' => __('Item has been marked as ' . $newStatus, 'fluentform'),
524 'status' => $newStatus,
525 ], 200);
526 }
527
528 public function deleteEntry()
529 {
530 $formId = intval($this->request->get('form_id'));
531 $entryId = intval($this->request->get('entry_id'));
532 $newStatus = sanitize_text_field($this->request->get('status'));
533
534 $this->deleteEntryById($entryId, $formId);
535
536 wp_send_json_success([
537 'message' => __('Item Successfully deleted', 'fluentform'),
538 'status' => $newStatus,
539 ], 200);
540 }
541
542 public function deleteEntryById($entryId, $formId = false)
543 {
544 do_action('fluentform_before_entry_deleted', $entryId, $formId);
545
546 $disableAttachmentDelete = apply_filters('fluentform_disable_attachment_delete', false, $formId);
547 if (defined('FLUENTFORMPRO') && $formId && !$disableAttachmentDelete) {
548 if (is_numeric($formId)) {
549 $form = wpFluent()->table('fluentform_forms')->find($formId);
550 } else {
551 $form = $formId;
552 }
553 $deletableFiles = $this->getSubmissionAttachments($entryId, $form);
554 if ($deletableFiles) {
555 foreach ($deletableFiles as $eachFile) {
556 $file = wp_upload_dir()['basedir'] . FLUENTFORM_UPLOAD_DIR . '/' . basename($eachFile);
557 if (is_readable($file) && !is_dir($file)) {
558 @unlink($file);
559 }
560 }
561 }
562 }
563
564 wpFluent()->table('fluentform_submissions')
565 ->where('id', $entryId)
566 ->delete();
567 wpFluent()->table('fluentform_submission_meta')
568 ->where('response_id', $entryId)
569 ->delete();
570
571 wpFluent()->table('fluentform_logs')
572 ->where('source_id', $entryId)
573 ->where('source_type', 'submission_item')
574 ->delete();
575
576 wpFluent()->table('fluentform_entry_details')
577 ->where('submission_id', $entryId)
578 ->delete();
579
580 ob_start();
581 if (defined('FLUENTFORMPRO')) {
582 try {
583 wpFluent()->table('fluentform_order_items')
584 ->where('submission_id', $entryId)
585 ->delete();
586
587 wpFluent()->table('fluentform_transactions')
588 ->where('submission_id', $entryId)
589 ->delete();
590
591 wpFluent()->table('fluentform_subscriptions')
592 ->where('submission_id', $entryId)
593 ->delete();
594
595 wpFluent()->table('ff_scheduled_actions')
596 ->where('origin_id', $entryId)
597 ->where('type', 'submission_action')
598 ->delete();
599 } catch (\Exception $exception) {
600 // ...
601 }
602 }
603
604 $errors = ob_get_clean();
605
606 do_action('fluentform_after_entry_deleted', $entryId, $formId);
607
608 return true;
609 }
610
611 private function getSubmissionAttachments($submissionId, $form)
612 {
613 $fields = FormFieldsParser::getAttachmentInputFields($form, ['element', 'attributes']);
614
615 $deletableFiles = [];
616 if ($fields) {
617 $submission = wpFluent()->table('fluentform_submissions')
618 ->where('id', $submissionId)
619 ->first();
620
621 $data = json_decode($submission->response, true);
622
623 foreach ($fields as $field) {
624 if (!empty($data[$field['attributes']['name']])) {
625 $files = $data[$field['attributes']['name']];
626 if (is_array($files)) {
627 $deletableFiles = array_merge($deletableFiles, $files);
628 } else {
629 $deletableFiles = $files;
630 }
631 }
632 }
633 }
634
635 return $deletableFiles;
636 }
637
638 public function favoriteChange()
639 {
640 $formId = intval($this->request->get('form_id'));
641 $entryId = intval($this->request->get('entry_id'));
642 $newStatus = intval($this->request->get('is_favourite'));
643 if ($newStatus) {
644 $message = __('Item has been added to favorites', 'fluentform');
645 } else {
646 $message = __('Item has been removed from favorites', 'fluentform');
647 }
648 $this->responseModel
649 ->where('form_id', $formId)
650 ->where('id', $entryId)
651 ->update(['is_favourite' => $newStatus]);
652
653 wp_send_json_success([
654 'message' => $message,
655 'is_favourite' => $newStatus,
656 ], 200);
657 }
658
659 public function handleBulkAction()
660 {
661 $formId = intval($this->request->get('form_id'));
662 $entries = fluentFormSanitizer($this->request->get('entries', []));
663
664 $actionType = sanitize_text_field($this->request->get('action_type'));
665
666 // check if it's status change or not
667 $statuses = Helper::getEntryStatuses($formId);
668
669 if (!$formId || !count($entries)) {
670 wp_send_json_error([
671 'message' => __('Please select entries first', 'fluentform'),
672 ], 400);
673 }
674
675 $bulkQuery = wpFluent()->table('fluentform_submissions')
676 ->where('form_id', $formId)
677 ->whereIn('id', $entries);
678
679 if (isset($statuses[$actionType])) {
680 // it's status change
681 $bulkQuery->update([
682 'status' => $actionType,
683 'updated_at' => current_time('mysql'),
684 ]);
685
686 wp_send_json_success([
687 'message' => 'Selected entries successfully marked as ' . $statuses[$actionType],
688 ], 200);
689 }
690
691 // now other action handler
692 if ('other.delete_permanently' == $actionType) {
693 $form = wpFluent()->table('fluentform_forms')->find($formId);
694 foreach ($entries as $entryId) {
695 $this->deleteEntryById($entryId, $form);
696 }
697 $message = __('Selected entries successfully deleted', 'fluentform');
698 } elseif ('other.make_favorite' == $actionType) {
699 $bulkQuery->update([
700 'is_favourite' => 1,
701 ]);
702 $message = __('Selected entries successfully marked as favorites', 'fluentform');
703 } elseif ('other.unmark_favorite' == $actionType) {
704 $bulkQuery->update([
705 'is_favourite' => 0,
706 ]);
707 $message = __('Selected entries successfully removed from favorites', 'fluentform');
708 }
709
710 wp_send_json_success([
711 'message' => $message,
712 ], 200);
713 }
714
715 public function recordEntryDetails($entryId, $formId, $data)
716 {
717 $formData = ArrayHelper::except($data, [
718 '__fluent_form_embded_post_id',
719 '_fluentform_' . $formId . '_fluentformnonce',
720 '_wp_http_referer',
721 'g-recaptcha-response',
722 'h-captcha-response',
723 'cf-turnstile-response',
724 '__stripe_payment_method_id',
725 '__ff_all_applied_coupons',
726 '__entry_intermediate_hash',
727 ]);
728
729 $entryItems = [];
730 foreach ($formData as $dataKey => $dataValue) {
731 if (empty($dataValue)) {
732 continue;
733 }
734
735 if (is_array($dataValue) || is_object($dataValue)) {
736 foreach ($dataValue as $subKey => $subValue) {
737 if (empty($subValue)) {
738 continue;
739 }
740 $entryItems[] = [
741 'form_id' => $formId,
742 'submission_id' => $entryId,
743 'field_name' => trim($dataKey),
744 'sub_field_name' => $subKey,
745 'field_value' => maybe_serialize($subValue),
746 ];
747 }
748 } else {
749 $entryItems[] = [
750 'form_id' => $formId,
751 'submission_id' => $entryId,
752 'field_name' => trim($dataKey),
753 'sub_field_name' => '',
754 'field_value' => $dataValue,
755 ];
756 }
757 }
758
759 foreach ($entryItems as $entryItem) {
760 wpFluent()->table('fluentform_entry_details')->insert($entryItem);
761 }
762
763 return true;
764 }
765
766 public function updateEntryDiffs($entryId, $formId, $formData)
767 {
768 wpFluent()->table('fluentform_entry_details')
769 ->where('submission_id', $entryId)
770 ->where('form_id', $formId)
771 ->whereIn('field_name', array_keys($formData))
772 ->delete();
773
774 $entryItems = [];
775 foreach ($formData as $dataKey => $dataValue) {
776 if (!$dataValue) {
777 continue;
778 }
779
780 if (is_array($dataValue)) {
781 foreach ($dataValue as $subKey => $subValue) {
782 $entryItems[] = [
783 'form_id' => $formId,
784 'submission_id' => $entryId,
785 'field_name' => $dataKey,
786 'sub_field_name' => $subKey,
787 'field_value' => maybe_serialize($subValue),
788 ];
789 }
790 } else {
791 $entryItems[] = [
792 'form_id' => $formId,
793 'submission_id' => $entryId,
794 'field_name' => $dataKey,
795 'sub_field_name' => '',
796 'field_value' => $dataValue,
797 ];
798 }
799 }
800
801 foreach ($entryItems as $entryItem) {
802 wpFluent()->table('fluentform_entry_details')->insert($entryItem);
803 }
804
805 return true;
806 }
807
808 public function getUsers()
809 {
810 // if (!current_user_can('list_users')) {
811 // wp_send_json_error([
812 // 'message' => __('Sorry, You do not have permission to list users', 'fluentform')
813 // ]);
814 // }
815
816 $search = sanitize_text_field($this->request->get('search'));
817
818 $users = get_users([
819 'search' => "*{$search}*",
820 'number' => 50,
821 ]);
822
823 $formattedUsers = [];
824
825 foreach ($users as $user) {
826 $formattedUsers[] = [
827 'ID' => $user->ID,
828 'label' => $user->display_name . ' - ' . $user->user_email,
829 ];
830 }
831
832 wp_send_json_success([
833 'users' => $formattedUsers,
834 ]);
835 }
836
837 public function changeEntryUser()
838 {
839 $userId = intval($this->request->get('user_id'));
840 $submissionId = intval($this->request->get('submission_id'));
841
842 if (!$userId || !$submissionId) {
843 wp_send_json_error([
844 'message' => __('Submission ID and User ID is required', 'fluentform'),
845 ], 423);
846 }
847
848 $submission = fluentFormApi('submissions')->find($submissionId);
849
850 $user = get_user_by('ID', $userId);
851
852 if (!$submission || $submission->user_id == $userId || !$user) {
853 wp_send_json_error([
854 'message' => __('Invalid Request', 'fluentform'),
855 ], 423);
856 }
857
858 wpFluent()->table('fluentform_submissions')
859 ->where('id', $submission->id)
860 ->update([
861 'user_id' => $userId,
862 'updated_at' => current_time('mysql'),
863 ]);
864
865 if (defined('FLUENTFORMPRO')) {
866 // let's update the corresponding user IDs for transactions and
867 wpFluent()->table('fluentform_transactions')
868 ->where('submission_id', $submission->id)
869 ->update([
870 'user_id' => $userId,
871 'updated_at' => current_time('mysql'),
872 ]);
873 }
874
875 do_action('ff_log_data', [
876 'parent_source_id' => $submission->form_id,
877 'source_type' => 'submission_item',
878 'source_id' => $submission->id,
879 'component' => 'General',
880 'status' => 'info',
881 'title' => 'Associate user has been changed from ' . $submission->user_id . ' to ' . $userId,
882 ]);
883
884 do_action('fluentform_submission_user_changed', $submission, $user);
885
886 wp_send_json_success([
887 'message' => __('Selected user has been successfully assigned to this submission', 'fluentform'),
888 'user' => [
889 'name' => $user->display_name,
890 'email' => $user->user_email,
891 'ID' => $user->ID,
892 'permalink' => get_edit_user_link($user->ID),
893 ],
894 'user_id' => $userId,
895 ]);
896 }
897
898 public function getAvailableForms()
899 {
900 $forms = wpFluent()->table('fluentform_forms')
901 ->select(['id', 'title'])
902 ->orderBy('id', 'DESC')
903 ->get();
904
905 $formattedForms = [];
906 foreach ($forms as $form) {
907 $formattedForms[] = [
908 'id' => $form->id,
909 'title' => $form->title,
910 ];
911 }
912
913 return $formattedForms;
914 }
915 }
916