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