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

//-------------------------------------------------------------------------------------
// AMINA Skin Lib for AMINA BBS & THEMA - Copyright (c) 2012 AMINA - http://amina.co.kr
//
// only for AMINA View Skin
//-------------------------------------------------------------------------------------

include_once(AMINA_PATH.'/lib/video.lib.php');

//Auto Move
function amina_move($board, $wr_id_list, $bo_table_list, $ca_name='', $sw='move') {
    global $g4, $member, $config, $is_admin, $amina;

	$chk_bo_table = array();
	$chk_bo_table = explode(",", $bo_table_list);
	$auto_move = true;
	$bo_table = $board['bo_table'];
    $write_table = $g4['write_prefix'].$bo_table;

	include_once(AMINA_PATH.'/move.func.php');

    alert('이동된 게시물입니다.', G4_BBS_URL.'/board.php?bo_table='.$bo_table);
}

//Show Video Player
function amina_video_content($vid, $mobile='') {
	global $g4_m;

	$video = array();
	$video = amina_video_info($vid, "view");

	//Player Size
	$auto_size = false;
	if(!$video['width']) {
		$video['width'] = 640;
		$auto_size = true;
	}

	if(!$video['height']) {
		switch($video['type']) {
			case 'nate'		: $video['height'] = 384; break;
			default			: $video['height'] = 360; break;			
		}
	}

	$v = $video['type'];
	$m_video = ((G4_IS_MOBILE && $g4_m[$v]) || ($mobile == "rss")) ? true : false;

	$video_show = '';

	if($m_video) {
		switch ($video['type']) {
			case 'youtube'		: $m_txt = 'Youtube'; break;
			case 'vimeo'		: $m_txt = 'Vimeo'; break;
			case 'daum'			: $m_txt = 'DaumTV'; break;
			case 'pandora'		: $m_txt = 'PandoraTV'; break;
			case 'nate'			: $m_txt = 'NateTV'; break;
			case 'ted'			: $m_txt = 'TED'; break;
			case 'tagstory'		: $m_txt = 'Tagstory'; break;
			case 'dailymotion'	: $m_txt = 'Dailymotion'; break;
		}

		if($m_txt) {
			$m_photo = amina_video_img($video['video_url'], $video['vid'], $video['type']);
			$video_show .= '<div class="m_video"><a href="'.$video['video'].'" target="_blank"><img src="'.$m_photo.'" class="mimg" alt="" /></a><p>['.$m_txt.'] 동영상을 보실려면 클릭해 주세요.</p></div>'."\n";
		}
	} else {
		if($video['type'] == "youtube") { //유튜브
			$show = '<iframe width="'.$video['width'].'" height="'.$video['height'].'" src="http://www.youtube.com/embed/'.$video['vid'].'" frameborder="0" allowfullscreen></iframe>';

		} else if($video['type'] == "vimeo") { //비메오
			if($video['auto']) $auto = "&amp;autoplay=1";
			$show = '<iframe src="http://player.vimeo.com/video/'.$video['vid'].'?title=0&amp;byline=0&amp;portrait=0&amp;color=ffffff'.$auto.'" width="'.$video['width'].'" height="'.$video['height'].'" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>';

		} else if($video['type'] == "ted") { //테드
			$show = '<iframe src="http://embed.ted.com'.$video['rid'].'" width="'.$video['width'].'" height="'.$video['height'].'" frameborder="0" scrolling="no" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>';

		} else if($video['type'] == "daum") { //다음TV
			$show = '<iframe width="'.$video['width'].'" height="'.$video['height'].'" src="http://videofarm.daum.net/controller/video/viewer/Video.html?vid='.$video['rid'].'&play_loc=undefined" frameborder="0" scrolling="no"></iframe>';

		} else if($video['type'] == "dailymotion") { //Dailymotion
			$show = '<iframe frameborder="0" width="'.$video['width'].'" height="'.$video['height'].'" src="http://www.dailymotion.com/embed/video/'.$video['vid'].'"></iframe>';

		} else if($video['type'] == "pandora") { //판도라TV
			if($video['auto']) $auto = "&amp;autoPlay=true";
			$show = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0" width="'.$video['width'].'" height="'.$video['height'].'" id="movie" align="middle">';
			$show .= '<param name="quality" value="high" /><param name="movie" value="http://flvr.pandora.tv/flv2pan/flvmovie.dll/userid='.$video['ch_userid'].'&amp;prgid='.$video['prgid'].'&amp;skin=1'.$auto.'&amp;share=on&countryChk=ko" /><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="true" /><param name="wmode" value="transparent" />';
			$show .= '<embed src="http://flvr.pandora.tv/flv2pan/flvmovie.dll/userid='.$video['ch_userid'].'&amp;prgid='.$video['prgid'].'&amp;skin=1'.$auto.'&amp;share=on&countryChk=ko" type="application/x-shockwave-flash" wmode="transparent" allowScriptAccess="always" allowFullScreen="true" pluginspage="http://www.macromedia.com/go/getflashplayer" width="'.$video['width'].'" height="'.$video['height'].'" /></embed></object>';

		} else if($video['type'] == "nate") { //네이트TV
			$show = '<object id="skplayer" name="skplayer" width="'.$video['width'].'" height="'.$video['height'].'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9.0.115.00">';
			$show .= '<param name="movie" value="http://v.nate.com/v.sk/movie/'.$video[vs_keys].'/'.$video[mov_id].'" /><param name="allowFullscreen" value="true" /><param name="allowScriptAccess" value="always" /><param name="wmode" value="transparent" />';
			$show .= '<embed src="http://v.nate.com/v.sk/movie/'.$video['vs_keys'].'/'.$video['mov_id'].'" wmode="transparent" allowScriptAccess="always" allowFullscreen="true" name="skplayer" width="'.$video['width'].'" height="'.$video['height'].'" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /></object>';

		} else if($video['type'] == "tagstory") { //Tagstory

			$show = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,16,0" width="'.$video['width'].'" height="'.$video['height'].'" id="ScrapPlayer" >';
			$show .= '<param name="movie" value="http://www.tagstory.com/player/basic/'.$video['vid'].'" /><param name="wmode" value="transparent" /><param name="quality" value="high" /><param name="allowScriptAccess" value="always" /><param name="allowNetworking" value="all" /><param name="allowFullScreen" value="true" />';
			$show .= '<embed src="http://www.tagstory.com/player/basic/'.$video[vid].'" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,16,0" id="ScrapPlayer" name="ScrapPlayer" width="'.$video['width'].'" height="'.$video['height'].'" wmode="transparent" quality="high" allowScriptAccess="always" allowNetworking="all" allowFullScreen="true" /></object>';
		}

		if($show) {
			$v_css = (G4_IS_MOBILE || $auto_size) ? 'm_' : '';
			$video_show .= '<div class="'.$v_css.'video-container">';
			$video_show .= $show;
			$video_show .= '</div>'."\n";
		}
	}

	return $video_show;
}

//Syntaxhighlighter
function amina_syntaxhighlighter($m) {

	$str = $m[1];
	$str = str_replace(array("<br>", "<br/>", "<br />", "<div>", "</div>", "<p>", "</p>", "&nbsp;"), array("\n", "\n", "\n", "", "", "\n", "", "\t"), $str);
	$str = stripslashes($str);

	return '<pre class="brush:php;">'.$str.'</pre>';
}

//Google Map
function amina_google_map($marker, $map_info) {

	if(!$map_info) return;

	$map = array();
	$map = amina_array_map($map_info);

	if(!$map['map_lat'] || !$map['map_lng']) return;

	if(!$map['map_width'] || $map['map_width'] < 0) $map['map_width'] = 640;
	if(!$map['map_height'] || $map['map_height'] < 0) $map['map_height'] = 450;
	if(!$map['map_zoom'] || $map['map_zomm'] < 0) $map['map_zoom'] = 14;
	if($marker) {
		$marker = preg_replace('/\<div[^\<\>]*\>/i', '', $marker);
		$marker = str_replace(array('\"', "\r", "\n", "\r\n", "</div>"), array("", "", "", "", "<br />"), $marker);
	} else {
		$marker = "Here!";
	}

	ob_start();
	include AMINA_PATH.'/google.map.load.php';
    $load_map = ob_get_contents();
    ob_end_clean();

	return $load_map;
}

//Good
function amina_good_skin($skin, $bo_table, $wr_id, $good_cnt, $nogood_cnt){
	global $board;

	if(!$bo_table || !$wr_id) return;

	$good_skin_path = AMINA_PATH.'/skin/good/'.$skin;
	$good_skin_url = AMINA_URL.'/skin/good/'.$skin;

	ob_start();
	include_once($good_skin_path.'/load.style.php');
	include $good_skin_path.'/good.skin.php';
	$view_good = ob_get_contents();
    ob_end_clean();

	return $view_good;
}

//Star
function amina_star_skin($skin, $bo_table, $wr_id, $wr_7, $opt=false){
	global $amina;

	if(!$bo_table || !$wr_id) return;

	$star_skin_path = AMINA_PATH.'/skin/star/'.$skin;
	$star_skin_url = AMINA_URL.'/skin/star/'.$skin;

	ob_start();
	if(!$opt) {
		include_once($star_skin_path."/load.style.php");
		echo "<div id=\"view_star".$wr_id."\">\n";
	}
	if(G4_IS_MOBILE && file_exists($star_skin_path.'/m.star.skin.php')) {
		include $star_skin_path.'/m.star.skin.php';
	} else {
		include $star_skin_path.'/star.skin.php';
	}
	if(!$opt) echo "</div>\n";

	$view_star = ob_get_contents();
    ob_end_clean();

	return $view_star;
}

//Sign
function amina_sign_skin($skin, $bo_table, $wr_id, $mb_id, $name, $signature){
	global $g4, $amina;

	if(!$bo_table || !$wr_id || !$mb_id) return;

	$xp = xp_info($mb_id); //현재 레벨
	$xp['icon'] = xp_icon($mb_id, $xp['level']);

	if(!$signature) $signature = '등록된 서명이 없습니다.';

	$sign_skin_path = AMINA_PATH.'/skin/sign/'.$skin;
	$sign_skin_url = AMINA_URL.'/skin/sign/'.$skin;

	ob_start();
	include_once($sign_skin_path.'/load.style.php');
	if(G4_IS_MOBILE && file_exists($sign_skin_path.'/m.sign.skin.php')) {
		include $sign_skin_path.'/m.sign.skin.php';
	} else {
		include $sign_skin_path.'/sign.skin.php';
	}
	$view_sign = ob_get_contents();
    ob_end_clean();

	return $view_sign;
}

//Attach
function amina_attach_skin($skin, $bo_table, $wr_id, $view, $opt=''){
	global $g4, $amina;

	if(!$bo_table || !$wr_id) return;

	$attach_skin_path = AMINA_PATH.'/skin/attach/'.$skin;
	$attach_skin_url = AMINA_URL.'/skin/attach/'.$skin;

	ob_start();
	include_once($attach_skin_path.'/load.style.php');
	if(G4_IS_MOBILE && file_exists($attach_skin_path.'/m.attach.skin.php')) {
		include $attach_skin_path.'/m.attach.skin.php';
	} else {
		include $attach_skin_path.'/attach.skin.php';
	}
	$view_attach = ob_get_contents();
    ob_end_clean();

	return $view_attach;
}

//Summary
function amina_preview_skin($skin, $bo_table, $wr_id, $view, $title){
	global $g4, $board, $page, $qstr;

	if(!$bo_table || !$wr_id) return;

	if($view['wr_3']) {
		$desc = amina_text($view['wr_3']);
	} else {
		$desc = amina_cut($view['wr_content'], 250); //요약글이 없으면, 본문 내용의 일부를 사용함
	}

	$icon = amina_array_icon($view['wr_5']);
	$preview_cnt = (int)$icon['po_img_cnt'];
	if($preview_cnt > 0) {
		$preview = array();		
		$preview = amina_thumb_img($view['file'], $view['wr_6'], $view['wr_content'], $preview_cnt, $view['wr_4'], $view['wr_8'], '');
		$preview_img = '';
		for($i=0;$i < count($preview);$i++) {
			$preview_img .= '<p class="img_space"><img src="'.$preview[$i].'" alt="" /></p>'."\n";
		}

		if($preview_img) $preview_img = amina_resize_content($preview_img, (int)$board['bo_image_width']);
	}

	$preview_skin_path = AMINA_PATH.'/skin/preview/'.$skin;
	$preview_skin_url = AMINA_URL.'/skin/preview/'.$skin;

	ob_start();
	include_once($preview_skin_path.'/load.style.php');
	if(G4_IS_MOBILE && file_exists($preview_skin_path.'/m.preview.skin.php')) {
		include $preview_skin_path.'/m.preview.skin.php';
	} else {
		include $preview_skin_path.'/preview.skin.php';
	}
	$view_preview = ob_get_contents();
    ob_end_clean();

	return $view_preview;
}

//Poll
function amina_poll_skin($skin, $bo_table, $wr_id, $mb_id, $opt=false){
	global $g4, $board, $frame, $bo_it, $bo_linked, $bo_row;

	if(!$bo_table || !$wr_id) return;

	$poll = array();
	$poll = sql_fetch(" select * from {$g4['amina_poll']} where bo_table = '$bo_table' and wr_id = '$wr_id' limit 1 ");

	if(!$poll['poll_id']) return;

	$poll_subject = cut_hangul_last(get_text($poll['poll_subject']));
	$poll_status = '';

	$poll_endtime = strtotime($poll['poll_enddate']);
	if(G4_SERVER_TIME > $poll_endtime) $poll_status = 'end';

	if(!$poll_status) {
		if($poll['poll_level']) {
			if($mb_id) {
				$row = sql_fetch(" select poll_id from {$g4['amina_polllog']} where bo_table = '$bo_table' and wr_id = '$wr_id' and mb_id = '$mb_id' limit 1 ");
				if($row['poll_id']) $poll_status = 'done';
			} 
		} else {
			if($mb_id) {
				$poll_done = "and ( mb_id = '$mb_id' or poll_ip = '{$_SERVER['REMOTE_ADDR']}')";
			} else {
				$poll_done = "and poll_ip = '{$_SERVER['REMOTE_ADDR']}'";
			}
			$row = sql_fetch(" select poll_id from {$g4['amina_polllog']} where bo_table = '$bo_table' and wr_id = '$wr_id' $poll_done limit 1 ");
			if($row['poll_id']) $poll_status = 'done';
		}
	}

	$poll_skin_path = AMINA_PATH.'/skin/poll/'.$skin;
	$poll_skin_url = AMINA_URL.'/skin/poll/'.$skin;

	ob_start();
	if(!$opt) {
		include_once($poll_skin_path.'/load.style.php');
		echo "<div id=\"view_poll".$wr_id."\">\n";
	}
	if(G4_IS_MOBILE && file_exists($poll_skin_path.'/m.poll.skin.php')) {
		include $poll_skin_path.'/m.poll.skin.php';
	} else {
		include $poll_skin_path.'/poll.skin.php';
	}
	if(!$opt) echo "</div>\n";

	$view_poll = ob_get_contents();
    ob_end_clean();

	return $view_poll;
}

//Related info
function amina_related_skin($skin, $bo_table, $it_id){
	global $g4, $config, $board, $board_skin_path, $board_skin_url, $frame;

	if(!$it_id) return;

	$is_related = $view_related = '';

	$related_skin_path = AMINA_PATH.'/skin/related/'.$skin;
	$related_skin_url = AMINA_URL.'/skin/related/'.$skin;

	if($bo_table) { //게시판 연동
		$bo = sql_fetch(" select * from {$g4['board_table']} where bo_table = '$bo_table' ");
		if($bo['bo_table']) {
			$tmp_write_table = $g4['write_prefix'] . $board['bo_table'];
			$row = sql_fetch(" select * from $tmp_write_table where wr_id = '$it_id' limit 1");
			if($row['wr_id']) {
				$list = get_list($row, $board, $board_skin_url, $subject_len);
				$is_related = 'board';
				$list['bo_subject'] = $bo['bo_subject'];
			}
		}
	} else { //영카트
		$it_img = G4_DATA_PATH."/item/".$it_id."_l1";
		if(file_exists(G4_LIB_PATH."/shop.lib.php") && file_exists($it_img)) { //상품이미지
			$it = amina_it_info($it_id);
			if($it['it_id']) {
				include_once(G4_LIB_PATH."/shop.lib.php");
				$is_related = 'youngcart';
			}
		}
	}

	if($is_related) {
		ob_start();
		include_once($related_skin_path.'/load.style.php');
		if(G4_IS_MOBILE && file_exists($related_skin_path.'/m.related.skin.php')) {
			include $related_skin_path.'/m.related.skin.php';
		} else {
			include $related_skin_path.'/related.skin.php';
		}
	    $view_related = ob_get_contents();
	    ob_end_clean();
	} 

	return $view_related;
}

// Comment Reset
function amina_cmt_list($row, $stx, $photo='56', $opt='') {
	global $g4, $config, $board, $amina, $member, $is_admin, $write, $is_ip_view, $lurl, $surl, $bo_table, $wr_id, $frame, $go_url, $token, $cwin, $page, $qstr, $cmt_url;

	$list = array();

	$list = $row;

	$list['comment_id'] = $row['wr_id'];

	//xp 및 모바일 아이콘
	$wr_5 = amina_array_icon($row['wr_5']);

	$list['level'] = $wr_5['level'];
	$list['mobile'] = $wr_5['mobile'];
	$list['choice'] = $wr_5['choice'];
	$list['choice_mb'] = $wr_5['choice_mb'];
	$list['post_cool'] = $wr_5['post_cool'];
	$list['datetime'] = date("Y.m.d H:i:s", strtotime($row['wr_datetime']));
	$list['level_icon'] = xp_icon($list['mb_id'], $list['level']);

	//Secret
	$list['is_secret'] = (strstr($row['wr_option'], "secret")) ? true : false;
	
	//Shingo
	$list['is_blind'] = ($row['wr_9'] == "lock" || $row['wr_9'] == "shingo") ? true : false;

	//Photo
	switch($amina['cmt_photo']) {
		case '1'	: $list['mb_photo'] = mb_photo($member['mb_id'], $row['mb_id'], $photo, $photo); break;
		case '2'	: $list['mb_photo'] = mb_photo($member['mb_id'], $row['mb_id'], $photo, $photo, "is"); break;
		default		: $list['mb_photo'] = ''; break;
	}
	
	//Cool & Bad
	if($amina['cmt_cool']) {
		switch($list['post_cool']) {
			case '<cool>'	: $list['cool_txt'] = '<span class="cmt_cool">'.$amina['cmt_cool_txt'].'</span>&nbsp; '; break;
			case '<bad>'	: $list['cool_txt'] = '<span class="cmt_bad">'.$amina['cmt_bad_txt'].'</span>&nbsp; '; break;
			default			: $list['cool_txt'] = ''; break;
		}
	}

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

	if ($is_admin || $is_ip_view) { 
		if (!$is_admin) $row['wr_ip'] = preg_replace("/([0-9]+).([0-9]+).([0-9]+).([0-9]+)/", "\\1.♡.\\3.\\4", $row['wr_ip']); 
		$list['ip'] = ' ('.$row['wr_ip'].')'; 
	} else {
		$list['ip'] = '';
	}

	//SNS Icon
	if ($list['is_blind'] || $list['is_secret'] || $amina['cmt_sns'] == "none") { 
		$list['sns'] = '';
	} else {
		$clurl = $lurl.'#c_'.$row['wr_id'];
		$csurl = ($amina['use_surl'] == "1") ? $surl.'#c_'.$row['wr_id'] : $sulr;

		switch($opt) {
			case 'best'		: $sns_id = 'best_sns'.$row['wr_id']; break;
			case 'choice'	: $sns_id = 'choice_sns'.$row['wr_id']; break;
			default			: $sns_id = 'cmt_sns'.$row['wr_id']; break;
		}
		$list['sns'] = amina_sns($sns_id, $amina['cmt_sns'], '', $row['wr_content'], $clurl, $csurl, '', 'cmt');
	} 

	//Blind
	switch($row['wr_9']) {
		case 'lock'		: $list['blind_msg'] = '관리자가 블라인드 처리한 댓글입니다.'; break;
		case 'shingo'	: $list['blind_msg'] = '신고누적으로 블라인드 처리된 댓글입니다.'; break;
		default			: $list['blind_msg'] = ''; break;
	}

	//Best
	$list['is_best'] = ($amina['cmt_best'] > 0 && $row['wr_good'] >= $amina['cmt_best']) ? true : false;

	//Content
	$str = '';
	if(!$list['is_blind'] || $is_admin) {
	    $str = '비밀글 입니다.';
	    if (!$list['is_secret'] || $is_admin || ($write['mb_id']==$member['mb_id'] && $member['mb_id']) || ($row['mb_id']==$member['mb_id'] && $member['mb_id'])) {
		        //$str = search_font($stx, conv_content($row['wr_content'], 0, 'wr_content'));
				$str = $row['content'];
				$str = preg_replace("/\[\<a\s.*href\=\"(http|https|ftp|mms)\:\/\/([^[:space:]]+)\.(mp3|wma|wmv|asf|asx|mpg|mpeg)\".*\<\/a\>\]/i", "<script>doc_write(obj_movie('$1://$2.$3'));</script>", $str);
				if(G4_IS_MOBILE) {
					$str = preg_replace("/\[\<a\s*href\=\"(http|https|ftp)\:\/\/([^[:space:]]+)\.(gif|png|jpg|jpeg|bmp)\"\s*[^\>]*\>[^\s]*\<\/a\>\]/i", "<img src='$1://$2.$3' class='mimg' alt='' border='0'>", $str);
				} else {
					$str = preg_replace("/\[\<a\s*href\=\"(http|https|ftp)\:\/\/([^[:space:]]+)\.(gif|png|jpg|jpeg|bmp)\"\s*[^\>]*\>[^\s]*\<\/a\>\]/i", "<img src='$1://$2.$3' class='aimg' onclick='amina_img(\"$1://$2.$3\");' alt='' border='0'>", $str);
				}

				//Syntaxhighlighter
				if($amina['view_code']) $str = preg_replace_callback("/\[code\](.*)\[\/code\]/iUs", "amina_syntaxhighlighter", $str);

				//Video
				$str = preg_replace("/{동영상\:([^}]*)}/ie", "amina_video_content('\\1','')", $str);

		}
		if ($list['is_secret']) $str = '<span class="cmt_secret">* '.$str.'</span>';
		if ($row['wr_trackback']) $str .= '<p>'.url_auto_link($row['wr_trackback']).'</p>';
	}

	$list['content'] = $str;

	//Link
	$list['lock_link'] = "javascript:amina_shingo('".AMINA_URL."/blind.php?bo_table=".$bo_table."&wr_id=".$list['comment_id']."&act=lock','lock');";
	$list['unlock_link'] = "javascript:amina_shingo('".AMINA_URL."/blind.php?bo_table=".$bo_table."&wr_id=".$list['comment_id']."&act=unlock','unlock');";
	$list['shingo_link'] = "javascript:amina_shingo('".AMINA_URL."/blind.php?bo_table=".$bo_table."&wr_id=".$list['comment_id']."','shingo');";

	if(preg_match("/password\.php/i", $row['del_link'])) {
		$row['del_link'] = str_replace("./", G4_BBS_URL."/", $row['del_link']);
		$del_opt = '';
		if($frame && $go_url) {
			$del_opt = 1;
			$row['del_link'] = str_replace("&frame=ok", "", $row['del_link']);
		}
		$list['del_link']  = "javascript:comment_delete('".$row['del_link']."','".$del_opt."');";
	} else {
		$del_link = AMINA_URL."/comment.php?w=cd&bo_table=".$bo_table."&comment_id=".$list['comment_id'];
		if($token) $del_link .= "&token=".$token;
		if($cwin) $del_link .= "&cwin=".$cwin;
		if($page) $del_link .= "&page=".$page;
		if($qstr) $del_link .= $qstr;
		if($go_url) $del_link .= "&go_url=".urlencode(urlencode($go_url));
		$list['del_link']  = "javascript:amina_cmt_del('".$del_link."','cmt_".$wr_id."','".$cmt_url."');";
	}

	$list['choice_link'] = AMINA_URL."/choice.php?bo_table=".$bo_table."&wr_id=".$list['comment_id'];

	$good_opt = '';
	if($list['is_best']) $good_opt = '&type=best';
	if($list['choice']) $good_opt = '&type=choice';
	$list['good_link'] = AMINA_URL.'/good.php?bo_table='.$bo_table.'&wr_id='.$list['comment_id'].'&good=good'.$good_opt.'&mode=c';

	return $list;
}

//Show Contents
function amina_view_contents($wr_content, $wr_file, $wr_6, $wr_opt, $width='640', $mobile='', $map_info='', $code='') {
	global $g4, $board, $bo_table, $board_skin_path, $board_skin_url, $amina;

	//Mobile
	if($mobile == "rss") $board['no_view_resize'] = true; 

	if($wr_opt['img_location'] == "insert") {
		if(AMINA == "g4s") {
			$wr_content = str_replace("class=\"view_image\"","class=\"view_image_no\"", $wr_content);
		}
		$content = $wr_content;		
	} else if($wr_opt['img_location'] == "hide") {
		$content = $wr_content;
	} else {
		$file = '';
		$img_css = $wr_opt['img_space'] ? '' : ' style="margin-bottom:15px;"';
		for ($i=0; $i<=count($wr_file); $i++) {
		    if($wr_file[$i]['view']) {
				$file .= '<img src="'.G4_DATA_URL.'/file/'.$board['bo_table'].'/'.urlencode($wr_file[$i]['file']).'" alt="'.$wr_file[$i]['content'].'" '.$img_css.'>'."\n";
			}
		}

		$content = '';
		if($file && $wr_opt['img_location'] != "bottom") {
			$content .= '<div class="attach-img">';
			$content .= $file;
			$content .= '</div>';
			if(G4_IS_MOBILE || $wr_opt['img_space'] || $board['is_print']) $content .= '<br />';
		}
		$content .= $wr_content;
		if($file && $wr_opt['img_location'] == "bottom") {
			if($wr_opt['img_space']) $content .= '<br />';
			$content .= '<div class="attach-img">';
			$content .= $file;
			$content .= '</div>';
		}
	}

	$content = amina_resize_content($content, $width);

	//Syntaxhighlighter
	if($code) $content = preg_replace_callback("/\[code\](.*)\[\/code\]/iUs", "amina_syntaxhighlighter", $content);

	//Google Map
	if($map_info) $content = preg_replace("/\[map\](.*)\[\/map\]/ies", "amina_google_map('\\1','{$map_info}')", $content);

	//Video
	$content = preg_replace("/{동영상\:([^}]*)}/ie", "amina_video_content('\\1','{$mobile}')", $content);

	$view_content = '';
	if($wr_6) {
		$video = amina_array_video($wr_6);
		if($video['movie_url']) $view_content .= amina_video_content($video['movie_info'], $mobile);
	}
	$view_content .= $content;

	return $view_content;
}


// 한별아빠 수정사항 - 본문 썸네일 출력관련 부분만 별도 정리 - 함수충돌방지를 위해 각 함수명에 amina_ 붙임

// 프로그램 : 그누보드 불당팩 라이브러리 
// 개 발 자 : 아빠불당 (echo4me@gmail.com)
//
// 저 작 권 : GPL2
// 불당팩 : 이미지 resize (청춘불안정 : http://www.sir.co.kr/bbs/board.php?bo_table=cm_free&wr_id=306629)
function amina_resize($string)
{ 
    global $g4, $board;

    //print_r($board);

    // 전역변수를 받아들이기 때문에 설정값이 없으면, 기본으로 게시판의 폭을 지정. 게시판 폭도 없으면 기본으로 500
    $max_img_width = (int) $board['resize_img_width'];
    if ($max_img_width <= 0) {
        if ((int)$board['bo_image_width'] > 0)
            $max_img_width = $board['bo_image_width'];
        else
            $max_img_width = 640;
    }
    
    // max_img_height에 값이 있는 경우는 crop을 허용 합니다.
    $max_img_height = (int) $board['resize_img_height'];
    $is_crop = false;
    if ($max_img_height > 0)
        $is_crop = true;

    // 실행할 때마다 image를 create할지 설정 (무조건 false)
    $is_create = false;
    
    // 이미지의 quality 값을 설정 (없으면, thumb의 기본값으로 90이 적용됨)
    $quality = (int) $board['resize_img_quality'];
    if ($quality <= 0)
        $quality = 90;

    // $water_mark 변수를 전달 받습니다
    $water_mark = $board['water_mark'];

    // $board[thumb_create]에 값이 있으면 무조건 썸네일을 생성 합니다.
    if ($board['thumb_create'])
        $thumb_create = 1;

    // 이미지 필터 - 기본으로 UnSharpMask
    if ($board['image_filter']) {
        $filter['type'] = $board['image_filter']['type'];
        $filter['arg1'] = $board['image_filter']['arg1'];
        $filter['arg2'] = $board['image_filter']['arg2'];
        $filter['arg3'] = $board['image_filter']['arg3'];
        $filter['arg4'] = $board['image_filter']['arg4'];
    } else {
        $filter['type'] = 99;
        $filter['arg1'] = 10;
        $filter['arg2'] = 1;
        $filter['arg3'] = 2;
    }

    // 변수를 setting
    $return = $string['0']; 
	$img = amina_value($return);

    // 실제 디렉토리 이름을 구하고 절대경로에서 잘라낼 글자수를 계산
    $real_dir = dirname($_SERVER['DOCUMENT_ROOT'] . '/nothing');
    $cut_len = strlen($real_dir);

    // 가끔씩 img의 파일이름이 깨어지는 경우가 있어서 decoding 해줍니다 (예: &#111;&#110; = on)
    $img['src'] = html_entity_decode($img['src']); 

    // 이미지 파일의 경로를 설정 (외부? 내부? 내부인경우 절대경로? 상대경로?)
    if (preg_match("/^(http|https|ftp|telnet|news|mms)\:\/\//i", $img['src'])) {
        // 내 서버에 있는 이미지?
        $img_src = @getimagesize($img['src']);
        if (preg_match('/' . $_SERVER['HTTP_HOST'] . '/', $img['src'], $matches)) {
            $url = parse_url($img['src']);
            $img['src'] = $url['path'];
            $thumb_path = '1';
        } else {
            $thumb_path = '';
        }
    } else {
        $thumb_path = '1';
    }

    if ($thumb_path) {
        $dir = dirname(amina_file_path($img['src']));
        $file = basename($img['src']);
        $img_path = $dir . '/' . $file;
        // 첨부파일의 이름은 urlencode로 들어가게 됩니다. 따라서, decode해줘야 합니다. (/bbs/write_update.php 참조)
        $img_path = urldecode($img_path);
        $img_src = @getimagesize($img_path);
        // 잊어버리지말고 여기도 urldecode 해줘야죠?
        $thumb_path = urldecode($img['src']);
    }

    // 이미지파일의 정보를 얻지 못했을 때
	if(preg_match("/\/(cheditor5|amina\/app|plugin|skin)\//i", $img['src'])) {
		$img_css = '';
		$img_big = false;
	} else {
		$img_css = (G4_IS_MOBILE || $board['is_print']) ? "class='mimg'" : "class='aimg'";
		$img_big = true;
	}

	// 이미지팝업 삭제...
	$return = preg_replace('/height\=(\'|\")?[^\s\'\"]+(\'|\")?/i', '', $return); 

	if (!$img_src) {
		if(G4_IS_MOBILE || $board['is_print']) {
			$return = preg_replace('/name\=(\'|\")?[^\s\'\"]+(\'|\")?/i', '', $return); 
			$return = preg_replace('/style\=(\'|\")?[^\s\'\"]+(\'|\")?/i', '', $return); 
			$return = preg_replace('/class\=(\'|\")?[^\s\'\"]+(\'|\")?/i', '', $return); 
			$return = preg_replace('/width\=(\'|\")?[^\s\'\"]+(\'|\")?/i', '', $return); 
			$return = preg_replace('/height\=(\'|\")?[^\s\'\"]+(\'|\")?/i', '', $return); 
			$return = preg_replace("/(\<img )([^\>]*)(\>)/i", "\\1 $img_css \\2 \\3", $return);
		} else {
		    if((int)$img['width'] > $max_img_width) {
				$return = preg_replace('/width\=(\'|\")?[^\s\'\"]+(\'|\")?/i', 'width="' . $max_img_width . '"', $return); 
				$return = preg_replace('/height\=(\'|\")?[^\s\'\"]+(\'|\")?/i', '', $return); 
			}
			$return = preg_replace("/(\<img )([^\>]*)(\>)/i", "\\1 $img_css \\2 \\3", $return);
			if($img_big) $return = preg_replace("/(\<img )([^\>]*)(\>)/i", "\\1 onClick='amina_img(\"".$img['src']."\")' \\2 \\3", $return);
		}

		return $return;
    }

    // 이미지생성의 최소 넓이가 있으면, 이미지가 그 크기 이상일때만, 썸을 만들어야징.
    // 이거는 작은 아이콘 같은 것의 썸을 만들지 않게 하려고 하는거임
    if ($board['image_min'] && $img_src[0] < $board['image_min'])
        return $return;

    // 이미지 파일의 크기를 구해서
    $fsize = amina_filesize2bytes(filesize($img_path));

    // 이미지 파일의 전체 크기와 갯수 저장
    if ($board['bo_image_info']) {
        $g4['resize']['image_size'] = $g4['resize']['image_size'] + $fsize/1000;
        $g4['resize']['image_count'] = $g4['resize']['image_count'] + 1;
        $g4['resize']['image_file'][] = $img_path;
    }

    // 이미지생성의 최소 파일용량이 있으면, 이미지가 그 파일크기 이상일때만, 썸을 만들어야징.
    // 이거는 작은 아이콘 같은 것이나 효율적으로 줄어든 이미지의 썸을 만들지 않게 하려고 하는거임
    if ($board['image_min_kb']) {
        // 용량은 kb에서 byte로 바꿔서
        $min_kb = $board['image_min_kb']*1024;
        if ($fsize < $min_kb) {
            return $return;
        }
    }

	// 썸네일 생성여부
	if (!$board['no_view_resize'] && ((int)$img_src[0] > $max_img_width || $thumb_create) && $thumb_path) {
		$thumb_path = bthumbnail($thumb_path, $max_img_width,$max_img_height,$is_create,$is_crop,$quality, '', $water_mark, $filter);
		if(!G4_IS_MOBILE && !$board['is_print']) $return = preg_replace('/src\=(\'|\")?[^\s\'\"]+(\'|\")?/i', 'src="' . $thumb_path . '"', $return);
	}

	// onclick 삭제
	$return = preg_replace('/onClick\=(\'|\")?[^\s\'\"]+(\'|\")?/i', '', $return);

	if(G4_IS_MOBILE || $board['is_print']) {
		$return = preg_replace('/name\=(\'|\")?[^\s\'\"]+(\'|\")?/i', '', $return); 
		$return = preg_replace('/style\=(\'|\")?[^\s\'\"]+(\'|\")?/i', '', $return); 
		$return = preg_replace('/class\=(\'|\")?[^\s\'\"]+(\'|\")?/i', '', $return); 
		$return = preg_replace('/width\=(\'|\")?[^\s\'\"]+(\'|\")?/i', '', $return); 
		$return = preg_replace('/height\=(\'|\")?[^\s\'\"]+(\'|\")?/i', '', $return); 
		$return = preg_replace("/(\<img )([^\>]*)(\>)/i", "\\1 $img_css \\2 \\3", $return);
	} else {
		if((int)$img['width'] > $max_img_width) {
			$return = preg_replace('/width\=(\'|\")?[^\s\'\"]+(\'|\")?/i', 'width="' . $max_img_width . '"', $return); 
			$return = preg_replace('/height\=(\'|\")?[^\s\'\"]+(\'|\")?/i', '', $return); 
		} else {
			$width = (!$img['width'] && $img_src[0] > $max_img_width) ? 'width="'.$max_img_width.'"' : '';
		}

		$return = preg_replace("/(\<img )([^\>]*)(\>)/i", "\\1 $img_css \\2 \\3", $return);
		if($img_big) $return = preg_replace("/(\<img )([^\>]*)(\>)/i", "\\1 $width onClick='amina_img(\"".$img['src']."\", \"".$img_src[0]."\", \"".$img_src[1]."\")' \\2 \\3", $return);
	}

    return $return; 
}

// $content                                   : resize할 img 태그가 있는 html
// $width         = $board[resize_img_width]  : 최대 이미지의 폭 (값이 없으면 $board[bo_img_width] 값을 씁니다
// $height        = $board[resize_img_height] : 최대 이미지의 높이 (이것이 지정되면 $is_crop = true가 됩니다) 값이 없으면, 비율대로 줄이고 crop 하지 않습니다.
// $quality       = $board[resize_img_quality]: 썸네일 이미지의 quality (없으면 기본값, 70%를 사용)
// $thumb_create  = $board[thumb_create]      : 이미지의 폭이 지정보다 작은경우에도 썸네일을 생성할지를 지정
// $image_window  = $board[image_window]      : 이미지를 누를때 팝업창을 띄울 것인지를 선택 (1: 팝업)
// $water_mark    = $board[water_mark]        : 워터마크
// $image_filter  = $board[image_filter]      : 이미지필터
// $image_min     = $board[image_min]         : 값이 있으면, $thumb_create=1이더라도 image_min 이상의 폭의 이미지에 대해서만, 썸을 만든다
// $image_min_kb  = $board[image_min_kb]      : 값이 있으면, $thumb_create=1이더라도 image_kb 이상의 이미지 용량에 대해서만, 썸을 만든다
function amina_resize_content($content, $width=0, $height=0, $quality=0, $thumb_create=0, $image_window=1, $water_mark='', $image_filter='', $image_min=0, $image_min_kb=0)
{
    global $g4, $board;

    if ($width > 0)
        $board['resize_img_width'] = (int)$width;
    else
        $board['resize_img_width'] = 0;

    if ($height > 0)
        $board['resize_img_height'] = (int)$height;
    else
        $board['resize_img_height'] = 0;

    if ($quality > 0)
        $board['resize_img_quality'] = (int)$quality;
    else
        $board['resize_img_quality'] = 90;

    if ($thumb_create)
        $board['thumb_create'] = 1;
    else
        $board['thumb_create'] = 0;

    if ($image_window)
        $board['image_window'] = 1;
    else
        $board['image_window'] = 0;

    if ($image_min)
        $board['image_min'] = $image_min;

    if ($image_min_kb)
        $board['image_min_kb'] = $image_min_kb;

    if ($water_mark)
        $board['water_mark'] = $water_mark;

    if ($image_filter)
        $board['image_filter'] = $image_filter;
    
    return preg_replace_callback('/\<img[^\<\>]*\>/i', 'amina_resize', $content);
}

// $content                                   : resize할 img 태그가 있는 html
// $image_min     = $board[image_min]         : 값이 있으면, $thumb_create=1이더라도 image_min 이상의 폭의 이미지에 대해서만, 썸을 만든다
// $image_min_kb  = $board[image_min_kb]      : 값이 있으면, $thumb_create=1이더라도 image_kb 이상의 이미지 용량에 대해서만, 썸을 만든다
// $quality       = $board[resize_img_quality]: 썸네일 이미지의 quality (없으면 기본값, 70%를 사용)
// $image_window  = $board[image_window]      : 이미지를 누를때 팝업창을 띄울 것인지를 선택 (1: 팝업)
function amina_resize_dica($content, $image_min=0, $image_min_kb=0, $quality=90, $image_window=1)
{
    global $g4, $board;

    $board['image_min'] = (int)$image_min;

    $board['image_min_kb'] = (int)$image_min_kb;

    $board['resize_img_quality'] = (int)$quality;

    $board['image_window'] = $image_window;

    return preg_replace_callback('/\<img[^\<\>]*\>/i', 'amina_resize', $content);
}

/** 
 * Converts human readable file size (e.g. 10 MB, 200.20 GB) into bytes. 
 * 
 * @param string $str 
 * @return int the result is in bytes 
 * @author Svetoslav Marinov 
 * @author http://slavi.biz 
 */ 

function amina_filesize2bytes($str) { 
    $bytes = 0; 

    $bytes_array = array( 
        'B' => 1, 
        'KB' => 1024, 
        'MB' => 1024 * 1024, 
        'GB' => 1024 * 1024 * 1024, 
        'TB' => 1024 * 1024 * 1024 * 1024, 
        'PB' => 1024 * 1024 * 1024 * 1024 * 1024, 
    ); 

    $bytes = floatval($str); 

    if (preg_match('#([KMGTP]?B)$#si', $str, $matches) && !empty($bytes_array[$matches[1]])) { 
        $bytes *= $bytes_array[$matches[1]]; 
    } 

    $bytes = intval(round($bytes, 2)); 

    return $bytes; 
} 

?>