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