-
Notifications
You must be signed in to change notification settings - Fork 510
/
ConversationsController.php
executable file
·2721 lines (2326 loc) · 112 KB
/
ConversationsController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace App\Http\Controllers;
use App\Attachment;
use App\Conversation;
use App\Customer;
use App\Email;
use App\Events\ConversationStatusChanged;
use App\Events\ConversationUserChanged;
use App\Events\UserAddedNote;
use App\Events\UserCreatedConversation;
use App\Events\UserCreatedConversationDraft;
use App\Events\UserCreatedThreadDraft;
use App\Events\UserReplied;
use App\Folder;
use App\Follower;
use App\Mailbox;
use App\MailboxUser;
use App\SendLog;
use App\Thread;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Validator;
class ConversationsController extends Controller
{
const PREV_CONVERSATIONS_LIMIT = 5;
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* View conversation.
*/
public function view(Request $request, $id)
{
$conversation = Conversation::findOrFail($id);
$this->authorize('viewCached', $conversation);
$mailbox = $conversation->mailbox;
$customer = $conversation->customer_cached;
$user = auth()->user();
// To let other parts of the app easily access.
\Helper::setGlobalEntity('conversation', $conversation);
\Helper::setGlobalEntity('mailbox', $mailbox);
if ($user->isAdmin()) {
$mailbox->fetchUserSettings($user->id);
}
// Mark notifications as read
if (!empty($request->mark_as_read)) {
$mark_read_result = $user->unreadNotifications()->where('id', $request->mark_as_read)->update(['read_at' => now()]);
$user->clearWebsiteNotificationsCache();
} else {
$mark_read_result = $user->unreadNotifications()->where('data', 'like', '%"conversation_id":'.$conversation->id.'%')->update(['read_at' => now()]);
}
if ($mark_read_result) {
$user->clearWebsiteNotificationsCache();
}
// Detect folder and redirect if needed
$folder = null;
if (Conversation::getFolderParam()) {
$folder = $conversation->mailbox->folders()->where('folders.id', Conversation::getFolderParam())->first();
if ($folder) {
// Check if conversation can be located in the passed folder_id
if (!$conversation->isInFolderAllowed($folder)) {
// Without reflash green flash will not be displayed on assignee change
\Session::reflash();
//$request->session()->reflash();
return redirect()->away($conversation->url($conversation->folder_id));
}
// If conversation assigned to user, select Mine folder instead of Assigned
if ($folder->type == Folder::TYPE_ASSIGNED && $conversation->user_id == $user->id) {
$folder = $conversation->mailbox->folders()
->where('type', Folder::TYPE_MINE)
->where('user_id', $user->id)
->first();
\Session::reflash();
return redirect()->away($conversation->url($folder->id));
}
}
}
// Add folder if empty
if (!$folder) {
if ($conversation->user_id == $user->id) {
$folder = $conversation->mailbox->folders()
->where('type', Folder::TYPE_MINE)
->where('user_id', $user->id)
->first();
} else {
$folder = $conversation->folder;
}
\Session::reflash();
return redirect()->away($conversation->url($folder->id));
}
//$after_send = $conversation->mailbox->getUserSettings($user->id)->after_send;
$after_send = $user->mailboxSettings($conversation->mailbox_id)->after_send;
// Detect customers and emails to which user can reply
$to_customers = [];
// Add all customer emails
$customer_emails = [];
$distinct_emails = [];
// Add emails of customers from whom there were replies in the conversation
$prev_customers_emails = [];
if ($conversation->customer_email) {
$prev_customers_emails = Thread::select('from', 'customer_id')
->where('conversation_id', $id)
->where('type', Thread::TYPE_CUSTOMER)
->where('from', '<>', $conversation->customer_email)
->groupBy(['from', 'customer_id'])
->get();
}
foreach ($prev_customers_emails as $prev_customer) {
if (!in_array($prev_customer->from, $distinct_emails) && $prev_customer->customer && $prev_customer->from) {
$to_customers[] = [
'customer' => $prev_customer->customer,
'email' => $prev_customer->from,
];
$distinct_emails[] = $prev_customer->from;
}
}
// Add customer email(s) if there more than one or if there are other emails in threads.
if ($customer) {
$customer_emails = $customer->emails;
}
if (count($customer_emails) > 1 || count($to_customers)) {
foreach ($customer_emails as $customer_email) {
$to_customers[] = [
'customer' => $customer,
'email' => $customer_email->email,
];
$distinct_emails[] = $customer_email->email;
}
}
// To (for new conversation draft only).
$to = [];
$emails = Conversation::sanitizeEmails($conversation->customer_email);
// Get customers info for emails.
if (count($emails)) {
$to = Customer::emailsToCustomers($emails);
}
// Exclude mailbox emails from $to_customers.
$mailbox_emails = $mailbox->getEmails();
foreach ($to_customers as $key => $to_customer) {
if (in_array($to_customer['email'], $mailbox_emails)) {
unset($to_customers[$key]);
}
}
// Previous conversations
$prev_conversations = [];
if ($customer) {
$prev_conversations = $mailbox->conversations()
->where('customer_id', $customer->id)
->where('id', '<>', $conversation->id)
->where('status', '!=', Conversation::STATUS_SPAM)
->where('state', Conversation::STATE_PUBLISHED)
//->limit(self::PREV_CONVERSATIONS_LIMIT)
->orderBy('created_at', 'desc')
->paginate(self::PREV_CONVERSATIONS_LIMIT);
}
$template = 'conversations/view';
if ($conversation->state == Conversation::STATE_DRAFT) {
$template = 'conversations/create';
}
$exclude_array = $conversation->getExcludeArray($mailbox);
// Get data for creating a phone conversation.
$name = [];
$phone = '';
$to_email = [];
if ($customer) {
if ($customer->getFullName()) {
$name = [$customer->id => $customer->getFullName()];
}
$last_phone = array_last($customer->getPhones());
if (!empty($last_phone)) {
$phone = $last_phone['value'];
}
if ($conversation->customer_email) {
$customer_email = $conversation->customer_email;
} else {
$customer_email = $customer->getMainEmail();
}
if ($customer_email) {
$to_email = [$customer_email];
}
}
// Notify other users that current user is viewing conversation.
// Eventually notification data will be saved in polycast_events table and processes
// in JS in users browsers.
// $notification = new \App\Notifications\UserViewingConversationNotification(
// $conversation, $user, false
// );
// This broadcasts to specific users.
// \Notification::send($mailbox->usersHavingAccess(), $notification);
// Notification is sent to all via public channel: conview
// If we send notification to each user, applications having thouthans of users
// will be overloaded.
// // https://laravel.com/docs/5.5/broadcasting#broadcasting-events
\App\Events\RealtimeConvView::dispatchSelf($conversation->id, $user, false);
// Get viewers.
$viewers = [];
$conv_view = \Cache::get('conv_view');
if ($conv_view && !empty($conv_view[$conversation->id])) {
$viewing_users = User::whereIn('id', array_keys($conv_view[$conversation->id]))->get();
foreach ($viewing_users as $viewer) {
if (isset($conv_view[$conversation->id][$viewer->id]['r']) && $viewer->id != $user->id) {
$viewers[] = [
'user' => $viewer,
'replying' => (int)$conv_view[$conversation->id][$viewer->id]['r']
];
}
}
// Show replying first.
usort($viewers, function($a, $b) {
return $b['replying'] <=> $a['replying'];
});
}
$is_following = $conversation->isUserFollowing($user->id);
\Eventy::action('conversation.view.start', $conversation);
return view($template, [
'conversation' => $conversation,
'mailbox' => $conversation->mailbox,
'customer' => $customer,
'threads' => $conversation->threads()->orderBy('created_at', 'desc')->get(),
'folder' => $folder,
'folders' => $conversation->mailbox->getAssesibleFolders(),
'after_send' => $after_send,
'to' => $to,
'to_customers' => $to_customers,
'prev_conversations' => $prev_conversations,
'cc' => $conversation->getCcArray($exclude_array),
'bcc' => [], //$conversation->getBccArray($exclude_array),
// Data for creating a phone conversation.
'name' => $name,
'phone' => $phone,
'to_email' => $to_email,
'viewers' => $viewers,
'is_following' => $is_following,
]);
}
/**
* New conversation.
*/
public function create(Request $request, $mailbox_id)
{
$mailbox = Mailbox::findOrFail($mailbox_id);
$this->authorize('view', $mailbox);
$conversation = new Conversation();
$conversation->body = '';
$conversation->mailbox = $mailbox;
$folder = $mailbox->folders()->where('type', Folder::TYPE_DRAFTS)->first();
// todo: use $user->mailboxSettings()
$after_send = $mailbox->getUserSettings(auth()->user()->id)->after_send;
// Create conversation from thread
$thread = null;
if (!empty($request->from_thread_id)) {
$orig_thread = Thread::find($request->from_thread_id);
if ($orig_thread) {
$conversation->subject = $orig_thread->conversation->subject;
$conversation->subject = preg_replace('/^Fwd:/i', 'Re: ', $conversation->subject);
$thread = new \App\Thread();
$thread->body = $orig_thread->body;
// If this is a forwarded message, try to fetch From
preg_match_all("/From:[^<\n]+<([^<\n]+)>/m", html_entity_decode(strip_tags($thread->body)), $m);
if (!empty($m[1])) {
foreach ($m[1] as $value) {
if (\MailHelper::validateEmail($value)) {
$thread->to = json_encode([$value]);
break;
}
}
}
}
}
$to = [];
$prefill_to = \App\Email::sanitizeEmail($request->get('to'));
if ($prefill_to) {
$to = [$prefill_to => $prefill_to];
}
return view('conversations/create', [
'conversation' => $conversation,
'thread' => $thread,
'mailbox' => $mailbox,
'folder' => $folder,
'folders' => $mailbox->getAssesibleFolders(),
'after_send' => $after_send,
'to' => $to,
]);
}
/**
* Conversation draft.
*/
// public function draft($id)
// {
// $conversation = Conversation::findOrFail($id);
// $this->authorize('view', $conversation);
// return view('conversations/create', [
// 'conversation' => $conversation,
// 'mailbox' => $conversation->mailbox,
// 'folder' => $conversation->folder,
// 'folders' => $conversation->mailbox->getAssesibleFolders(),
// ]);
// }
/**
* Conversations ajax controller.
*/
public function ajax(Request $request)
{
$response = [
'status' => 'error',
'msg' => '', // this is error message
];
$user = auth()->user();
switch ($request->action) {
// Change conversation user
case 'conversation_change_user':
$conversation = Conversation::find($request->conversation_id);
$new_user_id = (int) $request->user_id;
if (!$conversation) {
$response['msg'] = __('Conversation not found');
}
if (!$response['msg'] && $conversation->user_id == $new_user_id) {
$response['msg'] = __('Assignee already set');
}
if (!$response['msg'] && !$user->can('update', $conversation)) {
$response['msg'] = __('Not enough permissions');
}
if (!$response['msg'] && (int) $new_user_id != -1 && !$conversation->mailbox->userHasAccess($new_user_id)) {
$response['msg'] = __('Not enough permissions');
}
if (!$response['msg']) {
// Determine redirect
// Must be done before updating current conversation's status or assignee.
$redirect_same_page = false;
if ($new_user_id == $user->id) {
// If user assigned conversation to himself, stay on the current page
$response['redirect_url'] = $conversation->url();
$redirect_same_page = true;
} else {
$response['redirect_url'] = $this->getRedirectUrl($request, $conversation, $user);
}
$conversation->changeUser($new_user_id, $user);
$response['status'] = 'success';
// Flash
$flash_message = __('Assignee updated');
if (!$redirect_same_page || $response['redirect_url'] != $conversation->url()) {
$flash_message .= ' <a href="'.$conversation->url().'">'.__('View').'</a>';
}
\Session::flash('flash_success_floating', $flash_message);
$response['msg'] = __('Assignee updated');
}
break;
// Change conversation status
case 'conversation_change_status':
$conversation = Conversation::find($request->conversation_id);
if ($request->status == 'not_spam') {
// Find previous status in threads
$new_status = $conversation
->threads()
->orderBy('created_at', 'desc')
->where('status', '!=', Thread::STATUS_SPAM)
->where('type', Thread::TYPE_LINEITEM)
->where('action_type', Thread::ACTION_TYPE_STATUS_CHANGED)
->value('status');
if (!$new_status) {
$new_status = Thread::STATUS_ACTIVE;
}
} else {
$new_status = (int) $request->status;
}
if (!$conversation) {
$response['msg'] = __('Conversation not found');
}
if (!$response['msg'] && $conversation->status == $new_status) {
$response['msg'] = __('Status already set');
}
if (!$response['msg'] && !$user->can('update', $conversation)) {
$response['msg'] = __('Not enough permissions');
}
if (!$response['msg'] && !in_array((int) $new_status, array_keys(Conversation::$statuses))) {
$response['msg'] = __('Incorrect status');
}
if (!$response['msg']) {
// Determine redirect
// Must be done before updating current conversation's status or assignee.
$redirect_same_page = false;
if ($request->status == 'not_spam') {
// Stay on the current page
$response['redirect_url'] = $conversation->url();
$redirect_same_page = true;
} else {
$response['redirect_url'] = $this->getRedirectUrl($request, $conversation, $user);
}
$conversation->changeStatus($new_status, $user);
$response['status'] = 'success';
// Flash
$flash_message = __('Status updated');
if (!$redirect_same_page || $response['redirect_url'] != $conversation->url()) {
$flash_message .= ' <a href="'.$conversation->url().'">'.__('View').'</a>';
}
\Session::flash('flash_success_floating', $flash_message);
$response['msg'] = __('Status updated');
}
break;
// Send reply, new conversation, add note or forward
case 'send_reply':
$mailbox = Mailbox::findOrFail($request->mailbox_id);
if (!$response['msg'] && !$user->can('view', $mailbox)) {
$response['msg'] = __('Not enough permissions');
}
$conversation = null;
if (!$response['msg'] && !empty($request->conversation_id)) {
$conversation = Conversation::find($request->conversation_id);
if ($conversation && !$user->can('view', $conversation)) {
$response['msg'] = __('Not enough permissions');
}
}
$new = false;
if (empty($request->conversation_id)) {
$new = true;
}
$is_note = false;
if (!empty($request->is_note)) {
$is_note = true;
}
// Conversation type.
$type = Conversation::TYPE_EMAIL;
if (!empty($request->type)) {
$type = (int)$request->type;
}
$is_phone = false;
if ($type == Conversation::TYPE_PHONE) {
$is_phone = true;
}
$is_create = false;
if (!empty($request->is_create)) {
//if ($new || ($from_draft && $conversation->threads_count == 1)) {
$is_create = $request->is_create;
}
$is_forward = false;
if (!empty($request->subtype) && (int)$request->subtype == Thread::SUBTYPE_FORWARD) {
$is_forward = true;
}
$is_multiple = false;
if (!empty($request->multiple_conversations)) {
$is_multiple = true;
}
// If reply is being created from draft, there is already thread created
$thread = null;
$from_draft = false;
if ((!$is_note || $is_phone) && !$response['msg'] && !empty($request->thread_id)) {
$thread = Thread::find($request->thread_id);
if ($thread && (!$conversation || $thread->conversation_id != $conversation->id)) {
$response['msg'] = __('Incorrect thread');
} else {
$from_draft = true;
}
}
if (!$response['msg']) {
if ($thread && $from_draft && $thread->state == Thread::STATE_PUBLISHED) {
$response['msg'] = __('Message has been already sent. Please discard this draft.');
}
}
// Validate form
if (!$response['msg']) {
if ($new) {
if ($type == Conversation::TYPE_EMAIL) {
$validator = Validator::make($request->all(), [
'to' => 'required|array',
'subject' => 'required|string|max:998',
'body' => 'required|string',
'cc' => 'nullable|array',
'bcc' => 'nullable|array',
]);
} else {
// Phone conversation.
$validator = Validator::make($request->all(), [
'name' => 'required|string',
'subject' => 'required|string|max:998',
'body' => 'required|string',
'phone' => 'nullable|string',
'to_email' => 'nullable|string',
]);
}
} else {
$validator = Validator::make($request->all(), [
'body' => 'required|string',
'cc' => 'nullable|array',
'bcc' => 'nullable|array',
]);
}
if ($validator->fails()) {
foreach ($validator->errors()->getMessages()as $errors) {
foreach ($errors as $field => $message) {
$response['msg'] .= $message.' ';
}
}
}
}
// List of emails.
$to_array = [];
if ($is_forward) {
$to_array = Conversation::sanitizeEmails($request->to_email);
} else {
$to_array = Conversation::sanitizeEmails($request->to);
}
// Check To
if (!$response['msg'] && $new && !$is_phone) {
if (!$to_array) {
$response['msg'] .= __('Incorrect recipients');
}
}
if (!$response['msg']) {
// Get attachments info
// Delete removed attachments.
$attachments_info = $this->processReplyAttachments($request);
// Determine redirect.
// Must be done before updating current conversation's status or assignee.
if (!$new) {
$response['redirect_url'] = $this->getRedirectUrl($request, $conversation, $user);
}
// Conversation
$now = date('Y-m-d H:i:s');
$status_changed = false;
$user_changed = false;
if ($new) {
// New conversation
$conversation = new Conversation();
$conversation->type = $type;
$conversation->subject = $request->subject;
$conversation->setPreview($request->body);
$conversation->mailbox_id = $request->mailbox_id;
$conversation->created_by_user_id = auth()->user()->id;
$conversation->source_via = Conversation::PERSON_USER;
$conversation->source_type = Conversation::SOURCE_TYPE_WEB;
} else {
// Reply or note
if ((int) $request->status != (int) $conversation->status) {
$status_changed = true;
}
if (!empty($request->subject)) {
$conversation->subject = $request->subject;
}
// When switching from regular message to phone and message sent
// without saving a draft type need to be saved here.
if ($conversation->type == Conversation::TYPE_EMAIL && $type == Conversation::TYPE_PHONE) {
$conversation->type = $type;
}
}
if ($attachments_info['has_attachments']) {
$conversation->has_attachments = true;
}
// Customer can be empty in existing conversation if this is a draft.
$customer_email = '';
$customer = null;
if ($is_phone) {
// Phone.
$phone_customer_data = $this->processPhoneCustomer($request);
$customer_email = $phone_customer_data['customer_email'];
$customer = $phone_customer_data['customer'];
if (!$conversation->customer_id) {
$conversation->customer_id = $customer->id;
}
} else {
// Email.
if (!empty($to_array)) {
$customer_email = $to_array[0];
}
if (!$conversation->customer_id) {
$customer = Customer::create($customer_email);
$conversation->customer_id = $customer->id;
} else {
$customer = $conversation->customer;
}
}
if ($customer_email && !$is_note && !$is_forward) {
$conversation->customer_email = $customer_email;
}
$prev_status = $conversation->status;
$conversation->status = $request->status;
if ($prev_status != $conversation->status && $conversation->status == Conversation::STATUS_CLOSED) {
$conversation->closed_by_user_id = $user->id;
$conversation->closed_at = date('Y-m-d H:i:s');
}
// We need to set state, as it may have been a draft
$conversation->state = Conversation::STATE_PUBLISHED;
// Set assignee
$prev_user_id = $conversation->user_id;
if ((int) $request->user_id != -1) {
// Check if user has access to the current mailbox
if ((int) $conversation->user_id != (int) $request->user_id && $mailbox->userHasAccess($request->user_id)) {
$conversation->user_id = $request->user_id;
$user_changed = true;
}
} else {
$conversation->user_id = null;
}
// To is a single email string.
$to = '';
// List of emails.
$to_list = [];
if ($is_forward) {
$to = $request->to_email[0];
} else {
if (!empty($request->to)) {
// When creating a new conversation, to is a list of emails.
if (is_array($request->to)) {
$to = $request->to[0];
} else {
$to = $request->to;
}
} else {
$to = $conversation->customer_email;
}
}
if (!$is_note && !$is_forward) {
// Save extra recipients to CC
if ($is_create && !$is_multiple && count($to_array) > 1) {
$conversation->setCc(array_merge(Conversation::sanitizeEmails($request->cc), $to_array));
} else {
$conversation->setCc(array_merge(Conversation::sanitizeEmails($request->cc), [$to]));
}
$conversation->setBcc($request->bcc);
$conversation->last_reply_at = $now;
$conversation->last_reply_from = Conversation::PERSON_USER;
$conversation->user_updated_at = $now;
}
if ($conversation->isPhone() && $is_note) {
$conversation->last_reply_at = $now;
$conversation->last_reply_from = Conversation::PERSON_USER;
}
$conversation->updateFolder();
if ($from_draft) {
// Increment number of replies in conversation
$conversation->threads_count++;
// We need to set preview here as when conversation is created from draft,
// ThreadObserver::created() method is not called.
$conversation->setPreview($request->body);
}
$conversation->save();
if ($new) {
$response['redirect_url'] = $this->getRedirectUrl($request, $conversation, $user);
}
// Fire events
\Eventy::action('conversation.send_reply_save', $conversation, $request);
if (!$new) {
if ($status_changed) {
event(new ConversationStatusChanged($conversation));
\Eventy::action('conversation.status_changed', $conversation, $user, $changed_on_reply = true, $prev_status);
}
if ($user_changed) {
event(new ConversationUserChanged($conversation, $user));
\Eventy::action('conversation.user_changed', $conversation, $user, $prev_user_id);
}
}
// Create thread
if (!$thread) {
$thread = new Thread();
$thread->conversation_id = $conversation->id;
if ($is_note || $is_forward) {
$thread->type = Thread::TYPE_NOTE;
} else {
$thread->type = Thread::TYPE_MESSAGE;
}
$thread->source_via = Thread::PERSON_USER;
$thread->source_type = Thread::SOURCE_TYPE_WEB;
} else {
if ($is_forward || $is_phone) {
$thread->type = Thread::TYPE_NOTE;
} else {
$thread->type = Thread::TYPE_MESSAGE;
}
$thread->created_at = $now;
}
if ($new) {
$thread->first = true;
}
$thread->user_id = $conversation->user_id;
$thread->status = $request->status;
$thread->state = Thread::STATE_PUBLISHED;
$thread->customer_id = $customer->id;
$thread->created_by_user_id = auth()->user()->id;
$thread->edited_by_user_id = null;
$thread->edited_at = null;
$thread->body = $request->body;
if ($is_create && !$is_multiple && count($to_array) > 1) {
$thread->setTo($to_array);
} else {
$thread->setTo($to);
}
// We save CC and BCC as is and filter emails when sending replies
$thread->setCc($request->cc);
$thread->setBcc($request->bcc);
if ($attachments_info['has_attachments'] && !$is_forward) {
$thread->has_attachments = true;
}
if (!empty($request->saved_reply_id)) {
$thread->saved_reply_id = $request->saved_reply_id;
}
$forwarded_conversations = [];
$forwarded_threads = [];
if ($is_forward) {
// Create forwarded conversations.
foreach ($to_array as $recipient_email) {
$forwarded_conversation = $conversation->replicate();
$forwarded_conversation->type = Conversation::TYPE_EMAIL;
$forwarded_conversation->setPreview($thread->body);
$forwarded_conversation->created_by_user_id = auth()->user()->id;
$forwarded_conversation->source_via = Conversation::PERSON_USER;
$forwarded_conversation->source_type = Conversation::SOURCE_TYPE_WEB;
$forwarded_conversation->threads_count = 0; // Counter will be incremented in ThreadObserver.
$forwarded_customer = Customer::create($recipient_email);
$forwarded_conversation->customer_id = $forwarded_customer->id;
// Reload customer object, otherwise it stores previous customer.
$forwarded_conversation->load('customer');
$forwarded_conversation->customer_email = $recipient_email;
$forwarded_conversation->subject = 'Fwd: '.$forwarded_conversation->subject;
//$forwarded_conversation->setCc(array_merge(Conversation::sanitizeEmails($request->cc), [$to]));
$forwarded_conversation->setCc(Conversation::sanitizeEmails($request->cc));
$forwarded_conversation->setBcc($request->bcc);
$forwarded_conversation->last_reply_at = $now;
$forwarded_conversation->last_reply_from = Conversation::PERSON_USER;
$forwarded_conversation->user_updated_at = $now;
if ($attachments_info['has_attachments']) {
$forwarded_conversation->has_attachments = true;
}
$forwarded_conversation->updateFolder();
$forwarded_conversation->save();
$forwarded_thread = $thread->replicate();
$forwarded_conversations[] = $forwarded_conversation;
$forwarded_threads[] = $forwarded_thread;
}
// Set forwarding meta data.
// todo: store array of numbers and IDs.
$thread->subtype = Thread::SUBTYPE_FORWARD;
$thread->setMeta('forward_child_conversation_number', $forwarded_conversation->number);
$thread->setMeta('forward_child_conversation_id', $forwarded_conversation->id);
}
// Conversation history.
if (!empty($request->conv_history)) {
if ($request->conv_history != 'global') {
if ($is_forward && !empty($forwarded_threads)) {
foreach ($forwarded_threads as $forwarded_thread) {
$forwarded_thread->setMeta(Thread::META_CONVERSATION_HISTORY, $request->conv_history);
}
} else {
$thread->setMeta(Thread::META_CONVERSATION_HISTORY, $request->conv_history);
}
}
}
\Eventy::action('thread.before_save_from_request', $thread, $request);
$thread->save();
// Save forwarded thread.
if ($is_forward) {
foreach ($forwarded_conversations as $i => $forwarded_conversation) {
$forwarded_thread = $forwarded_threads[$i];
$forwarded_thread->conversation_id = $forwarded_conversation->id;
$forwarded_thread->type = Thread::TYPE_MESSAGE;
$forwarded_thread->subtype = null;
if ($attachments_info['has_attachments']) {
$forwarded_thread->has_attachments = true;
}
$forwarded_thread->setMeta('forward_parent_conversation_number', $conversation->number);
$forwarded_thread->setMeta('forward_parent_conversation_id', $conversation->id);
$forwarded_thread->setMeta('forward_parent_thread_id', $thread->id);
$forwarded_thread->save();
}
}
// If thread has been created from draft, remove the draft
// if ($request->thread_id) {
// $draft_thread = Thread::find($request->thread_id);
// if ($draft_thread) {
// $draft_thread->delete();
// }
// }
if ($from_draft) {
// Remove conversation from drafts folder if needed
$conversation->maybeRemoveFromDrafts();
}
// Update folders counters
$conversation->mailbox->updateFoldersCounters();
$response['status'] = 'success';
// Set thread_id for uploaded attachments
if ($attachments_info['attachments']) {
if ($is_forward) {
// Copy attachments for each thread.
if (count($forwarded_threads) > 1) {
$attachments = Attachment::whereIn('id', $attachments_info['attachments'])->get();
}
foreach ($forwarded_threads as $i => $forwarded_thread) {
if ($i == 0) {
Attachment::whereIn('id', $attachments_info['attachments'])->update(['thread_id' => $forwarded_thread->id]);
} else {
foreach ($attachments as $attachment) {
$attachment->duplicate($forwarded_thread->id);
}
}
}
} else {
Attachment::whereIn('id', $attachments_info['attachments'])->update(['thread_id' => $thread->id]);
}
}
// When user creates a new conversation it may be saved as draft first.
if ($is_create) {
// New conversation.
event(new UserCreatedConversation($conversation, $thread));
\Eventy::action('conversation.created_by_user_can_undo', $conversation, $thread);
// After Conversation::UNDO_TIMOUT period trigger final event.
\Helper::backgroundAction('conversation.created_by_user', [$conversation, $thread], now()->addSeconds(Conversation::UNDO_TIMOUT));
} elseif ($is_forward) {
// Forward.
// Notifications to users not sent.
event(new UserAddedNote($conversation, $thread));
foreach ($forwarded_conversations as $i => $forwarded_conversation) {
$forwarded_thread = $forwarded_threads[$i];
// To send email with forwarded conversation.
event(new UserReplied($forwarded_conversation, $forwarded_thread));
\Eventy::action('conversation.user_forwarded_can_undo', $conversation, $thread, $forwarded_conversation, $forwarded_thread);
// After Conversation::UNDO_TIMOUT period trigger final event.
\Helper::backgroundAction('conversation.user_forwarded', [$conversation, $thread, $forwarded_conversation, $forwarded_thread], now()->addSeconds(Conversation::UNDO_TIMOUT));
}
} elseif ($is_note) {
// Note.
event(new UserAddedNote($conversation, $thread));
\Eventy::action('conversation.note_added', $conversation, $thread);
} else {
// Reply.
event(new UserReplied($conversation, $thread));
\Eventy::action('conversation.user_replied_can_undo', $conversation, $thread);
// After Conversation::UNDO_TIMOUT period trigger final event.
\Helper::backgroundAction('conversation.user_replied', [$conversation, $thread], now()->addSeconds(Conversation::UNDO_TIMOUT));
}
// Send new conversation separately to each customer.
if ($is_create && count($to_array) > 1 && $is_multiple) {
$prev_customers_ids = [];
foreach ($to_array as $i => $customer_email) {
// Skip first email, as conversation has already been created for it.
if ($i == 0) {
continue;
}
// Get customer by email.
$customer_tmp = Customer::getByEmail($customer_email);
// Skip same customers.
if ($customer_tmp && in_array($customer_tmp->id, $prev_customers_ids)) {
continue;
}
if (!$customer_tmp) {
$customer_tmp = Customer::create($customer_email);
}
$prev_customers_ids[] = $customer_tmp->id;
// Copy conversation and thread.
$conversation_copy = $conversation->replicate();
$thread_copy = $thread->replicate();
// Save conversation.
$conversation_copy->threads_count = 0;
$conversation_copy->customer_id = $customer_tmp->id;
// Reload customer, otherwise all recipients will have the same name.
$conversation_copy->load('customer');
$conversation_copy->customer_email = $customer_email;
$conversation_copy->has_attachments = $conversation->has_attachments;
$conversation_copy->push();
$thread_copy->conversation_id = $conversation_copy->id;
$thread_copy->customer_id = $customer_tmp->id;
$thread_copy->has_attachments = $conversation->has_attachments;
$thread_copy->setTo($customer_email);
$thread_copy->push();
// Copy attachments.
if (!empty($attachments_info['attachments'])) {
$attachments = Attachment::whereIn('id', $attachments_info['attachments'])->get();
foreach ($attachments as $attachment) {
$attachment->duplicate($thread_copy->id);
}
}
// Events.
// todo: allow to undo all emails
event(new UserCreatedConversation($conversation_copy, $thread_copy));