<?php
/**
 * @package Flatnux_auth_local
 * @param array $arrayfilter
 * @return int
 */
function FN_CountUsers($arrayfilter=false)
{
    $Table = FN_XmlTable("fn_users");
    return $Table->GetNumRecords($arrayfilter);
}
/**
 *
 * @param array $arrayfilter
 * @return array
 */
function FN_GetUsers($arrayfilter=false)
{
    $Table = FN_XmlTable("fn_users");
    return $Table->GetRecords($arrayfilter);
}
/**
 *
 */
function FN_ManageLogin()
{
    global $_FN;
    $fnlogin = FN_GetParam("fnlogin", $_GET);
    $fnuser = FN_GetParam("username", $_POST);
    $fnpwd = FN_GetParam("password", $_POST);
    $captcha_ok = true;
    //-------------------captcha----------------------------------------------->
    if (!empty($_FN['enable_captcha']))
    {
        $captcha = FN_GetSessionValue("captcha");
        $fnlogincode = FN_GetParam("fnlogin_code", $_POST);
        if ($fnlogincode == "" || empty($captcha['fnlogin_code']) || $captcha['fnlogin_code'] != $fnlogincode)
        {
            $captcha_ok = false;
            FN_SetSessionValue("captcha", array("fnlogin_code" => rand(1000, 9999)));
        }
    }
    //-------------------captcha-----------------------------------------------<
    $rememberlogin = FN_GetParam("rememberlogin", $_POST);
    if ($fnlogin == "login" && $fnuser != "" && $fnpwd != "")
    {
        if ($captcha_ok && FN_VerifyUserPassword($fnuser, $fnpwd))
        {
            FN_Login($fnuser, $rememberlogin);
        }
        else
        {
            FN_Logout();
            $_FN['login_error'] = "error username or password";
        }
    }
    $_FN['user'] = FN_GetParam("fnuser", $_COOKIE);
    if (!FN_CheckUser() || $fnlogin == "logout")
    {
        FN_Logout();
    }
}
/**
 *
 * @global array $_FN
 */
function FN_LoginForm()
{
    echo FN_HtmlLoginForm();
}
/**
 *
 * @global array $_FN
 */
function FN_HtmlLoginForm()
{
    global $_FN;
    $html = "";
    $querystring = FN_GetParam("QUERY_STRING", $_SERVER);
    $querystring = str_replace("&", "&amp;", $querystring);
    $html.= "<form method=\"post\" action=\"?$querystring&amp;fnlogin=login\" ><div>";
    $html.= (!empty($_FN['username_is_email'])) ? FN_Translate("email") : FN_Translate("username");
    $html.= "<br /><input type=\"text\" size=\"15\" name=\"username\" /></div>";
    $html.= "<div>" . FN_Translate("password") . "<br /><input type=\"password\" size=\"15\" name=\"password\" /></div>";
    //------------------------------------ captcha ---------------------------->
    $captcha_ok = true;
    if (!empty($_FN['enable_captcha']))
    {
        $captcha = FN_GetSessionValue("captcha");
        $fnlogincode = FN_GetParam("fnlogin_code", $_POST);
        if ($fnlogincode == "" || empty($captcha['fnlogin_code']) || $captcha['fnlogin_code'] != $fnlogincode)
            $captcha_ok = false;
        FN_SetSessionValue("captcha", array("fnlogin_code" => rand(1000, 9999)));
        $html.= "<div>" . FN_Translate("enter this security code") . ":<img style=\"vertical-align:middle\" src=\"{$_FN['siteurl']}captcha.php?t=fnlogin_code&amp;" . time() . "\" alt=\"\" title=\"\" /> <input size=\"4\" name=\"fnlogin_code\"  value = \"\" /></div>";
    }
    //------------------------------------ captcha ----------------------------<
    $html.= "<div><button type=\"submit\" >" . FN_Translate("login") . "</button></div>";
    if (!empty($_FN['remember_login']))
        $html.= "<div>" . "<input type=\"checkbox\" name=\"rememberlogin\" value=\"1\" />&nbsp;" . FN_Translate("stay connected") . "</div>";
    $html.= "</form>";
    if (!empty($_FN['login_error']))
    {
        $html.= "<div style=\"background-color:yellow;color:red\" >" . FN_Translate("authentication failure") . "</div>";
    }
    return $html;
}
/**
 *
 * @global array $_FN
 */
function FN_HtmlLogoutForm()
{
    global $_FN;
    $querystring = FN_GetParam("QUERY_STRING", $_SERVER);
    $querystring = str_replace("&", "&amp;", $querystring);
    $html = "<form method=\"post\" action=\"?$querystring&amp;fnlogin=logout\" >";
    $html.= "<div><button type=\"submit\">" . FN_i18n("logout") . "</button></div>";
    $html.= "</form>";
    return $html;
}
/**
 *
 * @global array $_FN
 */
function FN_LogoutForm()
{
    echo FN_HtmlLogoutForm();
}
/**
 *
 * @global  $_FN
 * @param string $fnuser
 * @param string $fnpwd
 * @return bool
 */
function FN_VerifyUserPassword($fnuser, $fnpwd)
{
    global $_FN;
    if (!empty($_FN['FN_VerifyUserPassword']) && $_FN['FN_VerifyUserPassword']!="FN_VerifyUserPassword" && function_exists($_FN['FN_VerifyUserPassword']))
    {
        return $_FN['FN_VerifyUserPassword']($fnuser, $fnpwd);
    }
    $lpass = md5($fnpwd);
    $us = FN_GetUser($fnuser);
    $passwd = $us['passwd'];
    if ($passwd == $lpass)
        return true;
    else
        return false;
}
/**
 *
 * @global  $_FN
 * @staticvar array $usercache
 * @param string $user
 * @param bool $usecache
 * @return array
 */
function FN_GetUser($user, $usecache = true)
{
    if ($user == "")
        return false;
    static $usercache = false;
    global $_FN;
	if ($usecache)
	{
		if ($usercache && is_array($usercache) && isset($usercache[$user]))
			return $usercache[$user];
    }
	$table = FN_XmlTable("fn_users");
    $UserValues = $table->GetRecordByPrimaryKey($user);
    if ($UserValues['level'] === "")
        $UserValues['level'] = "0";
    if (empty($UserValues['username']))
        return false;
    $_FN['uservalues'] = $usercache[$user] = $UserValues;
    return $usercache[$user];
}
/**
 *
 * @global  $_FN
 * @staticvar array $usercache
 * @param string $user
 * @param bool $usecache
 * @return int
 */
function FN_GetUserLevel($user, $usecache = true)
{
    $user = FN_GetUser($user, $usecache);
    if (!isset($user['level']))
        return -1;
    return $user['level'];
}
/**
 *
 * @param string $user
 * @return string
 */
function FN_GetPassword($user)
{
    $uservalues = FN_GetUser($user, false);
    if (!isset($uservalues['passwd']))
        return null;
    $pass = $uservalues['passwd'];
    return $pass;
}
/**
 *
 * @global  $_FN
 * @param string $fnuser
 * @return bool
 */
function FN_Login($fnuser, $rememberlogin=false)
{
    global $_FN;
    $password = Fn_GetPassword($fnuser);
    $us = FN_GetUser($fnuser, false);
    if ($us['active'] == 1)
    {
//---------------------url cookie---------------------------------------------->
        global $_FN;
        if (empty($_FN['urlcookie']))
        {
            $urlcookie = FN_GetParam("PHP_SELF", $_SERVER);
            $path = pathinfo($urlcookie);
            $urlcookie = $path["dirname"] . "/";
            $urlcookie = str_replace("\\", "/", $urlcookie);
            if ($urlcookie == "" || $urlcookie == "\\" || $urlcookie == "//")
                $urlcookie = "/";
            $_FN['urlcookie'] = $urlcookie;
        }
//---------------------url cookie----------------------------------------------<
        if (empty($_FN['remember_login']) || $rememberlogin == "")
        {
            setcookie("fnuser", $fnuser, 0, $_FN['urlcookie']);
            setcookie("secid", md5($fnuser . $password), 0, $_FN['urlcookie']);
        }
        else
        {
            setcookie("fnuser", $fnuser, time() + 99999999, $_FN['urlcookie']);
            setcookie("secid", md5($fnuser . $password), time() + 99999999, $_FN['urlcookie']);
        }
        FN_Log("User $fnuser login (function FN_Login).");
        $_FN['user'] = $_COOKIE['fnuser'] = $fnuser;
        $_COOKIE['secid'] = md5($fnuser . $password);

        return true;
    }
    else
    {
        return false;
    }
}
/**
 *
 * @global  $_FN
 * @param string $fnuser
 */
function FN_Logout()
{
//---------------------url cookie---------------------------------------------->
    global $_FN;
    if (empty($_FN['urlcookie']))
    {
        $urlcookie = FN_GetParam("PHP_SELF", $_SERVER);
        $path = pathinfo($urlcookie);
        $urlcookie = $path["dirname"] . "/";
        $urlcookie = str_replace("\\", "/", $urlcookie);
        if ($urlcookie == "" || $urlcookie == "\\" || $urlcookie == "//")
            $urlcookie = "/";
        $_FN['urlcookie'] = $urlcookie;
    }
//---------------------url cookie----------------------------------------------<

    setcookie("secid", "", 0, $_FN['urlcookie']);
    setcookie("fnuser", "", 0, $_FN['urlcookie']);
    setcookie("secid", "", 0, "/");
    setcookie("fnuser", "", 0, "/");
    $_FN['user'] = "";
    unset($_COOKIE['fnuser']);
    unset($_COOKIE['secid']);
}
/**
 * deleta user
 * @param string $user
 */
function FN_DeleteUser($user)
{
    global $_FN;
    if ($user != "")
    {
        $table = FN_XmlTable("fn_users");
        $table->DelRecord($user);
        if (file_exists("{$_FN['datadir']}/fndatabase/fn_users/" . $user))
        {
            remove_dir_rec("{$_FN['datadir']}/fndatabase/fn_users/" . $user);
        }
    }
}
/**
 * @param string $user
 * @param array $newvalues
 */
function FN_UpdateUser($user, $newvalues)
{
    if ($user != "")
    {
        if (!isset($newvalues['username']))
            $newvalues['username'] = $user;
        $table = FN_XmlTable("fn_users");
        if (isset($newvalues['passwd']))
        {
            if (!empty($newvalues['passwd']))
                $newvalues['passwd'] = md5($newvalues['passwd']);
            else
                unset($newvalues['passwd']);
        }
        $newvalues = $table->UpdateRecord($newvalues);
		FN_GetUser($user, false);
        return $newvalues;
    }
    return false;
}
/**
 *
 * @param array $newvalues
 * @return bool
 */
function FN_AddUser($newvalues)
{
    if ($newvalues['username'] != "")
    {
        $table = FN_XmlTable("fn_users");
        $newvalues['passwd'] = md5($newvalues['passwd']);
        if ($table->InsertRecord($newvalues))
        {
			if (function_exists("FN_OnAddUser"))
			{
				FN_OnAddUser($newvalues);
			}
			return true;
		}
    }
    return false;
}
/**
 *
 * @global array $_FN
 * @return bool 
 */
function FN_CheckUser()
{
    global $_FN;
    $secid = FN_GetParam("secid", $_COOKIE);
    $UserValues = FN_GetUser($_FN['user']);
    if (empty($secid) || empty($UserValues['passwd']))
        return false;
    $RequiredSecid = md5($_FN['user'] . $UserValues['passwd']);
    if ($RequiredSecid == $secid)
        return true;
    return false;
}
/**
 *
 * @global array $_FN
 * @param string $user
 * @return string 
 */
function FN_GetUserImage($user)
{
    global $_FN;
    $user = FN_GetUser($user);
    if (!empty($user['avatar']))
    {
        $image = urldecode(FN_GetParam("avatar", $user, "html"));
        $image = "{$_FN['datadir']}/{$_FN['database']}/fn_users/{$user['username']}/avatar/$image";
    }
    elseif (!empty($user['avatarimage']))
    {
        $image = urldecode($user['avatarimage']);
        $image = "{$_FN['datadir']}/{$_FN['database']}/fn_avatars/$image/filename/$image";
    }
    else
    {
        $image = FN_FromTheme("images/user.png",false);
    }
    return $image;
}
/**
 *
 * @global array $_FN
 * @param string $user
 * @return string 
 */
function FN_HtmlUserImage($user)
{
    global $_FN;
    $imagesrc = FN_GetUserImage($user);
    $image = "<img alt=\"\" src=\"{$_FN['siteurl']}$imagesrc\" />";
    return $image;
}
?>
