Beispiel #1
0
 public function testGetAttributes()
 {
     $ldap = new Ldap($this->container);
     $this->assertCount(3, $ldap->getProfileAttributes());
     $this->assertContains(LDAP_ACCOUNT_FULLNAME, $ldap->getProfileAttributes());
     $this->assertContains(LDAP_ACCOUNT_EMAIL, $ldap->getProfileAttributes());
     $this->assertContains(LDAP_ACCOUNT_MEMBEROF, $ldap->getProfileAttributes());
 }
Beispiel #2
0
 /**
  * plugin installation
  *
  * perform here all needed step for the plugin installation
  * such as create default config, add database tables,
  * add fields to existing tables, create local folders...
  */
 function install($plugin_version, &$errors = array())
 {
     global $conf;
     $config = new Ldap();
     if (file_exists(LDAP_LOGIN_PATH . 'data.dat')) {
         $config->load_config();
     } else {
         $config->load_default_config();
     }
     $config->save_config();
     $this->installed = true;
 }
Beispiel #3
0
 /**
  * Gather user information
  *
  * @param string $username Find information for 'username'
  * @param string $info Required attribute of the user account object
  * @return null|string User information
  * @throws Exception
  */
 public function getUserInformation($username, $info)
 {
     $toReturn = null;
     $db = new RecordSet($this->dbConnectionInfo, false, true);
     $information = $db->Open("SELECT email FROM users WHERE userName = '******' AND password != '';");
     switch ($information) {
         case 1:
             // User found in local database
             $toReturn = $db->Field('email');
             break;
         case 0:
             // User not found in local database
             // Try to find it in LDAP
             if ($this->ldap instanceof Ldap) {
                 try {
                     $information = $this->ldap->getUserInfo($username, array($info));
                     $toReturn = @$information[0][$info][0];
                 } catch (Exception $e) {
                     throw new Exception($e->getMessage());
                 }
             }
             break;
         default:
             throw new Exception('No or more than one email address found for ' . $username);
     }
     return $toReturn;
 }
Beispiel #4
0
 public function testFailedSearch()
 {
     if ($this->skipIfNoLdap()) {
         return;
     }
     $mock = $this->getMock('Bart\\PHPLDAP');
     $mock->expects($this->exactly(2))->method('ldap_bind')->will($this->returnValueMap(array(array('conn', 'binduser', 'bindpw', true), array('conn', $this->brayDN, 'jbraynardpwd', false))));
     $this->stubSearchSequence($mock);
     Diesel::registerInstantiator('Bart\\PHPLDAP', function () use($mock) {
         return $mock;
     });
     $ldap = new Ldap($this->config);
     $ldap->connect();
     $this->assertThrows('\\Bart\\LdapException', "LDAP Auth: failure, username/password did not match for {$this->brayDN}", function () use($mock, $ldap) {
         $ldap->auth_user('jbraynard', 'jbraynardpwd');
     });
 }
 public static function getLdapMemberGroups()
 {
     if (Ldap::getConnection()) {
         $query = ldap_search(Ldap::getConnection(), 'CN=groups,' . $GLOBALS['TL_CONFIG']['ldap_base'], "(objectClass=*)", LdapMemberGroup::getAttributes());
         if (!$query) {
             return false;
         }
         $found = ldap_get_entries(Ldap::getConnection(), $query);
         // groups not found
         if (!is_array($found) || count($found) <= 0) {
             return false;
         }
         return $found;
     } else {
         return false;
     }
 }
 public static function findLdapMember($strUsername)
 {
     if (Ldap::getConnection()) {
         $user_name_filter = $GLOBALS['TL_CONFIG']['ldap_uid'] . '=' . $strUsername;
         $filter = '(&(' . $user_name_filter . ')' . $GLOBALS['TL_CONFIG']['ldap_filter_person'] . ')';
         // search by username
         $query = ldap_search(Ldap::getConnection(), $GLOBALS['TL_CONFIG']['ldap_base'], $filter, LdapMember::getAttributes());
         if (!$query) {
             return null;
         }
         $found = ldap_get_entries(Ldap::getConnection(), $query);
         // user not found
         if (!is_array($found) || count($found) <= 0) {
             return null;
         }
         $found = (object) $found[0];
         return $found;
     } else {
         return null;
     }
 }
 public static function authenticateLdapMember($strUsername, $strPassword)
 {
     $objLdapUser = LdapMemberModel::findLdapMember($strUsername);
     if ($objLdapUser) {
         if (!@ldap_bind(Ldap::getConnection(), $objLdapUser->dn, $strPassword)) {
             $errno = ldap_errno(Ldap::getConnection());
             switch ($errno) {
                 case static::LDAP_INVALID_CREDENTIALS:
                     return false;
             }
             return false;
         }
         // ldap account requires an valid email and uid
         if ($objLdapUser->uid['count'] == 0 || $objLdapUser->mail['count'] == 0) {
             \Message::addError($GLOBALS['TL_LANG']['MSC']['ldap']['emailUidMissing']);
             return false;
         }
         return true;
     } else {
         return false;
     }
 }
Beispiel #8
0
 /**
  * Buscar al usuario en un grupo.
  *
  * @param string $userLogin con el login del usuario
  * @throws \Exception
  * @return bool
  */
 public static function searchADUserInGroup($userLogin)
 {
     if (Ldap::$_isADS === false) {
         return false;
     }
     $log = new Log(__FUNCTION__);
     $ldapGroup = Config::getValue('ldap_group');
     // El filtro de grupo no está establecido
     if (empty($ldapGroup)) {
         return true;
     }
     // Obtenemos el DN del grupo
     if (!($groupDN = Ldap::searchGroupDN())) {
         return false;
     }
     $filter = '(memberof:1.2.840.113556.1.4.1941:=' . $groupDN . ')';
     $filterAttr = array("sAMAccountName");
     $searchRes = @ldap_search(Ldap::$_ldapConn, Ldap::$_searchBase, $filter, $filterAttr);
     if (!$searchRes) {
         $log->addDescription(_('Error al buscar el grupo de usuarios'));
         $log->addDescription('LDAP ERROR: ' . ldap_error(Ldap::$_ldapConn) . '(' . ldap_errno(Ldap::$_ldapConn) . ')');
         $log->addDescription('LDAP FILTER: ' . $filter);
         $log->writeLog();
         throw new \Exception(_('Error al buscar el grupo de usuarios'));
     }
     if (@ldap_count_entries(Ldap::$_ldapConn, $searchRes) === 0) {
         $log->addDescription(_('No se encontró el grupo con ese nombre'));
         $log->addDescription('LDAP ERROR: ' . ldap_error(Ldap::$_ldapConn) . '(' . ldap_errno(Ldap::$_ldapConn) . ')');
         $log->addDescription('LDAP FILTER: ' . $filter);
         $log->writeLog();
         throw new \Exception(_('No se encontró el grupo con ese nombre'));
     }
     foreach (ldap_get_entries(Ldap::$_ldapConn, $searchRes) as $entry) {
         if ($userLogin === $entry['samaccountname'][0]) {
             return true;
         }
     }
     return false;
 }
Beispiel #9
0
 public function __construct(Ldap $link, $result = null)
 {
     $this->result = $result;
     if (is_resource($result)) {
         // Get the status code, matched DN and referrals from the response
         ldap_parse_result($link->resource(), $result, $this->code, $this->matchedDN, $this->message, $this->referrals);
         // Get the string representation of the status code
         $this->message = ldap_err2str($this->code);
         // Extract the data from the resource
         $this->data = ldap_get_entries($link->resource(), $result);
         $this->data = $this->cleanup_result($this->data);
         // Remove the referrals array if there's nothing inside
         count($this->referrals) == 0 && ($this->referrals = null);
         // Try to extract pagination cookie and estimated number of objects to be returned
         // Since there's no way to tell if pagination has been enabled or not, I am suppressing php errors
         @ldap_control_paged_result_response($link->resource(), $result, $this->cookie, $this->estimated);
     } else {
         $this->code = ldap_errno($link->resource());
         $this->message = ldap_error($link->resource());
     }
     // Active Directory conceals some additional error codes in the ErrorMessage of the response
     // that we cannot get to with ldap_errno() in authentication failures - let's try to
     // extract them!
     if ($this->code == 49) {
         $message = null;
         ldap_get_option($link->resource(), Option::ErrorString, $message);
         if (stripos($message, 'AcceptSecurityContext') !== false) {
             $message = explode(', ', $message);
             end($message);
             $message = prev($message);
             $this->code = explode(' ', $message)[1];
             // For compatibility reasons with standard ldap, if the error code
             // is 52e let's replace it with 49 ( their meanings are equal, it's just
             // Microsoft doing it its own way again )
             if ($this->code == '52e') {
                 $this->code = ResponseCode::InvalidCredentials;
             }
         }
     }
 }
 /**
  *      Function called when a Dolibarrr business event is done.
  *      All functions "run_trigger" are triggered if file is inside directory htdocs/includes/triggers
  *      @param      action      Event code (COMPANY_CREATE, PROPAL_VALIDATE, ...)
  *      @param      object      Object action is done on
  *      @param      user        Object user
  *      @param      langs       Object langs
  *      @param      conf        Object conf
  *      @return     int         <0 if KO, 0 if no action are done, >0 if OK
  */
 function run_trigger($action, $object, $user, $langs, $conf)
 {
     if (empty($conf->ldap->enabled)) {
         return 0;
     }
     // Module not active, we do nothing
     if (!function_exists('ldap_connect')) {
         dol_syslog("Warning, module LDAP is enabled but LDAP functions not available in this PHP", LOG_WARNING);
         return 0;
     }
     // Users
     if ($action == 'USER_CREATE') {
         dol_syslog("Trigger '" . $this->name . "' for action '{$action}' launched by " . __FILE__ . ". id=" . $object->id);
         if ($conf->ldap->enabled && $conf->global->LDAP_SYNCHRO_ACTIVE == 'dolibarr2ldap') {
             $ldap = new Ldap();
             $ldap->connect_bind();
             $info = $object->_load_ldap_info();
             $dn = $object->_load_ldap_dn($info);
             $result = $ldap->add($dn, $info, $user);
             if ($result < 0) {
                 $this->error = "ErrorLDAP" . " " . $ldap->error;
             }
             return $result;
         }
     } elseif ($action == 'USER_MODIFY') {
         dol_syslog("Trigger '" . $this->name . "' for action '{$action}' launched by " . __FILE__ . ". id=" . $object->id);
         if ($conf->ldap->enabled && $conf->global->LDAP_SYNCHRO_ACTIVE == 'dolibarr2ldap') {
             $ldap = new Ldap();
             $ldap->connect_bind();
             $oldinfo = $object->oldcopy->_load_ldap_info();
             $olddn = $object->oldcopy->_load_ldap_dn($oldinfo);
             // Verify if entry exist
             $container = $object->oldcopy->_load_ldap_dn($oldinfo, 1);
             $search = "(" . $object->oldcopy->_load_ldap_dn($oldinfo, 2) . ")";
             $records = $ldap->search($container, $search);
             if (sizeof($records) && $records['count'] == 0) {
                 $olddn = '';
             }
             $info = $object->_load_ldap_info();
             $dn = $object->_load_ldap_dn($info);
             $result = $ldap->update($dn, $info, $user, $olddn);
             if ($result < 0) {
                 $this->error = "ErrorLDAP" . " " . $ldap->error;
             }
             return $result;
         }
     } elseif ($action == 'USER_NEW_PASSWORD') {
         dol_syslog("Trigger '" . $this->name . "' for action '{$action}' launched by " . __FILE__ . ". id=" . $object->id);
         if ($conf->ldap->enabled && $conf->global->LDAP_SYNCHRO_ACTIVE == 'dolibarr2ldap') {
             $ldap = new Ldap();
             $ldap->connect_bind();
             $oldinfo = $object->oldcopy->_load_ldap_info();
             $olddn = $object->oldcopy->_load_ldap_dn($oldinfo);
             // Verify if entry exist
             $container = $object->oldcopy->_load_ldap_dn($oldinfo, 1);
             $search = "(" . $object->oldcopy->_load_ldap_dn($oldinfo, 2) . ")";
             $records = $ldap->search($container, $search);
             if (sizeof($records) && $records['count'] == 0) {
                 $olddn = '';
             }
             $info = $object->_load_ldap_info();
             $dn = $object->_load_ldap_dn($info);
             $result = $ldap->update($dn, $info, $user, $olddn);
             if ($result < 0) {
                 $this->error = "ErrorLDAP" . " " . $ldap->error;
             }
             return $result;
         }
     } elseif ($action == 'USER_ENABLEDISABLE') {
         dol_syslog("Trigger '" . $this->name . "' for action '{$action}' launched by " . __FILE__ . ". id=" . $object->id);
     } elseif ($action == 'USER_DELETE') {
         dol_syslog("Trigger '" . $this->name . "' for action '{$action}' launched by " . __FILE__ . ". id=" . $object->id);
         if ($conf->ldap->enabled && $conf->global->LDAP_SYNCHRO_ACTIVE == 'dolibarr2ldap') {
             $ldap = new Ldap();
             $ldap->connect_bind();
             $info = $object->_load_ldap_info();
             $dn = $object->_load_ldap_dn($info);
             $result = $ldap->delete($dn, $info, $user);
             if ($result < 0) {
                 $this->error = "ErrorLDAP" . " " . $ldap->error;
             }
             return $result;
         }
     } elseif ($action == 'GROUP_CREATE') {
         if ($conf->ldap->enabled && $conf->global->LDAP_SYNCHRO_ACTIVE == 'dolibarr2ldap') {
             $ldap = new Ldap();
             $ldap->connect_bind();
             $info = $object->_load_ldap_info();
             $dn = $object->_load_ldap_dn($info);
             // Get a gid number for objectclass PosixGroup
             if (in_array('posixGroup', $info['objectclass'])) {
                 $info['gidNumber'] = $ldap->getNextGroupGid();
             }
             $result = $ldap->add($dn, $info, $user);
             if ($result < 0) {
                 $this->error = "ErrorLDAP" . " " . $ldap->error;
             }
             return $result;
         }
     } elseif ($action == 'GROUP_MODIFY') {
         if ($conf->ldap->enabled && $conf->global->LDAP_SYNCHRO_ACTIVE == 'dolibarr2ldap') {
             $ldap = new Ldap();
             $ldap->connect_bind();
             $oldinfo = $object->oldcopy->_load_ldap_info();
             $olddn = $object->oldcopy->_load_ldap_dn($oldinfo);
             // Verify if entry exist
             $container = $object->oldcopy->_load_ldap_dn($oldinfo, 1);
             $search = "(" . $object->oldcopy->_load_ldap_dn($oldinfo, 2) . ")";
             $records = $ldap->search($container, $search);
             if (sizeof($records) && $records['count'] == 0) {
                 $olddn = '';
             }
             $info = $object->_load_ldap_info();
             $dn = $object->_load_ldap_dn($info);
             $result = $ldap->update($dn, $info, $user, $olddn);
             if ($result < 0) {
                 $this->error = "ErrorLDAP" . " " . $ldap->error;
             }
             return $result;
         }
     } elseif ($action == 'GROUP_DELETE') {
         if ($conf->ldap->enabled && $conf->global->LDAP_SYNCHRO_ACTIVE == 'dolibarr2ldap') {
             $ldap = new Ldap();
             $ldap->connect_bind();
             $info = $object->_load_ldap_info();
             $dn = $object->_load_ldap_dn($info);
             $result = $ldap->delete($dn, $info, $user);
             if ($result < 0) {
                 $this->error = "ErrorLDAP" . " " . $ldap->error;
             }
             return $result;
         }
     } elseif ($action == 'CONTACT_CREATE') {
         dol_syslog("Trigger '" . $this->name . "' for action '{$action}' launched by " . __FILE__ . ". id=" . $object->id);
         if ($conf->ldap->enabled && $conf->global->LDAP_CONTACT_ACTIVE) {
             $ldap = new Ldap();
             $ldap->connect_bind();
             $info = $object->_load_ldap_info();
             $dn = $object->_load_ldap_dn($info);
             $result = $ldap->add($dn, $info, $user);
             if ($result < 0) {
                 $this->error = "ErrorLDAP" . " " . $ldap->error;
             }
             return $result;
         }
     } elseif ($action == 'CONTACT_MODIFY') {
         dol_syslog("Trigger '" . $this->name . "' for action '{$action}' launched by " . __FILE__ . ". id=" . $object->id);
         if ($conf->ldap->enabled && $conf->global->LDAP_CONTACT_ACTIVE) {
             $ldap = new Ldap();
             $ldap->connect_bind();
             $oldinfo = $object->oldcopy->_load_ldap_info();
             $olddn = $object->oldcopy->_load_ldap_dn($oldinfo);
             // Verify if entry exist
             $container = $object->oldcopy->_load_ldap_dn($oldinfo, 1);
             $search = "(" . $object->oldcopy->_load_ldap_dn($oldinfo, 2) . ")";
             $records = $ldap->search($container, $search);
             if (sizeof($records) && $records['count'] == 0) {
                 $olddn = '';
             }
             $info = $object->_load_ldap_info();
             $dn = $object->_load_ldap_dn($info);
             $result = $ldap->update($dn, $info, $user, $olddn);
             if ($result < 0) {
                 $this->error = "ErrorLDAP" . " " . $ldap->error;
             }
             return $result;
         }
     } elseif ($action == 'CONTACT_DELETE') {
         dol_syslog("Trigger '" . $this->name . "' for action '{$action}' launched by " . __FILE__ . ". id=" . $object->id);
         if ($conf->ldap->enabled && $conf->global->LDAP_CONTACT_ACTIVE) {
             $ldap = new Ldap();
             $ldap->connect_bind();
             $info = $object->_load_ldap_info();
             $dn = $object->_load_ldap_dn($info);
             $result = $ldap->delete($dn, $info, $user);
             if ($result < 0) {
                 $this->error = "ErrorLDAP" . " " . $ldap->error;
             }
             return $result;
         }
     } elseif ($action == 'MEMBER_CREATE') {
         dol_syslog("Trigger '" . $this->name . "' for action '{$action}' launched by " . __FILE__ . ". id=" . $object->id);
         if ($conf->ldap->enabled && $conf->global->LDAP_MEMBER_ACTIVE) {
             $ldap = new Ldap();
             $ldap->connect_bind();
             $info = $object->_load_ldap_info();
             $dn = $object->_load_ldap_dn($info);
             $result = $ldap->add($dn, $info, $user);
             if ($result < 0) {
                 $this->error = "ErrorLDAP" . " " . $ldap->error;
             }
             return $result;
         }
     } elseif ($action == 'MEMBER_VALIDATE') {
         dol_syslog("Trigger '" . $this->name . "' for action '{$action}' launched by " . __FILE__ . ". id=" . $object->id);
         if ($conf->ldap->enabled && $conf->global->LDAP_MEMBER_ACTIVE) {
             # If status field is setup to be synchronized
             if ($conf->global->LDAP_FIELD_MEMBER_STATUS) {
                 $ldap = new Ldap();
                 $ldap->connect_bind();
                 $info = $object->_load_ldap_info();
                 $dn = $object->_load_ldap_dn($info);
                 $olddn = $dn;
                 // We know olddn=dn as we change only status
                 $result = $ldap->update($dn, $info, $user, $olddn);
                 if ($result < 0) {
                     $this->error = "ErrorLDAP" . " " . $ldap->error;
                 }
                 return $result;
             }
         }
     } elseif ($action == 'MEMBER_SUBSCRIPTION') {
         dol_syslog("Trigger '" . $this->name . "' for action '{$action}' launched by " . __FILE__ . ". id=" . $object->id);
         if ($conf->ldap->enabled && $conf->global->LDAP_MEMBER_ACTIVE) {
             # If subscriptions fields are setup to be synchronized
             if ($conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE || $conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_AMOUNT || $conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE || $conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT || $conf->global->LDAP_FIELD_MEMBER_END_LASTSUBSCRIPTION) {
                 $ldap = new Ldap();
                 $ldap->connect_bind();
                 $info = $object->_load_ldap_info();
                 $dn = $object->_load_ldap_dn($info);
                 $olddn = $dn;
                 // We know olddn=dn as we change only subscriptions
                 $result = $ldap->update($dn, $info, $user, $olddn);
                 if ($result < 0) {
                     $this->error = "ErrorLDAP" . " " . $ldap->error;
                 }
                 return $result;
             }
         }
     } elseif ($action == 'MEMBER_MODIFY') {
         dol_syslog("Trigger '" . $this->name . "' for action '{$action}' launched by " . __FILE__ . ". id=" . $object->id);
         if ($conf->ldap->enabled && $conf->global->LDAP_MEMBER_ACTIVE) {
             $ldap = new Ldap();
             $ldap->connect_bind();
             $oldinfo = $object->oldcopy->_load_ldap_info();
             $olddn = $object->oldcopy->_load_ldap_dn($oldinfo);
             // Verify if entry exist
             $container = $object->oldcopy->_load_ldap_dn($oldinfo, 1);
             $search = "(" . $object->oldcopy->_load_ldap_dn($oldinfo, 2) . ")";
             $records = $ldap->search($container, $search);
             if (sizeof($records) && $records['count'] == 0) {
                 $olddn = '';
             }
             $info = $object->_load_ldap_info();
             $dn = $object->_load_ldap_dn($info);
             $result = $ldap->update($dn, $info, $user, $olddn);
             if ($result < 0) {
                 $this->error = "ErrorLDAP" . " " . $ldap->error;
             }
             return $result;
         }
     } elseif ($action == 'MEMBER_NEW_PASSWORD') {
         dol_syslog("Trigger '" . $this->name . "' for action '{$action}' launched by " . __FILE__ . ". id=" . $object->id);
         if ($conf->ldap->enabled && $conf->global->LDAP_MEMBER_ACTIVE) {
             # If password field is setup to be synchronized
             if ($conf->global->LDAP_FIELD_PASSWORD || $conf->global->LDAP_FIELD_PASSWORD_CRYPTED) {
                 $ldap = new Ldap();
                 $ldap->connect_bind();
                 $info = $object->_load_ldap_info();
                 $dn = $object->_load_ldap_dn($info);
                 $olddn = $dn;
                 // We know olddn=dn as we change only password
                 $result = $ldap->update($dn, $info, $user, $olddn);
                 if ($result < 0) {
                     $this->error = "ErrorLDAP" . " " . $ldap->error;
                 }
                 return $result;
             }
         }
     } elseif ($action == 'MEMBER_RESILIATE') {
         dol_syslog("Trigger '" . $this->name . "' for action '{$action}' launched by " . __FILE__ . ". id=" . $object->id);
         if ($conf->ldap->enabled && $conf->global->LDAP_MEMBER_ACTIVE) {
             # If status field is setup to be synchronized
             if ($conf->global->LDAP_FIELD_MEMBER_STATUS) {
                 $ldap = new Ldap();
                 $ldap->connect_bind();
                 $info = $object->_load_ldap_info();
                 $dn = $object->_load_ldap_dn($info);
                 $olddn = $dn;
                 // We know olddn=dn as we change only status
                 $result = $ldap->update($dn, $info, $user, $olddn);
                 if ($result < 0) {
                     $this->error = "ErrorLDAP" . " " . $ldap->error;
                 }
                 return $result;
             }
         }
     } elseif ($action == 'MEMBER_DELETE') {
         dol_syslog("Trigger '" . $this->name . "' for action '{$action}' launched by " . __FILE__ . ". id=" . $object->id);
         if ($conf->ldap->enabled && $conf->global->LDAP_MEMBER_ACTIVE) {
             $ldap = new Ldap();
             $ldap->connect_bind();
             $info = $object->_load_ldap_info();
             $dn = $object->_load_ldap_dn($info);
             $result = $ldap->delete($dn, $info, $user);
             if ($result < 0) {
                 $this->error = "ErrorLDAP" . " " . $ldap->error;
             }
             return $result;
         }
     }
     // If not found
     /*
             else
             {
                 dol_syslog("Trigger '".$this->name."' for action '$action' was ran by ".__FILE__." but no handler found for this action.");
     			return -1;
             }
     */
     return 0;
 }
Beispiel #11
0
if (!empty($conf->global->LDAP_CONTACT_ACTIVE) && $conf->global->LDAP_CONTACT_ACTIVE != 'ldap2dolibarr') {
    print '<a class="butAction" href="' . $_SERVER["PHP_SELF"] . '?id=' . $contact->id . '&amp;action=dolibarr2ldap">' . $langs->trans("ForceSynchronize") . '</a>';
}
print "</div>\n";
if (!empty($conf->global->LDAP_CONTACT_ACTIVE) && $conf->global->LDAP_CONTACT_ACTIVE != 'ldap2dolibarr') {
    print "<br>\n";
}
// Affichage attributs LDAP
print_titre($langs->trans("LDAPInformationsForThisContact"));
print '<table width="100%" class="noborder">';
print '<tr class="liste_titre">';
print '<td>' . $langs->trans("LDAPAttributes") . '</td>';
print '<td>' . $langs->trans("Value") . '</td>';
print '</tr>';
// Lecture LDAP
$ldap = new Ldap();
$result = $ldap->connect_bind();
if ($result > 0) {
    $info = $contact->_load_ldap_info();
    $dn = $contact->_load_ldap_dn($info, 1);
    $search = "(" . $contact->_load_ldap_dn($info, 2) . ")";
    $records = $ldap->getAttribute($dn, $search);
    //var_dump($records);
    // Affichage arbre
    if (count($records) && $records != false && (!isset($records['count']) || $records['count'] > 0)) {
        if (!is_array($records)) {
            print '<tr ' . $bc[false] . '><td colspan="2"><font class="error">' . $langs->trans("ErrorFailedToReadLDAP") . '</font></td></tr>';
        } else {
            $result = show_ldap_content($records, 0, $records['count'], true);
        }
    } else {
    if ($num) {
        while ($i < $num) {
            $obj = $db->fetch_object($resql);
            if ($obj) {
                //print 'Load cache for country '.strtolower($obj->label).' rowid='.$obj->rowid."\n";
                $hashlib2rowid[strtolower($obj->label)] = $obj->rowid;
                $countries[$obj->rowid] = array('rowid' => $obj->rowid, 'label' => $obj->label, 'code' => $obj->code);
            }
            $i++;
        }
    }
} else {
    dol_print_error($db);
    exit(-1);
}
$ldap = new Ldap();
$result = $ldap->connect_bind();
if ($result >= 0) {
    $justthese = array();
    // We disable synchro Dolibarr-LDAP
    $conf->global->LDAP_MEMBER_ACTIVE = 0;
    $ldaprecords = $ldap->getRecords('*', $conf->global->LDAP_MEMBER_DN, $conf->global->LDAP_KEY_MEMBERS, $required_fields, 0);
    if (is_array($ldaprecords)) {
        $db->begin();
        // Warning $ldapuser has a key in lowercase
        foreach ($ldaprecords as $key => $ldapuser) {
            $member = new Adherent($db);
            // Propriete membre
            $member->firstname = $ldapuser[$conf->global->LDAP_FIELD_FIRSTNAME];
            $member->lastname = $ldapuser[$conf->global->LDAP_FIELD_NAME];
            $member->login = $ldapuser[$conf->global->LDAP_FIELD_LOGIN];
Beispiel #13
0
    print "<tr>" . '<td align="center" colspan="2"><input class="button" value="' . $langs->trans("CreateUser") . '" type="submit"></td></tr>';
    print "</table>\n";
    print "</form>";
} else {
    /* ************************************************************************** */
    /*                                                                            */
    /* Visu et edition                                                            */
    /*                                                                            */
    /* ************************************************************************** */
    if ($id) {
        $fuser = new User($db);
        $fuser->fetch($id);
        // Connexion ldap
        // pour recuperer passDoNotExpire et userChangePassNextLogon
        if ($conf->ldap->enabled && $fuser->ldap_sid) {
            $ldap = new Ldap();
            $result = $ldap->connect_bind();
            if ($result > 0) {
                $userSearchFilter = '(' . $conf->global->LDAP_FILTER_CONNECTION . '(' . $this->getUserIdentifier() . '=' . $fuser->login . '))';
                $entries = $ldap->fetch($fuser->login, $userSearchFilter);
                if (!$entries) {
                    $message .= $ldap->error;
                }
                $passDoNotExpire = 0;
                $userChangePassNextLogon = 0;
                $userDisabled = 0;
                $statutUACF = '';
                //On verifie les options du compte
                if (count($ldap->uacf) > 0) {
                    foreach ($ldap->uacf as $key => $statut) {
                        if ($key == 65536) {
    $input = trim(fgets(STDIN));
}
/*
if (! $conf->global->LDAP_CONTACT_ACTIVE)
{
	print $langs->trans("LDAPSynchronizationNotSetupInDolibarr");
	exit(-1);
}
*/
$sql = "SELECT rowid";
$sql .= " FROM " . MAIN_DB_PREFIX . "socpeople";
$resql = $db->query($sql);
if ($resql) {
    $num = $db->num_rows($resql);
    $i = 0;
    $ldap = new Ldap();
    $ldap->connect_bind();
    while ($i < $num) {
        $ldap->error = "";
        $obj = $db->fetch_object($resql);
        $contact = new Contact($db);
        $contact->id = $obj->rowid;
        $contact->fetch($contact->id);
        print $langs->trans("UpdateContact") . " rowid=" . $contact->id . " " . $contact->getFullName($langs);
        $oldobject = $contact;
        $oldinfo = $oldobject->_load_ldap_info();
        $olddn = $oldobject->_load_ldap_dn($oldinfo);
        $info = $contact->_load_ldap_info();
        $dn = $contact->_load_ldap_dn($info);
        $result = $ldap->add($dn, $info, $user);
        // Wil fail if already exists
Beispiel #15
0
 /**
  * Autentificación de usuarios con LDAP.
  *
  * @param string $userLogin con el login del usuario
  * @param string $userPass  con la clave del usuario
  * @return int|bool Número de error o boolean
  */
 public static function authUserLDAP($userLogin, $userPass)
 {
     if (!Util::ldapIsAvailable() || !Util::ldapIsEnabled() || !Ldap::checkLDAPParams()) {
         return false;
     }
     $ldapGroupAccess = false;
     $message['action'] = __FUNCTION__;
     // Conectamos al servidor realizamos la conexión con el usuario proxy
     try {
         Ldap::ldapConnect();
         Ldap::ldapBind();
         Ldap::getUserDN($userLogin);
     } catch (\Exception $e) {
         return false;
     }
     $userDN = Ldap::$ldapSearchData[0]['dn'];
     // Realizamos la conexión con el usuario real y obtenemos los atributos
     try {
         Ldap::ldapBind($userDN, $userPass);
         $attribs = Ldap::getLDAPAttr();
     } catch (\Exception $e) {
         return ldap_errno(Ldap::getConn());
     }
     // Comprobamos si la cuenta está bloqueada o expirada
     if (isset($attribs['expire']) && $attribs['expire'] > 0) {
         return 701;
     }
     if (Ldap::getLdapGroup() !== '*') {
         // Comprobamos que el usuario está en el grupo indicado buscando en los atributos del usuario
         if (isset($attribs['group'])) {
             if (is_array($attribs['group'])) {
                 foreach ($attribs['group'] as $group) {
                     if (is_int($group)) {
                         continue;
                     }
                     // Comprobamos que el usuario está en el grupo indicado
                     if (self::checkLDAPGroup($group)) {
                         $ldapGroupAccess = true;
                         break;
                     }
                 }
             } else {
                 $ldapGroupAccess = self::checkLDAPGroup($attribs['group']);
             }
             // Comprobamos que el usuario está en el grupo indicado buscando en los atributos del grupo
         } else {
             $ldapGroupAccess = Ldap::searchUserInGroup($userDN) || LdapADS::searchADUserInGroup($userLogin);
         }
     } else {
         $ldapGroupAccess = true;
     }
     if ($ldapGroupAccess === false) {
         $log = new Log(__FUNCTION__);
         $log->addDescription(_('Usuario no pertenece al grupo'));
         $log->addDescription(sprintf('%s : %s', _('Usuario'), $userDN));
         $log->writeLog();
         return 702;
     }
     self::$userName = isset($attribs['name']) ? $attribs['name'] : $userLogin;
     self::$userEmail = isset($attribs['mail']) ? $attribs['mail'] : '';
     return true;
 }
{
	print $langs->trans("LDAPSynchronizationNotSetupInDolibarr");
	exit 1;
}
*/

$sql = "SELECT rowid";
$sql .= " FROM ".MAIN_DB_PREFIX."usergroup";

$resql = $db->query($sql);
if ($resql)
{
	$num = $db->num_rows($resql);
	$i = 0;

	$ldap=new Ldap();
	$ldap->connect_bind();

	while ($i < $num)
	{
		$ldap->error="";

		$obj = $db->fetch_object($resql);

		$fgroup = new UserGroup($db);
		$fgroup->id = $obj->rowid;
		$fgroup->fetch($fgroup->id);

		print $langs->trans("UpdateGroup")." rowid=".$fgroup->id." ".$fgroup->name;

		$oldobject=$fgroup;
Beispiel #17
0
	$dn=$conf->global->LDAP_GROUP_DN;
	$objectclass=$conf->global->LDAP_GROUP_OBJECT_CLASS;

	show_ldap_test_button($butlabel,$testlabel,$key,$dn,$objectclass);
}

if (function_exists("ldap_connect"))
{
	if ($_GET["action"] == 'testgroup')
	{
		// Creation objet
		$object=new UserGroup($db);
		$object->initAsSpecimen();

		// Test synchro
		$ldap=new Ldap();
		$result=$ldap->connect_bind();

		if ($result > 0)
		{
			$info=$object->_load_ldap_info();
			$dn=$object->_load_ldap_dn($info);

			$result1=$ldap->delete($dn);			// To be sure to delete existing records
			$result2=$ldap->add($dn,$info,$user);	// Now the test
			$result3=$ldap->delete($dn);			// Clean what we did

			if ($result2 > 0)
			{
				print img_picto('','info').' ';
				print '<font class="ok">'.$langs->trans("LDAPSynchroOK").'</font><br>';
Beispiel #18
0
/**
 * Check validity of user/password/entity
 * If test is ko, reason must be filled into $_SESSION["dol_loginmesg"]
 *
 * @param	string	$usertotest		Login
 * @param	string	$passwordtotest	Password
 * @param   int		$entitytotest   Number of instance (always 1 if module multicompany not enabled)
 * @return	string					Login if OK, '' if KO
 */
function check_user_password_ldap($usertotest, $passwordtotest, $entitytotest)
{
    global $db, $conf, $langs;
    global $_POST;
    global $dolibarr_main_auth_ldap_host, $dolibarr_main_auth_ldap_port;
    global $dolibarr_main_auth_ldap_version, $dolibarr_main_auth_ldap_servertype;
    global $dolibarr_main_auth_ldap_login_attribute, $dolibarr_main_auth_ldap_dn;
    global $dolibarr_main_auth_ldap_admin_login, $dolibarr_main_auth_ldap_admin_pass;
    global $dolibarr_main_auth_ldap_filter;
    global $dolibarr_main_auth_ldap_debug;
    // Force master entity in transversal mode
    $entity = $entitytotest;
    if (!empty($conf->multicompany->enabled) && !empty($conf->multicompany->transverse_mode)) {
        $entity = 1;
    }
    $login = '';
    $resultFetchUser = '';
    if (!function_exists("ldap_connect")) {
        dol_syslog("functions_ldap::check_user_password_ldap Authentification ko failed to connect to LDAP. LDAP functions are disabled on this PHP");
        sleep(1);
        $langs->load('main');
        $langs->load('other');
        $_SESSION["dol_loginmesg"] = $langs->trans("ErrorLDAPFunctionsAreDisabledOnThisPHP") . ' ' . $langs->trans("TryAnotherConnectionMode");
        return;
    }
    if ($usertotest) {
        dol_syslog("functions_ldap::check_user_password_ldap usertotest=" . $usertotest . " passwordtotest=" . preg_replace('/./', '*', $passwordtotest) . " entitytotest=" . $entitytotest);
        // If test username/password asked, we define $test=false and $login var if ok, set $_SESSION["dol_loginmesg"] if ko
        $ldaphost = $dolibarr_main_auth_ldap_host;
        $ldapport = $dolibarr_main_auth_ldap_port;
        $ldapversion = $dolibarr_main_auth_ldap_version;
        $ldapservertype = empty($dolibarr_main_auth_ldap_servertype) ? 'openldap' : $dolibarr_main_auth_ldap_servertype;
        $ldapuserattr = $dolibarr_main_auth_ldap_login_attribute;
        $ldapdn = $dolibarr_main_auth_ldap_dn;
        $ldapadminlogin = $dolibarr_main_auth_ldap_admin_login;
        $ldapadminpass = $dolibarr_main_auth_ldap_admin_pass;
        $ldapdebug = empty($dolibarr_main_auth_ldap_debug) || $dolibarr_main_auth_ldap_debug == "false" ? false : true;
        if ($ldapdebug) {
            print "DEBUG: Logging LDAP steps<br>\n";
        }
        require_once DOL_DOCUMENT_ROOT . '/core/class/ldap.class.php';
        $ldap = new Ldap();
        $ldap->server = explode(',', $ldaphost);
        $ldap->serverPort = $ldapport;
        $ldap->ldapProtocolVersion = $ldapversion;
        $ldap->serverType = $ldapservertype;
        $ldap->searchUser = $ldapadminlogin;
        $ldap->searchPassword = $ldapadminpass;
        if ($ldapdebug) {
            dol_syslog("functions_ldap::check_user_password_ldap Server:" . join(',', $ldap->server) . ", Port:" . $ldap->serverPort . ", Protocol:" . $ldap->ldapProtocolVersion . ", Type:" . $ldap->serverType);
            dol_syslog("functions_ldap::check_user_password_ldap uid/samacountname=" . $ldapuserattr . ", dn=" . $ldapdn . ", Admin:" . $ldap->searchUser . ", Pass:"******"DEBUG: Server:" . join(',', $ldap->server) . ", Port:" . $ldap->serverPort . ", Protocol:" . $ldap->ldapProtocolVersion . ", Type:" . $ldap->serverType . "<br>\n";
            print "DEBUG: uid/samacountname=" . $ldapuserattr . ", dn=" . $ldapdn . ", Admin:" . $ldap->searchUser . ", Pass:"******"<br>\n";
        }
        $resultFetchLdapUser = 0;
        // Define $userSearchFilter
        $userSearchFilter = "";
        if (empty($dolibarr_main_auth_ldap_filter)) {
            $userSearchFilter = "(" . $ldapuserattr . "=" . $usertotest . ")";
        } else {
            $userSearchFilter = str_replace('%1%', $usertotest, $dolibarr_main_auth_ldap_filter);
        }
        // If admin login provided
        // Code to get user in LDAP from an admin connection (may differ from user connection, done later)
        if ($ldapadminlogin) {
            $result = $ldap->connect_bind();
            if ($result > 0) {
                $resultFetchLdapUser = $ldap->fetch($usertotest, $userSearchFilter);
                //dol_syslog('functions_ldap::check_user_password_ldap resultFetchLdapUser='******'functions_ldap::check_user_password_ldap ' . $usertotest . ' must change password next logon');
                    if ($ldapdebug) {
                        print "DEBUG: User " . $usertotest . " must change password<br>\n";
                    }
                    $ldap->close();
                    sleep(1);
                    $langs->load('ldap');
                    $_SESSION["dol_loginmesg"] = $langs->trans("YouMustChangePassNextLogon", $usertotest, $ldap->domainFQDN);
                    return '';
                }
            } else {
                if ($ldapdebug) {
                    print "DEBUG: " . $ldap->error . "<br>\n";
                }
            }
            $ldap->close();
        }
        // Forge LDAP user and password to test with them
        // If LDAP need a dn with login like "uid=jbloggs,ou=People,dc=foo,dc=com", default dn may work even if previous code with
        // admin login no exectued.
        $ldap->searchUser = $ldapuserattr . "=" . $usertotest . "," . $ldapdn;
        // Default dn (will work if LDAP accept a dn with login value inside)
        // But if LDAP need a dn with name like "cn=Jhon Bloggs,ou=People,dc=foo,dc=com", previous part must have been executed to have
        // dn detected into ldapUserDN.
        if ($resultFetchLdapUser and !empty($ldap->ldapUserDN)) {
            $ldap->searchUser = $ldap->ldapUserDN;
        }
        $ldap->searchPassword = $passwordtotest;
        // Test with this->seachUser and this->searchPassword
        //print $resultFetchLdapUser."-".$ldap->ldapUserDN."-".$ldap->searchUser.'-'.$ldap->searchPassword;exit;
        $result = $ldap->connect_bind();
        if ($result > 0) {
            if ($result == 2) {
                dol_syslog("functions_ldap::check_user_password_ldap Authentification ok");
                $login = $usertotest;
                // ldap2dolibarr synchronisation
                if ($login && !empty($conf->ldap->enabled) && $conf->global->LDAP_SYNCHRO_ACTIVE == 'ldap2dolibarr') {
                    dol_syslog("functions_ldap::check_user_password_ldap Sync ldap2dolibarr");
                    // On charge les attributs du user ldap
                    if ($ldapdebug) {
                        print "DEBUG: login ldap = " . $login . "<br>\n";
                    }
                    $resultFetchLdapUser = $ldap->fetch($login, $userSearchFilter);
                    if ($ldapdebug) {
                        print "DEBUG: UACF = " . join(',', $ldap->uacf) . "<br>\n";
                    }
                    if ($ldapdebug) {
                        print "DEBUG: pwdLastSet = " . dol_print_date($ldap->pwdlastset, 'day') . "<br>\n";
                    }
                    if ($ldapdebug) {
                        print "DEBUG: badPasswordTime = " . dol_print_date($ldap->badpwdtime, 'day') . "<br>\n";
                    }
                    // On recherche le user dolibarr en fonction de son SID ldap
                    $sid = $ldap->getObjectSid($login);
                    if ($ldapdebug) {
                        print "DEBUG: sid = " . $sid . "<br>\n";
                    }
                    $usertmp = new User($db);
                    $resultFetchUser = $usertmp->fetch('', $login, $sid);
                    if ($resultFetchUser > 0) {
                        dol_syslog("functions_ldap::check_user_password_ldap Sync user found user id=" . $usertmp->id);
                        // On verifie si le login a change et on met a jour les attributs dolibarr
                        if ($usertmp->login != $ldap->login && $ldap->login) {
                            $usertmp->login = $ldap->login;
                            $usertmp->update($usertmp);
                            // TODO Que faire si update echoue car on update avec un login deja existant.
                        }
                        //$resultUpdate = $usertmp->update_ldap2dolibarr($ldap);
                    }
                    unset($usertmp);
                }
                if (!empty($conf->multicompany->enabled)) {
                    global $mc;
                    $usertmp = new User($db);
                    $usertmp->fetch('', $login);
                    $ret = $mc->checkRight($usertmp->id, $entitytotest);
                    if ($ret < 0) {
                        dol_syslog("functions_ldap::check_user_password_ldap Authentification ko entity '" . $entitytotest . "' not allowed for user '" . $usertmp->id . "'");
                        $login = '';
                        // force authentication failure
                    }
                    unset($usertmp);
                }
            }
            if ($result == 1) {
                dol_syslog("functions_ldap::check_user_password_ldap Authentification ko bad user/password for '" . $usertotest . "'");
                sleep(1);
                $langs->load('main');
                $langs->load('other');
                $_SESSION["dol_loginmesg"] = $langs->trans("ErrorBadLoginPassword");
            }
        } else {
            /* Login failed. Return false, together with the error code and text from
             ** the LDAP server. The common error codes and reasons are listed below :
             ** (for iPlanet, other servers may differ)
             ** 19 - Account locked out (too many invalid login attempts)
             ** 32 - User does not exist
             ** 49 - Wrong password
             ** 53 - Account inactive (manually locked out by administrator)
             */
            dol_syslog("functions_ldap::check_user_password_ldap Authentification ko failed to connect to LDAP for '" . $usertotest . "'");
            if (is_resource($ldap->connection)) {
                $ldap->ldapErrorCode = ldap_errno($ldap->connection);
                $ldap->ldapErrorText = ldap_error($ldap->connection);
                dol_syslog("functions_ldap::check_user_password_ldap " . $ldap->ldapErrorCode . " " . $ldap->ldapErrorText);
            }
            sleep(1);
            $langs->load('main');
            $langs->load('other');
            $langs->load('errors');
            $_SESSION["dol_loginmesg"] = $ldap->error ? $ldap->error : $langs->trans("ErrorBadLoginPassword");
        }
        $ldap->close();
    }
    return $login;
}
Beispiel #19
0
<?php

if (!defined('PHPWG_ROOT_PATH')) {
    die('Hacking attempt!');
}
/*
*
*	Here we have everything if valid ldap users are allowed or not to connect to piwigo
*	Valid ldap users with no piwigo login can create their login this way.
*
*/
global $template;
$template->set_filenames(array('plugin_admin_content' => dirname(__FILE__) . '/newusers.tpl'));
$template->assign(array('PLUGIN_NEWUSERS' => get_root_url() . 'admin.php?page=plugin-Ldap_Login-newusers'));
$me = new Ldap();
$me->load_config();
// do we allow new users to have a piwigo login created if they have a valid ldap login ?
$template->assign('ALLOW_NEWUSERS', $me->config['allow_newusers']);
// do we send a mail to admins in case of new users ?
$template->assign('ADVERTISE_ADMINS', $me->config['advertise_admin_new_ldapuser']);
// do we send the piwigo (!) password to the mail address provided by ldap ?
$template->assign('SEND_CASUAL_MAIL', $me->config['send_password_by_mail_ldap']);
// Is there a restriction in the ldap users group ?
// Only members of this ldap group can log in !
$template->assign('USERS_GROUP', $me->config['users_group']);
if (isset($_POST['save'])) {
    $me->config['users_group'] = $_POST['USERS_GROUP'];
    if (isset($_POST['ALLOW_NEWUSERS'])) {
        $me->config['allow_newusers'] = True;
    } else {
        $me->config['allow_newusers'] = False;
Beispiel #20
0
 function is_what($login, $what)
 {
     $ldapconnisuid = Ldap::lda_connect(LDAP_ADMIN_DN, LDAP_ADMIN_PASS);
     $filter = "(" . $what . "=" . $login . ")";
     $sr = ldap_search($ldapconnisuid, LDAP_BASE, $filter);
     $info = ldap_get_entries($ldapconnisuid, $sr);
     if ($info['count']) {
         ldap_unbind($ldapconnisuid);
         return $info['count'];
     } else {
         ldap_unbind($ldapconnisuid);
         return FALSE;
     }
 }
Beispiel #21
0
 public function __construct($host = null, $port = 389, $version = 3, $useSsl = false, $useStartTls = false, $optReferrals = false, LdapInterface $ldap = null)
 {
     $config = array('host' => $host, 'port' => $port, 'version' => $version, 'useSsl' => (bool) $useSsl, 'useStartTls' => (bool) $useStartTls, 'optReferrals' => (bool) $optReferrals);
     $this->ldap = null !== $ldap ? $ldap : Ldap::create('ext_ldap', $config);
 }
Beispiel #22
0
 */
@(include_once 'classes/Ldap.php');
@(include_once '../../install/config.ldap.php');
$ldap_account_email = $_POST['accEmail'];
$ldap_account_full_name = $_POST['accFullName'];
$ldap_account_base = $_POST['accBase'];
$ldap_user_pattern = $_POST['userPattern'];
$ldap_server = $_POST['ldapHost'];
$ldap_port = $_POST['ldapPort'];
$ldap_ssl_verify = $_POST['ldapSslVerify'] == 'true' ? true : false;
$ldap_start_tls = $_POST['ldapStartTls'] == 'true' ? true : false;
$ldap_bind_type = $_POST['bindType'];
$ldap_bind_scope = $_POST['bindScope'];
$ldap_password = isset($_POST['ldapPass']) && trim($_POST['ldapPass']) != '' ? $_POST['ldapPass'] : null;
$ldap_username = isset($_POST['ldapUser']) && trim($_POST['ldapUser']) != '' ? $_POST['ldapUser'] : null;
$auth = new Ldap();
$auth->setLdapAccountBase($ldap_account_base);
$auth->setLdapAccountEmail($ldap_account_email);
$auth->setLdapAccountFullname($ldap_account_full_name);
$auth->setLdapBindType($ldap_bind_type);
$auth->setLdapBindScope($ldap_bind_scope);
$auth->setLdapPassword($ldap_password);
$auth->setLdapUsername($ldap_username);
$auth->setLdapPort($ldap_port);
$auth->setLdapServer($ldap_server);
$auth->setLdapSslVerify($ldap_ssl_verify);
$auth->setLdapStartTls($ldap_start_tls);
$auth->setLdapUserPattern($ldap_user_pattern);
try {
    $username = $auth->getLdapUserAttribute();
    $info = $auth->listAllUsers(array($auth->getLdapUserAttribute(), $ldap_account_full_name, $ldap_account_email), 0);
/*
 * Test de la connexion
 */
$butlabel = $langs->trans("LDAPTestSynchroContact");
$testlabel = 'test';
$key = $conf->global->LDAP_KEY_CONTACTS;
$dn = $conf->global->LDAP_CONTACT_DN;
$objectclass = $conf->global->LDAP_CONTACT_OBJECT_CLASS;
show_ldap_test_button($butlabel, $testlabel, $key, $dn, $objectclass);
if (function_exists("ldap_connect")) {
    if ($_GET["action"] == 'test') {
        // Creation objet
        $object = new Contact($db);
        $object->initAsSpecimen();
        // Test synchro
        $ldap = new Ldap();
        $result = $ldap->connect_bind();
        if ($result > 0) {
            $info = $object->_load_ldap_info();
            $dn = $object->_load_ldap_dn($info);
            $result1 = $ldap->delete($dn);
            // To be sure to delete existing records
            $result2 = $ldap->add($dn, $info, $user);
            // Now the test
            $result3 = $ldap->delete($dn);
            // Clean what we did
            if ($result2 > 0) {
                print img_picto('', 'info') . ' ';
                print '<font class="ok">' . $langs->trans("LDAPSynchroOK") . '</font><br>';
            } else {
                print img_picto('', 'error') . ' ';
Beispiel #24
0
 /**
  * Factory method to create an attached Zend_Ldap_Node for a given DN.
  *
  * @param  string|array|\Zend\Ldap\Dn $dn
  * @param  \Zend\Ldap\Ldap                 $ldap
  * @return \Zend\Ldap\Node|null
  * @throws \Zend\Ldap\Exception
  */
 public static function fromLdap($dn, Ldap $ldap)
 {
     if (is_string($dn) || is_array($dn)) {
         $dn = Dn::factory($dn);
     } else {
         if ($dn instanceof Dn) {
             $dn = clone $dn;
         } else {
             throw new Exception(null, '$dn is of a wrong data type.');
         }
     }
     $data = $ldap->getEntry($dn, array('*', '+'), true);
     if ($data === null) {
         return null;
     }
     $entry = new self($dn, $data, true, $ldap);
     return $entry;
 }
 protected function newLdap($config)
 {
     $ldap = new Ldap();
     $ldap->setHost($config['host']);
     $ldap->setPort($config['port']);
     $ldap->setDomain($config['domain']);
     $ldap->setLdapPrefix($config['suffix']);
     $ldap->setWindows(false);
     // FIXME: use configuration to determine this flag
     switch ($config['security']) {
         case 1:
             // TLS
             $ldap->setLdapTLS(true);
             $ldap->setLdapSecure(false);
             break;
         case 2:
             // SSL
             $ldap->setLdapTLS(false);
             $ldap->setLdapSecure(true);
             break;
         default:
             // unsecure
             $ldap->setLdapTLS(false);
             $ldap->setLdapSecure(false);
             break;
     }
     return $ldap;
 }
Beispiel #26
0
    /*                                                                            */
    /* View and edition                                                            */
    /*                                                                            */
    /* ************************************************************************** */

    if ($id > 0)
    {
        $object->fetch($id);
        if ($res < 0) { dol_print_error($db,$object->error); exit; }
        $res=$object->fetch_optionals($object->id,$extralabels);

        // Connexion ldap
        // pour recuperer passDoNotExpire et userChangePassNextLogon
        if (! empty($conf->ldap->enabled) && ! empty($object->ldap_sid))
        {
            $ldap = new Ldap();
            $result=$ldap->connect_bind();
            if ($result > 0)
            {
                $userSearchFilter = '('.$conf->global->LDAP_FILTER_CONNECTION.'('.$ldap->getUserIdentifier().'='.$object->login.'))';
                $entries = $ldap->fetch($object->login,$userSearchFilter);
                if (! $entries)
                {
                    setEventMessages($ldap->error, $ldap->errors, 'errors');
                }

                $passDoNotExpire = 0;
                $userChangePassNextLogon = 0;
                $userDisabled = 0;
                $statutUACF = '';
Beispiel #27
0
<?php

require_once 'smarty3/Smarty.class.php';
require_once dirname(__FILE__) . '/../model/Siga.php';
require_once dirname(__FILE__) . '/../model/Ldap.php';
session_start();
//Objeto da classe LDAP
$ldap = new Ldap();
//Se a variável login não existir na sessão, não deixar passar do index
if (!array_key_exists('login', $_SESSION)) {
    header('Location: index.php');
    exit;
    //Se o usuário for um solicitante, ele não poderá alterar seus dados
} else {
    if ($ldap->userExists($_SESSION['login'], "ou=solicitacoes")) {
        header('Location: home.php');
    }
}
$s = new Smarty();
//Diretório de templates
$s->addTemplateDir("../view/templates");
//Diretório de templates compilados
$s->setCompileDir("../view/com_templates");
$usuario = $ldap->getUsuario($_SESSION['login']);
//Verifica se o usuário possui foto
if ($usuario->jpegPhoto) {
    //Se existir, baixar a foto para a pasta do site e associar valor verdadeiro à variável foto, usada no html da "home"
    file_put_contents("imagens/" . $usuario->uid . ".jpg", $usuario->jpegPhoto);
    //Este valor é utilizado num if. Se o usuário tiver foto, carregar a foto dele. Se não, carregar a imagem padrão
    $s->assign('foto', true);
} else {
Beispiel #28
0
 public function testBindAnonymous()
 {
     $ldap = new Ldap($this->container);
     self::$functions->expects($this->once())->method('ldap_bind')->with($this->equalTo('my_ldap_connection'), $this->equalTo(null), $this->equalTo(null))->will($this->returnValue(true));
     $this->assertTrue($ldap->bind('my_ldap_connection', 'my_user', 'my_password', 'anonymous'));
 }
Beispiel #29
0
function cacti_ldap_search_dn($username, $dn = "", $host = "", $port = "", $port_ssl = "", $version = "", $encryption = "", $referrals = "", $mode = "", $search_base = "", $search_filter = "", $specific_dn = "", $specific_password = "")
{
    $ldap = new Ldap();
    if (!empty($username)) {
        $ldap->username = $username;
    }
    if (!empty($dn)) {
        $ldap->dn = $dn;
    }
    if (!empty($host)) {
        $ldap->host = $host;
    }
    if (!empty($port)) {
        $ldap->port = $port;
    }
    if (!empty($port_ssl)) {
        $ldap->port_ssl = $port_ssl;
    }
    if (!empty($version)) {
        $ldap->version = $version;
    }
    if (!empty($encryption)) {
        $ldap->encryption = $encryption;
    }
    if (!empty($referrals)) {
        $ldap->referrals = $referrals;
    }
    if (!empty($mode)) {
        $ldap->mode = $mode;
    }
    if (!empty($search_base)) {
        $ldap->search_base = $search_base;
    }
    if (!empty($search_filter)) {
        $ldap->search_filter = $search_filter;
    }
    if (!empty($specific_dn)) {
        $ldap->specific_dn = $specific_dn;
    }
    if (!empty($specific_password)) {
        $ldap->specific_password = $specific_password;
    }
    return $ldap->Search();
}
Beispiel #30
0
 */
if ($conf->global->LDAP_SYNCHRO_ACTIVE == 'dolibarr2ldap') {
    $butlabel = $langs->trans("LDAPTestSynchroGroup");
    $testlabel = 'testgroup';
    $key = $conf->global->LDAP_KEY_GROUPS;
    $dn = $conf->global->LDAP_GROUP_DN;
    $objectclass = $conf->global->LDAP_GROUP_OBJECT_CLASS;
    show_ldap_test_button($butlabel, $testlabel, $key, $dn, $objectclass);
}
if (function_exists("ldap_connect")) {
    if ($_GET["action"] == 'testgroup') {
        // Creation objet
        $object = new UserGroup($db);
        $object->initAsSpecimen();
        // Test synchro
        $ldap = new Ldap();
        $result = $ldap->connect_bind();
        if ($result > 0) {
            $info = $object->_load_ldap_info();
            $dn = $object->_load_ldap_dn($info);
            // Get a gid number for objectclass PosixGroup
            if (in_array('posixGroup', $info['objectclass'])) {
                $info['gidNumber'] = $ldap->getNextGroupGid();
            }
            $result1 = $ldap->delete($dn);
            // To be sure to delete existing records
            $result2 = $ldap->add($dn, $info, $user);
            // Now the test
            $result3 = $ldap->delete($dn);
            // Clean what we did
            if ($result2 > 0) {