Created
July 27, 2025 19:09
-
-
Save thinkphp/0bd08b19f97a844a36e3cfbfe9f1f33a to your computer and use it in GitHub Desktop.
newsletter.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Enable error reporting for debugging (disable in production) | |
ini_set('display_errors', 1); | |
ini_set('display_startup_errors', 1); | |
error_reporting(E_ALL); | |
// Set JSON header first | |
header('Content-Type: application/json; charset=utf-8'); | |
header('Access-Control-Allow-Origin: *'); | |
header('Access-Control-Allow-Methods: POST, GET, OPTIONS'); | |
header('Access-Control-Allow-Headers: Content-Type'); | |
// Handle preflight requests | |
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { | |
http_response_code(200); | |
exit(0); | |
} | |
// Function to send JSON response and exit | |
function sendJsonResponse($data, $httpCode = 200) { | |
http_response_code($httpCode); | |
echo json_encode($data, JSON_UNESCAPED_UNICODE); | |
exit; | |
} | |
// Function to log errors | |
function logError($message) { | |
error_log("[Newsletter Error] " . $message); | |
} | |
try { | |
// Configurare SQLite - fișierul bazei de date | |
$db_file = __DIR__ . '/newsletter.db'; | |
// Create directory if it doesn't exist | |
$dir = dirname($db_file); | |
if (!is_dir($dir)) { | |
if (!mkdir($dir, 0755, true)) { | |
throw new Exception("Nu se poate crea directorul pentru baza de date: $dir"); | |
} | |
} | |
// Verifică dacă directorul este scris | |
if (!is_writable($dir)) { | |
throw new Exception("Directorul nu este scris. Setează permisiuni 755 pentru director: $dir"); | |
} | |
// Check if SQLite3 extension is loaded | |
if (!extension_loaded('sqlite3')) { | |
throw new Exception('Extensia SQLite3 nu este instalată pe server'); | |
} | |
// Verifică dacă fișierul bazei de date există | |
$db_exists = file_exists($db_file); | |
// Conectare la SQLite (creează automat fișierul dacă nu există) | |
$db = new SQLite3($db_file); | |
if (!$db) { | |
throw new Exception('Nu se poate conecta la baza de date SQLite'); | |
} | |
// Activează exceptiile pentru erori | |
$db->enableExceptions(true); | |
// Setează permisiuni pentru fișierul bazei de date | |
if (!$db_exists && file_exists($db_file)) { | |
chmod($db_file, 0666); | |
} | |
// Creează tabela dacă nu există | |
$create_table = " | |
CREATE TABLE IF NOT EXISTS newsletter_emails ( | |
id INTEGER PRIMARY KEY AUTOINCREMENT, | |
email TEXT UNIQUE NOT NULL, | |
created_at DATETIME DEFAULT CURRENT_TIMESTAMP, | |
ip_address TEXT | |
) | |
"; | |
$result = $db->exec($create_table); | |
// Verifică dacă tabela a fost creată cu succes | |
if ($result === FALSE) { | |
throw new Exception('Nu s-a putut crea tabela newsletter_emails'); | |
} | |
// Log pentru debugging (doar când se creează prima dată) | |
if (!$db_exists) { | |
logError("Baza de date SQLite creată cu succes la: " . $db_file); | |
} | |
} catch (Exception $e) { | |
logError("Database connection error: " . $e->getMessage()); | |
sendJsonResponse([ | |
'success' => false, | |
'message' => 'Eroare la conectarea bazei de date: ' . $e->getMessage(), | |
'debug_info' => [ | |
'db_file' => $db_file ?? 'N/A', | |
'dir_writable' => is_writable(dirname($db_file ?? __DIR__)), | |
'sqlite3_loaded' => extension_loaded('sqlite3') | |
] | |
], 500); | |
} | |
// Procesare cerere POST (abonare) | |
if ($_SERVER['REQUEST_METHOD'] === 'POST') { | |
try { | |
// Get input data | |
$raw_input = file_get_contents('php://input'); | |
if (empty($raw_input)) { | |
sendJsonResponse([ | |
'success' => false, | |
'message' => 'Nu s-au primit date' | |
], 400); | |
} | |
$input = json_decode($raw_input, true); | |
if (json_last_error() !== JSON_ERROR_NONE) { | |
sendJsonResponse([ | |
'success' => false, | |
'message' => 'Date JSON invalide: ' . json_last_error_msg() | |
], 400); | |
} | |
// Validare input | |
if (empty($input['email'])) { | |
sendJsonResponse([ | |
'success' => false, | |
'message' => 'Email-ul este obligatoriu' | |
], 400); | |
} | |
$email = trim($input['email']); | |
// Validare email | |
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { | |
sendJsonResponse([ | |
'success' => false, | |
'message' => 'Adresa de email nu este validă' | |
], 400); | |
} | |
// Verifică dacă email-ul există deja | |
$check_stmt = $db->prepare("SELECT id FROM newsletter_emails WHERE email = :email"); | |
$check_stmt->bindValue(':email', $email, SQLITE3_TEXT); | |
$check_result = $check_stmt->execute(); | |
if ($check_result->fetchArray()) { | |
sendJsonResponse([ | |
'success' => false, | |
'message' => 'Acest email este deja abonat' | |
], 409); | |
} | |
// Obține IP-ul utilizatorului | |
$user_ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0'; | |
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { | |
$user_ip = $_SERVER['HTTP_X_FORWARDED_FOR']; | |
} elseif (isset($_SERVER['HTTP_X_REAL_IP'])) { | |
$user_ip = $_SERVER['HTTP_X_REAL_IP']; | |
} | |
// Inserează email-ul în baza de date | |
$insert_stmt = $db->prepare(" | |
INSERT INTO newsletter_emails (email, created_at, ip_address) | |
VALUES (:email, datetime('now'), :ip_address) | |
"); | |
$insert_stmt->bindValue(':email', $email, SQLITE3_TEXT); | |
$insert_stmt->bindValue(':ip_address', $user_ip, SQLITE3_TEXT); | |
if ($insert_stmt->execute()) { | |
$subscriber_id = $db->lastInsertRowID(); | |
// Log pentru debugging | |
logError("Newsletter subscription: Email = $email, IP = $user_ip, ID = $subscriber_id"); | |
sendJsonResponse([ | |
'success' => true, | |
'message' => 'Te-ai abonat cu succes!', | |
'subscriber_id' => $subscriber_id | |
]); | |
} else { | |
throw new Exception('Nu s-a putut salva în baza de date'); | |
} | |
} catch (Exception $e) { | |
logError("POST request error: " . $e->getMessage()); | |
sendJsonResponse([ | |
'success' => false, | |
'message' => 'Eroare la procesarea cererii: ' . $e->getMessage() | |
], 500); | |
} | |
} | |
// Procesare cerere GET (vizualizare abonați - pentru admin) | |
elseif ($_SERVER['REQUEST_METHOD'] === 'GET') { | |
try { | |
// Vizualizare toți abonații | |
if (isset($_GET['admin']) && $_GET['admin'] === 'view') { | |
$query = "SELECT id, email, created_at, ip_address FROM newsletter_emails ORDER BY created_at DESC"; | |
$result = $db->query($query); | |
$emails = []; | |
while ($row = $result->fetchArray(SQLITE3_ASSOC)) { | |
$emails[] = [ | |
'id' => $row['id'], | |
'email' => $row['email'], | |
'created_at' => $row['created_at'], | |
'ip_address' => $row['ip_address'] | |
]; | |
} | |
sendJsonResponse([ | |
'success' => true, | |
'emails' => $emails, | |
'total' => count($emails) | |
]); | |
} | |
// Export CSV pentru admin | |
elseif (isset($_GET['export']) && $_GET['export'] === 'csv') { | |
$query = "SELECT email, created_at FROM newsletter_emails ORDER BY created_at DESC"; | |
$result = $db->query($query); | |
// Set headers pentru download CSV | |
header('Content-Type: text/csv; charset=utf-8'); | |
header('Content-Disposition: attachment; filename=newsletter_subscribers_' . date('Y-m-d') . '.csv'); | |
// Creează output CSV | |
$output = fopen('php://output', 'w'); | |
// Header CSV | |
fputcsv($output, ['Email', 'Data Abonarii'], ';'); | |
// Date | |
while ($row = $result->fetchArray(SQLITE3_ASSOC)) { | |
fputcsv($output, [$row['email'], $row['created_at']], ';'); | |
} | |
fclose($output); | |
$db->close(); | |
exit; | |
} | |
// Statistici simple | |
elseif (isset($_GET['stats'])) { | |
// Numărul total de abonați | |
$total_result = $db->querySingle("SELECT COUNT(*) FROM newsletter_emails"); | |
// Abonați din ultima săptămână | |
$week_result = $db->querySingle(" | |
SELECT COUNT(*) FROM newsletter_emails | |
WHERE created_at >= datetime('now', '-7 days') | |
"); | |
// Abonați din ultima lună | |
$month_result = $db->querySingle(" | |
SELECT COUNT(*) FROM newsletter_emails | |
WHERE created_at >= datetime('now', '-30 days') | |
"); | |
// Ultimele 5 abonări | |
$recent_query = "SELECT email, created_at FROM newsletter_emails ORDER BY created_at DESC LIMIT 5"; | |
$recent_result = $db->query($recent_query); | |
$recent_subscribers = []; | |
while ($row = $recent_result->fetchArray(SQLITE3_ASSOC)) { | |
$recent_subscribers[] = $row; | |
} | |
sendJsonResponse([ | |
'success' => true, | |
'stats' => [ | |
'total_subscribers' => $total_result, | |
'this_week' => $week_result, | |
'this_month' => $month_result, | |
'growth_rate' => $total_result > 0 ? round(($week_result / $total_result) * 100, 2) : 0, | |
'recent_subscribers' => $recent_subscribers | |
] | |
]); | |
} | |
// Șterge un abonat (pentru admin) | |
elseif (isset($_GET['delete']) && !empty($_GET['id'])) { | |
$id = intval($_GET['id']); | |
$delete_stmt = $db->prepare("DELETE FROM newsletter_emails WHERE id = :id"); | |
$delete_stmt->bindValue(':id', $id, SQLITE3_INTEGER); | |
if ($delete_stmt->execute()) { | |
sendJsonResponse([ | |
'success' => true, | |
'message' => 'Abonatul a fost șters cu succes' | |
]); | |
} else { | |
throw new Exception('Nu s-a putut șterge abonatul'); | |
} | |
} | |
// Test endpoint | |
elseif (isset($_GET['test'])) { | |
sendJsonResponse([ | |
'success' => true, | |
'message' => 'Newsletter API funcționează!', | |
'server_info' => [ | |
'php_version' => PHP_VERSION, | |
'sqlite3_version' => SQLite3::version()['versionString'], | |
'db_file' => $db_file, | |
'db_exists' => file_exists($db_file), | |
'dir_writable' => is_writable(dirname($db_file)) | |
] | |
]); | |
} | |
else { | |
sendJsonResponse([ | |
'success' => false, | |
'message' => 'Parametri GET nevalizi. Folosește ?test pentru testare.' | |
], 400); | |
} | |
} catch (Exception $e) { | |
logError("GET request error: " . $e->getMessage()); | |
sendJsonResponse([ | |
'success' => false, | |
'message' => 'Eroare la procesarea cererii: ' . $e->getMessage() | |
], 500); | |
} | |
} | |
// Metodă HTTP nesuportată | |
else { | |
sendJsonResponse([ | |
'success' => false, | |
'message' => 'Metodă HTTP nesuportată: ' . $_SERVER['REQUEST_METHOD'] | |
], 405); | |
} | |
// Închide conexiunea | |
if (isset($db)) { | |
$db->close(); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment