log.php 19.4 KB
Newer Older
Prosper De Laure's avatar
Prosper De Laure committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?php

/*
 * Copyright (C) 2015 Maarch
 *
 * This file is part of bundle recordsManagement.
 *
 * Bundle recordsManagement is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Bundle recordsManagement is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with bundle recordsManagement.  If not, see <http://www.gnu.org/licenses/>.
 */

namespace bundle\recordsManagement\Controller;

/**
 * Class log
 *
 * @package RecordsManagement
 * @author  Cyril Vazquez <cyril.vazquez@maarch.org>
 */
Alexis Ragot's avatar
Alexis Ragot committed
30
class log implements archiveDescriptionInterface
Prosper De Laure's avatar
Prosper De Laure committed
31
32
33
34
{
    /* Properties */

    public $sdoFactory;
Alexis Ragot's avatar
Alexis Ragot committed
35
    public $logFilePlan;
36
    public $translationLogType;
Alexis Ragot's avatar
Alexis Ragot committed
37
    public $filePlanController;
Prosper De Laure's avatar
Prosper De Laure committed
38
39
40

    /**
     * Constructor of access control class
41
42
43
     * @param \dependency\sdo\Factory $sdoFactory         The factory
     * @param string                  $logFilePlan        The path of log in the file plan
     * @param array                   $translationLogType The translation of log types
Prosper De Laure's avatar
Prosper De Laure committed
44
     */
45
    public function __construct(\dependency\sdo\Factory $sdoFactory, $logFilePlan = null, $translationLogType = [])
Prosper De Laure's avatar
Prosper De Laure committed
46
47
    {
        $this->sdoFactory = $sdoFactory;
Alexis Ragot's avatar
Alexis Ragot committed
48
        $this->logFilePlan = $logFilePlan;
49
50
        $this->translationLogType = $translationLogType;

Alexis Ragot's avatar
Alexis Ragot committed
51
        $this->filePlanController = \laabs::newController("filePlan/filePlan");
Prosper De Laure's avatar
Prosper De Laure committed
52
53
54
55
    }

    /**
     * Get a  search result
56
57
58
59
60
61
62
63
64
     *
     * @param string  $archiveId   The archive identifier
     * @param string  $type        The type
     * @param date    $fromDate    The date
     * @param date    $toDate      The date
     * @param string  $processName The process name
     * @param string  $processId   The process identifier
     * @param string  $sortBy      The process identifier
     * @param integer $maxResults  The process identifier
Prosper De Laure's avatar
Prosper De Laure committed
65
66
67
     *
     * @return array Array of logs
     */
Alexandre Morin's avatar
Alexandre Morin committed
68
69
70
71
72
73
74
75
    public function find(
        $archiveId = null,
        $type = null,
        $fromDate = null,
        $toDate = null,
        $processName = null,
        $processId = null,
        $sortBy = ">fromDate",
76
        $maxResults = null
Alexandre Morin's avatar
Alexandre Morin committed
77
    ) {
78
        list($queryParams, $queryString) = $this->queryBuilder($archiveId, $type, $fromDate, $toDate, $processName, $processId);
Prosper De Laure's avatar
Prosper De Laure committed
79

80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
        $logs = $this->sdoFactory->find(
            "recordsManagement/log",
            $queryString,
            $queryParams,
            $sortBy,
            0,
            $maxResults
        );

        return $logs;
    }

    /**
     * Create query for search
     *
     * @param string  $archiveId      The archive identifier
     * @param string  $type           The type
     * @param date    $fromDate       The date
     * @param date    $toDate         The date
     * @param string  $processName    The process name
     * @param string  $processId      The process identifier
     *
     * @return
     */
    protected function queryBuilder(
        $archiveId = null,
        $type = null,
        $fromDate = null,
        $toDate = null,
        $processName = null,
        $processId = null
    ) {
        $queryParts = [];
        $queryParams = [];
Prosper De Laure's avatar
Prosper De Laure committed
114
115
116
117
118
119
120
121
122
123
124
125

        if ($archiveId) {
            $queryParams['archiveId'] = $archiveId;
            $queryParts['archiveId'] = "archiveId = :archiveId";
        }

        if ($type) {
            $queryParams['type'] = $type;
            $queryParts['type'] = "type = :type";
        }

        if ($fromDate && $toDate) {
Alexis Ragot's avatar
Alexis Ragot committed
126
127
128
129
130
131
            $queryParams['fromDate'] = $fromDate->format('Y-m-d').'T00:00:00';
            $queryParams['toDate'] = $toDate->format('Y-m-d').'T23:59:59';
            $queryParts['date'] = "fromDate <= :toDate AND toDate >= :fromDate";
        } elseif ($fromDate) {
            $queryParams['fromDate'] = $fromDate->format('Y-m-d').'T00:00:00';
            $queryParts['date'] = "fromDate >= :fromDate";
Prosper De Laure's avatar
Prosper De Laure committed
132
        } elseif ($toDate) {
Alexis Ragot's avatar
Alexis Ragot committed
133
134
            $queryParams['toDate'] = $toDate->format('Y-m-d').'T23:59:59';
            $queryParts['date'] = "toDate <= :toDate";
Prosper De Laure's avatar
Prosper De Laure committed
135
136
137
138
139
140
141
142
143
144
145
146
147
148
        }

        if ($processName) {
            $queryParams['processName'] = $processName;
            $queryParts['processName'] = "processName = :processName";
        }

        if ($processId) {
            $queryParams['processId'] = $processId;
            $queryParts['processId'] = "processId = :processId";
        }

        $queryString = implode(' AND ', $queryParts);

149
150
        return [$queryParams, $queryString];
    }
Alexandre Morin's avatar
Alexandre Morin committed
151

152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
    /**
     * Count search results
     *
     * @param string $archiveId      The archive identifier
     * @param string $type           The type
     * @param date   $fromDate       The date
     * @param date   $toDate         The date
     * @param string $processName    The process name
     * @param string $processId      The process identifier
     *
     * @return integer
     */
    public function countFind(
        $archiveId = null,
        $type = null,
        $fromDate = null,
        $toDate = null,
        $processName = null,
        $processId = null
    ) {
        list($queryParams, $queryString) = $this->queryBuilder($archiveId, $type, $fromDate, $toDate, $processName, $processId);

        $count = $this->sdoFactory->count(
Alexandre Morin's avatar
Alexandre Morin committed
175
176
            "recordsManagement/log",
            $queryString,
177
            $queryParams
Alexandre Morin's avatar
Alexandre Morin committed
178
        );
Prosper De Laure's avatar
Prosper De Laure committed
179

180
        return $count;
Prosper De Laure's avatar
Prosper De Laure committed
181
182
    }

183
184
    /**
     * Search the description objects
185
186
187
188
189
190
     *
     * @param string  $description The search args on description object
     * @param string  $text        The search args on text
     * @param array   $args        The search args on archive std properties
     * @param bool    $checkAccess Use access control. If not, called MUST control access before or after retrieving data
     * @param integer $maxResults  Max results to display
Alexis Ragot's avatar
Alexis Ragot committed
191
     *
192
     * @return object Array of description objects
193
     */
194
    public function search($description = null, $text = null, array $args = [], $checkAccess = null, $maxResults = null)
195
    {
196
        $queryParams = $queryParts = [];
197
        $queryString = "";
198
199
200
201
202
203
204
205
        if ($text) {
            $text = preg_replace('/[^\w\-\_]+/', ' ', $text);
            $tokens = \laabs\explode(' ', $text);

            $queryLogs = [];
            foreach ($tokens as $i => $token) {
                $queryTerm = [];
                $queryTerm[] = "archiveId = '*$token*'";
206
207
208
                $queryTerm[] = "processName = '*$token*'";
                $queryTerm[] = "type = '*$token*'";
                $queryTerm[] = "ownerOrgRegNumber = '*$token*'";
209
210
211
212
213
214
215
216
217

                try {
                    $date = new \DateTime($token);
                    $date = $date->format("Y-m-d");
                } catch (\Exception $e) {
                    $date = null;
                }

                if ($date) {
218
                    $queryLogs[] = "(fromDate <= $date T00:00:00 AND toDate >= $date T23:59:59)";
219
220
                }

221
                $queryString = \laabs\implode(' OR ', $queryTerm);
Alexis Ragot's avatar
Alexis Ragot committed
222
            }
Cyril Vazquez's avatar
Cyril Vazquez committed
223
224
        }

225
226
227
228
        if (!is_null($description)) {
            $queryString .= $description;
        }

229
230
        $archiveController = \laabs::newController('recordsManagement/archive');
        $archives = [];
231

232
        $sortBy = ">fromDate";
233

234
235
236
237
238
239
        try {
            $logs = $this->sdoFactory->find("recordsManagement/log", $queryString, [], $sortBy, 0, $maxResults);
        } catch (\Exception $e) {
            return [];
        }

240
241
242
243
244
245
246
247
248

        foreach ($logs as $log) {
            try {
                $archive = $archiveController->read($log->archiveId);
                $archive->descriptionObject = $log;
                $archives[] = $archive;
            } catch (\Exception $e) {
            }
        }
249

Cyril Vazquez's avatar
Cyril Vazquez committed
250
        return $archives;
251
252
    }

253
254
255
256
257
258
259
260
261
262
263
264
265
    /**
     * Count log objects
     * @param string $description The search args on description object
     * @param string $text        The search args on text
     * @param array  $args        The search args on archive std properties
     *
     * @return object Array of description objects
     */
    public function count($description = null, $text = null, array $args = [], $checkAccess = null, $maxResults = null)
    {
        return count($this->search($description, $text, $args, $checkAccess, $maxResults = null));
    }

Prosper De Laure's avatar
Prosper De Laure committed
266
267
268
269
270
271
272
273
274
    /**
     * Retrieve a journal by evenement date
     * @param string $type The journal type
     * @param string $date The date of the event
     *
     * @return recordsManagement/log The journal object
     */
    public function getByDate($type, $date)
    {
Alexandre Morin's avatar
Alexandre Morin committed
275
276
277
278
279
280
281
282
        $journal = $this->sdoFactory->find(
            'recordsManagement/log',
            "type='$type' AND fromDate <= '$date' AND toDate >= '$date'",
            [],
            ">fromDate",
            0,
            1
        );
Prosper De Laure's avatar
Prosper De Laure committed
283
284
285
286
287
288
289
290
291
292

        if (!count($journal)) {
            return null;
        }

        return end($journal);
    }

    /**
     * Create the requested log
293
     * @param object $archive The archived log object
Prosper De Laure's avatar
Prosper De Laure committed
294
295
296
     *
     * @return boolean status of the query
     */
297
    public function create($archive)
Prosper De Laure's avatar
Prosper De Laure committed
298
    {
299
        if (!\laabs::validate($archive->descriptionObject)) {
Prosper De Laure's avatar
Prosper De Laure committed
300
301
302
303
304
            $e = new \core\Exception('Invalid log data');

            $e->errors = \laabs::getValidationErrors();
            throw $e;
        }
Alexis Ragot's avatar
Alexis Ragot committed
305

306
        $archive->descriptionObject->archiveId = $archive->archiveId;
Alexis Ragot's avatar
Alexis Ragot committed
307

308
        $this->sdoFactory->create($archive->descriptionObject, 'recordsManagement/log');
Prosper De Laure's avatar
Prosper De Laure committed
309

310
        return true;
Prosper De Laure's avatar
Prosper De Laure committed
311
312
313
314
315
316
    }

    /**
     * Read an log with its archive identifier
     * @param id $archiveId
     *
317
     * @return recordsManagement/log Log with its archive identifier
Prosper De Laure's avatar
Prosper De Laure committed
318
319
320
321
322
323
     */
    public function read($archiveId)
    {
        return $this->sdoFactory->read("recordsManagement/log", $archiveId);
    }

324
325
    /**
     * Update the description object
Cyril Vazquez's avatar
Cyril Vazquez committed
326
     * @param object $archive
327
     */
Cyril Vazquez's avatar
Cyril Vazquez committed
328
    public function update($archive)
329
330
331
332
333
334
335
336
337
    {
        // Not implemented yet...
    }

    /**
     * Delete the description object
     * @param id   $archiveId
     * @param bool $deleteDescription
     */
Alexis Ragot's avatar
Alexis Ragot committed
338
    public function delete($archiveId, $deleteDescription = true)
339
340
341
342
    {
        // Not possible
    }

Prosper De Laure's avatar
Prosper De Laure committed
343
344
345
346
347
348
349
350
    /**
     * Read the first journal
     * @param string $type The type of journal
     *
     * @return recordsManagement/log The next journal
     */
    public function getFirstJournal($type)
    {
351
        $firstJournal = $this->sdoFactory->find('recordsManagement/log', "type='$type'", [], "<fromDate", 0, 1);
Prosper De Laure's avatar
Prosper De Laure committed
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
        if (!count($firstJournal)) {
            return null;
        }

        return end($firstJournal);
    }

    /**
     * Read the next journal
     * @param recordsManagement/log $journal THe current journal object
     *
     * @return recordsManagement/log The next journal
     */
    public function getNextJournal($journal)
    {
        if (is_scalar($journal) || get_class($journal) == 'core\Type\Id') {
            $journal = $this->sdoFactory->read('recordsManagement/log', $journal);
        }

Alexandre Morin's avatar
Alexandre Morin committed
371
372
373
374
375
376
377
378
379
        $nextJournal =  $this->sdoFactory->find(
            'recordsManagement/log',
            "type = '$journal->type' and fromDate >= '$journal->toDate'",
            [],
            '<fromDate',
            0,
            1
        );

Prosper De Laure's avatar
Prosper De Laure committed
380
381
382
383
384
385
386
387
388
        if (!count($nextJournal)) {
            return null;
        }

        return end($nextJournal);
    }

    /**
     * Get the last usable journal
389
390
     * @param string $type              The type of journal
     * @param string $ownerOrgRegNumber The journal owner organization registration number 
Prosper De Laure's avatar
Prosper De Laure committed
391
392
393
     *
     * @return recordsManagement/log The journal object
     */
394
    public function getLastJournal($type, $ownerOrgRegNumber = null)
Prosper De Laure's avatar
Prosper De Laure committed
395
    {
396
397
398
399
400
        if ($ownerOrgRegNumber) {
            $query = "type='$type' AND ownerOrgRegNumber = '$ownerOrgRegNumber'";
        } else {
            $query = "type='$type' AND ownerOrgRegNumber = null";
        }
401
        
402
        $journals = $this->sdoFactory->find('recordsManagement/log', $query, [], ">toDate", 0, 1);
Prosper De Laure's avatar
Prosper De Laure committed
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423

        if (empty($journals)) {
            return null;
        }

        $journal = end($journals);

        return $journal;
    }

    /**
     * Deposit a log file
     * @param string    $journalFileName   The name of the journal to deposit
     * @param timestamp $fromDate          The journal start date
     * @param timestamp $toDate            The journal end date
     * @param string    $type              The tye of the journal (system, lifeCycle, application)
     * @param string    $processName       The journal process name
     * @param string    $timestampFileName The name of the timestamp file
     *
     * @return string The archive id of the journal archive
     */
Alexandre Morin's avatar
Alexandre Morin committed
424
425
426
427
428
429
430
431
    public function depositJournal(
        $journalFileName,
        $fromDate,
        $toDate,
        $type,
        $processName = null,
        $timestampFileName = null
    ) {
Prosper De Laure's avatar
Prosper De Laure committed
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
        $newJournal = \laabs::newInstance('recordsManagement/log');
        $newJournal->archiveId = \laabs::newId();
        $newJournal->toDate = $toDate;
        $newJournal->fromDate = $fromDate;
        $newJournal->processName = $processName;
        $newJournal->type = $type;

        return $this->archiveJournal($journalFileName, $newJournal, $timestampFileName);
    }

    /**
     * Deposit a log file
     * @param string $journalFileName   The name of the journal to deposit
     * @param object $log               The log object
     * @param string $timestampFileName The name of the timestamp file
     *
     * @return string The archive id of the journal archive
     */
    public function archiveJournal($journalFileName, $log, $timestampFileName = null)
    {
        if (!in_array($log->type, array('system', 'lifeCycle', 'application'))) {
            throw \laabs::newException("recordsManagement/logException", "The journal type is not allowed.");
        }

        $currentOrganization = \laabs::getToken("ORGANIZATION");

Alexis Ragot's avatar
Alexis Ragot committed
458
        if (!($currentOrganization->orgRoleCodes && in_array("owner", (array) $currentOrganization->orgRoleCodes))) {
Alexandre Morin's avatar
Alexandre Morin committed
459
460
461
462
            throw \laabs::newException(
                "recordsManagement/logException",
                "The journal must be archived by an owner organization."
            );
Prosper De Laure's avatar
Prosper De Laure committed
463
464
465
466
467
468
469
470
471
472
473
474
        }

        $archiveController = \laabs::newController('recordsManagement/archive');
        $digitalResourceController = \laabs::newController('digitalResource/digitalResource');

        // Create archive
        $archive = $archiveController->newArchive();

        $archive->archiveId = $log->archiveId;
        $archive->accessRuleDuration = 'P0D';
        $archive->retentionDuration = 'P0D';
        $archive->finalDisposition = 'preservation';
475
        $archive->fileplanLevel = 'item';
Alexandre Morin's avatar
Alexandre Morin committed
476
477
478
479
480
481
482
        $archive->archiveName =
            'journal/'.
            $log->type.
            ' '.
            date_format($log->fromDate, 'Y/m/d').
            ' - '.
            date_format($log->toDate, 'Y/m/d');
Prosper De Laure's avatar
Prosper De Laure committed
483

Alexis Ragot's avatar
Alexis Ragot committed
484
485
        if (!empty($this->logFilePlan)) {
            $path = $this->resolveLogFilePlan($this->logFilePlan, ["type" => $log->type]);
Alexandre Morin's avatar
Alexandre Morin committed
486
487
488
489
490
            $position = $this->filePlanController->createFromPath(
                $path,
                $currentOrganization->registrationNumber,
                true
            );
Alexis Ragot's avatar
Alexis Ragot committed
491
492
493
            $archive->filePlanPosition = $position;
        }

Prosper De Laure's avatar
Prosper De Laure committed
494
495
496
497
         // Create resource
        $journalResource = $digitalResourceController->createFromFile($journalFileName);
        $journalResource->puid = "x-fmt/18";
        $journalResource->mimetype = "text/csv";
498
        $journalResource->archiveId = $archive->archiveId;
Prosper De Laure's avatar
Prosper De Laure committed
499
500
        $digitalResourceController->getHash($journalResource, "SHA256");

501
502
        $archive->digitalResources[] = $journalResource;

Prosper De Laure's avatar
Prosper De Laure committed
503
504
505
506
        if ($timestampFileName) {
            // Create timestamp resource
            $timestampResource = $digitalResourceController->createFromFile($timestampFileName);
            $digitalResourceController->getHash($timestampResource, "SHA256");
507
508
509
            
            $logMessage = ["message" => "Timestamp file generated"];
            \laabs::notify(\bundle\audit\AUDIT_ENTRY_OUTPUT, $logMessage);
Prosper De Laure's avatar
Prosper De Laure committed
510

511
512
513
514
515
            $timestampResource->archiveId = $journalResource->archiveId;
            $timestampResource->relatedResId = $journalResource->resId;
            $timestampResource->relationshipType = "isTimestampOf";

            $archive->digitalResources[] = $timestampResource;
Prosper De Laure's avatar
Prosper De Laure committed
516
517
518
519
520
        }

        $archive->descriptionObject = $log;
        $archive->descriptionClass = 'recordsManagement/log';

Alexandre Morin's avatar
Alexandre Morin committed
521
522
523
524
        $archive->originatorOrgRegNumber =
        $archive->archiverOrgRegNumber =
        $archive->depositorOrgRegNumber =
            (string) $currentOrganization->registrationNumber;
Prosper De Laure's avatar
Prosper De Laure committed
525
526
527
528
        $archive->originatorOwnerOrgId = (string) $currentOrganization->orgId;

        $archive->serviceLevelReference = $archiveController->useServiceLevel("deposit")->reference;

529
530
531
532
533
534
        if (strpos($archiveController->useServiceLevel("deposit")->control, "fullTextIndexation")) {
            $archive->fullTextIndexation = "requested";
        } else {
            $archive->fullTextIndexation = "none";
        }

535
536
537
538
539
540
541
542
543
544
545
546
        try {
            $archive = $archiveController->deposit($archive, 'journal/'.$log->type.'/<date("Y")>/<date("m")>');
            $logMessage = ["message" => "New journal identifier : %s", "variables" => $archive->archiveId];
            \laabs::notify(\bundle\audit\AUDIT_ENTRY_OUTPUT, $logMessage);

        } catch (\Exception $e) {
            $logMessage = ["message" => "Error on journal creation"];
            \laabs::notify(\bundle\audit\AUDIT_ENTRY_OUTPUT, $logMessage);
            throw $e;
        }

        return $archive->archiveId;
Prosper De Laure's avatar
Prosper De Laure committed
547
    }
Alexandre Morin's avatar
Alexandre Morin committed
548

Alexis Ragot's avatar
Alexis Ragot committed
549
550
551
552
553
554
555
556
557
558
559
560
561
    private function resolveLogFilePlan($path, $values)
    {
        $values = is_array($values) ? $values : get_object_vars($values);

        if (preg_match_all("/\<[^\>]+\>/", $path, $variables)) {
            foreach ($variables[0] as $variable) {
                $token = substr($variable, 1, -1);
                switch (true) {
                    case substr($token, 0, 5) == 'date(':
                        $format = substr($token, 5, -1);
                        $path = str_replace($variable, date($format), $path);
                        break;
                    case isset($values[$token]):
562
563
564
565
                        if (array_key_exists($values[$token], $this->translationLogType)) {
                            $values[$token] = $this->translationLogType[$values[$token]];
                        }

Alexis Ragot's avatar
Alexis Ragot committed
566
567
568
569
570
571
572
573
574
                        $path = str_replace($variable, (string) $values[$token], $path);
                        break;
                }
            }
        }

        return $path;
    }

Benjamin Rousselière's avatar
Benjamin Rousselière committed
575
576
    public function contents($type, $archiveId, $resourceId)
    {
Alexandre Morin's avatar
Alexandre Morin committed
577
578
579
        $archiveController = \laabs::newController('recordsManagement/archive');

        $res = $archiveController->consultation($archiveId, $resourceId);
580
581
582
583
584
585
        $maxResult = \laabs::configuration('presentation.maarchRM')['maxResults'];
        $stream = stream_get_line($res->attachment->data, 1 >> 15, "\n") . "\n";
        for ($i = 0; $i < $maxResult; $i++) {
            $stream .= stream_get_line($res->attachment->data, 1 >> 15, "\n") . "\n";
        }
        rewind($res->attachment->data);
Alexandre Morin's avatar
Alexandre Morin committed
586
587
        $journal = $type . PHP_EOL;
        $journal .= $archiveId . ',' . $resourceId . PHP_EOL;
Benjamin Rousselière's avatar
Benjamin Rousselière committed
588
        $journal .= $stream;
Alexandre Morin's avatar
Alexandre Morin committed
589
590
591

        return $journal;
    }
Prosper De Laure's avatar
Prosper De Laure committed
592
}