<?php /*

 Composr
 Copyright (c) Christopher Graham, 2004-2024

 See docs/LICENSE.md for full licensing information.


 NOTE TO PROGRAMMERS:
   Do not edit this file. If you need to make changes, save your changed file to the appropriate *_custom folder
   **** If you ignore this advice, then your website upgrades (e.g. for bug fixes) will likely kill your changes ****

*/

/**
 * @license    http://opensource.org/licenses/cpal_1.0 Common Public Attribution License
 * @copyright  Christopher Graham
 * @package    securitylogging
 */

/**
 * Hook class.
 */
class Hook_admin_stats_security_incidents extends CMSStatsProvider
{
    /**
     * Find metadata about stats categories that are defined by this stats hook.
     *
     * @return ?array Map of metadata (null: hook is disabled)
     */
    public function category_info() : ?array
    {
        if (!addon_installed('securitylogging')) {
            return null;
        }

        return [
            'security' => [
                'label_lang_string' => 'SECURITY',
                'icon' => 'menu/adminzone/audit/security_log',
            ],
        ];
    }

    /**
     * Find metadata about stats graphs that are provided by this stats hook.
     *
     * @param  boolean $for_kpi Whether this is for setting up a KPI
     * @return ?array Map of metadata (null: hook is disabled)
     */
    public function info(bool $for_kpi = false) : ?array
    {
        if (!addon_installed('securitylogging')) {
            return null;
        }

        require_lang('security');

        $ret = [];

        $ret['security_incidents'] = [
            'label' => do_lang_tempcode('SECURITY_LOG'),
            'category' => 'security',
            'filters' => [
                'security_incidents__month_range' => new CMSStatsDateMonthRangeFilter('security_incidents__month_range', do_lang_tempcode('DATE_RANGE'), null, $for_kpi),
                'security_incidents__include_hackattacks' => new CMSStatsTickFilter('security_incidents__include_hackattacks', do_lang_tempcode('SECURITY_ALERTS')),
                'security_incidents__include_failedlogins' => new CMSStatsTickFilter('security_incidents__include_failedlogins', do_lang_tempcode('FAILED_LOGINS')),
            ],
            'pivot' => new CMSStatsDatePivot('security_incidents__pivot', $this->get_date_pivots(!$for_kpi)),
        ];

        if (has_geolocation_data()) {
            $ret['security_incidents_countries'] = [
                'label' => do_lang_tempcode('_COUNTRIES', do_lang_tempcode('SECURITY_LOG')),
                'category' => 'security',
                'filters' => [
                    'security_incidents_countries__month_range' => new CMSStatsDateMonthRangeFilter('security_incidents_countries__month_range', do_lang_tempcode('DATE_RANGE'), null, $for_kpi),
                    'security_incidents_countries__include_hackattacks' => new CMSStatsTickFilter('security_incidents_countries__include_hackattacks', do_lang_tempcode('SECURITY_ALERTS')),
                    'security_incidents_countries__include_failedlogins' => new CMSStatsTickFilter('security_incidents_countries__include_failedlogins', do_lang_tempcode('FAILED_LOGINS')),
                ],
                'pivot' => null,
            ];
        }

        return $ret;
    }

    /**
     * Preprocess raw data in the database into something we can efficiently draw graphs/conclusions from.
     *
     * @param  TIME $start_time Start timestamp
     * @param  TIME $end_time End timestamp
     * @param  array $data_buckets Map of data buckets; a map of bucket name to nested maps with the following maps in sequence: 'month', 'pivot', 'value' (then further map data) ; extended and returned by reference
     */
    public function preprocess_raw_data(int $start_time, int $end_time, array &$data_buckets)
    {
        require_code('temporal');
        require_code('locations');

        $server_timezone = get_server_timezone();

        $max = 1000;
        $start = 0;

        $date_pivots = $this->get_date_pivots();

        $query = 'SELECT * FROM ' . get_table_prefix() . 'failedlogins WHERE ';
        $query .= 'date_and_time>=' . strval($start_time) . ' AND ';
        $query .= 'date_and_time<=' . strval($end_time);
        $query .= ' ORDER BY date_and_time';
        do {
            $rows = $GLOBALS['SITE_DB']->query($query, $max, $start);
            foreach ($rows as $row) {
                $timestamp = $row['date_and_time'];
                $timestamp = tz_time($timestamp, $server_timezone);

                $month = to_epoch_interval_index($timestamp, 'months');

                $country = geolocate_ip($row['ip']);
                if ($country === null) {
                    $country = '';
                }

                if (has_geolocation_data()) {
                    if (!isset($data_buckets['security_incidents_countries'][$month]['']['failedlogins'][$country])) {
                        $data_buckets['security_incidents_countries'][$month]['']['failedlogins'][$country] = 0;
                    }
                    $data_buckets['security_incidents_countries'][$month]['']['failedlogins'][$country]++;
                }

                foreach (array_keys($date_pivots) as $pivot) {
                    $pivot_value = $this->calculate_date_pivot_value($pivot, $timestamp);

                    if (!isset($data_buckets['security_incidents'][$month][$pivot][$pivot_value]['failedlogins'])) {
                        $data_buckets['security_incidents'][$month][$pivot][$pivot_value]['failedlogins'] = 0;
                    }
                    $data_buckets['security_incidents'][$month][$pivot][$pivot_value]['failedlogins']++;
                }
            }

            $start += $max;
        } while (!empty($rows));

        $start = 0;

        $query = 'SELECT date_and_time,ip FROM ' . get_table_prefix() . 'hackattack WHERE ';
        $query .= 'date_and_time>=' . strval($start_time) . ' AND ';
        $query .= 'date_and_time<=' . strval($end_time);
        $query .= ' ORDER BY date_and_time';
        do {
            $rows = $GLOBALS['SITE_DB']->query($query, $max, $start);
            foreach ($rows as $row) {
                $timestamp = $row['date_and_time'];
                $timestamp = tz_time($timestamp, $server_timezone);

                $month = to_epoch_interval_index($timestamp, 'months');

                $country = geolocate_ip($row['ip']);
                if ($country === null) {
                    $country = '';
                }

                if (has_geolocation_data()) {
                    if (!isset($data_buckets['security_incidents_countries'][$month]['']['hackattacks'][$country])) {
                        $data_buckets['security_incidents_countries'][$month]['']['hackattacks'][$country] = 0;
                    }
                    $data_buckets['security_incidents_countries'][$month]['']['hackattacks'][$country]++;
                }

                foreach (array_keys($date_pivots) as $pivot) {
                    $pivot_value = $this->calculate_date_pivot_value($pivot, $timestamp);

                    if (!isset($data_buckets['security_incidents'][$month][$pivot][$pivot_value]['hackattacks'])) {
                        $data_buckets['security_incidents'][$month][$pivot][$pivot_value]['hackattacks'] = 0;
                    }
                    $data_buckets['security_incidents'][$month][$pivot][$pivot_value]['hackattacks']++;
                }
            }

            $start += $max;
        } while (!empty($rows));
    }

    /**
     * Generate final data from preprocessed data.
     *
     * @param  string $bucket Data bucket we want data for
     * @param  string $pivot Pivot value
     * @param  array $filters Map of filters (including pivot if applicable)
     * @return ?array Final data in standardised map format (null: could not generate)
     */
    public function generate_final_data(string $bucket, string $pivot, array $filters) : ?array
    {
        switch ($bucket) {
            case 'security_incidents':
                $range = $this->convert_month_range_filter_to_pair($filters[$bucket . '__month_range']);

                $data = $this->fill_data_by_date_pivots($pivot, $range[0], $range[1]);

                $where = [
                    'p_bucket' => $bucket,
                    'p_pivot' => $pivot,
                ];
                $extra = '';
                $extra .= ' AND p_month>=' . strval($range[0]);
                $extra .= ' AND p_month<=' . strval($range[1]);
                $data_rows = $GLOBALS['SITE_DB']->query_select('stats_preprocessed', ['p_data'], $where, $extra);
                foreach ($data_rows as $data_row) {
                    $_data = @unserialize($data_row['p_data']);
                    foreach ($_data as $pivot_value => $__) {
                        $pivot_value = $this->make_date_pivot_value_nice($pivot, $pivot_value);

                        foreach ($__ as $record_type => $num_incidents) {
                            if ((empty($filters[$bucket . '__include_failedlogins'])) && ($record_type == 'failedlogins')) {
                                continue;
                            }

                            if ((empty($filters[$bucket . '__include_hackattacks'])) && ($record_type == 'hackattacks')) {
                                continue;
                            }

                            if (!isset($data[$pivot_value])) {
                                $data[$pivot_value] = 0;
                            }
                            $data[$pivot_value] += $num_incidents;
                        }
                    }
                }

                return [
                    'type' => null,
                    'data' => $data,
                    'x_axis_label' => do_lang_tempcode('TIME_IN_TIMEZONE', escape_html(make_nice_timezone_name(get_site_timezone()))),
                    'y_axis_label' => do_lang_tempcode('COUNT_NEW'),
                ];

            case 'security_incidents_countries':
                $range = $this->convert_month_range_filter_to_pair($filters[$bucket . '__month_range']);

                require_code('locations');

                $data = [];

                $where = [
                    'p_bucket' => $bucket,
                    'p_pivot' => $pivot,
                ];
                $extra = '';
                $extra .= ' AND p_month>=' . strval($range[0]);
                $extra .= ' AND p_month<=' . strval($range[1]);
                $data_rows = $GLOBALS['SITE_DB']->query_select('stats_preprocessed', ['p_data'], $where, $extra);
                foreach ($data_rows as $data_row) {
                    $_data = @unserialize($data_row['p_data']);
                    foreach ($_data as $record_type => $__) {
                        foreach ($__ as $country => $total_incidents) {
                            if ((empty($filters[$bucket . '__include_failedlogins'])) && ($record_type == 'failedlogins')) {
                                continue;
                            }

                            if ((empty($filters[$bucket . '__include_hackattacks'])) && ($record_type == 'hackattacks')) {
                                continue;
                            }

                            $_country = find_country_name_from_iso($country);
                            if ($_country === null) {
                                $_country = do_lang('OTHER');
                            }

                            if (!isset($data[$_country])) {
                                $data[$_country] = 0;
                            }
                            $data[$_country] += $total_incidents;
                        }
                    }
                }

                return [
                    'type' => self::GRAPH_BAR_CHART,
                    'data' => $data,
                    'x_axis_label' => do_lang_tempcode('COUNTRY'),
                    'y_axis_label' => do_lang_tempcode('COUNT_TOTAL'),
                    'limit_bars' => true,
                ];
        }

        fatal_exit(do_lang_tempcode('INTERNAL_ERROR', escape_html('935fdd2a812e55df94196faad20c5371')));
    }
}
