xref: /webtrees/app/Module/TimelineChartModule.php (revision 57ab22314b2599feb432b1a1ed71643cfc2f0452)
1<?php
2/**
3 * webtrees: online genealogy
4 * Copyright (C) 2019 webtrees development team
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16declare(strict_types=1);
17
18namespace Fisharebest\Webtrees\Module;
19
20use Fisharebest\Webtrees\Auth;
21use Fisharebest\Webtrees\Date\GregorianDate;
22use Fisharebest\Webtrees\Fact;
23use Fisharebest\Webtrees\GedcomRecord;
24use Fisharebest\Webtrees\I18N;
25use Fisharebest\Webtrees\Individual;
26use Fisharebest\Webtrees\Tree;
27use Illuminate\Support\Collection;
28use Psr\Http\Message\ResponseInterface;
29use Psr\Http\Message\ServerRequestInterface;
30
31/**
32 * Class TimelineChartModule
33 */
34class TimelineChartModule extends AbstractModule implements ModuleChartInterface
35{
36    use ModuleChartTrait;
37
38    // The user can alter the vertical scale
39    protected const SCALE_MIN     = 1;
40    protected const SCALE_MAX     = 200;
41    protected const SCALE_DEFAULT = 10;
42
43    // GEDCOM events that may have DATE data, but should not be displayed
44    protected const NON_FACTS = [
45        'BAPL',
46        'ENDL',
47        'SLGC',
48        'SLGS',
49        '_TODO',
50        'CHAN',
51    ];
52
53    // Box height
54    protected const BHEIGHT = 30;
55
56    /**
57     * How should this module be identified in the control panel, etc.?
58     *
59     * @return string
60     */
61    public function title(): string
62    {
63        /* I18N: Name of a module/chart */
64        return I18N::translate('Timeline');
65    }
66
67    /**
68     * A sentence describing what this module does.
69     *
70     * @return string
71     */
72    public function description(): string
73    {
74        /* I18N: Description of the “TimelineChart” module */
75        return I18N::translate('A timeline displaying individual events.');
76    }
77
78    /**
79     * CSS class for the URL.
80     *
81     * @return string
82     */
83    public function chartMenuClass(): string
84    {
85        return 'menu-chart-timeline';
86    }
87
88    /**
89     * The URL for this chart.
90     *
91     * @param Individual $individual
92     * @param string[]   $parameters
93     *
94     * @return string
95     */
96    public function chartUrl(Individual $individual, array $parameters = []): string
97    {
98        return route('module', [
99                'module'  => $this->name(),
100                'action'  => 'Chart',
101                'xrefs[]' => $individual->xref(),
102                'ged'     => $individual->tree()->name(),
103            ] + $parameters);
104    }
105
106    /**
107     * A form to request the chart parameters.
108     *
109     * @param ServerRequestInterface $request
110     *
111     * @return ResponseInterface
112     */
113    public function getChartAction(ServerRequestInterface $request): ResponseInterface
114    {
115        $tree = $request->getAttribute('tree');
116        $user = $request->getAttribute('user');
117
118        Auth::checkComponentAccess($this, 'chart', $tree, $user);
119
120        $ajax  = $request->getQueryParams()['ajax'] ?? '';
121        $scale = (int) ($request->getQueryParams()['scale'] ?? self::SCALE_DEFAULT);
122        $scale = min($scale, self::SCALE_MAX);
123        $scale = max($scale, self::SCALE_MIN);
124        $xrefs = $request->getQueryParams()['xrefs'] ?? [];
125
126        // Find the requested individuals.
127        $individuals = (new Collection($xrefs))
128            ->unique()
129            ->map(static function (string $xref) use ($tree): ?Individual {
130                return Individual::getInstance($xref, $tree);
131            })
132            ->filter()
133            ->filter(GedcomRecord::accessFilter());
134
135        // Generate URLs omitting each xref.
136        $remove_urls = [];
137
138        foreach ($individuals as $exclude) {
139            $xrefs_1 = $individuals
140                ->filter(static function (Individual $individual) use ($exclude): bool {
141                    return $individual->xref() !== $exclude->xref();
142                })
143                ->map(static function (Individual $individual): string {
144                    return $individual->xref();
145                });
146
147            $remove_urls[$exclude->xref()] = route('module', [
148                'module' => $this->name(),
149                'action' => 'Chart',
150                'ged'    => $tree->name(),
151                'scale'  => $scale,
152                'xrefs'  => $xrefs_1->all(),
153            ]);
154        }
155
156        $individuals = array_map(static function (string $xref) use ($tree): ?Individual {
157            return Individual::getInstance($xref, $tree);
158        }, $xrefs);
159
160        $individuals = array_filter($individuals, static function (?Individual $individual): bool {
161            return $individual instanceof Individual && $individual->canShow();
162        });
163
164        if ($ajax === '1') {
165            return $this->chart($tree, $xrefs, $scale);
166        }
167
168        $ajax_url = route('module', [
169            'ajax'   => true,
170            'module' => $this->name(),
171            'action' => 'Chart',
172            'ged'    => $tree->name(),
173            'scale'  => $scale,
174            'xrefs'  => $xrefs,
175        ]);
176
177        $reset_url = route('module', [
178            'module' => $this->name(),
179            'action' => 'Chart',
180            'ged'    => $tree->name(),
181        ]);
182
183        $zoom_in_url = route('module', [
184            'module' => $this->name(),
185            'action' => 'Chart',
186            'ged'    => $tree->name(),
187            'scale'  => min(self::SCALE_MAX, $scale + (int) ($scale * 0.2 + 1)),
188            'xrefs'  => $xrefs,
189        ]);
190
191        $zoom_out_url = route('module', [
192            'module' => $this->name(),
193            'action' => 'Chart',
194            'ged'    => $tree->name(),
195            'scale'  => max(self::SCALE_MIN, $scale - (int) ($scale * 0.2 + 1)),
196            'xrefs'  => $xrefs,
197        ]);
198
199        return $this->viewResponse('modules/timeline-chart/page', [
200            'ajax_url'     => $ajax_url,
201            'individuals'  => $individuals,
202            'module_name'  => $this->name(),
203            'remove_urls'  => $remove_urls,
204            'reset_url'    => $reset_url,
205            'title'        => $this->title(),
206            'scale'        => $scale,
207            'zoom_in_url'  => $zoom_in_url,
208            'zoom_out_url' => $zoom_out_url,
209        ]);
210    }
211
212    /**
213     * @param Tree  $tree
214     * @param array $xrefs
215     * @param int   $scale
216     *
217     * @return ResponseInterface
218     */
219    protected function chart(Tree $tree, array $xrefs, int $scale): ResponseInterface
220    {
221        $xrefs = array_unique($xrefs);
222
223        /** @var Individual[] $individuals */
224        $individuals = array_map(static function (string $xref) use ($tree): ?Individual {
225            return Individual::getInstance($xref, $tree);
226        }, $xrefs);
227
228        $individuals = array_filter($individuals, static function (?Individual $individual): bool {
229            return $individual instanceof Individual && $individual->canShow();
230        });
231
232        $baseyear    = (int) date('Y');
233        $topyear     = 0;
234        $indifacts   = new Collection();
235        $birthyears  = [];
236        $birthmonths = [];
237        $birthdays   = [];
238
239        foreach ($individuals as $individual) {
240            $bdate = $individual->getBirthDate();
241            if ($bdate->isOK()) {
242                $date = new GregorianDate($bdate->minimumJulianDay());
243
244                $birthyears [$individual->xref()] = $date->year;
245                $birthmonths[$individual->xref()] = max(1, $date->month);
246                $birthdays  [$individual->xref()] = max(1, $date->day);
247            }
248            // find all the fact information
249            $facts = $individual->facts();
250            foreach ($individual->spouseFamilies() as $family) {
251                foreach ($family->facts() as $fact) {
252                    $facts->push($fact);
253                }
254            }
255            foreach ($facts as $event) {
256                // get the fact type
257                $fact = $event->getTag();
258                if (!in_array($fact, self::NON_FACTS, true)) {
259                    // check for a date
260                    $date = $event->date();
261                    if ($date->isOK()) {
262                        $date     = new GregorianDate($date->minimumJulianDay());
263                        $baseyear = min($baseyear, $date->year);
264                        $topyear  = max($topyear, $date->year);
265
266                        if (!$individual->isDead()) {
267                            $topyear = max($topyear, (int) date('Y'));
268                        }
269
270                        $indifacts->push($event);
271                    }
272                }
273            }
274        }
275
276        // do not add the same fact twice (prevents marriages from being added multiple times)
277        $indifacts = $indifacts->unique();
278
279        if ($scale === 0) {
280            $scale = (int) (($topyear - $baseyear) / 20 * $indifacts->count() / 4);
281            if ($scale < 6) {
282                $scale = 6;
283            }
284        }
285        if ($scale < 2) {
286            $scale = 2;
287        }
288        $baseyear -= 5;
289        $topyear  += 5;
290
291        $indifacts = Fact::sortFacts($indifacts);
292
293        $html = view('modules/timeline-chart/chart', [
294            'baseyear'    => $baseyear,
295            'bheight'     => self::BHEIGHT,
296            'birthdays'   => $birthdays,
297            'birthmonths' => $birthmonths,
298            'birthyears'  => $birthyears,
299            'indifacts'   => $indifacts,
300            'individuals' => $individuals,
301            'placements'  => [],
302            'scale'       => $scale,
303            'topyear'     => $topyear,
304        ]);
305
306        return response($html);
307    }
308}
309