![]() Server : Apache/2 System : Linux server-15-235-50-60 5.15.0-164-generic #174-Ubuntu SMP Fri Nov 14 20:25:16 UTC 2025 x86_64 User : gositeme ( 1004) PHP Version : 8.2.29 Disable Function : exec,system,passthru,shell_exec,proc_close,proc_open,dl,popen,show_source,posix_kill,posix_mkfifo,posix_getpwuid,posix_setpgid,posix_setsid,posix_setuid,posix_setgid,posix_seteuid,posix_setegid,posix_uname Directory : /home/gositeme/domains/soundstudiopro.com/public_html/ |
<?php
/**
* Unified Subscription Signup Page
* Handles all subscription tiers: Essential, Starter, Pro, Premium
*/
// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 0); // CRITICAL: Disable display to prevent "headers already sent" errors
ini_set('log_errors', 1);
ini_set('max_execution_time', 30); // Prevent infinite loops
// Start output buffering BEFORE session_start to prevent any output
if (ob_get_level() === 0) {
ob_start();
}
session_start();
// CRITICAL: Handle POST requests FIRST, before any includes or database queries
// This ensures redirects work without any output interference
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_subscription'])) {
// Only load minimum required files for POST processing
if (!file_exists(__DIR__ . '/config/database.php')) {
error_log("Subscribe.php FATAL: config/database.php not found");
die("Configuration error. Please contact support.");
}
require_once __DIR__ . '/config/database.php';
if (!file_exists(__DIR__ . '/config/subscription_plans.php')) {
error_log("Subscribe.php FATAL: subscription_plans.php not found");
die("Configuration error. Please contact support.");
}
$plans_config = require __DIR__ . '/config/subscription_plans.php';
if (!file_exists(__DIR__ . '/utils/subscription_helpers.php')) {
error_log("Subscribe.php FATAL: subscription_helpers.php not found");
die("Configuration error. Please contact support.");
}
require_once __DIR__ . '/utils/subscription_helpers.php';
// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
while (ob_get_level() > 0) {
ob_end_clean();
}
header('Location: /auth/login.php?redirect=' . urlencode('/subscribe.php' . (!empty($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : '')));
exit;
}
// Get plan from query string
$plan_key = isset($_GET['plan']) ? trim(strtolower($_GET['plan'])) : 'essential';
if (!isset($plans_config[$plan_key])) {
$plan_key = 'essential';
}
$plan = $plans_config[$plan_key] ?? $plans_config['essential'];
$plan['stripe_price_id'] = $plan['stripe_price_id'] ?? '';
// Get database connection
try {
$pdo = getDBConnection();
if (!$pdo) {
throw new Exception("Database connection failed");
}
} catch (Exception $e) {
error_log("Subscribe.php: Database connection error: " . $e->getMessage());
die("Database connection error. Please try again later.");
}
// Get user info
try {
$stmt = $pdo->prepare("SELECT id, name, email, plan, stripe_customer_id FROM users WHERE id = ?");
$stmt->execute([$_SESSION['user_id']]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (Exception $e) {
error_log("Subscribe.php: Error fetching user: " . $e->getMessage());
die("Error loading user data. Please try again.");
}
if (!$user) {
while (ob_get_level() > 0) {
ob_end_clean();
}
header('Location: /auth/login.php');
exit;
}
// Now handle the subscription creation (rest of POST logic)
error_log("=== POST REQUEST DETECTED ===");
error_log("POST data: " . print_r($_POST, true));
error_log("User ID: " . $_SESSION['user_id']);
$stripe_secret = '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';
// Check subscription status FRESH
try {
$fresh_subscription_check = hasActiveSubscription($_SESSION['user_id']);
} catch (Exception $e) {
error_log("Subscribe.php: Error in fresh subscription check: " . $e->getMessage());
$fresh_subscription_check = false;
}
// Prevent duplicate subscriptions
if ($fresh_subscription_check && is_array($fresh_subscription_check)) {
while (ob_get_level() > 0) {
ob_end_clean();
}
header('Location: /subscribe.php?plan=' . urlencode($plan_key) . '&error=' . urlencode('You already have an active subscription.'));
exit;
}
// Check if price ID is configured
$price_id = $plan['stripe_price_id'] ?? '';
$is_placeholder = (
empty($price_id) ||
$price_id === 'price_essential_monthly' ||
strpos($price_id, 'YOUR_PRICE_ID') !== false ||
strpos($price_id, 'price_') === false ||
strlen($price_id) < 20
);
if ($is_placeholder) {
while (ob_get_level() > 0) {
ob_end_clean();
}
header('Location: /subscribe.php?plan=' . urlencode($plan_key) . '&error=' . urlencode('Subscription setup required. Please contact support.'));
exit;
}
// Rate limiting
$rate_limit_key = 'last_checkout_attempt_' . $_SESSION['user_id'];
$last_attempt = $_SESSION[$rate_limit_key] ?? 0;
$time_since_last = time() - $last_attempt;
if ($time_since_last < 5) {
while (ob_get_level() > 0) {
ob_end_clean();
}
header('Location: /subscribe.php?plan=' . urlencode($plan_key) . '&error=' . urlencode('Please wait a moment before creating another checkout session.'));
exit;
}
$_SESSION[$rate_limit_key] = time();
try {
$customer_id = !empty($user['stripe_customer_id']) ? $user['stripe_customer_id'] : null;
$checkout_params = [
'mode' => 'subscription',
'line_items[0][price]' => $price_id,
'line_items[0][quantity]' => 1,
'success_url' => 'https://soundstudiopro.com/subscription_success.php?session_id={CHECKOUT_SESSION_ID}',
'cancel_url' => 'https://soundstudiopro.com/subscribe.php?plan=' . urlencode($plan_key) . '&canceled=1',
'metadata[user_id]' => (string)$user['id'],
'metadata[plan]' => $plan_key
];
if ($customer_id) {
$checkout_params['customer'] = $customer_id;
} else {
$checkout_params['customer_email'] = $user['email'];
}
error_log("=== SUBSCRIPTION DEBUG ===");
error_log("Plan Key: {$plan_key}");
error_log("Price ID: {$price_id}");
error_log("User ID: {$user['id']}");
error_log("Checkout Params: " . print_r($checkout_params, true));
error_log("========================");
$ch = curl_init();
if ($ch === false) {
throw new Exception('Failed to initialize cURL');
}
curl_setopt($ch, CURLOPT_URL, 'https://api.stripe.com/v1/checkout/sessions');
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bearer ' . $stripe_secret]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($checkout_params));
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
$response = curl_exec($ch);
$curl_error = curl_error($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($response === false || !empty($curl_error)) {
error_log("cURL error: " . $curl_error);
throw new Exception('Failed to connect to Stripe API: ' . $curl_error);
}
error_log("Stripe API Response (HTTP $http_code): " . substr($response, 0, 500));
if ($http_code !== 200) {
$error_data = json_decode($response, true);
$stripe_error = 'Unknown Stripe API error';
if (isset($error_data['error']['message'])) {
$stripe_error = $error_data['error']['message'];
} elseif (isset($error_data['error'])) {
$stripe_error = is_string($error_data['error']) ? $error_data['error'] : 'Stripe API error';
} else {
$stripe_error = "Stripe API returned HTTP $http_code. Response: " . substr($response, 0, 500);
}
error_log("Stripe subscription error (HTTP $http_code): " . $response);
throw new Exception("Stripe API Error: " . $stripe_error);
}
$session = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
error_log("Stripe JSON decode error: " . json_last_error_msg());
throw new Exception('Invalid JSON response from Stripe: ' . json_last_error_msg());
}
if (!is_array($session) || empty($session)) {
error_log("Stripe returned invalid session object. Response: " . $response);
throw new Exception('Stripe returned invalid session data');
}
error_log("Stripe Checkout Session Created:");
error_log("Session ID: " . ($session['id'] ?? 'N/A'));
error_log("URL: " . ($session['url'] ?? 'N/A'));
if (!isset($session['url']) || empty($session['url'])) {
error_log("Stripe session created but no URL in response. Full response: " . $response);
throw new Exception('Stripe created session but did not return a checkout URL. Session ID: ' . ($session['id'] ?? 'N/A'));
}
// CRITICAL: Clean ALL output buffers before redirect
while (ob_get_level() > 0) {
ob_end_clean();
}
// Double-check no output was sent
if (headers_sent($file, $line)) {
error_log("Subscribe.php CRITICAL: Headers already sent in $file at line $line - cannot redirect!");
$redirect_url = $session['url'];
if (!preg_match('/^https?:\/\//', $redirect_url)) {
$redirect_url = 'https://' . $_SERVER['HTTP_HOST'] . $redirect_url;
}
echo '<!DOCTYPE html><html><head><meta http-equiv="refresh" content="0;url=' . htmlspecialchars($redirect_url) . '"></head><body><script>window.location.href="' . htmlspecialchars($redirect_url, ENT_QUOTES) . '";</script><p>Redirecting to Stripe Checkout... <a href="' . htmlspecialchars($redirect_url) . '">Click here if you are not redirected</a></p></body></html>';
exit;
}
// Perform redirect
$redirect_url = $session['url'];
if (!preg_match('/^https?:\/\//', $redirect_url)) {
$redirect_url = 'https://' . $_SERVER['HTTP_HOST'] . $redirect_url;
}
error_log("Subscribe.php: Redirecting to Stripe Checkout: " . $redirect_url);
header('Location: ' . $redirect_url, true, 302);
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
while (ob_get_level() > 0) {
ob_end_clean();
}
exit;
} catch (Exception $e) {
error_log("Subscription creation error: " . $e->getMessage());
error_log("Exception trace: " . $e->getTraceAsString());
while (ob_get_level() > 0) {
ob_end_clean();
}
header('Location: /subscribe.php?plan=' . urlencode($plan_key) . '&error=' . urlencode($e->getMessage()));
exit;
}
}
// If we get here, it's NOT a POST request - load everything for page rendering
// Check required files exist before requiring
if (!file_exists(__DIR__ . '/config/database.php')) {
error_log("Subscribe.php FATAL: config/database.php not found");
die("Configuration error. Please contact support.");
}
require_once __DIR__ . '/config/database.php';
if (!file_exists(__DIR__ . '/includes/translations.php')) {
error_log("Subscribe.php FATAL: includes/translations.php not found");
die("Configuration error. Please contact support.");
}
require_once __DIR__ . '/includes/translations.php';
// Verify required functions exist
if (!function_exists('getDBConnection')) {
error_log("Subscribe.php FATAL: getDBConnection function not found");
die("Configuration error. Please contact support.");
}
if (!function_exists('t')) {
error_log("Subscribe.php FATAL: t() translation function not found");
die("Configuration error. Please contact support.");
}
if (!function_exists('getPlanLabel')) {
error_log("Subscribe.php FATAL: getPlanLabel function not found");
die("Configuration error. Please contact support.");
}
if (!function_exists('getPlanAudienceLabel')) {
error_log("Subscribe.php FATAL: getPlanAudienceLabel function not found");
die("Configuration error. Please contact support.");
}
// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
// Clean output buffer before redirect
while (ob_get_level() > 0) {
ob_end_clean();
}
header('Location: /auth/login.php?redirect=' . urlencode('/subscribe.php' . (!empty($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : '')));
exit;
}
// Get database connection with timeout protection
try {
$pdo = getDBConnection();
if (!$pdo) {
throw new Exception("Database connection failed");
}
} catch (Exception $e) {
error_log("Subscribe.php: Database connection error: " . $e->getMessage());
die("Database connection error. Please try again later.");
}
// Load plans config with error handling
$plans_config_file = __DIR__ . '/config/subscription_plans.php';
if (!file_exists($plans_config_file)) {
error_log("Subscribe.php: subscription_plans.php file not found");
die("Configuration error. Please contact support.");
}
try {
$plans_config = require $plans_config_file;
} catch (Exception $e) {
error_log("Subscribe.php: Error loading plans config: " . $e->getMessage());
die("Configuration error. Please contact support.");
}
if (!is_array($plans_config)) {
error_log("Subscribe.php: subscription_plans.php did not return an array");
die("Configuration error. Please contact support.");
}
// Get plan from query string - sanitize input
$plan_key = isset($_GET['plan']) ? trim(strtolower($_GET['plan'])) : 'essential';
if (!isset($plans_config[$plan_key])) {
error_log("Subscribe.php: Invalid plan key '{$plan_key}', defaulting to 'essential'");
$plan_key = 'essential';
}
$plan = $plans_config[$plan_key] ?? null;
if (!$plan || !is_array($plan)) {
error_log("Subscribe.php: Plan '{$plan_key}' not found in config");
$plan_key = 'essential';
$plan = $plans_config[$plan_key] ?? null;
if (!$plan) {
die("Configuration error. Please contact support.");
}
}
// Ensure required plan fields exist
$plan['name'] = $plan['name'] ?? 'Plan';
$plan['target_audience'] = $plan['target_audience'] ?? '';
$plan['features'] = $plan['features'] ?? [];
$plan['color'] = $plan['color'] ?? '#667eea';
$plan['price'] = $plan['price'] ?? 0;
$plan['tracks_per_month'] = $plan['tracks_per_month'] ?? 0;
$plan['stripe_price_id'] = $plan['stripe_price_id'] ?? '';
$plan_display_name = getPlanLabel($plan_key, $plan['name']);
// Get user info with error handling
try {
$stmt = $pdo->prepare("SELECT id, name, email, plan, stripe_customer_id FROM users WHERE id = ?");
$stmt->execute([$_SESSION['user_id']]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (Exception $e) {
error_log("Subscribe.php: Error fetching user: " . $e->getMessage());
die("Error loading user data. Please try again.");
}
// Ensure user exists
if (!$user) {
error_log("Subscribe.php: User not found for ID: " . $_SESSION['user_id']);
// Clean output buffer before redirect
while (ob_get_level() > 0) {
ob_end_clean();
}
header('Location: /auth/login.php');
exit;
}
// Check if already subscribed
$subscription_helpers_file = __DIR__ . '/utils/subscription_helpers.php';
if (!file_exists($subscription_helpers_file)) {
error_log("Subscribe.php: subscription_helpers.php file not found");
die("Configuration error. Please contact support.");
}
require_once $subscription_helpers_file;
if (!function_exists('hasActiveSubscription')) {
error_log("Subscribe.php: hasActiveSubscription function not found");
die("Configuration error. Please contact support.");
}
// Check subscription status (for display purposes)
// Wrap in try-catch to prevent page from hanging if table doesn't exist
try {
$existing_subscription = hasActiveSubscription($_SESSION['user_id']);
} catch (Exception $e) {
error_log("Subscribe.php: Error checking subscription status: " . $e->getMessage());
$existing_subscription = false; // Default to no subscription if check fails
}
// Start output buffering for normal page rendering (if not already started)
if (ob_get_level() === 0) {
ob_start();
}
// Check for error message from redirect (if POST failed and redirected back)
$error_message = null;
if (isset($_GET['error'])) {
$error_message = urldecode($_GET['error']);
}
/**
* Translate a plan feature string
*/
function translateFeature($feature) {
if (!is_string($feature)) {
return (string)$feature;
}
// Extract number from "X tracks per month" format
if (preg_match('/^(\d+)\s+tracks\s+per\s+month$/i', $feature, $matches)) {
$translation = t('plan.feature.tracks_per_month');
// Replace :count placeholder if it exists
if (strpos($translation, ':count') !== false) {
return str_replace(':count', $matches[1], $translation);
}
return $translation;
}
// Map exact feature strings to translation keys
$featureMap = [
'Monthly reset' => 'plan.feature.monthly_reset',
'Basic AI models' => 'plan.feature.basic_ai_models',
'Advanced AI models' => 'plan.feature.advanced_ai_models',
'Standard generation speed' => 'plan.feature.standard_speed',
'High-speed generation' => 'plan.feature.high_speed',
'Priority queue access' => 'plan.feature.priority_queue',
'Highest priority queue' => 'plan.feature.highest_priority',
'Personal use license' => 'plan.feature.personal_license',
'Commercial use license' => 'plan.feature.commercial_license',
'Unlimited downloads' => 'plan.feature.unlimited_downloads',
'API access' => 'plan.feature.api_access',
'Full API access' => 'plan.feature.full_api_access',
'Dedicated support' => 'plan.feature.dedicated_support',
'White-label options' => 'plan.feature.white_label',
'Dedicated account manager' => 'plan.feature.account_manager',
'Custom integrations' => 'plan.feature.custom_integrations',
'SLA guarantee' => 'plan.feature.sla_guarantee',
'Cancel anytime' => 'plan.feature.cancel_anytime',
];
// Return translated feature if mapping exists, otherwise return original
if (isset($featureMap[$feature])) {
return t($featureMap[$feature]);
}
// Fallback to original if no translation found
return $feature;
}
// Get page title with fallback
$page_title_key = 'subscribe.page_title';
$page_title = t($page_title_key);
if ($page_title === $page_title_key) {
$page_title = 'Subscribe to ' . htmlspecialchars($plan_display_name);
} else {
// Replace :plan placeholder if it exists
$page_title = str_replace(':plan', htmlspecialchars($plan_display_name), $page_title);
}
$header_file = __DIR__ . '/includes/header.php';
if (!file_exists($header_file)) {
error_log("Subscribe.php: header.php file not found");
die("Configuration error. Please contact support.");
}
// Include header (output buffering already started above if needed)
try {
include $header_file;
} catch (Exception $e) {
if (ob_get_level() > 0) {
ob_end_clean();
}
error_log("Subscribe.php: Error including header: " . $e->getMessage());
die("Error loading page. Please try again.");
}
?>
<main style="max-width: 800px; margin: 40px auto; padding: 20px;">
<div style="background: #2a2a2a; border-radius: 12px; padding: 40px; text-align: center;">
<h1 style="color: white; margin-bottom: 10px;">🎵 <?php
$plan_text = t('subscribe.plan');
if (strpos($plan_text, ':plan') !== false) {
$plan_text = str_replace(':plan', htmlspecialchars($plan_display_name), $plan_text);
}
echo $plan_text;
?></h1>
<p style="color: #a0aec0; font-size: 1.2rem; margin-bottom: 30px;"><?= htmlspecialchars(getPlanAudienceLabel($plan_key, $plan['target_audience'])) ?></p>
<?php if ($existing_subscription && is_array($existing_subscription)): ?>
<div style="background: #2d5016; padding: 20px; border-radius: 8px; margin-bottom: 30px;">
<p style="color: #48bb78; font-size: 1.1rem;">✅ <?= t('subscribe.already_subscribed') ?></p>
<p style="color: white; margin-top: 10px;"><?= t('subscribe.current_plan') ?> <strong><?= ucfirst($existing_subscription['plan_name'] ?? 'Unknown') ?></strong></p>
<p style="color: white;"><?= t('subscribe.status') ?> <strong><?= ucfirst($existing_subscription['status'] ?? 'Unknown') ?></strong></p>
<?php if (isset($existing_subscription['current_period_end'])): ?>
<p style="color: white;"><?= t('subscribe.renews') ?> <strong><?= date('M j, Y', strtotime($existing_subscription['current_period_end'])) ?></strong></p>
<?php endif; ?>
<a href="/manage_subscription.php" style="display: inline-block; margin-top: 15px; padding: 10px 20px; background: #667eea; color: white; text-decoration: none; border-radius: 5px;"><?= t('subscribe.manage_subscription') ?></a>
</div>
<?php else: ?>
<?php if (isset($error_message) && !empty($error_message)): ?>
<div style="background: #5a1a1a; padding: 20px; border-radius: 8px; margin-bottom: 20px; border: 2px solid #e53e3e;">
<p style="color: #e53e3e; font-size: 1.1rem; font-weight: bold; margin-bottom: 10px;">❌ <?= t('subscribe.error') ?></p>
<p style="color: #ff6b6b;"><?= htmlspecialchars($error_message) ?></p>
<?php if (ini_get('display_errors')): ?>
<p style="color: #a0a0a0; font-size: 0.9rem; margin-top: 10px;">Check server logs for more details.</p>
<?php endif; ?>
</div>
<?php endif; ?>
<div style="background: #1a1a1a; padding: 30px; border-radius: 8px; margin-bottom: 30px;">
<div style="font-size: 3rem; color: <?= $plan['color'] ?>; font-weight: bold; margin-bottom: 10px;">
$<?= number_format($plan['price'], 2) ?><span style="font-size: 1.5rem; color: #a0aec0;"><?= t('subscribe.per_month') ?></span>
</div>
<div style="font-size: 1.5rem; color: white; margin-bottom: 30px;">
<?= $plan['tracks_per_month'] ?> <?= t('subscribe.tracks_per_month') ?>
</div>
<ul style="text-align: left; color: white; list-style: none; padding: 0; margin: 20px 0;">
<?php foreach ($plan['features'] as $feature): ?>
<li style="padding: 10px 0; border-bottom: 1px solid #333;">✅ <?= htmlspecialchars(translateFeature($feature)) ?></li>
<?php endforeach; ?>
</ul>
<form method="POST" style="margin-top: 30px;" id="subscribeForm">
<button type="submit" name="create_subscription" value="1" id="subscribeButton" style="padding: 15px 40px; background: <?= $plan['color'] ?>; color: white; border: none; border-radius: 8px; font-size: 1.2rem; cursor: pointer; width: 100%;" onclick="this.disabled=true; this.innerHTML='<?= addslashes(t('subscribe.processing')) ?>'; this.form.submit();">
<?php
$subscribe_text = t('subscribe.subscribe_now');
if (strpos($subscribe_text, ':price') !== false) {
$subscribe_text = str_replace(':price', number_format($plan['price'], 2), $subscribe_text);
}
echo $subscribe_text;
?>
</button>
</form>
<p style="color: #a0aec0; font-size: 0.9rem; margin-top: 15px;">
<?= t('subscribe.stripe_redirect') ?>
</p>
</div>
<?php endif; ?>
<div style="margin-top: 30px; padding-top: 30px; border-top: 1px solid #333;">
<a href="/pricing.php" style="color: #667eea; text-decoration: none; margin-right: 20px;"><?= t('subscribe.view_all_plans') ?></a>
<a href="/account_settings.php" style="color: #667eea; text-decoration: none;"><?= t('subscribe.account_settings') ?></a>
</div>
</div>
</main>
<?php include 'includes/footer.php'; ?>