<?php
defined('COT_CODE') or die('Wrong URL');

define('COT_AUTH', TRUE);

$return = array(
  'success' => 0,
  'error' => 'Произошла ошибка. Перезагрузите страницу.',
  'redirect' => ''
);

require_once cot_langfile('message', 'core');

if ($cfg['maintenance'])
{
  $return = array(
    'success' => 0,
    'error' => $cfg['maintenancereason'],
    'redirect' => ''
  );
}
else
{
	cot_shield_protect();

	/* === Hook for the plugins === */
	foreach (cot_getextplugins('users.auth.check') as $pl)
	{
		include $pl;
	}
	/* ===== */

	$rusername = cot_import('l_username','P','TXT', 100);
	$rpassword = cot_import('l_password','P','HTM', 32);
	$rremember = cot_import('l_remember_me', 'P', 'BOL');

  if (empty($rusername)) {
    $return['error'] = 'Нужно ввести логин.';
  } elseif (empty($rpassword)) {
    $return['error'] = 'Нужно ввести пароль.';
  } else {
  	if(!empty($rremember) || $cfg['forcerememberme'])
  	{
  		$rremember = true;
  	}

  	$login_param = !$cfg['useremailduplicate'] && cot_check_email($rusername) ?
  		'user_email' : 'user_name';

  	// Load salt and algo from db
  	$sql = $db->query("SELECT user_passsalt, user_passfunc FROM $db_users WHERE $login_param=".$db->quote($rusername));
  	if ($sql->rowCount() == 0)
  	{
  		// If login has e-mail format, try to find it as user_name
  		$sql = $db->query("SELECT user_passsalt, user_passfunc FROM $db_users WHERE user_name=".$db->quote($rusername));
  	}
  	if ($sql->rowCount() == 1)
  	{
  		$hash_params = $sql->fetch();
  		$rmdpass = cot_hash($rpassword, $hash_params['user_passsalt'], $hash_params['user_passfunc']);
  		unset($hash_params);
  	}

  	/**
  	 * Sets user selection criteria for authentication. Override this string in your plugin
  	 * hooking into users.auth.check.query to provide other authentication methods.
  	 */
  	$user_select_condition = "user_password=".$db->quote($rmdpass)." AND $login_param=".$db->quote($rusername);

  	/* === Hook for the plugins === */
  	foreach (cot_getextplugins('users.auth.check.query') as $pl)
  	{
  		include $pl;
  	}
  	/* ===== */

  	$sql = $db->query("SELECT user_id, user_name, user_token, user_regdate, user_maingrp, user_banexpire, user_theme, user_scheme, user_lang, user_sid, user_sidtime FROM $db_users WHERE $user_select_condition");

  	/* 	Checking if we got any entries with the current login conditions,
  		only may fail when user name has e-mail format or user is not registered,
  		added for compatibility, because disallowed using e-mail as login on registration
  	*/
  	if ( $sql->rowCount() == 0 )
  	{
  		// If login has e-mail format, try to find it as user_name
  		$user_select_condition = "user_password=".$db->quote($rmdpass)." AND user_name=".$db->quote($rusername);

  		// Query the database
  		$sql = $db->query("SELECT user_id, user_name, user_token, user_regdate, user_maingrp, user_banexpire, user_theme, user_scheme, user_lang, user_sid, user_sidtime FROM $db_users WHERE $user_select_condition");
  	}
  	if ($row = $sql->fetch())
  	{
      $return['success'] = 1;

  		$rusername = $row['user_name'];

  		if ($row['user_maingrp']==-1)
  		{
        $return['success'] = 0;
        $return['error'] = $L['msg152_body'];
  			//$env['status'] = '403 Forbidden';
  			cot_log("Log in attempt, user inactive : ".$rusername, 'usr');
  			//cot_redirect(cot_url('message', 'msg=152', '', true));
  		}
  		if ($row['user_maingrp']==2)
  		{
        $return['success'] = 0;
        $return['error'] = $L['msg152_body'];
  			//$env['status'] = '403 Forbidden';
  			cot_log("Log in attempt, user inactive : ".$rusername, 'usr');
  			//cot_redirect(cot_url('message', 'msg=152', '', true));
  		}
  		elseif ($row['user_maingrp']==3)
  		{
  			if ($sys['now'] > $row['user_banexpire'] && $row['user_banexpire']>0)
  			{
  				$sql = $db->update($db_users, array('user_maingrp' => '4'),  "user_id={$row['user_id']}");
  			}
  			else
  			{
          $return['success'] = 0;
          $return['error'] = $L['msg153_body'];
  				//$env['status'] = '403 Forbidden';
  				cot_log("Log in attempt, user banned : ".$rusername, 'usr');
  				//cot_redirect(cot_url('message', 'msg=153&num='.$row['user_banexpire'], '', true));
  			}
  		}

      if($return['success']) {
    		$ruserid = $row['user_id'];
    		$rdeftheme = $row['user_theme'];
    		$rdefscheme = $row['user_scheme'];

    		$token = cot_unique(16);

    		$sid = hash_hmac('sha256', $rmdpass . $row['user_sidtime'], $cfg['secret_key']);

    		if (empty($row['user_sid']) || $row['user_sid'] != $sid
    			|| $row['user_sidtime'] + $cfg['cookielifetime'] < $sys['now'])
    		{
    			// Generate new session identifier
    			$sid = hash_hmac('sha256', $rmdpass . $sys['now'], $cfg['secret_key']);
    			$update_sid = ", user_sid = " . $db->quote($sid) . ", user_sidtime = " . $sys['now'];
    		}
    		else
    		{
    			$update_sid = '';
    		}

    		$update_lostpass = '';

    		$db->query("UPDATE $db_users SET user_lastip='{$usr['ip']}', user_lastlog = {$sys['now']}, user_logcount = user_logcount + 1, user_token = '$token' $update_lostpass $update_sid WHERE user_id={$row['user_id']}");

    		// Hash the sid once more so it can't be faked even if you  know user_sid
    		$sid = hash_hmac('sha1', $sid, $cfg['secret_key']);

    		$u = base64_encode($ruserid.':'.$sid);

    		if($rremember)
    		{
    			cot_setcookie($sys['site_id'], $u, time()+$cfg['cookielifetime'], $cfg['cookiepath'], $cfg['cookiedomain'], $sys['secure'], true);
    			unset($_SESSION[$sys['site_id']]);
    		}
    		else
    		{
    			$_SESSION[$sys['site_id']] = $u;
    		}

    		/* === Hook === */
    		foreach (cot_getextplugins('users.auth.check.done') as $pl)
    		{
    			include $pl;
    		}
    		/* ===== */
      }
    } else {
  		//$env['status'] = '401 Unauthorized';
  		cot_shield_update(7, "Log in");
  		cot_log("Log in failed, user : ".$rusername,'usr');

  		/* === Hook === */
  		foreach (cot_getextplugins('users.auth.check.fail') as $pl)
  		{
  			include $pl;
  		}
  		/* ===== */
      $return['error'] = 'Логин или пароль указаны неверно.';
    }
  }
}

?>
