adLDAP library upgraded to 3.3.1
[dokuwiki.git] / inc / adLDAP.php
blob94cd8a50d2b30b32bb4e6e207ac3062dfb9d2684
1 <?php
2 /**
3 * PHP LDAP CLASS FOR MANIPULATING ACTIVE DIRECTORY
4 * Version 3.3.1
6 * PHP Version 5 with SSL and LDAP support
8 * Written by Scott Barnett, Richard Hyland
9 * email: scott@wiggumworld.com, adldap@richardhyland.com
10 * http://adldap.sourceforge.net/
12 * Copyright (c) 2006-2009 Scott Barnett, Richard Hyland
14 * We'd appreciate any improvements or additions to be submitted back
15 * to benefit the entire community :)
17 * This library is free software; you can redistribute it and/or
18 * modify it under the terms of the GNU Lesser General Public
19 * License as published by the Free Software Foundation; either
20 * version 2.1 of the License.
22 * This library is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
25 * Lesser General Public License for more details.
27 * @category ToolsAndUtilities
28 * @package adLDAP
29 * @author Scott Barnett, Richard Hyland
30 * @copyright (c) 2006-2009 Scott Barnett, Richard Hyland
31 * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html LGPLv2.1
32 * @revision $Revision: 67 $
33 * @version 3.3.1
34 * @link http://adldap.sourceforge.net/
37 /**
38 * Define the different types of account in AD
40 define ('ADLDAP_NORMAL_ACCOUNT', 805306368);
41 define ('ADLDAP_WORKSTATION_TRUST', 805306369);
42 define ('ADLDAP_INTERDOMAIN_TRUST', 805306370);
43 define ('ADLDAP_SECURITY_GLOBAL_GROUP', 268435456);
44 define ('ADLDAP_DISTRIBUTION_GROUP', 268435457);
45 define ('ADLDAP_SECURITY_LOCAL_GROUP', 536870912);
46 define ('ADLDAP_DISTRIBUTION_LOCAL_GROUP', 536870913);
47 define ('ADLDAP_FOLDER', 'OU');
48 define ('ADLDAP_CONTAINER', 'CN');
50 /**
51 * Main adLDAP class
53 * Can be initialised using $adldap = new adLDAP();
55 * Something to keep in mind is that Active Directory is a permissions
56 * based directory. If you bind as a domain user, you can't fetch as
57 * much information on other users as you could as a domain admin.
59 * Before asking questions, please read the Documentation at
60 * http://adldap.sourceforge.net/wiki/doku.php?id=api
62 class adLDAP {
63 /**
64 * The account suffix for your domain, can be set when the class is invoked
66 * @var string
68 protected $_account_suffix = "@mydomain.local";
70 /**
71 * The base dn for your domain
73 * @var string
75 protected $_base_dn = "DC=mydomain,DC=local";
77 /**
78 * Array of domain controllers. Specifiy multiple controllers if you
79 * would like the class to balance the LDAP queries amongst multiple servers
81 * @var array
83 protected $_domain_controllers = array ("dc01.mydomain.local");
85 /**
86 * Optional account with higher privileges for searching
87 * This should be set to a domain admin account
89 * @var string
90 * @var string
92 protected $_ad_username=NULL;
93 protected $_ad_password=NULL;
95 /**
96 * AD does not return the primary group. http://support.microsoft.com/?kbid=321360
97 * This tweak will resolve the real primary group.
98 * Setting to false will fudge "Domain Users" and is much faster. Keep in mind though that if
99 * someone's primary group is NOT domain users, this is obviously going to mess up the results
101 * @var bool
103 protected $_real_primarygroup=true;
106 * Use SSL (LDAPS), your server needs to be setup, please see
107 * http://adldap.sourceforge.net/wiki/doku.php?id=ldap_over_ssl
109 * @var bool
111 protected $_use_ssl=false;
114 * Use TLS
115 * If you wish to use TLS you should ensure that $_use_ssl is set to false and vice-versa
117 * @var bool
119 protected $_use_tls=false;
122 * When querying group memberships, do it recursively
123 * eg. User Fred is a member of Group A, which is a member of Group B, which is a member of Group C
124 * user_ingroup("Fred","C") will returns true with this option turned on, false if turned off
126 * @var bool
128 protected $_recursive_groups=true;
130 // You should not need to edit anything below this line
131 //******************************************************************************************
134 * Connection and bind default variables
136 * @var mixed
137 * @var mixed
139 protected $_conn;
140 protected $_bind;
143 * Getters and Setters
147 * Set the account suffix
149 * @param string $_account_suffix
150 * @return void
152 public function set_account_suffix($_account_suffix)
154 $this->_account_suffix = $_account_suffix;
158 * Get the account suffix
160 * @return string
162 public function get_account_suffix()
164 return $this->_account_suffix;
168 * Set the domain controllers array
170 * @param array $_domain_controllers
171 * @return void
173 public function set_domain_controllers(array $_domain_controllers)
175 $this->_domain_controllers = $_domain_controllers;
179 * Get the list of domain controllers
181 * @return void
183 public function get_domain_controllers()
185 return $this->_domain_controllers;
189 * Set the username of an account with higher priviledges
191 * @param string $_ad_username
192 * @return void
194 public function set_ad_username($_ad_username)
196 $this->_ad_username = $_ad_username;
200 * Get the username of the account with higher priviledges
202 * This will throw an exception for security reasons
204 public function get_ad_username()
206 throw new adLDAPException('For security reasons you cannot access the domain administrator account details');
210 * Set the password of an account with higher priviledges
212 * @param string $_ad_password
213 * @return void
215 public function set_ad_password($_ad_password)
217 $this->_ad_password = $_ad_password;
221 * Get the password of the account with higher priviledges
223 * This will throw an exception for security reasons
225 public function get_ad_password()
227 throw new adLDAPException('For security reasons you cannot access the domain administrator account details');
231 * Set whether to detect the true primary group
233 * @param bool $_real_primary_group
234 * @return void
236 public function set_real_primarygroup($_real_primarygroup)
238 $this->_real_primarygroup = $_real_primarygroup;
242 * Get the real primary group setting
244 * @return bool
246 public function get_real_primarygroup()
248 return $this->_real_primarygroup;
252 * Set whether to use SSL
254 * @param bool $_use_ssl
255 * @return void
257 public function set_use_ssl($_use_ssl)
259 $this->_use_ssl = $_use_ssl;
263 * Get the SSL setting
265 * @return bool
267 public function get_use_ssl()
269 return $this->_use_ssl;
273 * Set whether to use TLS
275 * @param bool $_use_tls
276 * @return void
278 public function set_use_tls($_use_tls)
280 $this->_use_tls = $_use_tls;
284 * Get the TLS setting
286 * @return bool
288 public function get_use_tls()
290 return $this->_use_tls;
294 * Set whether to lookup recursive groups
296 * @param bool $_recursive_groups
297 * @return void
299 public function set_recursive_groups($_recursive_groups)
301 $this->_recursive_groups = $_recursive_groups;
305 * Get the recursive groups setting
307 * @return bool
309 public function get_recursive_groups()
311 return $this->_recursive_groups;
315 * Default Constructor
317 * Tries to bind to the AD domain over LDAP or LDAPs
319 * @param array $options Array of options to pass to the constructor
320 * @throws Exception - if unable to bind to Domain Controller
321 * @return bool
323 function __construct($options=array()){
324 // You can specifically overide any of the default configuration options setup above
325 if (count($options)>0){
326 if (array_key_exists("account_suffix",$options)){ $this->_account_suffix=$options["account_suffix"]; }
327 if (array_key_exists("base_dn",$options)){ $this->_base_dn=$options["base_dn"]; }
328 if (array_key_exists("domain_controllers",$options)){ $this->_domain_controllers=$options["domain_controllers"]; }
329 if (array_key_exists("ad_username",$options)){ $this->_ad_username=$options["ad_username"]; }
330 if (array_key_exists("ad_password",$options)){ $this->_ad_password=$options["ad_password"]; }
331 if (array_key_exists("real_primarygroup",$options)){ $this->_real_primarygroup=$options["real_primarygroup"]; }
332 if (array_key_exists("use_ssl",$options)){ $this->_use_ssl=$options["use_ssl"]; }
333 if (array_key_exists("use_tls",$options)){ $this->_use_tls=$options["use_tls"]; }
334 if (array_key_exists("recursive_groups",$options)){ $this->_recursive_groups=$options["recursive_groups"]; }
337 if ($this->ldap_supported() === false) {
338 throw new adLDAPException('No LDAP support for PHP. See: http://www.php.net/ldap');
341 return $this->connect();
345 * Default Destructor
347 * Closes the LDAP connection
349 * @return void
351 function __destruct(){ $this->close(); }
354 * Connects and Binds to the Domain Controller
356 * @return bool
358 public function connect() {
359 // Connect to the AD/LDAP server as the username/password
360 $dc=$this->random_controller();
361 if ($this->_use_ssl){
362 $this->_conn = ldap_connect("ldaps://".$dc, 636);
363 } else {
364 $this->_conn = ldap_connect($dc);
367 // Set some ldap options for talking to AD
368 ldap_set_option($this->_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
369 ldap_set_option($this->_conn, LDAP_OPT_REFERRALS, 0);
371 if ($this->_use_tls) {
372 ldap_start_tls($this->_conn);
375 // Bind as a domain admin if they've set it up
376 if ($this->_ad_username!=NULL && $this->_ad_password!=NULL){
377 $this->_bind = @ldap_bind($this->_conn,$this->_ad_username.$this->_account_suffix,$this->_ad_password);
378 if (!$this->_bind){
379 if ($this->_use_ssl && !$this->_use_tls){
380 // If you have problems troubleshooting, remove the @ character from the ldap_bind command above to get the actual error message
381 throw new adLDAPException('Bind to Active Directory failed. Either the LDAPs connection failed or the login credentials are incorrect. AD said: ' . $this->get_last_error());
382 } else {
383 throw new adLDAPException('Bind to Active Directory failed. Check the login credentials and/or server details. AD said: ' . $this->get_last_error());
388 if ($this->_base_dn == NULL) {
389 $this->_base_dn = $this->find_base_dn();
392 return (true);
396 * Closes the LDAP connection
398 * @return void
400 public function close() {
401 ldap_close ($this->_conn);
405 * Validate a user's login credentials
407 * @param string $username A user's AD username
408 * @param string $password A user's AD password
409 * @param bool optional $prevent_rebind
410 * @return bool
412 public function authenticate($username,$password,$prevent_rebind=false){
413 // Prevent null binding
414 if ($username===NULL || $password===NULL){ return (false); }
415 if (empty($username) || empty($password)){ return (false); }
417 // Bind as the user
418 $this->_bind = @ldap_bind($this->_conn,$username.$this->_account_suffix,$password);
419 if (!$this->_bind){ return (false); }
421 // Cnce we've checked their details, kick back into admin mode if we have it
422 if ($this->_ad_username!=NULL && !$prevent_rebind){
423 $this->_bind = @ldap_bind($this->_conn,$this->_ad_username.$this->_account_suffix,$this->_ad_password);
424 if (!$this->_bind){
425 // This should never happen in theory
426 throw new adLDAPException('Rebind to Active Directory failed. AD said: ' . $this->get_last_error());
430 return (true);
433 //*****************************************************************************************************************
434 // GROUP FUNCTIONS
437 * Add a group to a group
439 * @param string $parent The parent group name
440 * @param string $child The child group name
441 * @return bool
443 public function group_add_group($parent,$child){
445 // Find the parent group's dn
446 $parent_group=$this->group_info($parent,array("cn"));
447 if ($parent_group[0]["dn"]===NULL){ return (false); }
448 $parent_dn=$parent_group[0]["dn"];
450 // Find the child group's dn
451 $child_group=$this->group_info($child,array("cn"));
452 if ($child_group[0]["dn"]===NULL){ return (false); }
453 $child_dn=$child_group[0]["dn"];
455 $add=array();
456 $add["member"] = $child_dn;
458 $result=@ldap_mod_add($this->_conn,$parent_dn,$add);
459 if ($result==false){ return (false); }
460 return (true);
464 * Add a user to a group
466 * @param string $group The group to add the user to
467 * @param string $user The user to add to the group
468 * @param bool $isGUID Is the username passed a GUID or a samAccountName
469 * @return bool
471 public function group_add_user($group,$user,$isGUID=false){
472 // Adding a user is a bit fiddly, we need to get the full DN of the user
473 // and add it using the full DN of the group
475 // Find the user's dn
476 $user_dn=$this->user_dn($user,$isGUID);
477 if ($user_dn===false){ return (false); }
479 // Find the group's dn
480 $group_info=$this->group_info($group,array("cn"));
481 if ($group_info[0]["dn"]===NULL){ return (false); }
482 $group_dn=$group_info[0]["dn"];
484 $add=array();
485 $add["member"] = $user_dn;
487 $result=@ldap_mod_add($this->_conn,$group_dn,$add);
488 if ($result==false){ return (false); }
489 return (true);
493 * Add a contact to a group
495 * @param string $group The group to add the contact to
496 * @param string $contact_dn The DN of the contact to add
497 * @return bool
499 public function group_add_contact($group,$contact_dn){
500 // To add a contact we take the contact's DN
501 // and add it using the full DN of the group
503 // Find the group's dn
504 $group_info=$this->group_info($group,array("cn"));
505 if ($group_info[0]["dn"]===NULL){ return (false); }
506 $group_dn=$group_info[0]["dn"];
508 $add=array();
509 $add["member"] = $contact_dn;
511 $result=@ldap_mod_add($this->_conn,$group_dn,$add);
512 if ($result==false){ return (false); }
513 return (true);
517 * Create a group
519 * @param array $attributes Default attributes of the group
520 * @return bool
522 public function group_create($attributes){
523 if (!is_array($attributes)){ return ("Attributes must be an array"); }
524 if (!array_key_exists("group_name",$attributes)){ return ("Missing compulsory field [group_name]"); }
525 if (!array_key_exists("container",$attributes)){ return ("Missing compulsory field [container]"); }
526 if (!array_key_exists("description",$attributes)){ return ("Missing compulsory field [description]"); }
527 if (!is_array($attributes["container"])){ return ("Container attribute must be an array."); }
528 $attributes["container"]=array_reverse($attributes["container"]);
530 //$member_array = array();
531 //$member_array[0] = "cn=user1,cn=Users,dc=yourdomain,dc=com";
532 //$member_array[1] = "cn=administrator,cn=Users,dc=yourdomain,dc=com";
534 $add=array();
535 $add["cn"] = $attributes["group_name"];
536 $add["samaccountname"] = $attributes["group_name"];
537 $add["objectClass"] = "Group";
538 $add["description"] = $attributes["description"];
539 //$add["member"] = $member_array; UNTESTED
541 $container="OU=".implode(",OU=",$attributes["container"]);
542 $result=ldap_add($this->_conn,"CN=".$add["cn"].", ".$container.",".$this->_base_dn,$add);
543 if ($result!=true){ return (false); }
545 return (true);
549 * Remove a group from a group
551 * @param string $parent The parent group name
552 * @param string $child The child group name
553 * @return bool
555 public function group_del_group($parent,$child){
557 // Find the parent dn
558 $parent_group=$this->group_info($parent,array("cn"));
559 if ($parent_group[0]["dn"]===NULL){ return (false); }
560 $parent_dn=$parent_group[0]["dn"];
562 // Find the child dn
563 $child_group=$this->group_info($child,array("cn"));
564 if ($child_group[0]["dn"]===NULL){ return (false); }
565 $child_dn=$child_group[0]["dn"];
567 $del=array();
568 $del["member"] = $child_dn;
570 $result=@ldap_mod_del($this->_conn,$parent_dn,$del);
571 if ($result==false){ return (false); }
572 return (true);
576 * Remove a user from a group
578 * @param string $group The group to remove a user from
579 * @param string $user The AD user to remove from the group
580 * @param bool $isGUID Is the username passed a GUID or a samAccountName
581 * @return bool
583 public function group_del_user($group,$user,$isGUID=false){
585 // Find the parent dn
586 $group_info=$this->group_info($group,array("cn"));
587 if ($group_info[0]["dn"]===NULL){ return (false); }
588 $group_dn=$group_info[0]["dn"];
590 // Find the users dn
591 $user_dn=$this->user_dn($user,$isGUID);
592 if ($user_dn===false){ return (false); }
594 $del=array();
595 $del["member"] = $user_dn;
597 $result=@ldap_mod_del($this->_conn,$group_dn,$del);
598 if ($result==false){ return (false); }
599 return (true);
603 * Remove a contact from a group
605 * @param string $group The group to remove a user from
606 * @param string $contact_dn The DN of a contact to remove from the group
607 * @return bool
609 public function group_del_contact($group,$contact_dn){
611 // Find the parent dn
612 $group_info=$this->group_info($group,array("cn"));
613 if ($group_info[0]["dn"]===NULL){ return (false); }
614 $group_dn=$group_info[0]["dn"];
616 $del=array();
617 $del["member"] = $contact_dn;
619 $result=@ldap_mod_del($this->_conn,$group_dn,$del);
620 if ($result==false){ return (false); }
621 return (true);
625 * Return a list of groups in a group
627 * @param string $group The group to query
628 * @param bool $recursive Recursively get groups
629 * @return array
631 public function groups_in_group($group, $recursive = NULL){
632 if (!$this->_bind){ return (false); }
633 if ($recursive===NULL){ $recursive=$this->_recursive_groups; } // Use the default option if they haven't set it
635 // Search the directory for the members of a group
636 $info=$this->group_info($group,array("member","cn"));
637 $groups=$info[0]["member"];
638 if (!is_array($groups)) {
639 return (false);
642 $group_array=array();
644 for ($i=0; $i<$groups["count"]; $i++){
645 $filter="(&(objectCategory=group)(distinguishedName=".$this->ldap_slashes($groups[$i])."))";
646 $fields = array("samaccountname", "distinguishedname", "objectClass");
647 $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);
648 $entries = ldap_get_entries($this->_conn, $sr);
650 // not a person, look for a group
651 if ($entries['count'] == 0 && $recursive == true) {
652 $filter="(&(objectCategory=group)(distinguishedName=".$this->ldap_slashes($groups[$i])."))";
653 $fields = array("distinguishedname");
654 $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);
655 $entries = ldap_get_entries($this->_conn, $sr);
656 if (!isset($entries[0]['distinguishedname'][0])) {
657 continue;
659 $sub_groups = $this->groups_in_group($entries[0]['distinguishedname'][0], $recursive);
660 if (is_array($sub_groups)) {
661 $group_array = array_merge($group_array, $sub_groups);
662 $group_array = array_unique($group_array);
664 continue;
667 $group_array[] = $entries[0]['distinguishedname'][0];
669 return ($group_array);
673 * Return a list of members in a group
675 * @param string $group The group to query
676 * @param bool $recursive Recursively get group members
677 * @return array
679 public function group_members($group, $recursive = NULL){
680 if (!$this->_bind){ return (false); }
681 if ($recursive===NULL){ $recursive=$this->_recursive_groups; } // Use the default option if they haven't set it
682 // Search the directory for the members of a group
683 $info=$this->group_info($group,array("member","cn"));
684 $users=$info[0]["member"];
685 if (!is_array($users)) {
686 return (false);
689 $user_array=array();
691 for ($i=0; $i<$users["count"]; $i++){
692 $filter="(&(objectCategory=person)(distinguishedName=".$this->ldap_slashes($users[$i])."))";
693 $fields = array("samaccountname", "distinguishedname", "objectClass");
694 $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);
695 $entries = ldap_get_entries($this->_conn, $sr);
697 // not a person, look for a group
698 if ($entries['count'] == 0 && $recursive == true) {
699 $filter="(&(objectCategory=group)(distinguishedName=".$this->ldap_slashes($users[$i])."))";
700 $fields = array("samaccountname");
701 $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);
702 $entries = ldap_get_entries($this->_conn, $sr);
703 if (!isset($entries[0]['samaccountname'][0])) {
704 continue;
706 $sub_users = $this->group_members($entries[0]['samaccountname'][0], $recursive);
707 if (is_array($sub_users)) {
708 $user_array = array_merge($user_array, $sub_users);
709 $user_array = array_unique($user_array);
711 continue;
714 if ($entries[0]['samaccountname'][0] === NULL && $entries[0]['distinguishedname'][0] !== NULL) {
715 $user_array[] = $entries[0]['distinguishedname'][0];
717 elseif ($entries[0]['samaccountname'][0] !== NULL) {
718 $user_array[] = $entries[0]['samaccountname'][0];
721 return ($user_array);
725 * Group Information. Returns an array of information about a group.
726 * The group name is case sensitive
728 * @param string $group_name The group name to retrieve info about
729 * @param array $fields Fields to retrieve
730 * @return array
732 public function group_info($group_name,$fields=NULL){
733 if ($group_name===NULL){ return (false); }
734 if (!$this->_bind){ return (false); }
736 if (stristr($group_name, '+')) {
737 $group_name=stripslashes($group_name);
740 $filter="(&(objectCategory=group)(name=".$this->ldap_slashes($group_name)."))";
741 //echo ($filter."!!!<br>");
742 if ($fields===NULL){ $fields=array("member","memberof","cn","description","distinguishedname","objectcategory","samaccountname"); }
743 $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);
744 $entries = ldap_get_entries($this->_conn, $sr);
745 //print_r($entries);
746 return ($entries);
750 * Return a complete list of "groups in groups"
752 * @param string $group The group to get the list from
753 * @return array
755 public function recursive_groups($group){
756 if ($group===NULL){ return (false); }
758 $ret_groups=array();
760 $groups=$this->group_info($group,array("memberof"));
761 if (is_array($groups[0]["memberof"])) {
762 $groups=$groups[0]["memberof"];
764 if ($groups){
765 $group_names=$this->nice_names($groups);
766 $ret_groups=array_merge($ret_groups,$group_names); //final groups to return
768 foreach ($group_names as $id => $group_name){
769 $child_groups=$this->recursive_groups($group_name);
770 $ret_groups=array_merge($ret_groups,$child_groups);
775 return ($ret_groups);
779 * Returns a complete list of the groups in AD based on a SAM Account Type
781 * @param string $samaccounttype The account type to return
782 * @param bool $include_desc Whether to return a description
783 * @param string $search Search parameters
784 * @param bool $sorted Whether to sort the results
785 * @return array
787 public function search_groups($samaccounttype = ADLDAP_SECURITY_GLOBAL_GROUP, $include_desc = false, $search = "*", $sorted = true) {
788 if (!$this->_bind){ return (false); }
790 $filter = '(&(objectCategory=group)';
791 if ($samaccounttype !== null) {
792 $filter .= '(samaccounttype='. $samaccounttype .')';
794 $filter .= '(cn='.$search.'))';
795 // Perform the search and grab all their details
796 $fields=array("samaccountname","description");
797 $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);
798 $entries = ldap_get_entries($this->_conn, $sr);
800 $groups_array = array();
801 for ($i=0; $i<$entries["count"]; $i++){
802 if ($include_desc && strlen($entries[$i]["description"][0]) > 0 ){
803 $groups_array[ $entries[$i]["samaccountname"][0] ] = $entries[$i]["description"][0];
804 } elseif ($include_desc){
805 $groups_array[ $entries[$i]["samaccountname"][0] ] = $entries[$i]["samaccountname"][0];
806 } else {
807 array_push($groups_array, $entries[$i]["samaccountname"][0]);
810 if( $sorted ){ asort($groups_array); }
811 return ($groups_array);
815 * Returns a complete list of all groups in AD
817 * @param bool $include_desc Whether to return a description
818 * @param string $search Search parameters
819 * @param bool $sorted Whether to sort the results
820 * @return array
822 public function all_groups($include_desc = false, $search = "*", $sorted = true){
823 $groups_array = $this->search_groups(null, $include_desc, $search, $sorted);
824 return ($groups_array);
828 * Returns a complete list of security groups in AD
830 * @param bool $include_desc Whether to return a description
831 * @param string $search Search parameters
832 * @param bool $sorted Whether to sort the results
833 * @return array
835 public function all_security_groups($include_desc = false, $search = "*", $sorted = true){
836 $groups_array = $this->search_groups(ADLDAP_SECURITY_GLOBAL_GROUP, $include_desc, $search, $sorted);
837 return ($groups_array);
841 * Returns a complete list of distribution lists in AD
843 * @param bool $include_desc Whether to return a description
844 * @param string $search Search parameters
845 * @param bool $sorted Whether to sort the results
846 * @return array
848 public function all_distribution_groups($include_desc = false, $search = "*", $sorted = true){
849 $groups_array = $this->search_groups(ADLDAP_DISTRIBUTION_GROUP, $include_desc, $search, $sorted);
850 return ($groups_array);
853 //*****************************************************************************************************************
854 // USER FUNCTIONS
857 * Create a user
859 * If you specify a password here, this can only be performed over SSL
861 * @param array $attributes The attributes to set to the user account
862 * @return bool
864 public function user_create($attributes){
865 // Check for compulsory fields
866 if (!array_key_exists("username",$attributes)){ return ("Missing compulsory field [username]"); }
867 if (!array_key_exists("firstname",$attributes)){ return ("Missing compulsory field [firstname]"); }
868 if (!array_key_exists("surname",$attributes)){ return ("Missing compulsory field [surname]"); }
869 if (!array_key_exists("email",$attributes)){ return ("Missing compulsory field [email]"); }
870 if (!array_key_exists("container",$attributes)){ return ("Missing compulsory field [container]"); }
871 if (!is_array($attributes["container"])){ return ("Container attribute must be an array."); }
873 if (array_key_exists("password",$attributes) && (!$this->_use_ssl && !$this->_use_tls)){
874 throw new adLDAPException('SSL must be configured on your webserver and enabled in the class to set passwords.');
877 if (!array_key_exists("display_name",$attributes)){ $attributes["display_name"]=$attributes["firstname"]." ".$attributes["surname"]; }
879 // Translate the schema
880 $add=$this->adldap_schema($attributes);
882 // Additional stuff only used for adding accounts
883 $add["cn"][0]=$attributes["display_name"];
884 $add["samaccountname"][0]=$attributes["username"];
885 $add["objectclass"][0]="top";
886 $add["objectclass"][1]="person";
887 $add["objectclass"][2]="organizationalPerson";
888 $add["objectclass"][3]="user"; //person?
889 //$add["name"][0]=$attributes["firstname"]." ".$attributes["surname"];
891 // Set the account control attribute
892 $control_options=array("NORMAL_ACCOUNT");
893 if (!$attributes["enabled"]){ $control_options[]="ACCOUNTDISABLE"; }
894 $add["userAccountControl"][0]=$this->account_control($control_options);
895 //echo ("<pre>"); print_r($add);
897 // Determine the container
898 $attributes["container"]=array_reverse($attributes["container"]);
899 $container="OU=".implode(",OU=",$attributes["container"]);
901 // Add the entry
902 $result=@ldap_add($this->_conn, "CN=".$add["cn"][0].", ".$container.",".$this->_base_dn, $add);
903 if ($result!=true){ return (false); }
905 return (true);
909 * Delete a user account
911 * @param string $username The username to delete (please be careful here!)
912 * @param bool $isGUID Is the username a GUID or a samAccountName
913 * @return array
915 public function user_delete($username,$isGUID=false) {
916 $userinfo = $this->user_info($username, array("*"),$isGUID);
917 $dn = $userinfo[0]['distinguishedname'][0];
918 $result=$this->dn_delete($dn);
919 if ($result!=true){ return (false); }
920 return (true);
924 * Groups the user is a member of
926 * @param string $username The username to query
927 * @param bool $recursive Recursive list of groups
928 * @param bool $isGUID Is the username passed a GUID or a samAccountName
929 * @return array
931 public function user_groups($username,$recursive=NULL,$isGUID=false){
932 if ($username===NULL){ return (false); }
933 if ($recursive===NULL){ $recursive=$this->_recursive_groups; } // Use the default option if they haven't set it
934 if (!$this->_bind){ return (false); }
936 // Search the directory for their information
937 $info=@$this->user_info($username,array("memberof","primarygroupid"),$isGUID);
938 $groups=$this->nice_names($info[0]["memberof"]); // Presuming the entry returned is our guy (unique usernames)
940 if ($recursive === true){
941 foreach ($groups as $id => $group_name){
942 $extra_groups=$this->recursive_groups($group_name);
943 $groups=array_merge($groups,$extra_groups);
947 return ($groups);
951 * Find information about the users
953 * @param string $username The username to query
954 * @param array $fields Array of parameters to query
955 * @param bool $isGUID Is the username passed a GUID or a samAccountName
956 * @return array
958 public function user_info($username,$fields=NULL,$isGUID=false){
959 if ($username===NULL){ return (false); }
960 if (!$this->_bind){ return (false); }
962 if ($isGUID === true) {
963 $username = $this->strguid2hex($username);
964 $filter="objectguid=".$username;
966 else {
967 $filter="samaccountname=".$username;
969 if ($fields===NULL){ $fields=array("samaccountname","mail","memberof","department","displayname","telephonenumber","primarygroupid","objectsid"); }
970 $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);
971 $entries = ldap_get_entries($this->_conn, $sr);
973 if ($entries[0]['count'] >= 1) {
974 // AD does not return the primary group in the ldap query, we may need to fudge it
975 if ($this->_real_primarygroup && isset($entries[0]["primarygroupid"][0]) && isset($entries[0]["objectsid"][0])){
976 //$entries[0]["memberof"][]=$this->group_cn($entries[0]["primarygroupid"][0]);
977 $entries[0]["memberof"][]=$this->get_primary_group($entries[0]["primarygroupid"][0], $entries[0]["objectsid"][0]);
978 } else {
979 $entries[0]["memberof"][]="CN=Domain Users,CN=Users,".$this->_base_dn;
983 $entries[0]["memberof"]["count"]++;
984 return ($entries);
988 * Determine if a user is in a specific group
990 * @param string $username The username to query
991 * @param string $group The name of the group to check against
992 * @param bool $recursive Check groups recursively
993 * @param bool $isGUID Is the username passed a GUID or a samAccountName
994 * @return bool
996 public function user_ingroup($username,$group,$recursive=NULL,$isGUID=false){
997 if ($username===NULL){ return (false); }
998 if ($group===NULL){ return (false); }
999 if (!$this->_bind){ return (false); }
1000 if ($recursive===NULL){ $recursive=$this->_recursive_groups; } // Use the default option if they haven't set it
1002 // Get a list of the groups
1003 $groups=$this->user_groups($username,$recursive,$isGUID);
1005 // Return true if the specified group is in the group list
1006 if (in_array($group,$groups)){ return (true); }
1008 return (false);
1012 * Determine a user's password expiry date
1014 * @param string $username The username to query
1015 * @param book $isGUID Is the username passed a GUID or a samAccountName
1016 * @requires bcmath http://www.php.net/manual/en/book.bc.php
1017 * @return array
1019 public function user_password_expiry($username,$isGUID=false) {
1020 if ($username===NULL){ return ("Missing compulsory field [username]"); }
1021 if (!$this->_bind){ return (false); }
1022 if (!function_exists('bcmod')) { return ("Missing function support [bcmod] http://www.php.net/manual/en/book.bc.php"); };
1024 $userinfo = $this->user_info($username, array("pwdlastset", "useraccountcontrol"), $isGUID);
1025 $pwdlastset = $userinfo[0]['pwdlastset'][0];
1026 $status = array();
1028 if ($userinfo[0]['useraccountcontrol'][0] == '66048') {
1029 // Password does not expire
1030 return "Does not expire";
1032 if ($pwdlastset === '0') {
1033 // Password has already expired
1034 return "Password has expired";
1037 // Password expiry in AD can be calculated from TWO values:
1038 // - User's own pwdLastSet attribute: stores the last time the password was changed
1039 // - Domain's maxPwdAge attribute: how long passwords last in the domain
1041 // Although Microsoft chose to use a different base and unit for time measurements.
1042 // This function will convert them to Unix timestamps
1043 $sr = ldap_read($this->_conn, $this->_base_dn, 'objectclass=*', array('maxPwdAge'));
1044 if (!$sr) {
1045 return false;
1047 $info = ldap_get_entries($this->_conn, $sr);
1048 $maxpwdage = $info[0]['maxpwdage'][0];
1051 // See MSDN: http://msdn.microsoft.com/en-us/library/ms974598.aspx
1053 // pwdLastSet contains the number of 100 nanosecond intervals since January 1, 1601 (UTC),
1054 // stored in a 64 bit integer.
1056 // The number of seconds between this date and Unix epoch is 11644473600.
1058 // maxPwdAge is stored as a large integer that represents the number of 100 nanosecond
1059 // intervals from the time the password was set before the password expires.
1061 // We also need to scale this to seconds but also this value is a _negative_ quantity!
1063 // If the low 32 bits of maxPwdAge are equal to 0 passwords do not expire
1065 // Unfortunately the maths involved are too big for PHP integers, so I've had to require
1066 // BCMath functions to work with arbitrary precision numbers.
1067 if (bcmod($maxpwdage, 4294967296) === '0') {
1068 return "Domain does not expire passwords";
1071 // Add maxpwdage and pwdlastset and we get password expiration time in Microsoft's
1072 // time units. Because maxpwd age is negative we need to subtract it.
1073 $pwdexpire = bcsub($pwdlastset, $maxpwdage);
1075 // Convert MS's time to Unix time
1076 $status['expiryts'] = bcsub(bcdiv($pwdexpire, '10000000'), '11644473600');
1077 $status['expiryformat'] = date('Y-m-d H:i:s', bcsub(bcdiv($pwdexpire, '10000000'), '11644473600'));
1079 return $status;
1083 * Modify a user
1085 * @param string $username The username to query
1086 * @param array $attributes The attributes to modify. Note if you set the enabled attribute you must not specify any other attributes
1087 * @param bool $isGUID Is the username passed a GUID or a samAccountName
1088 * @return bool
1090 public function user_modify($username,$attributes,$isGUID=false){
1091 if ($username===NULL){ return ("Missing compulsory field [username]"); }
1092 if (array_key_exists("password",$attributes) && !$this->_use_ssl){
1093 throw new adLDAPException('SSL must be configured on your webserver and enabled in the class to set passwords.');
1096 // Find the dn of the user
1097 $user_dn=$this->user_dn($username,$isGUID);
1098 if ($user_dn===false){ return (false); }
1100 // Translate the update to the LDAP schema
1101 $mod=$this->adldap_schema($attributes);
1103 // Check to see if this is an enabled status update
1104 if (!$mod && !array_key_exists("enabled", $attributes)){ return (false); }
1106 // Set the account control attribute (only if specified)
1107 if (array_key_exists("enabled",$attributes)){
1108 if ($attributes["enabled"]){ $control_options=array("NORMAL_ACCOUNT"); }
1109 else { $control_options=array("NORMAL_ACCOUNT","ACCOUNTDISABLE"); }
1110 $mod["userAccountControl"][0]=$this->account_control($control_options);
1113 // Do the update
1114 $result=@ldap_modify($this->_conn,$user_dn,$mod);
1115 if ($result==false){ return (false); }
1117 return (true);
1121 * Disable a user account
1123 * @param string $username The username to disable
1124 * @param bool $isGUID Is the username passed a GUID or a samAccountName
1125 * @return bool
1127 public function user_disable($username,$isGUID=false){
1128 if ($username===NULL){ return ("Missing compulsory field [username]"); }
1129 $attributes=array("enabled"=>0);
1130 $result = $this->user_modify($username, $attributes, $isGUID);
1131 if ($result==false){ return (false); }
1133 return (true);
1137 * Enable a user account
1139 * @param string $username The username to enable
1140 * @param bool $isGUID Is the username passed a GUID or a samAccountName
1141 * @return bool
1143 public function user_enable($username,$isGUID=false){
1144 if ($username===NULL){ return ("Missing compulsory field [username]"); }
1145 $attributes=array("enabled"=>1);
1146 $result = $this->user_modify($username, $attributes, $isGUID);
1147 if ($result==false){ return (false); }
1149 return (true);
1153 * Set the password of a user - This must be performed over SSL
1155 * @param string $username The username to modify
1156 * @param string $password The new password
1157 * @param bool $isGUID Is the username passed a GUID or a samAccountName
1158 * @return bool
1160 public function user_password($username,$password,$isGUID=false){
1161 if ($username===NULL){ return (false); }
1162 if ($password===NULL){ return (false); }
1163 if (!$this->_bind){ return (false); }
1164 if (!$this->_use_ssl && !$this->_use_tls){
1165 throw new adLDAPException('SSL must be configured on your webserver and enabled in the class to set passwords.');
1168 $user_dn=$this->user_dn($username,$isGUID);
1169 if ($user_dn===false){ return (false); }
1171 $add=array();
1172 $add["unicodePwd"][0]=$this->encode_password($password);
1174 $result=ldap_mod_replace($this->_conn,$user_dn,$add);
1175 if ($result==false){ return (false); }
1177 return (true);
1181 * Return a list of all users in AD
1183 * @param bool $include_desc Return a description of the user
1184 * @param string $search Search parameter
1185 * @param bool $sorted Sort the user accounts
1186 * @return array
1188 public function all_users($include_desc = false, $search = "*", $sorted = true){
1189 if (!$this->_bind){ return (false); }
1191 // Perform the search and grab all their details
1192 $filter = "(&(objectClass=user)(samaccounttype=". ADLDAP_NORMAL_ACCOUNT .")(objectCategory=person)(cn=".$search."))";
1193 $fields=array("samaccountname","displayname");
1194 $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);
1195 $entries = ldap_get_entries($this->_conn, $sr);
1197 $users_array = array();
1198 for ($i=0; $i<$entries["count"]; $i++){
1199 if ($include_desc && strlen($entries[$i]["displayname"][0])>0){
1200 $users_array[ $entries[$i]["samaccountname"][0] ] = $entries[$i]["displayname"][0];
1201 } elseif ($include_desc){
1202 $users_array[ $entries[$i]["samaccountname"][0] ] = $entries[$i]["samaccountname"][0];
1203 } else {
1204 array_push($users_array, $entries[$i]["samaccountname"][0]);
1207 if ($sorted){ asort($users_array); }
1208 return ($users_array);
1212 * Converts a username (samAccountName) to a GUID
1214 * @param string $username The username to query
1215 * @return string
1217 public function username2guid($username) {
1218 if (!$this->_bind){ return (false); }
1219 if ($username === null){ return ("Missing compulsory field [username]"); }
1221 $filter = "samaccountname=" . $username;
1222 $fields = array("objectGUID");
1223 $sr = @ldap_search($this->_conn, $this->_base_dn, $filter, $fields);
1224 if (ldap_count_entries($this->_conn, $sr) > 0) {
1225 $entry = @ldap_first_entry($this->_conn, $sr);
1226 $guid = @ldap_get_values_len($this->_conn, $entry, 'objectGUID');
1227 $strGUID = $this->binary2text($guid[0]);
1228 return ($strGUID);
1230 else {
1231 return (false);
1235 //*****************************************************************************************************************
1236 // CONTACT FUNCTIONS
1237 // * Still work to do in this area, and new functions to write
1240 * Create a contact
1242 * @param array $attributes The attributes to set to the contact
1243 * @return bool
1245 public function contact_create($attributes){
1246 // Check for compulsory fields
1247 if (!array_key_exists("display_name",$attributes)){ return ("Missing compulsory field [display_name]"); }
1248 if (!array_key_exists("email",$attributes)){ return ("Missing compulsory field [email]"); }
1249 if (!array_key_exists("container",$attributes)){ return ("Missing compulsory field [container]"); }
1250 if (!is_array($attributes["container"])){ return ("Container attribute must be an array."); }
1252 // Translate the schema
1253 $add=$this->adldap_schema($attributes);
1255 // Additional stuff only used for adding contacts
1256 $add["cn"][0]=$attributes["display_name"];
1257 $add["objectclass"][0]="top";
1258 $add["objectclass"][1]="person";
1259 $add["objectclass"][2]="organizationalPerson";
1260 $add["objectclass"][3]="contact";
1261 if (!isset($attributes['exchange_hidefromlists'])) {
1262 $add["msExchHideFromAddressLists"][0]="TRUE";
1265 // Determine the container
1266 $attributes["container"]=array_reverse($attributes["container"]);
1267 $container="OU=".implode(",OU=",$attributes["container"]);
1269 // Add the entry
1270 $result=@ldap_add($this->_conn, "CN=".$add["cn"][0].", ".$container.",".$this->_base_dn, $add);
1271 if ($result!=true){ return (false); }
1273 return (true);
1277 * Determine the list of groups a contact is a member of
1279 * @param string $distinguisedname The full DN of a contact
1280 * @param bool $recursive Recursively check groups
1281 * @return array
1283 public function contact_groups($distinguishedname,$recursive=NULL){
1284 if ($distinguishedname===NULL){ return (false); }
1285 if ($recursive===NULL){ $recursive=$this->_recursive_groups; } //use the default option if they haven't set it
1286 if (!$this->_bind){ return (false); }
1288 // Search the directory for their information
1289 $info=@$this->contact_info($distinguishedname,array("memberof","primarygroupid"));
1290 $groups=$this->nice_names($info[0]["memberof"]); //presuming the entry returned is our contact
1292 if ($recursive === true){
1293 foreach ($groups as $id => $group_name){
1294 $extra_groups=$this->recursive_groups($group_name);
1295 $groups=array_merge($groups,$extra_groups);
1299 return ($groups);
1303 * Get contact information
1305 * @param string $distinguisedname The full DN of a contact
1306 * @param array $fields Attributes to be returned
1307 * @return array
1309 public function contact_info($distinguishedname,$fields=NULL){
1310 if ($distinguishedname===NULL){ return (false); }
1311 if (!$this->_bind){ return (false); }
1313 $filter="distinguishedName=".$distinguishedname;
1314 if ($fields===NULL){ $fields=array("distinguishedname","mail","memberof","department","displayname","telephonenumber","primarygroupid","objectsid"); }
1315 $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);
1316 $entries = ldap_get_entries($this->_conn, $sr);
1318 if ($entries[0]['count'] >= 1) {
1319 // AD does not return the primary group in the ldap query, we may need to fudge it
1320 if ($this->_real_primarygroup && isset($entries[0]["primarygroupid"][0]) && isset($entries[0]["primarygroupid"][0])){
1321 //$entries[0]["memberof"][]=$this->group_cn($entries[0]["primarygroupid"][0]);
1322 $entries[0]["memberof"][]=$this->get_primary_group($entries[0]["primarygroupid"][0], $entries[0]["objectsid"][0]);
1323 } else {
1324 $entries[0]["memberof"][]="CN=Domain Users,CN=Users,".$this->_base_dn;
1328 $entries[0]["memberof"]["count"]++;
1329 return ($entries);
1333 * Determine if a contact is a member of a group
1335 * @param string $distinguisedname The full DN of a contact
1336 * @param string $group The group name to query
1337 * @param bool $recursive Recursively check groups
1338 * @return bool
1340 public function contact_ingroup($distinguisedname,$group,$recursive=NULL){
1341 if ($distinguisedname===NULL){ return (false); }
1342 if ($group===NULL){ return (false); }
1343 if (!$this->_bind){ return (false); }
1344 if ($recursive===NULL){ $recursive=$this->_recursive_groups; } //use the default option if they haven't set it
1346 // Get a list of the groups
1347 $groups=$this->contact_groups($distinguisedname,array("memberof"),$recursive);
1349 // Return true if the specified group is in the group list
1350 if (in_array($group,$groups)){ return (true); }
1352 return (false);
1356 * Modify a contact
1358 * @param string $distinguishedname The contact to query
1359 * @param array $attributes The attributes to modify. Note if you set the enabled attribute you must not specify any other attributes
1360 * @return bool
1362 public function contact_modify($distinguishedname,$attributes){
1363 if ($distinguishedname===NULL){ return ("Missing compulsory field [distinguishedname]"); }
1365 // Translate the update to the LDAP schema
1366 $mod=$this->adldap_schema($attributes);
1368 // Check to see if this is an enabled status update
1369 if (!$mod){ return (false); }
1371 // Do the update
1372 $result=ldap_modify($this->_conn,$distinguishedname,$mod);
1373 if ($result==false){ return (false); }
1375 return (true);
1379 * Delete a contact
1381 * @param string $distinguishedname The contact dn to delete (please be careful here!)
1382 * @return array
1384 public function contact_delete($distinguishedname) {
1385 $result = $this->dn_delete($distinguishedname);
1386 if ($result!=true){ return (false); }
1387 return (true);
1391 * Return a list of all contacts
1393 * @param bool $include_desc Include a description of a contact
1394 * @param string $search The search parameters
1395 * @param bool $sorted Whether to sort the results
1396 * @return array
1398 public function all_contacts($include_desc = false, $search = "*", $sorted = true){
1399 if (!$this->_bind){ return (false); }
1401 // Perform the search and grab all their details
1402 $filter = "(&(objectClass=contact)(cn=".$search."))";
1403 $fields=array("displayname","distinguishedname");
1404 $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);
1405 $entries = ldap_get_entries($this->_conn, $sr);
1407 $users_array = array();
1408 for ($i=0; $i<$entries["count"]; $i++){
1409 if ($include_desc && strlen($entries[$i]["displayname"][0])>0){
1410 $users_array[ $entries[$i]["distinguishedname"][0] ] = $entries[$i]["displayname"][0];
1411 } elseif ($include_desc){
1412 $users_array[ $entries[$i]["distinguishedname"][0] ] = $entries[$i]["distinguishedname"][0];
1413 } else {
1414 array_push($users_array, $entries[$i]["distinguishedname"][0]);
1417 if ($sorted){ asort($users_array); }
1418 return ($users_array);
1421 //*****************************************************************************************************************
1422 // FOLDER FUNCTIONS
1425 * Returns a folder listing for a specific OU
1426 * See http://adldap.sourceforge.net/wiki/doku.php?id=api_folder_functions
1428 * @param array $folder_name An array to the OU you wish to list.
1429 * If set to NULL will list the root, strongly recommended to set
1430 * $recursive to false in that instance!
1431 * @param string $dn_type The type of record to list. This can be ADLDAP_FOLDER or ADLDAP_CONTAINER.
1432 * @param bool $recursive Recursively search sub folders
1433 * @param bool $type Specify a type of object to search for
1434 * @return array
1436 public function folder_list($folder_name = NULL, $dn_type = ADLDAP_FOLDER, $recursive = NULL, $type = NULL) {
1437 if ($recursive===NULL){ $recursive=$this->_recursive_groups; } //use the default option if they haven't set it
1438 if (!$this->_bind){ return (false); }
1440 $filter = '(&';
1441 if ($type !== NULL) {
1442 switch ($type) {
1443 case 'contact':
1444 $filter .= '(objectClass=contact)';
1445 break;
1446 case 'computer':
1447 $filter .= '(objectClass=computer)';
1448 break;
1449 case 'group':
1450 $filter .= '(objectClass=group)';
1451 break;
1452 case 'folder':
1453 $filter .= '(objectClass=organizationalUnit)';
1454 break;
1455 case 'container':
1456 $filter .= '(objectClass=container)';
1457 break;
1458 case 'domain':
1459 $filter .= '(objectClass=builtinDomain)';
1460 break;
1461 default:
1462 $filter .= '(objectClass=user)';
1463 break;
1466 else {
1467 $filter .= '(objectClass=*)';
1469 // If the folder name is null then we will search the root level of AD
1470 // This requires us to not have an OU= part, just the base_dn
1471 $searchou = $this->_base_dn;
1472 if (is_array($folder_name)) {
1473 $ou = $dn_type . "=".implode("," . $dn_type . "=",$folder_name);
1474 $filter .= '(!(distinguishedname=' . $ou . ',' . $this->_base_dn . ')))';
1475 $searchou = $ou . ',' . $this->_base_dn;
1477 else {
1478 $filter .= '(!(distinguishedname=' . $this->_base_dn . ')))';
1481 if ($recursive === true) {
1482 $sr=ldap_search($this->_conn, $searchou, $filter, array('objectclass', 'distinguishedname', 'samaccountname'));
1483 $entries = @ldap_get_entries($this->_conn, $sr);
1484 if (is_array($entries)) {
1485 return $entries;
1488 else {
1489 $sr=ldap_list($this->_conn, $searchou, $filter, array('objectclass', 'distinguishedname', 'samaccountname'));
1490 $entries = @ldap_get_entries($this->_conn, $sr);
1491 if (is_array($entries)) {
1492 return $entries;
1496 return false;
1499 //*****************************************************************************************************************
1500 // COMPUTER FUNCTIONS
1503 * Get information about a specific computer
1505 * @param string $computer_name The name of the computer
1506 * @param array $fields Attributes to return
1507 * @return array
1509 public function computer_info($computer_name,$fields=NULL){
1510 if ($computer_name===NULL){ return (false); }
1511 if (!$this->_bind){ return (false); }
1513 $filter="(&(objectClass=computer)(cn=".$computer_name."))";
1514 if ($fields===NULL){ $fields=array("memberof","cn","displayname","dnshostname","distinguishedname","objectcategory","operatingsystem","operatingsystemservicepack","operatingsystemversion"); }
1515 $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);
1516 $entries = ldap_get_entries($this->_conn, $sr);
1518 return ($entries);
1522 * Check if a computer is in a group
1524 * @param string $computer_name The name of the computer
1525 * @param string $group The group to check
1526 * @param bool $recursive Whether to check recursively
1527 * @return array
1529 public function computer_ingroup($computer_name,$group,$recursive=NULL){
1530 if ($computer_name===NULL){ return (false); }
1531 if ($group===NULL){ return (false); }
1532 if (!$this->_bind){ return (false); }
1533 if ($recursive===NULL){ $recursive=$this->_recursive_groups; } // use the default option if they haven't set it
1535 //get a list of the groups
1536 $groups=$this->computer_groups($computer_name,array("memberof"),$recursive);
1538 //return true if the specified group is in the group list
1539 if (in_array($group,$groups)){ return (true); }
1541 return (false);
1545 * Get the groups a computer is in
1547 * @param string $computer_name The name of the computer
1548 * @param bool $recursive Whether to check recursively
1549 * @return array
1551 public function computer_groups($computer_name,$recursive=NULL){
1552 if ($computer_name===NULL){ return (false); }
1553 if ($recursive===NULL){ $recursive=$this->_recursive_groups; } //use the default option if they haven't set it
1554 if (!$this->_bind){ return (false); }
1556 //search the directory for their information
1557 $info=@$this->computer_info($computer_name,array("memberof","primarygroupid"));
1558 $groups=$this->nice_names($info[0]["memberof"]); //presuming the entry returned is our guy (unique usernames)
1560 if ($recursive === true){
1561 foreach ($groups as $id => $group_name){
1562 $extra_groups=$this->recursive_groups($group_name);
1563 $groups=array_merge($groups,$extra_groups);
1567 return ($groups);
1570 //************************************************************************************************************
1571 // EXCHANGE FUNCTIONS
1574 * Create an Exchange account
1576 * @param string $username The username of the user to add the Exchange account to
1577 * @param array $storagegroup The mailbox, Exchange Storage Group, for the user account, this must be a full CN
1578 * If the storage group has a different base_dn to the adLDAP configuration, set it using $base_dn
1579 * @param string $emailaddress The primary email address to add to this user
1580 * @param string $mailnickname The mail nick name. If mail nickname is blank, the username will be used
1581 * @param bool $usedefaults Indicates whether the store should use the default quota, rather than the per-mailbox quota.
1582 * @param string $base_dn Specify an alternative base_dn for the Exchange storage group
1583 * @param bool $isGUID Is the username passed a GUID or a samAccountName
1584 * @return bool
1586 public function exchange_create_mailbox($username, $storagegroup, $emailaddress, $mailnickname=NULL, $usedefaults=TRUE, $base_dn=NULL, $isGUID=false){
1587 if ($username===NULL){ return ("Missing compulsory field [username]"); }
1588 if ($storagegroup===NULL){ return ("Missing compulsory array [storagegroup]"); }
1589 if (!is_array($storagegroup)){ return ("[storagegroup] must be an array"); }
1590 if ($emailaddress===NULL){ return ("Missing compulsory field [emailaddress]"); }
1592 if ($base_dn===NULL) {
1593 $base_dn = $this->_base_dn;
1596 $container="CN=".implode(",CN=",$storagegroup);
1598 if ($mailnickname===NULL) { $mailnickname=$username; }
1599 $mdbUseDefaults = $this->bool2str($usedefaults);
1601 $attributes = array(
1602 'exchange_homemdb'=>$container.",".$base_dn,
1603 'exchange_proxyaddress'=>'SMTP:' . $emailaddress,
1604 'exchange_mailnickname'=>$mailnickname,
1605 'exchange_usedefaults'=>$mdbUseDefaults
1607 $result = $this->user_modify($username,$attributes,$isGUID);
1608 if ($result==false){ return (false); }
1609 return (true);
1613 * Add an X400 address to Exchange
1614 * See http://tools.ietf.org/html/rfc1685 for more information.
1615 * An X400 Address looks similar to this X400:c=US;a= ;p=Domain;o=Organization;s=Doe;g=John;
1617 * @param string $username The username of the user to add the X400 to to
1618 * @param string $country Country
1619 * @param string $admd Administration Management Domain
1620 * @param string $pdmd Private Management Domain (often your AD domain)
1621 * @param string $org Organization
1622 * @param string $surname Surname
1623 * @param string $givenName Given name
1624 * @param bool $isGUID Is the username passed a GUID or a samAccountName
1625 * @return bool
1627 public function exchange_add_X400($username, $country, $admd, $pdmd, $org, $surname, $givenname, $isGUID=false) {
1628 if ($username===NULL){ return ("Missing compulsory field [username]"); }
1630 $proxyvalue = 'X400:';
1632 // Find the dn of the user
1633 $user=$this->user_info($username,array("cn","proxyaddresses"), $isGUID);
1634 if ($user[0]["dn"]===NULL){ return (false); }
1635 $user_dn=$user[0]["dn"];
1637 // We do not have to demote an email address from the default so we can just add the new proxy address
1638 $attributes['exchange_proxyaddress'] = $proxyvalue . 'c=' . $country . ';a=' . $admd . ';p=' . $pdmd . ';o=' . $org . ';s=' . $surname . ';g=' . $givenname . ';';
1640 // Translate the update to the LDAP schema
1641 $add=$this->adldap_schema($attributes);
1643 if (!$add){ return (false); }
1645 // Do the update
1646 // Take out the @ to see any errors, usually this error might occur because the address already
1647 // exists in the list of proxyAddresses
1648 $result=@ldap_mod_add($this->_conn,$user_dn,$add);
1649 if ($result==false){ return (false); }
1651 return (true);
1655 * Add an address to Exchange
1657 * @param string $username The username of the user to add the Exchange account to
1658 * @param string $emailaddress The email address to add to this user
1659 * @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
1660 * @param bool $isGUID Is the username passed a GUID or a samAccountName
1661 * @return bool
1663 public function exchange_add_address($username, $emailaddress, $default=FALSE, $isGUID=false) {
1664 if ($username===NULL){ return ("Missing compulsory field [username]"); }
1665 if ($emailaddress===NULL) { return ("Missing compulsory fields [emailaddress]"); }
1667 $proxyvalue = 'smtp:';
1668 if ($default === true) {
1669 $proxyvalue = 'SMTP:';
1672 // Find the dn of the user
1673 $user=$this->user_info($username,array("cn","proxyaddresses"),$isGUID);
1674 if ($user[0]["dn"]===NULL){ return (false); }
1675 $user_dn=$user[0]["dn"];
1677 // We need to scan existing proxy addresses and demote the default one
1678 if (is_array($user[0]["proxyaddresses"]) && $default===true) {
1679 $modaddresses = array();
1680 for ($i=0;$i<sizeof($user[0]['proxyaddresses']);$i++) {
1681 if (strstr($user[0]['proxyaddresses'][$i], 'SMTP:') !== false) {
1682 $user[0]['proxyaddresses'][$i] = str_replace('SMTP:', 'smtp:', $user[0]['proxyaddresses'][$i]);
1684 if ($user[0]['proxyaddresses'][$i] != '') {
1685 $modaddresses['proxyAddresses'][$i] = $user[0]['proxyaddresses'][$i];
1688 $modaddresses['proxyAddresses'][(sizeof($user[0]['proxyaddresses'])-1)] = 'SMTP:' . $emailaddress;
1690 $result=@ldap_mod_replace($this->_conn,$user_dn,$modaddresses);
1691 if ($result==false){ return (false); }
1693 return (true);
1695 else {
1696 // We do not have to demote an email address from the default so we can just add the new proxy address
1697 $attributes['exchange_proxyaddress'] = $proxyvalue . $emailaddress;
1699 // Translate the update to the LDAP schema
1700 $add=$this->adldap_schema($attributes);
1702 if (!$add){ return (false); }
1704 // Do the update
1705 // Take out the @ to see any errors, usually this error might occur because the address already
1706 // exists in the list of proxyAddresses
1707 $result=@ldap_mod_add($this->_conn,$user_dn,$add);
1708 if ($result==false){ return (false); }
1710 return (true);
1715 * Remove an address to Exchange
1716 * If you remove a default address the account will no longer have a default,
1717 * we recommend changing the default address first
1719 * @param string $username The username of the user to add the Exchange account to
1720 * @param string $emailaddress The email address to add to this user
1721 * @param bool $isGUID Is the username passed a GUID or a samAccountName
1722 * @return bool
1724 public function exchange_del_address($username, $emailaddress, $isGUID=false) {
1725 if ($username===NULL){ return ("Missing compulsory field [username]"); }
1726 if ($emailaddress===NULL) { return ("Missing compulsory fields [emailaddress]"); }
1728 // Find the dn of the user
1729 $user=$this->user_info($username,array("cn","proxyaddresses"),$isGUID);
1730 if ($user[0]["dn"]===NULL){ return (false); }
1731 $user_dn=$user[0]["dn"];
1733 if (is_array($user[0]["proxyaddresses"])) {
1734 $mod = array();
1735 for ($i=0;$i<sizeof($user[0]['proxyaddresses']);$i++) {
1736 if (strstr($user[0]['proxyaddresses'][$i], 'SMTP:') !== false && $user[0]['proxyaddresses'][$i] == 'SMTP:' . $emailaddress) {
1737 $mod['proxyAddresses'][0] = 'SMTP:' . $emailaddress;
1739 elseif (strstr($user[0]['proxyaddresses'][$i], 'smtp:') !== false && $user[0]['proxyaddresses'][$i] == 'smtp:' . $emailaddress) {
1740 $mod['proxyAddresses'][0] = 'smtp:' . $emailaddress;
1744 $result=@ldap_mod_del($this->_conn,$user_dn,$mod);
1745 if ($result==false){ return (false); }
1747 return (true);
1749 else {
1750 return (false);
1754 * Change the default address
1756 * @param string $username The username of the user to add the Exchange account to
1757 * @param string $emailaddress The email address to make default
1758 * @param bool $isGUID Is the username passed a GUID or a samAccountName
1759 * @return bool
1761 public function exchange_primary_address($username, $emailaddress, $isGUID=false) {
1762 if ($username===NULL){ return ("Missing compulsory field [username]"); }
1763 if ($emailaddress===NULL) { return ("Missing compulsory fields [emailaddress]"); }
1765 // Find the dn of the user
1766 $user=$this->user_info($username,array("cn","proxyaddresses"), $isGUID);
1767 if ($user[0]["dn"]===NULL){ return (false); }
1768 $user_dn=$user[0]["dn"];
1770 if (is_array($user[0]["proxyaddresses"])) {
1771 $modaddresses = array();
1772 for ($i=0;$i<sizeof($user[0]['proxyaddresses']);$i++) {
1773 if (strstr($user[0]['proxyaddresses'][$i], 'SMTP:') !== false) {
1774 $user[0]['proxyaddresses'][$i] = str_replace('SMTP:', 'smtp:', $user[0]['proxyaddresses'][$i]);
1776 if ($user[0]['proxyaddresses'][$i] == 'smtp:' . $emailaddress) {
1777 $user[0]['proxyaddresses'][$i] = str_replace('smtp:', 'SMTP:', $user[0]['proxyaddresses'][$i]);
1779 if ($user[0]['proxyaddresses'][$i] != '') {
1780 $modaddresses['proxyAddresses'][$i] = $user[0]['proxyaddresses'][$i];
1784 $result=@ldap_mod_replace($this->_conn,$user_dn,$modaddresses);
1785 if ($result==false){ return (false); }
1787 return (true);
1793 * Mail enable a contact
1794 * Allows email to be sent to them through Exchange
1796 * @param string $distinguishedname The contact to mail enable
1797 * @param string $emailaddress The email address to allow emails to be sent through
1798 * @param string $mailnickname The mailnickname for the contact in Exchange. If NULL this will be set to the display name
1799 * @return bool
1801 public function exchange_contact_mailenable($distinguishedname, $emailaddress, $mailnickname=NULL){
1802 if ($distinguishedname===NULL){ return ("Missing compulsory field [distinguishedname]"); }
1803 if ($emailaddress===NULL){ return ("Missing compulsory field [emailaddress]"); }
1805 if ($mailnickname !== NULL) {
1806 // Find the dn of the user
1807 $user=$this->contact_info($distinguishedname,array("cn","displayname"));
1808 if ($user[0]["displayname"]===NULL){ return (false); }
1809 $mailnickname = $user[0]['displayname'][0];
1812 $attributes = array("email"=>$emailaddress,"contact_email"=>"SMTP:" . $emailaddress,"exchange_proxyaddress"=>"SMTP:" . $emailaddress,"exchange_mailnickname"=>$mailnickname);
1814 // Translate the update to the LDAP schema
1815 $mod=$this->adldap_schema($attributes);
1817 // Check to see if this is an enabled status update
1818 if (!$mod){ return (false); }
1820 // Do the update
1821 $result=ldap_modify($this->_conn,$distinguishedname,$mod);
1822 if ($result==false){ return (false); }
1824 return (true);
1828 * Returns a list of Exchange Servers in the ConfigurationNamingContext of the domain
1830 * @param array $attributes An array of the AD attributes you wish to return
1831 * @return array
1833 public function exchange_servers($attributes = array('cn','distinguishedname','serialnumber')) {
1834 if (!$this->_bind){ return (false); }
1836 $configurationNamingContext = $this->get_root_dse(array('configurationnamingcontext'));
1837 $sr = @ldap_search($this->_conn,$configurationNamingContext[0]['configurationnamingcontext'][0],'(&(objectCategory=msExchExchangeServer))',$attributes);
1838 $entries = @ldap_get_entries($this->_conn, $sr);
1839 return $entries;
1843 * Returns a list of Storage Groups in Exchange for a given mail server
1845 * @param string $exchangeServer The full DN of an Exchange server. You can use exchange_servers() to find the DN for your server
1846 * @param array $attributes An array of the AD attributes you wish to return
1847 * @param bool $recursive If enabled this will automatically query the databases within a storage group
1848 * @return array
1850 public function exchange_storage_groups($exchangeServer, $attributes = array('cn','distinguishedname'), $recursive = NULL) {
1851 if (!$this->_bind){ return (false); }
1852 if ($exchangeServer===NULL){ return ("Missing compulsory field [exchangeServer]"); }
1853 if ($recursive===NULL){ $recursive=$this->_recursive_groups; }
1855 $filter = '(&(objectCategory=msExchStorageGroup))';
1856 $sr=@ldap_search($this->_conn, $exchangeServer, $filter, $attributes);
1857 $entries = @ldap_get_entries($this->_conn, $sr);
1859 if ($recursive === true) {
1860 for ($i=0; $i<$entries['count']; $i++) {
1861 $entries[$i]['msexchprivatemdb'] = $this->exchange_storage_databases($entries[$i]['distinguishedname'][0]);
1865 return $entries;
1869 * Returns a list of Databases within any given storage group in Exchange for a given mail server
1871 * @param string $storageGroup The full DN of an Storage Group. You can use exchange_storage_groups() to find the DN
1872 * @param array $attributes An array of the AD attributes you wish to return
1873 * @return array
1875 public function exchange_storage_databases($storageGroup, $attributes = array('cn','distinguishedname','displayname')) {
1876 if (!$this->_bind){ return (false); }
1877 if ($storageGroup===NULL){ return ("Missing compulsory field [storageGroup]"); }
1879 $filter = '(&(objectCategory=msExchPrivateMDB))';
1880 $sr=@ldap_search($this->_conn, $storageGroup, $filter, $attributes);
1881 $entries = @ldap_get_entries($this->_conn, $sr);
1882 return $entries;
1885 //************************************************************************************************************
1886 // SERVER FUNCTIONS
1889 * Find the Base DN of your domain controller
1891 * @return string
1893 public function find_base_dn() {
1894 $namingContext = $this->get_root_dse(array('defaultnamingcontext'));
1895 return $namingContext[0]['defaultnamingcontext'][0];
1899 * Get the RootDSE properties from a domain controller
1901 * @param array $attributes The attributes you wish to query e.g. defaultnamingcontext
1902 * @return array
1904 public function get_root_dse($attributes = array("*", "+")) {
1905 if (!$this->_bind){ return (false); }
1907 $sr = @ldap_read($this->_conn, NULL, 'objectClass=*', $attributes);
1908 $entries = @ldap_get_entries($this->_conn, $sr);
1909 return $entries;
1912 //************************************************************************************************************
1913 // UTILITY FUNCTIONS (Many of these functions are protected and can only be called from within the class)
1916 * Get last error from Active Directory
1918 * This function gets the last message from Active Directory
1919 * This may indeed be a 'Success' message but if you get an unknown error
1920 * it might be worth calling this function to see what errors were raised
1922 * return string
1924 public function get_last_error() {
1925 return @ldap_error($this->_conn);
1929 * Detect LDAP support in php
1931 * @return bool
1933 protected function ldap_supported() {
1934 if (!function_exists('ldap_connect')) {
1935 return (false);
1937 return (true);
1941 * Schema
1943 * @param array $attributes Attributes to be queried
1944 * @return array
1946 protected function adldap_schema($attributes){
1948 // LDAP doesn't like NULL attributes, only set them if they have values
1949 // If you wish to remove an attribute you should set it to a space
1950 // TO DO: Adapt user_modify to use ldap_mod_delete to remove a NULL attribute
1951 $mod=array();
1953 // Check every attribute to see if it contains 8bit characters and then UTF8 encode them
1954 array_walk($attributes, array($this, 'encode8bit'));
1956 if ($attributes["address_city"]){ $mod["l"][0]=$attributes["address_city"]; }
1957 if ($attributes["address_code"]){ $mod["postalCode"][0]=$attributes["address_code"]; }
1958 //if ($attributes["address_country"]){ $mod["countryCode"][0]=$attributes["address_country"]; } // use country codes?
1959 if ($attributes["address_country"]){ $mod["c"][0]=$attributes["address_country"]; }
1960 if ($attributes["address_pobox"]){ $mod["postOfficeBox"][0]=$attributes["address_pobox"]; }
1961 if ($attributes["address_state"]){ $mod["st"][0]=$attributes["address_state"]; }
1962 if ($attributes["address_street"]){ $mod["streetAddress"][0]=$attributes["address_street"]; }
1963 if ($attributes["company"]){ $mod["company"][0]=$attributes["company"]; }
1964 if ($attributes["change_password"]){ $mod["pwdLastSet"][0]=0; }
1965 if ($attributes["department"]){ $mod["department"][0]=$attributes["department"]; }
1966 if ($attributes["description"]){ $mod["description"][0]=$attributes["description"]; }
1967 if ($attributes["display_name"]){ $mod["displayName"][0]=$attributes["display_name"]; }
1968 if ($attributes["email"]){ $mod["mail"][0]=$attributes["email"]; }
1969 if ($attributes["expires"]){ $mod["accountExpires"][0]=$attributes["expires"]; } //unix epoch format?
1970 if ($attributes["firstname"]){ $mod["givenName"][0]=$attributes["firstname"]; }
1971 if ($attributes["home_directory"]){ $mod["homeDirectory"][0]=$attributes["home_directory"]; }
1972 if ($attributes["home_drive"]){ $mod["homeDrive"][0]=$attributes["home_drive"]; }
1973 if ($attributes["initials"]){ $mod["initials"][0]=$attributes["initials"]; }
1974 if ($attributes["logon_name"]){ $mod["userPrincipalName"][0]=$attributes["logon_name"]; }
1975 if ($attributes["manager"]){ $mod["manager"][0]=$attributes["manager"]; } //UNTESTED ***Use DistinguishedName***
1976 if ($attributes["office"]){ $mod["physicalDeliveryOfficeName"][0]=$attributes["office"]; }
1977 if ($attributes["password"]){ $mod["unicodePwd"][0]=$this->encode_password($attributes["password"]); }
1978 if ($attributes["profile_path"]){ $mod["profilepath"][0]=$attributes["profile_path"]; }
1979 if ($attributes["script_path"]){ $mod["scriptPath"][0]=$attributes["script_path"]; }
1980 if ($attributes["surname"]){ $mod["sn"][0]=$attributes["surname"]; }
1981 if ($attributes["title"]){ $mod["title"][0]=$attributes["title"]; }
1982 if ($attributes["telephone"]){ $mod["telephoneNumber"][0]=$attributes["telephone"]; }
1983 if ($attributes["mobile"]){ $mod["mobile"][0]=$attributes["mobile"]; }
1984 if ($attributes["pager"]){ $mod["pager"][0]=$attributes["pager"]; }
1985 if ($attributes["ipphone"]){ $mod["ipphone"][0]=$attributes["ipphone"]; }
1986 if ($attributes["web_page"]){ $mod["wWWHomePage"][0]=$attributes["web_page"]; }
1987 if ($attributes["fax"]){ $mod["facsimileTelephoneNumber"][0]=$attributes["fax"]; }
1988 if ($attributes["enabled"]){ $mod["userAccountControl"][0]=$attributes["enabled"]; }
1990 // Distribution List specific schema
1991 if ($attributes["group_sendpermission"]){ $mod["dlMemSubmitPerms"][0]=$attributes["group_sendpermission"]; }
1992 if ($attributes["group_rejectpermission"]){ $mod["dlMemRejectPerms"][0]=$attributes["group_rejectpermission"]; }
1994 // Exchange Schema
1995 if ($attributes["exchange_homemdb"]){ $mod["homeMDB"][0]=$attributes["exchange_homemdb"]; }
1996 if ($attributes["exchange_mailnickname"]){ $mod["mailNickname"][0]=$attributes["exchange_mailnickname"]; }
1997 if ($attributes["exchange_proxyaddress"]){ $mod["proxyAddresses"][0]=$attributes["exchange_proxyaddress"]; }
1998 if ($attributes["exchange_usedefaults"]){ $mod["mDBUseDefaults"][0]=$attributes["exchange_usedefaults"]; }
1999 if ($attributes["exchange_policyexclude"]){ $mod["msExchPoliciesExcluded"][0]=$attributes["exchange_policyexclude"]; }
2000 if ($attributes["exchange_policyinclude"]){ $mod["msExchPoliciesIncluded"][0]=$attributes["exchange_policyinclude"]; }
2002 // This schema is designed for contacts
2003 if ($attributes["exchange_hidefromlists"]){ $mod["msExchHideFromAddressLists"][0]=$attributes["exchange_hidefromlists"]; }
2004 if ($attributes["contact_email"]){ $mod["targetAddress"][0]=$attributes["contact_email"]; }
2006 //echo ("<pre>"); print_r($mod);
2008 // modifying a name is a bit fiddly
2009 if ($attributes["firstname"] && $attributes["surname"]){
2010 $mod["cn"][0]=$attributes["firstname"]." ".$attributes["surname"];
2011 $mod["displayname"][0]=$attributes["firstname"]." ".$attributes["surname"];
2012 $mod["name"][0]=$attributes["firstname"]." ".$attributes["surname"];
2016 if (count($mod)==0){ return (false); }
2017 return ($mod);
2021 * Coping with AD not returning the primary group
2022 * http://support.microsoft.com/?kbid=321360
2024 * For some reason it's not possible to search on primarygrouptoken=XXX
2025 * If someone can show otherwise, I'd like to know about it :)
2026 * this way is resource intensive and generally a pain in the @#%^
2028 * @deprecated deprecated since version 3.1, see get get_primary_group
2029 * @param string $gid Group ID
2030 * @return string
2032 protected function group_cn($gid){
2033 if ($gid===NULL){ return (false); }
2034 $r=false;
2036 $filter="(&(objectCategory=group)(samaccounttype=". ADLDAP_SECURITY_GLOBAL_GROUP ."))";
2037 $fields=array("primarygrouptoken","samaccountname","distinguishedname");
2038 $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);
2039 $entries = ldap_get_entries($this->_conn, $sr);
2041 for ($i=0; $i<$entries["count"]; $i++){
2042 if ($entries[$i]["primarygrouptoken"][0]==$gid){
2043 $r=$entries[$i]["distinguishedname"][0];
2044 $i=$entries["count"];
2048 return ($r);
2052 * Coping with AD not returning the primary group
2053 * http://support.microsoft.com/?kbid=321360
2055 * This is a re-write based on code submitted by Bruce which prevents the
2056 * need to search each security group to find the true primary group
2058 * @param string $gid Group ID
2059 * @param string $usersid User's Object SID
2060 * @return string
2062 protected function get_primary_group($gid, $usersid){
2063 if ($gid===NULL || $usersid===NULL){ return (false); }
2064 $r=false;
2066 $gsid = substr_replace($usersid,pack('V',$gid),strlen($usersid)-4,4);
2067 $filter='(objectsid='.$this->getTextSID($gsid).')';
2068 $fields=array("samaccountname","distinguishedname");
2069 $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);
2070 $entries = ldap_get_entries($this->_conn, $sr);
2072 return $entries[0]['distinguishedname'][0];
2076 * Convert a binary SID to a text SID
2078 * @param string $binsid A Binary SID
2079 * @return string
2081 protected function getTextSID($binsid) {
2082 $hex_sid = bin2hex($binsid);
2083 $rev = hexdec(substr($hex_sid, 0, 2));
2084 $subcount = hexdec(substr($hex_sid, 2, 2));
2085 $auth = hexdec(substr($hex_sid, 4, 12));
2086 $result = "$rev-$auth";
2088 for ($x=0;$x < $subcount; $x++) {
2089 $subauth[$x] =
2090 hexdec($this->little_endian(substr($hex_sid, 16 + ($x * 8), 8)));
2091 $result .= "-" . $subauth[$x];
2094 // Cheat by tacking on the S-
2095 return 'S-' . $result;
2099 * Converts a little-endian hex number to one that hexdec() can convert
2101 * @param string $hex A hex code
2102 * @return string
2104 protected function little_endian($hex) {
2105 $result = '';
2106 for ($x = strlen($hex) - 2; $x >= 0; $x = $x - 2) {
2107 $result .= substr($hex, $x, 2);
2109 return $result;
2113 * Converts a binary attribute to a string
2115 * @param string $bin A binary LDAP attribute
2116 * @return string
2118 protected function binary2text($bin) {
2119 $hex_guid = bin2hex($bin);
2120 $hex_guid_to_guid_str = '';
2121 for($k = 1; $k <= 4; ++$k) {
2122 $hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
2124 $hex_guid_to_guid_str .= '-';
2125 for($k = 1; $k <= 2; ++$k) {
2126 $hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
2128 $hex_guid_to_guid_str .= '-';
2129 for($k = 1; $k <= 2; ++$k) {
2130 $hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
2132 $hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
2133 $hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);
2134 return strtoupper($hex_guid_to_guid_str);
2138 * Converts a binary GUID to a string GUID
2140 * @param string $binaryGuid The binary GUID attribute to convert
2141 * @return string
2143 public function decodeGuid($binaryGuid) {
2144 if ($binaryGuid === null){ return ("Missing compulsory field [binaryGuid]"); }
2146 $strGUID = $this->binary2text($binaryGuid);
2147 return ($strGUID);
2151 * Converts a string GUID to a hexdecimal value so it can be queried
2153 * @param string $strGUID A string representation of a GUID
2154 * @return string
2156 protected function strguid2hex($strGUID) {
2157 $strGUID = str_replace('-', '', $strGUID);
2159 $octet_str = '\\' . substr($strGUID, 6, 2);
2160 $octet_str .= '\\' . substr($strGUID, 4, 2);
2161 $octet_str .= '\\' . substr($strGUID, 2, 2);
2162 $octet_str .= '\\' . substr($strGUID, 0, 2);
2163 $octet_str .= '\\' . substr($strGUID, 10, 2);
2164 $octet_str .= '\\' . substr($strGUID, 8, 2);
2165 $octet_str .= '\\' . substr($strGUID, 14, 2);
2166 $octet_str .= '\\' . substr($strGUID, 12, 2);
2167 //$octet_str .= '\\' . substr($strGUID, 16, strlen($strGUID));
2168 for ($i=16; $i<=(strlen($strGUID)-2); $i++) {
2169 if (($i % 2) == 0) {
2170 $octet_str .= '\\' . substr($strGUID, $i, 2);
2174 return $octet_str;
2178 * Obtain the user's distinguished name based on their userid
2181 * @param string $username The username
2182 * @param bool $isGUID Is the username passed a GUID or a samAccountName
2183 * @return string
2185 protected function user_dn($username,$isGUID=false){
2186 $user=$this->user_info($username,array("cn"),$isGUID);
2187 if ($user[0]["dn"]===NULL){ return (false); }
2188 $user_dn=$user[0]["dn"];
2189 return ($user_dn);
2193 * Encode a password for transmission over LDAP
2195 * @param string $password The password to encode
2196 * @return string
2198 protected function encode_password($password){
2199 $password="\"".$password."\"";
2200 $encoded="";
2201 for ($i=0; $i <strlen($password); $i++){ $encoded.="{$password{$i}}\000"; }
2202 return ($encoded);
2206 * Escape strings for the use in LDAP filters
2208 * DEVELOPERS SHOULD BE DOING PROPER FILTERING IF THEY'RE ACCEPTING USER INPUT
2209 * Ported from Perl's Net::LDAP::Util escape_filter_value
2211 * @param string $str The string the parse
2212 * @author Port by Andreas Gohr <andi@splitbrain.org>
2213 * @return string
2215 protected function ldap_slashes($str){
2216 return preg_replace('/([\x00-\x1F\*\(\)\\\\])/e',
2217 '"\\\\\".join("",unpack("H2","$1"))',
2218 $str);
2222 * Select a random domain controller from your domain controller array
2224 * @return string
2226 protected function random_controller(){
2227 mt_srand(doubleval(microtime()) * 100000000); // For older PHP versions
2228 return ($this->_domain_controllers[array_rand($this->_domain_controllers)]);
2232 * Account control options
2234 * @param array $options The options to convert to int
2235 * @return int
2237 protected function account_control($options){
2238 $val=0;
2240 if (is_array($options)){
2241 if (in_array("SCRIPT",$options)){ $val=$val+1; }
2242 if (in_array("ACCOUNTDISABLE",$options)){ $val=$val+2; }
2243 if (in_array("HOMEDIR_REQUIRED",$options)){ $val=$val+8; }
2244 if (in_array("LOCKOUT",$options)){ $val=$val+16; }
2245 if (in_array("PASSWD_NOTREQD",$options)){ $val=$val+32; }
2246 //PASSWD_CANT_CHANGE Note You cannot assign this permission by directly modifying the UserAccountControl attribute.
2247 //For information about how to set the permission programmatically, see the "Property flag descriptions" section.
2248 if (in_array("ENCRYPTED_TEXT_PWD_ALLOWED",$options)){ $val=$val+128; }
2249 if (in_array("TEMP_DUPLICATE_ACCOUNT",$options)){ $val=$val+256; }
2250 if (in_array("NORMAL_ACCOUNT",$options)){ $val=$val+512; }
2251 if (in_array("INTERDOMAIN_TRUST_ACCOUNT",$options)){ $val=$val+2048; }
2252 if (in_array("WORKSTATION_TRUST_ACCOUNT",$options)){ $val=$val+4096; }
2253 if (in_array("SERVER_TRUST_ACCOUNT",$options)){ $val=$val+8192; }
2254 if (in_array("DONT_EXPIRE_PASSWORD",$options)){ $val=$val+65536; }
2255 if (in_array("MNS_LOGON_ACCOUNT",$options)){ $val=$val+131072; }
2256 if (in_array("SMARTCARD_REQUIRED",$options)){ $val=$val+262144; }
2257 if (in_array("TRUSTED_FOR_DELEGATION",$options)){ $val=$val+524288; }
2258 if (in_array("NOT_DELEGATED",$options)){ $val=$val+1048576; }
2259 if (in_array("USE_DES_KEY_ONLY",$options)){ $val=$val+2097152; }
2260 if (in_array("DONT_REQ_PREAUTH",$options)){ $val=$val+4194304; }
2261 if (in_array("PASSWORD_EXPIRED",$options)){ $val=$val+8388608; }
2262 if (in_array("TRUSTED_TO_AUTH_FOR_DELEGATION",$options)){ $val=$val+16777216; }
2264 return ($val);
2268 * Take an LDAP query and return the nice names, without all the LDAP prefixes (eg. CN, DN)
2270 * @param array $groups
2271 * @return array
2273 protected function nice_names($groups){
2275 $group_array=array();
2276 for ($i=0; $i<$groups["count"]; $i++){ // For each group
2277 $line=$groups[$i];
2279 if (strlen($line)>0){
2280 // More presumptions, they're all prefixed with CN=
2281 // so we ditch the first three characters and the group
2282 // name goes up to the first comma
2283 $bits=explode(",",$line);
2284 $group_array[]=substr($bits[0],3,(strlen($bits[0])-3));
2287 return ($group_array);
2291 * Delete a distinguished name from Active Directory
2292 * You should never need to call this yourself, just use the wrapper functions user_delete and contact_delete
2294 * @param string $dn The distinguished name to delete
2295 * @return bool
2297 protected function dn_delete($dn){
2298 $result=ldap_delete($this->_conn, $dn);
2299 if ($result!=true){ return (false); }
2300 return (true);
2304 * Convert a boolean value to a string
2305 * You should never need to call this yourself
2307 * @param bool $bool Boolean value
2308 * @return string
2310 protected function bool2str($bool) {
2311 return ($bool) ? 'TRUE' : 'FALSE';
2315 * Convert 8bit characters e.g. accented characters to UTF8 encoded characters
2317 protected function encode8bit(&$item, $key) {
2318 $encode = false;
2319 if (is_string($item)) {
2320 for ($i=0; $i<strlen($item); $i++) {
2321 if (ord($item[$i]) >> 7) {
2322 $encode = true;
2326 if ($encode === true && $key != 'password') {
2327 $item = utf8_encode($item);
2333 * adLDAP Exception Handler
2335 * Exceptions of this type are thrown on bind failure or when SSL is required but not configured
2336 * Example:
2337 * try {
2338 * $adldap = new adLDAP();
2340 * catch (adLDAPException $e) {
2341 * echo $e;
2342 * exit();
2345 class adLDAPException extends Exception {}