<?php
/* MT4Analysis - SQL Command line interface (CLI).
   Copyright (C) 2009-2010, Future Lab.

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, get a copy via the Internet at
   http://gnu.org/copyleft/gpl.html or write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston,
   MA 02111-1307 USA

   You can contact the author via email at rsmereka@future-lab.com

   Original version. Jul/2009, Rick Smereka

   Removed inline documentation and creation of view. Jul/2010,
   Rick Smereka */

// initialize session
session_start();

require '../lib/constants.php';
require '../lib/parse.php';
require '../lib/mt4analysis.php';
require '../lib/db.php';
require '../lib/datime.php';
require '../lib/sqlite_udf.php';

// no set value in drop-down constant
define('DD_NULL', '00');

// no set display in drop-down constant
define('DDD_NULL', '--Select--');

// html null drop-down value option line, not selected
$dd_null_ns = "<OPTION VALUE='" . DD_NULL . "'>" . DDD_NULL . '</OPTION>';

// html null drop-down value option line, selected
$dd_null_sel = "<OPTION VALUE='" . DD_NULL . "' SELECTED>" . DDD_NULL; 
$dd_null_sel .= '</OPTION>';

$database_driver = DATABASE_DRIVER;
$_SESSION['rpath_2_root'] = '..';

function set_dd_vars()
{
   // Populate drop-down session variables based on item changed.
   /* when any drop-down value is changed, the new value is passed as
      a 'GET' variable and the form is reloaded, all drop-down values
      are stored in session variables, any drop-down that has not been
      set has no corresponding session variable, 'GET' and 'SESSION'
      variable names are codes: 'dd' for dropdown 
      followed by the drop-down number, for example: 'dd1' is the
      database file name dropdown (the first one) and 'dd2' is the
      account name dropdown */

   for($i = 1; $i <= 2; $i++)
      {
      $idx = 'dd' . $i;

      // if 'GET' var is set, save it in a 'SESSION' var
      if (isset($_GET[$idx]) && strlen($_GET[$idx]) > 0)
         {
         $_SESSION[$idx] = $_GET[$idx];

         // populate session var logic
         switch($i)
            {
            case 1:
               // database changed
               $_SESSION['dname'] = '';
               $_SESSION['dd1'] = $_GET['dd1'];
               $_SESSION['dname'] = $_SESSION['dd1'];
               $_SESSION['dd2'] = DD_NULL;
               $_SESSION['account'] = DD_NULL;
               break;

            case 2:
               // account changed
               $_SESSION['dd2'] = $_GET['dd2'];
               $_SESSION['account'] = $_SESSION['dd2'];
               break;
            }
         }
      }
}

$title = 'SQL Command Line Interface (CLI)';
?>
<HTML>
<HEAD>
<?php puts("<TITLE>Mt4Analysis - $title</TITLE>"); ?>
<SCRIPT language=Javascript>
function reload(opt, fname, idx)
{
   var val = opt[opt.selectedIndex].value;
   self.location = fname + '?' + idx + '=' + urlencode(val);
}
function urlencode(inputString)
{
   var encodedInputString=escape(inputString);
   encodedInputString = encodedInputString.replace("+", "%2B");
   encodedInputString = encodedInputString.replace("/", "%2F");        
   return encodedInputString;
}
</SCRIPT>
</HEAD>
<BODY>
<A NAME="top"</A>
<?php
/* some Php versions still have 'magic quotes' turned on and since
   I cannot turn this off at runtime, the following code removes
   the quotes from the I/O arrays, taken from
   http://php.net/manual/en/security.magicquotes.disabling.php */
if (get_magic_quotes_gpc())
   {
   function stripslashes_deep($value)
      {
         $value = is_array($value) ?  array_map('stripslashes_deep', $value) :
                                      stripslashes($value);
         return $value;
      }

   $_POST = array_map('stripslashes_deep', $_POST);
   $_GET = array_map('stripslashes_deep', $_GET);
   $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
   $_REQUEST = array_map('stripslashes_deep', $_REQUEST);
   }

page_header($title);
set_dd_vars();
puts("<TABLE BORDER='2' ALIGN='CENTER'>");
puts("<FORM NAME='com' ACTION='{$_SERVER['PHP_SELF']}' METHOD='POST'>");
puts('<TR>');
puts('<TH>Database File Name</TH>');
$mes = "<TD><SELECT NAME='dd1' onchange=\"reload(this.form.dd1.options, ";
$mes .= "'{$_SERVER['PHP_SELF']}', 'dd1')\">";
puts($mes);
$sel = (isset($_SESSION['dd1'])) ? $_SESSION['dd1'] : DD_NULL;
$mes = ($sel == DD_NULL) ? $dd_null_sel : $dd_null_ns;
puts($mes);

// get a list of every file in the trade path
$spath = (IN_PRODUCTION) ? $_SERVER['DOCUMENT_ROOT_OLD'] : 
                           $_SERVER['DOCUMENT_ROOT'];
$dpath = (IN_PRODUCTION) ? TRADE_PATH_PRODUCTION : TRADE_PATH_LOCAL;
$db_path = $spath . $dpath;
// p("spath=$spath,dpath=$dpath,db_path=$db_path");
$db_files = scandir($db_path);
$cnt = 1;

// populate dropdown (skip current and parent dot references)
foreach ($db_files as $db_file)
   {
   if ($db_file == '.' || $db_file == '..')
      continue;

   $mes = "<OPTION VALUE='$db_file'";

   if ($db_file == $sel)
      $mes .= ' SELECTED';

   $mes .= ">$db_file</OPTION>";
   puts($mes);
   $cnt++;
   }
?>
</SELECT>
</TD>
</TR>
<TR>
<TH>Account Name</TH>
<?php
$mes = "<TD><SELECT NAME='dd2' onchange=\"reload(this.form.dd2.options, ";
$mes .= "'{$_SERVER['PHP_SELF']}', 'dd2')\">";
puts($mes);
$sel = (isset($_SESSION['dd2'])) ? $_SESSION['dd2'] : DD_NULL;
$mes = ($sel == DD_NULL) ? $dd_null_sel : $dd_null_ns;
puts($mes);

// only populate account dropdown if there is a valid database
if (isset($_SESSION['dd1']) && $_SESSION['dd1'] != DD_NULL)
   {
   // build database path and name
   $db = mt4a_dbname();
   $query = 'SELECT id, description FROM account';
 
   try
      {
      $dbh = new PDO("$database_driver:$db");

      if (!$stmt = $dbh->prepare($query))
         {
         puts('</SELECT></TD></TR>');
         $mes = '<P><CENTER>Unable to open database, is this an SQLite';
         $mes .= 'database?</CENTER></P>';
         puts($mes);
         die();
         }

      if ($stmt->execute())
         {
         while($row = $stmt->fetch(PDO::FETCH_ASSOC))
            {
            $mes = "<OPTION VALUE='{$row['id']}'";

            if ($row['id'] == $sel)
               $mes .= ' SELECTED';

            $mes .= ">{$row['description']}</OPTION>";
            puts($mes);
            }
         }
      else
         die('Unable to locate dd2 data');
      }
   catch(PDOException $e)
      {
      db_error($e->getMessage(), $db);
      die();
      }
   }
?>
</SELECT>
</TD>
</TR>
<TR>
<TH>Command</TH>
<TD>
<?php
$mes = "<TEXTAREA NAME='command' ROWS='10' COLS='80' VALUE='' ";
$mes .= "onKeyUp='if(this.value==\"\" || document.com.dd1.value==\"\" || ";
$mes .= "document.com.dd1.value==\"00\" || document.com.dd2.value==\"\" || ";
$mes .= "document.com.dd2.value==\"00\")";
$mes .= "{document.com.submit.disabled=\"disabled\";}else";
$mes .= "{document.com.submit.disabled=\"\";}'>";
puts($mes);
?>
</TEXTAREA></TD>
</TR>
<TR>
<TD>&nbsp;</TD>
<?php
// only enable submit button when all required values are present (dd1-2)
$state = true;

if (!isset($_SESSION['dd1']) || $_SESSION['dd1'] == '00')
   $state = false;

if ($state && (!isset($_SESSION['dd2']) || $_SESSION['dd2'] == '00'))
   $state = false;

$mes = "<TD><INPUT TYPE='submit' NAME='submit' VALUE='Run Command'";

if (!$state)
   $mes .= ' disabled ';

$mes .= '/>';
puts($mes);
?>
</TD>
</TR>
</FORM>
</TABLE>
<!-- Javascript set focus on command field -->
<SCRIPT LANGUAGE="Javascript">
document.com.command.focus();
</SCRIPT>
<?php
// execute command when submitted
if (isset($_POST['command']) && trim($_POST['command']) != '')
   {
   $dbf = mt4a_dbname();
   $account = $_SESSION['account'];
   $command = $_POST['command'];
   br('');
   br(">$command");

   /* if database is in read-only mode deny access to 'delete',
      'insert' and 'update' commands */
   if (DATABASE_RO)
      {   
      if (stristr($command, 'delete'))
         db_mode();

      if (stristr($command, 'insert'))
         db_mode();
     
      if (stristr($command, 'update'))
         db_mode();
      }

   // database is already open
   try
      {
      // hook in SQLite UDF's
      // ea id
      if (!$dbh->sqliteCreateFunction('eaid', 'ea_id', 1))
         die('sqliteCreateFunction failed(eaid)');

      // ea description
      if (!$dbh->sqliteCreateFunction('eadesc', 'ea_desc', 1))
         die('sqliteCreateFunction failed(eadesc)');

      // pips
      if (!$dbh->sqliteCreateFunction('pips', 'pips', 1))
         die('sqliteCreateFunction failed(pips)');

      // balance
      if (!$dbh->sqliteCreateFunction('balance', 'account_balance', 1))
         die('sqliteCreateFunction failed(balance)');
      }
   catch(PDOException $e)
      {
      db_error($e->getMessage(), $db);
      die();
      }

   // set session vars needed by udf's
   $query = 'SELECT broker FROM account WHERE id = ' . $account;
   $broker = db_get_one($dbh, $query, 'broker');

   if ($broker == '')
      die('unable to locate broker id');

   $query = 'SELECT fiveDecimals FROM broker WHERE id = ' . $broker;
   $tmp = db_get_one($dbh, $query, 'fiveDecimals');

   if ($tmp == '')
      die('unable to locate is 5 decimals(broker)');
   else
      $_SESSION['fiveDecimals'] = $tmp;

   $output_row = 0;

   try
      {
      if (!$stmt = $dbh->prepare($command))
         {
         puts('db prepare failed,SQL syntax error?');
         exit();
         }

      if ($stmt->execute())
         {
         puts('database result:<BR />');

         while($row = $stmt->fetch(PDO::FETCH_ASSOC))
            {
            $output_row++;
            echo "row($output_row):";
            print_r($row);
            echo "<BR />";
            }
         }
      else
         {
         puts('database execute failed<BR />');
         exit();
         }
      }
   catch(PDOException $e)
      {
      db_error($e->getMessage(), $db);
      die();
      }

   }

p("<CENTER><A HREF='../doc/index.php#cli'>CLI Help</A></CENTER>");
require 'footer.php';
?>
</BODY>
</HTML>

