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