xref: /webtrees/app/Services/ModuleService.php (revision 0e4a9e1c70d8cf85d3204cfcbd919da38e5ce8da)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2023 webtrees development team
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees\Services;
21
22use Closure;
23use Fisharebest\Webtrees\Auth;
24use Fisharebest\Webtrees\Contracts\UserInterface;
25use Fisharebest\Webtrees\FlashMessages;
26use Fisharebest\Webtrees\I18N;
27use Fisharebest\Webtrees\Module\AhnentafelReportModule;
28use Fisharebest\Webtrees\Module\AlbumModule;
29use Fisharebest\Webtrees\Module\AncestorsChartModule;
30use Fisharebest\Webtrees\Module\AustrianHistoricEvents;
31use Fisharebest\Webtrees\Module\AustrianPresidents;
32use Fisharebest\Webtrees\Module\BingMaps;
33use Fisharebest\Webtrees\Module\BingWebmasterToolsModule;
34use Fisharebest\Webtrees\Module\BirthDeathMarriageReportModule;
35use Fisharebest\Webtrees\Module\BirthReportModule;
36use Fisharebest\Webtrees\Module\BranchesListModule;
37use Fisharebest\Webtrees\Module\BritishMonarchs;
38use Fisharebest\Webtrees\Module\BritishPrimeMinisters;
39use Fisharebest\Webtrees\Module\BritishSocialHistory;
40use Fisharebest\Webtrees\Module\CalendarMenuModule;
41use Fisharebest\Webtrees\Module\CemeteryReportModule;
42use Fisharebest\Webtrees\Module\CensusAssistantModule;
43use Fisharebest\Webtrees\Module\ChangeReportModule;
44use Fisharebest\Webtrees\Module\ChartsBlockModule;
45use Fisharebest\Webtrees\Module\ChartsMenuModule;
46use Fisharebest\Webtrees\Module\CheckForNewVersion;
47use Fisharebest\Webtrees\Module\CkeditorModule;
48use Fisharebest\Webtrees\Module\ClippingsCartModule;
49use Fisharebest\Webtrees\Module\CloudsTheme;
50use Fisharebest\Webtrees\Module\ColorsTheme;
51use Fisharebest\Webtrees\Module\CompactTreeChartModule;
52use Fisharebest\Webtrees\Module\ContactsFooterModule;
53use Fisharebest\Webtrees\Module\CustomCssJsModule;
54use Fisharebest\Webtrees\Module\CzechMonarchsAndPresidents;
55use Fisharebest\Webtrees\Module\DeathReportModule;
56use Fisharebest\Webtrees\Module\DescendancyChartModule;
57use Fisharebest\Webtrees\Module\DescendancyModule;
58use Fisharebest\Webtrees\Module\DescendancyReportModule;
59use Fisharebest\Webtrees\Module\DutchMonarchs;
60use Fisharebest\Webtrees\Module\DutchPrimeMinisters;
61use Fisharebest\Webtrees\Module\EsriMaps;
62use Fisharebest\Webtrees\Module\FabTheme;
63use Fisharebest\Webtrees\Module\FactSourcesReportModule;
64use Fisharebest\Webtrees\Module\FamilyBookChartModule;
65use Fisharebest\Webtrees\Module\FamilyGroupReportModule;
66use Fisharebest\Webtrees\Module\FamilyListModule;
67use Fisharebest\Webtrees\Module\FamilyNavigatorModule;
68use Fisharebest\Webtrees\Module\FamilyTreeFavoritesModule;
69use Fisharebest\Webtrees\Module\FamilyTreeNewsModule;
70use Fisharebest\Webtrees\Module\FamilyTreeStatisticsModule;
71use Fisharebest\Webtrees\Module\FanChartModule;
72use Fisharebest\Webtrees\Module\FixCemeteryTag;
73use Fisharebest\Webtrees\Module\FixDuplicateLinks;
74use Fisharebest\Webtrees\Module\FixMissingDeaths;
75use Fisharebest\Webtrees\Module\FixNameSlashesAndSpaces;
76use Fisharebest\Webtrees\Module\FixNameTags;
77use Fisharebest\Webtrees\Module\FixPlaceNames;
78use Fisharebest\Webtrees\Module\FixPrimaryTag;
79use Fisharebest\Webtrees\Module\FixSearchAndReplace;
80use Fisharebest\Webtrees\Module\FixWtObjeSortTag;
81use Fisharebest\Webtrees\Module\FrenchHistory;
82use Fisharebest\Webtrees\Module\FrequentlyAskedQuestionsModule;
83use Fisharebest\Webtrees\Module\GeonamesAutocomplete;
84use Fisharebest\Webtrees\Module\GoogleAnalyticsModule;
85use Fisharebest\Webtrees\Module\GoogleMaps;
86use Fisharebest\Webtrees\Module\GoogleWebmasterToolsModule;
87use Fisharebest\Webtrees\Module\HereMaps;
88use Fisharebest\Webtrees\Module\HitCountFooterModule;
89use Fisharebest\Webtrees\Module\HourglassChartModule;
90use Fisharebest\Webtrees\Module\HtmlBlockModule;
91use Fisharebest\Webtrees\Module\IndividualFactsTabModule;
92use Fisharebest\Webtrees\Module\IndividualFamiliesReportModule;
93use Fisharebest\Webtrees\Module\IndividualListModule;
94use Fisharebest\Webtrees\Module\IndividualMetadataModule;
95use Fisharebest\Webtrees\Module\IndividualReportModule;
96use Fisharebest\Webtrees\Module\InteractiveTreeModule;
97use Fisharebest\Webtrees\Module\LanguageAfrikaans;
98use Fisharebest\Webtrees\Module\LanguageAlbanian;
99use Fisharebest\Webtrees\Module\LanguageArabic;
100use Fisharebest\Webtrees\Module\LanguageBosnian;
101use Fisharebest\Webtrees\Module\LanguageBulgarian;
102use Fisharebest\Webtrees\Module\LanguageCatalan;
103use Fisharebest\Webtrees\Module\LanguageChineseSimplified;
104use Fisharebest\Webtrees\Module\LanguageChineseTraditional;
105use Fisharebest\Webtrees\Module\LanguageCroatian;
106use Fisharebest\Webtrees\Module\LanguageCzech;
107use Fisharebest\Webtrees\Module\LanguageDanish;
108use Fisharebest\Webtrees\Module\LanguageDivehi;
109use Fisharebest\Webtrees\Module\LanguageDutch;
110use Fisharebest\Webtrees\Module\LanguageEnglishAustralia;
111use Fisharebest\Webtrees\Module\LanguageEnglishGreatBritain;
112use Fisharebest\Webtrees\Module\LanguageEnglishUnitedStates;
113use Fisharebest\Webtrees\Module\LanguageEstonian;
114use Fisharebest\Webtrees\Module\LanguageFaroese;
115use Fisharebest\Webtrees\Module\LanguageFarsi;
116use Fisharebest\Webtrees\Module\LanguageFinnish;
117use Fisharebest\Webtrees\Module\LanguageFrench;
118use Fisharebest\Webtrees\Module\LanguageFrenchCanada;
119use Fisharebest\Webtrees\Module\LanguageGalician;
120use Fisharebest\Webtrees\Module\LanguageGeorgian;
121use Fisharebest\Webtrees\Module\LanguageGerman;
122use Fisharebest\Webtrees\Module\LanguageGreek;
123use Fisharebest\Webtrees\Module\LanguageHebrew;
124use Fisharebest\Webtrees\Module\LanguageHindi;
125use Fisharebest\Webtrees\Module\LanguageHungarian;
126use Fisharebest\Webtrees\Module\LanguageIcelandic;
127use Fisharebest\Webtrees\Module\LanguageIndonesian;
128use Fisharebest\Webtrees\Module\LanguageItalian;
129use Fisharebest\Webtrees\Module\LanguageJapanese;
130use Fisharebest\Webtrees\Module\LanguageJavanese;
131use Fisharebest\Webtrees\Module\LanguageKazhak;
132use Fisharebest\Webtrees\Module\LanguageKorean;
133use Fisharebest\Webtrees\Module\LanguageKurdish;
134use Fisharebest\Webtrees\Module\LanguageLatvian;
135use Fisharebest\Webtrees\Module\LanguageLingala;
136use Fisharebest\Webtrees\Module\LanguageLithuanian;
137use Fisharebest\Webtrees\Module\LanguageMalay;
138use Fisharebest\Webtrees\Module\LanguageMaori;
139use Fisharebest\Webtrees\Module\LanguageMarathi;
140use Fisharebest\Webtrees\Module\LanguageNepalese;
141use Fisharebest\Webtrees\Module\LanguageNorwegianBokmal;
142use Fisharebest\Webtrees\Module\LanguageNorwegianNynorsk;
143use Fisharebest\Webtrees\Module\LanguageOccitan;
144use Fisharebest\Webtrees\Module\LanguagePolish;
145use Fisharebest\Webtrees\Module\LanguagePortuguese;
146use Fisharebest\Webtrees\Module\LanguagePortugueseBrazil;
147use Fisharebest\Webtrees\Module\LanguageRomanian;
148use Fisharebest\Webtrees\Module\LanguageRussian;
149use Fisharebest\Webtrees\Module\LanguageSerbian;
150use Fisharebest\Webtrees\Module\LanguageSerbianLatin;
151use Fisharebest\Webtrees\Module\LanguageSlovakian;
152use Fisharebest\Webtrees\Module\LanguageSlovenian;
153use Fisharebest\Webtrees\Module\LanguageSpanish;
154use Fisharebest\Webtrees\Module\LanguageSundanese;
155use Fisharebest\Webtrees\Module\LanguageSwahili;
156use Fisharebest\Webtrees\Module\LanguageSwedish;
157use Fisharebest\Webtrees\Module\LanguageTagalog;
158use Fisharebest\Webtrees\Module\LanguageTamil;
159use Fisharebest\Webtrees\Module\LanguageTatar;
160use Fisharebest\Webtrees\Module\LanguageThai;
161use Fisharebest\Webtrees\Module\LanguageTurkish;
162use Fisharebest\Webtrees\Module\LanguageUkranian;
163use Fisharebest\Webtrees\Module\LanguageUrdu;
164use Fisharebest\Webtrees\Module\LanguageUzbek;
165use Fisharebest\Webtrees\Module\LanguageVietnamese;
166use Fisharebest\Webtrees\Module\LanguageWelsh;
167use Fisharebest\Webtrees\Module\LanguageYiddish;
168use Fisharebest\Webtrees\Module\LifespansChartModule;
169use Fisharebest\Webtrees\Module\ListsMenuModule;
170use Fisharebest\Webtrees\Module\LocationListModule;
171use Fisharebest\Webtrees\Module\LoggedInUsersModule;
172use Fisharebest\Webtrees\Module\LoginBlockModule;
173use Fisharebest\Webtrees\Module\LowCountriesRulers;
174use Fisharebest\Webtrees\Module\MapBox;
175use Fisharebest\Webtrees\Module\MapGeoLocationGeonames;
176use Fisharebest\Webtrees\Module\MapGeoLocationNominatim;
177use Fisharebest\Webtrees\Module\MapGeoLocationOpenRouteService;
178use Fisharebest\Webtrees\Module\MapLinkBing;
179use Fisharebest\Webtrees\Module\MapLinkGoogle;
180use Fisharebest\Webtrees\Module\MapLinkOpenStreetMap;
181use Fisharebest\Webtrees\Module\MarriageReportModule;
182use Fisharebest\Webtrees\Module\MatomoAnalyticsModule;
183use Fisharebest\Webtrees\Module\MediaListModule;
184use Fisharebest\Webtrees\Module\MediaTabModule;
185use Fisharebest\Webtrees\Module\MinimalTheme;
186use Fisharebest\Webtrees\Module\MissingFactsReportModule;
187use Fisharebest\Webtrees\Module\ModuleAnalyticsInterface;
188use Fisharebest\Webtrees\Module\ModuleBlockInterface;
189use Fisharebest\Webtrees\Module\ModuleChartInterface;
190use Fisharebest\Webtrees\Module\ModuleCustomInterface;
191use Fisharebest\Webtrees\Module\ModuleDataFixInterface;
192use Fisharebest\Webtrees\Module\ModuleFooterInterface;
193use Fisharebest\Webtrees\Module\ModuleHistoricEventsInterface;
194use Fisharebest\Webtrees\Module\ModuleInterface;
195use Fisharebest\Webtrees\Module\ModuleLanguageInterface;
196use Fisharebest\Webtrees\Module\ModuleListInterface;
197use Fisharebest\Webtrees\Module\ModuleMapAutocompleteInterface;
198use Fisharebest\Webtrees\Module\ModuleMapGeoLocationInterface;
199use Fisharebest\Webtrees\Module\ModuleMapLinkInterface;
200use Fisharebest\Webtrees\Module\ModuleMapProviderInterface;
201use Fisharebest\Webtrees\Module\ModuleMenuInterface;
202use Fisharebest\Webtrees\Module\ModuleReportInterface;
203use Fisharebest\Webtrees\Module\ModuleShareInterface;
204use Fisharebest\Webtrees\Module\ModuleSidebarInterface;
205use Fisharebest\Webtrees\Module\ModuleTabInterface;
206use Fisharebest\Webtrees\Module\ModuleThemeInterface;
207use Fisharebest\Webtrees\Module\NoteListModule;
208use Fisharebest\Webtrees\Module\NotesTabModule;
209use Fisharebest\Webtrees\Module\OccupationReportModule;
210use Fisharebest\Webtrees\Module\OnThisDayModule;
211use Fisharebest\Webtrees\Module\OpenRouteServiceAutocomplete;
212use Fisharebest\Webtrees\Module\OpenStreetMap;
213use Fisharebest\Webtrees\Module\PedigreeChartModule;
214use Fisharebest\Webtrees\Module\PedigreeMapModule;
215use Fisharebest\Webtrees\Module\PedigreeReportModule;
216use Fisharebest\Webtrees\Module\PlaceHierarchyListModule;
217use Fisharebest\Webtrees\Module\PlacesModule;
218use Fisharebest\Webtrees\Module\PoweredByWebtreesModule;
219use Fisharebest\Webtrees\Module\PrivacyPolicy;
220use Fisharebest\Webtrees\Module\RecentChangesModule;
221use Fisharebest\Webtrees\Module\RedirectLegacyUrlsModule;
222use Fisharebest\Webtrees\Module\RelatedIndividualsReportModule;
223use Fisharebest\Webtrees\Module\RelationshipsChartModule;
224use Fisharebest\Webtrees\Module\RelativesTabModule;
225use Fisharebest\Webtrees\Module\ReportsMenuModule;
226use Fisharebest\Webtrees\Module\RepositoryListModule;
227use Fisharebest\Webtrees\Module\ResearchTaskModule;
228use Fisharebest\Webtrees\Module\ReviewChangesModule;
229use Fisharebest\Webtrees\Module\SearchMenuModule;
230use Fisharebest\Webtrees\Module\ShareAnniversaryModule;
231use Fisharebest\Webtrees\Module\ShareUrlModule;
232use Fisharebest\Webtrees\Module\SiteMapModule;
233use Fisharebest\Webtrees\Module\SlideShowModule;
234use Fisharebest\Webtrees\Module\SourceListModule;
235use Fisharebest\Webtrees\Module\SourcesTabModule;
236use Fisharebest\Webtrees\Module\StatcounterModule;
237use Fisharebest\Webtrees\Module\StatisticsChartModule;
238use Fisharebest\Webtrees\Module\StoriesModule;
239use Fisharebest\Webtrees\Module\SubmitterListModule;
240use Fisharebest\Webtrees\Module\ThemeSelectModule;
241use Fisharebest\Webtrees\Module\TimelineChartModule;
242use Fisharebest\Webtrees\Module\TopGivenNamesModule;
243use Fisharebest\Webtrees\Module\TopPageViewsModule;
244use Fisharebest\Webtrees\Module\TopSurnamesModule;
245use Fisharebest\Webtrees\Module\TreesMenuModule;
246use Fisharebest\Webtrees\Module\UpcomingAnniversariesModule;
247use Fisharebest\Webtrees\Module\UserFavoritesModule;
248use Fisharebest\Webtrees\Module\UserJournalModule;
249use Fisharebest\Webtrees\Module\UserMessagesModule;
250use Fisharebest\Webtrees\Module\UserWelcomeModule;
251use Fisharebest\Webtrees\Module\USPresidents;
252use Fisharebest\Webtrees\Module\WebtreesTheme;
253use Fisharebest\Webtrees\Module\WelcomeBlockModule;
254use Fisharebest\Webtrees\Module\XeneaTheme;
255use Fisharebest\Webtrees\Module\YahrzeitModule;
256use Fisharebest\Webtrees\Registry;
257use Fisharebest\Webtrees\Tree;
258use Fisharebest\Webtrees\Webtrees;
259use Illuminate\Database\Capsule\Manager as DB;
260use Illuminate\Support\Collection;
261use Psr\Http\Server\MiddlewareInterface;
262use Throwable;
263
264use function basename;
265use function dirname;
266use function glob;
267use function is_object;
268use function str_contains;
269use function strlen;
270
271use const GLOB_NOSORT;
272
273/**
274 * Functions for managing and maintaining modules.
275 */
276class ModuleService
277{
278    // Components are pieces of user-facing functionality, are managed together in the control panel.
279    private const COMPONENTS = [
280        ModuleAnalyticsInterface::class,
281        ModuleBlockInterface::class,
282        ModuleChartInterface::class,
283        ModuleDataFixInterface::class,
284        ModuleFooterInterface::class,
285        ModuleHistoricEventsInterface::class,
286        ModuleLanguageInterface::class,
287        ModuleListInterface::class,
288        ModuleMapAutocompleteInterface::class,
289        ModuleMapLinkInterface::class,
290        ModuleMapProviderInterface::class,
291        ModuleMapGeoLocationInterface::class,
292        ModuleMenuInterface::class,
293        ModuleReportInterface::class,
294        ModuleShareInterface::class,
295        ModuleSidebarInterface::class,
296        ModuleTabInterface::class,
297        ModuleThemeInterface::class,
298    ];
299
300    // Components that have access levels.
301    private const COMPONENTS_WITH_ACCESS = [
302        ModuleBlockInterface::class,
303        ModuleChartInterface::class,
304        ModuleListInterface::class,
305        ModuleMenuInterface::class,
306        ModuleReportInterface::class,
307        ModuleSidebarInterface::class,
308        ModuleTabInterface::class,
309    ];
310
311    // Components that are displayed in a particular order
312    private const COMPONENTS_WITH_SORT = [
313        ModuleFooterInterface::class,
314        ModuleMenuInterface::class,
315        ModuleSidebarInterface::class,
316        ModuleTabInterface::class,
317    ];
318
319    // Array keys are module names, and should match module names from earlier versions of webtrees.
320    private const CORE_MODULES = [
321        'GEDFact_assistant'       => CensusAssistantModule::class,
322        'ahnentafel_report'       => AhnentafelReportModule::class,
323        'ancestors_chart'         => AncestorsChartModule::class,
324        'austrian-history'        => AustrianHistoricEvents::class,
325        'austrian-presidents'     => AustrianPresidents::class,
326        'bdm_report'              => BirthDeathMarriageReportModule::class,
327        'bing-maps'               => BingMaps::class,
328        'bing-webmaster-tools'    => BingWebmasterToolsModule::class,
329        'birth_report'            => BirthReportModule::class,
330        'branches_list'           => BranchesListModule::class,
331        'british-monarchs'        => BritishMonarchs::class,
332        'british-prime-ministers' => BritishPrimeMinisters::class,
333        'british-social-history'  => BritishSocialHistory::class,
334        'calendar-menu'           => CalendarMenuModule::class,
335        'cemetery_report'         => CemeteryReportModule::class,
336        'change_report'           => ChangeReportModule::class,
337        'charts'                  => ChartsBlockModule::class,
338        'charts-menu'             => ChartsMenuModule::class,
339        'check-for-new-version'   => CheckForNewVersion::class,
340        'ckeditor'                => CkeditorModule::class,
341        'clippings'               => ClippingsCartModule::class,
342        'clouds'                  => CloudsTheme::class,
343        'colors'                  => ColorsTheme::class,
344        'compact-chart'           => CompactTreeChartModule::class,
345        'contact-links'           => ContactsFooterModule::class,
346        'czech-leaders'           => CzechMonarchsAndPresidents::class,
347        'custom-css-js'           => CustomCssJsModule::class,
348        'death_report'            => DeathReportModule::class,
349        'descendancy'             => DescendancyModule::class,
350        'descendancy_chart'       => DescendancyChartModule::class,
351        'descendancy_report'      => DescendancyReportModule::class,
352        'dutch_monarchs'          => DutchMonarchs::class,
353        'dutch_prime_ministers'   => DutchPrimeMinisters::class,
354        'esri-maps'               => EsriMaps::class,
355        'extra_info'              => IndividualMetadataModule::class,
356        'fab'                     => FabTheme::class,
357        'fact_sources'            => FactSourcesReportModule::class,
358        'family_book_chart'       => FamilyBookChartModule::class,
359        'family_group_report'     => FamilyGroupReportModule::class,
360        'family_list'             => FamilyListModule::class,
361        'family_nav'              => FamilyNavigatorModule::class,
362        'fan_chart'               => FanChartModule::class,
363        'faq'                     => FrequentlyAskedQuestionsModule::class,
364        'french-history'          => FrenchHistory::class,
365        'fix-add-death'           => FixMissingDeaths::class,
366        'fix-ceme-tag'            => FixCemeteryTag::class,
367        'fix-duplicate-links'     => FixDuplicateLinks::class,
368        'fix-name-slashes-spaces' => FixNameSlashesAndSpaces::class,
369        'fix-name-tags'           => FixNameTags::class,
370        'fix-place-names'         => FixPlaceNames::class,
371        'fix-prim-tag'            => FixPrimaryTag::class,
372        'fix-search-and-replace'  => FixSearchAndReplace::class,
373        'fix-wt-obje-sort'        => FixWtObjeSortTag::class,
374        'gedcom_block'            => WelcomeBlockModule::class,
375        'gedcom_favorites'        => FamilyTreeFavoritesModule::class,
376        'gedcom_news'             => FamilyTreeNewsModule::class,
377        'gedcom_stats'            => FamilyTreeStatisticsModule::class,
378        'geonames'                => GeonamesAutocomplete::class,
379        'google-analytics'        => GoogleAnalyticsModule::class,
380        'google-maps'             => GoogleMaps::class,
381        'google-webmaster-tools'  => GoogleWebmasterToolsModule::class,
382        'here-maps'               => HereMaps::class,
383        'hit-counter'             => HitCountFooterModule::class,
384        'hourglass_chart'         => HourglassChartModule::class,
385        'html'                    => HtmlBlockModule::class,
386        'individual_ext_report'   => IndividualFamiliesReportModule::class,
387        'individual_list'         => IndividualListModule::class,
388        'individual_report'       => IndividualReportModule::class,
389        'language-af'             => LanguageAfrikaans::class,
390        'language-ar'             => LanguageArabic::class,
391        'language-bg'             => LanguageBulgarian::class,
392        'language-bs'             => LanguageBosnian::class,
393        'language-ca'             => LanguageCatalan::class,
394        'language-cs'             => LanguageCzech::class,
395        'language-cy'             => LanguageWelsh::class,
396        'language-da'             => LanguageDanish::class,
397        'language-de'             => LanguageGerman::class,
398        'language-dv'             => LanguageDivehi::class,
399        'language-el'             => LanguageGreek::class,
400        'language-en-AU'          => LanguageEnglishAustralia::class,
401        'language-en-GB'          => LanguageEnglishGreatBritain::class,
402        'language-en-US'          => LanguageEnglishUnitedStates::class,
403        'language-es'             => LanguageSpanish::class,
404        'language-et'             => LanguageEstonian::class,
405        'language-fa'             => LanguageFarsi::class,
406        'language-fi'             => LanguageFinnish::class,
407        'language-fo'             => LanguageFaroese::class,
408        'language-fr'             => LanguageFrench::class,
409        'language-fr-CA'          => LanguageFrenchCanada::class,
410        'language-gl'             => LanguageGalician::class,
411        'language-he'             => LanguageHebrew::class,
412        'language-hi'             => LanguageHindi::class,
413        'language-hr'             => LanguageCroatian::class,
414        'language-hu'             => LanguageHungarian::class,
415        'language-id'             => LanguageIndonesian::class,
416        'language-is'             => LanguageIcelandic::class,
417        'language-it'             => LanguageItalian::class,
418        'language-ja'             => LanguageJapanese::class,
419        'language-jv'             => LanguageJavanese::class,
420        'language-ka'             => LanguageGeorgian::class,
421        'language-kk'             => LanguageKazhak::class,
422        'language-ko'             => LanguageKorean::class,
423        'language-ku'             => LanguageKurdish::class,
424        'language-ln'             => LanguageLingala::class,
425        'language-lt'             => LanguageLithuanian::class,
426        'language-lv'             => LanguageLatvian::class,
427        'language-mi'             => LanguageMaori::class,
428        'language-mr'             => LanguageMarathi::class,
429        'language-ms'             => LanguageMalay::class,
430        'language-nb'             => LanguageNorwegianBokmal::class,
431        'language-ne'             => LanguageNepalese::class,
432        'language-nl'             => LanguageDutch::class,
433        'language-nn'             => LanguageNorwegianNynorsk::class,
434        'language-oc'             => LanguageOccitan::class,
435        'language-pl'             => LanguagePolish::class,
436        'language-pt'             => LanguagePortuguese::class,
437        'language-pt-BR'          => LanguagePortugueseBrazil::class,
438        'language-ro'             => LanguageRomanian::class,
439        'language-ru'             => LanguageRussian::class,
440        'language-sk'             => LanguageSlovakian::class,
441        'language-sl'             => LanguageSlovenian::class,
442        'language-sq'             => LanguageAlbanian::class,
443        'language-sr'             => LanguageSerbian::class,
444        'language-sr-Latn'        => LanguageSerbianLatin::class,
445        'language-su'             => LanguageSundanese::class,
446        'language-sv'             => LanguageSwedish::class,
447        'language-sw'             => LanguageSwahili::class,
448        'language-ta'             => LanguageTamil::class,
449        'language-th'             => LanguageThai::class,
450        'language-tl'             => LanguageTagalog::class,
451        'language-tr'             => LanguageTurkish::class,
452        'language-tt'             => LanguageTatar::class,
453        'language-uk'             => LanguageUkranian::class,
454        'language-ur'             => LanguageUrdu::class,
455        'language-uz'             => LanguageUzbek::class,
456        'language-vi'             => LanguageVietnamese::class,
457        'language-yi'             => LanguageYiddish::class,
458        'language-zh-Hans'        => LanguageChineseSimplified::class,
459        'language-zh-Hant'        => LanguageChineseTraditional::class,
460        'legacy-urls'             => RedirectLegacyUrlsModule::class,
461        'lifespans_chart'         => LifespansChartModule::class,
462        'lightbox'                => AlbumModule::class,
463        'lists-menu'              => ListsMenuModule::class,
464        'location_list'           => LocationListModule::class,
465        'logged_in'               => LoggedInUsersModule::class,
466        'login_block'             => LoginBlockModule::class,
467        'low_countries_rulers'    => LowCountriesRulers::class,
468        'map-link-bing'           => MapLinkBing::class,
469        'map-link-google'         => MapLinkGoogle::class,
470        'map-link-openstreetmap'  => MapLinkOpenStreetMap::class,
471        'map-location-geonames'   => MapGeoLocationGeonames::class,
472        'map-location-nominatim'  => MapGeoLocationNominatim::class,
473        'map-location-ors'        => MapGeoLocationOpenRouteService::class,
474        'mapbox'                  => MapBox::class,
475        'marriage_report'         => MarriageReportModule::class,
476        'matomo-analytics'        => MatomoAnalyticsModule::class,
477        'media'                   => MediaTabModule::class,
478        'media_list'              => MediaListModule::class,
479        'minimal'                 => MinimalTheme::class,
480        'missing_facts_report'    => MissingFactsReportModule::class,
481        'notes'                   => NotesTabModule::class,
482        'note_list'               => NoteListModule::class,
483        'occupation_report'       => OccupationReportModule::class,
484        'openrouteservice'        => OpenRouteServiceAutocomplete::class,
485        'openstreetmap'           => OpenStreetMap::class,
486        'pedigree-map'            => PedigreeMapModule::class,
487        'pedigree_chart'          => PedigreeChartModule::class,
488        'pedigree_report'         => PedigreeReportModule::class,
489        'personal_facts'          => IndividualFactsTabModule::class,
490        'places'                  => PlacesModule::class,
491        'places_list'             => PlaceHierarchyListModule::class,
492        'powered-by-webtrees'     => PoweredByWebtreesModule::class,
493        'privacy-policy'          => PrivacyPolicy::class,
494        'random_media'            => SlideShowModule::class,
495        'recent_changes'          => RecentChangesModule::class,
496        'relationships_chart'     => RelationshipsChartModule::class,
497        'relative_ext_report'     => RelatedIndividualsReportModule::class,
498        'relatives'               => RelativesTabModule::class,
499        'reports-menu'            => ReportsMenuModule::class,
500        'repository_list'         => RepositoryListModule::class,
501        'review_changes'          => ReviewChangesModule::class,
502        'search-menu'             => SearchMenuModule::class,
503        'share-anniversary'       => ShareAnniversaryModule::class,
504        'share-url'               => ShareUrlModule::class,
505        'sitemap'                 => SiteMapModule::class,
506        'source_list'             => SourceListModule::class,
507        'sources_tab'             => SourcesTabModule::class,
508        'statcounter'             => StatcounterModule::class,
509        'statistics_chart'        => StatisticsChartModule::class,
510        'stories'                 => StoriesModule::class,
511        'submitter_list'          => SubmitterListModule::class,
512        'theme_select'            => ThemeSelectModule::class,
513        'timeline_chart'          => TimelineChartModule::class,
514        'todays_events'           => OnThisDayModule::class,
515        'todo'                    => ResearchTaskModule::class,
516        'top10_givnnames'         => TopGivenNamesModule::class,
517        'top10_pageviews'         => TopPageViewsModule::class,
518        'top10_surnames'          => TopSurnamesModule::class,
519        'tree'                    => InteractiveTreeModule::class,
520        'trees-menu'              => TreesMenuModule::class,
521        'upcoming_events'         => UpcomingAnniversariesModule::class,
522        'us-presidents'           => USPresidents::class,
523        'user_blog'               => UserJournalModule::class,
524        'user_favorites'          => UserFavoritesModule::class,
525        'user_messages'           => UserMessagesModule::class,
526        'user_welcome'            => UserWelcomeModule::class,
527        'webtrees'                => WebtreesTheme::class,
528        'xenea'                   => XeneaTheme::class,
529        'yahrzeit'                => YahrzeitModule::class,
530    ];
531
532    /**
533     * A function to convert modules into their titles - to create option lists, etc.
534     *
535     * @return Closure(ModuleInterface):string
536     */
537    public function titleMapper(): Closure
538    {
539        return static function (ModuleInterface $module): string {
540            return $module->title();
541        };
542    }
543
544    /**
545     * Modules which (a) provide a specific function and (b) we have permission to see.
546     *
547     * @template T of ModuleInterface
548     *
549     * @param class-string<T> $interface
550     * @param Tree            $tree
551     * @param UserInterface   $user
552     *
553     * @return Collection<int,T>
554     */
555    public function findByComponent(string $interface, Tree $tree, UserInterface $user): Collection
556    {
557        return $this->findByInterface($interface, false, true)
558            ->filter(static function (ModuleInterface $module) use ($interface, $tree, $user): bool {
559                return $module->accessLevel($tree, $interface) >= Auth::accessLevel($tree, $user);
560            });
561    }
562
563    /**
564     * All modules which provide a specific function.
565     *
566     * @template T of ModuleInterface|MiddlewareInterface
567     *
568     * @param class-string<T> $interface
569     * @param bool            $include_disabled
570     * @param bool            $sort
571     *
572     * @return Collection<int,T&ModuleInterface>
573     */
574    public function findByInterface(string $interface, bool $include_disabled = false, bool $sort = false): Collection
575    {
576        /** @var Collection<int,T&ModuleInterface> $modules */
577        $modules = $this->all($include_disabled)
578            ->filter($this->interfaceFilter($interface));
579
580        switch ($interface) {
581            case ModuleFooterInterface::class:
582                /** @var Collection<int,T&ModuleInterface> */
583                return $modules->sort($this->footerComparator());
584
585            case ModuleMenuInterface::class:
586                /** @var Collection<int,T&ModuleInterface> */
587                return $modules->sort($this->menuComparator());
588
589            case ModuleSidebarInterface::class:
590                /** @var Collection<int,T&ModuleInterface> */
591                return $modules->sort($this->sidebarComparator());
592
593            case ModuleTabInterface::class:
594                /** @var Collection<int,T&ModuleInterface> */
595                return $modules->sort($this->tabComparator());
596
597            default:
598                if ($sort) {
599                    /** @var Collection<int,T&ModuleInterface> */
600                    return $modules->sort($this->moduleComparator());
601                }
602
603                return $modules;
604        }
605    }
606
607    /**
608     * All modules.
609     *
610     * @param bool $include_disabled
611     *
612     * @return Collection<int,ModuleInterface>
613     */
614    public function all(bool $include_disabled = false): Collection
615    {
616        return Registry::cache()->array()->remember('all-modules', function (): Collection {
617            // Modules have a default status, order etc.
618            // We can override these from database settings.
619            $module_info = DB::table('module')
620                ->get()
621                ->mapWithKeys(static function (object $row): array {
622                    return [$row->module_name => $row];
623                });
624
625            return $this->coreModules()
626                ->merge($this->customModules())
627                ->map(static function (ModuleInterface $module) use ($module_info): ModuleInterface {
628                    $info = $module_info->get($module->name());
629
630                    if (is_object($info)) {
631                        $module->setEnabled($info->status === 'enabled');
632
633                        if ($module instanceof ModuleFooterInterface && $info->footer_order !== null) {
634                            $module->setFooterOrder((int) $info->footer_order);
635                        }
636
637                        if ($module instanceof ModuleMenuInterface && $info->menu_order !== null) {
638                            $module->setMenuOrder((int) $info->menu_order);
639                        }
640
641                        if ($module instanceof ModuleSidebarInterface && $info->sidebar_order !== null) {
642                            $module->setSidebarOrder((int) $info->sidebar_order);
643                        }
644
645                        if ($module instanceof ModuleTabInterface && $info->tab_order !== null) {
646                            $module->setTabOrder((int) $info->tab_order);
647                        }
648                    } else {
649                        $module->setEnabled($module->isEnabledByDefault());
650
651                        DB::table('module')->insert([
652                            'module_name' => $module->name(),
653                            'status'      => $module->isEnabled() ? 'enabled' : 'disabled',
654                        ]);
655                    }
656
657                    return $module;
658                });
659        })->filter($this->enabledFilter($include_disabled));
660    }
661
662    /**
663     * All core modules in the system.
664     *
665     * @return Collection<int,ModuleInterface>
666     */
667    private function coreModules(): Collection
668    {
669        return Collection::make(self::CORE_MODULES)
670            ->map(static function (string $class, string $name): ModuleInterface {
671                $module = Registry::container()->get($class);
672
673                $module->setName($name);
674
675                return $module;
676            });
677    }
678
679    /**
680     * All custom modules in the system.  Custom modules are defined in modules_v4/
681     *
682     * @return Collection<int,ModuleCustomInterface>
683     */
684    private function customModules(): Collection
685    {
686        $pattern   = Webtrees::MODULES_DIR . '*/module.php';
687        $filenames = glob($pattern, GLOB_NOSORT);
688
689        return Collection::make($filenames)
690            ->filter(static function (string $filename): bool {
691                // Special characters will break PHP variable names.
692                // This also allows us to ignore modules called "foo.example" and "foo.disable"
693                $module_name = basename(dirname($filename));
694
695                foreach (['.', ' ', '[', ']'] as $character) {
696                    if (str_contains($module_name, $character)) {
697                        return false;
698                    }
699                }
700
701                return strlen($module_name) <= 30;
702            })
703            ->map(static function (string $filename): ?ModuleCustomInterface {
704                $module = self::load($filename);
705
706                if ($module instanceof ModuleCustomInterface) {
707                    $module->setName('_' . basename(dirname($filename)) . '_');
708
709                    return $module;
710                }
711
712                return null;
713            })
714            ->filter()
715            ->mapWithKeys(static function (ModuleCustomInterface $module): array {
716                return [$module->name() => $module];
717            });
718    }
719
720    /**
721     * Load a custom module in a static scope, to prevent it from modifying local or object variables.
722     *
723     * @param string $filename
724     *
725     * @return ModuleInterface|null
726     */
727    private static function load(string $filename): ?ModuleInterface
728    {
729        try {
730            return include $filename;
731        } catch (Throwable $exception) {
732            $module_name = basename(dirname($filename));
733            $message     = 'Fatal error in module: ' . $module_name . '<br>' . $exception;
734            FlashMessages::addMessage($message, 'danger');
735        }
736
737        return null;
738    }
739
740    /**
741     * A function filter modules by enabled/disabled
742     *
743     * @param bool $include_disabled
744     *
745     * @return Closure(ModuleInterface):bool
746     */
747    private function enabledFilter(bool $include_disabled): Closure
748    {
749        return static function (ModuleInterface $module) use ($include_disabled): bool {
750            return $include_disabled || $module->isEnabled();
751        };
752    }
753
754    /**
755     * A function filter modules by type
756     *
757     * @template T of ModuleInterface|MiddlewareInterface
758     *
759     * @param class-string<T> $interface
760     *
761     * @return Closure(ModuleInterface):bool
762     */
763    private function interfaceFilter(string $interface): Closure
764    {
765        return static function (ModuleInterface $module) use ($interface): bool {
766            return $module instanceof $interface;
767        };
768    }
769
770    /**
771     * A function to sort footers
772     *
773     * @return Closure(ModuleFooterInterface,ModuleFooterInterface):int
774     */
775    private function footerComparator(): Closure
776    {
777        return static function (ModuleFooterInterface $x, ModuleFooterInterface $y): int {
778            return $x->getFooterOrder() <=> $y->getFooterOrder();
779        };
780    }
781
782    /**
783     * A function to sort menus
784     *
785     * @return Closure(ModuleMenuInterface,ModuleMenuInterface):int
786     */
787    private function menuComparator(): Closure
788    {
789        return static function (ModuleMenuInterface $x, ModuleMenuInterface $y): int {
790            return $x->getMenuOrder() <=> $y->getMenuOrder();
791        };
792    }
793
794    /**
795     * A function to sort sidebars
796     *
797     * @return Closure(ModuleSidebarInterface,ModuleSidebarInterface):int
798     */
799    private function sidebarComparator(): Closure
800    {
801        return static function (ModuleSidebarInterface $x, ModuleSidebarInterface $y): int {
802            return $x->getSidebarOrder() <=> $y->getSidebarOrder();
803        };
804    }
805
806    /**
807     * A function to sort tabs
808     *
809     * @return Closure(ModuleTabInterface,ModuleTabInterface):int
810     */
811    private function tabComparator(): Closure
812    {
813        return static function (ModuleTabInterface $x, ModuleTabInterface $y): int {
814            return $x->getTabOrder() <=> $y->getTabOrder();
815        };
816    }
817
818    /**
819     * A function to sort modules by name.
820     *
821     * Languages have a "sortable" name, so that "British English" sorts as "English, British".
822     * This provides a more natural order in the language menu.
823     *
824     * @return Closure(ModuleInterface,ModuleInterface):int
825     */
826    private function moduleComparator(): Closure
827    {
828        return static function (ModuleInterface $x, ModuleInterface $y): int {
829            $title1 = $x instanceof ModuleLanguageInterface ? $x->locale()->endonymSortable() : $x->title();
830            $title2 = $y instanceof ModuleLanguageInterface ? $y->locale()->endonymSortable() : $y->title();
831
832            return I18N::comparator()($title1, $title2);
833        };
834    }
835
836    /**
837     * During setup, we'll need access to some languages.
838     *
839     * @return Collection<int,ModuleLanguageInterface>
840     */
841    public function setupLanguages(): Collection
842    {
843        return $this->coreModules()
844            ->filter(static function (ModuleInterface $module): bool {
845                return $module instanceof ModuleLanguageInterface && $module->isEnabledByDefault();
846            })
847            ->sort(static function (ModuleLanguageInterface $x, ModuleLanguageInterface $y): int {
848                return $x->locale()->endonymSortable() <=> $y->locale()->endonymSortable();
849            });
850    }
851
852    /**
853     * Find a specified module, if it is currently active.
854     *
855     * @param string $module_name
856     * @param bool   $include_disabled
857     *
858     * @return ModuleInterface|null
859     */
860    public function findByName(string $module_name, bool $include_disabled = false): ?ModuleInterface
861    {
862        return $this->all($include_disabled)
863            ->first(static function (ModuleInterface $module) use ($module_name): bool {
864                return $module->name() === $module_name;
865            });
866    }
867
868    /**
869     * Configuration settings are available through the various "module component" pages.
870     * For modules that do not provide a component, we need to list them separately.
871     *
872     * @param bool $include_disabled
873     *
874     * @return Collection<int,ModuleInterface>
875     */
876    public function otherModules(bool $include_disabled = false): Collection
877    {
878        return $this->findByInterface(ModuleInterface::class, $include_disabled, true)
879            ->filter(static function (ModuleInterface $module): bool {
880                foreach (self::COMPONENTS as $interface) {
881                    if ($module instanceof $interface) {
882                        return false;
883                    }
884                }
885
886                return true;
887            });
888    }
889
890    /**
891     * Generate a list of module names which exist in the database but not on disk.
892     *
893     * @return Collection<int,string>
894     */
895    public function deletedModules(): Collection
896    {
897        $database_modules = DB::table('module')->pluck('module_name');
898
899        $disk_modules = $this->all(true)
900            ->map(static function (ModuleInterface $module): string {
901                return $module->name();
902            });
903
904        return $database_modules->diff($disk_modules);
905    }
906
907    /**
908     * Boot all the modules.
909     *
910     * @param ModuleThemeInterface $current_theme
911     */
912    public function bootModules(ModuleThemeInterface $current_theme): void
913    {
914        foreach ($this->all() as $module) {
915            // Only bootstrap the current theme.
916            if ($module instanceof ModuleThemeInterface && $module !== $current_theme) {
917                continue;
918            }
919
920            $module->boot();
921        }
922    }
923
924    /**
925     * @return Collection<int,string>
926     */
927    public function componentsWithAccess(): Collection
928    {
929        return new Collection(self::COMPONENTS_WITH_ACCESS);
930    }
931
932    /**
933     * @return Collection<int,string>
934     */
935    public function componentsWithOrder(): Collection
936    {
937        return new Collection(self::COMPONENTS_WITH_SORT);
938    }
939}
940