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