Lines 79.85% 218 / 273
Functions and Methods 58.06% 18 / 31
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
Log 79.85% 218 / 273 58.06% 18 / 31 146.48 0.00% 0 / 1
 writeLogEntry 100.00% 24 / 24 100.00% 1 / 1 4
 writeProcessLog 100.00% 14 / 14 100.00% 1 / 1 5
 buildProcessLogPayload 100.00% 23 / 23 100.00% 1 / 1 2
 actionCodeFromLabel 100.00% 1 / 1 100.00% 1 / 1 1
 actionLabelFromCode 0.00% 0 / 1 0.00% 0 / 1 2
 formatDisplayFields 100.00% 1 / 1 100.00% 1 / 1 1
 readByProcessId 100.00% 5 / 5 100.00% 1 / 1 1
 readByProcessData 100.00% 9 / 9 100.00% 1 / 1 1
 countByProcessData 100.00% 7 / 7 100.00% 1 / 1 1
 countBySearchParams 100.00% 6 / 6 100.00% 1 / 1 1
 buildSearchConditions 100.00% 9 / 9 100.00% 1 / 1 1
 getBySearchParams 100.00% 8 / 8 100.00% 1 / 1 2
 buildFieldValueConditions 69.23% 9 / 13 0.00% 0 / 1 7.05
 buildGeneralSearchConditionList 100.00% 3 / 3 100.00% 1 / 1 3
 buildScopeIdConditions 100.00% 8 / 8 100.00% 1 / 1 3
 buildDateConditions 28.57% 2 / 7 0.00% 0 / 1 3.46
 buildUserActionConditions 100.00% 6 / 6 100.00% 1 / 1 3
 normalizeLogRow 100.00% 5 / 5 100.00% 1 / 1 5
 delete 0.00% 0 / 5 0.00% 0 / 1 2
 backtraceLogEntry 87.50% 7 / 8 0.00% 0 / 1 5.05
 escapeLikeValue 100.00% 1 / 1 100.00% 1 / 1 1
 buildGeneralSearchConditions 93.75% 15 / 16 0.00% 0 / 1 6.01
 buildUnquotedSearchParts 70.58% 12 / 17 0.00% 0 / 1 5.64
 buildTextColumnBoundaryLikeParts 100.00% 14 / 14 100.00% 1 / 1 2
 escapeFulltextBooleanTerm 66.66% 6 / 9 0.00% 0 / 1 5.93
 buildQuotedCitizenNameSearchParts 45.45% 5 / 11 0.00% 0 / 1 4.46
 escapeFulltextQuotedTerm 66.66% 6 / 9 0.00% 0 / 1 5.93
 buildCitizenNameWordBoundaryParts 0.00% 0 / 10 0.00% 0 / 1 2
 parseSearchTerms 78.57% 11 / 14 0.00% 0 / 1 6.35
 isNumericSearchQuery 100.00% 1 / 1 100.00% 1 / 1 1
 clearLogsOlderThan 0.00% 0 / 8 0.00% 0 / 1 6
1<?php
2
3namespace BO\Zmsbackend\Log\Service;
4
5use BO\Zmsentities\Collection\LogList;
6use BO\Zmsentities\Collection\RequestList;
7use BO\Zmsentities\Log as Entity;
8use DateTime;
9
10/**
11 * Logging for actions
12 *
13 */
14class Log extends \BO\Zmsbackend\Base
15{
16    const string PROCESS = 'buerger';
17    const string MIGRATION = 'migration';
18    const string ERROR = 'error';
19
20    const string ACTION_MAIL_SUCCESS = 'E-Mail-Versand erfolgreich';
21    const string ACTION_MAIL_FAIL = 'E-Mail-Versand ist fehlgeschlagen';
22    const string ACTION_STATUS_CHANGE = 'Terminstatus wurde geändert';
23    const string ACTION_SEND_REMINDER = 'Erinnerungsmail wurde gesendet';
24    const string ACTION_REMOVED = 'Termin aus der Warteschlange entfernt';
25    const string ACTION_CALLED = 'Termin wurde aufgerufen';
26    const string ACTION_ARCHIVED = 'Termin wurde archiviert';
27    const string ACTION_EDITED = 'Termin wurde geändert';
28    const string ACTION_REDIRECTED = 'Termin wurde weitergeleitet';
29    const string ACTION_NEW = 'Neuer Termin wurde erstellt';
30    const string ACTION_DELETED = 'Termin wurde gelöscht';
31    const string ACTION_CANCELED = 'Termin wurde abgesagt';
32
33    private const string FULLTEXT_SEARCH_COLUMNS = 'citizen_name, services, scope_name, citizen_email';
34
35    private const array TEXT_SEARCH_COLUMNS = [
36        'citizen_name',
37        'services',
38        'scope_name',
39        'citizen_email',
40    ];
41
42    private const array INDEXED_COLUMNS = [
43        'action',
44        'display_number',
45        'queue_number',
46        'appointment_at',
47        'slot_count',
48        'citizen_name',
49        'services',
50        'scope_name',
51        'citizen_email',
52        'citizen_phone',
53        'process_status',
54        'db_status',
55        'process_amendment',
56    ];
57
58    private const array ACTION_LABEL_TO_CODE = [
59        self::ACTION_MAIL_SUCCESS => 'mail_success',
60        self::ACTION_MAIL_FAIL => 'mail_fail',
61        self::ACTION_STATUS_CHANGE => 'status_changed',
62        self::ACTION_SEND_REMINDER => 'reminder_sent',
63        self::ACTION_REMOVED => 'removed_from_queue',
64        self::ACTION_CALLED => 'called',
65        self::ACTION_ARCHIVED => 'archived',
66        self::ACTION_EDITED => 'edited',
67        self::ACTION_REDIRECTED => 'redirected',
68        self::ACTION_NEW => 'created',
69        self::ACTION_DELETED => 'deleted',
70        self::ACTION_CANCELED => 'canceled',
71    ];
72
73    public static $operator = 'lib';
74
75    public static function writeLogEntry(
76        string $message,
77        int $referenceId,
78        string $type = self::PROCESS,
79        ?int $scopeId = null,
80        ?string $userId = null,
81        ?array $indexedFields = null
82    ) {
83        $message .= " [" . static::$operator . "]";
84        $log = new static();
85        $setParts = [
86            '`message`=:message',
87            '`reference_id`=:referenceId',
88            '`type`=:type',
89            '`scope_id`=:scopeId',
90            '`user_id`=:userId',
91        ];
92        $parameters = [
93            'message' => $message . static::backtraceLogEntry(),
94            'referenceId' => $referenceId,
95            'type' => $type,
96            'scopeId' => $scopeId,
97            'userId' => $userId,
98        ];
99
100        if ($indexedFields !== null) {
101            foreach (self::INDEXED_COLUMNS as $column) {
102                if (!array_key_exists($column, $indexedFields)) {
103                    continue;
104                }
105                $setParts[] = '`' . $column . '`=:' . $column;
106                $parameters[$column] = $indexedFields[$column];
107            }
108        }
109
110        $sql = 'INSERT INTO `log` SET ' . implode(', ', $setParts);
111
112        return $log->perform($sql, $parameters);
113    }
114
115    /**
116     * @return void
117     */
118    public static function writeProcessLog(
119        string $method,
120        string $action,
121        ?\BO\Zmsentities\Process $process,
122        ?\BO\Zmsentities\Useraccount $userAccount = null
123    ) {
124        if (empty($process) || empty($process->getId()) || empty($userAccount)) {
125            return;
126        }
127
128        $requests = new RequestList();
129        if (!empty($process->getRequestIds())) {
130            $requests = (new \BO\Zmsbackend\Request\Service\Request())->readRequestsByIds($process->getRequestIds());
131        }
132
133        $payload = self::buildProcessLogPayload($process, $action, $requests);
134
135        \BO\Zmsbackend\Log\Service\Log::writeLogEntry(
136            $method,
137            $process->getId(),
138            self::PROCESS,
139            $process->getScopeId(),
140            $userAccount->getId(),
141            $payload['indexed']
142        );
143    }
144
145    public static function buildProcessLogPayload(
146        \BO\Zmsentities\Process $process,
147        string $action,
148        RequestList $requests
149    ): array {
150        $appointmentAt = $process->getFirstAppointment()->toDateTime();
151
152        $indexed = array_filter([
153            'action' => self::actionCodeFromLabel($action),
154            'display_number' => $process->getDisplayNumber(),
155            'queue_number' => $process->getQueueNumber(),
156            'appointment_at' => $appointmentAt->format('Y-m-d H:i:s'),
157            'slot_count' => $process->getFirstAppointment()->slotCount ?? null,
158            'citizen_name' => $process->getFirstClient()->familyName,
159            'services' => implode(', ', array_map(function ($request) {
160                return $request->getName();
161            }, $requests->getAsArray())),
162            'scope_name' => $process->scope->getName(),
163            'citizen_email' => $process->getFirstClient()->email,
164            'citizen_phone' => $process->getFirstClient()->telephone,
165            'process_status' => $process->getStatus(),
166            'db_status' => $process->dbstatus,
167            'process_amendment' => $process->getAmendment(),
168        ], static function ($value) {
169            return $value !== null && $value !== '';
170        });
171
172        return [
173            'indexed' => $indexed,
174        ];
175    }
176
177    public static function actionCodeFromLabel(string $label): ?string
178    {
179        return self::ACTION_LABEL_TO_CODE[$label] ?? null;
180    }
181
182    /** @psalm-api */
183    public static function actionLabelFromCode(?string $code): ?string
184    {
185        return Entity::actionLabelFromCode($code);
186    }
187
188    public static function formatDisplayFields(array $log): array
189    {
190        return Entity::formatDisplayFields($log);
191    }
192
193    public function readByProcessId(string|int $processId): LogList
194    {
195        $query = new \BO\Zmsbackend\Log\Repository\Log(\BO\Zmsbackend\Query\Base::SELECT);
196        $query->addEntityMapping();
197        $query->addConditionProcessId($processId);
198        $logList = new \BO\Zmsentities\Collection\LogList($this->fetchList($query, new Entity()));
199        return $logList;
200    }
201
202    public function readByProcessData(
203        ?string $generalSearch,
204        ?string $service,
205        ?string $provider,
206        DateTime|null $date,
207        int $userAction,
208        int $page = 1,
209        int $perPage = 100,
210        ?array $scopeIds = null
211    ) {
212        return $this->getBySearchParams(
213            array_filter(['scope_name' => $provider, 'services' => $service]),
214            $generalSearch,
215            $userAction,
216            $date,
217            $perPage,
218            ($page - 1) * $perPage,
219            $scopeIds
220        );
221    }
222
223    public function countByProcessData(
224        ?string $generalSearch,
225        ?string $service,
226        ?string $provider,
227        DateTime|null $date,
228        int $userAction,
229        ?array $scopeIds = null
230    ): int {
231        return $this->countBySearchParams(
232            array_filter(['scope_name' => $provider, 'services' => $service]),
233            $generalSearch,
234            $userAction,
235            $date,
236            $scopeIds
237        );
238    }
239
240    public function countBySearchParams(
241        array $fieldValues,
242        ?string $generalSearch,
243        int $userAction,
244        ?DateTime $date,
245        ?array $scopeIds = null
246    ): int {
247        $params = [];
248        $conditions = $this->buildSearchConditions($fieldValues, $generalSearch, $userAction, $date, $scopeIds, $params);
249
250        return (int) $this->fetchValue(
251            'SELECT COUNT(*) FROM log WHERE ' . implode(' AND ', $conditions),
252            $params
253        );
254    }
255
256    private function buildSearchConditions(
257        array $fieldValues,
258        ?string $generalSearch,
259        int $userAction,
260        ?DateTime $date,
261        ?array $scopeIds,
262        array &$params
263    ): array {
264        $params = ['logType' => self::PROCESS];
265
266        return array_merge(
267            ['type = :logType'],
268            $this->buildFieldValueConditions($fieldValues, $params),
269            $this->buildGeneralSearchConditionList($generalSearch, $params),
270            $this->buildScopeIdConditions($scopeIds, $params),
271            $this->buildDateConditions($date, $params),
272            $this->buildUserActionConditions($userAction)
273        );
274    }
275
276    public function getBySearchParams(
277        array $fieldValues,
278        ?string $generalSearch,
279        int $userAction,
280        ?DateTime $date,
281        int $perPage,
282        int $offset,
283        ?array $scopeIds = null
284    ): LogList {
285        $params = [];
286        $conditions = $this->buildSearchConditions($fieldValues, $generalSearch, $userAction, $date, $scopeIds, $params);
287
288        $sql = 'SELECT * FROM log WHERE ' . implode(' AND ', $conditions);
289
290        $sql .= ' ORDER BY ts DESC LIMIT ' . $perPage . ' OFFSET ' . $offset;
291
292        $logs = new LogList();
293        foreach ($this->fetchAll($sql, $params) as $row) {
294            $logs->addEntity(new Entity($this->normalizeLogRow($row)));
295        }
296
297        return $logs;
298    }
299
300    private function buildFieldValueConditions(array $fieldValues, array &$params): array
301    {
302        $conditions = [];
303        foreach ($fieldValues as $field => $value) {
304            if ($value === null || $value === '') {
305                continue;
306            }
307
308            $likeValue = '%' . $this->escapeLikeValue((string) $value) . '%';
309            if ($field === 'scope_name') {
310                $conditions[] = 'scope_name LIKE :scopeName';
311                $params['scopeName'] = $likeValue;
312                continue;
313            }
314
315            if ($field === 'services') {
316                $conditions[] = 'services LIKE :services';
317                $params['services'] = $likeValue;
318            }
319        }
320
321        return $conditions;
322    }
323
324    private function buildGeneralSearchConditionList(?string $generalSearch, array &$params): array
325    {
326        if ($generalSearch === null || trim($generalSearch) === '') {
327            return [];
328        }
329
330        return $this->buildGeneralSearchConditions(trim($generalSearch), $params);
331    }
332
333    private function buildScopeIdConditions(?array $scopeIds, array &$params): array
334    {
335        if (empty($scopeIds)) {
336            return [];
337        }
338
339        $scopePlaceholders = [];
340        foreach (array_values($scopeIds) as $index => $scopeId) {
341            $parameterKey = 'scopeId' . $index;
342            $scopePlaceholders[] = ':' . $parameterKey;
343            $params[$parameterKey] = (int) $scopeId;
344        }
345
346        return ['scope_id IN (' . implode(', ', $scopePlaceholders) . ')'];
347    }
348
349    private function buildDateConditions(?DateTime $date, array &$params): array
350    {
351        if (empty($date)) {
352            return [];
353        }
354
355        $start = (clone $date)->setTime(0, 0, 0);
356        $end = (clone $date)->setTime(0, 0, 0)->add(new \DateInterval('P1D'));
357        $params['start'] = $start->format('Y-m-d H:i:s');
358        $params['end'] = $end->format('Y-m-d H:i:s');
359
360        return ['(ts >= :start AND ts < :end)'];
361    }
362
363    private function buildUserActionConditions(int $userAction): array
364    {
365        $systemUserPattern = $this->escapeLikeValue('_system_') . '%';
366
367        if ($userAction === 1) {
368            return ['(user_id IS NOT NULL AND user_id != \'\' AND user_id NOT LIKE \'' . $systemUserPattern . '\')'];
369        }
370
371        if ($userAction === 2) {
372            return ['(user_id LIKE \'' . $systemUserPattern . '\')'];
373        }
374
375        return [];
376    }
377
378    private function normalizeLogRow(array $row): array
379    {
380        if (isset($row['reference_id']) && !isset($row['reference'])) {
381            $row['reference'] = $row['reference_id'];
382        }
383
384        if (isset($row['ts']) && !is_numeric($row['ts'])) {
385            $row['ts'] = strtotime((string) $row['ts']);
386        }
387
388        return $row;
389    }
390
391    /**
392     * @psalm-api
393     */
394    public function delete(string|int $processId): LogList
395    {
396        $query = new \BO\Zmsbackend\Log\Repository\Log(\BO\Zmsbackend\Query\Base::SELECT);
397        $query->addEntityMapping();
398        $query->addConditionProcessId($processId);
399        $logList = new \BO\Zmsentities\Collection\LogList($this->fetchList($query, new Entity()));
400        return $logList;
401    }
402
403    protected static function backtraceLogEntry(): string
404    {
405        $trace = debug_backtrace();
406        $short = '';
407        foreach ($trace as $step) {
408            if (
409                isset($step['file'])
410                && isset($step['line'])
411                && !strpos($step['file'], 'Zmsbackend')
412            ) {
413                return ' (' . basename($step['file'], '.php') . ')';
414            }
415        }
416        return $short;
417    }
418
419    private function escapeLikeValue(string $value): string
420    {
421        return str_replace(['\\', '%', '_'], ['\\\\', '\\%', '\\_'], $value);
422    }
423
424    private function buildGeneralSearchConditions(string $generalSearch, array &$params): array
425    {
426        $terms = $this->parseSearchTerms($generalSearch);
427        if ($terms === []) {
428            return [];
429        }
430
431        $conditions = [];
432        foreach ($terms as $index => $termInfo) {
433            $term = $termInfo['value'];
434            $prefix = 'generalSearch' . $index;
435            $useWordBoundary = $termInfo['quoted'];
436
437            if ($useWordBoundary) {
438                $parts = $this->buildQuotedCitizenNameSearchParts($term, $params, $prefix . 'Name');
439            } else {
440                $parts = $this->buildUnquotedSearchParts($term, $prefix, $params);
441            }
442
443            if (count($terms) === 1 && $this->isNumericSearchQuery($term)) {
444                $params[$prefix . 'Id'] = (int) $term;
445                $parts[] = 'reference_id = :' . $prefix . 'Id';
446            }
447
448            $conditions[] = '(' . implode(' OR ', $parts) . ')';
449        }
450
451        return $conditions;
452    }
453
454    private function buildUnquotedSearchParts(string $term, string $paramPrefix, array &$params): array
455    {
456        $parts = [];
457        $params[$paramPrefix . 'Exact'] = $term;
458        $parts[] = 'display_number = :' . $paramPrefix . 'Exact';
459
460        if (mb_strlen($term) <= 2) {
461            if (mb_strlen($term) === 1) {
462                $escaped = $this->escapeLikeValue($term);
463                $params[$paramPrefix . 'Prefix'] = $escaped . '%';
464                foreach (self::TEXT_SEARCH_COLUMNS as $column) {
465                    $parts[] = $column . ' LIKE :' . $paramPrefix . 'Prefix';
466                }
467
468                return $parts;
469            }
470
471            $parts = array_merge($parts, $this->buildTextColumnBoundaryLikeParts($term, $paramPrefix, $params));
472
473            return $parts;
474        }
475
476        $fulltextTerm = $this->escapeFulltextBooleanTerm($term);
477        if ($fulltextTerm !== '') {
478            $params[$paramPrefix . 'Ft'] = $fulltextTerm;
479            $parts[] = 'MATCH(' . self::FULLTEXT_SEARCH_COLUMNS . ') AGAINST(:' . $paramPrefix . 'Ft IN BOOLEAN MODE)';
480        }
481
482        return $parts;
483    }
484
485    private function buildTextColumnBoundaryLikeParts(string $term, string $paramPrefix, array &$params): array
486    {
487        $escaped = $this->escapeLikeValue($term);
488        $params[$paramPrefix . 'Start'] = $escaped . '%';
489        $params[$paramPrefix . 'End'] = '%' . $escaped;
490        $params[$paramPrefix . 'Middle'] = '% ' . $escaped . ' %';
491        $params[$paramPrefix . 'MiddleStart'] = '% ' . $escaped;
492        $params[$paramPrefix . 'Exact'] = $term;
493
494        $parts = [];
495        foreach (self::TEXT_SEARCH_COLUMNS as $column) {
496            $parts[] = $column . ' LIKE :' . $paramPrefix . 'Start';
497            $parts[] = $column . ' LIKE :' . $paramPrefix . 'End';
498            $parts[] = $column . ' LIKE :' . $paramPrefix . 'Middle';
499            $parts[] = $column . ' LIKE :' . $paramPrefix . 'MiddleStart';
500            $parts[] = $column . ' = :' . $paramPrefix . 'Exact';
501        }
502
503        return $parts;
504    }
505
506    private function escapeFulltextBooleanTerm(string $term): string
507    {
508        $term = trim(preg_replace('/[+\-><()~*"@]+/u', ' ', $term) ?? '');
509        if ($term === '') {
510            return '';
511        }
512
513        $words = preg_split('/\s+/u', $term, -1, PREG_SPLIT_NO_EMPTY);
514        if ($words === false || $words === []) {
515            return '';
516        }
517
518        if (count($words) > 1) {
519            return '"' . implode(' ', array_map(static fn ($word) => str_replace('"', '', $word), $words)) . '"';
520        }
521
522        return '+' . $words[0] . '*';
523    }
524
525    private function buildQuotedCitizenNameSearchParts(string $term, array &$params, string $paramPrefix): array
526    {
527        if (mb_strlen($term) <= 2) {
528            return $this->buildCitizenNameWordBoundaryParts(
529                $this->escapeLikeValue($term),
530                $params,
531                $paramPrefix
532            );
533        }
534
535        $fulltextTerm = $this->escapeFulltextQuotedTerm($term);
536        if ($fulltextTerm === '') {
537            return [];
538        }
539
540        $params[$paramPrefix . 'Ft'] = $fulltextTerm;
541
542        return ['MATCH(citizen_name) AGAINST(:' . $paramPrefix . 'Ft IN BOOLEAN MODE)'];
543    }
544
545    private function escapeFulltextQuotedTerm(string $term): string
546    {
547        $term = trim(preg_replace('/[+\-><()~*"@]+/u', ' ', $term) ?? '');
548        if ($term === '') {
549            return '';
550        }
551
552        $words = preg_split('/\s+/u', $term, -1, PREG_SPLIT_NO_EMPTY);
553        if ($words === false || $words === []) {
554            return '';
555        }
556
557        if (count($words) > 1) {
558            return '"' . implode(' ', array_map(static fn ($word) => str_replace('"', '', $word), $words)) . '"';
559        }
560
561        return '+' . $words[0];
562    }
563
564    private function buildCitizenNameWordBoundaryParts(string $escapedTerm, array &$params, string $prefix): array
565    {
566        $params[$prefix . 'Start'] = $escapedTerm . ' %';
567        $params[$prefix . 'End'] = '% ' . $escapedTerm;
568        $params[$prefix . 'Middle'] = '% ' . $escapedTerm . ' %';
569        $params[$prefix . 'Exact'] = $escapedTerm;
570
571        return [
572            'citizen_name LIKE :' . $prefix . 'Start',
573            'citizen_name LIKE :' . $prefix . 'End',
574            'citizen_name LIKE :' . $prefix . 'Middle',
575            'citizen_name = :' . $prefix . 'Exact',
576        ];
577    }
578
579    private function parseSearchTerms(string $queryString): array
580    {
581        if ($queryString === '') {
582            return [];
583        }
584
585        if (!preg_match_all('/"([^"]+)"|(\S+)/u', $queryString, $matches, PREG_SET_ORDER)) {
586            return [['value' => $queryString, 'quoted' => false]];
587        }
588
589        $terms = [];
590        foreach ($matches as $match) {
591            $value = trim($match[1] !== '' ? $match[1] : $match[2]);
592            if ($value === '') {
593                continue;
594            }
595            $terms[] = [
596                'value' => $value,
597                'quoted' => $match[1] !== '',
598            ];
599        }
600
601        return $terms;
602    }
603
604    private function isNumericSearchQuery(string $queryString): bool
605    {
606        return (bool) preg_match('#^\d+$#', $queryString);
607    }
608
609    public function clearLogsOlderThan(int $olderThan): bool
610    {
611        try {
612            $olderThanDate = (new \DateTime())->modify('-' . $olderThan . ' days');
613
614            $query = new \BO\Zmsbackend\Log\Repository\Log(\BO\Zmsbackend\Query\Base::DELETE);
615            $query->addConditionOlderThan($olderThanDate);
616
617            $result = $this->writeItem($query);
618            return $result !== false;
619        } catch (\Exception $e) {
620            \App::$log->error('Error during log cleanup', ['exception' => $e->getMessage()]);
621            return false;
622        }
623    }
624}