Вход Регистрация
Файл: modules/profile/skl.php
Строк: 141
<?php

/**
 * This file is part of JohnCMS Content Management System.
 *
 * @copyright JohnCMS Community
 * @license   https://opensource.org/licenses/GPL-3.0 GPL-3.0
 * @link      https://johncms.com JohnCMS Project
 */

declare(strict_types=1);

use 
JohncmsSystemHttpRequest;
use 
JohncmsSystemi18nTranslator;
use 
JohncmsSystemViewRender;
use 
JohncmsNavChain;

$config di('config')['johncms'];

// Register the module languages domain and folder
di(Translator::class)->addTranslationDomain('profile'__DIR__ '/locale');

/** @var PDO $db */
$db di(PDO::class);
/** @var Request $request */
$request di(Request::class);

/** @var JohncmsSystemLegacyTools $tools */
$tools di(JohncmsSystemLegacyTools::class);

$view di(Render::class);

/** @var NavChain $nav_chain */
$nav_chain di(NavChain::class);

// Регистрируем Namespace для шаблонов модуля
$view->addFolder('profile'__DIR__ '/templates/');

$nav_chain->add(__('Restore password'));

function 
passgen($length)
{
    
$vals 'abcdefghijklmnopqrstuvwxyz0123456789';
    
$result '';
    for (
$i 1$i <= $length$i++) {
        
$result .= $vals[rand(0strlen($vals) - 1)];
    }

    return 
$result;
}

$id $request->getQuery('id'0FILTER_VALIDATE_INT);
$act $request->getQuery('act'''FILTER_SANITIZE_STRING);

switch (
$act) {
    case 
'sent':
        
// Отправляем E-mail с инструкциями по восстановлению пароля
        
$nick = isset($_POST['nick']) ? $tools->rusLat($_POST['nick']) : '';
        
$email = isset($_POST['email']) ? htmlspecialchars(trim($_POST['email'])) : '';
        
$code = isset($_POST['code']) ? trim($_POST['code']) : '';
        
$rand = (string) rand(10009999);
        
$check_code md5($rand);
        
$error false;
        
$type 'error';

        if (! 
$nick || ! $email || ! $code) {
            
$error __('The required fields are not filled');
        } elseif (! isset(
$_SESSION['code']) || mb_strlen($code) < || strtolower($code) != strtolower($_SESSION['code'])) {
            
$error __('Incorrect code');
        }

        unset(
$_SESSION['code']);

        if (! 
$error) {
            
// Проверяем данные по базе
            
$req $db->prepare('SELECT `id`, `name`, `mail`, `rest_time` FROM `users` WHERE `name_lat` = ? LIMIT 1');
            
$req->execute([$nick]);

            if (
$req->rowCount()) {
                
$res $req->fetch();

                if (empty(
$res['mail']) || $res['mail'] != $email) {
                    
$error __('Invalid Email address');
                }

                if (
$res['rest_time'] > time() - 86400) {
                    
$error __('Password can be recovered 1 time per day');
                }
            } else {
                
$error __('User does not exists');
            }
        }

        if (! 
$error) {
            
// Высылаем инструкции на E-mail
            
$link $config['homeurl'] . '/profile/skl.php?act=set&id=' $res['id'] . '&code=' $check_code;
            
$subject __('Password recovery');
            
$mail sprintf(
                
__("Hello %s!nYou start process of password recovery on the site %snIn order to recover your password, you must click on the link: %snLink valid for 1 hournnIf you receive this mail by mistake, just ignore this letter"), // phpcs:ignore
                
$res['name'],
                
$config['homeurl'],
                
$link
            
);
            
$adds 'From: <' $config['email'] . ">rnContent-Type: text/plain; charset="utf-8"rn";

            if (
mail($res['mail'], $subject$mail$adds)) {
                
$req $db->prepare('UPDATE `users` SET `rest_code` = ?, `rest_time` = ? WHERE `id` = ?');
                
$req->execute([$check_codetime(), $res['id']]);
                
$type 'success';
                
$message __('Check your e-mail for further information');
            } else {
                
$message __('Error sending E-mail');
            }
        } else {
            
// Выводим сообщение об ошибке
            
$message $error;
        }

        echo 
$view->render('profile::restore_password_result', [
            
'type'    => $type,
            
'message' => $message,
        ]);
        break;

    case 
'set':
        
// Устанавливаем новый пароль
        
$code trim($request->getQuery('code'''FILTER_SANITIZE_STRING));
        
$error false;
        
$type 'error';

        if (! 
$id || mb_strlen($code) !== 32) {
            
$error __('Wrong data');
        }

        if (! 
$error) {
            
$req $db->query('SELECT `id`, `name`, `mail`, `rest_code`, `rest_time` FROM `users` WHERE `id` = ' $id);

            if (
$req->rowCount()) {
                
$res $req->fetch();

                if (empty(
$res['rest_code']) || empty($res['rest_time'])) {
                    
$error __('Password recovery is impossible');
                }

                if (! 
$error && ($res['rest_time'] < time() - 3600 || $code != $res['rest_code'])) {
                    
$error __('Time allotted for the password recovery has been exceeded');
                    
$req $db->prepare('UPDATE `users` SET `rest_code` = "", `rest_time` = "" WHERE `id` = ?');
                    
$req->execute([$res['id']]);
                }
            } else {
                
$error __('User does not exists');
            }
        }

        if (! 
$error) {
            
// Высылаем пароль на E-mail
            
$pass passgen(4);
            
$subject __('Your new password');
            
$mail sprintf(
                
__("Hello %snYou have changed your password on the site %snnYour new password: %snnAfter logging in, you can change your password to new one."),
                
$res['name'],
                
$config['homeurl'],
                
$pass
            
);
            
$adds 'From: <' $config['email'] . ">nContent-Type: text/plain; charset="utf-8"n";

            if (
mail($res['mail'], $subject$mail$adds)) {
                
$req $db->prepare('UPDATE `users` SET `rest_code` = "", `password` = ? WHERE `id` = ?');
                
$req->execute([md5(md5($pass)), $res['id']]);
                
$type 'success';
                
$message __('Password successfully changed.<br>New password sent to your E-mail address.');
            } else {
                
$message __('Error sending E-mail');
            }
        } else {
            
// Выводим сообщение об ошибке
            
$message $error;
        }

        echo 
$view->render('profile::restore_password_result', [
            
'type'    => $type,
            
'message' => $message,
        ]);
        break;

    default:
        
$code = (string) new MobicmsCaptchaCode();
        
$_SESSION['code'] = $code;
        
// Показываем запрос на подтверждение выхода с сайта
        
echo $view->render('profile::restore_password', [
            
'captcha' => new MobicmsCaptchaImage($code),
        ]);
        break;
}
Онлайн: 1
Реклама