<?
/*********************************** 게시판 관리 *************************************/

//게시판 디비 만들기
function makeBoard($boardid){
	// 테이블 중복검사(게시판용 테이블이 아닌 일반용에서)
	$tblid = $GLOBALS["_SITE"]["BOARD_PREWORD"] . $boardid;
	
	$sql = "SHOW TABLES FROM ".$GLOBALS["_conf_db"]["main_db"]["db"];
	$result = mysql_query($sql);
	if (!$result) {
		jsMsg("테이블 선택 실패");
		jsHistory("-1") ;
	}

	while ($row = mysql_fetch_row($result)) {
		if($tblid == $row[0]) {
			jsMsg("이미 사용중인 테이블 입니다.");
			jsHistory("-1") ;
		}
	}

	//게시판 정보 테이블에 입력
	$sql = "INSERT INTO ".$GLOBALS["_conf_tbl"]["board_info"]." set 
		boardid='$boardid',
		wdate=now()
	";


    $rs = mysql_query($sql, $GLOBALS["dblink"]);
    $total = mysql_affected_rows($GLOBALS["dblink"]);

	if($total > 0){
		//게시판 테이블 생성
		$sql = "CREATE TABLE $tblid (
			idx int(10) unsigned NOT NULL auto_increment COMMENT '일련번호',
			no tinyint(1) unsigned DEFAULT '1' NOT NULL COMMENT '정렬용 번호',
			main int(10) unsigned DEFAULT '99999999' NOT NULL COMMENT '원글번호',
			sub tinyint(3) unsigned DEFAULT '0' NOT NULL COMMENT '답글위치',
			depth tinyint(3) unsigned DEFAULT '0' NOT NULL COMMENT '답글깊이',
			w_user varchar(20) NOT NULL COMMENT '글쓴사람',
			r_user varchar(20) NOT NULL COMMENT '답글쓴사람',
			name varchar(20) NOT NULL COMMENT '작성자명',
			pass varchar(20) NOT NULL COMMENT '비밀번호',
			homepage varchar(100) COMMENT '홈페이지',
			email varchar(100) COMMENT '이메일',
			subject varchar(100) NOT NULL COMMENT '제목',
			contents TEXT NOT NULL COMMENT '내용',
			usereplyemail enum('Y','N') NOT NULL default 'N' COMMENT '답변시 메일받음',
			usehtml enum('Y','N') NOT NULL default 'N' COMMENT 'HTML 사용',
			category varchar(50) COMMENT '게시판 카테고리',
			uselock enum('Y','N') NOT NULL default 'N' COMMENT '글잠금',
			hit int(10) COMMENT '조회수',
			etc_1 varchar(255) COMMENT '여분필드1',
			etc_2 varchar(255) COMMENT '여분필드2',
			etc_3 varchar(255) COMMENT '여분필드3',
			etc_4 varchar(255) COMMENT '여분필드4',
			etc_5 varchar(255) COMMENT '여분필드5',
			etc_6 varchar(255) COMMENT '여분필드6',
			etc_7 varchar(255) COMMENT '여분필드7',
			etc_8 varchar(255) COMMENT '여분필드8',
			etc_9 varchar(255) COMMENT '여분필드9',
			etc_10 varchar(255) COMMENT '여분필드10',
			ip varchar(24) COMMENT 'IP주소',
			schedule_date DATE NOT NULL DEFAULT '0000-00-00' COMMENT '스케줄일정',
			wdate DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT '작성일',
			PRIMARY KEY (idx),
			KEY no (no, main, sub),
			KEY s_date (schedule_date)
		)";

		$rs = mysql_query($sql, $GLOBALS["dblink"]);
		//exit;
		if($rs){
			return true;
		}else{

			//위에서 입력한 게시판 정보 삭제
			$sql = "delete from ".$GLOBALS["_conf_tbl"]["board_info"]." where boardid='$boardid' ";
			mysql_query($sql, $GLOBALS["dblink"]);
			return false;
		}
	}else{
		jsMsg("게시판 정보 테이블 입력실패");
		return false;
	}
}

function editBoard($arrData){
	if($arrData[f_header]=="<p>&nbsp;</p>"){
		$arrData[f_header] = "";
	}
	if($arrData[f_footer]=="<p>&nbsp;</p>"){
		$arrData[f_footer] = "";
	}

	//게시판 데이터 수정
	$sql = "UPDATE ".$GLOBALS["_conf_tbl"]["board_info"]." SET
		boardname='".mysql_real_escape_string($arrData[f_boardname])."', 
		skin='".mysql_real_escape_string($arrData[f_skin])."', 
		scale='".mysql_real_escape_string($arrData[f_scale])."', 
		pagescale='".mysql_real_escape_string($arrData[f_pagescale])."', 
		widthscale='".mysql_real_escape_string($arrData[f_widthscale])."', 
		thumwidth='".mysql_real_escape_string($arrData[f_thumwidth])."', 
		newmark='".mysql_real_escape_string($arrData[f_newmark])."', 
		besthit='".mysql_real_escape_string($arrData[f_besthit])."', 
		subjectcut='".mysql_real_escape_string($arrData[f_subjectcut])."', 
		useadminonly='".mysql_real_escape_string($arrData[f_useadminonly])."', 
		useintranet='".mysql_real_escape_string($arrData[f_intranet])."', 
		usepds='".mysql_real_escape_string($arrData[f_usepds])."', 
		usereply='".mysql_real_escape_string($arrData[f_usereply])."', 
		usereplyemail='".mysql_real_escape_string($arrData[f_usereplyemail])."', 
		usecat='".mysql_real_escape_string($arrData[f_usecat])."', 
		usememo='".mysql_real_escape_string($arrData[f_usememo])."', 
		uselock='".mysql_real_escape_string($arrData[f_uselock])."', 
		readlevel='".mysql_real_escape_string($arrData[f_readlevel])."', 
		writelevel='".mysql_real_escape_string($arrData[f_writelevel])."', 
		replylevel='".mysql_real_escape_string($arrData[f_replylevel])."', 
		listlevel='".mysql_real_escape_string($arrData[f_listlevel])."', 
		category='".mysql_real_escape_string(str_replace(" ","",$arrData[f_category]))."', 
		header='".mysql_real_escape_string($arrData[f_header])."', 
		footer='".mysql_real_escape_string($arrData[f_footer])."' 
		WHERE idx='".mysql_real_escape_string($arrData["idx"])."' 
	";

	$rs = mysql_query($sql, $GLOBALS["dblink"]);

	if($rs){
		return true;
	}else{
		return false;
	}
}

//웹사이트용 게시판수정
function editAdminBoard(){
	for ($i=0; $i<count($_POST['sub_idx']); $i++) {
		$sql = " UPDATE ".$GLOBALS["_conf_tbl"]["board_info"]."
                    set boardname               = '{$_POST['boardname'][$i]}',
						useadminonly               = '{$_POST['f_useadminonly'][$i]}',
						usepds               = '{$_POST['f_usepds'][$i]}',
						usereply               = '{$_POST['f_usereply'][$i]}',
						usememo               = '{$_POST['f_usememo'][$i]}',
						listlevel               = '{$_POST['f_listlevel'][$i]}',
						writelevel               = '{$_POST['f_writelevel'][$i]}',
						readlevel               = '{$_POST['f_readlevel'][$i]}',
						replylevel               = '{$_POST['f_replylevel'][$i]}',
						scale               = '{$_POST['f_scale'][$i]}',
						thumwidth               = '{$_POST['f_thumwidth'][$i]}',
						skin               = '{$_POST['f_skin'][$i]}'
                  where idx            = '{$_POST['sub_idx'][$i]}' ";
		//echo $sql."</br>";
		$rs = mysql_query($sql, $GLOBALS["dblink"]);
	}

	if($rs){
		return true;
	}else{
		return false;
	}
}

function deleteBoard($idx){
	//게시판 정보 가져오기
	$arrInfo = getArticleInfo($GLOBALS["_conf_tbl"]["board_info"], $idx);

	if($arrInfo["total"] > 0){
		$tblid = $GLOBALS["_SITE"]["BOARD_PREWORD"] . $arrInfo["list"][0]["boardid"];

		//게시판 정보 삭제
		$sql = "DELETE FROM ".$GLOBALS["_conf_tbl"]["board_info"]." WHERE idx='".mysql_real_escape_string($idx)."'	";
		$rs1 = mysql_query($sql, $GLOBALS["dblink"]);

		//게시판 테이블 삭제
		$sql = "DROP TABLE ".$tblid;
		$rs2 = mysql_query($sql, $GLOBALS["dblink"]);

		//파일 테이블 정보 삭제
		$sql = "DELETE FROM ".$GLOBALS["_conf_tbl"]["board_files"]." WHERE boardid='".$arrInfo["list"][0]["boardid"]."'	";
		$rs3 = mysql_query($sql, $GLOBALS["dblink"]);

		//댓글 삭제
		mysql_query("DELETE FROM ".$GLOBALS["_conf_tbl"]["comment"]." WHERE boardid='".$arrInfo["list"][0]["boardid"]."'", $GLOBALS["dblink"]);


		if($rs1 && $rs2 &&$rs3){
			return true;
		}else{
			return false;
		}
	}else{
		return false;
	}
}
/*********************************** 게시판 관리 *************************************/

/*********************************** 게시물관련 *************************************/
//게시판 설정정보 가져오기
function getBoardInfo($tbl, $boardid){
    $sql  = "SELECT * ";
    $sql .= "FROM ".$GLOBALS["_conf_tbl"]["board_info"]." ";
    $sql .= "WHERE boardid = '$boardid' ";
	//echo $sql;
    $rs = mysql_query($sql, $GLOBALS["dblink"]);
    $total_rs = mysql_num_rows($rs);
    
    if($total_rs > 0){
        $list['total'] = $total_rs;
        for($i=0; $i < $total_rs; $i++){
            $list['list'][$i] = mysql_fetch_assoc($rs);
        }
    }else{
        $list['total'] = 0;
    }
    return $list;
}


//게시물 가져오기 - 파일 제외
function getBoardListBase($boardid, $category, $sw="", $sk="", $scale, $offset=0){
	$que_catcode='';
        $que_category='';
        $que_where='';

	//게시판 테이블 지정
	$tblid = $GLOBALS["_SITE"]["BOARD_PREWORD"] . $boardid;

	//카테고리가 있을경우
	if($category !=""){
		$que_category = " and category='$category' ";
	}

	//검색키워드가 있을경우
	if($sk !=""){
		switch($sw){
		case("n") :
			$que_where = "and name like '%$sk%'";
		break;
		case("s") :
			$que_where = "and subject like '%$sk%'";
		break;
		case("c") :
			$que_where = "and contents like '%$sk%'";
		break;
		case("u_id") :
			$que_where = "and w_user like '%$sk%'";
		break;
		case("a") :
		default :
			$que_where = "and (name like '%$sk%' or subject like '%$sk%' or contents like '%$sk%' or w_user like '%$sk%')";
		}

		// 검색시 영역을 분할하여 검색=> 속도향상용
		$sql = "select count(idx) as cnt from $tblid ";
		$rs = mysql_query($sql, $GLOBALS["dblink"]);

		$row = mysql_fetch_assoc($rs);
		$q_total = $row[cnt];
		$q_start = $q_total - 10000; // 최근 10000건만 검색
		
		if($q_total>10000){
			$q_limit = " idx between " . $q_start . " and " . $q_total . " ";
		}
		// 검색시 영역을 분할하여 검색=> 속도향상용
	}
	//카운트
//	$sql = "select count(idx) from $tblid WHERE no='1' $q_limit $que_where $que_category ";
	$sql = "select count(idx) from $tblid WHERE 1=1 $q_limit $que_where $que_category ";
    $rs = mysql_query($sql, $GLOBALS["dblink"]);
    $row = mysql_fetch_row($rs);
    $total_rs = $row[0];

	//목록
    $sql  = "SELECT * ";
    $sql .= "FROM $tblid ";
    //$sql .= "WHERE no='1' $q_limit $que_where $que_category ";
	$sql .= "WHERE 1=1 $q_limit $que_where $que_category ";

    if($total_rs > 0){
        $list['total'] = $total_rs;
        // 페이지 네비게이션 오프셋 지정.
		    if(!$offset){
		        $offset=0;
		    }else{
		        $offset=$offset;
		    }

		    // offset 이 전체 게시물수보다 작을때 offset 을 전체게시물 - 페이지당 보여줄 글 수로 offset 설정
		    if($total_rs<=$offset){
		        $offset = $total_rs - $scale;
		    }

				//scale 0 으로 지정시에는 전체 가져옴
				if($scale > 0){
			    $sql .= " order by no, main, sub limit $offset,$scale ";
				}else{
				  $sql .= " order by no, main, sub ";
				}

	    	
		    $rs = mysql_query($sql,$GLOBALS["dblink"]);
		//echo $sql;
		    // offset 을 이용한 limit 가 적용된 갯수
		    $total = mysql_num_rows($rs);
		    $list['list']['total'] = $total;
		    // 페이지 네비게이션 오프셋 지정.
		    
        for($i=0; $i < $total; $i++){
            $list['list'][$i] = mysql_fetch_assoc($rs);
        }
    }else{
        $list['total'] = 0;
    }
    return $list;
}

//게시물 가져오기 - 스케줄 형식
function getBoardListSchedule($boardid, $s_date, $e_date){
	//게시판 테이블 지정
	$tblid = $GLOBALS["_SITE"]["BOARD_PREWORD"] . $boardid;

	$que_where = "and schedule_date >= '$sk-01' AND  schedule_date <= '$sk-31' ";
	
	//목록
    $sql  = "SELECT * ";
    $sql .= "FROM $tblid ";
	$sql .= "WHERE schedule_date >= '$s_date' AND  schedule_date <= '$e_date' ";
    $sql .= " order by no, main, sub ";
       	
	$rs = mysql_query($sql,$GLOBALS["dblink"]);
	$total = mysql_num_rows($rs);
	$list['list']['total'] = $total;
		
	for($i=0; $i < $total; $i++){
		$row = mysql_fetch_assoc($rs);
		$list['list'][$row[schedule_date]][] = $row;
	}
    
    return $list;
}

//게시물 가져오기 - 파일 제외
function getBoardListBaseWuser($boardid, $category, $sw="", $sk="", $scale, $offset=0, $user_id){
	//게시판 테이블 지정
	$tblid = $GLOBALS["_SITE"]["BOARD_PREWORD"] . $boardid;

	//카테고리가 있을경우
	if($category !=""){
		$que_category = " and category='$category' ";
	}

	//검색키워드가 있을경우
	if($sk !=""){
		switch($sw){
		case("n") :
			$que_where = "and name like '%$sk%'";
		break;
		case("s") :
			$que_where = "and subject like '%$sk%'";
		break;
		case("c") :
			$que_where = "and contents like '%$sk%'";
		break;
		case("a") :
		default :
			$que_where = "and (name like '%$sk%' or subject like '%$sk%' or contents like '%$sk%')";
		}

		// 검색시 영역을 분할하여 검색=> 속도향상용
		$sql = "select count(idx) as cnt from $tblid ";
		$rs = mysql_query($sql, $GLOBALS["dblink"]);

		$row = mysql_fetch_assoc($rs);
		$q_total = $row[cnt];
		$q_start = $q_total - 10000; // 최근 10000건만 검색
		
		if($q_total>10000){
			$q_limit = " idx between " . $q_start . " and " . $q_total . " ";
		}
		// 검색시 영역을 분할하여 검색=> 속도향상용
	}

	//카운트
//	$sql = "select count(idx) from $tblid WHERE no='1' $q_limit $que_where $que_category ";
	$sql = "select count(idx) from $tblid WHERE 1=1 $q_limit $que_where $que_category AND w_user='$user_id' ";
    $rs = mysql_query($sql, $GLOBALS["dblink"]);
    $row = mysql_fetch_row($rs);
    $total_rs = $row[0];

	//목록
    $sql  = "SELECT * ";
    $sql .= "FROM $tblid ";
    //$sql .= "WHERE no='1' $q_limit $que_where $que_category ";
	$sql .= "WHERE 1=1 $q_limit $que_where $que_category AND w_user='$user_id' ";

    if($total_rs > 0){
        $list['total'] = $total_rs;
        // 페이지 네비게이션 오프셋 지정.
		    if(!$offset){
		        $offset=0;
		    }else{
		        $offset=$offset;
		    }

		    // offset 이 전체 게시물수보다 작을때 offset 을 전체게시물 - 페이지당 보여줄 글 수로 offset 설정
		    if($total_rs<=$offset){
		        $offset = $total_rs - $scale;
		    }

				//scale 0 으로 지정시에는 전체 가져옴
				if($scale > 0){
			    $sql .= " order by no, main, sub limit $offset,$scale ";
				}else{
				  $sql .= " order by no, main, sub ";
				}

	    	
		    $rs = mysql_query($sql,$GLOBALS["dblink"]);
		//echo $sql;
		    // offset 을 이용한 limit 가 적용된 갯수
		    $total = mysql_num_rows($rs);
		    $list['list']['total'] = $total;
		    // 페이지 네비게이션 오프셋 지정.
		    
        for($i=0; $i < $total; $i++){
            $list['list'][$i] = mysql_fetch_assoc($rs);
        }
    }else{
        $list['total'] = 0;
    }
    return $list;
}


//게시물 가져오기 - 파일 포함
function getBoardListBaseNFile($boardid, $category, $sw="", $sk="", $scale, $offset=0){
	//게시판 테이블 지정
	$tblid = $GLOBALS["_SITE"]["BOARD_PREWORD"] . $boardid;

	//카테고리가 있을경우
	if($category !=""){
		$que_category = " and A.category='$category' ";
	}
	//echo $sk;
	//검색키워드가 있을경우
	if($sk !=""){
		switch($sw){
		case("n") :
			$que_where = "and A.name like '%$sk%'";
		break;
		case("s") :
			$que_where = "and A.subject like '%$sk%'";
		break;
		case("c") :
			$que_where = "and A.contents like '%$sk%'";
		break;
		case("e1") :
			$que_where = "and A.etc_1='$sk'";
		break;
		case("e4") :
			$que_where = "and A.etc_4='$sk'";
		break;
		case("e") :
			$que_where .= "and A.etc_1 = '$sk'";
		break;
		case("a") :
		default :
			$que_where = "and (A.name like '%$sk%' or A.subject like '%$sk%' or A.contents like '%$sk%')";
		}

		// 검색시 영역을 분할하여 검색=> 속도향상용
		$sql = "select count(A.idx) as cnt from $tblid A";
		$rs = mysql_query($sql, $GLOBALS["dblink"]);

		$row = mysql_fetch_assoc($rs);
		$q_total = $row[cnt];
		$q_start = $q_total - 10000; // 최근 10000건만 검색
		
		if($q_total>10000){
			$q_limit = " A.idx between " . $q_start . " and " . $q_total . " ";
		}
		// 검색시 영역을 분할하여 검색=> 속도향상용
	}
	
	//카운트
	//$sql = "select count(A.idx) from $tblid A WHERE A.no='1' $q_limit $que_where $que_category ";
	$sql = "select count(A.idx) from $tblid A WHERE 1=1 $q_limit $que_where $que_category ";
    $rs = mysql_query($sql, $GLOBALS["dblink"]);
    $row = mysql_fetch_row($rs);
    $total_rs = $row[0];
	//echo $sql;
	//=========================================================  
	// mysql 4.1 부터 적용되는 쿼리
	//=========================================================  
	// 20100624
	// 그림의 정렬순서를 입력된 순서로 하고자 할경우 실행
	// 4.1 부터 서브쿼리가 적용되므로 이하일경우 
	// 일반 group by 쿼리를 그냥 사용한다
	//=========================================================  
	if (mysql_get_server_info()>4.1){
		$sub_query=" ( SELECT *  FROM ".$GLOBALS["_conf_tbl"]["board_files"]." ORDER BY idx ASC ) ";
	}else{
		$sub_query= $GLOBALS["_conf_tbl"]["board_files"];
	}

	//목록
	$sql  = " SELECT A.*, B.idx AS f_idx, B.boardid, B.b_idx, B.ori_name, B.re_name, B.type, B.size ";
	$sql .= " FROM $tblid A LEFT JOIN ".$sub_query." B ON B.boardid='$boardid' AND A.idx=B.b_idx ";
	$sql .= " WHERE 1=1 $q_limit $que_where $que_category group by A.idx";

    if($total_rs > 0){
        $list['total'] = $total_rs;
        // 페이지 네비게이션 오프셋 지정.
		    if(!$offset){
		        $offset=0;
		    }else{
		        $offset=$offset;
		    }

		    // offset 이 전체 게시물수보다 작을때 offset 을 전체게시물 - 페이지당 보여줄 글 수로 offset 설정
		    if($total_rs<=$offset){
		        $offset = $total_rs - $scale;
		    }

				//scale 0 으로 지정시에는 전체 가져옴
				if($scale > 0){
	    		$sql .= " order by A.no, A.main, A.sub limit $offset,$scale ";
				}else{
					$sql .= " order by A.no, A.main, A.sub ";
				}
		    $rs = mysql_query($sql,$GLOBALS["dblink"]);

		    // offset 을 이용한 limit 가 적용된 갯수
		    $total = mysql_num_rows($rs);
		    $list['list']['total'] = $total;
		    // 페이지 네비게이션 오프셋 지정.
		    
        for($i=0; $i < $total; $i++){
            $list['list'][$i] = mysql_fetch_assoc($rs);
        }
    }else{
        $list['total'] = 0;
    }
    return $list;
}


//게시물 가져오기 - 댓글카운트 포함
function getBoardListBaseNMemoCnt($boardid, $category, $sw="", $sk="", $scale, $offset=0){
	$que_catcode='';
        $que_category='';
        $que_where='';
	//게시판 테이블 지정
	$tblid = $GLOBALS["_SITE"]["BOARD_PREWORD"] . $boardid;

	$tbl_comment = $GLOBALS["_conf_tbl"]["comment"];

	if($boardid == "after" && $_SESSION[$GLOBALS["_SITE"]["DOMAIN"]]["MEMBER"]["ID"]) {
	//	$que_where .= " or (w_user='".$_SESSION[$GLOBALS["_SITE"]["DOMAIN"]]["MEMBER"]["ID"]."') ";
	}

	//카테고리가 있을경우
	if($category !=""){
		$que_category = " and category='$category' ";
	}
	
	if(strpos($_SERVER["DOCUMENT_URI"], 'backoffice') !== false){
	}else{
		if(($boardid == "qna" && $_REQUEST[goPage]=="MyQna") || ($boardid == "after" && $_REQUEST[goPage]=="MyReview")) {
			$que_where .= "and (w_user = '".$_SESSION[$GLOBALS["_SITE"]["DOMAIN"]]["MEMBER"]["ID"]."') ";
		} else if($boardid == "after" && $_SESSION[$GLOBALS["_SITE"]["DOMAIN"]]["ADMIN"]["GRADE"]!="ROOT") {
			//$que_where .= " and schedule_date!='0000-00-00'";
		}
	}

	//검색키워드가 있을경우
	if($sk !=""){
		switch($sw){
		case("n") :
			$que_where .= "and name like '%$sk%'";
		break;
		case("s") :
			$que_where .= "and subject like '%$sk%'";
		break;
		case("c") :
			$que_where .= "and contents like '%$sk%'";
		break;
		case("e") :
			$que_where .= "and etc_1 = '$sk'";
		break;
		case("sp") :
			$que_where = "and schedule_date = '0000-00-00'";
		break;
		case("a") :
		default :
			$que_where .= "and (name like '%$sk%' or subject like '%$sk%' or contents like '%$sk%')";
		}

		// 검색시 영역을 분할하여 검색=> 속도향상용
		$sql = "select count(idx) as cnt from $tblid ";
		$rs = mysql_query($sql, $GLOBALS["dblink"]);

		$row = mysql_fetch_assoc($rs);
		$q_total = $row[cnt];
		$q_start = $q_total - 10000; // 최근 10000건만 검색
		
		if($q_total>10000){
			$q_limit = " idx between " . $q_start . " and " . $q_total . " ";
		}
		// 검색시 영역을 분할하여 검색=> 속도향상용
	}
	//카운트
	//$sql = "select count(idx) from $tblid WHERE no='1' $q_limit $que_where $que_category $que_catcode ";
	$sql = "select count(idx) from $tblid WHERE 1=1 $q_limit $que_where $que_category $que_catcode ";
    $rs = mysql_query($sql, $GLOBALS["dblink"]);
    $row = mysql_fetch_row($rs);
    $total_rs = $row[0];
	
	//목록
    $sql  = "SELECT * ";
    $sql .= "FROM $tblid ";
    //$sql .= "WHERE no='1' $q_limit $que_where $que_category $que_catcode ";
	$sql .= "WHERE 1=1 $q_limit $que_where $que_category $que_catcode ";
	//echo $sql."</br>";

    if($total_rs > 0){
        $list['total'] = $total_rs;

		// 페이지 네비게이션 오프셋 지정.
		if(!$offset){
			$offset=0;
		}else{
			$offset=$offset;
		}

		// offset 이 전체 게시물수보다 작을때 offset 을 전체게시물 - 페이지당 보여줄 글 수로 offset 설정
		if($total_rs<=$offset){
			$offset = $total_rs - $scale;
		}

		//scale 0 으로 지정시에는 전체 가져옴
		if($scale > 0){
			$sql .= " order by no, main, sub limit $offset,$scale ";
		}else{
		  $sql .= " order by no, main, sub ";
		}

		
		$rs = mysql_query($sql,$GLOBALS["dblink"]);
		//echo $sql;
		// offset 을 이용한 limit 가 적용된 갯수
		$total = mysql_num_rows($rs);
		$list['list']['total'] = $total;
		// 페이지 네비게이션 오프셋 지정.
		    
        for($i=0; $i < $total; $i++){
            $list['list'][$i] = mysql_fetch_assoc($rs);
			$m_cnt_row = mysql_fetch_row(mysql_query("select count(idx) from $tbl_comment WHERE boardid='$boardid' AND board_idx='".$list['list'][$i]["idx"]."' "));
            $list['list'][$i]["cmt_count"] = $m_cnt_row[0];
        }
    }else{
        $list['total'] = 0;
    }
    return $list;
}

//게시물 가져오기 - 파일 포함
function getBoardListBaseNImage($boardid, $category, $sw="", $sk="", $scale, $offset=0){
	//게시판 테이블 지정
	$tblid = $GLOBALS["_SITE"]["BOARD_PREWORD"] . $boardid;

	//카테고리가 있을경우
	if($category !=""){
		$que_category = " and A.category='$category' ";
	}

	//검색키워드가 있을경우
	if($sk !=""){
		switch($sw){
		case("n") :
			$que_where = "and A.name like '%$sk%'";
		break;
		case("s") :
			$que_where = "and A.subject like '%$sk%'";
		break;
		case("c") :
			$que_where = "and A.contents like '%$sk%'";
		break;
		case("a") :
		default :
			$que_where = "and (A.name like '%$sk%' or A.subject like '%$sk%' or A.contents like '%$sk%')";
		}

		// 검색시 영역을 분할하여 검색=> 속도향상용
		$sql = "select count(A.idx) as cnt from $tblid A";
		$rs = mysql_query($sql, $GLOBALS["dblink"]);

		$row = mysql_fetch_assoc($rs);
		$q_total = $row[cnt];
		$q_start = $q_total - 10000; // 최근 10000건만 검색
		
		if($q_total>10000){
			$q_limit = " A.idx between " . $q_start . " and " . $q_total . " ";
		}
		// 검색시 영역을 분할하여 검색=> 속도향상용
	}

	//카운트
//	$sql = "select count(A.idx) from $tblid A WHERE A.no='1' $q_limit $que_where $que_category ";
	$sql = "select count(A.idx) from $tblid A WHERE 1=1 $q_limit $que_where $que_category ";
    $rs = mysql_query($sql, $GLOBALS["dblink"]);
    $row = mysql_fetch_row($rs);
    $total_rs = $row[0];

	//목록
    $sql  = "SELECT A.*, B.idx AS f_idx, B.boardid, B.b_idx, B.ori_name, B.re_name, B.type, B.size ";
    $sql .= "FROM $tblid A LEFT JOIN ".$GLOBALS["_conf_tbl"]["board_files"]." B ON B.boardid='$boardid' AND A.idx=B.b_idx AND B.ext IN('jpg','gif','png')";
//    $sql .= "WHERE A.no='1' $q_limit $que_where $que_category group by A.idx";
    $sql .= "WHERE 1=1 $q_limit $que_where $que_category group by A.idx";


    if($total_rs > 0){
        $list['total'] = $total_rs;
        // 페이지 네비게이션 오프셋 지정.
		    if(!$offset){
		        $offset=0;
		    }else{
		        $offset=$offset;
		    }

		    // offset 이 전체 게시물수보다 작을때 offset 을 전체게시물 - 페이지당 보여줄 글 수로 offset 설정
		    if($total_rs<=$offset){
		        $offset = $total_rs - $scale;
		    }

				//scale 0 으로 지정시에는 전체 가져옴
				if($scale > 0){
					$sql .= " order by A.no, A.main, A.sub limit $offset,$scale ";
				}else{
					$sql .= " order by A.no, A.main, A.sub ";
				}
		    $rs = mysql_query($sql,$GLOBALS["dblink"]);

		    // offset 을 이용한 limit 가 적용된 갯수
		    $total = mysql_num_rows($rs);
		    $list['list']['total'] = $total;
		    // 페이지 네비게이션 오프셋 지정.
		    
        for($i=0; $i < $total; $i++){
            $list['list'][$i] = mysql_fetch_assoc($rs);
        }
    }else{
        $list['total'] = 0;
    }
    return $list;
}

//게시물 등록하기
function insertBoardArticle($boardid, $thumwidth){

	//게시판 테이블 지정
	$tblid = $GLOBALS["_SITE"]["BOARD_PREWORD"] . $boardid;
	
	//보안단어 체크
	if($_SESSION[$GLOBALS["_SITE"]["DOMAIN"]]["ADMIN"]["ID"]==""){
		if($_SESSION[captcha_keystring] != mysql_real_escape_string($_POST[writekey])) {
			jsMsg("보안단어가 일치하지 않습니다.");
			jsHistory("-1") ;
			exit;
		}
	}

	//main 번호 가져오기
	$q_main = mysql_query("select min(main) from $tblid ");	
	$c_main = @mysql_result($q_main,0,0);
		
	if(!$c_main){	
		$main='99999999';
	}else{	
		$main=$c_main-1;
	}

	//게시판 공지 설정
	if($_POST[is_notice]=="Y"){
		$setNo = "0";
	}else{
		$setNo = "1";
	}

	if($_POST[usehtml]=="Y") {
		$contents = mysql_real_escape_string($_POST[contents]);
	} else {
		$contents = mysql_real_escape_string($_POST[contents1]);
	}
	
	if($boardid=="store" && $_POST[etc_9]=="" && $_POST[etc_10]==""){
		$URL_googleAPI      =   "http://maps.googleapis.com/maps/api/geocode/json?address=".urlencode($_POST[etc_2])."&sensor=false";
		$targetURL      =   str_replace("[ADDRESS]", urlencode( $_REQUEST['ADDRESS'] ), $URL_googleAPI);
		$temp_fileContents  =   json_decode( file_get_contents($targetURL), true );
		//var_dump( $temp_fileContents );
		$_POST[etc_9] = $temp_fileContents['results'][0]['geometry']['location']['lat'];
		$_POST[etc_10] = $temp_fileContents['results'][0]['geometry']['location']['lng'];
	}

	//게시판 테이블에 입력
	if($_POST[schedule_date]){
		$sql = "INSERT INTO ".$tblid." set 
			no='$setNo',
			main='$main',
			sub='0',
			depth='0',
			w_user='".$_SESSION[$GLOBALS["_SITE"]["DOMAIN"]]["MEMBER"]["ID"]."',
			r_user='".$_POST[r_user_id]."',
			name='".mysql_real_escape_string($_POST[name])."',
			pass='".mysql_real_escape_string($_POST[pass])."',
			homepage='".mysql_real_escape_string($_POST[homepage])."',
			email='".mysql_real_escape_string($_POST[email])."',
			subject='".mysql_real_escape_string(str_replace("\"","'",$_POST[subject]))."',
			contents='".$contents."',
			usereplyemail='".mysql_real_escape_string($_POST[usereplyemail]=="Y"?"Y":"N")."',
			usehtml='".mysql_real_escape_string($_POST[usehtml]=="Y"?"Y":"N")."',
			category='".mysql_real_escape_string($_POST[category])."',
			uselock='".mysql_real_escape_string($_POST[uselock]=="Y"?"Y":"N")."',
			hit='0',
			etc_1='".mysql_real_escape_string($_POST[etc_1])."',
			etc_2='".mysql_real_escape_string($_POST[etc_2])."',
			etc_3='".mysql_real_escape_string($_POST[etc_3])."',
			etc_4='".mysql_real_escape_string($_POST[etc_4])."',
			etc_5='".mysql_real_escape_string($_POST[etc_5])."',
			etc_6='".mysql_real_escape_string($_POST[etc_6])."',
			etc_7='".mysql_real_escape_string($_POST[etc_7])."',
			etc_8='".mysql_real_escape_string($_POST[etc_8])."',
			etc_9='".mysql_real_escape_string($_POST[etc_9])."',
			etc_10='".mysql_real_escape_string($_POST[etc_10])."',
			ip='".$_SERVER[REMOTE_ADDR]."',
			schedule_date='".mysql_real_escape_string($_POST[schedule_date])."',
			wdate=now()
		";
	}
	else {
		$sql = "INSERT INTO ".$tblid." set 
			no='$setNo',
			main='$main',
			sub='0',
			depth='0',
			w_user='".$_SESSION[$GLOBALS["_SITE"]["DOMAIN"]]["MEMBER"]["ID"]."',
			r_user='".$_POST[r_user_id]."',
			name='".mysql_real_escape_string($_POST[name])."',
			pass='".mysql_real_escape_string($_POST[pass])."',
			homepage='".mysql_real_escape_string($_POST[homepage])."',
			email='".mysql_real_escape_string($_POST[email])."',
			subject='".mysql_real_escape_string(str_replace("\"","'",$_POST[subject]))."',
			contents='".$contents."',
			usereplyemail='".mysql_real_escape_string($_POST[usereplyemail]=="Y"?"Y":"N")."',
			usehtml='".mysql_real_escape_string($_POST[usehtml]=="Y"?"Y":"N")."',
			category='".mysql_real_escape_string($_POST[category])."',
			uselock='".mysql_real_escape_string($_POST[uselock]=="Y"?"Y":"N")."',
			hit='0',
			etc_1='".mysql_real_escape_string($_POST[etc_1])."',
			etc_2='".mysql_real_escape_string($_POST[etc_2])."',
			etc_3='".mysql_real_escape_string($_POST[etc_3])."',
			etc_4='".mysql_real_escape_string($_POST[etc_4])."',
			etc_5='".mysql_real_escape_string($_POST[etc_5])."',
			etc_6='".mysql_real_escape_string($_POST[etc_6])."',
			etc_7='".mysql_real_escape_string($_POST[etc_7])."',
			etc_8='".mysql_real_escape_string($_POST[etc_8])."',
			etc_9='".mysql_real_escape_string($_POST[etc_9])."',
			etc_10='".mysql_real_escape_string($_POST[etc_10])."',
			ip='".$_SERVER[REMOTE_ADDR]."',
			wdate=now()
		";
	}
	//echo $sql;
	//exit;

	$rs = mysql_query($sql, $GLOBALS["dblink"]);
	$insert_idx = mysql_insert_id($GLOBALS["dblink"]);
	$total = mysql_affected_rows($GLOBALS["dblink"]);

	//메인 event
	if($boardid == "event1" || $boardid == "event2") { 

		switch ($boardid) {
			case("event1") : $linkurl = "/sub/event_01.php"; break;
			case("event2") : $linkurl = "/sub/event_02.php"; break;
		}

		$sql_tmp = "INSERT INTO tbl_board_tmp set 
			  boardid='".$boardid."',
			  linkurl='".$linkurl."',
			  b_idx='".$insert_idx."',
			  subject='".mysql_real_escape_string(str_replace("\"","'",$_POST[subject]))."',
			  wdate=now()
		";
		$rs_tmp = mysql_query($sql_tmp, $GLOBALS["dblink"]);
		
		//4개이상일때 오래된글삭제
		$arrBoard = getListByTbl("tbl_board_tmp", "order by wdate");
		if($arrBoard["total"] > 9) {
			for($i=0; $i < 1; $i++){
				$sql_delete = "DELETE FROM tbl_board_tmp where wdate='".$arrBoard["list"][$i]["wdate"]."'";
				mysql_query($sql_delete, $GLOBALS["dblink"]);
			}
		}

	}

	//파일처리
	inputBoardFiles($boardid, $insert_idx, $_FILES, $thumwidth);

	if($total > 0){
		return true;
	}else{
		return false;
	}

}


//게시물 수정하기
function modifyBoardArticle($boardid, $idx, $thumwidth){
	//게시판 테이블 지정
	$tblid = $GLOBALS["_SITE"]["BOARD_PREWORD"] . $boardid;

	//수정권한 설정
	$modifyPerm = false;
	
	//보안단어 체크
	if($_SESSION[$GLOBALS["_SITE"]["DOMAIN"]]["ADMIN"]["ID"]==""){
		if($_SESSION[captcha_keystring] != mysql_real_escape_string($_POST[writekey])) {
			jsMsg("보안단어가 일치하지 않습니다.");
			jsHistory("-1") ;
			exit;
		}
	}

	//관리자는 그냥 통과
	if($_SESSION[$GLOBALS["_SITE"]["DOMAIN"]]["ADMIN"]["GRADE"]=="ROOT" || @in_array("board_manage",$_SESSION[$GLOBALS["_SITE"]["DOMAIN"]]["ADMIN"]["AUTH"])){
		$modifyPerm = true;
	}
	//기존정보와 비밀번호를 비교
	$arrArticleInfo = getArticleInfo($tblid, $idx);
	
	if($arrArticleInfo["list"][0]["pass"] && $arrArticleInfo["list"][0]["pass"]==trim($_POST[pass])){
		$modifyPerm = true;
	}
	
	// 본인아이디 확인
	// 로그인 상태이고 로그인 아이디와 글 쓴 아이디가 같을 경우	
	if($_SESSION[$GLOBALS["_SITE"]["DOMAIN"]]["MEMBER"]["ID"] && $_SESSION[$GLOBALS["_SITE"]["DOMAIN"]]["MEMBER"]["ID"]==$arrArticleInfo["list"][0]["w_user"]){
		$modifyPerm = true;
	}


	//게시판 공지 설정
	if($_POST[is_notice]=="Y"){
		$setNo = "0";
	}else{
		$setNo = "1";
	}

	if($_POST[usehtml]=="Y") {
		$contents = mysql_real_escape_string($_POST[contents]);
	} else {
		$contents = mysql_real_escape_string($_POST[contents1]);
	}
	
	if($boardid=="store" && $_POST[etc_9]=="" && $_POST[etc_10]==""){
		$URL_googleAPI      =   "http://maps.googleapis.com/maps/api/geocode/json?address=".urlencode($_POST[etc_2])."&sensor=false";
		$targetURL      =   str_replace("[ADDRESS]", urlencode( $_REQUEST['ADDRESS'] ), $URL_googleAPI);
		$temp_fileContents  =   json_decode( file_get_contents($targetURL), true );
		//var_dump( $temp_fileContents );
		$_POST[etc_9] = $temp_fileContents['results'][0]['geometry']['location']['lat'];
		$_POST[etc_10] = $temp_fileContents['results'][0]['geometry']['location']['lng'];
	}

	if($modifyPerm==true){
		//게시판 테이블 지정
		$tblid = $GLOBALS["_SITE"]["BOARD_PREWORD"] . $boardid;

		//게시판 테이블에 입력
		$sql = "UPDATE ".$tblid." set 
			no='$setNo',
			r_user='".$_POST[r_user_id]."',
			name='".mysql_real_escape_string($_POST[name])."',
			pass='".mysql_real_escape_string($_POST[pass])."',
			homepage='".mysql_real_escape_string($_POST[homepage])."',
			email='".mysql_real_escape_string($_POST[email])."',
			subject='".mysql_real_escape_string(str_replace("\"","'",$_POST[subject]))."',
			contents='".$contents."',
			usereplyemail='".mysql_real_escape_string($_POST[usereplyemail]=="Y"?"Y":"N")."',
			usehtml='".mysql_real_escape_string($_POST[usehtml]=="Y"?"Y":"N")."',
			category='".mysql_real_escape_string($_POST[category])."',
			uselock='".mysql_real_escape_string($_POST[uselock]=="Y"?"Y":"N")."',
			etc_1='".mysql_real_escape_string($_POST[etc_1])."',
			etc_2='".mysql_real_escape_string($_POST[etc_2])."',
			etc_3='".mysql_real_escape_string($_POST[etc_3])."',
			etc_4='".mysql_real_escape_string($_POST[etc_4])."',
			etc_5='".mysql_real_escape_string($_POST[etc_5])."',
			etc_6='".mysql_real_escape_string($_POST[etc_6])."',
			etc_7='".mysql_real_escape_string($_POST[etc_7])."',
			etc_8='".mysql_real_escape_string($_POST[etc_8])."',
			etc_9='".mysql_real_escape_string($_POST[etc_9])."',
			etc_10='".mysql_real_escape_string($_POST[etc_10])."',
			schedule_date='".mysql_real_escape_string($_POST[schedule_date])."'
			WHERE idx='".mysql_real_escape_string($_POST["idx"])."'
		";

		$rs = mysql_query($sql, $GLOBALS["dblink"]);
		$total = mysql_affected_rows($GLOBALS["dblink"]);

		//파일삭제 코딩 시작 - 삭제체크 한것만 처리
		for($i=0;$i<count($_POST[filedel]);$i++){
			if($_POST[filedel][$i]>0){
				$fileinfo = getArticleFileInfo($boardid, $_POST["idx"], $_POST[filedel][$i]);
				//디비에서 파일정보 삭제
				mysql_query("DELETE FROM ".$GLOBALS["_conf_tbl"]["board_files"]." WHERE boardid='".$boardid."' AND idx='".$fileinfo["list"][0]["idx"]."' ", $GLOBALS["dblink"]);
				//디스크에서 파일 삭제
				@unlink($GLOBALS["_SITE"]["BOARD_DATA"] . "/".$boardid."/".$fileinfo["list"][0][re_name]);
			}
		}
		//파일삭제 코딩 종료

		//파일처리
		inputBoardFiles($boardid, $idx, $_FILES, $thumwidth);

		//포인트지급
		if($_POST[point]=="Y"){
			$RS = setPlusPoint($arrArticleInfo["list"][0]["w_user"], "2000", "리뷰작성 포인트 지급");

			$sql = "UPDATE ".$tblid." set schedule_date=now() WHERE idx='".mysql_real_escape_string($_POST["idx"])."'";
			$rs_point = mysql_query($sql, $GLOBALS["dblink"]);
		}

		//메인 event
		if($boardid == "event1" || $boardid == "event2") { 
			$sql_tmp = "UPDATE tbl_board_tmp set 
				  subject='".mysql_real_escape_string(str_replace("\"","'",$_POST[subject]))."'
				  where boardid='".$boardid."' and b_idx='".mysql_real_escape_string($_POST["idx"])."'
			";
			$rs_tmp = mysql_query($sql_tmp, $GLOBALS["dblink"]);
		}

		if($rs){
			return true;
		}else{
			return false;
		}
	}else{
		jsMsg("비밀번호가 일치하지 않습니다.");
		return false;
	}

}

//답글 등록하기
function insertBoardArticleReply($boardid, $idx, $thumwidth){
	//게시판 테이블 지정
	$tblid = $GLOBALS["_SITE"]["BOARD_PREWORD"] . $boardid;

	//main 번호 가져오기
	$q_main = mysql_query("select main,sub,depth,email,usereplyemail,pass,uselock,no from ".$tblid." where idx = '".$idx."'", $GLOBALS["dblink"]);	
	$row = mysql_fetch_array($q_main);

	$c_main =						$row[0];
	$c_sub =						$row[1];
	$c_depth =					$row[2];
	$c_email =					$row[3];
	$c_usereplyemail =	$row[4];
	$c_pass =						$row[5];
	$c_lock =						$row[6];
	$c_no =						$row[7];
	
	//보안단어 체크
	if($_SESSION[$GLOBALS["_SITE"]["DOMAIN"]]["ADMIN"]["ID"]==""){
		if($_SESSION[captcha_keystring] != mysql_real_escape_string($_POST[writekey])) {
			jsMsg("보안단어가 일치하지 않습니다.");
			jsHistory("-1") ;
			exit;
		}
	}

	if($c_no=="0"){
		jsMsg("공지글에는 답글을 달 수 없습니다.");
		return false;
	}

	//잠긴글에 답글을 달 경우 원 사용자가 볼수 있게 비밀번호를 원 글의 비밀번호로 입력
	if($c_lock =="Y"){
		$pass = $c_pass;
		$uselock = "Y";
	}else{
		$pass = mysql_real_escape_string($_POST[pass]);
		$uselock = mysql_real_escape_string($_POST[uselock]=="Y"?"Y":"N");
	}

	$main = $c_main;
	$sub = $c_sub + 1;
	$depth = $c_depth + 1;

	mysql_query("UPDATE ".$tblid." set sub=sub+1 where no='1' and main='$main' and sub>'$c_sub'", $GLOBALS["dblink"]);	

	if($_POST[usehtml]=="Y") {
		$contents = mysql_real_escape_string($_POST[contents]);
	} else {
		$contents = mysql_real_escape_string($_POST[contents1]);
	}

	//게시판 테이블에 입력
	$sql = "INSERT INTO ".$tblid." set 
		no='1',
		main='$main',
		sub='$sub',
		depth='$depth',
		w_user='".$_POST[w_user_id]."',
		r_user='".$_POST[r_user_id]."',
		name='".mysql_real_escape_string($_POST[name])."',
		pass='".$pass."',
		homepage='".mysql_real_escape_string($_POST[homepage])."',
		email='".mysql_real_escape_string($_POST[email])."',
		subject='".mysql_real_escape_string(str_replace("\"","'",$_POST[subject]))."',
		contents='".$contents."',
		usereplyemail='".mysql_real_escape_string($_POST[usereplyemail]=="Y"?"Y":"N")."',
		usehtml='".mysql_real_escape_string($_POST[usehtml]=="Y"?"Y":"N")."',
		category='".mysql_real_escape_string($_POST[category])."',
		uselock='".$uselock."',
		hit='0',
		etc_1='".mysql_real_escape_string($_POST[etc_1])."',
		etc_2='".mysql_real_escape_string($_POST[etc_2])."',
		etc_3='".mysql_real_escape_string($_POST[etc_3])."',
		etc_4='".mysql_real_escape_string($_POST[etc_4])."',
		etc_5='".mysql_real_escape_string($_POST[etc_5])."',
		ip='".$_SERVER[REMOTE_ADDR]."',
		schedule_date='".mysql_real_escape_string($_POST[schedule_date])."',
		wdate=now()
	";

	$rs = mysql_query($sql, $GLOBALS["dblink"]);
	$insert_idx = mysql_insert_id($GLOBALS["dblink"]);
	$total = mysql_affected_rows($GLOBALS["dblink"]);

	//파일처리
	inputBoardFiles($boardid, $insert_idx, $_FILES, $thumwidth);

	if($total > 0){
		// 글 등록시 메일링여부
		if ($c_usereplyemail=='Y'){
			if($_POST[usehtml] !='Y') $contents = nl2br($_POST[contents]);
			mailing($GLOBALS["_SITE"]["NAME"],$GLOBALS["_SITE"]["EMAIL"],$c_email,$_POST[subject],$contents);
		}

		return true;
	}else{
		return false;
	}
}

//게시물 삭제하기
function deleteBoardArticle($boardid, $idx){
	//게시판 테이블 지정
	$tblid = $GLOBALS["_SITE"]["BOARD_PREWORD"] . $boardid;
	$tbl_comment = $GLOBALS["_conf_tbl"]["comment"];
	$tbl_board_product = $GLOBALS["_conf_tbl"]["board_product"];
	//삭제권한 설정
	$deletePerm = false;

	//관리자는 그냥 통과
	if($_SESSION[$GLOBALS["_SITE"]["DOMAIN"]]["ADMIN"]["GRADE"]=="ROOT" || @in_array("board_manage",$_SESSION[$GLOBALS["_SITE"]["DOMAIN"]]["ADMIN"]["AUTH"])){
		$deletePerm = true;
	}

	//기존정보와 비밀번호를 비교 - 수정할때와 다른 함수를 씀 (파일 삭제 때문에)
	$arrArticleInfo = getBoardArticleView($boardid, $category, $idx, "delete");
	
	if($arrArticleInfo["list"][0]["pass"]==trim($_POST[pass])){
		$deletePerm = true;
	}

	
	if($deletePerm==true){
		//게시판 테이블 지정
		$tblid = $GLOBALS["_SITE"]["BOARD_PREWORD"] . $boardid;

		//게시판 테이블에서 삭제
		$sql = "DELETE FROM ".$tblid." 
			WHERE idx='".$idx."'
		";

		$rs = mysql_query($sql, $GLOBALS["dblink"]);
		$total = mysql_affected_rows($GLOBALS["dblink"]);

	

		//파일삭제 코딩 시작
		for($i=0;$i<$arrArticleInfo["total_files"];$i++){
			//디비에서 파일정보 삭제
			mysql_query("DELETE FROM ".$GLOBALS["_conf_tbl"]["board_files"]." WHERE boardid='".$boardid."' AND idx='".$arrArticleInfo["files"][$i]["idx"]."' ", $GLOBALS["dblink"]);
			//디스크에서 파일 삭제
			@unlink($GLOBALS["_SITE"]["BOARD_DATA"] . "/".$boardid."/".$arrArticleInfo["files"][$i][re_name]);
			//썸네일 삭제
			if($arrArticleInfo["files"][$i]["type"]=="image/pjpeg" || $arrArticleInfo["files"][$i]["type"]=="image/x-png" || $arrArticleInfo["files"][$i]["type"]=="image/gif"){
				@unlink($GLOBALS["_SITE"]["BOARD_DATA"] . "/".$boardid."/t_".$arrArticleInfo["files"][$i][re_name]);
			}
		}
		//파일삭제 코딩 종료

		//댓글 삭제
		mysql_query("DELETE FROM ".$tbl_comment." WHERE boardid='".$boardid."' AND board_idx='".$idx."' ", $GLOBALS["dblink"]);

		//메인 event
		if($boardid == "event1" || $boardid == "event2") { 
			mysql_query("DELETE FROM tbl_board_tmp WHERE boardid='".$boardid."' AND b_idx='".$idx."' ", $GLOBALS["dblink"]);
		}


		if($total > 0){
			return true;
		}else{
			return false;
		}
	}else{
		jsMsg("비밀번호가 일치하지 않습니다.");
		return false;
	}
}

//게시물 가져오기 - id
function getBoardArticleView($boardid, $category, $idx, $mode="read"){
	//게시판 테이블 지정
	$tblid = $GLOBALS["_SITE"]["BOARD_PREWORD"] . $boardid;

	//카테고리가 있을경우
	if($category !=""){
		$que_category = " and category='$category' ";
	}

	//조회수 먼저 업데이트
	if($mode=="read"){
		$sql  = "UPDATE $tblid SET ";
		$sql .= " hit = hit + 1 ";
		$sql .= "WHERE idx = '$idx' ";
		$rs = mysql_query($sql, $GLOBALS["dblink"]);
	}
	
    $sql  = "SELECT * ";
    $sql .= "FROM $tblid ";
    $sql .= "WHERE idx = '$idx' ";
    $rs = mysql_query($sql, $GLOBALS["dblink"]);
	//echo $sql;
    $total_rs = mysql_num_rows($rs);
    
    if($total_rs > 0){
        $list['total'] = $total_rs;
        for($i=0; $i < $total_rs; $i++){
            $list['list'][$i] = mysql_fetch_assoc($rs);
			//html 사용여부 체크-> 읽기 페이지에서만
			if($mode=="read" && $list['list'][$i][usehtml]!='Y'){
				$list['list'][$i][contents] = nl2br(htmlspecialchars($list['list'][$i][contents]));
			}
        }
    }else{
        $list['total'] = 0;
    }


	//이전글, 다음글은 읽기 모드일때만
	if($mode=="read"){
		//이전글 정보 가져오기
		$sql  = "SELECT max(idx) ";
		$sql .= "FROM $tblid ";
		$sql .= "WHERE idx < '$idx' $que_category ";
		$rs = mysql_query($sql, $GLOBALS["dblink"]);
		$prev = mysql_result($rs,0,0);
		if($prev > 0){
			$list["prev"]["idx"] = $prev;

			$sql  = "SELECT idx, name, subject, hit, wdate  ";
			$sql .= "FROM $tblid ";
			$sql .= "WHERE idx = '$prev' $que_category ";
			$rs = mysql_query($sql, $GLOBALS["dblink"]);

			$list["prev"] = mysql_fetch_assoc($rs);
		}else{
			$list["prev"]["idx"] = 0;
		}


		//다음글 정보 가져오기
		$sql  = "SELECT min(idx) ";
		$sql .= "FROM $tblid ";
		$sql .= "WHERE idx > '$idx' $que_category ";
		$rs = mysql_query($sql, $GLOBALS["dblink"]);
		$next = mysql_result($rs,0,0);
		if($next > 0){
			$list["next"]["idx"] = $next;

			$sql  = "SELECT idx, name, subject, hit, wdate  ";
			$sql .= "FROM $tblid ";
			$sql .= "WHERE idx = '$next' $que_category ";
			$rs = mysql_query($sql, $GLOBALS["dblink"]);

			$list["next"] = mysql_fetch_assoc($rs);
		}else{
			$list["next"]["idx"] = 0;
		}
	}


	//파일정보 가져오기
    $sql  = "SELECT * ";
    $sql .= "FROM ".$GLOBALS["_conf_tbl"]["board_files"]." ";
    $sql .= "WHERE boardid = '$boardid' ";
    $sql .= "AND b_idx = '$idx' and type2='' order by idx";
    $rs = mysql_query($sql, $GLOBALS["dblink"]);
    $total_rs = mysql_num_rows($rs);
    
    if($total_rs > 0){
        $list['total_files'] = $total_rs;
        for($i=0; $i < $total_rs; $i++){
            $list['files'][$i] = mysql_fetch_assoc($rs);
        }
    }else{
        $list['total_files'] = 0;
    }

	//파일정보 가져오기
    $sql  = "SELECT * ";
    $sql .= "FROM ".$GLOBALS["_conf_tbl"]["board_files"]." ";
    $sql .= "WHERE boardid = '$boardid' ";
    $sql .= "AND b_idx = '$idx' and type2='con1' order by idx";
    $rs = mysql_query($sql, $GLOBALS["dblink"]);
    $total_rs = mysql_num_rows($rs);
    
    if($total_rs > 0){
        $list['total_files1'] = $total_rs;
        for($i=0; $i < $total_rs; $i++){
            $list['files1'][$i] = mysql_fetch_assoc($rs);
        }
    }else{
        $list['total_files1'] = 0;
    }

    return $list;
}


//게시물 가져오기 - id
function getBoardArticleSchedule($boardid, $date){
	//게시판 테이블 지정
	$tblid = $GLOBALS["_SITE"]["BOARD_PREWORD"] . $boardid;

    $sql  = "SELECT * ";
    $sql .= "FROM $tblid ";
    $sql .= "WHERE schedule_date = '$date' ";
    $rs = mysql_query($sql, $GLOBALS["dblink"]);
    $total_rs = mysql_num_rows($rs);
    
    if($total_rs > 0){
        $list['total'] = $total_rs;
        for($i=0; $i < $total_rs; $i++){
            $list['list'][$i] = mysql_fetch_assoc($rs);
        }
    }else{
        $list['total'] = 0;
    }

    return $list;
}



//글잠금 해제
function unlockBoardArticle($boardid, $idx, $pass){
	//게시판 테이블 지정
	$tblid = $GLOBALS["_SITE"]["BOARD_PREWORD"] . $boardid;

	$sql  = "SELECT * ";
	$sql .= "FROM $tblid ";
	$sql .= "WHERE idx = '$idx' AND pass='$pass'";
	$rs = mysql_query($sql, $GLOBALS["dblink"]);

	$total_rs = mysql_num_rows($rs);
	
	if($total_rs > 0){
		return true;
	}else{
		return false;
	}
}

//파일정보 가져오기
function getArticleFileInfo($boardid, $b_idx, $idx){
    $sql  = "SELECT * ";
    $sql .= "FROM " .$GLOBALS["_conf_tbl"]["board_files"]." ";
    $sql .= "WHERE boardid = '$boardid' ";
    $sql .= "AND b_idx = '$b_idx' ";
    $sql .= "AND idx = '$idx' ";
//	echo $sql;
    $rs = mysql_query($sql, $GLOBALS["dblink"]);
    $total_rs = mysql_num_rows($rs);
    
    if($total_rs > 0){
        $list['total'] = $total_rs;
        for($i=0; $i < $total_rs; $i++){
            $list['list'][$i] = mysql_fetch_assoc($rs);
        }
    }else{
        $list['total'] = 0;
    }
    return $list;
}

//최근게시물 목록 가져오기
function getBoardLast($boardid, $limit){
	//게시판 테이블 지정
	$tblid = $GLOBALS["_SITE"]["BOARD_PREWORD"] . $boardid;

    $sql = "SELECT * FROM $tblid order by wdate desc limit $limit";
    $rs = mysql_query($sql, $GLOBALS["dblink"]);
    $total = mysql_num_rows($rs);
    
    if($total > 0){
        $list['total'] = $total;
	    $rs = mysql_query($sql,$GLOBALS["dblink"]);
    
        for($i=0; $i < $total; $i++){
            $list['list'][$i] = mysql_fetch_assoc($rs);
        }
    }else{
        $list['total'] = 0;
    }
    
    return $list;
}

//게시판 파일처리
function inputBoardFiles($boardid, $idx, $HTTP_POST_FILES, $thumwidth){
	for($i=0;$i<count($HTTP_POST_FILES[upfiles][error]);$i++){
		if ($HTTP_POST_FILES[upfiles][error][$i] == 0){
		    //확장자 검사후 파일이름 생성
		    $filename = $HTTP_POST_FILES[upfiles][name][$i];
		    $attach_ext = explode(".",$filename);
		    $extension = $attach_ext[sizeof($attach_ext)-1];
		    $extension = strtolower($extension);		    
		    $filerename = md5(time()) . $i . "." . $extension;
	  		$filesize = $HTTP_POST_FILES[upfiles][size][$i];
	  		$filetype = $HTTP_POST_FILES[upfiles][type][$i];
			
		    // 파일 확장자 검사
		    if(!strcmp($extension,"htm") ||!strcmp($extension,"html") ||!strcmp($extension,"phtml") ||!strcmp($extension,"php") ||!strcmp($extension,"php3") ||!strcmp($extension,"php4") ||!strcmp($extension,"inc") ||!strcmp($extension,"pl") ||!strcmp($extension,"cgi")){
				jsMsg("not allowed file extension");
		        jsHistory("-1");
		    }
			
			if (is_uploaded_file($HTTP_POST_FILES[upfiles][tmp_name][$i])) {	
				move_uploaded_file ($HTTP_POST_FILES[upfiles][tmp_name][$i], $GLOBALS["_SITE"]["BOARD_DATA"] . "/".$boardid."/".$filerename);
				//썸네일 만들기
				if($filetype=="image/pjpeg" || $filetype=="image/x-png" || $filetype=="image/jpeg" || $filetype=="image/png" || $filetype=="image/gif"){
					@MakeThum($GLOBALS["_SITE"]["BOARD_DATA"] . "/".$boardid."/".$filerename, $GLOBALS["_SITE"]["BOARD_DATA"] . "/".$boardid."/t_".$filerename, $thumwidth);
				}
			}
			
			$sql = "insert into ".$GLOBALS["_conf_tbl"]["board_files"]." set 
				boardid='".$boardid."',/*게시판 아이디*/
				b_idx='".$idx."',/* 글 번호 id*/
				ori_name='".$filename."',/*파일원본이름*/
				re_name='".$filerename."',/*md5로 변환된 파일이름*/
				type='".$filetype."',/*파일타입*/
				ext ='".$extension."',/*파일확장자*/
				size='".$filesize."',/*첨부파일 용량*/
				wdate=now()
			";
			$rsf = mysql_query($sql,$GLOBALS["dblink"]);
		}
	}
	for($i=0;$i<count($_FILES[upfiles1][error]);$i++){
		if ($_FILES[upfiles1][error][$i] == 0){
		    //확장자 검사후 파일이름 생성
		    $filename = $_FILES[upfiles1][name][$i];
		    $attach_ext = explode(".",$filename);
		    $extension = $attach_ext[sizeof($attach_ext)-1];
		    $extension = strtolower($extension);		    
		    $filerename = $filename;
	  		$filesize = $_FILES[upfiles1][size][$i];
	  		$filetype = $_FILES[upfiles1][type][$i];
			
		    // 파일 확장자 검사
		    if(!strcmp($extension,"htm") ||!strcmp($extension,"html") ||!strcmp($extension,"phtml") ||!strcmp($extension,"php") ||!strcmp($extension,"php3") ||!strcmp($extension,"php4") ||!strcmp($extension,"inc") ||!strcmp($extension,"pl") ||!strcmp($extension,"cgi")){
				jsMsg("not allowed file extension");
		        jsHistory("-1");
		    }
			
			if (is_uploaded_file($_FILES[upfiles1][tmp_name][$i])) {	
				move_uploaded_file ($_FILES[upfiles1][tmp_name][$i], $GLOBALS["_SITE"]["BOARD_DATA"] . "/".$boardid."/".$filerename);
				//썸네일 만들기
				if($filetype=="image/pjpeg" || $filetype=="image/x-png" || $filetype=="image/jpeg" || $filetype=="image/png" || $filetype=="image/gif"){
					@MakeThum($GLOBALS["_SITE"]["BOARD_DATA"] . "/".$boardid."/".$filerename, $GLOBALS["_SITE"]["BOARD_DATA"] . "/".$boardid."/t_".$filerename, $thumwidth);
				}
			}
			
			$sql = "insert into ".$GLOBALS["_conf_tbl"]["board_files"]." set 
				boardid='".$boardid."',/*게시판 아이디*/
				b_idx='".$idx."',/* 글 번호 id*/
				ori_name='".$filename."',/*파일원본이름*/
				re_name='".$filerename."',/*md5로 변환된 파일이름*/
				type='".$filetype."',/*파일타입*/
				ext ='".$extension."',/*파일확장자*/
				size='".$filesize."',/*첨부파일 용량*/
				type2='con1',
				wdate=now()
			";
			$rsf = mysql_query($sql,$GLOBALS["dblink"]);
		}
	}
}

//댓글 목록 가져오기
function getCommentList($boardid, $board_idx, $scale, $offset=0){
		// 테이블 지정
		$tbl = $GLOBALS["_conf_tbl"]["comment"];

    $sql = "SELECT * FROM $tbl WHERE 1=1 ";

		if($boardid !=""){
			$sql .= " AND boardid='$boardid' "; 
		}
		if($board_idx !=""){
			$sql .= " AND board_idx='$board_idx' ";
		}
		$sql .= " order by idx desc ";

    $rs = mysql_query($sql, $GLOBALS["dblink"]);
    $total_rs = mysql_num_rows($rs);

	//echo $sql;

    if($total_rs > 0){
        $list['total'] = $total_rs;
        // 페이지 네비게이션 오프셋 지정.
		    if(!$offset){
		        $offset=0;
		    }else{
		        $offset=$offset;
		    }

		    // offset 이 전체 게시물수보다 작을때 offset 을 전체게시물 - 페이지당 보여줄 글 수로 offset 설정
		    if($total_rs<=$offset){
		        $offset = $total_rs - $scale;
		    }

				//scale 0 으로 지정시에는 전체 가져옴
				if($scale > 0){
		    	$sql .= " limit $offset,$scale ";
				}
		    $rs = mysql_query($sql,$GLOBALS["dblink"]);
		
		    // offset 을 이용한 limit 가 적용된 갯수
		    $total = mysql_num_rows($rs);
		    $list['list']['total'] = $total;
		    // 페이지 네비게이션 오프셋 지정.
		    
        for($i=0; $i < $total; $i++){
            $list['list'][$i] = mysql_fetch_assoc($rs);
        }
    }else{
        $list['total'] = 0;
    }
    
    return $list;
}

//댓글 등록하기
function insertComment($boardid, $board_idx){
	// 테이블 지정
	$tbl = $GLOBALS["_conf_tbl"]["comment"];

	if($_SESSION[$GLOBALS["_SITE"]["DOMAIN"]]["ADMIN"]["ID"]) {
		$user_id = $_SESSION[$GLOBALS["_SITE"]["DOMAIN"]]["ADMIN"]["ID"];
		$user_name = $_SESSION[$GLOBALS["_SITE"]["DOMAIN"]]["ADMIN"]["NAME"];;
	} else {
		$user_id = $_SESSION[$GLOBALS["_SITE"]["DOMAIN"]]["MEMBER"]["ID"]; 
		$user_name = $_SESSION[$GLOBALS["_SITE"]["DOMAIN"]]["MEMBER"]["NAME"];
	}
	
	if($_SESSION[$GLOBALS["_SITE"]["DOMAIN"]]["ADMIN"]["ID"] || $_SESSION[$GLOBALS["_SITE"]["DOMAIN"]]["MEMBER"]["ID"]) {
		//댓글 테이블에 입력
		$sql = "INSERT INTO ".$tbl." set 
			boardid='$boardid',
			board_idx='$board_idx',
			user_id='".$user_id."',
			user_name='".$user_name."',
			comment='".mysql_real_escape_string($_POST[comment])."',
			ip='".$_SERVER[REMOTE_ADDR]."',
			wdate=now()
		";
	}

	$rs = mysql_query($sql, $GLOBALS["dblink"]);
	$total = mysql_affected_rows($GLOBALS["dblink"]);

	if($total > 0){
		return true;
	}else{
		return false;
	}
}

//댓글 가져오기 - id
function getCommentInfo($idx){
	// 테이블 지정
	$tbl = $GLOBALS["_conf_tbl"]["comment"];

	$sql  = "SELECT * ";
	$sql .= "FROM $tbl ";
	$sql .= "WHERE idx = '$idx' ";
	$rs = mysql_query($sql, $GLOBALS["dblink"]);
	//echo $sql;

	$total_rs = mysql_num_rows($rs);
	
	if($total_rs > 0){
			$list['total'] = $total_rs;
			for($i=0; $i < $total_rs; $i++){
					$list['list'][$i] = mysql_fetch_assoc($rs);
			}
	}else{
			$list['total'] = 0;
	}
	return $list;
}

//댓글 삭제하기
function deleteComment($idx){
	// 테이블 지정
	$tbl = $GLOBALS["_conf_tbl"]["comment"];

	//삭제권한 설정
	$deletePerm = false;

	//관리자는 그냥 통과
	if($_SESSION[$GLOBALS["_SITE"]["DOMAIN"]]["ADMIN"]["GRADE"]=="ROOT" || @in_array("board_manage",$_SESSION[$GLOBALS["_SITE"]["DOMAIN"]]["ADMIN"]["AUTH"])){
		$deletePerm = true;
	}

	//기존정보
	$arrArticleInfo = getCommentInfo($idx);
	
	if($arrArticleInfo["list"][0]["user_id"]==$_SESSION[$GLOBALS["_SITE"]["DOMAIN"]]["MEMBER"]["ID"]){
		$deletePerm = true;
	}

	
	if($deletePerm==true){
		//댓글 테이블에서 삭제
		$sql = "DELETE FROM ".$tbl." 
			WHERE idx='$idx'
		";

		$rs = mysql_query($sql, $GLOBALS["dblink"]);
		$total = mysql_affected_rows($GLOBALS["dblink"]);

		if($total > 0){
			return true;
		}else{
			return false;
		}
	}else{
		jsMsg("삭제할 권한이 없습니다.");
		return false;
	}
}

//==================================================
// 첫화면 인텍스 메인화면에 리스트와 이미지 부르기
// 200900604
//===================================================

function getBoardLastNImage($boardid, $limit,$category=""){
	//게시판 테이블 지정
	$tblid = $GLOBALS["_SITE"]["BOARD_PREWORD"] . $boardid;

	//카테고리가 있을경우
	if($category !=""){
			$que_category = " and A.category='$category' ";
	}

    //목록
    $sql  = "SELECT A.*, B.idx AS f_idx, B.boardid, B.b_idx, B.ori_name, B.re_name, B.type, B.size ";
    $sql .= "FROM $tblid A LEFT JOIN ".$GLOBALS["_conf_tbl"]["board_files"]." B ON B.boardid='$boardid' AND A.idx=B.b_idx AND B.ext IN('jpg','gif','png')";
    $sql .= "WHERE A.no='1' $que_where $que_category group by A.idx DESC LIMIT $limit";


	$rs = mysql_query($sql,$GLOBALS["dblink"]);

	// offset 을 이용한 limit 가 적용된 갯수
	$total = mysql_num_rows($rs);
	$list['list']['total'] = $total;
	// 페이지 네비게이션 오프셋 지정.

    if($total > 0){
        $list['total'] = $total;
        // 페이지 네비게이션 오프셋 지정.
			
		for($i=0; $i < $total; $i++){
            $list['list'][$i] = mysql_fetch_assoc($rs);
    	}	
    }else{
        $list['total'] = 0;
    }
	
    return $list;
}


//==============================================
// 게시물 첨부파일,메모카운트
// 20090507
// 첨부파일조인후 메모카운트는 배열에 추가저장
// 피노갤러리에서 가져옴
//==============================================
function getBoardListBaseNFileNMemoCnt($boardid, $category, $sw="", $sk="", $scale, $offset=0){
	//게시판 테이블 지정
	$tblid = $GLOBALS["_SITE"]["BOARD_PREWORD"] . $boardid;
	
	// 추가부분
	// 코멘트 테이블
	$tbl_comment = $GLOBALS["_conf_tbl"]["comment"];

	//카테고리가 있을경우
	if($category !=""){
		$que_category = " and A.category='$category' ";
	}

	//검색키워드가 있을경우
	if($sk !=""){
		switch($sw){
		case("n") :
			$que_where = "and A.name like '%$sk%'";
		break;
		case("s") :
			$que_where = "and A.subject like '%$sk%'";
		break;
		case("c") :
			$que_where = "and A.contents like '%$sk%'";
		break;
		case("a") :
		default :
			$que_where = "and (A.name like '%$sk%' or A.subject like '%$sk%' or A.contents like '%$sk%')";
		}

		// 검색시 영역을 분할하여 검색=> 속도향상용
		$sql = "select count(A.idx) as cnt from $tblid A";
		$rs = mysql_query($sql, $GLOBALS["dblink"]);

		$row = mysql_fetch_assoc($rs);
		$q_total = $row[cnt];
		$q_start = $q_total - 10000; // 최근 10000건만 검색
		
		if($q_total>10000){
			$q_limit = " A.idx between " . $q_start . " and " . $q_total . " ";
		}
		// 검색시 영역을 분할하여 검색=> 속도향상용
	}


		
	//카운트
	$sql = "select count(A.idx) from $tblid A WHERE A.no='1' $q_limit $que_where $que_category ";
    $rs = mysql_query($sql, $GLOBALS["dblink"]);
    $row = mysql_fetch_row($rs);
    $total_rs = $row[0];


	//목록
    $sql  = "SELECT A.*, B.idx AS f_idx, B.boardid, B.b_idx, B.ori_name, B.re_name, B.type, B.size ";
    $sql .= "FROM $tblid A LEFT JOIN ".$GLOBALS["_conf_tbl"]["board_files"]." B ON B.boardid='$boardid' AND A.idx=B.b_idx ";
    $sql .= "WHERE A.no='1' $q_limit $que_where $que_category group by A.idx";


    if($total_rs > 0){
        $list['total'] = $total_rs;
        // 페이지 네비게이션 오프셋 지정.
		    if(!$offset){
		        $offset=0;
		    }else{
		        $offset=$offset;
		    }

		    // offset 이 전체 게시물수보다 작을때 offset 을 전체게시물 - 페이지당 보여줄 글 수로 offset 설정
		    if($total_rs<=$offset){
		        $offset = $total_rs - $scale;
		    }

			//scale 0 으로 지정시에는 전체 가져옴
			if($scale > 0){
				$sql .= " order by A.main limit $offset,$scale ";
			}else{
				$sql .= " order by A.main ";
			}
			
			
		
		    $rs = mysql_query($sql,$GLOBALS["dblink"]);

		    // offset 을 이용한 limit 가 적용된 갯수
		    $total = mysql_num_rows($rs);
		    $list['list']['total'] = $total;
		    // 페이지 네비게이션 오프셋 지정.

			for($i=0; $i < $total; $i++){
				$list['list'][$i] = mysql_fetch_assoc($rs);
			
				// 댓글 카운트 추가 부분
				$m_cnt_row = mysql_fetch_row(mysql_query("select count(idx) from $tbl_comment WHERE boardid='$boardid' AND board_idx='".$list['list'][$i]["idx"]."' "));			
				$list['list'][$i]["cmt_count"] = $m_cnt_row[0];
			}		
		
		
    }else{
        $list['total'] = 0;
    }
    return $list;
}


function getBoardListMiQna($boardid, $category, $sw="", $sk="", $scale, $offset=0){
	//게시판 테이블 지정
	$tblid = $GLOBALS["_SITE"]["BOARD_PREWORD"] . $boardid;

	//카테고리가 있을경우
	if($category !=""){
		$que_category = " and category='$category' ";
	}

	//검색키워드가 있을경우
	if($sk !=""){
		switch($sw){
		case("n") :
			$que_where = "and name like '%$sk%'";
		break;
		case("s") :
			$que_where = "and subject like '%$sk%'";
		break;
		case("c") :
			$que_where = "and contents like '%$sk%'";
		break;
		case("u_id") :
			$que_where = "and w_user like '%$sk%'";
		break;
		case("a") :
		default :
			$que_where = "and (name like '%$sk%' or subject like '%$sk%' or contents like '%$sk%' or w_user like '%$sk%')";
		}

		// 검색시 영역을 분할하여 검색=> 속도향상용
		$sql = "select count(idx) as cnt from $tblid ";
		$rs = mysql_query($sql, $GLOBALS["dblink"]);

		$row = mysql_fetch_assoc($rs);
		$q_total = $row[cnt];
		$q_start = $q_total - 10000; // 최근 10000건만 검색
		
		if($q_total>10000){
			$q_limit = " idx between " . $q_start . " and " . $q_total . " ";
		}
		// 검색시 영역을 분할하여 검색=> 속도향상용
	}
	//카운트
	$sql = "select count(idx) from $tblid WHERE no=1 $q_limit $que_where $que_category GROUP BY main HAVING COUNT(main) < 2 ";
    $rs = mysql_query($sql, $GLOBALS["dblink"]);
    $row = mysql_fetch_row($rs);
    $total_rs = $row[0];

	//목록
    $sql  = "SELECT * ";
    $sql .= "FROM $tblid ";
	$sql .= "WHERE no=1 $q_limit $que_where $que_category GROUP BY main HAVING COUNT(main) < 2 ";

    if($total_rs > 0){
        $list['total'] = $total_rs;
        // 페이지 네비게이션 오프셋 지정.
		    if(!$offset){
		        $offset=0;
		    }else{
		        $offset=$offset;
		    }

		    // offset 이 전체 게시물수보다 작을때 offset 을 전체게시물 - 페이지당 보여줄 글 수로 offset 설정
		    if($total_rs<=$offset){
		        $offset = $total_rs - $scale;
		    }

				//scale 0 으로 지정시에는 전체 가져옴
				if($scale > 0){
			    $sql .= " order by main, sub limit $offset,$scale ";
				}else{
				  $sql .= " order by main, sub ";
				}

	    	
		    $rs = mysql_query($sql,$GLOBALS["dblink"]);
		//echo $sql;
		    // offset 을 이용한 limit 가 적용된 갯수
		    $total = mysql_num_rows($rs);
		    $list['list']['total'] = $total;
		    // 페이지 네비게이션 오프셋 지정.
		    
        for($i=0; $i < $total; $i++){
            $list['list'][$i] = mysql_fetch_assoc($rs);
        }
    }else{
        $list['total'] = 0;
    }
    return $list;
}
?>
