<?php
  $dbhandle = dbConnect($dbhost, $dbport, $dbuser, $dbpassword, $dbname);

   setCharset();

  function setCharset()
  {
      dbQuery("SET character_set_client = 'UTF8'");
      dbQuery("SET character_set_results = 'UTF8'");
      dbQuery("SET character_set_connection = 'LATIN1'");
  }
  // Exportiere Daten als CSV-Datei. Setze Flag auf 1 ("exportiert")
  function exportCSV($gesamtexport=0,
          $u18=false,
          $from=false,$end=false,
          $erstellt=false)
  {

      global $exportpath;

      $now = time();
      if ($end) {
          $now = $end;
      }
      $year = date('Y',$now);
      $month = date('m',$now);
      $day = date('d',$now);
      $leastbirthday = ($year - 18) . "-" . $month . "-" . $day;
      $mostbirthday = ($year - 5) . "-" . $month . "-" . $day;
      $mydate = date('YmdHi', $now);
      $query = "LOCK TABLES users WRITE, admins READ";
      $result = dbQuery($query) or
          error("Konnte Tabelle users nicht locken: " . dbError());
      if ($erstellt) {
          $changefield = 'erstellungsdatum';
      } else {
          $changefield = 'aenderungsdatum';
      }

      if ($u18) {
          $query = "SELECT * FROM users WHERE status = 0 
              AND geburtsdatum > '$leastbirthday'
              AND geburtsdatum < '$mostbirthday'
              AND $changefield < $now ORDER BY $changefield ASC";
      } else {
          $query = "SELECT * FROM users WHERE status = 0 
              AND geburtsdatum <= '$leastbirthday'
              AND $changefield < $now ORDER BY $changefield ASC";
      }
      if ($gesamtexport == 1)
      {
          if ($u18) {
              $query = "SELECT * FROM users WHERE 
                  geburtsdatum > '$leastbirthday'
                  $changefield < $now ORDER BY $changefield ASC";
          } else {
              $query = "SELECT * FROM users WHERE 
                  geburtsdatum <= '$leastbirthday'
                  $changefield < $now ORDER BY $changefield ASC";
          }
      }
      if ($from or $end) {
          print "Start: $from\nEnd: $end\nNow: $now\n";
          if ($u18) {
              $query = "SELECT * FROM users WHERE 
                  geburtsdatum > '$leastbirthday'
                  AND $changefield < $end 
                  AND $changefield > $from 
                  ORDER BY $changefield ASC";
          } else {
              $query = "SELECT * FROM users WHERE 
                  geburtsdatum <= '$leastbirthday'
                  AND $changefield < $end 
                  AND $changefield > $from 
                  ORDER BY $changefield ASC";
          }
#          $query = "SELECT * FROM users WHERE
#              $changefield < $end
#              AND $changefield > $from
#              ORDER BY $changefield ASC";
          print $query . "\n";
      }

      print "Query: $query<br/>\n";

      $result = dbQuery($query) or
          error("Konnte csv-Daten nicht aus der Datenbank holen: " . dbError());
      $numRows = dbNumRows($result);
      if ($u18) {
          $filename = "$exportpath/U18$mydate"."_healthmiles.csv.xls";
      } else {
          $filename = "$exportpath/$mydate"."_healthmiles.csv.xls";
      }
      print "Schreibe in $filename\n";

      $fileout = fopen($filename,"w+") or
         die ("Kann $filename nicht oeffnen.\n");

      $fields = array('anrede','titel','name','vorname','strasse','hausnummer','plz','ort',
                      'email','versnummer','erstellungsdatum','aenderungsdatum','ersteller');
      $first = true;
      $line = '';
      foreach ($fields as $field) {
        if ($first) { $first = false; } else { $line .= ";"; }
        $line .='"' . $field . '"';
      }
      $line .= "\n";
      if (!fputs($fileout, $line, strlen($line))) error("Konnte nicht schreiben");
      fflush($fileout);
      while ($row = dbFetchRow($result))
      {
          $first = 1;
          $line = "";
          foreach ($fields as $field)
          {
              $$field = unescape($row[$field]);
              if ($field == 'ersteller') {
                  if ($$field == 0) { $ersteller = "Internet"; } else {
                      $subquery = "SELECT name FROM admins WHERE userId = " . $$field;
                      $subresult = dbQuery($subquery) or
                          error ("Konnte Ersteller nicht aus der Datenbank holen: " . dbError() . ", Query: $subquery" .
                                 "Datenexport abgebrochen. Bitte melden sie sich beim <a href='mailto:$adminEmail'>Administrator</a> ($adminTel).");
                      $myrow = dbFetchRow($subresult);
                      $ersteller = $myrow['name'];
                  }
              }
              if ($field == 'erstellungsdatum') { $erstellungsdatum = date('d.m.Y G:i:s', $erstellungsdatum); }
              if ($field == 'aenderungsdatum') { $aenderungsdatum = date('d.m.Y G:i:s', $aenderungsdatum); }
              if ($first == 1) { $first = 0; } else { $line.=";"; }
              $line .=  '"' . $$field . '"';
          }
          $line .= "\n";
          if (!fputs($fileout, $line, strlen($line))) error("Konnte nicht schreiben");
          fflush($fileout);
      }
      fclose($fileout);
      if ($u18) {
          $query = "UPDATE users SET status = 1 WHERE status = 0 
              AND geburtsdatum > '$leastbirthday'
              AND geburtsdatum < '$mostbirthday'
              AND $changefield < $now";
      } else {
          $query = "UPDATE users SET status = 1 WHERE status = 0 
              AND geburtsdatum <= '$leastbirthday'
              AND $changefield < $now";
      }
      if (!($from && $end)) {
          $result = dbQuery($query) or error("Konnte Export-Status nicht setzen " . dbError());
      }

      $query = "UNLOCK TABLES";
      $result = dbQuery($query) or
          error("Konnte Tabelle users nicht unlocken: " . dbError());
  }

  function exportCSVselected($users, $filesuffix='datenexport')
  {

      global $exportpath;

      $now = time();
      $mydate = date('Y-m-d', $now);
      $filename = "extended/$mydate" . "_$filesuffix.xls";

      $fields = array('anrede','titel','name','vorname','strasse','hausnummer','plz','ort',
                      'email','versnummer','erstellungsdatum','aenderungsdatum','ersteller');

      $data = Array();
      /* print data */
      foreach ($users as $myUser)
      {
          $row = Array();
          $user = new user('',$myUser);
          $first = 1;
          $line = "";
          foreach ($fields as $field)
          {
              $$field = $user->$field;
              if ($field == 'ersteller') {
                  if ($$field == 0) { $ersteller = "Internet"; } else {
                      $subquery = "SELECT name FROM admins WHERE userId = " . $$field;
                      $subresult = dbQuery($subquery) or
                          error ("Konnte Ersteller nicht aus der Datenbank holen: " . dbError() . ", Query: $subquery");
                      $myrow = dbFetchRow($subresult);
                      $ersteller = $myrow['name'];
                  }
              }
              if ($field == 'erstellungsdatum') { $erstellungsdatum = date('d.m.Y G:i:s', $erstellungsdatum); }
              if ($field == 'aenderungsdatum') { $aenderungsdatum = date('d.m.Y G:i:s', $aenderungsdatum); }
              array_push($row, $$field);
          }
          array_push($data, $row);
      }
      $spreadsheet = new Excelexport("$exportpath/" . $filename,$filesuffix,$fields,$data);
      $spreadsheet->create();

      return($filename);

  }

  function exportdoublettes() {
    $doublettes = checkdoublettes();
    $users = array();
    foreach ($doublettes as $row) {
      $userId = $row['userId'];
      array_push($users, $userId);
    }
    $filename = exportCSVselected($users, 'doubletten');
    return $filename;
  }

  function getLastExport($u18=false)
  {
      $query = "SELECT timestamp FROM userlogs WHERE aktion = 'datenexport" . ($u18?'U18':'') . "' order by timestamp DESC";
      $result = dbQuery($query) or
          error("Konnte csv-Daten nicht aus der Datenbank holen: " . dbError());

      $row = dbFetchRow($result);
      $lastexport = date('d.m.Y G:i:s', $row['timestamp']);

      return $lastexport;
  }

  function exportCSVU18($gesamtexport=0,$u18=false)
  {

      global $exportpath;

      $now = 1247608800; # 2009-07-15: Stichtag Start U18
      $year = date('Y',$now);
      $month = date('m',$now);
      $day = date('d',$now);
      $leastbirthday = ($year - 18) . "-" . $month . "-" . $day;
      $mostbirthday = ($year - 0) . "-" . $month . "-" . $day;
      $mydate = date('YmdHi', $now);
      $query = "LOCK TABLES users WRITE, admins READ";
      $result = dbQuery($query) or
          error("Konnte Tabelle users nicht locken: " . dbError());
      if ($u18) {
          $query = "SELECT * FROM users WHERE  geburtsdatum >= '$leastbirthday' AND status = 1
              AND geburtsdatum < '$mostbirthday' 
              AND aenderungsdatum < $now ORDER BY aenderungsdatum ASC";
      } else {
          $query = "SELECT * FROM users WHERE status = 0 
              AND geburtsdatum <= '$leastbirthday'
              AND aenderungsdatum < $now ORDER BY aenderungsdatum ASC";
      }
      if ($gesamtexport == 1)
      {
          if ($u18) {
              $query = "SELECT * FROM users WHERE 
                  geburtsdatum > '$leastbirthday'
                  aenderungsdatum < $now ORDER BY aenderungsdatum ASC";
          } else {
              $query = "SELECT * FROM users WHERE 
                  geburtsdatum <= '$leastbirthday'
                  aenderungsdatum < $now ORDER BY aenderungsdatum ASC";
          }
      }

      print "Query: $query<br/>\n";
      $result = dbQuery($query) or
          error("Konnte csv-Daten nicht aus der Datenbank holen: " . dbError());
      $numRows = dbNumRows($result);
      if ($u18) {
          $filename = "$exportpath/U18$mydate"."_healthmiles.csv.xls";
      } else {
          $filename = "$exportpath/$mydate"."_healthmiles.csv.xls";
      }

      $fileout = fopen($filename,"w+") or
         die ("Kann $filename nicht oeffnen.\n");
      print "Filename: $filename<br/>\n";

      $fields = array('anrede','titel','name','vorname','strasse','hausnummer','plz','ort',
                      'email','versnummer','erstellungsdatum','aenderungsdatum','ersteller');
      $first = true;
      $line = '';
      foreach ($fields as $field) {
        if ($first) { $first = false; } else { $line .= ";"; }
        $line .='"' . $field . '"';
      }
      $line .= "\n";
      if (!fputs($fileout, $line, strlen($line))) error("Konnte nicht schreiben");
      fflush($fileout);
      while ($row = dbFetchRow($result))
      {
          $first = 1;
          $line = "";
          foreach ($fields as $field)
          {
              $$field = unescape($row[$field]);
              if ($field == 'ersteller') {
                  if ($$field == 0) { $ersteller = "Internet"; } else {
                      $subquery = "SELECT name FROM admins WHERE userId = " . $$field;
                      $subresult = dbQuery($subquery) or
                          error ("Konnte Ersteller nicht aus der Datenbank holen: " . dbError() . ", Query: $subquery" .
                                 "Datenexport abgebrochen. Bitte melden sie sich beim <a href='mailto:$adminEmail'>Administrator</a> ($adminTel).");
                      $myrow = dbFetchRow($subresult);
                      $ersteller = $myrow['name'];
                  }
              }
              if ($field == 'erstellungsdatum') { $erstellungsdatum = date('d.m.Y G:i:s', $erstellungsdatum); }
              if ($field == 'aenderungsdatum') { $aenderungsdatum = date('d.m.Y G:i:s', $aenderungsdatum); }
              if ($first == 1) { $first = 0; } else { $line.=";"; }
              $line .=  '"' . $$field . '"';
          }
          $line .= "\n";
          if (!fputs($fileout, $line, strlen($line))) error("Konnte nicht schreiben");
          fflush($fileout);
      }
      fclose($fileout);
      if ($u18) {
          $query = "UPDATE users SET status = 1 WHERE status = 0 
              AND geburtsdatum >= '$leastbirthday'
              AND geburtsdatum < '$mostbirthday' 
              AND aenderungsdatum < $now";
      } else {
          $query = "UPDATE users SET status = 1 WHERE status = 0 
              AND geburtsdatum <= '$leastbirthday'
              AND aenderungsdatum < $now";
      }
      $result = dbQuery($query) or error("Konnte Export-Status nicht setzen " . dbError());

      $query = "UNLOCK TABLES";
      $result = dbQuery($query) or
          error("Konnte Tabelle users nicht unlocken: " . dbError());
  }


function dbConnect($dbhost, $dbport, $dbuser, $dbpassword, $dbname)
{
    global $dbhandle;
    $dbhandle = mysqli_connect($dbhost.':'.$dbport,$dbuser,$dbpassword,$dbname) or
        error("Die Verbindung mit dem Datenbankserver ist fehlgeschlagen ($dbhost . ':' . $dbport, $dbuser, $dbpassword, $dbname): " .  dbError());
    return $dbhandle;

}


function dbEscapeString($string)
{
    global $dbhandle;
    return mysqli_real_escape_string($dbhandle, $string);
}


function dbQuery($query)
{
    global $dbhandle;
    $result = mysqli_query($dbhandle,$query);
    return $result;
}


function dbNumRows($result)
{
    global $dbhandle;
    return mysqli_num_rows($result);
}


function dbFetchRow($result)
{
    global $dbhandle;
    return mysqli_fetch_assoc($result);
}


function dbError()
{
    global $dbhandle;
    return mysqli_error($dbhandle);
}


function dbFreeResult($result)
{
    global $dbhandle;
    return;
}

function dbInsertId()
{
    global $dbhandle;
    return mysqli_insert_id($dbhandle);
}
