<?php
function p( $val, $title="" ){
  if( $title ){
    echo "==-- {$title} ==<br>".PHP_EOL;
  }
  if( is_array($val) || is_object($val) ){
    print_r($val);
  }else{
    echo $val;
  }
  if( $title ){
    echo PHP_EOL."<br>== {$title} --==<br>".PHP_EOL;
  }
}

function pp( $val, $title="" ){
  echo "<pre>";
  if( $title ){
    echo "==-- {$title} ==".PHP_EOL;
  }
  if( is_array($val) || is_object($val) ){
    print_r($val);
  }else{
    echo $val;
  }
  if( $title ){
    echo PHP_EOL."== {$title} --==".PHP_EOL;
  }
  echo "</pre>";
}

function alert($mesg, $url=""){
  echo "<script>alert('{$mesg}')</script>";
  if( $url ){
    move_page($url);
    exit;
  }
}

function move_page($url, $mesg=""){
  if( $mesg ){
    alert($mesg);
  }
  echo "<script>location.href = '{$url}';</script>";
  exit;
}

function hback($mesg=""){
  if( $mesg ){
    alert($mesg);
  }
  echo "<script>history.back();</script>";
  exit;
}

function is_mobile(){
  if(preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i',$_SERVER['HTTP_USER_AGENT'])||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i',substr($_SERVER['HTTP_USER_AGENT'],0,4))){
    return true;
  }
  return false;
}

function strpos_arr($haystack, $needle) {
  if(!is_array($needle)) $needle = array($needle);
  foreach($needle as $what) {
    if(($pos = strpos($haystack, $what))!==false) return $pos;
  }
  return false;
}

function referer_check(){//이전페이지 체크. 보안용
  $refer = preg_replace("/https?:\/\//","",$_SERVER['HTTP_REFERER']);
  $refer = substr($refer,0,strpos($refer,"/"));
  return preg_match( "/".preg_quote($_SERVER['HTTP_HOST'],"/")."/i", $refer ) === 0;
}

function getDT_datetime( $dt, $format="Y-m-d H:i:s" ){
  if( is_object($dt) && get_class($dt) == "DateTime" ){
    return $dt->format($format);
  }else if( $dt ){
    return date($format,strtotime($dt));
  }
  return "";
}
function getDT_date( $dt, $format="Y-m-d" ){
  if( is_object($dt) && get_class($dt) == "DateTime" ){
    return $dt->format($format);
  }else if( $dt ){
    return date($format,strtotime($dt));
  }
  return "";
}
function strtodate( $str, $format="Y-m-d" ){
  if( $str ){
    return date($format, strtotime($str));
  }
  return "";
}
function ndate( $seconds, $format="Y-m-d" ){
  if( (int)$seconds ){
    return date($format, $seconds);
  }
  return "";
}

function hidden_input($key, $val){
  return '<input type="hidden" name="'.$key.'" value="'.$val.'" />'.PHP_EOL;
}

function csrf_input($mode){
  $name = '_CSRF_check_'.$mode;
  $sess = uniqid($mode);
  if( !isset($_SESSION[$name]) || count($_SESSION[$name]) > 1000 ){
    $_SESSION[$name] = Array();
  }
  $_SESSION[$name][] = $sess;
  return '<input type="hidden" name="'.$name.'" class="csrf_'.$mode.'" value="'.$sess.'" />'.PHP_EOL;
}

function csrf_check($mode, $del=false){ //찾을수 없으면 true 리턴
  $name = '_CSRF_check_'.$mode;
  if( is_array($_SESSION[$name] ) ){
    $key = array_search($_REQUEST[$name],$_SESSION[$name]);
    if( hasval($key) ){
      if( $del ){
        csrf_remove($mode);
      }
      return false;
    }
  }
  return true;
}

function csrf_remove($mode){
  $name = '_CSRF_check_'.$mode;
  $key = array_search($_REQUEST[$name],$_SESSION[$name]);
  if( hasval($key) ){
    unset($_SESSION[$name][$key]);
  }
}

function image_thumb($src_img, $dest_img, $dest_w, $dest_h, $stretch="N", $force="N", $dest_ext=""){//이미지 변환 - 아이구 지겨워 재미없음..
  $src_image = @getimagesize($src_img);
  $src_w = $src_image[0];
  $src_h = $src_image[1];
  $src_ext = $src_image[2];

  $img_size = image_size($src_w, $src_h, $dest_w, $dest_h, $stretch, $force);
  $dest_w = $img_size['width'];
  $dest_h = $img_size['height'];

  switch($src_ext){
    case 1 :
      $src_image_stream = @imagecreatefromgif($src_img);
      break;
    case 2 :
      $src_image_stream = @imagecreatefromjpeg($src_img);
      break;
    case 3 :
      $src_image_stream = @imagecreatefrompng($src_img);
      break;
    case 15 :
      $src_image_stream = @imagecreatefromwbmp($src_img);
      break;
    default :
      echo "<script>alert('Not Supported File Type!!!')</script>";
      return false;
  }

//  $dest_image_stream = imagecreate($dest_w, $dest_h);   // GD 2.0 이상 지원시 이것을 사용
  $dest_image_stream = @imagecreatetruecolor($dest_w, $dest_h);
//  imagecolorallocate($dest_image_stream, 255, 255, 255);
//  @imagecopyresized($dest_image_stream, $src_image_stream, 0, 0, 0, 0, $dest_w, $dest_h, $src_w, $src_h);
  imagecopyresampled($dest_image_stream, $src_image_stream, 0, 0, 0, 0, $dest_w, $dest_h, $src_w, $src_h); //<-php4.0이후

  if( $dest_ext ){
    switch($dest_ext)  {
      case 1 :
        @imagegif($dest_image_stream,$dest_img);
        break;
      case 2 :
        @imagejpeg($dest_image_stream,$dest_img,100);
        break;
      case 3 :
        @imagepng($dest_image_stream,$dest_img);
        break;
      case 15 :
        @imagewbmp($dest_image_stream,$dest_img);
        break;
      default :
        echo "<script>alert('지원되지 않는 화일형식!!!')</script>";
        return false;
    }
  }else{
    switch($src_ext){
      case 1 :
        @imagegif($dest_image_stream,$dest_img);
        break;
      case 2 :
        @imagejpeg($dest_image_stream,$dest_img,100);
        break;
      case 3 :
        @imagepng($dest_image_stream,$dest_img);
        break;
      case 15 :
        @imagewbmp($dest_image_stream,$dest_img);
        break;
      default :
        echo "<script>alert('지원되지 않는 화일형식!!!')</script>";
        return false;
    }
  }
}

function image_cthumb($src_img, $dest_img, $dest_w, $dest_h){//이미지 크기 맞춤 이외삭제
  $src_image = @getimagesize($src_img);
  $src_w = $src_image[0];
  $src_h = $src_image[1];
  $src_ext = $src_image[2];

  if( $src_w < $dest_w || $src_h < $dest_h ){
    return image_thumb($src_img, $dest_img, $dest_w, $dest_h);
  }

  if( ($src_w - $dest_w) > ($src_h - $dest_h) ){
    $last_w = $dest_w * $src_h/$dest_h;
    $last_h = $src_h;
  }else{
    $last_w = $src_w;
    $last_h = $dest_h * $src_w/$dest_w;
  }

  switch($src_ext){
    case 1 :
      $src_image_stream = @imagecreatefromgif($src_img);
      break;
    case 2 :
      $src_image_stream = @imagecreatefromjpeg($src_img);
      break;
    case 3 :
      $src_image_stream = @imagecreatefrompng($src_img);
      break;
    case 15 :
      $src_image_stream = @imagecreatefromwbmp($src_img);
      break;
    default :
      echo "<script>alert('Not Supported File Type!!!')</script>";
      return false;
  }

  $dest_image_stream = @imagecreatetruecolor($dest_w, $dest_h);
  imagecopyresampled($dest_image_stream, $src_image_stream, 0, 0, ($src_w-$last_w)/2, ($src_h-$last_h)/2, $dest_w, $dest_h, $last_w, $last_h);
  @imagejpeg($dest_image_stream,$dest_img,100);
}

function image_size($s_wd, $s_ht, $d_wd, $d_ht, $stretch = "N", $force = "N"){//stretch 늘이기, force 대상크기로 강제맞춤(이미지변형)
  if( !$s_wd or !$s_ht or !$d_wd and !$d_ht ){
    echo "Error : image_size function parameter error";
  }

  if( $d_wd and !$d_ht ){
    $d_ht = $s_ht * $d_wd / $s_wd;
  }else if( !$d_wd and $d_ht ){
    $d_wd = $s_wd * $d_ht / $s_ht;
  }

  if( $force == "Y" ){
    if( $stretch == "Y" ){
      $size['width'] = $d_wd;
      $size['height'] = $d_ht;
    }else{
      if( $s_wd < $d_wd ){
        $size['width'] = $s_wd;
      }else{
        $size['width'] = $d_wd;
      }

      if( $s_ht < $d_ht ){
        $size['height'] = $s_ht;
      }else{
        $size['height'] = $d_ht;
      }
    }
  }else{
    if( ($s_wd/$d_wd) > ($s_ht/$d_ht) ){
      if( $stretch == "N" and $s_wd < $d_wd ){
        $d_wd = $s_wd;
      }

      $size['width'] = $d_wd;
      $size['height'] = $s_ht * $d_wd / $s_wd;
    }else{
      if( $stretch == "N" and $s_ht < $d_ht ){
        $d_ht = $s_ht;
      }

      $size['width'] = $s_wd * $d_ht / $s_ht;
      $size['height'] = $d_ht;
    }
  }

  return $size;
}

function file_remove($filepath, $unremove=""){
  $glob = glob($filepath);
  $rst = true;
  foreach( $glob as $filename ) {
    if( !$unremove || $filename != $unremove ){
      $rst = $rst && @unlink($filename);
    }
  }
  return $rst;
}

function oldfile_remove($filepath, $day=1, $unremove=""){
  $glob = glob($filepath);
  $rmday = $day * 86400;
  $rst = true;
  foreach( $glob as $filename ) {
    if( fileatime($filename) < time()-$rmday && ( !$unremove || $filename != $unremove && substr(strrchr($filename,'/'),1) != $unremove ) ){
      $rst = $rst && @unlink($filename);
    }
  }
  return $rst;
}

function get_ip(){
  switch(true){
    case (!empty($_SERVER['HTTP_X_REAL_IP'])) :
      $real_ip = $_SERVER['HTTP_X_REAL_IP']; break;
    case (!empty($_SERVER['HTTP_CLIENT_IP'])) :
      $real_ip = $_SERVER['HTTP_CLIENT_IP']; break;
    case (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) :
      $real_ip = $_SERVER['HTTP_X_FORWARDED_FOR']; break;
    default :
      $real_ip = $_SERVER['REMOTE_ADDR'];
  }
  $real_ip = explode(":",$real_ip);
  return $real_ip[0];
}

function getRefRow($fields=array()){ //HTTP_REFERER 를 배열로 변경, $fields가 존재하면 그부분 제외
  $query= explode("?",$_SERVER['HTTP_REFERER']);
  $query= explode("&",$query[1]);
  $qrow = Array();
  if( count($query) > 0 ){
    foreach( $query as $val ){
      $temp = explode("=",$val);
      if( !in_array($temp[0], $fields) ){
        $qrow[$temp[0]] = $temp[1];
      }
    }
  }
  return $qrow;
}

function getQuery($qrow, $addrow=array()){
  if( count($addrow) > 0 ){
    $qrow = array_merge($qrow, $addrow);
  }
  $query = array();
  if( count($qrow) > 0 ){
    foreach( $qrow as $key => $val ){
      if( hasval($val) ){
        $query[] = "{$key}={$val}";
      }
    }
  }
  return implode("&", $query);
}

function base64url_encode($data){
  $base64 = base64_encode($data);

  if ($base64 === false) {
    return false;
  }
  $url = strtr($base64, '+/', '-_');
  return rtrim($url, '=');
}

function base64url_decode($data, $strict = false){
  $b64 = strtr($data, '-_', '+/');
  return base64_decode($b64, $strict);
}

function cval($key){
  if( isset($$key) ){
    return $$key;
  }
  return "";
}

function crowval($row, $key, $dval=""){
  if( isset($row[$key]) ){
    return $row[$key];
  }
  return $dval;
}

function hasval( $val ){
  if( isset($val) && ($val || $val === 0 || $val === "0") ){
    return true;
  }
  return false;
}

function array_merge_static( $row1, $row2 ){
  foreach( (array)$row2 as $k => $v ){
    $row1[$k] = $v;
  }
  return $row1;
}

/** getSelectOptions
 * @param $row : 선택값
 * @param string $emptv : 빈값추가
 * @param array $exck : 선택값중 제외(기준키)
 * @param array $excv : 선택값중 제외(기준값)
 * @return string
 */
function getSelectOptions( $row, $emptv="", $defval="", $exck=array(), $excv=array() ){
  $reopt = array();
  if( $emptv ){
    $reopt[] = "<option value=''>{$emptv}</option>";
  }
  foreach( (array)$row as $key => $val ){
    if( in_array($key, (array)$exck) ) continue;
    if( in_array($val, (array)$excv) ) continue;
    $selected = false;
    if( $defval ){
      if( is_array($defval) && in_array( $key, $defval ) ){
        $selected = true;
      }else if( $key == $defval ){
        $selected = true;
      }
    }
    $reopt[] = "<option value='{$key}'".($selected?" selected":"").">{$val}</option>";
  }
  return implode(PHP_EOL,$reopt);
}
function getSelectOptionsExp( $row, $emptv="", $defval="", $exck=array(), $excv=array() ){
  $reopt = array();
  if( $emptv ){
    $reopt[] = "<option value=''>{$emptv}</option>";
  }
  foreach( (array)$row as $key => $val ){
    if( in_array($key, (array)$exck) ) continue;
    if( in_array($val[0], (array)$excv) ) continue;
    $selected = false;
    if( $defval ){
      if( is_array($defval) && in_array( $key, $defval ) ){
        $selected = true;
      }else if( $key == $defval ){
        $selected = true;
      }
    }
    $reopt[] = "<option value='{$key}'".($selected?" selected":"").">{$val[1]} ({$val[0]})</option>";
  }
  return implode(PHP_EOL,$reopt);
}

/** getCheckboxes
 * @param $name : name Attr
 * @param $vrow : 선택값
 * @param string $defval : default 값
 * @param string $cls1 : 클래스1 label 용
 * @param string $cls2 : 클래스2 input 용
 * @return string
 */
function getCheckboxes( $name, $vrow, $defval="", $cls1="", $cls2="" ){
  $reopt = array();
  $checked = false;
  foreach( (array)$vrow as $key => $val ){
    if( $defval ){
      if( is_array($defval) && in_array( $key, $defval ) ){
        $checked = true;
      }else if( $key == $defval ){
        $checked = true;
      }
    }
    //$reopt[] = "<label".(($cls1)?" class='{$cls1}'":"")."><input type='checkbox' name='{$name}' value='{$key}' data-defval='".json_encode($defval)."' ".(($cls2)?" class='{$cls2}'":"")."> {$val}</label>";
    $reopt[] = "<label".(($cls1)?" class='{$cls1}'":"")."><input type='checkbox' name='{$name}' value='{$key}' ".($checked?" checked":"")." ".(($cls2)?" class='{$cls2}'":"")."> {$val}</label>";
  }
  return implode(PHP_EOL,$reopt);
}


/** getRadios
 * @param $name : name Attr
 * @param $vrow : 선택값
 * @param string $defval : default 값
 * @param string $cls1 : 클래스1 label 용
 * @param string $cls2 : 클래스2 input 용
 * @return string
 */
function getRadios( $name, $vrow, $defval='', $cls1='', $cls2='' ){
  $reopt = array();
  foreach( (array)$vrow as $key => $val ){
    if( is_object($defval) || is_array($defval) ){
      $defval = json_encode($defval);
    }
    //$reopt[] = "<label".(($cls1)?" class='{$cls1}'":"")."><input type='radio' name='{$name}' value='{$key}' data-defval='".$defval."' ".(($cls2)?" class='{$cls2}'":"")."> {$val}</label>";
    $reopt[] = "<label".(($cls1)?" class='{$cls1}'":"")."><input type='radio' name='{$name}' value='{$key}' ". (($defval == $key)?"checked":"") ." ".(($cls2)?" class='{$cls2}'":"")."> {$val}</label>";
  }
  return implode(PHP_EOL,$reopt);
}

function chkValiMail( $email ){
  if( !$email || preg_match("/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/", $email) ){
    return true;
  }
  return false;
}

function chkValiDomain( $domain ){
  if( !$domain || preg_match("/(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]/", $domain) ){
    return true;
  }
  return false;
}

function chkValiUrl( $url ){
  if( !$url || preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i", $url) ){
    return true;
  }
  return false;
}

function chkValiPhone( $phone ){
  if( !$phone || preg_match("/^\d{2,3}-\d{3,4}-\d{4}$/", $phone) ){
    return true;
  }
  return false;
}

function chkValiDate( $date ){
  if( !$date || preg_match("/^(19|20)\d\d([-])(0[1-9]|1[012])\2(0[1-9]|[12][0-9]|3[01])$/", $date) ){
    return true;
  }
  return false;
}

function chkValiAaSpNum( $str ){
  if( !$str || preg_match("/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]$/im", $str) ){
    return true;
  }
  return false;
}

function chkValiAaSp( $str ){
  if( !$str || preg_match("/^(?=.*[a-z])(?=.*[A-Z])(?=.*[@$!%*?&])[A-Za-z@$!%*?&]$/im", $str) ){
    return true;
  }
  return false;
}

function chkValiAaNum( $str ){
  if( !$str || preg_match("/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[A-Za-z\d]$/im", $str) ){
    return true;
  }
  return false;
}

function chkValiSpNum( $str ){
  if( !$str || preg_match("/^(?=.*[a-z])(?=.*\d)(?=.*[@$!%*?&])[a-z\d@$!%*?&]$/im", $str) ){
    return true;
  }
  return false;
}

function addzero($num, $dan){
  return str_pad($num,$dan,'0',STR_PAD_LEFT);
}

function _notAuth( $auth, &$rval="", $cate_id="", $msg="" ){ //단축형... 귀찮아서
  global $retval;
  if( !$rval ) $rval = &$retval['mesg'];
  if( !$GLOBALS['_Auth_']['menuObj']->hasMenuAuth( $auth, $cate_id ) ){
    $rval = $msg?:$GLOBALS['_Auth_']['deny_mesg'];
    return true;
  }
  return false;
}

function file_size($bytes, $precision=2){
  $unit = ["B", "KB", "MB", "GB"];
  $exp = floor(log($bytes, 1024)) ?: 0;
  return round($bytes / (pow(1024, $exp)), $precision).$unit[$exp];
}

function get_encode_base64_str($en_word, $charset="UTF-8"){
  return "=?" . strtolower($charset) . "?B?" . base64_encode($en_word) . "?=";
}


/*
 * javascript : btoa(encodeURIComponent(JSON.stringify(data))) 의 역, 배열처리
 * */
function decode_Post($pval){
  return json_decode(urldecode(base64_decode($pval)),true);
}

function curl_request( $access_url, $query="", $method="GET", $headers="", $options="", $cookie="", $retm="body" ){
  if( is_array($query) ){
    $strquery = http_build_query($query);
  }else{
    $strquery = $query;
  }
  $ch = curl_init();
  switch( strtoupper($method) ){
    case "POST" :
      curl_setopt( $ch, CURLOPT_POST, 1);
      curl_setopt( $ch, CURLOPT_POSTFIELDS, $strquery);
    break;

    case "GET" :
      if( $strquery ){
        $access_url = $access_url."?".$strquery;
      }
    break;

    case "PUT" :
      curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, "PUT");
      curl_setopt( $ch, CURLOPT_POSTFIELDS, $strquery);
    break;

    case "DELETE" :
      curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, "DELETE");
      curl_setopt( $ch, CURLOPT_POSTFIELDS, $strquery);
    break;

    case "RAW" :
      if( is_array($query) ){
        $strquery = json_encode( $query );
      };
      curl_setopt( $ch, CURLOPT_POST, 1);
      curl_setopt( $ch, CURLOPT_POSTFIELDS, $strquery);

      if( $headers ){
        if( !is_array($headers) ){
          $headers = Array($headers);
        }
      }else{
        $headers = array();
      }
      $headers[] = 'Content-Type: application/json';
    break;
  }

  if( $headers ) { //(e.g., array("fruit: apple", "colour: red")
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  }

  if( $options ) { //(e.g., array("fruit"=>"apple", "colour"=>"red")
    curl_setopt_array($ch, $options);
  }

  curl_setopt( $ch, CURLOPT_URL, $access_url);
  curl_setopt( $ch, CURLOPT_USERAGENT, "Kuls Api" );
  curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
  curl_setopt( $ch, CURLOPT_HEADER, 1);
  curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);

  if( $cookie ){ //(e.g., "fruit=apple; colour=red")
    curl_setopt( $ch, CURLOPT_COOKIE, $cookie);
  }

  $curl_result = curl_exec( $ch );
  curl_close( $ch );

  list( $header, $response ) = explode("\r\n\r\n", $curl_result, 2);
  $header = get_http_header_as_array($header);

  switch( $retm ){
    case "all":
      return Array(
        "header" => $header,
        "response" => $response,
      );
    case "header":
      return $header;
    case "body":
    default:
      return $response;
  }
}

function get_http_header_as_array($rawheader){
  $header_array = array();
  $header_rows = explode("\n",$rawheader);
  for($i=0;$i<count($header_rows);$i++){
    $fields = explode(":",$header_rows[$i]);

    if($i != 0 && !isset($fields[1])){//carriage return bug fix.
      if(substr($fields[0], 0, 1) == "\t"){
        end($header_array);
        $header_array[key($header_array)] .= "\r\n\t".trim($fields[0]);
      }else{
        end($header_array);
        $header_array[key($header_array)] .= trim($fields[0]);
      }
    }else{
      $field_title = trim($fields[0]);
      if (!isset($header_array[$field_title])){
        $header_array[$field_title]=trim($fields[1]);
      }else if(is_array($header_array[$field_title])){
        $header_array[$field_title] = array_merge($header_array[$fields[0]], array(trim($fields[1])));
      }else{
        $header_array[$field_title] = array_merge(array($header_array[$fields[0]]), array(trim($fields[1])));
      }
    }
  }
  return $header_array;
}

function Spcurl_response($url, $query, $method) {
  return curl_request( $url, $query, $method, "", "", "" );
}

function Spcurl_header($url, $query, $method) {
  return curl_request( $url, $query, $method, "", "", "", "header" );
}

function Spcurl($url, $query, $method) {
  return curl_request( $url, $query, $method, "", "", "", "all" );
}

//테스트결과 저정/확인용 함수 
function chkToFile( $filename, $contents ){
  $fp = fopen(_UP_PATH_."/{$filename}","a+");
  fwrite($fp, $contents.PHP_EOL);
  fclose($fp);
}