# wt-security/3.0.1/lib/Ajax.php

WebTotem Security, version 3.0.1. 2,259 lines.

- Page: https://pluginprobe.com/plugins/wt-security/3.0.1/code/lib/Ajax.php
- Raw: https://pluginprobe.com/plugins/wt-security/3.0.1/raw/lib/Ajax.php
- Modified: 2026-05-15T03:23:06+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/wt-security/3.0.1/code/lib/Ajax.php#L10-L20`.

```php
<?php
if (!defined('WEBTOTEM_INIT') || WEBTOTEM_INIT !== true) {
	if (!headers_sent()) {
		header('HTTP/1.1 403 Forbidden');
	}
	die('Protected By WebTotem!');
}

class WebTotemAjax
{

	/**
	 * Activation plugin.
	 *
	 * @return void
	 */
	public static function activation()
	{

		if (WebTotemRequest::post('ajax_action') !== 'activation') {
			return;
		}

		if ($api_key = WebTotemRequest::post('api_key')) {

			$result = WebTotemAPI::auth($api_key);

			if ($result == 'success') {
//				if (WebTotem::isMultiSite()) {
//					$link = WebTotem::adminURL('admin.php?page=wtotem_all_sites');
//				} else {
//					$link = WebTotem::adminURL('admin.php?page=wtotem');
//				}
                $link = WebTotem::adminURL('admin.php?page=wtotem');
				// $email = WebTotemAPI::getEmail();
//				WebTotemOption::setOptions(['user_email' => $email]);
				wp_send_json([
					'link' => $link,
					'success' => true,
//					'user' => $email,
				], 200);
			} else {

				wp_send_json([
					'notifications' => self::notifications(),
					'success' => false,
				], 200);
			}
		}

	}

	/**
	 * The process of installing agents (WAF, AV) on the main page.
	 *
	 * @return void
	 */
	public static function agentsInstallation()
	{

		if (WebTotemRequest::post('ajax_action') !== 'agents_installation') {
			return;
		}

		$av_installed = WebTotemOption::getOption('av_installed');
		$waf_installed = WebTotemOption::getOption('waf_installed');

		// Check if the agents are installed.
		if ($av_installed and $waf_installed) {
			$agents_statuses = [
				'process_statuses' => [
					'av' => 'available',
					'waf' => 'available',
				],
			];
		} else {
			// If not installed, then request statuses from the WebTotem API.
			$data = WebTotemAPI::getAgentsStatusesFromAPI();

			$agents_statuses = [
				'av' => $data['av'],
				'waf' => $data['waf'],
			];

			$agents_statuses = WebTotem::getAgentsStatuses($agents_statuses);
		}

		$build[] = [
			'variables' => [
				'process_status' => $agents_statuses['process_statuses'],
			],
			'template' => 'agents_installation',
		];

		$status = [
			'av' => $agents_statuses['process_statuses']['av'] == 'available',
			'waf' => $agents_statuses['process_statuses']['waf'] == 'available',
		];

		WebTotemOption::setOptions([
			'av_installed' => $status['av'],
			'waf_installed' => $status['waf'],
		]);

		$template = new WebTotemTemplate();
		$agents = $template->arrayRender($build);

		wp_send_json([
			'success' => true,
			'notifications' => self::notifications(),
			'agents' => $agents,
			'agents_statuses' => $status['av'] && $status['waf'],
		]);
	}

	/**
	 * Reinstall agents.
	 *
	 * @return void
	 */
	public static function reinstallAgents()
	{

		if (WebTotemRequest::post('ajax_action') !== 'reinstall_agents') {
			return;
		}

		WebTotemAgentManager::amInstall();

		$response['success'] = true;
		$response['redirect_link'] = WebTotem::adminURL('admin.php?page=wtotem');
		wp_send_json($response);

	}

	/**
	 * Deleting plugin activation data and redirecting to the activation page.
	 *
	 * @return void
	 */
	public static function logout()
	{

		if (WebTotemRequest::post('ajax_action') !== 'logout') {
			return;
		}

		WebTotemOption::logout();

		$response['success'] = true;
		$response['redirect_link'] = WebTotem::adminURL('admin.php?page=wtotem_activation');
		wp_send_json($response);

	}

	/**
	 * Creating a modal window.
	 *
	 * @return void
	 */
	public static function popup()
	{

		if (WebTotemRequest::post('ajax_action') !== 'popup') {
			return;
		}

		$action = WebTotemRequest::post('popup_action');
		$template = new WebTotemTemplate();

		if ($action) {
			switch ($action) {
				case 'reinstall_agents':
					$build[] = [
						'variables' => [
							'message' => sprintf(__('Some scanning data for %s may be deleted.', 'wtotem'), WEBTOTEM_SITE_DOMAIN),
							'action' => 'reinstall_agents',
							'page_nonce' => wp_create_nonce('wtotem_page_nonce'),
						],
						'template' => 'popup',
					];
					break;

				case 'logout':
					$build[] = [
						'variables' => [
							'message' => __('Are you sure you want to change the API key?', 'wtotem'),
							'action' => 'logout',
							'page_nonce' => wp_create_nonce('wtotem_page_nonce'),
						],
						'template' => 'popup',
					];
					break;


                case 'update_plugin':
                    $build[] = [
                        'variables' => [
                            'message' => __('Do you really want to update the plugin?', 'wtotem'),
                            'action' => 'update_plugin',
                            'slug' => WebTotemRequest::post('slug'),
                            'page_nonce' => wp_create_nonce('wtotem_page_nonce'),
                        ],
                        'template' => 'popup',
                    ];
                    break;

			}

			wp_send_json([
				'success' => true,
				'content' => $template->arrayRender($build),
			]);
		}

		wp_send_json([
			'success' => false,
		]);

	}

	/**
	 * Request to update charts with parameters.
	 *
	 * @return void
	 */
	public static function chart()
	{

		if (WebTotemRequest::post('ajax_action') !== 'chart') {
			return;
		}

		$template = new WebTotemTemplate();

		$days = (integer)WebTotemRequest::post('days');
		$service = WebTotemRequest::post('service');

		$host = WebTotemAPI::siteInfo();

		switch ($service) {
			case 'waf':

				WebTotemOption::setSessionOptions(['firewall_period' => $days]);

				// Firewall chart.
				$data = WebTotemAPI::getFirewallStatistics($days);
				$chart = WebTotem::generateWafChart($data['signatures_statistic'] ?? []);

				$_chart[] = [
					'variables' => [
						'days' => $days,
						'chart' => $chart['chart'],
					],
					'template' => 'firewall_chart',
				];

				$response = [
					'chart' => $template->arrayRender($_chart),
					'service' => 'waf',
				];

				break;

			case 'cpu':
				WebTotemOption::setSessionOptions(['cpu_period' => $days]);

				$data = WebTotemAPI::getServerStatusData($host['id'], $days);
				$chart = WebTotem::generateChart($data['cpuChart'], $days);

				$_chart[] = [
					'variables' => [
						'days' => $days,
						'chart' => $chart,
					],
					'template' => 'cpu_chart',
				];

				$response = [
					'chart' => $template->arrayRender($_chart),
					'service' => 'cpu',
				];

				break;

			case 'ram':
				WebTotemOption::setSessionOptions(['ram_period' => $days]);

				$data = WebTotemAPI::getServerStatusData($host['id'], $days);
				$chart = WebTotem::generateChart($data['ramChart'], $days);

				$_chart[] = [
					'variables' => [
						'days' => $days,
						'chart' => $chart,
					],
					'template' => 'ram_chart',
				];

				$response = [
					'chart' => $template->arrayRender($_chart),
					'service' => 'ram',
				];

				break;

			case 'map':

				$data = WebTotemAPI::getFirewallStatistics($days);
				$chart = WebTotem::generateAttacksMapChart($data['countries_statistics'] ?? []);
				$world_map_json = WEBTOTEM_URL . '/includes/js/world_map.json';

				$_chart[] = [
					'variables' => [
						'attacks_map' => $chart,
						'world_map_json' => $world_map_json,
					],
					'template' => 'map_chart',
				];

				$response = [
					'chart' => $template->arrayRender($_chart),
					'service' => 'map',
				];

				break;

		}

		if ($service) {
			$response['success'] = true;
			$response['notifications'] = self::notifications();
			wp_send_json($response);
		}

	}


    /**
     * Pagination.
     * @return void
     */
    public static function pagination()
    {

        if (WebTotemRequest::post('ajax_action') !== 'pagination') {
            return;
        }

        $template = new WebTotemTemplate();

        $service = WebTotemRequest::post('service');
        $current_page = WebTotemRequest::post('current_page');


        switch ($service) {

            case 'firewall':
                $firewall_data = WebTotemAPI::getFirewall(10, $current_page, 7);

                $build[] = [
                    'variables' => [
                        "logs" => WebTotem::wafLogs($firewall_data['logs'] ?? []),
                    ],
                    'template' => 'firewall_logs',
                ];
               $pagination = WebTotem::paginationBuild(10, $firewall_data['total'], $current_page);

                break;

            case 'antivirus':
                $antivirus_history_data = WebTotemAPI::getAntivirusHistory($current_page);
                $build[] = [
                    'variables' => [
                        "logs" => WebTotem::getAntivirusLogsData($antivirus_history_data['history']),
                    ],
                    'template' => 'antivirus_history_items',
                ];

                $pagination = WebTotem::paginationBuild(10, $antivirus_history_data['total'], $current_page);

                break;

            case 'infected_files':
                $infected_files = WebTotemAPI::getAntivirusCurrentDetails($current_page);
                $build[] = [
                    'variables' => [
                        "logs" => WebTotem::getInfectedFilesData($infected_files['current_infected_files'] ?? []),
                        "type" => 'infected',
                    ],
                    'template' => 'quarantine_logs',
                ];

                $pagination =  WebTotem::paginationBuild(5, (int)$infected_files['total'], $current_page);
                break;

            case 'quarantine':
                $quarantine_files = WebTotemAPI::getQuarantineList($current_page);
                $build[] = [
                    'variables' => [
                        "logs" => WebTotem::getQuarantineListData($quarantine_files['quarantine_files'] ?? []),
                        "type" => 'quarantine',
                    ],
                    'template' => 'quarantine_logs',
                ];

                $pagination = WebTotem::paginationBuild(5, (int)$quarantine_files['total'], $current_page);
                break;
        }

        if ($service) {

            wp_send_json([
                'success' => true,
                'content' => $template->arrayRender($build),
                'pagination' => $pagination,
                'notifications' => self::notifications(),
            ]);
        }
    }


    /**
	 * Data lazy load.
	 * @return void
	 */
	public static function logs()
	{
		if (WebTotemRequest::post('ajax_action') !== 'logs') {
			return;
		}

		$template = new WebTotemTemplate();
		$logs_action = WebTotemRequest::post('logs_action');

		switch ($logs_action) {
			case 'audit_logs_pagination':
				$order = WebTotemRequest::post('order') === 'ascending' ? 'ASC' : 'DESC';
				$current_page = (int)WebTotemRequest::post('current_page');
				$event = WebTotemRequest::post('event');
				$filter = $event === 'All' ? [] : ['LIKE', ['event' => $event . '%']];

				$audit_logs = WebTotemDB::getRows(
					$filter,
					'audit_logs',
					false,
					['limit' => 10, 'page' => $current_page],
					['order_by' => 'created_at', 'direction' => $order]
				);

				$build[] = [
					'variables' => [
						"audit_logs" => WebTotem::getAuditLogs($audit_logs['data'], $audit_logs['dates_count']),
					],
					'template' => 'scan_audit_logs',
				];

				$response = [
					'success' => true,
					'content' => $template->arrayRender($build),
					"pagination" => WebTotem::paginationBuild(10, $audit_logs['count'], $current_page),
					'notifications' => self::notifications(),
				];

				break;
            case 'cve_logs_pagination':
                $current_page = (int)WebTotemRequest::post('current_page');

                $plugins_cve_list = WebTotemDB::getRows([], 'plugins_cve_list', false, ['limit' => 8, 'page' => $current_page]);

                $build[] = [
                    'variables' => [
                        "logs" => WebTotem::preparePluginsCveList($plugins_cve_list['data']),
                    ],
                    'template' => 'scan_logs_cve',
                ];

                $response = [
                    'success' => true,
                    'content' => $template->arrayRender($build),
                    "pagination" => WebTotem::paginationBuild(8, $plugins_cve_list['count'], $current_page),
                    'notifications' => self::notifications(),
                ];

                break;

			case 'audit_logs_sort_filter':
				$order = WebTotemRequest::post('order') === 'ascending' ? 'ASC' : 'DESC';
				$event = WebTotemRequest::post('event');
				$filter = $event === 'All' ? [] : ['LIKE', ['event' => $event . '%']];
				$audit_logs = WebTotemDB::getRows(
					$filter,
					'audit_logs',
					false,
					['limit' => 10, 'page' => 1],
					['order_by' => 'created_at', 'direction' => $order]
				);

				$build[] = [
					'variables' => [
						"audit_logs" => WebTotem::getAuditLogs($audit_logs['data'], $audit_logs['dates_count']),
					],
					'template' => 'scan_audit_logs',
				];

				$response = [
					'success' => true,
					'content' => $template->arrayRender($build),
					"pagination" => WebTotem::paginationBuild(10, $audit_logs['count'], 1),
					'notifications' => self::notifications(),
				];

				break;

			case 'confidential_files':
				$id = WebTotemRequest::post('id') ?? false;
				if ($id) {
					$file = WebTotemDB::getData(['id' => $id], 'confidential_files');
					if ($file['path']) {
						$path = urldecode($file['path']);
						if(file_exists($path)) unlink($path);
						WebTotemDB::deleteData(['id' => $id], 'confidential_files');
						WebTotemOption::setNotification('info', sprintf(__('File %s was deleted', 'wtotem'), json_decode($file['name'])));
					}
				}
				$order_by = WebTotemRequest::post('order');
				$direction = WebTotemRequest::post('direction') === 'ascending' ? 'ASC' : 'DESC';
				$current_page = (int)WebTotemRequest::post('current_page') ?: 1;

				$confidential_files = WebTotemDB::getRows(
					[],
					'confidential_files',
					false,
					['limit' => 10, 'page' => $current_page],
					$order_by ? ['order_by' => $order_by, 'direction' => $direction] : ['order_by' => 'id', 'direction' => 'DESC']
				);

				$build[] = [
					'variables' => [
						"confidential_files" => WebTotem::getConfidentialFiles($confidential_files['data']),
					],
					'template' => 'scan_confidential_files',
				];

				$response = [
					'success' => true,
					'content' => $template->arrayRender($build),
					'count' => $confidential_files['count'],
					"pagination" => WebTotem::paginationBuild(10, $confidential_files['count'], $current_page),
					'notifications' => self::notifications(),
				];

				break;

			case 'logs_pagination':
				$current_page = (int)WebTotemRequest::post('current_page');
				$type = WebTotemRequest::post('type');
				$direction = WebTotemRequest::post('direction') === 'ascending' ? 'ASC' : 'DESC';

				$scan_logs = WebTotemDB::getRows(
					['AND', ['data_type' => $type]],
					'scan_logs',
					'content',
					['limit' => 10, 'page' => $current_page],
					!empty($direction) ? ['order_by' => 'is_internal', 'direction' => $direction] : ['order_by' => 'id', 'direction' => 'DESC']
				);

				$build[] = [
					'variables' => [
						"logs" => WebTotem::prepareLinksData($scan_logs['data']),
						"data_type" => $type
					],
					'template' => 'scan_logs_items',
				];

				$response = [
					'success' => true,
					'content' => $template->arrayRender($build),
					"pagination" => WebTotem::paginationBuild(10, $scan_logs['count'], $current_page),
					'notifications' => self::notifications(),
				];

				break;

			case 'rescan':
//                WebTotem::updateCveData();
				WebTotemOption::setOptions(['scan_init' => 1]);
				WebTotemScan::initialize();
				$response = [
						'success' => true,
						'notifications' => self::notifications(),
				];

			break;

			case 'check_scan':

				if(WebTotemOption::getOption('scan_init')){
					WebTotemScan::initialize();
					$response = [
						'success' => true,
						'scan_finished' => false,
						'notifications' => self::notifications(),
					];
				} else {
					$content = [];
					$pagination = [];
					$count = [];
					$types = ['links', 'scripts', 'iframes'];

					foreach ($types as $type) {
						$scan_logs = WebTotemDB::getRows(
								['AND', ['data_type' => $type]],
								'scan_logs',
								'content'
						);

						$build[$type][] = [
								'variables' => [
										"logs" => $scan_logs['data'],
										"data_type" => $type
								],
								'template' => 'scan_logs_items',
						];
						$content[$type] = $template->arrayRender($build[$type]);
						$pagination[$type] = WebTotem::paginationBuild(10, $scan_logs['count']);
						$count[$type] = $scan_logs['count'];
					}

                    $plugins_cve_list = WebTotemDB::getRows([], 'plugins_cve_list', false, ['limit' => 8, 'page' => 1]);
                    $content['cve'] = $template->arrayRender([
                        'variables' => [
                            "logs" => WebTotem::preparePluginsCveList($plugins_cve_list['data']),
                        ],
                        'template' => 'scan_logs_cve',
                    ]);
                    $count['cve'] = $plugins_cve_list['count'];
                    $pagination['cve'] = WebTotem::paginationBuild(8, $plugins_cve_list['count']);

					$confidential_files = WebTotemDB::getRows([], 'confidential_files');
					$content['confidential_files'] = $template->arrayRender([
							'variables' => [
									"confidential_files" => WebTotem::getConfidentialFiles($confidential_files['data']),
							],
							'template' => 'scan_confidential_files',
					]);
					$pagination['confidential_files'] = WebTotem::paginationBuild(10, $confidential_files['count']);
					$count['confidential_files'] = $confidential_files['count'];

					// Resetting the task in the cron.
					wp_clear_scheduled_hook('webtotem_daily_cron');
					wp_schedule_event(time() + 86395, 'daily', 'webtotem_daily_cron');

					$until_next_scan = wp_next_scheduled('webtotem_daily_cron') - time();

					$hr = floor($until_next_scan / 3600);
					$min = floor(($until_next_scan % 3600) / 60);

					$response = [
							'success' => true,
							'scan_finished' => true,
							'content' => $content,
							"pagination" => $pagination,
							"next_scan" => sprintf(__('%dh %dm', 'wtotem'), $hr, $min),
							"count" => $count,
							'notifications' => self::notifications(),
					];
				}

				break;
		}

		wp_send_json($response ?? []);
	}

	/**
	 * Add date filter.
	 *
	 * @return void
	 */
	public static function wafDateFilter()
	{

		if (WebTotemRequest::post('ajax_action') !== 'waf_date_filter') {
			return;
		}

		$template = new WebTotemTemplate();

		$period = [WebTotemRequest::post('date_from'), WebTotemRequest::post('date_to')];
		WebTotemOption::setSessionOptions(['firewall_period' => $period]);

		// Firewall logs.
		$data = WebTotemAPI::getFirewall(10, 1, $period);
		$firewall = $data['firewall'];

		$waf_logs[] = [
			'variables' => [
				'logs' => WebTotem::wafLogs($firewall['logs']['edges']),
			],
			'template' => 'firewall_logs',
		];

		// Firewall chart.
		$data = WebTotemAPI::getFirewallStatistics($period);
		$chart = WebTotem::generateWafChart($data['signatures_statistic']);

		$_chart[] = [
			'variables' => [
				'days' => $chart['days'],
				'chart' => $chart['chart'],
			],
			'template' => 'firewall_chart',
		];

		// Firewall stats.
		$waf_stats[] = [
			'variables' => [
				'is_waf_training' => WebTotem::isWafTraining(),
				'all_attacks' => $chart['count_attacks'],
				'blocking' => $chart['count_blocks'],
				'not_blocking' => $chart['count_attacks'] - $chart['count_blocks'],
				'most_attacks' => WebTotem::getMostAttacksData($firewall['map']),
			],
			'template' => 'firewall_stats',
		];

		WebTotemOption::setSessionOptions([
			'firewall_cursor' => $firewall['logs']['pageInfo']['endCursor'],
		]);

		$has_next_page = $firewall['logs']['pageInfo']['hasNextPage'];

		$response = [
			'success' => true,
			'chart' => $template->arrayRender($_chart),
			'waf_logs' => $template->arrayRender($waf_logs),
			'waf_stats' => $template->arrayRender($waf_stats),
			'has_next_page' => $has_next_page,
			'notifications' => self::notifications(),
		];

		wp_send_json($response);
	}


	/**
	 * Request to restart re-scan and receive antivirus data.
	 *
	 * @return void
	 */
	public static function antivirus()
	{

		if (WebTotemRequest::post('ajax_action') !== 'antivirus') {
			return;
		}

		$action = WebTotemRequest::post('av_action');
		$host = WebTotemAPI::siteInfo();
        $template = new WebTotemTemplate();

		switch ($action) {


            case 'get_infected_files':
                $session_id = WebTotemRequest::post('session_id');
                $page_num = WebTotemRequest::post('page_num') ?? 1;

                $infected_files = WebTotemAPI::getAntivirusHistoryDetails($session_id, $page_num);

                $infected_files_wrap[] = [
                    'variables' => [
                        "logs" => WebTotem::getInfectedFilesData($infected_files['history_details']),
                        "total" => $infected_files['total'],
                        "type" => 'infected_ajax',
                    ],
                    'template' => 'quarantine_logs',
                ];

                $response['content'] = $template->arrayRender($infected_files_wrap);

                break;
		}

		$response['success'] = true;
		$response['notifications'] = self::notifications();

		wp_send_json($response);
	}

	/**
	 * Request to add a file to quarantine.
	 *
	 * @return void
	 */
	public static function quarantine()
	{
		if (WebTotemRequest::post('ajax_action') !== 'quarantine') {
			return;
		}

		$action = WebTotemRequest::post('quarantine_action');
		$path = urlencode(WebTotemRequest::post('path'));

		$response = [];

		switch ($action) {
			case 'add':
				$api_response = WebTotemAPI::moveToQuarantine($path);
				break;

			case 'remove':
				$api_response = WebTotemAPI::moveFromQuarantine($path);
				break;
		}

        $response['success'] = false;
        if (!isset($api_response['message'])) {

            $infected_files_data = WebTotemAPI::getAntivirusCurrentDetails();
            $quarantine_files_data = WebTotemAPI::getQuarantineList();

            $quarantine = [
                'variables' => [
                    "logs" => WebTotem::getQuarantineListData($quarantine_files_data['quarantine_files'] ?? []),
                    "type" => 'quarantine',
                ],
                'template' => 'quarantine_logs',
            ];
            $pagination_quarantine = WebTotem::paginationBuild(5, (int)$quarantine_files_data['total']);

            $infected_files = [
                'variables' => [
                    "logs" => WebTotem::getInfectedFilesData($infected_files_data['current_infected_files'] ?? []),
                    "type" => 'infected',
                ],
                'template' => 'quarantine_logs',
            ];
            $pagination_infected_files = WebTotem::paginationBuild(5, (int)$infected_files_data['total']);

            $template = new WebTotemTemplate();
            $response = [
                'infected_files' => $template->arrayRender($infected_files),
                'quarantine_files' => $template->arrayRender($quarantine),
                'pagination_infected_files' => $pagination_infected_files,
                'pagination_quarantine' => $pagination_quarantine,
                'infected_files_total' => (int)$infected_files_data['total'],
                'quarantine_files_total' => (int)$quarantine_files_data['total'],
            ];

            $response['success'] = true;
        }

        $response['notifications'] = self::notifications();

		wp_send_json($response);

	}

	/**
	 * Request to add or remove a port to the ignore list.
	 *
	 * @return void
	 */
	public static function ignorePorts()
	{

		if (WebTotemRequest::post('ajax_action') !== 'ignore_ports') {
			return;
		}


		$action = WebTotemRequest::post('port_action');
		$port = (int)WebTotemRequest::post('port');

		$host = WebTotemAPI::siteInfo();

		switch ($action) {
			case 'add':
				$response = WebTotemAPI::addIgnorePort($host['id'], $port);
				break;

			case 'remove':
				$response = WebTotemAPI::removeIgnorePort($host['id'], $port);
				break;
		}

		if (!isset($response['errors'])) {

			$ports = WebTotemAPI::getAllPortsList($host['id']);
			$open_ports[] = [
				'variables' => [
                    "ports" => $ports['TCPResults'] ? WebTotem::getOpenPortsData(array_slice($ports['TCPResults'], 0, 3)) : [],
                    'more' => true,
				],
				'template' => 'open_ports',
			];

            $open_ports_modal[] = [
                'variables' => [
                    "ports" => WebTotem::getOpenPortsData($ports['TCPResults']),
                ],
                'template' => 'open_ports',
            ];

			$ignore_ports[] = [
				'variables' => [
					"ports" => $ports,
				],
				'template' => 'ignore_ports',
			];

            $template = new WebTotemTemplate();
			$response = [
                'open_ports' => $template->arrayRender($open_ports),
                'open_ports_modal' => $template->arrayRender($open_ports_modal),
				'ignore_ports' => $template->arrayRender($ignore_ports),
			];

		}

		$response['success'] = true;
		$response['notifications'] = self::notifications();

		wp_send_json($response);
	}

	/**
	 * Request for a report link.
	 *
	 * @return void
	 */
	public static function reports()
	{

		if (WebTotemRequest::post('ajax_action') !== 'reports') {
			return;
		}

		$template = new WebTotemTemplate();

		$action = WebTotemRequest::post('report_action');

		switch ($action) {
			case 'download':
				$id = WebTotemRequest::post('id');
				$link = WebTotemAPI::downloadReport($id);
				if ($link) {
					$response['link'] = $link;
				}
				break;
			case 'report_form':

				$period = [WebTotemRequest::post('date_from'), WebTotemRequest::post('date_to')];
				$modules_data = WebTotemRequest::post('modules');

				$modules = [
					'wa' => 'false',
					'dc' => 'false',
					'ps' => 'false',
					'rc' => 'false',
					'sc' => 'false',
					'av' => 'false',
					'waf' => 'false'
				];

				foreach ($modules_data as $module => $value) {
					$modules[$module] = 'true';
				}

				$host = WebTotemAPI::siteInfo();
				$api_response = WebTotemAPI::generateReport($host['id'], $period, $modules);

				if (!$api_response) {
					$massage = '<div class="message error_message">' . __('Report generation error', 'wtotem') . '</div>';
				} else {
					$data = WebTotemAPI::getAllReports($host['id']);
					WebTotemCache::setData(['getAllReports' => $data], $host['id']);

					// Reports.
					$build[] = [
						'variables' => [
							"reports" => WebTotem::getReports($data['edges']),
							"has_next_page" => $data['pageInfo']['hasNextPage'],
						],
						'template' => 'reports_list',
					];

					// Reports mobile.
					$build_mobile[] = [
						'variables' => [
							"reports" => WebTotem::getReports($data['edges']),
							"has_next_page" => $data['pageInfo']['hasNextPage'],
						],
						'template' => 'reports_list_mobile',
					];

					$response = [
						'reports' => $template->arrayRender($build),
						'reports_m' => $template->arrayRender($build_mobile),
						'link' => $api_response,
					];

					$massage = '<div class="message success_message">' . __('The report was successfully generated', 'wtotem') . '</div>';
				}

				$response['massage'] = $massage;

				break;
		}

		$response['success'] = true;
		$response['notifications'] = self::notifications();
		wp_send_json($response);
	}

	/**
	 * Request for a report link.
	 *
	 * @return void
	 */
	public static function settings()
	{

		if (WebTotemRequest::post('ajax_action') !== 'settings') {
			return;
		}

		$av_installed = WebTotemOption::getOption('av_installed');
		$waf_installed = WebTotemOption::getOption('waf_installed');
		$action = WebTotemRequest::post('settings_action');

		if (in_array($action, ['module_toggle', 'module_notifications', 'waf_settings', 'add_allow_ip', 'add_deny_ip', 'add_allow_url', 'add_ip_list', 'country_blocking'])) {
			if (!$av_installed && !$waf_installed) {
				WebTotemOption::setNotification('warning', __('It is not possible to make changes because the agents are not installed.', 'wtotem'));

				wp_send_json([
					'success' => false,
					'notifications' => self::notifications()
				]);
				return;
			}
		}

		$host = WebTotemAPI::siteInfo();
		$template = new WebTotemTemplate();

		switch ($action) {

			case 'module_toggle':
				$config = WebTotemAPI::toggleConfigs(WebTotemRequest::post('value'));

				$configs_data = WebTotemAPI::getConfigs($host['id']);
				WebTotemCache::setData(['getConfigs' => $configs_data], $host['id']);

				WebTotemOption::setNotification('success', __('Your changes have been applied successfully.', 'wtotem'));
				$response['isActive'] = $config['isActive'];
				$response['success'] = true;
				break;

			case 'country_blocking':
				$countries = WebTotemRequest::post('checked_countries');

				if (WebTotemAPI::syncBlockedCountries($host['id'], $countries)) {
					$waf_data = WebTotemAPI::getBlockedCountries($host['id']);
					WebTotemCache::setData(['getBlockedCountries' => $waf_data], $host['id']);

					WebTotemOption::setNotification('success', __('Your changes have been applied successfully.', 'wtotem'));
					$response['blocked_countries_list'] = $waf_data['blockedCountries'];
					$response['success'] = true;
				} else {
					WebTotemOption::setNotification('success', __('Your changes have not been applied.', 'wtotem'));
					$response['success'] = false;
				}

				break;

			case 'module_notifications':
				$config = WebTotemAPI::toggleNotifications($host['id'], WebTotemRequest::post('value'));

				$configs_data = WebTotemAPI::getConfigs($host['id']);
				WebTotemCache::setData(['getConfigs' => $configs_data], $host['id']);

				WebTotemOption::setNotification('success', __('Your changes have been applied successfully.', 'wtotem'));
				$response['isActive'] = $config;
				$response['success'] = true;
				break;

			case 'waf_settings':

				$response['success'] = true;

				$dos = filter_var( WebTotemRequest::post('dos'), FILTER_VALIDATE_BOOLEAN);
                $dos_limit = WebTotemRequest::post('dos_limit');
                $gdn= filter_var( WebTotemRequest::post('gdn'), FILTER_VALIDATE_BOOLEAN);
//              $login_attempt = filter_var( WebTotemRequest::post('login_attempt'), FILTER_VALIDATE_BOOLEAN);
//              $login_attempt_limit = WebTotemRequest::post('login_attempt_limit');

				if ($dos) {
					if (empty($dos_limit)) {
						$response['errors']['dos_limit'] = __('The field is required.', 'wtotem');
					} else if ($dos_limit < 500 or $dos_limit > 10000) {
						$response['success'] = false;
						$response['errors']['dos_limit'] = sprintf(__('Please specify a value from %s to %s.', 'wtotem'), '500', '10 000');
					}
				}

//              if ($login_attempt) {
//                  if (empty($login_attempt_limit)) {
//                      $response['errors']['login_attempt_limit'] = __('The field is required.', 'wtotem');
//                  } else if ($login_attempt_limit < 5 or $login_attempt_limit > 30) {
//                      $response['success'] = false;
//                      $response['errors']['login_attempt_limit'] = sprintf(__('Please specify a value from %s to %s.', 'wtotem'), '5', '30');
//                  }
//              }

				if (!$response['success']) {
					break;
				} else {
					$response['errors'] = false;
				}

                $waf_settings = WebTotemAPI::getFirewallSettings();

                $waf_settings['dos_protect'] = $dos;
                $waf_settings['dos_limit'] = (int) $dos_limit;
                $waf_settings['global_defense_network'] = $gdn;

				$api_response = WebTotemAPI::setFirewallSettings($waf_settings);
                WebTotemCache::setData(['getFirewallSettings' => $waf_settings], $host['id']);

				if (!$api_response['message']) {

					WebTotemOption::setNotification('success', __('Your changes have been applied successfully.', 'wtotem'));
				}

				break;

			case 'recaptcha_settings':

				$recaptcha_v3_site_key = WebTotemRequest::post('recaptcha_v3_site_key');
				$recaptcha_v3_secret = WebTotemRequest::post('recaptcha_v3_secret');
				$recaptcha_token = WebTotemRequest::post('recaptcha_token');
				$recaptcha = filter_var(WebTotemRequest::post('recaptcha'), FILTER_VALIDATE_BOOLEAN) ?: false;

				if ($recaptcha) {
					if (empty($recaptcha_v3_site_key) or empty($recaptcha_v3_secret) or strlen($recaptcha_v3_site_key) != 40 or strlen($recaptcha_v3_secret) != 40) {
						$response['success'] = false;

						$response['errors'] = ['recaptcha_v3_site_key' => '', 'recaptcha_v3_secret' => ''];

						if (empty($recaptcha_v3_site_key)) {
							$response['errors']['recaptcha_v3_site_key'] = __('The field is required.', 'wtotem');
						} else if (strlen($recaptcha_v3_site_key) != 40) {
							$response['errors']['recaptcha_v3_site_key'] = __('Invalid field length.', 'wtotem');
						}
						if (empty($recaptcha_v3_secret)) {
							$response['errors']['recaptcha_v3_secret'] = __('The field is required.', 'wtotem');
						} else if (strlen($recaptcha_v3_secret) != 40) {
							$response['errors']['recaptcha_v3_secret'] = __('Invalid field length.', 'wtotem');
						}

						break;
					}

					$score = WebTotemCaptcha::score($recaptcha_token, $recaptcha_v3_secret);

					if ($score == 0) {
						$response['success'] = false;
						$response['errors']['recaptcha_v3_secret'] = __('Please check your keys and try again.', 'wtotem');
						$response['errors']['recaptcha_v3_site_key'] = __('Please check your keys and try again.', 'wtotem');
						break;
					}
				}

				if ($recaptcha) {
					$settings = [
						'recaptcha_v3_site_key' => $recaptcha_v3_site_key,
						'recaptcha_v3_secret' => $recaptcha_v3_secret,
					];
				}
				$settings['recaptcha'] = $recaptcha;

				if ($settings['hide_wp_version']) {
					WebTotemOption::hideReadme();
				} else {
					WebTotemOption::restoreReadme();
				}

				WebTotemOption::setPluginSettings($settings);

				WebTotemOption::setNotification('success', __('Your changes have been applied successfully.', 'wtotem'));
				if($recaptcha){
                    WebTotemOption::setNotification('warning', __('Please make sure that no other recaptcha is used on your site. Otherwise, there may be a conflict that will cause problems when logging into the admin panel.', 'wtotem'));
                }

				$response['success'] = true;


				break;

			case 'two_factor_settings':
				$two_factor = filter_var(WebTotemRequest::post('two_factor'), FILTER_VALIDATE_BOOLEAN) ?: false;

				WebTotemOption::setPluginSettings([
					'two_factor' => $two_factor,
				]);

				WebTotemOption::setNotification('success', __('Your changes have been applied successfully.', 'wtotem'));
				if ($two_factor) {
					WebTotemOption::setNotification('warning', __('Please make sure that no other 2FA is used on your site. Otherwise, there may be a conflict that will cause problems when logging into the admin panel.', 'wtotem'));
				}

				$response['success'] = true;

				break;


			case 'other_settings':

				$settings = [
                    'hide_wp_version' => filter_var(WebTotemRequest::post('hide_wp_version'), FILTER_VALIDATE_BOOLEAN) ?: false,
                    'disable_user_enumeration' => filter_var(WebTotemRequest::post('disable_user_enumeration'), FILTER_VALIDATE_BOOLEAN) ?: false,
				];

				if ($settings['hide_wp_version']) {
					WebTotemOption::hideReadme();

				} else {
					WebTotemOption::restoreReadme();
				}

				WebTotemOption::setPluginSettings($settings);

				WebTotemOption::setNotification('success', __('Your changes have been applied successfully.', 'wtotem'));

				$response['success'] = true;

				break;

			case 'bruteforce_protection_settings':

				$data = WebTotemRequest::post('data');
				$response['success'] = true;

				$login_attempts = filter_var($data['login_attempts'], FILTER_VALIDATE_BOOLEAN) ?: false;
				$password_reset = filter_var($data['password_reset'], FILTER_VALIDATE_BOOLEAN) ?: false;

				if ($login_attempts) {
					$response['errors'] = ['login_number_of_attempts' => '', 'login_minutes_of_ban' => ''];

					if (empty($data['login_number_of_attempts']) or empty($data['login_minutes_of_ban'])) {
						$response['success'] = false;

						if (empty($data['login_number_of_attempts'])) {
							$response['errors']['login_number_of_attempts'] = __('The field is required.', 'wtotem');
						}
						if (empty($data['login_minutes_of_ban'])) {
							$response['errors']['login_minutes_of_ban'] = __('The field is required.', 'wtotem');
						}
					} else if ($data['login_number_of_attempts'] <= 0 or $data['login_number_of_attempts'] > 1000000) {
						$response['success'] = false;
						$response['errors']['login_number_of_attempts'] = sprintf(__('Please specify a value from %s to %s.', 'wtotem'), '1', '1000000');
					}
				}

				if ($password_reset) {
					if (empty($data['password_reset_number_of_attempts']) or empty($data['password_reset_minutes_of_ban'])) {
						$response['success'] = false;

						$response['errors']['password_reset_number_of_attempts'] = '';
						$response['errors']['password_reset_minutes_of_ban'] = '';

						if (empty($data['password_reset_number_of_attempts'])) {
							$response['errors']['password_reset_number_of_attempts'] = __('The field is required.', 'wtotem');
						}
						if (empty($data['password_reset_minutes_of_ban'])) {
							$response['errors']['password_reset_minutes_of_ban'] = __('The field is required.', 'wtotem');
						}
					} else if ($data['password_reset_number_of_attempts'] <= 0 or $data['password_reset_number_of_attempts'] > 1000000) {
						$response['success'] = false;
						$response['errors']['password_reset_number_of_attempts'] = sprintf(__('Please specify a value from %s to %s.', 'wtotem'), '1', '1000000');
					}
				}
				if (!$response['success']) {
					break;
				} else {
					$response['errors'] = false;
				}

				$settings = [
					'login_attempts' => $login_attempts,
					'password_reset' => $password_reset,
				];

				if ($login_attempts) {
					$settings['login_number_of_attempts'] = $data['login_number_of_attempts'];
					$settings['login_minutes_of_ban'] = $data['login_minutes_of_ban'];
				}
				if ($password_reset) {
					$settings['password_reset_number_of_attempts'] = $data['password_reset_number_of_attempts'];
					$settings['password_reset_minutes_of_ban'] = $data['password_reset_minutes_of_ban'];
				}

				WebTotemOption::setPluginSettings($settings);

				WebTotemOption::setNotification('success', __('Your changes have been applied successfully.', 'wtotem'));

				break;

			case 'add_allow_ip':
			    $ip = WebTotemRequest::post('value');
                if(!WebTotem::validateIpOrCidr($ip)){
                    WebTotemOption::setNotification('warning', __('The IP address is incorrect', 'wtotem'));
                    $response['success'] = false;
                    break;
                }
			    if($ip){
                    $api_response = WebTotemAPI::addIpToList([$ip], 'whitelist');
                    if ($api_response) {

                        $data = WebTotemAPI::getIpLists('whitelist');
                        WebTotemCache::setData(['getIpLists_whitelist' => $data], $host['id']);

                        $build[] = [
                            'variables' => [
                                "list" => WebTotem::getIpList($data, 'ip_allow'),
                            ],
                            'template' => 'allow_deny_list',
                        ];

                        $response['content'] = $template->arrayRender($build);
                    }

                    $response['success'] = true;
                } else {
                    $response['success'] = false;
                }

				break;

			case 'add_deny_ip':
                $ip = WebTotemRequest::post('value');
                if(!WebTotem::validateIpOrCidr($ip)){
                    WebTotemOption::setNotification('warning', __('The IP address is incorrect', 'wtotem'));
                    $response['success'] = false;
                    break;
                }
                if($ip){
                    $api_response = WebTotemAPI::addIpToList([$ip], 'blacklist');
                    if ($api_response) {
                        $data = WebTotemAPI::getIpLists();
                        WebTotemCache::setData(['getIpLists_blacklist' => $data], $host['id']);

                        $build[] = [
                            'variables' => [
                                "list" => WebTotem::getIpList($data, 'ip_deny'),
                            ],
                            'template' => 'allow_deny_list',
                        ];

                        $response['content'] = $template->arrayRender($build);
                    }

                    $response['success'] = true;
                } else {
                    $response['success'] = false;
                }
				break;

			case 'add_allow_url':
                $url = WebTotemRequest::post('value');
                if($url){
                    $api_response = WebTotemAPI::addIpToList([$url], 'checklist');
                    if ($api_response) {
                        $data = WebTotemAPI::getIpLists('checklist');
                        WebTotemCache::setData(['getIpLists_checklist' => $data], $host['id']);

                        $build[] = [
                            'variables' => [
                                "list" => WebTotem::getIpList($data, 'allow_url'),
                            ],
                            'template' => 'allow_deny_list',
                        ];

                        $response['content'] = $template->arrayRender($build);
                    }

                    $response['success'] = true;
                } else {
                    $response['success'] = false;
                }
				break;

			case 'add_ip_list':
				$ips = WebTotem::convertIpListForApi(WebTotemRequest::post('ips'));
				$list_name = WebTotemRequest::post('list');

				foreach ($ips as $key => $ip){
                    if(!WebTotem::validateIpOrCidr($ip)){
                        WebTotemOption::setNotification('warning', __('The IP address is incorrect', 'wtotem')) . ': ' . $ip;
                        unset($ips[$key]);
                    }
                }

				$api_response = WebTotemAPI::addIpToList($ips, $list_name);

				if ($api_response) {
					$data = WebTotemAPI::getIpLists($list_name);
                    WebTotemCache::setData(['getIpLists_' . $list_name => $data], $host['id']);
					$ip_list = ($list_name == 'whitelist') ? 'ip_allow' : 'ip_deny';

					$build[] = [
						'variables' => [
							"list" => WebTotem::getIpList($data, $ip_list),
						],
						'template' => 'allow_deny_list',
					];

					if ($api_response['status'] != 0) {
						$response['invalidIPs'] = implode("\n", $api_response['invalidIPs']);
					}

					$response['wrap'] = ($list_name == 'white') ? '#wtotem_ip_allow_list' : '#wtotem_ip_deny_list';
					$response['content'] = $template->arrayRender($build);
				}
				$response['success'] = true;

				break;
		}

		$response['notifications'] = self::notifications();
		wp_send_json($response);
	}


/**
 * Update cash data.
 *
 * @return void
 */
public static function cashUpdate()
{

    if (WebTotemRequest::post('ajax_action') !== 'cash_update') {
        return;
    }

    $page = WebTotemRequest::post('page');

    $host = WebTotemAPI::siteInfo();
    $template = new WebTotemTemplate();

    switch ($page) {
        case 'dashboard':

            if ($cacheData = WebTotemCache::getdata('getMonitoringData', $host['id'])) {
                if ($cacheData['remained'] < 60) {
                    $data_monitoring = WebTotemAPI::getMonitoringData($host['id']);
                    WebTotemCache::setData(['getMonitoringData' => $data_monitoring], $host['id']);
                }
            }
            if ($cacheData = WebTotemCache::getdata('getFirewall', $host['id'])) {
                if ($cacheData['remained'] < 60) {
                    $data_firewall = WebTotemAPI::getFirewall(10, 1, 7);
                    WebTotemCache::setData(['getFirewall' => $data_firewall], $host['id']);
                }
            }
            if ($cacheData = WebTotemCache::getdata('getFirewallStatistics', $host['id'])) {
                if ($cacheData['remained'] < 60) {
                    $data_firewall_statistics = WebTotemAPI::getFirewallStatistics();
                    WebTotemCache::setData(['getFirewallStatistics' => $data_firewall_statistics], $host['id']);
                }
            }
            if ($cacheData = WebTotemCache::getdata('getAgentsStatusesFromAPI', $host['id'])) {
                if ($cacheData['remained'] < 60) {
                    $data_agents_statuses = WebTotemAPI::getAgentsStatusesFromAPI();
                    WebTotemCache::setData(['getAgentsStatusesFromAPI' => $data_agents_statuses], $host['id']);
                }
            }
            break;

        case 'open_paths':
            if($cacheData = WebTotemCache::getdata('getMonitoringData', $host['id'])) {
                if ($cacheData['remained'] < 60) {
                    $data = WebTotemAPI::getMonitoringData($host['id']);
                    WebTotemCache::setData(['getMonitoringData' => $data], $host['id']);
                }
            }
            break;


        case 'firewall':
            if ($cacheData = WebTotemCache::getdata('getFirewallStatistics', $host['id'])) {
                if ($cacheData['remained'] < 60) {
                    $data_firewall_statistics = WebTotemAPI::getFirewallStatistics();
                    WebTotemCache::setData(['getFirewallStatistics' => $data_firewall_statistics], $host['id']);
                }
            }
            if ($cacheData = WebTotemCache::getdata('getFirewall', $host['id'])) {
                if ($cacheData['remained'] < 60) {
                    $data_firewall = WebTotemAPI::getFirewall(10, 1, 7);
                    WebTotemCache::setData(['getFirewall' => $data_firewall], $host['id']);
                }
            }
            break;

        case 'antivirus':
            if ($cacheData = WebTotemCache::getdata('getAntivirusHistory', $host['id'])) {
                if ($cacheData['remained'] < 60) {

                    $antivirus_history_data = WebTotemAPI::getAntivirusHistory();
                    WebTotemCache::setData(['getAntivirusHistory' => $antivirus_history_data], $host['id']);
                }
            }
            if ($cacheData = WebTotemCache::getdata('getAntivirusCurrentDetails', $host['id'])) {
                if ($cacheData['remained'] < 60) {
                    $infected_files = WebTotemAPI::getAntivirusCurrentDetails();
                    WebTotemCache::setData(['getAntivirusCurrentDetails' => $infected_files], $host['id']);

                }
            }

            if ($cacheData = WebTotemCache::getdata('getQuarantineList', $host['id'])) {
                if ($cacheData['remained'] < 60) {
                    $quarantine_files = WebTotemAPI::getQuarantineList();
                    WebTotemCache::setData(['getQuarantineList' => $quarantine_files], $host['id']);
                }
            }
            break;

        case 'settings':
            if ($cacheData = WebTotemCache::getdata('getAgentsStatusesFromAPI', $host['id'])) {
                if ($cacheData['remained'] < 60) {
                    $agents_statuses = WebTotemAPI::getAgentsStatusesFromAPI();
                    WebTotemCache::setData(['getAgentsStatusesFromAPI' => $agents_statuses], $host['id']);
                }
            }
            if ($cacheData = WebTotemCache::getdata('getFirewallSettings', $host['id'])) {
                if ($cacheData['remained'] < 60) {
                    $waf_settings = WebTotemAPI::getFirewallSettings();
                    WebTotemCache::setData(['getFirewallSettings' => $waf_settings], $host['id']);
                }
            }
            if ($cacheData = WebTotemCache::getdata('getIpLists_whitelist', $host['id'])) {
                if ($cacheData['remained'] < 60) {
                    $ip_whiteList = WebTotemAPI::getIpLists('whitelist');
                    WebTotemCache::setData(['getIpLists_whitelist' => $ip_whiteList], $host['id']);
                }
            }
            if ($cacheData = WebTotemCache::getdata('getIpLists_blacklist', $host['id'])) {
                if ($cacheData['remained'] < 60) {
                    $ip_blackList = WebTotemAPI::getIpLists();
                    WebTotemCache::setData(['getIpLists_blacklist' => $ip_blackList], $host['id']);
                }
            }
            if ($cacheData = WebTotemCache::getdata('getIpLists_checklist', $host['id'])) {
                if ($cacheData['remained'] < 60) {
                    $ip_checklist = WebTotemAPI::getIpLists('checklist');
                    WebTotemCache::setData(['getIpLists_checklist' => $ip_checklist], $host['id']);
                }
            }
            break;

    }

    $response['success'] = true;
    $response['notifications'] = self::notifications();
    wp_send_json($response);
}

	/**
	 * Request to remove from the list of deny/allowed ip or url addresses.
	 *
	 * @return void
	 */
	public static function remove()
	{

		if (WebTotemRequest::post('ajax_action') !== 'remove') {
			return;
		}

		$av_installed = WebTotemOption::getOption('av_installed');
		$waf_installed = WebTotemOption::getOption('waf_installed');

		if (!$av_installed && !$waf_installed) {
			WebTotemOption::setNotification('warning', __('It is not possible to make changes because the agents are not installed.', 'wtotem'));

			wp_send_json([
				'success' => false,
				'notifications' => self::notifications()
			]);
		}

		$action = WebTotemRequest::post('remove_action');
		$host = WebTotemAPI::siteInfo();
		$template = new WebTotemTemplate();

		switch ($action) {
			case 'ip_allow':
				$api_response = WebTotemAPI::removeIpFromList(WebTotemRequest::post('ip'), 'whitelist');

				if ($api_response) {
                    $data = WebTotemAPI::getIpLists('whitelist');
                    WebTotemCache::setData(['getIpLists_whitelist' => $data], $host['id']);

					$build[] = [
						'variables' => [
							"list" => WebTotem::getIpList($data, 'ip_allow'),
						],
						'template' => 'allow_deny_list',
					];

					$response['content'] = $template->arrayRender($build);
					$response['wrap'] = '#wtotem_ip_allow_list';
				}
				break;

			case 'ip_deny':
				$api_response = WebTotemAPI::removeIpFromList(WebTotemRequest::post('ip'), 'blacklist');

				if ($api_response) {
                    $data = WebTotemAPI::getIpLists();
                    WebTotemCache::setData(['getIpLists_blacklist' => $data], $host['id']);

					$build[] = [
						'variables' => [
							"list" => WebTotem::getIpList($data, 'ip_deny'),
						],
						'template' => 'allow_deny_list',
					];

					$response['content'] = $template->arrayRender($build);
					$response['wrap'] = '#wtotem_ip_deny_list';
				}
				break;

			case 'url_allow':
                $api_response = WebTotemAPI::removeIpFromList(WebTotemRequest::post('ip'), 'checklist');

				if ($api_response) {
                    $data = WebTotemAPI::getIpLists('checklist');
                    WebTotemCache::setData(['getIpLists_checklist' => $data], $host['id']);

                    $build[] = [
                        'variables' => [
                            "list" => WebTotem::getIpList($data, 'allow_url'),
                        ],
                        'template' => 'allow_deny_list',
                    ];

					$response['content'] = $template->arrayRender($build);
					$response['wrap'] = '#wtotem_allow_url';
				}
				break;
		}

		$response['success'] = true;
		$response['notifications'] = self::notifications();
		wp_send_json($response);
	}

	/**
	 * Request to remove site from WebTotem.
	 *
	 * @return void
	 */
	public static function multisite()
	{

		if (WebTotemRequest::post('ajax_action') !== 'multisite') {
			return;
		}

		$action = WebTotemRequest::post('multisite_action');
		$template = new WebTotemTemplate();

		switch ($action) {
			case 'remove_site':

				$host_id = WebTotemRequest::post('hid');
				$main_host = WebTotemOption::getMainHost();

				if ($host_id == $main_host['id']) {
					WebTotemOption::setNotification('error', __('You cannot delete the primary domain.', 'wtotem'));
					break;
				}
				WebTotemAPI::removeMultiSiteHost($host_id);

				break;

			case 'add_site':

				$new_site = WebTotemRequest::post('site_name');
				WebTotemAPI::addMultiSiteNewSites([$new_site]);

				break;
		}

		$allSites = WebTotemAPI::getSites();
		$has_next_page = $allSites['pageInfo']['hasNextPage'];

		WebTotemOption::setSessionOptions([
			'sites_cursor' => $allSites['pageInfo']['endCursor'],
		]);

		// Sites list.
		$build[] = [
			'variables' => [
				'sites' => WebTotem::allSitesData($allSites),
				'has_next_page' => $has_next_page,
			],
			'template' => 'multisite_list'
		];

		$response['content'] = $template->arrayRender($build);

		$response['success'] = true;
		$response['notifications'] = self::notifications();
		wp_send_json($response);
	}

	/**
	 * Request to remove site from WebTotem.
	 *
	 * @return void
	 */
	public static function twoFactorAuth()
	{

		if (WebTotemRequest::post('ajax_action') !== 'two_factor_auth') {
			return;
		}

		$action = WebTotemRequest::post('case_action');
		$template = new WebTotemTemplate();
		$current_user = wp_get_current_user();

		if ($user_id = (int)WebTotemRequest::post('user_id')) {
			if ($current_user->ID !== $user_id and !current_user_can('manage_options')) {

				WebTotemOption::setNotification('info', '$current_user->ID: ' . $current_user->ID . ', $user_id: ' . $user_id);
				WebTotemOption::setNotification('error', __('You cannot edit this user.', 'wtotem'));
				return;
			}
			$user = get_user_by('id', $user_id);
		} else {
			$user = $current_user;
		}

		switch ($action) {
			case 'activate':

				$g = new WebTotemGoogleAuthenticator();

				$secret = WebTotemRequest::post('secret');
				$recovery = WebTotemRequest::post('recovery');
				$code = WebTotemRequest::post('code');

				if ($g->checkCode($secret, $code)) {
					WebTotemLogin::saveData($user->ID, $recovery, $secret);
					WebTotemOption::setNotification('success', __('Your changes have been applied successfully.', 'wtotem'));
					$response['success'] = true;
				} else {
					WebTotemOption::setNotification('error', __('You have entered an incorrect activation code.', 'wtotem'));
					$response['success'] = false;
				}

				break;

			case 'deactivate':

				WebTotemLogin::delete($user->ID);

				$response['success'] = true;

				break;
		}

		$build[] = [
			'variables' => [
				'two_factor' => WebTotemLogin::getTwoFactorData($user),
				'page_nonce' => wp_create_nonce('wtotem_page_nonce'),
				'user_id' => $user->ID,
			],
			'template' => 'two_factor_auth'
		];

		$response['content'] = $template->arrayRender($build);

		$response['notifications'] = self::notifications();
		wp_send_json($response);
	}

	/**
	 * Changing the theme mode.
	 *
	 * @return void
	 */
	public static function changeThemeMode()
	{

		if (WebTotemRequest::post('ajax_action') !== 'theme_mode') {
			return;
		}

		$theme_mode = WebTotemOption::getSessionOption('theme_mode');

		if ($theme_mode == 'dark') {
			WebTotemOption::setSessionOptions(['theme_mode' => 'light']);
			$response = 'light';
		} else {
			WebTotemOption::setSessionOptions(['theme_mode' => 'dark']);
			$response = 'dark';
		}

		wp_send_json($response);
	}

	/**
	 * Set user time zone offset.
	 *
	 * @return void
	 */
	public static function userTimeZone()
	{

		if (WebTotemRequest::post('ajax_action') !== 'set_time_zone') {
			return;
		}

		$time_zone_offset = WebTotemRequest::post('offset');
		$now = strtotime('now');
		$check = WebTotemOption::getOption('time_zone_check') ?: 0;

		// Checking whether an hour has elapsed since the previous request.
		if ($now >= $check) {
			$time_zone = WebTotemAPI::getTimeZone();
			if ($time_zone) {
				$time_zone_offset = timezone_offset_get(new \DateTimeZone($time_zone), new \DateTime('now', new \DateTimeZone('Europe/London'))) / 3600;
				WebTotemOption::setOptions(['time_zone_check' => $now + 3600]);
			}
			WebTotemOption::setOptions(['time_zone_offset' => $time_zone_offset]);
		}

		wp_send_json([
			'success' => true,
			'time_zone_offset' => $time_zone_offset
		]);

	}

	/**
	 * Forced checking of services.
	 *
	 * @return void
	 */
	public static function force_check()
	{
		if (WebTotemRequest::post('ajax_action') !== 'force_check') {
			return;
		}

		$service = WebTotemRequest::post('service');
		$host = WebTotemAPI::siteInfo();
		$template = new WebTotemTemplate();

		$response['success'] = false;

		if($service){

            $services = [
                'ssl' => 'ssl',
                'rc' => 'reputation',
//                'dec' => 'location',
                'ops' => 'openPath',
                'ps' => 'openPort',
                'availability' => 'availability',
            ];

            // force check service
            if($service == 'av'){
			    $_response = WebTotemAPI::forceCheckAV();
            } else {
                if(isset( $services[$service] )){
                    $_response = WebTotemAPI::forceCheck($host['id'], $services[$service]);
                }
            }

			if (!isset($_response['message'])) {

				switch ($service) {

					case 'ssl':
					$data = WebTotemAPI::getMonitoringData($host['id']);

					$ssl = [
                        'status' => WebTotem::getStatusData($data['module_ssl']['info']['status']),
                        'cert_name' => $data['module_ssl']['result']['certificate_name'],
                        'days_left' => $data['module_ssl']['result']['days_left'],
                        'issue_date' => WebTotem::dateFormatter($data['module_ssl']['result']['issue_date']),
                        'expiry_date' => WebTotem::dateFormatter($data['module_ssl']['result']['expiry_date']),
					];

					$build[] = [
						'variables' => [
							'ssl' => $ssl,
						],
						'template' => 'monitoring_ssl',
					];

					$response['content'] = $template->arrayRender($build);
					$response['success'] = true;
					break;

					case 'availability':
					$data = WebTotemAPI::getMonitoringData($host['id']);

					$domain = [
                        'status' => WebTotem::getStatusData($data['module_location']['info']['status']),
                        "redirect_link" => $data['module_location']['result']['redirect_link'],
                        "is_created_at" => (bool)$data['module_location']['result']['checked_at'],
                        "created_at" => WebTotem::dateFormatter($data['module_location']['result']['checked_at']),
                        "is_taken" => $data['module_location']['result']['is_taken'],
                        "ips" => $data['module_location']['result']['locations'],
                        "protection" => $data['module_location']['result']['protection'],
					];

					$build[] = [
						'variables' => [
							'domain' => $domain,
                            'availability' => [
                                'chart' => json_encode($data['module_availability']['result']['stats_by_day']),
                                'status' => WebTotem::getStatusData($data['module_availability']['info']['status'])
                            ],
						],
						'template' => 'monitoring_domain',
					];

					$response['content'] = $template->arrayRender($build);
					$response['success'] = true;
					break;

					case 'rc':
					$data = WebTotemAPI::getMonitoringData($host['id']);

					$reputation = [
                        "status" => WebTotem::getStatusData($data['module_reputation']['info']['status'] ?? ''),
                        "info" => WebTotem::getReputationInfo($data['reputation']['result']['status'] ?? ''),
                        "last_test" => WebTotem::dateFormatter($data['reputation']['result']['checked_at'] ?? ''),
					];

					$build[] = [
						'variables' => [
							'reputation' => $reputation,
						],
						'template' => 'monitoring_reputation',
					];

					$response['content'] = $template->arrayRender($build);
					$response['success'] = true;
					break;

					case 'ps':
                        $data = WebTotemAPI::getMonitoringData($host['id']);
                        $ports = $data['module_port_scanner']['result']['open_ports'];

						if($ports['TCPResults']){
							$open_ports[] = [
								'variables' => [
                                    "ports" => WebTotem::getOpenPortsData($ports['open_ports'] ?? []),
								],
								'template' => 'open_ports',
							];

							$open_ports_few[] = [
								'variables' => [
									"ports" => $ports['open_ports'] ? WebTotem::getOpenPortsData(array_slice($ports['open_ports'], 0, 3)) : [],
                                    "more" => true,
								],
								'template' => 'open_ports',
							];
						}

						$ignore_ports[] = [
							'variables' => [
								"ports" => [], /** TODO ignore_ports **/
							],
							'template' => 'ignore_ports',
						];
						$response = [
							'status' => WebTotem::getStatusData($ports['module_port_scanner']['info']['status']),
							'last_test' =>  WebTotem::dateFormatter($data['module_port_scanner']['result']['checked_at']),
							'open_ports' => (isset($open_ports)) ? $template->arrayRender($open_ports) : '',
							'open_ports_few' =>  (isset($open_ports_few)) ? $template->arrayRender($open_ports_few) : '',
							'ignore_ports' => $template->arrayRender($ignore_ports),
						];

						$response['success'] = true;

						break;

					case 'ops':

                        $data = WebTotemAPI::getMonitoringData($host['id']);
						$open_path[] = [
							'variables' => [
								"paths" => $data['module_open_paths']['result']['open_paths'],
							],
							'template' => 'open_paths',
						];

						$response = [
                            'status' => WebTotem::getStatusData($data['module_open_paths']['info']['status'] ),
                            "last_test" => WebTotem::dateFormatter($data['module_open_paths']['result']['checked_at']  ?? false),
                            'open_paths' => $template->arrayRender($open_path),
						];

						$response['success'] = true;
						break;
				}

			}
		}

		$response['notifications'] = self::notifications();

		wp_send_json($response);
	}

	/**
	 * Initialization scanning and checking the current status.
	 *
	 * @return void
	 */
	public static function wtotem_scan()
	{

		if (WebTotemRequest::get('ajax_action') !== 'wtotem_scan') {
			return;
		}

		$logs_action = WebTotemRequest::get('scan_action');

		switch ($logs_action) {
			case 'init':
				if(!WebTotemOption::getOption('scan_init')){
					WebTotemOption::setOptions(['scan_init' => 1]);
					WebTotemScan::initialize();
					$response = [
							'success' => true,
							'scan_start' => 'success',
					];
				} else {
					$response = [
							'success' => false,
							'error' => 'The scan is already running',
					];
				}

				break;

			case 'push':
				if(WebTotemOption::getOption('scan_init')) {
					WebTotemScan::initialize();
					$response = [
							'success' => true,
							'scan_finished' => false,
							'push' => 'success',
					];
				} else {
					$response = [
							'success' => false,
							'scan_finished' => true,
							'push' => 'fail',
							'error' => 'Scan completed',
					];
				}

				break;
		}


		wp_send_json($response ?? ['success' => false, 'error' => 'No action found']);
	}

	/**
   * Forced checking of services.
   *
   * @return void
   */
  public static function user_feedback() {
	if (WebTotemRequest::post('ajax_action') !== 'user_feedback') {
	  return;
	}

	$data = [
	  'score' => (int)WebTotemRequest::post('score'),
	  'feedback' => WebTotemRequest::post('feedback') ?? "",
	];

	$response_data = WebTotemAPI::setFeedback($data);
	if($response_data['message'] == 'Score added'){
	  $response['content'] = '<div style="text-align: center;"><img src="'.WebTotem::getImagePath('').'popup_success_icon.svg" style="width: 85px;"><p class="user-feedback__title" style="margin-bottom: 20px">'.__('Thank you for feedback', 'wtotem').'</p><button id="user-feedback-ok" class="wtotem_control__btn">Okay</button></div>';
	  $response['success'] = true;
	  WebTotemOption::setNotification('success', __('Your reply has been sent successfully.', 'wtotem'));
	} else {
	  WebTotemOption::setNotification('error', __('There were difficulties. Your reply has not been sent.', 'wtotem'));
	  $response['success'] = false;
	}

	$response['notifications'] = self::notifications();

	wp_send_json($response);
  }

    public static function update_plugin() {

	    if (WebTotemRequest::post('ajax_action') !== 'update_plugin') {
            return;
        }
        $plugin_slug = WebTotemRequest::post('slug');

        include_once(ABSPATH . 'wp-admin/includes/class-wp-upgrader.php');

        $plugin = $plugin_slug . '/' . $plugin_slug . '.php';

        $upgrader = new Plugin_Upgrader();
        $upgrader->upgrade($plugin);

        WebTotemOption::setNotification('success', __('The plugin has been updated', 'wtotem'));
        die();
    }

    public static function after_plugin_update(){

        if (WebTotemRequest::post('ajax_action') !== 'after_plugin_update') {
            return;
        }
        $plugin_slug = WebTotemRequest::post('slug');

        $plugin_info = WebTotem::get_plugin_info($plugin_slug);

//        if( WebTotem::updateCveDataByPluginName($plugin_info)){
//
//            $template = new WebTotemTemplate();
//            $plugins_cve_list = WebTotemDB::getRows([], 'plugins_cve_list', false, ['limit' => 8, 'page' => 1]);
//            $response['content'] = $template->arrayRender([
//                'variables' => [
//                    "logs" => WebTotem::preparePluginsCveList($plugins_cve_list['data']),
//                ],
//                'template' => 'scan_logs_cve',
//            ]);
//            $response['count'] = $plugins_cve_list['count'];
//            $response['pagination'] = WebTotem::paginationBuild(8, $plugins_cve_list['count']);
//        }

        $response['notifications'] = self::notifications();

        wp_send_json($response);
    }

	public static function authenticate()
	{

		if (WebTotemRequest::post('ajax_action') !== 'authenticate') {
			return;
		}

		$credentials = array(
			'log' => 'pwd',
			'username' => 'password'
		);
		$username = null;
		$password = null;
		foreach ($credentials as $usernameKey => $passwordKey) {
			if (array_key_exists($usernameKey, $_POST) &&
				array_key_exists($passwordKey, $_POST) &&
				is_string($_POST[$usernameKey]) &&
				is_string($_POST[$passwordKey])) {
				$username = $_POST[$usernameKey];
				$password = $_POST[$passwordKey];
				break;
			}
		}
		if (empty($username) || empty($password)) {
			$response['error'] = wp_kses(sprintf(__('<strong>ERROR</strong>: A username and password must be provided. <a href="%s" title="Password Lost and Found">Lost your password</a>?'), wp_lostpassword_url()), array('strong' => array(), 'a' => array('href' => array(), 'title' => array())));
		}

		do_action_ref_array('wp_authenticate', array(&$username, &$password));

		$user = wp_authenticate($username, $password);
		$user = WebTotemBFProtection::checkBruteForceAttempts($user, $username);

		if (is_object($user) && ($user instanceof \WP_User)) {

			$response['login'] = true;

			if (WebTotemLogin::hasUser2faActivated($user)) {

				$template = new WebTotemTemplate();

				$response['2fa'] = true;
				$response['content'] = $template->getHtml('login_auth_form');

			}
		} else if (is_wp_error($user)) {
			$errors = array();
			foreach ($user->get_error_codes() as $code) {
				if ($code == 'invalid_username' || $code == 'invalid_email' || $code == 'incorrect_password' || $code == 'authentication_failed') {
					$errors[] = wp_kses(sprintf(__('<strong>ERROR</strong>: The username or password you entered is incorrect. <a href="%s" title="Password Lost and Found">Lost your password</a>?'), wp_lostpassword_url()), array('strong' => array(), 'a' => array('href' => array(), 'title' => array())));
				} else {
					foreach ($user->get_error_messages($code) as $error_message) {
						$errors[] = $error_message;
					}
				}
			}

			if (!empty($errors)) {
				$errors = implode('<br>', $errors);
				$response['error'] = apply_filters('login_errors', $errors);
			}

		}

		wp_send_json($response);
	}

	/**
	 * Notification output.
	 *
	 * @return string
	 */
	public static function notifications()
	{

		$notifications = WebTotem::getNotifications();

		if ($notifications) {
			$build[] = [
				'variables' => [
					'notifications' => $notifications,
				],

				'template' => 'notifications',
			];

			$template = new WebTotemTemplate();
			return $template->arrayRender($build);
		}
		return false;

	}


}

```
