<?php

include_once(dirname(__FILE__).'/../../Base/Model.php');
include_once(dirname(__FILE__).'/../../Base/Mail.php');
include_once(dirname(__FILE__).'/../Log/Model.php');

class User extends Model
{
  var $Dependencies = array('Log');
  var $Data = array();
  var $DefaultRole = 2;
  var $OnlineStateTimeout = 600; // in seconds

  function PasswordHash($Name, $Password)
  {
    return(sha1(strtoupper($Name.':'.$Password)));
  }

  function Check()
  {
    $SID = session_id();

    // Remove inactive users
    $DbResult = $this->Database->select('UserOnline', 'Id, User', 'ActivityTime < DATE_SUB(NOW(), INTERVAL '.$this->OnlineStateTimeout.' SECOND)');
    while($DbRow = $DbResult->fetch_array())
    {
      $this->System->Modules['User']->Data['Id'] = $DbRow['User'];
      if($DbRow['User'] != $this->Config['Web']['UserAnonymousId']) $this->System->Modules['Log']->NewRecord('User', 'Logout');
      $this->Database->delete('UserOnline', 'Id='.$DbRow['Id']);
    }

    // Lookup user record
    $Query = $this->Database->select('UserOnline', '*', 'SessionId="'.$SID.'"');
    if($Query->num_rows == 0)
      $this->Database->insert('UserOnline', array('SessionId' => $SID, 'User' => $this->Config['Web']['UserAnonymousId'], 'LoginTime' => 'NOW()', 'ActivityTime' => 'NOW()', 'IpAddress' => $this->System->GetRemoteAddress(), 'HostName' => gethostbyaddr($this->System->GetRemoteAddress()), 'ScriptName' => $_SERVER['PHP_SELF']));
    //echo($this->Database->LastQuery);

    // Check login
    $Query = $this->Database->select('UserOnline', '*', 'SessionId="'.$SID.'"');
    $Row = $Query->fetch_assoc();
    if($Row['User'] != $this->Config['Web']['UserAnonymousId']) 
    {
      $Query = $this->Database->select('User', '*', 'Id='.$Row['User']);
      $this->Data = $Query->fetch_assoc();
      $Result = $this->System->Translate('UserLogged');
    } else 
    {
      $Query = $this->Database->select('User', '*', 'Id='.$this->Config['Web']['UserAnonymousId']);
      $this->Data = $Query->fetch_assoc();
      $Result = $this->System->Translate('UserNotLogged');
    }

    // Refresh time of last access
    $this->Database->update('UserOnline', 'SessionId="'.$SID.'"', array('ActivityTime' => 'NOW()'));
  }

  function Register($Login, $Password, $Password2, $Email, $Name)
  {
    if(($Email == '') || ($Login == '') || ($Password == '') || ($Password2 == '')  || ($Name == '')) $Result = $this->System->Translate('MissingData');
    else if($Password != $Password2) $Result = $this->System->Translate('PasswordsUnmatched');
    else
    {
      // Je uživatel registrován?
      $Query = $this->Database->select('User', '*', 'Login = "'.$Login.'"');
      if($Query->num_rows > 0) $Result = $this->System->Translate('LoginUsed');
      else
      {
        $Query = $this->Database->select('User', '*', 'Name = "'.$Name.'"');
        if($Query->num_rows > 0) $Result = $this->System->Translate('NameUsed');
        else
        { 
          $Query = $this->Database->select('User', '*', 'Email = "'.$Email.'"');
          if($Query->num_rows > 0) $Result = $this->System->Translate('EmailUsed');
          else
          {
            $this->Database->insert('User', array('Name' => $Name, 'Login' => $Login, 'Password' => $this->PasswordHash($Login, $Password), 'Email' => $Email, 'RegistrationTime' => 'NOW()', 'Locked' => 1));
            $UserId = $this->Database->insert_id;
            
            $Mail = new Mail();
            $Mail->Content = 'Provedli jste registraci nového účtu na serveru <a href="http://'.$this->Config['Web']['Host'].$this->Config['Web']['RootFolder'].'/">http://'.$this->Config['Web']['Host'].$this->Config['Web']['RootFolder']."/</a>.<br>\nPokud jste tak neučinili, měli by jste tento email ignorovat.<br><br>\n\nVáš účet je: ".$Login."\n<br>Pro dokončení registrace klikněte na tento odkaz: ".'<a href="http://'.$this->Config['Web']['Host'].$this->Config['Web']['RootFolder'].'/?Action=UserRegisterConfirm&User='.$UserId.'&H='.$this->PasswordHash($Login, $Password).'">http://'.$this->Config['Web']['Host'].$this->Config['Web']['RootFolder'].'/?Action=UserRegisterConfirm&User='.$UserId.'&H='.$this->PasswordHash($Login, $Password).'</a>.'."\n<br> \n\n<br><br>Na tento email neodpovídejte.";
            $Mail->Subject = 'Registrace nového účtu';
            $Mail->RecipientName = $Name;
            $Mail->RecipientAddress = $Email;
            $Mail->SenderName = $this->Config['Web']['Title'];
            $Mail->SenderAddress = 'noreplay@zdechov.net';
            $Mail->Send();

            $Result = $this->System->Translate('UserRegistrated');
            $this->System->Modules['Log']->NewRecord('User', 'NewRegistration', $Login);
          }
        }
      }
    }
    return($Result);
  }

  function RegisterConfirm($Id, $Hash)
  {
    $DbResult = $this->Database->select('User', 'Id, Login, Password', 'Id = '.$Id);
    if($DbResult->num_rows > 0)
    {
      $Row = $DbResult->fetch_array();
      if($Hash == $Row['Password'])
      {
        $this->Database->update('User', 'Id='.$Row['Id'], array('Locked' => 0));
        $Output = $this->System->Translate('UserRegistrationConfirmed');
        $this->System->Modules['Log']->NewRecord('User', 'RegisterConfirm', 'Login='.$Row['Login'].', Id='.$Row['Id']);
      } else $Output = $this->System->Translate('PasswordsUnmatched');
    } else $Output = $this->System->Translate('UserNotFound');
    return($Output);
  }

  function Login($Login, $Password)
  {
    $SID = session_id();
    $Query = $this->Database->select('User', '*', 'Login="'.$Login.'"');
    if($Query->num_rows > 0)
    {
      $Row = $Query->fetch_assoc();
      if($Row['Password'] != $this->PasswordHash($Login, $Password)) $Result = $this->System->Translate('BadPassword');
      else if($Row['Locked'] == 1) $Result = $this->System->Translate('AccountLocked');
      else 
      {
        $this->Database->update('User', 'Id='.$Row['Id'], array('LastLoginTime' => 'NOW()', 'LastIpAddress' => $this->System->GetRemoteAddress()));      
        $this->Database->update('UserOnline', 'SessionId="'.$SID.'"', array('User' => $Row['Id']));
        // načtení stavu stromu
        $Result = $this->System->Translate('UserLoggedIn');
        $this->System->Modules['Log']->NewRecord('User', 'Login', 'Login='.$Login.',Host='.gethostbyaddr($this->System->GetRemoteAddress()));
      }
    } else $Result = $this->System->Translate('UserNotRegistred');
    $this->Check();
    return($Result);
  }

  function Logout()
  {
    $SID = session_id();
    $this->Database->update('UserOnline', 'SessionId="'.$SID.'"', array('User' => $this->Config['Web']['UserAnonymousId']));
    $this->System->Modules['Log']->NewRecord('User', 'Logout', $this->Data['Login']);
    $this->Check();
    return($this->System->Translate('UserLoggedOut'));
  }

  function PasswordRecoveryRequest($Login, $Email)
  {
    $DbResult = $this->Database->select('User', 'Login, Name, Id, Email, Password', '`Login`="'.$Login.'" AND `Email`="'.$Email.'"');
    if($DbResult->num_rows > 0)
    {
      $Row = $DbResult->fetch_assoc();
      $NewPassword = substr(sha1(strtoupper($Row['Login'])), 0, 7);

      $Mail = new Mail();
      $Mail->Subject = 'Obnova hesla';
      $Mail->Content = 'Požádali jste o zaslání nového hesla na serveru <a href="http://'.
        $this->Config['Web']['Host'].$this->Config['Web']['RootFolder'].'">http://'.
        $this->Config['Web']['Host'].$this->Config['Web']['RootFolder']."</a>.<br />\n".
        "Pokud jste tak neučinili, měli by jste tento email ignorovat.<br /><br />\n\nVaše nové heslo k účtu ".
        $Row['Login']." je: ".$NewPassword."\n<br>Pro aktivaci tohoto hesla klikněte na ".
        '<a href="http://'.$this->Config['Web']['Host'].$this->Config['Web']['RootFolder'].
        '/?Action=PasswordRecoveryConfirm&User='.$Row['Id'].'&H='.$Row['Password'].'&P='.
        $NewPassword.'">tento odkaz</a>.'."\n<br /> Po přihlášení si prosím změňte heslo na nové.\n\n".
        "<br><br>Na tento email neodpovídejte.";
      $Mail->RecipientName = $Row['Name'];
      $Mail->RecipientAddress = $Row['Email'];
      $Mail->SenderName = $this->Config['Web']['Title'];
      $Mail->SenderAddress = 'noreplay@zdechov.net';
      $Mail->Send();
      
      $Output = $this->System->Translate('UserPasswordRecoverySuccess');
      $this->System->Modules['Log']->NewRecord('User', 'PasswordRecoveryRequest', 'Login='.$Login.',Email='.$Email);
    } else $Output = $this->System->Translate('UserPasswordRecoveryFail');
    return($Output);
  }

  function PasswordRecoveryConfirm($Id, $Hash, $NewPassword)
  {
    $DbResult = $this->Database->select('User', 'Id, Login, Password', 'Id = '.$Id);
    if($DbResult->num_rows > 0)
    {
      $Row = $DbResult->fetch_array();
      $NewPassword2 = substr(sha1(strtoupper($Row['Login'])), 0, 7);
      if(($NewPassword == $NewPassword2) and ($Hash == $Row['Password']))
      {
        $this->Database->update('User', 'Id='.$Row['Id'], array('Password' => sha1($NewPassword), 'Locked' => 0));
        $Output = $this->System->Translate('UserPasswordRecoveryConfirmed');
        $this->System->Modules['Log']->NewRecord('User', 'PasswordRecoveryConfirm', 'Login='.$Row['Login']);
      } else $Output = $this->System->Translate('UserPasswordUnmatched');
    } else $Output = $this->System->Translate('UserNotFound');
    return($Output);
  }
}
