ArchiveTransfer.php 35 KB
Newer Older
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 medona
 *
 * Bundle medona 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 medona 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 medona.  If not, see <http://www.gnu.org/licenses/>.
 */

namespace ext\thirdPartyArchiving\bundle\medona\Controller;

/**
 * trait for archive transfer
 *
 * @package Medona
 * @author  Alexis Ragot <alexis.ragot@maarch.org>
 */
30
class ArchiveTransfer extends abstractMessage
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
{
    protected $archiveParser;

    protected $droid;

    protected $jhove;

    /**
     * Get received archive tranfer message
     *
     * @return array Array of medona/message object
     */
    public function listReception()
    {
        $registrationNumber = $this->getCurrentRegistrationNumber();

        $queryParts = [];
        $queryParts[] = "recipientOrgRegNumber=$registrationNumber";
        $queryParts[] = "type='ArchiveTransfer'";
        $queryParts[] = "active=true";
51
52
        $queryParts[] = "isIncoming=true";
        $queryParts[] = "status != 'processed' AND status != 'error' AND status != 'invalid' AND status !='draft' AND status !='template' AND status !='rejected' AND status !='acknowledge'" ;
53
54
55
56
57
58
59
60
61
62
63
64

        return $this->sdoFactory->find('medona/message', implode(' and ', $queryParts), null, false, false, 300);
    }

    /**
     * Get sending archive tranfer message
     *
     * @return array Array of medona/message object
     */
    public function listSending()
    {
        $registrationNumber = $this->getCurrentRegistrationNumber();
65
        $accountToken = \laabs::getToken("AUTH");
66
67

        $queryParts = [];
68
        $queryParts[] = "(accountId= '$accountToken->accountId' OR senderOrgRegNumber=$registrationNumber)";
69
70
        $queryParts[] = "type='ArchiveTransfer'";
        $queryParts[] = "active=true";
71
        $queryParts[] = "isIncoming=true";
72
73
74
75
76
77
78
        $queryParts[] = "status=['sent', 'received','accepted']";

        return $this->sdoFactory->find("medona/message", implode(' and ', $queryParts), null, false, false, 300);
    }

    /**
     * Get transfer history
79
80
81
82
83
84
85
     * @param string $reference
     * @param string $archiver
     * @param string $originator
     * @param string $depositor
     * @param string $archivalAgreement
     * @param date   $fromDate
     * @param date   $toDate
86
87
88
89
90
     *
     * @return array Array of medona/message object
     */
    public function history($reference = null, $archiver = null, $originator = null, $depositor = null, $archivalAgreement = null, $fromDate = null, $toDate = null)
    {
91
        return $this->search("ArchiveTransfer", $reference, $archiver, $originator, $depositor, $archivalAgreement, $fromDate, $toDate, true);
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
119
120
    }

    /**
     * Count archive tranfer message
     *
     * @return array Number of received and sent messages
     */
    public function count()
    {
        $registrationNumber = $this->getCurrentRegistrationNumber();

        $res = array();
        $queryParts = array();

        $queryParts["type"] = "type='ArchiveTransfer'";
        $queryParts["registrationNumber"] = "recipientOrgRegNumber=$registrationNumber";
        $queryParts["active"] = "active=true";
        $res['received'] = $this->sdoFactory->count('medona/message', implode(' and ', $queryParts));

        $queryParts["registrationNumber"] = "senderOrgRegNumber=$registrationNumber";

        $res['sent'] = $this->sdoFactory->count('medona/message', implode(' and ', $queryParts));

        return $res;
    }

    /**
     * Receive message with all contents embedded
     * @param string $messageFile The message binary contents OR a filename
Cyril Vazquez's avatar
Merge    
Cyril Vazquez committed
121
     * @param array  $attachments  An array of attachment binary data
Prosper De Laure's avatar
Prosper De Laure committed
122
     * @param string $filename    The message file name
123
124
125
126
127
     *
     * @return medona/message
     *
     * @todo Remove files from sas when error on reception
     */
Cyril Vazquez's avatar
Merge    
Cyril Vazquez committed
128
    public function receive($messageFile, $attachments = array(), $schema = false, $filename = false)
129
130
131
132
133
134
    {
        $messageId = \laabs::newId();
        $message = \laabs::newInstance('medona/message');
        $message->messageId = $messageId;
        $message->type = "ArchiveTransfer";
        $message->receptionDate = \laabs::newTimestamp();
135
        $message->schema = $schema;
Prosper De Laure's avatar
Prosper De Laure committed
136

137
138
139
140
141
        $messageDir = $this->messageDirectory.DIRECTORY_SEPARATOR.(string) $message->messageId;
        if (!is_dir($messageDir)) {
            mkdir($messageDir, 0777, true);
        }

142
        $this->receivePackage($message, $messageFile, $attachments, $filename);
143

Cyril Vazquez's avatar
merge    
Cyril Vazquez committed
144
        if (empty($schema)) {
145
            $this->detectSchema($message);
Cyril Vazquez's avatar
merge    
Cyril Vazquez committed
146
147
        }

Cyril Vazquez's avatar
Merge    
Cyril Vazquez committed
148
149
        try {
            $archiveTransferController = \laabs::newController($message->schema. '/ArchiveTransfer');
150
151
            $archiveTransferController->receive($message);

152
153
154
155
156
157
            try {
                $message->senderOrg = $this->orgController->getOrgByRegNumber($message->senderOrgRegNumber);
                $message->senderOrgName = $message->senderOrg->orgName;
            } catch (\Exception $e) {
                $this->sendError("202", "Le service versant identifié par '".$message->senderOrgRegNumber."' est inconnu du système.");

Alexis Ragot's avatar
Alexis Ragot committed
158
                throw \laabs::newException('medona/invalidMessageException', "Invalid message", 400);
159
160
161
162
163
164
165
166
            }

            try {
                $message->recipientOrg = $this->orgController->getOrgByRegNumber($message->recipientOrgRegNumber);
                $message->recipientOrgName = $message->recipientOrg->orgName;
            } catch (\Exception $e) {
                $this->sendError("201", "Le service d'archive identifié par '".$message->recipientOrgRegNumber."' est inconnu du système.");

Alexis Ragot's avatar
Alexis Ragot committed
167
                throw \laabs::newException('medona/invalidMessageException', "Invalid message", 400);
168
169
            }

170
            $message->isIncoming = true;
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
            $message->status = "received";
            $this->create($message);
        } catch (\Exception $e) {
            $event = $this->lifeCycleJournalController->logEvent(
                'medona/reception',
                'medona/message',
                $message->messageId,
                $message,
                false
            );

            // Remove files from sas
            $messageURI = $this->messageDirectory.DIRECTORY_SEPARATOR.$message->messageId;
            if (is_dir($messageURI)) {
                \laabs\rmdir($messageURI, true);
            }

Alexis Ragot's avatar
Alexis Ragot committed
188
189
190
            if ($e->getCode() != 0) {
                $exception = \laabs::newException('medona/invalidMessageException', "Invalid message", $e->getCode());
            } else {
191
                $exception = \laabs::newException('medona/invalidMessageException', "Invalid message", 400);
Alexis Ragot's avatar
Alexis Ragot committed
192
193
            }

194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
            if (is_array($e->errors)) {
                $exception->errors = array_merge($this->errors, $e->errors);
            } else {
                $exception->errors = $this->errors;
            }

            throw $exception;
        }

        $event = $this->lifeCycleJournalController->logEvent(
            'medona/reception',
            'medona/message',
            $message->messageId,
            $message,
            true
        );

211
212
213
214
215
        $acknowledgementController = \laabs::newController('medona/Acknowledgement');
        $acknowledgement = $acknowledgementController->send($message);
        $acknowledgement->receivedMessageId = $message->messageId;

        return $acknowledgement;
216
217
    }

218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
    protected function receivePackage($message, $messageFile, $attachments, $filename)
    {
        // Valid URL file:// http:// data://
        if (filter_var($messageFile, FILTER_VALIDATE_URL)) { 
            $data = stream_get_contents($handler);
        } elseif (preg_match('%^[a-zA-Z0-9/+]*={0,2}$%', $messageFile)) {
            $data = base64_decode($messageFile);  
        } elseif (is_file($messageFile)) {
            $data = file_get_contents($messageFile);
        }

        $mediatype = $this->finfo->buffer($data);

        if ($mediatype == 'application/zip' || $mediatype == 'application/octet-stream') {
            $this->receiveZip($message, $data, $attachments, $filename);
        } else {
            $this->receiveFiles($message, $data, $attachments, $filename);
        }
    }

    protected function receiveZip($message, $data, $filename)
    {
        $messageDir = $this->messageDirectory.DIRECTORY_SEPARATOR.(string) $message->messageId;

        $zipfile = \laabs\tempnam();
        file_put_contents($zipfile, $data);
        $tmpdir = \laabs::getTmpDir();

        $zip = \laabs::newService('dependency/fileSystem/plugins/zip');
        $zip->extract($zipfile, $tmpdir);

        $zipContents = scandir($tmpdir);
        if (!isset($zipContents[2])) {
            throw \laabs::newException('medona/invalidMessageException', "Invalid message", 400);
        }

        $message->path = $messageDir.DIRECTORY_SEPARATOR.$filename;
        $message->attachments = [];
        
        if (is_dir($tmpdir.DIRECTORY_SEPARATOR.$zipContents[2])) {
            $zipFolder = $tmpdir.DIRECTORY_SEPARATOR.$zipContents[2];
            foreach (scandir($zipFolder) as $file) {
                if ($file != "." && $file != "..") {
                    rename($zipFolder.DIRECTORY_SEPARATOR.$file, $messageDir.DIRECTORY_SEPARATOR.$file);
                    if ($file != $filename) {
                        $message->attachments[] = $file;
                    }
                }
            }

            rmdir($zipFolder);
        }
    }

    protected function receiveFiles($message, $data, $attachments, $filename=false)
    {
        $messageDir = $this->messageDirectory.DIRECTORY_SEPARATOR.(string) $message->messageId;

        if (!$filename) {
            $filename = (string) $message->messageId;
        }

        file_put_contents($messageDir.DIRECTORY_SEPARATOR.$filename, $data);
        
        $message->path = $messageDir.DIRECTORY_SEPARATOR.$filename;
        $message->attachments = [];
        
        if (count($attachments)) {
            foreach ($attachments as $attachment) {
                if (filter_var($attachment->data, FILTER_VALIDATE_URL)) { 
                    $data = stream_get_contents($attachment->data);
                } elseif (preg_match('%^[a-zA-Z0-9/+]*={0,2}$%', $attachment->data)) {
                    $data = base64_decode($attachment->data);  
                } elseif (is_file($attachment->data)) {
                    $data = file_get_contents($attachment->data);
                }
                
                file_put_contents($messageDir.DIRECTORY_SEPARATOR.$attachment->filename, $data);
                $message->attachments[] = $attachment->filename;
            }
        }
        
    }

    protected function detectSchema($message)
    {
        $mediatype = $this->finfo->file($message->path);
        if ($mediatype == 'application/xml') {
            $xml = new \DOMDocument();
            $xml->load($message->path);
            $messageNamespace = $xml->documentElement->namespaceURI;
            if (!$messageSchema = \laabs::resolveXmlNamespace($messageNamespace)) {
                throw \laabs::newException('medona/invalidMessageException', "Unknown message namespace'.$messageNamespace", 400);
            }
            $message->schema = $messageSchema;
        } else {
            $message->schema = 'recordsManagement';
        }
    }

Cyril Vazquez's avatar
Merge    
Cyril Vazquez committed
318
    protected function receiveXmlFile($message, $messageFile, $attachments = array())
319
320
    {
        $messageDir = $this->messageDirectory.DIRECTORY_SEPARATOR.(string) $message->messageId;
Cyril Vazquez's avatar
Merge    
Cyril Vazquez committed
321
322
323
        if (!is_dir($messageDir)) {
            mkdir($messageDir, 0777, true);
        }
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350

        // Load Xml from file
        $this->loadXmlFile($message, $messageFile);

        // Save to message directory
        $this->save($message);

        if (count($attachments)) {
            foreach ($attachments as $attachment) {
                if (is_file($attachment)) {
                    copy($attachment, $messageDir.DIRECTORY_SEPARATOR.basename($attachment));
                } elseif (is_dir($attachment)) {
                    $filenames = glob(dirname($messageFile).DIRECTORY_SEPARATOR."*.*");
                    foreach ($filenames as $filename) {
                        if (basename($filename) === basename($messageFile)) {
                            continue;
                        }
                        copy($filename, $messageDir.DIRECTORY_SEPARATOR.basename($filename));
                    }
                }
            }
        }
    }

    protected function receiveXml($message, $messageFile, $attachments = array())
    {
        $messageDir = $this->messageDirectory.DIRECTORY_SEPARATOR.(string) $message->messageId;
Cyril Vazquez's avatar
Merge    
Cyril Vazquez committed
351
352
353
        if (!is_dir($messageDir)) {
            mkdir($messageDir, 0777, true);
        }
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394

        // Load file xml
        $this->loadXml($message, $messageFile);

        // Save to message directory
        $this->save($message);

        if (count($attachments)) {
            foreach ($attachments as $attachment) {
                $attachment->data = base64_decode($attachment->data);
                file_put_contents($messageDir.DIRECTORY_SEPARATOR.$attachment->filename, $attachment->data);
            }
        }
    }


    /**
     * Validate the messages
     *
     * @return medona/message $message
     */
    public function validateBatch()
    {
        $results = array();

        $messages = $this->sdoFactory->find("medona/message", "status='received' AND type='ArchiveTransfer' AND active=true");
        foreach ($messages as $message) {
            $this->loadData($message);

            try {
                $results[(string) $message->messageId] = $this->validate($message);
            } catch (\Exception $e) {
                $results[(string) $message->messageId] = $e;
            }
        }

        return $results;
    }

    /**
     * Validate message against schema and rules
Cyril Vazquez's avatar
Merge    
Cyril Vazquez committed
395
396
     * @param mixed  $messageId         The message identifier
     * @param object $archivalAgreement The archival agreement
397
398
399
     *
     * @return boolean
     */
Cyril Vazquez's avatar
Merge    
Cyril Vazquez committed
400
    public function validate($messageId, $archivalAgreement = null)
401
402
    {
        $this->errors = array();
403
        $this->replyCode = null;
404
405
406
407
408
409

        $message = $this->sdoFactory->read('medona/message', $messageId);
        $this->loadData($message);

        if ($message->status == "error") {
            $this->sendError('104', "The message is in error status");
410
            $exception = \laabs::newException('medona/invalidMessageException', "Invalid message", 400);
411
412
413
414
415
416
            $exception->errors = $this->errors;

            throw $exception;
        }

        try {
Cyril Vazquez's avatar
Merge    
Cyril Vazquez committed
417
            $this->validateMessageHeaders($message);
418

Cyril Vazquez's avatar
Merge    
Cyril Vazquez committed
419
420
            $archiveTransferController = \laabs::newController($message->schema.'/ArchiveTransfer');
            $archiveTransferController->validate($message, $this->currentArchivalAgreement);
421

Cyril Vazquez's avatar
Merge    
Cyril Vazquez committed
422
423
            if ($archiveTransferController->replyCode) {
                $this->replyCode = $archiveTransferController->replyCode;
424
425
            }

Cyril Vazquez's avatar
Merge    
Cyril Vazquez committed
426
427
428
            $this->errors = array_merge($this->errors, $archiveTransferController->errors);
            $this->infos = array_merge($this->infos, $archiveTransferController->infos);
        
429
430
431
432
        } catch (\Exception $exception) {
            $this->errors[] = new \core\Error($exception->getMessage());
            $this->sendValidationError($message);

433
            $exception = \laabs::newException('medona/invalidMessageException', "Invalid message", 400);
434
435
436
437
            $exception->errors = $this->errors;

            throw $exception;
        }
438

439
440
441
442
        // Non blocking errors
        if (count($this->errors) > 0) {
            $this->sendValidationError($message);

443
            $exception = \laabs::newException('medona/invalidMessageException', "Invalid message", 400);
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
            $exception->errors = $this->errors;

            throw $exception;
        } else {

            $message->status = "valid";

            foreach ((array) $this->infos as $info) {
                $eventInfo = array();
                $eventInfo['type'] = "ArchiveTransfer";
                $eventInfo['senderOrgRegNumber'] = $message->senderOrgRegNumber;
                $eventInfo['recipientOrgRegNumber'] = $message->recipientOrgRegNumber;
                $eventInfo['reference'] = $message->reference;
                $eventInfo['code'] = "OK";
                $eventInfo['info'] = $info;

                $event = $this->lifeCycleJournalController->logEvent(
                    'medona/validation',
                    'medona/message',
                    $message->messageId,
                    $eventInfo,
                    true
                );
            }

            $this->sdoFactory->update($message);
        }

        if ($this->currentArchivalAgreement && $this->currentArchivalAgreement->autoTransferAcceptance) {
            $this->accept((string) $message->messageId);
        }

        return true;
    }

Cyril Vazquez's avatar
Merge    
Cyril Vazquez committed
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
    /**
     * Validate message header info
     */
    protected function validateMessageHeaders($message)
    {
        // Check sender (depositor) roles
        $this->validateDepositor($message);

        // Check recipient (archiver) roles
        $this->validateArchiver($message);

        if (isset($message->archivalAgreementReference)) {
            $this->validateArchivalAgreement($message);
        }
    }

Cyril Vazquez's avatar
Cyril Vazquez committed
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
    /**
     * Validate message against schema and rules for a draft message with no status change nor reply
     * @param mixed $messageId The message identifier
     *
     * @return boolean
     */
    public function validateDraft($messageId)
    {
        $this->errors = array();
        $this->replyCode = null;

        $message = $this->sdoFactory->read('medona/message', $messageId);
        $this->loadData($message);

        try {
Cyril Vazquez's avatar
Merge    
Cyril Vazquez committed
510
            $this->validateMessageHeaders($message);
511

Cyril Vazquez's avatar
Merge    
Cyril Vazquez committed
512
513
            $archiveTransferController = \laabs::newController($message->schema.'/ArchiveTransfer');
            $archiveTransferController->validate($message, $this->currentArchivalAgreement);
Cyril Vazquez's avatar
Cyril Vazquez committed
514

Cyril Vazquez's avatar
Merge    
Cyril Vazquez committed
515
516
            $this->errors = array_merge($this->errors, $archiveTransferController->errors);
            $this->infos = array_merge($this->infos, $archiveTransferController->infos);
Cyril Vazquez's avatar
Cyril Vazquez committed
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538

        } catch (\Exception $exception) {
            $this->errors[] = new \core\Error($exception->getMessage());

            $exception = \laabs::newException('medona/invalidMessageException', "Invalid message", 400);
            $exception->errors = $this->errors;

            throw $exception;
        }

        // Non blocking errors
        if (count($this->errors) > 0) {

            $exception = \laabs::newException('medona/invalidMessageException', "Invalid message", 400);
            $exception->errors = $this->errors;

            throw $exception;
        }

        return true;
    }

539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
    protected function sendValidationError($message)
    {
        $message->status = "invalid";
        foreach ((array) $this->errors as $error) {
            $eventInfo = array();
            $eventInfo['type'] = "ArchiveTransfer";
            $eventInfo['senderOrgRegNumber'] = $message->senderOrgRegNumber;
            $eventInfo['recipientOrgRegNumber'] = $message->recipientOrgRegNumber;
            $eventInfo['reference'] = $message->reference;
            $eventInfo['code'] = $error->getCode();
            $eventInfo['info'] = $error->getMessage();

            $event = $this->lifeCycleJournalController->logEvent(
                'medona/validation',
                'medona/message',
                $message->messageId,
                $eventInfo,
                false
            );
        }

        $this->sdoFactory->update($message);

        $archiveTransferReplyController = \laabs::newController('medona/ArchiveTransferReply');
        $archiveTransferReplyController->send($message, $this->replyCode);
    }

    protected function validateDepositor($message)
    {
        try {
            $senderOrg = $this->orgController->getOrgByRegNumber($message->senderOrgRegNumber);
        } catch (\Exception $e) {
            $this->sendError("202", "Le service versant identifié par '".$message->senderOrgRegNumber."' est inconnu du système.");

573
            throw \laabs::newException('medona/invalidMessageException', "Invalid message", 400);
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
        }

        $senderRoles = (array) $senderOrg->orgRoleCodes;
        if (!in_array("depositor", $senderRoles)) {
            $this->sendError("202", "Le service versant identifié par '".$message->senderOrgRegNumber."' ne possède pas le rôle d'acteur adéquat dans le système.");
        }

        return true;
    }

    protected function validateArchiver($message)
    {
        try {
            $recipientOrg = $this->orgController->getOrgByRegNumber($message->recipientOrgRegNumber);
        } catch (\Exception $e) {
            $this->sendError("201", "Le service d'archive identifié par '".$message->recipientOrgRegNumber."' est inconnu du système.");

591
            throw \laabs::newException('medona/invalidMessageException', "Invalid message", 400);
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
        }

        $recipientRoles = (array) $recipientOrg->orgRoleCodes;
        if (!in_array("archiver", $recipientRoles)) {
            $this->sendError("202", "Le service d'archives identifié par '".$message->recipientOrgRegNumber."' ne possède pas le rôle d'acteur adéquat dans le système.");
        }

        return true;
    }

    protected function validateArchivalAgreement($message)
    {

        try {
            $this->useArchivalAgreement($message->archivalAgreementReference);

        } catch (\Exception $e) {
            $this->sendError("300", "L'accord de versement '$message->archivalAgreementReference' n'a pas pu être lu.");

611
            throw \laabs::newException('medona/invalidMessageException', "Invalid message", 400);
612
613
614
615
616
617
618
619
620
621
622
        }

        // Check actor orgnizations
        if ($this->currentArchivalAgreement->depositorOrgRegNumber != $message->senderOrgRegNumber) {
            $this->sendError("303", "Le service versant n'est pas conforme à celui indiqué dans l'accord de versement.");
        }

        if ($this->currentArchivalAgreement->archiverOrgRegNumber != $message->recipientOrgRegNumber) {
            $this->sendError("304", "Le service d'archives n'est pas conforme à celui indiqué dans l'accord de versement.");
        }

623
624
625
626
        if ($message->schema == 'medona') {
            if (empty($this->currentArchivalAgreement->originatorOrgIds)) {
                $this->sendError("300", "Il n'y a pas de service producteur.");
            } else {
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
                $archivalAgreementOriginators = [];

                foreach ((array) $this->currentArchivalAgreement->originatorOrgIds as $orgId) {
                    $organization = $this->orgController->read($orgId);
                    $archivalAgreementOriginators[] = $organization->registrationNumber;
                }

                $originators = (array) $message->object->dataObjectPackage->managementMetadata->accessRule->originatorOrgRegNumber;

                if (is_array($message->object->dataObjectPackage->descriptiveMetadata->archive)) {
                    foreach ($message->object->dataObjectPackage->descriptiveMetadata->archive as $archive) {
                        if ($archive->originatorOrgRegNumber) {
                            $originators[] = $archive->originatorOrgRegNumber;
                        }
                    }
                }

                foreach ($originators as $originator) {
                    if (!in_array($originator, $archivalAgreementOriginators)) {
                        $this->sendError("302", "Le service producteur identifié par $originator ne correspond pas à l'accord de versement.");
                    }
                }
            }
        }

        $today = \laabs::newDate();
        // Check dates and activity
        if (isset($this->currentArchivalAgreement->beginDate)) {
            if ($this->currentArchivalAgreement->beginDate->diff($today)->invert) {
                $this->sendError("312", "L'accord de versement n'est pas encore en cours de validité.");
            }
        }

        if (isset($this->currentArchivalAgreement->endDate)) {
            if (!$this->currentArchivalAgreement->endDate->diff($today)->invert) {
                $this->sendError("312", "L'accord de versement n'est plus en cours de validité.");
            }
        }

        if ($this->currentArchivalAgreement->enabled != true) {
            $this->sendError("300", "L'accord de versement n'est pas actif.");
        }

670
671
672
673
        $dateOnDay = $today->shift(new \core\Type\Duration("P1D"));
        $dateOnWeek = $today->shift(new \core\Type\Duration("P7D"));
        $dateOnMonth = $today->shift(new \core\Type\Duration("P1M"));
        $dateOnYear = $today->shift(new \core\Type\Duration("P1Y"));
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
        $dateArchivalAgreement = $this->currentArchivalAgreement->beginDate;

        if ($message->size > ($this->currentArchivalAgreement->maxSizeTransfer*1048576) && $this->currentArchivalAgreement->maxSizeTransfer > 0) {
            $this->sendError("301", "La taille maximale par tranfert de l'accord de versement est dépassée.");
        }

        $res = $this->sdoFactory->summarise("medona/message", "archivalAgreementReference", "size", "date > '$dateOnDay' and archivalAgreementReference='".$this->currentArchivalAgreement->reference."'");
        if (count($res) && $res[$this->currentArchivalAgreement->reference] > ($this->currentArchivalAgreement->maxSizeDay*1048576) && $this->currentArchivalAgreement->maxSizeDay > 0) {
            $this->sendError("301", "La taille maximale par jour de l'accord de versement est dépassée.");
        }

        $res = $this->sdoFactory->summarise("medona/message", "archivalAgreementReference", "size", "date > '$dateOnWeek' and archivalAgreementReference='".$this->currentArchivalAgreement->reference."'");
        if (count($res) && $res[$this->currentArchivalAgreement->reference] > ($this->currentArchivalAgreement->maxSizeWeek*1048576) && $this->currentArchivalAgreement->maxSizeWeek > 0) {
            $this->sendError("301", "La taille maximale par semaine de l'accord de versement est dépassée.");
        }

        $res = $this->sdoFactory->summarise("medona/message", "archivalAgreementReference", "size", "date > '$dateOnMonth' and archivalAgreementReference='".$this->currentArchivalAgreement->reference."'");
        if (count($res) && $res[$this->currentArchivalAgreement->reference] > ($this->currentArchivalAgreement->maxSizeMonth*1048576) && $this->currentArchivalAgreement->maxSizeMonth > 0) {
            $this->sendError("301", "La taille maximale par mois de l'accord de versement est dépassée.");
        }

        $res = $this->sdoFactory->summarise("medona/message", "archivalAgreementReference", "size", "date > '$dateOnYear' and archivalAgreementReference='".$this->currentArchivalAgreement->reference."'");
        if (count($res) && $res[$this->currentArchivalAgreement->reference] > ($this->currentArchivalAgreement->maxSizeYear*1048576) && $this->currentArchivalAgreement->maxSizeYear > 0) {
            $this->sendError("301", "La taille maximale par année de l'accord de versement est dépassée.");
        }

        $res = $this->sdoFactory->summarise("medona/message", "archivalAgreementReference", "size", "date > '$dateArchivalAgreement' and archivalAgreementReference='".$this->currentArchivalAgreement->reference."'");
        if (count($res) && $res[$this->currentArchivalAgreement->reference] > ($this->currentArchivalAgreement->maxSizeAgreement*1048576) && $this->currentArchivalAgreement->maxSizeAgreement > 0) {
            $this->sendError("301", "La taille maximale de l'accord de versement est dépassée.");
        }

        return true;
    }

    /**
     * Process the messages
     *
     * @return medona/message $message
     */
    public function processBatch()
    {
        $results = array();

        $messages = $this->sdoFactory->find("medona/message", "status='accepted' AND type='ArchiveTransfer' AND active=true");
        foreach ($messages as $message) {
            $this->changeStatus($message->messageId, "processing");
            $this->loadData($message);

            try {
                $results[(string) $message->messageId] = $this->process($message);
            } catch (\Exception $e) {
                $results[(string) $message->messageId] = $e;
            }
        }

729
730
731
        $logMessage = ["message" => "%s message(s) processed", "variables"=> count($results)];
        \laabs::notify(\bundle\audit\AUDIT_ENTRY_OUTPUT, $logMessage);

732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
        return $results;
    }

    /**
     * Validate message against schema and rules
     * @param medona/message $messageId
     *
     * @return the result of process
     */
    public function process($messageId)
    {
        if (is_scalar($messageId)) {
            $message = $this->read($messageId);

            $this->loadData($message);
        } else {
            $message = $messageId;
        }

cyril-vazquez's avatar
cyril-vazquez committed
751
        $this->changeStatus((string) $message->messageId, "processing");
752
753
754
755
756
757

        if (!isset($this->finfo)) {
            $this->finfo = new \finfo();
        }

        try {
Cyril Vazquez's avatar
Merge    
Cyril Vazquez committed
758
759
            $archiveTransferController = \laabs::newController($message->schema.'/ArchiveTransfer');
            list($archives, $archiveRelationships) = $archiveTransferController->process($message);
760
761
762

            $operationResult = true;
        } catch (\Exception $e) {
cyril-vazquez's avatar
cyril-vazquez committed
763
764
            $message->status = "error";
            $this->sdoFactory->update($message);
765

766
767
768
769
770
771
772
773
            $this->lifeCycleJournalController->logEvent(
                'medona/processing',
                'medona/message',
                $message->messageId,
                $message,
                false
            );

774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
            throw $e;
        }

        $transactionControl = !$this->sdoFactory->inTransaction();

        if ($transactionControl) {
            $this->sdoFactory->beginTransaction();
        }

        try {
            $message->unitIdentifier = array();

            $originatorOrgs = [];
            $organizationController = \laabs::newController("organization/organization");

789
790
            $filePlanPosition = $this->archiveController->resolveStoragePath(get_object_vars($message));

791
792
793
794
795
796
797
798
            foreach ($archives as $archive) {
                if (!isset($originatorOrgs[$archive->originatorOrgRegNumber])) {
                    $originatorOrg = $organizationController->getOrgByRegNumber($archive->originatorOrgRegNumber);
                    $originatorOrgs[$archive->originatorOrgRegNumber] = $originatorOrg;
                } else {
                    $originatorOrg = $originatorOrgs[$archive->originatorOrgRegNumber];
                }

Alexis Ragot's avatar
Alexis Ragot committed
799
                $archive->originatorOwnerOrgId = $originatorOrg->ownerOrgId;
Alexis Ragot's avatar
Alexis Ragot committed
800

Alexandre Morin's avatar
Alexandre Morin committed
801
                if (!empty($archive->archiveUnitProfile)) {
Alexis Ragot's avatar
Alexis Ragot committed
802
                    $this->archiveController->completeArchivalProfileCodes($archive);
Alexandre Morin's avatar
Alexandre Morin committed
803
804
805
                }

                if (!empty($archive->accessRuleCode)) {
Alexis Ragot's avatar
Alexis Ragot committed
806
                    $this->archiveController->completeAccessRule($archive);
Alexandre Morin's avatar
Alexandre Morin committed
807
808
                }

Alexandre Morin's avatar
Alexandre Morin committed
809
                if (!empty($archive->retentionRuleCode) || (!empty($archive->retentionDuration) && !empty($archive->retentionStartDate))) {
Alexis Ragot's avatar
Alexis Ragot committed
810
                    $this->archiveController->completeRetentionRule($archive);
Alexandre Morin's avatar
Alexandre Morin committed
811
812
813
                }

                if (!empty($archive->serviceLevelReference)) {
Alexis Ragot's avatar
Alexis Ragot committed
814
                    $this->archiveController->completeServiceLevel($archive);
Alexandre Morin's avatar
Alexandre Morin committed
815
816
                }

817
                $this->archiveController->convertArchive($archive);
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
                $this->archiveController->deposit($archive, $filePlanPosition);

                $unitIdentifier = \laabs::newInstance("medona/unitIdentifier");
                $unitIdentifier->messageId = $message->messageId;
                $unitIdentifier->objectId = (string) $archive->archiveId;
                $unitIdentifier->objectClass = "recordsManagement/archive";

                $this->sdoFactory->create($unitIdentifier);
                $message->unitIdentifier[] = $unitIdentifier;
            }

            //add archives relationships
            if (isset($archiveRelationships)) {
                foreach ($archiveRelationships as $relationship) {
                    $this->archiveRelationshipController->create($relationship);
                }
            }

            $message->status = "processed";
            $this->sdoFactory->update($message);
        } catch (\Exception $e) {
            if ($transactionControl) {
                $this->sdoFactory->rollback();
            }

            $message->status = "error";
844
            $operationResult = false;
845
846
            $this->sdoFactory->update($message);

847
848
849
850
851
852
853
854
            $this->lifeCycleJournalController->logEvent(
                'medona/processing',
                'medona/message',
                $message->messageId,
                $message,
                false
            );

855
856
857
858
859
860
861
            throw $e;
        }

        if ($transactionControl) {
            $this->sdoFactory->commit();
        }

862
863
864
865
866
867
868
869
        $this->lifeCycleJournalController->logEvent(
            'medona/processing',
            'medona/message',
            $message->messageId,
            $message,
            true
        );

870
871
        $archiveTransferReplyController = \laabs::newController('medona/ArchiveTransferReply');

872
        $replyMessage = $archiveTransferReplyController->send($message, "000");
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914

        return (string) $replyMessage->messageId;
    }

    /**
     * Accept a message
     * @param string $messageId The message identifier
     * @param string $comment   1 comment
     */
    public function accept($messageId, $comment = null)
    {
        $this->changeStatus($messageId, "accepted", $comment);

        $message = $this->sdoFactory->read('medona/message', $messageId);
        if (isset($message->archivalAgreementReference)) {
            $archivalAgreement = $this->sdoFactory->read('medona/archivalAgreement', array("reference" => $message->archivalAgreementReference));

            if ($archivalAgreement->processSmallArchive && $message->size <= $this->autoProcessSize) {
                $this->process($messageId);
            }
        }

        $message = $this->sdoFactory->read('medona/message', array('messageId' => $messageId));

        $this->lifeCycleJournalController->logEvent(
            'medona/acceptance',
            'medona/message',
            $message->messageId,
            $message,
            true
        );
    }

    /**
     * Reject a message
     * @param string $messageId The message identifier
     * @param string $comment   a comment
     */
    public function reject($messageId, $comment = null)
    {
        $this->changeStatus($messageId, "rejected", $comment);
        $archiveTransferReplyController = \laabs::newController('medona/ArchiveTransferReply');
915
        $archiveTransferReplyController->send($messageId, "rejected", $comment);
916
917
918
919
920
921
922
923
924
925
926
927

        $message = $this->sdoFactory->read('medona/message', array('messageId' => $messageId));

        $this->lifeCycleJournalController->logEvent(
            'medona/rejection',
            'medona/message',
            $message->messageId,
            $message,
            true
        );
    }
}