<?php
// dsurvey library
// a) names of directories and files
// b) functions
//   connect to database for sesssion aname (exit if errof)
//       connectDsurveyDatabase($aname)
//   does this session exist?
//       checkXmlExists($sessName,$sessions_dir,"- Error. No such session: $sessName (getUserList) ");
//   extract a request field (GET or POST).
//       extractRequestVar($varname,$default,$errorMess) {
//   check xml syntax of a string. Return 0 if no errors, otherwise, returns an HTML message pointing out the errors
//      checkSyntaxXML($xmlstr,$dafile) {
//   break string into words (collapses space strings
//      getWords(astring)

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

 $svydir='';
 $rootdir=$_SERVER['DOCUMENT_ROOT'];
 $dsvydir=$rootdir.'dSurvey/';
 $tmpdir=$dsvydir.'temp/';
 $wwwdir=$dsvydir;
 $instruments_dir=$dsvydir.'instruments/';
 $sessions_dir=$dsvydir.'sessions/';
 $data_dir=$dsvydir.'data/';
 $lookup_dir=$dsvydir.'pinfo/';
 $pinfo_dir=$lookup_dir;
 $debug=0;

 $hdrMysql='dsurvey_';
 $mysqlHdr='dSurvey_';
 $currentDatabse='';

$aa=0;
if (array_key_exists('showDirs',$_GET)) {
   $aa=$_GET['showDirs'];
}

if ($aa == 1 ) {
print '<h1>Directories </h1>';
print '<ul>';
print "<li>Rootdir= $rootdir   ";
print "<li>dsvyDir= $dsvydir ";
print "<li>wwwDir= $wwwdir ";
print "<li>instruments_dir= $instruments_dir ";
print "<li>sessions_dir= $sessions_dir     ";
print "<li>data_dir= $data_dir ";
print "<li>lookup_dir= $lookup_dir ";
print "<li>pinfo_dir= $pinfo_dir ";
print '</ul> ';
}


//=========================
// check xml syntax of a string. Return 0 if no errors
// otherwise, returns an HTML message pointing out the errors

function checkSyntaxXML($xmlstr,$dafile) {

libxml_use_internal_errors(true);

$doc = simplexml_load_string($xmlstr);
//header('Content-Type: text/plain; charset=iso-8859-1');

if (!$doc) {
   $xml = explode("\n", $xmlstr);
   $errors = libxml_get_errors();
   $stuff=" <h3>Errors in XML file  $dafile </h3>  <ul> ";
    foreach ($errors as $error) {
        $stuff=$stuff . ' <li> ' .  display_xml_error($error, $xml);
    }
    libxml_clear_errors();
    return $stuff .  ' </ul>' ;
}
return 0 ;
}

function display_xml_error($error, $xml) {
    $return  = '<div style="white-space:pre;font-family:monospace;stybackground-color:#ababab">' .htmlentities($xml[$error->line - 1]) . '<br>' ;
    $return .= str_repeat('-', $error->column)  ;
    $return .= '</div> ';

    switch ($error->level) {
        case LIBXML_ERR_WARNING:
            $return .= "Warning $error->code: ";
            break;
         case LIBXML_ERR_ERROR:
            $return .= "Error $error->code: ";
            break;
        case LIBXML_ERR_FATAL:
            $return .= "Fatal Error $error->code: ";
            break;
    }

    $return .= trim($error->message) .
               "<br/>  Line:  $error->line   , Column: $error->column";

    if ($error->file) {
        $return .= "<br/>  File: $error->file";
    }

    return $return;
}


//===-
// conect to a dsurvey session mysql database
function connectDsurveyDatabase($aname) {

global $svydir,$rootdir,$dsvydir,$wwwdir,$instruments_dir,$sessions_dir,$data_dir,$lookup_dir;
global $pinfo_dir,$debug,$hdrMysql,$mysqlHdr,$currentDatabase,$tmpdir;


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

$mdata=$hdrMysql . $aname ;
$qq=mysql_select_db($mdata, $link);
if (!$qq) {
   header("Content-Type: text/plain");
   print '- Error. Unable to select mysql database ' . $mdata . ': '  . mysql_error();
   mysql_close($link);
   exit ;
}

$currentDatabase=$mdata ;    // a global ;

return $link ;
}

//===-
// extract a request field (GET or POST)
// varname is name of field to get. can be a space delimited list of names (first one found is returned)
// if $errormess='', return $default if no such field
//    if = '1',  display generic error  message and exit
//    else, display $errormess and exit
function extractRequestVar($varname,$default,$errorMess) {

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

foreach ($_REQUEST as $vname=>$oof) {
     $avar=trim(strtoupper($vname)) ;
     for ($ith=0;$ith<count($vars);$ith++) {
        if ($avar==$vars[$ith]) {
           return $oof ;
        }
     }
}
// if here, could not be found
$errorMess=trim($errorMess);
if ($errorMess!=='') {          // an error, quit
  if ($errorMess=='1') {
     $file = $_SERVER["SCRIPT_NAME"];
      $break = explode('/', $file);
      $pfile = $break[count($break) - 1];
      header("Content-Type: text/plain");
      print '- Error. Unable to find request variable (' . $varname . ') in ' . $pfile ;
  } else {
     header("Content-Type: text/plain");
     print $errorMess ;
  }
  exit ;
}
  return $default ;
}

//=======================
// see if session exists. If not, exit with error message
function checkXMLexists($fname,$adir,$errorMess) {

global $svydir,$rootdir,$dsvydir,$wwwdir,$instruments_dir,$sessions_dir,$data_dir,$lookup_dir;
global $pinfo_dir,$debug,$hdrMysql,$mysqlHdr,$currentDatabase;


  $dafile=$adir . $fname . '.XML' ;
  $isfile=file_exists($dafile);
  if ($isfile) return 1 ;

  if (trim($errorMess)!=='') {
      header("Content-Type: text/plain");
      print $errorMess;
      exit;
  }

 $file = $_SERVER["SCRIPT_NAME"];
 $break = explode('/', $file);
 $pfile = $break[count($break) - 1];

 header("Content-Type: text/plain");
 print '- Error. No such XML file ' . $dafile . ' (' . $pfile . ')';

 exit ;
}

//=============
// trim spaces, convert internal spaces to single space string, break into an array
function getWords($cval3) {
    $cval3=trim($cval3);
    $cval4=preg_replace("/\s+/"," ", $cval3) ;             // collapse spaces
    $bvars=explode(' ',$cval4) ;

    return $bvars ;

}

?>