<?php
//    save a server variable (todo =121)
// Fields in the request are:
//        session: the survey session
//        varname: variable to be saved (or space delimited list of variables)
//        value : value of the variable  (or delim delimited list of values)
//        delim: a delimiter (used only if multiple varnames). Default is a ','
require("phpVars.php");

  $sessName='';
  $varname=''   ;
  $aValue='' ;
  $delim=',';

header("Content-Type: text/plain");

  foreach ($_REQUEST as $vname=>$oof) {
     $avar=strtoupper(trim($vname)) ;
     if ($avar=='SESSION' || $avar=='NAME' ) $sessName=trim($oof) ;
     if ($avar=='VARNAME' || $avar=='VAR') $varname=trim($oof) ;
     if ($avar=='VALUE' || $avar=='VAL') $aValue=trim($oof) ;
     if ($avar=='DELIM') $delim=trim($oof) ;
  }


if ($sessName=='') {
  print '- ERROR: No SESSION=  in call to   saveServerVar.php ';
  exit ;
}

if ($varname=='') {
  print '- ERROR: No VARNAME=  in call to   saveServerVar.php ';
  exit ;
}

$bvars=getWords($varname);
//$avars=trim($varname);
//$avars = preg_replace("/\s+/"," ", $avars) ;             // collapse spaces
//$bvars=explode(' ',$avars) ;

$avals=trim($aValue);
if (count($bvars)>1) {
  $bvals=explode($delim,$avals);   // note: default delim is a comma
}   else {
  $bvals= array ('1');
  $bvals[0]=$avals ;
}
 if (count($bvals)!=count($bvars)) {
    print ' - Error. Number of variables ( ' . count($bvars) . ') not equal to number of values ( ' . count($bvals) . ')';
    exit;
 }

// add variables to SERVERVARS table

$idate =time();

$link=mysql_connect('localhost','dsurveyAdmin','admin');
if (!$link) {
   print ' - Error. Could not connect to mysql (with username=`dsurveyAdmin` and password=`admin`): ' . mysql_error();
   exit ;
}

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


$iadded=0; $ireplaced=0;
for ($ith=0; $ith<count($bvars); $ith++) {

 $cvar=trim(strtoupper($bvars[$ith]));
 $cval=$bvals[$ith];

// variable exists?
//$isnew=0;
//  $result = mysql_query("SELECT * FROM servervars WHERE varname='$cvar'");
//  if (!$result)  $isnew=1;

// use REPLACE (since varname is a primary key). Note replace of ' characters
//  $cval2=preg_replace("/\'/",'`',$cval);
  $cvalE=mysql_real_escape_string($cval);


 $sql="REPLACE INTO servervars (varname,varvalue,modified)
              VALUES
     ('$cvar' ,'$cvalE','$idate') ";

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

}

mysql_close($link);
print 'Ok. Variables added or updated= ' . $iadded ;
exit ;


?>

