PluginProbe
WebTotem Security / 2.4.11
WebTotem Security v2.4.11
3.0.2 3.0.1 3.0.0 trunk 1.0 1.1 1.2 1.3 1.3.1 1.3.2 1.3.3 2.0 2.1 2.1.1 2.1.2 2.1.3 2.1.4 2.1.5 2.1.6 2.1.7 2.1.8 2.1.9 2.2.1 2.2.2 2.2.3 All 110 releases
← All changes | lib/API.php +784 -859 trunk2.4.11 View file →
@@ -1,11 +1,11 @@
1 1 <?php
2 2
3 3 if (!defined('WEBTOTEM_INIT') || WEBTOTEM_INIT !== true) {
4 - if (!headers_sent()) {
5 - header('HTTP/1.1 403 Forbidden');
6 - }
7 - die("Protected By WebTotem!");
4 + if (!headers_sent()) {
5 + header('HTTP/1.1 403 Forbidden');
6 + }
7 + die("Protected By WebTotem!");
8 8 }
9 9
10 10 /**
11 11 * WebTotem API class.
@@ -15,1001 +15,926 @@
15 15 * @version 1.0
16 16 * @copyright (C) 2022 WebTotem team (http://wtotem.com)
17 17 * @license GNU/GPL: http://www.gnu.org/copyleft/gpl.html
18 18 */
19 -class WebTotemAPI extends WebTotem
20 -{
19 +class WebTotemAPI extends WebTotem {
21 20
22 - /**
23 - * HTTP status of the most recent API call, 0 when the request never landed.
24 - *
25 - * @var int
26 - */
27 - protected static $last_status = 0;
21 + /**
22 + * Method for getting a auth token.
23 + *
24 + * @param string $api_key
25 + * Application programming interface key.
26 + *
27 + * @return bool|string
28 + * Returns auth status
29 + */
30 + public static function auth($api_key) {
31 + $domain = WEBTOTEM_SITE_DOMAIN;
28 32
29 - /**
30 - * HTTP status of the most recent API call.
31 - *
32 - * @return int
33 - * Status code, or 0 when the request did not reach the server.
34 - */
35 - public static function getLastStatus()
36 - {
37 - return (int) self::$last_status;
38 - }
33 + $payload = '{"query":"mutation{ guest{ apiKeys{ auth(apiKey:\"' . $api_key . '\", source:\"' . $domain . '\"),{ token{ value, refreshToken, expiresIn } } } } }"}';
34 + $result = self::sendRequest($payload, FALSE, TRUE);
39 35
40 - /**
41 - * Raises a notification unless the caller asked to stay quiet.
42 - *
43 - * Probing calls (such as the WebSocket ticket, which is expected to be
44 - * missing on older API builds) must not spam the admin with errors.
45 - *
46 - * @param bool $silent
47 - * TRUE to swallow the notification.
48 - * @param string $type
49 - * Notification type.
50 - * @param string $message
51 - * Notification text.
52 - *
53 - * @return void
54 - */
55 - protected static function notify($silent, $type, $message)
56 - {
57 - if (!$silent) {
58 - WebTotemOption::setNotification($type, $message);
59 - }
36 + if (isset($result['data']['guest']['apiKeys']['auth']['token']['value'])) {
37 + $auth_token = $result['data']['guest']['apiKeys']['auth']['token'];
38 + WebTotemOption::login(['token' => $auth_token, 'api_key' => $api_key]);
39 + return 'success';
40 + } elseif($result['errors'][0]['message'] == 'INVALID_API_KEY') {
41 + WebTotemOption::logout();
60 42 }
61 43
44 + return FALSE;
45 + }
62 46
63 - /**
64 - * Method for getting an auth token.
65 - *
66 - * @param string $api_key
67 - * Application programming interface key.
68 - *
69 - * @return bool|string
70 - * Returns auth status
71 - */
72 - public static function auth($api_key, $repeat = FALSE)
73 - {
74 - $domain = WEBTOTEM_SITE_DOMAIN;
47 + /**
48 + * Get site info from API server.
49 + *
50 + * @param string $attempt
51 + * Is the request an attempt to get host data.
52 + *
53 + * @return array
54 + * Returns host data.
55 + */
56 + public static function siteInfo($attempt = FALSE) {
75 57
76 - if (empty($api_key)) {
77 - return FALSE;
78 - }
58 + if(self::isMultiSite()){
59 + $host['id'] = WebTotemOption::getSessionOption('host_id');
79 60
80 - $data = ['api_key' => $api_key, 'site' => $domain];
81 - $result = self::sendRequest('auth/sign-in/api-key', $data, 'POST', FALSE, TRUE);
61 + if ($host['id']) {
62 + return $host;
63 + }
64 + }
82 65
83 - if($result === null){
84 - WebTotemOption::setNotification('warning' , __('Authorization failed. The server may be temporarily unavailable', 'wtotem'));
85 - }
66 + $host = WebTotemOption::getHost();
86 67
87 - if (isset($result['access_token'])) {
88 - $auth_token = $result['access_token'];
89 - if(!WebTotemOption::isActivated()){
90 - WebTotemOption::login(['token' => $auth_token, 'api_key' => $api_key]);
91 - WebTotemAgentManager::postdelete();
92 - } else {
93 - WebTotemOption::refreshToken($auth_token);
94 - }
95 -
96 - return 'success';
97 - } elseif (isset($result['message']) and $result['message'] == 'invalid credentials') {
98 - WebTotemOption::logout();
99 - }
100 -
101 - if($repeat == false){
102 - //self::checkEndpoint();
103 - return self::auth($api_key, true);
104 - }
105 -
106 - return FALSE;
68 + if ($host['id']) {
69 + return $host;
107 70 }
108 71
109 - /**
110 - * Method for getting API url.
111 - *
112 - * @return string|bool
113 - * API url
114 - */
115 - public static function getApiUrl()
116 - {
117 - return 'https://app.wtotem.com';
118 - }
72 + $all_sites = self::getSites(null, 0);
73 + if($all_sites){
74 + if(self::isMultiSite()) {
75 + $sites = get_sites();
76 + foreach ($sites as $site){
77 + $domain = untrailingslashit($site->domain . $site->path);
78 + self::addSite($domain, $all_sites);
79 + }
119 80
120 - /**
121 - * Method for getting the WebSocket endpoint url.
122 - *
123 - * @return string
124 - * WebSocket url, without any credentials.
125 - */
126 - public static function getWsUrl()
127 - {
128 - $api_url = WebTotemOption::getOption('api_url');
129 - if (!$api_url) {
130 - $api_url = self::getApiUrl();
131 - }
81 + if (!$attempt) {
82 + return self::siteInfo(TRUE);
83 + }
84 + }
85 + else {
86 + $domain = WEBTOTEM_SITE_DOMAIN;
87 + return self::addSite($domain, $all_sites);
88 + }
89 + }
132 90
133 - return preg_replace('#^http#i', 'ws', rtrim($api_url, '/')) . '/api/v1/ws';
134 - }
91 + return [];
92 + }
135 93
94 + /**
95 + * Method for adding a site to the WebTotem platform.
96 + *
97 + * @param string $domain
98 + * Domain to add.
99 + * @param array $all_sites
100 + * Array with site data on the WebTotem platform.
101 + *
102 + * @return array
103 + * Returns host data.
104 + */
105 + public static function addSite( $domain, $all_sites) {
136 106
137 - /**
138 - * Get site info from API server.
139 - *
140 - * @param string $attempt
141 - * Is the request an attempt to get host data.
142 - *
143 - * @return array
144 - * Returns host data.
145 - */
146 - public static function siteInfo($attempt = FALSE)
147 - {
148 - if (self::isMultiSite()) {
149 - $host['id'] = WebTotemOption::getSessionOption('host_id');
150 - $host['name'] = WebTotemOption::getSessionOption('host_name');
107 + if(function_exists('idn_to_utf8')){
108 + $domain = idn_to_utf8($domain);
109 + }
151 110
152 - if ($host['id']) {
153 - return $host;
154 - }
155 - }
111 + // Checking if the site has been added to the WebTotem.
112 + if(array_key_exists('edges', $all_sites)){
156 113
157 - $host = WebTotemOption::getHost();
114 + foreach ($all_sites['edges'] as $site){
115 + $site = $site['node'];
116 + $hostname = untrailingslashit($site['hostname']);
117 + // If it added, save site data to DB.
118 + if($hostname == $domain or $hostname == 'www.' . $domain){
119 + WebTotemOption::setHost($site['hostname'], $site['id']);
120 + return [
121 + 'id' => $site['id'],
122 + 'name' => $site['hostname'],
123 + ];
124 + }
125 + }
158 126
159 - if ($host['id']) {
160 - return $host;
161 - }
127 + }
162 128
163 -// if (self::isMultiSite()) {
164 -// $sites = get_sites();
165 -// foreach ($sites as $site) {
166 -// $domain = untrailingslashit($site->domain . $site->path);
167 -// self::addSite($domain);
168 -// }
169 -//
170 -// if (!$attempt) {
171 -// return self::siteInfo(TRUE);
172 -// }
173 -// } else {
174 -// $domain = WEBTOTEM_SITE_DOMAIN;
175 -// return self::addSite($domain);
176 -// }
177 - $domain = WEBTOTEM_SITE_DOMAIN;
178 - return self::addSite($domain);
129 + // If the site is not added then try to add.
130 + $payload = '{"variables":{"input":{"title":"' . $domain . '","hostname":"' . $domain . '","configs":{"scheme":"http","port":80,"wa":{},"dec":{},"ps":{}}}},"query":"mutation ($input: CreateSiteInput) { auth { sites { create(input: $input) { id hostname title } } } }"}';
131 + $add_site = self::sendRequest($payload, TRUE);
132 + if (isset($add_site['errors'])) {
133 + WebTotemOption::setNotification('error', __('Failed to add the site to the WebTotem platform.', 'wtotem'));
134 + }
135 + else {
136 + if($host = $add_site['data']['auth']['sites']['create']) {
137 + // If it added, save site ID.
138 + WebTotemOption::setHost($host['title'], $host['id']);
139 + return [
140 + 'id' => $host['id'],
141 + 'name' => $host['title'],
142 + ];
143 + }
144 + }
145 + return [];
146 + }
179 147
180 -// return [];
181 - }
148 + /**
149 + * Get all sites from API.
150 + *
151 + * @param string $cursor
152 + * Mark for loading data.
153 + * @param string $limit
154 + * Limit of sites to loading.
155 + *
156 + * @return array
157 + * Returns host data.
158 + */
159 + public static function getSites($cursor = null, $limit = 15, $filter = false) {
160 + $cursor = ($cursor == null) ? 'null' : '\"' . $cursor . '\"';
161 + if(!$filter) {
162 + $filter = ($limit === 0) ? '' : 'pagination:{ first: ' . $limit . ', cursor: ' . $cursor . ' }';
163 + }
182 164
183 - /**
184 - * Method for adding a site to the WebTotem platform.
185 - *
186 - * @param string $domain
187 - * Domain to add.
188 - *
189 - * @return array
190 - * Returns host data.
191 - */
192 - public static function addSite($domain)
193 - {
194 - if (function_exists('idn_to_utf8')) {
195 - $domain = idn_to_utf8($domain);
196 - }
165 + $payload = '{"query":"query getSites { auth { viewer { sites { ...sites } } } } fragment sites on SiteQueries { list(filter: { ' . $filter . ' }) { pageInfo{ hasNextPage endCursor } edges { node { id hostname title createdAt ssl { status } availability { status } reputation { status } ports { status } deface { status } domain { status } antivirus { status } firewall { status } maliciousScript { stack { name } } } } } }"}';
166 + $result = self::sendRequest($payload, true);
197 167
198 - // Checking if the site has been added to the WebTotem.
199 - if(!$host = self::getHostID($domain)){
200 - $host = self::getHostID('www.' . $domain);
201 - }
168 + if (isset($result['data']['auth']['viewer']['sites']['list']['edges'])) {
169 + return $result['data']['auth']['viewer']['sites']['list'];
170 + }
202 171
203 - if($host['id']){
204 - // Remember the binding: otherwise every page load asks the API
205 - // for the host id again (and again for the www. variant).
206 - WebTotemOption::setHost($host['hostname'], $host['id']);
172 + return [];
173 + }
207 174
208 - return [
209 - 'id' => $host['id'],
210 - 'name' => $host['hostname'],
211 - ];
212 - }
175 + /**
176 + * Method to get the agents file names and AM file link.
177 + *
178 + * @param string $host_id
179 + * Host id on WebTotem.
180 + *
181 + * @return array
182 + * Returns agents files data.
183 + */
184 + public static function getAgentsFiles($host_id) {
213 185
214 - // If the site is not added then try to add.
215 - $data = ['hosts' => [$domain]];
216 - $response = self::sendRequest('hosts', $data, 'POST', TRUE);
186 + if(WebTotem::isMultiSite()){
187 + $all_hosts = WebTotemOption::getOption('all_hosts') ?: [];
188 + $siteIdsArray = $all_hosts ? array_values($all_hosts) : [];
189 + $siteIds = $siteIdsArray ? addslashes(WebTotem::convertArrayToString($siteIdsArray)) : '';
217 190
218 - if (isset($response['message'])) {
219 - WebTotemOption::setNotification('error', __('Failed to add the site to the WebTotem platform.', 'wtotem'));
220 - } else {
221 - if ($response['data']['added']) {
222 - // If it added, save site ID.
223 - $host = self::getHostID($domain);
224 - WebTotemOption::setHost($domain, $host['id']);
225 - return [
226 - 'id' => $host['id'],
227 - 'name' => $host['hostname'],
228 - ];
229 - }
230 - }
231 - return [];
232 - }
191 + $payload = '{"query":"mutation { auth { am { installMultisite(mainSiteId: \"' . $host_id . '\", siteIds: [' . $siteIds . ']){ downloadLink, amFilename, wafFilename, avFilename } } } }"}';
192 + $response = self::sendRequest($payload, TRUE);
233 193
234 - /**
235 - * Get all sites from API.
236 - *
237 - * @param string $page_num
238 - * Mark for loading data.
239 - * @param string $limit
240 - * Limit of sites to loading.
241 - *
242 - * @return array
243 - * Returns host data.
244 - */
245 - public static function getSites($page_num = 1, $page_size = 15, $status = 'active', $hostname = '')
246 - {
247 - $query = [
248 - 'page_num' => $page_num,
249 - 'page_size' => $page_size,
250 - 'status' => $status,
251 - ];
194 + return $response['data']['auth']['am']['installMultisite'];
195 + }
196 + else {
197 + $payload = '{"query":"mutation { auth { am { install(siteId: \"' . $host_id . '\"){ downloadLink, amFilename, wafFilename, avFilename } } } }"}';
198 + $response = self::sendRequest($payload, TRUE);
199 + return $response['data']['auth']['am']['install'];
200 + }
201 + }
252 202
253 - if ($hostname !== '') {
254 - $query['hostname'] = $hostname;
255 - }
203 + /**
204 + * Add secondary MultiSite host.
205 + *
206 + * @param $new_sites
207 + * An array with sites to add.
208 + *
209 + * @return void.
210 + */
211 + public static function addMultiSiteNewSites($new_sites){
212 + // Host id of the main site in MultiSite network.
213 + $main_host = WebTotemOption::getMainHost();
256 214
257 - $result = self::sendRequest('hosts', $query, 'GET', TRUE);
215 + foreach ($new_sites as $site){
216 + $all_sites = self::getSites(null, 0);
217 + $host = self::addSite($site, $all_sites);
218 + if(key_exists('id', $host)){
219 + $payload = '{"query":"mutation { auth { am { addMultisiteHost(mainSiteId: \"' . $main_host['id'] . '\", siteId: \"' . $host['id'] . '\") } } }"}';
258 220
259 - // The API answers { "data": { "hosts": [...], "host_limit": n, "can_defrost": bool } }.
260 - $payload = self::payload($result);
221 + $result = self::sendRequest($payload, TRUE);
222 + if(!$result['errors'][0]['message']){
223 + WebTotemOption::setNotification( 'info', __('A new website has been added: ', 'wtotem') . $new_sites);
224 + }
225 + }
226 + }
227 + }
261 228
262 - return isset($payload['hosts']) && is_array($payload['hosts']) ? $payload['hosts'] : [];
263 - }
229 + /**
230 + * Remove secondary MultiSite host.
231 + *
232 + * @param $host_id
233 + * Host id on WebTotem.
234 + *
235 + * @return bool
236 + * Returns result removing host.
237 + */
238 + public static function removeMultiSiteHost($host_id){
239 + $payload = '{"query":"mutation { auth { am { removeMultisiteHost(siteId: \"' . $host_id . '\") } } }"}';
240 + $response = self::sendRequest($payload, TRUE);
241 + return $response['data']['auth']['am']['removeSecondaryMultisiteHost'];
242 + }
264 243
265 - /**
266 - * Reads the payload out of the API response envelope.
267 - *
268 - * Most endpoints answer { "data": ... }; a few older builds used "Data".
269 - *
270 - * @param mixed $response
271 - * Decoded API response.
272 - *
273 - * @return array
274 - * Payload, or an empty array when the response carried none.
275 - */
276 - protected static function payload($response)
277 - {
278 - if (!is_array($response)) {
279 - return [];
280 - }
244 + /**
245 + * Method to get agents (AM, WAF, AV) statuses.
246 + *
247 + * @param string $host_id
248 + * Host id on WebTotem.
249 + *
250 + * @return array
251 + * Returns agents statuses data.
252 + */
253 + public static function getAgentsStatusesFromAPI($host_id) {
254 + $payload = '{"query":"query ($id: ID!) { auth { viewer { sites { one(id: $id) { agentManager { statuses { am { status } av { status } waf { status } } } } } } } }", "variables":{"id":"' . $host_id . '"}}';
255 + $response = self::sendRequest($payload, TRUE);
281 256
282 - foreach (['data', 'Data'] as $key) {
283 - if (isset($response[$key]) && is_array($response[$key])) {
284 - return $response[$key];
285 - }
286 - }
287 -
288 - return [];
257 + if (isset($response['data']['auth']['viewer']['sites']['one']['agentManager']['statuses'])) {
258 + return $response['data']['auth']['viewer']['sites']['one']['agentManager']['statuses'];
289 259 }
290 260
291 - /**
292 - * Requests a single-use ticket for the browser WebSocket connection.
293 - *
294 - * The ticket replaces the access token that used to be printed into the
295 - * page: it is short-lived, may be used once, and is bound to the browser
296 - * Origin it was issued for.
297 - *
298 - * @param string $origin
299 - * Browser origin the ticket is issued for, e.g. https://example.com.
300 - *
301 - * @return string
302 - * The ticket, or an empty string when it could not be obtained.
303 - */
304 - public static function getWSTicket($origin = '')
305 - {
306 - $query = [];
307 - if (is_string($origin) && $origin !== '') {
308 - // add_query_arg() does not encode values; the origin carries "://".
309 - $query['origin'] = rawurlencode($origin);
310 - }
261 + return [];
262 + }
311 263
312 - $response = self::sendRequest('ws/ticket', $query, 'GET', TRUE, FALSE, TRUE);
264 + /**
265 + * Method to get user time zone.
266 + *
267 + * @return string|bool
268 + * Returns time zone data.
269 + */
270 + public static function getTimeZone() {
271 + $payload = '{"query":"query { auth { viewer{ timezone } } } "}';
272 + $response = self::sendRequest($payload, TRUE);
313 273
314 - if (is_array($response) && !empty($response['ticket'])) {
315 - return (string) $response['ticket'];
316 - }
317 -
318 - // Tolerate a wrapped answer in case the endpoint starts using the envelope.
319 - $payload = self::payload($response);
320 -
321 - return !empty($payload['ticket']) ? (string) $payload['ticket'] : '';
274 + if (isset($response['data']['auth']['viewer']['timezone'])) {
275 + return $response['data']['auth']['viewer']['timezone'];
322 276 }
277 + return FALSE;
278 + }
323 279
324 - /**
325 - * Check the site's presence in the list on the API side.
326 - *
327 - * @param string $site
328 - * The domain we want to check.
329 - *
330 - * @return array
331 - * Returns host data.
332 - */
333 - public static function getHostID($site)
334 - {
335 - $result = self::sendRequest('hosts/id', ['hostname' => $site], 'GET', TRUE);
280 + /**
281 + * Method for get all the site security data.
282 + *
283 + * @param string $host_id
284 + * Host id on WebTotem.
285 + * @param int|array $days
286 + * For what period data is needed.
287 + *
288 + * @return array
289 + * Returns all data.
290 + */
291 + public static function getAllData($host_id, $days = 7) {
292 + $language = WebTotem::getLanguage();
293 + $period = WebTotem::getPeriod($days);
336 294
337 - if (isset($result['data'])) {
338 - WebTotemOption::setOptions(['config_id' => $result['data']['config_id']]);
339 - return ['id' => $result['data']['host_id'], 'hostname' => $site];
340 - }
295 + $payload = '{"query":"query($id: ID!, $dateRange: DateRangeInput!, $language: Language!, $dateRangeWeek: DateRangeInput!, $wafLogFilter: WafLogFilter!) { auth { viewer { sites { one(id: $id) { ports { status ip tcp ignorePorts lastTest { time } } availability { status lastTest { time } responseTime downTime(dateRange: $dateRange) percent(dateRange: $dateRange) } deface { status lastTest { time } words count } domain { status registrar owner email createdDate expiredDate } ports { status lastTest { time } ip tcp country } ssl { status daysLeft expiryDate issueDate } reputation { status lastTest { time } virusList { virus{ type path } antiVirus } } firewall { lastTest { time } logs(wafLogFilter: $wafLogFilter){ edges{ node{ type blocked payload ip location{ country{ nameEn } } time request status country category } } } map(dateRange: $dateRange) { attacks, country } status chart(dateRange: $dateRange) { time attacks blocked } report(dateRange: $dateRange) { time attacks ip } } serverStatus { info { phpVersion phpServerUser phpServerSoftware phpGatewayInterface phpServerProtocol osInfo cpuCount cpuModel CpuFreq cpuFamily lsCpu maxExecTime mathLibraries } ramChart(dateRange: $dateRangeWeek){ total value time } cpuChart(dateRange: $dateRangeWeek){ value time } discUsage{ total free } status } maliciousScript { lastTest { time } status } scoring( language: $language ){ score lastTest{ time } result{ ip country isHigherThan }} agentManager{ createdAt } antivirus { status stats { changed deleted scanned infected error } lastTest { time } isFirstCheck } } } } } }","variables":{"id":"' . $host_id . '","dateRange":{"to":' . $period['to'] . ',"from":' . $period['from'] . '}, "dateRangeWeek":{"to":' . $period['to'] . ',"from":' . $period['from'] . '}, "wafLogFilter": {"dateRange":{"to":' . $period['to'] . ',"from":' . $period['from'] . '},"order":{"direction":"DESC","field":"time"},"pagination":{"first": 10,"cursor":null}}, "language":"' . $language . '"}}';
296 + $response = self::sendRequest($payload, TRUE);
341 297
342 - return ['id' => '', 'hostname' => ''];
298 + if (isset($response['data']['auth']['viewer']['sites']['one'])) {
299 + return $response['data']['auth']['viewer']['sites']['one'];
343 300 }
344 301
302 + return [];
303 + }
345 304
346 - /**
347 - * Method to get the agents file names and AM file link.
348 - *
349 - * @param string $host_id
350 - * Host id on WebTotem.
351 - *
352 - * @return array
353 - * Returns agents files data.
354 - */
355 - public static function getAgentsFiles($host_id)
356 - {
305 + /**
306 + * Method to get firewall data.
307 + *
308 + * @param string $host_id
309 + * Host id on WebTotem.
310 + * @param int $limit
311 + * Limit on the number of records.
312 + * @param string $cursor
313 + * Mark for loading data.
314 + * @param int|array $days
315 + * For what period data is needed.
316 + *
317 + * @return array
318 + * Returns firewall data.
319 + */
320 + public static function getFirewall($host_id, $limit = 20, $cursor = NULL, $days = 365) {
321 + $period = WebTotem::getPeriod($days);
322 + $cursor = ($cursor == NULL) ? 'null' : '"' . $cursor . '"';
357 323
358 -// if (WebTotem::isMultiSite()) {
359 -// $all_hosts = WebTotemOption::getOption('all_hosts');
360 -// $all_hosts = $all_hosts ? json_decode($all_hosts, true) : [];
361 -//
362 -// $siteIdsArray = $all_hosts ? array_values($all_hosts) : [];
363 -// $siteIds = $siteIdsArray ? addslashes(WebTotem::convertArrayToString($siteIdsArray)) : '';
364 -//
365 -// $payload = '{"query":"mutation { auth { am { installMultisite(mainSiteId: \"' . $host_id . '\", siteIds: [' . $siteIds . ']){ downloadLink, amFilename, wafFilename, avFilename } } } }"}';
366 -// $response = self::sendRequest($payload, TRUE);
367 -//
368 -// if (isset($response['data']['auth']['am']['installMultisite'])) {
369 -// return $response['data']['auth']['am']['installMultisite'];
370 -// }
371 -// } else {
372 - $response = self::sendRequest('/agents/' . $host_id . '/install', [], 'POST', TRUE);
324 + $payload = '{"query":"query($id: ID!, $wafLogFilter: WafLogFilter!, $dateRange: DateRangeInput!) { auth { viewer { sites { one(id: $id) { firewall { lastTest { time } status map(dateRange: $dateRange) { attacks, country, location { country { nameEn } } } chart(dateRange: $dateRange) { time attacks blocked } ...FirewallLogFragment } agentManager { createdAt } } } } } } fragment FirewallLogFragment on Waf { logs(wafLogFilter: $wafLogFilter) { edges { cursor node { type blocked payload ip location { country { nameEn } } time request status country category } } pageInfo { endCursor hasNextPage } } }", "variables":{"dateRange":{"to":' . $period['to'] . ',"from":' . $period['from'] . '},"id":"' . $host_id . '","wafLogFilter":{"dateRange":{"to":' . $period['to'] . ',"from":' . $period['from'] . '},"order":{"direction":"DESC","field":"time"},"pagination":{"first":' . $limit . ',"cursor":' . $cursor . '}}} }';
325 + $response = self::sendRequest($payload, TRUE);
373 326
374 - if (isset($response['data'])) {
375 - return $response['data'];
376 - }
377 -// }
378 - return [];
379 - }
327 + if (isset($response['data']['auth']['viewer']['sites']['one'])) {
328 + return $response['data']['auth']['viewer']['sites']['one'];
329 + }
380 330
381 - /**
382 - * Add secondary MultiSite host.
383 - *
384 - * @param $new_sites
385 - * An array with sites to add.
386 - *
387 - * @return void.
388 - */
389 - public static function addMultiSiteNewSites($new_sites)
390 - {
331 + return [];
332 + }
391 333
392 - }
334 + /**
335 + * Method to get firewall chart data.
336 + *
337 + * @param string $host_id
338 + * Host id on WebTotem.
339 + * @param int $days
340 + * For what period data is needed.
341 + *
342 + * @return array
343 + * Returns firewall chart data.
344 + */
345 + public static function getFirewallChart($host_id, $days = 7) {
346 + $period = WebTotem::getPeriod($days);
393 347
394 - /**
395 - * Get the date of creation of the site.
396 - *
397 - * @param string $site
398 - * The domain we want to check.
399 - *
400 - * @return string|bool
401 - * Returns host data.
402 - */
403 - public static function getGetSiteAddedDate($site)
404 - {
405 - if (!$site) {
406 - return FALSE;
407 - }
348 + $payload = '{ "query":"query($id: ID!, $dateRange: DateRangeInput!) { auth { viewer { sites { one(id: $id) { firewall { lastTest { time } status map(dateRange: $dateRange) { attacks, country, location { country { nameEn } } } chart(dateRange: $dateRange) { time attacks blocked } } } } } } }", "operationName":null,"variables":{"id":"' . $host_id . '","dateRange":{"to":' . $period['to'] . ',"from":' . $period['from'] . '} } }';
349 + $response = self::sendRequest($payload, TRUE);
408 350
409 - $hosts = self::getSites(1, 1, 'active', $site);
351 + if (isset($response['data']['auth']['viewer']['sites']['one']['firewall'])) {
352 + return $response['data']['auth']['viewer']['sites']['one']['firewall'];
353 + }
410 354
411 - foreach ($hosts as $host) {
412 - if (!empty($host['created_at'])) {
413 - return $host['created_at'];
414 - }
415 - }
355 + return [];
356 + }
416 357
417 - return FALSE;
418 - }
358 + /**
359 + * Method to set firewall settings.
360 + *
361 + * @param string $host_id
362 + * Host id on WebTotem.
363 + * @param array $settings
364 + * User-specified settings.
365 + *
366 + * @return array
367 + * Returns information whether the request was successful.
368 + */
369 + public static function setFirewallSettings($host_id, array $settings) {
370 + $payload = '{"variables":{"input": {"siteId": "' . $host_id . '", "gdn": ' . $settings['gdn'] . ', "dosProtection": ' . $settings['dosProtection'] . ', "dosLimit": ' . $settings['dosLimit'] . ', "loginAttemptsProtection": ' . $settings['loginAttemptsProtection'] . ', "loginAttemptsLimit": ' . $settings['loginAttemptsLimit'] . '}},"query":"mutation WafSettings($input: WafSettingsInput!) { auth { sites { waf{ settings(input: $input) { gdn dosProtection loginAttemptsProtection dosLimit loginAttemptsLimit } } } } }"}';
371 + return self::sendRequest($payload, TRUE);
372 + }
419 373
420 - /**
421 - * Remove secondary MultiSite host.
422 - *
423 - * @param $host_id
424 - * Host id on WebTotem.
425 - *
426 - * @return bool
427 - * Returns result removing host.
428 - */
429 - public static function removeMultiSiteHost($host_id)
430 - {
374 + /**
375 + * Method to get antivirus data.
376 + *
377 + * @param array $params
378 + * Parameters for filtering data.
379 + *
380 + * @return array
381 + * Returns antivirus data.
382 + */
383 + public static function getAntivirus(array $params) {
384 + $cursor = ($params['cursor']) ? '"' . $params['cursor'] . '"' : 'null';
385 + $event = ($params['event']) ? '"' . $params['event'] . '"' : '"new"';
386 + $permissions = ($params['permissions']) ? ' "permissionsChanged":true, ' : '';
387 + $period = WebTotem::getPeriod($params['days']);
431 388
432 - return false;
433 - }
389 + $payload = '{"operationName":null,"variables":{"id":"' . $params['host_id'] . '","avLogFilter":{' . $permissions . '"event":' . $event . ', "dateRange":{"to":' . $period['to'] . ',"from":' . $period['from'] . '},"order":{"direction":"DESC","field":"time"},"pagination":{"first":' . $params['limit'] . ',"cursor":' . $cursor . '}}},"query":"query ($id: ID!, $avLogFilter: AvLogFilter!) { auth { viewer { sites { one(id: $id) { id ... on Site { configs { ... on AvConfig { isActive id } } } antivirus { quarantine{ id path date } status log(avLogFilter: $avLogFilter) { edges { node { filePath event signatures time permissions permissionsChanged } } pageInfo { endCursor hasNextPage __typename } } lastTest { time } stats { changed deleted scanned infected } } } } } } }"}';
390 + $response = self::sendRequest($payload, TRUE);
434 391
435 - /**
436 - * Method to get agents (AM, WAF, AV) statuses.
437 - *
438 - * @return array
439 - * Returns agents statuses data.
440 - */
441 - public static function getAgentsStatusesFromAPI()
442 - {
443 - $config_id = WebTotemOption::getOption('config_id');
444 - $response = self::sendRequest('/agents/' . $config_id . '/status', [], 'GET', TRUE);
445 -
446 - if (isset($response['data'])) {
447 - return $response['data'];
448 - }
449 -
450 - return [];
392 + if (isset($response['data']['auth']['viewer']['sites']['one']['antivirus'])) {
393 + return $response['data']['auth']['viewer']['sites']['one']['antivirus'];
451 394 }
395 + return [];
396 + }
452 397
453 - /**
454 - * Method for get monitoring data.
455 - *
456 - * @param string $host_id
457 - * Host id on WebTotem.
458 - * @param int|array $days
459 - * For what period data is needed.
460 - *
461 - * @return array
462 - * Returns all data.
463 - */
464 - public static function getMonitoringData($host_id)
465 - {
466 - $response = self::sendRequest('/dashboard/monitoring/' . $host_id . '/results', [], 'GET', TRUE);
398 + /**
399 + * Method to get antivirus last test.
400 + *
401 + * @param string $host_id
402 + * Host id on WebTotem.
403 + *
404 + * @return array
405 + * Returns antivirus last test data.
406 + */
407 + public static function getAntivirusLastTest($host_id) {
467 408
468 - if (isset($response['data'])) {
469 - return $response['data'];
470 - }
409 + $payload = '{"variables":{"id":"' . $host_id . '"},"query":"query ($id: ID!) { auth { viewer { sites { one(id: $id) { antivirus { status lastTest { time } } } } } } }"}';
410 + $response = self::sendRequest($payload, TRUE);
471 411
472 - return [];
412 + if (isset($response['data']['auth']['viewer']['sites']['one']['antivirus'])) {
413 + return $response['data']['auth']['viewer']['sites']['one']['antivirus'];
473 414 }
415 + return [];
416 + }
474 417
475 - /**
476 - * Method to get firewall data.
477 - *
478 - * @param int $limit
479 - * Limit on the number of records.
480 - * @param string $page
481 - * Page for loading data.
482 - * @param int|array $days
483 - * For what period data is needed.
484 - *
485 - * @return array
486 - * Returns firewall data.
487 - */
488 - public static function getFirewall($limit = 20, $page = 1, $days = 365)
489 - {
490 - $period = WebTotem::getPeriod($days);
418 + /**
419 + * Method to force check services.
420 + *
421 + * @param string $host_id
422 + * Host id on WebTotem.
423 + * @param string $service
424 + * Service that needs to be checked.
425 + *
426 + * @return array
427 + * Returns information whether the request was successful.
428 + */
429 + public static function forceCheck($host_id, $service) {
430 + $payload = '{"variables":{"id":"' . $host_id . '","service":"' . $service . '"},"query":"mutation ($id: ID!, $service: ForceCheckService!) { auth { sites { forceCheck(siteId: $id, service: $service) } } }"} ';
431 + return self::sendRequest($payload, TRUE);
432 + }
491 433
492 - $config_id = WebTotemOption::getOption('config_id');
493 - $response = self::sendRequest('/dashboard/firewall/' . $config_id . '/logs', [
494 - 'page_num' => $page,
495 - 'page_size' => $limit,
496 - 'from' => $period['from'],
497 - 'to' => $period['to']
498 - ], 'GET', TRUE);
434 + /**
435 + * Method to export antivirus report.
436 + *
437 + * @param string $host_id
438 + * Host id on WebTotem.
439 + * @param int|array $days
440 + * For what period data is needed.
441 + *
442 + * @return array
443 + * Returns information whether the request was successful.
444 + */
445 + public static function avExport($host_id, $days = 30) {
446 + $period = WebTotem::getPeriod($days);
447 + $payload = '{"variables":{ "input":{"siteId":"' . $host_id . '", "dateRange":{"to":' . $period['to'] . ',"from":' . $period['from'] . '} }},"query":"mutation ($input: AvLogExportInput!) { auth { sites { av { export(input: $input) } } } }"} ';
448 + return self::sendRequest($payload, TRUE);
449 + }
499 450
451 + /**
452 + * Method to get quarantine data.
453 + *
454 + * @param string $host_id
455 + * Host id on WebTotem.
456 + *
457 + * @return array
458 + * Returns quarantine data.
459 + */
460 + public static function getQuarantineList($host_id) {
461 + $payload = '{"query":"query{ auth{ viewer{ sites{ one(id:\"' . $host_id . '\"){ antivirus{ quarantine{ id path date } } } } } } } "}';
462 + $response = self::sendRequest($payload, TRUE);
500 463
501 - if (isset($response['data'])) {
502 - return $response['data'];
503 - }
504 -
505 - return [];
464 + if (isset($response['data']['auth']['viewer']['sites']['one']['antivirus']['quarantine'])) {
465 + return $response['data']['auth']['viewer']['sites']['one']['antivirus']['quarantine'];
506 466 }
467 + return [];
468 + }
507 469
508 - /**
509 - * Method to get firewall chart data.
510 - *
511 - * @param int $days
512 - * For what period data is needed.
513 - *
514 - * @return array
515 - * Returns firewall chart data.
516 - */
517 - public static function getFirewallStatistics($days = 7)
518 - {
519 - $period = WebTotem::getPeriod($days);
470 + /**
471 + * Method to move file to quarantine.
472 + *
473 + * @param string $host_id
474 + * Host id on WebTotem.
475 + * @param string $path
476 + * Path to the file.
477 + *
478 + * @return array
479 + * Returns information whether the request was successful.
480 + */
481 + public static function moveToQuarantine($host_id, $path) {
482 + $payload = '{"query":"mutation{ auth{ sites{ av{ moveToQuarantine(input:{ siteId:\"' . $host_id . '\", path:\"' . $path . '\" }) } } } } "}';
483 + return self::sendRequest($payload, TRUE);
484 + }
520 485
521 - $config_id = WebTotemOption::getOption('config_id');
522 - $response = self::sendRequest('/dashboard/firewall/' . $config_id . '/statistics', [
523 - 'from' => $period['from'],
524 - 'to' => $period['to']
525 - ], 'GET', TRUE);
486 + /**
487 + * Method to move file from quarantine.
488 + *
489 + * @param string $id
490 + * Id assigned to the file.
491 + *
492 + * @return array
493 + * Returns information whether the request was successful.
494 + */
495 + public static function moveFromQuarantine($id) {
496 + $payload = '{"query":"mutation{ auth{ sites{ av{ moveFromQuarantine(id: \"' . $id . '\") } } } } "}';
497 + return self::sendRequest($payload, TRUE);
498 + }
526 499
500 + /**
501 + * Method to get server status data.
502 + *
503 + * @param string $host_id
504 + * Host id on WebTotem.
505 + * @param int|array $days
506 + * For what period data is needed.
507 + *
508 + * @return array
509 + * Returns server status data.
510 + */
511 + public static function getServerStatusData($host_id, $days = 7) {
512 + $period = WebTotem::getPeriod($days);
513 + $payload = '{ "query":"query($id: ID!, $dateRange: DateRangeInput!) { auth { viewer { sites { one(id: $id) { serverStatus { ramChart(dateRange: $dateRange){ total value time } cpuChart(dateRange: $dateRange){ value time } } } } } } }", "variables":{"id":"' . $host_id . '","dateRange":{"to":' . $period['to'] . ',"from":' . $period['from'] . '} } }';
527 514
528 - if (isset($response['data'])) {
529 - return $response['data'];
530 - }
515 + $response = self::sendRequest($payload, TRUE);
531 516
532 - return [];
517 + if (isset($response['data']['auth']['viewer']['sites']['one']['serverStatus'])) {
518 + return $response['data']['auth']['viewer']['sites']['one']['serverStatus'];
533 519 }
534 520
535 - /**
536 - * Method to get firewall settings.
537 - *
538 - * @return array
539 - * Returns information whether the request was successful.
540 - */
541 - public static function getFirewallSettings()
542 - {
543 - $config_id = WebTotemOption::getOption('config_id');
544 - $response = self::sendRequest('/dashboard/firewall/' . $config_id . '/configs', [], 'GET', TRUE);
545 - if (isset($response['data'])) {
546 - return $response['data'];
547 - }
521 + return [];
522 + }
548 523
549 - return [];
550 - }
524 + /**
525 + * Method to remove port from ignore list.
526 + *
527 + * @param string $host_id
528 + * Host id on WebTotem.
529 + * @param string $port
530 + * User specified port.
531 + *
532 + * @return array
533 + * Returns information whether the request was successful.
534 + */
535 + public static function removeIgnorePort($host_id, $port) {
536 + $payload = '{"variables":{ "input": { "siteId": "' . $host_id . '", "port":' . $port . '} },"query":"mutation($input: IgnorePortInput!) { auth { sites { ps { removeIgnorePort(input: $input) } } } }"} ';
537 + return self::sendRequest($payload, TRUE);
538 + }
551 539
552 - /**
553 - * Method to set firewall settings.
554 - *
555 - * @param array $settings
556 - * User-specified settings.
557 - *
558 - * @return array
559 - * Returns information whether the request was successful.
560 - */
561 - public static function setFirewallSettings(array $settings)
562 - {
563 - $config_id = WebTotemOption::getOption('config_id');
564 - return self::sendRequest('/dashboard/firewall/' . $config_id . '/configs', $settings, 'PATCH', TRUE);
565 - }
540 + /**
541 + * Method to add port to ignore list.
542 + *
543 + * @param string $host_id
544 + * Host id on WebTotem.
545 + * @param string $port
546 + * User specified port.
547 + *
548 + * @return array
549 + * Returns information whether the request was successful.
550 + */
551 + public static function addIgnorePort($host_id, $port) {
552 + $payload = '{"variables":{ "input": { "siteId": "' . $host_id . '", "port":' . (int) $port . '} },"query":"mutation($input: IgnorePortInput!) { auth { sites { ps { addIgnorePort(input: $input) } } } }"} ';
553 + return self::sendRequest($payload, TRUE);
554 + }
566 555
556 + /**
557 + * Method to get all ports list.
558 + *
559 + * @param string $host_id
560 + * Host id on WebTotem.
561 + *
562 + * @return array
563 + * Returns ports data.
564 + */
565 + public static function getAllPortsList($host_id) {
566 + $payload = '{"query":"query($id: ID!) { auth { viewer { sites { one(id: $id) { ports { status ip tcp ignorePorts lastTest { time } } } } } } } ","variables":{"id":"' . $host_id . '"}}';
567 567
568 - /**
569 - * Method to get antivirus history data.
570 - *
571 - * @param int $page_num
572 - * Page number.
573 - * @param int $page_size
574 - * Number of entries per page.
575 - *
576 - * @return array
577 - * Returns antivirus history data.
578 - */
579 - public static function getAntivirusHistory($page_num = 1, $page_size = 10)
580 - {
581 - $config_id = WebTotemOption::getOption('config_id');
582 - $response = self::sendRequest('/dashboard/antivirus/' . $config_id . '/history', [
583 - 'page_num' => $page_num,
584 - 'page_size' => $page_size
585 - ], 'GET', TRUE);
568 + $response = self::sendRequest($payload, TRUE);
586 569
587 - if (isset($response['data'])) {
588 - return $response['data'];
589 - }
590 - return [];
570 + if (isset($response['data']['auth']['viewer']['sites']['one']['ports'])) {
571 + return $response['data']['auth']['viewer']['sites']['one']['ports'];
591 572 }
592 573
593 - /**
594 - * Method to get antivirus history details data.
595 - *
596 - * @param int $scan_id
597 - * Scan ID.
598 - * @param int $page_num
599 - * Page number.
600 - * @param int $page_size
601 - * Number of entries per page.
602 - *
603 - * @return array
604 - * Returns antivirus history data.
605 - */
606 - public static function getAntivirusHistoryDetails($scan_id, $page_num = 1, $page_size = 10)
607 - {
608 - $config_id = WebTotemOption::getOption('config_id');
609 - $response = self::sendRequest('/dashboard/antivirus/' . $config_id . '/history/' . $scan_id . '/details', [
610 - 'page_num' => $page_num,
611 - 'page_size' => $page_size
612 - ], 'GET', TRUE);
574 + return [];
575 + }
613 576
577 + /**
578 + * Method to get all reports.
579 + *
580 + * @param string $host_id
581 + * Host id on WebTotem.
582 + * @param int $limit
583 + * Limit on the number of records.
584 + * @param string $cursor
585 + * Mark for loading data.
586 + *
587 + * @return array
588 + * Returns reports data.
589 + */
590 + public static function getAllReports($host_id, $limit = 10, $cursor = NULL) {
591 + $cursor = ($cursor == NULL) ? 'null' : '"' . $cursor . '"';
592 + $payload = '{"variables":{"filter": { "order": { "direction": "DESC", "field": "created_at"}, "siteId":"' . $host_id . '", "pagination":{"first":' . $limit . ', "cursor":' . $cursor . '} } },"query":"query ReportsQuery($filter: ReportListFilter!) { auth { viewer { reports { list(filter: $filter) { edges { node { id site { hostname } createdAt wa dc ps rc sc av waf } cursor } pageInfo { endCursor hasNextPage } } } } } }"}';
593 + $response = self::sendRequest($payload, TRUE);
614 594
615 - if (isset($response['data'])) {
616 - return $response['data'];
617 - }
618 - return [];
595 + if (isset($response['data']['auth']['viewer']['reports']['list']['edges'])) {
596 + return $response['data']['auth']['viewer']['reports']['list'];
619 597 }
620 598
621 - /**
622 - * Method to get quarantine data.
623 - *
624 - * @param int $page_num
625 - * Page number.
626 - * @param int $page_size
627 - * Number of entries per page.
628 - *
629 - * @return array
630 - * Returns quarantine data.
631 - */
632 - public static function getAntivirusCurrentDetails($page_num = 1, $page_size = 5)
633 - {
634 - $config_id = WebTotemOption::getOption('config_id');
635 - $response = self::sendRequest('/dashboard/antivirus/' . $config_id . '/current/details', [
636 - 'page_num' => $page_num,
637 - 'page_size' => $page_size
638 - ], 'GET', TRUE);
599 + return [];
600 + }
639 601
640 - if (isset($response['data'])) {
641 - return $response['data'];
642 - }
643 - return [];
644 - }
602 + /**
603 + * Method to generate report.
604 + *
605 + * @param string $host_id
606 + * Host id on WebTotem.
607 + * @param int|array $days
608 + * For what period data is needed.
609 + * @param array $services
610 + * User-specified module settings.
611 + *
612 + * @return string|bool
613 + * Returns report download link.
614 + */
615 + public static function generateReport($host_id, $days, array $services) {
616 + $period = WebTotem::getPeriod($days);
617 + $language = WebTotem::getLanguage();
645 618
619 + $payload = '{"query":"query ($input: GenerateReportInput) { auth { viewer { reports { generate(input: $input) } } } }", "variables":{ "input": { "siteId": "' . $host_id . '", "from": ' . $period['from'] . ', "to": ' . $period['to'] . ', "wa": ' . $services['wa'] . ', "dc": ' . $services['dc'] . ', "ps": ' . $services['ps'] . ', "rc": ' . $services['rc'] . ', "sc": ' . $services['sc'] . ', "av": ' . $services['av'] . ', "waf": ' . $services['waf'] . ', "language": "' . $language . '" } } }';
620 + $response = self::sendRequest($payload, TRUE);
646 621
647 - /**
648 - * Method to force check Antivirus.
649 - *
650 - * @return mixed
651 - * Returns information whether the request was successful.
652 - */
653 - public static function forceCheckAV()
654 - {
655 - $config_id = WebTotemOption::getOption('config_id');
656 - return self::sendRequest('/dashboard/antivirus/' . $config_id . '/check', [], 'POST', TRUE);
622 + if (isset($response['data']['auth']['viewer']['reports']['generate'])) {
623 + return $response['data']['auth']['viewer']['reports']['generate'];
657 624 }
658 625
626 + return FALSE;
627 + }
659 628
660 - /**
661 - * Method to force check services.
662 - *
663 - * @param string $host_id
664 - * Host id on WebTotem.
665 - * @param string $module_name
666 - * Service that needs to be checked.
667 - *
668 - * @return array
669 - * Returns information whether the request was successful.
670 - */
671 - public static function forceCheck($host_id, $module_name)
672 - {
673 - return self::sendRequest('/dashboard/hosts/' . $host_id . '/check', ['module_name' => $module_name], 'POST', TRUE);
629 + /**
630 + * Method to download report.
631 + *
632 + * @param string $id
633 + * Assigned to the report.
634 + *
635 + * @return string|bool
636 + * Returns report download link.
637 + */
638 + public static function downloadReport($id) {
639 + $payload = '{"query": "query { auth { viewer { reports { download(id: \"' . $id . '\") } } } }"}';
640 + $response = self::sendRequest($payload, TRUE);
641 +
642 + if (isset($response['data']['auth']['viewer']['reports']['download'])) {
643 + return $response['data']['auth']['viewer']['reports']['download'];
674 644 }
675 645
676 - /**
677 - * Method to get quarantine data.
678 - *
679 - * @param int $page_num
680 - * Page number.
681 - * @param int $page_size
682 - * Number of entries per page.
683 - *
684 - * @return array
685 - * Returns quarantine data.
686 - */
687 - public static function getQuarantineList($page_num = 1, $page_size = 5)
688 - {
689 - $config_id = WebTotemOption::getOption('config_id');
690 - $response = self::sendRequest('/dashboard/antivirus/' . $config_id . '/quarantine', [
691 - 'page_num' => $page_num,
692 - 'page_size' => $page_size
693 - ], 'GET', TRUE);
646 + return FALSE;
647 + }
694 648
695 - if (isset($response['data'])) {
696 - return $response['data'];
697 - }
698 - return [];
649 + /**
650 + * Method to get configs data.
651 + *
652 + * @param string $host_id
653 + * Host id on WebTotem.
654 + *
655 + * @return array|bool
656 + * Returns configs data.
657 + */
658 + public static function getConfigs($host_id) {
659 + $payload = '{"query":"query{ auth{ viewer{ sites{ one(id:\"' . $host_id . '\"){ configs{ ... on WaConfig { id service isActive notifications } ... on WafConfig { id service isActive notifications } ... on AvConfig { id service isActive notifications } ... on DcConfig { id service isActive notifications } ... on DecConfig { id service isActive } ... on RcConfig { id service isActive notifications} ... on CmsConfig { id service isActive } ... on PsConfig { id service isActive notifications } ... on SsConfig { id service isActive } ... on ScConfig { id service isActive } } } } } } } "}';
660 + $response = self::sendRequest($payload, TRUE);
661 +
662 + if (isset($response['data']['auth']['viewer']['sites']['one']['configs'])) {
663 + return $response['data']['auth']['viewer']['sites']['one']['configs'];
699 664 }
700 665
701 - /**
702 - * Method to move file to quarantine.
703 - *
704 - * @param string $file_id
705 - * File ID.
706 - *
707 - * @return array
708 - * Returns information whether the request was successful.
709 - */
710 - public static function moveToQuarantine($file_id)
711 - {
712 - $config_id = WebTotemOption::getOption('config_id');
713 - return self::sendRequest('/dashboard/antivirus/' . $config_id . '/quarantine/to-quarantine', [
714 - 'file_id' => $file_id,
715 - ], 'POST', TRUE);
716 - }
666 + return FALSE;
667 + }
717 668
718 - /**
719 - * Method to move file from quarantine.
720 - *
721 - * @param string $file_id
722 - * File ID.
723 - *
724 - * @return array
725 - * Returns information whether the request was successful.
726 - */
727 - public static function moveFromQuarantine($file_id)
728 - {
729 - $config_id = WebTotemOption::getOption('config_id');
730 - return self::sendRequest('/dashboard/antivirus/' . $config_id . '/quarantine/from-quarantine', [
731 - 'file_id' => $file_id,
732 - ], 'POST', TRUE);
669 + /**
670 + * Method to toggle modules config.
671 + *
672 + * @param string $service_id
673 + * Service id that we enable or disable.
674 + *
675 + * @return string|bool
676 + * Returns information whether the request was successful.
677 + */
678 + public static function toggleConfigs($service_id) {
679 + $payload = '{"query":"mutation{ auth{ configs{ toggle(id: \"' . $service_id . '\"){ ... on WaConfig { service isActive } ... on AvConfig { service isActive } ... on DcConfig { service isActive } ... on DecConfig { service isActive } ... on RcConfig { service isActive } ... on CmsConfig { service isActive } ... on PsConfig { service isActive } ... on WafConfig { service isActive } } } } } "}';
680 + $response = self::sendRequest($payload, TRUE);
681 +
682 + if (isset($response['data']['auth']['configs']['toggle'])) {
683 + return $response['data']['auth']['configs']['toggle'];
733 684 }
734 685
735 - /**
736 - * Method to get allow/deny ip list.
737 - *
738 - * @param string $type
739 - * Type of ip list
740 - *
741 - * @return array|bool
742 - * Returns ip allow/deny lists.
743 - */
744 - public static function getIpLists($type = 'blacklist')
745 - {
746 - $config_id = WebTotemOption::getOption('config_id');
747 - $response = self::sendRequest('/dashboard/firewall/' . $config_id . '/configs/iplist', [
748 - 'type' => $type,
749 - ], 'GET', TRUE);
686 + return FALSE;
687 + }
750 688
751 - if (isset($response['data'])) {
752 - return $response['data'];
753 - }
689 + /**
690 + * Method to toggle modules notification.
691 + *
692 + * @param string $host_id
693 + * Host id on WebTotem.
694 + * @param string $service
695 + * Service id in which we enable or disable notifications.
696 + *
697 + * @return string|bool
698 + * Returns information whether the request was successful.
699 + */
700 + public static function toggleNotifications($host_id, $service) {
701 + $payload = '{"query":"mutation{ auth{ sites{ toggleNotifications(siteId: \"' . $host_id . '\", service: ' . $service . ') } } }"}';
702 + $response = self::sendRequest($payload, TRUE);
754 703
755 - return [];
704 + if (isset($response['data']['auth']['sites']['toggleNotifications'])) {
705 + return $response;//['data']['auth']['sites']['toggleNotifications'];
756 706 }
757 707
758 - /**
759 - * Method to add ip to allow/deny list.
760 - *
761 - * @param string $ip
762 - * Ip address.
763 - * @param string $type
764 - * Allow or deny type.
765 - *
766 - * @return bool
767 - * Returns information whether the request was successful.
768 - */
769 - public static function addIpToList($ips, $type)
770 - {
771 - $config_id = WebTotemOption::getOption('config_id');
772 - self::sendRequest('/dashboard/firewall/' . $config_id . '/configs/iplist?type=' . $type, [
773 - 'ip' => array_filter($ips),
774 - ], 'POST', TRUE);
708 + return FALSE;
709 + }
775 710
776 - return true;
777 - }
711 + /**
712 + * Method to get allow/deny ip list.
713 + *
714 + * @param string $host_id
715 + * Host id on WebTotem.
716 + *
717 + * @return array|bool
718 + * Returns ip allow/deny lists.
719 + */
720 + public static function getIpLists($host_id) {
721 + $payload = '{"variables":{ "id": "' . $host_id . '" },"query":"query($id: ID!) { auth { viewer { sites{ one(id: $id){ firewall{ blackList{ id ip createdAt } whiteList{ id ip createdAt } settings{ gdn dosProtection dosLimit loginAttemptsProtection loginAttemptsLimit } } } } } } }"} ';
722 + $response = self::sendRequest($payload, TRUE);
778 723
779 - /**
780 - * Method to remove ip from allow/deny list by id.
781 - *
782 - * @param string $ip
783 - * Ip address.
784 - * @param string $type
785 - * Allow or deny type.
786 - *
787 - * @return bool
788 - * Returns information whether the request was successful.
789 - */
790 - public static function removeIpFromList($ip, $type)
791 - {
792 - $config_id = WebTotemOption::getOption('config_id');
793 - self::sendRequest('/dashboard/firewall/' . $config_id . '/configs/iplist?type=' . $type, [
794 - 'ip' => $ip,
795 - ], 'DELETE', TRUE);
796 -
797 - return true;
724 + if (isset($response['data']['auth']['viewer']['sites']['one']['firewall'])) {
725 + return $response['data']['auth']['viewer']['sites']['one']['firewall'];
798 726 }
799 727
800 - /**
801 - * Sends a REST API request to the WebTotem API server.
802 - *
803 - * @param string $endpoint
804 - * REST API endpoint (e.g., 'scan', 'status', etc.).
805 - * @param array $data
806 - * Associative array of data to send as JSON body or query parameters.
807 - * @param string $method
808 - * HTTP method: GET, POST, PUT, DELETE (default is POST).
809 - * @param bool $useToken
810 - * Whether to include the auth token.
811 - * @param bool $retry
812 - * Used to prevent recursion on token renewal.
813 - *
814 - * @return array|null
815 - * API response as an associative array, or null on failure.
816 - */
817 - protected static function sendRequest($endpoint, $data = [], $method = 'POST', $useToken = false, $retry = false, $silent = false)
818 - {
819 - self::$last_status = 0;
820 - $api_key = WebTotemOption::getOption('api_key');
728 + return [];
729 + }
821 730
822 - // Get or initialize the API URL.
823 - $api_url = WebTotemOption::getOption('api_url');
824 - if (!$api_url) {
825 - $api_url = self::getApiUrl();
826 - WebTotemOption::setOptions(['api_url' => $api_url]);
827 - }
731 + /**
732 + * Method to add ip to allow/deny list.
733 + *
734 + * @param string $host_id
735 + * Host id on WebTotem.
736 + * @param string $ips
737 + * Ip address list.
738 + * @param string $list
739 + * Allow or deny list.
740 + *
741 + * @return bool
742 + * Returns information whether the request was successful.
743 + */
744 + public static function addIpToList($host_id, $ips, $list) {
828 745
829 - // The API previously answered 429: respect the requested pause instead of
830 - // hammering the server (and getting the whole site throttled).
831 - $throttled_until = (int) WebTotemOption::getOption('api_retry_after');
832 - if ($throttled_until > time()) {
833 - self::notify($silent, 'warning', sprintf(
834 - /* translators: %d: number of seconds to wait. */
835 - __('Too many requests to the WebTotem API. Please try again in %d seconds.', 'wtotem'),
836 - $throttled_until - time()
837 - ));
746 + if ($ips) {
747 + $ips = WebTotem::convertIpListForApi($ips);
748 + $payload = '{"variables":{ "input": { "siteId": "' . $host_id . '", "ips": ' . $ips . ', "color": "' . $list . '" } }, "query":"mutation($input: WafListInput!) { auth { sites { waf { addToList(input: $input){ status invalidIPs} } } } }"} ';
749 + $response = self::sendRequest($payload, TRUE);
838 750
839 - return NULL;
840 - }
751 + if (isset($response['data']['auth']['sites']['waf']['addToList'])) {
752 + return $response['data']['auth']['sites']['waf']['addToList'];
753 + }
754 + }
841 755
842 - $auth_token = NULL;
843 - if ($useToken) {
844 - $auth_token = WebTotemOption::getOption('auth_token');
845 - $auth_token_expired = (int) WebTotemOption::getOption('auth_token_expired');
756 + return FALSE;
757 + }
846 758
847 - if ((!$auth_token || $auth_token_expired <= time()) && !$retry) {
848 - $result = self::auth($api_key);
849 - if ($result === 'success') {
850 - return self::sendRequest($endpoint, $data, $method, $useToken, TRUE, $silent);
851 - }
852 - }
853 - }
759 + /**
760 + * Method to remove ip from allow/deny list by id.
761 + *
762 + * @param string $id
763 + * Id assignment to ip address.
764 + *
765 + * @return bool
766 + * Returns information whether the request was successful.
767 + */
768 + public static function removeIpFromList($id) {
769 + $payload = '{"variables":{ "id": "' . $id . '" },"query":"mutation($id: ID!) { auth { sites { waf { removeFromList(id: $id) } } } }"} ';
770 + $response = self::sendRequest($payload, TRUE);
854 771
855 - $url = rtrim($api_url, '/') . '/api/v1/' . ltrim($endpoint, '/');
772 + if (isset($response['data']['auth']['sites']['waf']['removeFromList'])) {
773 + return $response['data']['auth']['sites']['waf']['removeFromList'];
774 + }
856 775
857 - $args = [
858 - 'timeout' => 60,
859 - 'sslverify' => TRUE,
860 - 'headers' => [
861 - 'Accept' => 'application/json',
862 - 'Content-Type' => 'application/json',
863 - 'source' => 'WORDPRESS',
864 - ],
865 - ];
776 + return FALSE;
777 + }
866 778
867 - if ($auth_token) {
868 - $args['headers']['Authorization'] = "Bearer $auth_token";
869 - }
779 + /**
780 + * Method to get allow url list.
781 + *
782 + * @param string $host_id
783 + * Host id on WebTotem.
784 + *
785 + * @return array
786 + * Returns url allow lists.
787 + */
788 + public static function getAllowUrlList($host_id) {
789 + $payload = '{"query":"query { auth { viewer { sites { one(id: \"' . $host_id . '\"){ firewall{ urlWhiteList{ id url createdAt } } } } } } }"} ';
790 + $response = self::sendRequest($payload, TRUE);
870 791
871 - if (strtoupper($method) === 'GET') {
872 - $url = add_query_arg($data, $url);
873 - } else {
874 - $args['body'] = wp_json_encode($data);
875 - }
792 + if (isset($response['data']['auth']['viewer']['sites']['one']['firewall']['urlWhiteList'])) {
793 + return $response['data']['auth']['viewer']['sites']['one']['firewall']['urlWhiteList'];
794 + }
876 795
877 - $response = wp_remote_request($url, array_merge($args, ['method' => strtoupper($method)]));
796 + return [];
797 + }
878 798
879 - if (is_wp_error($response)) {
880 - self::notify($silent, 'error', WebTotem::messageForHuman(
881 - 'SERVER UNAVAILABLE: ' . $response->get_error_message()
882 - ));
799 + /**
800 + * Method to add url to allow list.
801 + *
802 + * @param string $host_id
803 + * Host id on WebTotem.
804 + * @param string $url
805 + * User-specified url.
806 + *
807 + * @return bool|string
808 + * Returns information whether the request was successful.
809 + */
810 + public static function addUrlToAllowList($host_id, $url) {
811 + $payload = '{"variables":{ "input": { "siteId": "' . $host_id . '", "url": "' . $url . '" } }, "query":"mutation($input: WafUrlWhiteListInput!) { auth { sites { waf { addToUrlWhiteList(input: $input) } } } }"} ';
812 + $response = self::sendRequest($payload, TRUE);
883 813
884 - return NULL;
885 - }
814 + if (isset($response['data']['auth']['sites']['waf']['addToUrlWhiteList'])) {
815 + return $response['data']['auth']['sites']['waf']['addToUrlWhiteList'];
816 + }
886 817
887 - $code = (int) wp_remote_retrieve_response_code($response);
888 - self::$last_status = $code;
889 - $body = wp_remote_retrieve_body($response);
890 - $decoded = json_decode($body, TRUE);
818 + return FALSE;
819 + }
891 820
892 - if (!is_array($decoded)) {
893 - $decoded = [];
894 - }
821 + /**
822 + * Method to remove url from allow list.
823 + *
824 + * @param string $id
825 + * Id assignment to url address.
826 + *
827 + * @return bool|string
828 + * Returns information whether the request was successful.
829 + */
830 + public static function removeUrlFromAllowList($id) {
831 + $payload = '{"variables":{ "id": "' . $id . '" }, "query":"mutation($id: ID!) { auth { sites { waf { removeFromUrlWhiteList(id: $id) } } } }"} ';
832 + $response = self::sendRequest($payload, TRUE);
895 833
896 - $error_message = isset($decoded['message']) ? (string) $decoded['message'] : '';
834 + if (isset($response['data']['auth']['sites']['waf']['removeFromUrlWhiteList'])) {
835 + return $response['data']['auth']['sites']['waf']['removeFromUrlWhiteList'];
836 + }
897 837
898 - // Terminal account states: show the dedicated page and stop.
899 - if ($error_message !== '') {
900 - if (stripos($error_message, 'Password expired') !== FALSE) {
901 - wtotem_error_page(['errors' => 'PASSWORD_EXPIRED']);
902 - exit();
903 - }
838 + return FALSE;
839 + }
904 840
905 - if (stripos($error_message, 'API_KEY_DEACTIVATED') !== FALSE) {
906 - wtotem_error_page(['errors' => 'TARIFF_EXPIRED']);
907 - exit();
908 - }
909 - }
841 + /**
842 + * Method to get user's email.
843 + *
844 + * @return string
845 + * Returns user's email.
846 + */
847 + public static function getEmail(){
848 + $payload = '{"query":"query { auth { viewer { email __typename } __typename } }"}';
849 + $response = self::sendRequest($payload, true);
910 850
911 - // 429 Too Many Requests: honour Retry-After and never re-authorize.
912 - if ($code === 429) {
913 - $delay = self::parseRetryAfter(wp_remote_retrieve_header($response, 'retry-after'));
914 - WebTotemOption::setOptions(['api_retry_after' => time() + $delay]);
915 - self::notify($silent, 'warning', sprintf(
916 - /* translators: %d: number of seconds to wait. */
917 - __('Too many requests to the WebTotem API. Please try again in %d seconds.', 'wtotem'),
918 - $delay
919 - ));
851 + return $response['data']['auth']['viewer']['email'];
852 + }
920 853
921 - return NULL;
922 - }
854 + /**
855 + * Function sends GraphQL request to API server.
856 + *
857 + * @param string $payload
858 + * Payload to be sent to API server.
859 + * @param bool $token
860 + * Whether a token is needed when sending a request.
861 + * @param bool $repeat
862 + * Required to avoid recursion.
863 + *
864 + * @return array
865 + * Returns response from WebTotem API.
866 + */
867 + protected static function sendRequest($payload, $token = FALSE, $repeat = FALSE) {
923 868
924 - // 401 Unauthorized: the token is gone or expired. Re-login by API key once.
925 - if ($code === 401) {
926 - if (!$retry && $api_key && self::auth($api_key, TRUE) === 'success') {
927 - return self::sendRequest($endpoint, $data, $method, $useToken, TRUE, $silent);
928 - }
869 + $api_key = WebTotemOption::getOption('api_key');
929 870
930 - self::notify($silent, 'error', WebTotem::messageForHuman(
931 - $error_message !== '' ? $error_message : 'invalid credentials'
932 - ));
871 + // Checking whether a token is needed.
872 + if ($token) {
873 + $auth_token = WebTotemOption::getOption('auth_token');
874 + $auth_token_expired = WebTotemOption::getOption('auth_token_expired');
933 875
934 - return $decoded;
876 + // Checking whether the token has expired.
877 + if ($auth_token_expired <= time() && !$repeat) {
878 + $result = self::auth($api_key);
879 + if ($result === 'success') {
880 + return self::sendRequest($payload, $token, TRUE);
935 881 }
936 -
937 - // 403 Forbidden: authenticated, but not allowed. Re-login would not help.
938 - if ($code === 403) {
939 - if (stripos($error_message, 'USERHOST_NOT_BELONG_TO_USER') !== FALSE) {
940 - self::forgetHost();
941 - } else {
942 - self::notify($silent, 'error', WebTotem::messageForHuman(
943 - $error_message !== '' ? $error_message : 'access denied'
944 - ));
945 - }
946 -
947 - return $decoded;
882 + else {
883 + if(isset($result['errors'])){
884 + $message = WebTotem::messageForHuman($result['errors'][0]['message']);
885 + WebTotemOption::setNotification('error', $message);
886 + }
948 887 }
888 + }
889 + }
949 890
950 - // Older API builds answer 200 with an error message in the body.
951 - if ($error_message !== '') {
952 - if ($error_message === 'invalid credentials') {
953 - if (!$retry && $api_key && self::auth($api_key, TRUE) === 'success') {
954 - return self::sendRequest($endpoint, $data, $method, $useToken, TRUE, $silent);
955 - }
956 - } elseif (stripos($error_message, 'USERHOST_NOT_BELONG_TO_USER') !== FALSE) {
957 - self::forgetHost();
958 - } else {
959 - self::notify($silent, 'error', WebTotem::messageForHuman($error_message));
960 - }
961 - }
891 + if (function_exists('wp_remote_post')) {
962 892
963 - return $decoded;
964 - }
893 + $args = [
894 + 'body' => $payload,
895 + 'timeout' => '60',
896 + 'sslverify' => false,
897 + 'headers' => [
898 + 'Content-Type:application/json',
899 + 'Content-Type' => 'application/json',
900 + 'Accept: application/json',
901 + 'source: WORDPRESS',
902 + ],
903 + ];
965 904
966 - /**
967 - * Reads the Retry-After header into a number of seconds.
968 - *
969 - * The header is either a number of seconds or an HTTP date.
970 - *
971 - * @param string $header
972 - * Raw Retry-After header value.
973 - *
974 - * @return int
975 - * Seconds to wait, clamped to a sane range.
976 - */
977 - protected static function parseRetryAfter($header)
978 - {
979 - $delay = 0;
980 - $header = is_string($header) ? trim($header) : '';
905 + if (isset($auth_token)) {
906 + $auth = "Bearer " . $auth_token;
907 + $args['headers'] = array_merge($args['headers'], ["Authorization" => $auth]);
908 + }
981 909
982 - if ($header !== '') {
983 - if (ctype_digit($header)) {
984 - $delay = (int) $header;
985 - } else {
986 - $timestamp = strtotime($header);
987 - if ($timestamp !== FALSE) {
988 - $delay = $timestamp - time();
989 - }
990 - }
991 - }
910 + $response = wp_remote_post(WEBTOTEM_API_URL, $args);
911 + $response = wp_remote_retrieve_body($response);
912 + $response = json_decode($response, true);
992 913
993 - if ($delay < 1) {
994 - $delay = 60;
995 - }
996 -
997 - // Never park the plugin for longer than an hour.
998 - return min($delay, HOUR_IN_SECONDS);
999 914 }
915 + else {
916 + $error = 'WP_REMOTE_POST_NOT_EXIST';
917 + }
1000 918
1001 - /**
1002 - * Drops the locally stored host binding after the API disowned it.
1003 - *
1004 - * @return void
1005 - */
1006 - protected static function forgetHost()
1007 - {
1008 - if (WebTotem::isMultiSite()) {
1009 - WebTotemOption::clearAllHosts();
919 + // Checking if there are errors in the response.
920 + if (isset($response['errors'][0]['message'])) {
921 + $message = WebTotem::messageForHuman($response['errors'][0]['message']);
922 + if (stripos($response['errors'][0]['message'], "INVALID_TOKEN") !== FALSE && !$repeat) {
923 + $response = self::auth($api_key);
924 + if ($response === 'success') {
925 + return self::sendRequest($payload, $token, TRUE);
1010 926 }
927 + }
928 + else {
929 + WebTotemOption::setNotification('error', $message); // for debug json_encode($payload).' '.
930 + }
931 + }
1011 932
1012 - WebTotemOption::clearOptions(['host_id', 'host_name']);
933 + if (!empty($error)) {
934 + WebTotemOption::setNotification('error', $error);
1013 935 }
936 +
937 + return $response;
938 + }
1014 939
1015 940 }