├── .gitignore
├── LICENSE
├── README.md
├── carddav2fb.php
├── config.example.php
└── lib
├── CardDAV-PHP
├── CHANGELOG
├── LICENSE
├── README.md
└── carddav.php
├── fritzbox_api_php
├── CHANGELOG.txt
├── README.md
├── README.txt
├── fritzbox_api.class.php
├── fritzbox_delete_foncallslist.php
├── fritzbox_diversity0on.php
├── fritzbox_get_foncallslist.php
├── fritzbox_get_foncallslist_xml.php
├── fritzbox_guestlan_on_off.php
├── fritzbox_guestwlan_on_off.php
├── fritzbox_ring_phone.php
├── fritzbox_tam_on_off.php
├── fritzbox_tam_swap.php
└── fritzbox_user.conf.php
└── vCard-parser
├── .gitignore
├── Example.vcf
├── Example2.1.vcf
├── Example3.0.vcf
├── LICENSE
├── README.md
├── test.php
├── vCard.php
└── write-test.php
/.gitignore:
--------------------------------------------------------------------------------
1 | /config.php
2 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | This is free and unencumbered software released into the public domain.
2 |
3 | Anyone is free to copy, modify, publish, use, compile, sell, or
4 | distribute this software, either in source code form or as a compiled
5 | binary, for any purpose, commercial or non-commercial, and by any
6 | means.
7 |
8 | In jurisdictions that recognize copyright laws, the author or authors
9 | of this software dedicate any and all copyright interest in the
10 | software to the public domain. We make this dedication for the benefit
11 | of the public at large and to the detriment of our heirs and
12 | successors. We intend this dedication to be an overt act of
13 | relinquishment in perpetuity of all present and future rights to this
14 | software under copyright law.
15 |
16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19 | IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20 | OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22 | OTHER DEALINGS IN THE SOFTWARE.
23 |
24 | For more information, please refer to
25 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | The most active fork AFAIK is this one: https://github.com/andig/carddav2fb (with PHP8 support).
2 |
3 | # CardDAV contacts import for AVM FRITZ!Box
4 |
5 | [](https://scrutinizer-ci.com/g/jens-maus/carddav2fb/build-status/master) [](https://scrutinizer-ci.com/g/jens-maus/carddav2fb/?branch=master)
6 |
7 | Features:
8 |
9 | * Allows to import CardDAV-based VCard contacts (e.g. from 'owncloud') to a phonebook in a AVM FRITZ!Box
10 | * CardDAV import includes photo images specified in VCards
11 | * No modification of FRITZ!Box firmware (aka FRITZ!OS) required
12 | * Definition of multiple CardDAV accounts and "folders" possible
13 | * Format of full name in FRITZ!Box phonebook can be designed
14 |
15 | **CAUTION: This script will overwrite your current contacts in the FritzBox without any warning!**
16 |
17 | ## Requirements
18 |
19 | * PHP-version 5.3.6 or higher
20 | * PHP-curl module
21 | * PHP-ftp module
22 | * PHP-mbstring module
23 |
24 | ## Installation
25 |
26 | Checkout the carddav2fb sources including its related subprojects using the following command:
27 |
28 | ```
29 | git clone https://github.com/carlos22/carddav2fb.git
30 | ```
31 |
32 | Now you should have everything setup and checked out to a 'carddav2fb' directory.
33 |
34 | ### Configuration
35 | 1. Make sure you have `System -> FRITZ!Box-Users -> Login via Username+Password` in your FRITZ!Box activated.
36 | 2. Make sure you have a separate user created under `System -> FRITZ!Box-Users` for which the following access rights have been granted:
37 | * `FRITZ!Box settings` (required to upload telephone book data)
38 | * `Access to NAS content` (required to upload photos via ftp).
39 | 3. Make sure the telephone book you are going to update via carddav2fb exists on the FRITZ!Box, otherwise the upload will fail.
40 | 4. Copy `config.example.php` to `config.php` and adapt it to your needs including setting the FRITZ!Box user settings.
41 |
42 | ## Usage
43 |
44 | ### Ubuntu
45 |
46 | 1. Install PHP, PHP-curl, PHP-ftp, PHP-mbstring and php-xml module:
47 |
48 | sudo apt-get install php-cli php-curl php-ftp php-mbstring php-xml
49 |
50 | 2. Open a Terminal and execute:
51 |
52 | php carddav2fb.php
53 |
54 | ### Windows
55 |
56 | 1. Download PHP from [php.net](http://windows.php.net/download/). Extract it to `C:\PHP`.
57 | 2. Start -> cmd. Run `C:\PHP\php.exe C:\path\to\carddav2fb\carddav2fb.php`
58 |
59 | ## config.php Example (owncloud)
60 |
61 | ```php
62 | $config['fritzbox_ip'] = 'fritz.box';
63 | $config['fritzbox_user'] = '';
64 | $config['fritzbox_pw'] = '';
65 | $config['phonebook_number'] = '0';
66 | $config['phonebook_name'] = 'Telefonbuch';
67 | $config['fritzbox_path'] = 'file:///var/media/ftp/';
68 |
69 | // full name format options default 0
70 | // parts in '' will only added if existing and switched to true in config
71 | // 0 = 'Prefix' Lastname, Firstname, 'Additional Names', 'Suffix', 'orgname'
72 | // 1 = 'Prefix' Firstname Lastname 'AdditionalNames' 'Suffix' '(orgname)'
73 | // 2 = 'Prefix' Firstname 'AdditionalNames' Lastname 'Suffix' '(orgname)'
74 | $config['fullname_format'] = 0;
75 |
76 | // fullname parts
77 | $config['prefix'] = false; // include prefix in fullname if existing
78 | $config['suffix'] = false; // include suffix in fullname if existing
79 | $config['addnames'] = false; // include additionalnames in fullname if existing
80 | $config['orgname'] = false; // include organisation (company) in fullname if existing
81 |
82 | $config['quickdial_keyword'] = 'Quickdial:'; // once activated you may add 'Quickdial:+49030123456:**709' to the contact note field and the number will be set as quickdialnumber in your FRITZ!Box. It is possible to add more quickdials for one contact each in a new line
83 |
84 | // first
85 | $config['carddav'][0] = array(
86 | 'url' => 'https:///remote.php/carddav/addressbooks//contacts',
87 | 'user' => '',
88 | 'pw' => ''
89 | );
90 | ```
91 |
92 | ## Note
93 | This script is using third-party libraries for downloading VCards from CardDAV servers based on the following packages
94 | * CardDAV-PHP (https://github.com/jens-maus/CardDAV-PHP.git)
95 | * FRITZ!Box-API-PHP (https://github.com/jens-maus/fritzbox_api_php.git)
96 | * VCard-Parser (https://github.com/jens-maus/vCard-parser.git)
97 |
98 | ## License
99 | This script is released under Public Domain.
100 |
101 | ## Authors
102 | Copyright (c) 2012-2016 Karl Glatz, Martin Rost, Jens Maus, Johannes Freiburger
103 |
--------------------------------------------------------------------------------
/carddav2fb.php:
--------------------------------------------------------------------------------
1 | (LICNECE: unknown)
11 | * * CardDAV-PHP (LICENCE: AGPLv3)
12 | * * fritzbox_api_php (LICENCE: CC-by-SA 3.0)
13 | *
14 | * LICENCE (of this file): MIT
15 | *
16 | * Autors: Karl Glatz (original author)
17 | * Martin Rost
18 | * Jens Maus
19 | * Johannes Freiburger
20 | *
21 | */
22 | error_reporting(E_ALL);
23 | setlocale(LC_ALL, 'de_DE.UTF8');
24 |
25 | // Version identifier for CardDAV2FB
26 | $carddav2fb_version = '1.11 (2016-05-12)';
27 |
28 | // check for the minimum php version
29 | $php_min_version = '5.3.6';
30 | if(version_compare(PHP_VERSION, $php_min_version) < 0)
31 | {
32 | print 'ERROR: PHP version ' . $php_min_version . ' is required. Found version: ' . PHP_VERSION . PHP_EOL;
33 | exit(1);
34 | }
35 |
36 | require_once('lib/CardDAV-PHP/carddav.php');
37 | require_once('lib/vCard-parser/vCard.php');
38 | require_once('lib/fritzbox_api_php/fritzbox_api.class.php');
39 |
40 | if($argc == 2)
41 | $config_file_name = $argv[1];
42 | else
43 | $config_file_name = __DIR__ . '/config.php';
44 |
45 | // default/fallback config options
46 | $config['tmp_dir'] = sys_get_temp_dir();
47 | $config['fritzbox_ip'] = 'fritz.box';
48 | $config['fritzbox_ip_ftp'] = $config['fritzbox_ip'];
49 | $config['fritzbox_force_local_login'] = false;
50 | $config['phonebook_number'] = '0';
51 | $config['phonebook_name'] = 'Telefonbuch';
52 | $config['usb_disk'] = '';
53 | $config['fritzbox_path'] = 'file:///var/media/ftp/';
54 | $config['fullname_format'] = 0; // see config.example.php for options
55 | $config['prefix'] = false;
56 | $config['suffix'] = false;
57 | $config['addnames'] = false;
58 | $config['orgname'] = false;
59 | $config['build_photos'] = true;
60 | $config['quickdial_keyword'] = 'Quickdial:';
61 |
62 | if(is_file($config_file_name))
63 | require($config_file_name);
64 | else
65 | {
66 | print 'ERROR: No ' . $config_file_name . ' found, please take a look at config.example.php and create a ' . $config_file_name . ' file!' . PHP_EOL;
67 | exit(1);
68 | }
69 |
70 | // ---------------------------------------------
71 | // MAIN
72 | print "carddav2fb.php " . $carddav2fb_version . " - CardDAV to FRITZ!Box phonebook conversion tool" . PHP_EOL;
73 | print "Copyright (c) 2012-2016 Karl Glatz, Martin Rost, Jens Maus, Johannes Freiburger" . PHP_EOL . PHP_EOL;
74 |
75 | $client = new CardDAV2FB($config);
76 |
77 | // read vcards from webdav
78 | print 'Retrieving VCards from all CardDAV server(s):' . PHP_EOL;
79 | $client->get_carddav_entries();
80 | print 'Done.' . PHP_EOL;
81 |
82 | flush(); // in case this script runs by php-cgi
83 |
84 | // transform them to a fritzbox compatible xml file
85 | print 'Converting VCards to FritzBox XML format:' . PHP_EOL;
86 | $client->build_fb_xml();
87 | print 'Done.' . PHP_EOL;
88 |
89 | flush(); // in case this script runs by php-cgi
90 |
91 | // upload the XML-file to the FRITZ!Box (CAUTION: this will overwrite all current entries in the phone book!!)
92 | print 'Upload data to FRITZ!Box @ ' . $config['fritzbox_ip'] . PHP_EOL;
93 | if($client->upload_to_fb())
94 | print 'Done.' . PHP_EOL;
95 | else
96 | exit(1);
97 |
98 | flush(); // in case this script runs by php-cgi
99 |
100 | // ---------------------------------------------
101 | // Class definition
102 | class CardDAV2FB
103 | {
104 | protected $entries = array();
105 | protected $fbxml = "";
106 | protected $config = null;
107 | protected $tmpdir = null;
108 |
109 | public function __construct($config)
110 | {
111 | $this->config = $config;
112 |
113 | // create a temp directory where we store photos
114 | $this->tmpdir = $this->mktemp($this->config['tmp_dir']);
115 | }
116 |
117 | public function __destruct()
118 | {
119 | // remote temp directory
120 | $this->rmtemp($this->tmpdir);
121 | }
122 |
123 | // Source: https://php.net/manual/de/function.tempnam.php#61436
124 | public function mktemp($dir, $prefix = '', $mode = 0700)
125 | {
126 | if(substr($dir, -1) != '/')
127 | $dir .= '/';
128 |
129 | do
130 | {
131 | $path = $dir . $prefix . mt_rand(0, 9999999);
132 | }
133 | while(!mkdir($path, $mode));
134 |
135 | return $path;
136 | }
137 |
138 | public function rmtemp($dir)
139 | {
140 | if(is_dir($dir))
141 | {
142 | $objects = scandir($dir);
143 | foreach($objects as $object)
144 | {
145 | if($object != "." && $object != "..")
146 | {
147 | if(filetype($dir . "/" . $object) == "dir")
148 | rrmdir($dir . "/" . $object); else unlink($dir . "/" . $object);
149 | }
150 | }
151 | reset($objects);
152 | rmdir($dir);
153 | }
154 | }
155 |
156 | public function is_base64($str)
157 | {
158 | try
159 | {
160 | // Check if there are valid base64 characters
161 | if(!preg_match('/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $str))
162 | return false;
163 |
164 | // Decode the string in strict mode and check the results
165 | $decoded = base64_decode($str, true);
166 | if($decoded === false)
167 | return false;
168 |
169 | // Encode the string again
170 | if(base64_encode($decoded) === $str)
171 | return true;
172 | else
173 | return false;
174 | }
175 | catch(Exception $e)
176 | {
177 | // If exception is caught, then it is not a base64 encoded string
178 | return false;
179 | }
180 | }
181 |
182 | public function base64_to_jpeg($inputfile, $outputfile)
183 | {
184 | // read data (binary)
185 | $ifp = fopen($inputfile, "rb");
186 | $imageData = fread($ifp, filesize($inputfile));
187 | fclose($ifp);
188 |
189 | // encode & write data (binary)
190 | $ifp = fopen($outputfile, "wb");
191 | fwrite($ifp, base64_decode($imageData));
192 | fclose($ifp);
193 |
194 | // return output filename
195 | return($outputfile);
196 | }
197 |
198 | public function get_carddav_entries()
199 | {
200 | $entries = array();
201 | $snum = 0;
202 |
203 | if(is_array($this->config['carddav']))
204 | {
205 | foreach($this->config['carddav'] as $conf)
206 | {
207 | print " [" . $snum . "]: " . $conf['url'] . " ";
208 | $carddav = new CardDavPHP\CardDavBackend($conf['url']);
209 | $carddav->setAuth($conf['user'], $conf['pw']);
210 |
211 | // set the vcard extension in case the user
212 | // defined it in the config
213 | if(isset($conf['extension']))
214 | $carddav->setVcardExtension($conf['extension']);
215 |
216 | // retrieve data from the CardDAV server now
217 | $xmldata = $carddav->get();
218 |
219 | // identify if we received UTF-8 encoded data from the
220 | // CardDAV server and if not reencode it since the FRITZ!Box
221 | // requires UTF-8 encoded data
222 | if(iconv('utf-8', 'utf-8//IGNORE', $xmldata) != $xmldata)
223 | $xmldata = utf8_encode($xmldata);
224 |
225 | // read raw_vcard data from xml response
226 | $raw_vcards = array();
227 | $xmlvcard = new SimpleXMLElement($xmldata);
228 |
229 | foreach($xmlvcard->element as $vcard_element)
230 | {
231 | $id = $vcard_element->id->__toString();
232 | $value = (string)$vcard_element->vcard->__toString();
233 | $raw_vcards[$id] = $value;
234 | }
235 |
236 | print " " . count($raw_vcards) . " VCards retrieved." . PHP_EOL;
237 |
238 | // parse raw_vcards
239 | $quick_dial_arr = array();
240 | foreach($raw_vcards as $v)
241 | {
242 | $vcard_obj = new vCard(false, $v);
243 | $name_arr = null;
244 | if(isset($vcard_obj->n[0]))
245 | $name_arr = $vcard_obj->n[0];
246 | $org_arr = null;
247 | if(isset($vcard_obj->org[0]))
248 | $org_arr = $vcard_obj->org[0];
249 | $addnames = '';
250 | $prefix = '';
251 | $suffix = '';
252 | $orgname = '';
253 | $formattedname = '';
254 |
255 | // Build name Parts if existing ans switch to true in config
256 | if(isset($name_arr['prefixes']) and $this->config['prefix'])
257 | $prefix = trim($name_arr['prefixes']);
258 |
259 | if(isset($name_arr['suffixes']) and $this->config['suffix'])
260 | $suffix = trim($name_arr['suffixes']);
261 |
262 | if(isset($name_arr['additionalnames']) and $this->config['addnames'])
263 | $addnames = trim($name_arr['additionalnames']);
264 |
265 | if(isset($org_arr['name']) and $this->config['orgname'])
266 | $orgname = trim($org_arr['name']);
267 |
268 | if (isset($vcard_obj->fn[0]))
269 | $formattedname = $vcard_obj->fn[0];
270 |
271 | $firstname = trim($name_arr['firstname']);
272 | $lastname = trim($name_arr['lastname']);
273 |
274 | // the following section implemented different ways of constructing the
275 | // final phonebook name entry depending on user preferred settings
276 | // selectable in the config file. Possible options are:
277 | //
278 | // $this->config['fullname_format']:
279 | //
280 | // 0: "Prefix Lastname, Firstname AdditionalNames Suffix (orgname)"
281 | // 1: "Prefix Firstname Lastname AdditionalNames Suffix (orgname)"
282 | // 2: "Prefix Firstname AdditionalNames Lastname Suffix (orgname)"
283 | //
284 | $name = '';
285 | $format = $this->config['fullname_format'];
286 |
287 | // Prefix
288 | if(!empty($prefix))
289 | $name .= $prefix;
290 |
291 | if($format == 0)
292 | {
293 | // Lastname
294 | if(!empty($name) and !empty($lastname))
295 | $name .= ' ' . $lastname;
296 | else
297 | $name .= $lastname;
298 | }
299 | else
300 | {
301 | // Firstname
302 | if(!empty($name) and !empty($firstname))
303 | $name .= ' ' . $firstname;
304 | else
305 | $name .= $firstname;
306 | }
307 |
308 | if($format == 2)
309 | {
310 | // AdditionalNames
311 | if(!empty($name) and !empty($addnames))
312 | $name .= ' ' . $addnames;
313 | else
314 | $name .= $addnames;
315 | }
316 |
317 | if($format == 0)
318 | {
319 | // Firstname
320 | if(!empty($name) and !empty($firstname))
321 | $name .= ', ' . $firstname;
322 | else
323 | $name .= $firstname;
324 | }
325 | else
326 | {
327 | // Lastname
328 | if(!empty($name) and !empty($lastname))
329 | $name .= ' ' . $lastname;
330 | else
331 | $name .= $lastname;
332 | }
333 |
334 | if($format != 2)
335 | {
336 | // AdditionalNames
337 | if(!empty($name) and !empty($addnames))
338 | $name .= ' ' . $addnames;
339 | else
340 | $name .= $addnames;
341 | }
342 |
343 | // Suffix
344 | if(!empty($name) and !empty($suffix))
345 | $name .= ' ' . $suffix;
346 | else
347 | $name .= $suffix;
348 |
349 | // OrgName
350 | if(!empty($name) and !empty($orgname))
351 | $name .= ' (' . $orgname . ')';
352 | else
353 | $name .= $orgname;
354 |
355 | // make sure to trim whitespaces and double spaces
356 | $name = trim(str_replace(' ', ' ', $name));
357 |
358 | // perform a fallback to formatted name, if we don't have any name and formatted name is available
359 | if(empty($name) and !empty($formattedname))
360 | $name = $formattedname;
361 |
362 | if(empty($name))
363 | {
364 | print ' WARNING: No fullname, lastname, orgname or formatted name found!' . PHP_EOL;
365 | $name = 'UNKNOWN';
366 | }
367 |
368 | // format filename of contact photo; remove special letters
369 | if($vcard_obj->photo)
370 | {
371 | $photo = str_replace(array(',', '&', ' ', '/', 'ä', 'ö', 'ü', 'Ä', 'Ö', 'Ü', 'ß', 'á', 'à', 'ó', 'ò', 'ú', 'ù', 'í', 'ø'),
372 | array('', '_', '_', '_', 'ae', 'oe', 'ue', 'Ae', 'Oe', 'Ue', 'ss', 'a', 'a', 'o', 'o', 'u', 'u', 'i', 'oe'), $name);
373 | }
374 | else
375 | $photo = '';
376 |
377 | // phone
378 | $phone_no = array();
379 | if($vcard_obj->categories)
380 | $categories = $vcard_obj->categories[0];
381 | else
382 | $categories = array();
383 |
384 | // check for quickdial entry
385 | if(isset($vcard_obj->note[0]))
386 | {
387 | $note = $vcard_obj->note[0];
388 | $notes = explode($this->config['quickdial_keyword'], $note);
389 | foreach($notes as $linenr => $linecontent)
390 | {
391 | $found = strrpos($linecontent, ":**7");
392 | if($found > 0)
393 | {
394 | $pos_qd_start = strrpos($linecontent, ":**7");
395 | $quick_dial_for_nr = preg_replace("/[^0-9+]/", "", substr($linecontent, 0, $pos_qd_start));
396 | $quick_dial_nr = intval(substr($linecontent, $pos_qd_start + 4, 3));
397 | $quick_dial_arr[$quick_dial_for_nr] = $quick_dial_nr;
398 | }
399 | }
400 | }
401 |
402 | // e-mail addresses
403 | $email_add = array();
404 | $vip = isset($this->config['group_vip']) && in_array((string)$this->config['group_vip'], $categories);
405 |
406 | if(array_key_exists('group_filter', $this->config) && is_array($this->config['group_filter']))
407 | {
408 | $add_entry = 0;
409 | foreach($this->config['group_filter'] as $group_filter)
410 | {
411 | if(in_array($group_filter, $categories))
412 | {
413 | $add_entry = 1;
414 | break;
415 | }
416 | }
417 | }
418 | else
419 | $add_entry = 1;
420 |
421 | if($add_entry == 1)
422 | {
423 | foreach($vcard_obj->tel as $t)
424 | {
425 | $prio = 0;
426 | $quickdial = null;
427 |
428 | if(!is_array($t) || empty($t['type']))
429 | {
430 | $type = "mobile";
431 | $phone_number = $t;
432 | }
433 | else
434 | {
435 | $phone_number = $t['value'];
436 |
437 | $phone_number_clean = preg_replace("/[^0-9+]/", "", $phone_number);
438 | foreach($quick_dial_arr as $qd_phone_nr => $value)
439 | {
440 | if($qd_phone_nr == $phone_number_clean)
441 | {
442 | //Set quickdial
443 | if($value == 1)
444 | print "\nWARNING: Quickdial value 1 (**701) is not possible but used! \n";
445 | elseif($value >= 100)
446 | print "\nWARNING: Quickdial value bigger than 99 (**799) is not possible but used! \n";
447 |
448 | $quickdial = $value;
449 | }
450 | }
451 |
452 | foreach($t['type'] as $k=>$v) {
453 | $t['type'][$k] = str_replace('"','',$v);
454 | }
455 |
456 | $typearr_lower = unserialize(strtolower(serialize($t['type'])));
457 |
458 | // find out priority
459 | if(in_array("pref", $typearr_lower))
460 | $prio = 1;
461 |
462 | // set the proper type
463 | if(in_array("cell", $typearr_lower))
464 | $type = "mobile";
465 | elseif(in_array("home", $typearr_lower))
466 | $type = "home";
467 | elseif(in_array("fax", $typearr_lower))
468 | $type = "fax_work";
469 | elseif(in_array("work", $typearr_lower))
470 | $type = "work";
471 | elseif(in_array("other", $typearr_lower))
472 | $type = "other";
473 | elseif(in_array("dom", $typearr_lower))
474 | $type = "other";
475 | elseif(in_array("voice", $typearr_lower))
476 | $type = "other";
477 | else
478 | continue;
479 | }
480 | $phone_no[] = array("type"=>$type, "prio"=>$prio, "quickdial"=>$quickdial, "value" => $this->_clear_phone_number($phone_number));
481 | }
482 |
483 | // request email address and type
484 | if($vcard_obj->email)
485 | {
486 | foreach($vcard_obj->email as $e)
487 | {
488 | if(empty($e['type']))
489 | {
490 | $type_email = "work";
491 | $email = $e;
492 | }
493 | else
494 | {
495 | $email = $e['value'];
496 | $typearr_lower = unserialize(strtolower(serialize($e['type'])));
497 | if(in_array("work", $typearr_lower))
498 | $type_email = "work";
499 | elseif(in_array("home", $typearr_lower))
500 | $type_email = "home";
501 | elseif(in_array("other", $typearr_lower))
502 | $type_email = "other";
503 | else
504 | continue;
505 | }
506 |
507 | // DEBUG: print out the email address on the console
508 | //print $type_email.": ".$email."\n";
509 |
510 | $email_add[] = array("type"=>$type_email, "value" => $email);
511 | }
512 | }
513 | $entries[] = array("realName" => $name, "telephony" => $phone_no, "email" => $email_add, "vip" => $vip, "photo" => $photo, "photo_data" => $vcard_obj->photo);
514 | }
515 | }
516 |
517 | $snum++;
518 | }
519 | }
520 |
521 | $this->entries = $entries;
522 | }
523 |
524 | private function _clear_phone_number($number)
525 | {
526 | return preg_replace("/[^0-9+]/", "", $number);
527 | }
528 |
529 | public function build_fb_xml()
530 | {
531 | if(empty($this->entries))
532 | throw new Exception('No entries available! Call get_carddav_entries or set $this->entries manually!');
533 |
534 | // create FB XML in utf-8 format
535 | $root = new SimpleXMLElement('');
536 | $pb = $root->phonebook;
537 | $pb->addAttribute("name", $this->config['phonebook_name']);
538 |
539 | foreach($this->entries as $entry)
540 | {
541 | $contact = $pb->addChild("contact");
542 | $contact->addChild("category", $entry['vip']);
543 | $person = $contact->addChild("person");
544 | $person->addChild("realName", $this->_convert_text($entry['realName']));
545 |
546 | echo " VCard: '" . utf8_decode($entry['realName']) . "'" . PHP_EOL;
547 |
548 | // telephone: put the phonenumbers into the fritzbox xml file
549 | $telephony = $contact->addChild("telephony");
550 | $id = 0;
551 | foreach($entry['telephony'] as $tel)
552 | {
553 | $num = $telephony->addChild("number", $tel['value']);
554 | $num->addAttribute("type", $tel['type']);
555 | $num->addAttribute("vanity", "");
556 | $num->addAttribute("prio", $tel['prio']);
557 | $num->addAttribute("id", $id);
558 |
559 | if(isset($tel['quickdial']))
560 | {
561 | $num->addAttribute("quickdial", $tel['quickdial']);
562 | print " Added quickdial: " . $tel['quickdial'] . " for: " . $tel['value'] . " (" . $tel['type'] . ")" . PHP_EOL;
563 | }
564 |
565 | $id++;
566 | print " Added phone: " . $tel['value'] . " (" . $tel['type'] . ")" . PHP_EOL;
567 | }
568 |
569 | // output a warning if no telephone number was found
570 | if($id == 0)
571 | print " WARNING: no phone entry found. VCard will be ignored." . PHP_EOL;
572 |
573 | // email: put the email addresses into the fritzbox xml file
574 | $email = $contact->addChild("services");
575 | $id = 0;
576 | foreach($entry['email'] as $mail)
577 | {
578 | $mail_adr = $email->addChild("email", $mail['value']);
579 | $mail_adr->addAttribute("classifier", $mail['type']);
580 | $mail_adr->addAttribute("id", $id);
581 | $id++;
582 |
583 | print " Added email: " . $mail['value'] . " (" . $mail['type'] . ")" . PHP_EOL;
584 | }
585 |
586 | // check for a photo being part of the VCard
587 | if(($entry['photo']) and ($entry['photo_data']) and (is_array($entry['photo_data'])) and ($entry['photo_data'][0]))
588 | {
589 | // check if 'photo_data'[0] is an array as well because then
590 | // we have to extract ['value'] and friends.
591 | if(is_array($entry['photo_data'][0]) and (array_key_exists('value', $entry['photo_data'][0])))
592 | {
593 | // check if photo_data really contains JPEG data
594 | if((array_key_exists('type', $entry['photo_data'][0])) and (is_array($entry['photo_data'][0]['type'])) and
595 | ($entry['photo_data'][0]['type'][0] == 'jpeg' or $entry['photo_data'][0]['type'][0] == 'jpg' or $entry['photo_data'][0]['type'][0] == 'image/jpeg'))
596 | {
597 | // get photo, rename, base64 convert and save as jpg
598 | $photo_data = $entry['photo_data'][0]['value'];
599 | $photo_version = substr(sha1($photo_data), 0, 5);
600 | $photo_file = $this->tmpdir . '/' . "{$entry['photo']}_{$photo_version}.jpg";
601 |
602 | // check for base64 encoding of the photo data and convert it
603 | // accordingly.
604 | if(((array_key_exists('encoding', $entry['photo_data'][0])) and ($entry['photo_data'][0]['encoding'] == 'b')) or $this->is_base64($photo_data))
605 | {
606 | file_put_contents($photo_file . ".b64", $photo_data);
607 | $this->base64_to_jpeg($photo_file . ".b64", $photo_file);
608 | unlink($photo_file . ".b64");
609 | }
610 | else
611 | {
612 | print " WARNING: non-base64 encoded photo data found and used." . PHP_EOL;
613 | file_put_contents($photo_file, $photo_data);
614 | }
615 |
616 | // add contact photo to xml
617 | $person->addChild("imageURL", $this->config['fritzbox_path'] . $this->config['usb_disk'] . "FRITZ/fonpix/" . basename($photo_file));
618 |
619 | print " Added photo: " . basename($photo_file) . PHP_EOL;
620 | }
621 | else
622 | print " WARNING: Only jpg contact photos are currently supported." . PHP_EOL;
623 | }
624 | elseif(substr($entry['photo_data'][0], 0, 4) == 'http')
625 | {
626 | // add contact photo to xml
627 | $person->addChild("imageURL", $entry['photo_data'][0]);
628 |
629 | print " Added photo: " . $entry['photo_data'][0] . PHP_EOL;
630 | }
631 | else
632 | print " WARNING: Only VCard embedded photo data or a reference URL is currently supported." . PHP_EOL;
633 | }
634 |
635 | $contact->addChild("services");
636 | $contact->addChild("setup");
637 | $contact->addChild("mod_time", (string)time());
638 | }
639 |
640 | if($root->asXML() !== false)
641 | $this->fbxml = $root->asXML();
642 | else
643 | {
644 | print " ERROR: created XML data isn't well-formed." . PHP_EOL;
645 | exit(1);
646 | }
647 | }
648 |
649 | public function _convert_text($text)
650 | {
651 | $text = htmlspecialchars($text);
652 | return $text;
653 | }
654 |
655 | public function _concat($text1, $text2)
656 | {
657 | if($text1 == '')
658 | return $text2;
659 | elseif($text2 == '')
660 | return $text1;
661 | else
662 | return $text1 . ", " . $text2;
663 | }
664 |
665 | public function _parse_fb_result($text)
666 | {
667 | if(preg_match("/\
([^\<]+)\<\/h2\>/", $text, $matches) == 1 && !empty($matches))
668 | return $matches[1];
669 | else
670 | return "Error while uploading xml to fritzbox";
671 | }
672 |
673 | public function upload_to_fb()
674 | {
675 | // if the user wants to save the xml to a separate file, we do so now
676 | if(array_key_exists('output_file', $this->config))
677 | {
678 | // build md5 hash of previous stored xml without Elements
679 | $oldphonebhash = md5(preg_replace("/(\\d{10})/","",file_get_contents($this->config['output_file'],'r'),-1,$debugoldtsreplace));
680 | $output = fopen($this->config['output_file'], 'w');
681 | if($output)
682 | {
683 | fwrite($output, $this->fbxml);
684 | fclose($output);
685 | print " Saved to file " . $this->config['output_file'] . PHP_EOL;
686 | }
687 | if (array_key_exists('output_and_upload', $this->config) and $this->config['output_and_upload'])
688 | {
689 | $newphonebhash = md5(preg_replace("/(\\d{10})/","",file_get_contents($this->config['output_file'],'r'),-1,$debugnewtsreplace));
690 | print " INFO: Compare old and new phonebook file versions." . PHP_EOL . " INFO: old version: " . $oldphonebhash . PHP_EOL . " INFO: new version: " . $newphonebhash . PHP_EOL;
691 | if($oldphonebhash === $newphonebhash)
692 | {
693 | print " INFO: Same versions ==> No changes in phonebook or images" . PHP_EOL . " EXIT: No need to upload phonebook to the FRITZ!Box.". PHP_EOL;
694 | return 0;
695 | }
696 | else
697 | print " INFO: Different versions ==> Changes in phonebook." . PHP_EOL . " INFO: Changes dedected! Continue with upload." . PHP_EOL;
698 | }
699 | else
700 | return 0;
701 | }
702 | // now we upload the photo jpgs first being stored in the
703 | // temp directory.
704 |
705 | // perform an ftps-connection to copy over the photos to a specified directory
706 | $ftp_server = $this->config['fritzbox_ip_ftp'];
707 | $conn_id = ftp_ssl_connect($ftp_server);
708 | if($conn_id == false)
709 | {
710 | print " WARNING: Secure connection to FTP-server '" . $ftp_server . "' failed, retrying without SSL." . PHP_EOL;
711 | $conn_id = ftp_connect($ftp_server);
712 | }
713 |
714 | if($conn_id != false)
715 | {
716 | ftp_set_option($conn_id, FTP_TIMEOUT_SEC, 60);
717 | $login_result = ftp_login($conn_id, $this->config['fritzbox_user'], $this->config['fritzbox_pw']);
718 | if($login_result === true)
719 | {
720 | ftp_pasv($conn_id, true);
721 |
722 | // create remote photo path on FRITZ!Box if it doesn't exist
723 | $remote_path = $this->config['usb_disk'] . "/FRITZ/fonpix";
724 | $all_existing_files = ftp_nlist($conn_id, $remote_path);
725 | if($all_existing_files == false)
726 | {
727 | ftp_mkdir($conn_id, $remote_path);
728 | $all_existing_files = array();
729 | }
730 |
731 | // now iterate through all jpg files in tempdir and upload them if necessary
732 | $dir = new DirectoryIterator($this->tmpdir);
733 | foreach($dir as $fileinfo)
734 | {
735 | if(!$fileinfo->isDot())
736 | {
737 | if($fileinfo->getExtension() == "jpg")
738 | {
739 | $file = $fileinfo->getFilename();
740 |
741 | print " FTP-Upload '" . $file . "'...";
742 | if(!in_array($remote_path . "/" . $file, $all_existing_files))
743 | {
744 | if(!ftp_put($conn_id, $remote_path . "/" . $file, $fileinfo->getPathname(), FTP_BINARY))
745 | {
746 | // retry when a fault occurs.
747 | print " retrying... ";
748 | $conn_id = ftp_ssl_connect($ftp_server);
749 | if($conn_id == false)
750 | {
751 | print " WARNING: Secure re-connection to FTP-server '" . $ftp_server . "' failed, retrying without SSL." . PHP_EOL;
752 | $conn_id = ftp_connect($ftp_server);
753 | }
754 |
755 | if($conn_id == false)
756 | {
757 | print " ERROR: couldn't re-connect to FTP server '" . $ftp_server . "', abortіng." . PHP_EOL;
758 | break;
759 | }
760 |
761 | $login_result = ftp_login($conn_id, $this->config['fritzbox_user'], $this->config['fritzbox_pw']);
762 | if($login_result === false)
763 | {
764 | print " ERROR: couldn't re-login to FTP-server '" . $ftp_server . "' with provided username/password settings." . PHP_EOL;
765 | break;
766 | }
767 |
768 | ftp_pasv($conn_id, true);
769 | if(!ftp_put($conn_id, $remote_path . "/" . $file, $fileinfo->getPathname(), FTP_BINARY))
770 | print " ERROR: while uploading file " . $fileinfo->getFilename() . PHP_EOL;
771 | else
772 | print " ok." . PHP_EOL;
773 | }
774 | else
775 | print " ok." . PHP_EOL;
776 |
777 | // cleanup old files
778 | foreach($all_existing_files as $existing_file)
779 | {
780 | if(strpos($existing_file, $remote_path . "/" . substr($file, 0, -10)) !== false)
781 | {
782 | print " FTP-Delete: " . $existing_file . PHP_EOL;
783 | ftp_delete($conn_id, $remote_path . "/" . basename($existing_file));
784 | }
785 | }
786 | }
787 | else
788 | print " already exists." . PHP_EOL;
789 | }
790 | }
791 | }
792 | }
793 | else
794 | print " ERROR: couldn't login to FTP-server '" . $ftp_server . "' with provided username/password settings." . PHP_EOL;
795 |
796 | // close ftp connection
797 | ftp_close($conn_id);
798 | }
799 | else
800 | print " ERROR: couldn't connect to FTP server '" . $ftp_server . "'." . PHP_EOL;
801 |
802 | // lets post the phonebook xml to the FRITZ!Box
803 | print " Uploading Phonebook XML to " . $this->config['fritzbox_ip'] . PHP_EOL;
804 | try
805 | {
806 | $fritz = new fritzbox_api($this->config['fritzbox_pw'],
807 | $this->config['fritzbox_user'],
808 | $this->config['fritzbox_ip'],
809 | $this->config['fritzbox_force_local_login']);
810 |
811 | $formfields = array(
812 | 'PhonebookId' => $this->config['phonebook_number']
813 | );
814 |
815 | $filefileds = array('PhonebookImportFile' => array(
816 | 'type' => 'text/xml',
817 | 'filename' => 'updatepb.xml',
818 | 'content' => $this->fbxml,
819 | )
820 | );
821 |
822 | $raw_result = $fritz->doPostFile($formfields, $filefileds); // send the command
823 | $msg = $this->_parse_fb_result($raw_result);
824 | unset($fritz); // destroy the object to log out
825 |
826 | print " FRITZ!Box returned message: '" . $msg . "'" . PHP_EOL;
827 | }
828 | catch(Exception $e)
829 | {
830 | print " ERROR: " . $e->getMessage() . PHP_EOL; // show the error message in anything failed
831 | return false;
832 | }
833 | return true;
834 | }
835 | }
836 |
--------------------------------------------------------------------------------
/config.example.php:
--------------------------------------------------------------------------------
1 | use internal fritzbox storage
51 | //$config['usb_disk'] = 'Generic-FlashDisk-01';
52 |
53 | // many version Fritz!Box use 'file:///var/media/ftp/' others 'file:///var/InternerSpeicher/' to check just export an your current phonebook and have a look at any imageURL tag `file:///var/media/ftp/(HERE_config_from:usb_disk)/FRITZ/fonpix/9.jpg`.
54 | //$config['fritzbox_path'] = 'file:///var/media/ftp/';
55 |
56 | // multiple carddav adressbooks could be specified and will be merged together.
57 |
58 | // first
59 | $config['carddav'][0] = array(
60 | // URL of first CardDAV address book on cloud storage
61 | 'url' => 'https://raspserver/owncloud/remote.php/carddav/addressbooks/fritzbox/fb_contacts',
62 | // user name/password for CardDAV access
63 | 'user' => 'oc_username',
64 | 'pw' => 'oc_password',
65 | // vcf extension
66 | 'extension' => '.vcf'
67 | );
68 |
69 | // second
70 | //$config['carddav'][1] = array(
71 | // 'url' => 'https://raspserver/owncloud/remote.php/carddav/addressbooks/fritzbox/fb_contacts_second',
72 | // 'user' => 'oc_username',
73 | // 'pw' => 'oc_password',
74 | // 'extension' => '.vcf'
75 | //);
76 |
--------------------------------------------------------------------------------
/lib/CardDAV-PHP/CHANGELOG:
--------------------------------------------------------------------------------
1 | Changes from v0.5.2 to v0.6
2 | - Added Exception handling
3 | - Each method now analyzes the http status code on it's own
4 | - Minor comment, documentation and phpdoc changes
5 |
6 | Changes from v0.5.1 to v0.5.2
7 | - Added debug function
8 | - Some minor class structure changes
9 | - Some comment, documentation and phpdoc changes
10 |
11 | Changes from v0.5 to v0.5.1
12 | - Added SOGo to the CardDAV server list
13 | - Deleted the method get_last_vcard_id() -> the add method does now returns the vCard id
14 | - Added posibility to get a raw XML vCard response to the get_xml_vcard() method
15 | - Some comment, documentation and phpdoc changes
16 |
17 | Changes from v0.4.9 to v0.5
18 | - Added SOGo support
19 | - Special thanks to xbgmsharp for the great feedback!
20 | - Cache curl connection so that only one authentication process is needed
21 | - Added boolean return value for add-, edit- and delete-methods
22 | - Added addressbook handling
23 |
24 | Changes from v0.4.8 to v0.4.9
25 | - New method: clean_vcard
26 | - New method: get_last_vcard_id
27 |
28 | Changes from v0.4.7 to v0.4.8
29 | - Extended clean_response() method and added utf-encoding
30 |
31 | Changes from v0.4.6 to v0.4.7
32 | - Changed license from LGPLv2 to AGPLv3
33 | - Changed minor wordings in the changelog
34 |
35 | Changes from v0.4.5 to v0.4.6
36 | - Added "get XML vCard"-method to get a single vCard with more detailed information
37 |
38 | Changes from v0.4.4 to v0.4.5
39 | - Minor comment and class changes
40 |
41 | Changes from v0.4.3 to v0.4.4
42 | - Verified ownCloud support
43 | - Store username and password for class internal use
44 | - Cleaned the class
45 | - Automaticly adds a / at the end of an url if it's missing
46 | - Added a URL-Schema list
47 |
48 | Changes from v0.4.2 to v0.4.3
49 | - Added sabreDAV support
50 |
51 | Changes from v0.4.1 to v0.4.2
52 | - Standardized "get last modified" seems not to work with every server configuration -> no standardized date anymore!
53 |
54 | Changes from v0.4 to v0.4.1
55 | - Added memotoo support
56 | - Bugfix: mostly check_connection() returned "true" if the server connection failed
57 | - Removed unused code
58 | - Standardized "get last modified" to unix-timestamp
59 | - Changed version naming
60 |
61 | Changes from v0.3.3 to v0.4
62 | - Switched from "fopen" to curl for all server requests
63 | - get() uses now PROPFIND instead of REPORT
64 | - Simplified response additionally returns "get last modified"
65 | - Added Apple addressbook server support
66 |
67 | Changes from v0.3.3 to v0.3.4
68 | - vCard id returned by get() excludes now the file extension ".vcf"
69 |
70 | Changes from v0.3.2 to v0.3.3
71 | - Minor comment changes
72 |
73 | Changes from v0.3.1 to v0.3.2
74 | - Minor phpdoc changes / extensions
75 |
76 | Changes from v0.3 to v0.3.1
77 | - Get only entries if a vCard id exists
78 | - Get etag bugfix (PROFIND -> REPORT)
79 | - vCard id generator bugfix
80 | - Minor class-structure and comment changes
81 |
82 | Changes from v0.2.2 to v0.3
83 | - Deleted unused methods
84 | - Added server connection check
85 | - Added some more examples
86 | - get() can now return complete vCards
87 |
88 | Changes from v0.2.1 to v0.2.2
89 | - Added error handling
90 | - Added phpdoc support
91 | - Cleaned comments / variables
92 |
93 | Changes from v0.2 to v0.2.1
94 | - XML requests will be built by the XMLWriter
95 | - Added etag to simplified response
96 |
97 | Changes from v0.1.2 to v0.2
98 | - Added add functionality
99 | - Added update functionality
100 | - Added get vCard functionality
101 | - Added user-agent to http-requests
102 | - Added simplified response
103 | - Set vCard standard fields (Version, N, FN)
104 |
105 | Changes from v0.1.1 to v0.1.2
106 | - Added delete functionality
107 |
108 | Changes from v0.1 to v0.1.1
109 | - Added filter type (OR / AND)
110 |
111 | release v0.1
112 | - Query CardDAV server with XML response (only tested on davical)
113 | - Filter functionality for search implementations
114 | - Fieldsets for minimal vCards within the XML response
115 | - Authentification
116 |
--------------------------------------------------------------------------------
/lib/CardDAV-PHP/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published by
637 | the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
--------------------------------------------------------------------------------
/lib/CardDAV-PHP/README.md:
--------------------------------------------------------------------------------
1 | Description
2 | -----------
3 | This is a simple CardDAV client written in PHP called "CardDAV PHP".
4 |
5 |
6 | Features
7 | --------
8 | * Query your CardDAV server with XML response (simplified or raw)
9 | * Supports many authentication methods
10 | * You can add / update / delete vCards from your CardDAV server
11 | * Get single vCards (raw or extended XML) from your CardDAV server
12 | * Check CardDAV server connection
13 | * Tested CardDAV servers: DAViCal, Apple Addressbook Server, memotoo, SabreDAV, ownCloud, SOGo
14 |
15 |
16 | Installation
17 | ------------
18 | * Nothing to install - it's standalone
19 | * Requires PHP 5.3 and CURL
20 | * The documentation can be found in the class itself
21 |
22 |
23 | Special thanks
24 | --------------
25 | * xbgmsharp for the great feedback!
26 |
27 |
28 | Contact
29 | -------
30 | * Author: Christian Putzke
31 | * Report feature requests and bugs here: https://github.com/graviox/CardDAV-PHP/issues
32 | * Visit my website: http://www.graviox.de/
33 | * Follow me on Twitter: https://twitter.com/cputzke/
--------------------------------------------------------------------------------
/lib/CardDAV-PHP/carddav.php:
--------------------------------------------------------------------------------
1 | setAuth('username', 'password');
10 | * echo $carddav->get();
11 | *
12 | *
13 | * Simple vCard query
14 | * ------------------
15 | * $carddav = new CardDavBackend('https://davical.example.com/user/contacts/');
16 | * $carddav->setAuth('username', 'password');
17 | * echo $carddav->getVcard('0126FFB4-2EB74D0A-302EA17F');
18 | *
19 | *
20 | * XML vCard query
21 | * ------------------
22 | * $carddav = new CardDavBackend('https://davical.example.com/user/contacts/');
23 | * $carddav->setAuth('username', 'password');
24 | * echo $carddav->getXmlVcard('0126FFB4-2EB74D0A-302EA17F');
25 | *
26 | *
27 | * Check CardDAV server connection
28 | * -------------------------------
29 | * $carddav = new CardDavBackend('https://davical.example.com/user/contacts/');
30 | * $carddav->setAuth('username', 'password');
31 | * var_dump($carddav->checkConnection());
32 | *
33 | *
34 | * CardDAV delete query
35 | * --------------------
36 | * $carddav = new CardDavBackend('https://davical.example.com/user/contacts/');
37 | * $carddav->setAuth('username', 'password');
38 | * $carddav->delete('0126FFB4-2EB74D0A-302EA17F');
39 | *
40 | *
41 | * CardDAV add query
42 | * --------------------
43 | * $vcard = 'BEGIN:VCARD
44 | * VERSION:3.0
45 | * UID:1f5ea45f-b28a-4b96-25as-ed4f10edf57b
46 | * FN:Christian Putzke
47 | * N:Christian;Putzke;;;
48 | * EMAIL;TYPE=OTHER:christian.putzke@graviox.de
49 | * END:VCARD';
50 | *
51 | * $carddav = new CardDavBackend('https://davical.example.com/user/contacts/');
52 | * $carddav->setAuth('username', 'password');
53 | * $vcard_id = $carddav->add($vcard);
54 | *
55 | *
56 | * CardDAV update query
57 | * --------------------
58 | * $vcard = 'BEGIN:VCARD
59 | * VERSION:3.0
60 | * UID:1f5ea45f-b28a-4b96-25as-ed4f10edf57b
61 | * FN:Christian Putzke
62 | * N:Christian;Putzke;;;
63 | * EMAIL;TYPE=OTHER:christian.putzke@graviox.de
64 | * END:VCARD';
65 | *
66 | * $carddav = new CardDavBackend('https://davical.example.com/user/contacts/');
67 | * $carddav->setAuth('username', 'password');
68 | * $carddav->update($vcard, '0126FFB4-2EB74D0A-302EA17F');
69 | *
70 | *
71 | * CardDAV debug
72 | * -------------
73 | * $carddav = new CardDavBackend('https://davical.example.com/user/contacts/');
74 | * $carddav->enableDebug();
75 | * $carddav->setAuth('username', 'password');
76 | * $carddav->get();
77 | * var_dump($carddav->getDebug());
78 | *
79 | *
80 | * CardDAV server list
81 | * -------------------
82 | * DAViCal: https://example.com/{resource|principal|username}/{collection}/
83 | * Apple Addressbook Server: https://example.com/addressbooks/users/{resource|principal|username}/{collection}/
84 | * memotoo: https://sync.memotoo.com/cardDAV/
85 | * SabreDAV: https://example.com/addressbooks/{resource|principal|username}/{collection}/
86 | * ownCloud: https://example.com/apps/contacts/carddav.php/addressbooks/{resource|principal|username}/{collection}/
87 | * SOGo: https://example.com/SOGo/dav/{resource|principal|username}/Contacts/{collection}/
88 | * Google (direct): https://google.com/m8/carddav/principals/__uids__/{username}/lists/default/
89 | *
90 | *
91 | * @author Christian Putzke
92 | * @copyright Christian Putzke
93 | * @link http://www.graviox.de/
94 | * @link https://twitter.com/cputzke/
95 | * @since 24.05.2015
96 | * @version 0.7
97 | * @license http://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
98 | *
99 | */
100 |
101 | class CardDavBackend
102 | {
103 | /**
104 | * CardDAV PHP Version
105 | *
106 | * @constant string
107 | */
108 | const VERSION = '0.7';
109 |
110 | /**
111 | * User agent displayed in http requests
112 | *
113 | * @constant string
114 | */
115 | const USERAGENT = 'CardDAV PHP/';
116 |
117 | /**
118 | * CardDAV server url
119 | *
120 | * @var string
121 | */
122 | private $url = null;
123 |
124 | /**
125 | * CardDAV server url_parts
126 | *
127 | * @var array
128 | */
129 | private $url_parts = null;
130 |
131 | /**
132 | * VCard File URL Extension
133 | *
134 | * @var string
135 | */
136 | private $url_vcard_extension = '.vcf';
137 |
138 | /**
139 | * Authentication string
140 | *
141 | * @var string
142 | */
143 | private $auth = null;
144 |
145 | /**
146 | * Authentication: username
147 | *
148 | * @var string
149 | */
150 | private $username = null;
151 |
152 | /**
153 | * Authentication: password
154 | *
155 | * @var string
156 | */
157 | private $password = null;
158 |
159 | /**
160 | * Characters used for vCard id generation
161 | *
162 | * @var array
163 | */
164 | private $vcard_id_chars = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F');
165 |
166 | /**
167 | * CardDAV server connection (curl handle)
168 | *
169 | * @var resource
170 | */
171 | private $curl;
172 |
173 | /**
174 | * Follow redirects (Location Header)
175 | *
176 | * @var boolean
177 | */
178 | private $follow_redirects = true;
179 |
180 | /**
181 | * Maximum redirects to follow
182 | *
183 | * @var integer
184 | */
185 | private $follow_redirects_count = 3;
186 |
187 | /**
188 | * Debug on or off
189 | *
190 | * @var boolean
191 | */
192 | private $debug = false;
193 |
194 | /**
195 | * All available debug information
196 | *
197 | * @var array
198 | */
199 | private $debug_information = array();
200 |
201 | /**
202 | * Exception codes
203 | */
204 | const EXCEPTION_WRONG_HTTP_STATUS_CODE_GET = 1000;
205 | const EXCEPTION_WRONG_HTTP_STATUS_CODE_GET_VCARD = 1001;
206 | const EXCEPTION_WRONG_HTTP_STATUS_CODE_GET_XML_VCARD = 1002;
207 | const EXCEPTION_WRONG_HTTP_STATUS_CODE_DELETE = 1003;
208 | const EXCEPTION_WRONG_HTTP_STATUS_CODE_ADD = 1004;
209 | const EXCEPTION_WRONG_HTTP_STATUS_CODE_UPDATE = 1005;
210 | const EXCEPTION_MALFORMED_XML_RESPONSE = 1006;
211 | const EXCEPTION_COULD_NOT_GENERATE_NEW_VCARD_ID = 1007;
212 |
213 |
214 | /**
215 | * Constructor
216 | * Sets the CardDAV server url
217 | *
218 | * @param string $url CardDAV server url
219 | */
220 | public function __construct($url = null)
221 | {
222 | if ($url !== null) {
223 | $this->setUrl($url);
224 | }
225 | }
226 |
227 | /**
228 | * Sets debug information
229 | *
230 | * @param array $debug_information Debug information
231 | * @return void
232 | */
233 | public function setDebug(array $debug_information)
234 | {
235 | $this->debug_information[] = $debug_information;
236 | }
237 |
238 | /**
239 | * Sets the CardDAV server url
240 | *
241 | * @param string $url CardDAV server url
242 | * @return void
243 | */
244 | public function setUrl($url)
245 | {
246 | $this->url = $url;
247 |
248 | if (substr($this->url, -1, 1) !== '/') {
249 | $this->url = $this->url . '/';
250 | }
251 |
252 | $this->url_parts = parse_url($this->url);
253 |
254 | // workaround for providers that don't use the default .vcf extension
255 | if (strpos($this->url, "google.com"))
256 | {
257 | $this->setVcardExtension("");
258 | }
259 | }
260 |
261 | /**
262 | * Sets the CardDAV vcard url extension
263 | *
264 | * Most providers do requests handling Vcards with .vcf, however
265 | * this isn't always the case and some providers (such as Google)
266 | * returned a 404 if the .vcf extension is used - or the other
267 | * way around, returning 404 unless .vcf is used.
268 | *
269 | * Both approaches are technically correct, see rfc635
270 | * http://tools.ietf.org/html/rfc6352
271 | *
272 | *
273 | * @param string $extension File extension
274 | * @return void
275 | */
276 | public function setVcardExtension($extension)
277 | {
278 | $this->url_vcard_extension = $extension;
279 | }
280 |
281 | /**
282 | * Sets authentication information
283 | *
284 | * @param string $username CardDAV server username
285 | * @param string $password CardDAV server password
286 | * @return void
287 | */
288 | public function setAuth($username, $password)
289 | {
290 | $this->username = $username;
291 | $this->password = $password;
292 | $this->auth = $username . ':' . $password;
293 | }
294 |
295 | /**
296 | * Sets wether to follow redirects and if yes how often
297 | *
298 | * @param boolean $follow_redirects
299 | * @param integer $follow_redirects_count
300 | * @return void
301 | */
302 | public function setFollowRedirects($follow_redirects, $follow_redirects_count = 3)
303 | {
304 | $this->follow_redirects = $follow_redirects && $follow_redirects_count > 0;
305 | $this->follow_redirects_count = $follow_redirects_count > 0 ? $follow_redirects_count : 0;
306 | }
307 |
308 | /**
309 | * Gets all available debug information
310 | *
311 | * @return array $this->debug_information All available debug information
312 | */
313 | public function getDebug()
314 | {
315 | return $this->debug_information;
316 | }
317 |
318 | /**
319 | * Gets all vCards including additional information from the CardDAV server
320 | *
321 | * @param boolean $include_vcards Include vCards within the response (simplified only)
322 | * @param boolean $raw Get response raw or simplified
323 | * @return string Raw or simplified XML response
324 | */
325 | public function get($include_vcards = true, $raw = false)
326 | {
327 | // for owncloud&co. Doesn't work with OpenXchange/Appsuite
328 | $result = $this->query($this->url, 'PROPFIND');
329 |
330 | // for OpenXchange/Appsuite
331 | $content = '';
332 | $content_type = 'application/xml';
333 | //$result = $this->query($this->url, 'REPORT', $content, $content_type);
334 |
335 | // DEBUG: print the response of the carddav-server
336 | //print_r($result);
337 |
338 | switch ($result['http_code'])
339 | {
340 | case 200:
341 | case 207:
342 | if ($raw === true) {
343 | return $result['response'];
344 | } else {
345 | return $this->simplify($result['response'], $include_vcards);
346 | }
347 | }
348 |
349 | throw new \Exception(
350 | "Woops, something's gone wrong! The CardDAV server returned the http status code {$result['http_code']}.",
351 | self::EXCEPTION_WRONG_HTTP_STATUS_CODE_GET
352 | );
353 |
354 | }
355 |
356 | /**
357 | * Gets a clean vCard from the CardDAV server
358 | *
359 | * @param string $vcard_id vCard id on the CardDAV server
360 | * @return string vCard (text/vcard)
361 | */
362 | public function getVcard($vcard_id)
363 | {
364 | $vcard_id = str_replace($this->url_vcard_extension, null, $vcard_id);
365 | $result = $this->query($this->url . $vcard_id . $this->url_vcard_extension, 'GET');
366 |
367 | // DEBUG: print the response of the carddav-server
368 | // print_r($result);
369 |
370 | switch ($result['http_code'])
371 | {
372 | case 404:
373 | $altResult = $this->query($this->url . $vcard_id , 'GET');
374 | // DEBUG: print the response of the carddav-server
375 | // print_r($altResult);
376 | switch ($altResult['http_code'])
377 | {
378 | case 200:
379 | case 207:
380 | print "Ignoring given Vcard Extension (".$this->url_vcard_extension.")" . PHP_EOL. ".";
381 | $this->setVcardExtension("");
382 | return $altResult['response'];
383 | }
384 | throw new \Exception(
385 | "Woops, something's gone wrong! The CardDAV server returned the http status code {$result['http_code']}:{$result['response']}:{$vcard_id}.",
386 | self::EXCEPTION_WRONG_HTTP_STATUS_CODE_GET_VCARD
387 | );
388 |
389 | case 200:
390 | case 207:
391 | print ".";
392 | return $result['response'];
393 | }
394 |
395 | throw new \Exception(
396 | "Woops, something's gone wrong! The CardDAV server returned the http status code {$result['http_code']}:{$result['response']}:{$vcard_id}.",
397 | self::EXCEPTION_WRONG_HTTP_STATUS_CODE_GET_VCARD
398 | );
399 | }
400 |
401 | /**
402 | * Gets a vCard + XML from the CardDAV Server
403 | *
404 | * @param string $vcard_id vCard id on the CardDAV Server
405 | * @return string Raw or simplified vCard (text/xml)
406 | */
407 | public function getXmlVcard($vcard_id)
408 | {
409 | $vcard_id = str_replace($this->url_vcard_extension, null, $vcard_id);
410 |
411 | $xml = new XMLWriter();
412 | $xml->openMemory();
413 | $xml->setIndent(4);
414 | $xml->startDocument('1.0', 'utf-8');
415 | $xml->startElement('C:addressbook-multiget');
416 | $xml->writeAttribute('xmlns:D', 'DAV:');
417 | $xml->writeAttribute('xmlns:C', 'urn:ietf:params:xml:ns:carddav');
418 | $xml->startElement('D:prop');
419 | $xml->writeElement('D:getetag');
420 | $xml->writeElement('D:getlastmodified');
421 | $xml->endElement();
422 | $xml->writeElement('D:href', $this->url_parts['path'] . $vcard_id . $this->url_vcard_extension);
423 | $xml->endElement();
424 | $xml->endDocument();
425 |
426 | $result = $this->query($this->url, 'REPORT', $xml->outputMemory(), 'text/xml');
427 |
428 | switch ($result['http_code'])
429 | {
430 | case 200:
431 | case 207:
432 | return $this->simplify($result['response'], true);
433 |
434 | }
435 |
436 | throw new \Exception(
437 | "Woops, something's gone wrong! The CardDAV server returned the http status code {$result['http_code']}.",
438 | self::EXCEPTION_WRONG_HTTP_STATUS_CODE_GET_XML_VCARD
439 | );
440 | }
441 |
442 | /**
443 | * Enables the debug mode
444 | *
445 | * @return void
446 | */
447 | public function enableDebug()
448 | {
449 | $this->debug = true;
450 | }
451 |
452 | /**
453 | * Checks if the CardDAV server is reachable
454 | *
455 | * @return boolean
456 | */
457 | public function checkConnection()
458 | {
459 | $result = $this->query($this->url, 'OPTIONS');
460 |
461 | if ($result['http_code'] === 200) {
462 | return true;
463 | } else {
464 | return false;
465 | }
466 | }
467 |
468 | /**
469 | * Cleans the vCard
470 | *
471 | * @param string $vcard vCard
472 | * @return string $vcard vCard
473 | */
474 | private function cleanVcard($vcard)
475 | {
476 | $vcard = str_replace("\t", null, $vcard);
477 |
478 | return $vcard;
479 | }
480 |
481 | /**
482 | * Deletes an entry from the CardDAV server
483 | *
484 | * @param string $vcard_id vCard id on the CardDAV server
485 | * @return boolean
486 | */
487 | public function delete($vcard_id)
488 | {
489 | $result = $this->query($this->url . $vcard_id . $this->url_vcard_extension, 'DELETE');
490 |
491 | switch ($result['http_code'])
492 | {
493 | case 204:
494 | return true;
495 | }
496 |
497 | throw new \Exception(
498 | "Woops, something's gone wrong! The CardDAV server returned the http status code {$result['http_code']}.",
499 | self::EXCEPTION_WRONG_HTTP_STATUS_CODE_DELETE
500 | );
501 | }
502 |
503 | /**
504 | * Adds an entry to the CardDAV server
505 | *
506 | * @param string $vcard vCard
507 | * @param string $vcard_id vCard id on the CardDAV server
508 | * @return string The new vCard id
509 | */
510 | public function add($vcard, $vcard_id = null)
511 | {
512 | if ($vcard_id === null) {
513 | $vcard_id = $this->generateVcardId();
514 | }
515 | $vcard = $this->cleanVcard($vcard);
516 | $result = $this->query($this->url . $vcard_id . $this->url_vcard_extension, 'PUT', $vcard, 'text/vcard');
517 |
518 | switch($result['http_code'])
519 | {
520 | case 201:
521 | return $vcard_id;
522 | }
523 |
524 | throw new \Exception(
525 | "Woops, something's gone wrong! The CardDAV server returned the http status code {$result['http_code']}.",
526 | self::EXCEPTION_WRONG_HTTP_STATUS_CODE_ADD
527 | );
528 | }
529 |
530 | /**
531 | * Updates an entry to the CardDAV server
532 | *
533 | * @param string $vcard vCard
534 | * @param string $vcard_id vCard id on the CardDAV server
535 | * @return boolean
536 | */
537 | public function update($vcard, $vcard_id)
538 | {
539 | try {
540 | return $this->add($vcard, $vcard_id);
541 | } catch (Exception $e) {
542 | throw new \Exception($e->getMessage(), self::EXCEPTION_WRONG_HTTP_STATUS_CODE_UPDATE);
543 | }
544 | }
545 |
546 | /**
547 | * Simplify CardDAV XML response
548 | *
549 | * @param string $response CardDAV XML response
550 | * @param boolean $include_vcards Include vCards or not
551 | * @return string Simplified CardDAV XML response
552 | */
553 | private function simplify($response, $include_vcards = true)
554 | {
555 | $response = $this->cleanResponse($response);
556 |
557 | try {
558 | $xml = new \SimpleXMLElement($response);
559 | } catch (Exception $e) {
560 | throw new \Exception(
561 | "The XML response seems to be malformed and can't be simplified!",
562 | self::EXCEPTION_MALFORMED_XML_RESPONSE,
563 | $e
564 | );
565 | }
566 |
567 | $simplified_xml = new \XMLWriter();
568 | $simplified_xml->openMemory();
569 | $simplified_xml->setIndent(4);
570 |
571 | $simplified_xml->startDocument('1.0', 'utf-8');
572 | $simplified_xml->startElement('response');
573 |
574 | if (!empty($xml->response)) {
575 | foreach ($xml->response as $response) {
576 | if ((preg_match('/vcard/', $response->propstat->prop->getcontenttype) || preg_match('/vcf/', $response->href)) &&
577 | !$response->propstat->prop->resourcetype->collection) {
578 | $id = basename($response->href);
579 | $id = str_replace($this->url_vcard_extension, null, $id);
580 |
581 | try {
582 | $vcardData = $this->getVcard($id);
583 | if (!empty($id)) {
584 | $simplified_xml->startElement('element');
585 | $simplified_xml->writeElement('id', $id);
586 | $simplified_xml->writeElement('etag', str_replace('"', null, $response->propstat->prop->getetag));
587 | $simplified_xml->writeElement('last_modified', $response->propstat->prop->getlastmodified);
588 |
589 | if ($include_vcards === true) {
590 | $simplified_xml->writeElement('vcard', $vcardData);
591 | }
592 | $simplified_xml->endElement();
593 | }
594 | } catch (\Exception $e) {
595 | print("Error fetching vCard: {$id}: {$e->getMessage()}\n");
596 | }
597 | } elseif (preg_match('/unix-directory/', $response->propstat->prop->getcontenttype)) {
598 | if (isset($response->propstat->prop->href)) {
599 | $href = $response->propstat->prop->href;
600 | } elseif (isset($response->href)) {
601 | $href = $response->href;
602 | } else {
603 | $href = null;
604 | }
605 |
606 | $url = str_replace($this->url_parts['path'], null, $this->url) . $href;
607 | $simplified_xml->startElement('addressbook_element');
608 | $simplified_xml->writeElement('display_name', $response->propstat->prop->displayname);
609 | $simplified_xml->writeElement('url', $url);
610 | $simplified_xml->writeElement('last_modified', $response->propstat->prop->getlastmodified);
611 | $simplified_xml->endElement();
612 | }
613 | }
614 | }
615 |
616 | $simplified_xml->endElement();
617 | $simplified_xml->endDocument();
618 |
619 | return $simplified_xml->outputMemory();
620 | }
621 |
622 | /**
623 | * Cleans CardDAV XML response
624 | *
625 | * @param string $response CardDAV XML response
626 | * @return string $response Cleaned CardDAV XML response
627 | */
628 | private function cleanResponse($response)
629 | {
630 | $response = utf8_encode($response);
631 | $response = str_replace('D:', null, $response);
632 | $response = str_replace('d:', null, $response);
633 | $response = str_replace('C:', null, $response);
634 | $response = str_replace('c:', null, $response);
635 |
636 | return $response;
637 | }
638 |
639 | /**
640 | * Curl initialization
641 | *
642 | * @return void
643 | */
644 | public function curlInit()
645 | {
646 | if (empty($this->curl)) {
647 | $this->curl = curl_init();
648 | curl_setopt($this->curl, CURLOPT_HEADER, true);
649 | curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, false);
650 | curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, false);
651 | curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true);
652 | curl_setopt($this->curl, CURLOPT_USERAGENT, self::USERAGENT.self::VERSION);
653 |
654 | if ($this->auth !== null) {
655 | curl_setopt($this->curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
656 | curl_setopt($this->curl, CURLOPT_USERPWD, $this->auth);
657 | }
658 |
659 | /* allow to follow redirects if activated */
660 | curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, $this->follow_redirects);
661 | if ($this->follow_redirects)
662 | {
663 | curl_setopt($this->curl, CURLOPT_MAXREDIRS, $this->follow_redirects_count);
664 | }
665 | }
666 | }
667 |
668 | /**
669 | * Query the CardDAV server via curl and returns the response
670 | *
671 | * @param string $url CardDAV server URL
672 | * @param string $method HTTP method like (OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, COPY, MOVE)
673 | * @param string $content Content for CardDAV queries
674 | * @param string $content_type Set content type
675 | * @return array Raw CardDAV Response and http status code
676 | */
677 | private function query($url, $method, $content = null, $content_type = null)
678 | {
679 | $this->curlInit();
680 |
681 | curl_setopt($this->curl, CURLOPT_URL, $url);
682 | curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, $method);
683 |
684 | if ($content !== null) {
685 | curl_setopt($this->curl, CURLOPT_POST, true);
686 | curl_setopt($this->curl, CURLOPT_POSTFIELDS, $content);
687 | } else {
688 | curl_setopt($this->curl, CURLOPT_POST, false);
689 | curl_setopt($this->curl, CURLOPT_POSTFIELDS, null);
690 | }
691 |
692 | if ($content_type !== null) {
693 | curl_setopt($this->curl, CURLOPT_HTTPHEADER, array('Content-type: '.$content_type, 'Depth: 1'));
694 | } else {
695 | curl_setopt($this->curl, CURLOPT_HTTPHEADER, array('Depth: 1'));
696 | }
697 |
698 | $complete_response = curl_exec($this->curl);
699 | $header_size = curl_getinfo($this->curl, CURLINFO_HEADER_SIZE);
700 | $http_code = curl_getinfo($this->curl, CURLINFO_HTTP_CODE);
701 | $header = trim(substr($complete_response, 0, $header_size));
702 | $response = substr($complete_response, $header_size);
703 |
704 | $return = array(
705 | 'response' => $response,
706 | 'http_code' => $http_code
707 | );
708 |
709 | if ($this->debug === true) {
710 | $debug = $return;
711 | $debug['url'] = $url;
712 | $debug['method'] = $method;
713 | $debug['content'] = $content;
714 | $debug['content_type'] = $content_type;
715 | $debug['header'] = $header;
716 | $this->setDebug($debug);
717 | }
718 |
719 | return $return;
720 | }
721 |
722 | /**
723 | * Returns a valid and unused vCard id
724 | *
725 | * @return string $vcard_id Valid vCard id
726 | */
727 | private function generateVcardId()
728 | {
729 | $vcard_id = null;
730 |
731 | for ($number = 0; $number <= 25; $number ++) {
732 | if ($number == 8 || $number == 17) {
733 | $vcard_id .= '-';
734 | } else {
735 | $vcard_id .= $this->vcard_id_chars[mt_rand(0, (count($this->vcard_id_chars) - 1))];
736 | }
737 | }
738 |
739 | try {
740 | $carddav = new CardDavBackend($this->url);
741 | $carddav->setAuth($this->username, $this->password);
742 |
743 | $result = $carddav->query($this->url . $vcard_id . $this->url_vcard_extension, 'GET');
744 |
745 | if ($result['http_code'] !== 404) {
746 | $vcard_id = $this->generateVcardId();
747 | }
748 |
749 | return $vcard_id;
750 | } catch (Exception $e) {
751 | throw new \Exception($e->getMessage(), self::EXCEPTION_COULD_NOT_GENERATE_NEW_VCARD_ID);
752 | }
753 | }
754 |
755 | /**
756 | * Destructor
757 | * Close curl connection if it's open
758 | *
759 | * @return void
760 | */
761 | public function __destruct()
762 | {
763 | if (!empty($this->curl)) {
764 | curl_close($this->curl);
765 | }
766 | }
767 | }
768 |
769 | ?>
770 |
--------------------------------------------------------------------------------
/lib/fritzbox_api_php/CHANGELOG.txt:
--------------------------------------------------------------------------------
1 | 0.5.0b7 2013-01-02:
2 | ---
3 |
4 | * added a parameter to the constructor of the api to load a different config file (i.e. new frizbox_api('alt') loads fritzbox_user_alt.conf.php
5 | * fixed the logfile-logging in all bundled scripts
6 |
7 |
8 | 0.5.0b6 2012-12-23:
9 | ---
10 |
11 | * added a username config item to login with a local user, when user-based login is enabled in the box config
12 |
13 |
14 | 0.5.0b5 2012-12-18:
15 | ---
16 |
17 | * fixed the remoteconfig login code to work with new user system
18 | * fixed the logger calls to echo the message, when the logger is not initialized
19 |
20 |
21 | 0.5.0b4 2012-12-16:
22 | ---
23 |
24 | * fixed a typo in the remoteconfig login code
25 |
26 |
27 | 0.5.0b3 2012-12-09:
28 | ---
29 |
30 | * changed fritzbox_get_foncallslist.php to work with new firmwares, moved old method to fritzbox_get_foncallslist_xml.php
31 |
32 |
33 | 0.5.0b3 2012-12-07:
34 | ---
35 |
36 | * fixed internal SID login/logut-handling
37 |
38 |
39 | 0.5.0b1 2012-12-05:
40 | ---
41 |
42 | * added support for the new .lua-loginpage in newest Fritz Labor firmwares
43 | * refactored the whole codebase, introduced a new autoloaded config object, so check the new config file fritzbox_user.conf.php
44 |
45 |
46 | 0.4.1 2012-03-15:
47 | ---
48 |
49 | * added a new script fritzbox_guestlan_on_off.php to switch the new Guest-LAN on and off
50 | * tested all builtin scripts with new FRITZ!OS 05.20
51 |
52 |
53 | 0.4 2011-05-15:
54 | ---
55 |
56 | * added support for the new .lua forms like the WLAN guest access settings
57 |
58 |
59 | 0.3 2010-05-19:
60 | ---
61 |
62 | * added a doGetRequest method in the API
63 | * some minor changes
64 | * a new module for downloading the foncalls list
65 |
66 |
67 | 0.2 2010-04-07:
68 | ---
69 |
70 | * added a capability to use the Fritz!Box remote admin mode
71 | Important limitation: does not check the certificate, so the password is sent to any computer responding at the configured address.
72 | Feel free to hack the cURL calls to accept only a given certrificate
73 |
74 |
75 | 0.1:
76 | ---
77 |
78 | * First release
79 |
80 |
--------------------------------------------------------------------------------
/lib/fritzbox_api_php/README.md:
--------------------------------------------------------------------------------
1 | # FritzBox! PHP API
2 |
3 | Provides an interface to your FritzBox! using the webinterface. Thus, no modification the to firmware (aka FritzOS) is required!
4 |
5 | ### Requirements
6 | * PHP 5 (tested with 5.3)
7 | * PHP-curl
8 |
9 | Install on Debian/Ubuntu: sudo apt-get install php5-cli php5-curl
10 |
11 | ###Sample Scripts
12 |
13 | * Enable/Disable TAM
14 | * Download Phone call list
15 | * Enable/Disable Guest (W)LAN
16 | * Ring a Phone
17 | * Reboot
18 | * Export the Phonebook
19 | * **Import the Phonebook (only tested with FB 71xx) [not available in the original version]**
20 |
21 | **Newer Version available at**: [IPF discussion thread](http://www.ip-phone-forum.de/showthread.php?t=196309)
22 |
23 | AUTHORS: [Gregor Nathanael Meyer](http://spackmat.de/spackblog), Karl Glatz, (maybe others)
24 |
25 | ----------
26 |
27 | ### Important! ###
28 | Do not use Windows Notepad as it will break the files due to their UTF-8 coding and UNIX linebreaks. Download a serious editor like Notepad++ instead.
29 | Also do not use or modify this scripts, if you do not know, what you do. This script is itended for advanced users
30 |
31 |
32 |
33 | ### Basic usage advisory ####
34 |
35 | The scripts are well documented, please take a look to understand them.
36 | This is also the right moment to check the config file "fritzbox.conf.php"!
37 |
38 | All files must be in the same directory. If this condition is fulfilled, you don't need to pay any more attention to "fritzbox_api.class.php".
39 |
40 | To use "fritzbox_tam_on_off.php", you have to call it in a terminal, it will then explain its usage. This script is a reference implementation of the PHP Fritz!Box API, use it as a base for your own implementations
41 |
42 |
43 |
44 | ### Usage on a Windows system ###
45 |
46 | The script works fine on my Windows Vista machine and a simply extraced PHP 5.3.0 distribution (get it at http://windows.php.net/download/, PHP 5.4.0 works as well). The cURL extension and the mbstring extenstion must be enabled in the php.ini and the correct timezone must be set. To do this, copy the php.ini-production to php.ini and uncomment/change the following directives:
47 |
48 | extension_dir = "ext"
49 | extension=php_curl.dll
50 | extension=php_mbstring.dll
51 | date.timezone = Europe/Berlin
52 |
53 | After you have done that, you can call the script in a terminal:
54 |
55 | C:\>path\to\php.exe path\to\fritzbox_tam_on_off.php
56 |
57 | i.e. if you extracted PHP to c:\php and the Fritz!Box PHP API to a subfolder named fritz_api, you call it this way:
58 | C:\>cd php
59 | C:\php>php fritz_api\fritzbox_tam_on_off.php
60 |
61 | If you use the Windows taskplanner, configure the logger to a logfile or to silent mode and call via php-win.exe instead of php.exe. This will prevent the terminal from being opened.
62 |
63 |
64 |
65 | ### Usage on a UNIX system ###
66 |
67 | If you use UNIX, you should be familiar with calling a PHP script via the PHP-CLI. If you don't have the PHP-CLI installed, you can edit the $argv part in "fritz_tam_on_off.php" to work with PHP-CGI and $_GET or you hardcode the necessary arguments.
68 |
69 | Ensure that the cURL and the mbstring extensions are available and a valid timezone is set. The script was tested on a Ubuntu Server machine with PHP 5.2.
70 |
71 |
72 |
73 | ### Feedback, license, support ###
74 | You are welcome to send me feedback via email (Gregor [at] der-meyer.de) or visit my personal blog at http://spackmat.de/spackblog (in German)
75 |
76 | The whole work is licensed under a Creative Commons cc-by-sa license (http://creativecommons.org/licenses/by-sa/3.0/de/). You are free to use and modify it, even for commercial use. If you redistribute it, you have to ensure my name is kept in the code and you use the same conditions.
77 |
78 | Feel free to add (and contribute) other nice scripts. The API class should work with any config item, which is available in the Fritz!Box Web UI. Use Firebug or LiveHeaders to figure out the name of the proper POST-Field.
79 |
80 | I won't give any personal support for this script, unless you pay for it. :) I'm a freelance IT-consultant and webdeveloper, loocated in Düsseldorf, Germany.
81 |
--------------------------------------------------------------------------------
/lib/fritzbox_api_php/README.txt:
--------------------------------------------------------------------------------
1 | ### Important! ###
2 | Do not use Windows Notepad as it will break the files due to their UTF-8 coding and UNIX linebreaks. Download a serious editor like Notepad++ instead.
3 | Also do not use or modify this scripts, if you do not know, what you do. This script is itended for advanced users
4 |
5 |
6 | ### Upgrade advisory for version 0.5.0 and up ####
7 |
8 | Version 0.5.0 introduced a new config format with graceful default values, so check the new config file fritzbox_user.conf.php
9 |
10 |
11 | ### Basic usage advisory ####
12 |
13 | The scripts are well documented, please take a look to understand them.
14 | This is also the right moment to check the config file "fritzbox.conf.php"!
15 |
16 | All files must be in the same directory. If this condition is fulfilled, you don't need to pay any more attention to "fritzbox_api.class.php".
17 |
18 | To use "fritzbox_tam_on_off.php", you have to call it in a terminal, it will then explain its usage. This script is a reference implementation of the PHP Fritz!Box API, use it as a base for your own implementations
19 |
20 |
21 |
22 | ### Usage on a Windows system ###
23 |
24 | The script works fine on my Windows 7 machine and a simply extraced PHP 5.3 distribution (get it at http://windows.php.net/download/, PHP 5.4 works as well). The cURL extension and the mbstring extenstion must be enabled in the php.ini and the correct timezone must be set. To do this, copy the php.ini-production to php.ini and uncomment/change the following directives:
25 |
26 | extension_dir = "ext"
27 | extension=php_curl.dll
28 | extension=php_mbstring.dll
29 | date.timezone = Europe/Berlin
30 |
31 | After you have done that, you can call the script in a terminal:
32 |
33 | C:\>"path\to\php.exe" "path\to\fritzbox_tam_on_off.php"
34 |
35 | i.e. if you extracted PHP to c:\php and the Fritz!Box PHP API to a subfolder named fritz_api, you call it this way:
36 | C:\>cd php
37 | C:\php>"php.exe" "fritz_api\fritzbox_tam_on_off.php"
38 |
39 | If you use the Windows taskplanner, configure the logger to a logfile or to silent mode and call via php-win.exe instead of php.exe. This will prevent the terminal from being opened.
40 |
41 |
42 |
43 | ### Usage on a UNIX system ###
44 |
45 | If you use UNIX, you should be familiar with calling a PHP script via the PHP-CLI. If you don't have the PHP-CLI installed, you can edit the $argv part in "fritz_tam_on_off.php" to work with PHP-CGI and $_GET or you hardcode the necessary arguments.
46 |
47 | Ensure that the cURL and the mbstring extensions are available and a valid timezone is set. The script was tested on a Ubuntu Server machine with PHP 5.3.
48 |
49 |
50 |
51 | ### Feedback, license, support ###
52 | You are welcome to send me feedback via email (Gregor [at] der-meyer.de) or visit my personal blog at http://spackmat.de/spackblog (in German)
53 |
54 | The whole work is licensed under a Creative Commons cc-by-sa license (http://creativecommons.org/licenses/by-sa/3.0/de/). You are free to use and modify it, even for commercial use. If you redistribute it, you have to ensure my name is kept in the code and you use the same conditions.
55 |
56 | Feel free to add (and contribute) other nice scripts. The API class should work with any config item, which is available in the Fritz!Box Web UI. Use Firebug or LiveHeaders to figure out the name of the proper POST-Field.
57 |
58 | I won't give any personal support for this script, unless you pay for it. :) I'm a freelance IT-consultant and webdeveloper, loocated in Düsseldorf, Germany.
--------------------------------------------------------------------------------
/lib/fritzbox_api_php/fritzbox_api.class.php:
--------------------------------------------------------------------------------
1 |
12 | * @license http://creativecommons.org/licenses/by-sa/3.0/de/ Creative Commons cc-by-sa
13 | * @version 0.5.0b7 2013-01-02
14 | * @package Fritz!Box PHP tools
15 | */
16 |
17 | /* A simple usage example
18 | *
19 | * try
20 | * {
21 | * // load the fritzbox_api class
22 | * require_once('fritzbox_api.class.php');
23 | * $fritz = new fritzbox_api();
24 | *
25 | * // init the output message
26 | * $message = date('Y-m-d H:i') . ' ';
27 | *
28 | * // update the setting
29 | * $formfields = array(
30 | * 'telcfg:command/Dial' => '**610',
31 | * );
32 | * $fritz->doPostForm($formfields);
33 | * $message .= 'Phone ' . $dial . ' ringed.';
34 | * }
35 | * catch (Exception $e)
36 | * {
37 | * $message .= $e->getMessage();
38 | * }
39 | *
40 | * // log the result
41 | * $fritz->logMessage($message);
42 | * $fritz = null; // destroy the object to log out
43 | */
44 |
45 | /**
46 | * the main Fritz!Box API class
47 | *
48 | */
49 | class fritzbox_api {
50 | /**
51 | * @var object config object
52 | */
53 | public $config = array();
54 |
55 | /**
56 | * @var string the session ID, set by method initSID() after login
57 | */
58 | protected $sid = '0000000000000000';
59 |
60 |
61 | /**
62 | * the constructor, initializes the object and calls the login method
63 | *
64 | * @access public
65 | */
66 | public function __construct($password = false,$user_name = false,$fritzbox_ip = 'fritz.box',$force_local_login = false)
67 | {
68 | // init the config object
69 | $this->config = new fritzbox_api_config();
70 |
71 | // try autoloading the config
72 | if (file_exists(__DIR__ . '/fritzbox_user.conf.php') && is_readable(__DIR__ . '/fritzbox_user.conf.php') ) {
73 | require_once(__DIR__ . '/fritzbox_user.conf.php');
74 | }
75 |
76 | // set FRITZ!Box-IP and URL
77 | $this->config->setItem('fritzbox_ip',$fritzbox_ip);
78 |
79 | // check if login on local network (fritz.box) or via a dynamic DNS-host
80 | if ($fritzbox_ip != 'fritz.box' && !$force_local_login) {
81 | $this->config->setItem('enable_remote_config',true);
82 | $this->config->setItem('remote_config_user',$user_name);
83 | $this->config->setItem('remote_config_password',$password);
84 | $this->config->setItem('fritzbox_url', 'https://'.$this->config->getItem('fritzbox_ip'));
85 | } else {
86 | $this->config->setItem('enable_remote_config',false);
87 | if($user_name != false){
88 | $this->config->setItem('username',$user_name);
89 | }
90 | if($password != false){
91 | $this->config->setItem('password',$password);
92 | }
93 | $this->config->setItem('fritzbox_url', 'http://' . $this->config->getItem('fritzbox_ip'));
94 | }
95 |
96 | // make some config consistency checks
97 | if ( $this->config->getItem('enable_remote_config') === true ){
98 | if ( !$this->config->getItem('remote_config_user') || !$this->config->getItem('remote_config_password') ){
99 | $this->error('ERROR: Remote config mode enabled, but no username or no password provided');
100 | }
101 | }
102 | else {
103 | $this->config->setItem('old_remote_config_user', null);
104 | $this->config->setItem('old_remote_config_password', null);
105 | }
106 | $this->sid = $this->initSID();
107 | }
108 |
109 |
110 | /**
111 | * the destructor just calls the logout method
112 | *
113 | * @access public
114 | */
115 | public function __destruct()
116 | {
117 | $this->logout();
118 | }
119 |
120 |
121 | /**
122 | * do a POST request on the box
123 | * the main cURL wrapper handles the command
124 | *
125 | * @param array $formfields an associative array with the POST fields to pass
126 | * @return string the raw HTML code returned by the Fritz!Box
127 | */
128 | public function doPostForm($formfields = array())
129 | {
130 | $ch = curl_init();
131 |
132 | if ( isset($formfields['getpage']) && strpos($formfields['getpage'], '.lua') > 0 )
133 | {
134 | curl_setopt($ch, CURLOPT_URL, $this->config->getItem('fritzbox_url') . $formfields['getpage'] . '?sid=' . $this->sid);
135 | unset($formfields['getpage']);
136 | }
137 | else
138 | {
139 | // add the sid, if it is already set
140 | if ($this->sid != '0000000000000000')
141 | {
142 | $formfields['sid'] = $this->sid;
143 | }
144 | curl_setopt($ch, CURLOPT_URL, $this->config->getItem('fritzbox_url') . '/cgi-bin/webcm');
145 | }
146 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
147 | curl_setopt($ch, CURLOPT_POST, 1);
148 | if ( $this->config->getItem('enable_remote_config') == true )
149 | {
150 | // set name of SSL-certificate (must be same as remote-hostname (dynDNS) of FRITZ!Box) and remove port in address if alternate port is given
151 | if (strpos($this->config->getItem('fritzbox_ip'),":")){
152 | $ssl_cert_fritzbox = explode(":", $this->config->getItem('fritzbox_ip'));
153 | $ssl_cert_fritzbox = $ssl_cert_fritzbox[0];
154 | } else {
155 | $ssl_cert_fritzbox = $this->config->getItem('fritzbox_ip');
156 | }
157 |
158 | // set SSL-options and path to certificate
159 | curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 2);
160 | curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
161 | curl_setopt($ch, CURLOPT_CAPATH, '/etc/ssl/certs');
162 |
163 | // support for pre FRITZ!OS 5.50 remote config
164 | if (!$this->config->getItem('use_lua_login_method')){
165 | curl_setopt($ch, CURLOPT_USERPWD, $this->config->getItem('remote_config_user') . ':' . $this->config->getItem('remote_config_password'));
166 | }
167 | }
168 | curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($formfields));
169 | $output = curl_exec($ch);
170 | curl_close($ch);
171 | return $output;
172 | }
173 |
174 | public function doPostFile($formfields = array(), $filefileds = array())
175 | {
176 | $ch = curl_init();
177 |
178 | // add the sid, if it is already set
179 | if ($this->sid != '0000000000000000')
180 | {
181 | // 'sid' MUST be the first POST variable!!! (otherwise it will not work!!)
182 | // therfore we use array_merge to ensuere the foreach outputs 'sid' fist
183 | $formfields = array_merge(array('sid' => $this->sid), $formfields);
184 | //$formfields['sid'] = $this->sid;
185 | }
186 | curl_setopt($ch, CURLOPT_URL, $this->config->getItem('fritzbox_url') . '/cgi-bin/firmwarecfg');
187 | curl_setopt($ch, CURLOPT_POST, 1);
188 |
189 | // enable for debugging:
190 | //curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
191 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
192 |
193 | // if filefileds not specified ('@/path/to/file.xml;type=text/xml' works fine)
194 | if(empty( $filefileds )) {
195 | curl_setopt($ch, CURLOPT_POSTFIELDS, $formfields); // http_build_query
196 | }
197 | // post calculated raw data
198 | else {
199 | $header = $this->_create_custom_file_post_header($formfields, $filefileds);
200 | curl_setopt($ch, CURLOPT_HTTPHEADER , array(
201 | 'Content-Type: multipart/form-data; boundary=' . $header['delimiter'], 'Content-Length: ' . strlen($header['data']) )
202 | );
203 |
204 | curl_setopt($ch, CURLOPT_POSTFIELDS, $header['data']);
205 | }
206 |
207 | $output = curl_exec($ch);
208 |
209 | // curl error
210 | if(curl_errno($ch)) {
211 | $this->error(curl_error($ch)." (".curl_errno($ch).")");
212 | }
213 |
214 | // finger out an error message, if given
215 | preg_match('@
(.*?)
@is', $output, $matches);
216 | if (isset($matches[1]))
217 | {
218 | $this->error(str_replace(' ', ' ', $matches[1]));
219 | }
220 |
221 | curl_close($ch);
222 | return $output;
223 | }
224 |
225 | private function _create_custom_file_post_header($postFields, $fileFields) {
226 | // form field separator
227 | $delimiter = '-------------' . uniqid();
228 |
229 | /*
230 | // file upload fields: name => array(type=>'mime/type',content=>'raw data')
231 | $fileFields = array(
232 | 'file1' => array(
233 | 'type' => 'text/xml',
234 | 'content' => '...your raw file content goes here...',
235 | 'filename' = 'filename.xml'
236 | ),
237 | );
238 | // all other fields (not file upload): name => value
239 | $postFields = array(
240 | 'otherformfield' => 'content of otherformfield is this text',
241 | );
242 | */
243 |
244 | $data = '';
245 |
246 | // populate normal fields first (simpler)
247 | foreach ($postFields as $name => $content) {
248 | $data .= "--" . $delimiter . "\r\n";
249 | $data .= 'Content-Disposition: form-data; name="' . urlencode($name) . '"';
250 | $data .= "\r\n\r\n";
251 | $data .= $content;
252 | $data .= "\r\n";
253 | }
254 | // populate file fields
255 | foreach ($fileFields as $name => $file) {
256 | $data .= "--" . $delimiter . "\r\n";
257 | // "filename" attribute is not essential; server-side scripts may use it
258 | $data .= 'Content-Disposition: form-data; name="' . urlencode($name) . '";' .
259 | ' filename="' . $file['filename'] . '"' . "\r\n";
260 |
261 | //$data .= 'Content-Transfer-Encoding: binary'."\r\n";
262 | // this is, again, informative only; good practice to include though
263 | $data .= 'Content-Type: ' . $file['type'] . "\r\n";
264 | // this endline must be here to indicate end of headers
265 | $data .= "\r\n";
266 | // the file itself (note: there's no encoding of any kind)
267 | $data .= $file['content'] . "\r\n";
268 | }
269 | // last delimiter
270 | $data .= "--" . $delimiter . "--\r\n";
271 |
272 | return array('delimiter' => $delimiter, 'data' => $data);
273 | }
274 |
275 | /**
276 | * do a GET request on the box
277 | * the main cURL wrapper handles the command
278 | *
279 | * @param array $params an associative array with the GET params to pass
280 | * @return string the raw HTML code returned by the Fritz!Box
281 | */
282 | public function doGetRequest($params = array())
283 | {
284 | // add the sid, if it is already set
285 | if ($this->sid != '0000000000000000')
286 | {
287 | $params['sid'] = $this->sid;
288 | }
289 |
290 | $ch = curl_init();
291 | if ( strpos($params['getpage'], '.lua') > 0 )
292 | {
293 | $getpage = $params['getpage'] . '?';
294 | unset($params['getpage']);
295 | }
296 | else
297 | {
298 | $getpage = '/cgi-bin/webcm?';
299 | }
300 | curl_setopt($ch, CURLOPT_URL, $this->config->getItem('fritzbox_url') . $getpage . http_build_query($params));
301 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
302 | curl_setopt($ch, CURLOPT_HTTPGET, 1);
303 | if ( $this->config->getItem('enable_remote_config') )
304 | {
305 | curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
306 | curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
307 |
308 | // support for pre FRITZ!OS 5.50 remote config
309 | if ( !$this->config->getItem('use_lua_login_method') )
310 | {
311 | curl_setopt($ch, CURLOPT_USERPWD, $this->config->getItem('remote_config_user') . ':' . $this->config->getItem('remote_config_password'));
312 | }
313 | }
314 | $output = curl_exec($ch);
315 | curl_close($ch);
316 | return $output;
317 | }
318 |
319 |
320 | /**
321 | * the login method, handles the secured login-process
322 | * newer firmwares (xx.04.74 and newer) need a challenge-response mechanism to prevent Cross-Site Request Forgery attacks
323 | * see http://www.avm.de/de/Extern/Technical_Note_Session_ID.pdf for details
324 | *
325 | * @return string a valid SID, if the login was successful, otherwise throws an Exception with an error message
326 | */
327 | protected function initSID()
328 | {
329 | // determine, wich login type we have to use
330 | if ( $this->config->getItem('use_lua_login_method') == true )
331 | {
332 | $loginpage = '/login_sid.lua';
333 | }
334 | else
335 | {
336 | $loginpage = '../html/login_sid.xml';
337 | }
338 |
339 | // read the current status
340 | $session_status_simplexml = simplexml_load_string($this->doGetRequest(array('getpage' => $loginpage)));
341 |
342 | if ( !is_object($session_status_simplexml) || get_class($session_status_simplexml) != 'SimpleXMLElement' )
343 | {
344 | $this->error('Response of initialization call ' . $loginpage . ' in ' . __FUNCTION__ . ' was not xml-formatted.');
345 | }
346 |
347 | // perhaps we already have a SID (i.e. when no password is set)
348 | if ( $session_status_simplexml->SID != '0000000000000000' )
349 | {
350 | return $session_status_simplexml->SID;
351 | }
352 | // we have to login and get a new SID
353 | else
354 | {
355 | // the challenge-response magic, pay attention to the mb_convert_encoding()
356 | $challenge = $session_status_simplexml->Challenge;
357 |
358 | // do the login
359 | $formfields = array(
360 | 'getpage' => $loginpage,
361 | );
362 | if ( $this->config->getItem('use_lua_login_method') )
363 | {
364 | if ( $this->config->getItem('enable_remote_config') )
365 | {
366 | $formfields['username'] = $this->config->getItem('remote_config_user');
367 | $response = $challenge . '-' . md5(mb_convert_encoding($challenge . '-' . $this->config->getItem('remote_config_password'), "UCS-2LE", "UTF-8"));
368 | }
369 | else
370 | {
371 | if ( $this->config->getItem('username') )
372 | {
373 | $formfields['username'] = $this->config->getItem('username');
374 | }
375 | $response = $challenge . '-' . md5(mb_convert_encoding($challenge . '-' . $this->config->getItem('password'), "UCS-2LE", "UTF-8"));
376 | }
377 | $formfields['response'] = $response;
378 | }
379 | else
380 | {
381 | $response = $challenge . '-' . md5(mb_convert_encoding($challenge . '-' . $this->config->getItem('password'), "UCS-2LE", "UTF-8"));
382 | $formfields['login:command/response'] = $response;
383 | }
384 | $output = $this->doPostForm($formfields);
385 |
386 | // finger out the SID from the response
387 | $session_status_simplexml = simplexml_load_string($output);
388 | if ( !is_object($session_status_simplexml) || get_class($session_status_simplexml) != 'SimpleXMLElement' )
389 | {
390 | $this->error('Response of login call to ' . $loginpage . ' in ' . __FUNCTION__ . ' was not xml-formatted.');
391 | }
392 |
393 | if ( $session_status_simplexml->SID != '0000000000000000' )
394 | {
395 | return (string)$session_status_simplexml->SID;
396 | }
397 | else
398 | {
399 | $this->error('ERROR: Login failed with an unknown response.');
400 | }
401 | }
402 | }
403 |
404 |
405 | /**
406 | * the logout method just sends a logout command to the Fritz!Box
407 | *
408 | */
409 | protected function logout()
410 | {
411 | if ( $this->config->getItem('use_lua_login_method') == true )
412 | {
413 | $this->doGetRequest(array('getpage' => '/home/home.lua', 'logout' => '1'));
414 | }
415 | else
416 | {
417 | $formfields = array(
418 | 'getpage' => '../html/de/menus/menu2.html',
419 | 'security:command/logout' => 'logout',
420 | );
421 | $this->doPostForm($formfields);
422 | }
423 | }
424 |
425 |
426 | /**
427 | * the error method just throws an Exception
428 | *
429 | * @param string $message an error message for the Exception
430 | */
431 | public function error($message = null)
432 | {
433 | throw new Exception($message);
434 | }
435 |
436 |
437 | /**
438 | * a getter for the session ID
439 | *
440 | * @return string $this->sid
441 | */
442 | public function getSID()
443 | {
444 | return $this->sid;
445 | }
446 |
447 | /**
448 | * log a message
449 | *
450 | * @param $message string the message to log
451 | */
452 | public function logMessage($message)
453 | {
454 | if ( $this->config->getItem('newline') == false )
455 | {
456 | $this->config->setItem('newline', (PHP_OS == 'WINNT') ? "\r\n" : "\n");
457 | }
458 |
459 | if ( $this->config->getItem('logging') == 'console' )
460 | {
461 | echo $message;
462 | }
463 | else if ( $this->config->getItem('logging') == 'silent' || $this->config->getItem('logging') == false )
464 | {
465 | // do nothing
466 | }
467 | else
468 | {
469 | if ( is_writable($this->config->getItem('logging')) || is_writable(dirname($this->config->getItem('logging'))) )
470 | {
471 | file_put_contents($this->config->getItem('logging'), $message . $this->config->getItem('newline'), FILE_APPEND);
472 | }
473 | else
474 | {
475 | echo('Error: Cannot log to non-writeable file or dir: ' . $this->config->getItem('logging'));
476 | }
477 | }
478 | }
479 | }
480 |
481 | class fritzbox_api_config {
482 | protected $config = array();
483 |
484 | public function __construct()
485 | {
486 | # use the new .lua login method in current (end 2012) labor and newer firmwares (Fritz!OS 5.50 and up)
487 | $this->setItem('use_lua_login_method', true);
488 |
489 | # set to your Fritz!Box IP address or DNS name (defaults to fritz.box), for remote config mode, use the dyndns-name like example.dyndns.org
490 | $this->setItem('fritzbox_ip', 'fritz.box');
491 |
492 | # if needed, enable remote config here
493 | #$this->setItem('enable_remote_config', true);
494 | #$this->setItem('remote_config_user', 'test');
495 | #$this->setItem('remote_config_password', 'test123');
496 |
497 | # set to your Fritz!Box username, if login with username is enabled (will be ignored, when remote config is enabled)
498 | $this->setItem('username', false);
499 |
500 | # set to your Fritz!Box password (defaults to no password)
501 | $this->setItem('password', false);
502 |
503 | # set the logging mechanism (defaults to console logging)
504 | $this->setItem('logging', 'console'); // output to the console
505 | #$this->setItem('logging', 'silent'); // do not output anything, be careful with this logging mode
506 | #$this->setItem('logging', 'tam.log'); // the path to a writeable logfile
507 |
508 | # the newline character for the logfile (does not need to be changed in most cases)
509 | $this->setItem('newline', (PHP_OS == 'WINNT') ? "\r\n" : "\n");
510 | }
511 |
512 | /* gets an item from the config
513 | *
514 | * @param $item string the item to get
515 | * @return mixed the value of the item
516 | */
517 | public function getItem($item = 'all')
518 | {
519 | if ( $item == 'all' )
520 | {
521 | return $this->config;
522 | }
523 | elseif ( isset($this->config[$item]) )
524 | {
525 | return $this->config[$item];
526 | }
527 | return false;
528 | }
529 |
530 | /* sets an item into the config
531 | *
532 | * @param $item string the item to set
533 | * @param $value mixed the value to store into the item
534 | */
535 | public function setItem($item, $value)
536 | {
537 | $this->config[$item] = $value;
538 | }
539 | }
540 |
--------------------------------------------------------------------------------
/lib/fritzbox_api_php/fritzbox_delete_foncallslist.php:
--------------------------------------------------------------------------------
1 |
8 | * @license http://creativecommons.org/licenses/by-sa/3.0/de/ Creative Commons cc-by-sa
9 | * @version 0.1 2015-06-11
10 | * @package Fritz!Box PHP tools
11 | */
12 |
13 | try
14 | {
15 | // load the fritzbox_api class
16 | require_once('fritzbox_api.class.php');
17 | $fritz = new fritzbox_api();
18 |
19 | // init the output message
20 | $message = date('Y-m-d H:i') . ' ';
21 |
22 | // delete calllist form fields
23 | $formfields = array(
24 | 'getpage' => '/fon_num/foncalls_list.lua',
25 | 'usejournal' => '1',
26 | 'callstab' => 'all',
27 | 'submit' => 'clear',
28 | 'clear' => '1',
29 | );
30 |
31 | $fritz->doPostForm($formfields);
32 | // set a log message
33 | $message .= 'Call list sucessfully deleted';
34 | }
35 | catch (Exception $e)
36 | {
37 | $message .= $e->getMessage();
38 | }
39 |
40 | // log the result
41 | if ( isset($fritz) && is_object($fritz) && get_class($fritz) == 'fritzbox_api' )
42 | {
43 | $fritz->logMessage($message);
44 | }
45 | else
46 | {
47 | echo($message);
48 | }
49 | $fritz = null; // destroy the object to log out
50 | ?>
51 |
--------------------------------------------------------------------------------
/lib/fritzbox_api_php/fritzbox_diversity0on.php:
--------------------------------------------------------------------------------
1 | '../html/de/menus/menu2.html',
18 | 'telcfg:settings/Diversity' . $diversity . '/Active' => $mode,
19 | );
20 | $fritz->doPostForm($formfields);
21 | }
22 | catch (Exception $e)
23 | {
24 | $message .= $e->getMessage();
25 | }
26 |
27 | // log the result
28 | if ( isset($fritz) && is_object($fritz) && get_class($fritz) == 'fritzbox_api' )
29 | {
30 | $fritz->logMessage($message);
31 | }
32 | else
33 | {
34 | echo($message);
35 | }
36 | $fritz = null; // destroy the object to log out
37 | ?>
--------------------------------------------------------------------------------
/lib/fritzbox_api_php/fritzbox_get_foncallslist.php:
--------------------------------------------------------------------------------
1 |
12 | * @license http://creativecommons.org/licenses/by-sa/3.0/de/ Creative Commons cc-by-sa
13 | * @version 0.4 2013-01-02
14 | * @package Fritz!Box PHP tools
15 | */
16 |
17 | try
18 | {
19 | // load the fritzbox_api class
20 | require_once('fritzbox_api.class.php');
21 | $fritz = new fritzbox_api();
22 |
23 | // init the output message
24 | $message = date('Y-m-d H:i') . ' ';
25 |
26 | if ( !$fritz->config->getItem('foncallslist_path') )
27 | {
28 | throw new Exception('Mandatory config Item foncallslist_path not set.');
29 | }
30 | if ( ( file_exists($fritz->config->getItem('foncallslist_path')) && !is_writable($fritz->config->getItem('foncallslist_path')) ) || ( !file_exists($fritz->config->getItem('foncallslist_path')) && !is_writable(dirname($fritz->config->getItem('foncallslist_path'))) ) )
31 | {
32 | throw new Exception('Config item foncallslist_path (' . $fritz->config->getItem('foncallslist_path') . ') is not writeable.');
33 | }
34 |
35 | // get the phone calls list
36 | $params = array(
37 | //'getpage' => '../html/de/home/foncallsdaten.xml',
38 | //'getpage' => '../html/de/FRITZ!Box_Anrufliste.csv',
39 | 'getpage' => '/fon_num/foncalls_list.lua',
40 | );
41 | $fritz->doGetRequest($params);
42 |
43 | // get the phone calls list
44 | $params = array(
45 | //'getpage' => '../html/de/home/foncallsdaten.xml',
46 | //'getpage' => '../html/de/FRITZ!Box_Anrufliste.csv',
47 | 'getpage' => '/fon_num/foncalls_list.lua',
48 | 'csv' => '',
49 | );
50 | $output = $fritz->doGetRequest($params);
51 |
52 | // write out the call list to the desired path
53 | file_put_contents($fritz->config->getItem('foncallslist_path'), $output);
54 |
55 | // set a log message
56 | $message .= 'Call list sucessfully downloaded';
57 | }
58 | catch (Exception $e)
59 | {
60 | $message .= $e->getMessage();
61 | }
62 |
63 | // log the result
64 | if ( isset($fritz) && is_object($fritz) && get_class($fritz) == 'fritzbox_api' )
65 | {
66 | $fritz->logMessage($message);
67 | }
68 | else
69 | {
70 | echo($message);
71 | }
72 | $fritz = null; // destroy the object to log out
73 | ?>
--------------------------------------------------------------------------------
/lib/fritzbox_api_php/fritzbox_get_foncallslist_xml.php:
--------------------------------------------------------------------------------
1 |
12 | * @license http://creativecommons.org/licenses/by-sa/3.0/de/ Creative Commons cc-by-sa
13 | * @version 0.3 2013-01-02
14 | * @package Fritz!Box PHP tools
15 | */
16 |
17 | try
18 | {
19 | // load the fritzbox_api class
20 | require_once('fritzbox_api.class.php');
21 | $fritz = new fritzbox_api();
22 |
23 | // init the output message
24 | $message = date('Y-m-d H:i') . ' ';
25 |
26 | if ( !$fritz->config->getItem('foncallslist_path') )
27 | {
28 | throw new Exception('Mandatory config Item foncallslist_path not set.');
29 | }
30 | if ( ( file_exists($fritz->config->getItem('foncallslist_path')) && !is_writable($fritz->config->getItem('foncallslist_path')) ) || ( !file_exists($fritz->config->getItem('foncallslist_path')) && !is_writable(dirname($fritz->config->getItem('foncallslist_path'))) ) )
31 | {
32 | throw new Exception('Config item foncallslist_path (' . $fritz->config->getItem('foncallslist_path') . ') is not writeable.');
33 | }
34 |
35 | // get the frontend-page to refresh the list
36 | $params = array(
37 | 'getpage' => '../html/de/menus/menu2.html',
38 | 'var:menu' => 'fon',
39 | 'var:pagename' => 'foncalls',
40 | 'var:errorpagename' => 'foncalls',
41 | 'var:type' => '0',
42 | );
43 | $fritz->doPostForm($params);
44 |
45 | // get the phone calls list
46 | $params = array(
47 | 'getpage' => '../html/de/home/foncallsdaten.xml',
48 | );
49 | $output = $fritz->doGetRequest($params);
50 |
51 | // write out the call list to the desired path
52 | file_put_contents($fritz->config->getItem('foncallslist_path'), $output);
53 |
54 | // set a log message
55 | $message .= 'Call list sucessfully downloaded';
56 | }
57 | catch (Exception $e)
58 | {
59 | $message .= $e->getMessage();
60 | }
61 |
62 | // log the result
63 | if ( isset($fritz) && is_object($fritz) && get_class($fritz) == 'fritzbox_api' )
64 | {
65 | $fritz->logMessage($message);
66 | }
67 | else
68 | {
69 | echo($message);
70 | }
71 | $fritz = null; // destroy the object to log out
72 | ?>
--------------------------------------------------------------------------------
/lib/fritzbox_api_php/fritzbox_guestlan_on_off.php:
--------------------------------------------------------------------------------
1 |
11 | * @license http://creativecommons.org/licenses/by-sa/3.0/de/ Creative Commons cc-by-sa
12 | * @version 0.3 2013-01-02
13 | * @package Fritz!Box PHP tools
14 | */
15 |
16 | try
17 | {
18 | // load the fritzbox_api class
19 | require_once('fritzbox_api.class.php');
20 | $fritz = new fritzbox_api();
21 |
22 | // init the output message
23 | $message = date('Y-m-d H:i') . ' ';
24 |
25 | // handle the CLI arguments or give a help message
26 | if (isset($argv[1]) && ($argv[1] == 0 || $argv[1] == 1) )
27 | {
28 | $mode = (bool)$argv[1];
29 | }
30 | else
31 | {
32 | if ( $fritz->config->getItem('logging') == 'console' )
33 | {
34 | echo '
35 | Enables or disables the LAN4 guest access of a Fritz!Box
36 |
37 | Usage on UNIX systems:
38 | /path/to/php ' . $argv[0] . ' {0|1}
39 |
40 | Usage on Windows systems:
41 | "c:\path\to\php.exe" ' . $argv[0] . ' {0|1}
42 |
43 | 0 disables the guest access
44 | 1 enables the guest access
45 | ';
46 | }
47 | else
48 | {
49 | $fritz->logMessage($message . 'ERROR: Script was called without or with an invalid argument');
50 | }
51 | exit;
52 | }
53 |
54 |
55 | // read the current settings
56 | $formfields = array(
57 | 'getpage' => '/net/network_settings.lua',
58 | );
59 | $output = $fritz->doGetRequest($formfields);
60 |
61 |
62 | // read time_server_activ setting
63 | preg_match('@name="time_server_activ"[^>]+(checked)[^>]*@', $output, $matches);
64 | if ( isset($matches[1]) )
65 | {
66 | $formfields['time_server_activ'] = 'on';
67 | }
68 | // read time_server setting
69 | preg_match('@name="time_server"[^>]+value="([^"]*)"[^>]*@', $output, $matches);
70 | $formfields['time_server'] = isset($matches[1]) ? $matches[1] : '0.europe.pool.ntp.org';
71 | // read other_prefix_allowed setting
72 | preg_match('@name="other_prefix_allowed"[^>]+(checked)[^>]*@', $output, $matches);
73 | if ( isset($matches[1]) )
74 | {
75 | $formfields['other_prefix_allowed'] = 'on';
76 | }
77 | // read dnsv6_server_activ setting
78 | preg_match('@name="dnsv6_server_activ"[^>]+(checked)[^>]*@', $output, $matches);
79 | if ( isset($matches[1]) )
80 | {
81 | $formfields['dnsv6_server_activ'] = 'on';
82 | }
83 |
84 | // set new given setting
85 | if ( $mode == true )
86 | {
87 | $formfields['guest_enabled'] = 'on';
88 | }
89 |
90 | // do the update
91 | $formfields['btnSave'] = '';
92 | $output = $fritz->doPostForm($formfields);
93 |
94 | preg_match('@name="guest_enabled"[^>]+(checked)[^>]*@', $output, $matches);
95 | if ( isset($matches[1]) && $mode == true )
96 | {
97 | $message .= 'LAN4 guest access is now active.';
98 | }
99 | else if ( !isset($matches[1]) && $mode == false )
100 | {
101 | $message .= 'LAN4 guest access is now inactive.';
102 | }
103 | else if ( isset($matches[1]) && $mode == false )
104 | {
105 | $message .= 'ERROR: LAN4 guest access status change failed, should be inactive, but is still active.';
106 | }
107 | else if ( !isset($matches[1]) && $mode == true )
108 | {
109 | $message .= 'ERROR: LAN4 guest access status change failed, should be active, but is still inactive.';
110 | }
111 | }
112 | catch (Exception $e)
113 | {
114 | $message .= $e->getMessage();
115 | }
116 |
117 | // log the result
118 | if ( isset($fritz) && is_object($fritz) && get_class($fritz) == 'fritzbox_api' )
119 | {
120 | $fritz->logMessage($message);
121 | }
122 | else
123 | {
124 | echo($message);
125 | }
126 | $fritz = null; // destroy the object to log out
127 | ?>
--------------------------------------------------------------------------------
/lib/fritzbox_api_php/fritzbox_guestwlan_on_off.php:
--------------------------------------------------------------------------------
1 |
10 | * @license http://creativecommons.org/licenses/by-sa/3.0/de/ Creative Commons cc-by-sa
11 | * @version 0.3 2013-01-02
12 | * @package Fritz!Box PHP tools
13 | */
14 |
15 | try
16 | {
17 | // load the fritzbox_api class
18 | require_once('fritzbox_api.class.php');
19 | $fritz = new fritzbox_api();
20 |
21 | // init the output message
22 | $message = date('Y-m-d H:i') . ' ';
23 |
24 | // handle the CLI arguments or give a help message
25 | if (isset($argv[1]) && ($argv[1] == 0 || $argv[1] == 1) )
26 | {
27 | $mode = (bool)$argv[1];
28 | }
29 | else
30 | {
31 | if ( $fritz->config->getItem('logging') == 'console' )
32 | {
33 | echo '
34 | Enables or disables the WLAN guest access of a Fritz!Box
35 |
36 | Usage on UNIX systems:
37 | /path/to/php ' . $argv[0] . ' {0|1} [optional: PASSWORD]
38 |
39 | Usage on Windows systems:
40 | c:\path\to\php.exe ' . $argv[0] . ' {0|1} [optional: PASSWORD]
41 |
42 | 0 disables the guest access
43 | 1 enables the guest access
44 |
45 | The optional argument PASSWORD sets a new guest access password (min 8 chars)
46 | Defaults to false, so the current password is kept.
47 | ';
48 | }
49 | else
50 | {
51 | $fritz->logMessage($message . 'ERROR: Script was called without or with an invalid argument');
52 | }
53 | exit;
54 | }
55 | $wpa_key = (isset($argv[2]) && strlen($argv[2]) >= 8 && strlen($argv[2]) <= 63) ? $argv[2] : false;
56 |
57 |
58 | // read the current settings
59 | $formfields = array(
60 | 'getpage' => '/wlan/guest_access.lua',
61 | );
62 | $output = $fritz->doGetRequest($formfields);
63 |
64 | // read down_time_activ setting
65 | preg_match('@name="down_time_activ"[^>]+(checked)[^>]*@', $output, $matches);
66 | if ( isset($matches[1]) )
67 | {
68 | $formfields['down_time_activ'] = 'on';
69 | }
70 | // read down_time_value setting
71 | preg_match('@name="down_time_value".*?
';
38 |
39 | if ($vCard -> PHOTO)
40 | {
41 | foreach ($vCard -> PHOTO as $Photo)
42 | {
43 | if ($Photo['encoding'] == 'b')
44 | {
45 | echo ' ';
46 | }
47 | else
48 | {
49 | echo ' ';
50 | }
51 |
52 | /*
53 | // It can also be saved to a file
54 | try
55 | {
56 | $vCard -> SaveFile('photo', 0, 'test_image.jpg');
57 | // The parameters are:
58 | // - name of the file we want to save (photo, logo or sound)
59 | // - index of the file in case of multiple files (defaults to 0)
60 | // - target path to save to, including the filenam
61 | }
62 | catch (Exception $E)
63 | {
64 | // Target path not writable
65 | }
66 | */
67 | }
68 | }
69 |
70 | foreach ($vCard -> N as $Name)
71 | {
72 | echo '