<?php
/**
 * User Profile
 *
 * @package Cotonti
 * @copyright (c) Cotonti Team
 * @license https://github.com/Cotonti/Cotonti/blob/master/License.txt
 */

defined('COT_CODE') or die('Wrong URL');

require_once cot_incfile('uploads');

@clearstatcache();

list($usr['auth_read'], $usr['auth_write'], $usr['isadmin']) = cot_auth('users', 'a');
cot_block($usr['auth_write']);
require_once cot_langfile('users', 'module');

/* === Hook === */
foreach (cot_getextplugins('users.profile.first') as $pl)
{
	include $pl;
}
/* ===== */

$showsavemsg = true;

$id = cot_import('id','G','TXT');
$action = cot_import('action','P','TXT');

$sql = $db->query("SELECT * FROM $db_users WHERE user_id='".$usr['id']."' LIMIT 1");
cot_die($sql->rowCount()==0);
$urr = $sql->fetch();

if(!empty($action))
{
	//cot_check_xg();

  $ruser = array();

	/* === Hook === */
	foreach (cot_getextplugins('users.profile.update.first') as $pl)
	{
		include $pl;
	}
	/* ===== */

  if($action == 'main') {
  	$ruser['user_text'] = cot_import('rusertext','P','HTM', cot::$cfg['users']['usertextmax']);
  	$ruser['user_country'] = cot_import('rusercountry','P','ALP');
  	$ruser['user_timezone'] = cot_import('rusertimezone','P','TXT');

    $uname = cot_import('uname','P','TXT');
    if(!empty($uname) && $uname != $urr['user_name']) {
      if($urr['user_chgname'] == 1) {
        cot_error('Вы уже меняли свой логин, в случае необходимости обратитесь к администратору', 'rusername');
      } else {
        $ruser['user_name'] = $uname;

      	$user_exists = (bool)cot::$db->query("SELECT user_id FROM ".cot::$db->users." WHERE user_name = ? LIMIT 1",
              array($ruser['user_name']))->fetch();

      	if (!preg_match("/^[0-9a-zA-Z\-_]+$/", $ruser['user_name'])) cot_error('aut_invalidloginchars', 'rusername');
      	if (mb_strlen($ruser['user_name']) < 2) cot_error('aut_usernametooshort', 'rusername');
        if (mb_strlen($ruser['user_name']) > 10) cot_error('Логин должен быть короче 10 символов', 'rusername');
      	if ($user_exists) cot_error('aut_usernamealreadyindb', 'rusername');

        if(!cot_error_found()) {
           $ruser['user_chgname'] = 1;
        }
      }
    }

    $uemail = cot_import('email','P','TXT');
    if(!empty($uemail) && $uemail != $urr['user_email']) {
      //if($urr['user_chgname'] == 1) {
      //  cot_error('Вы уже меняли свой логин, в случае необходимости обратитесь к администратору', 'rusername');
      //} else {
        $ruseremail = $uemail;

      	$email_exists = (bool)cot::$db->query("SELECT user_id FROM ".cot::$db->users." WHERE user_email = ? LIMIT 1",
              array($ruseremail))->fetch();

      	if (!cot_check_email($ruseremail))	cot_error('aut_emailtooshort', 'ruseremail');
      	if ($email_exists && !$cfg['useremailduplicate']) cot_error('aut_emailalreadyindb', 'ruseremail');

        if(!cot_error_found()) {
        	if (!$cfg['users']['user_email_noprotection'])
        	{
        		$validationkey = md5(microtime());

        		//$db->update($db_users, array('user_email' => $ruseremail, 'user_paychgblock' => ($sys['now']+(86400*7)), 'user_lostpass' => $validationkey, 'user_maingrp' => '-1', 'user_sid' => $urr['user_maingrp']), "user_id='".$usr['id']."'");
            $db->update($db_users, array('user_newemail' => $ruseremail, 'user_lostpass' => $validationkey), "user_id='".$usr['id']."'");

        		$rsubject = $L['aut_mailnoticetitle'];
        		$ractivate = $cfg['mainurl'].'/'.cot_url('users', 'm=confirmemail&a=validate&v='.$validationkey, '', true);
        		$rbody = sprintf($L['aut_emailchange'], $usr['name'], $ractivate);
        		$rbody .= "\n\n".$L['aut_contactadmin'];
        		cot_mail($ruseremail, $rsubject, $rbody);

            /*
        		if(cot_import($sys['site_id'], 'COOKIE', 'ALP'))
        		{
        			cot_setcookie($sys['site_id'], '', time()-63072000, $cfg['cookiepath'], $cfg['cookiedomain'], $sys['secure'], true);
        		}

        		if (!empty($_SESSION[$sys['site_id']]))
        		{
        			session_unset();
        			session_destroy();
        		}
        		if (cot_plugin_active('whosonline'))
        		{
        			$db->delete($db_online, "online_ip='{$usr['ip']}'");
        		}
            */
            $showsavemsg = false;
            cot_message('На указанный электронный адрес отправлено письмо, для подтверждения следуйте инструкциям в письме.');

            $ruser = array();
        	}
        	else
        	{
            $showsavemsg = false;
        		$db->update($db_users, array('user_email' => $ruseremail, 'user_paychgblock' => ($sys['now']+(86400*7))), "user_id='".$usr['id']."'");
            cot_message('Ваш электронный адрес изменен.');

            $ruser = array();
        	}
        }
     // }
    }

    if (!empty(cot::$extrafields[cot::$db->users])) {
      foreach (cot::$extrafields[cot::$db->users] as $exfld) {
        if(isset($_POST['ruser' . $exfld['field_name']])) {
          $ruser['user_' . $exfld['field_name']] = cot_import_extrafields('ruser' . $exfld['field_name'], $exfld, 'P',
              $urr['user_' . $exfld['field_name']], 'user_');
        }
      }
    }
  } elseif($action == 'changepass') {
  	$rnewpass1 = cot_import('pass','P','HTM', 32);
  	$rnewpass2 = cot_import('pass2','P','HTM', 32);

  	if (!empty($rnewpass1) && !empty($rnewpass2))
  	{
  		if ($rnewpass1 != $rnewpass2) cot_error('pro_passdiffer', 'pass2');
  		if (mb_strlen($rnewpass1) < 4) cot_error('pro_passtoshort', 'pass');

  		if (!cot_error_found())
  		{
  			$ruserpass = array();
  			$ruserpass['user_passsalt'] = cot_unique(16);
  			$ruserpass['user_passfunc'] = empty($cfg['hashfunc']) ? 'sha256' : $cfg['hashfunc'];
  			$ruserpass['user_password'] = cot_hash($rnewpass1, $ruserpass['user_passsalt'], $ruserpass['user_passfunc']);
  			$db->update($db_users, $ruserpass, "user_id={$usr['id']}");
  			unset($ruserpass);

        $showsavemsg = false;

  			cot_message('Ваш пароль успешно изменен');

        $ruser = array();
        /*
          На Ваш текущий email отправлено письмо для подтверждения изменений
        */
  		}
  	}
  }

	if (!cot_error_found() && count($ruser) > 0)
	{
		$ruser['user_auth'] = '';
		$db->update($db_users, $ruser, "user_id='".$usr['id']."'");
		cot_extrafield_movefiles();

		/* === Hook === */
		foreach (cot_getextplugins('users.profile.update.done') as $pl)
		{
			include $pl;
		}
		/* ===== */

    if($showsavemsg) {
      if(!$cfg['users']['regnoactivation'] && $urr['user_logcount'] == 1 && empty($urr['user_email'])) {
        cot_message('Ваши настройки сохранены.');
      } else {
        if($usr['user_maingrp'] == 4) {
          cot_message('Ваши настройки сохранены. <a href="'.cot_url('market', 'm=add').'">Создать '.cot_sitename('padeg', 'v').'</a> или <a href="/">Перейти на главную</a>');
        } else {
    		  cot_message('Ваши настройки сохранены. <a href="'.cot_url('index').'">Начать работу</a>');
        }
      }
    }
	}
  cot_redirect(cot_url('users', 'm=profile', '', true));
} elseif(!$cfg['users']['regnoactivation'] && $urr['user_logcount'] == 1 && empty($urr['user_email'])) {
  cot_message('На указанный электронный адрес отправленно письмо с ссылкой на подтверждения аккаунта, следуйте инструкциям в письме. Проверьте СПАМ если нет письма и нажмите кнопку не СПАМ, ');
}

$sql = $db->query("SELECT * FROM $db_users WHERE user_id='".$usr['id']."' LIMIT 1");
$urr = $sql->fetch();

$out['subtitle'] = $L['Profile'];
$out['head'] .= $R['code_noindex'];

$mskin = cot_tplfile(array('users', 'profile'), 'module');

/* === Hook === */
foreach (cot_getextplugins('users.profile.main') as $pl)
{
	include $pl;
}
/* ===== */

require_once $cfg['system_dir'] . '/header.php';

$t = new XTemplate($mskin);

require_once cot_incfile('forms');

$protected = !$cfg['users']['useremailchange'] ? array('disabled' => 'disabled') : array();
$profile_form_email = cot_inputbox('text', 'ruseremail', $urr['user_email'], array('size' => 32, 'maxlength' => 64)
	+ $protected);

$editor_class = $cfg['users']['usertextimg'] ? 'minieditor' : '';

$t->assign(array(
	'USERS_PROFILE_TITLE' => cot_rc_link(cot_url('users', 'm=profile'), $L['pro_title']),
	'USERS_PROFILE_SUBTITLE' => $L['pro_subtitle'],
	'USERS_PROFILE_DETAILSLINK' => cot_url('users', 'm=details&id='.$urr['user_id']),
	'USERS_PROFILE_EDITLINK' => cot_url('users', 'm=edit&id='.$urr['user_id']),
	'USERS_PROFILE_FORM_SEND' => cot_url('users', "m=profile&a=update&".cot_xg()),
	'USERS_PROFILE_ID' => $urr['user_id'],
	'USERS_PROFILE_NAME' => htmlspecialchars($urr['user_name']),
	'USERS_PROFILE_MAINGRP' => cot_build_group($urr['user_maingrp']),
	'USERS_PROFILE_GROUPS' => cot_build_groupsms($urr['user_id'], FALSE, $urr['user_maingrp']),
	'USERS_PROFILE_COUNTRY' => cot_selectbox_countries($urr['user_country'], 'rusercountry'),
	'USERS_PROFILE_TEXT' => cot_textarea('rusertext', $urr['user_text'], 8, 56, array('class' => $editor_class)),
	'USERS_PROFILE_EMAIL' => $profile_form_email,
	'USERS_PROFILE_EMAILPASS' => cot_inputbox('password', 'rmailpass', '', array('size' => 12, 'maxlength' => 32, 'autocomplete' => 'off')),
	'USERS_PROFILE_HIDEEMAIL' => cot_radiobox($urr['user_hideemail'], 'ruserhideemail', array(1, 0), array($L['Yes'], $L['No'])),
	'USERS_PROFILE_THEME' => cot_selectbox_theme($urr['user_theme'], $urr['user_scheme'], 'rusertheme'),
	'USERS_PROFILE_LANG' => cot_selectbox_lang($urr['user_lang'], 'ruserlang'),
	'USERS_PROFILE_GENDER' => cot_selectbox_gender($urr['user_gender'] ,'rusergender'),
	'USERS_PROFILE_BIRTHDATE' => cot_selectbox_date(cot_date2stamp($urr['user_birthdate']), 'short', 'ruserbirthdate', cot_date('Y', $sys['now']), cot_date('Y', $sys['now']) - 100, false),
	'USERS_PROFILE_TIMEZONE' => cot_selectbox_timezone($urr['user_timezone'], 'rusertimezone'),
	'USERS_PROFILE_REGDATE' => cot_date('datetime_medium', $urr['user_regdate']),
	'USERS_PROFILE_REGDATE_STAMP' => $urr['user_regdate'],
	'USERS_PROFILE_LASTLOG' => cot_date('datetime_medium', $urr['user_lastlog']),
	'USERS_PROFILE_LASTLOG_STAMP' => $urr['user_lastlog'],
	'USERS_PROFILE_LOGCOUNT' => $urr['user_logcount'],
  'USERS_PROFILE_PHONE' => $urr['user_phone'],
	'USERS_PROFILE_ADMINRIGHTS' => '',
	'USERS_PROFILE_OLDPASS' => cot_inputbox('password', 'roldpass', '', array('size' => 12, 'maxlength' => 32)),
	'USERS_PROFILE_NEWPASS1' => cot_inputbox('password', 'rnewpass1', '', array('size' => 12, 'maxlength' => 32, 'autocomplete' => 'off')),
	'USERS_PROFILE_NEWPASS2' => cot_inputbox('password', 'rnewpass2', '', array('size' => 12, 'maxlength' => 32, 'autocomplete' => 'off')),
));

// Extra fields
if (!empty(cot::$extrafields[cot::$db->users])) {
    foreach (cot::$extrafields[cot::$db->users] as $exfld) {
        $uname = strtoupper($exfld['field_name']);
        $exfld_val = cot_build_extrafields('ruser'.$exfld['field_name'], $exfld, $urr['user_'.$exfld['field_name']]);
        $exfld_title = cot_extrafield_title($exfld, 'user_');

        $t->assign(array(
            'USERS_PROFILE_' . $uname => $exfld_val,
            'USERS_PROFILE_' . $uname . '_TITLE' => $exfld_title,
            'USERS_PROFILE_EXTRAFLD' => $exfld_val,
            'USERS_PROFILE_EXTRAFLD_TITLE' => $exfld_title
        ));
        $t->parse('MAIN.EXTRAFLD');
    }
}

/* === Hook === */
foreach (cot_getextplugins('users.profile.tags') as $pl)
{
	include $pl;
}
/* ===== */

// Error handling
cot_display_messages($t);

if ($cfg['users']['useremailchange'])
{
	if (!$cfg['users']['user_email_noprotection'])
	{
		$t->parse('MAIN.USERS_PROFILE_EMAILCHANGE.USERS_PROFILE_EMAILPROTECTION');
	}
	$t->parse('MAIN.USERS_PROFILE_EMAILCHANGE');
}

$t->parse('MAIN');
$t->out('MAIN');

require_once cot::$cfg['system_dir'] . '/footer.php';
