<?php

define('NICK_USED', 'Přihlašovací jméno již použito.');
define('EMAIL_USED', 'Email je již použitý. Použijte jiný email nebo si můžete nechat zaslat nové heslo na email.');
define('USER_REGISTRATED', 'Uživatel registrován. Na zadanou emailovou adresu byl poslán mail s odkazem pro aktivování účtu.');
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 je uzamčen. Po registraci je nutné provést aktivaci účtu pomocí odkazu zaslaného v aktivačním 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_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 $AnonymousUserId = 98;
  var $OnlineStateTimeout = 600; // in seconds

  function Check()
  {
    $SID = session_id();
    // Lookup user record
    $Query = $this->Database->select('UserOnline', '*', 'SessionId="'.$SID.'"');
    if($Query->num_rows > 0)
    {
      // Refresh time of last access
      $this->Database->update('UserOnline', 'SessionId="'.$SID.'"', array('ActivityTime' => 'NOW()'));
    } else $this->Database->insert('UserOnline', array('SessionId' => $SID, 'User' => $this->AnonymousUserId, 'LoginTime' => 'NOW()', 'ActivityTime' => 'NOW()', 'IpAddress' => GetRemoteAddress(), 'HostName' => gethostbyaddr(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->AnonymousUserId) 
    {
      $Query = $this->Database->select('User', '*', "Id=".$Row['User']."");
      $this->User = $Query->fetch_assoc();
      $Result = USER_LOGGED;
    } else 
    {
      $Query = $this->Database->select('User', '*', "Id=".$this->AnonymousUserId);
      $this->User = $Query->fetch_assoc();
      $Result = USER_NOT_LOGGED;
    }

    // Remove nonactive users
    $DbResult = $this->Database->select('UserOnline', 'Id, User', 'ActivityTime < DATE_SUB(NOW(), INTERVAL '.$this->OnlineStateTimeout.' SECOND)');
    while($DbRow = $DbResult->fetch_array())
    {
      $this->Database->delete('UserOnline', 'Id='.$DbRow['Id']);
      if($DbRow['Id'] != $this->AnonymousUserId) $this->System->Modules['Log']->NewRecord('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('User', '*', 'Name = "'.$Nick.'"');
      if($Query->num_rows > 0) $Result = NICK_USED;
      else
      {
        $Query = $this->Database->select('User', '*', 'Email = "'.$Email.'"');
        if($Query->num_rows > 0) $Result = EMAIL_USED;
        else
        {
          $this->Database->insert('User', array('Name' => $Nick, 'FirstName' => $FirstName, 'SecondName' => $SecondName, 'Password' => sha1($Password), 'Email' => $Email, 'RegistrationTime' => 'NOW()', 'Locked' => 1));
          $UserId = $this->Database->insert_id;
		  $this->Database->insert('PermissionUserAssignment', array('User' => $UserId, 'GroupOrOperation' => 1, 'Type' => 'Group'));
          
          $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&User='.$UserId.'&H='.sha1($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('User', 'Id, Name, 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 = 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();
    $Query = $this->Database->select('User', '*', 'Name="'.$Nick.'"');
    if($Query->num_rows > 0)
    {
      $Row = $Query->fetch_assoc();
      if($Row['Password'] != sha1($Password)) $Result = BAD_PASSWORD;
      else if($Row['Locked'] == 1) $Result = ACCOUNT_LOCKED;
      else 
      {
        $this->Database->update('User', 'Id='.$Row['Id'], array('LastLoginTime' => 'NOW()', 'LastIpAddress' => GetRemoteAddress()));    	
        $this->Database->update('UserOnline', 'SessionId="'.$SID.'"', array('User' => $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()
  {
    $SID = session_id();
    $this->Database->update('UserOnline', 'SessionId="'.$SID.'"', array('User' => $this->AnonymousUserId));
    $this->System->Modules['Log']->NewRecord('User', 'Logout', $this->User['Name']);
    $this->Check();
    return(USER_LOGGED_OUT);
  }

  function LoadRoles()
  {
    $this->Roles = array();
    $DbResult = $this->Database->select('UserRole', '*');
    while($DbRow = $DbResult->fetch_array())
      $this->Roles[] = $DbRow;
  }

  function LoadPermission($Role)
  {
    $this->User['Permission'] = array();
    $DbResult = $this->Database->query('SELECT `UserRolePermission`.*, `PermissionOperation`.`Description` FROM `UserRolePermission` JOIN `PermissionOperation` ON `PermissionOperation`.`Id` = `UserRolePermission`.`Operation` WHERE `UserRolePermission`.`Role` = '.$Role);
    if($DbResult->num_rows > 0)
    while($DbRow = $DbResult->fetch_array())
      $this->User['Permission'][$DbRow['Operation']] = $DbRow;
  }

  function PermissionMatrix()
  {
    $Result = array();
    $DbResult = $this->Database->query('SELECT `UserRolePermission`.*, `PermissionOperation`.`Description`, `UserRole`.`Title` FROM `UserRolePermission` LEFT JOIN `PermissionOperation` ON `PermissionOperation`.`Id` = `UserRolePermission`.`Operation` LEFT JOIN `UserRole` ON `UserRole`.`Id` = `UserRolePermission`.`Role`');
    while($DbRow = $DbResult->fetch_array())
    {
      $Value = '';
      if($DbRow['Read']) $Value .= 'R';
      if($DbRow['Write']) $Value .= 'W';
      $Result[$DbRow['Description']][$DbRow['Title']] = $Value;
    }
    return($Result);
  }

  function CheckGroupPermission($GroupId, $OperationId)
  {
    // Check group-group relation
    $DbResult = $this->Database->select('PermissionGroupAssignment', '*', '`Group`="'.$GroupId.'" AND `Type`="Group"');
    while($DbRow = $DbResult->fetch_array())
    {
       if($this->CheckGroupPermission($DbRow['GroupOrOperation'], $OperationId) == true) return(true);
    }

    // Check group-operation relation
    $DbResult = $this->Database->select('PermissionGroupAssignment', '*', '`Group`="'.$GroupId.'" AND `GroupOrOperation`="'.$OperationId.'" AND `Type`="Operation"');
    if($DbResult->num_rows > 0) return(true); 
    return(false);
  }

  function CheckPermission($Module, $Operation, $ItemType = '', $ItemIndex = 0)
  {
	$DbResult = $this->Database->select('PermissionOperation', 'Id', '`Module`="'.$Module.'" AND `Item`="'.$ItemType.'" AND `ItemId`='.$ItemIndex.' AND `Operation`="'.$Operation.'"');
    if($DbResult->num_rows > 0)
    {
      $DbRow = $DbResult->fetch_array();
      $OperationId = $DbRow['Id'];

      // Check user-operation relation
      $DbResult = $this->Database->select('PermissionUserAssignment', '*', '`User`="'.$this->User['Id'].'" AND `GroupOrOperation`="'.$OperationId.'" AND `Type`="Operation"');
      if($DbResult->num_rows > 0) return(true);

      // Check user-group relation
      $DbResult = $this->Database->select('PermissionUserAssignment', 'GroupOrOperation', '`User`="'.$this->User['Id'].'" AND `Type`="Group"');
      while($DbRow = $DbResult->fetch_array())
      {
         if($this->CheckGroupPermission($DbRow['GroupOrOperation'], $OperationId) == true) return(true);
      }
      return(false);
    } else return(false);
  }

  function PasswordRecoveryRequest($Name, $Email)
  {
    global $Config;

    $DbResult = $this->Database->select('User', 'Name, Id, Email, Password', '`Name`="'.$Name.'" AND `Email`="'.$Email.'"');
    if($DbResult->num_rows > 0)
    {
      $Row = $DbResult->fetch_array();
      $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&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.";
      $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('User', 'Id, Name, Password', 'Id = '.$Id);
    if($DbResult->num_rows > 0)
    {
      $Row = $DbResult->fetch_array();
      $NewPassword2 = substr(sha1(strtoupper($Row['Name'])), 0, 7);
      if(($NewPassword == $NewPassword2) and ($Hash == $Row['Password']))
      {
        $this->Database->update('User', 'Id='.$Row['Id'], array('Password' => sha1($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);
  }
}

?>
