HistoryController.php 30.6 KB
Newer Older
Florian Azizian's avatar
Florian Azizian committed
1
2
3
<?php

/**
4
5
* Copyright Maarch since 2008 under license.
* See LICENSE.txt file at the root folder for more details.
Florian Azizian's avatar
Florian Azizian committed
6
7
8
9
10
11
12
13
14
15
16
* This file is part of Maarch software.
*
*/

/**
* @brief History Controller
* @author dev@maarch.org
*/

namespace History\controllers;

17
use Attachment\models\AttachmentModel;
18
use Configuration\models\ConfigurationModel;
19
use Docserver\controllers\DocserverController;
20
21
use Docserver\models\AdrModel;
use Docserver\models\DocserverModel;
22
use Document\controllers\DigitalSignatureController;
Damien's avatar
Damien committed
23
24
use Document\controllers\DocumentController;
use Document\models\DocumentModel;
25
use Email\models\EmailModel;
26
use Group\controllers\PrivilegeController;
27
use Group\models\GroupModel;
28
use History\models\HistoryModel;
Damien's avatar
Damien committed
29
use Respect\Validation\Validator;
30
use setasign\Fpdi\Tcpdf\Fpdi;
Damien's avatar
Damien committed
31
32
use Slim\Http\Request;
use Slim\Http\Response;
33
use SrcCore\controllers\AutoCompleteController;
Damien's avatar
Damien committed
34
use SrcCore\controllers\LanguageController;
35
use SrcCore\models\CoreConfigModel;
Damien's avatar
Damien committed
36
use SrcCore\models\DatabaseModel;
37
use SrcCore\models\PasswordModel;
38
use SrcCore\models\TextFormatModel;
Florian Azizian's avatar
Florian Azizian committed
39
use SrcCore\models\ValidatorModel;
Damien's avatar
Damien committed
40
use User\models\UserModel;
41
use Workflow\controllers\YousignController;
42
use Workflow\models\WorkflowExternalInformationModel;
43
use Workflow\models\WorkflowModel;
44
use Workflow\models\WorkflowTemplateModel;
Florian Azizian's avatar
Florian Azizian committed
45
46
47

class HistoryController
{
Damien's avatar
Damien committed
48
    public static function add(array $args)
Florian Azizian's avatar
Florian Azizian committed
49
    {
Damien's avatar
Damien committed
50
51
52
        ValidatorModel::notEmpty($args, ['code', 'objectType', 'objectId', 'type', 'message']);
        ValidatorModel::stringType($args, ['code', 'objectType', 'type', 'message']);
        ValidatorModel::arrayType($args, ['data']);
Florian Azizian's avatar
Florian Azizian committed
53

54
55
56
57
58
59
60
61
        if (!empty($GLOBALS['id'])) {
            $user = UserModel::getLabelledUserById(['id' => $GLOBALS['id']]);
        } elseif (!empty($GLOBALS['webhook'])) {
            $user = $GLOBALS['webhook'];
        } else {
            $user = '';
        }

Florian Azizian's avatar
Florian Azizian committed
62
        HistoryModel::create([
Damien's avatar
Damien committed
63
64
65
66
            'code'          => $args['code'],
            'object_type'   => $args['objectType'],
            'object_id'     => $args['objectId'],
            'type'          => $args['type'],
Damien's avatar
Damien committed
67
            'user_id'       => $GLOBALS['id'],
68
            'user'          => $user,
Damien's avatar
Damien committed
69
70
            'message'       => $args['message'],
            'data'          => empty($args['data']) ? '{}' : json_encode($args['data']),
71
            'ip'            => empty($_SERVER['REMOTE_ADDR']) ? 'script' : $_SERVER['REMOTE_ADDR']
Florian Azizian's avatar
Florian Azizian committed
72
73
        ]);

Damien's avatar
Damien committed
74
        return true;
Florian Azizian's avatar
Florian Azizian committed
75
    }
Damien's avatar
Damien committed
76

Damien's avatar
Damien committed
77
    public function get(Request $request, Response $response)
Damien's avatar
Damien committed
78
    {
79
80
81
        if (!PrivilegeController::hasPrivilege(['userId' => $GLOBALS['id'], 'privilege' => 'manage_history'])) {
            return $response->withStatus(403)->withJson(['errors' => 'Service forbidden']);
        }
Damien's avatar
Damien committed
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100

        $queryParams = $request->getQueryParams();
        $body = $request->getParsedBody();

        $limit = 25;
        if (!empty($queryParams['limit']) && is_numeric($queryParams['limit'])) {
            $limit = (int)$queryParams['limit'];
        }
        $offset = 0;
        if (!empty($queryParams['offset']) && is_numeric($queryParams['offset'])) {
            $offset = (int)$queryParams['offset'];
        }

        $where = [];
        $data = [];
        if (!empty($body['users']) && is_array($body['users'])) {
            $where[] = 'user_id in (?)';
            $data[]  = $body['users'];
        }
101
102
103
        if (!empty($body['user']) && strlen($body['user']) >= 2) {
            $searchFields = ['firstname', 'lastname'];
            $fields = AutoCompleteController::getInsensitiveFieldsForRequest(['fields' => $searchFields]);
Damien's avatar
Damien committed
104

105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
            $requestData = AutoCompleteController::getDataForRequest([
                'search'        => $body['user'],
                'fields'        => $fields,
                'where'         => $where,
                'data'          => $data,
                'fieldsNumber'  => 2,
                'longField'     => true
            ]);
            $matchedUsers = UserModel::get([
                'select' => ['id'],
                'where'  => $requestData['where'],
                'data'   => $requestData['data']
            ]);

            $searchFields = ['user'];
            $fields = AutoCompleteController::getInsensitiveFieldsForRequest(['fields' => $searchFields]);
            $requestData = AutoCompleteController::getDataForRequest([
                'search'        => $body['user'],
                'fields'        => $fields,
                'where'         => $where,
                'data'          => $data,
                'fieldsNumber'  => 1,
                'longField'     => true
            ]);

            $userWhere = $requestData['where'][0];
            $data[] = $requestData['data'][0];
Damien's avatar
Damien committed
132
133
134
135
136
137
138
            if (!empty($matchedUsers)) {
                $matchedUsers = array_column($matchedUsers, 'id');
                $userWhere .= ' OR user_id in (?)';
                $userWhere = "({$userWhere})";
                $data[]  = $matchedUsers;
            }
            $where[] = $userWhere;
139
        }
Damien's avatar
Damien committed
140
141
142

        if (!empty($body['date']['start'])) {
            $where[] = 'date > ?';
Damien's avatar
Damien committed
143
            $data[]  = TextFormatModel::getStartDayDate(['date' => $body['date']['start']]);
Damien's avatar
Damien committed
144
145
146
        }
        if (!empty($body['date']['end'])) {
            $where[] = 'date < ?';
147
            $data[]  = TextFormatModel::getEndDayDate(['date' => $body['date']['end']]);
Damien's avatar
Damien committed
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
        }
        if (!empty($body['messageTypes']) && is_array($body['messageTypes'])) {
            $queryTypes = '{';
            foreach ($body['messageTypes'] as $key => $messageType) {
                if ($key > 0) {
                    $queryTypes .= ',';
                }
                $queryTypes .= "\"%{{$messageType}}%\"";
            }
            $queryTypes .= '}';
            $where[] = 'message like any (?)';
            $data[]  = $queryTypes;
        }

        $history = HistoryModel::get([
163
            'select'    => ['id', 'code', 'type', '"user"', 'date', 'message', 'data', 'user_id', 'ip', 'object_id', 'object_type', 'count(1) OVER()'],
Damien's avatar
Damien committed
164
165
166
167
168
169
            'where'     => $where,
            'data'      => $data,
            'orderBy'   => ['date DESC'],
            'limit'     => $limit,
            'offset'    => $offset
        ]);
170
171
        $total = $history[0]['count'] ?? 0;
        $history = array_column($history, null, 'id');
Damien's avatar
Damien committed
172
173
174
175
176
177
178
179
180
181
182

        $formattedHistory = [];

        $lang       = LanguageController::get();
        $langKeys   = [];
        $langValues = [];
        foreach ($lang as $key => $value) {
            $langKeys[]   = "/{{$key}}/";
            $langValues[] = $value;
        }

183
184
185
186
187
188
189
190
191
        $objectTypes = ['attachment', 'attachments', 'configurations', 'emails', 'document', 'groups', 'main_documents', 'password_rules', 'signatures', 'workflowTemplates', 'users'];

        foreach ($objectTypes as $objectType) {
            $filteredHistory = array_filter($history, function ($element) use ($objectType) {
                return $element['object_type'] == $objectType;
            });
            if (!empty($filteredHistory)) {
                $filteredHistoryIds = array_column($filteredHistory, 'object_id', 'id');
                $objects = [];
192
                if (in_array($objectType, ['attachment', 'attachments'])) {
193
194
195
                    $objects = AttachmentModel::get(['select' => ['id', 'title'], 'where' => ['id in (?)'], 'data' => [$filteredHistoryIds]]);
                } elseif ($objectType == 'configurations') {
                    $objects = ConfigurationModel::get(['select' => ['id', 'label as title'], 'where' => ['id in (?)'], 'data' => [$filteredHistoryIds]]);
196
                } elseif ($objectType == 'emails') {
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
                    $objects = EmailModel::get(['select' => ['id', 'subject as title'], 'where' => ['id in (?)'], 'data' => [$filteredHistoryIds]]);
                } elseif ($objectType == 'groups') {
                    $objects = GroupModel::get(['select' => ['id', 'label as title'], 'where' => ['id in (?)'], 'data' => [$filteredHistoryIds]]);
                } elseif (in_array($objectType, ['main_documents', 'document'])) {
                    $objects = DocumentModel::get(['select' => ['id', 'title'], 'where' => ['id in (?)'], 'data' => [$filteredHistoryIds]]);
                } elseif ($objectType == 'password_rules') {
                    $objects = PasswordModel::getRules(['select' => ['id', 'label as title'], 'where' => ['id in (?)'], 'data' => [$filteredHistoryIds]]);
                } elseif ($objectType == 'workflowTemplates') {
                    $objects = WorkflowTemplateModel::get(['select' => ['id', 'title'], 'where' => ['id in (?)'], 'data' => [$filteredHistoryIds]]);
                } elseif ($objectType == 'users') {
                    $objects = UserModel::get(['select' => ['id', "(firstname || ' ' || lastname) as title"], 'where' => ['id in (?)'], 'data' => [$filteredHistoryIds]]);
                }
                $objects = array_column($objects, 'title', 'id');

                foreach ($filteredHistoryIds as $key => $objectId) {
                    $history[$key]['label'] = $objects[$objectId];
                }
            }
        }

Damien's avatar
Damien committed
217
218
219
220
        foreach ($history as $value) {
            $date = new \DateTime($value['date']);

            $data = json_decode($value['data'], true);
221
222
223
224
225
226
227
228

            $message = preg_replace($langKeys, $langValues, $value['message']);

            foreach (PrivilegeController::PRIVILEGES as $privilege) {
                $message = str_replace($privilege['id'], $lang[$privilege['id']], $message);
            }

            if ($value['type'] == 'ACTION') {
229
230
                $message = str_replace('VAL', $lang['documentValidateAs'], $message);
                $message = str_replace('REF', $lang['documentRefusedAs'], $message);
231
232

                if (!empty($data['mode'])) {
233
234
235
236
                    $message .= ' ' . $lang[$data['mode'] . 'User'];
                    if (!empty($data['signatureMode']) && $data['mode'] == 'sign') {
                        $message .= ' (' . $lang[$data['signatureMode'] . 'User'] . ')';
                    }
237
238
239
                }
            }

Damien's avatar
Damien committed
240
            $formattedHistory[] = [
241
242
243
244
245
246
247
248
249
250
251
                'code'        => $value['code'],
                'objectId'    => $value['object_id'],
                'objectType'  => $value['object_type'],
                'type'        => $value['type'],
                'userId'      => $value['user_id'],
                'user'        => $value['user'],
                'date'        => $date->format('c'),
                'ip'          => $value['ip'],
                'message'     => $message,
                'data'        => $data,
                'objectLabel' => $value['label']
Damien's avatar
Damien committed
252
253
254
255
            ];
        }

        return $response->withJson(['history' => $formattedHistory, 'total' => $total]);
Damien's avatar
Damien committed
256
257
    }

Damien's avatar
Damien committed
258
259
    public function getByDocumentId(Request $request, Response $response, array $args)
    {
Damien's avatar
Damien committed
260
261
262
263
        if (!Validator::intVal()->notEmpty()->validate($args['id'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Route id is not an integer']);
        }

264
265
266
267
        if (!DocumentController::hasRightById(['id' => $args['id'], 'userId' => $GLOBALS['id']]) && !PrivilegeController::hasPrivilege(['userId' => $GLOBALS['id'], 'privilege' => 'manage_documents'])) {
            return $response->withStatus(403)->withJson(['errors' => 'Document out of perimeter']);
        }

Damien's avatar
Damien committed
268
269
270
271
272
        $document = DocumentModel::getById(['select' => [1], 'id' => $args['id']]);
        if (empty($document)) {
            return $response->withStatus(400)->withJson(['errors' => 'Document does not exist']);
        }

273
274
275
276
277
278
279
        $formattedHistory = HistoryController::getFormattedHistory(['id' => $args['id']]);
        if (!empty($formattedHistory['errors'])) {
            return $response->withStatus(400)->withJson(['errors' => $formattedHistory['errors']]);
        }

        HistoryController::add([
            'code'          => 'OK',
280
            'objectType'    => 'main_documents',
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
            'objectId'      => $args['id'],
            'type'          => 'VIEW',
            'message'       => '{documentHistoryViewed}',
            'data'          => ['objectType' => 'main_documents']
        ]);

        $queryParams = $request->getQueryParams();
        if (!isset($queryParams['mode']) || $queryParams['mode'] == 'json') {
            return $response->withJson(['history' => $formattedHistory['formattedHistory']]);
        } else {
            $historyXml = HistoryController::arrayToXml(['data' => $formattedHistory['formattedHistory'], 'xml' => false]);
            $response->write($historyXml);
            $response = $response->withAddedHeader('Content-Disposition', "inline; filename=maarch_history.xml");
            return $response->withHeader('Content-Type', 'application/xml');
        }
    }

Damien's avatar
Damien committed
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
    public function getMessageTypes(Request $request, Response $response)
    {
        if (!PrivilegeController::hasPrivilege(['userId' => $GLOBALS['id'], 'privilege' => 'manage_history'])) {
            return $response->withStatus(403)->withJson(['errors' => 'Service forbidden']);
        }

        $rawHistory = DatabaseModel::select([
            'select'    => ['DISTINCT h.msg'],
            'table'     => ["(SELECT REGEXP_MATCHES(message, '{[a-zA-Z]+}', 'g') AS msg FROM history) h"],
        ]);

        $messageTypes = [];
        foreach ($rawHistory as $value) {
            $messageTypes[] = str_replace(['"', '{', '}'], '', $value['msg']);
        }

        return $response->withJson(['messageTypes' => $messageTypes]);
    }

317
318
    public static function getFormattedHistory($args = [])
    {
319
320
321
322
323
324
325
326
327
        $adr = AdrModel::getDocumentsAdr([
            'select'    => ['filename', 'fingerprint', 'path'],
            'where'     => ['main_document_id = ?', 'type = ?'],
            'data'      => [$args['id'], 'DOC']
        ]);
        $adr = $adr[0];

        $docserver = DocserverModel::getByType(['type' => 'DOC', 'select' => ['path']]);
        if (empty($docserver['path']) || !file_exists($docserver['path'])) {
328
            return ['errors' => 'Docserver does not exist'];
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
        }

        $pathToDocument = $docserver['path'] . $adr['path'] . $adr['filename'];
        unset($adr['path']);

        $fileContent = file_get_contents($pathToDocument);
        if ($fileContent !== false) {
            $finfo    = new \finfo(FILEINFO_MIME_TYPE);
            $adr['mimeType'] = $finfo->buffer($fileContent);
        }

        $certificate = DocumentController::getPdfCertificate(['path' => $pathToDocument, 'documentId' => $args['id']]);
        if (!empty($certificate)) {
            $adr['certificate'] = $certificate;
        }

Damien's avatar
Damien committed
345
        $history = HistoryModel::get([
346
            'select'    => ['code', 'type', '"user"', 'date', 'message', 'data', 'user_id', 'ip'],
Damien's avatar
Damien committed
347
348
349
            'where'     => ["(object_type = ? AND object_id = ?) OR (data->>'mainDocumentId' = ?)"],
            'data'      => ['main_documents', $args['id'], $args['id']],
            'orderBy'   => ['date']
Damien's avatar
Damien committed
350
351
352
353
        ]);

        $formattedHistory = [];

354
355
        $lang       = LanguageController::get();
        $langKeys   = [];
Damien's avatar
Damien committed
356
357
        $langValues = [];
        foreach ($lang as $key => $value) {
358
            $langKeys[]   = "/{{$key}}/";
Damien's avatar
Damien committed
359
360
361
            $langValues[] = $value;
        }

Damien's avatar
Damien committed
362
363
364
        foreach ($history as $value) {
            $date = new \DateTime($value['date']);

365
366
367
368
369
370
371
372
            $user = UserModel::getById(['id' => $value['user_id'], 'select' => ['id', 'email', 'firstname', 'lastname']]);
            $user['ip'] = $value['ip'];

            $data = json_decode($value['data'], true);
            $formatted = [
                'code'     => $value['code'],
                'type'     => $value['type'],
                'user'     => $user,
373
                'date'     => $date->format('c'),
374
375
                'message'  => preg_replace($langKeys, $langValues, $value['message']),
                'data'     => $data
Damien's avatar
Damien committed
376
            ];
377

378
            if ($value['type'] == 'ACTION' && $data['actionId'] == 1 && $data['mode'] == 'sign') {
379
380
381
382
                $formatted['document'] = $adr;
            }

            $formattedHistory[] = $formatted;
Damien's avatar
Damien committed
383
384
        }

385
386
387
388
389
390
391
392
393
394
395
396
397
        return ['formattedHistory' => $formattedHistory];
    }

    public function getHistoryProofByDocumentId(Request $request, Response $response, array $args)
    {
        if (!Validator::intVal()->notEmpty()->validate($args['id'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Route id is not an integer']);
        }

        if (!DocumentController::hasRightById(['id' => $args['id'], 'userId' => $GLOBALS['id']]) && !PrivilegeController::hasPrivilege(['userId' => $GLOBALS['id'], 'privilege' => 'manage_documents'])) {
            return $response->withStatus(403)->withJson(['errors' => 'Document out of perimeter']);
        }

398
        $workflow = WorkflowModel::getByDocumentId(['select' => ['id', 'user_id', 'process_date', 'note', 'status', 'signature_mode'], 'documentId' => $args['id'], 'orderBy' => ['"order"']]);
399
        $hasCertificate       = false;
400
        $workflowTerminated   = true;
401
        $workflowCompleted    = true;
402
        foreach ($workflow as $step) {
403
404
            if (!$hasCertificate && in_array($step['signature_mode'], ['eidas', 'rgs_2stars', 'rgs_2stars_timestamped', 'inca_card', 'inca_card_eidas'])) {
                $hasCertificate = true;
405
406
407
408
            }
            if (empty($step['status'])) {
                $workflowTerminated = false;
            }
409
            if (in_array($step['status'], ['REF', 'STOP'])) {
410
                $workflowCompleted = false;
411
            }
412
413
        }
        if (empty($workflow) || !$workflowTerminated) {
414
415
416
            return $response->withStatus(403)->withJson(['errors' => 'The document is still being processed']);
        }

417
        if ($workflowCompleted) {
418
419
420
421
            $proofDocument = DigitalSignatureController::proof(['documentId' => $args['id']]);
            if (!empty($proofDocument['errors'])) {
                return $response->withStatus(403)->withJson(['errors' => $proofDocument['errors']]);
            }
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
        }

        $documentPathToZip = [];
        $tmpPath = CoreConfigModel::getTmpPath();

        if (!empty($proofDocument)) {
            $docapostePath = $tmpPath . 'docaposteProof' . $GLOBALS['id'] . "_" . rand() . '.pdf';
            file_put_contents($docapostePath, $proofDocument);
            $documentPathToZip[] = ['path' => $docapostePath, 'filename' => 'docaposteProof.pdf'];
        }

        $queryParams = $request->getQueryParams();
        if (!$queryParams['onlyProof'] || empty($proofDocument)) {
            $formattedHistory = HistoryController::getFormattedHistory(['id' => $args['id']]);
            $historyXml       = HistoryController::arrayToXml(['data' => $formattedHistory['formattedHistory'], 'xml' => false]);
437
            $historyXmlPath = $tmpPath . 'maarchProof' . $GLOBALS['id'] . "_" . rand() . '.xml';
438
            file_put_contents($historyXmlPath, $historyXml);
439
440
441
442
443

            $loadedXml  = simplexml_load_file($historyXmlPath);
            $historyXml = HistoryController::formatXml($loadedXml);
            file_put_contents($historyXmlPath, $historyXml);

444
445
446
            $documentPathToZip[] = ['path' => $historyXmlPath, 'filename' => 'maarchProof.xml'];
        }

447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
        $notesWorkflow = [];
        foreach ($workflow as $step) {
            $workflowExternalInformations = WorkflowExternalInformationModel::getByWorkflowId(['select' => ['informations', 'firstname', 'lastname'], 'workflowId' => $step['id']]);
            if (!empty($step['note'])) {
                if (empty($step['user_id'])) {
                    if (!empty($workflowExternalInformations)) {
                        $userDisplay = "{$workflowExternalInformations['firstname']} {$workflowExternalInformations['lastname']}";
                    }
                } else {
                    $userDisplay = UserModel::getLabelledUserById(['id' => $step['user_id']]);
                }
                $notesWorkflow[] = [
                    'creator'      => $userDisplay,
                    'creationDate' => $step['process_date'],
                    'value'        => $step['note']
                ];
463
            }
464
465
466
467
468

            if (!empty($workflowExternalInformations)) {
                $informations = json_decode($workflowExternalInformations['informations'], true);
                if ($informations['type'] == 'yousign' && !empty($informations['yousignProcedureId'])) {
                    $yousignProof = YousignController::getProofByWorkflowId(['workflowId' => $step['id']]);
469
470
471
472
473
474
475
476
477
478
479
480
481
                    if (empty($yousignProof['errors'])) {
                        $archivePath = $tmpPath . 'yousignProof' . $GLOBALS['id'] . "_" . rand() . '.zip';
                        file_put_contents($archivePath, base64_decode($yousignProof));
                        $zipArchive = new \ZipArchive();
                        $zipArchive->open($archivePath);
                        $nameInArchive = $zipArchive->getNameIndex(0);
                        $yousignPdfProof = $zipArchive->getFromIndex(0);
                        $yousignPath = $tmpPath . 'yousignProof' . $GLOBALS['id'] . "_" . rand() . '.pdf';
                        file_put_contents($yousignPath, $yousignPdfProof);
                        unlink($archivePath);

                        $documentPathToZip[] = ['path' => $yousignPath, 'filename' => $nameInArchive];
                    }
482
483
484
485
486
                }
            }
        }

        if (!$queryParams['onlyProof']) {
487
488
489
            if ($workflowCompleted && ($queryParams['eSignDocument'] ?? $hasCertificate)) {
                $contentType = 'ESIGN';
            }
490

491
            $mainDocument = DocumentController::getContentPath(['id' => $args['id'], 'type' => $contentType]);
492
493
494
            if (!empty($mainDocument['errors'])) {
                return $response->withStatus($mainDocument['code'])->withJson(['errors' => $mainDocument['errors']]);
            }
495
496
497
498
499
500
501

            $document = DocumentModel::getById(['select' => ['sender', 'creation_date', 'notes', 'title'], 'id' => $args['id']]);
            $filename = TextFormatModel::createFilename([
                'label'     => $document['title'],
                'extension' => 'pdf'
            ]);
            $documentPathToZip[] = ['path' => $mainDocument['path'], 'filename' => 'mainDocument_'.$filename];
502
503
504
505
506
507
508
509
510
511
512

            $attachments = AttachmentModel::getByDocumentId(['select' => ['id', 'title'], 'documentId' => $args['id']]);
            foreach ($attachments as $key => $attachment) {
                $adr = AdrModel::getAttachmentsAdr([
                    'select'  => ['type',' path', 'filename', 'fingerprint'],
                    'where'   => ['attachment_id = ?', 'type = ?'],
                    'data'    => [$attachment['id'], 'ATTACH']
                ]);
                if (empty($adr[0])) {
                    continue;
                }
513

514
515
516
517
                $docserver = DocserverModel::getByType(['type' => $adr[0]['type'], 'select' => ['path']]);
                if (empty($docserver['path']) || !file_exists($docserver['path'])) {
                    return $response->withStatus(400)->withJson(['errors' => 'Docserver does not exist']);
                }
518

519
520
521
522
                $pathToDocument = $docserver['path'] . $adr[0]['path'] . $adr[0]['filename'];
                if (!is_file($pathToDocument)) {
                    return $response->withStatus(404)->withJson(['errors' => 'Document not found on docserver']);
                }
523

524
525
526
527
                $fingerprint = DocserverController::getFingerPrint(['path' => $pathToDocument]);
                if ($adr[0]['fingerprint'] != $fingerprint) {
                    return $response->withStatus(400)->withJson(['errors' => 'Fingerprint do not match']);
                }
528
529
530
531
532
                $filename = TextFormatModel::createFilename([
                    'label'     => $attachment['title'],
                    'extension' => 'pdf'
                ]);
                $documentPathToZip[] = ['path' => $pathToDocument, 'filename' => 'attachment_' . $key . '_' . $filename];
533
            }
534

535
536
537
538
539
            $notes = [];
            $documentNotes = json_decode($document['notes'], true);
            if (!empty($documentNotes)) {
                $notes[] = $documentNotes;
            }
540
            $notes = array_merge($notes, $notesWorkflow);
541
542
543
544

            if (!empty($notes)) {
                $documentPathToZip[] = HistoryController::createNotesFile(['notes' => $notes]);
            }
545
        }
546

547
548
549
        $content = HistoryController::createZip(['documents' => $documentPathToZip]);
        if (!empty($content['errors'])) {
            return $response->withStatus(400)->withJson(['errors' => $content['errors']]);
550
        }
551
552
553
        $content  = $content['fileContent'];
        $format   = 'zip';
        $mimeType = 'application/zip';
554

Damien's avatar
Damien committed
555
556
        HistoryController::add([
            'code'          => 'OK',
557
            'objectType'    => 'main_documents',
Damien's avatar
Damien committed
558
559
            'objectId'      => $args['id'],
            'type'          => 'VIEW',
560
            'message'       => '{documentProofViewed}',
Damien's avatar
Damien committed
561
562
563
            'data'          => ['objectType' => 'main_documents']
        ]);

564
565
        if (empty($queryParams['mode']) || $queryParams['mode'] == 'base64') {
            return $response->withJson(['encodedProofDocument' => base64_encode($content), 'format' => $format]);
566
        } else {
567
568
569
            $response->write($content);
            $response = $response->withAddedHeader('Content-Disposition', "inline; filename=maarch_history_proof." . $format);
            return $response->withHeader('Content-Type', $mimeType);
570
        }
571
    }
572

573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
    public static function createZip(array $aArgs)
    {
        $zip = new \ZipArchive();

        $tmpPath     = CoreConfigModel::getTmpPath();
        $zipFilename = $tmpPath . 'archivedProof' . $GLOBALS['id'] . '_' . rand() . '.zip';

        if ($zip->open($zipFilename, \ZipArchive::CREATE) === true) {
            foreach ($aArgs['documents'] as $document) {
                $zip->addFile($document['path'], $document['filename']);
            }

            $zip->close();

            $fileContent = file_get_contents($zipFilename);
            unlink($zipFilename);
            return ['fileContent' => $fileContent];
        } else {
            return ['errors' => 'Cannot create archive'];
        }
Damien's avatar
Damien committed
593
    }
Damien's avatar
Damien committed
594

595
596
597
598
599
600
601
602
603
604
605
    public function formatXml($simpleXMLElement)
    {
        $xmlDocument = new \DOMDocument('1.0');
        $xmlDocument->preserveWhiteSpace = false;
        $xmlDocument->formatOutput = true;
        $xmlDocument->loadXML($simpleXMLElement->asXML());

        return $xmlDocument->saveXML();
    }

    public static function arrayToXml($args = [])
606
607
    {
        if ($args['xml'] === false) {
608
609
            $args['xml'] = new \SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><root></root>', null, false);
            $historyNode = 'History';
610
        }
611

612
        foreach ($args['data'] as $key => $value) {
613
614
            $node = $historyNode ?? $key;

615
            if (is_array($value)) {
616
                HistoryController::arrayToXml(['data' => $value, 'xml' => $args['xml']->addChild(str_replace(' ', '', $node))]);
617
            } else {
618
                $args['xml']->addChild(str_replace(' ', '', $node), $value);
619
620
            }
        }
621

622
623
624
        return $args['xml']->asXML();
    }

625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
    public static function createNotesFile($args = [])
    {
        $pdf = new Fpdi('P', 'pt');
        $pdf->setPrintHeader(false);

        $pdf->AddPage();
        $dimensions     = $pdf->getPageDimensions();
        $widthNoMargins = $dimensions['w'] - $dimensions['rm'] - $dimensions['lm'];
        $bottomHeight   = $dimensions['h'] - $dimensions['bm'];
        $widthNotes     = $widthNoMargins / 2;

        if (($pdf->GetY() + 80) > $bottomHeight) {
            $pdf->AddPage();
        }

        $pdf->SetFont('', 'B', 11);
        $pdf->Cell(0, 15, 'Notes', 0, 2, 'L', false);

        $pdf->SetY($pdf->GetY() + 2);
        $pdf->SetFont('', '', 10);

        foreach ($args['notes'] as $note) {
            if (($pdf->GetY() + 65) > $bottomHeight) {
                $pdf->AddPage();
            }
650
651

            $date = new \DateTime($note['creationDate']);
652
653
654
            $pdf->SetFont('', 'B', 10);
            $pdf->Cell($widthNotes, 20, $note['creator'], 1, 0, 'L', false);
            $pdf->SetFont('', '', 10);
655
            $pdf->Cell($widthNotes, 20, $date->format('d-m-Y H:i'), 1, 1, 'L', false);
656
657
658
659
660
            $pdf->MultiCell(0, 40, $note['value'], 1, 'L', false);
            $pdf->SetY($pdf->GetY() + 5);
        }

        $noteFileContent = $pdf->Output('', 'S');
661
        $tmpPath         = CoreConfigModel::getTmpPath();
662
663
664
665
666
667
668
        $notesFilePath   = $tmpPath . 'notes' . $GLOBALS['id'] . "_" . rand() . '.pdf';
        file_put_contents($notesFilePath, $noteFileContent);
        $documentPathToZip = ['path' => $notesFilePath, 'filename' => 'notes.pdf'];

        return $documentPathToZip;
    }

Damien's avatar
Damien committed
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
    public function getByUserId(Request $request, Response $response, array $args)
    {
        if ($GLOBALS['id'] != $args['id'] && !PrivilegeController::hasPrivilege(['userId' => $GLOBALS['id'], 'privilege' => 'manage_users'])) {
            return $response->withStatus(403)->withJson(['errors' => 'Privilege forbidden']);
        }

        if (!Validator::intVal()->notEmpty()->validate($args['id'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Route id is not an integer']);
        }

        $user = UserModel::getById(['select' => [1], 'id' => $args['id']]);
        if (empty($user)) {
            return $response->withStatus(400)->withJson(['errors' => 'User does not exist']);
        }

        $history = HistoryModel::get([
            'select'    => ['code', 'type', '"user"', 'date', 'message', 'data'],
            'where'     => ["(object_type = ? AND object_id = ?) OR (data->>'userId' = ?) OR (user_id = ?)"],
            'data'      => ['main_documents', $args['id'], $args['id'], $args['id']],
            'orderBy'   => ['date']
        ]);

        $formattedHistory = [];

        $lang = LanguageController::get();
        $langKeys = [];
        $langValues = [];
        foreach ($lang as $key => $value) {
            $langKeys[] = "/{{$key}}/";
            $langValues[] = $value;
        }

        foreach ($history as $value) {
            $date = new \DateTime($value['date']);

            $formattedHistory[] = [
                'code'          => $value['code'],
                'type'          => $value['type'],
                'user'          => $value['user'],
                'date'          => $date->format('d-m-Y H:i'),
                'message'       => preg_replace($langKeys, $langValues, $value['message']),
                'data'          => json_decode($value['data'], true)
            ];
        }

        HistoryController::add([
            'code'          => 'OK',
716
            'objectType'    => 'users',
Damien's avatar
Damien committed
717
718
719
720
721
722
723
724
            'objectId'      => $args['id'],
            'type'          => 'VIEW',
            'message'       => '{userHistoryViewed}',
            'data'          => ['objectType' => 'users']
        ]);

        return $response->withJson(['history' => $formattedHistory]);
    }
Florian Azizian's avatar
Florian Azizian committed
725
}