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