Exemple #1
6
 public static function lookup($query, $type)
 {
     $person_array = array();
     $x500 = ldap_connect('ldap.utexas.edu');
     $bind = ldap_bind($x500);
     $dn = "ou=people,dc=directory,dc=utexas,dc=edu";
     $filter = "{$type}={$query}";
     $ldap_result = @ldap_search($x500, $dn, $filter);
     $attributes = array('eid' => 'uid', 'email' => 'mail', 'name' => 'cn', 'firstname' => 'givenname', 'lastname' => 'sn', 'office' => 'utexasedupersonofficelocation', 'phone' => 'telephonenumber', 'title' => 'title', 'unit' => 'ou');
     if ($ldap_result) {
         $entry_array = ldap_get_entries($x500, $ldap_result);
         for ($i = 0; $i < count($entry_array) - 1; $i++) {
             $person = array();
             if ($entry_array[$i]) {
                 $eid = $entry_array[$i]['uid'][0];
                 foreach ($attributes as $label => $att) {
                     if (isset($entry_array[$i][$att])) {
                         $person[$label] = $entry_array[$i][$att][0];
                     } else {
                         $person[$label] = '';
                     }
                 }
             }
             $person_array[] = $person;
         }
         ldap_close($x500);
     }
     return $person_array;
 }
function ldap_authenticate($user, $pass)
{
    // Global variables
    global $ldap_base_DN, $ldap_server, $template, $admin_users, $ldap_user_cn;
    // Connect to the LDAP server
    $conn = ldap_connect($ldap_server) or die("Cannot connect");
    ldap_set_option($conn, LDAP_OPT_PROTOCOL_VERSION, 3);
    // Bind anonymously, query the server for the user, and error if it can't be found
    if (!($bind = ldap_bind($conn))) {
        $template['message'] = "<p>Anonymous bind failed.</p>";
        return;
    }
    // Do a search for the username and get the DN - this is easier than manually constructing it
    if (!($search = ldap_search($conn, $ldap_base_DN, "{$ldap_user_cn}={$user}"))) {
        $template['message'] = "<p><strong>Error:</strong> Could not find the username.</p>";
        return;
    }
    // If there isn't only one row.
    if (ldap_count_entries($conn, $search) != 1) {
        $template['message'] = "<p>There was an error processing the username, or it cannot be found.</p>";
        return;
    }
    // Extract the entries, and bind with the user's full DN, then unset the password for security
    $entries = @ldap_get_entries($conn, $search);
    $bind_auth = @ldap_bind($conn, $entries[0]['dn'], $pass);
    unset($pass);
    // If we have a successful bind, add the relevant session information
    if ($bind_auth) {
        $_SESSION['admin'] = in_array($user, $admin_users);
        $_SESSION['username'] = $user;
        header('Location: index.php');
    } else {
        $template['message'] = "<p><strong>Login failed.</strong> Please try again.</p>";
    }
}
Exemple #3
1
 protected function loadPage()
 {
     if (!ldap_control_paged_result($this->connection, $this->pageSize, true, $this->pageToken)) {
         throw new SearchException("Unable to set paged control pageSize: " . $this->pageSize);
     }
     $search = ldap_search($this->connection, $this->baseDn, $this->filter, is_array($this->attributes) ? $this->attributes : []);
     if (!$search) {
         // Something went wrong in search
         throw Connection::createLdapSearchException(ldap_errno($this->connection), $this->baseDn, $this->filter, $this->pageSize);
     }
     $this->entries = ldap_get_entries($this->connection, $search);
     $this->entriesPosition = 0;
     if (!$this->entries) {
         throw Connection::createLdapSearchException(ldap_errno($this->connection), $this->baseDn, $this->filter, $this->pageSize);
     }
     // check if on first page
     if (empty($this->pageToken)) {
         $this->currentPage = 0;
     } else {
         $this->currentPage++;
     }
     // Ok go to next page
     ldap_control_paged_result_response($this->connection, $search, $this->pageToken);
     if (empty($this->pageToken)) {
         $this->isLastPage = true;
     }
 }
 public function connect()
 {
     // basic sequence with LDAP is connect, bind, search, interpret search
     // result, close connection
     $ds = ldap_connect("192.168.0.111");
     // must be a valid LDAP server!
     if ($ds) {
         $r = ldap_bind($ds, "portalusr01", "tbs4portal");
         // this is an "anonymous" bind, typically
         if (!$r) {
             echo "Unable to connect to LDAP server";
             die;
         }
         // Search surname entry
         //			$dn = "OU=Users,OU=PT. Monica Hijau Lestari,DC=thebodyshop,DC=co,DC=id";
         $dn = "OU=Users,OU=ho-bintaro,DC=thebodyshop,DC=co,DC=id";
         $filter = "(|(SN=*)(CN=*))";
         $sr = ldap_search($ds, $dn, $filter);
         $info = ldap_get_entries($ds, $sr);
         $dn = "OU=user,OU=warehouse-bsd,DC=thebodyshop,DC=co,DC=id";
         $filter = "(|(SN=*)(CN=*))";
         $sr = ldap_search($ds, $dn, $filter);
         $infoDc = ldap_get_entries($ds, $sr);
         $this->parseUsers($info, $infoDc);
         ldap_close($ds);
     } else {
         echo "Unable to connect to LDAP server";
     }
 }
 function DoTest($testname, $param, $hostname, $timeout, $params)
 {
     global $NATS;
     $url = $params[0];
     $bind = $params[1];
     $pasw = $params[2];
     $base = $params[3];
     $filter = $params[4];
     $ds = ldap_connect($url);
     if (!$ds) {
         return -2;
     }
     $ldap = $bind && $pasw ? ldap_bind($ds, $bind, $pasw) : ldap_bind($ds);
     if (!$ldap) {
         return -1;
     }
     if ($base && $filter) {
         $search = ldap_search($ds, $base, $filter);
         $val = ldap_count_entries($ds, $search);
     } else {
         $val = 1;
     }
     ldap_close($ds);
     return $val;
 }
Exemple #6
0
function authenticate($username, $password)
{
    global $error;
    sleep(1);
    $server = "ldap.rit.edu";
    //RIT LDAP Server
    $basedn = "ou=people,dc=rit,dc=edu";
    //Base DN
    $script = $_SERVER['SCRIPT_NAME'];
    $filter = "(uid={$username})";
    //$filter="(&(|(!(displayname=Administrator*))(!(displayname=Admin*)))(uid=$username))";    //define an appropriate ldap search filter to find your users, and filter out accounts such as administrator(administrator should be renamed anyway!).
    $dn = "uid={$username}, ";
    if (!($connect = ldap_connect($server))) {
        return 0;
    }
    ini_set("display_errors", "0");
    if (!($bind = ldap_bind($connect, "{$dn}" . $basedn, $password)) || empty($password)) {
        $error = "You either have a wrong username or wrong password";
        return 0;
    }
    ini_set("display_errors", "1");
    $sr = ldap_search($connect, $basedn, "{$filter}");
    $info = ldap_get_entries($connect, $sr);
    $_SESSION['accountUserName'] = $username;
    $_SESSION['accountFirstName'] = $info[0]['givenname'][0];
    $_SESSION['accountLastName'] = $info[0]['sn'][0];
    $_SESSION['accountPhone'] = $info[0]['telephonenumber'][0];
    $_SESSION['accountEmail'] = $info[0]['mail'][0];
    $_SESSION['accountType'] = $info[0]['riteduaccounttype'][0];
    return 1;
}
Exemple #7
0
 function Logon($user, $domain, $pass)
 {
     debugLog('Wiper::Logon: ' . $user . '/' . $pass);
     if ($user == "") {
         debugLog('Wiper::Logon: No user name.');
     }
     if ($pass == "") {
         debugLog('Wiper::Logon: No password.');
     }
     $link_id = ldap_connect(LDAP_SERVER, 389);
     if (!$link_id) {
         debugLog('Wiper::Logon: Cannot connect LDAP server.');
     }
     if (!ldap_set_option($link_id, LDAP_OPT_PROTOCOL_VERSION, 3)) {
         debugLog('Wiper::Logon: Failed to set v3 protocol.');
     }
     $dn = LDAP_DOMAIN;
     $filter = "(&(objectclass=person)(userPassword=*)(|(uid={$user})(cn={$user})) )";
     $attributes = array('cn', 'userpassword', 'uid');
     $search = ldap_search($link_id, $dn, $filter, $attributes);
     $info = ldap_get_entries($link_id, $search);
     if ($info['count'] == 0) {
         debugLog("Wiper::Logon: No such ID: {$user}");
         return false;
     }
     if (!ldap_bind($link_id, $info[0]['dn'], $pass)) {
         debugLog("Wiper::Logon: Invalid Password: {$user}");
         return false;
     }
     return true;
 }
Exemple #8
0
 public function __construct($userKey)
 {
     $config = new Configuration();
     //try to connect to ldap if the settings are entered
     if ($config->ldap->host) {
         //If you are using OpenLDAP 2.x.x you can specify a URL instead of the hostname. To use LDAP with SSL, compile OpenLDAP 2.x.x with SSL support, configure PHP with SSL, and set this parameter as ldaps://hostname/.
         //note that connect happens regardless if host is valid
         $ds = ldap_connect($config->ldap->host);
         //may need ldap_bind( $ds, $username, $password )
         $bd = ldap_bind($ds) or die("<br /><h3>" . _("Could not connect to ") . $config->ldap->host . "</h3>");
         if ($bd) {
             $filter = $config->ldap->search_key . "=" . $userKey;
             $sr = ldap_search($ds, $config->ldap->base_dn, $filter);
             if ($entries = ldap_get_entries($ds, $sr)) {
                 $entry = $entries[0];
                 $fieldNames = array('fname', 'lname', 'email', 'phone', 'department', 'title', 'address');
                 foreach ($fieldNames as $fieldName) {
                     $configName = $fieldName . '_field';
                     $this->{$fieldName} = $entry[$config->ldap->{$configName}][0];
                 }
                 $this->fullname = addslashes($this->fname . ' ' . $this->lname);
             }
             ldap_close($ds);
         }
     }
 }
Exemple #9
0
function login_ad($user_, $pass_, $tipo_)
{
    //Comienzo la conexión al servidor para tomar los datos de active directory
    $host = get_config('host');
    $puerto = get_config('puerto');
    $filter = "sAMAccountName=" . $user_ . "*";
    $attr = array("displayname", "mail", "givenname", "sn", "useraccountcontrol");
    $dn = get_config('dn');
    $conex = ldap_connect($host, $puerto) or die("No ha sido posible conectarse al servidor");
    if (!ldap_set_option($conex, LDAP_OPT_PROTOCOL_VERSION, 3)) {
        echo "<br>Failed to set protocol version to 3";
    }
    if ($conex) {
        $dominio = get_config("dominio");
        $r = @ldap_bind($conex, $user_ . $dominio, $pass_);
        $existe = get_perfil($user_, $tipo_);
        if ($r && count($existe) > 0) {
            //LOGIN CORRECTO
            $result = ldap_search($conex, $dn, $filter, $attr);
            $entries = ldap_get_entries($conex, $result);
            for ($i = 0; $i < $entries["count"]; $i++) {
                $nombre = fix_data(utf8_decode($entries[$i]["givenname"][0]));
                $apellidos = fix_data(utf8_decode($entries[$i]["sn"][0]));
                $email = fix_data($entries[$i]["mail"][0]);
                //Acutalizar información desde AD en la tabla de empleados
                $s_ = "update empleados set nombre='{$nombre}', apellidos='{$apellidos}', mail='{$email}' where id='{$existe['id']}'";
                $r_ = mysql_query($s_);
                session_name("loginUsuario");
                session_start();
                $_SESSION['NAME'] = $nombre . " " . $apellidos;
                $_SESSION['USER'] = $user_;
                $_SESSION['IDEMP'] = $existe['id'];
                $_SESSION['AUSENCIA'] = get_ausencia($existe['id']);
                $_SESSION['DEPTO'] = $existe['depto'];
                $_SESSION['TYPE'] = $tipo_;
            }
            switch ($tipo_) {
                case "administrador":
                    header("Location: admin/inicio.php");
                    break;
                case "capturista":
                    header("Location: capturista/inicio.php");
                    break;
                case "autorizador":
                    header("Location: autorizador/scrap_firmar.php");
                    break;
                case "reportes":
                    header("Location: reportes/rep_general.php?op=listado");
                    break;
            }
        } else {
            echo "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"0; URL=index.php?error=2&user_={$user_}&tipo_={$tipo_}\">";
            exit;
        }
        ldap_close($conex);
    } else {
        echo "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"0; URL=index.php?error=3&user_={$user_}&tipo_={$tipo_}\">";
        exit;
    }
}
Exemple #10
0
function ldap_auth()
{
    $ldap_server = 'ldap://127.0.0.1/';
    $ldap_domain = 'dc=rugion,dc=ru';
    //$ldap_userbase = 'ou=users,ou=chelyabinsk,' . $ldap_domain;
    //$ldap_user = '******' . $_SERVER['PHP_AUTH_USER'] . ',' . $ldap_userbase;
    $ldap_user = '******';
    $ldap_pass = $_SERVER['PHP_AUTH_PW'];
    $ldapconn_s = ldap_connect($ldap_server) or die("Could not connect to LDAP server.");
    ldap_set_option($ldapconn_s, LDAP_OPT_PROTOCOL_VERSION, 3);
    if ($ldapconn_s) {
        $ldapbind_s = @ldap_bind($ldapconn_s);
        $result = ldap_search($ldapconn_s, $ldap_domain, "(&(uid=" . $_SERVER['PHP_AUTH_USER'] . ")(objectClass=sambaSamAccount)(!(sambaAcctFlags=[DU ])))");
        $info = ldap_get_entries($ldapconn_s, $result);
        $ldap_user = $info[0]["dn"];
    }
    ldap_close($ldapconn_s);
    // connect to ldap server
    $ldapconn = ldap_connect($ldap_server) or die("Could not connect to LDAP server.");
    ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
    if ($ldapconn) {
        // try to bind/authenticate against ldap
        $ldapbind = @ldap_bind($ldapconn, $ldap_user, $ldap_pass) || forbidden();
        // "LDAP bind successful...";
        error_log("success: " . $_SERVER['REMOTE_ADDR'] . ', user: '******'PHP_AUTH_USER']);
    }
    ldap_close($ldapconn);
}
function get_ldap_members($group, $user, $password)
{
    global $ldap_host;
    global $ldap_dn;
    $LDAPFieldsToFind = array("member");
    print "{$ldap_host} {$ldap_dn}\n";
    $ldap = ldap_connect($ldap_host) or die("Could not connect to LDAP");
    // OPTIONS TO AD
    ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
    ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
    ldap_bind($ldap, $user, $password) or die("Could not bind to LDAP");
    //check if group is just a name or an ldap string
    $group_cn = preg_match("/cn=/i", $group) ? $group : "cn={$group}";
    $results = ldap_search($ldap, $ldap_dn, $group_cn, $LDAPFieldsToFind);
    $member_list = ldap_get_entries($ldap, $results);
    $group_member_details = array();
    if (is_array($member_list[0])) {
        foreach ($member_list[0] as $list) {
            if (is_array($list)) {
                foreach ($list as $member) {
                    $member_dn = explode_dn($member);
                    $member_cn = str_replace("CN=", "", $member_dn[0]);
                    $member_search = ldap_search($ldap, $ldap_dn, "(CN=" . $member_cn . ")");
                    $member_details = ldap_get_entries($ldap, $member_search);
                    $group_member_details[] = array($member_details[0]['samaccountname'][0], $member_details[0]['displayname'][0], $member_details[0]['useraccountcontrol'][0]);
                }
            }
        }
    }
    ldap_close($ldap);
    array_shift($group_member_details);
    return $group_member_details;
    ldap_unbind($ldap);
}
function AD_Login($user, $password, &$userdata)
{
    global $SYS;
    $adServer = $SYS["AUTH"]["activedirectory"]["server"];
    $basedn = $SYS["AUTH"]["activedirectory"]["basedn"];
    $searchuserdn = $SYS["AUTH"]["activedirectory"]["searchdn"];
    $domain = $SYS["AUTH"]["activedirectory"]["domain"];
    $ldapconn = ldap_connect($adServer);
    if (!$ldapconn) {
        return false;
    }
    $ldapbind = ldap_bind($ldapconn, "{$user}@{$domain}", $password);
    if ($ldapbind) {
        // We're inside!!
        $filter = "CN={$user}";
        foreach ($SYS["AUTH"]["activedirectory"]["searchdn"] as $v) {
            $sr = ldap_search($ldapconn, " {$v},{$basedn}", $filter);
            if ($sr) {
                $info = ldap_get_entries($ldapconn, $sr);
                if ($info["count"] > 0) {
                    $userdata["username"] = $info[0]["cn"][0];
                    $guessNameArr1 = explode("-", $info[0]["displayname"][0]);
                    $guessNameArr = explode(" ", trim($guessNameArr1[0]));
                    $userdata["apellidos"] = $guessNameArr[sizeof($guessNameArr) - 2] . " " . $guessNameArr[sizeof($guessNameArr) - 1];
                    $nombreArr = array_shift(array_reverse($guessNameArr));
                    $userdata["nombre"] = str_replace($userdata["apellidos"], "", trim($guessNameArr1[0]));
                    $userdata["email"] = $info[0]["mail"][0];
                    return true;
                }
            }
        }
    }
    return false;
}
Exemple #13
0
/**
 * Load current tags of an entry
 */
function ajax_loadtags($dn, $type = 'plain')
{
    global $conf;
    global $LDAP_CON;
    global $FIELDS;
    if (!$FIELDS['_marker']) {
        return;
    }
    header('Content-Type: text/html; charset=utf-8');
    $sr = ldap_search($LDAP_CON, $dn, '(objectClass=inetOrgPerson)', array($FIELDS['_marker']));
    if (!ldap_count_entries($LDAP_CON, $sr)) {
        return false;
    }
    $result = ldap_get_binentries($LDAP_CON, $sr);
    $entry = $result[0];
    if ($type == 'plain') {
        echo join(', ', (array) $entry[$FIELDS['_marker']]);
    } else {
        foreach ((array) $entry[$FIELDS['_marker']] as $tag) {
            echo '<a href="index.php?marker=';
            echo rawurlencode($tag);
            echo '" class="tag">';
            echo htmlspecialchars($tag);
            echo '</a> ';
        }
    }
}
Exemple #14
0
 /**
  * Conecta ao servidor LDAP com o usuário e senha configurado e depois verifica
  * se existe o usuário e senha informados por parâmetro.
  *
  * @param type $username
  * @param type $password
  *
  * @throws \Exception
  *
  * @return bool
  */
 public function auth($username, $password)
 {
     if ($this->host) {
         $message = _('Não foi possível conectar ao servidor LDAP. Favor verificar se as configurações estão corretas.');
         list($conn, $bind) = $this->connect($this->username, $this->password);
         if ($conn && $bind) {
             if (!empty($this->filter)) {
                 $filter = $this->filter[0] != '(' ? '(' . $this->filter . ')' : $this->filter;
                 $filter = sprintf('(&%s(%s=%s))', $filter, $this->loginAttribute, $username);
             } else {
                 $filter = sprintf('(%s=%s)', $this->loginAttribute, $username);
             }
             $search = @ldap_search($conn, $this->baseDn, $filter);
             if ($search) {
                 $result = @ldap_get_entries($conn, $search);
                 if ($result && $result['count'] == 1) {
                     $user = $result[0];
                     $bind = @ldap_bind($conn, $user['dn'], $password);
                     if ($bind) {
                         return $this->createUser($username, $user);
                     }
                 }
             } else {
                 throw new \Exception($message);
             }
         } else {
             throw new \Exception($message);
         }
     }
     return parent::auth($username, $password);
 }
Exemple #15
0
function findDN($id, $password)
{
    // Finds the user's Distinguished Name - the key that uniquely identifies each entry in the directory
    global $ldap_host;
    // Connects to the LDAP server
    $ds = ldap_connect($ldap_host) or die("LDAP connection failed. Please see installation notes on how to configure Apache to work with LDAP.");
    if ($ds) {
        // Connection was successful
        // Performs anonymous bind to LDAP server
        $r = ldap_bind($ds);
        if ($r) {
            // Binding to LDAP server was unsuccessful
            // Determines whether the username provided is the uidNumber (which is numeric - 499908), or the uniqueID (which is alphanumeric - cam01329)
            $filterString = is_numeric($id) ? "uidNumber={$id}" : "uniqueID={$id}";
            // Performs search for the LDAP number
            $searchResult = ldap_search($ds, "ou=LAN,o=PORT", $filterString);
            // Gets entries for this search
            $info = ldap_get_entries($ds, $searchResult);
            // Retrieves the DN and givenname (e.g. Alasdair) for the user
            $dn = $info[0]["dn"];
            $givenname = $info[0]['givenname'][0];
            // Calls the authenticate function
            authenticate($dn, $password, $givenname);
        } else {
            // Binding to LDAP server was unsuccessful
            echo "Unable to connect to LDAP server";
            echo "<p>Click <a href='../../login.php'>here</a> to go back.</p>";
        }
    } else {
        // Connection to LDAP server was unsuccessful
        echo "Unable to connect to LDAP server";
        echo "<p>Click <a href='../../login.php'>here</a> to go back.</p>";
    }
}
Exemple #16
0
function autmount_list()
{
    $samba = new samba();
    $ldap = new clladp();
    $dn = "ou=auto.automounts,ou=mounts,{$ldap->suffix}";
    $filter = "(&(ObjectClass=automount)(automountInformation=*))";
    $attrs = array("automountInformation", "cn");
    $html = "<table style='width:99%'>";
    $sr = @ldap_search($ldap->ldap_connection, $dn, $filter, $attrs);
    if ($sr) {
        $hash = ldap_get_entries($ldap->ldap_connection, $sr);
        if ($hash["count"] > 0) {
            for ($i = 0; $i < $hash["count"]; $i++) {
                $path = $hash[$i]["cn"][0];
                $automountInformation = $hash[$i][strtolower("automountInformation")][0];
                $js = "ShareDevice('{$path}');";
                $delete = "&nbsp;";
                if (is_array($samba->main_array[$path])) {
                    $delete = imgtootltip('ed_delete.gif', '{delete}', "DeleteUsbShare('{$path}')");
                    $js = "FolderProp('{$path}')";
                }
                $html = $html . "\n\t\t\t\t\t<tr " . CellRollOver($js) . ">\n\t\t\t\t\t\t<td width=1%><img src='img/fw_bold.gif'></td>\n\t\t\t\t\t\t<td colspan=2 ><code style='font-size:13px;font-weight:bold'>{$path}</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t\t<td ><code style='font-size:1Opx;font-weight:bold'>{$automountInformation}</td>\n\t\t\t\t\t\t<td width=1%>{$delete}</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr><td colspan=3><hr></td></tr>\t";
            }
        }
    }
    $html = $html . "</table>";
    $tpl = new templates();
    return $tpl->_ENGINE_parse_body($html);
}
 public static function updateProfile($numero_membre, $data)
 {
     $handle_ldap = self::initialize();
     if (self::$isDisabled) {
         self::$logger->info("Ldap is disabled, doing nothing.");
         return false;
     }
     $membreExists = @ldap_search($handle_ldap, "cn={$numero_membre}, " . self::$conf['basedn'], "objectclass=*", array("cn", "description", "mail"));
     if ($membreExists) {
         $personnes = ldap_get_entries($handle_ldap, $membreExists);
         $personne = $personnes[0];
         $dn = $personne["dn"];
         //self::$logger->debug(print_r($personne, true));
         $newEmail = self::$conf['defaultEmail'];
         if (isset($data['email']) && $data['email']) {
             $newEmail = $data['email'];
         }
         $hasLdapEmail = @is_array($personne["mail"]);
         $ldapData = ['mail' => [$newEmail]];
         if ($hasLdapEmail) {
             self::$logger->info("Replacing ldap email for #{$numero_membre}: {$newEmail}");
             ldap_mod_replace($handle_ldap, $dn, $ldapData);
         } else {
             self::$logger->info("Adding ldap email for #{$numero_membre}: {$newEmail}");
             ldap_mod_add($handle_ldap, $dn, $ldapData);
         }
         $err = ldap_error($handle_ldap);
         if ($err != "Success") {
             return $err;
         }
     } else {
         return "Membre not found in ldap repo: #{$numero_membre}";
     }
 }
Exemple #18
0
function hook_post_auth_update_zonep_config($login = null, $password = null) {
    global $ad_server, $ad_base_dn, $ad_bind_dn, $ad_bind_pw;
    global $ldap_server, $ldap_base_dn, $adminRdn, $adminPw, $se3Ip;

    // Check arguments
    if(!is_string($login) or !is_string($password))
	return false;

    // Ensure we have an ActiveDirectory server or LDAP server to contact
    if (empty($ad_server) && empty($ldap_server))
	return false;
	
	// Connect to AD or LDAP
	if (!empty($ad_server))    
		$ds = ldap_connect($ad_server);
	else
		$ds = ldap_connect($ldap_server);	

    if(!$ds)
	return false;
	
    // admin Bind on AD or LDAP
	if (!empty($ad_server))    
    	$r = ldap_bind($ds, $ad_bind_dn, $ad_bind_pw);
    else
    	$r = ldap_bind($ds, $adminRddn.$ldap_base_dn, $adminPw);    

    if(!$r)
	return false;

    // Fetch UNC from Active Directory
    $attributes = array('homeDirectory');

	if (!empty($ad_server))
    	$sr = ldap_search($ds, $ad_base_dn, "(sAMAccountName=$login)", $attributes);
    else 	
    	$sr = ldap_search($ds, $ldap_base_dn, "(uid=$login)", $attributes);

    if (! $sr)
	return false;

    $entries = ldap_get_entries($ds, $sr);

    if(empty($entries[0]['homedirectory'][0]))
	return false;

    if (!empty($ad_server))
    	$smb_share = str_replace('\\', '/', $entries[0]['homedirectory'][0]);
    else
    	$smb_share = "//$se3Ip/$login";

    // Call sudo wrapper to create autofs configuration file
    $handle = popen('sudo lcs-zonep-update-credentials', 'w');
    fwrite($handle, "$login\n$password\n$smb_share\n");
    $status = pclose($handle) >> 8;
    if ($status != 0)
	return false;

    return true;
}
function computer_list()
{
    $userid = new user($_GET["userid"]);
    $dn = $userid->dn;
    $ldap = new clladp();
    $pattern = "(&(objectClass=ComputerAfectation)(cn=*))";
    $attr = array();
    $sr = @ldap_search($ldap->ldap_connection, $dn, $pattern, $attr);
    if (!$sr) {
        return null;
    }
    $hash = ldap_get_entries($ldap->ldap_connection, $sr);
    if ($hash["count"] == 0) {
        return;
    }
    for ($i = 0; $i < $hash["count"]; $i++) {
        $uid = $hash[$i]["uid"][0];
        $mac = $hash[$i]["computermacaddress"][0];
        $computer = new computers($uid);
        $uid_text = str_replace("\$", "", $uid);
        $js = "javascript:Loadjs('computer.infos.php?uid={$uid}');";
        $tb[] = "<div style='float:left;margin:3px'>" . Paragraphe("64-computer.png", $uid_text, "<strong>{$mac}<div><i>{$computer->ComputerOS}</i></div><div>{$computer->ComputerIP}</div></strong>", $js) . "</div>";
    }
    $html = "<div style='width:100%'>" . implode("\n", $tb);
    $tpl = new templates();
    echo $tpl->_ENGINE_parse_body($html);
}
 /**
  * Auth request
  */
 public function request()
 {
     // bail out if we didn't get a username and password passed
     if (empty($this->env['username']) or empty($this->env['password'])) {
         $error = array('code' => 'credentials_error', 'message' => 'LDAP user credentials not passed in the request', 'raw' => array());
         $this->errorCallback($error);
     }
     // create an ldap binding
     $this->ldap_login(str_replace('$username$', $this->env['username'], $this->strategy['bind-cn']) . ',' . $this->strategy['bind-dn'], str_replace('$password$', $this->env['password'], $this->strategy['bind-password']), $this->strategy['server'], isset($this->strategy['options']) ? $this->strategy['options'] : array());
     // fetch the users attributes
     try {
         $attrs = ldap_search($this->ldap, $this->strategy['bind-dn'], '(' . str_replace('$username$', $this->env['username'], $this->strategy['bind-cn']) . ')');
         $attrs = ldap_get_entries($this->ldap, $attrs);
     } catch (Exception $e) {
         $error = array('code' => 'bind_error', 'message' => $e->getMessage(), 'raw' => array());
         $this->errorCallback($error);
     }
     // attribute mapping
     $mapping = array_merge(array('uid' => 'uid', 'name' => 'name', 'email' => 'email', 'username' => 'username'), $this->strategy['attributes']);
     // fetch the attribute data
     foreach ($mapping as $k => $v) {
         if (isset($attrs[0][$v][0])) {
             $mapping[$k] = $attrs[0][$v][0];
         } else {
             $error = array('code' => 'fetch_error', 'message' => 'Required attribute "' . $k . '" not found in LDAP search', 'raw' => array());
             $this->errorCallback($error);
         }
     }
     // construct the response array
     $this->auth = array('uid' => $mapping['uid'], 'info' => array('name' => $mapping['name'], 'email' => $mapping['email'], 'nickname' => $mapping['username']), 'credentials' => array('token' => 0, 'expires' => date('c', time() + isset($this->strategy['expiry']) ? $this->strategy['expiry'] : 86400)), 'raw' => $attrs);
     // and process the callback
     $this->callback();
 }
 public function getObject($identity)
 {
     $connection = $this->bindToLdap();
     if ($resultSet = ldap_search($connection, $this->searchBase, "(&(cn={$identity})(objectClass=jsonObject))")) {
         if ($results = ldap_get_entries($connection, $resultSet)) {
             if ($results['count'] > 0) {
                 $tmp = json_decode($results[0]['jsonstring'][0], true);
                 if (is_array($tmp)) {
                     $value = $tmp;
                     $value['id'] = $results[0]['cn'][0];
                     $value['expire'] = intval($results[0]['expiretime'][0]);
                 }
             }
         } else {
             $error = 'failed to retrieve search result';
         }
     } else {
         $error = 'failed to execute search';
     }
     ldap_close($connection);
     if (isset($error)) {
         throw new Exception($error);
     } else {
         if (isset($value) && $value['expire'] > time()) {
             return $value;
         } else {
             return null;
         }
     }
 }
 public function __construct($user)
 {
     $this->_id = $user;
     /* Connect to the IU's ADS server */
     $ds = ldap_connect(LDAP_HOST, LDAP_PORT) or die("Could not connect to ads.iu.edu:636 server");
     ldap_bind($ds, LDAP_USER . "," . LDAP_BASEDN, LDAP_PWD) or die("LDAP bind to ADS failed.");
     /* Search for a particular user information (Only required info) */
     $reqatr = array("mail", "displayName", "givenName", "title");
     $result = ldap_search($ds, LDAP_BASEDN, "(sAMAccountName={$this->_id})", $reqatr) or die("Search: No ADS entry has been found for the current user.");
     /* Each node in a directory tree has an entry. */
     $entry = ldap_first_entry($ds, $result);
     while ($entry) {
         /* Each entry is a set of attribute value pairs */
         /* Extracting only required values              */
         /* Also assuming there is only single value     */
         $this->_email = ldap_get_values($ds, $entry, "mail");
         $this->_email = $this->_email[0];
         /* Php 5.3 */
         $this->_name = ldap_get_values($ds, $entry, "displayName");
         if (is_null($this->_name)) {
             $this->_name = ldap_get_values($ds, $entry, "givenName");
         }
         $this->_name = $this->_name[0];
         /* Php 5.3 */
         $this->_instructor = ldap_get_values($ds, $entry, "title");
         $this->_instructor = $this->_instructor[0];
         /* Not expecting multiple entries */
         /* $entry = ldap_next_entry($ds, $result); */
         $entry = null;
     }
 }
Exemple #23
0
 function search($uname, &$u)
 {
     $utimer = utime();
     $filter = '(sAMAccountName=' . $uname . ')';
     if ($result = ldap_search($this->c, LDAPTREE, $filter)) {
         $data = ldap_get_entries($this->c, $result);
         $keys = array_keys($data[0]);
         $member = '';
         while (list($k, $v) = each($keys)) {
             //  echo "<!-- [$v] -->\n";
             if (isset($u->{$v})) {
                 if ($v == 'memberof') {
                     for ($i = 0; $i < $data[0][$v]['count']; $i++) {
                         $member .= $data[0][$v][$i] . ';';
                     }
                     $u->{$v} = $member;
                 } else {
                     $u->{$v} = $data[0][$v]['0'];
                 }
             }
             // debug - et mis meil üldse AD'st saada on
             //  $uu = $data['0'][$v]['0'];
             //  echo "<!-- $v = $uu -->\n";
         }
         if ($this->debug) {
             $t = stop_utimer($utimer);
             $this->m[] = "<!-- LDAP [{$t}] userdata for [{$uname}] -->\n";
         }
         return true;
     }
     return false;
 }
Exemple #24
0
 public function checkLogin($username, $password)
 {
     if (!$username || !$password) {
         return false;
     }
     $username = $this->escapeUsername($username);
     if (!$username) {
         return false;
     }
     $this->bind();
     $dn = 'cn=' . $username . ',' . $this->config['dn'];
     $authenticated = ldap_bind($this->connection, $dn, $password);
     if (!$authenticated) {
         return false;
         // User details where invalid
     }
     $result = ldap_search($this->connection, $this->config['dn'], 'cn= ' . $username);
     if (!$result) {
         return false;
         // Couldn't find user
     }
     $info = ldap_get_entries($this->connection, $result);
     $user_id = intval($info[0]['uid'][0]);
     if (!$user_id) {
         return false;
         // No user_id defined, or invalid
     }
     return $user_id;
     // Login successful
 }
Exemple #25
0
function ParseLDAP()
{
    $ldap = new cronldap();
    $today = date('Y-m-d');
    $connect = $ldap->ldap_connection;
    $_GET["suffix"] = $ldap->suffix;
    $pattern = "(&(objectClass=UserArticaClass)(FinalDateToLive=*)(!(FinalDateToLive=0)))";
    $attr = array("uid", "FinalDateToLive", "dn");
    $sr = ldap_search($connect, $_GET["suffix"], $pattern, $attr);
    if ($sr) {
        $hash = ldap_get_entries($connect, $sr);
        if ($hash["count"] > 0) {
            for ($i = 0; $i < $hash["count"]; $i++) {
                $uid = $hash[$i]["uid"][0];
                $dn = $hash[$i]["dn"];
                $FinalDateToLive = $hash[$i][strtolower("FinalDateToLive")][0];
                $diff = DateDiff($today, $FinalDateToLive);
                echo "Analyze {$dn}: {$uid} :{$FinalDateToLive} ({$diff} day(s))\n";
                if ($diff < 0) {
                    echo "This user must be deleted...\n";
                    delete_ldap($dn, $connect, true);
                    DeleteMBX($uid);
                }
            }
        }
    }
    @ldap_unbind($connect);
    unset($GLOBALS["LDAP_BIN_ID"]);
    unset($GLOBALS["LDAP_CONNECT_ID"]);
    echo "\n";
}
Exemple #26
0
 private function searchID($id, $dir)
 {
     #if($dir == "") $dir = $this->LD->A("optionen");
     #array("cn")
     $sr = ldap_search($this->c, $dir, "(uid={$id})");
     return ldap_get_entries($this->c, $sr);
 }
Exemple #27
0
 private function __userInfo($ldapCon)
 {
     $filter = preg_replace('/UNAME/', $this->credentials['username'], $this->config['userFilter']);
     $result = ldap_search($ldapCon, $this->config['baseDn'], $filter);
     $user = ldap_get_entries($ldapCon, $result);
     return $user;
 }
Exemple #28
0
function ldap_call($connection, $bind_user, $bind_pass, $filter)
{
    $ds = ldap_connect($connection);
    //echo $connection . $bind_user . $bind_pass . $filter ;
    //personal e-mails
    if ($ds) {
        $r = ldap_bind($ds, $bind_user, $bind_pass);
        //$filter="(|(mail= null)(objectCategory=group))";
        $sr = ldap_search($ds, "ou=LMC, dc=lamontanita, dc=local", $filter);
        ldap_sort($ds, $sr, "cn");
        $info = ldap_get_entries($ds, $sr);
        //echo $info["count"] . " results returned:<p>";
        echo "<table id='ldaptable' border=1><tr><th>Name</th><th>E-mail</th></tr>";
        for ($i = 0; $i < $info["count"]; $i++) {
            if ($info[$i]["mail"][0] != null) {
                echo "<td>" . $info[$i]["cn"][0] . "</td>";
                echo "<td>" . $info[$i]["mail"][0] . "</td></tr>";
            }
        }
        echo "</table>";
        return $info;
        ldap_close($ds);
    } else {
        echo "<h4>LDAP_CALL unable to connect to LDAP server</h4>";
    }
}
Exemple #29
0
function ParseAllcontacts()
{
    $unix = new unix();
    $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid";
    $pidtime = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".time";
    $pid = @file_get_contents($pidfile);
    if ($unix->process_exists($pid)) {
        return;
    }
    @file_put_contents($pidfile, getmypid());
    if ($unix->file_time_min($pidtime) < 120) {
        return;
    }
    @file_put_contents($pidtime, time());
    $ldap = new clladp();
    $suffix = $ldap->suffix;
    $arr = array("uid");
    $sr = @ldap_search($ldap->ldap_connection, "dc=organizations,{$suffix}", '(objectclass=userAccount)', $arr);
    if ($sr) {
        $hash = ldap_get_entries($ldap->ldap_connection, $sr);
        for ($i = 0; $i < $hash["count"]; $i++) {
            ParseContacts($hash[$i]["uid"][0]);
            if (system_is_overloaded(dirname(__FILE__))) {
                $unix->send_email_events(basename(__FILE__) . " Overloaded aborting task", "Zarafa contacts importation has been canceled due to overloaded system", "mailbox");
                return;
            }
            sleep(1);
        }
    }
}
 function getUserDn($username)
 {
     if ($this->send_utf8_credentials) {
         $username = studip_utf8encode($username);
         $reader_password = studip_utf8encode($this->reader_password);
     }
     $user_dn = "";
     if (!($r = @ldap_bind($this->conn, $this->reader_dn, $this->reader_password))) {
         $this->error_msg = sprintf(_("Anmeldung von %s fehlgeschlagen."), $this->reader_dn) . $this->getLdapError();
         return false;
     }
     if (!($result = @ldap_search($this->conn, $this->base_dn, $this->getLdapFilter($username), array('dn')))) {
         $this->error_msg = _("Durchsuchen des LDAP Baumes fehlgeschlagen.") . $this->getLdapError();
         return false;
     }
     if (!ldap_count_entries($this->conn, $result)) {
         $this->error_msg = sprintf(_("%s wurde nicht unterhalb von %s gefunden."), $username, $this->base_dn);
         return false;
     }
     if (!($entry = @ldap_first_entry($this->conn, $result))) {
         $this->error_msg = $this->getLdapError();
         return false;
     }
     if (!($user_dn = @ldap_get_dn($this->conn, $entry))) {
         $this->error_msg = $this->getLdapError();
         return false;
     }
     return $user_dn;
 }