# firebox/3.1.14/Inc/Core/Analytics/Ajax/Main.php

FireBox – WooCommerce Popup Builder, Exit Intent Popup, Email Optin &amp; Cart Abandonment, version 3.1.14. 642 lines.

- Page: https://pluginprobe.com/plugins/firebox/3.1.14/code/Inc/Core/Analytics/Ajax/Main.php
- Raw: https://pluginprobe.com/plugins/firebox/3.1.14/raw/Inc/Core/Analytics/Ajax/Main.php
- Modified: 2026-10-02T13:37:30+00:00

Line numbers below start at 1. Link to a line or a range by appending a fragment to the
page URL, for example `https://pluginprobe.com/plugins/firebox/3.1.14/code/Inc/Core/Analytics/Ajax/Main.php#L10-L20`.

```php
<?php
/**
 * @package         FireBox
 * @version         3.1.14 Free
 * 
 * @author          FirePlugins <info@fireplugins.com>
 * @link            https://www.fireplugins.com
 * @copyright       Copyright © 2026 FirePlugins All Rights Reserved
 * @license         GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> or later
*/

namespace FireBox\Core\Analytics\Ajax;

if (!defined('ABSPATH'))
{
	exit; // Exit if accessed directly.
}

class Main
{
    use Shared;
    
    public function __construct()
    {
        add_action('wp_ajax_firebox_analytics_stats', [$this, 'firebox_analytics_stats']);

        add_action('wp_ajax_firebox_analytics_get_campaigns', [$this, 'firebox_analytics_get_campaigns']);

        add_action('wp_ajax_firebox_analytics_get_dropdown_campaigns', [$this, 'firebox_analytics_get_dropdown_campaigns']);

        add_action('wp_ajax_firebox_delete_campaign', [$this, 'firebox_delete_campaign']);

        add_action('wp_ajax_firebox_duplicate_campaign', [$this, 'firebox_duplicate_campaign']);

        add_action('wp_ajax_firebox_analytics_get_charts_data', [$this, 'firebox_analytics_get_charts_data']);

        add_action('wp_ajax_firebox_analytics_get_trending_templates', [$this, 'firebox_analytics_get_trending_templates']);
    }

    /**
     * Analytics Counts
     * 
     * @return  void
     */
    public function firebox_analytics_stats()
    {
		if (!current_user_can('read_fireboxes'))
		{
			return;
        }
        
        $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
        
        // verify nonce
        if (!$verify = wp_verify_nonce($nonce, 'fpf_js_nonce'))
        {
            return false;
		}

        $date_period = isset($_POST['date_period']) ? sanitize_text_field(wp_unslash($_POST['date_period'])) : '';
        $start_date = isset($_POST['start_date']) ? sanitize_text_field(wp_unslash($_POST['start_date'])) : '';
        $end_date = isset($_POST['end_date']) ? sanitize_text_field(wp_unslash($_POST['end_date'])) : '';

        if (!$start_date || $start_date === 'false' || !$end_date || $end_date === 'false')
        {
            return;
        }
        
        $selected_campaign = isset($_POST['selected_campaign']) && !empty($_POST['selected_campaign']) ? intval(wp_unslash($_POST['selected_campaign'])) : '';

        $metrics = [
            'views',
            'clicks',
            'conversions',
            'conversionrate',
            'revenue'
        ];

        $filters = [];
        if ($selected_campaign)
        {
            $filters['campaign'] = [
                'value' => [$selected_campaign]
            ];
        }

        $cache_key = 'firebox_analytics_' . md5(serialize([
            'stats',
            $metrics,
            $filters,
            $start_date,
            $end_date
        ]));

        $cache_ttl = $this->getAnalyticsCacheTtl($end_date);

        if ($cache_ttl)
        {
            $cached = get_transient($cache_key);
            if ($cached !== false)
            {
                echo wp_json_encode($cached);
                wp_die();
            }
        }

        $data = new \FireBox\Core\Analytics\Data($start_date, $end_date);

        // Use new fluent interface
        $data->metrics($metrics)->filters($filters);

        // Get current period data
        $currentData = $data->getData('count');

        

        // Calculate previous period data
        $start_date_ts = strtotime($start_date);
        $end_date_ts = strtotime($end_date);
        $days_between = ceil(abs($end_date_ts - $start_date_ts) / 86400);

        $previousPeriodData = [
            'views' => 0,
            'clicks' => 0,
            'conversions' => 0,
            'conversionrate' => 0,
            'revenue' => 0,
            'view_through_revenue' => 0,
            'conversion_through_revenue' => 0
        ];

        if ($previousPeriodDates = $this->getPreviousPeriodDates($start_date, $days_between))
        {
            $previousData = new \FireBox\Core\Analytics\Data($previousPeriodDates[0], $previousPeriodDates[1]);

            $previousMetrics = [
                'views',
                'conversions',
                'conversionrate',
                
            ];

            // Use new fluent interface
            $previousData->metrics($previousMetrics)->filters($filters);

            $previousPeriodData = $previousData->getData('count');

            
        }

        $response = [
            'current' => $currentData,
            'previous' => $previousPeriodData
        ];

        if ($cache_ttl)
        {
            set_transient($cache_key, $response, $cache_ttl);
        }

        echo wp_json_encode($response);
        wp_die();
    }

    /**
     * Analytics Get All Dropdown Campaigns
     * 
     * @return  void
     */
    public function firebox_analytics_get_dropdown_campaigns()
    {
		if (!current_user_can('read_fireboxes'))
		{
			return;
        }
        
        $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
        
        // verify nonce
        if (!$verify = wp_verify_nonce($nonce, 'fpf_js_nonce'))
        {
            return false;
		}

        if (!current_user_can('read_fireboxes'))
        {
            echo wp_json_encode([
                'permission_denied' => true
            ]);
            wp_die();
        }
        
        $boxes = \FireBox\Core\Helpers\BoxHelper::getAllBoxes(['draft', 'publish']);
		$boxes = $boxes->posts;

		if (!count($boxes))
		{
            echo wp_json_encode([]);
            wp_die();
		}

		$data = [
            [
                'id' => null,
                'label' => 'All Campaigns'
            ]
        ];
		
		foreach ($boxes as $box)
		{
			$data[] = [
				'id' => $box->ID,
				'label' => $box->post_title
			];
		}

        echo wp_json_encode($data);
        wp_die();
    }

    /**
     * Analytics Get Chart Data
     * 
     * @return  void
     */
    public function firebox_analytics_get_charts_data()
    {
		if (!current_user_can('read_fireboxes'))
		{
			return;
        }
        
        $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
        
        // verify nonce
        if (!$verify = wp_verify_nonce($nonce, 'fpf_js_nonce'))
        {
            return false;
		}

        $start_date = isset($_POST['start_date']) ? sanitize_text_field(wp_unslash($_POST['start_date'])) : '';
        $end_date = isset($_POST['end_date']) ? sanitize_text_field(wp_unslash($_POST['end_date'])) : '';

        if (!$start_date || $start_date === 'false' || !$end_date || $end_date === 'false')
        {
            return;
        }

        $filter = isset($_POST['filter']) ? sanitize_text_field(wp_unslash($_POST['filter'])) : 'list';

        $start_date_ts = strtotime($start_date);
        $end_date_ts = strtotime($end_date);
        $days_between = ceil(abs($end_date_ts - $start_date_ts) / 86400);

        // prepare labels
        $labels = [];

        // We are fetching data for a single day
        if ($days_between == 1)
        {
            for ($hour = 0; $hour < 24; $hour++)
            {
                $start_hour = sprintf('%02d', $hour);
                $labels[] = $start_hour . ':00';
            }
        }
        // Multiple days
        else if ($days_between > 1)
        {
            switch ($filter)
            {
                case 'list':
                default:
                    $tmp_start_date_ts = $start_date_ts;
                    for ($i = 0; $i < $days_between; $i++)
                    {
                        $labels[] = gmdate('Y-m-d', $tmp_start_date_ts);
                        $tmp_start_date_ts = strtotime("+1 day", $tmp_start_date_ts);
                    }
                    break;
                
                case 'weekly':
                    $startDate = new \DateTime();
                    $startDate->setTimestamp($start_date_ts);

                    $endDate = new \DateTime();
                    $endDate->setTimestamp($end_date_ts);

                    // Find the nearest Monday to the start date
                    while ($startDate->format('N') != 1)
                    {
                        $startDate->modify('-1 day');
                    }

                    while ($startDate <= $endDate)
                    {
                        $labels[] = $startDate->format('d M y');
                        $startDate->modify('+1 week');
                    }
                    break;
                
                case 'monthly':
                    $startDate = new \DateTime();
                    $startDate->setTimestamp($start_date_ts);

                    $endDate = new \DateTime();
                    $endDate->setTimestamp($end_date_ts);

                    // Set the start date to the first day of the month
                    $startDate->modify('first day of this month');

                    while ($startDate <= $endDate)
                    {
                        $labels[] = $startDate->format('M Y');
                        $startDate->modify('+1 month');
                    }
                    break;
            }
        }
        
		$selected_campaign = isset($_POST['selected_campaign']) && !empty($_POST['selected_campaign']) ? intval(wp_unslash($_POST['selected_campaign'])) : '';

        $metrics = [
            'views',
            'clicks',
            'conversions',
            'conversionrate',
            'revenue'
        ];

        $filters = [];
        if ($selected_campaign)
        {
            $filters = [
                'campaign' => [
                    'value' => [$selected_campaign]
                ]
            ];
        }

        $cache_key = 'firebox_analytics_' . md5(serialize([
            'charts',
            $metrics,
            $filters,
            $filter,
            $start_date,
            $end_date
        ]));

        $cache_ttl = $this->getAnalyticsCacheTtl($end_date);

        if ($cache_ttl)
        {
            $cached = get_transient($cache_key);
            if ($cached !== false)
            {
                echo wp_json_encode($cached);
                wp_die();
            }
        }

        $data = new \FireBox\Core\Analytics\Data($start_date, $end_date);

        // Use new fluent interface
        $data->metrics($metrics)->filters($filters);

        $chartData = $data->getData($filter);

        $revenueBreakdownByLabel = [];
        
        

        $response = [
            'labels' => $labels,
            'data' => $chartData,
            'revenue_breakdown' => $revenueBreakdownByLabel
        ];

        if ($cache_ttl)
        {
            set_transient($cache_key, $response, $cache_ttl);
        }

        echo wp_json_encode($response);
        wp_die();
    }

    /**
     * Analytics Get Latest 5 Campaigns
     * 
     * @return  void
     */
    public function firebox_analytics_get_campaigns()
    {
		if (!current_user_can('read_fireboxes'))
		{
			return;
        }
        
        $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
        
        // verify nonce
        if (!$verify = wp_verify_nonce($nonce, 'fpf_js_nonce'))
        {
            return false;
		}
        
        if (!current_user_can('read_fireboxes'))
        {
            echo wp_json_encode([
                'permission_denied' => true
            ]);
            wp_die();
        }

        $boxes = \FireBox\Core\Analytics\Helpers\Campaigns::getRecentCampaignsList(5);

		if (!count($boxes->posts))
		{
            echo wp_json_encode([]);
            wp_die();
		}

        $start_date = isset($_POST['start_date']) ? sanitize_text_field(wp_unslash($_POST['start_date'])) : '';
        $end_date = isset($_POST['end_date']) ? sanitize_text_field(wp_unslash($_POST['end_date'])) : '';
		
		$data = [];
		
		foreach ($boxes->posts as $box)
		{
            $meta = \FireBox\Core\Helpers\BoxHelper::getMeta($box->ID);

			$data[] = [
				'id' => $box->ID,
				'label' => $box->post_title,
				'status' => $box->post_status,
				'trigger' => isset($meta['triggermethod']) ? $meta['triggermethod'] : '',
				'position' => isset($meta['position']) ? $meta['position'] : '',
				'totals' => $this->getBoxAnalyticsTotals($box->ID, $start_date, $end_date)
			];
		}

        echo wp_json_encode($data);
        wp_die();
    }

    /**
     * Delete a campaign by ID.
     * 
     * @return  void
     */
    public function firebox_delete_campaign()
    {
		if (!current_user_can('delete_fireboxes'))
		{
			return;
        }
        
        $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
        
        // verify nonce
        if (!$verify = wp_verify_nonce($nonce, 'fpf_js_nonce'))
        {
            return false;
		}

        $id = isset($_POST['id']) ? intval($_POST['id']) : '';
        if (!$id)
        {
            return;
        }
		
        /**
         * "delete_fireboxes" is a global capability, so on its own it would authorise
         * deleting any post in the site. Confirm the target really is a campaign and
         * that this user may delete this specific one.
         */
        if (!self::userCanActOnCampaign($id, 'delete_post'))
        {
            echo wp_json_encode([
                'error' => true
            ]);
            wp_die();
        }

        $error = false;

        if (!wp_delete_post($id, true))
        {
            $error = true;
        }
        
        echo wp_json_encode([
            'error' => $error
        ]);
        wp_die();
    }

    /**
     * Duplicate a campaign by ID.
     * 
     * @return  void
     */
    public function firebox_duplicate_campaign()
    {
		if (!current_user_can('edit_fireboxes'))
		{
			return;
        }
        
        $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
        
        // verify nonce
        if (!$verify = wp_verify_nonce($nonce, 'fpf_js_nonce'))
        {
            return false;
		}

        $id = isset($_POST['id']) ? intval($_POST['id']) : '';
        if (!$id)
        {
            return;
        }
		
        /**
         * Same reasoning as firebox_delete_campaign(): without this a global capability
         * would allow duplicating — and therefore reading — any post in the site.
         */
        if (!self::userCanActOnCampaign($id, 'edit_post'))
        {
            echo wp_json_encode([
                'error' => true
            ]);
            wp_die();
        }

        $error = false;

        if (!\FireBox\Core\Helpers\BoxHelper::duplicateBox($id))
        {
            $error = true;
        }

        echo wp_json_encode([
            'error' => $error
        ]);
        wp_die();
    }

    /**
     * Returns whether the given ID is a campaign the current user may act on.
     *
     * @param   int     $id          Post ID.
     * @param   string  $capability  Meta capability to check, i.e. edit_post/delete_post.
     *
     * @return  bool
     */
    private static function userCanActOnCampaign($id, $capability)
    {
        $id = (int) $id;

        if (!$id || get_post_type($id) !== 'firebox')
        {
            return false;
        }

        return current_user_can($capability, $id);
    }

    /**
     * Retrieve trending templates.
     * 
     * @return  void
     */
    public function firebox_analytics_get_trending_templates()
    {
		if (!current_user_can('read_fireboxes'))
		{
			return;
        }
        
        $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
        
        // verify nonce
        if (!$verify = wp_verify_nonce($nonce, 'fpf_js_nonce'))
        {
            return false;
		}

        $templates = \FPFramework\Helpers\Templates::getTemplates('firebox');

        if (!isset($templates->templates))
        {
            echo wp_json_encode([
                'templates' => []
            ]);
            wp_die();
        }

        $templates = $templates->templates;

        // Find top trending templates
        usort($templates, function($a, $b) {
            return $b->sort->trending - $a->sort->trending;
        });

        // First top 6 trending templates
        $templates = array_slice($templates, 0, 6);

        echo wp_json_encode($templates);
        wp_die();
    }

    private function getBoxAnalyticsTotals($id = null, $start_date = null, $end_date = null)
    {
        if (!$id || !$start_date || !$end_date)
        {
            return;
        }

        $data = new \FireBox\Core\Analytics\Data($start_date, $end_date);

        $metrics = [
            'views',
            'clicks',
            'conversions',
            'conversionrate'
        ];

    	$filters = [
            'campaign' => [
                'value' => [$id]
            ]
        ];
        
        // Use new fluent interface
        $data->metrics($metrics)->filters($filters);

        return $data->getData('count');
    }
}

```
