<?php
/* MT4Analysis - Add/Change/Delete EAs
   Copyright (C) 2009, 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 */

// initialize session
session_start();

require '../lib/constants.php';
require '../lib/mt4analysis.php';
require '../lib/db.php';

// db must be present
if (!isset($_SESSION['dname']) || strlen($_SESSION['dname']) <= 0)
   die('database not set');

function check_sql($com)
{
   /* Check one of the sql filter statements. Returns 'false' if the sql
      statement is in error, 'true' otherwise. */
   global $dbh;


   $query = 'SELECT id, description, magic FROM ea WHERE 0=1 AND ' . $com;
   // puts("<P>query=$query");

   try
      {
      if (!$stmt = $dbh->prepare($query))
         {
         // puts('<P>prepare failed</P>');
         return(false);
         }

      if (!$stmt->execute())
         {
         // puts('<P>execute failed</P>');
         return(false);
         }
      }
   catch(PDOException $e)
      {
      // puts('<P>exception</P>');
      return(false);
      }

   return(true);
}

// change ID supplied?
if (isset($_GET['c']) && strlen($_GET['c']) > 0)
   $change_id = $_GET['c'];
else
   $change_id = '';

// change submit ID supplied?
if (isset($_GET['cs']) && strlen($_GET['cs']) > 0)
   $change_submit_id = $_GET['cs'];
else
   $change_submit_id = '';

$database_driver = DATABASE_DRIVER;
$db = mt4a_dbname();
$_SESSION['rpath_2_root'] = '..';
$title = 'Add/Change/Delete Expert Advisors';

// open database
try
   {
   $dbh = new PDO("$database_driver:$db");
   }
catch(PDOException $e)
   {
   db_error($e->getMessage(), $db);
   die();
   }

// delete record
if (isset($_GET['d']) && strlen($_GET['d']) > 0)
   {
   // make sure database is in rw mode
   db_mode(true);

   $id = $_GET['d'];
   $mes = "DELETE from ea WHERE id = '$id'";

   try
      {
      if (!$stmt = $dbh->prepare($mes))
         die('PDO prepare failed(delete ea record), SQL query syntax error?');

      if (!$stmt->execute())
         die('Delete of ea record failed.');
      }
   catch(PDOException $e)
      {
      db_error($e->getMessage(), $db);
      die();
      }
   }

// on record change, load fields
if ($change_id != '')
   {
   $query = 'SELECT id, description, magic FROM ea WHERE id = ';
   $query .= "'" . $change_id . "'";

   try
      {
      if (!$stmt = $dbh->prepare($query))
         die('PDO prepare failed(load ea record), SQL query syntax error?');

      if ($stmt->execute())
         $ea_row = $stmt->fetch(PDO::FETCH_ASSOC);
      }
   catch(PDOException $e)
      {
      db_error($e->getMessage(), $db);
      die();
      }
   }

/* 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);
   }

// if form has not been submitted, display it
if (!isset($_POST['submit']))
   {
puts('<HTML>');
puts('<HEAD>');
puts("<TITLE>Mt4Analysis - $title</TITLE");
puts('</HEAD>');
puts('<BODY>');
puts("<A NAME='top'></A>");
page_header($title);
puts("<H2>Database: {$_SESSION['dname']}</H2>");
puts("<P><TABLE BORDER='2'>");

// different form action depending on whether a change record is in effect
$mes = "<FORM NAME='ea' ACTION='{$_SERVER['PHP_SELF']}";

if ($change_id != '')
   $mes .= "?cs=$change_id' ";
else
   $mes .= "' ";

$mes .= "METHOD='POST'>";
puts($mes);
puts('<TR>');
puts('<TH>Description</TH>');

if ($change_id != '')
   $desc = $ea_row['description'];
else
   $desc = '';

$mes = "<TD><INPUT TYPE='TEXT' SIZE='60' NAME='desc' VALUE='$desc' ";
$mes .= "onKeyUp='if(this.value==\"\" || document.ea.magic.value == \"\")";
$mes .= "{document.ea.submit.disabled=\"disabled\";}else";
$mes .= "{document.ea.submit.disabled=\"\";}'>";
puts($mes);
?>
</TD>
</TR>
<TR>
<TH>Magic(sql)</TH>
<?php
if ($change_id != '')
   $magic = $ea_row['magic'];
else
   $magic = '';

$mes = "<TD><INPUT TYPE='TEXT' SIZE='60' NAME='magic' VALUE=\"$magic\" ";
$mes .= "onKeyUp='if(this.value==\"\" || document.ea.desc.value == \"\")";
$mes .= "{document.ea.submit.disabled=\"disabled\";}else";
$mes .= "{document.ea.submit.disabled=\"\";}'>";
puts($mes);
?>
<TR>
<TD>&nbsp;</TD>
<TD><INPUT TYPE='SUBMIT' NAME='submit' VALUE='Submit' disabled />
</TD>
</TR>
</FORM>
</TABLE>
</P>
<!-- Javascript set focus on first form field -->
<SCRIPT LANGUAGE="Javascript">
document.ea.desc.focus();
</SCRIPT>
<P>Good examples of magic sql line are:
<UL>
<LI>magic = 300 - which will exactly match magic 300
<LI>magic like '300%' - which will match any magic starting with 300
<LI>magic like '200%' and magic <> 20091 and magic <> 20092 - any magic starting
with 200 but not 20091 and not 20092
<LI>(magic like '51%' or magic like '61%') - any magic starting with 51
or starting with 61, the brackets are necessary because of the 'or'
</UL></P>
<P>
<TABLE BORDER='2'>
<TR>
<TH>ID</TH>
<TH>Description</TH>
<TH>Magic(Sql)</TH>
<TH>Action</TH>
</TR>
<?php
// display all records in another table
$query = 'SELECT id, description as desc, magic FROM ea';

try
   {
   if (!$stmt = $dbh->prepare($query))
      die('PDO prepare failed(ea), SQL query syntax error?');

   if ($stmt->execute())
      {
      while($row = $stmt->fetch(PDO::FETCH_ASSOC))
         {
         puts('<TR>');
         tableputd($row[id], 'C');
         tableputd($row['desc']);
         tableputd($row['magic']);
         puts("<TD><A HREF='ea.php?c={$row['id']}'>Change</A> | ");
         puts("<A HREF='ea.php?d={$row['id']}'>Delete</A></TD>");
         puts('</TR>');
         }

      puts('</TABLE>');
      }
   else
      puts('</TABLE><P>No ea records on file</P>');
   }
catch(PDOException $e)
   {
   db_error($e->getMessage(), $db);
   die();
   }

   puts('</P>');
   // end of form display before submission
   }
else
   {
   // form has been submitted, validate it
   $mes = '';
 
   // description must be present
   if (!isset($_POST['desc']) || strlen($_POST['desc']) <= 0)
      $mes = 'Description must be present';

   // magic must be present
   if (!isset($_POST['magic']) || strlen($_POST['magic']) <= 0)
      $mes = 'SQL code to identify magic number must be present';

   if ($mes == '' && !check_sql($_POST['magic']))
      $mes = 'Magic SQL has a syntax error in it (not a valid SQL statement)';

   if ($mes == '')
      {
      // form is clean
      // make sure database is in rw mode
      db_mode(true);

      if ($change_submit_id == '')
         {
         // insert new ea record
         $mes = 'INSERT INTO ea (id, description, magic) ';
         $mes .= 'VALUES(NULL, ';
         $mes .= sql_addquotes($_POST['desc'], true);
         $mes .= sql_addquotes($_POST['magic']) . ')';
         }
      else
         {
         // modify account record
         $mes = 'UPDATE ea SET ';
         $mes .= 'description = ' . sql_addquotes($_POST['desc'], true);
         $mes .= 'magic = ' . sql_addquotes($_POST['magic']) . ' ';
         $mes .= "WHERE id = '{$change_submit_id}'";
         }

      try
         {
         if (!$stmt = $dbh->prepare($mes))
            die('PDO prepare failed(save cp record), SQL syntax error?');

         if (!$stmt->execute())
            die('cp record save failed');
         }
      catch(PDOException $e)
         {
         db_error($e->getMessage(), $db);
         die();
         }

      // reload page
      $fname = $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
      header("Location: http://$fname");
      exit;
      }
   else
      {
      // validation error, display error and ask user to try again
      puts('<HTML>');
      puts('<HEAD>');
      puts("<TITLE>Mt4Analysis - $title</TITLE>");
      puts('</HEAD>');
      puts('<BODY>');
      page_header($title);
      p("<CENTER>$mes</CENTER>");
      p("<CENTER><A HREF='{$_SERVER['PHP_SELF']}'>Try Again</A></CENTER>");
      }
   }

require '../misc/footer.php';
?>
</BODY>
</HTML>

