<?php
session_start();

include_once 'classes/TestProjektSmarty.class.php';
#require_once("config.inc.php");
require_once("config/datenbankanbindung.php");     // f&uuml;gt die Datenbankanbindung ein: Sys:\php\includes\kurs\datenbankanbindung.php
$smarty = new Smarty();
$template = "login";
$templatename = substr(basename($_SERVER['PHP_SELF']),0,-3)."html";
$smarty = new Smarty();
require_once "language/german.inc.php";


$action = $_GET['action'];
if($action == ''){
$smarty->assign('index_error', $_GET[error]);
  
  # Daten aufbereiten bei Fehler
  if(isset($_SESSION["global_domain"])){
    $smarty->assign('index_domain', $_SESSION["global_domain"]);
  }else{
    # defaultwert festlegen
    $smarty->assign('index_domain', "hsnet");
  }
  
  if(isset($_SESSION["global_username"])){
    $smarty->assign('index_user', $_SESSION["global_username"]);
  }
  
  

}

if($action == 'anmeld'){
  $username=strtoupper($_POST["user"]); //remove case sensitivity on the username
  $password=$_POST["password"];
  $domain=$_POST["domain"];

  if($_POST["domain"] != ""){
    $_SESSION["global_domain"]=$domain;
  }
  
  if($_POST["user"] != ""){
    $_SESSION["global_username"]=$username;
  }
  
  if($username == "" OR $password == ""){
     echo "<meta http-equiv=\"refresh\" content=\"0; URL=".$_SERVER['PHP_SELF']."?error=1\">";
  }else{
  
     # muss gesetzte werden nachdem die Session global_domain definiert wurde
     require_once("class_idee.php");
    

    
    try {
      $idee = new idee();
    }
      catch (adLDAPException $e) {
      echo $e; exit();   
    }

      //authenticate the user
      #$adldap -> set_domain_controllers(array("$ipdc"));
      if ($idee -> authenticate($username,$password)){
        //establish your session and redirect

        $db = dbconnect();

        
        $objectsid = $idee -> username2osid($_SESSION["global_username"]);

        $result_imt = $db->query("SELECT uid FROM dep_user WHERE objectsid='$objectsid' AND accountname=upper('$_SESSION[global_username]') LIMIT 1");
        $row_imt = $result_imt->fetch_array();
        
        if($row_imt[uid] == ""){
          $result_1 = $db->query("INSERT INTO dep_user (objectsid, accountname) VALUES ('$objectsid', '$_SESSION[global_username]')");
          $uid = $db->insert_id;
        }else{
          $uid = $row_imt[uid];
        }
        $_SESSION["global_uid"] = $uid;
                
        $datum=date("Y-m-d H:i:s");
        $ip=getenv("REMOTE_ADDR");
        $agent=getenv("HTTP_USER_AGENT");
        $user= $row[dtuid];
        $_SESSION["user"] = $row[dtuid];
        $result_1 = $db->query("INSERT INTO dep_userlog (Datum, IP, user_agent, uid) VALUES ('$datum', '$ip', '$agent', '$_SESSION[global_uid]')");
       
        $redir="Location: indexframe.php";
        header($redir);
      }else{
        echo "<meta http-equiv=\"refresh\" content=\"0; URL=".$_SERVER['PHP_SELF']."?error=2\">";
      }
      
  }
  
  
  
  /*
  
  $db = dbconnect();
  $result = $db->query("SELECT dtuid, uid, passwort FROM dt_user WHERE inaktiv != 'J' AND UPPER(uid)=UPPER('$_POST[user]')");
  $row = $result->fetch_array();
  
  
  // Anzahl der IPs im Monat
  $result1 = $db->query("SELECT count(distinct left( ip, locate( '.', ip, 5 ) -1 )) ips_monat
                            FROM dt_userlog
                           WHERE dtuid ='$row[dtuid]'
                             AND DATE_SUB(NOW(), INTERVAL 1 MONTH) < Datum
                        ");
  $row1 = $result1->fetch_array();
  
  
  // Wenn expiredate überschritten, dann 1
  $result2 = $db->query("SELECT 1
                            FROM dt_user
                           WHERE pw_expire < now()
                             AND dtuid = '$row[dtuid]'
                        ");
  $row2 = $result2->fetch_array();
  

 
  // Leere Textfelder
  if (empty($_POST['user']) or empty($_POST['passwort'])){
    $smarty->assign('index_noinput', "1");
  }
  // Benutzer nicht im System
  elseif (strtoupper($_POST['user']) != strtoupper($row[uid])) {
    $smarty->assign('index_nouser', "1");
  }
  // Passwort falsch
  elseif (md5($_POST['passwort']) != $row[passwort]){  //verschlüsseltes Passwort überprüfen
    # Session-Cookies werden bereits gesetzt, falls sich jemand ein passwort zusenden lässt.
    $_SESSION["user"] = $row[dtuid];
    $smarty->assign('index_passwrong', "1");
  }
  // Passwortwechsel notwendig  
  elseif(($row1[ips_monat] > 2 AND $row2[0] == 1) OR $row[uid] == $_POST['passwort']){ //Wenn mehr als 2 unterschiedliche Provider innerhalb eines Monats und Maximaldauer des Passworts abgelaufen, dann ändern
    $db = dbconnect();
    $datum=date("Y-m-d H:i:s");
    $ip=getenv("REMOTE_ADDR");
    $agent=getenv("HTTP_USER_AGENT");
    $user= $row[dtuid];
    $_SESSION["user"] = $row[dtuid];
    
    $result_dt = $db->query("SELECT dtid FROM dt_user_tankstelle WHERE dtuid='$user' LIMIT 1");
    $row_dt = $result_dt->fetch_array();
    $_SESSION["dtid"] = $row_dt[dtid];
    
    $result_1 = $db->query("INSERT INTO dt_userlog (Datum, IP, user_agent, dtuid) VALUES ('$datum', '$ip', '$agent', '$user')");
    $sql = $db->query ("UPDATE dt_user SET mail_inaktiv='0000-00-00 00:00:00' WHERE dtuid='$user'");
    $smarty->assign('index_passswitch', "1");
  }else{
    $db = dbconnect();
    $datum=date("Y-m-d H:i:s");
    $ip=getenv("REMOTE_ADDR");
    $agent=getenv("HTTP_USER_AGENT");
    $user= $row[dtuid];
    $_SESSION["user"] = $row[dtuid];
    
    $result_dt = $db->query("SELECT dtid FROM dt_user_tankstelle WHERE dtuid='$user' LIMIT 1");
    $row_dt = $result_dt->fetch_array();
    $_SESSION["dtid"] = $row_dt[dtid];

    $result_1 = $db->query("INSERT INTO dt_userlog (Datum, IP, user_agent, dtuid) VALUES ('$datum', '$ip', '$agent', '$user')");
    $sql = $db->query ("UPDATE dt_user SET mail_inaktiv='0000-00-00 00:00:00' WHERE dtuid='$user'");    $smarty->assign('index_login', "1");
  }
  mysqli_close($db);
  */
}


if($action == 'pass_gen'){

 $dtuid = $_SESSION["user"];
 
 $pool = "qwertzupasdfghkyxcvbnm";
 $pool .= "23456789";
 $pool .= "WERTZUPLKJHGFDSAYXCVBNM";
 
 srand ((double)microtime()*1000000);
 for($index = 0; $index < 7; $index++)
 {
     $pass_word .= substr($pool,(rand()%(strlen ($pool))), 1);
 }
 
 $new_pw_md5=md5($pass_word);
 
 $db = dbconnect();
 $result = $db->query("SELECT distinct DATE_ADD(NOW(), INTERVAL 1 MONTH) exp_date
                          FROM dt_user
                         WHERE dtuid ='$dtuid'
                      ");
 $row = $result->fetch_array();
 
 $sql = $db->query ("UPDATE dt_user SET passwort='$new_pw_md5', pw_expire='$row[exp_date]' WHERE dtuid='$dtuid'");
 
 $result2 = $db->query("SELECT uid, vorname, nachname, mail FROM dt_user WHERE dtuid='$dtuid'");
 $row2 = $result2->fetch_array();
 
 $empfaenger = "$row2[mail]";
   $betreff = "RefillDB: Passwort zurückgesetzt";
   $text = "
     <html>
     <head>
     <title>Passwort zur&uuml;ckgesetzt</title>
     </head>
     <body>
     <font face='Arial' size='2'>
     Guten Tag $row2[vorname] $row2[nachname]!<br><br>
     Sie haben Ihr Passwort innerhalb der RefillDB zur&uuml;ckgesetzt!<br>
     Nachfolgend finden Sie Ihre neuen Zugangsdaten:
     <br>
     <br>
     <table>
     <tr>
        <td valign='top'>
          <font face='Arial' size='2'>
            Benutzerkennung:
          </font>
        </td>
        <td valign='top'>
          <font face='Arial' size='2'>
            <b>$row2[uid]</b>
          </font>
        </td>
     </tr>
     <tr>
        <td valign='top'>
          <font face='Arial' size='2'>
            Passwort:
          </font>
        </td>
        <td valign='top'>
          <font face='Arial' size='2'>
            <b>$pass_word</b>
          </font>
        </td>
     </tr>
     </table>
     <br>
     Bitte beachten Sie, dass zwischen Gro&szlig;- und<br>
     Kleinschreibung unterschieden wird.
     <p>
     Link zu Leitgedanken-Online: <a href=\"https://www.lg-on.de/refill\">RefillDB</a>
     <p>
     Diese Mail wurde automatisch generiert!<br>
     Antworten Sie daher nicht auf diese Mail.<br />
     <br>
     Vielen Dank!
     </body>
     </html>";
 
 
 $headers = "MIME-Version: 1.0\n";
 $headers .= "Content-type: text/html; charset=utf-8\n";
 $headers .= "From: RefillDB <$row2[mail]>\n";
     
 $return = @mail($empfaenger, $betreff, $text,  $headers);
 
 if($return){
  $smarty->assign('index_mailpass', "1");
  $mailadresse = $row2[mail];
  $smarty->assign('index_mailadr', "$mailadresse");
 }else{
  $smarty->assign('index_nomailpass', "1");
 }
}


$smarty->assign('action', "$action");


$smarty->display("$template/$templatename");
?>