<?php
//글자 자르기(utf8)
function text_cut($str, $size) {
	$substr = substr( $str, 0, $size * 2 );
	$multi_size = preg_match_all( '/[\\x80-\\xff]/', $substr, $multi_chars );

	if ( $multi_size > 0 )
		$size = $size + intval( $multi_size / 3 ) - 1;

	if ( strlen( $str ) > $size )
	{
		$str = substr( $str, 0, $size );
		$str = preg_replace( '/(([\\x80-\\xff]{3})*?)([\\x80-\\xff]{0,2})$/', '$1', $str );
		$str .= '...';
	}

	return $str;
}

function dateDiff($strDate1, $strDate2){
	$timeDiff = strtotime($strDate2) - strtotime($strDate1);	
	return number_format($timeDiff / 86400);
}

//캘린더 날짜 가져오기
function getDiarySet($year, $month, $day){
  $diary = array();

  //setlocale(LC_ALL, "ko_KR.UTF-8");
  $diary[to_weekday_str] = strftime("%a", mktime(0,0,0, $month, $day, $year));    // 한글로 요일 출력.

  $diary[prev_month] = date("Y-m-d",strtotime("-1 Month", mktime(0,0,0,$month,1,$year)));
  $diary[this_month] = date("Y-m-d",mktime(0,0,0,$month,1,$year));
  $diary[next_month] = date("Y-m-d",strtotime("+1 Month", mktime(0,0,0,$month,1,$year)));

  $diary[first] = 1;                // 1일.
  $diary[last] = date('t', mktime(0,0,0, $month, 1, $year));  // 말일.

  $diary[s_weekday] = date('w', mktime(0,0,0, $month, 1, $year));             // 1일의 요일.숫자.
  $diary[e_weekday] = date('w', mktime(0,0,0, $month, $diary[last], $year));  // 말일의 요일.숫자.

  $diary[first_before] = date('Y-m-d', mktime(0,0,0, $month, $diary[first] - $diary[s_weekday], $year));     // 1일 이전의 날짜.
  $diary[last_after] = date('Y-m-d', mktime(0,0,0, $month, $diary[last] + (6 - $diary[e_weekday]), $year));  // 말일 이후의 날짜.

	//이주시작(월) 끝(금), 다음주시작(월) 끝(금)
	$todayN = date('N', mktime(0,0,0, $month, $day, $year));
	$this_week_mon_time = mktime(0,0,0, $month, $day, $year) - (($todayN-1) * 24 * 3600);
	$diary[last_week_fri] = date('Y-m-d',$this_week_mon_time - (3 * 24 * 3600));
	$diary[this_week_sun] = date('Y-m-d',$this_week_mon_time - (24 * 3600));
	$diary[this_week_mon] = date('Y-m-d',$this_week_mon_time);
	$diary[this_week_wed] = date('Y-m-d',$this_week_mon_time + (3 * 24 * 3600));
	$diary[this_week_fri] = date('Y-m-d',$this_week_mon_time + (4 * 24 * 3600));
	$diary[next_week_sun] = date('Y-m-d',$this_week_mon_time + (6 * 24 * 3600));
	$diary[next_week_mon] = date('Y-m-d',$this_week_mon_time + (7 * 24 * 3600));
	$diary[next_week_wed] = date('Y-m-d',$this_week_mon_time + (10 * 24 * 3600));
	$diary[next_week_fri] = date('Y-m-d',$this_week_mon_time + (11 * 24 * 3600));
	

	// 1일 이전의 날짜 부터, 말일 이후의 날짜 까지를 배열에 넣기.
	for($i=0;;$i++){
		for($j=0;$j<=6;$j++){
      $diary[box][$i][$j] = date('Y-m-d', strtotime($diary[first_before]) + ($i*7+$j) * 24*3600);
		}

		if($diary[box][$i][6]==$diary[last_after])
			break;
	}

  return $diary;
}


/**
 * Makes directory and returns BOOL(TRUE) if exists OR made.
 *
 * @param  $path Path name
 * @return bool
 */
function rmkdir($path, $mode = 0755) {
    $path = rtrim(preg_replace(array("/\\\\/", "/\/{2,}/"), "/", $path), "/");
    $e = explode("/", ltrim($path, "/"));
    if(substr($path, 0, 1) == "/") {
        $e[0] = "/".$e[0];
    }
    $c = count($e);
    $cp = $e[0];
    for($i = 1; $i < $c; $i++) {
        if(!is_dir($cp) && !@mkdir($cp, $mode)) {
            return false;
        }
        $cp .= "/".$e[$i];
    }
    return @mkdir($path, $mode);
}

/* 지정된 디렉토리 및의 모든 데이터 삭제*/
function rrmdir($f) {
    if (is_dir($f)) {
        foreach(glob($f.'/*') as $sf) {
            if (is_dir($sf) && !is_link($sf)) {
                rrmdir($sf);
            } else {
                @unlink($sf);
            }
            @rmdir($f);
        }
    }
}

//파일 바이트수 개산
function getByte($intSize){
  if( strlen($intSize) < 7 ) {
	 $filesize = sprintf("%0.1f KB", $intSize/1024);
  }else{
	 $filesize = sprintf("%0.1f MB", $intSize/1024000);
  }

  return $filesize;
}

//썸네일 만들기
function MakeThum($src, $dst, $size){
	$quality = '100';    //-- jpg 퀄리티 
	//$size = '200';    //-- 줄일 크기 pixel (너비, 또는 높이에 적용) 
	//$ratio = '4:3';        //-- 이미지를 4:3 비율로 잘라냄 
	$ratio = 'false';        //-- 원본 이미지비율을 유지 

	$get_size = _getimagesize($src, $size, $ratio); 
	$result = resize_image($dst, $src, $get_size, $quality, $ratio); 

	if($result === TRUE) 
		return true;
	else 
		return false; 
}

// $destination : 이미지가 저장될 경로 
// $departure : 원본 이미지 경로 
// $size : _getimagesize() 의 return 값을 넣을 것 
// $quality : JPG 퀄리티 
// $ratio : 비율 강제설정 

function resize_image($destination, $departure, $size, $quality='80', $ratio='false'){ 

    if($size[2] == 1)    //-- GIF 
        $src = imageCreateFromGIF($departure); 
    elseif($size[2] == 2) //-- JPG 
        $src = imageCreateFromJPEG($departure); 
    else    //-- $size[2] == 3, PNG 
        $src = imageCreateFromPNG($departure); 

    $dst = imagecreatetruecolor($size['w'], $size['h']); 


    $dstX = 0; 
    $dstY = 0; 
    $dstW = $size['w']; 
    $dstH = $size['h']; 

    if($ratio != 'false' && $size['w']/$size['h'] <= $size[0]/$size[1]){ 
        $srcX = ceil(($size[0]-$size[1]*($size['w']/$size['h']))/2); 
        $srcY = 0; 
        $srcW = $size[1]*($size['w']/$size['h']); 
        $srcH = $size[1]; 
    }elseif($ratio != 'false'){ 
        $srcX = 0; 
        $srcY = ceil(($size[1]-$size[0]*($size['h']/$size['w']))/2); 
        $srcW = $size[0]; 
        $srcH = $size[0]*($size['h']/$size['w']); 
    }else{ 
        $srcX = 0; 
        $srcY = 0; 
        $srcW = $size[0]; 
        $srcH = $size[1]; 
    } 

    @imagecopyresampled($dst, $src, $dstX, $dstY, $srcX, $srcY, $dstW, $dstH, $srcW, $srcH); 
    @imagejpeg($dst, $destination, $quality); 
    @imagedestroy($src); 
    @imagedestroy($dst); 

    return TRUE; 
} 

// $img : 원본이미지 
// $m : 목표크기 pixel 
// $ratio : 비율 강제설정 
function _getimagesize($img, $m, $ratio='false'){ 

    $v = @getImageSize($img); 

    if($v === FALSE || $v[2] < 1 || $v[2] > 3) 
        return FALSE; 

    $m = intval($m); 

    if($m > $v[0] && $m > $v[1]) 
        return array_merge($v, array("w"=>$v[0], "h"=>$v[1])); 

    if($ratio != 'false'){ 
        $xy = explode(':',$ratio); 
        return array_merge($v, array("w"=>$m, "h"=>ceil($m*intval(trim($xy[1]))/intval(trim($xy[0]))))); 
    }elseif($v[0] > $v[1]){ 
        $t = $v[0]/$m; 
        $s = floor($v[1]/$t); 
        $m = ($m > 0) ? $m : 1; 
        $s = ($s > 0) ? $s : 1; 
        return array_merge($v, array("w"=>$m, "h"=>$s)); 
    } else { 
        $t = $v[1]/intval($m); 
        $s = floor($v[0]/$t); 
        $m = ($m > 0) ? $m : 1; 
        $s = ($s > 0) ? $s : 1; 
        return array_merge($v, array("w"=>$s, "h"=>$m)); 
    } 
}

//  메일보내기
function mailing($Mail_Name,$Mail_From,$Mail_To,$Mail_Subject,$Mail_Contents){
    $Mail_Header = "from:$Mail_Name<$Mail_From>\nreply-to:$Mail_Name<$Mail_From>\n";
    $Mail_Header .= "Content-Type: text/html;charset=euc_kr";
    mail($Mail_To,$Mail_Subject,$Mail_Contents,$Mail_Header);
} // end func


/** 
 * 파일 다운로드 
 * @param $download_file 다운로드 할 파일경로 
 * @param $file_org_name 다운로드 파일 이름 
 */ 
function fileDownload($download_file, $file_org_name='') { 
	$copy_file_name = substr($download_file, strrpos($download_file, '/')+1); 
	$file_name = ($file_org_name) ? $file_org_name : $copy_file_name; 
	if(file_exists($download_file) == true) { 
		if (preg_match("(MSIE 5.5|MSIE 6.0)", $HTTP_USER_AGENT)) {
            Header("Content-type:application/octet-stream");
            Header("Content-Length:".filesize($download_file));
            Header("Content-Disposition:attachment;filename=".$file_name."");
            Header("Content-Transfer-Encoding:binary");
            Header("Pragma:no-cache");
            Header("Expires:0");
        } else {
            Header("Content-type:file/unknown");
            Header("Content-Length:".filesize($download_file));
            Header("Content-Disposition:attachment; filename=".$file_name."");
            Header("Content-Description:PHP3 Generated Data");
            Header("Pragma: no-cache");
            Header("Expires: 0");
        }

        if (is_file($download_file)) {
            $fp = fopen($download_file, "rb");
            if (!fpassthru($fp)) fclose($fp);
            clearstatcache();
        }
	} else { 

		jsMsg($download_file . '해당 파일이 없습니다.');
		selfClose();
	} 
}



function makeincFiles($boardid, $limit){
	if($boardid){
		if(!$limit){
			$limit = 5;
		}
		$arrList = getBoardLast($boardid, $limit);
		$makeinc_path = $_SERVER["DOCUMENT_ROOT"] . "/bbs/makeinc/";
		$nowfile = $makeinc_path . $boardid . ".inc.php";
		$newfile = $makeinc_path . $boardid . ".inc.php.new";

		if(!file_exists($nowfile)){
			$fp = fopen($nowfile, 'w');
			fclose($fp);
		}
		if(copy($nowfile, $newfile)){
			$fp = fopen($newfile, 'w');
			if($arrList["total"] > 0){
				fwrite($fp, "<?php $makeinc_".$boardid." = ");
				for($i=0; $i<$arrList["total"];$i++){
					fwrite($fp, $arrList["list"][$i][idx]);
				}
				fwrite($fp, "?>");
			}else{
				fwrite($fp, "<?php $makeinc_".$boardid." = NULL;?>");
			}
			fclose($fp);
		}

	}else{
		return false;
	}
}

/**  * Get Video ID  * 유투브 주소에서 Video ID를 추출합니다.  *  * @access  public  * @param   string  * @return  string  */
if ( ! function_exists( 'get_video_id' ) ) {    
	function get_video_id( $str )     {         
		if( substr( $str, 0, 4 ) == 'http' )         { 
			if( strpos( $str, 'youtu.be' ) )             {
				$id = explode( '/', str_replace("https://youtu.be","",$str));
				$id2 = explode( '?', $id[1]);
				return $id2[0];             
			}else if( strpos( $str, '/embed/' ) )             {
				$id = explode( '/embed/', $str);
				return $id[1];    
				//return array_pop( explode( '/', $str ) );             
			}else if( strpos( $str, '/v/' ) )             {                 
				$id = explode( '/', $str);
				return $id[1];    
				//return array_pop( explode( '/', $str ) );            
			}else{
				$id = explode( '?', $str);
				$params = explode( '&', $id[1] ); 
				foreach( $params as $data )                 {
					$arr = explode( '=', $data );                     
					//echo $data;
					if( $arr[0] == 'v' )                     {
						return $arr[1];                     
					}
				}
			}
		}else{
			return $str;
		}
		return '';
	}
}
/**  * Get Thumbnail URL  * 썸네일 주소를 가져옵니다. 기본값은 default 입니다.  *  * @param $url_or_id  * @param $type  * @return string  */
if ( ! function_exists( 'get_yt_thumb' ) ) {
	function get_yt_thumb( $url_or_id, $type )     {
		switch( $type )         {
			case '0' :
			return '//img.youtube.com/vi/'.get_video_id( $url_or_id ).'/0.jpg';
			break;
			case '1' :
			return '//img.youtube.com/vi/'.get_video_id( $url_or_id ).'/1.jpg';
			break;
			case '2' :
			return '//img.youtube.com/vi/'.get_video_id( $url_or_id ).'/2.jpg';
			break;
			case '3' :                 
			return '//img.youtube.com/vi/'.get_video_id( $url_or_id ).'/3.jpg';
			break;
			case 'hq' :
			return '//img.youtube.com/vi/'.get_video_id( $url_or_id ).'/hqdefault.jpg';
			break;
			case 'mq' :
			return '//img.youtube.com/vi/'.get_video_id( $url_or_id ).'/mqdefault.jpg';
			break;
			case 'sd' :
			return '//img.youtube.com/vi/'.get_video_id( $url_or_id ).'/sddefault.jpg';
			break;
			case 'maxres' :
			return '//img.youtube.com/vi/'.get_video_id( $url_or_id ).'/maxresdefault.jpg';
			break;
			default :
			return '//img.youtube.com/vi/'.get_video_id( $url_or_id ).'/default.jpg';
			}
		}
	}
	/**  * Get Thumbnail URL 0  *  * @param $url_or_id  * @return string  */
	if ( ! function_exists( 'get_yt_thumb_0' ) ) {     
		function get_yt_thumb_0( $url_or_id )     {
			return get_yt_thumb( $url_or_id, '0' );     
		}
	}
	/**  * Get Thumbnail URL 1  *  * @param $url_or_id  * @return string  */
	if ( ! function_exists( 'get_yt_thumb_1' ) ) {     function get_yt_thumb_1( $url_or_id )     {         return get_yt_thumb( $url_or_id, '1' );     } }   
	/**  * Get Thumbnail URL 2  *  * @param $url_or_id  * @return string  */
	if ( ! function_exists( 'get_yt_thumb_2' ) ) {     function get_yt_thumb_2( $url_or_id )     {         return get_yt_thumb( $url_or_id, '2' );     } }   
	/**  * Get Thumbnail URL 3  *  * @param $url_or_id  * @return string  */
	if ( ! function_exists( 'get_yt_thumb_3' ) ) {     function get_yt_thumb_3( $url_or_id )     {         return get_yt_thumb( $url_or_id, '3' );     } }   
	/**  * Get Thumbnail URL HQ  *  * @param $url_or_id  * @return string  */
	if ( ! function_exists( 'get_yt_thumb_hq' ) ) {     function get_yt_thumb_hq( $url_or_id )     {         return get_yt_thumb( $url_or_id, 'hq' );     } }   
	/**  * Get Thumbnail URL MQ  *  * @param $url_or_id  * @return string  */
	if ( ! function_exists( 'get_yt_thumb_mq' ) ) {     function get_yt_thumb_mq( $url_or_id )     {         return get_yt_thumb( $url_or_id, 'mq' );     } }   
	/**  * Get Thumbnail URL SD  *  * @param $url_or_id  * @return string  */if ( ! function_exists( 'get_yt_thumb_sd' ) ) {
		function get_yt_thumb_sd( $url_or_id )     { 
			return get_yt_thumb( $url_or_id, 'sd' );     
		}
	}   
	/**  * Get Thumbnail URL Max Resolution  *  * @param $url_or_id  * @return string  */
	if ( ! function_exists( 'get_yt_thumb_maxres' ) ) {     function get_yt_thumb_maxres( $url_or_id )     {         return get_yt_thumb( $url_or_id, 'maxres' );     } }
?>