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

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

// /var/www/personal/
echo `clear`;
echo "Utilites for import passwords\r\n";

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

   $files = array();

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

  $query_usr = mysql_query("SELECT `login_id` FROM `tbl_logins` WHERE `login`='robot' LIMIT 1");
   if(!$query_usr) puterror2(mysql_error());
    $user_tmp=mysql_fetch_array($query_usr);
     $change_user = $user_tmp['login_id'];

  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/pass/".$files[$i]);
   $size = filesize("/var/www/personal/pass/".$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 import - \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";
   echo "Import data...\r\n";

  foreach($handle as $line_num => $line) 
        {
         $line_total = ($line_num + 1);
         $linedump=trim($line);
         if(!($linedump ==''))
         {
          // работаем с доп заголовком, первая строка не обрабатывается, но должна присутствовать
          // пример: LoginFromUser;Visible;Nazvanie(самое верхнее поле);NewPassword(первый сверху-вниз);NewPassword2(тот что для e-mail, второй сверху-вниз)
          if($line_num > 0)
          {
          $n = $n+1;
          $csv_line = explode($delimiter,$linedump,5);
          // Пользователь от которого работаем (для ключа шифрования)
          $programm_user = trim($csv_line[0]);
          // Уровень доступа show/hide, (для ключа шифрования)
          $pass_dost_tmp = trim($csv_line[1]);
          // Кого обновляем (название, точное совпадение)
          $pass_username = trim($csv_line[2]);
          // Первый пароль
          $pass_pwd = trim($csv_line[3]);
          // Второй пароль (может быть пустым)
          $pass_pwd2 = trim($csv_line[4]);
          if($pass_dost_tmp == "show") $pass_dost = 1;
           else $pass_dost = 2;

          //Ищем знакомых...
          $query_pass = mysql_query("SELECT `p_tmp` FROM `tbl_p_tmp` WHERE `usr_id`=(SELECT `login_id` FROM `tbl_logins` WHERE `login`='".$programm_user."' LIMIT 1)  AND `stat` = '".$pass_dost."' ");
           if(!$query_pass) puterror2 (mysql_error());
           $query_pass_rows = mysql_numrows($query_pass);
            if($query_pass_rows > 0)
            {
             $kfr_tmp=mysql_fetch_array($query_pass,MYSQL_ASSOC);

             if($pass_pwd2 !== "") $mail_pwd = " `mail_pass` = AES_ENCRYPT('".$pass_pwd2."','".$kfr_tmp['p_tmp']."'), ";
              else $mail_pwd = "";

             $query = "UPDATE `tbl_pass_keep` SET
              `dom_pass` = AES_ENCRYPT('".$pass_pwd."','".$kfr_tmp['p_tmp']."'),
              ".$mail_pwd."
              `data_edt` = NOW(),
              `login_edt_id` = '".$change_user."'
              WHERE `fio` = '".$pass_username."' LIMIT 1";
             $result_usr = mysql_query($query);
              if($result_usr) echo "Updated rows - \033[33m\033[1m".mysql_affected_rows()."\033[0m\033[0m.\r\n";
               else puterror2(mysql_error());
            }
            else
            {
              echo "Password for encripting procedure - not found\r\n";
            }
          }
        }
      }
      //*************************************
      $ip = "127.0.0.1";
      $doing = "Update passwords";
      $what = "File - ".$files[$i].", Size - ".round($size)." Kb, Rows inserted - ".$n;
      $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 = "";
      unlink("/var/www/personal/pass/".$files[$i]);
      echo "Close and delete file - \033[33m\033[1m".$files[$i]."\033[0m\033[0m\r\n";
      echo "Add information to project log\r\n-----\r\n\r\n";
  }
  echo "\r\n\033[32m\033[1mUpdate complete.\033[0m\033[0m\r\n";
?>