<?php
    $valid=false;
    include "authcfg.php";
    include "db.php";
    if($db_link) {
        mysqli_select_db($db_link,$db);
        $table="auth";
        $query="desc $table";
        $result=mysqli_query($db_link,$query);
        if(!$result) {
            $query="create table $table (id int not null auto_increment primary key, name varchar(32) not null default '', pass varchar(32) default '', admin int not null default 0, rights int not null default 0, date int not null default 0)";
            mysqli_query($db_link,$query) or die(mysqli_error());
        }
        mysqli_close($db_link);
        unset($db_link);
    }
    $module=isset($module)?$module:"";
    $action=isset($action)?$action:"";
    $loginform="<form action=\"$PHP_SELF?action=login".($module?"&amp;module=$module":"").(!empty($section)?("&amp;section=".$section):"")."&amp;lang=$lang\" method=\"post\">";

    $loginform.= "<table class=\"form\" id=\"login\" width=\"100%\">
    <tr>
        <td width=\"25%\">".getstr("login_name",$lang).":</td>
        <td width=\"75%\"><input name=\"user\" type=\"text\" style=\"width:100%; box-sizing:border-box;\"></td>
    </tr>
    <tr>
        <td>".getstr("login_pass",$lang).":</td>
        <td><input name=\"pass\" type=\"password\" style=\"width:100%; box-sizing:border-box;\"></td>
    </tr>
    <tr>
        <td colspan=\"2\"><hr>".getstr("login_captcha",$lang).":<div style=\"float:right\"><img onclick=\"reload('login_verimg'); document.getElementById('login_ver').value=''; document.getElementById('login_ver').focus()\" src=\"/images/refresh.png\"></div></td>
    </tr>
    <tr>
        <td style=\"text-align:center; min-width:100px\"><img alt=\"Captcha\" src=\"/randimg.php?cid=login\" id=\"login_verimg\"></td>
        <td><input name=\"ver\" id=\"login_ver\" type=\"text\" style=\"width:100%; box-sizing:border-box;\"></td>
    </tr>
    <tr>
        <td colspan=\"2\"><hr></td>
    </tr>
    <tr>
        <td colspan=\"2\" style=\"text-align:center\"><input value=\"".getstr("login",$lang)."\" type=\"submit\"></td>
    </tr>
</table>
</form>";

    function getUser($name) {
        global $login, $adm;
        if ($name == $adm[0]) {
            $login=$adm;
            return true;
        } else {
            include "db.php";
            if($db_link) {
                mysqli_select_db($db_link,$db);
                $table="auth";
                $query="select name, pass, admin from auth where name='".mysqli_real_escape_string($db_link,$name)."'";
                $result=mysqli_query($db_link,$query) or die(mysqli_error());
                $count=mysqli_num_rows($result);
                if($count > 0) {
                    $arr=mysqli_fetch_assoc($result);
                    $login=array($arr['name'],$arr['pass'],$arr['admin'],false);
                } else
                    $login=false;
                mysqli_close($db_link);
                return $login != false;
            }
        }
    }
    function checkPw($name,$pass) {
        global $login;
        if ($name == $login[0] && $pass == $login[1]) {
            if (empty($_SESSION['name'])) $_SESSION['name']=$name;
            if (empty($_SESSION['pass'])) $_SESSION['pass']=$pass;
            if (empty($_SESSION['captcha'])) $_SESSION['captcha']=true;
            return true;
        } else return false;
    }
    if($action=="logout") {
        //session_unset();
        unset($_SESSION['name'], $_SESSION['pass'], $_SESSION['captcha']);
        header("Location: $PHP_SELF?".($module?"module=$module&":"").(!empty($section)?("section=$section&"):"")."lang=$lang");
        exit;
    }
    $capcheck=true;
    //unset($adm);
    $valid=false;
    $admin=false;
    $login=false;
    $redir=false;
    if (!empty($_POST) && $action=="login") {
        $ver=isset($_POST['ver'])?$_POST['ver']:"";
        if (empty($_COOKIE)) {
            $err=getstr("loginerr_nocookies",$lang);
            $msg= getinfo()."No cookies\n";
        } elseif(empty($_SESSION)) {
            $err=getstr("loginerr_nosession",$lang); //No session cookie set.
            $msg= getinfo()."No session cookie set\n";
        } elseif (!isset($_SESSION['data']['login']['captcha'])) {
            $err=getstr("loginerr_badcaptcha",$lang);//The Captcha value is missing.
            $msg= getinfo()."No Captcha Hash".(!empty($_POST['name'])?(" (User name: ".$_POST['name'].")"):"")."\n";
        } elseif (empty($ver)) {
            $err=getstr("loginerr_captchamissing",$lang);//You forgot to type the Captcha.
            $msg= getinfo()."Captcha Missing".(!empty($_POST['name'])?(" (User name: ".$_POST['name'].")"):"")."\n";
        } elseif (md5($ver) != $_SESSION['data']['login']['captcha']) {
            $err=getstr("loginerr_captchafail",$lang);//The Captcha is not correct.
            $msg= getinfo()."Bad Captcha:$ver".(!empty($_POST['name'])?(" (User name: ".$_POST['name'].")"):"")."\n";
        } elseif (empty($_POST['user'])) {
            $err=getstr("loginerr_userblank",$lang); //You forgot to enter user name.;
            $msg= getinfo()."Invalid Login\n";
        } elseif (!getUser($_POST['user'])) {
            $err=getstr("loginerr_usermissing",$lang);//The user name does not exist.
            $msg= getinfo()."Invalid user: ".$_POST['user']."\n";
        } elseif (empty($_POST['pass'])) {
            $err=getstr("loginerr_blankpassword",$lang);
            $msg= getinfo()."Invalid Password for user ".$_POST['user']."\n";
        } elseif (!checkPw($_POST['user'],md5($_POST['pass']))) {
            $err=getstr("loginerr_wrongpassword",$lang);
            $msg= getinfo()."Invalid Password for user ".$_POST['user']."\n";
        } else {
            $admin=$login[2];
            $valid=true;
            $redir=true;
        }
        if (isset($msg)) {
            $file=fopen("$prefix/logs/login.txt", "a");
            fwrite($file, $msg);
            fclose($file);
        }
        if(isset ($_SESSION['data']) && isset($_SESSION['data']['login'])) unset($_SESSION['data']['login']);
    } elseif(isset($_SESSION['name']) && isset($_SESSION['pass']) && getUser($_SESSION['name']) && checkPw($_SESSION['name'],$_SESSION['pass'])) {
        if (!isset($_SESSION['captcha']) || $_SESSION['captcha'] != true)
            unset($_SESSION['name'], $_SESSION['pass'], $_SESSION['captcha']);
        else {
            $valid=true;
            $admin=$login[2];
        }
    }
    if($redir) {
        header("Location: $PHP_SELF?".($module?"module=$module&":"").(!empty($section)?("section=".$section."&"):"")."lang=$lang");
        exit;
    }
    if (!isset($valid) || $valid == false) {
        if (!isset($_SESSION['data'])) $_SESSION['data']=Array();
        $agent=!empty($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:"";
        if (!isset($_SESSION['data']['login']['time']) || $_SESSION['data']['login']['time'] < time())
            $_SESSION['data']['login']=Array("time"=>time(),"ip"=>$ip,"agent"=>$agent);
        foreach(array_keys($_SESSION['data']) as $value) {
            if (!isset($_SESSION['data'][$value]['time']) || $_SESSION['data'][$value]['time'] <= time()-5*60)
                unset($_SESSION['data'][$value]);
        }
    }
?>