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