<?php

/*
=====================================================================

  프로젝트 이름 : 피리 카페 심플

  만든사람 : 피리 PIREE ( tosports@naver.com )

  홈페이지 : https://piree.kr/nett_dev

  작성날짜 : 2024년 04월 14일 일요일 오후 18시 30분 / 맑음, 26.5, 건조주의보, 28, 9, 0%, 0%, 2.4ms / 양호, 33, 12, 0.005

  저 작 권 : Copyright ⓒ 2024 피리 piree.kr All right reserved
              그누보드 외에 추가된 소스는~
              만든사람의 허락없이 무단으로 사용할수 없습니다.
              사용하고자 할 경우 만든사람의 허락을 받아야 합니다.
              http://.piree.kr 에 문의해 주세요.

=====================================================================
 피리 카페 심플 > 프로그램 > 피리 카페 관리 > 내 카페 > 게시판 > 게시글 쓰기
=====================================================================

*/

  include_once('./_common.php');

  $board_cate_n_a = array();

  $count_write = 0;

  $count_comment = 0;

  include_once(G5_LIB_PATH.'/naver_syndi.lib.php' );

  include_once(G5_CAPTCHA_PATH.'/captcha.lib.php' );

  include_once( piree__path($piree_prog_a[770099]['num'], 'piree.cafe.board.lib.inc.php') );

  include_once( piree__path($piree_prog_a[770099]['num'], '_CAFE.INFO.CHECK.inc.php') );

  check_write_token($piree['cafe_board_code']);

  $uid = isset($_POST['uid']) ? preg_replace('/[^0-9]/', '', $_POST['uid']) : 0;

  $board_cate_n = isset($_POST['board_cate_n']) ? trim($_POST['board_cate_n']) : '';
  $board_cate_n = (int)$board_cate_n;

  $g5['title'] = '게시글 저장';

  $msg = array();

  IF ( !$board_cate_n )
  {

      $msg[] = '<strong>게시판 분류</strong>를 선택하세요.';
  }
  ELSE
  {

      IF ( !$board_cate_list_a[$board_cate_n]['board_cate_s'] || $board_cate_n != $board_cate_list_a[$board_cate_n]['bca_cate_n'] )
      {
          $msg[] = '게시판 분류를 올바르게 입력하세요.';
      }

  }

  $wr_subject = '';

  IF ( isset($_POST['wr_subject']) )
  {
    $wr_subject = substr(trim($_POST['wr_subject']),0,255);
    $wr_subject = preg_replace("#[\\\]+$#", "", $wr_subject);
  }

  IF ( $wr_subject == '' )
  {
    $msg[] = '<strong>제목</strong>을 입력하세요.';
  }

  $wr_content = '';

  IF ( isset($_POST['wr_content']) )
  {
    $wr_content = substr(trim($_POST['wr_content']),0,65536);
    $wr_content = preg_replace("#[\\\]+$#", "", $wr_content);
  }

  IF ( $wr_content == '' )
  {
    $msg[] = '<strong>내용</strong>을 입력하세요.';
  }

  $wr_link1 = '';

  IF ( isset($_POST['wr_link1']) )
  {
    $wr_link1 = substr($_POST['wr_link1'],0,1000);
    $wr_link1 = trim(strip_tags($wr_link1));
    $wr_link1 = preg_replace("#[\\\]+$#", "", $wr_link1);
  }

  $wr_link2 = '';

  IF ( isset($_POST['wr_link2']) )
  {
    $wr_link2 = substr($_POST['wr_link2'],0,1000);
    $wr_link2 = trim(strip_tags($wr_link2));
    $wr_link2 = preg_replace("#[\\\]+$#", "", $wr_link2);
  }

  $msg = implode('<br>', $msg);

  IF ( $msg)
  {
    alert($msg );
  }

  IF ( substr_count($wr_content, '&#') > 50 )
  {
    alert('내용에 올바르지 않은 코드가 다수 포함되어 있습니다.');
    exit;
  }

  $upload_max_filesize = ini_get('upload_max_filesize');

  IF ( empty($_POST) )
  {
    alert("파일 또는 글내용의 크기가 서버에서 설정한 값을 넘어 오류가 발생하였습니다.\\npost_max_size=". ini_get('post_max_size') ." , upload_max_filesize=". $upload_max_filesize ."\\n게시판관리자 또는 서버관리자에게 문의 바랍니다.");
  }

  $notice_array = explode(",", $board_cate_list_a[$board_cate_n]['bca_notice']);

  $wr_password = isset($_POST['wr_password']) ? $_POST['wr_password'] : '';

  $bf_content = isset($_POST['bf_content']) ? (array) $_POST['bf_content'] : array();

  $_POST['html'] = isset($_POST['html']) ? clean_xss_tags($_POST['html'], 1, 1) : '';

  $_POST['secret'] = isset($_POST['secret']) ? clean_xss_tags($_POST['secret'], 1, 1) : '';

  $_POST['mail'] = isset($_POST['mail']) ? clean_xss_tags($_POST['mail'], 1, 1) : '';

  IF ( $w == 'u' || $w == 'r' )
  {

    $wr = get_write($piree['cafe_article'], $wr_id);

    IF ( !$wr['wr_id'] )
    {
        alert("글이 존재하지 않습니다.\\n글이 삭제되었거나 이동하였을 수 있습니다.");
    }

  }

  IF ( !piree_cafe_auth_get() && !$board_cate_list_a[$board_cate_n]['bca_use_secret'] && (stripos($_POST['html'], 'secret') !== false || stripos($_POST['secret'], 'secret') !== false || stripos($_POST['mail'], 'secret') !== false) )
  {
    alert('비밀글을 사용하지 않는 게시판 이므로 비밀글로 등록할 수 없습니다.');
  }

  $secret = '';

  IF ( isset($_POST['secret']) && $_POST['secret'] )
  {

    IF ( preg_match('#secret#', strtolower($_POST['secret']), $matches) )
    {
        $secret = $matches[0];
    }

  }

  IF ( !piree_cafe_auth_get() && $board_cate_list_a[$board_cate_n]['bca_use_secret'] == 2 )
  {
    $secret = 'secret';
  }

  $html = '';

  IF ( isset($_POST['html']) && $_POST['html'] )
  {

    IF (preg_match('#html(1|2)#', strtolower($_POST['html']), $matches) )
    {
        $html = $matches[0];
    }

  }

  $mail = '';

  IF ( isset($_POST['mail']) && $_POST['mail'] )
  {

    IF (preg_match('#mail#', strtolower($_POST['mail']), $matches))
    {
        $mail = $matches[0];
    }

  }

  $notice = '';

  IF ( isset($_POST['notice']) && $_POST['notice'] )
  {
    $notice = $_POST['notice'];
  }

  FOR ( $loop_n=1; $loop_n<=10; $loop_n++ )
  {

    $var = "wr_". $loop_n;
    $$var = "";

    IF ( isset($_POST['wr_'. $loop_n]) && settype($_POST['wr_'. $loop_n], 'string') )
    {
        $$var = trim($_POST['wr_'. $loop_n]);
    }

  }

  @include_once($board_cate_list_a[$board_cate_n]['board_skin_p'] .'/write_update.head.skin.php' );

//('write_update_before', $board, $wr_id, $w, $qstr);
  run_event('cafe_board_write_update_before', $piree_cafe_n, $board_cate_n, $wr_id, $w, $qstr);

  $is_use_captcha = ((($board_cate_list_a[$board_cate_n]['bca_use_captcha'] && $w !== 'u') || $is_guest) && !piree_cafe_auth_get()) ? 1 : 0;

  IF ( $is_use_captcha && !chk_captcha() )
  {
    alert('자동등록방지 숫자가 틀렸습니다.');
  }

  SWITCH ( $w )
  {

    CASE 'u' :

      IF ( !piree_cafe_auth_get() && $notice )
      {
          alert('관리자만 공지할 수 있습니다.');
      }

      IF ( !piree_cafe_auth_get() && $board_cate_list_a[$board_cate_n]['bca_notice'] && in_array($wr['wr_id'], $notice_array) )
      {
          $notice = 1;
      }

// .00 : 글쓰기 권한과 수정은 별도로 처리되어야 함
      IF ( $member['mb_id'] && $wr['mb_id'] === $member['mb_id'] )
      {
          ;
      }
      ELSE IF ( $cafe_member_a['cafe_mem_level_n'] < $board_cate_list_a[$board_cate_n]['bca_write_level'] )
      {
          alert('글을 쓸 권한이 없습니다.');
      }
// .00 : 글쓰기 권한과 수정은 별도로 처리되어야 함

    BREAK;

    CASE 'r' :

      IF ( in_array((int)$wr_id, $notice_array) )
      {
          alert('공지에는 답변 할 수 없습니다.');
      }

      IF ( $cafe_member_a['cafe_mem_level_n'] < $board_cate_list_a[$board_cate_n]['bca_reply_level'] )
      {
          alert('글을 답변할 권한이 없습니다.');
      }

      $reply_array = &$wr;

      IF ( strlen($reply_array['wr_reply']) == 10 )
      {
          alert("더 이상 답변하실 수 없습니다.\\n답변은 10단계 까지만 가능합니다.");
      }

      $reply_len = strlen($reply_array['wr_reply']) + 1;

      IF ( $board_cate_list_a[$board_cate_n]['bca_reply_order'] )
      {

          $begin_reply_char = 'A';
          $end_reply_char = 'Z';
          $reply_number = +1;

          $sql_select  = "SELECT MAX(SUBSTRING(`wr_reply`, ". $reply_len .", 1)) AS `reply` FROM `". $piree['cafe_article'] ."` ";
          $sql_select .= "WHERE `wr_num` = '". $reply_array['wr_num'] ."' AND SUBSTRING(`wr_reply`, ". $reply_len .", 1) <> '' ";

      }
      ELSE
      {

          $begin_reply_char = 'Z';
          $end_reply_char = 'A';
          $reply_number = -1;

          $sql_select  = "SELECT MIN(SUBSTRING(`wr_reply`, ". $reply_len .", 1)) AS `reply` FROM `". $piree['cafe_article'] ."` ";
          $sql_select .= "WHERE `wr_num` = '". $reply_array['wr_num'] ."' AND SUBSTRING(`wr_reply`, ". $reply_len .", 1) <> '' ";

      }

      IF ( $reply_array['wr_reply'])
      {
          $sql_select .= " AND `wr_reply` LIKE '". $reply_array['wr_reply'] ."%'";
      }

      $row = sql_fetch($sql_select);

      IF ( !$row['reply'] )
      {

          $reply_char = $begin_reply_char;

      }
      ELSE IF ( $row['reply'] == $end_reply_char )
      {


          alert("더 이상 답변하실 수 없습니다.\\n답변은 26개 까지만 가능합니다.");

      }
      ELSE
      {

          $reply_char = chr(ord($row['reply']) + $reply_number);

      }

      $reply = $reply_array['wr_reply'] . $reply_char;

      IF ( isset($_SESSION['ss_datetime']) )
      {

        IF ( $_SESSION['ss_datetime'] >= (G5_SERVER_TIME - $config['cf_delay_sec']) && !piree_cafe_auth_get() )
        {
            alert('너무 빠른 시간내에 게시물을 연속해서 올릴 수 없습니다.');
        }

      }

      set_session("ss_datetime", G5_SERVER_TIME);

    BREAK;

    DEFAULT :

      IF ( !piree_cafe_auth_get() && $notice )
      {
          alert('관리자만 공지할 수 있습니다.');
      }

      IF ( isset($_SESSION['ss_datetime']) )
      {

        IF ( $_SESSION['ss_datetime'] >= (G5_SERVER_TIME - $config['cf_delay_sec']) && !piree_cafe_auth_get() )
        {
            alert('너무 빠른 시간내에 게시물을 연속해서 올릴 수 없습니다.');
        }

      }

      set_session("ss_datetime", G5_SERVER_TIME);

    BREAK;

  }

  IF ( !isset($_POST['wr_subject']) || !trim($_POST['wr_subject']) )
  {
    alert('제목을 입력하여 주십시오.');
  }

  $wr_seo_title = exist_seo_title_recursive('bbs', generate_seo_title($wr_subject), $piree['cafe_article'], $wr_id);

  $options = array($html, $secret, $mail);

  $wr_option = implode(',', array_filter(array_map('trim', $options)));

  SWITCH ( $w )
  {

    CASE 'u' :

      IF ( get_session('ss_bo_table') != $_POST['bo_table'] || get_session('ss_wr_id') != $_POST['wr_id'] )
      {
        alert('올바른 방법으로 수정하여 주십시오.', go_piree_cafe_board('', $piree_cafe_n, $board_cate_n));
      }

      $return_url = go_piree_cafe_board('', $piree_cafe_n, $board_cate_n, $wr_id);

      IF ( piree_cafe_auth_get() )
      {

          ;

      }
      ELSE IF ( $member['mb_id'] )
      {

          IF ( $member['mb_id'] != $write['mb_id'])
          {
              alert('자신의 글이 아니므로 수정할 수 없습니다.', $return_url);
          }

      }
      ELSE
      {

          IF ( !$member['mb_id'] || $member['mb_id'] != $write['mb_id'] )
          {
              alert('로그인 후 수정하세요.', G5_BBS_URL.'/login.php?url='.urlencode($return_url));
          }

      }

      $sql_update  = "UPDATE `". $piree['cafe_article'] ."` SET ";

      IF ( $member['mb_id'] === $wr['mb_id'] )
      {

          $mb_id = $member['mb_id'];

          $wr_name = addslashes(clean_xss_tags($board_cate_list_a[$board_cate_n]['bca_use_name'] ? $member['mb_name'] : $member['mb_nick']));

          $wr_email = addslashes($member['mb_email']);

          $wr_homepage = addslashes(clean_xss_tags($member['mb_homepage']));

      }
      ELSE
      {

          $mb_id = $wr['mb_id'];

          IF ( isset($_POST['wr_name']) && $_POST['wr_name'] )
          {
              $wr_name = clean_xss_tags(trim($_POST['wr_name']));
          }
          ELSE
          {
              $wr_name = addslashes(clean_xss_tags($wr['wr_name']));
          }

          IF ( isset($_POST['wr_email']) && $_POST['wr_email'] )
          {
              $wr_email = get_email_address(trim($_POST['wr_email']));
          }
          ELSE
          {
              $wr_email = addslashes($wr['wr_email']);
          }

          IF ( isset($_POST['wr_homepage']) && $_POST['wr_homepage'] )
          {
              $wr_homepage = addslashes(clean_xss_tags($_POST['wr_homepage']));
          }
          ELSE
          {
              $wr_homepage = addslashes(clean_xss_tags($wr['wr_homepage']));
          }

      }

      $sql_select  = "SELECT COUNT(*) FROM `". $piree['cafe_article'] ."` ";
      $sql_select .= "WHERE `wr_parent` = '". $wr_id ."' AND `wr_is_comment` = '1'";
      $comment_t = (int)sql_efv($sql_select);

      $sql_password = $wr_password ? " , `wr_password` = '". get_encrypt_string($wr_password) ."' " : "";

      $sql_ip = '';

      IF ( !piree_cafe_auth_get() )
      {
          $sql_ip = " , `wr_ip` = '". $_SERVER['REMOTE_ADDR'] ."' ";
      }

      $sql_update  = "UPDATE `". $piree['cafe_article'] ."` SET ";
      $sql_update .= "`wr_comment`   = '". $comment_t ."', ";
      $sql_update .= "`ca_name`      = '". $ca_name ."', ";
      $sql_update .= "`wr_option`    = '". $wr_option ."', ";
      $sql_update .= "`wr_subject`   = '". $wr_subject ."', ";
      $sql_update .= "`wr_content`   = '". $wr_content ."', ";
      $sql_update .= "`wr_seo_title` = '". $wr_seo_title ."', ";
      $sql_update .= "`wr_link1`     = '". $wr_link1 ."', ";
      $sql_update .= "`wr_link2`     = '". $wr_link2 ."', ";
      $sql_update .= "`mb_id`        = '". $mb_id ."', ";
      $sql_update .= "`wr_name`      = '". $wr_name ."', ";
      $sql_update .= "`wr_email`     = '". $wr_email ."', ";
      $sql_update .= "`wr_homepage`  = '". $wr_homepage ."', ";
      $sql_update .= "`wr_1`         = '". $wr_1 ."', ";
      $sql_update .= "`wr_2`         = '". $wr_2 ."', ";
      $sql_update .= "`wr_3`         = '". $wr_3 ."', ";
      $sql_update .= "`wr_4`         = '". $wr_4 ."', ";
      $sql_update .= "`wr_5`         = '". $wr_5 ."', ";
      $sql_update .= "`wr_6`         = '". $wr_6 ."', ";
      $sql_update .= "`wr_7`         = '". $wr_7 ."', ";
      $sql_update .= "`wr_8`         = '". $wr_8 ."', ";
      $sql_update .= "`wr_9`         = '". $wr_9 ."', ";
      $sql_update .= "`wr_10`        = '". $$wr_10 ."' ";
      $sql_update .= $sql_ip;
      $sql_update .= $sql_password;

      $sql_update .= ", ";
      $sql_update .= "`wr_pi_piree_cafe_n`  = '". $piree_cafe_n ."', ";
      $sql_update .= "`wr_pi_board_cate_n`  = '". $board_cate_n ."', ";
      $sql_update .= "`wr_pi_piree_cafe_s`  = '". $piree_cafe_name_s ."', ";
      $sql_update .= "`wr_pi_board_cate_s`  = '". $board_cate_list_a[$board_cate_n]['board_cate_path_s'] ."' ";

      $sql_update .= "WHERE `wr_id` = '". $wr['wr_id'] ."'";

      IF ( !sql_query($sql_update) )
      {

        $sql_alter = "ALTER TABLE `". $piree['cafe_article'] ."` ADD `wr_pi_piree_cafe_n` INT UNSIGNED NOT NULL DEFAULT '0'";
        sql_query($sql_alter, false);

        $sql_alter = "ALTER TABLE `". $piree['cafe_article'] ."` ADD `wr_pi_board_cate_n` INT UNSIGNED NOT NULL DEFAULT '0'";
        sql_query($sql_alter, false);

        $sql_alter = "ALTER TABLE `". $piree['cafe_article'] ."` ADD `wr_pi_piree_cafe_s` VARCHAR(255) NOT NULL DEFAULT ''";
        sql_query($sql_alter, false);

        $sql_alter = "ALTER TABLE `". $piree['cafe_article'] ."` ADD `wr_pi_board_cate_s` VARCHAR(255) NOT NULL DEFAULT ''";
        sql_query($sql_alter, false);

        IF ( !sql_query($sql_update) )
        {

          $msg_s = "게시글을 수정하지 못했습니다.";
          alert($msg_s);
        }

      }

      $bca_notice = board_notice($board_cate_list_a[$board_cate_n]['bca_notice'], $wr_id, $notice);

      $sql_update  = "UPDATE `". $piree['cafe_board'] ."` SET ";
      $sql_update .= "`bca_notice` = '". $bca_notice ."' ";
      $sql_update .= "WHERE `bca_cafe_n` = '". $piree_cafe_n ."' AND `bca_cate_n` = '". $board_cate_n ."'";
      sql_query($sql_update);

      $write = get_write($piree['cafe_article'], $wr['wr_id'], false);

    BREAK;

    DEFAULT :

      IF ( $member['mb_id'] )
      {

          $mb_id = $member['mb_id'];

          $wr_name = addslashes(clean_xss_tags($board_cate_list_a[$board_cate_n]['bca_use_name'] ? $member['mb_name'] : $member['mb_nick']));

          $wr_password = '';

          $wr_email = addslashes($member['mb_email']);

          $wr_homepage = addslashes(clean_xss_tags($member['mb_homepage']));

      }
      ELSE
      {

          $mb_id = '';

// 이름이 누락되는 경우가 있음
          $wr_name = clean_xss_tags(trim($_POST['wr_name']));

          IF ( !$wr_name )
          {
              alert('이름은 필히 입력하셔야 합니다.');
          }

          $wr_password = get_encrypt_string($wr_password);

          $wr_email = get_email_address(trim($_POST['wr_email']));

          $wr_homepage = clean_xss_tags($wr_homepage);

      }

      IF ( $w == 'r' )
      {

          IF ( $secret )
          {
              $wr_password = $wr['wr_password'];
          }

          $wr_id = $wr_id . $reply;

          $wr_num = $write['wr_num'];

          $wr_reply = $reply;

      }
      ELSE
      {

          $wr_num = get_next_num($piree['cafe_article']);

          $wr_reply = '';

      }

      $sql_insert  = "INSERT INTO `". $piree['cafe_article'] ."` SET ";
      $sql_insert .= "`wr_num`        = '". $wr_num ."', ";
      $sql_insert .= "`wr_reply`      = '". $wr_reply ."', ";
      $sql_insert .= "`wr_comment`    = '0', ";
      $sql_insert .= "`ca_name`       = '". $ca_name ."', ";
      $sql_insert .= "`wr_option`     = '". $wr_option ."', ";
      $sql_insert .= "`wr_subject`    = '". $wr_subject ."', ";
      $sql_insert .= "`wr_content`    = '". $wr_content ."', ";
      $sql_insert .= "`wr_seo_title`  = '". $wr_seo_title ."', ";
      $sql_insert .= "`wr_link1`      = '". $wr_link1 ."', ";
      $sql_insert .= "`wr_link2`      = '". $wr_link2 ."', ";
      $sql_insert .= "`wr_link1_hit`  = '0', ";
      $sql_insert .= "`wr_link2_hit`  = '0', ";
      $sql_insert .= "`wr_hit`        = '0', ";
      $sql_insert .= "`wr_good`       = '0', ";
      $sql_insert .= "`wr_nogood`     = '0', ";
      $sql_insert .= "`mb_id`         = '". $member['mb_id'] ."', ";
      $sql_insert .= "`wr_password`   = '". $wr_password ."', ";
      $sql_insert .= "`wr_name`       = '". $wr_name ."', ";
      $sql_insert .= "`wr_email`      = '". $wr_email ."', ";
      $sql_insert .= "`wr_homepage`   = '". $wr_homepage ."', ";
      $sql_insert .= "`wr_datetime`   = '". G5_TIME_YMDHIS ."', ";
      $sql_insert .= "`wr_last`       = '". G5_TIME_YMDHIS ."', ";
      $sql_insert .= "`wr_ip`         = '". $_SERVER['REMOTE_ADDR'] ."', ";
      $sql_insert .= "`wr_1`          = '". $wr_1 ."', ";
      $sql_insert .= "`wr_2`          = '". $wr_2 ."', ";
      $sql_insert .= "`wr_3`          = '". $wr_3 ."', ";
      $sql_insert .= "`wr_4`          = '". $wr_4 ."', ";
      $sql_insert .= "`wr_5`          = '". $wr_5 ."', ";
      $sql_insert .= "`wr_6`          = '". $wr_6 ."', ";
      $sql_insert .= "`wr_7`          = '". $wr_7 ."', ";
      $sql_insert .= "`wr_8`          = '". $wr_8 ."', ";
      $sql_insert .= "`wr_9`          = '". $wr_9 ."', ";
      $sql_insert .= "`wr_10`         = '". $wr_10 ."'";

      $sql_insert .= ", ";
      $sql_insert .= "`wr_pi_piree_cafe_n`  = '". $piree_cafe_n ."', ";
      $sql_insert .= "`wr_pi_board_cate_n`  = '". $board_cate_n ."', ";
      $sql_insert .= "`wr_pi_piree_cafe_s`  = '". $piree_cafe_name_s ."', ";
      $sql_insert .= "`wr_pi_board_cate_s`  = '". $board_cate_list_a[$board_cate_n]['board_cate_path_s'] ."'";

      IF ( !sql_query($sql_insert) )
      {

        $sql_alter = "ALTER TABLE `". $piree['cafe_article'] ."` ADD `wr_pi_piree_cafe_n` INT UNSIGNED NOT NULL DEFAULT '0'";
        sql_query($sql_alter, false);

        $sql_alter = "ALTER TABLE `". $piree['cafe_article'] ."` ADD `wr_pi_board_cate_n` INT UNSIGNED NOT NULL DEFAULT '0'";
        sql_query($sql_alter, false);

        $sql_alter = "ALTER TABLE `". $piree['cafe_article'] ."` ADD `wr_pi_piree_cafe_s` VARCHAR(255) NOT NULL DEFAULT ''";
        sql_query($sql_alter, false);

        $sql_alter = "ALTER TABLE `". $piree['cafe_article'] ."` ADD `wr_pi_board_cate_s` VARCHAR(255) NOT NULL DEFAULT ''";
        sql_query($sql_alter, false);

        IF ( !sql_query($sql_insert) )
        {

          $msg_s = "게시글을 등록하지 못했습니다.";
          alert($msg_s);
        }

      }

      $wr_id = sql_insert_id();

      $count_write++;

      $board_cate_n_a[$board_cate_n] = $wr_id;

      $sql_update  = "UPDATE `". $piree['cafe_article'] ."` SET ";
      $sql_update .= "`wr_parent` = '". $wr_id ."' ";
      $sql_update .= "WHERE `wr_id` = '". $wr_id ."'";
      sql_query($sql_update);

      $sql_insert  = "INSERT INTO `". $g5['board_new_table'] ."` SET ";
      $sql_insert .= "`bo_table`    = '". $piree['cafe_board_code'] ."', ";
      $sql_insert .= "`wr_id`       = '". $wr_id ."', ";
      $sql_insert .= "`wr_parent`   = '". $wr_id ."', ";
      $sql_insert .= "`bn_datetime` = '". G5_TIME_YMDHIS ."', ";
      $sql_insert .= "`mb_id`       = '". $member['mb_id'] ."'";

      $sql_insert .= ", ";
      $sql_insert .= "`bn_pi_piree_cafe_n`  = '". $piree_cafe_n ."', ";
      $sql_insert .= "`bn_pi_board_cate_n`  = '". $board_cate_n ."', ";
      $sql_insert .= "`bn_pi_piree_cafe_s`  = '". $piree_cafe_name_s ."', ";
      $sql_insert .= "`bn_pi_board_cate_s`  = '". $board_cate_list_a[$board_cate_n]['board_cate_path_s'] ."'";

      IF ( !sql_query($sql_insert) )
      {

        $sql_alter = "ALTER TABLE `". $g5['board_new_table'] ."` ADD `bn_pi_piree_cafe_n` INT UNSIGNED NOT NULL DEFAULT '0'";
        sql_query($sql_alter, false);

        $sql_alter = "ALTER TABLE `". $g5['board_new_table'] ."` ADD `bn_pi_board_cate_n` INT UNSIGNED NOT NULL DEFAULT '0'";
        sql_query($sql_alter, false);

        $sql_alter = "ALTER TABLE `". $g5['board_new_table'] ."` ADD `bn_pi_piree_cafe_s` VARCHAR(255) NOT NULL DEFAULT ''";
        sql_query($sql_alter, false);

        $sql_alter = "ALTER TABLE `". $g5['board_new_table'] ."` ADD `bn_pi_board_cate_s` VARCHAR(255) NOT NULL DEFAULT ''";
        sql_query($sql_alter, false);

        IF ( !sql_query($sql_insert) )
        {

          $msg_s = "새글 테이블에 게시글을 등록하지 못했습니다.";
          alert($msg_s);
        }

      }

      IF ( $w == '' )
      {

          IF ( $notice )
          {

              $bca_notice = $wr_id . ($board_cate_list_a[$board_cate_n]['bca_notice'] ? ",".$board_cate_list_a[$board_cate_n]['bca_notice'] : '');

              $sql_update  = "UPDATE `". $piree['cafe_board'] ."` SET ";
              $sql_update .= "`bca_notice` = '". $bca_notice ."' ";
              $sql_update .= "WHERE `bca_table` = '". $piree['cafe_board_code'] ."'";
              sql_query($sql_update);

          }

          $point_trade_title_s = "[ ". $piree_cafe_name_s ." ] 카페의 [ ". $board_cate_list_a[$board_cate_n]['bca_cate_s'] ." ] 게시판에 ". $wr_id ." 글쓰기";

          insert_point($member['mb_id'], $board_cate_list_a[$board_cate_n]['bca_write_point'], $point_trade_title_s, $piree['cafe_board_code'], $wr_id, '쓰기');

      }
      ELSE
      {

          $point_trade_title_s = "[ ". $piree_cafe_name_s ." ] 카페의 [ ". $board_cate_list_a[$board_cate_n]['bca_cate_s'] ." ] 게시판에 ". $wr_id ." 글답변";

          insert_point($member['mb_id'], $board_cate_list_a[$board_cate_n]['bca_comment_point'], $point_trade_title_s, $piree['cafe_board_code'], $wr_id, '쓰기');

      }

    BREAK;

  }

  IF ( $board_cate_list_a[$board_cate_n]['bca_read_level'] < 2 && !$secret )
  {
      naver_syndi_ping($piree['cafe_board_code'], $wr_id);
  }

  $file_count = 0;

  $upload_count = (isset($_FILES['bf_file']['name']) && is_array($_FILES['bf_file']['name'])) ? count($_FILES['bf_file']['name']) : 0;

  FOR ( $i=0; $i<$upload_count; $i++ )
  {

    IF ( $_FILES['bf_file']['name'][$i] && is_uploaded_file($_FILES['bf_file']['tmp_name'][$i]) )
    {

        $file_count++;

    }

  }

  IF ( $w == 'u' )
  {

    $file = get_file($piree['cafe_board_code'], $wr_id);

    IF ( $file_count && (int)$file['count'] > $board_cate_list_a[$board_cate_n]['bca_upload_count'] )
    {
        alert('기존 파일을 삭제하신 후 첨부파일을 '.number_format($board_cate_list_a[$board_cate_n]['bca_upload_count']).'개 이하로 업로드 해주십시오.');
    }

  }
  ELSE
  {

    IF ( $file_count > $board_cate_list_a[$board_cate_n]['bca_upload_count'] )
    {
        alert('첨부파일을 '.number_format($board_cate_list_a[$board_cate_n]['bca_upload_count']).'개 이하로 업로드 해주십시오.');
    }

  }

  @mkdir(G5_DATA_PATH .'/file/'. $piree['cafe_board_code'], G5_DIR_PERMISSION);
  @chmod(G5_DATA_PATH .'/file/'. $piree['cafe_board_code'], G5_DIR_PERMISSION);

  $chars_array = array_merge(range(0,9), range('a','z'), range('A','Z'));

  $file_upload_msg = '';

  $upload = array();

  IF (isset($_FILES['bf_file']['name']) && is_array($_FILES['bf_file']['name']) )
  {

    FOR ( $loop_n=0; $loop_n<count($_FILES['bf_file']['name']); $loop_n++ )
    {

        $upload[$loop_n]['file']     = '';
        $upload[$loop_n]['source']   = '';
        $upload[$loop_n]['filesize'] = 0;
        $upload[$loop_n]['image']    = array();
        $upload[$loop_n]['image'][0] = 0;
        $upload[$loop_n]['image'][1] = 0;
        $upload[$loop_n]['image'][2] = 0;
        $upload[$loop_n]['fileurl'] = '';
        $upload[$loop_n]['thumburl'] = '';
        $upload[$loop_n]['storage'] = '';

        IF ( isset($_POST['bf_file_del'][$loop_n]) && $_POST['bf_file_del'][$loop_n] )
        {

            $upload[$loop_n]['del_check'] = true;

            $sql_select  = "SELECT * FROM `". $g5['board_file_table'] ."` ";
            $sql_select .= "WHERE `bca_table` = '". $piree['cafe_board_code'] ."' AND `wr_id` = '". $wr_id ."' AND `bf_no` = '". $loop_n ."'";
            $row = sql_fetch($sql_select);

            $delete_file = run_replace('delete_file_path', G5_DATA_PATH .'/file/'. $piree['cafe_board_code'] .'/'. str_replace('../', '', $row['bf_file']), $row);

            IF ( file_exists($delete_file) )
            {
                @unlink($delete_file);
            }

            IF ( preg_match("/\.({$config['cf_image_extension']})$/i", $row['bf_file']) )
            {
                delete_board_thumbnail($piree['cafe_board_code'], $row['bf_file']);
            }

        }
        ELSE
        {

            $upload[$loop_n]['del_check'] = false;

        }

        $tmp_file  = $_FILES['bf_file']['tmp_name'][$loop_n];
        $filesize  = $_FILES['bf_file']['size'][$loop_n];
        $filename  = $_FILES['bf_file']['name'][$loop_n];
        $filename  = get_safe_filename($filename);

        IF ( $filename )
        {

            IF ( $_FILES['bf_file']['error'][$loop_n] == 1 )
            {
                $file_upload_msg .= '\"'. $filename.'\" 파일의 용량이 서버에 설정('. $upload_max_filesize.')된 값보다 크므로 업로드 할 수 없습니다.\\n';
                continue;
            }
            ELSE IF ( $_FILES['bf_file']['error'][$loop_n] != 0 )
            {
                $file_upload_msg .= '\"'. $filename.'\" 파일이 정상적으로 업로드 되지 않았습니다.\\n';
                continue;
            }

        }

        IF ( is_uploaded_file($tmp_file) )
        {

            IF ( !piree_cafe_auth_get() && $filesize > $board_cate_list_a[$board_cate_n]['bca_upload_size'] )
            {
                $file_upload_msg .= '\"'. $filename.'\" 파일의 용량('.number_format($filesize).' 바이트)이 게시판에 설정('.number_format($board_cate_list_a[$board_cate_n]['bca_upload_size']).' 바이트)된 값보다 크므로 업로드 하지 않습니다.\\n';
                continue;
            }

// 파일에 악성코드를 심어 업로드 하는 경우를 방지
// 않는다.
//-------------------------------------------------------

            $timg = @getimagesize($tmp_file);

            IF ( preg_match("/\.({$config['cf_image_extension']})$/i", $filename) ||preg_match("/\.({$config['cf_flash_extension']})$/i", $filename)  )
            {

                IF ( $timg['2'] < 1 || $timg['2'] > 18 )
                {
                    continue;
                }

            }

            $upload[$loop_n]['image'] = $timg;

//.00.11 - 글답변에서 파일 업로드시 원글의 파일이 삭제되는 오류를 수정
            IF ( $w == 'u' )
            {

                $sql_select  = "SELECT * FROM `". $g5['board_file_table'] ."` ";
                $sql_select .= "WHERE `bca_table` = '". $piree['cafe_board_code'] ."' AND `wr_id` = '". $wr_id ."' AND `bf_no` = '". $i ."'";
                $row = sql_fetch($sql_select);

                IF ( isset($row['bf_file']) && $row['bf_file'] )
                {

                    $delete_file = run_replace('delete_file_path', G5_DATA_PATH.'/file/'. $piree['cafe_board_code'] .'/'.str_replace('../', '', $row['bf_file']), $row);

                    IF ( file_exists($delete_file) )
                    {
                        @unlink(G5_DATA_PATH.'/file/'. $piree['cafe_board_code'] .'/'. $row['bf_file']);
                    }

                    IF (preg_match("/\.({$config['cf_image_extension']})$/i", $row['bf_file']) )
                    {
                        delete_board_thumbnail($piree['cafe_board_code'], $row['bf_file']);
                    }

                }

            }

            $upload[$loop_n]['source'] = $filename;
            $upload[$loop_n]['filesize'] = $filesize;

//-x_를_붙여서__웹경로를_알더라도__실행을__하지_못하도록_함
            $filename = preg_replace("/\.(php|pht|phtm|htm|cgi|pl|exe|jsp|asp|inc|phar)/i", "$0-x", $filename);

            shuffle($chars_array);

            $shuffle = implode('', $chars_array);

//._(길상여의_님_090925)
            $upload[$loop_n]['file'] = md5(sha1($_SERVER['REMOTE_ADDR'])).'_'.substr($shuffle,0,8).'_'.replace_filename($filename);

            $dest_file = G5_DATA_PATH.'/file/'. $piree['cafe_board_code'] .'/'. $upload[$loop_n]['file'];

            $error_code = move_uploaded_file($tmp_file, $dest_file) or die($_FILES['bf_file']['error'][$loop_n]);

            chmod($dest_file, G5_FILE_PERMISSION);

            $dest_file = run_replace('write_update_upload_file', $dest_file, $board, $wr_id, $w);
            $upload[$loop_n] = run_replace('write_update_upload_array', $upload[$loop_n], $dest_file, $board, $wr_id, $w);

        }

    }

  }

// 저장하는 이유는 $wr_id 값을 저장해야 하기 때문입니다.
  FOR ( $loop_n=0; $loop_n<count($upload); $loop_n++ )
  {

    $upload[$loop_n]['source'] = sql_real_escape_string($upload[$loop_n]['source']);
    $bf_content[$loop_n]       = isset($bf_content[$loop_n])         ? sql_real_escape_string($bf_content[$loop_n]) : '';
    $bf_width                  = isset($upload[$loop_n]['image'][0]) ? (int) $upload[$loop_n]['image'][0]           : 0;
    $bf_height                 = isset($upload[$loop_n]['image'][1]) ? (int) $upload[$loop_n]['image'][1]           : 0;
    $bf_type                   = isset($upload[$loop_n]['image'][2]) ? (int) $upload[$loop_n]['image'][2]           : 0;

    IF ( $upload[$loop_n]['source'] )
    {

        $sql_select  = "SELECT COUNT(*) FROM `". $g5['board_file_table'] ."` ";
        $sql_select .= "WHERE `bca_table` = '". $piree['cafe_board_code'] ."' and wr_id = '". $wr_id ."' and bf_no = '". $loop_n ."'";
        $exist_t = sql_efv($sql_select);

        IF ( $exist_t > 0 )
        {

//.
            IF ( $upload[$loop_n]['del_check'] || $upload[$loop_n]['file'])
            {

                $sql_update  = "UPDATE `". $g5['board_file_table'] ."` SET ";
                $sql_update .= "`bf_source`          = '". $upload[$loop_n]['source'] ."', ";
                $sql_update .= "`bf_file`            = '". $upload[$loop_n]['file'] ."', ";
                $sql_update .= "`bf_content`         = '". $bf_content[$loop_n] ."', ";
                $sql_update .= "`bf_fileurl`         = '". $upload[$loop_n]['fileurl'] ."', ";
                $sql_update .= "`bf_thumburl`        = '". $upload[$loop_n]['thumburl'] ."', ";
                $sql_update .= "`bf_storage`         = '". $upload[$loop_n]['storage'] ."', ";
                $sql_update .= "`bf_filesize`        = '". (int)$upload[$loop_n]['filesize'] ."', ";
                $sql_update .= "`bf_width`           = '". $bf_width ."', ";
                $sql_update .= "`bf_height`          = '". $bf_height ."', ";
                $sql_update .= "`bf_type`            = '". $bf_type ."', ";
                $sql_update .= "`bf_datetime`        = '". G5_TIME_YMDHIS ."', ";
                $sql_update .= "`bf_pi_piree_cafe_n` = '". $piree_cafe_n ."', ";
                $sql_update .= "`bf_pi_board_cate_n` = '". $board_cate_n ."', ";
                $sql_update .= "`bf_pi_piree_cafe_s` = '". addslashes($piree_cafe_name_s) ."', ";
                $sql_update .= "`bf_pi_board_cate_s` = '". addslashes($board_cate_list_a[$board_cate_n]['board_cate_path_s']) ."' ";
                $sql_update .= "WHERE bca_table` = '". $piree['cafe_board_code'] ."' AND wr_id` = '". $wr_id ."' AND bf_no` = '". $loop_n ."'";

                sql_query($sql_update);

            }
            ELSE
            {

                $sql_update  = "UPDATE `". $g5['board_file_table'] ."` SET ";
                $sql_update .= "`bf_content` = '". $bf_content[$loop_n] ."' ";
                $sql_update .= "WHERE `bca_table` = '". $piree['cafe_board_code'] ."' AND `wr_id` = '". $wr_id ."' AND `bf_no` = '". $loop_n ."'";

                sql_query($sql_update);

            }

        }
        ELSE
        {

            $sql_insert  = "INSERT INTO `". $g5['board_file_table'] ."` SET ";
            $sql_insert .= "`bo_table`           = '". $piree['cafe_board_code'] ."', ";
            $sql_insert .= "`wr_id`              = '". $wr_id ."', ";
            $sql_insert .= "`bf_no`              = '". $loop_n ."', ";
            $sql_insert .= "`bf_source`          = '". $upload[$loop_n]['source'] ."', ";
            $sql_insert .= "`bf_file`            = '". $upload[$loop_n]['file'] ."', ";
            $sql_insert .= "`bf_content`         = '". $bf_content[$loop_n] ."', ";
            $sql_insert .= "`bf_fileurl`         = '". $upload[$loop_n]['fileurl'] ."', ";
            $sql_insert .= "`bf_thumburl`        = '". $upload[$loop_n]['thumburl'] ."', ";
            $sql_insert .= "`bf_storage`         = '". $upload[$loop_n]['storage'] ."', ";
            $sql_insert .= "`bf_download`        = '0', ";
            $sql_insert .= "`bf_filesize`        = '". (int)$upload[$loop_n]['filesize'] ."', ";
            $sql_insert .= "`bf_width`           = '". $bf_width ."', ";
            $sql_insert .= "`bf_height`          = '". $bf_height ."', ";
            $sql_insert .= "`bf_type`            = '". $bf_type ."', ";
            $sql_insert .= "`bf_datetime`        = '". G5_TIME_YMDHIS ."', ";
            $sql_insert .= "`bf_pi_piree_cafe_n` = '". $piree_cafe_n ."', ";
            $sql_insert .= "`bf_pi_board_cate_n` = '". $board_cate_n ."', ";
            $sql_insert .= "`bf_pi_piree_cafe_s` = '". addslashes($piree_cafe_name_s) ."', ";
            $sql_insert .= "`bf_pi_board_cate_s` = '". addslashes($board_cate_list_a[$board_cate_n]['board_cate_path_s']) ."'";
            sql_query($sql_insert);

            run_event('write_update_file_insert', $piree['cafe_board_code'], $wr_id, $upload[$loop_n], $w);

        }

    }

  }

// 내용에서 가장 큰 번호를 얻어 거꾸로 확인해 가면서
// 없다면 테이블의 내용을 삭제합니다.
  $sql_select  = "SELECT MAX`(bf_no`) AS `max_bf_no` FROM `". $g5['board_file_table'] ."` ";
  $sql_select .= "WHERE `bca_table` = '". $piree['cafe_board_code'] ."' AND `wr_id` = '". $wr_id ."'";
  $row = sql_fetch($sql_select);

  FOR ( $loop_n=(int)$row['max_bf_no']; $loop_n>=0; $loop_n-- )
  {

    $sql_select  = "SELECT `bf_file` FROM `". $g5['board_file_table'] ."` ";
    $sql_select .= "WHERE `bca_table` = '". $piree['cafe_board_code'] ."' AND `wr_id` = '". $wr_id ."' AND `bf_no` = '". $loop_n ."'";
    $row2 = sql_fetch($sql_select);

    IF ( isset($row2['bf_file']) && $row2['bf_file'] )
    {
      break;
    }

    $sql_delete  = "DELETE FROM `". $g5['board_file_table'] ."` ";
    $sql_delete .= "WHERE `bca_table` = '". $piree['cafe_board_code'] ."' AND `wr_id` = '". $wr_id ."' AND `bf_no` = '". $loop_n ."'";
    sql_query($sql_delete);

  }

  $sql_select  = "SELECT COUNT(*) FROM `". $g5['board_file_table'] ."` ";
  $sql_select .= "WHERE `bo_table` = '". $piree['cafe_board_code'] ."' AND `wr_id` = '". $wr_id ."'";
  $file_t = sql_efv($sql_select);

  $sql_update  = "UPDATE `". $piree['cafe_article'] ."` SET ";
  $sql_update .= "`wr_file` = '". $file_t ."' ";
  $sql_update .= "WHERE `wr_id` = '". $wr_id ."'";
  sql_query($sql_update);

  $sql_delete  = "DELETE FROM `". $g5['autosave_table'] ."` ";
  $sql_delete .= "WHERE `as_uid` = '". $uid ."'";
  sql_query($sql_delete);

  IF ( $secret )
  {
    set_session("ss_secret_". $piree['cafe_board_code'] ."_". $wr_num, TRUE);
  }

// 실행
  @include_once($board_cate_list_a[$board_cate_n]['board_skin_p'] .'/write_update.skin.php' );
  @include_once($board_cate_list_a[$board_cate_n]['board_skin_p'] .'/write_update.tail.skin.php' );

  delete_cache_latest($piree['cafe_board_code']);

  cafe_article_count_reload($piree_cafe_n, $member['mb_id'], $board_cate_n_a, 'plus', $count_write);

//$redirect_url = run_replace('write_update_move_url', short_url_clean(G5_HTTP_BBS_URL.'/piree.cafe.board.php?bca_table='. $piree['cafe_board_code'].'&amp;wr_id='. $wr_id.$qstr), $board, $wr_id, $w, $qstr, $file_upload_msg);
//$redirect_url = piree__url($piree_prog_a[770099]['num'], 'piree.cafe.board.php') .'?piree_cafe_n='. $piree_cafe_n .'&board_cate_n='. $board_cate_n .'&bo_table='. $piree['cafe_board_code'] .'&amp;wr_id='. $wr_id.$qstr;
  $redirect_url = go_piree_cafe_board('', $piree_cafe_n, $board_cate_n, $write['wr_parent'], $wr_id) .'&bo_table='. $piree['cafe_board_code'] .'&amp;'. $qstr;

  run_event('write_update_after', $board, $wr_id, $w, $qstr, $redirect_url);

  IF ( $file_upload_msg )
  {
    alert($file_upload_msg, $redirect_url);
  }
  ELSE
  {
    goto_url($redirect_url);
  }

?>