xref: /webtrees/app/Services/ModuleService.php (revision fcfa147e10aaa6c7ff580c29bd6e5b88666befc1)
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\I18N;
26use Fisharebest\Webtrees\Module\AhnentafelReportModule;
27use Fisharebest\Webtrees\Module\AlbumModule;
28use Fisharebest\Webtrees\Module\AncestorsChartModule;
29use Fisharebest\Webtrees\Module\BatchUpdateModule;
30use Fisharebest\Webtrees\Module\BingWebmasterToolsModule;
31use Fisharebest\Webtrees\Module\BirthDeathMarriageReportModule;
32use Fisharebest\Webtrees\Module\BirthReportModule;
33use Fisharebest\Webtrees\Module\BranchesListModule;
34use Fisharebest\Webtrees\Module\BritishMonarchs;
35use Fisharebest\Webtrees\Module\BritishPrimeMinisters;
36use Fisharebest\Webtrees\Module\BritishSocialHistory;
37use Fisharebest\Webtrees\Module\CalendarMenuModule;
38use Fisharebest\Webtrees\Module\CemeteryReportModule;
39use Fisharebest\Webtrees\Module\CensusAssistantModule;
40use Fisharebest\Webtrees\Module\ChangeReportModule;
41use Fisharebest\Webtrees\Module\ChartsBlockModule;
42use Fisharebest\Webtrees\Module\ChartsMenuModule;
43use Fisharebest\Webtrees\Module\CkeditorModule;
44use Fisharebest\Webtrees\Module\ClippingsCartModule;
45use Fisharebest\Webtrees\Module\CloudsTheme;
46use Fisharebest\Webtrees\Module\ColorsTheme;
47use Fisharebest\Webtrees\Module\CompactTreeChartModule;
48use Fisharebest\Webtrees\Module\ContactsFooterModule;
49use Fisharebest\Webtrees\Module\CookieWarningModule;
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\RecentChangesModule;
177use Fisharebest\Webtrees\Module\RelatedIndividualsReportModule;
178use Fisharebest\Webtrees\Module\RelationshipsChartModule;
179use Fisharebest\Webtrees\Module\RelativesTabModule;
180use Fisharebest\Webtrees\Module\ReportsMenuModule;
181use Fisharebest\Webtrees\Module\RepositoryListModule;
182use Fisharebest\Webtrees\Module\ResearchTaskModule;
183use Fisharebest\Webtrees\Module\ReviewChangesModule;
184use Fisharebest\Webtrees\Module\SearchMenuModule;
185use Fisharebest\Webtrees\Module\SiteMapModule;
186use Fisharebest\Webtrees\Module\SlideShowModule;
187use Fisharebest\Webtrees\Module\SourceListModule;
188use Fisharebest\Webtrees\Module\SourcesTabModule;
189use Fisharebest\Webtrees\Module\StatcounterModule;
190use Fisharebest\Webtrees\Module\StatisticsChartModule;
191use Fisharebest\Webtrees\Module\StoriesModule;
192use Fisharebest\Webtrees\Module\ThemeSelectModule;
193use Fisharebest\Webtrees\Module\TimelineChartModule;
194use Fisharebest\Webtrees\Module\TopGivenNamesModule;
195use Fisharebest\Webtrees\Module\TopPageViewsModule;
196use Fisharebest\Webtrees\Module\TopSurnamesModule;
197use Fisharebest\Webtrees\Module\TreesMenuModule;
198use Fisharebest\Webtrees\Module\UpcomingAnniversariesModule;
199use Fisharebest\Webtrees\Module\UserFavoritesModule;
200use Fisharebest\Webtrees\Module\UserJournalModule;
201use Fisharebest\Webtrees\Module\UserMessagesModule;
202use Fisharebest\Webtrees\Module\UserWelcomeModule;
203use Fisharebest\Webtrees\Module\USPresidents;
204use Fisharebest\Webtrees\Module\WebtreesTheme;
205use Fisharebest\Webtrees\Module\WelcomeBlockModule;
206use Fisharebest\Webtrees\Module\XeneaTheme;
207use Fisharebest\Webtrees\Module\YahrzeitModule;
208use Fisharebest\Webtrees\Tree;
209use Fisharebest\Webtrees\Webtrees;
210use Illuminate\Database\Capsule\Manager as DB;
211use Illuminate\Support\Collection;
212use Illuminate\Support\Str;
213use stdClass;
214use Throwable;
215
216use function app;
217use function method_exists;
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 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        return include $filename;
618    }
619
620    /**
621     * A function filter modules by enabled/disabled
622     *
623     * @param bool $include_disabled
624     *
625     * @return Closure
626     */
627    private function enabledFilter(bool $include_disabled): Closure
628    {
629        return static function (ModuleInterface $module) use ($include_disabled): bool {
630            return $include_disabled || $module->isEnabled();
631        };
632    }
633
634    /**
635     * A function filter modules by type
636     *
637     * @param string $interface
638     *
639     * @return Closure
640     */
641    private function interfaceFilter(string $interface): Closure
642    {
643        return static function (ModuleInterface $module) use ($interface): bool {
644            return $module instanceof $interface;
645        };
646    }
647
648    /**
649     * A function to sort footers
650     *
651     * @return Closure
652     */
653    private function footerSorter(): Closure
654    {
655        return static function (ModuleFooterInterface $x, ModuleFooterInterface $y): int {
656            return $x->getFooterOrder() <=> $y->getFooterOrder();
657        };
658    }
659
660    /**
661     * A function to sort menus
662     *
663     * @return Closure
664     */
665    private function menuSorter(): Closure
666    {
667        return static function (ModuleMenuInterface $x, ModuleMenuInterface $y): int {
668            return $x->getMenuOrder() <=> $y->getMenuOrder();
669        };
670    }
671
672    /**
673     * A function to sort menus
674     *
675     * @return Closure
676     */
677    private function sidebarSorter(): Closure
678    {
679        return static function (ModuleSidebarInterface $x, ModuleSidebarInterface $y): int {
680            return $x->getSidebarOrder() <=> $y->getSidebarOrder();
681        };
682    }
683
684    /**
685     * A function to sort menus
686     *
687     * @return Closure
688     */
689    private function tabSorter(): Closure
690    {
691        return static function (ModuleTabInterface $x, ModuleTabInterface $y): int {
692            return $x->getTabOrder() <=> $y->getTabOrder();
693        };
694    }
695
696    /**
697     * A function to sort modules by name.
698     *
699     * Languages have a "sortable" name, so that "British English" sorts as "English, British".
700     * This provides a more natural order in the language menu.
701     *
702     * @return Closure
703     */
704    private function moduleSorter(): Closure
705    {
706        return static function (ModuleInterface $x, ModuleInterface $y): int {
707            $title1 = $x instanceof ModuleLanguageInterface ? $x->locale()->endonymSortable() : $x->title();
708            $title2 = $y instanceof ModuleLanguageInterface ? $y->locale()->endonymSortable() : $y->title();
709
710            return I18N::strcasecmp($title1, $title2);
711        };
712    }
713
714    /**
715     * Find a specified module, if it is currently active.
716     *
717     * @param string $module_name
718     * @param bool   $include_disabled
719     *
720     * @return ModuleInterface|null
721     */
722    public function findByName(string $module_name, bool $include_disabled = false): ?ModuleInterface
723    {
724        return $this->all($include_disabled)
725            ->first(static function (ModuleInterface $module) use ($module_name): bool {
726                return $module->name() === $module_name;
727            });
728    }
729
730    /**
731     * Configuration settings are available through the various "module component" pages.
732     * For modules that do not provide a component, we need to list them separately.
733     *
734     * @param bool $include_disabled
735     *
736     * @return Collection
737     */
738    public function otherModules(bool $include_disabled = false): Collection
739    {
740        return $this->findByInterface(ModuleInterface::class, $include_disabled, true)
741            ->filter(static function (ModuleInterface $module): bool {
742                foreach (self::COMPONENTS as $interface) {
743                    if ($module instanceof $interface) {
744                        return false;
745                    }
746                }
747
748                return true;
749            });
750    }
751
752    /**
753     * Generate a list of module names which exist in the database but not on disk.
754     *
755     * @return Collection
756     */
757    public function deletedModules(): Collection
758    {
759        $database_modules = DB::table('module')->pluck('module_name');
760
761        $disk_modules = $this->all(true)
762            ->map(static function (ModuleInterface $module): string {
763                return $module->name();
764            });
765
766        return $database_modules->diff($disk_modules);
767    }
768
769    /**
770     * Boot all the modules.
771     *
772     * @param ModuleThemeInterface $current_theme
773     */
774    public function bootModules(ModuleThemeInterface $current_theme): void
775    {
776        $bootable_modules = $this->all()->filter(static function (ModuleInterface $module) {
777            return method_exists($module, 'boot');
778        });
779
780        foreach ($bootable_modules as $module) {
781            // Only bootstrap the current theme.
782            if ($module instanceof ModuleThemeInterface && $module !== $current_theme) {
783                continue;
784            }
785
786            app()->dispatch($module, 'boot');
787        }
788    }
789}
790