message.php 37.6 KB
Newer Older
Prosper De Laure's avatar
Prosper De Laure committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?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;

/**
 * Class for message management
 *
 * @author Maarch Prosper DE LAURE <prosper.delaure@maarch.org>
 */
class message
{
    /**
     * @var organization/organization
     */
34
    protected $orgControler;
Prosper De Laure's avatar
Prosper De Laure committed
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77

    protected $archiveController;

    protected $archiveRelationshipController;

    protected $lifeCycleJournalController;

    protected $digitalResourceController;

    protected $archivalAgreementController;

    protected $sdoFactory;

    protected $messageTypeController;

    protected $messageTypeParser;

    protected $messageTypeSerializer;

    protected $messageDirectory;

    protected $removeMessageTask;

    protected $profilesDirectory;

    protected $messageStandard;

    protected $archivalAgreements = array();

    protected $currentArchivalAgreement;

    protected $autoValidateSize;

    protected $autoProcessSize;

    public $errors = [];

    public $infos = [];

    public $replyCode;

    protected $message;

78
79
    protected $orgController;

Prosper De Laure's avatar
Prosper De Laure committed
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
    protected $parentsDerogation;

    /**
     * Constructor
     * @param string                  $messageDirectory  The message directory
     * @param \dependency\sdo\Factory $sdoFactory        The dependency Sdo Factory
     * @param string                  $messageStandard   The standard to use : MEDONA / SEDA
     * @param bool                    $parentsDerogation See the child org messages
     * @param array                   $removeMessageTask Tasks to remove medona messages directories
     * @param integer                 $autoValidateSize  Min size for auto-validation
     * @param integer                 $autoProcessSize   Min size for auto-process
     */
    public function __construct(
        $messageDirectory,
        \dependency\sdo\Factory $sdoFactory,
        $messageStandard = 'medona',
96
        $parentsDerogation = true,
Prosper De Laure's avatar
Prosper De Laure committed
97
98
        $removeMessageTask = null,
        $autoValidateSize = 0,
99
100
        $autoProcessSize = 0)
    {
Prosper De Laure's avatar
Prosper De Laure committed
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
        $this->orgController = \laabs::newController('organization/organization');
        $this->archiveController = \laabs::newController('recordsManagement/archive');
        $this->archiveRelationshipController = \laabs::newController('recordsManagement/archiveRelationship');
        $this->lifeCycleJournalController = \laabs::newController('lifeCycle/journal');
        $this->digitalResourceController = \laabs::newController('digitalResource/digitalResource');
        $this->archivalAgreementController = \laabs::newController('medona/archivalAgreement');

        $this->profilesDirectory = \laabs::configuration('recordsManagement')['profilesDirectory'];

        $this->messageDirectory = $messageDirectory;
        $this->removeMessageTask = $removeMessageTask;

        if (!is_dir($messageDirectory)) {
            mkdir($messageDirectory, 0777, true);
        }

        $this->sdoFactory = $sdoFactory;
        $this->messageStandard = $messageStandard;

        $this->parentsDerogation = (bool) $parentsDerogation;

        $this->autoValidateSize = $autoValidateSize;
        $this->autoProcessSize = $autoProcessSize;

        $this->errors = array();
    }

    /**
     * Extract message info the specific schema model objects
     * @param medona/message $message
     */
    public function extract($message)
    {
        if (is_scalar($message)) {
            $messageId = $message;
            $message = $this->sdoFactory->read('medona/message', $messageId);

            $this->loadXml($message);
        }
    }

    /**
     * Load message xml file, orgnization information and message object
     * @param medona/message $message  The medona message object
     * @param string         $filename The path to a message xml file
     *
     * @return object The Xml document
     */
    public function loadData($message, $filename = null)
    {
        $this->readOrgs($message);

        if (!empty($message->data)) {
            $message->object = json_decode($message->data);
        }
    }

    /**
     * Get processed archive history message
     * @param string $type
     * @param string $reference
     * @param string $archiver
     * @param string $originator
     * @param string $depositor
     * @param string $archivalAgreement
     * @param date   $fromDate
     * @param date   $toDate
     *
     * @return array Array of medona/message object
     */
171
    public function search($type, $reference = null, $archiver = null, $originator = null, $depositor = null, $archivalAgreement = null, $fromDate = null, $toDate = null, $isIncoming = null)
Prosper De Laure's avatar
Prosper De Laure committed
172
    {
Dylan's avatar
Dylan committed
173
174
        $queryParams = array();
        $queryString = $this->searchMessage($type, $reference, $archiver, $originator, $depositor, $archivalAgreement, $fromDate, $toDate, $isIncoming,$queryParams);
Prosper De Laure's avatar
Prosper De Laure committed
175

Dylan's avatar
Dylan committed
176
        return $this->sdoFactory->find('medona/message', $queryString, $queryParams, false, false, 300);
Prosper De Laure's avatar
Prosper De Laure committed
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
    }

    /**
     * Search message by sender / recipient / reference / date
     * @param string $type
     * @param string $reference
     * @param string $archiver
     * @param string $originator
     * @param string $depositor
     * @param string $archivalAgreement
     * @param date   $fromDate
     * @param date   $toDate
     *
     * @return medona/message[]
     */
Dylan's avatar
Dylan committed
192
    public function searchMessage($type, $reference = null, $archiver = null, $originator = null, $depositor = null, $archivalAgreement = null, $fromDate = null, $toDate = null, $isIncoming = null,&$queryParams)
Prosper De Laure's avatar
Prosper De Laure committed
193
194
    {
        $queryParts = array();
195
        $currentService = \laabs::getToken("ORGANIZATION");
196
        $currentService->orgRoleCodes = (array) $currentService->orgRoleCodes;
197

Cyril Vazquez's avatar
Cyril Vazquez committed
198
199
200
201
        $isOriginator = in_array('originator', $currentService->orgRoleCodes);
        $isArchiver = in_array('archiver', $currentService->orgRoleCodes);
        $isControlAuthority = in_array('controlAuthority', $currentService->orgRoleCodes);

Prosper De Laure's avatar
Prosper De Laure committed
202
203
        if ($archiver || $originator || $depositor) {
            $query = [];
Dylan's avatar
Dylan committed
204

Prosper De Laure's avatar
Prosper De Laure committed
205
            if ($archiver) {
Dylan's avatar
Dylan committed
206
207
208
                $query[] = "(senderOrgRegNumber= :archiver OR recipientOrgRegNumber= :archiver)";
                $queryParams['archiver'] = $archiver;

Prosper De Laure's avatar
Prosper De Laure committed
209
210
            }
            if ($originator) {
Dylan's avatar
Dylan committed
211
212
                $query[] = "(senderOrgRegNumber= :originator OR recipientOrgRegNumber= :originator)";
                $queryParams['originator'] = $originator;
Prosper De Laure's avatar
Prosper De Laure committed
213
214
            }
            if ($depositor) {
Dylan's avatar
Dylan committed
215
216
                $query[] = "(senderOrgRegNumber= :depositor OR recipientOrgRegNumber= :depositor)";
                $queryParams['depositor'] = $depositor;
Prosper De Laure's avatar
Prosper De Laure committed
217
218
219
220
221
222
            }

            $size = sizeof($query);
            if ($size == 1) {
                $queryParts[] = $query[0];
            } elseif ($size == 2) {
Alexandre Morin's avatar
Alexandre Morin committed
223
                $queryParts[] = '('.$query[0].' AND '.$query[1].')';
Prosper De Laure's avatar
Prosper De Laure committed
224
            } else {
Alexandre Morin's avatar
Alexandre Morin committed
225
                $queryParts[] = '('.$query[0].' AND '.$query[1].' AND '.$query[2].')';
Prosper De Laure's avatar
Prosper De Laure committed
226
227
228
            }
        }
        if ($archivalAgreement) {
Dylan's avatar
Dylan committed
229
230
            $queryParts[] = "archivalAgreementReference= :archivalAgreementReference";
            $queryParams['archivalAgreementReference'] = $archivalAgreement;
Prosper De Laure's avatar
Prosper De Laure committed
231
232
        }
        if ($fromDate) {
Alexandre Morin's avatar
Alexandre Morin committed
233
            $fromDate = \laabs::newDate($fromDate, "Y-m-d H:i:s");
Dylan's avatar
Dylan committed
234
235
            $queryParts[] = "date >= :fromDate";
            $queryParams['fromDate'] = $fromDate;
Prosper De Laure's avatar
Prosper De Laure committed
236
237
        }
        if ($toDate) {
Alexandre Morin's avatar
Alexandre Morin committed
238
239
            $toDate = \laabs::newDate($toDate, "Y-m-d H:i:s");
            $toDate->add(new \DateInterval("PT23H59M59S"));
Dylan's avatar
Dylan committed
240
241
            $queryParts[] = "date <= :toDate";
            $queryParams['toDate'] = $toDate;
Prosper De Laure's avatar
Prosper De Laure committed
242
243
        }
        if ($reference) {
Dylan's avatar
Dylan committed
244
245
            $queryParts[] = "reference= :reference";
            $queryParams['reference'] = $reference;
Prosper De Laure's avatar
Prosper De Laure committed
246
        }
Alexandre Morin's avatar
Alexandre Morin committed
247
248
249
250
        if ($isIncoming !== null) {
            switch ($isIncoming) {
                case true :
                    $queryParts[] = "isIncoming= true";
Dylan's avatar
Dylan committed
251
                    break;
Alexandre Morin's avatar
Alexandre Morin committed
252
253
254
255
                case false :
                    $queryParts[] = "isIncoming= false";
                    break;
            }
256
        }
Prosper De Laure's avatar
Prosper De Laure committed
257
        if ($type) {
258
            $clause = [];
Cyril Vazquez's avatar
Cyril Vazquez committed
259
260
261
262
263
264
265
266
267
268
269
            switch ($type) {
                case  "ArchiveDelivery":
                    if ($isOriginator || $isArchiver) {
                        $clause[] = "type='*$type*'";
                    }

                    if (in_array('controlAuthority', $currentService->orgRoleCodes)) {
                        $clause[] =  "type='AuthorizationControlAuthorityRequest' AND authorizationReason='ArchiveDeliveryRequest'";
                    }
                    break;

Dylan's avatar
Dylan committed
270
                case "ArchiveDestruction":
Cyril Vazquez's avatar
Cyril Vazquez committed
271
272
273
274
275
                    if ($isArchiver) {
                        $clause[] = "type='*$type*'";
                    }

                    if ($isOriginator) {
276
                        $clause[] = "type='ArchiveDestructionRequest' OR (type='AuthorizationOriginatingAgencyRequest' AND authorizationReason='ArchiveDestructionRequest')";
Cyril Vazquez's avatar
Cyril Vazquez committed
277
278
279
280
281
282
283
284
285
286
                    }

                    if ($isControlAuthority) {
                        $clause[] = "type='AuthorizationControlAuthorityRequest' AND authorizationReason='ArchiveDestructionRequest'";
                    }

                    if (!$isArchiver && !$isOriginator && !$isControlAuthority) {

                    }
                    break;
Dylan's avatar
Dylan committed
287

Cyril Vazquez's avatar
Cyril Vazquez committed
288
289
290
                case "ArchiveRestitution":
                    $clause[] = "type=['ArchiveRestitutionRequest','ArchiveRestitution']";
                    break;
Dylan's avatar
#6982    
Dylan committed
291
292
293
294

                case "ArchiveNotification":
                    $clause[] = "type=['ArchiveModificationNotification','ArchiveDestructionNotification','ArchivalProfileModificationNotification']";
                    break;
Dylan's avatar
Dylan committed
295

Cyril Vazquez's avatar
Cyril Vazquez committed
296
                default :
Dylan's avatar
Dylan committed
297
298
                    $clause[] = "type= :type AND status !='template'";
                    $queryParams['type'] = $type;
Cyril Vazquez's avatar
Cyril Vazquez committed
299
                    break;
Prosper De Laure's avatar
Prosper De Laure committed
300
            }
301

302
            if (!empty($clause)) {
Dylan's avatar
Dylan committed
303
                $queryParts[] =
304
                    '('
Dylan's avatar
Dylan committed
305
                    .\laabs\implode(') OR (', $clause)
306
                    .')';
Dylan's avatar
Dylan committed
307
            }
Prosper De Laure's avatar
Prosper De Laure committed
308
309
        }

Cyril Vazquez's avatar
Cyril Vazquez committed
310
        $currentServiceOrgRegNumber = $currentService->registrationNumber;
Dylan's avatar
Dylan committed
311
312
        $queryParts[] = "(recipientOrgRegNumber= :currentServiceOrgRegNumber OR senderOrgRegNumber= :currentServiceOrgRegNumber)";
        $queryParams['currentServiceOrgRegNumber'] = $currentServiceOrgRegNumber;
313

Dylan's avatar
Dylan committed
314
        return '('.implode(') and (', $queryParts).')';
Prosper De Laure's avatar
Prosper De Laure committed
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
    }

    /**
     * Get current registration number
     *
     * @return string
     */
    protected function getCurrentRegistrationNumber()
    {
        if ($this->parentsDerogation) {
            $childrenOrgs = \laabs::callService('organization/userPosition/readDescendantservices');

            if ($childrenOrgs == null) {
                $registrationNumber = "''";
            } else {
                $registrationNumber = "['".\laabs\implode("', '", $childrenOrgs)."']";
            }
        } else {
            $organization = \laabs::getToken("ORGANIZATION");

            if (!$organization) {
                $registrationNumber = "''";
            } else {
                $registrationNumber = "'$organization->registrationNumber'";
            }
        }

        return $registrationNumber;
    }

    /**
     * Save xml file
     * @param medona/message $message The Object message
     */
    public function save($message)
    {
        if (isset($message->xml)) {
            $messageFile = $this->messageDirectory.DIRECTORY_SEPARATOR.(string) $message->messageId.DIRECTORY_SEPARATOR.(string) $message->messageId.'.xml';

            if (!is_dir($this->messageDirectory.DIRECTORY_SEPARATOR.(string) $message->messageId)) {
                mkdir($this->messageDirectory.DIRECTORY_SEPARATOR.(string) $message->messageId, 0777, true);
            }

            $message->xml->save($messageFile);

            $message->xml->uri = $messageFile;
        }
    }

    /**
     * Create a message
     * @param medona/message $message The message object
     *
     * @throws \Exception
     *
     * @return string The new message identifier
     */
    public function create($message)
    {
        // Check unique
        $unique = array(
            'type' => $message->type,
            'senderOrgRegNumber' => $message->senderOrgRegNumber,
            'reference' => $message->reference,
        );

        if ($this->sdoFactory->exists("medona/message", $unique)) {
            $this->sendError("103", "The message has already been received ('%s' Ref. '%s' from '%s')", array($message->type, $message->reference, $message->senderOrgRegNumber));
Alexis Ragot's avatar
Alexis Ragot committed
383
            throw \laabs::newException("medona/invalidMessageException", "The message has already been received ('%s' Ref. '%s' from '%s')", 409, null, array($message->type, $message->reference, $message->senderOrgRegNumber));
Prosper De Laure's avatar
Prosper De Laure committed
384
385
386
387
388
389
390
391
392
393
394
395
396
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
        }

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

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

        try {
            if ($accountToken = \laabs::getToken('AUTH')) {
                $message->accountId = $accountToken->accountId;
            }

            if (isset($message->object)) {
                $message->data = json_encode($message->object);
            }

            $this->sdoFactory->create($message, 'medona/message');

            if (is_array($message->unitIdentifier)) {
                foreach ($message->unitIdentifier as $unitIdentifier) {
                    $this->sdoFactory->create($unitIdentifier);
                }
            }

        } catch (\Exception $exception) {
            if ($transactionControl) {
                $this->sdoFactory->rollback();
            }

            throw $exception;
        }

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

        return $message->messageId;
    }

    /**
     * Update a message
     * @param medona/message $message The message object
     *
     * @return string
     *
     * @throws \Exception
     * @throws \dependency\sdo\Exception
     */
    public function update($message)
    {
        $transactionControl = !$this->sdoFactory->inTransaction();

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

        try {
            if (isset($message->object)) {
                $message->data = json_encode($message->object);
            }

            $this->sdoFactory->update($message, 'medona/message');

        } catch (\Exception $exception) {
            if ($transactionControl) {
                $this->sdoFactory->rollback();
            }

            throw $exception;
        }

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

        return $message->messageId;
    }

    /**
     * Read a message
     * @param string $messageId The message identifier
     *
     * @return medona/message The message object
     */
    public function read($messageId)
    {
        $message = $this->sdoFactory->read('medona/message', $messageId);
        $message->unitIdentifier = $this->sdoFactory->readChildren('medona/unitIdentifier', $message);

Alexandre Morin's avatar
Alexandre Morin committed
474
475
        $message->lifeCycleEvent = $this->lifeCycleJournalController->getObjectEvents($message->messageId, 'medona/message');

Prosper De Laure's avatar
Prosper De Laure committed
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
        $this->loadData($message);

        // Parent request to child reply
        try {
            $replyMessages = $this->sdoFactory->find('medona/message', "type='".$message->type."Reply' AND recipientOrgRegNumber='".$message->senderOrgRegNumber."' AND senderOrgRegNumber='".$message->recipientOrgRegNumber."' AND requestReference='".$message->reference."'");
            if (count($replyMessages) > 0) {
                $replyMessage = $replyMessages[0];
                $this->loadData($replyMessage);

                $message->replyMessage = $replyMessage;
            }
        } catch (\Exception $e) {

        }

491
492
493
494
495
496
497
498
499
500
501
502
503
        // Ack
        try {
            $ackMessages = $this->sdoFactory->find('medona/message', "type='Acknowledgement' AND recipientOrgRegNumber='".$message->senderOrgRegNumber."' AND senderOrgRegNumber='".$message->recipientOrgRegNumber."' AND requestReference='".$message->reference."'");
            if (count($ackMessages) > 0) {
                $ackMessage = $ackMessages[0];
                $this->loadData($ackMessage);

                $message->acknowledgement = $ackMessage;
            }
        } catch (\Exception $e) {

        }

Prosper De Laure's avatar
Prosper De Laure committed
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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
        // Related authorization messages for communication and destruction requests
        try {
            $authorizationMessages = $this->sdoFactory->find('medona/message', "type=['AuthorizationOriginatingAgencyRequest', 'AuthorizationControlAuthorityRequest'] AND authorizationReason='".$message->type."' AND authorizationRequesterOrgRegNumber='".$message->senderOrgRegNumber."' AND authorizationReference='".$message->reference."'", null, "date");
            if (count($authorizationMessages) > 0) {
                foreach ($authorizationMessages as $authorizationMessage) {
                    if ($message->messageId != $authorizationMessage->messageId) {
                        $authorization = $this->read($authorizationMessage->messageId);

                        $message->authorizationMessages[] = $authorization;

                        // Read reply
                        if (isset($authorization->replyMessage)) {
                            $message->authorizationMessages[] = $authorization->replyMessage;
                        }
                    }
                }
            }
        } catch (\Exception $e) {

        }

        return $message;
    }

    protected function readOrgs($message)
    {
        $message->recipientOrg = $this->readOrg($message->recipientOrgRegNumber);
        $message->recipientOrgName = $message->recipientOrg->orgName;

        $message->senderOrg = $this->readOrg($message->senderOrgRegNumber);
        $message->senderOrgName = $message->senderOrg->orgName;
    }

    protected function readOrg($regNumber)
    {
        $organization = $this->orgController->getOrgByRegNumber($regNumber);

        // Address
        $organization->address = $this->orgController->getAddresses($organization->orgId);

        // Communication
        $organization->communication = $this->orgController->getCommunications($organization->orgId);

        // Contact
        $organization->contact = $this->orgController->getContacts($organization->orgId);

        return $organization;
    }

    /**
     * Compose a new message
     * @param medona/message $message The message Object
     */
    public function generate($message)
    {
        $message->xml = \laabs::newService('dependency/xml/Document');
        $message->xPath = new \DOMXPath($message->xml);

        if (!\laabs::getXmlNamespace($message->schema)) {
563
            throw new \Exception('Unknown message schema '.$message->schema, 400);
Prosper De Laure's avatar
Prosper De Laure committed
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
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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
        }

        $messageTypeSerializer = $this->getMessageTypeSerializer($message);

        $messageTypeSerializer->generate($message);

        if (!isset($message->object)) {
            $this->extract($message);
        }

    }

    /**
     * End a transaction
     * @param string $messageId The message identifier
     *
     * @return boolean The result of the operation
     */
    public function endTransaction($messageId)
    {
        $message = $this->sdoFactory->read('medona/message', $messageId);

        $type = substr($message->type, -5);

        if ($type != "Reply") {
            // EXCEPTION
        }

        $message->active = false;
        if (isset($message->requestReference)) {
            $parentKey = array(
                "reference" => $message->requestReference,
                "senderOrgRegNumber" => $message->recipientOrgRegNumber,
                "type" => substr($message->type, 0, -5),
            );

            $parentMessage = $this->sdoFactory->read('medona/message', $parentKey);
            $parentMessage->active = false;
            $this->sdoFactory->update($parentMessage);
        }

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

        return true;
    }

    /**
     * Count active messages for each type
     *
     * @return array The number of active messages sorted by type
     */
    public function countActiveMessages()
    {
        $count = [];

        $count['deposit'] = \laabs::newController('medona/ArchiveTransfer')->count();
        $count['notification'] = \laabs::newController('medona/ArchiveNotification')->count();
        $count['communication'] = \laabs::newController('medona/ArchiveDeliveryRequest')->count();
        $count['restitution'] = \laabs::newController('medona/ArchiveRestitutionRequest')->count();
        $count['restitution']['processed'] = \laabs::newController('medona/ArchiveRestitution')->count();
        $count['destruction'] = \laabs::newController('medona/ArchiveDestructionRequest')->count();

        $authorizationController = \laabs::newController('medona/AuthorizationRequest');

        $count['communicationAuthorization'] = $authorizationController->countCommunication();
        $count['destructionAuthorization'] = $authorizationController->countDestruction();

        return $count;
    }

    /**
     * Export a message
     * @param string $messageId The message identifier
     *
     * @return string The zip of message xml + attachments
     */
    public function export($messageId)
    {
        $message = $this->read($messageId);

        $zip = \laabs::newService('dependency/fileSystem/plugins/zip');

        $messageDirectory = $this->messageDirectory.DIRECTORY_SEPARATOR.$message->messageId;

        $zipfile = $this->messageDirectory.DIRECTORY_SEPARATOR.$message->messageId.".zip";
        if (!is_file($zipfile)) {
            if (is_dir($messageDirectory)) {
                $zip->add($zipfile, $messageDirectory.DIRECTORY_SEPARATOR."*");
            }
        }

        $zipContents = file_get_contents($zipfile);

        //unlink($zipfile);

        return $zipContents;
    }

662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
    /**
     * Retry a message
     * @param string $messageId The message identifier
     */
    public function retry($messageId)
    {
        $message = $message = $this->sdoFactory->read('medona/message', $messageId);
        $message->object = json_decode($message->data);

        $status = '';
        if ($message->schema !== 'medona') {
            $messageController = \laabs::newController($message->schema.'/'.$message->type);
            $status = $messageController->retry($message);
        } else {
            // TODO
        }

        $this->changeStatus($messageId, $status);

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

Prosper De Laure's avatar
Prosper De Laure committed
690
691
692
693
694
695
696
697
698
699
700
701
702
    /**
     * Get the data object attachment
     * @param string $messageId    The message identifier
     * @param string $attachmentId The attachment identifier
     * @param string $format       The format of message
     *
     * @return string
     */
    public function getDataObjectAttachment($messageId, $attachmentId, $format = "xml")
    {
        $message = $this->sdoFactory->read('medona/message', $messageId);
        $message->object = json_decode($message->data);

703
704
        if ($message->schema != 'medona') {
            $messageController = \laabs::newController($message->schema.'/'.$message->type);
Prosper De Laure's avatar
Prosper De Laure committed
705

706
            $resource = $messageController->getAttachment($message, $attachmentId);
Prosper De Laure's avatar
Prosper De Laure committed
707

708
709
            return $resource;
        }
Prosper De Laure's avatar
Prosper De Laure committed
710
711

        // Medona attachment
712
        $attachment = false;
713

Prosper De Laure's avatar
Prosper De Laure committed
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
        foreach ($message->object->dataObjectPackage->binaryDataObject as $binaryDataObject) {
            if ($binaryDataObject->id == $attachmentId) {
                $attachment = $binaryDataObject->attachment;
            }
        }

        if (!$attachment) {
            return false;
        }

        $resource = \laabs::newInstance('digitalResource/digitalResource');

        switch (true) {
            case isset($attachment->filename):
                $filepath = $this->messageDirectory.DIRECTORY_SEPARATOR.(string) $message->messageId.DIRECTORY_SEPARATOR.$attachment->filename;
                $contents = file_get_contents($filepath);

                $resource->fileExtension = pathinfo($attachment->filename, \PATHINFO_EXTENSION);
                $resource->fileName = basename($attachment->filename);
                break;

            case isset($attachment->uri):
                $contents = file_get_contents($attachment->uri);
                break;

            case isset($attachment->value):
                $contents = base64_decode($attachment->value);
                break;

            default:
                return false;
        }

        $finfo = new \finfo(\FILEINFO_MIME_TYPE);
        $resource->mimetype = $finfo->buffer($contents);

        $resource->setContents($contents);

        return $resource;

    }

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

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

        return $this->currentArchivalAgreement;
    }

    /**
     * Get the message schema
     * @param medona/message $message The message object
     *
     * @return string The bundle
     */
    protected function getMessageSchema($message)
    {
        $messageNamespace = $message->xml->documentElement->namespaceURI;
        if (!$messageSchema = \laabs::resolveXmlNamespace($messageNamespace)) {
779
            throw \laabs::newException('medona/invalidMessageException', "Unknown message namespace'.$messageNamespace", 400);
Prosper De Laure's avatar
Prosper De Laure committed
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
        }
        $message->schema = $messageSchema;

        return $messageSchema;
    }

    /**
     * Get the message type and schema specific controller
     * @param medona/message $message The message object
     *
     * @return The controller
     */
    protected function getMessageTypeController($message)
    {
        if (!isset($message->type)) {
            $message->type = $message->xml->documentElement->nodeName;
        }

        if (!isset($message->schema)) {
            $messageNamespace = $message->xml->documentElement->namespaceURI;
            if (!$messageSchema = \laabs::resolveXmlNamespace($messageNamespace)) {
801
                throw new \Exception('Unknown message namespace'.$messageNamespace, 400);
Prosper De Laure's avatar
Prosper De Laure committed
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
            }
            $message->schema = $messageSchema;
        }

        $this->messageTypeController = \laabs::newController($message->schema.LAABS_URI_SEPARATOR.$message->type);

        return $this->messageTypeController;
    }

    /**
     * Get the message type and schema specific parser
     * @param medona/message $message The message object
     * @param string         $format  The implementation format
     *
     * @return The parser
     */
    protected function getMessageTypeParser($message, $format = "xml")
    {
        if (!isset($message->type)) {
            $message->type = $message->xml->documentElement->nodeName;
        }

        if (!isset($message->schema)) {
            $messageNamespace = $message->xml->documentElement->namespaceURI;
            if (!$messageSchema = \laabs::resolveXmlNamespace($messageNamespace)) {
827
                throw new \Exception('Unknown message namespace '.$messageNamespace, 400);
Prosper De Laure's avatar
Prosper De Laure committed
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
            }
            $message->schema = $messageSchema;
        }

        $this->messageTypeParser = \laabs::newParser($message->schema.LAABS_URI_SEPARATOR.$message->type, $format);

        return $this->messageTypeParser;
    }

    /**
     * Get the message type and schema specific serializer
     * @param medona/message $message The message object
     * @param string         $format  The implementation format
     *
     * @return The parser
     */
    protected function getMessageTypeSerializer($message, $format = "xml")
    {
        if (!isset($message->type)) {
            $message->type = $message->xml->documentElement->nodeName;
        }

        if (!isset($message->schema)) {
            $messageNamespace = $message->xml->documentElement->namespaceURI;
            if (!$messageSchema = \laabs::resolveXmlNamespace($messageNamespace)) {
853
                throw new \Exception('Unknown message namespace'.$messageNamespace, 400);
Prosper De Laure's avatar
Prosper De Laure committed
854
855
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
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
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
            }
            $message->schema = $messageSchema;
        }
        $this->messageTypeSerializer = \laabs::newSerializer($message->schema.LAABS_URI_SEPARATOR.$message->type, $format);

        return $this->messageTypeSerializer;
    }

    /**
     * Change status of message
     * @param string $messageId The message identifier
     * @param string $status    The new status for message
     * @param string $comment   A comment
     *
     * @return boolean The result of the operation
     */
    protected function changeStatus($messageId, $status, $comment = null)
    {
        $messageStatus = \laabs::newMessage('medona/messageStatus');
        $messageStatus->messageId = $messageId;
        $messageStatus->status = strtolower($status);

        if ($comment) {
            $messageStatus->comment[] = $comment;
        }

        $this->sdoFactory->update($messageStatus, 'medona/message');

        return true;
    }

    /**
     * Archive messages
     *
     * @return array
     */
    public function archiveMessages()
    {
        $messages = $this->sdoFactory->find('medona/message', "archived=false");

        $archivedMessageIds = [];

        if (count($messages)) {
            foreach ($messages as $message) {
                if ($this->archiveMessage($message)) {
                    $archivedMessageIds[] = (string) $message->messageId;
                }
            }
        }

        return $archivedMessageIds;
    }

    /**
     * Archive a message
     * @param mixed $messageId The message identifier OR the message itself
     *
     * @return bool
     */
    public function archiveMessage($messageId)
    {
        if (is_object($messageId)) {
            $message = $messageId;
            $messageId = (string) $message->messageId;
        }

        $filename = $this->messageDirectory.DIRECTORY_SEPARATOR.(string) $messageId.DIRECTORY_SEPARATOR.(string) $messageId.'.xml';
        if (!is_file($filename)) {
            return false;
        }

        if (!is_object($messageId)) {
            $message = $this->read($messageId);
        }

        $this->readOrgs($message);

        // Create archive
        $archive = $this->archiveController->newArchive();

        $archive->archiveId = $message->messageId;
        $archive->accessRuleDuration = 'P0D';
        $archive->retentionDuration = 'P0D';
        $archive->finalDisposition = 'preservation';
        $archive->descriptionId = $messageId;
        $archive->descriptionClass = 'medona/message';

        // Create resource
        $messageResource = $this->digitalResourceController->createFromFile($filename);
943
        $messageResource->archiveId = $archive->archiveId;
Prosper De Laure's avatar
Prosper De Laure committed
944
945
946
947
        $messageResource->puid = "fmt/101";
        $messageResource->mimetype = "text/xml";
        $this->digitalResourceController->getHash($messageResource, "SHA256");

948
        $archive->digitalResources[] = $messageResource;
Prosper De Laure's avatar
Prosper De Laure committed
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986

        if ($message->type == 'ArchiveTransferReply' || $message->type == 'ArchiveDeliveryRequestReply' || $message->type == 'ArchiveModificationNotification' || $message->type == 'ArchiveDestructionNotification') {
            $archive->archiverOrgRegNumber = $archive->depositorOrgRegNumber = (string) $message->senderOrgRegNumber;
            $archive->originatorOrgRegNumber = (string) $message->recipientOrgRegNumber;
            $archive->originatorOwnerOrgId = (string) $message->recipientOrg->orgId;
        } else {
            $archive->archiverOrgRegNumber = $archive->depositorOrgRegNumber = (string) $message->recipientOrgRegNumber;
            $archive->originatorOrgRegNumber = (string) $message->senderOrgRegNumber;
            $archive->originatorOwnerOrgId = (string) $message->senderOrg->orgId;
        }

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

        $originatorOrgs = [];
        if (!isset($originatorOrgs[$archive->originatorOrgRegNumber])) {
            $originatorOrg = $this->orgController->getOrgByRegNumber($archive->originatorOrgRegNumber);
            $originatorOrgs[$archive->originatorOrgRegNumber] = $originatorOrg;
        } else {
            $originatorOrg = $originatorOrgs[$archive->originatorOrgRegNumber];
        }

        $archive->originatorOwnerOrgId = $originatorOrg->ownerOrgId;

        $context = array_merge(get_object_vars($message), get_object_vars($archive));
        $filePlanPosition = $this->archiveController->resolveStoragePath($context);
        $archived = $this->archiveController->deposit($archive, $filePlanPosition);

        if ($archived) {
            $archivedMessage = new \StdClass();
            $archivedMessage->messageId = $messageId;
            $archivedMessage->archived = true;

            $this->sdoFactory->update($archivedMessage, 'medona/message');

            return $archived;
        }
    }

987
988
989
990
991
992
993
994
    /**
     * Get a message with the reference
     * @param string $reference
     *
     * @return mixte Return a message or null if not exist
     */
    public function getByReference($reference)
    {
Dylan's avatar
Dylan committed
995
996
997
//        $queryParts = $this->searchMessage(null, $reference);
        $queryParams = array();
        $queryString = $this->searchMessage(null, $reference, null, null, null, null, null, null, null,$queryParams);
998

Dylan's avatar
Dylan committed
999
        $message = $this->sdoFactory->find('medona/message', $queryString, $queryParams, false, false, 300);
Alexandre Morin's avatar
Alexandre Morin committed
1000

For faster browsing, not all history is shown. View entire blame