<?php


include_once("session.php");

class Process
{
    /* Class constructor */
    function __construct(){
        global $session,$db;

        /* User submitted login form */
        if(isset($_REQUEST['sublogin'])){
            $this->procLogin();
        }

        /* User submitted forgot password form */
        else if(isset($_POST['subforgot'])){
            $this->procForgotPass();
        }

        /* User entered with login key from foreign system */
        // This will allow people to log in on the fly from other systems (for SPE versoins)
        // lgpkey should consist of 2 md5 hashes, one for username and one for password, seperated by a colon
        else if (isset($_REQUEST['lgpkey'])) {
            if (_LOGAHOLIC_EDITION == 4 || LOGAHOLIC_BASE_EDITION == "cPanel Edition") {
                echo "This functionality is not available in Logaholic SPE for cPanel.";
                exit();
            } else {
                $this->procLogout();
                $lgpkey = explode(":",$_REQUEST['lgpkey']);
                $q = "SELECT username FROM ".TBL_USERS." WHERE MD5(username) = ".$db->Quote($lgpkey[0]);
                $result = $db->Execute($q) or die("Error locating user: " . $db->ErrorMsg());
                $data= $result->FetchRow();
                $_REQUEST['login_user'] = $data["username"];
                $_REQUEST['login_pass'] = @$lgpkey[1];
                $_REQUEST['login_remember'] = 1;
                $this->procLogin();
            }
        }
    }

    /**
     * procLogin - Processes the user submitted login form, if errors
     * are found, the user is redirected to correct the information,
     * if not, the user is effectively logged in to the system.
     */
    function procLogin(){
        global $session, $form, $cloudapi;
        /* Login attempt */
        $retval = $session->login($_REQUEST['login_user'], $_REQUEST['login_pass'], isset($_REQUEST['login_remember']));

        /* Login successful */
        if($retval){
        }
        /* Login failed */
        else{
            if (!empty($cloudapi)) {
                //echo "failed so try cloud $cloudapi<br>";
                include_once "$cloudapi/includes/CloudApi.php";
                include_once "$cloudapi/includes/Server.php";
                include_once "$cloudapi/includes/User.php";
                $cuser = new User();
                $cuser->username = $_REQUEST['login_user'];
                $cuser->password = $_REQUEST['login_pass'];

                $info = $cuser->UserLoginUrl();
                //$info = json_decode($cuser->UserLoginUrl(), true);
                if(empty($info['Status']) || $info['Status'] == "Error"){
                    $form->clearErrors();
                    if ($info['Msg'] == "Unknown User") {
                        $form->setError("login_user", $info['Msg']);
                    } else if ($info['Msg'] == "Invalid Password") {
                        $form->setError("login_pass", $info['Msg']);
                    } else {
                        # some uninteresting error, just continue.
                    }
                } else {
                    header("Location: {$info['Url']}");
                    exit();
                }
                //dump($info);
                //exit();

            }

            $_SESSION['value_array'] = $_POST;
            $_SESSION['error_array'] = $form->getErrorArray();
        }
    }

    /**
     * procLogout - Simply attempts to log the user out of the system
     * given that there is no logout form to process.
     */
    function procLogout(){
        global $session;

        $retval = $session->logout();
        $_SESSION['value_array'] = "";
    }

    /**
     * procForgotPass - Validates the given username then if
     * everything is fine, a new password is generated and
     * emailed to the address the user gave on sign up.
     */
    function procForgotPass(){
        global $database, $session, $mailer, $form;
        /* Username error checking */
        $subuser = $_POST['login_user'];

        $field = "login_user";  //Use field name for username
        if(!$subuser || strlen($subuser = trim($subuser)) == 0){
            $form->setError($field, "* Username not entered<br>");
        } else {
            /* Make sure username is in database */
            $subuser = stripslashes($subuser);
            if(strlen($subuser) < 1 || strlen($subuser) > 100 || (preg_match("/[^0-9A-Za-z@.\-\_]/" ,$subuser)===1) || (!$database->usernameTaken($subuser))) {
                $form->setError($field, "* Username does not exist<br>");
            } else {
                /* Get email of user */
                $usrinf = $database->getUserInfo($subuser);
                $email  = $usrinf['email'];
                if ($email=="") {
                    $form->setError($field, "* There is no email address associated with your account<br>");
                }
            }

            if(!empty($usrinf["metadata"]) && intval($usrinf['isAdmin']) !== 1) {
                $meta = json_decode($usrinf["metadata"],true);

                if(isset($meta["changeAccountInfo"]) && (!$meta["changeAccountInfo"]) ){
                    $form->setError($field, "* This user cannot request a new password. Please contact your administrator<br>");
                }
            }
        }
        // exit;
        /* Errors exist, have user correct them */
        if($form->num_errors > 0){
            $_SESSION['value_array'] = $_POST;
            $_SESSION['error_array'] = $form->getErrorArray();
        } else {
            /* Generate new password */
            $newpass = $session->generateRandStr(8);

            /* Attempt to send the email with new password */
            if($mailer->sendNewPass($subuser,$email,$newpass)){
                /* Email sent, update database */
                $database->updateUserField($subuser, "password", md5($newpass));
                $_SESSION['forgotpass'] = true;
            } else {
                /* Email failure, do not change password */
                $_SESSION['forgotpass'] = false;
            }
        }
    }
}

?>
