<?php
/*
 * JohnCMS NEXT Mobile Content Management System (http://johncms.com)
 *
 * For copyright and license information, please see the LICENSE.md
 * Installing the system or redistributions of files must retain the above copyright notice.
 *
 * @link        http://johncms.com JohnCMS Project
 * @copyright   Copyright (C) JohnCMS Community
 * @license     GPL-3
 */

define('_IN_JOHNCMS', 1);

require('../system/bootstrap.php');

/** @var Psr\Container\ContainerInterface $container */
$container = App::getContainer();

/** @var Johncms\Api\UserInterface $systemUser */
$systemUser = $container->get(Johncms\Api\UserInterface::class);

/** @var Johncms\Api\ToolsInterface $tools */
$tools = $container->get(Johncms\Api\ToolsInterface::class);

/** @var Johncms\Api\ConfigInterface $config */
$config = $container->get(Johncms\Api\ConfigInterface::class);

/** @var Zend\I18n\Translator\Translator $translator */
$translator = $container->get(Zend\I18n\Translator\Translator::class);
$translator->addTranslationFilePattern('gettext', __DIR__ . '/locale', '/%s/default.mo');

$textl = _t('Registration');
$headmod = 'registration';
require('../system/head.php');

// Если регистрация закрыта, выводим предупреждение
if (!$config->mod_reg || $systemUser->isValid()) {
    echo '<p>' . _t('Registration is temporarily closed') . '</p>';
    require('../system/end.php');
    exit;
}

$captcha = isset($_POST['captcha']) ? trim($_POST['captcha']) : null;
$reg_nick = isset($_POST['nick']) ? trim($_POST['nick']) : '';
$lat_nick = $tools->rusLat($reg_nick);
$reg_pass = isset($_POST['password']) ? trim($_POST['password']) : '';
$user['dayb'] = isset($_POST['dayb']) ? intval($_POST['dayb']) : '';
$user['monthb'] = isset($_POST['monthb']) ? intval($_POST['monthb']) : '';
$user['yearofbirth'] = isset($_POST['yearofbirth']) ? intval($_POST['yearofbirth']) : '';
$reg_mail = isset($_POST['mail']) ? trim($_POST['mail']) : '';
$reg_name = isset($_POST['imname']) ? trim($_POST['imname']) : '';
$reg_about = isset($_POST['about']) ? trim($_POST['about']) : '';
$reg_sex = isset($_POST['sex']) ? trim($_POST['sex']) : '';

$subject = "Registration at " . $config['copyright'] . "";
$mail = "Hello $reg_nick.. This email has been sent from " . $config['copyright'] . "\r\n
You have received this mail because this email address was used during registration at our forum..\r\n If you did not register at our forums, please disregard this email.. You do not need to unsubscribe or take any further action..\r\n\r\n -------------------------------------------------\r\n Welcome on board\r\n -------------------------------------------------\r\n\r\n Thank you for joining us.. We suggest you save this email in a safe place.. This reminds, in case you forget your login detail..\r\n And your details are shown below:\r\n\r\n Username: $reg_nick\r\n Password: $reg_pass\r\n Email: $reg_mail\r\n\r\n And to go to our site please visit this page:\r\n $home/index.php\r\n It will ask you for a username, and your password..\r\n You may copy and paste, or type those username and password into the corresponding fields in the form.. If you still cannot login to your account, its possible that the account has been removed.. If this is the case, please contact the administrator (" . $config['email'] . ") to rectify the problem.. Thank you for registering and enjoy your stay..\r\n dont forget to update your profile after you login..\r\n and please dont reply this email, because its automatically sent from our servers..\r\n\r\n Please do ignore this message if you didn't sign-up or register at our website...\r\n -------------------------------------------------\r\n\r\n Regards,\r\n Administrators of " . $config['copyright'] . "";
$adds = "From: <no-reply@".$_SERVER['HTTP_HOST'].">\n";

echo '<div class="mainblok"><div class="phdr"><img src="/images/file.png" align="left" alt="file"/>&#160;&#160;<b>' . _t('Registration') . '</b></div>';

if (isset($_POST['submit'])) {
    /** @var PDO $db */
    $db = $container->get(PDO::class);

    // Принимаем переменные
    $error = [];

    // Проверка Логина
    if (empty($reg_nick)) {
        $error['login'][] = _t('You have not entered Nickname');
    } elseif (mb_strlen($reg_nick) < 2 || mb_strlen($reg_nick) > 20) {
        $error['login'][] = _t('Nickname wrong length');
    }

    if (preg_match('/[^\da-z\-\@\*\(\)\?\!\~\_\=\[\]]+/', $lat_nick)) {
        $error['login'][] = _t('Invalid characters');
    }

    // Проверка пароля
    if (empty($reg_pass)) {
        $error['password'][] = _t('You have not entered password');
    } elseif (mb_strlen($reg_pass) < 3) {
        $error['password'][] = _t('Invalid length');
    }

	if (empty($reg_mail)) { 
		$error['mail'][] = _t('E-mail address cannot be empty..!!');
	} elseif (mb_strlen($reg_mail) < 3 || mb_strlen($reg_mail) > 40) { 
		$error[] = _t('E-mail length is not valid');
	} 
	if (!preg_match("#^[a-z0-9\.\-_\+]+?@(.*?\.)*?[a-z0-9\-_]+?\.[a-z]{2,4}$#i", $reg_mail)) { 
		$error[] = _t('E-mail format is not valid'); 
	} 

	if ($user['dayb'] < 1 || $user['dayb'] > 31 || $user['monthb'] < 1 || $user['monthb'] > 12) {
		$error[] = 'Your birthday is not valid..!!';
		} 

    // Проверка пола
    if ($reg_sex != 'm' && $reg_sex != 'zh') {
        $error['sex'] = _t('You have not selected gender');
    }

    // Проверка кода CAPTCHA
    if (!$captcha
        || !isset($_SESSION['code'])
        || mb_strlen($captcha) < 4
        || $captcha != $_SESSION['code']
    ) {
        $error['captcha'] = _t('The security code is not correct');
    }

    unset($_SESSION['code']);

    // Проверка переменных
    if (empty($error)) {
        $pass = md5(md5($reg_pass));
        $reg_name = htmlspecialchars(mb_substr($reg_name, 0, 50));
        $reg_mail = htmlspecialchars(mb_substr($reg_mail, 0, 40));
        $reg_about = htmlspecialchars(mb_substr($reg_about, 0, 1000));
        // Проверка, занят ли ник
        $stmt = $db->prepare('SELECT * FROM `users` WHERE `name_lat` = ?');
        $stmt->execute([$lat_nick]);

        if ($stmt->rowCount()) {
            $error['login'][] = _t('Selected Nickname is already in use');
        }
        $stmail = $db->prepare('SELECT * FROM `users` WHERE `mail` = ?');
        $stmail->execute([$reg_mail]);

        if ($stmail->rowCount()) {
            $error['mail'][] = _t('Selected Email is already in use');
        }
    }

    if (empty($error)) {
        /** @var Johncms\Api\EnvironmentInterface $env */
        $env = $container->get(Johncms\Api\EnvironmentInterface::class);

        $preg = $config->mod_reg > 1 ? 1 : 0;
        $db->prepare('
          INSERT INTO `users` SET
          `name` = ?,
          `name_lat` = ?,
          `mail` = ?,
          `dayb` = ?,
          `monthb` = ?,
          `yearofbirth` = ?,
          `password` = ?,
          `imname` = ?,
          `about` = ?,
          `sex` = ?,
          `rights` = 0,
          `ip` = ?,
          `ip_via_proxy` = ?,
          `browser` = ?,
          `datereg` = ?,
          `lastdate` = ?,
          `sestime` = ?,
          `preg` = ?,
          `set_user` = \'\',
          `set_forum` = \'\',
          `set_mail` = \'\',
          `smileys` = \'\'
        ')->execute([
            $reg_nick,
            $lat_nick,
            $reg_mail,
            $user['dayb'],
            $user['monthb'],
            $user['yearofbirth'],
            $pass,
            $reg_name,
            $reg_about,
            $reg_sex,
            $env->getIp(),
            $env->getIpViaProxy(),
            $env->getUserAgent(),
            time(),
            time(),
            time(),
            $preg,
        ]);

        $usid = $db->lastInsertId();
			$bot = '[c]Hello @'.$reg_nick.', Welcome to '.$config['copyright'].' you may please update your profile for introduce your self[/c]';
				$botida = $config['botida'];
				$botnamea = $config['botnamea'];
				$db->prepare("INSERT INTO `shout` SET
				`adm` = 0,
				`time` = ?,
				`user_id` = ?,
				`name` = ?,
				`text` = ?,
				`ip` = ?,
				`browser` = ?,
				`otvet` = ''
				")->execute([
				time(),
				$botida,
				$botnamea,
				$bot,
				$env->getIp(),
				$env->getUserAgent(),
				]);

			$set_mail = $config['mailReg']; 
			if (!isset($set_mail['message_include'])) { 
				$set_mail['message_include'] = 0; 
			} 
			if ($set_mail['message_include']) { 
				$array = array('{LOGIN}', '{TIME}'); 
				$array_replace = array($reg_nick, '{TIME=' . time() . 				'}'); 
					if (empty($config['messageTheme'])) { 
					$config['messageTheme'] = _t('Welcome Message'); 
				} 
					if (empty($config['regMessage'])) { 
						$config['regMessage'] = _t('Hi') . ", {LOGIN}\r\n" . _t('We are pleased to see you on our website.') . "\r\n" . _t('Come more often and here it will be pleasant to you.') . "\r\n" . _t('Yours faithfully, administrator.'); 
				} 
			$theme = str_replace($array, $array_replace, $config['messageTheme']); 
			$system = str_replace($array, $array_replace, $config['regMessage']); 
                        $db->prepare('
                          INSERT INTO `cms_mail` SET
                          `user_id` = 0,
                          `from_id` = ?,
                          `text` = ?,
                          `time` = ?,
                          `sys` = 1,
                          `them` = ?
                        ')->execute([
                            $usid,
                            $system,
                            time(),
                            $theme,
                        ]);

}
			mail($reg_mail, $subject, $mail, $adds);

        echo '<div class="menu"><p><h3>' . _t('Your registratiton data') . '</h3>'
            . _t('Your ID') . ': <b>' . $usid . '</b><br>'
            . _t('Your Username') . ': <b>' . $reg_nick . '</b><br>'
            . _t('Your Password') . ': <b>' . $reg_pass . '</b></p>';

        if ($config->mod_reg == 1) {
            echo '<p><span class="red"><b>' . _t('Please, wait until a moderator approves your registration') . '</b></span></p>';
        } else {
            $_SESSION['uid'] = $usid;
            $_SESSION['ups'] = md5(md5($reg_pass));
            echo '<p><a href="' . $config->homeurl . '">' . _t('Enter') . '</a></p>';
        }

        echo '</div>';
        require('../system/end.php');
        exit;
    }
}

// Форма регистрации
if ($config->mod_reg == 1) {
    echo '<div class="rmenu"><p>' . _t('You can get authorized on the site after confirmation of your registration.') . '</p></div>';
}

echo '<form action="index.php" method="post"><div class="gmenu">' .
    '<p><h3>' . _t('Choose Nickname') . '</h3>' .
    (isset($error['login']) ? '<span class="red"><small>' . implode('<br />',
            $error['login']) . '</small></span><br />' : '') .
    '<input type="text" name="nick" maxlength="15" value="' . htmlspecialchars($reg_nick) . '"' . (isset($error['login']) ? ' style="background-color: #FFCCCC"' : '') . '/><br />' .
    '<small>' . _t('Min. 2, Max. 20 characters.<br />Allowed letters of the russian and latin alphabets, numbers and symbols - = @ ! ? ~ _ ( ) [ ] . * (Except zero)') . '</small></p>' .
    '<p><h3>' . _t('Assign a password') . '</h3>' .
    (isset($error['password']) ? '<span class="red"><small>' . implode('<br />',
            $error['password']) . '</small></span><br />' : '') .
    '<input type="text" name="password" maxlength="20" value="' . htmlspecialchars($reg_pass) . '"' . (isset($error['password']) ? ' style="background-color: #FFCCCC"' : '') . '/><br>' .
    '<small>' . _t('Min. 3 characters') . '</small></p>' .
    '<p><h3>' . _t('Enter Email') . '</h3>' .
    (isset($error['mail']) ? '<span class="red"><small>' . implode('<br />',
            $error['mail']) . '</small></span><br />' : '') .
    '<input type="text" name="mail" maxlength="40" value="' . htmlspecialchars($reg_mail) . '"' . (isset($error['mail']) ? ' style="background-color: #FFCCCC"' : '') . '/><br>' .
    '<small>' . _t('Ensure to insert valid email address because your login details will be forwarded to it') . '</small></p>' .
	 '<p><h3>' . _t('Date of birth') . '</h3>' .
	 '<select name="dayb"
size="1">
	<option value="01"> 01 </option>
	<option value="02"> 02 </option>
	<option value="03"> 03 </option>
	<option value="04"> 04 </option>
	<option value="05"> 05 </option>
	<option value="06"> 06 </option>
	<option value="07"> 07 </option>
	<option value="08"> 08 </option>
	<option value="09"> 09 </option>
	<option value="10"> 10 </option>
	<option value="11"> 11 </option>
	<option value="12"> 12 </option>
	<option value="13"> 13 </option>
	<option value="14"> 14 </option>
	<option value="15"> 15 </option>
	<option value="16"> 16 </option>
	<option value="17"> 17 </option>
	<option value="18"> 18 </option>
	<option value="19"> 19 </option>
	<option value="20"> 20 </option>
	<option value="21"> 21 </option>
	<option value="22"> 22 </option>
	<option value="23"> 23 </option>
	<option value="24"> 24 </option>
	<option value="25"> 25 </option>
	<option value="26"> 26 </option>
	<option value="27"> 27 </option>
	<option value="28"> 28 </option>
	<option value="29"> 29 </option>
	<option value="30"> 30 </option>
	<option value="31"> 31 </option>
	</select>&#160;-&#160;<select name="monthb"
size="1">
	<option value="01"> January </option>
	<option value="02"> February </option>
	<option value="03"> March </option>
	<option value="04"> April </option>
	<option value="05"> May </option>
	<option value="06"> June </option>
	<option value="07"> July </option>
	<option value="08"> August </option>
	<option value="09"> September </option>
	<option value="10"> October </option>
	<option value="11"> November </option>
	<option value="12"> December </option></select>&#160;-&#160;<select name="yearofbirth"
size="1">
	<option value="2016"> 2016 </option>
	<option value="2015"> 2015 </option>
	<option value="2014"> 2014 </option>
	<option value="2013"> 2013 </option>
	<option value="2012"> 2012 </option>
	<option value="2011"> 2011 </option>
	<option value="2010"> 2010 </option>
	<option value="2009"> 2009 </option>
	<option value="2008"> 2008 </option>
	<option value="2007"> 2007 </option>
	<option value="2006"> 2006 </option>
	<option value="2005"> 2005 </option>
	<option value="2004"> 2004 </option>
	<option value="2003"> 2003 </option>
	<option value="2002"> 2002 </option>
	<option value="2001"> 2001 </option>
	<option value="2000"> 2000 </option>
	<option value="1999"> 1999 </option>
	<option value="1998"> 1998 </option>
	<option value="1997"> 1997 </option>
	<option value="1996"> 1996 </option>
	<option value="1995"> 1995 </option>
	<option value="1994"> 1994 </option>
	<option value="1993"> 1993 </option>
	<option value="1992"> 1992 </option>
	<option value="1991"> 1991 </option>
	<option value="1990"> 1990 </option>
	<option value="1989"> 1989 </option>
	<option value="1988"> 1988 </option>
	<option value="1987"> 1987 </option>
	<option value="1986"> 1986 </option>
	<option value="1985"> 1985 </option>
	<option value="1984"> 1984 </option>
	<option value="1983"> 1983 </option>
	<option value="1982"> 1982 </option>
	<option value="1981"> 1981 </option>
	<option value="1980"> 1980 </option>
	<option value="1979"> 1979 </option>
	<option value="1978"> 1978 </option>
	<option value="1977"> 1977 </option>
	<option value="1976"> 1976 </option>
	<option value="1975"> 1975 </option>
	<option value="1974"> 1974 </option>
	<option value="1973"> 1973 </option>
	<option value="1972"> 1972 </option>
	<option value="1971"> 1971 </option>
	<option value="1970"> 1970 </option>
	<option value="1969"> 1969 </option>
	<option value="1968"> 1968 </option>
	<option value="1967"> 1967 </option>
	<option value="1966"> 1966 </option>
	<option value="1965"> 1965 </option>
	<option value="1964"> 1964 </option>
	<option value="1963"> 1963 </option>
	<option value="1962"> 1962 </option>
	<option value="1961"> 1961 </option>
	<option value="1960"> 1960 </option>
	<option value="1959"> 1959 </option>
	<option value="1958"> 1958 </option>
	<option value="1957"> 1957 </option>
	<option value="1956"> 1956 </option>
	<option value="1955"> 1955 </option>
	<option value="1954"> 1954 </option>
	<option value="1953"> 1953 </option>
	<option value="1952"> 1952 </option>
	<option value="1951"> 1951 </option>
	<option value="1950"> 1950 </option>
	<option value="1949"> 1949 </option>
	<option value="1948"> 1948 </option>
	<option value="1947"> 1947 </option>
	<option value="1946"> 1946 </option>
	<option value="1945"> 1945 </option>
	<option value="1944"> 1944 </option>
	<option value="1943"> 1943</option>
	<option value="1942"> 1942 </option>
	<option value="1941"> 1941 </option>
	</select></p>' .
    '<p><h3>' . _t('Select Gender') . '</h3>' .
    (isset($error['sex']) ? '<span class="red"><small>' . $error['sex'] . '</small></span><br />' : '') .
    '<select name="sex"' . (isset($error['sex']) ? ' style="background-color: #FFCCCC"' : '') . '>' .
    '<option value="?">-?-</option>' .
    '<option value="m"' . ($reg_sex == 'm' ? ' selected="selected"' : '') . '>' . _t('Man') . '</option>' .
    '<option value="zh"' . ($reg_sex == 'zh' ? ' selected="selected"' : '') . '>' . _t('Woman') . '</option>' .
    '</select></p></div>' .
    '<div class="menu">' .
    '<p><h3>' . _t('Your name') . '</h3>' .
    '<input type="text" name="imname" maxlength="30" value="' . htmlspecialchars($reg_name) . '" /><br />' .
    '<small>' . _t('Max. 50 characters') . '</small></p>' .
    '<p><h3>' . _t('Tell us a little about yourself') . '</h3>' .
    '<textarea rows="3" name="about">' . htmlspecialchars($reg_about) . '</textarea><br />' .
    '<small>' . _t('Max. 1000 characters') . '</small></p></div>' .
    '<div class="gmenu"><p>' .
    '<h3>' . _t('Verification code') . '</h3>' .
    '<img src="../captcha.php?r=' . rand(1000, 9999) . '" alt="' . _t('Verification code') . '" border="1"/><br />' .
    (isset($error['captcha']) ? '<span class="red"><small>' . $error['captcha'] . '</small></span><br />' : '') .
    '<input type="text" size="7" maxlength="7"  name="captcha" ' . (isset($error['captcha']) ? ' style="background-color: #FFCCCC"' : '') . '/><br />' .
    '<small>' . _t('If you cannot see the image code, enable graphics in your browser and refresh this page') . '</small></p>' .
    '<p><input type="submit" name="submit" value="' . _t('Registration') . '"/></p></div></form>' .
    '<div class="phdr"><small>' . _t('Please, do not register names like 111, shhhh, uuuu, etc. They will be deleted. <br /> Also all the profiles registered via proxy servers will be deleted') . '</small></div></div>';

require('../system/end.php');
