-
Notifications
You must be signed in to change notification settings - Fork 317
Expand file tree
/
Copy pathMailManager.php
More file actions
966 lines (878 loc) Β· 25.7 KB
/
MailManager.php
File metadata and controls
966 lines (878 loc) Β· 25.7 KB
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
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-only
*/
namespace OCA\Mail\Service;
use Horde_Imap_Client;
use Horde_Imap_Client_Exception;
use Horde_Imap_Client_Exception_NoSupportExtension;
use Horde_Imap_Client_Socket;
use Horde_Mime_Exception;
use OCA\Mail\Account;
use OCA\Mail\Attachment;
use OCA\Mail\Contracts\IMailManager;
use OCA\Mail\Db\Mailbox;
use OCA\Mail\Db\MailboxMapper;
use OCA\Mail\Db\Message;
use OCA\Mail\Db\MessageMapper as DbMessageMapper;
use OCA\Mail\Db\MessageTags;
use OCA\Mail\Db\MessageTagsMapper;
use OCA\Mail\Db\Tag;
use OCA\Mail\Db\TagMapper;
use OCA\Mail\Db\ThreadMapper;
use OCA\Mail\Events\BeforeMessageDeletedEvent;
use OCA\Mail\Events\MessageDeletedEvent;
use OCA\Mail\Events\MessageFlaggedEvent;
use OCA\Mail\Exception\ClientException;
use OCA\Mail\Exception\ImapFlagEncodingException;
use OCA\Mail\Exception\ServiceException;
use OCA\Mail\Exception\TrashMailboxNotSetException;
use OCA\Mail\Folder;
use OCA\Mail\IMAP\FolderMapper;
use OCA\Mail\IMAP\IMAPClientFactory;
use OCA\Mail\IMAP\ImapFlag;
use OCA\Mail\IMAP\MailboxSync;
use OCA\Mail\IMAP\MessageMapper as ImapMessageMapper;
use OCA\Mail\Model\IMAPMessage;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\EventDispatcher\IEventDispatcher;
use Psr\Log\LoggerInterface;
use function array_map;
use function array_values;
class MailManager implements IMailManager {
/**
* https://datatracker.ietf.org/doc/html/rfc9051#name-flags-message-attribute
*/
private const SYSTEM_FLAGS = [
'seen' => [Horde_Imap_Client::FLAG_SEEN],
'answered' => [Horde_Imap_Client::FLAG_ANSWERED],
'flagged' => [Horde_Imap_Client::FLAG_FLAGGED],
'deleted' => [Horde_Imap_Client::FLAG_DELETED],
'draft' => [Horde_Imap_Client::FLAG_DRAFT],
'recent' => [Horde_Imap_Client::FLAG_RECENT],
];
/** @var IMAPClientFactory */
private $imapClientFactory;
/** @var MailboxSync */
private $mailboxSync;
/** @var MailboxMapper */
private $mailboxMapper;
/** @var FolderMapper */
private $folderMapper;
/** @var ImapMessageMapper */
private $imapMessageMapper;
/** @var DbMessageMapper */
private $dbMessageMapper;
/** @var IEventDispatcher */
private $eventDispatcher;
/** @var LoggerInterface */
private $logger;
/** @var TagMapper */
private $tagMapper;
/** @var MessageTagsMapper */
private $messageTagsMapper;
/** @var ThreadMapper */
private $threadMapper;
public function __construct(
IMAPClientFactory $imapClientFactory,
MailboxMapper $mailboxMapper,
MailboxSync $mailboxSync,
FolderMapper $folderMapper,
ImapMessageMapper $messageMapper,
DbMessageMapper $dbMessageMapper,
IEventDispatcher $eventDispatcher,
LoggerInterface $logger,
TagMapper $tagMapper,
MessageTagsMapper $messageTagsMapper,
ThreadMapper $threadMapper,
private ImapFlag $imapFlag,
) {
$this->imapClientFactory = $imapClientFactory;
$this->mailboxMapper = $mailboxMapper;
$this->mailboxSync = $mailboxSync;
$this->folderMapper = $folderMapper;
$this->imapMessageMapper = $messageMapper;
$this->dbMessageMapper = $dbMessageMapper;
$this->eventDispatcher = $eventDispatcher;
$this->logger = $logger;
$this->tagMapper = $tagMapper;
$this->messageTagsMapper = $messageTagsMapper;
$this->threadMapper = $threadMapper;
}
#[\Override]
public function getMailbox(string $uid, int $id): Mailbox {
try {
return $this->mailboxMapper->findByUid($id, $uid);
} catch (DoesNotExistException $e) {
throw new ClientException("Mailbox $id does not exist", 0, $e);
}
}
/**
* @param Account $account
* @param bool $forceSync
*
* @return Mailbox[]
* @throws ServiceException
*/
#[\Override]
public function getMailboxes(Account $account, bool $forceSync = false): array {
$this->mailboxSync->sync($account, $this->logger, $forceSync);
return $this->mailboxMapper->findAll($account);
}
#[\Override]
public function createMailbox(Account $account, string $name, array $specialUse = []): Mailbox {
$client = $this->imapClientFactory->getClient($account);
try {
$folder = $this->folderMapper->createFolder($client, $name, $specialUse);
$this->folderMapper->fetchFolderAcls([$folder], $client);
$this->folderMapper->detectFolderSpecialUse([$folder]);
$this->mailboxSync->sync($account, $this->logger, true, $client);
} catch (Horde_Imap_Client_Exception $e) {
throw new ServiceException(
'Could not get mailbox status: ' . $e->getMessage(),
$e->getCode(),
$e
);
} finally {
$client->logout();
}
return $this->mailboxMapper->find($account, $name);
}
#[\Override]
public function getImapMessage(Horde_Imap_Client_Socket $client,
Account $account,
Mailbox $mailbox,
int $uid,
bool $loadBody = false): IMAPMessage {
try {
return $this->imapMessageMapper->find(
$client,
$mailbox->getName(),
$uid,
$account->getUserId(),
$loadBody
);
} catch (DoesNotExistException|Horde_Mime_Exception|Horde_Imap_Client_Exception $e) {
throw new ServiceException(
'Could not load message',
$e->getCode(),
$e
);
}
}
/**
* @param Account $account
* @param Mailbox $mailbox
* @param int[] $uids
* @return IMAPMessage[]
* @throws ServiceException
*/
public function getImapMessagesForScheduleProcessing(Account $account,
Mailbox $mailbox,
array $uids): array {
$client = $this->imapClientFactory->getClient($account);
try {
return $this->imapMessageMapper->findByIds(
$client,
$mailbox->getName(),
$uids,
$account->getUserId(),
true
);
} catch (Horde_Imap_Client_Exception $e) {
throw new ServiceException(
'Could not load messages: ' . $e->getMessage(),
$e->getCode(),
$e
);
} finally {
$client->logout();
}
}
#[\Override]
public function getThread(Account $account, string $threadRootId): array {
return $this->dbMessageMapper->findThread($account, $threadRootId);
}
#[\Override]
public function getMessageIdForUid(Mailbox $mailbox, $uid): ?int {
return $this->dbMessageMapper->getIdForUid($mailbox, $uid);
}
#[\Override]
public function getMessage(string $uid, int $id): Message {
return $this->dbMessageMapper->findByUserId($uid, $id);
}
/**
* @param Horde_Imap_Client_Socket $client
* @param Account $account
* @param string $mailbox
* @param int $uid
*
* @return string
*
* @throws ServiceException
*/
#[\Override]
public function getSource(Horde_Imap_Client_Socket $client,
Account $account,
string $mailbox,
int $uid): ?string {
try {
return $this->imapMessageMapper->getFullText(
$client,
$mailbox,
$uid,
$account->getUserId(),
false,
);
} catch (Horde_Imap_Client_Exception|DoesNotExistException $e) {
throw new ServiceException('Could not load message', 0, $e);
}
}
/**
* @param Account $sourceAccount
* @param string $sourceFolderId
* @param int $uid
* @param Account $destinationAccount
* @param string $destFolderId
*
* @return ?int the new UID (or null if couldn't be determined)
* @throws ServiceException
*/
#[\Override]
public function moveMessage(Account $sourceAccount,
string $sourceFolderId,
int $uid,
Account $destinationAccount,
string $destFolderId): ?int {
if ($sourceAccount->getId() === $destinationAccount->getId()) {
try {
$sourceMailbox = $this->mailboxMapper->find($sourceAccount, $sourceFolderId);
} catch (DoesNotExistException $e) {
throw new ServiceException("Source mailbox $sourceFolderId does not exist", 0, $e);
}
$newUid = $this->moveMessageOnSameAccount(
$sourceAccount,
$sourceFolderId,
$destFolderId,
$uid
);
// Delete cached source message (the source imap message is copied and deleted)
$this->eventDispatcher->dispatch(
MessageDeletedEvent::class,
new MessageDeletedEvent($sourceAccount, $sourceMailbox, $uid)
);
return $newUid;
} else {
throw new ServiceException('It is not possible to move across accounts yet');
}
}
/**
* @throws ClientException
* @throws ServiceException
* @todo evaluate if we should sync mailboxes first
*/
#[\Override]
public function deleteMessage(Account $account,
string $mailboxId,
int $messageUid): void {
try {
$sourceMailbox = $this->mailboxMapper->find($account, $mailboxId);
} catch (DoesNotExistException $e) {
throw new ServiceException("Source mailbox $mailboxId does not exist", 0, $e);
}
$client = $this->imapClientFactory->getClient($account);
try {
$this->deleteMessageWithClient($account, $sourceMailbox, $messageUid, $client);
} finally {
$client->logout();
}
}
/**
* @throws ServiceException
* @throws ClientException
* @throws TrashMailboxNotSetException
*
* @todo evaluate if we should sync mailboxes first
*/
#[\Override]
public function deleteMessageWithClient(
Account $account,
Mailbox $mailbox,
int $messageUid,
Horde_Imap_Client_Socket $client,
): void {
$this->eventDispatcher->dispatchTyped(
new BeforeMessageDeletedEvent($account, $mailbox->getName(), $messageUid)
);
try {
$trashMailboxId = $account->getMailAccount()->getTrashMailboxId();
if ($trashMailboxId === null) {
throw new TrashMailboxNotSetException();
}
$trashMailbox = $this->mailboxMapper->findById($trashMailboxId);
} catch (DoesNotExistException $e) {
throw new ServiceException('No trash folder', 0, $e);
}
if ($mailbox->getName() === $trashMailbox->getName()) {
// Delete inside trash -> expunge
$this->imapMessageMapper->expunge(
$client,
$mailbox->getName(),
$messageUid
);
} else {
$this->imapMessageMapper->move(
$client,
$mailbox->getName(),
$messageUid,
$trashMailbox->getName()
);
}
$this->eventDispatcher->dispatchTyped(
new MessageDeletedEvent($account, $mailbox, $messageUid)
);
}
/**
* @param Account $account
* @param string $sourceFolderId
* @param string $destFolderId
* @param int $messageId
*
* @return ?int the new UID (or null if it couldn't be determined)
* @throws ServiceException
*
*/
private function moveMessageOnSameAccount(Account $account,
string $sourceFolderId,
string $destFolderId,
int $messageId): ?int {
$client = $this->imapClientFactory->getClient($account);
try {
return $this->imapMessageMapper->move($client, $sourceFolderId, $messageId, $destFolderId);
} finally {
$client->logout();
}
}
#[\Override]
public function markFolderAsRead(Account $account, Mailbox $mailbox): void {
$client = $this->imapClientFactory->getClient($account);
try {
$this->imapMessageMapper->markAllRead($client, $mailbox->getName());
} finally {
$client->logout();
}
}
#[\Override]
public function updateSubscription(Account $account, Mailbox $mailbox, bool $subscribed): Mailbox {
/**
* 1. Change subscription on IMAP
*/
$client = $this->imapClientFactory->getClient($account);
try {
$client->subscribeMailbox($mailbox->getName(), $subscribed);
/**
* 2. Pull changes into the mailbox database cache
*/
$this->mailboxSync->sync($account, $this->logger, true, $client);
} catch (Horde_Imap_Client_Exception $e) {
throw new ServiceException(
"Could not set subscription status for mailbox {$mailbox->getId()} on IMAP: {$e->getMessage()}",
$e->getCode(),
$e
);
} finally {
$client->logout();
}
/**
* 3. Return the updated object
*/
return $this->mailboxMapper->find($account, $mailbox->getName());
}
#[\Override]
public function enableMailboxBackgroundSync(Mailbox $mailbox,
bool $syncInBackground): Mailbox {
$mailbox->setSyncInBackground($syncInBackground);
return $this->mailboxMapper->update($mailbox);
}
#[\Override]
public function flagMessage(Account $account, string $mailbox, int $uid, string $flag, bool $value): void {
try {
$mb = $this->mailboxMapper->find($account, $mailbox);
} catch (DoesNotExistException $e) {
throw new ClientException("Mailbox $mailbox does not exist", 0, $e);
}
$client = $this->imapClientFactory->getClient($account);
try {
// Only send system flags to the IMAP server as other flags might not be supported
$imapFlags = $this->filterFlags($client, $account, $flag, $mailbox);
foreach ($imapFlags as $imapFlag) {
if (empty($imapFlag) === true) {
continue;
}
if ($value) {
$this->imapMessageMapper->addFlag($client, $mb, [$uid], $imapFlag);
} else {
$this->imapMessageMapper->removeFlag($client, $mb, [$uid], $imapFlag);
}
}
} catch (Horde_Imap_Client_Exception $e) {
throw new ServiceException(
'Could not set message flag on IMAP: ' . $e->getMessage(),
$e->getCode(),
$e
);
} finally {
$client->logout();
}
$this->eventDispatcher->dispatch(
MessageFlaggedEvent::class,
new MessageFlaggedEvent(
$account,
$mb,
$uid,
$flag,
$value
)
);
}
/**
* Tag (flag) multiple messages on IMAP using a given client instance
*
* @param Message[] $messages
*
* @throws ClientException
* @throws ServiceException
*/
public function tagMessagesWithClient(Horde_Imap_Client_Socket $client, Account $account, Mailbox $mailbox, array $messages, Tag $tag, bool $value, string $type = MessageTags::TYPE_USER):void {
if ($this->isPermflagsEnabled($client, $account, $mailbox->getName()) === true) {
$messageIds = array_map(static fn (Message $message) => $message->getUid(), $messages);
try {
if ($value) {
// imap keywords and flags work the same way
$this->imapMessageMapper->addFlag($client, $mailbox, $messageIds, $tag->getImapLabel());
} else {
$this->imapMessageMapper->removeFlag($client, $mailbox, $messageIds, $tag->getImapLabel());
}
} catch (Horde_Imap_Client_Exception $e) {
throw new ServiceException(
'Could not set message keyword on IMAP: ' . $e->getMessage(),
$e->getCode(),
$e
);
}
}
if ($value) {
foreach ($messages as $message) {
$this->tagMapper->tagMessage($tag, $message->getMessageId(), $account->getUserId(), $type);
}
} else {
foreach ($messages as $message) {
$this->tagMapper->untagMessage($tag, $message->getMessageId());
}
}
}
/**
* Tag (flag) a message on IMAP
*
* @param Account $account
* @param string $mailbox
* @param Message $message
* @param Tag $tag
* @param boolean $value
* @return void
*
* @throws ClientException
* @throws ServiceException
* @uses
*
* @link https://github.com/nextcloud/mail/issues/25
*/
#[\Override]
public function tagMessage(Account $account, string $mailbox, Message $message, Tag $tag, bool $value, string $type = MessageTags::TYPE_USER): void {
try {
$mb = $this->mailboxMapper->find($account, $mailbox);
} catch (DoesNotExistException $e) {
throw new ClientException("Mailbox $mailbox does not exist", 0, $e);
}
$client = $this->imapClientFactory->getClient($account);
try {
$this->tagMessagesWithClient($client, $account, $mb, [$message], $tag, $value, $type);
} finally {
$client->logout();
}
}
/**
* @param Account $account
*
* @return Quota|null
* @see https://tools.ietf.org/html/rfc2087
*/
#[\Override]
public function getQuota(Account $account): ?Quota {
/**
* Get all the quotas roots of the user's mailboxes
*/
$client = $this->imapClientFactory->getClient($account);
try {
$quotas = array_map(static fn (Folder $mb) => $client->getQuotaRoot($mb->getMailbox()), $this->folderMapper->getFolders($account, $client));
} catch (Horde_Imap_Client_Exception_NoSupportExtension $ex) {
return null;
} finally {
$client->logout();
}
/**
* Extract the 'storage' quota
*
* Falls back to 0/0 if this quota has no storage information
*
* @see https://tools.ietf.org/html/rfc2087#section-3
*/
$storageQuotas = array_map(static fn (array $root) => $root['storage'] ?? [
'usage' => 0,
'limit' => 0,
], array_merge(...array_values($quotas)));
if ($storageQuotas === []) {
// Nothing left to do, and array_merge doesn't like to be called with zero arguments.
return null;
}
/**
* Deduplicate identical quota roots
*/
$storage = array_merge(...array_values($storageQuotas));
return new Quota(
1024 * (int)($storage['usage'] ?? 0),
1024 * (int)($storage['limit'] ?? 0)
);
}
#[\Override]
public function renameMailbox(Account $account, Mailbox $mailbox, string $name): Mailbox {
/*
* 1. Rename on IMAP
*/
$client = $this->imapClientFactory->getClient($account);
try {
$this->folderMapper->renameFolder(
$client,
$mailbox->getName(),
$name
);
/**
* 2. Get the IMAP changes into our database cache
*/
$this->mailboxSync->sync($account, $this->logger, true, $client);
} finally {
$client->logout();
}
/**
* 3. Return the cached object with the new ID
*/
try {
return $this->mailboxMapper->find($account, $name);
} catch (DoesNotExistException $e) {
throw new ServiceException("The renamed mailbox $name does not exist", 0, $e);
}
}
/**
* @param Account $account
* @param Mailbox $mailbox
*
* @throws ServiceException
*/
#[\Override]
public function deleteMailbox(Account $account,
Mailbox $mailbox): void {
$client = $this->imapClientFactory->getClient($account);
try {
$this->folderMapper->delete($client, $mailbox->getName());
} finally {
$client->logout();
}
$this->mailboxMapper->delete($mailbox);
}
/**
* Clear messages in folder
*
* @param Account $account
* @param Mailbox $mailbox
*
* @throws DoesNotExistException
* @throws Horde_Imap_Client_Exception
* @throws Horde_Imap_Client_Exception_NoSupportExtension
* @throws ServiceException
*/
#[\Override]
public function clearMailbox(Account $account,
Mailbox $mailbox): void {
$client = $this->imapClientFactory->getClient($account);
$trashMailboxId = $account->getMailAccount()->getTrashMailboxId();
$currentMailboxId = $mailbox->getId();
try {
if (($currentMailboxId !== $trashMailboxId) && !is_null($trashMailboxId)) {
$trash = $this->mailboxMapper->findById($trashMailboxId);
$client->copy($mailbox->getName(), $trash->getName(), [
'move' => true
]);
} else {
$client->expunge($mailbox->getName(), [
'delete' => true
]);
}
$this->dbMessageMapper->deleteAll($mailbox);
} finally {
$client->logout();
}
}
/**
* @param Account $account
* @param Mailbox $mailbox
* @param Message $message
* @return Attachment[]
*/
#[\Override]
public function getMailAttachments(Account $account, Mailbox $mailbox, Message $message): array {
$client = $this->imapClientFactory->getClient($account);
try {
return $this->imapMessageMapper->getAttachments(
$client,
$mailbox->getName(),
$message->getUid(),
$account->getUserId(),
);
} finally {
$client->logout();
}
}
/**
* @param Account $account
* @param Mailbox $mailbox
* @param Message $message
* @param string $attachmentId
* @return Attachment
*
* @throws DoesNotExistException
* @throws Horde_Imap_Client_Exception
* @throws Horde_Imap_Client_Exception_NoSupportExtension
* @throws ServiceException
* @throws Horde_Mime_Exception
*/
#[\Override]
public function getMailAttachment(Account $account,
Mailbox $mailbox,
Message $message,
string $attachmentId): Attachment {
$client = $this->imapClientFactory->getClient($account);
try {
return $this->imapMessageMapper->getAttachment(
$client,
$mailbox->getName(),
$message->getUid(),
$attachmentId,
$account->getUserId(),
);
} finally {
$client->logout();
}
}
/**
* @param string $imapLabel
* @param string $userId
* @return Tag
* @throws ClientException
*/
#[\Override]
public function getTagByImapLabel(string $imapLabel, string $userId): Tag {
try {
return $this->tagMapper->getTagByImapLabel($imapLabel, $userId);
} catch (DoesNotExistException $e) {
throw new ClientException('Unknown Tag', 0, $e);
}
}
/**
* Filter out IMAP flags that aren't supported by the client server
*
* @param string $flag
* @param string $mailbox
* @return array
*/
public function filterFlags(Horde_Imap_Client_Socket $client, Account $account, string $flag, string $mailbox): array {
// check if flag is RFC defined system flag
if (array_key_exists($flag, self::SYSTEM_FLAGS) === true) {
return self::SYSTEM_FLAGS[$flag];
}
// check if server supports custom keywords / this specific keyword
try {
$capabilities = $client->status($mailbox, Horde_Imap_Client::STATUS_PERMFLAGS);
} catch (Horde_Imap_Client_Exception $e) {
throw new ServiceException(
'Could not get message flag options from IMAP: ' . $e->getMessage(),
$e->getCode(),
$e
);
}
// check if server returned supported flags
if (!isset($capabilities['permflags'])) {
return [];
}
// check if server supports custom flags or specific flag
if (in_array("\*", $capabilities['permflags']) || in_array($flag, $capabilities['permflags'])) {
return [$flag];
}
return [];
}
/**
* Check IMAP server for support for PERMANENTFLAGS
*
* @param Account $account
* @param string $mailbox
* @return boolean
*/
#[\Override]
public function isPermflagsEnabled(Horde_Imap_Client_Socket $client, Account $account, string $mailbox): bool {
try {
$capabilities = $client->status($mailbox, Horde_Imap_Client::STATUS_PERMFLAGS);
} catch (Horde_Imap_Client_Exception $e) {
throw new ServiceException(
'Could not get message flag options from IMAP: ' . $e->getMessage(),
$e->getCode(),
$e
);
}
return (is_array($capabilities) === true && array_key_exists('permflags', $capabilities) === true && in_array("\*", $capabilities['permflags'], true) === true);
}
#[\Override]
public function createTag(string $displayName, string $color, string $userId): Tag {
try {
$imapLabel = $this->imapFlag->create($displayName);
} catch (ImapFlagEncodingException $e) {
throw new ClientException('Error converting display name to UTF7-IMAP ', 0, $e);
}
try {
return $this->getTagByImapLabel($imapLabel, $userId);
} catch (ClientException $e) {
// it's valid that a tag does not exist.
}
$tag = new Tag();
$tag->setUserId($userId);
$tag->setDisplayName($displayName);
$tag->setImapLabel($imapLabel);
$tag->setColor($color);
$tag->setIsDefaultTag(false);
return $this->tagMapper->insert($tag);
}
#[\Override]
public function updateTag(int $id, string $displayName, string $color, string $userId): Tag {
try {
$tag = $this->tagMapper->getTagForUser($id, $userId);
} catch (DoesNotExistException $e) {
throw new ClientException('Tag not found', 0, $e);
}
$tag->setDisplayName($displayName);
$tag->setColor($color);
return $this->tagMapper->update($tag);
}
#[\Override]
public function deleteTag(int $id, string $userId, array $accounts) :Tag {
try {
$tag = $this->tagMapper->getTagForUser($id, $userId);
} catch (DoesNotExistException $e) {
throw new ClientException('Tag not found', 0, $e);
}
foreach ($accounts as $account) {
$this->deleteTagForAccount($id, $userId, $tag, $account);
}
return $this->tagMapper->delete($tag);
}
#[\Override]
public function deleteTagForAccount(int $id, string $userId, Tag $tag, Account $account) :void {
try {
$messageTags = $this->messageTagsMapper->getMessagesByTag($id);
$messages = array_merge(... array_map(fn ($messageTag) => $this->getByMessageId($account, $messageTag->getImapMessageId()), array_values($messageTags)));
} catch (DoesNotExistException $e) {
throw new ClientException('Messages not found', 0, $e);
}
$client = $this->imapClientFactory->getClient($account);
foreach ($messageTags as $messageTag) {
$this->messageTagsMapper->delete($messageTag);
}
$groupedMessages = [];
foreach ($messages as $message) {
$mailboxId = $message->getMailboxId();
if (array_key_exists($mailboxId, $groupedMessages)) {
$groupedMessages[$mailboxId][] = $message;
} else {
$groupedMessages[$mailboxId] = [$message];
}
}
try {
foreach ($groupedMessages as $mailboxId => $messages) {
$mailbox = $this->getMailbox($userId, $mailboxId);
$this->tagMessagesWithClient($client, $account, $mailbox, $messages, $tag, false);
}
} finally {
$client->logout();
}
}
#[\Override]
public function moveThread(Account $srcAccount, Mailbox $srcMailbox, Account $dstAccount, Mailbox $dstMailbox, string $threadRootId): array {
$mailAccount = $srcAccount->getMailAccount();
$messageInTrash = $srcMailbox->getId() === $mailAccount->getTrashMailboxId();
$messages = $this->threadMapper->findMessageUidsAndMailboxNamesByAccountAndThreadRoot(
$mailAccount,
$threadRootId,
$messageInTrash
);
$newUids = [];
foreach ($messages as $message) {
$this->logger->debug('move message', [
'messageId' => $message['messageUid'],
'srcMailboxId' => $srcMailbox->getId(),
'dstMailboxId' => $dstMailbox->getId()
]);
$newUid = $this->moveMessage(
$srcAccount,
$message['mailboxName'],
$message['messageUid'],
$dstAccount,
$dstMailbox->getName()
);
if ($newUid !== null) {
$newUids[] = $newUid;
}
}
return $newUids;
}
/**
* @throws ClientException
* @throws ServiceException
*/
#[\Override]
public function deleteThread(Account $account, Mailbox $mailbox, string $threadRootId): void {
$mailAccount = $account->getMailAccount();
$messageInTrash = $mailbox->getId() === $mailAccount->getTrashMailboxId();
$messages = $this->threadMapper->findMessageUidsAndMailboxNamesByAccountAndThreadRoot(
$mailAccount,
$threadRootId,
$messageInTrash
);
foreach ($messages as $message) {
$this->logger->debug('deleting message', [
'messageId' => $message['messageUid'],
'mailboxId' => $mailbox->getId(),
]);
$this->deleteMessage(
$account,
$message['mailboxName'],
$message['messageUid']
);
}
}
/**
* @return Message[]
*/
#[\Override]
public function getByMessageId(Account $account, string $messageId): array {
return $this->dbMessageMapper->findByMessageId($account, $messageId);
}
}