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

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

  $title=$titlepage = $TEXT['pass-title'];
  $helppage = "";

  require_once "../config.php";
  require_once "top.php";
  ?>
  <title><?php echo $title; ?></title>
  <link rel="StyleSheet" type="text/css" href="../utils/reader.css" />
  <link rel="StyleSheet" type="text/css" href="../utils/grid.css" />
  <link rel="shortcut icon" href="../Favicon/know-base.ico" type="image/x-icon" />
  </head>
  <body leftmargin="0" marginheight="0" marginwidth="0" rightmargin="0" bottommargin="0" topmargin="0" >
  <?php
  if($result2['administrator'] == 0) puterror2($TEXT['error-supp11']);

  if(empty($_POST['pas_str_id'])) puterror2($TEXT['error-zhurn1']);
  if(strlen($_POST['pas_str_id'])>11) puterror2($TEXT['meet-err-edit3']);
  if(strlen($_POST['org_id'])>11) puterror2($TEXT['meet-err-edit3']);
  if(strlen($_POST['upr_id'])>11) puterror2($TEXT['meet-err-edit3']);
  if(strlen($_POST['otd_id'])>11) puterror2($TEXT['meet-err-edit3']);
  if(strlen($_POST['dol_id'])>11) puterror2($TEXT['meet-err-edit3']);
  if(strlen($_POST['city_id'])>11) puterror2($TEXT['meet-err-edit3']);
  if(strlen($_POST['str_id'])>11) puterror2($TEXT['meet-err-edit3']);
  if(strlen($_POST['house_id'])>11) puterror2($TEXT['meet-err-edit3']);
  if(strlen($_POST['dom_id'])>11) puterror2($TEXT['meet-err-edit3']);
  if(strlen($_POST['position'])>5) puterror2($TEXT['error-zhurn8']);

  $_POST['pas_str_id'] = rep($_POST['pas_str_id']);
  $_POST['org_id'] = rep($_POST['org_id']);
  $_POST['upr_id'] = rep($_POST['upr_id']);
  $_POST['otd_id'] = rep($_POST['otd_id']);
  $_POST['position'] = rep($_POST['position']);
  $_POST['dol_id'] = rep2($_POST['dol_id']);
  $_POST['city_id'] = rep2($_POST['city_id']);
  $_POST['str_id'] = rep($_POST['str_id']);
  $_POST['house_id'] = rep($_POST['house_id']);
  $_POST['dom_id'] = rep($_POST['dom_id']);

  $query_organizaciya2 = "SELECT * FROM `tbl_organizaciya` WHERE `org_id`='".$_POST['org_id']."' ";
   $result_org2 = mysql_query($query_organizaciya2);
     if(!$result_org2) puterror2($TEXT['error-tbl7']);
      $result_organizaciya2 = mysql_fetch_array($result_org2,MYSQL_ASSOC);
      $org_pos = $result_organizaciya2['position'];

  $query_upravlenie2 = "SELECT * FROM `tbl_upravlenie` WHERE `upr_id`= '".$_POST['upr_id']."' ";
    $result_upr2 = mysql_query($query_upravlenie2);
      if(!$result_upr2) puterror2($TEXT['error-tbl9']);
       $result_upravlenie2 = mysql_fetch_array($result_upr2,MYSQL_ASSOC);
       $upr_pos = $result_upravlenie2['position'];

  $query_otdel2 = "SELECT * FROM `tbl_otdel` WHERE `otd_id`= '".$_POST['otd_id']."' ";
   $result_otd2 = mysql_query($query_otdel2);
     if(!$result_otd2) puterror2($TEXT['error-tbl8']);
      $result_otdel2 = mysql_fetch_array($result_otd2,MYSQL_ASSOC);
      $otd_pos = $result_otdel2['position'];

  $query_dom2 = "SELECT `domain` FROM `tbl_domain` WHERE `dom_id`= '".$_POST['dom_id']."' ";
   $result_dom2 = mysql_query($query_dom2);
     if(!$result_dom2) puterror2($TEXT['error-tbl5']);
      $result_domain2 = mysql_fetch_array($result_dom2,MYSQL_ASSOC);

  $query_dol2 = "SELECT `dolzhnost` FROM `tbl_dolzhnost` WHERE `dol_id`= '".$_POST['dol_id']."' ";
   $result_dol2 = mysql_query($query_dol2);
     if(!$result_dol2) puterror2($TEXT['error-tbl6']);
      $result_dolzh2 = mysql_fetch_array($result_dol2,MYSQL_ASSOC);

  $query_str2 = "SELECT `street` FROM `tbl_street` WHERE `str_id`= '".$_POST['str_id']."' ";
   $result_str2 = mysql_query($query_str2);
     if(!$result_str2) puterror2($TEXT['error-tbl3']);
      $result_street2 = mysql_fetch_array($result_str2,MYSQL_ASSOC);

  $query_cit2 = "SELECT `city` FROM `tbl_city` WHERE `city_id`= '".$_POST['city_id']."' ";
   $result_cit2 = mysql_query($query_cit2);
     if(!$result_cit2) puterror2($TEXT['error-tbl1']);
      $result_city2 = mysql_fetch_array($result_cit2,MYSQL_ASSOC);

  $query_hou2 = "SELECT `house` FROM `tbl_house` WHERE `house_id`= '".$_POST['house_id']."' ";
   $result_hou2 = mysql_query($query_hou2);
     if(!$result_hou2) puterror2($TEXT['error-tbl4']);
      $result_house2 = mysql_fetch_array($result_hou2,MYSQL_ASSOC);

  if(!empty($result_city2['city']) && $result_city2['city'] !== "-"){$cit = $TEXT['user-city']." ".$result_city2['city'].", ";}
   else $cit = " ";

  if(!empty($result_street2['street']) && $result_street2['street'] !== "-"){$str = $TEXT['user-str']." ".$result_street2['street'].", ";}
   else $str = " ";

  if(!empty($result_house2['house']) && $result_house2['house'] !== "-"){$hou = $TEXT['user-home']." ".$result_house2['house'];}
   else $hou = " ";

  if(!empty($_POST['room']) && $_POST['room']!=="-"){$rum = ", ".$TEXT['user-room']." ".$_POST['room'];}
   else $rum = " ";

 $res_room = "-";
 $res_phone = "+";
 $res_phone_int = "";
 $res_phone_mob = "+";
?>
<table align="right">
  <tr><td><img align="bottom" alt="Logo" title='<?php echo $TEXT['global-title']; ?>' src="../img/logo.png" /></td><td class="logo"><?php echo $TEXT['global-title']; ?>&nbsp;<span class="logover">(<?php echo $TEXT['maker8']; ?>)</span></td></tr>
  <tr><td></td><td class="logo"><?php echo $TEXT['pass-title']; ?></td></tr>
  <tr><td></td><td>&nbsp;</td></tr>
</table>
<br />
<?php
  $result_strukt_name = "";

//function disabled by php > 5.5.3
// added 07.15.2014
////import_request_variables("gP", "in_");
// before using only ->  while(list($id,$value) = @each($in_printitem))
 while(list($id2,$value2) = @each($_POST)) {
  if($id2 == "printitem") {
   while(list($id,$value) = each($value2)) {
     if($id > 0 && $value == 'on')
     {
      $query4 = "SELECT
    tbl_pass_keep.pas_id,
    tbl_pass_keep.pas_str_id,
    tbl_pass_keep.usr_id,
    TRIM(SUBSTRING_INDEX(tbl_pass_keep.fio, ' ', 1)) AS fio_f,
    TRIM(SUBSTRING_INDEX(SUBSTRING_INDEX(tbl_pass_keep.fio, ' ', 2),' ',-1)) AS fio_i,
    TRIM(SUBSTRING_INDEX(SUBSTRING_INDEX(tbl_pass_keep.fio, ' ', 3),' ',-1)) AS fio_o,
    tbl_pass_keep.visible,
    tbl_pass_keep.mast_edt,
    tbl_logins.fullname,
    tbl_users.user_id
    FROM tbl_pass_keep
    JOIN tbl_logins ON tbl_pass_keep.login_id=tbl_logins.login_id
    LEFT JOIN tbl_users ON tbl_pass_keep.usr_id=tbl_users.user_id
    WHERE tbl_pass_keep.pas_id = '".$id."' ";
    $tmp4 = mysql_query($query4);
     if(!$tmp4) puterror2(mysql_error());
      $num_rows = mysql_num_rows($tmp4);
        if($num_rows == 0)
          {
           echo "<h1 class='userpage'><br />&nbsp;&nbsp;".$TEXT['zhurn-nodata']."</h1>";
          }
           else
           {
           while($sost4 = mysql_fetch_array($tmp4,MYSQL_ASSOC))
           {

            if($sost4['fio_i'] == $sost4['fio_o']) $sost4['fio_o'] = "";
              else $sost4['fio_o'] = $sost4['fio_o'];

             $result_strukt_name .= "&laquo;".$sost4['fio_f']." ".$sost4['fio_i']." ".$sost4['fio_o']."&raquo;, ";
             if($sost4['visible'] == 'show')
               {
                $query_count = mysql_query("SELECT COUNT(ptmp_id) FROM tbl_p_tmp WHERE usr_id = '".$result2['login_id']."' AND stat = '1' ");
                $coun_rows = mysql_result($query_count, 0);
                  if($coun_rows > 0) $pass_root = "<img alt='picture' src='../img/active.png' height='16' width='16' align='top' />";
                    else $pass_root = "<a href=# onClick=\"window.open('pass_userkfr_form.php','popup','top=".$TEXT['user-top'].",left=".$TEXT['user-left'].",width=".$TEXT['user-width'].",height=".$TEXT['user-height'].",status=no,scrollbars=no,location=no,menubar=no,toolbar=no')\" title ='".$TEXT['pass-err11']."'><img alt='picture' src='../img/warn_usr.png' height='16' width='16' align='top' /></a>";

                $query_iskh = "SELECT `p_tmp` FROM `tbl_p_tmp` WHERE `usr_id` = '".$result2['login_id']."' AND stat = '1' LIMIT 1";
                $result_iskh = mysql_query($query_iskh);
                  if(!$result_iskh) puterror2($TEXT['error-tbl53']);
                   $result_iskh2 = mysql_fetch_array($result_iskh,MYSQL_ASSOC);
                   $kfr_tmp = $result_iskh2['p_tmp'];
                   $cls_frm = "<fieldset class='zayavka_view' >";
                }
                else
                  {
                   $query_count = mysql_query("SELECT COUNT(ptmp_id) FROM tbl_p_tmp WHERE usr_id = '".$result2['login_id']."' AND stat = '2' ");
                   $coun_rows = mysql_result($query_count, 0);
                     if($coun_rows > 0) $pass_root = "<img alt='picture' src='../img/active.png' height='16' width='16' align='top' />";
                      else $pass_root = "<a href=# onClick=\"window.open('pass_rootkfr_form.php','popup','top=".$TEXT['user-top'].",left=".$TEXT['user-left'].",width=".$TEXT['user-width'].",height=".$TEXT['user-height'].",status=no,scrollbars=no,location=no,menubar=no,toolbar=no')\" title ='".$TEXT['pass-err10']."'><img alt='picture' src='../img/warn.png' height='16' width='16' align='top' /></a>";

                    $query_iskh = "SELECT `p_tmp` FROM `tbl_p_tmp` WHERE `usr_id` = '".$result2['login_id']."' AND stat = '2' LIMIT 1";
                    $result_iskh = mysql_query($query_iskh);
                      if(!$result_iskh) puterror2($TEXT['error-tbl53']);
                        $result_iskh2 = mysql_fetch_array($result_iskh,MYSQL_ASSOC);
                        $kfr_tmp = $result_iskh2['p_tmp'];
                        $cls_frm = "<fieldset class='zayavka_view' >";
                  }

               $query_iskh_p = "SELECT
                   AES_DECRYPT(tbl_pass_keep.dom_lgn,'".$kfr_tmp."') AS dom_login,
                   AES_DECRYPT(tbl_pass_keep.mail_lgn,'".$kfr_tmp."') AS mail_login
                   FROM `tbl_pass_keep`
                   WHERE `pas_id` = '".$sost4['pas_id']."'";
                    $result_iskh_p = mysql_query($query_iskh_p);
                      if(!$result_iskh_p) puterror2($TEXT['error-tbl53']);
                        $result_iskh_p2 = mysql_fetch_array($result_iskh_p,MYSQL_ASSOC);
                        $login_usr = $result_iskh_p2['dom_login'];
                        $login_mail = $result_iskh_p2['mail_login'];

                        $name_tmp=substr($sost4['fio_i'], 0,2);
                        $otch_tmp=substr($sost4['fio_o'], 0,2);
                        $inits1 = strtoupper($name_tmp).".";
                        $inits2 = strtoupper($otch_tmp).".";

                        if($_POST['onepass'] == "on") $mailbase = strtolower($result_iskh_p2['mail_login']);
                           else $mailbase = strtolower($result_iskh_p2['dom_login']);
                        if($mailbase == "") $mailbase = strtolower($result_iskh_p2['dom_login']);
                           else $mailbase = $mailbase;

               // Open Phone book record
                $image = "";
                $smallimage = "";
                $visible = "show";
                $subscribe = "unscribe";

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

              //*************************************
              $ip = $_SERVER['REMOTE_ADDR'];
              $doing = $TEXT['log-usr1'];
              $what = $sost4['fio_f']." ".$sost4['fio_i']." ".$sost4['fio_o'];
              $who = $result2['fullname'];
              //*************************************
              $query = "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', '".$sost4['fio_f']."', '".$sost4['fio_i']."', '".$sost4['fio_o']."', '".$_POST['position']."', '".$_POST['dom_id']."', '$mailbase', '', '', '', '".$_POST['dol_id']."', '".$_POST['otd_id']."', '$otd_pos', '".$_POST['upr_id']."', '$upr_pos', '".$_POST['org_id']."', '$org_pos', '-', '".$_POST['house_id']."', '".$_POST['str_id']."', '".$_POST['city_id']."', '', '$subscribe', '$visible') ";

            if(mysql_query($query))
            {
             $query_last_id = mysql_query("SELECT LAST_INSERT_ID() AS last_usr");
             $result_last_id = mysql_fetch_array($query_last_id,MYSQL_ASSOC);
             $last_usr = $result_last_id['last_usr'];
             $query_ins_last_id = mysql_query("UPDATE `tbl_pass_keep` SET usr_id = '".$last_usr."' WHERE pas_id='".$id."'");

            if($result_srv_set['repl'] == 1 && $_POST['org_id'] == $result_srv_set['rep_org_id'])
            {
                $exp_path = "../replica/main-organization";
                if(is_file($exp_path))
                {
                $file = fopen($exp_path,"a");
                if($result_srv_set['repl_mail'] == "yes") $exp_param = $result_organizaciya2['organizaciya'].";---;---;---;---;---;;".$sost4['fio_f'].";".$sost4['fio_i'].";".$sost4['fio_o'].";---;;;;".$_POST['mail'].";".$result_domain2['domain'].";".$_POST['position'].";add;-;-;-;-;-;-;-;-;-;-;-;-;-;-;-;-;-\r\n";
                else $exp_param = $result_organizaciya2['organizaciya'].";".$result_upravlenie2['upravlenie'].";".$result_otdel2['otdel'].";".$result_city2['city'].";".$result_street2['street'].";".$result_house2['house'].";;".$sost4['fio_f'].";".$sost4['fio_i'].";".$sost4['fio_o'].";".$result_dolzh2['dolzhnost'].";;;;".$_POST['mail'].";".$result_domain2['domain'].";".$_POST['position'].";add;-;-;-;-;-;-;-;-;-;-;-;-;-;-;-;-;-\r\n";
                    fwrite($file, $exp_param, strlen($exp_param));
                    fclose($file);
                }
                else
                {
                $file = fopen($exp_path,"a");
                $exp_head = "организация;управление;отдел;город;улица;дом;комната;Фамилия;Имя;Отчество;должность;город.тел;моб.тел;внутр.тел;почта;домен;позиция пользователя;действие;Ст.организация;Ст.управление;Ст.отдел;Ст.город;Ст.улица;Ст.дом;Ст.комната;Ст.Фамилия;Ст.Имя;Ст.Отчество;Ст.должность;Ст.город.тел;Ст.моб.тел;Ст.внутр.тел;Ст.почта;Ст.домен;Ст.позиция пользователя\r\n";
                fwrite($file, $exp_head, strlen($exp_head));
                if($result_srv_set['repl_mail'] == "yes") $exp_param = $result_organizaciya2['organizaciya'].";---;---;---;---;---;;".$sost4['fio_f'].";".$sost4['fio_i'].";".$sost4['fio_o'].";---;;;;".$_POST['mail'].";".$result_domain2['domain'].";".$_POST['position'].";add;-;-;-;-;-;-;-;-;-;-;-;-;-;-;-;-;-\r\n";
                 else $exp_param = $result_organizaciya2['organizaciya'].";".$result_upravlenie2['upravlenie'].";".$result_otdel2['otdel'].";".$result_city2['city'].";".$result_street2['street'].";".$result_house2['house'].";;".$sost4['fio_f'].";".$sost4['fio_i'].";".$sost4['fio_o'].";".$result_dolzh2['dolzhnost'].";;;;".$_POST['mail'].";".$result_domain2['domain'].";".$_POST['position'].";add;-;-;-;-;-;-;-;-;-;-;-;-;-;-;-;-;-\r\n";
                fwrite($file, $exp_param, strlen($exp_param));
                fclose($file);
                chmod($exp_path,0644);
                }
            }
            $query2 = mysql_query("INSERT INTO tbl_logs ( `log_id` , `data` , `ip` , `who` , `doing` , `what` ) VALUES ( NULL , NOW() , '$ip' , '$who' , '$doing' , '$what')");
              // Close Phone book record

              // Open LDAP record

              if($ldp == 1) {
                if($result_otdel2['otdel'] == "") $res_otd = $result_upravlenie2['upravlenie'];
                  else $res_otd = $result_otdel2['otdel'];
                $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=".$sost4['fio_f']." ".$sost4['fio_i']." ".$sost4['fio_o'].",".$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'] = $sost4['fio_f']." ".$sost4['fio_i']." ".$sost4['fio_o']; // полное имя, равно отображаемому имени
                $ldap_mass['givenName'] = $sost4['fio_i']." ".$sost4['fio_o']; //имя
                $ldap_mass['sn'] = $sost4['fio_f']; // фамилия
                $ldap_mass['displayName'] = $sost4['fio_f']." ".$sost4['fio_i']." ".$sost4['fio_o']; //отображаемое имя
                $ldap_mass['uid'] = $mailbase; //уникальное имя, я исп чать мыльника
                $ldap_mass['initials'] = $inits1.$inits2; // инициалы
                $ldap_mass['postalAddress'] = $cit."".$str."".$hou."".$rum; // почтовый адрес
                $ldap_mass['o'] = $result_organizaciya2['organizaciya']; // организация
                $ldap_mass['l'] = $result_city2['city']; // город
                $ldap_mass['mail'] = $mailbase."@".$result_domain2['domain']; // почта
                $ldap_mass['title'] = $result_dolzh2['dolzhnost']; // должность
                $ldap_mass['ou'] = $res_otd; // отдел
                $ldap_mass['telephoneNumber'] = $res_phone." ".$res_phone_int; // телефон
                $ldap_mass['mobile'] = $res_phone_mob; // телефон мобильный
                $ldap_mass['street'] = $result_street2['street']; // улица
                $ldap_mass['roomNumber'] = $res_room; // номер комнаты
                $ldap_mass['physicalDeliveryOfficeName'] = $res_room; // номер комнаты

                ldap_add($ds, $dn, $ldap_mass);
                if(ldap_error($ds) == "Already exists")
                 {
                 //*************************************
                 $what_tmp = $TEXT['global-est']."<br />".$dn."<br />".$TEXT['ldap-export3'];
                 //*************************************
                $query3 = mysql_query("INSERT INTO tbl_logs ( `log_id` , `data` , `ip` , `who` , `doing` , `what` ) VALUES ( NULL , NOW() , '".$_SERVER['REMOTE_ADDR']."' , '".$result2['fullname']."' , '".$TEXT['menu-btn37']."' , '".$what_tmp."')");
                }
                ldap_unbind($ds);
                ldap_close($ds);
              }
              // Close LDAP record
            } else  puterror2(mysql_error());

            }
         }
     }
   }
// added 07.15.2014 //
  }
 }
////
  //*************************************
  $ip = $_SERVER['REMOTE_ADDR'];
  $doing = $TEXT['pass-log'];
  $what = $TEXT['pass-log9'].substr($result_strukt_name,0,-2);
  $who = $result2['fullname'];
  //*************************************
  $query2 = "INSERT INTO tbl_logs ( `log_id` , `data` , `ip` , `who` , `doing` , `what` ) VALUES ( NULL , NOW() , '$ip' , '$who' , '$doing' , '$what')";
    if(mysql_query($query2))
    {
        echo "<html><body>
                  <meta HTTP-EQUIV='Refresh' CONTENT='0; URL=pass_keep.php?pas_str_id=".$_POST['pas_str_id']."'  />
                  </body></html>";
    }
?>
</body>
</html>
