<?php

define('NICK_USED', 'Přezdívka použita!');
define('USER_REGISTRATED', 'Uživatel zaregistrován.');
define('DATA_MISSING', 'Chybí emailová adresa, přezdívka, nebo některé z hesel!');
define('PASSWORDS_UNMATCHED', 'Hesla si neodpovídají!');
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_TIMEOUT', 300);  // in seconds

class User extends Module
{
  var $Roles = array();
  var $User = array();
  var $DefaultRole = 2;
  var $AnonymousUserId = 1;

  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('Time' => 'NOW()'));
    } else $this->Database->insert('UserOnline', array('SessionId' => $SID, 'User' => $this->AnonymousUserId, 'Time' => 'NOW()', 'IpAddress' => GetRemoteAddress(), 'HostName' => gethostbyaddr(GetRemoteAddress())));  
    //echo($this->Database->LastQuery);

    // Odeber neaktivní uživatele
    $this->Database->delete('UserOnline', 'Time < DATE_SUB(NOW(), INTERVAL '.USER_TIMEOUT.' SECOND)');

    // Zkontroluj přihlášení
    $Query = $this->Database->select('UserOnline', '*', 'SessionId="'.$SID.'"');
    $Row = $Query->fetch_array();
    if(($Row['User'] != $this->AnonymousUserId) and ($Query->num_rows > 0))
    {
      $Query = $this->Database->select('User', '*', "Id=".$Row['User']."");
      $this->User = $Query->fetch_array();
      $Result = USER_LOGGED;
    } else
    {
      $Query = $this->Database->select('User', '*', "Id=".$this->AnonymousUserId);
      $this->User = $Query->fetch_array();
      $Result = USER_NOT_LOGGED;
    }
    $this->LoadPermission($this->User['Role']);

    // Role and permission
    $this->LoadRoles();
  }

  function Register($Nick, $Password, $Password2, $Email, $FullName)
  {
    global $Options;
    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 
      {
        $this->Database->insert('User', array('Name' => addslashes($Nick), 'FullName' => addslashes($FullName), 'Password' => addslashes($Password), 'Email' => htmlspecialchars($Email), 'Role' => $this->DefaultRole));
        $Result = USER_REGISTRATED;
      }
    }
    return($Result);
  }

  function Login($Nick, $Password)
  {
    $SID = session_id();
    // Je uživatel registrován?
    $Query = $this->Database->select('User', '*', 'Name="'.$Nick.'"');
    if($Query->num_rows > 0)
    {
      $Row = $Query->fetch_array();
      if($Row['Password'] != $Password) $Result = BAD_PASSWORD;
      else 
      {
        $this->Database->update('User', 'Id='.$Row['Id'], array('LastLoginTime' => 'NOW()'));    
        $this->Database->update('UserOnline', 'SessionId="'.$SID.'"', array('User' => $Row['Id']));
        // načtení stavu stromu
        $Result = USER_LOGGED_IN;    
      }
    } else $Result = USER_NOT_REGISTRED;
    return($Result);
  }

  function Logout()
  {
    $SID = session_id();
    $this->Database->update('UserOnline', 'SessionId="'.$SID.'"', array('User' => $this->AnonymousUserId));
    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);
  }
}

?>
