xref: /webtrees/app/Module/TimelineChartModule.php (revision b0fcccb03b84c12d54b4ae85014c3af52863d08c)
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\Webtrees\Auth;
25use Fisharebest\Webtrees\Date\GregorianDate;
26use Fisharebest\Webtrees\Fact;
27use Fisharebest\Webtrees\GedcomRecord;
28use Fisharebest\Webtrees\I18N;
29use Fisharebest\Webtrees\Individual;
30use Fisharebest\Webtrees\Tree;
31use Illuminate\Support\Collection;
32use Psr\Http\Message\ResponseInterface;
33use Psr\Http\Message\ServerRequestInterface;
34use Psr\Http\Server\RequestHandlerInterface;
35
36use function app;
37use function assert;
38use function redirect;
39use function route;
40
41/**
42 * Class TimelineChartModule
43 */
44class TimelineChartModule extends AbstractModule implements ModuleChartInterface, RequestHandlerInterface
45{
46    use ModuleChartTrait;
47
48    private const ROUTE_NAME = 'timeline-chart';
49    private const ROUTE_URL  = '/tree/{tree}/timeline-{scale}';
50
51    // Defaults
52    protected const DEFAULT_SCALE      = 10;
53    protected const DEFAULT_PARAMETERS = [
54        'scale' => self::DEFAULT_SCALE,
55    ];
56
57    // Limits
58    protected const MINIMUM_SCALE = 1;
59    protected const MAXIMUM_SCALE = 200;
60
61    // GEDCOM events that may have DATE data, but should not be displayed
62    protected const NON_FACTS = [
63        'BAPL',
64        'ENDL',
65        'SLGC',
66        'SLGS',
67        '_TODO',
68        'CHAN',
69    ];
70    protected const BHEIGHT   = 30;
71
72    // Box height
73
74    /**
75     * Initialization.
76     *
77     * @return void
78     */
79    public function boot(): void
80    {
81        $router_container = app(RouterContainer::class);
82        assert($router_container instanceof RouterContainer);
83
84        $router_container->getMap()
85            ->get(self::ROUTE_NAME, self::ROUTE_URL, $this)
86            ->allows(RequestMethodInterface::METHOD_POST);
87    }
88
89    /**
90     * How should this module be identified in the control panel, etc.?
91     *
92     * @return string
93     */
94    public function title(): string
95    {
96        /* I18N: Name of a module/chart */
97        return I18N::translate('Timeline');
98    }
99
100    /**
101     * A sentence describing what this module does.
102     *
103     * @return string
104     */
105    public function description(): string
106    {
107        /* I18N: Description of the “TimelineChart” module */
108        return I18N::translate('A timeline displaying individual events.');
109    }
110
111    /**
112     * CSS class for the URL.
113     *
114     * @return string
115     */
116    public function chartMenuClass(): string
117    {
118        return 'menu-chart-timeline';
119    }
120
121    /**
122     * The URL for this chart.
123     *
124     * @param Individual $individual
125     * @param mixed[]    $parameters
126     *
127     * @return string
128     */
129    public function chartUrl(Individual $individual, array $parameters = []): string
130    {
131        return route(self::ROUTE_NAME, [
132                'tree'  => $individual->tree()->name(),
133                'xrefs' => [$individual->xref()],
134            ] + $parameters + self::DEFAULT_PARAMETERS);
135    }
136
137    /**
138     * @param ServerRequestInterface $request
139     *
140     * @return ResponseInterface
141     */
142    public function handle(ServerRequestInterface $request): ResponseInterface
143    {
144        $tree = $request->getAttribute('tree');
145        assert($tree instanceof Tree);
146
147        $user  = $request->getAttribute('user');
148        $scale = (int) $request->getAttribute('scale');
149        $xrefs = $request->getQueryParams()['xrefs'] ?? [];
150        $add   = $request->getParsedBody()['add'] ?? '';
151        $ajax  = $request->getQueryParams()['ajax'] ?? '';
152
153        Auth::checkComponentAccess($this, 'chart', $tree, $user);
154
155        $scale = min($scale, self::MAXIMUM_SCALE);
156        $scale = max($scale, self::MINIMUM_SCALE);
157
158        $xrefs[] = $add;
159        $xrefs = array_filter(array_unique($xrefs));
160
161        // Convert POST requests into GET requests for pretty URLs.
162        if ($request->getMethod() === RequestMethodInterface::METHOD_POST) {
163            return redirect(route(self::ROUTE_NAME, [
164                'scale' => $scale,
165                'tree'  => $tree->name(),
166                'xrefs' => $xrefs,
167            ]));
168        }
169
170        // Find the requested individuals.
171        $individuals = (new Collection($xrefs))
172            ->unique()
173            ->map(static function (string $xref) use ($tree): ?Individual {
174                return Individual::getInstance($xref, $tree);
175            })
176            ->filter()
177            ->filter(GedcomRecord::accessFilter());
178
179        // Generate URLs omitting each xref.
180        $remove_urls = [];
181
182        foreach ($individuals as $exclude) {
183            $xrefs_1 = $individuals
184                ->filter(static function (Individual $individual) use ($exclude): bool {
185                    return $individual->xref() !== $exclude->xref();
186                })
187                ->map(static function (Individual $individual): string {
188                    return $individual->xref();
189                });
190
191            $remove_urls[$exclude->xref()] = route(self::ROUTE_NAME, [
192                'tree'  => $tree->name(),
193                'scale' => $scale,
194                'xrefs' => $xrefs_1->all(),
195            ]);
196        }
197
198        $individuals = array_map(static function (string $xref) use ($tree): ?Individual {
199            return Individual::getInstance($xref, $tree);
200        }, $xrefs);
201
202        $individuals = array_filter($individuals, static function (?Individual $individual): bool {
203            return $individual instanceof Individual && $individual->canShow();
204        });
205
206        Auth::checkComponentAccess($this, 'chart', $tree, $user);
207
208        if ($ajax === '1') {
209            $this->layout = 'layouts/ajax';
210
211            return $this->chart($tree, $xrefs, $scale);
212        }
213
214        $reset_url = route(self::ROUTE_NAME, [
215            'scale' => self::DEFAULT_SCALE,
216            'tree'  => $tree->name(),
217        ]);
218
219        $zoom_in_url = route(self::ROUTE_NAME, [
220            'scale' => min(self::MAXIMUM_SCALE, $scale + (int) ($scale * 0.2 + 1)),
221            'tree'  => $tree->name(),
222            'xrefs' => $xrefs,
223        ]);
224
225        $zoom_out_url = route(self::ROUTE_NAME, [
226            'scale' => max(self::MINIMUM_SCALE, $scale - (int) ($scale * 0.2 + 1)),
227            'tree'  => $tree->name(),
228            'xrefs' => $xrefs,
229        ]);
230
231        $ajax_url = route(self::ROUTE_NAME, [
232            'ajax'  => true,
233            'scale' => $scale,
234            'tree'  => $tree->name(),
235            'xrefs' => $xrefs,
236        ]);
237
238        return $this->viewResponse('modules/timeline-chart/page', [
239            'ajax_url'     => $ajax_url,
240            'individuals'  => $individuals,
241            'module'       => $this->name(),
242            'remove_urls'  => $remove_urls,
243            'reset_url'    => $reset_url,
244            'scale'        => $scale,
245            'title'        => $this->title(),
246            'tree'         => $tree,
247            'zoom_in_url'  => $zoom_in_url,
248            'zoom_out_url' => $zoom_out_url,
249        ]);
250    }
251
252    /**
253     * @param Tree  $tree
254     * @param array $xrefs
255     * @param int   $scale
256     *
257     * @return ResponseInterface
258     */
259    protected function chart(Tree $tree, array $xrefs, int $scale): ResponseInterface
260    {
261        /** @var Individual[] $individuals */
262        $individuals = array_map(static function (string $xref) use ($tree): ?Individual {
263            return Individual::getInstance($xref, $tree);
264        }, $xrefs);
265
266        $individuals = array_filter($individuals, static function (?Individual $individual): bool {
267            return $individual instanceof Individual && $individual->canShow();
268        });
269
270        $baseyear    = (int) date('Y');
271        $topyear     = 0;
272        $indifacts   = new Collection();
273        $birthyears  = [];
274        $birthmonths = [];
275        $birthdays   = [];
276
277        foreach ($individuals as $individual) {
278            $bdate = $individual->getBirthDate();
279            if ($bdate->isOK()) {
280                $date = new GregorianDate($bdate->minimumJulianDay());
281
282                $birthyears [$individual->xref()] = $date->year;
283                $birthmonths[$individual->xref()] = max(1, $date->month);
284                $birthdays  [$individual->xref()] = max(1, $date->day);
285            }
286            // find all the fact information
287            $facts = $individual->facts();
288            foreach ($individual->spouseFamilies() as $family) {
289                foreach ($family->facts() as $fact) {
290                    $facts->push($fact);
291                }
292            }
293            foreach ($facts as $event) {
294                // get the fact type
295                $fact = $event->getTag();
296                if (!in_array($fact, self::NON_FACTS, true)) {
297                    // check for a date
298                    $date = $event->date();
299                    if ($date->isOK()) {
300                        $date     = new GregorianDate($date->minimumJulianDay());
301                        $baseyear = min($baseyear, $date->year);
302                        $topyear  = max($topyear, $date->year);
303
304                        if (!$individual->isDead()) {
305                            $topyear = max($topyear, (int) date('Y'));
306                        }
307
308                        $indifacts->push($event);
309                    }
310                }
311            }
312        }
313
314        // do not add the same fact twice (prevents marriages from being added multiple times)
315        $indifacts = $indifacts->unique();
316
317        if ($scale === 0) {
318            $scale = (int) (($topyear - $baseyear) / 20 * $indifacts->count() / 4);
319            if ($scale < 6) {
320                $scale = 6;
321            }
322        }
323        if ($scale < 2) {
324            $scale = 2;
325        }
326        $baseyear -= 5;
327        $topyear  += 5;
328
329        $indifacts = Fact::sortFacts($indifacts);
330
331        $html = view('modules/timeline-chart/chart', [
332            'baseyear'    => $baseyear,
333            'bheight'     => self::BHEIGHT,
334            'birthdays'   => $birthdays,
335            'birthmonths' => $birthmonths,
336            'birthyears'  => $birthyears,
337            'indifacts'   => $indifacts,
338            'individuals' => $individuals,
339            'placements'  => [],
340            'scale'       => $scale,
341            'topyear'     => $topyear,
342        ]);
343
344        return response($html);
345    }
346}
347