xref: /webtrees/app/Module/TimelineChartModule.php (revision 6de87b62c2f9ee5ee446e7c23a7efdb096c917fc)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2022 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        Registry::routeFactory()->routeMap()
83            ->get(static::class, static::ROUTE_URL, $this)
84            ->allows(RequestMethodInterface::METHOD_POST);
85    }
86
87    /**
88     * How should this module be identified in the control panel, etc.?
89     *
90     * @return string
91     */
92    public function title(): string
93    {
94        /* I18N: Name of a module/chart */
95        return I18N::translate('Timeline');
96    }
97
98    /**
99     * A sentence describing what this module does.
100     *
101     * @return string
102     */
103    public function description(): string
104    {
105        /* I18N: Description of the “TimelineChart” module */
106        return I18N::translate('A timeline displaying individual events.');
107    }
108
109    /**
110     * CSS class for the URL.
111     *
112     * @return string
113     */
114    public function chartMenuClass(): string
115    {
116        return 'menu-chart-timeline';
117    }
118
119    /**
120     * The URL for this chart.
121     *
122     * @param Individual                                $individual
123     * @param array<bool|int|string|array<string>|null> $parameters
124     *
125     * @return string
126     */
127    public function chartUrl(Individual $individual, array $parameters = []): string
128    {
129        return route(static::class, [
130                'tree'  => $individual->tree()->name(),
131                'xrefs' => [$individual->xref()],
132            ] + $parameters + self::DEFAULT_PARAMETERS);
133    }
134
135    /**
136     * @param ServerRequestInterface $request
137     *
138     * @return ResponseInterface
139     */
140    public function handle(ServerRequestInterface $request): ResponseInterface
141    {
142        $tree  = Validator::attributes($request)->tree();
143        $user  = Validator::attributes($request)->user();
144        $scale = Validator::attributes($request)->isBetween(self::MINIMUM_SCALE, self::MAXIMUM_SCALE)->integer('scale');
145        $xrefs = Validator::queryParams($request)->array('xrefs');
146        $ajax  = Validator::queryParams($request)->boolean('ajax', false);
147        $xrefs = array_filter(array_unique($xrefs));
148
149        // Convert POST requests into GET requests for pretty URLs.
150        if ($request->getMethod() === RequestMethodInterface::METHOD_POST) {
151            $xrefs[] = Validator::parsedBody($request)->isXref()->string('add', '');
152
153            return redirect(route(static::class, [
154                'tree'  => $tree->name(),
155                'scale' => $scale,
156                'xrefs' => $xrefs,
157            ]));
158        }
159
160        Auth::checkComponentAccess($this, ModuleChartInterface::class, $tree, $user);
161
162        // Find the requested individuals.
163        $individuals = (new Collection($xrefs))
164            ->uniqueStrict()
165            ->map(static function (string $xref) use ($tree): ?Individual {
166                return Registry::individualFactory()->make($xref, $tree);
167            })
168            ->filter()
169            ->filter(GedcomRecord::accessFilter());
170
171        // Generate URLs omitting each xref.
172        $remove_urls = [];
173
174        foreach ($individuals as $exclude) {
175            $xrefs_1 = $individuals
176                ->filter(static function (Individual $individual) use ($exclude): bool {
177                    return $individual->xref() !== $exclude->xref();
178                })
179                ->map(static function (Individual $individual): string {
180                    return $individual->xref();
181                });
182
183            $remove_urls[$exclude->xref()] = route(static::class, [
184                'tree'  => $tree->name(),
185                'scale' => $scale,
186                'xrefs' => $xrefs_1->all(),
187            ]);
188        }
189
190        $individuals = array_map(static function (string $xref) use ($tree): ?Individual {
191            return Registry::individualFactory()->make($xref, $tree);
192        }, $xrefs);
193
194        $individuals = array_filter($individuals, static function (?Individual $individual): bool {
195            return $individual instanceof Individual && $individual->canShow();
196        });
197
198        if ($ajax) {
199            $this->layout = 'layouts/ajax';
200
201            return $this->chart($tree, $xrefs, $scale);
202        }
203
204        $reset_url = route(static::class, [
205            'scale' => self::DEFAULT_SCALE,
206            'tree'  => $tree->name(),
207        ]);
208
209        $zoom_in_url = route(static::class, [
210            'scale' => min(self::MAXIMUM_SCALE, $scale + (int) ($scale * 0.4 + 1)),
211            'tree'  => $tree->name(),
212            'xrefs' => $xrefs,
213        ]);
214
215        $zoom_out_url = route(static::class, [
216            'scale' => max(self::MINIMUM_SCALE, $scale - (int) ($scale * 0.4 + 1)),
217            'tree'  => $tree->name(),
218            'xrefs' => $xrefs,
219        ]);
220
221        $ajax_url = route(static::class, [
222            'ajax'  => true,
223            'scale' => $scale,
224            'tree'  => $tree->name(),
225            'xrefs' => $xrefs,
226        ]);
227
228        return $this->viewResponse('modules/timeline-chart/page', [
229            'ajax_url'     => $ajax_url,
230            'individuals'  => $individuals,
231            'module'       => $this->name(),
232            'remove_urls'  => $remove_urls,
233            'reset_url'    => $reset_url,
234            'scale'        => $scale,
235            'title'        => $this->title(),
236            'tree'         => $tree,
237            'zoom_in_url'  => $zoom_in_url,
238            'zoom_out_url' => $zoom_out_url,
239        ]);
240    }
241
242    /**
243     * @param Tree          $tree
244     * @param array<string> $xrefs
245     * @param int           $scale
246     *
247     * @return ResponseInterface
248     */
249    protected function chart(Tree $tree, array $xrefs, int $scale): ResponseInterface
250    {
251        /** @var Individual[] $individuals */
252        $individuals = array_map(static function (string $xref) use ($tree): ?Individual {
253            return Registry::individualFactory()->make($xref, $tree);
254        }, $xrefs);
255
256        $individuals = array_filter($individuals, static function (?Individual $individual): bool {
257            return $individual instanceof Individual && $individual->canShow();
258        });
259
260        $baseyear    = (int) date('Y');
261        $topyear     = 0;
262        $indifacts   = new Collection();
263        $birthyears  = [];
264        $birthmonths = [];
265        $birthdays   = [];
266
267        foreach ($individuals as $individual) {
268            $bdate = $individual->getBirthDate();
269            if ($bdate->isOK()) {
270                $date = new GregorianDate($bdate->minimumJulianDay());
271
272                $birthyears [$individual->xref()] = $date->year;
273                $birthmonths[$individual->xref()] = max(1, $date->month);
274                $birthdays  [$individual->xref()] = max(1, $date->day);
275            }
276            // find all the fact information
277            $facts = $individual->facts();
278            foreach ($individual->spouseFamilies() as $family) {
279                foreach ($family->facts() as $fact) {
280                    $facts->push($fact);
281                }
282            }
283
284            foreach ($facts as $event) {
285                if (!in_array($event->tag(), self::NON_FACTS, true)) {
286                    // check for a date
287                    $date = $event->date();
288                    if ($date->isOK()) {
289                        $date     = new GregorianDate($date->minimumJulianDay());
290                        $baseyear = min($baseyear, $date->year);
291                        $topyear  = max($topyear, $date->year);
292
293                        if (!$individual->isDead()) {
294                            $topyear = max($topyear, (int) date('Y'));
295                        }
296
297                        $indifacts->push($event);
298                    }
299                }
300            }
301        }
302
303        // do not add the same fact twice (prevents marriages from being added multiple times)
304        $indifacts = $indifacts->uniqueStrict(static function (Fact $fact): string {
305            return $fact->id();
306        });
307
308        if ($scale === 0) {
309            $scale = (int) (($topyear - $baseyear) / 20 * $indifacts->count() / 4);
310            if ($scale < 6) {
311                $scale = 6;
312            }
313        }
314        if ($scale < 2) {
315            $scale = 2;
316        }
317        $baseyear -= 5;
318        $topyear  += 5;
319
320        $indifacts = Fact::sortFacts($indifacts);
321
322        $html = view('modules/timeline-chart/chart', [
323            'baseyear'    => $baseyear,
324            'bheight'     => self::BOX_HEIGHT,
325            'birthdays'   => $birthdays,
326            'birthmonths' => $birthmonths,
327            'birthyears'  => $birthyears,
328            'indifacts'   => $indifacts,
329            'individuals' => $individuals,
330            'placements'  => [],
331            'scale'       => $scale,
332            'topyear'     => $topyear,
333        ]);
334
335        return response($html);
336    }
337}
338