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