source: documentation/trunk/packages/dokuwiki-2011-05-25a/inc/adLDAP.php@ 25027

Last change on this file since 25027 was 25027, checked in by jmt12, 12 years ago

Adding the packages directory, and within it a configured version of dokuwiki all ready to run

File size: 91.9 KB
Line 
1<?php
2/**
3 * PHP LDAP CLASS FOR MANIPULATING ACTIVE DIRECTORY
4 * Version 3.3.2
5 *
6 * PHP Version 5 with SSL and LDAP support
7 *
8 * Written by Scott Barnett, Richard Hyland
9 * email: [email protected], [email protected]
10 * http://adldap.sourceforge.net/
11 *
12 * Copyright (c) 2006-2010 Scott Barnett, Richard Hyland
13 *
14 * We'd appreciate any improvements or additions to be submitted back
15 * to benefit the entire community :)
16 *
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.
21 *
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.
26 *
27 * @category ToolsAndUtilities
28 * @package adLDAP
29 * @author Scott Barnett, Richard Hyland
30 * @copyright (c) 2006-2010 Scott Barnett, Richard Hyland
31 * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html LGPLv2.1
32 * @revision $Revision: 91 $
33 * @version 3.3.2
34 * @link http://adldap.sourceforge.net/
35 */
36
37/**
38 * Define the different types of account in AD
39 */
40define ('ADLDAP_NORMAL_ACCOUNT', 805306368);
41define ('ADLDAP_WORKSTATION_TRUST', 805306369);
42define ('ADLDAP_INTERDOMAIN_TRUST', 805306370);
43define ('ADLDAP_SECURITY_GLOBAL_GROUP', 268435456);
44define ('ADLDAP_DISTRIBUTION_GROUP', 268435457);
45define ('ADLDAP_SECURITY_LOCAL_GROUP', 536870912);
46define ('ADLDAP_DISTRIBUTION_LOCAL_GROUP', 536870913);
47define ('ADLDAP_FOLDER', 'OU');
48define ('ADLDAP_CONTAINER', 'CN');
49
50/**
51* Main adLDAP class
52*
53* Can be initialised using $adldap = new adLDAP();
54*
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.
58*
59* Before asking questions, please read the Documentation at
60* http://adldap.sourceforge.net/wiki/doku.php?id=api
61*/
62class adLDAP {
63 /**
64 * The account suffix for your domain, can be set when the class is invoked
65 *
66 * @var string
67 */
68 protected $_account_suffix = "@mydomain.local";
69
70 /**
71 * The base dn for your domain
72 *
73 * @var string
74 */
75 protected $_base_dn = "DC=mydomain,DC=local";
76
77 /**
78 * Array of domain controllers. Specifiy multiple controllers if you
79 * would like the class to balance the LDAP queries amongst multiple servers
80 *
81 * @var array
82 */
83 protected $_domain_controllers = array ("dc01.mydomain.local");
84
85 /**
86 * Optional account with higher privileges for searching
87 * This should be set to a domain admin account
88 *
89 * @var string
90 * @var string
91 */
92 protected $_ad_username=NULL;
93 protected $_ad_password=NULL;
94
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
100 *
101 * @var bool
102 */
103 protected $_real_primarygroup=true;
104
105 /**
106 * Use SSL (LDAPS), your server needs to be setup, please see
107 * http://adldap.sourceforge.net/wiki/doku.php?id=ldap_over_ssl
108 *
109 * @var bool
110 */
111 protected $_use_ssl=false;
112
113 /**
114 * Use TLS
115 * If you wish to use TLS you should ensure that $_use_ssl is set to false and vice-versa
116 *
117 * @var bool
118 */
119 protected $_use_tls=false;
120
121 /**
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
125 *
126 * @var bool
127 */
128 protected $_recursive_groups=true;
129
130 // You should not need to edit anything below this line
131 //******************************************************************************************
132
133 /**
134 * Connection and bind default variables
135 *
136 * @var mixed
137 * @var mixed
138 */
139 protected $_conn;
140 protected $_bind;
141
142 /**
143 * Getters and Setters
144 */
145
146 /**
147 * Set the account suffix
148 *
149 * @param string $_account_suffix
150 * @return void
151 */
152 public function set_account_suffix($_account_suffix)
153 {
154 $this->_account_suffix = $_account_suffix;
155 }
156
157 /**
158 * Get the account suffix
159 *
160 * @return string
161 */
162 public function get_account_suffix()
163 {
164 return $this->_account_suffix;
165 }
166
167 /**
168 * Set the domain controllers array
169 *
170 * @param array $_domain_controllers
171 * @return void
172 */
173 public function set_domain_controllers(array $_domain_controllers)
174 {
175 $this->_domain_controllers = $_domain_controllers;
176 }
177
178 /**
179 * Get the list of domain controllers
180 *
181 * @return void
182 */
183 public function get_domain_controllers()
184 {
185 return $this->_domain_controllers;
186 }
187
188 /**
189 * Set the username of an account with higher priviledges
190 *
191 * @param string $_ad_username
192 * @return void
193 */
194 public function set_ad_username($_ad_username)
195 {
196 $this->_ad_username = $_ad_username;
197 }
198
199 /**
200 * Get the username of the account with higher priviledges
201 *
202 * This will throw an exception for security reasons
203 */
204 public function get_ad_username()
205 {
206 throw new adLDAPException('For security reasons you cannot access the domain administrator account details');
207 }
208
209 /**
210 * Set the password of an account with higher priviledges
211 *
212 * @param string $_ad_password
213 * @return void
214 */
215 public function set_ad_password($_ad_password)
216 {
217 $this->_ad_password = $_ad_password;
218 }
219
220 /**
221 * Get the password of the account with higher priviledges
222 *
223 * This will throw an exception for security reasons
224 */
225 public function get_ad_password()
226 {
227 throw new adLDAPException('For security reasons you cannot access the domain administrator account details');
228 }
229
230 /**
231 * Set whether to detect the true primary group
232 *
233 * @param bool $_real_primary_group
234 * @return void
235 */
236 public function set_real_primarygroup($_real_primarygroup)
237 {
238 $this->_real_primarygroup = $_real_primarygroup;
239 }
240
241 /**
242 * Get the real primary group setting
243 *
244 * @return bool
245 */
246 public function get_real_primarygroup()
247 {
248 return $this->_real_primarygroup;
249 }
250
251 /**
252 * Set whether to use SSL
253 *
254 * @param bool $_use_ssl
255 * @return void
256 */
257 public function set_use_ssl($_use_ssl)
258 {
259 $this->_use_ssl = $_use_ssl;
260 }
261
262 /**
263 * Get the SSL setting
264 *
265 * @return bool
266 */
267 public function get_use_ssl()
268 {
269 return $this->_use_ssl;
270 }
271
272 /**
273 * Set whether to use TLS
274 *
275 * @param bool $_use_tls
276 * @return void
277 */
278 public function set_use_tls($_use_tls)
279 {
280 $this->_use_tls = $_use_tls;
281 }
282
283 /**
284 * Get the TLS setting
285 *
286 * @return bool
287 */
288 public function get_use_tls()
289 {
290 return $this->_use_tls;
291 }
292
293 /**
294 * Set whether to lookup recursive groups
295 *
296 * @param bool $_recursive_groups
297 * @return void
298 */
299 public function set_recursive_groups($_recursive_groups)
300 {
301 $this->_recursive_groups = $_recursive_groups;
302 }
303
304 /**
305 * Get the recursive groups setting
306 *
307 * @return bool
308 */
309 public function get_recursive_groups()
310 {
311 return $this->_recursive_groups;
312 }
313
314 /**
315 * Default Constructor
316 *
317 * Tries to bind to the AD domain over LDAP or LDAPs
318 *
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
322 */
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"]; }
335 }
336
337 if ($this->ldap_supported() === false) {
338 throw new adLDAPException('No LDAP support for PHP. See: http://www.php.net/ldap');
339 }
340
341 return $this->connect();
342 }
343
344 /**
345 * Default Destructor
346 *
347 * Closes the LDAP connection
348 *
349 * @return void
350 */
351 function __destruct(){ $this->close(); }
352
353 /**
354 * Connects and Binds to the Domain Controller
355 *
356 * @return bool
357 */
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);
365 }
366
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);
370
371 if ($this->_use_tls) {
372 ldap_start_tls($this->_conn);
373 }
374
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());
384 }
385 }
386 }
387
388 if ($this->_base_dn == NULL) {
389 $this->_base_dn = $this->find_base_dn();
390 }
391
392 return (true);
393 }
394
395 /**
396 * Closes the LDAP connection
397 *
398 * @return void
399 */
400 public function close() {
401 ldap_close ($this->_conn);
402 }
403
404 /**
405 * Validate a user's login credentials
406 *
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
411 */
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; }
416
417 // Bind as the user
418 $ret = true;
419 $this->_bind = @ldap_bind($this->_conn, $username . $this->_account_suffix, $password);
420 if (!$this->_bind){ $ret = false; }
421
422 // Cnce we've checked their details, kick back into admin mode if we have it
423 if ($this->_ad_username !== NULL && !$prevent_rebind) {
424 $this->_bind = @ldap_bind($this->_conn, $this->_ad_username . $this->_account_suffix , $this->_ad_password);
425 if (!$this->_bind){
426 // This should never happen in theory
427 throw new adLDAPException('Rebind to Active Directory failed. AD said: ' . $this->get_last_error());
428 }
429 }
430
431 return $ret;
432 }
433
434 //*****************************************************************************************************************
435 // GROUP FUNCTIONS
436
437 /**
438 * Add a group to a group
439 *
440 * @param string $parent The parent group name
441 * @param string $child The child group name
442 * @return bool
443 */
444 public function group_add_group($parent,$child){
445
446 // Find the parent group's dn
447 $parent_group=$this->group_info($parent,array("cn"));
448 if ($parent_group[0]["dn"]===NULL){ return (false); }
449 $parent_dn=$parent_group[0]["dn"];
450
451 // Find the child group's dn
452 $child_group=$this->group_info($child,array("cn"));
453 if ($child_group[0]["dn"]===NULL){ return (false); }
454 $child_dn=$child_group[0]["dn"];
455
456 $add=array();
457 $add["member"] = $child_dn;
458
459 $result=@ldap_mod_add($this->_conn,$parent_dn,$add);
460 if ($result==false){ return (false); }
461 return (true);
462 }
463
464 /**
465 * Add a user to a group
466 *
467 * @param string $group The group to add the user to
468 * @param string $user The user to add to the group
469 * @param bool $isGUID Is the username passed a GUID or a samAccountName
470 * @return bool
471 */
472 public function group_add_user($group,$user,$isGUID=false){
473 // Adding a user is a bit fiddly, we need to get the full DN of the user
474 // and add it using the full DN of the group
475
476 // Find the user's dn
477 $user_dn=$this->user_dn($user,$isGUID);
478 if ($user_dn===false){ return (false); }
479
480 // Find the group's dn
481 $group_info=$this->group_info($group,array("cn"));
482 if ($group_info[0]["dn"]===NULL){ return (false); }
483 $group_dn=$group_info[0]["dn"];
484
485 $add=array();
486 $add["member"] = $user_dn;
487
488 $result=@ldap_mod_add($this->_conn,$group_dn,$add);
489 if ($result==false){ return (false); }
490 return (true);
491 }
492
493 /**
494 * Add a contact to a group
495 *
496 * @param string $group The group to add the contact to
497 * @param string $contact_dn The DN of the contact to add
498 * @return bool
499 */
500 public function group_add_contact($group,$contact_dn){
501 // To add a contact we take the contact's DN
502 // and add it using the full DN of the group
503
504 // Find the group's dn
505 $group_info=$this->group_info($group,array("cn"));
506 if ($group_info[0]["dn"]===NULL){ return (false); }
507 $group_dn=$group_info[0]["dn"];
508
509 $add=array();
510 $add["member"] = $contact_dn;
511
512 $result=@ldap_mod_add($this->_conn,$group_dn,$add);
513 if ($result==false){ return (false); }
514 return (true);
515 }
516
517 /**
518 * Create a group
519 *
520 * @param array $attributes Default attributes of the group
521 * @return bool
522 */
523 public function group_create($attributes){
524 if (!is_array($attributes)){ return ("Attributes must be an array"); }
525 if (!array_key_exists("group_name",$attributes)){ return ("Missing compulsory field [group_name]"); }
526 if (!array_key_exists("container",$attributes)){ return ("Missing compulsory field [container]"); }
527 if (!array_key_exists("description",$attributes)){ return ("Missing compulsory field [description]"); }
528 if (!is_array($attributes["container"])){ return ("Container attribute must be an array."); }
529 $attributes["container"]=array_reverse($attributes["container"]);
530
531 //$member_array = array();
532 //$member_array[0] = "cn=user1,cn=Users,dc=yourdomain,dc=com";
533 //$member_array[1] = "cn=administrator,cn=Users,dc=yourdomain,dc=com";
534
535 $add=array();
536 $add["cn"] = $attributes["group_name"];
537 $add["samaccountname"] = $attributes["group_name"];
538 $add["objectClass"] = "Group";
539 $add["description"] = $attributes["description"];
540 //$add["member"] = $member_array; UNTESTED
541
542 $container="OU=".implode(",OU=",$attributes["container"]);
543 $result=ldap_add($this->_conn,"CN=".$add["cn"].", ".$container.",".$this->_base_dn,$add);
544 if ($result!=true){ return (false); }
545
546 return (true);
547 }
548
549 /**
550 * Remove a group from a group
551 *
552 * @param string $parent The parent group name
553 * @param string $child The child group name
554 * @return bool
555 */
556 public function group_del_group($parent,$child){
557
558 // Find the parent dn
559 $parent_group=$this->group_info($parent,array("cn"));
560 if ($parent_group[0]["dn"]===NULL){ return (false); }
561 $parent_dn=$parent_group[0]["dn"];
562
563 // Find the child dn
564 $child_group=$this->group_info($child,array("cn"));
565 if ($child_group[0]["dn"]===NULL){ return (false); }
566 $child_dn=$child_group[0]["dn"];
567
568 $del=array();
569 $del["member"] = $child_dn;
570
571 $result=@ldap_mod_del($this->_conn,$parent_dn,$del);
572 if ($result==false){ return (false); }
573 return (true);
574 }
575
576 /**
577 * Remove a user from a group
578 *
579 * @param string $group The group to remove a user from
580 * @param string $user The AD user to remove from the group
581 * @param bool $isGUID Is the username passed a GUID or a samAccountName
582 * @return bool
583 */
584 public function group_del_user($group,$user,$isGUID=false){
585
586 // Find the parent dn
587 $group_info=$this->group_info($group,array("cn"));
588 if ($group_info[0]["dn"]===NULL){ return (false); }
589 $group_dn=$group_info[0]["dn"];
590
591 // Find the users dn
592 $user_dn=$this->user_dn($user,$isGUID);
593 if ($user_dn===false){ return (false); }
594
595 $del=array();
596 $del["member"] = $user_dn;
597
598 $result=@ldap_mod_del($this->_conn,$group_dn,$del);
599 if ($result==false){ return (false); }
600 return (true);
601 }
602
603 /**
604 * Remove a contact from a group
605 *
606 * @param string $group The group to remove a user from
607 * @param string $contact_dn The DN of a contact to remove from the group
608 * @return bool
609 */
610 public function group_del_contact($group,$contact_dn){
611
612 // Find the parent dn
613 $group_info=$this->group_info($group,array("cn"));
614 if ($group_info[0]["dn"]===NULL){ return (false); }
615 $group_dn=$group_info[0]["dn"];
616
617 $del=array();
618 $del["member"] = $contact_dn;
619
620 $result=@ldap_mod_del($this->_conn,$group_dn,$del);
621 if ($result==false){ return (false); }
622 return (true);
623 }
624
625 /**
626 * Return a list of groups in a group
627 *
628 * @param string $group The group to query
629 * @param bool $recursive Recursively get groups
630 * @return array
631 */
632 public function groups_in_group($group, $recursive = NULL){
633 if (!$this->_bind){ return (false); }
634 if ($recursive===NULL){ $recursive=$this->_recursive_groups; } // Use the default option if they haven't set it
635
636 // Search the directory for the members of a group
637 $info=$this->group_info($group,array("member","cn"));
638 $groups=$info[0]["member"];
639 if (!is_array($groups)) {
640 return (false);
641 }
642
643 $group_array=array();
644
645 for ($i=0; $i<$groups["count"]; $i++){
646 $filter="(&(objectCategory=group)(distinguishedName=".$this->ldap_slashes($groups[$i])."))";
647 $fields = array("samaccountname", "distinguishedname", "objectClass");
648 $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);
649 $entries = ldap_get_entries($this->_conn, $sr);
650
651 // not a person, look for a group
652 if ($entries['count'] == 0 && $recursive == true) {
653 $filter="(&(objectCategory=group)(distinguishedName=".$this->ldap_slashes($groups[$i])."))";
654 $fields = array("distinguishedname");
655 $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);
656 $entries = ldap_get_entries($this->_conn, $sr);
657 if (!isset($entries[0]['distinguishedname'][0])) {
658 continue;
659 }
660 $sub_groups = $this->groups_in_group($entries[0]['distinguishedname'][0], $recursive);
661 if (is_array($sub_groups)) {
662 $group_array = array_merge($group_array, $sub_groups);
663 $group_array = array_unique($group_array);
664 }
665 continue;
666 }
667
668 $group_array[] = $entries[0]['distinguishedname'][0];
669 }
670 return ($group_array);
671 }
672
673 /**
674 * Return a list of members in a group
675 *
676 * @param string $group The group to query
677 * @param bool $recursive Recursively get group members
678 * @return array
679 */
680 public function group_members($group, $recursive = NULL){
681 if (!$this->_bind){ return (false); }
682 if ($recursive===NULL){ $recursive=$this->_recursive_groups; } // Use the default option if they haven't set it
683 // Search the directory for the members of a group
684 $info=$this->group_info($group,array("member","cn"));
685 $users=$info[0]["member"];
686 if (!is_array($users)) {
687 return (false);
688 }
689
690 $user_array=array();
691
692 for ($i=0; $i<$users["count"]; $i++){
693 $filter="(&(objectCategory=person)(distinguishedName=".$this->ldap_slashes($users[$i])."))";
694 $fields = array("samaccountname", "distinguishedname", "objectClass");
695 $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);
696 $entries = ldap_get_entries($this->_conn, $sr);
697
698 // not a person, look for a group
699 if ($entries['count'] == 0 && $recursive == true) {
700 $filter="(&(objectCategory=group)(distinguishedName=".$this->ldap_slashes($users[$i])."))";
701 $fields = array("samaccountname");
702 $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);
703 $entries = ldap_get_entries($this->_conn, $sr);
704 if (!isset($entries[0]['samaccountname'][0])) {
705 continue;
706 }
707 $sub_users = $this->group_members($entries[0]['samaccountname'][0], $recursive);
708 if (is_array($sub_users)) {
709 $user_array = array_merge($user_array, $sub_users);
710 $user_array = array_unique($user_array);
711 }
712 continue;
713 }
714
715 if ($entries[0]['samaccountname'][0] === NULL && $entries[0]['distinguishedname'][0] !== NULL) {
716 $user_array[] = $entries[0]['distinguishedname'][0];
717 }
718 elseif ($entries[0]['samaccountname'][0] !== NULL) {
719 $user_array[] = $entries[0]['samaccountname'][0];
720 }
721 }
722 return ($user_array);
723 }
724
725 /**
726 * Group Information. Returns an array of information about a group.
727 * The group name is case sensitive
728 *
729 * @param string $group_name The group name to retrieve info about
730 * @param array $fields Fields to retrieve
731 * @return array
732 */
733 public function group_info($group_name,$fields=NULL){
734 if ($group_name===NULL){ return (false); }
735 if (!$this->_bind){ return (false); }
736
737 if (stristr($group_name, '+')) {
738 $group_name=stripslashes($group_name);
739 }
740
741 $filter="(&(objectCategory=group)(name=".$this->ldap_slashes($group_name)."))";
742 //echo ($filter."!!!<br>");
743 if ($fields===NULL){ $fields=array("member","memberof","cn","description","distinguishedname","objectcategory","samaccountname"); }
744 $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);
745 $entries = ldap_get_entries($this->_conn, $sr);
746 //print_r($entries);
747 return ($entries);
748 }
749
750 /**
751 * Return a complete list of "groups in groups"
752 *
753 * @param string $group The group to get the list from
754 * @return array
755 */
756 public function recursive_groups($group){
757 if ($group===NULL){ return (false); }
758
759 $ret_groups=array();
760
761 $groups=$this->group_info($group,array("memberof"));
762 if (isset($groups[0]["memberof"]) && is_array($groups[0]["memberof"])) {
763 $groups=$groups[0]["memberof"];
764
765 if ($groups){
766 $group_names=$this->nice_names($groups);
767 $ret_groups=array_merge($ret_groups,$group_names); //final groups to return
768
769 foreach ($group_names as $id => $group_name){
770 $child_groups=$this->recursive_groups($group_name);
771 $ret_groups=array_merge($ret_groups,$child_groups);
772 }
773 }
774 }
775
776 return ($ret_groups);
777 }
778
779 /**
780 * Returns a complete list of the groups in AD based on a SAM Account Type
781 *
782 * @param string $samaccounttype The account type to return
783 * @param bool $include_desc Whether to return a description
784 * @param string $search Search parameters
785 * @param bool $sorted Whether to sort the results
786 * @return array
787 */
788 public function search_groups($samaccounttype = ADLDAP_SECURITY_GLOBAL_GROUP, $include_desc = false, $search = "*", $sorted = true) {
789 if (!$this->_bind){ return (false); }
790
791 $filter = '(&(objectCategory=group)';
792 if ($samaccounttype !== null) {
793 $filter .= '(samaccounttype='. $samaccounttype .')';
794 }
795 $filter .= '(cn='.$search.'))';
796 // Perform the search and grab all their details
797 $fields=array("samaccountname","description");
798 $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);
799 $entries = ldap_get_entries($this->_conn, $sr);
800
801 $groups_array = array();
802 for ($i=0; $i<$entries["count"]; $i++){
803 if ($include_desc && strlen($entries[$i]["description"][0]) > 0 ){
804 $groups_array[ $entries[$i]["samaccountname"][0] ] = $entries[$i]["description"][0];
805 } elseif ($include_desc){
806 $groups_array[ $entries[$i]["samaccountname"][0] ] = $entries[$i]["samaccountname"][0];
807 } else {
808 array_push($groups_array, $entries[$i]["samaccountname"][0]);
809 }
810 }
811 if( $sorted ){ asort($groups_array); }
812 return ($groups_array);
813 }
814
815 /**
816 * Returns a complete list of all groups in AD
817 *
818 * @param bool $include_desc Whether to return a description
819 * @param string $search Search parameters
820 * @param bool $sorted Whether to sort the results
821 * @return array
822 */
823 public function all_groups($include_desc = false, $search = "*", $sorted = true){
824 $groups_array = $this->search_groups(null, $include_desc, $search, $sorted);
825 return ($groups_array);
826 }
827
828 /**
829 * Returns a complete list of security groups in AD
830 *
831 * @param bool $include_desc Whether to return a description
832 * @param string $search Search parameters
833 * @param bool $sorted Whether to sort the results
834 * @return array
835 */
836 public function all_security_groups($include_desc = false, $search = "*", $sorted = true){
837 $groups_array = $this->search_groups(ADLDAP_SECURITY_GLOBAL_GROUP, $include_desc, $search, $sorted);
838 return ($groups_array);
839 }
840
841 /**
842 * Returns a complete list of distribution lists in AD
843 *
844 * @param bool $include_desc Whether to return a description
845 * @param string $search Search parameters
846 * @param bool $sorted Whether to sort the results
847 * @return array
848 */
849 public function all_distribution_groups($include_desc = false, $search = "*", $sorted = true){
850 $groups_array = $this->search_groups(ADLDAP_DISTRIBUTION_GROUP, $include_desc, $search, $sorted);
851 return ($groups_array);
852 }
853
854 //*****************************************************************************************************************
855 // USER FUNCTIONS
856
857 /**
858 * Create a user
859 *
860 * If you specify a password here, this can only be performed over SSL
861 *
862 * @param array $attributes The attributes to set to the user account
863 * @return bool
864 */
865 public function user_create($attributes){
866 // Check for compulsory fields
867 if (!array_key_exists("username",$attributes)){ return ("Missing compulsory field [username]"); }
868 if (!array_key_exists("firstname",$attributes)){ return ("Missing compulsory field [firstname]"); }
869 if (!array_key_exists("surname",$attributes)){ return ("Missing compulsory field [surname]"); }
870 if (!array_key_exists("email",$attributes)){ return ("Missing compulsory field [email]"); }
871 if (!array_key_exists("container",$attributes)){ return ("Missing compulsory field [container]"); }
872 if (!is_array($attributes["container"])){ return ("Container attribute must be an array."); }
873
874 if (array_key_exists("password",$attributes) && (!$this->_use_ssl && !$this->_use_tls)){
875 throw new adLDAPException('SSL must be configured on your webserver and enabled in the class to set passwords.');
876 }
877
878 if (!array_key_exists("display_name",$attributes)){ $attributes["display_name"]=$attributes["firstname"]." ".$attributes["surname"]; }
879
880 // Translate the schema
881 $add=$this->adldap_schema($attributes);
882
883 // Additional stuff only used for adding accounts
884 $add["cn"][0]=$attributes["display_name"];
885 $add["samaccountname"][0]=$attributes["username"];
886 $add["objectclass"][0]="top";
887 $add["objectclass"][1]="person";
888 $add["objectclass"][2]="organizationalPerson";
889 $add["objectclass"][3]="user"; //person?
890 //$add["name"][0]=$attributes["firstname"]." ".$attributes["surname"];
891
892 // Set the account control attribute
893 $control_options=array("NORMAL_ACCOUNT");
894 if (!$attributes["enabled"]){ $control_options[]="ACCOUNTDISABLE"; }
895 $add["userAccountControl"][0]=$this->account_control($control_options);
896 //echo ("<pre>"); print_r($add);
897
898 // Determine the container
899 $attributes["container"]=array_reverse($attributes["container"]);
900 $container="OU=".implode(",OU=",$attributes["container"]);
901
902 // Add the entry
903 $result=@ldap_add($this->_conn, "CN=".$add["cn"][0].", ".$container.",".$this->_base_dn, $add);
904 if ($result!=true){ return (false); }
905
906 return (true);
907 }
908
909 /**
910 * Delete a user account
911 *
912 * @param string $username The username to delete (please be careful here!)
913 * @param bool $isGUID Is the username a GUID or a samAccountName
914 * @return array
915 */
916 public function user_delete($username,$isGUID=false) {
917 $userinfo = $this->user_info($username, array("*"),$isGUID);
918 $dn = $userinfo[0]['distinguishedname'][0];
919 $result=$this->dn_delete($dn);
920 if ($result!=true){ return (false); }
921 return (true);
922 }
923
924 /**
925 * Groups the user is a member of
926 *
927 * @param string $username The username to query
928 * @param bool $recursive Recursive list of groups
929 * @param bool $isGUID Is the username passed a GUID or a samAccountName
930 * @return array
931 */
932 public function user_groups($username,$recursive=NULL,$isGUID=false){
933 if ($username===NULL){ return (false); }
934 if ($recursive===NULL){ $recursive=$this->_recursive_groups; } // Use the default option if they haven't set it
935 if (!$this->_bind){ return (false); }
936
937 // Search the directory for their information
938 $info=@$this->user_info($username,array("memberof","primarygroupid"),$isGUID);
939 $groups=$this->nice_names($info[0]["memberof"]); // Presuming the entry returned is our guy (unique usernames)
940
941 if ($recursive === true){
942 foreach ($groups as $id => $group_name){
943 $extra_groups=$this->recursive_groups($group_name);
944 $groups=array_merge($groups,$extra_groups);
945 }
946 }
947
948 return ($groups);
949 }
950
951 /**
952 * Find information about the users
953 *
954 * @param string $username The username to query
955 * @param array $fields Array of parameters to query
956 * @param bool $isGUID Is the username passed a GUID or a samAccountName
957 * @return array
958 */
959 public function user_info($username,$fields=NULL,$isGUID=false){
960 if ($username===NULL){ return (false); }
961 if (!$this->_bind){ return (false); }
962
963 if ($isGUID === true) {
964 $username = $this->strguid2hex($username);
965 $filter="objectguid=".$username;
966 }
967 else if (strstr($username, "@")) {
968 $filter="userPrincipalName=".$username;
969 }
970 else {
971 $filter="samaccountname=".$username;
972 }
973 $filter = "(&(objectCategory=person)({$filter}))";
974 if ($fields===NULL){ $fields=array("samaccountname","mail","memberof","department","displayname","telephonenumber","primarygroupid","objectsid"); }
975 if (!in_array("objectsid",$fields)){
976 $fields[] = "objectsid";
977 }
978 $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);
979 $entries = ldap_get_entries($this->_conn, $sr);
980
981 if (isset($entries[0])) {
982 if ($entries[0]['count'] >= 1) {
983 if (in_array("memberof", $fields)) {
984 // AD does not return the primary group in the ldap query, we may need to fudge it
985 if ($this->_real_primarygroup && isset($entries[0]["primarygroupid"][0]) && isset($entries[0]["objectsid"][0])){
986 //$entries[0]["memberof"][]=$this->group_cn($entries[0]["primarygroupid"][0]);
987 $entries[0]["memberof"][]=$this->get_primary_group($entries[0]["primarygroupid"][0], $entries[0]["objectsid"][0]);
988 } else {
989 $entries[0]["memberof"][]="CN=Domain Users,CN=Users,".$this->_base_dn;
990 }
991 $entries[0]["memberof"]["count"]++;
992 }
993 }
994 return $entries;
995 }
996 return false;
997 }
998
999 /**
1000 * Determine if a user is in a specific group
1001 *
1002 * @param string $username The username to query
1003 * @param string $group The name of the group to check against
1004 * @param bool $recursive Check groups recursively
1005 * @param bool $isGUID Is the username passed a GUID or a samAccountName
1006 * @return bool
1007 */
1008 public function user_ingroup($username,$group,$recursive=NULL,$isGUID=false){
1009 if ($username===NULL){ return (false); }
1010 if ($group===NULL){ return (false); }
1011 if (!$this->_bind){ return (false); }
1012 if ($recursive===NULL){ $recursive=$this->_recursive_groups; } // Use the default option if they haven't set it
1013
1014 // Get a list of the groups
1015 $groups=$this->user_groups($username,$recursive,$isGUID);
1016
1017 // Return true if the specified group is in the group list
1018 if (in_array($group,$groups)){ return (true); }
1019
1020 return (false);
1021 }
1022
1023 /**
1024 * Determine a user's password expiry date
1025 *
1026 * @param string $username The username to query
1027 * @param book $isGUID Is the username passed a GUID or a samAccountName
1028 * @requires bcmath http://www.php.net/manual/en/book.bc.php
1029 * @return array
1030 */
1031 public function user_password_expiry($username,$isGUID=false) {
1032 if ($username===NULL){ return ("Missing compulsory field [username]"); }
1033 if (!$this->_bind){ return (false); }
1034 if (!function_exists('bcmod')) { return ("Missing function support [bcmod] http://www.php.net/manual/en/book.bc.php"); };
1035
1036 $userinfo = $this->user_info($username, array("pwdlastset", "useraccountcontrol"), $isGUID);
1037 $pwdlastset = $userinfo[0]['pwdlastset'][0];
1038 $status = array();
1039
1040 if ($userinfo[0]['useraccountcontrol'][0] == '66048') {
1041 // Password does not expire
1042 return "Does not expire";
1043 }
1044 if ($pwdlastset === '0') {
1045 // Password has already expired
1046 return "Password has expired";
1047 }
1048
1049 // Password expiry in AD can be calculated from TWO values:
1050 // - User's own pwdLastSet attribute: stores the last time the password was changed
1051 // - Domain's maxPwdAge attribute: how long passwords last in the domain
1052 //
1053 // Although Microsoft chose to use a different base and unit for time measurements.
1054 // This function will convert them to Unix timestamps
1055 $sr = ldap_read($this->_conn, $this->_base_dn, 'objectclass=*', array('maxPwdAge'));
1056 if (!$sr) {
1057 return false;
1058 }
1059 $info = ldap_get_entries($this->_conn, $sr);
1060 $maxpwdage = $info[0]['maxpwdage'][0];
1061
1062
1063 // See MSDN: http://msdn.microsoft.com/en-us/library/ms974598.aspx
1064 //
1065 // pwdLastSet contains the number of 100 nanosecond intervals since January 1, 1601 (UTC),
1066 // stored in a 64 bit integer.
1067 //
1068 // The number of seconds between this date and Unix epoch is 11644473600.
1069 //
1070 // maxPwdAge is stored as a large integer that represents the number of 100 nanosecond
1071 // intervals from the time the password was set before the password expires.
1072 //
1073 // We also need to scale this to seconds but also this value is a _negative_ quantity!
1074 //
1075 // If the low 32 bits of maxPwdAge are equal to 0 passwords do not expire
1076 //
1077 // Unfortunately the maths involved are too big for PHP integers, so I've had to require
1078 // BCMath functions to work with arbitrary precision numbers.
1079 if (bcmod($maxpwdage, 4294967296) === '0') {
1080 return "Domain does not expire passwords";
1081 }
1082
1083 // Add maxpwdage and pwdlastset and we get password expiration time in Microsoft's
1084 // time units. Because maxpwd age is negative we need to subtract it.
1085 $pwdexpire = bcsub($pwdlastset, $maxpwdage);
1086
1087 // Convert MS's time to Unix time
1088 $status['expiryts'] = bcsub(bcdiv($pwdexpire, '10000000'), '11644473600');
1089 $status['expiryformat'] = date('Y-m-d H:i:s', bcsub(bcdiv($pwdexpire, '10000000'), '11644473600'));
1090
1091 return $status;
1092 }
1093
1094 /**
1095 * Modify a user
1096 *
1097 * @param string $username The username to query
1098 * @param array $attributes The attributes to modify. Note if you set the enabled attribute you must not specify any other attributes
1099 * @param bool $isGUID Is the username passed a GUID or a samAccountName
1100 * @return bool
1101 */
1102 public function user_modify($username,$attributes,$isGUID=false){
1103 if ($username===NULL){ return ("Missing compulsory field [username]"); }
1104 if (array_key_exists("password",$attributes) && !$this->_use_ssl){
1105 throw new adLDAPException('SSL must be configured on your webserver and enabled in the class to set passwords.');
1106 }
1107
1108 // Find the dn of the user
1109 $user_dn=$this->user_dn($username,$isGUID);
1110 if ($user_dn===false){ return (false); }
1111
1112 // Translate the update to the LDAP schema
1113 $mod=$this->adldap_schema($attributes);
1114
1115 // Check to see if this is an enabled status update
1116 if (!$mod && !array_key_exists("enabled", $attributes)){ return (false); }
1117
1118 // Set the account control attribute (only if specified)
1119 if (array_key_exists("enabled",$attributes)){
1120 if ($attributes["enabled"]){ $control_options=array("NORMAL_ACCOUNT"); }
1121 else { $control_options=array("NORMAL_ACCOUNT","ACCOUNTDISABLE"); }
1122 $mod["userAccountControl"][0]=$this->account_control($control_options);
1123 }
1124
1125 // Do the update
1126 $result=@ldap_modify($this->_conn,$user_dn,$mod);
1127 if ($result==false){ return (false); }
1128
1129 return (true);
1130 }
1131
1132 /**
1133 * Disable a user account
1134 *
1135 * @param string $username The username to disable
1136 * @param bool $isGUID Is the username passed a GUID or a samAccountName
1137 * @return bool
1138 */
1139 public function user_disable($username,$isGUID=false){
1140 if ($username===NULL){ return ("Missing compulsory field [username]"); }
1141 $attributes=array("enabled"=>0);
1142 $result = $this->user_modify($username, $attributes, $isGUID);
1143 if ($result==false){ return (false); }
1144
1145 return (true);
1146 }
1147
1148 /**
1149 * Enable a user account
1150 *
1151 * @param string $username The username to enable
1152 * @param bool $isGUID Is the username passed a GUID or a samAccountName
1153 * @return bool
1154 */
1155 public function user_enable($username,$isGUID=false){
1156 if ($username===NULL){ return ("Missing compulsory field [username]"); }
1157 $attributes=array("enabled"=>1);
1158 $result = $this->user_modify($username, $attributes, $isGUID);
1159 if ($result==false){ return (false); }
1160
1161 return (true);
1162 }
1163
1164 /**
1165 * Set the password of a user - This must be performed over SSL
1166 *
1167 * @param string $username The username to modify
1168 * @param string $password The new password
1169 * @param bool $isGUID Is the username passed a GUID or a samAccountName
1170 * @return bool
1171 */
1172 public function user_password($username,$password,$isGUID=false){
1173 if ($username===NULL){ return (false); }
1174 if ($password===NULL){ return (false); }
1175 if (!$this->_bind){ return (false); }
1176 if (!$this->_use_ssl && !$this->_use_tls){
1177 throw new adLDAPException('SSL must be configured on your webserver and enabled in the class to set passwords.');
1178 }
1179
1180 $user_dn=$this->user_dn($username,$isGUID);
1181 if ($user_dn===false){ return (false); }
1182
1183 $add=array();
1184 $add["unicodePwd"][0]=$this->encode_password($password);
1185
1186 $result=@ldap_mod_replace($this->_conn,$user_dn,$add);
1187 if ($result==false){
1188 $err = ldap_errno($this->_conn);
1189 if($err){
1190 $msg = 'Error '.$err.': '.ldap_err2str($err).'.';
1191 if($err == 53) $msg .= ' Your password might not match the password policy.';
1192 throw new adLDAPException($msg);
1193 }else{
1194 return false;
1195 }
1196 }
1197
1198 return (true);
1199 }
1200
1201 /**
1202 * Return a list of all users in AD
1203 *
1204 * @param bool $include_desc Return a description of the user
1205 * @param string $search Search parameter
1206 * @param bool $sorted Sort the user accounts
1207 * @return array
1208 */
1209 public function all_users($include_desc = false, $search = "*", $sorted = true){
1210 if (!$this->_bind){ return (false); }
1211
1212 // Perform the search and grab all their details
1213 $filter = "(&(objectClass=user)(samaccounttype=". ADLDAP_NORMAL_ACCOUNT .")(objectCategory=person)(cn=".$search."))";
1214 $fields=array("samaccountname","displayname");
1215 $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);
1216 $entries = ldap_get_entries($this->_conn, $sr);
1217
1218 $users_array = array();
1219 for ($i=0; $i<$entries["count"]; $i++){
1220 if ($include_desc && strlen($entries[$i]["displayname"][0])>0){
1221 $users_array[ $entries[$i]["samaccountname"][0] ] = $entries[$i]["displayname"][0];
1222 } elseif ($include_desc){
1223 $users_array[ $entries[$i]["samaccountname"][0] ] = $entries[$i]["samaccountname"][0];
1224 } else {
1225 array_push($users_array, $entries[$i]["samaccountname"][0]);
1226 }
1227 }
1228 if ($sorted){ asort($users_array); }
1229 return ($users_array);
1230 }
1231
1232 /**
1233 * Converts a username (samAccountName) to a GUID
1234 *
1235 * @param string $username The username to query
1236 * @return string
1237 */
1238 public function username2guid($username) {
1239 if (!$this->_bind){ return (false); }
1240 if ($username === null){ return ("Missing compulsory field [username]"); }
1241
1242 $filter = "samaccountname=" . $username;
1243 $fields = array("objectGUID");
1244 $sr = @ldap_search($this->_conn, $this->_base_dn, $filter, $fields);
1245 if (ldap_count_entries($this->_conn, $sr) > 0) {
1246 $entry = @ldap_first_entry($this->_conn, $sr);
1247 $guid = @ldap_get_values_len($this->_conn, $entry, 'objectGUID');
1248 $strGUID = $this->binary2text($guid[0]);
1249 return ($strGUID);
1250 }
1251 else {
1252 return (false);
1253 }
1254 }
1255
1256 /**
1257 * Move a user account to a different OU
1258 *
1259 * @param string $username The username to move (please be careful here!)
1260 * @param array $container The container or containers to move the user to (please be careful here!).
1261 * accepts containers in 1. parent 2. child order
1262 * @return array
1263 */
1264 public function user_move($username, $container) {
1265 if (!$this->_bind){ return (false); }
1266 if ($username === null){ return ("Missing compulsory field [username]"); }
1267 if ($container === null){ return ("Missing compulsory field [container]"); }
1268 if (!is_array($container)){ return ("Container must be an array"); }
1269
1270 $userinfo = $this->user_info($username, array("*"));
1271 $dn = $userinfo[0]['distinguishedname'][0];
1272 $newrdn = "cn=" . $username;
1273 $container = array_reverse($container);
1274 $newcontainer = "ou=" . implode(",ou=",$container);
1275 $newbasedn = strtolower($newcontainer) . "," . $this->_base_dn;
1276 $result=@ldap_rename($this->_conn,$dn,$newrdn,$newbasedn,true);
1277 if ($result !== true) {
1278 return (false);
1279 }
1280 return (true);
1281 }
1282
1283 //*****************************************************************************************************************
1284 // CONTACT FUNCTIONS
1285 // * Still work to do in this area, and new functions to write
1286
1287 /**
1288 * Create a contact
1289 *
1290 * @param array $attributes The attributes to set to the contact
1291 * @return bool
1292 */
1293 public function contact_create($attributes){
1294 // Check for compulsory fields
1295 if (!array_key_exists("display_name",$attributes)){ return ("Missing compulsory field [display_name]"); }
1296 if (!array_key_exists("email",$attributes)){ return ("Missing compulsory field [email]"); }
1297 if (!array_key_exists("container",$attributes)){ return ("Missing compulsory field [container]"); }
1298 if (!is_array($attributes["container"])){ return ("Container attribute must be an array."); }
1299
1300 // Translate the schema
1301 $add=$this->adldap_schema($attributes);
1302
1303 // Additional stuff only used for adding contacts
1304 $add["cn"][0]=$attributes["display_name"];
1305 $add["objectclass"][0]="top";
1306 $add["objectclass"][1]="person";
1307 $add["objectclass"][2]="organizationalPerson";
1308 $add["objectclass"][3]="contact";
1309 if (!isset($attributes['exchange_hidefromlists'])) {
1310 $add["msExchHideFromAddressLists"][0]="TRUE";
1311 }
1312
1313 // Determine the container
1314 $attributes["container"]=array_reverse($attributes["container"]);
1315 $container="OU=".implode(",OU=",$attributes["container"]);
1316
1317 // Add the entry
1318 $result=@ldap_add($this->_conn, "CN=".$add["cn"][0].", ".$container.",".$this->_base_dn, $add);
1319 if ($result!=true){ return (false); }
1320
1321 return (true);
1322 }
1323
1324 /**
1325 * Determine the list of groups a contact is a member of
1326 *
1327 * @param string $distinguisedname The full DN of a contact
1328 * @param bool $recursive Recursively check groups
1329 * @return array
1330 */
1331 public function contact_groups($distinguishedname,$recursive=NULL){
1332 if ($distinguishedname===NULL){ return (false); }
1333 if ($recursive===NULL){ $recursive=$this->_recursive_groups; } //use the default option if they haven't set it
1334 if (!$this->_bind){ return (false); }
1335
1336 // Search the directory for their information
1337 $info=@$this->contact_info($distinguishedname,array("memberof","primarygroupid"));
1338 $groups=$this->nice_names($info[0]["memberof"]); //presuming the entry returned is our contact
1339
1340 if ($recursive === true){
1341 foreach ($groups as $id => $group_name){
1342 $extra_groups=$this->recursive_groups($group_name);
1343 $groups=array_merge($groups,$extra_groups);
1344 }
1345 }
1346
1347 return ($groups);
1348 }
1349
1350 /**
1351 * Get contact information
1352 *
1353 * @param string $distinguisedname The full DN of a contact
1354 * @param array $fields Attributes to be returned
1355 * @return array
1356 */
1357 public function contact_info($distinguishedname,$fields=NULL){
1358 if ($distinguishedname===NULL){ return (false); }
1359 if (!$this->_bind){ return (false); }
1360
1361 $filter="distinguishedName=".$distinguishedname;
1362 if ($fields===NULL){ $fields=array("distinguishedname","mail","memberof","department","displayname","telephonenumber","primarygroupid","objectsid"); }
1363 $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);
1364 $entries = ldap_get_entries($this->_conn, $sr);
1365
1366 if ($entries[0]['count'] >= 1) {
1367 // AD does not return the primary group in the ldap query, we may need to fudge it
1368 if ($this->_real_primarygroup && isset($entries[0]["primarygroupid"][0]) && isset($entries[0]["primarygroupid"][0])){
1369 //$entries[0]["memberof"][]=$this->group_cn($entries[0]["primarygroupid"][0]);
1370 $entries[0]["memberof"][]=$this->get_primary_group($entries[0]["primarygroupid"][0], $entries[0]["objectsid"][0]);
1371 } else {
1372 $entries[0]["memberof"][]="CN=Domain Users,CN=Users,".$this->_base_dn;
1373 }
1374 }
1375
1376 $entries[0]["memberof"]["count"]++;
1377 return ($entries);
1378 }
1379
1380 /**
1381 * Determine if a contact is a member of a group
1382 *
1383 * @param string $distinguisedname The full DN of a contact
1384 * @param string $group The group name to query
1385 * @param bool $recursive Recursively check groups
1386 * @return bool
1387 */
1388 public function contact_ingroup($distinguisedname,$group,$recursive=NULL){
1389 if ($distinguisedname===NULL){ return (false); }
1390 if ($group===NULL){ return (false); }
1391 if (!$this->_bind){ return (false); }
1392 if ($recursive===NULL){ $recursive=$this->_recursive_groups; } //use the default option if they haven't set it
1393
1394 // Get a list of the groups
1395 $groups=$this->contact_groups($distinguisedname,array("memberof"),$recursive);
1396
1397 // Return true if the specified group is in the group list
1398 if (in_array($group,$groups)){ return (true); }
1399
1400 return (false);
1401 }
1402
1403 /**
1404 * Modify a contact
1405 *
1406 * @param string $distinguishedname The contact to query
1407 * @param array $attributes The attributes to modify. Note if you set the enabled attribute you must not specify any other attributes
1408 * @return bool
1409 */
1410 public function contact_modify($distinguishedname,$attributes){
1411 if ($distinguishedname===NULL){ return ("Missing compulsory field [distinguishedname]"); }
1412
1413 // Translate the update to the LDAP schema
1414 $mod=$this->adldap_schema($attributes);
1415
1416 // Check to see if this is an enabled status update
1417 if (!$mod){ return (false); }
1418
1419 // Do the update
1420 $result=ldap_modify($this->_conn,$distinguishedname,$mod);
1421 if ($result==false){ return (false); }
1422
1423 return (true);
1424 }
1425
1426 /**
1427 * Delete a contact
1428 *
1429 * @param string $distinguishedname The contact dn to delete (please be careful here!)
1430 * @return array
1431 */
1432 public function contact_delete($distinguishedname) {
1433 $result = $this->dn_delete($distinguishedname);
1434 if ($result!=true){ return (false); }
1435 return (true);
1436 }
1437
1438 /**
1439 * Return a list of all contacts
1440 *
1441 * @param bool $include_desc Include a description of a contact
1442 * @param string $search The search parameters
1443 * @param bool $sorted Whether to sort the results
1444 * @return array
1445 */
1446 public function all_contacts($include_desc = false, $search = "*", $sorted = true){
1447 if (!$this->_bind){ return (false); }
1448
1449 // Perform the search and grab all their details
1450 $filter = "(&(objectClass=contact)(cn=".$search."))";
1451 $fields=array("displayname","distinguishedname");
1452 $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);
1453 $entries = ldap_get_entries($this->_conn, $sr);
1454
1455 $users_array = array();
1456 for ($i=0; $i<$entries["count"]; $i++){
1457 if ($include_desc && strlen($entries[$i]["displayname"][0])>0){
1458 $users_array[ $entries[$i]["distinguishedname"][0] ] = $entries[$i]["displayname"][0];
1459 } elseif ($include_desc){
1460 $users_array[ $entries[$i]["distinguishedname"][0] ] = $entries[$i]["distinguishedname"][0];
1461 } else {
1462 array_push($users_array, $entries[$i]["distinguishedname"][0]);
1463 }
1464 }
1465 if ($sorted){ asort($users_array); }
1466 return ($users_array);
1467 }
1468
1469 //*****************************************************************************************************************
1470 // FOLDER FUNCTIONS
1471
1472 /**
1473 * Returns a folder listing for a specific OU
1474 * See http://adldap.sourceforge.net/wiki/doku.php?id=api_folder_functions
1475 *
1476 * @param array $folder_name An array to the OU you wish to list.
1477 * If set to NULL will list the root, strongly recommended to set
1478 * $recursive to false in that instance!
1479 * @param string $dn_type The type of record to list. This can be ADLDAP_FOLDER or ADLDAP_CONTAINER.
1480 * @param bool $recursive Recursively search sub folders
1481 * @param bool $type Specify a type of object to search for
1482 * @return array
1483 */
1484 public function folder_list($folder_name = NULL, $dn_type = ADLDAP_FOLDER, $recursive = NULL, $type = NULL) {
1485 if ($recursive===NULL){ $recursive=$this->_recursive_groups; } //use the default option if they haven't set it
1486 if (!$this->_bind){ return (false); }
1487
1488 $filter = '(&';
1489 if ($type !== NULL) {
1490 switch ($type) {
1491 case 'contact':
1492 $filter .= '(objectClass=contact)';
1493 break;
1494 case 'computer':
1495 $filter .= '(objectClass=computer)';
1496 break;
1497 case 'group':
1498 $filter .= '(objectClass=group)';
1499 break;
1500 case 'folder':
1501 $filter .= '(objectClass=organizationalUnit)';
1502 break;
1503 case 'container':
1504 $filter .= '(objectClass=container)';
1505 break;
1506 case 'domain':
1507 $filter .= '(objectClass=builtinDomain)';
1508 break;
1509 default:
1510 $filter .= '(objectClass=user)';
1511 break;
1512 }
1513 }
1514 else {
1515 $filter .= '(objectClass=*)';
1516 }
1517 // If the folder name is null then we will search the root level of AD
1518 // This requires us to not have an OU= part, just the base_dn
1519 $searchou = $this->_base_dn;
1520 if (is_array($folder_name)) {
1521 $ou = $dn_type . "=".implode("," . $dn_type . "=",$folder_name);
1522 $filter .= '(!(distinguishedname=' . $ou . ',' . $this->_base_dn . ')))';
1523 $searchou = $ou . ',' . $this->_base_dn;
1524 }
1525 else {
1526 $filter .= '(!(distinguishedname=' . $this->_base_dn . ')))';
1527 }
1528
1529 if ($recursive === true) {
1530 $sr=ldap_search($this->_conn, $searchou, $filter, array('objectclass', 'distinguishedname', 'samaccountname'));
1531 $entries = @ldap_get_entries($this->_conn, $sr);
1532 if (is_array($entries)) {
1533 return $entries;
1534 }
1535 }
1536 else {
1537 $sr=ldap_list($this->_conn, $searchou, $filter, array('objectclass', 'distinguishedname', 'samaccountname'));
1538 $entries = @ldap_get_entries($this->_conn, $sr);
1539 if (is_array($entries)) {
1540 return $entries;
1541 }
1542 }
1543
1544 return false;
1545 }
1546
1547 //*****************************************************************************************************************
1548 // COMPUTER FUNCTIONS
1549
1550 /**
1551 * Get information about a specific computer
1552 *
1553 * @param string $computer_name The name of the computer
1554 * @param array $fields Attributes to return
1555 * @return array
1556 */
1557 public function computer_info($computer_name,$fields=NULL){
1558 if ($computer_name===NULL){ return (false); }
1559 if (!$this->_bind){ return (false); }
1560
1561 $filter="(&(objectClass=computer)(cn=".$computer_name."))";
1562 if ($fields===NULL){ $fields=array("memberof","cn","displayname","dnshostname","distinguishedname","objectcategory","operatingsystem","operatingsystemservicepack","operatingsystemversion"); }
1563 $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);
1564 $entries = ldap_get_entries($this->_conn, $sr);
1565
1566 return ($entries);
1567 }
1568
1569 /**
1570 * Check if a computer is in a group
1571 *
1572 * @param string $computer_name The name of the computer
1573 * @param string $group The group to check
1574 * @param bool $recursive Whether to check recursively
1575 * @return array
1576 */
1577 public function computer_ingroup($computer_name,$group,$recursive=NULL){
1578 if ($computer_name===NULL){ return (false); }
1579 if ($group===NULL){ return (false); }
1580 if (!$this->_bind){ return (false); }
1581 if ($recursive===NULL){ $recursive=$this->_recursive_groups; } // use the default option if they haven't set it
1582
1583 //get a list of the groups
1584 $groups=$this->computer_groups($computer_name,array("memberof"),$recursive);
1585
1586 //return true if the specified group is in the group list
1587 if (in_array($group,$groups)){ return (true); }
1588
1589 return (false);
1590 }
1591
1592 /**
1593 * Get the groups a computer is in
1594 *
1595 * @param string $computer_name The name of the computer
1596 * @param bool $recursive Whether to check recursively
1597 * @return array
1598 */
1599 public function computer_groups($computer_name,$recursive=NULL){
1600 if ($computer_name===NULL){ return (false); }
1601 if ($recursive===NULL){ $recursive=$this->_recursive_groups; } //use the default option if they haven't set it
1602 if (!$this->_bind){ return (false); }
1603
1604 //search the directory for their information
1605 $info=@$this->computer_info($computer_name,array("memberof","primarygroupid"));
1606 $groups=$this->nice_names($info[0]["memberof"]); //presuming the entry returned is our guy (unique usernames)
1607
1608 if ($recursive === true){
1609 foreach ($groups as $id => $group_name){
1610 $extra_groups=$this->recursive_groups($group_name);
1611 $groups=array_merge($groups,$extra_groups);
1612 }
1613 }
1614
1615 return ($groups);
1616 }
1617
1618 //************************************************************************************************************
1619 // ORGANIZATIONAL UNIT FUNCTIONS
1620
1621 /**
1622 * Create an organizational unit
1623 *
1624 * @param array $attributes Default attributes of the ou
1625 * @return bool
1626 */
1627 public function ou_create($attributes){
1628 if (!is_array($attributes)){ return ("Attributes must be an array"); }
1629 if (!array_key_exists("ou_name",$attributes)){ return ("Missing compulsory field [ou_name]"); }
1630 if (!array_key_exists("container",$attributes)){ return ("Missing compulsory field [container]"); }
1631 if (!is_array($attributes["container"])){ return ("Container attribute must be an array."); }
1632 $attributes["container"]=array_reverse($attributes["container"]);
1633
1634 $add=array();
1635 $add["objectClass"] = "organizationalUnit";
1636
1637 $container="OU=".implode(",OU=",$attributes["container"]);
1638 $result=ldap_add($this->_conn,"CN=".$add["cn"].", ".$container.",".$this->_base_dn,$add);
1639 if ($result!=true){ return (false); }
1640
1641 return (true);
1642 }
1643
1644 //************************************************************************************************************
1645 // EXCHANGE FUNCTIONS
1646
1647 /**
1648 * Create an Exchange account
1649 *
1650 * @param string $username The username of the user to add the Exchange account to
1651 * @param array $storagegroup The mailbox, Exchange Storage Group, for the user account, this must be a full CN
1652 * If the storage group has a different base_dn to the adLDAP configuration, set it using $base_dn
1653 * @param string $emailaddress The primary email address to add to this user
1654 * @param string $mailnickname The mail nick name. If mail nickname is blank, the username will be used
1655 * @param bool $usedefaults Indicates whether the store should use the default quota, rather than the per-mailbox quota.
1656 * @param string $base_dn Specify an alternative base_dn for the Exchange storage group
1657 * @param bool $isGUID Is the username passed a GUID or a samAccountName
1658 * @return bool
1659 */
1660 public function exchange_create_mailbox($username, $storagegroup, $emailaddress, $mailnickname=NULL, $usedefaults=TRUE, $base_dn=NULL, $isGUID=false){
1661 if ($username===NULL){ return ("Missing compulsory field [username]"); }
1662 if ($storagegroup===NULL){ return ("Missing compulsory array [storagegroup]"); }
1663 if (!is_array($storagegroup)){ return ("[storagegroup] must be an array"); }
1664 if ($emailaddress===NULL){ return ("Missing compulsory field [emailaddress]"); }
1665
1666 if ($base_dn===NULL) {
1667 $base_dn = $this->_base_dn;
1668 }
1669
1670 $container="CN=".implode(",CN=",$storagegroup);
1671
1672 if ($mailnickname===NULL) { $mailnickname=$username; }
1673 $mdbUseDefaults = $this->bool2str($usedefaults);
1674
1675 $attributes = array(
1676 'exchange_homemdb'=>$container.",".$base_dn,
1677 'exchange_proxyaddress'=>'SMTP:' . $emailaddress,
1678 'exchange_mailnickname'=>$mailnickname,
1679 'exchange_usedefaults'=>$mdbUseDefaults
1680 );
1681 $result = $this->user_modify($username,$attributes,$isGUID);
1682 if ($result==false){ return (false); }
1683 return (true);
1684 }
1685
1686 /**
1687 * Add an X400 address to Exchange
1688 * See http://tools.ietf.org/html/rfc1685 for more information.
1689 * An X400 Address looks similar to this X400:c=US;a= ;p=Domain;o=Organization;s=Doe;g=John;
1690 *
1691 * @param string $username The username of the user to add the X400 to to
1692 * @param string $country Country
1693 * @param string $admd Administration Management Domain
1694 * @param string $pdmd Private Management Domain (often your AD domain)
1695 * @param string $org Organization
1696 * @param string $surname Surname
1697 * @param string $givenName Given name
1698 * @param bool $isGUID Is the username passed a GUID or a samAccountName
1699 * @return bool
1700 */
1701 public function exchange_add_X400($username, $country, $admd, $pdmd, $org, $surname, $givenname, $isGUID=false) {
1702 if ($username===NULL){ return ("Missing compulsory field [username]"); }
1703
1704 $proxyvalue = 'X400:';
1705
1706 // Find the dn of the user
1707 $user=$this->user_info($username,array("cn","proxyaddresses"), $isGUID);
1708 if ($user[0]["dn"]===NULL){ return (false); }
1709 $user_dn=$user[0]["dn"];
1710
1711 // We do not have to demote an email address from the default so we can just add the new proxy address
1712 $attributes['exchange_proxyaddress'] = $proxyvalue . 'c=' . $country . ';a=' . $admd . ';p=' . $pdmd . ';o=' . $org . ';s=' . $surname . ';g=' . $givenname . ';';
1713
1714 // Translate the update to the LDAP schema
1715 $add=$this->adldap_schema($attributes);
1716
1717 if (!$add){ return (false); }
1718
1719 // Do the update
1720 // Take out the @ to see any errors, usually this error might occur because the address already
1721 // exists in the list of proxyAddresses
1722 $result=@ldap_mod_add($this->_conn,$user_dn,$add);
1723 if ($result==false){ return (false); }
1724
1725 return (true);
1726 }
1727
1728 /**
1729 * Add an address to Exchange
1730 *
1731 * @param string $username The username of the user to add the Exchange account to
1732 * @param string $emailaddress The email address to add to this user
1733 * @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
1734 * @param bool $isGUID Is the username passed a GUID or a samAccountName
1735 * @return bool
1736 */
1737 public function exchange_add_address($username, $emailaddress, $default=FALSE, $isGUID=false) {
1738 if ($username===NULL){ return ("Missing compulsory field [username]"); }
1739 if ($emailaddress===NULL) { return ("Missing compulsory fields [emailaddress]"); }
1740
1741 $proxyvalue = 'smtp:';
1742 if ($default === true) {
1743 $proxyvalue = 'SMTP:';
1744 }
1745
1746 // Find the dn of the user
1747 $user=$this->user_info($username,array("cn","proxyaddresses"),$isGUID);
1748 if ($user[0]["dn"]===NULL){ return (false); }
1749 $user_dn=$user[0]["dn"];
1750
1751 // We need to scan existing proxy addresses and demote the default one
1752 if (is_array($user[0]["proxyaddresses"]) && $default===true) {
1753 $modaddresses = array();
1754 for ($i=0;$i<sizeof($user[0]['proxyaddresses']);$i++) {
1755 if (strstr($user[0]['proxyaddresses'][$i], 'SMTP:') !== false) {
1756 $user[0]['proxyaddresses'][$i] = str_replace('SMTP:', 'smtp:', $user[0]['proxyaddresses'][$i]);
1757 }
1758 if ($user[0]['proxyaddresses'][$i] != '') {
1759 $modaddresses['proxyAddresses'][$i] = $user[0]['proxyaddresses'][$i];
1760 }
1761 }
1762 $modaddresses['proxyAddresses'][(sizeof($user[0]['proxyaddresses'])-1)] = 'SMTP:' . $emailaddress;
1763
1764 $result=@ldap_mod_replace($this->_conn,$user_dn,$modaddresses);
1765 if ($result==false){ return (false); }
1766
1767 return (true);
1768 }
1769 else {
1770 // We do not have to demote an email address from the default so we can just add the new proxy address
1771 $attributes['exchange_proxyaddress'] = $proxyvalue . $emailaddress;
1772
1773 // Translate the update to the LDAP schema
1774 $add=$this->adldap_schema($attributes);
1775
1776 if (!$add){ return (false); }
1777
1778 // Do the update
1779 // Take out the @ to see any errors, usually this error might occur because the address already
1780 // exists in the list of proxyAddresses
1781 $result=@ldap_mod_add($this->_conn,$user_dn,$add);
1782 if ($result==false){ return (false); }
1783
1784 return (true);
1785 }
1786 }
1787
1788 /**
1789 * Remove an address to Exchange
1790 * If you remove a default address the account will no longer have a default,
1791 * we recommend changing the default address first
1792 *
1793 * @param string $username The username of the user to add the Exchange account to
1794 * @param string $emailaddress The email address to add to this user
1795 * @param bool $isGUID Is the username passed a GUID or a samAccountName
1796 * @return bool
1797 */
1798 public function exchange_del_address($username, $emailaddress, $isGUID=false) {
1799 if ($username===NULL){ return ("Missing compulsory field [username]"); }
1800 if ($emailaddress===NULL) { return ("Missing compulsory fields [emailaddress]"); }
1801
1802 // Find the dn of the user
1803 $user=$this->user_info($username,array("cn","proxyaddresses"),$isGUID);
1804 if ($user[0]["dn"]===NULL){ return (false); }
1805 $user_dn=$user[0]["dn"];
1806
1807 if (is_array($user[0]["proxyaddresses"])) {
1808 $mod = array();
1809 for ($i=0;$i<sizeof($user[0]['proxyaddresses']);$i++) {
1810 if (strstr($user[0]['proxyaddresses'][$i], 'SMTP:') !== false && $user[0]['proxyaddresses'][$i] == 'SMTP:' . $emailaddress) {
1811 $mod['proxyAddresses'][0] = 'SMTP:' . $emailaddress;
1812 }
1813 elseif (strstr($user[0]['proxyaddresses'][$i], 'smtp:') !== false && $user[0]['proxyaddresses'][$i] == 'smtp:' . $emailaddress) {
1814 $mod['proxyAddresses'][0] = 'smtp:' . $emailaddress;
1815 }
1816 }
1817
1818 $result=@ldap_mod_del($this->_conn,$user_dn,$mod);
1819 if ($result==false){ return (false); }
1820
1821 return (true);
1822 }
1823 else {
1824 return (false);
1825 }
1826 }
1827 /**
1828 * Change the default address
1829 *
1830 * @param string $username The username of the user to add the Exchange account to
1831 * @param string $emailaddress The email address to make default
1832 * @param bool $isGUID Is the username passed a GUID or a samAccountName
1833 * @return bool
1834 */
1835 public function exchange_primary_address($username, $emailaddress, $isGUID=false) {
1836 if ($username===NULL){ return ("Missing compulsory field [username]"); }
1837 if ($emailaddress===NULL) { return ("Missing compulsory fields [emailaddress]"); }
1838
1839 // Find the dn of the user
1840 $user=$this->user_info($username,array("cn","proxyaddresses"), $isGUID);
1841 if ($user[0]["dn"]===NULL){ return (false); }
1842 $user_dn=$user[0]["dn"];
1843
1844 if (is_array($user[0]["proxyaddresses"])) {
1845 $modaddresses = array();
1846 for ($i=0;$i<sizeof($user[0]['proxyaddresses']);$i++) {
1847 if (strstr($user[0]['proxyaddresses'][$i], 'SMTP:') !== false) {
1848 $user[0]['proxyaddresses'][$i] = str_replace('SMTP:', 'smtp:', $user[0]['proxyaddresses'][$i]);
1849 }
1850 if ($user[0]['proxyaddresses'][$i] == 'smtp:' . $emailaddress) {
1851 $user[0]['proxyaddresses'][$i] = str_replace('smtp:', 'SMTP:', $user[0]['proxyaddresses'][$i]);
1852 }
1853 if ($user[0]['proxyaddresses'][$i] != '') {
1854 $modaddresses['proxyAddresses'][$i] = $user[0]['proxyaddresses'][$i];
1855 }
1856 }
1857
1858 $result=@ldap_mod_replace($this->_conn,$user_dn,$modaddresses);
1859 if ($result==false){ return (false); }
1860
1861 return (true);
1862 }
1863
1864 }
1865
1866 /**
1867 * Mail enable a contact
1868 * Allows email to be sent to them through Exchange
1869 *
1870 * @param string $distinguishedname The contact to mail enable
1871 * @param string $emailaddress The email address to allow emails to be sent through
1872 * @param string $mailnickname The mailnickname for the contact in Exchange. If NULL this will be set to the display name
1873 * @return bool
1874 */
1875 public function exchange_contact_mailenable($distinguishedname, $emailaddress, $mailnickname=NULL){
1876 if ($distinguishedname===NULL){ return ("Missing compulsory field [distinguishedname]"); }
1877 if ($emailaddress===NULL){ return ("Missing compulsory field [emailaddress]"); }
1878
1879 if ($mailnickname !== NULL) {
1880 // Find the dn of the user
1881 $user=$this->contact_info($distinguishedname,array("cn","displayname"));
1882 if ($user[0]["displayname"]===NULL){ return (false); }
1883 $mailnickname = $user[0]['displayname'][0];
1884 }
1885
1886 $attributes = array("email"=>$emailaddress,"contact_email"=>"SMTP:" . $emailaddress,"exchange_proxyaddress"=>"SMTP:" . $emailaddress,"exchange_mailnickname"=>$mailnickname);
1887
1888 // Translate the update to the LDAP schema
1889 $mod=$this->adldap_schema($attributes);
1890
1891 // Check to see if this is an enabled status update
1892 if (!$mod){ return (false); }
1893
1894 // Do the update
1895 $result=ldap_modify($this->_conn,$distinguishedname,$mod);
1896 if ($result==false){ return (false); }
1897
1898 return (true);
1899 }
1900
1901 /**
1902 * Returns a list of Exchange Servers in the ConfigurationNamingContext of the domain
1903 *
1904 * @param array $attributes An array of the AD attributes you wish to return
1905 * @return array
1906 */
1907 public function exchange_servers($attributes = array('cn','distinguishedname','serialnumber')) {
1908 if (!$this->_bind){ return (false); }
1909
1910 $configurationNamingContext = $this->get_root_dse(array('configurationnamingcontext'));
1911 $sr = @ldap_search($this->_conn,$configurationNamingContext[0]['configurationnamingcontext'][0],'(&(objectCategory=msExchExchangeServer))',$attributes);
1912 $entries = @ldap_get_entries($this->_conn, $sr);
1913 return $entries;
1914 }
1915
1916 /**
1917 * Returns a list of Storage Groups in Exchange for a given mail server
1918 *
1919 * @param string $exchangeServer The full DN of an Exchange server. You can use exchange_servers() to find the DN for your server
1920 * @param array $attributes An array of the AD attributes you wish to return
1921 * @param bool $recursive If enabled this will automatically query the databases within a storage group
1922 * @return array
1923 */
1924 public function exchange_storage_groups($exchangeServer, $attributes = array('cn','distinguishedname'), $recursive = NULL) {
1925 if (!$this->_bind){ return (false); }
1926 if ($exchangeServer===NULL){ return ("Missing compulsory field [exchangeServer]"); }
1927 if ($recursive===NULL){ $recursive=$this->_recursive_groups; }
1928
1929 $filter = '(&(objectCategory=msExchStorageGroup))';
1930 $sr=@ldap_search($this->_conn, $exchangeServer, $filter, $attributes);
1931 $entries = @ldap_get_entries($this->_conn, $sr);
1932
1933 if ($recursive === true) {
1934 for ($i=0; $i<$entries['count']; $i++) {
1935 $entries[$i]['msexchprivatemdb'] = $this->exchange_storage_databases($entries[$i]['distinguishedname'][0]);
1936 }
1937 }
1938
1939 return $entries;
1940 }
1941
1942 /**
1943 * Returns a list of Databases within any given storage group in Exchange for a given mail server
1944 *
1945 * @param string $storageGroup The full DN of an Storage Group. You can use exchange_storage_groups() to find the DN
1946 * @param array $attributes An array of the AD attributes you wish to return
1947 * @return array
1948 */
1949 public function exchange_storage_databases($storageGroup, $attributes = array('cn','distinguishedname','displayname')) {
1950 if (!$this->_bind){ return (false); }
1951 if ($storageGroup===NULL){ return ("Missing compulsory field [storageGroup]"); }
1952
1953 $filter = '(&(objectCategory=msExchPrivateMDB))';
1954 $sr=@ldap_search($this->_conn, $storageGroup, $filter, $attributes);
1955 $entries = @ldap_get_entries($this->_conn, $sr);
1956 return $entries;
1957 }
1958
1959 //************************************************************************************************************
1960 // SERVER FUNCTIONS
1961
1962 /**
1963 * Find the Base DN of your domain controller
1964 *
1965 * @return string
1966 */
1967 public function find_base_dn() {
1968 $namingContext = $this->get_root_dse(array('defaultnamingcontext'));
1969 return $namingContext[0]['defaultnamingcontext'][0];
1970 }
1971
1972 /**
1973 * Get the RootDSE properties from a domain controller
1974 *
1975 * @param array $attributes The attributes you wish to query e.g. defaultnamingcontext
1976 * @return array
1977 */
1978 public function get_root_dse($attributes = array("*", "+")) {
1979 if (!$this->_bind){ return (false); }
1980
1981 $sr = @ldap_read($this->_conn, NULL, 'objectClass=*', $attributes);
1982 $entries = @ldap_get_entries($this->_conn, $sr);
1983 return $entries;
1984 }
1985
1986 //************************************************************************************************************
1987 // UTILITY FUNCTIONS (Many of these functions are protected and can only be called from within the class)
1988
1989 /**
1990 * Get last error from Active Directory
1991 *
1992 * This function gets the last message from Active Directory
1993 * This may indeed be a 'Success' message but if you get an unknown error
1994 * it might be worth calling this function to see what errors were raised
1995 *
1996 * return string
1997 */
1998 public function get_last_error() {
1999 return @ldap_error($this->_conn);
2000 }
2001
2002 /**
2003 * Detect LDAP support in php
2004 *
2005 * @return bool
2006 */
2007 protected function ldap_supported() {
2008 if (!function_exists('ldap_connect')) {
2009 return (false);
2010 }
2011 return (true);
2012 }
2013
2014 /**
2015 * Schema
2016 *
2017 * @param array $attributes Attributes to be queried
2018 * @return array
2019 */
2020 protected function adldap_schema($attributes){
2021
2022 // LDAP doesn't like NULL attributes, only set them if they have values
2023 // If you wish to remove an attribute you should set it to a space
2024 // TO DO: Adapt user_modify to use ldap_mod_delete to remove a NULL attribute
2025 $mod=array();
2026
2027 // Check every attribute to see if it contains 8bit characters and then UTF8 encode them
2028 array_walk($attributes, array($this, 'encode8bit'));
2029
2030 if ($attributes["address_city"]){ $mod["l"][0]=$attributes["address_city"]; }
2031 if ($attributes["address_code"]){ $mod["postalCode"][0]=$attributes["address_code"]; }
2032 //if ($attributes["address_country"]){ $mod["countryCode"][0]=$attributes["address_country"]; } // use country codes?
2033 if ($attributes["address_country"]){ $mod["c"][0]=$attributes["address_country"]; }
2034 if ($attributes["address_pobox"]){ $mod["postOfficeBox"][0]=$attributes["address_pobox"]; }
2035 if ($attributes["address_state"]){ $mod["st"][0]=$attributes["address_state"]; }
2036 if ($attributes["address_street"]){ $mod["streetAddress"][0]=$attributes["address_street"]; }
2037 if ($attributes["company"]){ $mod["company"][0]=$attributes["company"]; }
2038 if ($attributes["change_password"]){ $mod["pwdLastSet"][0]=0; }
2039 if ($attributes["department"]){ $mod["department"][0]=$attributes["department"]; }
2040 if ($attributes["description"]){ $mod["description"][0]=$attributes["description"]; }
2041 if ($attributes["display_name"]){ $mod["displayName"][0]=$attributes["display_name"]; }
2042 if ($attributes["email"]){ $mod["mail"][0]=$attributes["email"]; }
2043 if ($attributes["expires"]){ $mod["accountExpires"][0]=$attributes["expires"]; } //unix epoch format?
2044 if ($attributes["firstname"]){ $mod["givenName"][0]=$attributes["firstname"]; }
2045 if ($attributes["home_directory"]){ $mod["homeDirectory"][0]=$attributes["home_directory"]; }
2046 if ($attributes["home_drive"]){ $mod["homeDrive"][0]=$attributes["home_drive"]; }
2047 if ($attributes["initials"]){ $mod["initials"][0]=$attributes["initials"]; }
2048 if ($attributes["logon_name"]){ $mod["userPrincipalName"][0]=$attributes["logon_name"]; }
2049 if ($attributes["manager"]){ $mod["manager"][0]=$attributes["manager"]; } //UNTESTED ***Use DistinguishedName***
2050 if ($attributes["office"]){ $mod["physicalDeliveryOfficeName"][0]=$attributes["office"]; }
2051 if ($attributes["password"]){ $mod["unicodePwd"][0]=$this->encode_password($attributes["password"]); }
2052 if ($attributes["profile_path"]){ $mod["profilepath"][0]=$attributes["profile_path"]; }
2053 if ($attributes["script_path"]){ $mod["scriptPath"][0]=$attributes["script_path"]; }
2054 if ($attributes["surname"]){ $mod["sn"][0]=$attributes["surname"]; }
2055 if ($attributes["title"]){ $mod["title"][0]=$attributes["title"]; }
2056 if ($attributes["telephone"]){ $mod["telephoneNumber"][0]=$attributes["telephone"]; }
2057 if ($attributes["mobile"]){ $mod["mobile"][0]=$attributes["mobile"]; }
2058 if ($attributes["pager"]){ $mod["pager"][0]=$attributes["pager"]; }
2059 if ($attributes["ipphone"]){ $mod["ipphone"][0]=$attributes["ipphone"]; }
2060 if ($attributes["web_page"]){ $mod["wWWHomePage"][0]=$attributes["web_page"]; }
2061 if ($attributes["fax"]){ $mod["facsimileTelephoneNumber"][0]=$attributes["fax"]; }
2062 if ($attributes["enabled"]){ $mod["userAccountControl"][0]=$attributes["enabled"]; }
2063
2064 // Distribution List specific schema
2065 if ($attributes["group_sendpermission"]){ $mod["dlMemSubmitPerms"][0]=$attributes["group_sendpermission"]; }
2066 if ($attributes["group_rejectpermission"]){ $mod["dlMemRejectPerms"][0]=$attributes["group_rejectpermission"]; }
2067
2068 // Exchange Schema
2069 if ($attributes["exchange_homemdb"]){ $mod["homeMDB"][0]=$attributes["exchange_homemdb"]; }
2070 if ($attributes["exchange_mailnickname"]){ $mod["mailNickname"][0]=$attributes["exchange_mailnickname"]; }
2071 if ($attributes["exchange_proxyaddress"]){ $mod["proxyAddresses"][0]=$attributes["exchange_proxyaddress"]; }
2072 if ($attributes["exchange_usedefaults"]){ $mod["mDBUseDefaults"][0]=$attributes["exchange_usedefaults"]; }
2073 if ($attributes["exchange_policyexclude"]){ $mod["msExchPoliciesExcluded"][0]=$attributes["exchange_policyexclude"]; }
2074 if ($attributes["exchange_policyinclude"]){ $mod["msExchPoliciesIncluded"][0]=$attributes["exchange_policyinclude"]; }
2075 if ($attributes["exchange_addressbook"]){ $mod["showInAddressBook"][0]=$attributes["exchange_addressbook"]; }
2076
2077 // This schema is designed for contacts
2078 if ($attributes["exchange_hidefromlists"]){ $mod["msExchHideFromAddressLists"][0]=$attributes["exchange_hidefromlists"]; }
2079 if ($attributes["contact_email"]){ $mod["targetAddress"][0]=$attributes["contact_email"]; }
2080
2081 //echo ("<pre>"); print_r($mod);
2082 /*
2083 // modifying a name is a bit fiddly
2084 if ($attributes["firstname"] && $attributes["surname"]){
2085 $mod["cn"][0]=$attributes["firstname"]." ".$attributes["surname"];
2086 $mod["displayname"][0]=$attributes["firstname"]." ".$attributes["surname"];
2087 $mod["name"][0]=$attributes["firstname"]." ".$attributes["surname"];
2088 }
2089 */
2090
2091 if (count($mod)==0){ return (false); }
2092 return ($mod);
2093 }
2094
2095 /**
2096 * Coping with AD not returning the primary group
2097 * http://support.microsoft.com/?kbid=321360
2098 *
2099 * For some reason it's not possible to search on primarygrouptoken=XXX
2100 * If someone can show otherwise, I'd like to know about it :)
2101 * this way is resource intensive and generally a pain in the @#%^
2102 *
2103 * @deprecated deprecated since version 3.1, see get get_primary_group
2104 * @param string $gid Group ID
2105 * @return string
2106 */
2107 protected function group_cn($gid){
2108 if ($gid===NULL){ return (false); }
2109 $r=false;
2110
2111 $filter="(&(objectCategory=group)(samaccounttype=". ADLDAP_SECURITY_GLOBAL_GROUP ."))";
2112 $fields=array("primarygrouptoken","samaccountname","distinguishedname");
2113 $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);
2114 $entries = ldap_get_entries($this->_conn, $sr);
2115
2116 for ($i=0; $i<$entries["count"]; $i++){
2117 if ($entries[$i]["primarygrouptoken"][0]==$gid){
2118 $r=$entries[$i]["distinguishedname"][0];
2119 $i=$entries["count"];
2120 }
2121 }
2122
2123 return ($r);
2124 }
2125
2126 /**
2127 * Coping with AD not returning the primary group
2128 * http://support.microsoft.com/?kbid=321360
2129 *
2130 * This is a re-write based on code submitted by Bruce which prevents the
2131 * need to search each security group to find the true primary group
2132 *
2133 * @param string $gid Group ID
2134 * @param string $usersid User's Object SID
2135 * @return string
2136 */
2137 protected function get_primary_group($gid, $usersid){
2138 if ($gid===NULL || $usersid===NULL){ return (false); }
2139 $r=false;
2140
2141 $gsid = substr_replace($usersid,pack('V',$gid),strlen($usersid)-4,4);
2142 $filter='(objectsid='.$this->getTextSID($gsid).')';
2143 $fields=array("samaccountname","distinguishedname");
2144 $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);
2145 $entries = ldap_get_entries($this->_conn, $sr);
2146
2147 return $entries[0]['distinguishedname'][0];
2148 }
2149
2150 /**
2151 * Convert a binary SID to a text SID
2152 *
2153 * @param string $binsid A Binary SID
2154 * @return string
2155 */
2156 protected function getTextSID($binsid) {
2157 $hex_sid = bin2hex($binsid);
2158 $rev = hexdec(substr($hex_sid, 0, 2));
2159 $subcount = hexdec(substr($hex_sid, 2, 2));
2160 $auth = hexdec(substr($hex_sid, 4, 12));
2161 $result = "$rev-$auth";
2162
2163 for ($x=0;$x < $subcount; $x++) {
2164 $subauth[$x] =
2165 hexdec($this->little_endian(substr($hex_sid, 16 + ($x * 8), 8)));
2166 $result .= "-" . $subauth[$x];
2167 }
2168
2169 // Cheat by tacking on the S-
2170 return 'S-' . $result;
2171 }
2172
2173 /**
2174 * Converts a little-endian hex number to one that hexdec() can convert
2175 *
2176 * @param string $hex A hex code
2177 * @return string
2178 */
2179 protected function little_endian($hex) {
2180 $result = '';
2181 for ($x = strlen($hex) - 2; $x >= 0; $x = $x - 2) {
2182 $result .= substr($hex, $x, 2);
2183 }
2184 return $result;
2185 }
2186
2187 /**
2188 * Converts a binary attribute to a string
2189 *
2190 * @param string $bin A binary LDAP attribute
2191 * @return string
2192 */
2193 protected function binary2text($bin) {
2194 $hex_guid = bin2hex($bin);
2195 $hex_guid_to_guid_str = '';
2196 for($k = 1; $k <= 4; ++$k) {
2197 $hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
2198 }
2199 $hex_guid_to_guid_str .= '-';
2200 for($k = 1; $k <= 2; ++$k) {
2201 $hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
2202 }
2203 $hex_guid_to_guid_str .= '-';
2204 for($k = 1; $k <= 2; ++$k) {
2205 $hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
2206 }
2207 $hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
2208 $hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);
2209 return strtoupper($hex_guid_to_guid_str);
2210 }
2211
2212 /**
2213 * Converts a binary GUID to a string GUID
2214 *
2215 * @param string $binaryGuid The binary GUID attribute to convert
2216 * @return string
2217 */
2218 public function decodeGuid($binaryGuid) {
2219 if ($binaryGuid === null){ return ("Missing compulsory field [binaryGuid]"); }
2220
2221 $strGUID = $this->binary2text($binaryGuid);
2222 return ($strGUID);
2223 }
2224
2225 /**
2226 * Converts a string GUID to a hexdecimal value so it can be queried
2227 *
2228 * @param string $strGUID A string representation of a GUID
2229 * @return string
2230 */
2231 protected function strguid2hex($strGUID) {
2232 $strGUID = str_replace('-', '', $strGUID);
2233
2234 $octet_str = '\\' . substr($strGUID, 6, 2);
2235 $octet_str .= '\\' . substr($strGUID, 4, 2);
2236 $octet_str .= '\\' . substr($strGUID, 2, 2);
2237 $octet_str .= '\\' . substr($strGUID, 0, 2);
2238 $octet_str .= '\\' . substr($strGUID, 10, 2);
2239 $octet_str .= '\\' . substr($strGUID, 8, 2);
2240 $octet_str .= '\\' . substr($strGUID, 14, 2);
2241 $octet_str .= '\\' . substr($strGUID, 12, 2);
2242 //$octet_str .= '\\' . substr($strGUID, 16, strlen($strGUID));
2243 for ($i=16; $i<=(strlen($strGUID)-2); $i++) {
2244 if (($i % 2) == 0) {
2245 $octet_str .= '\\' . substr($strGUID, $i, 2);
2246 }
2247 }
2248
2249 return $octet_str;
2250 }
2251
2252 /**
2253 * Obtain the user's distinguished name based on their userid
2254 *
2255 *
2256 * @param string $username The username
2257 * @param bool $isGUID Is the username passed a GUID or a samAccountName
2258 * @return string
2259 */
2260 protected function user_dn($username,$isGUID=false){
2261 $user=$this->user_info($username,array("cn"),$isGUID);
2262 if ($user[0]["dn"]===NULL){ return (false); }
2263 $user_dn=$user[0]["dn"];
2264 return ($user_dn);
2265 }
2266
2267 /**
2268 * Encode a password for transmission over LDAP
2269 *
2270 * @param string $password The password to encode
2271 * @return string
2272 */
2273 protected function encode_password($password){
2274 $password="\"".$password."\"";
2275 $encoded="";
2276 for ($i=0; $i <strlen($password); $i++){ $encoded.="{$password{$i}}\000"; }
2277 return ($encoded);
2278 }
2279
2280 /**
2281 * Escape strings for the use in LDAP filters
2282 *
2283 * DEVELOPERS SHOULD BE DOING PROPER FILTERING IF THEY'RE ACCEPTING USER INPUT
2284 * Ported from Perl's Net::LDAP::Util escape_filter_value
2285 *
2286 * @param string $str The string the parse
2287 * @author Port by Andreas Gohr <[email protected]>
2288 * @return string
2289 */
2290 protected function ldap_slashes($str){
2291 return preg_replace('/([\x00-\x1F\*\(\)\\\\])/e',
2292 '"\\\\\".join("",unpack("H2","$1"))',
2293 $str);
2294 }
2295
2296 /**
2297 * Select a random domain controller from your domain controller array
2298 *
2299 * @return string
2300 */
2301 protected function random_controller(){
2302 mt_srand(doubleval(microtime()) * 100000000); // For older PHP versions
2303 return ($this->_domain_controllers[array_rand($this->_domain_controllers)]);
2304 }
2305
2306 /**
2307 * Account control options
2308 *
2309 * @param array $options The options to convert to int
2310 * @return int
2311 */
2312 protected function account_control($options){
2313 $val=0;
2314
2315 if (is_array($options)){
2316 if (in_array("SCRIPT",$options)){ $val=$val+1; }
2317 if (in_array("ACCOUNTDISABLE",$options)){ $val=$val+2; }
2318 if (in_array("HOMEDIR_REQUIRED",$options)){ $val=$val+8; }
2319 if (in_array("LOCKOUT",$options)){ $val=$val+16; }
2320 if (in_array("PASSWD_NOTREQD",$options)){ $val=$val+32; }
2321 //PASSWD_CANT_CHANGE Note You cannot assign this permission by directly modifying the UserAccountControl attribute.
2322 //For information about how to set the permission programmatically, see the "Property flag descriptions" section.
2323 if (in_array("ENCRYPTED_TEXT_PWD_ALLOWED",$options)){ $val=$val+128; }
2324 if (in_array("TEMP_DUPLICATE_ACCOUNT",$options)){ $val=$val+256; }
2325 if (in_array("NORMAL_ACCOUNT",$options)){ $val=$val+512; }
2326 if (in_array("INTERDOMAIN_TRUST_ACCOUNT",$options)){ $val=$val+2048; }
2327 if (in_array("WORKSTATION_TRUST_ACCOUNT",$options)){ $val=$val+4096; }
2328 if (in_array("SERVER_TRUST_ACCOUNT",$options)){ $val=$val+8192; }
2329 if (in_array("DONT_EXPIRE_PASSWORD",$options)){ $val=$val+65536; }
2330 if (in_array("MNS_LOGON_ACCOUNT",$options)){ $val=$val+131072; }
2331 if (in_array("SMARTCARD_REQUIRED",$options)){ $val=$val+262144; }
2332 if (in_array("TRUSTED_FOR_DELEGATION",$options)){ $val=$val+524288; }
2333 if (in_array("NOT_DELEGATED",$options)){ $val=$val+1048576; }
2334 if (in_array("USE_DES_KEY_ONLY",$options)){ $val=$val+2097152; }
2335 if (in_array("DONT_REQ_PREAUTH",$options)){ $val=$val+4194304; }
2336 if (in_array("PASSWORD_EXPIRED",$options)){ $val=$val+8388608; }
2337 if (in_array("TRUSTED_TO_AUTH_FOR_DELEGATION",$options)){ $val=$val+16777216; }
2338 }
2339 return ($val);
2340 }
2341
2342 /**
2343 * Take an LDAP query and return the nice names, without all the LDAP prefixes (eg. CN, DN)
2344 *
2345 * @param array $groups
2346 * @return array
2347 */
2348 protected function nice_names($groups){
2349
2350 $group_array=array();
2351 for ($i=0; $i<$groups["count"]; $i++){ // For each group
2352 $line=$groups[$i];
2353
2354 if (strlen($line)>0){
2355 // More presumptions, they're all prefixed with CN=
2356 // so we ditch the first three characters and the group
2357 // name goes up to the first comma
2358 $bits=explode(",",$line);
2359 $group_array[]=substr($bits[0],3,(strlen($bits[0])-3));
2360 }
2361 }
2362 return ($group_array);
2363 }
2364
2365 /**
2366 * Delete a distinguished name from Active Directory
2367 * You should never need to call this yourself, just use the wrapper functions user_delete and contact_delete
2368 *
2369 * @param string $dn The distinguished name to delete
2370 * @return bool
2371 */
2372 protected function dn_delete($dn){
2373 $result=ldap_delete($this->_conn, $dn);
2374 if ($result!=true){ return (false); }
2375 return (true);
2376 }
2377
2378 /**
2379 * Convert a boolean value to a string
2380 * You should never need to call this yourself
2381 *
2382 * @param bool $bool Boolean value
2383 * @return string
2384 */
2385 protected function bool2str($bool) {
2386 return ($bool) ? 'TRUE' : 'FALSE';
2387 }
2388
2389 /**
2390 * Convert 8bit characters e.g. accented characters to UTF8 encoded characters
2391 */
2392 protected function encode8bit(&$item, $key) {
2393 $encode = false;
2394 if (is_string($item)) {
2395 for ($i=0; $i<strlen($item); $i++) {
2396 if (ord($item[$i]) >> 7) {
2397 $encode = true;
2398 }
2399 }
2400 }
2401 if ($encode === true && $key != 'password') {
2402 $item = utf8_encode($item);
2403 }
2404 }
2405}
2406
2407/**
2408* adLDAP Exception Handler
2409*
2410* Exceptions of this type are thrown on bind failure or when SSL is required but not configured
2411* Example:
2412* try {
2413* $adldap = new adLDAP();
2414* }
2415* catch (adLDAPException $e) {
2416* echo $e;
2417* exit();
2418* }
2419*/
2420class adLDAPException extends Exception {}
2421
2422?>
Note: See TracBrowser for help on using the repository browser.