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