xref: /webtrees/app/Module/LifespansChartModule.php (revision b55cbc6b43247e8b2ad14af6f6d24dc6747195ff)
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\ExtCalendar\GregorianCalendar;
25use Fisharebest\Webtrees\Auth;
26use Fisharebest\Webtrees\ColorGenerator;
27use Fisharebest\Webtrees\Date;
28use Fisharebest\Webtrees\I18N;
29use Fisharebest\Webtrees\Individual;
30use Fisharebest\Webtrees\Place;
31use Fisharebest\Webtrees\Registry;
32use Fisharebest\Webtrees\Tree;
33use Fisharebest\Webtrees\Validator;
34use Illuminate\Database\Capsule\Manager as DB;
35use Illuminate\Database\Query\JoinClause;
36use Psr\Http\Message\ResponseInterface;
37use Psr\Http\Message\ServerRequestInterface;
38use Psr\Http\Server\RequestHandlerInterface;
39
40use function app;
41use function array_filter;
42use function array_intersect;
43use function array_map;
44use function array_merge;
45use function array_reduce;
46use function array_unique;
47use function assert;
48use function count;
49use function date;
50use function explode;
51use function implode;
52use function intdiv;
53use function is_array;
54use function max;
55use function md5;
56use function min;
57use function redirect;
58use function response;
59use function route;
60use function usort;
61use function view;
62
63use const PHP_INT_MAX;
64
65/**
66 * Class LifespansChartModule
67 */
68class LifespansChartModule extends AbstractModule implements ModuleChartInterface, RequestHandlerInterface
69{
70    use ModuleChartTrait;
71
72    protected const ROUTE_URL = '/tree/{tree}/lifespans';
73
74    // In theory, only "@" is a safe separator, but it gives longer and uglier URLs.
75    // Unless some other application generates XREFs with a ".", we are safe.
76    protected const SEPARATOR = '.';
77
78    // Defaults
79    protected const DEFAULT_PARAMETERS = [];
80
81    // Parameters for generating colors
82    protected const RANGE      = 120; // degrees
83    protected const SATURATION = 100; // percent
84    protected const LIGHTNESS  = 30; // percent
85    protected const ALPHA      = 0.25;
86
87    /**
88     * Initialization.
89     *
90     * @return void
91     */
92    public function boot(): void
93    {
94        $router_container = app(RouterContainer::class);
95        assert($router_container instanceof RouterContainer);
96
97        $router_container->getMap()
98            ->get(static::class, static::ROUTE_URL, $this)
99            ->allows(RequestMethodInterface::METHOD_POST);
100    }
101
102    /**
103     * How should this module be identified in the control panel, etc.?
104     *
105     * @return string
106     */
107    public function title(): string
108    {
109        /* I18N: Name of a module/chart */
110        return I18N::translate('Lifespans');
111    }
112
113    /**
114     * A sentence describing what this module does.
115     *
116     * @return string
117     */
118    public function description(): string
119    {
120        /* I18N: Description of the “LifespansChart” module */
121        return I18N::translate('A chart of individuals’ lifespans.');
122    }
123
124    /**
125     * CSS class for the URL.
126     *
127     * @return string
128     */
129    public function chartMenuClass(): string
130    {
131        return 'menu-chart-lifespan';
132    }
133
134    /**
135     * The URL for this chart.
136     *
137     * @param Individual                                $individual
138     * @param array<bool|int|string|array<string>|null> $parameters
139     *
140     * @return string
141     */
142    public function chartUrl(Individual $individual, array $parameters = []): string
143    {
144        return route(static::class, [
145                'tree'  => $individual->tree()->name(),
146                'xrefs' => $individual->xref(),
147            ] + $parameters + self::DEFAULT_PARAMETERS);
148    }
149
150    /**
151     * @param ServerRequestInterface $request
152     *
153     * @return ResponseInterface
154     */
155    public function handle(ServerRequestInterface $request): ResponseInterface
156    {
157        $tree  = Validator::attributes($request)->tree();
158        $user  = Validator::attributes($request)->user();
159        $xrefs = Validator::queryParams($request)->array('xrefs');
160        $ajax  = Validator::queryParams($request)->boolean('ajax', false);
161
162        $params = (array) $request->getParsedBody();
163
164        $addxref   = $params['addxref'] ?? '';
165        $addfam    = (bool) ($params['addfam'] ?? false);
166        $place_id  = (int) ($params['place_id'] ?? 0);
167        $start     = $params['start'] ?? '';
168        $end       = $params['end'] ?? '';
169
170        $place      = Place::find($place_id, $tree);
171        $start_date = new Date($start);
172        $end_date   = new Date($end);
173
174        $xrefs = array_unique($xrefs);
175
176        // Add an individual, and family members
177        $individual = Registry::individualFactory()->make($addxref, $tree);
178        if ($individual !== null) {
179            $xrefs[] = $addxref;
180            if ($addfam) {
181                $xrefs = array_merge($xrefs, $this->closeFamily($individual));
182            }
183        }
184
185        // Select by date and/or place.
186        if ($place_id !== 0 && $start_date->isOK() && $end_date->isOK()) {
187            $date_xrefs  = $this->findIndividualsByDate($start_date, $end_date, $tree);
188            $place_xrefs = $this->findIndividualsByPlace($place, $tree);
189            $xrefs       = array_intersect($date_xrefs, $place_xrefs);
190        } elseif ($start_date->isOK() && $end_date->isOK()) {
191            $xrefs = $this->findIndividualsByDate($start_date, $end_date, $tree);
192        } elseif ($place_id !== 0) {
193            $xrefs = $this->findIndividualsByPlace($place, $tree);
194        }
195
196        // Filter duplicates and private individuals.
197        $xrefs = array_unique($xrefs);
198        $xrefs = array_filter($xrefs, static function (string $xref) use ($tree): bool {
199            $individual = Registry::individualFactory()->make($xref, $tree);
200
201            return $individual !== null && $individual->canShow();
202        });
203
204        // Convert POST requests into GET requests for pretty URLs.
205        if ($request->getMethod() === RequestMethodInterface::METHOD_POST) {
206            return redirect(route(static::class, [
207                'tree'  => $tree->name(),
208                'xrefs' => implode(self::SEPARATOR, $xrefs),
209            ]));
210        }
211
212        Auth::checkComponentAccess($this, ModuleChartInterface::class, $tree, $user);
213
214        if ($ajax) {
215            $this->layout = 'layouts/ajax';
216
217            return $this->chart($tree, $xrefs);
218        }
219
220        $reset_url = route(static::class, ['tree' => $tree->name()]);
221
222        $ajax_url = route(static::class, [
223            'ajax'  => true,
224            'tree'  => $tree->name(),
225            'xrefs' => implode(self::SEPARATOR, $xrefs),
226        ]);
227
228        return $this->viewResponse('modules/lifespans-chart/page', [
229            'ajax_url'  => $ajax_url,
230            'module'    => $this->name(),
231            'reset_url' => $reset_url,
232            'title'     => $this->title(),
233            'tree'      => $tree,
234            'xrefs'     => $xrefs,
235        ]);
236    }
237
238    /**
239     * @param Tree          $tree
240     * @param array<string> $xrefs
241     *
242     * @return ResponseInterface
243     */
244    protected function chart(Tree $tree, array $xrefs): ResponseInterface
245    {
246        /** @var Individual[] $individuals */
247        $individuals = array_map(static function (string $xref) use ($tree): ?Individual {
248            return Registry::individualFactory()->make($xref, $tree);
249        }, $xrefs);
250
251        $individuals = array_filter($individuals, static function (?Individual $individual): bool {
252            return $individual instanceof Individual && $individual->canShow();
253        });
254
255        // Sort the array in order of birth year
256        usort($individuals, Individual::birthDateComparator());
257
258        // Round to whole decades
259        $start_year = intdiv($this->minYear($individuals), 10) * 10;
260        $end_year   = intdiv($this->maxYear($individuals) + 9, 10) * 10;
261
262        $lifespans = $this->layoutIndividuals($individuals);
263
264        $callback = static fn (int $carry, object $item): int => max($carry, $item->row);
265        $max_rows = array_reduce($lifespans, $callback, 0);
266
267        $count    = count($xrefs);
268        $subtitle = I18N::plural('%s individual', '%s individuals', $count, I18N::number($count));
269
270        $html = view('modules/lifespans-chart/chart', [
271            'dir'        => I18N::direction(),
272            'end_year'   => $end_year,
273            'lifespans'  => $lifespans,
274            'max_rows'   => $max_rows,
275            'start_year' => $start_year,
276            'subtitle'   => $subtitle,
277        ]);
278
279        return response($html);
280    }
281
282    /**
283     * Find the latest event year for individuals
284     *
285     * @param array<Individual> $individuals
286     *
287     * @return int
288     */
289    protected function maxYear(array $individuals): int
290    {
291        $jd = array_reduce($individuals, static function (int $carry, Individual $item): int {
292            if ($item->getEstimatedDeathDate()->isOK()) {
293                return max($carry, $item->getEstimatedDeathDate()->maximumJulianDay());
294            }
295
296            return $carry;
297        }, 0);
298
299        $year = $this->jdToYear($jd);
300
301        // Don't show future dates
302        return min($year, (int) date('Y'));
303    }
304
305    /**
306     * Find the earliest event year for individuals
307     *
308     * @param array<Individual> $individuals
309     *
310     * @return int
311     */
312    protected function minYear(array $individuals): int
313    {
314        $jd = array_reduce($individuals, static function (int $carry, Individual $item): int {
315            if ($item->getEstimatedBirthDate()->isOK()) {
316                return min($carry, $item->getEstimatedBirthDate()->minimumJulianDay());
317            }
318
319            return $carry;
320        }, PHP_INT_MAX);
321
322        return $this->jdToYear($jd);
323    }
324
325    /**
326     * Convert a julian day to a gregorian year
327     *
328     * @param int $jd
329     *
330     * @return int
331     */
332    protected function jdToYear(int $jd): int
333    {
334        if ($jd === 0) {
335            return 0;
336        }
337
338        $gregorian = new GregorianCalendar();
339        [$y] = $gregorian->jdToYmd($jd);
340
341        return $y;
342    }
343
344    /**
345     * @param Date $start
346     * @param Date $end
347     * @param Tree $tree
348     *
349     * @return array<string>
350     */
351    protected function findIndividualsByDate(Date $start, Date $end, Tree $tree): array
352    {
353        return DB::table('individuals')
354            ->join('dates', static function (JoinClause $join): void {
355                $join
356                    ->on('d_file', '=', 'i_file')
357                    ->on('d_gid', '=', 'i_id');
358            })
359            ->where('i_file', '=', $tree->id())
360            ->where('d_julianday1', '<=', $end->maximumJulianDay())
361            ->where('d_julianday2', '>=', $start->minimumJulianDay())
362            ->whereNotIn('d_fact', ['BAPL', 'ENDL', 'SLGC', 'SLGS', '_TODO', 'CHAN'])
363            ->pluck('i_id')
364            ->all();
365    }
366
367    /**
368     * @param Place $place
369     * @param Tree  $tree
370     *
371     * @return array<string>
372     */
373    protected function findIndividualsByPlace(Place $place, Tree $tree): array
374    {
375        return DB::table('individuals')
376            ->join('placelinks', static function (JoinClause $join): void {
377                $join
378                    ->on('pl_file', '=', 'i_file')
379                    ->on('pl_gid', '=', 'i_id');
380            })
381            ->where('i_file', '=', $tree->id())
382            ->where('pl_p_id', '=', $place->id())
383            ->pluck('i_id')
384            ->all();
385    }
386
387    /**
388     * Find the close family members of an individual.
389     *
390     * @param Individual $individual
391     *
392     * @return array<string>
393     */
394    protected function closeFamily(Individual $individual): array
395    {
396        $xrefs = [];
397
398        foreach ($individual->spouseFamilies() as $family) {
399            foreach ($family->children() as $child) {
400                $xrefs[] = $child->xref();
401            }
402
403            foreach ($family->spouses() as $spouse) {
404                $xrefs[] = $spouse->xref();
405            }
406        }
407
408        foreach ($individual->childFamilies() as $family) {
409            foreach ($family->children() as $child) {
410                $xrefs[] = $child->xref();
411            }
412
413            foreach ($family->spouses() as $spouse) {
414                $xrefs[] = $spouse->xref();
415            }
416        }
417
418        return $xrefs;
419    }
420
421    /**
422     * @param array<Individual> $individuals
423     *
424     * @return array<object>
425     */
426    private function layoutIndividuals(array $individuals): array
427    {
428        $colors = [
429            'M' => new ColorGenerator(240, self::SATURATION, self::LIGHTNESS, self::ALPHA, self::RANGE * -1),
430            'F' => new ColorGenerator(000, self::SATURATION, self::LIGHTNESS, self::ALPHA, self::RANGE),
431            'U' => new ColorGenerator(120, self::SATURATION, self::LIGHTNESS, self::ALPHA, self::RANGE),
432        ];
433
434        $current_year = (int) date('Y');
435
436        // Latest year used in each row
437        $rows = [];
438
439        $lifespans = [];
440
441        foreach ($individuals as $individual) {
442            $birth_jd   = $individual->getEstimatedBirthDate()->minimumJulianDay();
443            $birth_year = $this->jdToYear($birth_jd);
444            $death_jd   = $individual->getEstimatedDeathDate()->maximumJulianDay();
445            $death_year = $this->jdToYear($death_jd);
446
447            // Died before they were born?  Swapping the dates allows them to be shown.
448            if ($death_year < $birth_year) {
449                $death_year = $birth_year;
450            }
451
452            // Don't show death dates in the future.
453            $death_year = min($death_year, $current_year);
454
455            // Add this individual to the next row in the chart...
456            $next_row = count($rows);
457            // ...unless we can find an existing row where it fits.
458            foreach ($rows as $row => $year) {
459                if ($year < $birth_year) {
460                    $next_row = $row;
461                    break;
462                }
463            }
464
465            // Fill the row up to the year (leaving a small gap)
466            $rows[$next_row] = $death_year;
467
468            $lifespans[] = (object) [
469                'background' => $colors[$individual->sex()]->getNextColor(),
470                'birth_year' => $birth_year,
471                'death_year' => $death_year,
472                'id'         => 'individual-' . md5($individual->xref()),
473                'individual' => $individual,
474                'row'        => $next_row,
475            ];
476        }
477
478        return $lifespans;
479    }
480}
481