xref: /webtrees/app/Module/ModuleThemeTrait.php (revision a6656bb5f7cff260502deaf88d26942745ca1e1e)
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\Module;
21
22use Fisharebest\Webtrees\Auth;
23use Fisharebest\Webtrees\Fact;
24use Fisharebest\Webtrees\Gedcom;
25use Fisharebest\Webtrees\GedcomTag;
26use Fisharebest\Webtrees\Http\RequestHandlers\AccountEdit;
27use Fisharebest\Webtrees\Http\RequestHandlers\ControlPanel;
28use Fisharebest\Webtrees\Http\RequestHandlers\LoginPage;
29use Fisharebest\Webtrees\Http\RequestHandlers\Logout;
30use Fisharebest\Webtrees\Http\RequestHandlers\PendingChanges;
31use Fisharebest\Webtrees\Http\RequestHandlers\SelectLanguage;
32use Fisharebest\Webtrees\Http\RequestHandlers\SelectTheme;
33use Fisharebest\Webtrees\Http\RequestHandlers\TreePage;
34use Fisharebest\Webtrees\Http\RequestHandlers\TreePageEdit;
35use Fisharebest\Webtrees\Http\RequestHandlers\UserPage;
36use Fisharebest\Webtrees\Http\RequestHandlers\UserPageEdit;
37use Fisharebest\Webtrees\I18N;
38use Fisharebest\Webtrees\Individual;
39use Fisharebest\Webtrees\Menu;
40use Fisharebest\Webtrees\Services\ModuleService;
41use Fisharebest\Webtrees\Tree;
42use Fisharebest\Webtrees\User;
43use Fisharebest\Webtrees\Webtrees;
44use Psr\Http\Message\ServerRequestInterface;
45
46use function app;
47use function assert;
48use function route;
49
50/**
51 * Trait ModuleThemeTrait - default implementation of ModuleThemeInterface
52 */
53trait ModuleThemeTrait
54{
55    /**
56     * @return string
57     */
58    abstract public function name(): string;
59
60    /**
61     * @return string
62     */
63    abstract public function title(): string;
64
65    /**
66     * A sentence describing what this module does.
67     *
68     * @return string
69     */
70    public function description(): string
71    {
72        return I18N::translate('Theme') . ' — ' . $this->title();
73    }
74
75    /**
76     * Generate the facts, for display in charts.
77     *
78     * @param Individual $individual
79     *
80     * @return string
81     */
82    public function individualBoxFacts(Individual $individual): string
83    {
84        $html = '';
85
86        $opt_tags = preg_split('/\W/', $individual->tree()->getPreference('CHART_BOX_TAGS'), 0, PREG_SPLIT_NO_EMPTY);
87        // Show BIRT or equivalent event
88        foreach (Gedcom::BIRTH_EVENTS as $birttag) {
89            if (!in_array($birttag, $opt_tags, true)) {
90                $event = $individual->facts([$birttag])->first();
91                if ($event instanceof Fact) {
92                    $html .= $event->summary();
93                    break;
94                }
95            }
96        }
97        // Show optional events (before death)
98        foreach ($opt_tags as $key => $tag) {
99            if (!in_array($tag, Gedcom::DEATH_EVENTS, true)) {
100                $event = $individual->facts([$tag])->first();
101                if ($event instanceof Fact) {
102                    $html .= $event->summary();
103                    unset($opt_tags[$key]);
104                }
105            }
106        }
107        // Show DEAT or equivalent event
108        foreach (Gedcom::DEATH_EVENTS as $deattag) {
109            $event = $individual->facts([$deattag])->first();
110            if ($event instanceof Fact) {
111                $html .= $event->summary();
112                if (in_array($deattag, $opt_tags, true)) {
113                    unset($opt_tags[array_search($deattag, $opt_tags, true)]);
114                }
115                break;
116            }
117        }
118        // Show remaining optional events (after death)
119        foreach ($opt_tags as $tag) {
120            $event = $individual->facts([$tag])->first();
121            if ($event instanceof Fact) {
122                $html .= $event->summary();
123            }
124        }
125
126        return $html;
127    }
128
129    /**
130     * Links, to show in chart boxes;
131     *
132     * @param Individual $individual
133     *
134     * @return Menu[]
135     */
136    public function individualBoxMenu(Individual $individual): array
137    {
138        $menus = array_merge(
139            $this->individualBoxMenuCharts($individual),
140            $this->individualBoxMenuFamilyLinks($individual)
141        );
142
143        return $menus;
144    }
145
146    /**
147     * Chart links, to show in chart boxes;
148     *
149     * @param Individual $individual
150     *
151     * @return Menu[]
152     */
153    public function individualBoxMenuCharts(Individual $individual): array
154    {
155        $menus = [];
156        foreach (app(ModuleService::class)->findByComponent(ModuleChartInterface::class, $individual->tree(), Auth::user()) as $chart) {
157            $menu = $chart->chartBoxMenu($individual);
158            if ($menu) {
159                $menus[] = $menu;
160            }
161        }
162
163        usort($menus, static function (Menu $x, Menu $y): int {
164            return I18N::strcasecmp($x->getLabel(), $y->getLabel());
165        });
166
167        return $menus;
168    }
169
170    /**
171     * Family links, to show in chart boxes.
172     *
173     * @param Individual $individual
174     *
175     * @return Menu[]
176     */
177    public function individualBoxMenuFamilyLinks(Individual $individual): array
178    {
179        $menus = [];
180
181        foreach ($individual->spouseFamilies() as $family) {
182            $menus[] = new Menu('<strong>' . I18N::translate('Family with spouse') . '</strong>', $family->url());
183            $spouse  = $family->spouse($individual);
184            if ($spouse && $spouse->canShowName()) {
185                $menus[] = new Menu($spouse->fullName(), $spouse->url());
186            }
187            foreach ($family->children() as $child) {
188                if ($child->canShowName()) {
189                    $menus[] = new Menu($child->fullName(), $child->url());
190                }
191            }
192        }
193
194        return $menus;
195    }
196
197    /**
198     * Generate a menu item to change the blocks on the current tree/user page.
199     *
200     * @param Tree $tree
201     *
202     * @return Menu|null
203     */
204    public function menuChangeBlocks(Tree $tree): ?Menu
205    {
206        /** @var ServerRequestInterface $request */
207        $request = app(ServerRequestInterface::class);
208
209        $route = $request->getAttribute('route');
210
211        if (Auth::check() && $route === UserPage::class) {
212            return new Menu(I18N::translate('Customize this page'), route(UserPageEdit::class, ['tree' => $tree->name()]), 'menu-change-blocks');
213        }
214
215        if (Auth::isManager($tree) && $route === TreePage::class) {
216            return new Menu(I18N::translate('Customize this page'), route(TreePageEdit::class, ['tree' => $tree->name()]), 'menu-change-blocks');
217        }
218
219        return null;
220    }
221
222    /**
223     * Generate a menu item for the control panel.
224     *
225     * @param Tree $tree
226     *
227     * @return Menu|null
228     */
229    public function menuControlPanel(Tree $tree): ?Menu
230    {
231        if (Auth::isAdmin()) {
232            return new Menu(I18N::translate('Control panel'), route(ControlPanel::class), 'menu-admin');
233        }
234
235        if (Auth::isManager($tree)) {
236            return new Menu(I18N::translate('Control panel'), route('manage-trees', ['tree' => $tree->name()]), 'menu-admin');
237        }
238
239        return null;
240    }
241
242    /**
243     * A menu to show a list of available languages.
244     *
245     * @return Menu|null
246     */
247    public function menuLanguages(): ?Menu
248    {
249        $menu = new Menu(I18N::translate('Language'), '#', 'menu-language');
250
251        foreach (I18N::activeLocales() as $active_locale) {
252            $language_tag = $active_locale->languageTag();
253            $class        = 'menu-language-' . $language_tag . (I18N::languageTag() === $language_tag ? ' active' : '');
254            $menu->addSubmenu(new Menu($active_locale->endonym(), '#', $class, [
255                'data-post-url' => route(SelectLanguage::class, ['language' => $language_tag]),
256            ]));
257        }
258
259        if (count($menu->getSubmenus()) > 1) {
260            return $menu;
261        }
262
263        return null;
264    }
265
266    /**
267     * A login menu option (or null if we are already logged in).
268     *
269     * @return Menu|null
270     */
271    public function menuLogin(): ?Menu
272    {
273        if (Auth::check()) {
274            return null;
275        }
276
277        $request = app(ServerRequestInterface::class);
278
279        // Return to this page after login...
280        $redirect = $request->getQueryParams()['url'] ?? (string) $request->getUri();
281
282        $tree = $request->getAttribute('tree');
283
284        // ...but switch from the tree-page to the user-page
285        if ($request->getAttribute('route') === TreePage::class) {
286            $redirect = route(UserPage::class, ['tree' => $tree instanceof Tree ? $tree->name() : null]);
287        }
288
289        // Stay on the same tree page
290        $url  = route(LoginPage::class, ['tree' => $tree instanceof Tree ? $tree->name() : null, 'url' => $redirect]);
291
292        return new Menu(I18N::translate('Sign in'), $url, 'menu-login', ['rel' => 'nofollow']);
293    }
294
295    /**
296     * A logout menu option (or null if we are already logged out).
297     *
298     * @return Menu|null
299     */
300    public function menuLogout(): ?Menu
301    {
302        if (Auth::check()) {
303            $parameters = [
304                'data-post-url' => route(Logout::class),
305            ];
306
307            return new Menu(I18N::translate('Sign out'), '#', 'menu-logout', $parameters);
308        }
309
310        return null;
311    }
312
313    /**
314     * A link to allow users to edit their account settings.
315     *
316     * @param Tree|null $tree
317     *
318     * @return Menu
319     */
320    public function menuMyAccount(?Tree $tree): Menu
321    {
322        $url = route(AccountEdit::class, ['tree' => $tree instanceof Tree ? $tree->name() : null]);
323
324        return new Menu(I18N::translate('My account'), $url);
325    }
326
327    /**
328     * A link to the user's individual record (individual.php).
329     *
330     * @param Tree $tree
331     *
332     * @return Menu|null
333     */
334    public function menuMyIndividualRecord(Tree $tree): ?Menu
335    {
336        $record = Individual::getInstance($tree->getUserPreference(Auth::user(), User::PREF_TREE_ACCOUNT_XREF), $tree);
337
338        if ($record) {
339            return new Menu(I18N::translate('My individual record'), $record->url(), 'menu-myrecord');
340        }
341
342        return null;
343    }
344
345    /**
346     * A link to the user's personal home page.
347     *
348     * @param Tree $tree
349     *
350     * @return Menu
351     */
352    public function menuMyPage(Tree $tree): Menu
353    {
354        return new Menu(I18N::translate('My page'), route(UserPage::class, ['tree' => $tree->name()]), 'menu-mypage');
355    }
356
357    /**
358     * A menu for the user's personal pages.
359     *
360     * @param Tree|null $tree
361     *
362     * @return Menu|null
363     */
364    public function menuMyPages(?Tree $tree): ?Menu
365    {
366        if (Auth::id()) {
367            if ($tree instanceof Tree) {
368                return new Menu(I18N::translate('My pages'), '#', 'menu-mymenu', [], array_filter([
369                    $this->menuMyPage($tree),
370                    $this->menuMyIndividualRecord($tree),
371                    $this->menuMyPedigree($tree),
372                    $this->menuMyAccount($tree),
373                    $this->menuControlPanel($tree),
374                    $this->menuChangeBlocks($tree),
375                ]));
376            }
377
378            return $this->menuMyAccount($tree);
379        }
380
381        return null;
382    }
383
384    /**
385     * A link to the user's individual record.
386     *
387     * @param Tree $tree
388     *
389     * @return Menu|null
390     */
391    public function menuMyPedigree(Tree $tree): ?Menu
392    {
393        $gedcomid = $tree->getUserPreference(Auth::user(), User::PREF_TREE_ACCOUNT_XREF);
394
395        $pedigree_chart = app(ModuleService::class)->findByComponent(ModuleChartInterface::class, $tree, Auth::user())
396            ->filter(static function (ModuleInterface $module): bool {
397                return $module instanceof PedigreeChartModule;
398            });
399
400        if ($gedcomid !== '' && $pedigree_chart instanceof PedigreeChartModule) {
401            return new Menu(
402                I18N::translate('My pedigree'),
403                route('pedigree', [
404                    'xref' => $gedcomid,
405                    'tree'  => $tree->name(),
406                ]),
407                'menu-mypedigree'
408            );
409        }
410
411        return null;
412    }
413
414    /**
415     * Create a pending changes menu.
416     *
417     * @param Tree|null $tree
418     *
419     * @return Menu|null
420     */
421    public function menuPendingChanges(?Tree $tree): ?Menu
422    {
423        if ($tree instanceof Tree && $tree->hasPendingEdit() && Auth::isModerator($tree)) {
424            $url = route(PendingChanges::class, [
425                'tree' => $tree->name(),
426                'url' => (string) app(ServerRequestInterface::class)->getUri(),
427            ]);
428
429            return new Menu(I18N::translate('Pending changes'), $url, 'menu-pending');
430        }
431
432        return null;
433    }
434
435    /**
436     * Themes menu.
437     *
438     * @return Menu|null
439     */
440    public function menuThemes(): ?Menu
441    {
442        $themes = app(ModuleService::class)->findByInterface(ModuleThemeInterface::class, false, true);
443
444        $current_theme = app(ModuleThemeInterface::class);
445
446        if ($themes->count() > 1) {
447            $submenus = $themes->map(static function (ModuleThemeInterface $theme) use ($current_theme): Menu {
448                $active     = $theme->name() === $current_theme->name();
449                $class      = 'menu-theme-' . $theme->name() . ($active ? ' active' : '');
450
451                return new Menu($theme->title(), '#', $class, [
452                    'data-post-url' => route(SelectTheme::class, ['theme' => $theme->name()]),
453                ]);
454            });
455
456            return new Menu(I18N::translate('Theme'), '#', 'menu-theme', [], $submenus->all());
457        }
458
459        return null;
460    }
461
462    /**
463     * Misecellaneous dimensions, fonts, styles, etc.
464     *
465     * @param string $parameter_name
466     *
467     * @return string|int|float
468     */
469    public function parameter($parameter_name)
470    {
471        return '';
472    }
473
474    /**
475     * Generate a list of items for the main menu.
476     *
477     * @param Tree|null $tree
478     *
479     * @return Menu[]
480     */
481    public function genealogyMenu(?Tree $tree): array
482    {
483        if ($tree === null) {
484            return [];
485        }
486
487        return app(ModuleService::class)->findByComponent(ModuleMenuInterface::class, $tree, Auth::user())
488            ->map(static function (ModuleMenuInterface $menu) use ($tree): ?Menu {
489                return $menu->getMenu($tree);
490            })
491            ->filter()
492            ->all();
493    }
494
495    /**
496     * Create the genealogy menu.
497     *
498     * @param Menu[] $menus
499     *
500     * @return string
501     */
502    public function genealogyMenuContent(array $menus): string
503    {
504        return implode('', array_map(static function (Menu $menu): string {
505            return $menu->bootstrap4();
506        }, $menus));
507    }
508
509    /**
510     * Generate a list of items for the user menu.
511     *
512     * @param Tree|null $tree
513     *
514     * @return Menu[]
515     */
516    public function userMenu(?Tree $tree): array
517    {
518        return array_filter([
519            $this->menuPendingChanges($tree),
520            $this->menuMyPages($tree),
521            $this->menuThemes(),
522            $this->menuLanguages(),
523            $this->menuLogin(),
524            $this->menuLogout(),
525        ]);
526    }
527
528    /**
529     * A list of CSS files to include for this page.
530     *
531     * @return string[]
532     */
533    public function stylesheets(): array
534    {
535        return [];
536    }
537}
538