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