<?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='';

 $break = Explode('/',$_SERVER['SCRIPT_NAME']);
 $myScriptName = $break[count($break) - 1];

$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,$myScriptName;
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,$myScriptName;
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 ;

}

// copy one php table to a new table
// Requires that $link be the pointer to the mysql database (i.e.;  $link=mysql_connect('localhost','username','password');

//  from http://www.electrictoolbox.com/php-script-backup-copy-mysql-table/
// noowerwrite means "do NOT overwrite exisdting table "
function copy_table($from, $to,$link,$noOverwrite) {

   if ($noOverwrite!="1") {
       mysql_query("DROP TABLE IF EXISTS '$to' ",$link);
       mysql_query("CREATE TABLE  '$to'  SELECT * FROM  '$from' ",$link);
       return 1;
   }

    if(table_exists($to,$link)) {
        $success = false;
    }
    else {
        mysql_query("CREATE TABLE '$to' LIKE '$from'");
        mysql_query("INSERT INTO '$to' SELECT * FROM '$from'");
        $success = true;
    }

    return $success;

}

function table_exists($tablename, $database = false) {

    if(!$database) {
        $res = mysql_query("SELECT DATABASE()");
        $database = mysql_result($res, 0);
    }

    $res = mysql_query("
        SELECT COUNT(*) AS count
        FROM information_schema.tables
        WHERE table_schema = '$database'
        AND table_name = '$tablename'
    ");

    return mysql_result($res, 0) == 1;
}


//===========================
// write a mysql table as a CSV
// Database MUST be selected before calling this: i.e using mysql_select_db($dbname);
//
// $outfile is a string containing path to the output file
// $link is from a $link=mysql_connect($server, $login, $password);
// $escape =1, then escape the contents of the table (this allows crlfs, etc to be transfered, albeit in an escaped format)
// $table is table from selected database
// return codes:
//  -1 : could not open output file
//  -2 : could not select database
//  -3 : could not write output file
// >0  : number of lines copied

function mysqlToCSV($table,$outfile,$escape,$link) {


$fp = fopen($outfile, "w");
if (!$fp) return -1 ;

$res = mysql_query("SELECT * FROM '$table' ",$link);
if (!$res) return -2 ;

// fetch a row and write the column names out to the file
$row = mysql_fetch_assoc($res);
$line = "";
$comma = "";
foreach($row as $name => $value) {
    $line .= $comma . '"' . str_replace('"', '""', $name) . '"';
    $comma = ",";
}
$line .= "\n";
$qq=fputs($fp, $line);
if (!$qq) return -3 ;

// remove the result pointer back to the start
mysql_data_seek($res, 0,$link);

// and loop through the actual data
$nrows=0;
while($row = mysql_fetch_assoc($res)) {

    $line = "";
    $comma = "";                       // a fun hack
    foreach($row as $value) {
       if (is_numeric($value)) {                    // a number, than do NOT quote
             $line .= $comma . $value  ;
       } else {
          if ($escape==1) {                        // might be crlfs and other stuff -- then escape it (CSV-escaped file)
             $line .= $comma . '"' . rawurlencode($value) . '"';
          } else {                                                   // deal with "s
            $line .= $comma . '"' . str_replace('"', '""', $value) . '"';
          }
       }
       $comma = ",";              // hack for fun!

    }
    $line .= "\n";
    fputs($fp, $line);
    $nrows++ ;

}

fclose($fp);
return $nrows ;
}

//================================
// dump sql database to output file (entire database, not just one table)
// Note: restoring from this (using restoreMysqlDatabase will overwrite an existing version of the database (on the mysql server)
function saveMysqlDatabase($database,$outfile) {

//'dsurveyAdmin','admin'
$command="mysqldump  --add-drop-table --host=localhost --user=dsurveyAdmin --password=admin '$database' > '$outfile' ";
$qq=system($command);
return $qq ;
}

// restore sql database from output file (entire database, not just one table)
function restoreMysqlDatabase($database,$infile) {

//'dsurveyAdmin','admin'
$command="mysql  --host=localhost --user=dsurveyAdmin --password=admin '$database' < '$infile' ";
$qq=system($command);
return $qq ;
}


//=============
/*
// backup, and restore, mysql table
$tableName  = 'mypet';
$backupFile = 'backup/mypet.sql';
$query      = "SELECT * INTO OUTFILE '$backupFile' FROM $tableName";
$result = mysql_query($query);

To restore the backup you just need to run LOAD DATA INFILE query like this :

$tableName  = 'mypet';
$backupFile = 'mypet.sql';
$query      = "LOAD DATA INFILE 'backupFile' INTO TABLE $tableName";
$result = mysql_query($query);
*/

?>