<?php
session_set_cookie_params(['secure' => true,'httponly' => true,'samesite' => 'Strict']);
session_start();
$session_lifetime = 3 * 60; // Session timeout
$correct_username = "admin";
$correct_password_hash = '$2y$10$S9naYnE6MqP14zVRfIsig.A98jBGzEImaGLgKVuiSGKpI7yr7XeGG'; // password: 4869
//echo password_hash("pass", PASSWORD_DEFAULT); //generate
if (isset($_GET['logout'])) {
session_unset();
session_destroy();
header("Location: " . $_SERVER['PHP_SELF']);
exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['heartbeat'])) {
$_SESSION['last_activity'] = time();
exit;
}
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = $_POST['username'] ?? '';
$password = $_POST['password'] ?? '';
if ($username === $correct_username && password_verify($password, $correct_password_hash)) {
session_regenerate_id(true);
$_SESSION['logged_in'] = true;
$_SESSION['last_activity'] = time();
header("Location: " . $_SERVER['PHP_SELF']);
exit;
} else {
$error = "Invalid username or password.";
}
}
?>
<?php if (isset($error)) echo "<p style='color:red;'>$error</p>"; ?>
<form method="post">
<label>Username: <input name="username" required></label><br>
<label>Password: <input type="password" name="password" required></label><br>
<button type="submit">Login</button>
</form>

<?php
exit;
}
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity']) > $session_lifetime) {
session_unset();
session_destroy();
header("Location: " . $_SERVER['PHP_SELF']);
exit;
}
$_SESSION['last_activity'] = time(); // Refresh session activity
$remaining_time = ($_SESSION['last_activity'] + $session_lifetime) - time();
?>
Welcome, you are logged in! <span id="countdown"></span><hr>
<a href="?logout=1">Logout</a>
<script>
let remaining = <?php echo $remaining_time; ?>;
function updateCountdown() {
if (remaining <= 0) {
clearInterval(timer);
alert("Session expired due to inactivity.");
location.reload();
return;
}
const minutes = Math.floor(remaining / 60);
const seconds = remaining % 60;
document.getElementById('countdown').textContent =
minutes + "m " + (seconds < 10 ? "0" : "") + seconds + "s";
remaining--;
}
updateCountdown();
const timer = setInterval(updateCountdown, 1000);
setInterval(() => {
fetch("", {
method: "POST",
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: "heartbeat=1"
});
}, 30000);
</script>




<?php
// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['url'])) {
    $url = trim($_POST['url']);
    $result = processFediverseUrl($url);
}

function processFediverseUrl($url) {
    // Parse the URL
    $parsedUrl = parse_url($url);
    if (!$parsedUrl || !isset($parsedUrl['host'])) {
        return ['success' => false, 'message' => 'Invalid URL format'];
    }

    $domain = $parsedUrl['host'];
    $username = null;

    // Check if it's a direct @user@domain style URL (like Mastodon)
    if (preg_match('#/@([^/@]+)(?:@[^/]+)?/(?:posts/)?\d+#', $parsedUrl['path'] ?? '', $matches)) {
        $username = $matches[1];
    } 
    // Check for notice/status IDs (like Pleroma/Akkoma)
    else if (preg_match('#/notice/([^/?]+)#', $parsedUrl['path'] ?? '', $matches)) {
        $statusId = $matches[1];
        $username = resolveUsernameFromNotice($domain, $statusId);
        
        if (!$username) {
            // Prompt for username if resolution fails
            if (isset($_POST['username']) && !empty($_POST['username'])) {
                $username = $_POST['username'];
            } else {
                return [
                    'success' => false, 
                    'needs_username' => true,
                    'url' => $url,
                    'domain' => $domain,
                    'message' => 'Could not resolve username automatically. Please enter it below.'
                ];
            }
        }
    } else {
        return ['success' => false, 'message' => 'URL format not recognized: ' . ($parsedUrl['path'] ?? 'no path')];
    }

    // Try to fetch profile picture
    $pfpUrl = null;
    if (!isset($_POST['pfp_url'])) {
        $pfpUrl = fetchProfilePicture($domain, $username);
    } else if (!empty($_POST['pfp_url'])) {
        $pfpUrl = $_POST['pfp_url'];
    }
    
    // If we couldn't get the pfp URL and it wasn't provided, prompt for it
    if (!$pfpUrl && !isset($_POST['pfp_url'])) {
        return [
            'success' => false, 
            'needs_pfp' => true,
            'url' => $url,
            'domain' => $domain,
            'username' => $username,
            'message' => 'Could not fetch profile picture automatically. Please enter the URL below.'
        ];
    }

    // Save to JSON
    $userIdentifier = "$username@$domain";
    $success = saveToJson($userIdentifier, $url, $pfpUrl);
    
    if ($success) {
        return ['success' => true, 'user' => $userIdentifier, 'url' => $url, 'pfp' => $pfpUrl];
    } else {
        return ['success' => false, 'message' => 'Failed to save to JSON file'];
    }
}

function resolveUsernameFromNotice($domain, $statusId) {
    // Try to fetch the status information using ActivityPub or Mastodon API
    $apiUrl = "https://$domain/api/v1/statuses/$statusId";
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $apiUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Fediverse-User-Resolver/1.0');
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode === 200 && $response) {
        $data = json_decode($response, true);
        if (isset($data['account']['acct'])) {
            return $data['account']['acct'];
        }
        if (isset($data['account']['username'])) {
            return $data['account']['username'];
        }
    }
    
    return null;
}

function fetchProfilePicture($domain, $username) {
    // Try to fetch user information using Mastodon API
    $apiUrl = "https://$domain/api/v1/accounts/lookup?acct=$username";
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $apiUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Fediverse-User-Resolver/1.0');
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode === 200 && $response) {
        $data = json_decode($response, true);
        if (isset($data['avatar'])) {
            return $data['avatar'];
        }
    }
    
    return null;
}

function saveToJson($userIdentifier, $url, $pfpUrl) {
    $filename = 'fediusers.json';
    $data = [];
    
    // Read existing data if file exists
    if (file_exists($filename)) {
        $existingData = file_get_contents($filename);
        if ($existingData) {
            $data = json_decode($existingData, true) ?: [];
        }
    }
    
    // Check if this user already exists
    $exists = false;
    foreach ($data as $entry) {
        if ($entry['user'] === $userIdentifier) {
            $exists = true;
            break;
        }
    }
    
    // Add new entry if it doesn't exist
    if (!$exists) {
        $data[] = [
            'user' => $userIdentifier,
            'url' => $url,
            'pfp' => $pfpUrl,
            'added' => date('Y-m-d H:i:s')
        ];
        
        // Write back to file
        $json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
        return file_put_contents($filename, $json) !== false;
    }
    
    return true; // Already exists, consider it a success
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fediverse User Saver</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 600px; margin: 20px auto; padding: 20px; }
        .form-group { margin-bottom: 15px; }
        input[type="text"], input[type="url"] { width: 100%; padding: 8px; border: 1px solid #ccc; border-radius: 4px; }
        button { background: #007bff; color: white; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; }
        button:hover { background: #0056b3; }
        .alert { padding: 10px; margin: 10px 0; border-radius: 4px; }
        .success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        .info { background: #d1ecf1; color: #0c5460; border: 1px solid #bee5eb; }
        .pfp-preview { max-width: 100px; max-height: 100px; margin-top: 10px; }
    </style>
</head>
<body>
    <h1>Fediverse User Saver</h1>
    
    <?php if (isset($result)): ?>
        <?php if ($result['success']): ?>
            <div class="alert success">
                Successfully saved: <?php echo htmlspecialchars($result['user']); ?>
                <?php if (!empty($result['pfp'])): ?>
                    <div><img src="<?php echo htmlspecialchars($result['pfp']); ?>" alt="Profile picture" class="pfp-preview"></div>
                <?php endif; ?>
            </div>
        <?php elseif (isset($result['needs_username']) && $result['needs_username']): ?>
            <div class="alert info">
                <?php echo htmlspecialchars($result['message']); ?>
            </div>
            <form method="POST">
                <input type="hidden" name="url" value="<?php echo htmlspecialchars($result['url']); ?>">
                <div class="form-group">
                    <label for="username">Username:</label>
                    <input type="text" id="username" name="username" required 
                           placeholder="Enter username (without @domain)">
                </div>
                <button type="submit">Save User</button>
            </form>
        <?php elseif (isset($result['needs_pfp']) && $result['needs_pfp']): ?>
            <div class="alert info">
                <?php echo htmlspecialchars($result['message']); ?>
            </div>
            <form method="POST">
                <input type="hidden" name="url" value="<?php echo htmlspecialchars($result['url']); ?>">
                <input type="hidden" name="username" value="<?php echo htmlspecialchars($result['username']); ?>">
                <div class="form-group">
                    <label for="pfp_url">Profile Picture URL:</label>
                    <input type="url" id="pfp_url" name="pfp_url" 
                           placeholder="https://example.com/profile-picture.jpg">
                </div>
                <button type="submit">Save User</button>
            </form>
        <?php else: ?>
            <div class="alert error">
                Error: <?php echo htmlspecialchars($result['message']); ?>
            </div>
        <?php endif; ?>
    <?php endif; ?>
    
    <form method="POST">
        <div class="form-group">
            <label for="url">Fediverse Post URL:</label>
            <input type="url" id="url" name="url" required 
                   placeholder="https://mastodon.example/@user/123456 or https://instance.example/notice/ABC123"
                   value="<?php echo isset($_POST['url']) ? htmlspecialchars($_POST['url']) : ''; ?>">
        </div>
        <button type="submit">Process URL</button>
    </form>
    
    <p>Supported formats:</p>
    <ul>
        <li>Mastodon: https://mastodon.example/@username/123456789</li>
        <li>Pleroma/Akkoma: https://instance.example/notice/ABC123DEF456</li>
    </ul>
</body>
</html>
