<?php
class security
{
  public static function checkPassword($password, $dbPasswordHash)
  {
    $pwHash                         = new pwhash(BCRYPT_HASH_ROUNDS, FALSE);
    $loginPass                      = md5($password);
    $loginPasspwHash                = $pwHash->CheckPassword($loginPass, $dbPasswordHash);
    
    if ($loginPasspwHash            == 1) {
      return 1;
    } else {
      return 0;
    }
  }
  
  public static function checkPasswdComplexity($string, $complexity, $length)
  {
    /**
     * Komplexität = 0 -> Zahlen und Buchstaben, Gross und Klein
     * Komplexität = 1 -> Zahlen und Buchstaben, Gross und Klein, sowie Sonderzeichen
     */
    switch ($complexity) {
      case 0:
        if( preg_match( '/[[:lower:]]/', $string ) && preg_match( '/[[:upper:]]/', $string ) && preg_match( '/[[:digit:]]/', $string )) {
          $val                      = 1;
        } else {
          $val                      = 0;
          $errorMsg                 = 'La contraseña debe ser grande en minúsculas letras y números! (0-9, a-Z)';
        }
        break;
      case 1:
        if( preg_match( '/[[:lower:]]/', $string ) && preg_match( '/[[:upper:]]/', $string ) && preg_match( '/[[:digit:]]/', $string ) && preg_match( '/[[:punct:]]/', $string )) {
          $val                    = 1;
        } else {
          $val                                = 0;
          $errorMsg                 = 'La contraseña debe ser grande en minúsculas letras y números y caracteres especiales! (0-9, a-Z, ?!#@&%$=/)';
        }
        break;
    }  
    
    if (strlen($string)             < $length) {
      return 'Contraseña demasiado corta, min. ' . $length . ' caracteres';
    } elseif ($val                  == 0) {
      return $errorMsg;
    } else {
      return 'OK';
    }
  }
  
  public static function checkAuth($uuid)
  {
    $db                             = new Database();
    
    $sql                            = 'SELECT COUNT(id) as amount FROM tbl_users WHERE uuid = :uuid AND account_locked = :account_locked';
    $db->query($sql);
    $db->bind(':uuid', $uuid);
    $db->bind('account_locked', 0);
    $row                            = $db->single();
    return $row['amount'];
  }
  
  public static function encode($string)
  {
    $result                         = '';
    for($value                      = 0; $value < strlen ($string); $value++) {
      $secKey                       = constant("SEC_PW"); //zusaetzlicher Verschluesselumgskey
      $valueChar                    = substr($string, $value, 1);
      $secKeyChar                   = substr($secKey, ($value % strlen($secKey))-1, 1);
      $valueCharShow                = chr(ord($valueChar)+ord($secKeyChar));
      $result                       .= $valueCharShow;
    }
    return base64_encode($result);
  }

  public static function decode($stringVal)
  {
    $result                         = '';
    $string                         = base64_decode($stringVal);
    for($value                      = 0; $value < strlen($string); $value++) {
      $secKey                       = constant("SEC_PW"); //zusaetzlicher Dekodierumgskey
      $valueChar                    = substr($string, $value, 1);
      $secKeyChar                   = substr($secKey, ($value % strlen($secKey))-1, 1);
      $valueCharShow                = chr(ord($valueChar)-ord($secKeyChar));
      $result                       .= $valueCharShow;
    }
    return $result;
  }
  
  public static function sh1($str) 
  {
    $val                              = '10000';
    $sec_pw                           = 'Yhf548933FeSScxpljgTh89Gdswqfybhnzxtujqbao7G69DRE7fgd';
    for ($x                           = 0; $x < $val; $x++) {
      $str                            = hash('sha512', $str . $sec_pw);
    }
    return $str;
  }
  
  public static function setLoginCookie($cookieName, $cookieVal)
  {
    $validTime                        = time() + (3600 * COOKIE_VALID_TIME);
    $loginCookie                      = setcookie($cookieName, $cookieVal, $validTime, "/", "", 0, true);
    return $loginCookie;
  }
  
  public static function createSecToken()
  {
    $letters                          = array("A", "B", "C", "D", "E", "F", "G", "H", "J", "I", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
    $numbers                          = array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9");

    for($i                            = 0, $Code = "", $AthCode = ""; strlen($Code) < 120; $i++) {
      if(rand(0, 1)                   == 0 && isset($letters)) {
        $letter                       = $letters[rand(0, count($letters)-1)];
        $Code                         .= $letter;
        $secToken                     .= $letter;
      } else {
        $number                       = $numbers[rand(0, count($numbers)-1)];
        $Code                         .= $number;
        $secToken                     .= $number;
      }
    }
    return $secToken;
  }
  
  public static function deleteLoginCookie($cookieName)
  {
    $delCookie                        = setcookie($cookieName,"",time() - 3600, "/");
    return $delCookie;
  }
  
  public static function saveUnauthorizedLoginsExt($userUuid, $username, $ipAddress)
  {
    $insertArray                      = array(
        'user_uuid'                   => $userUuid,
        'username'                    => $username,
        'ip_address'                  => $ipAddress,
        'reg_datetime'                => date("Y-m-d H:i:s"),
    );
    return pdoDbInsert("tbl_login_ext_not_allowed", $insertArray);
  }
  
  public static function saveUnauthorizedLogins($username, $password, $ipAddress)
  {
    $insertArray                      = array(
        'username'                    => $username,
        'password'                    => $password,
        'ip_address'                  => $ipAddress,
        'reg_datetime'                => date("Y-m-d H:i:s"),
    );
    return pdoDbInsert("tbl_login_incorrect", $insertArray);
  }
  
  public static function getAmountUnauthorizedLoginsByIP($ipAddress)
  {
    $db                               = new Database();
    $sql                              = 'SELECT COUNT(id) as amount FROM tbl_login_incorrect WHERE ip_address = :ip_address AND is_unlocked = :is_unlocked';
    $db->query($sql);
    $db->bind(':ip_address', $ipAddress);
    $db->bind(':is_unlocked', 0);
    $row                              = $db->single();
    return $row['amount'];
  }
  
  
  
  public static function saveAuthorizedLogins($userUuid, $username, $ipAddress, $isCookie)
  {
    $insertArray                      = array(
        'user_uuid'                   => $userUuid,
        'username'                    => $username,
        'is_cookie'                   => $isCookie,
        'ip_address'                  => $ipAddress,
        'reg_datetime'                => date("Y-m-d H:i:s"),
    );
    return pdoDbInsert("tbl_login_correct", $insertArray);
  }
  
  public static function getOfficeIpAddress()
  {
    $db                               = new Database();
    $sql                              = 'SELECT ip_address FROM tbl_office_ip ORDER BY id DESC';
    $db->query($sql);
    $row                              = $db->single();
    return $row['ip_address'];
  }
  
  public static function setOfficeIpAddress()
  {
    $insertArray                      = array(
        'ip_address'                  => $_SERVER['REMOTE_ADDR'],
        'reg_by'                      => $_SESSION[ALLOW],
        'reg_datetime'                => date("Y-m-d H:i:s"),
    );
    return pdoDbInsert("tbl_office_ip", $insertArray);
  }
  
  public static function getLastUpdateIpAddress()
  {
    $db                               = new Database();
    $sql                              = 'SELECT reg_datetime FROM tbl_office_ip ORDER BY id DESC';
    $db->query($sql);
    $row                              = $db->single();
    return makeLocalDate($row['reg_datetime'], "DE");
  }
  
  public static function resetUnauthorizedLoginsExt()
  {
    $db                               = new Database();
    $sql                              = 'UPDATE tbl_login_ext_not_allowed SET is_deactivated = :is_deactivated';
    $db->query($sql);
    $db->bind(':is_deactivated', 1);
    return $db->execute();
  }
  
  public static function resetUnauthorizedLogins()
  {
    $db                               = new Database();
    $sql                              = 'UPDATE tbl_login_incorrect SET is_deactivated = :is_deactivated';
    $db->query($sql);
    $db->bind(':is_deactivated', 1);
    return $db->execute();
  }
  
  public static function resetAuthorizedLogins()
  {
    $db                               = new Database();
    $sql                              = 'UPDATE tbl_login_correct SET is_deactivated = :is_deactivated';
    $db->query($sql);
    $db->bind(':is_deactivated', 1);
    return $db->execute();
  }
  
  public static function logout()
  {
    $insertArray                      = array(
        'ip_address'                  => $_SERVER['REMOTE_ADDR'],
        'reg_by'                      => $_SESSION[ALLOW],
        'reg_datetime'                => date("Y-m-d H:i:s"),
    );
    return pdoDbInsert("tbl_users_logout", $insertArray);
  }
  
  public static function checkBelongToUser($kundenId)
  {
    $db                               = new Database();
    $sql                              = 'SELECT COUNT(id) as amount FROM kunden WHERE belong_to_user_uuid = :belong_to_user_uuid AND id = :kunden_id';
    $db->query($sql);
    $db->bind(':belong_to_user_uuid', $_SESSION[ALLOW]);
    $db->bind(':kunden_id', $kundenId);
    $row                              = $db->single();
    return $row['amount'];
  }
}

