forked from horde/turba
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Api.php
2561 lines (2248 loc) · 90.8 KB
/
Api.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
/**
* Turba external API interface.
*
* This file defines Turba's external API interface. Other applications can
* interact with Turba through this API.
*
* Copyright 2009-2017 Horde LLC (http://www.horde.org/)
*
* See the enclosed file LICENSE for license information (ASL). If you did
* did not receive this file, see http://www.horde.org/licenses/apache.
*
* @author Michael Slusarz <[email protected]>
* @category Horde
* @license http://www.horde.org/licenses/apache ASL
* @package Turba
*/
class Turba_Api extends Horde_Registry_Api
{
/**
* Links.
*
* @var array
*/
protected $_links = array(
'show' => '%application%/contact.php?source=|source|&key=|key|&uid=|uid|',
'smartmobile_browse' => '%application%/smartmobile.php#browse'
);
/**
* The listing of API calls that do not require permissions checking.
*
* @var array
*/
protected $_noPerms = array(
'getClientSource', 'getClient', 'getClients', 'searchClients'
);
/**
* Callback for comment API.
*
* @param integer $id Internal data identifier.
*
* @return mixed Name of object on success, false on failure.
*/
public function commentCallback($id)
{
if (!$GLOBALS['conf']['comments']['allow']) {
return false;
}
@list($source, $key) = explode('.', $id, 2);
if (isset($GLOBALS['cfgSources'][$source]) && $key) {
try {
return $GLOBALS['injector']->getInstance('Turba_Factory_Driver')->create($source)->getObject($key)->getValue('name');
} catch (Horde_Exception $e) {
}
}
return false;
}
/**
* Does this API allow comments?
*
* @return boolean True if API allows comments.
*/
public function hasComments()
{
return !empty($GLOBALS['conf']['comments']['allow']);
}
/**
* Returns a list of available sources.
*
* @param boolean $writeable If true, limits to writeable sources.
* @param boolean $sync_only Only include synchable address books.
*
* @return array An array of the available sources. Keys are source IDs,
* values are source titles.
*/
public function sources($writeable = false, $sync_only = false)
{
$out = array();
foreach (Turba::getAddressBooks($writeable ? Horde_Perms::EDIT : Horde_Perms::READ) as $key => $val) {
$out[$key] = $val['title'];
}
if ($sync_only) {
$syncable = unserialize($GLOBALS['prefs']->getValue('sync_books'));
$out = array_intersect_key($out, array_flip($syncable));
}
return $out;
}
/**
* Returns a list of fields avaiable in a source.
*
* @param string $source The source name.
*
* @return array An array describing the fields. Keys are the field name,
* values are arrays with these keys:
* - name: (string) Field name.
* - label: (string) Field label.
* - search: (boolean) Can this field be searched?
* - type: (string) See turba/config/attributes.php.
*
* @throws Turba_Exception
*/
public function fields($source = null)
{
global $attributes, $cfgSources;
if (is_null($source) || !isset($cfgSources[$source])) {
throw new Turba_Exception(_("Invalid address book."));
}
$fields = array();
foreach (array_keys($cfgSources[$source]['map']) as $name) {
if (substr($name, 0, 2) != '__') {
$fields[$name] = array(
'label' => $attributes[$name]['label'],
'name' => $name,
'search' => in_array($name, $cfgSources[$source]['search']),
'type' => $attributes[$name]['type']
);
}
}
return $fields;
}
/**
* Retrieve the UID for the current user's default Turba share.
*
* @return string UID.
*/
public function getDefaultShare()
{
global $injector, $prefs, $session;
// Bring in a clean copy of sources.
$cfgSources = Turba::availableSources();
if ($session->get('turba', 'has_share')) {
$driver = $injector->getInstance('Turba_Factory_Driver');
foreach (Turba::listShares(true) as $uid => $share) {
$params = @unserialize($share->get('params'));
if (!empty($params['source'])) {
try {
if ($driver->create($uid)->checkDefaultShare($share, $cfgSources[$params['source']])) {
return $uid;
}
} catch (Turba_Exception $e) {}
}
}
}
// Return Turba's default_dir as default.
return $prefs->getValue('default_dir');
}
/**
* Retrieve the UID for the Global Address List source.
*
* @return string|boolean The UID or false if none configured.
*/
public function getGalUid()
{
return empty($GLOBALS['conf']['gal']['addressbook'])
? false
: $GLOBALS['conf']['gal']['addressbook'];
}
/**
* Browses through Turba's object tree.
*
* @param string $path The path of the tree to browse.
* @param array $properties The item properties to return. Defaults to
* 'name', 'icon', and 'browseable'.
*
* @return array Content of the specified path.
* @throws Turba_Exception
* @throws Horde_Exception_NotFound
*/
public function browse($path = '',
$properties = array('name', 'icon', 'browseable'))
{
global $injector, $registry, $session;
// Strip off the application name if present
if (substr($path, 0, 5) == 'turba') {
$path = substr($path, 5);
}
$path = trim($path, '/');
$results = array();
if (empty($path)) {
/* We always provide the "global" folder which contains address
* book sources that are shared among all users. Per-user shares
* are shown in a folder for each respective user. */
$owners = array(
'global' => _("Global Address Books")
);
foreach (Turba::listShares() as $share) {
$owners[$share->get('owner') ? $registry->convertUsername($share->get('owner'), false) : '-system-'] = $share->get('owner') ?: '-system-';
}
$now = time();
foreach ($owners as $externalOwner => $internalOwner) {
if (in_array('name', $properties)) {
$results['turba/' . $externalOwner]['name'] = $injector
->getInstance('Horde_Core_Factory_Identity')
->create($internalOwner)
->getName();
}
if (in_array('icon', $properties)) {
$results['turba/' . $externalOwner]['icon'] = Horde_Themes::img('turba.png');
}
if (in_array('browseable', $properties)) {
$results['turba/' . $externalOwner]['browseable'] = true;
}
if (in_array('read-only', $properties)) {
$results['turba/' . $externalOwner]['read-only'] = true;
}
}
return $results;
}
$parts = explode('/', $path);
if (count($parts) == 1) {
/* We should either have the username that is a valid share owner
* or 'global'. */
if (empty($parts[0])) {
// We need either 'global' or a valid username with shares.
return array();
}
if ($parts[0] == 'global') {
// The client is requesting a list of global address books.
$addressbooks = Turba::getAddressBooks();
foreach ($addressbooks as $addressbook => $info) {
if ($info['type'] == 'share') {
// Ignore address book shares in the 'global' folder
unset($addressbooks[$addressbook]);
}
}
} else {
/* Assume $parts[0] is a valid username and we need to list
* their shared addressbooks. */
if (!$session->get('turba', 'has_share')) {
// No backends are configured to provide shares
return array();
}
$addressbooks = $injector->getInstance('Turba_Shares')
->listShares(
$registry->getAuth(),
array(
'attributes' => $registry->convertUsername($parts[0], true),
'perm' => Horde_Perms::READ
)
);
}
$curpath = 'turba/' . $registry->convertUsername($parts[0], true) . '/';
foreach ($addressbooks as $addressbook => $info) {
$label = ($info instanceof Horde_Share_Object)
? $info->get('name')
: $info['title'];
if (in_array('name', $properties)) {
$results[$curpath . $addressbook]['name'] =
sprintf(_("Contacts from %s"), $label);
}
if (in_array('displayname', $properties)) {
$results[$curpath . $addressbook]['displayname'] = $label;
}
if (in_array('owner', $properties)) {
$results[$curpath . $addressbook]['owner'] = ($info instanceof Horde_Share_Object)
? $registry->convertUsername($info->get('owner'), false)
: '-system-';
}
if (in_array('icon', $properties)) {
$results[$curpath . $addressbook]['icon'] = Horde_Themes::img('turba.png');
}
if (in_array('browseable', $properties)) {
$results[$curpath . $addressbook]['browseable'] = true;
}
if (in_array('read-only', $properties) &&
($info instanceof Horde_Share_Object)) {
$results[$curpath . $addressbook]['read-only'] = !$info->hasPermission($registry->getAuth(), Horde_Perms::EDIT);
}
}
return $results;
}
if (count($parts) == 2) {
/* The client is requesting all contacts from a given
* addressbook. */
if (empty($parts[0]) || empty($parts[1])) {
/* $parts[0] must be either 'global' or a valid user with
* shares; $parts[1] must be an addressbook ID. */
return array();
}
$addressbooks = Turba::getAddressBooks();
if (!isset($addressbooks[$parts[1]])) {
// We must have a valid addressbook to continue.
return array();
}
$addressbook = $injector->getInstance('Turba_Factory_Driver')
->create($parts[1]);
$owner = $registry->convertUsername($addressbook->getContactOwner(), false);
$contacts = $addressbook->search(array());
$contacts->reset();
$curpath = 'turba/' . $registry->convertUsername($parts[0], false) . '/' . $parts[1] . '/';
$dav = $injector->getInstance('Horde_Dav_Storage');
while ($contact = $contacts->next()) {
$id = $contact->getValue('__key');
try {
$id = $dav->getExternalObjectId($id, $parts[1]) ?: $id;
} catch (Horde_Dav_Exception $e) {
}
$key = $curpath . $id;
if (in_array('name', $properties)) {
$results[$key]['name'] = Turba::formatName($contact);
}
if (in_array('owner', $properties)) {
$results[$key]['owner'] = $owner;
}
if (in_array('icon', $properties)) {
$results[$key]['icon'] = Horde_Themes::img('mime/vcard.png');
}
if (in_array('browseable', $properties)) {
$results[$key]['browseable'] = false;
}
if (in_array('read-only', $properties)) {
$results[$key]['read-only'] = !$addressbook->hasPermission(Horde_Perms::EDIT);
}
if (in_array('contenttype', $properties)) {
$results[$key]['contenttype'] = 'text/x-vcard';
}
if (in_array('modified', $properties)) {
$results[$key]['modified'] = $contact->lastModification() ?: null;
}
if (in_array('created', $properties)) {
$results[$key]['created'] = $this->getActionTimestamp($contact->getValue('__uid'), 'add', $parts[1]);
}
if (in_array('etag', $properties)) {
$results[$key]['etag'] = '"' . md5($contact->getValue('__key') . '|' . $contact->lastModification()) . '"';
}
}
return $results;
}
if (count($parts) == 3) {
/* The client is requesting an individual contact. */
$addressbooks = Turba::getAddressBooks();
if (!isset($addressbooks[$parts[1]])) {
// We must have a valid addressbook to continue.
return array();
}
// Load the Turba driver.
$driver = $injector->getInstance('Turba_Factory_Driver')->create($parts[1]);
$dav = $injector->getInstance('Horde_Dav_Storage');
$object = $parts[2];
try {
$object = $dav->getInternalObjectId($object, $parts[1])
?: $object;
} catch (Horde_Dav_Exception $e) {
}
$contact = $driver->getObject($object);
$result = array(
'data' => $driver->tovCard($contact, '2.1', null, true)->exportVcalendar(),
'mimetype' => 'text/x-vcard'
);
$modified = $this->_modified($contact->getValue('__uid'), $parts[1]);
if (!empty($modified)) {
$result['mtime'] = $modified;
}
return $result;
}
throw new Turba_Exception(_("Malformed request."));
}
/**
* Deletes a file from the Turba tree.
*
* @param string $path The path to the file.
*
* @return string The event's UID.
* @throws Turba_Exception
*/
public function path_delete($path)
{
global $injector;
// Strip off the application name if present
if (substr($path, 0, 5) == 'turba') {
$path = substr($path, 5);
}
$parts = explode('/', trim($path, '/'));
if (count($parts) < 3) {
// Deletes must be on individual contacts.
throw new Turba_Exception(_("Delete denied."));
}
if (!array_key_exists($parts[1], Turba::getAddressBooks())) {
throw new Turba_Exception(_("Address book does not exist"));
}
$dav = $injector->getInstance('Horde_Dav_Storage');
$id = $parts[2];
try {
$id = $dav->getInternalObjectId($id, $parts[1]) ?: $id;
} catch (Horde_Dav_Exception $e) {
}
return $injector->getInstance('Turba_Factory_Driver')->create($parts[1])->delete($id);
}
/**
* Returns an array of UIDs for all contacts that the current user is
* authorized to see.
*
* @param string|array $sources The name(s) of the source(s) to return
* contacts of. If empty, the current user's
* sync sources or default source are used.
*
* @return array An array of UIDs for all contacts the user can access.
* @throws Turba_Exception
*/
public function listUids($sources = null)
{
$driver = $GLOBALS['injector']->getInstance('Turba_Factory_Driver');
$uids = array();
foreach ($this->_getSources($sources) as $source) {
try {
$results = $driver->create($source)->search(array());
} catch (Turba_Exception $e) {
throw new Turba_Exception(sprintf(_("Error searching the address book: %s"), $e->getMessage()));
}
foreach ($results->objects as $o) {
if (!$o->isGroup()) {
$uids[] = $o->getValue('__uid');
}
}
}
return $uids;
}
/**
* Returns an array of UIDs for contacts that have had a given action
* since a certain time.
*
* @param string $action The action to check for - add, modify, or
* delete.
* @param integer $timestamp The time to start the search.
* @param string|array $sources The source(s) for which to retrieve the
* history.
* @param integer $end The optional ending timestamp.
* @param boolean $isModSeq If true, $timestamp and $end are
* modification sequences and not timestamps.
* @since 4.1.1
*
* @return array An array of UIDs matching the action and time criteria.
*
* @throws Turba_Exception
*/
public function listBy($action, $timestamp, $sources = null, $end = null, $isModSeq = false)
{
$driver = $GLOBALS['injector']->getInstance('Turba_Factory_Driver');
$history = $GLOBALS['injector']->getInstance('Horde_History');
$filter = array(
array(
'field' => 'action',
'op' => '=',
'value' => $action
)
);
$uids = array();
if (!empty($end) && !$isModSeq) {
$filter[] = array(
'field' => 'ts',
'op' => '<',
'value' => $end
);
}
foreach ($this->_getSources($sources) as $source) {
$sdriver = $driver->create($source);
if (!$isModSeq) {
$histories = $history->getByTimestamp(
'>', $timestamp, $filter,
'turba:' . $sdriver->getName()
);
} else {
$histories = $history->getByModSeq(
$timestamp, $end, $filter, 'turba:' . $sdriver->getName());
}
// Filter out groups
$nguids = str_replace(
'turba:' . $sdriver->getName() . ':',
'',
array_keys($histories)
);
$include = array();
foreach ($nguids as $uid) {
if ($action != 'delete') {
$list = $sdriver->search(array('__uid' => $uid));
if ($list->count()) {
$object = $list->next();
if ($object->isGroup()) {
continue;
}
}
}
$include[] = $uid;
}
// Strip leading turba:addressbook:.
$uids = array_merge($uids, $include);
}
return $uids;
}
/**
* Method for obtaining all server changes between two timestamps.
* Essentially a wrapper around listBy(), but returns an array containing
* all adds, edits, and deletions.
*
* @param integer $start The starting timestamp
* @param integer $end The ending timestamp.
* @param boolean $isModSeq If true, $start and $end are modification
* sequences and not timestamps. @since 4.1.1
* @param string|array $sources The sources to check. @since 4.2.0
*
* @return array A hash with 'add', 'modify' and 'delete' arrays.
*/
public function getChanges($start, $end, $isModSeq = false, $sources = null)
{
$sources = $this->_getSources($sources, true);
return array(
'add' => $this->listBy('add', $start, $sources, $end, $isModSeq),
'modify' => $this->listBy('modify', $start, $sources, $end, $isModSeq),
'delete' => $this->listBy('delete', $start, $sources, $end, $isModSeq)
);
}
/**
* Return all changes occuring between the specified modification
* sequences.
*
* @param integer $start The starting modseq.
* @param integer $end The ending modseq.
* @param string|array $sources The sources to check. @since 4.2.0
*
* @return array The changes @see getChanges()
* @since 4.1.1
*/
public function getChangesByModSeq($start, $end, $sources = null)
{
return $this->getChanges($start, $end, true, $sources);
}
/**
* Returns the timestamp of an operation for a given UID and action.
*
* @param string $uid The UID to look for.
* @param string $action The action to check for - add, modify, or
* delete.
* @param string|array $sources The source(s) for which to retrieve the
* history.
* @param boolean $modSeq Request a modification sequence instead of
* timestamp. @since 4.1.1
*
* @return integer The timestamp for this action.
*
* @throws Turba_Exception
*/
public function getActionTimestamp($uid, $action, $sources = null, $modSeq = false)
{
$driver = $GLOBALS['injector']->getInstance('Turba_Factory_Driver');
$history = $GLOBALS['injector']->getInstance('Horde_History');
$last = 0;
foreach ($this->_getSources($sources) as $source) {
if (!$modSeq) {
$ts = $history->getActionTimestamp(
'turba:' . $driver->create($source)->getName() . ':' . $uid,
$action);
} else {
$ts = $history->getActionModSeq(
'turba:' . $driver->create($source)->getName() . ':' . $uid,
$action);
}
if (!empty($ts) && $ts > $last) {
$last = $ts;
}
}
return $last;
}
/**
* Return the largest modification sequence from the history backend.
*
* @param string $id Addressbook id to return highest MODSEQ for. If
* null, the highest MODSEQ across all addressbooks is
* returned. @since 4.2.0
*
* @return integer The modseq.
* @since 4.1.1
*/
public function getHighestModSeq($id = null)
{
$parent = 'turba';
if (!empty($id)) {
$parent .= ':' . $id;
}
return $GLOBALS['injector']->getInstance('Horde_History')->getHighestModSeq($parent);
}
/**
* Import a contact represented in the specified contentType.
*
* @param string $content The content of the contact.
* @param string $contentType What format is the data in? Currently
* supports array, text/directory, text/vcard,
* text/x-vcard, and activesync.
* @param string $source The source into which the contact will be
* imported.
* @param array $options Additional options:
* - match_on_email: (boolean) If true, will detect entry as duplicate
* if ANY email field matches. Useful for
* automatically adding contacts from an
* email application, such as IMP.
* @since 4.2.9
*
* @return string The new UID.
*
* @throws Turba_Exception
* @throws Turba_Exception_ObjectExists
*/
public function import($content, $contentType = 'array', $source = null, array $options = array())
{
global $injector;
$source = $this->_getSource($source);
$driver = $injector->getInstance('Turba_Factory_Driver')
->create($source);
if (!$driver->hasPermission(Horde_Perms::EDIT)) {
throw new Turba_Exception(_("Permission denied"));
}
if ($content instanceof Horde_Icalendar_Vcard) {
$content = $driver->toHash($content);
} else {
switch ($contentType) {
case 'activesync':
$content = $driver->fromASContact($content);
break;
case 'array':
if (!isset($content['emails']) && isset($content['email'])) {
$content['emails'] = $content['email'];
}
break;
case 'text/x-vcard':
case 'text/vcard':
case 'text/directory':
$iCal = new Horde_Icalendar();
if (!$iCal->parsevCalendar($content)) {
throw new Turba_Exception(_("There was an error importing the iCalendar data."));
}
switch ($iCal->getComponentCount()) {
case 0:
throw new Turba_Exception(_("No vCard data was found."));
case 1:
$content = $driver->toHash($iCal->getComponent(0));
break;
default:
$ids = array();
foreach ($iCal->getComponents() as $c) {
if ($c instanceof Horde_Icalendar_Vcard) {
$content = $driver->toHash($c);
$result = $driver->search($content);
if (count($result)) {
continue;
}
$ids[] = $driver->add($content);
}
}
return $ids;
}
break;
default:
throw new Turba_Exception(sprintf(_("Unsupported Content-Type: %s"), $contentType));
}
}
if (!empty($options['match_on_email'])) {
$content_copy = array();
foreach (Turba::getAvailableEmailFields() as $field) {
if (!empty($content[$field])) {
$rfc = new Horde_Mail_Rfc822();
$email = $rfc->parseAddressList($content[$field]);
$content_copy[$field] = (string)$email;
}
}
} else {
$content_copy = $content;
}
// Check if the entry already exists in the data source.
$result = $driver->search(
$content_copy, null, !empty($options['match_on_email']) ? 'OR' : 'AND');
if (count($result)) {
throw new Turba_Exception_ObjectExists(_("Already Exists"));
}
// We can't use $object->setValue() here since that cannot be used
// with composite fields.
return $driver->getObject(
$driver->add($this->_encodeContent($content))
)->getValue('__uid');
}
/**
* Adds a group (and its members) to the source provided.
*
* @param string $name Group name.
* @param array $members An array of members to add to the group. Format
* is the same as the 'array' argument to the
* import() API function.
* @param array $opts Additional options:
* <pre>
* - attr: (array) Additional attributes to add to group.
* - source: (string) Source to import contacts to.
* </pre>
*
* @return array An array with the following keys:
* <pre>
* - added: (integer) The number of addresses added to the group.
* - uid: (string) The uid of the group object.
* </pre>
*
* @throws Turba_Exception
*/
public function addGroup($name, $members, array $opts = array())
{
global $injector;
$source = $this->_getSource(
isset($opts['source']) ? $opts['source'] : null
);
$driver = $injector->getInstance('Turba_Factory_Driver')
->create($source);
if (!$driver->hasPermission(Horde_Perms::EDIT)) {
throw new Turba_Exception(_("Permission denied"));
}
$group_add = array();
foreach ($members as $val) {
$ob = null;
$result = $driver->search($val);
if (count($result)) {
$ob = $result->reset();
} else {
try {
$ob = $driver->getObject(
$driver->add($this->_encodeContent($val))
);
} catch (Exception $e) {}
}
if ($ob) {
$group_add[] = array(
$source,
$ob->getValue('__key')
);
}
}
$res = Turba_Object_Group::createGroup(
$source,
$group_add,
array(
'attr' => array_merge(
isset($opts['attr']) ? $opts['attr'] : array(),
array('name' => $name)
)
)
);
return array(
'added' => $res->success,
'uid' => $res->group->getValue('__uid')
);
}
/**
* Export a contact, identified by UID, in the requested contentType.
*
* @param string $uid Identify the contact to export.
* @param mixed $contentType What format should the data be in?
* - text/directory: Returns RFC2426 vcard3.0
* - text/vcard: Returns RFC2426 vcard3.0
* - text/x-vcard: Returns imc.org vcard 2.1 format.
* - array: Returns a raw array
* - activesync: Returns a Horde_ActiveSync_Message_Contact:: object
* @param string|array $sources The source(s) from which the contact will
* be exported.
* @param array $fields Hash of field names and
* Horde_SyncMl_Property properties with the
* requested fields.
* @param array $options Any additional options to be passed to the
* exporter. Currently supported:
* - skip_empty: (boolean) {text/vcard or text/x-vcard} Set to
* true to not output empty properties.
* DEFAULT: false.
* - protocolversion: (float) {activesync} The EAS version to support
* DEFAULT: 2.5
* - bodyprefs: (array) {activesync} A BODYPREFERENCE array.
* DEFAULT: none (No body prefs enforced).
* - truncation: (integer) {activesync} Truncate event body to this
* length.
* DEFAULT: none (No truncation).
*
* @return mixed The requested data.
* @throws Turba_Exception
*/
public function export($uid, $contentType, $sources = null, $fields = null, array $options = array())
{
if (empty($uid)) {
throw new Turba_Exception(_("Invalid ID"));
}
$driver = $GLOBALS['injector']->getInstance('Turba_Factory_Driver');
foreach ($this->_getSources($sources) as $source) {
$sdriver = $driver->create($source);
if (!$sdriver->hasPermission(Horde_Perms::READ)) {
continue;
}
$result = $sdriver->search(array('__uid' => $uid));
if (count($result) == 0) {
continue;
} elseif (count($result) > 1) {
throw new Turba_Exception(sprintf("Internal Horde Error: multiple Turba objects with same objectId %s.", $uid));
}
$version = '3.0';
list($contentType,) = explode(';', $contentType);
switch ($contentType) {
case 'text/x-vcard':
$version = '2.1';
// Fall-through
case 'text/vcard':
case 'text/directory':
$export = '';
foreach ($result->objects as $obj) {
$vcard = $sdriver->tovCard($obj, $version, $fields, !empty($options['skip_empty']));
/* vCards are not enclosed in
* BEGIN:VCALENDAR..END:VCALENDAR. Export the individual
* cards instead. */
$export .= $vcard->exportvCalendar();
}
return $export;
case 'array':
$attributes = array();
foreach ($result->objects as $object) {
foreach (array_keys($GLOBALS['cfgSources'][$source]['map']) as $field) {
$attributes[$field] = $object->getValue($field);
}
}
return $attributes;
case 'activesync':
foreach ($result->objects as $object) {
$return = $object;
}
return $sdriver->toASContact($return, $options);
default:
throw new Turba_Exception(sprintf(_("Unsupported Content-Type: %s"), $contentType));
}
}
throw new Turba_Exception(sprintf(_("Object %s not found."), $uid));
}
/**
* Exports the user's own contact as a vCard string.
*
* @return string The requested vCard data.
* @throws Turba_Exception
*/
public function ownVCard()
{
$contact = $this->getOwnContactObject();
$vcard = $GLOBALS['injector']->getInstance('Turba_Factory_Driver')->create($contact['source'])->tovCard($contact['contact'], '3.0', null, true);
$vcard->setAttribute('VERSION', '3.0');
return $vcard->exportvCalendar();
}
/**
* Export the user's own contact as a hash.
*
* @return array The contact hash.
* @throws Turba_Exception
*/
public function ownContact()
{
$contact = $this->getOwnContactObject();
return $contact['contact']->getAttributes();
}
/**
* Helper function to return the user's own contact object
*
* @return array An array containing the following keys:
* - contact: (Turba_Object) Object representing the user's own contact.
* - source: (string) The source of the user's own contact.
* @throws Turba_Exception
*/
public function getOwnContactObject()
{
$own_contact = $GLOBALS['prefs']->getValue('own_contact');
if (empty($own_contact)) {
throw new Turba_Exception(_("You didn't mark a contact as your own yet."));
}
@list($source, $id) = explode(';', $own_contact);
if (!isset($GLOBALS['cfgSources'][$source])) {
throw new Turba_Exception(_("The address book with your own contact doesn't exist anymore."));
}
$driver = $GLOBALS['injector']->getInstance('Turba_Factory_Driver')->create($source);
if (!$driver->hasPermission(Horde_Perms::READ)) {
throw new Turba_Exception(_("You don't have sufficient permissions to read the address book that contains your own contact."));
}
try {
$contact = $driver->getObject($id);
} catch (Horde_Exception_NotFound $e) {
throw new Turba_Exception(_("Your own contact cannot be found in the address book."));
}
return array(
'contact' => $contact,
'source'=> $source
);