ArchiveTransfer.php 37.3 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
{
    protected $archiveParser;

    protected $droid;

    protected $jhove;

    /**
     * Receive message with all contents embedded
     * @param string $messageFile The message binary contents OR a filename
Cyril Vazquez's avatar
Merge    
Cyril Vazquez committed
41
     * @param array  $attachments  An array of attachment binary data
Prosper De Laure's avatar
Prosper De Laure committed
42
     * @param string $filename    The message file name
43
44
45
46
47
     *
     * @return medona/message
     *
     * @todo Remove files from sas when error on reception
     */
Cyril Vazquez's avatar
Merge    
Cyril Vazquez committed
48
    public function receive($messageFile, $attachments = array(), $schema = false, $filename = false)
49
50
51
52
53
54
    {
        $messageId = \laabs::newId();
        $message = \laabs::newInstance('medona/message');
        $message->messageId = $messageId;
        $message->type = "ArchiveTransfer";
        $message->receptionDate = \laabs::newTimestamp();
55
        $message->schema = $schema;
56
        $message->isIncoming = true;
Prosper De Laure's avatar
Prosper De Laure committed
57

58
59
60
61
62
        $messageDir = $this->messageDirectory.DIRECTORY_SEPARATOR.(string) $message->messageId;
        if (!is_dir($messageDir)) {
            mkdir($messageDir, 0777, true);
        }

63
        $this->receivePackage($message, $messageFile, $attachments, $filename);
64

Cyril Vazquez's avatar
merge    
Cyril Vazquez committed
65
        if (empty($schema)) {
66
            $this->detectSchema($message);
Cyril Vazquez's avatar
merge    
Cyril Vazquez committed
67
68
        }

Cyril Vazquez's avatar
Merge    
Cyril Vazquez committed
69
70
        try {
            $archiveTransferController = \laabs::newController($message->schema. '/ArchiveTransfer');
71
72
            $archiveTransferController->receive($message);

73
74
75
76
77
78
79
80
            if ($archiveTransferController->replyCode) {
                $this->replyCode = $archiveTransferController->replyCode;

                $this->errors = array_merge($this->errors, $archiveTransferController->errors);

                throw \laabs::newException('medona/invalidMessageException', "Invalid message", 400);
            }

81
82
83
84
85
86
            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
87
                throw \laabs::newException('medona/invalidMessageException', "Invalid message", 400);
88
89
90
91
92
93
94
95
            }

            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
96
                throw \laabs::newException('medona/invalidMessageException', "Invalid message", 400);
97
98
99
100
101
            }

            $message->status = "received";
            $this->create($message);
        } catch (\Exception $e) {
102

103
104
105
106
107
108
109
110
111
112
113
114
115
116
            $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
117
118
119
            if ($e->getCode() != 0) {
                $exception = \laabs::newException('medona/invalidMessageException', "Invalid message", $e->getCode());
            } else {
120
                $exception = \laabs::newException('medona/invalidMessageException', "Invalid message", 400);
Alexis Ragot's avatar
Alexis Ragot committed
121
            }
Alexis Ragot's avatar
Alexis Ragot committed
122

123
            if (isset($e->errors) && is_array($e->errors)) {
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
                $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
        );

140
141
142
143
144
        $acknowledgementController = \laabs::newController('medona/Acknowledgement');
        $acknowledgement = $acknowledgementController->send($message);
        $acknowledgement->receivedMessageId = $message->messageId;

        return $acknowledgement;
145
146
    }

147
148
149
150
    protected function receivePackage($message, $messageFile, $attachments, $filename)
    {
        // Valid URL file:// http:// data://
        if (filter_var($messageFile, FILTER_VALIDATE_URL)) { 
Alexis Ragot's avatar
Alexis Ragot committed
151
            $data = stream_get_contents($messageFile);
152
153
154
        } elseif (preg_match('%^[a-zA-Z0-9/+]*={0,2}$%', $messageFile)) {
            $data = base64_decode($messageFile);  
        } elseif (is_file($messageFile)) {
155
156
157
            if (empty($filename)) {
                $filename = basename($messageFile);
            }
158
            $data = file_get_contents($messageFile);
159
160
        } else {
            $data = $messageFile;
161
162
163
        }

        $mediatype = $this->finfo->buffer($data);
164
165
166
167
168
169
170
171
172
        switch ($mediatype) {
            case 'application/zip':
            case 'application/octet-stream':
            case 'application/x-7z-compressed' : 
                $this->receiveZip($message, $data, $attachments, $filename);
                break;

            default:
                $this->receiveFiles($message, $data, $attachments, $filename);
173
174
175
        }
    }

176
    protected function receiveZip($message, $data, $attachments, $filename)
177
178
179
180
181
    {
        $messageDir = $this->messageDirectory.DIRECTORY_SEPARATOR.(string) $message->messageId;

        $zipfile = \laabs\tempnam();
        file_put_contents($zipfile, $data);
182
183
184
185
        $tmpdir = \laabs::getTmpDir().DIRECTORY_SEPARATOR.$message->messageId;
        if (!is_dir($tmpdir)) {
            mkdir($tmpdir, 0777, true);
        }
186
187
188
189
190

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

        $zipContents = scandir($tmpdir);
191

192
193
194
        if (!isset($zipContents[2])) {
            throw \laabs::newException('medona/invalidMessageException', "Invalid message", 400);
        }
195
        
196
197
198
199
        $message->attachments = [];
        
        if (is_dir($tmpdir.DIRECTORY_SEPARATOR.$zipContents[2])) {
            $zipFolder = $tmpdir.DIRECTORY_SEPARATOR.$zipContents[2];
200
201
202
203
204
        } else {
            $zipFolder = $tmpdir;
        }
        
        $messagePathinfo = pathinfo($filename, PATHINFO_FILENAME);
205

206
207
208
209
210
211
212
213
        foreach (scandir($zipFolder) as $file) {
            if ($file != "." && $file != "..") {
                rename($zipFolder.DIRECTORY_SEPARATOR.$file, $messageDir.DIRECTORY_SEPARATOR.$file);

                if (pathinfo($file, PATHINFO_FILENAME) == pathinfo($filename, PATHINFO_FILENAME)) {
                    $message->path = $messageDir.DIRECTORY_SEPARATOR.$file;
                } else {
                    $message->attachments[] = $file;
214
215
216
                }
            }
        }
217
218

        rmdir($zipFolder);
219
220
221
222
223
224
225
    }

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

        if (!$filename) {
226
            $filename = (string) $message->messageId . '.xml';
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
        }

        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;
258
259
260
261
262
263
264
265
266
267
268
269
270
            foreach ($this->packageSchemas as $name => $info) {
                if (isset($info->xmlNamespace) && $info->xmlNamespace == $messageNamespace) {
                    $schema = $name;
                    break;
                }
            }

            if (!isset($schema)) {
                $schema = \laabs::resolveXmlNamespace($messageNamespace);
            }

            if (!isset($schema)) {
                throw \laabs::newException('medona/invalidMessageException', "Unknown message schema'.$messageNamespace", 400);
271
            }
272
273
            
            $message->schema = $schema;
274
275
276
277
278
        } else {
            $message->schema = 'recordsManagement';
        }
    }

Cyril Vazquez's avatar
Merge    
Cyril Vazquez committed
279
    protected function receiveXmlFile($message, $messageFile, $attachments = array())
280
281
    {
        $messageDir = $this->messageDirectory.DIRECTORY_SEPARATOR.(string) $message->messageId;
Cyril Vazquez's avatar
Merge    
Cyril Vazquez committed
282
283
284
        if (!is_dir($messageDir)) {
            mkdir($messageDir, 0777, true);
        }
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

        // 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
312
313
314
        if (!is_dir($messageDir)) {
            mkdir($messageDir, 0777, true);
        }
315
316
317
318
319
320
321
322
323
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
351
352
353
354
355

        // 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
356
357
     * @param mixed  $messageId         The message identifier
     * @param object $archivalAgreement The archival agreement
358
359
360
     *
     * @return boolean
     */
Cyril Vazquez's avatar
Merge    
Cyril Vazquez committed
361
    public function validate($messageId, $archivalAgreement = null)
362
363
    {
        $this->errors = array();
364
        $this->replyCode = null;
365
366
367
368
369
370

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

        if ($message->status == "error") {
            $this->sendError('104', "The message is in error status");
371
            $exception = \laabs::newException('medona/invalidMessageException', "Invalid message", 400);
372
373
374
375
376
377
            $exception->errors = $this->errors;

            throw $exception;
        }

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

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

Cyril Vazquez's avatar
Merge    
Cyril Vazquez committed
383
384
            if ($archiveTransferController->replyCode) {
                $this->replyCode = $archiveTransferController->replyCode;
385
386
            }

Cyril Vazquez's avatar
Merge    
Cyril Vazquez committed
387
388
389
            $this->errors = array_merge($this->errors, $archiveTransferController->errors);
            $this->infos = array_merge($this->infos, $archiveTransferController->infos);
        
390
391
392
393
        } catch (\Exception $exception) {
            $this->errors[] = new \core\Error($exception->getMessage());
            $this->sendValidationError($message);

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

            throw $exception;
        }
399

400
401
        // Non blocking errors
        if (count($this->errors) > 0) {
402
403
404
405
406
            if ($res = -1) {
                $this->sendValidationError($message, false,'toBeModified');
            } else {
                $this->sendValidationError($message);
            }
407

408
            $exception = \laabs::newException('medona/invalidMessageException', "Invalid message", 400);
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
            $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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
    /**
     * 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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
    /**
     * 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
475
            $this->validateMessageHeaders($message);
476

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

Cyril Vazquez's avatar
Merge    
Cyril Vazquez committed
480
481
            $this->errors = array_merge($this->errors, $archiveTransferController->errors);
            $this->infos = array_merge($this->infos, $archiveTransferController->infos);
Cyril Vazquez's avatar
Cyril Vazquez committed
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503

        } 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;
    }

504
    protected function sendValidationError($message, $sendReply = true, $status = null)
505
    {
506
507
508
509
510
        if ($status) {
            $message->status = $status;
        } else {
            $message->status = "invalid";
        }
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
        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);

531
532
533
534
        if ($sendReply) {
            $archiveTransferReplyController = \laabs::newController('medona/ArchiveTransferReply');
            $archiveTransferReplyController->send($message, $this->replyCode);
        }
535
536
537
538
539
540
541
542
543
    }

    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.");

544
            throw \laabs::newException('medona/invalidMessageException', "Invalid message", 400);
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
        }

        $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.");

562
            throw \laabs::newException('medona/invalidMessageException', "Invalid message", 400);
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
        }

        $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.");

582
            throw \laabs::newException('medona/invalidMessageException', "Invalid message", 400);
583
584
585
586
587
588
589
590
591
592
593
        }

        // 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.");
        }

594
595
596
597
        if ($message->schema == 'medona') {
            if (empty($this->currentArchivalAgreement->originatorOrgIds)) {
                $this->sendError("300", "Il n'y a pas de service producteur.");
            } else {
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
                $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.");
        }

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

645
646
647
648
649
        if ($this->currentArchivalAgreement->maxSizeDay > 0) {
            $res = $this->sdoFactory->summarise("medona/message", "archivalAgreementReference", "size", ["receptionDate > :today and archivalAgreementReference='".$this->currentArchivalAgreement->reference."'", ["today" => $today]]);
            if (count($res) && ($res[$this->currentArchivalAgreement->reference]+$message->size) > ($this->currentArchivalAgreement->maxSizeDay*1048576)) {
                $this->sendError("301", "La taille maximale par jour de l'accord de versement est dépassée.");
            }
650
651
        }

652
653
654
655
656
657
        if ($this->currentArchivalAgreement->maxSizeWeek > 0) {
            $aWeekAgo = $today->shift(new \core\Type\Duration("-P7D"));
            $res = $this->sdoFactory->summarise("medona/message", "archivalAgreementReference", "size", ["receptionDate > :aWeekAgo and archivalAgreementReference='".$this->currentArchivalAgreement->reference."'", ["aWeekAgo" => $aWeekAgo]]);
            if (count($res) && ($res[$this->currentArchivalAgreement->reference]+$message->size) > ($this->currentArchivalAgreement->maxSizeWeek*1048576)) {
                $this->sendError("301", "La taille maximale par semaine de l'accord de versement est dépassée.");
            }
658
659
        }

660
661
662
663
664
665
        if ($this->currentArchivalAgreement->maxSizeMonth > 0) {
            $aMonthAgo = $today->shift(new \core\Type\Duration("-P1M"));
            $res = $this->sdoFactory->summarise("medona/message", "archivalAgreementReference", "size", ["receptionDate > :aMonthAgo and archivalAgreementReference='".$this->currentArchivalAgreement->reference."'", ["aMonthAgo" => $aMonthAgo]]);
            if (count($res) && ($res[$this->currentArchivalAgreement->reference]+$message->size) > ($this->currentArchivalAgreement->maxSizeMonth*1048576)) {
                $this->sendError("301", "La taille maximale par mois de l'accord de versement est dépassée.");
            }
666
667
        }

668
669
670
671
672
673
        if ($this->currentArchivalAgreement->maxSizeYear > 0) {
            $aYearAgo = $today->shift(new \core\Type\Duration("-P1Y"));
            $res = $this->sdoFactory->summarise("medona/message", "archivalAgreementReference", "size", ["receptionDate > :aYearAgo and archivalAgreementReference='".$this->currentArchivalAgreement->reference."'", ["aYearAgo" => $aYearAgo]]);
            if (count($res) && ($res[$this->currentArchivalAgreement->reference]+$message->size) > ($this->currentArchivalAgreement->maxSizeYear*1048576)) {
                $this->sendError("301", "La taille maximale par année de l'accord de versement est dépassée.");
            }
674
675
        }

676
677
678
679
680
681
        if (isset($this->currentArchivalAgreement->beginDate) && $this->currentArchivalAgreement->maxSizeAgreement > 0) {
            $archivalAgreementBeginDate = $this->currentArchivalAgreement->beginDate;
            $res = $this->sdoFactory->summarise("medona/message", "archivalAgreementReference", "size", ["receptionDate > :archivalAgreementBeginDate and archivalAgreementReference='".$this->currentArchivalAgreement->reference."'", ["archivalAgreementBeginDate" => $archivalAgreementBeginDate]]);
            if (count($res) && ($res[$this->currentArchivalAgreement->reference]+$message->size) > ($this->currentArchivalAgreement->maxSizeAgreement*1048576)) {
                $this->sendError("301", "La taille maximale de l'accord de versement est dépassée.");
            }
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
        }

        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;
            }
        }

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

711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
        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
730
        $this->changeStatus((string) $message->messageId, "processing");
731
732
733
734
735
736

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

        try {
Cyril Vazquez's avatar
Merge    
Cyril Vazquez committed
737
738
            $archiveTransferController = \laabs::newController($message->schema.'/ArchiveTransfer');
            list($archives, $archiveRelationships) = $archiveTransferController->process($message);
739
740
741

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

745
746
747
748
749
750
751
752
            $this->lifeCycleJournalController->logEvent(
                'medona/processing',
                'medona/message',
                $message->messageId,
                $message,
                false
            );

753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
            throw $e;
        }

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

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

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

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

768
769
            $filePlanPosition = $this->archiveController->resolveStoragePath(get_object_vars($message));

770
771
772
773
774
775
776
777
            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
778
                $archive->originatorOwnerOrgId = $originatorOrg->ownerOrgId;
Alexis Ragot's avatar
Alexis Ragot committed
779

Alexandre Morin's avatar
Alexandre Morin committed
780
                if (!empty($archive->archiveUnitProfile)) {
Alexis Ragot's avatar
Alexis Ragot committed
781
                    $this->archiveController->completeArchivalProfileCodes($archive);
Alexandre Morin's avatar
Alexandre Morin committed
782
783
784
                }

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

Alexandre Morin's avatar
Alexandre Morin committed
788
                if (!empty($archive->retentionRuleCode) || (!empty($archive->retentionDuration) && !empty($archive->retentionStartDate))) {
Alexis Ragot's avatar
Alexis Ragot committed
789
                    $this->archiveController->completeRetentionRule($archive);
Alexandre Morin's avatar
Alexandre Morin committed
790
791
792
                }

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

796
                $this->archiveController->convertArchive($archive);
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
                $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";
823
            $operationResult = false;
824
825
            $this->sdoFactory->update($message);

826
827
828
829
830
831
832
833
            $this->lifeCycleJournalController->logEvent(
                'medona/processing',
                'medona/message',
                $message->messageId,
                $message,
                false
            );

834
835
836
837
838
839
840
            throw $e;
        }

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

841
842
843
844
845
846
847
848
        $this->lifeCycleJournalController->logEvent(
            'medona/processing',
            'medona/message',
            $message->messageId,
            $message,
            true
        );

849
850
        $archiveTransferReplyController = \laabs::newController('medona/ArchiveTransferReply');

851
        $replyMessage = $archiveTransferReplyController->send($message, "000");
852
853
854
855

        return (string) $replyMessage->messageId;
    }

856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
        /**
     * 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";
        $queryParts[] = "isIncoming=true";
        $queryParts[] = "status != 'processed' AND status != 'error' AND status != 'invalid' AND status !='draft' AND status !='template' AND status !='rejected' AND status !='acknowledge'" ;

        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();
        $accountToken = \laabs::getToken("AUTH");

        $queryParts = [];
        $queryParts[] = "(accountId= '$accountToken->accountId' OR senderOrgRegNumber=$registrationNumber)";
        $queryParts[] = "type='ArchiveTransfer'";
        $queryParts[] = "active=true";
        $queryParts[] = "isIncoming=true";
890
        $queryParts[] = "status=['sent', 'valid', 'received','accepted']";
891
892
893
894
895
896

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

    /**
     * Get transfer history
Alexandre Morin's avatar
Alexandre Morin committed
897
898
899
900
901
902
903
904
905
     *
     * @param string $reference         Reference
     * @param string $archiver          Archiver
     * @param string $originator        Originator
     * @param string $depositor         Depositor
     * @param string $archivalAgreement Archival agreement
     * @param date   $fromDate          From date
     * @param date   $toDate            To date
     * @param string $status            Status
906
907
908
     *
     * @return array Array of medona/message object
     */
Alexandre Morin's avatar
Alexandre Morin committed
909
    public function history($reference = null, $archiver = null, $originator = null, $depositor = null, $archivalAgreement = null, $fromDate = null, $toDate = null, $status = null)
910
    {
Alexandre Morin's avatar
Alexandre Morin committed
911
        return $this->search("ArchiveTransfer", $reference, $archiver, $originator, $depositor, $archivalAgreement, $fromDate, $toDate, $status, true);
912
913
    }

914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
    /**
     * 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');
952
        $archiveTransferReplyController->send($messageId, "rejected", $comment);
953
954
955
956
957
958
959
960
961
962
963

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

        $this->lifeCycleJournalController->logEvent(
            'medona/rejection',
            'medona/message',
            $message->messageId,
            $message,
            true
        );
    }
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988


    /**
     * 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;
    }
989
}