<?
function XML_import(){ if (!is_object($GLOBALS['XML_import'])) $GLOBALS['XML_import']=new i_XML_import();return($GLOBALS['XML_import']);}
include_once(_DIR_EXT.'/esmo_gateway/i_personal_import.php') ;
class i_XML_import extends i_personal_import
{
  var $db_debug=0;
  var $import_begin_time=0;
  var $XLS_fname=0;
  var $read_only=0;
  var $full_update=0;
  var $XML_content='' ;

  var $arr_SOURCE_fields=array() ;
  var $arr_SOURCE_DB_fields=array() ;
  var $arr_XLS_row_names=array() ;
  var $read_block_stats=array() ;

  var $source_fnames=array('org_name'=>array('code'=>'Org'),
                           'otdel_name'=>array('code'=>'Structure'),
                           'work_name'=>array('code'=>'Working'),
                           'uid_fl'=>array('code'=>'uid'),
                           'uid_so'=>array('code'=>'uid'),
                           'fio'=>array('code'=>'Name'),
                           'vz'=>array('code'=>'Vid_zanyatosti'),
                           'pol'=>array('code'=>'Pol'),
                           'dr'=>array('code'=>'Dr','is_data'=>1),
                           'du'=>array('code'=>'Data_uvolneniya','is_data'=>1),

          ) ;

  var $XLS_data_fields=array('Дата рождения','Дата увольнения') ;

  function import_persons($options=array())
     {   ob_start() ; $t1=fixed_time() ;

         $this->read_only=$options['read_only'] ;
         $this->full_update=$options['full_update'] ;

         $this->connect_SOURCE($options['local_fname']) ;

         if (strlen($this->XML_content))
         {
             $this->parse_source_headers() ;
             echo 'SOAP_XML_count_rows='.$this->SOAP_XML_count_rows.'<br>' ;
             if ($this->SOAP_XML_count_rows>0)
             {   $this->create_temp_tables() ;
                 $this->parse_SOURCE_to_DB() ;

                 if ($this->full_update) $this->personal_update_levels_parents() ;
                 if ($this->full_update) $this->workers_update_levels_parents() ;

                 $this->sync_TEMP_DB_ESMO() ;
                 $this->sync_workings_persons() ;
             }
         }

         $text=ob_get_clean() ;  $t2=fixed_time($t1) ;
         echo $text ;
         $action=($options['local_fname'])? 'Загрузка XML из файла '.basename($options['local_fname']):'Загрузка данных XML c узла '.SOAP_import()->SOAP_node ;
         $edit_mode=($this->full_update)? 'срез':'изменения' ;
         LOGS()->reg_log('Импорт сотрудников из 1С ЗУП '.$edit_mode,$action,array('save_to_file'=>$text,'time_exec'=>$t2));
     }

  // подключается к источнику данных и сохраняет XML контент в  XML_content
  function connect_SOURCE($fname="")
  {   if ($this->read_only) {?><div class="alert">Режим только чтение</div><?}
      if ($fname) $this->XML_content=file_get_contents($fname) ;
      else        $this->XML_content = file_get_contents("php://input");

      $this->XLS_fname=$fname ;
      $this->defined_vars() ;
      define('MAIN_WORK_NAME','Основное место работы') ;
      define('FIO',$this->source_fnames['fio']['code']) ;
      set_time_limit(0) ;
  }

  function defined_vars()
  {   define('ORG_NAME',$this->source_fnames['org_name']['code']) ;
      define('OTDEL_NAME',$this->source_fnames['otdel_name']['code']) ;
      define('WORK_NAME',$this->source_fnames['work_name']['code']) ;
      define('UID_FL',$this->source_fnames['uid_fl']['code']) ;
      define('UID_SO',$this->source_fnames['uid_so']['code']) ;
      define('VZ',$this->source_fnames['vz']['code']) ;
      define('DR',$this->source_fnames['dr']['code']) ;
      define('DU',$this->source_fnames['du']['code']) ;
      define('POL',$this->source_fnames['pol']['code']) ;
  }


    function parse_source_headers()
    {   $XML=new SimpleXMLElement($this->XML_content) ;
        //$this->arr_SOURCE_fields - массив с именами и размером полей


        if (is_object($XML))
            {  foreach($XML->Person as $item) $recs2[]=(array)$item ; //damp_array($recs2)  ;
               $this->SOAP_XML_count_rows=sizeof($recs2) ;
               $arr=array() ;
               if (sizeof($recs2)) foreach($recs2 as $rec)
                {   //damp_array($rec) ;
                    $arr['pl'][(string)$rec['uid']]++ ;
                    $arr['fl'][(string)$rec['uid']]++ ;
                    $arr['org'][(string)$rec['Org']]++ ;
                    $arr['otdel'][(string)$rec['Structure']]++ ;
                    $arr['working'][(string)$rec['Working']]++ ;
                    // собираем данные по полям XML и размеру данных
                    if (sizeof($rec)) foreach($rec as $fname=>$fvalue)
                    {   $len=strlen($fvalue) ;
                        if (!isset($this->arr_SOURCE_fields[$fname])) $this->arr_SOURCE_fields[$fname]=$len ;
                        else if ($len>$this->arr_SOURCE_fields[$fname])  $this->arr_SOURCE_fields[$fname]=$len ;
                    }
                    $this->arr_SOURCE_fields['Vid_zanyatosti']=6 ;
                }
            }

         if (sizeof($this->arr_SOURCE_fields)) foreach($this->arr_SOURCE_fields as $fname=>$len) $this->arr_SOURCE_DB_fields[$fname]=$this->check_db_fields_names($fname) ;
        //damp_array($recs2,1,-1) ;
        // анализируем полученный массив
        //damp_array($arr,1,-1) ;

        $this->read_block_stats=array( 'fname'=>basename($this->XLS_fname),
                                       'Организации'=>sizeof($arr['org']),
                                       'Подразделения'=>sizeof($arr['otdel']),
                                       'Должности'=>sizeof($arr['working']),
                                       'ФизическиеЛица'=>sizeof($arr['fl']),
                                       'СотрудникиОрганизаций'=>sizeof($arr['pl'])
                                       ) ;

        //damp_array($this->read_block_stats) ;
        //damp_array($this->arr_SOURCE_fields) ;
        //damp_array($this->arr_SOURCE_DB_fields) ;

    }


    // пересим данные из XML в таблицу soap_xml_block в формате "как есть"
     function parse_SOURCE_to_DB()
     { ?><strong>Переносим данные в таблицу источника</strong><br><?
       $XML=new SimpleXMLElement($this->XML_content) ;
       $this->import_begin_time=time() ;
       if (is_object($XML))
       {
          $j=0 ; $arr=array() ; $i=0 ; $table_fields=implode(',',$this->arr_SOURCE_DB_fields) ;
          foreach($XML->Person as $item)
          {   $rec=(array)$item ;
              $fields=array() ;
              // данные необходимо подготовить для вставки в том же самом порядке, как поля были объявлены в таблице
              if (sizeof($this->arr_SOURCE_fields)) foreach($this->arr_SOURCE_fields as $fname=>$len) $fields[]='"'.addslashes($rec[$fname]).'"' ;
              $arr[]='('.implode(',',$fields).')' ;
              $j++ ; $i++ ;
              if ($j==$GLOBALS['LS_magnit_insert_rows_count'])
              {  $this->insert_arr_to_db($table_fields,$arr) ;
                 $j=0 ; $arr=array() ;
                 FILE_LOG()->append('parse_SOURCE_to_DB: insert_arr_to_db => +'.$GLOBALS['LS_magnit_insert_rows_count']) ;
              }
          }
          if ($j) $this->insert_arr_to_db($table_fields,$arr) ;
          echo 'Cохранено <strong>'.$i.'</strong> строк</br>' ;
           FILE_LOG()->append('parse_SOURCE_to_DB: save '.$i.' rows') ;

          // имеем две таблицы - одна ФЛ, вторая - сотрудники
          /*
          $count=execSQL_update('update '.$this->table_fz.' set obj_name=CONCAT(Familiya," ",Imya," ",Otchestvo)') ;
          $this->flog_append('update '.$this->table_fz.':obj_name -> '.$count.' rows') ;

          $count=execSQL_update('update '.$this->table_fz.' set dr=DATE_FORMAT('.DR.',"%d.%m.%Y");') ;
          $this->flog_append('update '.$this->table_fz.':dr -> '.$count.' rows') ;

          $count=execSQL_update('update '.$this->table_fz.' set poll=0 where Pol!="Женский"') ;
          $this->flog_append('update '.$this->table_fz.':pol "man" -> '.$count.' rows') ;

          $count=execSQL_update('update '.$this->table_fz.' set poll=1 where Pol="Женский"') ;
          $this->flog_append('update '.$this->table_fz.':pol "woman" -> '.$count.' rows') ;

          $count=execSQL_update('update '.$this->table_so.' set obj_name=CONCAT(Familiya," ",Imya," ",Otchestvo)') ;
          $this->flog_append('update '.$this->table_so.':obj_name -> '.$count.' rows') ;

          $count=execSQL_update('update '.$this->table_so.' set fired_data=UNIX_TIMESTAMP('.DU.') where '.DU.'!=""') ;
          $this->flog_append('update '.$this->table_so.':fired_data -> '.$count.' rows') ;

          $count=execSQL_update('update '.$this->table_so.' set is_main=1 where '.VZ.'="'.MAIN_WORK_NAME.'"') ;
          $this->flog_append('update '.$this->table_so.':is_main -> '.$count.' rows') ;

          $count=execSQL_update('update '.$this->table_so.' set is_second=1 where '.VZ.'!="'.MAIN_WORK_NAME.'"') ;
          $this->flog_append('update '.$this->table_so.':is_second -> '.$count.' rows') ;

          // фиксируем в базе номер последнего принятого блока
          */

       }
       else echo 'Not valid XML structure' ;

     }
}

?>