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