<commit_before><?php
use application\classes\Registry;
use application\classes\Session;
class Users
{
    protected $table = 'users';
    protected $user = array();
    private $is_authorized = false;
    private $user_id = null;
    private $sid;
    private $errorValid = '';

    public function __construct()
    {
        $this->db = Registry::get('database');
    }
    public function create()
    {
        $login = preg_match('/^[a-zA-Z0-9_-]{3,16}$/', $_POST['login']) ? $_POST['login'] : false;
        $password = preg_match('/^[a-zA-Z0-9_-]{3,18}$/', $_POST['password1']) ? $_POST['password1'] : false;
        $name = preg_match('/^[a-zA-ZА-Яа-я]{3,18}$/', $_POST['name']) ? $_POST['name'] : false;
        $email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
        $phone = preg_match('/^\+38\d{10}$/', $_POST['phone']) ? $_POST['phone'] : false;

        if(!$name) {
            return $this->errorValid = "Не правильно введено имя!<br />";
        }
        if(!$login) {
            return $this->errorValid = "Не правильно введен логин!<br />";
        }

        if(!$email){
            return $this->errorValid = "Введите правильный email!<br />";
        }
        if(!$password){
            return $this->errorValid = "Пароль не соответствует правилам заполнения<br />";
        }
        if($password !== $_POST['password2']) {
            return $this->errorValid = "Пароли не совпадают<br />";
        }

        $user_exists = $this->getSalt($login);
        if($user_exists) {
            return $this->errorValid .= "Пользователь с таким логином уже существует<br />";
        }

        $hashes = $this->passwHash($password);
        $data['login'] = $login;
        $data['name'] = $name;
        $data['email'] = $email;
        $data['password'] = $<PASSWORD>['<PASSWORD>'];
        $data['salt'] = $hashes['salt'];
        $data['phone'] = $phone;
        $data['create_time'] = date('Y-m-d H:i:s');

        $this->user = $data;

        try {
            $this->db->insert($this->table, $this->user);
        }catch(PDOException $e){
            echo "Database error: ".$e->getMessage();
            die();
        }
        return true;
    }

    public function getSalt($login) {
        return $this->db->fetchOne($this->table, 'salt', ['login' => $login]);
    }

    public function authorize($remember = false)
    {
        $this->clearUsers();
        $login = preg_match('/^[a-zA-Z0-9_-]{3,16}$/', $_POST['login']) ? $_POST['login'] : false;
        $password = preg_match('/^[a-zA-Z0-9_-]{3,18}$/', $_POST['password']) ? $_POST['password'] : false;
        if (!$login) {
            return $this->errorValid = 'Логин должен состоять только из букв английского алфавита и цифр';
        }
        if(!$password) {
            return $this->errorValid = 'Пароль не соответствует правилам составления';
        }

        $salt = $this->getSalt($login);
        if(!$salt) {
            return $this->errorValid = "Пользователь с таким логином не существует!<br />";
        }
        $hashes = $this->passwHash($password, $salt);
        $this->user = $this->db->fetchRow($this->table, ['*'], ['login' => $login, 'password' => $hashes['hash']]);
        if(!$this->user) {
            return $this->errorValid = "Не правильно введен пароль!<br />";
        }
        if($this->user['status'] == 'registered') {
            return $this->errorValid = "Пользователь еще не активирован.<br />";
        }
        if($this->user) {
            $this->user_id = $this->user['id'];
            $this->saveSession($remember);
            $this->is_authorized = true;
        }
        else return;

    }


    public static function isAuthorized()
    {
        if (!empty($_SESSION["user_id"])) {
            return (bool) $_SESSION["user_id"];
        }
        return false;
    }


    public function passwHash($password, $salt = false)
    {
        $salt || $salt = uniqid();
        $hash = md5(md5($password . md5(sha1($salt))));
        return ['hash' => $hash, 'salt' => $salt];
    }

    public function saveSession($remember = false, $http_only = true, $days = 7)
    {
        $_SESSION["user_id"] = $this->user['id'];
        $guid = $this->generateStr();
        $this->db->update($this->table, ['guid' => $guid], ['id' => $this->user_id]);

        if ($remember) {
            $expire = time() + $days * 24 * 3600;
            $domain = ""; // default domain
            $secure = false;
            $path = "/";

            $cookie = setcookie("sid", $guid, $expire, $path, $domain, $secure, $http_only);
        }
    }

    public function clearUsers()
    {
        $min = date('Y-m-d H:i:s', time() - 60 * 10);
        $where = [':minn' => $min];
        //$this->db->query("DELETE FROM users WHERE create_time > :minn AND status = 'registered'", $where);
    }

    public function get($userId = null)
    {
       // $this->clearUsers();

        if($userId === null)
            $this->user_id = $this->getUid();

        if($this->user_id == null)
            return false;

        $this->user = $this->db->fetchRow($this->table, ['*'], ['id' => $this->user_id]);
        return $this->user;
    }

    private function generateStr($length = 10)
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPRQSTUVWXYZ0123456789";
        $code = "";
        $clen = strlen($chars) - 1;

        while (strlen($code) < $length)
            $code .= $chars[mt_rand(0, $clen)];

        return $code;
    }
<commit_msg>edit model Users<commit_after><?php
use application\classes\Registry;
use application\classes\Session;
class Users
{
    protected $table = 'users';
    protected $user = array();
    private $is_authorized = false;
    private $user_id = null;
    private $sid;
    private $errorValid = '';

    public function __construct()
    {
        $this->db = Registry::get('database');
    }
    public function create()
    {
        $login = preg_match('/^[a-zA-Z0-9_-]{3,16}$/', $_POST['login']) ? $_POST['login'] : false;
        $password = preg_match('/^[a-zA-Z0-9_-]{3,18}$/', $_POST['password1']) ? $_POST['password1'] : false;
        $name = preg_match('/^[a-zA-ZА-Яа-я]{3,18}$/', $_POST['name']) ? $_POST['name'] : false;
        $email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
        $phone = preg_match('/^\+38\d{10}$/', $_POST['phone']) ? $_POST['phone'] : false;

        if(!$name) {
            return $this->errorValid = "Не правильно введено имя!<br />";
        }
        if(!$login) {
            return $this->errorValid = "Не правильно введен логин!<br />";
        }

        if(!$email){
            return $this->errorValid = "Введите правильный email!<br />";
        }
        if(!$password){
            return $this->errorValid = "Пароль не соответствует правилам заполнения<br />";
        }
        if($password !== $_POST['password2']) {
            return $this->errorValid = "Пароли не совпадают<br />";
        }

        $user_exists = $this->getSalt($login);
        if($user_exists) {
            return $this->errorValid .= "Пользователь с таким логином уже существует<br />";
        }

        $hashes = $this->passwHash($password);
        $data['login'] = $login;
        $data['name'] = $name;
        $data['email'] = $email;
        $data['password'] = $hashes['<PASSWORD>'];
        $data['salt'] = $hashes['salt'];
        $data['phone'] = $phone;
        $data['create_time'] = date('Y-m-d H:i:s');

        $this->user = $data;

        try {
            $this->db->insert($this->table, $this->user);
        } catch(PDOException $e) {
            echo "Database error: ".$e->getMessage();
            die();
        }
        return true;
    }

    public function getSalt($login)
    {
        return $this->db->fetchOne($this->table, 'salt', ['login' => $login]);
    }

    public function authorize($remember = false)
    {
        $this->clearUsers();
        $login = preg_match('/^[a-zA-Z0-9_-]{3,16}$/', $_POST['login']) ? $_POST['login'] : false;
        $password = preg_match('/^[a-zA-Z0-9_-]{3,18}$/', $_POST['password']) ? $_POST['password'] : false;
        if (!$login) {
            return $this->errorValid = 'Логин должен состоять только из букв английского алфавита и цифр';
        }
        if(!$password) {
            return $this->errorValid = 'Пароль не соответствует правилам составления';
        }

        $salt = $this->getSalt($login);
        if(!$salt) {
            return $this->errorValid = "Пользователь с таким логином не существует!<br />";
        }
        $hashes = $this->passwHash($password, $salt);
        $this->user = $this->db->fetchRow($this->table, ['*'], ['login' => $login, 'password' => $hashes['<PASSWORD>']]);
        if(!$this->user) {
            return $this->errorValid = "Не правильно введен пароль!<br />";
        }
        if($this->user['status'] == 'registered') {
            return $this->errorValid = "Пользователь еще не активирован.<br />";
        }
        if($this->user) {
            $this->user_id = $this->user['id'];
            $this->saveSession($remember);
            $this->is_authorized = true;
        }
        else return;

    }


    public static function isAuthorized()
    {
        if (!empty($_SESSION["user_id"])) {
            return (bool) $_SESSION["user_id"];
        }
        return false;
    }


    public function passwHash($password, $salt = false)
    {
        $salt || $salt = uniqid();
        $hash = md5(md5($password . md5(sha1($salt))));
        return ['hash' => $hash, 'salt' => $salt];
    }

    public function saveSession($remember = false, $http_only = true, $days = 7)
    {
        $_SESSION["user_id"] = $this->user['id'];
        $guid = $this->generateStr();
        $this->db->update($this->table, ['guid' => $guid], ['id' => $this->user_id]);

        if ($remember) {
            $expire = time() + $days * 24 * 3600;
            $domain = ""; // default domain
            $secure = false;
            $path = "/";

            $cookie = setcookie("sid", $guid, $expire, $path, $domain, $secure, $http_only);
        }
    }

    public function clearUsers()
    {
        $min = date('Y-m-d H:i:s', time() - 24 * 6 * 60 * 10);
        $where = [':minn' => $min];
        //$this->db->query("DELETE FROM users WHERE create_time > :minn AND status = 'registered'", $where);
    }

    public function get($userId = null)
    {
       // $this->clearUsers();

        if($userId === null)
            $this->user_id = $this->getUid();

        if($this->user_id == null)
            return false;

        $this->user = $this->db->fetchRow($this->table, ['*'], ['id' => $this->user_id]);
        return $this->user;
    }

    private function generateStr($length = 10)
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPRQSTUVWXYZ0123456789";
        $code = "";
        $clen = strlen($chars) - 1;

        while (strlen($code) < $length)
            $code .= $chars[mt_rand(0, $clen)];

        return $code;
    }

{'fraction_non_alphanumeric': 0.1933260790714545, 'fraction_numerical': 0.010972071091766412, 'mean_word_length': 2.2070369293399246, 'pattern_counts': {'":': 0, '<': 29, '<?xml version=': 0, '>': 155, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1019182', 'n_tokens_mistral': 3758, 'n_tokens_neox': 3667, 'n_words': 690}