<?php  ob_start();
require_once('../inc/config.php');

// init
    global $gIAsql;
    $gIAsql['usr_err']=true;
    global $gSecure;    // en false permite recibir sql del jggrid
    $gSecure=true; 
    global $jqDef;      // definicion de que parametros recibimos y sus defaults 
    $jqDef=array();
    jqDef_init();
    $gParams=read_params(); // get parameters
    
//reportaparams();
//ia_query("INSERT INTO dime(dime) VALUES(".strit("jqgrid_read.php: REQUEST=".print_r($_REQUEST,true)).")" );

/*
   if(!array_key_exists('usuario_id',$_SESSION)) {
        header($_SERVER["SERVER_PROTOCOL"]." 505 Sesion terminada! Haga login e intente de nuevo.\r\n");
        header("Status: 505  Sesion terminada! Haga login e intente de nuevo.");
        die();        
   } 
   // logged, mismo usuario
*/   
    $iacm=md5($gParams['iact'].$gParams['iactbl'].$gParams['iacc'].$gParams['iacwhere'].$gParams['iauid'].$gParams['iacpk'].$gParams['iacsql'].$gParams['iacsqlid']);
    if($iacm!=$gParams['iacm']) {       
        header($_SERVER["SERVER_PROTOCOL"]." 505 Error en la transmision de datos. Recargue la hoja e intente de nuevo");
        header("Status: 505 Error en la transmision de datos. Recargue la hoja e intente de nuevo. ");
        die();    
    }
    global $iacase;
    $iacase=get_iacase();  
    $extraColsNum= $gParams['iaccolse'] == '' ? 0 : sizeof(explode(',',$gParams['iaccolse'] ) );
     
    if($gParams['oper']=='') {
        $response = new stdClass();
        $sql=select_build();  
        
        $arr=ia_sqlArrayIndx($sql,MYSQL_NUM);
        if(!$gCountTotalRecords) {
            $gParams['total_records']=$gIAsql['found_rows'];
        }
  
        $i=0;
        if($arr) foreach($arr as $i=> $row) {
            $response->rows[$i]['id']=$row[0];
            for($itmp=0; $itmp<$extraColsNum; $itmp++)
                $response->rows[$i]['cell'][]='';        
            foreach($row as $d)        
                $response->rows[$i]['cell'][]=$d;
            $i++;
        }
        
        total_pages();
        $response->page = $gParams['page'];
        $response->total = $gParams['total_pages'];
        $response->records = $gParams['total_records'];                
        send_response($response);
        
    } elseif($gParams['oper']=='csv') {
        $fileName=$gParams['iact'].'csv';        
        $sql=select_build();
        if($iacase==NULL)
            exporta_csv($sql,$fileName);
        else
            $iacase->exporta_listado_csv(false,'',$sql);
    } elseif($gParams['oper']=='xlsx') {
    } elseif($gParams['oper']=='xls') {
    } elseif($gParams['oper']=='word') {    
    } elseif($gParams['oper']=='pdf') {
    } elseif($gParams['oper']=='html') {
    } elseif($gParams['oper']=='edit') {
        if(array_key_exists('iaccols',$gParams)) {
            $pk=$gParams['iacpk'];
            $log=$msg=$sql='';
            $valid=true;
            $tmp=explode(',',$gParams['iaccols']);
            if($gParams['iact']=='iacase') {
                // $iacase=get_iacase();
                $iacase->saveChilds=false;
                $iacase->h='s';
                // validate
                if( !$iacase->may_update() ) {
                    $valid=false;
                    $msg="Sin permiso de editar";
                } else {                
                    $iacase->id=$iacase->values[$pk]=$gParams['id'];                 
                    $iacase->ori=$iacase->values=ia_singleton("SELECT * FROM $iacase->table WHERE $pk=".strit($iacase->id));
                    $iacase->params_to_value(false,false);                          
                    if( !$iacase->validate() ) {
                        $valid=false;
                        $msg="<ul>".$iacase->msg_err."</ul>";
                    } else {
                       $valid=$iacase->update();  
                       if(!$valid) 
                        $msg="<ul>".$iacase->msg_err."</ul>";             
                    }
                }
                if($valid) {
                    $response['success']='true';
                    $response['msg']="Datos guardados!";                        
                } else {
                    $response['success']='false';
                    $response['msg']=$msg;                         
                }                
            } else { // por tabla  
                // validate
                foreach($tmp as $fieldName) {            
                    if( array_key_exists($fieldName,$_REQUEST) && $fieldName!=$pk )
                        $sql.=",$fieldName=".strit(param($fieldName));
                }
                $sql="UPDATE $gParams[iactbl] SET ".substr($sql,1)." WHERE $pk=".strit($gParams['id'])." LIMIT 1";
                if($valid) {
                    $response=array();
                    if(empty($sql)) {
                        $response['success']='true';
                        $response['msg']="Datos guardados!, sin cambios";                    
                    } elseif( ia_query($sql) ) {
                        // sql error!
                        $response['success']='false';
                        $response['msg']='Error al guardar los datos!<ul>'.$gIAsql['err'].'</ul>';
                    } else {
                        $response['success']='true';
                        $response['msg']="Datos guardados!";              
                    }                
                } else {
                        $response['success']='false';
                        $response['msg']=$msg;                
                }
                echo "{\"success\":$response[success] , \"msg\":\"$response[msg]\"}"; 
            }
        }
        
    } if($gParams['oper']=='add') {  

        if(array_key_exists('iaccols',$gParams)) {
            $pk=$gParams['iacpk'];
            $log=$msg=$sql=$ins='';
            $valid=true;
            $tmp=explode(',',$gParams['iaccols']);
            if($gParams['iact']=='iacase') {
                // $iacase=get_iacase();
                $iacase->saveChilds=false;
                $iacase->h='i';
                // validate
                if( !$iacase->may_insert() ) {
                    $response['success']='false';
                    $response['msg']="No tiene permiso de agregar registros";  
                } else {                
                    $iacase->id=$iacase->values[$pk]=$gParams['id'];                 
                    $iacase->ori=$iacase->values=ia_singleton("SELECT * FROM $iacase->table WHERE $pk=".strit($iacase->id));
                    foreach($tmp as $fieldName) 
                            if( array_key_exists($fieldName,$iacase->campos) )
                                $iacase->values[$fieldName]=param($fieldName);
                    foreach($iacase->campos as $fieldName=>$tmpV)
                                  $iacase->values[$fieldName]=param($fieldName);  
                    $iacase->id=$iacase->values[$pk]=$gParams['id'];                   
                    if($iacase->insert()) {
                        $response['success']='true';
                        $response['msg']="Alta realizada!";                         
                    } else {
                        $response['success']='false';
                        $response['msg']="<ul>".$iacase->msg_err."</li>";                         
                    }
                }
            } else { // por tabla  
                // validate
                foreach($tmp as $fieldName) {            
                    if( array_key_exists($fieldName,$_REQUEST) && $fieldName!=$pk ) {
                        $ins.=",$fieldName";
                        $sql.=",".strit(param($fieldName));
                    }
                }
                $sql="INSERT INTO $gParams[iactbl](".substr($ins,1).") VALUES(".substr($sql,1).")";
                if($valid) {
                    if(empty($sql)) {
                        $response['success']='true';
                        $response['msg']="Datos guardados!, sin cambios";                    
                    } elseif( ia_query($sql) ) {
                        // sql error!
                        $response['success']='false';
                        $response['msg']='Error al guardar los datos!';
                    } else {
                        $response['success']='true';
                        $response['msg']="Datos guardados!";
                        if($log!='') {                     
                            $iacase->log('update',$log);
                        }               
                    }                
                } else {
                    $response['success']='false';
                    $response['msg']=$msg;                
                }                
             }
            echo "{\"success\":$response[success] , \"msg\":\"$response[msg]\"}"; 
        }
        
    } if($gParams['oper']=='del') {
        if($gParams['iact']=='iacase') {
            $pk=$gParams['iacpk'];
            // $iacase=get_iacase();
            $iacase->id=$iacase->values[$pk]=$gParams['id'];
            $iacase->h='d';                 
            $iacase->values=ia_singleton("SELECT * FROM $iacase->table WHERE $pk=".strit($iacase->id));
            if( $iacase->may_delete() ) {
                if( $iacase->validate_delete($iacase->id,'d') ) {
                    $sql=array();
                    $sql=$iacase->delete_sql($iacase->values);
                    if( ia_transaction($sql) ) {
                        $response['success']='false';
                        $response['msg']='<ul>'.$gIAsql['err'].'</ul>';                        
                    } else {
                        $response['success']='true';
                        $response['msg']=$iacase->label.' eliminado!'; 
                        $iacase->log('delete',ia_htmlentities($iacase->label_record_summary()));                       
                    }
                } else {
                    $response['success']='false';
                    $response['msg']='<ul>'.$iacase->msg_err.'</ul>';                     
                }
            } else {
                    $response['success']='false';
                    $response['msg']='No tiene permiso de borrar!';                 
            }
        } else { //iactable 
            if(ia_query("DELETE FROM $gParams[iactbl] WHERE $gParams[iacpk]=".strit($gParams['id'])." LIMIT 1" )  ) {
                    $response['success']='false';
                    $response['msg']='No se pudo borrar el registro';                  
            } else {
                    $response['success']='true';
                    $response['msg']="Registro eliminado!";                  
            }
        }
        echo "{\"success\":$response[success] , \"msg\":\"$response[msg]\"}"; 
    }
    

// reporta errores
    reporta_errores();
    function reporta_errores() {
    global $gIAsql;
        $tmp=error_last();
        if($tmp!='' || $gIAsql['err']!='') {
            ia_query("INSERT INTO dime(dime) VALUES(".strit("jqgrid_read.php:\r\n$tmp\r\n".$gIAsql['err']).")");
        }
    }
               
// select maker
    function select_build() {
    global $gParams, $gSecure,$gCountTotalRecords;
        // select clause               
        if($gParams['iact']=='iacase')
            $select = get_select_iacase();
        elseif($gParams['iact']=='iacsqlid')
            $select = get_select_sqlid();
        elseif(!$gSecure && $gParams['iact']=='iacsql')
            $select = $gParams['iacsql'];
        elseif($gParams['iact']=='iactbl')
            $select = get_select_table();
        else
            $seleect='';
        // where clause
        $where=where_build();
        if(!empty($where))
            if( stripos($select,'where'))
                $select.=" AND $where ";
            else
                $select.=" WHERE $where ";
        // revisa si tenemos que hacer count del select o no
        $gCountTotalRecords=stripos($select,'SQL_CALC_FOUND_ROWS')===FALSE;      
        if($gCountTotalRecords) {
            $ipos=stripos($select,' FROM');
            $cnt="SELECT COUNT(*) ".substr($select,$ipos);
            $gParams['total_records']=ia_singleread($cnt,0);
        }
        
        // order by
        $orderby=orderby_build();
        if(!empty($orderby))
            if(stripos($select,'ORDER BY'))
                $select.=", $orderby";
            else
                $select.=" ORDER BY $orderby";
        //ia_query("INSERT INTO dime(dime) VALUES(".strit("jqgrid_read.php $gParams[oper]: select_build da:\r\n$select") .")" );                  
        if( empty($gParams['iacallPages']) || $gParams['iacallPages']=='false' )
            return $select.limit_build();
        else
            return $select;              
    }
    
    function get_select_iacase() {  
    global $iacase,$gParams;
        $gParams['tablePrefix']=$iacase->table;
        // falta checar permisos en tabla y campos en iaccols
        if(!empty($iacase->jqGridExtraWhere))
            $where=" WHERE ($iacase->jqGridExtraWhere) ";   
        else
            $where='';        
        return "SELECT ".get_select_columns_iacase()." FROM $gParams[iactbl]".$where;
       
    }

    function get_select_columns_iacase() {
    global $iacase,$gParams;
        if( empty($gParams['iacallColumns']) || $gParams['iacallColumns']=='false'  ) {
            $cols='';
            foreach( $gParams['iajqcolsArr'] as $d)
                if( strcasecmp('actions',$d) ) {
                    if( !array_key_exists('virtual_sql', $iacase->campos[$d]) )
                        $cols.=','.$d;
                    else {
                        $cols.=','.$iacase->campos[$d]['virtual_sql'];
                    }
                }
            return substr($cols,1);          
        }
        if( $gParams['iacallColumns']===true || $gParams['iacallColumns']=='true' || $gParams['iacallColumns']==1 || $gParams['iacallColumns']==-1 || $gParams['iacallColumns']=='*' )
            return '*';
        if(strpos($gParams['iacallColumns'],','))
            return $gParams['iacallColumns'];        
    }
        
    function get_select_columns() {
    global $iacase,$gParams;
        if( empty($gParams['iacallColumns']) || $gParams['iacallColumns']=='false'  ) {
            $cols='';
            foreach( $gParams['iajqcolsArr'] as $d)
                if( strcasecmp('actions',$d) )
                    $cols.=','.$d;  
            return substr($cols,1);          
        }
        if( $gParams['iacallColumns']===true || $gParams['iacallColumns']=='true' || $gParams['iacallColumns']==1 || $gParams['iacallColumns']==-1 || $gParams['iacallColumns']=='*' )
            return '*';
        if(strpos($gParams['iacallColumns'],','))
            return $gParams['iacallColumns'];        
    }
    
    function get_select_table() {
    global $gParams;
        return "SELECT ".get_select_columns()." FROM $gParams[iactbl]";
    }

    
    function get_select_sqlid() {
    global $gParams;
        $appRelate=new appRelate();
        if(!array_key_exists($gParams['iacsqlid'],$appRelate->sqlRead))
            return '';
        return $appRelate->sqlRead[$gParams['iacsqlid']];
    }

    // where
    function where_build($tablePrefix='',$kv=null) {
    global $gParams;
        if($gParams['_search']===FALSE || $gParams['_search']=='false' || $gParams['_search']=='FALSE' || $gParams['_search']=='')
            return $gParams['iacwhere']=='' ? '' : " ($gParams[iacwhere]) ";
        
        $where='';
        if($gParams['searchField']!='') {
                              
            where_op($where,'AND');
            $where='('.where_clause($tablePrefix.$gParams['searchField'],$gParams['searchOper'],$gParams['searchString']) .')';
        } 
        
          $group_clauses='AND';
          $op='bw';
          $tmp='';
          if($gParams['iajqcolsArr']) foreach($gParams['iajqcolsArr'] as $fieldname) {
            $value=param($fieldname);          
            if(!empty($value) || ( $op=='nu' || $op=='nn' ) ) {
                where_op($tmp,$group_clauses);
                if( $kv!=null && isset( $kv->fields[$fieldname]) && ( $kv->fields[$fieldname]['dataType']=='bit' )  )
                    $tmp.=where_clause($tablePrefix.$fieldname,'eq',$value );
                elseif($value==1 || $value==0)
                    $tmp.=where_clause($tablePrefix.$fieldname,'eq',$value );
                else
                    $tmp.=where_clause($tablePrefix.$fieldname,$op,$value );
            }
          } 
          if($tmp!='') {
            where_op($where,'AND');
            $where.="($tmp)";
          }
       
        if($gParams['filters']!='') {
            $tmp='';
            $f=json_decode( $gParams['filters'] );
            if( isset( $f->groupOn ) )
                $op=$f->groupOn;
            else
                $op='AND';
            if($op!='AND' && $op!='OR') 
                $op='AND';
            if( $f->rules ) foreach( $f->rules as $rule ) {
                $tiene=trim($rule->data);   
                if( !empty($tiene) || ( $rule->op=='nu' || $rule->op=='nn' ) ) {
                    where_op($tmp,$op);
                    $tmp.=where_clause($tablePrefix.$rule->field,$rule->op,$rule->data);
                }
            }
            if($tmp!='') {
                where_op($where,'AND');
                $where.="($tmp)";
            }
        }
    
        if($where=='')
            return $gParams['iacwhere']=='' ? '' : " ($gParams[iacwhere]) ";
        return  $gParams['iacwhere']=='' ?  $where : " ($gParams[iacwhere]) AND ($where)"; 
    }
    
    function where_op(&$where,$op) {
        if($where!='')
            $where.=" $op ";
    }
    
    function where_clause($field,$op,$data) {
    global $jqDef,$iacase;
        if(!empty($iacase) && array_key_exists($field,$iacase->campos) && array_key_exists('virtual_sql',$iacase->campos[$field]) ) {
            $field= str_replace("as $field","", $iacase->campos[$field]['virtual_sql']);
        }    
    
        if(is_array($data)) {
            if(sizeof($data)==1)
                $data=$data[0];
            elseif($op=='ne')
                $op='ni';
            elseif( $op!='ni' )
                $op='in';
        }
        if($op=='eq')   return "$field = ".strit($data);
        if($op=='ne')   return "$field <> ".strit($data);
        if($op=='lt')   return "$field < ".strit($data);
        if($op=='le')   return "$field <= ".strit($data);
        if($op=='gt')   return "$field > ".strit($data);
        if($op=='ge')   return "$field >= ".strit($data);
        if($op=='bw')   return "$field LIKE ".strit("$data%");
        if($op=='bn')   return "$field NOT LIKE ".strit("$data%");
        if($op=='ew')   return "$field LIKE ".strit("%$data");
        if($op=='en')   return "$field NOT LIKE ".strit("%$data");
        if($op=='cn')   return "$field LIKE ".strit("%$data%");
        if($op=='nc')   return "$field NOT LIKE ".strit("%$data%");
        if($op=='in' || $op=='ni') {
            $in='';
            if(is_array($data) && $data) 
                foreach($data as $d)
                    $in.=",".strit($d);
            elseif($op=='in')
                return "$field = ".strit($data);
            elseif($op=='ni')
                return "$field <> ".strit($data);
            $in=substr($in,1);
            if($in=='') return "1=0";
            
            if($op=='in')   return "$field IN ($in)";
            return "$field NOT IN ($in)";
        }
        if($op=='nu')   return "$field IS NULL ";
        if($op=='nn')   return "$field IS NOT NULL ";    
        return "$field=".strit($data); 
    }

    // order by
    function orderby_build($tablePrefix='',$kv=null) {
    global $gParams;
        $orderby= ($gParams['sidx']=='' ? '' : "$gParams[sidx] $gParams[sord],").($gParams['iacorderby']=='' ? '' : $gParams['iacorderby'].',' );
        return substr($orderby,0,-1);
    }

    // limit
    function limit_build() {
    global $gParams;
        if(empty($gParams['rows']) || !is_numeric($gParams['rows']) ) 
            return '';
        if($gParams['rows']<=0)
            $gParams['rows']=10;
        if( empty($gParams['page']) || !is_numeric($gParams['page']) || $gParams['page']<=0 )
            $gParams['page']=1;
        $start = $gParams['rows']*$gParams['page'] - $gParams['rows'];
        if($start <0) 
            $start = 0;  
        return " LIMIT $start,$gParams[rows] ";            
    }
    
    // total pages
    function total_pages() {
    global $gParams;
        if(empty($gParams['rows']) || !is_numeric($gParams['rows']) || $gParams['rows']<0 ) {
            $gParams['total_pages']=1;
        } else {
            if( $gParams['total_records'] > 0 && $gParams['rows'] > 0)  {
                $gParams['total_pages'] = max( ceil($gParams['total_records']/$gParams['rows']),1);
                
            } else 
                $gParams['total_pages'] = 0;
            if ($gParams['page'] > $gParams['total_pages'])
                $gParams['page']=$gParams['total_pages'];             
        }
    }

// iacse
    function get_iacase() {
    global $gParams;
        if( !empty($gParams['iacc']) ) {
            return new $gParams['iacc']();
        }
        return null;
    }
    
// init
    function read_params() {
    global $jqDef;
        $gParams=array();
        foreach($jqDef['param'] as $k=>$v)
            $gParams[$k]=param($v, isset($jqDef['default'][$k]) ? $jqDef['default'][$k] : '' );
        
        // iaccols columnas en el select
        if(isset($gParams['iaccols']) && $gParams['iaccols']!='') {
            $gParams['iaccols']=str_replace('%2C',',',$gParams['iaccols']); 
            $gParams['iajqcolsArr']=explode(',', $gParams['iaccols']);
        } else
            $gParams['iajqcolsArr']=array();
        //iacuid id del usuario
        //iaccolse columnas extra propias del grid
        //iact  indica el tipo del read:   iaccase,iacsqlid,iacsql,iactbl
            // iacsqlid id del sql en appRelate
            // iactable table a reportar
            // iacsql sql a reportar sin order by ni limit, debe estar $gSecure en false
            // iaccase iacase class a reportar
        //iacwhere extra where para el select
        //iacorderby extra orderby para el select
        //iacm md5 para checar
        $gParams['total_records']=0;
        $gParams['total_pages']=0;
            
        return $gParams;
    }

    function jqDef_init() {
    global $jqDef;
        // read parameters: param: param name, default: default value
        $jqDef['param']['page']='page'; // requested page
        $jqDef['default']['page']=1;
        $jqDef['param']['rows']='rows'; // rows per page
        $jqDef['default']['rows']=10;
        $jqDef['param']['sidx']='sidx'; // sort col after that the index from colModel
        $jqDef['default']['sidx']=1;
        $jqDef['param']['sord']='sord';
        $jqDef['default']['sord']='';    // sorting order
        $jqDef['param']['_search']='_search';   // search true/false
        $jqDef['default']['_search']='false';
        // single search  
        $jqDef['param']['searchField']='searchField';    // search field
        $jqDef['default']['searchField']='';
        $jqDef['param']['searchString']='searchString';  // buscar
        $jqDef['default']['searchString']='';
        $jqDef['param']['searchOper'] = 'searchOper';    // oper as per sopt
        $jqDef['default']['searchOper'] = '';
        $jqDef['param']['filters'] = 'filters';          // filters
        $jqDef['default']['filters'] = '';
        // advanced search
        $jqDef['param']['groupOp']='groupOp';       // este set con AND/OR
        $jqDef['param']['rules']='rules';           // and array with: field, op, data
        $jqDef['param']['groups']='groups';         // groups an array with more sets
    
        // editurl
        $jqDef['param']['id']='id';     // record id
        $jqDef['default']['id']=''; 
        $jqDef['param']['oper']='oper'; // add,edit,del
        $jqDef['default']['oper']='';
    
        // iac iacase params
        $jqDef['param']['iacm'] = 'iacm';                   // md5 para checar params ok
        $jqDef['param']['iacpk'] = 'iacpk';
        $jqDef['param']['iauid'] = 'iauid';             // user id
        
        $jqDef['param']['iaccols'] = 'iaccols';         // colnames a reportar
        $jqDef['param']['iaccolse'] = 'iaccolse';         // columnas especiales del jqgrid
        
        $jqDef['param']['iact'] = 'iact';               // metodo del sql default es clase iacase     
        $jqDef['default']['iact']='iacc';
        $jqDef['param']['iacc'] = 'iacc';               // iacase class a reportar
        $jqDef['param']['iactbl'] = 'iactbl';           // tabla a reportar
        $jqDef['param']['iacsqlid'] = 'iacsqlid';       // id del sql en appRelate
        $jqDef['param']['iacsql'] = 'iacsql';           // sql a ejecutar inseguro! 
          
        $jqDef['param']['iacwhere']='iacwhere';         // where se agrega adicionalmente a filtro/select o where del sql con AND
        $jqDef['param']['iacorderby']='iacorderby';        // order by columns se agregan adicionalmente a sidx
    
        $jqDef['param']['iacallPages']='iacallPages';  // en true ho hace limit by
        $jqDef['param']['iacallColumns']='iacallColumns'; //blanco/false saca cols del grid, true all columns, nombre variable cols a sacar,comas columnas a sacar
        $jqDef['param']['iacisrep']='iacisrep';         // es un reporte usar iaccolumns
        $jqDef['param']['iaccolumns']='iaccolumns';     // como estan las columnas      
        $jqDef['param']['iacm'] = 'iacm';              // md5 de parametros para checarlos
    
        $jqDef['sopt']['eq']='eq';
        $jqDef['sopt']['ne']='ne';
        $jqDef['sopt']['lt']='lt';
        $jqDef['sopt']['le']='le';
        $jqDef['sopt']['gt']='gt';
        $jqDef['sopt']['ge']='ge';
        $jqDef['sopt']['bw']='bw';  // begins with
        $jqDef['sopt']['bn']='bn';  // not begins with
        $jqDef['sopt']['in']='in';  // is in set
        $jqDef['sopt']['ni']='ni';  // is not in set
        $jqDef['sopt']['ew']='ew';  // ends with
        $jqDef['sopt']['en']='en';  // not ends
        $jqDef['sopt']['cn']='cn';  // containds
        $jqDef['sopt']['nc']='nc';  // not contains
        $jqDef['sopt']['nu']='nu';  // is null
        $jqDef['sopt']['nn']='nn';  // not null    
    }

//
    function send_response($response) {
    global $gIAsql;
        $err='';
        //$arr=error_get_last();
       // if(!empty($arr) )
       //     $err.=" $arr[message]";        
        if($gIAsql['err']!='') {
            $err.=' '.$gIAsql['err'];
        }
        if($err!='') {
            header($_SERVER["SERVER_PROTOCOL"]." 505 $err");
            header("Status: 505 $err");            
        } else
            echo json_encode($response);
    }

    function reportaparams() {
        $ret='';
        if($_REQUEST) 
            foreach($_REQUEST as $k=>$v)
                $ret.="&$k=$v";
        ia_query("INSERT INTO dime(dime) VALUES(".strit('ajax/jqgrid_read.php?'.substr($ret,1)).")");
    }

    function exporta_csv($sql,$fileName='download.csv') {
        header("Content-Type: text/html; charset=utf-8");
        header("Cache-Control: no-store, no-cache");
        header("Content-Disposition: attachment; filename*=UTF-8''".$fileName.".csv");
        echo "\xEF\xBB\xBF";
        $exporta=ia_sqlArrayIndx($sql);
        if($exporta) {
            foreach($exporta as $rec) {
                $con=false;
                foreach($rec as $fieldName=>$v) if($conPK || (!$conPK && $fieldName!=$this->pk_field)) {
                    if($con)
                        echo ','.comillea(to_label($fieldName));
                    else {
                        echo comillea(to_label($fieldName));
                        $con=true;
                    }
                }
                break;
            }
            
            foreach($exporta as $rec) {
                echo PHP_EOL;
                $con=false;
                foreach($rec as $fieldName=>$v) if($conPK || (!$conPK && $fieldName!=$this->pk_field)) {
                    if( is_numeric($v) )
                        if($con)
                            echo ','.$v;
                        else {
                            echo $v;
                            $con=true;
                        }                    
                    else
                    if($con)
                        echo ','.comillea($v);
                    else {
                        echo comillea($v);
                        $con=true;
                    }
                }
            }
            echo PHP_EOL;
        }
        reporta_errores();
        die();
    }
?>