<?php session_start(); ?>
<!DOCTYPE html>
<html>
  <head>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>leave me a note</title>
    <link rel="icon" type="image/png" href="favicon.png">
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link href="https://fonts.googleapis.com/css2?family=Manrope:wght@200..800&display=swap" rel="stylesheet" />
    <link href="guest.css" rel="stylesheet" />
   
  </head>


  <header>

<nav>
    <ul>
        <li>leave a note ~｡:* </li>
        <li id="time">time</li>
        <li> <a href="https://www.liaosirui.online">back</a></li>
    </ul>
</nav>

</header>
<body>

<div class="guestbook" id="guestbook">
   
<?php

// ===================================================================
// PHP FLAT-FILE GUESTBOOK by Taufik Nurrohman <http://gplus.to/tovic>
// ===================================================================

// START CONFIGURATION
$database = 'database-001'; // Your TXT file xinming as database.
$per_page = 7; // The number of items you want to display per page.
$time_zone = 'America/New_York'; // 设置为纽约时区
$max_length_xinming = 60; // Maximum character length for guest xinming
$max_length_url = 120; // Maximum character length for guest URL
$max_length_liuyan = 1000; // Maximum character length for guest liuyan
$liuyans = array(
    'database_missing' => 'Database not found. Created one. Please reload the page.',
    'xinming_missing' => 'Please enter your xinming.',
   
    'liuyan_missing' => 'Please enter your liuyan.',
    'math_invalid' => 'Wrong math answer.',
    'max_length_xinming' => 'Maximum character length for guest xinming is ' . $max_length_xinming,
   
    'max_length_liuyan' => 'Maximum character length for guest liuyan is ' . $max_length_liuyan,
    'no_content' => 'No content.'
);
// END CONFIGURATION

// Set default timezone to adjust the timestamp.
date_default_timezone_set($time_zone);

// Functions to create and/or update the content of the TXT file (our database)
function create_or_update_file($file_path, $data) {
    $handle = fopen($file_path, 'w') or die('Cannot open file: ' . $file_path);
    fwrite($handle, $data);
}

// Filter HTML outputs. 
function filter_html($data) {
    return preg_replace(
        array(
            '/&lt;(\/?)(b|blockquote|br|em|i|ins|mark|q|strong|u)&gt;/i', // Allowed HTML tags
            '/&lt;center&gt;/', // Deprecated <center> tag
            '/&lt;\/center&gt;/', // Deprecated </center> tag
            '/&amp;([a-zA-Z]+|\#[0-9]+);/' // Symbols
        ),
        array(
            '<$1$2>',
            '<div style="text-align:center;">',
            '</div>',
            '&$1;'
        ),
    $data);
}

// Redefine database xinming via URL to load
if(isset($_GET['data'])) {
    $database = $_GET['data'];
}

if( ! file_exists($database . '.txt')) {
    if( ! isset($_GET['data'])) {
        create_or_update_file($database . '.txt', "");
        echo "<p class=\"liuyan-warning\">" . $liuyans['database_missing'] . "</p>";
    }
    return false;
} else {
    $old_data = file_get_contents($database . '.txt');
}


/**
 * Post a liuyan
 */
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    // 添加防重复提交保护
    if(isset($_SESSION['last_submit_time']) && 
       time() - $_SESSION['last_submit_time'] < 10) { // 10秒内不能重复提交
        echo "<p class=\"liuyan-warning\">请不要频繁提交留言</p>";
    } else {
        $xinming = "";
        $liuyan = "";
        $timestamp = date('U');
    
        if(isset($_POST['xinming']) && !empty($_POST['xinming'])) {
            $xinming = strip_tags($_POST['xinming']);
        }
    
        if(isset($_POST['liuyan']) && !empty($_POST['liuyan'])) {
            $liuyan = preg_replace(
                array(
                    '/[\n\r]{4,}/',
                    '/\n/',
                    '/[\r\t]/',
                    '/ {2}/',
                    '/ &nbsp;|&nbsp; /',
                    '/<a (.*?)?href=(\'|\")(.*?)(\'|\")(.*?)?>(.*?)<\/a>/i'
                ),
                array(
                    '<br><br>',
                    '<br>',
                    '',
                    '&nbsp;&nbsp;',
                    '&nbsp;&nbsp;',
                    '$6'
                ),
            $_POST['liuyan']);
            $liuyan = htmlentities($liuyan, ENT_QUOTES, 'UTF-8');
        }
    
        if($xinming && $liuyan) {
            // 添加验证码检查
            if(!isset($_POST['math']) || $_POST['math'] != $_SESSION['math']) {
                echo "<p class=\"liuyan-warning\">验证码错误</p>";
            } else {
                try {
                    $new_data = $xinming . "\n" . $liuyan . "\n" . $timestamp;
                    if(!empty($old_data)) {
                        create_or_update_file($database . '.txt', $new_data . "\n\n==\n" . $old_data);
                    } else {
                        create_or_update_file($database . '.txt', $new_data);
                    }
                    
                    $_SESSION['last_submit_time'] = time();
                    // 直接显示成功消息而不是重定向
                    echo "<p class=\"liuyan-success\">sent!</p>";
                    
                    // 清空表单数据
                    $_SESSION['guest_xinming'] = "";
                    $_SESSION['guest_liuyan'] = "";
                    
                    // 清空 POST 数据，确保表单显示为空
                    $_POST['xinming'] = "";
                    $_POST['liuyan'] = "";
                    
                    // 重新读取数据库内容以显示包括新提交内容的留言列表
                    $old_data = file_get_contents($database . '.txt');

                    // 在提交成功后添加
                    echo "<script>document.getElementById('guest-form').reset();</script>";
                } catch (Exception $e) {
                    // 记录错误但不显示给用户
                    error_log('留言保存失败: ' . $e->getMessage());
                    echo "<p class=\"liuyan-warning\">wait</p>";
                }
            }
        } else {
            if(empty($xinming)) {
                echo "<p class=\"liuyan-warning\">name?</p>";
            }
            if(empty($liuyan)) {
                echo "<p class=\"liuyan-warning\">empty??</p>";
            }
        }
    }
}

// 显示提交成功消息
if(isset($_SESSION['liuyan_success'])) {
    echo "<p class=\"liuyan-success\">send~</p>";
    unset($_SESSION['liuyan_success']); // 清除标志，防止刷新时重复显示
}

$_SESSION['guest_xinming'] = isset($_POST['xinming']) ? $_POST['xinming'] : "";
$_SESSION['guest_liuyan'] = isset($_POST['liuyan']) ? htmlentities($_POST['liuyan'], ENT_QUOTES, 'UTF-8') : "";

// Math challenge to prevent spam robot. 
$x = mt_rand(1, 10);
$y = mt_rand(1, 10);
if($x - $y > 0) {
    $math = $x . ' - ' . $y;
    $_SESSION['math'] = $x - $y;
} else {
    $math = $x . ' + ' . $y;
    $_SESSION['math'] = $x + $y;
}

/**
 * Show the existing data.
 */
$data = file_get_contents($database . '.txt');
$current_page = isset($_GET['page']) ? $_GET['page'] : 1;
$nav = "";

if( ! empty($data)) {

    $data = explode("\n\n==\n", $data);
    $total_pages = ceil(count($data) / $per_page);

    if($total_pages > 1) {
        for($i = 0; $i < $total_pages; $i++) {
            if($current_page == ($i + 1)) {
                $nav .= " <span>" . ($i + 1) . "</span>";
            } else {
                $nav .= " <a href=\"?page=" . ($i + 1) . (isset($_GET['data']) ? '&amp;data=' . $database : '') . "\">" . ($i + 1) . "</a>";
            }
        }
    }

    for($i = 0; $i < count($data); $i++) {
        $item = explode("\n", $data[$i]);
        // 确保时间戳索引存在且是有效数字
        $timestamp = isset($item[2]) && is_numeric($item[2]) ? $item[2] : time();
        
        if(isset($_GET['guest']) && preg_match('/[0-9]+/', $_GET['guest'])) {
            if($timestamp == $_GET['guest']) {
                echo "        <div class=\"guest-item\" id=\"guest-" . $timestamp . "\">\n";
                echo "          <span class=\"guest-xinming\">" . (isset($item[0]) ? $item[0] : 'Anonymous') . "</span>\n";
                echo "          <span class=\"guest-timestamp\">";
                echo "<time datetime=\"" . date('c', (int)$timestamp) . "\">" . date('Y/m/d H:i', (int)$timestamp) . "</time>";
                echo " <a href=\"?data=" . $database . "&amp;guest=" . $timestamp . "\" title=\"Permanent Link\"></a>";
                echo "</span>\n";
                echo "          <div class=\"guest-liuyan\">" . (isset($item[1]) ? filter_html($item[1]) : '') . "</div>\n";
                echo "        </div>\n";
            }
        } else {
            if($i <= ($per_page * $current_page) - 1 && $i > ($per_page * ($current_page - 1)) - 1) {
                echo "        <div class=\"guest-item\" id=\"guest-" . $timestamp . "\">\n";
                echo "          <span class=\"guest-xinming\">" . (isset($item[0]) ? $item[0] : 'Anonymous') . "</span>\n";
                echo "          <span class=\"guest-timestamp\">";
                echo "<time datetime=\"" . date('c', (int)$timestamp) . "\">" . date('Y/m/d H:i', (int)$timestamp) . "</time>";
                echo " <a href=\"?data=" . $database . "&amp;guest=" . $timestamp . "\" title=\"Permanent Link\"></a>";
                echo "</span>\n";
                echo "          <div class=\"guest-liuyan\">" . (isset($item[1]) ? filter_html($item[1]) : '') . "</div>\n";
                echo "        </div>\n";
            }
        }
    }

} else {
    echo "        <div class=\"guest-item\">\n";
    echo "          <span class=\"guest-xinming\">Guestbook</span>\n";
    echo "          <span class=\"guest-liuyan\">" . $liuyans['no_content'] . "</span>\n";
    echo "        </div>\n";
}

?>
      </div>
      
      <form method="post" id="guest-form">
       <input type="text" name="xinming" value="<?php echo isset($_SESSION['guest_xinming']) ? $_SESSION['guest_xinming'] : ''; ?>" />
      <textarea name="liuyan"><?php echo isset($_SESSION['guest_liuyan']) ? $_SESSION['guest_liuyan'] : ''; ?></textarea>
      <div class="submit"><?php echo $math; ?> = <input type="text" name="math" autocomplete="off" /> <button type="submit">Send</button></div>
      </form>
   

    <p style="font-size:10px; position: absolute; bottom: 5px; width: 100%; display: flex; justify-content: center; align-items: center;">
    original php by &nbsp;<a href="https://github.com/taufik-nurrohman/flat-file-guestbook">Taufik Nurrohman</a> &nbsp; and inspired by my good friend &nbsp;<a href="https://ericko.info"> eric.</a>
</p>
</div>


<script src="guest.js"></script>


  
</body>
</html>


