<?php

/*
 * ask Theme 라이브러리 모음. 수정금지.
 */

function print_t($var) {
    echo "<textarea style='width:100%; height:300px;'>";
    print_r($var);
    echo "</textarea>";
}

function ask_menu($add_item = false) {
    global $g5, $is_admin;
    $sql = " select * from {$g5['menu_table']} where me_use = '1' and length(me_code) = '2' order by me_order, me_id ";
    $result = sql_query($sql, false);
    $str = "<ul class='ask-default-menu'>" . PHP_EOL;
    for ($i = 0; $row = sql_fetch_array($result); $i++) {
        $str .= "<li class='ask-parent'>" . PHP_EOL;
        $str .= "<a href='{$row['me_link']}' target='_{$row['me_target']}' class='ask-parent-link'>{$row['me_name']}</a>" . PHP_EOL;
        $sql2 = " select * from {$g5['menu_table']} where me_use = '1' and length(me_code) = '4' and substring(me_code, 1, 2) = '{$row['me_code']}' order by me_order, me_id ";
        $result2 = sql_query($sql2);

        for ($k = 0; $row2 = sql_fetch_array($result2); $k++) {
            if ($k == 0) {
                $str .= '<ul class="dropdown">' . PHP_EOL;
            }
            $str .= "<li><a href='{$row2['me_link']}' target='_{$row2['me_target']}'>{$row2['me_name']}</a></li>" . PHP_EOL;
        }

        if ($k > 0) {
            $str .= '</ul>' . PHP_EOL;
        }
        $str .= "</li>" . PHP_EOL;
    }

    if ($i == 0) {
        $str .= "<li class='ask-parent'>" . PHP_EOL;
        if ($is_admin) {
            $str .=" <a href='" . G5_ADMIN_URL . "/menu_list.php' class='ask-parent-link'>메뉴 생성하기</a>" . PHP_EOL;
        }
        $str .= "</li>" . PHP_EOL;
    }
    if ($add_item) {
        $str .= $add_item;
    }
    $str .= "</ul>" . PHP_EOL;
    return $str;
}

function ask_mobile_menu($add_item = false) {
    global $g5, $is_admin;
    $sql = " select * from {$g5['menu_table']} where me_use = '1' and length(me_code) = '2' order by me_order, me_id ";
    $result = sql_query($sql, false);
    $str = "";
    $str .= "<ul class='ask-mobile-menu'>" . PHP_EOL;
    for ($i = 0; $row = sql_fetch_array($result); $i++) {

        $sqlcount = " select count(*) as cnt from {$g5['menu_table']} where me_use = '1' and length(me_code) = '4' and substring(me_code, 1, 2) = '{$row['me_code']}' order by me_order, me_id "; // ㅠㅠ 
        $count = sql_fetch($sqlcount);

        $str .= "<li class='ask-mobile-parent'>" . PHP_EOL;
        if ($count['cnt'] > 0) {
            $str .= "<span class='ask-submenu'><i class='fa fa-angle-down'></i></span>" . PHP_EOL;
        }
        $str .= "<a href='{$row['me_link']}' target='_{$row['me_target']}' class='ask-mobile-parent-link'>{$row['me_name']}</a>" . PHP_EOL;

        $sql2 = " select * from {$g5['menu_table']} where me_use = '1' and length(me_code) = '4' and substring(me_code, 1, 2) = '{$row['me_code']}' order by me_order, me_id ";
        $result2 = sql_query($sql2);
        for ($k = 0; $row2 = sql_fetch_array($result2); $k++) {
            if ($k == 0) {
                $str .= '<ul class="dropdown">' . PHP_EOL;
            }
            $str .= "<li><a href='{$row2['me_link']}' target='_{$row2['me_target']}'>{$row2['me_name']}</a></li>" . PHP_EOL;
        }

        if ($k > 0) {
            $str .= '</ul>' . PHP_EOL;
        }
        $str .= "</li>" . PHP_EOL;
    }

    if ($i == 0) {
        $str .= "<li class='ask-mobile-parent'>" . PHP_EOL;
        if ($is_admin) {
            $str .=" <a href='" . G5_ADMIN_URL . "/menu_list.php' class='ask-mobile-parent-link'>메뉴생성</a>" . PHP_EOL;
        }
        $str .= "</li>" . PHP_EOL;
    }
    if ($add_item) {
        $str .= $add_item;
    }
    $str .= "</ul>" . PHP_EOL;
    return $str;
}

function ask_get_board($bo_table) {
    global $g5;
    $sql = "select * from {$g5['board_table']} where bo_table = '$bo_table'";
    return sql_fetch($sql);
}

// 게시글보기 썸네일 생성
function ask_view_thumbnail($contents, $thumb_width = 0) {
    global $board, $config;

    if (!$thumb_width) {
        $thumb_width = $board['bo_image_width'];
    }

    // $contents 중 img 태그 추출
    $matches = get_editor_image($contents, true);

    if (empty($matches)) {
        return $contents;
    }

    for ($i = 0; $i < count($matches[1]); $i++) {

        $img = $matches[1][$i];
        preg_match("/src=[\'\"]?([^>\'\"]+[^>\'\"]+)/i", $img, $m);
        $src = $m[1];
        preg_match("/style=[\"\']?([^\"\'>]+)/i", $img, $m);
        $style = $m[1];
        preg_match("/width:\s*(\d+)px/", $style, $m);
        $width = $m[1];
        preg_match("/height:\s*(\d+)px/", $style, $m);
        $height = $m[1];
        preg_match("/alt=[\"\']?([^\"\']*)[\"\']?/", $img, $m);
        $alt = get_text($m[1]);

        // 이미지 path 구함
        $p = parse_url($src);
        if (strpos($p['path'], '/' . G5_DATA_DIR . '/') != 0) {
            $data_path = preg_replace('/^\/.*\/' . G5_DATA_DIR . '/', '/' . G5_DATA_DIR, $p['path']);
        } else {
            $data_path = $p['path'];
        }

        $srcfile = G5_PATH . $data_path;

        if (is_file($srcfile)) {
            $size = @getimagesize($srcfile);
            if (empty($size)) {
                continue;
            }

            // jpg 이면 exif 체크
            if ($size[2] == 2 && function_exists('exif_read_data')) {
                $degree = 0;
                $exif = @exif_read_data($srcfile);
                if (!empty($exif['Orientation'])) {
                    switch ($exif['Orientation']) {
                        case 8:
                            $degree = 90;
                            break;
                        case 3:
                            $degree = 180;
                            break;
                        case 6:
                            $degree = -90;
                            break;
                    }

                    // 세로사진의 경우 가로, 세로 값 바꿈
                    if ($degree == 90 || $degree == -90) {
                        $tmp = $size;
                        $size[0] = $tmp[1];
                        $size[1] = $tmp[0];
                    }
                }
            }

            // 원본 width가 thumb_width보다 작다면
            if ($size[0] <= $thumb_width) {
                continue;
            }

            // Animated GIF 체크
            $is_animated = false;
            if ($size[2] == 1) {
                $is_animated = is_animated_gif($srcfile);
            }

            // 썸네일 높이
            $thumb_height = round(($thumb_width * $size[1]) / $size[0]);
            $filename = basename($srcfile);
            $filepath = dirname($srcfile);

            // 썸네일 생성
            if (!$is_animated) {
                $thumb_file = thumbnail($filename, $filepath, $filepath, $thumb_width, $thumb_height, false);
            } else {
                $thumb_file = $filename;
            }

            if (!$thumb_file) {
                continue;
            }

            if ($width) {
                $thumb_tag = '<img src="' . G5_URL . str_replace($filename, $thumb_file, $data_path) . '" alt="' . $alt . '" width="' . $width . '" height="' . $height . '" class="view-images"/>';
            } else {
                $thumb_tag = '<img src="' . G5_URL . str_replace($filename, $thumb_file, $data_path) . '" alt="' . $alt . '" class="view-images"/>';
            }

            // $img_tag에 editor 경로가 있으면 원본보기 링크 추가
            $img_tag = $matches[0][$i];
            if (strpos($img_tag, G5_DATA_DIR . '/' . G5_EDITOR_DIR) && preg_match("/\.({$config['cf_image_extension']})$/i", $filename)) {
                $imgurl = str_replace(G5_URL, "", $src);
                $thumb_tag = '<a href="' . G5_BBS_URL . '/view_image.php?fn=' . urlencode($imgurl) . '" target="_blank" class="view_image">' . $thumb_tag . '</a>';
            }

            $contents = str_replace($img_tag, $thumb_tag, $contents);
        }
    }

    return $contents;
}

//스크랩 체크 - 원본이 팝업용이라서 오류가 있다.
if (strstr($_SERVER['PHP_SELF'], 'scrap_popin') && $bo_table && $wr_id) {
    $sql = " select count(*) as cnt from {$g5['scrap_table']} where mb_id = '{$member['mb_id']}' and bo_table = '$bo_table' and wr_id = '$wr_id' ";
    $row = sql_fetch($sql);
    if ($row['cnt']) {
        echo "<script>alert('이미 스크랩한 게시물입니다.'); history.back();</script>";
        //alert('이미 스크랩한 게시물입니다.','./board.php?bo_table=' . $bo_table . '&wr_id='. $wr_id);        
        exit;
    }
}
//스크랩 후에 취소 클릭시 이전페이지로 가게 해야한다.
if (strstr($_SERVER['PHP_SELF'], 'scrap_popin_update')) {
    echo "<script> window.close = function(){history.go(-1);}</script>";
}
//메일 발송후 뒤로가기
if (strstr($_SERVER['PHP_SELF'], 'formmail_send')) {
    echo "<script> window.close = function(){history.go(-1);}</script>";
}

//정보찾기 발송후 뒤로가기
if (strstr($_SERVER['PHP_SELF'], 'password_lost2')) {
    echo "<script> window.close = function(){history.go(-1);}</script>";
}

//팝업 제거
function no_popup($tags) {
    $tags = str_replace('onclick="win_memo(this.href); return false;"', '', $tags);
    $tags = str_replace('onclick="win_email(this.href); return false;"', '', $tags);
    $tags = str_replace('onclick="win_profile(this.href); return false;"', '', $tags);
    return $tags;
}

function ask_captcha_html() {
    $captcha_html = captcha_html();
    $captcha_html = str_replace("<button ", "<button class='button' ", $captcha_html);
    $captcha_html = str_replace("숫자음성듣기", "<i class='fa fa-volume-up'></i> <span class='hide-420'>숫자음성듣기</span>", $captcha_html);
    $captcha_html = str_replace("새로고침", "<i class='fa fa-refresh'></i> <span class='hide-420'>새로고침</span>", $captcha_html);
    $captcha_html = str_replace("captcha_box", "captcha_box input ", $captcha_html);
    $captcha_html = str_replace('captcha_info"', 'captcha_info" class="help-text"', $captcha_html);
    return $captcha_html;
}

// 다중 게시글리스트 첨부파일 $theme_config['thumb_-_count'] 설정수 까지 썸네일 생성 - 슬라이드 생성 가능.
function ask_list_thumbnail($bo_table, $wr_id, $thumb_width, $thumb_height, $is_create = false, $is_crop = true, $crop_mode = 'center', $is_sharpen = false, $um_value = '80/0.5/3') {
    global $g5, $config, $theme_config;
    $file = $filename = $alt = "";
    $edt = false;
    $sql = " select bf_file, bf_content from {$g5['board_file_table']} where bo_table = '{$bo_table}' and wr_id = '{$wr_id}' and bf_type between '1' and '3' order by bf_no limit 0, {$theme_config['thumb_count']}";
    $result = sql_query($sql);
    $files = array();
    while ($row = sql_fetch_array($result)) {
        $files[]['bf_file'] = $row['bf_file'];
    }
    //첨부파일이면
    if ($files) {
        for ($i = 0; $i < count($files); $i++) {
            $file[$i]['filename'] = $files[$i]['bf_file'];
            $file[$i]['filepath'] = G5_DATA_PATH . '/file/' . $bo_table;
            $file[$i]['alt'] = get_text($row['bf_content']);
        }
    } else {
        //본문 에디터 삽입
        $write_table = $g5['write_prefix'] . $bo_table;
        $sql = " select wr_content from {$write_table} where wr_id = '{$wr_id}' ";
        $write = sql_fetch($sql);
        $matches = get_editor_image($write['wr_content'], false);
        $edt = true;

        for ($i = 0; $i < count($matches[1]); $i++) {
            // 이미지 path 구함
            $p[$i] = parse_url($matches[1][$i]);
            if (strpos($p[$i]['path'], '/' . G5_DATA_DIR . '/') != 0) {
                $data_path[$i] = preg_replace('/^\/.*\/' . G5_DATA_DIR . '/', '/' . G5_DATA_DIR, $p[$i]['path']);
            } else {
                $data_path[$i] = $p[$i]['path'];
            }

            $srcfile[$i] = G5_PATH . $data_path[$i];

            if (preg_match("/\.({$config['cf_image_extension']})$/i", $srcfile[$i]) && is_file($srcfile[$i])) {
                $size[$i] = @getimagesize($srcfile[$i]);
                if (empty($size[$i])) {
                    continue;
                }

                $file[$i]['filename'] = basename($srcfile[$i]);
                $file[$i]['filepath'] = dirname($srcfile[$i]);

                preg_match("/alt=[\"\']?([^\"\']*)[\"\']?/", $matches[0][$i], $malt);
                $alt[$i] = get_text($malt[1]);
                //테마 설정 수만큼만 만들기.
                if ($theme_config['thumb_count'] == $i + 1) {
                    break;
                }
            }//if
        }//for
    }

    if (!$file) {
        return false;
    }
    for ($i = 0; $i < count($file); $i++) {
        $tname[$i] = thumbnail($file[$i]['filename'], $file[$i]['filepath'], $file[$i]['filepath'], $thumb_width, $thumb_height, $is_create, $is_crop, $crop_mode, $is_sharpen, $um_value);
    }
    if ($tname) {
        //에디터 업로드
        if ($edt) {
            for ($i = 0; $i < count($tname); $i++) {
                // 오리지날 이미지
                $ori[$i] = G5_URL . $data_path[$i];
                // 썸네일 이미지
                $src[$i] = G5_URL . str_replace($file[$i]['filename'], $tname[$i], $data_path[$i]);
            }
        } else {
            //첨부파일 업로드
            for ($i = 0; $i < count($tname); $i++) {
                $ori[$i] = G5_DATA_URL . '/file/' . $bo_table . '/' . $file[$i]['filename'];
                $src[$i] = G5_DATA_URL . '/file/' . $bo_table . '/' . $tname[$i];
            }
        }
    } else {
        return false;
    }

    for ($i = 0; $i < count($src); $i++) {
        $thumb[$i] = array("src" => $src[$i], "ori" => $ori[$i], "alt" => $file[$i]['alt']);
    }
    return $thumb;
}

//내용관리 메뉴로 만들기 - 배열
function get_content_list($exclude = array()) {
    global $g5;
    $menu = array();
    if (!is_array($exclude)) {
        return false;
    }
    if (is_array($exclude) && count($exclude) > 0) {
        foreach ($exclude as $value) {
            $data[] = "'" . $value . "'";
        }
        $ex_id = implode(',', $data);
        $where = " where co_id not in ({$ex_id}) ";
    }

    $sql = "select * from {$g5['content_table']} {$where} order by co_id asc";
    $result = sql_query($sql);
    for ($i = 0; $row = sql_fetch_array($result); $i++) {
        $menu[$i]['id'] = $row['co_id'];
        $menu[$i]['subject'] = $row['co_subject'];
    }
    return $menu;
}

//내용관리 li 로 만들기
function make_content_menu($array) {
    if (!is_array($array)) {
        return false;
    }
    $list = '';
    for ($i = 0; count($array) > $i; $i++) {
        $list .= "<li>";
        $list .= "<a href='" . G5_BBS_URL . "/content.php?co_id={$array[$i]['id']}'>{$array[$i]['subject']}</a>";
        $list .= "</li>" . PHP_EOL;
    }
    return $list;
}

function strip_plugin_tags($tags) {
    $tags = str_replace('[[', '', $tags);
    $tags = str_replace(']]', '', $tags);
    return $tags;
}

/*
 * 문자열을 통한 플러그인 실행
 * 입력문자열 [[함수명]]
 * 내용 기능에 이용한다.
 */

function plugin_run($tags, $str, $return = false, $args = false) {
    global $ask_plugin;
    $org_content = $str;
    $str = strip_tags($str);
    preg_match_all('/\[\[[\w]+\]\]/', $str, $plugin_tags);
    //내용에서 호출된 플러그인 지정하기.
    for ($i = 0; count($plugin_tags['0']) > $i; $i++) {
        $plugin_tags['0'][$i] = strip_plugin_tags($plugin_tags['0'][$i]);
        $filepath = G5_PLUGIN_PATH . '/asktheme/plugin/' . $plugin_tags['0'][$i] . '/' . $plugin_tags['0'][$i] . '.function.php'; // 플러그인 메인 함수 위치.
        if (file_exists($filepath)) {
            //플러그인 함수 파일이 있으면 include
            include_once $filepath;
        }
        //함수가 존재하면 플러그인 실행하기.
        if (function_exists("plugin_" . $plugin_tags['0'][$i])) {//보안을 위해 plugin_ 함수 prefix 를 추가하자.
            //태그삭제
            $org_content = str_replace("[[{$plugin_tags['0'][$i]}]]", '', $org_content);
            $ask_plugin->add_action($tags . $plugin_tags['0'][$i], "plugin_" . $plugin_tags['0'][$i]); //보안을 위해 plugin_ 함수 prefix 를 추가하자.
            //플러그인 실행 코드 - args 인자로 넘겨줄수 있다. 태그를 넘겨주자
            $ask_plugin->do_action($tags . $plugin_tags['0'][$i], $args); //인자 : 위치, 함수에 전달할 값,
        }
    }
    if ($return) {
        return $org_content;
    }
}

function get_plugin_config($plugin_id) {
    $sql = "select * from ask_plugin_config where pc_id = '{$plugin_id}'"; //플러그인 정보 테이블
    $data = sql_fetch($sql);
    return unserialize($data['pc_config']);
}

function sql_escape($str, $link = null) {
    global $g5;
    //미작성..

    return $str;
}

function getDataURI($image, $mime = '') {
    return 'data: ' . (function_exists('mime_content_type') ? mime_content_type($image) : $mime) . ';base64,' . base64_encode(file_get_contents($image));
}

/*
  //class auto loader
  function ask_plugin_autoloader($classname) {
  $filepath = G5_THEME_PATH . '/plugin/' . $classname . '/' . $classname . '.class.php';
  if (file_exists($filepath)) {
  include_once $filepath;
  // 선언된 클래스를 포함했는지 확인합니다
  if (!class_exists($classname, false)) {
  trigger_error("Unable to load class: $classname", E_USER_WARNING);
  }
  } else {
  echo "Unable to load class";
  return false;
  }
  }

  spl_autoload_register('ask_plugin_autoloader');
 */

function validate_alphanumeric_underscore($str) {
    return preg_match('/^[a-zA-Z0-9_]+$/', $str);
}

// 1차 메뉴를 select 형식으로 얻음
function ask_get_menu_select($name, $selected = '', $event = '') {
    global $g5, $is_admin, $member;
    $sql = " select * from {$g5['menu_table']} where me_use = '1' and length(me_code) = '2' order by me_order, me_id ";

    $result = sql_query($sql);
    $str = "<select id=\"$name\" name=\"$name\" $event>\n";
    for ($i = 0; $row = sql_fetch_array($result); $i++) {
        if ($i == 0)
            $str .= "<option value=\"\">선택</option>";
        $str .= option_selected($row['me_code'], $selected, $row['me_name']);
    }
    $str .= "</select>";
    return $str;
}

function ask_group_option($mobile = false) {
    global $g5;
    $sql = "select * from {$g5['group_table']} order by gr_order";
    $result = sql_query($sql);
    $options = "";
    while ($row = sql_fetch_array($result)) {
        if ($mobile) {
            $options .= "<option value='mobile-{$row['gr_id']}'>모바일-{$row['gr_subject']}</option>";
        } else {
            $options .= "<option value='{$row['gr_id']}'>{$row['gr_subject']}</option>";
        }
    }
    return $options;
}

function ask_board_option($gr_id) {
    global $g5;
    $sql = "select * from {$g5['board_table']} where gr_id = '{$gr_id}' order by bo_order";
    $result = sql_query($sql);
    $options = "";
    while ($row = sql_fetch_array($result)) {
        $options .= "<option value='{$row['bo_table']}'>{$row['bo_subject']}</option>";
    }
    return $options;
}

function ask_group_board_select() {
    global $g5;
    $sql = "select * from {$g5['group_table']} order by gr_order";
    $result = sql_query($sql);
    $options = "";
    while ($row = sql_fetch_array($result)) {
        $options .= "<optgroup label='{$row['gr_subject']}'>";
        $options .= ask_board_option($row['gr_id']);
        $options .= "</optgroup>";
    }
    return $options;
}

// 스킨디렉토리를 SELECT 형식으로 얻음
function ask_skin_select($skin_gubun, $id, $name, $selected = '', $event = '') {
    global $config;

    $skins = array();

    if (defined('G5_THEME_PATH') && $config['cf_theme']) {
        //테마스킨
        $dirs = ask_skin_dir($skin_gubun, G5_THEME_PATH . '/' . G5_SKIN_DIR);
        if (!empty($dirs)) {
            foreach ($dirs as $dir) {
                $skins[] = 'theme/' . $dir;
            }
        }
        //테마모바일스킨
        $dirs = ask_skin_dir($skin_gubun, G5_THEME_MOBILE_PATH . '/' . G5_SKIN_DIR);
        if (!empty($dirs)) {
            foreach ($dirs as $dir) {
                $skins[] = '(mobile)theme/' . $dir;
            }
        }
    }

    //일반스킨
    $skins = array_merge($skins, ask_skin_dir($skin_gubun));

    $str = "<select id=\"$id\" name=\"$name\" $event class='input'>\n";
    for ($i = 0; $i < count($skins); $i++) {
        if ($i == 0) {
            $str .= "<option value=\"\">선택을 선택하세요.</option>";
        }
        if (preg_match('#^theme/(.+)$#', $skins[$i], $match)) {
            $text = '(테마) ' . $match[1];
        } else {
            $text = $skins[$i];
        }
        //모바일 스킨 표시해줌
        if (strstr($skins[$i], 'mobile')) {
            $skins[$i] = str_replace("(mobile)", "", $skins[$i]);
            $text = str_replace("(mobile)", "", $skins[$i]);
            $text = '(모바일) ' . $skins[$i];
        }

        $str .= option_selected($skins[$i], $selected, $text);
    }
    $str .= "</select>";
    return $str;
}

// 스킨경로를 얻는다
function ask_skin_dir($skin, $skin_path = G5_SKIN_PATH) {
    global $g5;

    $result_array = array();

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

    $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 latest_admin($skin_dir = '', $bo_table, $rows = 10, $subject_len = 40, $cache_time = 1, $options = '') {
    global $g5;

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

    if (preg_match('#^theme/(.+)$#', $skin_dir, $match)) {
        if (G5_IS_MOBILE || $options == 'mobile-demo') {
            $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;
        }
    }

    $cache_fwrite = false;
    if (G5_USE_CACHE) {
        $cache_file = G5_DATA_PATH . "/cache/latest-{$bo_table}-{$skin_dir}-{$rows}-{$subject_len}.php";

        if (!file_exists($cache_file)) {
            $cache_fwrite = true;
        } else {
            if ($cache_time > 0) {
                $filetime = filemtime($cache_file);
                if ($filetime && $filetime < (G5_SERVER_TIME - 3600 * $cache_time)) {
                    @unlink($cache_file);
                    $cache_fwrite = true;
                }
            }

            if (!$cache_fwrite) {
                include($cache_file);
            }
        }
    }

    if (!G5_USE_CACHE || $cache_fwrite) {
        $list = array();

        $sql = " select * from {$g5['board_table']} where bo_table = '{$bo_table}' ";
        $board = sql_fetch($sql);
        $bo_subject = get_text($board['bo_subject']);

        $tmp_write_table = $g5['write_prefix'] . $bo_table; // 게시판 테이블 전체이름
        $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++) {
            $list[$i] = get_list($row, $board, $latest_skin_url, $subject_len);
        }

        if ($cache_fwrite) {
            $handle = fopen($cache_file, 'w');
            $cache_content = "<?php\nif (!defined('_GNUBOARD_')) exit;\n\$bo_subject='" . $bo_subject . "';\n\$list=" . var_export($list, true) . "?>";
            fwrite($handle, $cache_content);
            fclose($handle);
        }
    }

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

    return $content;
}
