T.ME/BIBIL_0DAY
CasperSecurity


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/.cursor-server/data/User/History/33ee19dd/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /home/gositeme/.cursor-server/data/User/History/33ee19dd/sCq5.php
<?php
/**
 * Subscription Helper Functions
 * Functions to check subscription status and monthly track limits
 */

require_once __DIR__ . '/../config/database.php';

/**
 * Check if user has active subscription
 */
function hasActiveSubscription($user_id) {
    try {
        $pdo = getDBConnection();
        
        // Check if table exists first
        $table_check = $pdo->query("SHOW TABLES LIKE 'user_subscriptions'");
        if ($table_check->rowCount() === 0) {
            error_log("hasActiveSubscription: user_subscriptions table does not exist");
            return false; // Table doesn't exist, so no subscriptions
        }
        
        $stmt = $pdo->prepare("
            SELECT id, plan_name, status, current_period_start, current_period_end
            FROM user_subscriptions
            WHERE user_id = ?
            AND status IN ('active', 'trialing')
            AND current_period_end > NOW()
            ORDER BY created_at DESC
            LIMIT 1
        ");
        $stmt->execute([$user_id]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        return $result ? $result : false;
    } catch (PDOException $e) {
        error_log("hasActiveSubscription PDO error: " . $e->getMessage());
        return false; // Return false on error instead of throwing
    } catch (Exception $e) {
        error_log("hasActiveSubscription error: " . $e->getMessage());
        return false;
    }
}

/**
 * Check if subscription is in a state that allows track creation
 * Returns true if subscription is active/trialing, false if past_due/canceled
 */
function isSubscriptionActiveForUsage($user_id) {
    $pdo = getDBConnection();
    
    $stmt = $pdo->prepare("
        SELECT status
        FROM user_subscriptions
        WHERE user_id = ?
        AND status IN ('active', 'trialing')
        AND current_period_end > NOW()
        ORDER BY created_at DESC
        LIMIT 1
    ");
    $stmt->execute([$user_id]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    
    return $result !== false;
}

/**
 * Get or create monthly track usage record based on subscription period
 */
function getMonthlyTrackUsage($user_id, $plan_name = null) {
    $pdo = getDBConnection();
    
    // Get active subscription to determine current period
    $subscription = hasActiveSubscription($user_id);
    if (!$subscription) {
        return null; // No subscription, no usage tracking
    }
    
    $subscription_id = $subscription['id'] ?? null;
    $period_start = $subscription['current_period_start'] ?? null;
    
    if (!$period_start) {
        return null;
    }
    
    // Convert period_start to datetime string if it's not already
    if (is_numeric($period_start)) {
        $period_start = date('Y-m-d H:i:s', $period_start);
    }
    
    // If plan_name not provided, get it from subscription
    if (!$plan_name) {
        $plan_name = $subscription['plan_name'];
    }
    
    // Get or create usage record for this subscription period
    $stmt = $pdo->prepare("
        SELECT * FROM monthly_track_usage
        WHERE user_id = ? AND subscription_period_start = ?
    ");
    $stmt->execute([$user_id, $period_start]);
    $usage = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$usage) {
        // Determine track limit based on plan
        $track_limit = 0;
        $plans_config = require __DIR__ . '/../config/subscription_plans.php';
        
        if (isset($plans_config[$plan_name])) {
            $track_limit = $plans_config[$plan_name]['tracks_per_month'];
        }
        
        // Create new record for this subscription period
        // Also set year_month for backward compatibility
        $year_month = date('Y-m', strtotime($period_start));
        
        $stmt = $pdo->prepare("
            INSERT INTO monthly_track_usage (
                user_id, subscription_id, subscription_period_start, 
                year_month, tracks_created, track_limit, reset_at
            )
            VALUES (?, ?, ?, ?, 0, ?, NOW())
        ");
        $stmt->execute([
            $user_id, 
            $subscription_id, 
            $period_start, 
            $year_month, 
            $track_limit
        ]);
        
        // Get the created record
        $stmt = $pdo->prepare("
            SELECT * FROM monthly_track_usage
            WHERE user_id = ? AND subscription_period_start = ?
        ");
        $stmt->execute([$user_id, $period_start]);
        $usage = $stmt->fetch(PDO::FETCH_ASSOC);
    }
    
    return $usage;
}

/**
 * Check if user can create a track (monthly limit check)
 * Returns array with 'allowed' => true/false and 'message' => string
 */
function canCreateTrack($user_id) {
    $pdo = getDBConnection();
    
    // Get user info
    $stmt = $pdo->prepare("SELECT plan FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$user) {
        return ['allowed' => false, 'message' => 'User not found'];
    }
    
    // Check if user has active subscription (all subscription tiers)
    $subscription = hasActiveSubscription($user_id);
    
    if ($subscription) {
        // Check if subscription status allows usage (exclude past_due, unpaid, canceled)
        if (!in_array($subscription['status'], ['active', 'trialing'])) {
            // Subscription exists but not in usable state
            return [
                'allowed' => false,
                'message' => "Your subscription is {$subscription['status']}. Please update your payment method or contact support.",
                'status' => $subscription['status']
            ];
        }
        
        // User has subscription - check monthly limit for all subscription tiers
        $subscription_plans = ['essential', 'starter', 'pro', 'premium', 'enterprise'];
        
        if (in_array(strtolower($subscription['plan_name']), $subscription_plans)) {
            $usage = getMonthlyTrackUsage($user_id, $subscription['plan_name']);
            
            if (!$usage) {
                return [
                    'allowed' => false,
                    'message' => 'Unable to retrieve subscription usage. Please contact support.',
                ];
            }
            
            if ($usage['tracks_created'] >= $usage['track_limit']) {
                // Subscription limit reached - check if user has credits to fall back to
                $stmt = $pdo->prepare("SELECT credits FROM users WHERE id = ?");
                $stmt->execute([$user_id]);
                $user_credits = $stmt->fetch(PDO::FETCH_ASSOC);
                
                if ($user_credits && $user_credits['credits'] >= 1) {
                    // User has credits available - allow using credits
                    return [
                        'allowed' => true,
                        'system' => 'credits',
                        'tracks_used' => $usage['tracks_created'],
                        'track_limit' => $usage['track_limit'],
                        'subscription_limit_reached' => true,
                        'message' => "You've reached your monthly subscription limit. Using your available credits instead."
                    ];
                }
                
                // No credits available - block creation
                $subscription = hasActiveSubscription($user_id);
                $next_reset = 'the start of your next billing period';
                if ($subscription && isset($subscription['current_period_end'])) {
                    $period_end = $subscription['current_period_end'];
                    if (is_numeric($period_end)) {
                        $period_end = date('Y-m-d H:i:s', $period_end);
                    }
                    $next_reset = date('F j, Y', strtotime($period_end));
                }
                
                return [
                    'allowed' => false,
                    'message' => "You've reached your monthly limit of {$usage['track_limit']} tracks. Your limit will reset on {$next_reset} (your next billing date). You can purchase extra credits if you need more tracks now.",
                    'tracks_used' => $usage['tracks_created'],
                    'track_limit' => $usage['track_limit']
                ];
            }
            
            return [
                'allowed' => true,
                'tracks_used' => $usage['tracks_created'],
                'track_limit' => $usage['track_limit'],
                'tracks_remaining' => $usage['track_limit'] - $usage['tracks_created']
            ];
        }
    }
    
    // For non-subscription plans (free, or credit-based), use credit system
    return ['allowed' => true, 'system' => 'credits'];
}

/**
 * Increment monthly track usage for current subscription period
 */
function incrementMonthlyTrackUsage($user_id) {
    $pdo = getDBConnection();
    
    // Get active subscription to find current period
    $subscription = hasActiveSubscription($user_id);
    if (!$subscription) {
        return false;
    }
    
    $period_start = $subscription['current_period_start'] ?? null;
    if (!$period_start) {
        return false;
    }
    
    // Convert period_start to datetime string if needed
    if (is_numeric($period_start)) {
        $period_start = date('Y-m-d H:i:s', $period_start);
    }
    
    $stmt = $pdo->prepare("
        UPDATE monthly_track_usage
        SET tracks_created = tracks_created + 1,
            updated_at = NOW()
        WHERE user_id = ? AND subscription_period_start = ?
    ");
    $stmt->execute([$user_id, $period_start]);
    
    return $stmt->rowCount() > 0;
}

/**
 * Get subscription info for user
 */
function getSubscriptionInfo($user_id) {
    try {
        $pdo = getDBConnection();
        
        $stmt = $pdo->prepare("
            SELECT 
                us.*,
                u.name as user_name,
                u.email as user_email
            FROM user_subscriptions us
            JOIN users u ON us.user_id = u.id
            WHERE us.user_id = ?
            ORDER BY us.created_at DESC
            LIMIT 1
        ");
        $stmt->execute([$user_id]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        return $result ? $result : null;
    } catch (Exception $e) {
        error_log("Error in getSubscriptionInfo: " . $e->getMessage());
        return null;
    }
}
?>


CasperSecurity Mini