summaryrefslogtreecommitdiff
path: root/platform/www/lib/plugins/authad/adLDAP/classes/adLDAPExchange.php
blob: d70aac77993854edabb78ca79a73f1bb6c9c88ec (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
<?php
/**
 * PHP LDAP CLASS FOR MANIPULATING ACTIVE DIRECTORY 
 * Version 4.0.4
 * 
 * PHP Version 5 with SSL and LDAP support
 * 
 * Written by Scott Barnett, Richard Hyland
 *   email: scott@wiggumworld.com, adldap@richardhyland.com
 *   http://adldap.sourceforge.net/
 * 
 * Copyright (c) 2006-2012 Scott Barnett, Richard Hyland
 * 
 * We'd appreciate any improvements or additions to be submitted back
 * to benefit the entire community :)
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * @category ToolsAndUtilities
 * @package adLDAP
 * @subpackage Exchange
 * @author Scott Barnett, Richard Hyland
 * @copyright (c) 2006-2012 Scott Barnett, Richard Hyland
 * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html LGPLv2.1
 * @revision $Revision: 97 $
 * @version 4.0.4
 * @link http://adldap.sourceforge.net/
 */
require_once(dirname(__FILE__) . '/../adLDAP.php');

/**
* MICROSOFT EXCHANGE FUNCTIONS
*/
class adLDAPExchange {
    /**
    * The current adLDAP connection via dependency injection
    * 
    * @var adLDAP
    */
    protected $adldap;
    
    public function __construct(adLDAP $adldap) {
        $this->adldap = $adldap;
    }
    
    /**
    * Create an Exchange account
    * 
    * @param string $username The username of the user to add the Exchange account to
    * @param array $storageGroup The mailbox, Exchange Storage Group, for the user account, this must be a full CN
    *                            If the storage group has a different base_dn to the adLDAP configuration, set it using $base_dn
    * @param string $emailAddress The primary email address to add to this user
    * @param string $mailNickname The mail nick name.  If mail nickname is blank, the username will be used
    * @param bool $mdbUseDefaults Indicates whether the store should use the default quota, rather than the per-mailbox quota.
    * @param string $baseDn Specify an alternative base_dn for the Exchange storage group
    * @param bool $isGUID Is the username passed a GUID or a samAccountName
    * @return bool
    */
    public function createMailbox($username, $storageGroup, $emailAddress, $mailNickname=NULL, $useDefaults=TRUE, $baseDn=NULL, $isGUID=false)
    {
        if ($username === NULL){ return "Missing compulsory field [username]"; }     
        if ($storageGroup === NULL) { return "Missing compulsory array [storagegroup]"; }
        if (!is_array($storageGroup)) { return "[storagegroup] must be an array"; }
        if ($emailAddress === NULL) { return "Missing compulsory field [emailAddress]"; }
        
        if ($baseDn === NULL) {
            $baseDn = $this->adldap->getBaseDn();   
        }
        
        $container = "CN=" . implode(",CN=", $storageGroup);
        
        if ($mailNickname === NULL) { 
            $mailNickname = $username; 
        }
        $mdbUseDefaults = $this->adldap->utilities()->boolToString($useDefaults);
        
        $attributes = array(
            'exchange_homemdb'=>$container.",".$baseDn,
            'exchange_proxyaddress'=>'SMTP:' . $emailAddress,
            'exchange_mailnickname'=>$mailNickname,
            'exchange_usedefaults'=>$mdbUseDefaults
        );
        $result = $this->adldap->user()->modify($username, $attributes, $isGUID);
        if ($result == false) { 
            return false; 
        }
        return true;
    }
    
    /**
    * Add an X400 address to Exchange
    * See http://tools.ietf.org/html/rfc1685 for more information.
    * An X400 Address looks similar to this X400:c=US;a= ;p=Domain;o=Organization;s=Doe;g=John;
    * 
    * @param string $username The username of the user to add the X400 to to
    * @param string $country Country
    * @param string $admd Administration Management Domain
    * @param string $pdmd Private Management Domain (often your AD domain)
    * @param string $org Organization
    * @param string $surname Surname
    * @param string $givenName Given name
    * @param bool $isGUID Is the username passed a GUID or a samAccountName
    * @return bool
    */
    public function addX400($username, $country, $admd, $pdmd, $org, $surname, $givenName, $isGUID=false) 
    {
        if ($username === NULL){ return "Missing compulsory field [username]"; }     
        
        $proxyValue = 'X400:';
            
        // Find the dn of the user
        $user = $this->adldap->user()->info($username, array("cn","proxyaddresses"), $isGUID);
        if ($user[0]["dn"] === NULL) { return false; }
        $userDn = $user[0]["dn"];
        
        // We do not have to demote an email address from the default so we can just add the new proxy address
        $attributes['exchange_proxyaddress'] = $proxyValue . 'c=' . $country . ';a=' . $admd . ';p=' . $pdmd . ';o=' . $org . ';s=' . $surname . ';g=' . $givenName . ';';
       
        // Translate the update to the LDAP schema                
        $add = $this->adldap->adldap_schema($attributes);
        
        if (!$add) { return false; }
        
        // Do the update
        // Take out the @ to see any errors, usually this error might occur because the address already
        // exists in the list of proxyAddresses
        $result = @ldap_mod_add($this->adldap->getLdapConnection(), $userDn, $add);
        if ($result == false) { 
            return false; 
        }
        
        return true;
    }
    
    /**
    * Add an address to Exchange
    * 
    * @param string $username The username of the user to add the Exchange account to
    * @param string $emailAddress The email address to add to this user
    * @param bool $default Make this email address the default address, this is a bit more intensive as we have to demote any existing default addresses
    * @param bool $isGUID Is the username passed a GUID or a samAccountName
    * @return bool
    */
    public function addAddress($username, $emailAddress, $default = FALSE, $isGUID = false) 
    {
        if ($username === NULL) { return "Missing compulsory field [username]"; }     
        if ($emailAddress === NULL) { return "Missing compulsory fields [emailAddress]"; }
        
        $proxyValue = 'smtp:';
        if ($default === true) {
            $proxyValue = 'SMTP:';
        }
              
        // Find the dn of the user
        $user = $this->adldap->user()->info($username, array("cn","proxyaddresses"), $isGUID);
        if ($user[0]["dn"] === NULL){ return false; }
        $userDn = $user[0]["dn"];
        
        // We need to scan existing proxy addresses and demote the default one
        if (is_array($user[0]["proxyaddresses"]) && $default === true) {
            $modAddresses = array();
            for ($i=0;$i<sizeof($user[0]['proxyaddresses']);$i++) {
                if (strstr($user[0]['proxyaddresses'][$i], 'SMTP:') !== false) {
                    $user[0]['proxyaddresses'][$i] = str_replace('SMTP:', 'smtp:', $user[0]['proxyaddresses'][$i]);
                }
                if ($user[0]['proxyaddresses'][$i] != '') {
                    $modAddresses['proxyAddresses'][$i] = $user[0]['proxyaddresses'][$i];
                }
            }
            $modAddresses['proxyAddresses'][(sizeof($user[0]['proxyaddresses'])-1)] = 'SMTP:' . $emailAddress;
            
            $result = @ldap_mod_replace($this->adldap->getLdapConnection(), $userDn, $modAddresses);
            if ($result == false) { 
                return false; 
            }
            
            return true;
        }
        else {
            // We do not have to demote an email address from the default so we can just add the new proxy address
            $attributes['exchange_proxyaddress'] = $proxyValue . $emailAddress;
            
            // Translate the update to the LDAP schema                
            $add = $this->adldap->adldap_schema($attributes);
            
            if (!$add) { 
                return false; 
            }
            
            // Do the update
            // Take out the @ to see any errors, usually this error might occur because the address already
            // exists in the list of proxyAddresses
            $result = @ldap_mod_add($this->adldap->getLdapConnection(), $userDn,$add);
            if ($result == false) { 
                return false; 
            }
            
            return true;
        }
    }
    
    /**
    * Remove an address to Exchange
    * If you remove a default address the account will no longer have a default, 
    * we recommend changing the default address first
    * 
    * @param string $username The username of the user to add the Exchange account to
    * @param string $emailAddress The email address to add to this user
    * @param bool $isGUID Is the username passed a GUID or a samAccountName
    * @return bool
    */
    public function deleteAddress($username, $emailAddress, $isGUID=false) 
    {
        if ($username === NULL) { return "Missing compulsory field [username]"; }     
        if ($emailAddress === NULL) { return "Missing compulsory fields [emailAddress]"; }
        
        // Find the dn of the user
        $user = $this->adldap->user()->info($username, array("cn","proxyaddresses"), $isGUID);
        if ($user[0]["dn"] === NULL) { return false; }
        $userDn = $user[0]["dn"];
        
        if (is_array($user[0]["proxyaddresses"])) {
            $mod = array();
            for ($i=0;$i<sizeof($user[0]['proxyaddresses']);$i++) {
                if (strstr($user[0]['proxyaddresses'][$i], 'SMTP:') !== false && $user[0]['proxyaddresses'][$i] == 'SMTP:' . $emailAddress) {
                    $mod['proxyAddresses'][0] = 'SMTP:' . $emailAddress;
                }
                elseif (strstr($user[0]['proxyaddresses'][$i], 'smtp:') !== false && $user[0]['proxyaddresses'][$i] == 'smtp:' . $emailAddress) {
                    $mod['proxyAddresses'][0] = 'smtp:' . $emailAddress;
                }
            }
            
            $result = @ldap_mod_del($this->adldap->getLdapConnection(), $userDn,$mod);
            if ($result == false) { 
                return false; 
            }
            
            return true;
        }
        else {
            return false;
        }
    }
    /**
    * Change the default address
    * 
    * @param string $username The username of the user to add the Exchange account to
    * @param string $emailAddress The email address to make default
    * @param bool $isGUID Is the username passed a GUID or a samAccountName
    * @return bool
    */
    public function primaryAddress($username, $emailAddress, $isGUID = false) 
    {
        if ($username === NULL) { return "Missing compulsory field [username]"; }     
        if ($emailAddress === NULL) { return "Missing compulsory fields [emailAddress]"; }
        
        // Find the dn of the user
        $user = $this->adldap->user()->info($username, array("cn","proxyaddresses"), $isGUID);
        if ($user[0]["dn"] === NULL){ return false; }
        $userDn = $user[0]["dn"];
        
        if (is_array($user[0]["proxyaddresses"])) {
            $modAddresses = array();
            for ($i=0;$i<sizeof($user[0]['proxyaddresses']);$i++) {
                if (strstr($user[0]['proxyaddresses'][$i], 'SMTP:') !== false) {
                    $user[0]['proxyaddresses'][$i] = str_replace('SMTP:', 'smtp:', $user[0]['proxyaddresses'][$i]);
                }
                if ($user[0]['proxyaddresses'][$i] == 'smtp:' . $emailAddress) {
                    $user[0]['proxyaddresses'][$i] = str_replace('smtp:', 'SMTP:', $user[0]['proxyaddresses'][$i]);
                }
                if ($user[0]['proxyaddresses'][$i] != '') {
                    $modAddresses['proxyAddresses'][$i] = $user[0]['proxyaddresses'][$i];
                }
            }
            
            $result = @ldap_mod_replace($this->adldap->getLdapConnection(), $userDn, $modAddresses);
            if ($result == false) { 
                return false; 
            }
            
            return true;
        }
        
    }
    
    /**
    * Mail enable a contact
    * Allows email to be sent to them through Exchange
    * 
    * @param string $distinguishedName The contact to mail enable
    * @param string $emailAddress The email address to allow emails to be sent through
    * @param string $mailNickname The mailnickname for the contact in Exchange.  If NULL this will be set to the display name
    * @return bool
    */
    public function contactMailEnable($distinguishedName, $emailAddress, $mailNickname = NULL)
    {
        if ($distinguishedName === NULL) { return "Missing compulsory field [distinguishedName]"; }   
        if ($emailAddress === NULL) { return "Missing compulsory field [emailAddress]"; }  
        
        if ($mailNickname !== NULL) {
            // Find the dn of the user
            $user = $this->adldap->contact()->info($distinguishedName, array("cn","displayname"));
            if ($user[0]["displayname"] === NULL) { return false; }
            $mailNickname = $user[0]['displayname'][0];
        }
        
        $attributes = array("email"=>$emailAddress,"contact_email"=>"SMTP:" . $emailAddress,"exchange_proxyaddress"=>"SMTP:" . $emailAddress,"exchange_mailnickname" => $mailNickname);
         
        // Translate the update to the LDAP schema                
        $mod = $this->adldap->adldap_schema($attributes);
        
        // Check to see if this is an enabled status update
        if (!$mod) { return false; }
        
        // Do the update
        $result = ldap_modify($this->adldap->getLdapConnection(), $distinguishedName, $mod);
        if ($result == false) { return false; }
        
        return true;
    }
    
    /**
    * Returns a list of Exchange Servers in the ConfigurationNamingContext of the domain
    * 
    * @param array $attributes An array of the AD attributes you wish to return
    * @return array
    */
    public function servers($attributes = array('cn','distinguishedname','serialnumber')) 
    {
        if (!$this->adldap->getLdapBind()){ return false; }
        
        $configurationNamingContext = $this->adldap->getRootDse(array('configurationnamingcontext'));
        $sr = @ldap_search($this->adldap->getLdapConnection(), $configurationNamingContext[0]['configurationnamingcontext'][0],'(&(objectCategory=msExchExchangeServer))', $attributes);
        $entries = @ldap_get_entries($this->adldap->getLdapConnection(), $sr);
        return $entries;
    }
    
    /**
    * Returns a list of Storage Groups in Exchange for a given mail server
    * 
    * @param string $exchangeServer The full DN of an Exchange server.  You can use exchange_servers() to find the DN for your server
    * @param array $attributes An array of the AD attributes you wish to return
    * @param bool $recursive If enabled this will automatically query the databases within a storage group
    * @return array
    */
    public function storageGroups($exchangeServer, $attributes = array('cn','distinguishedname'), $recursive = NULL) 
    {
        if (!$this->adldap->getLdapBind()){ return false; }
        if ($exchangeServer === NULL) { return "Missing compulsory field [exchangeServer]"; }
        if ($recursive === NULL) { $recursive = $this->adldap->getRecursiveGroups(); }

        $filter = '(&(objectCategory=msExchStorageGroup))';
        $sr = @ldap_search($this->adldap->getLdapConnection(), $exchangeServer, $filter, $attributes);
        $entries = @ldap_get_entries($this->adldap->getLdapConnection(), $sr);

        if ($recursive === true) {
            for ($i=0; $i<$entries['count']; $i++) {
                $entries[$i]['msexchprivatemdb'] = $this->storageDatabases($entries[$i]['distinguishedname'][0]);       
            }
        }
        
        return $entries;
    }
    
    /**
    * Returns a list of Databases within any given storage group in Exchange for a given mail server
    * 
    * @param string $storageGroup The full DN of an Storage Group.  You can use exchange_storage_groups() to find the DN 
    * @param array $attributes An array of the AD attributes you wish to return
    * @return array
    */
    public function storageDatabases($storageGroup, $attributes = array('cn','distinguishedname','displayname')) {
        if (!$this->adldap->getLdapBind()){ return false; }
        if ($storageGroup === NULL) { return "Missing compulsory field [storageGroup]"; }
        
        $filter = '(&(objectCategory=msExchPrivateMDB))';
        $sr = @ldap_search($this->adldap->getLdapConnection(), $storageGroup, $filter, $attributes);
        $entries = @ldap_get_entries($this->adldap->getLdapConnection(), $sr);
        return $entries;
    }
}
?>