forked from jens-maus/carddav2fb
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcarddav2fb.php
More file actions
432 lines (361 loc) · 12.4 KB
/
carddav2fb.php
File metadata and controls
432 lines (361 loc) · 12.4 KB
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
<?php
/**
* CardDAV to FritzBox! XML (automatic upload)
* inspired by http://www.wehavemorefun.de/fritzbox/Hochladen_eines_MySQL-Telefonbuchs
*
* Requirements:
* php5, php-curl (Debian/Ubuntu install shortcut: sudo apt-get install php5-cli php5-curl)
*
* used libraries:
* * vCard-parser <https://github.com/nuovo/vCard-parser> (LICNECE: unknown)
* * CardDAV-PHP <https://github.com/graviox/CardDAV-PHP>(LICENCE: AGPLv3)
* * fritzbox_api_php <https://github.com/carlos22/fritzbox_api_php> (LICENCE: CC-by-SA 3.0)
*
* LICENCE (of this file): MIT
*
* Autors: Karl Glatz (original author)
* Martin Rost
* Jens Maus <mail@jens-maus.de>
*
* version 1.5 2014-08-25
*
*/
error_reporting(E_ALL);
setlocale(LC_ALL, 'de_DE.UTF8');
require_once('lib/CardDAV-PHP/carddav.php');
require_once('lib/vCard-parser/vCard.php');
require_once('lib/fritzbox_api_php/fritzbox_api.class.php');
if ($argc == 2) {
$config_file_name = $argv[1];
} else {
$config_file_name = 'config.php';
}
if(is_file($config_file_name)) {
require($config_file_name);
} else {
print 'ERROR: No '.$config_file_name.' found, please take a look at config.example.php and create a '.$config_file_name.' file!'.PHP_EOL;
exit(1);
}
// ---------------------------------------------
// MAIN
$client = new CardDAV2FB($config);
// read vcards from webdav
print 'Get all entries from CardDAV server(s)... ';
$client->get_carddav_entries();
print 'Done.'.PHP_EOL;
flush(); // in case this script runs by php-cgi
// transform them to a fritzbox compatible xml file
print 'Transform to FritzBox XML File... ';
$client->build_fb_xml();
print 'Done.'.PHP_EOL;
flush(); // in case this script runs by php-cgi
// upload the XML-file to the FRITZ!Box (CAUTION: this will overwrite all current entries in the phone book!!)
print 'Upload to FRITZ!Box at '.$config['fritzbox_ip'].'...';
$ul_msg = $client->upload_to_fb();
print 'Done.'.PHP_EOL;
print 'FritzBox: '.$ul_msg.PHP_EOL;
flush(); // in case this script runs by php-cgi
class CardDAV2FB {
protected $entries = array();
protected $fbxml = "";
protected $config = null;
public function __construct($config) {
$this->config = $config;
}
public function base64_to_jpeg( $inputfile, $outputfile ) {
/* read data (binary) */
$ifp = fopen( $inputfile, "rb" );
$imageData = fread( $ifp, filesize( $inputfile ) );
fclose( $ifp );
/* encode & write data (binary) */
$ifp = fopen( $outputfile, "wb" );
fwrite( $ifp, base64_decode( $imageData ) );
fclose( $ifp );
/* return output filename */
return( $outputfile );
}
public function get_carddav_entries() {
$entries = array();
// format output of messages (info, debug, error)
$message_info = "[\033[32m INFO \033[0m] ";
$message_successful = "[\033[32m OK \033[0m] ";
$message_debug = "[\033[36m DEBUG \033[0m] ";
$message_error = "[\033[31m ERROR \033[0m] ";
// perform an ftps-connection to copy over the photos to a specified directory
$ftp_server = $this->config['fritzbox_ip_ftp'];
$conn_id = ftp_ssl_connect($ftp_server);
$login_result = ftp_login($conn_id, $this->config['fritzbox_user'], $this->config['fritzbox_pw']);
ftp_pasv($conn_id, true);
foreach($this->config['carddav'] as $conf) {
$carddav = new carddav_backend($conf['url']);
$carddav->set_auth($conf['user'], $conf['pw']);
$xmldata = $carddav->get();
// convert everything to utf-8 (for OpenXchange/Appsuite)
//$xmldata = utf8_encode($xmldata);
// DEBUG: writes an XML-file of the addressbook to the server from where the script is executed
/*
$filename = $conf['user']."_".basename($conf['url']) . ".xml";
print PHP_EOL."Save whole addressbook as xml file: ".$filename;
file_put_contents($filename, $xmldata);
*/
// read raw_vcard data from xml response
$raw_vcards = array();
$xmlvcard = new SimpleXMLElement($xmldata);
foreach($xmlvcard->element as $vcard_element)
{
$id = $vcard_element->id->__toString();
$value = (string)$vcard_element->vcard->__toString();
$raw_vcards[$id] = $value;
}
// parse raw_vcards
$result = array();
foreach($raw_vcards as $v) {
$vcard_obj = new vCard(false, $v);
// name
$name_arr = $vcard_obj->n[0];
$name = $this->_concat($this->_concat($name_arr['LastName'],$name_arr['FirstName']),$name_arr['AdditionalNames']);
// if name is empty we take organization instead
if(empty($name)) {
$name_arr = $vcard_obj->org[0];
$name = $name_arr['Name'];
}
// format filename of contact photo; remove special letters
if ($vcard_obj->photo) {
$photo = str_replace(array(',','&',' ','ä','ö','ü','Ä','Ö','Ü','ß','á','à','ó','ò','ú','ù','í'),
array('','_','_','ae','oe','ue','Ae','Oe','Ue','ss','a','a','o','o','u','u','i'),$name);
} else {
$photo = '';
}
// phone
$phone_no = array();
if ($vcard_obj->categories) {
$categories = $vcard_obj->categories[0];
} else {
$categories = array('');
}
// e-mail addresses
$email_add = array();
// retrieve photos, save them as jpg and put them via ftp to the FRITZ!Box
if ($vcard_obj->photo) {
// get photos, rename and save as xml
$photo_jpg = $vcard_obj->photo;
$tempfile = basename($photo).".xml";
echo PHP_EOL.$message_info."Saving image as XML: ".$tempfile;
file_put_contents($tempfile, $photo_jpg[0]['Value']);
// convert base64 representation to jpg and delete tempfile afterwards
$this->base64_to_jpeg($tempfile, $photo.".jpg");
unlink($tempfile);
// copy photos via ftp to the FRITZ!Box
$file = $photo.".jpg";
$remote_path = $this->config['usb_disk']."/FRITZ/fonpix";
$remote_file = $photo.".jpg";
// upload photo file. If successful delete afterwards
if (ftp_put($conn_id, $remote_path."/".$file, $remote_file, FTP_BINARY)) {
echo PHP_EOL.$message_successful."Successful upload of photo: ".$file;
unlink($file);
} else {
// retry when a fault occurs.
echo PHP_EOL.$message_error."While uploading file ".$file." an error occurred. - retrying".PHP_EOL;
$conn_id = ftp_ssl_connect($ftp_server);
$login_result = ftp_login($conn_id, $this->config['fritzbox_user'], $this->config['fritzbox_pw']);
ftp_pasv($conn_id, true);
if (ftp_put($conn_id, $remote_path."/".$file, $remote_file, FTP_BINARY)) {
echo PHP_EOL.$message_successful."Successful upload of photo: ".$file;
unlink($file);
} else {
echo PHP_EOL.$message_error."While uploading file ".$file." an error occurred. - giving up".PHP_EOL;
}
}
}
if (in_array($this->config['group_vip'],$categories)) {
$vip = 1;
} else {
$vip = 0;
}
if (array_key_exists('group_filter',$this->config)) {
$add_entry = 0;
foreach($this->config['group_filter'] as $group_filter) {
if (in_array($group_filter,$categories)) {
$add_entry = 1;
break;
}
}
} else {
$add_entry = 1;
}
if ($add_entry == 1) {
foreach($vcard_obj->tel as $t) {
$prio = 0;
if (!is_array($t) || empty($t['Type'])) {
$type = "mobile";
$phone_number = $t;
} else {
$phone_number = $t['Value'];
$typearr_lower = unserialize(strtolower(serialize($t['Type'])));
// find out priority
if (in_array("pref", $typearr_lower)) {
$prio = 1;
}
// set the proper type
if (in_array("work", $typearr_lower)) {
$type = "work";
}
elseif (in_array("cell", $typearr_lower)) {
$type = "mobile";
}
elseif (in_array("home", $typearr_lower)) {
$type = "home";
}
elseif (in_array("other", $typearr_lower)) {
$type = "other";
}
elseif (in_array("dom", $typearr_lower)) {
$type = "other";
}
else {
continue;
}
}
$phone_no[] = array("type"=>$type, "prio"=>$prio, "value" => $this->_clear_phone_number($phone_number));
}
// request email address and type
if ($vcard_obj->email){
foreach($vcard_obj->email as $e) {
if (empty($e['Type'])) {
$type_email = "work";
$email = $e;
} else {
$email = $e['Value'];
$typearr_lower = unserialize(strtolower(serialize($e['Type'])));
if (in_array("work", $typearr_lower)) {
$type_email = "work";
}
elseif (in_array("home", $typearr_lower)) {
$type_email = "home";
}
elseif (in_array("other", $typearr_lower)) {
$type_email = "other";
}
else {
continue;
}
}
// DEBUG: print out the email address on the console
//print $type_email.": ".$email."\n";
$email_add[] = array("type"=>$type_email, "value" => $email);
}
}
$entries[] = array("realName" => $name, "telephony" => $phone_no, "email" => $email_add, "vip" => $vip, "photo" => $photo);
}
}
}
// close ftp connection
ftp_close($conn_id);
$this->entries = $entries;
}
private function _clear_phone_number($number) {
return preg_replace("/[^0-9+]/", "", $number);
// return $number;
}
public function build_fb_xml() {
if(empty($this->entries)) {
throw new Exception('No entries available! Call get_carddav_entries or set $this->entries manually!');
}
// create FB XML in utf-8 format
$root = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><phonebooks><phonebook></phonebook></phonebooks>');
$pb = $root->phonebook;
$pb->addAttribute("name",$this->config['phonebook_name']);
foreach($this->entries as $entry) {
$contact = $pb->addChild("contact");
$contact->addChild("category", $entry['vip']);
$person = $contact->addChild("person");
$person->addChild("realName", $this->_convert_text($entry['realName']));
// contact photo: set path to contact photo on fritzbox
if (($entry['photo']) and (array_key_exists('usb_disk',$this->config))) {
$person->addChild("imageURL","file:///var/media/ftp/".$this->config['usb_disk']."/FRITZ/fonpix/".$entry['photo'].".jpg");
}
// telephone: put the phonenumbers into the fritzbox xml file
$telephony = $contact->addChild("telephony");
$id = 0;
foreach($entry['telephony'] as $tel) {
$num = $telephony->addChild("number", $tel['value']);
$num->addAttribute("type", $tel['type']);
$num->addAttribute("vanity","");
$num->addAttribute("prio", $tel['prio']);
$num->addAttribute("id", $id);
$id++;
}
// email: put the email addresses into the fritzbox xml file
$email = $contact->addChild("services");
$id = 0;
foreach($entry['email'] as $mail) {
$mail_adr = $email->addChild("email", $mail['value']);
$mail_adr->addAttribute("classifier", $mail['type']);
$mail_adr->addAttribute("id", $id);
$id++;
}
$contact->addChild("services");
$contact->addChild("setup");
$contact->addChild("mod_time", (string)time());
}
$this->fbxml = $root->asXML();
}
public function _convert_text($text) {
$text = htmlspecialchars($text);
//$text = iconv("UTF-8", "ISO-8859-1//IGNORE", $text);
return $text;
}
public function _concat ($text1,$text2) {
if ($text1 == '') {
return $text2;
}
elseif ($text2 == '') {
return $text1;
}
else
{
return $text1.", ".$text2;
}
}
public function _parse_fb_result($text) {
preg_match("/\<h2\>([^\<]+)\<\/h2\>/", $text, $matches);
if($matches)
return $matches[1];
else
return "Error while uploading xml to fritzbox";
}
public function upload_to_fb() {
if (array_key_exists('output_file',$this->config)) {
$output = fopen($this->config['output_file'], 'w');
if ($output) {
fwrite($output, $this->fbxml);
fclose($output);
}
return 0;
};
$msg = "";
try
{
$fritz = new fritzbox_api($this->config['fritzbox_pw'],$this->config['fritzbox_user'],$this->config['fritzbox_ip']);
$formfields = array(
'PhonebookId' => $this->config['phonebook_number']
);
$filefileds = array('PhonebookImportFile' => array(
'type' => 'text/xml',
'filename' => 'updatepb.xml',
'content' => $this->fbxml,
)
);
$raw_result = $fritz->doPostFile($formfields, $filefileds); // send the command
$msg = $this->_parse_fb_result($raw_result);
$fritz = null; // destroy the object to log out
}
catch (Exception $e)
{
print $e->getMessage(); // show the error message in anything failed
print PHP_EOL;
}
return $msg;
}
}
?>