abstractMessage.php 44.2 KB
Newer Older
Alexandre Morin's avatar
Alexandre Morin committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php

/*
 * Copyright (C) 2015 Maarch
 *
 * This file is part of bundle seda.
 *
 * Bundle seda 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 seda 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 seda.  If not, see <http://www.gnu.org/licenses/>.
 */
namespace ext\archivesPubliques\bundle\seda2\Controller;
22

23
use core\Exception;
Alexandre Morin's avatar
Alexandre Morin committed
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60

/**
 * Class abstractMessage
 *
 * @package Seda2
 *
 */
abstract class abstractMessage
{
    protected $archivalAgreements = array();

    protected $currentArchivalAgreement;

    protected $archives;

    protected $digitalResources;

    protected $archiveRelationships;

    protected $resRelationships;

    protected $message;

    protected $messageDirectory;

    protected $profilesDirectory;

    protected $orgController;

    protected $sdoFactory;

    protected $xml;

    protected $xPath;

    protected $jhove;

61

Alexandre Morin's avatar
Alexandre Morin committed
62
63
64
65
66
67
68
69
70
71
72
73
74
    /**
     * Constructor
     * @param object $sdoFactory
     */
    public function __construct(\dependency\sdo\Factory $sdoFactory)
    {
        $this->messageDirectory = \laabs::configuration('medona')['messageDirectory'];
        $this->profilesDirectory = \laabs::configuration('recordsManagement')['profilesDirectory'];

        $this->sdoFactory = $sdoFactory;

        $this->orgController = \laabs::newController('organization/organization');
        $this->archiveController = \laabs::newController('recordsManagement/archive');
75
        $this->digitalResourceController = \laabs::newController('digitalResource/digitalResource');
Cyril Vazquez's avatar
Cyril Vazquez committed
76
        $this->lifeCycleJournalController = \laabs::newController('lifeCycle/journal');
77
        $this->archivalProfileController = \laabs::newController("recordsManagement/archivalProfile");
78
        $this->retentionRuleController = \laabs::newController("recordsManagement/retentionRule");
79
        $this->accessRuleController = \laabs::newController("recordsManagement/accessRule");
80
        $this->contentController = \laabs::newController("archivesPubliques/content");
81
        $this->serviceLevelController = \laabs::newController('recordsManagement/serviceLevel');
Alexandre Morin's avatar
Alexandre Morin committed
82
83
84
85
    }

    /**
     * Load a message
86
     * @param seda2/message $message The message object
Alexandre Morin's avatar
Alexandre Morin committed
87
88
89
90
91
     */
    public function loadMessage($message)
    {
        $this->message = $message;

Cyril Vazquez's avatar
Cyril Vazquez committed
92
93
        $message->xml = \laabs::newService('dependency/xml/Document');

94
95
        $message->xml->resolveExternals = false;

Cyril Vazquez's avatar
Cyril Vazquez committed
96
97
        $message->xml->load($message->path);

98
        $message->xml->XPath = \laabs::newService('dependency/xml/XPath', $message->xml);
Cyril Vazquez's avatar
Cyril Vazquez committed
99

100
        $message->xml->XPath->registerNamespace('seda2', $message->xml->documentElement->namespaceURI);
Cyril Vazquez's avatar
Cyril Vazquez committed
101
    }
Alexandre Morin's avatar
Alexandre Morin committed
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122

    protected function useArchivalAgreement($archivalAgreementReference)
    {
        $archivalAgreementController = \laabs::newController('medona/archivalAgreement');

        if (!isset($this->archivalAgreements[$archivalAgreementReference])) {
            $this->currentArchivalAgreement = $archivalAgreementController->getByReference($archivalAgreementReference);

            $this->archivalAgreements[$archivalAgreementReference] = $this->currentArchivalAgreement;
        } else {
            $this->currentArchivalAgreement = $this->archivalAgreements[$archivalAgreementReference];
        }

        return $this->currentArchivalAgreement;
    }

    /**
     * Get an attacheent resource from a message
     * @param medona/message $message      The message
     * @param string         $attachmentId The attachment identifier
     *
123
     * @return digitalResource/digitalResource The resource
Alexandre Morin's avatar
Alexandre Morin committed
124
125
126
     */
    public function getAttachment($message, $attachmentId)
    {
Cyril Vazquez's avatar
Cyril Vazquez committed
127
        $binaryDataObject = $this->getBinaryDataObjectById($attachmentId, $message);
Alexandre Morin's avatar
Alexandre Morin committed
128

Cyril Vazquez's avatar
Cyril Vazquez committed
129
130
        if (!$binaryDataObject) {
            throw \Laabs::newException('seda2/invalidMessageException', "Le document identifié par $attachmentId n'a pas été trouvé.");
Alexandre Morin's avatar
Alexandre Morin committed
131
132
        }

Cyril Vazquez's avatar
Cyril Vazquez committed
133
134
135
136
137
138
139
140
141
142
143
144
        if (isset($binaryDataObject->attachment)) {
            $attachment = $binaryDataObject->attachment;

            if (isset($attachment->filename)) {           // Non compliant with SEDA2 but...
                $uri = $attachment->filename;
            } elseif (isset($attachment->uri)) {                // Non compliant with SEDA2 but...
                $uri = $attachment->uri;
            }
        } elseif (isset($binaryDataObject->uri)) {
            $uri = $binaryDataObject->uri;
        } else {
            throw \Laabs::newException('seda2/invalidMessageException', "Le document identifié par $attachmentId n'a pas été trouvé.");
Alexandre Morin's avatar
Alexandre Morin committed
145
146
        }

Cyril Vazquez's avatar
Cyril Vazquez committed
147
148
149
150
151
152
        $messageDir = dirname($message->path);
        $filepath = $messageDir.DIRECTORY_SEPARATOR.$uri;
        $stream = fopen($filepath, 'r');

        $resource = $this->digitalResourceController->createFromStream($stream);

Alexandre Morin's avatar
Alexandre Morin committed
153
154
155
        return $resource;
    }

Cyril Vazquez's avatar
Cyril Vazquez committed
156
    protected function getBinaryDataObjectById($id, $message)
Alexandre Morin's avatar
Alexandre Morin committed
157
    {
158
        $binaryDataObjects = (array)$message->object->dataObjectPackage->binaryDataObject;
159
        foreach ($binaryDataObjects as $binaryDataObject) {
Cyril Vazquez's avatar
Cyril Vazquez committed
160
161
            if ($binaryDataObject->id == $id) {
                return $binaryDataObject;
Alexandre Morin's avatar
Alexandre Morin committed
162
163
164
165
            }
        }
    }

166
167
168
169
170
171
172
173
174
175
176
    protected function getBinaryDataObjectsByGroupId($id, $message)
    {
        $dataObjectGroups = (array)$message->object->dataObjectPackage->dataObjectGroup;
        foreach ($dataObjectGroups as $dataObjectGroup) {
            if ($dataObjectGroup->id != $id || !isset($dataObjectGroup->binaryDataObject)) {
                continue;
            }
            return $dataObjectGroup->binaryDataObject;
        }
    }

177
    /***********************************************************************************
178
    **
Alexandre Morin's avatar
Alexandre Morin committed
179
180
    **  SEND XML MESSAGES
    **
181
    ***********************************************************************************/
Alexandre Morin's avatar
Alexandre Morin committed
182
183
    protected function send($message)
    {
184
185
        $messageType = $message->type == "ArchiveRestitution" ? "ArchiveTransfer" : $message->type;
        $sedaMessage = \laabs::newInstance('seda2/'.$messageType);
Alexandre Morin's avatar
Alexandre Morin committed
186
187
188

        $message->object = $sedaMessage;

189
        $sedaMessage->date = $this->sendDate($message->date, true);
Alexandre Morin's avatar
Alexandre Morin committed
190

191
        if (isset($message->comment) && !empty($message->comment)) {
Alexandre Morin's avatar
Alexandre Morin committed
192
193
            $sedaMessage->comment = $this->sendComment($message->comment);
        }
Alexandre Morin's avatar
Alexandre Morin committed
194

195
196
        $sedaMessage->messageIdentifier =  \laabs::newInstance("seda2/ID", (string)$message->messageId);

197
198
        $message->size = 0;

199
200
        if (isset($message->archive[0]->archivalAgreementReference)) {
            $sedaMessage->archivalAgreement = \laabs::newInstance("seda2/ID", (string)$message->archive[0]->archivalAgreementReference);
201
        }
Alexandre Morin's avatar
Alexandre Morin committed
202
203
204
205

        return $sedaMessage;
    }

206
    protected function sendDescriptiveMetadata($identifiers)
207
    {
208
209
        $descriptiveMetadata = \laabs::newInstance("seda2/DescriptiveMetadata");
        $descriptiveMetadata->archiveUnit = [];
210

211
212
213
214
215
216
217
218
219
        $identifiersIds = [];
        foreach ($identifiers as $key => $identifier) {
            if (in_array((string) $identifier->messageId, $identifiersIds)) {
                unset($identifiers[$key]);
            } else {
                $identifiersIds[] = (string) $identifier->messageId;
            }
        }

220
        foreach ($identifiers as $identifier) {
221
            $descriptiveMetadata->archiveUnit[] = $this->sendArchiveUnit($identifier->objectId);
222
223
224
        }

        return $descriptiveMetadata;
225
226
    }

227
228
229
230
    protected function sendFormatIdentification($format)
    {
        $formatIdentification = \laabs::newInstance("seda2/FormatIdentification");

231
232
233
234
235
236
237
238
239
        if (isset($format->name)) {
            $formatIdentification->formatLitteral = $format->name;
        }
        if (isset($format->mimetypes[0])) {
            $formatIdentification->mimeType = $format->mimetypes[0];
        }
        if (isset($format->puid)) {
            $formatIdentification->formatId = $format->puid;
        }
240
241
242
243

        return $formatIdentification;
    }

244
    protected function sendFileInfo($fileName)
245
246
247
    {
        $fileInfo = \laabs::newInstance("seda2/FileInfo");

248
        $fileInfo->filename = $fileName;
249
250
251
252

        return $fileInfo;
    }

253
    protected function sendBinaryDataObject($message, $identifier, $withAttachment, $listChildren = true)
254
255
256
    {
        $binaryDataObject = [];

257
258
259
        $digitalResources = $this->digitalResourceController->getResourcesByArchiveId($identifier);
        foreach ($digitalResources as $digitalResource) {
            $binary = \laabs::newInstance("seda2/BinaryDataObject");
260

261
262
            $binary->id = $digitalResource->resId;
            $binary->dataObjectSystemId = $digitalResource->resId;
263
264
            if (isset($digitalResource->size)) {
                $binary->size = $digitalResource->size;
265
                $message->size += $binary->size;
266
267
268
269
            }
            if (isset($digitalResource->format)) {
                $binary->formatIdentification = $this->sendFormatIdentification($digitalResource->format);
            }
270

271
272
273
            if (isset($digitalResource->fileName)) {
                $binary->fileInfo = $this->sendFileInfo($digitalResource->fileName);
            }
274

275
            if ($withAttachment) {
276
                $binary->uri = "content/".$binary->fileInfo->filename;
277
                $binary->messageDigest = \laabs::newInstance("seda2/MessageDigest", $digitalResource->hash, $digitalResource->hashAlgorithm);
278
            }
279
280
281

            $binaryDataObject[] = $binary;
        }
282
283
284
        if ($listChildren) {
            $children = array_slice($this->archiveController->listChildrenArchiveId($identifier), 1);
            foreach ($children as $childArchiveId) {
285
                $binaryDataObject = array_merge($binaryDataObject, $this->sendBinaryDataObject($message, $childArchiveId, $withAttachment, false));
286
            }
287
288
289
290
291
        }

        return $binaryDataObject;
    }

292
    protected function sendDataObjectPackage($message, $withAttachment)
293
294
295
    {
        $dataObjectPackage = \laabs::newInstance('seda2/DataObjectPackage');

296
297
298
        $identifiers = (array)(isset($message->authorizationRequestContent->unitIdentifier) ? $message->authorizationRequestContent->unitIdentifier : $message->unitIdentifier);

        $dataObjectPackage->descriptiveMetadata = $this->sendDescriptiveMetadata($identifiers);
299

300
        $dataObjectPackage->managementMetadata = $this->sendManagementMetadata($message);
301

302
303
304
305
306
307
308
309
310
        $identifiersIds = [];
        foreach ($identifiers as $key => $identifier) {
            if (in_array((string) $identifier->messageId, $identifiersIds)) {
                unset($identifiers[$key]);
            } else {
                $identifiersIds[] = (string) $identifier->messageId;
            }
        }

311
312
313
314
        $dataObjectPackage->binaryDataObject = [];
        if (!empty($identifiers) && $withAttachment) {
            foreach ($identifiers as $identifier) {
                $dataObjectPackage->binaryDataObject = array_merge($dataObjectPackage->binaryDataObject, $this->sendBinaryDataObject($message, $identifier->objectId, $withAttachment));
315
            }
316
        }
317
318
319
320

        return $dataObjectPackage;
    }

321
322
323
    protected function sendManagementMetadata($message)
    {
        $managementMetadata = \laabs::newInstance("seda2/ManagementMetadata");
324
325
326

        // TODO Prendre les bonnes managementmetadata une fois déterminé
        /*if (isset($message->object->unitIdentifier[0]->value)) {
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
            $rmArchive = $this->archiveController->read($message->object->unitIdentifier[0]->value);

            if (isset($rmArchive->archivalProfileReference) && !empty($rmArchive->archivalProfileReference)) {
                $managementMetadata->archivalProfile = \laabs::newInstance('seda2/ID', (string) $rmArchive->archivalProfileReference);
            }

            if (isset($rmArchive->serviceLevelReference) && !empty($rmArchive->serviceLevelReference)) {
                $managementMetadata->serviceLevel = \laabs::newInstance('seda2/ID', (string) $rmArchive->serviceLevelReference);
            }

            if (isset($rmArchive->originatorOrgRegNumber) && !empty($rmArchive->originatorOrgRegNumber)) {
                $managementMetadata->originatingAgencyIdentifier = \laabs::newInstance('seda/ID', (string) $rmArchive->originatorOrgRegNumber);
            }

            if (isset($rmArchive->depositorOrgRegNumber) && !empty($rmArchive->depositorOrgRegNumber)) {
                $managementMetadata->submissionAgencyIdentifier = \laabs::newInstance('seda/ID', (string) $rmArchive->depositorOrgRegNumber);
            }
344
        }*/
345
346
347
348

        return $managementMetadata;
    }

Alexandre Morin's avatar
Alexandre Morin committed
349
350
351
352
353
    protected function sendComment($comments)
    {
        $res = [];

        foreach ($comments as $comment) {
354
355
356
            if (isset($comment->value)) {
                $comment = $comment->value;
            }
Alexandre Morin's avatar
Alexandre Morin committed
357
358
359
360
361
362
363
364
365
366
367
368
369
370
            $res[] = \laabs::newInstance('seda2/Comment', $comment, 'fr');
        }

        return $res;
    }

    protected function sendReplyCode($code)
    {
        $replyCode = \laabs::newInstance('seda2/Code', $code);

        $replyCode->name = $this->getReplyMessage($code);

        return $replyCode;
    }
Alexandre Morin's avatar
Alexandre Morin committed
371

Alexandre Morin's avatar
Alexandre Morin committed
372
373
374
375
376
377
378
379
380
381
382
383
384
    protected function sendError($code, $message = false)
    {
        if ($message) {
            array_push($this->errors, new \core\Error($message, null, $code));
        } else {
            array_push($this->errors, new \core\Error($this->getReplyMessage($code), null, $code));
        }

        if ($this->replyCode == null) {
            $this->replyCode = $code;
        }
    }

385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
    protected function sendXmlDigitalResources($identifier, $messageDir)
    {
        $digitalResources = $this->digitalResourceController->getResourcesByArchiveId($identifier);
        foreach ($digitalResources as $digitalResource) {
            if (!is_dir($messageDir)) {
                mkdir($messageDir, 0777, true);
            }
            if (!is_dir($messageDir."/content/")) {
                mkdir($messageDir."/content/", 0777, true);
            }
            $address = $digitalResource->address[0];
            copy($address->repository->repositoryUri . $address->path, $messageDir."/content/".$digitalResource->fileName);
        }
        $children = array_slice($this->archiveController->listChildrenArchiveId($identifier), 1);
        foreach ($children as $childArchiveId) {
            $this->sendXmlDigitalResources($childArchiveId, $messageDir);
        }
    }

Alexandre Morin's avatar
Alexandre Morin committed
404
405
    protected function sendXml($message, $withData)
    {
406
        $messageType = $message->type == "ArchiveRestitution" ? "ArchiveTransfer" : $message->type;
Alexandre Morin's avatar
Alexandre Morin committed
407
        $message->xml = \laabs::newService('dependency/xml/Document');
408
409
        $message->xml->loadResource('seda2/'.$messageType.'.xml');
        $message->xml->setSource($messageType, $message->object);
Alexandre Morin's avatar
Alexandre Morin committed
410
411
412
413
        $message->xml->merge();

        $message->xml->removeEmptyNodes();

414
415
416
417
        $messageDir = $this->messageDirectory.DIRECTORY_SEPARATOR.$message->messageId;

        if (!is_dir($messageDir)) {
            mkdir($messageDir, 0777, true);
Alexandre Morin's avatar
Alexandre Morin committed
418
419
        }

420
        $message->xml->loadXml($message->xml->saveXml());
421
        $message->path = $messageDir.DIRECTORY_SEPARATOR.$message->messageId.'.xml';
422

423
        $this->validateSchema($message);
424

425
426
        // Documents
        if ($withData) {
427
428
            $identifiers = (array)(isset($message->authorizationRequestContent->unitIdentifier) ? $message->authorizationRequestContent->unitIdentifier : $message->unitIdentifier);
            foreach ($identifiers as $identifier) {
429
                $this->sendXmlDigitalResources($identifier->objectId, $messageDir);
430
            }
Alexandre Morin's avatar
Alexandre Morin committed
431
432
        }

433
434
        $xmlContent = preg_replace(
            [
435
                "/<!--.*-->/",
436
437
438
439
440
441
                '/xmlns:default="fr:gouv:culture:archivesdefrance:seda:v2.1"/'
            ],
            "",
            $message->xml->saveXml()
        );

442
        file_put_contents($message->path, $xmlContent);
Alexandre Morin's avatar
Alexandre Morin committed
443
444
    }

445
446
447
448
449
450
451
452
453
    public function validateSchema($message)
    {
        // Conformité au schéma SEDA2
        $schemaUri = 'seda2'.LAABS_URI_SEPARATOR.'2.1'.LAABS_URI_SEPARATOR.'schema'.LAABS_URI_SEPARATOR.'seda-2.1-main.xsd';
        $router = new \core\Route\ResourceRouter($schemaUri);
        $schemaFile = $router->getResource()->getRealPath();

        libxml_use_internal_errors(true);
        $valid = $message->xml->schemaValidate($schemaFile);
Jerome Boucher's avatar
Jerome Boucher committed
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
479
480
481
        if ($valid == false) {
            $libXMLerrors = libxml_get_errors();
            $message = "";
            $errors = [];
            foreach ($libXMLerrors as $libXMLerror) {
                $message = " " . $libXMLerror->message;

                $errors[] = new \core\Error($libXMLerror->message, null, $libXMLerror->code, $libXMLerror->file, $libXMLerror->line);
            }

            if ($message) {
                $exception = \laabs::newException('seda2/invalidMessageException', 'Le bordereau ne respecte pas le formalisme du SEDA 2.1. ' . $message);
            } else {
                $exception = \laabs::newException('seda2/invalidMessageException', 'Le bordereau ne respecte pas le formalisme du SEDA 2.1.');
            }

            $exception->errors = $errors;

            libxml_clear_errors();
            libxml_use_internal_errors(false);

            throw $exception;
        }

        libxml_use_internal_errors(false);
    }

Alexandre Morin's avatar
Alexandre Morin committed
482
483
484
485
486
487
488
489
490
491
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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
    protected function getReplyMessage($code)
    {
        switch ((string) $code) {
            case "000":
                $name = "OK";
                break;
            case "001":
                $name = "OK (consulter les commentaires pour information)";
                break;
            case "002":
                $name = "OK (Demande aux autorités de contrôle effectuée)";
                break;

            case "101":
                $name = "Message mal formé.";
                break;
            case "102":
                $name = "Système momentanément indisponible.";
                break;

            case "200":
                $name = "Service producteur non reconnu.";
                break;
            case "201":
                $name = "Service d'archive non reconnu.";
                break;
            case "202":
                $name = "Service versant non reconnu.";
                break;
            case "203":
                $name = "Dépôt non conforme au profil de données.";
                break;
            case "204":
                $name = "Format de document non géré.";
                break;
            case "205":
                $name = "Format de document non conforme au format déclaré.";
                break;
            case "206":
                $name = "Signature du message invalide.";
                break;
            case "207":
                $name = "Empreinte(s) invalide(s).";
                break;
            case "208":
                $name = "Archive indisponible. Délai de communication non écoulé.";
                break;
            case "209":
                $name = "Archive absente (élimination, restitution, transfert)";
                break;
            case "210":
                $name = "Archive inconnue";
                break;
            case "211":
                $name = "Pièce attachée absente.";
                break;
            case "212":
                $name = "Dérogation refusée.";
                break;
541
            case "213":
542
                $name = "Le bordereau doit contenir au moins une archive";
543
                break;
Alexandre Morin's avatar
Alexandre Morin committed
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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590

            case "300":
                $name = "Convention invalide.";
                break;
            case "301":
                $name = "Dépôt non conforme à la convention. Quota des versements dépassé.";
                break;
            case "302":
                $name = "Dépôt non conforme à la convention. Identifiant du producteur non conforme.";
                break;
            case "303":
                $name = "Dépôt non conforme à la convention. Identifiant du service versant non conforme.";
                break;
            case "304":
                $name = "Dépôt non conforme à la convention. Identifiant du service d'archives non conforme.";
                break;
            case "305":
                $name = "Dépôt non conforme à la convention. Signature(s) de document(s) absente(s).";
                break;
            case "306":
                $name = "Dépôt non conforme à la convention. Volume non conforme.";
                break;
            case "307":
                $name = "Dépôt non conforme à la convention. Format non conforme.";
                break;
            case "308":
                $name = "Dépôt non conforme à la convention. Empreinte(s) non transmise(s).";
                break;
            case "309":
                $name = "Dépôt non conforme à la convention. Absence de signature du message.";
                break;
            case "310":
                $name = "Dépôt non conforme à la convention. Signature(s) de document(s) non valide(s).";
                break;
            case "311":
                $name = "Dépôt non conforme à la convention. Signature(s) de document(s) non vérifiée(s).";
                break;
            case "312":
                $name = "Dépôt non conforme à la convention. Dates de début ou de fin non respectées.";
                break;

            default:
                $name = null;
        }

        return $name;
    }
Alexandre Morin's avatar
Alexandre Morin committed
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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
    protected function sendOrganizationDescriptiveMetadata($organization)
    {
        $orgDescMetadata = \laabs::newInstance('seda2/OrganizationDescriptiveMetadata');
        if (isset($organization->orgId)) {
            $orgDescMetadata->id = (string) $organization->orgId;
        }
        if (isset($organization->registrationNumber)) {
            $orgDescMetadata->identification = \laabs::newInstance('seda/ID', $organization->registrationNumber);
        }
        if (isset($organization->orgName)) {
            $orgDescMetadata->name = $organization->orgName;
        }

        if (isset($organization->legalClassification)) {
            $orgDescMetadata->legalClassification = \laabs::newInstance('seda/Code', $organization->legalClassification);
        }

        if (isset($organization->businessType)) {
            $orgDescMetadata->businessType = \laabs::newInstance('seda/Code', $organization->businessType);
        }

        if (isset($organization->description)) {
            $orgDescMetadata->description = $organization->description;
        }

        if (isset($organization->address)) {
            foreach ($organization->address as $address) {
                $orgDescMetadata->address[] = $this->sendAddress($address);
            }
        }

        if (isset($organization->communication)) {
            foreach ($organization->communication as $communication) {
                $orgDescMetadata->communication[] = $this->sendCommunication($communication);
            }
        }

        if (isset($organization->contact)) {
            foreach ($organization->contact as $contact) {
                $orgDescMetadata->contact[] = $this->sendContact($contact);
            }
        }

        return $orgDescMetadata;
    }

Alexandre Morin's avatar
Alexandre Morin committed
638
639
    protected function sendOrganization($orgOrganization)
    {
640
        $organization = \laabs::newInstance('seda2/Organization');
641
642
643
644
        $identifier = isset($orgOrganization->registrationNumber)
            ? $orgOrganization->registrationNumber
            : $orgOrganization->identifier->value;
        $organization->identifier = \laabs::newInstance('seda2/ID', $identifier);
Alexandre Morin's avatar
Alexandre Morin committed
645

646
647
        $organization->organizationDescriptiveMetadata = $this->sendOrganizationDescriptiveMetadata($orgOrganization);

Alexandre Morin's avatar
Alexandre Morin committed
648
649
650
651
652
        return $organization;
    }

    protected function sendAddress($orgAddress)
    {
653
        $address = \laabs::newInstance('seda/Address');
Alexandre Morin's avatar
Alexandre Morin committed
654
655
656
        $address->id = (string) $orgAddress->addressId;
        $address->blockName = $orgAddress->block;
        $address->buildingName = $orgAddress->building;
657
        $address->number = $orgAddress->number;
Alexandre Morin's avatar
Alexandre Morin committed
658
659
660
661
662
663
664
665
666
667
668
669
670
671
        $address->cityName = $orgAddress->city;
        $address->citySubDivisionName = $orgAddress->citySubDivision;
        $address->country = $orgAddress->country;
        $address->floorIdentification = $orgAddress->floor;
        $address->postCode = $orgAddress->postCode;
        $address->postOfficeBox = $orgAddress->postBox;
        $address->roomIdentification = $orgAddress->room;
        $address->streetName = $orgAddress->street;

        return $address;
    }

    protected function sendCommunication($orgCommunication)
    {
672
        $communication = \laabs::newInstance('seda/Communication');
Alexandre Morin's avatar
Alexandre Morin committed
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
        $communication->id = (string) $orgCommunication->communicationId;
        $communication->channel = $orgCommunication->comMeanCode;

        switch ($orgCommunication->comMeanCode) {
            case 'EM':
            case 'FTP':
                $communication->URIID = $orgCommunication->value;
                break;

            default:
                $communication->completeNumber = $orgCommunication->value;
        }

        return $communication;
    }

    protected function sendContact($orgContact)
    {
691
        $contact = \laabs::newInstance('seda/Contact');
Alexandre Morin's avatar
Alexandre Morin committed
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
        $contact->id = (string) $orgContact->contactId;
        $contact->departmentName = $orgContact->service;
        $contact->identification = $orgContact->contactId;
        $contact->personName = $orgContact->displayName;
        $contact->responsibility = $orgContact->function;

        if (isset($orgContact->address)) {
            foreach ($orgContact->address as $address) {
                $contact->address[] = $this->sendAddress($address);
            }
        }

        if (isset($orgContact->communication)) {
            foreach ($orgContact->communication as $communication) {
                $contact->communication[] = $this->sendCommunication($communication);
            }
        }

        return $contact;
    }
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730

    protected function sendUnitIdentifier($mUnitIdentifier)
    {
        $unitIdentifier = \laabs::newInstance('seda2/ID');
        $unitIdentifier->value = $mUnitIdentifier->objectId;

        switch ($mUnitIdentifier->objectClass) {
            case 'recordsManagement/archive':
                $unitIdentifier->schemeName = 'ArchivalAgencyArchiveIdentifier';
                break;

            case 'archivesPubliques/document':
                $unitIdentifier->schemeName = 'ArchivalAgencyDocumentIdentifier';
                break;
        }

        return $unitIdentifier;
    }

731
732
    protected function sendAccessRule($rmArchive)
    {
733
734
735
        if (!isset($rmArchive->accessRuleCode)) {
            return null;
        }
736
737
738
        $accessRule = \laabs::newInstance('seda2/CommonRule');

        if ($rmArchive->accessRuleCode) {
739
            $accessRule->rule = \laabs::newInstance('seda2/Rule', $rmArchive->accessRuleCode);
740
741
742
743
744
            $accessRule->startDate = $this->sendDate($rmArchive->accessRuleStartDate);
        } elseif ($rmArchive->archivalProfileReference) {
            $archivalProfileController = \laabs::newController("recordsManagement/archivalProfile");
            $archivalProfile = $archivalProfileController->getByReference($rmArchive->archivalProfileReference);
            if ($archivalProfile && $archivalProfile->accessRule) {
745
                $accessRule->rule = \laabs::newInstance('seda2/Rule', $archivalProfile->accessRule->code);
746
                $accessRule->startDate = $this->sendDate($rmArchive->depositDate);
747
            } else {
748
                $accessRule->rule = \laabs::newInstance('seda2/Rule', "AR038");
749
                $accessRule->startDate = $this->sendDate($rmArchive->depositDate);
750
751
            }
        } else {
752
            $accessRule->rule = \laabs::newInstance('seda2/Rule', "AR038");
753
            $accessRule->startDate = $this->sendDate($rmArchive->depositDate);
754
755
756
757
758
759
        }
        return $accessRule;
    }

    protected function sendAppraisalRule($rmArchive)
    {
760
761
762
        if (!isset($rmArchive->retentionRuleCode)) {
            return null;
        }
763
        $appraisalRule = \laabs::newInstance('seda2/AppraisalRule');
764

765
766
767
        $appraisalRule->rule = \laabs::newInstance('seda2/Rule', $rmArchive->retentionRuleCode);

        if ($rmArchive->finalDisposition == "preservation") {
768
            $appraisalRule->finalAction = "Keep";
769
        } else {
770
            $appraisalRule->finalAction = "Destroy";
771
772
773
        }

        $appraisalRule->startDate = $this->sendDate($rmArchive->retentionStartDate);
774

775
776
777
778
779
        return $appraisalRule;
    }

    protected function sendClassificationRule($rmArchive)
    {
780
        if (!isset($rmArchive->classificationLevel) || !isset($rmArchive->classificationOwner) || !isset($rmArchive->classificationRuleCode)) {
781
782
            return null;
        }
783

784
785
786
787
788
789
        $classificationRule = \laabs::newInstance('seda2/ClassificationRule');

        $classificationRule->rule = \laabs::newInstance('seda2/Rule', $rmArchive->classificationRuleCode);
        $classificationRule->startDate = $this->sendDate($rmArchive->classificationRuleStartDate);
        $classificationRule->classificationLevel = $rmArchive->classificationLevel;
        $classificationRule->classificationOwner = $rmArchive->classificationOwner;
790

791
792
793
        return $classificationRule;
    }

794
795
796
797
798
    protected function sendManagement($rmArchive)
    {
        $management = \laabs::newInstance("seda2/Management");

        $management->appraisalRule = $this->sendAppraisalRule($rmArchive);
799
800
        $management->accessRule = $this->sendAccessRule($rmArchive);
        $management->classificationRule = $this->sendClassificationRule($rmArchive);
801
802
803
804

        return $management;
    }

805
806
807
808
809
    protected function sendRequest($authorizationRequestContent)
    {
        $request = \laabs::newInstance('seda2/Request');

        $request->authorisationReason = $authorizationRequestContent->authorizationReason;
810
        $request->requestDate = $this->sendDate($authorizationRequestContent->requestDate);
811
812
813
814
815
816
817
818
819
820
821
822
823

        foreach ($authorizationRequestContent->unitIdentifier as $unitIdentifier) {
            $id = \laabs::newInstance('seda2/ID');
            $id->schemeID = $unitIdentifier->objectId;
            $id->schemeName = $unitIdentifier->objectClass;
            $request->unitIdentifier[] = $id;
        }

        $request->requester = $this->sendOrganization($authorizationRequestContent->requester);

        return $request;
    }

824
    protected function sendOneOfInstance($archiveObject, $instance, $attrObject = null)
825
    {
826
        $object = \laabs::newInstance("seda2/$instance");
827

828
829
830
831
832
833
834
        foreach (get_class_vars(get_class($object)) as $attribute => $value) {
            if (isset($archiveObject->$attribute)) {
                if (isset($attrObject) && strpos($attribute, $attrObject["name"]) > -1) {
                    $object->$attribute = $this->sendOneOfInstance($archiveObject->$attribute, $attrObject["instance"]);
                } else {
                    $object->$attribute = $archiveObject->$attribute;
                }
835
836
837
            }
        }

838
        return $object;
839
840
    }

841
    protected function sendMultipleOfInstance($archiveObjects, $instance, $attrObject = null)
842
    {
843
        $objects = [];
844

845
846
        foreach ($archiveObjects as $archiveObject) {
            $objects[] = $this->sendOneOfInstance($archiveObject, $instance, $attrObject);
847
848
        }

849
        return $objects;
850
851
852
853
854
855
    }

    public function sendCustodialHistory($archiveCustodialHistory)
    {
        $custodialHistory = \laabs::newInstance("seda2/CustodialHistory");

856
857
        $custodialHistoryItems = is_array($archiveCustodialHistory) ? $archiveCustodialHistory : $archiveCustodialHistory->custodialHistoryItem;

858
        $custodialHistory->custodialHistoryItem = [];
859
        foreach ($custodialHistoryItems as $item) {
860
861
            $custodialHistory->custodialHistoryItem[] = \laabs::newInstance(
                "seda2/CustodialHistoryItem",
862
                (isset($item->item) ? $item->item : $item->value),
863
864
                (isset($item->when) ? $item->when : null)
            );
865
866
867
868
869
        }

        return $custodialHistory;
    }

870
871
872
873
874
875
876
877
878
879
880
881
882
883
    public function sendReferencedObject($archiveReferencedObject)
    {
        $referencedObject = \laabs::newInstance("seda2/ReferencedObject");

        $referencedObject->signedObjectId = $archiveReferencedObject->signedObjectId;
        $referencedObject->signedObjectDigest = \laabs::newInstance(
            "seda2/MessageDigest",
            $archiveReferencedObject->signedObjectDigest->value,
            $archiveReferencedObject->signedObjectDigest->algorithm
        );

        return $referencedObject;
    }

884
885
886
887
888
    public function sendSignature($archiveSignature)
    {
        $signature = \laabs::newInstance("seda2/Signature");

        if (isset($archiveSignature->signer)) {
889
890
891
892
893
894
            $signature->signer = [];
            foreach ($archiveSignature->signer as $msigner) {
                $signer = $this->sendOneOfInstance($msigner, "Signer", ["name" => "Place", "instance" => "BirthOrDeathPlace"]);
                $signer->signingTime = $this->sendDate($msigner->signingTime, true);
                $signature->signer[] = $signer;
            }
895
896
        }
        if (isset($archiveSignature->validator)) {
897
            $signature->validator = $this->sendOneOfInstance($archiveSignature->validator, "Validator", ["name" => "Place", "instance" => "BirthOrDeathPlace"]);
898
899
            $signature->validator->validationTime = $this->sendDate($archiveSignature->validator->validationTime, true);
        }
900

901
902
        if (isset($archiveSignature->referencedObject)) {
            $signature->referencedObject = $this->sendReferencedObject($archiveSignature->referencedObject);
903
904
        }

905
906
907
908
        if (isset($archiveSignature->masterdata->value)) {
            $signature->masterdata = \laabs::newInstance("seda2/Code", $archiveSignature->masterdata->value);
        }

909
910
911
        return $signature;
    }

912
    public function sendArchiveContent($descriptionValue, $archiveId)
913
    {
914
        $content = \laabs::newInstance("seda2/Content");
915

916
        $attributes = [
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
            "descriptionLevel",
            "title",
            "filePlanPosition",
            "systemId",
            "originatingSystemId",
            "archivalAgencyArchiveUnitIdentifier",
            "originatingAgencyArchiveUnitIdentifier",
            "transferringAgencyArchiveUnitIdentifier",
            "description",
            "custodialHistory",
            "type",
            "language",
            "descriptionLanguage",
            "status",
            "version",
            "tag",
            "keyword",
            "coverage",
            "originatingAgency",
            "submissionAgency",
            "source",
            "relatedObjectReference",
            "createdDate",
            "transactedDate",
            "acquiredDate",
            "sentDate",
            "receivedDate",
            "registeredDate",
            "startDate",
            "endDate",
            "event",
            "signature",
            "gps",
            "documentType",
            "originatingSystemId"
952
953
954
        ];

        $agentTypes = [
955
956
957
958
959
960
            "authorizedAgent",
            "writer",
            "addressee",
            "recipient",
            "transmitter",
            "sender"
961
962
        ];

963
        $needToBeArray = [
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
            "title",
            "filePlanPosition",
            "systemId",
            "originatingSystemId",
            "archivalAgencyArchiveUnitIdentifier",
            "originatingAgencyArchiveUnitIdentifier",
            "transferringAgencyArchiveUnitIdentifier",
            "description",
            "language",
            "tag",
            "keyword",
            "createdDate",
            "transactedDate",
            "acquiredDate",
            "sentDate",
            "receivedDate",
            "registeredDate",
            "startDate",
            "endDate",
            "event",
            "signature"
985
986
        ];

Jerome Boucher's avatar
Jerome Boucher committed
987
        $content->systemId = [(string) $archiveId];
988
989
990
991
992
993

        if (isset($descriptionValue->systemId)) {
            $content->systemId = array_merge($content->systemId, $descriptionValue->systemId);
        }

        foreach ($attributes as $attribute) {
994
995
996
997
998
999
1000
            if (isset($descriptionValue->$attribute) && !is_null($descriptionValue->$attribute)) {
                if ((is_string($descriptionValue->$attribute) && trim($descriptionValue->$attribute) != '')
                    || is_array($descriptionValue->$attribute)
                    || is_object($descriptionValue->$attribute)) {
                    if ($descriptionValue->$attribute instanceof \DateTime) {
                        $content->$attribute = $this->sendDate($descriptionValue->$attribute);
                    } else {
For faster browsing, not all history is shown. View entire blame