<?php
// blog.php
// Single-file blog with admin protection by password OR allowed IPs.
// --- CONFIGURE BELOW ---
$dir = '/var/www/blog_data';
$file = $dir . '/posts.txt';

// Password hash for admin login (use password_hash('yourpassword', PASSWORD_DEFAULT) to generate).
// Example: password_hash('supersecret', PASSWORD_DEFAULT)
$password_hash = '$2y$10$BLEmETgMmP0V.zwfxZydjOSWJ7Qj1InIsfKdYSLmgmZAbyWLmH50e';

// Allowed IP addresses (strings). Supports exact matches or simple wildcard like '192.168.1.*'
$allowed_ips = [
    '107.140.22.165',      // localhost example
    '12.74.221.75',      //wildcard example
    '108.147.10.49',
    '2604:a880:400:d0::187c:6001'
];

// Maximum post length (characters)
$max_post_length = 6000;
// --------------------------

// Start session for login + CSRF
session_start();

// Helper: check if client IP matches allowed list (supports '*' wildcard)
function ip_allowed($client_ip, $allowed_list) {
    foreach ($allowed_list as $mask) {
        if (strpos($mask, '*') !== false) {
            // wildcard logic
            $base = rtrim($mask, '*');
            if (strpos($client_ip, $base) === 0) return true;
        } else {
            if ($client_ip === $mask) return true;
        }
    }
    return false;
}

// Get client IP (basic)
$client_ip = $_SERVER['REMOTE_ADDR'] ?? '';

// Check if this client is allowed by IP
$client_allowed_by_ip = ip_allowed($client_ip, $allowed_ips);

// Authentication status
$logged_in = !empty($_SESSION['blog_logged_in']) && $_SESSION['blog_logged_in'] === true;

// If allowed by IP, treat as logged-in for posting only (no session required)
$can_post = $client_allowed_by_ip || $logged_in;

// CSRF token generation/validation
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(24));
}
$csrf_token = $_SESSION['csrf_token'];

// Handle logout
if (isset($_GET['action']) && $_GET['action'] === 'logout') {
    unset($_SESSION['blog_logged_in']);
    header('Location: blog.php');
    exit;
}

// Handle login attempt
$login_error = '';
if (isset($_POST['login']) && isset($_POST['password'])) {
    $pw = $_POST['password'];
    if (password_verify($pw, $password_hash)) {
        $_SESSION['blog_logged_in'] = true;
        $logged_in = true;
        $can_post = true;
        // regenerate CSRF token on login
        $_SESSION['csrf_token'] = bin2hex(random_bytes(24));
        $csrf_token = $_SESSION['csrf_token'];
        // redirect to avoid resubmission
        header('Location: blog.php');
        exit;
    } else {
        $login_error = 'Incorrect password.';
    }
}

// Handle new post submission (only if allowed)
$post_error = '';
if (isset($_POST['submit_post'])) {
    if (!$can_post) {
        $post_error = 'You are not authorized to post.';
    } else {
        // CSRF check
        
        if (empty($_POST['csrf_token']) || !hash_equals($csrf_token, $_POST['csrf_token'])) {
            $post_error = 'Invalid form submission (CSRF).';
        } else {
            $content_raw = $_POST['content'] ?? '';
            $content_trim = trim($content_raw);
            if ($content_trim === '') {
                $post_error = 'Post is empty.';
            } elseif (mb_strlen($content_trim) > $max_post_length) {
                $post_error = 'Post is too long (max ' . $max_post_length . ' chars).';
            } else {
                // Prepare post: timestamp, IP, and sanitized content
                $timestamp = date('Y-m-d H:i:s');
                $author = $logged_in ? 'Admin' : ('User: ' . 'bookz.media');
                // sanitize to prevent HTML injection
                $content_safe = htmlspecialchars($content_trim, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
                // Build line(s). Use a delimiter so we can parse safely. We'll store in a simple format.
                $post_entry = json_encode([
                    'time' => $timestamp,
                    'author' => $author,
                    'content' => $content_safe
                ], JSON_UNESCAPED_UNICODE) . PHP_EOL;

                // Prepend to file (read existing and write new + existing). Use LOCK_EX.
                if (!file_exists($file)) {
                    // create directory if needed
                   
                    $dir = dirname($file);
                    if (!is_dir($dir)) @mkdir($dir, 0755, true);
                    file_put_contents($file, $post_entry, LOCK_EX);
                } else {
                    // read existing then prepend
                    $existing = file_get_contents($file);
                    $to_write = $post_entry . $existing;
                    file_put_contents($file, $to_write, LOCK_EX);
                }

                // redirect to avoid accidental resubmission
                header('Location: blog.php');
                exit;
            }
        }
    }
}

// Read posts
$posts = [];
if (file_exists($file)) {
    $lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        $decoded = json_decode($line, true);
        if (is_array($decoded) && isset($decoded['time'], $decoded['author'], $decoded['content'])) {
            $posts[] = $decoded;
        } else {
            // fallback: treat line as plain text
            $posts[] = ['time' => '', 'author' => '', 'content' => htmlspecialchars($line)];
        }
    }
}

// Simple HTML output below
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Simple Blog</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>
    body{font-family:Arial,Helvetica,sans-serif;max-width:900px;margin:22px auto;padding:0 12px;color:#111}
    header{display:flex;justify-content:space-between;align-items:center}
    .meta{font-size:0.9em;color:#666}
    textarea{width:100%;min-height:140px;padding:8px;font-size:1em;box-sizing:border-box}
    .post{border-bottom:1px solid #e2e2e2;padding:12px 0}
    .ptime{font-size:0.85em;color:#666}
    .author{font-size:0.9em;color:#444}
    .error{color:#b00}
    .loginbox{border:1px solid #ddd;padding:12px;margin-bottom:12px}
    .small{font-size:0.9em;color:#666}
    .btn{padding:8px 12px;border:1px solid #333;background:#f5f5f5;cursor:pointer}
</style>
</head>
<body>
<br>
<a href="./index.php">HOME PAGE</a>
<br>	
<header>
    <h1>Bookz's Blog</h1>
    <div class="meta">
        <?php if ($can_post): ?>
            <strong>Posting enabled</strong> (<?php echo htmlspecialchars($client_ip); ?>)
            <?php if ($logged_in): ?> — <a href="blog.php?action=logout">Logout</a><?php endif; ?>
        <?php else: ?>
            <span class="small">Posting restricted. <?php echo 'Your IP: ' . htmlspecialchars($client_ip); ?></span>
        <?php endif; ?>
    </div>
</header>

<?php if (!$can_post): ?>
    <div class="loginbox">
        <strong>Admin login</strong>
        <?php if ($login_error): ?><div class="error"><?php echo htmlspecialchars($login_error); ?></div><?php endif; ?>
        <form method="post" style="margin-top:8px">
            <label>Password: <input type="password" name="password" required></label>
            <button type="submit" name="login" class="btn">Login</button>
        </form>
        <p class="small">Or post from an allowed IP address configured on the server.</p>
    </div>
<?php endif; ?>

<?php if ($can_post): ?>
    <section aria-labelledby="postform">
        <h2 id="postform">Create a new post</h2>
        <?php if ($post_error): ?><div class="error"><?php echo htmlspecialchars($post_error); ?></div><?php endif; ?>
        <form method="post">
            <textarea name="content" maxlength="<?php echo (int)$max_post_length; ?>" placeholder="Write your post..." required></textarea>
            <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
            <div style="margin-top:8px">
                <button type="submit" name="submit_post" class="btn">Post</button>
                <span class="small" style="margin-left:8px">Max <?php echo $max_post_length; ?> characters.</span>
            </div>
        </form>
    </section>
<?php endif; ?>

<hr>

<section aria-labelledby="posts">
    <h2 id="posts">Posts</h2>
    <?php if (empty($posts)): ?>
        <p>No posts yet.</p>
    <?php else: ?>
        <?php foreach ($posts as $p): ?>
            <article class="post">
                <div class="ptime"><?php echo htmlspecialchars($p['time']); ?></div>
                <div class="author"><?php echo htmlspecialchars($p['author']); ?></div>
                <div class="content" style="margin-top:6px;white-space:pre-wrap;"><?php echo $p['content']; ?></div>
            </article>
        <?php endforeach; ?>
    <?php endif; ?>
</section>

<footer style="margin-top:24px;font-size:0.9em;color:#666">
     
</footer>





</body>




</html>
