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

//ini_set("display_errors", 1); // 디버깅
define('RB_VER',  '1.1.5'); // 버전


/*********************************************/
$rb_config = sql_fetch (" select * from rb_config "); // 환경설정 테이블 조회
$rb_builder = sql_fetch (" select * from rb_builder "); // 빌더설정 테이블 조회

// 영카트 사용여부 (테이블 존재여부 조회)
$yc = sql_fetch(" select COUNT(*) AS cnt FROM information_schema.TABLES WHERE `TABLE_NAME` = '{$g5['g5_shop_item_table']}' ");
$is_yc = $yc['cnt'];

$rb_core['theme'] = $config['cf_theme']; // 테마
$rb_core['layout'] = $rb_config['co_layout']; // 레이아웃
$rb_core['color'] = 'co_'.$rb_config['co_color']; // 강조컬러
$rb_core['header'] = 'co_header'.$rb_config['co_header']; // 헤더스타일
$rb_core['font'] = $rb_config['co_font']; // 폰트스타일

if($rb_config['co_sub_width']) {
    $rb_core['sub_width'] = $rb_config['co_sub_width']; // 서브가로사이즈
} else { 
    $rb_core['sub_width'] = "1400"; // 설정없을때 기본
}

if($rb_config['co_main_width']) {
    $rb_core['main_width'] = $rb_config['co_main_width']; // 메인가로사이즈
} else { 
    $rb_core['main_width'] = "1400"; // 설정없을때 기본
}

if($rb_config['co_tb_width']) {
    $rb_core['tb_width'] = $rb_config['co_tb_width']; // 상단, 하단 가로사이즈
} else { 
    $rb_core['tb_width'] = "1400"; // 설정없을때 기본
}

// SEO설정
$sql_seo = " select * from rb_seo limit 1";
$seo = sql_fetch($sql_seo);


/*********************************************/


// SIR @트리플님 코드적용 // 출처 : https://sir.kr/g5_tip/21657
add_event('tail_sub', 'prism_tail_sub', G5_HOOK_DEFAULT_PRIORITY);
add_replace('html_purifier_result', 'prism_html_purifier_result', 10, 3);
function prism_script(){
    add_stylesheet('<link rel="stylesheet" href="'.G5_URL.'/rb/rb.mod/prism/prism.css">', -2);
    $sh = '<script src="'.G5_URL.'/rb/rb.mod/prism/prism.js"></script>'.PHP_EOL;
    $sh .= '<script>var is_SyntaxHighlighter = true;</script>';
    add_javascript($sh, 0);
}
function prism_tail_sub(){
    global $wr_id;
    if($_SERVER['SCRIPT_NAME'] != '/bbs/board.php' || !$wr_id) return;
    prism_script();
}
function PrismJS($m) {
    $str = isset($m[3]) ? $m[3] : '';
    if(!$str)
        return;
    $str = stripslashes($str);
    $str = preg_replace("/(<br>|<br \/>|<br\/>|<p>)/i", "\n", $str);
    $str = preg_replace("/(<div>|<\/div>|<\/p>)/i", "", $str);
    $str = str_replace(" ", " ", $str);
    $str = str_replace("/</", "<", $str);
    $str = str_replace("/[/", "&lsqb;", $str);
    $str = str_replace("/{/", "&lcub;", $str);
    if(!$str)
        return;
    //$brush = isset($m[2]) ? strtolower(trim($m[2])) : 'html';
    $brush = 'php';
    //prism_script();
    return '<div class="line-numbers"><pre><code class="language-'.$brush.'">'.$str.'</code></pre></div>'.PHP_EOL;
}
function prism_html_purifier_result($str){
    $content = preg_replace_callback("/(\[code\]|\[code=(.*)\])(.*)\[\/code\]/iUs", "PrismJS", $str); // PrismJS
    return $content;
}


// 새글에 NEW 아이콘
function get_new_ico($bo_table, $ca_name) {
    
    global $g5;


    $new_icon = '';
    $bbs = sql_fetch("select * from {$g5['board_table']} where bo_table = '{$bo_table}'");


    if($bbs && isset($bbs['bo_table'])) {
        $write_table = $g5['write_prefix'].$bbs['bo_table'];
        if(isset($ca_name) && !empty($ca_name)) {
            $time = sql_fetch("select * from {$write_table} where wr_is_comment = 0 and ca_name = '{$ca_name}' or wr_is_comment = 1 and ca_name = '{$ca_name}' order by wr_id desc limit 1");
        } else { 
            $time = sql_fetch("select * from {$write_table} where wr_is_comment = 0 or wr_is_comment = 1 order by wr_id desc limit 1");
        }
    }


    if (isset($bbs['bo_new']) && isset($time['wr_datetime']) && $time['wr_datetime'] >= date("Y-m-d H:i:s", G5_SERVER_TIME - ($bbs['bo_new'] * 3600))) {
        $new_icon = '<span class="gnb_new_ico">n</span>';
    }


    return $new_icon;
}

    
// 전체 URL (SEO)
function getCurrentUrl() {
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $host = $_SERVER['HTTP_HOST'];
    $requestUri = $_SERVER['REQUEST_URI'];
    
    return $protocol . $host . $requestUri;
}


// 안읽은 쪽지
if ($is_member) {
    if( isset($member['mb_memo_cnt']) ){
        $memo_not_read = $member['mb_memo_cnt'];
    } else {
        $memo_not_read = get_memo_not_read($member['mb_id']);
    }
}

// 날자계산
function passing_time($datetime) {
	$time_lag = time() - strtotime($datetime);
	
	if($time_lag < 60) {
		$posting_time = "방금";
	} else if($time_lag >= 60 and $time_lag < 3600) {
		$posting_time = floor($time_lag/60)."분 전";
	} else if($time_lag >= 3600 and $time_lag < 86400) {
		$posting_time = floor($time_lag/3600)."시간 전";
	} else if($time_lag >= 86400 and $time_lag < 2419200) {
		$posting_time = floor($time_lag/86400)."일 전";
	} else {
		$posting_time = date("Y.m.d", strtotime($datetime));
	} 
	
	return $posting_time;
}

// 날자계산2
function passing_time2($datetime) {
	$time_lag = time() - strtotime($datetime);
	
	if($time_lag < 60) {
		$posting_time = "방금<br>".date("Y.m.d", strtotime($datetime));
	} else if($time_lag >= 60 and $time_lag < 3600) {
		$posting_time = floor($time_lag/60)."분 전<br>".date("Y.m.d", strtotime($datetime));
	} else if($time_lag >= 3600 and $time_lag < 86400) {
		$posting_time = floor($time_lag/3600)."시간 전<br>".date("Y.m.d", strtotime($datetime));
	} else if($time_lag >= 86400 and $time_lag < 2419200) {
		$posting_time = floor($time_lag/86400)."일 전<br>".date("Y.m.d", strtotime($datetime));
	} else {
        $posting_time = "오래 전<br>".date("Y.m.d", strtotime($datetime));
	} 
	
	return $posting_time;
}

// 날자계산3
function passing_time3($datetime) {
	$time_lag = time() - strtotime($datetime);
	
	if($time_lag < 60) {
		$posting_time = "방금";
	} else if($time_lag >= 60 and $time_lag < 3600) {
		$posting_time = floor($time_lag/60)."분 전";
	} else if($time_lag >= 3600 and $time_lag < 86400) {
		$posting_time = floor($time_lag/3600)."시간 전";
	} else if($time_lag >= 86400 and $time_lag < 2419200) {
		$posting_time = floor($time_lag/86400)."일 전";
	} else {
        $posting_time = "오래 전";
	} 
	
	return $posting_time;
}

// 회원 게시물 갯수
function wr_cnt($mb_id, $type){
    global $g5;

    $wr_sum = 0;
    $sql = sql_query(" select bo_table from {$g5['board_table']} ");
    
    while($row = sql_fetch_array($sql)) {
        
        $write_table = $g5['write_prefix'] . $row['bo_table'];
        
        if($type == "w") {
            $sql2 = " select count(*) as cnt from {$write_table} where mb_id = '{$mb_id}' and wr_is_comment = 0 ";
        } else if ($type == "c") {
            $sql2 = " select count(*) as cnt from {$write_table} where mb_id = '{$mb_id}' and wr_is_comment = 1 ";
        }
        $wr = sql_fetch($sql2);
        $wr_sum += $wr['cnt'];
    }

    return $wr_sum;
}


// 생성된 게시판 목록조회
function rb_board_list($bo_tables) {
    global $g5;
    $sql = " select bo_table, bo_subject from {$g5['board_table']} group by bo_table order by bo_table asc"; 
    $result = sql_query($sql); 
    
    for ($i=0; $row=sql_fetch_array($result); $i++) 
    { 
        if($bo_tables == $row['bo_table']) {
            $str .= "<option value='$row[bo_table]' selected"; 
        } else { 
            $str .= "<option value='$row[bo_table]'"; 
        }
        
        $str .= ">$row[bo_subject] ($row[bo_table])</option>"; 
    } 
    return $str; 
}

// 카테고리 목록조회
function rb_sca_list($md_bo_table, $md_sca) {
    global $g5;
    
    $res_ca = sql_fetch (" select bo_category_list from {$g5['board_table']} where bo_table = '{$md_bo_table}' and bo_use_category = '1' "); 
    $cat = $res_ca['bo_category_list'];
    $cat_opt = explode("|", $cat);
    
    if($cat) {
        foreach($cat_opt as $option):
            if($md_sca == $option) {
                $str .= "<option value='$option' selected>$option</option>";
            } else { 
                $str .= "<option value='$option'>$option</option>";
            }
        endforeach;
    }

    return $str; 
}



// 생성된 배너 목록조회
function rb_banner_list($bn_id) {
    $sql = " select bn_id, bn_position, bn_alt from rb_banner where bn_position = '일반' order by bn_id asc"; 
    $result = sql_query($sql); 
    
    for ($i=0; $row=sql_fetch_array($result); $i++) 
    { 
        if($bn_id == $row['bn_id']) {
            $str .= "<option value='$row[bn_id]' selected"; 
        } else { 
            $str .= "<option value='$row[bn_id]'"; 
        }
        
        $str .= ">[$row[bn_position] / $row[bn_id]] $row[bn_alt]</option>"; 
    } 
    return $str; 
}

// 배너 ID가 있는지 검사
function rb_banner_select_is($bn_id) {
    $sql = sql_fetch ( " select COUNT(*) as cnt from rb_banner where bn_position = '일반' and bn_id = '{$bn_id}' " );
    if($sql['cnt'] > 0) {
        $str = "true";
    }
    
    return $str;
}


// 디렉토리 조회
function rb_dir_select($skin_gubun, $selected = '')
{
    global $config;

    $skins = array();


        $dirs = rb_skin_dir($skin_gubun, G5_THEME_PATH . '/');
        if (!empty($dirs)) {
            foreach ($dirs as $dir) {
                $skins[] = 'theme/' . $dir;
            }
        }


    $skins = array_merge($skins, rb_skin_dir($skin_gubun));


    for ($i = 0; $i < count($skins); $i++) {

        if (preg_match('#^theme/(.+)$#', $skins[$i], $match)) {
            $text = $match[1];
        }
        
        if(strpos($skins[$i], "theme/") !== false) {
            $str .= option_selected($text, $selected, $text);
        }
    }

    return $str;
}

// 스킨디렉토리에 지정한 스킨이 있는지 여부 검사
function rb_skin_select_is($skin_gubun, $selected = '')
{
    global $config;

    $skins = array();

    if (defined('G5_THEME_PATH') && $config['cf_theme']) {
        $dirs = rb_skin_dir($skin_gubun, G5_THEME_PATH . '/' . G5_SKIN_DIR);
        if (!empty($dirs)) {
            foreach ($dirs as $dir) {
                $skins[] = 'theme/' . $dir;
            }
        }
    }

    $skins = array_merge($skins, rb_skin_dir($skin_gubun));


    for ($i = 0; $i < count($skins); $i++) {
        if(strpos($skins[$i], "theme/") !== false) {
            if($skins[$i] == $selected) {
                $str = "true";
            }
        }
    }

    return $str;
}




// 스킨디렉토리 조회
function rb_skin_select($skin_gubun, $selected = '')
{
    global $config;

    $skins = array();

    if (defined('G5_THEME_PATH') && $config['cf_theme']) {
        $dirs = rb_skin_dir($skin_gubun, G5_THEME_PATH . '/' . G5_SKIN_DIR);
        if (!empty($dirs)) {
            foreach ($dirs as $dir) {
                $skins[] = 'theme/' . $dir;
            }
        }
    }

    $skins = array_merge($skins, rb_skin_dir($skin_gubun));


    for ($i = 0; $i < count($skins); $i++) {

        if (preg_match('#^theme/(.+)$#', $skins[$i], $match)) {
            $text = $match[1];
        }
        
        if(strpos($skins[$i], "theme/") !== false) {
            $str .= option_selected($skins[$i], $selected, $text);
        }
    }

    return $str;
}


                      
// 스킨디렉토리 조회 내부함수
function rb_skin_dir($skin, $skin_path = G5_SKIN_PATH)
{
    global $g5;

    $result_array = array();

    $dirname = $skin_path . '/' . $skin . '/';
    if (!is_dir($dirname)) {
        return array();
    }

    $handle = opendir($dirname);
    while ($file = readdir($handle)) {
        if ($file == '.' || $file == '..') {
            continue;
        }

        if (is_dir($dirname . $file)) {
            $result_array[] = $file;
        }
    }
    closedir($handle);
    sort($result_array);

    return $result_array;
}



// 위젯디렉토리에 지정한 위젯이 있는지 여부 검사
function rb_widget_select_is($skin_gubun, $selected = '')
{
    global $config;

    $skins = array();

        $dirs = rb_widget_dir($skin_gubun, G5_PATH . '/rb');
        if (!empty($dirs)) {
            foreach ($dirs as $dir) {
                $skins[] = 'rb.widget/' . $dir;
            }
        }


    $skins = array_merge($skins, rb_skin_dir($skin_gubun));


    for ($i = 0; $i < count($skins); $i++) {
        if(strpos($skins[$i], "rb.widget/") !== false) {
            if($skins[$i] == $selected) {
                $str = "true";
            }
        }
    }

    return $str;
}



// 위젯디렉토리 조회
function rb_widget_select($skin_gubun, $selected = '')
{
    global $config;

    $skins = array();


        $dirs = rb_widget_dir($skin_gubun, G5_PATH . '/rb');
        if (!empty($dirs)) {
            foreach ($dirs as $dir) {
                $skins[] = 'rb.widget/' . $dir;
            }
        }


    $skins = array_merge($skins, rb_widget_dir($skin_gubun));


    for ($i = 0; $i < count($skins); $i++) {

        if (preg_match('#^rb.widget/(.+)$#', $skins[$i], $match)) {
            $text = $match[1];
        }
        
        if(strpos($skins[$i], "rb.widget/") !== false) {
            $str .= option_selected($skins[$i], $selected, $text);
        }
    }

    return $str;
}

// 위젯디렉토리 조회 내부함수
function rb_widget_dir($skin, $skin_path = G5_SKIN_PATH)
{
    global $g5;

    $result_array = array();

    $dirname = $skin_path . '/' . $skin . '/';
    if (!is_dir($dirname)) {
        return array();
    }

    $handle = opendir($dirname);
    while ($file = readdir($handle)) {
        if ($file == '.' || $file == '..') {
            continue;
        }

        if (is_dir($dirname . $file)) {
            $result_array[] = $file;
        }
    }
    closedir($handle);
    sort($result_array);

    return $result_array;
}


// 쪽지발송 (쪽지타입, 제목, 링크주소, 수신ID, 발신ID)
function memo_auto_send($title, $link_url, $recv_id, $send_id) {
    
    global $g5;
    
    $me = sql_fetch(" select max(me_id) as new_me_id from {$g5['memo_table']} ");
    $me_id = $me['new_me_id'] + 1;
    
    $memo_cont = $title.'
'.$link_url;
    
    $recv = $recv_id; // 수신 아이디
    $send = $send_id; // 발신 아이디
    $memo = $memo_cont;

    $sql_msg = " insert into {$g5['memo_table']} set me_id = '{$me_id}', me_recv_mb_id = '{$recv}', me_send_mb_id = '{$send}', me_send_datetime =' ".G5_TIME_YMDHIS."', me_memo = '".$memo."', me_type = 'recv' ";
    sql_query($sql_msg);

    $sql_al = " update {$g5['member_table']} set mb_memo_call = 'system-msg', mb_memo_cnt = '".get_memo_not_read($recv)."' where mb_id = '{$recv}' ";
    sql_query($sql_al);
    
}


// 바이트 환산
function byteFormat($bytes, $unit = "", $decimals = 0) {
    $units = array('B' => 0, 'KB' => 1, 'MB' => 2, 'GB' => 3, 'TB' => 4, 'PB' => 5, 'EB' => 6, 'ZB' => 7, 'YB' => 8);
    $value = 0;

    if ($bytes > 0) {

        // Generate automatic prefix by bytes 
        // If wrong prefix given
        if (!array_key_exists($unit, $units)) {
            $pow = floor(log($bytes)/log(1024));
            $unit = array_search($pow, $units);

        }

        // Calculate byte value by prefix
        $value = ($bytes/pow(1024,floor($units[$unit])));

    }


    // If decimals is not numeric or decimals is less than 0 
    // then set default value

    if (!is_numeric($decimals) || $decimals < 0) {
        $decimals = 2;
    }

    // Format output
    return sprintf('%.' . $decimals . 'f '.$unit, $value);

}

// 사용예
/*
echo byteFormat(4096, "B");
echo byteFormat(8, "B", 2);
echo byteFormat(1, "KB", 5);
echo byteFormat(1073741824, "B", 0);
echo byteFormat(1073741824, "KB", 0);
echo byteFormat(1073741824, "MB");
echo byteFormat(1073741824);
echo byteFormat(1073741824, "TB", 10);
echo byteFormat(1099511627776, "PB", 6);
*/

// 최신글 함수(메인용)
function rb_latest($skin_dir='', $bo_table, $rows=10, $subject_len=40, $cache_time=1, $options='', $md_sca='')
{
    global $g5;

    if (!$skin_dir) $skin_dir = 'basic';
    
    $time_unit = 3600;  // 1시간으로 고정

    if(preg_match('#^theme/(.+)$#', $skin_dir, $match)) {
        if (G5_IS_MOBILE) {
            $latest_skin_path = G5_THEME_MOBILE_PATH.'/'.G5_SKIN_DIR.'/latest/'.$match[1];
            if(!is_dir($latest_skin_path))
                $latest_skin_path = G5_THEME_PATH.'/'.G5_SKIN_DIR.'/latest/'.$match[1];
            $latest_skin_url = str_replace(G5_PATH, G5_URL, $latest_skin_path);
        } else {
            $latest_skin_path = G5_THEME_PATH.'/'.G5_SKIN_DIR.'/latest/'.$match[1];
            $latest_skin_url = str_replace(G5_PATH, G5_URL, $latest_skin_path);
        }
        $skin_dir = $match[1];
    } else {
        if(G5_IS_MOBILE) {
            $latest_skin_path = G5_MOBILE_PATH.'/'.G5_SKIN_DIR.'/latest/'.$skin_dir;
            $latest_skin_url  = G5_MOBILE_URL.'/'.G5_SKIN_DIR.'/latest/'.$skin_dir;
        } else {
            $latest_skin_path = G5_SKIN_PATH.'/latest/'.$skin_dir;
            $latest_skin_url  = G5_SKIN_URL.'/latest/'.$skin_dir;
        }
    }

    $caches = false;

    if(G5_USE_CACHE) {
        $cache_file_name = "latest-{$bo_table}-{$skin_dir}-{$rows}-{$subject_len}-".g5_cache_secret_key();
        $caches = g5_get_cache($cache_file_name, (int) $time_unit * (int) $cache_time);
        $cache_list = isset($caches['list']) ? $caches['list'] : array();
        g5_latest_cache_data($bo_table, $cache_list);
    }

    if( $caches === false ){

        $list = array();

        $board = get_board_db($bo_table, true);

        if( ! $board ){
            return '';
        }

        $bo_subject = get_text($board['bo_subject']);

        $tmp_write_table = $g5['write_prefix'] . $bo_table; // 게시판 테이블 전체이름
        
        if($md_sca) { //카테고리 있는경우
            $sql = " select * from {$tmp_write_table} where wr_is_comment = 0 and ca_name = '{$md_sca}' order by wr_num limit 0, {$rows} ";
        } else { 
            $sql = " select * from {$tmp_write_table} where wr_is_comment = 0 order by wr_num limit 0, {$rows} ";
        }

        
        $result = sql_query($sql);
        for ($i=0; $row = sql_fetch_array($result); $i++) {
            try {
                unset($row['wr_password']);     //패스워드 저장 안함( 아예 삭제 )
            } catch (Exception $e) {
            }
            $row['wr_email'] = '';              //이메일 저장 안함
            if (strstr($row['wr_option'], 'secret')){           // 비밀글일 경우 내용, 링크, 파일 저장 안함
                $row['wr_content'] = $row['wr_link1'] = $row['wr_link2'] = '';
                $row['file'] = array('count'=>0);
            }
            $list[$i] = get_list($row, $board, $latest_skin_url, $subject_len);

            $list[$i]['first_file_thumb'] = (isset($row['wr_file']) && $row['wr_file']) ? get_board_file_db($bo_table, $row['wr_id'], 'bf_file, bf_content', "and bf_type in (1, 2, 3, 18) ", true) : array('bf_file'=>'', 'bf_content'=>'');
            $list[$i]['bo_table'] = $bo_table;


            if(! isset($list[$i]['icon_file'])) $list[$i]['icon_file'] = '';
        }
        g5_latest_cache_data($bo_table, $list);

        if(G5_USE_CACHE) {

            $caches = array(
                'list' => $list,
                'bo_subject' => sql_escape_string($bo_subject),
            );

            g5_set_cache($cache_file_name, $caches, (int) $time_unit * (int) $cache_time);
        }
    } else {
        $list = $cache_list;
        $bo_subject = (is_array($caches) && isset($caches['bo_subject'])) ? $caches['bo_subject'] : '';
    }

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

    return $content;
}


// 파일업로드
function rb_upload_files($srcfile, $destfile, $dir)
{
    if ($destfile == "") return false;
    // 업로드 한후 , 퍼미션을 변경함
    @move_uploaded_file($srcfile, $dir.'/'.$destfile);
    @chmod($dir.'/'.$destfile, G5_FILE_PERMISSION);
    return true;
}

// 배너출력
function rb_banners($position, $bnid='', $skin='')
{
    global $g5;


    $skin = 'banner.skin.php';
    $skin_path = G5_PATH.'/rb/rb.mod/banner/'.$skin;

    if(file_exists($skin_path)) {
        // 접속기기
        $sql_device = " and ( bn_device = 'both' or bn_device = 'pc' ) ";
        if(G5_IS_MOBILE)
            $sql_device = " and ( bn_device = 'both' or bn_device = 'mobile' ) ";

        // 배너 출력
        
        if($position == "일반") {
            $sql = " select * from rb_banner where '".G5_TIME_YMDHIS."' between bn_begin_time and bn_end_time $sql_device and bn_position = '$position' and bn_id = '$bnid' order by bn_order, bn_id desc ";
            $result = sql_query($sql);
        } else if($position == "메인") {
            $sql = " select * from rb_banner where '".G5_TIME_YMDHIS."' between bn_begin_time and bn_end_time $sql_device and bn_position = '$position' order by rand() limit 1 ";
            $result = sql_query($sql);
        } else {
            $sql = " select * from rb_banner where '".G5_TIME_YMDHIS."' between bn_begin_time and bn_end_time $sql_device and bn_position = '$position' order by bn_order, bn_id desc ";
            $result = sql_query($sql);
        }
        
        include $skin_path;
    } else {
        echo '<p>'.str_replace(G5_PATH.'/', '', $skin_path).' 경로에 스킨 파일이 존재하지 않습니다.</p>';
    }
}


?>
