log.php 15.9 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
     */
Alexis Ragot's avatar
Alexis Ragot committed
141
    public function search($description = null, $text = null, array $args = [])
142
    {
Cyril Vazquez's avatar
Cyril Vazquez committed
143
144
145
146
        $archiveController = \laabs::newController('recordsManagement/archive');
        $archives = [];

        $sortBy = ">fromDate";
Alexandre Morin's avatar
Alexandre Morin committed
147
        $numberOfResult = \laabs::configuration('presentation.maarchRM')['maxResults'];
Cyril Vazquez's avatar
Cyril Vazquez committed
148

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

        return $archives;
160
161
    }

Prosper De Laure's avatar
Prosper De Laure committed
162
163
164
165
166
167
168
169
170
    /**
     * 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
171
172
173
174
175
176
177
178
        $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
179
180
181
182
183
184
185
186
187
188

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

        return end($journal);
    }

    /**
     * Create the requested log
189
     * @param object $archive The archived log object
Prosper De Laure's avatar
Prosper De Laure committed
190
191
192
     *
     * @return boolean status of the query
     */
193
    public function create($archive)
Prosper De Laure's avatar
Prosper De Laure committed
194
    {
195
        if (!\laabs::validate($archive->descriptionObject)) {
Prosper De Laure's avatar
Prosper De Laure committed
196
197
198
199
200
            $e = new \core\Exception('Invalid log data');

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

202
        $archive->descriptionObject->archiveId = $archive->archiveId;
Alexis Ragot's avatar
Alexis Ragot committed
203

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

206
        return true;
Prosper De Laure's avatar
Prosper De Laure committed
207
208
209
210
211
212
    }

    /**
     * Read an log with its archive identifier
     * @param id $archiveId
     *
213
     * @return recordsManagement/log Log with its archive identifier
Prosper De Laure's avatar
Prosper De Laure committed
214
215
216
217
218
219
     */
    public function read($archiveId)
    {
        return $this->sdoFactory->read("recordsManagement/log", $archiveId);
    }

220
221
    /**
     * Update the description object
Cyril Vazquez's avatar
Cyril Vazquez committed
222
     * @param object $archive
223
     */
Cyril Vazquez's avatar
Cyril Vazquez committed
224
    public function update($archive)
225
226
227
228
229
230
231
232
233
    {
        // Not implemented yet...
    }

    /**
     * Delete the description object
     * @param id   $archiveId
     * @param bool $deleteDescription
     */
Alexis Ragot's avatar
Alexis Ragot committed
234
    public function delete($archiveId, $deleteDescription = true)
235
236
237
238
    {
        // Not possible
    }

Prosper De Laure's avatar
Prosper De Laure committed
239
240
241
242
243
244
245
246
    /**
     * Read the first journal
     * @param string $type The type of journal
     *
     * @return recordsManagement/log The next journal
     */
    public function getFirstJournal($type)
    {
247
        $firstJournal = $this->sdoFactory->find('recordsManagement/log', "type='$type'", [], "<fromDate", 0, 1);
Prosper De Laure's avatar
Prosper De Laure committed
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
        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
267
268
269
270
271
272
273
274
275
        $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
276
277
278
279
280
281
282
283
284
        if (!count($nextJournal)) {
            return null;
        }

        return end($nextJournal);
    }

    /**
     * Get the last usable journal
285
286
     * @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
287
288
289
     *
     * @return recordsManagement/log The journal object
     */
290
    public function getLastJournal($type, $ownerOrgRegNumber = null)
Prosper De Laure's avatar
Prosper De Laure committed
291
    {
292
293
294
295
296
        if ($ownerOrgRegNumber) {
            $query = "type='$type' AND ownerOrgRegNumber = '$ownerOrgRegNumber'";
        } else {
            $query = "type='$type' AND ownerOrgRegNumber = null";
        }
297
        
298
        $journals = $this->sdoFactory->find('recordsManagement/log', $query, [], ">toDate", 0, 1);
Prosper De Laure's avatar
Prosper De Laure committed
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319

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

        $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';
371
        $archive->fileplanLevel = 'item';
Alexandre Morin's avatar
Alexandre Morin committed
372
373
374
375
376
377
378
        $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
379

Alexis Ragot's avatar
Alexis Ragot committed
380
381
        if (!empty($this->logFilePlan)) {
            $path = $this->resolveLogFilePlan($this->logFilePlan, ["type" => $log->type]);
Alexandre Morin's avatar
Alexandre Morin committed
382
383
384
385
386
            $position = $this->filePlanController->createFromPath(
                $path,
                $currentOrganization->registrationNumber,
                true
            );
Alexis Ragot's avatar
Alexis Ragot committed
387
388
389
            $archive->filePlanPosition = $position;
        }

Prosper De Laure's avatar
Prosper De Laure committed
390
391
392
393
         // Create resource
        $journalResource = $digitalResourceController->createFromFile($journalFileName);
        $journalResource->puid = "x-fmt/18";
        $journalResource->mimetype = "text/csv";
394
        $journalResource->archiveId = $archive->archiveId;
Prosper De Laure's avatar
Prosper De Laure committed
395
396
        $digitalResourceController->getHash($journalResource, "SHA256");

397
398
        $archive->digitalResources[] = $journalResource;

Prosper De Laure's avatar
Prosper De Laure committed
399
400
401
402
        if ($timestampFileName) {
            // Create timestamp resource
            $timestampResource = $digitalResourceController->createFromFile($timestampFileName);
            $digitalResourceController->getHash($timestampResource, "SHA256");
403
404
405
            
            $logMessage = ["message" => "Timestamp file generated"];
            \laabs::notify(\bundle\audit\AUDIT_ENTRY_OUTPUT, $logMessage);
Prosper De Laure's avatar
Prosper De Laure committed
406

407
408
409
410
411
            $timestampResource->archiveId = $journalResource->archiveId;
            $timestampResource->relatedResId = $journalResource->resId;
            $timestampResource->relationshipType = "isTimestampOf";

            $archive->digitalResources[] = $timestampResource;
Prosper De Laure's avatar
Prosper De Laure committed
412
413
414
415
416
        }

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

Alexandre Morin's avatar
Alexandre Morin committed
417
418
419
420
        $archive->originatorOrgRegNumber =
        $archive->archiverOrgRegNumber =
        $archive->depositorOrgRegNumber =
            (string) $currentOrganization->registrationNumber;
Prosper De Laure's avatar
Prosper De Laure committed
421
422
423
424
        $archive->originatorOwnerOrgId = (string) $currentOrganization->orgId;

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

425
426
427
428
429
430
        if (strpos($archiveController->useServiceLevel("deposit")->control, "fullTextIndexation")) {
            $archive->fullTextIndexation = "requested";
        } else {
            $archive->fullTextIndexation = "none";
        }

431
432
433
434
435
436
437
438
439
440
441
442
        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
443
    }
Alexandre Morin's avatar
Alexandre Morin committed
444

Alexis Ragot's avatar
Alexis Ragot committed
445
446
447
448
449
450
451
452
453
454
455
456
457
    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]):
458
459
460
461
                        if (array_key_exists($values[$token], $this->translationLogType)) {
                            $values[$token] = $this->translationLogType[$values[$token]];
                        }

Alexis Ragot's avatar
Alexis Ragot committed
462
463
464
465
466
467
468
469
470
                        $path = str_replace($variable, (string) $values[$token], $path);
                        break;
                }
            }
        }

        return $path;
    }

Benjamin Rousselière's avatar
Benjamin Rousselière committed
471
472
    public function contents($type, $archiveId, $resourceId)
    {
Alexandre Morin's avatar
Alexandre Morin committed
473
474
475
476
        $archiveController = \laabs::newController('recordsManagement/archive');

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

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

Alexandre Morin's avatar
Alexandre Morin committed
479
480
        $journal = $type . PHP_EOL;
        $journal .= $archiveId . ',' . $resourceId . PHP_EOL;
Benjamin Rousselière's avatar
Benjamin Rousselière committed
481
        $journal .= $stream;
Alexandre Morin's avatar
Alexandre Morin committed
482
483
484

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