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