<?php

define('NICK_USED', 'Přihlašovací jméno již použito.');
define('EMAIL_USED', 'Email je již použitý.');
define('USER_REGISTRATED', 'Uživatel zaregistrován.');
define('USER_REGISTRATION_CONFIRMED', 'Vaše registrace byla potvrzena.');
define('DATA_MISSING', 'Chybí emailová adresa, přezdívka, nebo některé z hesel.');
define('PASSWORDS_UNMATCHED', 'Hesla si neodpovídají.');
define('ACCOUNT_LOCKED', 'Účet uzamčen. Po registraci je nutné provést aktivaci účtu podle zaslaného aktivačního emailu.');
define('USER_NOT_LOGGED', 'Nejste přihlášen.');
define('USER_LOGGED', 'Uživatel přihlášen.');
define('USER_NOT_REGISTRED', 'Uživatel neregistrován.');
define('USER_ALREADY_LOGGED', 'Uživatel již přihlášen.');
define('USER_LOGGED_IN', 'Byl jste přihlášen.');
define('USER_LOGGED_OUT', 'Byl jste odhlášen.');
define('BAD_PASSWORD', 'Špatné heslo.');
define('USER_NOT_FOUND', 'Uživatel nenalezen.');
define('USER_TIMEOUT', 300);  // in seconds
define('USER_PASSWORD_RECOVERY_SUCCESS', 'Přihlašovací údaje byly odeslány na zadanou emailovou adresu.');
define('USER_PASSWORD_RECOVERY_FAIL', 'Podle zadaných údajů nebyl nalezen žádný uživatel.');
define('USER_PASSWORD_RECOVERY_CONFIRMED', 'Nové heslo bylo aktivováno.');

define('USER_EVENT_REGISTER', 1);
define('USER_EVENT_LOGIN', 2);
define('USER_EVENT_LOGOUT', 3);
define('USER_EVENT_OPTIONS_CHANGED', 4);

class User extends Module
{
  var $Dependencies = array('Log');
  var $Roles = array();
  var $User = array();
  var $DefaultRole = 2;
  var $TableUser = 'User';
  var $TableUserOnline = 'UserOnline';

  function Check()
  {
    global $Config;

    $SID = session_id();
    // Lookup user record
    $Query = $this->Database->select(array('Table' => $this->TableUserOnline, 'Condition' => '`SessionId`="'.$SID.'"'));
    if($Query->num_rows > 0)
    {
      // Refresh time of last access
      $this->Database->update(array('Table' => $this->TableUserOnline, 'Condition' => '`SessionId`="'.$SID.'"'), array('ActivityTime' => 'NOW()'));
    } else $this->Database->insert(array('Table' => $this->TableUserOnline), array('SessionId' => $SID, 'User' => 0, 'LoginTime' => 'NOW()', 'ActivityTime' => 'NOW()', 'IpAddress' => GetRemoteAddress(), 'HostName' => gethostbyaddr(GetRemoteAddress())));
    //echo($this->Database->LastQuery);

    // Zkontroluj přihlášení
    $Query = $this->Database->select(array('Table' => $this->TableUserOnline, 'Condition' => 'SessionId="'.$SID.'"'));
    $Row = $Query->fetch_assoc();
    if($Row['User'] != 0)
    {
      $Query = $this->Database->query('SELECT * FROM `'.$this->TableUser.'` WHERE `Id`='.$Row['User']);
      $this->User = $Query->fetch_assoc();
      //print_r($this->User);
      $Result = USER_LOGGED;
    } else
    {
      $Query = $this->Database->select(array('Table' => $this->TableUser, 'Condition' => "`Id`=0"));
      $this->User = $Query->fetch_assoc();
      $Result = USER_NOT_LOGGED;
    }

    // Odeber neaktivní uživatele
    $DbResult = $this->Database->select(array('Table' => $this->TableUserOnline, 'Columns' => 'User', 'Condition' => '`ActivityTime` < DATE_SUB(NOW(), INTERVAL '.USER_TIMEOUT.' SECOND)'));
    while($DbRow = $DbResult->fetch_assoc())
    {
      $this->Database->delete(array('Table' => $this->TableUserOnline, 'Condition' => '`User`='.$DbRow['User']));
      //$this->System->Modules['Log']->Add('User', 'Logout');
    }
    //$this->LoadPermission($this->User['Role']);

    // Role and permission
    //$this->LoadRoles();
  }

  function Register($Nick, $Password, $Password2, $Email, $FirstName, $SecondName)
  {
    global $Options, $Config;

    if(($Email == '') || ($Nick == '') || ($Password == '') || ($Password2 == '')) $Result = DATA_MISSING;
    else if($Password != $Password2) $Result = PASSWORDS_UNMATCHED;
    else
    {
      // Je uživatel registrován?
      $Query = $this->Database->select(array('Table' => $this->TableUser, 'Condition' => 'Name = "'.$Nick.'"'));
      if($Query->num_rows > 0) $Result = NICK_USED;
      else
      {
        $Query = $this->Database->select(array('Table' => $this->TableUser, 'Condition' => 'Email = "'.$Email.'"'));
        if($Query->num_rows > 0) $Result = EMAIL_USED;
        else
        {
          $this->Database->insert(array('Table' => $this->TableUser), array('Name' => $Nick, 'FirstName' => $FirstName, 'SecondName' => $SecondName, 'Password' => $Password, 'Email' => $Email, 'RegistrationTime' => 'NOW()', 'Locked' => 1));
          $UserId = $this->Database->insert_id;

          $Subject = FromUTF8('Registrace nového účtu', 'iso2');
          $Message = 'Provedli jste registraci nového účtu na serveru <a href="http://'.$Config['Web']['Host'].$Config['Web']['RootFolder'].'">http://'.$Config['Web']['Host'].$Config['Web']['RootFolder']."</a>.<br>\nPokud jste tak neučinili, měli by jste tento email ignorovat.<br><br>\n\nVáš účet je: ".$Nick."\n<br>Pro dokončení registrace klikněte na ".'<a href="http://'.$Config['Web']['Host'].$Config['Web']['RootFolder'].'/?Action=UserRegisterConfirm&amp;User='.$UserId.'&amp;H='.$Password.'">tento odkaz</a>.'."\n<br> \n\n<br><br>Na tento email neodpovídejte.";
          $AdditionalHeaders = "To: ".$Nick." <".$Email.">\n"."From: ".FromUTF8($Config['Web']['Title'], 'iso2')." <noreplay@zdechov.net>\n"."MIME-Version: 1.0\n"."Content-type: text/html; charset=utf-8";
          mail($Email, $Subject, $Message, $AdditionalHeaders);
          $Result = USER_REGISTRATED;
          //$this->System->Modules['Log']->NewRecord('User', 'NewRegistration', $Nick);
        }
      }
    }
    return($Result);
  }

  function RegisterConfirm($Id, $Hash)
  {
    $DbResult = $this->Database->select(array('Table' => $this->TableUser, 'Columns' => 'Id, Name, Password', 'Condition' => 'Id = '.$Id));
    if($DbResult->num_rows > 0)
    {
      $Row = $DbResult->fetch_assoc();
      if($Hash == $Row['Password'])
      {
        $this->Database->update(array('Table' => $this->TableUser, 'Condition' => 'Id='.$Row['Id']), array('Locked' => 0));
        $Output = USER_REGISTRATION_CONFIRMED;
        //$this->System->Modules['Log']->NewRecord('User', 'RegisterConfirm', 'UserName='.$Row['Name']);
      } else $Output = PASSWORDS_UNMATCHED;
    } else $Output = USER_NOT_FOUND;
    return($Output);
  }

  function Login($Nick, $Password)
  {
    $SID = session_id();
    // Je uživatel registrován?
    $Query = $this->Database->select(array('Table' => $this->TableUser, 'Condition' => 'UserName="'.$Nick.'"'));
    if($Query->num_rows > 0)
    {
      $Row = $Query->fetch_assoc();
      if($Row['Password'] != $Password) $Result = BAD_PASSWORD;
      else if($Row['Locked'] == 1) $Result = ACCOUNT_LOCKED;
      else
      {
        $this->Database->update(array('Table' => $this->TableUser, 'Condition' => 'Id='.$Row['Id']), array('LastLoginTime' => 'NOW()'));
        $this->Database->update(array('Table' => $this->TableUserOnline, 'Condition' => 'SessionId="'.$SID.'"'), array('User' => $Row['Id'], 'Id' => $Row['Id']));
        // načtení stavu stromu
        $Result = USER_LOGGED_IN;
        //$this->System->Modules['Log']->NewRecord('User', 'Login', 'Nick='.$Nick.',Host='.gethostbyaddr(GetRemoteAddress()));
      }
    } else $Result = USER_NOT_REGISTRED;
    $this->Check();
    return($Result);
  }

  function Logout()
  {
    global $Config;

    $SID = session_id();
    $this->Database->update(array('Table' => $this->TableUserOnline, 'Condition' => 'SessionId="'.$SID.'"'), array('User' => 0));
    //$this->System->Modules['Log']->NewRecord('User', 'Logout', $this->User['Name']);
    $this->Check();
    return(USER_LOGGED_OUT);
  }

  function PasswordRecoveryRequest($Name, $Email)
  {
    global $Config;

    $DbResult = $this->Database->select(array('Table' => $this->TableUser, 'Columns' => 'Name, Id, Email, Password', 'Condition' => '`Name`="'.$Name.'" AND `Email`="'.$Email.'"'));
    if($DbResult->num_rows > 0)
    {
      $Row = $DbResult->fetch_assoc();
      $NewPassword = substr(sha1(strtoupper($Row['Name'])), 0, 7);

      $Subject = 'Obnova hesla';
      $Message = 'Požádali jste o zaslání nového hesla na serveru <a href="http://'.$Config['Web']['Host'].$Config['Web']['RootFolder'].'">http://'.$Config['Web']['Host'].$Config['Web']['RootFolder']."</a>.<br>\nPokud jste tak neučinili, měli by jste tento email ignorovat.<br><br>\n\nVaše nové heslo k účtu ".$Row['Name']." je: ".$NewPassword."\n<br>Pro aktivaci tohoto hesla klikněte na ".'<a href="http://'.$Config['Web']['Host'].$Config['Web']['RootFolder'].'/?Action=PasswordRecoveryConfirm&amp;User='.$Row['Id'].'&amp;H='.$Row['Password'].'&amp;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.";
      $AdditionalHeaders = "To: ".$Row['Name']." <".$Row['Email'].">\n"."From: ".FromUTF8($Config['Web']['Title'], 'iso2')." <noreplay@zdechov.net>\n"."MIME-Version: 1.0\n"."Content-type: text/html; charset=utf-8";
      mail($Row['Email'], $Subject, $Message, $AdditionalHeaders);
      $Output = USER_PASSWORD_RECOVERY_SUCCESS;
      //$this->System->Modules['Log']->NewRecord('User', 'PasswordRecoveryRequest', 'UserName='.$Name.',Email='.$Email);
    } else $Output = USER_PASSWORD_RECOVERY_FAIL;
    return($Output);
  }

  function PasswordRecoveryConfirm($Id, $Hash, $NewPassword)
  {
    $DbResult = $this->Database->select(array('Table' => $this->TableUser, 'Columns' => 'Id, Name, Password', 'Condition' => 'Id = '.$Id));
    if($DbResult->num_rows > 0)
    {
      $Row = $DbResult->fetch_assoc();
      $NewPassword2 = substr(sha1(strtoupper($Row['Name'])), 0, 7);
      if(($NewPassword == $NewPassword2) and ($Hash == $Row['Password']))
      {
        $this->Database->update(array('Table' => $this->TableUser, 'Condition' => 'Id='.$Row['Id']), array('Password' => $NewPassword, 'Locked' => 0));
        $Output = USER_PASSWORD_RECOVERY_CONFIRMED;
        //$this->System->Modules['Log']->NewRecord('User', 'PasswordRecoveryConfirm', 'UserName='.$Row['Name']);
      } else $Output = PASSWORDS_UNMATCHED;
    } else $Output = USER_NOT_FOUND;
    return($Output);
  }
}

?>
