<?php
// 이 파일은 새로운 파일 생성시 반드시 포함되어야 함
if (!defined('_GNUBOARD_')) exit; // 개별 페이지 접근 불가

$g5_debug['php']['begin_time'] = $begin_time = get_microtime();

if (!isset($g5['title'])) {
    $g5['title'] = $config['cf_title'];
    $g5_head_title = $g5['title'];
}
else {
    $g5_head_title = $g5['title']; // 상태바에 표시될 제목
    $g5_head_title .= " | ".$config['cf_title'];
}

$g5['title'] = strip_tags($g5['title']);
$g5_head_title = strip_tags($g5_head_title);

// 현재 접속자
// 게시판 제목에 ' 포함되면 오류 발생
$g5['lo_location'] = addslashes($g5['title']);
if (!$g5['lo_location'])
    $g5['lo_location'] = addslashes(clean_xss_tags($_SERVER['REQUEST_URI']));
$g5['lo_url'] = addslashes(clean_xss_tags($_SERVER['REQUEST_URI']));
if (strstr($g5['lo_url'], '/'.G5_ADMIN_DIR.'/') || $is_admin == 'super') $g5['lo_url'] = '';

/*
// 만료된 페이지로 사용하시는 경우
header("Cache-Control: no-cache"); // HTTP/1.1
header("Expires: 0"); // rfc2616 - Section 14.21
header("Pragma: no-cache"); // HTTP/1.0
*/
?>

<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<?php
if (G5_IS_MOBILE) {
    echo '<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=0,maximum-scale=10,user-scalable=no">'.PHP_EOL;
    echo '<meta name="HandheldFriendly" content="true">'.PHP_EOL;
    echo '<meta name="format-detection" content="telephone=no">'.PHP_EOL;
} else {
    echo '<meta http-equiv="imagetoolbar" content="no">'.PHP_EOL;
    echo '<meta http-equiv="X-UA-Compatible" content="IE=edge">'.PHP_EOL;
}

if($config['cf_add_meta'])
    echo $config['cf_add_meta'].PHP_EOL;
?>
<title><?php echo $g5_head_title; ?></title>
<link rel="stylesheet" href="<?php echo run_replace('head_css_url', G5_THEME_CSS_URL.'/'.(G5_IS_MOBILE ? 'mobile' : 'default').'.css?ver='.G5_CSS_VER, G5_THEME_URL); ?>">
<!--[if lte IE 8]>
<script src="<?php echo G5_JS_URL ?>/html5.js"></script>
<![endif]-->
<script>
// 자바스크립트에서 사용하는 전역변수 선언
var g5_url       = "<?php echo G5_URL ?>";
var g5_bbs_url   = "<?php echo G5_BBS_URL ?>";
var g5_is_member = "<?php echo isset($is_member)?$is_member:''; ?>";
var g5_is_admin  = "<?php echo isset($is_admin)?$is_admin:''; ?>";
var g5_is_mobile = "<?php echo G5_IS_MOBILE ?>";
var g5_bo_table  = "<?php echo isset($bo_table)?$bo_table:''; ?>";
var g5_sca       = "<?php echo isset($sca)?$sca:''; ?>";
var g5_editor    = "<?php echo ($config['cf_editor'] && $board['bo_use_dhtml_editor'])?$config['cf_editor']:''; ?>";
var g5_cookie_domain = "<?php echo G5_COOKIE_DOMAIN ?>";
</script>
<?php
add_javascript('<script src="'.G5_JS_URL.'/jquery-1.12.4.min.js"></script>', 0);
add_javascript('<script src="'.G5_JS_URL.'/jquery-migrate-1.4.1.min.js"></script>', 0);
add_javascript('<script src="'.G5_JS_URL.'/jquery.menu.js?ver='.G5_JS_VER.'"></script>', 0);
add_javascript('<script src="'.G5_JS_URL.'/common.js?ver='.G5_JS_VER.'"></script>', 0);
add_javascript('<script src="'.G5_JS_URL.'/wrest.js?ver='.G5_JS_VER.'"></script>', 0);
add_javascript('<script src="'.G5_JS_URL.'/placeholders.min.js"></script>', 0);
add_stylesheet('<link rel="stylesheet" href="'.G5_JS_URL.'/font-awesome/css/font-awesome.min.css">', 0);

if(G5_IS_MOBILE) {
    echo '<script src="'.G5_JS_URL.'/modernizr.custom.70111.js"></script>'.PHP_EOL; // overflow scroll 감지
}
if(!defined('G5_IS_ADMIN'))
    echo $config['cf_add_script'];
?>
<!-- lazyload{ -->
<script src="<?php echo G5_JS_URL; ?>/jquery.lazyload.min.js"></script>
<script type="text/javascript" charset="utf-8"> //lazyload 기능 추가
    $(document).ready(function(){
        $("img.lazy").lazyload({
            threshold : 10,
            effect : "fadeIn",
        });
    });
</script>

    <!-- 모바일 확대 방지{ -->
<script>
  document.addEventListener('touchstart', function(event) {
    if (event.touches.length > 1) {
      event.preventDefault();
    }
  }, { passive: false });

  document.addEventListener('gesturestart', function(event) {
    event.preventDefault();
  });
</script>

<!-- 링크 썸네일(OG이미지메타테그) 게시판 이미지에 따라 자동 설정/ https://dsclub.kr/code/1079 적용{ -->
<?php
function override_og_image() {
    $html = ob_get_contents();
    libxml_use_internal_errors(true);
    
    $dom = new DOMDocument();
    @$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
    $xpath = new DOMXPath($dom);
    
    // Find view_image class images
    $images = $xpath->query('//a[@class="view_image"]//img');
    
    // Extract current OG image
    preg_match('/<meta\s+property="og:image"\s+content="([^"]*)"[^>]*>/i', $html, $matches);
    $defaultImageUrl = isset($matches[1]) ? $matches[1] : G5_THEME_IMG_URL.'/logo.png';
    
    // Select random image or fallback
    if ($images->length > 0) {
        $randomIndex = rand(0, $images->length - 1);
        $newImageUrl = $images->item($randomIndex)->getAttribute('src');
        
        // Validate URL format
        if (!filter_var($newImageUrl, FILTER_VALIDATE_URL)) {
            $newImageUrl = $defaultImageUrl;
        }
    } else {
        $newImageUrl = $defaultImageUrl;
    }
    
    // Replace OG image meta tag
    $pattern = '/<meta\s+property="og:image"\s+content="[^"]*"[^>]*>/i';
    $replacement = '<meta property="og:image" content="' . htmlspecialchars($newImageUrl, ENT_QUOTES, 'UTF-8') . '">';
    $modified_html = preg_replace($pattern, $replacement, $html);
    
    ob_clean();
    echo $modified_html;
}

ob_start();
register_shutdown_function('override_og_image');
?>
<!-- }자동 og 이미지 -->

</head>
<body<?php echo isset($g5['body_script']) ? $g5['body_script'] : ''; ?>>
<?php
if ($is_member) { // 회원이라면 로그인 중이라는 메세지를 출력해준다.
    $sr_admin_msg = '';
    if ($is_admin == 'super') $sr_admin_msg = "최고관리자 ";
    else if ($is_admin == 'group') $sr_admin_msg = "그룹관리자 ";
    else if ($is_admin == 'board') $sr_admin_msg = "게시판관리자 ";

    echo '<div id="hd_login_msg">'.$sr_admin_msg.get_text($member['mb_nick']).'님 로그인 중 ';
    echo '<a href="'.G5_BBS_URL.'/logout.php">로그아웃</a></div>';
}
?>
<!-- 온라인/오프라인 표시{ -->
<style> .offline-banner{background-color:#3c3c3c;color:#ddd;border-bottom: 1px solid #4c4c4c;text-align:center;padding:10px;border-top:1px solid #ccc;position:fixed;top:0;left:0;width:100%;z-index:9999;display:none}.online-banner{background-color:#f1f1f1;color:3c3c3c;text-align:center;padding:10px;border-top:1px solid #ccc;position:fixed;top:0;left:0;width:100%;z-index:9999;display:none}.banner-content{display:flex;align-items:center;justify-content:center}.icon{margin-right:10px}</style><div id="status-banner" class="offline-banner"><div class="banner-content"><div class="icon">✈️</div><div class="status-text">오프라인</div></div></div><script>
const statusBanner=document.getElementById('status-banner');const statusText=document.querySelector('.status-text');function checkOnlineStatus(){if(navigator.onLine){statusText.textContent = '온라인입니다.';statusBanner.classList.remove('offline-banner');
statusBanner.classList.add('online-banner');setTimeout(() => {statusBanner.style.display = 'none';}, 3000);}else{statusText.textContent = '오프라인입니다.';statusBanner.style.display = 'block';statusBanner.classList.remove('online-banner');
statusBanner.classList.add('offline-banner');}}
checkOnlineStatus();window.addEventListener('online', checkOnlineStatus);window.addEventListener('offline', checkOnlineStatus);</script>