<?php
//    record submitted data (in submitted mysql database)
//  or to simple history

// submitted data structure:
//  clientid varchar(40) NOT NULL ,    -- from client
//  round int(4) not null ,            -- from client
//     PRIMARY KEY (clientid,round)  ,
//  servertime int,                  -- COMPUTED by server upon reciept of submitted data
//  clienttime varchar(40) ,         -- from client
//  notFinal int(2),                  -- from client
//  ct int(2),                       -- from client
//  entry text,                      -- from client
//  comment tinytext         -- from client

// fields submitted:
// todo=401,
// tocurrent=0/1  (deprecated, controls if added to full, or current, submitted database)
// session=sessionName,
// verify=a verification string = escaped(clientId ' ' clienttime)
// submit_status: client,round information for submitStatus storage (
// message: a descriptive message about this submission
//    typically:  id=anid & name=aname & time=jsIntegerTime & round=roundNumber & action=Submit
// content: partially escaped xml-line with content (variables/values filled in by participant)
//      Content contains <data ...> <vals>, <vars>, <status> </data>
//                <data includes attributes: id, round, ct, notFinal, time
// these are and saved to the above (comment=message)

// Note: these maybe "double" escaped -- the browser escapes an "escaped" sequence (internal escaping is used
//       to preserve parsing order ). apache's unescaping will not yield the original 'internally escaped' string


require("phpVars.php");

// extract request fields (typically in  a POST)
  $todo='';
  $tocurrent='0';
  $sessName='';
  $verify='';
  $sstatus='';
  $comment='';
  $content='';
  foreach ($_REQUEST as $vname=>$oof) {
     $avar=trim(strtoupper($vname)) ;
     if ($avar=='TODO') $todo=trim($oof);
     if ($avar=='TOCURRENT') $tocurrent=trim($oof);
     if ($avar=='NAME' || $avar=='SESSION') $sessName=trim($oof);
     if ($avar=='VERIFY') $verify=trim($oof);
     if ($avar=='SUBMIT_STATUS' || $avar=='SUBMITSTATUS' || $avar=='STATUS') $sstatus=trim($oof);
     if ($avar=='MESSAGE' || $avar=='COMMENT') {
        $comment=trim($oof);
     }
     if ($avar=='CONTENT' || $avar=='CONTENTS') {
       $content=trim($oof);
     }
  }

if ($sessName=='') {
  header('Content-type:text/plain');
  print '- Error. No NAME or SESSION= in call to submitEntry.php ';
  exit ;
}

if ($tocurrent!=='0' && $tocurrent!=='') {
    header('Content-type:text/plain');
    print '- Error.  tocurrent=1 is no longer supported by dSUrvey (in submitEntry.php) ';
    exit ;
}

// open databsae (exit on error in connectSurveyDatabase)
$link=connectDsurveyDatabase($sessName);
$mdata=$currentDatabase ;

// simpleHistory? call something else
//       session=sessname&message=short_message&contents=partiallyEscapedXMLDataRow
if ($todo=='4011') {
    $ares=goto4011($comment,$content,$mdata,$link);
    mysql_close($link);
//  header('Content-type:text/plain');
    print $ares ;
    exit ;
}

// if here, add to submitted data

// look for prior submission, and failure if there was one?
// march 2011: sstatus notes the client and id, but not round. Thus, "no update"
// implies "only one entry (ct=1) per client/round"
if ($sstatus!=='') {
 $sstatus=strtoupper($sstatus);
 $sql="SELECT * FROM submitStatus WHERE sstatus='$sstatus'" ;
 $qq=mysql_query($sql,$link);
 if (!$qq) {
    header('Content-type:text/plain');
     print '- Error. Unable to read submitStatus table in mysql database ' . $mdata . ': '  . mysql_error();
     mysql_close($link);
     exit ;
  }
  $nmatch=mysql_num_rows($qq);
  if ($nmatch>0) {
     header('Content-type:text/plain');
     print '4 Sorry, you have already submitted an entry for this round=' . $sstatus ;
     mysql_close($link);
     exit ;
  }
}

$idate =time();
$comment2=urldecode($comment);
$verify2=urldecode($verify);

// parse the <data> element in $content, extract attributes
$contents2=trim($content);
$goo0="<?xml version='1.0'?><stuff>".$content.'</stuff>';
$goo=new SimpleXMLElement($goo0);

if (!$goo) {
   header('Content-type:text/plain');
   print '- Error. Unable to parse content (in submitEntry.php) ';
   exit;
}

 $clientid='';  $round='0'; $clienttime='';
 $ct='0';       $notfinal='0';
 $hoo=$goo->data->attributes() ;
 foreach ($hoo as $vname=>$vval) {
  $vv=strtoupper(trim($vname));
  $aval=trim($vval);
   if ($vv=='ID' || $vv=='CLIENTID')  $clientid=$aval  ;
   if ($vv=='ROUND') $round=$aval  ;
   if ($vv=='TIME' || $vv=='CLIENTTIME') $clienttime=$aval;
   if ($vv=='CT') $ct=$aval  ;
   if ($vv=='NOTFINAL') $notfinal=$aval  ;
 }

if ($clientid=='') {
    header('Content-type:text/plain');
    print '- Error.  no ID= attribute in <data> field (in submitEntry.php) ';
    exit ;
}

// save to submitted database (possibly a replace) - key is clientid, round, ct

  $sql="REPLACE INTO submitted (clientid,round,servertime,clienttime,notFinal,ct,entry,comment)
              VALUES
      ('$clientid','$round','$idate','$clienttime','$notfinal','$ct','$content','$comment2') ";
  $qq=mysql_query($sql,$link);
  if (!$qq) {
     mysql_close($link);
     header('Content-type:text/plain');
     print '- Error. Unable to add entry  to SUBMITTED table in mysql database ' . $mdata . ': '  . mysql_error();
     exit ;
  }

// add entry to submitStatus
if ($sstatus!=='') {
  $sql="INSERT INTO submitStatus (sstatus,clienttime)
              VALUES
     ('$sstatus','$clienttime') ";
  $qq=mysql_query($sql,$link);
  if (!$qq) {
     mysql_close($link);
     header('Content-type:text/plain');
     print '- Error. Unable to add entry  to SUBMITSTATUS table in mysql database ' . $mdata . ': '  . mysql_error();
     exit ;
  }
}

mysql_close($link);

header('Content-type:text/plain');
print "Ok " . $verify2 ;

// Inserted ( $qq) for $clientid and round $round, submitted at clienttime= $clienttime (ct, notfinal= $ct , $notfinal :
//    <ul>
//    <li> submitstatus = $sstatus
//    <li> verify= $verify2
//    <li> commentx= $comment2
//   <li> content = " . $content . "
//   </ul>
//  ";

 exit ;

 /* note: this is no longer required (pull stuff from <data>, rather than from message field
$cval4=preg_replace("/\s+/","", $comment2) ;             // remove spaces
$clist=explode('&',$cval4);
for ($ith=0;$ith<count($clist);$ith++) {                 // id, round, ct, notFinal, time
  $t1=trim($clist[$ith]);
  $t2=explode('=',$t1);
  $vv=strtoupper($t2[0]);
  $aval=trim($t2[1]);
   if ($vv=='ID' || $vv=='CLIENTID')  $clientid=$aval  ;
   if ($vv=='ROUND') $round=$aval  ;
   if ($vv=='TIME' || $vv=='CLIENTTIME') $clienttime=$aval;
   if ($vv=='CT') $ct=$aval  ;
   if ($vv=='NOTFINAL') $notfinal=$aval  ;
}
*/

//====================================
// simplehistory
function goto4011($comment,$contents,$mdata,$link) {

  $sql="INSERT INTO simpleHistory (content,comment)
              VALUES
     ('$contents','$comment') ";
  $qq=mysql_query($sql,$link);
  if (!$qq) {
     mysql_close($link);
    return '-Error. Unable to add entry  to SIMPLEHISTORY table in mysql database ' . $mdata . ': '  . mysql_error();
  }

 return 'ok simplHistoryUpload';
}


 ?>

