This commit is contained in:
Flatlogic Bot 2025-11-07 06:26:03 +00:00
parent 577ca93381
commit a37fc59b93
14 changed files with 815 additions and 149 deletions

0
.perm_test_apache Normal file
View File

0
.perm_test_exec Normal file
View File

311
ai/LocalAIApi.php Normal file
View File

@ -0,0 +1,311 @@
<?php
// LocalAIApi — proxy client for the Responses API.
// Usage:
// require_once __DIR__ . '/ai/LocalAIApi.php';
// $response = LocalAIApi::createResponse([
// 'input' => [
// ['role' => 'system', 'content' => 'You are a helpful assistant.'],
// ['role' => 'user', 'content' => 'Tell me a bedtime story.'],
// ],
// ]);
// if (!empty($response['success'])) {
// $decoded = LocalAIApi::decodeJsonFromResponse($response);
// }
class LocalAIApi
{
/** @var array<string,mixed>|null */
private static ?array $configCache = null;
/**
* Signature compatible with the OpenAI Responses API.
*
* @param array<string,mixed> $params Request body (model, input, text, reasoning, metadata, etc.).
* @param array<string,mixed> $options Extra options (timeout, verify_tls, headers, path, project_uuid).
* @return array{
* success:bool,
* status?:int,
* data?:mixed,
* error?:string,
* response?:mixed,
* message?:string
* }
*/
public static function createResponse(array $params, array $options = []): array
{
$cfg = self::config();
$payload = $params;
if (empty($payload['input']) || !is_array($payload['input'])) {
return [
'success' => false,
'error' => 'input_missing',
'message' => 'Parameter "input" is required and must be an array.',
];
}
if (!isset($payload['model']) || $payload['model'] === '') {
$payload['model'] = $cfg['default_model'];
}
return self::request($options['path'] ?? null, $payload, $options);
}
/**
* Snake_case alias for createResponse (matches the provided example).
*
* @param array<string,mixed> $params
* @param array<string,mixed> $options
* @return array<string,mixed>
*/
public static function create_response(array $params, array $options = []): array
{
return self::createResponse($params, $options);
}
/**
* Perform a raw request to the AI proxy.
*
* @param string $path Endpoint (may be an absolute URL).
* @param array<string,mixed> $payload JSON payload.
* @param array<string,mixed> $options Additional request options.
* @return array<string,mixed>
*/
public static function request(?string $path = null, array $payload = [], array $options = []): array
{
if (!function_exists('curl_init')) {
return [
'success' => false,
'error' => 'curl_missing',
'message' => 'PHP cURL extension is missing. Install or enable it on the VM.',
];
}
$cfg = self::config();
$projectUuid = $cfg['project_uuid'];
if (empty($projectUuid)) {
return [
'success' => false,
'error' => 'project_uuid_missing',
'message' => 'PROJECT_UUID is not defined; aborting AI request.',
];
}
$defaultPath = $cfg['responses_path'] ?? null;
$resolvedPath = $path ?? ($options['path'] ?? $defaultPath);
if (empty($resolvedPath)) {
return [
'success' => false,
'error' => 'project_id_missing',
'message' => 'PROJECT_ID is not defined; cannot resolve AI proxy endpoint.',
];
}
$url = self::buildUrl($resolvedPath, $cfg['base_url']);
$baseTimeout = isset($cfg['timeout']) ? (int) $cfg['timeout'] : 30;
$timeout = isset($options['timeout']) ? (int) $options['timeout'] : $baseTimeout;
if ($timeout <= 0) {
$timeout = 30;
}
$baseVerifyTls = array_key_exists('verify_tls', $cfg) ? (bool) $cfg['verify_tls'] : true;
$verifyTls = array_key_exists('verify_tls', $options)
? (bool) $options['verify_tls']
: $baseVerifyTls;
$projectHeader = $cfg['project_header'];
$headers = [
'Content-Type: application/json',
'Accept: application/json',
];
$headers[] = $projectHeader . ': ' . $projectUuid;
if (!empty($options['headers']) && is_array($options['headers'])) {
foreach ($options['headers'] as $header) {
if (is_string($header) && $header !== '') {
$headers[] = $header;
}
}
}
if (!empty($projectUuid) && !array_key_exists('project_uuid', $payload)) {
$payload['project_uuid'] = $projectUuid;
}
$body = json_encode($payload, JSON_UNESCAPED_UNICODE);
if ($body === false) {
return [
'success' => false,
'error' => 'json_encode_failed',
'message' => 'Failed to encode request body to JSON.',
];
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $verifyTls);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $verifyTls ? 2 : 0);
curl_setopt($ch, CURLOPT_FAILONERROR, false);
$responseBody = curl_exec($ch);
if ($responseBody === false) {
$error = curl_error($ch) ?: 'Unknown cURL error';
curl_close($ch);
return [
'success' => false,
'error' => 'curl_error',
'message' => $error,
];
}
$status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$decoded = null;
if ($responseBody !== '' && $responseBody !== null) {
$decoded = json_decode($responseBody, true);
if (json_last_error() !== JSON_ERROR_NONE) {
$decoded = null;
}
}
if ($status >= 200 && $status < 300) {
return [
'success' => true,
'status' => $status,
'data' => $decoded ?? $responseBody,
];
}
$errorMessage = 'AI proxy request failed';
if (is_array($decoded)) {
$errorMessage = $decoded['error'] ?? $decoded['message'] ?? $errorMessage;
} elseif (is_string($responseBody) && $responseBody !== '') {
$errorMessage = $responseBody;
}
return [
'success' => false,
'status' => $status,
'error' => $errorMessage,
'response' => $decoded ?? $responseBody,
];
}
/**
* Extract plain text from a Responses API payload.
*
* @param array<string,mixed> $response Result of LocalAIApi::createResponse|request.
* @return string
*/
public static function extractText(array $response): string
{
$payload = $response['data'] ?? $response;
if (!is_array($payload)) {
return '';
}
if (!empty($payload['output']) && is_array($payload['output'])) {
$combined = '';
foreach ($payload['output'] as $item) {
if (!isset($item['content']) || !is_array($item['content'])) {
continue;
}
foreach ($item['content'] as $block) {
if (is_array($block) && ($block['type'] ?? '') === 'output_text' && !empty($block['text'])) {
$combined .= $block['text'];
}
}
}
if ($combined !== '') {
return $combined;
}
}
if (!empty($payload['choices'][0]['message']['content'])) {
return (string) $payload['choices'][0]['message']['content'];
}
return '';
}
/**
* Attempt to decode JSON emitted by the model (handles markdown fences).
*
* @param array<string,mixed> $response
* @return array<string,mixed>|null
*/
public static function decodeJsonFromResponse(array $response): ?array
{
$text = self::extractText($response);
if ($text === '') {
return null;
}
$decoded = json_decode($text, true);
if (is_array($decoded)) {
return $decoded;
}
$stripped = preg_replace('/^```json|```$/m', '', trim($text));
if ($stripped !== null && $stripped !== $text) {
$decoded = json_decode($stripped, true);
if (is_array($decoded)) {
return $decoded;
}
}
return null;
}
/**
* Load configuration from ai/config.php.
*
* @return array<string,mixed>
*/
private static function config(): array
{
if (self::$configCache === null) {
$configPath = __DIR__ . '/config.php';
if (!file_exists($configPath)) {
throw new RuntimeException('AI config file not found: ai/config.php');
}
$cfg = require $configPath;
if (!is_array($cfg)) {
throw new RuntimeException('Invalid AI config format: expected array');
}
self::$configCache = $cfg;
}
return self::$configCache;
}
/**
* Build an absolute URL from base_url and a path.
*/
private static function buildUrl(string $path, string $baseUrl): string
{
$trimmed = trim($path);
if ($trimmed === '') {
return $baseUrl;
}
if (str_starts_with($trimmed, 'http://') || str_starts_with($trimmed, 'https://')) {
return $trimmed;
}
if ($trimmed[0] === '/') {
return $baseUrl . $trimmed;
}
return $baseUrl . '/' . $trimmed;
}
}
// Legacy alias for backward compatibility with the previous class name.
if (!class_exists('OpenAIService')) {
class_alias(LocalAIApi::class, 'OpenAIService');
}

52
ai/config.php Normal file
View File

@ -0,0 +1,52 @@
<?php
// OpenAI proxy configuration (workspace scope).
// Reads values from environment variables or executor/.env.
$projectUuid = getenv('PROJECT_UUID');
$projectId = getenv('PROJECT_ID');
if (
($projectUuid === false || $projectUuid === null || $projectUuid === '') ||
($projectId === false || $projectId === null || $projectId === '')
) {
$envPath = realpath(__DIR__ . '/../../.env'); // executor/.env
if ($envPath && is_readable($envPath)) {
$lines = @file($envPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
foreach ($lines as $line) {
$line = trim($line);
if ($line === '' || $line[0] === '#') {
continue;
}
if (!str_contains($line, '=')) {
continue;
}
[$key, $value] = array_map('trim', explode('=', $line, 2));
if ($key === '') {
continue;
}
$value = trim($value, "\"' ");
if (getenv($key) === false || getenv($key) === '') {
putenv("{$key}={$value}");
}
}
$projectUuid = getenv('PROJECT_UUID');
$projectId = getenv('PROJECT_ID');
}
}
$projectUuid = ($projectUuid === false) ? null : $projectUuid;
$projectId = ($projectId === false) ? null : $projectId;
$baseUrl = 'https://flatlogic.com';
$responsesPath = $projectId ? "/projects/{$projectId}/ai-request" : null;
return [
'base_url' => $baseUrl,
'responses_path' => $responsesPath,
'project_id' => $projectId,
'project_uuid' => $projectUuid,
'project_header' => 'project-uuid',
'default_model' => 'gpt-5',
'timeout' => 30,
'verify_tls' => true,
];

51
assets/css/custom.css Normal file
View File

@ -0,0 +1,51 @@
body {
font-family: 'Inter', sans-serif;
background-color: #121212;
color: #E0E0E0;
}
.navbar-dark .navbar-nav .nav-link {
color: rgba(255, 255, 255, .75);
}
.navbar-dark .navbar-nav .nav-link.active,
.navbar-dark .navbar-nav .nav-link:hover {
color: #fff;
}
.card {
background-color: #1E1E1E;
border: 1px solid rgba(255, 255, 255, 0.1);
}
.form-control {
background-color: #2a2a2a;
color: #fff;
border: 1px solid #444;
}
.form-control:focus {
background-color: #2a2a2a;
color: #fff;
border-color: #0D6EFD;
box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, .25);
}
.form-control::placeholder {
color: #888;
}
.btn-primary {
background-color: #0D6EFD;
border-color: #0D6EFD;
}
.text-muted {
color: #A0A0A0 !important;
}
.feature-icon {
font-size: 2.5rem;
color: #0D6EFD;
}

58
dashboard.php Normal file
View File

@ -0,0 +1,58 @@
<?php
session_start();
// If user is not logged in, redirect to login page
if (!isset($_SESSION['user_id'])) {
header("Location: login.php");
exit;
}
include 'header.php';
?>
<main class="container flex-grow-1 my-5">
<div class="row">
<div class="col-md-4">
<div class="card">
<div class="card-header">
Conversations
</div>
<ul class="list-group list-group-flush">
<li class="list-group-item"><a href="#">User 1</a></li>
<li class="list-group-item"><a href="#">User 2</a></li>
<li class="list-group-item"><a href="#">User 3</a></li>
</ul>
</div>
</div>
<div class="col-md-8">
<div class="card">
<div class="card-header">
Chat with User 1
</div>
<div class="card-body" style="height: 400px; overflow-y: auto;">
<!-- Chat messages will go here -->
<div class="d-flex justify-content-end mb-3">
<div class="bg-primary text-white p-2 rounded">
Hello!
</div>
</div>
<div class="d-flex justify-content-start mb-3">
<div class="bg-light p-2 rounded">
Hi there!
</div>
</div>
</div>
<div class="card-footer">
<form>
<div class="input-group">
<input type="text" class="form-control" placeholder="Type a message...">
<button class="btn btn-primary" type="button">Send</button>
</div>
</form>
</div>
</div>
</div>
</div>
</main>
<?php include 'footer.php'; ?>

29
db/setup.php Normal file
View File

@ -0,0 +1,29 @@
<?php
require_once 'config.php';
try {
// 1. Connect without a database selected
$pdo_admin = new PDO('mysql:host='.DB_HOST.';charset=utf8mb4', DB_USER, DB_PASS, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
// 2. Create the database if it doesn't exist
$pdo_admin->exec("CREATE DATABASE IF NOT EXISTS ".DB_NAME);
echo "Database '" . DB_NAME . "' created or already exists.\n";
// 3. Now, connect to the specific database and create the table
$pdo = db();
$sql = "
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
display_name VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE,
password_hash VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);";
$pdo->exec($sql);
echo "Table 'users' created successfully (if it didn't exist).\n";
} catch (PDOException $e) {
die("DB SETUP ERROR: " . $e->getMessage());
}

10
footer.php Normal file
View File

@ -0,0 +1,10 @@
<footer class="footer mt-auto py-3 bg-dark text-white">
<div class="container text-center">
<small>harmony3 &copy; 2025</small>
</div>
</footer>
<!-- <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script> -->
</body>
</html>

54
header.php Normal file
View File

@ -0,0 +1,54 @@
<?php session_start(); ?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>harmony3</title>
<meta name="description" content="A simple user-to-user messaging system.">
<meta name="keywords" content="messaging, chat, private messages, user-to-user, real-time chat, harmony3, Built with Flatlogic Generator">
<meta property="og:title" content="harmony3">
<meta property="og:description" content="A simple user-to-user messaging system.">
<meta property="og:image" content="">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
<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=Inter:wght@400;500;700&display=swap" rel="stylesheet">
<link href="assets/css/custom.css" rel="stylesheet">
</head>
<body class="d-flex flex-column min-vh-100">
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container">
<a class="navbar-brand" href="index.php">
<i class="bi bi-chat-quote-fill"></i>
harmony3
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ms-auto">
<?php if (isset($_SESSION['user_id'])): ?>
<li class="nav-item">
<a class="nav-link" href="dashboard.php">Dashboard</a>
</li>
<li class="nav-item">
<a class="nav-link" href="logout.php">Logout</a>
</li>
<?php else: ?>
<li class="nav-item">
<a class="nav-link" href="login.php">Sign In</a>
</li>
<li class="nav-item">
<a class="nav-link btn btn-primary btn-sm px-3" href="signup.php">Sign Up</a>
</li>
<?php endif; ?>
</ul>
</div>
</div>
</nav>

189
index.php
View File

@ -1,150 +1,43 @@
<?php <?php include 'header.php'; ?>
declare(strict_types=1);
@ini_set('display_errors', '1');
@error_reporting(E_ALL);
@date_default_timezone_set('UTC');
$phpVersion = PHP_VERSION; <main class="container my-5">
$now = date('Y-m-d H:i:s'); <div class="row align-items-center">
?> <div class="col-md-6">
<!doctype html> <h1 class="display-4 fw-bold">Connect Privately.</h1>
<html lang="en"> <p class="lead text-muted">A simple, secure, and real-time messaging platform for personal conversations. Your space to talk, without the noise.</p>
<head> <div class="d-grid gap-2 d-md-flex justify-content-md-start">
<meta charset="utf-8" /> <a href="signup.php" class="btn btn-primary btn-lg px-4 me-md-2">Get Started</a>
<meta name="viewport" content="width=device-width, initial-scale=1" /> <a href="login.php" class="btn btn-outline-secondary btn-lg px-4">Sign In</a>
<title>New Style</title> </div>
<?php </div>
// Read project preview data from environment <div class="col-md-6 text-center">
$projectDescription = $_SERVER['PROJECT_DESCRIPTION'] ?? ''; <i class="bi bi-shield-lock-fill" style="font-size: 12rem; color: #0D6EFD;"></i>
$projectImageUrl = $_SERVER['PROJECT_IMAGE_URL'] ?? ''; </div>
?>
<?php if ($projectDescription): ?>
<!-- Meta description -->
<meta name="description" content='<?= htmlspecialchars($projectDescription) ?>' />
<!-- Open Graph meta tags -->
<meta property="og:description" content="<?= htmlspecialchars($projectDescription) ?>" />
<!-- Twitter meta tags -->
<meta property="twitter:description" content="<?= htmlspecialchars($projectDescription) ?>" />
<?php endif; ?>
<?php if ($projectImageUrl): ?>
<!-- Open Graph image -->
<meta property="og:image" content="<?= htmlspecialchars($projectImageUrl) ?>" />
<!-- Twitter image -->
<meta property="twitter:image" content="<?= htmlspecialchars($projectImageUrl) ?>" />
<?php endif; ?>
<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=Inter:wght@400;700&display=swap" rel="stylesheet">
<style>
:root {
--bg-color-start: #6a11cb;
--bg-color-end: #2575fc;
--text-color: #ffffff;
--card-bg-color: rgba(255, 255, 255, 0.01);
--card-border-color: rgba(255, 255, 255, 0.1);
}
body {
margin: 0;
font-family: 'Inter', sans-serif;
background: linear-gradient(45deg, var(--bg-color-start), var(--bg-color-end));
color: var(--text-color);
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
text-align: center;
overflow: hidden;
position: relative;
}
body::before {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100"><path d="M-10 10L110 10M10 -10L10 110" stroke-width="1" stroke="rgba(255,255,255,0.05)"/></svg>');
animation: bg-pan 20s linear infinite;
z-index: -1;
}
@keyframes bg-pan {
0% { background-position: 0% 0%; }
100% { background-position: 100% 100%; }
}
main {
padding: 2rem;
}
.card {
background: var(--card-bg-color);
border: 1px solid var(--card-border-color);
border-radius: 16px;
padding: 2rem;
backdrop-filter: blur(20px);
-webkit-backdrop-filter: blur(20px);
box-shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.1);
}
.loader {
margin: 1.25rem auto 1.25rem;
width: 48px;
height: 48px;
border: 3px solid rgba(255, 255, 255, 0.25);
border-top-color: #fff;
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.hint {
opacity: 0.9;
}
.sr-only {
position: absolute;
width: 1px; height: 1px;
padding: 0; margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap; border: 0;
}
h1 {
font-size: 3rem;
font-weight: 700;
margin: 0 0 1rem;
letter-spacing: -1px;
}
p {
margin: 0.5rem 0;
font-size: 1.1rem;
}
code {
background: rgba(0,0,0,0.2);
padding: 2px 6px;
border-radius: 4px;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
footer {
position: absolute;
bottom: 1rem;
font-size: 0.8rem;
opacity: 0.7;
}
</style>
</head>
<body>
<main>
<div class="card">
<h1>Analyzing your requirements and generating your website…</h1>
<div class="loader" role="status" aria-live="polite" aria-label="Applying initial changes">
<span class="sr-only">Loading…</span>
</div>
<p class="hint"><?= ($_SERVER['HTTP_HOST'] ?? '') === 'appwizzy.com' ? 'AppWizzy' : 'Flatlogic' ?> AI is collecting your requirements and applying the first changes.</p>
<p class="hint">This page will update automatically as the plan is implemented.</p>
<p>Runtime: PHP <code><?= htmlspecialchars($phpVersion) ?></code> — UTC <code><?= htmlspecialchars($now) ?></code></p>
</div> </div>
</main>
<footer> <div class="row text-center g-4 py-5 mt-5">
Page updated: <?= htmlspecialchars($now) ?> (UTC) <div class="col-lg-4">
</footer> <div class="feature-icon mb-3">
</body> <i class="bi bi-person-badge"></i>
</html> </div>
<h2 class="fw-normal">User Profiles</h2>
<p>Create your profile, set your display name, and connect with others.</p>
</div>
<div class="col-lg-4">
<div class="feature-icon mb-3">
<i class="bi bi-chat-dots"></i>
</div>
<h2 class="fw-normal">Direct Messaging</h2>
<p>Start one-on-one conversations with any other registered user on the platform.</p>
</div>
<div class="col-lg-4">
<div class="feature-icon mb-3">
<i class="bi bi-broadcast"></i>
</div>
<h2 class="fw-normal">Real-Time Chat</h2>
<p>Experience live messaging with WebSocket technology for instant communication.</p>
</div>
</div>
</main>
<?php include 'footer.php'; ?>

106
login.php Normal file
View File

@ -0,0 +1,106 @@
<?php
// Start session and load DB config right away.
session_start();
require_once 'db/config.php';
// --- STANDARD PAGE LOAD (NON-AJAX) ---
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Include header AFTER ajax block.
include 'header.php';
// If user is already logged in, redirect to dashboard
if (isset($_SESSION['user_id'])) {
echo '<script>window.top.location.href = "dashboard.php";</script>';
exit;
}
$errors = [];
$registered_success = isset($_GET['registered']);
// This block now only handles the STANDARD (non-fetch) form submission.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
echo '<div class="alert alert-info">DEBUG: Standard POST handler reached.</div>';
echo '<pre class="alert alert-warning">DEBUG: $_POST data: ' . htmlspecialchars(print_r($_POST, true)) . '</pre>';
$email = trim($_POST['login_email']);
$password = $_POST['login_pass'];
if (empty($email)) {
$errors[] = 'Email is required.';
}
if (empty($password)) {
$errors[] = 'Password is required.';
}
if (empty($errors)) {
try {
$pdo = db();
$stmt = $pdo->prepare("SELECT id, display_name, password_hash FROM users WHERE email = ?");
$stmt->execute([$email]);
$user = $stmt->fetch();
if ($user && password_verify($password, $user['password_hash'])) {
$_SESSION['user_id'] = $user['id'];
$_SESSION['display_name'] = $user['display_name'];
// Use JS redirect for consistency
echo '<script>window.top.location.href = "dashboard.php";</script>';
exit;
} else {
$errors[] = 'Invalid email or password.';
}
} catch (PDOException $e) {
error_log("Database error in login.php (Standard): " . $e->getMessage());
$errors[] = 'A server error occurred. Please try again later.';
}
}
}
?>
<main class="container flex-grow-1 d-flex align-items-center justify-content-center">
<div class="col-md-6 col-lg-4">
<div class="card my-5">
<div class="card-body p-4">
<h1 class="card-title text-center mb-4">Sign In</h1>
<div id="alert-container">
<?php if ($registered_success): ?>
<div class="alert alert-success" role="alert">
Registration successful! You can now sign in.
</div>
<?php endif; ?>
<?php if (!empty($errors)): ?>
<div class="alert alert-danger" role="alert">
<?php foreach ($errors as $error): ?>
<p class="mb-0"><?php echo htmlspecialchars($error); ?></p>
<?php endforeach; ?>
</div>
<?php endif; ?>
</div>
<form id="login-form" method="POST" action="login.php">
<div class="mb-3">
<label for="email" class="form-label">Email address</label>
<input type="email" class="form-control" id="email" name="login_email" placeholder="name@example.com" required>
</div>
<div class="mb-3">
<label for="password" class="form-label">Password</label>
<input type="password" class="form-control" id="password" name="login_pass" required>
</div>
<div class="d-grid">
<button type="submit" class="btn btn-primary">Sign In</button>
</div>
</form>
</div>
<div class="card-footer text-center py-3">
<small class="text-muted">Don't have an account? <a href="signup.php">Sign Up</a></small>
</div>
</div>
</div>
</main>
<?php include 'footer.php'; ?>

6
logout.php Normal file
View File

@ -0,0 +1,6 @@
<?php
session_start();
session_unset();
session_destroy();
header("Location: index.php");
exit;

96
signup.php Normal file
View File

@ -0,0 +1,96 @@
<?php
session_start();
require_once 'db/config.php';
$errors = [];
$success_message = '';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$display_name = trim($_POST['display_name']);
$email = trim($_POST['email']);
$password = $_POST['password'];
if (empty($display_name)) {
$errors[] = 'Display name is required.';
}
if (empty($email)) {
$errors[] = 'Email is required.';
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = 'Invalid email format.';
}
if (empty($password)) {
$errors[] = 'Password is required.';
} elseif (strlen($password) < 8) {
$errors[] = 'Password must be at least 8 characters long.';
}
if (empty($errors)) {
try {
$pdo = db();
$stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
$stmt->execute([$email]);
if ($stmt->fetch()) {
$errors[] = 'Email address is already registered.';
} else {
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$stmt = $pdo->prepare("INSERT INTO users (display_name, email, password_hash) VALUES (?, ?, ?)");
if ($stmt->execute([$display_name, $email, $hashed_password])) {
// Redirect to login page after successful registration
header("Location: login.php?registered=true");
exit;
} else {
$errors[] = 'Failed to create account. Please try again later.';
}
}
} catch (PDOException $e) {
error_log($e->getMessage());
$errors[] = 'Database error. Please try again later.';
}
}
}
include 'header.php';
?>
<main class="container flex-grow-1 d-flex align-items-center justify-content-center">
<div class="col-md-6 col-lg-4">
<div class="card my-5">
<div class="card-body p-4">
<h1 class="card-title text-center mb-4">Create Account</h1>
<?php if (!empty($errors)): ?>
<div class="alert alert-danger" role="alert">
<?php foreach ($errors as $error): ?>
<p class="mb-0"><?php echo htmlspecialchars($error); ?></p>
<?php endforeach; ?>
</div>
<?php endif; ?>
<form action="signup.php" method="post" novalidate>
<div class="mb-3">
<label for="displayName" class="form-label">Display Name</label>
<input type="text" class="form-control" id="displayName" name="display_name" required value="<?php echo isset($_POST['display_name']) ? htmlspecialchars($_POST['display_name']) : ''; ?>">
</div>
<div class="mb-3">
<label for="email" class="form-label">Email address</label>
<input type="email" class="form-control" id="email" name="email" placeholder="name@example.com" required value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : ''; ?>">
</div>
<div class="mb-3">
<label for="password" class="form-label">Password</label>
<input type="password" class="form-control" id="password" name="password" required>
</div>
<div class="d-grid">
<button type="submit" class="btn btn-primary">Sign Up</button>
</div>
</form>
</div>
<div class="card-footer text-center py-3">
<small class="text-muted">Already have an account? <a href="login.php">Sign In</a></small>
</div>
</div>
</div>
</main>
<?php include 'footer.php'; ?>