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