-
Notifications
You must be signed in to change notification settings - Fork 2
/
Module.php
2832 lines (2495 loc) · 107 KB
/
Module.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
/**
* This code is licensed under AGPLv3 license or Afterlogic Software License
* if commercial version of the product was purchased.
* For full statements of the licenses see LICENSE-AFTERLOGIC and LICENSE-AGPL3 files.
*/
namespace Aurora\Modules\Contacts;
use Afterlogic\DAV\Backend;
use Afterlogic\DAV\Constants;
use Aurora\Api;
use Aurora\Modules\Contacts\Enums\Access;
use Aurora\Modules\Contacts\Enums\StorageType;
use Aurora\Modules\Contacts\Enums\SortField;
use Aurora\System\Enums\SortOrder;
use Aurora\Modules\Contacts\Classes\Contact;
use Aurora\Modules\Contacts\Classes\VCard\Helper;
use Aurora\Modules\Contacts\Models\ContactCard;
use Aurora\Modules\Contacts\Classes\Group;
use Aurora\Modules\Core\Module as CoreModule;
use Aurora\System\Exceptions\ApiException;
use Aurora\System\Notifications;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Capsule\Manager as Capsule;
use Sabre\DAV\UUIDUtil;
use Sabre\DAV\PropPatch;
/**
* @license https://www.gnu.org/licenses/agpl-3.0.html AGPL-3.0
* @license https://afterlogic.com/products/common-licensing Afterlogic Software License
* @copyright Copyright (c) 2023, Afterlogic Corp.
*
* @property Settings $oModuleSettings
*
* @package Modules
*/
class Module extends \Aurora\System\Module\AbstractModule
{
protected $aImportExportFormats = ['csv', 'vcf'];
protected $userPublicIdToDelete = null;
/**
* @return Module
*/
public static function getInstance()
{
return parent::getInstance();
}
/**
* @return Module
*/
public static function Decorator()
{
return parent::Decorator();
}
/**
* @return Settings
*/
public function getModuleSettings()
{
return $this->oModuleSettings;
}
/**
* Initializes Contacts Module.
*
* @ignore
*/
public function init()
{
$this->subscribeEvent('Mail::AfterUseEmails', array($this, 'onAfterUseEmails'));
$this->subscribeEvent('Mail::GetBodyStructureParts', array($this, 'onGetBodyStructureParts'));
$this->subscribeEvent('Core::DeleteUser::before', array($this, 'onBeforeDeleteUser'));
$this->subscribeEvent('Core::DeleteUser::after', array($this, 'onAfterDeleteUser'));
$this->subscribeEvent('System::toResponseArray::after', array($this, 'onContactToResponseArray'));
$this->denyMethodsCallByWebApi([
'UpdateContactObject',
'CheckAccessToAddressBook',
'CheckAccessToObject'
]);
}
/***** public functions might be called with web API *****/
/**
* @apiDefine Contacts Contacts Module
* Main Contacts module. It provides PHP and Web APIs for managing contacts.
*/
/**
* @api {post} ?/Api/ GetSettings
* @apiName GetSettings
* @apiGroup Contacts
* @apiDescription Obtains list of module settings for authenticated user.
*
* @apiHeader {string} [Authorization] "Bearer " + Authentication token which was received as the result of Core.Login method.
* @apiHeaderExample {json} Header-Example:
* {
* "Authorization": "Bearer 32b2ecd4a4016fedc4abee880425b6b8"
* }
*
* @apiParam {string=Contacts} Module Module name
* @apiParam {string=GetSettings} Method Method name
*
* @apiParamExample {json} Request-Example:
* {
* Module: 'Contacts',
* Method: 'GetSettings'
* }
*
* @apiSuccess {object[]} Result Array of response objects.
* @apiSuccess {string} Result.Module Module name.
* @apiSuccess {string} Result.Method Method name.
* @apiSuccess {mixed} Result.Result List of module settings in case of success, otherwise **false**.
* @apiSuccess {int} Result.Result.ContactsPerPage=20 Count of contacts that will be displayed on one page.
* @apiSuccess {string} Result.Result.ImportContactsLink="" Link for learning more about CSV format.
* @apiSuccess {array} Result.Result.Storages='[]' List of storages wich will be shown in the interface.
* @apiSuccess {array} Result.Result.ImportExportFormats='[]' List of formats that can be used for import and export contacts.
* @apiSuccess {array} Result.Result.\Aurora\Modules\Contacts\Enums\PrimaryEmail='[]' Enumeration with primary email values.
* @apiSuccess {array} Result.Result.\Aurora\Modules\Contacts\Enums\PrimaryPhone='[]' Enumeration with primary phone values.
* @apiSuccess {array} Result.Result.\Aurora\Modules\Contacts\Enums\PrimaryAddress='[]' Enumeration with primary address values.
* @apiSuccess {array} Result.Result.\Aurora\Modules\Contacts\Enums\SortField='[]' Enumeration with sort field values.
* @apiSuccess {int} [Result.ErrorCode] Error code
*
* @apiSuccessExample {json} Success response example:
* {
* Module: 'Contacts',
* Method: 'GetSettings',
* Result: { ContactsPerPage: 20, ImportContactsLink: '', Storages: ['personal', 'team'],
* ImportExportFormats: ['csv', 'vcf'], \Aurora\Modules\Contacts\Enums\PrimaryEmail: {'Personal': 0, 'Business': 1, 'Other': 2},
* \Aurora\Modules\Contacts\Enums\PrimaryPhone: {'Mobile': 0, 'Personal': 1, 'Business': 2},
* \Aurora\Modules\Contacts\Enums\PrimaryAddress: {'Personal': 0, 'Business': 1},
* \Aurora\Modules\Contacts\Enums\SortField: {'Name': 1, 'Email': 2, 'Frequency': 3} }
* }
*
* @apiSuccessExample {json} Error response example:
* {
* Module: 'Contacts',
* Method: 'GetSettings',
* Result: false,
* ErrorCode: 102
* }
*/
/**
* Obtains list of module settings for authenticated user.
* @return array
*/
public function GetSettings()
{
\Aurora\System\Api::checkUserRoleIsAtLeast(\Aurora\System\Enums\UserRole::NormalUser);
$oUser = \Aurora\System\Api::getAuthenticatedUser();
$aResult = [
'AllowAddressBooksManagement' => $this->oModuleSettings->AllowAddressBooksManagement,
'ImportContactsLink' => $this->oModuleSettings->ImportContactsLink,
'PrimaryEmail' => (new Enums\PrimaryEmail())->getMap(),
'PrimaryPhone' => (new Enums\PrimaryPhone())->getMap(),
'PrimaryAddress' => (new Enums\PrimaryAddress())->getMap(),
'SortField' => (new SortField())->getMap(),
'ImportExportFormats' => $this->aImportExportFormats,
'SaveVcfServerModuleName' => \Aurora\System\Api::GetModuleManager()->ModuleExists('DavContacts') ? 'DavContacts' : '',
'ContactsPerPage' => $this->oModuleSettings->ContactsPerPage,
'ContactsSortBy' => $this->oModuleSettings->ContactsSortBy
];
if ($oUser && $oUser->isNormalOrTenant()) {
if (null !== $oUser->getExtendedProp(self::GetName() . '::ContactsPerPage')) {
$aResult['ContactsPerPage'] = $oUser->getExtendedProp(self::GetName() . '::ContactsPerPage');
}
$aResult['Storages'] = self::Decorator()->GetStorages();
}
return $aResult;
}
public function IsDisplayedStorage($Storage)
{
return true;
}
/**
* @deprecated since version 9.7.2
*/
public function GetContactStorages()
{
return $this->Decorator()->GetStorages();
}
public function GetStorageDisplayName($Storage)
{
$result = '';
switch($Storage) {
case Enums\StorageType::All:
$result = $this->i18N('LABEL_STORAGE_ALL');
break;
case Enums\StorageType::Personal:
$result = $this->i18N('LABEL_STORAGE_PERSONAL');
break;
case Enums\StorageType::Collected:
$result = $this->i18N('LABEL_STORAGE_COLLECTED');
break;
case Enums\StorageType::Team:
$result = $this->i18N('LABEL_STORAGE_TEAM');
break;
case Enums\StorageType::Shared:
$result = $this->i18N('LABEL_STORAGE_SHARED');
break;
}
return $result;
}
protected function GetStorageDisplayNameOverride($sStorageName, $sSotrageId)
{
$result = $sStorageName;
switch(true) {
case $sSotrageId === Enums\StorageType::Personal && $sStorageName === Constants::ADDRESSBOOK_DEFAULT_DISPLAY_NAME:
$result = $this->i18N('LABEL_STORAGE_PERSONAL');
break;
case $sSotrageId === Enums\StorageType::Collected && $sStorageName === Constants::ADDRESSBOOK_COLLECTED_DISPLAY_NAME:
$result = $this->i18N('LABEL_STORAGE_COLLECTED');
break;
case $sSotrageId === Enums\StorageType::Team && $sStorageName === Constants::ADDRESSBOOK_TEAM_DISPLAY_NAME:
$result = $this->i18N('LABEL_STORAGE_TEAM');
break;
case $sSotrageId === Enums\StorageType::Shared && $sStorageName === Constants::ADDRESSBOOK_SHARED_WITH_ALL_DISPLAY_NAME:
$result = $this->i18N('LABEL_STORAGE_SHARED');
break;
}
return $result;
}
public function GetStorages()
{
\Aurora\System\Api::checkUserRoleIsAtLeast(\Aurora\System\Enums\UserRole::NormalUser);
$iUserId = \Aurora\System\Api::getAuthenticatedUserId();
$aAddressBooks = $this->Decorator()->GetAddressBooks($iUserId);
foreach ($aAddressBooks as &$oAddressBook) {
$oAddressBook['DisplayName'] = $this->GetStorageDisplayNameOverride($oAddressBook['DisplayName'], $oAddressBook['Id']);
}
$aStoragesOrder = [
StorageType::Personal,
StorageType::Collected,
StorageType::Shared,
StorageType::Team
];
return $this->sortAddressBooks($aAddressBooks, $aStoragesOrder);
}
protected function sortAddressBooks($aAddressBooks, $aOrder = [])
{
$priority_books = array();
$non_priority_books = array();
// Loop through the address books and check their ids
foreach ($aAddressBooks as $book) {
$id = $book['Id'];
if (in_array($id, $aOrder)) {
$priority_books[] = $book;
} else {
$non_priority_books[] = $book;
}
}
// Sort the priority books array by the order of the priority ids array
usort($priority_books, function ($a, $b) use ($aOrder) {
// Get the index of the ids in the priority ids array
$index_a = array_search($a['Id'], $aOrder);
$index_b = array_search($b['Id'], $aOrder);
// Compare the indexes
return $index_a - $index_b;
});
// Sort the non-priority books array by the DisplayName property in ascending order
usort($non_priority_books, function ($a, $b) {
// Compare the names
return strcmp($a['DisplayName'], $b['DisplayName']);
});
// Merge the two arrays and return the result
return array_merge($priority_books, $non_priority_books);
}
protected function getContactsCollection($iSortField = SortField::Name, $iSortOrder = SortOrder::ASC, $iOffset = 0, $iLimit = 20, $oFilters = null)
{
$sSortField = 'FullName';
$sSortFieldSecond = 'ViewEmail';
$sSortOrder = $iSortOrder === SortOrder::ASC ? 'asc' : 'desc';
switch ($iSortField) {
case SortField::Email:
$sSortField = 'ViewEmail';
$sSortFieldSecond = 'FullName';
break;
case SortField::Frequency:
$sSortField = 'AgeScore';
// $oFilters->select(Capsule::connection()->raw('*, (Frequency/CEIL(DATEDIFF(CURDATE() + INTERVAL 1 DAY, DateModified)/30)) as AgeScore'));
break;
case SortField::FirstName:
$sSortField = 'FirstName';
break;
case SortField::LastName:
$sSortField = 'LastName';
break;
case SortField::Name:
$sSortField = 'FullName';
break;
}
if ($iOffset > 0) {
$oFilters->offset($iOffset);
}
if ($iLimit > 0) {
$oFilters->limit($iLimit);
}
$oFilters
->orderBy(Capsule::connection()->raw("CASE WHEN `$sSortField` = '' THEN 1 ELSE 0 END"))
->orderBy($sSortField, $sSortOrder)
->orderBy($sSortFieldSecond, $sSortOrder)
;
return $oFilters->get();
}
/**
* Resolve addressbooks numeric ids to text text ids
*
* @param mixed $oUser
* @param mixed $aContactsCollection
* @return void
*/
protected function resolveAddressbooksIdsForContacts($oUser, &$aContactsCollection)
{
$aAddressbooksMap = self::Decorator()->GetStoragesMapToAddressbooks();
$aAddressBooks = [];
$aPersonalAddressBooks = Backend::Carddav()->getAddressBooksForUser(Constants::PRINCIPALS_PREFIX . $oUser->PublicId);
foreach ($aPersonalAddressBooks as $oAddressBook) {
$aAddressBooks[$oAddressBook['id']] = $oAddressBook;
}
$aContactsCollection->each(function (&$contact) use ($aAddressBooks, $aAddressbooksMap) {
$contact->UUID = (string) $contact->UUID;
if (!isset($aAddressBooks[$contact->Storage])) {
$aAddressBooks[$contact->Storage] = Backend::Carddav()->getAddressBookById($contact->Storage);
}
$StorageTextId = false;
if ($aAddressBooks[$contact->Storage]) {
$StorageTextId = array_search($aAddressBooks[$contact->Storage]['uri'], $aAddressbooksMap);
}
$contact->AddressBookId = (int) $contact->Storage;
$contact->Storage = $StorageTextId ? $StorageTextId : (StorageType::AddressBook . '-' . $contact->Storage);
});
}
/**
* @api {post} ?/Api/ UpdateSettings
* @apiName UpdateSettings
* @apiGroup Contacts
* @apiDescription Updates module's settings - saves them to config.json file.
*
* @apiHeader {string} Authorization "Bearer " + Authentication token which was received as the result of Core.Login method.
* @apiHeaderExample {json} Header-Example:
* {
* "Authorization": "Bearer 32b2ecd4a4016fedc4abee880425b6b8"
* }
*
* @apiParam {string=Contacts} Module Module name
* @apiParam {string=UpdateSettings} Method Method name
* @apiParam {string} Parameters JSON.stringified object <br>
* {<br>
*   **ContactsPerPage** *int* Count of contacts per page.<br>
* }
*
* @apiParamExample {json} Request-Example:
* {
* Module: 'Contacts',
* Method: 'UpdateSettings',
* Parameters: '{ ContactsPerPage: 10 }'
* }
*
* @apiSuccess {object[]} Result Array of response objects.
* @apiSuccess {string} Result.Module Module name
* @apiSuccess {string} Result.Method Method name
* @apiSuccess {bool} Result.Result Indicates if settings were updated successfully.
* @apiSuccess {int} [Result.ErrorCode] Error code
*
* @apiSuccessExample {json} Success response example:
* {
* Module: 'Contacts',
* Method: 'UpdateSettings',
* Result: true
* }
*
* @apiSuccessExample {json} Error response example:
* {
* Module: 'Contacts',
* Method: 'UpdateSettings',
* Result: false,
* ErrorCode: 102
* }
*/
/**
* Updates module's settings - saves them to config.json file or to user settings in db.
* @param int $ContactsPerPage Count of contacts per page.
* @return boolean
*/
public function UpdateSettings($ContactsPerPage)
{
\Aurora\System\Api::checkUserRoleIsAtLeast(\Aurora\System\Enums\UserRole::NormalUser);
$bResult = false;
$oUser = \Aurora\System\Api::getAuthenticatedUser();
if ($oUser) {
if ($oUser->isNormalOrTenant()) {
$oUser->setExtendedProp(self::GetName() . '::ContactsPerPage', $ContactsPerPage);
return CoreModule::Decorator()->UpdateUserObject($oUser);
}
if ($oUser->isAdmin()) {
$this->setConfig('ContactsPerPage', $ContactsPerPage);
$bResult = $this->saveModuleConfig();
}
}
return $bResult;
}
/**
* @api {post} ?/Api/ Export
* @apiName Export
* @apiGroup Contacts
* @apiDescription Exports specified contacts to a file with specified format.
*
* @apiHeader {string} Authorization "Bearer " + Authentication token which was received as the result of Core.Login method.
* @apiHeaderExample {json} Header-Example:
* {
* "Authorization": "Bearer 32b2ecd4a4016fedc4abee880425b6b8"
* }
*
* @apiParam {string=Contacts} Module Module name
* @apiParam {string=Export} Method Method name
* @apiParam {string} Parameters JSON.stringified object <br>
* {<br>
*   **Format** *string* File format that should be used for export.<br>
*   **Filters** *array* Filters for obtaining specified contacts.<br>
*   **GroupUUID** *string* UUID of group that should contain contacts for export.<br>
*   **ContactUUIDs** *array* List of UUIDs of contacts that should be exported.<br>
* }
*
* @apiParamExample {json} Request-Example:
* {
* Module: 'Contacts',
* Method: 'Export',
* Parameters: '{ Format: "csv", Filters: [], GroupUUID: "", ContactUUIDs: [] }'
* }
*
* @apiSuccess {object[]} Result Array of response objects.
* @apiSuccess {string} Result.Module Module name
* @apiSuccess {string} Result.Method Method name
* @apiSuccess {mixed} Result.Result Contents of CSV or VCF file in case of success, otherwise **false**.
* @apiSuccess {int} [Result.ErrorCode] Error code
*
* @apiSuccessExample {json} Success response example:
* contents of CSV or VCF file
*
* @apiSuccessExample {json} Error response example:
* {
* Module: 'Contacts',
* Method: 'Export',
* Result: false,
* ErrorCode: 102
* }
*/
/**
* Exports specified contacts to a file with specified format.
* @param string $Format File format that should be used for export.
* @param Builder $Filters Filters for obtaining specified contacts.
* @param string $GroupUUID UUID of group that should contain contacts for export.
* @param array $ContactUUIDs List of UUIDs of contacts that should be exported.
* @param bool $AddressBookId
*/
public function Export($UserId, $Storage, $Format, Builder $Filters = null, $GroupUUID = '', $ContactUUIDs = [], $AddressBookId = null)
{
Api::CheckAccess($UserId);
\Aurora\System\Api::checkUserRoleIsAtLeast(\Aurora\System\Enums\UserRole::NormalUser);
$sOutput = '';
if (!empty($GroupUUID)) {
$oGroup = self::Decorator()->GetGroup($UserId, $GroupUUID);
if ($oGroup) {
$ContactUUIDs = (is_array($ContactUUIDs) && count($ContactUUIDs) > 0) ? array_intersect(
$oGroup->Contacts,
$ContactUUIDs
) : $oGroup->Contacts;
}
}
if (is_array($ContactUUIDs)) {
$query = $this->getGetContactsQueryBuilder($UserId, $Storage, $AddressBookId, $Filters, false, true);
if ($Format === 'vcf') {
if (count($ContactUUIDs) > 0) {
$query = $query->whereIn('contacts_cards.CardId', $ContactUUIDs);
}
$rows = $query->select('carddata')->pluck('carddata')->toArray();
foreach ($rows as $row) {
$sOutput .= $row;
}
} elseif ($Format === 'csv') {
$oSync = new Classes\Csv\Sync();
if (count($ContactUUIDs) === 0) {
$ContactUUIDs = $query->select('CardId')->pluck('CardId')->toArray();
}
$aContacts = self::Decorator()->GetContactsByUids($UserId, $ContactUUIDs);
$sOutput = $oSync->Export($aContacts);
}
}
if (is_string($sOutput) && !empty($sOutput)) {
$fileName = 'export';
$aStorages = self::Decorator()->GetStorages();
foreach ($aStorages as $aStorage) {
if ($aStorage['Id'] === $Storage) {
$fileName = isset($aStorage['DisplayName']) ? $aStorage['DisplayName'] : $aStorage['Id'];
break;
}
}
header('Pragma: public');
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . $fileName . '.' . $Format . '";');
header('Content-Transfer-Encoding: binary');
}
echo $sOutput;
}
public function GetContactAsVCF($UserId, $Contact)
{
Api::CheckAccess($UserId);
$oVCard = new \Sabre\VObject\Component\VCard();
Classes\VCard\Helper::UpdateVCardFromContact($Contact, $oVCard);
return $oVCard->serialize();
}
/**
* @api {post} ?/Api/ GetGroups
* @apiName GetGroups
* @apiGroup Contacts
* @apiDescription Returns all groups for authenticated user.
*
* @apiHeader {string} Authorization "Bearer " + Authentication token which was received as the result of Core.Login method.
* @apiHeaderExample {json} Header-Example:
* {
* "Authorization": "Bearer 32b2ecd4a4016fedc4abee880425b6b8"
* }
*
* @apiParam {string=Contacts} Module Module name
* @apiParam {string=GetGroups} Method Method name
*
* @apiParamExample {json} Request-Example:
* {
* Module: 'Contacts',
* Method: 'GetGroups'
* }
*
* @apiSuccess {object[]} Result Array of response objects.
* @apiSuccess {string} Result.Module Module name
* @apiSuccess {string} Result.Method Method name
* @apiSuccess {mixed} Result.Result List of groups in case of success, otherwise **false**.
* @apiSuccess {int} [Result.ErrorCode] Error code
*
* @apiSuccessExample {json} Success response example:
* {
* Module: 'Contacts',
* Method: 'GetGroups',
* Result: [{ City: '', Company: '', Contacts: [], Country: '', Email: '', Fax: '', IdUser: 3,
* IsOrganization: false, Name: 'group_name', Phone: '', State: '', Street: '', UUID: 'uuid_value',
* Web: '', Zip: '' }]
* }
*
* @apiSuccessExample {json} Error response example:
* {
* Module: 'Contacts',
* Method: 'GetGroups',
* Result: false,
* ErrorCode: 102
* }
*/
/**
* Returns all groups for authenticated user.
* @return array
*/
public function GetGroups($UserId = null, $UUIDs = [], $Search = '')
{
$result = [];
\Aurora\System\Api::checkUserRoleIsAtLeast(\Aurora\System\Enums\UserRole::NormalUser);
Api::CheckAccess($UserId);
$aArgs = [
'UserId' => $UserId,
'Storage' => StorageType::Personal,
'AddressBookId' => 0
];
if ($this->populateContactArguments($aArgs)) {
$query = Capsule::connection()->table('contacts_cards')
->join('adav_cards', 'contacts_cards.CardId', '=', 'adav_cards.id')
->select('adav_cards.id as card_id', 'carddata');
$query->where(function ($whereQuery) use ($UserId, $aArgs, $query) {
$this->prepareFiltersFromStorage($UserId, StorageType::Personal, $aArgs['AddressBookId'], $query, $whereQuery);
})->where('IsGroup', true);
if (is_array($UUIDs) && count($UUIDs) > 0) {
$query->whereIn('adav_cards.id', $UUIDs);
}
if (!empty($Search)) {
$query->where('FullName', 'LIKE', "%$Search%");
}
$groups = $query->get();
foreach ($groups as $group) {
$groupObj = new Group();
$groupObj->Id = (int) $group->card_id;
$groupObj->IdUser = $UserId;
$groupObj->populate(Helper::GetGroupDataFromVcard(
\Sabre\VObject\Reader::read(
$group->carddata,
\Sabre\VObject\Reader::OPTION_IGNORE_INVALID_LINES
),
$group->card_id
));
$result[] = $groupObj;
}
}
return $result;
}
/**
* @api {post} ?/Api/ GetGroup
* @apiName GetGroup
* @apiGroup Contacts
* @apiDescription Returns group with specified UUID.
*
* @apiHeader {string} Authorization "Bearer " + Authentication token which was received as the result of Core.Login method.
* @apiHeaderExample {json} Header-Example:
* {
* "Authorization": "Bearer 32b2ecd4a4016fedc4abee880425b6b8"
* }
*
* @apiParam {string=Contacts} Module Module name
* @apiParam {string=GetGroup} Method Method name
* @apiParam {string} Parameters JSON.stringified object <br>
* {<br>
*   **$UUID** *string* UUID of group to return.<br>
* }
*
* @apiParamExample {json} Request-Example:
* {
* Module: 'Contacts',
* Method: 'GetGroup',
* Parameters: '{ UUID: "group_uuid" }'
* }
*
* @apiSuccess {object[]} Result Array of response objects.
* @apiSuccess {string} Result.Module Module name
* @apiSuccess {string} Result.Method Method name
* @apiSuccess {mixed} Result.Result Group object in case of success, otherwise **false**.
* @apiSuccess {string} Result.Result.City=""
* @apiSuccess {string} Result.Result.Company=""
* @apiSuccess {array} Result.Result.Contacts='[]'
* @apiSuccess {string} Result.Result.Country=""
* @apiSuccess {string} Result.Result.Email=""
* @apiSuccess {string} Result.Result.Fax=""
* @apiSuccess {int} Result.Result.IdUser=0
* @apiSuccess {bool} Result.Result.IsOrganization=false
* @apiSuccess {string} Result.Result.Name=""
* @apiSuccess {string} Result.Result.Phone=""
* @apiSuccess {string} Result.Result.Street=""
* @apiSuccess {string} Result.Result.UUID=""
* @apiSuccess {string} Result.Result.Web=""
* @apiSuccess {string} Result.Result.Zip=""
* @apiSuccess {int} [Result.ErrorCode] Error code
*
* @apiSuccessExample {json} Success response example:
* {
* Module: 'Contacts',
* Method: 'GetGroup',
* Result: { City: '', Company: 'group_company', Contacts: [], Country: '', Email: '', Fax: '',
* IdUser: 3, IsOrganization: true, Name: 'group_name', Phone:'', State:'', Street:'',
* UUID: 'group_uuid', Web:'', Zip: '' }
*
* @apiSuccessExample {json} Error response example:
* {
* Module: 'Contacts',
* Method: 'GetGroup',
* Result: false,
* ErrorCode: 102
* }
*/
/**
* Returns group with specified UUID.
* @param string $UUID UUID of group to return.
* @return \Aurora\Modules\Contacts\Classes\Group
*/
public function GetGroup($UserId, $UUID)
{
$mResult = false;
\Aurora\System\Api::checkUserRoleIsAtLeast(\Aurora\System\Enums\UserRole::NormalUser);
Api::CheckAccess($UserId);
$oUser = Api::getUserById($UserId);
if ($oUser instanceof \Aurora\Modules\Core\Models\User) {
$query = Capsule::connection()->table('contacts_cards')
->join('adav_cards', 'contacts_cards.CardId', '=', 'adav_cards.id')
->join('adav_addressbooks', 'adav_cards.addressbookid', '=', 'adav_addressbooks.id')
->select('adav_cards.id as card_id', 'adav_cards.uri as card_uri', 'adav_addressbooks.id as addressbook_id', 'carddata');
$aArgs = [
'UUID' => $UUID,
'UserId' => $UserId
];
$query->where(function ($q) use ($aArgs, $query) {
$aArgs['Query'] = $query;
$this->broadcastEvent(self::GetName() . '::ContactQueryBuilder', $aArgs, $q);
});
$row = $query->where('contacts_cards.IsGroup', true)->first();
if ($row) {
if (!self::Decorator()->CheckAccessToAddressBook($oUser, $row->addressbook_id, Access::Read)) {
throw new ApiException(Notifications::AccessDenied, null, 'AccessDenied');
}
$mResult = new Group();
$mResult->IdUser = $UserId;
$mResult->Id = $row->card_id;
$mResult->populate(
Helper::GetGroupDataFromVcard(
\Sabre\VObject\Reader::read(
$row->carddata,
\Sabre\VObject\Reader::OPTION_IGNORE_INVALID_LINES
),
$row->card_uri
)
);
$mResult->UUID = $UUID;
}
}
return $mResult;
}
/**
* @api {post} ?/Api/ GetContacts
* @apiName GetContacts
* @apiGroup Contacts
* @apiDescription Returns list of contacts for specified parameters.
*
* @apiHeader {string} Authorization "Bearer " + Authentication token which was received as the result of Core.Login method.
* @apiHeaderExample {json} Header-Example:
* {
* "Authorization": "Bearer 32b2ecd4a4016fedc4abee880425b6b8"
* }
*
* @apiParam {string=Contacts} Module Module name
* @apiParam {string=GetContacts} Method Method name
* @apiParam {string} Parameters JSON.stringified object <br>
* {<br>
*   **Offset** *int* Offset of contacts list.<br>
*   **Limit** *int* Limit of result contacts list.<br>
*   **SortField** *int* Name of field order by.<br>
*   **SortOrder** *int* Sorting direction.<br>
*   **Storage** *string* Storage value.<br>
*   **Search** *string* Search string.<br>
*   **GroupUUID** *string* UUID of group that should contain all returned contacts.<br>
*   **Filters** *array* Other conditions for obtaining contacts list.<br>
* }
*
* @apiParamExample {json} Request-Example:
* {
* Module: 'Contacts',
* Method: 'GetContacts',
* Parameters: '{ Offset: 0, Limit: 20, SortField: 1, SortOrder: 0, Storage: "personal",
* Search: "", GroupUUID: "", Filters: [] }'
* }
*
* @apiSuccess {object[]} Result Array of response objects.
* @apiSuccess {string} Result.Module Module name
* @apiSuccess {string} Result.Method Method name
* @apiSuccess {mixed} Result.Result Object with contacts data in case of success, otherwise **false**.
* @apiSuccess {int} Result.Result.ContactCount Count of contacts that are obtained with specified conditions.
* @apiSuccess {array} Result.Result.List List of contacts objects.
* @apiSuccess {int} [Result.ErrorCode] Error code
*
* @apiSuccessExample {json} Success response example:
* {
* Module: 'Contacts',
* Method: 'GetContacts',
* Result: '{ "ContactCount": 6, "List": [{ "UUID": "contact_uuid", "IdUser": 3, "Name": "",
* "Email": "[email protected]", "Storage": "personal" }] }'
* }
*
* @apiSuccessExample {json} Error response example:
* {
* Module: 'Contacts',
* Method: 'GetContacts',
* Result: false,
* ErrorCode: 102
* }
*/
/**
* Returns list of contacts for specified parameters.
* @param string $Storage Storage type of contacts.
* @param int $Offset Offset of contacts list.
* @param int $Limit Limit of result contacts list.
* @param int $SortField Name of field order by.
* @param int $SortOrder Sorting direction.
* @param string $Search Search string.
* @param string $GroupUUID UUID of group that should contain all returned contacts.
* @param Builder $Filters Other conditions for obtaining contacts list.
* @param bool $WithGroups Indicates whether contact groups should be included in the contact list
* @param bool $WithoutTeamContactsDuplicates Do not show a contact from the global address book if the contact with the same email address already exists in personal address book
* @param bool $Suggestions
* @param bool $AddressBookId
* @return array
*/
public function GetContacts($UserId, $Storage = '', $Offset = 0, $Limit = 20, $SortField = SortField::Name, $SortOrder = SortOrder::ASC, $Search = '', $GroupUUID = '', Builder $Filters = null, $WithGroups = false, $WithoutTeamContactsDuplicates = false, $Suggestions = false, $AddressBookId = null)
{
// $Storage is used by subscribers to prepare filters.
\Aurora\System\Api::checkUserRoleIsAtLeast(\Aurora\System\Enums\UserRole::NormalUser);
Api::CheckAccess($UserId);
$oUser = Api::getUserById($UserId);
$aContacts = [];
if (self::Decorator()->CheckAccessToAddressBook($oUser, $AddressBookId, Access::Read)) {
$query = $this->getGetContactsQueryBuilder($UserId, $Storage, $AddressBookId, $Filters, $Suggestions);
if (!empty($Search)) {
$query = $query->where(function ($query) use ($Search) {
$query->where('FullName', 'LIKE', "%$Search%")
->orWhere('PersonalEmail', 'LIKE', "%$Search%")
->orWhere('BusinessEmail', 'LIKE', "%$Search%")
->orWhere('OtherEmail', 'LIKE', "%$Search%")
->orWhere('BusinessCompany', 'LIKE', "%$Search%");
});
}
if (!empty($GroupUUID)) {
$oGroup = self::Decorator()->GetGroup($UserId, $GroupUUID);
if ($oGroup) {
$contacts = $oGroup->Contacts;
if (count($contacts) === 0) {
$contacts = [null];
}
$query->whereIn('adav_cards.id', $contacts);
}
}
$count = $query->count();
$aContactsCollection = $this->getContactsCollection($SortField, $SortOrder, $Offset, $Limit, $query);
if ($Storage === StorageType::All) {
$personalContacsCollection = $aContactsCollection->filter(function ($contact) {
return !$contact->IsTeam && !$contact->Shared;
});
if ($WithoutTeamContactsDuplicates) {
$aContactsCollection->each(function ($contact, $key) use (&$aContactsCollection, $personalContacsCollection) {
if ($contact->IsTeam && $personalContacsCollection->unique()->contains('ViewEmail', $contact->ViewEmail)) {
$aContactsCollection->forget($key);
} elseif ($contact->Auto) { // is collected contact
$aContactsCollection->each(function (&$subContact) use (&$aContactsCollection, $contact, $key) {
if ($subContact->IsTeam && $subContact->ViewEmail === $contact->ViewEmail) {
$subContact->AgeScore = $contact->AgeScore;
$aContactsCollection->forget($key);
}
if (!$contact->IsTeam && !$contact->Shared && !$contact->Auto && $subContact->ViewEmail === $contact->ViewEmail) {
$aContactsCollection->forget($key);
}
});
}
});
} else {
$aContactsCollection->each(function (&$contact, $key) use (&$aContactsCollection, $personalContacsCollection) {
if ($contact->IsTeam) {
$personalContact = $personalContacsCollection->unique()->filter(function ($subContact) use (&$contact) {
return strtolower($contact->ViewEmail) === strtolower($subContact->ViewEmail);
})->first(); // Find collected contact with same email
if ($personalContact) {
$contact->Frequency = $personalContact->Frequency;
if ($contact->Auto) { // is collected contact
$aContactsCollection = $aContactsCollection->filter(function ($subContact) use ($contact) {
return (strtolower($subContact->ViewEmail) === strtolower($contact->ViewEmail) && !$contact->Auto) ||
strtolower($subContact->ViewEmail) !== strtolower($contact->ViewEmail);
}); // remove all collected contacts
}
}
}
});
}
}
$this->resolveAddressbooksIdsForContacts($oUser, $aContactsCollection);
// TODO: workaround for mobile APP
$aContactsCollection->each(function ($contact) use ($UserId) {
if (!$contact->UserId) {
$contact->UserId = $UserId;
}
});
$aContacts = $aContactsCollection->toArray();
if ($WithGroups) {
$groups = self::Decorator()->GetGroups($UserId, [], $Search);
if (is_array($groups) && count($groups) > 0) {
$groupContactsUuids = [];
$contactsUuids = [];
array_map(function ($item) use (&$groupContactsUuids, &$contactsUuids) {
if (is_array($item->Contacts) && count($item->Contacts) > 0) {
$groupContactsUuids[$item->UUID] = $item->Contacts;
$contactsUuids = array_merge($contactsUuids, $item->Contacts);
}
}, $groups);
$groupContacts = [];
$contactsUuids = array_unique($contactsUuids);
if (count($contactsUuids) > 0) {
foreach (self::Decorator()->GetContactsByUids($UserId, $contactsUuids) as $groupContact) {
$groupContacts[$groupContact->UUID] = $groupContact;
}
$aGroupUsersList = [];
foreach ($groups as $group) {
$aGroupContactsEmails = [];
if (is_array($group->Contacts)) {
foreach ($group->Contacts as $contactUuid) {
if (isset($groupContacts[$contactUuid])) {
$oContact = $groupContacts[$contactUuid];
$aGroupContactsEmails[] = $oContact->FullName ? "\"{$oContact->FullName}\" <{$oContact->ViewEmail}>" : $oContact->ViewEmail;
}
}
$aGroupUsersList[] = [
'UUID' => (string)$group->UUID,
'IdUser' => $group->IdUser,
'FullName' => $group->Name,
'FirstName' => '',
'LastName' => '',
'ViewEmail' => implode(', ', $aGroupContactsEmails),
'Storage' => '',
'Frequency' => 0,
'DateModified' => '',
'IsGroup' => true,
];
}
}
$aContacts = array_merge($aContacts, $aGroupUsersList);
}
}
}
} else {
throw new ApiException(Notifications::AccessDenied, null, 'AccessDenied');