<?php
    require("config.php");
    
    if (!function_exists("getuserdata"))
    {
    function getuserdata($paramname, $defaultvalue=NULL)
    {
        if (isset($_REQUEST[$paramname]))
            if ($_REQUEST[$paramname] != "")
                if (get_magic_quotes_gpc())
                    return $_REQUEST[$paramname];
                else
                    return addslashes($_REQUEST[$paramname]);
            else return $defaultvalue;
        else return $defaultvalue;
    }
    }

    @session_start();

    $connected = false;
    $authenticated = false;

    if (isset($_SESSION['saved_session_id']))
        if ($_SESSION['saved_session_id'] != session_id())
        {
            $_SESSION['saved_session_id'] = session_id();
            unset($_SESSION['masterpassword']);
        }
        else ;
    else $_SESSION['saved_session_id'] = session_id();

    $connection = mysql_connect($dbserver, $dbuser, $dbpass, true);
    $db = mysql_select_db($dbname);
    $error = "";
    if ($connection)
    {
        $connected = true;
        $q = mysql_query("SET CHARACTER SET latin2");
        if (isset($_POST['utilizator'])) $_SESSION['utilizator'] = getuserdata('utilizator');
        if (isset($_POST['parola'])) $_SESSION['parola'] = getuserdata('parola');
        if (!isset($_SESSION['utilizator'])) $_SESSION['utilizator'] = '';
        if (!isset($_SESSION['parola'])) $_SESSION['parola'] = '';
        if ($_SESSION['utilizator'] && $_SESSION['parola'])
        {
        $q = mysql_query("SELECT * FROM utilizatori WHERE utilizator = '{$_SESSION['utilizator']}' ".
                         "AND parola = '".sha1($_SESSION['parola'])."'");
        if ($q)
        {
            if (mysql_num_rows($q) == 1)
            {
                $authenticated = true;
            }
            else $error = 'Nume utilizator sau parola gresite';
        }
        else $error = "Eroare la preluarea datelor din baza de date!";
        }
    }
    else $error = "Serverul de date este oprit. Reveniți mai tarziu!.<br><br>".mysql_error();

    if (!function_exists("check_auth"))
    {
        function check_auth()
        {
            global $authenticated;
            if (!$authenticated)
            {
                header("Location: {$scriptindex}admin/index.php");
                echo "Apăsați <a href='{$scriptindex}admin/index.php'>aici</a> pentru conectare în sistem.";
                exit;
            }
        }
    }

    if (!function_exists("check_connected"))
    {
        function check_connected()
        {
            global $connected;
            if (!$connected)
            {
                header("Location: {$scriptindex}admin/index.php");
                echo "Apăsați <a href='{$scriptindex}admin/index.php'>aici</a> pentru conectare în sistem.";
                exit;
            }
        }
    }
?>