ArchiveTransfer.php 36.2 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
            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
79
                throw \laabs::newException('medona/invalidMessageException', "Invalid message", 400);
80
81
82
83
84
85
86
87
            }

            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
88
                throw \laabs::newException('medona/invalidMessageException', "Invalid message", 400);
89
90
91
92
93
            }

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

95
96
97
98
99
100
101
102
103
104
105
106
107
108
            $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
109
110
111
            if ($e->getCode() != 0) {
                $exception = \laabs::newException('medona/invalidMessageException', "Invalid message", $e->getCode());
            } else {
112
                $exception = \laabs::newException('medona/invalidMessageException', "Invalid message", 400);
Alexis Ragot's avatar
Alexis Ragot committed
113
            }
Alexis Ragot's avatar
Alexis Ragot committed
114

115
            if (isset($e->errors) && is_array($e->errors)) {
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
                $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
        );

132
133
134
135
136
        $acknowledgementController = \laabs::newController('medona/Acknowledgement');
        $acknowledgement = $acknowledgementController->send($message);
        $acknowledgement->receivedMessageId = $message->messageId;

        return $acknowledgement;
137
138
    }

139
140
141
142
    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
143
            $data = stream_get_contents($messageFile);
144
145
146
        } elseif (preg_match('%^[a-zA-Z0-9/+]*={0,2}$%', $messageFile)) {
            $data = base64_decode($messageFile);  
        } elseif (is_file($messageFile)) {
147
148
149
            if (empty($filename)) {
                $filename = basename($messageFile);
            }
150
            $data = file_get_contents($messageFile);
151
152
        } else {
            $data = $messageFile;
153
154
155
        }

        $mediatype = $this->finfo->buffer($data);
156
157
158
159
160
161
162
163
164
        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);
165
166
167
        }
    }

168
    protected function receiveZip($message, $data, $attachments, $filename)
169
170
171
172
173
    {
        $messageDir = $this->messageDirectory.DIRECTORY_SEPARATOR.(string) $message->messageId;

        $zipfile = \laabs\tempnam();
        file_put_contents($zipfile, $data);
174
175
176
177
        $tmpdir = \laabs::getTmpDir().DIRECTORY_SEPARATOR.$message->messageId;
        if (!is_dir($tmpdir)) {
            mkdir($tmpdir, 0777, true);
        }
178
179
180
181
182

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

        $zipContents = scandir($tmpdir);
183

184
185
186
        if (!isset($zipContents[2])) {
            throw \laabs::newException('medona/invalidMessageException', "Invalid message", 400);
        }
187
        
188
189
190
191
        $message->attachments = [];
        
        if (is_dir($tmpdir.DIRECTORY_SEPARATOR.$zipContents[2])) {
            $zipFolder = $tmpdir.DIRECTORY_SEPARATOR.$zipContents[2];
192
193
194
195
196
        } else {
            $zipFolder = $tmpdir;
        }
        
        $messagePathinfo = pathinfo($filename, PATHINFO_FILENAME);
197

198
199
200
201
202
203
204
205
        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;
206
207
208
                }
            }
        }
209
210

        rmdir($zipFolder);
211
212
213
214
215
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
    }

    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;
250
251
252
253
254
255
256
257
258
259
260
261
262
            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);
263
            }
264
265
            
            $message->schema = $schema;
266
267
268
269
270
        } else {
            $message->schema = 'recordsManagement';
        }
    }

Cyril Vazquez's avatar
Merge    
Cyril Vazquez committed
271
    protected function receiveXmlFile($message, $messageFile, $attachments = array())
272
273
    {
        $messageDir = $this->messageDirectory.DIRECTORY_SEPARATOR.(string) $message->messageId;
Cyril Vazquez's avatar
Merge    
Cyril Vazquez committed
274
275
276
        if (!is_dir($messageDir)) {
            mkdir($messageDir, 0777, true);
        }
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

        // 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
304
305
306
        if (!is_dir($messageDir)) {
            mkdir($messageDir, 0777, true);
        }
307
308
309
310
311
312
313
314
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

        // 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
348
349
     * @param mixed  $messageId         The message identifier
     * @param object $archivalAgreement The archival agreement
350
351
352
     *
     * @return boolean
     */
Cyril Vazquez's avatar
Merge    
Cyril Vazquez committed
353
    public function validate($messageId, $archivalAgreement = null)
354
355
    {
        $this->errors = array();
356
        $this->replyCode = null;
357
358
359
360
361
362

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

        if ($message->status == "error") {
            $this->sendError('104', "The message is in error status");
363
            $exception = \laabs::newException('medona/invalidMessageException', "Invalid message", 400);
364
365
366
367
368
369
            $exception->errors = $this->errors;

            throw $exception;
        }

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

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

Cyril Vazquez's avatar
Merge    
Cyril Vazquez committed
375
376
            if ($archiveTransferController->replyCode) {
                $this->replyCode = $archiveTransferController->replyCode;
377
378
            }

Cyril Vazquez's avatar
Merge    
Cyril Vazquez committed
379
380
381
            $this->errors = array_merge($this->errors, $archiveTransferController->errors);
            $this->infos = array_merge($this->infos, $archiveTransferController->infos);
        
382
383
384
385
        } catch (\Exception $exception) {
            $this->errors[] = new \core\Error($exception->getMessage());
            $this->sendValidationError($message);

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

            throw $exception;
        }
391

392
393
394
395
        // Non blocking errors
        if (count($this->errors) > 0) {
            $this->sendValidationError($message);

396
            $exception = \laabs::newException('medona/invalidMessageException', "Invalid message", 400);
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
            $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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
    /**
     * 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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
    /**
     * 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
463
            $this->validateMessageHeaders($message);
464

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

Cyril Vazquez's avatar
Merge    
Cyril Vazquez committed
468
469
            $this->errors = array_merge($this->errors, $archiveTransferController->errors);
            $this->infos = array_merge($this->infos, $archiveTransferController->infos);
Cyril Vazquez's avatar
Cyril Vazquez committed
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491

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

492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
    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.");

526
            throw \laabs::newException('medona/invalidMessageException', "Invalid message", 400);
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
        }

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

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
562
563
        }

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

564
            throw \laabs::newException('medona/invalidMessageException', "Invalid message", 400);
565
566
567
568
569
570
571
572
573
574
575
        }

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

576
577
578
579
        if ($message->schema == 'medona') {
            if (empty($this->currentArchivalAgreement->originatorOrgIds)) {
                $this->sendError("300", "Il n'y a pas de service producteur.");
            } else {
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
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
                $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.");
        }

623
624
625
626
        $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"));
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
670
671
672
673
674
675
676
677
678
679
680
681
        $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;
            }
        }

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

685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
        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
704
        $this->changeStatus((string) $message->messageId, "processing");
705
706
707
708
709
710

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

        try {
Cyril Vazquez's avatar
Merge    
Cyril Vazquez committed
711
712
            $archiveTransferController = \laabs::newController($message->schema.'/ArchiveTransfer');
            list($archives, $archiveRelationships) = $archiveTransferController->process($message);
713
714
715

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

719
720
721
722
723
724
725
726
            $this->lifeCycleJournalController->logEvent(
                'medona/processing',
                'medona/message',
                $message->messageId,
                $message,
                false
            );

727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
            throw $e;
        }

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

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

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

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

742
743
            $filePlanPosition = $this->archiveController->resolveStoragePath(get_object_vars($message));

744
745
746
747
748
749
750
751
            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
752
                $archive->originatorOwnerOrgId = $originatorOrg->ownerOrgId;
Alexis Ragot's avatar
Alexis Ragot committed
753

Alexandre Morin's avatar
Alexandre Morin committed
754
                if (!empty($archive->archiveUnitProfile)) {
Alexis Ragot's avatar
Alexis Ragot committed
755
                    $this->archiveController->completeArchivalProfileCodes($archive);
Alexandre Morin's avatar
Alexandre Morin committed
756
757
758
                }

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

Alexandre Morin's avatar
Alexandre Morin committed
762
                if (!empty($archive->retentionRuleCode) || (!empty($archive->retentionDuration) && !empty($archive->retentionStartDate))) {
Alexis Ragot's avatar
Alexis Ragot committed
763
                    $this->archiveController->completeRetentionRule($archive);
Alexandre Morin's avatar
Alexandre Morin committed
764
765
766
                }

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

770
                $this->archiveController->convertArchive($archive);
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
                $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";
797
            $operationResult = false;
798
799
            $this->sdoFactory->update($message);

800
801
802
803
804
805
806
807
            $this->lifeCycleJournalController->logEvent(
                'medona/processing',
                'medona/message',
                $message->messageId,
                $message,
                false
            );

808
809
810
811
812
813
814
            throw $e;
        }

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

815
816
817
818
819
820
821
822
        $this->lifeCycleJournalController->logEvent(
            'medona/processing',
            'medona/message',
            $message->messageId,
            $message,
            true
        );

823
824
        $archiveTransferReplyController = \laabs::newController('medona/ArchiveTransferReply');

825
        $replyMessage = $archiveTransferReplyController->send($message, "000");
826
827
828
829

        return (string) $replyMessage->messageId;
    }

830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
        /**
     * 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";
        $queryParts[] = "status=['sent', 'received','accepted']";

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

    /**
     * Get transfer history
Alexandre Morin's avatar
Alexandre Morin committed
871
872
873
874
875
876
877
878
879
     *
     * @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
880
881
882
     *
     * @return array Array of medona/message object
     */
Alexandre Morin's avatar
Alexandre Morin committed
883
    public function history($reference = null, $archiver = null, $originator = null, $depositor = null, $archivalAgreement = null, $fromDate = null, $toDate = null, $status = null)
884
    {
Alexandre Morin's avatar
Alexandre Morin committed
885
        return $this->search("ArchiveTransfer", $reference, $archiver, $originator, $depositor, $archivalAgreement, $fromDate, $toDate, $status, true);
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
915
916
917
918
919
920
921
922
923
924
925
    /**
     * 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');
926
        $archiveTransferReplyController->send($messageId, "rejected", $comment);
927
928
929
930
931
932
933
934
935
936
937

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

        $this->lifeCycleJournalController->logEvent(
            'medona/rejection',
            'medona/message',
            $message->messageId,
            $message,
            true
        );
    }
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962


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