<?php
//    Post to dsurvey message box

/*
 messageSendPost (todo=521)
    post a message to a client, or multiple clients, messageboxes
         session=sessname&clientList=clientIds&message=escapedMesssage
   (if more than one clientid, seperate with a ,

  messageRetrieve (todo=522) retrieve contents of message box. Then empty the messagebox
       session=sessname&client=clientId
*/

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 postMessage.php ';
  exit ;
}

$todo=$_REQUEST['todo'] ;

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


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


// rebuild messagebox
if ($todo==523) {
    header("Content-Type: text/plain");
    $ugly=goAction523($sessions_dir,$instruments_dir,$data_dir,$pinfo_dir);
    exit;
}

print 'Error: unknown action in postMessage = ' . $todo ;
exit;



//==================
// post a message

//        session=sessname&clientList=clientIds&message=escapedMesssage


function goAction521($sessions_dir,$instruments_dir,$data_dir,$pinfo_dir) {
  global $hdrMysql,$mysqlHdr,$currentDatabase ;
  $toList='';  $urgent=0; $fromId='' ; $fromName='';
  $sessName=''; $ctime='';
  $message=''; $subject='';
  foreach ($_REQUEST as $vname=>$oof) {

     $avar=trim(strtoupper($vname)) ;
     $toof=trim($oof);
     if ($avar=='CLIENTS' || $avar=='CLIENTLIST') $toList=$toof ;
     if ($avar=='SESSION') $sessName=$toof;
     if ($avar=='MESSAGE') $message=$oof;
     if ($avar=='SUBJECT') $subject=$oof;
     if ($avar=='FROMNAME') $fromName=$oof;
     if ($avar=='FROM' || $avar=='FROMID') $fromId=$oof;
     if ($avar=='URGENT') $urgent=$oof;
     if ($avar=='TIME') $ctime=$oof;
  }

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

  if ($toList=='') {
    print ' - Error No CLIENTLIST= argument in call to postMessage.php (521)  ';
    return 0 ;
  }

  $idate =time();

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

  $mdata=$currentDatabase ;

  $eMessage=mysql_real_escape_string($message,$link);       // avoid quote problems
  $eSubject=mysql_real_escape_string($subject,$link);       // avoid quote problems
  $sendto=explode(',',$toList);

//   amessageA=aurgent||','||atime||','||afrom||','||afromName||','||clientids||','||asubject||','||amessage

  $uMessage=rawurlencode($message);  $uSubject=rawurlencode($subject);    
  $toList2=str_replace(',',' ',$toList);
  $stuff1="$urgent,$ctime,$fromId,$fromName,$toList2,$uSubject,$uMessage";

  $stuff2=mysql_real_escape_string($stuff1);
  $isent=0;
  for ($ii=0; $ii<count($sendto);$ii++) {
     $aclient=trim(strtoupper($sendto[$ii])) ;
     if ($aclient=='') continue ;
     $isent++ ;
     $sql="INSERT INTO messages (clientId,servertime,content,subject,cTime,fromId,fromName,toList,urgent,stuff)
              VALUES
     ('$aclient','$idate','$eMessage','$eSubject','$ctime','$fromId','$fromName','$toList','$urgent','$stuff2')
      ";

     $qq=mysql_query($sql,$link);

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

// is there an entry in messageAdmins for this client?
    $sql="SELECT * FROM messagesAdmin  WHERE clientId='$aclient' ";
    $qq=mysql_query($sql,$link);
    if (!$qq) {
        print 'Error. Unable to read from MESSAGESADMIN  table in mysql database ' . $mdata . ': '  . mysql_error();
        return 0;
    }
    if (mysql_num_rows($qq)==0) {
       $sql="INSERT INTO messagesAdmin (clientId,lastReadTime,newFlag)
              VALUES
        ('$aclient','0','1') ";

       $qq=mysql_query($sql,$link);
       if (!$qq) {
          print 'Error. Unable to add entry ( ' . $aclient . ') to MESSAGESADMIN  table in mysql database ' . $mdata . ': '  . mysql_error();
          return 0;
       }
    }   else {                 // entry exists, to update it

         $sql="UPDATE  messagesAdmin SET newFlag='1' where clientId='$aclient' " ;
         $qq=mysql_query($sql,$link);
         if (!$qq) {
             print 'Error. Unable to update info ( '. $aclient . ') in MESSAGESADMIN  table in mysql database ' . $mdata . ': '  . mysql_error();
             return 0;
          }
    }                 // create new, or update, entry in messagesAdmin

  }                             // aclient


  mysql_close($link);
  print 'ok ' . $isent . ' messages added (#bytes= '. strlen($message).')';
  return 0;


}


//==================
// retrieve messages
//       session=sessname&client=clientId

function goAction522($sessions_dir,$instruments_dir,$data_dir,$pinfo_dir) {
  global $hdrMysql,$mysqlHdr,$currentDatabase ;
  $toList='';
  $sessName='';
  $content='';
  $doReset='0';
  foreach ($_REQUEST as $vname=>$oof) {
     $avar=trim(strtoupper($vname)) ;
     $toof=trim($oof);
     $aclient='' ;
     if ($avar=='CLIENT') $aclient=strtoupper($toof) ;
     if ($avar=='SESSION') $sessName=$toof;
     if ($avar=='ERASE') $doReset=$toof;              // value of 1 means "return unread, and mark as read
                                                      // 0 means "return all, don't mark" ( erase should be "spy")

  }

  if ($sessName=='') {
    print ' - Error No SESSION= argument in call to postMessage.php (522) ';
    return 0 ;
  }
  if ($aclient=='') {
    print ' - Error No CLIENT= argument in call to postMessage.php (522) ';
    return 0 ;
  }

   $idate =time();

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

  if ($aclient!='$ALL') {                 //$ALL is special

     $sql="SELECT * FROM messagesAdmin WHERE clientId='$aclient' ";

     $qq=mysql_query($sql,$link);

     if (!$qq) {
        print 'Error. Unable to read from MESSAGESADMIN  table in mysql database ' . $mdata . ': '  . mysql_error();
        mysql_close($link);
        return 0;
     }
     if (mysql_num_rows($qq)==0) {                               // no such entry, might as well create it
       $sql="INSERT INTO messagesAdmin (clientId,lastReadTime,newFlag)
             VALUES
           ('$aclient','0','1') ";
       $qq=mysql_query($sql,$link);
       if (!$qq) {
          print 'Error. Unable to add an entry ( ' . $aclient . ') to MESSAGESADMIN  table in mysql database ' . $mdata . ': '  . mysql_error();
          mysql_close($link);
          return 0;
       }
       print  ' ';        // no entry means no messages, so return blank
       mysql_close($link);
       return ;
     }

// now see if any new messages (or grab all messages)?
     $row = mysql_fetch_array($qq) ;           // there should only be one entry for this clientid
     $newMessages=$row['newFlag'];
     if ($newMessages=='0' && $doReset=='1') {                      // no new messages, give up (and not a "spy"
        print ' ';
        mysql_close($link);
        return 0;
     }
     
   $lastRead=$row['lastReadTime'];

  }              // $ALL
// got new messages, retrieve them (or doReset='0'


   if ($aclient!='$ALL') {
      $sql="SELECT * FROM messages WHERE clientId='$aclient'  ";
   } else {
      $sql="SELECT * FROM messages  ";
   }

   $qq=mysql_query($sql,$link);
   
   if (!$qq) {
          print 'Error. Unable to read messages ( ' . $aclient . ', ' . $lastRead . ') from MESSAGES  table in mysql database ' . $mdata . ': '  . mysql_error();
          mysql_close($link);
          return 0;
   }
  if (mysql_num_rows($qq)==0 && $doReset=='1') {                               // no new entries? Error
          print 'Error. No new MESSAGES, but there should be ( ' . $aclient . ', ' . $lastRead . ') from MESSAGES  table in mysql database ' ;
          mysql_close($link);
          return 0 ;
  }
 $glug='';
 while($row = mysql_fetch_array($qq)) {
       $aline=$row['stuff'];                 // 'content' contains original submissiona
       if ($aline=='') continue ;               // emnpty, skip
       $atime=$row['servertime'];
       if ($doReset=='1' && $atime<$lastRead) continue ;  // already read, so skip
       $glug=$glug . "$aline \n";
   }

   if ($doReset=='1') {
     $sql="UPDATE  messagesAdmin SET newFlag='0' , lastReadTime='$idate'  where clientId='$aclient' ";
     $qq=mysql_query($sql,$link);
     if (!$qq) {
             print 'Error. Unable to reset newFlag in ( '. $aclient . ') in MESSAGESADMIN  table in mysql database ' . $mdata . ': '  . mysql_error();
             mysql_close($link);
             return 0;
     }
   }
   print $glug ;
   mysql_close($link);
   return 0;

}

//==================
// rebuild messagebox
//       session=sessname&client=clientId

function goAction523($sessions_dir,$instruments_dir,$data_dir,$pinfo_dir) {
  global $hdrMysql,$mysqlHdr,$currentDatabase ;
  $aclient='';
  $sessName='';
  foreach ($_REQUEST as $vname=>$oof) {
     $avar=trim(strtoupper($vname)) ;
     $toof=trim($oof);
     if ($avar=='CLIENT') $aclient=strtoupper($toof) ;
     if ($avar=='SESSION') $sessName=$toof;
  }

  if ($sessName=='') {
    print ' - Error No SESSION= argument in call to postMessage.php (523) ';
    return 0 ;
  }
  if ($aclient=='') {
    print ' - Error No CLIENT= argument in call to postMessage.php (523) ';
    return 0 ;
  }

   $idate =time();
  // open databsae (exit on error in connectSurveyDatabase)
  $link=connectDsurveyDatabase($sessName);
  $mdata=$currentDatabase ;
  
     $sql="SELECT * FROM messagesAdmin WHERE clientId='$aclient' ";

     $qq=mysql_query($sql,$link);

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

     if (mysql_num_rows($qq)==0) {                               // no such entry, might as well create it
       $sql="INSERT INTO messagesAdmin (clientId,lastReadTime,newFlag)
             VALUES
           ('$aclient','0','1') ";
       $qq=mysql_query($sql,$link);
       if (!$qq) {
          print 'Error. Unable to add an entry ( ' . $aclient . ') to MESSAGESADMIN  table in mysql database ' . $mdata . ': '  . mysql_error();
          mysql_close($link);
          return 0;
       }
       print  'ok. New entry created for ' . $aclient ;        // no entry means no messages, so return blank
       mysql_close($link);
       return ;
     }


     $sql="UPDATE  messagesAdmin SET newFlag='1' , lastReadTime='0'  where clientId='$aclient' ";
     $qq=mysql_query($sql,$link);
     if (!$qq) {
             print 'Error. Unable to reset ( '. $aclient . ') in MESSAGESADMIN  table in mysql database ' . $mdata . ': '  . mysql_error();
             mysql_close($link);
             return 0;
     }
     print  'ok. Entry reset for ' . $aclient ;        // no entry means no messages, so return blank
     mysql_close($link);
    return ;

}

?>
