<?php
  include( dirname(__FILE__) . '/config.php');
  include_once ( dirname(__FILE__) . '/classes.php');
  include_once ( dirname(__FILE__) . '/dbfunctions.php');

  function login($login, $password, $area)
  {
      global $_SERVER;
      global $allowedIps;
      global $DEBUG;
      if ($login == "" || $password == "") {
        return false;
      }
      if ($area=='admin')
      {
          $user = new admin($login);
          if ($user == false) {
              if ($DEBUG) {
                  debug('User unknown');
              }
              return false;
          }

          /* just allow configured IP addresses to log in */
          /* Ausnahmen für den IP-Check sind in die Tabelle 'admins' eingetragen */
          if ($user->ipcheck == '1') {
              $ipcheck = false;
              foreach ($allowedIps as $allowedIp) {
                  if ($allowedIp == $user->ip) {
                      $ipcheck = true;
                      break;
                  }
              }
              if (!$ipcheck) {
                  return false;
              }
          }

          /* check if password was entered and if it's valid */
          if (!$password || !$user->login($password))
          {
              $user = false;
          }
          return ($user);
      } else {

          /* Ein Teilnehmer wird ueber die Versnummer identifiziert,
             welche in der Maske das Passwort ist */
          $matchUser = new user();
#          $matchUser->email= $login;
          $matchUser->emailanmeldung = $login;
//          $matchUser->passwort = $password;
          $users = $matchUser->getUsers();

          if ( count($users) == 0) {
              $matchUser->emailanmeldung = null;
              $matchUser->email = $login;
              $users = $matchUser->getUsers();
          }

          foreach ($users as $user) {
              # print "Login: found user: " . $user->name . "<br/>\n";
              if ($user->login($login,$password)) {
                  return $user;
              }
          }
      }
      return false;
  }

  function error($errorString)
  {
      global $adminEmail;
      $backtrace = '';
      $mysqlerror = dbError();
      print "<br><strong>Anwendungsfehler</strong><br>\n";
      print "Es ist ein Fehler in der Anwendung aufgetreten. Bitte \n" .
            "wiederholen Sie den letzten Vorgang oder melden sie sich beim\n" .
            "<a href=\"mailto:$adminEmail\">Systemverwalter</a>.<br>";
//            "<br>Fehlermeldung:<hr><pre>$errorString</pre>\n";
/*
      if ($mysqlerror) {
          print "MySQL-Fehlermeldung: <pre>$mysqlerror</pre>\n";
      }
*/

      $backtrace = print_r(debug_backtrace(),true);
      $messagebody = "$errorString - $mysqlerror\n$backtrace";

      mail("rath@frankschuessler.de","Healthmiles - Fehler",$messagebody);
      exit;
  }

  function getCategories()
  {
      $myCategories = array();
      $query = "SELECT pkey, beschreibung FROM kategorie WHERE 1 ORDER BY beschreibung ASC";
      $result = dbQuery($query) or
        error("Kann Kategorien nicht aus der Datenbank holen: " .
        dbError());
      while ($row = dbFetchRow($result))
      {
          array_push($myCategories, new kategorie($row['pkey'], $row['beschreibung']));
      }
      return ($myCategories);
  }

  function getSubCategories($deleted=false)
  {
      $myCategories = array();
      $query = "SELECT * FROM unterkategorie WHERE 1";
      if (!$deleted) { $query .= " AND geloescht != 1 "; }
      $query .= " ORDER BY name ASC";
      $result = dbQuery($query) or
          error("Kann Kategorien nicht aus der Datenbank holen: " .  dbError());
      while ($row=dbFetchRow($result))
      {
          array_push($myCategories, new unterkategorie($row));
      }
      return $myCategories;
  }


/*  */
  function unescape($string)
  {
      $string= preg_replace('/\\\\([^\\\\])/', "$1$2", $string);
      $string = preg_replace('/\\\\\\\\/', '\\\\', $string);
      return $string;
  }

  function escape($string)
  {
      $string = preg_replace('/([$\'\"\\\\])/', '\\\\$1', $string);
      #return trim($string);
      return $string;
  }

  function htmlescape($string)
  {
      $string = htmlentities($string,ENT_QUOTES,'ISO-8859-15');
      return $string;
  }

  function capitalize($string, $isStreet=0)
  {
      global $webroot;
      $excludes = file($webroot . '/admin/include/dontcapitalize.txt');

      /* splitte den String in einzelne Worte, schreibe jeweils den ersten
       Buchstaben gross und alle anderen klein.
       Worte werden durch ' ', '-', '.', ';', ',' getrennt */
      $words = preg_split('/( |-|;|,)/', $string,-1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
      $string = '';

      $i=0;
      foreach ($words as $word)
      {
          $word = unescape($word);
          $i++;

          /* teste, ob Wort in exclude-liste steht
           * wenn ja: erzwinge keine grossschreibung */
          foreach ($excludes as $exclude)
          {
              $exclude = rtrim($exclude);
              $gross = false;
              if ($exclude == strtolower($word))
              {
                  /* wenn das wort sich in einem strassennamen
                   * am Anfang befindet, schreibe es gross */
                  if ($isStreet && $i == 1) { $gross = true; }
                  break;
              } else {
                  /* wort ist nicht in exclude-liste:
                   * schreibe es gross */
                  $gross = true;
              }
          }
          if (preg_match('/^d\'/i', $word))
          {
              $gross = false;
          }


          if (($gross == true) && !($word[0] >='A' && $word[0] <= 'Z'))
          {
              $word = strtoupper(substr($word, 0,1)) . strtolower(substr($word,1));
          } else {
              /* Wenn das Wort gross eingegeben wurde, dann soll es gross
               * bleiben */
              $change=true;
              for ($i=0; $i < strlen($word); $i++) {
                  if ($word[$i] >= "A" && $word[$i] <= "Z") $change=false;
              }
              if ($change)  $word = strtolower($word);
          }
          $string .= $word;
      }
      return trim(escape($string));
  }

/* Site functions */
function getFilename($file="",$part = 1)
{
    global $_SERVER;
    if ($file== "") $file=$_SERVER['PHP_SELF'];
    /*
    if (preg_match("/\\/dev\\//", $file))
    {
        $part = 2;
    }
    */
    $aPath = explode('/', $file);
    $aPath = explode('.' , $aPath[sizeof($aPath)-$part]);
    return($aPath[0]);
}

function getDir($file="")
{
    return getFilename($file,1);
}

function pathToRoot($file="")
{
    global $_SERVER;
    global $webroot;
    global $rooturl;
    $numUrlDirs = count(explode('/',$rooturl))-2;
    $pathToRoot = '';
    $offset = $numUrlDirs;
    if ($file== "") $file=$_SERVER['PHP_SELF'];
    $numDirs = count(preg_split("/.\//", $file)) -1 -$offset;
    for ($i=0; $i < $numDirs; $i++) {
        $pathToRoot .= '../';
    }
    return $pathToRoot;
}

function dateToTimestamp($string)
{
  preg_match("/([0-3]?[0-9]).([01]?[0-9]).([2]?[01]?[0-9][0-9]) ?([123]?[0-9])?:?([0-5]?[0-9])?/", $string,$matches);
  $myNewDate = $matches[2] . '/' . $matches[1] . '/' . $matches[3];
  if ($matches[4]) { $myNewDate .= ' ' . $matches[4]; }
  if ($matches[5]) { $myNewDate .= ':' . $matches[5]; }
  return( strtotime($myNewDate));
}

# Converts "German" date format (dd.mm.yyyyy) to iso date (yyyy-mm-dd)
function convertdate($date) {
  if (preg_match("/^[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{2,4}$/",$date)) {
    list($day,$month,$year) = explode('.',$date);
    return ("$year-" . substr('0'. $month,-2,2) . "-" . substr('0'. $day,-2,2));
  } else {
    return ($date);
  }
}

# Converts iso date (yyyy-mm-dd) to "German" date format (dd.mm.yyyyy)
function convertdatefromsql($date) {
  if (preg_match("/^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]$/",$date)) {
    list($year, $month,$day) = explode('-',$date);
    $newdate = "$day.$month.$year";
    return ($newdate);
  } else {
    return ($date);
  }
}
function isodatetotimestamp($date) {
    List($year,$month,$day) = explode('-', $date);
    $timestamp= mktime(0,0,0,$month,$day,$year);
    return $timestamp;
}




/*****************************************************************************
Helper function to mime-encode the mail message
*/
function qp_enc($input = "", $line_max = 180) {
    $hex = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
    $lines = preg_split("/(?:\r\n|\r|\n)/", $input);
    $eol = "\r\n";
    $escape = "=";
    $output = "";

    while( list(, $line) = each($lines) ) {
        $line = rtrim($line); // remove trailing white space -> no =20\r\n necessary
        $linlen = strlen($line);
        $newline = "";
        for($i = 0; $i < $linlen; $i++) {
            $c = substr($line, $i, 1);
            $dec = ord($c);
            if ( ($dec == 32) && ($i == ($linlen - 1)) ) { // convert space at eol only
                $c = "=20";
            } elseif ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) ) { // always encode "\t", which is *
                $h2 = floor($dec/16); $h1 = floor($dec%16);
                $c = $escape.$hex["$h2"].$hex["$h1"];
            }
            if ( (strlen($newline) + strlen($c)) >= $line_max ) { // CRLF is not counted
                $output .= $newline.$escape.$eol; // soft line break; " =\r\n" is okay
                $newline = "";
            }
            $newline .= $c;
        } // end of for
        $output .= $newline.$eol;
    }
    return trim($output);
}

function checkdoublettes($sortfield = '', $dir = '', $from = '', $anzahl = '')
{
    $doublettes = array();
    $user = array();
    $query = "SELECT userId, versnummer, name, vorname, ort FROM users WHERE 1";
    if ($sortfield && $dir)
    {
        $query .= " ORDER BY $sortfield $dir";
    }

    $result = dbQuery($query) or die ($query . ": " . dbError());

    while ($row = dbFetchRow($result))
    {
        $userId = $row['userId'];
        $name = $row['name'];
        $vorname = $row['vorname'];
        $ort = $row['ort'];
        $versnummer = $row['versnummer'];

        #$key = "$versnummer;$name;$vorname;$ort";
        $key = "$name;$vorname;$ort";
        if ($user[$key]) {
            array_push($doublettes,$user[$key]);
            array_push($doublettes,$row);
        } else {
            $user[$key] = $row;
        }
   }
   dbFreeResult($result);
   return $doublettes;
}

function _mysqlescapestring($string)
{
    return dbEscapeString($string);
    return str_replace('_','\_',
            str_replace('%','\%',
                dbEscapeString($string)
                )
            );
}

function convertFileName($name)
{
    $name = preg_replace("/\\(/", "", $name);
    $name = preg_replace("/\\)/", "", $name);
    $name = preg_replace("/\\'/", "", $name);
    $name = preg_replace("/&/", "", $name);
    $name = preg_replace("/;/", "", $name);
    $name = preg_replace("/\\\"/", "", $name);
    $name = preg_replace("/!/", "", $name);
    $name = preg_replace("/!/", "", $name);
    $name = preg_replace("/:/", "", $name);

    return $name;
}

function debug($message) {
#    $backtrace = debug_backtrace();
#    $callPath = $backtrace[1]['function'];
#    $callPath .= ' [Line ' . $backtrace[1]['line'];
#    $callPath .= '; File: ' . $backtrace[1]['file'] . ']';
    print "<div style='border: 1px dashed red'>";
#    print "In $callPath: $message<br/>\n";
    print "DEBUG: $message<br/>\n";
    print "</div>";
}
