xref: /webtrees/app/Module/TimelineChartModule.php (revision 5fb61fc65b99b2d532a8e4bc9f5ba7068636203f)
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\Registry;
28use Fisharebest\Webtrees\GedcomRecord;
29use Fisharebest\Webtrees\I18N;
30use Fisharebest\Webtrees\Individual;
31use Fisharebest\Webtrees\Tree;
32use Illuminate\Support\Collection;
33use Psr\Http\Message\ResponseInterface;
34use Psr\Http\Message\ServerRequestInterface;
35use Psr\Http\Server\RequestHandlerInterface;
36
37use function app;
38use function assert;
39use function redirect;
40use function route;
41
42/**
43 * Class TimelineChartModule
44 */
45class TimelineChartModule extends AbstractModule implements ModuleChartInterface, RequestHandlerInterface
46{
47    use ModuleChartTrait;
48
49    protected const ROUTE_URL  = '/tree/{tree}/timeline-{scale}';
50
51    // Defaults
52    protected const DEFAULT_SCALE      = 10;
53    protected const DEFAULT_PARAMETERS = [
54        'scale' => self::DEFAULT_SCALE,
55    ];
56
57    // Limits
58    protected const MINIMUM_SCALE = 1;
59    protected const MAXIMUM_SCALE = 200;
60
61    // GEDCOM events that may have DATE data, but should not be displayed
62    protected const NON_FACTS = [
63        'FAM:CHAN',
64        'INDI:BAPL',
65        'INDI:CHAN',
66        'INDI:ENDL',
67        'INDI:SLGC',
68        'INDI:SLGS',
69        'INDI:_TODO',
70    ];
71
72    // Box height
73    protected const BHEIGHT = 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 mixed[]    $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 = $request->getAttribute('tree');
146        assert($tree instanceof Tree);
147
148        $user  = $request->getAttribute('user');
149        $scale = (int) $request->getAttribute('scale');
150        $xrefs = $request->getQueryParams()['xrefs'] ?? [];
151        $ajax  = $request->getQueryParams()['ajax'] ?? '';
152
153
154        $params = (array) $request->getParsedBody();
155
156        $add  = $params['add'] ?? '';
157
158        Auth::checkComponentAccess($this, ModuleChartInterface::class, $tree, $user);
159
160        $scale = min($scale, self::MAXIMUM_SCALE);
161        $scale = max($scale, self::MINIMUM_SCALE);
162
163        $xrefs[] = $add;
164        $xrefs = array_filter(array_unique($xrefs));
165
166        // Convert POST requests into GET requests for pretty URLs.
167        if ($request->getMethod() === RequestMethodInterface::METHOD_POST) {
168            return redirect(route(static::class, [
169                'scale' => $scale,
170                'tree'  => $tree->name(),
171                'xrefs' => $xrefs,
172            ]));
173        }
174
175        // Find the requested individuals.
176        $individuals = (new Collection($xrefs))
177            ->uniqueStrict()
178            ->map(static function (string $xref) use ($tree): ?Individual {
179                return Registry::individualFactory()->make($xref, $tree);
180            })
181            ->filter()
182            ->filter(GedcomRecord::accessFilter());
183
184        // Generate URLs omitting each xref.
185        $remove_urls = [];
186
187        foreach ($individuals as $exclude) {
188            $xrefs_1 = $individuals
189                ->filter(static function (Individual $individual) use ($exclude): bool {
190                    return $individual->xref() !== $exclude->xref();
191                })
192                ->map(static function (Individual $individual): string {
193                    return $individual->xref();
194                });
195
196            $remove_urls[$exclude->xref()] = route(static::class, [
197                'tree'  => $tree->name(),
198                'scale' => $scale,
199                'xrefs' => $xrefs_1->all(),
200            ]);
201        }
202
203        $individuals = array_map(static function (string $xref) use ($tree): ?Individual {
204            return Registry::individualFactory()->make($xref, $tree);
205        }, $xrefs);
206
207        $individuals = array_filter($individuals, static function (?Individual $individual): bool {
208            return $individual instanceof Individual && $individual->canShow();
209        });
210
211        Auth::checkComponentAccess($this, ModuleChartInterface::class, $tree, $user);
212
213        if ($ajax === '1') {
214            $this->layout = 'layouts/ajax';
215
216            return $this->chart($tree, $xrefs, $scale);
217        }
218
219        $reset_url = route(static::class, [
220            'scale' => self::DEFAULT_SCALE,
221            'tree'  => $tree->name(),
222        ]);
223
224        $zoom_in_url = route(static::class, [
225            'scale' => min(self::MAXIMUM_SCALE, $scale + (int) ($scale * 0.2 + 1)),
226            'tree'  => $tree->name(),
227            'xrefs' => $xrefs,
228        ]);
229
230        $zoom_out_url = route(static::class, [
231            'scale' => max(self::MINIMUM_SCALE, $scale - (int) ($scale * 0.2 + 1)),
232            'tree'  => $tree->name(),
233            'xrefs' => $xrefs,
234        ]);
235
236        $ajax_url = route(static::class, [
237            'ajax'  => true,
238            'scale' => $scale,
239            'tree'  => $tree->name(),
240            'xrefs' => $xrefs,
241        ]);
242
243        return $this->viewResponse('modules/timeline-chart/page', [
244            'ajax_url'     => $ajax_url,
245            'individuals'  => $individuals,
246            'module'       => $this->name(),
247            'remove_urls'  => $remove_urls,
248            'reset_url'    => $reset_url,
249            'scale'        => $scale,
250            'title'        => $this->title(),
251            'tree'         => $tree,
252            'zoom_in_url'  => $zoom_in_url,
253            'zoom_out_url' => $zoom_out_url,
254        ]);
255    }
256
257    /**
258     * @param Tree  $tree
259     * @param array $xrefs
260     * @param int   $scale
261     *
262     * @return ResponseInterface
263     */
264    protected function chart(Tree $tree, array $xrefs, int $scale): ResponseInterface
265    {
266        /** @var Individual[] $individuals */
267        $individuals = array_map(static function (string $xref) use ($tree): ?Individual {
268            return Registry::individualFactory()->make($xref, $tree);
269        }, $xrefs);
270
271        $individuals = array_filter($individuals, static function (?Individual $individual): bool {
272            return $individual instanceof Individual && $individual->canShow();
273        });
274
275        $baseyear    = (int) date('Y');
276        $topyear     = 0;
277        $indifacts   = new Collection();
278        $birthyears  = [];
279        $birthmonths = [];
280        $birthdays   = [];
281
282        foreach ($individuals as $individual) {
283            $bdate = $individual->getBirthDate();
284            if ($bdate->isOK()) {
285                $date = new GregorianDate($bdate->minimumJulianDay());
286
287                $birthyears [$individual->xref()] = $date->year;
288                $birthmonths[$individual->xref()] = max(1, $date->month);
289                $birthdays  [$individual->xref()] = max(1, $date->day);
290            }
291            // find all the fact information
292            $facts = $individual->facts();
293            foreach ($individual->spouseFamilies() as $family) {
294                foreach ($family->facts() as $fact) {
295                    $facts->push($fact);
296                }
297            }
298
299            foreach ($facts as $event) {
300                if (!in_array($event->tag(), self::NON_FACTS, true)) {
301                    // check for a date
302                    $date = $event->date();
303                    if ($date->isOK()) {
304                        $date     = new GregorianDate($date->minimumJulianDay());
305                        $baseyear = min($baseyear, $date->year);
306                        $topyear  = max($topyear, $date->year);
307
308                        if (!$individual->isDead()) {
309                            $topyear = max($topyear, (int) date('Y'));
310                        }
311
312                        $indifacts->push($event);
313                    }
314                }
315            }
316        }
317
318        // do not add the same fact twice (prevents marriages from being added multiple times)
319        $indifacts = $indifacts->uniqueStrict(static function (Fact $fact): string {
320            return $fact->id();
321        });
322
323        if ($scale === 0) {
324            $scale = (int) (($topyear - $baseyear) / 20 * $indifacts->count() / 4);
325            if ($scale < 6) {
326                $scale = 6;
327            }
328        }
329        if ($scale < 2) {
330            $scale = 2;
331        }
332        $baseyear -= 5;
333        $topyear  += 5;
334
335        $indifacts = Fact::sortFacts($indifacts);
336
337        $html = view('modules/timeline-chart/chart', [
338            'baseyear'    => $baseyear,
339            'bheight'     => self::BHEIGHT,
340            'birthdays'   => $birthdays,
341            'birthmonths' => $birthmonths,
342            'birthyears'  => $birthyears,
343            'indifacts'   => $indifacts,
344            'individuals' => $individuals,
345            'placements'  => [],
346            'scale'       => $scale,
347            'topyear'     => $topyear,
348        ]);
349
350        return response($html);
351    }
352}
353