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