pastebin - collaborative debugging

pastebin is a collaborative debugging tool allowing you to share and modify code snippets while chatting on IRC, IM or a message board.

This site is developed to XHTML and CSS2 W3C standards. If you see this paragraph, your browser does not support those standards and you need to upgrade. Visit WaSP for a variety of options.

PHP ZTDev Pastebin View Help

Posted by mcutting on Fri 1st May 10:46 (modification of post by view diff)
download | new post

  1. <?php
  2.  
  3.         /********************
  4.        
  5.         A highly verbose PHP script to import new Active Directory users into Zentrack via LDAP
  6.         Adds new user accounts into Zentrack's database users table (zentrack_users)
  7.         Updates existing user accounts / Removes accounts that no longer exist
  8.        
  9.         ********************/
  10.  
  11.         // AD/LDAP settings
  12.         // AD USER SHOULD BE AN ACCOUNT THAT HAS RIGHTS TO READ FROM ACTIVE DIRECTORY
  13.        
  14.         // ENTER THE ADDRESS OF YOUR LDAP SERVER HERE
  15.   $dc = "ldap://";
  16.   // ENTER THE FULL AD PATH OF YOUR USER HERE
  17.         $user = "";
  18.         // ENTER THE PASSWORD OF YOUR AD USER HERE
  19.         $pw = "";
  20.         //ENTER THE FULL DN FOR YOUR DOMAIN, EXAMPLE dc=microsoft,dc=com
  21.         $dn = "";
  22.         // ENTER ATTRIBUTES THAT YOU WISH TO PULL FROM AD, FOR EXAMPLE "displayname" AND "givenname" ETC
  23.         $attributes = array ("cn", "samaccountname", "displayname", "givenname", "sn", "mail");
  24.         // ENTER FILTER ATTRIBUTES HERE, FOR EXAMPLE "person" AND "telephoneNumber"
  25.         $filter = "(&(objectClass=person)(objectCategory=person)(telephoneNumber=*)(mail=*youremail.com)(cn=*))";
  26.  
  27.         // MySQL settings
  28.         $mysql_server = "localhost";
  29.         $mysql_user = "";
  30.         $mysql_password = "";
  31.         $mysql_database = "zentrack";
  32.  
  33.  
  34. /*     
  35. The following allow us to define users in the local db that should not be deleted. 
  36. The second variable defines a string for the zentrack_users table 'notes' field
  37. that you can use to prevent deleteing users in addition to the local admin specified in adminexempt. 
  38. To use this go into your Zentrack instance, click admin, then go to the edit users page and enter the exact same text as 'otherexempt'
  39. in the NOTES field for any users AFTER they are populated into the DB. 
  40. You could also modify the code below to use this field to prevent updates as well.
  41. If you don't want to keep any non-AD users just set these to a empty strings.
  42. */
  43.         $adminexempt = "Administrator";     // will be compared against the login field of zentrack_users
  44.         $otherexempt = "DO NOT DELETE";   // will be compared against the notes field of zentrack_users
  45.  
  46. // Begin code to do the import/update
  47.        
  48.         echo "<HTML>\n<HEAD><TITLE>Active Directory >> Zentrack Import</TITLE></HEAD>\n<BODY>\n";
  49.         echo "<b>Active Directory >> Zentrack Users Database Import Tool</b> <BR><BR>\n";
  50.   echo "Run on: " . date(DATE_RFC822) . "<BR><BR>\n";
  51.  
  52.         // Query AD for user accounts
  53.         $ad = ldap_connect($dc) or die("Couldn't connect to AD!");
  54.         echo "Connected to AD via LDAP<br>\n";
  55.  
  56.         // Required for AD/Server 2003?
  57.         ldap_set_option($ad, LDAP_OPT_PROTOCOL_VERSION, 3);
  58.   ldap_set_option($ldapconn, LDAP_OPT_REFERRALS, 0);
  59.  
  60.         $bd = ldap_bind($ad,$user,$pw) or die("Couldn't bind to AD!");
  61.         echo "Bound to AD via LDAP<br>\n";
  62.  
  63.         // Recursive Query:
  64.         $ldapResults = ldap_search($ad, $dn, $filter, $attributes);
  65.  
  66.         // Same-Level Query:
  67.         // Uncomment the following line and comment out the line above to search only the same OU level
  68.         // $ldapResults = ldap_list($ad, $dn, $filter, $attributes);
  69.  
  70.         $entries = ldap_get_entries($ad, $ldapResults);
  71.         echo "Found ".$entries["count"]." entries in AD via LDAP Search<br>\n";
  72.  
  73.         // Match AD users accounts to MySQL user table
  74.         $db = mysql_connect($mysql_server,$mysql_user,$mysql_password);
  75.         if (!$db) {
  76.                 die('Could not connect: ' . mysql_error());
  77.         }
  78.         echo "Connected to MySQL server ".$mysql_server."<br>\n";
  79.  
  80.         mysql_select_db($mysql_database, $db);
  81.  
  82.         // begin loop through the DB usernames and if they aren't in AD delete them
  83.         $sql = "SELECT login,notes FROM zentrack_users";
  84.         $result = mysql_query($sql, $db);
  85.                 if (!$result)
  86.                 {
  87.                         $message  = 'Invalid query: ' . mysql_error($db) . "<br>";
  88.                         $message .= 'Whole query: ' . $sql  . "<BR>";
  89.                         die($message);
  90.                 }
  91.  
  92.         $deletedcount = 0;
  93.         $totalrows = mysql_num_rows($result);
  94.  
  95.         echo "Found " . $totalrows . " entries in DB via SQL Search<br>\n";
  96.        
  97.         echo "<br>";
  98.        
  99.         while ($row = mysql_fetch_array($result))
  100.                 {
  101.                 $namearray[] = strtolower($row['login']);
  102.                 $otherarray[] = $row['notes'];
  103.                 }
  104.  
  105.         for ($j=0; $j<($totalrows); $j++)
  106.                 {
  107.                 $inAD = false;
  108.                 $exemptuser = false;
  109.                 if ($namearray[$j] == $adminexempt)
  110.                         {
  111.                         echo "<br>Admin User : " . $namearray[$j] . "<br>\n";
  112.                         $exemptuser = true;
  113.                         }
  114.                 if (($otherarray[$j] == $otherexempt) && (!$exemptuser))
  115.                         {
  116.                         echo "<b>Exempt User: </b> : " . $namearray[$j] . "<BR>\n";
  117.                                         $exemptuser = true;
  118.                         }
  119.                 if (!$exemptuser)
  120.                         {
  121.                         for ($i=0; $i<$entries["count"]; $i++)
  122.                                 {
  123.                                 if ($namearray[$j] == strtolower($entries[$i]["samaccountname"][0]))
  124.                                         {
  125.                                         $i=$entries["count"];
  126.                                         $inAD=true;                         
  127.                                         }
  128.                                 }
  129.                         if (!($inAD))
  130.                                 {
  131.                                 DeleteUser( $j, $db, $namearray[$j]);
  132.                                 ++$deletedcount;
  133.                                 }
  134.                         }
  135.                 }
  136.         // end loop through the DB usernames and if they aren't in AD delete them
  137.                        
  138.         $usersadded=0;
  139.         $usersupdated=0;
  140.  
  141.         echo "<BR>\n"
  142.  
  143.         for ($i=0; $i<$entries["count"]; $i++)
  144.                 {
  145.                 // look up AD user account in MySQL database
  146.                 // add to database if user does not exist in database already
  147.                 // update all user DB fields if they are already in the database so the DB matches AD
  148.                 // PLEASE NOTE:  All "index" values must be in lower-case!  This is a PHP array handling quirk?
  149.  
  150.                 $username = $entries[$i]["samaccountname"][0];
  151.  
  152.                 if (DatabaseLookup($username, $db))
  153.                         {
  154. //                  echo $i." : AD user: ".$username." found in database<br>\n";
  155.                         if (UpdateUser( $i, $db,
  156.                                 $entries[$i]["givenname"][0],
  157.                                 $entries[$i]["sn"][0],
  158.                                 $entries[$i]["samaccountname"][0],
  159.                                 $entries[$i]["mail"][0]))
  160.  
  161.                                 {
  162.                                 ++$usersupdated;
  163.                                 }
  164.                         }
  165.                 else
  166.                         {
  167. //          echo $i." : AD user: ".$username." <b><i>not</i></b> found in database<br>\n";
  168.                 AddUser( $i, $db,
  169.                                 $entries[$i]["givenname"][0],
  170.                                 $entries[$i]["sn"][0],
  171.                                 $entries[$i]["samaccountname"][0],
  172.               $entries[$i]["mail"][0]);
  173.  
  174.                         ++$usersadded
  175.                         }
  176.         }
  177.        
  178.         echo "<br>";
  179.        
  180.         if (($deletedcount>0)||($usersadded>0)||($usersupdated>0)) { echo "<BR>\n"; }
  181.         echo "Number of users deleted : " . $deletedcount . "<BR>\n";
  182.         echo "Number of users added : " . $usersadded . "<br>\n";
  183.         echo "Number of users updated : " . $usersupdated . "<br>\n";
  184.         echo "</BODY></HTML>\n";
  185.  
  186.         ldap_unbind($ad);
  187.         mysql_close($db);
  188.  
  189. //
  190. // DatabaseLookup - Check for match between AD account and Users table in MySQL
  191. //
  192. function DatabaseLookup( $cn, $db ) {
  193.         // check for match against mysql database
  194.         $sql = "SELECT login FROM zentrack_users WHERE login = '".mysql_real_escape_string($cn)."'";
  195.  
  196.         $result = mysql_query($sql, $db);
  197.         if (!$result) {
  198.                 $message  = 'Invalid query: ' . mysql_error($db) . "<br>";
  199.                 $message .= 'Whole query: ' . $sql . "<BR>";
  200.                 die($message);
  201.         }
  202.         if (mysql_error($db) != "")
  203.                 {
  204.                 echo mysql_error($db) . "<BR>";
  205.                 }
  206.         if (mysql_errno($db) != 0)
  207.                 {
  208.                 echo mysql_errno($db) . "<BR>";
  209.                 }
  210.         $num_rows = mysql_num_rows($result);
  211.         return ($num_rows > 0);
  212. }
  213.  
  214.  
  215.  
  216. // AddUser - Adds record to MySQL Zentrack Users table
  217.  
  218. function AddUser ($i, $db, $fname, $lname, $uname, $email_add) {
  219.         $sql =
  220.         "INSERT INTO zentrack_users (fname, lname, login, initials, access_level, email) VALUES (" .
  221.                 " '" . mysql_real_escape_string($fname) . "', " .
  222.                 " '" . mysql_real_escape_string($lname) . "', " .
  223.                 " '" . mysql_real_escape_string(strtolower($uname)) . "', " .
  224.                 " '" . mysql_real_escape_string(strtolower($uname)) . "', " .
  225.                 " '" . mysql_real_escape_string('2') . "', " .
  226.                 " '" . mysql_real_escape_string(strtolower($email_add)) . "')";
  227.  
  228.         $result = mysql_query($sql, $db);
  229.         if (mysql_error($db) != "")
  230.                 {
  231.                 echo mysql_error($db) . "<BR>";
  232.                 }
  233.         if (mysql_errno($db) != 0)
  234.                 {
  235.                 echo mysql_errno($db) . "<BR>";
  236.                 }
  237.         if (mysql_affected_rows()>0)
  238.                 {
  239.                 echo "LDAP user " . $i . " : " . $sql . "<br>\n" ;
  240.                 }
  241.         //echo $i . " : INSERT effected <b>" .mysql_affected_rows(). " rows</b><br>\n";
  242. }
  243.  
  244.  
  245. // UpdateUser - Updates record in MySQL Zentrack Users table
  246.  
  247. function UpdateUser ($i, $db, $fname, $lname, $uname, $email_add) {
  248.         $sql =
  249.                 "UPDATE zentrack_users SET
  250.                 fname='" . mysql_real_escape_string($fname) . "',
  251.                 lname='" . mysql_real_escape_string($lname) . "',
  252.                 email='" . mysql_real_escape_string($email_add) . "',
  253.                 initials='" . mysql_real_escape_string(strtolower($uname)) . "'
  254.                 WHERE login='" . mysql_real_escape_string($uname) . "'";
  255.  
  256.         $result = mysql_query($sql, $db);
  257.         if (mysql_error($db) != "")
  258.                 {
  259.                 echo mysql_error($db) . "<BR>";
  260.                 }
  261.         if (mysql_errno($db) != 0)
  262.                 {
  263.                 echo mysql_errno($db) . "<BR>";
  264.                 }
  265.         if (mysql_affected_rows()>0)
  266.                 {
  267.                 echo "LDAP user " . $i . " : " . $sql . "<br>\n" ;
  268.                 return true;
  269.                 }
  270.         //echo $i . " : Update effected <b>" .mysql_affected_rows(). " rows</b><br>\n";
  271. }
  272.  
  273.  
  274.  
  275. // DeleteUser - Deletes records from the MySQL Zentrack Users table
  276.  
  277. function DeleteUser ($i, $db, $uname) {
  278.         $sql = "DELETE FROM zentrack_users WHERE login = '" . $uname . "'";
  279.         $result = mysql_query($sql, $db);
  280.         if (mysql_error($db) != "")
  281.                 {
  282.                 echo mysql_error($db) . "<BR>";
  283.                 }
  284.         if (mysql_errno($db) != 0)
  285.                 {
  286.                 echo mysql_errno($db) . "<BR>";
  287.                 }
  288.         if (mysql_affected_rows()>0)
  289.                 {
  290.                 echo "LDAP user " . $i . " : " . $sql . "<br>\n" ;
  291.                 }
  292.         //echo $i . " : Delete effected <b>" .mysql_affected_rows(). " rows</b><br>\n";
  293. }
  294.        
  295. ?>

Submit a correction or amendment below (click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:

To highlight particular lines, prefix each line with @@


Remember me