/** * LDAP Password Driver * * Driver for passwords stored in LDAP * This driver use the PEAR Net_LDAP2 class (http://pear.php.net/package/Net_LDAP2). * * @version 1.0 (2009-06-24) * @author Edouard MOREAU <*****@*****.**> * * function hashPassword based on code from the phpLDAPadmin development team (http://phpldapadmin.sourceforge.net/). * function randomSalt based on code from the phpLDAPadmin development team (http://phpldapadmin.sourceforge.net/). * */ function password_save($curpass, $passwd) { $rcmail = rcmail::get_instance(); require_once 'Net/LDAP2.php'; // Building user DN $userDN = str_replace('%login', $_SESSION['username'], $rcmail->config->get('password_ldap_userDN_mask')); $parts = explode('@', $_SESSION['username']); if (count($parts) == 2) { $userDN = str_replace('%name', $parts[0], $userDN); $userDN = str_replace('%domain', $parts[1], $userDN); } if (empty($userDN)) { return PASSWORD_CONNECT_ERROR; } // Connection Method switch ($rcmail->config->get('password_ldap_method')) { case 'user': $binddn = $userDN; $bindpw = $curpass; break; case 'admin': $binddn = $rcmail->config->get('password_ldap_adminDN'); $bindpw = $rcmail->config->get('password_ldap_adminPW'); break; default: $binddn = $userDN; $bindpw = $curpass; break; // default is user mode } // Configuration array $ldapConfig = array('binddn' => $binddn, 'bindpw' => $bindpw, 'basedn' => $rcmail->config->get('password_ldap_basedn'), 'host' => $rcmail->config->get('password_ldap_host'), 'port' => $rcmail->config->get('password_ldap_port'), 'starttls' => $rcmail->config->get('password_ldap_starttls'), 'version' => $rcmail->config->get('password_ldap_version')); // Connecting using the configuration array $ldap = Net_LDAP2::connect($ldapConfig); // Checking for connection error if (PEAR::isError($ldap)) { return PASSWORD_CONNECT_ERROR; } // Crypting new password $newCryptedPassword = hashPassword($passwd, $rcmail->config->get('password_ldap_encodage')); if (!$newCryptedPassword) { return PASSWORD_CRYPT_ERROR; } // Writing new crypted password to LDAP $userEntry = $ldap->getEntry($userDN); if (Net_LDAP2::isError($userEntry)) { return PASSWORD_CONNECT_ERROR; } if (!$userEntry->replace(array($rcmail->config->get('password_ldap_pwattr') => $newCryptedPassword), $rcmail->config->get('password_ldap_force_replace'))) { return PASSWORD_CONNECT_ERROR; } if (Net_LDAP2::isError($userEntry->update())) { return PASSWORD_CONNECT_ERROR; } // All done, no error return PASSWORD_SUCCESS; }
/** * LDAP Password Driver * * Driver for passwords stored in LDAP * This driver use the PEAR Net_LDAP2 class (http://pear.php.net/package/Net_LDAP2). * * @version 1.1 (2010-04-07) * @author Edouard MOREAU <*****@*****.**> * * function hashPassword based on code from the phpLDAPadmin development team (http://phpldapadmin.sourceforge.net/). * function randomSalt based on code from the phpLDAPadmin development team (http://phpldapadmin.sourceforge.net/). * */ function password_save($curpass, $passwd) { $rcmail = rcmail::get_instance(); require_once 'Net/LDAP2.php'; // Building user DN if ($userDN = $rcmail->config->get('password_ldap_userDN_mask')) { $userDN = substitute_vars($userDN); } else { $userDN = search_userdn($rcmail); } if (empty($userDN)) { return PASSWORD_CONNECT_ERROR; } // Connection Method switch ($rcmail->config->get('password_ldap_method')) { case 'admin': $binddn = $rcmail->config->get('password_ldap_adminDN'); $bindpw = $rcmail->config->get('password_ldap_adminPW'); break; case 'user': default: $binddn = $userDN; $bindpw = $curpass; break; } // Configuration array $ldapConfig = array('binddn' => $binddn, 'bindpw' => $bindpw, 'basedn' => $rcmail->config->get('password_ldap_basedn'), 'host' => $rcmail->config->get('password_ldap_host'), 'port' => $rcmail->config->get('password_ldap_port'), 'starttls' => $rcmail->config->get('password_ldap_starttls'), 'version' => $rcmail->config->get('password_ldap_version')); // Connecting using the configuration array $ldap = Net_LDAP2::connect($ldapConfig); // Checking for connection error if (PEAR::isError($ldap)) { return PASSWORD_CONNECT_ERROR; } // Crypting new password $newCryptedPassword = hashPassword($passwd, $rcmail->config->get('password_ldap_encodage')); if (!$newCryptedPassword) { return PASSWORD_CRYPT_ERROR; } // Writing new crypted password to LDAP $userEntry = $ldap->getEntry($userDN); if (Net_LDAP2::isError($userEntry)) { return PASSWORD_CONNECT_ERROR; } $pwattr = $rcmail->config->get('password_ldap_pwattr'); $force = $rcmail->config->get('password_ldap_force_replace'); if (!$userEntry->replace(array($pwattr => $newCryptedPassword), $force)) { return PASSWORD_CONNECT_ERROR; } if (Net_LDAP2::isError($userEntry->update())) { return PASSWORD_CONNECT_ERROR; } // All done, no error return PASSWORD_SUCCESS; }
/** * Execute the shutdown procedure. * * @throws <b>AgaviDatabaseException</b> If an error occurs while shutting * down this database. * * @author Bram Goessens <*****@*****.**> */ public function shutdown() { if ($this->connection != null) { @($result = $this->connection->done()); $this->connection = null; if (Net_LDAP2::isError($result)) { $error = 'Could not close KVDag_LdapDatabase connection'; throw new AgaviDatabaseException($error); } } }
/** * LDAP Password Driver * * Driver for passwords stored in LDAP * This driver use the PEAR Net_LDAP2 class (http://pear.php.net/package/Net_LDAP2). * * @version 1.1 (2010-04-07) * @author Edouard MOREAU <*****@*****.**> * * function hashPassword based on code from the phpLDAPadmin development team (http://phpldapadmin.sourceforge.net/). * function randomSalt based on code from the phpLDAPadmin development team (http://phpldapadmin.sourceforge.net/). * */ function password_save($curpass, $passwd) { $rcmail = rcmail::get_instance(); require_once 'Net/LDAP2.php'; // Building user DN if ($userDN = $rcmail->config->get('password_ldap_userDN_mask')) { $userDN = substitute_vars($userDN); } else { $userDN = search_userdn($rcmail); } if (empty($userDN)) { return PASSWORD_CONNECT_ERROR; } // Connection Method switch ($rcmail->config->get('password_ldap_method')) { case 'admin': $binddn = $rcmail->config->get('password_ldap_adminDN'); $bindpw = $rcmail->config->get('password_ldap_adminPW'); break; case 'user': default: $binddn = $userDN; $bindpw = $curpass; break; } // Configuration array $ldapConfig = array('binddn' => $binddn, 'bindpw' => $bindpw, 'basedn' => $rcmail->config->get('password_ldap_basedn'), 'host' => $rcmail->config->get('password_ldap_host'), 'port' => $rcmail->config->get('password_ldap_port'), 'starttls' => $rcmail->config->get('password_ldap_starttls'), 'version' => $rcmail->config->get('password_ldap_version')); // Connecting using the configuration array $ldap = Net_LDAP2::connect($ldapConfig); // Checking for connection error if (PEAR::isError($ldap)) { return PASSWORD_CONNECT_ERROR; } // Crypting new password $newCryptedPassword = hashPassword($passwd, $rcmail->config->get('password_ldap_encodage')); if (!$newCryptedPassword) { return PASSWORD_CRYPT_ERROR; } // Writing new crypted password to LDAP $userEntry = $ldap->getEntry($userDN); if (Net_LDAP2::isError($userEntry)) { return PASSWORD_CONNECT_ERROR; } $pwattr = $rcmail->config->get('password_ldap_pwattr'); $force = $rcmail->config->get('password_ldap_force_replace'); if (!$userEntry->replace(array($pwattr => $newCryptedPassword), $force)) { return PASSWORD_CONNECT_ERROR; } // Updating PasswordLastChange Attribute if desired if ($lchattr = $rcmail->config->get('password_ldap_lchattr')) { $current_day = (int) (time() / 86400); if (!$userEntry->replace(array($lchattr => $current_day), $force)) { return PASSWORD_CONNECT_ERROR; } } if (Net_LDAP2::isError($userEntry->update())) { return PASSWORD_CONNECT_ERROR; } // Update Samba password fields, ignore errors if attributes are not found if ($rcmail->config->get('password_ldap_samba')) { $sambaNTPassword = hash('md4', rcube_charset_convert($passwd, RCMAIL_CHARSET, 'UTF-16LE')); $userEntry->replace(array('sambaNTPassword' => $sambaNTPassword), $force); $userEntry->replace(array('sambaPwdLastSet' => time()), $force); $userEntry->update(); } // All done, no error return PASSWORD_SUCCESS; }
function changePassword($username, $oldpassword, $newpassword) { if (!isset($this->attributes['password']) || !isset($this->password_encoding)) { //throw new Exception(_('Sorry, changing LDAP passwords is not supported at this time')); return false; } $entry = $this->get_user($username, array('dn' => 'dn')); if (!$entry) { return false; } else { $config = $this->get_ldap_config(); $config['binddn'] = $entry->dn(); $config['bindpw'] = $oldpassword; try { $ldap = $this->get_ldap_connection($config); $entry = $this->get_user($username, array(), $ldap); $newCryptedPassword = $this->hashPassword($newpassword, $this->password_encoding); if ($newCryptedPassword === false) { return false; } if ($this->password_encoding == 'ad') { //TODO I believe this code will work once this bug is fixed: http://pear.php.net/bugs/bug.php?id=16796 $oldCryptedPassword = $this->hashPassword($oldpassword, $this->password_encoding); $entry->delete(array($this->attributes['password'] => $oldCryptedPassword)); } $entry->replace(array($this->attributes['password'] => $newCryptedPassword), true); if (Net_LDAP2::isError($entry->upate())) { return false; } return true; } catch (LdapInvalidCredentialsException $e) { return false; } } return false; }
/** * @todo Implement testCreateFresh(). */ public function testCreateFresh() { // test failing creation $t = Net_LDAP2_Entry::createFresh("cn=test", "I should be an array"); $this->assertTrue(Net_LDAP2::isError($t), 'Creating fresh entry succeeded but was supposed to fail!'); // test failing creation $t = Net_LDAP2_Entry::createFresh("cn=test", array('attr1' => 'single', 'attr2' => array('mv1', 'mv2'))); $this->assertInstanceOf('Net_LDAP2_Entry', $t, 'Creating fresh entry failed but was supposed to succeed!'); }
public function get_groups($force_reload = false) { $this->get_user_attributes($force_reload); // ensure we have a connection to the ldap server if ($this->bind() != 'LDAP_SUCCESS') { $this->add_log('ldap', 'Reuse of ldap connection failed: ' . $this->ldaplink->getMessage() . ' at line ' . __LINE__ . ' in ' . __FILE__); return false; } $filter1 = Net_LDAP2_Filter::create('objectClass', 'equals', $this->options['groupoc']); if (!empty($this->options['groupmemberattr'])) { // get membership from group information if ($this->options['groupmemberisdn']) { if ($this->user_attributes['dn'] == null) { return false; } $filter2 = Net_LDAP2_Filter::create($this->options['groupmemberattr'], 'equals', $this->user_dn()); } else { $filter2 = Net_LDAP2_Filter::create($this->options['groupmemberattr'], 'equals', $this->options['username']); } $filter = Net_LDAP2_Filter::combine('and', array($filter1, $filter2)); } else { if (!empty($this->options['usergroupattr'])) { // get membership from user information $ugi =& $this->user_attributes[$this->options['usergroupattr']]; if (!empty($ugi)) { if (!is_array($ugi)) { $ugi = array($ugi); } if (count($ugi) == 1) { // one gid $filter3 = Net_LDAP2_Filter::create($this->options['groupgroupattr'], 'equals', $ugi[0]); } else { // mor gids $filtertmp = array(); foreach ($ugi as $g) { $filtertmp[] = Net_LDAP2_Filter::create($this->options['groupgroupattr'], 'equals', $g); } $filter3 = Net_LDAP2_Filter::combine('or', $filtertmp); } $filter = Net_LDAP2_Filter::combine('and', array($filter1, $filter3)); } else { // User has no group $filter = NULL; } } else { // not possible to get groups - return empty array return array(); } } if (Net_LDAP2::isError($filter)) { $this->add_log('ldap', 'LDAP Filter creation error: ' . $filter->getMessage() . ' at line ' . __LINE__ . ' in ' . __FILE__); return false; } $this->add_log('ldap', 'Searching for group entries with filter: ' . $filter->asString() . ' base ' . $this->groupbase_dn() . ' at line ' . __LINE__ . ' in ' . __FILE__); $searchoptions = array('scope' => $this->options['scope']); $searchresult = $this->ldaplink->search($this->groupbase_dn(), $filter, $searchoptions); if (Net_LDAP2::isError($searchresult)) { $this->add_log('ldap', 'Search failed: ' . $searchresult->getMessage() . ' at line ' . __LINE__ . ' in ' . __FILE__); return false; } $this->add_log('ldap', 'Found ' . $searchresult->count() . ' entries. Extracting entries now.'); $this->groups = array(); while ($entry = $searchresult->shiftEntry()) { if (Net_LDAP2::isError($entry)) { $this->add_log('ldap', 'Error fetching group entries: ' . $entry->getMessage() . ' at line ' . __LINE__ . ' in ' . __FILE__); return false; } $this->groups[$entry->dn()] = $entry->getValues(); // no error checking necessary here } $this->add_log('ldap', count($this->groups) . ' groups found at line ' . __LINE__ . ' in ' . __FILE__); return $this->groups; }
/** * @param $username string * @param $configFilter string * @return void */ private function PopulateUser($username, $configFilter) { $uidAttribute = $this->options->GetUserIdAttribute(); Log::Debug('LDAP - uid attribute: %s', $uidAttribute); $RequiredGroup = $this->options->GetRequiredGroup(); $filter = Net_LDAP2_Filter::create($uidAttribute, 'equals', $username); if ($configFilter) { $configFilter = Net_LDAP2_Filter::parse($configFilter); if (Net_LDAP2::isError($configFilter)) { $message = 'Could not parse search filter %s: ' . $configFilter->getMessage(); Log::Error($message, $username); } $filter = Net_LDAP2_Filter::combine('and', array($filter, $configFilter)); } $attributes = $this->options->Attributes(); Log::Debug('LDAP - Loading user attributes: %s', implode(', ', $attributes)); $options = array('attributes' => $attributes); Log::Debug('Searching ldap for user %s', $username); $searchResult = $this->ldap->search(null, $filter, $options); if (Net_LDAP2::isError($searchResult)) { $message = 'Could not search ldap for user %s: ' . $searchResult->getMessage(); Log::Error($message, $username); } $currentResult = $searchResult->current(); if ($searchResult->count() == 1 && $currentResult !== false) { Log::Debug('Found user %s', $username); if (!empty($RequiredGroup)) { Log::Debug('LDAP - Required Group: %s', $RequiredGroup); $group_filter = Net_LDAP2_Filter::create('uniquemember', 'equals', $currentResult->dn()); $group_searchResult = $this->ldap->search($RequiredGroup, $group_filter, null); if (Net_LDAP2::isError($group_searchResult) && !empty($RequiredGroup)) { $message = 'Could not match Required Group %s: ' . $group_searchResult->getMessage(); Log::Error($message, $username); } if ($group_searchResult->count() == 1 && $group_searchResult !== false) { Log::Debug('Matched Required Group %s', $RequiredGroup); /** @var Net_LDAP2_Entry $entry */ $this->user = new LdapUser($currentResult, $this->options->AttributeMapping()); } } else { /** @var Net_LDAP2_Entry $entry */ $this->user = new LdapUser($currentResult, $this->options->AttributeMapping()); } } else { Log::Debug('Could not find user %s', $username); } }
/** * testIsError(). */ public function testIsError() { if (!$this->ldapcfg) { $this->markTestSkipped('No ldapconfig.ini found. Skipping test!'); } else { $error = PEAR::raiseError('TestError'); $this->assertTrue(Net_LDAP2::isError($error)); $this->assertFalse(Net_LDAP2::isError('noerror')); } }
<?php /** * This file shows you how to connect to a ldap server using Net_LDAP2. * * It also establishes connections for the other examples; * they include this file to get a ldap link. */ // Class includes; this assumes Net_LDAP2 installed in PHPs include path // or under subfolder "Net" in the local directory. require_once 'Net/LDAP2.php'; // Configuration // host can be a single server (string) or multiple ones - if we define more // servers here (array), we can implement a basic fail over scenario. // If no credentials (binddn and bindpw) are given, Net_LDAP2 establishes // an anonymous bind. // See the documentation for more information on the configuration items! $ldap_config = array('host' => array('ldap1.example.org', 'ldap2.example.org'), 'tls' => false, 'base' => 'o=example,dc=org', 'port' => 389, 'version' => 3, 'filter' => '(cn=*)', 'scope' => 'sub'); // Connect to configured ldap server $ldap = Net_LDAP2::connect($ldap_config); // It is important to check for errors. // Nearly every method of Net_LDAP2 returns a Net_LDAP2_Error object // if something went wrong. Through this object, you can retrieve detailed // information on what exactly happened. // // Here we drop a die with the error message, so the other example // files will not be calles unless we have a valid link. if (Net_LDAP2::isError($ldap)) { die('BIND FAILED: ' . $ldap->getMessage()); }
function ldap_get_connection($config = null) { if ($config == null && isset($this->default_ldap)) { return $this->default_ldap; } //cannot use Net_LDAP2::connect() as StatusNet uses //PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'handleError'); //PEAR handling can be overridden on instance objects, so we do that. $ldap = new Net_LDAP2(isset($config) ? $config : $this->ldap_get_config()); $ldap->setErrorHandling(PEAR_ERROR_RETURN); $err = $ldap->bind(); if (Net_LDAP2::isError($err)) { // if we were called with a config, assume caller will handle // incorrect username/password (LDAP_INVALID_CREDENTIALS) if (isset($config) && $err->getCode() == 0x31) { return null; } throw new Exception('Could not connect to LDAP server: ' . $err->getMessage()); return false; } if ($config == null) { $this->default_ldap = $ldap; } return $ldap; }
if (Net_LDAP2::isError($search)) { die('LDAP search failed: ' . $search->getMessage()); } // Lets see what entries we got and print the names and telephone numbers: if ($search->count() > 0) { echo "Found " . $search->count() . ' entries:<br>'; // Note, this is is only one of several ways to fetch entries! // You can also retrieve all entries in an array with // $entries = $search->entries() // or the same thing sorted: // $entries = $search->sorted() // Since Net_LDAP2 you can also use a foreach loop: // foreach ($search as $dn => $entry) { while ($entry = $search->shiftEntry()) { $surename = $entry->getValue('sn', 'single'); if (Net_LDAP2::isError($surename)) { die('Unable to get surename: ' . $surename->getMessage()); } $givenname = $entry->getValue('gn', 'single'); if (Net_LDAP2::isError($givenname)) { die('Unable to get givenname: ' . $givenname->getMessage()); } $phone = $entry->getValue('telephonenumber', 'single'); if (Net_LDAP2::isError($phone)) { die('Unable to get phone number: ' . $phone->getMessage()); } echo "<br>{$givenname} {$surename}: {$phone}"; } } else { die('Sorry, no entries found!'); }
function authenticate($login, $password) { if ($login && $password) { if (!function_exists('ldap_connect')) { trigger_error('auth_ldap requires PHP\'s PECL LDAP package installed.'); return FALSE; } if (!(require_once 'Net/LDAP2.php')) { trigger_error('auth_ldap requires the PEAR package Net::LDAP2'); return FALSE; } $debugMode = defined('LDAP_AUTH_DEBUG') ? LDAP_AUTH_DEBUG : FALSE; $anonymousBeforeBind = defined('LDAP_AUTH_ANONYMOUSBEFOREBIND') ? LDAP_AUTH_ANONYMOUSBEFOREBIND : FALSE; $parsedURI = parse_url(LDAP_AUTH_SERVER_URI); if ($parsedURI === FALSE) { $this->_log('Could not parse LDAP_AUTH_SERVER_URI in config.php'); return FALSE; } $ldapConnParams = array('host' => $parsedURI['scheme'] . '://' . $parsedURI['host'], 'basedn' => LDAP_AUTH_BASEDN, 'options' => array('LDAP_OPT_REFERRALS' => 0)); if (!$anonymousBeforeBind) { $ldapConnParams['binddn'] = LDAP_AUTH_BINDDN; $ldapConnParams['bindpw'] = LDAP_AUTH_BINDPW; } $ldapConnParams['starttls'] = defined('LDAP_AUTH_USETLS') ? LDAP_AUTH_USETLS : FALSE; if (is_int($parsedURI['port'])) { $ldapConnParams['port'] = $parsedURI['port']; } $ldapSchemaCacheEnable = defined('LDAP_AUTH_SCHEMA_CACHE_ENABLE') ? LDAP_AUTH_SCHEMA_CACHE_ENABLE : TRUE; $ldapSchemaCacheTimeout = defined('LDAP_AUTH_SCHEMA_CACHE_TIMEOUT') ? LDAP_AUTH_SCHEMA_CACHE_TIMEOUT : 86400; $logAttempts = defined('LDAP_AUTH_LOG_ATTEMPTS') ? LDAP_AUTH_LOG_ATTEMPTS : FALSE; // Making connection to LDAP server if (LDAP_AUTH_ALLOW_UNTRUSTED_CERT === TRUE) { putenv('LDAPTLS_REQCERT=never'); } $ldapConn = Net_LDAP2::connect($ldapConnParams); if (Net_LDAP2::isError($ldapConn)) { $this->_log('Could not connect to LDAP Server: ' . $ldapConn->getMessage()); return FALSE; } // Bind with service account if orignal connexion was anonymous if ($anonymousBeforeBind) { $binding = $ldapConn->bind(LDAP_AUTH_BINDDN, LDAP_AUTH_BINDPW); if (Net_LDAP2::isError($binding)) { $this->_log('Cound not bind service account: ' . $binding->getMessage()); return FALSE; } } //Cache LDAP Schema if ($ldapSchemaCacheEnable) { if (!sys_get_temp_dir()) { $tmpFile = tmp; $tmpDir = dirname($tmpFile); unlink($tmpFile); unset($tmpFile); } else { $tmpDir = sys_get_temp_dir(); } if (empty($parsedURI['port'])) { $ldapPort = $parsedURI['scheme'] == 'ldaps' ? 636 : 389; } else { $ldapPort = $parsedURI['port']; } $cacheFileLoc = $tmpDir . '/ttrss-ldapCache-' . $parsedURI['host'] . ':' . $ldapPort . '.cache'; if ($debugMode) { $this->_log('Schema Cache File: ' . $cacheFileLoc, E_USER_NOTICE); } $schemaCacheConf = array('path' => $cacheFileLoc, 'max_age' => $ldapSchemaCacheTimeout); $schemaCacheObj = new Net_LDAP2_SimpleFileSchemaCache($schemaCacheConf); $ldapConn->registerSchemaCache($schemaCacheObj); $schemaCacheObj->storeSchema($ldapConn->schema()); } //Searching for user $completedSearchFiler = str_replace('???', $login, LDAP_AUTH_SEARCHFILTER); $filterObj = Net_LDAP2_Filter::parse($completedSearchFiler); $searchResults = $ldapConn->search(LDAP_AUTH_BASEDN, $filterObj); if (Net_LDAP2::isError($searchResults)) { $this->_log('LDAP Search Failed: ' . $searchResults->getMessage()); return FALSE; } elseif ($searchResults->count() === 0) { if ($logAttempts) { $this->_logAttempt((string) $login, 'Unknown User'); } return FALSE; } elseif ($searchResults->count() > 1) { $this->_log('Multiple DNs found for username ' . $login); return FALSE; } //Getting user's DN from search $userEntry = $searchResults->shiftEntry(); $userDN = $userEntry->dn(); //Binding with user's DN. $loginAttempt = $ldapConn->bind($userDN, $password); $ldapConn->disconnect(); if ($loginAttempt === TRUE) { if ($logAttempts) { $this->_logAttempt((string) $login, 'successful'); } return $this->base->auto_create_user($login); } elseif ($loginAttempt->getCode() == 49) { if ($logAttempts) { $this->_logAttempt((string) $login, 'bad password'); } return FALSE; } else { $this->_log('Unknown Error: Code: ' . $loginAttempt->getCode() . ' Message: ' . $loginAttempt->getMessage() . ' user(' . (string) $login . ')'); return FALSE; } } return false; }
/** * This is a short example on how to fetch a specific entry in the * directory using Net_LDAP2. */ // We use the connecting.php example to get a link to our server. // This file will also include all required basic Net_LDAP2 classes. include_once 'connecting.php'; // Okay, we should have a valid link now. // Lets fetch an entry! We want to know the admins first and last name. // If we need additional attributes later, we must refetch the entry. // It is a good practice to only select the attributes really needed. // Since we want to be a little flexible, we make the base // dynamic, so it is enough to change the base-dn in your // $ldap_config array. $entry = $ldap->getEntry('cn=admin,' . $ldap_config['base'], array('gn', 'sn')); // Error checking is important! if (Net_LDAP2::isError($entry)) { die('Could not fetch entry: ' . $entry->getMessage()); } // Now fetch the data from the entry $surename = $entry->getValue('sn', 'single'); if (Net_LDAP2::isError($surename)) { die('Unable to get surename: ' . $surename->getMessage()); } $givenname = $entry->getValue('gn', 'single'); if (Net_LDAP2::isError($givenname)) { die('Unable to get surename: ' . $givenname->getMessage()); } // Finally output the data of the entry: // This will give something like "Name of cn=admin,o=example,dc=org: Foo Bar" echo 'Name of ' . $entry->DN() . ': ' . $givenname . ' ' . $surename;
/** * Haal de rollen van de huidige gebruiker op voor een opgegeven applicatie naam * In onze LDAP server vertegenwoordigd het veld description de volledige naam van de applicatie * * @param KVDutil_Auth_Gebruiker $gebruiker * @param string $applicatieNaam * structuur: 'ou='.$applicatieNaam.',ou=productie,ou=groups,dc=vioe,dc=be' * @return KVDutil_AuthRolCollectie $rollen */ public function getRollenVoorApplicatieNaam(KVDutil_Auth_Gebruiker $gebruiker, $applicatieNaam) { $filter = Net_LDAP2_Filter::create($this->parameters['gebruiker_bij_rol'], 'contains', $gebruiker->getId()); $options = array('scope' => 'sub', 'attributes' => array($this->parameters['rol_naam'], $this->parameters['rol_beschrijving'])); //Voer zoekactie uit op boven meegegeven searchbase met de opgegeven options en filters $search = $this->connectie->search($applicatieNaam, $filter, $options); if (Net_LDAP2::isError($search)) { throw new Exception($search->getMessage()); } $results = array(); //objecten worden 1 voor 1 volledig geladen en in een array geplaatst. foreach ($search as $dn => $entry) { $results[$dn] = new KVDutil_Auth_Rol($dn, $entry->getValue($this->parameters['rol_naam'], 'single'), $entry->getValue($this->parameters['rol_beschrijving'], 'single')); } //De array met objecten wordt in een KVDdom_DomainObjectCollection geplaatst. return new KVDutil_Auth_RolCollectie($results); }
function ldap_get_connection($config = null) { if ($config == null && isset($this->default_ldap)) { return $this->default_ldap; } //cannot use Net_LDAP2::connect() as StatusNet uses //PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'handleError'); //PEAR handling can be overridden on instance objects, so we do that. $ldap = new Net_LDAP2(isset($config) ? $config : $this->ldap_get_config()); $ldap->setErrorHandling(PEAR_ERROR_RETURN); $err = $ldap->bind(); if (Net_LDAP2::isError($err)) { // if we were called with a config, assume caller will handle // incorrect username/password (LDAP_INVALID_CREDENTIALS) if (isset($config) && $err->getCode() == 0x31) { return null; } throw new Exception('Could not connect to LDAP server: ' . $err->getMessage()); } if ($config == null) { $this->default_ldap = $ldap; } $c = common_memcache(); if (!empty($c)) { $cacheObj = new MemcacheSchemaCache(array('c' => $c, 'cacheKey' => common_cache_key('ldap_schema:' . crc32(serialize($config))))); $ldap->registerSchemaCache($cacheObj); } return $ldap; }
/** * Check if $user and $password are related to a valid user and password * * @param string $check_password * @return boolean */ function isValidPasswordLdap($user, $password, $config) { // Connecting using the configuration: require_once "Net/LDAP2.php"; $ldap = Net_LDAP2::connect($config); // Testing for connection error if (PEAR::isError($ldap)) { return false; } $filter = Net_LDAP2_Filter::create($config['uid'], 'equals', $user); $search = $ldap->search(null, $filter, null); if (Net_LDAP2::isError($search)) { return false; } if ($search->count() != 1) { return false; } // User exists so we may rebind to authenticate the password $entries = $search->entries(); $bind_result = $ldap->bind($entries[0]->dn(), $password); if (PEAR::isError($bind_result)) { return false; } return true; }
public function login() { global $tables; if (!class_exists('Net_LDAP2')) { require getConfig('casldap_netldap2_path'); } self::init_cas_client(); // force CAS authentication phpCAS::forceAuthentication(); $cas_login = phpCAS::getUser(); if (!$cas_login) { return; } $ldap_config = array('host' => getConfig('ldap_host'), 'port' => getConfig('ldap_port'), 'basedn' => getConfig('ldap_basedn')); $ldap_version = getConfig('ldap_version'); if (is_int($ldap_version)) { $ldap_config['version'] = $ldap_version; } if (getConfig('ldap_starttls')) { $ldap_config['starttls'] = true; } $ldap_binddn = getConfig('ldap_binddn'); $ldap_bindpw = getConfig('ldap_bindpw'); if ($ldap_binddn && $ldap_bindpw) { $ldap_config['binddn'] = $ldap_binddn; $ldap_config['bindpw'] = $ldap_bindpw; } $ldap = Net_LDAP2::connect($ldap_config); if (Net_LDAP2::isError($ldap)) { die(Fatal_Error(s("Could not connect to LDAP-server: %s", $ldap->getMessage()))); } $user_filter = str_replace('%login', $cas_login, getConfig('ldap_search_user_filter')); $user_basedn = getConfig('ldap_search_user_basedn'); if (!$user_basedn) { $user_basedn = NULL; } $user_scope = getConfig('ldap_search_user_scope'); if (!in_array($user_scope, array('one', 'base', 'sub'))) { $user_scope = 'sub'; } $user_login_attr = getConfig('ldap_search_user_login_attr'); $user_mail_attr = getConfig('ldap_search_user_mail_attr'); $options = array('scope' => $user_scope, 'attributes' => array($user_mail_attr)); if ($user_login_attr) { $options['attributes'][] = $user_login_attr; } $search = $ldap->search($user_basedn, $user_filter, $options); if (Net_LDAP2::isError($search)) { die(Fatal_Error(s("A problem occured during user search in LDAP : %s", $search->getMessage()))); } if ($search->count() == 0) { die(Error(s("You are not authorized to access to this page"))); } elseif ($search->count() != 1) { die(Fatal_Error(s("Found %d users in LDAP corresponding to CAS login %s.", $search->count(), $cas_login))); } $user_entry = $search->shiftEntry(); if ($user_login_attr) { $login = $user_entry->getValue($user_login_attr, 'single'); if (!is_string($login)) { die(Fatal_Error(s("Fail to retreive user login from LDAP data"))); } } else { $login = $cas_login; } $mail = $user_entry->getValue($user_mail_attr, 'single'); if (!is_string($mail)) { die(Fatal_Error(s("Fail to retreive user mail from LDAP data"))); } $superuser = 0; $superuser_filter = getConfig('ldap_search_superuser_filter'); if ($superuser_filter) { $superuser_filter = str_replace('%login', $login, $superuser_filter); $superuser_basedn = getConfig('ldap_search_superuser_basedn'); if (!$superuser_basedn) { $superuser_basedn = NULL; } $superuser_scope = getConfig('ldap_search_superuser_scope'); if (!in_array($superuser_scope, array('one', 'base', 'sub'))) { $superuser_scope = 'sub'; } $search = $ldap->search($superuser_basedn, $superuser_filter, array('scope' => $superuser_scope, 'attrsonly' => true)); if (Net_LDAP2::isError($search)) { die(Fatal_Error(s("A problem occured during the search in LDAP to known if user is a superuser : %s", $search->getMessage()))); } if ($search->count() > 0) { $superuser = 1; } } elseif (getConfig('casldap_all_user_superadmin')) { $superuser = 1; } $row = Sql_Fetch_Row_Query(sprintf("SELECT id, privileges\n\t\t\tFROM {$tables['admin']}\n\t\t\tWHERE loginname = '%s'", sql_escape($login))); if ($row) { list($id, $privileges) = $row; $update = Sql_Query(sprintf("UPDATE {$tables['admin']} SET\n\t\t\t\temail = '%s',\n\t\t\t\tsuperuser = %s,\n\t\t\t\tdisabled = 0\n\t\t\t\tWHERE id=%s", sql_escape($mail), $superuser, $id)); if (!$update) { die(Fatal_Error(s("Fail to update user informations in database : %s", Sql_Error()))); } } else { $insert = Sql_Query(sprintf("INSERT INTO {$tables['admin']}\n\t\t\t\t(loginname,email,superuser,disabled)\n\t\t\t\tVALUES\n\t\t\t\t('%s','%s',%s,0)", sql_escape($login), sql_escape($mail), $superuser)); if (!$insert) { die(Fatal_Error(s("Fail to create user in database : %s", Sql_Error()))); } $id = Sql_Insert_Id(); } $_SESSION['adminloggedin'] = $_SERVER["REMOTE_ADDR"]; $_SESSION['logindetails'] = array('adminname' => $login, 'id' => $id, 'superuser' => $superuser); if ($privileges) { $_SESSION['privileges'] = unserialize($privileges); } if (isset($_GET['ticket'])) { header('Location: ' . $_SERVER['REQUEST_URI']); exit; } return true; }
if (Net_LDAP2::isError($result)) { die('Unable to add attribute: ' . $result->getMessage()); } // Now we modify the first value // Note, that we must give all old values, otherwise the attribute // will be deleted. We specify the new absolute attribute state $result = $entry->replace(array('mail' => array('*****@*****.**', '*****@*****.**'))); if (Net_LDAP2::isError($result)) { die('Unable to modify attribute: ' . $result->getMessage()); } // And now we delete the second attribute value // We must provide the old value, so the ldap server knows, // which value we want to be deleted $result = $entry->delete(array('mail' => '*****@*****.**')); if (Net_LDAP2::isError($result)) { die('Unable to delete attribute value: ' . $result->getMessage()); } // Finally, we delete the whole attribute 'telephoneNumber': $result = $entry->delete('telephoneNumber'); if (Net_LDAP2::isError($result)) { die('Unable to delete attribute: ' . $result->getMessage()); } // Now it is time to transfer the changes to the ldap // directory. However, for security reasons, this line is // commented out. /* $result = $entry->update(); if (Net_LDAP2::isError($result)) { die('Unable to update entry: '.$result->getMessage()); } */
public function login($queryStr) { // If username and password provided if (isset($queryStr['username']) && isset($queryStr['password'])) { $username = addslashes($queryStr['username']); $password = addslashes($queryStr['password']); // If not already logged in if (!isset($_SESSION['username'])) { $_SESSION['start'] = "login " . $queryStr['username'] . " "; $netLogin = false; if ($this->registry->ldapAuth == true) { $where = "username=?"; $bind = array($username); $result = $this->registry->db->select('User', $where, $bind); // LDAP Authentication $config = array('binddn' => $queryStr['username'] . "@aston.ac.uk", 'bindpw' => $queryStr['password'], 'basedn' => 'dc=campus,dc=aston,dc=ac,dc=uk', 'host' => 'gc.campus.aston.ac.uk', 'port' => '3268'); // Connecting using the configuration: $ldap = Net_LDAP2::connect($config); if ($this->registry->ldapAuth == true && Net_LDAP2::isError($ldap)) { error_log("ldap ERROR=" . $ldap->getMessage()); } else { //error_log("LDAP CONNECTED"); $netLogin = TRUE; } } else { $where = "username=? and password=?"; $bind = array($username, $password); $result = $this->registry->db->select('User', $where, $bind); $netLogin = true; } // If user/pass match a user then set login session if ($netLogin == TRUE && sizeof($result) == 1) { if (!isset($_SESSION["timeout"])) { $_SESSION['timeout'] = time(); } $st = $_SESSION['timeout'] + 3600; //session time is 1 hour $_SESSION['start'] .= "One row "; $row = $result[0]; $_SESSION['start'] .= sizeof($row) . " "; $_SESSION['username'] = $row['username']; $_SESSION['name'] = $row['firstname'] . ' ' . $row['surname']; $where = "username=?"; $bind = array($username); $result = $this->registry->db->select('Admin', $where, $bind); if (sizeof($result) == 1) { $row = $result[0]; $_SESSION['admin'] = true; } $result = $this->registry->db->select('Tutors', $where, $bind); if (sizeof($result) == 1) { $row = $result[0]; $_SESSION['tutor'] = true; } $result = $this->registry->db->select('TeachAssist', $where, $bind); if (sizeof($result) >= 1) { $row = $result[0]; $_SESSION['ta'] = true; } } else { $_SESSION['start'] .= "no rows"; } } } // If login was successful if (isset($_SESSION['username'])) { $_SESSION['invalid_login'] = false; } else { $_SESSION['invalid_login'] = true; } }
public function save($curpass, $passwd) { $rcmail = rcmail::get_instance(); require_once 'Net/LDAP2.php'; // Building user DN if ($userDN = $rcmail->config->get('password_ldap_userDN_mask')) { $userDN = self::substitute_vars($userDN); } else { $userDN = $this->search_userdn($rcmail); } if (empty($userDN)) { return PASSWORD_CONNECT_ERROR; } // Connection Method switch ($rcmail->config->get('password_ldap_method')) { case 'admin': $binddn = $rcmail->config->get('password_ldap_adminDN'); $bindpw = $rcmail->config->get('password_ldap_adminPW'); break; case 'user': default: $binddn = $userDN; $bindpw = $curpass; break; } // Configuration array $ldapConfig = array('binddn' => $binddn, 'bindpw' => $bindpw, 'basedn' => $rcmail->config->get('password_ldap_basedn'), 'host' => $rcmail->config->get('password_ldap_host'), 'port' => $rcmail->config->get('password_ldap_port'), 'starttls' => $rcmail->config->get('password_ldap_starttls'), 'version' => $rcmail->config->get('password_ldap_version')); // Connecting using the configuration array $ldap = Net_LDAP2::connect($ldapConfig); // Checking for connection error if (PEAR::isError($ldap)) { return PASSWORD_CONNECT_ERROR; } $crypted_pass = self::hash_password($passwd, $rcmail->config->get('password_ldap_encodage')); $force = $rcmail->config->get('password_ldap_force_replace'); $pwattr = $rcmail->config->get('password_ldap_pwattr'); $lchattr = $rcmail->config->get('password_ldap_lchattr'); $smbpwattr = $rcmail->config->get('password_ldap_samba_pwattr'); $smblchattr = $rcmail->config->get('password_ldap_samba_lchattr'); $samba = $rcmail->config->get('password_ldap_samba'); // Support password_ldap_samba option for backward compat. if ($samba && !$smbpwattr) { $smbpwattr = 'sambaNTPassword'; $smblchattr = 'sambaPwdLastSet'; } // Crypt new password if (!$crypted_pass) { return PASSWORD_CRYPT_ERROR; } // Crypt new samba password if ($smbpwattr && !($samba_pass = self::hash_password($passwd, 'samba'))) { return PASSWORD_CRYPT_ERROR; } // Writing new crypted password to LDAP $userEntry = $ldap->getEntry($userDN); if (Net_LDAP2::isError($userEntry)) { return PASSWORD_CONNECT_ERROR; } if (!$userEntry->replace(array($pwattr => $crypted_pass), $force)) { return PASSWORD_CONNECT_ERROR; } // Updating PasswordLastChange Attribute if desired if ($lchattr) { $current_day = (int) (time() / 86400); if (!$userEntry->replace(array($lchattr => $current_day), $force)) { return PASSWORD_CONNECT_ERROR; } } // Update Samba password and last change fields if ($smbpwattr) { $userEntry->replace(array($smbpwattr => $samba_pass), $force); } // Update Samba password last change field if ($smblchattr) { $userEntry->replace(array($smblchattr => time()), $force); } if (Net_LDAP2::isError($userEntry->update())) { return PASSWORD_CONNECT_ERROR; } // All done, no error return PASSWORD_SUCCESS; }
} } /** * Store the schema object in session * * @return true|Net_LDAP2_Error */ public function storeSchema($schema) { // Just dump the given object into the session // unless in loadSchema(), it is important to only return // Net_LDAP2_Error objects if something crucial went wrong. // If you feel that you want to return an error object, be sure // that you have read the comments in Net_LDAP2_SchemaCache.interface.php // or you will seriously hurt the performance of your application!!!! $_SESSION[__CLASS__] = $schema; return true; } } // Ok, now we have our finished cache object. Now initialize and register it // the usual way: $mySchemaCache = new MySessionSchemaCache(); $ldap = Net_LDAP2::connect($ldap_config); if (Net_LDAP2::isError($ldap)) { die('BIND FAILED: ' . $ldap->getMessage()); } $res = $ldap->registerSchemaCache($mySchemaCache); if (Net_LDAP2::isError($res)) { die('REGISTER CACHE FAILED: ' . $res->getMessage()); } // Now, the Schema is cached in the PHP session :)
/** * Applies a regular expression onto a single- or multivalued attribute (like preg_match()) * * This method behaves like PHPs preg_match() but with some exceptions. * If you want to retrieve match information, then you MUST pass the * $matches parameter via reference! otherwise you will get no matches. * Since it is possible to have multi valued attributes the $matches * array will have a additionally numerical dimension (one for each value): * <code> * $matches = array( * 0 => array (usual preg_match() returnarray), * 1 => array (usual preg_match() returnarray) * ) * </code> * Please note, that $matches will be initialized to an empty array inside. * * Usage example: * <code> * $result = $entry->preg_match('/089(\d+)/', 'telephoneNumber', &$matches); * if ( $result === true ){ * echo "First match: ".$matches[0][1]; // Match of value 1, content of first bracket * } else { * if ( Net_LDAP2::isError($result) ) { * echo "Error: ".$result->getMessage(); * } else { * echo "No match found."; * } * } * </code> * * Please note that it is important to test for an Net_LDAP2_Error, because objects are * evaluating to true by default, thus if an error occured, and you only check using "==" then * you get misleading results. Use the "identical" (===) operator to test for matches to * avoid this as shown above. * * @param string $regex The regular expression * @param string $attr_name The attribute to search in * @param array $matches (optional, PASS BY REFERENCE!) Array to store matches in * * @return boolean|Net_LDAP2_Error TRUE, if we had a match in one of the values, otherwise false. Net_LDAP2_Error in case something went wrong */ public function pregMatch($regex, $attr_name, $matches = array()) { $matches = array(); // fetch attribute values $attr = $this->getValue($attr_name, 'all'); if (Net_LDAP2::isError($attr)) { return $attr; } else { unset($attr['count']); } // perform preg_match() on all values $match = false; foreach ($attr as $thisvalue) { $matches_int = array(); if (preg_match($regex, $thisvalue, $matches_int)) { $match = true; array_push($matches, $matches_int); // store matches in reference } } return $match; }
function vacation_read(array &$data) { require_once 'Net/LDAP2.php'; $rcmail = rcmail::get_instance(); $search = array('%username', '%email_local', '%email_domain', '%email'); $replace = array($data['username'], $data['email_local'], $data['email_domain'], $data['email']); $ldap_basedn = str_replace($search, $replace, $rcmail->config->get('vacation_ldap_basedn')); $ldap_binddn = str_replace($search, $replace, $rcmail->config->get('vacation_ldap_binddn')); $search = array('%username', '%password', '%email_local', '%email_domain', '%email'); $replace = array($data['username'], $rcmail->decrypt($_SESSION['password']), $data['email_local'], $data['email_domain'], $data['email']); $ldap_bindpw = str_replace($search, $replace, $rcmail->config->get('vacation_ldap_bindpw')); $ldapConfig = array('host' => $rcmail->config->get('vacation_ldap_host'), 'port' => $rcmail->config->get('vacation_ldap_port'), 'starttls' => $rcmail->config->get('vacation_ldap_starttls'), 'version' => $rcmail->config->get('vacation_ldap_version'), 'basedn' => $ldap_basedn, 'binddn' => $ldap_binddn, 'bindpw' => $ldap_bindpw); $ldap = Net_LDAP2::connect($ldapConfig); if (PEAR::isError($ldap)) { return PLUGIN_ERROR_CONNECT; } $search = array('%username', '%email_local', '%email_domain', '%email', '%vacation_enable', '%vacation_start', '%vacation_end', '%vacation_subject', '%vacation_message', '%vacation_keepcopyininbox', '%vacation_forwarder'); $replace = array($data['username'], $data['email_local'], $data['email_domain'], $data['email'], $data['vacation_enable'], $data['vacation_start'], $data['vacation_end'], $data['vacation_subject'], $data['vacation_message'], $data['vacation_keepcopyininbox'], $data['vacation_forwarder']); $search_base = str_replace($search, $replace, $rcmail->config->get('vacation_ldap_search_base')); $search_filter = str_replace($search, $replace, $rcmail->config->get('vacation_ldap_search_filter')); $search_params = array('attributes' => $rcmail->config->get('vacation_ldap_search_attrs')); $search = $ldap->search($search_base, $search_filter, $search_params); if (Net_LDAP2::isError($userEntry)) { $ldap->done(); return PLUGIN_ERROR_PROCESS; } if ($search->count() < 1) { $ldap->done(); return PLUGIN_ERROR_PROCESS; } $entry = $search->shiftEntry(); if ($entry->exists($rcmail->config->get('vacation_ldap_attr_email'))) { $data['email'] = $entry->get_value($rcmail->config->get('vacation_ldap_search_attr_email')); } if ($entry->exists($rcmail->config->get('vacation_ldap_attr_emaillocal'))) { $data['email_local'] = $entry->get_value($rcmail->config->get('vacation_ldap_search_attr_emaillocal')); } if ($entry->exists($rcmail->config->get('vacation_ldap_attr_emaildomain'))) { $data['email_domain'] = $entry->get_value($rcmail->config->get('vacation_ldap_search_attr_emaildomain')); } if ($entry->exists($rcmail->config->get('vacation_ldap_attr_vacationenable'))) { if ($entry->get_value($rcmail->config->get('vacation_ldap_attr_vacationenable')) == $rcmail->config->get('vacation_ldap_attr_vacationenable_value_enabled')) { $data['vacation_enable'] = 1; } else { $data['vacation_enable'] = 0; } } if ($entry->exists($rcmail->config->get('vacation_ldap_attr_vacationstart'))) { $data['vacation_start'] = $entry->get_value($rcmail->config->get('vacation_ldap_attr_vacationstart')); } if ($entry->exists($rcmail->config->get('vacation_ldap_attr_vacationend'))) { $data['vacation_end'] = $entry->get_value($rcmail->config->get('vacation_ldap_attr_vacationend')); } if ($entry->exists($rcmail->config->get('vacation_ldap_attr_vacationsubject'))) { $data['vacation_subject'] = $entry->get_value($rcmail->config->get('vacation_ldap_attr_vacationsubject')); } if ($entry->exists($rcmail->config->get('vacation_ldap_attr_vacationmessage'))) { $data['vacation_message'] = $entry->get_value($rcmail->config->get('vacation_ldap_attr_vacationmessage')); } if ($entry->exists($rcmail->config->get('vacation_ldap_attr_vacationkeepcopyininbox'))) { if ($entry->get_value($rcmail->config->get('vacation_ldap_attr_vacationkeepcopyininbox')) == $rcmail->config->get('vacation_ldap_attr_vacationkeepcopyininbox_value_enabled')) { $data['vacation_keepcopyininbox'] = 1; } else { $data['vacation_keepcopyininbox'] = 0; } } if ($entry->exists($rcmail->config->get('vacation_ldap_attr_vacationforwarder'))) { $data['vacation_forwarder'] = $entry->get_value($rcmail->config->get('vacation_ldap_attr_vacationforwarder')); } $ldap->done(); return PLUGIN_SUCCESS; }
/** * Returns last error message if error was found. * * Example: * <code> * $ldif->someAction(); * if ($ldif->error()) { * echo "Error: ".$ldif->error()." at input line: ".$ldif->error_lines(); * } * </code> * * @param boolean $as_string If set to true, only the message is returned * * @return false|Net_LDAP2_Error */ public function error($as_string = false) { if (Net_LDAP2::isError($this->_error['error'])) { return $as_string ? $this->_error['error']->getMessage() : $this->_error['error']; } else { return false; } }
/** * Update the entry on the directory server * * This will evaluate all changes made so far and send them * to the directory server. * Please note, that if you make changes to objectclasses wich * have mandatory attributes set, update() will currently fail. * Remove the entry from the server and readd it as new in such cases. * This also will deal with problems with setting structural object classes. * * @param Net_LDAP2 $ldap If passed, a call to setLDAP() is issued prior update, thus switching the LDAP-server. This is for perl-ldap interface compliance * * @access public * @return true|Net_LDAP2_Error * @todo Entry rename with a DN containing special characters needs testing! */ public function update($ldap = null) { if ($ldap) { $msg = $this->setLDAP($ldap); if (Net_LDAP2::isError($msg)) { return PEAR::raiseError('You passed an invalid $ldap variable to update()'); } } // ensure we have a valid LDAP object $ldap = $this->getLDAP(); if (!$ldap instanceof Net_LDAP2) { return PEAR::raiseError("The entries LDAP object is not valid"); } // Get and check link $link = $ldap->getLink(); if (!is_resource($link)) { return PEAR::raiseError("Could not update entry: internal LDAP link is invalid"); } /* * Delete the entry */ if (true === $this->_delete) { return $ldap->delete($this); } /* * New entry */ if (true === $this->_new) { $msg = $ldap->add($this); if (Net_LDAP2::isError($msg)) { return $msg; } $this->_new = false; $this->_changes['add'] = array(); $this->_changes['delete'] = array(); $this->_changes['replace'] = array(); $this->_original = $this->_attributes; // In case the "new" entry was moved after creation, we must // adjust the internal DNs as the entry was already created // with the most current DN. if (false == is_null($this->_newdn)) { $this->_dn = $this->_newdn; $this->_newdn = null; } $return = true; return $return; } /* * Rename/move entry */ if (false == is_null($this->_newdn)) { if ($ldap->getLDAPVersion() !== 3) { return PEAR::raiseError("Renaming/Moving an entry is only supported in LDAPv3"); } // make dn relative to parent (needed for ldap rename) $parent = Net_LDAP2_Util::ldap_explode_dn($this->_newdn, array('casefolding' => 'none', 'reverse' => false, 'onlyvalues' => false)); if (Net_LDAP2::isError($parent)) { return $parent; } $child = array_shift($parent); // maybe the dn consist of a multivalued RDN, we must build the dn in this case // because the $child-RDN is an array! if (is_array($child)) { $child = Net_LDAP2_Util::canonical_dn($child); } $parent = Net_LDAP2_Util::canonical_dn($parent); // rename/move if (false == @ldap_rename($link, $this->_dn, $child, $parent, false)) { return PEAR::raiseError("Entry not renamed: " . @ldap_error($link), @ldap_errno($link)); } // reflect changes to local copy $this->_dn = $this->_newdn; $this->_newdn = null; } /* * Retrieve a entry that has all attributes we need so that the list of changes to build is created accurately */ $fullEntry = $ldap->getEntry($this->dn()); if (Net_LDAP2::isError($fullEntry)) { return PEAR::raiseError("Could not retrieve a full set of attributes to reconcile changes with"); } $modifications = array(); // ADD foreach ($this->_changes["add"] as $attr => $value) { // if attribute exists, we need to combine old and new values if ($fullEntry->exists($attr)) { $currentValue = $fullEntry->getValue($attr, "all"); $value = array_merge($currentValue, $value); } $modifications[$attr] = $value; } // DELETE foreach ($this->_changes["delete"] as $attr => $value) { // In LDAPv3 you need to specify the old values for deleting if (is_null($value) && $ldap->getLDAPVersion() === 3) { $value = $fullEntry->getValue($attr); } if (!is_array($value)) { $value = array($value); } // Find out what is missing from $value and exclude it $currentValue = isset($modifications[$attr]) ? $modifications[$attr] : $fullEntry->getValue($attr, "all"); $modifications[$attr] = array_values(array_diff($currentValue, $value)); } // REPLACE foreach ($this->_changes["replace"] as $attr => $value) { $modifications[$attr] = $value; } // COMMIT if (false === @ldap_modify($link, $this->dn(), $modifications)) { return PEAR::raiseError("Could not modify the entry: " . @ldap_error($link), @ldap_errno($link)); } // all went well, so _original (server) becomes _attributes (local copy), reset _changes too... $this->_changes['add'] = array(); $this->_changes['delete'] = array(); $this->_changes['replace'] = array(); $this->_original = $this->_attributes; $return = true; return $return; }
/** * Returns wether a attribute syntax is binary or not * * This method gets used by Net_LDAP2_Entry to decide which * PHP function needs to be used to fetch the value in the * proper format (e.g. binary or string) * * @param string $attribute The name of the attribute (eg.: 'sn') * * @access public * @return boolean */ public function isBinary($attribute) { $return = false; // default to false // This list contains all syntax that should be treaten as // containing binary values // The Syntax Definitons go into constants at the top of this page $syntax_binary = array(NET_LDAP2_SYNTAX_OCTET_STRING, NET_LDAP2_SYNTAX_JPEG); // Check Syntax $attr_s = $this->get('attribute', $attribute); if (Net_LDAP2::isError($attr_s)) { // Attribute not found in schema $return = false; // consider attr not binary } elseif (isset($attr_s['syntax']) && in_array($attr_s['syntax'], $syntax_binary)) { // Syntax is defined as binary in schema $return = true; } else { // Syntax not defined as binary, or not found // if attribute is a subtype, check superior attribute syntaxes if (isset($attr_s['sup'])) { foreach ($attr_s['sup'] as $superattr) { $return = $this->isBinary($superattr); if ($return) { break; // stop checking parents since we are binary } } } } return $return; }
/** * Returns wether a attribute syntax is binary or not * * This method gets used by Net_LDAP2_Entry to decide which * PHP function needs to be used to fetch the value in the * proper format (e.g. binary or string) * * @param string $attribute The name of the attribute (eg.: 'sn') * * @access public * @return boolean */ public function isBinary($attribute) { // This list contains all syntax that should be treaten as // containing binary values // The Syntax Definitons go into constants at the top of this page $syntax_binary = array(NET_LDAP_SYNTAX_OCTET_STRING, NET_LDAP_SYNTAX_JPEG); // Check Syntax $attr_s = $this->get('attribute', $attribute); if (false === Net_LDAP2::isError($attr_s) && isset($attr_s['syntax']) && in_array($attr_s['syntax'], $syntax_binary)) { $return = true; return $return; } else { $return = false; return $return; } }