xref: /webtrees/app/Module/HourglassChartModule.php (revision 982e6c5587f167a514f0634a1e3d44fc2835f003)
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\Family;
26use Fisharebest\Webtrees\I18N;
27use Fisharebest\Webtrees\Individual;
28use Fisharebest\Webtrees\Menu;
29use Fisharebest\Webtrees\Tree;
30use Illuminate\Support\Collection;
31use InvalidArgumentException;
32use Psr\Http\Message\ResponseInterface;
33use Psr\Http\Message\ServerRequestInterface;
34use Psr\Http\Server\RequestHandlerInterface;
35
36use function assert;
37use function response;
38use function view;
39
40/**
41 * Class HourglassChartModule
42 */
43class HourglassChartModule extends AbstractModule implements ModuleChartInterface, RequestHandlerInterface
44{
45    use ModuleChartTrait;
46
47    private const ROUTE_NAME = 'hourglass-chart';
48    private const ROUTE_URL  = '/tree/{tree}/hourglass-{generations}-{spouses}/{xref}';
49
50    // Defaults
51    private const   DEFAULT_GENERATIONS = '3';
52    private const   DEFAULT_SPOUSES     = false;
53    protected const DEFAULT_PARAMETERS  = [
54        'generations' => self::DEFAULT_GENERATIONS,
55        'spouses'     => self::DEFAULT_SPOUSES,
56    ];
57
58    // Limits
59    protected const MINIMUM_GENERATIONS = 2;
60    protected const MAXIMUM_GENERATIONS = 10;
61
62    /**
63     * Initialization.
64     *
65     * @param RouterContainer $router_container
66     */
67    public function boot(RouterContainer $router_container): void
68    {
69        $router_container->getMap()
70            ->get(self::ROUTE_NAME, self::ROUTE_URL, self::class)
71            ->allows(RequestMethodInterface::METHOD_POST)
72            ->tokens([
73                'generations' => '\d+',
74                'spouses'     => '1?',
75            ]);
76    }
77
78    /**
79     * How should this module be identified in the control panel, etc.?
80     *
81     * @return string
82     */
83    public function title(): string
84    {
85        /* I18N: Name of a module/chart */
86        return I18N::translate('Hourglass chart');
87    }
88
89    /**
90     * A sentence describing what this module does.
91     *
92     * @return string
93     */
94    public function description(): string
95    {
96        /* I18N: Description of the “HourglassChart” module */
97        return I18N::translate('An hourglass chart of an individual’s ancestors and descendants.');
98    }
99
100    /**
101     * CSS class for the URL.
102     *
103     * @return string
104     */
105    public function chartMenuClass(): string
106    {
107        return 'menu-chart-hourglass';
108    }
109
110    /**
111     * Return a menu item for this chart - for use in individual boxes.
112     *
113     * @param Individual $individual
114     *
115     * @return Menu|null
116     */
117    public function chartBoxMenu(Individual $individual): ?Menu
118    {
119        return $this->chartMenu($individual);
120    }
121
122    /**
123     * The title for a specific instance of this chart.
124     *
125     * @param Individual $individual
126     *
127     * @return string
128     */
129    public function chartTitle(Individual $individual): string
130    {
131        /* I18N: %s is an individual’s name */
132        return I18N::translate('Hourglass chart of %s', $individual->fullName());
133    }
134
135    /**
136     * The URL for a page showing chart options.
137     *
138     * @param Individual $individual
139     * @param mixed[]    $parameters
140     *
141     * @return string
142     */
143    public function chartUrl(Individual $individual, array $parameters = []): string
144    {
145        return route(self::ROUTE_NAME, [
146                'xref' => $individual->xref(),
147                'tree' => $individual->tree()->name(),
148            ] + $parameters + self::DEFAULT_PARAMETERS);
149    }
150
151    /**
152     * @param ServerRequestInterface $request
153     *
154     * @return ResponseInterface
155     */
156    public function handle(ServerRequestInterface $request): ResponseInterface
157    {
158        $tree        = $request->getAttribute('tree');
159        $user        = $request->getAttribute('user');
160        $xref        = $request->getAttribute('xref');
161        $generations = (int) $request->getAttribute('generations');
162        $spouses     = (bool) $request->getAttribute('spouses');
163        $ajax        = $request->getQueryParams()['ajax'] ?? '';
164        $individual  = Individual::getInstance($xref, $tree);
165
166        // Convert POST requests into GET requests for pretty URLs.
167        if ($request->getMethod() === RequestMethodInterface::METHOD_POST) {
168            return redirect(route(self::ROUTE_NAME, [
169                'tree'        => $request->getAttribute('tree')->name(),
170                'xref'        => $request->getParsedBody()['xref'],
171                'generations' => $request->getParsedBody()['generations'],
172                'spouses'     => $request->getParsedBody()['spouses'] ?? false,
173            ]));
174        }
175
176        Auth::checkIndividualAccess($individual);
177        Auth::checkComponentAccess($this, 'chart', $tree, $user);
178
179        $generations = min($generations, self::MAXIMUM_GENERATIONS);
180        $generations = max($generations, self::MINIMUM_GENERATIONS);
181
182        if ($ajax === '1') {
183            $this->layout = 'layouts/ajax';
184
185            return $this->viewResponse('modules/hourglass-chart/chart', [
186                'generations' => $generations,
187                'individual'  => $individual,
188                'spouses'     => $spouses,
189            ]);
190        }
191
192        $ajax_url = $this->chartUrl($individual, [
193            'ajax'        => true,
194            'generations' => $generations,
195            'spouses'     => $spouses,
196        ]);
197
198        return $this->viewResponse('modules/hourglass-chart/page', [
199            'ajax_url'            => $ajax_url,
200            'generations'         => $generations,
201            'individual'          => $individual,
202            'maximum_generations' => self::MAXIMUM_GENERATIONS,
203            'minimum_generations' => self::MINIMUM_GENERATIONS,
204            'module'              => $this->name(),
205            'spouses'             => $spouses,
206            'title'               => $this->chartTitle($individual),
207        ]);
208    }
209
210    /**
211     * Generate an extension to the chart
212     *
213     * @param ServerRequestInterface $request
214     *
215     * @return ResponseInterface
216     */
217    public function getAncestorsAction(ServerRequestInterface $request): ResponseInterface
218    {
219        $tree = $request->getAttribute('tree');
220        assert($tree instanceof Tree, new InvalidArgumentException());
221
222        $xref = $request->getQueryParams()['xref'] ?? '';
223
224        $family = Family::getInstance($xref, $tree);
225        Auth::checkFamilyAccess($family);
226
227        return response(view('modules/hourglass-chart/parents', [
228            'family'      => $family,
229            'generations' => 1,
230        ]));
231    }
232
233    /**
234     * Generate an extension to the chart
235     *
236     * @param ServerRequestInterface $request
237     *
238     * @return ResponseInterface
239     */
240    public function getDescendantsAction(ServerRequestInterface $request): ResponseInterface
241    {
242        $tree = $request->getAttribute('tree');
243        assert($tree instanceof Tree, new InvalidArgumentException());
244
245        $xref = $request->getQueryParams()['xref'] ?? '';
246
247        $spouses    = (bool) ($request->getQueryParams()['spouses'] ?? false);
248        $individual = Individual::getInstance($xref, $tree);
249
250        Auth::checkIndividualAccess($individual);
251
252        $children = $individual->spouseFamilies()->map(static function (Family $family): Collection {
253            return $family->children();
254        })->flatten();
255
256        return response(view('modules/hourglass-chart/children', [
257            'children'    => $children,
258            'generations' => 1,
259            'spouses'     => $spouses,
260        ]));
261    }
262}
263