log.php 18 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
79
80
81
82
        $fromDate = \laabs::newDateTime($fromDate);
        $toDate = \laabs::newDateTime($toDate);
        $fromDate->setTimezone(new \DateTimeZone('UTC'));
        $toDate->setTimezone(new \DateTimeZone('UTC'));
        
83
        list($queryParams, $queryString) = $this->queryBuilder($archiveId, $type, $fromDate, $toDate, $processName, $processId);
Prosper De Laure's avatar
Prosper De Laure committed
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
114
115
116
117
118
        $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
119
120
121
122
123
124
125
126
127
128
129
130

        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
131
132
133
134
135
136
            $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
137
        } elseif ($toDate) {
Alexis Ragot's avatar
Alexis Ragot committed
138
139
            $queryParams['toDate'] = $toDate->format('Y-m-d').'T23:59:59';
            $queryParts['date'] = "toDate <= :toDate";
Prosper De Laure's avatar
Prosper De Laure committed
140
141
142
143
144
145
146
147
148
149
150
151
152
153
        }

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

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

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

154
155
        return [$queryParams, $queryString];
    }
Alexandre Morin's avatar
Alexandre Morin committed
156

157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
    /**
     * 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
180
181
            "recordsManagement/log",
            $queryString,
182
            $queryParams
Alexandre Morin's avatar
Alexandre Morin committed
183
        );
Prosper De Laure's avatar
Prosper De Laure committed
184

185
        return $count;
Prosper De Laure's avatar
Prosper De Laure committed
186
187
    }

188
189
190
191
192
    /**
     * Search the description 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
Alexis Ragot's avatar
Alexis Ragot committed
193
     *
194
     * @return object Array of description objects
195
     */
196
    public function search($description = null, $text = null, array $args = [], $checkAccess = null, $maxResults = null)
197
    {
Cyril Vazquez's avatar
Cyril Vazquez committed
198
199
200
201
202
        $archiveController = \laabs::newController('recordsManagement/archive');
        $archives = [];

        $sortBy = ">fromDate";

203
        $logs = $this->sdoFactory->find("recordsManagement/log", $description, [], $sortBy, 0, $maxResults);
Cyril Vazquez's avatar
Cyril Vazquez committed
204
205
206
207
208
209
        foreach ($logs as $log) {
            try {
                $archive = $archiveController->read($log->archiveId);
                $archive->descriptionObject = $log;
                $archives[] = $archive;
            } catch (\Exception $e) {
Alexis Ragot's avatar
Alexis Ragot committed
210
            }
Cyril Vazquez's avatar
Cyril Vazquez committed
211
212
213
        }

        return $archives;
214
215
    }

216
217
218
219
220
221
222
223
224
225
226
227
228
    /**
     * 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
229
230
231
232
233
234
235
236
237
    /**
     * 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
238
239
240
241
242
243
244
245
        $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
246
247
248
249
250
251
252
253
254
255

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

        return end($journal);
    }

    /**
     * Create the requested log
256
     * @param object $archive The archived log object
Prosper De Laure's avatar
Prosper De Laure committed
257
258
259
     *
     * @return boolean status of the query
     */
260
    public function create($archive)
Prosper De Laure's avatar
Prosper De Laure committed
261
    {
262
        if (!\laabs::validate($archive->descriptionObject)) {
Prosper De Laure's avatar
Prosper De Laure committed
263
264
265
266
267
            $e = new \core\Exception('Invalid log data');

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

269
        $archive->descriptionObject->archiveId = $archive->archiveId;
Alexis Ragot's avatar
Alexis Ragot committed
270

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

273
        return true;
Prosper De Laure's avatar
Prosper De Laure committed
274
275
276
277
278
279
    }

    /**
     * Read an log with its archive identifier
     * @param id $archiveId
     *
280
     * @return recordsManagement/log Log with its archive identifier
Prosper De Laure's avatar
Prosper De Laure committed
281
282
283
284
285
286
     */
    public function read($archiveId)
    {
        return $this->sdoFactory->read("recordsManagement/log", $archiveId);
    }

287
288
    /**
     * Update the description object
Cyril Vazquez's avatar
Cyril Vazquez committed
289
     * @param object $archive
290
     */
Cyril Vazquez's avatar
Cyril Vazquez committed
291
    public function update($archive)
292
293
294
295
296
297
298
299
300
    {
        // Not implemented yet...
    }

    /**
     * Delete the description object
     * @param id   $archiveId
     * @param bool $deleteDescription
     */
Alexis Ragot's avatar
Alexis Ragot committed
301
    public function delete($archiveId, $deleteDescription = true)
302
303
304
305
    {
        // Not possible
    }

Prosper De Laure's avatar
Prosper De Laure committed
306
307
308
309
310
311
312
313
    /**
     * Read the first journal
     * @param string $type The type of journal
     *
     * @return recordsManagement/log The next journal
     */
    public function getFirstJournal($type)
    {
314
        $firstJournal = $this->sdoFactory->find('recordsManagement/log', "type='$type'", [], "<fromDate", 0, 1);
Prosper De Laure's avatar
Prosper De Laure committed
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
        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
334
335
336
337
338
339
340
341
342
        $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
343
344
345
346
347
348
349
350
351
        if (!count($nextJournal)) {
            return null;
        }

        return end($nextJournal);
    }

    /**
     * Get the last usable journal
352
353
     * @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
354
355
356
     *
     * @return recordsManagement/log The journal object
     */
357
    public function getLastJournal($type, $ownerOrgRegNumber = null)
Prosper De Laure's avatar
Prosper De Laure committed
358
    {
359
360
361
362
363
        if ($ownerOrgRegNumber) {
            $query = "type='$type' AND ownerOrgRegNumber = '$ownerOrgRegNumber'";
        } else {
            $query = "type='$type' AND ownerOrgRegNumber = null";
        }
364
        
365
        $journals = $this->sdoFactory->find('recordsManagement/log', $query, [], ">toDate", 0, 1);
Prosper De Laure's avatar
Prosper De Laure committed
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386

        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
387
388
389
390
391
392
393
394
    public function depositJournal(
        $journalFileName,
        $fromDate,
        $toDate,
        $type,
        $processName = null,
        $timestampFileName = null
    ) {
Prosper De Laure's avatar
Prosper De Laure committed
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
        $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
421
        if (!($currentOrganization->orgRoleCodes && in_array("owner", (array) $currentOrganization->orgRoleCodes))) {
Alexandre Morin's avatar
Alexandre Morin committed
422
423
424
425
            throw \laabs::newException(
                "recordsManagement/logException",
                "The journal must be archived by an owner organization."
            );
Prosper De Laure's avatar
Prosper De Laure committed
426
427
428
429
430
431
432
433
434
435
436
437
        }

        $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';
438
        $archive->fileplanLevel = 'item';
Alexandre Morin's avatar
Alexandre Morin committed
439
440
441
442
443
444
445
        $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
446

Alexis Ragot's avatar
Alexis Ragot committed
447
448
        if (!empty($this->logFilePlan)) {
            $path = $this->resolveLogFilePlan($this->logFilePlan, ["type" => $log->type]);
Alexandre Morin's avatar
Alexandre Morin committed
449
450
451
452
453
            $position = $this->filePlanController->createFromPath(
                $path,
                $currentOrganization->registrationNumber,
                true
            );
Alexis Ragot's avatar
Alexis Ragot committed
454
455
456
            $archive->filePlanPosition = $position;
        }

Prosper De Laure's avatar
Prosper De Laure committed
457
458
459
460
         // Create resource
        $journalResource = $digitalResourceController->createFromFile($journalFileName);
        $journalResource->puid = "x-fmt/18";
        $journalResource->mimetype = "text/csv";
461
        $journalResource->archiveId = $archive->archiveId;
Prosper De Laure's avatar
Prosper De Laure committed
462
463
        $digitalResourceController->getHash($journalResource, "SHA256");

464
465
        $archive->digitalResources[] = $journalResource;

Prosper De Laure's avatar
Prosper De Laure committed
466
467
468
469
        if ($timestampFileName) {
            // Create timestamp resource
            $timestampResource = $digitalResourceController->createFromFile($timestampFileName);
            $digitalResourceController->getHash($timestampResource, "SHA256");
470
471
472
            
            $logMessage = ["message" => "Timestamp file generated"];
            \laabs::notify(\bundle\audit\AUDIT_ENTRY_OUTPUT, $logMessage);
Prosper De Laure's avatar
Prosper De Laure committed
473

474
475
476
477
478
            $timestampResource->archiveId = $journalResource->archiveId;
            $timestampResource->relatedResId = $journalResource->resId;
            $timestampResource->relationshipType = "isTimestampOf";

            $archive->digitalResources[] = $timestampResource;
Prosper De Laure's avatar
Prosper De Laure committed
479
480
481
482
483
        }

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

Alexandre Morin's avatar
Alexandre Morin committed
484
485
486
487
        $archive->originatorOrgRegNumber =
        $archive->archiverOrgRegNumber =
        $archive->depositorOrgRegNumber =
            (string) $currentOrganization->registrationNumber;
Prosper De Laure's avatar
Prosper De Laure committed
488
489
490
491
        $archive->originatorOwnerOrgId = (string) $currentOrganization->orgId;

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

492
493
494
495
496
497
        if (strpos($archiveController->useServiceLevel("deposit")->control, "fullTextIndexation")) {
            $archive->fullTextIndexation = "requested";
        } else {
            $archive->fullTextIndexation = "none";
        }

498
499
500
501
502
503
504
505
506
507
508
509
        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
510
    }
Alexandre Morin's avatar
Alexandre Morin committed
511

Alexis Ragot's avatar
Alexis Ragot committed
512
513
514
515
516
517
518
519
520
521
522
523
524
    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]):
525
526
527
528
                        if (array_key_exists($values[$token], $this->translationLogType)) {
                            $values[$token] = $this->translationLogType[$values[$token]];
                        }

Alexis Ragot's avatar
Alexis Ragot committed
529
530
531
532
533
534
535
536
537
                        $path = str_replace($variable, (string) $values[$token], $path);
                        break;
                }
            }
        }

        return $path;
    }

Benjamin Rousselière's avatar
Benjamin Rousselière committed
538
539
    public function contents($type, $archiveId, $resourceId)
    {
Alexandre Morin's avatar
Alexandre Morin committed
540
541
542
543
        $archiveController = \laabs::newController('recordsManagement/archive');

        $res = $archiveController->consultation($archiveId, $resourceId);

Benjamin Rousselière's avatar
Benjamin Rousselière committed
544
545
        $stream = (stream_get_contents($res->attachment->data));

Alexandre Morin's avatar
Alexandre Morin committed
546
547
        $journal = $type . PHP_EOL;
        $journal .= $archiveId . ',' . $resourceId . PHP_EOL;
Benjamin Rousselière's avatar
Benjamin Rousselière committed
548
        $journal .= $stream;
Alexandre Morin's avatar
Alexandre Morin committed
549
550
551

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