-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDownloadGedcomWithURL.php
More file actions
2465 lines (2089 loc) · 107 KB
/
DownloadGedcomWithURL.php
File metadata and controls
2465 lines (2089 loc) · 107 KB
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
/**
* webtrees: online genealogy
* Copyright (C) 2024 webtrees development team
* <http://webtrees.net>
*
* Fancy Research Links (webtrees custom module):
* Copyright (C) 2022 Carmen Just
* <https://justcarmen.nl>
*
* ExtendedImportExport (webtrees custom module):
* Copyright (C) 2025 Markus Hemprich
* <http://www.familienforschung-hemprich.de>
*
* This program 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.
* This program 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 this program. If not, see <https://www.gnu.org/licenses/>.
*
*
* ExtendedImportExport
*
* A weebtrees(https://webtrees.net) 2.1 custom module for advanced GEDCOM import, export
* and filter operations. The module also supports remote downloads/uploads via URL requests.
*
*/
declare(strict_types=1);
namespace Jefferson49\Webtrees\Module\ExtendedImportExport;
use Fig\Http\Message\RequestMethodInterface;
use Fig\Http\Message\StatusCodeInterface;
use Fisharebest\Localization\Translation;
use Fisharebest\Webtrees\Auth;
use Fisharebest\Webtrees\Cli\Console;
use Fisharebest\Webtrees\Encodings\ANSEL;
use Fisharebest\Webtrees\Encodings\ASCII;
use Fisharebest\Webtrees\Encodings\UTF16BE;
use Fisharebest\Webtrees\Encodings\UTF8;
use Fisharebest\Webtrees\Encodings\Windows1252;
use Fisharebest\Webtrees\Exceptions\FileUploadException;
use Fisharebest\Webtrees\Factories\GedcomRecordFactory;
use Fisharebest\Webtrees\Family;
use Fisharebest\Webtrees\FlashMessages;
use Fisharebest\Webtrees\Gedcom;
use Fisharebest\Webtrees\GedcomFilters\GedcomEncodingFilter;
use Fisharebest\Webtrees\GedcomRecord;
use Fisharebest\Webtrees\Http\RequestHandlers\CreateTreeAction;
use Fisharebest\Webtrees\Http\RequestHandlers\HomePage;
use Fisharebest\Webtrees\Http\RequestHandlers\MergeTreesAction;
use Fisharebest\Webtrees\Http\RequestHandlers\RenumberTreeAction;
use Fisharebest\Webtrees\I18N;
use Fisharebest\Webtrees\Individual;
use Fisharebest\Webtrees\Location;
use Fisharebest\Webtrees\Media;
use Fisharebest\Webtrees\Note;
use Fisharebest\Webtrees\Module\AbstractModule;
use Fisharebest\Webtrees\Module\ModuleConfigInterface;
use Fisharebest\Webtrees\Module\ModuleConfigTrait;
use Fisharebest\Webtrees\Module\ModuleCustomInterface;
use Fisharebest\Webtrees\Module\ModuleCustomTrait;
use Fisharebest\Webtrees\Module\ModuleDataFixInterface;
use Fisharebest\Webtrees\Module\ModuleDataFixTrait;
use Fisharebest\Webtrees\Module\ModuleGlobalInterface;
use Fisharebest\Webtrees\Module\ModuleGlobalTrait;
use Fisharebest\Webtrees\Module\ModuleListInterface;
use Fisharebest\Webtrees\Module\ModuleListTrait;
use Fisharebest\Webtrees\Registry;
use Fisharebest\Webtrees\Repository;
use Fisharebest\Webtrees\Services\AdminService;
use Fisharebest\Webtrees\Services\DataFixService;
use Fisharebest\Webtrees\Services\GedcomImportService;
use Fisharebest\Webtrees\Services\PhpService;
use Fisharebest\Webtrees\Services\TreeService;
use Fisharebest\Webtrees\Services\TimeoutService;
use Fisharebest\Webtrees\Session;
use Fisharebest\Webtrees\Source;
use Fisharebest\Webtrees\Submitter;
use Fisharebest\Webtrees\Site;
use Fisharebest\Webtrees\Tree;
use Fisharebest\Webtrees\Validator;
use Fisharebest\Webtrees\View;
use Fisharebest\Webtrees\Webtrees;
use Illuminate\Support\Collection;
use Jefferson49\Webtrees\Exceptions\GithubCommunicationError;
use Jefferson49\Webtrees\Helpers\GithubService;
use Jefferson49\Webtrees\Internationalization\MoreI18N;
use Jefferson49\Webtrees\Helpers\Functions;
use League\Flysystem\FilesystemException;
use League\Flysystem\FilesystemOperator;
use League\Flysystem\UnableToWriteFile;
use Nyholm\Psr7\Factory\Psr17Factory;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\StreamInterface;
use Psr\Http\Message\StreamFactoryInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\StreamOutput;
use ErrorException;
use CURLFile;
use RuntimeException;
use ReflectionClass;
use stdClass;
use Throwable;
use function substr;
use function str_replace;
class DownloadGedcomWithURL extends AbstractModule implements
ModuleCustomInterface,
ModuleConfigInterface,
RequestHandlerInterface,
ModuleDataFixInterface,
ModuleGlobalInterface,
ModuleListInterface
{
use ModuleCustomTrait;
use ModuleConfigTrait;
use ModuleDataFixTrait;
use ModuleGlobalTrait;
use ModuleListTrait;
//The data fix service
private DataFixService $data_fix_service;
//The tree service
private TreeService $tree_service;
//The Gedcom filter Service
private FilteredGedcomExportService $filtered_gedcom_export_service;
//A stream factory
private StreamFactoryInterface $stream_factory;
//The root file system
private FilesystemOperator $root_filesystem;
//A set of patterns for tag combinations, which has already been matched in a data fix
private array $matched_pattern_for_tag_combination_in_data_fix;
//A set of Gedcom filters, which is used in the data fix
private array $gedcom_filters_in_data_fix;
//A set of standard parameters to be used for calling Gedcom filter
private array $standard_params;
//Path for temporary GEDCOM files
private string $gedcom_temp_path;
//Custom module version
public const CUSTOM_VERSION = '4.2.11';
//Routes
protected const ROUTE_REMOTE_ACTION_OLD = '/DownloadGedcomWithURL';
public const ROUTE_REMOTE_ACTION = '/ExtendedImportExport';
protected const ROUTE_EXPORT_PAGE = '/ExtendedGedcomExport';
protected const ROUTE_IMPORT_PAGE = '/ExtendedGedcomImport';
protected const ROUTE_CONVERT_PAGE = '/ExtendedGedcomConvert';
protected const ROUTE_SELECTION_PAGE = '/ExtendedImportExportSelection';
//Github repository
public const GITHUB_REPO = 'Jefferson49/ExtendedImportExport';
//Github API URL to get the information about the latest releases
public const GITHUB_API_LATEST_VERSION = 'https://api.github.com/repos/'. self::GITHUB_REPO . '/releases/latest';
public const GITHUB_API_TAG_NAME_PREFIX = '"tag_name":"v';
//Author of custom module
public const CUSTOM_AUTHOR = 'Markus Hemprich';
//Old module name (based on the installation folder)
public const OLD_MODULE_NAME_FOR_PREFERENCES = '_download_gedcom_with_url_';
//Strings cooresponding to variable names
public const VAR_GEDOCM_FILTER = 'gedcom_filter';
public const VAR_GEDCOM_FILTER_LIST = 'gedcom_filter_list';
public const VAR_DATA_FIX_TYPES = 'types';
public const VAR_DATA_FIX_DEFAULT_TYPE = 'default_type';
//Prefences, Settings
public const PREF_MODULE_VERSION = 'module_version';
public const PREF_DEFAULT_TREE_NAME = 'default_tree_name';
public const PREF_SECRET_KEY = "secret_key";
public const PREF_USE_HASH = "use_hash";
public const PREF_ALLOW_REMOTE_DOWNLOAD = "allow_remote_download";
public const PREF_ALLOW_REMOTE_UPLOAD = "allow_remote_upload";
public const PREF_ALLOW_REMOTE_SAVE = "allow_remote_save";
public const PREF_ALLOW_REMOTE_CONVERT = "allow_remote_convert";
public const PREF_ALLOW_REMOTE_GEDBAS_UPLOAD = 'allow_remote_gedbas_upload';
public const PREF_SHOW_MENU_LIST_ITEM = "show_menu_list_item";
public const PREF_ALLOW_GEDBAS_UPLOAD = 'allow_gedbas_upload';
public const PREF_USE_HEAD_NOTE_FOR_GEDBAS = 'use_head_note_for_gedbas';
public const PREF_FOLDER_TO_SAVE = "folder_to_save";
public const PREF_DEFAULT_GEDCOM_FILTER1 = 'default_gedcom_filter1';
public const PREF_DEFAULT_GEDCOM_FILTER2 = 'default_gedcom_filter2';
public const PREF_DEFAULT_GEDCOM_FILTER3 = 'default_gedcom_filter3';
public const PREF_DEFAULT_PRIVACY_LEVEL = 'default_privacy_level';
public const PREF_DEFAULT_EXPORT_FORMAT = 'default_export_format';
public const PREF_DEFAULT_ENCODING = 'default_encoding';
public const PREF_DEFAULT_ENDING = 'default_ending';
public const PREF_DEFAULT_TIME_STAMP = 'default_time_stamp';
//Preferences for trees
public const TREE_PREF_GEDBAS_ID = 'GEDBAS_Id';
public const TREE_PREF_GEDBAS_TITLE = 'GEDBAS_title';
public const TREE_PREF_GEDBAS_APIKEY = 'GEDBAS_apiKey';
public const TREE_PREF_GEDBAS_DESCRIPTION = 'GEDBAS_description';
//Actions
public const ACTION_DOWNLOAD = 'download';
public const ACTION_SAVE = 'save';
public const ACTION_BOTH = 'both';
public const ACTION_GEDBAS = 'GEDBAS';
public const ACTION_UPLOAD = 'upload';
public const ACTION_CONVERT = 'convert';
public const ACTION_RENUMBER_XREF = 'renumber_tree';
public const ACTION_MERGE_TREES = 'merge_trees';
public const ACTION_CREATE_TREE = 'create_tree';
public const CALLED_FROM_CONTROL_PANEL = "called_from_control_panel";
//Time stamp values
public const TIME_STAMP_PREFIX = 'prefix';
public const TIME_STAMP_POSTFIX = 'postfix';
public const TIME_STAMP_NONE = 'none';
//Session values
public const SESSION_GEDCOM_FILTERS = 'gedcom_filters';
public const SESSION_RECORD_TYPE = 'record_type';
public const SESSION_RECORDS_TO_FIX = 'records_to_fix';
//Alert tpyes
public const ALERT_DANGER = 'alert_danger';
public const ALERT_SUCCESS = 'alert_success';
//Maximum level of includes for Gedcom filters
private const MAXIMUM_FILTER_INCLUDE_LEVELS = 10;
//Record types (for record selection in datafix)
private const RECORD_TYPE_ALL = 'ALL';
private const RECORD_TYPE_HEAD = 'HEAD';
//Others
private const UPLOAD_TEMP_FOLDER = 'tmp/';
/**
* DownloadGedcomWithURL constructor.
*/
public function __construct()
{
//Caution: Do not use the shared library jefferson47/webtrees-common within __construct(),
// because it might result in wrong autoload behavior
}
/**
* Initialization.
*
* @return void
*/
public function boot(): void
{
//Check update of module version
$this->checkModuleVersionUpdate();
//Initialize services etc.
$response_factory = Functions::getFromContainer(ResponseFactoryInterface::class);
$this->stream_factory = new Psr17Factory();
$this->data_fix_service = New DataFixService();
$this->tree_service = new TreeService(new GedcomImportService);
$this->filtered_gedcom_export_service = new FilteredGedcomExportService($response_factory, $this->stream_factory);
//Initialize variables
$this->matched_pattern_for_tag_combination_in_data_fix = [];
$this->gedcom_filters_in_data_fix = [];
$this->gedcom_filters_loaded_in_data_fix = false;
$this->root_filesystem = Registry::filesystem()->root();
$this->standard_params = [];
$this->gedcom_temp_path = 'modules_v4/' . basename(__DIR__) . '/resources/temp/';
$router = Registry::routeFactory()->routeMap();
//Register a route for remote requests
$router
->get(static::class, self::ROUTE_REMOTE_ACTION, $this)
->allows(RequestMethodInterface::METHOD_POST);
//Register the old route of the former DownloadGedcomWithURL module
$router
->get('DownloadGedcomWithURL', self::ROUTE_REMOTE_ACTION_OLD, $this)
->allows(RequestMethodInterface::METHOD_POST);
//Register a route for the selection view
$router
->get(SelectionPage::class, self::ROUTE_SELECTION_PAGE)
->allows(RequestMethodInterface::METHOD_POST);
//Register a route for the import view
$router
->get(ImportGedcomPage::class, self::ROUTE_IMPORT_PAGE)
->allows(RequestMethodInterface::METHOD_POST);
//Register a route for the export view
$router
->get(ExportGedcomPage::class, self::ROUTE_EXPORT_PAGE)
->allows(RequestMethodInterface::METHOD_POST);
//Register a route for the convert view
$router
->get(ConvertGedcomPage::class, self::ROUTE_CONVERT_PAGE)
->allows(RequestMethodInterface::METHOD_POST);
// Register a namespace for the views.
View::registerNamespace($this->name(), $this->resourcesFolder() . 'views/');
}
/**
* {@inheritDoc}
*
* @return string
*
* @see \Fisharebest\Webtrees\Module\AbstractModule::title()
*/
public function title(): string
{
return I18N::translate('Extended Import/Export');
}
/**
* {@inheritDoc}
*
* @return string
*
* @see \Fisharebest\Webtrees\Module\AbstractModule::description()
*/
public function description(): string
{
/* I18N: Description of the “AncestorsChart” module */
return I18N::translate('A custom module for advanced GEDCOM import, export, and filter operations. The module also supports remote downloads/uploads/filters via URL requests.');
}
/**
* {@inheritDoc}
*
* @return string
*
* @see \Fisharebest\Webtrees\Module\AbstractModule::resourcesFolder()
*/
public function resourcesFolder(): string
{
return __DIR__ . '/resources/';
}
/**
* Get the active module name, e.g. the name of the currently running module
*
* @return string
*/
public static function activeModuleName(): string
{
return '_' . basename(__DIR__) . '_';
}
/**
* {@inheritDoc}
*
* @return string
*
* @see \Fisharebest\Webtrees\Module\ModuleCustomInterface::customModuleAuthorName()
*/
public function customModuleAuthorName(): string
{
return self::CUSTOM_AUTHOR;
}
/**
* {@inheritDoc}
*
* @return string
*
* @see \Fisharebest\Webtrees\Module\ModuleCustomInterface::customModuleVersion()
*/
public function customModuleVersion(): string
{
return self::CUSTOM_VERSION;
}
/**
* {@inheritDoc}
*
* @return string
*
* @see \Fisharebest\Webtrees\Module\ModuleCustomInterface::customModuleLatestVersion()
*/
public function customModuleLatestVersion(): string
{
return Registry::cache()->file()->remember(
$this->name() . '-latest-version',
function (): string {
try {
//Get latest release from GitHub
return GithubService::getLatestReleaseTag(self::GITHUB_REPO);
}
catch (GithubCommunicationError $ex) {
// Can't connect to GitHub?
return $this->customModuleVersion();
}
},
86400
);
}
/**
* {@inheritDoc}
*
* @return string
*
* @see \Fisharebest\Webtrees\Module\ModuleCustomInterface::customModuleSupportUrl()
*/
public function customModuleSupportUrl(): string
{
return 'https://github.com/' . self::GITHUB_REPO;
}
/**
* {@inheritDoc}
*
* @param string $language
*
* @return array
*
* @see \Fisharebest\Webtrees\Module\ModuleCustomInterface::customTranslations()
*/
public function customTranslations(string $language): array
{
$lang_dir = $this->resourcesFolder() . 'lang/';
$file = $lang_dir . $language . '.mo';
if (file_exists($file)) {
return (new Translation($file))->asArray();
} else {
return [];
}
}
/**
* View module settings in control panel
*
* @param ServerRequestInterface $request
*
* @return ResponseInterface
*/
public function getAdminAction(ServerRequestInterface $request): ResponseInterface
{
$this->layout = 'layouts/administration';
$base_url = Validator::attributes($request)->string('base_url');
//Load Gedcom filters
try {
self::loadGedcomFilterClasses();
}
catch (DownloadGedcomWithUrlException $ex) {
FlashMessages::addMessage($ex->getMessage(), 'danger');
}
//Generate a tree list with all the trees, the user has access to; authorization is checked in tree service
$tree_list = $this->tree_service->titles();
//Check the Gedcom filters, which are defined in the prefernces
$this->checkFilterPreferences(self::PREF_DEFAULT_GEDCOM_FILTER1);
$this->checkFilterPreferences(self::PREF_DEFAULT_GEDCOM_FILTER2);
$this->checkFilterPreferences(self::PREF_DEFAULT_GEDCOM_FILTER3);
$data_folder = str_replace('\\', '/', Registry::filesystem()->dataName());
$root_folder = str_replace('\\', '/', Registry::filesystem()->rootName());
$data_folder_relative = str_replace($root_folder, '', $data_folder);
return $this->viewResponse(
$this->name() . '::settings',
[
'title' => $this->title(),
'tree_list' => $tree_list,
'base_url' => $base_url,
self::VAR_GEDCOM_FILTER_LIST => $this->getGedcomFilterList(),
self::PREF_SECRET_KEY => $this->getPreference(self::PREF_SECRET_KEY, ''),
self::PREF_USE_HASH => boolval($this->getPreference(self::PREF_USE_HASH, '1')),
self::PREF_ALLOW_REMOTE_DOWNLOAD => boolval($this->getPreference(self::PREF_ALLOW_REMOTE_DOWNLOAD, '0')),
self::PREF_ALLOW_REMOTE_UPLOAD => boolval($this->getPreference(self::PREF_ALLOW_REMOTE_UPLOAD, '0')),
self::PREF_ALLOW_REMOTE_SAVE => boolval($this->getPreference(self::PREF_ALLOW_REMOTE_SAVE, '0')),
self::PREF_ALLOW_REMOTE_CONVERT => boolval($this->getPreference(self::PREF_ALLOW_REMOTE_CONVERT, '0')),
self::PREF_ALLOW_REMOTE_GEDBAS_UPLOAD => boolval($this->getPreference(self::PREF_ALLOW_REMOTE_GEDBAS_UPLOAD, '0')),
self::PREF_SHOW_MENU_LIST_ITEM => boolval($this->getPreference(self::PREF_SHOW_MENU_LIST_ITEM, '1')),
self::PREF_ALLOW_GEDBAS_UPLOAD => boolval($this->getPreference(self::PREF_ALLOW_GEDBAS_UPLOAD, '0')),
self::PREF_USE_HEAD_NOTE_FOR_GEDBAS => boolval($this->getPreference(self::PREF_USE_HEAD_NOTE_FOR_GEDBAS, '0')),
self::PREF_FOLDER_TO_SAVE => $this->getPreference(self::PREF_FOLDER_TO_SAVE, $data_folder_relative),
self::PREF_DEFAULT_GEDCOM_FILTER1 => $this->getPreference(self::PREF_DEFAULT_GEDCOM_FILTER1, ''),
self::PREF_DEFAULT_GEDCOM_FILTER2 => $this->getPreference(self::PREF_DEFAULT_GEDCOM_FILTER2, ''),
self::PREF_DEFAULT_GEDCOM_FILTER3 => $this->getPreference(self::PREF_DEFAULT_GEDCOM_FILTER3, ''),
self::PREF_DEFAULT_PRIVACY_LEVEL => $this->getPreference(self::PREF_DEFAULT_PRIVACY_LEVEL, 'none'),
self::PREF_DEFAULT_EXPORT_FORMAT => $this->getPreference(self::PREF_DEFAULT_EXPORT_FORMAT, 'gedcom'),
self::PREF_DEFAULT_ENCODING => $this->getPreference(self::PREF_DEFAULT_ENCODING, UTF8::NAME),
self::PREF_DEFAULT_ENDING => $this->getPreference(self::PREF_DEFAULT_ENDING, 'CRLF'),
self::PREF_DEFAULT_TIME_STAMP => $this->getPreference(self::PREF_DEFAULT_TIME_STAMP, self::TIME_STAMP_NONE),
]
);
}
/**
* Save module settings after returning from control panel
*
* @param ServerRequestInterface $request
*
* @return ResponseInterface
*/
public function postAdminAction(ServerRequestInterface $request): ResponseInterface
{
$save = Validator::parsedBody($request)->string('save', '');
$use_hash = Validator::parsedBody($request)->boolean(self::PREF_USE_HASH, false);
$use_hash = Validator::parsedBody($request)->boolean(self::PREF_USE_HASH, false);
$allow_remote_download = Validator::parsedBody($request)->boolean(self::PREF_ALLOW_REMOTE_DOWNLOAD, false);
$allow_remote_upload = Validator::parsedBody($request)->boolean(self::PREF_ALLOW_REMOTE_UPLOAD, false);
$allow_remote_save = Validator::parsedBody($request)->boolean(self::PREF_ALLOW_REMOTE_SAVE, false);
$allow_remote_convert = Validator::parsedBody($request)->boolean(self::PREF_ALLOW_REMOTE_CONVERT, false);
$allow_remote_gedbas_upload = Validator::parsedBody($request)->boolean(self::PREF_ALLOW_REMOTE_GEDBAS_UPLOAD, false);
$new_secret_key = Validator::parsedBody($request)->string('new_secret_key', '');
$folder_to_save = Validator::parsedBody($request)->string(self::PREF_FOLDER_TO_SAVE, Site::getPreference('INDEX_DIRECTORY'));
$show_menu_list_item = Validator::parsedBody($request)->boolean(self::PREF_SHOW_MENU_LIST_ITEM, false);
$allow_gedbas_upload = Validator::parsedBody($request)->boolean(self::PREF_ALLOW_GEDBAS_UPLOAD, false);
$use_head_note_for_gedbas = Validator::parsedBody($request)->boolean(self::PREF_USE_HEAD_NOTE_FOR_GEDBAS, false);
$default_gedcom_filter1 = Validator::parsedBody($request)->string(self::PREF_DEFAULT_GEDCOM_FILTER1, '');
$default_gedcom_filter2 = Validator::parsedBody($request)->string(self::PREF_DEFAULT_GEDCOM_FILTER2, '');
$default_gedcom_filter3 = Validator::parsedBody($request)->string(self::PREF_DEFAULT_GEDCOM_FILTER3, '');
$default_privacy_level = Validator::parsedBody($request)->string(self::PREF_DEFAULT_PRIVACY_LEVEL, 'none');
$default_export_format = Validator::parsedBody($request)->string(self::PREF_DEFAULT_EXPORT_FORMAT, 'gedcom');
$default_encoding = Validator::parsedBody($request)->string(self::PREF_DEFAULT_ENCODING, UTF8::NAME);
$default_ending = Validator::parsedBody($request)->string(self::PREF_DEFAULT_ENDING, 'CRLF');
$default_time_stamp = Validator::parsedBody($request)->string(self::PREF_DEFAULT_TIME_STAMP, self::TIME_STAMP_NONE);
//Save the received settings to the user preferences
if ($save === '1') {
$new_key_error = false;
//If no new secret key is provided
if($new_secret_key === '') {
//If use hash changed from true to false, reset key (hash cannot be used any more)
if(boolval($this->getPreference(self::PREF_USE_HASH, '0')) && !$use_hash) {
$this->setPreference(self::PREF_SECRET_KEY, '');
}
//If use hash changed from false to true, take old key (for planned encryption) and save as hash
elseif(!boolval($this->getPreference(self::PREF_USE_HASH, '0')) && $use_hash) {
$new_secret_key = $this->getPreference(self::PREF_SECRET_KEY, '');
$hash_value = password_hash($new_secret_key, PASSWORD_BCRYPT);
$this->setPreference(self::PREF_SECRET_KEY, $hash_value);
}
//If no new secret key and no changes in hashing, do nothing
}
//If new secret key is too short
elseif(strlen($new_secret_key)<8) {
$message = I18N::translate('The provided secret key is too short. Please provide a minimum length of 8 characters.');
FlashMessages::addMessage($message, 'danger');
$new_key_error = true;
}
//If new secret key does not escape correctly
elseif($new_secret_key !== e($new_secret_key)) {
$message = I18N::translate('The provided secret key contains characters, which are not accepted. Please provide a different key.');
FlashMessages::addMessage($message, 'danger');
$new_key_error = true;
}
//If new secret key shall be stored with a hash, create and save hash
elseif($use_hash) {
$hash_value = password_hash($new_secret_key, PASSWORD_BCRYPT);
$this->setPreference(self::PREF_SECRET_KEY, $hash_value);
}
//Otherwise, simply store the new secret key
else {
$this->setPreference(self::PREF_SECRET_KEY, $new_secret_key);
}
//Check and set folder to save
if (substr_compare($folder_to_save, '/', -1, 1) !== 0) {
$folder_to_save .= '/';
}
if (substr_compare($folder_to_save, '/', 0, 1) === 0) {
$folder_to_save = substr($folder_to_save, 1,null);
}
if ($folder_to_save === '') {
$folder_to_save = '/';
}
if (is_dir($folder_to_save)) {
$this->setPreference(self::PREF_FOLDER_TO_SAVE, $folder_to_save);
} else {
FlashMessages::addMessage(I18N::translate('The folder settings could not be saved, because the folder "%s" does not exist.', e($folder_to_save)), 'danger');
}
//Save settings to preferences
if(!$new_key_error) {
$this->setPreference(self::PREF_USE_HASH, $use_hash ? '1' : '0');
}
//Save settingss
$this->setPreference(self::PREF_ALLOW_REMOTE_DOWNLOAD, $allow_remote_download ? '1' : '0');
$this->setPreference(self::PREF_ALLOW_REMOTE_UPLOAD, $allow_remote_upload ? '1' : '0');
$this->setPreference(self::PREF_ALLOW_REMOTE_SAVE, $allow_remote_save ? '1' : '0');
$this->setPreference(self::PREF_ALLOW_REMOTE_CONVERT, $allow_remote_convert ? '1' : '0');
$this->setPreference(self::PREF_ALLOW_REMOTE_GEDBAS_UPLOAD, $allow_remote_gedbas_upload ? '1' : '0');
$this->setPreference(self::PREF_SHOW_MENU_LIST_ITEM, $show_menu_list_item ? '1' : '0');
$this->setPreference(self::PREF_ALLOW_GEDBAS_UPLOAD, $allow_gedbas_upload ? '1' : '0');
$this->setPreference(self::PREF_USE_HEAD_NOTE_FOR_GEDBAS, $use_head_note_for_gedbas ? '1' : '0');
//Save default settings to preferences
$this->setPreference(self::PREF_DEFAULT_GEDCOM_FILTER1, $default_gedcom_filter1);
$this->setPreference(self::PREF_DEFAULT_GEDCOM_FILTER2, $default_gedcom_filter2);
$this->setPreference(self::PREF_DEFAULT_GEDCOM_FILTER3, $default_gedcom_filter3);
$this->setPreference(self::PREF_DEFAULT_PRIVACY_LEVEL, $default_privacy_level);
$this->setPreference(self::PREF_DEFAULT_EXPORT_FORMAT, $default_export_format);
$this->setPreference(self::PREF_DEFAULT_ENCODING, $default_encoding);
$this->setPreference(self::PREF_DEFAULT_ENDING, $default_ending);
$this->setPreference(self::PREF_DEFAULT_TIME_STAMP, $default_time_stamp);
//Finally, show a success message
$message = I18N::translate('The preferences for the module "%s" were updated.', $this->title());
FlashMessages::addMessage($message, 'success');
}
return redirect($this->getConfigLink());
}
/**
* {@inheritDoc}
*
* @param Tree $tree
* @param array $parameters
*
* @return string
*
* @see \Fisharebest\Webtrees\Module\ModuleListInterface::listUrl()
*/
public function listUrl(Tree $tree, array $parameters = []): string
{
return route(SelectionPage::class, ['tree' => $tree->name()]);
}
/**
* {@inheritDoc}
*
* @return string
*
* @see \Fisharebest\Webtrees\Module\ModuleGlobalInterface::headContent()
*/
public function headContent(): string
{
//Include CSS file in head of webtrees HTML to make sure it is always found
return '<link href="' . $this->assetUrl('css/extended-import-export.css') . '" type="text/css" rel="stylesheet" />';
}
/**
* {@inheritDoc}
*
* @param Tree $tree
*
* @return string
*
* @see \Fisharebest\Webtrees\Module\ModuleListInterface::listIsEmpty()
*/
public function listIsEmpty(Tree $tree): bool
{
if (!Auth::isAdmin() OR !boolval($this->getPreference(self::PREF_SHOW_MENU_LIST_ITEM, '1'))) {
return true;
}
return false;
}
/**
* {@inheritDoc}
*
* @return string
*
* @see \Fisharebest\Webtrees\Module\ModuleListInterface::listMenuClass()
*/
public function listMenuClass(): string
{
//CSS class for module Icon (included in CSS file) is returned to be shown in the list menu
return 'menu-list-extended-import-export';
}
/**
* Check if module version is new and start update activities if needed
*
* @return void
*/
public function checkModuleVersionUpdate(): void
{
$updated = false;
//If started for the very first time, try to migrate preferences of former module
if ($this->getPreference(self::PREF_MODULE_VERSION, '') === '') {
$this->migratePreferencesFromFormerModule();
$updated = true;
}
//Update custom module version if changed
if($this->getPreference(self::PREF_MODULE_VERSION, '') !== self::CUSTOM_VERSION) {
//Update module files
if (require __DIR__ . '/update_module_files.php') {
$this->setPreference(self::PREF_MODULE_VERSION, self::CUSTOM_VERSION);
$updated = true;
}
}
if ($updated) {
//Show flash message for update of preferences
$message = I18N::translate('The preferences for the custom module "%s" were sucessfully updated to the new module version %s.', $this->title(), self::CUSTOM_VERSION);
FlashMessages::addMessage($message, 'success');
}
}
/**
* Migration from former module DownloadGedcomWith URL to current module ExtendedImportExport
*
* @return void
*/
public function migratePreferencesFromFormerModule(): void {
$updated_settings = false;
//If secret key is already stored and secret key hashing preference is not available (i.e. before module version v3.0.1)
if( Functions::getPreferenceForModule(self::OLD_MODULE_NAME_FOR_PREFERENCES, self::PREF_SECRET_KEY, '') !== ''
&& Functions::getPreferenceForModule(self::OLD_MODULE_NAME_FOR_PREFERENCES, self::PREF_USE_HASH, '') === '') {
//Set secret key hashing to false
$this->setPreference(self::PREF_USE_HASH, '0');
$updated_settings = true;
}
$preferences = [
self::PREF_SECRET_KEY,
self::PREF_USE_HASH,
self::PREF_ALLOW_REMOTE_DOWNLOAD,
self::PREF_ALLOW_REMOTE_UPLOAD,
self::PREF_ALLOW_REMOTE_SAVE,
self::PREF_ALLOW_REMOTE_CONVERT,
self::PREF_SHOW_MENU_LIST_ITEM,
self::PREF_FOLDER_TO_SAVE,
self::PREF_DEFAULT_GEDCOM_FILTER1,
self::PREF_DEFAULT_GEDCOM_FILTER2,
self::PREF_DEFAULT_GEDCOM_FILTER3,
self::PREF_DEFAULT_PRIVACY_LEVEL,
self::PREF_DEFAULT_EXPORT_FORMAT,
self::PREF_DEFAULT_ENCODING,
self::PREF_DEFAULT_ENDING,
self::PREF_DEFAULT_TIME_STAMP,
];
foreach($preferences as $preference) {
$setting_value = Functions::getPreferenceForModule(self::OLD_MODULE_NAME_FOR_PREFERENCES, $preference, '');
if ($setting_value !== '') {
$this->setPreference($preference, $setting_value);
$updated_settings = true;
}
}
if ($updated_settings) {
//Show flash message for update of preferences
$message = I18N::translate('The preferences for the custom module %s were imported from the earlier custom module version %s.', $this->title(), 'DownloadGedcomWithURL');
FlashMessages::addMessage($message, 'success');
}
}
/**
* Check if a Gedcom filter is available. If not, reset Gedcom filter to none
*
* @param string $preference_name The preference name of an Gedcom filter
*
* @return string The class name of the Gedcom filter
*/
private function checkFilterPreferences(string $preference_name): string {
//Get a list with the class names of all available Gedcom filters
$gedcom_filter_list = $this->getGedcomFilterList();
//Filter name from preferences
$gedcom_filter_class_name = $this->getPreference($preference_name);
//If currently selected Gedcom filter is not in the available filter list, reset Gedcom filter to none
if (!array_key_exists($gedcom_filter_class_name, $gedcom_filter_list)) {
//Reset preference
$this->setPreference($preference_name, '');
//Create flash message
$message = I18N::translate('The preferences for the default GEDCOM filter were reset to "none", because the selected GEDCOM filter %s could not be found', $gedcom_filter_class_name);
FlashMessages::addMessage($message, 'danger');
$gedcom_filter_class_name = '';
}
//Validate the Gedcom filter
if ($gedcom_filter_class_name !== '' && ($error = $this->validateGedcomFilter($gedcom_filter_class_name)) !== '') {
FlashMessages::addMessage($error, 'danger');
}
return $gedcom_filter_class_name;
}
/**
* Send a response, depending on the client type
*
* @param string $text
* @param bool $is_error Whether the response contains an error
* @param bool $for_browser Whether the client is a browser and we respond with a view; otherwise plain text is returned, e.g. for scripts
*
* @return ResponseInterface
*/
public function sendResponse(string $text, bool $is_error = false, bool $for_browser = true): ResponseInterface
{
$title = $is_error ? MoreI18N::xlate('Error') : MoreI18N::xlate('Success');
if ($for_browser) {
//Return a view, i.e. for a browser
return $this->viewResponse($this->name() . '::alert', [
'title' => $title,
'tree' => null,
'alert_type' => $is_error ? DownloadGedcomWithURL::ALERT_DANGER : DownloadGedcomWithURL::ALERT_SUCCESS,
'module_name' => $this->title(),
'text' => $text,
]);
}
//Return plain text, e.g. for a script
return response($title . ': ' . $text, $is_error ? StatusCodeInterface::STATUS_OK : StatusCodeInterface::STATUS_OK);
}
/**
* Load classes for Gedcom filters
*
* @return string error message
*/
public static function loadGedcomFilterClasses(): string {
$name_space = str_replace('\\\\', '\\',__NAMESPACE__ ) .'\\';
$filter_files = scandir(dirname(__FILE__) . "/resources/filter/");
$onError = function ($level, $message, $file, $line) {
throw new ErrorException($message, 0, $level, $file, $line);
};
foreach ($filter_files as $file) {
if (substr_compare($file, '.php', -4, 4) === 0) {
$class_name = str_replace('.php', '', $file);
if (!class_exists($name_space . $class_name)) {
try {
set_error_handler($onError);
require __DIR__ . '/resources/filter/' . $file;
}
catch (Throwable $th) {
throw new DownloadGedcomWithUrlException(I18N::translate('A compilation error was detected in the following GEDCOM filter') . ': ' .
__DIR__ . '/resources/filter/' . $file . ', ' . I18N::translate('line') . ': ' . $th-> getLine() . ', ' . I18N::translate('error message') . ': ' . $th->getMessage());
}
finally {
restore_error_handler();
}
}
}
};
return '';
}
/**
* Get all available Gedcom filters
*
* @return array<string> An array with the class names all available Gedcom filters
*/
public function getGedcomFilterList(): array {
foreach (get_declared_classes() as $class_name) {
$name_space = str_replace('\\\\', '\\',__NAMESPACE__ ) .'\\';
if (strpos($class_name, $name_space) !== false) {
if (in_array($name_space . 'GedcomFilterInterface', class_implements($class_name))) {
if ($class_name !== $name_space . 'AbstractGedcomFilter') {
$filter = new $class_name();
$class_name = str_replace($name_space, '', $class_name);
$gedcom_filter_list[$class_name] = $filter->name();
}
}
}
}
uasort($gedcom_filter_list, function (string $a, string $b) {
return strcmp($a, $b);
});
$no_filter = ['' => I18N::translate('No filter')];
return $no_filter + $gedcom_filter_list;
}
/**
* Validate Gedcom filter
*
* @param $gedcom_filter_name
*
* @return string error message
*/
private function validateGedcomFilter($gedcom_filter_name): string {
//Check if Gedcom filter class is valid
$gedcom_filter_class_name = __NAMESPACE__ . '\\' . $gedcom_filter_name;
if (!class_exists($gedcom_filter_class_name) OR !($this->getInstanceOfGedcomFilter($gedcom_filter_class_name) instanceof GedcomFilterInterface)) {
return I18N::translate('The GEDCOM filter was not found') . ': ' . $gedcom_filter_name;
}
$gedcom_filter_instance = $this->getInstanceOfGedcomFilter($gedcom_filter_class_name);
//Validate the content of the Gedcom filter
$error = $gedcom_filter_instance !== null ? $gedcom_filter_instance->validate() : '';
if ($error !== '') {
return $error;
}
return '';
}
/**
* Check whether further filters are included in a list of Gedcom filters and add to Gedcom filter list accordingly
*
* @param array $gedcom_filter_set A set of (already inlcuded) Gedcom filters
* @param array $additional_filters A set of Gedcom filters to be checked and included
* @param array $include_structure A hierarchical list of included Gedcom filters to check loops etc.
*
* @return array
*/
private function addIncludedGedcomFilters(array $gedcom_filter_set, array $additional_filters, array $include_structure): array {
while (sizeof($additional_filters) > 0) {
//Get first item of Gedcom filter set and remove it from additional filter list
$gedcom_filter = array_shift($additional_filters);
//Add Gedcom filter to include structure
$include_structure[] = $gedcom_filter;
//Error if size of include structure exceeds maximum level
if (sizeof($include_structure) > self::MAXIMUM_FILTER_INCLUDE_LEVELS) {
$error = I18N::translate('The include hierarchy for GEDCOM filters exceeds the maximum level of %s includes.', (string) self::MAXIMUM_FILTER_INCLUDE_LEVELS);
if (in_array($gedcom_filter, $include_structure)) {
$error .= ' ' . I18N::translate('The following GEDCOM filter might cause a loop in the include structure, because it was detected more than once in the include hierarchy') . ': ' . (new ReflectionClass($gedcom_filter))->getShortName();
}
else {
$error .= ' ' . I18N::translate('Please check the include structure of the selected GEDCOM filters.');
}
throw new DownloadGedcomWithUrlException($error);
}
if ($gedcom_filter !== null) {
//Add include filters before
$gedcom_filter_set = array_merge($gedcom_filter_set, $this->addIncludedGedcomFilters([], $gedcom_filter->getIncludedFiltersBefore(), $include_structure));
//Add filter
array_push($gedcom_filter_set, $gedcom_filter);
//Add include filters after