forked from mstilkerich/rcmcarddav
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcarddav_backend.php
2399 lines (2087 loc) · 72.2 KB
/
carddav_backend.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
/*
RCM CardDAV Plugin
Copyright (C) 2011-2016 Benjamin Schieder <[email protected]>,
Michael Stilkerich <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
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 General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
require_once("carddav_common.php");
use \Sabre\VObject;
class carddav_backend extends rcube_addressbook
{
private static $helper;
// database primary key, used by RC to search by ID
public $primary_key = 'id';
public $coltypes;
private $fallbacktypes = array( 'email' => array('internet') );
// database ID of the addressbook
private $id;
// currently active search filter
private $filter;
private $result;
// configuration of the addressbook
private $config;
// custom labels defined in the addressbook
private $xlabels;
const SEPARATOR = ',';
// contains a the URIs, db ids and etags of the locally stored cards whenever
// a refresh from the server is attempted. This is used to avoid a separate
// "exists?" DB query for each card retrieved from the server and also allows
// to detect whether cards were deleted on the server
private $existing_card_cache = array();
// same thing for groups
private $existing_grpcard_cache = array();
// used in refresh DB to record group memberships for the delayed
// creation in the database (after all contacts have been loaded and
// stored from the server)
private $users_to_add;
// total number of contacts in address book
private $total_cards = -1;
// attributes that are redundantly stored in the contact table and need
// not be parsed from the vcard
private $table_cols = array('id', 'name', 'email', 'firstname', 'surname');
// maps VCard property names to roundcube keys
private $vcf2rc = array(
'simple' => array(
'BDAY' => 'birthday',
'FN' => 'name',
'NICKNAME' => 'nickname',
'NOTE' => 'notes',
'PHOTO' => 'photo',
'TITLE' => 'jobtitle',
'UID' => 'cuid',
'X-ABShowAs' => 'showas',
'X-ANNIVERSARY' => 'anniversary',
'X-ASSISTANT' => 'assistant',
'X-GENDER' => 'gender',
'X-MANAGER' => 'manager',
'X-SPOUSE' => 'spouse',
// the two kind attributes should not occur both in the same vcard
//'KIND' => 'kind', // VCard v4
'X-ADDRESSBOOKSERVER-KIND' => 'kind', // Apple Addressbook extension
),
'multi' => array(
'EMAIL' => 'email',
'TEL' => 'phone',
'URL' => 'website',
),
);
// array with list of potential date fields for formatting
private $datefields = array('birthday', 'anniversary');
public function __construct($dbid)
{{{
$dbh = rcmail::get_instance()->db;
$this->ready = $dbh && !$dbh->is_error();
$this->groups = true;
$this->readonly = false;
$this->id = $dbid;
$this->config = self::carddavconfig($dbid);
if ($this->config["needs_update"]){
$this->refreshdb_from_server();
}
$prefs = carddav_common::get_adminsettings();
if($this->config['presetname']) {
if($prefs[$this->config['presetname']]['readonly'])
$this->readonly = true;
}
$rc = rcmail::get_instance();
$this->coltypes = array( /* {{{ */
'name' => array('type' => 'text', 'size' => 40, 'maxlength' => 50, 'limit' => 1, 'label' => $rc->gettext('name'), 'category' => 'main'),
'firstname' => array('type' => 'text', 'size' => 19, 'maxlength' => 50, 'limit' => 1, 'label' => $rc->gettext('firstname'), 'category' => 'main'),
'surname' => array('type' => 'text', 'size' => 19, 'maxlength' => 50, 'limit' => 1, 'label' => $rc->gettext('surname'), 'category' => 'main'),
'email' => array('type' => 'text', 'size' => 40, 'maxlength' => 50, 'label' => $rc->gettext('email'), 'subtypes' => array('home','work','other','internet'), 'category' => 'main'),
'middlename' => array('type' => 'text', 'size' => 19, 'maxlength' => 50, 'limit' => 1, 'label' => $rc->gettext('middlename'), 'category' => 'main'),
'prefix' => array('type' => 'text', 'size' => 8, 'maxlength' => 20, 'limit' => 1, 'label' => $rc->gettext('nameprefix'), 'category' => 'main'),
'suffix' => array('type' => 'text', 'size' => 8, 'maxlength' => 20, 'limit' => 1, 'label' => $rc->gettext('namesuffix'), 'category' => 'main'),
'nickname' => array('type' => 'text', 'size' => 40, 'maxlength' => 50, 'limit' => 1, 'label' => $rc->gettext('nickname'), 'category' => 'main'),
'jobtitle' => array('type' => 'text', 'size' => 40, 'maxlength' => 50, 'limit' => 1, 'label' => $rc->gettext('jobtitle'), 'category' => 'main'),
'organization' => array('type' => 'text', 'size' => 40, 'maxlength' => 50, 'limit' => 1, 'label' => $rc->gettext('organization'), 'category' => 'main'),
'department' => array('type' => 'text', 'size' => 40, 'maxlength' => 50, 'label' => $rc->gettext('department'), 'category' => 'main'),
'gender' => array('type' => 'select', 'limit' => 1, 'label' => $rc->gettext('gender'), 'options' => array('male' => $rc->gettext('male'), 'female' => $rc->gettext('female')), 'category' => 'personal'),
'phone' => array('type' => 'text', 'size' => 40, 'maxlength' => 20, 'label' => $rc->gettext('phone'), 'subtypes' => array('home','home2','work','work2','mobile','cell','main','homefax','workfax','car','pager','video','assistant','other'), 'category' => 'main'),
'address' => array('type' => 'composite', 'label' => $rc->gettext('address'), 'subtypes' => array('home','work','other'), 'childs' => array(
'street' => array('type' => 'text', 'size' => 40, 'maxlength' => 50, 'label' => $rc->gettext('street'), 'category' => 'main'),
'locality' => array('type' => 'text', 'size' => 28, 'maxlength' => 50, 'label' => $rc->gettext('locality'), 'category' => 'main'),
'zipcode' => array('type' => 'text', 'size' => 8, 'maxlength' => 15, 'label' => $rc->gettext('zipcode'), 'category' => 'main'),
'region' => array('type' => 'text', 'size' => 12, 'maxlength' => 50, 'label' => $rc->gettext('region'), 'category' => 'main'),
'country' => array('type' => 'text', 'size' => 40, 'maxlength' => 50, 'label' => $rc->gettext('country'), 'category' => 'main'),), 'category' => 'main'),
'birthday' => array('type' => 'date', 'size' => 12, 'maxlength' => 16, 'label' => $rc->gettext('birthday'), 'limit' => 1, 'render_func' => 'rcmail_format_date_col', 'category' => 'personal'),
'anniversary' => array('type' => 'date', 'size' => 12, 'maxlength' => 16, 'label' => $rc->gettext('anniversary'), 'limit' => 1, 'render_func' => 'rcmail_format_date_col', 'category' => 'personal'),
'website' => array('type' => 'text', 'size' => 40, 'maxlength' => 50, 'label' => $rc->gettext('website'), 'subtypes' => array('homepage','work','blog','profile','other'), 'category' => 'main'),
'notes' => array('type' => 'textarea', 'size' => 40, 'rows' => 15, 'maxlength' => 500, 'label' => $rc->gettext('notes'), 'limit' => 1),
'photo' => array('type' => 'image', 'limit' => 1, 'category' => 'main'),
'assistant' => array('type' => 'text', 'size' => 40, 'maxlength' => 50, 'limit' => 1, 'label' => $rc->gettext('assistant'), 'category' => 'personal'),
'manager' => array('type' => 'text', 'size' => 40, 'maxlength' => 50, 'limit' => 1, 'label' => $rc->gettext('manager'), 'category' => 'personal'),
'spouse' => array('type' => 'text', 'size' => 40, 'maxlength' => 50, 'limit' => 1, 'label' => $rc->gettext('spouse'), 'category' => 'personal'),
// TODO: define fields for vcards like GEO, KEY
); /* }}} */
$this->addextrasubtypes();
}}}
/**
* Stores a custom label in the database (X-ABLabel extension).
*
* @param string Name of the type/category (phone,address,email)
* @param string Name of the custom label to store for the type
*/
private function storeextrasubtype($typename, $subtype)
{{{
$dbh = rcmail::get_instance()->db;
$sql_result = $dbh->query('INSERT INTO ' .
$dbh->table_name('carddav_xsubtypes') .
' (typename,subtype,abook_id) VALUES (?,?,?)',
$typename, $subtype, $this->id);
}}}
/**
* Adds known custom labels to the roundcube subtype list (X-ABLabel extension).
*
* Reads the previously seen custom labels from the database and adds them to the
* roundcube subtype list in #coltypes and additionally stores them in the #xlabels
* list.
*/
private function addextrasubtypes()
{{{
$this->xlabels = array();
foreach($this->coltypes as $k => $v) {
if(array_key_exists('subtypes', $v)) {
$this->xlabels[$k] = array();
} }
// read extra subtypes
$xtypes = self::get_dbrecord($this->id,'typename,subtype','xsubtypes',false,'abook_id');
foreach ($xtypes as $row) {
$this->coltypes[$row['typename']]['subtypes'][] = $row['subtype'];
$this->xlabels[$row['typename']][] = $row['subtype'];
}
}}}
/**
* Returns addressbook name (e.g. for addressbooks listing).
*
* @return string name of this addressbook
*/
public function get_name()
{{{
return $this->config['name'];
}}}
/**
* Save a search string for future listings.
*
* @param mixed Search params to use in listing method, obtained by get_search_set()
*/
public function set_search_set($filter)
{{{
$this->filter = $filter;
$this->total_cards = -1;
}}}
/**
* Getter for saved search properties
*
* @return mixed Search properties used by this class
*/
public function get_search_set()
{{{
return $this->filter;
}}}
/**
* Reset saved results and search parameters
*/
public function reset()
{{{
$this->result = null;
$this->filter = null;
$this->total_cards = -1;
}}}
/**
* Determines the name to be displayed for a contact. The routine
* distinguishes contact cards for individuals from organizations.
*/
private function set_displayname(&$save_data)
{{{
if(strcasecmp($save_data['showas'], 'COMPANY') == 0 && strlen($save_data['organization'])>0) {
$save_data['name'] = $save_data['organization'];
}
// we need a displayname; if we do not have one, try to make one up
if(strlen($save_data['name']) == 0) {
$dname = array();
if(strlen($save_data['firstname'])>0)
$dname[] = $save_data['firstname'];
if(strlen($save_data['surname'])>0)
$dname[] = $save_data['surname'];
if(count($dname) > 0) {
$save_data['name'] = implode(' ', $dname);
} else { // no name? try email and phone
$ep_keys = array_keys($save_data);
$ep_keys = preg_grep(";^(email|phone):;", $ep_keys);
sort($ep_keys, SORT_STRING);
foreach($ep_keys as $ep_key) {
$ep_vals = $save_data[$ep_key];
if(!is_array($ep_vals)) $ep_vals = array($ep_vals);
foreach($ep_vals as $ep_val) {
if(strlen($ep_val)>0) {
$save_data['name'] = $ep_val;
break 2;
}
}
}
}
// still no name? set to unknown and hope the user will fix it
if(strlen($save_data['name']) == 0)
$save_data['name'] = 'Unset Displayname';
}
}}}
/**
* Stores a group vcard in the database.
*
* @param string etag of the VCard in the given version on the CardDAV server
* @param string path to the VCard on the CardDAV server
* @param string string representation of the VCard
* @param array associative array containing at least name and cuid (card UID)
* @param int optionally, database id of the group if the store operation is an update
*
* @return int The database id of the created or updated card, false on error.
*/
private function dbstore_group($etag, $uri, $vcfstr, $save_data, $dbid=0)
{{{
return $this->dbstore_base('groups',$etag,$uri,$vcfstr,$save_data,$dbid);
}}}
private function dbstore_base($table, $etag, $uri, $vcfstr, $save_data, $dbid=0, $xcol=array(), $xval=array())
{{{
$dbh = rcmail::get_instance()->db;
// get rid of the %u placeholder in the URI, otherwise the refresh operation
// will not be able to match local cards with those provided by the server
$username = $this->config['username'];
if($username === "%u")
$username = $_SESSION['username'];
$uri = str_replace("%u", $username, $uri);
$xcol[]='name'; $xval[]=$save_data['name'];
$xcol[]='etag'; $xval[]=$etag;
$xcol[]='vcard'; $xval[]=$vcfstr;
if($dbid) {
self::$helper->debug("UPDATE card $uri");
$xval[]=$dbid;
$sql_result = $dbh->query('UPDATE ' .
$dbh->table_name("carddav_$table") .
' SET ' . implode('=?,', $xcol) . '=?' .
' WHERE id=?', $xval);
} else {
self::$helper->debug("INSERT card $uri");
if ("x".$save_data['cuid'] == "x"){
// There is no contact UID in the VCARD, try to create one
$cuid = $uri;
$cuid = preg_replace(';^.*/;', "", $cuid);
$cuid = preg_replace(';\.vcf$;', "", $cuid);
$save_data['cuid'] = $cuid;
}
$xcol[]='abook_id'; $xval[]=$this->id;
$xcol[]='uri'; $xval[]=$uri;
$xcol[]='cuid'; $xval[]=$save_data['cuid'];
$sql_result = $dbh->query('INSERT INTO ' .
$dbh->table_name("carddav_$table") .
' (' . implode(',',$xcol) . ') VALUES (?' . str_repeat(',?', count($xcol)-1) .')',
$xval);
$dbid = $dbh->insert_id("carddav_$table");
}
if($dbh->is_error()) {
self::$helper->warn($dbh->is_error());
$this->set_error(self::ERROR_SAVING, $dbh->is_error());
return false;
}
return $dbid;
}}}
/**
* Stores a contact to the local database.
*
* @param string etag of the VCard in the given version on the CardDAV server
* @param string path to the VCard on the CardDAV server
* @param string string representation of the VCard
* @param array associative array containing the roundcube save data for the contact
* @param int optionally, database id of the contact if the store operation is an update
*
* @return int The database id of the created or updated card, false on error.
*/
private function dbstore_contact($etag, $uri, $vcfstr, $save_data, $dbid=0)
{{{
$this->preprocess_rc_savedata($save_data);
// build email search string
$email_keys = preg_grep('/^email(:|$)/', array_keys($save_data));
$email_addrs = array();
foreach($email_keys as $email_key) {
$email_addrs = array_merge($email_addrs, (array) $save_data[$email_key]);
}
$save_data['email'] = implode(', ', $email_addrs);
// extra columns for the contacts table
$xcol_all=array('firstname','surname','organization','showas','email');
$xcol=array();
$xval=array();
foreach($xcol_all as $k) {
if(array_key_exists($k,$save_data)) {
$xcol[] = $k;
$xval[] = $save_data[$k];
} }
return $this->dbstore_base('contacts',$etag,$uri,$vcfstr,$save_data,$dbid,$xcol,$xval);
}}}
/**
* Checks if the given local card cache (for contacts or groups) contains
* a card with the given URI. If not, the function returns false.
* If yes, the card is marked seen in the cache, and the cached etag is
* compared with the given one. The function returns an associative array
* with the database id of the existing card (key dbid) and a boolean that
* indicates whether the card needs a server refresh as determined by the
* etag comparison (key needs_update).
*/
private static function checkcache(&$cache, $uri, $etag)
{{{
if(!array_key_exists($uri, $cache))
return false;
$cache[$uri]['seen'] = true;
$dbrec = $cache[$uri];
$dbid = $dbrec['id'];
$needsupd = true;
// abort if card has not changed
if($etag === $dbrec['etag']) {
self::$helper->debug("UNCHANGED card $uri");
$needsupd = false;
}
return array('needs_update'=>$needsupd, 'dbid'=>$dbid);
}}}
/**
* Synchronizes the local card store with the CardDAV server.
*/
private function refreshdb_from_server()
{{{
$dbh = rcmail::get_instance()->db;
$duration = time();
// determine existing local contact URIs and ETAGs
$contacts = self::get_dbrecord($this->id,'id,uri,etag','contacts',false,'abook_id');
foreach($contacts as $contact) {
$this->existing_card_cache[$contact['uri']] = $contact;
}
if(!$this->config['use_categories']) {
// determine existing local group URIs and ETAGs
$groups = self::get_dbrecord($this->id,'id,uri,etag','groups',false,'abook_id');
foreach($groups as $group) {
$this->existing_grpcard_cache[$group['uri']] = $group;
}
}
// used to record which users need to be added to which groups
$this->users_to_add = array();
// Check for supported-report-set and only use sync-collection if server advertises it.
// This suppresses 501 Not implemented errors with ownCloud.
$opts = array(
'method'=>"PROPFIND",
'header'=>array("Depth: 0", 'Content-Type: application/xml; charset="utf-8"'),
'content'=> <<<EOF
<?xml version="1.0" encoding="UTF-8" ?>
<propfind xmlns="DAV:"> <prop>
<supported-report-set/>
</prop> </propfind>
EOF
);
$reply = self::$helper->cdfopen($this->config['url'], $opts, $this->config);
$records = -1;
$xml = self::$helper->checkAndParseXML($reply);
if($xml !== false) {
$xpresult = $xml->xpath('//RCMCD:supported-report/RCMCD:report/RCMCD:sync-collection');
if(count($xpresult) > 0) {
$records = $this->list_records_sync_collection();
}
}
// sync-collection not supported or returned error
if ($records < 0){
$records = $this->list_records_propfind();
}
foreach($this->users_to_add as $dbid => $cuids) {
if(count($cuids)<=0) continue;
$sql_result = $dbh->query('INSERT INTO '.
$dbh->table_name('carddav_group_user') .
' (group_id,contact_id) SELECT ?,id from ' .
$dbh->table_name('carddav_contacts') .
' WHERE abook_id=? AND cuid IN (' . implode(',', $cuids) . ')', $dbid, $this->id);
self::$helper->debug("Added " . $dbh->affected_rows($sql_result) . " contacts to group $dbid");
}
unset($this->users_to_add);
$this->existing_card_cache = array();
$this->existing_grpcard_cache = array();
// set last_updated timestamp
$dbh->query('UPDATE ' .
$dbh->table_name('carddav_addressbooks') .
' SET last_updated=' . $dbh->now() .' WHERE id=?',
$this->id);
$duration = time() - $duration;
self::$helper->debug("server refresh took $duration seconds");
if($records < 0) {
self::$helper->warn("Errors occurred during the refresh of addressbook " . $this->id);
}
}}}
/**
* List the current set of contact records
*
* @param array List of cols to show, Null means all
* @param int Only return this number of records, use negative values for tail
* @param boolean True to skip the count query (select only)
* @return array Indexed list of contact records, each a hash array
*/
public function list_records($cols=array(), $subset=0, $nocount=false)
{{{
// refresh from server if refresh interval passed
if ( $this->config['needs_update'] == 1 )
$this->refreshdb_from_server();
// XXX workaround for a roundcube bug to support roundcube's displayname setting
// Reported as Roundcube Ticket #1488394
if(count($cols)>0) {
if(!in_array('firstname', $cols)) {
$cols[] = 'firstname';
}
if(!in_array('surname', $cols)) {
$cols[] = 'surname';
}
}
// XXX workaround for a roundcube bug to support roundcube's displayname setting
// if the count is not requested we can save one query
if($nocount)
$this->result = new rcube_result_set();
else
$this->result = $this->count();
$records = $this->list_records_readdb($cols,$subset);
if($nocount) {
$this->result->count = $records;
} else if ($this->list_page <= 1) {
if ($records < $this->page_size && $subset == 0)
$this->result->count = $records;
else
$this->result->count = $this->_count($cols);
}
if ($records > 0){
return $this->result;
}
return false;
}}}
/**
* Retrieves the Card URIs from the CardDAV server
*
* @return int number of cards in collection, -1 on error
*/
private function list_records_sync_collection()
{{{
$sync_token = $this->config['sync_token'];
while(true) {
$opts = array(
'method'=>"REPORT",
'header'=>array("Depth: 0", 'Content-Type: application/xml; charset="utf-8"'),
'content'=> <<<EOF
<?xml version="1.0" encoding="utf-8" ?>
<D:sync-collection xmlns:D="DAV:" xmlns:C="urn:ietf:params:xml:ns:carddav">
<D:sync-token>$sync_token</D:sync-token>
<D:sync-level>1</D:sync-level>
<D:prop>
<D:getcontenttype/>
<D:getetag/>
</D:prop>
</D:sync-collection>
EOF
);
$reply = self::$helper->cdfopen($this->config['url'], $opts, $this->config);
$xml = self::$helper->checkAndParseXML($reply);
if($xml === false) {
// a server may invalidate old sync-tokens, in which case we need to do a full resync
if (strlen($sync_token)>0 && $reply == 412){
self::$helper->warn("Server reported invalid sync-token in sync of addressbook " . $this->config['abookid'] . ". Resorting to full resync.");
$sync_token = '';
continue;
} else {
return -1;
}
}
list($new_sync_token) = $xml->xpath('//RCMCD:sync-token');
$records = $this->addvcards($xml);
if(strlen($sync_token) == 0) {
if($records>=0) {
$this->delete_unseen();
}
} else {
$this->delete_synccoll($xml);
}
if($records >= 0) {
carddav::update_abook($this->config['abookid'], array('sync_token' => "$new_sync_token"));
// if we got a truncated result set continue sync
$xpresult = $xml->xpath('//RCMCD:response[contains(child::RCMCD:status, " 507 Insufficient Storage")]');
if(count($xpresult) > 0) {
$sync_token = "$new_sync_token";
continue;
}
}
break;
}
return $records;
}}}
private function list_records_readdb($cols, $subset=0, $count_only=false)
{{{
$dbh = rcmail::get_instance()->db;
// true if we can use DB filtering or no filtering is requested
$filter = $this->get_search_set();
$this->determine_filter_params($cols,$subset, $firstrow, $numrows, $read_vcard);
$dbattr = $read_vcard ? 'vcard' : 'firstname,surname,email';
$limit_index = $firstrow;
$limit_rows = $numrows;
$xfrom = '';
$xwhere = '';
if($this->group_id) {
$xfrom = ',' . $dbh->table_name('carddav_group_user');
$xwhere = ' AND id=contact_id AND group_id=' . $dbh->quote($this->group_id) . ' ';
}
// Workaround for Roundcube versions < 0.7.2
$sort_column = $this->sort_col ? $this->sort_col : 'surname';
$sort_order = $this->sort_order ? $this->sort_order : 'ASC';
$sql_result = $dbh->limitquery("SELECT id,name,$dbattr FROM " .
$dbh->table_name('carddav_contacts') . $xfrom .
' WHERE abook_id=? ' . $xwhere .
($this->filter ? " AND (".$this->filter.")" : "") .
" ORDER BY (CASE WHEN showas='COMPANY' THEN organization ELSE " . $sort_column . " END) "
. $sort_order,
$limit_index,
$limit_rows,
$this->id
);
$addresses = array();
while($contact = $dbh->fetch_assoc($sql_result)) {
if($read_vcard) {
$save_data = $this->create_save_data_from_vcard($contact['vcard']);
if (!$save_data){
self::$helper->warn("Couldn't parse vcard ".$contact['vcard']);
continue;
}
// needed by the calendar plugin
if(is_array($cols) && in_array('vcard', $cols)) {
$save_data['save_data']['vcard'] = $contact['vcard'];
}
$save_data = $save_data['save_data'];
} else {
$save_data = array();
foreach ($cols as $col) {
if(strcmp($col,'email')==0)
$save_data[$col] = preg_split('/,\s*/', $contact[$col]);
else
$save_data[$col] = $contact[$col];
}
}
$addresses[] = array('ID' => $contact['id'], 'name' => $contact['name'], 'save_data' => $save_data);
}
if(!$count_only) {
// create results for roundcube
foreach($addresses as $a) {
$a['save_data']['ID'] = $a['ID'];
$this->result->add($a['save_data']);
}
}
return count($addresses);
}}}
private function query_addressbook_multiget($hrefs)
{{{
$dbh = rcmail::get_instance()->db;
$hrefstr = '';
foreach ($hrefs as $href) {
$hrefstr .= "<D:href>$href</D:href>\n";
}
$optsREPORT = array(
'method'=>"REPORT",
'header'=>array("Depth: 0", 'Content-Type: application/xml; charset="utf-8"'),
'content'=> <<<EOF
<?xml version="1.0" encoding="utf-8" ?>
<C:addressbook-multiget xmlns:D="DAV:" xmlns:C="urn:ietf:params:xml:ns:carddav">
<D:prop>
<D:getetag/>
<C:address-data>
<C:allprop/>
</C:address-data>
</D:prop>
$hrefstr
</C:addressbook-multiget>
EOF
);
$reply = self::$helper->cdfopen($this->config['url'], $optsREPORT, $this->config);
$xml = self::$helper->checkAndParseXML($reply);
if($xml === false) return -1;
$xpresult = $xml->xpath('//RCMCD:response[descendant::RCMCC:address-data]');
$numcards = 0;
foreach ($xpresult as $vcard) {
self::$helper->registerNamespaces($vcard);
list($href) = $vcard->xpath('child::RCMCD:href');
list($etag) = $vcard->xpath('descendant::RCMCD:getetag');
list($vcf) = $vcard->xpath('descendant::RCMCC:address-data');
// determine database ID of existing cards by checking the cache
$dbid = 0;
if( ($ret = self::checkcache($this->existing_card_cache,"$href","$etag"))
|| ($ret = self::checkcache($this->existing_grpcard_cache,"$href","$etag")) ) {
$dbid = $ret['dbid'];
}
// changed on server, parse VCF
$save_data = $this->create_save_data_from_vcard("$vcf");
$vcfobj = $save_data['vcf'];
if($save_data['needs_update'])
$vcf = $vcfobj->serialize();
$save_data = $save_data['save_data'];
if($save_data['kind'] === 'group') {
if(!$this->config['use_categories']) {
self::$helper->debug('Processing Group ' . $save_data['name']);
// delete current group members (will be reinserted if needed below)
if($dbid) self::delete_dbrecord($dbid,'group_user','group_id');
// store group card
if(!($dbid = $this->dbstore_group("$etag","$href","$vcf",$save_data,$dbid)))
return -1;
// record group members for deferred store
$this->users_to_add[$dbid] = array();
$members = $vcfobj->{'X-ADDRESSBOOKSERVER-MEMBER'};
self::$helper->debug("Group $dbid has " . count($members) . " members");
foreach($members as $mbr) {
$mbr = preg_split('/:/', $mbr);
if(!$mbr) continue;
if(count($mbr)!=3 || $mbr[0] !== 'urn' || $mbr[1] !== 'uuid') {
self::$helper->warn("don't know how to interpret group membership: " . implode(':', $mbr));
continue;
}
$this->users_to_add[$dbid][] = $dbh->quote($mbr[2]);
}
}
} else { // individual/other
if (trim($save_data['name']) == '') { // roundcube display fix for contacts that don't have first/last names
if ($save_data['nickname'] !== NULL && trim($save_data['nickname'] !== '')) {
$save_data['name'] = $save_data['nickname'];
} else {
foreach ($save_data as $key=>$val) {
if (strpos($key,'email') !== false) {
$save_data['name'] = $val[0];
break;
}
}
}
}
if($this->config['use_categories']) {
// delete current member from groups (will be reinserted if needed below)
self::delete_dbrecord($dbid,'group_user','contact_id');
foreach ($this->getCategories($vcfobj) as $category) {
if($category !== "All" && $category !== "Unfiled") {
$record = self::get_dbrecord($category, 'id', 'groups', true, 'name', array('abook_id' => $this->config['abookid']));
if(!$record) {
$cuid = $this->find_free_uid();
$uri = "$cuid.vcf";
$gsave_data = array(
'name' => $category,
'kind' => 'group',
'cuid' => $cuid,
);
$url = carddav_common::concaturl($this->config['url'], $uri);
$url = preg_replace(';https?://[^/]+;', '', $url);
// store group card
$vcfg = $this->create_vcard_from_save_data($gsave_data);
$vcfgstr = $vcfg->serialize();
if(!($database = $this->dbstore_group("dummy",$url,$vcfgstr,$gsave_data)))
return -1;
} else {
$database = $record['id'];
}
if(!isset($this->users_to_add[$database])) {
$this->users_to_add[$database] = array();
}
$uid = $save_data['cuid'];
$this->users_to_add[$database][] = $dbh->quote($uid);
}
}
}
if(!$this->dbstore_contact("$etag","$href","$vcf",$save_data,$dbid))
return -1;
}
$numcards++;
}
return $numcards;
}}}
private function list_records_propfind()
{{{
$opts = array(
'method'=>"PROPFIND",
'header'=>array("Depth: 1", 'Content-Type: application/xml; charset="utf-8"'),
'content'=> <<<EOF
<?xml version="1.0" encoding="utf-8" ?>
<a:propfind xmlns:a="DAV:"> <a:prop>
<a:getcontenttype/>
<a:getetag/>
</a:prop> </a:propfind>
EOF
);
$reply = self::$helper->cdfopen("", $opts, $this->config);
$xml = self::$helper->checkAndParseXML($reply);
if($xml === false) return -1;
$records = $this->addvcards($xml);
if($records>=0) {
$this->delete_unseen();
}
return $records;
}}}
private function addvcards($xml)
{{{
$urls = array();
$xpresult = $xml->xpath('//RCMCD:response[starts-with(translate(child::RCMCD:propstat/RCMCD:status, "ABCDEFGHJIKLMNOPQRSTUVWXYZ", "abcdefghjiklmnopqrstuvwxyz"), "http/1.1 200 ") and child::RCMCD:propstat/RCMCD:prop/RCMCD:getetag]');
foreach ($xpresult as $r) {
self::$helper->registerNamespaces($r);
list($href) = $r->xpath('child::RCMCD:href');
if(preg_match('/\/$/', $href)) continue;
list($etag) = $r->xpath('descendant::RCMCD:getetag');
$ret = self::checkcache($this->existing_card_cache,"$href","$etag");
$retgrp = self::checkcache($this->existing_grpcard_cache,"$href","$etag");
if( ($ret===false && $retgrp===false)
|| (is_array($ret) && $ret['needs_update'])
|| (is_array($retgrp) && $retgrp['needs_update']) )
{
$urls[] = "$href";
}
}
if (count($urls) > 0) {
$records = $this->query_addressbook_multiget($urls);
}
}}}
/** delete cards not present on the server anymore */
private function delete_unseen()
{{{
$delids = array();
foreach($this->existing_card_cache as $value) {
if(!array_key_exists('seen', $value) || !$value['seen']) {
$delids[] = $value['id'];
}
}
$del = self::delete_dbrecord($delids);
self::$helper->debug("deleted $del contacts during server refresh");
$delids = array();
foreach($this->existing_grpcard_cache as $value) {
if(!array_key_exists('seen', $value) || !$value['seen']) {
$delids[] = $value['id'];
}
}
$del = self::delete_dbrecord($delids,'groups');
self::$helper->debug("deleted $del groups during server refresh");
}}}
/** delete cards reported deleted by the server */
private function delete_synccoll($xml)
{{{
$xpresult = $xml->xpath('//RCMCD:response[contains(child::RCMCD:status, " 404 Not Found")]');
$del_contacts = array();
$del_groups = array();
foreach ($xpresult as $r) {
self::$helper->registerNamespaces($r);
list($href) = $r->xpath('child::RCMCD:href');
if(preg_match('/\/$/', $href)) continue;
if(isset($this->existing_card_cache["$href"])) {
$del_contacts[] = $this->existing_card_cache["$href"]['id'];
} else if(isset($this->existing_grpcard_cache["$href"])) {
$del_groups[] = $this->existing_grpcard_cache["$href"]['id'];
}
}
$del = self::delete_dbrecord($del_contacts);
self::$helper->debug("deleted $del contacts during incremental server refresh");
$del = self::delete_dbrecord($del_groups,'groups');
self::$helper->debug("deleted $del groups during incremental server refresh");
}}}
/**
* Search contacts
*
* @param mixed $fields The field name of array of field names to search in
* @param mixed $value Search value (or array of values when $fields is array)
* @param int $mode Matching mode:
* 0 - partial (*abc*),
* 1 - strict (=),
* 2 - prefix (abc*)
* @param boolean $select True if results are requested, False if count only
* @param boolean $nocount True to skip the count query (select only)
* @param array $required List of fields that cannot be empty
*
* @return object rcube_result_set Contact records and 'count' value
*/
function search($fields, $value, $mode=0, $select=true, $nocount=false, $required=array())
{{{
$dbh = rcmail::get_instance()->db;
if (!is_array($fields))
$fields = array($fields);
if (!is_array($required) && !empty($required))
$required = array($required);
$where = $and_where = array();
$mode = intval($mode);
$WS = ' ';
$AS = self::SEPARATOR;
// build the $where array; each of its entries is an SQL search condition
foreach ($fields as $idx => $col) {
// direct ID search
if ($col == 'ID' || $col == $this->primary_key) {
$ids = !is_array($value) ? explode(self::SEPARATOR, $value) : $value;
$ids = $dbh->array2list($ids, 'integer');
$where[] = $this->primary_key.' IN ('.$ids.')';
continue;
}
$val = is_array($value) ? $value[$idx] : $value;
// table column
if (in_array($col, $this->table_cols)) {
switch ($mode) {
case 1: // strict
$where[] =
// exact match '[email protected]'
'(' . $dbh->ilike($col, $val)
// line beginning match '[email protected],%'
. ' OR ' . $dbh->ilike($col, $val . $AS . '%')
// middle match '%, [email protected],%'
. ' OR ' . $dbh->ilike($col, '%' . $AS . $WS . $val . $AS . '%')
// line end match '%, [email protected]'
. ' OR ' . $dbh->ilike($col, '%' . $AS . $WS . $val) . ')';
break;
case 2: // prefix
$where[] = '(' . $dbh->ilike($col, $val . '%')
. ' OR ' . $dbh->ilike($col, $AS . $WS . $val . '%') . ')';
break;
default: // partial
$where[] = $dbh->ilike($col, '%' . $val . '%');
}
}
// vCard field
else {
foreach (explode(" ", self::normalize_string($val)) as $word) {
switch ($mode) {
case 1: // strict
$words[] = '(' . $dbh->ilike('vcard', $word . $WS . '%')
. ' OR ' . $dbh->ilike('vcard', '%' . $AS . $WS . $word . $WS .'%')
. ' OR ' . $dbh->ilike('vcard', '%' . $AS . $WS . $word) . ')';
break;
case 2: // prefix
$words[] = '(' . $dbh->ilike('vcard', $word . '%')
. ' OR ' . $dbh->ilike('vcard', $AS . $WS . $word . '%') . ')';
break;
default: // partial
$words[] = $dbh->ilike('vcard', '%' . $word . '%');
}
}
$where[] = '(' . join(' AND ', $words) . ')';
if (is_array($value))
$post_search[$col] = mb_strtolower($val);
}
}
foreach (array_intersect($required, $this->table_cols) as $col) {
$and_where[] = $dbh->quoteIdentifier($col).' <> '.$dbh->quote('');
}
if (!empty($where)) {
// use AND operator for advanced searches