summaryrefslogtreecommitdiff
path: root/platform/www/lib/plugins/authad/adLDAP/classes/adLDAPUsers.php
blob: dc3ebd7ccb6c217a10e45308bbacb58c8a7acd47 (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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
<?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 User
 * @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');
require_once(dirname(__FILE__) . '/../collections/adLDAPUserCollection.php');

/**
* USER FUNCTIONS
*/
class adLDAPUsers {
    /**
    * The current adLDAP connection via dependency injection
    * 
    * @var adLDAP
    */
    protected $adldap;
    
    public function __construct(adLDAP $adldap) {
        $this->adldap = $adldap;
    }
    
    /**
    * Validate a user's login credentials
    * 
    * @param string $username A user's AD username
    * @param string $password A user's AD password
    * @param bool optional $prevent_rebind
    * @return bool
    */
    public function authenticate($username, $password, $preventRebind = false) {
        return $this->adldap->authenticate($username, $password, $preventRebind);
    }
    
    /**
    * Create a user
    * 
    * If you specify a password here, this can only be performed over SSL
    * 
    * @param array $attributes The attributes to set to the user account
    * @return bool
    */
    public function create($attributes)
    {
        // Check for compulsory fields
        if (!array_key_exists("username", $attributes)){ return "Missing compulsory field [username]"; }
        if (!array_key_exists("firstname", $attributes)){ return "Missing compulsory field [firstname]"; }
        if (!array_key_exists("surname", $attributes)){ return "Missing compulsory field [surname]"; }
        if (!array_key_exists("email", $attributes)){ return "Missing compulsory field [email]"; }
        if (!array_key_exists("container", $attributes)){ return "Missing compulsory field [container]"; }
        if (!is_array($attributes["container"])){ return "Container attribute must be an array."; }

        if (array_key_exists("password",$attributes) && (!$this->adldap->getUseSSL() && !$this->adldap->getUseTLS())){ 
            throw new adLDAPException('SSL must be configured on your webserver and enabled in the class to set passwords.');
        }

        if (!array_key_exists("display_name", $attributes)) { 
            $attributes["display_name"] = $attributes["firstname"] . " " . $attributes["surname"]; 
        }

        // Translate the schema
        $add = $this->adldap->adldap_schema($attributes);
        
        // Additional stuff only used for adding accounts
        $add["cn"][0] = $attributes["display_name"];
        $add["samaccountname"][0] = $attributes["username"];
        $add["objectclass"][0] = "top";
        $add["objectclass"][1] = "person";
        $add["objectclass"][2] = "organizationalPerson";
        $add["objectclass"][3] = "user"; //person?
        //$add["name"][0]=$attributes["firstname"]." ".$attributes["surname"];

        // Set the account control attribute
        $control_options = array("NORMAL_ACCOUNT");
        if (!$attributes["enabled"]) { 
            $control_options[] = "ACCOUNTDISABLE"; 
        }
        $add["userAccountControl"][0] = $this->accountControl($control_options);
        
        // Determine the container
        $attributes["container"] = array_reverse($attributes["container"]);
        $container = "OU=" . implode(", OU=",$attributes["container"]);

        // Add the entry
        $result = @ldap_add($this->adldap->getLdapConnection(), "CN=" . $add["cn"][0] . ", " . $container . "," . $this->adldap->getBaseDn(), $add);
        if ($result != true) { 
            return false; 
        }
        
        return true;
    }
    
    /**
    * Account control options
    *
    * @param array $options The options to convert to int 
    * @return int
    */
    protected function accountControl($options)
    {
        $val=0;

        if (is_array($options)) {
            if (in_array("SCRIPT",$options)){ $val=$val+1; }
            if (in_array("ACCOUNTDISABLE",$options)){ $val=$val+2; }
            if (in_array("HOMEDIR_REQUIRED",$options)){ $val=$val+8; }
            if (in_array("LOCKOUT",$options)){ $val=$val+16; }
            if (in_array("PASSWD_NOTREQD",$options)){ $val=$val+32; }
            //PASSWD_CANT_CHANGE Note You cannot assign this permission by directly modifying the UserAccountControl attribute.
            //For information about how to set the permission programmatically, see the "Property flag descriptions" section.
            if (in_array("ENCRYPTED_TEXT_PWD_ALLOWED",$options)){ $val=$val+128; }
            if (in_array("TEMP_DUPLICATE_ACCOUNT",$options)){ $val=$val+256; }
            if (in_array("NORMAL_ACCOUNT",$options)){ $val=$val+512; }
            if (in_array("INTERDOMAIN_TRUST_ACCOUNT",$options)){ $val=$val+2048; }
            if (in_array("WORKSTATION_TRUST_ACCOUNT",$options)){ $val=$val+4096; }
            if (in_array("SERVER_TRUST_ACCOUNT",$options)){ $val=$val+8192; }
            if (in_array("DONT_EXPIRE_PASSWORD",$options)){ $val=$val+65536; }
            if (in_array("MNS_LOGON_ACCOUNT",$options)){ $val=$val+131072; }
            if (in_array("SMARTCARD_REQUIRED",$options)){ $val=$val+262144; }
            if (in_array("TRUSTED_FOR_DELEGATION",$options)){ $val=$val+524288; }
            if (in_array("NOT_DELEGATED",$options)){ $val=$val+1048576; }
            if (in_array("USE_DES_KEY_ONLY",$options)){ $val=$val+2097152; }
            if (in_array("DONT_REQ_PREAUTH",$options)){ $val=$val+4194304; } 
            if (in_array("PASSWORD_EXPIRED",$options)){ $val=$val+8388608; }
            if (in_array("TRUSTED_TO_AUTH_FOR_DELEGATION",$options)){ $val=$val+16777216; }
        }
        return $val;
    }
    
    /**
    * Delete a user account
    * 
    * @param string $username The username to delete (please be careful here!)
    * @param bool $isGUID Is the username a GUID or a samAccountName
    * @return array
    */
    public function delete($username, $isGUID = false) 
    {      
        $userinfo = $this->info($username, array("*"), $isGUID);
        $dn = $userinfo[0]['distinguishedname'][0];
        $result = $this->adldap->folder()->delete($dn);
        if ($result != true) { 
            return false;
        }        
        return true;
    }
    
    /**
    * Groups the user is a member of
    * 
    * @param string $username The username to query
    * @param bool $recursive Recursive list of groups
    * @param bool $isGUID Is the username passed a GUID or a samAccountName
    * @return array
    */
    public function groups($username, $recursive = NULL, $isGUID = false)
    {
        if ($username === NULL) { return false; }
        if ($recursive === NULL) { $recursive = $this->adldap->getRecursiveGroups(); } // Use the default option if they haven't set it
        if (!$this->adldap->getLdapBind()) { return false; }
        
        // Search the directory for their information
        $info = @$this->info($username, array("memberof", "primarygroupid"), $isGUID);
        $groups = $this->adldap->utilities()->niceNames($info[0]["memberof"]); // Presuming the entry returned is our guy (unique usernames)

        if ($recursive === true){
            foreach ($groups as $id => $groupName){
                $extraGroups = $this->adldap->group()->recursiveGroups($groupName);
                $groups = array_merge($groups, $extraGroups);
            }
        }
        
        return $groups;
    }
    
    /**
    * Find information about the users. Returned in a raw array format from AD
    * 
    * @param string $username The username to query
    * @param array $fields Array of parameters to query
    * @param bool $isGUID Is the username passed a GUID or a samAccountName
    * @return array
    */
    public function info($username, $fields = NULL, $isGUID = false)
    {
        if ($username === NULL) { return false; }
        if (!$this->adldap->getLdapBind()) { return false; }

        if ($isGUID === true) {
            $username = $this->adldap->utilities()->strGuidToHex($username);
            $filter = "objectguid=" . $username;
        }
        else if (strstr($username, "@")) {
             $filter = "userPrincipalName=" . $username;
        }
        else {
             $filter = "samaccountname=" . $username;
        }
        $filter = "(&(objectCategory=person)({$filter}))";
        if ($fields === NULL) { 
            $fields = array("samaccountname","mail","memberof","department","displayname","telephonenumber","primarygroupid","objectsid"); 
        }
        if (!in_array("objectsid", $fields)) {
            $fields[] = "objectsid";
        }
        $sr = ldap_search($this->adldap->getLdapConnection(), $this->adldap->getBaseDn(), $filter, $fields);
        $entries = ldap_get_entries($this->adldap->getLdapConnection(), $sr);
        
        if (isset($entries[0])) {
            if ($entries[0]['count'] >= 1) {
                if (in_array("memberof", $fields)) {
                    // AD does not return the primary group in the ldap query, we may need to fudge it
                    if ($this->adldap->getRealPrimaryGroup() && isset($entries[0]["primarygroupid"][0]) && isset($entries[0]["objectsid"][0])){
                        //$entries[0]["memberof"][]=$this->group_cn($entries[0]["primarygroupid"][0]);
                        $entries[0]["memberof"][] = $this->adldap->group()->getPrimaryGroup($entries[0]["primarygroupid"][0], $entries[0]["objectsid"][0]);
                    } else {
                        $entries[0]["memberof"][] = "CN=Domain Users,CN=Users," . $this->adldap->getBaseDn();
                    }
                    if (!isset($entries[0]["memberof"]["count"])) {
                        $entries[0]["memberof"]["count"] = 0;
                    }
                    $entries[0]["memberof"]["count"]++;
                }
            }
            
            return $entries;
        }
        return false;
    }
    
    /**
    * Find information about the users. Returned in a raw array format from AD
    * 
    * @param string $username The username to query
    * @param array $fields Array of parameters to query
    * @param bool $isGUID Is the username passed a GUID or a samAccountName
    * @return mixed
    */
    public function infoCollection($username, $fields = NULL, $isGUID = false)
    {
        if ($username === NULL) { return false; }
        if (!$this->adldap->getLdapBind()) { return false; }
        
        $info = $this->info($username, $fields, $isGUID);
        
        if ($info !== false) {
            $collection = new adLDAPUserCollection($info, $this->adldap);
            return $collection;
        }
        return false;
    }
    
    /**
    * Determine if a user is in a specific group
    * 
    * @param string $username The username to query
    * @param string $group The name of the group to check against
    * @param bool $recursive Check groups recursively
    * @param bool $isGUID Is the username passed a GUID or a samAccountName
    * @return bool
    */
    public function inGroup($username, $group, $recursive = NULL, $isGUID = false)
    {
        if ($username === NULL) { return false; }
        if ($group === NULL) { return false; }
        if (!$this->adldap->getLdapBind()) { return false; }
        if ($recursive === NULL) { $recursive = $this->adldap->getRecursiveGroups(); } // Use the default option if they haven't set it
        
        // Get a list of the groups
        $groups = $this->groups($username, $recursive, $isGUID);
        
        // Return true if the specified group is in the group list
        if (in_array($group, $groups)) { 
            return true; 
        }

        return false;
    }
    
    /**
    * Determine a user's password expiry date
    * 
    * @param string $username The username to query
    * @param book $isGUID Is the username passed a GUID or a samAccountName
    * @requires bcmath http://php.net/manual/en/book.bc.php
    * @return array
    */
    public function passwordExpiry($username, $isGUID = false) 
    {
        if ($username === NULL) { return "Missing compulsory field [username]"; }
        if (!$this->adldap->getLdapBind()) { return false; }
        if (!function_exists('bcmod')) { throw new adLDAPException("Missing function support [bcmod] http://php.net/manual/en/book.bc.php"); };
        
        $userInfo = $this->info($username, array("pwdlastset", "useraccountcontrol"), $isGUID);
        $pwdLastSet = $userInfo[0]['pwdlastset'][0];
        $status = array();
        
        if ($userInfo[0]['useraccountcontrol'][0] == '66048') {
            // Password does not expire
            return "Does not expire";
        }
        if ($pwdLastSet === '0') {
            // Password has already expired
            return "Password has expired";
        }
        
         // Password expiry in AD can be calculated from TWO values:
         //   - User's own pwdLastSet attribute: stores the last time the password was changed
         //   - Domain's maxPwdAge attribute: how long passwords last in the domain
         //
         // Although Microsoft chose to use a different base and unit for time measurements.
         // This function will convert them to Unix timestamps
         $sr = ldap_read($this->adldap->getLdapConnection(), $this->adldap->getBaseDn(), 'objectclass=*', array('maxPwdAge'));
         if (!$sr) {
             return false;
         }
         $info = ldap_get_entries($this->adldap->getLdapConnection(), $sr);
         $maxPwdAge = $info[0]['maxpwdage'][0];
         

         // See MSDN: http://msdn.microsoft.com/en-us/library/ms974598.aspx
         //
         // pwdLastSet contains the number of 100 nanosecond intervals since January 1, 1601 (UTC), 
         // stored in a 64 bit integer. 
         //
         // The number of seconds between this date and Unix epoch is 11644473600.
         //
         // maxPwdAge is stored as a large integer that represents the number of 100 nanosecond
         // intervals from the time the password was set before the password expires.
         //
         // We also need to scale this to seconds but also this value is a _negative_ quantity!
         //
         // If the low 32 bits of maxPwdAge are equal to 0 passwords do not expire
         //
         // Unfortunately the maths involved are too big for PHP integers, so I've had to require
         // BCMath functions to work with arbitrary precision numbers.
         if (bcmod($maxPwdAge, 4294967296) === '0') {
            return "Domain does not expire passwords";
        }
        
        // Add maxpwdage and pwdlastset and we get password expiration time in Microsoft's
        // time units.  Because maxpwd age is negative we need to subtract it.
        $pwdExpire = bcsub($pwdLastSet, $maxPwdAge);
    
        // Convert MS's time to Unix time
        $status['expiryts'] = bcsub(bcdiv($pwdExpire, '10000000'), '11644473600');
        $status['expiryformat'] = date('Y-m-d H:i:s', bcsub(bcdiv($pwdExpire, '10000000'), '11644473600'));
        
        return $status;
    }
    
    /**
    * Modify a user
    * 
    * @param string $username The username to query
    * @param array $attributes The attributes to modify.  Note if you set the enabled attribute you must not specify any other attributes
    * @param bool $isGUID Is the username passed a GUID or a samAccountName
    * @return bool
    */
    public function modify($username, $attributes, $isGUID = false)
    {
        if ($username === NULL) { return "Missing compulsory field [username]"; }
        if (array_key_exists("password", $attributes) && !$this->adldap->getUseSSL() && !$this->adldap->getUseTLS()) { 
            throw new adLDAPException('SSL/TLS must be configured on your webserver and enabled in the class to set passwords.');
        }

        // Find the dn of the user
        $userDn = $this->dn($username, $isGUID);
        if ($userDn === false) { 
            return false; 
        }
        
        // 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 && !array_key_exists("enabled", $attributes)){ 
            return false; 
        }
        
        // Set the account control attribute (only if specified)
        if (array_key_exists("enabled", $attributes)){
            if ($attributes["enabled"]){ 
                $controlOptions = array("NORMAL_ACCOUNT"); 
            }
            else { 
                $controlOptions = array("NORMAL_ACCOUNT", "ACCOUNTDISABLE"); 
            }
            $mod["userAccountControl"][0] = $this->accountControl($controlOptions);
        }

        // Do the update
        $result = @ldap_modify($this->adldap->getLdapConnection(), $userDn, $mod);
        if ($result == false) { 
            return false; 
        }
        
        return true;
    }
    
    /**
    * Disable a user account
    * 
    * @param string $username The username to disable
    * @param bool $isGUID Is the username passed a GUID or a samAccountName
    * @return bool
    */
    public function disable($username, $isGUID = false)
    {
        if ($username === NULL) { return "Missing compulsory field [username]"; }
        $attributes = array("enabled" => 0);
        $result = $this->modify($username, $attributes, $isGUID);
        if ($result == false) { return false; }
        
        return true;
    }
    
    /**
    * Enable a user account
    * 
    * @param string $username The username to enable
    * @param bool $isGUID Is the username passed a GUID or a samAccountName
    * @return bool
    */
    public function enable($username, $isGUID = false)
    {
        if ($username === NULL) { return "Missing compulsory field [username]"; }
        $attributes = array("enabled" => 1);
        $result = $this->modify($username, $attributes, $isGUID);
        if ($result == false) { return false; }
        
        return true;
    }
    
    /**
    * Set the password of a user - This must be performed over SSL
    * 
    * @param string $username The username to modify
    * @param string $password The new password
    * @param bool $isGUID Is the username passed a GUID or a samAccountName
    * @return bool
    */
    public function password($username, $password, $isGUID = false)
    {
        if ($username === NULL) { return false; }
        if ($password === NULL) { return false; }
        if (!$this->adldap->getLdapBind()) { return false; }
        if (!$this->adldap->getUseSSL() && !$this->adldap->getUseTLS()) { 
            throw new adLDAPException('SSL must be configured on your webserver and enabled in the class to set passwords.');
        }
        
        $userDn = $this->dn($username, $isGUID);
        if ($userDn === false) { 
            return false; 
        }
                
        $add=array();
        $add["unicodePwd"][0] = $this->encodePassword($password);
        
        $result = @ldap_mod_replace($this->adldap->getLdapConnection(), $userDn, $add);
        if ($result === false){
            $err = ldap_errno($this->adldap->getLdapConnection());
            if ($err) {
                $msg = 'Error ' . $err . ': ' . ldap_err2str($err) . '.';
                if($err == 53) {
                    $msg .= ' Your password might not match the password policy.';
                }
                throw new adLDAPException($msg);
            }
            else {
                return false;
            }
        }
        
        return true;
    }
    
    /**
    * Encode a password for transmission over LDAP
    *
    * @param string $password The password to encode
    * @return string
    */
    public function encodePassword($password)
    {
        $password="\"".$password."\"";
        $encoded="";
        for ($i=0; $i <strlen($password); $i++){ $encoded.="{$password{$i}}\000"; }
        return $encoded;
    }
     
    /**
    * Obtain the user's distinguished name based on their userid 
    * 
    * 
    * @param string $username The username
    * @param bool $isGUID Is the username passed a GUID or a samAccountName
    * @return string
    */
    public function dn($username, $isGUID=false)
    {
        $user = $this->info($username, array("cn"), $isGUID);
        if ($user[0]["dn"] === NULL) { 
            return false; 
        }
        $userDn = $user[0]["dn"];
        return $userDn;
    }
    
    /**
    * Return a list of all users in AD
    * 
    * @param bool $includeDescription Return a description of the user
    * @param string $search Search parameter
    * @param bool $sorted Sort the user accounts
    * @return array
    */
    public function all($includeDescription = false, $search = "*", $sorted = true)
    {
        if (!$this->adldap->getLdapBind()) { return false; }
        
        // Perform the search and grab all their details
        $filter = "(&(objectClass=user)(samaccounttype=" . adLDAP::ADLDAP_NORMAL_ACCOUNT .")(objectCategory=person)(cn=" . $search . "))";
        $fields = array("samaccountname","displayname");
        $sr = ldap_search($this->adldap->getLdapConnection(), $this->adldap->getBaseDn(), $filter, $fields);
        $entries = ldap_get_entries($this->adldap->getLdapConnection(), $sr);

        $usersArray = array();
        for ($i=0; $i<$entries["count"]; $i++){
            if ($includeDescription && strlen($entries[$i]["displayname"][0])>0){
                $usersArray[$entries[$i]["samaccountname"][0]] = $entries[$i]["displayname"][0];
            } elseif ($includeDescription){
                $usersArray[$entries[$i]["samaccountname"][0]] = $entries[$i]["samaccountname"][0];
            } else {
                array_push($usersArray, $entries[$i]["samaccountname"][0]);
            }
        }
        if ($sorted) { 
            asort($usersArray); 
        }
        return $usersArray;
    }
    
    /**
    * Converts a username (samAccountName) to a GUID
    * 
    * @param string $username The username to query
    * @return string
    */
    public function usernameToGuid($username) 
    {
        if (!$this->adldap->getLdapBind()){ return false; }
        if ($username === null){ return "Missing compulsory field [username]"; }
        
        $filter = "samaccountname=" . $username; 
        $fields = array("objectGUID"); 
        $sr = @ldap_search($this->adldap->getLdapConnection(), $this->adldap->getBaseDn(), $filter, $fields); 
        if (ldap_count_entries($this->adldap->getLdapConnection(), $sr) > 0) { 
            $entry = @ldap_first_entry($this->adldap->getLdapConnection(), $sr); 
            $guid = @ldap_get_values_len($this->adldap->getLdapConnection(), $entry, 'objectGUID'); 
            $strGUID = $this->adldap->utilities()->binaryToText($guid[0]);          
            return $strGUID; 
        }
        return false; 
    }
    
    /**
    * Return a list of all users in AD that have a specific value in a field
    *
    * @param bool $includeDescription Return a description of the user
    * @param string $searchField Field to search search for
    * @param string $searchFilter Value to search for in the specified field
    * @param bool $sorted Sort the user accounts
    * @return array
    */
    public function find($includeDescription = false, $searchField = false, $searchFilter = false, $sorted = true){
        if (!$this->adldap->getLdapBind()){ return false; }
          
        // Perform the search and grab all their details
        $searchParams = "";
        if ($searchField) {
            $searchParams = "(" . $searchField . "=" . $searchFilter . ")";
        }                           
        $filter = "(&(objectClass=user)(samaccounttype=" . adLDAP::ADLDAP_NORMAL_ACCOUNT .")(objectCategory=person)" . $searchParams . ")";
        $fields = array("samaccountname","displayname");
        $sr = ldap_search($this->adldap->getLdapConnection(), $this->adldap->getBaseDn(), $filter, $fields);
        $entries = ldap_get_entries($this->adldap->getLdapConnection(), $sr);

        $usersArray = array();
        for ($i=0; $i < $entries["count"]; $i++) {
            if ($includeDescription && strlen($entries[$i]["displayname"][0]) > 0) {
                $usersArray[$entries[$i]["samaccountname"][0]] = $entries[$i]["displayname"][0];
            }
            else if ($includeDescription) {
                $usersArray[$entries[$i]["samaccountname"][0]] = $entries[$i]["samaccountname"][0];
            }
            else {
                array_push($usersArray, $entries[$i]["samaccountname"][0]);
            }
        }
        if ($sorted){ 
          asort($usersArray); 
        }
        return ($usersArray);
    }
    
    /**
    * Move a user account to a different OU
    *
    * @param string $username The username to move (please be careful here!)
    * @param array $container The container or containers to move the user to (please be careful here!).
    * accepts containers in 1. parent 2. child order
    * @return array
    */
    public function move($username, $container) 
    {
        if (!$this->adldap->getLdapBind()) { return false; }
        if ($username === null) { return "Missing compulsory field [username]"; }
        if ($container === null) { return "Missing compulsory field [container]"; }
        if (!is_array($container)) { return "Container must be an array"; }
        
        $userInfo = $this->info($username, array("*"));
        $dn = $userInfo[0]['distinguishedname'][0];
        $newRDn = "cn=" . $username;
        $container = array_reverse($container);
        $newContainer = "ou=" . implode(",ou=",$container);
        $newBaseDn = strtolower($newContainer) . "," . $this->adldap->getBaseDn();
        $result = @ldap_rename($this->adldap->getLdapConnection(), $dn, $newRDn, $newBaseDn, true);
        if ($result !== true) {
            return false;
        }
        return true;
    }
    
    /**
    * Get the last logon time of any user as a Unix timestamp
    * 
    * @param string $username
    * @return long $unixTimestamp
    */
    public function getLastLogon($username) {
        if (!$this->adldap->getLdapBind()) { return false; }
        if ($username === null) { return "Missing compulsory field [username]"; }
        $userInfo = $this->info($username, array("lastLogonTimestamp"));
        $lastLogon = adLDAPUtils::convertWindowsTimeToUnixTime($userInfo[0]['lastLogonTimestamp'][0]);
        return $lastLogon;
    }
    
}
?>