-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathroundcubecontacts.php
917 lines (814 loc) · 27.4 KB
/
roundcubecontacts.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
<?php
/**
* This backend is for roundcube contacts in MySQL
*
* Based on Zarafa's vcard directory backend
* Roundcube modifications by Alex Charrett.
* TODO: Switch to PDO, clean up SQL injection, import IMAP message code.
* Buggy mobile number detection code is around line 560.
*
* @author Alex Charrett <alex@transposed.org>
* @author Kitson Consulting <kitson-consulting.co.uk>
* @copyright 2007-2012 Zarafa Deutschland GmbH
* @copyright 2013-2015 Alex Charrett
* @copyright 2015 Kitson Consulting Limited
* @opyright 2017 James Coyle - JamesCoyle.net Limited
* @date 2015-09-20
* @file roundcubecontacts.php
* @licence https://www.gnu.org/licenses/agpl-3.0.en.html Gnu Affero Public Licence v3
* @project Z-Push
*/
// config file
require_once("backend/roundcubecontacts/config.php");
include_once( 'lib/default/diffbackend/diffbackend.php' );
class BackendRoundcubeContacts extends BackendDiff {
private $logged_in_user;
private $db_user_id;
private $contactsdb;
private $authdb;
private function dbConnectContacts()
{
ZLog::Write( LOGLEVEL_DEBUG, 'dbConnectContacts()' );
$this->contactsdb = mysqli_connect( ROUNDCUBE_CONTACT_DB_HOST, ROUNDCUBE_CONTACT_DB_USER, ROUNDCUBE_CONTACT_DB_PASS );
@mysqli_select_db( $this->contactsdb, ROUNDCUBE_CONTACT_DB_NAME ) or ZLog::Write( LOGLEVEL_ERROR, ( 'Unable to open contacts database' ) );
}
private function dbConnectAuth()
{
ZLog::Write( LOGLEVEL_DEBUG, 'dbConnectAuth()' );
$this->authdb = mysqli_connect( ROUNDCUBE_AUTH_DB_HOST, ROUNDCUBE_AUTH_DB_USER, ROUNDCUBE_AUTH_DB_PASS );
@mysqli_select_db( $this->authdb, ROUNDCUBE_AUTH_DB_NAME ) or ZLog::Write( LOGLEVEL_ERROR, ( 'Unable to open auth database' ) );
}
private function dbSelectUserId( $username )
{
// select the user id from the database with the username that's logging in
ZLog::Write( LOGLEVEL_DEBUG, "dbSelectUserId( $username )" );
$query = "SELECT user_id FROM users where username='$username'";
$result = mysqli_query( $this->contactsdb, $query ) or ZLog::Write( LOGLEVEL_ERROR, ( mysqli_error( $this->contactsdb ) ) );
$user_id = "~none~";
while( $result_rows = mysqli_fetch_array( $result ) )
{
$user_id = $result_rows[0];
}
return $user_id;
}
private function dbCreateUser( $username )
{
// add a new user row to theusers table for our user
ZLog::Write( LOGLEVEL_DEBUG, "dbCreateUser( $username )" );
$query = "SELECT DISTINCT mail_host,language FROM users LIMIT 1";
$result = mysqli_query($this->contactsdb, $query ) or ZLog::Write( LOGLEVEL_ERROR, ( mysqli_error( $this->contactsdb ) ) );
$mail_host = "";
$lang = "";
while( $result_rows = mysqli_fetch_array( $result ) )
{
$mail_host = $result_rows[0];
$lang = $result_rows[1];
}
$insert = "INSERT INTO users ( username, created, mail_host, language ) VALUES ( '$username', NOW(), '$mail_host', '$lang' )";
mysqli_query( $this->contactsdb, $insert ) or ZLog::Write( LOGLEVEL_DEBUG, ( mysqli_error( $this->contactsdb ) ) );
}
private function getUserId( $username )
{
// Get the user ID, if none is found, create one
ZLog::Write( LOGLEVEL_DEBUG, "getUserId( $username )" );
$clean_username = mysqli_real_escape_string( $this->contactsdb, $username );
$user_id = $this->dbSelectUserId( $clean_username );
if( strcmp( $user_id, "~none~" ) === 0 )
{
$this->dbCreateUser( $clean_username );
$user_id = $this->dbSelectUserId( $clean_username );
}
return $user_id;
}
/**----------------------------------
* default backend methods
*/
/**
* Authenticates the user
*
* @param string $username
* @param string $domain
* @param string $password
*
* @access public
* @return boolean
*/
public function Logon( $username, $domain, $password )
{
$this->dbConnectContacts();
$login_success = false;
if(strcmp(ROUNDCUBE_CONTACT_USER_AUTH,"database")==0)
{
$this->dbConnectAuth();
$password_from_db=$this->getEncryptedPassword($username);
$crypted=crypt($password, $password_from_db);
if (strcmp($crypted,$password_from_db)==0)
{
$login_success = true;
}
}
elseif(strcmp(ROUNDCUBE_CONTACT_USER_AUTH,"imap")==0)
{
$imap_handle = imap_open (ROUNDCUBE_CONTACT_IMAP_SERVER, $username, $password);
if( ! ($imap_handle === false ) )
{
imap_close( $imap_handle );
$login_success = true;
}
}
if( $login_success )
{
ZLog::Write( LOGLEVEL_DEBUG, sprintf( "Logon(): User '%s' is authenticated", $username ) );
$this->logged_in_user = strtolower( $username );
$this->db_user_id = $this->getUserId( $this->logged_in_user );
ZLog::Write( LOGLEVEL_DEBUG, "Logon(): User $username has ID $this->db_user_id in contacts DB" );
return true;
}
else
{
ZLog::Write( LOGLEVEL_DEBUG, sprintf( "Logon(): User '%s' failed to authenticate", $username ) );
return false;
}
}
/**
* Logs off
*
* @access public
* @return boolean
*/
public function Logoff()
{
return true;
}
/**
* Sends an e-mail
* Not implemented here
*
* @param SyncSendMail $sm SyncSendMail object
*
* @access public
* @return boolean
* @throws StatusException
*/
public function SendMail( $sm )
{
return false;
}
/**
* Returns the waste basket
*
* @access public
* @return string
*/
public function GetWasteBasket()
{
return 'DeletedItems';
}
/**
* Returns the content of the named attachment as stream
* not implemented
*
* @param string $attname
*
* @access public
* @return SyncItemOperationsAttachment
* @throws StatusException
*/
public function GetAttachmentData( $attname )
{
return false;
}
/**----------------------------------
* implemented DiffBackend methods
*/
/**
* Returns a list (array) of folders.
* In simple implementations like this one, probably just one folder is returned.
*
* @access public
* @return array
*/
public function GetFolderList()
{
ZLog::Write( LOGLEVEL_DEBUG, 'VCDir::GetFolderList()' );
$contacts = array();
$folder = $this->StatFolder( 'root' );
$contacts[] = $folder;
return $contacts;
}
/**
* Returns an actual SyncFolder object
*
* @param string $id id of the folder
*
* @access public
* @return object SyncFolder with information
*/
public function GetFolder($id)
{
ZLog::Write( LOGLEVEL_DEBUG, "VCDir::GetFolder( $id )" );
if( $id === 'root' )
{
$folder = new SyncFolder();
$folder->serverid = $id;
$folder->parentid = '0';
$folder->displayname = 'Contacts';
$folder->type = SYNC_FOLDER_TYPE_CONTACT;
return $folder;
}
else return false;
}
/**
* Returns folder stats. An associative array with properties is expected.
*
* @param string $id id of the folder
*
* @access public
* @return array
*/
public function StatFolder( $id )
{
ZLog::Write( LOGLEVEL_DEBUG, "VCDir::StatFolder( $id )" );
$folder = $this->GetFolder( $id );
$stat = array();
$stat['id'] = $id;
$stat['parent'] = $folder->parentid;
$stat['mod'] = $folder->displayname;
return $stat;
}
/**
* Creates or modifies a folder
* not implemented
*
* @param string $folderid id of the parent folder
* @param string $oldid if empty -> new folder created, else folder is to be renamed
* @param string $displayname new folder name (to be created, or to be renamed to)
* @param int $type folder type
*
* @access public
* @return boolean status
* @throws StatusException could throw specific SYNC_FSSTATUS_* exceptions
*
*/
public function ChangeFolder( $folderid, $oldid, $displayname, $type )
{
return false;
}
/**
* Deletes a folder
*
* @param string $id
* @param string $parent is normally false
*
* @access public
* @return boolean status - false if e.g. does not exist
* @throws StatusException could throw specific SYNC_FSSTATUS_* exceptions
*
*/
public function DeleteFolder( $id, $parentid )
{
return false;
}
/**
* Returns a list (array) of messages
*
* @param string $folderid id of the parent folder
* @param long $cutoffdate timestamp in the past from which on messages should be returned
*
* @access public
* @return array/false array with messages or false if folder is not available
*/
public function GetMessageList( $folderid, $cutoffdate )
{
ZLog::Write( LOGLEVEL_DEBUG, "VCDir::GetMessageList( $folderid )" );
$messages = array();
// if the folder is "DeletedItems" then return items flagged as deleted
if( strcmp( "$folderid", 'DeletedItems' ) === 0 )
{
$del = 1;
}
else
{
$del = 0;
}
$query = "SELECT contact_id, changed from contacts where user_id = '$this->db_user_id' and del = '$del'";
$result = mysqli_query( $this->contactsdb, $query ) or print ( mysqli_error( $this->contactsdb ) );
while( $result_rows = mysqli_fetch_array( $result ) )
{
$message = array();
$message['id'] = $result_rows[0];
$message['mod'] = strtotime( $result_rows[1] );
$message['flags'] = 1; // always 'read'
$messages[] = $message;
}
/* $dir = opendir($this->getPath());
if(!$dir)
return false;
while($entry = readdir($dir)) {
if(is_dir($this->getPath() .'/'.$entry))
continue;
$message = array();
$message["id"] = $entry;
$stat = stat($this->getPath() .'/'.$entry);
$message["mod"] = $stat["mtime"];
$message["flags"] = 1; // always 'read'
$messages[] = $message;
}
*/
return $messages;
}
/**
* Returns the actual SyncXXX object type.
*
* @param string $folderid id of the parent folder
* @param string $id id of the message
* @param ContentParameters $contentparameters parameters of the requested message (truncation, mimesupport etc)
*
* @access public
* @return object/false false if the message could not be retrieved
*/
public function GetMessage( $folderid, $id, $contentparameters )
{
ZLog::Write( LOGLEVEL_DEBUG, "VCDir::GetMessage($folderid, $id, ..)" );
if( $folderid !== 'root' )
return;
$types = array ('dom' => 'type', 'intl' => 'type', 'postal' => 'type', 'parcel' => 'type', 'home' => 'type', 'work' => 'type',
'pref' => 'type', 'voice' => 'type', 'fax' => 'type', 'msg' => 'type', 'cell' => 'type', 'pager' => 'type',
'bbs' => 'type', 'modem' => 'type', 'car' => 'type', 'isdn' => 'type', 'video' => 'type',
'aol' => 'type', 'applelink' => 'type', 'attmail' => 'type', 'cis' => 'type', 'eworld' => 'type',
'internet' => 'type', 'ibmmail' => 'type', 'mcimail' => 'type',
'powershare' => 'type', 'prodigy' => 'type', 'tlx' => 'type', 'x400' => 'type',
'gif' => 'type', 'cgm' => 'type', 'wmf' => 'type', 'bmp' => 'type', 'met' => 'type', 'pmb' => 'type', 'dib' => 'type',
'pict' => 'type', 'tiff' => 'type', 'pdf' => 'type', 'ps' => 'type', 'jpeg' => 'type', 'qtime' => 'type',
'mpeg' => 'type', 'mpeg2' => 'type', 'avi' => 'type',
'wave' => 'type', 'aiff' => 'type', 'pcm' => 'type',
'x509' => 'type', 'pgp' => 'type', 'text' => 'value', 'inline' => 'value', 'url' => 'value', 'cid' => 'value', 'content-id' => 'value',
'7bit' => 'encoding', '8bit' => 'encoding', 'quoted-printable' => 'encoding', 'base64' => 'encoding',
);
// Parse the vcard
$message = new SyncContact();
$query = "SELECT vcard, name, email, firstname, surname from contacts where user_id = '$this->db_user_id' and contact_id = '$id' and del = '0'";
$result = mysqli_query( $query, $this->contactsdb ) or print ( mysqli_error( $this->contactsdb ) );
$results = 0;
while( $result_rows = mysqli_fetch_array( $result ) )
{
$data = $result_rows[0];
$name = $result_rows[1];
$email = $result_rows[2];
$firstname = $result_rows[3];
$surname = $result_rows[4];
++$results;
}
if( ( $results >= 1 ) and ( ( strlen( $data ) ) === 0 ) )
{
$data = "BEGIN:VCARD\nVERSION:3.0\nN:$surname;$firstname;;;\nFN:$name\nEMAIL;TYPE=INTERNET:$email\nEND:VCARD";
}
$data = str_replace( "\x00", '', $data );
$data = str_replace( "\r\n", "\n", $data );
$data = str_replace( "\r", "\n", $data );
$data = preg_replace( '/(\n)([ \t])/i', '', $data );
$lines = explode( "\n", $data );
$vcard = array();
foreach( $lines as $line )
{
if( trim( $line ) === '' )
continue;
$pos = strpos( $line, ':' );
if( $pos === false )
continue;
$field = trim( substr( $line, 0, $pos ) );
$value = trim( substr( $line, $pos + 1 ) );
$fieldparts = preg_split( '/(?<!\\\\)(\;)/i', $field, -1, PREG_SPLIT_NO_EMPTY );
$type = strtolower( array_shift( $fieldparts ) );
$fieldvalue = array();
foreach( $fieldparts as $fieldpart )
{
if( preg_match( '/([^=]+)=(.+)/', $fieldpart, $matches ) )
{
if( !in_array( strtolower( $matches[1] ), array( 'value', 'type', 'encoding', 'language' ) ) )
continue;
if( isset( $fieldvalue[strtolower( $matches[1] )] ) and is_array( $fieldvalue[strtolower( $matches[1] )] ) )
{
$fieldvalue[strtolower( $matches[1] )] = array_merge( $fieldvalue[strtolower( $matches[1] )], preg_split( '/(?<!\\\\)(\,)/i', $matches[2], -1, PREG_SPLIT_NO_EMPTY ) );
}
else
{
$fieldvalue[strtolower( $matches[1] )] = preg_split( '/(?<!\\\\)(\,)/i', $matches[2], -1, PREG_SPLIT_NO_EMPTY );
}
}
else
{
if( !isset( $types[strtolower( $fieldpart )] ) )
continue;
$fieldvalue[$types[strtolower( $fieldpart )]][] = $fieldpart;
}
}
//
switch( $type )
{
case 'categories':
//case 'nickname':
$val = preg_split( '/(?<!\\\\)(\,)/i', $value );
$val = array_map( 'w2ui', $val );
break;
default:
$val = preg_split( '/(?<!\\\\)(\;)/i', $value );
break;
}
if( isset( $fieldvalue['encoding'][0] ) )
{
switch( strtolower( $fieldvalue['encoding'][0] ) )
{
case 'q':
case 'quoted-printable':
foreach( $val as $i => $v )
{
$val[$i] = quoted_printable_decode( $v );
}
break;
case 'b':
case 'base64':
foreach( $val as $i => $v )
{
$val[$i] = base64_decode( $v );
}
break;
}
}
else
{
foreach( $val as $i => $v )
{
$val[$i] = $this->unescape( $v );
}
}
$fieldvalue['val'] = $val;
$vcard[$type][] = $fieldvalue;
}
if( isset( $vcard['email'][0]['val'][0] ) )
$message->email1address = $vcard['email'][0]['val'][0];
if( isset( $vcard['email'][1]['val'][0] ) )
$message->email2address = $vcard['email'][1]['val'][0];
if( isset( $vcard['email'][2]['val'][0] ) )
$message->email3address = $vcard['email'][2]['val'][0];
// Calling array_map repeatedly throughout this clause is inefficient, but it works.
// This code shouldn't get called all that often. Refactoring welcome.
if( isset( $vcard['tel'] ) )
{
foreach( $vcard['tel'] as $tel )
{
if( !isset( $tel['type'] ) )
{
$tel['type'] = array();
}
if( in_array( 'car', array_map( 'mb_strtolower', $tel['type'] ) ) )
{
$message->carphonenumber = $tel['val'][0];
}
elseif( in_array( 'pager', array_map( 'mb_strtolower', $tel['type'] ) ) )
{
$message->pagernumber = $tel['val'][0];
}
elseif( in_array( 'cell', array_map( 'mb_strtolower', $tel['type'] ) ) )
{
$message->mobilephonenumber = $tel['val'][0];
}
elseif( in_array( 'home', array_map( 'mb_strtolower', $tel['type'] ) ) )
{
if( in_array( 'fax', array_map( 'mb_strtolower', $tel['type'] ) ) )
{
$message->homefaxnumber = $tel['val'][0];
}
elseif( empty( $message->homephonenumber ) )
{
$message->homephonenumber = $tel['val'][0];
}
else
{
$message->home2phonenumber = $tel['val'][0];
}
}
elseif( in_array( 'work', array_map( 'mb_strtolower', $tel['type'] ) ) )
{
if( in_array( 'fax', array_map( 'mb_strtolower', $tel['type'] ) ) )
{
$message->businessfaxnumber = $tel['val'][0];
}
elseif( empty( $message->businessphonenumber ) )
{
$message->businessphonenumber = $tel['val'][0];
}
else
{
$message->business2phonenumber = $tel['val'][0];
}
}
elseif( empty(
$message->homephonenumber ) )
{
$message->homephonenumber = $tel['val'][0];
}
elseif( empty( $message->home2phonenumber ) )
{
$message->home2phonenumber = $tel['val'][0];
}
else
{
$message->radiophonenumber = $tel['val'][0];
}
}
}
//;;street;city;state;postalcode;country
if(isset($vcard['adr'])){
foreach($vcard['adr'] as $adr) {
if(empty($adr['type'])){
$a = 'other';
}elseif(in_array('home', $adr['type'])){
$a = 'home';
}elseif(in_array('work', $adr['type'])){
$a = 'business';
}else{
$a = 'other';
}
if(!empty($adr['val'][2])){
$b=$a.'street';
$message->$b = w2ui($adr['val'][2]);
}
if(!empty($adr['val'][3])){
$b=$a.'city';
$message->$b = w2ui($adr['val'][3]);
}
if(!empty($adr['val'][4])){
$b=$a.'state';
$message->$b = w2ui($adr['val'][4]);
}
if(!empty($adr['val'][5])){
$b=$a.'postalcode';
$message->$b = w2ui($adr['val'][5]);
}
if(!empty($adr['val'][6])){
$b=$a.'country';
$message->$b = w2ui($adr['val'][6]);
}
}
}
if(!empty($vcard['fn'][0]['val'][0]))
$message->fileas = w2ui($vcard['fn'][0]['val'][0]);
if(!empty($vcard['n'][0]['val'][0]))
$message->lastname = w2ui($vcard['n'][0]['val'][0]);
if(!empty($vcard['n'][0]['val'][1]))
$message->firstname = w2ui($vcard['n'][0]['val'][1]);
if(!empty($vcard['n'][0]['val'][2]))
$message->middlename = w2ui($vcard['n'][0]['val'][2]);
if(!empty($vcard['n'][0]['val'][3]))
$message->title = w2ui($vcard['n'][0]['val'][3]);
if(!empty($vcard['n'][0]['val'][4]))
$message->suffix = w2ui($vcard['n'][0]['val'][4]);
if(!empty($vcard['bday'][0]['val'][0])){
$tz = date_default_timezone_get();
date_default_timezone_set('UTC');
$message->birthday = strtotime($vcard['bday'][0]['val'][0]);
date_default_timezone_set($tz);
}
if(!empty($vcard['org'][0]['val'][0]))
$message->companyname = w2ui($vcard['org'][0]['val'][0]);
if(!empty($vcard['note'][0]['val'][0])){
$message->body = w2ui($vcard['note'][0]['val'][0]);
$message->bodysize = strlen($vcard['note'][0]['val'][0]);
$message->bodytruncated = 0;
}
if(!empty($vcard['role'][0]['val'][0]))
$message->jobtitle = w2ui($vcard['role'][0]['val'][0]);//$vcard['title'][0]['val'][0]
if(!empty($vcard['url'][0]['val'][0]))
$message->webpage = w2ui($vcard['url'][0]['val'][0]);
if(!empty($vcard['categories'][0]['val']))
$message->categories = $vcard['categories'][0]['val'];
if(!empty($vcard['photo'][0]['val'][0]))
$message->picture = base64_encode($vcard['photo'][0]['val'][0]);
return $message;
}
/**
* Returns message stats, analogous to the folder stats from StatFolder().
*
* @param string $folderid id of the folder
* @param string $id id of the message
*
* @access public
* @return array
*/
public function StatMessage($folderid, $id) {
ZLog::Write(LOGLEVEL_DEBUG, 'VCDir::StatMessage('.$folderid.', '.$id.')');
if($folderid != "root")
return false;
$query="SELECT contact_id,changed from contacts where user_id='$this->db_user_id' and del='0' and contact_id='$id'";
$result=mysqli_query($query,$this->contactsdb) or print (mysqli_error($this->contactsdb));
$message = array();
while($result_rows = mysqli_fetch_array($result)){
$message["id"] = $result_rows[0];
$message["mod"] = strtotime($result_rows[1]);
$message["flags"] = 1; // always 'read'
}
return $message;
}
/**
* Called when a message has been changed on the mobile.
* This functionality is not available for emails.
*
* @param string $folderid id of the folder
* @param string $id id of the message
* @param SyncXXX $message the SyncObject containing a message
*
* @access public
* @return array same return value as StatMessage()
* @throws StatusException could throw specific SYNC_STATUS_* exceptions
*/
public function ChangeMessage($folderid, $id, $message, $contentParameters) {
ZLog::Write(LOGLEVEL_DEBUG, 'VCDir::ChangeMessage('.$folderid.', '.$id.', ..)');
$mapping = array(
'fileas' => 'FN',
'lastname;firstname;middlename;title;suffix' => 'N',
'email1address' => 'EMAIL;INTERNET',
'email2address' => 'EMAIL;INTERNET',
'email3address' => 'EMAIL;INTERNET',
'businessphonenumber' => 'TEL;WORK',
'business2phonenumber' => 'TEL;WORK',
'businessfaxnumber' => 'TEL;WORK;FAX',
'homephonenumber' => 'TEL;HOME',
'home2phonenumber' => 'TEL;HOME',
'homefaxnumber' => 'TEL;HOME;FAX',
'mobilephonenumber' => 'TEL;CELL',
'carphonenumber' => 'TEL;CAR',
'pagernumber' => 'TEL;PAGER',
';;businessstreet;businesscity;businessstate;businesspostalcode;businesscountry' => 'ADR;WORK',
';;homestreet;homecity;homestate;homepostalcode;homecountry' => 'ADR;HOME',
';;otherstreet;othercity;otherstate;otherpostalcode;othercountry' => 'ADR',
'companyname' => 'ORG',
'body' => 'NOTE',
'jobtitle' => 'ROLE',
'webpage' => 'URL',
);
$data = "BEGIN:VCARD\nVERSION:2.1\nPRODID:Z-Push\n";
foreach($mapping as $k => $v){
$val = '';
$ks = explode(';', $k);
foreach($ks as $i){
if(!empty($message->$i))
$val .= $this->escape($message->$i);
$val.=';';
}
if(empty($val))
continue;
$val = substr($val,0,-1);
if(strlen($val)>50){
$data .= $v.":\n\t".substr(chunk_split($val, 50, "\n\t"), 0, -1);
}else{
$data .= $v.':'.$val."\n";
}
}
if(!empty($message->categories))
$data .= 'CATEGORIES:'.implode(',', $this->escape($message->categories))."\n";
if(!empty($message->picture))
$data .= 'PHOTO;ENCODING=BASE64;TYPE=JPEG:'."\n\t".substr(chunk_split($message->picture, 50, "\n\t"), 0, -1);
if(isset($message->birthday))
$data .= 'BDAY:'.date('Y-m-d', $message->birthday)."\n";
$data .= "END:VCARD";
// not supported: anniversary, assistantname, assistnamephonenumber, children, department, officelocation, radiophonenumber, spouse, rtf
$fullname=$message->fileas;
$surname=$message->lastname;
$firstname=$message->firstname;
// Roundcube appears to file multiple email addresses as CSV in the email field
$emailaddress=$message->email1address;
if((strlen($message->email2address))>0) {
$emailaddress .= ",$message->email2address";
}
if((strlen($message->email3address))>0) {
$emailaddress .= ",$message->email3address";
}
// If there's no $id, then this is a new record.
if(!$id){
$query1="INSERT INTO contacts (vcard,name,email,firstname,surname,user_id,del,changed) VALUES ('$data','$fullname','$emailaddress','$firstname','$surname','$this->db_user_id','0',NOW())";
}
// Otherwise, we're updating an exisitng id.
else {
$query1="UPDATE contacts SET vcard='$data',name='$fullname',email='$emailaddress',firstname='$firstname',surname='$surname',changed=NOW() WHERE user_id='$this->db_user_id' and contact_id='$id'";
}
ZLog::Write(LOGLEVEL_DEBUG, "ChangeMessage $query1");
mysqli_query($query1,$this->contactsdb) or ZLog::Write(LOGLEVEL_DEBUG, (mysqli_error($this->contactsdb)));
// If this is a new entry, we want to know the ID of the record we just added
if(!$id){
$query2="SELECT contact_id FROM contacts WHERE user_id='$this->db_user_id' AND name='$fullname' AND email='$emailaddress' AND firstname='$firstname' AND surname='$surname' AND vcard='$data' ORDER BY contact_id DESC LIMIT 1";
$result2=mysqli_query($query2,$this->contactsdb) or print (mysqli_error($this->contactsdb));
while($result_rows = mysqli_fetch_array($result2)){
$id=$result_rows[0];
ZLog::Write(LOGLEVEL_DEBUG, "ChangeMessage new contact id is $id");
}
}
return $this->StatMessage($folderid, $id);
}
/**
* Changes the 'read' flag of a message on disk
*
* @param string $folderid id of the folder
* @param string $id id of the message
* @param int $flags read flag of the message
*
* @access public
* @return boolean status of the operation
* @throws StatusException could throw specific SYNC_STATUS_* exceptions
*/
public function SetReadFlag($folderid, $id, $flags, $contentParameters) {
return false;
}
/**
* Called when the user has requested to delete (really delete) a message
*
* @param string $folderid id of the folder
* @param string $id id of the message
*
* @access public
* @return boolean status of the operation
* @throws StatusException could throw specific SYNC_STATUS_* exceptions
*/
public function DeleteMessage($folderid, $id, $contentParameters) {
//return unlink($this->getPath() . '/' . $id);
$query="UPDATE contacts SET del='1',changed=NOW() where contact_id='$id' and user_id='$this->db_user_id'";
mysqli_query($query,$this->contactsdb) or print (mysqli_error($this->contactsdb));
return false;
}
/**
* Called when the user moves an item on the PDA from one folder to another
* not implemented
*
* @param string $folderid id of the source folder
* @param string $id id of the message
* @param string $newfolderid id of the destination folder
*
* @access public
* @return boolean status of the operation
* @throws StatusException could throw specific SYNC_MOVEITEMSSTATUS_* exceptions
*/
public function MoveMessage($folderid, $id, $newfolderid, $contentParameters) {
return false;
}
/**----------------------------------------------------------------------------------------------------------
* private vcard-specific internals
*/
/**
* The path we're working on
*
* @access private
* @return string
*/
private function getPath() {
ZLog::Write(LOGLEVEL_DEBUG, sprintf("getPath(): '%s'",$this->logged_in_user));
return str_replace('%u', $this->logged_in_user, VCARDDIR_DIR);
}
private function getEncryptedPassword($username) {
ZLog::Write(LOGLEVEL_DEBUG, sprintf("getEncryptedPassword(): '%s'", $username));
$password="not found";
$clean_username=mysqli_real_escape_string($this->contactsdb, $username);
$query=str_replace('%u', $clean_username, ROUNDCUBE_PASSWORD_SQL);
$result=mysqli_query($query,$this->authdb) or print (mysqli_error($this->authdb));
while($result_rows = mysqli_fetch_array($result)){
// Remove any {SPEC} password hasing spec that Dovecot might need (PHP does not need it)
// See http://wiki.dovecot.org/Authentication/PasswordSchemes
$password=preg_replace('/^{.*}/','',$result_rows[0]);
}
return $password;
}
/**
* Escapes a string
*
* @param string $data string to be escaped
*
* @access private
* @return string
*/
function escape($data){
if (is_array($data)) {
foreach ($data as $key => $val) {
$data[$key] = $this->escape($val);
}
return $data;
}
$data = str_replace("\r\n", "\n", $data);
$data = str_replace("\r", "\n", $data);
$data = str_replace(array('\\', ';', ',', "\n"), array('\\\\', '\\;', '\\,', '\\n'), $data);
return u2wi($data);
}
/**
* Un-escapes a string
*
* @param string $data string to be un-escaped
*
* @access private
* @return string
*/
function unescape($data){
$data = str_replace(array('\\\\', '\\;', '\\,', '\\n','\\N'),array('\\', ';', ',', "\n", "\n"),$data);
return $data;
}
public function GetSupportedASVersion() {
return ZPush::ASV_14;
}
};