<?php
/*
# Fuer debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);
#echo __LINE__."<br>";
*/
session_start();

include_once 'classes/lg-on_Smarty.class.php';
$smarty = new lgon_Smarty();
require_once("config.inc.php");
$template = "standard";
$templatename = substr(basename($_SERVER['PHP_SELF']),0,-3)."html";
require_once "language/german.inc.php";


if(isset($_GET['action'])){
  $action = $_GET['action'];
}else{
  $action = '';
}

if($action == ''){
}


if($action == 'anmeld'){

  $db = dbconnect();
  $result = $db->query( "SELECT vaid, user, passwort FROM admin WHERE inaktiv != 'J' AND UPPER(user)=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 userlog
                          WHERE uid ='$row[user]'
                            AND DATE_SUB(NOW(), INTERVAL 1 MONTH) < Datum
                        " );
  $row1 = $result1->fetch_array();

  // Anzahl der Anmeldungen der letzten 5 Minuten
  $result1a = $db->query( "SELECT count(*) logins
                           FROM userlog
                          WHERE uid ='$row[user]'
                            AND DATE_SUB(NOW(), INTERVAL 5 MINUTE ) < Datum
                        " );
  $row1a = $result1a->fetch_array();


  // Wenn expiredate überschritten, dann 1
  $result2 = $db->query( "SELECT 1
                            FROM admin
                           WHERE pw_expire < now()
                             AND user = '$row[user]'
                        ");
  $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['user'])) {
    $smarty->assign('index_nouser', '1');
  }
  // Passwort falsch
  elseif (md5($_POST['passwort']) != $row['passwort']){  //verschlüsseltes Passwort überprüfen
    # Cookies werden bereits gesetzt, falls sich jemand ein passwort zusenden lässt.
    setcookie("user_admin","");
    setcookie("user_admin",$row['user']);
    setcookie("user_vaid","");
    setcookie("user_vaid",$row['vaid']);
    $smarty->assign('index_passwrong', '1');
  }
  // Passwortwechsel notwendig
  elseif(($row1['ips_monat'] > 2 AND $row2[0] == 1) OR $row['user'] == $_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_admin = $row['user'];
#     $url= "http://www.whois-api.com/?$ip";
#     $xml = @simplexml_load_file( $url );
#     $isp = $xml->isp;
#     $host = gethostbyaddr($ip);
#     $organisation = $xml->organization;
    $url=file_get_contents("https://whatismyipaddress.com/ip/$ip");
    preg_match_all('/<th>(.*?)<\/th><td>(.*?)<\/td>/s',$url,$output,PREG_SET_ORDER);
    $isp=$output[4][2];
    $host=$output[2][2];
    $organisation=$output[5][2];

    setcookie("user_admin","");
    setcookie("user_admin",$user_admin);
    $user_vaid = $row['vaid'];
    setcookie("user_vaid","");
    setcookie("user_vaid",$user_vaid);
    $sid = session_id();
    if($row1a['logins'] == 0){
      $result_1 = $db->query( "INSERT INTO userlog (Datum, IP, user_agent, isp, organisation, host, uid, session_id) VALUES ('$datum', '$ip', '$agent', '$isp', '$organisation', '$host', '$user_admin', '$sid')");
    }

    $sql = $db->query( "UPDATE admin SET mail_inaktiv='0000-00-00 00:00:00' WHERE user='$user_admin'");


    $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_admin = $row['user'];
#     $url= "http://www.whois-api.com/?$ip";
#     $xml = @simplexml_load_file( $url );
#     $isp = $xml->isp;
#     $host = gethostbyaddr($ip);
#     $organisation = $xml->organization;
    $url=file_get_contents("https://whatismyipaddress.com/ip/$ip");
    preg_match_all('/<th>(.*?)<\/th><td>(.*?)<\/td>/s',$url,$output,PREG_SET_ORDER);
    $isp=$output[4][2];
    $host=$output[2][2];
    $organisation=$output[5][2];

    setcookie("user_admin","");
    setcookie("user_admin",$user_admin);
    $user_vaid = $row['vaid'];
    setcookie("user_vaid","");
    setcookie("user_vaid",$user_vaid);
    $sid = session_id();
    if($row1a['logins'] == 0){
      $result_1 = $db->query( "INSERT INTO userlog (Datum, IP, user_agent, isp, organisation, host, uid, session_id) VALUES ('$datum', '$ip', '$agent', '$isp', '$organisation', '$host', '$user_admin', '$sid')");
    }
    $sql = $db->query("UPDATE admin SET mail_inaktiv='0000-00-00 00:00:00' WHERE user='$user_admin'");
    $smarty->assign('index_login', '1');
  }
}

if($action == 'pass_gen'){
 $uid1=$_COOKIE["user_admin"];

 $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 admin
                         WHERE user ='$uid1'
                       ");
 $row = $result->fetch_array();

 $sql = $db->query( "UPDATE admin SET passwort='$new_pw_md5', pw_expire='$row[exp_date]' WHERE user='$uid1'");


 $result2 = $db->query("SELECT user, vorname, nachname, mail FROM admin WHERE user='$uid1'");
 $row2 = $result2->fetch_array();

 $empfaenger = "$row2[mail]";
   $betreff = "Leitgedanken-Online: 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 in Leitgedanken-Online 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[user]</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=\"http://www.lg-on.de\">Leitgedanken-Online</a>
     <p>
     Diese Mail wurde automatisch generiert!<br>
     Antworten Sie daher nicht auf diese Mail<br>
     <br>
     Vielen Dank
     </body>
     </html>";


     $text = stripslashes($text);
     $headers = "MIME-Version: 1.0\n";
     #$headers .= "Content-type: text/html; charset=iso-8859-1\n";
     $headers .= "Content-type: text/html; charset=utf-8\n";
     $headers .= "From: Leitgedanken Online <admin@lg-on.de>\n";
     #$headers .= "Bcc: $empfaenger\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");

?>