xref: /webtrees/app/Module/TimelineChartModule.php (revision 541cf44d763a8aa5906f3fce58ca6b0ac3a25986)
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\Module;
21
22use Aura\Router\RouterContainer;
23use Fig\Http\Message\RequestMethodInterface;
24use Fisharebest\Webtrees\Auth;
25use Fisharebest\Webtrees\Date\GregorianDate;
26use Fisharebest\Webtrees\Fact;
27use Fisharebest\Webtrees\GedcomRecord;
28use Fisharebest\Webtrees\I18N;
29use Fisharebest\Webtrees\Individual;
30use Fisharebest\Webtrees\Registry;
31use Fisharebest\Webtrees\Tree;
32use Fisharebest\Webtrees\Validator;
33use Illuminate\Support\Collection;
34use Psr\Http\Message\ResponseInterface;
35use Psr\Http\Message\ServerRequestInterface;
36use Psr\Http\Server\RequestHandlerInterface;
37
38use function app;
39use function assert;
40use function redirect;
41use function route;
42
43/**
44 * Class TimelineChartModule
45 */
46class TimelineChartModule extends AbstractModule implements ModuleChartInterface, RequestHandlerInterface
47{
48    use ModuleChartTrait;
49
50    protected const ROUTE_URL = '/tree/{tree}/timeline-{scale}';
51
52    // Defaults
53    protected const DEFAULT_SCALE      = 10;
54    protected const DEFAULT_PARAMETERS = [
55        'scale' => self::DEFAULT_SCALE,
56    ];
57
58    // Limits
59    protected const MINIMUM_SCALE = 1;
60    protected const MAXIMUM_SCALE = 200;
61
62    // GEDCOM events that may have DATE data, but should not be displayed
63    protected const NON_FACTS = [
64        'FAM:CHAN',
65        'INDI:BAPL',
66        'INDI:CHAN',
67        'INDI:ENDL',
68        'INDI:SLGC',
69        'INDI:SLGS',
70        'INDI:_TODO',
71    ];
72
73    protected const BOX_HEIGHT = 30;
74
75    /**
76     * Initialization.
77     *
78     * @return void
79     */
80    public function boot(): void
81    {
82        $router_container = app(RouterContainer::class);
83        assert($router_container instanceof RouterContainer);
84
85        $router_container->getMap()
86            ->get(static::class, static::ROUTE_URL, $this)
87            ->allows(RequestMethodInterface::METHOD_POST);
88    }
89
90    /**
91     * How should this module be identified in the control panel, etc.?
92     *
93     * @return string
94     */
95    public function title(): string
96    {
97        /* I18N: Name of a module/chart */
98        return I18N::translate('Timeline');
99    }
100
101    /**
102     * A sentence describing what this module does.
103     *
104     * @return string
105     */
106    public function description(): string
107    {
108        /* I18N: Description of the “TimelineChart” module */
109        return I18N::translate('A timeline displaying individual events.');
110    }
111
112    /**
113     * CSS class for the URL.
114     *
115     * @return string
116     */
117    public function chartMenuClass(): string
118    {
119        return 'menu-chart-timeline';
120    }
121
122    /**
123     * The URL for this chart.
124     *
125     * @param Individual                                $individual
126     * @param array<bool|int|string|array<string>|null> $parameters
127     *
128     * @return string
129     */
130    public function chartUrl(Individual $individual, array $parameters = []): string
131    {
132        return route(static::class, [
133                'tree'  => $individual->tree()->name(),
134                'xrefs' => [$individual->xref()],
135            ] + $parameters + self::DEFAULT_PARAMETERS);
136    }
137
138    /**
139     * @param ServerRequestInterface $request
140     *
141     * @return ResponseInterface
142     */
143    public function handle(ServerRequestInterface $request): ResponseInterface
144    {
145        $tree  = Validator::attributes($request)->tree();
146        $user  = Validator::attributes($request)->user();
147        $scale = Validator::attributes($request)->isBetween(self::MINIMUM_SCALE, self::MAXIMUM_SCALE)->integer('scale');
148        $xrefs = Validator::queryParams($request)->array('xrefs');
149        $ajax  = Validator::queryParams($request)->boolean('ajax', false);
150        $params = (array) $request->getParsedBody();
151        $add = $params['add'] ?? '';
152
153        $xrefs[] = $add;
154        $xrefs = array_filter(array_unique($xrefs));
155
156        // Convert POST requests into GET requests for pretty URLs.
157        if ($request->getMethod() === RequestMethodInterface::METHOD_POST) {
158            return redirect(route(static::class, [
159                'tree'  => $tree->name(),
160                'scale' => $scale,
161                'xrefs' => $xrefs,
162            ]));
163        }
164
165        Auth::checkComponentAccess($this, ModuleChartInterface::class, $tree, $user);
166
167        // Find the requested individuals.
168        $individuals = (new Collection($xrefs))
169            ->uniqueStrict()
170            ->map(static function (string $xref) use ($tree): ?Individual {
171                return Registry::individualFactory()->make($xref, $tree);
172            })
173            ->filter()
174            ->filter(GedcomRecord::accessFilter());
175
176        // Generate URLs omitting each xref.
177        $remove_urls = [];
178
179        foreach ($individuals as $exclude) {
180            $xrefs_1 = $individuals
181                ->filter(static function (Individual $individual) use ($exclude): bool {
182                    return $individual->xref() !== $exclude->xref();
183                })
184                ->map(static function (Individual $individual): string {
185                    return $individual->xref();
186                });
187
188            $remove_urls[$exclude->xref()] = route(static::class, [
189                'tree'  => $tree->name(),
190                'scale' => $scale,
191                'xrefs' => $xrefs_1->all(),
192            ]);
193        }
194
195        $individuals = array_map(static function (string $xref) use ($tree): ?Individual {
196            return Registry::individualFactory()->make($xref, $tree);
197        }, $xrefs);
198
199        $individuals = array_filter($individuals, static function (?Individual $individual): bool {
200            return $individual instanceof Individual && $individual->canShow();
201        });
202
203        if ($ajax) {
204            $this->layout = 'layouts/ajax';
205
206            return $this->chart($tree, $xrefs, $scale);
207        }
208
209        $reset_url = route(static::class, [
210            'scale' => self::DEFAULT_SCALE,
211            'tree'  => $tree->name(),
212        ]);
213
214        $zoom_in_url = route(static::class, [
215            'scale' => min(self::MAXIMUM_SCALE, $scale + (int) ($scale * 0.4 + 1)),
216            'tree'  => $tree->name(),
217            'xrefs' => $xrefs,
218        ]);
219
220        $zoom_out_url = route(static::class, [
221            'scale' => max(self::MINIMUM_SCALE, $scale - (int) ($scale * 0.4 + 1)),
222            'tree'  => $tree->name(),
223            'xrefs' => $xrefs,
224        ]);
225
226        $ajax_url = route(static::class, [
227            'ajax'  => true,
228            'scale' => $scale,
229            'tree'  => $tree->name(),
230            'xrefs' => $xrefs,
231        ]);
232
233        return $this->viewResponse('modules/timeline-chart/page', [
234            'ajax_url'     => $ajax_url,
235            'individuals'  => $individuals,
236            'module'       => $this->name(),
237            'remove_urls'  => $remove_urls,
238            'reset_url'    => $reset_url,
239            'scale'        => $scale,
240            'title'        => $this->title(),
241            'tree'         => $tree,
242            'zoom_in_url'  => $zoom_in_url,
243            'zoom_out_url' => $zoom_out_url,
244        ]);
245    }
246
247    /**
248     * @param Tree          $tree
249     * @param array<string> $xrefs
250     * @param int           $scale
251     *
252     * @return ResponseInterface
253     */
254    protected function chart(Tree $tree, array $xrefs, int $scale): ResponseInterface
255    {
256        /** @var Individual[] $individuals */
257        $individuals = array_map(static function (string $xref) use ($tree): ?Individual {
258            return Registry::individualFactory()->make($xref, $tree);
259        }, $xrefs);
260
261        $individuals = array_filter($individuals, static function (?Individual $individual): bool {
262            return $individual instanceof Individual && $individual->canShow();
263        });
264
265        $baseyear    = (int) date('Y');
266        $topyear     = 0;
267        $indifacts   = new Collection();
268        $birthyears  = [];
269        $birthmonths = [];
270        $birthdays   = [];
271
272        foreach ($individuals as $individual) {
273            $bdate = $individual->getBirthDate();
274            if ($bdate->isOK()) {
275                $date = new GregorianDate($bdate->minimumJulianDay());
276
277                $birthyears [$individual->xref()] = $date->year;
278                $birthmonths[$individual->xref()] = max(1, $date->month);
279                $birthdays  [$individual->xref()] = max(1, $date->day);
280            }
281            // find all the fact information
282            $facts = $individual->facts();
283            foreach ($individual->spouseFamilies() as $family) {
284                foreach ($family->facts() as $fact) {
285                    $facts->push($fact);
286                }
287            }
288
289            foreach ($facts as $event) {
290                if (!in_array($event->tag(), self::NON_FACTS, true)) {
291                    // check for a date
292                    $date = $event->date();
293                    if ($date->isOK()) {
294                        $date     = new GregorianDate($date->minimumJulianDay());
295                        $baseyear = min($baseyear, $date->year);
296                        $topyear  = max($topyear, $date->year);
297
298                        if (!$individual->isDead()) {
299                            $topyear = max($topyear, (int) date('Y'));
300                        }
301
302                        $indifacts->push($event);
303                    }
304                }
305            }
306        }
307
308        // do not add the same fact twice (prevents marriages from being added multiple times)
309        $indifacts = $indifacts->uniqueStrict(static function (Fact $fact): string {
310            return $fact->id();
311        });
312
313        if ($scale === 0) {
314            $scale = (int) (($topyear - $baseyear) / 20 * $indifacts->count() / 4);
315            if ($scale < 6) {
316                $scale = 6;
317            }
318        }
319        if ($scale < 2) {
320            $scale = 2;
321        }
322        $baseyear -= 5;
323        $topyear  += 5;
324
325        $indifacts = Fact::sortFacts($indifacts);
326
327        $html = view('modules/timeline-chart/chart', [
328            'baseyear'    => $baseyear,
329            'bheight'     => self::BOX_HEIGHT,
330            'birthdays'   => $birthdays,
331            'birthmonths' => $birthmonths,
332            'birthyears'  => $birthyears,
333            'indifacts'   => $indifacts,
334            'individuals' => $individuals,
335            'placements'  => [],
336            'scale'       => $scale,
337            'topyear'     => $topyear,
338        ]);
339
340        return response($html);
341    }
342}
343