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