log.php 16.3 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
56
57
58
59
60
61
62
63
64
65
66
    }

    /**
     * Get a  search result
     * @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 int    $numberOfResult The process identifier
     *
     * @return array Array of logs
     */
Alexandre Morin's avatar
Alexandre Morin committed
67
68
69
70
71
72
73
74
75
76
    public function find(
        $archiveId = null,
        $type = null,
        $fromDate = null,
        $toDate = null,
        $processName = null,
        $processId = null,
        $sortBy = ">fromDate",
        $numberOfResult = null
    ) {
Prosper De Laure's avatar
Prosper De Laure committed
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
        $queryParts = array();
        $queryParams = array();

        //$queryParts[] = $this->auth->getUserAccessRule('recordsManagement/log');

        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
93
94
95
96
97
98
            $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
99
100

        } elseif ($toDate) {
Alexis Ragot's avatar
Alexis Ragot committed
101
102
            $queryParams['toDate'] = $toDate->format('Y-m-d').'T23:59:59';
            $queryParts['date'] = "toDate <= :toDate";
Prosper De Laure's avatar
Prosper De Laure committed
103
104
105
106
107
108
109
110
111
112
113
114
115
116
        }

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

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

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

Alexandre Morin's avatar
Alexandre Morin committed
117
118
119
120
121
122
123
124
125
126
127
128
        if (!$numberOfResult) {
            $numberOfResult = \laabs::configuration('presentation.maarchRM')['maxResults'];
        }

        $logs = $this->sdoFactory->find(
            "recordsManagement/log",
            $queryString,
            $queryParams,
            $sortBy,
            0,
            $numberOfResult
        );
Prosper De Laure's avatar
Prosper De Laure committed
129
130
131
132

        return $logs;
    }

133
134
135
136
137
    /**
     * 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
138
     *
139
     * @return object Array of description objects
140
     */
141
    public function search($description = null, $text = null, array $args = [], $checkAccess = null, $maxResults = null)
142
    {
Cyril Vazquez's avatar
Cyril Vazquez committed
143
144
145
146
147
        $archiveController = \laabs::newController('recordsManagement/archive');
        $archives = [];

        $sortBy = ">fromDate";

148
        $logs = $this->sdoFactory->find("recordsManagement/log", $description, [], $sortBy, 0, $maxResults);
Cyril Vazquez's avatar
Cyril Vazquez committed
149
150
151
152
153
154
        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
155
            }
Cyril Vazquez's avatar
Cyril Vazquez committed
156
157
158
        }

        return $archives;
159
160
    }

161
162
163
164
165
166
167
168
169
170
    /**
     * 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)
    {
171
        return count($this->search($description, $text, $args, $checkAccess, $maxResults = null));
172
173
    }

Prosper De Laure's avatar
Prosper De Laure committed
174
175
176
177
178
179
180
181
182
    /**
     * 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
183
184
185
186
187
188
189
190
        $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
191
192
193
194
195
196
197
198
199
200

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

        return end($journal);
    }

    /**
     * Create the requested log
201
     * @param object $archive The archived log object
Prosper De Laure's avatar
Prosper De Laure committed
202
203
204
     *
     * @return boolean status of the query
     */
205
    public function create($archive)
Prosper De Laure's avatar
Prosper De Laure committed
206
    {
207
        if (!\laabs::validate($archive->descriptionObject)) {
Prosper De Laure's avatar
Prosper De Laure committed
208
209
210
211
212
            $e = new \core\Exception('Invalid log data');

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

214
        $archive->descriptionObject->archiveId = $archive->archiveId;
Alexis Ragot's avatar
Alexis Ragot committed
215

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

218
        return true;
Prosper De Laure's avatar
Prosper De Laure committed
219
220
221
222
223
224
    }

    /**
     * Read an log with its archive identifier
     * @param id $archiveId
     *
225
     * @return recordsManagement/log Log with its archive identifier
Prosper De Laure's avatar
Prosper De Laure committed
226
227
228
229
230
231
     */
    public function read($archiveId)
    {
        return $this->sdoFactory->read("recordsManagement/log", $archiveId);
    }

232
233
    /**
     * Update the description object
Cyril Vazquez's avatar
Cyril Vazquez committed
234
     * @param object $archive
235
     */
Cyril Vazquez's avatar
Cyril Vazquez committed
236
    public function update($archive)
237
238
239
240
241
242
243
244
245
    {
        // Not implemented yet...
    }

    /**
     * Delete the description object
     * @param id   $archiveId
     * @param bool $deleteDescription
     */
Alexis Ragot's avatar
Alexis Ragot committed
246
    public function delete($archiveId, $deleteDescription = true)
247
248
249
250
    {
        // Not possible
    }

Prosper De Laure's avatar
Prosper De Laure committed
251
252
253
254
255
256
257
258
    /**
     * Read the first journal
     * @param string $type The type of journal
     *
     * @return recordsManagement/log The next journal
     */
    public function getFirstJournal($type)
    {
259
        $firstJournal = $this->sdoFactory->find('recordsManagement/log', "type='$type'", [], "<fromDate", 0, 1);
Prosper De Laure's avatar
Prosper De Laure committed
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
        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
279
280
281
282
283
284
285
286
287
        $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
288
289
290
291
292
293
294
295
296
        if (!count($nextJournal)) {
            return null;
        }

        return end($nextJournal);
    }

    /**
     * Get the last usable journal
297
     * @param string $type              The type of journal
298
     * @param string $ownerOrgRegNumber The journal owner organization registration number
Prosper De Laure's avatar
Prosper De Laure committed
299
300
301
     *
     * @return recordsManagement/log The journal object
     */
302
    public function getLastJournal($type, $ownerOrgRegNumber = null)
Prosper De Laure's avatar
Prosper De Laure committed
303
    {
304
305
306
307
308
        if ($ownerOrgRegNumber) {
            $query = "type='$type' AND ownerOrgRegNumber = '$ownerOrgRegNumber'";
        } else {
            $query = "type='$type' AND ownerOrgRegNumber = null";
        }
309

310
        $journals = $this->sdoFactory->find('recordsManagement/log', $query, [], ">toDate", 0, 1);
Prosper De Laure's avatar
Prosper De Laure committed
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331

        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
332
333
334
335
336
337
338
339
    public function depositJournal(
        $journalFileName,
        $fromDate,
        $toDate,
        $type,
        $processName = null,
        $timestampFileName = null
    ) {
Prosper De Laure's avatar
Prosper De Laure committed
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
        $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
366
        if (!($currentOrganization->orgRoleCodes && in_array("owner", (array) $currentOrganization->orgRoleCodes))) {
Alexandre Morin's avatar
Alexandre Morin committed
367
368
369
370
            throw \laabs::newException(
                "recordsManagement/logException",
                "The journal must be archived by an owner organization."
            );
Prosper De Laure's avatar
Prosper De Laure committed
371
372
373
374
375
376
377
378
379
380
381
382
        }

        $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';
383
        $archive->fileplanLevel = 'item';
Alexandre Morin's avatar
Alexandre Morin committed
384
385
386
387
388
389
390
        $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
391

Alexis Ragot's avatar
Alexis Ragot committed
392
393
        if (!empty($this->logFilePlan)) {
            $path = $this->resolveLogFilePlan($this->logFilePlan, ["type" => $log->type]);
Alexandre Morin's avatar
Alexandre Morin committed
394
395
396
397
398
            $position = $this->filePlanController->createFromPath(
                $path,
                $currentOrganization->registrationNumber,
                true
            );
Alexis Ragot's avatar
Alexis Ragot committed
399
400
401
            $archive->filePlanPosition = $position;
        }

Prosper De Laure's avatar
Prosper De Laure committed
402
403
404
405
         // Create resource
        $journalResource = $digitalResourceController->createFromFile($journalFileName);
        $journalResource->puid = "x-fmt/18";
        $journalResource->mimetype = "text/csv";
406
        $journalResource->archiveId = $archive->archiveId;
Prosper De Laure's avatar
Prosper De Laure committed
407
408
        $digitalResourceController->getHash($journalResource, "SHA256");

409
410
        $archive->digitalResources[] = $journalResource;

Prosper De Laure's avatar
Prosper De Laure committed
411
412
413
414
        if ($timestampFileName) {
            // Create timestamp resource
            $timestampResource = $digitalResourceController->createFromFile($timestampFileName);
            $digitalResourceController->getHash($timestampResource, "SHA256");
415

416
417
            $logMessage = ["message" => "Timestamp file generated"];
            \laabs::notify(\bundle\audit\AUDIT_ENTRY_OUTPUT, $logMessage);
Prosper De Laure's avatar
Prosper De Laure committed
418

419
420
421
422
423
            $timestampResource->archiveId = $journalResource->archiveId;
            $timestampResource->relatedResId = $journalResource->resId;
            $timestampResource->relationshipType = "isTimestampOf";

            $archive->digitalResources[] = $timestampResource;
Prosper De Laure's avatar
Prosper De Laure committed
424
425
426
427
428
        }

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

Alexandre Morin's avatar
Alexandre Morin committed
429
430
431
432
        $archive->originatorOrgRegNumber =
        $archive->archiverOrgRegNumber =
        $archive->depositorOrgRegNumber =
            (string) $currentOrganization->registrationNumber;
Prosper De Laure's avatar
Prosper De Laure committed
433
434
435
436
        $archive->originatorOwnerOrgId = (string) $currentOrganization->orgId;

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

437
438
439
440
441
442
        if (strpos($archiveController->useServiceLevel("deposit")->control, "fullTextIndexation")) {
            $archive->fullTextIndexation = "requested";
        } else {
            $archive->fullTextIndexation = "none";
        }

443
444
445
446
447
448
449
450
451
452
453
454
        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
455
    }
Alexandre Morin's avatar
Alexandre Morin committed
456

Alexis Ragot's avatar
Alexis Ragot committed
457
458
459
460
461
462
463
464
465
466
467
468
469
    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]):
470
471
472
473
                        if (array_key_exists($values[$token], $this->translationLogType)) {
                            $values[$token] = $this->translationLogType[$values[$token]];
                        }

Alexis Ragot's avatar
Alexis Ragot committed
474
475
476
477
478
479
480
481
482
                        $path = str_replace($variable, (string) $values[$token], $path);
                        break;
                }
            }
        }

        return $path;
    }

Alexandre Morin's avatar
Alexandre Morin committed
483
484
485
486
487
488
489
    public function contents ($type, $archiveId, $resourceId) {
        $archiveController = \laabs::newController('recordsManagement/archive');

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

        $journal = $type . PHP_EOL;
        $journal .= $archiveId . ',' . $resourceId . PHP_EOL;
Alexandre Morin's avatar
Alexandre Morin committed
490
        $journal .= base64_decode($res->attachment->data);
Alexandre Morin's avatar
Alexandre Morin committed
491
492
493

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