xref: /webtrees/app/Module/TimelineChartModule.php (revision cacefda1879a630cb123d4cd92f434ddbcc1f10e)
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, self::class)
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            ] + $parameters + self::DEFAULT_PARAMETERS);
134    }
135
136    /**
137     * @param ServerRequestInterface $request
138     *
139     * @return ResponseInterface
140     */
141    public function handle(ServerRequestInterface $request): ResponseInterface
142    {
143        $tree  = $request->getAttribute('tree');
144        $user  = $request->getAttribute('user');
145        $scale = (int) $request->getAttribute('scale');
146        $xrefs = $request->getQueryParams()['xrefs'] ?? [];
147        $add   = $request->getParsedBody()['add'] ?? '';
148        $ajax  = $request->getQueryParams()['ajax'] ?? '';
149
150        Auth::checkComponentAccess($this, 'chart', $tree, $user);
151
152        $scale = min($scale, self::MAXIMUM_SCALE);
153        $scale = max($scale, self::MINIMUM_SCALE);
154
155        $xrefs[] = $add;
156        $xrefs = array_filter(array_unique($xrefs));
157
158        // Convert POST requests into GET requests for pretty URLs.
159        if ($request->getMethod() === RequestMethodInterface::METHOD_POST) {
160            return redirect(route(self::ROUTE_NAME, [
161                'scale' => $scale,
162                'tree'  => $tree->name(),
163                'xrefs' => $xrefs,
164            ]));
165        }
166
167        // Find the requested individuals.
168        $individuals = (new Collection($xrefs))
169            ->unique()
170            ->map(static function (string $xref) use ($tree): ?Individual {
171                return Individual::getInstance($xref, $tree);
172            })
173            ->filter()
174            ->filter(GedcomRecord::accessFilter());
175
176        // Generate URLs omitting each xref.
177        $remove_urls = [];
178
179        foreach ($individuals as $exclude) {
180            $xrefs_1 = $individuals
181                ->filter(static function (Individual $individual) use ($exclude): bool {
182                    return $individual->xref() !== $exclude->xref();
183                })
184                ->map(static function (Individual $individual): string {
185                    return $individual->xref();
186                });
187
188            $remove_urls[$exclude->xref()] = route(self::ROUTE_NAME, [
189                'tree'  => $tree->name(),
190                'scale' => $scale,
191                'xrefs' => $xrefs_1->all(),
192            ]);
193        }
194
195        $individuals = array_map(static function (string $xref) use ($tree): ?Individual {
196            return Individual::getInstance($xref, $tree);
197        }, $xrefs);
198
199        $individuals = array_filter($individuals, static function (?Individual $individual): bool {
200            return $individual instanceof Individual && $individual->canShow();
201        });
202
203        Auth::checkComponentAccess($this, 'chart', $tree, $user);
204
205        if ($ajax === '1') {
206            $this->layout = 'layouts/ajax';
207
208            return $this->chart($tree, $xrefs, $scale);
209        }
210
211        $reset_url = route(self::ROUTE_NAME, [
212            'scale' => self::DEFAULT_SCALE,
213            'tree'  => $tree->name(),
214        ]);
215
216        $zoom_in_url = route(self::ROUTE_NAME, [
217            'scale' => min(self::MAXIMUM_SCALE, $scale + (int) ($scale * 0.2 + 1)),
218            'tree'  => $tree->name(),
219            'xrefs' => $xrefs,
220        ]);
221
222        $zoom_out_url = route(self::ROUTE_NAME, [
223            'scale' => max(self::MINIMUM_SCALE, $scale - (int) ($scale * 0.2 + 1)),
224            'tree'  => $tree->name(),
225            'xrefs' => $xrefs,
226        ]);
227
228        $ajax_url = route(self::ROUTE_NAME, [
229            'ajax'  => true,
230            'scale' => $scale,
231            'tree'  => $tree->name(),
232            'xrefs' => $xrefs,
233        ]);
234
235        return $this->viewResponse('modules/timeline-chart/page', [
236            'ajax_url'     => $ajax_url,
237            'individuals'  => $individuals,
238            'module'       => $this->name(),
239            'remove_urls'  => $remove_urls,
240            'reset_url'    => $reset_url,
241            'scale'        => $scale,
242            'title'        => $this->title(),
243            'zoom_in_url'  => $zoom_in_url,
244            'zoom_out_url' => $zoom_out_url,
245        ]);
246    }
247
248    /**
249     * @param Tree  $tree
250     * @param array $xrefs
251     * @param int   $scale
252     *
253     * @return ResponseInterface
254     */
255    protected function chart(Tree $tree, array $xrefs, int $scale): ResponseInterface
256    {
257        /** @var Individual[] $individuals */
258        $individuals = array_map(static function (string $xref) use ($tree): ?Individual {
259            return Individual::getInstance($xref, $tree);
260        }, $xrefs);
261
262        $individuals = array_filter($individuals, static function (?Individual $individual): bool {
263            return $individual instanceof Individual && $individual->canShow();
264        });
265
266        $baseyear    = (int) date('Y');
267        $topyear     = 0;
268        $indifacts   = new Collection();
269        $birthyears  = [];
270        $birthmonths = [];
271        $birthdays   = [];
272
273        foreach ($individuals as $individual) {
274            $bdate = $individual->getBirthDate();
275            if ($bdate->isOK()) {
276                $date = new GregorianDate($bdate->minimumJulianDay());
277
278                $birthyears [$individual->xref()] = $date->year;
279                $birthmonths[$individual->xref()] = max(1, $date->month);
280                $birthdays  [$individual->xref()] = max(1, $date->day);
281            }
282            // find all the fact information
283            $facts = $individual->facts();
284            foreach ($individual->spouseFamilies() as $family) {
285                foreach ($family->facts() as $fact) {
286                    $facts->push($fact);
287                }
288            }
289            foreach ($facts as $event) {
290                // get the fact type
291                $fact = $event->getTag();
292                if (!in_array($fact, self::NON_FACTS, true)) {
293                    // check for a date
294                    $date = $event->date();
295                    if ($date->isOK()) {
296                        $date     = new GregorianDate($date->minimumJulianDay());
297                        $baseyear = min($baseyear, $date->year);
298                        $topyear  = max($topyear, $date->year);
299
300                        if (!$individual->isDead()) {
301                            $topyear = max($topyear, (int) date('Y'));
302                        }
303
304                        $indifacts->push($event);
305                    }
306                }
307            }
308        }
309
310        // do not add the same fact twice (prevents marriages from being added multiple times)
311        $indifacts = $indifacts->unique();
312
313        if ($scale === 0) {
314            $scale = (int) (($topyear - $baseyear) / 20 * $indifacts->count() / 4);
315            if ($scale < 6) {
316                $scale = 6;
317            }
318        }
319        if ($scale < 2) {
320            $scale = 2;
321        }
322        $baseyear -= 5;
323        $topyear  += 5;
324
325        $indifacts = Fact::sortFacts($indifacts);
326
327        $html = view('modules/timeline-chart/chart', [
328            'baseyear'    => $baseyear,
329            'bheight'     => self::BHEIGHT,
330            'birthdays'   => $birthdays,
331            'birthmonths' => $birthmonths,
332            'birthyears'  => $birthyears,
333            'indifacts'   => $indifacts,
334            'individuals' => $individuals,
335            'placements'  => [],
336            'scale'       => $scale,
337            'topyear'     => $topyear,
338        ]);
339
340        return response($html);
341    }
342}
343