<?php
//    Post a file, or files, to the server: several variants
//postSessionFilesHeader='todo=4';  -- CREATE A NEW SESSION
//postFileHeader='todo=7';
//postInstrumentFileHeader='todo=76';
// retrieve uploaded file (see uploadFile.php for template) ($todo==77) {
// create/overwrite file in PINFO/ ($todo==124) {
// echo back a posted string, for saving as a file on local disk ($todo==500) {
// 711 -- save a note to notes database, or read note ($todo==711) {
// create/overwrite dsurvey.htm file ($todo==802) {


require("phpVars.php");

// if no todo argumeint in body (of the POST), error

if (!array_key_exists('todo',$_REQUEST)) {
  header('Content-type: text/plain ');
  print 'Sorry. No todo= argument in call to postFile.php ';
  exit ;
}

$todo=$_REQUEST['todo'] ;
$todo2=extractRequestVar('todo2','0','');
//print 'xxxx ' . $todo2 ;
//return 0;



// create basic file and directories for a session
if ($todo==4) {
    header("Content-Type: text/plain");
    $ugly=goAction4($sessions_dir,$instruments_dir,$data_dir,$pinfo_dir,$hdrMysql);
    exit;
}


// modify/overwrite a parameter file for a session (using content)
if ($todo==7) {
    header("Content-Type: text/plain");
    $ugly=goAction7($sessions_dir,$instruments_dir,$data_dir,$pinfo_dir,$todo2);
    exit;
}


// modify/overwrite a parameter file for an instrument (using content)
if ($todo==76) {
    header("Content-Type: text/plain");
    if ($todo2=='1' || $todo2=='2' || $todo2=='3' || $todo2=='11') {                     // instrument
        $ugly=goAction76($sessions_dir,$instruments_dir,$data_dir,$pinfo_dir,$todo2);
    } else {                                          // session
        $ugly=goAction7($sessions_dir,$instruments_dir,$data_dir,$pinfo_dir,$todo2);
    }
    exit;
}


// retrieve uploaded file (see uploadFile.php for template)
if ($todo==77) {
    header("Content-Type: text/plain");
    $ugly=goAction77($sessions_dir,$instruments_dir,$data_dir,$pinfo_dir,$todo2);
    exit;
}

// create/overwrite file in PINFO/
if ($todo==124) {
    header("Content-Type: text/plain");
    $ugly=goAction124($sessions_dir,$instruments_dir,$data_dir,$pinfo_dir);
    exit;
}


// echo back a posted string, for saving as a file on local disk
if ($todo==500) {
     header('Content-Type: text/plain; charset=iso-8859-1');
     $ugly=goAction500($sessions_dir,$instruments_dir,$data_dir,$pinfo_dir) ;
     exit ;
}

// 711 -- save a note to notes database, or read note
if ($todo==711) {
     header('Content-Type: text/plain; charset=iso-8859-1');
     $ugly=goAction711($sessions_dir) ;;
     exit ;
}

// create/overwrite dsurvey.htm file
if ($todo==802) {
     header('Content-Type: text/plain; charset=iso-8859-1');
     $ugly=goAction802($wwwdir) ;
     exit ;
}
print 'Error: unknown action = ' . $todo ;
exit;


//==================
// create a  new session: create session descriptor file, session directory, data directory, pinfo directoyr
// and copy parameter (and possiblye Scenario and Scenario list) files to session directory

/*
    ------- MYSQL databases created for each session ---

basic: Basic session info
   instrument, filelist, creation

servervars: Store varname as a serverVar:   (varname is key)
   varname, varvalue, modified

statusVars: Store varname as a statusVar  (varname is key)
   varname,varvalue, modified

clientstatus: Store client status (such as last requested variable)    (clientid is key)
   clientid , servertime, clienttime, state, message, varname, varvalue

submitted:   Store data "submitted" by clients (clientid, round, ct are keys)
   clientid, round, ct  , servertime,clienttime, notfinal ct, entry, comment

submitStatus: Store client submission status (time/comment of last submission (sStatus is key)
   sstatus,clienttime

simpleHistory:  store simple history information uploaded by clients (arow is key, auto incremented)
     arow, round, servertime, content, comment

clientIds: information about a client (clientid is key)
  clientid, clientName, refId, serverTime, content

assignCID: assigning unique client IDs  (used if server-side id assignation is enabled) (clientid is auto-incremented key)
   clientid, clientName, servertime

messages: store dSurvey messages
  clientId varchar(40) NOT NULL ,
  servertime int,
  content text,
  subject varchar(250),
  cTime varchar(20) ,
  fromId varchar(30),
  fromName varchar(80),
  toList varchar(1000),
  urgent int,
  stuff text

 
messagesAdmin : info on dsurveyMessages
   clientId varchar(40) NOT NULL ,
    PRIMARY KEY (clientId)  ,
   lastReadTime int,
   newFlag  int

The next several xxxxData databases are used to store "archives" of results, by round.

generalData: store general data (round is key) -- one entry per round
  round int(4) not null ,
     PRIMARY KEY (round)  ,
  servertime int,
  entry text

participantsData: store participants data (round is key) -- one entry per round
  round int(4) not null ,
     PRIMARY KEY (round)  ,
  servertime int,
  entry text

usersData: store users  data (round is key) -- one entry, with records for many clients, per round
  round int(4) not null ,
     PRIMARY KEY (round)  ,
  servertime int,
  entry text

resultsData: store results data (round is key) -- one entry, with records for many clients, per round
  round int(4) not null ,
     PRIMARY KEY (round)  ,
  servertime int,
  entry text

historyData: store history data (round is key) -- one entry, with records for many clients, per round
  round int(4) not null ,
     PRIMARY KEY (round)  ,
  servertime int,
  entry text

customData: store custom data (possibly several kinds) (name and round is key) -- one entry, with records for many clients, per round
  round int(4) not null ,
  cname varchar(60) not null,
     PRIMARY KEY (aname,round)  ,
  servertime int,
  entry text


*/


function goAction4($sessions_dir,$instruments_dir,$data_dir,$pinfo_dir,$hdrMysql) {

$vudate=date(DATE_RFC822)  ;
$idate =time();

  $doscenario=0;
  $filelist='';
  $aname='';
  $doOverWrite='0';
  $content='';
  $todo='0';
  $instName='';
  foreach ($_REQUEST as $vname=>$oof) {
     $avar=trim(strtoupper($vname)) ;
     $toof=trim($oof);
     if ($avar=='DOSCENARIO') $doscenario=$toof;
     if ($avar=='FILELIST') $filelist=$oof ;
     if ($avar=='NAME') $aname=$toof;
     if ($avar=='OVERWRITE') $doOverWrite=$toof;
     if ($avar=='CONTENT') $content=$oof;
     if ($avar=='TODO') $todo=$toof;
     if ($avar=='INSTNAME') $instName=trim($oof);
  }

  if ($aname=='') {
    print 'Sorry. No NAME= argument in call to postFile.php ';
  }
  if ($content=='') {
    print 'Sorry. No content= argument in call to postFile.php ';
    return 0 ;
  }

  $newdir=$sessions_dir . $aname . '/'  ;
  if (file_exists($newdir)) {
       print "Sorry. Session $aname already exists (to use this name, you must first remove the session) ";
       return 0;
  }

  if (!mkdir($newdir)) {
       print "Sorry.  Unable to create directory: $newdir ";
      return 0 ;
  }

   $newfile=$sessions_dir . $aname . '.xml' ;
   $fnum=fopen($newfile,'w');
   if (!$fnum) {
     print "Sorry. Unable to open file: $newfile ";
     return 0 ;
   }
   if (!fwrite($fnum,$content)) {
       print "Sorry. Unable to write to file: $newfile ";
       return 0 ;
   }
   fclose($fnum);

   $backdir=$newdir . 'BACKUP/';
   if (!file_exists($backdir)) {
     if (!mkdir($backdir)) {
        print "Sorry. Unable to create directory: $backdir ";
       return 0 ;
     }
   }

  $dnewdir=$data_dir . $aname . '/';
  if (!file_exists($dnewdir)) {
    if (!mkdir($dnewdir)) {
      print "Sorry. Unable to create DATA/ directory: $dnewdir ";
      return 0 ;
    }
  }

  $pnewdir=$pinfo_dir . $aname . '/';
  if (!file_exists($pnewdir)) {
    if (!mkdir($pnewdir)) {
       print "Sorry. Unable to create PINFO/ directory: $pnewdir ";
       return 0 ;
    }
  }


//  $bb=http_get_request_body(0);
//  print 'Ok '. $doscenario . '=' .  $filelist . '; '. $bb ;
//  exit;

  if ($doscenario==1) {
    $thisIdir=$instruments_dir .  $instName . '/' ;
    $dir=opendir($thisIdir);
    while (!($filename= readdir($dir)) === FALSE) {
         $foof1=$thisIdir . $filename ;
         if (is_dir($foof1)) continue ;
         $foof=$filename . '.0';
         $apath=explode('.',$foof );
         $aext=$apath[1];
         if (strtoupper($aext)=='.XML') continue ;
         $c3s=strtoupper(substr($filename,0,3)) ;
         if ($c3s=='SC_' || $c3s=='SL_') {
            $filelist=$filelist . ' ' . $filename ;
         }
    }       // while
  }         // doscenario

// copy from thisIdir to newdir
 $icopied=0;
 $tcreated=0;

 if ($filelist!='') {
     $f12=explode(' ',$filelist);
     for ($i=0 ; $i<count($f12) ; $i++) {
       $afile=trim($f12[$i]);
       if ($afile=='')   continue ;
       $fromF=$thisIdir . $afile ;
       $toF=$newdir . $afile ;
       if (copy($fromF,$toF)) $icopied++ ;
    }
 }


// create a mysql database
 $link=mysql_connect('localhost','dsurveyAdmin','admin');
 if (!$link) {
   print 'Error. Could not connect to mysql: ' . mysql_error();
   return 1;
 }
$mdata=$hdrMysql . $aname ;
if (!mysql_query("CREATE DATABASE " . $mdata,$link))  {
  print "Error creating mysql database: " . mysql_error();
  return 1 ;
}

// Create table
$qq=mysql_select_db($mdata, $link);
if (!$qq) {
   print 'Error. Unable to select mysql database ' . $mdata . ': '  . mysql_error();
   return 0;
}

$sql = "create table basic
(
  instrument varchar(40),
  filelist text ,
  creation datetime
)";
$qq=mysql_query($sql,$link);
if (!$qq) {
   print 'Error. Unable to create BASIC table in mysql database ' . $mdata . ': '  . mysql_error();
   return 0;
}

// add basic data
$date = new DateTime();
$creation=$date->format('Y-m-d H:i:s') ;    // YYYY-MM-DD HH:MM:SS
$sql="INSERT INTO basic (instrument,filelist,creation)
              VALUES
     ('$instName' ,'$filelist','$creation') ";

$qq=mysql_query($sql,$link);
if (!$qq) {
   print 'Error. Unable to add info to BASIC table in mysql database ' . $mdata . ': '  . mysql_error();
   return 0;
}
$tcreated++ ;

// create server variables table
$sql = "create table servervars
(
  varname varchar(40) NOT NULL ,
  PRIMARY KEY(varname),
  varvalue tinytext ,
  modified int
)";
$qq=mysql_query($sql,$link);
if (!$qq) {
   print 'Error. Unable to create SERVERVARS table in mysql database ' . $mdata . ': '  . mysql_error();
   return 0;
}
// add SERVERVAR data
$sql="INSERT INTO servervars (varname,varvalue,modified)
              VALUES
     ('_created' ,'$idate','$idate') ";

$qq=mysql_query($sql,$link);
if (!$qq) {
   print 'Error. Unable to add info to SERVERVARS  table in mysql database ' . $mdata . ': '  . mysql_error();
   return 0;
}
$tcreated++ ;

// create server status table
$sql = "create table statusvars
(
  varname varchar(40) NOT NULL ,
  PRIMARY KEY(varname),
  varvalue tinytext ,
  modified int
)";
$qq=mysql_query($sql,$link);
if (!$qq) {
   print 'Error. Unable to create STATUSVARS table in mysql database ' . $mdata . ': '  . mysql_error();
   return 0;
}
// add STATUS data

$sql="INSERT INTO statusvars (varname,varvalue,modified)
              VALUES
     ('_created' ,'$vudate','$idate') ";

$qq=mysql_query($sql,$link);
if (!$qq) {
   print 'Error. Unable to add info to STATUSVARS  table in mysql database ' . $mdata . ': '  . mysql_error();
   return 0;
}
$tcreated++ ;

// add  empty users row (for storing space delimited list of users
$sql="INSERT INTO statusvars (varname,varvalue,modified)
              VALUES
     ('users' ,'','$idate') ";

$qq=mysql_query($sql,$link);
if (!$qq) {
   print 'Error. Unable to add users var to STATUSVARS  table in mysql database ' . $mdata . ': '  . mysql_error();
   return 0;
}
$tcreated++ ;


// create  client status table  (will contain current status of client, which may be frequently updated)

//   clientid: id supplied by client
//   servertime: time response was sent to client
//   clienttime=when client asked (javascript time)
//   state= 1 word client status (as provided by client)
//   message=message supplied by client
//   var=variable requested by client
//   value=value returned to client

$sql = "create table clientstatus
(
  clientid varchar(40) NOT NULL ,
  PRIMARY KEY(clientid),
  servertime int,
  clienttime varchar(40) ,
  state varchar(40),
  message tinytext,
  varname varchar(40),
  varvalue tinytext
)";
$qq=mysql_query($sql,$link);
if (!$qq) {
   print 'Error. Unable to create CLIENTSTATUS table in mysql database ' . $mdata . ': '  . mysql_error();
   return 0;
}
// add clientSTATUS data

$sql="INSERT INTO clientstatus (clientid,servertime,clienttime,state,message,varname,varvalue)
              VALUES
     ('_created','$idate','$idate','Created','Database created','_started','$idate') ";

$qq=mysql_query($sql,$link);
if (!$qq) {
   print 'Error. Unable to add info to CLIENTSTATUS  table in mysql database ' . $mdata . ': '  . mysql_error();
   return 0;
}
$tcreated++ ;

//xxxxxxxxxxxxxxxxxxxxxxxxxxxx
// create  submitted table
//  clientid varchar(40) NOT NULL ,    -- from client
//  round int(4) not null ,            -- from client
//     PRIMARY KEY (clientid,round,ct)  ,
//  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


$sql = "create table submitted
(
  clientid varchar(40) NOT NULL ,
  round int(4) not null ,
     PRIMARY KEY (clientid,round,ct)  ,
  servertime int,
  clienttime varchar(40) ,
  notFinal int(2),
  ct int(2),
  entry text,
  comment tinytext
)";

$qq=mysql_query($sql,$link);
if (!$qq) {
   print 'Error. Unable to create SUBMITTED table in mysql database ' . $mdata . ': '  . mysql_error();
   return 0;
}
// add submitted data header row

$sql="INSERT INTO submitted (clientid,round,servertime,clienttime,comment)
              VALUES
     ('_created','-1','$idate','$vudate','for submitted data') ";
$qq=mysql_query($sql,$link);
if (!$qq) {
   print 'Error. Unable to add info to SUBMITTED table in mysql database ' . $mdata . ': '  . mysql_error();
   return 0;
}
$tcreated++ ;


//xxxxxxxxxxxxxxxxxxxxxxxxxxxx
// create  submitStatus table
$sql = "create table submitStatus
(
  sstatus varchar(40) NOT NULL ,
     PRIMARY KEY (sstatus)  ,
  clienttime varchar(40)
)";

$qq=mysql_query($sql,$link);
if (!$qq) {
   print 'Error. Unable to create SUBMITSTATUS table in mysql database ' . $mdata . ': '  . mysql_error();
   return 0;
}
// add submittStatus data header row
$sql="INSERT INTO submitStatus (sstatus,clienttime)
              VALUES
     ('_created','$idate') ";
$qq=mysql_query($sql,$link);
if (!$qq) {
   print 'Error. Unable to add info to SUBMITSTATUS table in mysql database ' . $mdata . ': '  . mysql_error();
   return 0;
}
$tcreated++ ;


// create  simpleHistory table
$sql = "create table simpleHistory
(
  arow int(4) AUTO_INCREMENT NOT NULL ,
     PRIMARY KEY (arow)  ,
  round int(4),
  content text ,
  servertime int,
  comment varchar(120)
)";

$qq=mysql_query($sql,$link);
if (!$qq) {
   print 'Error. Unable to create simpleHistory table in mysql database ' . $mdata . ': '  . mysql_error();
   return 0;
}
// add submittStatus data header row
$sql="INSERT INTO simpleHistory (content,comment,round,servertime)
              VALUES
     ('_created','$idate',-1,'$idate') ";
$qq=mysql_query($sql,$link);
if (!$qq) {
   print 'Error. Unable to add info to SIMPLEHISTORY table in mysql database ' . $mdata . ': '  . mysql_error();
   return 0;
}
$tcreated++ ;

//  xxxxxxxxxx
// create  clientIds table
//   servertime: time client joined  (in js time, rounded to second)
//   clientname: name supplied by client
//   content=xml line supplied by client

$sql = "create table clientids
(
  clientid varchar(40) NOT NULL ,
      PRIMARY KEY(clientid),
  clientName varchar(40) ,
  refId int(4),
  servertime int,
  content text
)";
$qq=mysql_query($sql,$link);
if (!$qq) {
   print 'Error. Unable to create CLIENTIDS table in mysql database ' . $mdata . ': '  . mysql_error();
   return 0;
}
// add clientID data

$sql="INSERT INTO clientids (clientid,clientName,refId,servertime,content)
              VALUES
     ('_created','_created',-2,'$idate','$vudate') ";

$qq=mysql_query($sql,$link);
if (!$qq) {
   print 'Error. Unable to add info to CLIENTIDS  table in mysql database ' . $mdata . ': '  . mysql_error();
   return 0;
}
$tcreated++ ;

//xxxxxxxxxxxxxxxxxxxxxx
// create  assignCID table
//   servertime: time client joined  (in js time, rounded to second)
//   clientname: name supplied by client
//   id: auto incremented id to give to client
// Note: this is not always used (i.e.; it is NOT used when client-side generation of ids is specified)

$sql = "create table assignCID
(
  clientid int(2) auto_increment NOT NULL ,
      PRIMARY KEY(clientid),
  clientName varchar(40) ,
  servertime int
)";
$qq=mysql_query($sql,$link);
if (!$qq) {
   print 'Error. Unable to create ASSSIGNCLIENTIDS table in mysql database ' . $mdata . ': '  . mysql_error();
   return 0;
}

// add assignCID data

$sql="INSERT INTO assignCID (clientName,servertime)
              VALUES
     ('_created','$idate') ";

$qq=mysql_query($sql,$link);
if (!$qq) {
   print 'Error. Unable to add info to ASSIGNCID  table in mysql database ' . $mdata . ': '  . mysql_error();
   return 0;
}
$tcreated++ ;

//xxxxxxxxxxxxxxxxxxxxxx
// messages database

$sql = "create table messages
( clientId varchar(40) NOT NULL ,
  servertime int,
  content text,
  subject varchar(250),
  cTime varchar(20) ,
  fromId varchar(30),
  fromName varchar(80),
  toList varchar(1000),
  urgent int,
  stuff text
)";
$qq=mysql_query($sql,$link);
if (!$qq) {
   print 'Error. Unable to create MESSAGES table in mysql database ' . $mdata . ': '  . mysql_error();
   return 0;
}

// add message data

$sql="INSERT INTO messages (clientId,servertime,content,subject,cTime,fromId,fromName,toList,urgent,stuff)
              VALUES
     ('_created','$idate','dSurvey messages','messages','$idate','initId','initName','-1','0',' ') ";

$qq=mysql_query($sql,$link);
if (!$qq) {
   print 'Error. Unable to add info to MESSAGES  table in mysql database ' . $mdata . ': '  . mysql_error();
   return 0;
}
$tcreated++ ;

//xxxxxxxxxxxxxxxxxxxxxx
// message admin database
//   clientId: who message was submitted to
//   lastReadTime: time of the last message retrieved     (for this clientId)
//   newFlag : number of unread messages (for this clientId)

$sql = "create table messagesAdmin
( clientId varchar(40) NOT NULL ,
     PRIMARY KEY (clientId)  ,
  lastReadTime int,
  newFlag  int
)";
$qq=mysql_query($sql,$link);
if (!$qq) {
   print 'Error. Unable to create MESSAGESADMIN table in mysql database ' . $mdata . ': '  . mysql_error();
   return 0;
}

// add message data

$sql="INSERT INTO messagesAdmin (clientId,lastReadTime,newFlag)
              VALUES
     ('_created','$idate','0') ";

$qq=mysql_query($sql,$link);
if (!$qq) {
   print 'Error. Unable to add info to MESSAGESADMIN  table in mysql database ' . $mdata . ': '  . mysql_error();
   return 0;
}
$tcreated++ ;


//============

// xxxxxxxxxxxxxxxxxxx
// create  generalData table
$sql = "create table generalData
(
  round int(4)  NOT NULL ,
     PRIMARY KEY (round)  ,
  content text ,
  servertime int
)";

$qq=mysql_query($sql,$link);
if (!$qq) {
   print 'Error. Unable to create GENERALDATA table in mysql database ' . $mdata . ': '  . mysql_error();
   return 0;
}

// xxxxxxxxxxxxxxxxxxx
// create  participantsData table
$sql = "create table participantsData
(
  round int(4)  NOT NULL ,
     PRIMARY KEY (round)  ,
  content text ,
  servertime int
)";

$qq=mysql_query($sql,$link);
if (!$qq) {
   print 'Error. Unable to create participantsDATA table in mysql database ' . $mdata . ': '  . mysql_error();
   return 0;
}

// add participantsData header row
$sql="INSERT INTO participantsData(round,content,servertime)
              VALUES
     (-1,'_created','$idate') ";
$qq=mysql_query($sql,$link);
if (!$qq) {
   print 'Error. Unable to add info to participantsDATA table in mysql database ' . $mdata . ': '  . mysql_error();
   return 0;
}
$tcreated++ ;



// add generalData header row
$sql="INSERT INTO generalData(round,content,servertime)
              VALUES
     (-1,'_created','$idate') ";
$qq=mysql_query($sql,$link);
if (!$qq) {
   print 'Error. Unable to add info to GENERALDATA table in mysql database ' . $mdata . ': '  . mysql_error();
   return 0;
}
$tcreated++ ;

// xxxxxxxxxxxxxxxxxxx
// create  usersData table
$sql = "create table usersData
(
  round int(4)  NOT NULL ,
     PRIMARY KEY (round)  ,
  content text ,
  servertime int
)";

$qq=mysql_query($sql,$link);
if (!$qq) {
   print 'Error. Unable to create usersDATA table in mysql database ' . $mdata . ': '  . mysql_error();
   return 0;
}

// add usersData header row
$sql="INSERT INTO usersData(round,content,servertime)
              VALUES
     (-1,'_created','$idate') ";
$qq=mysql_query($sql,$link);
if (!$qq) {
   print 'Error. Unable to add info to usersDATA table in mysql database ' . $mdata . ': '  . mysql_error();
   return 0;
}
$tcreated++ ;



// xxxxxxxxxxxxxxxxxxx
// create  usersData table
$sql = "create table resultsData
(
  round int(4)  NOT NULL ,
     PRIMARY KEY (round)  ,
  content text ,
  servertime int
)";

$qq=mysql_query($sql,$link);
if (!$qq) {
   print 'Error. Unable to create resultsDATA table in mysql database ' . $mdata . ': '  . mysql_error();
   return 0;
}

// add resultsData header row
$sql="INSERT INTO resultsData(round,content,servertime)
              VALUES
     (-1,'_created','$idate') ";
$qq=mysql_query($sql,$link);
if (!$qq) {
   print 'Error. Unable to add info to resultsDATA table in mysql database ' . $mdata . ': '  . mysql_error();
   return 0;
}
$tcreated++ ;

// xxxxxxxxxxxxxxxxxxx
// create  historyData table
$sql = "create table historyData
(
  round int(4)  NOT NULL ,
     PRIMARY KEY (round)  ,
  content text ,
  servertime int
)";

$qq=mysql_query($sql,$link);
if (!$qq) {
   print 'Error. Unable to create historyDATA table in mysql database ' . $mdata . ': '  . mysql_error();
   return 0;
}

// add historyData header row
$sql="INSERT INTO historyData(round,content,servertime)
              VALUES
     (-1,'_created','$idate') ";
$qq=mysql_query($sql,$link);
if (!$qq) {
   print 'Error. Unable to add info to historyDATA table in mysql database ' . $mdata . ': '  . mysql_error();
   return 0;
}
$tcreated++ ;

// xxxxxxxxxxxxxxxxxxx
// create  notes table
$sql = "create table notes
(
  content text NOT NULL  ,
  servertime int
)";

$qq=mysql_query($sql,$link);
if (!$qq) {
   print 'Error. Unable to create notes table in mysql database ' . $mdata . ': '  . mysql_error();
   return 0;
}

// add notes header row
$sql="INSERT INTO notes(content,servertime)
              VALUES
     ('_created','$idate') ";
$qq=mysql_query($sql,$link);
if (!$qq) {
   print 'Error. Unable to add info to notes table in mysql database ' . $mdata . ': '  . mysql_error();
   return 0;
}
$tcreated++ ;

// xxxxxxxxxxxxxxxxxxx
// create  customData table
$sql = "create table customData
(
  round int(4)  NOT NULL ,
  cname varchar(60) NOT NULL ,
     PRIMARY KEY (cname,round)  ,
  content text ,
  servertime int
)";

$qq=mysql_query($sql,$link);
if (!$qq) {
   print 'Error. Unable to create customDATA table in mysql database ' . $mdata . ': '  . mysql_error();
   return 0;
}

// add customData header row
$sql="INSERT INTO customData(cname,round,content,servertime)
              VALUES
     ('0',-1,'_created','$idate') ";
$qq=mysql_query($sql,$link);
if (!$qq) {
   print 'Error. Unable to add info to customDATA table in mysql database ' . $mdata . ': '  . mysql_error();
   return 0;
}
$tcreated++ ;




//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

// 17 tables added:
//    basic, servervars, statusvars, clientstatus, clientIds,
//    submitted, submitStatus, simpleHistory, assignCID,messages,messagesAdmin,
//    generalData, resultsData, usersData, historyData,custom
//    notes
mysql_close($link);

print 'Ok. Files copied: ' . $icopied . '; the session mysql database created (with ' .$tcreated.' tables) is ' . $mdata  ;


 return 1 ;

}           // todo=4


//==================
// create/overwrite session parameter file

function goAction7($sessions_dir,$instruments_dir,$data_dir,$pinfo_dir,$todo2) {
  $afile='';
  $aname='';
  $content='';
  foreach ($_REQUEST as $vname=>$oof) {
     $avar=trim(strtoupper($vname)) ;
     $toof=trim($oof);
     if ($avar=='FILE') $afile=$toof ;
     if ($avar=='NAME') $aname=$toof;
     if ($avar=='CONTENT') $content=$oof;
  }

  if ($aname=='') {
    print ' - Error No NAME= argument in call to postFile.php (7) ';
    return 0 ;
  }
  if ($afile=='') {
    print ' - Error No FILE= argument in call to postFile.php (7) ';
    return 0 ;
  }
  if ($content=='') {
    print ' - Error No content= argument in call to postFile.php (7) ';
    return 0 ;
  }
  if ($todo2=='1') {
    $thisdir = $instruments_dir . $aname . '/' ;
  } else if ($todo2=='11') {
     $rootdir=$_SERVER['DOCUMENT_ROOT'];
     $ll=strlen($rootdir);
     $ll2=substr($rootdir,$ll-1,1);

     if ($ll2=='\\' || $ll2=='/') {
         $rootdir=substr($rootdir,0,$ll-1);
     };
     $thisdir=$rootdir.$aname;
  } else {
    $thisdir = $sessions_dir . $aname . '/' ;
  }
  $newfile=$thisdir . $afile  ;

   $fnum=fopen($newfile,'w');
   if (!$fnum) {
     print "- Error Unable to open (for writing) file: $newfile ";
     return 0 ;
   }
   if (!fwrite($fnum,$content)) {
       print "- Error  Unable to write to file: $newfile ";
       return 0 ;
   }
   print 'ok. File created: ' . $newfile ;
   fclose($fnum);
   return 0 ;
}


//==================
// 711 -- save a note to notes database
// Or read notes

function goAction711($sessiondir) {
  global $hdrMysql,$mysqlHdr,$currentDatabase ;
  $content=''        ;
  $sessName='';
  $goo=file_get_contents('php://input');
  $gg=explode('&',$goo);

  for ($i=0;$i<count($gg);$i++) {
     $gg2=explode('=',$gg[$i],2);
     $avar=strtoupper($gg2[0]) ;
     if ($avar=='CONTENTS' || $avar=='CONTENT') $content=rawurldecode($gg2[1]);
     if ($avar=='SESSION') $sessName=rawurldecode($gg2[1]);
  }

  header('Content-type:text/plain');

  if ($sessName=='') {
    print ' - Error No sessName= argument in call to postFile.php (711) ';
    return 0 ;
  }

  $idate =time();

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

  $mdata=$currentDatabase ;

// return all current notes
  if ($content=='') {
    $sql="SELECT * FROM notes where content != '_created'" ;
    $qq=mysql_query($sql,$link);
    if (!$qq) {
       header('Content-type:text/plain');
       print '- Error. Unable to read  ' . $mdata . ': '  . mysql_error();
       mysql_close($link);
       return 0;
    }
    $vudate=date(DATE_RFC822)  ;

    $stuff='';
    while($row = mysql_fetch_array($qq)) {
       $aline=$row['content'];                 // 'content' contains original submissiona
       $stuff=$stuff . "$aline \n  ------------------------------------------- \n";
    }
    mysql_close($link);

    $stuff .="\n\n [Note file retrieved: $vudate  ] \n\n ";
    print $stuff ;

    return 0 ;

 }              // content=''


  $contentE=mysql_real_escape_string($content,$link);       // avoid quote problems
  $sql="INSERT INTO notes(content,servertime)
              VALUES
     ('$contentE','$idate') ";
   $qq=mysql_query($sql,$link);

  if (!$qq) {
     print 'Error. Unable to add info to notes table in mysql database ' . $mdata . ': '  . mysql_error();
      mysql_close($link);
     return 0;
  }

  mysql_close($link);
  return 'ok Note added (#bytes= '. strlen($content).')';



 }

//==================
// create/overwrite instrument parameter file

function goAction76($sessions_dir,$instruments_dir,$data_dir,$pinfo_dir,$todo2) {
  $afile='';
  $aname='';
  $content=''; $afoo=0;
  foreach ($_REQUEST as $vname=>$oof) {
     $avar=trim(strtoupper($vname)) ;
     $toof=trim($oof);
     if ($avar=='FILE') $afile=$toof ;
     if ($avar=='NAME') $aname=$toof;
     if ($avar=='CONTENT') $content=$oof;
     if ($avar=='FOOBAR') $afoo=$oof;

  }

  if ($aname=='') {
    print ' - Error No NAME= argument in call to postFile.php (7) ';
    return 0 ;
  }
  if ($afile=='') {
    print ' - Error No FILE= argument in call to postFile.php (7) ';
    return 0 ;
  }
  if ($content=='') {
    print ' - Error No content= argument in call to postFile.php (7) ';
    return 0 ;
  }
  if ($todo2!=='2' && $todo2!=='11') {
     $thisdir = $instruments_dir . $aname . '/' ;
     $newfile=$thisdir . $afile  ;
  } else {
     $rootdir=$_SERVER['DOCUMENT_ROOT'];
     $ll=strlen($rootdir);
     $ll2=substr($rootdir,$ll-1,1);

     if ($ll2=='\\' || $ll2=='/') {
         $rootdir=substr($rootdir,0,$ll-1);
     };
     $newfile=$rootdir.$afile;
//  if ($afoo==1) {print "dcabfooo $afoo $todo2 $newfile "; return 0; }

   }
//print "abfooo34 $afoo $todo2 $newfile "; return 0;

   $fnum=fopen($newfile,'w');

   if (!$fnum) {
     print "- Error Unable to open (for writing) file: $newfile ";
     return 0 ;
   }
   if (!fwrite($fnum,$content)) {
       print "- Error  Unable to write to file: $newfile ";
       return 0 ;
   }
   print 'ok. File created: ' . $aname ;
   fclose($fnum);
   return 0 ;
}

//==================
// create/overwrite dsurvey.htm file

function goAction802($wwwdir) {
  $content=''        ;

  $goo=file_get_contents('php://input');
  $gg=explode('&',$goo);

  for ($i=0;$i<count($gg);$i++) {
     $gg2=explode('=',$gg[$i],2);
     if (strtoupper($gg2[0])=='CONTENTS') $content=rawurldecode($gg2[1]);
  }

//  $content='';
//  foreach ($_REQUEST as $vname=>$oof) {
//     $avar=trim(strtoupper($vname)) ;
//     $toof=trim($oof);
//     if ($avar=='CONTENT' || $avar=="CONTENTS" ) $content=$oof;
//  }

  if ($content=='') {
    print ' - Error No content= argument in call to postFile.php (802) ';
    return 0 ;
  }

  $newfile=$wwwdir . 'dsurvey.htm'  ;

   $fnum=fopen($newfile,'w');
   if (!$fnum) {
     print "- Error Unable to open (for writing) file: $newfile ";
     return 0 ;
   }
   if (!fwrite($fnum,$content)) {
       print "- Error  Unable to write to file: $newfile ";
       return 0 ;
   }
   print 'ok. File created: ' . $newfile;
   fclose($fnum);
   return 0 ;
}



//==================
// create/overwrite file in PINFO/

function goAction124($sessions_dir,$instruments_dir,$data_dir,$pinfo_dir) {
  $atype='';
  $sessName='';
  $afile='';
  $content='';
  foreach ($_REQUEST as $vname=>$oof) {
     $avar=trim(strtoupper($vname)) ;
     $toof=trim($oof);
     if ($avar=='TYPE') $atype=strtoupper($toof) ;
     if ($avar=='SESSION') $sessName=$toof;
     if ($avar=='NAME') $afile=$toof;
     if ($avar=='CONTENT' || $avar=='CONTENTS') $content=$oof;
  }

  if ($sessName=='') {
    print ' - Error No SESSNAME= argument in call to postFile.php (124) ';
    return 0 ;
  }

  if ($content=='') {
    print ' - Error No content= argument in call to postFile.php (124) ';
    return 0 ;
  }

  if ($atype=='SESSION') {
     $afile=$sessName . '.XML';
  }
  if ($atype=='ROUND') {
     $afile='_' . $sessName . '.XML';
  }

  if ($afile=='') {
    print ' - Error No TYPE or NAME argument in call to postFile.php (124) ';
    return 0 ;
  }

  $thisdir = $pinfo_dir . $sessName . '/' ;
  $newfile=$thisdir . $afile  ;

   $fnum=fopen($newfile,'w');
   if (!$fnum) {
     print "- Error Unable to open (for writing) file: $newfile ";
     return 0 ;
   }
   if (!fwrite($fnum,$content)) {
       print "- Error  Unable to write to file: $newfile ";
       return 0 ;
   }
   print 'ok. File created: ' . $afile ;
   fclose($fnum);
   return 0 ;
}

//==================
// retrieve uploaded file (see uploadFile.php for template)

function goAction77($sessions_dir,$instruments_dir,$data_dir,$pinfo_dir) {
global $svydir,$rootdir,$dsvydir,$wwwdir,$instruments_dir,$sessions_dir,$data_dir,$lookup_dir;
global $pinfo_dir,$debug,$hdrMysql,$mysqlHdr,$currentDatabase,$tmpdir;

if(!array_key_exists('thefile', $_FILES)) {
 print "-Error. NO file uploaded ";
 return 0 ;
}

// Validate the uploaded file
if($_FILES['thefile']['size'] === 0 || empty($_FILES['thefile']['tmp_name'])) {
    print "-Error. No file was selected (or file size of selected file exceeded limit) (file chosen=" . $_FILES['thefile']['name'] ;
    return 0 ;

} else if($_FILES['thefile']['size'] > 100000) {
    print  '-Error. Uploaded file too large: ' . $_FILES['thefile']['size'] ;
    return 0 ;

} else if($_FILES['thefile']['error'] !== UPLOAD_ERR_OK) {    // There was a PHP error
    print "-Error. Error uploading file ";
    return 0 ;

} else {
   $origname=$_FILES['thefile']['name'] ;
   $idate =time();

  // Move the file
   $target=$tmpdir . 'upload_' . mt_rand() . '.tmp'  ;

   if(move_uploaded_file($_FILES['thefile']['tmp_name'],$target)) {
//        print 'Ok. File ' .  $_FILES['thefile']['name'] . ' (' . $_FILES['thefile']['size'] . ' bytes)  uploaded successfully to ' . $target     ;
        $stuff=file_get_contents($target);
        print $stuff ;
        unlink($target);
        return 0 ;



   } else {
       print "-Error. There was an error moving the file.";
   }
   }


}

//===========================
// echo back a posted string, for saving as a file on local disk
function goAction500($sessions_dir,$instruments_dir,$data_dir,$pinfo_dir) {

  $filename='submitted.xml';
  $contents='';
  foreach ($_REQUEST as $vname=>$oof) {
     $avar=trim(strtoupper($vname)) ;
     $toof=trim($oof);
     if ($avar=='FILENAME' || $avar=='FILE' ) $filename=$oof ;
     if ($avar=='CONTENTS')  $contents=$oof ;
  }

  header('Content-disposition: attachment ; filename='.$filename)    ;
  echo($contents) ;
  return 0;
}

?>
