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