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

// 아미나스킨 체크
function is_amina($skin) {
	$is_amina = 'amina';
	return preg_match('/('.$is_amina.')/i', $skin);
}
// 모바일 체크
function amina_mobile() {
	return preg_match('/'.G5_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));

}

// 보안서버 주소 파악
function amina_https($dir, $https=true) {
    if ($https) {
        if (G5_HTTPS_DOMAIN) {
            $url = G5_HTTPS_DOMAIN.'/'.$dir;
        } else {
            $url = G5_URL.'/'.$dir;
        }
    } else {
        if (G5_DOMAIN) {
            $url = G5_DOMAIN.'/'.$dir;
        } else {
            $url = G5_URL.'/'.$dir;
        }
    }

    return $url;
}

// 아미나설정값 로딩
function load_amina_setting($amina, $bo_table, $bo_skin, $m_skin, $sca) {
	global $g5, $frame, $pv_skin;

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

	if($pv_skin) {
		$sca = $pv_skin;
	} else {
		$sca = ($frame == "linked") ? '연동보드' : $sca;
	}

	if(AMINA) { //G5 & G4S
		if(G5_IS_MOBILE && is_amina($m_skin)) { //mobile
			$func = sql_fetch(" select * from {$g5['amina']} where bo_table='$bo_table' ", false);
			if($sca) {
				$skin = sql_fetch(" select * from {$g5['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 {$g5['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 {$g5['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 {$g5['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 {$g5['amina']} where bo_table='$bo_table' ", false);
				if($sca) {
					$skin = sql_fetch(" select * from {$g5['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 {$g5['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 {$g5['amina']} where bo_table='$bo_table' ", false);
			if(G5_IS_MOBILE) { //mobile
				if($sca) {
					$skin = sql_fetch(" select * from {$g5['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 {$g5['amina_skin']} where bo_table='$bo_table' and skin_type = '2' and sca = '' ", false);
				}
			} 
			if(!$skin) { //pc
				if($sca) {
					$skin = sql_fetch(" select * from {$g5['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 {$g5['amina_skin']} where bo_table='$bo_table' and skin_type = '0' and sca = '' ", false);
				}
			}
		} else {
			if(G5_IS_MOBILE) { //mobile
				if($sca) {
					$skin = sql_fetch(" select * from {$g5['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 {$g5['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'], $set['subj_icon'], $set['post_ccl'], $set['img_except']) = 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'], $set['movie_sound'], $set['movie_caption']) = 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'].' sound='.$set['movie_sound'].' caption='.$set['movie_caption'];
	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'], $set['po_wr_type'], $set['po_wr_table'], $set['po_wr_id'], $set['wr_copy']) = 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));

	$tab_cnt = count($tab);

	for($i=0; $i < $tab_cnt; $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;
}

// Selected
function amina_selected($field, $value) {
    return ($field==$value) ? ' selected="selected"' : '';
}

// Checked
function amina_checked($field, $value) {
    return ($field==$value) ? ' checked="checked"' : '';
}

// 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;
}

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

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

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

    $sec_diff = G5_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();

			$tmp_cnt = count($tmp_array);

		    for($i=0;$i < $tmp_cnt; $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 {$g5['amina_cache']} set c_text = '$c_text1', c_datetime='".G5_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 = G5_URL.'/';
		$path = G5_PATH.'/';
		$file = str_replace($path,$url,$file);
	}

	return $file;
}

// 로그인 후 이동할 URL
function amina_login_url($url='') {

	if($url) {
		$url = urldecode($url);
		$url = str_replace("./", G5_URL, $url);
	} else {
		$url = G5_URL;
	}

	$url = urlencode($url);

    return $url;
}

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

	if(!$type) {
		return $longUrl;
	}

	if($type == "1") {
		$shortUrl = ($bo_table && $wr_id) ? G5_URL.'/'.$bo_table.'/'.$wr_id : $longUrl;
		return $shortUrl;

	} else if($type == "2" || $type == "bitly") {

		if(!$amina['bitly_id'] || !$amina['bitly_key']) {
			return $longUrl;
		}

		$bitly = 'http://api.bit.ly/shorten?version=2.0.1&longUrl='.urlencode($longUrl).'&login='.$amina['bitly_id'].'&apiKey='.$amina['bitly_key'].'&format=json&history=1';
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_URL, $bitly); 
		$data = curl_exec($ch);
		curl_close($ch); 

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

		return $url;

	} else if($type == "3" || $type == "google") {

		if(!$amina['googl_key']) {
			return $longUrl;
		}

		$postData = array('longUrl' => $longUrl, 'key' => $amina['googl_key']);
		$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 $longUrl;
}

// 경고메세지를 경고창으로
function amina_alert($msg='', $url='') {
    global $g5;

    if (!$msg) $msg = '올바른 방법으로 이용해 주십시오.';

	echo "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\">";
	echo "<script type='text/javascript'>";
	echo "alert('$msg');";
	if($url == '' || $url == 'fbox' || $url == 'close') {
		if($url = 'back') {
			echo "history.go(-1);";
		} else if($url == 'close') {
			echo "window.close();";
		} else {
			echo "parent.jQuery.fancybox.close();";
		}
		echo "</script>";
	} else {
		echo "</script>";
		goto_url($url);
	}
    exit;
}

// JWPlayer List
function amina_jwplayer_list($url) {

	if(!$url) return;

	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	@curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);    
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_TIMEOUT, 10);
	$xml = trim(curl_exec($ch));
	curl_close($ch);

	if(!$xml) return;

	preg_match_all("/<item>(.*)<\/item>/iUs", $xml, $matchs);

	return count($matchs[1]);
}

// JWPlayer
function amina_jwplayer($file, $img='', $caption=''){
	global $g5, $amina;
	
	if(!$file) return;

	$video = array("mp4", "m4v", "f4v", "mov", "flv", "webm");
	$audio = array("acc", "m4a", "f4a", "mp3", "ogg", "oga");
	$ext = amina_getExt($file);
	if($ext == "rss") {
		$is_type = 'plist';
		$cnt = amina_jwplayer_list($file);
		if($cnt > 0) {
			;
		} else {
			return;
		}
	} else if(in_array($ext, $audio)) {
		$is_type = 'audio';
	} else if(in_array($ext, $video)) {
		$is_type = 'video';
	} else {
		return;
	}

	if($img == 'check') return $is_type;

	$jwplayer = '';	
	if(!$g5['amina_ajax'] && !defined('AMINA_JWPLAYER6')) {
		define('AMINA_JWPLAYER6', true);
		$jwplayer .= '<script type="text/javascript" src="'.AMINA_URL.'/app/jwplayer/jwplayer.js"></script>'."\n";
		$jwplayer .= '<script type="text/javascript">jwplayer.key="'.$amina['jwplayer6_key'].'";</script>'."\n";
	}

	$jw_id = 'jwplayer6_'.mt_rand(1,1000);
	$jwplayer .= '<div id="'.$jw_id.'">Loading the player...</div>'."\n";
	if($is_type == 'audio') {
		$jwplayer .= '<script type="text/javascript">
					    jwplayer("'.$jw_id.'").setup({
							file: "'.$file.'",
							width: "100%",
							height: "40",
							repeat: "file"
						});
					 </script>'."\n";
	} else if($is_type == 'plist') {
		$plist_set = 'aspectratio: "16:9"';
		if($cnt > 1) $plist_set = G5_IS_MOBILE ? 'aspectratio: "16:10", listbar: { position: "right", size:150 }' : 'aspectratio: "16:10", listbar: { position: "right", size:200 }';
		$jwplayer .= '<script type="text/javascript">
						jwplayer("'.$jw_id.'").setup({
							playlist: "'.$file.'",
							width: "100%",
							'.$plist_set.'
						});
					 </script>'."\n";
		$jwplayer = '<div class="auto-size">'.$jwplayer.'</div>'."\n";
	} else {
		$img_file = $img ? 'image: "'.$img.'",' : '';
		$caption = $caption ? 'tracks: [{file: "'.$caption.'"}],' : '';
		$jwplayer .= '<script type="text/javascript">
						jwplayer("'.$jw_id.'").setup({
							file: "'.$file.'",
							'.$img_file.'
							'.$caption.'
							aspectratio: "16:9",
							width: "100%"
						});
					 </script>'."\n";
		$jwplayer = '<div class="auto-size">'.$jwplayer.'</div>'."\n";
	}

	return $jwplayer;
}

// 회원 레이어
function amina_sideview($mb_id, $name='', $email='', $homepage='') {
    global $g5, $config, $bo_table, $sca, $is_admin;

    $email = base64_encode($email);
    $homepage = set_http($homepage);

	$name = get_text(cut_str($name, $config['cf_cut_name'])); // 설정된 자리수 만큼만 이름 출력
    $name = preg_replace("/\&#039;/", "", $name);
    $name = preg_replace("/\'/", "", $name);
    $name = preg_replace("/\"/", "&#034;", $name);
    $title_name = $name;

	$tmp_name = '';
    if ($mb_id) {
        if ($config['cf_use_member_icon']) {
            $mb_dir = substr($mb_id,0,2);
            $icon_file = G5_DATA_PATH.'/member/'.$mb_dir.'/'.$mb_id.'.gif';

            if (file_exists($icon_file)) {
                $width = $config['cf_member_icon_width'];
                $height = $config['cf_member_icon_height'];
                $icon_file_url = G5_DATA_URL.'/member/'.$mb_dir.'/'.$mb_id.'.gif';
                $tmp_name .= '<img src="'.$icon_file_url.'" width="'.$width.'" height="'.$height.'" alt="">';

                if ($config['cf_use_member_icon'] == 2) // 회원아이콘+이름
                    $tmp_name = $tmp_name.' <span class="member">'.$name.'</span>';
            } else {
		        $tmp_name = '<span class="member">'.$name.'</span>';
			}
        } else {
	        $tmp_name = '<span class="member">'.$name.'</span>';
		}
        $title_mb_id = '['.$mb_id.']';
    } else {
        if(!$bo_table)
            return $name;

        $tmp_name = '<span class="guest">'.$name.'</span>';
        $title_mb_id = '[비회원]';
    }

    $name     = get_text($name);
    $email    = get_text($email);
    $homepage = get_text($homepage);

    return "<a href=\"javascript:;\" onClick=\"showSideView(this, '$mb_id', '$name', '$email', '$homepage');\" title=\"{$title_mb_id}{$title_name}\">$tmp_name</a>";
}

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

	$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) : '';

	$g5['title'] = $g5['title'] ? $g5['title'] : 'amina_sns';

	$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;
	$twitter_url = 'http://twitter.com/?status='.$msg_url;
	$fb_msg = $sns_title ? $sns_title : $sns_emsg;

	if(G5_IS_MOBILE) {
		// 카카오톡 매뉴얼 : https://github.com/kakao/kakaolink-web
		$kakao_appid   = $_SERVER['HTTP_HOST']; // Mobile Site Domain 정확히 입력하지 않을 경우 이용이 제한될 수 있습니다.
		$kakao_appname = urlencode($g5['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 = '';
	}

    $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='.$lurl;
	$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 $g5, $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 = G5_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';
	if(!$g5['amina_ajax'] && !defined('AMINA_LIKE_LIB')) 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, $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'];

	if(!trim($star_color)) $star_color = 'gold';

	$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;
}

// Icon
function amina_icon($str){

	if(!$str || $str == 'none') return;

	list($icon, $opt) = explode(";", $str);
	switch($opt) {
		case 'c' : $str = "<i class='".$icon."'></i>"; break;
		case 't' : $str = $icon; break;
		default	 : $str = "<i class='fa fa-".$icon."'></i>"; break;
	}

	return $str;
}

// FA Icon
function amina_fa($str){

	$str = preg_replace("/{아이콘\:([^}]*)}/ie", "amina_icon('\\1')", $str);

	return $str;
}

// Tooltip
function amina_tooltip($str){

	$str = str_replace(array("<", ">", "\"", "'"), array("&lt;", "&gt;", "&quot;", "&apos;"), $str);

	return $str;
}

// Emoticon
function amina_ticon($str){

	if(!$str) return;

	list($emo, $width) = explode(":", $str);
	if(file_exists(AMINA_PATH.'/app/emoticon/'.$emo)) {
		$width = ($width > 0) ? $width : 50;
		$icon = '<img src="'.AMINA_URL.'/app/emoticon/'.$emo.'" width="'.$width.'" alt="" />';
	} else {
		$icon = '';
	}

	return $icon;
}

// Extract Text
function amina_text($str) {

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

	return $str;
}

// G5 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 = G5_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) {

	$ext_arr = array("mp4", "m4v", "f4v", "mov", "flv", "webm", "acc", "m4a", "f4a", "mp3", "ogg", "oga", "jpg", "jpeg", "bmp", "gif", "png");

	$chk_file = '';
	$attach_cnt = count($attach);
	for ($i=0; $i < $attach_cnt; $i++) {

		if(!trim($attach[$i]['source'])) continue;

		if ($attach[$i]['source'] && !$attach[$i]['view']) {
			$ext = amina_getExt($attach[$i]['source']);
			if(!in_array($ext, $ext_arr)) {
				$chk_file = true;
				return $chk_file;
			}
		}
    }

	return $chk_file;
}

// Sort Attach Files
function amina_attach_sort($attach) {

	$arr = array();
	$file = array();
	$video = array();
	$audio = array();
	$image = array();
	$ext_video = array("rss", "mp4", "m4v", "f4v", "mov", "flv", "webm");
	$ext_audio = array("acc", "m4a", "f4a", "mp3", "ogg", "oga");
	$ext_image = array("jpg", "jpeg", "bmp", "gif", "png");
	
	$attach_cnt = count($attach);
	for ($i=0; $i < $attach_cnt; $i++) {

		if(!trim($attach[$i]['source'])) continue;

		$ext = amina_getExt($attach[$i]['source']);
		if(in_array($ext, $ext_audio)) {
			$audio[] = $attach[$i];
		} else if(in_array($ext, $ext_video)) {
			$video[] = $attach[$i];
		} else if(in_array($ext, $ext_image)) {
			$image[] = $attach[$i];
		} else {
			$file[] = $attach[$i];
		}
    }

	$arr = array($file, $image, $video, $audio);

	return $arr;
}

// Check Attached Image
function amina_attach_img_url($str) {

	$str = explode("/data/", $str);
	$url = G5_DATA_URL.'/'.$str[1];

	return $url;
}

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

	$img = array();

	$z = 0;
	//Direct Attach
	$attach_cnt = count($attach);
	for ($i=0; $i < $attach_cnt; $i++) {
		if ($attach[$i]['view']) {
			$attach_img = amina_attach_img_url($attach[$i]['path']).'/'.$attach[$i]['file'];
			if(preg_match("/\.(jpg|jpeg|bmp|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)) {
		$match_cnt = count($match[0]);
		for ($i=0; $i < $match_cnt; $i++) {
			$chk_img = amina_value($match[0][$i]);
			if($chk_img['src'] && !preg_match("/(\/cheditor5\/|\/plugin\/|\/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;

	// 직접 첨부한 이미지
	$attach_cnt = count($attach);
	for ($i=0; $i < $attach_cnt; $i++) {
		if ($attach[$i]['view']) {
			$attach_img = amina_attach_img_url($attach[$i]['path']).'/'.$attach[$i]['file'];
			if(preg_match("/\.(jpg|jpeg|bmp|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'] && $info['movie_sound'] != "soundcloud") {
			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)) {
		$match_cnt = count($match[0]);
		for ($i=0; $i < $match_cnt; $i++) {
			$chk_img = amina_value($match[0][$i]);
			if($chk_img['src'] && !preg_match("/(\/cheditor5\/|\/plugin\/|\/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');
		$match_cnt = count($match[1]);
		for ($i=0; $i < $match_cnt; $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 $g5;	
			$bo = sql_fetch(" select bo_table from {$g5['board_table']} where bo_table = '$linked_bo' ");
			if($bo['bo_table']) {
				$tmp_write_table = $g5['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 = G5_DATA_PATH.'/item/'.$it_id.'_l1';
			if(file_exists($it_img)) { //상품이미지
				$img[] = $it_img;
				$z++;
				if($rows != "all" && $z == $rows) return $img;
			}
		}
	}

	return $img;
}

// 움직이는 GIF 파악 - G5에서 차용
function amina_animated_gif($filename) {

	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_url, $thumb_w, $thumb_h, $quality='90', $opt='', $wm='') {

	$thumb = $thumb_url;

	if(!$thumb) return $thumb_url;

	if (preg_match("/^(http|https)\:\/\//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 $thumb_url;
		} else {
			return $thumb_url;
		}
    }

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

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

	if (!preg_match("/^(http|https)\:\/\//i", $thumb) && preg_match("/\/data\//i", $thumb)) {
		$thumb_arr = explode("/data/", $thumb);
		$thumb = G5_DATA_URL.'/'.$thumb_arr[1];
	}

	return $thumb;
}

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

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

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

	$logo = array();

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

	if(!is_dir($logo_path)) return;

	$handle = opendir($logo_path);
	while ($file = readdir($handle)) {
		if(preg_match("/\.(jpg|jpeg|bmp|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 $g5;

	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
	$thumb = amina_make_thumb($thumb, $thumb_w, $thumb_h);

	//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 $g5;

	unset($list['file']);

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

	for ($i=0; $i < $img_cnt; $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])) {
			if (preg_match("/" . AMINA_HOST . "/", $img_arr[$i]) && preg_match("/\/data\/(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, AMINA_FILE_PERMISSION);
					@unlink($img);
				}
			}
		}
	}
}

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

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

	if(!$mb_id || !file_exists(G5_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 $g5, $xp;

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

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

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

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

	//Delete Photo
	if ($del_photo == "1") {
		@unlink($photo_dir.'/'.$mb_id);
		sql_query(" update {$g5['member_table']} set mb_6 = '' where mb_id = '$mb_id' ");
	}
    
	//Upload Photo
	if (is_uploaded_file($file['mb_icon2']['tmp_name'])) {
		if (!preg_match("/(\.(jpg|jpeg|bmp|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, AMINA_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, AMINA_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, AMINA_FILE_PERMISSION);
							@unlink($thumb);
							@unlink($temp_photo);
							sql_query(" update {$g5['member_table']} set mb_6 = '1' where mb_id = '$mb_id' ");
						} else {
							@unlink($temp_photo);
							alert('회원사진 등록에 실패했습니다. 이미지 파일이 정상적으로 업로드 되지 않았거나, 이미지 파일이 아닙니다.', AMINA_URL.'/mb.photo.php');
						}
					} else {
						copy($temp_photo, $org_photo);
						chmod($org_photo, AMINA_FILE_PERMISSION);
						@unlink($temp_photo);
						sql_query(" update {$g5['member_table']} set mb_6 = '1' where mb_id = '$mb_id' ");
					}
				}
			}
		}
	}
}

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

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

	$info = array();

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

	//Member Info
	$sql = " select mb_point, mb_9 from {$g5['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($xp['exp']['support']) $rule_table .= "'@support',";
		if($xp['exp']['chulsuk']) $rule_table .= "'@chulsuk',";
		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) ? '댓글' : '코멘트';
			$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']['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 {$g5['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 {$g5['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 {
			$mb_admin = true;
			$no_admin = explode(",", trim($xp['xp_no_admin'])); //관리자 제외 아이디
			for($i = 0; $i < count($no_admin); $i++) {
				if($xp_id == $no_admin[$i]) {
					$mb_admin = false;
					break;
				}
			}

			$chk_admin = $mb_admin ? is_admin($xp_id) : '';

			if($chk_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.'/misc/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 $g5, $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['mp'] = 0;
		$info['ap'] = 0;
	} else {
		$mb = sql_fetch(" select mb_level, mb_point, mb_7, mb_8, mb_9, mb_10 from {$g5['member_table']} where mb_id = '$mb_id' ");
		$grade = $mb['mb_level'];
		$info['mp'] = $mb['mb_point'];
		$info['ap'] = (int)$mb['mb_7'];
		$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;
}

// goo.gl 짧은주소 만들기 - G5S 함수 : 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 문자열 자르기 - G5S 함수 : 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;
	}
}

//특수문자 변환
if (!function_exists('specialchars_replace')) {
	function specialchars_replace($str, $len=0) {
		if ($len) {
	        $str = substr($str, 0, $len);
		}

		$str = preg_replace("/&/", "&amp;", $str);
		$str = preg_replace("/</", "&lt;", $str);
	    $str = preg_replace("/>/", "&gt;", $str);
		return $str;
	}
}

// htmlspecialchars 반대 
if (!function_exists("unhtmlspecialchars")) {
    function unhtmlspecialchars($str) {
		$trans = get_html_translation_table();
		$trans = array_flip($trans);
		$str = strtr($str, $trans);
		return $str;
    }
}

// 복수관리자 체크
if (!function_exists('chk_multiple_admin')) {
	function chk_multiple_admin($mb_id, $mb_arr) {

		if(!$mb_id || !$mb_arr) return false;

		$mb_list = explode(",", $mb_arr);

		if(count($mb_list) > 0) {
			if(in_array($mb_id, $mb_list)) {
				return true;
			}
		}

		return false;
	}
}

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

		if ($mb_id) {
	        $row = sql_fetch(" select count(*) as cnt from {$g5['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 $g5;

	    sql_query(" LOCK TABLE {$g5['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 {$g5['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;
	}
}

if (!function_exists('convert_charset')) {
    /*
    -----------------------------------------------------------
        Charset 을 변환하는 함수
    -----------------------------------------------------------
    iconv 함수가 있으면 iconv 로 변환하고
    없으면 mb_convert_encoding 함수를 사용한다.
    둘다 없으면 사용할 수 없다.
    */
    function convert_charset($from_charset, $to_charset, $str) {
        if(function_exists('iconv')) {
            return iconv($from_charset, $to_charset, $str);
        } else if( function_exists('mb_convert_encoding')) {
            return mb_convert_encoding($str, $to_charset, $from_charset);
        } else {
            die("Not found 'iconv' or 'mbstring' library in server.");
		}
    }
}

// 다음뷰 아이콘 출력
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 amina_insert_mileage($mb_id, $from_id, $point, $content='', $rel_table='', $rel_id='', $rel_action='') {
    global $g5, $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 {$g5['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 {$g5['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 {$g5['amina_mileage']}
                set mb_id = '$mb_id',
                    from_id = '$from_id',
					po_datetime = '".G5_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 {$g5['amina_mileage']} where mb_id = '$mb_id' ";
    $row = sql_fetch($sql);
    $sum_point = $row['sum_po_point'];

    // 마일리지 UPDATE(회원 여분필드 7번사용)
    $sql = " update {$g5['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 $g5;

    $result = false;
    if ($rel_table || $rel_id || $rel_action)
    {
        $result = sql_query(" delete from {$g5['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 {$g5['amina_mileage']} where mb_id = '$mb_id' ";
        $row = sql_fetch($sql);
        $sum_point = $row['sum_po_point'];

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

    return $result;
}

// Response
function amina_response($bo_table, $wr_id, $wr_subject, $mb_id, $re_id, $re_name, $re_flag, $re_type="0", $wr_cmt="0") {
    global $g5, $member;

    if (!$mb_id || !$re_flag || ($member['mb_id'] && $member['mb_id'] == $mb_id)) return;

	//Check flag
	$re_arr = array("linked", "reply", "cmt", "good", "nogood", "star", "poll", "shingo", "cmt_reply", "cmt_good", "cmt_choice", "cmt_shingo");

	if(!in_array($re_flag, $re_arr)) return;

	//Check Response
	$row = sql_fetch(" select * from {$g5['amina_response']} where bo_table = '$bo_table' and wr_id = '$wr_id' and mb_id = '$mb_id' and re_flag = '$re_flag' and re_chk <> '1' ");

	if (!isset($row['wr_cmt'])) {
		sql_query(" alter table {$g5['amina_response']} add wr_cmt int(11) default '0' NOT NULL AFTER wr_id", false);
	}

	if ($row['id']) {
		$id_query = $re_id ? "re_id = '$re_id', re_name = '$re_name'," : "";
		$cmt_query = $wr_cmt ? "wr_cmt = '$wr_cmt'," : "";
		sql_query(" update {$g5['amina_response']} set $id_query re_cnt = re_cnt + 1, $cmt_query re_datetime = '".G5_TIME_YMDHIS."' where id = '{$row['id']}' ");
	} else {
		sql_query(" insert into {$g5['amina_response']} set bo_table = '$bo_table', wr_id = '$wr_id', wr_cmt = '$wr_cmt', wr_subject = '".addslashes($wr_subject)."', mb_id = '$mb_id', re_id = '$re_id', re_name = '$re_name', re_flag = '$re_flag', re_type = '$re_type', re_datetime = '".G5_TIME_YMDHIS."' ");
	}

    return;
}

// Response cnt
function amina_response_cnt($mb_id) {
    global $g5;

    if (!$mb_id) return 0;

	$row = sql_fetch(" select count(*) as cnt from {$g5['amina_response']} where mb_id = '{$mb_id}' and re_chk <> '1' ", false);

	$row['cnt'] = ($row['cnt'] > 0) ? $row['cnt'] : 0;

	return $row['cnt'];
}

// html 형식으로 변환
function amina_get_html($str) {

    $target[] = "/</";
    $source[] = "&lt;";
    $target[] = "/>/";
    $source[] = "&gt;";
    $target[] = "/\"/";
    $source[] = "&#034;";
    $target[] = "/\'/";
    $source[] = "&#039;";

    return preg_replace($source, $target, $str);
}

function amina_geo_info($bo_table, $attach, $i) {

	if(!function_exists('exif_read_data')) return;

	if(!$i) $i = 0;

	$img_file = G5_DATA_PATH.'/file/'.$bo_table.'/'.$attach[$i]['file'];

	$geo = array();
	if(file_exists($img_file)) {
		$exif = @exif_read_data($img_file, 0, true);
		if ($exif['GPS'] && $exif['GPS']['GPSLatitude'] && $exif['GPS']['GPSLongitude']) { //위경도 좌표가 있다면
			list($temp_d1, $temp_d2) = sscanf($exif['GPS']['GPSLatitude'][0], "%d/%d"); //문자->숫자로 계산
			$gps_lat_d = $temp_d1/$temp_d2;
			list($temp_d1, $temp_d2) = sscanf($exif['GPS']['GPSLatitude'][1], "%d/%d");
			$gps_lat_m = $temp_d1/$temp_d2;
			list($temp_d1, $temp_d2) = sscanf($exif['GPS']['GPSLatitude'][2], "%d/%d");
			$gps_lat_s = $temp_d1/$temp_d2;
			list($temp_d1, $temp_d2) = sscanf($exif['GPS']['GPSLongitude'][0], "%d/%d"); //문자->숫자로 계산
			$gps_lon_d = $temp_d1/$temp_d2;
			list($temp_d1, $temp_d2) = sscanf($exif['GPS']['GPSLongitude'][1], "%d/%d");
			$gps_lon_m = $temp_d1/$temp_d2;
			list($temp_d1, $temp_d2) = sscanf($exif['GPS']['GPSLongitude'][2], "%d/%d");
			$gps_lon_s = $temp_d1/$temp_d2;

			$geo[0] = $gps_lat_d+$gps_lat_m/60+$gps_lat_s/3600; //도분초를 도로 변환
			$geo[1] = $gps_lon_d+$gps_lon_m/60+$gps_lon_s/3600;
		}
	}

	return $geo;
}

//----------------------------------------------------------------//
// 최근글 관련 함수들
//----------------------------------------------------------------//

// 최글글 정리
function amina_get_list($write_row, $board, $skin_path, $subject_len=40, $type='') {
    global $g4, $g5, $config, $is_sideview;

    // 배열전체를 복사
    $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'] == G5_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'] == G5_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'] = $is_sideview ? amina_sideview($list['mb_id'], $tmp_name, $list['wr_email'], $list['wr_homepage']) : 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'] = G5_BBS_URL.'/board.php?bo_table='.$board['bo_table'].'&sca='.urlencode($list['ca_name']);

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

    $list['icon_new'] = '';
    if ($list['wr_datetime'] >= date("Y-m-d H:i:s", G5_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<=G5_LINK_COUNT; $i++)
    {
        $list['link'][$i] = set_http(get_text($list["wr_link{$i}"]));
        $list['link_href'][$i] = G5_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 amina_details($type, $list, $date='1', $star_color='gold', $star_size='s', $more='More') {

	if($type == 'date') {
		switch($date) {
			case '1'	: $item = $list['datetime2']; break;
			case '2'	: $item = amina_date($list['wr_datetime']); break;
			default		: $item = date($date, strtotime($list['wr_datetime'])); break;
		}
	} else {
		switch($type) {
			case 'more'		: $item = $more; break;
			case 'cate'		: $item = $list['ca_name']; break;
			case 'name'		: $item = $list['wr_name']; break;
			case 'cmt'		: $item = number_format($list['wr_comment']); break;
			case 'hit'		: $item = number_format($list['wr_hit']); break;
			case 'good'		: $item = number_format($list['wr_good']); break;
			case 'nogood'	: $item = number_format($list['wr_nogood']); break;
			case 'view'		: $item = number_format($list['wr_view_point']); break;
			case 'down'		: $item = number_format($list['wr_down_point']); break;
			case 'star'		: $item = amina_star_mark($star_color, $list['wr_7'], $star_size); break;
			default			: $item = ''; break;
		}
	}

	return $item;
}

// RSS Strip
function amina_rss_str($str) {

	if(!$str) return;

	$str = str_replace("<![CDATA[", "", $str);
	$str = str_replace("]]>", "", $str);
	$str = trim($str);

	return $str;
}

// RSS 추출
function amina_rss_rows($url) {

	if(!$url) return;

	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	@curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);    
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_TIMEOUT, 10);
	$xml = trim(curl_exec($ch));
	curl_close($ch);

	if(!$xml) return;

	$encoding = explode("encoding=\"", $xml);
	$encoding = substr($encoding[1], 0, 6);
	if(strtolower($encoding) == 'euc-kr') $xml = convert_charset('euc-kr','UTF-8',$xml);

    $list = '';
    preg_match_all("/<item>(.*)<\/item>/iUs", $xml, $matchs);

	$max = count($matchs[1]);
	for ($i=0; $i < $max; $i++) {

		preg_match("/<title>(.*)<\/title>/iUs", $matchs[1][$i], $match);
		$list .= amina_text(unhtmlspecialchars(amina_rss_str($match[1]))).'||';

		preg_match("/<link>(.*)<\/link>/iUs", $matchs[1][$i], $match);
		$list .= amina_rss_str($match[1]).'||';

		preg_match("/<description>(.*)<\/description>/iUs", $matchs[1][$i], $match);
		$wr_content = unhtmlspecialchars(amina_rss_str($match[1]));

		if(preg_match_all("/\<img[^\<\>]*\>/i", $wr_content, $match)) {
			$img = amina_value($match[0][0]);
			$img = $img['src'] ? '<p><img src="'.$img['src'].'"></p>' : '';
		} else {
			$img = '';
		}

		$list .= $img.''.amina_cut($wr_content, 250).'||';

		preg_match("/<category>(.*)<\/category>/iUs", $matchs[1][$i], $match);
		$list .= amina_text(amina_rss_str($match[1])).'||';

		preg_match("/<pubDate>(.*)<\/pubDate>/iUs", $matchs[1][$i], $match);
		$wr_time = amina_rss_str($match[1]);
		if(!$wr_time) {
			preg_match("/<dc:date>(.*)<\/dc:date>/iUs", $matchs[1][$i], $match);
			$wr_time = amina_rss_str($match[1]);
		}
		$wr_time = date("Y-m-d H:i:s", strtotime($wr_time));
		$list .= $wr_time.'||';
		$list .= substr($wr_time,0,10).'||';
		$list .= substr($wr_time,5,5).'||';

		preg_match("/<author>(.*)<\/author>/iUs", $matchs[1][$i], $match);
		$wr_name = amina_text(amina_rss_str($match[1]));
		if(!$wr_name) {
			preg_match("/<dc\:creator>(.*)<\/dc\:creator>/iUs", $matchs[1][$i], $match);
			$wr_name = amina_text(amina_rss_str($match[1]));
		}
		$list .= $wr_name.'||';

		preg_match("/<comment>(.*)<\/comment>/iUs", $matchs[1][$i], $match);
		$list .= amina_text(amina_rss_str($match[1])).'||';

		preg_match("/<hit>(.*)<\/hit>/iUs", $matchs[1][$i], $match);
		$list .= amina_text(amina_rss_str($match[1])).'||';

		preg_match("/<good>(.*)<\/good>/iUs", $matchs[1][$i], $match);
		$list .= amina_text(amina_rss_str($match[1])).'||';

		$icon_new = ($wr_time && $wr_time >= date("Y-m-d H:i:s", G5_SERVER_TIME - (24 * 3600))) ? '1' : '';
		$list .= $icon_new.'||';

		$list .= $img ? '1' : '';

		if($i < $max - 1) $list .= '<>';
	}

	return $list;
}

// 최근글 출력함수
function latest_amina($skin_dir="", $bo_id="", $rows=10, $subject_len=40, $options="", $tab_list="", $sql_opt="") {
    global $g4, $g5, $config, $amina, $member, $pv_thema, $bo_table, $wr_id;

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

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

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

	//탭이 1개이상일 경우에는 jquery용으로
	if($tab_num > 1) { 

		//공통옵션 정리하기
		$tmp2 = amina_query($options);

		$tab_opt = '&org='.urlencode("skin_dir={$skin_dir} bo_id={$bo_id} 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]);

			$tmp['title'] = $tmp['title'] ? $tmp['title'] : $tmp2['title'];
			$tmp['list_effect'] = $tmp['list_effect'] ? $tmp['list_effect'] : $tmp2['list_effect'];
			$tmp['title_off'] = $tmp['title_off'] ? $tmp['title_off'] : $tmp2['title_off'];
			$tmp['new_icon'] = $tmp['new_icon'] ? $tmp['new_icon'] : $tmp2['new_icon'];
			$tmp['bo_list'] = $tmp['bo_list'] ? $tmp['bo_list'] : $tmp2['bo_list'];
			$tmp['head_href'] = $tmp['head_href'] ? $tmp['head_href'] : $tmp2['head_href'];
			$tmp['type'] = $tmp['type'] ? $tmp['type'] : $tmp2['type'];

			$tab[$i]['title'] = amina_fa($tmp['title']);
			$tab[$i]['list_effect'] = $tmp['list_effect'];
			$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'] = G5_BBS_URL.'/new.php?view=w';
				} else if($tmp['type'] == "newcmt") {
					$tab[$i]['href'] = G5_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'] = G5_BBS_URL.'/board.php?bo_table='.$tmp['bo_list'].'&sca='.urlencode($tmp['ca_name']);
					}
				}
			}
		}	

		$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);
		}
	}

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

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

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

	//페이지
	$page_num = ($opt['page'] > 1) ? $opt['page'] : 1;

	//시작번호
	$start_rows = 0;

	//랜덤추출
	$rdm_rows = false;

	if($opt['type'] == "none") {
		$tab[$z]['title'] = '제목입력';
		$tab[$z]['href'] = '#';
	} else if($opt['type'] == "rss") {
		if($opt['rss']) {
			$r = $opt['rss']; //RSS ID
			$rss = array();
			@include(G5_PATH.'/amina.rss.php');
			if($rss[$r]) {
				$tab[$z]['title'] = $rss[$r][1] ? $rss[$r][1] : $rss[$r][0];
				$opt['target'] = $opt['target'] ? $opt['target'] : '_blank';
				$rss[$r][2] = ($rss[$r][2] > 0) ? $rss[$r][2] : 600;
				$xml = explode("<>", amina_cache($r, $rss[$r][2], "amina_rss_rows(".$rss[$r][3].")"));

				$xml_cnt = count($xml);
				$xml_cnt = ($xml_cnt > $rows) ? $rows : $xml_cnt;
			
				for($i=0; $i < $xml_cnt; $i++) {
					list($list[$i]['wr_subject'], $list[$i]['href'], $list[$i]['wr_content'], $list[$i]['ca_name'], $list[$i]['wr_datetime'], $list[$i]['datetime'], $list[$i]['datetime2'], $list[$i]['wr_name'], $list[$i]['wr_comment'], $list[$i]['wr_hit'], $list[$i]['wr_good'], $list[$i]['icon_new'], $list[$i]['rss_img']) = explode("||", $xml[$i]);
				}
			}
		}

		$tab[$z]['title'] = $tab[$z]['title'] ? $tab[$z]['title'] : 'RSS';
		$tab[$z]['href'] = '#';

	} else if($opt['type'] == "member") {
		$tab[$z]['title'] = '회원';
		$tab[$z]['href'] = '#';

		//회원사진
		$sql_photo = $opt['mb_photo'] ? "and mb_6 = '1'" : "";

		//관리자
		$sql_admin = $opt['admin'] ? "" : "and mb_id <> '{$config['cf_admin']}'";

		//정보공개여부
		$sql_open = $opt['mb_open'] ? "and mb_open = '1'" : "";

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

					if (!$order_list[$i]) continue;
					
					switch($order_list[$i]) {
						case 'login'		: $order_by .= ' mb_today_login desc, '; break;
						case 'mp'			: $order_by .= ' mb_point desc, '; break;
						case 'ap'			: $order_by .= ' SUBSTRING_INDEX(mb_7, '.', 1 )+0 desc, '; break;
						case 'level'		: $order_by .= ' SUBSTRING_INDEX(mb_10, '.', 1 )+0 desc, '; break;
					}
				}
				$order_by = $order_by.'mb_datetime desc';
			}
		} else {
			$order_by = 'mb_datetime desc';
		}

		$sql_common = "from {$g5['member_table']} where mb_leave_date = '' and mb_intercept_date = '' $sql_photo $sql_admin $sql_open";
		if($page_num > 1 && !$rdm_rows) {
			$a_total = sql_fetch("select count(*) as cnt $sql_common ");
			$total_count = $a_total['cnt'];
			$total_page  = ceil($total_count / $rows);  // 전체 페이지 계산
			if (!$page_num) { $page_num = 1; } // 페이지가 없으면 첫 페이지 (1 페이지)
			$start_rows = ($page_num - 1) * $rows; // 시작 열을 구함
		}

		//정보공개 및 회원사진 있는 회원만 출력
		$result = sql_query("select * $sql_common order by $order_by limit $start_rows, $rows ");
		$rank = 1;
		for ($i=0; $row=sql_fetch_array($result); $i++) {
			if($opt['order']) {
				$row['mb_rank'] = $rank + $start_rows;
				$rank++;
			}
			$list[$i] = $row;
		}

	} else if($opt['type'] == "point") {
		$tab[$z]['title'] = '포인트';
		$tab[$z]['href'] = '#';

		//관리자
		$sql_admin = $opt['admin'] ? "" : "and mb_id <> '{$config['cf_admin']}'";

		//추출기간 설정
		$sql_term = '';
		if($opt['term']) {
			$time = G5_SERVER_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 date_format(po_datetime, '%Y%m%d') between '$startYmd' and '$nowYmd' ";
		}

		$point_table = $opt['ap'] ? $g5['amina_mileage'] : $g5['point_table'];
		$sql_common = "from {$point_table} where po_point > 0 $sql_admin $sql_term group by mb_id";
		if($page_num > 1) {
			$a_total = sql_fetch("select count(*) as cnt $sql_common ");
			$total_count = $a_total['cnt'];
			$total_page  = ceil($total_count / $rows);  // 전체 페이지 계산
			if (!$page_num) { $page_num = 1; } // 페이지가 없으면 첫 페이지 (1 페이지)
			$start_rows = ($page_num - 1) * $rows; // 시작 열을 구함
		}

		$result = sql_query("select mb_id, sum(po_point) as po_point $sql_common order by sum(po_point) desc limit $start_rows, $rows ");
		$rank = 1;
		for ($i=0; $row=sql_fetch_array($result); $i++) {
			$mb_row = sql_fetch("select * from {$g5['member_table']} where mb_id = '{$row['mb_id']}' ");
			$mb_row['po_point'] = $row['po_point'];
			$mb_row['mb_rank'] = $rank + $start_rows;
			$rank++;
			$list[$i] = $mb_row;
		}

	} else if($opt['type'] == "mygul") {
		$tab[$z]['title'] = '내글반응';
		$tab[$z]['href'] = '#';

		if($member['mb_id']) {
			$result = sql_query(" select bo_table, wr_id, mb_id, wr_subject, count(*) as re_mb, sum(re_cnt) as re_cnt, max(re_datetime) as re_datetime from {$g5['amina_response']} where mb_id = '{$member['mb_id']}' and re_chk <> '1' group by bo_table, wr_id order by re_datetime desc limit 0, $rows ");
			for ($i=0; $row=sql_fetch_array($result); $i++) {
				$row['href'] = AMINA_URL.'/response.php';
				$row['wr_datetime'] = $row['re_datetime'];
				$row['wr_comment'] = $row['re_cnt'] + $row['re_mb'];
				$list[$i] = $row;
			}
		}

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

		$mode_sql = '';
		if($opt['mode']) {
			$mode_list = explode(";", $opt['mode']);
			$mode_list_cnt = count($mode_list);
			for ($i=0; $i < $mode_list_cnt; $i++) {

				if (!$mode_list[$i]) continue;
				
				switch($mode_list[$i]) {
					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;
				}
			}
		} 

		//포함 게시판 설정
		$new_sql = '';
		if($opt['gr_list']) { //그룹추출
			$gr_sql = '';
			$gr_bo = explode(";", $opt['gr_list']);
			$gr_bo_cnt = count($gr_bo);
			for ($i=0; $i < $gr_bo_cnt; $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 {$g5['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']);
			$bo_in_cnt = count($bo_in);
			for ($k=0; $k < $bo_in_cnt; $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']);
			$bo_ex_cnt = count($bo_ex);
			for ($k=0; $k < $bo_ex_cnt; $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'] = G5_BBS_URL.'/new.php?view=c';

			$sql_common = "from {$g5['board_new_table']} where bo_table <> '' and wr_id <> wr_parent $new_sql $mode_sql ";
			if($page_num > 1) {
				$a_total = sql_fetch("select count(*) as cnt $sql_common ");
				$total_count = $a_total['cnt'];
				$total_page  = ceil($total_count / $rows);  // 전체 페이지 계산
				if (!$page_num) { $page_num = 1; } // 페이지가 없으면 첫 페이지 (1 페이지)
				$start_rows = ($page_num - 1) * $rows; // 시작 열을 구함
			}

			$result = sql_query(" select * $sql_common order by bn_id desc limit $start_rows, $rows ");
			for ($i=0; $row=sql_fetch_array($result); $i++) {

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

				$tmp_write_table = $g5['write_prefix'] . $row['bo_table']; // 게시판 테이블 전체이름
				$board = sql_fetch(" select * from {$g5['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'] == "newcmtgul") {
				$tab[$z]['title'] = '새로 댓글달린 글';
				$tab[$z]['href'] = G5_BBS_URL.'/new.php?view=c';

				$sql_common = "from {$g5['board_new_table']} where bo_table <> '' and wr_id <> wr_parent $new_sql $mode_sql group by bo_table, wr_parent";
				if($page_num > 1) {
					$a_total = sql_fetch("select count(*) as cnt $sql_common ");
					$total_count = $a_total['cnt'];
					$total_page  = ceil($total_count / $rows);  // 전체 페이지 계산
					if (!$page_num) { $page_num = 1; } // 페이지가 없으면 첫 페이지 (1 페이지)
					$start_rows = ($page_num - 1) * $rows; // 시작 열을 구함
				}

				$result = sql_query(" select bo_table, wr_parent, max(bn_id) as bn_id $sql_common order by bn_id desc limit $start_rows, $rows ");

			} else if($opt['type'] == "file") {
				$tab[$z]['title'] = '다운로드';
				$tab[$z]['href'] = '#';

				// 추출기간 설정
				$sql_term = '';
				if($opt['term']) {
					$time = G5_SERVER_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 date_format(bf_datetime, '%Y%m%d') between '$startYmd' and '$nowYmd' ";
				}

				$sql_common = "from {$g5['board_file_table']} where bo_table <> '' and bf_type = '0' $new_sql $sql_term group by bo_table, wr_id ";

				if($page_num > 1) {
					$a_total = sql_fetch("select count(*) as cnt $sql_common ");
					$total_count = $a_total['cnt'];
					$total_page  = ceil($total_count / $rows);  // 전체 페이지 계산
					if (!$page_num) { $page_num = 1; } // 페이지가 없으면 첫 페이지 (1 페이지)
					$start_rows = ($page_num - 1) * $rows; // 시작 열을 구함
				}

				if($opt['sum']) {
					$order_by = $opt['order'] ? "sum(bf_download) desc" : "bf_datetime desc";
					$result = sql_query(" select bo_table, wr_id, wr_id as wr_parent, sum(bf_download) as bf_download $sql_common order by $order_by limit $start_rows, $rows ");
				} else {
					$order_by = $opt['order'] ? "bf_download desc" : "bf_datetime desc";
				    $result = sql_query(" select bo_table, wr_id, wr_id as wr_parent, max(bf_download) as bf_download $sql_common order by $order_by limit $start_rows, $rows ");
				}

			} else if($opt['type'] == "poll") {
				$tab[$z]['title'] = '설문조사';
				$tab[$z]['href'] = '#';

				// 추출기간 설정
				$sql_term = '';
				if($opt['term']) {
					$time = G5_SERVER_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 date_format(poll_regdate, '%Y%m%d') between '$startYmd' and '$nowYmd' ";
				}

				$sql_ca = $opt['ca_name'] ? "and ca_name = '{$opt['ca_name']}'" : "";
				$sql_ing = $opt['ing'] ? "and TO_DAYS('".G5_TIME_YMDHIS."') < TO_DAYS(poll_enddate)" : "";
				$sql_common = "from {$g5['amina_poll']} where bo_table <> '' $new_sql $sql_term $sql_ing $sql_ca";

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

							if (!$order_list[$i]) continue;
							
							switch($order_list[$i]) {
								case 'join'			: $order_by .= ' poll_cnt desc, '; break;
								case 'point'		: $order_by .= ' poll_point desc, '; break;
								case 'end'			: $order_by .= ' poll_enddate desc, '; break;
							}
						}
						$order_by = $order_by.'poll_id desc';
					}
				} else {
					$order_by = 'poll_id desc';
				}

				if($page_num > 1 && !$rdm_rows) {
					$a_total = sql_fetch("select count(*) as cnt $sql_common ");
					$total_count = $a_total['cnt'];
					$total_page  = ceil($total_count / $rows);  // 전체 페이지 계산
					if (!$page_num) { $page_num = 1; } // 페이지가 없으면 첫 페이지 (1 페이지)
					$start_rows = ($page_num - 1) * $rows; // 시작 열을 구함
				}

			    $result = sql_query(" select *, wr_id as wr_parent $sql_common order by $order_by limit $start_rows, $rows ");

			} else {
				$tab[$z]['title'] = '새로 등록된 글';
				$tab[$z]['href'] = G5_BBS_URL.'/new.php?view=w';

				$sql_common = "from {$g5['board_new_table']} where bo_table <> '' and wr_id = wr_parent $new_sql $mode_sql";
				if($page_num > 1) {
					$a_total = sql_fetch("select count(*) as cnt $sql_common ");
					$total_count = $a_total['cnt'];
					$total_page  = ceil($total_count / $rows);  // 전체 페이지 계산
					if (!$page_num) { $page_num = 1; } // 페이지가 없으면 첫 페이지 (1 페이지)
					$start_rows = ($page_num - 1) * $rows; // 시작 열을 구함
				}
				$result = sql_query(" select bo_table, wr_parent, bn_id $sql_common order by bn_id desc limit $start_rows, $rows ");
			}

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

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

				$tmp_write_table = $g5['write_prefix'] . $row['bo_table']; // 게시판 테이블 전체이름
				$board = sql_fetch(" select * from {$g5['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']}' "); //글 정보 불러오기..

				if($opt['type'] == "file") {
					$row1['wr_download'] = $row['bf_download'];
				}

				if($opt['order']) {
					$row1['wr_rank'] = $rank + $start_rows;
					$rank++;
				}

				if($opt['type'] == "poll") {
					$row1['wr_subject'] = $row['poll_subject'] ? $row['poll_subject'] : $row1['wr_subject'];
					$row1['poll_cnt'] = $row['poll_cnt'];
					$row1['poll_point'] = $row['poll_point'];
					$row1['poll_regdate'] = $row['poll_regdate'];
					$row1['poll_enddate'] = $row['poll_enddate'];
				}

				$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']);
			$ca_ex_cnt = count($ca_ex);
			for ($k=0; $k < $ca_ex_cnt; $k++) {

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

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

		//mode 설정
		$mode_sql = '';
		if($opt['mode']) {
			$mode_list = explode(";", $opt['mode']);
			$mode_list_cnt = count($mode_list);
			for ($i=0; $i < $mode_list_cnt; $i++) {

				if (!$mode_list[$i]) continue;
				
				switch($mode_list[$i]) {
					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;
				}
			}
		} 

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

		// 추출기간 설정
		if($opt['term']) {
			$time = G5_SERVER_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' ";
		}

		// 정렬방법
		$order_by = '';
		if($opt['order']) {
			$order_list = explode(";", $opt['order']);
			if(in_array('rdm', $order_list)) {
				$order_by = ' rand() ';
				$rdm_rows = true;
				$opt['order'] = '';
			} else {
				$o = 0;
				$order_list_cnt = count($order_list);
				for ($i=0; $i < $order_list_cnt; $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;
					}
				}
			}
		}

		// 글과 댓글 구분하기
		$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']);
			$gr_bo_cnt = count($gr_bo);
			for ($i=0; $i < $gr_bo_cnt; $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 {$g5['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(!$rdm_rows) $order_by .= ' wr_datetime desc ';
			
			$tmp = '';
			for($i=0; $i < $bo_num; $i++){ 
				
				if (!$arr_bo[$i]) continue;

				//필드수가 다를 경우 오류방지를 위해 매칭필드 직접 지정
				$tmp_write_table = $g5['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) return; //설정이 없을 경우

			$sql_tmp = substr($tmp,0,-10);
				
			if($page_num > 1 && !$rdm_rows) {
				$a_total = sql_fetch("select count(*) as cnt from ( ".$sql_tmp.") as a ");
				$total_count = $a_total['cnt'];
				$total_page  = ceil($total_count / $rows);  // 전체 페이지 계산
				if (!$page_num) { $page_num = 1; } // 페이지가 없으면 첫 페이지 (1 페이지)
				$start_rows = ($page_num - 1) * $rows; // 시작 열을 구함
			}

			$tmp = "select * from ( ".$sql_tmp.") as a order by $order_by limit $start_rows, $rows";
			$result = sql_query($tmp);

			$rank = 1;
			for ($i=0; $row=sql_fetch_array($result); $i++){ 
				$sql = "select * from {$g5['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 + $start_rows;
					$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(!$rdm_rows) $order_by .= ' wr_id desc ';

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

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

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

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

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

				$i = 0;
				if($opt['type'] == "notice" || $opt['type'] == "nonotice") {
					$notice_sql = '';
				    $arr_notice = AMINA ? explode(",", trim($board['bo_notice'])) : explode("\n", trim($board['bo_notice']));
					if($opt['type'] == "notice" && $page_num == "1") {
						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_common = "from $tmp_write_table where $post_type $sql_ca $notice_sql $sql_opt $sql_term $mode_sql $ex_sql";
					if($page_num > 1) {
						$a_total = sql_fetch("select count(*) as cnt $sql_common ");
						$total_count = $a_total['cnt'];
						$total_page  = ceil($total_count / $rows);  // 전체 페이지 계산
						if (!$page_num) { $page_num = 1; } // 페이지가 없으면 첫 페이지 (1 페이지)
						$start_rows = ($page_num - 1) * $rows; // 시작 열을 구함
					}
					$sql = " select * $sql_common order by $order_by limit $start_rows, $rows ";
				} else {
					$sql_common = "from $tmp_write_table where $post_type $sql_ca $sql_opt $sql_term $mode_sql $ex_sql";
					if($page_num > 1 && !$rdm_rows) {
						$a_total = sql_fetch("select count(*) as cnt $sql_common ");
						$total_count = $a_total['cnt'];
						$total_page  = ceil($total_count / $rows);  // 전체 페이지 계산
						if (!$page_num) { $page_num = 1; } // 페이지가 없으면 첫 페이지 (1 페이지)
						$start_rows = ($page_num - 1) * $rows; // 시작 열을 구함
					}
					$sql = " select * $sql_common order by $order_by limit $start_rows, $rows ";
				}

				$result = sql_query($sql);
				$rank = 1;
				for ($i=$i; $row = sql_fetch_array($result); $i++) { 
					if($opt['order']) {
						$row['wr_rank'] = $rank + $start_rows;
						$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'];
			}
		}
	}

	if($opt['type'] != 'none') {

		//추출 글 정보만 넘기기
		if($opt['list_rdm']) {
			if(count($list) > 0) shuffle($list);
		}

		//이미지글로 정렬
		if($opt['img_row'] > 0) {
			$fixList = array();
			$fixCount = count($list);
			$f = 0;
			for($i=0; $i < $fixCount; $i++) {
				if(strstr($list[$i]['wr_10'], "photo") || strstr($list[$i]['wr_10'], "video") || $list[$i]['rss_img']) {
					$list[$i]['fixList'] = true;
					$fixList[$f] = $list[$i];
					$f++;
				}

				if($f == $opt['img_row']) break;
			}

			for($i=0; $i < $fixCount; $i++) {
				if(!$list[$i]['fixList']) {
					$fixList[$f] = $list[$i];
					$f++;
				}
			}

			unset($list);
			$list = $fixList;
		}

		//추출 글 정보만 넘기기
		if($opt['list_data']) return $list;
	}

	$tab[$z]['title'] = $opt['title'] ? amina_fa($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, $g5, $is_admin, $pv_thema;

    $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'];
		$thema = '';
		if($list['thema']) $thema = G5_IS_MOBILE ? '&m_thema='.$list['thema'] : '&thema='.$list['thema'];
		$tab[$i]['href'] = G5_URL.'/index.php?page_name='.$page_name.'&tab_id='.$list['tab_id'].'&frame=1&first_view=no'.$thema;
		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 = G5_SKIN_PATH."/latest/".$skin_dir;
	$latest_skin_url = G5_SKIN_URL."/latest/".$skin_dir;

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

    return $content;
} 

//----------------------------------------------------------------//
// 태마 관련 함수들
//----------------------------------------------------------------//

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

	$list = array();

	$chk_date = date("Y-m-d H:i:s", G5_SERVER_TIME - ($update * 24 * 3600));
	if($bo_table) {
	    $tmp_write_table = $g5['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 {$g5['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";
	$list_cnt = count($list);
	$arr_bo_cnt = count($arr_bo);

	for ($i=0; $i < $list_cnt; $i++) { 
		for ($j=0; $j < $arr_bo_cnt; $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));
		$chk_cnt = count($chk_gr);
		for ($i=0; $i < $chk_cnt; $i++) { 
			if ($gr_id == $chk_gr[$i]) return $sel_icon;
		}
	}

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

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

	$sel_icon = '';

	return $sel_icon;

}

// 새글 갯수 체크
function new_cnt($bo_list, $ca_name='', $head='', $tail='') {
    global $g5;

	$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 {$g5['board_table']} where bo_table = '{$bo_table}'");

		if(!$board) continue;

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

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

	return $new_post;
}

// 제외메뉴 체크
function chk_menu_exclude($arr, $item) {

	$item = trim($item);

	if($arr && $item) {
		$arr_cnt = count($arr);
		for ($i=0; $i < $arr_cnt; $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='', $page_id='') {
	global $g5, $is_admin, $member, $sca;

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

	list($gr_ex, $gr_in) = explode("|",$gr_exclude);
	$gr_exclude = explode(";",$gr_ex);
	$bo_exclude = explode(";",$bo_exclude);

	if(AMINA) {
		$gr_order = 'gr_order';
		$gr_show = "and gr_show_menu = '1' ";
		$gr_show .= G5_IS_MOBILE ? "and gr_device <> 'pc'" : "and gr_device <> 'mobile'";
		$bo_order = 'bo_order';
		$bo_show = "and bo_show_menu = '1' ";
		$bo_search = "and bo_use_search = '1'";
		$bo_sql = G5_IS_MOBILE ? "bo_device <> 'pc'" : "bo_device <> 'mobile'";
	} else {
		$gr_order = 'gr_10';
		$gr_show = "and gr_9_subj <> 'none' ";
		$bo_order = 'bo_order_search';
		$bo_show = '';
		$bo_search = "and bo_use_search = '1'";
		$bo_sql = G5_IS_MOBILE ? "bo_10 <> 'none' and bo_10 <> 'pc'" : "bo_10 <> 'none' and bo_10 <> 'mobile'";
	}

	//첫번째 배열(0번)은 전체통계로 사용
	$z = 1;
	$count_write = 0;
	$count_comment = 0;
	$sql = " select gr_id, gr_subject, gr_2_subj, gr_2, gr_9_subj, gr_9, gr_10_subj from {$g5['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($gr_in) {
			if(!chk_menu_exclude($gr_exclude, $row['gr_id'])) continue;
		} else {
			if(chk_menu_exclude($gr_exclude, $row['gr_id'])) continue;
		}

		if(!$is_admin && $row['gr_10_subj'] && (int)$row['gr_10_subj'] > 1) {
			if((int)$row['gr_10_subj'] > $member['mb_level']) continue;
		}

		//게시판 정리
		$sql2 = " select bo_table, bo_subject, bo_count_write, bo_count_comment, bo_category_list, bo_2_subj, bo_2, bo_9_subj, bo_10_subj from {$g5['board_table']} where gr_id = '{$row['gr_id']}' $bo_show and $bo_sql 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;

			if(!$is_admin && $row2['bo_10_subj'] && (int)$row2['bo_10_subj'] > 1) {
				if((int)$row2['bo_10_subj'] > $member['mb_level']) continue;
			}

			$board[$n] = $row2;
			$n++;
		}

		$board_cnt = count($board);	

		if(!$board_cnt && $row['gr_9_subj'] != 'view') continue;

		for ($k=0; $k < $board_cnt; $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_2_subj'] ? amina_fa($board[$k]['bo_2_subj']).' '.$board[$k]['bo_subject'] : $board[$k]['bo_subject']; //게시판 제목 - 여분필드 2번의 제목이 아이콘임
			$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'] = $board[$k]['bo_2'] ? $board[$k]['bo_2'] : G5_BBS_URL.'/board.php?bo_table='.$board[$k]['bo_table']; //링크 - 여분필드 2번에 링크가 있으면 그곳으로 이동
			$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++; //새글이 있는지 체크

			$list[$z]['board'][$k]['bo_cate'] = 0;
			if($board[$k]['bo_9_subj'] == "1") { //분류출력
			    $cate = explode("|", $board[$k]['bo_category_list']);
				for ($j=0; $j<count($cate); $j++) {
					$list[$z]['board'][$k]['cate'][$j]['name'] = $ca[$z]['board'][$j]['bo_subject'] = $cate[$j];
					$list[$z]['board'][$k]['cate'][$j]['href'] = $ca[$z]['board'][$j]['bo_href'] = G5_BBS_URL.'/board.php?bo_table='.$board[$k]['bo_table'].'&sca='.urlencode($cate[$j]);
					$list[$z]['board'][$k]['cate'][$j]['on'] = ($board[$k]['bo_table'] == $bo_table && $sca == $cate[$j]) ? 'on' : 'off'; //현재 선택게시판인지 표시
					$ca[$z]['board'][$k]['bo_on'] = $list[$z]['board'][$k]['cate'][$j]['on'];
				}
				$list[$z]['board'][$k]['bo_cate'] = $j;
			}
			$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_count_write'] = $gr_count_write; //글갯수
		$list[$z]['gr_count_comment'] = $gr_count_comment; //댓글갯수
		$list[$z]['gr_cnt'] = ($board_cnt == 1 && $row['gr_9_subj'] == "view") ? 2 : $board_cnt; //게시판 갯수

		if($list[$z]['gr_cnt'] == 1) { //게시판이 하나뿐일 때
			$list[$z]['gr_id'] = $list[$z]['board'][0]['bo_table'];
			$list[$z]['gr_subject'] = $list[$z]['board'][0]['bo_subject'];
			$list[$z]['gr_href'] = $list[$z]['board'][0]['bo_href'];
			$list[$z]['gr_on'] = $list[$z]['board'][0]['bo_on'];
			$list[$z]['gr_new'] = $list[$z]['board'][0]['bo_new'];
			if($list[$z]['board'][0]['bo_cate'] > 0) {
				$list[$z]['gr_cnt'] = $list[$z]['board'][0]['bo_cate'];
				$list[$z]['board'] = $ca[$z]['board'];
			} else {
				unset($list[$z]['board']); //그룹으로 보내고 게시판은 지움
			}
		} else {
			$list[$z]['gr_subject'] = $row['gr_2_subj'] ? amina_fa($row['gr_2_subj']).' '.$row['gr_subject'] : $row['gr_subject']; //그룹 제목 - 여분필드 2번 제목이 아이콘임
			$list[$z]['gr_href'] = $row['gr_2'] ? $row['gr_2'] : $list[$z]['board'][0]['bo_href']; // 여분필드 2번 내용에 링크가 있으면 그곳으로 이동 그렇지 않으면 첫번째 게시판 링크로 이동
			$list[$z]['gr_on'] = ($list[$z]['gr_id'] == $gr_id) ? 'on' : 'off'; //현재 선택 그룹인지 표시
			$list[$z]['gr_new'] = ($gr_new > 0) ? 'new' : 'old'; //새글이 있는지 체크
		}

		unset($pg);
		if($page_id && $row['gr_9']) {
			$pg = explode(",", $row['gr_9']);
			if(count($pg) > 0) $list[$z]['gr_on'] = in_array($page_id, $pg) ? 'on' : $list[$z]['gr_on'];
		}

		$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 $g5, $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 {$g5['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 {$g5['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 {$g5['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 {$g5['member_table']} "); 
	$lnb['join_total'] = $row['cnt'];

    return $lnb;
}

// HTML 마지막 처리
if (!function_exists('html_end')) {
	function html_end() {
	    global $config, $g5, $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);
	}
}

?>