update readme
[auerswald-compact-ldap.git] / ldap2csv.php
1 #!/usr/bin/env php
2 <?php
3 /**
4  * Fetches all entries from the LDAP server and outputs a CSV file
5  * compatible with a Auerswald COMpact 3000's address book upload.
6  *
7  * PHP version 5
8  *
9  * @category Tools
10  * @package  auerswald-compact-ldap
11  * @author   Christian Weiske <cweiske@cweiske.de>
12  * @license  http://www.gnu.org/licenses/agpl.html AGPL v3 or later
13  */
14 if (!is_file(__DIR__ . '/config.php')) {
15     echo "Copy config.php.dist to config.php and adjust it.\n";
16     exit(1);
17 }
18 require_once __DIR__ . '/config.php';
19 require_once 'Net/LDAP2.php';
20
21 $ldap = Net_LDAP2::connect($ldapcfg);
22 if (Net_LDAP2::isError($ldap)) {
23     die('Could not connect to LDAP-server: ' . $ldap->getMessage() . "\n");
24 }
25
26 $numberfields = array(
27     'companyPhone',
28     'facsimileTelephoneNumber',
29     'homeFacsimileTelephoneNumber',
30     'homePhone',
31     'mobile',
32     'otherPhone',
33     'pager',
34     'telephoneNumber',
35 );
36
37 $search = $ldap->search(
38     null, null, 
39     array(
40         'scope' => 'sub',
41         'attributes' => array_merge(
42             array('displayName', 'cn'),
43             $numberfields
44         )
45     )
46 );
47 if (Net_LDAP2::isError($search)) {
48     die('Error searching: ' . $search->getMessage() . "\n");
49 }
50
51 echo "Kurzwahl;Rufnummer;Name\n";
52 while ($entry = $search->shiftEntry()) {
53     $a = $entry->getValues();
54     if (count($a) == 0) {
55         continue;
56     }
57     if (strpos($entry->dn(), ',ou=test,') !== false) {
58         continue;
59     }
60     if (isset($a['displayName'])) {
61         $name = $a['displayName'];
62     } else {
63         $name = $a['cn'];
64     }
65
66     foreach ($numberfields as $nfield) {
67         if (isset($a[$nfield])) {
68             foreach ((array)$a[$nfield] as $fv) {
69                 echo sprintf(
70                     ";%s;%s\n",
71                     str_replace(
72                         array(' ', '+'),
73                         array('', '00'),
74                         $fv
75                     ),
76                     utf8_decode($name)
77                 );
78             }
79         }
80     }
81 }
82 ?>