<?php
/**
 * @copyright (c) Kufer Software GmbH, Oderstraße 7, D-84453 Mühldorf
 */


class RequestOperations
{
  public static function getMethod()
  {
    $method = StringOperations::strtolower(static::getVarValueServer('REQUEST_METHOD'));
    
    if (in_array($method, array('get', 'head', 'post', 'put', 'delete', 'connect', 'options', 'trace', 'patch'))) {
      return $method;
    } else {
      return '';
    }
  }

  public static function isPost()
  {
    return static::getMethod() === 'post';
  }

  public static function isGet()
  {
    return static::getMethod() === 'get';
  }

  
  public static function isAjax(): bool
  {
    return static::getVarValueServer('HTTP_X_REQUESTED_WITH') === 'XMLHttpRequest';
  }

  public static function getClientIPAddress()
  {
    return static::getVarValueServer('REMOTE_ADDR');
  }

  
  public static function getPhpSelf($pDefault = '')
  {
    return static::getVarValueServer('PHP_SELF', $pDefault);
  }

  public static function getReferer($pDefault = '')
  {
    if (isset($_SERVER['HTTP_REFERER'])) {
      return filter_input(INPUT_SERVER, 'HTTP_REFERER', FILTER_SANITIZE_URL);
    }

    return $pDefault;
  }

  public static function getScriptName($pDefault = '')
  {
    return static::getVarValueServer('SCRIPT_NAME', $pDefault);
  }

  public static function getServerName($pDefault = '')
  {
    return static::getVarValueServer('SERVER_NAME', $pDefault);
  }

  public static function getHostName($pDefault = '')
  {
    return static::getVarValueServer('HTTP_HOST', $pDefault);
  }

  public static function getVarValueServer($pVarname, $pDefault = '')
  {
    if (isset($_SERVER[$pVarname])) {
      return FilterBasis::stdFilterServerString($_SERVER[$pVarname]);
    } else {
      return $pDefault;
    }
  }

  
  public static function getFromHTTP($pAdress)
  {
    if (CURL_USE) {
      $ch = curl_init($pAdress);
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      if (CURL_PROXYSERVER != '') {
        curl_setopt($ch, CURLOPT_PROXY, CURL_PROXYSERVER);
      }
      if (CURL_PROXYPASS != '') {
        curl_setopt($ch, CURLOPT_PROXYUSERPWD, CURL_PROXYPASS);
      }
      curl_setopt($ch, CURLOPT_HEADER, false);
      $site = curl_exec($ch);
      curl_close($ch);

      return $site;
    } else {
      return implode('', file($pAdress));
    }
  }

  public static function getFromInputStream()
  {
    return file_get_contents('php://input');
  }

  public static function getJsonFromInputStream($decodeAssoc = false)
  {
    return json_decode(self::getFromInputStream(), $decodeAssoc);
  }

  
  public static function getFromPOST($url, $postData)
  {
    $curl = RequestOperations::getStandardCurl($url, $postData);
    $result = curl_exec($curl);
    curl_close($curl);

    return $result;
  }

  public static function getFromPostAuth($url, $postData, $username, $password, $contenttype)
  {
    $curl = RequestOperations::getStandardCurl($url, $postData);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
      'Content-Type: ' . $contenttype,
      'Authorization: Basic ' . base64_encode($username . ':' . $password)
    ));
    $result = curl_exec($curl);
    curl_close($curl);

    return $result;
  }

  
  public static function getStandardCurl($pAdress = '', $params = '', $type = 'POST', int $timeout = 20)
  {
    

    if (!function_exists('curl_init')) {
      Logger::logg('Konnte Curl nicht instantiieren, da nicht installiert.', 1890);

      return false;
    }
    $curl = curl_init();
    if ($curl === false) {
      return false;
    }

    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    if ($pAdress !== '' && $pAdress !== null) {
      curl_setopt($curl, CURLOPT_URL, $pAdress);
    }

    if (CURL_USE) {
      if (CURL_PROXYSERVER != '') {
        curl_setopt($curl, CURLOPT_PROXY, CURL_PROXYSERVER);
      }
      if (CURL_PROXYPASS != '') {
        curl_setopt($curl, CURLOPT_PROXYUSERPWD, CURL_PROXYPASS);
      }
    }

    switch (StringOperations::strtoupper($type)) {
      case 'POST':
        curl_setopt($curl, CURLOPT_POST, true);
        if (is_string($params) || (is_array($params) && count($params) > 0)) {
          curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
        }
        break;
      case 'GET':
        curl_setopt($curl, CURLOPT_URL, $pAdress . '?' . http_build_query($params));
        break;
      default:
        throw new InvalidArgumentException("HTTP Typ $type ist nicht definiert");
    }

    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);

    return $curl;
  }

  public static function getUserAgent()
  {
    return FilterBasis::getOnlyAlphaNumeric($_SERVER['HTTP_USER_AGENT']);
  }

  
  public static function getVarValue($varname, $default = '')
  {
    if (isset($_REQUEST[$varname])) {
      return $_REQUEST[$varname];
    } else {
      return $default;
    }
  }

  public static function setVarValue($varname, $value) : void
  {
    $_REQUEST[$varname] = $value;
  }

  
  public static function getVarValuePG($pVarname, $pDefault = '')
  {
    $result = static::getVarValue($pVarname, $pDefault);
    if ($result === $pDefault) {
      $result = PostOperations::getVarValue($pVarname, $pDefault);
      if ($result === $pDefault) {
        $result = GetOperations::getVarValue($pVarname, $pDefault);
      }
    }

    return $result;
  }

  
  public static function isDefined($varname)
  {
    return isset($_REQUEST[$varname]);
  }

  public static function getInt($varname, $default = 0)
  {
    return Type::getInt(self::getVarValue($varname, $default), $default);
  }

  public static function getFloatKomma($varname, $default = '0')
  {
    return Type::getFloatKomma(self::getVarValue($varname, $default), $default);
  }

  public static function getFloatPunkt($varname, $default = 0.0)
  {
    return Type::getFloatPunkt(self::getVarValue($varname, $default), $default);
  }

  
  public static function toKathaupt($pKathauptId)
  {
    $urlparam = new URLParameterHauptmenue();
    $urlparam->kathaupt = $pKathauptId;
    $url = CmsAnb::getAnbindung()->rewriteUrl($urlparam);
    header('Location: ' . $url);
    die();
  }

  
  public static function to($pURL)
  {
    header('Location: ' . $pURL);
    die();
  }

  
  public static function sendHttpStatusAndQuit(int $responseCode): void
  {
    while (ob_get_level() > 0) {
      ob_end_clean();
    }
    http_response_code($responseCode);
    die();
  }

  public static function getWarenkorbUrl($message = '', $epayment = false)
  {
    $urlparam = new URLParameterWarenkorb();
    $urlparam->kathaupt = 4;
    if ($epayment) {
      $urlparam->payOnline = 1;
    }
    if ($message != '') {
      $urlparam->message = base64_encode(StringOperations::utf8_encode($message));
    }

    return str_replace('&amp;', '&', CmsAnb::getAnbindung()->rewriteUrl($urlparam));
  }

  public static function redirectToWarenkorb($message = '')
  {
    $url = self::getWarenkorbUrl($message, true);
    self::to($url);
  }

  
  public static function isHttps()
  {
    return (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1))
        || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https');
  }

  
  public static function getHttpProtocolPrefix()
  {
    return self::isHttps() ? 'https://' : 'http://';
  }

  public static function setRequestHeaderByFilename($filename)
  {
    $contentType = FSOperations::getContentTypeByFileName($filename);

    if ($contentType) {
      header('Content-Type: ' . $contentType);
    }
    $fileparts = FSOperations::getFileParts($filename);
    header('Content-Disposition: attachment; filename="' . $fileparts['name'] . '.' . $fileparts['extension'] . '"');
  }
}