PluginProbe
ووسلام – همگام سازی ووکامرس و باسلام / 1.10.18
ووسلام – همگام سازی ووکامرس و باسلام v1.10.18
1.10.18 1.10.17 1.10.15 1.10.14 1.10.13 1.10.12 1.10.10 1.10.9 1.10.8 1.10.7 1.10.6 1.10.5 1.10.4 1.10.3 1.10.2 1.10.1 1.10.0 1.9.2 1.9.1 1.9.0 1.8.8 1.8.5 1.8.6 1.8.7 1.8.4 All 51 releases
sync-basalam / includes / Endpoints / InformationEndpoint.php

InformationEndpoint.php in ووسلام – همگام سازی ووکامرس و باسلام 1.10.18, at includes/Endpoints/InformationEndpoint.php

190 lines 5.6 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace SyncBasalam\Endpoints;
4
5 use SyncBasalam\Admin\Product\Category\CategoryMapping;
6 use SyncBasalam\Admin\Settings\SettingsConfig;
7 use SyncBasalam\Services\Api\RequestStatusTracker;
8 use SyncBasalam\Utilities\DateConverter;
9 use SyncBasalam\Services\ApiServiceManager;
10
11 defined('ABSPATH') || exit;
12
13 class InformationEndpoint
14 {
15 private const TOKEN_VALIDATION_URL = 'https://api.hamsalam.ir/api/v1/woo-plugin/validate-token';
16 private const SENSITIVE_SETTING_KEYS = [
17 SettingsConfig::TOKEN,
18 SettingsConfig::REFRESH_TOKEN,
19 SettingsConfig::HAMSALAM_TOKEN,
20 SettingsConfig::WEBHOOK_HEADER_TOKEN,
21 ];
22
23 public static function registerRoutes(): void
24 {
25 register_rest_route(
26 'sync-basalam',
27 '/v1/plugin-status',
28 [
29 'methods' => 'GET',
30 'callback' => [__CLASS__, 'getPluginStatus'],
31 'permission_callback' => [__CLASS__, 'checkPermissions'],
32 ]
33 );
34 }
35
36 public static function checkPermissions($request)
37 {
38 $token = self::extractRequestToken($request);
39
40 if (empty($token)) {
41 return new \WP_Error(
42 'sync_basalam_missing_status_token',
43 'Token is required.',
44 ['status' => 403]
45 );
46 }
47
48 if (!self::validateStatusEndpointToken($token)) {
49 return new \WP_Error(
50 'sync_basalam_invalid_status_token',
51 'توکن �
52 عتبر نیست.',
53 ['status' => 403]
54 );
55 }
56
57 return true;
58 }
59
60 public static function getPluginStatus($request)
61 {
62 global $wp_version;
63
64 $settings = syncBasalamSettings()->getSettings();
65
66 return rest_ensure_response([
67 'domain' => get_site_url(),
68 'woosalam_version' => syncBasalamPlugin()->getVersion(),
69 'wordpress_version' => $wp_version,
70 'woocommerce_version' => defined('WC_VERSION') ? WC_VERSION : null,
71 'connection_status' => !empty($settings[SettingsConfig::TOKEN]),
72 'settings' => self::getPublicSettings($settings),
73 'request_status' => RequestStatusTracker::getSummary(),
74 'last_10_log' => [
75 'info' => self::getLastLogsByLevel('INFO', 10),
76 'error' => self::getLastLogsByLevel('ERROR', 10),
77 ],
78 'category_mapping_list' => CategoryMapping::getCategoryMappings(),
79 ]);
80 }
81
82 private static function getPublicSettings(array $settings): array
83 {
84 foreach (self::SENSITIVE_SETTING_KEYS as $settingKey) {
85 unset($settings[$settingKey]);
86 }
87
88 foreach (array_keys($settings) as $settingKey) {
89 if (stripos((string) $settingKey, 'token') !== false) {
90 unset($settings[$settingKey]);
91 }
92 }
93
94 return $settings;
95 }
96
97 private static function extractRequestToken($request): ?string
98 {
99 $headers = $request->get_headers();
100
101 if (!empty($headers['token'][0])) {
102 return sanitize_text_field($headers['token'][0]);
103 }
104
105 if (!empty($headers['authorization'][0])) {
106 $authorization = sanitize_text_field($headers['authorization'][0]);
107
108 if (stripos($authorization, 'Bearer ') === 0) {
109 return trim(substr($authorization, 7));
110 }
111
112 return $authorization;
113 }
114
115 $paramToken = $request->get_param('token');
116
117 return !empty($paramToken) ? sanitize_text_field($paramToken) : null;
118 }
119
120 private static function validateStatusEndpointToken(string $token): bool
121 {
122 $url = add_query_arg(
123 ['token' => $token],
124 self::TOKEN_VALIDATION_URL
125 );
126
127
128 $apiServiceManager = syncBasalamContainer()->get(ApiServiceManager::class);
129
130 $response = $apiServiceManager->get($url);
131
132 if ($response['success'] == true) {
133 return true;
134 }
135
136 return false;
137 }
138
139
140 private static function getLastLogsByLevel(string $targetLevel, int $limit = 10): array
141 {
142 $uploadDir = wp_upload_dir();
143 $logDir = trailingslashit($uploadDir['basedir']) . 'wc-logs/';
144 $logFiles = glob($logDir . 'basalam-sync-plugin*.log');
145
146 if (empty($logFiles)) {
147 return [];
148 }
149
150 usort($logFiles, fn($a, $b) => filemtime($b) <=> filemtime($a));
151
152 $logs = [];
153
154 foreach ($logFiles as $logFile) {
155 if (!is_readable($logFile)) {
156 continue;
157 }
158
159 $lines = file($logFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
160
161 foreach (array_reverse($lines) as $line) {
162 if (!preg_match(
163 '/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[+-]\d{2}:\d{2}) (INFO|WARNING|ERROR|DEBUG|ALERT) (.*?)( CONTEXT: (.*))?$/',
164 $line,
165 $matches
166 )) {
167 continue;
168 }
169
170 if ($matches[2] !== $targetLevel) {
171 continue;
172 }
173
174 $logs[] = [
175 'date' => DateConverter::utcToJalaliDateTime($matches[1]),
176 'level' => strtolower($matches[2]),
177 'message' => $matches[3],
178 'context' => isset($matches[5]) ? json_decode($matches[5], true) : null,
179 ];
180
181 if (count($logs) >= $limit) {
182 return $logs;
183 }
184 }
185 }
186
187 return $logs;
188 }
189 }
190