#!/usr/bin/php4 -q
<?php

##################### T E S T - V A R I A B L E S ##################
$server= "localhost";
$filter= "(uid=*)";
$base  = "dc=example,dc=net";


######################## F U N C T I O N S #########################
function get_additional_error($res)
{
	$error= "";
	ldap_get_option ($res, LDAP_OPT_ERROR_STRING, $error);
	return ($error);
}

function get_error($res)
{
	$error= ldap_error($res);
	if ($error == 'Success'){
		return "success";
	} else {
		$adderror= get_additional_error($res);
		if ($adderror != ""){
			$error= $error." (".get_additional_error($res).")";
		}
		return $error;
	}
}


####################################################################
#                             M A I N                              #
####################################################################
echo "Opening connection to $server - ";
$ds= @ldap_connect($server);

if ($ds) {
	echo "success\n";

	echo "Setting up link parameters - ";
	ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
	ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);
	echo get_error($ds)."\n";

	echo "Binding - ";
	if (!($r= @ldap_bind($ds))){
		echo get_error($ds)."\n\n";
		exit (2);
	}
	echo "success\n";
} else {
	echo get_error($ds)."\n\n";
	exit (1);
}

echo "Performing search with base '$base' and filter '$filter'\n";
echo "* starting search - ";
$sr=   @ldap_search($ds, $base, $filter, array('uid', 'cn'), 0, 0, 0, LDAP_DEREF_ALWAYS);
echo get_error($ds)."\n";
if (!$sr){
	exit (3);
}

$ref = ldap_first_reference($ds, $sr);
while ($ref) {
	if (ldap_parse_reference($ds, $ref, $referrals)) {
		while ($referral = array_shift($referrals)) {
			echo "-> Need to walk through $referral\n";
		}
		$ref = ldap_next_reference($ds, $ref);
	}
}
$info= @ldap_get_entries($ds, $sr);

echo "* getting entries - ";
echo get_error($ds)."\n";
if (!$info){
	exit (4);
}
for ($n= 0; $n<=$info['count']; $n++){
	if (!isset($info[$n]['uid'][0])){
		continue;
	}
	echo "  ".$info[$n]['dn']."\n";
}


echo "Closing connection...\n";
ldap_close($ds);
exit;

