<?php
//로그인체크 한후 권한체크
function isRole_CommonHelper(array $userRoles, $categoryEntity, $roleField = 'isaccess')
{
  return in_array($categoryEntity->getRole($roleField), $userRoles);
}

function getValueByKey_CommonHelper($key, array $attributes)
{
  $options = array();
  $replace_attributes = array();
  foreach ($attributes as $idx => $value) {
    if ($idx == $key) {
      $replace_attributes[$idx] = $value;
    } else {
      array_push($options, $value);
    }
  }
  return array($replace_attributes, $options);
}

function getRandomString_CommonHelper($length = 10, $characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
{
  return substr(str_shuffle($characters), 0, $length);
}
function getPasswordString_CommonHelper($length = 8)
{
  return getRandomString_CommonHelper($length, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_-=+;:,.?");
} //

//byte값을 알아보기 쉽게 변환
function getSizeForHuman_CommonHelper($bytes)
{
  $ext = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
  $unitCount = 0;
  for (; $bytes > 1024; $unitCount++) {
    $bytes /= 1024;
  }
  return floor($bytes) . $ext[$unitCount];
} //

//Proxy등을 통하여 Client_IP가 알수없는경우 실제사용자의 IP를 가져오기 위한것
function getClientIP_CommonHelper($clientIP = false)
{
  if (isset($_SERVER['HTTP_CLIENT_IP'])) {
    $clientIP = $_SERVER['HTTP_CLIENT_IP'];
  } else if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $clientIP = $_SERVER['HTTP_X_FORWARDED_FOR'];
  } else if (isset($_SERVER['HTTP_X_FORWARDED'])) {
    $clientIP = $_SERVER['HTTP_X_FORWARDED'];
  } else if (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
    $clientIP = $_SERVER['HTTP_FORWARDED_FOR'];
  } else if (isset($_SERVER['HTTP_FORWARDED'])) {
    $clientIP = $_SERVER['HTTP_FORWARDED'];
  } else if (isset($_SERVER['REMOTE_ADDR'])) {
    $clientIP = $_SERVER['REMOTE_ADDR'];
  }
  return $clientIP;
} //

function isDomain_CommonHelper(string $domain): bool
{
  $parttern_validation = '/((http|https)\:\/\/)?[a-zA-Z0-9\.\/\?\:@\-_=#]+\.([a-zA-Z0-9\&\.\/\?\:@\-_=#])*/';
  return preg_match("$parttern_validation", $domain);
}

function isIPAddress_CommonHelper(string $ip, $type = false): bool
{
  switch ($type) {
    case 'ipv4':
      return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
      break;
    case 'ipv6':
      return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);
      break;
    case 'all':
      return filter_var($ip, FILTER_VALIDATE_IP);
      break;
    default:
      return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE);
      break;
  }
}

function isHost_CommonHelper(string $host): bool
{
  $parttern_validation = '/[a-zA-Z0-9\.\/\?\:@\*\-_=#]/';
  return preg_match($parttern_validation, $host);
}
//(EX:192.168.1.0 -> 192.168.001.000)
function convertIPV4toCIDR_CommonHelper($cidr)
{
  $temps = explode(".", $cidr);
  return sprintf("%03d.%03d.%03d.%03d", $temps[0], $temps[1], $temps[2], $temps[3]);
} //
//(EX:192.168.001.0000 -> 192.168.1.0)
function convertCIDRtoIPV4_CommonHelper($ipv4)
{
  $temps = explode(".", $ipv4);
  return sprintf("%d.%d.%d.%d", $temps[0], $temps[1], $temps[2], $temps[3]);
} //
function isMobile_CommonHelper()
{
  // Check the server headers to see if they're mobile friendly
  if (isset($_SERVER["HTTP_X_WAP_PROFILE"])) {
    return true;
  }
  // If the http_accept header supports wap then it's a mobile too
  if (preg_match("/wap\.|\.wap/i", $_SERVER["HTTP_ACCEPT"])) {
    return true;
  }
  // Still no luck? Let's have a look at the user agent on the browser. If it contains
  // any of the following, it's probably a mobile device. Kappow!
  if (isset($_SERVER["HTTP_USER_AGENT"])) {
    $user_agents = array("midp", "j2me", "avantg", "docomo", "novarra", "palmos", "palmsource", "240x320", "opwv", "chtml", "pda", "windows\ ce", "mmp\/", "blackberry", "mib\/", "symbian", "wireless", "nokia", "hand", "mobi", "phone", "cdm", "up\.b", "audio", "SIE\-", "SEC\-", "samsung", "HTC", "mot\-", "mitsu", "sagem", "sony", "alcatel", "lg", "erics", "vx", "NEC", "philips", "mmm", "xx", "panasonic", "sharp", "wap", "sch", "rover", "pocket", "benq", "java", "pt", "pg", "vox", "amoi", "bird", "compal", "kg", "voda", "sany", "kdd", "dbt", "sendo", "sgh", "gradi", "jb", "\d\d\di", "moto");
    foreach ($user_agents as $user_string) {
      if (preg_match("/" . $user_string . "/i", $_SERVER["HTTP_USER_AGENT"])) {
        return true;
      }
    }
  }
  // Let's NOT return "mobile" if it's an iPhone, because the iPhone can render normal pages quite well.
  if (preg_match("/iphone/i", $_SERVER["HTTP_USER_AGENT"])) {
    return false;
  }
  // None of the above? Then it's probably not a mobile device.
  return false;
} //

function alert_CommonHelper(string $msg, $url = null)
{
  $msg = preg_replace("/\r/", "\\r", $msg);
  $msg = preg_replace("/\n/", "\\n", $msg);
  $msg = preg_replace("/\'/", "\'", $msg);
  $msg = preg_replace("/\"/", "\'", $msg);
  $msg = "alert(\"{$msg}\");";
  switch ($url) {
    case 'close':
      $msg .= "window.close();";
      break;
    case 'back':
      $msg .= "history.back();";
      break;
    default:
      $msg .= $url ? "location.href=\"{$url}\";" : "";
      break;
  }
  return "<script type=\"text/javascript\">{$msg}</script>";
} //

// STATUS가 use가 아닐때 option을 disabled되게 하기위함 (override form_dropdown)
function form_dropdown_test($data = '', $options = [], $selected = [], $extra = ''): string
{
  $defaults = [];
  if (is_array($data)) {
    if (isset($data['selected'])) {
      $selected = $data['selected'];
      unset($data['selected']); // select tags don't have a selected attribute
    }
    if (isset($data['options'])) {
      $options = $data['options'];
      unset($data['options']); // select tags don't use an options attribute
    }
  } else {
    $defaults = ['name' => $data];
  }

  if (!is_array($selected)) {
    $selected = [$selected];
  }
  if (!is_array($options)) {
    $options = [$options];
  }

  // If no selected state was submitted we will attempt to set it automatically
  if (empty($selected)) {
    if (is_array($data)) {
      if (isset($data['name'], $_POST[$data['name']])) {
        $selected = [$_POST[$data['name']]];
      }
    } elseif (isset($_POST[$data])) {
      $selected = [$_POST[$data]];
    }
  }

  // Standardize selected as strings, like the option keys will be
  foreach ($selected as $key => $item) {
    $selected[$key] = (string) $item;
  }

  $extra    = stringify_attributes($extra);
  $multiple = (count($selected) > 1 && stripos($extra, 'multiple') === false) ? ' multiple="multiple"' : '';
  $form     = '<select ' . rtrim(parse_form_attributes($data, $defaults)) . $extra . $multiple . ">\n";

  foreach ($options as $key => $val) {
    // Keys should always be strings for strict comparison
    $key = (string) $key;

    if (is_array($val)) {
      if (empty($val)) {
        continue;
      }

      $form .= '<optgroup label="' . $key . "\">\n";

      foreach ($val as $optgroupKey => $optgroupVal) {
        // Keys should always be strings for strict comparison
        $optgroupKey = (string) $optgroupKey;

        $sel = in_array($optgroupKey, $selected, true) ? ' selected="selected"' : '';
        $form .= '<option value="' . $optgroupKey . '"' . $sel . '>' . $optgroupVal . "</option>\n";
      }

      $form .= "</optgroup>\n";
    } else {
      $form .= '<option value="' . $key . '"'
        . (in_array($key, $selected, true) ? ' selected="selected"' : '') . '>'
        . $val . "</option>\n";
    }
  }

  return $form . "</select>\n";
}
