<?php
// run this on your domain controller
// ldifde -f export.ldf -s SERVER -r "(objectclass=user)" -l "dn, cn, samAccountName"
// run this on export.ldf:
// grep -o -P "(dn:.*|cn:.*|sAMAccountName:.*)" export.ldf > temp
// run this script as follows:
// php format_AD.php > format.csv

$file "data/temp";
$handle fopen ($file,"r");
$x 0;
// while we haven't reached EOF
while(!feof($handle)) {
        
$i 0;
        
// get each line and store as an array of three data segments
        
while($i 3) {
                
$arr[$x][$i] = stream_get_line($handle,4096,"\n");
                
$i++;
        }
        
$x++;
}
// for each chunk of data
foreach($arr as $index=>$user) {
        
// separate the "dn:" line
        
$dn explode(",",$user[0]);
        
// pull out the name
        
preg_match("/dn: CN=(.+)/",$dn[0],$names[]);
        
// pull out the "cn:" name
        
preg_match("/cn: (.+)/",$arr[$index][1],$cns[]);
        
// pull out the "sAMAccountName:" name
        
preg_match("/sAMAccountName: (.+)/",$arr[$index][2],$sams[]);
}
// for each match, pull out the name only, and store in another array
$i 0;
foreach(
$names as $name) {
        
// explode first and last name
        
$exploded_names[$i] = explode(" ",$name[1]);
        
// remove extraneous user names (like "sponsorship")
        
if (count($exploded_names[$i]) == 1) {
                unset(
$exploded_names[$i]);
                unset(
$names[$i]);
                unset(
$sams[$i]);
                unset(
$cns[$i]);
        }
        
// replace the middle name of some users with their last name, unset their last name
        
if (count($exploded_names[$i]) == 3) {
                
$exploded_names[$i][1] = $exploded_names[$i][2];
                unset(
$exploded_names[$i][2]);
        }
        
$i++;
}
echo 
"username,first name,last name,password\n";
foreach(
$names as $index=>$name) {
        echo 
trim($sams[$index][1]).",".trim($exploded_names[$index][0]).",".trim($exploded_names[$index][1]).",".genPass()."\n";
}
function 
genPass ($length 8) {
        
// start with a blank password
        
$password "";
        
// define possible characters
        
$possible "0123456789bcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        
// set up a counter
        
$i 0;
        
// add random characters to $password until $length is reached
        
while ($i $length) {
                
// pick a random character from the possible ones
                
$char substr($possiblemt_rand(0strlen($possible)-1), 1);
                
// we don't want this character if it's already in the password
                
if (!strstr($password$char)) {
                        
$password .= $char;
                        
$i++;
                }
        }
        return 
$password;
}
?>