-
Notifications
You must be signed in to change notification settings - Fork 0
/
commit-transaction.php
1553 lines (1394 loc) · 58.3 KB
/
commit-transaction.php
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
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
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
383
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
474
475
476
477
478
479
480
481
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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
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
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
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
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
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
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
853
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
943
944
945
946
947
948
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
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
try {
// Includes
//
include_once("includes/error-handler.php");
include_once("includes/defines.php");
include_once("includes/configuration.php");
include_once("includes/communicator.php");
include_once("includes/platforms.php");
include_once("includes/parameters.php");
include_once("includes/filetransfer/file-transfer-base.php");
include_once("includes/filetransfer/file-transfer-ssh.php");
include_once("includes/filetransfer/file-transfer-sftp.php");
include_once("includes/filetransfer/file-transfer-disk.php");
include_once("includes/logger.php");
include_once("includes/metadata-parser.php");
include_once("includes/general-functions.php");
include_once("includes/script-context.php");
include_once("includes/ehealth1-sip.php");
include_once("includes/python-runner.php");
include_once("metadata-description.php");
include_once("metadata-description-package.php");
include_once("config.php");
// Setup
//
// Setup logging
$logger = new Logger($configuration->getValue("LogDir"));
$logger->setLogDebug($configuration->getValue("LogDebug"));
$logger->setLogInfo($configuration->getValue("LogInfo"));
$logger->setLogWarning($configuration->getValue("LogWarning"));
$logger->setLogError($configuration->getValue("LogError"));
// Create communication line to GUI
$communicator = new Communicator(true);
// Input arguments
//
$parameters = new Parameters();
// Get language
if (!$parameters->get($language, 1))
{
exitWithError("Missing argument: Language");
}
if (!selectLanguage($language))
{
exitWithError("Failed to setup language: $language");
}
// Get context
if (!$parameters->get($contextPath, 2))
{
exitWithError("Missing argument: Context");
}
$contextPath = normalizeFilePath($contextPath);
$scriptContext = new ScriptContext();
if (!$scriptContext->readFile($contextPath))
{
exitWithError("Failed to read context: $contextPath");
}
// Get temp directory path
if (!$scriptContext->valueAsString($tempDirectoryPath, "TempFileDirectory"))
{
exitWithError("Failed to get temp directory");
}
$tempDirectoryPath = normalizeFilePath($tempDirectoryPath);
if (substr($tempDirectoryPath, strlen($tempDirectoryPath) - 1, 1) == "/")
{
$tempDirectoryPath = substr($tempDirectoryPath, 0, strlen($tempDirectoryPath) - 1);
}
if (!file_exists($tempDirectoryPath) || !is_dir($tempDirectoryPath))
{
exitWithError("Temp directory does not exist: " . $tempDirectoryPath);
}
// Get files
if (!$scriptContext->valueAsArray($filePathList, "FilePaths"))
{
exitWithError("Failed to get file paths");
}
if (count($filePathList) == 0)
{
exitWithError("Path list is empty");
}
for ($i = 0; $i < count($filePathList); $i++)
{
// Normalize directory separators
$filePathList[$i] = normalizeFilePath($filePathList[$i]);
// Check that file exists on disk
if (!file_exists($filePathList[$i]))
{
exitWithError("File does not exist on disk: " . $filePathList[$i]);
}
// Remove trailing slash on directories
$filePathList[$i] = rtrim($filePathList[$i], '/');
}
// Get relative paths of files
if (!$scriptContext->valueAsArray($relativeFilePathList, "RelativeFilePaths"))
{
exitWithError("Failed to get relative file paths");
}
if (count($relativeFilePathList) == 0)
{
exitWithError("Relative path list is empty");
}
for ($i = 0; $i < count($relativeFilePathList); $i++)
{
// Normalize directory separators
$relativeFilePathList[$i] = normalizeFilePath($relativeFilePathList[$i]);
// Remove trailing slash on directories
$relativeFilePathList[$i] = rtrim($relativeFilePathList[$i], '/');
}
// Get file item types - file, directory etc.
if (!$scriptContext->valueAsArray($fileItemTypeList, "FileItemTypes"))
{
exitWithError("Failed to get file item types");
}
if (count($fileItemTypeList) == 0)
{
exitWithError("File item type list is empty");
}
// Get file IDs
if (!$scriptContext->valueAsArray($fileIdList, "FileIds"))
{
exitWithError("Failed to get file IDs");
}
if (count($fileIdList) == 0)
{
exitWithError("File ID list is empty");
}
for ($i = 0; $i < count($fileIdList); $i++)
{
if (!is_numeric($fileIdList[$i]))
{
exitWithError("Invalid file ID: " . $fileIdList[$i]);
}
}
// Get parent file IDs
if (!$scriptContext->valueAsArray($parentFileIdList, "ParentFileIds"))
{
exitWithError("Failed to get parent file IDs");
}
if (count($parentFileIdList) == 0)
{
exitWithError("Parent file ID list is empty");
}
for ($i = 0; $i < count($parentFileIdList); $i++)
{
if (!is_numeric($parentFileIdList[$i]))
{
exitWithError("Invalid parent file ID: " . $parentFileIdList[$i]);
}
}
// Get metadata
if (!$scriptContext->valueAsArray($metadataList, "FileMetadata"))
{
exitWithError("Failed to get metadata");
}
if (count($metadataList) == 0)
{
exitWithError("Metadata list is empty");
}
// Get package metadata
if (!$scriptContext->valueAsString($packageMetadata, "PackageMetadata"))
{
// Package metadata is not mandatory
$packageMetadata = "";
}
// Functions
//
function logError($text)
{
global $logger;
$logger->logError($text);
}
function logInfo($text)
{
global $logger;
$logger->logInfo($text);
}
function createMetadata($metadataListIn, $metadataFileOut, $fileNameList, $metadataTemplate, $configuration)
{
$metadataParser = new MetadataParser();
// Get output format
$metadataOutputFormat = $configuration->getValue("MetadataOutputFormat");
// Setup expected keys
for ($i = 0; $i < $metadataTemplate->groupCount(); $i++)
{
if (!$metadataTemplate->getGroup($group, $i))
{
logError("Failed to get group");
return false;
}
for ($j = 0; $j < $group->itemCount(); $j++)
{
if (!$group->getItem($item, $j))
{
logError("Failed to get metadata item");
return false;
}
$required = true;
if (!$metadataParser->addKeyTemplate(new MetadataParserKeyTemplate($item->name(), $required)))
{
logError("Failed to add key template");
return false;
}
}
}
// Read metadata for file
for ($i = 0; $i < count($metadataListIn); $i++)
{
if (!$metadataParser->readString($metadataListIn[$i], $errorMessage))
{
logError("Failed to read metadata: $errorMessage");
return false;
}
}
// Skip metadata if empty
if ($metadataParser->itemCount() == 0)
{
return true;
}
// Write output in CSV format
if ($metadataOutputFormat == METADATA_OUTPUT_FORMAT_DUBLINCORE_CSV)
{
// Get output order
$outputOrder = array();
if ($configuration->exists("MetadataOutputItemOrder"))
{
$outputOrder = $configuration->getValue("MetadataOutputItemOrder");
}
// Get output order
$fondPosition = -1;
if ($configuration->exists("MetadataCsvFondPosition"))
{
$fondPosition = $configuration->getValue("MetadataCsvFondPosition");
}
if (!$metadataParser->writeDublinCoreCsvToFile($metadataFileOut, $fileNameList, $outputOrder, $fondPosition))
{
logError("Failed to write metadata to output file: $metadataFileOut");
return false;
}
}
else
{
logError("Invalid metadata output format");
return false;
}
return true;
}
function createBagitDescriptionFile($descriptionOutFile, $version)
{
$text = "";
$text .= "BagIt-Version: " . $version . "\n";
$text .= "Tag-File-Character-Encoding: UTF-8" . "\n";
file_put_contents($descriptionOutFile, $text, LOCK_EX);
return true;
}
function createChecksumManifestFile($checksumManifestOut, $filePathList, $relativeFilePathList)
{
$text = "";
for ($i = 0; $i < count($filePathList); $i++)
{
$filePath = $filePathList[$i];
if (!is_dir($filePath))
{
$text .= md5_file($filePath) . " " . "data/" . $relativeFilePathList[$i] . "\n";
}
}
file_put_contents($checksumManifestOut, $text, LOCK_EX);
return true;
}
function sendProgressCallback($bytesSent, $bytesTotal)
{
global $communicator;
$percent = round(($bytesSent/$bytesTotal)*100);
$communicator->sendProgress($percent, gettext("Sending to server"));
}
function isSubmissionAgreement($path)
{
$fileName = basename($path);
// Check file extension
if (strtolower(pathinfo($fileName, PATHINFO_EXTENSION)) != 'pdf')
{
return false;
}
// Check that fileName starts with "SA-"
if (substr($fileName, 0, 3) != 'SA-')
{
return false;
}
// Validate OID
$oid = substr($fileName, 3, strlen($fileName) - 7);
if (strlen($oid) < 1)
{
return false;
}
for ($i = 0; $i < strlen($oid); $i++)
{
if ($oid[$i] != '.' && !is_numeric($oid[$i]))
{
return false;
}
}
return true;
}
// Commit instructions
//
// Identify platform
$platforms = new Platforms();
$platforms->addSupported(PLATFORM_CENTOS6);
$platforms->addSupported(PLATFORM_CENTOS7);
$platforms->addSupported(PLATFORM_RHEL7);
$platforms->addSupported(PLATFORM_RHEL8);
$platforms->addSupported(PLATFORM_WINDOWS7);
$platforms->addSupported(PLATFORM_WINDOWS8);
$platforms->addSupported(PLATFORM_WINDOWS10);
$platforms->addSupported(PLATFORM_OSX);
$platform = $platforms->identify($os, $distribution);
if (!$platforms->isSupported($platform))
{
exitWithError("Unsupported platform: platform='$platform' os='$os' distribution='$distribution'");
}
logInfo("Identified OS: {$platform}");
// Pre-process input data
if ($configuration->exists("PreProcessInputDataScript"))
{
$communicator->sendProgress(0, gettext("Pre-processing data"));
$scriptPath = $configuration->getValue("PreProcessInputDataScript");
include_once($scriptPath);
if (!preProcessInputData($errorMessage, $filePathList, $relativeFilePathList, $tempDirectoryPath))
{
exitWithError("Failed to pre-process input data: {$errorMessage}");
}
}
// Build data for archive
logInfo("Building SIP");
$communicator->sendProgress(0, gettext("Preparing data"));
$archiveFiles = array();
{
// Create package files
if ($configuration->getValue("OutputFormat") == OUTPUT_FORMAT_EHEALTH1_SIP)
{
// Create a SIP compliant to the eHealth1 standard
// The payload can contain files or directory stuctures
//
// SIP structure:
// {TRANSFER_NAME}
// mets.xml
// metadata/
// descriptive/
// Patients.xml
// preservation/
// schemas/
// condition.xsd
// DILCISExtensionMETS.xsd
// DILCISExtensionSIPMETS.xsd
// patient.xsd
// xlink.xsd
// xml.xsd
// documentation/
// submissionagreement.pdf
// submissionagreement_old.pdf
// representations/
// Patientrecord_{ID}
// mets.xml
// metadata/
// descriptive/
// Patient1_condition.xml
// preservation/
// data/
// {PAYLOAD}
//
// Input structure:
// eHealth1_Transfer_{ID}
// Patients.xml
// submissionagreement.pdf
// submissionagreement_old.pdf
// patientrecord_1/
// Patient1_condition.xml
// Patient1Case1/
// Patient1Case1Document1/
// patient1_record1.pdf
// Patient1Case2/
// Patient1Case2Document1/
// patient1_record2.pdf
// patientrecord_2/
// Patient2_condition.xml
// Patient2Case1/
// Patient2Case1Subcase1/
// Patient2Case1Subcase1Document1/
// patient2_record1.pdf
// Patient2Case1Subcase1Document2/
// patient2_record2.pdf
// Define SIP
$sip = new Ehealth1Sip();
// Populate files in SIP
for ($i = 0; $i < count($filePathList); $i++)
{
$filePath = $filePathList[$i];
$relativeFilePath = $relativeFilePathList[$i];
$directoryDepth = substr_count($relativeFilePath, '/');
if ($directoryDepth == 0)
{
// This is a SIP
//
// Set transfer name
if (strlen($sip->transferName()) > 0)
{
exitWithError('Only one SIP per commit is allowed');
}
$parts = explode('_', $relativeFilePath);
if (count($parts) == 0)
{
exitWithError("SIP name is in wrong format: {$relativeFilePath}");
}
$sip->setTransferName($relativeFilePath);
}
else if ($directoryDepth == 1)
{
// This file should be added to SIP
//
if ($sip->isSubmissionAgreement($relativeFilePath))
{
// Add submission agreement
$sip->addSubmissionAgreement($filePath);
}
else if ($sip->isDescriptiveMetadata($relativeFilePath))
{
// Add descriptive metadata
$sip->addDescriptiveMetadata($filePath);
}
else if (is_dir($filePath) && $sip->isPatientDirectory($relativeFilePath))
{
// This is a patient data folder
//
// Set patient ID
$parts = explode('_', basename($filePath));
$patientId = '';
if (count($parts) >= 2)
{
$patientId = $parts[count($parts)-1];
}
else
{
$patientId = guidv4(openssl_random_pseudo_bytes(16));
}
$patient = new Ehealth1SipPatient($patientId);
// Add files
$patientDirectoryPath = $filePath;
for ($j = 0; $j < count($filePathList); $j++)
{
$filePath = $filePathList[$j];
$relativeFilePath = $relativeFilePathList[$j];
// Check if file is part of this patient directory
if (substr($filePath, 0, strlen($patientDirectoryPath)) != $patientDirectoryPath || $filePath == $patientDirectoryPath)
{
continue;
}
if ($patient->isDescriptiveMetadata($relativeFilePath))
{
// Add descriptive metadata
$patient->addDescriptiveMetadata($filePath);
}
else
{
// Add payload
$patient->addFile($filePath, substr($filePath, strlen($patientDirectoryPath)+1));
}
}
// Check that patient has data files
if (count($patient->files()) == 0)
{
exitWithError("Patient has no data files");
}
// Add patient to SIP
$sip->addPatient($patient);
}
else
{
exitWithError("File was not recognized as SIP data: {$relativeFilePath}");
}
}
}
// Add schemas
$schemaDirectory = $configuration->getValue("Ehealth1SipSchemaDirectory");
if (!is_dir($schemaDirectory))
{
exitWithError("Schema directory could not be found: {$schemaDirectory}");
}
$schemaFiles = scandir($schemaDirectory);
if ($schemaFiles === false)
{
exitWithError("Failed to read schema directory: {$schemaDirectory}");
}
foreach ($schemaFiles as $schemaFile)
{
if (substr($schemaFile, 0, 1) == '.')
{
// Skipping file
continue;
}
$sip->addSchemaFile("{$schemaDirectory}/{$schemaFile}");
}
// Populate package metadata
$metadataParser = new MetadataParser();
if (!$metadataParser->readString($packageMetadata, $errorMessage))
{
exitWithError($errorMessage);
}
$metadataList = $metadataParser->getMetadata();
if (count($metadataList) == 0)
{
exitWithError("No package metadata was submitted");
}
foreach ($metadataList as $metadataItem)
{
$sip->addPackageMetadata($metadataItem->key(), $metadataItem->value());
}
// Check that the SIP has an ID
if (strlen($sip->transferName()) == 0)
{
exitWithError('The SIP does not have an ID');
}
// Check that SIP contains exactly one submission agreement
$submissionAgreementCount = count($sip->submissionAgreements());
if ($submissionAgreementCount < 1 || $submissionAgreementCount > 2)
{
exitWithError("One or two submission agreements expected, {$submissionAgreementCount} found");
}
// Check that SIP contains exactly one document of descriptive metadata
$descriptiveMetadataCount = count($sip->descriptiveMetadata());
if ($descriptiveMetadataCount != 1)
{
exitWithError("One document of descriptive metadata expected, {$descriptiveMetadataCount} found");
}
// Check that SIP contains schema files
if (count($sip->schemaFiles()) == 0)
{
exitWithError("SIP does not contain schema files");
}
// Produce SIP
if (!$sip->produceSip($outPath, $tempDirectoryPath))
{
exitWithError('Producing SIP gave following error: ' . $sip->error());
}
// Setup path for SIP to be archived
array_push($archiveFiles, basename($outPath));
}
else if ($configuration->getValue("OutputFormat") == OUTPUT_FORMAT_NHA_OTHER)
{
// Create a SIP compliant to the NHA 'other' SIP package type
//
// SIP structure:
// {UUID}/
// OTHER/
// journal/
// avlxml.xml
// {SUBMISSION_AGREEMENT}
// objekter/
// {PAYLOAD}
// metadata/
// checksum.md5
// metadata.csv
// identifiers.json
$checksumPaths = array();
// Get info from package metadata
$metadataParser = new MetadataParser();
if (!$metadataParser->readString($packageMetadata, $errorMessage))
{
exitWithError($errorMessage);
}
if (!$metadataParser->getValue("avleveringsidentifikator", 0, $avleveringsidentifikator) ||
!$metadataParser->getValue("avleveringsbeskrivelse", 0, $avleveringsbeskrivelse) ||
!$metadataParser->getValue("avtaleidentifikator", 0, $avtaleidentifikator) ||
!$metadataParser->getValue("avtaledato", 0, $avtaledato) ||
!$metadataParser->getValue("avtalebeskrivelse", 0, $avtalebeskrivelse) ||
!$metadataParser->getValue("virksomhetsnavn", 0, $virksomhetsnavn) ||
!$metadataParser->getValue("foretaksnavn", 0, $foretaksnavn) ||
!$metadataParser->getValue("organisasjonsnummer", 0, $organisasjonsnummer))
{
exitWithError("Failed to read values from metadata");
}
// Create SIP root directory
$sipPath = $tempDirectoryPath . "/" . guidv4(openssl_random_pseudo_bytes(16));
if (!mkdir($sipPath))
{
exitWithError("Failed to create directory: $sipPath");
}
// Create metadata directory
$metadataPath = $sipPath . "/metadata";
if (!mkdir($metadataPath))
{
exitWithError("Failed to create directory: $metadataPath");
}
// Create other directory
$otherPath = $sipPath . "/OTHER";
if (!mkdir($otherPath))
{
exitWithError("Failed to create directory: $otherPath");
}
// Create journal directory
$journalPath = $otherPath . "/journal";
if (!mkdir($journalPath))
{
exitWithError("Failed to create directory: $journalPath");
}
// Create objects directory
$objectsPath = $otherPath . "/objekter";
if (!mkdir($objectsPath))
{
exitWithError("Failed to create directory: $objectsPath");
}
// Create AVLXML
$avlxmlPath = $otherPath . "/journal/avlxml.xml";
array_push($checksumPaths, "OTHER/journal/avlxml.xml");
$avlxml = "";
$avlxml .= "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" . "\n";
$avlxml .= "<avlxml xmlns=\"http://www.arkivverket.no/standarder/nha/avlxml\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.arkivverket.no/standarder/nha/avlxml avlxml.xsd\">" . "\n";
$avlxml .= " <avlxmlversjon>2.16.578.1.39.100.5.2.2</avlxmlversjon>" . "\n";
$avlxml .= " <avleveringsidentifikator>" . htmlspecialchars($avleveringsidentifikator) . "</avleveringsidentifikator>" . "\n";
$avlxml .= " <avleveringsbeskrivelse>" . htmlspecialchars($avleveringsbeskrivelse) . "</avleveringsbeskrivelse>" . "\n";
$avlxml .= " <arkivskaper>NHA</arkivskaper>" . "\n";
$avlxml .= " <avtale>" . "\n";
$avlxml .= " <avtaleidentifikator>" . htmlspecialchars($avtaleidentifikator) . "</avtaleidentifikator>" . "\n";
$avlxml .= " <avtaledato>" . htmlspecialchars($avtaledato) . "</avtaledato>" . "\n";
$avlxml .= " <avtalebeskrivelse>" . htmlspecialchars($avtalebeskrivelse) . "</avtalebeskrivelse>" . "\n";
$avlxml .= " <virksomhet>" . "\n";
$avlxml .= " <virksomhetsnavn>" . htmlspecialchars($virksomhetsnavn) . "</virksomhetsnavn>" . "\n";
$avlxml .= " <foretaksnavn>" . htmlspecialchars($foretaksnavn) . "</foretaksnavn>" . "\n";
$avlxml .= " <organisasjonsnummer>" . htmlspecialchars($organisasjonsnummer) . "</organisasjonsnummer>" . "\n";
$avlxml .= " </virksomhet>" . "\n";
$avlxml .= " </avtale>" . "\n";
$avlxml .= "</avlxml>" . "\n";
if (file_put_contents($avlxmlPath, $avlxml) === false)
{
exitWithError("Failed to write to file: " . $avlxmlPath);
}
// Create identifiers.json
$identifiersPath = "$metadataPath/identifiers.json";
$identifiersOut = "";
$identifiersOut .= "[ { \"file\": \"objects/OTHER/journal/avlxml.xml\", \"identifiers\": [" . "\n";
$identifiersOut .= " {" . "\n";
$identifiersOut .= " \"identifierType\": \"avleveringsidentifikator\"," . "\n";
$identifiersOut .= " \"identifier\": \"" . $avleveringsidentifikator . "\"" . "\n";
$identifiersOut .= " }," . "\n";
$identifiersOut .= " {" . "\n";
$identifiersOut .= " \"identifierType\": \"avtaleidentifikator\"," . "\n";
$identifiersOut .= " \"identifier\": \"" . $avtaleidentifikator . "\"" . "\n";
$identifiersOut .= " }," . "\n";
$identifiersOut .= " {" . "\n";
$identifiersOut .= " \"identifierType\": \"organisasjonsnummer\"," . "\n";
$identifiersOut .= " \"identifier\": \"" . $organisasjonsnummer . "\"" . "\n";
$identifiersOut .= " }" . "\n";
$identifiersOut .= " ]" . "\n";
$identifiersOut .= " }" . "\n";
$identifiersOut .= "]" . "\n";
if (file_put_contents($identifiersPath, $identifiersOut) === false)
{
exitWithError("Failed to write to file: " . $identifiersPath);
}
// Add submission agreement
$submissionAgreements = 0;
for ($fileIndex = 0; $fileIndex < count($filePathList); $fileIndex++)
{
// Get file info
$filePath = $filePathList[$fileIndex];
$fileItemType = $fileItemTypeList[$fileIndex];
// Skip files that are not submission agreements
if (!isSubmissionAgreement($filePath))
{
continue;
}
// Copy file
$submissionAgreementPath = $otherPath . "/journal/" . basename($filePath);
array_push($checksumPaths, "OTHER/journal/" . basename($filePath));
if (!copy($filePath, $submissionAgreementPath))
{
exitWithError("Failed to copy file $filePath to $submissionAgreementPath");
}
$submissionAgreements++;
}
if ($submissionAgreements < 1)
{
exitWithError("Failed to find submission agreement");
}
if ($submissionAgreements > 1)
{
exitWithError("Found more than one submission agreement");
}
// Remove submission agreement metadata
$temporaryFileNames = array();
$temporaryMetadataList = array();
for ($i = 0; $i < count($filePathList); $i++)
{
if (!isSubmissionAgreement($filePathList[$i]))
{
array_push($temporaryFileNames, basename($filePathList[$i]));
array_push($temporaryMetadataList, $metadataList[$i]);
}
}
// Create metadata file
$metadataOut = "$metadataPath/metadata.csv";
if (!createMetadata($temporaryMetadataList, $metadataOut, $temporaryFileNames, $metadataTemplate, $configuration))
{
exitWithError("Failed to create metadata file");
}
// Fetch objects
for ($fileIndex = 0; $fileIndex < count($filePathList); $fileIndex++)
{
// Get file info
$filePath = $filePathList[$fileIndex];
$fileItemType = $fileItemTypeList[$fileIndex];
// Skip submission agreement
if (isSubmissionAgreement($filePath))
{
continue;
}
if ($fileItemType != FILE_ITEM_TYPE_FILE)
{
exitWithError("Invalid file item type: " . $fileItemType);
}
$destination = $objectsPath . "/" . basename($filePath);
if (!copy($filePath, $destination))
{
exitWithError("Failed to copy file $filePath to $destination");
}
array_push($checksumPaths, "OTHER/objekter/" . basename($filePath));
}
// Create checksum file
$checksumFilePath = $metadataPath . "/checksum.md5";
foreach ($checksumPaths as $relativePath)
{
$absolutePath = $sipPath . "/" . $relativePath;
$checksum = md5_file($absolutePath);
if ($checksum === false)
{
exitWithError("Failed to calculate checksum for file: " . $absolutePath);
}
if (file_put_contents($checksumFilePath, $checksum . " " . $relativePath . "\n", FILE_APPEND | LOCK_EX) === false)
{
exitWithError("Failed to write to file: " . $checksumFilePath);
}
}
// Setup path for SIP to be archived
array_push($archiveFiles, basename($sipPath));
// Create AVLXML item on server
$serverAddress = $configuration->getValue("ProductionServerAddress");
$url="http://$serverAddress/api/v1/prod/avlxml";
$ch = curl_init("$url");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // TODO REMOVE ME!
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // TODO REMOVE ME!
curl_setopt($ch, CURLOPT_POST, 1);
$avlxml=json_encode($avlxml);
$post = [
'data' => "{\"xml\": $avlxml, \"validate\" : \"0\", \"indextype\" : \"\", \"avlxmltype\" : \"3\" }",
];
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$data = curl_exec($ch);
if (!$data)
{
exitWithError("Failed to register avlxml in server");
}
$response = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
if ( "$response" != "201" )
{
exitWithError("Got error response from production server: $response");
}
}
else if ($configuration->getValue("OutputFormat") == OUTPUT_FORMAT_BAGIT_V097)
{
// Create a SIP in bagit format
// - One or multiple files per SIP
// - One metadata row per file
// - Directories are supported
// - Directory structure is maintained
// - Can be processed by Archivematica
//
// Bag structure:
// <file_basename>
// metadata
// metadata.csv
// data
// <filename_1>
// <filename_2>
// bagit.txt
// manifest-md5.txt
$dataRootDirectory = "";
$dataDirectory = "";
for ($fileIndex = 0; $fileIndex < count($filePathList); $fileIndex++)
{
// Get file info
$filePath = $filePathList[$fileIndex];
$fileName = basename($filePath);
$fileItemType = $fileItemTypeList[$fileIndex];
$relativeFilePath = $relativeFilePathList[$fileIndex];
if ($fileItemType != FILE_ITEM_TYPE_FILE && $fileItemType != FILE_ITEM_TYPE_DIRECTORY)
{
exitWithError("Invalid file item type: $fileItemType");
}
if ($fileIndex == 0)
{
if (count($filePathList) < 1)
{
exitWithError("One or multiple files is supported for format OUTPUT_FORMAT_BAGIT_V097, " . count($filePathList) . " was given");
}
$dataRootDirectory = "$tempDirectoryPath";
// Create data directory
$dataDirectory = "$dataRootDirectory/data";
if (!mkdir($dataDirectory, 0777, false))
{
exitWithError("Failed to create data directory");
}
array_push($archiveFiles, basename($dataDirectory));
// Create metadata directory
$metadataDirectory = "$dataRootDirectory/metadata";
if (!mkdir($metadataDirectory, 0777, false))
{
exitWithError("Failed to create metadata directory");
}
// Create metadata file
$fileNames = array();
for ($i = 0; $i < count($filePathList); $i++)
{
array_push($fileNames, basename($filePathList[$i]));
}
$metadataOut = "$metadataDirectory/metadata.csv";
if (!createMetadata($metadataList, $metadataOut, $fileNames, $metadataTemplate, $configuration))
{
exitWithError("Failed to create metadata file");
}
// Include metadata if generated
if (is_file($metadataOut))
{
array_push($archiveFiles, basename($metadataDirectory));
}
// Create BagIt description file
$descriptionOut = "$dataRootDirectory/bagit.txt";
if (!createBagitDescriptionFile($descriptionOut, "0.97"))
{
exitWithError("Failed to create BagIt description file");
}
array_push($archiveFiles, basename($descriptionOut));
// Create checksum manifest
$checksumManifestOut = "$dataRootDirectory/manifest-md5.txt";
if (!createChecksumManifestFile($checksumManifestOut, $filePathList, $relativeFilePathList))
{
exitWithError("Failed to create checksum manifest file");
}
array_push($archiveFiles, basename($checksumManifestOut));
}
// Add data
$source = $filePath;
$destination = "$dataDirectory/$relativeFilePath";
if ($fileItemType == FILE_ITEM_TYPE_DIRECTORY)
{
if (!mkdir($destination, 0777, false))
{
exitWithError("Failed to create directory: $destination");
}
}
else
{
if (!copy($source, $destination))
{
exitWithError("Failed to copy file '$source' to '$destination'");
}
}
}
}
else if ($configuration->getValue("OutputFormat") == OUTPUT_FORMAT_BAGIT_V1)
{
// Create a SIP in bagit format
// - One or multiple files per SIP
// - One metadata row per file
// - Directories not supported
// - Directory structure is ignored
// - Can be processed by Archivematica if repackaged
//
// Bag structure:
// <file_basename>
// metadata
// metadata.csv
// <filename_1>
// <filename_2>
$dataRootDirectory = "";
for ($fileIndex = 0; $fileIndex < count($filePathList); $fileIndex++)
{
// Get file info
$filePath = $filePathList[$fileIndex];
$fileName = basename($filePath);
$fileItemType = $fileItemTypeList[$fileIndex];
if ($fileItemType == FILE_ITEM_TYPE_DIRECTORY)
{
exitWithError("Directories are not allowed for format: " . OUTPUT_FORMAT_BAGIT_V1);
}
else if ($fileItemType != FILE_ITEM_TYPE_FILE)
{