require_once(realpath(dirname(__FILE__).'/../../lib/php/nb.php'));
require_once(NB_ROOT.'/lib/php/http.php');
-class Ldap extends nb {
+class Ldap {
public static function connect(&$o=[]) {
$host = '127.0.0.1';
return $new;
}
+ public $host = '127.0.0.1';
+ public $base;
+ public $user;
+ public $password;
+ public $search = false;
+
+ private $conn;
+
+ public function __construct($opt = []) {
+ foreach ($opt as $k => $v) $this->$k = $v;
+ if (isset($this->search)) return $this->_search($this->search);
+ }
+
+ public function __destruct() {
+ if ($this->conn) $this->disconnect();
+ }
+
+ public static function bye($msg) { die($msg); }
+
+ public function conn($exit=true) {
+ if ($this->conn) return $this->conn;
+ if (!$this->conn = @ldap_connect($this->host)) return self::bye("Could not connect to LDAP server");
+
+ ldap_set_option($this->conn, LDAP_OPT_PROTOCOL_VERSION, 3);
+ ldap_set_option($this->conn, LDAP_OPT_REFERRALS, 0);
+
+#debug($this);
+ if (!@ldap_bind($this->conn, $this->user, $this->password)) self::bye("Could not bind to LDAP server");
+ return $this->conn;
+ }
+
+ private function disconnect() {
+ ldap_close($this->conn);
+ }
+
+ public function _search(&$o=[]) {
+
+ $connect = $this->conn();
+
+ $read = ldap_search($connect, $o['base'], $o['filter'], $o['attrs'], $o['limit']) or self::bye("Unable to search ldap server");
+
+ # ldap_get_entries is shite !! It does not workds with binary datas, put all attrs in lower case
+ $info = [];
+ $i = 0;
+ $entry = ldap_first_entry($connect, $read);
+ if ($entry !== false) do {
+
+ $attributes = ldap_get_attributes($connect, $entry);
+
+ for($j=0; $j<$attributes['count']; $j++) {
+ $values = ldap_get_values_len($connect, $entry,$attributes[$j]);
+ unset($values['count']);
+ if (isset($values) and count($values) == 1) $values = $values[0];
+ $info[$i][$attributes[$j]] = $values;
+ }
+ if (!empty($o['dn']) and
+ in_array('dn',!empty($o['attrs']) ? $o['attrs'] : ['dn'])
+ ) $info[$i] = ['dn' => ldap_get_dn($connect,$entry)] + (empty($info[$i]) ? [] : $info[$i]);
+
+ # Re-order by attrs
+ if (!empty($o['attrs']) and !empty($info[$i])) $info[$i] = self::ar_filter_keys($info[$i],$o['attrs']);
+
+ $i++;
+
+ } while ($entry = ldap_next_entry($connect, $entry));
+
+ #bye($info);
+ return $info;
+
+ $info = ldap_get_entries($connect, $read);
+
+ $recs = [];
+ #debug($info);
+ for ($r=0; $r<$info["count"]; $r++){
+ $rec = $info[$r];
+
+ for ($i=0; $i<$rec["count"]; $i++){
+ # Fields
+ $key = $info[$r][$i];
+ if (!empty($o['attrs']) and !in_array($key,$o['attrs'])) continue;
+ $recs[$r][$key] = [];
+
+ # Values
+ if (isset($rec[$key]['count'])) for ($j=0; $j<$rec[$key]['count']; $j++){
+ $recs[$r][$key][] = $rec[$key][$j];
+ }
+ if (count($recs[$r][$key]) == 1) $recs[$r][$key] = $recs[$r][$key][0];
+
+ }
+ }
+
+ $o['count'] = count($rec);
+ #return $info;
+ return $recs;
+
+ } # < ldap_search
+ public static function add($o) {
+ }
+
}