<?php

//$AllowedIp = array ('83.246.136.189');  // List of allowed ip

if (!isset ($_POST['Type'])) {

   header ('Content-Type: text/html');

?>
<html>
 <head>
  <title>Call Office Proxy script v1.2</title>
 </head>
 <body>
  <h1>Call Office Proxy script v1.2</h1>
  <p>Call Office Proxy script is installed correctly.</p>
 </body>
</html>
<?

}
else {

   header ('Content-type: application/json');

   function ToJSON ($Text)
   {
      return str_replace (array ('\\'  , "\n", "\r", "\t", '"' , "\x08", "\x0b"),
                          array ('\\\\', '\n', '\r', '\t', '\"', '\b'  , '\v'  ), $Text);
   }

   function OutError ($Error)
   {
      die ('{Status: "Error", Description: "'.ToJSON ($Error).'"}');
   }

   if (isset ($AllowedIp)) {
      if (!in_array (getenv ('REMOTE_ADDR'), $AllowedIp)) OutError ('Not allowed access from '.getenv ('REMOTE_ADDR'));
   }

   if (isset ($_POST['Type'    ]) and
       isset ($_POST['User'    ]) and
       isset ($_POST['Password'])) {

      if (function_exists ('get_magic_quotes_gpc')) {
         if (get_magic_quotes_gpc ()) foreach ($_POST as $Key => $Value) $_POST[$Key] = stripslashes ($Value);
      }

      if ($_POST['Type'] == 'MySQL') {

         function MySQLError ($Connection, $Err)
         {
            $TextError = @mysqli_error ($Connection);

            if ($TextError == '') $TextError = $Err;
            if ($TextError == '') $TextError = 'unknown mysql error';

            @mysqli_query ($Connection, 'ROLLBACK');

            OutError ($TextError);
         }

         $Host = isset ($_POST['Host'])? $_POST['Host'] : 'localhost';
         $Port = isset ($_POST['Port'])? $_POST['Port'] : 3306; //3389;

         $Socket = null;

         if (!is_numeric ($Port)) {

            if (substr ($Port, 0, 1) != '/') {
               $Socket = "\\\\.\\pipe\\".$Port;
               $Host = '.';
            } else $Host = 'localhost';

            $Port = null;
         }

         try {

            $Connection = @mysqli_connect ($Host, $_POST['User'], $_POST['Password'], null, $Port, $Socket) or MySQLError ($Connection, mysqli_connect_error ());

            if (isset ($_POST['DBName'])) mysqli_select_db ($Connection, $_POST['DBName' ]) or MySQLError ($Connection, 'Database not found');

            if (isset ($_POST['Charset'])) mysqli_query ($Connection, '/*!40101 SET NAMES \''.$_POST['Charset'].'\' */') or MySQLError ($Connection, 'Can not set character set');
            else mysqli_query ($Connection, '/*!40101 SET NAMES \'utf8\' */');

            $Out = '{Status: "OK", Result:[';

            mysqli_query ($Connection, 'BEGIN');

            for ($NQuery = 1; $NQuery < 1000; $NQuery++) {

               if (!isset ($_POST['Q'.$NQuery])) break;

               if ($NQuery != 1) $Out .= ',';

               $Request = $_POST['Q'.$NQuery];

               if ($Request == 'info') {
                  $Out .= '{Server: "'.ToJSON (mysqli_get_server_info ($Connection)).'", '.
                           'Client: "'.ToJSON (mysqli_get_client_info ($Connection)).'", '.
                            'Proto: "'.ToJSON (mysqli_get_proto_info  ($Connection)).'", '.
                             'Host: "'.ToJSON (mysqli_get_host_info   ($Connection)).'"}';
               }
               else {

                  $Result = mysqli_query ($Connection, $Request) or MySQLError ($Connection, 'Unknown query execution error');

                  if ($Result === true) {
                     $Out .= '{AffectedRows: '.mysqli_affected_rows ($Connection).'}';
                  }
                  else {

                     $Out .= '{Fields: [';

                     for ($i = 0; $i < mysqli_num_fields ($Result); $i++) {

                        $Field = mysqli_fetch_field_direct ($Result, $i);

                        if ($i != 0) $Out .= ',';

                        $Out .= '{Name: "'.ToJSON ($Field->name  ).'", '.
                                 'Type: "'.ToJSON ($Field->type  ).'", '.
                                'Flags: "'.ToJSON ($Field->flags ).'", '.
                               'Length: "'.ToJSON ($Field->length).'"}';
                     }

                     $Out .= '], Data: [';

                     for ($i = 0; $i < mysqli_num_rows ($Result); $i++) {

                        $Row = mysqli_fetch_row ($Result);

                        if ($i != 0) $Out .= ',';

                        $Out .= '[';

                        for ($j = 0; $j < mysqli_num_fields ($Result); $j++) {
                           if ($j != 0) $Out .= ',';
                           if (is_null ($Row[$j])) $Out .= 'null';
                           else                    $Out .= '"'.ToJSON ($Row[$j]).'"';
                        }

                        $Out .= ']';
                     }

                     $Out .= ']}';

                     mysqli_free_result ($Result);
                  }
               }
            }

            $Out .= ']}';

            echo $Out;

            mysqli_query ($Connection, 'COMMIT');
         }
         catch (mysqli_sql_exception $Err) {
            OutError ($Err->getMessage ());
         }
         catch (Throwable $Err) {
            OutError ($Err->getMessage ());
         }

      } else OutError ('Server type '.$_POST['Type'].' is not supported');
   } else OutError ('Malformed request');
}
?>