<?php
  ///////////////////////////////////////////////////
  //2011 (C)
  //Карпухин Павел
  ///////////////////////////////////////////////////
  require_once "/var/www/personal/admin/config.php";
  require_once "/var/www/personal/admin/lang/ru/trans.php";
  require_once "/var/www/personal/lang/ru/trans.php";

  if(! @mysql_select_db($dbname,$dbcnx))
    {
    echo "At this moment the database is not accessible.";
    exit();
    }

  $query_srv = "SELECT * FROM `tbl_srv_param` LIMIT 1";
  $result_srv = mysql_query($query_srv);
  if(!$result_srv) puterror2($TEXT['error-tbl44']);
   $result_srv_set = mysql_fetch_array($result_srv,MYSQL_ASSOC);

  //ldap
  $ldp = $result_srv_set['ldp']; //1 - использовать, 0 - не использовать
  $ldp_dn = $result_srv_set['ldp_dn'];
  $ldp_user = $result_srv_set['ldp_user'];
  $ldp_pass = $result_srv_set['ldp_pass'];
  $dlp_srv = $result_srv_set['dlp_srv']; //также можно указать имя или вот так ldaps://server-address
  $ldp_port = $result_srv_set['ldp_port'];

echo `clear`;
echo "Utilites for replication users informetion for Personal project\r\n";

// Ищем файлы
echo "\r\n\033[33m\033[1mSearch files fo replication.\033[0m\033[0m\r\n";

   $files = array();

   $repl_dir = opendir("/var/www/personal/replica/");
    while(($dir = readdir($repl_dir)))
      {
       if(@is_file("/var/www/personal/replica/".$dir) && $dir !== "." && $dir !== ".." && $dir !== "main-organization")
        {
//         $dir_name = $repl_dir . '/' . $dir;
         $files[] = $dir;
        }
      }
   closedir($repl_dir);
   $cnt_fl = count($files);
  
  $delimiter = ";";
  

  echo "Found - \033[32m\033[1m".$cnt_fl."\033[0m\033[0m files\r\n\r\n";

  for($i=0;$i<$cnt_fl;$i++){
   $n = 0;
   $handle = file("/var/www/personal/replica/".$files[$i]);
   $size = filesize("/var/www/personal/replica/".$files[$i])/1024;
   $numrows_w = count($handle)-1;
   $numrows = count($handle);
   echo "File - \033[32m\033[1m".$files[$i]."\033[0m\033[0m, Size - \033[32m\033[1m".round($size)." Kb\033[0m\033[0m, Rows for replication - \033[32m\033[1m".$numrows_w."\033[0m\033[0m\r\n";

   echo "Open file - \033[33m\033[1m".$files[$i]."\033[0m\033[0m\r\n";

       foreach($handle as $line_num => $line) 
        {
         $line_total = ($line_num + 1);
         $linedump=trim($line);
         if(!($linedump ==''))
         {
          if($line_num > 0)
          {
          $n = $n+1;
          $csv_line = explode($delimiter,$linedump,35);
          $org = ucfirst(trim($csv_line[0]));
          if($org == "") $org = "-";
          $upr = ucfirst(trim($csv_line[1]));
          if($upr == "") $upr = "-";
          $otd = ucfirst(trim($csv_line[2]));
          if($otd == "") $otd = "-";
          $city = ucfirst(strtolower(trim($csv_line[3])));
          if($city == "") $city = "-";
          $str = ucfirst(strtolower(trim($csv_line[4])));
          if($str == "") $str = "-";
          $house = trim($csv_line[5]);
          $room = trim($csv_line[6]);
          $fam = ucfirst(strtolower(trim($csv_line[7])));
          $name = ucfirst(strtolower(trim($csv_line[8])));
          $otch = ucfirst(strtolower(trim($csv_line[9])));
          $dol = ucfirst(strtolower(trim($csv_line[10])));
          if($dol == "") $dol = "-";
          $gortel = trim($csv_line[11]);
          $mobtel = trim($csv_line[12]);
          $inttel = trim($csv_line[13]);
          $mail = strtolower(trim($csv_line[14]));
          $dom = strtolower(trim($csv_line[15]));
          if($dom == "") $dom = "-";
          $pos = trim($csv_line[16]);
          $what_do = trim($csv_line[17]);
          $org_old = ucfirst(trim($csv_line[18]));
          if($org_old == "") $org_old = "-";
          $upr_old = ucfirst(trim($csv_line[19]));
          if($upr_old == "") $upr_old = "-";
          $otd_old = ucfirst(trim($csv_line[20]));
          if($otd_old == "") $otd_old = "-";
          $city_old = ucfirst(strtolower(trim($csv_line[21])));
          if($city_old == "") $city_old = "-";
          $str_old = ucfirst(strtolower(trim($csv_line[22])));
          if($str_old == "") $str_old = "-";
          $house_old = trim($csv_line[23]);
          $room_old = trim($csv_line[24]);
          $fam_old = ucfirst(strtolower(trim($csv_line[25])));
          $name_old = ucfirst(strtolower(trim($csv_line[26])));
          $otch_old = ucfirst(strtolower(trim($csv_line[27])));
          $dol_old = ucfirst(strtolower(trim($csv_line[28])));
          if($dol_old == "") $dol_old = "-";
          $gortel_old = trim($csv_line[29]);
          $mobtel_old = trim($csv_line[30]);
          $inttel_old = trim($csv_line[31]);
          $mail_old = strtolower(trim($csv_line[32]));
          $dom_old = strtolower(trim($csv_line[33]));
          if($dom_old == "") $dom_old = "-";
          $pos_old = trim($csv_line[34]);

          $pos_org = 1;
          $pos_upr = 1;
          $pos_otd = 1;

          //Ищем знакомых и строим структуру
          $query_org = mysql_query("SELECT `org_id`, `organizaciya`, `position` FROM `tbl_organizaciya` WHERE LOWER(organizaciya)=LOWER('".$org."')");
           if(!$query_org) puterror2 (mysql_error());
           $org_rows = mysql_numrows($query_org);
            if($org_rows == 0)
            {
             if($org == "-") $vis_org = "hide";
              else $vis_org = "show";
             $query_org2 = mysql_query("INSERT INTO `tbl_organizaciya` ( `org_id`, `organizaciya`, `position`, `visible` ) VALUES ( NULL , '".$org."', '".$pos_org."', '".$vis_org."')");
              if(!$query_org2) puterror2 (mysql_error());
             $query_org3 = mysql_query("SELECT `org_id`, `organizaciya`, `position` FROM `tbl_organizaciya` WHERE LOWER(organizaciya)=LOWER('".$org."')");
              if(!$query_org3) puterror2 (mysql_error());
               $res_org = mysql_fetch_array($query_org3,MYSQL_ASSOC);
               $org_id = $res_org['org_id'];
               $org_pos = $res_org['position'];
            }
            elseif($org_rows == 1)
              {
                $res_org = mysql_fetch_array($query_org,MYSQL_ASSOC);
                $org_id = $res_org['org_id'];
                $org_pos = $res_org['position'];
              }

          $query_upr = mysql_query("SELECT `upr_id`, `upravlenie`, `position` FROM `tbl_upravlenie` WHERE LOWER(upravlenie)=LOWER('".$upr."')");
           if(!$query_upr) puterror2 (mysql_error());
           $upr_rows = mysql_numrows($query_upr);
            if($upr_rows == 0)
            {
             if($upr == "-") $vis_upr = "hide";
              else $vis_upr = "show";
             $query_upr2 = mysql_query("INSERT INTO `tbl_upravlenie` ( `upr_id`, `upravlenie`, `position`, `visible` ) VALUES ( NULL , '".$upr."',  '".$pos_upr."', '".$vis_upr."')");
              if(!$query_upr2) puterror2 (mysql_error());
             $query_upr3 = mysql_query("SELECT `upr_id`, `upravlenie`, `position` FROM `tbl_upravlenie` WHERE LOWER(upravlenie)=LOWER('".$upr."')");
              if(!$query_upr3) puterror2 (mysql_error());
               $res_upr = mysql_fetch_array($query_upr3,MYSQL_ASSOC);
               $upr_id = $res_upr['upr_id'];
               $upr_pos = $res_upr['position'];
            }
            elseif($upr_rows == 1)
              {
                $res_upr = mysql_fetch_array($query_upr,MYSQL_ASSOC);
                $upr_id = $res_upr['upr_id'];
                $upr_pos = $res_upr['position'];
              }

          $query_otd = mysql_query("SELECT `otd_id`, `otdel`, `position` FROM `tbl_otdel` WHERE LOWER(otdel)=LOWER('".$otd."')");
           if(!$query_otd) puterror2 (mysql_error());
           $otd_rows = mysql_numrows($query_otd);
            if($otd_rows == 0)
            {
             if($otd == "-") $vis_otd = "hide";
              else $vis_otd = "show";
             $query_otd2 = mysql_query("INSERT INTO `tbl_otdel` (`otd_id`, `otdel`, `position`, `visible`, `phone` ) VALUES ( NULL , '".$otd."', '".$pos_otd."', '".$vis_otd."','')");
              if(!$query_otd2) puterror2 (mysql_error());
             $query_otd3 = mysql_query("SELECT `otd_id`, `otdel`, `position` FROM `tbl_otdel` WHERE LOWER(otdel)=LOWER('".$otd."')");
              if(!$query_otd3) puterror2 (mysql_error());
               $res_otd = mysql_fetch_array($query_otd3,MYSQL_ASSOC);
               $otd_id = $res_otd['otd_id'];
               $otd_pos = $res_otd['position'];
            }
            elseif($otd_rows == 1)
              {
                $res_otd = mysql_fetch_array($query_otd,MYSQL_ASSOC);
                $otd_id = $res_otd['otd_id'];
                $otd_pos = $res_otd['position'];
              }

          $query_city = mysql_query("SELECT `city_id`, `city` FROM `tbl_city` WHERE LOWER(city)=LOWER('".$city."')");
           if(!$query_city) puterror2 (mysql_error());
           $city_rows = mysql_numrows($query_city);
            if($city_rows == 0)
            {
             $query_city2 = mysql_query("INSERT INTO `tbl_city` (`city_id`, `city`) VALUES ( NULL , '".$city."')");
              if(!$query_city2) puterror2 (mysql_error());
             $query_city3 = mysql_query("SELECT `city_id`, `city` FROM `tbl_city` WHERE LOWER(city)=LOWER('".$city."')");
              if(!$query_city3) puterror2 (mysql_error());
               $res_city = mysql_fetch_array($query_city3,MYSQL_ASSOC);
               $city_id = $res_city['city_id'];
            }
            elseif($city_rows == 1)
              {
                $res_city = mysql_fetch_array($query_city,MYSQL_ASSOC);
                $city_id = $res_city['city_id'];
              }

          $query_str = mysql_query("SELECT `str_id`, `street` FROM `tbl_street` WHERE LOWER(street)=LOWER('".$str."')");
           if(!$query_str) puterror2 (mysql_error());
           $str_rows = mysql_numrows($query_str);
            if($str_rows == 0)
            {
             $query_str2 = mysql_query("INSERT INTO `tbl_street` (`str_id`, `street`) VALUES ( NULL , '".$str."')");
              if(!$query_str2) puterror2 (mysql_error());
             $query_str3 = mysql_query("SELECT `str_id`, `street` FROM `tbl_street` WHERE LOWER(street)=LOWER('".$str."')");
              if(!$query_str3) puterror2 (mysql_error());
               $res_str = mysql_fetch_array($query_str3,MYSQL_ASSOC);
               $str_id = $res_str['str_id'];
            }
            elseif($str_rows == 1)
              {
                $res_str = mysql_fetch_array($query_str,MYSQL_ASSOC);
                $str_id = $res_str['str_id'];
              }

          $query_house = mysql_query("SELECT `house_id`, `house` FROM `tbl_house` WHERE LOWER(house)=LOWER('".$house."')");
           if(!$query_house) puterror2 (mysql_error());
           $house_rows = mysql_numrows($query_house);
            if($house_rows == 0)
            {
             $query_house2 = mysql_query("INSERT INTO `tbl_house` (`house_id`, `house`) VALUES ( NULL , '".$house."')");
              if(!$query_house2) puterror2 (mysql_error());
             $query_house3 = mysql_query("SELECT `house_id`, `house` FROM `tbl_house` WHERE LOWER(house)=LOWER('".$house."')");
              if(!$query_house3) puterror2 (mysql_error());
               $res_house = mysql_fetch_array($query_house3,MYSQL_ASSOC);
               $house_id = $res_house['house_id'];
            }
            elseif($house_rows == 1)
              {
                $res_house = mysql_fetch_array($query_house,MYSQL_ASSOC);
                $house_id = $res_house['house_id'];
              }

          $query_dol = mysql_query("SELECT `dol_id`, `dolzhnost` FROM `tbl_dolzhnost` WHERE LOWER(`dolzhnost`)=LOWER('".$dol."')");
           if(!$query_dol) puterror2 (mysql_error());
           $dol_rows = mysql_numrows($query_dol);
            if($dol_rows == 0)
            {
             echo $dol_rows."<br />";
             $query_dol2 = mysql_query("INSERT INTO `tbl_dolzhnost` ( `dol_id`, `dolzhnost`, `position` ) VALUES ( NULL , '".$dol."', '1')");
              if(!$query_dol2) puterror2 (mysql_error());
             $query_dol3 = mysql_query("SELECT `dol_id`, `dolzhnost` FROM `tbl_dolzhnost` WHERE LOWER(`dolzhnost`)=LOWER('".$dol."')");
              if(!$query_dol3) puterror2 (mysql_error());
               $res_dol = mysql_fetch_array($query_dol3,MYSQL_ASSOC);
               $dol_id = $res_dol['dol_id'];
            }
            elseif($dol_rows == 1)
              {
                $res_dol = mysql_fetch_array($query_dol,MYSQL_ASSOC);
                $dol_id = $res_dol['dol_id'];
              }

          $query_dom = mysql_query("SELECT `dom_id`, `domain` FROM `tbl_domain` WHERE LOWER(domain)=LOWER('".$dom."')");
           if(!$query_dom) puterror2 (mysql_error());
           $dom_rows = mysql_numrows($query_dom);
            if($dom_rows == 0)
            {
             $query_dom2 = mysql_query("INSERT INTO `tbl_domain` ( `dom_id`, `domain` ) VALUES ( NULL , '".$dom."')");
              if(!$query_dom2) puterror2 (mysql_error());
             $query_dom3 = mysql_query("SELECT `dom_id`, `domain` FROM `tbl_domain` WHERE LOWER(domain)=LOWER('".$dom."')");
              if(!$query_dom3) puterror2 (mysql_error());
               $res_dom = mysql_fetch_array($query_dom3,MYSQL_ASSOC);
               $dom_id = $res_dom['dom_id'];
            }
            elseif($dom_rows == 1)
              {
                $res_dom = mysql_fetch_array($query_dom,MYSQL_ASSOC);
                $dom_id = $res_dom['dom_id'];
              }

       $first_bt = substr($fam, 0,1);
         if(preg_match("/[A-Z]/i", $first_bt)) $first_b = substr($fam, 0,1);
        //if(preg_match("/[A-Z]/i", $first_bt)) $first_b = substr($_POST['familiya'], 0,3);
         else $first_b = substr($fam, 0,2);

         if($what_do == "add")
             {
             $query_usr = "INSERT INTO tbl_users (
             `user_id` ,
             `first_b`,
             `familiya`,
             `name`,
             `otchestvo`,
             `position`,
             `dom_id`,
             `mail`,
             `phone_mob`,
             `phone_int`,
             `phone_city`,
             `dol_id`,
             `otd_id`,
             `otd_pos`,
             `upr_id`,
             `upr_pos`,
             `org_id`,
             `org_pos`,
             `room`,
             `house_id`,
             `str_id`,
             `city_id`,
             `photo`,
             `subscribe`,
             `visible` )
              VALUES (
             NULL ,
             '$first_b',
             '".$fam."',
             '".$name."',
             '".$otch."',
             '".$pos."',
             '".$dom_id."',
             '".$mail."',
             '".$mobtel."',
             '".$inttel."',
             '".$gortel."',
             '".$dol_id."',
             '".$otd_id."',
             '".$otd_pos."',
             '".$upr_id."',
             '".$upr_pos."',
             '".$org_id."',
             '".$org_pos."',
             '".$room."',
             '".$house_id."',
             '".$str_id."',
             '".$city_id."',
             '',
             'unscribe',
             'show') ";
             $result_usr = mysql_query($query_usr);
              if(!$result_usr) puterror2(mysql_error());

              if($ldp == 1)
               {
             $ds=ldap_connect($dlp_srv, $ldp_port) or die("Could not connect to {$ldp_srv}");
             ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
             $usr_bnd=ldap_bind($ds, $ldp_user, $ldp_pass) or die(ldap_error($ds));

             $ldap_mass = array();

             if($otd == "-") $res_otd = $upr;
                else $res_otd = $otd;
             if($room == "") $res_room = "-";
                 else $res_room = $room;
             if($gortel == "") $res_phone = "+";
                 else $res_phone = $gortel;
             if($inttel == "-")  $res_phone_int = "";
               else $res_phone_int = $inttel;
             if($mobtel == "") $res_phone_mob = "+";
                 else $res_phone_mob = $mobtel;

             $name_tmp=substr($name, 0,2);
             $otch_tmp=substr($otch, 0,2);
             $inits1 = strtoupper($name_tmp).".";
             $inits2 = strtoupper($otch_tmp).".";
             $mailbase = strtolower($mail);
             if($mailbase == "") $mailbase = "no-mail";
               else $mailbase = $mailbase;

             if($city == "" && $city !== "-"){$cit = $TEXT['user-city']." ".$city.", ";}
               else $cit = " ";
             if($str == "" && $str !== "-"){$strt = $TEXT['user-str']." ".$str.", ";}
               else $strt = " ";
             if($house == "" && $house !== "-"){$hou = $TEXT['user-home']." ".$house.", ";}
               else $hou = " ";
             if($room == "" && $room !== "-"){$rum = $TEXT['user-room']." ".$room;}
               else $rum = " ";

             $dn = "cn=".$fam." ".$name." ".$otch.",".$ldp_dn; // dn: uid=user,ou=people,dc=atomstroyexport,dc=local

            $ldap_mass['objectClass'] [0] = "top";
            $ldap_mass['objectClass'] [1] = "person";
            $ldap_mass['objectClass'] [2] = "organizationalPerson";
            $ldap_mass['objectClass'] [3] = "inetOrgPerson";
            $ldap_mass['cn'] = $fam." ".$name." ".$otch; // полное имя, равно отображаемому имени
            $ldap_mass['givenName'] = $name." ".$otch; //имя
            $ldap_mass['sn'] = $fam; // фамилия
            $ldap_mass['displayName'] = $fam." ".$name." ".$otch; //отображаемое имя
            $ldap_mass['uid'] = $mailbase; //уникальное имя, я исп чать мыльника
            $ldap_mass['initials'] = $inits1.$inits2; // инициалы
            $ldap_mass['postalAddress'] = $cit.$strt.$hou.$rum; // почтовый адрес
            $ldap_mass['o'] = $org; // организация
            $ldap_mass['l'] = $cit; // город
            $ldap_mass['mail'] = $mailbase."@".$dom; // почта
            $ldap_mass['title'] = $dol; // должность
            $ldap_mass['ou'] = $res_otd; // отдел
            $ldap_mass['telephoneNumber'] = $res_phone." ".$res_phone_int; // телефон
            $ldap_mass['mobile'] = $res_phone_mob; // телефон мобильный
            $ldap_mass['street'] = $str; // улица
            $ldap_mass['roomNumber'] = $res_room; // номер комнаты
            $ldap_mass['physicalDeliveryOfficeName'] = $res_room; // номер комнаты

            ldap_add($ds, $dn, $ldap_mass);
            ldap_unbind($ds) or die(ldap_error($ds));
            ldap_close($ds) or die(ldap_error($ds));
            $dn = "";
             }
            //*************************************
             $ip = "127.0.0.1";
             $doing = $TEXT['repl-add'];
             $what = $fam." ".$name." ".$otch;
             $who = "Robot";
            //*************************************
             $query_rep = mysql_query("INSERT INTO tbl_logs ( `log_id` , `data` , `ip` , `who` , `doing` , `what` ) VALUES ( NULL , NULL , '$ip' , '$who' , '$doing' , '$what')");
             $ip = "";
             $doing = "";
             $what = "";
             $who = "";
             echo "User - \033[32m\033[1m".$fam." ".$name." ".$otch." added\033[0m\033[0m to PhoneBook\r\n";
            }
            elseif($what_do == "del")
             {
             $query_usr = "DELETE FROM `tbl_users` WHERE `familiya` = '".$fam."' AND `name` = '".$name."' AND `otchestvo` = '".$otch."' AND `position` = '".$pos."' AND `mail` = '".$mail."' AND `phone_mob` = '".$mobtel."' AND `phone_int` = '".$inttel."' AND `phone_city` = '".$gortel."' AND `room` = '".$room."' LIMIT 1";
             $result_usr = mysql_query($query_usr);
              if(!$result_usr) puterror2(mysql_error());
              if(mysql_affected_rows() > 0) {
               $dlt_usr = "User - \033[31m\033[1m".$fam." ".$name." ".$otch." deleted\033[0m\033[0m from PhoneBook\r\n";
               $dlt_usr_log = "Пользователь - ".$fam." ".$name." ".$otch." удалён";}
                else {
                    $dlt_usr = "User - \033[36m\033[1m".$fam." ".$name." ".$otch." not found\033[0m\033[0m in PhoneBook\r\n";
                    $dlt_usr_log = "Пользователь - ".$fam." ".$name." ".$otch." не найден";
                    ////////////////////////////////////////////////////////
                    // mail
                    ////////////////////////////////////////////////////////
                    $address = $result_srv_set['admin_mail'];
                    $podpis = $TEXT['admin-podpis']."<br />".date("D, d-M-Y H:i:s", time());
                    $tema = $TEXT['repl-tema-err'];
                    $msg = "<b>".$TEXT['repl-del']."</b>&nbsp;(".$TEXT['search-org']." ".$org.")<br /><br />".$dlt_usr_log."<br /><hr />".$podpis."";

                    $podpis = stripslashes($podpis);
                    $tema = stripslashes($tema);
                    $msg = stripslashes($msg);

                    @mail($address, $tema, $msg, join("\r\n", array(
                    "From: phonebook@local",
                    "MIME-Version: 1.0",
                    "Content-type: text/html; charset=utf-8",
                    "Content-Transfer-Encoding: 8bit",
                    "Date: ".date("D, d-M-Y H:i:s", time())."",
                    "X-Mailer: Phone Book"
                    )));
                    ////////////////////////////////////////////////////////
                    // end mail
                    ////////////////////////////////////////////////////////
                    }

              if($ldp == 1)
               {

             $ds=ldap_connect($dlp_srv, $ldp_port) or die("Could not connect to {$ldp_srv}");
             ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
             $usr_bnd=ldap_bind($ds, $ldp_user, $ldp_pass) or die(ldap_error($ds));

             $dn = "cn=".$fam." ".$name." ".$otch.",".$ldp_dn; // dn: uid=user,ou=people,dc=atomstroyexport,dc=local
             ldap_delete($ds, $dn) or die(ldap_error($ds));
             ldap_unbind($ds) or die(ldap_error($ds));
             ldap_close($ds) or die(ldap_error($ds));
             $dn = "";
            }
            //*************************************
             $ip = "127.0.0.1";
             $doing = $TEXT['repl-del'];
             $what = $dlt_usr_log;
             $who = "Robot";
            //*************************************
             $query_rep = mysql_query("INSERT INTO tbl_logs ( `log_id` , `data` , `ip` , `who` , `doing` , `what` ) VALUES ( NULL , NULL , '$ip' , '$who' , '$doing' , '$what')");
             $ip = "";
             $doing = "";
             $what = "";
             $who = "";
             echo $dlt_usr;
          }
            elseif($what_do == "edt")
             {
             $query_usr = "UPDATE tbl_users SET
                `first_b` =  '$first_b',
                `familiya` = '".$fam."',
                `name` = '".$name."',
                `otchestvo` = '".$otch."',
                `position` = '".$pos."',
                `dom_id` = '$dom_id',
                `mail` = '".$mail."',
                `phone_mob` = '".$mobtel."',
                `phone_int` = '".$inttel."',
                `phone_city` = '".$gortel."',
                `dol_id` = '$dol_id',
                `otd_id` = '$otd_id',
                `otd_pos` = '$otd_pos',
                `upr_id` = '$upr_id',
                `upr_pos` = '$upr_pos',
                `org_id` = '$org_id',
                `org_pos` = '$org_pos',
                `room` = '".$room."',
                `house_id` = '$house_id',
                `str_id` = '$str_id',
                `city_id` = '$city_id'
                WHERE `familiya` = '".$fam_old."' AND `name` = '".$name_old."' AND `otchestvo` = '".$otch_old."' AND `position` = '".$pos_old."' AND `mail` = '".$mail_old."' AND `phone_mob` = '".$mobtel_old."' AND `phone_int` = '".$inttel_old."' AND `phone_city` = '".$gortel_old."' AND `room` = '".$room_old."' LIMIT 1";
             $result_usr = mysql_query($query_usr);
              if(!$result_usr) puterror2(mysql_error());
              if(mysql_affected_rows() > 0) {
               $dlt_usr = "User - \033[33m\033[1m".$fam_old." ".$name_old." ".$otch_old." edited\033[0m\033[0m from PhoneBook\r\n";
               $dlt_usr_log = "Пользователь - ".$fam_old." ".$name_old." ".$otch_old." отредактирован";}
                else {
                    $dlt_usr = "User - \033[36m\033[1m".$fam_old." ".$name_old." ".$otch_old." not found\033[0m\033[0m in PhoneBook\r\n";
                    $dlt_usr_log = "Пользователь - ".$fam_old." ".$name_old." ".$otch_old." не найден";
                    ////////////////////////////////////////////////////////
                    // mail
                    ////////////////////////////////////////////////////////
                    $address = $result_srv_set['admin_mail'];
                    $podpis = $TEXT['admin-podpis']."<br />".date("D, d-M-Y H:i:s", time());
                    $tema = $TEXT['repl-tema-err'];
                    $msg = "<b>".$TEXT['repl-edt']."</b>&nbsp;(".$TEXT['search-org']." ".$org_old.")<br /><br />".$dlt_usr_log."<br /><br />".$TEXT['repl-bilo']."<br /><b>".$fam_old." ".$name_old." ".$otch_old."</b><br />".$TEXT['user-adrr']." ".$TEXT['user-city'].$city_old.", ".$TEXT['user-str'].$str_old.", ".$TEXT['user-home'].$house_old.", ".$TEXT['user-room'].$room_old."<br />".$TEXT['search-org']." ".$org_old."<br />".$TEXT['search-upr']." ".$upr_old."<br />".$TEXT['search-otd']." ".$otd_old."<br />".$TEXT['search-dol']." ".$dol_old."<br />".$TEXT['user-tel-mob']." ".$mobtel_old."<br />".$TEXT['user-tel-city']." ".$gortel_old."<br />".$TEXT['user-tel-int']." ".$inttel_old."<br />".$TEXT['user-e-mail']." ".$mail_old."@".$dom_old."<br />".$TEXT['izm-pos'].": ".$pos_old."<br /><br />".$TEXT['repl-stalo']."<br /><b>".$fam." ".$name." ".$otch."</b><br />".$TEXT['user-adrr']." ".$TEXT['user-city'].$city.", ".$TEXT['user-str'].$str.", ".$TEXT['user-home'].$house.", ".$TEXT['user-room'].$room."<br />".$TEXT['search-org']." ".$org."<br />".$TEXT['search-upr']." ".$upr."<br />".$TEXT['search-otd']." ".$otd."<br />".$TEXT['search-dol']." ".$dol."<br />".$TEXT['user-tel-mob']." ".$mobtel."<br />".$TEXT['user-tel-city']." ".$gortel."<br />".$TEXT['user-tel-int']." ".$inttel."<br />".$TEXT['user-e-mail']." ".$mail."@".$dom."<br />".$TEXT['izm-pos'].": ".$pos."<br /><hr />".$podpis."";

                    $podpis = stripslashes($podpis);
                    $tema = stripslashes($tema);
                    $msg = stripslashes($msg);

                    @mail($address, $tema, $msg, join("\r\n", array(
                    "From: phonebook@local",
                    "MIME-Version: 1.0",
                    "Content-type: text/html; charset=utf-8",
                    "Content-Transfer-Encoding: 8bit",
                    "Date: ".date("D, d-M-Y H:i:s", time())."",
                    "X-Mailer: Phone Book"
                    )));
                    ////////////////////////////////////////////////////////
                    // end mail
                    ////////////////////////////////////////////////////////
                    }

              if($ldp == 1)
               {
             $ds=ldap_connect($dlp_srv, $ldp_port) or die("Could not connect to {$ldp_srv}");
             ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
             $usr_bnd=ldap_bind($ds, $ldp_user, $ldp_pass) or die(ldap_error($ds));

             $ldap_mass = array();

             if($otd == "-") $res_otd = $upr;
                else $res_otd = $otd;
             if($room == "") $res_room = "-";
                 else $res_room = $room;
             if($gortel == "") $res_phone = "+";
                 else $res_phone = $gortel;
             if($inttel == "-")  $res_phone_int = "";
               else $res_phone_int = $inttel;
             if($mobtel == "") $res_phone_mob = "+";
                 else $res_phone_mob = $mobtel;

             $name_tmp=substr($name, 0,2);
             $otch_tmp=substr($otch, 0,2);
             $inits1 = strtoupper($name_tmp).".";
             $inits2 = strtoupper($otch_tmp).".";
             $mailbase = strtolower($mail);
             if($mailbase == "") $mailbase = "no-mail";
               else $mailbase = $mailbase;

             if($city == "" && $city !== "-"){$cit = $TEXT['user-city']." ".$city.", ";}
               else $cit = " ";
             if($str == "" && $str !== "-"){$strt = $TEXT['user-str']." ".$str.", ";}
               else $strt = " ";
             if($house == "" && $house !== "-"){$hou = $TEXT['user-home']." ".$house.", ";}
               else $hou = " ";
             if($room == "" && $room !== "-"){$rum = $TEXT['user-room']." ".$room;}
               else $rum = " ";

              $dn_tmp1 = $fam." ".$name." ".$otch;
              $dn_tmp2 = $fam_old." ".$name_old." ".$otch_old;
             if($dn_tmp1 !== $dn_tmp2)
             {
             $dn = "cn=".$dn_tmp2.",".$ldp_dn; // dn: uid=user,ou=people,dc=atomstroyexport,dc=local
             ldap_delete($ds, $dn) or die(ldap_error($ds));
             $dn = "cn=".$dn_tmp1.",".$ldp_dn; // dn: uid=user,ou=people,dc=atomstroyexport,dc=local

            $ldap_mass['objectClass'] [0] = "top";
            $ldap_mass['objectClass'] [1] = "person";
            $ldap_mass['objectClass'] [2] = "organizationalPerson";
            $ldap_mass['objectClass'] [3] = "inetOrgPerson";
            $ldap_mass['cn'] = $fam." ".$name." ".$otch; // полное имя, равно отображаемому имени
            $ldap_mass['givenName'] = $name." ".$otch; //имя
            $ldap_mass['sn'] = $fam; // фамилия
            $ldap_mass['displayName'] = $fam." ".$name." ".$otch; //отображаемое имя
            $ldap_mass['uid'] = $mailbase; //уникальное имя, я исп чать мыльника
            $ldap_mass['initials'] = $inits1.$inits2; // инициалы
            $ldap_mass['postalAddress'] = $cit.$strt.$hou.$rum; // почтовый адрес
            $ldap_mass['o'] = $org; // организация
            $ldap_mass['l'] = $cit; // город
            $ldap_mass['mail'] = $mailbase."@".$dom; // почта
            $ldap_mass['title'] = $dol; // должность
            $ldap_mass['ou'] = $res_otd; // отдел
            $ldap_mass['telephoneNumber'] = $res_phone." ".$res_phone_int; // телефон
            $ldap_mass['mobile'] = $res_phone_mob; // телефон мобильный
            $ldap_mass['street'] = $str; // улица
            $ldap_mass['roomNumber'] = $res_room; // номер комнаты
            $ldap_mass['physicalDeliveryOfficeName'] = $res_room; // номер комнаты

           ldap_add($ds, $dn, $ldap_mass) or die(ldap_error($ds));
           }
           else {
           $dn = "cn=".$dn_tmp2.",".$ldp_dn; // dn: uid=user,ou=people,dc=atomstroyexport,dc=local

           //$ldap_mass['cn'] = $_POST['familiya']." ".$_POST['name']." ".$_POST['otchestvo']; // полное имя, равно отображаемому имени
            $ldap_mass['givenName'] = $name." ".$otch; //имя
            $ldap_mass['sn'] = $fam; // фамилия
            $ldap_mass['displayName'] = $fam." ".$name." ".$otch; //отображаемое имя
            $ldap_mass['uid'] = $mailbase; //уникальное имя, я исп чать мыльника
            $ldap_mass['initials'] = $inits1.$inits2; // инициалы
            $ldap_mass['postalAddress'] = $cit.$strt.$hou.$rum; // почтовый адрес
            $ldap_mass['o'] = $org; // организация
            $ldap_mass['l'] = $cit; // город
            $ldap_mass['mail'] = $mailbase."@".$dom; // почта
            $ldap_mass['title'] = $dol; // должность
            $ldap_mass['ou'] = $res_otd; // отдел
            $ldap_mass['telephoneNumber'] = $res_phone." ".$res_phone_int; // телефон
            $ldap_mass['mobile'] = $res_phone_mob; // телефон мобильный
            $ldap_mass['street'] = $str; // улица
            $ldap_mass['roomNumber'] = $res_room; // номер комнаты
            $ldap_mass['physicalDeliveryOfficeName'] = $res_room; // номер комнаты

           ldap_modify($ds, $dn, $ldap_mass);
           if(ldap_error($ds) == "No such object")
           {
           $dn = "cn=".$dn_tmp1.",".$ldp_dn; // dn: uid=user,ou=people,dc=atomstroyexport,dc=local

            $ldap_mass['objectClass'] [0] = "top";
            $ldap_mass['objectClass'] [1] = "person";
            $ldap_mass['objectClass'] [2] = "organizationalPerson";
            $ldap_mass['objectClass'] [3] = "inetOrgPerson";
            $ldap_mass['cn'] = $fam." ".$name." ".$otch; // полное имя, равно отображаемому имени
            $ldap_mass['givenName'] = $name." ".$otch; //имя
            $ldap_mass['sn'] = $fam; // фамилия
            $ldap_mass['displayName'] = $fam." ".$name." ".$otch; //отображаемое имя
            $ldap_mass['uid'] = $mailbase; //уникальное имя, я исп чать мыльника
            $ldap_mass['initials'] = $inits1.$inits2; // инициалы
            $ldap_mass['postalAddress'] = $cit.$strt.$hou.$rum; // почтовый адрес
            $ldap_mass['o'] = $org; // организация
            $ldap_mass['l'] = $cit; // город
            $ldap_mass['mail'] = $mailbase."@".$dom; // почта
            $ldap_mass['title'] = $dol; // должность
            $ldap_mass['ou'] = $res_otd; // отдел
            $ldap_mass['telephoneNumber'] = $res_phone." ".$res_phone_int; // телефон
            $ldap_mass['mobile'] = $res_phone_mob; // телефон мобильный
            $ldap_mass['street'] = $str; // улица
            $ldap_mass['roomNumber'] = $res_room; // номер комнаты
            $ldap_mass['physicalDeliveryOfficeName'] = $res_room; // номер комнаты

           ldap_add($ds, $dn, $ldap_mass) or die(ldap_error($ds));
           }
           ldap_unbind($ds) or die(ldap_error($ds));
           ldap_close($ds) or die(ldap_error($ds));
           }
            $dn = "";
             ldap_unbind($ds) or die(ldap_error($ds));
             ldap_close($ds) or die(ldap_error($ds));
             }
             //*************************************
             $ip = "127.0.0.1";
             $doing = $TEXT['repl-edt'];
             $what = $dlt_usr_log;
             $who = "Robot";
              //*************************************
             $query_rep = mysql_query("INSERT INTO tbl_logs ( `log_id` , `data` , `ip` , `who` , `doing` , `what` ) VALUES ( NULL , NULL , '$ip' , '$who' , '$doing' , '$what')");
             $ip = "";
             $doing = "";
             $what = "";
             $who = "";
             echo $dlt_usr;
           }

          }
        }
      }
      unlink("/var/www/personal/replica/".$files[$i]);
      echo "Close and delete file - \033[33m\033[1m".$files[$i]."\033[0m\033[0m\r\n\r\n";
      }
  echo "\r\n\033[32m\033[1mReplication complete.\033[0m\033[0m\r\n";
?>