<?php
  ///////////////////////////////////////////////////
  //2010 (C)
  //Карпухин Павел
  ///////////////////////////////////////////////////

  $lang = substr($_SERVER["HTTP_ACCEPT_LANGUAGE"], 0,2);
  if(is_file ("../lang/".$lang."/".$lang.".php")) include "../lang/".$lang."/".$lang.".php";
     else include "../lang/ru/ru.php";

  if(!isset($title)) $title = $TEXT['menu-btn36'];

  require_once "../config.php";
  require_once "../util/top_layer1.php";
  require_once "../lang/".$lang."/trans.php";

  if(empty($_POST['delimiter'])) puterror2($TEXT['error-delim1']);
  if(strlen($_POST['delimiter'])>1) puterror2($TEXT['error-delim2']);

  $delimiter = $_POST['delimiter'];
  $n = 0;

  if($result2['administrator'] == 0) puterror2($TEXT['error-loginform2']);

  if($_FILES['impfl']['size'] > 1024*10*1024) puterror2($TEXT['import_err1']);
    if(!empty($_FILES['impfl']['tmp_name']))
      {
       $dis_keys = mysql_query("ALTER TABLE DISABLE KEYS");
       $handle = file($_FILES['impfl']['tmp_name']);
       $size = filesize($_FILES['impfl']['tmp_name'])/1024;
       $numrows = count($handle);

       foreach($handle as $line_num => $line) 
        {
         $line_total = ($line_num + 1);
         $linedump=trim($line);
         if(!($linedump ==''))
         {
          if($line_num > 1)
          {
          $n = $n+1;
          $csv_line = explode($delimiter,$linedump,20);
          $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]);
          $pos_org = trim($csv_line[17]);
          $pos_upr = trim($csv_line[18]);
          $pos_otd = trim($csv_line[19]);
          //$linedump = str_replace($search, $replace, $linedump);
          //$query = "$linedump";
          //Ищем знакомых и строим структуру
          $query_org = mysql_query("SELECT `org_id`, `organizaciya` 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` 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'];
            }
            elseif($org_rows == 1)
              {
                $res_org = mysql_fetch_array($query_org,MYSQL_ASSOC);
                $org_id = $res_org['org_id'];
              }

          $query_upr = mysql_query("SELECT `upr_id`, `upravlenie` 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` 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'];
            }
            elseif($upr_rows == 1)
              {
                $res_upr = mysql_fetch_array($query_upr,MYSQL_ASSOC);
                $upr_id = $res_upr['upr_id'];
              }

          $query_otd = mysql_query("SELECT `otd_id`, `otdel` 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` 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'];
            }
            elseif($otd_rows == 1)
              {
                $res_otd = mysql_fetch_array($query_otd,MYSQL_ASSOC);
                $otd_id = $res_otd['otd_id'];
              }

          $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);

         $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."',
         '1',
         '".$upr_id."',
         '1',
         '".$org_id."',
         '1',
         '".$room."',
         '".$house_id."',
         '".$str_id."',
         '".$city_id."',
         '',
         'unscribe',
         'show') ";
          $result_usr = mysql_query($query_usr);
           if(!$result_usr) puterror2(mysql_error());
          }
        }
      }
      $en_keys = mysql_query("ALTER TABLE ENABLE KEYS");
      }
      unlink($_FILES['impfl']['tmp_name']);

  //*************************************
  //Информация для лога
  $ip = $_SERVER['REMOTE_ADDR'];
  $doing = $TEXT['log-import6'];
  $what = $TEXT['log-import2']."(".round($size, 2)." kb), ".$TEXT['log-import3']."(".$numrows."), ".$TEXT['log-import5']."(".$n.")";
  $who = $result2['fullname'];
  //*************************************
  $query2 = "INSERT INTO tbl_logs ( `log_id` , `data` , `ip` , `who` , `doing` , `what` ) VALUES ( NULL , NULL , '$ip' , '$who' , '$doing' , '$what')";
    if(mysql_query($query2))
     {
     echo "<html><head>
           <meta HTTP-EQUIV='Refresh' CONTENT='0; URL=index.php' />
           </head></html>";
     } else puterror2($TEXT['error-log']);
  require_once "../util/bottom.php";
?>