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