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