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