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