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