-
Notifications
You must be signed in to change notification settings - Fork 264
/
Copy pathMessageMapper.php
1008 lines (907 loc) Β· 29.5 KB
/
MessageMapper.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
declare(strict_types=1);
/**
* @author Christoph Wurst <[email protected]>
* @author Richard Steinmetz <[email protected]>
*
* Mail
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\Mail\IMAP;
use Horde_Imap_Client;
use Horde_Imap_Client_Base;
use Horde_Imap_Client_Data_Fetch;
use Horde_Imap_Client_Exception;
use Horde_Imap_Client_Exception_NoSupportExtension;
use Horde_Imap_Client_Fetch_Query;
use Horde_Imap_Client_Ids;
use Horde_Imap_Client_Search_Query;
use Horde_Imap_Client_Socket;
use Horde_Mime_Exception;
use Horde_Mime_Headers;
use Horde_Mime_Headers_ContentParam_ContentType;
use Horde_Mime_Headers_ContentTransferEncoding;
use Horde_Mime_Part;
use Html2Text\Html2Text;
use OCA\Mail\Attachment;
use OCA\Mail\Db\Mailbox;
use OCA\Mail\Exception\ServiceException;
use OCA\Mail\IMAP\Charset\Converter;
use OCA\Mail\Model\IMAPMessage;
use OCA\Mail\Service\SmimeService;
use OCA\Mail\Support\PerformanceLoggerTask;
use OCP\AppFramework\Db\DoesNotExistException;
use Psr\Log\LoggerInterface;
use function array_filter;
use function array_map;
use function count;
use function fclose;
use function in_array;
use function is_array;
use function iterator_to_array;
use function max;
use function min;
use function OCA\Mail\array_flat_map;
use function OCA\Mail\chunk_uid_sequence;
use function sprintf;
class MessageMapper {
/** @var LoggerInterface */
private $logger;
private SMimeService $smimeService;
private ImapMessageFetcherFactory $imapMessageFactory;
private Converter $converter;
public function __construct(LoggerInterface $logger,
SmimeService $smimeService,
ImapMessageFetcherFactory $imapMessageFactory,
Converter $converter) {
$this->logger = $logger;
$this->smimeService = $smimeService;
$this->imapMessageFactory = $imapMessageFactory;
$this->converter = $converter;
}
/**
* @return IMAPMessage
* @throws DoesNotExistException
* @throws Horde_Imap_Client_Exception
*/
public function find(Horde_Imap_Client_Base $client,
string $mailbox,
int $id,
string $userId,
bool $loadBody = false): IMAPMessage {
$result = $this->findByIds($client, $mailbox, new Horde_Imap_Client_Ids([$id]), $userId, $loadBody);
if (count($result) === 0) {
throw new DoesNotExistException("Message does not exist");
}
return $result[0];
}
/**
* @param Horde_Imap_Client_Socket $client
* @param string $mailbox
*
* @param int $maxResults
* @param int $highestKnownUid
* @param PerformanceLoggerTask $perf
*
* @return array
* @throws Horde_Imap_Client_Exception
*/
public function findAll(Horde_Imap_Client_Socket $client,
string $mailbox,
int $maxResults,
int $highestKnownUid,
LoggerInterface $logger,
PerformanceLoggerTask $perf,
string $userId): array {
/**
* To prevent memory exhaustion, we don't want to just ask for a list of
* all UIDs and limit them client-side. Instead, we can (hopefully
* efficiently) query the min and max UID as well as the number of
* messages. Based on that we assume that UIDs are somewhat distributed
* equally and build a page to fetch.
*
* This logic might return fewer or more results than $maxResults
*/
$metaResults = $client->search(
$mailbox,
null,
[
'results' => [
Horde_Imap_Client::SEARCH_RESULTS_MIN,
Horde_Imap_Client::SEARCH_RESULTS_MAX,
Horde_Imap_Client::SEARCH_RESULTS_COUNT,
]
]
);
$perf->step('mailbox meta search');
$min = (int) $metaResults['min'];
$total = (int) $metaResults['count'];
if ($total === 0) {
$perf->step('No data in mailbox');
// Nothing to fetch for this mailbox
return [
'messages' => [],
'all' => true,
'total' => $total,
];
}
// This can happen for iCloud
if ($metaResults['max'] === null) {
$uidnext = $client->status(
$mailbox
);
$perf->step('mailbox meta search for UIDNEXT');
$max = (int) $uidnext['uidnext'] - 1; // We need to subtract one for the last used UID
} else {
$max = ((int) $metaResults['max']);
}
// The inclusive range of UIDs
$totalRange = $max - $min + 1;
// Here we assume somewhat equally distributed UIDs
// +1 is added to fetch all messages with the rare case of strictly
// continuous UIDs and fractions
$estimatedPageSize = (int)(($totalRange / $total) * $maxResults) + 1;
// Determine min UID to fetch, but don't exceed the known maximum
$lower = max(
$min,
$highestKnownUid + 1
);
// Determine max UID to fetch, but don't exceed the known maximum
$upper = min(
$max,
$lower + $estimatedPageSize
);
if ($lower > $upper) {
$logger->debug("Range for findAll did not find any (not already known) messages and all messages of mailbox $mailbox have been fetched.");
return [
'messages' => [],
'all' => true,
'total' => 0,
];
}
$logger->debug("Built range for findAll: min=$min max=$max total=$total totalRange=$totalRange estimatedPageSize=$estimatedPageSize lower=$lower upper=$upper highestKnownUid=$highestKnownUid");
$query = new Horde_Imap_Client_Fetch_Query();
$query->uid();
$fetchResult = $client->fetch(
$mailbox,
$query,
[
'ids' => new Horde_Imap_Client_Ids($lower . ':' . $upper)
]
);
$perf->step('fetch UIDs');
if (count($fetchResult) === 0) {
/*
* There were no messages in this range.
* This means we should try again until there is a
* page that actually returns at least one message
*
* We take $upper as the lowest known UID as we just found out that
* there is nothing to fetch in $highestKnownUid:$upper
*/
$logger->debug("Range for findAll did not find any messages. Trying again with a succeeding range");
return $this->findAll($client, $mailbox, $maxResults, $upper, $logger, $perf, $userId);
}
$uidCandidates = array_filter(
array_map(
static function (Horde_Imap_Client_Data_Fetch $data) {
return $data->getUid();
},
iterator_to_array($fetchResult)
),
static function (int $uid) use ($highestKnownUid) {
// Don't load the ones we already know
return $uid > $highestKnownUid;
}
);
$uidsToFetch = array_slice(
$uidCandidates,
0,
$maxResults
);
$perf->step('calculate UIDs to fetch');
$highestUidToFetch = $uidsToFetch[count($uidsToFetch) - 1];
$logger->debug(sprintf("Range for findAll min=$min max=$max found %d messages, %d left after filtering. Highest UID to fetch is %d", count($uidCandidates), count($uidsToFetch), $highestUidToFetch));
$fetchRange = min($uidsToFetch) . ':' . max($uidsToFetch);
if ($highestUidToFetch === $max) {
$logger->debug("All messages of mailbox $mailbox have been fetched");
} else {
$logger->debug("Mailbox $mailbox has more messages to fetch: $fetchRange");
}
$messages = $this->findByIds(
$client,
$mailbox,
new Horde_Imap_Client_Ids($fetchRange),
$userId,
);
$perf->step('find IMAP messages by UID');
return [
'messages' => $messages,
'all' => $highestUidToFetch === $max,
'total' => $total,
];
}
/**
* @param Horde_Imap_Client_Base $client
* @param string $mailbox
* @param int[]|Horde_Imap_Client_Ids $ids
* @param string $userId
* @param bool $loadBody
* @return IMAPMessage[]
*
* @throws DoesNotExistException
* @throws Horde_Imap_Client_Exception
* @throws Horde_Imap_Client_Exception_NoSupportExtension
* @throws Horde_Mime_Exception
* @throws ServiceException
*/
public function findByIds(Horde_Imap_Client_Base $client,
string $mailbox,
$ids,
string $userId,
bool $loadBody = false): array {
$query = new Horde_Imap_Client_Fetch_Query();
$query->envelope();
$query->flags();
$query->uid();
$query->imapDate();
$query->headerText(
[
'cache' => true,
'peek' => true,
]
);
if (is_array($ids)) {
// Chunk to prevent overly long IMAP commands
/** @var Horde_Imap_Client_Data_Fetch[] $fetchResults */
$fetchResults = array_flat_map(function ($ids) use ($query, $mailbox, $client) {
return iterator_to_array($client->fetch($mailbox, $query, [
'ids' => $ids,
]), false);
}, chunk_uid_sequence($ids, 10000));
} else {
/** @var Horde_Imap_Client_Data_Fetch[] $fetchResults */
$fetchResults = iterator_to_array($client->fetch($mailbox, $query, [
'ids' => $ids,
]), false);
}
$fetchResults = array_values(array_filter($fetchResults, static function (Horde_Imap_Client_Data_Fetch $fetchResult) {
return $fetchResult->exists(Horde_Imap_Client::FETCH_ENVELOPE);
}));
if ($fetchResults === []) {
$this->logger->debug("findByIds in $mailbox got " . count($ids) . " UIDs but found none");
} else {
$minFetched = $fetchResults[0]->getUid();
$maxFetched = $fetchResults[count($fetchResults) - 1]->getUid();
if ($ids instanceof Horde_Imap_Client_Ids) {
$range = $ids->range_string;
} else {
$range = 'literals';
}
$this->logger->debug("findByIds in $mailbox got " . count($ids) . " UIDs ($range) and found " . count($fetchResults) . ". minFetched=$minFetched maxFetched=$maxFetched");
}
return array_map(function (Horde_Imap_Client_Data_Fetch $fetchResult) use ($client, $mailbox, $loadBody, $userId) {
return $this->imapMessageFactory
->build(
$fetchResult->getUid(),
$mailbox,
$client,
$userId,
)
->withBody($loadBody)
->fetchMessage($fetchResult);
}, $fetchResults);
}
/**
* @param Horde_Imap_Client_Base $client
* @param string $sourceFolderId
* @param int $messageId
* @param string $destFolderId
* @return int the new UID
*/
public function move(Horde_Imap_Client_Base $client,
string $sourceFolderId,
int $messageId,
string $destFolderId): int {
try {
$mapping = $client->copy($sourceFolderId, $destFolderId,
[
'ids' => new Horde_Imap_Client_Ids($messageId),
'move' => true,
'force_map' => true,
]);
return $mapping[$messageId];
} catch (Horde_Imap_Client_Exception $e) {
$this->logger->debug($e->getMessage(),
[
'exception' => $e,
]
);
throw new ServiceException(
"Could not move message $$messageId from $sourceFolderId to $destFolderId",
0,
$e
);
}
}
public function markAllRead(Horde_Imap_Client_Base $client,
string $mailbox): void {
$client->store($mailbox, [
'add' => [
[Horde_Imap_Client::FLAG_SEEN],
],
]);
}
/**
* @throws ServiceException
*/
public function expunge(Horde_Imap_Client_Base $client,
string $mailbox,
int $id): void {
try {
$client->expunge(
$mailbox,
[
'ids' => new Horde_Imap_Client_Ids([$id]),
'delete' => true,
]);
} catch (Horde_Imap_Client_Exception $e) {
$this->logger->debug($e->getMessage(),
[
'exception' => $e,
]
);
throw new ServiceException("Could not expunge message $id", 0, $e);
}
$this->logger->info("Message expunged: $id from mailbox $mailbox");
}
/**
* @throws Horde_Imap_Client_Exception
*/
public function save(Horde_Imap_Client_Socket $client,
Mailbox $mailbox,
string $mail,
array $flags = []): int {
$flags = array_merge([
Horde_Imap_Client::FLAG_SEEN,
], $flags);
$uids = $client->append(
$mailbox->getName(),
[
[
'data' => $mail,
'flags' => $flags,
]
]
);
return (int)$uids->current();
}
/**
* @throws Horde_Imap_Client_Exception
*/
public function addFlag(Horde_Imap_Client_Socket $client,
Mailbox $mailbox,
array $uids,
string $flag): void {
$client->store(
$mailbox->getName(),
[
'ids' => new Horde_Imap_Client_Ids($uids),
'add' => [$flag],
]
);
}
/**
* @throws Horde_Imap_Client_Exception
*/
public function removeFlag(Horde_Imap_Client_Socket $client,
Mailbox $mailbox,
array $uids,
string $flag): void {
$client->store(
$mailbox->getName(),
[
'ids' => new Horde_Imap_Client_Ids($uids),
'remove' => [$flag],
]
);
}
/**
* @param Horde_Imap_Client_Socket $client
* @param Mailbox $mailbox
* @param string $flag
* @return int[]
*
* @throws Horde_Imap_Client_Exception
*/
public function getFlagged(Horde_Imap_Client_Socket $client,
Mailbox $mailbox,
string $flag): array {
$query = new Horde_Imap_Client_Search_Query();
$query->flag($flag, true);
$messages = $client->search($mailbox->getName(), $query);
return $messages['match']->ids ?? [];
}
/**
* @param Horde_Imap_Client_Socket $client
* @param string $mailbox
* @param int $uid
* @param string $userId
* @param bool $decrypt
* @return string|null
*
* @throws ServiceException
*/
public function getFullText(Horde_Imap_Client_Socket $client,
string $mailbox,
int $uid,
string $userId,
bool $decrypt = true): ?string {
$query = new Horde_Imap_Client_Fetch_Query();
if ($decrypt) {
$this->smimeService->addDecryptQueries($query);
} else {
$query->fullText([ 'peek' => true ]);
}
try {
$result = $client->fetch($mailbox, $query, [
'ids' => new Horde_Imap_Client_Ids($uid),
]);
} catch (Horde_Imap_Client_Exception $e) {
throw new ServiceException(
"Could not fetch message source: " . $e->getMessage(),
$e->getCode(),
$e
);
}
if (($message = $result->first()) === null) {
return null;
}
if ($decrypt) {
return $this->smimeService->decryptDataFetch($message, $userId)->getDecryptedMessage();
}
return $message->getFullMsg();
}
/**
* @param Horde_Imap_Client_Socket $client
* @param string $mailbox
* @param int $uid
* @param string $userId
* @return string|null
*
* @throws DoesNotExistException
* @throws Horde_Imap_Client_Exception
* @throws Horde_Imap_Client_Exception_NoSupportExtension
* @throws Horde_Mime_Exception
* @throws ServiceException
*/
public function getHtmlBody(Horde_Imap_Client_Socket $client,
string $mailbox,
int $uid,
string $userId): ?string {
$messageQuery = new Horde_Imap_Client_Fetch_Query();
$messageQuery->envelope();
$messageQuery->structure();
$this->smimeService->addEncryptionCheckQueries($messageQuery, true);
$result = $client->fetch($mailbox, $messageQuery, [
'ids' => new Horde_Imap_Client_Ids([$uid]),
]);
if (($message = $result->first()) === null) {
throw new DoesNotExistException('Message does not exist');
}
$structure = $message->getStructure();
// Handle S/MIME encrypted message
if ($this->smimeService->isEncrypted($message)) {
// Encrypted messages have to be fully fetched in order to analyze the structure because
// it is hidden (obviously).
$fullText = $this->getFullText($client, $mailbox, $uid, $userId);
// Force mime parsing as decrypted S/MIME payload doesn't have to contain a MIME header
$mimePart = Horde_Mime_Part::parseMessage($fullText, ['forcemime' => true ]);
$htmlPartId = $mimePart->findBody('html');
if (!isset($mimePart[$htmlPartId])) {
return null;
}
return $mimePart[$htmlPartId];
}
$htmlPartId = $structure->findBody('html');
if ($htmlPartId === null) {
// No HTML part
return null;
}
$partsQuery = $this->buildAttachmentsPartsQuery($structure, [$htmlPartId]);
$parts = $client->fetch($mailbox, $partsQuery, [
'ids' => new Horde_Imap_Client_Ids([$uid]),
]);
foreach ($parts as $part) {
/** @var Horde_Imap_Client_Data_Fetch $part */
$body = $part->getBodyPart($htmlPartId);
if ($body !== null) {
$mimeHeaders = $part->getMimeHeader($htmlPartId, Horde_Imap_Client_Data_Fetch::HEADER_PARSE);
if ($enc = $mimeHeaders->getValue('content-transfer-encoding')) {
$structure->setTransferEncoding($enc);
}
$structure->setContents($body);
return $structure->getContents();
}
}
return null;
}
/**
* @deprecated Use getAttachments() instead
*
* @param Horde_Imap_Client_Socket $client
* @param string $mailbox
* @param int $uid
* @param string $userId
* @param array|null $attachmentIds
* @return array
*
* @throws DoesNotExistException
* @throws Horde_Imap_Client_Exception
* @throws Horde_Imap_Client_Exception_NoSupportExtension
* @throws Horde_Mime_Exception
* @throws ServiceException
*/
public function getRawAttachments(Horde_Imap_Client_Socket $client,
string $mailbox,
int $uid,
string $userId,
?array $attachmentIds = []): array {
$attachments = $this->getAttachments($client, $mailbox, $uid, $userId, $attachmentIds);
return array_map(static function (Attachment $attachment) {
return $attachment->getContent();
}, $attachments);
}
/**
* Get Attachments with size, content and name properties
*
* @param Horde_Imap_Client_Socket $client
* @param string $mailbox
* @param integer $uid
* @param string $userId
* @param array|null $attachmentIds
* @return Attachment[]
*
* @throws DoesNotExistException
* @throws Horde_Imap_Client_Exception
* @throws Horde_Imap_Client_Exception_NoSupportExtension
* @throws ServiceException
* @throws Horde_Mime_Exception
*/
public function getAttachments(Horde_Imap_Client_Socket $client,
string $mailbox,
int $uid,
string $userId,
?array $attachmentIds = []): array {
$uids = new Horde_Imap_Client_Ids([$uid]);
$messageQuery = new Horde_Imap_Client_Fetch_Query();
$messageQuery->structure();
$this->smimeService->addEncryptionCheckQueries($messageQuery);
$result = $client->fetch($mailbox, $messageQuery, ['ids' => $uids ]);
if (($structureResult = $result->first()) === null) {
throw new DoesNotExistException('Message does not exist');
}
$structure = $structureResult->getStructure();
$messageData = null;
$isEncrypted = $this->smimeService->isEncrypted($structureResult);
if ($isEncrypted) {
$fullTextQuery = new Horde_Imap_Client_Fetch_Query();
$this->smimeService->addDecryptQueries($fullTextQuery);
$fullTextParts = $client->fetch($mailbox, $fullTextQuery, ['ids' => $uids ]);
if (($fullTextResult = $fullTextParts->first()) === null) {
throw new DoesNotExistException('Message does not exist');
}
$decryptedText = $this->smimeService
->decryptDataFetch($fullTextResult, $userId)
->getDecryptedMessage();
// Replace opaque structure with decrypted structure
$structure = Horde_Mime_Part::parseMessage($decryptedText, [ 'forcemime' => true ]);
} else {
$partsQuery = $this->buildAttachmentsPartsQuery($structure, $attachmentIds);
$parts = $client->fetch($mailbox, $partsQuery, ['ids' => $uids ]);
if (($messageData = $parts->first()) === null) {
throw new DoesNotExistException('Message does not exist');
}
}
/** @var Attachment[] $attachments */
$attachments = [];
foreach ($structure->partIterator() as $key => $part) {
/** @var Horde_Mime_Part $part */
if (!$part->isAttachment()) {
continue;
}
if (!empty($attachmentIds) && !in_array($part->getMimeId(), $attachmentIds, true)) {
// We are looking for specific parts only and this is not one of them
continue;
}
// Encrypted parts were already decoded and their content can be used directly
if (!$isEncrypted) {
$stream = $messageData->getBodyPart($key, true);
$mimeHeaders = $messageData->getMimeHeader($key, Horde_Imap_Client_Data_Fetch::HEADER_PARSE);
if ($enc = $mimeHeaders->getValue('content-transfer-encoding')) {
$part->setTransferEncoding($enc);
}
/*
* usestream depends on transfer encoding
*
* Case 1: base64 encoded file
* Base64 stream is copied to a new stream and decoded using a convert.base64-decode stream filter.
*
* Case 2: text file (no transfer encoding)
* Existing stream is reused in Horde_Mime_Part.
*
* To handle both cases:
*
* 1) Horde_Mime_Part.clearContents to close the internal stream (Horde_Mime_Part._contents)
* 2) If $stream is still open, the data was transfer encoded, close it.
*
* Attachment.fromMimePart uses Horde_Mime_Part.getContents and Horde_Mime_Part.getBytes
* and therefore needs an open input stream.
*/
$part->setContents($stream, [
'usestream' => true
]);
$attachments[] = Attachment::fromMimePart($part);
$part->clearContents();
if (is_resource($stream)) {
fclose($stream);
}
} else {
$attachments[] = Attachment::fromMimePart($part);
$part->clearContents();
}
}
return $attachments;
}
/**
* @param Horde_Imap_Client_Base $client
* @param string $mailbox
* @param int $messageUid
* @param string $attachmentId
* @param string $userId
* @return Attachment
*
* @throws DoesNotExistException
* @throws Horde_Imap_Client_Exception
* @throws ServiceException
* @throws Horde_Mime_Exception
*/
public function getAttachment(Horde_Imap_Client_Base $client,
string $mailbox,
int $messageUid,
string $attachmentId,
string $userId): Attachment {
// TODO: compare logic and merge with getAttachments()
$query = new Horde_Imap_Client_Fetch_Query();
$query->bodyPart($attachmentId);
$query->mimeHeader($attachmentId);
$this->smimeService->addEncryptionCheckQueries($query);
$uids = new Horde_Imap_Client_Ids($messageUid);
$headers = $client->fetch($mailbox, $query, ['ids' => $uids]);
if (!isset($headers[$messageUid])) {
throw new DoesNotExistException('Unable to load the attachment.');
}
/** @var Horde_Imap_Client_Data_Fetch $fetch */
$fetch = $headers[$messageUid];
/** @var Horde_Mime_Headers $mimeHeaders */
$mimeHeaders = $fetch->getMimeHeader($attachmentId, Horde_Imap_Client_Data_Fetch::HEADER_PARSE);
$body = $fetch->getBodyPart($attachmentId);
$isEncrypted = $this->smimeService->isEncrypted($fetch);
if ($isEncrypted) {
$fullTextQuery = new Horde_Imap_Client_Fetch_Query();
$this->smimeService->addDecryptQueries($fullTextQuery);
$result = $client->fetch($mailbox, $fullTextQuery, ['ids' => $uids]);
if (!isset($result[$messageUid])) {
throw new DoesNotExistException('Unable to load the attachment.');
}
$fullTextResult = $result[$messageUid];
$decryptedText = $this->smimeService
->decryptDataFetch($fullTextResult, $userId)
->getDecryptedMessage();
$decryptedPart = Horde_Mime_Part::parseMessage($decryptedText, [ 'forcemime' => true ]);
if (!isset($decryptedPart[$attachmentId])) {
throw new DoesNotExistException('Unable to load the attachment.');
}
$attachmentPart = $decryptedPart[$attachmentId];
$body = $attachmentPart->getContents();
$mimeHeaders = $attachmentPart->addMimeHeaders();
}
$mimePart = new Horde_Mime_Part();
// Serve all files with a content-disposition of "attachment" to prevent Cross-Site Scripting
$mimePart->setDisposition('attachment');
// Extract headers from part
$contentDisposition = $mimeHeaders->getValue('content-disposition', Horde_Mime_Headers::VALUE_PARAMS);
if (!is_null($contentDisposition) && isset($contentDisposition['filename'])) {
$mimePart->setDispositionParameter('filename', $contentDisposition['filename']);
} else {
$contentDisposition = $mimeHeaders->getValue('content-type', Horde_Mime_Headers::VALUE_PARAMS);
if (isset($contentDisposition['name'])) {
$mimePart->setContentTypeParameter('name', $contentDisposition['name']);
}
}
// Content transfer encoding
// Decrypted parts are already decoded because they went through the MIME parser
if (!$isEncrypted && $tmp = $mimeHeaders->getValue('content-transfer-encoding')) {
$mimePart->setTransferEncoding($tmp);
}
/* Content type */
$contentType = $mimeHeaders->getValue('content-type');
if (!is_null($contentType) && str_contains($contentType, 'text/calendar')) {
$mimePart->setType('text/calendar');
if ($mimePart->getContentTypeParameter('name') === null) {
$mimePart->setContentTypeParameter('name', 'calendar.ics');
}
} else {
// To prevent potential problems with the SOP we serve all files but calendar entries with the
// MIME type "application/octet-stream"
$mimePart->setType('application/octet-stream');
}
$mimePart->setContents($body);
return Attachment::fromMimePart($mimePart);
}
/**
* Build the parts query for attachments
*
* @param Horde_Mime_Part $structure
* @param array $attachmentIds
* @return Horde_Imap_Client_Fetch_Query
*/
private function buildAttachmentsPartsQuery(Horde_Mime_Part $structure, array $attachmentIds) : Horde_Imap_Client_Fetch_Query {
$partsQuery = new Horde_Imap_Client_Fetch_Query();
$partsQuery->fullText();
foreach ($structure->partIterator() as $part) {
/** @var Horde_Mime_Part $part */
if ($part->getMimeId() === '0') {
// Ignore message header
continue;
}
if ($attachmentIds !== [] && !in_array($part->getMimeId(), $attachmentIds, true)) {
// We are looking for specific parts only and this is not one of them
continue;
}
$partsQuery->bodyPart($part->getMimeId(), [
'peek' => true,
]);
$partsQuery->mimeHeader($part->getMimeId(), [
'peek' => true
]);
$partsQuery->bodyPartSize($part->getMimeId());
}
return $partsQuery;
}
/**
* @param Horde_Imap_Client_Socket $client
* @param int[] $uids
*
* @return MessageStructureData[]
* @throws Horde_Imap_Client_Exception
*/
public function getBodyStructureData(Horde_Imap_Client_Socket $client,
string $mailbox,
array $uids): array {
$structureQuery = new Horde_Imap_Client_Fetch_Query();
$structureQuery->structure();
$structureQuery->headerText([
'cache' => true,
'peek' => true,
]);
$this->smimeService->addEncryptionCheckQueries($structureQuery);
$structures = $client->fetch($mailbox, $structureQuery, [
'ids' => new Horde_Imap_Client_Ids($uids),
]);
return array_map(function (Horde_Imap_Client_Data_Fetch $fetchData) use ($mailbox, $client) {
$hasAttachments = false;
$text = '';
$isImipMessage = false;
$isEncrypted = false;
if ($this->smimeService->isEncrypted($fetchData)) {
$isEncrypted = true;
}
$structure = $fetchData->getStructure();
/** @var Horde_Mime_Part $part */
foreach ($structure->getParts() as $part) {
if ($part->isAttachment()) {
$hasAttachments = true;
}
$bodyParts = $part->getParts();
/** @var Horde_Mime_Part $bodyPart */
foreach ($bodyParts as $bodyPart) {
$contentParameters = $bodyPart->getAllContentTypeParameters();
if ($bodyPart->getType() === 'text/calendar' && isset($contentParameters['method'])) {
$isImipMessage = true;
}
}
}
$textBodyId = $structure->findBody() ?? $structure->findBody('text');
$htmlBodyId = $structure->findBody('html');
if ($textBodyId === null && $htmlBodyId === null) {
return new MessageStructureData($hasAttachments, $text, $isImipMessage, $isEncrypted);
}
$partsQuery = new Horde_Imap_Client_Fetch_Query();
if ($htmlBodyId !== null) {
$partsQuery->bodyPart($htmlBodyId, [
'peek' => true,
]);
$partsQuery->mimeHeader($htmlBodyId, [
'peek' => true
]);
}
if ($textBodyId !== null) {
$partsQuery->bodyPart($textBodyId, [
'peek' => true,
]);
$partsQuery->mimeHeader($textBodyId, [
'peek' => true
]);
}
$parts = $client->fetch($mailbox, $partsQuery, [
'ids' => new Horde_Imap_Client_Ids([$fetchData->getUid()]),
]);
/** @var Horde_Imap_Client_Data_Fetch $part */
$part = $parts[$fetchData->getUid()];
// This is sus - why does this even happen? A delete / move in the middle of this processing?
if ($part === null) {
return new MessageStructureData($hasAttachments, $text, $isImipMessage, $isEncrypted);
}
// Convert a given binary body to utf-8 according to the transfer encoding and content
// type headers of the underlying MIME part
$convertBody = function (string $body, Horde_Mime_Headers $mimeHeaders) use ($structure): string {
/** @var Horde_Mime_Headers_ContentParam_ContentType $contentType */
$contentType = $mimeHeaders->getHeader('content-type');
/** @var Horde_Mime_Headers_ContentTransferEncoding $transferEncoding */
$transferEncoding = $mimeHeaders->getHeader('content-transfer-encoding');
if (!$contentType && !$transferEncoding) {
// Nothing to convert here ...
return $body;
}
if ($transferEncoding) {
$structure->setTransferEncoding($transferEncoding->value_single);
}
if ($contentType) {
$structure->setType($contentType->value_single);
if (isset($contentType['charset'])) {
$structure->setCharset($contentType['charset']);
}
}
$structure->setContents($body);
return $this->converter->convert($structure);
};
$htmlBody = ($htmlBodyId !== null) ? $part->getBodyPart($htmlBodyId) : null;
if (!empty($htmlBody)) {
$mimeHeaders = $part->getMimeHeader($htmlBodyId, Horde_Imap_Client_Data_Fetch::HEADER_PARSE);
$htmlBody = $convertBody($htmlBody, $mimeHeaders);
$html = new Html2Text($htmlBody, ['do_links' => 'none','alt_image' => 'hide']);
return new MessageStructureData(
$hasAttachments,
trim($html->getText()),
$isImipMessage,
$isEncrypted,
);
}
$textBody = $part->getBodyPart($textBodyId);
if (!empty($textBody)) {
$mimeHeaders = $part->getMimeHeader($textBodyId, Horde_Imap_Client_Data_Fetch::HEADER_PARSE);
$textBody = $convertBody($textBody, $mimeHeaders);
return new MessageStructureData(
$hasAttachments,
$textBody,