<?php
if (!defined('_GNUBOARD_')) exit; // 개별 페이지 접근 불가

//Check AMINA Skin
function is_amina($skin) {
	$is_amina = 'amina-v3';
	return preg_match('/'.$is_amina.'/i', $skin);
}

function amina_mobile() {
	return preg_match('/'.G4_MOBILE_AGENT.'/i', $_SERVER['HTTP_USER_AGENT']);
}

// mysql_real_escape_string 의 alias 기능을 한다.
function amina_trim($field) {

	if ($field) return mysql_real_escape_string(@trim($field));

}

//Load AMINA Skin Setting
function load_amina_setting($amina, $bo_table, $bo_skin, $m_skin, $sca) {
	global $g4;

	$set = array();
	$func = array();
	$skin = array();

	if(AMINA == "g4s") { //g4s
		if(G4_IS_MOBILE && is_amina($m_skin)) { //mobile
			$func = sql_fetch(" select * from {$g4['amina']} where bo_table='$bo_table' ", false);
			if($sca) {
				$skin = sql_fetch(" select * from {$g4['amina_skin']} where bo_table='$bo_table' and ((skin_type = '2' and sca = '') or (skin_type = '3' and sca = '$sca')) order by skin_type desc limit 1", false);
			} else {
				$skin = sql_fetch(" select * from {$g4['amina_skin']} where bo_table='$bo_table' and skin_type = '2' and sca = '' ", false);
			}
			if(!$skin && is_amina($bo_skin)) { //pc
				if($sca) {
					$skin = sql_fetch(" select * from {$g4['amina_skin']} where bo_table='$bo_table' and ((skin_type = '0' and sca = '') or (skin_type = '1' and sca = '$sca')) order by skin_type desc limit 1", false);
				} else {
					$skin = sql_fetch(" select * from {$g4['amina_skin']} where bo_table='$bo_table' and skin_type = '0' and sca = '' ", false);
				}
			}
		} else {
			if(is_amina($bo_skin)) { //pc
				$func = sql_fetch(" select * from {$g4['amina']} where bo_table='$bo_table' ", false);
				if($sca) {
					$skin = sql_fetch(" select * from {$g4['amina_skin']} where bo_table='$bo_table' and ((skin_type = '0' and sca = '') or (skin_type = '1' and sca = '$sca')) order by skin_type desc limit 1", false);
				} else {
					$skin = sql_fetch(" select * from {$g4['amina_skin']} where bo_table='$bo_table' and skin_type = '0' and sca = '' ", false);
				}
			}
		}
	} else { //g4
		if(is_amina($bo_skin)) {
			$func = sql_fetch(" select * from {$g4['amina']} where bo_table='$bo_table' ", false);
			if(G4_IS_MOBILE) { //mobile
				if($sca) {
					$skin = sql_fetch(" select * from {$g4['amina_skin']} where bo_table='$bo_table' and ((skin_type = '2' and sca = '') or (skin_type = '3' and sca = '$sca')) order by skin_type desc limit 1", false);
				} else {
					$skin = sql_fetch(" select * from {$g4['amina_skin']} where bo_table='$bo_table' and skin_type = '2' and sca = '' ", false);
				}
			} 
			if(!$skin) { //pc
				if($sca) {
					$skin = sql_fetch(" select * from {$g4['amina_skin']} where bo_table='$bo_table' and ((skin_type = '0' and sca = '') or (skin_type = '1' and sca = '$sca')) order by skin_type desc limit 1", false);
				} else {
					$skin = sql_fetch(" select * from {$g4['amina_skin']} where bo_table='$bo_table' and skin_type = '0' and sca = '' ", false);
				}
			}
		} else {
			if(G4_IS_MOBILE) { //mobile
				if($sca) {
					$skin = sql_fetch(" select * from {$g4['amina_skin']} where bo_table='$bo_table' and ((skin_type = '2' and sca = '') or (skin_type = '3' and sca = '$sca')) order by skin_type desc limit 1", false);
				} else {
					$skin = sql_fetch(" select * from {$g4['amina_skin']} where bo_table='$bo_table' and skin_type = '2' and sca = '' ", false);
				}
			}
		}
	}

	//Setting = Funcition + Skin Setting
	if($func && $skin) {
		$set = array_merge($func, $skin);
	} else if($func && !$skin) {
		$set = $func;
	} else if(!$func && $skin) {
		$set = $skin;
	}

	//Setting = Default + Funcition + Skin Setting
	if($amina && $set) {
		$set = array_merge($amina, $set);
	} else if($amina && !$set) {
		$set = $amina;
	} 

	return $set;
}

//Write Option Set for wr_10
function amina_array_write($wr_10) {
	$set = array();
	list($set['photo'], $set['img_location'], $set['img_space'], $set['post_main'], $set['post_good'], $set['post_rss'], $set['video'], $set['file'], $set['subj_b'], $set['subj_i'], $set['subj_s'], $set['subj_color'], $set['chk_tag'], $set['chk_poll'], $set['poll_location'], $set['daum_view']) = explode("|", $wr_10);
	return $set;
}

//Map Option Set for wr_2
function amina_array_map($wr_2) {
	$set = array();
	list($set['map_width'], $set['map_height'], $set['map_lat'], $set['map_lng'], $set['map_zoom']) = explode("|", $wr_2);
	return $set;
}

//Video Option Set for wr_6
function amina_array_video($wr_6) {
	$set = array();
	list($set['movie_url'], $set['movie_w'], $set['movie_h'], $set['movie_auto'], $set['movie_align'], $set['movie_img'], $set['movie_file']) = explode("|", $wr_6);
	$set['movie_info'] = $set['movie_url'].'|width='.$set['movie_w'].' height='.$set['movie_h'].' auto='.$set['movie_auto'].' img='.$set['movie_img'].' file='.$set['movie_file'];
	return $set;
}

//Icon Option Set for wr_5
function amina_array_icon($wr_5) {
	$set = array();
	list($set['level'], $set['mobile'], $set['post_icon'], $set['choice'], $set['choice_point'], $set['choice_mb'], $set['post_cool'], $set['post_icon_mb'], $set['po_view_point'], $set['po_down_point'], $set['po_img_cnt']) = explode("|", $wr_5);
	return $set;
}

//Icon Option Set for wr_7
function amina_array_tag($wr_7) {
	$set = array();
	list($set['score'], $set['people'], $set['tag_sop'], $set['related_tag']) = explode("|", $wr_7);
	return $set;
}

//Star Score
function amina_array_star($wr_7){
	$set = array();
	list($set['score'], $set['people']) = explode("|", $wr_7);
	return $set;
}

//Linked Tab Info
function amina_array_linked($linked) {

	$tab = array();
	$item = array();
	$set = array();

	$tab = explode("\n", trim($linked));
	for($i=0; $i < count($tab); $i++) {
		list($item['linked_type'], $item['linked_id'], $item['linked_name'], $item['linked_view'], $item['linked_post'], $item['linked_row'], $item['linked_opt']) = explode("|", $tab[$i]);
		$set[$i] = $item;
	}

	return $set;
}

//Sort Array
function amina_sort($Ary, $field, $reverse=false) {

	foreach($Ary as $res)
		$sortArr[] = $res[$field];

	($reverse) ? array_multisort($sortArr, SORT_DESC, $Ary) : array_multisort($sortArr, SORT_ASC, $Ary);

	return $Ary;
}

//Exchage Value
function amina_query($str) { 

	$querystring = array();
	$query = array();

	//공백(" ")으로 변수분리
	$querystring = explode(" ", $str);
	foreach($querystring as $q) {
		list($k, $v) = explode("=", $q, 2);
		$query[$k] = str_replace("+"," ",trim($v)); // "+" 를 공백으로 변환
	}

	return $query;
}

//Extract Value - 불당Resize에서 차용
function amina_value($tag) {

	$tag = stripcslashes($tag);

	preg_match_all('@(?P<attribute>[^\s\'\"]+)\s*=\s*(\'|\")?(?P<value>[^\s\'\"]+)(\'|\")?@i', $tag, $match);
    if (function_exists('array_combine')) {
        $value = array_change_key_case(array_combine($match['attribute'], $match['value']));
    } else {
        $value = array_change_key_case(amina_array_combine4($match['attribute'], $match['value']));
    }
		
	return $value;
}

// 함수명 변경 - php4를 위한 array_combine 함수정의, http://kr2.php.net/manual/kr/function.array-combine.php
function amina_array_combine4($arr1, $arr2) {

	$out = array();
    
    $arr1 = array_values($arr1);
    $arr2 = array_values($arr2);
    
    foreach($arr1 as $key1 => $value1) {
        $out[(string)$value1] = $arr2[$key1];
    }
    
    return $out;
}

//불당님 db_cache 함수 그대로 차용 - 파일캐쉬를 DB로 대신하는 것, $c_code = "latest(simple, gnu4_pack)"
function amina_cache($c_name, $seconds=300, $c_code, $c_opt='') {
    global $g4, $config, $amina, $member;

    $result = sql_fetch(" select c_name, c_text, c_datetime from {$g4['amina_cache']} where c_name = '$c_name' ");
    if (!$result) {
        // 시간을 offset 해서 입력 (-1을 해줘야 처음 call에 캐쉬를 만듭니다)
        $new_time = date("Y-m-d H:i:s", G4_SERVER_TIME - $seconds - 1);
        $result['c_datetime'] = $new_time;
        sql_query(" insert into {$g4['amina_cache']} set c_name='$c_name', c_datetime='$new_time' ");
    }

    $sec_diff = G4_SERVER_TIME - strtotime($result['c_datetime']);
    if ($sec_diff > $seconds) {
        // $c_code () 안에 내용만 살림 
        $pattern = "/[()]/";
        $tmp_c_code = preg_split($pattern, $c_code);
        
        // 수행할 함수의 이름
        $func_name = $tmp_c_code[0];

        // 수행할 함수의 인자
        $tmp_array = explode(",", $tmp_c_code[1]);
        
        if ($func_name == "include_once" || $func_name == "include") {

			$tmp_array[0] = trim($tmp_array[0]);
	        // 추가 trim으로 인자를 넘길 때 쓰는 '를 없앤다
		    $tmp_array[0] = trim($tmp_array[0], "'");
            // 추가 trim으로 인자를 넘길 때 쓰는 "를 없앤다
	        $tmp_array[0] = trim($tmp_array[0], '"');

            ob_start();
            include($c_opt.'/'.$tmp_array[0]);
            $c_text = ob_get_contents();
            ob_end_clean();
        } else {
	        // 수행할 함수의 인자를 담아둘 변수
	        $func_args = array();

		    for($i=0;$i < count($tmp_array); $i++) {
			    // 기본 trim은 여백 등을 없앤다. $charlist = " \t\n\r\0\x0B"
	            $tmp_args = trim($tmp_array[$i]);
		        // 추가 trim으로 인자를 넘길 때 쓰는 '를 없앤다
			    $tmp_args = trim($tmp_args, "'");
	            // 추가 trim으로 인자를 넘길 때 쓰는 "를 없앤다
		        $func_args[$i] = trim($tmp_args, '"');
	        }

			if($c_opt) $func_args[] = $c_opt;

	        // 새로운 캐쉬값을 만들고
		    $c_text = call_user_func_array($func_name, $func_args);
        }
        // db에 넣기전에 slashes들을 앞에 싹 붙여 주시고
        $c_text1 = addslashes($c_text);
        
        // 새로운 캐쉬값을 업데이트 하고
        sql_query(" update {$g4['amina_cache']} set c_text = '$c_text1', c_datetime='".G4_TIME_YMDHIS."' where c_name = '$c_name' ");

        // 새로운 캐쉬값을 return (slashes가 없는거를 return 해야합니다)
        return $c_text;
    } else {
        // 캐쉬한 데이터를 그대로 return
        return $result['c_text'];
    }
}

// Youngcart Item Info
function amina_it_info($it_id) {
	global $g4;

	// 분류사용, 상품사용하는 상품의 정보를 얻음
	$sql = " select a.*, b.ca_name, b.ca_use from {$g4['yc4_item_table']} a, {$g4['yc4_category_table']} b where a.it_id = '$it_id' and a.ca_id = b.ca_id limit 1 ";
	$it = sql_fetch($sql);

	return $it;
}

//Path to URL
function gnu_url($file, $opt) {

	if($opt) {
		$url = G4_URL.'/';
		$path = G4_PATH.'/';
		$file = str_replace($path,$url,$file);
	}

	return $file;
}

//Short URL
function amina_short_url($longUrl, $type='', $apiId='', $apiKey='') {
    global $config, $amina, $bo_table, $wr_id;

	if($amina['use_surl'] == "1" && $bo_table && $wr_id) {

		$surl = G4_URL.'/'.$bo_table.'/'.$wr_id;

		return $surl;

	} else if($amina['use_surl'] == "2" || $type == "bitly") {

		$apiId = $apiId ? $apiId : $amina['bitly_id'];
		$apiKey = $apiKey ? $apiKey : $amina['bitly_key'];

		if($appId && $appKey) {
			$data = 'http://api.bit.ly/shorten?version=2.0.1&longUrl='.urlencode($longUrl).'&login='.$apiId.'&apiKey='.$apiKey.'&format=json&history=1';
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_HEADER, 0);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_URL, $data); 
			$data = curl_exec($ch);
			curl_close($ch); 

		    $data = json_decode($data);
		    foreach($data->results as $row) {
				$url = $row->shortCNAMEUrl;
			}

			return $url;
		}

	} else if($amina['use_surl'] == "3" || $type == "googl") {

		if(!$apiKey) $apiKey = $config['cf_googl_shorturl_apikey'] ? $config['cf_googl_shorturl_apikey'] : $amina['googl_key'];

		if($apiKey) {
		    $postData = array('longUrl' => $longUrl, 'key' => $apiKey);
		    $jsonData = json_encode($postData);

		    $curlObj = curl_init();

			curl_setopt($curlObj, CURLOPT_URL, 'https://www.googleapis.com/urlshortener/v1/url');
			curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0);
			curl_setopt($curlObj, CURLOPT_HEADER, 0);
			curl_setopt($curlObj, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
			curl_setopt($curlObj, CURLOPT_POST, 1);
			curl_setopt($curlObj, CURLOPT_POSTFIELDS, $jsonData);

			$response = curl_exec($curlObj);
			$json = json_decode($response);

			curl_close($curlObj);

			return $json->id;
		}
	}

	return;
}

// SNS Icon
function amina_sns($id, $skin, $title, $content, $lurl, $surl='', $image='', $type=''){
	global $g4;

	$sns_skin_path = AMINA_PATH.'/skin/sns/'.$skin;
	$sns_skin_url = AMINA_URL.'/skin/sns/'.$skin;

	$sns_url = $surl ? $surl : $lurl;
	$sns_url = urlencode($sns_url);

	$sns_title = $title ? urlencode($title) : '';

	$sns_msg = $title;
	if($title && $content) $sns_msg .= ' - ';
	$sns_msg .= $content;

	$sns_msg = amina_cut($sns_msg, 100);
	$sns_msg = str_replace('\"', '"', $sns_msg);
	$sns_emsg = urlencode($sns_msg);
	$msg_url = $sns_emsg.' : '.$sns_url;
	
    $me2day_url = 'http://me2day.net/posts/new?new_post[body]='.$msg_url;
	$twitter_url = 'http://twitter.com/?status='.$msg_url;

	$fb_msg = $sns_title ? $sns_title : $sns_emsg;

	if(G4_IS_MOBILE) {
		// 카카오톡 매뉴얼 : https://github.com/kakao/kakaolink-web
		$kakao_appid   = $_SERVER['HTTP_HOST']; // Mobile Site Domain 정확히 입력하지 않을 경우 이용이 제한될 수 있습니다.
		$kakao_appname = urlencode($g4['title']);
		$kakao_url = 'kakaolink://sendurl?msg='.$sns_emsg.'&amp;url='.$sns_url.'&amp;appid='.$kakao_appid.'&amp;appver=1.0&amp;type=link&amp;appname='.$kakao_appname.'&amp;apiver=2.0';
	    $kakaostory_url = 'storylink://posting?post='.$sns_emsg.urlencode("\n").$sns_url.'&amp;apiver=1.0&amp;appname='.$kakao_appname.'&amp;appver=1&amp;appid='.$kakao_appid;
		$facebook_url = 'http://www.facebook.com/share.php?u='.$lurl.'&t='.$fb_msg;
	} else {
		$fb_image = $image ? '&p[images][0]='.urlencode($image) : '';
		$facebook_url  = 'http://www.facebook.com/sharer/sharer.php?s=100&p[url]='.$sns_url.'&p[title]='.$fb_msg.$fb_image;
		$kakao_url = $kakaostory_url = '';
	}

	$yozm_url = 'http://yozm.daum.net/api/popup/prePost?sourceid=41&link='.$sns_url.'&prefix='.$sns_emsg;
    $cy_url = "javascript:window.open('http://csp.cyworld.com/bi/bi_recommend_pop.php?url=".$sns_url."', 'recom_icon_pop', 'width=400,height=364,scrollbars=no,resizable=no');";
	$google_url = 'https://www.google.com/bookmarks/mark?op=add&title='.$sns_title.'&bkmk='.$lur;
	$naver_url = 'http://bookmark.naver.com/post?ns=1&title='.$sns_title.'&url='.$lurl;

    ob_start();
    include $sns_skin_path.'/sns.skin.php';
    $view_sns = ob_get_contents();
    ob_end_clean();

	return $view_sns;
}

// SNS Like
function amina_like($skin, $bo_table, $wr_id, $text, $url=''){
	global $g4, $config;

	$like_skin_path = AMINA_PATH.'/skin/like/'.$skin;
	$like_skin_url = AMINA_URL.'/skin/like/'.$skin;

	if($href) {
		$url = str_replace("&amp;", "&", $url);
		$url = str_replace("&", "&amp;", $url);
	} else {
		$url = G4_BBS_URL.'/board.php?bo_table='.$bo_table;
		if($wr_id) $url .= '&amp;wr_id='.$wr_id;
	}

	$text = amina_cut($text, 100);
	$text = str_replace("\"", "", $text);

	ob_start();
	include $like_skin_path.'/like.skin.php';
	include_once(AMINA_PATH.'/lib/like.lib.php');
	$view_like = ob_get_contents();
    ob_end_clean();

	return $view_like;
}

//Star Mark
function amina_star_mark($star_color='gold', $star_set, $type='s'){

	$star = amina_array_star($star_set);

	if(!is_numeric($star['score']) || !is_numeric($star['people'])) {
		$star['socre'] = 0;
		$star['people'] = 0;
	} 

	$score = 0;
	if($star['people'] > 0) $score = $star['score'] / $star['people'];

	$score = round($score,1);
	$point = round($score) * 10;

	$alt = number_format($score, 1)."점 / ".number_format($star['people'], 0)."명";

	$star = '<span class="star-'.$type.'" title="'.$alt.'"><span class="'.$star_color.'" style="width:'.$point.'%;">'.$alt.'</span></span>'."\n";

	return $star;
}

// Extract Text
function amina_text($str) {

	$str = strip_tags($str);
	$str = preg_replace("/{이미지\:([^}]*)}/ie", "", $str);
	$str = preg_replace("/{동영상\:([^}]*)}/ie", "", $str);
	$str = str_replace(array("&nbsp;", "[code]", "[/code]", "[map]", "[/map]"), array("", "", "", "", ""), $str);
	$str = preg_replace('/\s\s+/', ' ', $str);
	$str = trim($str);

	return $str;
}

// G4S Function
function amina_cut_str($str, $len, $suffix="…") {
    $arr_str = preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
    $str_len = count($arr_str);

    if ($str_len >= $len) {
        $slice_str = array_slice($arr_str, 0, $len);
        $str = join("", $slice_str);

        return $str . ($str_len > $len ? $suffix : '');
    } else {
        $str = join("", $arr_str);
        return $str;
    }
}

// Cut Text
function amina_cut($str, $len, $tail="…") {

	$str = amina_text($str);
	$str = amina_cut_str($str, $len, $tail);

	return $str;
}

// AMINA Date
function amina_date($wr_date) {

	$str_date = strtotime($wr_date);

	$diff = G4_SERVER_TIME - $str_date;

	$s = 60; //1분 = 60초
	$h = $s * 60; //1시간 = 60분
	$d = $h * 24; //1일 = 24시간
	$y = $d * 365; //1년 = 1일 * 365일

	if ($diff < $s) {
		$date = $diff."초전";
	} else if ($h > $diff && $diff >= $s) {
		$date = round($diff/$s)."분전";
	} else if ($d > $diff && $diff >= $h) {
		$date = round($diff/$h)."시간전";
	} else if ($y > $diff && $diff >= $d) {
		$date = round($diff/$d)."일전";
	} else {
		$date = date("Y.m.d", $str_date);
	} 

	return $date;
}

//Check Attached File
function amina_attach_file($attach) {

	$chk_file = false;
	for ($i=0; $i<count($attach); $i++) {
		if ($attach[$i]['source'] && !$attach[$i]['view']) {
			$chk_file = true;
			return $chk_file;
		}
    }

	return $chk_file;
}

//Check Attached Image
function amina_attach_img($attach, $wr_content, $rows='1') {

	$img = array();

	$z = 0;
	//Direct Attach
	for ($i=0; $i<count($attach); $i++) {
		if ($attach[$i]['view']) {
			$attach_img = $attach[$i]['path'].'/'.$attach[$i]['file'];
			if(preg_match("/\.(jpg|gif|png)$/i", $attach_img)) {
				$img[] = $attach_img;
				$z++;
				if($rows != "all" && $z == $rows) return $img;
			}
		}
	}

	//Edit Attach
	if(preg_match_all("/\<img[^\<\>]*\>/i", $wr_content, $match)) {
		for ($i=0; $i<count($match[0]); $i++) {
			$chk_img = amina_value($match[0][$i]);
			if($chk_img['src'] && !preg_match("/(\/cheditor5\/)/i", $chk_img['src']) && !preg_match("/(\/plugin\/)/i", $chk_img['src']) && !preg_match("/(\/amina\/app\/)/i", $chk_img['src'])) {
				$img[] = $chk_img['src'];
				$z++;
				if($rows != "all" && $z == $rows) return $img;
			}
		}
	}

	return $img;
}

//동영상 포함 썸네일용 이미지 하나 뽑아오기
function amina_thumb_img($attach, $wr_6, $wr_content, $rows='1', $linked_bo='', $it_id='', $linked_img='') {

	$img = array();
	$info = array();
	$video = array();

	$z = 0;

	//직접 첨부한 이미지
	for ($i=0; $i<count($attach); $i++) {
		if ($attach[$i]['view']) {
			$attach_img = $attach[$i]['path'].'/'.$attach[$i]['file'];
			if(preg_match("/\.(jpg|gif|png)$/i", $attach_img)) {
				$img[] = $attach_img;
				$z++;
				if($rows != "all" && $z == $rows) return $img;
			}
		}
	}

	//직접링크 동영상 이미지
	if($wr_6) {
		$info = amina_array_video($wr_6);
		if($info['movie_url']) {
			include_once(AMINA_PATH.'/lib/video.lib.php');
			$video = amina_video_info($info['movie_info']);
			$video_img = amina_video_img($video['video_url'], $video['vid'], $video['type'], '', $video['img']);
			if($video_img) $img[] = $video_img;
			$z++;
			if($rows != "all" && $z == $rows) return $img;
		} 
	}

	//에디터에 삽입된 이미지
	if(preg_match_all("/\<img[^\<\>]*\>/i", $wr_content, $match)) {
		for ($i=0; $i<count($match[0]); $i++) {
			$chk_img = amina_value($match[0][$i]);
			if($chk_img['src'] && !preg_match("/(\/cheditor5\/)/i", $chk_img['src']) && !preg_match("/(\/plugin\/)/i", $chk_img['src'])  && !preg_match("/(\/amina\/app\/)/i", $chk_img['src'])) {
				$img[] = $chk_img['src'];
				$z++;
				if($rows != "all" && $z == $rows) return $img;
			}
		}
	}

	//에디터에 삽입된 동영상
	if(preg_match_all("/{동영상\:([^}]*)}/ie", $wr_content, $match)) {
		include_once(AMINA_PATH.'/lib/video.lib.php');
		for ($i=0; $i<count($match[1]); $i++) {
			if(preg_match('/'.AMINA_VIDEO.'/i', $match[1][$i])) {
				list($url) = explode("|", trim(strip_tags($match[1][$i])));
				$video = amina_video_info($url);
				$video_img = amina_video_img($video['video_url'], $video['vid'], $video['type'], '', $video['img']);
				if($video_img)$img[] = $video_img;
				$z++;
				if($rows != "all" && $z == $rows) return $img;
			}
		}
	}

	//영카트 또는 게시판 연동 이미지
	if($linked_img && $it_id) {
		if($linked_bo) { //게시판 연동
			global $g4;	
			$bo = sql_fetch(" select bo_table from {$g4['board_table']} where bo_table = '$linked_bo' ");
			if($bo['bo_table']) {
				$tmp_write_table = $g4['write_prefix'] . $bo['bo_table'];
				$row = sql_fetch(" select wr_content from $tmp_write_table where wr_id = '$it_id' ");
				$file = get_file($bo['bo_table'], $it_id);
				list($linked_img) = amina_attach_img($file, $row['wr_content']);
				if($linked_img) {
					$img[] = $linked_img;
					$z++;
					if($rows != "all" && $z == $rows) return $img;
				}
			}
		} else { //영카트
			$it_img = G4_DATA_PATH.'/item/'.$it_id.'_l1';
			if(file_exists($it_img)) { //상품이미지
				$img[] = $it_img;
				$z++;
				if($rows != "all" && $z == $rows) return $img;
			}
		}
	}

	return $img;
}

function amina_animated_gif( $filename ) { //g4s에서 차용함

	if(!($fh = @fopen($filename, 'rb')))
        return false;
    $count = 0;
    // 출처 : http://www.php.net/manual/en/function.imagecreatefromgif.php#104473
    // an animated gif contains multiple "frames", with each frame having a
    // header made up of:
    // * a static 4-byte sequence (\x00\x21\xF9\x04)
    // * 4 variable bytes
    // * a static 2-byte sequence (\x00\x2C) (some variants may use \x00\x21 ?)

    // We read through the file til we reach the end of the file, or we've found
    // at least 2 frame headers
    while(!feof($fh) && $count < 2) {
        $chunk = fread($fh, 1024 * 100); //read 100kb at a time
        $count += preg_match_all('#\x00\x21\xF9\x04.{4}\x00(\x2C|\x21)#s', $chunk, $matches);
   }

    fclose($fh);
    return $count > 1;

} 

//파일의 경로를 가지고 옵니다 (함수명 중복 오류 해결을 위해 불당썸에서 차용함)
function amina_file_path($path) {

    $dir = dirname($path);
    $file = basename($path);
    
    if (substr($dir,0,1) == "/") {
        $real_dir = dirname($_SERVER['DOCUMENT_ROOT'] . "/nothing");
        $dir = $real_dir . $dir;
    }
    
    return $dir . "/" . $file;
}

//Make Tumbnail
function amina_make_thumb($thumb, $thumb_w, $thumb_h, $quality='90', $opt='', $wm='') {

	if(!$thumb) return;

	if (preg_match("/^(http|https|ftp|telnet|news|mms)\:\/\//i", $thumb)) {
        if (preg_match("/" . AMINA_HOST . "/", $thumb)) {
            $url = parse_url($thumb);
            $thumb = $url['path'];
			if(!file_exists($thumb)) $thumb = amina_file_path($thumb);
			if(amina_animated_gif($thumb)) return;
		} else {
			return;
		}
    }

	if($opt) {
		$img_size = @getimagesize($thumb);
		if($thumb_w >= $img_size[0]) return;
	}

	$thumb = bthumbnail($thumb, $thumb_w, $thumb_h, false, 1 , $quality, 1, $wm);

	return $thumb;
}

//Logo
function amina_logo($thumb) {
	global $g4;

	list($type, $skin) = explode(";", $thumb);

	if($type != "logo") return;

	$logo = array();

	if($skin) {
		$logo_path = G4_DATA_PATH.'/logo/'.$skin.'/';
		$logo_url = G4_DATA_URL.'/logo/'.$skin;
	} else {
		$logo_path = G4_DATA_PATH.'/logo/';
		$logo_url = G4_DATA_URL.'/logo';
	}

	if(!is_dir($logo_path)) return;

	$handle = opendir($logo_path);
	while ($file = readdir($handle)) {
		if(preg_match("/\.(jpg|gif|png)$/i", $file)) {
			$logo[] = $logo_url.'/'.$file;
		}
    }
    closedir($handle);

	return $logo;
}

//Thumbnail
function amina_thumb($list, $thumb_w, $thumb_h, $cut='', $no_thumb='', $type='', $linked='', $target='', $thumb_icon='', $thumb_css='', $logo='') {
	global $g4;

	if(!$list) return;

	list($thumb) = amina_thumb_img($list['file'], $list['wr_6'], $list['wr_content'], 1, $list['wr_4'], $list['wr_8'], $linked);

	if(!$thumb) {
		if($no_thumb == "none") {
			return;
		} else if($no_thumb == "logo" && $logo) {
			$thumb = $logo;
		}
	}

	if($cut == "nocut") $thumb_h = '';

    //make Thumbnail
	$make_thumb = amina_make_thumb($thumb, $thumb_w, $thumb_h);
	if($make_thumb) $thumb = $make_thumb;

	//Height
	if(!$thumb && !$thumb_h) {
		$thumb_h = ($thumb_w * 9)/16;
		$thumb_h = (int)$thumb_h;
		$thumb_h1 = ' height:'.$thumb_h.'px;';
		//$thumb_h2 = ' height="'.$thumb_h.'"';
		$thumb_h2 = '';
	} else if($thumb && !$thumb_h) {
		$thumb_h1 = '';
		$thumb_h2 = '';
	} else {
		$thumb_h1 = ' height:'.$thumb_h.'px;';
		//$thumb_h2 = ' height="'.$thumb_h.'"';
		$thumb_h2 = '';
	}

	//Icon
	list($type, $icon_view) = explode(",", $type);

	if(!$type) $type = 'm';

	if($icon_view == 'none') {
		$thumb_icon = '';
	} else {
		if($thumb_icon) {
			$thumb_icon = '" style="background: url(\''.$thumb_icon.'\') no-repeat top left;';
		} else {
			if($list['icon_hot']) {
				$thumb_icon = ' thumb-hot-'.$type;
			} else if($list['icon_new']) {
				$thumb_icon = ' thumb-new-'.$type;
			} 
		}
	}

	if(!$thumb_icon) {
		$wr_post = amina_array_write($list['wr_10']);
		$thumb_icon = $wr_post['video'] ? ' thumb-video-'.$type : '';
	}

	//Output
	$thumb_css = $thumb_css ? ' '.$thumb_css : '';
	
	//글제목 따옴표 지우기
	$list['wr_subject'] = str_replace('"','',$list['wr_subject']);

	if($thumb) {
		$thumbnail = '<div class="thumb'.$thumb_css.'" onClick="amina_thumb(\''.$list['href'].'\',\''.$target.'\');" style="width:'.$thumb_w.'px;'.$thumb_h1.'" title="'.$list['wr_subject'].'">';
			if($thumb_icon) $thumbnail .= '<div class="thumb-icon'.$thumb_icon.'"></div>'; 
			$thumbnail .= '<img src="'.$thumb.'" width="'.$thumb_w.'" '.$thumb_h2.' alt="" />';
		$thumbnail .= '</div>'."\n";
	} else {
		if($no_thumb != "none") {
			switch($no_thumb) {
				case 'black'	: $no_thumb = ' thumb-no-black'; break;
				default			: $no_thumb = ' thumb-no-white'; break;
			}
			$thumbnail = '<div class="thumb'.$no_thumb.$thumb_css.'" onClick="amina_thumb(\''.$list['href'].'\',\''.$target.'\');" style="width:'.$thumb_w.'px;'.$thumb_h1.'" title="'.$list['wr_subject'].'">';
			if($thumb_icon) $thumbnail .= '<div class="thumb-icon'.$thumb_icon.'"></div>'; 
			$thumbnail .= '</div>'."\n";
		}
	}

	return $thumbnail;
}

//Delete Image
function amina_del_img($list) {
	global $g4;

	unset($list['file']);

	//extract content & video image
	$img_arr = array();
	$img_arr = amina_thumb_img($list['file'], $list['wr_6'], $list['wr_content'], "all");

	for ($i=0; $i<count($img_arr); $i++) {
		if (preg_match("/^(http|https|ftp|telnet|news|mms)\:\/\//i", $img_arr[$i])) {
			if (preg_match("/" . AMINA_HOST . "/", $img_arr[$i]) && preg_match("/\/data\/(cheditor4|editor|video)\//i", $img_arr[$i])) {
			    $url = parse_url($img_arr[$i]);
				$img = $url['path'];
				if(!file_exists($img)) $img = amina_file_path($img);
				$img_size = @getimagesize($img);
				if($img_size[0] > 0) {
					@chmod($img, G4_FILE_PERMISSION);
					@unlink($img);
				}
			}
		}
	}
}

//Load Member Photo
function mb_photo($login_id, $mb_id, $width='', $height='', $no_photo='', $thumb='') {

	$mb_photo = G4_DATA_URL.'/mb_photo/'.$mb_id;

	if(!$mb_id || !file_exists(G4_DATA_PATH.'/mb_photo/'.$mb_id)) {
		if($no_photo) {
			$mb_photo = '';
			return $mb_photo;
		} else {
			$mb_photo = AMINA_URL.'/img/no_photo.gif';
		}
	}

	if($login_id && $login_id == $mb_id) $onclick = ' onclick="amina_photo();" class="my_photo" title="내사진 등록/수정"';

	$width = $width ? ' width="'.$width.'"' : '';
	$height = $height ? ' height="'.$height.'"' : '';

	$mb_photo = '<img src="'.$mb_photo.'"'.$width.$height.$onclick.' alt="" />';

	return $mb_photo;
}

//Upload Member Photo
function mb_photo_upload($mb_id, $del_photo, $file) {
	global $g4, $xp;

	//Photo Size
	$photo_w = $xp['photo_size'] ? $xp['photo_size'] : 80;
	$photo_h = $photo_w;

	$photo_dir = G4_DATA_PATH.'/mb_photo';
	$temp_dir = G4_DATA_PATH.'/mb_photo/temp';

	if(!is_dir($photo_dir)) {
        @mkdir($photo_dir, G4_DIR_PERMISSION);
        @chmod($photo_dir, G4_DIR_PERMISSION);
	}

	if(!is_dir($temp_dir)) {
        @mkdir($temp_dir, G4_DIR_PERMISSION);
        @chmod($temp_dir, G4_DIR_PERMISSION);
	}

	//Delete Photo
	if ($del_photo == "1")
		@unlink($photo_dir.'/'.$mb_id);
    
	//Upload Photo
	if (is_uploaded_file($file['mb_icon2']['tmp_name'])) {
		if (!preg_match("/(\.(jpg|gif|png))$/i", $file['mb_icon2']['name'])) {
			alert($file['mb_icon2']['name'].'은(는) 이미지(gif/jpg/png) 파일이 아닙니다.', AMINA_URL.'/mb.photo.php');
		} else {
			$org_photo = $photo_dir.'/'.$mb_id;
			$temp_photo = $temp_dir.'/'.$mb_id;
	        move_uploaded_file($file['mb_icon2']['tmp_name'], $temp_photo) or die($file['mb_icon2']['error']);
			chmod($temp_photo, G4_FILE_PERMISSION);
			if(file_exists($temp_photo)) {
			    $size = @getimagesize($temp_photo);

			    //Non Image
				if (!$size[0]) {
					@unlink($temp_photo);
					alert('회원사진 등록에 실패했습니다. 이미지 파일이 정상적으로 업로드 되지 않았거나, 이미지 파일이 아닙니다.', AMINA_URL.'/mb.photo.php');
				}			

				//Animated GIF
			    if($size[2] == IMG_GIF && amina_animated_gif($temp_photo)) {
					if($xp['animated_gif_photo']) {
						copy($temp_photo, $org_photo);
						chmod($org_photo, G4_FILE_PERMISSION);
						@unlink($temp_photo);
					} else {
						@unlink($temp_photo);
						alert('움직이는 GIF 파일은 회원사진으로 등록할 수 없습니다.', AMINA_URL.'/mb.photo.php');
					}
				} else {
					if($size[0] > $photo_w) {
						$thumb = bthumbnail($temp_photo, $photo_w, $photo_h);
						if($thumb) {
							if(!file_exists($thumb)) $thumb = amina_file_path($thumb);
							copy($thumb, $org_photo);
							chmod($org_photo, G4_FILE_PERMISSION);
							@unlink($thumb);
							@unlink($temp_photo);
						} else {
							@unlink($temp_photo);
							alert('회원사진 등록에 실패했습니다. 이미지 파일이 정상적으로 업로드 되지 않았거나, 이미지 파일이 아닙니다.', AMINA_URL.'/mb.photo.php');
						}
					} else {
						copy($temp_photo, $org_photo);
						chmod($org_photo, G4_FILE_PERMISSION);
						@unlink($temp_photo);
					}
				}
			}
		}
	}
}

//Calculate Level
include_once(AMINA_PATH.'/lib/level.lib.php');

// Check XP 
function check_xp($mb_id) {
	global $g4, $xp;

	$info = array();

	if(!$mb_id || !$xp['xp_use']) return;

	//Member Info
	$sql = " select mb_point, mb_9 from {$g4['member_table']} where mb_id = '$mb_id' ";
	$row = sql_fetch($sql);
	$point = $row['mb_point'];
	$now_level = (int)$row['mb_9'];

	if($xp['exp']['point']) { //현재 포인트
		;
	} else {

		$rule_table = "";
		if($xp['exp']['login']) $rule_table .= "'@login',";
		if($xp['exp']['join']) $rule_table .= "'@member',";
		if($rule_table) $rule_table = " or po_rel_table in (".substr($rule_table,0,-1).")";

		$rule_action = "";
		if($xp['exp']['write']) $rule_action .= "'쓰기',";
		if($xp['exp']['cmt']) {
			$cmt_log = (AMINA == "g4s") ? '댓글' : '코멘트';
			$rule_action .= "'{$cmt_log}',";
		}
		if($xp['exp']['read']) $rule_action .= "'읽기',";
		if($xp['exp']['good']) $rule_action .= "'@good',";
		if($xp['exp']['nogood']) $rule_action .= "'@nogood',";
		if($xp['exp']['star']) $rule_action .= "'@star',";
		if($xp['exp']['poll']) $rule_action .= "'@poll',";
		if($xp['exp']['choice']) $rule_action .= "'@choice',";
		if($xp['exp']['chulsuk']) $rule_action .= "'@chulsuk',";
		if($xp['exp']['lucky']) $rule_action .= "'@lucky',";
		if($rule_action) $rule_action = " or po_rel_action in (".substr($rule_action,0,-1).")";

		$rule_action_like = "";
		if($xp['exp']['star_re']) $rule_action_like .= " or po_rel_action like '%@star_re%' ";
		if($xp['exp']['nogood_re']) $rule_action_like .= " or po_rel_action like '%@nogood_re%' ";
		if($xp['exp']['good_re']) $rule_action_like .= " or po_rel_action like '%@good_re%' ";
		if($xp['exp']['po_view']) $rule_action_like .= " or po_rel_action like '%@po_view_re%' ";
		if($xp['exp']['po_down']) $rule_action_like .= " or po_rel_action like '%@po_down_re%' ";

		$sql = " select SUM(po_point) as point from {$g4['point_table']} where mb_id = '$mb_id' and ( po_content like '%\[exp\]%'{$rule_table}{$rule_action}{$rule_action_like}) ";
		$row = sql_fetch($sql);
		$point = $row['point'];
	}

	//Caculate Level
	list($level, $point, $min_xp, $max_xp) = chk_xp_num($point, $xp['xp_point'], $xp['xp_max'], $xp['xp_rate']);

	//Is_member_level
	$level_msg = "";
	if($now_level && $now_level != $level) {
		//Level Gap
		$level_gap = $level - $now_level;
		if($level_gap == "1") { //Level Up
			$level_msg = 'up';
		} else if($level_gap == "-1") { //Level Down
			$level_msg = 'down';
		} else { //Level Adjust
			$level_msg = 'adjust';
		}
	}

	//Update Member Info
	sql_query(" update {$g4['member_table']} set mb_8 = '$level_msg', mb_9 = '$level', mb_10 = '$point' where mb_id = '$mb_id' ");

	$info = array($level, $point, $min_xp, $max_xp);

	return $info;
}

//Calculate Level
function xp_level($mb_id='') {
	global $member, $xp;

	if(!$mb_id) $mb_id = $member['mb_id'];
	if($mb_id) {
		$level = (int)$member['mb_9'];
		if(!$level || !is_numeric($level)) {
			list($level) = check_xp($mb_id);
		} else {
			list($chk_level) = chk_xp_num((int)$member['mb_10'], (int)$xp['xp_point'], (int)$xp['xp_max'], $xp['xp_rate']);
			if($level != $chk_level) {
				list($level) = check_xp($mb_id);
			}
		}
	} else {
		$level = 1;
	}

	return $level;
}

//XP Level Icon
function xp_icon($xp_id, $xp_level, $opt='') {
	global $xp;

	$xp_icon = '';

	if($xp['xp_use'] == 1) {
		if(!$xp_id) {
			$xp_icon = 'guest';
		} else {
			$is_admin = is_admin($xp_id);
			if($is_admin || $xp_id == "@admin") {
				$xp_icon = 'admin';
			} else if($xp_id == "@special") {
				$xp_icon = 'special';
			} else {
				$xp_mb = explode(",", trim($xp['xp_mb_list']));
				for($i = 0 ; $i < count($xp_mb) ; $i++) {
					if($xp_id == $xp_mb[$i]) {
						$xp_icon = 'special';
						break;
					}
				}
			}
		}

		if(!$xp_icon) {
			if(is_numeric($xp_level)) {
				$xp_icon = $xp_level;
			} else {
				$xp_icon = 1;
			}
		}

		if($xp['xp_icon'] == "img") {
			$xp_icon = '<img src="'.AMINA_URL.'/skin/xp/'.$xp['xp_icon_skin'].'/'.$xp_icon.'.gif" alt="LV '.$xp_icon.'" />';
		} else {
			switch ($xp_icon) {
				case 'guest'	: $xp_icon = 'GT'; break;
				case 'admin'	: $xp_icon = 'AD'; break;
				case 'special'	: $xp_icon = 'SP'; break;
				default			: $xp_icon = 'LV '.$xp_icon; break;
			}

			$xp_icon = '<span class="xp_icon">'.$xp_icon.'</span>';
		}
	}

	return $xp_icon;
}

//XP Info
function xp_info($mb_id='') {
	global $g4, $xp;

	$info = array();

	if(!$mb_id || $xp['xp_use'] != 1) {
		$info['level'] = 1;
		$info['xp'] = 0;
		$info['max_xp'] = $xp['xp_point'];
		$info['min_xp'] = 0;
		$info['point'] = 0;
	} else {
		$mb = sql_fetch(" select mb_level, mb_point, mb_9, mb_10 from {$g4['member_table']} where mb_id = '$mb_id' ");
		$grade = $mb['mb_level'];
		$info['point'] = $mb['mb_point'];
		$mb['mb_9'] = (int)$mb['mb_9'];
		$mb['mb_10'] = (int)$mb['mb_10'];

		if($xp['xp_rule'][0]) {
			if(!$mb['mb_9'] || !is_numeric($mb['mb_9'])) {
				list($info['level'], $info['xp'], $info['min_xp'], $info['max_xp']) = check_xp($mb_id);
			} else {
				list($info['level'], $info['xp'], $info['min_xp'], $info['max_xp']) = chk_xp_num($mb['mb_10'], $xp['xp_point'], $xp['xp_max'], $xp['xp_rate']);
			}
		} else {
			if(!$mb['mb_9'] || !is_numeric($mb['mb_9']) || !$mb['mb_10'] || !is_numeric($mb['mb_10'])) {
				list($info['level'], $info['xp'], $info['min_xp'], $info['max_xp']) = check_xp($mb_id);
			} else {
				list($info['level'], $info['xp'], $info['min_xp'], $info['max_xp']) = chk_xp_num($mb['mb_10'], $xp['xp_point'], $xp['xp_max'], $xp['xp_rate']);
			}
		}
	}

	if($info['level'] >= $xp['xp_max']) {
		$info['per'] = 100;
		$info['up'] = 0;
	} else {
		$total_xp = $info['max_xp'] - $info['min_xp'];
		$now_xp = $info['xp'] - $info['min_xp'];
		$info['per'] = ($total_xp > 0) ? ($now_xp / $total_xp) * 100 : 0;
		$info['up'] = $total_xp - $now_xp;
	}	

	if(!$grade) $grade = 1;

	$info['grade'] = $xp['grade'][$grade];

	return $info;
}

//새글 목록 출력
function new_post($update='1', $bo_table='') {
	global $g4;

	$list = array();

	$chk_date = date("Y-m-d H:i:s", G4_SERVER_TIME - ($update * 24 * 3600));
	if($bo_table) {
	    $tmp_write_table = $g4['write_prefix'] . $bo_table; // 게시판 테이블 전체이름
	    $result = sql_query(" select distinct ca_name from $tmp_write_table where wr_datetime >= '$chk_date' and wr_is_comment = 0 ", FALSE);
		for ($i=0; $row=sql_fetch_array($result); $i++) {
			$list[$i] = $row['ca_name'];
		}
	} else {
		$result = sql_query(" select distinct bo_table from {$g4['board_new_table']} where bn_datetime >= '$chk_date' and wr_id = wr_parent ", FALSE); //새글 : 댓글은 wr_id <> wr_parent
		for ($i=0; $row=sql_fetch_array($result); $i++) {
			$list[$i] = $row['bo_table'];
		}
	}

	return $list;
}

//사이트 새글 아이콘
function new_menu($bo_list, $list) {

	$arr_bo = explode("|", trim($bo_list));

	$new_icon = "new";

	for ($i=0; $i<count($list); $i++) { 
		for ($j=0; $j<count($arr_bo); $j++) {
			if ($list[$i] == $arr_bo[$j]) return $new_icon;
		}
	}

	$new_icon = "old";

	return $new_icon;
}

//선택 메뉴 아이콘
function sel_menu($bo_list='', $page_list='', $gr_list='') {
	global $gr_id, $bo_table, $page_id;

	$sel_icon = ' class=on ';

	if($gr_id && $gr_list) {
		$chk_gr = explode("|", trim($gr_list));
		for ($i=0; $i<count($chk_gr); $i++) { 
			if ($gr_id == $chk_gr[$i]) return $sel_icon;
		}
	}

	if($page_id && $page_list) {
		$chk_page = explode("|", trim($page_list));
		for ($i=0; $i<count($chk_page); $i++) { 
			if ($page_id == $chk_page[$i]) return $sel_icon;
		}
	}

	if($bo_table && $bo_list) {
		$chk_bo = explode("|", trim($bo_list));
		for ($i=0; $i<count($chk_bo); $i++) { 
			if ($bo_table == $chk_bo[$i]) return $sel_icon;
		}
	}

	$sel_icon = '';

	return $sel_icon;

}

function amina_get_list($write_row, $board, $skin_path, $subject_len=40, $type='') {
    global $g4, $config;

    // 배열전체를 복사
    $list = $write_row;
    unset($write_row);

	if($type == "cmt") {
		$list['wr_subject'] = $list['wr_content'];
		$list['wr_comment'] = 0;
	}

    if ($subject_len)
        $list['subject'] = amina_cut($list['wr_subject'], $subject_len, "…");
    else
        $list['subject'] = amina_cut($list['wr_subject'], $board['bo_subject_len'], "…");

    // 목록에서 내용 미리보기 사용한 게시판만 내용을 변환함 (속도 향상) : kkal3(커피)님께서 알려주셨습니다.
    if ($board['bo_use_list_content'])
	{
		$html = 0;
		if (strstr($list['wr_option'], "html1"))
			$html = 1;
		else if (strstr($list['wr_option'], "html2"))
			$html = 2;

        $list['content'] = conv_content($list['wr_content'], $html);
	}

    $list['comment_cnt'] = "";
    if ($list['wr_comment'])
        $list['comment_cnt'] = "($list[wr_comment])";

    // 당일인 경우 시간으로 표시함
    $list['datetime'] = substr($list['wr_datetime'],0,10);
    $list['datetime2'] = $list['wr_datetime'];
    if ($list['datetime'] == G4_TIME_YMD)
        $list['datetime2'] = substr($list['datetime2'],11,5);
    else
        $list['datetime2'] = substr($list['datetime2'],5,5);
    // 4.1
    $list['last'] = substr($list['wr_last'],0,10);
    $list['last2'] = $list['wr_last'];
    if ($list['last'] == G4_TIME_YMD)
        $list['last2'] = substr($list['last2'],11,5);
    else
        $list['last2'] = substr($list['last2'],5,5);

    $list['wr_homepage'] = get_text(addslashes($list['wr_homepage']));

    $tmp_name = get_text(cut_str($list['wr_name'], $config['cf_cut_name'])); // 설정된 자리수 만큼만 이름 출력
    if ($board['bo_use_sideview'])
        $list['name'] = get_sideview($list['mb_id'], $tmp_name, $list['wr_email'], $list['wr_homepage']);
    else
        $list['name'] = "<span class='".($list['mb_id']?'member':'guest')."'>$tmp_name</span>";

    $reply = $list['wr_reply'];

    $list['reply'] = "";
    if (strlen($reply) > 0)
    {
        for ($k=0; $k<strlen($reply); $k++)
            $list['reply'] .= ' &nbsp;&nbsp; ';
    }

    $list['icon_reply'] = "";
    if ($list['reply'])
        $list['icon_reply'] = "<img src='$skin_path/img/icon_reply.gif' align='absmiddle'>";

    $list['icon_link'] = "";
    if ($list['wr_link1'] || $list['wr_link2'])
        $list['icon_link'] = "<img src='$skin_path/img/icon_link.gif' align='absmiddle'>";

    // 분류명 링크
    $list['ca_name_href'] = G4_BBS_URL.'/board.php?bo_table='.$board['bo_table'].'&sca='.urlencode($list['ca_name']);

	// 글 & 댓글 링크 설정
	$list['href'] = G4_BBS_URL.'/board.php?bo_table='.$board['bo_table'].'&wr_id='.$list['wr_parent'];
	if($type == "cmt") $list['href'] .= '#c_'.$list['wr_id'];

    $list['icon_new'] = '';
    if ($list['wr_datetime'] >= date("Y-m-d H:i:s", G4_SERVER_TIME - ($board['bo_new'] * 3600)))
        $list['icon_new'] = "<img src='$skin_path/img/icon_new.gif' alt='' />";

    $list['icon_hot'] = '';
    if ($list['wr_hit'] >= $board['bo_hot'])
        $list['icon_hot'] = "<img src='$skin_path/img/icon_hot.gif' alt='' />";

    $list['icon_secret'] = '';
    if (strstr($list['wr_option'], "secret"))
        $list['icon_secret'] = "<img src='$skin_path/img/icon_secret.gif' alt='' />";

    // 링크
    for ($i=1; $i<=$g4['link_count']; $i++)
    {
        $list['link'][$i] = set_http(get_text($list["wr_link{$i}"]));
        $list['link_href'][$i] = G4_BBS_URL."/link.php?bo_table=".$board['bo_table']."&wr_id=".$list['wr_id']."&no=".$i;
        $list['link_hit'][$i] = (int)$list["wr_link{$i}_hit"];
    }

    // 가변 파일
    $list['file'] = get_file($board['bo_table'], $list['wr_id']);

    if ($list['file']['count'])
        $list['icon_file'] = "<img src='$skin_path/img/icon_file.gif' alt='' />";

    return $list;
}
 
function latest_amina($skin_dir="", $bo_table="", $rows=10, $subject_len=40, $options="", $tab_list="", $sql_opt="") {
    global $g4, $config, $amina, $member;

    $list = array();
	$tab = array();
	$opt = array();

	//탭 아이디 설정
	$tab_id = $bo_table;

	//탭이 있는지 확인
	$tab_num = count($tab_list);

	//탭이 1개이상일 경우에는 jquery용으로
	if($tab_num > 1) { 
		$tab_opt = '&org='.urlencode("skin_dir={$skin_dir} rows={$rows} subject_len={$subject_len}").'&opt='.urlencode($options);
		for ($i=0; $i < $tab_num; $i++) {
			if($i == "0") {
				$tab[$i]['query'] = '#';
			} else {
				$tab[$i]['query'] = AMINA_URL.'/latest.php?tab='.urlencode($tab_list[$i]).$tab_opt;
			}

			$tab[$i]['num'] = $i;

			$tmp = amina_query($tab_list[$i]);
			$tab[$i]['title'] = $tmp['title'];
			$tab[$i]['title_off'] = $tmp['title_off'];
			if(!$tab[$i]['title_off']) $tab[$i]['title_off'] = $tab[$i]['title'];
			$tab[$i]['new_icon'] = $tmp['new_icon'];
			if(!$tab[$i]['new_icon']) $tab[$i]['new_icon'] = 'old';

			$arr_board = explode(";", $tmp['bo_list']);

			if($tmp['head_href']) {
				$tab[$i]['href'] = str_replace("~", "=", $tmp['head_href']);
			} else {
				// 타이틀 링크설정
				if($tmp['type'] == "newgul" || $tmp['type'] == "newcmtgul") {
					$tab[$i]['href'] = G4_BBS_URL.'/new.php?view=w';
				} else if($tmp['type'] == "newcmt") {
					$tab[$i]['href'] = G4_BBS_URL.'/new.php?view=c';
				} else if($tmp['type'] == "none") {
					$tab[$i]['href'] = '#';
				} else {
					if(!$tmp['bo_list'] || count($arr_board) > 1) {
						$tab[$i]['href'] = '#';
					} else {
						$tab[$i]['href'] = G4_BBS_URL.'/board.php?bo_table='.$tmp['bo_list'].'&sca='.urlencode($tmp['ca_name']);
					}
				}
			}
		}	

		// 첫번째 탭 정리하기..
		$tmp2 = amina_query($options);
		$tmp2['bo_list'] = $tmp2['title'] = $tmp2['ca_name'] = '';

		$tmp1 = amina_query($tab_list[0]);

		$opt = $tmp1 + $tmp2; //두 배열키로 합치기

		if($opt['skin_dir']) $skin_dir = $opt['skin_dir'];
		if($opt['rows']) $rows = $opt['rows'];
		if($opt['subject_len']) $subject_len = $opt['subject_len'];

	} else {
		//탭값 및 옵션을 변수값으로 변환
		if($tab_list) {
			$tmp2 = amina_query($options);
			$tmp2['bo_list'] = $tmp2['title'] = $tmp2['ca_name'] = '';

			$tmp1 = amina_query($tab_list);

			$opt = $tmp1 + $tmp2; //두 배열키로 합치기

			if($opt['skin_dir']) $skin_dir = $opt['skin_dir'];
			if($opt['rows']) $rows = $opt['rows'];
			if($opt['subject_len']) $subject_len = $opt['subject_len'];
		} else {
			$opt = amina_query($options);
		}
	}

	//sql 추가 쿼리 - 보안문제로 사용 제외
	//if($opt['sql']) {
	//	$sql_opt = str_replace("\\", "", $opt['sql']);
	//	$sql_opt = str_replace("~", "=", $sql_opt);
	//}

	//스킨디렉토리
	$latest_skin_path = G4_SKIN_PATH.'/latest/'.$skin_dir;
	$latest_skin_url = G4_SKIN_URL.'/latest/'.$skin_dir;

	//탭 초기번호..
	$z = 0;

	if($opt['ca_exculde']) $opt['ca_name'] = '';

	//새글, 새댓글 등
	if($opt['type'] == "none") {
		$tab[$z]['href'] = '#';
		$tab[$z]['title'] = '제목입력';

	} else if($opt['type'] == "poll" || $opt['type'] == "mygul" || $opt['type'] == "newgul" || $opt['type'] == "newcmt" || $opt['type'] == "newcmtgul") {

		//mode 설정
		switch($opt['mode']) {
			case 'text'		: $mode_sql = "and wr_photo == '' "; break;
			case 'photo'	: $mode_sql = "and wr_photo != '' "; break;
			case 'video'	: $mode_sql = "and wr_video != '' "; break;
			case 'rss'		: $mode_sql = "and wr_rss != '' "; break;
			case 'main'		: $mode_sql = "and wr_main != '' "; break;
			case 'good'		: $mode_sql = "and wr_good != '' "; break;
			case 'daum'		: $mode_sql = "and wr_daum != '' "; break;
			default			: $mode_sql = ""; break;
		}

		//포함 게시판 설정
		$new_sql = '';
		if($opt['gr_list']) { //그룹추출
			$gr_sql = '';
			$gr_bo = explode(";", $opt['gr_list']);
			for ($i=0; $i < count($gr_bo); $i++) {

				if (!$gr_bo[$i]) continue;

				$gr_sql .= " gr_id = '$gr_bo[$i]' or ";
			}

			if($gr_sql) $gr_sql = substr($gr_sql,0,-3);

			$gr_result = sql_query(" select bo_table from {$g4['board_table']} where $gr_sql ");

			for ($i=0; $row=sql_fetch_array($gr_result); $i++) {
				$new_sql .= " bo_table = '".$row['bo_table']."' or ";
		    }
		}

		if($opt['bo_include']) {
			$bo_in = explode(";", $opt['bo_include']);
			for ($k=0; $k < count($bo_in); $k++) {

				if (!$bo_in[$k]) continue;

				$new_sql .= " bo_table = '$bo_in[$k]' or ";
			}
		} 

		if($new_sql) $new_sql = " and (".substr($new_sql,0,-3).")";

		// 제외 게시판 설정
		if($opt['bo_exclude']) {
			$bo_ex = explode(";", $opt['bo_exclude']);
			for ($k=0; $k < count($bo_ex); $k++) {

				if (!$bo_ex[$k]) continue;

				$new_sql .= " and bo_table != '$bo_ex[$k]' ";
			}
		} 

		// sql 추가조건 결정
		if($sql_opt) $new_sql .= " and ".$sql_opt." ";

		// 추출 및 정리
		if($opt['type'] == "newcmt") {
			$tab[$z]['title'] = '새로 달린 댓글';
			$tab[$z]['href'] = G4_BBS_URL.'/new.php?view=c';

			$result = sql_query(" select * from {$g4['board_new_table']} where bo_table != '' and wr_id <> wr_parent $new_sql $mode_sql order by bn_id desc limit 0, $rows ");
			for ($i=0; $row=sql_fetch_array($result); $i++) {

				if (!$row['bo_table']) continue;

				$tmp_write_table = $g4['write_prefix'] . $row['bo_table']; // 게시판 테이블 전체이름
				$board = sql_fetch(" select * from {$g4['board_table']} where bo_table = '{$row['bo_table']}' ");

				if (!$board) continue;

				$row1 = sql_fetch(" select wr_subject, wr_comment, ca_name, wr_option from $tmp_write_table where wr_id = '{$row['wr_parent']}' "); //원글 글옵션
				$row2 = sql_fetch(" select * from $tmp_write_table where wr_id = '{$row['wr_id']}' "); //댓글 정보 불러오기..
				// 댓글이라 글제목을 글내용으로 대체
				if(strstr($row1['wr_option'], "secret") || strstr($row2['wr_option'], "secret")) {
					$row2['wr_subject'] = $row2['wr_content'] = '비밀 댓글입니다.';
					if(strstr($row1['wr_option'], "secret")) $row2['wr_option'] = $row1['wr_option'];
				} else {
					$row2['wr_subject'] = $row2['wr_content'];
				}
				$row2['wr_comment'] = 0; //댓글수 0으로
				$row2['bo_table'] = $board['bo_table'];
				$row2['ca_name'] = $board['bo_subject']; //게시판 제목을 카테고리로 사용..
				$row2['wr_post'] = $row1['wr_subject']; //원글제목
				$row2['wr_post_cmt'] = $row1['wr_comment']; //원글 댓글수
				$list[$i] = amina_get_list($row2, $board, $latest_skin_url, $subject_len, "cmt");
			}
		} else if($opt['type'] == "poll") {
			$tab[$z]['title'] = '설문조사';
			$tab[$z]['href'] = '#';

			$rank = 1;
			$sql_time = $sql_term = '';
			$order_by = " poll_id desc ";

			$sql_ca = $opt['ca_name'] ? " and ca_name = '{$opt['ca_name']}' " : "";

			if($opt['term']) {
				$nowYmd = date(Ymd); # 시작시간을 구합니다. 
				$time = time(); 
				$startYmd = date("Ymd",strtotime("-".$opt['term']." day", $time)); 
				$sql_term = " and date_format(poll_regdate, '%Y%m%d') between '$startYmd' and '$nowYmd' ";
			}

			switch($opt['order']) {
				case 'hot'			: $sql_time = " and poll_enddate > ".G4_TIME_YMDHIS." "; $order_by = " poll_cnt desc, poll_id desc "; break;
				case 'rand'			: $sql_time = " and poll_enddate > ".G4_TIME_YMDHIS." "; $order_by = " rand() "; break;
			}

			$result = sql_query(" select * from {$g4['amina_poll']} where bo_table != '' and wr_id != '' $new_sql $sql_ca $sql_time $sql_term order by $order_by limit 0, $rows ");
			for ($i=0; $row=sql_fetch_array($result); $i++) {

				if (!$row['bo_table'] || !$row['wr_id']) continue;

				$tmp_write_table = $g4['write_prefix'] . $row['bo_table']; // 게시판 테이블 전체이름
				$board = sql_fetch(" select * from {$g4['board_table']} where bo_table = '{$row['bo_table']}' ");

				if (!$board) continue;

				$row1 = sql_fetch(" select * from {$tmp_write_table} where wr_id = '{$row['wr_id']}' "); //글 정보 불러오기..
				$row1['bo_table'] = $board['bo_table'];
				$row1['poll_cnt'] = $row['poll_cnt'];
				if($opt['order']) {
					$row1['wr_rank'] = $rank;
					$rank++;
				}
				if(!$opt['ca_name']) $row1['ca_name'] = $board['bo_subject']; //게시판 제목을 카테고리로 사용..
				if(strstr($row1['wr_option'], "secret")) $row1['wr_content'] = '비밀글입니다.';
				$list[$i] = amina_get_list($row1, $board, $latest_skin_url, $subject_len);
			}
		} else {
			if($opt['type'] == "mygul") {
				$tab[$z]['title'] = '새로 댓글달린 내글';
				$tab[$z]['href'] = '#';

				if($member['mb_id']) {
					$result = sql_query(" select a.bo_table, a.wr_parent, max(a.bn_id) as bn_id, max(a.wr_id) as wr_id FROM {$g4['board_new_table']} as a inner join {$g4['board_new_table']} as b on b.mb_id = '{$member['mb_id']}' where a.wr_parent = b.wr_id and a.bo_table = b.bo_table and a.mb_id != '{$member['mb_id']}' group by b.bn_id, b.bo_table order by bn_id desc limit 0, $rows ");
				} else {
					$result = '';
				}
			} else if($opt['type'] == "newcmtgul") {
				$tab[$z]['title'] = '새로 댓글달린 글';
				$tab[$z]['href'] = G4_BBS_URL.'/new.php?view=c';

				$result = sql_query(" select bo_table, wr_parent, max(bn_id) as bn_id from {$g4['board_new_table']} where bo_table != '' and wr_id <> wr_parent $new_sql $mode_sql group by bo_table, wr_parent order by bn_id desc limit 0, $rows ");
			} else {
				$tab[$z]['title'] = '새로 등록된 글';
				$tab[$z]['href'] = G4_BBS_URL.'/new.php?view=w';

				$result = sql_query(" select bo_table, wr_parent, bn_id from {$g4['board_new_table']} where  bo_table != '' and wr_id = wr_parent $new_sql $mode_sql order by bn_id desc limit 0, $rows ");
			}

			for ($i=0; $row=sql_fetch_array($result); $i++) {

				if (!$row['bo_table']) continue;

				$tmp_write_table = $g4['write_prefix'] . $row['bo_table']; // 게시판 테이블 전체이름
				$board = sql_fetch(" select * from {$g4['board_table']} where bo_table = '{$row['bo_table']}' ");

				if (!$board) continue;

				$row1 = sql_fetch(" select * from {$tmp_write_table} where wr_id = '{$row['wr_parent']}' "); //글 정보 불러오기..
				$row1['bo_table'] = $board['bo_table'];
				$row1['ca_name'] = $board['bo_subject']; //게시판 제목을 카테고리로 사용..
				if(strstr($row1['wr_option'], "secret")) $row1['wr_content'] = '비밀글입니다.';
				$list[$i] = amina_get_list($row1, $board, $latest_skin_url, $subject_len);
			}
		}

	} else {

		// 제외 분류 설정
		$ex_sql = '';
		if($opt['ca_exclude']) {
			$ca_ex = explode(";", $opt['ca_exclude']);
			for ($k=0; $k < count($ca_ex); $k++) {

				if (!$ca_ex[$k]) continue;

				$ex_sql .= " and ca_name != '$ca_ex[$k]' ";
			}
		} 

		//mode 설정
		switch($opt['mode']) {
			case 'text'		: $mode_sql = "and wr_10 like '%text%' "; break;
			case 'photo'	: $mode_sql = "and wr_10 like '%photo%' "; break;
			case 'video'	: $mode_sql = "and wr_10 like '%video%' "; break;
			case 'rss'		: $mode_sql = "and wr_10 like '%rss%' "; break;
			case 'main'		: $mode_sql = "and wr_10 like '%main%' "; break;
			case 'good'		: $mode_sql = "and wr_10 like '%good%' "; break;
			default			: $mode_sql = ""; break;
		}

		// sql 추가조건 결정
		if($sql_opt) $sql_opt = " and ".$sql_opt." ";

		// 추출기간 설정
		if($opt['term']) {
			$time = time();
			list($endDay, $startDay) = explode(";", $opt['term']);
			if($startDay > 0) {
				$nowYmd = date("Ymd",strtotime("-".$startDay." day", $time)); 
				$endDay = $startDay + $endDay - 1;
				$startYmd = date("Ymd",strtotime("-".$endDay." day", $time)); 
			} else {
				$nowYmd = date(Ymd); # 시작시간을 구합니다.
				$time = time(); 
				$endDay = $endDay - 1;
				$startYmd = date("Ymd",strtotime("-".$endDay." day", $time)); 
			}

			//비밀글 제외함
			$sql_term = " and wr_option not like '%secret%' and date_format(wr_datetime, '%Y%m%d') between '$startYmd' and '$nowYmd' ";
		}

		// 정렬방법
		$rank = 1;
		$order_by = '';
		if($opt['order']) {
			$order_list = explode(";", $opt['order']);
			if($order_list[0] == "rdm") {
				$order_by = ' rand() ';
			} else {
				$o = 0;
				for ($i=0; $i < count($order_list); $i++) {

					if (!$order_list[$i]) continue;
					
					switch($order_list[$i]) {
						case 'hit'			: $order_by .= ' wr_hit desc, '; break;
						case 'good'			: $order_by .= ' wr_good desc, '; break;
						case 'nogood'		: $order_by .= ' wr_nogood desc, '; break;
						case 'goodgap'		: $order_by .= ' (wr_good - wr_nogood) desc, '; break;
						case 'nogoodgap'	: $order_by .= ' (wr_nogood - wr_good) desc, '; break;
						case 'cmt'			: $order_by .= ' wr_comment desc, '; break;
					}
				}

				if($order_by) $order_by = substr($order_by,0,-2);
			}
		}

		// 글과 댓글 구분하기
		$post_type = ($opt['type'] == "cmt") ? 'wr_is_comment=1' : 'wr_is_comment=0';

		// 복수게시판에서 추출
		if($opt['gr_list']) { //그룹추출
			$opt['bo_list'] = '';
			$gr_sql = '';
			$gr_bo = explode(";", $opt['gr_list']);
			for ($i=0; $i < count($gr_bo); $i++) {

				if (!$gr_bo[$i]) continue;

				$gr_sql .= " gr_id = '$gr_bo[$i]' or ";
			}

			if($gr_sql) $gr_sql = substr($gr_sql,0,-3);

			$gr_result = sql_query(" select bo_table from {$g4['board_table']} where $gr_sql ");
			for ($i=0; $row=sql_fetch_array($gr_result); $i++) {

				if (!$row['bo_table']) continue;

				$opt['bo_list'] .= $row['bo_table'].';';
			}

			if($opt['bo_list']) $opt['bo_list'] = substr($opt['bo_list'],0,-1);

		}

		$arr_bo = explode(";", $opt['bo_list']);

		$bo_num = count($arr_bo);

		// 복수 게시판일 경우
		if($bo_num > 1) {

			if(!$order_by) $order_by = ' wr_datetime desc ';
			
			$tmp = '';
			for($i=0; $i < $bo_num; $i++){ 
				
				if (!$arr_bo[$i]) continue;

				//필드수가 다를 경우 오류방지를 위해 매칭필드 직접 지정
				$tmp_write_table = $g4['write_prefix'] . $arr_bo[$i];
                $tmp_sql = $tmp_write_table.'.wr_id, ';
				$tmp_sql .= $tmp_write_table.'.wr_parent, ';
				$tmp_sql .= $tmp_write_table.'.wr_num, ';
                $tmp_sql .= $tmp_write_table.'.wr_reply, ';
                $tmp_sql .= $tmp_write_table.'.wr_comment, ';
                $tmp_sql .= $tmp_write_table.'.wr_option, ';
                $tmp_sql .= $tmp_write_table.'.wr_subject, ';
				$tmp_sql .= $tmp_write_table.'.wr_content, ';
                $tmp_sql .= $tmp_write_table.'.wr_link1, ';
                $tmp_sql .= $tmp_write_table.'.wr_link2, ';
                $tmp_sql .= $tmp_write_table.'.wr_link1_hit, ';
                $tmp_sql .= $tmp_write_table.'.wr_link2_hit, ';
                $tmp_sql .= $tmp_write_table.'.wr_hit, ';
                $tmp_sql .= $tmp_write_table.'.wr_good, ';
                $tmp_sql .= $tmp_write_table.'.wr_nogood, ';
                $tmp_sql .= $tmp_write_table.'.mb_id, ';
                $tmp_sql .= $tmp_write_table.'.wr_name, ';
                $tmp_sql .= $tmp_write_table.'.wr_email, ';
                $tmp_sql .= $tmp_write_table.'.wr_homepage, ';
                $tmp_sql .= $tmp_write_table.'.wr_datetime, ';
                $tmp_sql .= $tmp_write_table.'.wr_1, ';
                $tmp_sql .= $tmp_write_table.'.wr_2, ';
                $tmp_sql .= $tmp_write_table.'.wr_3, ';
                $tmp_sql .= $tmp_write_table.'.wr_4, ';
                $tmp_sql .= $tmp_write_table.'.wr_5, ';
                $tmp_sql .= $tmp_write_table.'.wr_6, ';
                $tmp_sql .= $tmp_write_table.'.wr_7, ';
                $tmp_sql .= $tmp_write_table.'.wr_8, ';
                $tmp_sql .= $tmp_write_table.'.wr_9, ';
                $tmp_sql .= $tmp_write_table.'.wr_10';

				$tmp .= " select '{$arr_bo[$i]}' as bo_table, $tmp_sql from $tmp_write_table where $post_type $sql_opt $sql_term $mode_sql $ex_sql UNION ALL ";
			}

			if($tmp) $tmp = "select * from ( ".substr($tmp,0,-10).") as a order by $order_by limit 0, $rows";

			$result = sql_query($tmp);
			for ($i=0; $row=sql_fetch_array($result); $i++){ 
				$sql = "select * from {$g4['board_table']} where bo_table='{$row['bo_table']}'";
				$board = sql_fetch($sql);

				if (!$board) continue;

				$row['bo_table'] = $board['bo_table'];
				$row['ca_name'] = $board['bo_subject']; //게시판 제목을 카테고리로 사용..
				if($opt['order']) {
					$row['wr_rank'] = $rank;
					$rank++;
				}
				if($opt['type'] == "cmt") {
					//원글
					$row1 = sql_fetch(" select wr_subject, wr_comment, ca_name, wr_option from $tmp_write_table where wr_id = '{$row['wr_parent']}' ");
					if(strstr($row1['wr_option'], "secret") || strstr($row['wr_option'], "secret")) {
						$row['wr_subject'] = $row['wr_content'] = '비밀 댓글입니다.';
						if(strstr($row1['wr_option'], "secret")) $row['wr_option'] = $row1['wr_option'];
					}
					$row['bo_table'] = $board['bo_table'];
					$row['ca_name'] = $board['bo_subject']; //게시판 제목을 카테고리로 사용..
					$row['wr_post'] = $row1['wr_subject']; //원글제목
					$row['wr_post_cmt'] = $row1['wr_comment']; //원글 댓글수
				} else {
					if(strstr($row['wr_option'], "secret")) $row['wr_content'] = '비밀글입니다.';
				}
				$list[$i] = amina_get_list($row, $board, $latest_skin_url, $subject_len, $opt['type']);
			} 

			$tab[$z]['href'] = '#';
			$tab[$z]['title'] = '제목입력';

		} else {

			if(!$order_by) $order_by = ' wr_id desc ';

			if($opt['bo_list']) list($bo_table) = explode(";", $opt['bo_list']);

			$tab[$z]['href'] = G4_BBS_URL.'/board.php?bo_table='.$bo_table;
			if($opt['ca_name']) $tab[$z]['href'] = $tab[$z]['href'].'&sca='.urlencode($opt['ca_name']);

			//일반 게시물 추출
		    $sql = " select * from {$g4['board_table']} where bo_table = '$bo_table' ";
		    $board = sql_fetch($sql);

			if(!$board || !$bo_table) {
				$tab[$z]['title'] = '미등록 게시판';
			} else {
				$tmp_write_table = $g4['write_prefix'] . $bo_table; // 게시판 테이블 전체이름

				if($opt['ca_name']) $sql_ca = " and ca_name = '{$opt['ca_name']}' ";

				$i = 0;
				if($opt['type'] == "notice" || $opt['type'] == "nonotice") {
					$notice_sql = '';
					if(AMINA == "g4s") {
					    $arr_notice = explode(",", trim($board['bo_notice']));
					} else {
					    $arr_notice = explode("\n", trim($board['bo_notice']));
					}
					if($opt['type'] == "notice") {
						for ($k=0; $k<count($arr_notice); $k++) {
							if (trim($arr_notice[$k])=='') continue;
							$row = sql_fetch(" select * from $tmp_write_table where wr_id = '$arr_notice[$k]' $sql_ca $sql_opt $mode_sql $ex_sql");
						    if (!$row['wr_id']) continue;
							$list[$i] = amina_get_list($row, $board, $latest_skin_url, $subject_len, $opt['type']);
							$list[$i]['is_notice'] = true;
							if($opt['ca_name']) $list[$i]['href'] = $list[$i]['href']."&sca=".urlencode($opt['ca_name']);
							$notice_sql .= " and wr_id != '$arr_notice[$k]' "; 
							$i++;
						}

						$rows = $rows - $i;
					} else { //공지는 출력안함
						for ($k=0; $k<count($arr_notice); $k++) {
							if (trim($arr_notice[$k])=='') continue;
							$notice_sql .= " and wr_id != '$arr_notice[$k]' "; 
						}
					}
					$sql = " select * from $tmp_write_table where $post_type $sql_ca $notice_sql $sql_opt $sql_term $mode_sql $ex_sql order by $order_by limit 0, $rows ";
				} else {
					$sql = " select * from $tmp_write_table where $post_type $sql_ca $sql_opt $sql_term $mode_sql $ex_sql order by $order_by limit 0, $rows ";
				}

				$result = sql_query($sql);
				for ($i=$i; $row = sql_fetch_array($result); $i++) { 
					if($opt['order']) {
						$row['wr_rank'] = $rank;
						$rank++;
					}

					if($opt['type'] == "cmt") {
						//원글
						$row1 = sql_fetch(" select wr_subject, wr_comment, ca_name, wr_option from $tmp_write_table where wr_id = '{$row['wr_parent']}' ");
						if(strstr($row1['wr_option'], "secret") || strstr($row['wr_option'], "secret")) {
							$row['wr_subject'] = $row['wr_content'] = '비밀 댓글입니다.';
							if(strstr($row1['wr_option'], "secret")) $row['wr_option'] = $row1['wr_option'];
						}
						$row['ca_name'] = $row1['ca_name'];
						$row['wr_post'] = $row1['wr_subject']; //원글제목
						$row['wr_post_cmt'] = $row1['wr_comment']; //원글 댓글수
					} else {
						if(strstr($row['wr_option'], "secret")) $row['wr_content'] = '비밀글입니다.';
					}
					$list[$i] = amina_get_list($row, $board, $latest_skin_url, $subject_len, $opt['type']);
					if($opt['ca_name']) $list[$i]['href'] = $list[$i]['href'].'&sca='.urlencode($opt['ca_name']);
				}

				$tab[$z]['title'] = $board['bo_subject'];
			}
		}
	}


	$tab[$z]['title'] = $opt['title'] ? $opt['title'] : $tab[$z]['title'];
	if($opt['head_href']) {
		$tab[$z]['href'] = str_replace("~", "=", $opt['head_href']);
	} else {
		$tab[$z]['href'] = ($opt['head_more'] == "none") ? '#' : $tab[$z]['href'];
	}
	$tab[$z]['new_icon'] = $opt['new_icon'] ? $opt['new_icon'] : 'old';

	$latest_amina = 'ok';

    ob_start();
	if(!$opt['tab']) include_once(AMINA_PATH.'/css.php'); 
	include $latest_skin_path.'/latest.skin.php';
    $content = ob_get_contents();
    ob_end_clean();

    return $content;
} 

function latest_amina_tab($skin_dir, $type, $main_id, $page_name, $options="", $tab_list="") {
    global $g4, $is_admin;

    $list = array();
	$tab = array();
	$opt = array();

	$opt = amina_query($options);

	$tab_cnt = count($tab_list);
	for ($i=0; $i < $tab_cnt; $i++) {

		$list = amina_query($tab_list[$i]);

		$tab[$i]['tab_id'] = $list['tab_id'];
		$tab[$i]['href'] = G4_URL.'/index.php?page_name='.$page_name.'&tab_id='.$list['tab_id'].'&frame=1&first_view=no';
		if($i == 0) $tab[$i]['href'] = '#';
		$tab[$i]['title'] = $list['title'];
		$tab[$i]['title_off'] = $list['title_off'] ? $list['title_off'] : $tab[$i]['title'];
		$tab[$i]['new_icon'] = $opt['new_icon'] ? $opt['new_icon'] : 'old';
		$tab[$i]['num'] = $i + 1;
	}

	//스킨디렉토리
	$latest_skin_path = G4_SKIN_PATH."/latest/".$skin_dir;
	$latest_skin_url = G4_SKIN_URL."/latest/".$skin_dir;

    ob_start();
    include $latest_skin_path.'/latest.tab.php';
    $content = ob_get_contents();
    ob_end_clean();

    return $content;
} 

// New Post
function new_cnt($bo_list, $ca_name='', $head='', $tail='') {
    global $g4;

	$bo = explode(";", trim($bo_list));
	$num = count($bo);

	$ca_name = $ca_name ? "and ca_name = '{$ca_name}'" : "";

	//새글 체크하기
	$cnt = 0;
	for ($i=0; $i < $num; $i++) {
		$bo_table = trim($bo[$i]);

		if(!$bo_table) continue;

		$board = sql_fetch("select * from {$g4['board_table']} where bo_table = '{$bo_table}'");

		if(!$board) continue;

		$row = sql_fetch("select count(wr_id) as cnt from ".$g4['write_prefix'].$bo_table." where wr_is_comment=0 $ca_name and wr_datetime >= '".date("Y-m-d H:i:s", G4_SERVER_TIME - ($board['bo_new'] * 3600))."'");
		$cnt = $cnt + $row['cnt'];
	}

	$new_post = ($cnt > 0) ? $head.$cnt.$tail : '';

	return $new_post;
}

// goo.gl 짧은주소 만들기 - G4S 함수 : SNS 동시 등록 플러그인용
if (!function_exists('googl_short_url')) {
	function googl_short_url($longUrl) {
	    global $config;

	    // Get API key from : http://code.google.com/apis/console/
	    // URL Shortener API ON
		$apiKey = $config['cf_googl_shorturl_apikey'];

	    $postData = array('longUrl' => $longUrl, 'key' => $apiKey);
	    $jsonData = json_encode($postData);

	    $curlObj = curl_init();

	    curl_setopt($curlObj, CURLOPT_URL, 'https://www.googleapis.com/urlshortener/v1/url');
	    curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
	    curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0);
	    curl_setopt($curlObj, CURLOPT_HEADER, 0);
	    curl_setopt($curlObj, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
	    curl_setopt($curlObj, CURLOPT_POST, 1);
	    curl_setopt($curlObj, CURLOPT_POSTFIELDS, $jsonData);

	    $response = curl_exec($curlObj);

	    //change the response json string to object
		$json = json_decode($response);

	    curl_close($curlObj);

	    return $json->id;
	}
}

// UTF-8 문자열 자르기 - G4S 함수 : SNS 동시 등록 플러그인용
// 출처 : https://www.google.co.kr/search?q=utf8_strcut&aq=f&oq=utf8_strcut&aqs=chrome.0.57j0l3.826j0&sourceid=chrome&ie=UTF-8
if (!function_exists('utf8_strcut')) {
	function utf8_strcut( $str, $size, $suffix='...' ) {
        $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 .= $suffix;
        }

        return $str;
	}
}

function daum_view($nid, $type='t') {

	if(!$nid) return;

	/* old
		$css = ' quality="high" bgcolor="#ffffff" type="application/x-shockwave-flash"';
		case 'l'	: $dv = '<div class="daum-view"><embed src="http://api.v.daum.net/static/recombox1.swf?nid='.$nid.'" width="400" height="80"'.$css.'></embed></div>'; break;
		case 'm'	: $dv = '<div class="daum-view"><embed src="http://api.v.daum.net/static/recombox2.swf?nid='.$nid.'" width="400" height="58"'.$css.'></embed></div>'; break;
		case 's'	: $dv = '<div class="daum-view"><embed src="http://api.v.daum.net/static/recombox3.swf?nid='.$nid.'" width="67" height="80"'.$css.'></embed></div>'; break;
		case 't'	: $dv = '<div class="daum-view"><embed src="http://api.v.daum.net/static/recombox4.swf?nid='.$nid.'" width="82" height="21"'.$css.'></embed></div>'; break;
	*/

	switch($type) {
		case 'l'	: $dv = '<div class="daum-view"><iframe width="100%" height="90" src="http://api.v.daum.net/widget1?nid='.$nid.'" frameborder="no" scrolling="no" allowtransparency="true"></iframe></div>'; break;
		case 'm'	: $dv = '<div class="daum-view"><iframe width="76" height="90" src="http://api.v.daum.net/widget2?nid='.$nid.'" frameborder="no" scrolling="no" allowtransparency="true"></iframe></div>'; break;
		case 's'	: $dv = '<div class="daum-view"><iframe width="136" height="44" src="http://api.v.daum.net/widget3?nid='.$nid.'" frameborder="no" scrolling="no" allowtransparency="true"></iframe></div>'; break;
		default		: $dv = '<div class="daum-view"><iframe width="112" height="30" src="http://api.v.daum.net/widget4?nid='.$nid.'" frameborder="no" scrolling="no" allowtransparency="true"></iframe></div>'; break;
	}

	return $dv;
}

function chk_menu_exclude($arr, $item) {

	$item = trim($item);

	if($arr && $item) {
		for ($i=0; $i<count($arr); $i++) { 

			$chk_item = trim($arr[$i]);

			if($chk_item == "") continue;

			if($chk_item == $item) return true;
		}
	}

	return false;
}

function amina_menu($gr_id, $bo_table, $gr_exclude, $bo_exclude, $newpost='') {
	global $g4;

	$list = array();
	$board = array();

	$gr_exclude = explode(";",$gr_exclude);
	$bo_exclude = explode(";",$bo_exclude);

	if(AMINA == "g4s") {
		$gr_order = 'gr_order';
		$gr_show = "and gr_show_menu = '1' ";
		$bo_order = 'bo_order';
		$bo_show = "and bo_show_menu = '1' ";
		$bo_search = "and bo_use_search = '1'";
	} else {
		$gr_order = 'gr_10';
		$gr_show = "and gr_10 != ''";
		$bo_order = 'bo_order_search';
		$bo_show = "";
		$bo_search = "and bo_use_search = '1'";
	}

	//첫번째 배열(0번)은 전체통계로 사용
	$z = 1;
	$count_write = 0;
	$count_comment = 0;
	$sql = " select gr_id, gr_subject from {$g4['group_table']} where 1 $gr_show order by $gr_order ";
	$result = sql_query($sql);
	for ($i=0; $row=sql_fetch_array($result); $i++) {

		$gr_new = 0;
		$gr_count_write = 0;
		$gr_count_comment = 0;

		if(chk_menu_exclude($gr_exclude, $row['gr_id'])) continue;

		//게시판 정리
		$sql2 = " select bo_table, bo_subject, bo_count_write, bo_count_comment from {$g4['board_table']} where gr_id = '{$row['gr_id']}' $bo_show order by $bo_order ";
		$result2 = sql_query($sql2);
		$ressult2_cnt = mysql_num_rows($result2);
		$n = 0;
		for ($k=0; $row2=sql_fetch_array($result2); $k++) {

			if(chk_menu_exclude($bo_exclude,$row2['bo_table'])) continue;

			$board[$n] = $row2;
			$n++;
		}
		
		for ($k=0; $k < count($board); $k++) {

			$list[$z]['board'][$k]['gr_id'] = $row['gr_id']; //그룹 아이디
			$list[$z]['board'][$k]['bo_table'] = $board[$k]['bo_table']; //게시판 아이디
			$list[$z]['board'][$k]['bo_subject'] = $board[$k]['bo_subject']; //게시판 제목
			$list[$z]['board'][$k]['bo_count_write'] = $board[$k]['bo_count_write']; //글갯수
			$list[$z]['board'][$k]['bo_count_comment'] = $board[$k]['bo_count_comment']; //댓글갯수
			$list[$z]['board'][$k]['bo_href'] = G4_BBS_URL.'/board.php?bo_table='.$board[$k]['bo_table']; //링크
			$list[$z]['board'][$k]['bo_on'] = ($board[$k]['bo_table'] == $bo_table) ? 'on' : 'off'; //현재 선택게시판인지 표시
			$list[$z]['board'][$k]['bo_new'] = new_menu($board[$k]['bo_table'], $newpost);
			if($list[$z]['board'][$k]['bo_new'] == 'new') $gr_new++; //새글이 있는지 체크

			$gr_count_write = $gr_count_write + $board[$k]['bo_count_write'];
			$gr_count_comment = $gr_count_comment + $board[$k]['bo_count_comment'];
		}

		//그룹정리
		$list[$z]['gr_id'] = $row['gr_id']; //그룹 아이디
		$list[$z]['gr_subject'] = $row['gr_subject']; //그룹 제목
		$list[$z]['gr_count_write'] = $gr_count_write; //글갯수
		$list[$z]['gr_count_comment'] = $gr_count_comment; //댓글갯수
		$list[$z]['gr_on'] = ($list[$z]['gr_id'] == $gr_id) ? 'on' : 'off'; //현재 선택 그룹인지 표시
		$list[$z]['gr_new'] = ($gr_new > 0) ? 'new' : 'old'; //새글이 있는지 체크

		$count_write = $count_write + $gr_count_write;
		$count_comment = $count_comment + $gr_count_comment;

		$z++;

		unset($board);
	}

	//전체 통계
	$list[0]['count_write'] = $count_write; //글갯수
	$list[0]['count_comment'] = $count_comment; //댓글갯수

	return $list;
}

// 사이트 통계 - 방문자수 출력
function amina_stats() {
    global $g4, $config;

	$lnb = array();

    // visit 배열변수에 $visit[1] = 오늘, $visit[2] = 어제, $visit[3] = 최대, $visit[4] = 전체 숫자가 들어감
    preg_match("/오늘:(.*),어제:(.*),최대:(.*),전체:(.*)/", $config['cf_visit'], $visit);
    settype($visit[0], "integer");
    settype($visit[1], "integer");
    settype($visit[2], "integer");
    settype($visit[3], "integer");

	$lnb['visit_today'] = $visit[1];
	$lnb['visit_yesterday'] = $visit[2];
	$lnb['visit_max'] = $visit[3];
	$lnb['visit_total'] = $visit[4];

	//현재 접속자
    $row = sql_fetch(" select sum(IF(mb_id<>'',1,0)) as mb_cnt, count(*) as total_cnt from {$g4['login_table']} where mb_id <> '{$config['cf_admin']}' ");
	if(!$row['mb_cnt']) $row['mb_cnt'] = 0;

	$lnb['now_total'] = $row['total_cnt'];
	$lnb['now_mb'] = $row['mb_cnt'];

	//오늘 가입자
	$row = sql_fetch(" select count(*) as cnt from {$g4['member_table']} where left(mb_datetime,10) = '".date("Y-m-d", time())."' "); 
	$lnb['join_today'] = $row['cnt'];

	//어제 가입자
	//$row = sql_fetch(" select count(*) as cnt from {$g4['member_table']} where left(mb_datetime,10) = '".date("Y-m-d", time()-86400)."' "); 
	//$lnb['join_yesterday'] = $row['cnt'];

	//전체회원
	$row = sql_fetch(" select count(*) as cnt from {$g4['member_table']} "); 
	$lnb['join_total'] = $row['cnt'];

    return $lnb;
}

// 임시 저장된 글 갯수
if (!function_exists('autosave_count')) {
	function autosave_count($mb_id) {
	    global $g4;

		if ($mb_id) {
	        $row = sql_fetch(" select count(*) as cnt from {$g4['autosave_table']} where mb_id = '$mb_id' ");
	        return (int)$row['cnt'];
	    } else {
	        return 0;
	    }
	}
}

// file_put_contents 는 PHP5 전용 함수이므로 PHP4 하위버전에서 사용하기 위함
// http://www.phpied.com/file_get_contents-for-php4/
if (!function_exists('file_put_contents')) {
    function file_put_contents($filename, $data) {
        $f = @fopen($filename, 'w');
        if (!$f) {
            return false;
        } else {
            $bytes = fwrite($f, $data);
            fclose($f);
            return $bytes;
        }
    }
}

// 기존의 get_unique_id() 함수를 사용하지 않고 get_uniqid() 를 사용한다.
if (!function_exists('get_uniqid')) {
	function get_uniqid() {
	    global $g4;

	    sql_query(" LOCK TABLE {$g4['uniqid_table']} WRITE ");
	    while (1) {
		    // 년월일시분초에 100분의 1초 두자리를 추가함 (1/100 초 앞에 자리가 모자르면 0으로 채움)
	        $key = date('ymdHis', time()) . str_pad((int)(microtime()*100), 2, "0", STR_PAD_LEFT);

		    $result = sql_query(" insert into {$g4['uniqid_table']} set uq_id = '$key', uq_ip = '{$_SERVER['REMOTE_ADDR']}' ", false);
	        if ($result) break; // 쿼리가 정상이면 빠진다.

		    // insert 하지 못했으면 일정시간 쉰다음 다시 유일키를 만든다.
	        usleep(10000); // 100분의 1초를 쉰다
	    }
		sql_query(" UNLOCK TABLES ");

	    return $key;
	}
}

// 마일리지 부여 - 포인트 테이블 응용
function amina_insert_mileage($mb_id, $from_id, $point, $content='', $rel_table='', $rel_id='', $rel_action='') {
    global $g4, $config, $amina, $is_admin;

    // 마일리지를 사용을 하지 않는다면 return
    if (!$amina['mileage']) { return 0; }

    // 포인트가 없다면 업데이트 할 필요 없음
    if ($point == 0) { return 0; }

    // 회원아이디가 없다면 업데이트 할 필요 없음
    if ($mb_id == '') { return 0; }
    $mb = sql_fetch(" select mb_id from {$g4['member_table']} where mb_id = '$mb_id' ");
    if (!$mb['mb_id']) { return 0; }

    // 이미 등록된 내역이라면 건너뜀
    if ($from_id || $rel_table || $rel_id || $rel_action) {
        $sql = " select count(*) as cnt from {$g4['amina_mileage']}
                  where mb_id = '$mb_id'
					and from_id = '$from_id'
					and po_rel_table = '$rel_table'
                    and po_rel_id = '$rel_id'
                    and po_rel_action = '$rel_action' ";
        $row = sql_fetch($sql);
        if ($row['cnt'])
            return -1;
    }

    // 마일리지 건별 생성
    $sql = " insert into {$g4['amina_mileage']}
                set mb_id = '$mb_id',
                    from_id = '$from_id',
					po_datetime = '".G4_TIME_YMDHIS."',
                    po_content = '".addslashes($content)."',
                    po_point = '$point',
                    po_rel_table = '$rel_table',
                    po_rel_id = '$rel_id',
                    po_rel_action = '$rel_action' ";
    sql_query($sql);

    // 마일리지 내역의 합을 구하고
    $sql = " select sum(po_point) as sum_po_point from {$g4['amina_mileage']} where mb_id = '$mb_id' ";
    $row = sql_fetch($sql);
    $sum_point = $row['sum_po_point'];

    // 마일리지 UPDATE(회원 여분필드 7번사용)
    $sql = " update {$g4['member_table']} set mb_7 = '$sum_point' where mb_id = '$mb_id' ";
    sql_query($sql);

    return 1;
}

// 마일리지 삭제
function amina_delete_mileage($mb_id, $from_id, $rel_table, $rel_id, $rel_action) {
    global $g4;

    $result = false;
    if ($rel_table || $rel_id || $rel_action)
    {
        $result = sql_query(" delete from {$g4['amina_mileage']}
                     where mb_id = '$mb_id'
                       and from_id = '$from_id'
					   and po_rel_table = '$rel_table'
                       and po_rel_id = '$rel_id'
                       and po_rel_action = '$rel_action' ", false);

        // 마일리지 내역의 합을 구하고
        $sql = " select sum(po_point) as sum_po_point from {$g4['amina_mileage']} where mb_id = '$mb_id' ";
        $row = sql_fetch($sql);
        $sum_point = $row['sum_po_point'];

        // 마일리지 UPDATE(회원 여분필드 7번 사용)
        $sql = " update {$g4['member_table']} set mb_7 = '$sum_point' where mb_id = '$mb_id' ";
        $result = sql_query($sql);
    }

    return $result;
}

// HTML 마지막 처리
if (!function_exists('html_end')) {
	function html_end() {
	    global $config, $g4, $member;

	    // 버퍼의 내용에서 body 태그 중간의 외부 css 파일을 CAPTURE 하여 head 태그로 이동시켜준다.
	    $buffer = ob_get_contents();
	    ob_end_clean();
	    preg_match('#<body>(.*)</body>#is', $buffer, $bodys);
	    preg_match_all('/(\r|\n)?<link[^>]+>/i', $bodys[0], $links);
	    $stylesheet = '';
	    $links[0] = array_unique($links[0]);
	    foreach ($links[0] as $key=>$link) {
		    //$link = PHP_EOL.$links[0][$i];
	        $stylesheet .= $link;
		    $buffer = preg_replace('#'.$link.'#', '', $buffer);
	    }
		/*
	    </title>
		<link rel="stylesheet" href="default.css">
	    밑으로 스킨의 스타일시트가 위치하도록 하게 한다.
		*/
	    return preg_replace('#(</title>[^<]*<link[^>]+>)#', "$1$stylesheet", $buffer);
	}
}

//확장자 파악하기
function amina_getExt($str) {
		$f = explode(".", $str);
		$l=sizeof($f);
		if($l>1) {
				return strtolower($f[$l-1]);
		} else {
				return '';
		}
}

?>