<?
/* внимание!!!
   в отчетах постепенно заменить
   <input type="hidden" name="filter_dir" value="<?echo _CUR_REPORT_DIR?>">
   на
   <input type="hidden" name="filter_dir" value="<?echo $this->url_report?>">
*/

include_once(_DIR_TO_ENGINE.'/c_system.php') ;
function REPORT() { if (!isset($GLOBALS['def_report_obj'])) $GLOBALS['def_report_obj']=new c_report ; return($GLOBALS['def_report_obj']); } ;


class c_report extends c_system
{ public $editing=false ;

  public $default_filter=array() ;
  public $filter=array() ;
  public $report_UID='' ;
  public $report_code='' ;
  public $report_class='' ;
  public $report_script='' ;
  public $usl_items ;
  public $cnt_items ;
  public $first_obj=1 ;
  public $result_params=array() ;
  public $report_info=array() ;
  public $get_cnt_items_time=0 ;
  public $get_items_time=0 ;
  public $report_paginator=1 ;
  public $no_view_title=0 ;
  public $view_panel_info=1 ;
  public $show_sign_stamp=0 ;
  public $sign_before_print=0 ;

  public $use_datepicker=1 ;
  public $use_jwplayer=0 ;
  public $use_fusioncharts=0 ;


    public $PDF_master='HTML2PDF' ;
//    public $PDF_master='TCPDF' ;
    public $PDF_page_orientation='L' ; // L P
    public $PDF_page_format='A4' ;
    public $PDF_page_keepmargins=false ;
    public $PDF_page_tocpage=false ;
    public $PDF_show_header=true ;
    public $is_signed=false ;
    public $db_report_code='' ; // Имя директории в таблице документов для сохранения докумена. Если не задать, будет использован код отчета. Необходимо задать, если требуется чтобы несколько отчетов имели общую нумерацию
    public $doc_id ;
    public $doc_code ;

    var $CSV_export_row_to_req=0 ;  // =0 - используем значение из  LS_CSV_export_row_count [def 10000]
    var $use_csv_easy=0 ;  // =0 - использовать простой конвертор в CSV, не фоновый

  // поля для работы с Excel
  public $file_name ;
  public $pExcel ;
  public $aSheet ;
  public $style ;
  public $title ;
  public $first_col_char=65 ; // A
  public $first_row=1 ;
  public $cur_col=65 ; // A
  public $cur_row=1 ;
  public $view_h1_title=true ;
  public $view_by_space_filter=0 ;
  public $url_report='' ;
  public $show_on_page_peports=1 ;
  public $rec_doc=array() ;
  public $content=array() ;
  public $copies=1 ;

  public $form ;
  public $uid ;
  public $is_local_verson ;
  var $arr_order=array(0=>'Обратная',1=>'Прямая') ;

  var $join_table ;
  var $join_usl ;
  var $left_join ;
  var $unions ;
  var $report_count_rows_all=0 ;

  function __construct($create_options=array())
  { $this->report_class=get_class($this) ;
    if (!$this->doc_code) $this->doc_code=str_replace('doc_','',$this->report_class) ;
    $this->report_code=$this->doc_code ;
    //echo '$this->doc_code='.$this->doc_code.'<br>' ;

    // в режиме инсталятора далее не идем
    if (ESMO_STATUS=='SETUP_FIRST' or ESMO_STATUS=='SETUP_SECOND') return ;

    $create_options['no_init']=1 ; // init будет вызвано позднее самостоятельно
    parent::__construct($create_options) ;
    if ($create_options['default_filter']) $this->default_filter=$create_options['default_filter'] ;
    if ($create_options['filter']) $this->filter=$create_options['filter'] ;
    else if (defined('_CUR_FILTER') and _CUR_FILTER!="")           $this->filter=ENGINE()->parse_url(_CUR_FILTER);
    if (_sizeof($this->default_filter))
    { $this->filter=array_merge($this->filter,$this->default_filter) ;
      foreach($this->default_filter as $name=>$value)  if (!isset($this->$name)) $this->$name=$value ; // проставляем значения типа personal_id=121
    }
    //damp_array($this->filter) ;
    // пока определяем report_code через URL, но в принципе должно задаваться в классе
    // проверить переменные $url_report
    //$this->report_code=(defined('_CUR_FILTER') and _CUR_FILTER!="")? _CUR_FILTER:'';
    //echo '$this->report_code='.$this->report_code.'<br>' ;

    //$this->report_class=get_class($this) ;
    if (!$this->report_script and isset(ENGINE()->reports_list[$this->report_code])) $this->report_script=hide_server_dir(_DIR_EXT.'/'.ENGINE()->reports_list[$this->report_code]['script_dir']) ;
    $this->url_report=(defined('_CUR_REPORT') and defined('_CUR_CAB_DIR') and _CUR_REPORT!="")? _CUR_REPORT_DIR:_CUR_CAB_DIR;

    if ($this->filter['doc_id']) $this->rec_doc=DOCS()->get_doc_by_id($this->filter['doc_id']) ;
    if ($this->filter['data_to'])
    {  $arr=explode(' ',trim($this->filter['data_to'])) ;
       if (!isset($arr[1])) $arr[1]='23:59:59' ;
       $this->filter['data_to']=$arr[0].' '.$arr[1] ;
    }

    if ($this->rec_doc['pkey']) $this->content=unserialize($this->rec_doc['content']) ;
    if (ESMO_STATUS!='SETUP_FIRST' and ESMO_STATUS!='SETUP_SECOND' and !$create_options['no_init_after_create'])$this->init($create_options) ;

    $this->report_UID=ENGINE()->generate_UID() ;

    // создаем экземляр формы на основе используемого дизайна
    $this->uid=ENGINE()->generate_UID() ;
    $this->form=new i_form(array('post_array_name'=>'filter','filter'=>$this->filter,'page'=>_CUR_PAGE(),'report'=>$this));
    //damp_array($this->form);
  }


  function init($create_options=array()) {}
  function setting() {}
  function upload_files() {}


    /**************************************************************************************************************************************/
    //
    // РАБОТА с URL, разбор параметров
    //
    /**************************************************************************************************************************************/

   // prepare_url by POST
   function prepare_url($filter,$options=array())
   {   $res_url=ENGINE()->prepare_url($filter,$options) ;
       return($res_url) ;
   }

  function prepare_url_by_filter($filter,$options=array())
   {   $res_url=ENGINE()->prepare_url_by_filter($filter,$options) ;
       return($res_url) ;
   }

   // меняем местами ключи со значениями в массивах фильтра
   function filter_array_flip($filter)
      { $res=ENGINE()->filter_array_flip($filter) ;
        return($res) ;
      }

   // меняем местами ключи со значениями в массивах фильтра
   function clear_space_value($filter)
      { $res=ENGINE()->clear_space_value($filter) ;
        return($res) ;
      }

   function get_filter_to_params($params,$options=array())
   { if (!$options['url_report']) $options['url_report']=$this->url_report  ;
     $res=ENGINE()->get_filter_to_params($this->filter,$params,$options) ;
     return($res) ;
   }

   function get_time_range_by_filter_to_cur_day()
   { $res=ENGINE()->get_time_range_by_filter_to_cur_day($this->filter) ;
     return($res) ;
   }


  function view($options=array())
  {   switch($this->filter['view'])
       { case 'prePDF': $this->prepare_PDF($options) ; break ;
         case 'PDF': $this->view_as_PDF($options) ; break ;
         case 'XLS': $this->view_as_XLS($options) ; break ;
         case 'CSV': $this->view_as_CSV($options) ; break ;
        case 'JSON': $this->view_as_JSON($options) ; break ;
         case 'print': $this->prepare_to_print($options) ; break ;
         default:    $this->view_as_HTML($options) ;
       }
  }

 function get_arr_info_filters()
 {   $info=array() ;
     if ($this->filter['client_id'])                       $info['клиент']=ACCOUNTS()->get_member_name_by_id($this->filter['client_id']) ;
     if ($this->filter['client_ids'])
     {   $arr=array() ;
         $recs_account=ACCOUNTS()->get_members_by_ids($this->filter['client_ids']) ;
         if (_sizeof($recs_account)) foreach($recs_account as $rec_account) $arr[]=$rec_account['obj_name'] ;
         $info['клиенты']=implode(', ',$arr) ;
     }

     if ($this->filter['group_id'])                        $info[$GLOBALS['LS_person_group_title'].':']=ACCOUNTS()->get_group_name($this->filter['group_id'])  ;
     if ($this->filter['org_group_id'])                    $info['Группа приписки:']=ACCOUNTS()->get_group_name($this->filter['org_group_id'])  ;
     if ($this->filter['dep_id'])                          $info['Подразделение']=PERSONAL()->get_full_dep_name_by_dep_id($this->filter['dep_id'])  ;
     if ($this->filter['dep_id2'])                          $info['Подразделение']=PERSONAL()->get_full_dep_name_by_dep_id($this->filter['dep_id2'])  ;
     if ($this->filter['dep_ids'])                         $info['Организация']=PERSONAL()->get_org_names_by_ids(array_keys($this->filter['dep_ids']))  ;
     if ($this->filter['org_id'])                          $info['Организация']=PERSONAL()->get_name_by_id($this->filter['org_id'])  ;
     if ($this->filter['org_ids'])                         $info['Организации']=PERSONAL()->get_org_names_by_ids(array_keys($this->filter['org_ids']))  ;
     //if ($this->filter['otdel_id'])                        $info['отдел']=PERSONAL()->get_name_by_id($this->filter['otdel_id']) ;
     // временно, потом найти где используется, переделать под otdel_ids и убрать отсюда
     if ($this->filter['otdel_id'])
        {   $arr=explode(',',$this->filter['otdel_id']) ;
            $arr2=array() ;
            foreach($arr as $otdel_id) $arr2[]=PERSONAL()->get_name_by_id($otdel_id) ;
            $info['отдел']=implode(', ',$arr2);
        }
     if ($this->filter['otdel_ids'])                       $info['Позразделения']=PERSONAL()->get_org_names_by_ids(array_keys($this->filter['otdel_ids']))  ;
     if ($this->filter['name'])                            $info['ФИО']='"'.$this->filter['name'].'"' ;
     if ($this->filter['personal_name'])                   $info['Сотрудник']='"'.$this->filter['personal_name'].'"' ;
     if ($this->filter['tk'])                              $info['Тип контроля']=$_SESSION['ARR_mo_tk_type'][$this->filter['tk']-1]  ;

     if ($this->filter['working'])                        $info['должность']=_IL('IL_works')->recs[$this->filter['working']]['obj_name'];
     if ($this->filter['working_id'])                     $info['должность']=_IL('IL_works')->recs[$this->filter['working_id']]['obj_name'];
     if (_sizeof($this->filter['working_ids']))
     {  $arr=array() ;
        foreach($this->filter['working_ids'] as $work_id=>$flag)  $arr[]=_IL('IL_works')->recs[$work_id]['obj_name'] ;
        $info['Должность']=implode(',',$arr) ;
     }

   if ($this->filter['job_data_from'])                        $info['Дата приема на работу, от']=$this->filter['job_data_from'];
   if ($this->filter['job_data_to'])                          $info['Дата приема на работу, до']=$this->filter['job_data_to'];


    if ($this->filter['age_from'])                        $info['возраст, от']=$this->filter['age_from'];
    if ($this->filter['age_to'])                          $info['возраст, до']=$this->filter['age_to'];
    if (is_array($this->filter['group_medic']) and _sizeof($this->filter['group_medic']))
    { $arr_group_name=array() ;
      foreach($this->filter['group_medic'] as $group_id=>$flag) $arr_group_name[]=_IL('IL_group_medic')->recs[$group_id]['obj_name'] ;
      if (_sizeof($arr_group_name)) $info['группа по болезни']=implode(',',$arr_group_name);
    } else if ($this->filter['group_medic']) $info['группа по болезни']=_IL('IL_group_medic')->recs[$this->filter['group_medic']]['obj_name'] ;

    if (_sizeof($this->filter['group_pers']))
    { $arr_group_name=array() ;
      foreach($this->filter['group_pers'] as $group_id=>$flag) $arr_group_name[]=_IL('IL_groups')->recs[$group_id]['obj_name'] ;
      if (_sizeof($arr_group_name)) $info['группа сотрудников']=implode(',',$arr_group_name);
    }

    if ($this->filter['uid'])                            $info['UID сотрудника']='"'.$this->filter['uid'].'"' ;
    if ($this->filter['propusk'])                        $info['номер пропуска']='"'.$this->filter['propusk'].'"' ;

    if ($this->filter['month'])                            $info['месяц']=get_month_year($this->filter['month'],'month year') ;
    if ($this->filter['data_from'])                        $info['c']=$this->filter['data_from'] ;
    if ($this->filter['data_to'])                          $info['по']=$this->filter['data_to'] ;
    if ($this->filter['time_from'])                        $info['c']=date('d.m.Y',$this->filter['time_from']) ;
    if ($this->filter['time_to'])                          $info['по']=date('d.m.Y',$this->filter['time_to']) ;

    return($info) ;

 }

 function panel_info_filter()
 { $_str=array() ; $title='' ;
   $info=$this->get_arr_info_filters() ;
   if (_sizeof($info)) foreach($info as $title=>$value) $_str[]=$title.': <strong>'.$value.'</strong>' ;
   if (_sizeof($_str)) $title='<div class=center>'.implode(' ',$_str).'</div>' ;
   return $title ;
   }

 // вызывает метод view_as_HTML,view_as_PDF или view_as_XLS в зависимости от типа текущего документа
  function print_template($list_recs,$method_name,$options=array())
     {
       if (method_exists($this,$method_name)) $this->$method_name($list_recs,$options) ;
     }

    function view_as_HTML($options=array())
    { if (!$this->no_view_title){?><h2 class="center"><?echo $this->title?></h2><?}
      if ($this->view_panel_info) echo '<div id=panel_info_filter>'.$this->panel_info_filter().'</div>' ;
      return($this->HTML_report_body($options)) ;

    }

    // основная функция в которорой будет фрмироваться тело отчета
    function HTML_report_body($options=array())
    { $options['panel_select_pages']=$this->report_paginator ;
      $options['panel_diapazon_page']=$this->report_paginator ;
      //$options['debug']=0 ;
      $template_name=($options['template_name'])? $options['template_name']:'print_template_HTML' ;
      $cnt=$this->show_list_items('',$template_name,$options) ;
      return($cnt) ;
    }

    // показ элементов раздела по указанному шаблону
     // obj 	- объект дерева, будут выбраны все дочерние элементы, если передана опция 'show_items_from_child' будут показываны и все дочерние элементы всех дочерних подразделов
     //		- либо код объекта дерева
     //		- либо условие выборки, например parent=3
     function show_list_items($_params,$func_name,$options=array())
     { $debug_text='' ;
       if (is_array($_params)) { $list_recs=$_params ; $count_obj=_sizeof($list_recs) ; } // если $_params - массив, то выборку не делаем
       else
       {   ob_start() ;
           //if (MEMBER()->info['debug_sql']) $options['debug']=1 ;
           // при поиске условия выборки объектов формируются в отдельной функции
           // так как там для полнотекстового поиска идет свой отдельный запрос
           $usl_items=$this->create_usl_select_obj($_params,$options) ;// echo '$usl_items='.$usl_items.'<br>' ;
           $this->usl_items=$usl_items ;
           // если в $this->cur_sort_type и $this->cur_sort_mode задан тип и направление сортировки по применяем его
           if ($this->cur_sort_type and !$options['order_by'] and !$options['no_order'])
           { $options['order_by']=$this->pages_info['sort_type'][$this->cur_sort_type]['order_by'] ;
             if ($this->cur_sort_mode)  $options['order_by'].=' '.$this->pages_info['sort_mode'][$this->cur_sort_mode] ;
           }

           //damp_array($this->pages_info) ;
           // новый способ получения записей - позволяет ускорить выборку при получении записей в 6 раз при использовании rand()
           if ($options['get_pkeys_before_exec'] or $options['order_by']=='rand()')
           { $tkey=($options['only_clss'])? _DOT($this->tkey)->list_clss[$options['only_clss']]:$this->tkey_items ;
             list($count_obj,$pkeys)=get_pkeys($tkey,$usl_items,$options) ;
             if ($pkeys) $usl_items='pkey in ('.$pkeys.')' ;
             $options['count']='' ;
             $options['limit']='' ;
             $options['order_by']='' ;
           }
           // иначе используетм стандартный способ получения количества записей
           else if (!$options['count'] and !$options['limit']) // добавлено 10.06.12 - если задано число позиций для показа, не делать запрос в базу на обзее количество
           {   $t1=fixed_time() ;
               $count_obj=$this->get_cnt_items($usl_items,$options) ;  // по умолчанию - get_cnt_items
               $this->report_count_rows_all=$count_obj ;
               if ($options['debug']) echo 'Получено всего записей по данному условию:'.$count_obj.'<br>';
               $this->get_cnt_items_time=round(fixed_time($t1),5) ;
           } else $count_obj=1 ;

           $cur_page=($options['cur_page'])? $options['cur_page']:_CUR_PAGE_NUMBER ; //$_GET['page'] ;
           if (!$options['count'] and !$options['limit'] and $options['panel_select_pages']) $this->prepare_pages_info($count_obj,$cur_page,$this->cur_list_size,$options) ;
           if ($count_obj)
           { $t1=fixed_time() ;
             $list_recs=$this->get_items($usl_items,$options) ;
             $count_obj=_sizeof($list_recs) ;
             $this->get_items_time=round(fixed_time($t1),5) ;
           }
           //echo 'Получено записей:'._sizeof($list_recs).'<br>' ;
           $options['usl_all_obj']=$usl_items ;
           $options['count_recs']=(_sizeof($list_recs))? _sizeof($list_recs):0 ;


           if (_sizeof($list_recs)==1) 		$options['panel_select_usl']=0 ; // если всего один элемент - не показываем панель сортировки и размера страниц

           if ($options['count_page']==1)  $options['panel_select_pages']=0 ; // если всего одна страница - не показываем панель выбора страниц
           $debug_text=ob_get_clean() ;
           // внимание! отладку в таком виде выводить нельзя, если отчет выводиться в формате не HTML (JSON, XML)
           if (!MEMBER()->info['debug_sql'] and $debug_text) echo  '<div style="margin-bottom:10px;">'.$debug_text.'</div>' ;
       }


       if ($count_obj and !$options['no_any_panels'] and !$options['no_top_panels'])
       { 	// показываем верхнюю панель
           $options_panel_top=(_sizeof($this->pages_info['panel_top']['options']))? array_merge($options,$this->pages_info['panel_top']['options']):$options ;
           $options_panel_top['panel_position']='top' ;
           $this->panel_list_items_top_navigat($options_panel_top) ;
       }
       	// показываем список

       if ($options['debug_sort']) echo 'sort='.$options['order_by'].'<br>' ;

       if (!_sizeof($list_recs)) $list_recs=array() ;
       $this->print_template($list_recs,$func_name,$options) ; // $func_name($this,$list_recs,$options) ;

       if ($count_obj and !$options['no_any_panels'] and !$options['no_bottom_panels'])
       {	// показываем нижнюю панель
           $options_panel_bottom=(_sizeof($this->pages_info['panel_bottom']['options']))? array_merge($options,$this->pages_info['panel_bottom']['options']):$options ;
           $options_panel_bottom['panel_position']='bottom' ;
           $this->panel_list_items_bottom_navigat($options_panel_bottom) ;

       	//$this->panel_list_items_bottom_navigat($options) ;
       }
       if (!_sizeof($list_recs)) $count_obj=0 ;
       //$this->result_params=array('from'=>$from_pos+1,'to'=>$to_pos,'all'=>$count_obj,'','next_page'=>$next_page) ;

       if (MEMBER()->info['debug_sql'] and $debug_text) echo  '<div style="margin-top:40px;">'.$debug_text.'</div>' ;
       return($count_obj) ;
     }


    // верхняя панель навигации
    function panel_list_items_top_navigat(&$options=array())
    { //damp_array($options) ;
      if ($options['no_any_panel']) return ;
      if ((!$options['panel_select_pages'] or $options['panel_select_pages']=='bottom') and (!$options['panel_select_usl'] or $options['panel_select_usl']=='bottom') and !$options['panel_diapazon_page']) return ;
  	?><div id=panel_navigat class="top isCorner"><?
  	  if ($options['panel_select_pages'] and $options['panel_select_pages']!='bottom') 	 $this->panel_select_pages($options);
  	  if ($options['panel_select_usl'] and $options['panel_select_usl']!='bottom') 		 $this->panel_select_usl($options,1);
  	  if ($options['panel_diapazon_page'] and $options['panel_diapazon_page']!='bottom') $this->panel_diapazon_page($options) ;
  	?><div class=clear></div></div><?
    }

    // нижняя панель навигации
    function panel_list_items_bottom_navigat(&$options=array())
    { if ($options['no_any_panel']) return ;
      if ((!$options['panel_select_pages'] or $options['panel_select_pages']=='top') and (!$options['panel_select_usl'] or $options['panel_select_usl']=='top')/* and !$options['panel_diapazon_page']*/) return ;
  	  ?><div id=panel_navigat class=bottom><?
  	  if ($options['panel_select_pages'] and $options['panel_select_pages']!='top') 	$this->panel_select_pages($options);
  	  if ($options['panel_select_usl'] and $options['panel_select_usl']!='top') 		$this->panel_select_usl($options,1);
  	  if ($options['panel_diapazon_page'] and $options['panel_diapazon_page']!='top') 	$this->panel_diapazon_page($options) ;
  	  ?><div class=clear></div></div><?
    }

    function panel_select_pages(&$options=array()) // show_page_panel
    {  $text=array() ;
       $page_number_rasdel=$this->pages_info['options']['page_number_rasdel'] ;
       $cur_page=$options['current_page'] ;
       list($arr_pages,$to_prev,$to_next)=$this->prepare_panel_select_pages($options) ;
       //damp_array($arr_pages) ; damp_array($to_prev) ; damp_array($to_next) ;

       ?><div class=list_pages><?

       if (_sizeof($to_prev))  if ($to_prev['href']) echo '<a href="'.$to_prev['href'].'"><img src="'.$to_prev['img_src'].'" alt="" border="0"></a>' ;
                              else                  echo '<img src="'.$to_prev['img_src'].'" alt="" border="0">' ;

       if (_sizeof($arr_pages)) { foreach($arr_pages as $rec) $text[]=($rec['selected'])? "<span class=cur_page>".$rec['value'].'</span>':'<a href="'.$rec['href'].'" >'.$rec['value'].'</a>' ;
       						   echo implode(' ',$text) ;
       						 }
       if (_sizeof($to_next))  if ($to_next['href']) echo '<a href="'.$to_next['href'].'"><img src="'.$to_next['img_src'].'" alt="" border="0"></a>' ;
                              else                  echo '<img src="'.$to_next['img_src'].'" alt="" border="0">' ;

       ?></div><?
     }


   function panel_diapazon_page($options=array())
   {
      echo '<div class=panel_diapazon_page>'.$options['first_obj'].' ... '.$options['last_obj'].' из '.$options['count_obj'].'</div>' ;
      $this->first_obj=$options['first_obj'] ;
   }

   function prepare_SQL_left_join()
  {
     list($this->join_table,$this->join_usl)=PERSONALS_FILTER()->prepare_SQL_left_join($this->left_join,$this->unions) ;
     return([$this->join_table,$this->join_usl]) ;
  }


    function view_as_JSON($options=array())
    { if (ob_get_length()) ob_clean() ;
      header('Content-Type: application/json');
      $this->show_list_items('','print_template_JSON',$options) ;
      exit() ;
    }

    function print_template_JSON($list_recs,$options=array())
    { $result=array() ;
      if (_sizeof($list_recs)) foreach($list_recs as $rec)
        $result[]=array('propusk'=>$rec['propusk'],
                        'photo'=>img_clone($rec,'small'),
                        'fio'=>$rec['obj_name'],
                        'uid'=>$rec['uid'],
                        'status'=>$rec['enabled'],
                        'dr'=>$rec['dr'],
                        'age'=>$rec['age'],
                        'org_name'=>$rec['_org_name'],
                        'otdel_name'=>$rec['_otdel_name'],
                        'org_id'=>$rec['_org_id'],
                        'otdel_id'=>$rec['_otdel_id'],
                        'working'=>_IL('IL_works')->recs[$rec['working']]['obj_name']
                       ) ;
        $text_json_out=json_encode($result,JSON_PRETTY_PRINT) ;
        // возвращает ответ устройству
        echo $text_json_out ;

    }

    function print_tag_manual() {}



    function view_as_XML($options=array())
    { header("Content-type: text/xml;charset=UTF-8") ;
      $imp = new DOMImplementation; // Creates an instance of the DOMImplementation class
      $this->xml_doc = $imp->createDocument("",""); // Creates a DOMDocument instance
      $this->xml_doc->encoding = 'utf-8';
      $this->xml_doc->formatOutput = true;
      $this->xml = add_element($this->xml_doc,$this->xml_doc,'xml_doc','',array('date'=>date('Y-m-d H:i'))) ;
      $filters=add_element($this->xml_doc,$this->xml,'filters','',array()) ;
      if (_sizeof($this->filter)) foreach($this->filter as $name=>$value)
      { if (is_string($value)) add_element($this->xml_doc,$filters,$name,$value) ;
        // для корректного значений ототбражения мультивыбора в select
        if (is_array($value)) add_element($this->xml_doc,$filters,$name,implode(', ',array_keys($value))) ;

      }

      $this->show_list_items('','print_template_XML',$options) ;
      echo $this->xml_doc->saveXML() ;
    }

    function print_template_XML($list_recs,$options=array())
    { if (_sizeof($list_recs)) foreach($list_recs as $rec)
      {   $item=add_element($this->xml_doc,$this->xml,'item','',array('id'=>$rec['pkey'])) ;
          add_element($this->xml_doc,$item,'propusk',$rec['propusk']) ;
          add_element($this->xml_doc,$item,'photo',img_clone($rec,'small')) ;
          add_element($this->xml_doc,$item,'fio',$rec['obj_name']) ;
          add_element($this->xml_doc,$item,'uid',$rec['uid']) ;
          add_element($this->xml_doc,$item,'status',$rec['status']) ;
          add_element($this->xml_doc,$item,'dr',$rec['dr']) ;
          add_element($this->xml_doc,$item,'age',$rec['age']) ;
          add_element($this->xml_doc,$item,'org_name',$rec['org_name']) ;
          add_element($this->xml_doc,$item,'otdel_name',$rec['otdel_name']) ;
          add_element($this->xml_doc,$item,'org_id',$rec['org_id']) ;
          add_element($this->xml_doc,$item,'otdel_id',$rec['otdel_id']) ;
          add_element($this->xml_doc,$item,'working',$rec['working']) ;
      }
    }

    //  подготавливаем PDF файл. Вызывается при передаче параметра в URL [view=prePDF]
    function prepare_PDF($options=array())
    {
        $result=$this->prepare_and_convert_to_PDF($options);
        // формируем URL, на который будет переход после формирования документа
        $temp_filter=$this->filter ;
        $temp_filter['view']='PDF' ;
        $temp_filter['file_pdf']=$result['PDF_file_name'] ;
        $url_page_doc_view=_PATH_TO_SITE._CUR_REPORT_DIR.$this->prepare_url_by_filter($temp_filter) ;
        //echo '$url_page_doc_view='.$url_page_doc_view.'<br>' ;
        //damp_array($temp_filter) ;
        //echo $url_report.'<br>' ;
        $this->panel_view_pdf_convert($result['cmd_uid'],$url_page_doc_view) ;
    }

    function prepare_and_convert_to_PDF($options=array())
    {
        ob_start() ;
            $this->report_paginator=0 ;
            $this->view_as_HTML($options) ;
        $html=ob_get_clean() ;
        $file_name=($options['file_name'])? $options['file_name']:'report_'.md5(rand(1,100000)) ;
        $result=$this->HTML2PDF_create_PDF_file($file_name,$this->title,$html) ;
        return $result;
    }

    function panel_view_pdf_convert($cmd_uid,$url_page_doc_view='',$url_link_doc_view='')
    {  ?><div class="green">Ожидайте, идет формирование документа PDF</div><div id="log_view"></div><div class="center" id="buttons777"><button class="button cancel">Отмена</button></div>
          <script type="text/javascript">
         var panel_messages=$j('#log_view') ;
         $j('#log_view').everyTime(1000,'update_log_view',function()
         {  send_ajax_request({cmd:'report/update_log_view',cmd_uid:'<?echo $cmd_uid?>',url_page_doc_view:'<?echo $url_page_doc_view?>',url_link_doc_view:'<?echo $url_link_doc_view?>'}) ;
            //console.log(panel_messages[0].scrollHeight+' - '+panel_messages[0].clientHeight);
            // scroll animate небходимо переставить в функцию, которая выводит текст, сейчас анимация опазывает за выводом
            panel_messages.animate({scrollTop:panel_messages[0].scrollHeight-panel_messages[0].clientHeight+20});
         });
        </script>
        <style type="text/css">
          #log_view{height:400px;overflow-y: scroll;margin-bottom:15px;border-top:1px solid #dddddd;border-left:1px solid #dddddd;border-bottom:1px solid #dddddd; padding:10px 0 10px 10px;margin-top:20px;}
        </style>
        <?
    }

    function view_as_PDF($options=array())
    {// $doc_file_name=($this->filter['file_pdf'])? $this->filter['file_pfd']:$this->save_as_PDF($options) ;
     if ($this->filter['file_pdf']) $doc_file_name=$this->filter['file_pdf'] ;
           else
                 { $result=$this->save_as_PDF($options) ;
                         $doc_file_name=$result['PDF_file_name'] ;
                               }
      $doc_file_path=_TEMP_PATH.$doc_file_name;
      sleep(1) ; // надо поставить проверку наличия файла в цикле, для случаев когда файл генериться через html2pdf
      ?><iframe src="<?echo $doc_file_path?>"  style="width:100%; height:1300px;margin-top:20px;" frameborder="0"></iframe><?
    }

    function save_as_PDF($options=array())
    { $result=array() ;
      ob_start() ;
      $this->report_paginator=0 ;
      $this->view_as_HTML($options) ;
      $html=ob_get_clean() ;
      $file_name=($options['file_name'])? $options['file_name']:'report_'.md5(rand(1,100000)) ;
      switch($this->PDF_master)
      {  case 'HTML2PDF': $result=$this->HTML2PDF_create_PDF_file($file_name,$this->title,$html) ;
                          break ;
          case 'TCPDF':   $result['PDF_file_name']=$this->TCPDF_create_PDF_file($file_name,$this->title,$html,$this->panel_info_filter(),$options) ;
                          break ;

      }


	  $this->PDF_generate_result=$result ;
      return($result) ;
    }

/**************************************************************************************************************************************/
//
// XLS
//
/**************************************************************************************************************************************/

    function view_as_XLS($options=array())
    {  // подготовить страницу
        set_time_limit(0) ;
        $this->XLS_prepare_Sheet() ;
        $this->XLS_report_body(array('order'=>'pkey','panel_select_pages'=>0,'debug'=>0)) ;
        ob_clean() ; // чисти вывод
        if (!$options['save_to_temp_file'])
            $this->XLS_put() ;
        else {
            if ($options['save_to_temp_file']['file_name']) {
                $file_name=$options['save_to_temp_file']['file_name'] ;
            } else {
                $file_name='temp_'.md5(rand(1,100000)).'.xls' ;
            }
            $this->XLS_save(_DIR_TO_ROOT.'/temp/'.$file_name) ;
        }
        // регистрируем в журнале
        //LOGS()->reg_log('XLS export',$cmd,array('member_id'=>MEMBER()->id,'data'=>$_GET)) ;
    }

    // основная функция в которорой будет фрмироваться тело отчета
    function XLS_report_body($options=array())
    { $template_name=($options['template_name'])? $options['template_name']:'print_template_XLS' ;
      $this->show_list_items('',$template_name,$options) ;
    }

    function print_template_XLS($list_recs,$options=array()){}

/**************************************************************************************************************************************/
//
// CSV
//
/**************************************************************************************************************************************/

    public $file_csv ;
    function save_as_CSV($options=array())
    {  // подготовить страницу
        $fname='report_'.date('d_m_Y_H_i_s').'.csv' ;
        $this->file_csv = fopen(_DIR_TO_ROOT.'/temp/'.$fname, 'w');
        $this->CSV_report_body(array('order'=>'pkey','panel_select_pages'=>0,'debug'=>0)) ;
        ob_clean() ; // чисти вывод
        fclose($this->file_csv);
        $result['file_name']=$fname ;
        $result['file_dir']=_DIR_TO_ROOT.'/temp/'.$fname ;
        $result['file_url']=_PATH_TO_SITE.'/temp/'.$fname ;
        return($result) ;
     }

    function view_as_CSV_easy($options=array())
    {  // подготовить страницу
         $result=$this->save_as_CSV($options) ;
         $cont=file_get_contents(_DIR_TO_ROOT.'/temp/'.$result['file_name']) ;
         //header('Content-Type: application/vnd.ms-excel;name="'.$this->title.'.csv"');
         header('Content-Type: application/vnd.ms-excel;name="'.$this->title.'.csv"');
         header('Content-Disposition: attachment;filename="'.$this->title.'.csv"');
         header('Cache-Control: max-age=0');
         echo $cont ;
         exit() ;
      }


    function view_as_CSV($options=array())
    {   if ($this->use_csv_easy) { $this->view_as_CSV_easy($options) ; return ; }
        // подготовить страницу

        $fname='report_'.date('d_m_Y_H_i_s').'.csv' ;

        $this->usl_items=$this->create_usl_select_obj('',$options) ;
        $export_id=rand(1,100) ;

        if (isset($this->personal_id)and !isset($this->filter['personal_id'])) $this->filter['personal_id']=$this->personal_id ;
        if (isset($this->dopusk) and $this->dopusk>0  and !isset($this->filter['dopusk']))      $this->filter['dopusk']=$this->dopusk ;
        //if (isset($this->dopusk))      $this->filter['dopusk']=$this->dopusk ;
        if (isset($this->event_id)and !isset($this->filter['event_id']))    $this->filter['event_id']=$this->event_id ;
        //if (isset($this->group_id)and !isset($this->filter['group_id']))    $this->filter['group_id']=$this->group_id ;
        if (isset($this->status)and !isset($this->filter['status']))    $this->filter['status']=$this->status ;

        $count_obj=$this->get_cnt_items($this->usl_items,$options) ;  // по умолчанию - get_cnt_items

        $row_to_req=($GLOBALS['LS_CSV_export_row_count'])? $GLOBALS['LS_CSV_export_row_count']:10000 ;
        if ($this->CSV_export_row_to_req) $row_to_req=$this->CSV_export_row_to_req ;

        $settings=array('report_class'=>$this->report_class,
                        'report_script'=>hide_server_dir($this->report_script),
                        'row_to_req'=>$row_to_req,
                        'fname'=>$fname,
                        'account_id'=>MEMBER()->id,
                        'all'=>$count_obj,
                        'filter'=>$this->filter,
                        'exec_start'=>fixed_time(),
                         //'report_obj'=>serialize($this) // сериализуем объект отчета для последующего восстановления
                        ) ;
        $setting_uid=ENGINE()->save_temp_setting($settings) ;

        file_put_contents(_TEMP_DIR.$setting_uid.'.ser',base64_encode(serialize($this))) ;

        //echo 'Получено всего записей по данному условию:'.$count_obj.'<br>';
        ?><div id="exec_CSV_export_title">Ожидайте, идет подготовка файла Excel CSV<br><br><br><img src="/images/loading17.gif"></div>
          <div id="exec_CSV_export_status"></div>
          <div id="exec_CSV_req_result"></div>
          <script type="text/javascript">
            send_ajax_request({cmd:'report/exec_CSV_export',setting_uid:'<?echo $setting_uid?>'},exec_ajax_cmd_success_CSV) ;

            function exec_ajax_cmd_success_CSV(responseXML)
            {   var data=convert_XML_to_obj(responseXML) ;
                if (data.to && data.all) $j('#exec_CSV_export_status').html('Обработано строк <span id=exec_CSV_export_status_from>'+data.from+'</span> - '+data.to+' из '+data.all+', <strong>'+data.proc+'%</strong> '+', размер файла <strong>'+data.file_size+'</strong>') ;
                else $j('#exec_CSV_export_status').html('') ;

                if (data.error!="")
                { $j('#exec_CSV_export_title').html('При выполнении запроса произошла ошибка') ;
                  $j('#exec_CSV_export_status').html(data.error) ;
                }
                else if (data.status=='process')  send_ajax_request({cmd:'report/exec_CSV_export',setting_uid:'<?echo $setting_uid?>'},exec_ajax_cmd_success_CSV) ;
                else if (data.status=='end') send_ajax_request({cmd:'report/log_CSV_export',setting_uid:'<?echo $setting_uid?>'}) ;
                else $j('#exec_CSV_export_title').html('По вашему запросу ничего не найдено') ;

                // если передан атрибут и в документе существует блок с таким ID - заменить содержимое блока
                update_panel_by_tag_name(responseXML) ;

            }
         </script>
         <style>
           #exec_CSV_export_title {margin:40px;text-align:center;font-size:24px;;}
           #exec_CSV_export_status {margin:20px;text-align:center;font-size:16px;;}
           #exec_CSV_export_status strong{font-size:20px;font-weight:normal;color:green;}
           #exec_CSV_req_result{font-size:20px;font-weight:normal;margin:20px;text-align:center;;}
         </style>
         <?
     }

    // основная функция в которорой будет фрмироваться тело отчета
    function CSV_report_body($options=array())
    { $template_name=($options['template_name'])? $options['template_name']:'print_template_CSV' ;
      $cnt=$this->show_list_items('',$template_name,$options) ;
      return($cnt) ;
    }

    function print_template_CSV($list_recs,$options=array()){}

    function put_data_to_CSV($data,$i)
    {
        if (_sizeof($data)) foreach($data as $fname=>$value) $data[$fname]=iconv('UTF-8','windows-1251',$value) ;
        // для первой строки выводим заголовки
        if (!$i)
        {   $arr_title=array_keys($data) ;
            foreach($arr_title as $i=>$title) $arr_title[$i]=iconv('UTF-8','windows-1251',$title) ;
            fputcsv($this->file_csv,$arr_title,';');
        }
        // вывод данных
        fputcsv($this->file_csv,$data,';');
    }


/**************************************************************************************************************************************/
//
// PRINT
//
/**************************************************************************************************************************************/

    function prepare_to_print($options=array())
    { // сохраняем HTML  во временный файл
      ob_start() ;
      $this->report_paginator=0 ;
      $this->view_as_HTML($options) ;
      $html=ob_get_clean() ;
      $html=preg_replace ("!<a.*?href=\"?'?([^ \"'>]+)\"?'?.*?>(.*?)</a>!is", "\\2", $html);    // удаляем все ссылкм
      $file_name='temp_'.md5(rand(1,100000)) ;
      //$doc_file_name=$this->create_HTML_file($file_name,$html,$this->title,$this->panel_info_filter()) ;
      $doc_file_name=$this->create_HTML_file($file_name,$html,'',$this->panel_info_filter()) ;
      $doc_file_path=_TEMP_PATH.$doc_file_name;
      // показываем  этот временный файл в отдельном фрейме
      ?><iframe src="<?echo $doc_file_path?>"  style="width:100%; height:700px;margin-top:20px;" frameborder="0"></iframe><div id="div_backgroudPrint"></div><?
      // отправляем фрейм на печать
      _CUR_PAGE()->use_printPage=1 ;
      ?><script type="text/javascript">
           $j(document).ready(function()
              {  $j('div#div_backgroudPrint').printPage({url:'<?echo $doc_file_path?>'}) ;
                       $j('div#div_backgroudPrint').click() ;
              }) ;
                     </script><?
      }


  //==========================================================================================================================================================================
   // формирование отчета
   //==========================================================================================================================================================================

    // информация о текущей выборке при постраничной  HTML выборке
    function panel_info_select($options=array(),$mode='')
    { $_str2=array() ; $info2=array() ;
      //damp_array($options,1,-1) ;
      if ($options['count_obj'])                             $info2['всего строк']=$options['count_obj'];
      if ($options['first_obj'] and $options['last_obj'])    $info2['показаны строки']=$options['first_obj'].' по '.$options['last_obj'];
      //damp_array($info,1,-1) ;
      if (_sizeof($info2)) foreach($info2 as $title=>$value) $_str2[]=$title.': <strong>'.$value.'</strong>' ;
      if (_sizeof($_str2)) echo '<div class="panel_info_select '.$mode.'">'.implode(', ',$_str2).'</div>' ;
    }

    function create_HTML_file($doc_name,$html,$report_title='',$report_info='',$options=array())
    {   $html_css ='<style>'.file_get_contents(_DIR_TO_CLASS.'/style_print.css').'</style>' ;
        $title=($report_title)? $title='<h2 class="center">'.$report_title.'</h2><p class="center">'.$report_info.'</p>':'' ;

        $doc_file_name=$doc_name.'.html' ;
        $doc_dir=_TEMP_DIR.$doc_file_name ;
        file_put_contents($doc_dir,$html_css.$title.$html);
        return($doc_file_name) ;
    }

    // подготовка HTML файла для преобразования в PDF
    // 1. Надо обернуть html в стандартные теги
    // 2. Дописать внуть содержимое файла стилей
    // 3. Убрать из текста ссылки
    // 4. Сохранить HTML во временный файл, вернуть путь к времененному файлу
    function prepare_HTML_to_PDF_convert($html,$title,$temp_file,$options=array())
    {    $text='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">' ;
         $text.='<head>';
         $text.='<title>'.$title.'</title>';
         $text.='<META http-equiv="Content-Type" content="text/html; charset=utf-8">';
         $text.='<style type="text/css">'.file_get_contents(_DIR_TO_CLASS.'/style.css').'</style>' ;
         //$text.='<link rel="stylesheet" type="text/css" href="/'._CLASS_.'/style_pdf.css" charset="utf-8">';
         $text.='</head>';
         $text.='<body>';
         $text.=$html ;
         if ($this->show_sign_stamp)
         { ob_start() ;
           ?><div style="border:3px solid black;border-radius:20px;text-align:center;padding:10px;margin:50px;font-size:20px;line-height:1.8em;float:left;">
                <strong>ДОКУМЕНТ ПОДПИСАН<br>УСИЛЕННОЙ КВАЛИФИЦИРОВАННОЙ<br>ЭЛЕКТРОННОЙ ПОДПИСЬЮ</strong><br>
                <div style="font-size:15px;">Сведения о сертификате ЭП<br>
                Сертификат: <?echo MEMBER()->certificate['SerialNumber']?><br>
                Владелец: <?echo MEMBER()->name?><br>
                Срок действия с <?echo MEMBER()->certificate['ValidFromDate']?> по <?echo MEMBER()->certificate['ValidToDate']?>
             </div></div><div class="clear"></div><?
           $text.=ob_get_clean() ;
         }
         $text.='</body>';
         $text.='</html>';
         $text=str_replace(_PATH_TO_SITE.'/public/','file://'._DIR_TO_ROOT.'/public/',$text);
         if ($GLOBALS['LS_use_localhost_in_pdf']) $text=str_replace(_PATH_TO_SITE,_MAIN_PROTOCOL.'127.0.0.1',$text);
         //elseif ($GLOBALS['LS_use_localhost_in_pdf']) $text=str_replace(_PATH_TO_SITE,_MAIN_PROTOCOL.'127.0.0.1',$text);
         $text=preg_replace('/<a\s+.*?href=[\"\']?([^\"\' >]*)[\"\']?[^>]*>(.*?)<\/a>/i','\2',$text) ;                  // удаляем все ссылкм
         $text=preg_replace ("!<a.*?href=\"?'?([^ \"'>]+)\"?'?.*?>(.*?)</a>!is", "\\2", $text);    // удаляем все ссылкм
         file_put_contents($temp_file,$text) ;
    }

    function execHTML2PDF($from,$to,$options=array())
    {   $_PDF_options=array() ;
        $_PDF_options[]='--footer-font-size 10';
        $_PDF_options[]='--page-size A4';
        $_PDF_options[]='--footer-right [page]/[toPage]' ;
        if ($this->footer_right) $_PDF_options[]='--footer-right '.$this->footer_right ;
        if ($this->PDF_page_orientation=='L') $_PDF_options[]='-O Landscape' ;
        if ($this->PDF_page_orientation=='P') $_PDF_options[]='-O Portrait' ;
        if ($options['pdf_options'])          $_PDF_options[]=$options['pdf_options'] ;
        $PDF_options=implode(' ',$_PDF_options) ;

        $cmd=_HTML2PDF_.' '.$PDF_options.' '.$from.' '.$to ;

        $cmd_uid=md5(uniqid(rand(),true)) ;

        $outputfile=_TEMP_DIR.'log_'.$cmd_uid.'.txt' ;
        $pidfile=_TEMP_DIR.'exec_'.$cmd_uid.'.txt' ;
        if (file_exists($outputfile)) unlink($outputfile) ;
        if (file_exists($pidfile)) unlink($pidfile) ;
        if (file_exists($to)) unlink($to) ;
        $bash_cmd=sprintf("%s > '%s' 2>&1 & echo $! >> '%s'", $cmd, $outputfile, $pidfile) ;
        exec($bash_cmd)   ;

        $res=array('from'=>$from,
                     'to'=>$to,
                     'outputfile'=>$outputfile,
                     'pidfile'=>$pidfile,
                     'cmd_uid'=>$cmd_uid,
                      'bash_cmd'=>$bash_cmd,
                     'HTML_file_name'=>basename($from),
                     'HTML_file_name_url'=>_PATH_TO_SITE.hide_server_dir($from),
                     'HTML_file_name_link'=>'<a href="'._PATH_TO_SITE.hide_server_dir($from).'" target=_blank>'._PATH_TO_SITE.hide_server_dir($from).'</a>',
                     'PDF_file_name'=>basename($to),
                     'PDF_file_name_url'=>_PATH_TO_SITE.hide_server_dir($to),
                     'PDF_file_name_link'=>'<a href="'._PATH_TO_SITE.hide_server_dir($to).'" target=_blank>'._PATH_TO_SITE.hide_server_dir($to).'</a>',
                )  ;

        $arr_from=explode(' ',$from) ;
        if (_sizeof($arr_from)>1)
        {   $res_from=array() ;
            foreach($arr_from as $from_item)
            {  $res_from['HTML_file_name'][]=basename($from_item) ;
               $res_from['HTML_file_name_url'][]=_PATH_TO_SITE.hide_server_dir($from_item) ;
               $res_from['HTML_file_name_link'][]='<a href="'._PATH_TO_SITE.hide_server_dir($from_item).'" target=_blank>'._PATH_TO_SITE.hide_server_dir($from_item).'</a>' ;
            }
            $res['HTML_file_name']=implode('<br>',$res_from['HTML_file_name']) ;
            $res['HTML_file_name_url']=implode('<br>',$res_from['HTML_file_name_url']) ;
            $res['HTML_file_name_link']=implode('<br>',$res_from['HTML_file_name_link']) ;
        }

        return($res) ;
    }

   var $footer_right='[page]/[toPage]' ;

   function HTML2PDF_create_PDF_file($doc_name,$report_title,$html)
   { ob_start() ;
     $source_html=_TEMP_DIR.$doc_name.'.html' ;
     $target_pdf=_TEMP_DIR.$doc_name.'.pdf' ;

     // обертываем в теги и сохраняем в файл
     $this->prepare_HTML_to_PDF_convert($html,$report_title,$source_html,array()) ;

     // отдаем HTML2PDF для преобразования
     $result_convert=$this->execHTML2PDF($source_html,$target_pdf) ;

     $text=ob_get_clean()  ;    echo $text ;
     LOGS()->reg_log('HTML2PDF',$text,array('data'=>$result_convert)) ;
     return($result_convert) ;
   }

   // сохраняем отчет в виде PDF
   function create_PDF_file($doc_name,$report_title,$html,$report_info='',$options=array())
   {
       $name=$this->TCPDF_create_PDF_file($doc_name,$report_title,$html,$report_info,$options) ;
       return($name) ;
   }

   function TCPDF_create_PDF_file($doc_name,$report_title,$html,$report_info='',$options=array())
    {  // Include the main TCPDF library (search for installation path).
            require_once(_DIR_TO_ROOT.'/AddOns/tcpdf/tcpdf.php');
        //$report_info='222' ;
            // create new PDF document
            $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

            // set document information
            $pdf->SetCreator(PDF_CREATOR);
            $pdf->SetAuthor('ESMO');
            $pdf->SetTitle($report_title);
            //$pdf->SetSubject('TCPDF Tutorial');
            //$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
       $pdf->setPrintHeader(false);
       $pdf->setPrintFooter(false);

            // set default header data
       if ($this->PDF_show_header)
       { //$report_info=($report_info)? strip_tags($report_info)."\n".'подготовлен: '.MEMBER()->name.' '.date('d.m.Y H:i'):'подготовлен: '.MEMBER()->name.' '.date('d.m.Y H:i') ;
         ////$pdf->SetHeaderData('esmo.png', 30, $report_title,$report_info);

            // set header and footer fonts
            $pdf->setHeaderFont(Array('dejavusans', '', PDF_FONT_SIZE_MAIN));
            $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
       }

            // set default monospaced font
            $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

            // set margins
       //$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
       $pdf->SetMargins(5, 5, 5,5);
       //$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
       $pdf->SetHeaderMargin(0);
       //$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
       $pdf->SetFooterMargin(0);

            // set auto page breaks
       //$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
       $pdf->SetAutoPageBreak(TRUE, 0);

            // set image scale factor
       $pdf->setImageScale(2);

            // set some language-dependent strings (optional)
            //if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
            //    require_once(dirname(__FILE__).'/lang/eng.php');
            //    $pdf->setLanguageArray($l);
            //}

            // ---------------------------------------------------------

            // set font
            $pdf->SetCellPadding(0);
       $pdf->SetFont('freeserif', '', 11); // любой шрифт из папки /AddOns/tcpdf/fonts/
       //$pdf->SetFont('stsongstdlight', '', 12); // любой шрифт из папки /AddOns/tcpdf/fonts/
       //$pdf->setFontSpacing(-2);

            // add a page
       $pdf->AddPage($this->PDF_page_orientation, $this->PDF_page_format);

       $html_css ='<style type="text/css">'.file_get_contents(_DIR_TO_CLASS.'/style_pdf.css').'</style>' ;

       // output the HTML content
       //$pdf->writeHTML($html2, true, false, true, false, '');

       // writeHTML($html, $ln=true, $fill=false, $reseth=false, $cell=false, $align='')
       $pdf->writeHTML($html_css.$html, true, false, true, false, '');
       //$pdf->writeHTML($html, true, false, true, false, '');

       //Sign doc
       if ($this->is_signed) $this->sign_pdf($pdf,$options);


       //Close and output PDF document
       $doc_file_name=$doc_name.'.pdf' ;
       $doc_dir=_TEMP_DIR.$doc_file_name ;
            $pdf->Output($doc_dir, 'F');

        return($doc_file_name) ;
    }

    /* не используется
     *
     * function prepare_url($filter,$options=array())
    {   $url=array() ; $_str_url=array() ;  $res_url=$options['base_url'] ;  //damp_array($options,1,-1) ;
        if (_sizeof($filter)) foreach($filter as $key=>$value) if ($value) switch($key)
        { case 'member':      $url['member']=$value ; break ;
          case 'doc_type':    $url['doc_type']=$value ; break ;
          case 'data':        $url['data']=$value ; break ;
          case 'check':       $url['check']=1 ; break ;
          default:            $url[$key]=$value ;
        }
        if (_sizeof($url)) foreach($url as $key=>$value) if ($value!=1) $_str_url[]=$key.'='.$value ; else  $_str_url[]=$key ;
        if (_sizeof($_str_url))  $res_url.='['.implode(',',$_str_url).']/';
        return($res_url) ;
    } */

   function sign_pdf($pdf,$options=array())
   {

   }
  //----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
   //
   //  сттандрантые операции подготовки XLS
   //
   //----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

  //подготовка страницы
  function XLS_prepare_Sheet()
  { set_include_path(_DIR_TO_ADDONS.'/PHPExcel/');
    include_once(_DIR_TO_ADDONS.'/PHPExcel/PHPExcel.php');
    include_once(_DIR_TO_ADDONS.'/PHPExcel/PHPExcel/IOFactory.php');

    $this->pExcel = new PHPExcel();
    $this->pExcel->setActiveSheetIndex(0);
    $this->aSheet = $this->pExcel->getActiveSheet();

    //настройки для шрифтов
    $this->style['Font'] = array('font'=>array('name'=>'Arial Cyr','size'=>'8','bold'=>false));
    $this->style['boldFont'] = array('font'=>array('name'=>'Arial Cyr','size'=>'10','bold'=>true));
    $this->style['center'] = array('font'=>array('name'=>'Arial Cyr','size'=>'8'),'alignment'=>array('horizontal'=>PHPExcel_Style_Alignment::HORIZONTAL_CENTER,'vertical'=>PHPExcel_Style_Alignment::VERTICAL_TOP));
    $this->style['left'] = array('font'=>array('name'=>'Arial Cyr','size'=>'8'),'alignment'=>array('horizontal'=>PHPExcel_Style_Alignment::HORIZONTAL_LEFT,'vertical'=>PHPExcel_Style_Alignment::VERTICAL_TOP));
  }

  function XLS_print_table_header()
  { // заголовок документа
    //$this->aSheet->setTitle($this->title);

    $cur_col_char=$this->first_col_char ;
    if (_sizeof($this->fields)) foreach($this->fields as $fname=>$options)
    { $col_char=iconv('windows-1251','UTF-8',chr($cur_col_char)) ;
      $this->aSheet->getColumnDimension($col_char)->setWidth($options['width']); //
      $this->aSheet->setCellValue($col_char.$this->cur_row,$options['title']);
      $this->aSheet->getStyle($col_char.$this->cur_row)->applyFromArray($this->style['boldFont'])->applyFromArray($this->style['center']);
      $cur_col_char++ ;
    }
    $this->cur_row++ ;
  }

  //отдаем пользователю в браузер
  function XLS_put()
  { include("PHPExcel/Writer/Excel5.php");
    $objWriter = new PHPExcel_Writer_Excel5($this->pExcel);
    header('Content-Type: application/vnd.ms-excel;name="'.$this->title.'.xls"');
    header('Content-Disposition: attachment;filename="'.$this->title.'.xls"');
    header('Cache-Control: max-age=0');
    $objWriter->save('php://output');
  }

  //отдаем сохраняем в файл
  function XLS_save($fname)
  { include("PHPExcel/Writer/Excel5.php");
    $objWriter = new PHPExcel_Writer_Excel5($this->pExcel);
    $objWriter->save($fname);
  }


 //----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 //
 //  обвязка для вывода страниц
 //
 //----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------


    function manual_tags_in()
    {
        ?><table class="basic fz_normal left">
                    <tr><td></td><td></td></tr>
        </table><?
    }

    function manual_tags_out()
    {
        ?><table class="basic fz_normal left">
                    <tr><td></td><td></td></tr>
          </table>
        <?
    }

    function filter_section_select_tree($element_name,$element_title,$col_count,$recs,$options=array())
    { ?><!--<script src="/AddOns/jstree/dist/jstree.min.js"></script>
        <link rel="stylesheet" href="/AddOns/jstree/dist/themes/default/style.css" />-->
        <section class="col col-<?echo $col_count?>">
                    <label class="label"><?echo $element_title?></label>
                    <div style="position:relative">
                        <div id="tree_check_result" style="border:1px solid gray;position:absolute;top:0;left:0;width:100%;min-height:30px;background:white;z-index:1000;" class="v2" cmd="get_panel_select_tree"></div>
                    </div>


        </section>
      <?
    }

    //----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    //
    //  работа с формами
    //
    //----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    function form_open() {$this->form->form_open();}
    function form_close() {$this->form->form_close();}
	function row_open() {$this->form->row_open();}
	function fieldset_open() {$this->form->fieldset_open();}
	function row_buttons() { $this->form->row_buttons();}
	function row_close() {$this->form->row_close();}
	function fieldset_close() {$this->form->fieldset_close();}
	function row_close_open() {$this->form->row_close_open();}

	function filter_section_select($element_name,$element_title,$col_count,$recs,$options=array()) {  $this->form->filter=$this->filter ; $this->form->filter_section_select($element_name,$element_title,$col_count,$recs,$options);}
    function filter_section_select_multiple($element_name,$element_title,$col_count,$recs,$options=array()) {$this->form->filter=$this->filter ; $this->form->filter_section_select_multiple($element_name,$element_title,$col_count,$recs,$options);}
    function filter_section_input_text($element_name,$element_title,$col_count,$options=array()) {$this->form->filter=$this->filter ; $this->form->filter_section_input_text($element_name,$element_title,$col_count,$options) ;}

    function element_input($options=array()) { $this->form->filter=$this->filter ; $this->form->element_input($options) ; }
    function hidden_var($var_name,$value) {$this->form->hidden_var($var_name,$value);}

    function form_checkbox($title,$comment,$var_name,$value=0,$check_value=1) {$this->form->filter=$this->filter ; $this->form->form_checkbox($title,$comment,$var_name,$value,$check_value) ;}
    function form_checkbox_left($title,$comment,$var_name,$value=0,$check_value=1) {$this->form->filter=$this->filter ; $this->form->form_checkbox_left($title,$comment,$var_name,$value,$check_value) ;}
    function form_checkbox_to_arr($title,$comment,$var_name,$var_name2) {$this->form->filter=$this->filter ; $this->form->form_checkbox_to_arr($title,$comment,$var_name,$var_name2) ;}
    function form_element_input($title,$comment,$var_name,$options=array()) {$this->form->filter=$this->filter ; $this->form->form_element_input($title,$comment,$var_name,$options) ;}
    function form_element_textarea($title,$comment,$var_name,$options=array()) {$this->form->filter=$this->filter ; $this->form->form_element_textarea($title,$comment,$var_name,$options) ;}
    function form_element_select($title,$comment,$var_name,$recs,$options=array()) {$this->form->filter=$this->filter ; $this->form->form_element_select($title,$comment,$var_name,$recs,$options) ;}

    function panel_report_buttons(){}
    function panel_buttons($options=array())  {$this->form->panel_buttons($options);}
    function panel_button_apply($options=array())  {$this->form->panel_button_apply($options);}
    function panel_buttons_action()  {$this->form->panel_buttons_action();}



    //----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    //
    //  другое
    //
    //----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------


     function check_doc_fields($filter)
    {  $arr_errors=array() ;  $result=array() ;
       if (_sizeof($this->required_fields)) foreach($this->required_fields as $required_field=>$title)
         if (!$filter[$required_field]) $arr_errors[]=$title ;
       if (_sizeof($arr_errors)) $result['error']='Не заполнено поле: '.implode(', ',$arr_errors) ;
         return($result) ;
     }

    // $group_ids - значения в ключах массива !!! так как передается фильтр
    function get_usl_group_personal($fname,$group_ids,$union='or')
    {   $usl=array() ;
        if (_sizeof($group_ids))
        { foreach($group_ids as $group_id=>$flag) $usl[]=$fname.' in (select pkey from view_personals_group_'.$group_id.')' ;
        $res='('.implode($union,$usl).')' ;
        }
        return($res) ;
    }


    // $group_ids - значения в ключах массива !!! так как передается фильтр
    function get_usl_group_medic($fname,$group_ids,$union='or')
    {   $usl=array() ;
        if (_sizeof($group_ids))
            { foreach($group_ids as $group_id=>$flag) $usl[]=$fname.' in (select pkey from view_personals_medic_group_'.$group_id.')' ;
        $res='('.implode(' '.$union.' ',$usl).')' ;
            }
        return($res) ;
    }

}

?>
