<?php
declare(strict_types=0);

function msql_connect($host='',$user='',$pass='',$data='')
{
// $server_name=$_SERVER['SERVER_NAME'];
// $script_name=$_SERVER['SCRIPT_NAME'];
// $request_uri=$_SERVER['REQUEST_URI'];
// $document_root=$_SERVER['DOCUMENT_ROOT'];

// $domain=$server_name;
// $subdom=substr($document_root,strrpos($document_root,'/')+1);
     $newdb=[];
     $newdb[]='demo';
     $newdb[]='emdc';
     $newdb[]='ptsa';
//      $newdb[]='vare';
//      var_dump2($newdb);
     
     $host=strtolower($host);
     $data=strtolower($data);
     date_default_timezone_set('America/Guayaquil');
     
//      SET lc_time_names = 'es_ES';     
     $ip_server=$_SERVER['SERVER_ADDR'];
     $server=$_SERVER['SERVER_NAME'];
     $document_root=$_SERVER['DOCUMENT_ROOT'];
     $script_name=$_SERVER['SCRIPT_NAME'];
     
     $subdom=substr($document_root,strrpos($document_root,'/')+1);
     if($subdom=='public_html'){$subdom='';}
     if(!empty($subdom)){$server=str_replace($subdom.'.','',$server);}
     if(empty($subdom)){$subdom=substr($script_name,strpos($script_name,'/')+1,strrpos($script_name,'/')-1);}
     if(mb_stristr($subdom,'.')){$subdom=$_SESSION['empr'];}
     if(empty($subdom)){$subdom=$data;}
     
     $db_server='vcrxol.com';
     $host='vcrxol.com';
     $hostip='192.185.41.206';
     
     if (in_array($subdom, $newdb))
     {$hostip='50.6.168.20';}
     
     if (in_array($data, $newdb))
     {$hostip='50.6.168.20';}
     
//      echo '=='.$hostip.$subdom;
     
     if(empty($data)){$data=$subdom;}
//      if(mb_stristr2('.ytf1',$data)){$db_server='yotefio.com';$host='yotefio.com';$pass='Pulso2020*';$hostip='108.167.161.55';}
//      if(mb_stristr2('.demo',$data)){$hostip='50.6.168.20';}
     
     $hostname=substr($db_server,0,strpos($db_server,'.'));
     if(mb_stristr($hostname,'.')){$hostname=$db_server;}
     $username=$hostname.'_'.$data.'full';
     $dataname=$hostname.'_'.$data;
     
     if(empty($host)){$host=$db_server;}
     if(empty($user)){$user=$username;}
     if(empty($pass)){$pass='vicore1976';}

     $link_data=$_SESSION['link_data'];
     $sql_test='select database()';
     
     $ver=substr(phpversion(),0,1);
     if($ver<=5)
     {
          if(gettype($link_data)=='resource')
          {
               $reso_test=mysql_query($sql_test,$link_data);
               if(mysql_result($reso_test,0,'database()')!=$dataname)
               {$link_data=mysql_connect($host,$user,$pass,true);}
          }
          else          
          {$link_data=mysql_connect($host,$user,$pass,true);}
          mysql_select_db($dataname,$link_data);
          mysql_query('set names utf8');
          mysql_query('set lc_time_names="es_EC"');
     }

     if($ver>=7)
     {
          // php 8.0
          // eliminar esta validacion
          if(gettype($link_data)=='object' and 1==2)
          {
               $reso_test=@mysqli_query($link_data,$sql_test);
               if(@msql_result($reso_test,0,'database()')!=$dataname)
               {$link_data=@mysqli_connect($hostip,$user,$pass,$dataname);}
          }
          else
          {
               $link_data=@mysqli_connect($hostip,$user,$pass,$dataname);
//                $link_data= new mysqli($host,$user,$pass,$dataname);
          }
          
//           setlocale(LC_TIME, "es_ES"); 
          setlocale(LC_TIME, "es_ES.UTF-8"); 
//           setlocale(LC_TIME, "es_419"); 
//           setlocale(LC_TIME, "es_ES.UTF-8", "es_ES", "Spanish_Spain", "es");
//           msql_query("set names 'utf8'",$link_data);
//           msql_query('SET lc_time_names = "es_ES"',$link_data);


//   $pdo->exec("SET SESSION sql_mode = REPLACE(@@sql_mode, 'ONLY_FULL_GROUP_BY', '');");

          mysqli_query($link_data,"SET SESSION sql_mode = REPLACE(@@sql_mode, 'ONLY_FULL_GROUP_BY', '');");
          
          
          mysqli_query($link_data,'set profiling=1');
          mysqli_query($link_data,'set names "utf8"');
          mysqli_query($link_data,'SET lc_time_names = "es_ES"');
          
     }
     
     if($ver>=8)
     {
        //   file_get_contents('http://vcrxol.com/_lib/cj_crea_hta.php');
     }     
     
//      $_SESSION['empr_codi']=$data;
     $_SESSION['link_data']=$link_data;
     $_SESSION['hostname']=$hostname;
     $_SESSION['dataname']=$dataname;
     $_SESSION['server']=$server;
     $_SESSION['subdom']=$subdom;
//      $_SESSION['dbserver']=$dbserver;
     
     
     return $link_data;
}

function msql_close($reso)
{mysqli_close($reso);}

function msql_query($sql,$link='',$explain=0)
{
     if(empty($sql)){return;}
     
     if($link->ping()!=1){return '*** SIN CONEXION ***';}
     
     $ver=substr(phpversion(),0,1);
    
     $sql=str_replace(', ',',',$sql);
     $sql=str_replace(', ',',',$sql);
     
     if(1==2)
     if(substr($sql,0,6)=='insert')
     {
          $sql=str_replace(' "','"',$sql);
          $sql=str_replace('" ','"',$sql);
          
          $sql=str_replace('("','+++++',$sql);
          $sql=str_replace('")','-----',$sql);
          $sql=str_replace('",','=====',$sql);
          
          $sql=str_replace('"','\"',$sql);
          
          $sql=str_replace('+++++','("',$sql);
          $sql=str_replace('-----','")',$sql);
          $sql=str_replace('=====','",',$sql);
     }
     

     if(1==2)
     if(substr($sql,0,6)=='update')
     {
          $sql=str_replace(' "','"',$sql);
          $sql=str_replace('" ','"',$sql);
          
          $sql=str_replace('="','+++++',$sql);
          $sql=str_replace('",','-----',$sql);
          
          $sql=str_replace('"','\"',$sql);
          
          $sql=str_replace('+++++','="',$sql);
          $sql=str_replace('-----','",',$sql);
//           $sql=str_replace('=====','",',$sql);
          
     }
     

     $sql=str_replace(',where',' where',$sql);
     $sql=str_replace(',from',' from',$sql);
//      if($_SESSION['user_codigo']==2)
     {
          $sql=str_replace(', where',' where',$sql);
          $sql=str_replace(', from',' from',$sql);
          $sql=str_replace('where ',' where ',$sql);

               {
                    $sql=str_replace('mdfrom','mdfroXm',$sql);
                    $sql=str_replace('idfrom','idfroXm',$sql);
                   // NO HABILITAR // CONFLICTO CON IDFROM MDFROM      
                    $sql=str_replace('from ',' from ',$sql);
                    $sql=str_replace('mdfroXm','mdfrom',$sql);
                    $sql=str_replace('idfroXm','idfrom',$sql);
               }          


          $sql=str_replace('  ',' ',$sql);
     }
     
     $msc = microtime(true);
     
     if($ver<=5){$reso=mysql_query($sql,$link); $errno=mysql_errno($link); $error=mysql_error($link);}
     if($ver>=7)
     {
          if(substr($sql,0,6)=='update')
          if(mb_stristr($sql,'now()'))
          {
               $sql_now='select hour(now()) as hora';
               $res_now=mysqli_query($link,$sql_now);
               $aso_now=@mysqli_fetch_assoc($res_now);

               if(msql_result($res_now,0,'hora')<date('G'))
               {$sql=str_replace('now()','date_add(now(),interval 1 hour)',$sql);}
               
               if(msql_result($res_now,0,'hora')=='23' and date('G')==0)
               {$sql=str_replace('now()','date_add(now(),interval 1 hour)',$sql);}
          }
          
//           $sql=str_replace('"0000-00-00 00:00:00"','null',$sql);
          
//           $resox=mysqli_query($link,"SET sql_mode = ''"); 
// SET sql_mode = '';
          
          $reso=mysqli_query($link,$sql); 
          $errno=mysqli_errno($link); 
          $error=mysqli_error($link);
     }

     $msc = microtime(true)-$msc;
     $msc=round($msc,2);
     $_SESSION['qtime']=$msc;

     if($msc>=10)
     {
          if(!is_dir('../-slow')){mkdir('../-slow');}
          
          $debug=show_debug(debug_backtrace(),'txt');
          $file_slow='../-slow/slow_'.date('Y_m_d_H').'.txt';
          $reg_slow='';
          $reg_slow.="\n";
          $reg_slow.="EMPR: ".$_SESSION['empr_codigo']."\n";
          $reg_slow.="TIME: ".date('H:i:s')."\n";
          $reg_slow.="SQLQ: ".$sql."\n";
          $reg_slow.="SECS: ".$msc."\n";
          $reg_slow.="DBUG: ".$debug."\n";
          file_put_contents($file_slow,$reg_slow,FILE_APPEND);
     }
     
     
     if(!empty($error))
     {
          echo '<br>'; 
          echo '<br>'; 
          echo ' ERROR : ('.$errno.') '.$error.' <br>'.' ==> SQL : '.$sql.' '; 
          
          $nodebug=array(1091);
          if(!in_array($errno,$nodebug))
          {
               echo '<br>';
               echo ' DEBUG : ';
               echo show_debug(debug_backtrace());
          }
//           1062 duplicate 
//           {var_dump(debug_backtrace());}
//           {print_r(debug_backtrace());}
//           {var_export(debug_backtrace());}
//           echo '<br>';
          
//           $output = ob_get_clean();
          echo '<br>'; 
          
     }

//      echo '<br>';
//      echo '<br>'.date('H:i:s');
//      echo '<br>='.$msc;
//      echo '<br>='.$sql;
     
     return $reso;
}  

function msql_result($reso='',$row=0,$col=0)
{
     if(empty($reso))
     {
          echo show_debug(debug_backtrace());
          return;
     }
     $val='';
     $ver=substr(phpversion(),0,1);
     if($ver<=5){if(mysql_num_rows($reso)!=0){$val=mysql_result($reso,$row,$col);}}
     if($ver>=7)
     {
//      echo '<br>=====> version '.$ver;
          if(mysqli_num_rows($reso)!=0)
          {$reso->data_seek((int)$row); $datarow=$reso->fetch_array(); $val=$datarow[$col];}
          if($col=='type')
          {if(mysqli_num_rows($reso)!=0){mysqli_data_seek($reso,$row); $datarow=mysqli_fetch_array($reso); $val=$datarow[0];}}
     }
     return $val;
}

function msql_data_seek(&$reso='',$row=0)
{
     if(empty($reso))
     {echo show_debug(debug_backtrace());return;}
//      {return 0;}
     
     $ver=substr(phpversion(),0,1);
     if($ver<=5){if(mysql_num_rows($reso)!=0){mysql_data_seek($reso,$row);}}
     if($ver>=7){if(mysqli_num_rows($reso)!=0){mysqli_data_seek($reso,$row);}}
     return $reso;
}

function msql_num_fields($reso='')
{
     if(empty($reso))
     {echo show_debug(debug_backtrace());return;}
     
     $val='';
     $ver=substr(phpversion(),0,1);
     if($ver<=5){$val=mysql_num_fields($reso);}
     if($ver>=7){$val=mysqli_num_fields($reso);}
     return $val;
}

function msql_affected_rows_rows($reso)
{
     $val='';
     $ver=substr(phpversion(),0,1);
     if($ver<=5){$val=mysql_affected_rows($reso);}
     if($ver>=7){$val=mysqli_affected_rows($reso);}
     return $val;
}

function msql_num_rows($reso='')
{
     if(empty($reso))
     {echo show_debug(debug_backtrace());return;}
//      {return 0;}
     
     $val=0;
     $ver=substr(phpversion(),0,1);
     if($ver<=5){$val=mysql_num_rows($reso);}
     if($ver>=7){$val=mysqli_num_rows($reso);}
     return $val;
}

function msql_fetch_assoc($reso)
{
     if(empty($reso))
     {echo show_debug(debug_backtrace());return;}
     $val='';
     $ver=substr(phpversion(),0,1);
     if($ver<=5){$val=mysql_fetch_assoc($reso);}
     if($ver>=7){$val=mysqli_fetch_assoc($reso);}
     return $val;
}

function msql_field_name($reso,$idx)
{
     $val='';
     $ver=substr(phpversion(),0,1);
     if($ver<=5){$val=mysql_field_name($reso,$idx);}
     if($ver>=7)
     {
          $properties = mysqli_fetch_field_direct($reso, $idx);
          $val=is_object($properties) ? $properties->name : null;
     }
     return $val;
}

function msql_field_type($reso,$idx)
{
     $val='';
     $ver=substr(phpversion(),0,1);
     if($ver<=5){$val=mysql_field_type($reso,$idx);}
     if($ver>=7)
     {
          $table_info = mysqli_fetch_field_direct($reso, $idx);
          $val=$table_info->type;
          if($val>=1 and $val<=3){$val='int';}
          if($val>=4 and $val<=5){$val='float';}
          if($val>=8 and $val<=9){$val='int';}
          if($val>=10 and $val<=13){$val='date';}
          if($val==246){$val='real';}
          if($val>=253 and $val<=254){$val='string';}
          
// 1=>'tinyint',
// 2=>'smallint',
// 3=>'int',
// 4=>'float',
// 5=>'double',
// 7=>'timestamp',
// 8=>'bigint',
// 9=>'mediumint',
// 10=>'date',
// 11=>'time',
// 12=>'datetime',
// 13=>'year',
// 16=>'bit',
// //252 is currently mapped to all text and blob types (MySQL 5.0.51a)
// 253=>'varchar',
// 254=>'char',
// 246=>'decimal'          
          
          
          
     }
     return $val;
}

function msql_insert_id($link)
{
     $val='';
     $ver=substr(phpversion(),0,1);
     if($ver<=5){$val=mysql_insert_id($link);}
     if($ver>=7){$val=mysqli_insert_id($link);}
     return $val;
}

function msql_errno($link)
{
     $val='';
     $ver=substr(phpversion(),0,1);
     if($ver<=5){$val=mysql_errno($link);}
     if($ver>=7){$val=mysqli_errno($link);}
     return $val;
}

function msql_error($link)
{
     $val='';
     $ver=substr(phpversion(),0,1);
//      $ver=7;
     if($ver<=5){$val=mysql_error($link);}
     if($ver>=7){$val=mysqli_error($link);}
     return $val;
}

?>