<?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";}

  $title = $TEXT['menu-btn37'];

  require_once "../config_a.php";
  require_once "../utils/functions.php";
  require_once "../utils/top_adm.php";

  if($result2['administrator'] == 0) {puterror($result2['skin'],$TEXT['error-loginform2']); require_once "../utils/bottom_adm.php"; exit();}

  if(empty($_POST['srv_id'])) {puterror($result2['skin'],$TEXT['error-srv21']); require_once "../utils/bottom_adm.php"; exit();}
  if(strlen($_POST['srv_id'])>5) {puterror($result2['skin'],$TEXT['error-srv22']); require_once "../utils/bottom_adm.php"; exit();}
  if(empty($_POST['typefile'])) {puterror($result2['skin'],$TEXT['import_err2']); require_once "../utils/bottom_adm.php"; exit();}
  if(strlen($_POST['typefile'])>1) {puterror($result2['skin'],$TEXT['import_err3']); require_once "../utils/bottom_adm.php"; exit();}
  if(empty($_POST['prefix'])) {puterror($result2['skin'],$TEXT['error-podset13']); require_once "../utils/bottom_adm.php"; exit();}
  if(empty($_POST['prefixnaz'])) {puterror($result2['skin'],$TEXT['error-podset14']); require_once "../utils/bottom_adm.php"; exit();}

  $_POST['srv_id'] = rep($_POST['srv_id']);
  $_POST['typefile'] = rep($_POST['typefile']);
  $_POST['prefix'] = rep($_POST['prefix']);
  $_POST['prefixnaz'] = rep($_POST['prefixnaz']);

  $delimiter = ".";
  $delimiter2 = ";";

    switch($_POST['typefile'])
      {
      case 1:
      $delimiter2 = ";";
      break;
      case 2:
      $delimiter2 = ",";
      break;
      }

      $n = 0;
      $s = 10;
      $exp_path = "../temp/sams_change_addr.csv";
      if(is_file($exp_path)) {unlink($exp_path);}
      $file = fopen($exp_path,"a");
      $exp_head = "old-ip;new-ip\r\n";
      fwrite($file, $exp_head, strlen($exp_head));

  if($_FILES['impfl']['size'] > 1024*10*1024) {puterror($result2['skin'],$TEXT['import_err1']); require_once "../utils/bottom_adm.php"; exit();}
    if(!empty($_FILES['impfl']['tmp_name']))
      {
       $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 > 0)
          {
           $csv_line = explode($delimiter2,$linedump,2);
           $mac = strtoupper(trim($csv_line[0]));
           $etazh = strtoupper(trim($csv_line[1]));

           $hwmass = Array(":","-");
           $mac=trim(strtoupper(str_replace($hwmass,"",$mac)));
           if(!preg_match("|^[0-9A-F]+$|i",$mac)) {puterror($result2['skin'],$TEXT['error-addr9']); require_once "../utils/bottom_adm.php"; exit();}
           if(strlen($mac) !== 12) {puterror($result2['skin'],$TEXT['error-addr9']); require_once "../utils/bottom_adm.php"; exit();}

// ищем подсеть
  $query_iskh = "SELECT
      tbl_podset.podset,
      tbl_podset.srv_id,
      tbl_podset.etazh_id,
      tbl_etazh.etazh,
      tbl_podset.house_id,
      tbl_house.house,
      tbl_podset.prefix
      FROM `tbl_podset`
      LEFT JOIN tbl_etazh ON tbl_podset.etazh_id=tbl_etazh.etazh_id
      LEFT JOIN tbl_house ON tbl_podset.house_id=tbl_house.house_id
      WHERE tbl_podset.srv_id='".$_POST['srv_id']."' AND tbl_podset.prefix='".$_POST['prefixnaz']."' AND tbl_podset.etazh_id=(SELECT etazh_id FROM tbl_etazh WHERE etazh='".$etazh."' LIMIT 1) ";
  $result_iskh = mysqli_query($dbcnx,$query_iskh);
  if(!$result_iskh) {puterror($result2['skin'],$TEXT['error-tbl13']); require_once "../utils/bottom_adm.php"; exit();}
      while($result_iskh2 = mysqli_fetch_array($result_iskh,MYSQLI_ASSOC))
      {
// Проверяем кол-во адресов на подсеть
  $query_iskh_check = "SELECT COUNT(ip_id) AS ip_chk  FROM tbl_ip WHERE ip_addr REGEXP '".$result_iskh2['podset']."' AND srv_id = '".$result_iskh2['srv_id']."' AND `vkl_ip` != '1' ";
  $result_iskh_check = mysqli_query($dbcnx,$query_iskh_check);
  if(!$result_iskh_check) {puterror($result2['skin'],$TEXT['error-tbl2']); require_once "../utils/bottom_adm.php"; exit();}
    $result_iskh_check2 = mysqli_fetch_array($result_iskh_check,MYSQLI_ASSOC);
     if($result_iskh_check2['ip_chk'] < 255)
     {

$query_iskh_srv = "SELECT ip_id, ip_addr, srv_id, descr FROM tbl_ip WHERE hw = '".$mac."' ";
  $result_iskh_srv = mysqli_query($dbcnx,$query_iskh_srv);
  if(!$result_iskh_srv) {puterror($result2['skin'],$TEXT['error-tbl2']); require_once "../utils/bottom_adm.php"; exit();}
    if(mysqli_num_rows($result_iskh_srv) > 0) {
      $result_iskh_srv2 = mysqli_fetch_array($result_iskh_srv,MYSQLI_ASSOC);
//     else {
//            //*************************************
//            //Информация для лога
//            $ip = $_SERVER['REMOTE_ADDR'];
//            $doing = $TEXT['menu-btn37-title'];
//            $what = $TEXT['error-addr19']."<br />".$TEXT['addr-mac']."&nbsp;&rArr;&nbsp;&laquo;".$mac."&raquo;";
//            $who = $result2['familiya']." ".$result2['name'];
//            //*************************************
//           $query2 = "INSERT INTO tbl_logs ( `log_id` , `data` , `ip` , `who` , `doing` , `what` ) VALUES ( NULL , NULL , '$ip' , '$who' , '$doing' , '$what')";
//            $to_log = mysqli_query($dbcnx,$query2);
//             }

      $addr = explode($delimiter,$result_iskh_srv2['ip_addr'],4);
       $oct1 = substr($addr['0'],0,1);
        if($oct1 == '0')
         {
          $oct_res1 = substr($addr['0'],1,1);
          if($oct_res1 == '0')
           {
         $oct_result1 = substr($addr['0'],2,3);
           } else {$oct_result1 = substr($addr['0'],1,3);}
         } else {$oct_result1 = $addr['0'];}

       $oct2 = substr($addr['1'],0,1);
        if($oct2 == '0')
         {
          $oct_res2 = substr($addr['1'],1,1);
           if($oct_res2 == '0')
            {
            $oct_result2 = substr($addr['1'],2,3);
            } else {$oct_result2 = substr($addr['1'],1,3);}
         } else {$oct_result2 = $addr['1'];}

       $oct3 = substr($addr['2'],0,1);
        if($oct3 == '0')
         {
         $oct_res3 = substr($addr['2'],1,1);
          if($oct_res3 == '0')
           {
           $oct_result3 = substr($addr['2'],2,3);
           } else {$oct_result3 = substr($addr['2'],1,3);}
         } else {$oct_result3 = $addr['2'];}

        $oct4 = substr($addr['3'],0,1);
         if($oct4 == '0')
          {
          $oct_res4 = substr($addr['3'],1,1);
           if($oct_res4 == '0')
            {
            $oct_result4 = substr($addr['3'],2,3);
            } else {$oct_result4 = substr($addr['3'],1,3);}
          } else {$oct_result4 = $addr['3'];}
        $ip_addres1 = $oct_result1.".".$oct_result2.".".$oct_result3.".".$oct_result4;
        $ip_addres1_new = $result_iskh_srv2['ip_addr'];
        $ip_addr_podset = $addr['0'].".".$addr['1'].".".$addr['2'].".";

// ищем подсеть исходного адреса
  $query_iskh_pods = "SELECT
      COUNT(pods_id) AS cnt_pods
      FROM `tbl_podset`
      WHERE tbl_podset.srv_id='".$result_iskh_srv2['srv_id']."' AND tbl_podset.prefix='".$_POST['prefix']."' AND tbl_podset.podset='".$ip_addr_podset."' ";
  $result_iskh_pods = mysqli_query($dbcnx,$query_iskh_pods);
  if(!$result_iskh_pods) {puterror($result2['skin'],$TEXT['error-tbl13']); require_once "../utils/bottom_adm.php"; exit();}
      $result_iskh2_pods = mysqli_fetch_array($result_iskh_pods,MYSQLI_ASSOC);

if($result_iskh2_pods['cnt_pods'] > 0) {
// Проверяем наличие исходной подсети

if($_POST['vikl_ip'] == "on") {
// Проверяем есть-ли на указанном сервере отключенные адреса
  $query_iskh_hw = "SELECT ip_id, ip_addr FROM tbl_ip WHERE ip_addr REGEXP '".$result_iskh2['podset']."' AND srv_id = '".$result_iskh2['srv_id']."' AND `vkl_ip` = '0' ORDER BY ip_addr LIMIT 1";
  $result_iskh_hw = mysqli_query($dbcnx,$query_iskh_hw);
   if(!$result_iskh_hw) {puterror($result2['skin'],mysqli_error($dbcnx)); require_once "../utils/bottom_adm.php"; exit();}
    if(mysqli_num_rows($result_iskh_hw) > 0)
     {
       $result_iskh_hw2 = mysqli_fetch_array($result_iskh_hw,MYSQLI_ASSOC);

       $ip_id_osn = $result_iskh_hw2['ip_id'];
       $addr2 = explode($delimiter,$result_iskh_hw2['ip_addr'],4);
       $oct12 = substr($addr2['0'],0,1);
        if($oct12 == '0')
         {
          $oct_res12 = substr($addr2['0'],1,1);
          if($oct_res12 == '0')
           {
         $oct_result12 = substr($addr2['0'],2,3);
           } else {$oct_result12 = substr($addr2['0'],1,3);}
         } else {$oct_result12 = $addr2['0'];}

       $oct22 = substr($addr2['1'],0,1);
        if($oct22 == '0')
         {
          $oct_res22 = substr($addr2['1'],1,1);
           if($oct_res22 == '0')
            {
            $oct_result22 = substr($addr2['1'],2,3);
            } else {$oct_result22 = substr($addr2['1'],1,3);}
         } else {$oct_result22 = $addr2['1'];}

       $oct32 = substr($addr2['2'],0,1);
        if($oct32 == '0')
         {
         $oct_res32 = substr($addr2['2'],1,1);
          if($oct_res32 == '0')
           {
           $oct_result32 = substr($addr2['2'],2,3);
           } else {$oct_result32 = substr($addr2['2'],1,3);}
         } else {$oct_result32 = $addr2['2'];}

        $oct42 = substr($addr2['3'],0,1);
         if($oct42 == '0')
          {
          $oct_res42 = substr($addr2['3'],1,1);
           if($oct_res42 == '0')
            {
            $oct_result42 = substr($addr2['3'],2,3);
            } else {$oct_result42 = substr($addr2['3'],1,3);}
          } else {$oct_result42 = $addr2['3'];}
        $ip_addres2 = $oct_result12.".".$oct_result22.".".$oct_result32.".".$oct_result42;
        $ip_addres = $ip_addres2;
        $ip_addres_new = $result_iskh_hw2['ip_addr'];
     }
     else
     {
//      $s = 10;
      $x = 0;
      for($s=10; $s<255; $s++)
      {
       $p_addr4 = strlen($s);
          if($p_addr4 == 1) {$p_addr4_result = "00".$s;}
           elseif($p_addr4 == 2) {$p_addr4_result = "0".$s;}
            else {$p_addr4_result = $s;}
       $srch_addr = $result_iskh2['podset'].$p_addr4_result;

     //Проверяем есть-ли в заданном диапазоне дырки
     $query_no_addr = "SELECT ip_addr FROM tbl_ip WHERE ip_addr = '".$srch_addr."' LIMIT 1";
     $result_no_addr = mysqli_query($dbcnx,$query_no_addr);
      if(!$result_no_addr) {puterror($result2['skin'],$TEXT['error-tbl2']); require_once "../utils/bottom_adm.php"; exit();}
        if(mysqli_num_rows($result_no_addr) == 0)
         {
          $x = 1;
          $no_addr2 = explode($delimiter,$srch_addr,4);
          $oct_no_addr12 = substr($no_addr2['0'],0,1);
          if($oct_no_addr12 == '0')
          {
          $oct_res_no_addr12 = substr($no_addr2['0'],1,1);
           if($oct_res_no_addr12 == '0')
            {
            $oct_result_no_addr12 = substr($no_addr2['0'],2,3);
            } else {$oct_result_no_addr12 = substr($no_addr2['0'],1,3);}
           } else {$oct_result_no_addr12 = $no_addr2['0'];}

         $oct_no_addr22 = substr($no_addr2['1'],0,1);
          if($oct_no_addr22 == '0')
          {
          $oct_res_no_addr22 = substr($no_addr2['1'],1,1);
           if($oct_res_no_addr22 == '0')
            {
            $oct_result_no_addr22 = substr($no_addr2['1'],2,3);
            } else {$oct_result_no_addr22 = substr($no_addr2['1'],1,3);}
           } else {$oct_result_no_addr22 = $no_addr2['1'];}

         $oct_no_addr32 = substr($no_addr2['2'],0,1);
          if($oct_no_addr32 == '0')
          {
          $oct_res_no_addr32 = substr($no_addr2['2'],1,1);
           if($oct_res_no_addr32 == '0')
           {
           $oct_result_no_addr32 = substr($no_addr2['2'],2,3);
           } else {$oct_result_no_addr32 = substr($no_addr2['2'],1,3);}
          } else {$oct_result_no_addr32 = $no_addr2['2'];}

          $oct_no_addr42 = substr($no_addr2['3'],0,1);
           if($oct_no_addr42 == '0')
           {
           $oct_res_no_addr42 = substr($no_addr2['3'],1,1);
            if($oct_res_no_addr42 == '0')
            {
            $oct_result_no_addr42 = substr($no_addr2['3'],2,3);
            } else {$oct_result_no_addr42 = substr($no_addr2['3'],1,3);}
           } else {$oct_result_no_addr42 = $no_addr2['3'];}
        $ip_addres3 = $oct_result_no_addr12.".".$oct_result_no_addr22.".".$oct_result_no_addr32.".".$oct_result_no_addr42;
        $ip_addres = $ip_addres3;
        $ip_addres_new = $srch_addr;
        if($x == 1) {break;}
         }
      $ip_addres = $ip_addres1;
      $ip_addres_new = $ip_addres1_new;
      }
    }
} else
    {
    // Выключенные адреса не учитываем
//      $s = 10;
      $x = 0;
      for($s=10; $s<255; $s++)
      {
       $p_addr4 = strlen($s);
          if($p_addr4 == 1) {$p_addr4_result = "00".$s;}
           elseif($p_addr4 == 2) {$p_addr4_result = "0".$s;}
            else {$p_addr4_result = $s;}
       $srch_addr = $result_iskh2['podset'].$p_addr4_result;

     //Проверяем есть-ли в заданном диапазоне дырки
     $query_no_addr = "SELECT ip_addr FROM tbl_ip WHERE ip_addr = '".$srch_addr."' LIMIT 1";
     $result_no_addr = mysqli_query($dbcnx,$query_no_addr);
      if(!$result_no_addr) {puterror($result2['skin'],$TEXT['error-tbl2']); require_once "../utils/bottom_adm.php"; exit();}
        if(mysqli_num_rows($result_no_addr) == 0)
         {
          $x = 1;
          $no_addr2 = explode($delimiter,$srch_addr,4);
          $oct_no_addr12 = substr($no_addr2['0'],0,1);
          if($oct_no_addr12 == '0')
          {
          $oct_res_no_addr12 = substr($no_addr2['0'],1,1);
           if($oct_res_no_addr12 == '0')
            {
            $oct_result_no_addr12 = substr($no_addr2['0'],2,3);
            } else {$oct_result_no_addr12 = substr($no_addr2['0'],1,3);}
           } else {$oct_result_no_addr12 = $no_addr2['0'];}

         $oct_no_addr22 = substr($no_addr2['1'],0,1);
          if($oct_no_addr22 == '0')
          {
          $oct_res_no_addr22 = substr($no_addr2['1'],1,1);
           if($oct_res_no_addr22 == '0')
            {
            $oct_result_no_addr22 = substr($no_addr2['1'],2,3);
            } else {$oct_result_no_addr22 = substr($no_addr2['1'],1,3);}
           } else {$oct_result_no_addr22 = $no_addr2['1'];}

         $oct_no_addr32 = substr($no_addr2['2'],0,1);
          if($oct_no_addr32 == '0')
          {
          $oct_res_no_addr32 = substr($no_addr2['2'],1,1);
           if($oct_res_no_addr32 == '0')
           {
           $oct_result_no_addr32 = substr($no_addr2['2'],2,3);
           } else {$oct_result_no_addr32 = substr($no_addr2['2'],1,3);}
          } else {$oct_result_no_addr32 = $no_addr2['2'];}

          $oct_no_addr42 = substr($no_addr2['3'],0,1);
           if($oct_no_addr42 == '0')
           {
           $oct_res_no_addr42 = substr($no_addr2['3'],1,1);
            if($oct_res_no_addr42 == '0')
            {
            $oct_result_no_addr42 = substr($no_addr2['3'],2,3);
            } else {$oct_result_no_addr42 = substr($no_addr2['3'],1,3);}
           } else {$oct_result_no_addr42 = $no_addr2['3'];}
        $ip_addres3 = $oct_result_no_addr12.".".$oct_result_no_addr22.".".$oct_result_no_addr32.".".$oct_result_no_addr42;
        $ip_addres = $ip_addres3;
        $ip_addres_new = $srch_addr;
        if($x == 1) {break;}
         }
      $ip_addres = $ip_addres1;
      $ip_addres_new = $ip_addres1_new;
      }
    }
// закрываем цикл проверки необходимости переноса (по подсетям, напр. перенносим только компьютеры)
     $query = "UPDATE `tbl_ip` SET
     `ip_addr` = '".$ip_addres_new."',
     `srv_id` = '".$_POST['srv_id']."',
     `vkl_ip` = '1',
     `data` = CURRENT_DATE(),
     `state_addr` = '0',
     `last_acc` = '1970-01-01'
     WHERE `ip_id`='".$result_iskh_srv2['ip_id']."'";
     $result = mysqli_query($dbcnx,$query);
       if(!$result) {puterror($result2['skin'],mysqli_error($dbcnx));}

       $exp_param = $ip_addres1.";".$ip_addres."\r\n";
       fwrite($file, $exp_param, strlen($exp_param));
       $n = $n+1;
       if($result_iskh_srv2['descr'] == "") {$result_iskh_srv2['descr'] = "---";}
       $msg_body .= $ip_addres1."&nbsp;&rArr;&nbsp;".$ip_addres." (".$result_iskh_srv2['descr'].", ".$result_iskh2['house']." ".$result_iskh2['etazh'].")\r\n";

        //*************************************
        //Информация для лога
        $ip = $_SERVER['REMOTE_ADDR'];
        $doing = $TEXT['menu-btn37-title'];
        $what = $result_iskh2['house']." ".$result_iskh2['etazh']." (".$ip_addres1."&nbsp;&rArr;&nbsp;".$ip_addres.")<br />".mysqli_error($dbcnx)."";
        $who = $result2['familiya']." ".$result2['name'];
        //*************************************
        $query3 = mysqli_query($dbcnx,"INSERT INTO tbl_logs ( `log_id` , `data` , `ip` , `who` , `doing` , `what` ) VALUES ( NULL , NULL , '$ip' , '$who' , '$doing' , '$what')");
        //$to_log2 = mysqli_query($dbcnx,$query3);
        }
      // Закрываем проверку на наличие подсети
      }
      // Закрываем проверку на наличие адреса
           else {
             // Пишем ошибку в лог о несуществующем адресе в лог
            //*************************************
            //Информация для лога
            $ip = $_SERVER['REMOTE_ADDR'];
            $doing = $TEXT['menu-btn37-title'];
            $what = $TEXT['error-addr19']."<br />".$TEXT['addr-mac']."&nbsp;&rArr;&nbsp;&laquo;".$mac."&raquo;";
            $who = $result2['familiya']." ".$result2['name'];
            //*************************************
           $query2 = "INSERT INTO tbl_logs ( `log_id` , `data` , `ip` , `who` , `doing` , `what` ) VALUES ( NULL , NULL , '$ip' , '$who' , '$doing' , '$what')";
            $to_log = mysqli_query($dbcnx,$query2);
             }

    }
   //  Закрываем проверку на кол-во адресов на подсеть
}
// Закрываем найденные подсети назначения
        }
     }
  }
}
unlink($_FILES['impfl']['tmp_name']);
  fclose($file);
  chmod($exp_path,0644);

////////////////////////////////////////////////////////
// mail
////////////////////////////////////////////////////////

$month["01"] = $TEXT['month01'];
$month["02"] = $TEXT['month02'];
$month["03"] = $TEXT['month03'];
$month["04"] = $TEXT['month04'];
$month["05"] = $TEXT['month05'];
$month["06"] = $TEXT['month06'];
$month["07"] = $TEXT['month07'];
$month["08"] = $TEXT['month08'];
$month["09"] = $TEXT['month09'];
$month["10"] = $TEXT['month10'];
$month["11"] = $TEXT['month11'];
$month["12"] = $TEXT['month12'];
$week["0"] = $TEXT['week01'];
$week["1"] = $TEXT['week02'];
$week["2"] = $TEXT['week03'];
$week["3"] = $TEXT['week04'];
$week["4"] = $TEXT['week05'];
$week["5"] = $TEXT['week06'];
$week["6"] = $TEXT['week07'];

$date_day = date("d");
$date_week = date("w");
$date_month = date("m");
$date_year = date("Y");
$year = $TEXT['year'];
$podpis = date("$week[$date_week], $date_day $month[$date_month] $date_year $year H:i:s");
$change_maker = " (".$result2['familiya']." ".$result2['name'].")";
$tema = $TEXT['menu-btn24-title'];
$msg = "<b>".$TEXT['menu-btn37-title']."</b><br /><br />".$msg_body."<br /><hr />".$podpis.$change_maker."";
$msg = nl2br($msg);

 mail($admin_mail, $tema, $msg, join("\r\n", array(
 "From: manydhcp@".$_SERVER['SERVER_NAME']."",
 "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: ManyDHCP"
 )));

////////////////////////////////////////////////////////
// end mail
////////////////////////////////////////////////////////

  //*************************************
  //Информация для лога
  $ip = $_SERVER['REMOTE_ADDR'];
  $doing = $TEXT['grp-srv-title'];
  $what = $TEXT['log-import2']."(".round($size, 2)." kb), ".$TEXT['log-import3']."(".$numrows."), ".$TEXT['grp-moved']."(".$n.")";
  $who = $result2['familiya']." ".$result2['name'];
  //*************************************
    $query2 = "INSERT INTO tbl_logs ( `log_id` , `data` , `ip` , `who` , `doing` , `what` ) VALUES ( NULL , NULL , '$ip' , '$who' , '$doing' , '$what')";
        if(mysqli_query($dbcnx,$query2))
           {
            if($_POST['sams_ch'] == "on") {
             echo "<html><head>
                   <meta HTTP-EQUIV='Refresh' CONTENT='0; URL=sams_upd.php?skin=".$result2['skin']."' />
                   </head></html>";
            } else
             {
             echo "<html><head>
                   <meta HTTP-EQUIV='Refresh' CONTENT='0; URL=../addresses/index.php' />
                   </head></html>";
            }
           } else {puterror($result2['skin'],$TEXT['error-log']); require_once "../utils/bottom_adm.php"; exit();}
  require_once "../utils/bottom_adm.php";
?>