Repository navigation
Expand file tree
/
Copy pathCustomModuleManager.php
More file actions
1384 lines (1131 loc) · 50.6 KB
/
Copy pathCustomModuleManager.php
File metadata and controls
1384 lines (1131 loc) · 50.6 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) 2026 webtrees development team
* <http://webtrees.net>
*
* Fancy Research Links (webtrees custom module):
* Copyright (C) 2026 Carmen Just
* <https://justcarmen.nl>
*
* CustomModuleManager (webtrees custom module):
* Copyright (C) 2026 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/>.
*
*
* CustomModuleManager
*
* A weebtrees(https://webtrees.net) 2.2 custom module to manage custom modules
*
*/
declare(strict_types=1);
namespace Jefferson49\Webtrees\Module\CustomModuleManager;
use Composer\Semver\Comparator;
use Composer\Semver\Semver;
use Composer\Semver\VersionParser;
use Fisharebest\Webtrees\Auth;
use Fisharebest\Webtrees\FlashMessages;
use Fisharebest\Webtrees\I18N;
use Fisharebest\Webtrees\Module\AbstractModule;
use Fisharebest\Webtrees\Module\ModuleConfigInterface;
use Fisharebest\Webtrees\Module\ModuleConfigTrait;
use Fisharebest\Webtrees\Module\ModuleCustomInterface;
use Fisharebest\Webtrees\Module\ModuleGlobalInterface;
use Fisharebest\Webtrees\Module\ModuleGlobalTrait;
use Fisharebest\Webtrees\Module\ModuleLanguageInterface;
use Fisharebest\Webtrees\Module\ModuleListInterface;
use Fisharebest\Webtrees\Module\ModuleListTrait;
use Fisharebest\Webtrees\Registry;
use Fisharebest\Webtrees\Services\ModuleService;
use Fisharebest\Webtrees\Validator;
use Fisharebest\Webtrees\Session;
use Fisharebest\Webtrees\Tree;
use Fisharebest\Webtrees\View;
use Fisharebest\Webtrees\Webtrees;
use Jefferson49\Webtrees\Exceptions\GithubCommunicationError;
use Jefferson49\Webtrees\Exceptions\HostingPlatformCommunicationError;
use Jefferson49\Webtrees\Helpers\Functions;
use Jefferson49\Webtrees\Helpers\GithubService;
use Jefferson49\Webtrees\Log\CustomModuleLogInterface;
use Jefferson49\Webtrees\Module\CustomModuleManager\Configuration\DefaultTitlesAndDescriptions;
use Jefferson49\Webtrees\Module\CustomModuleManager\Configuration\ModuleUpdateServiceConfiguration;
use Jefferson49\Webtrees\Module\CustomModuleManager\Factories\CustomModuleUpdateFactory;
use Jefferson49\Webtrees\Module\CustomModuleManager\ModuleUpdates\CodebergModuleUpdate;
use Jefferson49\Webtrees\Module\CustomModuleManager\ModuleUpdates\GithubModuleUpdate;
use Jefferson49\Webtrees\Module\CustomModuleManager\ModuleUpdates\PlatformModuleUpdate;
use Jefferson49\Webtrees\Module\CustomModuleManager\RequestHandlers\ColumnConfigurationAction;
use Jefferson49\Webtrees\Module\CustomModuleManager\RequestHandlers\ColumnConfigurationModal;
use Jefferson49\Webtrees\Module\CustomModuleManager\RequestHandlers\CustomModuleActivateAction;
use Jefferson49\Webtrees\Module\CustomModuleManager\RequestHandlers\CustomModuleUpdatePage;
use Jefferson49\Webtrees\Module\CustomModuleManager\RequestHandlers\IgnoreUpdateAction;
use Jefferson49\Webtrees\Module\CustomModuleManager\RequestHandlers\ModuleInformationModal;
use Jefferson49\Webtrees\Module\CustomModuleManager\RequestHandlers\ModuleUpgradeWizardPage;
use Jefferson49\Webtrees\Module\CustomModuleManager\RequestHandlers\ModuleUpgradeWizardStep;
use Jefferson49\Webtrees\Module\CustomModuleManager\RequestHandlers\ReleaseNotesModal;
use Jefferson49\Webtrees\Module\CustomModuleManager\RequestHandlers\VestaInformationAction;
use Jefferson49\Webtrees\Module\CustomModuleManager\RequestHandlers\VestaInformationModal;
use Jefferson49\Webtrees\Module\ModuleCustomTrait;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use DateTimeImmutable;
use Exception;
use InvalidArgumentException;
use RuntimeException;
use Throwable;
class CustomModuleManager extends AbstractModule implements
MiddlewareInterface,
ModuleCustomInterface,
ModuleConfigInterface,
ModuleGlobalInterface,
ModuleListInterface,
CustomModuleLogInterface
{
use ModuleCustomTrait;
use ModuleConfigTrait;
use ModuleGlobalTrait;
use ModuleListTrait;
//Custom module version
public const CUSTOM_VERSION = 'v2.0.6';
//GitHub repository
public const GITHUB_REPO = 'Jefferson49/CustomModuleManager';
//Author of custom module
public const CUSTOM_AUTHOR = 'Markus Hemprich';
//Whether a GiHub communication error occured
private static bool $platform_communication_error = false;
//Whether the current version is lower than the latest version of the module
private static bool $is_lower_than_latest_version;
//The module configuration (including all available module data)
private static array $configuration = [];
//Prefences, Settings
public const PREF_MODULE_VERSION = 'module_version';
public const PREF_DEBUGGING_ACTIVATED = 'debugging_activated';
public const PREF_CODEBERG_API_TOKEN = 'codeberg_api_token';
public const PREF_GITHUB_API_TOKEN = 'github_api_token';
public const PREF_LAST_UPDATED_MODULE = 'last_updated_module';
public const PREF_ROLLBACK_ONGOING = 'rollback_ongoing';
public const PREF_MODULES_TO_SHOW = 'modules_to_show';
public const PREF_SHOW_ALL = 'show_all_modules';
public const PREF_SHOW_INSTALLED = 'show_installed_modules';
public const PREF_SHOW_NOT_INSTALLED = 'show_not_installed_modules';
public const PREF_SHOW_MENU_LIST_ITEM = 'show_menu_list_item';
public const PREF_IGNORE_VERSION = 'ignore';
public const PREF_SHOW_COLUMN_DESCR = 'show_column_description';
public const PREF_SHOW_COLUMN_CATEGORY = 'show_column_category';
public const PREF_SHOW_COLUMN_DATE_ADDED = 'show_column_date_added';
public const PREF_SHOW_COLUMN_COMPATIB = 'show_column_compatibility';
public const PREF_SHOW_COLUMN_UPD_SERV = 'show_column_update_service';
public const PREF_SHOW_COLUMN_DOWNLOADS = 'show_column_downloads';
public const PREF_TABLE_LAYOUT = 'table_layout';
public const PREF_VESTA_CONFIRMED = 'vesta_confirmed';
public const PREF_COMP_WEBTREES_VERSION = 'webtrees_version';
//Table layout
public const TABLE_LAYOUT_TABLE = 'table_layout_table';
public const TABLE_LAYOUT_STICKY_HEAD = 'table_layout_sticky_head';
public const TABLE_LAYOUT_RESPONSIVE = 'table_layout_responsive';
//Actions
public const ACTION_DELETE = 'action_delete';
public const ACTION_UPDATE = 'action_update';
public const ACTION_INSTALL = 'action_install';
//Routes
public const ROUTE_WIZARD_PAGE = '/module-upgrade-wizard_page';
public const ROUTE_WIZARD_STEP = '/module-upgrade-wizard-step';
public const ROUTE_MODULE_UPDATE_PAGE = '/module-update-page';
public const ROUTE_MODULE_INFO_MODAL = '/module-info-modal';
public const ROUTE_RELEASE_NOTES_MODAL = '/release-notes-modal';
public const ROUTE_ACTIVATE_ACTION = '/activate-action';
public const ROUTE_IGNORE_UPDATE = '/ignore-update';
public const ROUTE_COLUMN_CONF_MODAL = '/column-config-modal';
public const ROUTE_COLUMN_CONF_ACTION = '/column-config-action';
public const ROUTE_VESTA_INFORMATION = '/vesta-information';
public const ROUTE_VESTA_INFO_ACTION = '/vesta-information-action';
//Language
public const DEFAULT_LANGUAGE = 'en-US';
public const DEFAULT_LANGUAGE_PREFIX = "[English:]";
//Session
public const SESSION_WIZARD_ABORTED = 'wizard_aborted';
//Errors
public const ERROR_MAX_LENGTH = 500;
//Cache
public const CACHE_REALEASE_INFO = 'cmm-release-info-';
//Config GitHub
public const CONFIG_GITHUB_BRANCH = 'config';
public const CONFIG_GITHUB_PATH = 'module_update_service_configuration.json';
//Versions
public const VERSION_NOT_AVAILABLE = 'not available';
public const VERSION_LATEST = 'latest';
public const VERSION_WEBTREES_COMP_DEFAULT = '2.3';
public const VERSION_WEBTREES_MINIMUM = '2.2.6';
//Path
public const PATH_LOCAL_CONFIG = '/Configuration/module_update_service_configuration.json';
public const PATH_CUSTOM_MODULE_LIST = '/Configuration/custom_module_list.json';
public const PATH_DEFAULT_TITLES_AND_DESCRIPTIONS = '/Configuration/DefaultTitlesAndDescriptions.php';
//Supported webtrees version
public const MINIMUM_WEBTREES_VERSION = '2.2.3';
//Switch to generate new default titles and description (in class DefaultTitlesAndDescriptions.php)
public const GENERATE_DEFAULT_TITLES_AND_DESCRIPTIONS = false;
//Switch to generate a JSON file with the custom module update configuration (in module_update_service_configuration.json)
public const GENERATE_CUSTOM_MODULE_UPDATE_CONFIG = false;
//Switch to generate a JSON file with the custom module list
public const GENERATE_CUSTOM_MODULE_LIST = false;
//Whether data of existing versions shall be replaced
public const REPLACE_EXISTING_VERSIONS = false;
//Switch to add conflicts with the current webtrees version
public const ADD_CONFLICTS_FOR_MODULES_NOT_EXISTING = false;
//Use the local json file for the custom module update configuration (in module_update_service_configuration.json)
public const USE_LOCAL_CONFIG = false;
//Use the local json file for the custom module update configuration (in module_update_service_configuration.json)
public const USE_LOCAL_CONFIG_FROM_CUSTOM_MODULE_LIST = true;
//Whether the enabled status is included during submitting the update form
public const ENABLED_STATUS_INCLUDED = 'enabled_status_included';
//Whether logging of communication errors with hosting platforms (i.e. GitHub, Codeberg) is activated
public const LOGGING_COMM_ERRORS_ENABLEDD = 'logging_of_communication_errors_enabled';
/**
* Constructor
*/
public function __construct()
{
//Caution: Do not use the shared library jefferson47/webtrees-common within __construct(),
// because it might result in wrong autoload behavior
}
/**
* {@inheritDoc}
*
* @return void
*
* @see \Fisharebest\Webtrees\Module\AbstractModule::boot()
*/
public function boot(): void
{
//Register the custom module in the webtrees container
Registry::container()->set(CustomModuleManager::class, $this);
//Check update of module version
$this->checkModuleVersionUpdate();
// Register a namespace for the views.
View::registerNamespace(self::viewsNamespace(), $this->resourcesFolder() . 'views/');
//Register the routes for the custom module
Functions::registerRoute(self::ROUTE_WIZARD_PAGE, ModuleUpgradeWizardPage::class);
Functions::registerRoute(self::ROUTE_WIZARD_STEP, ModuleUpgradeWizardStep::class);
Functions::registerRoute(self::ROUTE_MODULE_UPDATE_PAGE, CustomModuleUpdatePage::class);
Functions::registerRoute(self::ROUTE_MODULE_INFO_MODAL, ModuleInformationModal::class);
Functions::registerRoute(self::ROUTE_RELEASE_NOTES_MODAL, ReleaseNotesModal::class);
Functions::registerRoute(self::ROUTE_ACTIVATE_ACTION, CustomModuleActivateAction::class);
Functions::registerRoute(self::ROUTE_IGNORE_UPDATE, IgnoreUpdateAction::class);
Functions::registerRoute(self::ROUTE_COLUMN_CONF_MODAL, ColumnConfigurationModal::class);
Functions::registerRoute(self::ROUTE_COLUMN_CONF_ACTION, ColumnConfigurationAction::class);
Functions::registerRoute(self::ROUTE_VESTA_INFORMATION, VestaInformationModal::class);
Functions::registerRoute(self::ROUTE_VESTA_INFO_ACTION, VestaInformationAction::class);
}
/**
* {@inheritDoc}
*
* @return string
*
* @see \Fisharebest\Webtrees\Module\AbstractModule::title()
*/
public function title(): string
{
return I18N::translate('Custom Module Manager');
}
/**
* {@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 to manage webtrees custom modules.');
}
/**
* {@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
$css = '<link href="' . $this->asseturl(/sitelet?url=https%3A%2F%2Fgithub.com%2FJefferson49%2FCustomModuleManager%2Fblob%2Fmain%2Fsrc%2F%26%23039%3Bcss%2Fcustom-module-manager.css%26%23039%3B) . '" type="text/css" rel="stylesheet" />';
return $css;
}
/**
* {@inheritDoc}
*
* @param Tree $tree
* @param array $parameters
*
* @return string
*
* @see \Fisharebest\Webtrees\Module\ModuleListInterface::listurl()
*/
public function listurl(/sitelet?url=https%3A%2F%2Fgithub.com%2FJefferson49%2FCustomModuleManager%2Fblob%2Fmain%2Fsrc%2FTree%2520%24tree%2C%2520array%2520%24parameters%2520%3D%2520%5B%5D): string
{
return route(CustomModuleUpdatePage::class);
}
/**
* {@inheritDoc}
*
* @param Tree $tree
*
* @return string
*
* @see \Fisharebest\Webtrees\Module\ModuleListInterface::listIsEmpty()
*/
public function listIsEmpty(Tree $tree): bool
{
return ( !Auth::isAdmin()
OR !boolval($this->getPreference(self::PREF_SHOW_MENU_LIST_ITEM, '1'))
);
}
/**
* {@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-custom-module-manager';
}
/**
* Get the prefix for custom module specific logs
*
* @return string
*/
public static function getLogPrefix() : string {
return 'Custom Module Manager';
}
/**
* Whether debugging is activated
*
* @return bool
*/
public function debuggingActivated(): bool {
return boolval($this->getPreference(self::PREF_DEBUGGING_ACTIVATED, '0'));
}
/**
* View module settings in control panel
*
* @param ServerRequestInterface $request
*
* @return ResponseInterface
*/
public function getAdminAction(ServerRequestInterface $request): ResponseInterface
{
//Before generating configuration files, we need to initialize the configuration
$config = self::getConfig();
//If the corresponding switch is turned on, we generate default titles and descriptions
if (self::GENERATE_DEFAULT_TITLES_AND_DESCRIPTIONS) {
self::generateDefaultTitlesAndDescriptions();
}
//If the corresponding switch is turned on, we generate a JSON file for custom module update configuration
if (self::GENERATE_CUSTOM_MODULE_UPDATE_CONFIG) {
self::generateModuleUpdateServiceConfig();
}
//If the corresponding switch is turned on, we generate a JSON file for the custom module list
if (self::GENERATE_CUSTOM_MODULE_LIST) {
$this->generateCustomModuleList(self::REPLACE_EXISTING_VERSIONS);
}
//If the corresponding switch is turned on, we add conflicts to the custom module list
if (self::ADD_CONFLICTS_FOR_MODULES_NOT_EXISTING) {
$this->addConflictsForModulesNotExisting();
}
$this->layout = 'layouts/administration';
return $this->viewResponse(
self::viewsNamespace() . '::settings',
[
'runs_with_webtrees_version' => CustomModuleManager::runsWithInstalledWebtreesVersion(),
'php_extension_zip_missing' => !extension_loaded('zip'),
'title' => $this->title(),
self::PREF_CODEBERG_API_TOKEN => $this->getPreference(self::PREF_CODEBERG_API_TOKEN, ''),
self::PREF_GITHUB_API_TOKEN => $this->getPreference(self::PREF_GITHUB_API_TOKEN, ''),
self::PREF_MODULES_TO_SHOW => $this->getPreference(self::PREF_MODULES_TO_SHOW, self::PREF_SHOW_ALL),
self::PREF_SHOW_MENU_LIST_ITEM => boolval($this->getPreference(self::PREF_SHOW_MENU_LIST_ITEM, '1')),
self::PREF_TABLE_LAYOUT => $this->getPreference(self::PREF_TABLE_LAYOUT, self::TABLE_LAYOUT_STICKY_HEAD),
self::PREF_DEBUGGING_ACTIVATED => boolval($this->getPreference(self::PREF_DEBUGGING_ACTIVATED, '0')),
]
);
}
/**
* 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', '');
$codeberg_api_token = Validator::parsedBody($request)->string(self::PREF_CODEBERG_API_TOKEN, '');
$github_api_token = Validator::parsedBody($request)->string(self::PREF_GITHUB_API_TOKEN, '');
$modules_to_show = Validator::parsedBody($request)->string(self::PREF_MODULES_TO_SHOW, self::PREF_SHOW_ALL);
$show_menu_list_item = Validator::parsedBody($request)->boolean(self::PREF_SHOW_MENU_LIST_ITEM, false);
$table_layout = Validator::parsedBody($request)->string(self::PREF_TABLE_LAYOUT, SELF::TABLE_LAYOUT_STICKY_HEAD);
$debugging_activated = Validator::parsedBody($request)->boolean(self::PREF_DEBUGGING_ACTIVATED, false);
//Save the received settings to the user preferences
if ($save === '1') {
$this->setPreference(self::PREF_CODEBERG_API_TOKEN, $codeberg_api_token);
$this->setPreference(self::PREF_GITHUB_API_TOKEN, $github_api_token);
$this->setPreference(self::PREF_MODULES_TO_SHOW, $modules_to_show);
$this->setPreference(self::PREF_SHOW_MENU_LIST_ITEM, $show_menu_list_item ? '1' : '0');
$this->setPreference(self::PREF_TABLE_LAYOUT, $table_layout);
$this->setPreference(self::PREF_DEBUGGING_ACTIVATED, $debugging_activated ? '1' : '0');
}
//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());
}
/**
* Code here is executed before and after we process the request/response.
* We can block access by throwing an exception.
*
* @param ServerRequestInterface $request
* @param RequestHandlerInterface $handler
*
* @return ResponseInterface
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$updated_module_name = $this->getPreference(CustomModuleManager::PREF_LAST_UPDATED_MODULE, '');
//If a module has recently been updated
if ($updated_module_name !== '') {
$rollback_ongoing = boolval($this->getPreference(CustomModuleManager::PREF_ROLLBACK_ONGOING, '0'));
//If we are not already in the middle of an ongoing rollback
if (!$rollback_ongoing) {
$module_update_service = CustomModuleUpdateFactory::make($updated_module_name);
$test_result = $module_update_service !== null ? substr($module_update_service->testModuleUpdate(), 0, self::ERROR_MAX_LENGTH) : 'Error';
if ($test_result !== '') {
//Trigger rollback of the udpated module
$this->setPreference(CustomModuleManager::PREF_ROLLBACK_ONGOING, '1');
$modal = Validator::queryParams($request)->boolean('modal', false);
if ($modal) {
$this->layout = 'layouts/ajax';
$view = '::modals/steps-modal';
}
else{
$this->layout = 'layouts/administration';
$view = '::steps';
}
return $this->viewResponse(CustomModuleManager::viewsNamespace() . $view, [
'title' => I18N::translate('Rollback Custom Module Update'),
'steps' => [route(ModuleUpgradeWizardStep::class, ['step' => ModuleUpgradeWizardStep::STEP_ROLLBACK, 'module_name' => $updated_module_name, 'error_message' => $test_result, 'modal' => $modal]) => I18N::translate('Rollback')],
]);
}
//After successful test, reset update information
$this->setPreference(CustomModuleManager::PREF_LAST_UPDATED_MODULE, '');
}
}
return $handler->handle($request);
}
/**
* Check if module version is new and start update activities if needed
*
* @return void
*/
public function checkModuleVersionUpdate(): void
{
$updated = false;
// Update custom module version if changed
if($this->getPreference(self::PREF_MODULE_VERSION, '') !== self::CUSTOM_VERSION) {
$updated = false;
}
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');
}
}
/**
* Gemerate default titles and descriptions for all custom modules, which are available in this webtrees installation
*
* If a (complete) list of modules is installed, we can use the generate a (complete) list of default values for all languages,
* The default values are written to a PHP file, which is delivered with the Custom Module Manager code.
*
* @return void
*/
public static function generateDefaultTitlesAndDescriptions(): void {
$module_service = New ModuleService();
$custom_modules = $module_service->findByInterface(ModuleCustomInterface::class, true);
$titles = [];
$descriptions = [];
//Remember current language
$current_language = Session::get('language', '');
$languages = $module_service->findByInterface(ModuleLanguageInterface::class, true, true)
->mapWithKeys(static function (ModuleLanguageInterface $module): array {
if (version_compare(Webtrees::VERSION, '2.3', '>=')) {
$language = $module->language();
}
else {
$language = $module->locale();
}
return [$language->languageTag() => $language->endonym()];
});
foreach ($languages as $language_tag => $language_name) {
//Activate the language
I18N::init($language_tag);
Session::put('language', $language_tag);
foreach ($custom_modules as $module) {
$title = $module->title();
$title = json_encode($title) !== false ? $title : mb_convert_encoding($title, 'UTF-8');
$description = $module->description();
$description = json_encode($description) !== false ? $description : mb_convert_encoding($description, 'UTF-8');
$titles[$language_tag][$module->name()] = $title;
$descriptions[$language_tag][$module->name()] = $description;
}
}
//Reset language
I18N::init($current_language);
Session::put('language', $current_language);
//Delete values, which are identical to default language
$titles_for_default_language = $titles[CustomModuleManager::DEFAULT_LANGUAGE];
$descriptions_for_default_language = $descriptions[CustomModuleManager::DEFAULT_LANGUAGE];
foreach ($languages as $language_tag => $language_name) {
//Skip default language
if ($language_tag === CustomModuleManager::DEFAULT_LANGUAGE) continue;
$titles_for_language = $titles[$language_tag];
foreach ($titles_for_language as $module_name => $title) {
if ($title === $titles_for_default_language[$module_name]) {
unset($titles[$language_tag][$module_name]);
}
}
$descriptions_for_language = $descriptions[$language_tag];
foreach ($descriptions_for_language as $module_name => $description) {
if ($description === $descriptions_for_default_language[$module_name]) {
unset($descriptions[$language_tag][$module_name]);
}
}
}
$json_file = __DIR__ . '/Configuration/DefaultTitlesAndDescriptions.php';
//Delete file if already existing
if (file_exists($json_file)) {
unlink($json_file);
}
//Open stream
if (!$stream = fopen($json_file, "c")) {
throw new RuntimeException('Cannot open file: ' . $json_file);
}
if (fwrite($stream, "<?php\n\n") === false) {
throw new RuntimeException('Cannot write to file: ' . $json_file);
}
fwrite($stream, "declare(strict_types=1);\n\n");
fwrite($stream, "namespace Jefferson49\Webtrees\Module\CustomModuleManager\Configuration;\n\n");
fwrite($stream, "/**\n");
fwrite($stream, " * Default titles and descriptions\n");
fwrite($stream, " */\n");
fwrite($stream, "class DefaultTitlesAndDescriptions \n");
fwrite($stream, "{\n");
fwrite($stream, " public const MODULE_TITLES = [\n");
foreach ($languages as $language_tag => $language_name) {
//Generate JSON
$titles_for_language = $titles[$language_tag];
$title_json = json_encode($titles_for_language);
$title_json = str_replace("'", "\'", $title_json);
fwrite($stream, " '" . $language_tag . "' => '");
fwrite($stream, $title_json . "',\n");
}
fwrite($stream, " ];\n\n");
fwrite($stream, " public const MODULE_DESCRIPTIONS = [\n");
foreach ($languages as $language_tag => $language_name) {
//Generate JSON
$descriptions_for_language = $descriptions[$language_tag];
$description_json = json_encode($descriptions_for_language);
$description_json = str_replace("'", "\'", $description_json);
fwrite($stream, " '" . $language_tag . "' => '");
fwrite($stream, $description_json . "',\n");
}
fwrite($stream, " ];\n\n");
fwrite($stream, "}\n");
fclose($stream);
}
/**
* Gemerate a JSON file from the module update service configuration
*
* @return void
*/
public static function generateModuleUpdateServiceConfig(): void {
$json_file = __DIR__ . self::PATH_LOCAL_CONFIG;
//Delete file if already existing
if (file_exists($json_file)) {
unlink($json_file);
}
//Open stream
if (!$stream = fopen($json_file, "c")) {
throw new RuntimeException('Cannot open file: ' . $json_file);
}
//Create JSON from configuration
$json_config = json_encode(self::getConfig(), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
try {
fwrite($stream, $json_config);
}
catch (Throwable $th) {
throw new RuntimeException('Cannot write to file: ' . $json_file);
}
return;
}
/**
* Gemerate a custom module list in based on the Packagist API v2 JSON format
*
* Documentation: https://packagist.org/apidoc#get-package-data
* Example JSON file: https://repo.packagist.org/p2/monolog/monolog.json
*
* @param
*
* @return bool $replace_existing_versions Whether data of existing versions shall be replaced
*/
public function generateCustomModuleList(bool $replace_existing_versions = false): void {
//Load existing custom module list
$custom_module_list = self::loadCustomModuleList();
$config = self::getConfig();
$modified = false;
foreach ($config as $module_name => $module_config) {
/** @var PlatformModuleUpdate $module_update_service */
$module_update_service = CustomModuleUpdateFactory::make($module_name);
//Skip if module update service or module is not available
if ($module_update_service === null) {
continue;
}
elseif ($module_update_service->getModule() === null) {
continue;
}
//Get the module version
$version = CustomModuleManager::normalizeVersion($module_name, $module_update_service->customModuleVersion());
$package_name = $module_update_service->getPackageName();
//If current module version is not available
if ($version === '') {
$version = self::VERSION_NOT_AVAILABLE;
}
//If the version is not included in the list yet or we shall replace the existing version
if (!self::versionIsInList($custom_module_list, $package_name, $version) OR $replace_existing_versions) {
//Get the content of the current composer.json file
$composer_json = self::getComposerJson($module_update_service::getInstallationFolderFromModuleName($module_name));
//If we were not able to read composer.json data from the file, we try to retrieve it from GitHub
if ($composer_json === [] && in_array($module_update_service::NAME, [GithubModuleUpdate::NAME, CodebergModuleUpdate::NAME], true)) {
$tag = $version;
$tag_prefix = $module_update_service->getTagPrefix();
//Add prefix, if the tags of the repository have a prefix
if ($tag_prefix !== '') {
if ($tag !== '' && strlen($tag) > strlen($tag_prefix)) {
//If tag does not start with prefix, add prefix
if (substr($tag, 0, strlen($tag_prefix)) !== $tag_prefix) {
$tag = $tag_prefix . $tag;
}
}
}
try {
if (in_array($module_update_service::NAME, [CodebergModuleUpdate::NAME, GithubModuleUpdate::NAME])) {
$json = $module_update_service->getTextFileContent($module_update_service->getRepository(), $tag, 'composer.json');
}
$composer_json = json_decode($json, true);
}
catch (HostingPlatformCommunicationError $e) {
//Fail gracefully if communication with GitHub failed
}
}
//Get existing module versions
$module_versions = $custom_module_list['packages'][$package_name] ?? [];
//Add additional content to composer.json data
$composer_json['version'] = $version;
if (!isset($composer_json['time']) && in_array($module_update_service::NAME, [GithubModuleUpdate::NAME, CodebergModuleUpdate::NAME], true)) {
$release_info = $module_update_service->fetchReleasesInfoCached();
if (isset($release_info['published_at'])) {
$dt = new DateTimeImmutable($release_info['published_at']);
$composer_json['time'] = $dt->format("Y-m-d");
}
}
// If no conflict rule is available, copy conflict rule from version before
if (!isset($composer_json['conflict'])) {
$version_before = self::getVersionBefore($module_versions, $version);
foreach ($module_versions as $module_version) {
if ($module_version['version'] === $version_before && isset($module_version['conflict'])) {
$composer_json['conflict'] = $module_version['conflict'];
}
}
}
if (!isset($composer_json['name'])) {
$composer_json['name'] = $package_name;
}
if (!isset($composer_json['description'])) {
$composer_json['description'] = $module_update_service->description();
}
if (!isset($composer_json['authors'])) {
$module = $module_update_service->getModule();
if ($module !== null && $module->customModuleAuthorName() !== '') {
$composer_json['authors'] = [['name' => $module->customModuleAuthorName()]];
}
}
$extra = ['module_name' => $module_name] + $config[$module_name];
$composer_json['extra'] = ['custom-module-manager' => $extra];
//Sort composer.json data
self::sortComposerJsonData($composer_json);
//Remove data for version if already exists
self::removeVersion($custom_module_list, $package_name, $version);
//If package already exists, add the data of the new version at the beginning of the module list
if (isset($custom_module_list['packages'][$package_name])) {
array_unshift($custom_module_list['packages'][$package_name], $composer_json);
}
//Otherwise, add as new package
else {
$custom_module_list['packages'][$package_name][] = $composer_json;
}
$modified = true;
}
}
if ($modified) {
//Sort the module list by package name
ksort($custom_module_list['packages']);
//Save the custom module list
self::saveCustomModuleList($custom_module_list);
}
return;
}
/**
* Gemerate a custom module list in based on the Packagist API v2 JSON format
*
* @return void
*/
public function addConflictsForModulesNotExisting(): void {
//Load existing custom module list
$custom_module_list = self::loadCustomModuleList();
$modifed = false;
$config = self::getConfig();
foreach ($config as $module_name => $module_config) {
/** @var PlatformModuleUpdate $module_update_service */
$module_update_service = CustomModuleUpdateFactory::make($module_name);
if ($module_update_service === null) {
break;
}
$package_name = $module_update_service->getPackageName();
//Add a conflict with the current webtrees version, if module is not availalbe
if ( $module_update_service->getModule() === null
&& isset($custom_module_list['packages'][$package_name])) {
$latest_version = end($custom_module_list['packages'][$package_name]);
$version = $latest_version['version'];
//Add a conflict with the current webtrees version
if (!isset($latest_version['conflict']['fisharebest/webtrees'])) {
$latest_version['conflict'] = ['fisharebest/webtrees' => '>=' . Webtrees::VERSION];
}
//Append a conflict
elseif (strpos($latest_version['conflict']['fisharebest/webtrees'], '>=' . Webtrees::VERSION) === false) {
$latest_version['conflict']['fisharebest/webtrees'] .= ' || >=' . Webtrees::VERSION;
}
//Sort
self::sortComposerJsonData($latest_version);
//Remove data for version if already exists
self::removeVersion($custom_module_list, $package_name, $version);
//Add updated version data
$custom_module_list['packages'][$package_name][] = $latest_version;
$modifed = true;
}
}
if ($modifed) {
self::saveCustomModuleList($custom_module_list);
}
}
/**
* Load custom module list
*
* @return array
*/
public static function loadCustomModuleList(): array {
$json_file = __DIR__ . self::PATH_CUSTOM_MODULE_LIST;
//Get the data from the JSON custom module list
return json_decode(self::readFromFile($json_file), true) ?? [];
}
/**
* Save custom module list
*
* @param array $custom_module_list
* @return void
*/
public static function saveCustomModuleList(array $custom_module_list): void {
$json_file = __DIR__ . self::PATH_CUSTOM_MODULE_LIST;
//Create JSON
$json_custom_module_list = json_encode($custom_module_list, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
//Delete file if already existing
if (file_exists($json_file)) {
unlink($json_file);
}
//Write JSON to file
try {
if (!$stream = fopen($json_file, "c")) {
throw new RuntimeException('Cannot open file: ' . $json_file);
}
fwrite($stream, $json_custom_module_list);
fclose($stream);
}
catch (Throwable $th) {
throw new RuntimeException('Cannot write to file: ' . $json_file);
}
return;
}
/**
* Get the configuration
*
* @return array
*/
public static function getConfig(): array {
// If the config is already available, take it
if (!empty(self::$configuration)) {
return self::$configuration;
}
//Get data from current a json file (either local or remote)
$config_from_file = ModuleUpdateServiceConfiguration::getModuleUpdateServiceConfig();
//Get the configuration from the code
$configuration = (array) ModuleUpdateServiceConfiguration::MODULE_UPDATE_SERVICE_CONFIG;
//Add titles and descriptions
$titles_all_languages = DefaultTitlesAndDescriptions::MODULE_TITLES;
$descriptions_all_languages = DefaultTitlesAndDescriptions::MODULE_DESCRIPTIONS;
$titles = json_decode($titles_all_languages[CustomModuleManager::DEFAULT_LANGUAGE], true);
$descriptions = json_decode($descriptions_all_languages[CustomModuleManager::DEFAULT_LANGUAGE], true);
foreach ($configuration as $module_name => $module_config) {
$configuration[$module_name]['params']['title'] = $titles[$module_name] ?? '';
$configuration[$module_name]['params']['description'] = $descriptions[$module_name] ?? '';
}
//Date added
foreach ($configuration as $module_name => $module_config) {
//If date added does not exist already, we insert the current date
if (!isset($config_from_file[$module_name]['date_added'])) {
$configuration[$module_name]['date_added'] = date("Y-m-d");
}
//Otherwise, we take the existing value
else {
$configuration[$module_name]['date_added'] = $config_from_file[$module_name]['date_added'];
}
}