<?php
if (!defined('_GNUBOARD_')) exit;

/* MWB :: 최신글 추출 - 랜덤, 공지만, 공지제외, 비밀글제외, 검색 */
function mwb_latest_multi($skin_dir='', $bo_table, $rows=10, $subject_len=40, $order='', $notice='', $secret='', $search_opt='', $cache_time=1, $options='')
{
    global $g5;

    if (!$skin_dir) $skin_dir = 'basic';

    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;
        }
    }

    // $order 값에 따라 랜덤, 히트순, 날짜순(기본) 결정 - 20200116
    if (!$order) $order_cache = 'Num';
    $order_sql = 'wr_num'; 
    if($order == "rand") {
        $order_sql = 'rand()';
        $order_cache = 'Random';
    } else if ($order == "hit") {
        $order_sql = 'wr_hit desc';
        $order_cache = 'Hit';
    }

    // $notice 값에 따라 공지만 또는 공지제외 또는 모두(기본) 추출 결정
    if (!$notice) $notice_cache = 'NoticeAll';
    if ($notice == 'only') {
        $notice_cache = 'NoticeOnly';
    } else if ($notice == 'out') {
        $notice_cache = 'NoticeOut';
    }

    // $secret 값에 따라 비밀글제외 또는 모두(기본) 추출 여부 결정 - 20200116
    if (!$secret) $secret_cashe = 'SecretAll';
    $secret_key = 'secret';
    $secret_sql = '';
    if($secret == "out") {
        $secret_sql = " AND wr_option NOT LIKE '%$secret_key%' "; 
        $secret_cashe = 'SecretOut';
    }

    // $search_opt 값에 따라 검색값 결정 - 20200116
    if (!$search_opt) $search_cache = 'SearchAll';
    $search_sql = '';
    if($search_opt) {
        $options_arr = explode('|', $search_opt);
        if(is_array($options_arr)) { 
            $sfl = $options_arr[0];
            $stx = $options_arr[1];
            $sca = $options_arr[2];
            $search_sql = get_sql_search($sca, $sfl, $stx); 
            $search_sql = " AND ".$search_sql; 
            $search_cache = $search_opt;
        }
    } 

    $caches = false;

    if(G5_USE_CACHE) {
        $cache_file_name = "latest-{$bo_table}-{$skin_dir}-{$rows}-{$subject_len}-{$order_cache}-{$notice_cache}-{$secret_cashe}-{$search_cache}-".g5_cache_secret_key();
        $caches = g5_get_cache($cache_file_name);
        $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);

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

        $notice_sql = '';
        if ($notice == 'only') { // 공지만 출력 - 20200116 with SIR(해피정)
            $arr_notice = preg_replace("/\n/",',', trim($board['bo_notice']));
            if ($arr_notice) {
                $notice_sql = " wr_id IN({$arr_notice}) AND ";
            }
        } else if ($notice == 'out') { // 공지를 제외하고 출력 - 20200116 with SIR(해피정)
            $arr_notice = preg_replace("/\n/",',', trim($board['bo_notice'])); 
            if (!$arr_notice) $arr_notice = 0; 
            $notice_sql = " wr_id Not IN({$arr_notice}) AND ";
        }

        $tmp_write_table = $g5['write_prefix'] . $bo_table; // 게시판 테이블 전체이름
        $sql = " SELECT * from {$tmp_write_table} WHERE {$notice_sql} wr_is_comment = 0 {$secret_sql} {$search_sql} ORDER BY {$order_sql} 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 between '1' and '3'", true) : array('bf_file'=>'', 'bf_content'=>'');
            $list[$i]['bo_table'] = $bo_table;
            // 썸네일 추가
            if($options && is_string($options)) {
                $options_arr = explode(',', $options);
                $thumb_width = $options_arr[0];
                $thumb_height = $options_arr[1];
                $thumb = get_list_thumbnail($bo_table, $row['wr_id'], $thumb_width, $thumb_height, false, true);
                // 이미지 썸네일
                if($thumb['src']) {
                    $img_content = '<img src="'.$thumb['src'].'" alt="'.$thumb['alt'].'" width="'.$thumb_width.'" height="'.$thumb_height.'">';
                    $list[$i]['img_thumbnail'] = '<a href="'.$list[$i]['href'].'" class="lt_img">'.$img_content.'</a>';
                // } else {
                //     $img_content = '<img src="'. G5_IMG_URL.'/no_img.png'.'" alt="'.$thumb['alt'].'" width="'.$thumb_width.'" height="'.$thumb_height.'" class="no_img">';
                }
            }
        }
        g5_latest_cache_data($bo_table, $list);

        if(G5_USE_CACHE) {

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

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

    // $order 값이 rand일 경우 - 캐시 값 삭제 - 같은 게시판 캐시는 전부 삭제됨
    if($order == "rand") {
        delete_cache_latest($bo_table);
    }

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

    return $content;
}
?>