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