Actions
4 days ago
AnalyticsCleanup.php
4 years ago
AnalyticsConsent.php
1 month ago
AnalyticsEventDto.php
4 days ago
AnalyticsEventWithTimeDto.php
10 months ago
AnalyticsGenericEventHandler.php
4 days ago
AnalyticsSender.php
10 months ago
WithAnalyticsAPI.php
10 months ago
WithAnalyticsSiteInfo.php
6 months ago
AnalyticsGenericEventHandler.php
80 lines
| 1 | <?php |
| 2 | |
| 3 | namespace WPStaging\Framework\Analytics; |
| 4 | |
| 5 | use WPStaging\Framework\Analytics\Actions\AnalyticsGenericEvent; |
| 6 | use WPStaging\Framework\Security\Auth; |
| 7 | use WPStaging\Framework\Utils\Sanitize; |
| 8 | |
| 9 | /** |
| 10 | * Handles the AJAX endpoint for logging generic analytics events |
| 11 | */ |
| 12 | class AnalyticsGenericEventHandler |
| 13 | { |
| 14 | /** @var Auth */ |
| 15 | private $auth; |
| 16 | |
| 17 | /** @var Sanitize */ |
| 18 | private $sanitize; |
| 19 | |
| 20 | public function __construct(Auth $auth, Sanitize $sanitize) |
| 21 | { |
| 22 | $this->auth = $auth; |
| 23 | $this->sanitize = $sanitize; |
| 24 | } |
| 25 | |
| 26 | public function ajaxHandleGenericEvent() |
| 27 | { |
| 28 | if (!$this->auth->isAuthenticatedRequest()) { |
| 29 | wp_send_json_error(null, 401); |
| 30 | return; |
| 31 | } |
| 32 | |
| 33 | $eventName = isset($_POST['event_name']) ? $this->sanitize->sanitizeString($_POST['event_name']) : ''; |
| 34 | if ($eventName === '' || !preg_match('/^[a-zA-Z0-9_]{1,100}$/', $eventName)) { |
| 35 | wp_send_json_error(null, 400); |
| 36 | return; |
| 37 | } |
| 38 | |
| 39 | $groupName = isset($_POST['group_name']) ? $this->sanitize->sanitizeString($_POST['group_name']) : ''; |
| 40 | if ($groupName !== '' && !preg_match('/^[a-zA-Z0-9_]{1,100}$/', $groupName)) { |
| 41 | wp_send_json_error(null, 400); |
| 42 | return; |
| 43 | } |
| 44 | |
| 45 | $custom = isset($_POST['custom']) ? $this->sanitizeCustomData($this->sanitize->sanitizeArrayString($_POST['custom'])) : []; |
| 46 | |
| 47 | AnalyticsGenericEvent::logEvent($eventName, $groupName, $custom); |
| 48 | |
| 49 | wp_send_json_success(); |
| 50 | } |
| 51 | |
| 52 | /** |
| 53 | * @param array $data |
| 54 | * @return array<string, string> |
| 55 | */ |
| 56 | private function sanitizeCustomData(array $data): array |
| 57 | { |
| 58 | $sanitized = []; |
| 59 | |
| 60 | // Hard cap processed payload size to keep this endpoint lightweight. |
| 61 | $data = array_slice($data, 0, 20, true); |
| 62 | |
| 63 | foreach ($data as $key => $value) { |
| 64 | if (!is_scalar($value)) { |
| 65 | continue; |
| 66 | } |
| 67 | |
| 68 | $key = mb_substr((string)$key, 0, 100); |
| 69 | $key = $this->sanitize->sanitizeString($key); |
| 70 | if ($key === '') { |
| 71 | continue; |
| 72 | } |
| 73 | |
| 74 | $sanitized[$key] = mb_substr($this->sanitize->sanitizeString((string)$value), 0, 500); |
| 75 | } |
| 76 | |
| 77 | return $sanitized; |
| 78 | } |
| 79 | } |
| 80 |