<?php

class Board extends BaseCode {
  public $board_info = "";

  function __construct( $board_id ){
    parent::__construct();

    $this->DB->tableExists( TB_board_list );
    $this->DB->tableExists( TB_board_contents );
    $this->DB->tableExists( TB_board_attach );
    $this->DB->tableExists( TB_board_opinion );
    $this->DB->tableExists( TB_member );
    $this->board_info = $this->getBoardId($board_id);
  }

  function getBoardList($field="*",$where="", $orderby="",$limit=array()){ //게시판 리스트
    if( !$where ){
      $where = new DB_where("and");
    }

    $wqry = $where->get_where();
    $whereqry = $wqry['qry'];
    $whererow = $wqry['val'];

    //$sql = "select brd.{$field}, mem.member_name from ". TB_board_list ." as brd left join ". TB_member ." as mem on brd.board_admin = mem.member_id where {$whereqry}".(($orderby)?" order by {$orderby}":""). $this->DB->_limit($limit[0],$limit[1]);
    $sql = $this->DB->addLimit("select brd.{$field}, mem.member_name from ". TB_board_list ." as brd left join ". TB_member ." as mem on brd.board_admin = mem.member_id where {$whereqry}",$orderby,$limit[0],$limit[1]);
    $rows = $this->DB->query($sql, $whererow);
    return $rows;
  }

  function getBoardPage($sqldata="", $where=""){ //게시판 리스트(페이징)
    if( !$where ){
      $where = new DB_where("and");
    }
    if( $sqldata['stxt'] ){
      $subwhere = $where->sub_where("or");
      if( $sqldata['sfld'] ){
        $subwhere->add("{$sqldata['sfld']} like ?", "%{$sqldata['stxt']}%");
      }else{
        $subwhere->add("board_id like ?", "%{$sqldata['stxt']}%");
        $subwhere->add("board_name like ?", "%{$sqldata['stxt']}%");
      }
    }

    $wqry = $where->get_where();
    $whereqry = $wqry['qry'];
    $whererow = $wqry['val'];

    $orderby = "board_name asc";
    if( $sqldata['ofld'] && $sqldata['oasc'] ) $orderby = "{$sqldata['ofld']} {$sqldata['oasc']}";

    $query = array(
      "mode"     => $sqldata['mode'],
      "viewnum"  => $sqldata['viewnum']?:20,
      "sfld"     => $sqldata['sfld'],
      "stxt"     => $sqldata['stxt'],
      "ofld"     => $sqldata['ofld'],
      "oasc"     => $sqldata['oasc'],
    );

    $table = "(select brd.*, mem.member_name from ". TB_board_list ." as brd left join ". TB_member ." as mem on brd.board_admin = mem.member_id) as A";

    $lists = new clist();
    $lists->fld      = "*";
    $lists->where    = $whereqry;
    $lists->whererow = $whererow;
    $lists->orderby  = $orderby;
    $lists->url      = $_SERVER['PHP_SELF'];
    $lists->query    = $query;
    $lists->page     = $sqldata['page']?:1;
    $lists->linktype = "";
    $lists->viewnum  = $query['viewnum'];
    $lists->rownum   = $sqldata['rownum']?:5;
    $lists->getCommonList($table);

    for( $a=0 ; $a<@count($lists->rows) ; $a++ ){
      $lists->rows[$a]['board_id'] = stripslashes($lists->rows[$a]['board_id']);
      $lists->rows[$a]['board_name'] = stripslashes($lists->rows[$a]['board_name']);
      $lists->rows[$a]['con_num'] = $this->getContentsNum($lists->rows[$a]['board_id']);
    }
    return $lists;
  }

  function getBoard($board_id){ //게시판 불러오기
    return $this->getBoardId($board_id);
  }

  function getBoardId($board_id){ //게시판 불러오기 (board_id)
    $where = new DB_where("and");
    $where->add("board_id = ?", $board_id);

    $wqry = $where->get_where();
    $whereqry = $wqry['qry'];
    $whererow = $wqry['val'];

    $sql = "select * from ". TB_board_list ." where {$whereqry}";
    $rst = $this->DB->queryFirstRow($sql, $whererow);
    $rst['board_name'] = stripslashes($rst['board_name']);
    return $rst;
  }

  function putBoard( $sqldata ){
    $sqlrow = array(
      "board_id"        => $sqldata['board_id']?:"",
      "board_name"      => $sqldata['board_name']?:"",
      "board_admin"     => $sqldata['board_admin']?:"",
      "board_cate"      => $sqldata['board_cate']?:"",
      "read_level"      => $sqldata['read_level']?:"",
      "write_level"     => $sqldata['write_level']?:"",
      "ness_name"       => $sqldata['ness_name']?:"",
      "ness_passwd"     => $sqldata['ness_passwd']?:"",
      "ness_title"      => $sqldata['ness_title']?:"",
      "ness_homepage"   => $sqldata['ness_homepage']?:"",
      "ness_mail"       => $sqldata['ness_mail']?:"",
      "ness_contents"   => $sqldata['ness_contents']?:"",
      "ness_image"      => $sqldata['ness_image']?:"",
      "ness_file"       => $sqldata['ness_file']?:"",
      "use_opinion"     => $sqldata['use_opinion']?:"",
      "use_spamproof"   => $sqldata['use_spamproof']?:"",
      "use_webeditor"   => $sqldata['use_webeditor']?:"",
      "line_num"        => $sqldata['line_num']?:"",
      "page_num"        => $sqldata['page_num']?:"",
      "new_num"         => $sqldata['new_num']?:1,
      "hot_num"         => $sqldata['hot_num'],
      "skin_name"       => $sqldata['skin_name'],
    );
    $rst = $this->DB->insert( TB_board_list, $sqlrow );
    if( $rst ){
      return $sqlrow['board_id'];
    }
  }

  function setBoard( $sqldata ){
    $obrd = $this->getBoard($sqldata['board_id']);
    $sqlrow = array(
      "board_id"        => $sqldata['board_id']?:"",
      "board_name"      => $sqldata['board_name']?:"",
      "board_admin"     => $sqldata['board_admin']?:"",
      "board_cate"      => $sqldata['board_cate']?:"",
      "read_level"      => $sqldata['read_level']?:"",
      "write_level"     => $sqldata['write_level']?:"",
      "ness_name"       => $sqldata['ness_name']?:"",
      "ness_passwd"     => $sqldata['ness_passwd']?:"",
      "ness_title"      => $sqldata['ness_title']?:"",
      "ness_homepage"   => $sqldata['ness_homepage']?:"",
      "ness_mail"       => $sqldata['ness_mail']?:"",
      "ness_contents"   => $sqldata['ness_contents']?:"",
      "ness_image"      => $sqldata['ness_image']?:"",
      "ness_file"       => $sqldata['ness_file']?:"",
      "use_opinion"     => $sqldata['use_opinion']?:"",
      "use_spamproof"   => $sqldata['use_spamproof']?:"",
      "use_webeditor"   => $sqldata['use_webeditor']?:"",
      "line_num"        => $sqldata['line_num']?:"",
      "page_num"        => $sqldata['page_num']?:"",
      "new_num"         => $sqldata['new_num']?:1,
      "hot_num"         => $sqldata['hot_num'],
      "skin_name"       => $sqldata['skin_name'],
    );
    $where = new DB_where("and");
    $where->add("board_id = ?", $sqldata['board_id']);

    $wqry = $where->get_where();
    $whereqry = $wqry['qry'];
    $whererow = $wqry['val'];

    $rst = $this->DB->update( TB_board_list, $sqlrow, $whereqry, $whererow);
    if( $rst ){
      return $sqldata['board_id'];
    }
    return 0;
  }

  function delBoard( $board_id ){
    $where = new DB_where("and");
    $where->add("board_id = ?", $board_id);

    $wqry = $where->get_where();
    $whereqry = $wqry['qry'];
    $whererow = $wqry['val'];

    $rst = $this->DB->delete( TB_board_list, $whereqry, $whererow);
    $rst = $rst && $this->DB->delete( TB_board_contents, $whereqry, $whererow);
    $rst = $rst && $this->DB->delete( TB_board_opinion, $whereqry, $whererow);

    if( $rst ){
      $this->delFiles( "board", array("board_id"=>$board_id) );
      return 1;
    }
    return 0;
  }

  function getContentsList($field="*", $where="", $orderby="", $limit=array(), $dmode=""){ //게시물 리스트
    if( !$where ){
      $where = new DB_where("and");
    }

    if( $dmode != "all" ){ //전체 게시물 리스트 아니면
      $where->add("board_id = ?", $this->board_info['board_id']);
    }

    if( !$this->isAdmin() ){
      $where->add("state = ?", 1);
    }

    $wqry = $where->get_where();
    $whereqry = $wqry['qry'];
    $whererow = $wqry['val'];

    //$sql = "select {$field} from (select brc.*, brl.board_name from ". TB_board_contents ." as brc inner join ". TB_board_list ." as brl on brc.board_id = brl.board_id) as brd where {$whereqry} ".(($orderby)?"order by {$orderby}":""). $this->DB->_limit($limit[0],$limit[1]);
    $sql = $this->DB->addLimit("select {$field} from (select brc.*, brl.board_name from ". TB_board_contents ." as brc inner join ". TB_board_list ." as brl on brc.board_id = brl.board_id) as brd where {$whereqry}",$orderby,$limit[0],$limit[1]);
    $rst = $this->DB->qry($sql, $whererow);
    $rows = array();
    while( $tmp = $this->DB->fetch_array($rst) ){
      $tmp = $this->getContentsInfo($tmp);

      if( !$this->isAdmin() ){
        unset($tmp['ip_addr']);
      }
      $rows[] = $tmp;
    }
    return $rows;
  }

  function getContentsPage($sqldata="", $where=""){ //게시물 리스트(페이징)
    if( !$where ){
      $where = new DB_where("and");
    }

    if( $sqldata['dmode'] != "all" ){ //전체 게시물 리스트 아니면
      $where->add("board_id = ?", $this->board_info['board_id']);
    }

    if( $sqldata['gubun'] ){
      $where->add("gubun = ?", $sqldata['gubun']);
    }
    if( $sqldata['board_id'] ){
      $where->add("board_id = ?", $sqldata['board_id']);
    }
    if( !$this->isAdmin() ){
      $where->add("state = ?", 1);
    }
    if( $sqldata['stxt'] ){
      $subwhere = $where->sub_where("or");
      if( $sqldata['sfld'] ){
        $subwhere->add("{$sqldata['sfld']} like ?", "%{$sqldata['stxt']}%");
      }else{
        $subwhere->add("title like ?", "%{$sqldata['stxt']}%");
        $subwhere->add("contents like ?", "%{$sqldata['stxt']}%");
      }
    }

    $wqry = $where->get_where();
    $whereqry = $wqry['qry'];
    $whererow = $wqry['val'];

    $orderby = "cid desc";
    if( $sqldata['ofld'] && $sqldata['oasc'] ) $orderby = "{$sqldata['ofld']} {$sqldata['oasc']}";

    $query = array(
      "mode"      => $sqldata['mode'],
      "board_id"  => $sqldata['board_id'],
      "gubun"     => $sqldata['gubun'],
      "viewnum"   => $sqldata['viewnum']?:$this->board_info['line_num']?:30,
      "sfld"      => $sqldata['sfld'],
      "stxt"      => $sqldata['stxt'],
      "ofld"      => $sqldata['ofld'],
      "oasc"      => $sqldata['oasc'],
    );

    $table = "(select brc.*, brl.board_name from ". TB_board_contents ." as brc inner join ". TB_board_list ." as brl on brc.board_id = brl.board_id) as brd";
    $lists = new clist();
    $lists->fld      = "*";
    $lists->where    = $whereqry;
    $lists->whererow = $whererow;
    $lists->orderby  = $orderby;
    $lists->url      = $_SERVER['PHP_SELF'];
    $lists->query    = $query;
    $lists->page     = $sqldata['page']?:1;
    $lists->linktype = "";
    $lists->viewnum  = $query['viewnum'];
    $lists->rownum   = $this->board_info['page_num']?:10;
    $lists->getCommonList($table);

    for( $a=0 ; $a<@count($lists->rows) ; $a++ ){ $tmp = $lists->rows[$a];
      $tmp = $this->getContentsInfo($tmp);

      if( !$this->isAdmin() ){
        unset($tmp['ip_addr']);
      }
      $lists->rows[$a] = $tmp;
    }
    return $lists;
  }

  function getAllContentsList($field="*" ,$where="", $orderby="", $limit=array()){ //전체 게시물 리스트
    return $this->getContentsList($field, $where, $orderby, $limit, "all");
  }

  function getAllContentsPage($sqldata="", $where=""){ //전체 게시물 리스트(페이징)
    $sqldata['dmode'] = "all";
    return $this->getContentsPage($sqldata,$where);
  }

  function getContents( $cid ){ //게시물 불러오기
    if( !$cid ) return 0;

    $where = new DB_where("and");
    $where->add("board_id = ?", $this->board_info['board_id']);

    $where->add("cid = ?", $cid);
    if( !$this->isAdmin() ){
      $where->add("state != ?", 2);
    }

    $wqry = $where->get_where();
    $whereqry = $wqry['qry'];
    $whererow = $wqry['val'];

    $sql = "select * from ". TB_board_contents ." where {$whereqry}";
    $row = $this->DB->queryFirstRow( $sql, $whererow);
    $row = $this->getContentsInfo($row);

    if( !$this->isAdmin() ){
      unset($row['ip_addr']);
    }
    return $row;
  }

  function getContentsInfo( $row ){
    if( !$row['secret'] || $this->chkSecretAuth($row) ){
      $row['title']    = stripslashes($row['title']);
      $row['contents'] = stripslashes($row['contents']);
      switch( $this->board_info['use_webeditor'] ){
        case "Tinymce" : break;
        default : $row['contents'] = nl2br($row['contents']);
      }
      $row['contents_txt'] = strip_tags($row['contents']);
      $row['uname']    = stripslashes($row['uname']);
      $row['homepage'] = stripslashes($row['homepage']);
      $row['mail']     = $this->lcrypt->dec_secure($row['mail']);
      $row['mobile']   = $this->lcrypt->dec_secure($row['mobile']);
    }else{
      $row['title']    = "비밀글 입니다.";
      $row['contents'] = "비밀글 입니다.";
      $row['uname']    = "비밀글";
      $row['homepage'] = "http://xxx.xxx.xxx";
      $row['mail']     = "xxx@xxx.xxx";
      $row['mobile']   = "xxx-xxxx-xxxx";
    }
    return $row;
  }

  function putContents( $sqldata ){ //게시물 등록
    $sqlrow = array(
      "board_id"  => $this->board_info['board_id'],
      "gubun"     => $sqldata['gubun'],
      "title"     => $sqldata['title'],
      "contents"  => $sqldata['contents'],
      "notice"    => $sqldata['notice']?:"",
      "views"     => 0,
      "good"      => 0,
      "nogood"    => 0,
      "onum"      => 0,
      "secret"    => $sqldata['secret']?:"",
      "markup"    => $sqldata['markup']?:"",
      "state"     => $sqldata['state']?:1,
      "member_id" => $GLOBALS['_Umem']['member_id'],
      "uname"     => $sqldata['uname'],
      "passwd"    => $this->lcrypt->pw_make($sqldata['passwd']),
      "homepage"  => $sqldata['homepage'],
      "mail"      => $sqldata['mail']?$this->lcrypt->enc_secure($sqldata['mail']):"",
      "mobile"    => $sqldata['mobile']?$this->lcrypt->enc_secure($sqldata['mobile']):"",
      "ip_addr"   => get_ip(),
      "reg_date"  => $this->DB->sqleval("getdate()"),
      "mod_date"  => $this->DB->sqleval("getdate()"),
    );
    $rst = $this->DB->insert( TB_board_contents, $sqlrow );
    if( $rst ){
      $cid = $this->DB->insertId(TB_board_contents);
      $sqldata['cid'] = $cid;
      $this->putFiles( $sqldata );
      return $cid;
    }
  }

  function setContents( $sqldata ){ //게시물 수정
    $sqlrow = array(
      "gubun"     => $sqldata['gubun'],
      "title"     => $sqldata['title'],
      "contents"  => $sqldata['contents'],
      "uname"     => $sqldata['uname'],
      "homepage"  => $sqldata['homepage'],
      "mail"      => $sqldata['mail']?$this->lcrypt->enc_secure($sqldata['mail']):"",
      "mobile"    => $sqldata['mobile']?$this->lcrypt->enc_secure($sqldata['mobile']):"",
      "mod_date"  => $this->DB->sqleval("getdate()"),
    );

    if( $sqldata['state'] )  $sqlrow['state']  = $sqldata['state'];
    if( $sqldata['notice'] ) $sqlrow['notice'] = $sqldata['notice'];
    if( $sqldata['secret'] ) $sqlrow['secret'] = $sqldata['secret'];
    if( $sqldata['markup'] ) $sqlrow['markup'] = $sqldata['markup'];

    $where = new DB_where("and");
    $where->add("board_id = ?", $this->board_info['board_id']);
    $where->add("cid = ?", $sqldata['cid']);

    $wqry = $where->get_where();
    $whereqry = $wqry['qry'];
    $whererow = $wqry['val'];

    $rst = $this->DB->update( TB_board_contents, $sqlrow, $whereqry, $whererow );
    if( $rst ){
      $this->delFiles( "file", array("cid"=>$sqldata['cid'], "aid" => $sqldata['DEL_ATTFILES']) );
      $this->putFiles( $sqldata );
      return $sqldata['cid'];
    }
    return 0;
  }

  function delContents( $cid ){ //게시물 삭제
    $where = new DB_where("and");
    $where->add("board_id = ?", $this->board_info['board_id']);

    if( is_array($cid) ){
      $subwhere = $where->sub_where("or");
      foreach( (array)$cid as $v ){
        $subwhere->add("cid = ?", $v);
      }
    }else{
      $where->add("cid = ?", $cid);
    }

    $wqry = $where->get_where();
    $whereqry = $wqry['qry'];
    $whererow = $wqry['val'];

    $rst = 1;
    $rst = $rst && $this->DB->delete( TB_board_contents, $whereqry, $whererow);
    $rst = $rst && $this->DB->delete( TB_board_opinion, $whereqry, $whererow);
    if( $rst ){
      $this->delFiles( "contents", array("cid"=>$cid) );
      unset($_SESSION['board_read_'.$this->board_info['board_id']."_".$cid]);
      unset($_SESSION['board_secret_'.$this->board_info['board_id']."_".$cid]);
      return 1;
    }
    return 0;
  }

  function getContentsNum( $board_id ){
    $where = new DB_where("and");
    $where->add("board_id = ?", $board_id);

    $wqry = $where->get_where();
    $whereqry = $wqry['qry'];
    $whererow = $wqry['val'];

    $sql = "select count(*) from ". TB_board_contents ." where {$whereqry}";
    $con_num = $this->DB->queryFirstField($sql, $whererow);

    return $con_num?:0;
  }

  function getOpinionList($cid, $limit=array()){ //게시물 리스트
    $where = new DB_where("and");
    $where->add("board_id= ?", $this->board_info['board_id']);
    $where->add("cid = ?", $cid);

//    if( !$this->isAdmin() ){
//      $where->add("state = %i", 1);
//    }

    $wqry = $where->get_where();
    $whereqry = $wqry['qry'];
    $whererow = $wqry['val'];

    //$sql = "select A.*, B.snum from ". TB_board_opinion ." as A left join (select uid as sid, count(*)-1 as snum from ". TB_board_opinion ." group by uid) as B on A.oid = B.sid where {$whereqry} order by uid asc, oid asc ". $this->DB->_limit($limit[0],$limit[1]);
    $sql = $this->DB->addLimit("select A.*, B.snum from ". TB_board_opinion ." as A left join (select uid as sid, count(*)-1 as snum from ". TB_board_opinion ." group by uid) as B on A.oid = B.sid where {$whereqry}","uid asc, oid asc",$limit[0],$limit[1]);
    $rst = $this->DB->qry($sql, $whererow);
    $rows = array();
    while( $tmp = $this->DB->fetch_array($rst) ){
      $rows[] = $this->getFtOpinion($tmp);
    }
    return $rows;
  }

  function getOpinionSubList($cid, $uid){ //게시물 리스트
    $where = new DB_where("and");
    $where->add("board_id = ?", $this->board_info['board_id']);
    $where->add("cid = ?", $cid);
    $where->add("uid = ?", $uid);
    $where->add("oid != uid");

//    if( !$this->isAdmin() ){
//      $where->add("state = ?", 1);
//    }

    $wqry = $where->get_where();
    $whereqry = $wqry['qry'];
    $whererow = $wqry['val'];

    $sql = "select * from ". TB_board_opinion ." where {$whereqry} order by uid asc, oid asc";
    $rst = $this->DB->qry($sql, $whererow);
    $rows = array();
    while( $tmp = $this->DB->fetch_array($rst) ){
      $rows[] = $this->getFtOpinion($tmp);
    }
    return $rows;
  }

  function getOpinionPage($cid, $page=""){ //게시물 리스트(페이징)
    $where = new DB_where("and");
    $where->add("board_id = ?", $this->board_info['board_id']);
    $where->add("cid = ?", $cid);

    $wqry = $where->get_where();
    $whereqry = $wqry['qry'];
    $whererow = $wqry['val'];

    $orderby = "uid asc, oid asc";
    $query = array(
      "board_id"  => $this->board_info['board_id'],
      "cid"       => $cid,
      "viewnum"   => $this->board_info['line_num'],
    );

    $lists = new clist();
    $lists->fld      = "*";
    $lists->where    = $whereqry;
    $lists->whererow = $whererow;
    $lists->orderby  = $orderby;
    $lists->url      = $_SERVER['PHP_SELF'];
    $lists->query    = $query;
    $lists->page     = $page?:1;
    $lists->linktype = "";
    $lists->viewnum  = $query['viewnum'];
    $lists->rownum   = $this->board_info['page_num'];
    $lists->getCommonList(TB_board_opinion);

    for( $a=0 ; $a<@count($lists->rows) ; $a++ ){;
      $lists->rows[$a] = $this->getFtOpinion($lists->rows[$a]);
    }
    return $lists;
  }

  function getOpinion( $cid, $oid ){
    $where = new DB_where("and");
    $where->add("board_id = ?", $this->board_info['board_id']);
    $where->add("cid = ?", $cid);
    $where->add("oid = ?", $oid);

    $wqry = $where->get_where();
    $whereqry = $wqry['qry'];
    $whererow = $wqry['val'];

    $sql = "select * from ". TB_board_opinion ." where {$whereqry}";
    $row = $this->DB->queryFirstRow( $sql, $whererow );
    $row = $this->getFtOpinion($row);
    return $row;
  }

  function getFtOpinion( $row ){ //삭제 및 제한된 게시물조치
    switch( $row['state'] ){
      case "2" :
        $row['opinion'] = "관리규정에 의해 제한 조치 됨";
        $row['uname']   = "None";
      break;
      case "3" :
        $row['opinion'] = "사용자 삭제";
        $row['uname']   = "None";
      break;
      default :
        $row['opinion'] = stripslashes($row['opinion']);
        $row['uname']   = stripslashes($row['uname']);
      break;
    }
    return $row;
  }

  function putOpinion( $sqldata ){
    $sqlrow = array(
      "board_id"  => $this->board_info['board_id'],
      "cid"       => $sqldata['cid'],
      "uid"       => $sqldata['uid']?:0,
      "idx"       => $sqldata['idx']?:"",
      "opinion"   => $sqldata['opinion'],
      "good"      => 0,
      "nogood"    => 0,
      "state"     => $sqldata['state']?:1,
      "member_id" => $GLOBALS['_Umem']['member_id'],
      "uname"     => $sqldata['uname'],
      "passwd"    => $this->lcrypt->pw_make($sqldata['passwd']),
      "ip_addr"   => get_ip(),
      "reg_date"  => $this->DB->sqleval("getdate()"),
      "mod_date"  => $this->DB->sqleval("getdate()"),
    );

    $rst = $this->DB->insert( TB_board_opinion, $sqlrow );
    if( $rst ){
      $oid = $this->DB->insertId(TB_board_opinion);

      /*의견글 갯수 확인*/
      $where = new DB_where("and");
      $where->add("board_id = ?", $this->board_info['board_id']);
      $where->add("cid = ?", $sqldata['cid']);

      $wqry = $where->get_where();
      $whereqry = $wqry['qry'];
      $whererow = $wqry['val'];

      $onum = $this->DB->queryFirstField("select count(*) from ". TB_board_opinion ." where {$whereqry}",$whererow);

      /*상위 의견글이 없으면 자신의 oid 를 상위 의견글로 지정*/
      if( !$sqldata['uid'] ){
        $sqlrow2 = array(
          "uid" => $oid,
        );
        $where->add("oid = ?", $oid);

        $wqry = $where->get_where();
        $whereqry = $wqry['qry'];
        $whererow = $wqry['val'];

        $this->DB->update( TB_board_opinion, $sqlrow2, $whereqry, $whererow );
      }

      /*의견글 갯수 수정*/
      $sqlrow3 = array(
        "onum" => $onum,
      );
      $where = new DB_where("and");
      $where->add("board_id = ?", $this->board_info['board_id']);
      $where->add("cid = ?", $sqldata['cid']);

      $wqry = $where->get_where();
      $whereqry = $wqry['qry'];
      $whererow = $wqry['val'];

      $this->DB->update( TB_board_contents, $sqlrow3, $whereqry, $whererow );
      return $oid;
    }
  }

  function setOpinion( $sqldata ){
    $sqlrow = array(
      "opinion"   => $sqldata['opinion'],
      "uname"     => $sqldata['uname'],
      "mod_date"  => $this->DB->sqleval("getdate()"),
    );
    $where = new DB_where("and");
    $where->add("board_id = ?", $this->board_info['board_id']);
    $where->add("cid = ?", $sqldata['cid']);
    $where->add("oid = ?", $sqldata['oid']);

    $wqry = $where->get_where();
    $whereqry = $wqry['qry'];
    $whererow = $wqry['val'];

    $rst = $this->DB->update( TB_board_opinion, $sqlrow, $whereqry, $whererow);
    if( $rst ){
      return $sqldata['oid'];
    }
  }

  function delOpinion( $sqldata ){
    $where = new DB_where("and");
    $where->add("board_id = ?", $this->board_info['board_id']);
    $where->add("cid = ?", $sqldata['cid']);
    $where->add("oid = ?", $sqldata['oid']);

    $wqry = $where->get_where();
    $whereqry = $wqry['qry'];
    $whererow = $wqry['val'];

    switch( $sqldata['mode'] ){
      case "rejOpinion":
        $sqlrow = array(
          "state" => "2",
        );
      break;
      case "delOpinion":
        $sqlrow = array(
          "state" => "3",
        );
      break;
    }
    $rst = $this->DB->update( TB_board_opinion, $sqlrow, $whereqry, $whererow);

    return $rst;
  }

  function getFiles( $cid ){
    $where = new DB_where("and");
    $where->add("board_id = ?", $this->board_info['board_id']);
    $where->add("cid = ?", $cid);

    $wqry = $where->get_where();
    $whereqry = $wqry['qry'];
    $whererow = $wqry['val'];

    $sql = "select * from ". TB_board_attach ." where {$whereqry} order by aid asc";
    $rows = $this->DB->query($sql, $whererow);
    return $rows;
  }

  function putFiles( $sqldata ){
    if( $sqldata['ATTFILES'] ){
      $_SFILES = \Frody\Util\MultiFileUpload::swfFormFileInfo($sqldata['ATTFILES'], _UP_PATH_TMP_, "N");
      $rst = 1;
      for( $a = 0 ; $a<@count($_SFILES) ; $a++ ){
        $sqlrow = array(
          "board_id"    => $this->board_info['board_id'],
          "cid"         => $sqldata['cid'],
          "gubun"       => $sqldata['board_id']?:"",
          "file_name"   => addslashes($_SFILES[$a]['name']),
          "file_size"   => $_SFILES[$a]['size'],
          "file_type"   => $_SFILES[$a]['type'],
          "file_width"  => $_SFILES[$a]['width'],
          "file_height" => $_SFILES[$a]['height'],
          "reg_date"    => $this->DB->sqleval("getdate()"),
        );
        $rst = $this->DB->insert(TB_board_attach, $sqlrow);
        if( $rst ){
          $aid = $this->DB->insertId(TB_board_attach);
        }

        $upload_board_dir = _UP_PATH_."/board";
        if( !file_exists($upload_board_dir) ){
          mkdir($upload_board_dir);
        }
        $target_dir = $upload_board_dir."/{$this->board_info['board_id']}";
        if( !file_exists($target_dir) ){
          mkdir($target_dir);
        }
        $file_url = $this->getFileUrl($sqldata['cid'], $aid);
        $file_dir = $this->getFileDir($sqldata['cid'], $aid);

        $sqldata['contents'] = preg_replace("/((http).*?){0,1}src_{$_SFILES[$a]['tmp_text']}/ims", $file_url, $sqldata['contents']);
        $sqldata['contents'] = str_replace("ctrl_{$_SFILES[$a]['tmp_text']}", "ctrl_{$aid}", $sqldata['contents']);

        \Frody\Util\MultiFileUpload::swfMoveUploadedFile($_SFILES[$a]['tmp_name'], $file_dir);
      }
      $sqlrow = array(
        "board_id" => $sqldata['board_id'],
        "cid"      => $sqldata['cid'],
        "contents" => $sqldata['contents'],
      );
      \Frody\Util\MultiFileUpload::swfCleanDir(_UP_PATH_TMP_);
      return $this->setContentsParts($sqlrow);
    }
  }

  function getFileUrl( $cid, $aid ){
    $file_url = _SITE_INC_URL_."/getFile.php?gubun=board&amp;board_id={$this->board_info['board_id']}&amp;cid={$cid}&aid={$aid}";
    return $file_url;
  }

  function getFileDir( $cid, $aid ){
    $upload_board_dir = _UP_PATH_."/board";
    if( !file_exists($upload_board_dir) ){
      mkdir($upload_board_dir);
    }
    $target_dir = $upload_board_dir."/{$this->board_info['board_id']}";
    if( !file_exists($target_dir) ){
      mkdir($target_dir);
    }
    $file_dir = "{$target_dir}/{$cid}_{$aid}_".strrev(md5("{$cid}_{$aid}")).".data";
    return $file_dir;
  }

  function delFiles( $mode, $sqldata="" ){
    $target_dir = _UP_PATH_."/board/{$this->board_info['board_id']}";

    $where = new DB_where("and");
    $where->add("board_id = ?", $this->board_info['board_id']);
    if( $mode == "contents" ){
      $where->add("cid = ?", $sqldata['cid']);
    }
    if( $mode == "file" ){
      if( is_array($sqldata['aid']) ){
        $subwhere = $where->sub_where("or");
        foreach( (array)$sqldata['aid'] as $v ){
          $subwhere->add("aid = ?", $v);
        }
      }else{
        $where->add("aid = ?", $sqldata['aid']);
      }
    }

    $wqry = $where->get_where();
    $whereqry = $wqry['qry'];
    $whererow = $wqry['val'];

    $row = $this->DB->query("select * from ". TB_board_attach ." where {$whereqry}",$whererow);
    foreach( $row as $val ){
      $tgt_file = "{$target_dir}/{$val['cid']}_{$val['aid']}_".strrev(md5("{$val['cid']}_{$val['aid']}")).".data";
      @unlink($tgt_file);
    }
    return $this->DB->delete(TB_board_attach, $whereqry, $whererow);
  }

  function setCommonState( $sqldata ){
    if( $sqldata['oid'] ){
      return $this->setOpinionState( $sqldata );
    }else if( $sqldata['cid'] ){
      return $this->setContentsState( $sqldata );
    }
    return 0;
  }

  function addCommonGood( $sqldata ){
    if( $sqldata['oid'] ){
      return $this->addOpinionGood( $sqldata['cid'], $sqldata['oid'] );
    }else if( $sqldata['cid'] ){
      return $this->addContentsGood( $sqldata['cid'] );
    }
    return 0;
  }

  function addCommonNogood( $sqldata ){
    if( $sqldata['oid'] ){
      return $this->addOpinionNogood( $sqldata['cid'], $sqldata['oid'] );
    }else if( $sqldata['cid'] ){
      return $this->addContentsNogood( $sqldata['cid'] );
    }
    return 0;
  }

  function setContentsParts( $sqldata ){
    $cid = $sqldata['cid'];
    unset($sqldata['cid']);

    $where = new DB_where('and');
    if( !$this->table_mode ){
      $where->add("board_id = ?", $this->board_info['board_id']);
    }
    $where->add('cid = ?', $cid);

    $wqry = $where->get_where();
    $whereqry = $wqry['qry'];
    $whererow = $wqry['val'];

    return $this->DB->update( TB_board_contents, $sqldata, $whereqry, $whererow);
  }

  function setContentsState( $sqldata ){
    $sql_row = array(
      "cid"   => $sqldata['cid'],
      "state" => $sqldata['state'],
    );
    return $this->setContentsParts($sql_row);
  }

  function addContentsViews( $cid ){ //조회수 증가 및 세션 생성
    if( !$_SESSION['board_read_'.$this->board_info['board_id']."_".$cid] ){
      $sql_row = array(
        "cid"   => $cid,
        "views" => $this->DB->sqleval("views + 1"),
      );

      $rst = $this->setContentsParts($sql_row);;
      if( $rst ){
        $this->setSessRead($cid);
        return $rst;
      }
    }
    return 0;
  }

  function addContentsGood( $cid ){
    $sql_row = array(
      "cid"   => $cid,
      "good" => $this->DB->sqleval("good + 1"),
    );
    return $this->setContentsParts($sql_row);
  }

  function addContentsNogood( $cid ){
    $sql_row = array(
      "cid"   => $cid,
      "nogood" => $this->DB->sqleval("nogood + 1"),
    );
    return $this->setContentsParts($sql_row);
  }

  function getPrevContents( $cid, $num=1 ){
    $where = new DB_where('and');
    $where->add("board_id = ?", $this->board_info['board_id']);
    $where->add('state = ?', 1);
    $where->add('cid < ?', $cid);

    $wqry = $where->get_where();
    $whereqry = $wqry['qry'];
    $whererow = $wqry['val'];

    //$sql = "select * from ". TB_board_contents ." where {$whereqry} order by nid desc ". $this->DB->_limit(0,$num);
    $sql = $this->DB->addLimit("select * from ". TB_board_contents ." where {$whereqry}","nid desc",0,$num);
    $row = $this->DB->query($sql, $whererow);
    return $row;
  }

  function getNextContents( $cid, $num=1 ){
    $where = new DB_where('and');
    $where->add("board_id = ?", $this->board_info['board_id']);
    $where->add('state = ?', 1);
    $where->add('cid > ?', $cid);

    $wqry = $where->get_where();
    $whereqry = $wqry['qry'];
    $whererow = $wqry['val'];

    //$sql = "select * from (select * from ". TB_board_contents ." where {$whereqry} order by nid asc ". $this->DB->_limit(0,$num) .") as T order by nid desc";
    $sql = "select * from (". $this->DB->query("select * from ". TB_board_contents ." where {$whereqry}","nid asc",0,$num) .") as T order by nid desc";
    $row = $this->DB->query($sql, $whererow);
    return $row;
  }

  function getNearContents( $cid, $num){
    $row1 = $this->getNext( $cid, $num );
    $row2 = $this->getPrev( $cid, $num );

    return array_merge($row1, $row2);
  }

  function setOpinionState( $sqldata ){
    $sql_row = array(
      "state" => $sqldata['state']
    );
    $where = new DB_where('and');
    $where->add("board_id = ?", $this->board_info['board_id']);
    $where->add('cid = ?', $sqldata['cid']);
    $where->add('oid = ?', $sqldata['oid']);

    $wqry = $where->get_where();
    $whereqry = $wqry['qry'];
    $whererow = $wqry['val'];

    return $this->DB->update( TB_board_opinion, $sql_row, $whereqry, $whererow);
  }

  function addOpinionGood( $cid, $oid ){
    $sql_row = array(
      "good" => $this->DB->sqleval("good + 1")
    );
    $where = new DB_where('and');
    $where->add("board_id = ?", $this->board_info['board_id']);
    $where->add('cid = ?', $cid);
    $where->add('oid = ?', $oid);

    $wqry = $where->get_where();
    $whereqry = $wqry['qry'];
    $whererow = $wqry['val'];

    return $this->DB->update( TB_board_opinion, $sql_row, $whereqry, $whererow );
  }

  function addOpinionNogood( $cid, $oid ){
    $sql_row = array(
      "nogood" => $this->DB->sqleval("nogood + 1")
    );
    $where = new DB_where('and');
    $where->add("board_id = ?", $this->board_info['board_id']);
    $where->add('cid = ?', $cid);
    $where->add('oid = ?', $oid);

    $wqry = $where->get_where();
    $whereqry = $wqry['qry'];
    $whererow = $wqry['val'];

    return $this->DB->update( TB_board_opinion, $sql_row, $whereqry, $whererow );
  }

  function isMem(){ //회원권한이 있는지 확인
    return ($this->isMember() || $this->isBoardAdmin() || $this->isAdmin());
  }

  function isAdminAuth(){ //관리자권한이 있는지 확인
    return ($this->isBoardAdmin() || $this->isAdmin());
  }

  function useMemOnly($mode){ //회원전용체크. 권한이 있는 경우 1 리턴
    $mode = "{$mode}_level";
    if( !$this->board_info[$mode] || $this->isMem() ){
      return 1;
    }
    return 0;
  }

  function useAdminOnly($mode){ //관리자전용체크. 권한이 있는 경우 1 리턴
    $mode = "{$mode}_level";
    if( !$this->board_info[$mode] || $this->isAdminAuth() ){
      return 1;
    }
    return 0;
  }

  function chkUseOnly($mode){ //게시판 사용권한 있는지 체크.
    switch( $this->board_info["{$mode}_level"] ){
      case "M":
        return $this->useMemOnly($mode);
      case "A":
        return $this->useAdminOnly($mode);
    }
    return 1;
  }

  function isBoardAdmin(){ //게시판 관리자 인지 체크
    if( $this->board_info['board_admin'] && $this->board_info['board_admin'] == $GLOBALS['_Umem']['member_id'] ){
      return 1;
    }
    return 0;
  }

  function chkPasswd( $cid, $passwd ){ //게시물 비밀번호 체크
    $crow = $this->getContents($cid);
    if( $this->isBoardAdmin() || $this->isAdmin() || $crow['passwd'] && $this->lcrypt->pw_match( $passwd, $crow['passwd'] ) ){
      $this->setSessSecret($cid); //세션생성
      return 1;
    }
    return 0;
  }

  function chkOpinionPasswd( $cid, $oid, $passwd ){ //의견결 비밀번호 체크
    $orow = $this->getOpinion($cid, $oid);
    if( $this->isBoardAdmin() || $this->isAdmin() || $orow['passwd'] && $this->lcrypt->pw_match( $passwd, $orow['passwd'] ) ){
      return 1;
    }
    return 0;
  }

  function chkOpinionAdmin( $cid, $oid ){ //의견글 관리권한 체크
    $orow = $this->getOpinion($cid, $oid);
    if( $this->isBoardAdmin() || $this->isAdmin() || $orow['member_id'] === $GLOBALS['_Umem']['member_id'] ){
      return 1;
    }
    return 0;
  }

  function chkSecretAuth($crow){ //게시물 비밀번호 통과 권한이 있는지 체크 (소유자 포함)
    if( !$crow  ) return 0;

    if( is_numeric($crow) ){
      $crow = $this->getContents($crow);
    }else if( is_object($crow) ){
      $crow = (Array)$crow;
    }

    if( $_SESSION['board_secret_'.$this->board_info['board_id']."_".$crow['cid']] || $this->isAdminAuth() || $crow['member_id'] && $crow['member_id'] == $GLOBALS['_Umem']['member_id'] ){
      return 1;
    }
    return 0;
  }

  function setSessRead( $cid ){ //게시물 조회 체크 세션
    $_SESSION['board_read_'.$this->board_info['board_id']."_".$cid] = 1;
  }

  function setSessSecret( $cid ){ //게시물 비밀번호 체크 세션
    $_SESSION['board_secret_'.$this->board_info['board_id']."_".$cid] = 1;
  }

  function chkHasImageFile( $sqldata ){
    if( $sqldata['ATTFILES'] ){
      $_SFILES = \Frody\Util\MultiFileUpload::swfFormFileInfo($sqldata['ATTFILES'], _UP_PATH_TMP_, "N");
      $rst = 1;
      for( $a = 0 ; $a<@count($_SFILES) ; $a++ ){
        if( preg_match("/(\.|\/)(gif|jpe?g|png|svg)$/i", $_SFILES[$a]['name']) ){
          return 1;
        }
      }
    }
    return 0;
  }

  function chkHasFile( $sqldata ){
    if( $sqldata['ATTFILES'] ){
      $_SFILES = \Frody\Util\MultiFileUpload::swfFormFileInfo($sqldata['ATTFILES'], _UP_PATH_TMP_, "N");
      $rst = 1;
      for( $a = 0 ; $a<@count($_SFILES) ; $a++ ){
        if( !preg_match("/(\.|\/)(gif|jpe?g|png|svg)$/i", $_SFILES[$a]['name']) ){
          return 1;
        }
      }
    }
    return 0;
  }

  function isAdmin(){
    if( $GLOBALS['_Umem']['member_auth'] && array_key_exists($GLOBALS['_Umem']['member_auth'], $GLOBALS['_varsAuthAdmin']) ){
      return true;
    }
    return false;
  }

  function isMember(){
    if( $GLOBALS['_Umem']['member_id'] && $GLOBALS['_Umem']['member_status'] == 1 ){
      return true;
    }
    return false;
  }
}