diff options
46 files changed, 6312 insertions, 4526 deletions
diff --git a/.gitignore b/.gitignore index 1daf647bf..c725108c4 100644 --- a/.gitignore +++ b/.gitignore @@ -31,6 +31,11 @@ !/lib/tpl/dokuwiki !/lib/tpl/index.php /lib/plugins/* +!/lib/plugins/authad +!/lib/plugins/authldap +!/lib/plugins/authmysql +!/lib/plugins/authpgsql +!/lib/plugins/authplain !/lib/plugins/acl !/lib/plugins/config !/lib/plugins/info diff --git a/_test/bootstrap.php b/_test/bootstrap.php index 310b3627a..732fef9ed 100644 --- a/_test/bootstrap.php +++ b/_test/bootstrap.php @@ -27,6 +27,7 @@ define('DOKU_TMP_DATA', TMP_DIR.'/data/'); // default plugins $default_plugins = array( + 'authplain', 'acl', 'config', 'info', diff --git a/_test/tests/inc/auth_aclcheck.test.php b/_test/tests/inc/auth_aclcheck.test.php index 991f82da7..5dc0d7f60 100644 --- a/_test/tests/inc/auth_aclcheck.test.php +++ b/_test/tests/inc/auth_aclcheck.test.php @@ -11,7 +11,7 @@ class auth_acl_test extends DokuWikiTest { global $auth; $this->oldConf = $conf; $this->oldAuthAcl = $AUTH_ACL; - $auth = new auth_basic(); + $auth = new DokuWiki_Auth_Plugin(); } function teardown() { diff --git a/_test/tests/inc/auth_admincheck.test.php b/_test/tests/inc/auth_admincheck.test.php index d88399cbe..2fb5902d7 100644 --- a/_test/tests/inc/auth_admincheck.test.php +++ b/_test/tests/inc/auth_admincheck.test.php @@ -1,6 +1,6 @@ <?php -class auth_admin_test_AuthInSensitive extends auth_basic { +class auth_admin_test_AuthInSensitive extends DokuWiki_Auth_Plugin { function isCaseSensitive(){ return false; } @@ -17,7 +17,7 @@ class auth_admin_test extends DokuWikiTest { function setSensitive() { global $auth; - $auth = new auth_basic(); + $auth = new DokuWiki_Auth_Plugin(); } function setInSensitive() { diff --git a/_test/tests/inc/remote.test.php b/_test/tests/inc/remote.test.php index 49152d8db..c3d941a2c 100644 --- a/_test/tests/inc/remote.test.php +++ b/_test/tests/inc/remote.test.php @@ -1,6 +1,6 @@ <?php -class MockAuth extends auth_basic { +class MockAuth extends DokuWiki_Auth_Plugin { function isCaseSensitive() { return true; } } diff --git a/conf/dokuwiki.php b/conf/dokuwiki.php index cbd42115d..f5524de6b 100644 --- a/conf/dokuwiki.php +++ b/conf/dokuwiki.php @@ -54,7 +54,7 @@ $conf['hidepages'] = ''; //Regexp for pages to be skipped from /* Authentication Settings */ $conf['useacl'] = 0; //Use Access Control Lists to restrict access? $conf['autopasswd'] = 1; //autogenerate passwords and email them to user -$conf['authtype'] = 'plain'; //which authentication backend should be used +$conf['authtype'] = 'authplain'; //which authentication backend should be used $conf['passcrypt'] = 'smd5'; //Used crypt method (smd5,md5,sha1,ssha,crypt,mysql,my411) $conf['defaultgroup']= 'user'; //Default groups new Users are added to $conf['superuser'] = '!!not set!!'; //The admin can be user or @group or comma separated list user1,@group1,user2 diff --git a/inc/adLDAP.php b/inc/adLDAP.php deleted file mode 100644 index 24be6e475..000000000 --- a/inc/adLDAP.php +++ /dev/null @@ -1,2442 +0,0 @@ -<?php -/** - * PHP LDAP CLASS FOR MANIPULATING ACTIVE DIRECTORY - * Version 3.3.2 - * - * PHP Version 5 with SSL and LDAP support - * - * Written by Scott Barnett, Richard Hyland - * email: scott@wiggumworld.com, adldap@richardhyland.com - * http://adldap.sourceforge.net/ - * - * Copyright (c) 2006-2010 Scott Barnett, Richard Hyland - * - * We'd appreciate any improvements or additions to be submitted back - * to benefit the entire community :) - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * @category ToolsAndUtilities - * @package adLDAP - * @author Scott Barnett, Richard Hyland - * @copyright (c) 2006-2010 Scott Barnett, Richard Hyland - * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html LGPLv2.1 - * @revision $Revision: 91 $ - * @version 3.3.2 - * @link http://adldap.sourceforge.net/ - */ - -/** - * Define the different types of account in AD - */ -define ('ADLDAP_NORMAL_ACCOUNT', 805306368); -define ('ADLDAP_WORKSTATION_TRUST', 805306369); -define ('ADLDAP_INTERDOMAIN_TRUST', 805306370); -define ('ADLDAP_SECURITY_GLOBAL_GROUP', 268435456); -define ('ADLDAP_DISTRIBUTION_GROUP', 268435457); -define ('ADLDAP_SECURITY_LOCAL_GROUP', 536870912); -define ('ADLDAP_DISTRIBUTION_LOCAL_GROUP', 536870913); -define ('ADLDAP_FOLDER', 'OU'); -define ('ADLDAP_CONTAINER', 'CN'); - -/** -* Main adLDAP class -* -* Can be initialised using $adldap = new adLDAP(); -* -* Something to keep in mind is that Active Directory is a permissions -* based directory. If you bind as a domain user, you can't fetch as -* much information on other users as you could as a domain admin. -* -* Before asking questions, please read the Documentation at -* http://adldap.sourceforge.net/wiki/doku.php?id=api -*/ -class adLDAP { - /** - * The account suffix for your domain, can be set when the class is invoked - * - * @var string - */ - protected $_account_suffix = "@mydomain.local"; - - /** - * The base dn for your domain - * - * @var string - */ - protected $_base_dn = "DC=mydomain,DC=local"; - - /** - * Array of domain controllers. Specifiy multiple controllers if you - * would like the class to balance the LDAP queries amongst multiple servers - * - * @var array - */ - protected $_domain_controllers = array ("dc01.mydomain.local"); - - /** - * Optional account with higher privileges for searching - * This should be set to a domain admin account - * - * @var string - * @var string - */ - protected $_ad_username=NULL; - protected $_ad_password=NULL; - - /** - * AD does not return the primary group. http://support.microsoft.com/?kbid=321360 - * This tweak will resolve the real primary group. - * Setting to false will fudge "Domain Users" and is much faster. Keep in mind though that if - * someone's primary group is NOT domain users, this is obviously going to mess up the results - * - * @var bool - */ - protected $_real_primarygroup=true; - - /** - * Use SSL (LDAPS), your server needs to be setup, please see - * http://adldap.sourceforge.net/wiki/doku.php?id=ldap_over_ssl - * - * @var bool - */ - protected $_use_ssl=false; - - /** - * Use TLS - * If you wish to use TLS you should ensure that $_use_ssl is set to false and vice-versa - * - * @var bool - */ - protected $_use_tls=false; - - /** - * When querying group memberships, do it recursively - * eg. User Fred is a member of Group A, which is a member of Group B, which is a member of Group C - * user_ingroup("Fred","C") will returns true with this option turned on, false if turned off - * - * @var bool - */ - protected $_recursive_groups=true; - - // You should not need to edit anything below this line - //****************************************************************************************** - - /** - * Connection and bind default variables - * - * @var mixed - * @var mixed - */ - protected $_conn; - protected $_bind; - - /** - * Getters and Setters - */ - - /** - * Set the account suffix - * - * @param string $_account_suffix - * @return void - */ - public function set_account_suffix($_account_suffix) - { - $this->_account_suffix = $_account_suffix; - } - - /** - * Get the account suffix - * - * @return string - */ - public function get_account_suffix() - { - return $this->_account_suffix; - } - - /** - * Set the domain controllers array - * - * @param array $_domain_controllers - * @return void - */ - public function set_domain_controllers(array $_domain_controllers) - { - $this->_domain_controllers = $_domain_controllers; - } - - /** - * Get the list of domain controllers - * - * @return void - */ - public function get_domain_controllers() - { - return $this->_domain_controllers; - } - - /** - * Set the username of an account with higher priviledges - * - * @param string $_ad_username - * @return void - */ - public function set_ad_username($_ad_username) - { - $this->_ad_username = $_ad_username; - } - - /** - * Get the username of the account with higher priviledges - * - * This will throw an exception for security reasons - */ - public function get_ad_username() - { - throw new adLDAPException('For security reasons you cannot access the domain administrator account details'); - } - - /** - * Set the password of an account with higher priviledges - * - * @param string $_ad_password - * @return void - */ - public function set_ad_password($_ad_password) - { - $this->_ad_password = $_ad_password; - } - - /** - * Get the password of the account with higher priviledges - * - * This will throw an exception for security reasons - */ - public function get_ad_password() - { - throw new adLDAPException('For security reasons you cannot access the domain administrator account details'); - } - - /** - * Set whether to detect the true primary group - * - * @param bool $_real_primary_group - * @return void - */ - public function set_real_primarygroup($_real_primarygroup) - { - $this->_real_primarygroup = $_real_primarygroup; - } - - /** - * Get the real primary group setting - * - * @return bool - */ - public function get_real_primarygroup() - { - return $this->_real_primarygroup; - } - - /** - * Set whether to use SSL - * - * @param bool $_use_ssl - * @return void - */ - public function set_use_ssl($_use_ssl) - { - $this->_use_ssl = $_use_ssl; - } - - /** - * Get the SSL setting - * - * @return bool - */ - public function get_use_ssl() - { - return $this->_use_ssl; - } - - /** - * Set whether to use TLS - * - * @param bool $_use_tls - * @return void - */ - public function set_use_tls($_use_tls) - { - $this->_use_tls = $_use_tls; - } - - /** - * Get the TLS setting - * - * @return bool - */ - public function get_use_tls() - { - return $this->_use_tls; - } - - /** - * Set whether to lookup recursive groups - * - * @param bool $_recursive_groups - * @return void - */ - public function set_recursive_groups($_recursive_groups) - { - $this->_recursive_groups = $_recursive_groups; - } - - /** - * Get the recursive groups setting - * - * @return bool - */ - public function get_recursive_groups() - { - return $this->_recursive_groups; - } - - /** - * Default Constructor - * - * Tries to bind to the AD domain over LDAP or LDAPs - * - * @param array $options Array of options to pass to the constructor - * @throws Exception - if unable to bind to Domain Controller - * @return bool - */ - function __construct($options=array()){ - // You can specifically overide any of the default configuration options setup above - if (count($options)>0){ - if (array_key_exists("account_suffix",$options)){ $this->_account_suffix=$options["account_suffix"]; } - if (array_key_exists("base_dn",$options)){ $this->_base_dn=$options["base_dn"]; } - if (array_key_exists("domain_controllers",$options)){ $this->_domain_controllers=$options["domain_controllers"]; } - if (array_key_exists("ad_username",$options)){ $this->_ad_username=$options["ad_username"]; } - if (array_key_exists("ad_password",$options)){ $this->_ad_password=$options["ad_password"]; } - if (array_key_exists("real_primarygroup",$options)){ $this->_real_primarygroup=$options["real_primarygroup"]; } - if (array_key_exists("use_ssl",$options)){ $this->_use_ssl=$options["use_ssl"]; } - if (array_key_exists("use_tls",$options)){ $this->_use_tls=$options["use_tls"]; } - if (array_key_exists("recursive_groups",$options)){ $this->_recursive_groups=$options["recursive_groups"]; } - } - - if ($this->ldap_supported() === false) { - throw new adLDAPException('No LDAP support for PHP. See: http://www.php.net/ldap'); - } - - return $this->connect(); - } - - /** - * Default Destructor - * - * Closes the LDAP connection - * - * @return void - */ - function __destruct(){ $this->close(); } - - /** - * Connects and Binds to the Domain Controller - * - * @return bool - */ - public function connect() { - // Connect to the AD/LDAP server as the username/password - $dc=$this->random_controller(); - if ($this->_use_ssl){ - $this->_conn = ldap_connect("ldaps://".$dc, 636); - } else { - $this->_conn = ldap_connect($dc); - } - - // Set some ldap options for talking to AD - ldap_set_option($this->_conn, LDAP_OPT_PROTOCOL_VERSION, 3); - ldap_set_option($this->_conn, LDAP_OPT_REFERRALS, 0); - - if ($this->_use_tls) { - ldap_start_tls($this->_conn); - } - - // Bind as a domain admin if they've set it up - if ($this->_ad_username!=NULL && $this->_ad_password!=NULL){ - $this->_bind = @ldap_bind($this->_conn,$this->_ad_username.$this->_account_suffix,$this->_ad_password); - if (!$this->_bind){ - if ($this->_use_ssl && !$this->_use_tls){ - // If you have problems troubleshooting, remove the @ character from the ldap_bind command above to get the actual error message - 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()); - } else { - throw new adLDAPException('Bind to Active Directory failed. Check the login credentials and/or server details. AD said: ' . $this->get_last_error()); - } - } - } - - if ($this->_base_dn == NULL) { - $this->_base_dn = $this->find_base_dn(); - } - - return (true); - } - - /** - * Closes the LDAP connection - * - * @return void - */ - public function close() { - ldap_close ($this->_conn); - } - - /** - * Validate a user's login credentials - * - * @param string $username A user's AD username - * @param string $password A user's AD password - * @param bool optional $prevent_rebind - * @return bool - */ - public function authenticate($username, $password, $prevent_rebind = false) { - // Prevent null binding - if ($username === NULL || $password === NULL) { return false; } - if (empty($username) || empty($password)) { return false; } - - // Bind as the user - $ret = true; - $this->_bind = @ldap_bind($this->_conn, $username . $this->_account_suffix, $password); - if (!$this->_bind){ $ret = false; } - - // Cnce we've checked their details, kick back into admin mode if we have it - if ($this->_ad_username !== NULL && !$prevent_rebind) { - $this->_bind = @ldap_bind($this->_conn, $this->_ad_username . $this->_account_suffix , $this->_ad_password); - if (!$this->_bind){ - // This should never happen in theory - throw new adLDAPException('Rebind to Active Directory failed. AD said: ' . $this->get_last_error()); - } - } - - return $ret; - } - - //***************************************************************************************************************** - // GROUP FUNCTIONS - - /** - * Add a group to a group - * - * @param string $parent The parent group name - * @param string $child The child group name - * @return bool - */ - public function group_add_group($parent,$child){ - - // Find the parent group's dn - $parent_group=$this->group_info($parent,array("cn")); - if ($parent_group[0]["dn"]===NULL){ return (false); } - $parent_dn=$parent_group[0]["dn"]; - - // Find the child group's dn - $child_group=$this->group_info($child,array("cn")); - if ($child_group[0]["dn"]===NULL){ return (false); } - $child_dn=$child_group[0]["dn"]; - - $add=array(); - $add["member"] = $child_dn; - - $result=@ldap_mod_add($this->_conn,$parent_dn,$add); - if ($result==false){ return (false); } - return (true); - } - - /** - * Add a user to a group - * - * @param string $group The group to add the user to - * @param string $user The user to add to the group - * @param bool $isGUID Is the username passed a GUID or a samAccountName - * @return bool - */ - public function group_add_user($group,$user,$isGUID=false){ - // Adding a user is a bit fiddly, we need to get the full DN of the user - // and add it using the full DN of the group - - // Find the user's dn - $user_dn=$this->user_dn($user,$isGUID); - if ($user_dn===false){ return (false); } - - // Find the group's dn - $group_info=$this->group_info($group,array("cn")); - if ($group_info[0]["dn"]===NULL){ return (false); } - $group_dn=$group_info[0]["dn"]; - - $add=array(); - $add["member"] = $user_dn; - - $result=@ldap_mod_add($this->_conn,$group_dn,$add); - if ($result==false){ return (false); } - return (true); - } - - /** - * Add a contact to a group - * - * @param string $group The group to add the contact to - * @param string $contact_dn The DN of the contact to add - * @return bool - */ - public function group_add_contact($group,$contact_dn){ - // To add a contact we take the contact's DN - // and add it using the full DN of the group - - // Find the group's dn - $group_info=$this->group_info($group,array("cn")); - if ($group_info[0]["dn"]===NULL){ return (false); } - $group_dn=$group_info[0]["dn"]; - - $add=array(); - $add["member"] = $contact_dn; - - $result=@ldap_mod_add($this->_conn,$group_dn,$add); - if ($result==false){ return (false); } - return (true); - } - - /** - * Create a group - * - * @param array $attributes Default attributes of the group - * @return bool - */ - public function group_create($attributes){ - if (!is_array($attributes)){ return ("Attributes must be an array"); } - if (!array_key_exists("group_name",$attributes)){ return ("Missing compulsory field [group_name]"); } - if (!array_key_exists("container",$attributes)){ return ("Missing compulsory field [container]"); } - if (!array_key_exists("description",$attributes)){ return ("Missing compulsory field [description]"); } - if (!is_array($attributes["container"])){ return ("Container attribute must be an array."); } - $attributes["container"]=array_reverse($attributes["container"]); - - //$member_array = array(); - //$member_array[0] = "cn=user1,cn=Users,dc=yourdomain,dc=com"; - //$member_array[1] = "cn=administrator,cn=Users,dc=yourdomain,dc=com"; - - $add=array(); - $add["cn"] = $attributes["group_name"]; - $add["samaccountname"] = $attributes["group_name"]; - $add["objectClass"] = "Group"; - $add["description"] = $attributes["description"]; - //$add["member"] = $member_array; UNTESTED - - $container="OU=".implode(",OU=",$attributes["container"]); - $result=ldap_add($this->_conn,"CN=".$add["cn"].", ".$container.",".$this->_base_dn,$add); - if ($result!=true){ return (false); } - - return (true); - } - - /** - * Remove a group from a group - * - * @param string $parent The parent group name - * @param string $child The child group name - * @return bool - */ - public function group_del_group($parent,$child){ - - // Find the parent dn - $parent_group=$this->group_info($parent,array("cn")); - if ($parent_group[0]["dn"]===NULL){ return (false); } - $parent_dn=$parent_group[0]["dn"]; - - // Find the child dn - $child_group=$this->group_info($child,array("cn")); - if ($child_group[0]["dn"]===NULL){ return (false); } - $child_dn=$child_group[0]["dn"]; - - $del=array(); - $del["member"] = $child_dn; - - $result=@ldap_mod_del($this->_conn,$parent_dn,$del); - if ($result==false){ return (false); } - return (true); - } - - /** - * Remove a user from a group - * - * @param string $group The group to remove a user from - * @param string $user The AD user to remove from the group - * @param bool $isGUID Is the username passed a GUID or a samAccountName - * @return bool - */ - public function group_del_user($group,$user,$isGUID=false){ - - // Find the parent dn - $group_info=$this->group_info($group,array("cn")); - if ($group_info[0]["dn"]===NULL){ return (false); } - $group_dn=$group_info[0]["dn"]; - - // Find the users dn - $user_dn=$this->user_dn($user,$isGUID); - if ($user_dn===false){ return (false); } - - $del=array(); - $del["member"] = $user_dn; - - $result=@ldap_mod_del($this->_conn,$group_dn,$del); - if ($result==false){ return (false); } - return (true); - } - - /** - * Remove a contact from a group - * - * @param string $group The group to remove a user from - * @param string $contact_dn The DN of a contact to remove from the group - * @return bool - */ - public function group_del_contact($group,$contact_dn){ - - // Find the parent dn - $group_info=$this->group_info($group,array("cn")); - if ($group_info[0]["dn"]===NULL){ return (false); } - $group_dn=$group_info[0]["dn"]; - - $del=array(); - $del["member"] = $contact_dn; - - $result=@ldap_mod_del($this->_conn,$group_dn,$del); - if ($result==false){ return (false); } - return (true); - } - - /** - * Return a list of groups in a group - * - * @param string $group The group to query - * @param bool $recursive Recursively get groups - * @return array - */ - public function groups_in_group($group, $recursive = NULL){ - if (!$this->_bind){ return (false); } - if ($recursive===NULL){ $recursive=$this->_recursive_groups; } // Use the default option if they haven't set it - - // Search the directory for the members of a group - $info=$this->group_info($group,array("member","cn")); - $groups=$info[0]["member"]; - if (!is_array($groups)) { - return (false); - } - - $group_array=array(); - - for ($i=0; $i<$groups["count"]; $i++){ - $filter="(&(objectCategory=group)(distinguishedName=".$this->ldap_slashes($groups[$i])."))"; - $fields = array("samaccountname", "distinguishedname", "objectClass"); - $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields); - $entries = ldap_get_entries($this->_conn, $sr); - - // not a person, look for a group - if ($entries['count'] == 0 && $recursive == true) { - $filter="(&(objectCategory=group)(distinguishedName=".$this->ldap_slashes($groups[$i])."))"; - $fields = array("distinguishedname"); - $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields); - $entries = ldap_get_entries($this->_conn, $sr); - if (!isset($entries[0]['distinguishedname'][0])) { - continue; - } - $sub_groups = $this->groups_in_group($entries[0]['distinguishedname'][0], $recursive); - if (is_array($sub_groups)) { - $group_array = array_merge($group_array, $sub_groups); - $group_array = array_unique($group_array); - } - continue; - } - - $group_array[] = $entries[0]['distinguishedname'][0]; - } - return ($group_array); - } - - /** - * Return a list of members in a group - * - * @param string $group The group to query - * @param bool $recursive Recursively get group members - * @return array - */ - public function group_members($group, $recursive = NULL){ - if (!$this->_bind){ return (false); } - if ($recursive===NULL){ $recursive=$this->_recursive_groups; } // Use the default option if they haven't set it - // Search the directory for the members of a group - $info=$this->group_info($group,array("member","cn")); - $users=$info[0]["member"]; - if (!is_array($users)) { - return (false); - } - - $user_array=array(); - - for ($i=0; $i<$users["count"]; $i++){ - $filter="(&(objectCategory=person)(distinguishedName=".$this->ldap_slashes($users[$i])."))"; - $fields = array("samaccountname", "distinguishedname", "objectClass"); - $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields); - $entries = ldap_get_entries($this->_conn, $sr); - - // not a person, look for a group - if ($entries['count'] == 0 && $recursive == true) { - $filter="(&(objectCategory=group)(distinguishedName=".$this->ldap_slashes($users[$i])."))"; - $fields = array("samaccountname"); - $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields); - $entries = ldap_get_entries($this->_conn, $sr); - if (!isset($entries[0]['samaccountname'][0])) { - continue; - } - $sub_users = $this->group_members($entries[0]['samaccountname'][0], $recursive); - if (is_array($sub_users)) { - $user_array = array_merge($user_array, $sub_users); - $user_array = array_unique($user_array); - } - continue; - } - - if ($entries[0]['samaccountname'][0] === NULL && $entries[0]['distinguishedname'][0] !== NULL) { - $user_array[] = $entries[0]['distinguishedname'][0]; - } - elseif ($entries[0]['samaccountname'][0] !== NULL) { - $user_array[] = $entries[0]['samaccountname'][0]; - } - } - return ($user_array); - } - - /** - * Group Information. Returns an array of information about a group. - * The group name is case sensitive - * - * @param string $group_name The group name to retrieve info about - * @param array $fields Fields to retrieve - * @return array - */ - public function group_info($group_name,$fields=NULL){ - if ($group_name===NULL){ return (false); } - if (!$this->_bind){ return (false); } - - if (stristr($group_name, '+')) { - $group_name=stripslashes($group_name); - } - - $filter="(&(objectCategory=group)(name=".$this->ldap_slashes($group_name)."))"; - //echo ($filter."!!!<br>"); - if ($fields===NULL){ $fields=array("member","memberof","cn","description","distinguishedname","objectcategory","samaccountname"); } - $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields); - $entries = ldap_get_entries($this->_conn, $sr); - //print_r($entries); - return ($entries); - } - - /** - * Return a complete list of "groups in groups" - * - * @param string $group The group to get the list from - * @return array - */ - public function recursive_groups($group){ - if ($group===NULL){ return (false); } - - $ret_groups=array(); - - $groups=$this->group_info($group,array("memberof")); - if (isset($groups[0]["memberof"]) && is_array($groups[0]["memberof"])) { - $groups=$groups[0]["memberof"]; - - if ($groups){ - $group_names=$this->nice_names($groups); - $ret_groups=array_merge($ret_groups,$group_names); //final groups to return - - foreach ($group_names as $id => $group_name){ - $child_groups=$this->recursive_groups($group_name); - $ret_groups=array_merge($ret_groups,$child_groups); - } - } - } - - return ($ret_groups); - } - - /** - * Returns a complete list of the groups in AD based on a SAM Account Type - * - * @param string $samaccounttype The account type to return - * @param bool $include_desc Whether to return a description - * @param string $search Search parameters - * @param bool $sorted Whether to sort the results - * @return array - */ - public function search_groups($samaccounttype = ADLDAP_SECURITY_GLOBAL_GROUP, $include_desc = false, $search = "*", $sorted = true) { - if (!$this->_bind){ return (false); } - - $filter = '(&(objectCategory=group)'; - if ($samaccounttype !== null) { - $filter .= '(samaccounttype='. $samaccounttype .')'; - } - $filter .= '(cn='.$search.'))'; - // Perform the search and grab all their details - $fields=array("samaccountname","description"); - $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields); - $entries = ldap_get_entries($this->_conn, $sr); - - $groups_array = array(); - for ($i=0; $i<$entries["count"]; $i++){ - if ($include_desc && strlen($entries[$i]["description"][0]) > 0 ){ - $groups_array[ $entries[$i]["samaccountname"][0] ] = $entries[$i]["description"][0]; - } elseif ($include_desc){ - $groups_array[ $entries[$i]["samaccountname"][0] ] = $entries[$i]["samaccountname"][0]; - } else { - array_push($groups_array, $entries[$i]["samaccountname"][0]); - } - } - if( $sorted ){ asort($groups_array); } - return ($groups_array); - } - - /** - * Returns a complete list of all groups in AD - * - * @param bool $include_desc Whether to return a description - * @param string $search Search parameters - * @param bool $sorted Whether to sort the results - * @return array - */ - public function all_groups($include_desc = false, $search = "*", $sorted = true){ - $groups_array = $this->search_groups(null, $include_desc, $search, $sorted); - return ($groups_array); - } - - /** - * Returns a complete list of security groups in AD - * - * @param bool $include_desc Whether to return a description - * @param string $search Search parameters - * @param bool $sorted Whether to sort the results - * @return array - */ - public function all_security_groups($include_desc = false, $search = "*", $sorted = true){ - $groups_array = $this->search_groups(ADLDAP_SECURITY_GLOBAL_GROUP, $include_desc, $search, $sorted); - return ($groups_array); - } - - /** - * Returns a complete list of distribution lists in AD - * - * @param bool $include_desc Whether to return a description - * @param string $search Search parameters - * @param bool $sorted Whether to sort the results - * @return array - */ - public function all_distribution_groups($include_desc = false, $search = "*", $sorted = true){ - $groups_array = $this->search_groups(ADLDAP_DISTRIBUTION_GROUP, $include_desc, $search, $sorted); - return ($groups_array); - } - - //***************************************************************************************************************** - // USER FUNCTIONS - - /** - * Create a user - * - * If you specify a password here, this can only be performed over SSL - * - * @param array $attributes The attributes to set to the user account - * @return bool - */ - public function user_create($attributes){ - // Check for compulsory fields - if (!array_key_exists("username",$attributes)){ return ("Missing compulsory field [username]"); } - if (!array_key_exists("firstname",$attributes)){ return ("Missing compulsory field [firstname]"); } - if (!array_key_exists("surname",$attributes)){ return ("Missing compulsory field [surname]"); } - if (!array_key_exists("email",$attributes)){ return ("Missing compulsory field [email]"); } - if (!array_key_exists("container",$attributes)){ return ("Missing compulsory field [container]"); } - if (!is_array($attributes["container"])){ return ("Container attribute must be an array."); } - - if (array_key_exists("password",$attributes) && (!$this->_use_ssl && !$this->_use_tls)){ - throw new adLDAPException('SSL must be configured on your webserver and enabled in the class to set passwords.'); - } - - if (!array_key_exists("display_name",$attributes)){ $attributes["display_name"]=$attributes["firstname"]." ".$attributes["surname"]; } - - // Translate the schema - $add=$this->adldap_schema($attributes); - - // Additional stuff only used for adding accounts - $add["cn"][0]=$attributes["display_name"]; - $add["samaccountname"][0]=$attributes["username"]; - $add["objectclass"][0]="top"; - $add["objectclass"][1]="person"; - $add["objectclass"][2]="organizationalPerson"; - $add["objectclass"][3]="user"; //person? - //$add["name"][0]=$attributes["firstname"]." ".$attributes["surname"]; - - // Set the account control attribute - $control_options=array("NORMAL_ACCOUNT"); - if (!$attributes["enabled"]){ $control_options[]="ACCOUNTDISABLE"; } - $add["userAccountControl"][0]=$this->account_control($control_options); - //echo ("<pre>"); print_r($add); - - // Determine the container - $attributes["container"]=array_reverse($attributes["container"]); - $container="OU=".implode(",OU=",$attributes["container"]); - - // Add the entry - $result=@ldap_add($this->_conn, "CN=".$add["cn"][0].", ".$container.",".$this->_base_dn, $add); - if ($result!=true){ return (false); } - - return (true); - } - - /** - * Delete a user account - * - * @param string $username The username to delete (please be careful here!) - * @param bool $isGUID Is the username a GUID or a samAccountName - * @return array - */ - public function user_delete($username,$isGUID=false) { - $userinfo = $this->user_info($username, array("*"),$isGUID); - $dn = $userinfo[0]['distinguishedname'][0]; - $result=$this->dn_delete($dn); - if ($result!=true){ return (false); } - return (true); - } - - /** - * Groups the user is a member of - * - * @param string $username The username to query - * @param bool $recursive Recursive list of groups - * @param bool $isGUID Is the username passed a GUID or a samAccountName - * @return array - */ - public function user_groups($username,$recursive=NULL,$isGUID=false){ - if ($username===NULL){ return (false); } - if ($recursive===NULL){ $recursive=$this->_recursive_groups; } // Use the default option if they haven't set it - if (!$this->_bind){ return (false); } - - // Search the directory for their information - $info=@$this->user_info($username,array("memberof","primarygroupid"),$isGUID); - $groups=$this->nice_names($info[0]["memberof"]); // Presuming the entry returned is our guy (unique usernames) - - if ($recursive === true){ - foreach ($groups as $id => $group_name){ - $extra_groups=$this->recursive_groups($group_name); - $groups=array_merge($groups,$extra_groups); - } - } - - return ($groups); - } - - /** - * Find information about the users - * - * @param string $username The username to query - * @param array $fields Array of parameters to query - * @param bool $isGUID Is the username passed a GUID or a samAccountName - * @return array - */ - public function user_info($username,$fields=NULL,$isGUID=false){ - if ($username===NULL){ return (false); } - if (!$this->_bind){ return (false); } - - if ($isGUID === true) { - $username = $this->strguid2hex($username); - $filter="objectguid=".$username; - } - else if (strstr($username, "@")) { - $filter="userPrincipalName=".$username; - } - else { - $filter="samaccountname=".$username; - } - $filter = "(&(objectCategory=person)({$filter}))"; - if ($fields===NULL){ $fields=array("samaccountname","mail","memberof","department","displayname","telephonenumber","primarygroupid","objectsid"); } - if (!in_array("objectsid",$fields)){ - $fields[] = "objectsid"; - } - $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields); - $entries = ldap_get_entries($this->_conn, $sr); - - if (isset($entries[0])) { - if ($entries[0]['count'] >= 1) { - if (in_array("memberof", $fields)) { - // AD does not return the primary group in the ldap query, we may need to fudge it - if ($this->_real_primarygroup && isset($entries[0]["primarygroupid"][0]) && isset($entries[0]["objectsid"][0])){ - //$entries[0]["memberof"][]=$this->group_cn($entries[0]["primarygroupid"][0]); - $entries[0]["memberof"][]=$this->get_primary_group($entries[0]["primarygroupid"][0], $entries[0]["objectsid"][0]); - } else { - $entries[0]["memberof"][]="CN=Domain Users,CN=Users,".$this->_base_dn; - } - $entries[0]["memberof"]["count"]++; - } - } - return $entries; - } - return false; - } - - /** - * Determine if a user is in a specific group - * - * @param string $username The username to query - * @param string $group The name of the group to check against - * @param bool $recursive Check groups recursively - * @param bool $isGUID Is the username passed a GUID or a samAccountName - * @return bool - */ - public function user_ingroup($username,$group,$recursive=NULL,$isGUID=false){ - if ($username===NULL){ return (false); } - if ($group===NULL){ return (false); } - if (!$this->_bind){ return (false); } - if ($recursive===NULL){ $recursive=$this->_recursive_groups; } // Use the default option if they haven't set it - - // Get a list of the groups - $groups=$this->user_groups($username,$recursive,$isGUID); - - // Return true if the specified group is in the group list - if (in_array($group,$groups)){ return (true); } - - return (false); - } - - /** - * Return info about the domain itself - * - * @authot Andreas Gohr <gohr@cosmocode.de> - * @param array $fields The fields to query - * @return array - */ - public function domain_info($fields){ - if (!$this->_bind){ return (false); } - - $sr = ldap_read($this->_conn, $this->_base_dn, 'objectclass=*', $fields); - if (!$sr) { - return false; - } - $info = ldap_get_entries($this->_conn, $sr); - if(count($info)) return $info[0]; - - return false; - } - - /** - * Determine a user's password expiry date - * - * @param string $username The username to query - * @param book $isGUID Is the username passed a GUID or a samAccountName - * @requires bcmath http://www.php.net/manual/en/book.bc.php - * @return array - */ - public function user_password_expiry($username,$isGUID=false) { - if ($username===NULL){ return ("Missing compulsory field [username]"); } - if (!$this->_bind){ return (false); } - if (!function_exists('bcmod')) { return ("Missing function support [bcmod] http://www.php.net/manual/en/book.bc.php"); }; - - $userinfo = $this->user_info($username, array("pwdlastset", "useraccountcontrol"), $isGUID); - $pwdlastset = $userinfo[0]['pwdlastset'][0]; - $status = array(); - - if ($userinfo[0]['useraccountcontrol'][0] == '66048') { - // Password does not expire - return "Does not expire"; - } - if ($pwdlastset === '0') { - // Password has already expired - return "Password has expired"; - } - - // Password expiry in AD can be calculated from TWO values: - // - User's own pwdLastSet attribute: stores the last time the password was changed - // - Domain's maxPwdAge attribute: how long passwords last in the domain - // - // Although Microsoft chose to use a different base and unit for time measurements. - // This function will convert them to Unix timestamps - $sr = ldap_read($this->_conn, $this->_base_dn, 'objectclass=*', array('maxPwdAge')); - if (!$sr) { - return false; - } - $info = ldap_get_entries($this->_conn, $sr); - $maxpwdage = $info[0]['maxpwdage'][0]; - - - // See MSDN: http://msdn.microsoft.com/en-us/library/ms974598.aspx - // - // pwdLastSet contains the number of 100 nanosecond intervals since January 1, 1601 (UTC), - // stored in a 64 bit integer. - // - // The number of seconds between this date and Unix epoch is 11644473600. - // - // maxPwdAge is stored as a large integer that represents the number of 100 nanosecond - // intervals from the time the password was set before the password expires. - // - // We also need to scale this to seconds but also this value is a _negative_ quantity! - // - // If the low 32 bits of maxPwdAge are equal to 0 passwords do not expire - // - // Unfortunately the maths involved are too big for PHP integers, so I've had to require - // BCMath functions to work with arbitrary precision numbers. - if (bcmod($maxpwdage, 4294967296) === '0') { - return "Domain does not expire passwords"; - } - - // Add maxpwdage and pwdlastset and we get password expiration time in Microsoft's - // time units. Because maxpwd age is negative we need to subtract it. - $pwdexpire = bcsub($pwdlastset, $maxpwdage); - - // Convert MS's time to Unix time - $status['expiryts'] = bcsub(bcdiv($pwdexpire, '10000000'), '11644473600'); - $status['expiryformat'] = date('Y-m-d H:i:s', bcsub(bcdiv($pwdexpire, '10000000'), '11644473600')); - - return $status; - } - - /** - * Modify a user - * - * @param string $username The username to query - * @param array $attributes The attributes to modify. Note if you set the enabled attribute you must not specify any other attributes - * @param bool $isGUID Is the username passed a GUID or a samAccountName - * @return bool - */ - public function user_modify($username,$attributes,$isGUID=false){ - if ($username===NULL){ return ("Missing compulsory field [username]"); } - if (array_key_exists("password",$attributes) && !$this->_use_ssl){ - throw new adLDAPException('SSL must be configured on your webserver and enabled in the class to set passwords.'); - } - - // Find the dn of the user - $user_dn=$this->user_dn($username,$isGUID); - if ($user_dn===false){ return (false); } - - // Translate the update to the LDAP schema - $mod=$this->adldap_schema($attributes); - - // Check to see if this is an enabled status update - if (!$mod && !array_key_exists("enabled", $attributes)){ return (false); } - - // Set the account control attribute (only if specified) - if (array_key_exists("enabled",$attributes)){ - if ($attributes["enabled"]){ $control_options=array("NORMAL_ACCOUNT"); } - else { $control_options=array("NORMAL_ACCOUNT","ACCOUNTDISABLE"); } - $mod["userAccountControl"][0]=$this->account_control($control_options); - } - - // Do the update - $result=@ldap_modify($this->_conn,$user_dn,$mod); - if ($result==false){ return (false); } - - return (true); - } - - /** - * Disable a user account - * - * @param string $username The username to disable - * @param bool $isGUID Is the username passed a GUID or a samAccountName - * @return bool - */ - public function user_disable($username,$isGUID=false){ - if ($username===NULL){ return ("Missing compulsory field [username]"); } - $attributes=array("enabled"=>0); - $result = $this->user_modify($username, $attributes, $isGUID); - if ($result==false){ return (false); } - - return (true); - } - - /** - * Enable a user account - * - * @param string $username The username to enable - * @param bool $isGUID Is the username passed a GUID or a samAccountName - * @return bool - */ - public function user_enable($username,$isGUID=false){ - if ($username===NULL){ return ("Missing compulsory field [username]"); } - $attributes=array("enabled"=>1); - $result = $this->user_modify($username, $attributes, $isGUID); - if ($result==false){ return (false); } - - return (true); - } - - /** - * Set the password of a user - This must be performed over SSL - * - * @param string $username The username to modify - * @param string $password The new password - * @param bool $isGUID Is the username passed a GUID or a samAccountName - * @return bool - */ - public function user_password($username,$password,$isGUID=false){ - if ($username===NULL){ return (false); } - if ($password===NULL){ return (false); } - if (!$this->_bind){ return (false); } - if (!$this->_use_ssl && !$this->_use_tls){ - throw new adLDAPException('SSL must be configured on your webserver and enabled in the class to set passwords.'); - } - - $user_dn=$this->user_dn($username,$isGUID); - if ($user_dn===false){ return (false); } - - $add=array(); - $add["unicodePwd"][0]=$this->encode_password($password); - - $result=@ldap_mod_replace($this->_conn,$user_dn,$add); - if ($result==false){ - $err = ldap_errno($this->_conn); - if($err){ - $msg = 'Error '.$err.': '.ldap_err2str($err).'.'; - if($err == 53) $msg .= ' Your password might not match the password policy.'; - throw new adLDAPException($msg); - }else{ - return false; - } - } - - return (true); - } - - /** - * Return a list of all users in AD - * - * @param bool $include_desc Return a description of the user - * @param string $search Search parameter - * @param bool $sorted Sort the user accounts - * @return array - */ - public function all_users($include_desc = false, $search = "*", $sorted = true){ - if (!$this->_bind){ return (false); } - - // Perform the search and grab all their details - $filter = "(&(objectClass=user)(samaccounttype=". ADLDAP_NORMAL_ACCOUNT .")(objectCategory=person)(cn=".$search."))"; - $fields=array("samaccountname","displayname"); - $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields); - $entries = ldap_get_entries($this->_conn, $sr); - - $users_array = array(); - for ($i=0; $i<$entries["count"]; $i++){ - if ($include_desc && strlen($entries[$i]["displayname"][0])>0){ - $users_array[ $entries[$i]["samaccountname"][0] ] = $entries[$i]["displayname"][0]; - } elseif ($include_desc){ - $users_array[ $entries[$i]["samaccountname"][0] ] = $entries[$i]["samaccountname"][0]; - } else { - array_push($users_array, $entries[$i]["samaccountname"][0]); - } - } - if ($sorted){ asort($users_array); } - return ($users_array); - } - - /** - * Converts a username (samAccountName) to a GUID - * - * @param string $username The username to query - * @return string - */ - public function username2guid($username) { - if (!$this->_bind){ return (false); } - if ($username === null){ return ("Missing compulsory field [username]"); } - - $filter = "samaccountname=" . $username; - $fields = array("objectGUID"); - $sr = @ldap_search($this->_conn, $this->_base_dn, $filter, $fields); - if (ldap_count_entries($this->_conn, $sr) > 0) { - $entry = @ldap_first_entry($this->_conn, $sr); - $guid = @ldap_get_values_len($this->_conn, $entry, 'objectGUID'); - $strGUID = $this->binary2text($guid[0]); - return ($strGUID); - } - else { - return (false); - } - } - - /** - * Move a user account to a different OU - * - * @param string $username The username to move (please be careful here!) - * @param array $container The container or containers to move the user to (please be careful here!). - * accepts containers in 1. parent 2. child order - * @return array - */ - public function user_move($username, $container) { - if (!$this->_bind){ return (false); } - if ($username === null){ return ("Missing compulsory field [username]"); } - if ($container === null){ return ("Missing compulsory field [container]"); } - if (!is_array($container)){ return ("Container must be an array"); } - - $userinfo = $this->user_info($username, array("*")); - $dn = $userinfo[0]['distinguishedname'][0]; - $newrdn = "cn=" . $username; - $container = array_reverse($container); - $newcontainer = "ou=" . implode(",ou=",$container); - $newbasedn = strtolower($newcontainer) . "," . $this->_base_dn; - $result=@ldap_rename($this->_conn,$dn,$newrdn,$newbasedn,true); - if ($result !== true) { - return (false); - } - return (true); - } - - //***************************************************************************************************************** - // CONTACT FUNCTIONS - // * Still work to do in this area, and new functions to write - - /** - * Create a contact - * - * @param array $attributes The attributes to set to the contact - * @return bool - */ - public function contact_create($attributes){ - // Check for compulsory fields - if (!array_key_exists("display_name",$attributes)){ return ("Missing compulsory field [display_name]"); } - if (!array_key_exists("email",$attributes)){ return ("Missing compulsory field [email]"); } - if (!array_key_exists("container",$attributes)){ return ("Missing compulsory field [container]"); } - if (!is_array($attributes["container"])){ return ("Container attribute must be an array."); } - - // Translate the schema - $add=$this->adldap_schema($attributes); - - // Additional stuff only used for adding contacts - $add["cn"][0]=$attributes["display_name"]; - $add["objectclass"][0]="top"; - $add["objectclass"][1]="person"; - $add["objectclass"][2]="organizationalPerson"; - $add["objectclass"][3]="contact"; - if (!isset($attributes['exchange_hidefromlists'])) { - $add["msExchHideFromAddressLists"][0]="TRUE"; - } - - // Determine the container - $attributes["container"]=array_reverse($attributes["container"]); - $container="OU=".implode(",OU=",$attributes["container"]); - - // Add the entry - $result=@ldap_add($this->_conn, "CN=".$add["cn"][0].", ".$container.",".$this->_base_dn, $add); - if ($result!=true){ return (false); } - - return (true); - } - - /** - * Determine the list of groups a contact is a member of - * - * @param string $distinguisedname The full DN of a contact - * @param bool $recursive Recursively check groups - * @return array - */ - public function contact_groups($distinguishedname,$recursive=NULL){ - if ($distinguishedname===NULL){ return (false); } - if ($recursive===NULL){ $recursive=$this->_recursive_groups; } //use the default option if they haven't set it - if (!$this->_bind){ return (false); } - - // Search the directory for their information - $info=@$this->contact_info($distinguishedname,array("memberof","primarygroupid")); - $groups=$this->nice_names($info[0]["memberof"]); //presuming the entry returned is our contact - - if ($recursive === true){ - foreach ($groups as $id => $group_name){ - $extra_groups=$this->recursive_groups($group_name); - $groups=array_merge($groups,$extra_groups); - } - } - - return ($groups); - } - - /** - * Get contact information - * - * @param string $distinguisedname The full DN of a contact - * @param array $fields Attributes to be returned - * @return array - */ - public function contact_info($distinguishedname,$fields=NULL){ - if ($distinguishedname===NULL){ return (false); } - if (!$this->_bind){ return (false); } - - $filter="distinguishedName=".$distinguishedname; - if ($fields===NULL){ $fields=array("distinguishedname","mail","memberof","department","displayname","telephonenumber","primarygroupid","objectsid"); } - $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields); - $entries = ldap_get_entries($this->_conn, $sr); - - if ($entries[0]['count'] >= 1) { - // AD does not return the primary group in the ldap query, we may need to fudge it - if ($this->_real_primarygroup && isset($entries[0]["primarygroupid"][0]) && isset($entries[0]["primarygroupid"][0])){ - //$entries[0]["memberof"][]=$this->group_cn($entries[0]["primarygroupid"][0]); - $entries[0]["memberof"][]=$this->get_primary_group($entries[0]["primarygroupid"][0], $entries[0]["objectsid"][0]); - } else { - $entries[0]["memberof"][]="CN=Domain Users,CN=Users,".$this->_base_dn; - } - } - - $entries[0]["memberof"]["count"]++; - return ($entries); - } - - /** - * Determine if a contact is a member of a group - * - * @param string $distinguisedname The full DN of a contact - * @param string $group The group name to query - * @param bool $recursive Recursively check groups - * @return bool - */ - public function contact_ingroup($distinguisedname,$group,$recursive=NULL){ - if ($distinguisedname===NULL){ return (false); } - if ($group===NULL){ return (false); } - if (!$this->_bind){ return (false); } - if ($recursive===NULL){ $recursive=$this->_recursive_groups; } //use the default option if they haven't set it - - // Get a list of the groups - $groups=$this->contact_groups($distinguisedname,array("memberof"),$recursive); - - // Return true if the specified group is in the group list - if (in_array($group,$groups)){ return (true); } - - return (false); - } - - /** - * Modify a contact - * - * @param string $distinguishedname The contact to query - * @param array $attributes The attributes to modify. Note if you set the enabled attribute you must not specify any other attributes - * @return bool - */ - public function contact_modify($distinguishedname,$attributes){ - if ($distinguishedname===NULL){ return ("Missing compulsory field [distinguishedname]"); } - - // Translate the update to the LDAP schema - $mod=$this->adldap_schema($attributes); - - // Check to see if this is an enabled status update - if (!$mod){ return (false); } - - // Do the update - $result=ldap_modify($this->_conn,$distinguishedname,$mod); - if ($result==false){ return (false); } - - return (true); - } - - /** - * Delete a contact - * - * @param string $distinguishedname The contact dn to delete (please be careful here!) - * @return array - */ - public function contact_delete($distinguishedname) { - $result = $this->dn_delete($distinguishedname); - if ($result!=true){ return (false); } - return (true); - } - - /** - * Return a list of all contacts - * - * @param bool $include_desc Include a description of a contact - * @param string $search The search parameters - * @param bool $sorted Whether to sort the results - * @return array - */ - public function all_contacts($include_desc = false, $search = "*", $sorted = true){ - if (!$this->_bind){ return (false); } - - // Perform the search and grab all their details - $filter = "(&(objectClass=contact)(cn=".$search."))"; - $fields=array("displayname","distinguishedname"); - $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields); - $entries = ldap_get_entries($this->_conn, $sr); - - $users_array = array(); - for ($i=0; $i<$entries["count"]; $i++){ - if ($include_desc && strlen($entries[$i]["displayname"][0])>0){ - $users_array[ $entries[$i]["distinguishedname"][0] ] = $entries[$i]["displayname"][0]; - } elseif ($include_desc){ - $users_array[ $entries[$i]["distinguishedname"][0] ] = $entries[$i]["distinguishedname"][0]; - } else { - array_push($users_array, $entries[$i]["distinguishedname"][0]); - } - } - if ($sorted){ asort($users_array); } - return ($users_array); - } - - //***************************************************************************************************************** - // FOLDER FUNCTIONS - - /** - * Returns a folder listing for a specific OU - * See http://adldap.sourceforge.net/wiki/doku.php?id=api_folder_functions - * - * @param array $folder_name An array to the OU you wish to list. - * If set to NULL will list the root, strongly recommended to set - * $recursive to false in that instance! - * @param string $dn_type The type of record to list. This can be ADLDAP_FOLDER or ADLDAP_CONTAINER. - * @param bool $recursive Recursively search sub folders - * @param bool $type Specify a type of object to search for - * @return array - */ - public function folder_list($folder_name = NULL, $dn_type = ADLDAP_FOLDER, $recursive = NULL, $type = NULL) { - if ($recursive===NULL){ $recursive=$this->_recursive_groups; } //use the default option if they haven't set it - if (!$this->_bind){ return (false); } - - $filter = '(&'; - if ($type !== NULL) { - switch ($type) { - case 'contact': - $filter .= '(objectClass=contact)'; - break; - case 'computer': - $filter .= '(objectClass=computer)'; - break; - case 'group': - $filter .= '(objectClass=group)'; - break; - case 'folder': - $filter .= '(objectClass=organizationalUnit)'; - break; - case 'container': - $filter .= '(objectClass=container)'; - break; - case 'domain': - $filter .= '(objectClass=builtinDomain)'; - break; - default: - $filter .= '(objectClass=user)'; - break; - } - } - else { - $filter .= '(objectClass=*)'; - } - // If the folder name is null then we will search the root level of AD - // This requires us to not have an OU= part, just the base_dn - $searchou = $this->_base_dn; - if (is_array($folder_name)) { - $ou = $dn_type . "=".implode("," . $dn_type . "=",$folder_name); - $filter .= '(!(distinguishedname=' . $ou . ',' . $this->_base_dn . ')))'; - $searchou = $ou . ',' . $this->_base_dn; - } - else { - $filter .= '(!(distinguishedname=' . $this->_base_dn . ')))'; - } - - if ($recursive === true) { - $sr=ldap_search($this->_conn, $searchou, $filter, array('objectclass', 'distinguishedname', 'samaccountname')); - $entries = @ldap_get_entries($this->_conn, $sr); - if (is_array($entries)) { - return $entries; - } - } - else { - $sr=ldap_list($this->_conn, $searchou, $filter, array('objectclass', 'distinguishedname', 'samaccountname')); - $entries = @ldap_get_entries($this->_conn, $sr); - if (is_array($entries)) { - return $entries; - } - } - - return false; - } - - //***************************************************************************************************************** - // COMPUTER FUNCTIONS - - /** - * Get information about a specific computer - * - * @param string $computer_name The name of the computer - * @param array $fields Attributes to return - * @return array - */ - public function computer_info($computer_name,$fields=NULL){ - if ($computer_name===NULL){ return (false); } - if (!$this->_bind){ return (false); } - - $filter="(&(objectClass=computer)(cn=".$computer_name."))"; - if ($fields===NULL){ $fields=array("memberof","cn","displayname","dnshostname","distinguishedname","objectcategory","operatingsystem","operatingsystemservicepack","operatingsystemversion"); } - $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields); - $entries = ldap_get_entries($this->_conn, $sr); - - return ($entries); - } - - /** - * Check if a computer is in a group - * - * @param string $computer_name The name of the computer - * @param string $group The group to check - * @param bool $recursive Whether to check recursively - * @return array - */ - public function computer_ingroup($computer_name,$group,$recursive=NULL){ - if ($computer_name===NULL){ return (false); } - if ($group===NULL){ return (false); } - if (!$this->_bind){ return (false); } - if ($recursive===NULL){ $recursive=$this->_recursive_groups; } // use the default option if they haven't set it - - //get a list of the groups - $groups=$this->computer_groups($computer_name,array("memberof"),$recursive); - - //return true if the specified group is in the group list - if (in_array($group,$groups)){ return (true); } - - return (false); - } - - /** - * Get the groups a computer is in - * - * @param string $computer_name The name of the computer - * @param bool $recursive Whether to check recursively - * @return array - */ - public function computer_groups($computer_name,$recursive=NULL){ - if ($computer_name===NULL){ return (false); } - if ($recursive===NULL){ $recursive=$this->_recursive_groups; } //use the default option if they haven't set it - if (!$this->_bind){ return (false); } - - //search the directory for their information - $info=@$this->computer_info($computer_name,array("memberof","primarygroupid")); - $groups=$this->nice_names($info[0]["memberof"]); //presuming the entry returned is our guy (unique usernames) - - if ($recursive === true){ - foreach ($groups as $id => $group_name){ - $extra_groups=$this->recursive_groups($group_name); - $groups=array_merge($groups,$extra_groups); - } - } - - return ($groups); - } - - //************************************************************************************************************ - // ORGANIZATIONAL UNIT FUNCTIONS - - /** - * Create an organizational unit - * - * @param array $attributes Default attributes of the ou - * @return bool - */ - public function ou_create($attributes){ - if (!is_array($attributes)){ return ("Attributes must be an array"); } - if (!array_key_exists("ou_name",$attributes)){ return ("Missing compulsory field [ou_name]"); } - if (!array_key_exists("container",$attributes)){ return ("Missing compulsory field [container]"); } - if (!is_array($attributes["container"])){ return ("Container attribute must be an array."); } - $attributes["container"]=array_reverse($attributes["container"]); - - $add=array(); - $add["objectClass"] = "organizationalUnit"; - - $container="OU=".implode(",OU=",$attributes["container"]); - $result=ldap_add($this->_conn,"CN=".$add["cn"].", ".$container.",".$this->_base_dn,$add); - if ($result!=true){ return (false); } - - return (true); - } - - //************************************************************************************************************ - // EXCHANGE FUNCTIONS - - /** - * Create an Exchange account - * - * @param string $username The username of the user to add the Exchange account to - * @param array $storagegroup The mailbox, Exchange Storage Group, for the user account, this must be a full CN - * If the storage group has a different base_dn to the adLDAP configuration, set it using $base_dn - * @param string $emailaddress The primary email address to add to this user - * @param string $mailnickname The mail nick name. If mail nickname is blank, the username will be used - * @param bool $usedefaults Indicates whether the store should use the default quota, rather than the per-mailbox quota. - * @param string $base_dn Specify an alternative base_dn for the Exchange storage group - * @param bool $isGUID Is the username passed a GUID or a samAccountName - * @return bool - */ - public function exchange_create_mailbox($username, $storagegroup, $emailaddress, $mailnickname=NULL, $usedefaults=TRUE, $base_dn=NULL, $isGUID=false){ - if ($username===NULL){ return ("Missing compulsory field [username]"); } - if ($storagegroup===NULL){ return ("Missing compulsory array [storagegroup]"); } - if (!is_array($storagegroup)){ return ("[storagegroup] must be an array"); } - if ($emailaddress===NULL){ return ("Missing compulsory field [emailaddress]"); } - - if ($base_dn===NULL) { - $base_dn = $this->_base_dn; - } - - $container="CN=".implode(",CN=",$storagegroup); - - if ($mailnickname===NULL) { $mailnickname=$username; } - $mdbUseDefaults = $this->bool2str($usedefaults); - - $attributes = array( - 'exchange_homemdb'=>$container.",".$base_dn, - 'exchange_proxyaddress'=>'SMTP:' . $emailaddress, - 'exchange_mailnickname'=>$mailnickname, - 'exchange_usedefaults'=>$mdbUseDefaults - ); - $result = $this->user_modify($username,$attributes,$isGUID); - if ($result==false){ return (false); } - return (true); - } - - /** - * Add an X400 address to Exchange - * See http://tools.ietf.org/html/rfc1685 for more information. - * An X400 Address looks similar to this X400:c=US;a= ;p=Domain;o=Organization;s=Doe;g=John; - * - * @param string $username The username of the user to add the X400 to to - * @param string $country Country - * @param string $admd Administration Management Domain - * @param string $pdmd Private Management Domain (often your AD domain) - * @param string $org Organization - * @param string $surname Surname - * @param string $givenName Given name - * @param bool $isGUID Is the username passed a GUID or a samAccountName - * @return bool - */ - public function exchange_add_X400($username, $country, $admd, $pdmd, $org, $surname, $givenname, $isGUID=false) { - if ($username===NULL){ return ("Missing compulsory field [username]"); } - - $proxyvalue = 'X400:'; - - // Find the dn of the user - $user=$this->user_info($username,array("cn","proxyaddresses"), $isGUID); - if ($user[0]["dn"]===NULL){ return (false); } - $user_dn=$user[0]["dn"]; - - // We do not have to demote an email address from the default so we can just add the new proxy address - $attributes['exchange_proxyaddress'] = $proxyvalue . 'c=' . $country . ';a=' . $admd . ';p=' . $pdmd . ';o=' . $org . ';s=' . $surname . ';g=' . $givenname . ';'; - - // Translate the update to the LDAP schema - $add=$this->adldap_schema($attributes); - - if (!$add){ return (false); } - - // Do the update - // Take out the @ to see any errors, usually this error might occur because the address already - // exists in the list of proxyAddresses - $result=@ldap_mod_add($this->_conn,$user_dn,$add); - if ($result==false){ return (false); } - - return (true); - } - - /** - * Add an address to Exchange - * - * @param string $username The username of the user to add the Exchange account to - * @param string $emailaddress The email address to add to this user - * @param bool $default Make this email address the default address, this is a bit more intensive as we have to demote any existing default addresses - * @param bool $isGUID Is the username passed a GUID or a samAccountName - * @return bool - */ - public function exchange_add_address($username, $emailaddress, $default=FALSE, $isGUID=false) { - if ($username===NULL){ return ("Missing compulsory field [username]"); } - if ($emailaddress===NULL) { return ("Missing compulsory fields [emailaddress]"); } - - $proxyvalue = 'smtp:'; - if ($default === true) { - $proxyvalue = 'SMTP:'; - } - - // Find the dn of the user - $user=$this->user_info($username,array("cn","proxyaddresses"),$isGUID); - if ($user[0]["dn"]===NULL){ return (false); } - $user_dn=$user[0]["dn"]; - - // We need to scan existing proxy addresses and demote the default one - if (is_array($user[0]["proxyaddresses"]) && $default===true) { - $modaddresses = array(); - for ($i=0;$i<sizeof($user[0]['proxyaddresses']);$i++) { - if (strstr($user[0]['proxyaddresses'][$i], 'SMTP:') !== false) { - $user[0]['proxyaddresses'][$i] = str_replace('SMTP:', 'smtp:', $user[0]['proxyaddresses'][$i]); - } - if ($user[0]['proxyaddresses'][$i] != '') { - $modaddresses['proxyAddresses'][$i] = $user[0]['proxyaddresses'][$i]; - } - } - $modaddresses['proxyAddresses'][(sizeof($user[0]['proxyaddresses'])-1)] = 'SMTP:' . $emailaddress; - - $result=@ldap_mod_replace($this->_conn,$user_dn,$modaddresses); - if ($result==false){ return (false); } - - return (true); - } - else { - // We do not have to demote an email address from the default so we can just add the new proxy address - $attributes['exchange_proxyaddress'] = $proxyvalue . $emailaddress; - - // Translate the update to the LDAP schema - $add=$this->adldap_schema($attributes); - - if (!$add){ return (false); } - - // Do the update - // Take out the @ to see any errors, usually this error might occur because the address already - // exists in the list of proxyAddresses - $result=@ldap_mod_add($this->_conn,$user_dn,$add); - if ($result==false){ return (false); } - - return (true); - } - } - - /** - * Remove an address to Exchange - * If you remove a default address the account will no longer have a default, - * we recommend changing the default address first - * - * @param string $username The username of the user to add the Exchange account to - * @param string $emailaddress The email address to add to this user - * @param bool $isGUID Is the username passed a GUID or a samAccountName - * @return bool - */ - public function exchange_del_address($username, $emailaddress, $isGUID=false) { - if ($username===NULL){ return ("Missing compulsory field [username]"); } - if ($emailaddress===NULL) { return ("Missing compulsory fields [emailaddress]"); } - - // Find the dn of the user - $user=$this->user_info($username,array("cn","proxyaddresses"),$isGUID); - if ($user[0]["dn"]===NULL){ return (false); } - $user_dn=$user[0]["dn"]; - - if (is_array($user[0]["proxyaddresses"])) { - $mod = array(); - for ($i=0;$i<sizeof($user[0]['proxyaddresses']);$i++) { - if (strstr($user[0]['proxyaddresses'][$i], 'SMTP:') !== false && $user[0]['proxyaddresses'][$i] == 'SMTP:' . $emailaddress) { - $mod['proxyAddresses'][0] = 'SMTP:' . $emailaddress; - } - elseif (strstr($user[0]['proxyaddresses'][$i], 'smtp:') !== false && $user[0]['proxyaddresses'][$i] == 'smtp:' . $emailaddress) { - $mod['proxyAddresses'][0] = 'smtp:' . $emailaddress; - } - } - - $result=@ldap_mod_del($this->_conn,$user_dn,$mod); - if ($result==false){ return (false); } - - return (true); - } - else { - return (false); - } - } - /** - * Change the default address - * - * @param string $username The username of the user to add the Exchange account to - * @param string $emailaddress The email address to make default - * @param bool $isGUID Is the username passed a GUID or a samAccountName - * @return bool - */ - public function exchange_primary_address($username, $emailaddress, $isGUID=false) { - if ($username===NULL){ return ("Missing compulsory field [username]"); } - if ($emailaddress===NULL) { return ("Missing compulsory fields [emailaddress]"); } - - // Find the dn of the user - $user=$this->user_info($username,array("cn","proxyaddresses"), $isGUID); - if ($user[0]["dn"]===NULL){ return (false); } - $user_dn=$user[0]["dn"]; - - if (is_array($user[0]["proxyaddresses"])) { - $modaddresses = array(); - for ($i=0;$i<sizeof($user[0]['proxyaddresses']);$i++) { - if (strstr($user[0]['proxyaddresses'][$i], 'SMTP:') !== false) { - $user[0]['proxyaddresses'][$i] = str_replace('SMTP:', 'smtp:', $user[0]['proxyaddresses'][$i]); - } - if ($user[0]['proxyaddresses'][$i] == 'smtp:' . $emailaddress) { - $user[0]['proxyaddresses'][$i] = str_replace('smtp:', 'SMTP:', $user[0]['proxyaddresses'][$i]); - } - if ($user[0]['proxyaddresses'][$i] != '') { - $modaddresses['proxyAddresses'][$i] = $user[0]['proxyaddresses'][$i]; - } - } - - $result=@ldap_mod_replace($this->_conn,$user_dn,$modaddresses); - if ($result==false){ return (false); } - - return (true); - } - - } - - /** - * Mail enable a contact - * Allows email to be sent to them through Exchange - * - * @param string $distinguishedname The contact to mail enable - * @param string $emailaddress The email address to allow emails to be sent through - * @param string $mailnickname The mailnickname for the contact in Exchange. If NULL this will be set to the display name - * @return bool - */ - public function exchange_contact_mailenable($distinguishedname, $emailaddress, $mailnickname=NULL){ - if ($distinguishedname===NULL){ return ("Missing compulsory field [distinguishedname]"); } - if ($emailaddress===NULL){ return ("Missing compulsory field [emailaddress]"); } - - if ($mailnickname !== NULL) { - // Find the dn of the user - $user=$this->contact_info($distinguishedname,array("cn","displayname")); - if ($user[0]["displayname"]===NULL){ return (false); } - $mailnickname = $user[0]['displayname'][0]; - } - - $attributes = array("email"=>$emailaddress,"contact_email"=>"SMTP:" . $emailaddress,"exchange_proxyaddress"=>"SMTP:" . $emailaddress,"exchange_mailnickname"=>$mailnickname); - - // Translate the update to the LDAP schema - $mod=$this->adldap_schema($attributes); - - // Check to see if this is an enabled status update - if (!$mod){ return (false); } - - // Do the update - $result=ldap_modify($this->_conn,$distinguishedname,$mod); - if ($result==false){ return (false); } - - return (true); - } - - /** - * Returns a list of Exchange Servers in the ConfigurationNamingContext of the domain - * - * @param array $attributes An array of the AD attributes you wish to return - * @return array - */ - public function exchange_servers($attributes = array('cn','distinguishedname','serialnumber')) { - if (!$this->_bind){ return (false); } - - $configurationNamingContext = $this->get_root_dse(array('configurationnamingcontext')); - $sr = @ldap_search($this->_conn,$configurationNamingContext[0]['configurationnamingcontext'][0],'(&(objectCategory=msExchExchangeServer))',$attributes); - $entries = @ldap_get_entries($this->_conn, $sr); - return $entries; - } - - /** - * Returns a list of Storage Groups in Exchange for a given mail server - * - * @param string $exchangeServer The full DN of an Exchange server. You can use exchange_servers() to find the DN for your server - * @param array $attributes An array of the AD attributes you wish to return - * @param bool $recursive If enabled this will automatically query the databases within a storage group - * @return array - */ - public function exchange_storage_groups($exchangeServer, $attributes = array('cn','distinguishedname'), $recursive = NULL) { - if (!$this->_bind){ return (false); } - if ($exchangeServer===NULL){ return ("Missing compulsory field [exchangeServer]"); } - if ($recursive===NULL){ $recursive=$this->_recursive_groups; } - - $filter = '(&(objectCategory=msExchStorageGroup))'; - $sr=@ldap_search($this->_conn, $exchangeServer, $filter, $attributes); - $entries = @ldap_get_entries($this->_conn, $sr); - - if ($recursive === true) { - for ($i=0; $i<$entries['count']; $i++) { - $entries[$i]['msexchprivatemdb'] = $this->exchange_storage_databases($entries[$i]['distinguishedname'][0]); - } - } - - return $entries; - } - - /** - * Returns a list of Databases within any given storage group in Exchange for a given mail server - * - * @param string $storageGroup The full DN of an Storage Group. You can use exchange_storage_groups() to find the DN - * @param array $attributes An array of the AD attributes you wish to return - * @return array - */ - public function exchange_storage_databases($storageGroup, $attributes = array('cn','distinguishedname','displayname')) { - if (!$this->_bind){ return (false); } - if ($storageGroup===NULL){ return ("Missing compulsory field [storageGroup]"); } - - $filter = '(&(objectCategory=msExchPrivateMDB))'; - $sr=@ldap_search($this->_conn, $storageGroup, $filter, $attributes); - $entries = @ldap_get_entries($this->_conn, $sr); - return $entries; - } - - //************************************************************************************************************ - // SERVER FUNCTIONS - - /** - * Find the Base DN of your domain controller - * - * @return string - */ - public function find_base_dn() { - $namingContext = $this->get_root_dse(array('defaultnamingcontext')); - return $namingContext[0]['defaultnamingcontext'][0]; - } - - /** - * Get the RootDSE properties from a domain controller - * - * @param array $attributes The attributes you wish to query e.g. defaultnamingcontext - * @return array - */ - public function get_root_dse($attributes = array("*", "+")) { - if (!$this->_bind){ return (false); } - - $sr = @ldap_read($this->_conn, NULL, 'objectClass=*', $attributes); - $entries = @ldap_get_entries($this->_conn, $sr); - return $entries; - } - - //************************************************************************************************************ - // UTILITY FUNCTIONS (Many of these functions are protected and can only be called from within the class) - - /** - * Get last error from Active Directory - * - * This function gets the last message from Active Directory - * This may indeed be a 'Success' message but if you get an unknown error - * it might be worth calling this function to see what errors were raised - * - * return string - */ - public function get_last_error() { - return @ldap_error($this->_conn); - } - - /** - * Detect LDAP support in php - * - * @return bool - */ - protected function ldap_supported() { - if (!function_exists('ldap_connect')) { - return (false); - } - return (true); - } - - /** - * Schema - * - * @param array $attributes Attributes to be queried - * @return array - */ - protected function adldap_schema($attributes){ - - // LDAP doesn't like NULL attributes, only set them if they have values - // If you wish to remove an attribute you should set it to a space - // TO DO: Adapt user_modify to use ldap_mod_delete to remove a NULL attribute - $mod=array(); - - // Check every attribute to see if it contains 8bit characters and then UTF8 encode them - array_walk($attributes, array($this, 'encode8bit')); - - if ($attributes["address_city"]){ $mod["l"][0]=$attributes["address_city"]; } - if ($attributes["address_code"]){ $mod["postalCode"][0]=$attributes["address_code"]; } - //if ($attributes["address_country"]){ $mod["countryCode"][0]=$attributes["address_country"]; } // use country codes? - if ($attributes["address_country"]){ $mod["c"][0]=$attributes["address_country"]; } - if ($attributes["address_pobox"]){ $mod["postOfficeBox"][0]=$attributes["address_pobox"]; } - if ($attributes["address_state"]){ $mod["st"][0]=$attributes["address_state"]; } - if ($attributes["address_street"]){ $mod["streetAddress"][0]=$attributes["address_street"]; } - if ($attributes["company"]){ $mod["company"][0]=$attributes["company"]; } - if ($attributes["change_password"]){ $mod["pwdLastSet"][0]=0; } - if ($attributes["department"]){ $mod["department"][0]=$attributes["department"]; } - if ($attributes["description"]){ $mod["description"][0]=$attributes["description"]; } - if ($attributes["display_name"]){ $mod["displayName"][0]=$attributes["display_name"]; } - if ($attributes["email"]){ $mod["mail"][0]=$attributes["email"]; } - if ($attributes["expires"]){ $mod["accountExpires"][0]=$attributes["expires"]; } //unix epoch format? - if ($attributes["firstname"]){ $mod["givenName"][0]=$attributes["firstname"]; } - if ($attributes["home_directory"]){ $mod["homeDirectory"][0]=$attributes["home_directory"]; } - if ($attributes["home_drive"]){ $mod["homeDrive"][0]=$attributes["home_drive"]; } - if ($attributes["initials"]){ $mod["initials"][0]=$attributes["initials"]; } - if ($attributes["logon_name"]){ $mod["userPrincipalName"][0]=$attributes["logon_name"]; } - if ($attributes["manager"]){ $mod["manager"][0]=$attributes["manager"]; } //UNTESTED ***Use DistinguishedName*** - if ($attributes["office"]){ $mod["physicalDeliveryOfficeName"][0]=$attributes["office"]; } - if ($attributes["password"]){ $mod["unicodePwd"][0]=$this->encode_password($attributes["password"]); } - if ($attributes["profile_path"]){ $mod["profilepath"][0]=$attributes["profile_path"]; } - if ($attributes["script_path"]){ $mod["scriptPath"][0]=$attributes["script_path"]; } - if ($attributes["surname"]){ $mod["sn"][0]=$attributes["surname"]; } - if ($attributes["title"]){ $mod["title"][0]=$attributes["title"]; } - if ($attributes["telephone"]){ $mod["telephoneNumber"][0]=$attributes["telephone"]; } - if ($attributes["mobile"]){ $mod["mobile"][0]=$attributes["mobile"]; } - if ($attributes["pager"]){ $mod["pager"][0]=$attributes["pager"]; } - if ($attributes["ipphone"]){ $mod["ipphone"][0]=$attributes["ipphone"]; } - if ($attributes["web_page"]){ $mod["wWWHomePage"][0]=$attributes["web_page"]; } - if ($attributes["fax"]){ $mod["facsimileTelephoneNumber"][0]=$attributes["fax"]; } - if ($attributes["enabled"]){ $mod["userAccountControl"][0]=$attributes["enabled"]; } - - // Distribution List specific schema - if ($attributes["group_sendpermission"]){ $mod["dlMemSubmitPerms"][0]=$attributes["group_sendpermission"]; } - if ($attributes["group_rejectpermission"]){ $mod["dlMemRejectPerms"][0]=$attributes["group_rejectpermission"]; } - - // Exchange Schema - if ($attributes["exchange_homemdb"]){ $mod["homeMDB"][0]=$attributes["exchange_homemdb"]; } - if ($attributes["exchange_mailnickname"]){ $mod["mailNickname"][0]=$attributes["exchange_mailnickname"]; } - if ($attributes["exchange_proxyaddress"]){ $mod["proxyAddresses"][0]=$attributes["exchange_proxyaddress"]; } - if ($attributes["exchange_usedefaults"]){ $mod["mDBUseDefaults"][0]=$attributes["exchange_usedefaults"]; } - if ($attributes["exchange_policyexclude"]){ $mod["msExchPoliciesExcluded"][0]=$attributes["exchange_policyexclude"]; } - if ($attributes["exchange_policyinclude"]){ $mod["msExchPoliciesIncluded"][0]=$attributes["exchange_policyinclude"]; } - if ($attributes["exchange_addressbook"]){ $mod["showInAddressBook"][0]=$attributes["exchange_addressbook"]; } - - // This schema is designed for contacts - if ($attributes["exchange_hidefromlists"]){ $mod["msExchHideFromAddressLists"][0]=$attributes["exchange_hidefromlists"]; } - if ($attributes["contact_email"]){ $mod["targetAddress"][0]=$attributes["contact_email"]; } - - //echo ("<pre>"); print_r($mod); - /* - // modifying a name is a bit fiddly - if ($attributes["firstname"] && $attributes["surname"]){ - $mod["cn"][0]=$attributes["firstname"]." ".$attributes["surname"]; - $mod["displayname"][0]=$attributes["firstname"]." ".$attributes["surname"]; - $mod["name"][0]=$attributes["firstname"]." ".$attributes["surname"]; - } - */ - - if (count($mod)==0){ return (false); } - return ($mod); - } - - /** - * Coping with AD not returning the primary group - * http://support.microsoft.com/?kbid=321360 - * - * For some reason it's not possible to search on primarygrouptoken=XXX - * If someone can show otherwise, I'd like to know about it :) - * this way is resource intensive and generally a pain in the @#%^ - * - * @deprecated deprecated since version 3.1, see get get_primary_group - * @param string $gid Group ID - * @return string - */ - protected function group_cn($gid){ - if ($gid===NULL){ return (false); } - $r=false; - - $filter="(&(objectCategory=group)(samaccounttype=". ADLDAP_SECURITY_GLOBAL_GROUP ."))"; - $fields=array("primarygrouptoken","samaccountname","distinguishedname"); - $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields); - $entries = ldap_get_entries($this->_conn, $sr); - - for ($i=0; $i<$entries["count"]; $i++){ - if ($entries[$i]["primarygrouptoken"][0]==$gid){ - $r=$entries[$i]["distinguishedname"][0]; - $i=$entries["count"]; - } - } - - return ($r); - } - - /** - * Coping with AD not returning the primary group - * http://support.microsoft.com/?kbid=321360 - * - * This is a re-write based on code submitted by Bruce which prevents the - * need to search each security group to find the true primary group - * - * @param string $gid Group ID - * @param string $usersid User's Object SID - * @return string - */ - protected function get_primary_group($gid, $usersid){ - if ($gid===NULL || $usersid===NULL){ return (false); } - $r=false; - - $gsid = substr_replace($usersid,pack('V',$gid),strlen($usersid)-4,4); - $filter='(objectsid='.$this->getTextSID($gsid).')'; - $fields=array("samaccountname","distinguishedname"); - $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields); - $entries = ldap_get_entries($this->_conn, $sr); - - return $entries[0]['distinguishedname'][0]; - } - - /** - * Convert a binary SID to a text SID - * - * @param string $binsid A Binary SID - * @return string - */ - protected function getTextSID($binsid) { - $hex_sid = bin2hex($binsid); - $rev = hexdec(substr($hex_sid, 0, 2)); - $subcount = hexdec(substr($hex_sid, 2, 2)); - $auth = hexdec(substr($hex_sid, 4, 12)); - $result = "$rev-$auth"; - - for ($x=0;$x < $subcount; $x++) { - $subauth[$x] = - hexdec($this->little_endian(substr($hex_sid, 16 + ($x * 8), 8))); - $result .= "-" . $subauth[$x]; - } - - // Cheat by tacking on the S- - return 'S-' . $result; - } - - /** - * Converts a little-endian hex number to one that hexdec() can convert - * - * @param string $hex A hex code - * @return string - */ - protected function little_endian($hex) { - $result = ''; - for ($x = strlen($hex) - 2; $x >= 0; $x = $x - 2) { - $result .= substr($hex, $x, 2); - } - return $result; - } - - /** - * Converts a binary attribute to a string - * - * @param string $bin A binary LDAP attribute - * @return string - */ - protected function binary2text($bin) { - $hex_guid = bin2hex($bin); - $hex_guid_to_guid_str = ''; - for($k = 1; $k <= 4; ++$k) { - $hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2); - } - $hex_guid_to_guid_str .= '-'; - for($k = 1; $k <= 2; ++$k) { - $hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2); - } - $hex_guid_to_guid_str .= '-'; - for($k = 1; $k <= 2; ++$k) { - $hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2); - } - $hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4); - $hex_guid_to_guid_str .= '-' . substr($hex_guid, 20); - return strtoupper($hex_guid_to_guid_str); - } - - /** - * Converts a binary GUID to a string GUID - * - * @param string $binaryGuid The binary GUID attribute to convert - * @return string - */ - public function decodeGuid($binaryGuid) { - if ($binaryGuid === null){ return ("Missing compulsory field [binaryGuid]"); } - - $strGUID = $this->binary2text($binaryGuid); - return ($strGUID); - } - - /** - * Converts a string GUID to a hexdecimal value so it can be queried - * - * @param string $strGUID A string representation of a GUID - * @return string - */ - protected function strguid2hex($strGUID) { - $strGUID = str_replace('-', '', $strGUID); - - $octet_str = '\\' . substr($strGUID, 6, 2); - $octet_str .= '\\' . substr($strGUID, 4, 2); - $octet_str .= '\\' . substr($strGUID, 2, 2); - $octet_str .= '\\' . substr($strGUID, 0, 2); - $octet_str .= '\\' . substr($strGUID, 10, 2); - $octet_str .= '\\' . substr($strGUID, 8, 2); - $octet_str .= '\\' . substr($strGUID, 14, 2); - $octet_str .= '\\' . substr($strGUID, 12, 2); - //$octet_str .= '\\' . substr($strGUID, 16, strlen($strGUID)); - for ($i=16; $i<=(strlen($strGUID)-2); $i++) { - if (($i % 2) == 0) { - $octet_str .= '\\' . substr($strGUID, $i, 2); - } - } - - return $octet_str; - } - - /** - * Obtain the user's distinguished name based on their userid - * - * - * @param string $username The username - * @param bool $isGUID Is the username passed a GUID or a samAccountName - * @return string - */ - protected function user_dn($username,$isGUID=false){ - $user=$this->user_info($username,array("cn"),$isGUID); - if ($user[0]["dn"]===NULL){ return (false); } - $user_dn=$user[0]["dn"]; - return ($user_dn); - } - - /** - * Encode a password for transmission over LDAP - * - * @param string $password The password to encode - * @return string - */ - protected function encode_password($password){ - $password="\"".$password."\""; - $encoded=""; - for ($i=0; $i <strlen($password); $i++){ $encoded.="{$password{$i}}\000"; } - return ($encoded); - } - - /** - * Escape strings for the use in LDAP filters - * - * DEVELOPERS SHOULD BE DOING PROPER FILTERING IF THEY'RE ACCEPTING USER INPUT - * Ported from Perl's Net::LDAP::Util escape_filter_value - * - * @param string $str The string the parse - * @author Port by Andreas Gohr <andi@splitbrain.org> - * @return string - */ - protected function ldap_slashes($str){ - return preg_replace('/([\x00-\x1F\*\(\)\\\\])/e', - '"\\\\\".join("",unpack("H2","$1"))', - $str); - } - - /** - * Select a random domain controller from your domain controller array - * - * @return string - */ - protected function random_controller(){ - mt_srand(doubleval(microtime()) * 100000000); // For older PHP versions - return ($this->_domain_controllers[array_rand($this->_domain_controllers)]); - } - - /** - * Account control options - * - * @param array $options The options to convert to int - * @return int - */ - protected function account_control($options){ - $val=0; - - if (is_array($options)){ - if (in_array("SCRIPT",$options)){ $val=$val+1; } - if (in_array("ACCOUNTDISABLE",$options)){ $val=$val+2; } - if (in_array("HOMEDIR_REQUIRED",$options)){ $val=$val+8; } - if (in_array("LOCKOUT",$options)){ $val=$val+16; } - if (in_array("PASSWD_NOTREQD",$options)){ $val=$val+32; } - //PASSWD_CANT_CHANGE Note You cannot assign this permission by directly modifying the UserAccountControl attribute. - //For information about how to set the permission programmatically, see the "Property flag descriptions" section. - if (in_array("ENCRYPTED_TEXT_PWD_ALLOWED",$options)){ $val=$val+128; } - if (in_array("TEMP_DUPLICATE_ACCOUNT",$options)){ $val=$val+256; } - if (in_array("NORMAL_ACCOUNT",$options)){ $val=$val+512; } - if (in_array("INTERDOMAIN_TRUST_ACCOUNT",$options)){ $val=$val+2048; } - if (in_array("WORKSTATION_TRUST_ACCOUNT",$options)){ $val=$val+4096; } - if (in_array("SERVER_TRUST_ACCOUNT",$options)){ $val=$val+8192; } - if (in_array("DONT_EXPIRE_PASSWORD",$options)){ $val=$val+65536; } - if (in_array("MNS_LOGON_ACCOUNT",$options)){ $val=$val+131072; } - if (in_array("SMARTCARD_REQUIRED",$options)){ $val=$val+262144; } - if (in_array("TRUSTED_FOR_DELEGATION",$options)){ $val=$val+524288; } - if (in_array("NOT_DELEGATED",$options)){ $val=$val+1048576; } - if (in_array("USE_DES_KEY_ONLY",$options)){ $val=$val+2097152; } - if (in_array("DONT_REQ_PREAUTH",$options)){ $val=$val+4194304; } - if (in_array("PASSWORD_EXPIRED",$options)){ $val=$val+8388608; } - if (in_array("TRUSTED_TO_AUTH_FOR_DELEGATION",$options)){ $val=$val+16777216; } - } - return ($val); - } - - /** - * Take an LDAP query and return the nice names, without all the LDAP prefixes (eg. CN, DN) - * - * @param array $groups - * @return array - */ - protected function nice_names($groups){ - - $group_array=array(); - for ($i=0; $i<$groups["count"]; $i++){ // For each group - $line=$groups[$i]; - - if (strlen($line)>0){ - // More presumptions, they're all prefixed with CN= - // so we ditch the first three characters and the group - // name goes up to the first comma - $bits=explode(",",$line); - $group_array[]=substr($bits[0],3,(strlen($bits[0])-3)); - } - } - return ($group_array); - } - - /** - * Delete a distinguished name from Active Directory - * You should never need to call this yourself, just use the wrapper functions user_delete and contact_delete - * - * @param string $dn The distinguished name to delete - * @return bool - */ - protected function dn_delete($dn){ - $result=ldap_delete($this->_conn, $dn); - if ($result!=true){ return (false); } - return (true); - } - - /** - * Convert a boolean value to a string - * You should never need to call this yourself - * - * @param bool $bool Boolean value - * @return string - */ - protected function bool2str($bool) { - return ($bool) ? 'TRUE' : 'FALSE'; - } - - /** - * Convert 8bit characters e.g. accented characters to UTF8 encoded characters - */ - protected function encode8bit(&$item, $key) { - $encode = false; - if (is_string($item)) { - for ($i=0; $i<strlen($item); $i++) { - if (ord($item[$i]) >> 7) { - $encode = true; - } - } - } - if ($encode === true && $key != 'password') { - $item = utf8_encode($item); - } - } -} - -/** -* adLDAP Exception Handler -* -* Exceptions of this type are thrown on bind failure or when SSL is required but not configured -* Example: -* try { -* $adldap = new adLDAP(); -* } -* catch (adLDAPException $e) { -* echo $e; -* exit(); -* } -*/ -class adLDAPException extends Exception {} - -?> diff --git a/inc/auth.php b/inc/auth.php index 1c8a8f5f5..76356c37f 100644 --- a/inc/auth.php +++ b/inc/auth.php @@ -34,38 +34,37 @@ define('AUTH_ADMIN', 255); */ function auth_setup() { global $conf; - /* @var auth_basic $auth */ + /* @var DokuWiki_Auth_Plugin $auth */ global $auth; /* @var Input $INPUT */ global $INPUT; global $AUTH_ACL; global $lang; + global $config_cascade; + global $plugin_controller; $AUTH_ACL = array(); if(!$conf['useacl']) return false; - // load the the backend auth functions and instantiate the auth object XXX - if(@file_exists(DOKU_INC.'inc/auth/'.$conf['authtype'].'.class.php')) { - require_once(DOKU_INC.'inc/auth/basic.class.php'); - require_once(DOKU_INC.'inc/auth/'.$conf['authtype'].'.class.php'); - - $auth_class = "auth_".$conf['authtype']; - if(class_exists($auth_class)) { - $auth = new $auth_class(); - if($auth->success == false) { - // degrade to unauthenticated user - unset($auth); - auth_logoff(); - msg($lang['authtempfail'], -1); - } - } else { - nice_die($lang['authmodfailed']); - } - } else { - nice_die($lang['authmodfailed']); + // try to load auth backend from plugins + foreach ($plugin_controller->getList('auth') as $plugin) { + if ($conf['authtype'] === $plugin) { + $auth = $plugin_controller->load('auth', $plugin); + break; + } } - if(!isset($auth) || !$auth) return false; + if(!$auth){ + msg($lang['authtempfail'], -1); + return false; + } + + if ($auth && $auth->success == false) { + // degrade to unauthenticated user + unset($auth); + auth_logoff(); + msg($lang['authtempfail'], -1); + } // do the login either by cookie or provided credentials XXX $INPUT->set('http_credentials', false); @@ -91,7 +90,9 @@ function auth_setup() { } // apply cleaning - $INPUT->set('u', $auth->cleanUser($INPUT->str('u'))); + if (true === $auth->success) { + $_REQUEST['u'] = $auth->cleanUser($_REQUEST['u']); + } if($INPUT->str('authtok')) { // when an authentication token is given, trust the session diff --git a/inc/auth/ad.class.php b/inc/auth/ad.class.php deleted file mode 100644 index e161c2939..000000000 --- a/inc/auth/ad.class.php +++ /dev/null @@ -1,390 +0,0 @@ -<?php -/** - * Active Directory authentication backend for DokuWiki - * - * This makes authentication with a Active Directory server much easier - * than when using the normal LDAP backend by utilizing the adLDAP library - * - * Usage: - * Set DokuWiki's local.protected.php auth setting to read - * - * $conf['useacl'] = 1; - * $conf['disableactions'] = 'register'; - * $conf['autopasswd'] = 0; - * $conf['authtype'] = 'ad'; - * $conf['passcrypt'] = 'ssha'; - * - * $conf['auth']['ad']['account_suffix'] = '@my.domain.org'; - * $conf['auth']['ad']['base_dn'] = 'DC=my,DC=domain,DC=org'; - * $conf['auth']['ad']['domain_controllers'] = 'srv1.domain.org,srv2.domain.org'; - * - * //optional: - * $conf['auth']['ad']['sso'] = 1; - * $conf['auth']['ad']['ad_username'] = 'root'; - * $conf['auth']['ad']['ad_password'] = 'pass'; - * $conf['auth']['ad']['real_primarygroup'] = 1; - * $conf['auth']['ad']['use_ssl'] = 1; - * $conf['auth']['ad']['use_tls'] = 1; - * $conf['auth']['ad']['debug'] = 1; - * // warn user about expiring password this many days in advance: - * $conf['auth']['ad']['expirywarn'] = 5; - * - * // get additional information to the userinfo array - * // add a list of comma separated ldap contact fields. - * $conf['auth']['ad']['additional'] = 'field1,field2'; - * - * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) - * @author James Van Lommel <jamesvl@gmail.com> - * @link http://www.nosq.com/blog/2005/08/ldap-activedirectory-and-dokuwiki/ - * @author Andreas Gohr <andi@splitbrain.org> - */ - -require_once(DOKU_INC.'inc/adLDAP.php'); - -class auth_ad extends auth_basic { - var $cnf = null; - var $opts = null; - var $adldap = null; - var $users = null; - var $msgshown = false; - - /** - * Constructor - */ - function __construct() { - global $conf; - $this->cnf = $conf['auth']['ad']; - - // additional information fields - if (isset($this->cnf['additional'])) { - $this->cnf['additional'] = str_replace(' ', '', $this->cnf['additional']); - $this->cnf['additional'] = explode(',', $this->cnf['additional']); - } else $this->cnf['additional'] = array(); - - // ldap extension is needed - if (!function_exists('ldap_connect')) { - if ($this->cnf['debug']) - msg("AD Auth: PHP LDAP extension not found.",-1); - $this->success = false; - return; - } - - // Prepare SSO - if(!utf8_check($_SERVER['REMOTE_USER'])){ - $_SERVER['REMOTE_USER'] = utf8_encode($_SERVER['REMOTE_USER']); - } - if($_SERVER['REMOTE_USER'] && $this->cnf['sso']){ - // remove possible NTLM domain - list($dom,$usr) = explode('\\',$_SERVER['REMOTE_USER'],2); - if(!$usr) $usr = $dom; - - // remove possible Kerberos domain - list($usr,$dom) = explode('@',$usr); - - $dom = strtolower($dom); - $_SERVER['REMOTE_USER'] = $usr; - - // we need to simulate a login - if(empty($_COOKIE[DOKU_COOKIE])){ - $_REQUEST['u'] = $_SERVER['REMOTE_USER']; - $_REQUEST['p'] = 'sso_only'; - } - } - - // prepare adLDAP standard configuration - $this->opts = $this->cnf; - - // add possible domain specific configuration - if($dom && is_array($this->cnf[$dom])) foreach($this->cnf[$dom] as $key => $val){ - $this->opts[$key] = $val; - } - - // handle multiple AD servers - $this->opts['domain_controllers'] = explode(',',$this->opts['domain_controllers']); - $this->opts['domain_controllers'] = array_map('trim',$this->opts['domain_controllers']); - $this->opts['domain_controllers'] = array_filter($this->opts['domain_controllers']); - - // we can change the password if SSL is set - if($this->opts['use_ssl'] || $this->opts['use_tls']){ - $this->cando['modPass'] = true; - } - $this->cando['modName'] = true; - $this->cando['modMail'] = true; - } - - /** - * Check user+password [required auth function] - * - * Checks if the given user exists and the given - * plaintext password is correct by trying to bind - * to the LDAP server - * - * @author James Van Lommel <james@nosq.com> - * @return bool - */ - function checkPass($user, $pass){ - if($_SERVER['REMOTE_USER'] && - $_SERVER['REMOTE_USER'] == $user && - $this->cnf['sso']) return true; - - if(!$this->_init()) return false; - return $this->adldap->authenticate($user, $pass); - } - - /** - * Return user info [required auth function] - * - * Returns info about the given user needs to contain - * at least these fields: - * - * name string full name of the user - * mail string email address of the user - * grps array list of groups the user is in - * - * This LDAP specific function returns the following - * addional fields: - * - * dn string distinguished name (DN) - * uid string Posix User ID - * - * @author James Van Lommel <james@nosq.com> - */ - function getUserData($user){ - global $conf; - global $lang; - global $ID; - if(!$this->_init()) return false; - - if($user == '') return array(); - - $fields = array('mail','displayname','samaccountname','lastpwd','pwdlastset','useraccountcontrol'); - - // add additional fields to read - $fields = array_merge($fields, $this->cnf['additional']); - $fields = array_unique($fields); - - //get info for given user - $result = $this->adldap->user_info($user, $fields); - if($result == false){ - return array(); - } - - //general user info - $info['name'] = $result[0]['displayname'][0]; - $info['mail'] = $result[0]['mail'][0]; - $info['uid'] = $result[0]['samaccountname'][0]; - $info['dn'] = $result[0]['dn']; - //last password set (Windows counts from January 1st 1601) - $info['lastpwd'] = $result[0]['pwdlastset'][0] / 10000000 - 11644473600; - //will it expire? - $info['expires'] = !($result[0]['useraccountcontrol'][0] & 0x10000); //ADS_UF_DONT_EXPIRE_PASSWD - - // additional information - foreach ($this->cnf['additional'] as $field) { - if (isset($result[0][strtolower($field)])) { - $info[$field] = $result[0][strtolower($field)][0]; - } - } - - // handle ActiveDirectory memberOf - $info['grps'] = $this->adldap->user_groups($user,(bool) $this->opts['recursive_groups']); - - if (is_array($info['grps'])) { - foreach ($info['grps'] as $ndx => $group) { - $info['grps'][$ndx] = $this->cleanGroup($group); - } - } - - // always add the default group to the list of groups - if(!is_array($info['grps']) || !in_array($conf['defaultgroup'],$info['grps'])){ - $info['grps'][] = $conf['defaultgroup']; - } - - // check expiry time - if($info['expires'] && $this->cnf['expirywarn']){ - $result = $this->adldap->domain_info(array('maxpwdage')); // maximum pass age - $maxage = -1 * $result['maxpwdage'][0] / 10000000; // negative 100 nanosecs - $timeleft = $maxage - (time() - $info['lastpwd']); - $timeleft = round($timeleft/(24*60*60)); - $info['expiresin'] = $timeleft; - - // if this is the current user, warn him (once per request only) - if( ($_SERVER['REMOTE_USER'] == $user) && - ($timeleft <= $this->cnf['expirywarn']) && - !$this->msgshown - ){ - $msg = sprintf($lang['authpwdexpire'],$timeleft); - if($this->canDo('modPass')){ - $url = wl($ID,array('do'=>'profile')); - $msg .= ' <a href="'.$url.'">'.$lang['btn_profile'].'</a>'; - } - msg($msg); - $this->msgshown = true; - } - } - - return $info; - } - - /** - * Make AD group names usable by DokuWiki. - * - * Removes backslashes ('\'), pound signs ('#'), and converts spaces to underscores. - * - * @author James Van Lommel (jamesvl@gmail.com) - */ - function cleanGroup($name) { - $sName = str_replace('\\', '', $name); - $sName = str_replace('#', '', $sName); - $sName = preg_replace('[\s]', '_', $sName); - return $sName; - } - - /** - * Sanitize user names - */ - function cleanUser($name) { - return $this->cleanGroup($name); - } - - /** - * Most values in LDAP are case-insensitive - */ - function isCaseSensitive(){ - return false; - } - - /** - * Bulk retrieval of user data - * - * @author Dominik Eckelmann <dokuwiki@cosmocode.de> - * @param start index of first user to be returned - * @param limit max number of users to be returned - * @param filter array of field/pattern pairs, null for no filter - * @return array of userinfo (refer getUserData for internal userinfo details) - */ - function retrieveUsers($start=0,$limit=-1,$filter=array()) { - if(!$this->_init()) return false; - - if ($this->users === null) { - //get info for given user - $result = $this->adldap->all_users(); - if (!$result) return array(); - $this->users = array_fill_keys($result, false); - } - - $i = 0; - $count = 0; - $this->_constructPattern($filter); - $result = array(); - - foreach ($this->users as $user => &$info) { - if ($i++ < $start) { - continue; - } - if ($info === false) { - $info = $this->getUserData($user); - } - if ($this->_filter($user, $info)) { - $result[$user] = $info; - if (($limit >= 0) && (++$count >= $limit)) break; - } - } - return $result; - } - - /** - * Modify user data - * - * @param $user nick of the user to be changed - * @param $changes array of field/value pairs to be changed - * @return bool - */ - function modifyUser($user, $changes) { - $return = true; - - // password changing - if(isset($changes['pass'])){ - try { - $return = $this->adldap->user_password($user,$changes['pass']); - } catch (adLDAPException $e) { - if ($this->cnf['debug']) msg('AD Auth: '.$e->getMessage(), -1); - $return = false; - } - if(!$return) msg('AD Auth: failed to change the password. Maybe the password policy was not met?',-1); - } - - // changing user data - $adchanges = array(); - if(isset($changes['name'])){ - // get first and last name - $parts = explode(' ',$changes['name']); - $adchanges['surname'] = array_pop($parts); - $adchanges['firstname'] = join(' ',$parts); - $adchanges['display_name'] = $changes['name']; - } - if(isset($changes['mail'])){ - $adchanges['email'] = $changes['mail']; - } - if(count($adchanges)){ - try { - $return = $return & $this->adldap->user_modify($user,$adchanges); - } catch (adLDAPException $e) { - if ($this->cnf['debug']) msg('AD Auth: '.$e->getMessage(), -1); - $return = false; - } - } - - return $return; - } - - /** - * Initialize the AdLDAP library and connect to the server - */ - function _init(){ - if(!is_null($this->adldap)) return true; - - // connect - try { - $this->adldap = new adLDAP($this->opts); - if (isset($this->opts['ad_username']) && isset($this->opts['ad_password'])) { - $this->canDo['getUsers'] = true; - } - return true; - } catch (adLDAPException $e) { - if ($this->cnf['debug']) { - msg('AD Auth: '.$e->getMessage(), -1); - } - $this->success = false; - $this->adldap = null; - } - return false; - } - - /** - * return 1 if $user + $info match $filter criteria, 0 otherwise - * - * @author Chris Smith <chris@jalakai.co.uk> - */ - function _filter($user, $info) { - foreach ($this->_pattern as $item => $pattern) { - if ($item == 'user') { - if (!preg_match($pattern, $user)) return 0; - } else if ($item == 'grps') { - if (!count(preg_grep($pattern, $info['grps']))) return 0; - } else { - if (!preg_match($pattern, $info[$item])) return 0; - } - } - return 1; - } - - function _constructPattern($filter) { - $this->_pattern = array(); - foreach ($filter as $item => $pattern) { - $this->_pattern[$item] = '/'.str_replace('/','\/',$pattern).'/i'; // allow regex characters - } - } -} - -//Setup VIM: ex: et ts=4 : diff --git a/inc/auth/ldap.class.php b/inc/auth/ldap.class.php deleted file mode 100644 index 23c2c281c..000000000 --- a/inc/auth/ldap.class.php +++ /dev/null @@ -1,486 +0,0 @@ -<?php -/** - * LDAP authentication backend - * - * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) - * @author Andreas Gohr <andi@splitbrain.org> - * @author Chris Smith <chris@jalakaic.co.uk> - */ - -class auth_ldap extends auth_basic { - var $cnf = null; - var $con = null; - var $bound = 0; // 0: anonymous, 1: user, 2: superuser - - /** - * Constructor - */ - function __construct(){ - global $conf; - $this->cnf = $conf['auth']['ldap']; - - // ldap extension is needed - if(!function_exists('ldap_connect')) { - if ($this->cnf['debug']) - msg("LDAP err: PHP LDAP extension not found.",-1,__LINE__,__FILE__); - $this->success = false; - return; - } - - if(empty($this->cnf['groupkey'])) $this->cnf['groupkey'] = 'cn'; - if(empty($this->cnf['userscope'])) $this->cnf['userscope'] = 'sub'; - if(empty($this->cnf['groupscope'])) $this->cnf['groupscope'] = 'sub'; - - // auth_ldap currently just handles authentication, so no - // capabilities are set - } - - /** - * Check user+password - * - * Checks if the given user exists and the given - * plaintext password is correct by trying to bind - * to the LDAP server - * - * @author Andreas Gohr <andi@splitbrain.org> - * @return bool - */ - function checkPass($user,$pass){ - // reject empty password - if(empty($pass)) return false; - if(!$this->_openLDAP()) return false; - - // indirect user bind - if($this->cnf['binddn'] && $this->cnf['bindpw']){ - // use superuser credentials - if(!@ldap_bind($this->con,$this->cnf['binddn'],$this->cnf['bindpw'])){ - if($this->cnf['debug']) - msg('LDAP bind as superuser: '.htmlspecialchars(ldap_error($this->con)),0,__LINE__,__FILE__); - return false; - } - $this->bound = 2; - }else if($this->cnf['binddn'] && - $this->cnf['usertree'] && - $this->cnf['userfilter']) { - // special bind string - $dn = $this->_makeFilter($this->cnf['binddn'], - array('user'=>$user,'server'=>$this->cnf['server'])); - - }else if(strpos($this->cnf['usertree'], '%{user}')) { - // direct user bind - $dn = $this->_makeFilter($this->cnf['usertree'], - array('user'=>$user,'server'=>$this->cnf['server'])); - - }else{ - // Anonymous bind - if(!@ldap_bind($this->con)){ - msg("LDAP: can not bind anonymously",-1); - if($this->cnf['debug']) - msg('LDAP anonymous bind: '.htmlspecialchars(ldap_error($this->con)),0,__LINE__,__FILE__); - return false; - } - } - - // Try to bind to with the dn if we have one. - if(!empty($dn)) { - // User/Password bind - if(!@ldap_bind($this->con,$dn,$pass)){ - if($this->cnf['debug']){ - msg("LDAP: bind with $dn failed", -1,__LINE__,__FILE__); - msg('LDAP user dn bind: '.htmlspecialchars(ldap_error($this->con)),0); - } - return false; - } - $this->bound = 1; - return true; - }else{ - // See if we can find the user - $info = $this->getUserData($user,true); - if(empty($info['dn'])) { - return false; - } else { - $dn = $info['dn']; - } - - // Try to bind with the dn provided - if(!@ldap_bind($this->con,$dn,$pass)){ - if($this->cnf['debug']){ - msg("LDAP: bind with $dn failed", -1,__LINE__,__FILE__); - msg('LDAP user bind: '.htmlspecialchars(ldap_error($this->con)),0); - } - return false; - } - $this->bound = 1; - return true; - } - - return false; - } - - /** - * Return user info - * - * Returns info about the given user needs to contain - * at least these fields: - * - * name string full name of the user - * mail string email addres of the user - * grps array list of groups the user is in - * - * This LDAP specific function returns the following - * addional fields: - * - * dn string distinguished name (DN) - * uid string Posix User ID - * inbind bool for internal use - avoid loop in binding - * - * @author Andreas Gohr <andi@splitbrain.org> - * @author Trouble - * @author Dan Allen <dan.j.allen@gmail.com> - * @author <evaldas.auryla@pheur.org> - * @author Stephane Chazelas <stephane.chazelas@emerson.com> - * @return array containing user data or false - */ - function getUserData($user,$inbind=false) { - global $conf; - if(!$this->_openLDAP()) return false; - - // force superuser bind if wanted and not bound as superuser yet - if($this->cnf['binddn'] && $this->cnf['bindpw'] && $this->bound < 2){ - // use superuser credentials - if(!@ldap_bind($this->con,$this->cnf['binddn'],$this->cnf['bindpw'])){ - if($this->cnf['debug']) - msg('LDAP bind as superuser: '.htmlspecialchars(ldap_error($this->con)),0,__LINE__,__FILE__); - return false; - } - $this->bound = 2; - }elseif($this->bound == 0 && !$inbind) { - // in some cases getUserData is called outside the authentication workflow - // eg. for sending email notification on subscribed pages. This data might not - // be accessible anonymously, so we try to rebind the current user here - list($loginuser,$loginsticky,$loginpass) = auth_getCookie(); - if($loginuser && $loginpass){ - $loginpass = PMA_blowfish_decrypt($loginpass, auth_cookiesalt(!$loginsticky)); - $this->checkPass($loginuser, $loginpass); - } - } - - $info['user'] = $user; - $info['server'] = $this->cnf['server']; - - //get info for given user - $base = $this->_makeFilter($this->cnf['usertree'], $info); - if(!empty($this->cnf['userfilter'])) { - $filter = $this->_makeFilter($this->cnf['userfilter'], $info); - } else { - $filter = "(ObjectClass=*)"; - } - - $sr = $this->_ldapsearch($this->con, $base, $filter, $this->cnf['userscope']); - $result = @ldap_get_entries($this->con, $sr); - if($this->cnf['debug']){ - msg('LDAP user search: '.htmlspecialchars(ldap_error($this->con)),0,__LINE__,__FILE__); - msg('LDAP search at: '.htmlspecialchars($base.' '.$filter),0,__LINE__,__FILE__); - } - - // Don't accept more or less than one response - if(!is_array($result) || $result['count'] != 1){ - return false; //user not found - } - - $user_result = $result[0]; - ldap_free_result($sr); - - // general user info - $info['dn'] = $user_result['dn']; - $info['gid'] = $user_result['gidnumber'][0]; - $info['mail'] = $user_result['mail'][0]; - $info['name'] = $user_result['cn'][0]; - $info['grps'] = array(); - - // overwrite if other attribs are specified. - if(is_array($this->cnf['mapping'])){ - foreach($this->cnf['mapping'] as $localkey => $key) { - if(is_array($key)) { - // use regexp to clean up user_result - list($key, $regexp) = each($key); - if($user_result[$key]) foreach($user_result[$key] as $grp){ - if (preg_match($regexp,$grp,$match)) { - if($localkey == 'grps') { - $info[$localkey][] = $match[1]; - } else { - $info[$localkey] = $match[1]; - } - } - } - } else { - $info[$localkey] = $user_result[$key][0]; - } - } - } - $user_result = array_merge($info,$user_result); - - //get groups for given user if grouptree is given - if ($this->cnf['grouptree'] || $this->cnf['groupfilter']) { - $base = $this->_makeFilter($this->cnf['grouptree'], $user_result); - $filter = $this->_makeFilter($this->cnf['groupfilter'], $user_result); - $sr = $this->_ldapsearch($this->con, $base, $filter, $this->cnf['groupscope'], array($this->cnf['groupkey'])); - if($this->cnf['debug']){ - msg('LDAP group search: '.htmlspecialchars(ldap_error($this->con)),0,__LINE__,__FILE__); - msg('LDAP search at: '.htmlspecialchars($base.' '.$filter),0,__LINE__,__FILE__); - } - if(!$sr){ - msg("LDAP: Reading group memberships failed",-1); - return false; - } - $result = ldap_get_entries($this->con, $sr); - ldap_free_result($sr); - - if(is_array($result)) foreach($result as $grp){ - if(!empty($grp[$this->cnf['groupkey']][0])){ - if($this->cnf['debug']) - msg('LDAP usergroup: '.htmlspecialchars($grp[$this->cnf['groupkey']][0]),0,__LINE__,__FILE__); - $info['grps'][] = $grp[$this->cnf['groupkey']][0]; - } - } - } - - // always add the default group to the list of groups - if(!in_array($conf['defaultgroup'],$info['grps'])){ - $info['grps'][] = $conf['defaultgroup']; - } - return $info; - } - - /** - * Most values in LDAP are case-insensitive - */ - function isCaseSensitive(){ - return false; - } - - /** - * Bulk retrieval of user data - * - * @author Dominik Eckelmann <dokuwiki@cosmocode.de> - * @param start index of first user to be returned - * @param limit max number of users to be returned - * @param filter array of field/pattern pairs, null for no filter - * @return array of userinfo (refer getUserData for internal userinfo details) - */ - function retrieveUsers($start=0,$limit=-1,$filter=array()) { - if(!$this->_openLDAP()) return false; - - if (!isset($this->users)) { - // Perform the search and grab all their details - if(!empty($this->cnf['userfilter'])) { - $all_filter = str_replace('%{user}', '*', $this->cnf['userfilter']); - } else { - $all_filter = "(ObjectClass=*)"; - } - $sr=ldap_search($this->con,$this->cnf['usertree'],$all_filter); - $entries = ldap_get_entries($this->con, $sr); - $users_array = array(); - for ($i=0; $i<$entries["count"]; $i++){ - array_push($users_array, $entries[$i]["uid"][0]); - } - asort($users_array); - $result = $users_array; - if (!$result) return array(); - $this->users = array_fill_keys($result, false); - } - $i = 0; - $count = 0; - $this->_constructPattern($filter); - $result = array(); - - foreach ($this->users as $user => &$info) { - if ($i++ < $start) { - continue; - } - if ($info === false) { - $info = $this->getUserData($user); - } - if ($this->_filter($user, $info)) { - $result[$user] = $info; - if (($limit >= 0) && (++$count >= $limit)) break; - } - } - return $result; - } - - /** - * Make LDAP filter strings. - * - * Used by auth_getUserData to make the filter - * strings for grouptree and groupfilter - * - * filter string ldap search filter with placeholders - * placeholders array array with the placeholders - * - * @author Troels Liebe Bentsen <tlb@rapanden.dk> - * @return string - */ - function _makeFilter($filter, $placeholders) { - preg_match_all("/%{([^}]+)/", $filter, $matches, PREG_PATTERN_ORDER); - //replace each match - foreach ($matches[1] as $match) { - //take first element if array - if(is_array($placeholders[$match])) { - $value = $placeholders[$match][0]; - } else { - $value = $placeholders[$match]; - } - $value = $this->_filterEscape($value); - $filter = str_replace('%{'.$match.'}', $value, $filter); - } - return $filter; - } - - /** - * return 1 if $user + $info match $filter criteria, 0 otherwise - * - * @author Chris Smith <chris@jalakai.co.uk> - */ - function _filter($user, $info) { - foreach ($this->_pattern as $item => $pattern) { - if ($item == 'user') { - if (!preg_match($pattern, $user)) return 0; - } else if ($item == 'grps') { - if (!count(preg_grep($pattern, $info['grps']))) return 0; - } else { - if (!preg_match($pattern, $info[$item])) return 0; - } - } - return 1; - } - - function _constructPattern($filter) { - $this->_pattern = array(); - foreach ($filter as $item => $pattern) { - $this->_pattern[$item] = '/'.str_replace('/','\/',$pattern).'/i'; // allow regex characters - } - } - - /** - * Escape a string to be used in a LDAP filter - * - * Ported from Perl's Net::LDAP::Util escape_filter_value - * - * @author Andreas Gohr - */ - function _filterEscape($string){ - return preg_replace('/([\x00-\x1F\*\(\)\\\\])/e', - '"\\\\\".join("",unpack("H2","$1"))', - $string); - } - - /** - * Opens a connection to the configured LDAP server and sets the wanted - * option on the connection - * - * @author Andreas Gohr <andi@splitbrain.org> - */ - function _openLDAP(){ - if($this->con) return true; // connection already established - - $this->bound = 0; - - $port = ($this->cnf['port']) ? $this->cnf['port'] : 389; - $bound = false; - $servers = explode(',', $this->cnf['server']); - foreach ($servers as $server) { - $server = trim($server); - $this->con = @ldap_connect($server, $port); - if (!$this->con) { - continue; - } - - /* - * When OpenLDAP 2.x.x is used, ldap_connect() will always return a resource as it does - * not actually connect but just initializes the connecting parameters. The actual - * connect happens with the next calls to ldap_* funcs, usually with ldap_bind(). - * - * So we should try to bind to server in order to check its availability. - */ - - //set protocol version and dependend options - if($this->cnf['version']){ - if(!@ldap_set_option($this->con, LDAP_OPT_PROTOCOL_VERSION, - $this->cnf['version'])){ - msg('Setting LDAP Protocol version '.$this->cnf['version'].' failed',-1); - if($this->cnf['debug']) - msg('LDAP version set: '.htmlspecialchars(ldap_error($this->con)),0,__LINE__,__FILE__); - }else{ - //use TLS (needs version 3) - if($this->cnf['starttls']) { - if (!@ldap_start_tls($this->con)){ - msg('Starting TLS failed',-1); - if($this->cnf['debug']) - msg('LDAP TLS set: '.htmlspecialchars(ldap_error($this->con)),0,__LINE__,__FILE__); - } - } - // needs version 3 - if(isset($this->cnf['referrals'])) { - if(!@ldap_set_option($this->con, LDAP_OPT_REFERRALS, - $this->cnf['referrals'])){ - msg('Setting LDAP referrals to off failed',-1); - if($this->cnf['debug']) - msg('LDAP referal set: '.htmlspecialchars(ldap_error($this->con)),0,__LINE__,__FILE__); - } - } - } - } - - //set deref mode - if($this->cnf['deref']){ - if(!@ldap_set_option($this->con, LDAP_OPT_DEREF, $this->cnf['deref'])){ - msg('Setting LDAP Deref mode '.$this->cnf['deref'].' failed',-1); - if($this->cnf['debug']) - msg('LDAP deref set: '.htmlspecialchars(ldap_error($this->con)),0,__LINE__,__FILE__); - } - } - /* As of PHP 5.3.0 we can set timeout to speedup skipping of invalid servers */ - if (defined('LDAP_OPT_NETWORK_TIMEOUT')) { - ldap_set_option($this->con, LDAP_OPT_NETWORK_TIMEOUT, 1); - } - $bound = @ldap_bind($this->con); - if ($bound) { - break; - } - } - - if(!$bound) { - msg("LDAP: couldn't connect to LDAP server",-1); - return false; - } - - - $this->canDo['getUsers'] = true; - return true; - } - - /** - * Wraps around ldap_search, ldap_list or ldap_read depending on $scope - * - * @param $scope string - can be 'base', 'one' or 'sub' - * @author Andreas Gohr <andi@splitbrain.org> - */ - function _ldapsearch($link_identifier, $base_dn, $filter, $scope='sub', $attributes=null, - $attrsonly=0, $sizelimit=0, $timelimit=0, $deref=LDAP_DEREF_NEVER){ - if(is_null($attributes)) $attributes = array(); - - if($scope == 'base'){ - return @ldap_read($link_identifier, $base_dn, $filter, $attributes, - $attrsonly, $sizelimit, $timelimit, $deref); - }elseif($scope == 'one'){ - return @ldap_list($link_identifier, $base_dn, $filter, $attributes, - $attrsonly, $sizelimit, $timelimit, $deref); - }else{ - return @ldap_search($link_identifier, $base_dn, $filter, $attributes, - $attrsonly, $sizelimit, $timelimit, $deref); - } - } -} - -//Setup VIM: ex: et ts=4 : diff --git a/inc/auth/pgsql.class.php b/inc/auth/pgsql.class.php deleted file mode 100644 index b422b100d..000000000 --- a/inc/auth/pgsql.class.php +++ /dev/null @@ -1,419 +0,0 @@ -<?php -/** - * PgSQL authentication backend - * - * This class inherits much functionality from the MySQL class - * and just reimplements the Postgres specific parts. - * - * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) - * @author Andreas Gohr <andi@splitbrain.org> - * @author Chris Smith <chris@jalakai.co.uk> - * @author Matthias Grimm <matthias.grimmm@sourceforge.net> - */ - -require_once(DOKU_INC.'inc/auth/mysql.class.php'); - -class auth_pgsql extends auth_mysql { - - /** - * Constructor - * - * checks if the pgsql interface is available, otherwise it will - * set the variable $success of the basis class to false - * - * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> - * @author Andreas Gohr <andi@splitbrain.org> - */ - function __construct() { - global $conf; - $this->cnf = $conf['auth']['pgsql']; - if(!$this->cnf['port']){ - $this->cnf['port'] = 5432; - } - - if (method_exists($this, 'auth_basic')){ - parent::auth_basic(); - } - - if(!function_exists('pg_connect')) { - if ($this->cnf['debug']) - msg("PgSQL err: PHP Postgres extension not found.",-1); - $this->success = false; - return; - } - - $this->defaultgroup = $conf['defaultgroup']; - - // set capabilities based upon config strings set - if (empty($this->cnf['user']) || - empty($this->cnf['password']) || empty($this->cnf['database'])){ - if ($this->cnf['debug']){ - msg("PgSQL err: insufficient configuration.",-1,__LINE__,__FILE__); - } - $this->success = false; - return; - } - - $this->cando['addUser'] = $this->_chkcnf(array( - 'getUserInfo', - 'getGroups', - 'addUser', - 'getUserID', - 'getGroupID', - 'addGroup', - 'addUserGroup')); - $this->cando['delUser'] = $this->_chkcnf(array( - 'getUserID', - 'delUser', - 'delUserRefs')); - $this->cando['modLogin'] = $this->_chkcnf(array( - 'getUserID', - 'updateUser', - 'UpdateTarget')); - $this->cando['modPass'] = $this->cando['modLogin']; - $this->cando['modName'] = $this->cando['modLogin']; - $this->cando['modMail'] = $this->cando['modLogin']; - $this->cando['modGroups'] = $this->_chkcnf(array( - 'getUserID', - 'getGroups', - 'getGroupID', - 'addGroup', - 'addUserGroup', - 'delGroup', - 'getGroupID', - 'delUserGroup')); - /* getGroups is not yet supported - $this->cando['getGroups'] = $this->_chkcnf(array('getGroups', - 'getGroupID')); */ - $this->cando['getUsers'] = $this->_chkcnf(array( - 'getUsers', - 'getUserInfo', - 'getGroups')); - $this->cando['getUserCount'] = $this->_chkcnf(array('getUsers')); - } - - /** - * Check if the given config strings are set - * - * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> - * @return bool - */ - function _chkcnf($keys, $wop=false){ - foreach ($keys as $key){ - if (empty($this->cnf[$key])) return false; - } - return true; - } - - // @inherit function checkPass($user,$pass) - // @inherit function getUserData($user) - // @inherit function createUser($user,$pwd,$name,$mail,$grps=null) - // @inherit function modifyUser($user, $changes) - // @inherit function deleteUsers($users) - - - /** - * [public function] - * - * Counts users which meet certain $filter criteria. - * - * @param array $filter filter criteria in item/pattern pairs - * @return count of found users. - * - * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> - */ - function getUserCount($filter=array()) { - $rc = 0; - - if($this->_openDB()) { - $sql = $this->_createSQLFilter($this->cnf['getUsers'], $filter); - - // no equivalent of SQL_CALC_FOUND_ROWS in pgsql? - if (($result = $this->_queryDB($sql))){ - $rc = count($result); - } - $this->_closeDB(); - } - return $rc; - } - - /** - * Bulk retrieval of user data. [public function] - * - * @param first index of first user to be returned - * @param limit max number of users to be returned - * @param filter array of field/pattern pairs - * @return array of userinfo (refer getUserData for internal userinfo details) - * - * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> - */ - function retrieveUsers($first=0,$limit=10,$filter=array()) { - $out = array(); - - if($this->_openDB()) { - $this->_lockTables("READ"); - $sql = $this->_createSQLFilter($this->cnf['getUsers'], $filter); - $sql .= " ".$this->cnf['SortOrder']." LIMIT $limit OFFSET $first"; - $result = $this->_queryDB($sql); - - foreach ($result as $user) - if (($info = $this->_getUserInfo($user['user']))) - $out[$user['user']] = $info; - - $this->_unlockTables(); - $this->_closeDB(); - } - return $out; - } - - // @inherit function joinGroup($user, $group) - // @inherit function leaveGroup($user, $group) { - - /** - * Adds a user to a group. - * - * If $force is set to '1' non existing groups would be created. - * - * The database connection must already be established. Otherwise - * this function does nothing and returns 'false'. - * - * @param $user user to add to a group - * @param $group name of the group - * @param $force '1' create missing groups - * @return bool 'true' on success, 'false' on error - * - * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> - * @author Andreas Gohr <andi@splitbrain.org> - */ - function _addUserToGroup($user, $group, $force=0) { - $newgroup = 0; - - if (($this->dbcon) && ($user)) { - $gid = $this->_getGroupID($group); - if (!$gid) { - if ($force) { // create missing groups - $sql = str_replace('%{group}',addslashes($group),$this->cnf['addGroup']); - $this->_modifyDB($sql); - //group should now exists try again to fetch it - $gid = $this->_getGroupID($group); - $newgroup = 1; // group newly created - } - } - if (!$gid) return false; // group didn't exist and can't be created - - $sql = $this->cnf['addUserGroup']; - if(strpos($sql,'%{uid}') !== false){ - $uid = $this->_getUserID($user); - $sql = str_replace('%{uid}', addslashes($uid), $sql); - } - $sql = str_replace('%{user}', addslashes($user),$sql); - $sql = str_replace('%{gid}', addslashes($gid),$sql); - $sql = str_replace('%{group}',addslashes($group),$sql); - if ($this->_modifyDB($sql) !== false) return true; - - if ($newgroup) { // remove previously created group on error - $sql = str_replace('%{gid}', addslashes($gid),$this->cnf['delGroup']); - $sql = str_replace('%{group}',addslashes($group),$sql); - $this->_modifyDB($sql); - } - } - return false; - } - - // @inherit function _delUserFromGroup($user $group) - // @inherit function _getGroups($user) - // @inherit function _getUserID($user) - - /** - * Adds a new User to the database. - * - * The database connection must already be established - * for this function to work. Otherwise it will return - * 'false'. - * - * @param $user login of the user - * @param $pwd encrypted password - * @param $name full name of the user - * @param $mail email address - * @param $grps array of groups the user should become member of - * @return bool - * - * @author Andreas Gohr <andi@splitbrain.org> - * @author Chris Smith <chris@jalakai.co.uk> - * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> - */ - function _addUser($user,$pwd,$name,$mail,$grps){ - if($this->dbcon && is_array($grps)) { - $sql = str_replace('%{user}', addslashes($user),$this->cnf['addUser']); - $sql = str_replace('%{pass}', addslashes($pwd),$sql); - $sql = str_replace('%{name}', addslashes($name),$sql); - $sql = str_replace('%{email}',addslashes($mail),$sql); - if($this->_modifyDB($sql)){ - $uid = $this->_getUserID($user); - }else{ - return false; - } - - if ($uid) { - foreach($grps as $group) { - $gid = $this->_addUserToGroup($user, $group, 1); - if ($gid === false) break; - } - - if ($gid) return true; - else { - /* remove the new user and all group relations if a group can't - * be assigned. Newly created groups will remain in the database - * and won't be removed. This might create orphaned groups but - * is not a big issue so we ignore this problem here. - */ - $this->_delUser($user); - if ($this->cnf['debug']) - msg("PgSQL err: Adding user '$user' to group '$group' failed.",-1,__LINE__,__FILE__); - } - } - } - return false; - } - - // @inherit function _delUser($user) - // @inherit function _getUserInfo($user) - // @inherit function _updateUserInfo($changes, $uid) - // @inherit function _getGroupID($group) - - /** - * Opens a connection to a database and saves the handle for further - * usage in the object. The successful call to this functions is - * essential for most functions in this object. - * - * @return bool - * - * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> - */ - function _openDB() { - if (!$this->dbcon) { - $dsn = $this->cnf['server'] ? 'host='.$this->cnf['server'] : ''; - $dsn .= ' port='.$this->cnf['port']; - $dsn .= ' dbname='.$this->cnf['database']; - $dsn .= ' user='.$this->cnf['user']; - $dsn .= ' password='.$this->cnf['password']; - - $con = @pg_connect($dsn); - if ($con) { - $this->dbcon = $con; - return true; // connection and database successfully opened - } else if ($this->cnf['debug']){ - msg ("PgSQL err: Connection to {$this->cnf['user']}@{$this->cnf['server']} not possible.", - -1,__LINE__,__FILE__); - } - return false; // connection failed - } - return true; // connection already open - } - - /** - * Closes a database connection. - * - * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> - */ - function _closeDB() { - if ($this->dbcon) { - pg_close ($this->dbcon); - $this->dbcon = 0; - } - } - - /** - * Sends a SQL query to the database and transforms the result into - * an associative array. - * - * This function is only able to handle queries that returns a - * table such as SELECT. - * - * @param $query SQL string that contains the query - * @return array with the result table - * - * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> - */ - function _queryDB($query) { - if ($this->dbcon) { - $result = @pg_query($this->dbcon,$query); - if ($result) { - while (($t = pg_fetch_assoc($result)) !== false) - $resultarray[]=$t; - pg_free_result ($result); - return $resultarray; - }elseif ($this->cnf['debug']) - msg('PgSQL err: '.pg_last_error($this->dbcon),-1,__LINE__,__FILE__); - } - return false; - } - - /** - * Executes an update or insert query. This differs from the - * MySQL one because it does NOT return the last insertID - * - * @author Andreas Gohr - */ - function _modifyDB($query) { - if ($this->dbcon) { - $result = @pg_query($this->dbcon,$query); - if ($result) { - pg_free_result ($result); - return true; - } - if ($this->cnf['debug']){ - msg('PgSQL err: '.pg_last_error($this->dbcon),-1,__LINE__,__FILE__); - } - } - return false; - } - - /** - * Start a transaction - * - * @param $mode could be 'READ' or 'WRITE' - * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> - */ - function _lockTables($mode) { - if ($this->dbcon) { - $this->_modifyDB('BEGIN'); - return true; - } - return false; - } - - /** - * Commit a transaction - * - * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> - */ - function _unlockTables() { - if ($this->dbcon) { - $this->_modifyDB('COMMIT'); - return true; - } - return false; - } - - // @inherit function _createSQLFilter($sql, $filter) - - - /** - * Escape a string for insertion into the database - * - * @author Andreas Gohr <andi@splitbrain.org> - * @param string $string The string to escape - * @param boolean $like Escape wildcard chars as well? - */ - function _escape($string,$like=false){ - $string = pg_escape_string($string); - if($like){ - $string = addcslashes($string,'%_'); - } - return $string; - } - -} - -//Setup VIM: ex: et ts=2 : diff --git a/inc/auth/plain.class.php b/inc/auth/plain.class.php deleted file mode 100644 index e682d2522..000000000 --- a/inc/auth/plain.class.php +++ /dev/null @@ -1,328 +0,0 @@ -<?php -/** - * Plaintext authentication backend - * - * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) - * @author Andreas Gohr <andi@splitbrain.org> - * @author Chris Smith <chris@jalakai.co.uk> - */ - -class auth_plain extends auth_basic { - - var $users = null; - var $_pattern = array(); - - /** - * Constructor - * - * Carry out sanity checks to ensure the object is - * able to operate. Set capabilities. - * - * @author Christopher Smith <chris@jalakai.co.uk> - */ - function __construct() { - global $config_cascade; - - if (!@is_readable($config_cascade['plainauth.users']['default'])){ - $this->success = false; - }else{ - if(@is_writable($config_cascade['plainauth.users']['default'])){ - $this->cando['addUser'] = true; - $this->cando['delUser'] = true; - $this->cando['modLogin'] = true; - $this->cando['modPass'] = true; - $this->cando['modName'] = true; - $this->cando['modMail'] = true; - $this->cando['modGroups'] = true; - } - $this->cando['getUsers'] = true; - $this->cando['getUserCount'] = true; - } - } - - /** - * Check user+password [required auth function] - * - * Checks if the given user exists and the given - * plaintext password is correct - * - * @author Andreas Gohr <andi@splitbrain.org> - * @return bool - */ - function checkPass($user,$pass){ - - $userinfo = $this->getUserData($user); - if ($userinfo === false) return false; - - return auth_verifyPassword($pass,$this->users[$user]['pass']); - } - - /** - * Return user info - * - * Returns info about the given user needs to contain - * at least these fields: - * - * name string full name of the user - * mail string email addres of the user - * grps array list of groups the user is in - * - * @author Andreas Gohr <andi@splitbrain.org> - */ - function getUserData($user){ - - if($this->users === null) $this->_loadUserData(); - return isset($this->users[$user]) ? $this->users[$user] : false; - } - - /** - * Create a new User - * - * Returns false if the user already exists, null when an error - * occurred and true if everything went well. - * - * The new user will be added to the default group by this - * function if grps are not specified (default behaviour). - * - * @author Andreas Gohr <andi@splitbrain.org> - * @author Chris Smith <chris@jalakai.co.uk> - */ - function createUser($user,$pwd,$name,$mail,$grps=null){ - global $conf; - global $config_cascade; - - // user mustn't already exist - if ($this->getUserData($user) !== false) return false; - - $pass = auth_cryptPassword($pwd); - - // set default group if no groups specified - if (!is_array($grps)) $grps = array($conf['defaultgroup']); - - // prepare user line - $groups = join(',',$grps); - $userline = join(':',array($user,$pass,$name,$mail,$groups))."\n"; - - if (io_saveFile($config_cascade['plainauth.users']['default'],$userline,true)) { - $this->users[$user] = compact('pass','name','mail','grps'); - return $pwd; - } - - msg('The '.$config_cascade['plainauth.users']['default']. - ' file is not writable. Please inform the Wiki-Admin',-1); - return null; - } - - /** - * Modify user data - * - * @author Chris Smith <chris@jalakai.co.uk> - * @param $user nick of the user to be changed - * @param $changes array of field/value pairs to be changed (password will be clear text) - * @return bool - */ - function modifyUser($user, $changes) { - global $conf; - global $ACT; - global $INFO; - global $config_cascade; - - // sanity checks, user must already exist and there must be something to change - if (($userinfo = $this->getUserData($user)) === false) return false; - if (!is_array($changes) || !count($changes)) return true; - - // update userinfo with new data, remembering to encrypt any password - $newuser = $user; - foreach ($changes as $field => $value) { - if ($field == 'user') { - $newuser = $value; - continue; - } - if ($field == 'pass') $value = auth_cryptPassword($value); - $userinfo[$field] = $value; - } - - $groups = join(',',$userinfo['grps']); - $userline = join(':',array($newuser, $userinfo['pass'], $userinfo['name'], $userinfo['mail'], $groups))."\n"; - - if (!$this->deleteUsers(array($user))) { - msg('Unable to modify user data. Please inform the Wiki-Admin',-1); - return false; - } - - if (!io_saveFile($config_cascade['plainauth.users']['default'],$userline,true)) { - msg('There was an error modifying your user data. You should register again.',-1); - // FIXME, user has been deleted but not recreated, should force a logout and redirect to login page - $ACT == 'register'; - return false; - } - - $this->users[$newuser] = $userinfo; - return true; - } - - /** - * Remove one or more users from the list of registered users - * - * @author Christopher Smith <chris@jalakai.co.uk> - * @param array $users array of users to be deleted - * @return int the number of users deleted - */ - function deleteUsers($users) { - global $config_cascade; - - if (!is_array($users) || empty($users)) return 0; - - if ($this->users === null) $this->_loadUserData(); - - $deleted = array(); - foreach ($users as $user) { - if (isset($this->users[$user])) $deleted[] = preg_quote($user,'/'); - } - - if (empty($deleted)) return 0; - - $pattern = '/^('.join('|',$deleted).'):/'; - - if (io_deleteFromFile($config_cascade['plainauth.users']['default'],$pattern,true)) { - foreach ($deleted as $user) unset($this->users[$user]); - return count($deleted); - } - - // problem deleting, reload the user list and count the difference - $count = count($this->users); - $this->_loadUserData(); - $count -= count($this->users); - return $count; - } - - /** - * Return a count of the number of user which meet $filter criteria - * - * @author Chris Smith <chris@jalakai.co.uk> - */ - function getUserCount($filter=array()) { - - if($this->users === null) $this->_loadUserData(); - - if (!count($filter)) return count($this->users); - - $count = 0; - $this->_constructPattern($filter); - - foreach ($this->users as $user => $info) { - $count += $this->_filter($user, $info); - } - - return $count; - } - - /** - * Bulk retrieval of user data - * - * @author Chris Smith <chris@jalakai.co.uk> - * @param start index of first user to be returned - * @param limit max number of users to be returned - * @param filter array of field/pattern pairs - * @return array of userinfo (refer getUserData for internal userinfo details) - */ - function retrieveUsers($start=0,$limit=0,$filter=array()) { - - if ($this->users === null) $this->_loadUserData(); - - ksort($this->users); - - $i = 0; - $count = 0; - $out = array(); - $this->_constructPattern($filter); - - foreach ($this->users as $user => $info) { - if ($this->_filter($user, $info)) { - if ($i >= $start) { - $out[$user] = $info; - $count++; - if (($limit > 0) && ($count >= $limit)) break; - } - $i++; - } - } - - return $out; - } - - /** - * Only valid pageid's (no namespaces) for usernames - */ - function cleanUser($user){ - global $conf; - return cleanID(str_replace(':',$conf['sepchar'],$user)); - } - - /** - * Only valid pageid's (no namespaces) for groupnames - */ - function cleanGroup($group){ - global $conf; - return cleanID(str_replace(':',$conf['sepchar'],$group)); - } - - /** - * Load all user data - * - * loads the user file into a datastructure - * - * @author Andreas Gohr <andi@splitbrain.org> - */ - function _loadUserData(){ - global $config_cascade; - - $this->users = array(); - - if(!@file_exists($config_cascade['plainauth.users']['default'])) return; - - $lines = file($config_cascade['plainauth.users']['default']); - foreach($lines as $line){ - $line = preg_replace('/#.*$/','',$line); //ignore comments - $line = trim($line); - if(empty($line)) continue; - - $row = explode(":",$line,5); - $groups = array_values(array_filter(explode(",",$row[4]))); - - $this->users[$row[0]]['pass'] = $row[1]; - $this->users[$row[0]]['name'] = urldecode($row[2]); - $this->users[$row[0]]['mail'] = $row[3]; - $this->users[$row[0]]['grps'] = $groups; - } - } - - /** - * return 1 if $user + $info match $filter criteria, 0 otherwise - * - * @author Chris Smith <chris@jalakai.co.uk> - */ - function _filter($user, $info) { - // FIXME - foreach ($this->_pattern as $item => $pattern) { - if ($item == 'user') { - if (!preg_match($pattern, $user)) return 0; - } else if ($item == 'grps') { - if (!count(preg_grep($pattern, $info['grps']))) return 0; - } else { - if (!preg_match($pattern, $info[$item])) return 0; - } - } - return 1; - } - - function _constructPattern($filter) { - $this->_pattern = array(); - foreach ($filter as $item => $pattern) { - // $this->_pattern[$item] = '/'.preg_quote($pattern,"/").'/i'; // don't allow regex characters - $this->_pattern[$item] = '/'.str_replace('/','\/',$pattern).'/i'; // allow regex characters - } - } -} - -//Setup VIM: ex: et ts=2 : diff --git a/inc/init.php b/inc/init.php index 9568d9b93..30eb1b251 100644 --- a/inc/init.php +++ b/inc/init.php @@ -196,7 +196,7 @@ init_paths(); init_files(); // setup plugin controller class (can be overwritten in preload.php) -$plugin_types = array('admin','syntax','action','renderer', 'helper','remote'); +$plugin_types = array('auth', 'admin','syntax','action','renderer', 'helper','remote'); global $plugin_controller_class, $plugin_controller; if (empty($plugin_controller_class)) $plugin_controller_class = 'Doku_Plugin_Controller'; diff --git a/inc/load.php b/inc/load.php index b8a279523..008613b2a 100644 --- a/inc/load.php +++ b/inc/load.php @@ -51,7 +51,6 @@ function load_autoload($name){ 'DokuHTTPClient' => DOKU_INC.'inc/HTTPClient.php', 'HTTPClient' => DOKU_INC.'inc/HTTPClient.php', 'JSON' => DOKU_INC.'inc/JSON.php', - 'adLDAP' => DOKU_INC.'inc/adLDAP.php', 'Diff' => DOKU_INC.'inc/DifferenceEngine.php', 'UnifiedDiffFormatter' => DOKU_INC.'inc/DifferenceEngine.php', 'TableDiffFormatter' => DOKU_INC.'inc/DifferenceEngine.php', @@ -86,6 +85,7 @@ function load_autoload($name){ 'DokuWiki_Admin_Plugin' => DOKU_PLUGIN.'admin.php', 'DokuWiki_Syntax_Plugin' => DOKU_PLUGIN.'syntax.php', 'DokuWiki_Remote_Plugin' => DOKU_PLUGIN.'remote.php', + 'DokuWiki_Auth_Plugin' => DOKU_PLUGIN.'auth.php', ); @@ -95,7 +95,7 @@ function load_autoload($name){ } // Plugin loading - if(preg_match('/^(helper|syntax|action|admin|renderer|remote)_plugin_('.DOKU_PLUGIN_NAME_REGEX.')(?:_([^_]+))?$/', + if(preg_match('/^(auth|helper|syntax|action|admin|renderer|remote)_plugin_('.DOKU_PLUGIN_NAME_REGEX.')(?:_([^_]+))?$/', $name, $m)) { // try to load the wanted plugin file $c = ((count($m) === 4) ? "/{$m[3]}" : ''); diff --git a/inc/plugin.php b/inc/plugin.php index b0518346d..6ffc1ddcb 100644 --- a/inc/plugin.php +++ b/inc/plugin.php @@ -22,6 +22,7 @@ class DokuWiki_Plugin { * * Needs to return a associative array with the following values: * + * base - the plugin's base name (eg. the directory it needs to be installed in) * author - Author of the plugin * email - Email address to contact the author * date - Last modified date of the plugin in YYYY-MM-DD format @@ -133,12 +134,20 @@ class DokuWiki_Plugin { * getConf($setting) * * use this function to access plugin configuration variables + * + * @param string $setting the setting to access + * @param mixed $notset what to return if the setting is not available + * @return mixed */ - function getConf($setting){ + function getConf($setting, $notset=false){ if (!$this->configloaded){ $this->loadConfig(); } - return $this->conf[$setting]; + if(isset($this->conf[$setting])){ + return $this->conf[$setting]; + }else{ + return $notset; + } } /** diff --git a/inc/auth/basic.class.php b/lib/plugins/auth.php index 7c0a5f2c9..42dbf1859 100644 --- a/inc/auth/basic.class.php +++ b/lib/plugins/auth.php @@ -1,22 +1,26 @@ <?php +// must be run within Dokuwiki +if(!defined('DOKU_INC')) die(); + /** - * auth/basic.class.php + * Auth Plugin Prototype * * foundation authorisation class * all auth classes should inherit from this class * + * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) * @author Chris Smith <chris@jalakai.co.uk> + * @author Jan Schumann <js@jschumann-it.com> */ - -class auth_basic { - var $success = true; +class DokuWiki_Auth_Plugin extends DokuWiki_Plugin { + public $success = true; /** - * Posible things an auth backend module may be able to + * Possible things an auth backend module may be able to * do. The things a backend can do need to be set to true * in the constructor. */ - var $cando = array ( + protected $cando = array( 'addUser' => false, // can Users be created? 'delUser' => false, // can Users be deleted? 'modLogin' => false, // can login names be changed? @@ -28,7 +32,7 @@ class auth_basic { 'getUserCount'=> false, // can the number of users be retrieved? 'getGroups' => false, // can a list of available groups be retrieved? 'external' => false, // does the module do external auth checking? - 'logout' => true, // can the user logout again? (eg. not possible with HTTP auth) + 'logout' => true, // can the user logout again? (eg. not possible with HTTP auth) ); /** @@ -38,11 +42,14 @@ class auth_basic { * able to operate. Set capabilities in $this->cando * array here * + * For future compatibility, sub classes should always include a call + * to parent::__constructor() in their constructors! + * * Set $this->success to false if checks fail * * @author Christopher Smith <chris@jalakai.co.uk> */ - function __construct() { + public function __construct() { // the base class constructor does nothing, derived class // constructors do the real work } @@ -58,29 +65,30 @@ class auth_basic { * shortcut capabilities start with uppercase letter * * @author Andreas Gohr <andi@splitbrain.org> + * @param string $cap the capability to check * @return bool */ - function canDo($cap) { - switch($cap){ + public function canDo($cap) { + switch($cap) { case 'Profile': // can at least one of the user's properties be changed? - return ( $this->cando['modPass'] || - $this->cando['modName'] || - $this->cando['modMail'] ); + return ($this->cando['modPass'] || + $this->cando['modName'] || + $this->cando['modMail']); break; case 'UserMod': // can at least anything be changed? - return ( $this->cando['modPass'] || - $this->cando['modName'] || - $this->cando['modMail'] || - $this->cando['modLogin'] || - $this->cando['modGroups'] || - $this->cando['modMail'] ); + return ($this->cando['modPass'] || + $this->cando['modName'] || + $this->cando['modMail'] || + $this->cando['modLogin'] || + $this->cando['modGroups'] || + $this->cando['modMail']); break; default: // print a helping message for developers - if(!isset($this->cando[$cap])){ - msg("Check for unknown capability '$cap' - Do you use an outdated Plugin?",-1); + if(!isset($this->cando[$cap])) { + msg("Check for unknown capability '$cap' - Do you use an outdated Plugin?", -1); } return $this->cando[$cap]; } @@ -95,10 +103,10 @@ class auth_basic { * * @author Gabriel Birke <birke@d-scribe.de> * @param string $type Modification type ('create', 'modify', 'delete') - * @param array $params Parameters for the createUser, modifyUser or deleteUsers method. The content of this array depends on the modification type + * @param array $params Parameters for the createUser, modifyUser or deleteUsers method. The content of this array depends on the modification type * @return mixed Result from the modification function or false if an event handler has canceled the action */ - function triggerUserMod($type, $params) { + public function triggerUserMod($type, $params) { $validTypes = array( 'create' => 'createUser', 'modify' => 'modifyUser', @@ -107,9 +115,9 @@ class auth_basic { if(empty($validTypes[$type])) return false; $eventdata = array('type' => $type, 'params' => $params, 'modification_result' => null); - $evt = new Doku_Event('AUTH_USER_CHANGE', $eventdata); - if ($evt->advise_before(true)) { - $result = call_user_func_array(array($this, $validTypes[$type]), $params); + $evt = new Doku_Event('AUTH_USER_CHANGE', $eventdata); + if($evt->advise_before(true)) { + $result = call_user_func_array(array($this, $validTypes[$type]), $params); $evt->data['modification_result'] = $result; } $evt->advise_after(); @@ -126,7 +134,7 @@ class auth_basic { * @see auth_logoff() * @author Andreas Gohr <andi@splitbrain.org> */ - function logOff(){ + public function logOff() { } /** @@ -162,7 +170,7 @@ class auth_basic { * @param bool $sticky Cookie should not expire * @return bool true on successful auth */ - function trustExternal($user,$pass,$sticky=false){ + public function trustExternal($user, $pass, $sticky = false) { /* some example: global $USERINFO; @@ -193,9 +201,11 @@ class auth_basic { * May be ommited if trustExternal is used. * * @author Andreas Gohr <andi@splitbrain.org> + * @param string $user the user name + * @param string $pass the clear text password * @return bool */ - function checkPass($user,$pass){ + public function checkPass($user, $pass) { msg("no valid authorisation system in use", -1); return false; } @@ -211,9 +221,10 @@ class auth_basic { * grps array list of groups the user is in * * @author Andreas Gohr <andi@splitbrain.org> + * @param string $user the user name * @return array containing user data or false */ - function getUserData($user) { + public function getUserData($user) { if(!$this->cando['external']) msg("no valid authorisation system in use", -1); return false; } @@ -230,8 +241,14 @@ class auth_basic { * Set addUser capability when implemented * * @author Andreas Gohr <andi@splitbrain.org> + * @param string $user + * @param string $pass + * @param string $name + * @param string $mail + * @param null|array $grps + * @return bool|null */ - function createUser($user,$pass,$name,$mail,$grps=null){ + public function createUser($user, $pass, $name, $mail, $grps = null) { msg("authorisation method does not allow creation of new users", -1); return null; } @@ -242,11 +259,11 @@ class auth_basic { * Set the mod* capabilities according to the implemented features * * @author Chris Smith <chris@jalakai.co.uk> - * @param $user nick of the user to be changed - * @param $changes array of field/value pairs to be changed (password will be clear text) + * @param string $user nick of the user to be changed + * @param array $changes array of field/value pairs to be changed (password will be clear text) * @return bool */ - function modifyUser($user, $changes) { + public function modifyUser($user, $changes) { msg("authorisation method does not allow modifying of user data", -1); return false; } @@ -260,7 +277,7 @@ class auth_basic { * @param array $users * @return int number of users deleted */ - function deleteUsers($users) { + public function deleteUsers($users) { msg("authorisation method does not allow deleting of users", -1); return false; } @@ -271,9 +288,11 @@ class auth_basic { * * Set getUserCount capability when implemented * - * @author Chris Smith <chris@jalakai.co.uk> + * @author Chris Smith <chris@jalakai.co.uk> + * @param array $filter array of field/pattern pairs, empty array for no filter + * @return int */ - function getUserCount($filter=array()) { + public function getUserCount($filter = array()) { msg("authorisation method does not provide user counts", -1); return 0; } @@ -284,12 +303,12 @@ class auth_basic { * Set getUsers capability when implemented * * @author Chris Smith <chris@jalakai.co.uk> - * @param start index of first user to be returned - * @param limit max number of users to be returned - * @param filter array of field/pattern pairs, null for no filter - * @return array of userinfo (refer getUserData for internal userinfo details) + * @param int $start index of first user to be returned + * @param int $limit max number of users to be returned + * @param array $filter array of field/pattern pairs, null for no filter + * @return array list of userinfo (refer getUserData for internal userinfo details) */ - function retrieveUsers($start=0,$limit=-1,$filter=null) { + public function retrieveUsers($start = 0, $limit = -1, $filter = null) { msg("authorisation method does not support mass retrieval of user data", -1); return array(); } @@ -300,9 +319,10 @@ class auth_basic { * Set addGroup capability when implemented * * @author Chris Smith <chris@jalakai.co.uk> + * @param string $group * @return bool */ - function addGroup($group) { + public function addGroup($group) { msg("authorisation method does not support independent group creation", -1); return false; } @@ -313,9 +333,11 @@ class auth_basic { * Set getGroups capability when implemented * * @author Chris Smith <chris@jalakai.co.uk> + * @param int $start + * @param int $limit * @return array */ - function retrieveGroups($start=0,$limit=0) { + public function retrieveGroups($start = 0, $limit = 0) { msg("authorisation method does not support group list retrieval", -1); return array(); } @@ -325,8 +347,10 @@ class auth_basic { * * When your backend is caseinsensitive (eg. you can login with USER and * user) then you need to overwrite this method and return false + * + * @return bool */ - function isCaseSensitive(){ + public function isCaseSensitive() { return true; } @@ -340,10 +364,10 @@ class auth_basic { * This should be used to enforce username restrictions. * * @author Andreas Gohr <andi@splitbrain.org> - * @param string $user - username - * @param string - the cleaned username + * @param string $user username + * @return string the cleaned username */ - function cleanUser($user){ + public function cleanUser($user) { return $user; } @@ -359,14 +383,13 @@ class auth_basic { * Groupnames are to be passed without a leading '@' here. * * @author Andreas Gohr <andi@splitbrain.org> - * @param string $group - groupname - * @param string - the cleaned groupname + * @param string $group groupname + * @return string the cleaned groupname */ - function cleanGroup($group){ + public function cleanGroup($group) { return $group; } - /** * Check Session Cache validity [implement only where required/possible] * @@ -392,10 +415,25 @@ class auth_basic { * @author Andreas Gohr <andi@splitbrain.org> * @return bool */ - function useSessionCache($user){ + public function useSessionCache($user) { global $conf; return ($_SESSION[DOKU_COOKIE]['auth']['time'] >= @filemtime($conf['cachedir'].'/sessionpurge')); } + /** + * Overrides the standard config loading to integrate old auth module style configs + * + * @deprecated 2012-11-09 + */ + public function loadConfig(){ + global $conf; + $plugin = $this->getPluginName(); + + $default = $this->readDefaultSettings(); + $oldconf = array(); + if(isset($conf['auth'][$plugin])) $oldconf = (array) $conf['auth'][$plugin]; + + $conf['plugin'][$plugin] = array_merge($default, $oldconf, $conf['plugin'][$plugin]); + $this->configloaded = true; + } } -//Setup VIM: ex: et ts=2 : diff --git a/lib/plugins/authad/adLDAP/adLDAP.php b/lib/plugins/authad/adLDAP/adLDAP.php new file mode 100644 index 000000000..a8f33b47e --- /dev/null +++ b/lib/plugins/authad/adLDAP/adLDAP.php @@ -0,0 +1,951 @@ +<?php
+/**
+ * PHP LDAP CLASS FOR MANIPULATING ACTIVE DIRECTORY
+ * Version 4.0.4
+ *
+ * PHP Version 5 with SSL and LDAP support
+ *
+ * Written by Scott Barnett, Richard Hyland
+ * email: scott@wiggumworld.com, adldap@richardhyland.com
+ * http://adldap.sourceforge.net/
+ *
+ * Copyright (c) 2006-2012 Scott Barnett, Richard Hyland
+ *
+ * We'd appreciate any improvements or additions to be submitted back
+ * to benefit the entire community :)
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * @category ToolsAndUtilities
+ * @package adLDAP
+ * @author Scott Barnett, Richard Hyland
+ * @copyright (c) 2006-2012 Scott Barnett, Richard Hyland
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html LGPLv2.1
+ * @revision $Revision: 169 $
+ * @version 4.0.4
+ * @link http://adldap.sourceforge.net/
+ */
+
+/**
+* Main adLDAP class
+*
+* Can be initialised using $adldap = new adLDAP();
+*
+* Something to keep in mind is that Active Directory is a permissions
+* based directory. If you bind as a domain user, you can't fetch as
+* much information on other users as you could as a domain admin.
+*
+* Before asking questions, please read the Documentation at
+* http://adldap.sourceforge.net/wiki/doku.php?id=api
+*/
+require_once(dirname(__FILE__) . '/collections/adLDAPCollection.php');
+require_once(dirname(__FILE__) . '/classes/adLDAPGroups.php');
+require_once(dirname(__FILE__) . '/classes/adLDAPUsers.php');
+require_once(dirname(__FILE__) . '/classes/adLDAPFolders.php');
+require_once(dirname(__FILE__) . '/classes/adLDAPUtils.php');
+require_once(dirname(__FILE__) . '/classes/adLDAPContacts.php');
+require_once(dirname(__FILE__) . '/classes/adLDAPExchange.php');
+require_once(dirname(__FILE__) . '/classes/adLDAPComputers.php');
+
+class adLDAP {
+
+ /**
+ * Define the different types of account in AD
+ */
+ const ADLDAP_NORMAL_ACCOUNT = 805306368;
+ const ADLDAP_WORKSTATION_TRUST = 805306369;
+ const ADLDAP_INTERDOMAIN_TRUST = 805306370;
+ const ADLDAP_SECURITY_GLOBAL_GROUP = 268435456;
+ const ADLDAP_DISTRIBUTION_GROUP = 268435457;
+ const ADLDAP_SECURITY_LOCAL_GROUP = 536870912;
+ const ADLDAP_DISTRIBUTION_LOCAL_GROUP = 536870913;
+ const ADLDAP_FOLDER = 'OU';
+ const ADLDAP_CONTAINER = 'CN';
+
+ /**
+ * The default port for LDAP non-SSL connections
+ */
+ const ADLDAP_LDAP_PORT = '389';
+ /**
+ * The default port for LDAPS SSL connections
+ */
+ const ADLDAP_LDAPS_PORT = '636';
+
+ /**
+ * The account suffix for your domain, can be set when the class is invoked
+ *
+ * @var string
+ */
+ protected $accountSuffix = "@mydomain.local";
+
+ /**
+ * The base dn for your domain
+ *
+ * If this is set to null then adLDAP will attempt to obtain this automatically from the rootDSE
+ *
+ * @var string
+ */
+ protected $baseDn = "DC=mydomain,DC=local";
+
+ /**
+ * Port used to talk to the domain controllers.
+ *
+ * @var int
+ */
+ protected $adPort = self::ADLDAP_LDAP_PORT;
+
+ /**
+ * Array of domain controllers. Specifiy multiple controllers if you
+ * would like the class to balance the LDAP queries amongst multiple servers
+ *
+ * @var array
+ */
+ protected $domainControllers = array("dc01.mydomain.local");
+
+ /**
+ * Optional account with higher privileges for searching
+ * This should be set to a domain admin account
+ *
+ * @var string
+ * @var string
+ */
+ protected $adminUsername = NULL;
+ protected $adminPassword = NULL;
+
+ /**
+ * AD does not return the primary group. http://support.microsoft.com/?kbid=321360
+ * This tweak will resolve the real primary group.
+ * Setting to false will fudge "Domain Users" and is much faster. Keep in mind though that if
+ * someone's primary group is NOT domain users, this is obviously going to mess up the results
+ *
+ * @var bool
+ */
+ protected $realPrimaryGroup = true;
+
+ /**
+ * Use SSL (LDAPS), your server needs to be setup, please see
+ * http://adldap.sourceforge.net/wiki/doku.php?id=ldap_over_ssl
+ *
+ * @var bool
+ */
+ protected $useSSL = false;
+
+ /**
+ * Use TLS
+ * If you wish to use TLS you should ensure that $useSSL is set to false and vice-versa
+ *
+ * @var bool
+ */
+ protected $useTLS = false;
+
+ /**
+ * Use SSO
+ * To indicate to adLDAP to reuse password set by the brower through NTLM or Kerberos
+ *
+ * @var bool
+ */
+ protected $useSSO = false;
+
+ /**
+ * When querying group memberships, do it recursively
+ * eg. User Fred is a member of Group A, which is a member of Group B, which is a member of Group C
+ * user_ingroup("Fred","C") will returns true with this option turned on, false if turned off
+ *
+ * @var bool
+ */
+ protected $recursiveGroups = true;
+
+ // You should not need to edit anything below this line
+ //******************************************************************************************
+
+ /**
+ * Connection and bind default variables
+ *
+ * @var mixed
+ * @var mixed
+ */
+ protected $ldapConnection;
+ protected $ldapBind;
+
+ /**
+ * Get the active LDAP Connection
+ *
+ * @return resource
+ */
+ public function getLdapConnection() {
+ if ($this->ldapConnection) {
+ return $this->ldapConnection;
+ }
+ return false;
+ }
+
+ /**
+ * Get the bind status
+ *
+ * @return bool
+ */
+ public function getLdapBind() {
+ return $this->ldapBind;
+ }
+
+ /**
+ * Get the current base DN
+ *
+ * @return string
+ */
+ public function getBaseDn() {
+ return $this->baseDn;
+ }
+
+ /**
+ * The group class
+ *
+ * @var adLDAPGroups
+ */
+ protected $groupClass;
+
+ /**
+ * Get the group class interface
+ *
+ * @return adLDAPGroups
+ */
+ public function group() {
+ if (!$this->groupClass) {
+ $this->groupClass = new adLDAPGroups($this);
+ }
+ return $this->groupClass;
+ }
+
+ /**
+ * The user class
+ *
+ * @var adLDAPUsers
+ */
+ protected $userClass;
+
+ /**
+ * Get the userclass interface
+ *
+ * @return adLDAPUsers
+ */
+ public function user() {
+ if (!$this->userClass) {
+ $this->userClass = new adLDAPUsers($this);
+ }
+ return $this->userClass;
+ }
+
+ /**
+ * The folders class
+ *
+ * @var adLDAPFolders
+ */
+ protected $folderClass;
+
+ /**
+ * Get the folder class interface
+ *
+ * @return adLDAPFolders
+ */
+ public function folder() {
+ if (!$this->folderClass) {
+ $this->folderClass = new adLDAPFolders($this);
+ }
+ return $this->folderClass;
+ }
+
+ /**
+ * The utils class
+ *
+ * @var adLDAPUtils
+ */
+ protected $utilClass;
+
+ /**
+ * Get the utils class interface
+ *
+ * @return adLDAPUtils
+ */
+ public function utilities() {
+ if (!$this->utilClass) {
+ $this->utilClass = new adLDAPUtils($this);
+ }
+ return $this->utilClass;
+ }
+
+ /**
+ * The contacts class
+ *
+ * @var adLDAPContacts
+ */
+ protected $contactClass;
+
+ /**
+ * Get the contacts class interface
+ *
+ * @return adLDAPContacts
+ */
+ public function contact() {
+ if (!$this->contactClass) {
+ $this->contactClass = new adLDAPContacts($this);
+ }
+ return $this->contactClass;
+ }
+
+ /**
+ * The exchange class
+ *
+ * @var adLDAPExchange
+ */
+ protected $exchangeClass;
+
+ /**
+ * Get the exchange class interface
+ *
+ * @return adLDAPExchange
+ */
+ public function exchange() {
+ if (!$this->exchangeClass) {
+ $this->exchangeClass = new adLDAPExchange($this);
+ }
+ return $this->exchangeClass;
+ }
+
+ /**
+ * The computers class
+ *
+ * @var adLDAPComputers
+ */
+ protected $computersClass;
+
+ /**
+ * Get the computers class interface
+ *
+ * @return adLDAPComputers
+ */
+ public function computer() {
+ if (!$this->computerClass) {
+ $this->computerClass = new adLDAPComputers($this);
+ }
+ return $this->computerClass;
+ }
+
+ /**
+ * Getters and Setters
+ */
+
+ /**
+ * Set the account suffix
+ *
+ * @param string $accountSuffix
+ * @return void
+ */
+ public function setAccountSuffix($accountSuffix)
+ {
+ $this->accountSuffix = $accountSuffix;
+ }
+
+ /**
+ * Get the account suffix
+ *
+ * @return string
+ */
+ public function getAccountSuffix()
+ {
+ return $this->accountSuffix;
+ }
+
+ /**
+ * Set the domain controllers array
+ *
+ * @param array $domainControllers
+ * @return void
+ */
+ public function setDomainControllers(array $domainControllers)
+ {
+ $this->domainControllers = $domainControllers;
+ }
+
+ /**
+ * Get the list of domain controllers
+ *
+ * @return void
+ */
+ public function getDomainControllers()
+ {
+ return $this->domainControllers;
+ }
+
+ /**
+ * Sets the port number your domain controller communicates over
+ *
+ * @param int $adPort
+ */
+ public function setPort($adPort)
+ {
+ $this->adPort = $adPort;
+ }
+
+ /**
+ * Gets the port number your domain controller communicates over
+ *
+ * @return int
+ */
+ public function getPort()
+ {
+ return $this->adPort;
+ }
+
+ /**
+ * Set the username of an account with higher priviledges
+ *
+ * @param string $adminUsername
+ * @return void
+ */
+ public function setAdminUsername($adminUsername)
+ {
+ $this->adminUsername = $adminUsername;
+ }
+
+ /**
+ * Get the username of the account with higher priviledges
+ *
+ * This will throw an exception for security reasons
+ */
+ public function getAdminUsername()
+ {
+ throw new adLDAPException('For security reasons you cannot access the domain administrator account details');
+ }
+
+ /**
+ * Set the password of an account with higher priviledges
+ *
+ * @param string $adminPassword
+ * @return void
+ */
+ public function setAdminPassword($adminPassword)
+ {
+ $this->adminPassword = $adminPassword;
+ }
+
+ /**
+ * Get the password of the account with higher priviledges
+ *
+ * This will throw an exception for security reasons
+ */
+ public function getAdminPassword()
+ {
+ throw new adLDAPException('For security reasons you cannot access the domain administrator account details');
+ }
+
+ /**
+ * Set whether to detect the true primary group
+ *
+ * @param bool $realPrimaryGroup
+ * @return void
+ */
+ public function setRealPrimaryGroup($realPrimaryGroup)
+ {
+ $this->realPrimaryGroup = $realPrimaryGroup;
+ }
+
+ /**
+ * Get the real primary group setting
+ *
+ * @return bool
+ */
+ public function getRealPrimaryGroup()
+ {
+ return $this->realPrimaryGroup;
+ }
+
+ /**
+ * Set whether to use SSL
+ *
+ * @param bool $useSSL
+ * @return void
+ */
+ public function setUseSSL($useSSL)
+ {
+ $this->useSSL = $useSSL;
+ // Set the default port correctly
+ if($this->useSSL) {
+ $this->setPort(self::ADLDAP_LDAPS_PORT);
+ }
+ else {
+ $this->setPort(self::ADLDAP_LDAP_PORT);
+ }
+ }
+
+ /**
+ * Get the SSL setting
+ *
+ * @return bool
+ */
+ public function getUseSSL()
+ {
+ return $this->useSSL;
+ }
+
+ /**
+ * Set whether to use TLS
+ *
+ * @param bool $useTLS
+ * @return void
+ */
+ public function setUseTLS($useTLS)
+ {
+ $this->useTLS = $useTLS;
+ }
+
+ /**
+ * Get the TLS setting
+ *
+ * @return bool
+ */
+ public function getUseTLS()
+ {
+ return $this->useTLS;
+ }
+
+ /**
+ * Set whether to use SSO
+ * Requires ldap_sasl_bind support. Be sure --with-ldap-sasl is used when configuring PHP otherwise this function will be undefined.
+ *
+ * @param bool $useSSO
+ * @return void
+ */
+ public function setUseSSO($useSSO)
+ {
+ if ($useSSO === true && !$this->ldapSaslSupported()) {
+ throw new adLDAPException('No LDAP SASL support for PHP. See: http://www.php.net/ldap_sasl_bind');
+ }
+ $this->useSSO = $useSSO;
+ }
+
+ /**
+ * Get the SSO setting
+ *
+ * @return bool
+ */
+ public function getUseSSO()
+ {
+ return $this->useSSO;
+ }
+
+ /**
+ * Set whether to lookup recursive groups
+ *
+ * @param bool $recursiveGroups
+ * @return void
+ */
+ public function setRecursiveGroups($recursiveGroups)
+ {
+ $this->recursiveGroups = $recursiveGroups;
+ }
+
+ /**
+ * Get the recursive groups setting
+ *
+ * @return bool
+ */
+ public function getRecursiveGroups()
+ {
+ return $this->recursiveGroups;
+ }
+
+ /**
+ * Default Constructor
+ *
+ * Tries to bind to the AD domain over LDAP or LDAPs
+ *
+ * @param array $options Array of options to pass to the constructor
+ * @throws Exception - if unable to bind to Domain Controller
+ * @return bool
+ */
+ function __construct($options = array()) {
+ // You can specifically overide any of the default configuration options setup above
+ if (count($options) > 0) {
+ if (array_key_exists("account_suffix",$options)){ $this->accountSuffix = $options["account_suffix"]; }
+ if (array_key_exists("base_dn",$options)){ $this->baseDn = $options["base_dn"]; }
+ if (array_key_exists("domain_controllers",$options)){
+ if (!is_array($options["domain_controllers"])) {
+ throw new adLDAPException('[domain_controllers] option must be an array');
+ }
+ $this->domainControllers = $options["domain_controllers"];
+ }
+ if (array_key_exists("admin_username",$options)){ $this->adminUsername = $options["admin_username"]; }
+ if (array_key_exists("admin_password",$options)){ $this->adminPassword = $options["admin_password"]; }
+ if (array_key_exists("real_primarygroup",$options)){ $this->realPrimaryGroup = $options["real_primarygroup"]; }
+ if (array_key_exists("use_ssl",$options)){ $this->setUseSSL($options["use_ssl"]); }
+ if (array_key_exists("use_tls",$options)){ $this->useTLS = $options["use_tls"]; }
+ if (array_key_exists("recursive_groups",$options)){ $this->recursiveGroups = $options["recursive_groups"]; }
+ if (array_key_exists("ad_port",$options)){ $this->setPort($options["ad_port"]); }
+ if (array_key_exists("sso",$options)) {
+ $this->setUseSSO($options["sso"]);
+ if (!$this->ldapSaslSupported()) {
+ $this->setUseSSO(false);
+ }
+ }
+ }
+
+ if ($this->ldapSupported() === false) {
+ throw new adLDAPException('No LDAP support for PHP. See: http://www.php.net/ldap');
+ }
+
+ return $this->connect();
+ }
+
+ /**
+ * Default Destructor
+ *
+ * Closes the LDAP connection
+ *
+ * @return void
+ */
+ function __destruct() {
+ $this->close();
+ }
+
+ /**
+ * Connects and Binds to the Domain Controller
+ *
+ * @return bool
+ */
+ public function connect()
+ {
+ // Connect to the AD/LDAP server as the username/password
+ $domainController = $this->randomController();
+ if ($this->useSSL) {
+ $this->ldapConnection = ldap_connect("ldaps://" . $domainController, $this->adPort);
+ } else {
+ $this->ldapConnection = ldap_connect($domainController, $this->adPort);
+ }
+
+ // Set some ldap options for talking to AD
+ ldap_set_option($this->ldapConnection, LDAP_OPT_PROTOCOL_VERSION, 3);
+ ldap_set_option($this->ldapConnection, LDAP_OPT_REFERRALS, 0);
+
+ if ($this->useTLS) {
+ ldap_start_tls($this->ldapConnection);
+ }
+
+ // Bind as a domain admin if they've set it up
+ if ($this->adminUsername !== NULL && $this->adminPassword !== NULL) {
+ $this->ldapBind = @ldap_bind($this->ldapConnection, $this->adminUsername . $this->accountSuffix, $this->adminPassword);
+ if (!$this->ldapBind) {
+ if ($this->useSSL && !$this->useTLS) {
+ // If you have problems troubleshooting, remove the @ character from the ldapldapBind command above to get the actual error message
+ throw new adLDAPException('Bind to Active Directory failed. Either the LDAPs connection failed or the login credentials are incorrect. AD said: ' . $this->getLastError());
+ }
+ else {
+ throw new adLDAPException('Bind to Active Directory failed. Check the login credentials and/or server details. AD said: ' . $this->getLastError());
+ }
+ }
+ }
+ if ($this->useSSO && $_SERVER['REMOTE_USER'] && $this->adminUsername === null && $_SERVER['KRB5CCNAME']) {
+ putenv("KRB5CCNAME=" . $_SERVER['KRB5CCNAME']);
+ $this->ldapBind = @ldap_sasl_bind($this->ldapConnection, NULL, NULL, "GSSAPI");
+ if (!$this->ldapBind){
+ throw new adLDAPException('Rebind to Active Directory failed. AD said: ' . $this->getLastError());
+ }
+ else {
+ return true;
+ }
+ }
+
+
+ if ($this->baseDn == NULL) {
+ $this->baseDn = $this->findBaseDn();
+ }
+
+ return true;
+ }
+
+ /**
+ * Closes the LDAP connection
+ *
+ * @return void
+ */
+ public function close() {
+ if ($this->ldapConnection) {
+ @ldap_close($this->ldapConnection);
+ }
+ }
+
+ /**
+ * Validate a user's login credentials
+ *
+ * @param string $username A user's AD username
+ * @param string $password A user's AD password
+ * @param bool optional $preventRebind
+ * @return bool
+ */
+ public function authenticate($username, $password, $preventRebind = false) {
+ // Prevent null binding
+ if ($username === NULL || $password === NULL) { return false; }
+ if (empty($username) || empty($password)) { return false; }
+
+ // Allow binding over SSO for Kerberos
+ if ($this->useSSO && $_SERVER['REMOTE_USER'] && $_SERVER['REMOTE_USER'] == $username && $this->adminUsername === NULL && $_SERVER['KRB5CCNAME']) {
+ putenv("KRB5CCNAME=" . $_SERVER['KRB5CCNAME']);
+ $this->ldapBind = @ldap_sasl_bind($this->ldapConnection, NULL, NULL, "GSSAPI");
+ if (!$this->ldapBind) {
+ throw new adLDAPException('Rebind to Active Directory failed. AD said: ' . $this->getLastError());
+ }
+ else {
+ return true;
+ }
+ }
+
+ // Bind as the user
+ $ret = true;
+ $this->ldapBind = @ldap_bind($this->ldapConnection, $username . $this->accountSuffix, $password);
+ if (!$this->ldapBind){
+ $ret = false;
+ }
+
+ // Cnce we've checked their details, kick back into admin mode if we have it
+ if ($this->adminUsername !== NULL && !$preventRebind) {
+ $this->ldapBind = @ldap_bind($this->ldapConnection, $this->adminUsername . $this->accountSuffix , $this->adminPassword);
+ if (!$this->ldapBind){
+ // This should never happen in theory
+ throw new adLDAPException('Rebind to Active Directory failed. AD said: ' . $this->getLastError());
+ }
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Find the Base DN of your domain controller
+ *
+ * @return string
+ */
+ public function findBaseDn()
+ {
+ $namingContext = $this->getRootDse(array('defaultnamingcontext'));
+ return $namingContext[0]['defaultnamingcontext'][0];
+ }
+
+ /**
+ * Get the RootDSE properties from a domain controller
+ *
+ * @param array $attributes The attributes you wish to query e.g. defaultnamingcontext
+ * @return array
+ */
+ public function getRootDse($attributes = array("*", "+")) {
+ if (!$this->ldapBind){ return (false); }
+
+ $sr = @ldap_read($this->ldapConnection, NULL, 'objectClass=*', $attributes);
+ $entries = @ldap_get_entries($this->ldapConnection, $sr);
+ return $entries;
+ }
+
+ /**
+ * Get last error from Active Directory
+ *
+ * This function gets the last message from Active Directory
+ * This may indeed be a 'Success' message but if you get an unknown error
+ * it might be worth calling this function to see what errors were raised
+ *
+ * return string
+ */
+ public function getLastError() {
+ return @ldap_error($this->ldapConnection);
+ }
+
+ /**
+ * Detect LDAP support in php
+ *
+ * @return bool
+ */
+ protected function ldapSupported()
+ {
+ if (!function_exists('ldap_connect')) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Detect ldap_sasl_bind support in PHP
+ *
+ * @return bool
+ */
+ protected function ldapSaslSupported()
+ {
+ if (!function_exists('ldap_sasl_bind')) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Schema
+ *
+ * @param array $attributes Attributes to be queried
+ * @return array
+ */
+ public function adldap_schema($attributes){
+
+ // LDAP doesn't like NULL attributes, only set them if they have values
+ // If you wish to remove an attribute you should set it to a space
+ // TO DO: Adapt user_modify to use ldap_mod_delete to remove a NULL attribute
+ $mod=array();
+
+ // Check every attribute to see if it contains 8bit characters and then UTF8 encode them
+ array_walk($attributes, array($this, 'encode8bit'));
+
+ if ($attributes["address_city"]){ $mod["l"][0]=$attributes["address_city"]; }
+ if ($attributes["address_code"]){ $mod["postalCode"][0]=$attributes["address_code"]; }
+ //if ($attributes["address_country"]){ $mod["countryCode"][0]=$attributes["address_country"]; } // use country codes?
+ if ($attributes["address_country"]){ $mod["c"][0]=$attributes["address_country"]; }
+ if ($attributes["address_pobox"]){ $mod["postOfficeBox"][0]=$attributes["address_pobox"]; }
+ if ($attributes["address_state"]){ $mod["st"][0]=$attributes["address_state"]; }
+ if ($attributes["address_street"]){ $mod["streetAddress"][0]=$attributes["address_street"]; }
+ if ($attributes["company"]){ $mod["company"][0]=$attributes["company"]; }
+ if ($attributes["change_password"]){ $mod["pwdLastSet"][0]=0; }
+ if ($attributes["department"]){ $mod["department"][0]=$attributes["department"]; }
+ if ($attributes["description"]){ $mod["description"][0]=$attributes["description"]; }
+ if ($attributes["display_name"]){ $mod["displayName"][0]=$attributes["display_name"]; }
+ if ($attributes["email"]){ $mod["mail"][0]=$attributes["email"]; }
+ if ($attributes["expires"]){ $mod["accountExpires"][0]=$attributes["expires"]; } //unix epoch format?
+ if ($attributes["firstname"]){ $mod["givenName"][0]=$attributes["firstname"]; }
+ if ($attributes["home_directory"]){ $mod["homeDirectory"][0]=$attributes["home_directory"]; }
+ if ($attributes["home_drive"]){ $mod["homeDrive"][0]=$attributes["home_drive"]; }
+ if ($attributes["initials"]){ $mod["initials"][0]=$attributes["initials"]; }
+ if ($attributes["logon_name"]){ $mod["userPrincipalName"][0]=$attributes["logon_name"]; }
+ if ($attributes["manager"]){ $mod["manager"][0]=$attributes["manager"]; } //UNTESTED ***Use DistinguishedName***
+ if ($attributes["office"]){ $mod["physicalDeliveryOfficeName"][0]=$attributes["office"]; }
+ if ($attributes["password"]){ $mod["unicodePwd"][0]=$this->user()->encodePassword($attributes["password"]); }
+ if ($attributes["profile_path"]){ $mod["profilepath"][0]=$attributes["profile_path"]; }
+ if ($attributes["script_path"]){ $mod["scriptPath"][0]=$attributes["script_path"]; }
+ if ($attributes["surname"]){ $mod["sn"][0]=$attributes["surname"]; }
+ if ($attributes["title"]){ $mod["title"][0]=$attributes["title"]; }
+ if ($attributes["telephone"]){ $mod["telephoneNumber"][0]=$attributes["telephone"]; }
+ if ($attributes["mobile"]){ $mod["mobile"][0]=$attributes["mobile"]; }
+ if ($attributes["pager"]){ $mod["pager"][0]=$attributes["pager"]; }
+ if ($attributes["ipphone"]){ $mod["ipphone"][0]=$attributes["ipphone"]; }
+ if ($attributes["web_page"]){ $mod["wWWHomePage"][0]=$attributes["web_page"]; }
+ if ($attributes["fax"]){ $mod["facsimileTelephoneNumber"][0]=$attributes["fax"]; }
+ if ($attributes["enabled"]){ $mod["userAccountControl"][0]=$attributes["enabled"]; }
+ if ($attributes["homephone"]){ $mod["homephone"][0]=$attributes["homephone"]; }
+
+ // Distribution List specific schema
+ if ($attributes["group_sendpermission"]){ $mod["dlMemSubmitPerms"][0]=$attributes["group_sendpermission"]; }
+ if ($attributes["group_rejectpermission"]){ $mod["dlMemRejectPerms"][0]=$attributes["group_rejectpermission"]; }
+
+ // Exchange Schema
+ if ($attributes["exchange_homemdb"]){ $mod["homeMDB"][0]=$attributes["exchange_homemdb"]; }
+ if ($attributes["exchange_mailnickname"]){ $mod["mailNickname"][0]=$attributes["exchange_mailnickname"]; }
+ if ($attributes["exchange_proxyaddress"]){ $mod["proxyAddresses"][0]=$attributes["exchange_proxyaddress"]; }
+ if ($attributes["exchange_usedefaults"]){ $mod["mDBUseDefaults"][0]=$attributes["exchange_usedefaults"]; }
+ if ($attributes["exchange_policyexclude"]){ $mod["msExchPoliciesExcluded"][0]=$attributes["exchange_policyexclude"]; }
+ if ($attributes["exchange_policyinclude"]){ $mod["msExchPoliciesIncluded"][0]=$attributes["exchange_policyinclude"]; }
+ if ($attributes["exchange_addressbook"]){ $mod["showInAddressBook"][0]=$attributes["exchange_addressbook"]; }
+ if ($attributes["exchange_altrecipient"]){ $mod["altRecipient"][0]=$attributes["exchange_altrecipient"]; }
+ if ($attributes["exchange_deliverandredirect"]){ $mod["deliverAndRedirect"][0]=$attributes["exchange_deliverandredirect"]; }
+
+ // This schema is designed for contacts
+ if ($attributes["exchange_hidefromlists"]){ $mod["msExchHideFromAddressLists"][0]=$attributes["exchange_hidefromlists"]; }
+ if ($attributes["contact_email"]){ $mod["targetAddress"][0]=$attributes["contact_email"]; }
+
+ //echo ("<pre>"); print_r($mod);
+ /*
+ // modifying a name is a bit fiddly
+ if ($attributes["firstname"] && $attributes["surname"]){
+ $mod["cn"][0]=$attributes["firstname"]." ".$attributes["surname"];
+ $mod["displayname"][0]=$attributes["firstname"]." ".$attributes["surname"];
+ $mod["name"][0]=$attributes["firstname"]." ".$attributes["surname"];
+ }
+ */
+
+ if (count($mod)==0){ return (false); }
+ return ($mod);
+ }
+
+ /**
+ * Convert 8bit characters e.g. accented characters to UTF8 encoded characters
+ */
+ protected function encode8Bit(&$item, $key) {
+ $encode = false;
+ if (is_string($item)) {
+ for ($i=0; $i<strlen($item); $i++) {
+ if (ord($item[$i]) >> 7) {
+ $encode = true;
+ }
+ }
+ }
+ if ($encode === true && $key != 'password') {
+ $item = utf8_encode($item);
+ }
+ }
+
+ /**
+ * Select a random domain controller from your domain controller array
+ *
+ * @return string
+ */
+ protected function randomController()
+ {
+ mt_srand(doubleval(microtime()) * 100000000); // For older PHP versions
+ /*if (sizeof($this->domainControllers) > 1) {
+ $adController = $this->domainControllers[array_rand($this->domainControllers)];
+ // Test if the controller is responding to pings
+ $ping = $this->pingController($adController);
+ if ($ping === false) {
+ // Find the current key in the domain controllers array
+ $key = array_search($adController, $this->domainControllers);
+ // Remove it so that we don't end up in a recursive loop
+ unset($this->domainControllers[$key]);
+ // Select a new controller
+ return $this->randomController();
+ }
+ else {
+ return ($adController);
+ }
+ } */
+ return $this->domainControllers[array_rand($this->domainControllers)];
+ }
+
+ /**
+ * Test basic connectivity to controller
+ *
+ * @return bool
+ */
+ protected function pingController($host) {
+ $port = $this->adPort;
+ fsockopen($host, $port, $errno, $errstr, 10);
+ if ($errno > 0) {
+ return false;
+ }
+ return true;
+ }
+
+}
+
+/**
+* adLDAP Exception Handler
+*
+* Exceptions of this type are thrown on bind failure or when SSL is required but not configured
+* Example:
+* try {
+* $adldap = new adLDAP();
+* }
+* catch (adLDAPException $e) {
+* echo $e;
+* exit();
+* }
+*/
+class adLDAPException extends Exception {}
+
+?>
\ No newline at end of file diff --git a/lib/plugins/authad/adLDAP/classes/adLDAPComputers.php b/lib/plugins/authad/adLDAP/classes/adLDAPComputers.php new file mode 100644 index 000000000..71b24a04f --- /dev/null +++ b/lib/plugins/authad/adLDAP/classes/adLDAPComputers.php @@ -0,0 +1,153 @@ +<?php
+/**
+ * PHP LDAP CLASS FOR MANIPULATING ACTIVE DIRECTORY
+ * Version 4.0.4
+ *
+ * PHP Version 5 with SSL and LDAP support
+ *
+ * Written by Scott Barnett, Richard Hyland
+ * email: scott@wiggumworld.com, adldap@richardhyland.com
+ * http://adldap.sourceforge.net/
+ *
+ * Copyright (c) 2006-2012 Scott Barnett, Richard Hyland
+ *
+ * We'd appreciate any improvements or additions to be submitted back
+ * to benefit the entire community :)
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * @category ToolsAndUtilities
+ * @package adLDAP
+ * @subpackage Computers
+ * @author Scott Barnett, Richard Hyland
+ * @copyright (c) 2006-2012 Scott Barnett, Richard Hyland
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html LGPLv2.1
+ * @revision $Revision: 97 $
+ * @version 4.0.4
+ * @link http://adldap.sourceforge.net/
+ */
+require_once(dirname(__FILE__) . '/../adLDAP.php');
+require_once(dirname(__FILE__) . '/../collections/adLDAPComputerCollection.php');
+
+/**
+* COMPUTER MANAGEMENT FUNCTIONS
+*/
+class adLDAPComputers {
+
+ /**
+ * The current adLDAP connection via dependency injection
+ *
+ * @var adLDAP
+ */
+ protected $adldap;
+
+ public function __construct(adLDAP $adldap) {
+ $this->adldap = $adldap;
+ }
+
+ /**
+ * Get information about a specific computer. Returned in a raw array format from AD
+ *
+ * @param string $computerName The name of the computer
+ * @param array $fields Attributes to return
+ * @return array
+ */
+ public function info($computerName, $fields = NULL)
+ {
+ if ($computerName === NULL) { return false; }
+ if (!$this->adldap->getLdapBind()) { return false; }
+
+ $filter = "(&(objectClass=computer)(cn=" . $computerName . "))";
+ if ($fields === NULL) {
+ $fields = array("memberof","cn","displayname","dnshostname","distinguishedname","objectcategory","operatingsystem","operatingsystemservicepack","operatingsystemversion");
+ }
+ $sr = ldap_search($this->adldap->getLdapConnection(), $this->adldap->getBaseDn(), $filter, $fields);
+ $entries = ldap_get_entries($this->adldap->getLdapConnection(), $sr);
+
+ return $entries;
+ }
+
+ /**
+ * Find information about the computers. Returned in a raw array format from AD
+ *
+ * @param string $computerName The name of the computer
+ * @param array $fields Array of parameters to query
+ * @return mixed
+ */
+ public function infoCollection($computerName, $fields = NULL)
+ {
+ if ($computerName === NULL) { return false; }
+ if (!$this->adldap->getLdapBind()) { return false; }
+
+ $info = $this->info($computerName, $fields);
+
+ if ($info !== false) {
+ $collection = new adLDAPComputerCollection($info, $this->adldap);
+ return $collection;
+ }
+ return false;
+ }
+
+ /**
+ * Check if a computer is in a group
+ *
+ * @param string $computerName The name of the computer
+ * @param string $group The group to check
+ * @param bool $recursive Whether to check recursively
+ * @return array
+ */
+ public function inGroup($computerName, $group, $recursive = NULL)
+ {
+ if ($computerName === NULL) { return false; }
+ if ($group === NULL) { return false; }
+ if (!$this->adldap->getLdapBind()) { return false; }
+ if ($recursive === NULL) { $recursive = $this->adldap->getRecursiveGroups(); } // use the default option if they haven't set it
+
+ //get a list of the groups
+ $groups = $this->groups($computerName, array("memberof"), $recursive);
+
+ //return true if the specified group is in the group list
+ if (in_array($group, $groups)){
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Get the groups a computer is in
+ *
+ * @param string $computerName The name of the computer
+ * @param bool $recursive Whether to check recursively
+ * @return array
+ */
+ public function groups($computerName, $recursive = NULL)
+ {
+ if ($computerName === NULL) { return false; }
+ if ($recursive === NULL) { $recursive = $this->adldap->getRecursiveGroups(); } //use the default option if they haven't set it
+ if (!$this->adldap->getLdapBind()){ return false; }
+
+ //search the directory for their information
+ $info = @$this->info($computerName, array("memberof", "primarygroupid"));
+ $groups = $this->adldap->utilities()->niceNames($info[0]["memberof"]); //presuming the entry returned is our guy (unique usernames)
+
+ if ($recursive === true) {
+ foreach ($groups as $id => $groupName){
+ $extraGroups = $this->adldap->group()->recursiveGroups($groupName);
+ $groups = array_merge($groups, $extraGroups);
+ }
+ }
+
+ return $groups;
+ }
+
+}
+?>
\ No newline at end of file diff --git a/lib/plugins/authad/adLDAP/classes/adLDAPContacts.php b/lib/plugins/authad/adLDAP/classes/adLDAPContacts.php new file mode 100644 index 000000000..addd3e5f0 --- /dev/null +++ b/lib/plugins/authad/adLDAP/classes/adLDAPContacts.php @@ -0,0 +1,294 @@ +<?php
+/**
+ * PHP LDAP CLASS FOR MANIPULATING ACTIVE DIRECTORY
+ * Version 4.0.4
+ *
+ * PHP Version 5 with SSL and LDAP support
+ *
+ * Written by Scott Barnett, Richard Hyland
+ * email: scott@wiggumworld.com, adldap@richardhyland.com
+ * http://adldap.sourceforge.net/
+ *
+ * Copyright (c) 2006-2012 Scott Barnett, Richard Hyland
+ *
+ * We'd appreciate any improvements or additions to be submitted back
+ * to benefit the entire community :)
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * @category ToolsAndUtilities
+ * @package adLDAP
+ * @subpackage Contacts
+ * @author Scott Barnett, Richard Hyland
+ * @copyright (c) 2006-2012 Scott Barnett, Richard Hyland
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html LGPLv2.1
+ * @revision $Revision: 97 $
+ * @version 4.0.4
+ * @link http://adldap.sourceforge.net/
+ */
+
+require_once(dirname(__FILE__) . '/../adLDAP.php');
+require_once(dirname(__FILE__) . '/../collections/adLDAPContactCollection.php');
+
+class adLDAPContacts {
+ /**
+ * The current adLDAP connection via dependency injection
+ *
+ * @var adLDAP
+ */
+ protected $adldap;
+
+ public function __construct(adLDAP $adldap) {
+ $this->adldap = $adldap;
+ }
+
+ //*****************************************************************************************************************
+ // CONTACT FUNCTIONS
+ // * Still work to do in this area, and new functions to write
+
+ /**
+ * Create a contact
+ *
+ * @param array $attributes The attributes to set to the contact
+ * @return bool
+ */
+ public function create($attributes)
+ {
+ // Check for compulsory fields
+ if (!array_key_exists("display_name", $attributes)) { return "Missing compulsory field [display_name]"; }
+ if (!array_key_exists("email", $attributes)) { return "Missing compulsory field [email]"; }
+ if (!array_key_exists("container", $attributes)) { return "Missing compulsory field [container]"; }
+ if (!is_array($attributes["container"])) { return "Container attribute must be an array."; }
+
+ // Translate the schema
+ $add = $this->adldap->adldap_schema($attributes);
+
+ // Additional stuff only used for adding contacts
+ $add["cn"][0] = $attributes["display_name"];
+ $add["objectclass"][0] = "top";
+ $add["objectclass"][1] = "person";
+ $add["objectclass"][2] = "organizationalPerson";
+ $add["objectclass"][3] = "contact";
+ if (!isset($attributes['exchange_hidefromlists'])) {
+ $add["msExchHideFromAddressLists"][0] = "TRUE";
+ }
+
+ // Determine the container
+ $attributes["container"] = array_reverse($attributes["container"]);
+ $container= "OU=" . implode(",OU=", $attributes["container"]);
+
+ // Add the entry
+ $result = @ldap_add($this->adldap->getLdapConnection(), "CN=" . $this->adldap->utilities()->escapeCharacters($add["cn"][0]) . ", " . $container . "," . $this->adldap->getBaseDn(), $add);
+ if ($result != true) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Determine the list of groups a contact is a member of
+ *
+ * @param string $distinguisedname The full DN of a contact
+ * @param bool $recursive Recursively check groups
+ * @return array
+ */
+ public function groups($distinguishedName, $recursive = NULL)
+ {
+ if ($distinguishedName === NULL) { return false; }
+ if ($recursive === NULL) { $recursive = $this->adldap->getRecursiveGroups(); } //use the default option if they haven't set it
+ if (!$this->adldap->getLdapBind()){ return false; }
+
+ // Search the directory for their information
+ $info = @$this->info($distinguishedName, array("memberof", "primarygroupid"));
+ $groups = $this->adldap->utilities()->niceNames($info[0]["memberof"]); //presuming the entry returned is our contact
+
+ if ($recursive === true){
+ foreach ($groups as $id => $groupName){
+ $extraGroups = $this->adldap->group()->recursiveGroups($groupName);
+ $groups = array_merge($groups, $extraGroups);
+ }
+ }
+
+ return $groups;
+ }
+
+ /**
+ * Get contact information. Returned in a raw array format from AD
+ *
+ * @param string $distinguisedname The full DN of a contact
+ * @param array $fields Attributes to be returned
+ * @return array
+ */
+ public function info($distinguishedName, $fields = NULL)
+ {
+ if ($distinguishedName === NULL) { return false; }
+ if (!$this->adldap->getLdapBind()) { return false; }
+
+ $filter = "distinguishedName=" . $distinguishedName;
+ if ($fields === NULL) {
+ $fields = array("distinguishedname", "mail", "memberof", "department", "displayname", "telephonenumber", "primarygroupid", "objectsid");
+ }
+ $sr = ldap_search($this->adldap->getLdapConnection(), $this->adldap->getBaseDn(), $filter, $fields);
+ $entries = ldap_get_entries($this->adldap->getLdapConnection(), $sr);
+
+ if ($entries[0]['count'] >= 1) {
+ // AD does not return the primary group in the ldap query, we may need to fudge it
+ if ($this->adldap->getRealPrimaryGroup() && isset($entries[0]["primarygroupid"][0]) && isset($entries[0]["primarygroupid"][0])){
+ //$entries[0]["memberof"][]=$this->group_cn($entries[0]["primarygroupid"][0]);
+ $entries[0]["memberof"][] = $this->adldap->group()->getPrimaryGroup($entries[0]["primarygroupid"][0], $entries[0]["objectsid"][0]);
+ } else {
+ $entries[0]["memberof"][] = "CN=Domain Users,CN=Users," . $this->adldap->getBaseDn();
+ }
+ }
+
+ $entries[0]["memberof"]["count"]++;
+ return $entries;
+ }
+
+ /**
+ * Find information about the contacts. Returned in a raw array format from AD
+ *
+ * @param string $distinguishedName The full DN of a contact
+ * @param array $fields Array of parameters to query
+ * @return mixed
+ */
+ public function infoCollection($distinguishedName, $fields = NULL)
+ {
+ if ($distinguishedName === NULL) { return false; }
+ if (!$this->adldap->getLdapBind()) { return false; }
+
+ $info = $this->info($distinguishedName, $fields);
+
+ if ($info !== false) {
+ $collection = new adLDAPContactCollection($info, $this->adldap);
+ return $collection;
+ }
+ return false;
+ }
+
+ /**
+ * Determine if a contact is a member of a group
+ *
+ * @param string $distinguisedName The full DN of a contact
+ * @param string $group The group name to query
+ * @param bool $recursive Recursively check groups
+ * @return bool
+ */
+ public function inGroup($distinguisedName, $group, $recursive = NULL)
+ {
+ if ($distinguisedName === NULL) { return false; }
+ if ($group === NULL) { return false; }
+ if (!$this->adldap->getLdapBind()) { return false; }
+ if ($recursive === NULL) { $recursive = $this->adldap->getRecursiveGroups(); } //use the default option if they haven't set it
+
+ // Get a list of the groups
+ $groups = $this->groups($distinguisedName, array("memberof"), $recursive);
+
+ // Return true if the specified group is in the group list
+ if (in_array($group, $groups)){
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Modify a contact
+ *
+ * @param string $distinguishedName The contact to query
+ * @param array $attributes The attributes to modify. Note if you set the enabled attribute you must not specify any other attributes
+ * @return bool
+ */
+ public function modify($distinguishedName, $attributes) {
+ if ($distinguishedName === NULL) { return "Missing compulsory field [distinguishedname]"; }
+
+ // Translate the update to the LDAP schema
+ $mod = $this->adldap->adldap_schema($attributes);
+
+ // Check to see if this is an enabled status update
+ if (!$mod) {
+ return false;
+ }
+
+ // Do the update
+ $result = ldap_modify($this->adldap->getLdapConnection(), $distinguishedName, $mod);
+ if ($result == false) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Delete a contact
+ *
+ * @param string $distinguishedName The contact dn to delete (please be careful here!)
+ * @return array
+ */
+ public function delete($distinguishedName)
+ {
+ $result = $this->folder()->delete($distinguishedName);
+ if ($result != true) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Return a list of all contacts
+ *
+ * @param bool $includeDescription Include a description of a contact
+ * @param string $search The search parameters
+ * @param bool $sorted Whether to sort the results
+ * @return array
+ */
+ public function all($includeDescription = false, $search = "*", $sorted = true) {
+ if (!$this->adldap->getLdapBind()) { return false; }
+
+ // Perform the search and grab all their details
+ $filter = "(&(objectClass=contact)(cn=" . $search . "))";
+ $fields = array("displayname","distinguishedname");
+ $sr = ldap_search($this->adldap->getLdapConnection(), $this->adldap->getBaseDn(), $filter, $fields);
+ $entries = ldap_get_entries($this->adldap->getLdapConnection(), $sr);
+
+ $usersArray = array();
+ for ($i=0; $i<$entries["count"]; $i++){
+ if ($includeDescription && strlen($entries[$i]["displayname"][0])>0){
+ $usersArray[$entries[$i]["distinguishedname"][0]] = $entries[$i]["displayname"][0];
+ } elseif ($includeDescription){
+ $usersArray[$entries[$i]["distinguishedname"][0]] = $entries[$i]["distinguishedname"][0];
+ } else {
+ array_push($usersArray, $entries[$i]["distinguishedname"][0]);
+ }
+ }
+ if ($sorted) {
+ asort($usersArray);
+ }
+ return $usersArray;
+ }
+
+ /**
+ * Mail enable a contact
+ * Allows email to be sent to them through Exchange
+ *
+ * @param string $distinguishedname The contact to mail enable
+ * @param string $emailaddress The email address to allow emails to be sent through
+ * @param string $mailnickname The mailnickname for the contact in Exchange. If NULL this will be set to the display name
+ * @return bool
+ */
+ public function contactMailEnable($distinguishedName, $emailAddress, $mailNickname = NULL){
+ return $this->adldap->exchange()->contactMailEnable($distinguishedName, $emailAddress, $mailNickname);
+ }
+
+
+}
+?>
diff --git a/lib/plugins/authad/adLDAP/classes/adLDAPExchange.php b/lib/plugins/authad/adLDAP/classes/adLDAPExchange.php new file mode 100644 index 000000000..dd0c6de05 --- /dev/null +++ b/lib/plugins/authad/adLDAP/classes/adLDAPExchange.php @@ -0,0 +1,390 @@ +<?php
+/**
+ * PHP LDAP CLASS FOR MANIPULATING ACTIVE DIRECTORY
+ * Version 4.0.4
+ *
+ * PHP Version 5 with SSL and LDAP support
+ *
+ * Written by Scott Barnett, Richard Hyland
+ * email: scott@wiggumworld.com, adldap@richardhyland.com
+ * http://adldap.sourceforge.net/
+ *
+ * Copyright (c) 2006-2012 Scott Barnett, Richard Hyland
+ *
+ * We'd appreciate any improvements or additions to be submitted back
+ * to benefit the entire community :)
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * @category ToolsAndUtilities
+ * @package adLDAP
+ * @subpackage Exchange
+ * @author Scott Barnett, Richard Hyland
+ * @copyright (c) 2006-2012 Scott Barnett, Richard Hyland
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html LGPLv2.1
+ * @revision $Revision: 97 $
+ * @version 4.0.4
+ * @link http://adldap.sourceforge.net/
+ */
+require_once(dirname(__FILE__) . '/../adLDAP.php');
+
+/**
+* MICROSOFT EXCHANGE FUNCTIONS
+*/
+class adLDAPExchange {
+ /**
+ * The current adLDAP connection via dependency injection
+ *
+ * @var adLDAP
+ */
+ protected $adldap;
+
+ public function __construct(adLDAP $adldap) {
+ $this->adldap = $adldap;
+ }
+
+ /**
+ * Create an Exchange account
+ *
+ * @param string $username The username of the user to add the Exchange account to
+ * @param array $storageGroup The mailbox, Exchange Storage Group, for the user account, this must be a full CN
+ * If the storage group has a different base_dn to the adLDAP configuration, set it using $base_dn
+ * @param string $emailAddress The primary email address to add to this user
+ * @param string $mailNickname The mail nick name. If mail nickname is blank, the username will be used
+ * @param bool $mdbUseDefaults Indicates whether the store should use the default quota, rather than the per-mailbox quota.
+ * @param string $baseDn Specify an alternative base_dn for the Exchange storage group
+ * @param bool $isGUID Is the username passed a GUID or a samAccountName
+ * @return bool
+ */
+ public function createMailbox($username, $storageGroup, $emailAddress, $mailNickname=NULL, $useDefaults=TRUE, $baseDn=NULL, $isGUID=false)
+ {
+ if ($username === NULL){ return "Missing compulsory field [username]"; }
+ if ($storageGroup === NULL) { return "Missing compulsory array [storagegroup]"; }
+ if (!is_array($storageGroup)) { return "[storagegroup] must be an array"; }
+ if ($emailAddress === NULL) { return "Missing compulsory field [emailAddress]"; }
+
+ if ($baseDn === NULL) {
+ $baseDn = $this->adldap->getBaseDn();
+ }
+
+ $container = "CN=" . implode(",CN=", $storageGroup);
+
+ if ($mailNickname === NULL) {
+ $mailNickname = $username;
+ }
+ $mdbUseDefaults = $this->adldap->utilities()->boolToString($useDefaults);
+
+ $attributes = array(
+ 'exchange_homemdb'=>$container.",".$baseDn,
+ 'exchange_proxyaddress'=>'SMTP:' . $emailAddress,
+ 'exchange_mailnickname'=>$mailNickname,
+ 'exchange_usedefaults'=>$mdbUseDefaults
+ );
+ $result = $this->adldap->user()->modify($username, $attributes, $isGUID);
+ if ($result == false) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Add an X400 address to Exchange
+ * See http://tools.ietf.org/html/rfc1685 for more information.
+ * An X400 Address looks similar to this X400:c=US;a= ;p=Domain;o=Organization;s=Doe;g=John;
+ *
+ * @param string $username The username of the user to add the X400 to to
+ * @param string $country Country
+ * @param string $admd Administration Management Domain
+ * @param string $pdmd Private Management Domain (often your AD domain)
+ * @param string $org Organization
+ * @param string $surname Surname
+ * @param string $givenName Given name
+ * @param bool $isGUID Is the username passed a GUID or a samAccountName
+ * @return bool
+ */
+ public function addX400($username, $country, $admd, $pdmd, $org, $surname, $givenName, $isGUID=false)
+ {
+ if ($username === NULL){ return "Missing compulsory field [username]"; }
+
+ $proxyValue = 'X400:';
+
+ // Find the dn of the user
+ $user = $this->adldap->user()->info($username, array("cn","proxyaddresses"), $isGUID);
+ if ($user[0]["dn"] === NULL) { return false; }
+ $userDn = $user[0]["dn"];
+
+ // We do not have to demote an email address from the default so we can just add the new proxy address
+ $attributes['exchange_proxyaddress'] = $proxyValue . 'c=' . $country . ';a=' . $admd . ';p=' . $pdmd . ';o=' . $org . ';s=' . $surname . ';g=' . $givenName . ';';
+
+ // Translate the update to the LDAP schema
+ $add = $this->adldap->adldap_schema($attributes);
+
+ if (!$add) { return false; }
+
+ // Do the update
+ // Take out the @ to see any errors, usually this error might occur because the address already
+ // exists in the list of proxyAddresses
+ $result = @ldap_mod_add($this->adldap->getLdapConnection(), $userDn, $add);
+ if ($result == false) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Add an address to Exchange
+ *
+ * @param string $username The username of the user to add the Exchange account to
+ * @param string $emailAddress The email address to add to this user
+ * @param bool $default Make this email address the default address, this is a bit more intensive as we have to demote any existing default addresses
+ * @param bool $isGUID Is the username passed a GUID or a samAccountName
+ * @return bool
+ */
+ public function addAddress($username, $emailAddress, $default = FALSE, $isGUID = false)
+ {
+ if ($username === NULL) { return "Missing compulsory field [username]"; }
+ if ($emailAddress === NULL) { return "Missing compulsory fields [emailAddress]"; }
+
+ $proxyValue = 'smtp:';
+ if ($default === true) {
+ $proxyValue = 'SMTP:';
+ }
+
+ // Find the dn of the user
+ $user = $this->adldap->user()->info($username, array("cn","proxyaddresses"), $isGUID);
+ if ($user[0]["dn"] === NULL){ return false; }
+ $userDn = $user[0]["dn"];
+
+ // We need to scan existing proxy addresses and demote the default one
+ if (is_array($user[0]["proxyaddresses"]) && $default === true) {
+ $modAddresses = array();
+ for ($i=0;$i<sizeof($user[0]['proxyaddresses']);$i++) {
+ if (strstr($user[0]['proxyaddresses'][$i], 'SMTP:') !== false) {
+ $user[0]['proxyaddresses'][$i] = str_replace('SMTP:', 'smtp:', $user[0]['proxyaddresses'][$i]);
+ }
+ if ($user[0]['proxyaddresses'][$i] != '') {
+ $modAddresses['proxyAddresses'][$i] = $user[0]['proxyaddresses'][$i];
+ }
+ }
+ $modAddresses['proxyAddresses'][(sizeof($user[0]['proxyaddresses'])-1)] = 'SMTP:' . $emailAddress;
+
+ $result = @ldap_mod_replace($this->adldap->getLdapConnection(), $userDn, $modAddresses);
+ if ($result == false) {
+ return false;
+ }
+
+ return true;
+ }
+ else {
+ // We do not have to demote an email address from the default so we can just add the new proxy address
+ $attributes['exchange_proxyaddress'] = $proxyValue . $emailAddress;
+
+ // Translate the update to the LDAP schema
+ $add = $this->adldap->adldap_schema($attributes);
+
+ if (!$add) {
+ return false;
+ }
+
+ // Do the update
+ // Take out the @ to see any errors, usually this error might occur because the address already
+ // exists in the list of proxyAddresses
+ $result = @ldap_mod_add($this->adldap->getLdapConnection(), $userDn,$add);
+ if ($result == false) {
+ return false;
+ }
+
+ return true;
+ }
+ }
+
+ /**
+ * Remove an address to Exchange
+ * If you remove a default address the account will no longer have a default,
+ * we recommend changing the default address first
+ *
+ * @param string $username The username of the user to add the Exchange account to
+ * @param string $emailAddress The email address to add to this user
+ * @param bool $isGUID Is the username passed a GUID or a samAccountName
+ * @return bool
+ */
+ public function deleteAddress($username, $emailAddress, $isGUID=false)
+ {
+ if ($username === NULL) { return "Missing compulsory field [username]"; }
+ if ($emailAddress === NULL) { return "Missing compulsory fields [emailAddress]"; }
+
+ // Find the dn of the user
+ $user = $this->adldap->user()->info($username, array("cn","proxyaddresses"), $isGUID);
+ if ($user[0]["dn"] === NULL) { return false; }
+ $userDn = $user[0]["dn"];
+
+ if (is_array($user[0]["proxyaddresses"])) {
+ $mod = array();
+ for ($i=0;$i<sizeof($user[0]['proxyaddresses']);$i++) {
+ if (strstr($user[0]['proxyaddresses'][$i], 'SMTP:') !== false && $user[0]['proxyaddresses'][$i] == 'SMTP:' . $emailAddress) {
+ $mod['proxyAddresses'][0] = 'SMTP:' . $emailAddress;
+ }
+ elseif (strstr($user[0]['proxyaddresses'][$i], 'smtp:') !== false && $user[0]['proxyaddresses'][$i] == 'smtp:' . $emailAddress) {
+ $mod['proxyAddresses'][0] = 'smtp:' . $emailAddress;
+ }
+ }
+
+ $result = @ldap_mod_del($this->adldap->getLdapConnection(), $userDn,$mod);
+ if ($result == false) {
+ return false;
+ }
+
+ return true;
+ }
+ else {
+ return false;
+ }
+ }
+ /**
+ * Change the default address
+ *
+ * @param string $username The username of the user to add the Exchange account to
+ * @param string $emailAddress The email address to make default
+ * @param bool $isGUID Is the username passed a GUID or a samAccountName
+ * @return bool
+ */
+ public function primaryAddress($username, $emailAddress, $isGUID = false)
+ {
+ if ($username === NULL) { return "Missing compulsory field [username]"; }
+ if ($emailAddress === NULL) { return "Missing compulsory fields [emailAddress]"; }
+
+ // Find the dn of the user
+ $user = $this->adldap->user()->info($username, array("cn","proxyaddresses"), $isGUID);
+ if ($user[0]["dn"] === NULL){ return false; }
+ $userDn = $user[0]["dn"];
+
+ if (is_array($user[0]["proxyaddresses"])) {
+ $modAddresses = array();
+ for ($i=0;$i<sizeof($user[0]['proxyaddresses']);$i++) {
+ if (strstr($user[0]['proxyaddresses'][$i], 'SMTP:') !== false) {
+ $user[0]['proxyaddresses'][$i] = str_replace('SMTP:', 'smtp:', $user[0]['proxyaddresses'][$i]);
+ }
+ if ($user[0]['proxyaddresses'][$i] == 'smtp:' . $emailAddress) {
+ $user[0]['proxyaddresses'][$i] = str_replace('smtp:', 'SMTP:', $user[0]['proxyaddresses'][$i]);
+ }
+ if ($user[0]['proxyaddresses'][$i] != '') {
+ $modAddresses['proxyAddresses'][$i] = $user[0]['proxyaddresses'][$i];
+ }
+ }
+
+ $result = @ldap_mod_replace($this->adldap->getLdapConnection(), $userDn, $modAddresses);
+ if ($result == false) {
+ return false;
+ }
+
+ return true;
+ }
+
+ }
+
+ /**
+ * Mail enable a contact
+ * Allows email to be sent to them through Exchange
+ *
+ * @param string $distinguishedName The contact to mail enable
+ * @param string $emailAddress The email address to allow emails to be sent through
+ * @param string $mailNickname The mailnickname for the contact in Exchange. If NULL this will be set to the display name
+ * @return bool
+ */
+ public function contactMailEnable($distinguishedName, $emailAddress, $mailNickname = NULL)
+ {
+ if ($distinguishedName === NULL) { return "Missing compulsory field [distinguishedName]"; }
+ if ($emailAddress === NULL) { return "Missing compulsory field [emailAddress]"; }
+
+ if ($mailNickname !== NULL) {
+ // Find the dn of the user
+ $user = $this->adldap->contact()->info($distinguishedName, array("cn","displayname"));
+ if ($user[0]["displayname"] === NULL) { return false; }
+ $mailNickname = $user[0]['displayname'][0];
+ }
+
+ $attributes = array("email"=>$emailAddress,"contact_email"=>"SMTP:" . $emailAddress,"exchange_proxyaddress"=>"SMTP:" . $emailAddress,"exchange_mailnickname" => $mailNickname);
+
+ // Translate the update to the LDAP schema
+ $mod = $this->adldap->adldap_schema($attributes);
+
+ // Check to see if this is an enabled status update
+ if (!$mod) { return false; }
+
+ // Do the update
+ $result = ldap_modify($this->adldap->getLdapConnection(), $distinguishedName, $mod);
+ if ($result == false) { return false; }
+
+ return true;
+ }
+
+ /**
+ * Returns a list of Exchange Servers in the ConfigurationNamingContext of the domain
+ *
+ * @param array $attributes An array of the AD attributes you wish to return
+ * @return array
+ */
+ public function servers($attributes = array('cn','distinguishedname','serialnumber'))
+ {
+ if (!$this->adldap->getLdapBind()){ return false; }
+
+ $configurationNamingContext = $this->adldap->getRootDse(array('configurationnamingcontext'));
+ $sr = @ldap_search($this->adldap->getLdapConnection(), $configurationNamingContext[0]['configurationnamingcontext'][0],'(&(objectCategory=msExchExchangeServer))', $attributes);
+ $entries = @ldap_get_entries($this->adldap->getLdapConnection(), $sr);
+ return $entries;
+ }
+
+ /**
+ * Returns a list of Storage Groups in Exchange for a given mail server
+ *
+ * @param string $exchangeServer The full DN of an Exchange server. You can use exchange_servers() to find the DN for your server
+ * @param array $attributes An array of the AD attributes you wish to return
+ * @param bool $recursive If enabled this will automatically query the databases within a storage group
+ * @return array
+ */
+ public function storageGroups($exchangeServer, $attributes = array('cn','distinguishedname'), $recursive = NULL)
+ {
+ if (!$this->adldap->getLdapBind()){ return false; }
+ if ($exchangeServer === NULL) { return "Missing compulsory field [exchangeServer]"; }
+ if ($recursive === NULL) { $recursive = $this->adldap->getRecursiveGroups(); }
+
+ $filter = '(&(objectCategory=msExchStorageGroup))';
+ $sr = @ldap_search($this->adldap->getLdapConnection(), $exchangeServer, $filter, $attributes);
+ $entries = @ldap_get_entries($this->adldap->getLdapConnection(), $sr);
+
+ if ($recursive === true) {
+ for ($i=0; $i<$entries['count']; $i++) {
+ $entries[$i]['msexchprivatemdb'] = $this->storageDatabases($entries[$i]['distinguishedname'][0]);
+ }
+ }
+
+ return $entries;
+ }
+
+ /**
+ * Returns a list of Databases within any given storage group in Exchange for a given mail server
+ *
+ * @param string $storageGroup The full DN of an Storage Group. You can use exchange_storage_groups() to find the DN
+ * @param array $attributes An array of the AD attributes you wish to return
+ * @return array
+ */
+ public function storageDatabases($storageGroup, $attributes = array('cn','distinguishedname','displayname')) {
+ if (!$this->adldap->getLdapBind()){ return false; }
+ if ($storageGroup === NULL) { return "Missing compulsory field [storageGroup]"; }
+
+ $filter = '(&(objectCategory=msExchPrivateMDB))';
+ $sr = @ldap_search($this->adldap->getLdapConnection(), $storageGroup, $filter, $attributes);
+ $entries = @ldap_get_entries($this->adldap->getLdapConnection(), $sr);
+ return $entries;
+ }
+}
+?>
\ No newline at end of file diff --git a/lib/plugins/authad/adLDAP/classes/adLDAPFolders.php b/lib/plugins/authad/adLDAP/classes/adLDAPFolders.php new file mode 100644 index 000000000..55120152d --- /dev/null +++ b/lib/plugins/authad/adLDAP/classes/adLDAPFolders.php @@ -0,0 +1,179 @@ +<?php
+/**
+ * PHP LDAP CLASS FOR MANIPULATING ACTIVE DIRECTORY
+ * Version 4.0.4
+ *
+ * PHP Version 5 with SSL and LDAP support
+ *
+ * Written by Scott Barnett, Richard Hyland
+ * email: scott@wiggumworld.com, adldap@richardhyland.com
+ * http://adldap.sourceforge.net/
+ *
+ * Copyright (c) 2006-2012 Scott Barnett, Richard Hyland
+ *
+ * We'd appreciate any improvements or additions to be submitted back
+ * to benefit the entire community :)
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * @category ToolsAndUtilities
+ * @package adLDAP
+ * @subpackage Folders
+ * @author Scott Barnett, Richard Hyland
+ * @copyright (c) 2006-2012 Scott Barnett, Richard Hyland
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html LGPLv2.1
+ * @revision $Revision: 97 $
+ * @version 4.0.4
+ * @link http://adldap.sourceforge.net/
+ */
+require_once(dirname(__FILE__) . '/../adLDAP.php');
+
+/**
+* FOLDER / OU MANAGEMENT FUNCTIONS
+*/
+class adLDAPFolders {
+ /**
+ * The current adLDAP connection via dependency injection
+ *
+ * @var adLDAP
+ */
+ protected $adldap;
+
+ public function __construct(adLDAP $adldap) {
+ $this->adldap = $adldap;
+ }
+
+ /**
+ * Delete a distinguished name from Active Directory
+ * You should never need to call this yourself, just use the wrapper functions user_delete and contact_delete
+ *
+ * @param string $dn The distinguished name to delete
+ * @return bool
+ */
+ public function delete($dn){
+ $result = ldap_delete($this->adldap->getLdapConnection(), $dn);
+ if ($result != true) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Returns a folder listing for a specific OU
+ * See http://adldap.sourceforge.net/wiki/doku.php?id=api_folder_functions
+ *
+ * @param array $folderName An array to the OU you wish to list.
+ * If set to NULL will list the root, strongly recommended to set
+ * $recursive to false in that instance!
+ * @param string $dnType The type of record to list. This can be ADLDAP_FOLDER or ADLDAP_CONTAINER.
+ * @param bool $recursive Recursively search sub folders
+ * @param bool $type Specify a type of object to search for
+ * @return array
+ */
+ public function listing($folderName = NULL, $dnType = adLDAP::ADLDAP_FOLDER, $recursive = NULL, $type = NULL)
+ {
+ if ($recursive === NULL) { $recursive = $this->adldap->getRecursiveGroups(); } //use the default option if they haven't set it
+ if (!$this->adldap->getLdapBind()) { return false; }
+
+ $filter = '(&';
+ if ($type !== NULL) {
+ switch ($type) {
+ case 'contact':
+ $filter .= '(objectClass=contact)';
+ break;
+ case 'computer':
+ $filter .= '(objectClass=computer)';
+ break;
+ case 'group':
+ $filter .= '(objectClass=group)';
+ break;
+ case 'folder':
+ $filter .= '(objectClass=organizationalUnit)';
+ break;
+ case 'container':
+ $filter .= '(objectClass=container)';
+ break;
+ case 'domain':
+ $filter .= '(objectClass=builtinDomain)';
+ break;
+ default:
+ $filter .= '(objectClass=user)';
+ break;
+ }
+ }
+ else {
+ $filter .= '(objectClass=*)';
+ }
+ // If the folder name is null then we will search the root level of AD
+ // This requires us to not have an OU= part, just the base_dn
+ $searchOu = $this->adldap->getBaseDn();
+ if (is_array($folderName)) {
+ $ou = $dnType . "=" . implode("," . $dnType . "=", $folderName);
+ $filter .= '(!(distinguishedname=' . $ou . ',' . $this->adldap->getBaseDn() . ')))';
+ $searchOu = $ou . ',' . $this->adldap->getBaseDn();
+ }
+ else {
+ $filter .= '(!(distinguishedname=' . $this->adldap->getBaseDn() . ')))';
+ }
+
+ if ($recursive === true) {
+ $sr = ldap_search($this->adldap->getLdapConnection(), $searchOu, $filter, array('objectclass', 'distinguishedname', 'samaccountname'));
+ $entries = @ldap_get_entries($this->adldap->getLdapConnection(), $sr);
+ if (is_array($entries)) {
+ return $entries;
+ }
+ }
+ else {
+ $sr = ldap_list($this->adldap->getLdapConnection(), $searchOu, $filter, array('objectclass', 'distinguishedname', 'samaccountname'));
+ $entries = @ldap_get_entries($this->adldap->getLdapConnection(), $sr);
+ if (is_array($entries)) {
+ return $entries;
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Create an organizational unit
+ *
+ * @param array $attributes Default attributes of the ou
+ * @return bool
+ */
+ public function create($attributes)
+ {
+ if (!is_array($attributes)){ return "Attributes must be an array"; }
+ if (!is_array($attributes["container"])) { return "Container attribute must be an array."; }
+ if (!array_key_exists("ou_name",$attributes)) { return "Missing compulsory field [ou_name]"; }
+ if (!array_key_exists("container",$attributes)) { return "Missing compulsory field [container]"; }
+
+ $attributes["container"] = array_reverse($attributes["container"]);
+
+ $add=array();
+ $add["objectClass"] = "organizationalUnit";
+ $add["OU"] = $attributes['ou_name'];
+ $containers = "";
+ if (count($attributes['container']) > 0) {
+ $containers = "OU=" . implode(",OU=", $attributes["container"]) . ",";
+ }
+
+ $containers = "OU=" . implode(",OU=", $attributes["container"]);
+ $result = ldap_add($this->adldap->getLdapConnection(), "OU=" . $add["OU"] . ", " . $containers . $this->adldap->getBaseDn(), $add);
+ if ($result != true) {
+ return false;
+ }
+
+ return true;
+ }
+
+}
+
+?>
\ No newline at end of file diff --git a/lib/plugins/authad/adLDAP/classes/adLDAPGroups.php b/lib/plugins/authad/adLDAP/classes/adLDAPGroups.php new file mode 100644 index 000000000..05e4cc93b --- /dev/null +++ b/lib/plugins/authad/adLDAP/classes/adLDAPGroups.php @@ -0,0 +1,631 @@ +<?php
+/**
+ * PHP LDAP CLASS FOR MANIPULATING ACTIVE DIRECTORY
+ * Version 4.0.4
+ *
+ * PHP Version 5 with SSL and LDAP support
+ *
+ * Written by Scott Barnett, Richard Hyland
+ * email: scott@wiggumworld.com, adldap@richardhyland.com
+ * http://adldap.sourceforge.net/
+ *
+ * Copyright (c) 2006-2012 Scott Barnett, Richard Hyland
+ *
+ * We'd appreciate any improvements or additions to be submitted back
+ * to benefit the entire community :)
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * @category ToolsAndUtilities
+ * @package adLDAP
+ * @subpackage Groups
+ * @author Scott Barnett, Richard Hyland
+ * @copyright (c) 2006-2012 Scott Barnett, Richard Hyland
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html LGPLv2.1
+ * @revision $Revision: 97 $
+ * @version 4.0.4
+ * @link http://adldap.sourceforge.net/
+ */
+require_once(dirname(__FILE__) . '/../adLDAP.php');
+require_once(dirname(__FILE__) . '/../collections/adLDAPGroupCollection.php');
+
+/**
+* GROUP FUNCTIONS
+*/
+class adLDAPGroups {
+ /**
+ * The current adLDAP connection via dependency injection
+ *
+ * @var adLDAP
+ */
+ protected $adldap;
+
+ public function __construct(adLDAP $adldap) {
+ $this->adldap = $adldap;
+ }
+
+ /**
+ * Add a group to a group
+ *
+ * @param string $parent The parent group name
+ * @param string $child The child group name
+ * @return bool
+ */
+ public function addGroup($parent,$child){
+
+ // Find the parent group's dn
+ $parentGroup = $this->ginfo($parent, array("cn"));
+ if ($parentGroup[0]["dn"] === NULL){
+ return false;
+ }
+ $parentDn = $parentGroup[0]["dn"];
+
+ // Find the child group's dn
+ $childGroup = $this->info($child, array("cn"));
+ if ($childGroup[0]["dn"] === NULL){
+ return false;
+ }
+ $childDn = $childGroup[0]["dn"];
+
+ $add = array();
+ $add["member"] = $childDn;
+
+ $result = @ldap_mod_add($this->adldap->getLdapConnection(), $parentDn, $add);
+ if ($result == false) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Add a user to a group
+ *
+ * @param string $group The group to add the user to
+ * @param string $user The user to add to the group
+ * @param bool $isGUID Is the username passed a GUID or a samAccountName
+ * @return bool
+ */
+ public function addUser($group, $user, $isGUID = false)
+ {
+ // Adding a user is a bit fiddly, we need to get the full DN of the user
+ // and add it using the full DN of the group
+
+ // Find the user's dn
+ $userDn = $this->adldap->user()->dn($user, $isGUID);
+ if ($userDn === false) {
+ return false;
+ }
+
+ // Find the group's dn
+ $groupInfo = $this->info($group, array("cn"));
+ if ($groupInfo[0]["dn"] === NULL) {
+ return false;
+ }
+ $groupDn = $groupInfo[0]["dn"];
+
+ $add = array();
+ $add["member"] = $userDn;
+
+ $result = @ldap_mod_add($this->adldap->getLdapConnection(), $groupDn, $add);
+ if ($result == false) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Add a contact to a group
+ *
+ * @param string $group The group to add the contact to
+ * @param string $contactDn The DN of the contact to add
+ * @return bool
+ */
+ public function addContact($group, $contactDn)
+ {
+ // To add a contact we take the contact's DN
+ // and add it using the full DN of the group
+
+ // Find the group's dn
+ $groupInfo = $this->info($group, array("cn"));
+ if ($groupInfo[0]["dn"] === NULL) {
+ return false;
+ }
+ $groupDn = $groupInfo[0]["dn"];
+
+ $add = array();
+ $add["member"] = $contactDn;
+
+ $result = @ldap_mod_add($this->adldap->getLdapConnection(), $groupDn, $add);
+ if ($result == false) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Create a group
+ *
+ * @param array $attributes Default attributes of the group
+ * @return bool
+ */
+ public function create($attributes)
+ {
+ if (!is_array($attributes)){ return "Attributes must be an array"; }
+ if (!array_key_exists("group_name", $attributes)){ return "Missing compulsory field [group_name]"; }
+ if (!array_key_exists("container", $attributes)){ return "Missing compulsory field [container]"; }
+ if (!array_key_exists("description", $attributes)){ return "Missing compulsory field [description]"; }
+ if (!is_array($attributes["container"])){ return "Container attribute must be an array."; }
+ $attributes["container"] = array_reverse($attributes["container"]);
+
+ //$member_array = array();
+ //$member_array[0] = "cn=user1,cn=Users,dc=yourdomain,dc=com";
+ //$member_array[1] = "cn=administrator,cn=Users,dc=yourdomain,dc=com";
+
+ $add = array();
+ $add["cn"] = $attributes["group_name"];
+ $add["samaccountname"] = $attributes["group_name"];
+ $add["objectClass"] = "Group";
+ $add["description"] = $attributes["description"];
+ //$add["member"] = $member_array; UNTESTED
+
+ $container = "OU=" . implode(",OU=", $attributes["container"]);
+ $result = ldap_add($this->adldap->getLdapConnection(), "CN=" . $add["cn"] . ", " . $container . "," . $this->adldap->getBaseDn(), $add);
+ if ($result != true) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Delete a group account
+ *
+ * @param string $group The group to delete (please be careful here!)
+ *
+ * @return array
+ */
+ public function delete($group) {
+ if (!$this->adldap->getLdapBind()){ return false; }
+ if ($group === null){ return "Missing compulsory field [group]"; }
+
+ $groupInfo = $this->info($group, array("*"));
+ $dn = $groupInfo[0]['distinguishedname'][0];
+ $result = $this->adldap->folder()->delete($dn);
+ if ($result !== true) {
+ return false;
+ } return true;
+ }
+
+ /**
+ * Remove a group from a group
+ *
+ * @param string $parent The parent group name
+ * @param string $child The child group name
+ * @return bool
+ */
+ public function removeGroup($parent , $child)
+ {
+
+ // Find the parent dn
+ $parentGroup = $this->info($parent, array("cn"));
+ if ($parentGroup[0]["dn"] === NULL) {
+ return false;
+ }
+ $parentDn = $parentGroup[0]["dn"];
+
+ // Find the child dn
+ $childGroup = $this->info($child, array("cn"));
+ if ($childGroup[0]["dn"] === NULL) {
+ return false;
+ }
+ $childDn = $childGroup[0]["dn"];
+
+ $del = array();
+ $del["member"] = $childDn;
+
+ $result = @ldap_mod_del($this->adldap->getLdapConnection(), $parentDn, $del);
+ if ($result == false) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Remove a user from a group
+ *
+ * @param string $group The group to remove a user from
+ * @param string $user The AD user to remove from the group
+ * @param bool $isGUID Is the username passed a GUID or a samAccountName
+ * @return bool
+ */
+ public function removeUser($group, $user, $isGUID = false)
+ {
+
+ // Find the parent dn
+ $groupInfo = $this->info($group, array("cn"));
+ if ($groupInfo[0]["dn"] === NULL){
+ return false;
+ }
+ $groupDn = $groupInfo[0]["dn"];
+
+ // Find the users dn
+ $userDn = $this->adldap->user()->dn($user, $isGUID);
+ if ($userDn === false) {
+ return false;
+ }
+
+ $del = array();
+ $del["member"] = $userDn;
+
+ $result = @ldap_mod_del($this->adldap->getLdapConnection(), $groupDn, $del);
+ if ($result == false) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Remove a contact from a group
+ *
+ * @param string $group The group to remove a user from
+ * @param string $contactDn The DN of a contact to remove from the group
+ * @return bool
+ */
+ public function removeContact($group, $contactDn)
+ {
+
+ // Find the parent dn
+ $groupInfo = $this->info($group, array("cn"));
+ if ($groupInfo[0]["dn"] === NULL) {
+ return false;
+ }
+ $groupDn = $groupInfo[0]["dn"];
+
+ $del = array();
+ $del["member"] = $contactDn;
+
+ $result = @ldap_mod_del($this->adldap->getLdapConnection(), $groupDn, $del);
+ if ($result == false) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Return a list of groups in a group
+ *
+ * @param string $group The group to query
+ * @param bool $recursive Recursively get groups
+ * @return array
+ */
+ public function inGroup($group, $recursive = NULL)
+ {
+ if (!$this->adldap->getLdapBind()){ return false; }
+ if ($recursive === NULL){ $recursive = $this->adldap->getRecursiveGroups(); } // Use the default option if they haven't set it
+
+ // Search the directory for the members of a group
+ $info = $this->info($group, array("member","cn"));
+ $groups = $info[0]["member"];
+ if (!is_array($groups)) {
+ return false;
+ }
+
+ $groupArray = array();
+
+ for ($i=0; $i<$groups["count"]; $i++){
+ $filter = "(&(objectCategory=group)(distinguishedName=" . $this->adldap->utilities()->ldapSlashes($groups[$i]) . "))";
+ $fields = array("samaccountname", "distinguishedname", "objectClass");
+ $sr = ldap_search($this->adldap->getLdapConnection(), $this->adldap->getBaseDn(), $filter, $fields);
+ $entries = ldap_get_entries($this->adldap->getLdapConnection(), $sr);
+
+ // not a person, look for a group
+ if ($entries['count'] == 0 && $recursive == true) {
+ $filter = "(&(objectCategory=group)(distinguishedName=" . $this->adldap->utilities()->ldapSlashes($groups[$i]) . "))";
+ $fields = array("distinguishedname");
+ $sr = ldap_search($this->adldap->getLdapConnection(), $this->adldap->getBaseDn(), $filter, $fields);
+ $entries = ldap_get_entries($this->adldap->getLdapConnection(), $sr);
+ if (!isset($entries[0]['distinguishedname'][0])) {
+ continue;
+ }
+ $subGroups = $this->inGroup($entries[0]['distinguishedname'][0], $recursive);
+ if (is_array($subGroups)) {
+ $groupArray = array_merge($groupArray, $subGroups);
+ $groupArray = array_unique($groupArray);
+ }
+ continue;
+ }
+
+ $groupArray[] = $entries[0]['distinguishedname'][0];
+ }
+ return $groupArray;
+ }
+
+ /**
+ * Return a list of members in a group
+ *
+ * @param string $group The group to query
+ * @param bool $recursive Recursively get group members
+ * @return array
+ */
+ public function members($group, $recursive = NULL)
+ {
+ if (!$this->adldap->getLdapBind()){ return false; }
+ if ($recursive === NULL){ $recursive = $this->adldap->getRecursiveGroups(); } // Use the default option if they haven't set it
+ // Search the directory for the members of a group
+ $info = $this->info($group, array("member","cn"));
+ $users = $info[0]["member"];
+ if (!is_array($users)) {
+ return false;
+ }
+
+ $userArray = array();
+
+ for ($i=0; $i<$users["count"]; $i++){
+ $filter = "(&(objectCategory=person)(distinguishedName=" . $this->adldap->utilities()->ldapSlashes($users[$i]) . "))";
+ $fields = array("samaccountname", "distinguishedname", "objectClass");
+ $sr = ldap_search($this->adldap->getLdapConnection(), $this->adldap->getBaseDn(), $filter, $fields);
+ $entries = ldap_get_entries($this->adldap->getLdapConnection(), $sr);
+
+ // not a person, look for a group
+ if ($entries['count'] == 0 && $recursive == true) {
+ $filter = "(&(objectCategory=group)(distinguishedName=" . $this->adldap->utilities()->ldapSlashes($users[$i]) . "))";
+ $fields = array("samaccountname");
+ $sr = ldap_search($this->adldap->getLdapConnection(), $this->adldap->getBaseDn(), $filter, $fields);
+ $entries = ldap_get_entries($this->adldap->getLdapConnection(), $sr);
+ if (!isset($entries[0]['samaccountname'][0])) {
+ continue;
+ }
+ $subUsers = $this->members($entries[0]['samaccountname'][0], $recursive);
+ if (is_array($subUsers)) {
+ $userArray = array_merge($userArray, $subUsers);
+ $userArray = array_unique($userArray);
+ }
+ continue;
+ }
+ else if ($entries['count'] == 0) {
+ continue;
+ }
+
+ if ((!isset($entries[0]['samaccountname'][0]) || $entries[0]['samaccountname'][0] === NULL) && $entries[0]['distinguishedname'][0] !== NULL) {
+ $userArray[] = $entries[0]['distinguishedname'][0];
+ }
+ else if ($entries[0]['samaccountname'][0] !== NULL) {
+ $userArray[] = $entries[0]['samaccountname'][0];
+ }
+ }
+ return $userArray;
+ }
+
+ /**
+ * Group Information. Returns an array of raw information about a group.
+ * The group name is case sensitive
+ *
+ * @param string $groupName The group name to retrieve info about
+ * @param array $fields Fields to retrieve
+ * @return array
+ */
+ public function info($groupName, $fields = NULL)
+ {
+ if ($groupName === NULL) { return false; }
+ if (!$this->adldap->getLdapBind()) { return false; }
+
+ if (stristr($groupName, '+')) {
+ $groupName = stripslashes($groupName);
+ }
+
+ $filter = "(&(objectCategory=group)(name=" . $this->adldap->utilities()->ldapSlashes($groupName) . "))";
+ if ($fields === NULL) {
+ $fields = array("member","memberof","cn","description","distinguishedname","objectcategory","samaccountname");
+ }
+ $sr = ldap_search($this->adldap->getLdapConnection(), $this->adldap->getBaseDn(), $filter, $fields);
+ $entries = ldap_get_entries($this->adldap->getLdapConnection(), $sr);
+
+ return $entries;
+ }
+
+ /**
+ * Group Information. Returns an collection
+ * The group name is case sensitive
+ *
+ * @param string $groupName The group name to retrieve info about
+ * @param array $fields Fields to retrieve
+ * @return adLDAPGroupCollection
+ */
+ public function infoCollection($groupName, $fields = NULL)
+ {
+ if ($groupName === NULL) { return false; }
+ if (!$this->adldap->getLdapBind()) { return false; }
+
+ $info = $this->info($groupName, $fields);
+ if ($info !== false) {
+ $collection = new adLDAPGroupCollection($info, $this->adldap);
+ return $collection;
+ }
+ return false;
+ }
+
+ /**
+ * Return a complete list of "groups in groups"
+ *
+ * @param string $group The group to get the list from
+ * @return array
+ */
+ public function recursiveGroups($group)
+ {
+ if ($group === NULL) { return false; }
+
+ $stack = array();
+ $processed = array();
+ $retGroups = array();
+
+ array_push($stack, $group); // Initial Group to Start with
+ while (count($stack) > 0) {
+ $parent = array_pop($stack);
+ array_push($processed, $parent);
+
+ $info = $this->info($parent, array("memberof"));
+
+ if (isset($info[0]["memberof"]) && is_array($info[0]["memberof"])) {
+ $groups = $info[0]["memberof"];
+ if ($groups) {
+ $groupNames = $this->adldap->utilities()->niceNames($groups);
+ $retGroups = array_merge($retGroups, $groupNames); //final groups to return
+ foreach ($groupNames as $id => $groupName) {
+ if (!in_array($groupName, $processed)) {
+ array_push($stack, $groupName);
+ }
+ }
+ }
+ }
+ }
+
+ return $retGroups;
+ }
+
+ /**
+ * Returns a complete list of the groups in AD based on a SAM Account Type
+ *
+ * @param string $sAMAaccountType The account type to return
+ * @param bool $includeDescription Whether to return a description
+ * @param string $search Search parameters
+ * @param bool $sorted Whether to sort the results
+ * @return array
+ */
+ public function search($sAMAaccountType = adLDAP::ADLDAP_SECURITY_GLOBAL_GROUP, $includeDescription = false, $search = "*", $sorted = true) {
+ if (!$this->adldap->getLdapBind()) { return false; }
+
+ $filter = '(&(objectCategory=group)';
+ if ($sAMAaccountType !== null) {
+ $filter .= '(samaccounttype='. $sAMAaccountType .')';
+ }
+ $filter .= '(cn=' . $search . '))';
+ // Perform the search and grab all their details
+ $fields = array("samaccountname", "description");
+ $sr = ldap_search($this->adldap->getLdapConnection(), $this->adldap->getBaseDn(), $filter, $fields);
+ $entries = ldap_get_entries($this->adldap->getLdapConnection(), $sr);
+
+ $groupsArray = array();
+ for ($i=0; $i<$entries["count"]; $i++){
+ if ($includeDescription && strlen($entries[$i]["description"][0]) > 0 ) {
+ $groupsArray[$entries[$i]["samaccountname"][0]] = $entries[$i]["description"][0];
+ }
+ else if ($includeDescription){
+ $groupsArray[$entries[$i]["samaccountname"][0]] = $entries[$i]["samaccountname"][0];
+ }
+ else {
+ array_push($groupsArray, $entries[$i]["samaccountname"][0]);
+ }
+ }
+ if ($sorted) {
+ asort($groupsArray);
+ }
+ return $groupsArray;
+ }
+
+ /**
+ * Returns a complete list of all groups in AD
+ *
+ * @param bool $includeDescription Whether to return a description
+ * @param string $search Search parameters
+ * @param bool $sorted Whether to sort the results
+ * @return array
+ */
+ public function all($includeDescription = false, $search = "*", $sorted = true){
+ $groupsArray = $this->search(null, $includeDescription, $search, $sorted);
+ return $groupsArray;
+ }
+
+ /**
+ * Returns a complete list of security groups in AD
+ *
+ * @param bool $includeDescription Whether to return a description
+ * @param string $search Search parameters
+ * @param bool $sorted Whether to sort the results
+ * @return array
+ */
+ public function allSecurity($includeDescription = false, $search = "*", $sorted = true){
+ $groupsArray = $this->search(adLDAP::ADLDAP_SECURITY_GLOBAL_GROUP, $includeDescription, $search, $sorted);
+ return $groupsArray;
+ }
+
+ /**
+ * Returns a complete list of distribution lists in AD
+ *
+ * @param bool $includeDescription Whether to return a description
+ * @param string $search Search parameters
+ * @param bool $sorted Whether to sort the results
+ * @return array
+ */
+ public function allDistribution($includeDescription = false, $search = "*", $sorted = true){
+ $groupsArray = $this->search(adLDAP::ADLDAP_DISTRIBUTION_GROUP, $includeDescription, $search, $sorted);
+ return $groupsArray;
+ }
+
+ /**
+ * Coping with AD not returning the primary group
+ * http://support.microsoft.com/?kbid=321360
+ *
+ * This is a re-write based on code submitted by Bruce which prevents the
+ * need to search each security group to find the true primary group
+ *
+ * @param string $gid Group ID
+ * @param string $usersid User's Object SID
+ * @return mixed
+ */
+ public function getPrimaryGroup($gid, $usersid)
+ {
+ if ($gid === NULL || $usersid === NULL) { return false; }
+ $sr = false;
+
+ $gsid = substr_replace($usersid, pack('V',$gid), strlen($usersid)-4,4);
+ $filter = '(objectsid=' . $this->adldap->utilities()->getTextSID($gsid).')';
+ $fields = array("samaccountname","distinguishedname");
+ $sr = ldap_search($this->adldap->getLdapConnection(), $this->adldap->getBaseDn(), $filter, $fields);
+ $entries = ldap_get_entries($this->adldap->getLdapConnection(), $sr);
+
+ if (isset($entries[0]['distinguishedname'][0])) {
+ return $entries[0]['distinguishedname'][0];
+ }
+ return false;
+ }
+
+ /**
+ * Coping with AD not returning the primary group
+ * http://support.microsoft.com/?kbid=321360
+ *
+ * For some reason it's not possible to search on primarygrouptoken=XXX
+ * If someone can show otherwise, I'd like to know about it :)
+ * this way is resource intensive and generally a pain in the @#%^
+ *
+ * @deprecated deprecated since version 3.1, see get get_primary_group
+ * @param string $gid Group ID
+ * @return string
+ */
+ public function cn($gid){
+ if ($gid === NULL) { return false; }
+ $sr = false;
+ $r = '';
+
+ $filter = "(&(objectCategory=group)(samaccounttype=" . adLDAP::ADLDAP_SECURITY_GLOBAL_GROUP . "))";
+ $fields = array("primarygrouptoken", "samaccountname", "distinguishedname");
+ $sr = ldap_search($this->adldap->getLdapConnection(), $this->adldap->getBaseDn(), $filter, $fields);
+ $entries = ldap_get_entries($this->adldap->getLdapConnection(), $sr);
+
+ for ($i=0; $i<$entries["count"]; $i++){
+ if ($entries[$i]["primarygrouptoken"][0] == $gid) {
+ $r = $entries[$i]["distinguishedname"][0];
+ $i = $entries["count"];
+ }
+ }
+
+ return $r;
+ }
+}
+?>
diff --git a/lib/plugins/authad/adLDAP/classes/adLDAPUsers.php b/lib/plugins/authad/adLDAP/classes/adLDAPUsers.php new file mode 100644 index 000000000..96a93b512 --- /dev/null +++ b/lib/plugins/authad/adLDAP/classes/adLDAPUsers.php @@ -0,0 +1,682 @@ +<?php
+/**
+ * PHP LDAP CLASS FOR MANIPULATING ACTIVE DIRECTORY
+ * Version 4.0.4
+ *
+ * PHP Version 5 with SSL and LDAP support
+ *
+ * Written by Scott Barnett, Richard Hyland
+ * email: scott@wiggumworld.com, adldap@richardhyland.com
+ * http://adldap.sourceforge.net/
+ *
+ * Copyright (c) 2006-2012 Scott Barnett, Richard Hyland
+ *
+ * We'd appreciate any improvements or additions to be submitted back
+ * to benefit the entire community :)
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * @category ToolsAndUtilities
+ * @package adLDAP
+ * @subpackage User
+ * @author Scott Barnett, Richard Hyland
+ * @copyright (c) 2006-2012 Scott Barnett, Richard Hyland
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html LGPLv2.1
+ * @revision $Revision: 97 $
+ * @version 4.0.4
+ * @link http://adldap.sourceforge.net/
+ */
+require_once(dirname(__FILE__) . '/../adLDAP.php');
+require_once(dirname(__FILE__) . '/../collections/adLDAPUserCollection.php');
+
+/**
+* USER FUNCTIONS
+*/
+class adLDAPUsers {
+ /**
+ * The current adLDAP connection via dependency injection
+ *
+ * @var adLDAP
+ */
+ protected $adldap;
+
+ public function __construct(adLDAP $adldap) {
+ $this->adldap = $adldap;
+ }
+
+ /**
+ * Validate a user's login credentials
+ *
+ * @param string $username A user's AD username
+ * @param string $password A user's AD password
+ * @param bool optional $prevent_rebind
+ * @return bool
+ */
+ public function authenticate($username, $password, $preventRebind = false) {
+ return $this->adldap->authenticate($username, $password, $preventRebind);
+ }
+
+ /**
+ * Create a user
+ *
+ * If you specify a password here, this can only be performed over SSL
+ *
+ * @param array $attributes The attributes to set to the user account
+ * @return bool
+ */
+ public function create($attributes)
+ {
+ // Check for compulsory fields
+ if (!array_key_exists("username", $attributes)){ return "Missing compulsory field [username]"; }
+ if (!array_key_exists("firstname", $attributes)){ return "Missing compulsory field [firstname]"; }
+ if (!array_key_exists("surname", $attributes)){ return "Missing compulsory field [surname]"; }
+ if (!array_key_exists("email", $attributes)){ return "Missing compulsory field [email]"; }
+ if (!array_key_exists("container", $attributes)){ return "Missing compulsory field [container]"; }
+ if (!is_array($attributes["container"])){ return "Container attribute must be an array."; }
+
+ if (array_key_exists("password",$attributes) && (!$this->adldap->getUseSSL() && !$this->adldap->getUseTLS())){
+ throw new adLDAPException('SSL must be configured on your webserver and enabled in the class to set passwords.');
+ }
+
+ if (!array_key_exists("display_name", $attributes)) {
+ $attributes["display_name"] = $attributes["firstname"] . " " . $attributes["surname"];
+ }
+
+ // Translate the schema
+ $add = $this->adldap->adldap_schema($attributes);
+
+ // Additional stuff only used for adding accounts
+ $add["cn"][0] = $attributes["display_name"];
+ $add["samaccountname"][0] = $attributes["username"];
+ $add["objectclass"][0] = "top";
+ $add["objectclass"][1] = "person";
+ $add["objectclass"][2] = "organizationalPerson";
+ $add["objectclass"][3] = "user"; //person?
+ //$add["name"][0]=$attributes["firstname"]." ".$attributes["surname"];
+
+ // Set the account control attribute
+ $control_options = array("NORMAL_ACCOUNT");
+ if (!$attributes["enabled"]) {
+ $control_options[] = "ACCOUNTDISABLE";
+ }
+ $add["userAccountControl"][0] = $this->accountControl($control_options);
+
+ // Determine the container
+ $attributes["container"] = array_reverse($attributes["container"]);
+ $container = "OU=" . implode(", OU=",$attributes["container"]);
+
+ // Add the entry
+ $result = @ldap_add($this->adldap->getLdapConnection(), "CN=" . $add["cn"][0] . ", " . $container . "," . $this->adldap->getBaseDn(), $add);
+ if ($result != true) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Account control options
+ *
+ * @param array $options The options to convert to int
+ * @return int
+ */
+ protected function accountControl($options)
+ {
+ $val=0;
+
+ if (is_array($options)) {
+ if (in_array("SCRIPT",$options)){ $val=$val+1; }
+ if (in_array("ACCOUNTDISABLE",$options)){ $val=$val+2; }
+ if (in_array("HOMEDIR_REQUIRED",$options)){ $val=$val+8; }
+ if (in_array("LOCKOUT",$options)){ $val=$val+16; }
+ if (in_array("PASSWD_NOTREQD",$options)){ $val=$val+32; }
+ //PASSWD_CANT_CHANGE Note You cannot assign this permission by directly modifying the UserAccountControl attribute.
+ //For information about how to set the permission programmatically, see the "Property flag descriptions" section.
+ if (in_array("ENCRYPTED_TEXT_PWD_ALLOWED",$options)){ $val=$val+128; }
+ if (in_array("TEMP_DUPLICATE_ACCOUNT",$options)){ $val=$val+256; }
+ if (in_array("NORMAL_ACCOUNT",$options)){ $val=$val+512; }
+ if (in_array("INTERDOMAIN_TRUST_ACCOUNT",$options)){ $val=$val+2048; }
+ if (in_array("WORKSTATION_TRUST_ACCOUNT",$options)){ $val=$val+4096; }
+ if (in_array("SERVER_TRUST_ACCOUNT",$options)){ $val=$val+8192; }
+ if (in_array("DONT_EXPIRE_PASSWORD",$options)){ $val=$val+65536; }
+ if (in_array("MNS_LOGON_ACCOUNT",$options)){ $val=$val+131072; }
+ if (in_array("SMARTCARD_REQUIRED",$options)){ $val=$val+262144; }
+ if (in_array("TRUSTED_FOR_DELEGATION",$options)){ $val=$val+524288; }
+ if (in_array("NOT_DELEGATED",$options)){ $val=$val+1048576; }
+ if (in_array("USE_DES_KEY_ONLY",$options)){ $val=$val+2097152; }
+ if (in_array("DONT_REQ_PREAUTH",$options)){ $val=$val+4194304; }
+ if (in_array("PASSWORD_EXPIRED",$options)){ $val=$val+8388608; }
+ if (in_array("TRUSTED_TO_AUTH_FOR_DELEGATION",$options)){ $val=$val+16777216; }
+ }
+ return $val;
+ }
+
+ /**
+ * Delete a user account
+ *
+ * @param string $username The username to delete (please be careful here!)
+ * @param bool $isGUID Is the username a GUID or a samAccountName
+ * @return array
+ */
+ public function delete($username, $isGUID = false)
+ {
+ $userinfo = $this->info($username, array("*"), $isGUID);
+ $dn = $userinfo[0]['distinguishedname'][0];
+ $result = $this->adldap->folder()->delete($dn);
+ if ($result != true) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Groups the user is a member of
+ *
+ * @param string $username The username to query
+ * @param bool $recursive Recursive list of groups
+ * @param bool $isGUID Is the username passed a GUID or a samAccountName
+ * @return array
+ */
+ public function groups($username, $recursive = NULL, $isGUID = false)
+ {
+ if ($username === NULL) { return false; }
+ if ($recursive === NULL) { $recursive = $this->adldap->getRecursiveGroups(); } // Use the default option if they haven't set it
+ if (!$this->adldap->getLdapBind()) { return false; }
+
+ // Search the directory for their information
+ $info = @$this->info($username, array("memberof", "primarygroupid"), $isGUID);
+ $groups = $this->adldap->utilities()->niceNames($info[0]["memberof"]); // Presuming the entry returned is our guy (unique usernames)
+
+ if ($recursive === true){
+ foreach ($groups as $id => $groupName){
+ $extraGroups = $this->adldap->group()->recursiveGroups($groupName);
+ $groups = array_merge($groups, $extraGroups);
+ }
+ }
+
+ return $groups;
+ }
+
+ /**
+ * Find information about the users. Returned in a raw array format from AD
+ *
+ * @param string $username The username to query
+ * @param array $fields Array of parameters to query
+ * @param bool $isGUID Is the username passed a GUID or a samAccountName
+ * @return array
+ */
+ public function info($username, $fields = NULL, $isGUID = false)
+ {
+ if ($username === NULL) { return false; }
+ if (!$this->adldap->getLdapBind()) { return false; }
+
+ if ($isGUID === true) {
+ $username = $this->adldap->utilities()->strGuidToHex($username);
+ $filter = "objectguid=" . $username;
+ }
+ else if (strstr($username, "@")) {
+ $filter = "userPrincipalName=" . $username;
+ }
+ else {
+ $filter = "samaccountname=" . $username;
+ }
+ $filter = "(&(objectCategory=person)({$filter}))";
+ if ($fields === NULL) {
+ $fields = array("samaccountname","mail","memberof","department","displayname","telephonenumber","primarygroupid","objectsid");
+ }
+ if (!in_array("objectsid", $fields)) {
+ $fields[] = "objectsid";
+ }
+ $sr = ldap_search($this->adldap->getLdapConnection(), $this->adldap->getBaseDn(), $filter, $fields);
+ $entries = ldap_get_entries($this->adldap->getLdapConnection(), $sr);
+
+ if (isset($entries[0])) {
+ if ($entries[0]['count'] >= 1) {
+ if (in_array("memberof", $fields)) {
+ // AD does not return the primary group in the ldap query, we may need to fudge it
+ if ($this->adldap->getRealPrimaryGroup() && isset($entries[0]["primarygroupid"][0]) && isset($entries[0]["objectsid"][0])){
+ //$entries[0]["memberof"][]=$this->group_cn($entries[0]["primarygroupid"][0]);
+ $entries[0]["memberof"][] = $this->adldap->group()->getPrimaryGroup($entries[0]["primarygroupid"][0], $entries[0]["objectsid"][0]);
+ } else {
+ $entries[0]["memberof"][] = "CN=Domain Users,CN=Users," . $this->adldap->getBaseDn();
+ }
+ if (!isset($entries[0]["memberof"]["count"])) {
+ $entries[0]["memberof"]["count"] = 0;
+ }
+ $entries[0]["memberof"]["count"]++;
+ }
+ }
+
+ return $entries;
+ }
+ return false;
+ }
+
+ /**
+ * Find information about the users. Returned in a raw array format from AD
+ *
+ * @param string $username The username to query
+ * @param array $fields Array of parameters to query
+ * @param bool $isGUID Is the username passed a GUID or a samAccountName
+ * @return mixed
+ */
+ public function infoCollection($username, $fields = NULL, $isGUID = false)
+ {
+ if ($username === NULL) { return false; }
+ if (!$this->adldap->getLdapBind()) { return false; }
+
+ $info = $this->info($username, $fields, $isGUID);
+
+ if ($info !== false) {
+ $collection = new adLDAPUserCollection($info, $this->adldap);
+ return $collection;
+ }
+ return false;
+ }
+
+ /**
+ * Determine if a user is in a specific group
+ *
+ * @param string $username The username to query
+ * @param string $group The name of the group to check against
+ * @param bool $recursive Check groups recursively
+ * @param bool $isGUID Is the username passed a GUID or a samAccountName
+ * @return bool
+ */
+ public function inGroup($username, $group, $recursive = NULL, $isGUID = false)
+ {
+ if ($username === NULL) { return false; }
+ if ($group === NULL) { return false; }
+ if (!$this->adldap->getLdapBind()) { return false; }
+ if ($recursive === NULL) { $recursive = $this->adldap->getRecursiveGroups(); } // Use the default option if they haven't set it
+
+ // Get a list of the groups
+ $groups = $this->groups($username, $recursive, $isGUID);
+
+ // Return true if the specified group is in the group list
+ if (in_array($group, $groups)) {
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Determine a user's password expiry date
+ *
+ * @param string $username The username to query
+ * @param book $isGUID Is the username passed a GUID or a samAccountName
+ * @requires bcmath http://www.php.net/manual/en/book.bc.php
+ * @return array
+ */
+ public function passwordExpiry($username, $isGUID = false)
+ {
+ if ($username === NULL) { return "Missing compulsory field [username]"; }
+ if (!$this->adldap->getLdapBind()) { return false; }
+ if (!function_exists('bcmod')) { throw new adLDAPException("Missing function support [bcmod] http://www.php.net/manual/en/book.bc.php"); };
+
+ $userInfo = $this->info($username, array("pwdlastset", "useraccountcontrol"), $isGUID);
+ $pwdLastSet = $userInfo[0]['pwdlastset'][0];
+ $status = array();
+
+ if ($userInfo[0]['useraccountcontrol'][0] == '66048') {
+ // Password does not expire
+ return "Does not expire";
+ }
+ if ($pwdLastSet === '0') {
+ // Password has already expired
+ return "Password has expired";
+ }
+
+ // Password expiry in AD can be calculated from TWO values:
+ // - User's own pwdLastSet attribute: stores the last time the password was changed
+ // - Domain's maxPwdAge attribute: how long passwords last in the domain
+ //
+ // Although Microsoft chose to use a different base and unit for time measurements.
+ // This function will convert them to Unix timestamps
+ $sr = ldap_read($this->adldap->getLdapConnection(), $this->adldap->getBaseDn(), 'objectclass=*', array('maxPwdAge'));
+ if (!$sr) {
+ return false;
+ }
+ $info = ldap_get_entries($this->adldap->getLdapConnection(), $sr);
+ $maxPwdAge = $info[0]['maxpwdage'][0];
+
+
+ // See MSDN: http://msdn.microsoft.com/en-us/library/ms974598.aspx
+ //
+ // pwdLastSet contains the number of 100 nanosecond intervals since January 1, 1601 (UTC),
+ // stored in a 64 bit integer.
+ //
+ // The number of seconds between this date and Unix epoch is 11644473600.
+ //
+ // maxPwdAge is stored as a large integer that represents the number of 100 nanosecond
+ // intervals from the time the password was set before the password expires.
+ //
+ // We also need to scale this to seconds but also this value is a _negative_ quantity!
+ //
+ // If the low 32 bits of maxPwdAge are equal to 0 passwords do not expire
+ //
+ // Unfortunately the maths involved are too big for PHP integers, so I've had to require
+ // BCMath functions to work with arbitrary precision numbers.
+ if (bcmod($maxPwdAge, 4294967296) === '0') {
+ return "Domain does not expire passwords";
+ }
+
+ // Add maxpwdage and pwdlastset and we get password expiration time in Microsoft's
+ // time units. Because maxpwd age is negative we need to subtract it.
+ $pwdExpire = bcsub($pwdLastSet, $maxPwdAge);
+
+ // Convert MS's time to Unix time
+ $status['expiryts'] = bcsub(bcdiv($pwdExpire, '10000000'), '11644473600');
+ $status['expiryformat'] = date('Y-m-d H:i:s', bcsub(bcdiv($pwdExpire, '10000000'), '11644473600'));
+
+ return $status;
+ }
+
+ /**
+ * Modify a user
+ *
+ * @param string $username The username to query
+ * @param array $attributes The attributes to modify. Note if you set the enabled attribute you must not specify any other attributes
+ * @param bool $isGUID Is the username passed a GUID or a samAccountName
+ * @return bool
+ */
+ public function modify($username, $attributes, $isGUID = false)
+ {
+ if ($username === NULL) { return "Missing compulsory field [username]"; }
+ if (array_key_exists("password", $attributes) && !$this->adldap->getUseSSL() && !$this->adldap->getUseTLS()) {
+ throw new adLDAPException('SSL/TLS must be configured on your webserver and enabled in the class to set passwords.');
+ }
+
+ // Find the dn of the user
+ $userDn = $this->dn($username, $isGUID);
+ if ($userDn === false) {
+ return false;
+ }
+
+ // Translate the update to the LDAP schema
+ $mod = $this->adldap->adldap_schema($attributes);
+
+ // Check to see if this is an enabled status update
+ if (!$mod && !array_key_exists("enabled", $attributes)){
+ return false;
+ }
+
+ // Set the account control attribute (only if specified)
+ if (array_key_exists("enabled", $attributes)){
+ if ($attributes["enabled"]){
+ $controlOptions = array("NORMAL_ACCOUNT");
+ }
+ else {
+ $controlOptions = array("NORMAL_ACCOUNT", "ACCOUNTDISABLE");
+ }
+ $mod["userAccountControl"][0] = $this->accountControl($controlOptions);
+ }
+
+ // Do the update
+ $result = @ldap_modify($this->adldap->getLdapConnection(), $userDn, $mod);
+ if ($result == false) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Disable a user account
+ *
+ * @param string $username The username to disable
+ * @param bool $isGUID Is the username passed a GUID or a samAccountName
+ * @return bool
+ */
+ public function disable($username, $isGUID = false)
+ {
+ if ($username === NULL) { return "Missing compulsory field [username]"; }
+ $attributes = array("enabled" => 0);
+ $result = $this->modify($username, $attributes, $isGUID);
+ if ($result == false) { return false; }
+
+ return true;
+ }
+
+ /**
+ * Enable a user account
+ *
+ * @param string $username The username to enable
+ * @param bool $isGUID Is the username passed a GUID or a samAccountName
+ * @return bool
+ */
+ public function enable($username, $isGUID = false)
+ {
+ if ($username === NULL) { return "Missing compulsory field [username]"; }
+ $attributes = array("enabled" => 1);
+ $result = $this->modify($username, $attributes, $isGUID);
+ if ($result == false) { return false; }
+
+ return true;
+ }
+
+ /**
+ * Set the password of a user - This must be performed over SSL
+ *
+ * @param string $username The username to modify
+ * @param string $password The new password
+ * @param bool $isGUID Is the username passed a GUID or a samAccountName
+ * @return bool
+ */
+ public function password($username, $password, $isGUID = false)
+ {
+ if ($username === NULL) { return false; }
+ if ($password === NULL) { return false; }
+ if (!$this->adldap->getLdapBind()) { return false; }
+ if (!$this->adldap->getUseSSL() && !$this->adldap->getUseTLS()) {
+ throw new adLDAPException('SSL must be configured on your webserver and enabled in the class to set passwords.');
+ }
+
+ $userDn = $this->dn($username, $isGUID);
+ if ($userDn === false) {
+ return false;
+ }
+
+ $add=array();
+ $add["unicodePwd"][0] = $this->encodePassword($password);
+
+ $result = @ldap_mod_replace($this->adldap->getLdapConnection(), $userDn, $add);
+ if ($result === false){
+ $err = ldap_errno($this->adldap->getLdapConnection());
+ if ($err) {
+ $msg = 'Error ' . $err . ': ' . ldap_err2str($err) . '.';
+ if($err == 53) {
+ $msg .= ' Your password might not match the password policy.';
+ }
+ throw new adLDAPException($msg);
+ }
+ else {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * Encode a password for transmission over LDAP
+ *
+ * @param string $password The password to encode
+ * @return string
+ */
+ public function encodePassword($password)
+ {
+ $password="\"".$password."\"";
+ $encoded="";
+ for ($i=0; $i <strlen($password); $i++){ $encoded.="{$password{$i}}\000"; }
+ return $encoded;
+ }
+
+ /**
+ * Obtain the user's distinguished name based on their userid
+ *
+ *
+ * @param string $username The username
+ * @param bool $isGUID Is the username passed a GUID or a samAccountName
+ * @return string
+ */
+ public function dn($username, $isGUID=false)
+ {
+ $user = $this->info($username, array("cn"), $isGUID);
+ if ($user[0]["dn"] === NULL) {
+ return false;
+ }
+ $userDn = $user[0]["dn"];
+ return $userDn;
+ }
+
+ /**
+ * Return a list of all users in AD
+ *
+ * @param bool $includeDescription Return a description of the user
+ * @param string $search Search parameter
+ * @param bool $sorted Sort the user accounts
+ * @return array
+ */
+ public function all($includeDescription = false, $search = "*", $sorted = true)
+ {
+ if (!$this->adldap->getLdapBind()) { return false; }
+
+ // Perform the search and grab all their details
+ $filter = "(&(objectClass=user)(samaccounttype=" . adLDAP::ADLDAP_NORMAL_ACCOUNT .")(objectCategory=person)(cn=" . $search . "))";
+ $fields = array("samaccountname","displayname");
+ $sr = ldap_search($this->adldap->getLdapConnection(), $this->adldap->getBaseDn(), $filter, $fields);
+ $entries = ldap_get_entries($this->adldap->getLdapConnection(), $sr);
+
+ $usersArray = array();
+ for ($i=0; $i<$entries["count"]; $i++){
+ if ($includeDescription && strlen($entries[$i]["displayname"][0])>0){
+ $usersArray[$entries[$i]["samaccountname"][0]] = $entries[$i]["displayname"][0];
+ } elseif ($includeDescription){
+ $usersArray[$entries[$i]["samaccountname"][0]] = $entries[$i]["samaccountname"][0];
+ } else {
+ array_push($usersArray, $entries[$i]["samaccountname"][0]);
+ }
+ }
+ if ($sorted) {
+ asort($usersArray);
+ }
+ return $usersArray;
+ }
+
+ /**
+ * Converts a username (samAccountName) to a GUID
+ *
+ * @param string $username The username to query
+ * @return string
+ */
+ public function usernameToGuid($username)
+ {
+ if (!$this->adldap->getLdapBind()){ return false; }
+ if ($username === null){ return "Missing compulsory field [username]"; }
+
+ $filter = "samaccountname=" . $username;
+ $fields = array("objectGUID");
+ $sr = @ldap_search($this->adldap->getLdapConnection(), $this->adldap->getBaseDn(), $filter, $fields);
+ if (ldap_count_entries($this->adldap->getLdapConnection(), $sr) > 0) {
+ $entry = @ldap_first_entry($this->adldap->getLdapConnection(), $sr);
+ $guid = @ldap_get_values_len($this->adldap->getLdapConnection(), $entry, 'objectGUID');
+ $strGUID = $this->adldap->utilities()->binaryToText($guid[0]);
+ return $strGUID;
+ }
+ return false;
+ }
+
+ /**
+ * Return a list of all users in AD that have a specific value in a field
+ *
+ * @param bool $includeDescription Return a description of the user
+ * @param string $searchField Field to search search for
+ * @param string $searchFilter Value to search for in the specified field
+ * @param bool $sorted Sort the user accounts
+ * @return array
+ */
+ public function find($includeDescription = false, $searchField = false, $searchFilter = false, $sorted = true){
+ if (!$this->adldap->getLdapBind()){ return false; }
+
+ // Perform the search and grab all their details
+ $searchParams = "";
+ if ($searchField) {
+ $searchParams = "(" . $searchField . "=" . $searchFilter . ")";
+ }
+ $filter = "(&(objectClass=user)(samaccounttype=" . adLDAP::ADLDAP_NORMAL_ACCOUNT .")(objectCategory=person)" . $searchParams . ")";
+ $fields = array("samaccountname","displayname");
+ $sr = ldap_search($this->adldap->getLdapConnection(), $this->adldap->getBaseDn(), $filter, $fields);
+ $entries = ldap_get_entries($this->adldap->getLdapConnection(), $sr);
+
+ $usersArray = array();
+ for ($i=0; $i < $entries["count"]; $i++) {
+ if ($includeDescription && strlen($entries[$i]["displayname"][0]) > 0) {
+ $usersArray[$entries[$i]["samaccountname"][0]] = $entries[$i]["displayname"][0];
+ }
+ else if ($includeDescription) {
+ $usersArray[$entries[$i]["samaccountname"][0]] = $entries[$i]["samaccountname"][0];
+ }
+ else {
+ array_push($usersArray, $entries[$i]["samaccountname"][0]);
+ }
+ }
+ if ($sorted){
+ asort($usersArray);
+ }
+ return ($usersArray);
+ }
+
+ /**
+ * Move a user account to a different OU
+ *
+ * @param string $username The username to move (please be careful here!)
+ * @param array $container The container or containers to move the user to (please be careful here!).
+ * accepts containers in 1. parent 2. child order
+ * @return array
+ */
+ public function move($username, $container)
+ {
+ if (!$this->adldap->getLdapBind()) { return false; }
+ if ($username === null) { return "Missing compulsory field [username]"; }
+ if ($container === null) { return "Missing compulsory field [container]"; }
+ if (!is_array($container)) { return "Container must be an array"; }
+
+ $userInfo = $this->info($username, array("*"));
+ $dn = $userInfo[0]['distinguishedname'][0];
+ $newRDn = "cn=" . $username;
+ $container = array_reverse($container);
+ $newContainer = "ou=" . implode(",ou=",$container);
+ $newBaseDn = strtolower($newContainer) . "," . $this->adldap->getBaseDn();
+ $result = @ldap_rename($this->adldap->getLdapConnection(), $dn, $newRDn, $newBaseDn, true);
+ if ($result !== true) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Get the last logon time of any user as a Unix timestamp
+ *
+ * @param string $username
+ * @return long $unixTimestamp
+ */
+ public function getLastLogon($username) {
+ if (!$this->adldap->getLdapBind()) { return false; }
+ if ($username === null) { return "Missing compulsory field [username]"; }
+ $userInfo = $this->info($username, array("lastLogonTimestamp"));
+ $lastLogon = adLDAPUtils::convertWindowsTimeToUnixTime($userInfo[0]['lastLogonTimestamp'][0]);
+ return $lastLogon;
+ }
+
+}
+?>
diff --git a/lib/plugins/authad/adLDAP/classes/adLDAPUtils.php b/lib/plugins/authad/adLDAP/classes/adLDAPUtils.php new file mode 100644 index 000000000..f039a4290 --- /dev/null +++ b/lib/plugins/authad/adLDAP/classes/adLDAPUtils.php @@ -0,0 +1,264 @@ +<?php
+/**
+ * PHP LDAP CLASS FOR MANIPULATING ACTIVE DIRECTORY
+ * Version 4.0.4
+ *
+ * PHP Version 5 with SSL and LDAP support
+ *
+ * Written by Scott Barnett, Richard Hyland
+ * email: scott@wiggumworld.com, adldap@richardhyland.com
+ * http://adldap.sourceforge.net/
+ *
+ * Copyright (c) 2006-2012 Scott Barnett, Richard Hyland
+ *
+ * We'd appreciate any improvements or additions to be submitted back
+ * to benefit the entire community :)
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * @category ToolsAndUtilities
+ * @package adLDAP
+ * @subpackage Utils
+ * @author Scott Barnett, Richard Hyland
+ * @copyright (c) 2006-2012 Scott Barnett, Richard Hyland
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html LGPLv2.1
+ * @revision $Revision: 97 $
+ * @version 4.0.4
+ * @link http://adldap.sourceforge.net/
+ */
+require_once(dirname(__FILE__) . '/../adLDAP.php');
+
+/**
+* UTILITY FUNCTIONS
+*/
+class adLDAPUtils {
+ const ADLDAP_VERSION = '4.0.4';
+
+ /**
+ * The current adLDAP connection via dependency injection
+ *
+ * @var adLDAP
+ */
+ protected $adldap;
+
+ public function __construct(adLDAP $adldap) {
+ $this->adldap = $adldap;
+ }
+
+
+ /**
+ * Take an LDAP query and return the nice names, without all the LDAP prefixes (eg. CN, DN)
+ *
+ * @param array $groups
+ * @return array
+ */
+ public function niceNames($groups)
+ {
+
+ $groupArray = array();
+ for ($i=0; $i<$groups["count"]; $i++){ // For each group
+ $line = $groups[$i];
+
+ if (strlen($line)>0) {
+ // More presumptions, they're all prefixed with CN=
+ // so we ditch the first three characters and the group
+ // name goes up to the first comma
+ $bits=explode(",", $line);
+ $groupArray[] = substr($bits[0], 3, (strlen($bits[0])-3));
+ }
+ }
+ return $groupArray;
+ }
+
+ /**
+ * Escape characters for use in an ldap_create function
+ *
+ * @param string $str
+ * @return string
+ */
+ public function escapeCharacters($str) {
+ $str = str_replace(",", "\,", $str);
+ return $str;
+ }
+
+ /**
+ * Escape strings for the use in LDAP filters
+ *
+ * DEVELOPERS SHOULD BE DOING PROPER FILTERING IF THEY'RE ACCEPTING USER INPUT
+ * Ported from Perl's Net::LDAP::Util escape_filter_value
+ *
+ * @param string $str The string the parse
+ * @author Port by Andreas Gohr <andi@splitbrain.org>
+ * @return string
+ */
+ public function ldapSlashes($str){
+ return preg_replace('/([\x00-\x1F\*\(\)\\\\])/e',
+ '"\\\\\".join("",unpack("H2","$1"))',
+ $str);
+ }
+
+ /**
+ * Converts a string GUID to a hexdecimal value so it can be queried
+ *
+ * @param string $strGUID A string representation of a GUID
+ * @return string
+ */
+ public function strGuidToHex($strGUID)
+ {
+ $strGUID = str_replace('-', '', $strGUID);
+
+ $octet_str = '\\' . substr($strGUID, 6, 2);
+ $octet_str .= '\\' . substr($strGUID, 4, 2);
+ $octet_str .= '\\' . substr($strGUID, 2, 2);
+ $octet_str .= '\\' . substr($strGUID, 0, 2);
+ $octet_str .= '\\' . substr($strGUID, 10, 2);
+ $octet_str .= '\\' . substr($strGUID, 8, 2);
+ $octet_str .= '\\' . substr($strGUID, 14, 2);
+ $octet_str .= '\\' . substr($strGUID, 12, 2);
+ //$octet_str .= '\\' . substr($strGUID, 16, strlen($strGUID));
+ for ($i=16; $i<=(strlen($strGUID)-2); $i++) {
+ if (($i % 2) == 0) {
+ $octet_str .= '\\' . substr($strGUID, $i, 2);
+ }
+ }
+
+ return $octet_str;
+ }
+
+ /**
+ * Convert a binary SID to a text SID
+ *
+ * @param string $binsid A Binary SID
+ * @return string
+ */
+ public function getTextSID($binsid) {
+ $hex_sid = bin2hex($binsid);
+ $rev = hexdec(substr($hex_sid, 0, 2));
+ $subcount = hexdec(substr($hex_sid, 2, 2));
+ $auth = hexdec(substr($hex_sid, 4, 12));
+ $result = "$rev-$auth";
+
+ for ($x=0;$x < $subcount; $x++) {
+ $subauth[$x] =
+ hexdec($this->littleEndian(substr($hex_sid, 16 + ($x * 8), 8)));
+ $result .= "-" . $subauth[$x];
+ }
+
+ // Cheat by tacking on the S-
+ return 'S-' . $result;
+ }
+
+ /**
+ * Converts a little-endian hex number to one that hexdec() can convert
+ *
+ * @param string $hex A hex code
+ * @return string
+ */
+ public function littleEndian($hex)
+ {
+ $result = '';
+ for ($x = strlen($hex) - 2; $x >= 0; $x = $x - 2) {
+ $result .= substr($hex, $x, 2);
+ }
+ return $result;
+ }
+
+ /**
+ * Converts a binary attribute to a string
+ *
+ * @param string $bin A binary LDAP attribute
+ * @return string
+ */
+ public function binaryToText($bin)
+ {
+ $hex_guid = bin2hex($bin);
+ $hex_guid_to_guid_str = '';
+ for($k = 1; $k <= 4; ++$k) {
+ $hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
+ }
+ $hex_guid_to_guid_str .= '-';
+ for($k = 1; $k <= 2; ++$k) {
+ $hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
+ }
+ $hex_guid_to_guid_str .= '-';
+ for($k = 1; $k <= 2; ++$k) {
+ $hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
+ }
+ $hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
+ $hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);
+ return strtoupper($hex_guid_to_guid_str);
+ }
+
+ /**
+ * Converts a binary GUID to a string GUID
+ *
+ * @param string $binaryGuid The binary GUID attribute to convert
+ * @return string
+ */
+ public function decodeGuid($binaryGuid)
+ {
+ if ($binaryGuid === null){ return "Missing compulsory field [binaryGuid]"; }
+
+ $strGUID = $this->binaryToText($binaryGuid);
+ return $strGUID;
+ }
+
+ /**
+ * Convert a boolean value to a string
+ * You should never need to call this yourself
+ *
+ * @param bool $bool Boolean value
+ * @return string
+ */
+ public function boolToStr($bool)
+ {
+ return ($bool) ? 'TRUE' : 'FALSE';
+ }
+
+ /**
+ * Convert 8bit characters e.g. accented characters to UTF8 encoded characters
+ */
+ public function encode8Bit(&$item, $key) {
+ $encode = false;
+ if (is_string($item)) {
+ for ($i=0; $i<strlen($item); $i++) {
+ if (ord($item[$i]) >> 7) {
+ $encode = true;
+ }
+ }
+ }
+ if ($encode === true && $key != 'password') {
+ $item = utf8_encode($item);
+ }
+ }
+
+ /**
+ * Get the current class version number
+ *
+ * @return string
+ */
+ public function getVersion() {
+ return self::ADLDAP_VERSION;
+ }
+
+ /**
+ * Round a Windows timestamp down to seconds and remove the seconds between 1601-01-01 and 1970-01-01
+ *
+ * @param long $windowsTime
+ * @return long $unixTime
+ */
+ public static function convertWindowsTimeToUnixTime($windowsTime) {
+ $unixTime = round($windowsTime / 10000000) - 11644477200;
+ return $unixTime;
+ }
+}
+
+?>
\ No newline at end of file diff --git a/lib/plugins/authad/adLDAP/collections/adLDAPCollection.php b/lib/plugins/authad/adLDAP/collections/adLDAPCollection.php new file mode 100644 index 000000000..c0a2eb2fa --- /dev/null +++ b/lib/plugins/authad/adLDAP/collections/adLDAPCollection.php @@ -0,0 +1,137 @@ +<?php
+/**
+ * PHP LDAP CLASS FOR MANIPULATING ACTIVE DIRECTORY
+ * Version 4.0.4
+ *
+ * PHP Version 5 with SSL and LDAP support
+ *
+ * Written by Scott Barnett, Richard Hyland
+ * email: scott@wiggumworld.com, adldap@richardhyland.com
+ * http://adldap.sourceforge.net/
+ *
+ * Copyright (c) 2006-2012 Scott Barnett, Richard Hyland
+ *
+ * We'd appreciate any improvements or additions to be submitted back
+ * to benefit the entire community :)
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * @category ToolsAndUtilities
+ * @package adLDAP
+ * @subpackage Collection
+ * @author Scott Barnett, Richard Hyland
+ * @copyright (c) 2006-2012 Scott Barnett, Richard Hyland
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html LGPLv2.1
+ * @revision $Revision: 97 $
+ * @version 4.0.4
+ * @link http://adldap.sourceforge.net/
+*/
+
+abstract class adLDAPCollection
+{
+ /**
+ * The current adLDAP connection via dependency injection
+ *
+ * @var adLDAP
+ */
+ protected $adldap;
+
+ /**
+ * The current object being modifed / called
+ *
+ * @var mixed
+ */
+ protected $currentObject;
+
+ /**
+ * The raw info array from Active Directory
+ *
+ * @var array
+ */
+ protected $info;
+
+ public function __construct($info, adLDAP $adldap)
+ {
+ $this->setInfo($info);
+ $this->adldap = $adldap;
+ }
+
+ /**
+ * Set the raw info array from Active Directory
+ *
+ * @param array $info
+ */
+ public function setInfo(array $info)
+ {
+ if ($this->info && sizeof($info) >= 1) {
+ unset($this->info);
+ }
+ $this->info = $info;
+ }
+
+ /**
+ * Magic get method to retrieve data from the raw array in a formatted way
+ *
+ * @param string $attribute
+ * @return mixed
+ */
+ public function __get($attribute)
+ {
+ if (isset($this->info[0]) && is_array($this->info[0])) {
+ foreach ($this->info[0] as $keyAttr => $valueAttr) {
+ if (strtolower($keyAttr) == strtolower($attribute)) {
+ if ($this->info[0][strtolower($attribute)]['count'] == 1) {
+ return $this->info[0][strtolower($attribute)][0];
+ }
+ else {
+ $array = array();
+ foreach ($this->info[0][strtolower($attribute)] as $key => $value) {
+ if ((string)$key != 'count') {
+ $array[$key] = $value;
+ }
+ }
+ return $array;
+ }
+ }
+ }
+ }
+ else {
+ return NULL;
+ }
+ }
+
+ /**
+ * Magic set method to update an attribute
+ *
+ * @param string $attribute
+ * @param string $value
+ * @return bool
+ */
+ abstract public function __set($attribute, $value);
+
+ /**
+ * Magic isset method to check for the existence of an attribute
+ *
+ * @param string $attribute
+ * @return bool
+ */
+ public function __isset($attribute) {
+ if (isset($this->info[0]) && is_array($this->info[0])) {
+ foreach ($this->info[0] as $keyAttr => $valueAttr) {
+ if (strtolower($keyAttr) == strtolower($attribute)) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+}
+?>
diff --git a/lib/plugins/authad/adLDAP/collections/adLDAPComputerCollection.php b/lib/plugins/authad/adLDAP/collections/adLDAPComputerCollection.php new file mode 100644 index 000000000..4f11d8f41 --- /dev/null +++ b/lib/plugins/authad/adLDAP/collections/adLDAPComputerCollection.php @@ -0,0 +1,46 @@ +<?php
+/**
+ * PHP LDAP CLASS FOR MANIPULATING ACTIVE DIRECTORY
+ * Version 4.0.4
+ *
+ * PHP Version 5 with SSL and LDAP support
+ *
+ * Written by Scott Barnett, Richard Hyland
+ * email: scott@wiggumworld.com, adldap@richardhyland.com
+ * http://adldap.sourceforge.net/
+ *
+ * Copyright (c) 2006-2012 Scott Barnett, Richard Hyland
+ *
+ * We'd appreciate any improvements or additions to be submitted back
+ * to benefit the entire community :)
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * @category ToolsAndUtilities
+ * @package adLDAP
+ * @subpackage ComputerCollection
+ * @author Scott Barnett, Richard Hyland
+ * @copyright (c) 2006-2012 Scott Barnett, Richard Hyland
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html LGPLv2.1
+ * @revision $Revision: 97 $
+ * @version 4.0.4
+ * @link http://adldap.sourceforge.net/
+*/
+
+class adLDAPComputerCollection extends adLDAPCollection
+{
+
+ public function __set($attribute, $value)
+ {
+
+ }
+}
+?>
diff --git a/lib/plugins/authad/adLDAP/collections/adLDAPContactCollection.php b/lib/plugins/authad/adLDAP/collections/adLDAPContactCollection.php new file mode 100644 index 000000000..d42fe6d4c --- /dev/null +++ b/lib/plugins/authad/adLDAP/collections/adLDAPContactCollection.php @@ -0,0 +1,46 @@ +<?php
+/**
+ * PHP LDAP CLASS FOR MANIPULATING ACTIVE DIRECTORY
+ * Version 4.0.4
+ *
+ * PHP Version 5 with SSL and LDAP support
+ *
+ * Written by Scott Barnett, Richard Hyland
+ * email: scott@wiggumworld.com, adldap@richardhyland.com
+ * http://adldap.sourceforge.net/
+ *
+ * Copyright (c) 2006-2012 Scott Barnett, Richard Hyland
+ *
+ * We'd appreciate any improvements or additions to be submitted back
+ * to benefit the entire community :)
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * @category ToolsAndUtilities
+ * @package adLDAP
+ * @subpackage ContactCollection
+ * @author Scott Barnett, Richard Hyland
+ * @copyright (c) 2006-2012 Scott Barnett, Richard Hyland
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html LGPLv2.1
+ * @revision $Revision: 97 $
+ * @version 4.0.4
+ * @link http://adldap.sourceforge.net/
+*/
+
+class adLDAPContactCollection extends adLDAPCollection
+{
+
+ public function __set($attribute, $value)
+ {
+
+ }
+}
+?>
diff --git a/lib/plugins/authad/adLDAP/collections/adLDAPGroupCollection.php b/lib/plugins/authad/adLDAP/collections/adLDAPGroupCollection.php new file mode 100644 index 000000000..cff12fc20 --- /dev/null +++ b/lib/plugins/authad/adLDAP/collections/adLDAPGroupCollection.php @@ -0,0 +1,46 @@ +<?php
+/**
+ * PHP LDAP CLASS FOR MANIPULATING ACTIVE DIRECTORY
+ * Version 4.0.4
+ *
+ * PHP Version 5 with SSL and LDAP support
+ *
+ * Written by Scott Barnett, Richard Hyland
+ * email: scott@wiggumworld.com, adldap@richardhyland.com
+ * http://adldap.sourceforge.net/
+ *
+ * Copyright (c) 2006-2012 Scott Barnett, Richard Hyland
+ *
+ * We'd appreciate any improvements or additions to be submitted back
+ * to benefit the entire community :)
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * @category ToolsAndUtilities
+ * @package adLDAP
+ * @subpackage GroupCollection
+ * @author Scott Barnett, Richard Hyland
+ * @copyright (c) 2006-2012 Scott Barnett, Richard Hyland
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html LGPLv2.1
+ * @revision $Revision: 97 $
+ * @version 4.0.4
+ * @link http://adldap.sourceforge.net/
+*/
+
+class adLDAPGroupCollection extends adLDAPCollection
+{
+
+ public function __set($attribute, $value)
+ {
+
+ }
+}
+?>
diff --git a/lib/plugins/authad/adLDAP/collections/adLDAPUserCollection.php b/lib/plugins/authad/adLDAP/collections/adLDAPUserCollection.php new file mode 100644 index 000000000..801d90296 --- /dev/null +++ b/lib/plugins/authad/adLDAP/collections/adLDAPUserCollection.php @@ -0,0 +1,46 @@ +<?php
+/**
+ * PHP LDAP CLASS FOR MANIPULATING ACTIVE DIRECTORY
+ * Version 4.0.4
+ *
+ * PHP Version 5 with SSL and LDAP support
+ *
+ * Written by Scott Barnett, Richard Hyland
+ * email: scott@wiggumworld.com, adldap@richardhyland.com
+ * http://adldap.sourceforge.net/
+ *
+ * Copyright (c) 2006-2012 Scott Barnett, Richard Hyland
+ *
+ * We'd appreciate any improvements or additions to be submitted back
+ * to benefit the entire community :)
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * @category ToolsAndUtilities
+ * @package adLDAP
+ * @subpackage UserCollection
+ * @author Scott Barnett, Richard Hyland
+ * @copyright (c) 2006-2012 Scott Barnett, Richard Hyland
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html LGPLv2.1
+ * @revision $Revision: 97 $
+ * @version 4.0.4
+ * @link http://adldap.sourceforge.net/
+*/
+
+class adLDAPUserCollection extends adLDAPCollection
+{
+
+ public function __set($attribute, $value)
+ {
+
+ }
+}
+?>
diff --git a/lib/plugins/authad/auth.php b/lib/plugins/authad/auth.php new file mode 100644 index 000000000..f651d87a1 --- /dev/null +++ b/lib/plugins/authad/auth.php @@ -0,0 +1,515 @@ +<?php +// must be run within Dokuwiki +if(!defined('DOKU_INC')) die(); + +require_once(DOKU_PLUGIN.'authad/adLDAP/adLDAP.php'); + +/** + * Active Directory authentication backend for DokuWiki + * + * This makes authentication with a Active Directory server much easier + * than when using the normal LDAP backend by utilizing the adLDAP library + * + * Usage: + * Set DokuWiki's local.protected.php auth setting to read + * + * $conf['authtype'] = 'authad'; + * + * $conf['plugin']['authad']['account_suffix'] = '@my.domain.org'; + * $conf['plugin']['authad']['base_dn'] = 'DC=my,DC=domain,DC=org'; + * $conf['plugin']['authad']['domain_controllers'] = 'srv1.domain.org,srv2.domain.org'; + * + * //optional: + * $conf['plugin']['authad']['sso'] = 1; + * $conf['plugin']['authad']['ad_username'] = 'root'; + * $conf['plugin']['authad']['ad_password'] = 'pass'; + * $conf['plugin']['authad']['real_primarygroup'] = 1; + * $conf['plugin']['authad']['use_ssl'] = 1; + * $conf['plugin']['authad']['use_tls'] = 1; + * $conf['plugin']['authad']['debug'] = 1; + * // warn user about expiring password this many days in advance: + * $conf['plugin']['authad']['expirywarn'] = 5; + * + * // get additional information to the userinfo array + * // add a list of comma separated ldap contact fields. + * $conf['plugin']['authad']['additional'] = 'field1,field2'; + * + * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) + * @author James Van Lommel <jamesvl@gmail.com> + * @link http://www.nosq.com/blog/2005/08/ldap-activedirectory-and-dokuwiki/ + * @author Andreas Gohr <andi@splitbrain.org> + * @author Jan Schumann <js@schumann-it.com> + */ +class auth_plugin_authad extends DokuWiki_Auth_Plugin { + + /** + * @var array hold connection data for a specific AD domain + */ + protected $opts = array(); + + /** + * @var array open connections for each AD domain, as adLDAP objects + */ + protected $adldap = array(); + + /** + * @var bool message state + */ + protected $msgshown = false; + + /** + * @var array user listing cache + */ + protected $users = array(); + + /** + * @var array filter patterns for listing users + */ + protected $_pattern = array(); + + /** + * Constructor + */ + public function __construct() { + parent::__construct(); + + // we load the config early to modify it a bit here + $this->loadConfig(); + + // additional information fields + if(isset($this->conf['additional'])) { + $this->conf['additional'] = str_replace(' ', '', $this->conf['additional']); + $this->conf['additional'] = explode(',', $this->conf['additional']); + } else $this->conf['additional'] = array(); + + // ldap extension is needed + if(!function_exists('ldap_connect')) { + if($this->conf['debug']) + msg("AD Auth: PHP LDAP extension not found.", -1); + $this->success = false; + return; + } + + // Prepare SSO + if(!utf8_check($_SERVER['REMOTE_USER'])) { + $_SERVER['REMOTE_USER'] = utf8_encode($_SERVER['REMOTE_USER']); + } + if($_SERVER['REMOTE_USER'] && $this->conf['sso']) { + $_SERVER['REMOTE_USER'] = $this->cleanUser($_SERVER['REMOTE_USER']); + + // we need to simulate a login + if(empty($_COOKIE[DOKU_COOKIE])) { + $_REQUEST['u'] = $_SERVER['REMOTE_USER']; + $_REQUEST['p'] = 'sso_only'; + } + } + + // other can do's are changed in $this->_loadServerConfig() base on domain setup + $this->cando['modName'] = true; + $this->cando['modMail'] = true; + } + + /** + * Check user+password [required auth function] + * + * Checks if the given user exists and the given + * plaintext password is correct by trying to bind + * to the LDAP server + * + * @author James Van Lommel <james@nosq.com> + * @param string $user + * @param string $pass + * @return bool + */ + public function checkPass($user, $pass) { + if($_SERVER['REMOTE_USER'] && + $_SERVER['REMOTE_USER'] == $user && + $this->conf['sso'] + ) return true; + + $adldap = $this->_adldap($this->_userDomain($user)); + if(!$adldap) return false; + + return $adldap->authenticate($this->_userName($user), $pass); + } + + /** + * Return user info [required auth function] + * + * Returns info about the given user needs to contain + * at least these fields: + * + * name string full name of the user + * mail string email address of the user + * grps array list of groups the user is in + * + * This AD specific function returns the following + * addional fields: + * + * dn string distinguished name (DN) + * uid string samaccountname + * lastpwd int timestamp of the date when the password was set + * expires true if the password expires + * expiresin int seconds until the password expires + * any fields specified in the 'additional' config option + * + * @author James Van Lommel <james@nosq.com> + * @param string $user + * @return array + */ + public function getUserData($user) { + global $conf; + global $lang; + global $ID; + $adldap = $this->_adldap($this->_userDomain($user)); + if(!$adldap) return false; + + if($user == '') return array(); + + $fields = array('mail', 'displayname', 'samaccountname', 'lastpwd', 'pwdlastset', 'useraccountcontrol'); + + // add additional fields to read + $fields = array_merge($fields, $this->conf['additional']); + $fields = array_unique($fields); + + //get info for given user + $result = $adldap->user()->info($this->_userName($user), $fields); + if($result == false){ + return array(); + } + + //general user info + $info['name'] = $result[0]['displayname'][0]; + $info['mail'] = $result[0]['mail'][0]; + $info['uid'] = $result[0]['samaccountname'][0]; + $info['dn'] = $result[0]['dn']; + //last password set (Windows counts from January 1st 1601) + $info['lastpwd'] = $result[0]['pwdlastset'][0] / 10000000 - 11644473600; + //will it expire? + $info['expires'] = !($result[0]['useraccountcontrol'][0] & 0x10000); //ADS_UF_DONT_EXPIRE_PASSWD + + // additional information + foreach($this->conf['additional'] as $field) { + if(isset($result[0][strtolower($field)])) { + $info[$field] = $result[0][strtolower($field)][0]; + } + } + + // handle ActiveDirectory memberOf + $info['grps'] = $adldap->user()->groups($this->_userName($user),(bool) $this->opts['recursive_groups']); + + if(is_array($info['grps'])) { + foreach($info['grps'] as $ndx => $group) { + $info['grps'][$ndx] = $this->cleanGroup($group); + } + } + + // always add the default group to the list of groups + if(!is_array($info['grps']) || !in_array($conf['defaultgroup'], $info['grps'])) { + $info['grps'][] = $conf['defaultgroup']; + } + + // add the user's domain to the groups + $domain = $this->_userDomain($user); + if($domain && !in_array("domain-$domain", (array) $info['grps'])) { + $info['grps'][] = $this->cleanGroup("domain-$domain"); + } + + // check expiry time + if($info['expires'] && $this->conf['expirywarn']){ + $timeleft = $adldap->user()->passwordExpiry($user); // returns unixtime + $timeleft = round($timeleft/(24*60*60)); + $info['expiresin'] = $timeleft; + + // if this is the current user, warn him (once per request only) + if(($_SERVER['REMOTE_USER'] == $user) && + ($timeleft <= $this->conf['expirywarn']) && + !$this->msgshown + ) { + $msg = sprintf($lang['authpwdexpire'], $timeleft); + if($this->canDo('modPass')) { + $url = wl($ID, array('do'=> 'profile')); + $msg .= ' <a href="'.$url.'">'.$lang['btn_profile'].'</a>'; + } + msg($msg); + $this->msgshown = true; + } + } + + return $info; + } + + /** + * Make AD group names usable by DokuWiki. + * + * Removes backslashes ('\'), pound signs ('#'), and converts spaces to underscores. + * + * @author James Van Lommel (jamesvl@gmail.com) + * @param string $group + * @return string + */ + public function cleanGroup($group) { + $group = str_replace('\\', '', $group); + $group = str_replace('#', '', $group); + $group = preg_replace('[\s]', '_', $group); + $group = utf8_strtolower(trim($group)); + return $group; + } + + /** + * Sanitize user names + * + * Normalizes domain parts, does not modify the user name itself (unlike cleanGroup) + * + * @author Andreas Gohr <gohr@cosmocode.de> + * @param string $user + * @return string + */ + public function cleanUser($user) { + $domain = ''; + + // get NTLM or Kerberos domain part + list($dom, $user) = explode('\\', $user, 2); + if(!$user) $user = $dom; + if($dom) $domain = $dom; + list($user, $dom) = explode('@', $user, 2); + if($dom) $domain = $dom; + + // clean up both + $domain = utf8_strtolower(trim($domain)); + $user = utf8_strtolower(trim($user)); + + // is this a known, valid domain? if not discard + if(!is_array($this->conf[$domain])) { + $domain = ''; + } + + // reattach domain + if($domain) $user = "$user@$domain"; + return $user; + } + + /** + * Most values in LDAP are case-insensitive + * + * @return bool + */ + public function isCaseSensitive() { + return false; + } + + /** + * Bulk retrieval of user data + * + * @author Dominik Eckelmann <dokuwiki@cosmocode.de> + * @param int $start index of first user to be returned + * @param int $limit max number of users to be returned + * @param array $filter array of field/pattern pairs, null for no filter + * @return array userinfo (refer getUserData for internal userinfo details) + */ + public function retrieveUsers($start = 0, $limit = -1, $filter = array()) { + $adldap = $this->_adldap(null); + if(!$adldap) return false; + + if($this->users === null) { + //get info for given user + $result = $adldap->user()->all(); + if (!$result) return array(); + $this->users = array_fill_keys($result, false); + } + + $i = 0; + $count = 0; + $this->_constructPattern($filter); + $result = array(); + + foreach($this->users as $user => &$info) { + if($i++ < $start) { + continue; + } + if($info === false) { + $info = $this->getUserData($user); + } + if($this->_filter($user, $info)) { + $result[$user] = $info; + if(($limit >= 0) && (++$count >= $limit)) break; + } + } + return $result; + } + + /** + * Modify user data + * + * @param string $user nick of the user to be changed + * @param array $changes array of field/value pairs to be changed + * @return bool + */ + public function modifyUser($user, $changes) { + $return = true; + $adldap = $this->_adldap($this->_userDomain($user)); + if(!$adldap) return false; + + // password changing + if(isset($changes['pass'])) { + try { + $return = $adldap->user()->password($this->_userName($user),$changes['pass']); + } catch (adLDAPException $e) { + if ($this->conf['debug']) msg('AD Auth: '.$e->getMessage(), -1); + $return = false; + } + if(!$return) msg('AD Auth: failed to change the password. Maybe the password policy was not met?', -1); + } + + // changing user data + $adchanges = array(); + if(isset($changes['name'])) { + // get first and last name + $parts = explode(' ', $changes['name']); + $adchanges['surname'] = array_pop($parts); + $adchanges['firstname'] = join(' ', $parts); + $adchanges['display_name'] = $changes['name']; + } + if(isset($changes['mail'])) { + $adchanges['email'] = $changes['mail']; + } + if(count($adchanges)) { + try { + $return = $return & $adldap->user()->modify($this->_userName($user),$adchanges); + } catch (adLDAPException $e) { + if ($this->conf['debug']) msg('AD Auth: '.$e->getMessage(), -1); + $return = false; + } + } + + return $return; + } + + /** + * Initialize the AdLDAP library and connect to the server + * + * When you pass null as domain, it will reuse any existing domain. + * Eg. the one of the logged in user. It falls back to the default + * domain if no current one is available. + * + * @param string|null $domain The AD domain to use + * @return adLDAP|bool true if a connection was established + */ + protected function _adldap($domain) { + if(is_null($domain) && is_array($this->opts)) { + $domain = $this->opts['domain']; + } + + $this->opts = $this->_loadServerConfig((string) $domain); + if(isset($this->adldap[$domain])) return $this->adldap[$domain]; + + // connect + try { + $this->adldap[$domain] = new adLDAP($this->opts); + return $this->adldap[$domain]; + } catch(adLDAPException $e) { + if($this->conf['debug']) { + msg('AD Auth: '.$e->getMessage(), -1); + } + $this->success = false; + $this->adldap[$domain] = null; + } + return false; + } + + /** + * Get the domain part from a user + * + * @param $user + * @return string + */ + public function _userDomain($user) { + list(, $domain) = explode('@', $user, 2); + return $domain; + } + + /** + * Get the user part from a user + * + * @param $user + * @return string + */ + public function _userName($user) { + list($name) = explode('@', $user, 2); + return $name; + } + + /** + * Fetch the configuration for the given AD domain + * + * @param string $domain current AD domain + * @return array + */ + protected function _loadServerConfig($domain) { + // prepare adLDAP standard configuration + $opts = $this->conf; + + $opts['domain'] = $domain; + + // add possible domain specific configuration + if($domain && is_array($this->conf[$domain])) foreach($this->conf[$domain] as $key => $val) { + $opts[$key] = $val; + } + + // handle multiple AD servers + $opts['domain_controllers'] = explode(',', $opts['domain_controllers']); + $opts['domain_controllers'] = array_map('trim', $opts['domain_controllers']); + $opts['domain_controllers'] = array_filter($opts['domain_controllers']); + + // we can change the password if SSL is set + if($opts['use_ssl'] || $opts['use_tls']) { + $this->cando['modPass'] = true; + } else { + $this->cando['modPass'] = false; + } + + if(isset($opts['ad_username']) && isset($opts['ad_password'])) { + $this->cando['getUsers'] = true; + } else { + $this->cando['getUsers'] = true; + } + + return $opts; + } + + /** + * Check provided user and userinfo for matching patterns + * + * The patterns are set up with $this->_constructPattern() + * + * @author Chris Smith <chris@jalakai.co.uk> + * @param string $user + * @param array $info + * @return bool + */ + protected function _filter($user, $info) { + foreach($this->_pattern as $item => $pattern) { + if($item == 'user') { + if(!preg_match($pattern, $user)) return false; + } else if($item == 'grps') { + if(!count(preg_grep($pattern, $info['grps']))) return false; + } else { + if(!preg_match($pattern, $info[$item])) return false; + } + } + return true; + } + + /** + * Create a pattern for $this->_filter() + * + * @author Chris Smith <chris@jalakai.co.uk> + * @param array $filter + */ + protected function _constructPattern($filter) { + $this->_pattern = array(); + foreach($filter as $item => $pattern) { + $this->_pattern[$item] = '/'.str_replace('/', '\/', $pattern).'/i'; // allow regex characters + } + } +} diff --git a/lib/plugins/authad/plugin.info.txt b/lib/plugins/authad/plugin.info.txt new file mode 100644 index 000000000..f02b5118c --- /dev/null +++ b/lib/plugins/authad/plugin.info.txt @@ -0,0 +1,7 @@ +base authad +author Andreas Gohr +email andi@splitbrain.org +date 2012-11-09 +name Active Directory auth plugin +desc Provides authentication against a Microsoft Active Directory +url http://www.dokuwiki.org/plugin:authad diff --git a/lib/plugins/authldap/auth.php b/lib/plugins/authldap/auth.php new file mode 100644 index 000000000..6e7bde1f0 --- /dev/null +++ b/lib/plugins/authldap/auth.php @@ -0,0 +1,534 @@ +<?php +// must be run within Dokuwiki +if(!defined('DOKU_INC')) die(); + +/** + * LDAP authentication backend + * + * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) + * @author Andreas Gohr <andi@splitbrain.org> + * @author Chris Smith <chris@jalakaic.co.uk> + * @author Jan Schumann <js@schumann-it.com> + */ +class auth_plugin_authldap extends DokuWiki_Auth_Plugin { + /* @var resource $con holds the LDAP connection*/ + protected $con = null; + + /* @var int $bound What type of connection does already exist? */ + protected $bound = 0; // 0: anonymous, 1: user, 2: superuser + + /* @var array $users User data cache */ + protected $users = null; + + /* @var array $_pattern User filter pattern */ + protected $_pattern = null; + + /** + * Constructor + */ + public function __construct() { + parent::__construct(); + + // ldap extension is needed + if(!function_exists('ldap_connect')) { + $this->_debug("LDAP err: PHP LDAP extension not found.", -1, __LINE__, __FILE__); + $this->success = false; + return; + } + + // auth_ldap currently just handles authentication, so no + // capabilities are set + } + + /** + * Check user+password + * + * Checks if the given user exists and the given + * plaintext password is correct by trying to bind + * to the LDAP server + * + * @author Andreas Gohr <andi@splitbrain.org> + * @param string $user + * @param string $pass + * @return bool + */ + public function checkPass($user, $pass) { + // reject empty password + if(empty($pass)) return false; + if(!$this->_openLDAP()) return false; + + // indirect user bind + if($this->getConf('binddn') && $this->getConf('bindpw')) { + // use superuser credentials + if(!@ldap_bind($this->con, $this->getConf('binddn'), $this->getConf('bindpw'))) { + $this->_debug('LDAP bind as superuser: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__); + return false; + } + $this->bound = 2; + } else if($this->getConf('binddn') && + $this->getConf('usertree') && + $this->getConf('userfilter') + ) { + // special bind string + $dn = $this->_makeFilter( + $this->getConf('binddn'), + array('user'=> $user, 'server'=> $this->getConf('server')) + ); + + } else if(strpos($this->getConf('usertree'), '%{user}')) { + // direct user bind + $dn = $this->_makeFilter( + $this->getConf('usertree'), + array('user'=> $user, 'server'=> $this->getConf('server')) + ); + + } else { + // Anonymous bind + if(!@ldap_bind($this->con)) { + msg("LDAP: can not bind anonymously", -1); + $this->_debug('LDAP anonymous bind: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__); + return false; + } + } + + // Try to bind to with the dn if we have one. + if(!empty($dn)) { + // User/Password bind + if(!@ldap_bind($this->con, $dn, $pass)) { + $this->_debug("LDAP: bind with $dn failed", -1, __LINE__, __FILE__); + $this->_debug('LDAP user dn bind: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__); + return false; + } + $this->bound = 1; + return true; + } else { + // See if we can find the user + $info = $this->getUserData($user, true); + if(empty($info['dn'])) { + return false; + } else { + $dn = $info['dn']; + } + + // Try to bind with the dn provided + if(!@ldap_bind($this->con, $dn, $pass)) { + $this->_debug("LDAP: bind with $dn failed", -1, __LINE__, __FILE__); + $this->_debug('LDAP user bind: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__); + return false; + } + $this->bound = 1; + return true; + } + } + + /** + * Return user info + * + * Returns info about the given user needs to contain + * at least these fields: + * + * name string full name of the user + * mail string email addres of the user + * grps array list of groups the user is in + * + * This LDAP specific function returns the following + * addional fields: + * + * dn string distinguished name (DN) + * uid string Posix User ID + * inbind bool for internal use - avoid loop in binding + * + * @author Andreas Gohr <andi@splitbrain.org> + * @author Trouble + * @author Dan Allen <dan.j.allen@gmail.com> + * @author <evaldas.auryla@pheur.org> + * @author Stephane Chazelas <stephane.chazelas@emerson.com> + * + * @param string $user + * @param bool $inbind authldap specific, true if in bind phase + * @return array containing user data or false + */ + public function getUserData($user, $inbind = false) { + global $conf; + if(!$this->_openLDAP()) return false; + + // force superuser bind if wanted and not bound as superuser yet + if($this->getConf('binddn') && $this->getConf('bindpw') && $this->bound < 2) { + // use superuser credentials + if(!@ldap_bind($this->con, $this->getConf('binddn'), $this->getConf('bindpw'))) { + $this->_debug('LDAP bind as superuser: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__); + return false; + } + $this->bound = 2; + } elseif($this->bound == 0 && !$inbind) { + // in some cases getUserData is called outside the authentication workflow + // eg. for sending email notification on subscribed pages. This data might not + // be accessible anonymously, so we try to rebind the current user here + list($loginuser, $loginsticky, $loginpass) = auth_getCookie(); + if($loginuser && $loginpass) { + $loginpass = PMA_blowfish_decrypt($loginpass, auth_cookiesalt(!$loginsticky)); + $this->checkPass($loginuser, $loginpass); + } + } + + $info['user'] = $user; + $info['server'] = $this->getConf('server'); + + //get info for given user + $base = $this->_makeFilter($this->getConf('usertree'), $info); + if($this->getConf('userfilter')) { + $filter = $this->_makeFilter($this->getConf('userfilter'), $info); + } else { + $filter = "(ObjectClass=*)"; + } + + $sr = $this->_ldapsearch($this->con, $base, $filter, $this->getConf('userscope')); + $result = @ldap_get_entries($this->con, $sr); + $this->_debug('LDAP user search: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__); + $this->_debug('LDAP search at: '.htmlspecialchars($base.' '.$filter), 0, __LINE__, __FILE__); + + // Don't accept more or less than one response + if(!is_array($result) || $result['count'] != 1) { + return false; //user not found + } + + $user_result = $result[0]; + ldap_free_result($sr); + + // general user info + $info['dn'] = $user_result['dn']; + $info['gid'] = $user_result['gidnumber'][0]; + $info['mail'] = $user_result['mail'][0]; + $info['name'] = $user_result['cn'][0]; + $info['grps'] = array(); + + // overwrite if other attribs are specified. + if(is_array($this->getConf('mapping'))) { + foreach($this->getConf('mapping') as $localkey => $key) { + if(is_array($key)) { + // use regexp to clean up user_result + list($key, $regexp) = each($key); + if($user_result[$key]) foreach($user_result[$key] as $grp) { + if(preg_match($regexp, $grp, $match)) { + if($localkey == 'grps') { + $info[$localkey][] = $match[1]; + } else { + $info[$localkey] = $match[1]; + } + } + } + } else { + $info[$localkey] = $user_result[$key][0]; + } + } + } + $user_result = array_merge($info, $user_result); + + //get groups for given user if grouptree is given + if($this->getConf('grouptree') || $this->getConf('groupfilter')) { + $base = $this->_makeFilter($this->getConf('grouptree'), $user_result); + $filter = $this->_makeFilter($this->getConf('groupfilter'), $user_result); + $sr = $this->_ldapsearch($this->con, $base, $filter, $this->getConf('groupscope'), array($this->getConf('groupkey'))); + $this->_debug('LDAP group search: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__); + $this->_debug('LDAP search at: '.htmlspecialchars($base.' '.$filter), 0, __LINE__, __FILE__); + + if(!$sr) { + msg("LDAP: Reading group memberships failed", -1); + return false; + } + $result = ldap_get_entries($this->con, $sr); + ldap_free_result($sr); + + if(is_array($result)) foreach($result as $grp) { + if(!empty($grp[$this->getConf('groupkey')][0])) { + $this->_debug('LDAP usergroup: '.htmlspecialchars($grp[$this->getConf('groupkey')][0]), 0, __LINE__, __FILE__); + $info['grps'][] = $grp[$this->getConf('groupkey')][0]; + } + } + } + + // always add the default group to the list of groups + if(!in_array($conf['defaultgroup'], $info['grps'])) { + $info['grps'][] = $conf['defaultgroup']; + } + return $info; + } + + /** + * Most values in LDAP are case-insensitive + * + * @return bool + */ + public function isCaseSensitive() { + return false; + } + + /** + * Bulk retrieval of user data + * + * @author Dominik Eckelmann <dokuwiki@cosmocode.de> + * @param int $start index of first user to be returned + * @param int $limit max number of users to be returned + * @param array $filter array of field/pattern pairs, null for no filter + * @return array of userinfo (refer getUserData for internal userinfo details) + */ + function retrieveUsers($start = 0, $limit = -1, $filter = array()) { + if(!$this->_openLDAP()) return false; + + if(is_null($this->users)) { + // Perform the search and grab all their details + if($this->getConf('userfilter')) { + $all_filter = str_replace('%{user}', '*', $this->getConf('userfilter')); + } else { + $all_filter = "(ObjectClass=*)"; + } + $sr = ldap_search($this->con, $this->getConf('usertree'), $all_filter); + $entries = ldap_get_entries($this->con, $sr); + $users_array = array(); + for($i = 0; $i < $entries["count"]; $i++) { + array_push($users_array, $entries[$i]["uid"][0]); + } + asort($users_array); + $result = $users_array; + if(!$result) return array(); + $this->users = array_fill_keys($result, false); + } + $i = 0; + $count = 0; + $this->_constructPattern($filter); + $result = array(); + + foreach($this->users as $user => &$info) { + if($i++ < $start) { + continue; + } + if($info === false) { + $info = $this->getUserData($user); + } + if($this->_filter($user, $info)) { + $result[$user] = $info; + if(($limit >= 0) && (++$count >= $limit)) break; + } + } + return $result; + } + + /** + * Make LDAP filter strings. + * + * Used by auth_getUserData to make the filter + * strings for grouptree and groupfilter + * + * @author Troels Liebe Bentsen <tlb@rapanden.dk> + * @param string $filter ldap search filter with placeholders + * @param array $placeholders placeholders to fill in + * @return string + */ + protected function _makeFilter($filter, $placeholders) { + preg_match_all("/%{([^}]+)/", $filter, $matches, PREG_PATTERN_ORDER); + //replace each match + foreach($matches[1] as $match) { + //take first element if array + if(is_array($placeholders[$match])) { + $value = $placeholders[$match][0]; + } else { + $value = $placeholders[$match]; + } + $value = $this->_filterEscape($value); + $filter = str_replace('%{'.$match.'}', $value, $filter); + } + return $filter; + } + + /** + * return true if $user + $info match $filter criteria, false otherwise + * + * @author Chris Smith <chris@jalakai.co.uk> + * + * @param string $user the user's login name + * @param array $info the user's userinfo array + * @return bool + */ + protected function _filter($user, $info) { + foreach($this->_pattern as $item => $pattern) { + if($item == 'user') { + if(!preg_match($pattern, $user)) return false; + } else if($item == 'grps') { + if(!count(preg_grep($pattern, $info['grps']))) return false; + } else { + if(!preg_match($pattern, $info[$item])) return false; + } + } + return true; + } + + /** + * Set the filter pattern + * + * @author Chris Smith <chris@jalakai.co.uk> + * + * @param $filter + * @return void + */ + protected function _constructPattern($filter) { + $this->_pattern = array(); + foreach($filter as $item => $pattern) { + $this->_pattern[$item] = '/'.str_replace('/', '\/', $pattern).'/i'; // allow regex characters + } + } + + /** + * Escape a string to be used in a LDAP filter + * + * Ported from Perl's Net::LDAP::Util escape_filter_value + * + * @author Andreas Gohr + * @param string $string + * @return string + */ + protected function _filterEscape($string) { + return preg_replace( + '/([\x00-\x1F\*\(\)\\\\])/e', + '"\\\\\".join("",unpack("H2","$1"))', + $string + ); + } + + /** + * Opens a connection to the configured LDAP server and sets the wanted + * option on the connection + * + * @author Andreas Gohr <andi@splitbrain.org> + */ + protected function _openLDAP() { + if($this->con) return true; // connection already established + + $this->bound = 0; + + $port = $this->getConf('port'); + $bound = false; + $servers = explode(',', $this->getConf('server')); + foreach($servers as $server) { + $server = trim($server); + $this->con = @ldap_connect($server, $port); + if(!$this->con) { + continue; + } + + /* + * When OpenLDAP 2.x.x is used, ldap_connect() will always return a resource as it does + * not actually connect but just initializes the connecting parameters. The actual + * connect happens with the next calls to ldap_* funcs, usually with ldap_bind(). + * + * So we should try to bind to server in order to check its availability. + */ + + //set protocol version and dependend options + if($this->getConf('version')) { + if(!@ldap_set_option( + $this->con, LDAP_OPT_PROTOCOL_VERSION, + $this->getConf('version') + ) + ) { + msg('Setting LDAP Protocol version '.$this->getConf('version').' failed', -1); + $this->_debug('LDAP version set: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__); + } else { + //use TLS (needs version 3) + if($this->getConf('starttls')) { + if(!@ldap_start_tls($this->con)) { + msg('Starting TLS failed', -1); + $this->_debug('LDAP TLS set: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__); + } + } + // needs version 3 + if($this->getConf('referrals')) { + if(!@ldap_set_option( + $this->con, LDAP_OPT_REFERRALS, + $this->getConf('referrals') + ) + ) { + msg('Setting LDAP referrals to off failed', -1); + $this->_debug('LDAP referal set: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__); + } + } + } + } + + //set deref mode + if($this->getConf('deref')) { + if(!@ldap_set_option($this->con, LDAP_OPT_DEREF, $this->getConf('deref'))) { + msg('Setting LDAP Deref mode '.$this->getConf('deref').' failed', -1); + $this->_debug('LDAP deref set: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__); + } + } + /* As of PHP 5.3.0 we can set timeout to speedup skipping of invalid servers */ + if(defined('LDAP_OPT_NETWORK_TIMEOUT')) { + ldap_set_option($this->con, LDAP_OPT_NETWORK_TIMEOUT, 1); + } + $bound = @ldap_bind($this->con); + if($bound) { + break; + } + } + + if(!$bound) { + msg("LDAP: couldn't connect to LDAP server", -1); + return false; + } + + $this->cando['getUsers'] = true; + return true; + } + + /** + * Wraps around ldap_search, ldap_list or ldap_read depending on $scope + * + * @author Andreas Gohr <andi@splitbrain.org> + * @param resource $link_identifier + * @param string $base_dn + * @param string $filter + * @param string $scope can be 'base', 'one' or 'sub' + * @param null $attributes + * @param int $attrsonly + * @param int $sizelimit + * @param int $timelimit + * @param int $deref + * @return resource + */ + protected function _ldapsearch($link_identifier, $base_dn, $filter, $scope = 'sub', $attributes = null, + $attrsonly = 0, $sizelimit = 0, $timelimit = 0, $deref = LDAP_DEREF_NEVER) { + if(is_null($attributes)) $attributes = array(); + + if($scope == 'base') { + return @ldap_read( + $link_identifier, $base_dn, $filter, $attributes, + $attrsonly, $sizelimit, $timelimit, $deref + ); + } elseif($scope == 'one') { + return @ldap_list( + $link_identifier, $base_dn, $filter, $attributes, + $attrsonly, $sizelimit, $timelimit, $deref + ); + } else { + return @ldap_search( + $link_identifier, $base_dn, $filter, $attributes, + $attrsonly, $sizelimit, $timelimit, $deref + ); + } + } + + /** + * Wrapper around msg() but outputs only when debug is enabled + * + * @param string $message + * @param int $err + * @param int $line + * @param string $file + * @return void + */ + protected function _debug($message, $err, $line, $file) { + if(!$this->getConf('debug')) return; + msg($message, $err, $line, $file); + } + +} diff --git a/lib/plugins/authldap/conf/default.php b/lib/plugins/authldap/conf/default.php new file mode 100644 index 000000000..35971d41d --- /dev/null +++ b/lib/plugins/authldap/conf/default.php @@ -0,0 +1,7 @@ +<?php + +$conf['port'] = 389; + +$conf['groupkey'] = 'cn'; +$conf['userscope'] = 'sub'; +$conf['groupscope'] = 'sub';
\ No newline at end of file diff --git a/lib/plugins/authldap/plugin.info.txt b/lib/plugins/authldap/plugin.info.txt new file mode 100644 index 000000000..2af8cf00a --- /dev/null +++ b/lib/plugins/authldap/plugin.info.txt @@ -0,0 +1,7 @@ +base authldap +author Andreas Gohr +email andi@splitbrain.org +date 2012-10-06 +name ldap auth plugin +desc Provides authentication against am LDAP server +url http://www.dokuwiki.org/plugin:authldap diff --git a/inc/auth/mysql.class.php b/lib/plugins/authmysql/auth.php index 9dcf82a87..7d303726b 100644 --- a/inc/auth/mysql.class.php +++ b/lib/plugins/authmysql/auth.php @@ -1,21 +1,25 @@ <?php +// must be run within Dokuwiki +if(!defined('DOKU_INC')) die(); + /** - * MySQLP authentication backend + * MySQL authentication backend * * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) * @author Andreas Gohr <andi@splitbrain.org> * @author Chris Smith <chris@jalakai.co.uk> * @author Matthias Grimm <matthias.grimmm@sourceforge.net> + * @author Jan Schumann <js@schumann-it.com> */ - -class auth_mysql extends auth_basic { - - var $dbcon = 0; - var $dbver = 0; // database version - var $dbrev = 0; // database revision - var $dbsub = 0; // database subrevision - var $cnf = null; - var $defaultgroup = ""; +class auth_plugin_authmysql extends DokuWiki_Auth_Plugin { + /** @var resource holds the database connection */ + protected $dbcon = 0; + /** @var int database version*/ + protected $dbver = 0; + /** @var int database revision */ + protected $dbrev = 0; + /** @var int database subrevision */ + protected $dbsub = 0; /** * Constructor @@ -25,90 +29,93 @@ class auth_mysql extends auth_basic { * * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> */ - function __construct() { - global $conf; - $this->cnf = $conf['auth']['mysql']; - - if (method_exists($this, 'auth_basic')){ - parent::__construct(); - } + public function __construct() { + parent::__construct(); if(!function_exists('mysql_connect')) { - if ($this->cnf['debug']){ - msg("MySQL err: PHP MySQL extension not found.",-1,__LINE__,__FILE__); - } + $this->_debug("MySQL err: PHP MySQL extension not found.", -1, __LINE__, __FILE__); $this->success = false; return; } - // default to UTF-8, you rarely want something else - if(!isset($this->cnf['charset'])) $this->cnf['charset'] = 'utf8'; - - $this->defaultgroup = $conf['defaultgroup']; - // set capabilities based upon config strings set - if (empty($this->cnf['server']) || empty($this->cnf['user']) || - !isset($this->cnf['password']) || empty($this->cnf['database'])){ + if(!$this->getConf('server') || !$this->getConf('user') || !$this->getConf('database')) { + $this->_debug("MySQL err: insufficient configuration.", -1, __LINE__, __FILE__); - if ($this->cnf['debug']){ - msg("MySQL err: insufficient configuration.",-1,__LINE__,__FILE__); - } $this->success = false; return; } - $this->cando['addUser'] = $this->_chkcnf(array( - 'getUserInfo', - 'getGroups', - 'addUser', - 'getUserID', - 'getGroupID', - 'addGroup', - 'addUserGroup'),true); - $this->cando['delUser'] = $this->_chkcnf(array( - 'getUserID', - 'delUser', - 'delUserRefs'),true); - $this->cando['modLogin'] = $this->_chkcnf(array( - 'getUserID', - 'updateUser', - 'UpdateTarget'),true); - $this->cando['modPass'] = $this->cando['modLogin']; - $this->cando['modName'] = $this->cando['modLogin']; - $this->cando['modMail'] = $this->cando['modLogin']; - $this->cando['modGroups'] = $this->_chkcnf(array( - 'getUserID', - 'getGroups', - 'getGroupID', - 'addGroup', - 'addUserGroup', - 'delGroup', - 'getGroupID', - 'delUserGroup'),true); + $this->cando['addUser'] = $this->_chkcnf( + array( + 'getUserInfo', + 'getGroups', + 'addUser', + 'getUserID', + 'getGroupID', + 'addGroup', + 'addUserGroup' + ), true + ); + $this->cando['delUser'] = $this->_chkcnf( + array( + 'getUserID', + 'delUser', + 'delUserRefs' + ), true + ); + $this->cando['modLogin'] = $this->_chkcnf( + array( + 'getUserID', + 'updateUser', + 'UpdateTarget' + ), true + ); + $this->cando['modPass'] = $this->cando['modLogin']; + $this->cando['modName'] = $this->cando['modLogin']; + $this->cando['modMail'] = $this->cando['modLogin']; + $this->cando['modGroups'] = $this->_chkcnf( + array( + 'getUserID', + 'getGroups', + 'getGroupID', + 'addGroup', + 'addUserGroup', + 'delGroup', + 'getGroupID', + 'delUserGroup' + ), true + ); /* getGroups is not yet supported $this->cando['getGroups'] = $this->_chkcnf(array('getGroups', 'getGroupID'),false); */ - $this->cando['getUsers'] = $this->_chkcnf(array( - 'getUsers', - 'getUserInfo', - 'getGroups'),false); - $this->cando['getUserCount'] = $this->_chkcnf(array('getUsers'),false); + $this->cando['getUsers'] = $this->_chkcnf( + array( + 'getUsers', + 'getUserInfo', + 'getGroups' + ), false + ); + $this->cando['getUserCount'] = $this->_chkcnf(array('getUsers'), false); } /** * Check if the given config strings are set * * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> + * @param array $keys + * @param bool $wop is this a check for a write operation? * @return bool */ - function _chkcnf($keys, $wop=false){ - foreach ($keys as $key){ - if (empty($this->cnf[$key])) return false; + protected function _chkcnf($keys, $wop = false) { + foreach($keys as $key) { + if(!$this->getConf($key)) return false; } /* write operation and lock array filled with tables names? */ - if ($wop && (!is_array($this->cnf['TablesToLock']) || - !count($this->cnf['TablesToLock']))){ + if($wop && (!is_array($this->getConf('TablesToLock')) || + !count($this->getConf('TablesToLock'))) + ) { return false; } @@ -123,27 +130,28 @@ class auth_mysql extends auth_basic { * Depending on which SQL string is defined in the config, password * checking is done here (getpass) or by the database (passcheck) * - * @param $user user who would like access - * @param $pass user's clear text password to check + * @param string $user user who would like access + * @param string $pass user's clear text password to check * @return bool * * @author Andreas Gohr <andi@splitbrain.org> * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> */ - function checkPass($user,$pass){ - $rc = false; + public function checkPass($user, $pass) { + global $conf; + $rc = false; if($this->_openDB()) { - $sql = str_replace('%{user}',$this->_escape($user),$this->cnf['checkPass']); - $sql = str_replace('%{pass}',$this->_escape($pass),$sql); - $sql = str_replace('%{dgroup}',$this->_escape($this->defaultgroup),$sql); + $sql = str_replace('%{user}', $this->_escape($user), $this->getConf('checkPass')); + $sql = str_replace('%{pass}', $this->_escape($pass), $sql); + $sql = str_replace('%{dgroup}', $this->_escape($conf['defaultgroup']), $sql); $result = $this->_queryDB($sql); if($result !== false && count($result) == 1) { - if($this->cnf['forwardClearPass'] == 1) + if($this->getConf('forwardClearPass') == 1) $rc = true; else - $rc = auth_verifyPassword($pass,$result[0]['pass']); + $rc = auth_verifyPassword($pass, $result[0]['pass']); } $this->_closeDB(); } @@ -151,20 +159,15 @@ class auth_mysql extends auth_basic { } /** - * [public function] - * - * Returns info about the given user needs to contain - * at least these fields: - * name string full name of the user - * mail string email addres of the user - * grps array list of groups the user is in - * - * @param $user user's nick to get data for + * Return user info * * @author Andreas Gohr <andi@splitbrain.org> * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> + * + * @param string $user user login to get data for + * @return array|bool */ - function getUserData($user){ + public function getUserData($user) { if($this->_openDB()) { $this->_lockTables("READ"); $info = $this->_getUserInfo($user); @@ -176,45 +179,46 @@ class auth_mysql extends auth_basic { } /** - * [public function] - * * Create a new User. Returns false if the user already exists, * null when an error occurred and true if everything went well. * * The new user will be added to the default group by this * function if grps are not specified (default behaviour). * - * @param $user nick of the user - * @param $pwd clear text password - * @param $name full name of the user - * @param $mail email address - * @param $grps array of groups the user should become member of - * * @author Andreas Gohr <andi@splitbrain.org> * @author Chris Smith <chris@jalakai.co.uk> * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> + * + * @param string $user nick of the user + * @param string $pwd clear text password + * @param string $name full name of the user + * @param string $mail email address + * @param array $grps array of groups the user should become member of + * @return bool|null */ - function createUser($user,$pwd,$name,$mail,$grps=null){ + public function createUser($user, $pwd, $name, $mail, $grps = null) { + global $conf; + if($this->_openDB()) { - if (($info = $this->_getUserInfo($user)) !== false) - return false; // user already exists + if(($info = $this->_getUserInfo($user)) !== false) + return false; // user already exists // set defaultgroup if no groups were given - if ($grps == null) - $grps = array($this->defaultgroup); + if($grps == null) + $grps = array($conf['defaultgroup']); $this->_lockTables("WRITE"); - $pwd = $this->cnf['forwardClearPass'] ? $pwd : auth_cryptPassword($pwd); - $rc = $this->_addUser($user,$pwd,$name,$mail,$grps); + $pwd = $this->getConf('forwardClearPass') ? $pwd : auth_cryptPassword($pwd); + $rc = $this->_addUser($user, $pwd, $name, $mail, $grps); $this->_unlockTables(); $this->_closeDB(); - if ($rc) return true; + if($rc) return true; } - return null; // return error + return null; // return error } /** - * Modify user data [public function] + * Modify user data * * An existing user dataset will be modified. Changes are given in an array. * @@ -233,37 +237,36 @@ class auth_mysql extends auth_basic { * should be modified). In this case we asure that we don't touch groups * even $changes['grps'] is set by mistake. * - * @param $user nick of the user to be changed - * @param $changes array of field/value pairs to be changed (password - * will be clear text) - * @return bool true on success, false on error - * * @author Chris Smith <chris@jalakai.co.uk> * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> + * + * @param string $user nick of the user to be changed + * @param array $changes array of field/value pairs to be changed (password will be clear text) + * @return bool true on success, false on error */ - function modifyUser($user, $changes) { + public function modifyUser($user, $changes) { $rc = false; - if (!is_array($changes) || !count($changes)) - return true; // nothing to change + if(!is_array($changes) || !count($changes)) + return true; // nothing to change if($this->_openDB()) { $this->_lockTables("WRITE"); - if (($uid = $this->_getUserID($user))) { + if(($uid = $this->_getUserID($user))) { $rc = $this->_updateUserInfo($changes, $uid); - if ($rc && isset($changes['grps']) && $this->cando['modGroups']) { + if($rc && isset($changes['grps']) && $this->cando['modGroups']) { $groups = $this->_getGroups($user); $grpadd = array_diff($changes['grps'], $groups); $grpdel = array_diff($groups, $changes['grps']); foreach($grpadd as $group) - if (($this->_addUserToGroup($user, $group, 1)) == false) + if(($this->_addUserToGroup($user, $group, 1)) == false) $rc = false; foreach($grpdel as $group) - if (($this->_delUserFromGroup($user, $group)) == false) + if(($this->_delUserFromGroup($user, $group)) == false) $rc = false; } } @@ -289,10 +292,10 @@ class auth_mysql extends auth_basic { $count = 0; if($this->_openDB()) { - if (is_array($users) && count($users)) { + if(is_array($users) && count($users)) { $this->_lockTables("WRITE"); - foreach ($users as $user) { - if ($this->_delUser($user)) + foreach($users as $user) { + if($this->_delUser($user)) $count++; } $this->_unlockTables(); @@ -303,28 +306,26 @@ class auth_mysql extends auth_basic { } /** - * [public function] - * * Counts users which meet certain $filter criteria. * - * @param array $filter filter criteria in item/pattern pairs - * @return count of found users. - * * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> + * + * @param array $filter filter criteria in item/pattern pairs + * @return int count of found users */ - function getUserCount($filter=array()) { + public function getUserCount($filter = array()) { $rc = 0; if($this->_openDB()) { - $sql = $this->_createSQLFilter($this->cnf['getUsers'], $filter); + $sql = $this->_createSQLFilter($this->getConf('getUsers'), $filter); - if ($this->dbver >= 4) { - $sql = substr($sql, 6); /* remove 'SELECT' or 'select' */ + if($this->dbver >= 4) { + $sql = substr($sql, 6); /* remove 'SELECT' or 'select' */ $sql = "SELECT SQL_CALC_FOUND_ROWS".$sql." LIMIT 1"; $this->_queryDB($sql); $result = $this->_queryDB("SELECT FOUND_ROWS()"); - $rc = $result[0]['FOUND_ROWS()']; - } else if (($result = $this->_queryDB($sql))) + $rc = $result[0]['FOUND_ROWS()']; + } else if(($result = $this->_queryDB($sql))) $rc = count($result); $this->_closeDB(); @@ -333,27 +334,27 @@ class auth_mysql extends auth_basic { } /** - * Bulk retrieval of user data. [public function] - * - * @param first index of first user to be returned - * @param limit max number of users to be returned - * @param filter array of field/pattern pairs - * @return array of userinfo (refer getUserData for internal userinfo details) + * Bulk retrieval of user data * * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> + * + * @param int $first index of first user to be returned + * @param int $limit max number of users to be returned + * @param array|string $filter array of field/pattern pairs + * @return array userinfo (refer getUserData for internal userinfo details) */ - function retrieveUsers($first=0,$limit=10,$filter=array()) { - $out = array(); + public function retrieveUsers($first = 0, $limit = 10, $filter = array()) { + $out = array(); if($this->_openDB()) { $this->_lockTables("READ"); - $sql = $this->_createSQLFilter($this->cnf['getUsers'], $filter); - $sql .= " ".$this->cnf['SortOrder']." LIMIT $first, $limit"; + $sql = $this->_createSQLFilter($this->getConf('getUsers'), $filter); + $sql .= " ".$this->getConf('SortOrder')." LIMIT $first, $limit"; $result = $this->_queryDB($sql); - if (!empty($result)) { - foreach ($result as $user) - if (($info = $this->_getUserInfo($user['user']))) + if(!empty($result)) { + foreach($result as $user) + if(($info = $this->_getUserInfo($user['user']))) $out[$user['user']] = $info; } @@ -364,20 +365,20 @@ class auth_mysql extends auth_basic { } /** - * Give user membership of a group [public function] - * - * @param $user - * @param $group - * @return bool true on success, false on error + * Give user membership of a group * * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> + * + * @param string $user + * @param string $group + * @return bool true on success, false on error */ - function joinGroup($user, $group) { + protected function joinGroup($user, $group) { $rc = false; - if ($this->_openDB()) { + if($this->_openDB()) { $this->_lockTables("WRITE"); - $rc = $this->_addUserToGroup($user, $group); + $rc = $this->_addUserToGroup($user, $group); $this->_unlockTables(); $this->_closeDB(); } @@ -385,20 +386,19 @@ class auth_mysql extends auth_basic { } /** - * Remove user from a group [public function] - * - * @param $user user that leaves a group - * @param $group group to leave - * @return bool + * Remove user from a group * * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> + * + * @param string $user user that leaves a group + * @param string $group group to leave + * @return bool */ - function leaveGroup($user, $group) { + protected function leaveGroup($user, $group) { $rc = false; - if ($this->_openDB()) { + if($this->_openDB()) { $this->_lockTables("WRITE"); - $uid = $this->_getUserID($user); $rc = $this->_delUserFromGroup($user, $group); $this->_unlockTables(); $this->_closeDB(); @@ -409,54 +409,54 @@ class auth_mysql extends auth_basic { /** * MySQL is case-insensitive */ - function isCaseSensitive(){ + public function isCaseSensitive() { return false; } /** * Adds a user to a group. * - * If $force is set to '1' non existing groups would be created. + * If $force is set to true non existing groups would be created. * * The database connection must already be established. Otherwise * this function does nothing and returns 'false'. It is strongly * recommended to call this function only after all participating * tables (group and usergroup) have been locked. * - * @param $user user to add to a group - * @param $group name of the group - * @param $force '1' create missing groups - * @return bool 'true' on success, 'false' on error - * * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> + * + * @param string $user user to add to a group + * @param string $group name of the group + * @param bool $force create missing groups + * @return bool true on success, false on error */ - function _addUserToGroup($user, $group, $force=0) { + protected function _addUserToGroup($user, $group, $force = false) { $newgroup = 0; - if (($this->dbcon) && ($user)) { + if(($this->dbcon) && ($user)) { $gid = $this->_getGroupID($group); - if (!$gid) { - if ($force) { // create missing groups - $sql = str_replace('%{group}',$this->_escape($group),$this->cnf['addGroup']); - $gid = $this->_modifyDB($sql); - $newgroup = 1; // group newly created + if(!$gid) { + if($force) { // create missing groups + $sql = str_replace('%{group}', $this->_escape($group), $this->getConf('addGroup')); + $gid = $this->_modifyDB($sql); + $newgroup = 1; // group newly created } - if (!$gid) return false; // group didn't exist and can't be created + if(!$gid) return false; // group didn't exist and can't be created } - $sql = $this->cnf['addUserGroup']; - if(strpos($sql,'%{uid}') !== false){ + $sql = $this->getConf('addUserGroup'); + if(strpos($sql, '%{uid}') !== false) { $uid = $this->_getUserID($user); - $sql = str_replace('%{uid}', $this->_escape($uid),$sql); + $sql = str_replace('%{uid}', $this->_escape($uid), $sql); } - $sql = str_replace('%{user}', $this->_escape($user),$sql); - $sql = str_replace('%{gid}', $this->_escape($gid),$sql); - $sql = str_replace('%{group}',$this->_escape($group),$sql); - if ($this->_modifyDB($sql) !== false) return true; - - if ($newgroup) { // remove previously created group on error - $sql = str_replace('%{gid}', $this->_escape($gid),$this->cnf['delGroup']); - $sql = str_replace('%{group}',$this->_escape($group),$sql); + $sql = str_replace('%{user}', $this->_escape($user), $sql); + $sql = str_replace('%{gid}', $this->_escape($gid), $sql); + $sql = str_replace('%{group}', $this->_escape($group), $sql); + if($this->_modifyDB($sql) !== false) return true; + + if($newgroup) { // remove previously created group on error + $sql = str_replace('%{gid}', $this->_escape($gid), $this->getConf('delGroup')); + $sql = str_replace('%{group}', $this->_escape($group), $sql); $this->_modifyDB($sql); } } @@ -466,26 +466,26 @@ class auth_mysql extends auth_basic { /** * Remove user from a group * - * @param $user user that leaves a group - * @param $group group to leave - * @return bool true on success, false on error - * * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> + * + * @param string $user user that leaves a group + * @param string $group group to leave + * @return bool true on success, false on error */ - function _delUserFromGroup($user, $group) { + protected function _delUserFromGroup($user, $group) { $rc = false; - if (($this->dbcon) && ($user)) { - $sql = $this->cnf['delUserGroup']; - if(strpos($sql,'%{uid}') !== false){ + if(($this->dbcon) && ($user)) { + $sql = $this->getConf('delUserGroup'); + if(strpos($sql, '%{uid}') !== false) { $uid = $this->_getUserID($user); - $sql = str_replace('%{uid}', $this->_escape($uid),$sql); + $sql = str_replace('%{uid}', $this->_escape($uid), $sql); } $gid = $this->_getGroupID($group); - if ($gid) { - $sql = str_replace('%{user}', $this->_escape($user),$sql); - $sql = str_replace('%{gid}', $this->_escape($gid),$sql); - $sql = str_replace('%{group}',$this->_escape($group),$sql); + if($gid) { + $sql = str_replace('%{user}', $this->_escape($user), $sql); + $sql = str_replace('%{gid}', $this->_escape($gid), $sql); + $sql = str_replace('%{group}', $this->_escape($group), $sql); $rc = $this->_modifyDB($sql) == 0 ? true : false; } } @@ -497,19 +497,18 @@ class auth_mysql extends auth_basic { * * The database connection must already be established * for this function to work. Otherwise it will return - * 'false'. - * - * @param $user user whose groups should be listed - * @return bool false on error - * @return array array containing all groups on success + * false. * * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> + * + * @param string $user user whose groups should be listed + * @return bool|array false on error, all groups on success */ - function _getGroups($user) { + protected function _getGroups($user) { $groups = array(); if($this->dbcon) { - $sql = str_replace('%{user}',$this->_escape($user),$this->cnf['getGroups']); + $sql = str_replace('%{user}', $this->_escape($user), $this->getConf('getGroups')); $result = $this->_queryDB($sql); if($result !== false && count($result)) { @@ -526,16 +525,16 @@ class auth_mysql extends auth_basic { * * The database connection must already be established * for this function to work. Otherwise it will return - * 'false'. - * - * @param $user user whose id is desired - * @return user id + * false. * * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> + * + * @param string $user user whose id is desired + * @return mixed user id */ - function _getUserID($user) { + protected function _getUserID($user) { if($this->dbcon) { - $sql = str_replace('%{user}',$this->_escape($user),$this->cnf['getUserID']); + $sql = str_replace('%{user}', $this->_escape($user), $this->getConf('getUserID')); $result = $this->_queryDB($sql); return $result === false ? false : $result[0]['id']; } @@ -547,43 +546,45 @@ class auth_mysql extends auth_basic { * * The database connection must already be established * for this function to work. Otherwise it will return - * 'false'. - * - * @param $user login of the user - * @param $pwd encrypted password - * @param $name full name of the user - * @param $mail email address - * @param $grps array of groups the user should become member of - * @return bool + * false. * * @author Andreas Gohr <andi@splitbrain.org> * @author Chris Smith <chris@jalakai.co.uk> * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> + * + * @param string $user login of the user + * @param string $pwd encrypted password + * @param string $name full name of the user + * @param string $mail email address + * @param array $grps array of groups the user should become member of + * @return bool */ - function _addUser($user,$pwd,$name,$mail,$grps){ + protected function _addUser($user, $pwd, $name, $mail, $grps) { if($this->dbcon && is_array($grps)) { - $sql = str_replace('%{user}', $this->_escape($user),$this->cnf['addUser']); - $sql = str_replace('%{pass}', $this->_escape($pwd),$sql); - $sql = str_replace('%{name}', $this->_escape($name),$sql); - $sql = str_replace('%{email}',$this->_escape($mail),$sql); + $sql = str_replace('%{user}', $this->_escape($user), $this->getConf('addUser')); + $sql = str_replace('%{pass}', $this->_escape($pwd), $sql); + $sql = str_replace('%{name}', $this->_escape($name), $sql); + $sql = str_replace('%{email}', $this->_escape($mail), $sql); $uid = $this->_modifyDB($sql); + $gid = false; + $group = ''; - if ($uid) { + if($uid) { foreach($grps as $group) { $gid = $this->_addUserToGroup($user, $group, 1); - if ($gid === false) break; + if($gid === false) break; } - if ($gid) return true; - else { + if($gid !== false){ + return true; + } else { /* remove the new user and all group relations if a group can't * be assigned. Newly created groups will remain in the database * and won't be removed. This might create orphaned groups but * is not a big issue so we ignore this problem here. */ $this->_delUser($user); - if ($this->cnf['debug']) - msg ("MySQL err: Adding user '$user' to group '$group' failed.",-1,__LINE__,__FILE__); + $this->_debug("MySQL err: Adding user '$user' to group '$group' failed.", -1, __LINE__, __FILE__); } } } @@ -595,21 +596,21 @@ class auth_mysql extends auth_basic { * * The database connection must already be established * for this function to work. Otherwise it will return - * 'false'. - * - * @param $user user whose id is desired - * @return bool + * false. * * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> + * + * @param string $user user whose id is desired + * @return bool */ - function _delUser($user) { + protected function _delUser($user) { if($this->dbcon) { $uid = $this->_getUserID($user); - if ($uid) { - $sql = str_replace('%{uid}',$this->_escape($uid),$this->cnf['delUserRefs']); + if($uid) { + $sql = str_replace('%{uid}', $this->_escape($uid), $this->getConf('delUserRefs')); $this->_modifyDB($sql); - $sql = str_replace('%{uid}',$this->_escape($uid),$this->cnf['delUser']); - $sql = str_replace('%{user}', $this->_escape($user),$sql); + $sql = str_replace('%{uid}', $this->_escape($uid), $this->getConf('delUser')); + $sql = str_replace('%{user}', $this->_escape($user), $sql); $this->_modifyDB($sql); return true; } @@ -624,17 +625,16 @@ class auth_mysql extends auth_basic { * must already be established for this function to work. * Otherwise it will return 'false'. * - * @param $user user's nick to get data for - * @return bool false on error - * @return array user info on success - * * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> + * + * @param string $user user's nick to get data for + * @return bool|array false on error, user info on success */ - function _getUserInfo($user){ - $sql = str_replace('%{user}',$this->_escape($user),$this->cnf['getUserInfo']); + protected function _getUserInfo($user) { + $sql = str_replace('%{user}', $this->_escape($user), $this->getConf('getUserInfo')); $result = $this->_queryDB($sql); if($result !== false && count($result)) { - $info = $result[0]; + $info = $result[0]; $info['grps'] = $this->_getGroups($user); return $info; } @@ -654,43 +654,43 @@ class auth_mysql extends auth_basic { * * The password will be crypted if necessary. * - * @param $changes array of items to change as pairs of item and value - * @param $uid user id of dataset to change, must be unique in DB - * @return true on success or false on error + * @param array $changes array of items to change as pairs of item and value + * @param mixed $uid user id of dataset to change, must be unique in DB + * @return bool true on success or false on error * * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> */ - function _updateUserInfo($changes, $uid) { - $sql = $this->cnf['updateUser']." "; + protected function _updateUserInfo($changes, $uid) { + $sql = $this->getConf('updateUser')." "; $cnt = 0; $err = 0; if($this->dbcon) { - foreach ($changes as $item => $value) { - if ($item == 'user') { - if (($this->_getUserID($changes['user']))) { + foreach($changes as $item => $value) { + if($item == 'user') { + if(($this->_getUserID($changes['user']))) { $err = 1; /* new username already exists */ - break; /* abort update */ + break; /* abort update */ } - if ($cnt++ > 0) $sql .= ", "; - $sql .= str_replace('%{user}',$value,$this->cnf['UpdateLogin']); - } else if ($item == 'name') { - if ($cnt++ > 0) $sql .= ", "; - $sql .= str_replace('%{name}',$value,$this->cnf['UpdateName']); - } else if ($item == 'pass') { - if (!$this->cnf['forwardClearPass']) + if($cnt++ > 0) $sql .= ", "; + $sql .= str_replace('%{user}', $value, $this->getConf('UpdateLogin')); + } else if($item == 'name') { + if($cnt++ > 0) $sql .= ", "; + $sql .= str_replace('%{name}', $value, $this->getConf('UpdateName')); + } else if($item == 'pass') { + if(!$this->getConf('forwardClearPass')) $value = auth_cryptPassword($value); - if ($cnt++ > 0) $sql .= ", "; - $sql .= str_replace('%{pass}',$value,$this->cnf['UpdatePass']); - } else if ($item == 'mail') { - if ($cnt++ > 0) $sql .= ", "; - $sql .= str_replace('%{email}',$value,$this->cnf['UpdateEmail']); + if($cnt++ > 0) $sql .= ", "; + $sql .= str_replace('%{pass}', $value, $this->getConf('UpdatePass')); + } else if($item == 'mail') { + if($cnt++ > 0) $sql .= ", "; + $sql .= str_replace('%{email}', $value, $this->getConf('UpdateEmail')); } } - if ($err == 0) { - if ($cnt > 0) { - $sql .= " ".str_replace('%{uid}', $uid, $this->cnf['UpdateTarget']); + if($err == 0) { + if($cnt > 0) { + $sql .= " ".str_replace('%{uid}', $uid, $this->getConf('UpdateTarget')); if(get_class($this) == 'auth_mysql') $sql .= " LIMIT 1"; //some PgSQL inheritance comp. $this->_modifyDB($sql); } @@ -705,16 +705,16 @@ class auth_mysql extends auth_basic { * * The database connection must already be established * for this function to work. Otherwise it will return - * 'false'. - * - * @param $group group name which id is desired - * @return group id + * false. * * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> + * + * @param string $group group name which id is desired + * @return mixed group id */ - function _getGroupID($group) { + protected function _getGroupID($group) { if($this->dbcon) { - $sql = str_replace('%{group}',$this->_escape($group),$this->cnf['getGroupID']); + $sql = str_replace('%{group}', $this->_escape($group), $this->getConf('getGroupID')); $result = $this->_queryDB($sql); return $result === false ? false : $result[0]['id']; } @@ -726,37 +726,39 @@ class auth_mysql extends auth_basic { * usage in the object. The successful call to this functions is * essential for most functions in this object. * - * @return bool - * * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> + * + * @return bool */ - function _openDB() { - if (!$this->dbcon) { - $con = @mysql_connect ($this->cnf['server'], $this->cnf['user'], $this->cnf['password']); - if ($con) { - if ((mysql_select_db($this->cnf['database'], $con))) { - if ((preg_match("/^(\d+)\.(\d+)\.(\d+).*/", mysql_get_server_info ($con), $result)) == 1) { + protected function _openDB() { + if(!$this->dbcon) { + $con = @mysql_connect($this->getConf('server'), $this->getConf('user'), $this->getConf('password')); + if($con) { + if((mysql_select_db($this->getConf('database'), $con))) { + if((preg_match('/^(\d+)\.(\d+)\.(\d+).*/', mysql_get_server_info($con), $result)) == 1) { $this->dbver = $result[1]; $this->dbrev = $result[2]; $this->dbsub = $result[3]; } $this->dbcon = $con; - if(!empty($this->cnf['charset'])){ - mysql_query('SET CHARACTER SET "' . $this->cnf['charset'] . '"', $con); + if($this->getConf('charset')) { + mysql_query('SET CHARACTER SET "'.$this->getConf('charset').'"', $con); } - return true; // connection and database successfully opened + return true; // connection and database successfully opened } else { - mysql_close ($con); - if ($this->cnf['debug']) - msg("MySQL err: No access to database {$this->cnf['database']}.",-1,__LINE__,__FILE__); + mysql_close($con); + $this->_debug("MySQL err: No access to database {$this->getConf('database')}.", -1, __LINE__, __FILE__); } - } else if ($this->cnf['debug']) - msg ("MySQL err: Connection to {$this->cnf['user']}@{$this->cnf['server']} not possible.", - -1,__LINE__,__FILE__); + } else { + $this->_debug( + "MySQL err: Connection to {$this->getConf('user')}@{$this->getConf('server')} not possible.", + -1, __LINE__, __FILE__ + ); + } - return false; // connection failed + return false; // connection failed } - return true; // connection already open + return true; // connection already open } /** @@ -764,9 +766,9 @@ class auth_mysql extends auth_basic { * * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> */ - function _closeDB() { - if ($this->dbcon) { - mysql_close ($this->dbcon); + protected function _closeDB() { + if($this->dbcon) { + mysql_close($this->dbcon); $this->dbcon = 0; } } @@ -778,27 +780,26 @@ class auth_mysql extends auth_basic { * This function is only able to handle queries that returns a * table such as SELECT. * - * @param $query SQL string that contains the query - * @return array with the result table - * * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> + * + * @param string $query SQL string that contains the query + * @return array with the result table */ - function _queryDB($query) { - if($this->cnf['debug'] >= 2){ - msg('MySQL query: '.hsc($query),0,__LINE__,__FILE__); + protected function _queryDB($query) { + if($this->getConf('debug') >= 2) { + msg('MySQL query: '.hsc($query), 0, __LINE__, __FILE__); } $resultarray = array(); - if ($this->dbcon) { - $result = @mysql_query($query,$this->dbcon); - if ($result) { - while (($t = mysql_fetch_assoc($result)) !== false) - $resultarray[]=$t; - mysql_free_result ($result); + if($this->dbcon) { + $result = @mysql_query($query, $this->dbcon); + if($result) { + while(($t = mysql_fetch_assoc($result)) !== false) + $resultarray[] = $t; + mysql_free_result($result); return $resultarray; } - if ($this->cnf['debug']) - msg('MySQL err: '.mysql_error($this->dbcon),-1,__LINE__,__FILE__); + $this->_debug('MySQL err: '.mysql_error($this->dbcon), -1, __LINE__, __FILE__); } return false; } @@ -809,20 +810,19 @@ class auth_mysql extends auth_basic { * This function is only able to handle queries that returns * either nothing or an id value such as INPUT, DELETE, UPDATE, etc. * - * @param $query SQL string that contains the query - * @return insert id or 0, false on error - * * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> + * + * @param string $query SQL string that contains the query + * @return int|bool insert id or 0, false on error */ - function _modifyDB($query) { - if ($this->dbcon) { - $result = @mysql_query($query,$this->dbcon); - if ($result) { + protected function _modifyDB($query) { + if($this->dbcon) { + $result = @mysql_query($query, $this->dbcon); + if($result) { $rc = mysql_insert_id($this->dbcon); //give back ID on insert - if ($rc !== false) return $rc; + if($rc !== false) return $rc; } - if ($this->cnf['debug']) - msg('MySQL err: '.mysql_error($this->dbcon),-1,__LINE__,__FILE__); + $this->_debug('MySQL err: '.mysql_error($this->dbcon), -1, __LINE__, __FILE__); } return false; } @@ -841,18 +841,19 @@ class auth_mysql extends auth_basic { * so that this functionality is simulated by this function. Nevertheless * it is not as powerful as transactions, it is a good compromise in safty. * - * @param $mode could be 'READ' or 'WRITE' - * * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> + * + * @param string $mode could be 'READ' or 'WRITE' + * @return bool */ - function _lockTables($mode) { - if ($this->dbcon) { - if (is_array($this->cnf['TablesToLock']) && !empty($this->cnf['TablesToLock'])) { - if ($mode == "READ" || $mode == "WRITE") { + protected function _lockTables($mode) { + if($this->dbcon) { + if(is_array($this->getConf('TablesToLock'))) { + if($mode == "READ" || $mode == "WRITE") { $sql = "LOCK TABLES "; $cnt = 0; - foreach ($this->cnf['TablesToLock'] as $table) { - if ($cnt++ != 0) $sql .= ", "; + foreach($this->getConf('TablesToLock') as $table) { + if($cnt++ != 0) $sql .= ", "; $sql .= "$table $mode"; } $this->_modifyDB($sql); @@ -869,8 +870,8 @@ class auth_mysql extends auth_basic { * * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> */ - function _unlockTables() { - if ($this->dbcon) { + protected function _unlockTables() { + if($this->dbcon) { $this->_modifyDB("UNLOCK TABLES"); return true; } @@ -882,32 +883,31 @@ class auth_mysql extends auth_basic { * The database connection must already be established, otherwise the * original SQL string without filter criteria will be returned. * - * @param $sql SQL string to which the $filter criteria should be added - * @param $filter array of filter criteria as pairs of item and pattern - * @return SQL string with attached $filter criteria on success - * @return the original SQL string on error. - * * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> + * + * @param string $sql SQL string to which the $filter criteria should be added + * @param array $filter array of filter criteria as pairs of item and pattern + * @return string SQL string with attached $filter criteria on success, original SQL string on error */ - function _createSQLFilter($sql, $filter) { + protected function _createSQLFilter($sql, $filter) { $SQLfilter = ""; - $cnt = 0; + $cnt = 0; - if ($this->dbcon) { - foreach ($filter as $item => $pattern) { + if($this->dbcon) { + foreach($filter as $item => $pattern) { $tmp = '%'.$this->_escape($pattern).'%'; - if ($item == 'user') { - if ($cnt++ > 0) $SQLfilter .= " AND "; - $SQLfilter .= str_replace('%{user}',$tmp,$this->cnf['FilterLogin']); - } else if ($item == 'name') { - if ($cnt++ > 0) $SQLfilter .= " AND "; - $SQLfilter .= str_replace('%{name}',$tmp,$this->cnf['FilterName']); - } else if ($item == 'mail') { - if ($cnt++ > 0) $SQLfilter .= " AND "; - $SQLfilter .= str_replace('%{email}',$tmp,$this->cnf['FilterEmail']); - } else if ($item == 'grps') { - if ($cnt++ > 0) $SQLfilter .= " AND "; - $SQLfilter .= str_replace('%{group}',$tmp,$this->cnf['FilterGroup']); + if($item == 'user') { + if($cnt++ > 0) $SQLfilter .= " AND "; + $SQLfilter .= str_replace('%{user}', $tmp, $this->getConf('FilterLogin')); + } else if($item == 'name') { + if($cnt++ > 0) $SQLfilter .= " AND "; + $SQLfilter .= str_replace('%{name}', $tmp, $this->getConf('FilterName')); + } else if($item == 'mail') { + if($cnt++ > 0) $SQLfilter .= " AND "; + $SQLfilter .= str_replace('%{email}', $tmp, $this->getConf('FilterEmail')); + } else if($item == 'grps') { + if($cnt++ > 0) $SQLfilter .= " AND "; + $SQLfilter .= str_replace('%{group}', $tmp, $this->getConf('FilterGroup')); } } @@ -915,9 +915,9 @@ class auth_mysql extends auth_basic { // any of cnf['Filter????'] is not defined, a malformed SQL string // would be generated. - if (strlen($SQLfilter)) { - $glue = strpos(strtolower($sql),"where") ? " AND " : " WHERE "; - $sql = $sql.$glue.$SQLfilter; + if(strlen($SQLfilter)) { + $glue = strpos(strtolower($sql), "where") ? " AND " : " WHERE "; + $sql = $sql.$glue.$SQLfilter; } } @@ -928,20 +928,34 @@ class auth_mysql extends auth_basic { * Escape a string for insertion into the database * * @author Andreas Gohr <andi@splitbrain.org> + * * @param string $string The string to escape * @param boolean $like Escape wildcard chars as well? + * @return string */ - function _escape($string,$like=false){ - if($this->dbcon){ + protected function _escape($string, $like = false) { + if($this->dbcon) { $string = mysql_real_escape_string($string, $this->dbcon); - }else{ + } else { $string = addslashes($string); } - if($like){ - $string = addcslashes($string,'%_'); + if($like) { + $string = addcslashes($string, '%_'); } return $string; } -} -//Setup VIM: ex: et ts=2 : + /** + * Wrapper around msg() but outputs only when debug is enabled + * + * @param string $message + * @param int $err + * @param int $line + * @param string $file + * @return void + */ + protected function _debug($message, $err, $line, $file) { + if(!$this->getConf('debug')) return; + msg($message, $err, $line, $file); + } +} diff --git a/lib/plugins/authmysql/conf/default.php b/lib/plugins/authmysql/conf/default.php new file mode 100644 index 000000000..ea2cdad72 --- /dev/null +++ b/lib/plugins/authmysql/conf/default.php @@ -0,0 +1,3 @@ +<?php + +$conf['charset'] = 'utf8';
\ No newline at end of file diff --git a/lib/plugins/authmysql/plugin.info.txt b/lib/plugins/authmysql/plugin.info.txt new file mode 100644 index 000000000..c1e118427 --- /dev/null +++ b/lib/plugins/authmysql/plugin.info.txt @@ -0,0 +1,7 @@ +base authmysql +author Andreas Gohr +email andi@splitbrain.org +date 2012-10-06 +name mysql auth plugin +desc Provides authentication against a MySQL Server +url http://www.dokuwiki.org/plugin:authmysql diff --git a/lib/plugins/authpgsql/auth.php b/lib/plugins/authpgsql/auth.php new file mode 100644 index 000000000..3f8ff3249 --- /dev/null +++ b/lib/plugins/authpgsql/auth.php @@ -0,0 +1,418 @@ +<?php +// must be run within Dokuwiki +if(!defined('DOKU_INC')) die(); + +/** + * PostgreSQL authentication backend + * + * This class inherits much functionality from the MySQL class + * and just reimplements the Postgres specific parts. + * + * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) + * @author Andreas Gohr <andi@splitbrain.org> + * @author Chris Smith <chris@jalakai.co.uk> + * @author Matthias Grimm <matthias.grimmm@sourceforge.net> + * @author Jan Schumann <js@schumann-it.com> + */ +class auth_plugin_authpgsql extends auth_plugin_authmysql { + + /** + * Constructor + * + * checks if the pgsql interface is available, otherwise it will + * set the variable $success of the basis class to false + * + * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> + * @author Andreas Gohr <andi@splitbrain.org> + */ + public function __construct() { + // we don't want the stuff the MySQL constructor does, but the grandparent might do something + DokuWiki_Auth_Plugin::__construct(); + + if(!function_exists('pg_connect')) { + $this->_debug("PgSQL err: PHP Postgres extension not found.", -1, __LINE__, __FILE__); + $this->success = false; + return; + } + + $this->loadConfig(); + + // set capabilities based upon config strings set + if(empty($this->conf['user']) || + empty($this->conf['password']) || empty($this->conf['database']) + ) { + $this->_debug("PgSQL err: insufficient configuration.", -1, __LINE__, __FILE__); + $this->success = false; + return; + } + + $this->cando['addUser'] = $this->_chkcnf( + array( + 'getUserInfo', + 'getGroups', + 'addUser', + 'getUserID', + 'getGroupID', + 'addGroup', + 'addUserGroup' + ) + ); + $this->cando['delUser'] = $this->_chkcnf( + array( + 'getUserID', + 'delUser', + 'delUserRefs' + ) + ); + $this->cando['modLogin'] = $this->_chkcnf( + array( + 'getUserID', + 'updateUser', + 'UpdateTarget' + ) + ); + $this->cando['modPass'] = $this->cando['modLogin']; + $this->cando['modName'] = $this->cando['modLogin']; + $this->cando['modMail'] = $this->cando['modLogin']; + $this->cando['modGroups'] = $this->_chkcnf( + array( + 'getUserID', + 'getGroups', + 'getGroupID', + 'addGroup', + 'addUserGroup', + 'delGroup', + 'getGroupID', + 'delUserGroup' + ) + ); + /* getGroups is not yet supported + $this->cando['getGroups'] = $this->_chkcnf(array('getGroups', + 'getGroupID')); */ + $this->cando['getUsers'] = $this->_chkcnf( + array( + 'getUsers', + 'getUserInfo', + 'getGroups' + ) + ); + $this->cando['getUserCount'] = $this->_chkcnf(array('getUsers')); + } + + /** + * Check if the given config strings are set + * + * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> + * + * @param array $keys + * @param bool $wop + * @return bool + */ + protected function _chkcnf($keys, $wop = false) { + foreach($keys as $key) { + if(empty($this->conf[$key])) return false; + } + return true; + } + + /** + * Counts users which meet certain $filter criteria. + * + * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> + * + * @param array $filter filter criteria in item/pattern pairs + * @return int count of found users. + */ + public function getUserCount($filter = array()) { + $rc = 0; + + if($this->_openDB()) { + $sql = $this->_createSQLFilter($this->conf['getUsers'], $filter); + + // no equivalent of SQL_CALC_FOUND_ROWS in pgsql? + if(($result = $this->_queryDB($sql))) { + $rc = count($result); + } + $this->_closeDB(); + } + return $rc; + } + + /** + * Bulk retrieval of user data + * + * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> + * + * @param int $first index of first user to be returned + * @param int $limit max number of users to be returned + * @param array $filter array of field/pattern pairs + * @return array userinfo (refer getUserData for internal userinfo details) + */ + public function retrieveUsers($first = 0, $limit = 10, $filter = array()) { + $out = array(); + + if($this->_openDB()) { + $this->_lockTables("READ"); + $sql = $this->_createSQLFilter($this->conf['getUsers'], $filter); + $sql .= " ".$this->conf['SortOrder']." LIMIT $limit OFFSET $first"; + $result = $this->_queryDB($sql); + + foreach($result as $user) + if(($info = $this->_getUserInfo($user['user']))) + $out[$user['user']] = $info; + + $this->_unlockTables(); + $this->_closeDB(); + } + return $out; + } + + // @inherit function joinGroup($user, $group) + // @inherit function leaveGroup($user, $group) { + + /** + * Adds a user to a group. + * + * If $force is set to true non existing groups would be created. + * + * The database connection must already be established. Otherwise + * this function does nothing and returns 'false'. + * + * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> + * @author Andreas Gohr <andi@splitbrain.org> + * + * @param string $user user to add to a group + * @param string $group name of the group + * @param bool $force create missing groups + * @return bool true on success, false on error + */ + protected function _addUserToGroup($user, $group, $force = false) { + $newgroup = 0; + + if(($this->dbcon) && ($user)) { + $gid = $this->_getGroupID($group); + if(!$gid) { + if($force) { // create missing groups + $sql = str_replace('%{group}', addslashes($group), $this->conf['addGroup']); + $this->_modifyDB($sql); + //group should now exists try again to fetch it + $gid = $this->_getGroupID($group); + $newgroup = 1; // group newly created + } + } + if(!$gid) return false; // group didn't exist and can't be created + + $sql = $this->conf['addUserGroup']; + if(strpos($sql, '%{uid}') !== false) { + $uid = $this->_getUserID($user); + $sql = str_replace('%{uid}', addslashes($uid), $sql); + } + $sql = str_replace('%{user}', addslashes($user), $sql); + $sql = str_replace('%{gid}', addslashes($gid), $sql); + $sql = str_replace('%{group}', addslashes($group), $sql); + if($this->_modifyDB($sql) !== false) return true; + + if($newgroup) { // remove previously created group on error + $sql = str_replace('%{gid}', addslashes($gid), $this->conf['delGroup']); + $sql = str_replace('%{group}', addslashes($group), $sql); + $this->_modifyDB($sql); + } + } + return false; + } + + // @inherit function _delUserFromGroup($user $group) + // @inherit function _getGroups($user) + // @inherit function _getUserID($user) + + /** + * Adds a new User to the database. + * + * The database connection must already be established + * for this function to work. Otherwise it will return + * 'false'. + * + * @param string $user login of the user + * @param string $pwd encrypted password + * @param string $name full name of the user + * @param string $mail email address + * @param array $grps array of groups the user should become member of + * @return bool + * + * @author Andreas Gohr <andi@splitbrain.org> + * @author Chris Smith <chris@jalakai.co.uk> + * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> + */ + protected function _addUser($user, $pwd, $name, $mail, $grps) { + if($this->dbcon && is_array($grps)) { + $sql = str_replace('%{user}', addslashes($user), $this->conf['addUser']); + $sql = str_replace('%{pass}', addslashes($pwd), $sql); + $sql = str_replace('%{name}', addslashes($name), $sql); + $sql = str_replace('%{email}', addslashes($mail), $sql); + if($this->_modifyDB($sql)) { + $uid = $this->_getUserID($user); + } else { + return false; + } + + $group = ''; + $gid = false; + + if($uid) { + foreach($grps as $group) { + $gid = $this->_addUserToGroup($user, $group, 1); + if($gid === false) break; + } + + if($gid !== false){ + return true; + } else { + /* remove the new user and all group relations if a group can't + * be assigned. Newly created groups will remain in the database + * and won't be removed. This might create orphaned groups but + * is not a big issue so we ignore this problem here. + */ + $this->_delUser($user); + $this->_debug("PgSQL err: Adding user '$user' to group '$group' failed.", -1, __LINE__, __FILE__); + } + } + } + return false; + } + + /** + * Opens a connection to a database and saves the handle for further + * usage in the object. The successful call to this functions is + * essential for most functions in this object. + * + * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> + * + * @return bool + */ + protected function _openDB() { + if(!$this->dbcon) { + $dsn = $this->conf['server'] ? 'host='.$this->conf['server'] : ''; + $dsn .= ' port='.$this->conf['port']; + $dsn .= ' dbname='.$this->conf['database']; + $dsn .= ' user='.$this->conf['user']; + $dsn .= ' password='.$this->conf['password']; + + $con = @pg_connect($dsn); + if($con) { + $this->dbcon = $con; + return true; // connection and database successfully opened + } else { + $this->_debug( + "PgSQL err: Connection to {$this->conf['user']}@{$this->conf['server']} not possible.", + -1, __LINE__, __FILE__ + ); + } + return false; // connection failed + } + return true; // connection already open + } + + /** + * Closes a database connection. + * + * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> + */ + protected function _closeDB() { + if($this->dbcon) { + pg_close($this->dbcon); + $this->dbcon = 0; + } + } + + /** + * Sends a SQL query to the database and transforms the result into + * an associative array. + * + * This function is only able to handle queries that returns a + * table such as SELECT. + * + * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> + * + * @param string $query SQL string that contains the query + * @return array the result table + */ + protected function _queryDB($query) { + $resultarray = array(); + if($this->dbcon) { + $result = @pg_query($this->dbcon, $query); + if($result) { + while(($t = pg_fetch_assoc($result)) !== false) + $resultarray[] = $t; + pg_free_result($result); + return $resultarray; + } else{ + $this->_debug('PgSQL err: '.pg_last_error($this->dbcon), -1, __LINE__, __FILE__); + } + } + return false; + } + + /** + * Executes an update or insert query. This differs from the + * MySQL one because it does NOT return the last insertID + * + * @author Andreas Gohr <andi@splitbrain.org> + */ + protected function _modifyDB($query) { + if($this->dbcon) { + $result = @pg_query($this->dbcon, $query); + if($result) { + pg_free_result($result); + return true; + } + $this->_debug('PgSQL err: '.pg_last_error($this->dbcon), -1, __LINE__, __FILE__); + } + return false; + } + + /** + * Start a transaction + * + * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> + * + * @param string $mode could be 'READ' or 'WRITE' + * @return bool + */ + protected function _lockTables($mode) { + if($this->dbcon) { + $this->_modifyDB('BEGIN'); + return true; + } + return false; + } + + /** + * Commit a transaction + * + * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> + */ + protected function _unlockTables() { + if($this->dbcon) { + $this->_modifyDB('COMMIT'); + return true; + } + return false; + } + + /** + * Escape a string for insertion into the database + * + * @author Andreas Gohr <andi@splitbrain.org> + * + * @param string $string The string to escape + * @param bool $like Escape wildcard chars as well? + * @return string + */ + protected function _escape($string, $like = false) { + $string = pg_escape_string($string); + if($like) { + $string = addcslashes($string, '%_'); + } + return $string; + } +}
\ No newline at end of file diff --git a/lib/plugins/authpgsql/conf/default.php b/lib/plugins/authpgsql/conf/default.php new file mode 100644 index 000000000..401da80b7 --- /dev/null +++ b/lib/plugins/authpgsql/conf/default.php @@ -0,0 +1,3 @@ +<?php + +$conf['port'] = 5432;
\ No newline at end of file diff --git a/lib/plugins/authpgsql/plugin.info.txt b/lib/plugins/authpgsql/plugin.info.txt new file mode 100644 index 000000000..598eb848b --- /dev/null +++ b/lib/plugins/authpgsql/plugin.info.txt @@ -0,0 +1,7 @@ +base authad +author Andreas Gohr +email andi@splitbrain.org +date 2012-10-06 +name active directory auth plugin +desc Provides authentication against a Microsoft Active Directory +url http://www.dokuwiki.org/plugin:authad diff --git a/lib/plugins/authplain/auth.php b/lib/plugins/authplain/auth.php new file mode 100644 index 000000000..3416ede89 --- /dev/null +++ b/lib/plugins/authplain/auth.php @@ -0,0 +1,358 @@ +<?php +// must be run within Dokuwiki +if(!defined('DOKU_INC')) die(); + +/** + * Plaintext authentication backend + * + * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) + * @author Andreas Gohr <andi@splitbrain.org> + * @author Chris Smith <chris@jalakai.co.uk> + * @author Jan Schumann <js@schumann-it.com> + */ +class auth_plugin_authplain extends DokuWiki_Auth_Plugin { + /** @var array user cache */ + protected $users = null; + + /** @var array filter pattern */ + protected $_pattern = array(); + + /** + * Constructor + * + * Carry out sanity checks to ensure the object is + * able to operate. Set capabilities. + * + * @author Christopher Smith <chris@jalakai.co.uk> + */ + public function __construct() { + parent::__construct(); + global $config_cascade; + + if(!@is_readable($config_cascade['plainauth.users']['default'])) { + $this->success = false; + } else { + if(@is_writable($config_cascade['plainauth.users']['default'])) { + $this->cando['addUser'] = true; + $this->cando['delUser'] = true; + $this->cando['modLogin'] = true; + $this->cando['modPass'] = true; + $this->cando['modName'] = true; + $this->cando['modMail'] = true; + $this->cando['modGroups'] = true; + } + $this->cando['getUsers'] = true; + $this->cando['getUserCount'] = true; + } + } + + /** + * Check user+password + * + * Checks if the given user exists and the given + * plaintext password is correct + * + * @author Andreas Gohr <andi@splitbrain.org> + * @param string $user + * @param string $pass + * @return bool + */ + public function checkPass($user, $pass) { + $userinfo = $this->getUserData($user); + if($userinfo === false) return false; + + return auth_verifyPassword($pass, $this->users[$user]['pass']); + } + + /** + * Return user info + * + * Returns info about the given user needs to contain + * at least these fields: + * + * name string full name of the user + * mail string email addres of the user + * grps array list of groups the user is in + * + * @author Andreas Gohr <andi@splitbrain.org> + * @param string $user + * @return array|bool + */ + public function getUserData($user) { + if($this->users === null) $this->_loadUserData(); + return isset($this->users[$user]) ? $this->users[$user] : false; + } + + /** + * Create a new User + * + * Returns false if the user already exists, null when an error + * occurred and true if everything went well. + * + * The new user will be added to the default group by this + * function if grps are not specified (default behaviour). + * + * @author Andreas Gohr <andi@splitbrain.org> + * @author Chris Smith <chris@jalakai.co.uk> + * + * @param string $user + * @param string $pwd + * @param string $name + * @param string $mail + * @param array $grps + * @return bool|null|string + */ + public function createUser($user, $pwd, $name, $mail, $grps = null) { + global $conf; + global $config_cascade; + + // user mustn't already exist + if($this->getUserData($user) !== false) return false; + + $pass = auth_cryptPassword($pwd); + + // set default group if no groups specified + if(!is_array($grps)) $grps = array($conf['defaultgroup']); + + // prepare user line + $groups = join(',', $grps); + $userline = join(':', array($user, $pass, $name, $mail, $groups))."\n"; + + if(io_saveFile($config_cascade['plainauth.users']['default'], $userline, true)) { + $this->users[$user] = compact('pass', 'name', 'mail', 'grps'); + return $pwd; + } + + msg( + 'The '.$config_cascade['plainauth.users']['default']. + ' file is not writable. Please inform the Wiki-Admin', -1 + ); + return null; + } + + /** + * Modify user data + * + * @author Chris Smith <chris@jalakai.co.uk> + * @param string $user nick of the user to be changed + * @param array $changes array of field/value pairs to be changed (password will be clear text) + * @return bool + */ + public function modifyUser($user, $changes) { + global $ACT; + global $config_cascade; + + // sanity checks, user must already exist and there must be something to change + if(($userinfo = $this->getUserData($user)) === false) return false; + if(!is_array($changes) || !count($changes)) return true; + + // update userinfo with new data, remembering to encrypt any password + $newuser = $user; + foreach($changes as $field => $value) { + if($field == 'user') { + $newuser = $value; + continue; + } + if($field == 'pass') $value = auth_cryptPassword($value); + $userinfo[$field] = $value; + } + + $groups = join(',', $userinfo['grps']); + $userline = join(':', array($newuser, $userinfo['pass'], $userinfo['name'], $userinfo['mail'], $groups))."\n"; + + if(!$this->deleteUsers(array($user))) { + msg('Unable to modify user data. Please inform the Wiki-Admin', -1); + return false; + } + + if(!io_saveFile($config_cascade['plainauth.users']['default'], $userline, true)) { + msg('There was an error modifying your user data. You should register again.', -1); + // FIXME, user has been deleted but not recreated, should force a logout and redirect to login page + $ACT = 'register'; + return false; + } + + $this->users[$newuser] = $userinfo; + return true; + } + + /** + * Remove one or more users from the list of registered users + * + * @author Christopher Smith <chris@jalakai.co.uk> + * @param array $users array of users to be deleted + * @return int the number of users deleted + */ + public function deleteUsers($users) { + global $config_cascade; + + if(!is_array($users) || empty($users)) return 0; + + if($this->users === null) $this->_loadUserData(); + + $deleted = array(); + foreach($users as $user) { + if(isset($this->users[$user])) $deleted[] = preg_quote($user, '/'); + } + + if(empty($deleted)) return 0; + + $pattern = '/^('.join('|', $deleted).'):/'; + + if(io_deleteFromFile($config_cascade['plainauth.users']['default'], $pattern, true)) { + foreach($deleted as $user) unset($this->users[$user]); + return count($deleted); + } + + // problem deleting, reload the user list and count the difference + $count = count($this->users); + $this->_loadUserData(); + $count -= count($this->users); + return $count; + } + + /** + * Return a count of the number of user which meet $filter criteria + * + * @author Chris Smith <chris@jalakai.co.uk> + * + * @param array $filter + * @return int + */ + public function getUserCount($filter = array()) { + + if($this->users === null) $this->_loadUserData(); + + if(!count($filter)) return count($this->users); + + $count = 0; + $this->_constructPattern($filter); + + foreach($this->users as $user => $info) { + $count += $this->_filter($user, $info); + } + + return $count; + } + + /** + * Bulk retrieval of user data + * + * @author Chris Smith <chris@jalakai.co.uk> + * + * @param int $start index of first user to be returned + * @param int $limit max number of users to be returned + * @param array $filter array of field/pattern pairs + * @return array userinfo (refer getUserData for internal userinfo details) + */ + public function retrieveUsers($start = 0, $limit = 0, $filter = array()) { + + if($this->users === null) $this->_loadUserData(); + + ksort($this->users); + + $i = 0; + $count = 0; + $out = array(); + $this->_constructPattern($filter); + + foreach($this->users as $user => $info) { + if($this->_filter($user, $info)) { + if($i >= $start) { + $out[$user] = $info; + $count++; + if(($limit > 0) && ($count >= $limit)) break; + } + $i++; + } + } + + return $out; + } + + /** + * Only valid pageid's (no namespaces) for usernames + * + * @param string $user + * @return string + */ + public function cleanUser($user) { + global $conf; + return cleanID(str_replace(':', $conf['sepchar'], $user)); + } + + /** + * Only valid pageid's (no namespaces) for groupnames + * + * @param string $group + * @return string + */ + public function cleanGroup($group) { + global $conf; + return cleanID(str_replace(':', $conf['sepchar'], $group)); + } + + /** + * Load all user data + * + * loads the user file into a datastructure + * + * @author Andreas Gohr <andi@splitbrain.org> + */ + protected function _loadUserData() { + global $config_cascade; + + $this->users = array(); + + if(!@file_exists($config_cascade['plainauth.users']['default'])) return; + + $lines = file($config_cascade['plainauth.users']['default']); + foreach($lines as $line) { + $line = preg_replace('/#.*$/', '', $line); //ignore comments + $line = trim($line); + if(empty($line)) continue; + + $row = explode(":", $line, 5); + $groups = array_values(array_filter(explode(",", $row[4]))); + + $this->users[$row[0]]['pass'] = $row[1]; + $this->users[$row[0]]['name'] = urldecode($row[2]); + $this->users[$row[0]]['mail'] = $row[3]; + $this->users[$row[0]]['grps'] = $groups; + } + } + + /** + * return true if $user + $info match $filter criteria, false otherwise + * + * @author Chris Smith <chris@jalakai.co.uk> + * + * @param string $user User login + * @param array $info User's userinfo array + * @return bool + */ + protected function _filter($user, $info) { + foreach($this->_pattern as $item => $pattern) { + if($item == 'user') { + if(!preg_match($pattern, $user)) return false; + } else if($item == 'grps') { + if(!count(preg_grep($pattern, $info['grps']))) return false; + } else { + if(!preg_match($pattern, $info[$item])) return false; + } + } + return true; + } + + /** + * construct a filter pattern + * + * @param array $filter + */ + protected function _constructPattern($filter) { + $this->_pattern = array(); + foreach($filter as $item => $pattern) { + $this->_pattern[$item] = '/'.str_replace('/', '\/', $pattern).'/i'; // allow regex characters + } + } +}
\ No newline at end of file diff --git a/lib/plugins/authplain/plugin.info.txt b/lib/plugins/authplain/plugin.info.txt new file mode 100644 index 000000000..cde38eaac --- /dev/null +++ b/lib/plugins/authplain/plugin.info.txt @@ -0,0 +1,7 @@ +base authplain +author Andreas Gohr +email andi@splitbrain.org +date 2012-10-06 +name auth plugin +desc Provides authentication against local password storage +url http://www.dokuwiki.org/plugin:authplain diff --git a/lib/plugins/config/admin.php b/lib/plugins/config/admin.php index 0d314d2e6..4d15bfd85 100644 --- a/lib/plugins/config/admin.php +++ b/lib/plugins/config/admin.php @@ -65,8 +65,7 @@ class admin_plugin_config extends DokuWiki_Admin_Plugin { // save state & force a page reload to get the new settings to take effect $_SESSION['PLUGIN_CONFIG'] = array('state' => 'updated', 'time' => time()); $this->_close_session(); - header("Location: ".wl($ID,array('do'=>'admin','page'=>'config'),true,'&')); - exit(); + send_redirect(wl($ID,array('do'=>'admin','page'=>'config'),true,'&')); } $this->_close_session(); diff --git a/lib/plugins/config/settings/config.class.php b/lib/plugins/config/settings/config.class.php index 5a2aa2980..d4d98ee01 100644 --- a/lib/plugins/config/settings/config.class.php +++ b/lib/plugins/config/settings/config.class.php @@ -38,6 +38,7 @@ if (!class_exists('configuration')) { msg('No configuration metadata found at - '.htmlspecialchars($datafile),-1); return; } + $meta = array(); include($datafile); if (isset($config['varname'])) $this->_name = $config['varname']; @@ -65,6 +66,7 @@ if (!class_exists('configuration')) { $keys = array_merge(array_keys($this->_metadata),array_keys($default), array_keys($local), array_keys($protected)); $keys = array_unique($keys); + $param = null; foreach ($keys as $key) { if (isset($this->_metadata[$key])) { $class = $this->_metadata[$key][0]; @@ -399,7 +401,7 @@ if (!class_exists('setting')) { } $key = htmlspecialchars($this->_key); - $value = htmlspecialchars($value); + $value = formText($value); $label = '<label for="config___'.$key.'">'.$this->prompt($plugin).'</label>'; $input = '<textarea rows="3" cols="40" id="config___'.$key.'" name="config['.$key.']" class="edit" '.$disable.'>'.$value.'</textarea>'; @@ -419,7 +421,7 @@ if (!class_exists('setting')) { if ($fmt=='php') { $tr = array("\\" => '\\\\', "'" => '\\\''); - $out = '$'.$var."['".$this->_out_key()."'] = '".strtr($this->_local, $tr)."';\n"; + $out = '$'.$var."['".$this->_out_key()."'] = '".strtr( cleanText($this->_local), $tr)."';\n"; } return $out; diff --git a/lib/plugins/config/settings/extra.class.php b/lib/plugins/config/settings/extra.class.php index b4e35b1cc..6998e1fbf 100644 --- a/lib/plugins/config/settings/extra.class.php +++ b/lib/plugins/config/settings/extra.class.php @@ -43,17 +43,57 @@ if (!class_exists('setting_authtype')) { class setting_authtype extends setting_multichoice { function initialize($default,$local,$protected) { + global $plugin_controller; - // populate $this->_choices with a list of available auth mechanisms - $authtypes = glob(DOKU_INC.'inc/auth/*.class.php'); - $authtypes = preg_replace('#^.*/([^/]*)\.class\.php$#i','$1', $authtypes); - $authtypes = array_diff($authtypes, array('basic')); - sort($authtypes); - - $this->_choices = $authtypes; + // retrive auth types provided by plugins + foreach ($plugin_controller->getList('auth') as $plugin) { + $this->_choices[] = $plugin; + } parent::initialize($default,$local,$protected); } + + function update($input) { + global $plugin_controller; + + // is an update posible? + $mayUpdate = parent::update($input); + + // is it an auth plugin? + if (in_array($input, $plugin_controller->getList('auth'))) { + // reject disabled plugins + if ($plugin_controller->isdisabled($input)) { + $this->_error = true; + msg('Auth type ' . $input . ' is disabled.', -1); + return false; + } + + // load the plugin + $auth_plugin = $plugin_controller->load('auth', $input); + + // @TODO: throw an error in plugin controller instead of returning null + if (is_null($auth_plugin)) { + $this->_error = true; + msg('Cannot load Auth Plugin "' . $input . '"', -1); + return false; + } + + // verify proper instanciation (is this really a plugin?) @TODO use instanceof? impement interface? + if (is_object($auth_plugin) && !method_exists($auth_plugin, 'getPluginName')) { + $this->_error = true; + msg('Cannot create Auth Plugin "' . $input . '"', -1); + return false; + } + } + + // did we change the auth type? logout + global $conf; + if($conf['authtype'] != $input) { + msg('Authentication system changed. Please re-login.'); + auth_logoff(); + } + return true; + } } } diff --git a/lib/plugins/config/style.css b/lib/plugins/config/style.css index 1be94feb9..397328937 100644 --- a/lib/plugins/config/style.css +++ b/lib/plugins/config/style.css @@ -104,6 +104,10 @@ height: 4em; } +#config__manager td textarea.edit:focus { + height: 10em; +} + #config__manager tr .input, #config__manager tr input, #config__manager tr textarea, |